text
stringlengths 8
6.88M
|
|---|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Espen Sand
*/
#include "core/pch.h"
#include "platforms/quix/toolkits/x11/X11FileChooser.h"
#include "platforms/quix/toolkits/x11/X11FileDialog.h"
#include "platforms/unix/base/x11/x11utils.h"
X11ToolkitFileChooser::X11ToolkitFileChooser()
: m_can_destroy(true)
, m_request_destroy(false)
{
}
X11ToolkitFileChooser::~X11ToolkitFileChooser()
{
}
void X11ToolkitFileChooser::InitDialog()
{
}
void X11ToolkitFileChooser::SetDialogType(DialogType type)
{
m_settings.type = type;
}
void X11ToolkitFileChooser::SetCaption(const char* caption)
{
m_settings.caption.SetFromUTF8(caption);
}
void X11ToolkitFileChooser::SetInitialPath(const char* path)
{
m_settings.path.SetFromUTF8(path);
// Do not strip path here. If caller wants us to use spaces we should
}
void X11ToolkitFileChooser::AddFilter(int id, const char* media_type)
{
X11FileChooserSettings::FilterData* f=0;
if (!m_settings.filter.Contains(id))
{
f = OP_NEW(X11FileChooserSettings::FilterData,());
if (!f)
return;
if( OpStatus::IsError(m_settings.filter.Add(id, f)))
{
OP_DELETE(f);
return;
}
}
else
{
RETURN_VOID_IF_ERROR(m_settings.filter.GetData(id, &f));
}
f->id = id;
f->media.SetFromUTF8(media_type);
// Remove filter information from media type
int pos = f->media.Find(UNI_L("("));
if (pos != KNotFound)
{
f->media.Delete(pos);
f->media.Strip();
}
}
void X11ToolkitFileChooser::AddExtension(int id, const char* extension)
{
X11FileChooserSettings::FilterData* f=0;
if (!m_settings.filter.Contains(id))
{
f = OP_NEW(X11FileChooserSettings::FilterData,());
if (!f || OpStatus::IsError(m_settings.filter.Add(id, f)))
{
OP_DELETE(f);
return;
}
}
else
{
RETURN_VOID_IF_ERROR(m_settings.filter.GetData(id, &f));
}
f->id = id;
OpString ext;
RETURN_VOID_IF_ERROR(ext.SetFromUTF8(extension));
if (f->extension.HasContent())
RETURN_VOID_IF_ERROR(f->extension.Append(" "));
f->extension.Append(ext);
}
void X11ToolkitFileChooser::SetDefaultFilter(int id)
{
m_settings.activefilter = id;
}
void X11ToolkitFileChooser::SetFixedExtensions(bool fixed)
{
m_settings.fixed = fixed;
}
void X11ToolkitFileChooser::ShowHiddenFiles(bool show_hidden)
{
m_settings.show_hidden = show_hidden;
}
void X11ToolkitFileChooser::OpenDialog(X11Types::Window parent, ToolkitFileChooserListener* result_listener)
{
if (!m_settings.dialog)
{
m_settings.dialog = OP_NEW(X11FileDialog,(m_settings));
if (!m_settings.dialog || OpStatus::IsError(m_settings.dialog->Init(X11Utils::GetDesktopWindowFromX11Window(parent), 0, TRUE)))
{
OP_DELETE(m_settings.dialog);
m_settings.dialog = 0;
}
else
{
// Dialog will self destruct in this case
if (result_listener)
{
m_can_destroy = false;
result_listener->OnChoosingDone(this);
m_can_destroy = true;
if (m_request_destroy)
{
delete this;
return;
}
}
m_settings.Reset();
}
}
}
void X11ToolkitFileChooser::Cancel()
{
if (m_settings.dialog)
m_settings.dialog->CloseDialog(TRUE, TRUE, TRUE);
}
void X11ToolkitFileChooser::Destroy()
{
if (!m_can_destroy)
{
m_request_destroy = true;
return;
}
delete this;
}
int X11ToolkitFileChooser::GetFileCount()
{
return m_settings.selected_files.GetCount();
}
const char* X11ToolkitFileChooser::GetFileName(int index)
{
return m_settings.selected_files.Get(index)->CStr();
}
const char* X11ToolkitFileChooser::GetActiveDirectory()
{
return m_settings.selected_path.CStr();
}
int X11ToolkitFileChooser::GetSelectedFilter()
{
return m_settings.activefilter;
}
|
#include "vector2.h"
//size constructor
vector2::vector2(int s) : sz{ s }, elem{ new double[s] } {
for (int i = 0; i < s; ++i)
elem[i] = 0;
}
//init
vector2::vector2(std::initializer_list<double> lst) : sz(lst.size()), elem{ new double[sz] } {
std::copy(lst.begin(), lst.end(), elem);
}
//copy copyconstructor
vector2::vector2(const vector2& arg) : sz{ arg.sz }, elem{ new double[arg.sz] } {
std::copy(arg.elem, arg.elem + arg.sz, elem);
}
//move construtor
vector2::vector2(vector2&& a) : sz{ a.sz }, elem{ a.elem } {
a.sz = 0;
a.elem = nullptr;
}
//distructor
vector2::~vector2() { delete[] elem; }
//overloaded operators
double vector2::operator[](int n) const { return elem[n]; }
double& vector2::operator[](int n) { return elem[n]; }
vector2& vector2::operator=(const vector2& a) {
double* p = new double[a.sz];
std::copy(a.elem, a.elem + a.sz, p);
delete[] elem;
elem = p;
sz = a.sz;
return *this;
}
//move operator=
vector2& vector2::operator=(vector2&& a) {
delete[] elem;
elem = a.elem;
sz = a.sz;
a.elem = nullptr;
a.sz = 0;
return *this;
}
//other
int vector2::size() { return sz; }
double vector2::get(int n) const { return elem[n]; }
void vector2::set(int n, double v) { elem[n] = v; }
|
#pragma once
#include "types.h"
namespace hdd::gamma
{
class IOVector
{
public:
IOVector(uint32_t in, uint32_t out);
uint32_t Inputs() const;
uint32_t Outputs() const;
valarray_fp& operator[](const uint32_t index);
void Resize(uint32_t in, uint32_t out);
const valarray_fp& InputVector() const;
double InputValue(uint32_t index) const;
double& InputValue(uint32_t index);
const valarray_fp& OutputVector() const;
valarray_fp& OutputVector();
double OutputValue(uint32_t index) const;
friend std::ostream& operator<<(std::ostream& os, const IOVector& iov);
private:
valarray_fp input_;
valarray_fp output_;
};
}
|
//
// Asignatura.cpp
// PrimerParcialEjercicio2
//
// Created by Daniel on 08/09/14.
// Copyright (c) 2014 Gotomo. All rights reserved.
//
#include "Asignatura.h"
Asignatura::Asignatura(){
srand((int)time(NULL));
codigo = rand() % 1000;
numAlum = rand() % 100;
unidades = rand() % 6;
montoT = numAlum * unidades * 1500;
}
void Asignatura::imprimir(){
std::cout<<"-----Asignatura: "<<codigo<<" -----"<<std::endl;
std::cout<<"Numero de alumnos: "<<numAlum<<std::endl;
if(montoT <= montoMin){
int falt = montoMin - montoT;
falt = falt/numAlum;
std::cout<<"Cada alumno debe pagar un exceso de: "<<falt<<" MXN, para que se abra la asignatura"<<std::endl;
}
}
|
#include "Sales.h"
using namespace SALES;
int main()
{
double arr[4]{ 45.3,23.0,30,20 };
Sales s1(arr, 4);
Sales s2;
s1.showSales();
s2.setSales();
s2.showSales();
}
|
#ifndef KING_CPP_INCLUDED
#define KING_CPP_INCLUDED
#include <iostream>
#include "BasePiece.h"
#include "King.h"
#include "Board.h"
extern Board board; //board is declared in the main and extern lets compiler know this
/**@summary Constructor
* @color Color of the new piece
* @pos Position of the new piece
*/
King::King(Color color, Position pos)
{
this->type = "K";
this->color = color;
this->position = pos;
}
/**@summary Default Destructor
*/
King::~King()
{ }
/**@summary Validates a move by the piece logic of moving
* @param moteToPos - Starting position of the piece
* @return bool - Success or Failure
*/
bool King::validateMove(Position moveToPos, BasePiece* &piece)
{
bool validMove = false;
//check if it's possible to move the king to this square
if((board.getPiece(moveToPos) == nullptr) ||
(board.getPiece(moveToPos) != nullptr && (board.getPiece(moveToPos)->getColor() != this->color)))
{
validMove = true;
}
else
{
validMove = false;
return validMove;
}
//(x-1,y+1), (x,y+1), (x+1,y+1),
if(moveToPos.ypos == (position.ypos + 1) && moveToPos.xpos == (position.xpos - 1))
{
validMove = true;
}
else if(moveToPos.ypos == (position.ypos + 1) && moveToPos.xpos == position.xpos)
{
validMove = true;
}
else if(moveToPos.ypos == (position.ypos + 1) && moveToPos.xpos == (position.xpos + 1))
{
validMove = true;
}
//(x-1,y), (x+1,y),
else if(moveToPos.ypos == position.ypos && moveToPos.xpos == (position.xpos - 1))
{
validMove = true;
}
else if(moveToPos.ypos == position.ypos && moveToPos.xpos == (position.xpos + 1))
{
validMove = true;
}
//(x-1,y-1), (x,y-1), (x+1,y-1),
else if(moveToPos.ypos == (position.ypos - 1) && moveToPos.xpos == (position.xpos - 1))
{
validMove = true;
}
else if(moveToPos.ypos == (position.ypos - 1) && moveToPos.xpos == position.xpos)
{
validMove = true;
}
else if(moveToPos.ypos == (position.ypos - 1) && moveToPos.xpos == (position.xpos + 1))
{
validMove = true;
}
else
{
validMove = false;
}
if(validMove && (board.getPiece(moveToPos) != nullptr) && (board.getPiece(moveToPos)->getType() == "K"))
{
std::cout << ((this->color == White) ? "White's " : "Black's ") << "king is checked!";
}
return validMove;
}
#endif // KING_CPP_INCLUDED
|
#ifndef __HELP_H__
#define __HELP_H__
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <dax/Types.h>
#include <dax/exec/WorkletMapField.h>
class PointLocator;
namespace help
{
void printStartCount(const std::vector<dax::Id>& pointStarts,
const std::vector<int>& pointCounts,
std::iostream& stream);
void printBinPoint(float x, float y, float z,
const PointLocator& locator,
std::iostream& stream);
void printCompare(const std::string& output, const std::string& filename);
void printCoinPoints(const std::vector<dax::Vector3>& testPoints,
const std::vector<dax::Id>& testBucketIds,
const std::vector<int>& testCounts,
const std::vector<dax::Vector3>& testCoinPoints,
std::iostream& stream);
struct FindPointsWorklet : dax::exec::WorkletMapField
{
// signatures
typedef void ControlSignature(Field(In), ExecObject(),
Field(Out), Field(Out), Field(Out));
// bucketId, point count, coincident point
typedef void ExecutionSignature(_1, _2, _3, _4, _5);
// overload operator()
template<typename Functor>
DAX_EXEC_EXPORT
void operator()(const dax::Vector3& point,
const Functor& execLocator,
dax::Id& bucketId,
int& pointCount,
dax::Vector3& coinPoint) const
{
bucketId = execLocator.getBucketId(point);
pointCount = execLocator.getBucketPointCount(bucketId);
dax::Id coinId = execLocator.findPoint(point);
if (coinId < 0)
coinPoint = dax::make_Vector3(-1.0, -1.0, -1.0);
else
coinPoint = execLocator.getPoint(coinId);
}
};
}
#endif //__HELP_H__
|
#include "mapinfo.h"
#include "ShareMemory.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <stdarg.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <pthread.h>
#include "soapH.h"
#include "httppost.h"
#include "json.h"
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
using namespace rapidjson;
#define BACKLOG (100)
#define MAX_THR (10)
#define MAX_QUEUE (1000)
#define HTTP_PORT 10000
#define JSON_FINDPOS_TEXT "\"Msisdn\":\"%s\",\"Latitude\":\"%f\",\"Longitude\":\"%f\",\"CurrTime\":\"%ld\""
SOAP_SOCKET queue[MAX_QUEUE];
//全局函数
CMapInfo g_objMapInfo;
void Gdaemon()
{
pid_t pid;
signal(SIGTTOU,SIG_IGN);
signal(SIGTTIN,SIG_IGN);
signal(SIGTSTP,SIG_IGN);
if(setpgrp() == -1)
{
perror("setpgrp failure");
}
signal(SIGHUP,SIG_IGN);
if((pid = fork()) < 0)
{
perror("fork failure");
exit(1);
}
else if(pid > 0)
{
exit(0);
}
setsid();
umask(0);
signal(SIGCLD,SIG_IGN);
signal(SIGCHLD,SIG_IGN);
signal(SIGPIPE,SIG_IGN);
}
//写独占文件锁
int AcquireWriteLock(int fd, int start, int len)
{
struct flock arg;
arg.l_type = F_WRLCK; // 加写锁
arg.l_whence = SEEK_SET;
arg.l_start = start;
arg.l_len = len;
arg.l_pid = getpid();
return fcntl(fd, F_SETLKW, &arg);
}
//释放独占文件锁
int ReleaseLock(int fd, int start, int len)
{
struct flock arg;
arg.l_type = F_UNLCK; // 解锁
arg.l_whence = SEEK_SET;
arg.l_start = start;
arg.l_len = len;
arg.l_pid = getpid();
return fcntl(fd, F_SETLKW, &arg);
}
//查看写锁
int SeeLock(int fd, int start, int len)
{
struct flock arg;
arg.l_type = F_WRLCK;
arg.l_whence = SEEK_SET;
arg.l_start = start;
arg.l_len = len;
arg.l_pid = getpid();
if (fcntl(fd, F_GETLK, &arg) != 0) // 获取锁
{
return -1; // 测试失败
}
if (arg.l_type == F_UNLCK)
{
return 0; // 无锁
}
else if (arg.l_type == F_RDLCK)
{
return 1; // 读锁
}
else if (arg.l_type == F_WRLCK)
{
return 2; // 写所
}
return 0;
}
int head = 0;
int tail = 0;
pthread_mutex_t queue_cs;
pthread_cond_t queue_cv;
static SOAP_SOCKET dequeue();
static int enqueue(SOAP_SOCKET sock);
static void *process_queue(void *soap);
int text_post_handler(struct soap *soap);
int sendPost(char *url,char *cont);
SOAP_NMAC struct Namespace namespaces[] =
{
{"SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/", "http://www.w3.org/*/soap-envelope", NULL},
{"SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/", "http://www.w3.org/*/soap-encoding", NULL},
{"xsi", "http://www.w3.org/2001/XMLSchema-instance", "http://www.w3.org/*/XMLSchema-instance", NULL},
{"xsd", "http://www.w3.org/2001/XMLSchema", "http://www.w3.org/*/XMLSchema", NULL},
{NULL, NULL, NULL, NULL}
};
int __ns1__add(struct soap *soap, struct ns2__pair *in, double *out)
{ *out = in->a + in->b;
return SOAP_OK;
}
int __ns1__sub(struct soap *soap, struct ns2__pair *in, double *out)
{ *out = in->a - in->b;
return SOAP_OK;
}
int __ns1__mul(struct soap *soap, struct ns2__pair *in, double *out)
{ *out = in->a * in->b;
return SOAP_OK;
}
int __ns1__div(struct soap *soap, struct ns2__pair *in, double *out)
{ *out = in->a / in->b;
return SOAP_OK;
}
int __ns1__pow(struct soap *soap, struct ns2__pair *in, double *out)
{ *out = pow(in->a, in->b);
return SOAP_OK;
}
static int enqueue(SOAP_SOCKET sock)
{
int status = SOAP_OK;
int next;
pthread_mutex_lock(&queue_cs);
next = tail + 1;
if (next >= MAX_QUEUE)
next = 0;
if (next == head)
status = SOAP_EOM;
else
{
queue[tail] = sock;
tail = next;
}
pthread_cond_signal(&queue_cv);
pthread_mutex_unlock(&queue_cs);
return status;
}
static SOAP_SOCKET dequeue()
{
SOAP_SOCKET sock;
pthread_mutex_lock(&queue_cs);
while (head == tail)
pthread_cond_wait(&queue_cv, &queue_cs);
sock = queue[head++];
if (head >= MAX_QUEUE)
head = 0;
pthread_mutex_unlock(&queue_cs);
return sock;
}
static void *process_queue(void *soap)
{
struct soap *tsoap = (struct soap*) soap;
for (;;)
{
tsoap->socket = dequeue();
if (!soap_valid_socket(tsoap->socket))
break;
soap_serve(tsoap);
soap_destroy(tsoap);
soap_end(tsoap);
}
return NULL;
}
int text_post_handler(struct soap *soap)
{
//处理Json字符串
Document document;
char *buf;
char retBuf[2048] = {'\0'};
memset(retBuf,0,sizeof(retBuf));
size_t len;
soap_http_body(soap, &buf, &len);
printf("[text_post_handler]buf=%s.\n", buf);
printf("[text_post_handler]path=%s.\n", soap->path);
//解析Json, 获得查询相关参数
if(false == document.Parse(buf).HasParseError())
{
double dLatitude = 0.0f;
double dLongitude = 0.0f;
double dRadius = 0.0f;
if(strcmp(soap->path, "/GeoHash/Search/") == 0)
{
//解析GeoHash查询功能参数
if(document.HasMember("Latitude") == true)
{
dLatitude = atof(document["Latitude"].GetString());
}
if(document.HasMember("Longitude") == true)
{
dLongitude = atof(document["Longitude"].GetString());
}
if(document.HasMember("Radius") == true)
{
dRadius = atof(document["Radius"].GetString());
}
if(dLatitude != 0.0f && dLongitude != 0.0f && dRadius != 0.0f)
{
//这里添加geo调用算法
vector<_Pos_Info*> vecPosList;
bool blState = g_objMapInfo.FindPos(dLatitude, dLongitude, dRadius, vecPosList);
if(true == blState)
{
//将结果拼装成Json
char szTemp[500] = {'\0'};
retBuf[0] = '{';
int nPos = 1;
for(int i = 0; i < (int)vecPosList.size(); i++)
{
if(i != (int)vecPosList.size() - 1)
{
sprintf(szTemp, JSON_FINDPOS_TEXT, vecPosList[i]->m_szMsisdn,
vecPosList[i]->m_dPosLatitude,
vecPosList[i]->m_dPosLongitude,
vecPosList[i]->m_ttCurrTime);
int nLen = (int)strlen(szTemp);
memcpy(&retBuf[nPos], szTemp, nLen);
nPos += nLen;
retBuf[nPos] = ',';
nPos += 1;
}
else
{
sprintf(szTemp, JSON_FINDPOS_TEXT, vecPosList[i]->m_szMsisdn,
vecPosList[i]->m_dPosLatitude,
vecPosList[i]->m_dPosLongitude,
vecPosList[i]->m_ttCurrTime);
int nLen = (int)strlen(szTemp);
memcpy(&retBuf[nPos], szTemp, nLen);
nPos += nLen;
retBuf[nPos] = '}';
nPos += 1;
}
}
}
else
{
sprintf(retBuf, "{\"error\":\"2\"}");
}
}
else
{
sprintf(retBuf, "{\"error\":\"1\"}");
}
}
else if(strcmp(soap->path, "/GeoHash/Add/") == 0)
{
char szMsisdn[15] = {'\0'};
double dLatitude = 0.0f;
double dLongitude = 0.0f;
time_t ttNow = 0;
//解析添加当前点数据参数
if(document.HasMember("Msisdn") == true)
{
sprintf(szMsisdn, "%s", document["Msisdn"].GetString());
}
if(document.HasMember("Latitude") == true)
{
dLatitude = atof(document["Latitude"].GetString());
}
if(document.HasMember("Longitude") == true)
{
dLongitude = atof(document["Longitude"].GetString());
}
if(document.HasMember("Time") == true)
{
ttNow = (time_t)atol(document["Time"].GetString());
}
if(strlen(szMsisdn) > 0 && dLatitude != 0.0f && dLongitude != 0.0f && ttNow != 0)
{
bool blState = g_objMapInfo.AddPos(szMsisdn, dLatitude, dLongitude, ttNow);
if(true == blState)
{
sprintf(retBuf, "{\"success\":\"0\"}");
}
else
{
sprintf(retBuf, "{\"error\":\"2\"}");
}
}
else
{
sprintf(retBuf, "{\"error\":\"1\"}");
}
}
}
printf("[text_post_handler]retBuf=%s.\n", retBuf);
len = strlen(retBuf);
soap_response(soap, SOAP_HTML);
soap_send_raw(soap, retBuf, len);
soap_end_send(soap);
return SOAP_OK;
}
int Chlid_Run()
{
//Http子进程
size_t stShareSize = g_objMapInfo.GetSize(1000000);
printf("[main]All Size=%d.\n", stShareSize);
int nPoolSize = 600000;
shm_key obj_key = 30010;
shm_id obj_shm_id;
bool blCreate = true;
char* pData = Open_Share_Memory_API(obj_key, stShareSize, obj_shm_id, blCreate);
//char* pData = new char[stShareSize];
if(NULL != pData)
{
if(blCreate == true)
{
memset(pData, 0, stShareSize);
g_objMapInfo.Init(pData);
}
else
{
g_objMapInfo.Load(pData);
}
}
else
{
printf("[main]Create share memory is fail.\n");
return 0;
}
int ret = 0;
char *buf;
size_t len;
struct soap soap;
soap_init(&soap);
soap_set_omode(&soap, SOAP_C_UTFSTRING);
struct http_post_handlers handlers[] =
{
{ "text/*", text_post_handler },
{ "text/*;*", text_post_handler },
{ "POST", text_post_handler },
{ NULL }
};
soap_register_plugin_arg(&soap, http_post, handlers);
struct soap *soap_thr[MAX_THR];
pthread_t tid[MAX_THR];
SOAP_SOCKET m, s;
int i;
m = soap_bind(&soap, NULL, HTTP_PORT, BACKLOG);
if (!soap_valid_socket(m))
{
printf("soap_valid_socket\n");
return 1;
}
pthread_mutex_init(&queue_cs, NULL);
pthread_cond_init(&queue_cv, NULL);
for (i = 0; i < MAX_THR; i++)
{
soap_thr[i] = soap_copy(&soap);
soap_set_mode(soap_thr[i], SOAP_C_UTFSTRING);
pthread_create(&tid[i], NULL, (void*(*)(void*)) process_queue,(void*) soap_thr[i]);
}
for (;;)
{
s = soap_accept(&soap);
if (!soap_valid_socket(s))
{
if (soap.errnum)
{
soap_print_fault(&soap, stderr);
continue;
}
else
{
break;
}
}
while (enqueue(s) == SOAP_EOM)
{
sleep(1);
}
}
for (i = 0; i < MAX_THR; i++)
{
while (enqueue(SOAP_INVALID_SOCKET) == SOAP_EOM)
{
sleep(1);
}
}
for (i = 0; i < MAX_THR; i++)
{
pthread_join(tid[i], NULL);
soap_done(soap_thr[i]);
free(soap_thr[i]);
}
pthread_mutex_destroy(&queue_cs);
pthread_cond_destroy(&queue_cv);
soap_done(&soap);
//delete[] pData;
return 0;
}
int main()
{
//当前监控子线程个数
int nNumChlid = 1;
//检测时间间隔参数
struct timespec tsRqt;
//文件锁
int fd_lock = 0;
int nRet = 0;
//主进程检测时间间隔(设置每隔5秒一次)
tsRqt.tv_sec = 5;
tsRqt.tv_nsec = 0;
//获得当前路径
char szWorkDir[255] = {0};
if(!getcwd(szWorkDir, 260))
{
exit(1);
}
printf("[Main]szWorkDir=%s.\n", szWorkDir);
// 打开(创建)锁文件
char szFileName[200] = {'\0'};
memset(szFileName, 0, sizeof(flock));
sprintf(szFileName, "%s/testwatch.lk", szWorkDir);
fd_lock = open(szFileName, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
if (fd_lock < 0)
{
printf("open the flock and exit, errno = %d.", errno);
exit(1);
}
//查看当前文件锁是否已锁
nRet = SeeLock(fd_lock, 0, sizeof(int));
if (nRet == -1 || nRet == 2)
{
printf("file is already exist!");
exit(1);
}
//如果文件锁没锁,则锁住当前文件锁
if (AcquireWriteLock(fd_lock, 0, sizeof(int)) != 0)
{
printf("lock the file failure and exit, idx = 0!.");
exit(1);
}
//写入子进程锁信息
lseek(fd_lock, 0, SEEK_SET);
for (int nIndex = 0; nIndex <= nNumChlid; nIndex++)
{
write(fd_lock, &nIndex, sizeof(nIndex));
}
Gdaemon();
while (1)
{
for (int nChlidIndex = 1; nChlidIndex <= nNumChlid; nChlidIndex++)
{
//测试每个子进程的锁是否还存在
nRet = SeeLock(fd_lock, nChlidIndex * sizeof(int), sizeof(int));
if (nRet == -1 || nRet == 2)
{
continue;
}
//如果文件锁没有被锁,则设置文件锁,并启动子进程
int npid = fork();
if (npid == 0)
{
//上文件锁
if(AcquireWriteLock(fd_lock, nChlidIndex * sizeof(int), sizeof(int)) != 0)
{
printf("child %d AcquireWriteLock failure.\n", nChlidIndex);
exit(1);
}
//启动子进程
Chlid_Run();
//子进程在执行完任务后必须退出循环和释放锁
ReleaseLock(fd_lock, nChlidIndex * sizeof(int), sizeof(int));
}
}
printf("child count(%d) is ok.\n", nNumChlid);
//检查间隔
nanosleep(&tsRqt, NULL);
}
return 0;
}
|
#include <iostream>
using namespace std;
#include "05_02_DynamicArrayClass.cpp"
int main()
{
DynamicArray d1; /// default constructor
d1.add(10);
d1.add(20);
d1.add(30);
d1.add(40);
d1.add(50);
cout << d1.getCapacity() << endl;
d1.add(60);
d1.print();
cout << d1.getCapacity() << endl;
DynamicArray d2(d1); //Copy Constructor inbuilt called &
// it also creates shallow copy
DynamicArray d3;
d3 = d1; // it also creates shallow copy
d1.add(100, 0);
d1.print();
cout << endl;
d2.print();
cout << endl;
d3.print();
cout << endl;
DynamicArray d4(100);
cout << d4.getCapacity();
return 0;
}
|
// cl -W3 -DUNICODE -D_UNICODE -D_WIN32_WINNT=0x500 libcvm.cpp cvm_test.cpp /link user32.lib
#include <tchar.h>
#include "libcvm.h"
#if !defined(NEVER_DEFINED)
#define DEBUG_CODE /##/
#else
#include <stdio.h>
#define DEBUG_CODE
#endif
namespace {
static const WORD LOOKUP_TABLE[] =
{
// 0x00-0xFF
/*00-0F*/ 0x401B, 0x4021, 0x4025, 0x402B, 0x4031, 0x403F, 0x4043, 0x4045, 0x405D, 0x4061, 0x4067, 0x406D, 0x4087, 0x4091, 0x40A3, 0x40A9,
/*10-1F*/ 0x40B1, 0x40B7, 0x40BD, 0x40DB, 0x40DF, 0x40EB, 0x40F7, 0x40F9, 0x4109, 0x410B, 0x4111, 0x4115, 0x4121, 0x4133, 0x4135, 0x413B,
/*20-2F*/ 0x413F, 0x4159, 0x4165, 0x416B, 0x4177, 0x417B, 0x4193, 0x41AB, 0x41B7, 0x41BD, 0x41BF, 0x41CB, 0x41E7, 0x41EF, 0x41F3, 0x41F9,
/*30-3F*/ 0x4205, 0x4207, 0x4219, 0x421F, 0x4223, 0x4229, 0x422F, 0x4243, 0x4253, 0x4255, 0x425B, 0x4261, 0x4273, 0x427D, 0x4283, 0x4285,
/*40-4F*/ 0x4289, 0x4291, 0x4297, 0x429D, 0x42B5, 0x42C5, 0x42CB, 0x42D3, 0x42DD, 0x42E3, 0x42F1, 0x4307, 0x430F, 0x431F, 0x4325, 0x4327,
/*50-5F*/ 0x4333, 0x4337, 0x4339, 0x434F, 0x4357, 0x4369, 0x438B, 0x438D, 0x4393, 0x43A5, 0x43A9, 0x43AF, 0x43B5, 0x43BD, 0x43C7, 0x43CF,
/*60-6F*/ 0x43E1, 0x43E7, 0x43EB, 0x43ED, 0x43F1, 0x43F9, 0x4409, 0x440B, 0x4417, 0x4423, 0x4429, 0x443B, 0x443F, 0x4445, 0x444B, 0x4451,
/*70-7F*/ 0x4453, 0x4459, 0x4465, 0x446F, 0x4483, 0x448F, 0x44A1, 0x44A5, 0x44AB, 0x44AD, 0x44BD, 0x44BF, 0x44C9, 0x44D7, 0x44DB, 0x44F9,
/*80-8F*/ 0x44FB, 0x4505, 0x4511, 0x4513, 0x452B, 0x4531, 0x4541, 0x4549, 0x4553, 0x4555, 0x4561, 0x4577, 0x457D, 0x457F, 0x458F, 0x45A3,
/*90-9F*/ 0x45AD, 0x45AF, 0x45BB, 0x45C7, 0x45D9, 0x45E3, 0x45EF, 0x45F5, 0x45F7, 0x4601, 0x4603, 0x4609, 0x4613, 0x4625, 0x4627, 0x4633,
/*A0-AF*/ 0x4639, 0x463D, 0x4643, 0x4645, 0x465D, 0x4679, 0x467B, 0x467F, 0x4681, 0x468B, 0x468D, 0x469D, 0x46A9, 0x46B1, 0x46C7, 0x46C9,
/*B0-BF*/ 0x46CF, 0x46D3, 0x46D5, 0x46DF, 0x46E5, 0x46F9, 0x4705, 0x470F, 0x4717, 0x4723, 0x4729, 0x472F, 0x4735, 0x4739, 0x474B, 0x474D,
/*C0-CF*/ 0x4751, 0x475D, 0x476F, 0x4771, 0x477D, 0x4783, 0x4787, 0x4789, 0x4799, 0x47A5, 0x47B1, 0x47BF, 0x47C3, 0x47CB, 0x47DD, 0x47E1,
/*D0-DF*/ 0x47ED, 0x47FB, 0x4801, 0x4807, 0x480B, 0x4813, 0x4819, 0x481D, 0x4831, 0x483D, 0x4847, 0x4855, 0x4859, 0x485B, 0x486B, 0x486D,
/*E0-EF*/ 0x4879, 0x4897, 0x489B, 0x48A1, 0x48B9, 0x48CD, 0x48E5, 0x48EF, 0x48F7, 0x4903, 0x490D, 0x4919, 0x491F, 0x492B, 0x4937, 0x493D,
/*F0-FF*/ 0x4945, 0x4955, 0x4963, 0x4969, 0x496D, 0x4973, 0x4997, 0x49AB, 0x49B5, 0x49D3, 0x49DF, 0x49E1, 0x49E5, 0x49E7, 0x4A03, 0x4A0F,
// 0x100-0x1FF
/*00-0F*/ 0x4A1D, 0x4A23, 0x4A39, 0x4A41, 0x4A45, 0x4A57, 0x4A5D, 0x4A6B, 0x4A7D, 0x4A81, 0x4A87, 0x4A89, 0x4A8F, 0x4AB1, 0x4AC3, 0x4AC5,
/*10-1F*/ 0x4AD5, 0x4ADB, 0x4AED, 0x4AEF, 0x4B07, 0x4B0B, 0x4B0D, 0x4B13, 0x4B1F, 0x4B25, 0x4B31, 0x4B3B, 0x4B43, 0x4B49, 0x4B59, 0x4B65,
/*20-2F*/ 0x4B6D, 0x4B77, 0x4B85, 0x4BAD, 0x4BB3, 0x4BB5, 0x4BBB, 0x4BBF, 0x4BCB, 0x4BD9, 0x4BDD, 0x4BDF, 0x4BE3, 0x4BE5, 0x4BE9, 0x4BF1,
/*30-3F*/ 0x4BF7, 0x4C01, 0x4C07, 0x4C0D, 0x4C0F, 0x4C15, 0x4C1B, 0x4C21, 0x4C2D, 0x4C33, 0x4C4B, 0x4C55, 0x4C57, 0x4C61, 0x4C67, 0x4C73,
/*40-4F*/ 0x4C79, 0x4C7F, 0x4C8D, 0x4C93, 0x4C99, 0x4CCD, 0x4CE1, 0x4CE7, 0x4CF1, 0x4CF3, 0x4CFD, 0x4D05, 0x4D0F, 0x4D1B, 0x4D27, 0x4D29,
/*50-5F*/ 0x4D2F, 0x4D33, 0x4D41, 0x4D51, 0x4D59, 0x4D65, 0x4D6B, 0x4D81, 0x4D83, 0x4D8D, 0x4D95, 0x4D9B, 0x4DB1, 0x4DB3, 0x4DC9, 0x4DCF,
/*60-6F*/ 0x4DD7, 0x4DE1, 0x4DED, 0x4DF9, 0x4DFB, 0x4E05, 0x4E0B, 0x4E17, 0x4E19, 0x4E1D, 0x4E2B, 0x4E35, 0x4E37, 0x4E3D, 0x4E4F, 0x4E53,
/*70-7F*/ 0x4E5F, 0x4E67, 0x4E79, 0x4E85, 0x4E8B, 0x4E91, 0x4E95, 0x4E9B, 0x4EA1, 0x4EAF, 0x4EB3, 0x4EB5, 0x4EC1, 0x4ECD, 0x4ED1, 0x4ED7,
/*80-8F*/ 0x4EE9, 0x4EFB, 0x4F07, 0x4F09, 0x4F19, 0x4F25, 0x4F2D, 0x4F3F, 0x4F49, 0x4F63, 0x4F67, 0x4F6D, 0x4F75, 0x4F7B, 0x4F81, 0x4F85,
/*90-9F*/ 0x4F87, 0x4F91, 0x4FA5, 0x4FA9, 0x4FAF, 0x4FB7, 0x4FBB, 0x4FCF, 0x4FD9, 0x4FDB, 0x4FFD, 0x4FFF, 0x5003, 0x501B, 0x501D, 0x5029,
/*A0-AF*/ 0x5035, 0x503F, 0x5045, 0x5047, 0x5053, 0x5071, 0x5077, 0x5083, 0x5093, 0x509F, 0x50A1, 0x50B7, 0x50C9, 0x50D5, 0x50E3, 0x50ED,
/*B0-BF*/ 0x50EF, 0x50FB, 0x5107, 0x510B, 0x510D, 0x5111, 0x5117, 0x5123, 0x5125, 0x5135, 0x5147, 0x5149, 0x5171, 0x5179, 0x5189, 0x518F,
/*C0-CF*/ 0x5197, 0x51A1, 0x51A3, 0x51A7, 0x51B9, 0x51C1, 0x51CB, 0x51D3, 0x51DF, 0x51E3, 0x51F5, 0x51F7, 0x5209, 0x5213, 0x5215, 0x5219,
/*D0-DF*/ 0x521B, 0x521F, 0x5227, 0x5243, 0x5245, 0x524B, 0x5261, 0x526D, 0x5273, 0x5281, 0x5293, 0x5297, 0x529D, 0x52A5, 0x52AB, 0x52B1,
/*E0-EF*/ 0x52BB, 0x52C3, 0x52C7, 0x52C9, 0x52DB, 0x52E5, 0x52EB, 0x52FF, 0x5315, 0x531D, 0x5323, 0x5341, 0x5345, 0x5347, 0x534B, 0x535D,
/*F0-FF*/ 0x5363, 0x5381, 0x5383, 0x5387, 0x538F, 0x5395, 0x5399, 0x539F, 0x53AB, 0x53B9, 0x53DB, 0x53E9, 0x53EF, 0x53F3, 0x53F5, 0x53FB,
// 0x200-0x2FF
/*00-0F*/ 0x53FF, 0x540D, 0x5411, 0x5413, 0x5419, 0x5435, 0x5437, 0x543B, 0x5441, 0x5449, 0x5453, 0x5455, 0x545F, 0x5461, 0x546B, 0x546D,
/*10-1F*/ 0x5471, 0x548F, 0x5491, 0x549D, 0x54A9, 0x54B3, 0x54C5, 0x54D1, 0x54DF, 0x54E9, 0x54EB, 0x54F7, 0x54FD, 0x5507, 0x550D, 0x551B,
/*20-2F*/ 0x5527, 0x552B, 0x5539, 0x553D, 0x554F, 0x5551, 0x555B, 0x5563, 0x5567, 0x556F, 0x5579, 0x5585, 0x5597, 0x55A9, 0x55B1, 0x55B7,
/*30-3F*/ 0x55C9, 0x55D9, 0x55E7, 0x55ED, 0x55F3, 0x55FD, 0x560B, 0x560F, 0x5615, 0x5617, 0x5623, 0x562F, 0x5633, 0x5639, 0x563F, 0x564B,
/*40-4F*/ 0x564D, 0x565D, 0x565F, 0x566B, 0x5671, 0x5675, 0x5683, 0x5689, 0x568D, 0x568F, 0x569B, 0x56AD, 0x56B1, 0x56D5, 0x56E7, 0x56F3,
/*50-5F*/ 0x56FF, 0x5701, 0x5705, 0x5707, 0x570B, 0x5713, 0x571F, 0x5723, 0x5747, 0x574D, 0x575F, 0x5761, 0x576D, 0x5777, 0x577D, 0x5789,
/*60-6F*/ 0x57A1, 0x57A9, 0x57AF, 0x57B5, 0x57C5, 0x57D1, 0x57D3, 0x57E5, 0x57EF, 0x5803, 0x580D, 0x580F, 0x5815, 0x5827, 0x582B, 0x582D,
/*70-7F*/ 0x5855, 0x585B, 0x585D, 0x586D, 0x586F, 0x5873, 0x587B, 0x588D, 0x5897, 0x58A3, 0x58A9, 0x58AB, 0x58B5, 0x58BD, 0x58C1, 0x58C7,
/*80-8F*/ 0x58D3, 0x58D5, 0x58DF, 0x58F1, 0x58F9, 0x58FF, 0x5903, 0x5917, 0x591B, 0x5921, 0x5945, 0x594B, 0x594D, 0x5957, 0x595D, 0x5975,
/*90-9F*/ 0x597B, 0x5989, 0x5999, 0x599F, 0x59B1, 0x59B3, 0x59BD, 0x59D1, 0x59DB, 0x59E3, 0x59E9, 0x59ED, 0x59F3, 0x59F5, 0x59FF, 0x5A01,
/*A0-AF*/ 0x5A0D, 0x5A11, 0x5A13, 0x5A17, 0x5A1F, 0x5A29, 0x5A2F, 0x5A3B, 0x5A4D, 0x5A5B, 0x5A67, 0x5A77, 0x5A7F, 0x5A85, 0x5A95, 0x5A9D,
/*B0-BF*/ 0x5AA1, 0x5AA3, 0x5AA9, 0x5ABB, 0x5AD3, 0x5AE5, 0x5AEF, 0x5AFB, 0x5AFD, 0x5B01, 0x5B0F, 0x5B19, 0x5B1F, 0x5B25, 0x5B2B, 0x5B3D,
/*C0-CF*/ 0x5B49, 0x5B4B, 0x5B67, 0x5B79, 0x5B87, 0x5B97, 0x5BA3, 0x5BB1, 0x5BC9, 0x5BD5, 0x5BEB, 0x5BF1, 0x5BF3, 0x5BFD, 0x5C05, 0x5C09,
/*D0-DF*/ 0x5C0B, 0x5C0F, 0x5C1D, 0x5C29, 0x5C2F, 0x5C33, 0x5C39, 0x5C47, 0x5C4B, 0x5C4D, 0x5C51, 0x5C6F, 0x5C75, 0x5C77, 0x5C7D, 0x5C87,
/*E0-EF*/ 0x5C89, 0x5CA7, 0x5CBD, 0x5CBF, 0x5CC3, 0x5CC9, 0x5CD1, 0x5CD7, 0x5CDD, 0x5CED, 0x5CF9, 0x5D05, 0x5D0B, 0x5D13, 0x5D17, 0x5D19,
/*F0-FF*/ 0x5D31, 0x5D3D, 0x5D41, 0x5D47, 0x5D4F, 0x5D55, 0x5D5B, 0x5D65, 0x5D67, 0x5D6D, 0x5D79, 0x5D95, 0x5DA3, 0x5DA9, 0x5DAD, 0x5DB9,
// 0x300-0x3FF
/*00-0F*/ 0x5DC1, 0x5DC7, 0x5DD3, 0x5DD7, 0x5DDD, 0x5DEB, 0x5DF1, 0x5DFD, 0x5E07, 0x5E0D, 0x5E13, 0x5E1B, 0x5E21, 0x5E27, 0x5E2B, 0x5E2D,
/*10-1F*/ 0x5E31, 0x5E39, 0x5E45, 0x5E49, 0x5E57, 0x5E69, 0x5E73, 0x5E75, 0x5E85, 0x5E8B, 0x5E9F, 0x5EA5, 0x5EAF, 0x5EB7, 0x5EBB, 0x5ED9,
/*20-2F*/ 0x5EFD, 0x5F09, 0x5F11, 0x5F27, 0x5F33, 0x5F35, 0x5F3B, 0x5F47, 0x5F57, 0x5F5D, 0x5F63, 0x5F65, 0x5F77, 0x5F7B, 0x5F95, 0x5F99,
/*30-3F*/ 0x5FA1, 0x5FB3, 0x5FBD, 0x5FC5, 0x5FCF, 0x5FD5, 0x5FE3, 0x5FE7, 0x5FFB, 0x6011, 0x6023, 0x602F, 0x6037, 0x6053, 0x605F, 0x6065,
/*40-4F*/ 0x606B, 0x6073, 0x6079, 0x6085, 0x609D, 0x60AD, 0x60BB, 0x60BF, 0x60CD, 0x60D9, 0x60DF, 0x60E9, 0x60F5, 0x6109, 0x610F, 0x6113,
/*50-5F*/ 0x611B, 0x612D, 0x6139, 0x614B, 0x6155, 0x6157, 0x615B, 0x616F, 0x6179, 0x6187, 0x618B, 0x6191, 0x6193, 0x619D, 0x61B5, 0x61C7,
/*60-6F*/ 0x61C9, 0x61CD, 0x61E1, 0x61F1, 0x61FF, 0x6209, 0x6217, 0x621D, 0x6221, 0x6227, 0x623B, 0x6241, 0x624B, 0x6251, 0x6253, 0x625F,
/*70-7F*/ 0x6265, 0x6283, 0x628D, 0x6295, 0x629B, 0x629F, 0x62A5, 0x62AD, 0x62D5, 0x62D7, 0x62DB, 0x62DD, 0x62E9, 0x62FB, 0x62FF, 0x6305,
/*80-8F*/ 0x630D, 0x6317, 0x631D, 0x632F, 0x6341, 0x6343, 0x634F, 0x635F, 0x6367, 0x636D, 0x6371, 0x6377, 0x637D, 0x637F, 0x63B3, 0x63C1,
/*90-9F*/ 0x63C5, 0x63D9, 0x63E9, 0x63EB, 0x63EF, 0x63F5, 0x6401, 0x6403, 0x6409, 0x6415, 0x6421, 0x6427, 0x642B, 0x6439, 0x6443, 0x6449,
/*A0-AF*/ 0x644F, 0x645D, 0x6467, 0x6475, 0x6485, 0x648D, 0x6493, 0x649F, 0x64A3, 0x64AB, 0x64C1, 0x64C7, 0x64C9, 0x64DB, 0x64F1, 0x64F7,
/*B0-BF*/ 0x64F9, 0x650B, 0x6511, 0x6521, 0x652F, 0x6539, 0x653F, 0x654B, 0x654D, 0x6553, 0x6557, 0x655F, 0x6571, 0x657D, 0x658D, 0x658F,
/*C0-CF*/ 0x6593, 0x65A1, 0x65A5, 0x65AD, 0x65B9, 0x65C5, 0x65E3, 0x65F3, 0x65FB, 0x65FF, 0x6601, 0x6607, 0x661D, 0x6629, 0x6631, 0x663B,
/*D0-DF*/ 0x6641, 0x6647, 0x664D, 0x665B, 0x6661, 0x6673, 0x667D, 0x6689, 0x668B, 0x6695, 0x6697, 0x669B, 0x66B5, 0x66B9, 0x66C5, 0x66CD,
/*E0-EF*/ 0x66D1, 0x66E3, 0x66EB, 0x66F5, 0x6703, 0x6713, 0x6719, 0x671F, 0x6727, 0x6731, 0x6737, 0x673F, 0x6745, 0x6751, 0x675B, 0x676F,
/*F0-FF*/ 0x6779, 0x6781, 0x6785, 0x6791, 0x67AB, 0x67BD, 0x67C1, 0x67CD, 0x67DF, 0x67E5, 0x6803, 0x6809, 0x6811, 0x6817, 0x682D, 0x6839,
};
inline void write4BE(BYTE *p, DWORD val)
{
DWORD shifts[4] = { 0x18, 0x10, 0x08, 0 };
for ( int i = 0; i < 4; ++i)
p[i] = static_cast<BYTE>((val >> shifts[i]) & 0xFF);
}
inline void write2BE(BYTE *p, DWORD val)
{
DWORD shifts[2] = { 0x08, 0 };
for ( int i = 0; i < 2; ++i)
p[i] = static_cast<BYTE>((val >> shifts[i]) & 0xFF);
}
inline DWORD read2BE(BYTE *p)
{
DWORD val = 0;
for ( int i = 0; i < 2; ++i)
val = (val << 8) + p[i];
return val;
}
DWORD GetMultipliers(const WORD* const /*in*/ pLookupTable, LPBYTE /*in*/ pInputBuffer, int inputBufferLength, int loopCount, LPBYTE /*out*/ pDestFactors = 0);
// Derives values from given buffer.
// Returns main value, and optionally write 2 other WORD values in user-provided pDestFactors buffer.
DWORD GetMultipliers(const WORD* const /*in*/ pLookupTable, LPBYTE /*in*/ pInputBuffer, int inputBufferLength, int loopCount, LPBYTE /*out*/ pDestFactors)
{
// note, only multiplier1 is used for scrambled ROFS
DWORD multiplier1 = 0x4A1D, multiplier2 = 0x53FF, multiplier3 = 0x5DC1;
for ( int i = 0; i < loopCount; ++i )
{
DWORD multiplier_tmp;
DEBUG_CODE fprintf(stderr, "# @(%02X): 0x%08X\n", pInputBuffer[i], pLookupTable[*(char*)(pInputBuffer + i) + 0x80]);
DEBUG_CODE fprintf(stderr, "### (0x%04X) 0x%04X * 0x%04X = 0x%08X\n", multiplier1, ((short int)multiplier1), (pLookupTable[*(char*)(pInputBuffer + i) + 0x80]), ((short int)multiplier1) * (pLookupTable[*(char*)(pInputBuffer + i) + 0x80]));
multiplier_tmp = multiplier1 = ((short int)multiplier1) * (pLookupTable[*(char*)(pInputBuffer + i) + 0x80]);
multiplier1 &= 0x800003FF;
if ( LONG(multiplier1) < 0 )
{
multiplier1 = static_cast<DWORD>(- LONG(multiplier1));
}
DEBUG_CODE fprintf(stderr, "#MUL1=> 0x%08X (0x%03X): 0x%04X\n", multiplier_tmp, multiplier1, pLookupTable[multiplier1]);
multiplier1 = pLookupTable[multiplier1];
multiplier_tmp = multiplier2 = ((short int)multiplier2) * (pLookupTable[*(char*)(pInputBuffer + i) + 0x80]);
multiplier2 &= 0x800003FF;
if ( LONG(multiplier2) < 0 )
{
multiplier2 = static_cast<DWORD>(- LONG(multiplier2));
}
DEBUG_CODE fprintf(stderr, "#MUL2=> 0x%08X (0x%03X): 0x%04X\n", multiplier_tmp, multiplier2, pLookupTable[multiplier2]);
multiplier2 = pLookupTable[multiplier2];
multiplier_tmp = multiplier3 = ((short int)multiplier3) * (pLookupTable[*(char*)(pInputBuffer + i) + 0x80]);
multiplier3 &= 0x800003FF;
if ( LONG(multiplier3) < 0 )
{
multiplier3 = static_cast<DWORD>(- LONG(multiplier3));
}
DEBUG_CODE fprintf(stderr, "#MUL3=> 0x%04X (0x%03X): 0x%04X\n", multiplier_tmp, multiplier3, pLookupTable[multiplier3]);
multiplier3 = pLookupTable[multiplier3];
}
DEBUG_CODE fprintf(stderr, "#MUL#0x%03X, 0x%03X, 0x%03X\n", multiplier1, multiplier2, multiplier3);
if ( pDestFactors )
{
write2BE(pDestFactors, multiplier2);
write2BE(pDestFactors+2, multiplier3);
}
return LOWORD(multiplier1);
}
// ; Xorgen0
void Xorgen0(LPBYTE /*in*/ IV, LPBYTE /*in*/ xorgenValues, LPBYTE /*out*/ mutatedVector)
{
mutatedVector[0] = IV[3] ^ xorgenValues[0];
mutatedVector[1] = IV[0];
mutatedVector[2] = IV[7] ^ xorgenValues[3];
mutatedVector[3] = IV[4];
mutatedVector[4] = IV[1];
mutatedVector[5] = IV[6] ^ xorgenValues[2];
mutatedVector[6] = IV[2];
mutatedVector[7] = IV[5] ^ xorgenValues[1];
}
// ; Xorgen1
void Xorgen1(LPBYTE /*in*/ IV, LPBYTE /*in*/ xorgenValues, LPBYTE /*out*/ mutatedVector)
{
mutatedVector[0] = IV[2] ^ xorgenValues[1];
mutatedVector[1] = IV[7];
mutatedVector[2] = IV[5];
mutatedVector[3] = IV[3] ^ xorgenValues[2];
mutatedVector[4] = IV[0] ^ xorgenValues[0];
mutatedVector[5] = IV[6];
mutatedVector[6] = IV[4];
mutatedVector[7] = IV[1] ^ xorgenValues[3];
}
// ; Xorgen2
void Xorgen2(LPBYTE /*in*/ IV, LPBYTE /*in*/ xorgenValues, LPBYTE /*out*/ mutatedVector)
{
mutatedVector[0] = IV[1];
mutatedVector[1] = IV[7] ^ xorgenValues[2];
mutatedVector[2] = IV[6];
mutatedVector[3] = IV[2] ^ xorgenValues[1];
mutatedVector[4] = IV[5] ^ xorgenValues[3];
mutatedVector[5] = IV[3];
mutatedVector[6] = IV[0] ^ xorgenValues[0];
mutatedVector[7] = IV[4];
}
// ; Xorgen3
void Xorgen3(LPBYTE /*in*/ IV, LPBYTE /*in*/ xorgenValues, LPBYTE /*out*/ mutatedVector)
{
// Conversion to BYTE truncates
mutatedVector[0] = IV[3] + xorgenValues[2];
mutatedVector[1] = IV[6];
mutatedVector[2] = IV[0];
mutatedVector[3] = IV[2];
mutatedVector[4] = IV[4] + xorgenValues[0];
mutatedVector[5] = IV[1] + xorgenValues[1];
mutatedVector[6] = IV[7];
mutatedVector[7] = IV[5] + xorgenValues[3];
}
// ; Xorgen4
void Xorgen4(LPBYTE /*in*/ IV, LPBYTE /*in*/ xorgenValues, LPBYTE /*out*/ mutatedVector)
{
mutatedVector[0] = IV[7];
mutatedVector[1] = IV[0] + xorgenValues[3];
mutatedVector[2] = IV[2] + xorgenValues[0];
mutatedVector[3] = IV[6] + xorgenValues[1];
mutatedVector[4] = IV[4];
mutatedVector[5] = IV[3];
mutatedVector[6] = IV[5];
mutatedVector[7] = IV[1] + xorgenValues[2];
}
// ; Xorgen5
void Xorgen5(LPBYTE /*in*/ IV, LPBYTE /*in*/ xorgenValues, LPBYTE /*out*/ mutatedVector)
{
mutatedVector[0] = IV[2];
mutatedVector[1] = IV[3] + xorgenValues[2];
mutatedVector[2] = IV[6];
mutatedVector[3] = IV[7] + xorgenValues[0];
mutatedVector[4] = IV[0];
mutatedVector[5] = IV[1] + xorgenValues[1];
mutatedVector[6] = IV[4];
mutatedVector[7] = IV[5] + xorgenValues[3];
}
// ; Xorgen6
void Xorgen6(LPBYTE /*in*/ IV, LPBYTE /*in*/ xorgenValues, LPBYTE /*out*/ mutatedVector)
{
mutatedVector[0] = IV[3] + xorgenValues[0];
mutatedVector[1] = IV[7];
mutatedVector[2] = IV[2] ^ xorgenValues[1];
mutatedVector[3] = IV[6];
mutatedVector[4] = IV[1];
mutatedVector[5] = IV[5] ^ xorgenValues[2];
mutatedVector[6] = IV[0];
mutatedVector[7] = IV[4] + xorgenValues[3];
}
// ; Xorgen7
void Xorgen7(LPBYTE /*in*/ IV, LPBYTE /*in*/ xorgenValues, LPBYTE /*out*/ mutatedVector)
{
mutatedVector[0] = IV[7];
mutatedVector[1] = IV[4] ^ xorgenValues[3];
mutatedVector[2] = IV[3];
mutatedVector[3] = IV[1] + xorgenValues[2];
mutatedVector[4] = IV[0];
mutatedVector[5] = IV[2];
mutatedVector[6] = IV[5] + xorgenValues[1];
mutatedVector[7] = IV[6] ^ xorgenValues[0];
}
// ; Xorgen8
void Xorgen8(LPBYTE /*in*/ IV, LPBYTE /*in*/ xorgenValues, LPBYTE /*out*/ mutatedVector)
{
mutatedVector[0] = IV[3];
mutatedVector[1] = IV[0] ^ xorgenValues[1];
mutatedVector[2] = IV[6];
mutatedVector[3] = IV[4] + xorgenValues[0];
mutatedVector[4] = IV[2] ^ xorgenValues[3];
mutatedVector[5] = IV[7];
mutatedVector[6] = IV[1];
mutatedVector[7] = IV[5] + xorgenValues[2];
}
CvmXorgenDelegate xorgen_methods[] = {
Xorgen0,
Xorgen1,
Xorgen2,
Xorgen3,
Xorgen4,
Xorgen5,
Xorgen6,
Xorgen7,
Xorgen8,
};
void createSeedTableFromInteger(DWORD seednum, BYTE* pDestSeed)
{
write4BE(pDestSeed, (seednum << 20) + seednum);
}
};
//----------------------------------- Public ---------------------------------------//
// Creates an initialization vector for the Xor operations
// Uses a seed (pInitializer), which is the product code of specified length. If length == -1, it is calculated based on string length of 0-terminated pInitializer.
// The vector (pDestBuffer), which is supposed to be at least 8 bytes long, is modified in-place.
void CvmCreateXorIV(const BYTE* const pInitializer, int length, const WORD* const pLookupTable, LPBYTE /*out*/ pDestBuffer)
{
if ( length == -1 )
length = lstrlenA(reinterpret_cast<const char* const>(pInitializer));
// ****
// Compute 32-bit hash of pInitializer
// ****
DWORD sum = 0;
int i, j;
for ( i = 0; i < length; ++i )
{
sum = pInitializer[i] * (sum + pInitializer[i]);
// fprintf(stderr, "*[i=%d] 0x%08X\n", i, sum);
for ( j = i + 1; j < length; ++j )
{
sum += pInitializer[j];
}
// fprintf(stderr, "*\t[j=%d]\t0x%08X\n", j, sum);
}
DWORD sum2 = (((sum << 0x14) & 0xFFFFFFFF) + sum) & 0xFFFFFFFF;
// fprintf(stderr, "0x%08X => 0x%08X\n", sum, sum2);
// ****
// Fill vector for computation (8 bytes)
// ****
DWORD shifts[4] = { 0x18, 0, 0x10, 0x08 };
for ( i = 0; i < 4; ++i)
{
pDestBuffer[i] = static_cast<BYTE>((sum2 >> shifts[i]) & 0xFF);
// fprintf(stderr, "# 0x%02X\n", pDestBuffer[i]);
pDestBuffer[7-i] = pDestBuffer[i]; // AA BB CC DD DD CC BB AA
}
// ****
// Compute vector in-place, word by word (for a total of 8 bytes)
// ****
for ( int k = 0; k < 4; ++k )
{
DWORD updated = GetMultipliers(pLookupTable, pDestBuffer, 8, 2);
write2BE(pDestBuffer, updated);
pDestBuffer += 2;
}
}
//-------------------------------------------------------------------------------//
const WORD * const CvmGetXorLookupTable()
{
return ::LOOKUP_TABLE;
}
const CvmXorgenDelegate * const CvmGetXorgenMethods()
{
return ::xorgen_methods;
}
void CvmDecodeSector(LPBYTE IV, LPBYTE /*in/out*/ pData, int dataLength, BYTE sectorIndex)
{
DWORD offset = 0;
// seednum is initialized using IV, and further modified when processing bytes
DWORD seednum = IV[5];
// seedTable is generated using seednum for every 8-byte block and is used in GetMultipliers()
BYTE seedTable[4] = {};
// xorgenValues is an array generated by GetMultipliers() and used by xorgen Methods
BYTE xorgenValues[4] = {};
// vector to XOR against, that changes every 8 bytes.
BYTE outputMutatedVector[8] = {};
for(LPBYTE pCurrent = pData; pCurrent < pData + 0x800; )
{
seednum *= sectorIndex;
createSeedTableFromInteger(seednum, seedTable);
// in:seedTable out:retval, xorgenValues
DWORD mul1 = GetMultipliers(LOOKUP_TABLE, seedTable, 4, 4, xorgenValues);
DEBUG_CODE fprintf(stderr, "mul1:[%04X](%d) mul2:[%04X] mul3:[%04X]\n", mul1, mul1 % 9, read2BE(xorgenValues), read2BE(xorgenValues+2));
memset(outputMutatedVector, 0x00, 8);
// Call function pointer in table
xorgen_methods[mul1 % 9](IV, xorgenValues, outputMutatedVector);
// reinitialize seednum, its final value in this block will be used for next block.
seednum = (mul1 % 9) + offset;
// process data (in-place) using outputMutatedVector, update seednum
for ( int i = 0; i < 8; ++i )
{
DEBUG_CODE fprintf(stderr, "### (%d, %d) 0x%08X * 0x%02X = 0x%08X\n", (mul1 % 9), offset, seednum, outputMutatedVector[i], seednum * outputMutatedVector[i]);
seednum *= outputMutatedVector[i];
pCurrent[i] ^= outputMutatedVector[i];
}
pCurrent += 8;
offset += 8;
DEBUG_CODE fprintf(stderr, "* seednum: [%08X]\n", seednum);
DEBUG_CODE fprintf(stderr, "* pCurrent: [%08X]\n", pCurrent);
}
DEBUG_CODE fprintf(stderr, "* seednum: [%08X]\n", seednum);
}
|
#ifndef ABSTRACT_GRAPH
#define ABSTRACT_GRAPH 1
#include "include/list.hpp"
#include "include/seq_linear_list.hpp"
#include "GraphAdjacencyBase.hpp"
namespace cs202 {
enum GraphMode
{
LIST,
MATRIX
};
enum Color
{
WHITE,
GRAY,
BLACK
};
/*
* An interface to represent any type of Graph
*/
class AbstractGraph {
public:
/* Destructor:
* releases all resources acquired by the class
*/
virtual ~AbstractGraph() {
}
/*
* Function: edgeExists
* Returns true if an edge exists between vertices i and j, false otherwise.
*/
virtual bool edgeExits(int i, int j) const = 0;
/*
* Function: edges
* Returns the number of edges in the adjacency structure.
*/
virtual int edges() const = 0;
/*
* Function: vertices
* Returns the number of vertices in the adjacency structure.
*/
virtual int vertices() const = 0;
/*
* Function add:
* Adds an edge between vertices i and j
*/
virtual void add(int i, int j, int weight) = 0;
/*
* Function: remove
* Deleted the edge between vertices i and j
*/
virtual void remove(int i, int j) = 0;
virtual list<GraphEdge> adjacentVertices(int i) const = 0;
/*
* Function dfs:
* Does a depth first traversal of the entire graph.
* Runs the given function work, with the value of each vertex.
*/
virtual LinearList<int> dfs(int source, void (*work)(int&)) = 0;
/*
* Function bfs:
* Does a breadth first traversal of the entire graph.
* Runs the given function work, with the value of each vertex.
*/
virtual LinearList<int> bfs(int source, void (*work)(int&)) = 0;
};
}
#endif /* ifndef ABSTRACT_GRAPH */
|
/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <ntddk.h>
#include <ntstrsafe.h>
#include <aux_klib.h>
#include "module.h"
typedef LONG HIGH_LOCK, * PHIGH_LOCK;
#define MODULE_TAG 'UDOM'
#define LOCK_MAGIC 0xFEEDFACE
static FORCEINLINE
__drv_maxIRQL(HIGH_LEVEL)
__drv_raisesIRQL(HIGH_LEVEL)
__drv_savesIRQL
KIRQL
__AcquireHighLock(
IN PHIGH_LOCK Lock
)
{
KIRQL Irql;
KeRaiseIrql(HIGH_LEVEL, &Irql);
while (InterlockedCompareExchange(Lock, LOCK_MAGIC, 0) != 0)
_mm_pause();
KeMemoryBarrier();
return Irql;
}
#define AcquireHighLock(_Lock, _Irql) \
do { \
*(_Irql) = __AcquireHighLock(_Lock); \
} while (FALSE)
static FORCEINLINE
__drv_maxIRQL(HIGH_LEVEL)
__drv_requiresIRQL(HIGH_LEVEL)
VOID
ReleaseHighLock(
IN PHIGH_LOCK Lock,
IN __drv_restoresIRQL KIRQL Irql
)
{
KeMemoryBarrier();
InterlockedExchange(Lock, 0);
KeLowerIrql(Irql);
}
static FORCEINLINE
VOID
InitializeHighLock(
IN PHIGH_LOCK Lock
)
{
RtlZeroMemory(&Lock, sizeof(HIGH_LOCK));
}typedef struct _MODULE {
LIST_ENTRY ListEntry;
ULONG_PTR Start;
ULONG_PTR End;
CHAR Name[AUX_KLIB_MODULE_PATH_LEN];
} MODULE, * PMODULE;
typedef struct _MODULE_CONTEXT {
LONG References;
LIST_ENTRY List;
PLIST_ENTRY Cursor;
HIGH_LOCK Lock;
} MODULE_CONTEXT, * PMODULE_CONTEXT;
static MODULE_CONTEXT ModuleContext;
static FORCEINLINE PVOID
__ModuleAllocate(
IN ULONG Length
)
{
return (PVOID)ExAllocatePoolWithTag(NonPagedPool, Length, MODULE_TAG);
}
static FORCEINLINE VOID
__ModuleFree(
IN PVOID Buffer
)
{
ExFreePoolWithTag(Buffer, MODULE_TAG);
}
static VOID
ModuleSearchForwards(
IN PMODULE_CONTEXT Context,
IN ULONG_PTR Address
)
{
while (Context->Cursor != &Context->List) {
PMODULE Module;
Module = CONTAINING_RECORD(Context->Cursor, MODULE, ListEntry);
if (Address <= Module->End)
break;
Context->Cursor = Context->Cursor->Flink;
}
}
static VOID
ModuleSearchBackwards(
IN PMODULE_CONTEXT Context,
IN ULONG_PTR Address
)
{
while (Context->Cursor != &Context->List) {
PMODULE Module;
Module = CONTAINING_RECORD(Context->Cursor, MODULE, ListEntry);
if (Address >= Module->Start)
break;
Context->Cursor = Context->Cursor->Blink;
}
}
static NTSTATUS
ModuleAdd(
IN PMODULE_CONTEXT Context,
IN PCHAR Name,
IN ULONG_PTR Start,
IN ULONG_PTR Size
)
{
#define INSERT_AFTER(_Cursor, _New) \
do { \
(_New)->Flink = (_Cursor)->Flink; \
(_Cursor)->Flink->Blink = (_New); \
\
(_Cursor)->Flink = (_New); \
(_New)->Blink = (_Cursor); \
} while (FALSE)
#define INSERT_BEFORE(_Cursor, _New) \
do { \
(_New)->Blink = (_Cursor)->Blink; \
(_Cursor)->Blink->Flink = (_New); \
\
(_Cursor)->Blink = (_New); \
(_New)->Flink = (_Cursor); \
} while (FALSE)
PMODULE New;
//ULONG Index;
PMODULE Module;
KIRQL Irql;
LIST_ENTRY List;
BOOLEAN After;
NTSTATUS status;
New = __ModuleAllocate(sizeof(MODULE));
status = STATUS_NO_MEMORY;
if (New == NULL)
goto fail1;
/*for (Index = 0; Index < AUX_KLIB_MODULE_PATH_LEN; Index++) {
if (Name[Index] == '\0')
break;
New->Name[Index] = (CHAR)tolower(Name[Index]);
}*/
RtlStringCbCopyA(New->Name, AUX_KLIB_MODULE_PATH_LEN, Name);
New->Start = Start;
New->End = Start + Size - 1;
InitializeListHead(&List);
AcquireHighLock(&Context->Lock, &Irql);
again:
After = TRUE;
if (Context->Cursor == &Context->List) {
ASSERT(IsListEmpty(&Context->List));
goto done;
}
Module = CONTAINING_RECORD(Context->Cursor, MODULE, ListEntry);
if (New->Start > Module->End) {
ModuleSearchForwards(Context, New->Start);
After = FALSE;
if (Context->Cursor == &Context->List) // End of list
goto done;
Module = CONTAINING_RECORD(Context->Cursor, MODULE, ListEntry);
if (New->End >= Module->Start) { // Overlap
PLIST_ENTRY Cursor = Context->Cursor->Blink;
RemoveEntryList(Context->Cursor);
InsertTailList(&List, &Module->ListEntry);
Context->Cursor = Cursor;
goto again;
}
}
else if (New->End < Module->Start) {
ModuleSearchBackwards(Context, New->End);
After = TRUE;
if (Context->Cursor == &Context->List) // Start of list
goto done;
Module = CONTAINING_RECORD(Context->Cursor, MODULE, ListEntry);
if (New->Start <= Module->End) { // Overlap
PLIST_ENTRY Cursor = Context->Cursor->Flink;
RemoveEntryList(Context->Cursor);
InsertTailList(&List, &Module->ListEntry);
Context->Cursor = Cursor;
goto again;
}
}
else {
PLIST_ENTRY Cursor;
Cursor = (Context->Cursor->Flink != &Context->List) ?
Context->Cursor->Flink :
Context->Cursor->Blink;
RemoveEntryList(Context->Cursor);
InsertTailList(&List, &Module->ListEntry);
Context->Cursor = Cursor;
goto again;
}
done:
if (After)
INSERT_AFTER(Context->Cursor, &New->ListEntry);
else
INSERT_BEFORE(Context->Cursor, &New->ListEntry);
Context->Cursor = &New->ListEntry;
ReleaseHighLock(&Context->Lock, Irql);
while (!IsListEmpty(&List)) {
PLIST_ENTRY ListEntry;
ListEntry = RemoveHeadList(&List);
ASSERT(ListEntry != &List);
Module = CONTAINING_RECORD(ListEntry, MODULE, ListEntry);
__ModuleFree(Module);
}
return STATUS_SUCCESS;
fail1:
return status;
#undef INSERT_AFTER
#undef INSERT_BEFORE
}
__drv_requiresIRQL(PASSIVE_LEVEL)
static VOID
ModuleLoad(
IN PUNICODE_STRING FullImageName,
IN HANDLE ProcessId,
IN PIMAGE_INFO ImageInfo
)
{
PMODULE_CONTEXT Context = &ModuleContext;
ANSI_STRING Ansi;
PCHAR Buffer;
PCHAR Name;
NTSTATUS status;
UNREFERENCED_PARAMETER(ProcessId);
if (!ImageInfo->SystemModeImage)
return;
status = RtlUnicodeStringToAnsiString(&Ansi, FullImageName, TRUE);
if (!NT_SUCCESS(status))
goto fail1;
Buffer = __ModuleAllocate(Ansi.Length + sizeof(CHAR));
status = STATUS_NO_MEMORY;
if (Buffer == NULL)
goto fail2;
RtlCopyMemory(Buffer, Ansi.Buffer, Ansi.Length);
Name = strrchr((const CHAR*)Buffer, '\\');
Name = (Name == NULL) ? Buffer : (Name + 1);
DbgPrintEx(DPFLTR_IHVDRIVER_ID, 0, "CrashMonitoringDriver: %s\n", Name);
status = ModuleAdd(Context,
Name,
(ULONG_PTR)ImageInfo->ImageBase,
(ULONG_PTR)ImageInfo->ImageSize);
if (!NT_SUCCESS(status))
goto fail3;
__ModuleFree(Buffer);
RtlFreeAnsiString(&Ansi);
return;
fail3:
__ModuleFree(Buffer);
fail2:
RtlFreeAnsiString(&Ansi);
fail1:
return;
}
VOID
ModuleLookup(
IN ULONG_PTR Address,
OUT PCHAR* Name,
OUT PULONG_PTR Offset
)
{
PMODULE_CONTEXT Context = &ModuleContext;
PLIST_ENTRY ListEntry;
KIRQL Irql;
*Name = NULL;
*Offset = 0;
AcquireHighLock(&Context->Lock, &Irql);
for (ListEntry = Context->List.Flink;
ListEntry != &Context->List;
ListEntry = ListEntry->Flink) {
PMODULE Module;
Module = CONTAINING_RECORD(ListEntry, MODULE, ListEntry);
if (Address >= Module->Start &&
Address <= Module->End) {
*Name = Module->Name;
*Offset = Address - Module->Start;
break;
}
}
ReleaseHighLock(&Context->Lock, Irql);
}
VOID
ModuleTeardown(
VOID
)
{
PMODULE_CONTEXT Context = &ModuleContext;
(VOID)PsRemoveLoadImageNotifyRoutine(ModuleLoad);
Context->Cursor = NULL;
while (!IsListEmpty(&Context->List)) {
PLIST_ENTRY ListEntry;
PMODULE Module;
ListEntry = RemoveHeadList(&Context->List);
ASSERT(ListEntry != &Context->List);
Module = CONTAINING_RECORD(ListEntry, MODULE, ListEntry);
__ModuleFree(Module);
}
RtlZeroMemory(&Context->List, sizeof(LIST_ENTRY));
RtlZeroMemory(&Context->Lock, sizeof(HIGH_LOCK));
(VOID)InterlockedDecrement(&Context->References);
}
NTSTATUS
ModuleInitialize(
VOID)
{
PMODULE_CONTEXT Context = &ModuleContext;
ULONG References;
ULONG BufferSize;
ULONG Count;
PAUX_MODULE_EXTENDED_INFO QueryInfo;
ULONG Index;
NTSTATUS status;
References = InterlockedIncrement(&Context->References);
status = STATUS_OBJECTID_EXISTS;
if (References != 1)
goto fail1;
InitializeHighLock(&Context->Lock);
(VOID)AuxKlibInitialize();
status = AuxKlibQueryModuleInformation(&BufferSize,
sizeof(AUX_MODULE_EXTENDED_INFO),
NULL);
if (!NT_SUCCESS(status))
goto fail2;
status = STATUS_UNSUCCESSFUL;
if (BufferSize == 0)
goto fail3;
again:
Count = BufferSize / sizeof(AUX_MODULE_EXTENDED_INFO);
QueryInfo = (PAUX_MODULE_EXTENDED_INFO)__ModuleAllocate(sizeof(AUX_MODULE_EXTENDED_INFO) * Count);
status = STATUS_NO_MEMORY;
if (QueryInfo == NULL)
goto fail4;
status = AuxKlibQueryModuleInformation(&BufferSize,
sizeof(AUX_MODULE_EXTENDED_INFO),
QueryInfo);
if (!NT_SUCCESS(status)) {
if (status != STATUS_BUFFER_TOO_SMALL)
goto fail5;
__ModuleFree(QueryInfo);
goto again;
}
InitializeListHead(&Context->List);
Context->Cursor = &Context->List;
for (Index = 0; Index < Count; Index++) {
PCHAR Name;
Name = strrchr((const CHAR*)QueryInfo[Index].FullPathName, '\\');
Name = (Name == NULL) ? (PCHAR)QueryInfo[Index].FullPathName : (Name + 1);
DbgPrintEx(DPFLTR_IHVDRIVER_ID, 0, "CrashMonitoringDriver: %s\n", Name);
status = ModuleAdd(Context,
Name,
(ULONG_PTR)QueryInfo[Index].BasicInfo.ImageBase,
(ULONG_PTR)QueryInfo[Index].ImageSize);
if (!NT_SUCCESS(status))
goto fail6;
}
status = PsSetLoadImageNotifyRoutine(ModuleLoad);
if (!NT_SUCCESS(status))
goto fail7;
__ModuleFree(QueryInfo);
return STATUS_SUCCESS;
fail7:
fail6:
while (!IsListEmpty(&Context->List)) {
PLIST_ENTRY ListEntry;
PMODULE Module;
ListEntry = RemoveHeadList(&Context->List);
ASSERT(ListEntry != &Context->List);
Module = CONTAINING_RECORD(ListEntry, MODULE, ListEntry);
__ModuleFree(Module);
}
RtlZeroMemory(&Context->List, sizeof(LIST_ENTRY));
fail5:
__ModuleFree(QueryInfo);
fail4:
fail3:
fail2:
fail1:
(VOID)InterlockedDecrement(&Context->References);
return status;
}
|
#pragma once
#include "WinDef.h"
#include <d3d11.h>
class Graphics
{
public:
Graphics(HWND hwnd);
Graphics(const Graphics&) = delete;
Graphics& operator=(const Graphics&) = delete;
~Graphics();
void EndFrame();
void ClearBuffer(float red, float green, float blue) noexcept;
private:
ID3D11Device* pDevice = nullptr;
IDXGISwapChain* pSwap = nullptr;
ID3D11DeviceContext* pContext = nullptr;
ID3D11RenderTargetView* pTarget = nullptr;
};
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4; -*-
*
* Copyright (C) 2007-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef POSIX_OK_SELECT
#include "platforms/posix/posix_selector.h" // PosixSelector, PosixSelectListener
#include "platforms/posix/net/posix_network_address.h" // PosixNetworkAddress
#include "platforms/posix/net/posix_base_socket.h"
PosixSelectListener::~PosixSelectListener()
{
Detach();
}
int PosixSelectListener::DetachAndClose(int fd)
{
Detach(fd);
return close(fd);
}
void PosixSelectListener::Detach(int fd /* = -1 */)
{
if (g_opera && g_posix_selector)
g_posix_selector->Detach(this, fd);
}
#ifdef POSIX_OK_NETADDR
// static
OP_STATUS PosixSelector::PrepareSocketAddress(PosixNetworkAddress *&posix,
const OpSocketAddress *given,
int fd, PosixSelectListener *listener)
{
PosixNetworkAddress *local = OP_NEW(PosixNetworkAddress, ());
if (local == 0)
return OpStatus::ERR_NO_MEMORY;
OP_STATUS st = local->Import(given);
if (OpStatus::IsError(st))
{
OP_DELETE(local);
return st;
}
RETURN_IF_ERROR(ConnectSocketAddress(local, fd, listener));
posix = local;
return OpStatus::OK;
}
// static
OP_STATUS PosixSelector::ConnectSocketAddress(PosixNetworkAddress*& address,
int fd, PosixSelectListener *listener)
{
// Connect() clears errno before calling connect().
if (address->Connect(fd) == 0 || errno == EISCONN)
{
/* Successful call to connect(), or follow-up call after async
* connect has completed; no need to do it again. */
OP_DELETE(address);
address = NULL;
listener->OnConnected(fd);
}
else
switch (errno)
{
case EINPROGRESS:
case EALREADY:
case EINTR:
// That's OK, we'll catch up with it later.
break;
case ENOMEM: case ENOBUFS:
OP_DELETE(address);
address = NULL;
return OpStatus::ERR_NO_MEMORY;
default:
OP_DELETE(address);
address = NULL;
listener->OnError(fd, errno); // May delete listener.
return OpStatus::ERR;
}
return OpStatus::OK;
}
#endif // POSIX_OK_NETADDR
class ButtonGroup
: public PosixBaseSocket
, public List<PosixSelector::Button>
, private Link
{
const int m_read;
const int m_write;
class Ear : public SocketBindListener
{
ButtonGroup *const m_boss;
public:
Ear(ButtonGroup *boss) : m_boss(boss) {}
// PosixSelectListener API
virtual void OnReadReady(int fd) { m_boss->OnReadReady(fd); }
virtual void OnError(int fd, int err=0) { m_boss->OnDetach(fd); }
virtual void OnDetach(int fd) { m_boss->OnDetach(fd); }
} m_ear;
ButtonGroup(int read, int write)
: PosixBaseSocket(ASYNC), m_read(read), m_write(write), m_ear(this) {}
static ButtonGroup *FirstGroup()
{
return g_opera && g_posix_selector
? static_cast<ButtonGroup *>(
g_opera->posix_module.GetSelectButtonGroups()->First())
: NULL;
}
ButtonGroup *Suc() const { return static_cast<ButtonGroup *>(Link::Suc()); }
ButtonGroup *Pred() const { return static_cast<ButtonGroup *>(Link::Pred()); }
// Find a currently un-used channel, if any
bool ClearChannel(unsigned char *clear) const;
public:
~ButtonGroup();
static OP_STATUS Create(ButtonGroup ** group);
static char GetChannel(ButtonGroup ** group, OP_STATUS * err);
bool Write(const char &byte) { errno = 0; return 1 == write(m_write, &byte, 1); }
void Finish(const char channel);
void OnReadReady(int fd);
void OnDetach(int fd) { OP_ASSERT(fd == m_read); Out(); OP_DELETE(this); }
};
OP_STATUS ButtonGroup::Create(ButtonGroup ** group)
{
if (!g_opera || !g_posix_selector)
return OpStatus::ERR_NULL_POINTER;
int fds[2];
errno = 0;
// NB: socketpair may be usable in place of pipe.
if (pipe(fds) == 0)
{
ButtonGroup *ans = OP_NEW(ButtonGroup, (fds[0], fds[1]));
int err;
OP_STATUS stat = ans
? (ans->SetSocketFlags(fds[0], &err) && ans->SetSocketFlags(fds[1], &err)
? g_posix_selector->Watch(fds[0], PosixSelector::READ, &(ans->m_ear))
: OpStatus::ERR)
: OpStatus::ERR_NO_MEMORY;
if (OpStatus::IsSuccess(stat))
*group = ans;
else
{
OP_DELETE(ans);
close(fds[0]);
close(fds[1]);
}
return stat;
}
const int err = errno;
switch (err)
{
// Documented errno values:
case EMFILE: // process ran out of file handles
case ENFILE: // system ran out of file handles
PosixLogger::PError("pipe", err, Str::S_ERR_FILE_NO_HANDLE,
"Failed (check ulimit) to create file-handle pair");
break;
default:
OP_ASSERT(!"Non-POSIX error from pipe()");
// PosixLogger::PError("pipe", err, 0, "failed to create pipe() file-handle pair");
break;
}
return OpStatus::ERR;
}
bool ButtonGroup::ClearChannel(unsigned char *clear) const
{
// Easy case:
int i = UCHAR_MAX + 1;
for (PosixSelector::Button * old = First(); old; old = old->Suc())
if (int chan = old->m_channel)
if (chan < i) i = chan;
if (i > 1) // No channel < i is busy:
{
*clear = i - 1;
return true;
}
// Look for a gap in the active channels:
const int word = sizeof(unsigned int) * CHAR_BIT;
const int bigenough = (UCHAR_MAX + word - 1) / word;
unsigned int flags[bigenough] = { 1 }; // ARRAY OK, Eddy/2010/Feb/18th
/* Channel '\0' is never available, all other channels' bits are implicitly
* initialized clear. In principle, we now need to mark as unavailable any
* bits representing channels above UCHAR_MAX: */
if (bigenough * word > UCHAR_MAX + 1) // unlikely
for (i = (UCHAR_MAX + 1) % word; i < word; i++)
flags[bigenough-1] |= 1 << i;
for (PosixSelector::Button * old = First(); old; old = old->Suc())
if (old->m_channel) // channel in use
{
unsigned char chan = old->m_channel;
flags[chan / word] |= 1 << (chan % word);
}
for (i = bigenough; i-- > 0;)
if (~flags[i]) // i.e. not all bits set
{
unsigned char chan = word;
while (chan-- > 0)
if (!(flags[i] & (1 << chan))) // busy channel
{
*clear = i * word + chan;
return true;
}
OP_ASSERT(!"We shouldn't get to here; at least one bit was allegedly unset !");
}
return false;
}
// static
char ButtonGroup::GetChannel(ButtonGroup ** group, OP_STATUS * err)
{
for (ButtonGroup * run = FirstGroup(); run; run = run->Suc())
{
unsigned char chan;
if (run->ClearChannel(&chan))
{
*group = run;
return chan;
}
// Full button group; try next.
}
// No space in an existing button group; try creating another.
OP_STATUS status = Create(group);
if (OpStatus::IsSuccess(status))
{
OP_ASSERT(*group && g_opera && g_posix_selector); // See Create().
(*group)->Into(g_opera->posix_module.GetSelectButtonGroups());
return UCHAR_MAX;
}
*err = status;
return '\0';
}
void ButtonGroup::OnReadReady(int fd)
{
OP_ASSERT(fd = m_read);
char buff[32]; // ARRAY OK 2010-08-12 markuso
ssize_t got;
while (errno = 0, (got = read(m_read, buff, sizeof(buff))) > 0)
while (got-- > 0)
if (buff[got])
{
for (PosixSelector::Button * run = First(); run; run = run->Suc())
if (run->m_channel == buff[got])
{
run->OnPressed();
break;
}
// avoid duplicates:
for (int i = 0; i < got; i++)
if (buff[i] == buff[got])
buff[i] = '\0';
}
#if 0
switch (errno)
{
case EINTR: case AGAINCASE: case ENOBUFS: case ENOMEM: break; // worry about it later
case EBADF: case EOVERFLOW: // bad news
case EIO: ENXIO: case EBADMSG: case EINVAL: case EISDIR: // impossible
case ETIMEDOUT: case ECONNRESET: case ENOTCONN: // socket !
}
#endif
}
ButtonGroup::~ButtonGroup()
{
// Called on PosixModule's destruction, also by Finish() and OnDetach()
for (PosixSelector::Button * run = First(); run; run = run->Suc())
{
run->OnDetach();
run->Out();
}
}
void ButtonGroup::Finish(const char /* channel */)
{
if (!Empty()) return;
size_t spare = 0;
for (ButtonGroup * run = Suc(); run; run = run->Suc())
spare += UCHAR_MAX - run->Cardinal();
for (ButtonGroup * run = Pred(); run; run = run->Pred())
spare += UCHAR_MAX - run->Cardinal();
if (spare > UCHAR_MAX / 8) // somewhat arbitrary cut-off
{
// Spare empty group; purge !
Out();
OP_DELETE(this);
}
else if (Suc()) // move to end of list
{
Head * was = GetList();
Out();
Into(was);
}
}
PosixSelector::Button::Button()
: m_channel(ButtonGroup::GetChannel(&d.m_group, &d.m_cause))
{
if (m_channel)
{
OP_ASSERT(d.m_group);
Into(d.m_group);
}
else
OP_ASSERT(OpStatus::IsError(d.m_cause));
}
PosixSelector::Button::~Button()
{
if (m_channel)
{
if (InList())
{
Out();
OP_ASSERT(d.m_group);
d.m_group->Finish(m_channel); // *after* Out()
}
d.m_group = 0;
}
}
OP_STATUS PosixSelector::Button::Ready()
{
return g_opera && g_posix_selector && InList()
? m_channel ? OpStatus::OK : d.m_cause
: OpStatus::ERR_NULL_POINTER;
}
bool PosixSelector::Button::Press()
{
if (m_channel)
return d.m_group->Write(m_channel);
OP_ASSERT(!"This button should not be in use;"
" its creator should have noticed it isn't Ready() !");
errno = ENODEV;
return false;
}
#endif // POSIX_OK_SELECT
|
#include<iostream>
#include<string>
using namespace std;
#ifndef JOBDESCRIPTION_H
#define JOBDESCRIPTION_H
class Employee;
class JobDescription {
private:
string description;
Employee * emp;
public:
JobDescription();
JobDescription(string s);
~JobDescription();
Employee * getEmployee();
string getDescription();
void setEmployee(Employee * e);
void setDescription(string s);
};
JobDescription :: JobDescription(){
description = " ";
}
JobDescription :: JobDescription(string s){
description = s;
}
JobDescription :: ~JobDescription(){
}
string JobDescription :: getDescription(){
return description;
}
Employee * JobDescription :: getEmployee(){
return emp;
}
void JobDescription :: setDescription(string s){
description = s;
}
void JobDescription :: setEmployee(Employee * e){
emp = e;
}
#endif
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <folly/portability/GTest.h>
#include <folly/Random.h>
#include <folly/io/Cursor.h>
#include <quic/codec/QuicConnectionId.h>
#include <quic/codec/QuicPacketBuilder.h>
#include <quic/codec/QuicReadCodec.h>
#include <quic/codec/Types.h>
#include <quic/codec/test/Mocks.h>
#include <quic/common/test/TestUtils.h>
#include <quic/fizz/handshake/FizzCryptoFactory.h>
#include <quic/fizz/handshake/FizzRetryIntegrityTagGenerator.h>
#include <quic/handshake/HandshakeLayer.h>
using namespace quic;
using namespace quic::test;
using namespace testing;
enum TestFlavor { Regular, Inplace };
Buf packetToBuf(
RegularQuicPacketBuilder::Packet& packet,
Aead* aead = nullptr) {
auto buf = folly::IOBuf::create(0);
// This does not matter.
PacketNum num = 10;
if (packet.header) {
buf->prependChain(packet.header->clone());
}
std::unique_ptr<folly::IOBuf> body = folly::IOBuf::create(0);
if (packet.body) {
body = packet.body->clone();
}
if (aead && packet.header) {
auto bodySize = body->computeChainDataLength();
body = aead->inplaceEncrypt(std::move(body), packet.header.get(), num);
EXPECT_GT(body->computeChainDataLength(), bodySize);
}
if (body) {
buf->prependChain(std::move(body));
}
return buf;
}
size_t longHeaderLength = sizeof(uint32_t) + sizeof(uint32_t) +
kDefaultConnectionIdSize + sizeof(uint8_t);
constexpr size_t kVersionNegotiationHeaderSize =
sizeof(uint8_t) + kDefaultConnectionIdSize * 2 + sizeof(QuicVersion);
std::unique_ptr<QuicReadCodec> makeCodec(
ConnectionId clientConnId,
QuicNodeType nodeType,
std::unique_ptr<Aead> zeroRttCipher = nullptr,
std::unique_ptr<Aead> oneRttCipher = nullptr,
QuicVersion version = QuicVersion::MVFST) {
FizzCryptoFactory cryptoFactory;
auto codec = std::make_unique<QuicReadCodec>(nodeType);
if (nodeType != QuicNodeType::Client) {
codec->setZeroRttReadCipher(std::move(zeroRttCipher));
codec->setZeroRttHeaderCipher(test::createNoOpHeaderCipher());
}
codec->setOneRttReadCipher(std::move(oneRttCipher));
codec->setOneRttHeaderCipher(test::createNoOpHeaderCipher());
codec->setHandshakeReadCipher(test::createNoOpAead());
codec->setHandshakeHeaderCipher(test::createNoOpHeaderCipher());
codec->setClientConnectionId(clientConnId);
if (nodeType == QuicNodeType::Client) {
codec->setInitialReadCipher(
cryptoFactory.getServerInitialCipher(clientConnId, version));
codec->setInitialHeaderCipher(
cryptoFactory.makeServerInitialHeaderCipher(clientConnId, version));
} else {
codec->setInitialReadCipher(
cryptoFactory.getClientInitialCipher(clientConnId, version));
codec->setInitialHeaderCipher(
cryptoFactory.makeClientInitialHeaderCipher(clientConnId, version));
}
return codec;
}
class QuicPacketBuilderTest : public TestWithParam<TestFlavor> {
protected:
std::unique_ptr<PacketBuilderInterface> testBuilderProvider(
TestFlavor flavor,
uint32_t pktSizeLimit,
PacketHeader header,
PacketNum largestAckedPacketNum,
folly::Optional<size_t> outputBufSize) {
switch (flavor) {
case TestFlavor::Regular:
return std::make_unique<RegularQuicPacketBuilder>(
pktSizeLimit, std::move(header), largestAckedPacketNum);
case TestFlavor::Inplace:
CHECK(outputBufSize);
simpleBufAccessor_ =
std::make_unique<SimpleBufAccessor>(*outputBufSize);
return std::make_unique<InplaceQuicPacketBuilder>(
*simpleBufAccessor_,
pktSizeLimit,
std::move(header),
largestAckedPacketNum);
}
folly::assume_unreachable();
}
protected:
std::unique_ptr<BufAccessor> simpleBufAccessor_;
};
TEST_F(QuicPacketBuilderTest, SimpleVersionNegotiationPacket) {
auto versions = versionList({1, 2, 3, 4, 5, 6, 7});
auto srcConnId = getTestConnectionId(0), destConnId = getTestConnectionId(1);
VersionNegotiationPacketBuilder builder(srcConnId, destConnId, versions);
EXPECT_TRUE(builder.canBuildPacket());
auto builtOut = std::move(builder).buildPacket();
auto resultVersionNegotiationPacket = builtOut.first;
// Verify the returned packet from packet builder:
EXPECT_EQ(resultVersionNegotiationPacket.versions, versions);
EXPECT_EQ(resultVersionNegotiationPacket.sourceConnectionId, srcConnId);
EXPECT_EQ(resultVersionNegotiationPacket.destinationConnectionId, destConnId);
// Verify the returned buf from packet builder can be decoded by read codec:
auto packetQueue = bufToQueue(std::move(builtOut.second));
auto decodedVersionNegotiationPacket =
makeCodec(destConnId, QuicNodeType::Client)
->tryParsingVersionNegotiation(packetQueue);
ASSERT_TRUE(decodedVersionNegotiationPacket.has_value());
EXPECT_EQ(decodedVersionNegotiationPacket->sourceConnectionId, srcConnId);
EXPECT_EQ(
decodedVersionNegotiationPacket->destinationConnectionId, destConnId);
EXPECT_EQ(decodedVersionNegotiationPacket->versions, versions);
}
TEST_F(QuicPacketBuilderTest, TooManyVersions) {
std::vector<QuicVersion> versions;
for (size_t i = 0; i < 1000; i++) {
versions.push_back(static_cast<QuicVersion>(i));
}
auto srcConnId = getTestConnectionId(0), destConnId = getTestConnectionId(1);
size_t expectedVersionsToWrite =
(kDefaultUDPSendPacketLen - kVersionNegotiationHeaderSize) /
sizeof(QuicVersion);
std::vector<QuicVersion> expectedWrittenVersions;
for (size_t i = 0; i < expectedVersionsToWrite; i++) {
expectedWrittenVersions.push_back(static_cast<QuicVersion>(i));
}
VersionNegotiationPacketBuilder builder(srcConnId, destConnId, versions);
EXPECT_LE(builder.remainingSpaceInPkt(), sizeof(QuicVersion));
EXPECT_TRUE(builder.canBuildPacket());
auto builtOut = std::move(builder).buildPacket();
auto resultVersionNegotiationPacket = builtOut.first;
auto resultBuf = std::move(builtOut.second);
EXPECT_EQ(
expectedVersionsToWrite, resultVersionNegotiationPacket.versions.size());
EXPECT_EQ(resultVersionNegotiationPacket.versions, expectedWrittenVersions);
EXPECT_EQ(resultVersionNegotiationPacket.sourceConnectionId, srcConnId);
EXPECT_EQ(resultVersionNegotiationPacket.destinationConnectionId, destConnId);
AckStates ackStates;
auto packetQueue = bufToQueue(std::move(resultBuf));
auto decodedPacket = makeCodec(destConnId, QuicNodeType::Client)
->tryParsingVersionNegotiation(packetQueue);
ASSERT_TRUE(decodedPacket.has_value());
EXPECT_EQ(decodedPacket->destinationConnectionId, destConnId);
EXPECT_EQ(decodedPacket->sourceConnectionId, srcConnId);
EXPECT_EQ(decodedPacket->versions, expectedWrittenVersions);
}
TEST_P(QuicPacketBuilderTest, LongHeaderRegularPacket) {
ConnectionId clientConnId = getTestConnectionId(),
serverConnId = ConnectionId({1, 3, 5, 7});
PacketNum pktNum = 444;
QuicVersion ver = QuicVersion::MVFST;
// create a server cleartext write codec.
FizzCryptoFactory cryptoFactory;
auto cleartextAead = cryptoFactory.getClientInitialCipher(serverConnId, ver);
auto headerCipher =
cryptoFactory.makeClientInitialHeaderCipher(serverConnId, ver);
std::unique_ptr<PacketBuilderInterface> builderOwner;
auto builderProvider = [&](PacketHeader header, PacketNum largestAcked) {
auto builder = testBuilderProvider(
GetParam(),
kDefaultUDPSendPacketLen,
std::move(header),
largestAcked,
kDefaultUDPSendPacketLen * 2);
auto rawBuilder = builder.get();
builderOwner = std::move(builder);
return rawBuilder;
};
auto resultRegularPacket = createInitialCryptoPacket(
serverConnId,
clientConnId,
pktNum,
ver,
*folly::IOBuf::copyBuffer("CHLO"),
*cleartextAead,
0 /* largestAcked */,
0 /* offset */,
"" /* token */,
builderProvider);
auto resultBuf = packetToBufCleartext(
resultRegularPacket, *cleartextAead, *headerCipher, pktNum);
auto& resultHeader = resultRegularPacket.packet.header;
EXPECT_NE(resultHeader.asLong(), nullptr);
auto& resultLongHeader = *resultHeader.asLong();
EXPECT_EQ(LongHeader::Types::Initial, resultLongHeader.getHeaderType());
EXPECT_EQ(serverConnId, resultLongHeader.getSourceConnId());
EXPECT_EQ(pktNum, resultLongHeader.getPacketSequenceNum());
EXPECT_EQ(ver, resultLongHeader.getVersion());
AckStates ackStates;
auto packetQueue = bufToQueue(std::move(resultBuf));
auto optionalDecodedPacket = makeCodec(serverConnId, QuicNodeType::Server)
->parsePacket(packetQueue, ackStates);
ASSERT_NE(optionalDecodedPacket.regularPacket(), nullptr);
auto& decodedRegularPacket = *optionalDecodedPacket.regularPacket();
auto& decodedHeader = *decodedRegularPacket.header.asLong();
EXPECT_EQ(LongHeader::Types::Initial, decodedHeader.getHeaderType());
EXPECT_EQ(clientConnId, decodedHeader.getDestinationConnId());
EXPECT_EQ(pktNum, decodedHeader.getPacketSequenceNum());
EXPECT_EQ(ver, decodedHeader.getVersion());
}
TEST_P(QuicPacketBuilderTest, ShortHeaderRegularPacket) {
auto connId = getTestConnectionId();
PacketNum pktNum = 222;
PacketNum largestAckedPacketNum = 0;
auto encodedPacketNum = encodePacketNumber(pktNum, largestAckedPacketNum);
auto builder = testBuilderProvider(
GetParam(),
kDefaultUDPSendPacketLen,
ShortHeader(ProtectionType::KeyPhaseZero, connId, pktNum),
largestAckedPacketNum,
2000);
builder->encodePacketHeader();
// write out at least one frame
writeFrame(PaddingFrame(), *builder);
EXPECT_TRUE(builder->canBuildPacket());
auto builtOut = std::move(*builder).buildPacket();
auto resultRegularPacket = builtOut.packet;
size_t expectedOutputSize =
sizeof(Sample) + kMaxPacketNumEncodingSize - encodedPacketNum.length;
// We wrote less than sample bytes into the packet, so we'll pad it to sample
EXPECT_EQ(builtOut.body->computeChainDataLength(), expectedOutputSize);
auto resultBuf = packetToBuf(builtOut);
auto& resultShortHeader = *resultRegularPacket.header.asShort();
EXPECT_EQ(
ProtectionType::KeyPhaseZero, resultShortHeader.getProtectionType());
EXPECT_EQ(connId, resultShortHeader.getConnectionId());
EXPECT_EQ(pktNum, resultShortHeader.getPacketSequenceNum());
// TODO: change this when we start encoding packet numbers.
AckStates ackStates;
auto packetQueue = bufToQueue(std::move(resultBuf));
auto parsedPacket =
makeCodec(
connId, QuicNodeType::Client, nullptr, quic::test::createNoOpAead())
->parsePacket(packetQueue, ackStates);
auto& decodedRegularPacket = *parsedPacket.regularPacket();
auto& decodedHeader = *decodedRegularPacket.header.asShort();
EXPECT_EQ(ProtectionType::KeyPhaseZero, decodedHeader.getProtectionType());
EXPECT_EQ(connId, decodedHeader.getConnectionId());
EXPECT_EQ(pktNum, decodedHeader.getPacketSequenceNum());
}
TEST_P(QuicPacketBuilderTest, EnforcePacketSizeWithCipherOverhead) {
auto connId = getTestConnectionId();
PacketNum pktNum = 222;
PacketNum largestAckedPacketNum = 0;
size_t cipherOverhead = 2;
uint64_t enforcedSize = 1400;
auto aead = std::make_unique<NiceMock<MockAead>>();
auto aead_ = aead.get();
EXPECT_CALL(*aead_, _inplaceEncrypt(_, _, _))
.WillRepeatedly(Invoke([&](auto& buf, auto, auto) {
auto overhead = folly::IOBuf::create(1000);
overhead->append(cipherOverhead);
auto clone = buf->clone();
clone->prependChain(std::move(overhead));
return std::move(clone);
}));
auto builder = testBuilderProvider(
GetParam(),
kDefaultUDPSendPacketLen,
ShortHeader(ProtectionType::KeyPhaseZero, connId, pktNum),
largestAckedPacketNum,
2000);
builder->accountForCipherOverhead(cipherOverhead);
builder->encodePacketHeader();
// write out at least one frame
writeFrame(PaddingFrame(), *builder);
EXPECT_TRUE(builder->canBuildPacket());
auto builtOut = std::move(*builder).buildPacket();
auto param = GetParam();
if (param == TestFlavor::Regular) {
EXPECT_EQ(builtOut.body->isManagedOne(), true);
RegularSizeEnforcedPacketBuilder sizeEnforcedBuilder(
std::move(builtOut), enforcedSize, cipherOverhead);
EXPECT_TRUE(sizeEnforcedBuilder.canBuildPacket());
auto out = std::move(sizeEnforcedBuilder).buildPacket();
EXPECT_EQ(
out.header->computeChainDataLength() +
out.body->computeChainDataLength(),
enforcedSize - cipherOverhead);
auto buf = packetToBuf(out, aead_);
EXPECT_EQ(buf->computeChainDataLength(), enforcedSize);
} else {
EXPECT_EQ(builtOut.body->isManagedOne(), false);
InplaceSizeEnforcedPacketBuilder sizeEnforcedBuilder(
*simpleBufAccessor_, std::move(builtOut), enforcedSize, cipherOverhead);
EXPECT_TRUE(sizeEnforcedBuilder.canBuildPacket());
auto out = std::move(sizeEnforcedBuilder).buildPacket();
EXPECT_EQ(
out.header->computeChainDataLength() +
out.body->computeChainDataLength(),
enforcedSize - cipherOverhead);
auto buf = packetToBuf(out, aead_);
EXPECT_EQ(buf->computeChainDataLength(), enforcedSize);
}
}
TEST_P(QuicPacketBuilderTest, ShortHeaderWithNoFrames) {
auto connId = getTestConnectionId();
PacketNum pktNum = 222;
// We expect that the builder will not add new frames to a packet which has no
// frames already and will be too small to parse.
auto builder = testBuilderProvider(
GetParam(),
kDefaultUDPSendPacketLen,
ShortHeader(ProtectionType::KeyPhaseZero, connId, pktNum),
0 /*largestAckedPacketNum*/,
kDefaultUDPSendPacketLen);
builder->encodePacketHeader();
EXPECT_TRUE(builder->canBuildPacket());
auto builtOut = std::move(*builder).buildPacket();
auto resultRegularPacket = builtOut.packet;
auto resultBuf = packetToBuf(builtOut);
EXPECT_EQ(resultRegularPacket.frames.size(), 0);
AckStates ackStates;
auto packetQueue = bufToQueue(std::move(resultBuf));
auto parsedPacket =
makeCodec(
connId, QuicNodeType::Client, nullptr, quic::test::createNoOpAead())
->parsePacket(packetQueue, ackStates);
auto decodedPacket = parsedPacket.regularPacket();
EXPECT_EQ(decodedPacket, nullptr);
}
TEST_P(QuicPacketBuilderTest, TestPaddingAccountsForCipherOverhead) {
auto connId = getTestConnectionId();
PacketNum pktNum = 222;
PacketNum largestAckedPacketNum = 0;
auto encodedPacketNum = encodePacketNumber(pktNum, largestAckedPacketNum);
size_t cipherOverhead = 2;
auto builder = testBuilderProvider(
GetParam(),
kDefaultUDPSendPacketLen,
ShortHeader(ProtectionType::KeyPhaseZero, connId, pktNum),
largestAckedPacketNum,
kDefaultUDPSendPacketLen);
builder->encodePacketHeader();
builder->accountForCipherOverhead(cipherOverhead);
EXPECT_TRUE(builder->canBuildPacket());
writeFrame(PaddingFrame(), *builder);
auto builtOut = std::move(*builder).buildPacket();
auto resultRegularPacket = builtOut.packet;
// We should have padded the remaining bytes with Padding frames.
size_t expectedOutputSize =
sizeof(Sample) + kMaxPacketNumEncodingSize - encodedPacketNum.length;
EXPECT_EQ(resultRegularPacket.frames.size(), 1);
EXPECT_EQ(
builtOut.body->computeChainDataLength(),
expectedOutputSize - cipherOverhead);
}
TEST_P(QuicPacketBuilderTest, TestPaddingRespectsRemainingBytes) {
auto connId = getTestConnectionId();
PacketNum pktNum = 222;
PacketNum largestAckedPacketNum = 0;
size_t totalPacketSize = 20;
auto builder = testBuilderProvider(
GetParam(),
totalPacketSize,
ShortHeader(ProtectionType::KeyPhaseZero, connId, pktNum),
largestAckedPacketNum,
2000);
builder->encodePacketHeader();
EXPECT_TRUE(builder->canBuildPacket());
writeFrame(PaddingFrame(), *builder);
auto builtOut = std::move(*builder).buildPacket();
auto resultRegularPacket = builtOut.packet;
size_t headerSize = 13;
// We should have padded the remaining bytes with Padding frames.
EXPECT_EQ(resultRegularPacket.frames.size(), 1);
EXPECT_EQ(
builtOut.body->computeChainDataLength(), totalPacketSize - headerSize);
}
TEST_F(QuicPacketBuilderTest, PacketBuilderWrapper) {
MockQuicPacketBuilder builder;
EXPECT_CALL(builder, remainingSpaceInPkt()).WillRepeatedly(Return(500));
PacketBuilderWrapper wrapper(builder, 400);
EXPECT_EQ(400, wrapper.remainingSpaceInPkt());
EXPECT_CALL(builder, remainingSpaceInPkt()).WillRepeatedly(Return(50));
EXPECT_EQ(0, wrapper.remainingSpaceInPkt());
}
TEST_P(QuicPacketBuilderTest, LongHeaderBytesCounting) {
ConnectionId clientCid = getTestConnectionId(0);
ConnectionId serverCid = getTestConnectionId(1);
PacketNum pktNum = 8 * 24;
PacketNum largestAcked = 8 + 24;
LongHeader header(
LongHeader::Types::Initial,
clientCid,
serverCid,
pktNum,
QuicVersion::MVFST);
auto builder = testBuilderProvider(
GetParam(),
kDefaultUDPSendPacketLen,
std::move(header),
largestAcked,
kDefaultUDPSendPacketLen);
builder->encodePacketHeader();
auto expectedWrittenHeaderFieldLen = sizeof(uint8_t) +
sizeof(QuicVersionType) + sizeof(uint8_t) + clientCid.size() +
sizeof(uint8_t) + serverCid.size();
auto estimatedHeaderBytes = builder->getHeaderBytes();
EXPECT_GT(
estimatedHeaderBytes, expectedWrittenHeaderFieldLen + kMaxPacketLenSize);
writeFrame(PaddingFrame(), *builder);
EXPECT_LE(
std::move(*builder).buildPacket().header->computeChainDataLength(),
estimatedHeaderBytes);
}
TEST_P(QuicPacketBuilderTest, ShortHeaderBytesCounting) {
PacketNum pktNum = 8 * 24;
ConnectionId cid = getTestConnectionId();
PacketNum largestAcked = 8 + 24;
auto builder = testBuilderProvider(
GetParam(),
kDefaultUDPSendPacketLen,
ShortHeader(ProtectionType::KeyPhaseZero, cid, pktNum),
largestAcked,
2000);
builder->encodePacketHeader();
auto headerBytes = builder->getHeaderBytes();
writeFrame(PaddingFrame(), *builder);
EXPECT_EQ(
std::move(*builder).buildPacket().header->computeChainDataLength(),
headerBytes);
}
TEST_P(QuicPacketBuilderTest, InplaceBuilderReleaseBufferInDtor) {
SimpleBufAccessor bufAccessor(2000);
EXPECT_TRUE(bufAccessor.ownsBuffer());
auto builder = std::make_unique<InplaceQuicPacketBuilder>(
bufAccessor,
1000,
ShortHeader(ProtectionType::KeyPhaseZero, getTestConnectionId(), 0),
0);
EXPECT_FALSE(bufAccessor.ownsBuffer());
builder.reset();
EXPECT_TRUE(bufAccessor.ownsBuffer());
}
TEST_P(QuicPacketBuilderTest, InplaceBuilderReleaseBufferInBuild) {
SimpleBufAccessor bufAccessor(2000);
EXPECT_TRUE(bufAccessor.ownsBuffer());
auto builder = std::make_unique<InplaceQuicPacketBuilder>(
bufAccessor,
1000,
ShortHeader(ProtectionType::KeyPhaseZero, getTestConnectionId(), 0),
0);
builder->encodePacketHeader();
EXPECT_FALSE(bufAccessor.ownsBuffer());
writeFrame(PaddingFrame(), *builder);
std::move(*builder).buildPacket();
EXPECT_TRUE(bufAccessor.ownsBuffer());
}
TEST_F(QuicPacketBuilderTest, BuildTwoInplaces) {
SimpleBufAccessor bufAccessor(2000);
EXPECT_TRUE(bufAccessor.ownsBuffer());
auto builder1 = std::make_unique<InplaceQuicPacketBuilder>(
bufAccessor,
1000,
ShortHeader(ProtectionType::KeyPhaseZero, getTestConnectionId(), 0),
0);
builder1->encodePacketHeader();
auto headerBytes = builder1->getHeaderBytes();
for (size_t i = 0; i < 20; i++) {
writeFrame(PaddingFrame(), *builder1);
}
EXPECT_EQ(headerBytes, builder1->getHeaderBytes());
auto builtOut1 = std::move(*builder1).buildPacket();
EXPECT_EQ(1, builtOut1.packet.frames.size());
ASSERT_TRUE(builtOut1.packet.frames[0].asPaddingFrame());
EXPECT_EQ(builtOut1.packet.frames[0].asPaddingFrame()->numFrames, 20);
auto builder2 = std::make_unique<InplaceQuicPacketBuilder>(
bufAccessor,
1000,
ShortHeader(ProtectionType::KeyPhaseZero, getTestConnectionId(), 0),
0);
builder2->encodePacketHeader();
EXPECT_EQ(headerBytes, builder2->getHeaderBytes());
for (size_t i = 0; i < 40; i++) {
writeFrame(PaddingFrame(), *builder2);
}
auto builtOut2 = std::move(*builder2).buildPacket();
EXPECT_EQ(1, builtOut2.packet.frames.size());
ASSERT_TRUE(builtOut2.packet.frames[0].asPaddingFrame());
EXPECT_EQ(builtOut2.packet.frames[0].asPaddingFrame()->numFrames, 40);
EXPECT_EQ(builtOut2.header->length(), builtOut1.header->length());
EXPECT_EQ(20, builtOut2.body->length() - builtOut1.body->length());
}
TEST_F(QuicPacketBuilderTest, InplaceBuilderShorterHeaderBytes) {
auto connId = getTestConnectionId();
PacketNum packetNum = 0;
PacketNum largestAckedPacketNum = 0;
auto inplaceBuilder = testBuilderProvider(
TestFlavor::Inplace,
kDefaultUDPSendPacketLen,
ShortHeader(ProtectionType::KeyPhaseZero, connId, packetNum),
largestAckedPacketNum,
kDefaultUDPSendPacketLen);
inplaceBuilder->encodePacketHeader();
EXPECT_EQ(2 + connId.size(), inplaceBuilder->getHeaderBytes());
}
TEST_F(QuicPacketBuilderTest, InplaceBuilderLongHeaderBytes) {
auto srcConnId = getTestConnectionId(0);
auto destConnId = getTestConnectionId(1);
PacketNum packetNum = 0;
PacketNum largestAckedPacketNum = 0;
auto inplaceBuilder = testBuilderProvider(
TestFlavor::Inplace,
kDefaultUDPSendPacketLen,
LongHeader(
LongHeader::Types::Initial,
srcConnId,
destConnId,
packetNum,
QuicVersion::MVFST),
largestAckedPacketNum,
kDefaultUDPSendPacketLen);
inplaceBuilder->encodePacketHeader();
EXPECT_EQ(
9 /* initial + version + cid + cid + token length */ + srcConnId.size() +
destConnId.size() + kMaxPacketLenSize,
inplaceBuilder->getHeaderBytes());
}
TEST_F(QuicPacketBuilderTest, PseudoRetryPacket) {
// The values used in this test case are based on Appendix-A.4 of the
// QUIC-TLS draft v29.
uint8_t initialByte = 0xff;
ConnectionId sourceConnectionId(
{0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5});
ConnectionId destinationConnectionId((std::vector<uint8_t>()));
ConnectionId originalDestinationConnectionId(
{0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08});
auto quicVersion = static_cast<QuicVersion>(0xff00001d);
Buf token = folly::IOBuf::copyBuffer(R"(token)");
PseudoRetryPacketBuilder builder(
initialByte,
sourceConnectionId,
destinationConnectionId,
originalDestinationConnectionId,
quicVersion,
std::move(token));
Buf pseudoRetryPacketBuf = std::move(builder).buildPacket();
FizzRetryIntegrityTagGenerator fizzRetryIntegrityTagGenerator;
auto integrityTag = fizzRetryIntegrityTagGenerator.getRetryIntegrityTag(
quicVersion, pseudoRetryPacketBuf.get());
Buf expectedIntegrityTag = folly::IOBuf::copyBuffer(
"\xd1\x69\x26\xd8\x1f\x6f\x9c\xa2\x95\x3a\x8a\xa4\x57\x5e\x1e\x49");
folly::io::Cursor cursorActual(integrityTag.get());
folly::io::Cursor cursorExpected(expectedIntegrityTag.get());
EXPECT_TRUE(folly::IOBufEqualTo()(*expectedIntegrityTag, *integrityTag));
}
TEST_F(QuicPacketBuilderTest, PseudoRetryPacketLarge) {
uint8_t initialByte = 0xff;
ConnectionId sourceConnectionId(
{0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5});
ConnectionId destinationConnectionId((std::vector<uint8_t>()));
ConnectionId originalDestinationConnectionId(
{0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08});
auto quicVersion = static_cast<QuicVersion>(0xff00001d);
Buf token = folly::IOBuf::create(500);
token->append(500);
PseudoRetryPacketBuilder builder(
initialByte,
sourceConnectionId,
destinationConnectionId,
originalDestinationConnectionId,
quicVersion,
std::move(token));
Buf pseudoRetryPacketBuf = std::move(builder).buildPacket();
}
TEST_F(QuicPacketBuilderTest, RetryPacketValid) {
auto srcConnId = getTestConnectionId(0), dstConnId = getTestConnectionId(1);
auto quicVersion = static_cast<QuicVersion>(0xff00001d);
std::string retryToken = "token";
Buf integrityTag = folly::IOBuf::copyBuffer(
"\xaa\xbb\xcc\xdd\xee\xff\x11\x22\x33\x44\x55\x66\x77\x88\x99\x11");
RetryPacketBuilder builder(
srcConnId,
dstConnId,
quicVersion,
std::string(retryToken),
integrityTag->clone());
EXPECT_TRUE(builder.canBuildPacket());
Buf retryPacket = std::move(builder).buildPacket();
uint32_t expectedPacketLen = 1 /* initial byte */ + 4 /* version */ +
1 /* dcid length */ + dstConnId.size() + 1 /* scid length */ +
srcConnId.size() + retryToken.size() + kRetryIntegrityTagLen;
// Check that the buffer containing the packet is of the correct length
EXPECT_EQ(retryPacket->computeChainDataLength(), expectedPacketLen);
// initial byte
folly::io::Cursor cursor(retryPacket.get());
auto initialByte = cursor.readBE<uint8_t>();
EXPECT_EQ(initialByte & 0xf0, 0xf0);
// version
EXPECT_EQ(cursor.readBE<uint32_t>(), 0xff00001d);
// dcid length
auto dcidLen = cursor.readBE<uint8_t>();
EXPECT_EQ(dcidLen, dstConnId.size());
// dcid
ConnectionId dcidObtained(cursor, dcidLen);
EXPECT_EQ(dcidObtained, dstConnId);
// scid length
auto scidLen = cursor.readBE<uint8_t>();
EXPECT_EQ(scidLen, srcConnId.size());
// scid
ConnectionId scidObtained(cursor, scidLen);
EXPECT_EQ(scidObtained, srcConnId);
// retry token
Buf retryTokenObtained;
cursor.clone(
retryTokenObtained, cursor.totalLength() - kRetryIntegrityTagLen);
std::string retryTokenObtainedString =
retryTokenObtained->moveToFbString().toStdString();
EXPECT_EQ(retryTokenObtainedString, retryToken);
// integrity tag
Buf integrityTagObtained;
cursor.clone(integrityTagObtained, kRetryIntegrityTagLen);
EXPECT_TRUE(folly::IOBufEqualTo()(integrityTagObtained, integrityTag));
}
TEST_F(QuicPacketBuilderTest, RetryPacketGiganticToken) {
auto srcConnId = getTestConnectionId(0), dstConnId = getTestConnectionId(1);
auto quicVersion = static_cast<QuicVersion>(0xff00001d);
std::string retryToken;
for (uint32_t i = 0; i < 500; i++) {
retryToken += "aaaaaaaaaa";
}
Buf integrityTag = folly::IOBuf::copyBuffer(
"\xaa\xbb\xcc\xdd\xee\xff\x11\x22\x33\x44\x55\x66\x77\x88\x99\x11");
RetryPacketBuilder builder(
srcConnId,
dstConnId,
quicVersion,
std::string(retryToken),
integrityTag->clone());
EXPECT_FALSE(builder.canBuildPacket());
}
TEST_P(QuicPacketBuilderTest, PadUpLongHeaderPacket) {
ConnectionId emptyCID(std::vector<uint8_t>(0));
PacketNum packetNum = 0;
PacketNum largestAcked = 0;
auto builder = testBuilderProvider(
GetParam(),
kDefaultUDPSendPacketLen,
LongHeader(
LongHeader::Types::Handshake,
emptyCID,
emptyCID,
packetNum,
QuicVersion::MVFST),
largestAcked,
kDefaultUDPSendPacketLen);
builder->encodePacketHeader();
writeFrame(PingFrame(), *builder);
EXPECT_TRUE(builder->canBuildPacket());
auto builtOut = std::move(*builder).buildPacket();
auto resultPacket = builtOut.packet;
auto resultBuf = packetToBuf(builtOut);
auto packetQueue = bufToQueue(std::move(resultBuf));
AckStates ackStates;
auto parsedPacket =
makeCodec(
emptyCID, QuicNodeType::Client, nullptr, quic::test::createNoOpAead())
->parsePacket(packetQueue, ackStates);
auto& decodedRegularPacket = *parsedPacket.regularPacket();
EXPECT_NE(nullptr, decodedRegularPacket.header.asLong());
EXPECT_GT(decodedRegularPacket.frames.size(), 1);
}
TEST_P(QuicPacketBuilderTest, TestCipherOverhead) {
ConnectionId emptyCID(std::vector<uint8_t>(0));
PacketNum packetNum = 0;
PacketNum largestAcked = 0;
size_t cipherOverhead = 200;
auto builder = testBuilderProvider(
GetParam(),
kDefaultUDPSendPacketLen,
LongHeader(
LongHeader::Types::Handshake,
emptyCID,
emptyCID,
packetNum,
QuicVersion::MVFST),
largestAcked,
kDefaultUDPSendPacketLen);
builder->encodePacketHeader();
builder->accountForCipherOverhead(cipherOverhead);
while (builder->canBuildPacket()) {
writeFrame(PingFrame(), *builder);
}
auto builtOut = std::move(*builder).buildPacket();
auto resultRegularPacket = builtOut.packet;
EXPECT_LT(
resultRegularPacket.frames.size(),
kDefaultUDPSendPacketLen - cipherOverhead);
}
INSTANTIATE_TEST_SUITE_P(
QuicPacketBuilderTests,
QuicPacketBuilderTest,
Values(TestFlavor::Regular, TestFlavor::Inplace));
|
/************************************************************************
* @project : sloth
* @class : StaticShader
* @version : v1.0.0
* @description : 和基本着色器(basic)的 uniform 变量相对应,用于修改着色器变量
* @author : Oscar Shen
* @creat : 2016年10月8日14:52:32
* @revise : 2017年2月9日14:53:47
************************************************************************
* Copyright @ OscarShen 2017. All rights reserved.
*************************************************************************/
#pragma once
#ifndef SLOTH_STATIC_SHADER_H_
#define SLOTH_STATIC_SHADER_H_
#include "shader.h"
#include <glm/glm.hpp>
#include <string>
#include <vector>
#include <shader/uniform.h>
#include <entities/light.hpp>
#include <camera/camera.h>
#include "../config/header.hpp"
namespace sloth {
class StaticShader : public Shader
{
private:
int m_LocDiffuseMap;
int m_LocModel;
int m_LocView;
int m_LocProjection;
int *m_LocLightPos; // 灯光位置
int *m_LocLightColor; // 灯光颜色
int *m_LocAttenuation; // 灯光衰减
int m_LocShininess;
int m_LocReflectivity;
int m_LocUseFakeLighting;
int m_LocSkyColor;
int m_LocNumberOfRows;
int m_LocOffset;
int m_LocClipPlane; // 裁剪平面方程
int m_LocSpeculateMap; // 高亮贴图
int m_LocUseSpecularMap;
public:
static std::shared_ptr<StaticShader> inst() {
static std::shared_ptr<StaticShader> shader(new StaticShader());
return shader;
}
virtual ~StaticShader();
void loadModelMatrix(const glm::mat4 &model);
void loadViewMatrix(const RawCamera &camera);
void loadProjectionMatrix(const glm::mat4 &projection);
void loadLight(const Light &light);
/************************************************************************
* @description : 加载灯光相关的变量值——位置、颜色、衰减
* @author : Oscar Shen
* @creat : 2017年2月8日16:52:25
***********************************************************************/
void loadLights(const std::vector<Light> &lights);
void loadShineVariable(const float shininess, const float reflectivity);
void loadUseFakeLighting(const bool useFake);
void loadSkyColor(const float r, const float g, const float b);
void loadNumberOfRows(int numberOfRaws);
void loadOffset(float x, float y);
void loadClipPlane(const glm::vec4 &clipPlane);
void loadUseSpecularMap(bool useSpeMap);
private:
StaticShader();
void connectTextureUnit();
protected:
/***********************************************************************
* @description : 初始化时获取所有变量的 uniform location
* @author : Oscar Shen
* @creat : 2016年12月8日16:52:25
***********************************************************************/
virtual void getAllUniformLocation() override;
};
}
#endif // !SLOTH_STATIC_SHADER_H_
|
/*
* Funktionen.h
*
* Created on: 15.12.2016
* Author: FruehwF
*/
#ifndef FUNKTIONEN_H_
#define FUNKTIONEN_H_
#include <time.h>
#include <cmath>
#define DATA_EXT ".txt"
#define PLOT_EXT ".png"
void sleepcp(int milliseconds) // cross-platform sleep function
{
clock_t time_end;
time_end = clock() + milliseconds * CLOCKS_PER_SEC/1000;
while (clock() < time_end)
{
}
}
class f1: public Funktion {
public:
double value(double x) {
sleepcp(30);
return 2*pow(x,2) + exp(-2*x);
}
};
class f2: public Funktion {
public:
double value(double x) {
return (pow(x,4)/4) - pow(x,2) + 2*x;
} //f(x)
};
class f3: public Funktion {
public:
double value(double x) {
return pow(x,5) + 5*pow(x,4) + 5*pow(x,3) - 5*pow(x,2) - 6*x;
} //f(x)
};
class f4: public Funktion {
public:
double value(double x) {
return pow(x,4) - 16*pow(x,2) - 1;
} //f(x)
};
class f5: public Funktion {
public:
double value(double x) {
return log(abs(pow(x,3) + 5*x - 5));
} //f(x)
};
class f6: public Funktion {
public:
double value(double x) {
return log(abs(pow(x,4) - 16*pow(x,2) - 1));
} //f(x)
};
#endif /* FUNKTIONEN_H_ */
|
/*
Name: �ǹ�����
Copyright:
Author: Hill bamboo
Date: 2019/8/17 10:40:26
Description: ����
˼·��
ÿɨ�赽һ��С���ѣ��������ı���nά��һ����СΪn������Ȧ��
����������һ�����䱨��һ����С���ѣ�������Ȧ�Ĵ�С -1��
����ɨ�裬ֱ������Ȧ��СΪ0��
3, 3, 3, 3 => 4
2, 2, 3 => 7
0, 0, 0 => 3
1, 1, 3 => 6
3, 1, 3 => 6
4 4 4 4 4 4 4 4
=> 10
*/
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000 + 10;
int kids[maxn];
int n;
//int main() {
//
// do {
// cin >> kids[n++];
// if (cin.get() == '\n') break;
// } while (1);
//
// int cnt = 0;
// sort(kids, kids + n);
// for (int i = 0; i < n; ++i) {
// if (kids[i] == cnt) ++cnt;
// else cnt += (kids[i] + 1);
// }
//
// printf("%d\n", cnt);
// return 0;
//}
//���ӣ�https://www.nowcoder.com/questionTerminal/8ff3e3a14ea04c6bb3a60e2e457dafb1?f=discussion
//��Դ��ţ����
//ֻ����ͬ�������п�����ͬһ����ɫ���ǹ���������ͬ�������ֵĴ������ڸ���+1����������������
//��һ������һ������ɫ������˼·����map��¼���ֳ��ֵĴ�����Ϊ0��˵���ճ��ֻ��ߴ����þ���
//�����ۼ�
//#include<iostream>
//#include<unordered_map>
//using namespace std;
int main() {
int num,res=0;
unordered_map<int, int> a;
while (cin >> num) {
// ��һ�α�����������Ȧ��С�Ѽ���0
if (a[num] == 0) {
a[num] = num; // ����ͳ������Ȧ
res += num + 1; // ͳ����Ŀ
}
// ��С���ѵı�����ͬ ˵��������Ȧa[num]�е�һԱ��������Ȧ��С��һ
else a[num]--;
}
cout << res << endl;
return 0;
}
|
#include "GrowingBrushStokeAct.h"
#include "Misc.h"
GrowingBrushStokeAct::GrowingBrushStokeAct()
{
for( int i = 0; i < 80; i++ ) {
std::vector< ofPoint > emptyPoints;
dottedPoints.push_back( emptyPoints );
}
tintBuffer.allocate( Misc::getDefaultFboSettings() );
secondTintBuffer.allocate( Misc::getDefaultFboSettings() );
//voroWebLayer.allocate( settings );
plainStone = new BrushStone();
secondPlainStone = new BrushStone();
edgeDetectionPostProcessing = new ofxPostProcessing();
secondEdgeDetectionPass = new ofxPostProcessing();
fourRocks = new FourGrowingStonesLayer();
//vectorField.setup( 1920, 1080, 200 );
//vectorField.randomize();
bigRockColor = ofColor( 232, 202, 44 );
secondBigRockColor = ofColor( 255 );
setup();
}
GrowingBrushStokeAct::~GrowingBrushStokeAct()
{
delete plainStone;
delete secondPlainStone;
delete edgeDetectionPostProcessing;
delete secondEdgeDetectionPass;
delete fourRocks;
}
void GrowingBrushStokeAct::setup() {
transparency = 255;
voronoiWebTransparency = 0;
secondPlainStoneTransparency = 0;
voro2.clear();
for( int i = 0; i < dottedPoints.size(); i++ ) {
dottedPoints.at( i ).clear();
}
for( int i = 0; i < dottedPoints.size(); i++ ) {
voro2.addPoint( ofRandom( 0, 1920 ), ofRandom( 0, 1080 ) );
}
voro2.setSmoothAmount( 15 );
voro2.compute();
voro2.render();
for( int i = 0; i < voro2.getLines().size(); i++ ) {
ofPolyline lineToDraw = *voro2.getLine( i ); // rocks.at( i ).border
std::vector< ofPoint > pointsToDraw = Misc::getLineSplitPoints( lineToDraw, 4 );
dottedPoints.at( i ) = pointsToDraw;
}
doDrawBackground = false;
doScale = false;
scaleNoiseVal = 0.0f;
rotateNoiseVal = 0.0f;
growBrushIndex = 0;
scaleVal = 0.0;
rockYpos = 0.0;
backgroundTransparency = 255;
secondBigRockSpeed = 0.5f;
//ofBackground( 0 );
blackWhiteColor.colors.clear();
blackWhiteColor.addColor( 90, 90, 90 );
blackWhiteColor.addColor( 255, 255, 255 );
ofPolyline line;
line.addVertex( 0, 0 );
line.addVertex( 1920, 0 );
line.addVertex( 0, 1080 );
line.addVertex( 1920, 1080 );
line.setClosed( true );
//voroWebLayer.begin();
//drawVoronoiWeb();
//voroWebLayer.end();
tintBuffer.begin();
ofBackground( 0 );
tintBuffer.end();
secondTintBuffer.begin();
ofBackground( 0 );
secondTintBuffer.end();
delete edgeDetectionPostProcessing;
delete secondEdgeDetectionPass;
edgeDetectionPostProcessing = new ofxPostProcessing();
edgeDetectionPostProcessing->init( 1920, 1080 );
edgePass = edgeDetectionPostProcessing->createPass< EdgePass >();
edgePass->setEnabled( true );
noiseWarp = edgeDetectionPostProcessing->createPass<NoiseWarpPass>();
noiseWarp->setEnabled( true );
edgeDetectionPostProcessing->setFlip( false );
noiseWarp->setAmplitude( 0.0 );
noiseWarp->setFrequency( 0.0 );
secondEdgeDetectionPass = new ofxPostProcessing();
secondEdgeDetectionPass->init( 1920, 1080 );
secondEdgePass = secondEdgeDetectionPass->createPass<EdgePass>();
secondEdgePass->setEnabled( true );
secondEdgeDetectionPass->setFlip( false );
edgeDetectionPostProcessing->begin();
ofClear( 0.0, 0.0, 0.0, 1.0 );
edgeDetectionPostProcessing->end();
secondEdgeDetectionPass->begin();
ofClear( 0.0, 0.0, 0.0, 1.0 );
secondEdgeDetectionPass->end();
delete fourRocks;
fourRocks = new FourGrowingStonesLayer();
addCustomVoronoiPoints();
}
void GrowingBrushStokeAct::createStone( ofPoint centerStone )
{
delete plainStone;
delete secondPlainStone;
plainStone = new BrushStone();
plainStone->setColorCollection( blackWhiteColor );
plainStone->setBrushCollection( brushCollection );
plainStone->setBrushStrokeAlpha( 255 );
plainStone->init( centerStone.x, centerStone.y );
plainStone->setBrushStrokeSizeMin( 10 );
plainStone->setBrushStrokeSizeMax( 40 );
for( int i = 0; i < 3; i++ ) {
plainStone->grow( *voro.getLine( 0 ), ofVec2f( 1920 / 2, 1080 / 2 ) );
}
plainStone->setBrushStrokeSizeMin( 20 );
plainStone->setBrushStrokeSizeMax( 80 );
secondPlainStone = new BrushStone();
secondPlainStone->setColorCollection( blackWhiteColor );
secondPlainStone->setBrushCollection( brushCollection );
secondPlainStone->setBrushStrokeAlpha( 255 );
secondPlainStone->init( centerStone.x, centerStone.y );
secondPlainStone->setBrushStrokeSizeMin( 10 );
secondPlainStone->setBrushStrokeSizeMax( 40 );
for( int i = 0; i < 3; i++ ) {
secondPlainStone->grow( *voro.getLine( 0 ), ofVec2f( 1920 / 2, 1080 / 2 ) );
}
secondPlainStone->setBrushStrokeSizeMin( 20 );
secondPlainStone->setBrushStrokeSizeMax( 80 );
}
void GrowingBrushStokeAct::addCustomVoronoiPoints() {
voro.clear();
voro.addPoint( 1920 / 2, 1080 / 2 );
voro.addPoint( ofRandom( 100, 300 ), 100 );
voro.addPoint( ofRandom( 300, 700 ), 100 );
voro.addPoint( ofRandom( 700, 1200 ), 100 );
voro.addPoint( ofRandom( 1200, 1600 ), 100 );
voro.addPoint( ofRandom( 1600, 1920 ), 100 );
voro.addPoint( ofRandom( 100, 300 ), 1000 );
voro.addPoint( ofRandom( 300, 700 ), 1000 );
voro.addPoint( ofRandom( 700, 1200 ), 1000 );
voro.addPoint( ofRandom( 1200, 1600 ), 1000 );
voro.addPoint( ofRandom( 1600, 1920 ), 1000 );
voro.addPoint( 100, ofRandom( 100, 300 ) );
voro.addPoint( 100, ofRandom( 300, 800 ) );
voro.addPoint( 100, ofRandom( 800, 1100 ) );
voro.addPoint( 1800, ofRandom( 100, 300 ) );
voro.addPoint( 1800, ofRandom( 300, 800 ) );
voro.addPoint( 1800, ofRandom( 800, 1100 ) );
voro.setSmoothAmount( 15 );
voro.compute();
voro.render();
}
void GrowingBrushStokeAct::update() {
if( ofGetFrameNum() % 8 == 0 ) {
plainStone->grow( *voro.getLine( 0 ), ofVec2f( 1920 / 2, 1080 / 2 ) );
}
if( doScale ) {
updateScale();
}
}
void GrowingBrushStokeAct::updateSecondStone()
{
if( ofGetFrameNum() % 4 == 0 ) {
secondPlainStone->grow( *voro.getLine( 0 ), ofVec2f( 1920 / 2, 1080 / 2 ) );
}
}
void GrowingBrushStokeAct::updateScale()
{
scaleVal += 0.0015f;
scaleVal = std::min( scaleVal, 2.4f );
}
void GrowingBrushStokeAct::draw() {
tintBuffer.begin();
edgeDetectionPostProcessing->begin();
ofPushStyle();
ofPushMatrix();
ofTranslate( 1920 / 2, 1080 / 2, 0 );
float actualScale = scaleVal + 1.6;
ofScale( actualScale, actualScale );
plainStone->setSelectedColor( ofColor( 255, 197, 120 ) );
plainStone->setTransparency( 255 );
plainStone->draw( -1920 / 2, -1080 / 2, 1920, 1080 );
ofPopMatrix();
ofPopStyle();
edgeDetectionPostProcessing->end();
tintBuffer.end();
//whiteLinesBackground.draw( 0, 0 );
ofPushStyle();
ofSetColor( bigRockColor, transparency );
//ofSetColor( 255, transparency );
tintBuffer.draw( 0, 0 );
ofPopStyle();
//ofPushStyle();
//vectorField.animate( 0.008 );
//vectorField.draw( transparency - 50 );
//ofPopStyle();
}
void GrowingBrushStokeAct::drawSecondStone()
{
secondTintBuffer.begin();
secondEdgeDetectionPass->begin();
ofPushStyle();
ofPushMatrix();
ofTranslate( 1920 / 2, 1080 / 2, 0 );
float scaleSecondStone = 1.3;
ofScale( scaleSecondStone, scaleSecondStone );
secondPlainStone->setSelectedColor( ofColor( 255 ) );
secondPlainStone->setTransparency( 255 );
secondPlainStone->draw( -1920 / 2, -1080 / 2, 1920, 1080 );
ofPopMatrix();
ofPopStyle();
secondEdgeDetectionPass->end();
secondTintBuffer.end();
ofPushStyle();
ofSetColor( secondBigRockColor, secondPlainStoneTransparency );
secondTintBuffer.draw( 0, rockYpos );
secondTintBuffer.draw( 0, rockYpos - 1080 );
ofPopStyle();
}
void GrowingBrushStokeAct::keyPressed( int key )
{
if( key == 'g' ) {
// 0 means random brush
//plainStone.growPlain( growBrushIndex );
plainStone->grow( *voro.getLine( 0 ) );
}
else if( key == 'f' ) {
ofToggleFullscreen();
}
else if( key == 'j' ) {
doScale = !doScale;
}
else if( key == 'q' ) {
growBrushIndex++;
}
else if( key == 'w' ) {
growBrushIndex--;
}
else if( key == 'i' ) {
}
}
void GrowingBrushStokeAct::updateFourStones()
{
}
void GrowingBrushStokeAct::drawVoronoiWeb()
{
ofPushStyle();
ofSetColor( 255, 255 );
glLineWidth( 3 );
for( int i = 0; i < dottedPoints.size(); i++ ) {
//voro2.getLine( i )->draw();
Misc::drawSplitLines( dottedPoints.at( i ) );
}
ofPopStyle();
}
void GrowingBrushStokeAct::lowerScale()
{
scaleVal -= 0.01f;
scaleVal = std::max( scaleVal, 0.0f );
doDrawBackground = true;
}
void GrowingBrushStokeAct::updateRockYpos()
{
rockYpos += secondBigRockSpeed;
if( rockYpos >= 1080 ){
rockYpos = 0;
}
}
|
#include <stdio.h>
#
main(){
int M[3][3]={0};
int N[3][3]={0};
int elemento[3][3]={0};
int i,j, Op;
for(i=0; i<3; i++){
for (j=0; j<3; j++){
printf("\n Introduce la cifra [%d] [%d] para rellenar la matriz 1: ",i, j);
scanf("%d", &M[i][j]); }
}
for(i=0; i<3; i++){
for (j=0; j<3; j++){
printf("\n Introduce la cifra [%d] [%d] para rellenar la matriz 2: ",i, j);
scanf("%d", &N[i][j]); }
}
printf("\n Vamos a sumar las matrices: \n\n");
for(i=0; i<3; i++){
for (j=0; j<3; j++){
printf("%3d", N[i][j]);
}
printf("\n");
}
printf("\n +\n\n");
for(i=0; i<3; i++){ for (j=0; j<3; j++){
printf("%3d", M[i][j]);
}
printf("\n");
}
printf("\n =\n");
for(i=0; i<3; i++){
for (j=0; j<3; j++){
elemento[i][j]=M[i][j]+N[i][j];
}
}
for(i=0; i<3; i++){
for (j=0; j<3; j++){
printf("%3d",elemento[i][j]);
}
printf("\n");
}
printf("\n Vamos a restar las matrices: \n\n");
for(i=0; i<3; i++){
for (j=0; j<3; j++){
printf("%3d", N[i][j]);
}
printf("\n");
}
printf("\n -\n\n");
for(i=0; i<3; i++){ for (j=0; j<3; j++){
printf("%3d", M[i][j]);
}
printf("\n");
}
printf("\n =\n");
for(i=0; i<3; i++){
for (j=0; j<3; j++){
elemento[i][j]=M[i][j]-N[i][j];
}
}
for(i=0; i<3; i++){
for (j=0; j<3; j++){
printf("%3d",elemento[i][j]);
}
printf("\n");
printf("\n Ahora vamos a dividir las matrices: \n\n");
for(i=0; i<3; i++){
for (j=0; j<3; j++){
printf("%3d", N[i][j]);
}
printf("\n");
}
printf("\n Entre \n\n");
for(i=0; i<3; i++){ for (j=0; j<3; j++){
printf("%3d", M[i][j]);
}
printf("\n");
}
printf("\n =\n");
for(i=0; i<3; i++){
for (j=0; j<3; j++){
elemento[i][j]=M[i][j]/N[i][j];
}
}
for(i=0; i<3; i++){
for (j=0; j<3; j++){
printf("%3d",elemento[i][j]);
}
printf("\n");
}
}
}
|
#include "bitmap.h"
#include "window.h"
#include "actor.h"
#include "world.h"
#include "board_screen.h"
#include <lundi.hpp>
#include <fstream>
struct com_ensure_initialized {
com_ensure_initialized() { CoInitialize(0); }
~com_ensure_initialized() { CoUninitialize(); }
};
std::tuple<std::unique_ptr<world>, std::unique_ptr<std::vector<actor>>>
load_scenario(std::string const &path) {
std::ifstream file(path);
std::unique_ptr<world> myworld;
std::unique_ptr<std::vector<actor>> actors(new std::vector<actor>);
std::string assets_path = "assets/";
lua::state lua([&](std::string){});
lua.register_function("world", [&](std::string name){
myworld.reset(new world(assets_path + name));
return 0;
});
lua.register_function("actor", [&](int i_type, int player, int x, int y){
static unsigned int last_id = 1;
actor_type type = static_cast<actor_type>(i_type);
actor ac;
ac.type = type;
ac.coordinates.x = x;
ac.coordinates.y = y;
ac.player_id = player;
ac.id = last_id++;
actors->push_back(ac);
return 0;
});
lua["tank"] = actor_type_tank;
lua["assault"] = actor_type_assault;
lua["scanner"] = actor_type_scanner;
lua["scout"] = actor_type_scout;
lua.eval(file);
return std::make_tuple(std::move(myworld), std::move(actors));
}
int WINAPI WinMain(
HINSTANCE /*hInstance*/,
HINSTANCE /*hPrevInstance*/,
LPSTR /*lpCmdLine*/,
int /*nCmdShow*/
)
{
com_ensure_initialized com_initialize;
asset_library library;
library.load();
main_window::register_window();
main_window window;
library.bind(window.render_target);
std::unique_ptr<world> myworld;
std::unique_ptr<std::vector<actor>> actors;
std::tie(myworld, actors) = load_scenario("scripts/scenario.lua");
board_screen screen(library, *actors, *myworld);
window.screen = static_cast<view&>(screen);
window.show();
window.update();
HCURSOR cursor = bitmap(L"assets/sprites/AIRTRANS_0.png");
MSG msg;
do {
window.paint();
if(PeekMessageW(&msg, 0, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
SetCursor(cursor);
} while(msg.message != WM_QUIT);
return 0;
}
|
#ifndef REGISTERFUNCTIONS_H
#define REGISTERFUNCTIONS_H
#include <set>
#include <string>
#include <vector>
#include <functional>
#include "SusyAnaTools/Tools/GetVectors.h"
#include "SusyAnaTools/Tools/CleanedJets.h"
#include "SusyAnaTools/Tools/RunTopTagger.h"
#include "SusyAnaTools/Tools/TopWeightCalculator.h"
class NTupleReader;
class BaselineVessel;
class PDFUncertainty;
class BTagCorrector;
class ISRCorrector;
class Pileup_Sys;
namespace plotterFunctions
{
class GenerateWeight;
class GeneratePhotonEfficiency;
class LepInfo;
class BasicLepton;
class GetSearchBin;
class PrepareMiniTupleVars;
class NJetWeight;
class SystematicPrep;
class SystematicCalc;
class PrepareTopVars;
class Gamma;
class ShapeNJets;
}
class SystWeights;
class RegisterFunctions
{
private:
public:
RegisterFunctions() {}
virtual void registerFunctions(NTupleReader& tr) {};
virtual void activateBranches(std::set<std::string>& activeBranches) {};
virtual const std::set<std::string> getMiniTupleSet();
virtual const std::set<std::string> getMiniTupleSetData();
virtual void remakeBTagCorrector(std::string sampleName) {};
virtual void remakeISRreweight(std::string sampleName) {};
virtual void setupTopWeightCalculator(NTupleReader& tr) {};
virtual void setSampleName(std::string sampleName) {};
};
class RegisterFunctionsNTuple : public RegisterFunctions
{
private:
bool doSystematics_;
std::string year_;
std::string sampleName_;
BaselineVessel *myBLV;
BaselineVessel *myBLV_jetpt30;
BaselineVessel *myBLV_jetpt30_jesTotalUp;
BaselineVessel *myBLV_jetpt30_jesTotalDown;
BaselineVessel *myBLV_jetpt30_METUnClustUp;
BaselineVessel *myBLV_jetpt30_METUnClustDown;
BaselineVessel *blv_drLeptonCleaned_jetpt30;
BaselineVessel *blv_drLeptonCleaned_jetpt30_jesTotalUp;
BaselineVessel *blv_drLeptonCleaned_jetpt30_jesTotalDown;
BaselineVessel *blv_drPhotonCleaned_jetpt30;
BaselineVessel *blv_drPhotonCleaned_jetpt30_jesTotalUp;
BaselineVessel *blv_drPhotonCleaned_jetpt30_jesTotalDown;
GetVectors *getVectors;
CleanedJets *cleanedJets;
RunTopTagger *runTopTagger;
RunTopTagger *runTopTagger_jesTotalUp;
RunTopTagger *runTopTagger_jesTotalDown;
RunTopTagger *runTopTagger_drLeptonCleaned;
RunTopTagger *runTopTagger_drLeptonCleaned_jesTotalUp;
RunTopTagger *runTopTagger_drLeptonCleaned_jesTotalDown;
RunTopTagger *runTopTagger_drPhotonCleaned;
RunTopTagger *runTopTagger_drPhotonCleaned_jesTotalUp;
RunTopTagger *runTopTagger_drPhotonCleaned_jesTotalDown;
TopWeightCalculator *topWeightCalculator;
plotterFunctions::Gamma *gamma;
PDFUncertainty *myPDFUnc;
BTagCorrector *bTagCorrector;
ISRCorrector *ISRcorrector;
Pileup_Sys *pileup;
plotterFunctions::GenerateWeight *weights;
plotterFunctions::GeneratePhotonEfficiency *generatePhotonEfficiency;
plotterFunctions::NJetWeight *njWeight;
plotterFunctions::BasicLepton *basicLepton;
plotterFunctions::LepInfo *lepInfo;
plotterFunctions::GetSearchBin *getSearchBin;
plotterFunctions::GetSearchBin *getSearchBin_jesTotalUp;
plotterFunctions::GetSearchBin *getSearchBin_jesTotalDown;
plotterFunctions::GetSearchBin *getSearchBin_METUnClustUp;
plotterFunctions::GetSearchBin *getSearchBin_METUnClustDown;
plotterFunctions::GetSearchBin *getSearchBin_drPhotonCleaned;
plotterFunctions::GetSearchBin *getSearchBin_drPhotonCleaned_jesTotalUp;
plotterFunctions::GetSearchBin *getSearchBin_drPhotonCleaned_jesTotalDown;
plotterFunctions::PrepareMiniTupleVars *prepareMiniTupleVars;
plotterFunctions::SystematicPrep *systematicPrep;
plotterFunctions::SystematicCalc *systematicCalc;
plotterFunctions::ShapeNJets *shapeNJets;
public:
RegisterFunctionsNTuple(bool doSystematics, std::string sbEra, std::string year);
~RegisterFunctionsNTuple();
void registerFunctions(NTupleReader& tr);
void activateBranches(std::set<std::string>& activeBranches);
void remakeBTagCorrector(std::string sampleName);
void remakeISRreweight(std::string sampleName);
void setupTopWeightCalculator(NTupleReader& tr);
void setSampleName(std::string sampleName);
};
class RegisterFunctionsMiniTuple : public RegisterFunctions
{
private:
plotterFunctions::NJetWeight *njWeight;
plotterFunctions::PrepareMiniTupleVars *prepareMiniTupleVars;
public:
RegisterFunctionsMiniTuple();
~RegisterFunctionsMiniTuple();
void registerFunctions(NTupleReader& tr);
void activateBranches(std::set<std::string>& activeBranches);
};
class RegisterFunctionsCalcEff : public RegisterFunctions
{
private:
BaselineVessel *myBLV;
GetVectors *getVectors;
CleanedJets *cleanedJets;
RunTopTagger *runTopTagger;
plotterFunctions::Gamma *gamma;
plotterFunctions::BasicLepton *basicLepton;
plotterFunctions::GeneratePhotonEfficiency *generatePhotonEfficiency;
public:
RegisterFunctionsCalcEff();
~RegisterFunctionsCalcEff();
void registerFunctions(NTupleReader& tr);
void activateBranches(std::set<std::string>& activeBranches);
};
class RegisterFunctionsSyst : public RegisterFunctions
{
private:
std::vector<std::function<void(NTupleReader&)> > funcs_;
plotterFunctions::PrepareMiniTupleVars *prepareMiniTupleVars;
plotterFunctions::NJetWeight *njWeight;
SystWeights *systWeights;
public:
RegisterFunctionsSyst();
~RegisterFunctionsSyst();
void addFunction(std::function<void(NTupleReader&)> func);
void registerFunctions(NTupleReader& tr);
};
class RegisterFunctions2Dplot : public RegisterFunctions
{
private:
plotterFunctions::PrepareMiniTupleVars *prepareMiniTupleVars;
public:
RegisterFunctions2Dplot();
~RegisterFunctions2Dplot();
void registerFunctions(NTupleReader& tr);
};
class RegisterFunctionsTopStudy : public RegisterFunctions
{
private:
BaselineVessel *myBLV;
plotterFunctions::PrepareTopVars *prepareTopVars;
public:
RegisterFunctionsTopStudy();
~RegisterFunctionsTopStudy();
void registerFunctions(NTupleReader& tr);
};
void drawSBregionDefCopy(const double ymin_Yields = 0.05, const double ymax_Yields = 500., const bool logscale = true);
#endif
|
//使用するヘッダーファイル
#include "GameL\DrawTexture.h"
#include "GameL\HitBoxManager.h"
#include "GameL\Audio.h"
#include "GameL\WinInputs.h"
#include "GameHead.h"
#include "CObjHeroSword.h"
#include "CObjHero.h"
//使用するネームスペース
using namespace GameL;
//コンストラクタ
CObjHeroSword::CObjHeroSword(float x, float y)
{
m_x = x;
m_y = y;
}
//イニシャライズ
void CObjHeroSword::Init()
{
m_vx = 0.0f;
m_vy = 0.0f;
m_hero_x = 0.0f;
m_hero_y = 0.0f;
m_posture = 0.0f; //右向き0.0f 左向き1.0f
//blockとの衝突状態確認
m_hit_left = false;
m_hit_right = false;
m_hit = false;
//主人公の位向きを取得
CObjHero* hero = (CObjHero*)Objs::GetObj(COBJ_HERO);
m_posture = hero->GetPOS();
m_ani_frame_x = 0; //ソードのアニメーション用
m_ani_frame_y = 0;
m_time = 0; //ソードが消える時間
m_sword_time = 10; //剣が消える時間
//当たり判定用HitBoxを作成
Hits::SetHitBox(this, m_x + 25, m_y, 50, 50, ELEMENT_ATTACK, OBJ_SWORD, 1);
}
//アクション
void CObjHeroSword::Action()
{
CObjHero* hero = (CObjHero*)Objs::GetObj(COBJ_HERO);
m_hero_x = hero->GetX();
m_hero_y = hero->GetY();
if (m_hit_left == true) //左
m_hit = true;
if (m_hit_right == true)//右
m_hit = true;
if (m_posture == 0.0f) {
m_ani_frame_y = 0;
}
if (m_posture == 1.0f) {
m_ani_frame_y = 1;
}
if (m_posture == 0.0f)
m_x = m_hero_x + 55;
else
m_x = m_hero_x - 35;
m_y = m_hero_y ;
//HitBox更新用ポインター取得
CHitBox* hit = Hits::GetHitBox(this);
hit->SetPos(m_x, m_y);
//敵と接触したら剣削除
if (hit->CheckElementHit(ELEMENT_ENEMY) == true)
{
//this->SetStatus(false);
//Hits::DeleteHitBox(this);
hit->SetInvincibility(true);
}
//壁に当たったら消える処理
if (m_hit == true) {
this->SetStatus(false);
Hits::DeleteHitBox(this);
}
//一定の時間で消える処理
if (m_sword_time > 0) {
m_sword_time--;
if (m_sword_time <= 0) {
this->SetStatus(false);
Hits::DeleteHitBox(this);
}
}
if (m_sword_time == 9) {
m_ani_frame_x = 0;
}
else if (m_sword_time == 6) {
m_ani_frame_x = 1;
}
else if (m_sword_time == 3) {
m_ani_frame_x = 2;
}
}
//ドロー
void CObjHeroSword::Draw()
{
//描画カラー情報 R=RED G=Green B=Blue A=alpha(透過情報)
float c[4] = { 1.0f,1.0f,1.0f,1.0f };
RECT_F src; //描画元切り取り位置
RECT_F dst; //描画先表示位置
//切り取り位置の設定
src.m_top = 0.0f + (64.0f * m_ani_frame_y);
src.m_left = 0.0f + (64.0f * m_ani_frame_x);
src.m_right = 64.0f + (64.0f * m_ani_frame_x);
src.m_bottom = 64.0f + (64.0f * m_ani_frame_y);
//表示位置の設定
dst.m_top = 0.0f + m_y;
dst.m_left = 0.0f + m_x;
dst.m_right = 50.0f + m_x;
dst.m_bottom = 50.0f + m_y;
Draw::Draw(16, &src, &dst, c, 0.0f);
}
|
//$$---- Form CPP ----
//---------------------------------------------------------------------------
#include <vcl.h>
#include <stdio.h>
#pragma hdrstop
#include "MainForm.h"
#include "BuildProtocol.h"
#include "PredStart.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TProtoBuild *ProtoBuild;
//---------------------------------------------------------------------------
__fastcall SPPanel::SPPanel(TComponent* Owner) : TPanel(Owner)
{
}
//---------------------------------------------------------------------------
__fastcall TProtoBuild::TProtoBuild(TComponent* Owner) : TForm(Owner)
{
//виды инструкций: 1 - тип инструкции (1 - стимуляция, 2 - пауза, 3 - цикл)
//2 - кол-во стимулов или повторений в цикле, 3 - длительность паузы или период стимуляции
//InstructBox->ComponentCount - количество блоков (компонентов)
//ProtoBuild->LoadProtocolClick(this);
//ProtoBuild->Width = InstructBox->Left + InstructBox->Width;//уменьшаем ширину окна
//ProtoBuild->Periods->Tag - наименьший период между импульсами стимуляции
}
//---------------------------------------------------------------------------
void __fastcall TProtoBuild::StimBlockClick(TObject *Sender)
{
//задание блока стимуляции
__int32 stimPrd,
stimNums;
StimsNum->Visible = !StimsNum->Visible;
Periods->Visible = !Periods->Visible;
Label1->Visible = !Label1->Visible;
//инактивируем кнопки
Silence->Enabled = false;
Repeat->Enabled = false;
DelLast->Enabled = false;
if (!StimsNum->Visible)
{
//проверяем значение на корректность
stimPrd = StrToInt(Periods->Text);
if (stimPrd < 5)//нижний предел периода стимуляции = 5 мс
{
stimPrd = 5;
Periods->Text = IntToStr(stimPrd);
}
if (stimPrd > 1e7)//верхний предел периода стимуляции = 1e7 мс (или 10000 с)
{
stimPrd = 1e7;
Periods->Text = IntToStr(stimPrd);
}
stimNums = StrToInt(StimsNum->Text);
if (stimNums < 1)
{
stimNums = 1;
StimsNum->Text = IntToStr(stimNums);
}
StimCreat(stimNums, stimPrd);//заносим в протокол блок стимуляции
//восстанавливаем кнопки
Silence->Enabled = true;
Repeat->Enabled = true;
DelLast->Enabled = true;
}
}
//---------------------------------------------------------------------------
void TProtoBuild::StimCreat(__int32 stimNums, __int32 stimPrd)
{
//заносим в протокол блок стимуляции
/*
stimNums - количество стимулов
stimPrd - период следования стимулов
*/
SPPanel *panel,
*leftPanel;
panel = new SPPanel(InstructBox);//создаём новый блок (инструкцию)
panel->Parent = InstructBox;//указываем родителя
panel->Caption = "Стим: " + IntToStr(stimNums) + "(имп), " + IntToStr(stimPrd) + "(мс)";
if (InstructBox->ComponentCount > 1)
{
leftPanel = (SPPanel*)InstructBox->Components[InstructBox->ComponentCount - 2];//предыдущий блок
panel->Left = leftPanel->Left + leftPanel->Width;
}
else
panel->Left = 0;
panel->Width = 10 + 5 * panel->Caption.Length();
panel->Visible = true;
panel->iType = 1;//тип инструкции (стимуляция)
panel->scCount = stimNums;//количество импульсов
panel->period = stimPrd;//период следования импульсов
}
//---------------------------------------------------------------------------
void __fastcall TProtoBuild::SilenceClick(TObject *Sender)
{
//задаём период ожидания
//желательно, чтобы пауза была более 100 мс, т.к. каждый старт
// непрерывного сбора создаёт задержку
__int32 prd;
Periods->Visible = !Periods->Visible;
Label2->Visible = !Label2->Visible;
//инактивируем кнопки
StimBlock->Enabled = false;
Repeat->Enabled = false;
DelLast->Enabled = false;
if (!Periods->Visible)
{
//проверяем значение на корректность
prd = StrToInt(Periods->Text);
if (prd < 5)
{
prd = 5;
Periods->Text = IntToStr(prd);
}
SilenceCreat(prd);//заносим в протокол ожидание
//восстанавливаем кнопки
StimBlock->Enabled = true;
Repeat->Enabled = true;
DelLast->Enabled = true;
}
}
//---------------------------------------------------------------------------
void TProtoBuild::SilenceCreat(__int32 prd)
{
//заносим в протокол ожидание
/*
prd - длительность паузы
*/
SPPanel *panel,
*leftPanel;
panel = new SPPanel(InstructBox);
panel->Parent = InstructBox;
panel->Caption = "Пауза: " + IntToStr(prd) + "(мс)";
if (InstructBox->ComponentCount > 1)
{
leftPanel = (SPPanel*)InstructBox->Components[InstructBox->ComponentCount - 2];//предыдущий блок
panel->Left = leftPanel->Left + leftPanel->Width;
}
else
panel->Left = 0;
panel->Width = 10 + 5 * panel->Caption.Length();
panel->Visible = true;
panel->iType = 2;//тип инструкции (пауза)
panel->period = prd;//период ожидания
panel->scCount = prd;//дублируем значение
}
//---------------------------------------------------------------------------
void __fastcall TProtoBuild::RepeatClick(TObject *Sender)
{
//задаём количество повторов сценария
__int32 reps;
repeats->Visible = !repeats->Visible;
Label3->Visible = !Label3->Visible;
Label4->Visible = !Label4->Visible;
//инактивируем кнопки
StimBlock->Enabled = false;
Silence->Enabled = false;
DelLast->Enabled = false;
if (!repeats->Visible)
{
//проверяем значение на корректность
reps = StrToInt(repeats->Text);
if (reps < 1)
{
reps = 1;
repeats->Text = IntToStr(reps);
}
RepeatCreat(reps);//заносим в протокол цикл
//восстанавливаем кнопки
StimBlock->Enabled = true;
Silence->Enabled = true;
DelLast->Enabled = true;
}
}
//---------------------------------------------------------------------------
void TProtoBuild::RepeatCreat(__int32 reps)
{
//заносим в протокол цикл
/*
reps - количество проходов в цикле
*/
SPPanel *panel,
*leftPanel;
panel = new SPPanel(InstructBox);
panel->Parent = InstructBox;
panel->Caption = "Цикл: " + IntToStr(reps) + "(повторы)";
if (InstructBox->ComponentCount > 1)
{
leftPanel = (SPPanel*)InstructBox->Components[InstructBox->ComponentCount - 2];//предыдущий блок
panel->Left = leftPanel->Left + leftPanel->Width;
}
else
panel->Left = 0;
panel->Width = 17 + 5 * panel->Caption.Length();
panel->Visible = true;
panel->iType = 3;//тип инструкция (цикл)
panel->scCount = reps;//количество повторов
panel->period = reps;//дублируем значение
}
//---------------------------------------------------------------------------
void __fastcall TProtoBuild::DelLastClick(TObject *Sender)
{
//отмена последнего действия по установке блока
if (InstructBox->ComponentCount > 0)
{
//InstructBox->RemoveComponent(InstructBox->Components[InstructBox->ComponentCount - 1]);
InstructBox->Controls[InstructBox->ComponentCount - 1]->Free();//удаляем панель-блок (вместо delete)
}
}
//---------------------------------------------------------------------------
void __fastcall TProtoBuild::CancelAllClick(TObject *Sender)
{
//отменяем весь протокол
while (InstructBox->ComponentCount > 0)
DelLastClick(this);
}
//---------------------------------------------------------------------------
void __fastcall TProtoBuild::EndOfProtoBuild(TObject *Sender)
{
//выполняется при закрытии
//применяем заданный протокол стимуляции
//нужно проверить не превышает ли длина сигнала минимальный период в протоколе
__int32 i;
SPPanel *panel;
//сигнализируем о наличии или отсутствии протокола
if (InstructBox->ComponentCount >= 1)//протокол вступил в силу
{
Experiment->SetScenar->Caption = "Редактировать";
Experiment->NumOfsignals->Enabled = false;//выбор количества сигналов
Experiment->nsLbl1->Enabled = false;//количество сигналов (лэйбл 1)
Experiment->nsLbl2->Enabled = false;//количество сигналов (лэйбл 2)
Experiment->StimFreq->Enabled = false;//выбор частоты стимуляции
Experiment->StimPeriod->Enabled = false;//выбор периода стимуляцц
Experiment->stimLbl1->Enabled = false;//стимуляция (лэйбл 1)
Experiment->stimLbl2->Enabled = false;//стимуляция (лэйбл 2)
Experiment->stimLbl3->Enabled = false;//стимуляция (лэйбл 3)
Experiment->stimLbl4->Enabled = false;//стимуляция (лэйбл 4)
//выбираем наименьший интервал между импульсами в данном протоколе
for (i = 0; i < InstructBox->ComponentCount; i++)
{
panel = (SPPanel*)InstructBox->Components[i];
if (((panel->iType == 1) || (panel->iType == 2)) && (panel->period < Periods->Tag))
Periods->Tag = panel->period;//наименьший период между импульсами стимуляции
}
PStart->NextBlock->Visible = true;//кнопка перехода к следующему блоку стимуляции
}
else//протокол отменён
{
Experiment->SetScenar->Caption = "Задать стимуляцию";
Experiment->NumOfsignals->Enabled = true;//выбор количества сигналов
Experiment->nsLbl1->Enabled = true;//количество сигналов (лэйбл 1)
Experiment->nsLbl2->Enabled = true;//количество сигналов (лэйбл 2)
Experiment->StimFreq->Enabled = true;//выбор частоты стимуляции
Experiment->StimPeriod->Enabled = true;//выбор периода стимуляцц
Experiment->stimLbl1->Enabled = true;//стимуляция (лэйбл 1)
Experiment->stimLbl2->Enabled = true;//стимуляция (лэйбл 2)
Experiment->stimLbl3->Enabled = true;//стимуляция (лэйбл 3)
Experiment->stimLbl4->Enabled = true;//стимуляция (лэйбл 4)
Periods->Tag = StrToInt(Experiment->StimPeriod->Text);//наименьший период между импульсами стимуляции
PStart->NextBlock->Visible = false;//кнопка перехода к следующему блоку стимуляции
}
}
//---------------------------------------------------------------------------
void __fastcall TProtoBuild::CloseClicked(TObject *Sender)
{
//закрываем редактор протокола
ProtoBuild->Close();
}
//---------------------------------------------------------------------------
void __fastcall TProtoBuild::SaveProtocolClick(TObject *Sender)
{
//сохраняем протокл в указанный файл
FILE *stream;
__int32 i;
SPPanel *panel;
if (SaveDialog1->Execute())
{
//*.spf (s - stimulation, p - protocol, f - file)
stream = fopen(SaveDialog1->FileName.c_str(), "w");
for (i = 0; i < InstructBox->ComponentCount; i++)
{
panel = (SPPanel*)InstructBox->Components[i];
fprintf(stream, "%d\t%d\t%d\n", panel->iType, panel->scCount, panel->period);
}
fclose(stream);
}
}
//---------------------------------------------------------------------------
void __fastcall TProtoBuild::LoadProtocolClick(TObject *Sender)
{
//загрузить протокол из указанного файла
FILE *stream;
__int32 d1, d2, d3;
if (OpenDialog1->Execute())
{
//специализированный файл настроек *.spf (s - stimulation, p - protocol, f - file)
stream = fopen(OpenDialog1->FileName.c_str(), "r");
CancelAllClick(this);//отменить пердыдущие команды
while (fscanf(stream, "%d%d%d", &d1, &d2, &d3) != EOF)
{
//d[0] - тип инструкции, d[1] - количество, d[2] - длительность
if (d1 == 1)//стимуляция
StimCreat(d2, d3);//заносим в протокол блок стимуляции
else if (d1 == 2)//пауза
SilenceCreat(d3);//заносим в протокол пауза
else if (d1 == 3)//цикл
RepeatCreat(d2);//заносим в протокол цикл
else
{
CancelAllClick(this);//отменить пердыдущие команды
Experiment->DevEvents->Text = "ошибка чтения протокола";
break;//ошибка чтения
}
}
fclose(stream);
}
}
//---------------------------------------------------------------------------
void __fastcall TProtoBuild::CheckForKeyOtherEdits(TObject *Sender, char &Key)
{
//проверка допустимости введения символа, соответствующего нажатой клавише
//для остальных полей ввода числовых данных
if (((Key < '0') || (Key > '9')) && (Key != '\b'))//проверим допустимость введённых символов
Key = '\0';//зануляем некорректный символ
}
//---------------------------------------------------------------------------
void __fastcall TProtoBuild::StarTimClick(TObject *Sender)
{
//выбор времени старта по часам компьютера
if (StarTim->Checked)//выбрано задание времени
{
ProtoBuild->Width = STLbl->Left + STLbl->Width + 12;//увеличиваем ширину окна
}
else//отмена момента старта
{
ProtoBuild->Width = DelLast->Left + DelLast->Width + 12;//уменьшаем ширину окна
}
}
//---------------------------------------------------------------------------
void __fastcall TProtoBuild::UpDownClick(TObject *Sender, TUDBtnType Button)
{
TUpDown *objUpDwn;//объект "кнопки вверх-вниз"
TEdit *objEdit;//объект "окно с текстом"
objUpDwn = (TUpDown*)Sender;//объект "кнопки вверх-вниз"
if (objUpDwn->Tag == 0)//часы
objEdit = HEdit;//объект "окно с текстом"
else if (objUpDwn->Tag == 1)//минуты
objEdit = MEdit;//объект "окно с текстом"
else if (objUpDwn->Tag == 2)//секунды
objEdit = SEdit;//объект "окно с текстом"
objEdit->Text = IntToStr(objUpDwn->Position);//изменение времени
}
//---------------------------------------------------------------------------
void __fastcall TProtoBuild::EditChange(TObject *Sender)
{
__int32 i;
TEdit *objEdit;//объект "окно с текстом"
TUpDown *objUpDwn;//объект "кнопки вверх-вниз"
objEdit = (TEdit*)Sender;//объект "окно с текстом"
i = StrToInt(objEdit->Text);//введённое время
if (objEdit->Tag == 0)//часы
objUpDwn = HUpDown;//объект "кнопки вверх-вниз"
else if (objEdit->Tag == 1)//минуты
objUpDwn = MUpDown;//объект "кнопки вверх-вниз"
else if (objEdit->Tag == 2)//секунды
objUpDwn = SUpDown;//объект "кнопки вверх-вниз"
if ((i > 0) && (i <= objUpDwn->Max))
objUpDwn->Position = i;//изменение времени
else
objEdit->Text = IntToStr(objUpDwn->Position);//возвращаем исходное значение
}
//---------------------------------------------------------------------------
|
#include <iostream>
int main()
{
int new_grade, index, limit_1, limit_2, freq[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
// The exception definition to deal with the end of the data
class NegativeInputException {
public:
NegativeInputException() {
std::cout << "End of input data reached\n";
}
};
try {
while (true) {
std::cout << "Please input a grade\n";
std::cin>>new_grade;
if (new_grade < 0)
throw NegativeInputException();
index = new_grade / 10;
try {
if (index > 9)
throw new_grade;
freq[index]++;
} // end of inner try
catch (int grade) {
if (grade == 100)
freq[9]++;
else
std::cout << "Error -- new grade:" << grade << " is out of range [1, 100]\n";
} // end of inner catch
} // end of while
} // end of outer try
catch (NegativeInputException e) {
std::cout << " Limits Frequency\n";
for (index = 0; index < 10; index++) {
limit_1 = 10 * index;
limit_2 = limit_1 + 9;
if (index == 9) {
limit_2 = 100;
} // end of if
std::cout << limit_1 <<"-" << limit_2 <<" " << freq[index] << "\n";
} // end of for
} // end of catch NegativeInputException
// DOES C++ sppport finally blocks?
// No, C++ does not support 'finally' blocks.
} // end of main
|
#include <iostream>
#include<string.h>
using namespace std;
class Stack
{
public:
int top;
unsigned capacity;
char* array;
};
Stack* createStack(unsigned capacity)
{
Stack* stack = new Stack();
stack->capacity = capacity;
stack->top = -1;
stack->array = new char[(stack->capacity * sizeof(char))];
return stack;
}
void push(Stack* stack, char item)
{
stack->array[++stack->top] = item;
}
char pop(Stack* stack)
{
return stack->array[stack->top--];
}
void reverse(char str[])
{
int n = strlen(str);
Stack* stack = createStack(n);
int i;
for (i = 0; i < n; i++)
push(stack, str[i]);
for (i = 0; i < n; i++)
str[i] = pop(stack);
}
int main()
{
char str[10];
for (int i = 0; i < 10; i++)
{
cin>>str[i];
}
reverse(str);
cout <<str;
return 0;
}
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Animal
{
public:
virtual void speak()//虚函数
{
cout << "动物在说话" << endl;
}
};
class Dog:public Animal
{
public:
//重写虚函数 函数的返回值 参数 函数名一致
void speak()
{
cout << "狗在说话" << endl;
}
};
class Cat : public Animal
{
public:
void speak()
{
cout << "猫在说话" << endl;
}
};
//如果两个类发生了继承,父类和子类编译器会自动转换,不需要人为转换
void do_work(Animal &obj)
{
obj.speak();//地址早绑定 ----函数前面加上virtual关键字-->>>地址晚绑定
}
void test01()
{
Animal p1;
do_work(p1);
Dog p2;
do_work(p2);
Cat p3;
do_work(p3);
}
int main(int argc, char **argv)
{
test01();
return 0;
}
|
#ifndef ss_math_Vector3_H_
#define ss_math_Vector3_H_
#include "ssPrerequisities.h"
namespace ssMath
{
class Vector3
{
public:
// constructors
inline explicit Vector3()
: x(0), y(0), z(0)
{
}
inline explicit Vector3(float _x, float _y, float _z)
: x(_x), y(_y), z(_z)
{
}
inline explicit Vector3(float scalar)
: x(scalar), y(scalar), z(scalar)
{
}
inline explicit Vector3(float *const r)
: x(r[0]), y(r[1]), z(r[2])
{
}
inline explicit Vector3(const float coord[3])
: x(coord[0]), y(coord[1]), z(coord[2])
{
}
inline explicit Vector3(const int coord[3])
{
x = (float)coord[0];
y = (float)coord[1];
z = (float)coord[2];
}
// copy constructor
inline Vector3(const Vector3 &vec)
{
x = vec.x;
y = vec.y;
z = vec.z;
}
// operator override
inline Vector3 &operator=(const Vector3 &v)
{
x = v.x;
y = v.y;
z = v.z;
return *this;
}
inline Vector3& operator = ( const float fScaler )
{
x = fScaler;
y = fScaler;
z = fScaler;
return *this;
}
inline friend Vector3 operator+(const Vector3 &lhs,const Vector3 &rhs)
{
return Vector3(lhs.x + rhs.x,
lhs.y + rhs.y,
lhs.z + rhs.z);
}
// inline Vector3 operator+(const Vector3 &v) const
// {
// return Vector3(x + v.x, y + v.y, z + v.z);
// }
inline Vector3& operator+=(const Vector3 &v)
{
x += v.x; y += v.y; z += v.z;
return *this;
}
inline friend Vector3 operator-(const Vector3 &lhs,const Vector3 &rhs)
{
return Vector3(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z);
}
// inline Vector3 operator-(const Vector3 &v) const
// {
// return Vector3(x - v.x, y - v.y, z - v.z);
// }
inline Vector3& operator-=(const Vector3 &v)
{
x -= v.x; y -= v.y; z -= v.z;
return *this;
}
inline friend Vector3 operator*(const Vector3 &lhs,const Vector3 &rhs)
{
return Vector3(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z);
}
inline friend Vector3 operator*(const Vector3 &lhs,float f)
{
return Vector3(lhs.x * f, lhs.y * f, lhs.z * f);
}
inline friend Vector3 operator*(float f,const Vector3 &rhs)
{
return rhs*f;
}
inline Vector3 &operator*=(float f)
{
x *= f; y *= f; z *= f;
return *this;
}
inline Vector3 &operator*=(const Vector3 &rhs)
{
x *= rhs.x;
y *= rhs.y;
z *= rhs.z;
return *this;
}
inline Vector3 operator/(float f) const
{
float inv = 1.f / f;
return Vector3(x * inv, y * inv, z * inv);
}
inline Vector3 &operator/=(float f)
{
float inv = 1.f / f;
x *= inv; y *= inv; z *= inv;
return *this;
}
inline Vector3 operator-() const
{
return Vector3(-x, -y, -z);
}
// logic operation
inline bool operator < ( const Vector3& rhs ) const
{
if( x < rhs.x && y < rhs.y && z < rhs.z )
return true;
return false;
}
inline bool operator > ( const Vector3& rhs ) const
{
if( x > rhs.x && y > rhs.y && z > rhs.z )
return true;
return false;
}
inline bool operator == ( const Vector3& rkVector ) const
{
return ( x == rkVector.x && y == rkVector.y && z == rkVector.z );
}
inline bool operator != ( const Vector3& rkVector ) const
{
return ( x != rkVector.x || y != rkVector.y || z != rkVector.z );
}
// exchange content with another vector
inline void swap(Vector3& other)
{
std::swap(x, other.x);
std::swap(y, other.y);
std::swap(z, other.z);
}
inline float* ptr()
{
return &x;
}
inline const float* ptr()const
{
return &x;
}
inline float distance(const Vector3 &v )
{
return (*this - v).length();
}
inline float distSquared(const Vector3 &v)
{
return (*this - v).squaredLength();
}
inline float dotProduct(const Vector3& vec) const
{
return x * vec.x + y * vec.y + z * vec.z;
}
inline float absDotProduct(const Vector3 &vec) const
{
return abs(x *vec.x) + abs(y *vec.y) + abs(z* vec.z);
}
inline float normalize()
{
float flen = length();
if(flen > 1e-6)
{
float invlen = 1.0f/flen;
x *= invlen;
y *= invlen;
z *= invlen;
}
return flen;
}
/** Sets this vector's components to the minimum of its own and the
ones of the passed in vector.
@remarks
'Minimum' in this case means the combination of the lowest
value of x, y and z from both vectors. Lowest is taken just
numerically, not magnitude, so -1 < 0.
*/
inline void makeFloor( const Vector3& cmp )
{
if( cmp.x < x ) x = cmp.x;
if( cmp.y < y ) y = cmp.y;
if( cmp.z < z ) z = cmp.z;
}
/** Sets this vector's components to the maximum of its own and the
ones of the passed in vector.
@remarks
'Maximum' in this case means the combination of the highest
value of x, y and z from both vectors. Highest is taken just
numerically, not magnitude, so 1 > -3.
*/
inline void makeCeil( const Vector3& cmp )
{
if( cmp.x > x ) x = cmp.x;
if( cmp.y > y ) y = cmp.y;
if( cmp.z > z ) z = cmp.z;
}
/** Generates a vector perpendicular to this vector (eg an 'up' vector).
@remarks
This method will return a vector which is perpendicular to this
vector. There are an infinite number of possibilities but this
method will guarantee to generate one of them. If you need more
control you should use the Quaternion class.
*/
inline Vector3 perpendicular(void) const
{
static const float fSquareZero = (float)(1e-06 * 1e-06);
Vector3 perp = this->crossProduct( Vector3::UNIT_X );
// Check length
if( perp.squaredLength() < fSquareZero )
{
/* This vector is the Y axis multiplied by a scalar, so we have
to use another axis.
*/
perp = this->crossProduct( Vector3::UNIT_Y );
}
perp.normalize();
return perp;
}
/** Gets the angle between 2 vectors.
@remarks
Vectors do not have to be unit-length but must represent directions.
Angle unit is radian.
*/
inline float angleBetween(const Vector3& dest)
{
float lenProduct = length() * dest.length();
// Divide by zero check
if(lenProduct < 1e-6f)
lenProduct = 1e-6f;
float f = dotProduct(dest) / lenProduct;
f = ss_fast_Clamp(f, float(-1.0), (float)1.0);
return acos(f);
}
/** Returns true if this vector is zero length. */
inline bool isZeroLength(void) const
{
float sqlen = (x * x) + (y * y) + (z * z);
return (sqlen < (1e-06 * 1e-06));
}
inline Vector3 crossProduct( const Vector3& rkVector ) const
{
return Vector3(
y * rkVector.z - z * rkVector.y,
z * rkVector.x - x * rkVector.z,
x * rkVector.y - y * rkVector.x);
}
/** Calculates a reflection vector to the plane with the given normal .
@remarks NB assumes 'this' is pointing AWAY FROM the plane, invert if it is not.
*/
inline Vector3 reflect(const Vector3& normal) const
{
return Vector3( *this - ( normal*2 * this->dotProduct(normal) ) );
}
/** Returns whether this vector is within a positional tolerance
of another vector.
@param rhs The vector to compare with
@param tolerance The amount that each element of the vector may vary by
and still be considered equal
*/
inline bool positionEquals(const Vector3& rhs, float tolerance = 1e-03) const
{
if( fabs(x-rhs.x) > tolerance)
return false;
if( fabs(y-rhs.y) > tolerance)
return false;
if( fabs(z-rhs.z) > tolerance)
return false;
return true;
}
/** Returns whether this vector is within a directional tolerance
of another vector.
@param rhs The vector to compare with
@param tolerance The maximum angle by which the vectors may vary and
still be considered equal
@note Both vectors should be normalised.
*/
inline bool directionEquals(const Vector3& rhs,
float tolerance) const
{
float dot = dotProduct(rhs);
float angle = acos(dot);
return abs(angle) <= tolerance;
}
inline Vector3 midPoint( const Vector3& vec ) const
{
return Vector3(
( x + vec.x ) * 0.5f,
( y + vec.y ) * 0.5f,
( z + vec.z ) * 0.5f );
}
// extract element
inline float operator[](int i) const { return (&x)[i]; }
inline float &operator[](int i) { return (&x)[i]; }
// square length
inline float squaredLength() const { return x*x + y*y + z*z; }
inline float length() const { return sqrtf( squaredLength() ); }
inline Vector3 hat() const { return (*this)*ss_fast_InvSqrt(squaredLength());}//return (*this)/len(); }
// Vector3 Public Data
float x, y, z;
// static members for convenience
static const Vector3 ZERO; // (0,0,0)
static const Vector3 UNIT_X;
static const Vector3 UNIT_Y;
static const Vector3 UNIT_Z;
static const Vector3 NEGATIVE_UNIT_X;
static const Vector3 NEGATIVE_UNIT_Y;
static const Vector3 NEGATIVE_UNIT_Z;
static const Vector3 UNIT_SCALE; // (1,1,1)
};
}
#endif
|
/*************************************************************************
> File Name: demo.cpp
> Author: billowqiu
> Mail: billowqiu@billowqiu.com
> Created Time: 2017-05-22 14:14:52
> Last Changed: 2017-05-22 14:14:52
*************************************************************************/
#include "ThostFtdcMdApi.h"
#include "ThostFtdcTraderApi.h"
#include <stdint.h>
#include <string.h>
#include <iostream>
#include <thread>
#include <iterator>
#include <unistd.h>
#include <fstream>
#include "util/tc_encoder.h"
#include "util/tc_common.h"
#include <unordered_map>
#include <set>
#include <mutex>
#include <typeinfo>
#include <condition_variable>
#include "util/tc_logger.h"
//#include "DataPersistence.h"
using namespace taf;
CThostFtdcTraderApi* traderapi = nullptr;
int requestid = 0;
//合约ID=>合约信息
typedef std::unordered_map<std::string, CThostFtdcInstrumentField> InstrumentMap;
InstrumentMap instruments_map;
bool instruments_pulled = false;
bool subscribe_all_instrument = false;
//指定订阅的合约
typedef std::vector<std::string> InstrumentVec;
InstrumentVec instruments_vec;
//交易所=>产品代码
typedef std::unordered_map<std::string, std::set<std::string>> Exchange2ProductIDMap;
Exchange2ProductIDMap exchange2productid_map;
//实际收到ctp订阅回应的合约id
std::vector<std::string> recv_sub_rsp_instrument;
std::set<std::string> recv_sub_rsp_instrument_set;
std::ofstream exchange_file("exchange_info", ios::binary);
taf::TC_RollLogger logger;
#define LOG_DEBUG logger.debug() << __LINE__ << "-" << std::this_thread::get_id() << "-"
int32_t SerializeToString(const CThostFtdcInstrumentField& instrument, std::string* output);
std::ostream& operator<<(std::ostream& os, const CThostFtdcRspUserLoginField& data)
{
os << data.TradingDay << '\n'
<< data.SystemName << '\n'
<< data.FrontID << '\n'
<< data.SessionID << '\n';
}
std::ostream& operator<<(std::ostream& os, const CThostFtdcDepthMarketDataField& data)
{
os << "交易日:" << data.TradingDay << '|'
<< "合约代码:" << data.InstrumentID << '|'
<< "交易所代码:" << data.ExchangeID << '|'
<< "合约在交易所代码:" << data.ExchangeInstID << '|'
<< "最新价:" << data.LastPrice << '|'
<< "上次结算价:" << data.PreSettlementPrice << '|'
<< "昨收盘:" << data.PreClosePrice << '|'
<< "昨持仓量:" << data.PreOpenInterest << '|'
<< "今开盘:" << data.OpenPrice << '|'
<< "最高价:" << data.HighestPrice << '|'
<< "最低价:" << data.LowestPrice << '|'
<< "数量:" << data.Volume << '|'
<< "成交金额:" << data.Turnover << '|'
<< "持仓量:" << data.OpenInterest << '|'
<< "今收盘:" << data.ClosePrice << '|'
<< "本次结算价:" << data.SettlementPrice << '|'
<< "跌停板价:" << data.LowerLimitPrice << '|'
<< "涨停板价:" << data.UpperLimitPrice << '|'
<< "昨虚实度:" << data.PreDelta << "|"
<< "今虚实度:" << data.CurrDelta << "|"
<< "最后修改时间:" << data.UpdateTime << "|"
<< "最后修改时间(MS):" << data.UpdateMillisec << "|"
<< "申买价1:" << data.BidPrice1 << "|"
<< "申买量1:" << data.BidVolume1 << "|"
<< "申卖价1:" << data.AskPrice1 << "|"
<< "申卖量1:" << data.AskVolume1 << "|"
<< "申买价2:" << data.BidPrice2 << "|"
<< "申买量2:" << data.BidVolume2 << "|"
<< "申卖价2:" << data.AskPrice2 << "|"
<< "申卖量2:" << data.AskVolume2 << "|"
<< "申买价3:" << data.BidPrice3 << "|"
<< "申买量3:" << data.BidVolume3 << "|"
<< "申卖价3:" << data.AskPrice3 << "|"
<< "申卖量3:" << data.AskVolume3 << "|"
<< "申买价4:" << data.BidPrice4 << "|"
<< "申买量4:" << data.BidVolume4 << "|"
<< "申卖价4:" << data.AskPrice4 << "|"
<< "申卖量4:" << data.AskVolume4 << "|"
<< "申买价5:" << data.BidPrice5 << "|"
<< "申买量5:" << data.BidVolume5 << "|"
<< "申卖价5:" << data.AskPrice5 << "|"
<< "申卖量5:" << data.AskVolume5 << "|"
<< "当日均价:" << data.AveragePrice << "|"
<< "业务日期:" << data.ActionDay << "|";
return os;
}
/*
///深度行情
struct CThostFtdcDepthMarketDataField
{
///交易日
TThostFtdcDateType TradingDay;
///合约代码
TThostFtdcInstrumentIDType InstrumentID;
///交易所代码
TThostFtdcExchangeIDType ExchangeID;
///合约在交易所的代码
TThostFtdcExchangeInstIDType ExchangeInstID;
///最新价
TThostFtdcPriceType LastPrice;
///上次结算价
TThostFtdcPriceType PreSettlementPrice;
///昨收盘
TThostFtdcPriceType PreClosePrice;
///昨持仓量
TThostFtdcLargeVolumeType PreOpenInterest;
///今开盘
TThostFtdcPriceType OpenPrice;
///最高价
TThostFtdcPriceType HighestPrice;
///最低价
TThostFtdcPriceType LowestPrice;
///数量
TThostFtdcVolumeType Volume;
///成交金额
TThostFtdcMoneyType Turnover;
///持仓量
TThostFtdcLargeVolumeType OpenInterest;
///今收盘
TThostFtdcPriceType ClosePrice;
///本次结算价
TThostFtdcPriceType SettlementPrice;
///涨停板价
TThostFtdcPriceType UpperLimitPrice;
///跌停板价
TThostFtdcPriceType LowerLimitPrice;
///昨虚实度
TThostFtdcRatioType PreDelta;
///今虚实度
TThostFtdcRatioType CurrDelta;
///最后修改时间
TThostFtdcTimeType UpdateTime;
///最后修改毫秒
TThostFtdcMillisecType UpdateMillisec;
///申买价一
TThostFtdcPriceType BidPrice1;
///申买量一
TThostFtdcVolumeType BidVolume1;
///申卖价一
TThostFtdcPriceType AskPrice1;
///申卖量一
TThostFtdcVolumeType AskVolume1;
///当日均价
TThostFtdcPriceType AveragePrice;
///业务日期
TThostFtdcDateType ActionDay;
};
*/
///////////////////////////////////////////////////
//交易
/*
///用户登录请求
struct CThostFtdcReqUserLoginField
{
///交易日
TThostFtdcDateType TradingDay;
///经纪公司代码
TThostFtdcBrokerIDType BrokerID;
///用户代码
TThostFtdcUserIDType UserID;
///密码
TThostFtdcPasswordType Password;
///用户端产品信息
TThostFtdcProductInfoType UserProductInfo;
///接口端产品信息
TThostFtdcProductInfoType InterfaceProductInfo;
///协议信息
TThostFtdcProtocolInfoType ProtocolInfo;
///Mac地址
TThostFtdcMacAddressType MacAddress;
///动态密码
TThostFtdcPasswordType OneTimePassword;
///终端IP地址
TThostFtdcIPAddressType ClientIPAddress;
///登录备注
TThostFtdcLoginRemarkType LoginRemark;
};
*/
class ThostFtdcTraderCallback : public CThostFtdcTraderSpi
{
private:
CThostFtdcTraderApi* api_;
public:
ThostFtdcTraderCallback(CThostFtdcTraderApi* api)
{
api_ = api;
}
///当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。
virtual void OnFrontConnected()
{
LOG_DEBUG << __FUNCTION__ << std::endl;
CThostFtdcReqUserLoginField login_req;
memset(&login_req, 0, sizeof(login_req));
strcpy((char*)(&login_req.BrokerID), "9999");
strcpy((char*)(&login_req.UserID), "092801");
strcpy((char*)(&login_req.Password), "123456");
int ret = api_->ReqUserLogin(&login_req, requestid++);
LOG_DEBUG << "tarde ReqUserLogin ret: " << ret << std::endl;
}
///当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。
///@param nReason 错误原因
/// 0x1001 网络读失败
/// 0x1002 网络写失败
/// 0x2001 接收心跳超时
/// 0x2002 发送心跳失败
/// 0x2003 收到错误报文
virtual void OnFrontDisconnected(int nReason)
{
LOG_DEBUG << __FUNCTION__ << ", ret: " << nReason << std::endl;
}
///心跳超时警告。当长时间未收到报文时,该方法被调用。
///@param nTimeLapse 距离上次接收报文的时间
virtual void OnHeartBeatWarning(int nTimeLapse){};
///客户端认证响应
virtual void OnRspAuthenticate(CThostFtdcRspAuthenticateField *pRspAuthenticateField, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///登录请求响应
virtual void OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
LOG_DEBUG << "threadid: " << std::this_thread::get_id() << ", " << __FUNCTION__ << std::endl;
LOG_DEBUG << "errorid: " << pRspInfo->ErrorID << ", errormsg: " << pRspInfo->ErrorMsg << std::endl;
//登录成功
if (pRspInfo->ErrorID == 0)
{
CThostFtdcQryInstrumentField qry_instrument;
memset(&qry_instrument, 0, sizeof(qry_instrument));
int ret = api_->ReqQryInstrument(&qry_instrument, requestid++);
LOG_DEBUG << "tarde ReqQryInstrument ret: " << ret << std::endl;
}
}
///登出请求响应
virtual void OnRspUserLogout(CThostFtdcUserLogoutField *pUserLogout, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///错误应答
virtual void OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///报单通知
virtual void OnRtnOrder(CThostFtdcOrderField *pOrder) {};
///请求查询交易所响应
virtual void OnRspQryExchange(CThostFtdcExchangeField *pExchange, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
LOG_DEBUG << "OnRspQryExchange isLast: " << bIsLast << std::endl;
std::string exchange_name = taf::TC_Encoder::gbk2utf8(pExchange->ExchangeName);
LOG_DEBUG << pExchange->ExchangeID << "|" << exchange_name << "|" << pExchange->ExchangeProperty << std::endl;
//write to binary file
exchange_file.write(reinterpret_cast<char*>(pExchange), sizeof(CThostFtdcExchangeField));
if (bIsLast)
{
exchange_file.close();
}
}
///请求查询产品响应
virtual void OnRspQryProduct(CThostFtdcProductField *pProduct, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};
///请求查询合约响应
/*
struct CThostFtdcInstrumentField
{
///合约代码
TThostFtdcInstrumentIDType InstrumentID;
///交易所代码
TThostFtdcExchangeIDType ExchangeID;
///合约名称
TThostFtdcInstrumentNameType InstrumentName;
///合约在交易所的代码
TThostFtdcExchangeInstIDType ExchangeInstID;
///产品代码
TThostFtdcInstrumentIDType ProductID;
///产品类型
TThostFtdcProductClassType ProductClass;
///交割年份
TThostFtdcYearType DeliveryYear;
///交割月
TThostFtdcMonthType DeliveryMonth;
///市价单最大下单量
TThostFtdcVolumeType MaxMarketOrderVolume;
///市价单最小下单量
TThostFtdcVolumeType MinMarketOrderVolume;
///限价单最大下单量
TThostFtdcVolumeType MaxLimitOrderVolume;
///限价单最小下单量
TThostFtdcVolumeType MinLimitOrderVolume;
///合约数量乘数
TThostFtdcVolumeMultipleType VolumeMultiple;
///最小变动价位
TThostFtdcPriceType PriceTick;
///创建日
TThostFtdcDateType CreateDate;
///上市日
TThostFtdcDateType OpenDate;
///到期日
TThostFtdcDateType ExpireDate;
///开始交割日
TThostFtdcDateType StartDelivDate;
///结束交割日
TThostFtdcDateType EndDelivDate;
///合约生命周期状态
TThostFtdcInstLifePhaseType InstLifePhase;
///当前是否交易
TThostFtdcBoolType IsTrading;
///持仓类型
TThostFtdcPositionTypeType PositionType;
///持仓日期类型
TThostFtdcPositionDateTypeType PositionDateType;
///多头保证金率
TThostFtdcRatioType LongMarginRatio;
///空头保证金率
TThostFtdcRatioType ShortMarginRatio;
///是否使用大额单边保证金算法
TThostFtdcMaxMarginSideAlgorithmType MaxMarginSideAlgorithm;
///基础商品代码
TThostFtdcInstrumentIDType UnderlyingInstrID;
///执行价
TThostFtdcPriceType StrikePrice;
///期权类型
TThostFtdcOptionsTypeType OptionsType;
///合约基础商品乘数
TThostFtdcUnderlyingMultipleType UnderlyingMultiple;
///组合类型
TThostFtdcCombinationTypeType CombinationType;
}; */
virtual void OnRspQryInstrument(CThostFtdcInstrumentField *pInstrument, CThostFtdcRspInfoField *pRspInfo,
int nRequestID, bool bIsLast)
{
std::string instrumentname = taf::TC_Encoder::gbk2utf8(pInstrument->InstrumentName);
/*
ofs << "合约代码:" << pInstrument->InstrumentID
<< ", 交易所代码:" << pInstrument->ExchangeID
<< ", 合约名称:" << instrumentname
<< ", 合约在交易所代码:" << pInstrument->ExchangeInstID
<< ",产品代码:" << pInstrument->ProductID
<< ",产品类型:" << pInstrument->ProductClass
<< ",交割年份:" << pInstrument->DeliveryYear
<< ",交割月份:" << pInstrument->DeliveryMonth
<< ",创建日:" << pInstrument->CreateDate
<< ",上市日:" << pInstrument->OpenDate
<< ",到期日:" << pInstrument->ExpireDate
<< ",开始交割日:" << pInstrument->StartDelivDate
<< ",结束交割日:" << pInstrument->EndDelivDate
<< ",当前是否交易:" << pInstrument->IsTrading
<< ",基础商品代码:" << pInstrument->UnderlyingInstrID
<< std::endl;
*/
std::string instrument;
SerializeToString(*pInstrument, &instrument);
instruments_map[pInstrument->InstrumentID] = *pInstrument;
exchange2productid_map[pInstrument->ExchangeID].insert(pInstrument->ProductID);
if (bIsLast)
{
LOG_DEBUG << "合约拉取完毕,可以开始订阅行情了, 合约总数:" << instruments_map.size() << std::endl;
instruments_pulled = true;
for(auto exchange2productid_item : exchange2productid_map)
{
LOG_DEBUG << "交易所:" << exchange2productid_item.first << "---------";
for(auto productid: exchange2productid_item.second)
{
LOG_DEBUG << productid;
LOG_DEBUG << "|";
}
LOG_DEBUG << endl;
}
}
}
};
int32_t SerializeToString(const CThostFtdcInstrumentField& instrument, std::string* output)
{
std::string instrumentname = taf::TC_Encoder::gbk2utf8(instrument.InstrumentName);
std::stringstream ss;
/*
ss << typeid(instrument.InstrumentID).name() << "|"
<< typeid(instrument.ExchangeID).name() << "|"
<< typeid(instrument.InstrumentName).name() << "|"
<< typeid(instrument.ExchangeInstID).name() << "|"
<< typeid(instrument.ProductID).name() << "|"
<< typeid(instrument.ProductClass).name() << "|"
<< typeid(instrument.DeliveryYear).name() << "|"
<< typeid(instrument.DeliveryMonth).name() << "|"
<< typeid(instrument.MaxMarketOrderVolume).name() << "|"
<< typeid(instrument.MinMarketOrderVolume).name() << "|"
<< typeid(instrument.MaxLimitOrderVolume).name() << "|"
<< typeid(instrument.MinLimitOrderVolume).name() << "|"
<< typeid(instrument.VolumeMultiple).name() << "|"
<< typeid(instrument.PriceTick).name() << "|"
<< typeid(instrument.CreateDate).name() << "|"
<< typeid(instrument.OpenDate).name() << "|"
<< typeid(instrument.ExpireDate).name() << "|"
<< typeid(instrument.StartDelivDate).name() << "|"
<< typeid(instrument.EndDelivDate).name() << "|"
<< typeid(instrument.InstLifePhase).name() << "|"
<< typeid(instrument.IsTrading).name() << "|"
<< typeid(instrument.PositionType).name() << "|"
<< typeid(instrument.PositionDateType).name() << "|"
<< typeid(instrument.LongMarginRatio).name() << "|"
<< typeid(instrument.ShortMarginRatio).name() << "|"
<< typeid(instrument.MaxMarginSideAlgorithm).name() << "|"
<< typeid(instrument.UnderlyingInstrID).name() << "|"
<< typeid(instrument.StrikePrice).name() << "|"
<< typeid(int(instrument.OptionsType)).name() << "|"
<< typeid(instrument.UnderlyingMultiple).name() << "|"
<< typeid(instrument.CombinationType).name();
*/
ss << instrument.InstrumentID << "|"
<< instrument.ExchangeID << "|"
<< instrument.InstrumentName << "|"
<< instrument.ExchangeInstID << "|"
<< instrument.ProductID << "|"
<< instrument.ProductClass << "|"
<< instrument.DeliveryYear << "|"
<< instrument.DeliveryMonth << "|"
<< instrument.MaxMarketOrderVolume << "|"
<< instrument.MinMarketOrderVolume << "|"
<< instrument.MaxLimitOrderVolume << "|"
<< instrument.MinLimitOrderVolume << "|"
<< instrument.VolumeMultiple << "|"
<< instrument.PriceTick << "|"
<< instrument.CreateDate << "|"
<< instrument.OpenDate << "|"
<< instrument.ExpireDate << "|"
<< instrument.StartDelivDate << "|"
<< instrument.EndDelivDate << "|"
<< instrument.InstLifePhase << "|"
<< instrument.IsTrading << "|"
<< instrument.PositionType << "|"
<< instrument.PositionDateType << "|"
<< instrument.LongMarginRatio << "|"
<< instrument.ShortMarginRatio << "|"
<< instrument.MaxMarginSideAlgorithm << "|"
<< instrument.UnderlyingInstrID << "|"
<< instrument.StrikePrice << "|"
//CTP返回的这个字段不正确,是数字0,不是'1','2'
<< int(instrument.OptionsType) << "|"
<< instrument.UnderlyingMultiple << "|"
<< instrument.CombinationType;
*output = ss.str();
return 0;
}
//A31_c|A9_c|A21_c|A31_c|A31_c|c|i|i|i|i|i|i|i|d|A9_c|A9_c|A9_c|A9_c|A9_c|c|i|c|c|d|d|c|A31_c|d|i|d|c
int32_t ParseFromString(CThostFtdcInstrumentField* instrument, const std::string& input)
{
int i = 0;
std::vector<std::string> fields = taf::TC_Common::sepstr<std::string>(input, "|", true);
LOG_DEBUG << fields.size() << std::endl;
//SR807|CZCE|白砂糖807|SR807|SR|1|2018|7|200|1|1000|1|10|1|20161215|20170117|20180713|20180716|20180717|1|1|2|2|0.05|0.05|0||1.79769e+308|0|1|0
memset(instrument->InstrumentID, 0, 31);
strncpy(instrument->InstrumentID, fields[i].c_str(), fields[i].size());
i++;
//A31_c|A9_c|A21_c|A31_c|A31_c|c|i|i|i|i|i|i|i|d|A9_c|A9_c|A9_c|A9_c|A9_c|c|i|c|c|d|d|c|A31_c|d|i|d|c
memset(instrument->ExchangeID, 0, 9);
strncpy(instrument->ExchangeID, fields[i].c_str(), fields[i].size());
i++;
memset(instrument->InstrumentName, 0, 21);
strncpy(instrument->InstrumentName, fields[i].c_str(), fields[i].size());
i++;
memset(instrument->ExchangeInstID, 0, 31);
strncpy(instrument->ExchangeInstID, fields[i].c_str(), fields[i].size());
i++;
memset(instrument->ProductID, 0, 31);
strncpy(instrument->ProductID, fields[i].c_str(), fields[i].size());
i++;
instrument->ProductClass = fields[i][0];
i++;
instrument->DeliveryYear = TC_Common::strto<int>(fields[i]);
i++;
instrument->DeliveryMonth = TC_Common::strto<int>(fields[i]);
i++;
instrument->MaxMarketOrderVolume = TC_Common::strto<int>(fields[i]);
i++;
instrument->MinMarketOrderVolume = TC_Common::strto<int>(fields[i]);
i++;
instrument->MaxLimitOrderVolume = TC_Common::strto<int>(fields[i]);
i++;
instrument->MinLimitOrderVolume = TC_Common::strto<int>(fields[i]);
i++;
instrument->VolumeMultiple = TC_Common::strto<int>(fields[i]);
i++;
instrument->PriceTick = TC_Common::strto<double>(fields[i]);
i++;
memset(instrument->CreateDate, 0, 9);
strncpy(instrument->CreateDate, fields[i].c_str(), fields[i].size());
i++;
memset(instrument->OpenDate, 0, 9);
strncpy(instrument->OpenDate, fields[i].c_str(), fields[i].size());
i++;
memset(instrument->ExpireDate, 0, 9);
strncpy(instrument->ExpireDate, fields[i].c_str(), fields[i].size());
i++;
memset(instrument->StartDelivDate, 0, 9);
strncpy(instrument->StartDelivDate, fields[i].c_str(), fields[i].size());
i++;
memset(instrument->EndDelivDate, 0, 9);
strncpy(instrument->EndDelivDate, fields[i].c_str(), fields[i].size());
i++;
instrument->InstLifePhase = fields[i][0];
i++;
//A31_c|A9_c|A21_c|A31_c|A31_c|c|i|i|i|i|i|i|i|d|A9_c|A9_c|A9_c|A9_c|A9_c|c|i|c|c|d|d|c|A31_c|d|i|d|c
instrument->IsTrading = TC_Common::strto<int>(fields[i]);
i++;
instrument->PositionType = fields[i][0];
i++;
instrument->PositionDateType = fields[i][0];
i++;
instrument->LongMarginRatio = TC_Common::strto<double>(fields[i]);
i++;
instrument->ShortMarginRatio = TC_Common::strto<double>(fields[i]);
i++;
instrument->MaxMarginSideAlgorithm = fields[i][0];
i++;
//基础商品代码为空
memset(instrument->UnderlyingInstrID, 0, 9);
i++;
instrument->StrikePrice = TC_Common::strto<double>(fields[i]);
i++;
//instrument->OptionsType = TC_Common::strto<int>(fields[i]);
instrument->OptionsType = fields[i][0]-'0';
i++;
instrument->UnderlyingMultiple = TC_Common::strto<double>(fields[i]);
i++;
instrument->CombinationType = fields[i][0];
LOG_DEBUG << "index: " << i << std::endl;
return 0;
}
int main(int argc, const char* argv[])
{
if (argc < 3)
{
LOG_DEBUG << "Usage: " << argv[0] << " tarde_ep(tcp://180.168.146.187:10030) instrumentids" << std::endl;
return 0;
}
std::string tarde_ep = argv[1];
std::string instrumentids = argv[2];
if (instrumentids == "0")
{
LOG_DEBUG << "订阅所有行情" << std::endl;
subscribe_all_instrument = true;
}
else
{
LOG_DEBUG << "订阅指定合约行情: " << instrumentids << std::endl;
instruments_vec = taf::TC_Common::sepstr<std::string>(instrumentids, ":");
}
logger.init("./ctp_query_demo");
//先拉取所有合约
if (subscribe_all_instrument)
{
auto trader_func = [&tarde_ep]() {
traderapi = CThostFtdcTraderApi::CreateFtdcTraderApi();
ThostFtdcTraderCallback trader_callback(traderapi);
traderapi->RegisterSpi(&trader_callback);
traderapi->RegisterFront((char*)tarde_ep.data());
traderapi->Init();
traderapi->Join();
LOG_DEBUG << std::this_thread::get_id() << " trade api exit" << std::endl;
};
std::thread tarder_thread(trader_func);
tarder_thread.detach();
}
std::cout << "ctp ctrl cmd: \n"
<< "1: query exchange\n"
<< "2: read exchang\n"
<< "3: query instrument\n"
<< std::endl;
std::ifstream ifs_exchange_file("exchange_info", ios::binary);
while(true)
{
int select = 0;
std::cin >> select;
switch (select)
{
case 1:
CThostFtdcQryExchangeField qry_exchange;
memset(&qry_exchange, 0, sizeof(CThostFtdcQryExchangeField));
traderapi->ReqQryExchange(&qry_exchange, requestid++);
break;
case 2:
CThostFtdcExchangeField exchange_info;
while(ifs_exchange_file.read(reinterpret_cast<char*>(&exchange_info), sizeof(CThostFtdcExchangeField)))
{
LOG_DEBUG << exchange_info.ExchangeID << "|" << taf::TC_Encoder::gbk2utf8(exchange_info.ExchangeName) << "|" << exchange_info.ExchangeProperty << std::endl;
}
break;
case 3:
{
CThostFtdcQryInstrumentField qry_instrument;
//查询所有合约信息
memset(&qry_instrument, 0, sizeof(qry_instrument));
int ret = traderapi->ReqQryInstrument(&qry_instrument, requestid++);
LOG_DEBUG << "tarde ReqQryInstrument ret: " << ret << std::endl;
break;
}
}
}
return 0;
}
|
//知识点:记忆化,dfs
/*
搜索 + 简单剪枝
比较简单 , 详见注释
*/
#include<cstdio>
#include<cstring>
#include<ctype.h>
#define min(a,b) a<b?a:b
const int INF = 0x3f3f3f;
const int ex[5] = {0,1,-1,0,0};//坐标变化量
const int ey[5] = {0,0,0,1,-1};
//=============================================================
int m,n,ans=INF, map[110][110],step[110][110];//map存图的情况,step存到达各点的花费
//=============================================================
inline int read()
{
int fl=1,w=0;char ch=getchar();
while(!isdigit(ch) && ch!='-') ch=getchar();
if(ch=='-') fl=-1;
while(isdigit(ch)){w=w*10+ch-'0',ch=getchar();}
return fl*w;
}
//x,y存当前点坐标,sum 存到达当前点的花费,magci存转移到当前点是否使用了魔法
void dfs(int x,int y,int sum,bool magic)
{
if(sum>=step[x][y]) return ;//最优性剪枝
step[x][y]=sum;//赋值
if(x==m && y==m)//到达终点
{
ans=min(ans,step[x][y]);
return ;
}
for(int i=1,nx=x+ex[i],ny=y+ey[i];i<=4;i++,nx=x+ex[i],ny=y+ey[i])//枚举能到达的点
if(nx>=1 && nx<=m && ny>=1 && ny<=m)//不越界
{
if(!map[nx][ny])//无色情况
{
if(!magic)//没有使用过魔法
{
map[nx][ny]=map[x][y];//更改颜色,并进行转移
dfs(nx,ny,sum+2,1);
map[nx][ny]=0;
}
continue;
}
dfs(nx,ny,sum+(map[x][y]!=map[nx][ny]),0);//有色情况,按照颜色同异情况进行转移
}
}
//=============================================================
signed main()
{
m=read(),n=read();
for(int i=1;i<=n;i++)
{
int x=read(),y=read(),c=read()+1;
map[x][y]=c;
}
memset(step,INF,sizeof(step));//初始化花费,为极大值
dfs(1,1,0,0);
printf("%d",ans>=INF?-1:ans);
}
|
#include <iostream>
#include <queue>
#include <utility>
#include <vector>
#include <algorithm>
using namespace std;
int matrix[25][25];
bool visited[25][25];
vector<int> area;
void bfs(int i, int j, int maxSize, int &count){
queue<pair<int, int>> q;
q.push(make_pair(i,j));
visited[i][j] = true;
while(!q.empty()){
//right
pair<int, int> cur = q.front();
q.pop();
if(cur.second != maxSize-1 && visited[cur.first][cur.second+1] == false
&& matrix[cur.first][cur.second+1] == 1){
//오른쪽 끝 아님
count++;
q.push(make_pair(cur.first, cur.second+1));
visited[cur.first][cur.second+1] = true;
}
//left
if(cur.second != 0 && visited[cur.first][cur.second-1] == false
&& matrix[cur.first][cur.second-1] == 1){
count++;
q.push(make_pair(cur.first, cur.second-1));
visited[cur.first][cur.second-1] = true;
}
//up
if(cur.first != 0 && visited[cur.first-1][cur.second] == false
&& matrix[cur.first-1][cur.second] == 1){
count++;
q.push(make_pair(cur.first-1, cur.second));
visited[cur.first-1][cur.second] = true;
}
//down
if(cur.first != maxSize-1 && visited[cur.first+1][cur.second] == false
&& matrix[cur.first+1][cur.second]){
count++;
q.push(make_pair(cur.first+1, cur.second));
visited[cur.first+1][cur.second] = true;
}
}
}
int main(){
int n;
cin >> n;
for(int i = 0; i < n; i++){
string line;
cin >> line;
for(int j = 0; j < n; j++){
matrix[i][j] = line[j] - '0';
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(matrix[i][j] == 1 && visited[i][j] == false){
area.push_back(1);
bfs(i, j, n, area.back());
}
}
}
sort(area.begin(), area.end());
cout << area.size() << endl;
for(auto it = area.begin(); it != area.end(); it++){
cout << *it << '\n';
}
return 0;
}
|
// tareaMatrizPunteros.cpp : Este archivo contiene la función "main". La ejecución del programa comienza y termina ahí.
//
#include <iostream>
#include <windows.h>
using namespace std;
void multiplicacionMatrices();
void recorrer(int** M, int fil, int col);
void print(int** M, int fil, int col);
int main()
{
cout << "Multiplicacion de Matrizes (Para que se puedan multiplicar el numero de columnas de la matriz 1 debe ser igual al numero de filas de la matriz 2)" << endl;
Sleep(5000);
system("cls");
multiplicacionMatrices();
}
void multiplicacionMatrices()
{
int f1, c1, filB, colB;
cout << "\nMatriz 1:";
cout << "\nFilas de la matriz: ";
cin >> f1;
cout << "Columnas de la matriz: ";
cin >> c1;
int** M1 = new int* [f1];
for (int i = 0; i < f1; i++)
M1[i] = new int[c1];
recorrer(M1, f1, c1);
cout << "\nMatriz 2:";
cout << "\nFilas de la matriz: ";
cin >> filB;
cout << "Columnas de la matriz: ";
cin >> c1;
int** M2 = new int* [filB];
for (int i = 0; i < filB; i++)
M2[i] = new int[c1];
recorrer(M2, filB, colB);
int** MatrizAux = new int* [f1];
for (int i = 0; i < f1; i++)
MatrizAux[i] = new int[c1];
if (c1 == filB) {
for (int i = 0; i < f1; ++i) {
for (int j = 0; j < colB; ++j) {
C[i][j] = 0;
for (int z = 0; z < c1; ++z)
C[i][j] += M1[i][z] * M2[z][j];
}
}
cout << "\nMATRIZ 1\n";
print(M1, f1, c1);
cout << "\nMATRIZ 2\n";
print(M2, filB, colB);
cout << "\nRESULTADO DE MULTIPLICACION (M1*M2):\n";
print(MatrizAux, f1, colB);
}
else
cout << "\n error a multiplicar ya que num de columnas de matriz 1 debe ser = a num de filas de matriz 2 " << endl;
}
void print(int** M, int fil, int col)
{
for (int i = 0; i < fil; i++) {
cout << "\n ";
for (int j = 0; j < col; j++)
cout << M[i][j] << " ";
cout << " ";
}
cout << endl;
}
void recorrer(int** M, int fil, int col)
{
for (int i = 0; i < fil; i++)
{
for (int j = 0; j < col; j++)
{
M[i][j] = rand() % 5;
cout << "\t" << M[i][j];
}
cout << endl;
}
}
// Ejecutar programa: Ctrl + F5 o menú Depurar > Iniciar sin depurar
// Depurar programa: F5 o menú Depurar > Iniciar depuración
// Sugerencias para primeros pasos: 1. Use la ventana del Explorador de soluciones para agregar y administrar archivos
// 2. Use la ventana de Team Explorer para conectar con el control de código fuente
// 3. Use la ventana de salida para ver la salida de compilación y otros mensajes
// 4. Use la ventana Lista de errores para ver los errores
// 5. Vaya a Proyecto > Agregar nuevo elemento para crear nuevos archivos de código, o a Proyecto > Agregar elemento existente para agregar archivos de código existentes al proyecto
// 6. En el futuro, para volver a abrir este proyecto, vaya a Archivo > Abrir > Proyecto y seleccione el archivo .sln
|
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int cChecked[101] ;
int bfs(int start, vector<int> a[])
{
int nResult = 0;
queue<int> q;
q.push(start);
cChecked[start] = true;
while (!q.empty())
{
int x = q.front();
q.pop();
for (int i = 0; i < a[x].size(); i++)
{
int y = a[x][i];
if (!cChecked[y])
{
nResult++;
q.push(y);
cChecked[y] = true;
}
}
}
return nResult;
}
int main(void)
{
int nCountOfComputer = 0;
int nCouple = 0;
int nInfected = 0;
vector<int> vNetwork[101];
cin >> nCountOfComputer;
cin >> nCouple;
for (int i = 0; i < nCouple; i++)
{
int nTemp1, nTemp2;
cin >> nTemp1 >> nTemp2;
vNetwork[nTemp1].push_back(nTemp2);
vNetwork[nTemp2].push_back(nTemp1);
}
nInfected = bfs(1, vNetwork);
cout << nInfected;
return 0;
}
|
#include "stdafx.h"
#include "GameTime.h"
GameTime::GameTime()
{
}
GameTime::~GameTime()
{
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#include "platforms/mac/model/UnicodeRangeDetectors.h"
/** Detect if the font supports a good range of glyphs in a unicode range.
* characterMap contains 2,048 32-bit ints, so a given utf-16 codepoint, uc, would be found in characterMap[uc >> 5].
* The bit-pattern is in big endian, first character is last (least significant) bit.
* For exaple, codepoint U+0041 (65, 'A') would be tested with (characterMap[2] & 0x00000002) or (characterMap[65 >> 5] & (1 << (65 & 31)))
* Conversely, (characterMap[a] & (1 << b)) is codepoint a * 32 + b
* The names are a tiny bit misleading, as these functions return Microsoft Usb ranges rather than the official unicode ranges.
* This will probably be ammended in the future, so this class solely reports unicode ranges, and Usb is calculated in MacFontIntern.cpp
*
* In the days before _GLYPHTESTING_SUPPORT_, these functions had to be pretty accurate at reporting what codepages they supported.
* So, only fonts that were likely support MOST of the CP were reported.
* Now, though, anything is better than a square box, so report ANY match.
*/
Boolean UnicodeRangeDetectors::hasLatin1(const uint32 *characterMap)
{
// U+0020 - U+007e
if (characterMap[1] || characterMap[2] || characterMap[3])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasLatin1Supplement(const uint32 *characterMap)
{
// U+00a0 - U+00ff
if (characterMap[5] || characterMap[6] || characterMap[7])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasLatinExtendedA(const uint32 *characterMap)
{
// U+0100 - U+017f
if (characterMap[8] || characterMap[9] || characterMap[10] || characterMap[11])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasLatinExtendedB(const uint32 *characterMap)
{
// U+0180 - U+024f
if (characterMap[12] || characterMap[13] || characterMap[14] || characterMap[15] ||
characterMap[16] || characterMap[17] || (characterMap[18] & 0x0000FFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasIPAExtensions(const uint32 *characterMap)
{
// U+0250 - U+02af
if((characterMap[18] & 0xFFFF0000) || characterMap[19] || characterMap[20] || (characterMap[21] & 0x0000FFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasSpacingModifiedLetters(const uint32 *characterMap)
{
// U+02b0 - U+02ff
if((characterMap[21] & 0xFFFF0000) || characterMap[22] || characterMap[23])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasCombiningDiacriticalMarks(const uint32 *characterMap)
{
// U+0300 - U+036f
if (characterMap[24] || characterMap[25] || characterMap[26] || (characterMap[27] & 0x0000FFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasGreek(const uint32 *characterMap)
{
// U+0370 - U+03ff
if ((characterMap[27] & 0xFFFF0000) || characterMap[28] || characterMap[29] || characterMap[30] || characterMap[31])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasCyrillic(const uint32 *characterMap)
{
// U+0400 - U+04ff
if (characterMap[32] || characterMap[33] || characterMap[34] || characterMap[35] ||
characterMap[36] || characterMap[37] || characterMap[38] || characterMap[39])
return true;
// U+0500 - U+052f, Cyrillic Supplementary
if (characterMap[40] || (characterMap[41] & 0x0000FFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasArmenian(const uint32 *characterMap)
{
// U+0530 - U+058F
if((characterMap[41] & 0xFFFF0000) || characterMap[42] || characterMap[43] || (characterMap[44] & 0x0000FFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasHebrew(const uint32 *characterMap)
{
// U+0590 - U+05FF
if((characterMap[44] & 0xFFFF0000) || characterMap[45] || characterMap[46] || characterMap[47])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasArabic(const uint32 *characterMap)
{
// U+0600 - U+06ff
if (characterMap[48] || characterMap[49] || characterMap[50] || characterMap[51] ||
characterMap[52] || characterMap[53] || characterMap[54] || characterMap[55])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasDevanagari(const uint32 *characterMap)
{
// U+0900 - U+097f
if (characterMap[72] || characterMap[73] || characterMap[74] || characterMap[75])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasBengali(const uint32 *characterMap)
{
// U+0980 - U+09ff
if (characterMap[76] || characterMap[77] || characterMap[78] || characterMap[79])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasGurmukhi(const uint32 *characterMap)
{
// U+0a00 - U+0a7f
if (characterMap[80] || characterMap[81] || characterMap[82] || characterMap[83])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasGujarati(const uint32 *characterMap)
{
// U+0a80 - U+0aff
if (characterMap[84] || characterMap[85] || characterMap[86] || characterMap[87])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasOriya(const uint32 *characterMap)
{
// U+0b00 - U+0b7f
if (characterMap[88] || characterMap[89] || characterMap[90] || characterMap[91])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasTamil(const uint32 *characterMap)
{
// U+0b80 - U+0bff
if (characterMap[92] || characterMap[93] || characterMap[94] || characterMap[95])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasTelugu(const uint32 *characterMap)
{
// U+0c00 - U+0c7f
if (characterMap[96] || characterMap[97] || characterMap[98] || characterMap[99])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasKannada(const uint32 *characterMap)
{
// U+0c80 - U+0cff
if (characterMap[100] || characterMap[101] || characterMap[102] || characterMap[103])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasMalayalam(const uint32 *characterMap)
{
// U+0d00 - U+0d7f
if (characterMap[104] || characterMap[105] || characterMap[106] || characterMap[107])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasThai(const uint32 *characterMap)
{
// U+0e00 - U+0e7f
if (characterMap[112] || characterMap[113] || characterMap[114] || characterMap[115])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasLao(const uint32 *characterMap)
{
// U+0e80 - U+0eff
if (characterMap[116] || characterMap[117] || characterMap[118] || characterMap[119])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasBasicGeorgian(const uint32 *characterMap)
{
// U+10a0 - U+10ff
if (characterMap[133] || characterMap[134] || characterMap[135])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasHangulJamo(const uint32 *characterMap)
{
// U+1100 - U+11ff
if (characterMap[136] || characterMap[137] || characterMap[138] || characterMap[139] ||
characterMap[140] || characterMap[141] || characterMap[142] || characterMap[143])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasLatinExtendedAdditional(const uint32 *characterMap)
{
// U+1e00 - U+1eff
if (characterMap[240] || characterMap[241] || characterMap[242] || characterMap[243] ||
characterMap[244] || characterMap[245] || characterMap[246] || characterMap[247])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasGreekExtended(const uint32 *characterMap)
{
// U+1f00 - U+1fff
if (characterMap[248] || characterMap[249] || characterMap[250] || characterMap[251] ||
characterMap[252] || characterMap[253] || characterMap[254] || characterMap[255])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasGeneralPunctuation(const uint32 *characterMap)
{
// U+2000 - U+206f
if (characterMap[256] || characterMap[257] || characterMap[258] || (characterMap[259] & 0x0000FFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasSuperscriptsAndSubscripts(const uint32 *characterMap)
{
// U+2070 - U+209f
if ((characterMap[259] & 0xFFFF0000) || characterMap[260])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasCurrencySymbols(const uint32 *characterMap)
{
// U+20a0 - U+20cf
if (characterMap[261] || (characterMap[262] & 0x0000FFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasCombiningDiacriticalMarksForSymbols(const uint32 *characterMap)
{
// U+20d0 - U+20ff
if ((characterMap[262] & 0xFFFF0000) || characterMap[263])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasLetterLikeSymbols(const uint32 *characterMap)
{
// U+2100 - U+214f
if (characterMap[264] || characterMap[265] || (characterMap[266] & 0x0000FFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasNumberForms(const uint32 *characterMap)
{
// U+2150 - U+218f
if ((characterMap[266] & 0xFFFF0000) || characterMap[267] || (characterMap[268] & 0x0000FFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasArrows(const uint32 *characterMap)
{
// U+2190 - U+21ff
if ((characterMap[268] & 0xFFFF0000) || characterMap[269] || characterMap[270] || characterMap[271])
return true;
// U+27F0 - U+27FF, Supplemental Arrows-A
if (characterMap[319] & 0xFFFF0000)
return true;
// U+2900 - U+297F, Supplemental Arrows-B
if (characterMap[328] || characterMap[329] || characterMap[330] || characterMap[331])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasMathematicalOperators(const uint32 *characterMap)
{
// U+2200 - U+22ff
if (characterMap[272] || characterMap[273] || characterMap[274] || characterMap[275] ||
characterMap[276] || characterMap[277] || characterMap[278] || characterMap[279])
return true;
// U+2A00 - U+2AFF, Supplemental Mathematical Operators
if (characterMap[336] || characterMap[337] || characterMap[338] || characterMap[339] ||
characterMap[340] || characterMap[341] || characterMap[342] || characterMap[343])
return true;
// U+27C0 - U+27EF, Miscellaneous Mathematical Symbols-A
if (characterMap[318] || (characterMap[319] & 0x0000FFFF))
return true;
// U+2980 - U+29FF, Miscellaneous Mathematical Symbols-B
if (characterMap[332] || characterMap[333] || characterMap[334] || characterMap[335])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasMiscellaneousTechnical(const uint32 *characterMap)
{
// U+2300 - U+23ff
if (characterMap[280] || characterMap[281] || characterMap[282] || characterMap[283] ||
characterMap[284] || characterMap[285] || characterMap[286] || characterMap[287])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasControlPictures(const uint32 *characterMap)
{
// U+2400 - U+243f
if (characterMap[288] || characterMap[289])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasOpticalCharacterRecognition(const uint32 *characterMap)
{
// U+2440 - U+245f
if (characterMap[290])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasEnclosedAlphanumerics(const uint32 *characterMap)
{
// U+2460 - U+24ff
if (characterMap[291] || characterMap[292] || characterMap[293] || characterMap[294] || characterMap[295])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasBoxDrawing(const uint32 *characterMap)
{
// U+2500 - U+257f
if (characterMap[296] || characterMap[297] || characterMap[298] || characterMap[299])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasBlockElements(const uint32 *characterMap)
{
// U+2580 - U+259f
if (characterMap[300])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasBlockGeometricShapes(const uint32 *characterMap)
{
// U+25a0 - U+25ff
if (characterMap[301] || characterMap[302] || characterMap[303])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasMiscellaneousSymbols(const uint32 *characterMap)
{
// U+2600 - U+26ff
if (characterMap[304] || characterMap[305] || characterMap[306] || characterMap[307] ||
characterMap[308] || characterMap[309] || characterMap[310] || characterMap[311])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasDingbats(const uint32 *characterMap)
{
// U+2700 - U+27bf
if (characterMap[312] || characterMap[313] || characterMap[314] ||
characterMap[315] || characterMap[316] || characterMap[317])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasCJKSymbolsAndPunctuation(const uint32 *characterMap)
{
// U+3000 - U+303f
if(characterMap[384] || characterMap[385])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasHiragana(const uint32 *characterMap)
{
// U+3040 - U+309f
if (characterMap[386] || characterMap[387] || characterMap[388])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasKatakana(const uint32 *characterMap)
{
// U+30a0 - U+30ff
if (characterMap[389] || characterMap[390] || characterMap[391])
return true;
// U+31f0 - U+31ff, Katakana Phonetic Extensions
if (characterMap[399] & 0xFFFF0000)
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasBopomofo(const uint32 *characterMap)
{
// U+3100 - U+312f
if (characterMap[392] || (characterMap[393] & 0x0000FFFF))
return true;
// U+31a0 - U+31bf, Bopomofo Extended
if (characterMap[397])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasHangulCompatibilityJamo(const uint32 *characterMap)
{
// U+3130 - U+318f
if ((characterMap[393] & 0xFFFF0000) || (characterMap[394]) || (characterMap[395]) || (characterMap[396] & 0x0000FFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasCJKMiscellaneous(const uint32 *characterMap)
{
// U+3190 - U+319f
if (characterMap[396] & 0xFFFF0000)
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasEnclosedCJKLettersAndMonths(const uint32 *characterMap)
{
// U+3200 - U+32ff
if (characterMap[400] || characterMap[401] || characterMap[402] || characterMap[403] ||
characterMap[404] || characterMap[405] || characterMap[406] || characterMap[407])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasCJKCompatibility(const uint32 *characterMap)
{
// U+3300 - U+33ff
if(characterMap[408] || characterMap[409] || characterMap[410] || characterMap[411])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasHangul(const uint32 *characterMap)
{
// U+ac00 - U+d7a3
// Keep original test
if(characterMap[1706] & 0x10000000)
if(characterMap[1387] & 0x00002000)
if(characterMap[1581] & 0x00100000)
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasCJKUnifiedIdeographs(const uint32 *characterMap)
{
// U+4e00 - U+9fff
// U+2e80 - U+2eff, CJK Radicals Supplement
// U+2F00 - U+2FDF, Kangxi Radicals
// U+2FF0 - U+2FFF, Ideographic Description Characters
// U+3400 - U+4DBF, CJK Unified Ideograph Extension A
// U+3190 - U+319F, Kanbun
// Keep original test
if(!(characterMap[625] & 0x00002000)) return false; // return true;
// if(!(characterMap[671] & 0x00800000)) return false;
if(!(characterMap[812] & 0x00000080)) return false; // return true;
if(!(characterMap[815] & 0x00000020)) return false; // return true;
if(!(characterMap[825] & 0x00001000)) return false; // return true;
if(!(characterMap[1108] & 0x40000000)) return false; // return true;
return true;
//return false;
}
Boolean UnicodeRangeDetectors::hasPrivateUseArea(const uint32 *characterMap)
{
// U+e000 - U+f8ff
for (int i = 1792; i < 1992; i++)
if (characterMap[i])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasCJKCompatibilityIdeographs(const uint32 *characterMap)
{
// U+f900 - U+faff
// This might be overdoing it.
if (characterMap[1992] || characterMap[1993] || characterMap[1994] || characterMap[1995] ||
characterMap[1996] || characterMap[1997] || characterMap[1998] || characterMap[1999] ||
characterMap[2000] || characterMap[2001] || characterMap[2002] || characterMap[2003] ||
characterMap[2004] || characterMap[2005] || characterMap[2006] || characterMap[2007])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasAlphabeticPresentationForms(const uint32 *characterMap)
{
// U+fb00 - U+fb4f
if(characterMap[2008] || characterMap[2009] || (characterMap[2010] & 0x0000FFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasArabicPresentationFormsA(const uint32 *characterMap)
{
// U+fb50 - U+fdff
if((characterMap[2010] & 0xFFFF0000) || characterMap[2011] || characterMap[2012] ||
characterMap[2013] || characterMap[2014] || characterMap[2015])
return true;
// Don't bother testing rest: fc00-fdff (2016-2031)
return false;
}
Boolean UnicodeRangeDetectors::hasCombiningHalfMarks(const uint32 *characterMap)
{
// fe20-fe2f
if (characterMap[2033] & 0x0000FFFF)
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasCJKCompatibilityForms(const uint32 *characterMap)
{
// fe30-fe4f
if ((characterMap[2033] & 0xFFFF0000) || (characterMap[2034] & 0x0000FFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasSmallFormVariants(const uint32 *characterMap)
{
// fe50-fe6f
if ((characterMap[2034] & 0xFFFF0000) || (characterMap[2035] & 0x0000FFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasArabicPresentationFormsB(const uint32 *characterMap)
{
// fe70-fefe
if ((characterMap[2035] & 0xFFFF0000) || characterMap[2036] || characterMap[2037] ||
characterMap[2038] || (characterMap[2039] & 0xEFFFFFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasHalfwidthAndFullwidthForms(const uint32 *characterMap)
{
// U+ff00 - U+ffef
if (characterMap[2040] || characterMap[2041] || characterMap[2042] || characterMap[2043] ||
characterMap[2044] || characterMap[2045] || characterMap[2046] || (characterMap[2047] & 0x0000FFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasTibetian(const uint32 *characterMap)
{
// U+0f00 - 0fff
if (characterMap[120] || characterMap[121] || characterMap[122] || characterMap[123] ||
characterMap[124] || characterMap[125] || characterMap[126] || characterMap[127])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasSyriac(const uint32 *characterMap)
{
// U+0700 - U+074f
if (characterMap[56] || characterMap[57] || (characterMap[58] & 0x0000FFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasThaana(const uint32 *characterMap)
{
// U+0780 - U+07bf
if (characterMap[60] || characterMap[61])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasSinhala(const uint32 *characterMap)
{
// U+0d80 - U+0dff
if(characterMap[108] || characterMap[109] || characterMap[110] || characterMap[111])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasMyanmar(const uint32 *characterMap)
{
// U+1000 - U+109f
if(characterMap[128] || characterMap[129] || characterMap[130] ||
characterMap[131] || characterMap[132])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasEthiopic(const uint32 *characterMap)
{
// U+1200 - U+137f
if(characterMap[144] || characterMap[145] || characterMap[146] || characterMap[147])
return true;
// Don't bother testing rest: 1280-137f (148-155)
return false;
}
Boolean UnicodeRangeDetectors::hasCherokee(const uint32 *characterMap)
{
// U+13a0 - U+13ff
if (characterMap[157] || characterMap[158] || characterMap[159])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasCanadianAboriginalSyllabics(const uint32 *characterMap)
{
// U+1400 - U+167f
if (characterMap[160] || characterMap[161] || characterMap[162] || characterMap[163] ||
characterMap[164] || characterMap[165] || characterMap[166] || characterMap[167])
return true;
// Don't bother testing rest: 1500-167f (168-179)
return false;
}
Boolean UnicodeRangeDetectors::hasOgham(const uint32 *characterMap)
{
// U+1680 - U+169f
if(characterMap[180])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasRunic(const uint32 *characterMap)
{
// U+16a0 - U+16ff
if(characterMap[181] || characterMap[182] || characterMap[183])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasKhmer(const uint32 *characterMap)
{
// U+1780 - U+17ff
if(characterMap[188] || characterMap[189] || characterMap[190] || characterMap[191])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasMongolian(const uint32 *characterMap)
{
// U+1800 - U+18af
if (characterMap[192] || characterMap[193] || characterMap[194] || characterMap[195] ||
characterMap[196] || (characterMap[197] & 0x0000FFFF))
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasBraille(const uint32 *characterMap)
{
// U+2800 - U+28ff
if (characterMap[320] || characterMap[321] || characterMap[322] || characterMap[323] ||
characterMap[324] || characterMap[325] || characterMap[326] || characterMap[327])
return true;
return false;
}
Boolean UnicodeRangeDetectors::hasYi(const uint32 *characterMap)
{
// U+a000 - U+a48f
if (characterMap[1280] || characterMap[1281] || characterMap[1282] || characterMap[1283] ||
characterMap[1284] || characterMap[1285] || characterMap[1286] || characterMap[1287])
return true;
// Don't bother testing rest
// U+A490 - U+A4CF, Yi Radicals
return false;
}
Boolean UnicodeRangeDetectors::hasPhilipino(const uint32 *characterMap)
{
// U+1700 - U+171F, Tagalog
if (characterMap[184])
return true;
// U+1720 - U+173F, Hanunoo
if (characterMap[185])
return true;
// U+1740 - U+175F, Buhid
if (characterMap[186])
return true;
// U+1760 - U+177F, Tagbanwa
if (characterMap[187])
return true;
return false;
}
Boolean UnicodeRangeDetectors::isSimplified(const uint32 *characterMap)
{
struct CharacterTestTable
{
unsigned short character;
unsigned short mapLocation;
unsigned int mask;
};
static const CharacterTestTable testTable[] =
{
{ 0x4E00, 624, 0x00000001 },
{ 0x4E0A, 624, 0x00000400 },
{ 0x4E16, 624, 0x00400000 },
{ 0x4E2A, 625, 0x00000400 },
{ 0x4E2D, 625, 0x00002000 },
{ 0x4E48, 626, 0x00000100 },
{ 0x4E61, 627, 0x00000002 },
{ 0x4E86, 628, 0x00000040 },
{ 0x4EC0, 630, 0x00000001 },
{ 0x4ECA, 630, 0x00000400 },
{ 0x4ECE, 630, 0x00004000 },
{ 0x4ED6, 630, 0x00400000 },
{ 0x4EEC, 631, 0x00001000 },
{ 0x4F1A, 632, 0x04000000 },
{ 0x4F5C, 634, 0x10000000 },
{ 0x4F60, 635, 0x00000001 },
{ 0x538C, 668, 0x00001000 },
{ 0x53BB, 669, 0x08000000 },
{ 0x53EB, 671, 0x00000800 },
{ 0x5403, 672, 0x00000008 },
{ 0x540D, 672, 0x00002000 },
{ 0x54EA, 679, 0x00000400 },
{ 0x559C, 684, 0x10000000 },
{ 0x5668, 691, 0x00000100 },
{ 0x56DE, 694, 0x40000000 },
{ 0x56FD, 695, 0x20000000 },
{ 0x5728, 697, 0x00000100 },
{ 0x574F, 698, 0x00008000 },
{ 0x5927, 713, 0x00000080 },
{ 0x5929, 713, 0x00000200 },
{ 0x597D, 715, 0x20000000 },
{ 0x5B50, 730, 0x00010000 },
{ 0x5B57, 730, 0x00800000 },
{ 0x5BB6, 733, 0x00400000 },
{ 0x5DE5, 751, 0x00000020 },
{ 0x5F88, 764, 0x00000100 },
{ 0x5FAE, 765, 0x00004000 },
{ 0x60F3, 775, 0x00080000 },
{ 0x6211, 784, 0x00020000 },
{ 0x6587, 812, 0x00000080 },
{ 0x662F, 817, 0x00008000 },
{ 0x6700, 824, 0x00000001 },
{ 0x6765, 827, 0x00000020 },
{ 0x6B22, 857, 0x00000004 },
{ 0x6C14, 864, 0x00100000 },
{ 0x6D4B, 874, 0x00000800 },
{ 0x6D4F, 874, 0x00008000 },
{ 0x70DF, 902, 0x80000000 },
{ 0x754C, 938, 0x00001000 },
{ 0x7684, 948, 0x00000010 },
{ 0x771F, 952, 0x80000000 },
{ 0x809A, 1028, 0x04000000 },
{ 0x86CB, 1078, 0x00000800 },
{ 0x8857, 1090, 0x00800000 },
{ 0x89C8, 1102, 0x00000100 },
{ 0x8BA8, 1117, 0x00000100 },
{ 0x8BD5, 1118, 0x00200000 },
{ 0x8BF4, 1119, 0x00100000 },
{ 0x8D77, 1131, 0x00800000 },
{ 0x8F6F, 1147, 0x00008000 },
{ 0x901B, 1152, 0x08000000 },
{ 0x91CC, 1166, 0x00001000 },
{ 0x996D, 1227, 0x00002000 },
{ 0x997F, 1227, 0x80000000 }
};
unsigned int testedOk=0;
unsigned int i;
for(i=0; i<ARRAY_SIZE(testTable); i++)
{
if((characterMap[testTable[i].mapLocation] & testTable[i].mask) == testTable[i].mask)
testedOk ++;
}
if(testedOk > ARRAY_SIZE(testTable) * 9 / 10)
return true;
return false;
}
Boolean UnicodeRangeDetectors::isTraditional(const uint32 *characterMap)
{
struct CharacterTestTable
{
unsigned short character;
unsigned short mapLocation;
unsigned int mask;
};
static const CharacterTestTable testTable[] =
{
{ 0x4E8B, 628, 0x00000800 },
{ 0x4E9B, 628, 0x08000000 },
{ 0x4EE5, 631, 0x00000020 },
{ 0x4EF6, 631, 0x00400000 },
{ 0x4F5C, 634, 0x10000000 },
{ 0x4F7F, 635, 0x80000000 },
{ 0x4F86, 636, 0x00000040 },
{ 0x4F9D, 636, 0x20000000 },
{ 0x5148, 650, 0x00000100 },
{ 0x5206, 656, 0x00000040 },
{ 0x5236, 657, 0x00400000 },
{ 0x529B, 660, 0x08000000 },
{ 0x52D9, 662, 0x02000000 },
{ 0x52D9, 662, 0x02000000 },
{ 0x5316, 664, 0x00400000 },
{ 0x53CA, 670, 0x00000400 },
{ 0x53EF, 671, 0x00008000 },
{ 0x5408, 672, 0x00000100 },
{ 0x5473, 675, 0x00080000 },
{ 0x548C, 676, 0x00001000 },
{ 0x5546, 682, 0x00000040 },
{ 0x5730, 697, 0x00010000 },
{ 0x5747, 698, 0x00000080 },
{ 0x597D, 715, 0x20000000 },
{ 0x5B9A, 732, 0x04000000 },
{ 0x5E0C, 752, 0x00001000 },
{ 0x5F0F, 760, 0x00008000 },
{ 0x5F71, 763, 0x00020000 },
{ 0x5F97, 764, 0x00800000 },
{ 0x5FEB, 767, 0x00000800 },
{ 0x6027, 769, 0x00000080 },
{ 0x60A8, 773, 0x00000100 },
{ 0x610F, 776, 0x00008000 },
{ 0x6167, 779, 0x00000080 },
{ 0x61C9, 782, 0x00000200 },
{ 0x6240, 786, 0x00000001 },
{ 0x63F4, 799, 0x00100000 },
{ 0x64CD, 806, 0x00002000 },
{ 0x652F, 809, 0x00008000 },
{ 0x6574, 811, 0x00100000 },
{ 0x6587, 812, 0x00000080 },
{ 0x65B9, 813, 0x02000000 },
{ 0x660E, 816, 0x00004000 },
{ 0x667A, 819, 0x04000000 },
{ 0x6703, 824, 0x00000008 },
{ 0x6709, 824, 0x00000200 },
{ 0x671B, 824, 0x08000000 },
{ 0x672C, 825, 0x00001000 },
{ 0x6790, 828, 0x00010000 },
{ 0x6848, 834, 0x00000100 },
{ 0x696D, 843, 0x00002000 },
{ 0x6BCB, 862, 0x00000800 },
{ 0x6C42, 866, 0x00000004 },
{ 0x6C7A, 867, 0x04000000 },
{ 0x7372, 923, 0x00040000 },
{ 0x7528, 937, 0x00000100 },
{ 0x7684, 948, 0x00000010 },
{ 0x7B26, 985, 0x00000040 },
{ 0x7B56, 986, 0x00400000 },
{ 0x7BC4, 990, 0x00000010 },
{ 0x7D44, 1002, 0x00000010 },
{ 0x7E54, 1010, 0x00100000 },
{ 0x7FA9, 1021, 0x00000200 },
{ 0x800C, 1024, 0x00001000 },
{ 0x80FD, 1031, 0x20000000 },
{ 0x81EA, 1039, 0x00000400 },
{ 0x8457, 1058, 0x00800000 },
{ 0x89E3, 1103, 0x00000008 },
{ 0x8A02, 1104, 0x00000004 },
{ 0x8A2D, 1105, 0x00002000 },
{ 0x8AAA, 1109, 0x00000400 },
{ 0x8ABF, 1109, 0x80000000 },
{ 0x9019, 1152, 0x02000000 },
{ 0x901F, 1152, 0x80000000 },
{ 0x9069, 1155, 0x00000200 },
{ 0x90A3, 1157, 0x00000008 },
{ 0x9375, 1179, 0x00200000 },
{ 0x95DC, 1198, 0x10000000 },
{ 0x9650, 1202, 0x00010000 },
{ 0x9700, 1208, 0x00000001 },
{ 0x97FF, 1215, 0x80000000 },
{ 0x9806, 1216, 0x00000040 }
};
unsigned int testedOk=0;
unsigned int i;
for(i=0; i<ARRAY_SIZE(testTable); i++)
{
if((characterMap[testTable[i].mapLocation] & testTable[i].mask) == testTable[i].mask)
testedOk ++;
}
if(testedOk > ARRAY_SIZE(testTable) * 9 / 10)
return true;
return false;
}
|
// 1006_10.cpp : 定义控制台应用程序的入口点。
//配对问题(匈牙利算法)(看了好久...)
//输入数据的第一行是三个整数K, M, N,分别表示可能的组合数目,女生的人数,男生的人数。0<K <= 1000
//1 <= N 和M <= 500.接下来的K行,每行有两个数,
//分别表示女生Ai愿意和男生Bj做partner。最后一个0结束输入
//输出最大匹配数
//匈牙利算法是寻找增广路径解决二分图匹配,达到完美匹配,即最大匹配,完全匹配
#include<iostream>
using namespace std;
const int max = 501;
int map[max][max];
int vis[max];
int boy[max];
//int i, j;如果把i,j定义成全局变量程序照常运行,但在OJ上WA
int k, m, n;
int find(int girl)
{
for (int j = 1; j <= n; j++)//依次访问所有的男生
{
if (vis[j] == 0 && map[girl][j] == 1)//本次搜索中之前没有访问过该男生,同时女生可以和男生配对
{
vis[j] = 1;//表示该男生已经访问过了
if (boy[j] == 0 || find(boy[j]))//该男生还没有配对或者可以将已经配对成功的男女重新拆开,给女生重新找到男生配对
{
boy[j] = girl;//男孩j与女孩i配对成功
return 1;
}
}
}
return 0;
}
int main()
{
while (cin >> k && k!=EOF)
{
if (k <= 0 || k > 1000)
break;
cin >> m >> n;
if (m > 500 || n < 1)
break;
int a, b;
memset(map, 0, sizeof(map));
memset(boy, 0, sizeof(boy));
for (int i = 0; i < k; i++)
{
cin >> a >> b;
map[a][b] = 1;
}
/*
for (i = 1; i <= m; i++)
{
cout << endl;
for (j = 1; j <= n; j++)
cout << map[i][j]<<" ";
}
*/
int num = 0;
for (int i = 1; i <= m; i++)
{
memset(vis, 0, sizeof(vis));
if (find(i))
num++;
}
cout << num << endl;
}
//system("pause");
return 0;
}
|
#include <gtest/gtest.h>
#include "Nodes/UnaryOperations/SigmoidUnaryOperation.hpp"
struct SigmoidUnaryOperationTest : testing::Test
{
};
struct CustomComputationNode : ComputationNode<float>
{
CustomComputationNode(float v)
: output(v)
{}
ArrayView<float const> getOutputValues() const override
{
return output;
}
void backPropagate(ArrayView<float const> v) override
{
std::cout << "propagated error " << v[0] << std::endl;
}
std::size_t getNumOutputs() const override
{
return 1;
}
void backPropagationPass() override
{
}
float output;
};
TEST_F(SigmoidUnaryOperationTest, TestSetsCanBeCompared)
{
CustomComputationNode input(4.0f);
SigmoidUnaryOperationNode<float> sut(&input, 1.0);
sut.forwardPass();
std::cout << sut.getOutputValues()[0] << std::endl;
float error = -1.0f;
sut.backPropagate(error);
}
|
#include <bits/stdc++.h>
using namespace std;
const int MAX=100005;
unordered_map <int,int> mp[MAX];
int sz[MAX];
vector <int> G[MAX];
int get_map(int C,int x) {
if(!mp[C].count(x)) return x;
return mp[C][x]=get_map(C,mp[C][x]);
}
void Union(int C,int x,int y) {
x=get_map(C,x);
y=get_map(C,y);
if(x>y) swap(x,y);
if(x!=y) {
mp[C][y]=x;
}
}
int main() {
int n,m;
cin>>n>>m;
int x,y;
int temp=m;
while(m--) {
int C;
scanf("%d %d %d",&x,&y,&C);
G[x].push_back(C);
G[y].push_back(C);
Union(C,x,y);
}
for(int C=1; C<=n; C++) {
sort(G[C].begin(),G[C].end());
G[C].erase(unique(G[C].begin(),G[C].end()),G[C].end());
sz[C]=G[C].size();
}
cin>>m;
map <pair <int,int> ,int> ans_map;
while(m--) {
scanf("%d %d",&x,&y);
if(x>y) swap(x,y);
pair <int,int> t=make_pair(x,y);
if(sz[x]>sz[y]) swap(x,y);
if(ans_map.count(t)) {
printf("%d\n",ans_map[t]);
continue;
}
int ans=0;
for(int i=0; i<G[x].size(); i++) {
int C=G[x][i];
if(get_map(C,x)==get_map(C,y)) ans++;
}
ans_map[t]=ans;
printf("%d\n",ans);
}
//while(true);
return 0;
}
|
#include "BotController.h"
int main(int argc, char* argv[])
{
WORD wVersionRequested = MAKEWORD(1,1);
WSADATA wsaData;
if(WSAStartup(wVersionRequested, &wsaData) != 0)
{
std::cerr << "error starting winsock";
}
std::vector<std::string> chanlist;
chanlist.push_back("#chan1");
chanlist.push_back("#chan2");
IRCOptotron::BotController::start("bot", "208.51.40.2", chanlist);
return 0;
}
|
#include "datewindow.h"
#include "ui_datewindow.h"
#include <iostream>
dateWindow::dateWindow(QWidget *parent) :
QDialog(parent),
ui(new Ui::dateWindow)
{
ui->setupUi(this);
doneButton = ui->pushButton;
connect(doneButton, SIGNAL(clicked()), this, SLOT(hide()));
}
dateWindow::~dateWindow()
{
delete ui;
delete doneButton;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2009 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef DEVICEAPI_OPVCARDENTRY_H
#define DEVICEAPI_OPVCARDENTRY_H
#ifdef DAPI_VCARD_SUPPORT
#include "modules/device_api/OpDirectoryEntry.h"
#include "modules/pi/device_api/OpAddressBook.h"
class OpVCardEntry : public OpDirectoryEntry
{
public:
/** Imports vCard data from OpAddressBookItem.
*
* If this operation fails then no rollback is performed so the
* vCard may be left in inconsistent state.
* @param item - Adddress book item which data will be imported.
*/
OP_STATUS ImportFromOpAddressBookItem(OpAddressBookItem* item);
// see RFC2426 (vCard) - FN
OP_STATUS SetFormattedName(const uni_char* fn);
// see RFC2426 (vCard) - N - 1st field
OP_STATUS AddFamilyName(const uni_char* family_name);
// see RFC2426 (vCard) - N - 2nd field
OP_STATUS AddGivenName(const uni_char* given_name);
// see RFC2426 (vCard) - N - 3rd field
OP_STATUS AddAdditionalName(const uni_char* additional_name);
// see RFC2426 (vCard) - N - 4th field
OP_STATUS AddHonorificPrefix(const uni_char* honorific_prefix);
// see RFC2426 (vCard) - N - 5th field
OP_STATUS AddHonorificSuffix(const uni_char* honorific_suffix);
// see RFC2426 (vCard) - NICKNAME
OP_STATUS AddNickname(const uni_char* nickname);
// see RFC2426 (vCard) - BDAY
/**
* @param year - 1 based - 1 AD = 1
* @param month - 0 based - Jan = 0, Feb = 1...
* @param day - 1 based - 1st = 1
* @param time_of_day - time of the day in miliseconds.
* @param timezone_offset - timezone in miliseconds in relation to UTC
*/
OP_STATUS SetBirthday(int year, int month, int day, double time_of_day, double time_offset);
enum AddressTypeFlags
{
ADDRESS_DOMESTIC = 0x0001,
ADDRESS_INTERNATIONAL = 0x0002,
ADDRESS_POSTAL = 0x0004,
ADDRESS_PARCEL = 0x0008,
ADDRESS_HOME = 0x0010,
ADDRESS_WORK = 0x0020,
ADDRESS_PREFERRED = 0x0040,
ADDRESS_LAST = ADDRESS_PREFERRED,
ADDRESS_DEFAULT = ADDRESS_INTERNATIONAL | ADDRESS_POSTAL | ADDRESS_PARCEL | ADDRESS_WORK, // as specified in RFC2426
};
// see RFC2426 (vCard) - ADR
/// @param type_flags - flags describing type of an address
/// values of the flags come are in AddressTypeFlags enum
OP_STATUS AddStructuredAddress(int type_flags
, const uni_char* post_office_box
, const uni_char* extended_address
, const uni_char* street_address
, const uni_char* locality
, const uni_char* region
, const uni_char* postal_code
, const uni_char* country_name);
// see RFC2426 (vCard) - LABEL
/// @param type_flags - flags describing type of an address
/// values of the flags come are in AddressTypeFlags enum
OP_STATUS AddPostalLabelAddress(int type_flags
, const uni_char* address);
enum TelephoneTypeFlags
{
TELEPHONE_HOME = 0x0001,
TELEPHONE_WORK = 0x0002,
TELEPHONE_CELL = 0x0004,
TELEPHONE_PREFERRED = 0x0008,
TELEPHONE_VOICE = 0x0010, // if nothing is specified this is default
TELEPHONE_FAX = 0x0020,
TELEPHONE_VIDEO = 0x0040,
TELEPHONE_PAGER = 0x0080,
TELEPHONE_BBS = 0x0100,
TELEPHONE_MODEM = 0x0200,
TELEPHONE_CAR = 0x0400,
TELEPHONE_ISDN = 0x0800,
TELEPHONE_PCS = 0x1000,
TELEPHONE_SUPPORTS_VOICE_MESSAGING = 0x2000,
TELEPHONE_LAST = TELEPHONE_SUPPORTS_VOICE_MESSAGING, // RFC2426 'msg'
TELEPHONE_DEFAULT = TELEPHONE_VOICE,
};
// see RFC2426 (vCard) - TEL
/// @param type_flags - flags describing type of an telephone
/// values of the flags come are in TelephoneTypeFlags enum
OP_STATUS AddTelephoneNumber(int type_flags
, const uni_char* number);
enum EMailTypeFlags
{
EMAIL_INTERNET = 0x0001,
EMAIL_X400 = 0x0002,
EMAIL_PREFERRED = 0x0004,
EMAIL_LAST = EMAIL_PREFERRED,
EMAIL_DEFAULT = EMAIL_INTERNET,
};
// see RFC2426 (vCard) - EMAIL
/// @param type_flags - flags describing type of an email
/// values of the flags come are in EMailTypeFlags enum
OP_STATUS AddEMail(int type_flags
, const uni_char* email);
// see RFC2426 (vCard) - MAILER
OP_STATUS SetMailer(const uni_char* mailer);
// see RFC2426 (vCard) - TZ
/// @param timezone_offset - timezone in miliseconds in relation to UTC
OP_STATUS SetTimezone(double timezone_offset);
// see RFC2426 (vCard) - GEO
/// @param latitude - latitude in degree
OP_STATUS SetLocation(double latitude, double longitude);
// see RFC2426 (vCard) - TITLE
OP_STATUS SetOrganizationTitle(const uni_char* title);
// see RFC2426 (vCard) - ROLE
OP_STATUS SetOrganizationRole(const uni_char* role );
// see RFC2426 (vCard) - AGENT
OP_STATUS AddAgentURI(const uni_char* uri);
OP_STATUS AddAgentVCard(const OpVCardEntry* v_card);
OP_STATUS AddAgentText(const uni_char* agent_text);
// see RFC2426 (vCard) - ORG
/**
* @param organizational_chain - array of pointers to zero terminated strings representing
* hierarchical organizational units. Most general organizational unit is first and most
* specific is last. Example:
* { "Opera Software", "Engineering", "Windows Mobile Deliveries" }
* @param chain_length number of entries in organizational_chain
*/
OP_STATUS SetOrganizationalChain(const uni_char** organizational_chain, UINT32 chain_length);
// see RFC2426 (vCard) - CATEGORIES
OP_STATUS AddCategory(const uni_char* category);
// see RFC2426 (vCard) - NOTE
OP_STATUS AddNote(const uni_char* note);
// see RFC2426 (vCard) - SORT-STRING
OP_STATUS AddSortString(const uni_char* sort_string);
// see RFC2426 (vCard) - URL
OP_STATUS AddURL(const uni_char* url);
// see RFC2426 (vCard) - PHOTO
OP_STATUS AddPhoto(const uni_char* uri);
OP_STATUS AddPhoto(OpFileDescriptor* opened_input_file, const uni_char* type);
// see RFC2426 (vCard) - LOGO
OP_STATUS AddLogo(const uni_char* uri);
OP_STATUS AddLogo(OpFileDescriptor* opened_input_file, const uni_char* type);
// see RFC2426 (vCard) - SOUND
OP_STATUS AddSound(const uni_char* uri);
OP_STATUS AddSound(OpFileDescriptor* opened_input_file, const uni_char* type);
// missing vCard types PRODID, REV, UID, CLASS, KEY, X-XXX...
/**
* Prints textual reprezentation of the vCard to the file.
* @param opened_file - file to which the vCard will be written.
*/
OP_STATUS Print(OpFileDescriptor* opened_file);
private:
OP_STATUS ApplyTypeFlags(OpDirectoryEntryContentLine* value, int flags, const uni_char* const* flags_texts, int last_flag);
OP_STATUS ApplyAddressTypeFlags(OpDirectoryEntryContentLine* value, int flags);
OP_STATUS ApplyTelephoneTypeFlags(OpDirectoryEntryContentLine* value, int flags);
OP_STATUS ApplyEmailTypeFlags(OpDirectoryEntryContentLine* value, int flags);
static BOOL FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::Meaning meaning, const OpAddressBook::OpAddressBookFieldInfo* infos, UINT32 infos_count, UINT32& index);
};
#endif // DAPI_VCARD_SUPPORT
#endif // DEVICEAPI_OPVCARDENTRY_H
|
/*
* OpenGL.cpp
*
* Created on: Apr 1, 2017
* Author: Patryk
*/
#include <OpenGL.hpp>
#include <Window.hpp>
#include <ErrorManager.hpp>
#include <GLFW/glfw3.h>
using namespace core::error;
namespace core
{
bool OpenGL::initialize(const WindowDesc &desc)
{
glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 4 );
glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 5 );
glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
//glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE );
int a = ((desc.vsync == true) ? 1 : 0);
glfwSwapInterval(a);
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if(err != GLEW_OK)
{
error::ErrorMsg error;
error.description = reinterpret_cast<const char*>(glGetString(err));
error.type = error::ErrorType::Error;
error.reaction = error::ErrorReaction::Shutdown;
ErrorManager::push(error);
return false;
}
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
return true;
}
void OpenGL::clear(const float *color)
{
//glClear(GL_COLOR_BUFFER_BIT);
//glClearColor(color[0],color[1],color[2],color[3]);
glClearBufferfv(GL_COLOR,0,color);
}
};
|
#ifndef _QUEUE_H_
#define _QUEUE_H_
#include "linked_list/doubly.h"
namespace cs2420 {
template <typename T>
class QueueADT {
public:
virtual void enqueue(T e) = 0;
virtual T dequeue() = 0;
virtual T peek() const = 0;
virtual void clear() = 0;
virtual bool empty() const = 0;
virtual ~QueueADT(){}
};
template<typename T>
class Queue : public QueueADT<T>{
private:
List<T> lst;
public:
Queue(): lst(List<T>()){}
void enqueue(T e) { lst.add_back(e); }
T dequeue() {
if(empty()) throw std::runtime_error("Empty queue.");
auto front = lst.begin();
T e = *front;
lst.remove_front();
return e;
}
T peek() const {
if(empty()) throw std::runtime_error("Empty queue.");
auto front = lst.begin();
return *front;
}
void clear() {
lst.clear();
}
bool empty() const {
return lst.empty();
}
};
}
#endif
|
#include <iostream>
using namespace std;
int max(int a,int b)
{
return a>b ? a:b ;
}
int main()
{
int size;
cout<<"Enter the size of the array: ";
cin>>size;
int nums[size];
cout<<"Enter the elements of the array: ";
for(int i=0;i<size;i++)
{
cin>>nums[i];
}
int max_sum=nums[0], sum=nums[0];
for(int i=1; i<size; i++)
{
sum = max(nums[i], sum+nums[i]);
if(sum>max_sum)
{
max_sum=sum;
}
}
cout<<"The maximum sum for the array is: "<<max_sum;
return 0;
}
|
#include "Parent.h"
void createList(ListP &L){
first(L) = nil;
}
adrP alokasiP(infotypeP x){
adrP P;
P = new elemenP;
info(P) = x;
nextP(P) = nil;
//nextC(P) = nil;
return P;
}
void insertFirst(ListP &L, adrP P){
if (first(L) == nil){
first(L) = P;
}
else{
nextP(P) = first(L);
first(L) = P;
}
}
void insertLast(ListP &L, adrP P){
adrP Q;
if (first(L) == nil){
first(L) = P;
}
else{
Q = first(L);
while (nextP(Q) != nil){
Q = nextP(Q);
}
nextP(Q) = P;
}
}
void deleteFirst(ListP &L, adrP &P){
if (first(L) == nil){
cout << "Data masih kosong" << endl;
}
else if (nextP(first(L)) == nil){
P = first(L);
first(L) = nil;
}
else{
P = first(L);
first(L) = nextP(first(L));
nextP(P) = nil;
}
}
void deleteLast(ListP &L, adrP &P){
adrP Q;
if (first(L) == nil){
cout << "Data masih kosong" << endl;
}
else if (nextP(first(L)) == nil){
P = first(L);
first(L) = nil;
}
else{
Q = first(L);
while (nextP(nextP(Q)) != nil){
Q = nextP(Q);
}
P = nextP(Q);
nextP(Q) = nil;
}
}
adrP searchParent(ListP L, infotypeP x){
adrP P = first(L);
while((info(P).namaLapas != x.namaLapas) && (P != NULL)){
P = nextP(P);
}
return P;
}
void countElm(ListP &L){
adrP P;
int Jumlah;
if (first(L) == nil){
cout << "data masih kosong" << endl;
}
else{
P = first(L);
Jumlah = 0;
while (P != nil){
Jumlah = Jumlah + 1;
P = nextP(P);
}
cout << Jumlah << endl;
}
}
void viewAll(ListP &L){
adrP P;
P = first(L);
if(first(L)!=NULL) {
do {
cout << info(P).namaLapas<<endl;
cout << info(P).kategori<<endl;
printInfoC(child(P));
P = nextP(P);
} while((P)!=first(L));
}
}
|
/*
* Copyright (c) 2011 Pierre-Etienne Bougué <pe.bougue(a)gmail.com>
* Copyright (c) 2011 Florian Colin <florian.colin28(a)gmail.com>
* Copyright (c) 2011 Kamal Fadlaoui <kamal.fadlaoui(a)gmail.com>
* Copyright (c) 2011 Quentin Lequy <quentin.lequy(a)gmail.com>
* Copyright (c) 2011 Guillaume Pinot <guillaume.pinot(a)tremplin-utc.net>
* Copyright (c) 2011 Cédric Royer <cedroyer(a)gmail.com>
* Copyright (c) 2011 Guillaume Turri <guillaume.turri(a)gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "dtoout/SolutionDtoout.hh"
#include "alg/ContextALG.hh"
#include "bo/ContextBO.hh"
#include "bo/MachineBO.hh"
#include "bo/ProcessBO.hh"
#include <fstream>
#include <sstream>
#include <boost/foreach.hpp>
#include <limits>
using namespace std;
string SolutionDtoout::outFileName_m;
pthread_mutex_t SolutionDtoout::mutex_m = PTHREAD_MUTEX_INITIALIZER;
uint64_t SolutionDtoout::bestScoreWritten_m = numeric_limits<uint64_t>::max();
vector<int> SolutionDtoout::bestSol_m;
void SolutionDtoout::setOutFileName(const string& outFileName_p){
outFileName_m = outFileName_p;
}
void SolutionDtoout::writeSolInit(ContextBO* pContextBO_p, const string& outFileName_p){
ofstream ofs_l(outFileName_p.c_str());
if ( ! ofs_l ){
ostringstream oss_l;
oss_l << "Impossible d'ouvrir le flux de sortie " << outFileName_m
<< " pour y ecrire une solution initiale" << endl;
throw oss_l.str();
}
int nbProcess_l = pContextBO_p->getNbProcesses();
for ( int idxP_l=0 ; idxP_l < nbProcess_l ; idxP_l++ ){
ofs_l << pContextBO_p->getProcess(idxP_l)->getMachineInit()->getId();
if ( idxP_l != nbProcess_l ){
ofs_l << " ";
}
}
}
bool SolutionDtoout::writeSol(const vector<int>& vSol_p, uint64_t score_p){
//Vu qu'on n'est pas cense passer souvent ici, on lock en global
pthread_mutex_lock(&mutex_m);
try {
if (score_p >= bestScoreWritten_m) {
pthread_mutex_unlock(&mutex_m);
return false;
}
ofstream ofs_l(outFileName_m.c_str());
if ( ! ofs_l ){
ostringstream oss_l;
oss_l << "Impossible d'ouvrir le flux de sortie " << outFileName_m
<< " pour y ecrire une solution" << endl;
throw oss_l.str();
}
copy(vSol_p.begin(), vSol_p.end(), ostream_iterator<int>(ofs_l, " "));
bestScoreWritten_m = score_p;
bestSol_m = vSol_p;
} catch (string exc) {
pthread_mutex_unlock(&mutex_m);
throw exc;
} catch (std::exception exc) {
pthread_mutex_unlock(&mutex_m);
throw exc;
} catch (...) {
pthread_mutex_unlock(&mutex_m);
throw string("Une exception a ete levee lors de l'ecriture d'une solution");
}
pthread_mutex_unlock(&mutex_m);
return true;
}
uint64_t SolutionDtoout::getBestScore(){
return bestScoreWritten_m;
}
const vector<int>& SolutionDtoout::getBestSol(){
return bestSol_m;
}
#ifdef UTEST
void SolutionDtoout::reinit(const string& outfile_p){
outFileName_m = outfile_p;
pthread_mutex_unlock(&mutex_m);
bestScoreWritten_m = numeric_limits<uint64_t>::max();
bestSol_m.clear();
}
#endif
|
#include "UserInfo.h"
UserInfo::UserInfo()
: userId(-1) {}
UserInfo::UserInfo(const std::string& login,
const std::string& password)
: login(login), password(password), userId(-1) {}
std::string UserInfo::encode() const {
parser->clear();
parser->addValue(login, KeyWords::login);
parser->addValue(password, KeyWords::password);
if (firstName != "") {
parser->addValue(firstName, KeyWords::firstName);
parser->addValue(lastName, KeyWords::lastName);
parser->addValue(role, KeyWords::role);
}
return parser->getJson();
}
void UserInfo::decode(const std::string &jsonStr) {
parser->setJson(jsonStr);
userId = parser->getValue<int>(KeyWords::userId);
role = parser->getValue<std::string>(KeyWords::role);
firstName = parser->getValue<std::string>(KeyWords::firstName);
lastName = parser->getValue<std::string>(KeyWords::lastName);
ip = parser->getValue<std::string>(KeyWords::ip);
port = parser->getValue<std::string>(KeyWords::port);
company = parser->getValue<std::string>(KeyWords::company);
}
|
#include <iostream>
#include <vector>
#include <string.h>
#include <string>
#include "FreeImage.h"
#include "glew.h"
#include "glut.h"
#include "mesh.h"
#include "viewing.h"
#include "light.h"
#include "scene.h"
using namespace std;
#define NUM_TEXTURE 20
unsigned int texObject[NUM_TEXTURE];
vector<Mesh> objects;
View *view;
Light *light;
Scene *scene;
int winWidth, winHeight;
int texTechnique = 0;
double rSide[3], forth[3];
size_t selectObjIndex = 0;
int preMouseX = 250, preMouseY = 250;
double movCamUnit = 5.0, movObjUnit = 2;
void loadTexture(const char* textureFile, size_t k);
void loadCubeMap(char textureFiles[6][100], size_t k);
void viewing();
void lighting();
void texBeforeRender(Textures tex);
void texAfterRender(Textures tex);
void display();
void reshape(GLsizei w, GLsizei h);
void keyboard(unsigned char key, int x, int y);
void drag(int x, int y);
int main(int argc, char** argv)
{
string parkObjFiles[] = { "bush.obj", "gem.obj", "groundv2.obj", "hedge.obj", "leaves.obj", "littlefountain.obj", "skybox.obj", "trunk.obj", "water.obj" };
string chessObjFiles[] = { "Bishop.obj", "Chessboard.obj", "King.obj", "Knight.obj", "Pawn.obj", "Queen.obj", "Rook.obj", "Room.obj" };
string *objFiles;
size_t objNum;
int test;
cout << "1: Park scene | 2: Chess scene" << endl;
cin >> test;
if (test == 1) {
objFiles = parkObjFiles;
objNum = 9;
view = new View("park.view");
light = new Light("park.light");
scene = new Scene("park.scene");
}
else {
objFiles = chessObjFiles;
objNum = 8;
view = new View("Chess.view");
light = new Light("Chess.light");
scene = new Scene("Chess.scene");
}
for (size_t i = 0; i<objNum; i++) {
Mesh obj(objFiles[i].c_str());
objects.push_back(obj);
}
cout << endl << "--------------------- finish loading files ---------------------" << endl;
glutInit(&argc, argv);
glutInitWindowSize(view->width_, view->height_);
glutInitWindowPosition(0, 0);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("OpenGL Project 2");
glewInit();
FreeImage_Initialise();
glGenTextures(NUM_TEXTURE, texObject);
size_t texNo = 0;
for (vector<Textures>::iterator it = scene->texList_.begin(); it != scene->texList_.end(); it++) {
if (it->technique_ != 3) { //not use cube-map
for (vector<TexImage>::iterator jt = it->imageList_.begin(); jt != it->imageList_.end(); jt++) {
jt->texID_ = texNo;
loadTexture(jt->imageFile.c_str(), texNo++);
}
}
else { //use cube-map
char iList[6][100];
for (size_t j = 0; j < 6; j++)
strcpy(iList[j], it->imageList_[j].imageFile.c_str());
it->texID_ = texNo;
loadCubeMap(iList, texNo++);
}
}
cout << endl << "-------------------- finish loading textures --------------------" << endl;
FreeImage_DeInitialise();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMotionFunc(drag);
glutMainLoop();
return 0;
}
void loadTexture(const char* textureFile, size_t k)
{
cout << textureFile << ": " << k << endl;
FIBITMAP* tImage = FreeImage_Load(FreeImage_GetFileType(textureFile, 0), textureFile);
FIBITMAP* t32BitsImage = FreeImage_ConvertTo32Bits(tImage);
int iWidth = FreeImage_GetWidth(t32BitsImage);
int iHeight = FreeImage_GetHeight(t32BitsImage);
glBindTexture(GL_TEXTURE_2D, texObject[k]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, iWidth, iHeight, 0, GL_BGRA, GL_UNSIGNED_BYTE, (void*)FreeImage_GetBits(t32BitsImage));
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1000);
FreeImage_Unload(t32BitsImage);
FreeImage_Unload(tImage);
}
void loadCubeMap(char textureFiles[6][100], size_t k)
{
FIBITMAP *tImage[6], *t32BitsImage[6];
int iWidth[6], iHeight[6];
for (size_t i = 0; i<6; i++) {
tImage[i] = FreeImage_Load(FreeImage_GetFileType(textureFiles[i], 0), textureFiles[i]);
t32BitsImage[i] = FreeImage_ConvertTo32Bits(tImage[i]);
iWidth[i] = FreeImage_GetWidth(t32BitsImage[i]);
iHeight[i] = FreeImage_GetHeight(t32BitsImage[i]);
}
glBindTexture(GL_TEXTURE_CUBE_MAP, texObject[k]);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGBA8, iWidth[0], iHeight[0], 0, GL_BGRA, GL_UNSIGNED_BYTE, (void*)FreeImage_GetBits(t32BitsImage[0]));
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GL_RGBA8, iWidth[1], iHeight[1], 0, GL_BGRA, GL_UNSIGNED_BYTE, (void*)FreeImage_GetBits(t32BitsImage[1]));
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GL_RGBA8, iWidth[2], iHeight[2], 0, GL_BGRA, GL_UNSIGNED_BYTE, (void*)FreeImage_GetBits(t32BitsImage[2]));
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GL_RGBA8, iWidth[3], iHeight[3], 0, GL_BGRA, GL_UNSIGNED_BYTE, (void*)FreeImage_GetBits(t32BitsImage[3]));
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GL_RGBA8, iWidth[4], iHeight[4], 0, GL_BGRA, GL_UNSIGNED_BYTE, (void*)FreeImage_GetBits(t32BitsImage[4]));
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GL_RGBA8, iWidth[5], iHeight[5], 0, GL_BGRA, GL_UNSIGNED_BYTE, (void*)FreeImage_GetBits(t32BitsImage[5]));
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
glTexEnvi(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, 1000);
for (size_t i = 0; i<6; i++) {
FreeImage_Unload(t32BitsImage[i]);
FreeImage_Unload(tImage[i]);
}
}
void viewing()
{
// viewport transformation
glViewport((GLint)view->x_, (GLint)view->y_, (GLsizei)view->width_, (GLsizei)view->height_);
// projection transformation
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective((GLdouble)view->fovy_, (GLfloat)winWidth / (GLfloat)winHeight, (GLdouble)view->dnear_, (GLdouble)view->dfar_);
// viewing and modeling transformation
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt((GLdouble)view->eye_[0], (GLdouble)view->eye_[1], (GLdouble)view->eye_[2], // eye
(GLdouble)view->vat_[0], (GLdouble)view->vat_[1], (GLdouble)view->vat_[2], // center
(GLdouble)view->vup_[0], (GLdouble)view->vup_[1], (GLdouble)view->vup_[2]); // up
}
void lighting()
{
glShadeModel(GL_SMOOTH);
// z buffer enable
glEnable(GL_DEPTH_TEST);
// enable lighting
glEnable(GL_LIGHTING);
// set light property
GLenum lightNo = GL_LIGHT0;
for (vector<Source>::iterator it = light->lList_.begin(); it != light->lList_.end(); it++) {
glEnable(lightNo);
glLightfv(lightNo, GL_POSITION, it->pos_);
glLightfv(lightNo, GL_DIFFUSE, it->diffuse_);
glLightfv(lightNo, GL_SPECULAR, it->specular_);
glLightfv(lightNo, GL_AMBIENT, it->ambient_);
lightNo++;
}
glEnable(GL_LIGHT_MODEL_AMBIENT);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, light->enAmbient_);
}
void texBeforeRender(Textures tex)
{
texTechnique = tex.technique_;
if (texTechnique == 0) { // no-texture
}
else if (texTechnique == 1) { // single-texture
cout << "single-texture:" << tex.imageList_[0].texID_ << endl;
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texObject[tex.imageList_[0].texID_]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0.5f);
}
else if (texTechnique == 2) { // multi-texture
cout << "multi-texture: " << tex.imageList_[0].texID_ << " " << tex.imageList_[1].texID_ << endl;
for (size_t i = 0; i < 2; i++) {
GLenum glTexture = GL_TEXTURE0 + i;
glActiveTexture(glTexture);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texObject[tex.imageList_[i].texID_]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
glTexEnvf(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE);
}
}
else { // cube-map
cout << "cube-map: " << tex.texID_ << endl;
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP);
glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP);
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_GEN_T);
glEnable(GL_TEXTURE_GEN_R);
glEnable(GL_TEXTURE_CUBE_MAP);
glBindTexture(GL_TEXTURE_CUBE_MAP, texObject[tex.texID_]);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
}
}
void texAfterRender(Textures tex)
{
texTechnique = tex.technique_;
if (texTechnique == 0) { // no-texture
}
else if (texTechnique == 1) { // single-texture
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
}
else if (texTechnique == 2) { // multi-texture
glActiveTexture(GL_TEXTURE1);
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE0);
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
}
else { // cube-map
glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);
glDisable(GL_TEXTURE_GEN_R);
glDisable(GL_TEXTURE_CUBE_MAP);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
}
}
void display()
{
// clear the buffer
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // for use in cleaning color buffers
glClearDepth(1.0f); // Depth Buffer (it's the buffer) Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Test To Do
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// this makes the scene black and clears the z buffer
viewing();
// note that light should be set after gluLookAt
lighting();
size_t lastTexIndex = -1;
Textures currTex;
// for each model in the scene file
for (vector<Model>::iterator it = scene->modelList_.begin(); it != scene->modelList_.end(); it++) {
glPushMatrix();
// enable and bind the texture if this model used different texture
if (lastTexIndex != it->texIndex_) {
if (lastTexIndex != -1)
texAfterRender(currTex);
lastTexIndex = it->texIndex_;
currTex = scene->texList_[lastTexIndex];
texBeforeRender(currTex);
}
// find the selected mesh in the scene file
Mesh* obj = nullptr;
for (vector<Mesh>::iterator jt = objects.begin(); jt != objects.end(); jt++)
if (jt->objFile_ == it->objFile_) {
obj = &(*jt);
break;
}
if (obj == nullptr) {
cout << "Don't have " << it->objFile_ << " in the object files" << endl;
continue;
}
glTranslated((GLdouble)it->transfer_[0], (GLdouble)it->transfer_[1], (GLdouble)it->transfer_[2]);
glRotated((GLdouble)it->angle_, (GLdouble)it->rotate_[0], (GLdouble)it->rotate_[1], (GLdouble)it->rotate_[2]);
glScaled((GLdouble)it->scale_[0], (GLdouble)it->scale_[1], (GLdouble)it->scale_[2]);
// for each face in the mesh object
int lastMaterial = -1;
for (size_t i = 0; i < obj->fTotal_; ++i) {
// set material property if this face used different material
if (lastMaterial != obj->faceList_[i].m) {
lastMaterial = (int)obj->faceList_[i].m;
glMaterialfv(GL_FRONT, GL_AMBIENT, obj->matList_[lastMaterial].Ka);
glMaterialfv(GL_FRONT, GL_DIFFUSE, obj->matList_[lastMaterial].Kd);
glMaterialfv(GL_FRONT, GL_SPECULAR, obj->matList_[lastMaterial].Ks);
glMaterialfv(GL_FRONT, GL_SHININESS, &obj->matList_[lastMaterial].Ns);
//you can obtain the texture name by obj->matList_[lastMaterial].map_Kd
//load them once in the main function before mainloop
//bind them in display function here
}
glBegin(GL_TRIANGLES);
// for each vertex in the face (triangle)
for (size_t j = 0; j < 3; ++j) {
if (texTechnique == 1 || texTechnique == 3) // single-texture or cube-map
glTexCoord2f(obj->tList_[obj->faceList_[i][j].t].ptr[0], obj->tList_[obj->faceList_[i][j].t].ptr[1]);
else if (texTechnique == 2) { // multi-texture
for (size_t k = 0; k < 2; k++) {
GLenum glTexture = GL_TEXTURE0 + k;
glMultiTexCoord2fv(glTexture, obj->tList_[obj->faceList_[i][j].t].ptr);
}
}
glNormal3fv(obj->nList_[obj->faceList_[i][j].n].ptr);
glVertex3fv(obj->vList_[obj->faceList_[i][j].v].ptr);
}
glEnd();
}
glPopMatrix();
}
texAfterRender(scene->texList_[lastTexIndex]);
glutSwapBuffers();
}
void reshape(GLsizei w, GLsizei h)
{
winWidth = w;
winHeight = h;
}
void keyboard(unsigned char key, int x, int y)
{
forth[0] = (view->vat_[0] - view->eye_[0]) / movCamUnit;
forth[1] = (view->vat_[1] - view->eye_[1]) / movCamUnit;
forth[2] = (view->vat_[2] - view->eye_[2]) / movCamUnit;
rSide[0] = (forth[1] * view->vup_[2] - forth[2] * view->vup_[1]) / movCamUnit;
rSide[1] = (forth[2] * view->vup_[0] - forth[0] * view->vup_[2]) / movCamUnit;
rSide[2] = (forth[0] * view->vup_[1] - forth[1] * view->vup_[0]) / movCamUnit;
if (key == 'w') { // zoom in
printf("keyboard: %c\n", key);
for (size_t i = 0; i < 3; i++)
view->eye_[i] += forth[i];
glutPostRedisplay();
}
else if (key == 'a') { // move left
printf("keyboard: %c\n", key);
for (size_t i = 0; i < 3; i++)
view->eye_[i] -= rSide[i];
glutPostRedisplay();
}
else if (key == 's') { // zoom out
printf("keyboard: %c\n", key);
for (size_t i = 0; i < 3; i++)
view->eye_[i] -= forth[i];
glutPostRedisplay();
}
else if (key == 'd') { //move right
printf("keyboard: %c\n", key);
for (size_t i = 0; i < 3; i++)
view->eye_[i] += rSide[i];
glutPostRedisplay();
}
else if (key >= '1' && key <= '9') { // select n-th object
selectObjIndex = key - '1';
if (selectObjIndex >= scene->modelTotal_)
selectObjIndex = scene->modelTotal_ - 1;
cout << "selected object: " << selectObjIndex + 1 << endl;
}
}
void drag(int x, int y)
{
if (x > preMouseX) { // right
scene->modelList_[selectObjIndex].transfer_[0] += movObjUnit;
cout << "moving object " << selectObjIndex + 1 << " right" << endl;
}
else if (x < preMouseX) { // left
scene->modelList_[selectObjIndex].transfer_[0] -= movObjUnit;
cout << "moving object " << selectObjIndex + 1 << " left" << endl;
}
if (y < preMouseY) { // up
scene->modelList_[selectObjIndex].transfer_[1] += movObjUnit;
cout << "moving object " << selectObjIndex + 1 << " up" << endl;
}
else if (y > preMouseY) { // down
scene->modelList_[selectObjIndex].transfer_[1] -= movObjUnit;
cout << "moving object " << selectObjIndex + 1 << " down" << endl;
}
preMouseX = x;
preMouseY = y;
glutPostRedisplay();
}
|
#include<bits/stdc++.h>
using namespace std;
void count_sort(vector<int> &p, vector<int> &c){
int n = p.size();
vector<int> cnt(n);
for(auto x: c){
++cnt[x];
}
vector<int> p_new(n);
vector<int> pos(n);
pos[0]=0;
for(int i = 1; i<n; ++i){
pos[i] = pos[i-1] + cnt[i-1];
}
for(auto x: p){
int i = c[x];
p_new[pos[i]]=x;
++pos[i];
}
p = p_new;
}
void suffixAr(string s){
s+='$';
int n = s.size();
vector<int> p(n), c(n);
{
vector<pair<char,int>>a(n);
for(int i = 0; i<n; ++i) a[i]={s[i],i};
sort(a.begin(), a.end());
for(int i = 0; i<n; ++i) p[i]=a[i].second;
c[p[0]]=0;
for(int i = 1; i<n; ++i){
if(a[i].first == a[i-1].first){
c[p[i]] = c[p[i-1]];
}
else{
c[p[i]]= c[p[i-1]]+1;
}
}
}
int k = 0;
while((1<<k)<n){
for(int i = 0; i<n; ++i){
p[i] = (p[i]-(1<<k) + n)%n;
}
count_sort(p,c);
vector<int>c_new(n);
c_new[p[0]]=0;
for(int i = 1; i<n; ++i){
pair<int,int> prev = {c[p[i-1]],c[(p[i-1]+(1<<k))%n]};
pair<int,int> now = {c[p[i]],c[(p[i]+(1<<k))%n]};
if(now == prev){
c_new[p[i]] = c_new[p[i-1]];
}
else{
c_new[p[i]]= c_new[p[i-1]]+1;
}
}
c=c_new;
++k;
}
vector<int>lcp(n);
k = 0;
for(int i = 0; i<n-1; ++i){
int pi = c[i];
int j = p[pi-1];
while(s[i+k] == s[j+k]) ++k;
lcp[pi] = k;
k = max(k-1,0);
}
for(int i = 0; i<n; ++i){
cout<<lcp[i]<<" "<<p[i]<<" "<<" "<<s.substr(p[i],n-p[i])<<endl;
}
}
int main(){
string s;
cin>>s;
suffixAr(s);
return 0;
}
|
#include <stdio.h>
void main()
{
int grade;
printf("enter grade\n");
scanf("%d",&grade);
if (grade<=100 || grade>=90)
{
printf("letter grade is A\n");
}
if (grade<=89 || grade>=80)
{
printf("letter grade is B\n");
}
if (grade<80)
{
printf("the student bogo\n");
}
}
|
#include "Vna.h"
#include "RsibBus.h"
#include "VisaBus.h"
using namespace RsaToolbox;
#include <QDebug>
#include <QString>
#include <QtTest>
#include <QSignalSpy>
#include <QScopedPointer>
class test_VnaMarker : public QObject
{
Q_OBJECT
public:
test_VnaMarker();
private:
Vna vna;
// Object to test
QScopedPointer<Log> log;
int cycle;
QString appName;
QString appVersion;
QString filename;
QString logPath;
private Q_SLOTS:
void init();
void cleanup();
void createMarker();
void name();
void coordinates();
void max();
void min();
void searchRight();
void searchLeft();
void referenceMarker();
void delta();
//void measureBandpassFilter();
};
test_VnaMarker::test_VnaMarker() {
cycle = 0;
appName = "test_VnaMarker";
appVersion = "0";
filename = "%1 %2 Log.txt";
logPath = "../RsaToolboxTest/Results/VnaMarker Logs";
// Initialize object here
}
void test_VnaMarker::init() {
log.reset(new Log(logPath, filename.arg(cycle++).arg("init()"), appName, appVersion));
log->printApplicationHeader();
vna.resetBus(new RsibBus(TCPIP_CONNECTION, "127.0.0.1", 1000));
vna.useLog(log.data());
vna.printInfo();
vna.preset();
vna.clearStatus();
vna.disconnectLog();
}
void test_VnaMarker::cleanup() {
vna.disconnectLog();
log.reset(new Log(logPath, filename.arg(cycle++).arg("cleanup()"), appName, appVersion));
log->printApplicationHeader();
vna.useLog(log.data());
vna.printInfo();
// Specific cleanup
vna.clearStatus();
vna.resetBus();
vna.disconnectLog();
}
void test_VnaMarker::createMarker() {
log.reset(new Log(logPath, filename.arg(cycle++).arg("createMarker()"), appName, appVersion));
log->printApplicationHeader();
vna.useLog(log.data());
vna.printInfo();
QVERIFY(vna.trace().isNotMarkers());
vna.trace().createMarker(1);
QVERIFY(vna.trace().isMarker(1));
QVERIFY(vna.trace().isMarkers());
QVERIFY(vna.trace().markers().size() == 1);
vna.trace().createMarker();
QVERIFY(vna.trace().isMarker(2));
QVERIFY(vna.trace().isMarkers());
QVERIFY(vna.trace().markers().size() == 2);
vna.trace().deleteMarker(1);
QVERIFY(vna.trace().isNotMarker(1));
QVERIFY(vna.trace().isMarker(2));
QVERIFY(vna.trace().isMarkers());
QVERIFY(vna.trace().markers().size() == 1);
vna.trace().createMarker(3);
QVERIFY(vna.trace().isMarker(2));
QVERIFY(vna.trace().isMarker(3));
QVERIFY(vna.trace().markers().size() == 2);
vna.trace().deleteMarkers();
QVERIFY(vna.trace().isNotMarkers());
QVERIFY(vna.trace().markers().size() == 0);
QVERIFY(vna.isError() == false);
}
void test_VnaMarker::name() {
log.reset(new Log(logPath, filename.arg(cycle++).arg("name()"), appName, appVersion));
log->printApplicationHeader();
vna.useLog(log.data());
vna.printInfo();
vna.trace().createMarker(1);
QCOMPARE(vna.trace().marker(1).name(), QString("M1"));
vna.trace().marker(1).setName("myMarker");
QCOMPARE(vna.trace().marker(1).name(), QString("myMarker"));
QVERIFY(vna.isError() == false);
}
void test_VnaMarker::coordinates() {
log.reset(new Log(logPath, filename.arg(cycle++).arg("coordinates()"), appName, appVersion));
log->printApplicationHeader();
vna.useLog(log.data());
vna.printInfo();
vna.channel().linearSweep().setStart(1, GIGA_PREFIX);
vna.channel().linearSweep().setStop(2, GIGA_PREFIX);
vna.trace().createMarker(1);
vna.trace().marker(1).setX(1, GIGA_PREFIX);
QCOMPARE(vna.trace().marker(1).x(), double(1E9));
vna.trace().marker(1).setX(1.5, GIGA_PREFIX);
QCOMPARE(vna.trace().marker(1).x(), double(1.5E9));
double x, y;
vna.trace().marker(1).setX(1.75E9);
vna.trace().marker(1).coordinates(x, y);
QCOMPARE(x, double(1.75E9));
QVERIFY(vna.isError() == false);
}
void test_VnaMarker::max() {
log.reset(new Log(logPath, filename.arg(cycle++).arg("max()"), appName, appVersion));
log->printApplicationHeader();
vna.useLog(log.data());
vna.printInfo();
vna.channel().manualSweepOn();
vna.startSweeps();
vna.wait();
vna.trace().createMarker(1);
vna.trace().marker(1).searchForMax();
double x, y;
vna.trace().marker(1).coordinates(x, y);
// How to verify?
vna.trace().createMarker(2);
vna.trace().marker(2).searchForMin();
QVERIFY(vna.trace().marker(1).x() != vna.trace().marker(2).x());
QVERIFY(vna.trace().marker(1).y() > vna.trace().marker(2).y());
QVERIFY(vna.isError() == false);
}
void test_VnaMarker::min() {
log.reset(new Log(logPath, filename.arg(cycle++).arg("min()"), appName, appVersion));
log->printApplicationHeader();
vna.useLog(log.data());
vna.printInfo();
vna.channel().manualSweepOn();
vna.startSweeps();
vna.wait();
vna.trace().createMarker(1);
vna.trace().marker(1).searchForMin();
double x, y;
vna.trace().marker(1).coordinates(x, y);
// How to verify?
vna.trace().createMarker(2);
vna.trace().marker(2).searchForMax();
QVERIFY(vna.trace().marker(1).x() != vna.trace().marker(2).x());
QVERIFY(vna.trace().marker(1).y() < vna.trace().marker(2).y());
QVERIFY(vna.isError() == false);
}
void test_VnaMarker::searchRight() {
log.reset(new Log(logPath, filename.arg(cycle++).arg("searchRight()"), appName, appVersion));
log->printApplicationHeader();
vna.useLog(log.data());
vna.printInfo();
vna.channel().manualSweepOn();
vna.startSweeps();
vna.wait();
double max;
vna.trace().createMarker(1);
vna.trace().marker(1).searchForMax();
max = vna.trace().marker(1).y();
double min;
vna.trace().marker(1).searchForMin();
min = vna.trace().marker(1).y();
vna.trace().marker(1).setX(vna.channel().linearSweep().start_Hz());
vna.trace().marker(1).searchRightFor((max - min)/2.0 + min);
QCOMPARE(vna.trace().marker(1).y(), (max - min)/2.0 + min);
vna.trace().marker(1).setX(vna.channel().linearSweep().start_Hz());
vna.trace().marker(1).searchRightForPeak();
double x, y;
vna.trace().marker(1).coordinates(x, y);
// How to verify?
QVERIFY(vna.isError() == false);
}
void test_VnaMarker::searchLeft() {
log.reset(new Log(logPath, filename.arg(cycle++).arg("searchLeft()"), appName, appVersion));
log->printApplicationHeader();
vna.useLog(log.data());
vna.printInfo();
vna.channel().manualSweepOn();
vna.startSweeps();
vna.wait();
double max;
vna.trace().createMarker(1);
vna.trace().marker(1).searchForMax();
max = vna.trace().marker(1).y();
double min;
vna.trace().marker(1).searchForMin();
min = vna.trace().marker(1).y();
vna.trace().marker(1).setX(vna.channel().linearSweep().stop_Hz());
vna.trace().marker(1).searchLeftFor((max - min)/2.0 + min);
QCOMPARE(vna.trace().marker(1).y(), (max - min)/2.0 + min);
vna.trace().marker(1).setX(vna.channel().linearSweep().stop_Hz());
vna.trace().marker(1).searchLeftForPeak();
double x, y;
vna.trace().marker(1).coordinates(x, y);
// How to verify?
QVERIFY(vna.isError() == false);
}
void test_VnaMarker::referenceMarker() {
log.reset(new Log(logPath, filename.arg(cycle++).arg("referenceMarker()"), appName, appVersion));
log->printApplicationHeader();
vna.useLog(log.data());
vna.printInfo();
vna.channel().manualSweepOn();
vna.startSweeps();
vna.wait();
QVERIFY(vna.trace().referenceMarker().isOff());
vna.trace().referenceMarker().on();
QVERIFY(vna.trace().referenceMarker().isOn());
vna.trace().createMarker(1);
vna.trace().marker(1).searchForMax();
vna.trace().marker(1).setReferenceMarker();
QCOMPARE(vna.trace().referenceMarker().x(), vna.trace().marker(1).x());
QCOMPARE(vna.trace().referenceMarker().y(), vna.trace().marker(1).y());
QVERIFY(vna.isError() == false);
}
void test_VnaMarker::delta() {
log.reset(new Log(logPath, filename.arg(cycle++).arg("delta()"), appName, appVersion));
log->printApplicationHeader();
vna.useLog(log.data());
vna.printInfo();
vna.channel().manualSweepOn();
vna.startSweeps();
vna.wait();
double min;
vna.trace().createMarker(1);
vna.trace().marker(1).searchForMin();
min = vna.trace().marker(1).y();
vna.trace().referenceMarker().on();
vna.trace().marker(1).setReferenceMarker();
double max;
vna.trace().marker(1).searchForMax();
max = vna.trace().marker(1).y();
QVERIFY(vna.trace().marker(1).isDeltaOff());
vna.trace().marker(1).deltaOn();
QVERIFY(vna.trace().marker(1).isDeltaOn());
QCOMPARE(vna.trace().marker(1).y(), max - min);
QVERIFY(vna.isError() == false);
}
QTEST_APPLESS_MAIN(test_VnaMarker)
#include "test_VnaMarker.moc"
|
#pragma once
#include <iterator>
template <class InIt>
void Insert(InIt itLow, InIt curIt)
{
if (curIt == itLow)
{
return;
}
int inserted = *curIt;
for (; curIt != itLow && inserted < *(curIt - 1); --curIt)
{
*curIt = *(curIt - 1);
}
*curIt = inserted;
}
template <class InIt>
void InsertSort( InIt itLow, InIt itHight)
{
for (InIt curIt = itLow + 1; curIt != itHight; ++curIt)
{
Insert(itLow, curIt);
}
}
|
namespace meta {
namespace ptr {
template<typename T>
struct is_ptr {
static constexpr value = 0;
};
template<typename T>
struct is_ptr<T*> {
static constexpr value = 1;
};
template<typename T>
struct remove_ptr {
using type = T;
};
template<typename T>
struct remove_ptr<T*> {
using type = T;
};
}
}
|
# include<iostream>
using namespace std;
// 标识符命名规则
// 1 标识符不可以是关键字
// 2 标识符是由字母 数字 下划线构成
// 3 标识符第一个字符只能是字母或下划线
// 4 标识符是区分大小写的
// 建议 给变量起名的时候 最好能够做到见名知意
int main2() {
return 0;
}
|
#ifndef _INPUTS_H_
#define _INPUTS_H_
#include "stdafx.h"
#include "macros.h"
#define FOREACH_INPUT_CONFIG(INPUT_CONFIG) \
INPUT_CONFIG(INPUT_ASYNC_KEY_STATE) \
INPUT_CONFIG(INPUT_DIRECT)
enum INPUT_CONFIG_ENUM {
FOREACH_INPUT_CONFIG(GENERATE_ENUM)
};
static const char *INPUT_CONFIG_ENUM_STRING[] = {
FOREACH_INPUT_CONFIG(GENERATE_STRING)
};
#define FOREACH_INPUT_MANAGER(INPUT) \
INPUT(P1_START) \
INPUT(P1_COIN) \
INPUT(P1_SERVICE) \
INPUT(P1_UP) \
INPUT(P1_DOWN) \
INPUT(P1_LEFT) \
INPUT(P1_RIGHT) \
INPUT(P1_BUTTON_1) \
INPUT(P1_BUTTON_2) \
INPUT(P1_BUTTON_3) \
INPUT(P1_BUTTON_4) \
INPUT(P1_BUTTON_5) \
INPUT(P1_BUTTON_6) \
INPUT(P2_START) \
INPUT(P2_COIN) \
INPUT(P2_SERVICE) \
INPUT(P2_UP) \
INPUT(P2_DOWN) \
INPUT(P2_LEFT) \
INPUT(P2_RIGHT) \
INPUT(P2_BUTTON_1) \
INPUT(P2_BUTTON_2) \
INPUT(P2_BUTTON_3) \
INPUT(P2_BUTTON_4) \
INPUT(P2_BUTTON_5) \
INPUT(P2_BUTTON_6) \
INPUT(TEST_MODE) \
INPUT(EXIT_CODE) \
INPUT(TEST_TILT1) \
INPUT(TEST_TILT2) \
INPUT(TEST_TILT3) \
INPUT(_SIZE_)
enum INPUT_MANAGER_ENUM {
FOREACH_INPUT_MANAGER(GENERATE_ENUM)
};
static const char *INPUT_MANAGER_ENUM_STRING[] = {
FOREACH_INPUT_MANAGER(GENERATE_STRING)
};
class InputConfig {
public:
InputConfig();
~InputConfig();
INPUT_CONFIG_ENUM toEnum(std::string str);
private:
unordered_map<std::string, INPUT_CONFIG_ENUM> mapStringEnumInput = {
{INPUT_CONFIG_ENUM_STRING[0], INPUT_ASYNC_KEY_STATE},
{INPUT_CONFIG_ENUM_STRING[1], INPUT_DIRECT}
};
/*
unordered_map<std::string, INPUT_MANAGER_ENUM> mapStringEnumInput = {
{INPUT_MANAGER_ENUM_STRING[0], P1_START},
{INPUT_MANAGER_ENUM_STRING[1], P1_COIN},
{INPUT_MANAGER_ENUM_STRING[2], P1_SERVICE},
{INPUT_MANAGER_ENUM_STRING[3], P1_UP},
{INPUT_MANAGER_ENUM_STRING[4], P1_DOWN},
{INPUT_MANAGER_ENUM_STRING[5], P1_LEFT},
{INPUT_MANAGER_ENUM_STRING[6], P1_RIGHT},
{INPUT_MANAGER_ENUM_STRING[7], P1_BUTTON_1},
{INPUT_MANAGER_ENUM_STRING[8], P1_BUTTON_2},
{INPUT_MANAGER_ENUM_STRING[9], P1_BUTTON_3},
{INPUT_MANAGER_ENUM_STRING[10], P1_BUTTON_4},
{INPUT_MANAGER_ENUM_STRING[11], P1_BUTTON_5},
{INPUT_MANAGER_ENUM_STRING[12], P1_BUTTON_6},
{INPUT_MANAGER_ENUM_STRING[13], P2_START},
{INPUT_MANAGER_ENUM_STRING[14], P2_COIN},
{INPUT_MANAGER_ENUM_STRING[15], P2_SERVICE},
{INPUT_MANAGER_ENUM_STRING[16], P2_UP},
{INPUT_MANAGER_ENUM_STRING[17], P2_DOWN},
{INPUT_MANAGER_ENUM_STRING[18], P2_LEFT},
{INPUT_MANAGER_ENUM_STRING[19], P2_RIGHT},
{INPUT_MANAGER_ENUM_STRING[20], P2_BUTTON_1},
{INPUT_MANAGER_ENUM_STRING[21], P2_BUTTON_2},
{INPUT_MANAGER_ENUM_STRING[22], P2_BUTTON_3},
{INPUT_MANAGER_ENUM_STRING[23], P2_BUTTON_4},
{INPUT_MANAGER_ENUM_STRING[24], P2_BUTTON_5},
{INPUT_MANAGER_ENUM_STRING[25], P2_BUTTON_6},
{INPUT_MANAGER_ENUM_STRING[26], TEST_MODE},
{INPUT_MANAGER_ENUM_STRING[27], EXIT_CODE},
{INPUT_MANAGER_ENUM_STRING[28], TEST_TILT1},
{INPUT_MANAGER_ENUM_STRING[29], TEST_TILT2},
{INPUT_MANAGER_ENUM_STRING[30], TEST_TILT3}
};
*/
};
#endif
|
//
// State.cpp
// Landru
//
// Created by Nick Porcino on 10/28/14.
//
//
#include "State.h"
#include "FnContext.h"
#include "LandruActorVM/VMContext.h"
#include <cstdint>
#include <cstdio>
namespace Landru {
uint32_t Meta::globalAddr = 0;
void Meta::exec(FnContext& run) const
{
std::cout << addr << ": " << str << std::endl;
if (run.vm->breakPoint == addr) {
std::cout << "Break hit" << std::endl;
}
}
}
|
#include<iostream>
#include<stdio.h>
using namespace std;
int main(){
long long int L, N;
long long int area, saida, tapetemax, numtapete;
cin >> L >> N;
numtapete = N - 1;
tapetemax = L - numtapete;
area = tapetemax * tapetemax;
saida = area + numtapete;
cout << saida;
return 0;
}
|
// I initially based this on
// https://blog.forrestthewoods.com/reverse-engineering-sublime-text-s-fuzzy-match-4cffeed33fdb
// https://medium.com/@Srekel/implementing-a-fuzzy-search-algorithm-for-the-debuginator-cacc349e6c55
// and ended up rewriting pretty much all of it from scrach to improve performance
// and changed match scores to fit my needs
#pragma once
#include <algorithm>
#include <string_view>
#include <type_traits>
#include <vector>
namespace FuzzySearch
{
struct PatternMatch
{
int m_Score = 0;
std::vector<int> m_Matches;
};
/*
* InputPattern struct contains small helper buffers to avoid reallocating inside FuzzyMatch.
*
* If you are going to search for the same pattern in multiple different strings
* reuse the same instance of InputPattern for every search instead of recreating it.
*/
struct InputPattern
{
explicit InputPattern(std::string_view pattern)
: m_Pattern(pattern)
{
m_PatternMatches.resize(pattern.length());
m_MatchIndexes.resize(pattern.length());
}
std::string_view m_Pattern;
std::vector<PatternMatch> m_PatternMatches;
std::vector<int> m_MatchIndexes;
};
struct SearchResult
{
std::string_view m_String;
PatternMatch m_PatternMatch;
};
enum class MatchMode
{
E_STRINGS,
E_FILENAMES,
E_SOURCE_FILES
};
constexpr size_t max_pattern_length = 1024;
PatternMatch FuzzyMatch(InputPattern& input_pattern, std::string_view str, MatchMode match_mode);
bool SearchResultComparator(const SearchResult& lhs, const SearchResult& rhs) noexcept;
template <typename Iterator, typename Func>
std::vector<SearchResult> Search(std::string_view pattern, Iterator&& begin, Iterator&& end, Func&& get_string_func, MatchMode match_mode)
{
static_assert(
std::is_invocable_r<std::string_view, decltype(get_string_func), typename std::iterator_traits<Iterator>::value_type>::value,
"get_string_func needs to be a pointer to function returning std::string_view");
if (pattern.empty())
{
return {};
}
else if (pattern.length() >= max_pattern_length)
{
pattern = pattern.substr(0, max_pattern_length);
}
std::vector<SearchResult> search_results;
search_results.reserve(std::distance(begin, end) / 2);
InputPattern input_pattern(pattern);
std::for_each(begin, end, [&input_pattern, &get_string_func, match_mode, &search_results](const auto& element) {
SearchResult search_result;
search_result.m_String = get_string_func(element);
search_result.m_PatternMatch = FuzzyMatch(input_pattern, search_result.m_String, match_mode);
if (search_result.m_PatternMatch.m_Score > 0)
{
search_results.push_back(search_result);
}
});
std::sort(search_results.begin(), search_results.end(), SearchResultComparator);
return search_results;
}
} // namespace FuzzySearch
|
// Created on: 2000-05-10
// Created by: Andrey BETENEV
// Copyright (c) 2000-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 _StepBasic_ExternalIdentificationAssignment_HeaderFile
#define _StepBasic_ExternalIdentificationAssignment_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <StepBasic_IdentificationAssignment.hxx>
class StepBasic_ExternalSource;
class TCollection_HAsciiString;
class StepBasic_IdentificationRole;
class StepBasic_ExternalIdentificationAssignment;
DEFINE_STANDARD_HANDLE(StepBasic_ExternalIdentificationAssignment, StepBasic_IdentificationAssignment)
//! Representation of STEP entity ExternalIdentificationAssignment
class StepBasic_ExternalIdentificationAssignment : public StepBasic_IdentificationAssignment
{
public:
//! Empty constructor
Standard_EXPORT StepBasic_ExternalIdentificationAssignment();
//! Initialize all fields (own and inherited)
Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aIdentificationAssignment_AssignedId, const Handle(StepBasic_IdentificationRole)& aIdentificationAssignment_Role, const Handle(StepBasic_ExternalSource)& aSource);
//! Returns field Source
Standard_EXPORT Handle(StepBasic_ExternalSource) Source() const;
//! Set field Source
Standard_EXPORT void SetSource (const Handle(StepBasic_ExternalSource)& Source);
DEFINE_STANDARD_RTTIEXT(StepBasic_ExternalIdentificationAssignment,StepBasic_IdentificationAssignment)
protected:
private:
Handle(StepBasic_ExternalSource) theSource;
};
#endif // _StepBasic_ExternalIdentificationAssignment_HeaderFile
|
#include <iostream>
#include <cstring>
#include <vector>
const int MAX = 101;
int n, m, d[MAX];
std::vector<int> list[MAX];
bool check[MAX];
bool dfs(int person)
{
for(int notebook : list[person])
{
if(check[notebook])
{
continue;
}
check[notebook] = 1;
if(d[notebook] == 0 || dfs(d[notebook]))
{
d[notebook] = person;
return 1;
}
}
return 0;
}
int main()
{
std::cin.sync_with_stdio(false);
std::cin.tie(NULL);
std::cin >> n >> m;
for(int i = 1; i <= m; i++)
{
int a, b;
std::cin >> a >> b;
list[a].push_back(b);
}
int ans = 0;
for(int i = 1; i <= n; i++)
{
std::memset(check, 0, sizeof(check));
if(dfs(i))
{
ans++;
}
}
std::cout << ans << '\n';
return 0;
}
|
#include<iostream>
using namespace std;
// LEFT ROTATE THE ELEMENT BY 1
// PARAMETERS : ARRAY, LENGHT OF ARRAY
void leftRotateByOne(int arr[],int lenghtOfArray){
int temp = arr[0];
for(int elem=0;elem<lenghtOfArray-1;elem++){
arr[elem] = arr[elem+1];
}
arr[lenghtOfArray-1]= temp;
}
// WILL PRINT THE FULL ARRAY.
// PARAMETERS : ARRAY, LENGHT OF ARRAY
void printFullArray(int arr[],int lengthOfArray){
for(int elem=0;elem<lengthOfArray;elem++){
cout<<arr[elem]<<" ";
}
}
// LEFT ROTATE FUNCTION
// PARAMETERS : ARRAY, NO. OF ROTATTIONS ,LENGHT OF ARRAY
void leftRotate(int arr[],int noOfTimesToRotate,int lengthOfArray){
for(int elem=0;elem<noOfTimesToRotate;elem++){
leftRotateByOne(arr,lengthOfArray);
}
printFullArray(arr,lengthOfArray);
}
// MAIN FUNCTION
int main(){
int arr[]={1,2,3,4,5};
int lengthOfArray = sizeof(arr)/sizeof(arr[0]);
leftRotate(arr,2,lengthOfArray);
return 0;
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e10
#define REP(i,n) for(int i=0; i<n; i++)
#define REP_R(i,n,m) for(int i=m; i<n; i++)
#define MAX 100
int gcd(int x, int y);
int main() {
int a,b;
cin >> a >> b;
cout << gcd(a,b) << endl;
}
// x > y
int gcd(int x, int y) {
if (y == 0) return x;
int amari = x % y;
return gcd(y, amari);
}
|
/* -*- 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 "adjunct/desktop_util/opfile/desktop_opfile.h"
#include "adjunct/desktop_util/transactions/CreateFileOperation.h"
CreateFileOperation::PathComponent::PathComponent(OpString& component)
{
m_component.TakeOver(component);
}
const OpStringC& CreateFileOperation::PathComponent::Get() const
{
return m_component;
}
CreateFileOperation::CreateFileOperation(const OpFile& file,
OpFileInfo::Mode file_mode)
: m_file_mode(file_mode)
{
const OP_STATUS copied = m_file.Copy(&file);
OP_ASSERT(OpStatus::IsSuccess(copied) || !"Could not create OpFile copy");
}
OP_STATUS CreateFileOperation::Do()
{
m_components.Clear();
// Determine the chances that this operation will succeed.
BOOL exists = FALSE;
RETURN_IF_ERROR(m_file.Exists(exists));
if (exists)
{
OpFileInfo::Mode mode = OpFileInfo::NOT_REGULAR;
RETURN_IF_ERROR(m_file.GetMode(mode));
if (mode != m_file_mode)
{
return OpStatus::ERR;
}
if (!m_file.IsWritable())
{
return OpStatus::ERR;
}
}
// Find out what path components (directories) will be created if this
// operation succeeds.
OpFile dir;
RETURN_IF_ERROR(dir.Copy(&m_file));
BOOL dir_exists = FALSE;
while (!dir_exists)
{
OpString path;
RETURN_IF_ERROR(dir.GetDirectory(path));
OP_ASSERT(path.HasContent()
|| !"This loop needs another stop condition");
RETURN_IF_ERROR(dir.Construct(path));
RETURN_IF_ERROR(dir.Exists(dir_exists));
if (dir_exists)
{
// Bail out if the current path component names an existing file.
OpFileInfo::Mode mode = OpFileInfo::NOT_REGULAR;
RETURN_IF_ERROR(dir.GetMode(mode));
if (OpFileInfo::DIRECTORY != mode)
{
return OpStatus::ERR;
}
}
else
{
// OpFile::GetDirectory() doesn't work as advertised on UNIX. Need to
// remove any trailing path separators.
if (path.HasContent() && PATHSEPCHAR == path[path.Length() - 1])
{
path.Delete(path.Length() - 1);
}
RETURN_IF_ERROR(dir.Construct(path));
PathComponent* component = OP_NEW(PathComponent, (path));
RETURN_OOM_IF_NULL(component);
component->Into(&m_components);
}
}
return OpStatus::OK;
}
void CreateFileOperation::Undo()
{
OpStatus::Ignore(m_file.Close());
if (OpFileInfo::DIRECTORY == m_file_mode)
{
OpStatus::Ignore(DeleteDirIfEmpty(m_file.GetFullPath()));
}
else
{
OpStatus::Ignore(m_file.Delete(FALSE));
}
for (PathComponent* component = m_components.First(); NULL != component;
component = component->Suc())
{
OpStatus::Ignore(DeleteDirIfEmpty(component->Get()));
}
}
OP_STATUS CreateFileOperation::DeleteDirIfEmpty(const OpStringC& path)
{
BOOL dir_empty = FALSE;
const OP_STATUS status = DesktopOpFileUtils::IsFolderEmpty(path, dir_empty);
if (OpStatus::ERR_FILE_NOT_FOUND == status)
{
// This can happen when the original file path had a trailing separator.
return OpStatus::OK;
}
RETURN_IF_ERROR(status);
if (dir_empty)
{
OpFile dir;
RETURN_IF_ERROR(dir.Construct(path));
RETURN_IF_ERROR(dir.Delete(FALSE));
}
return OpStatus::OK;
}
const OpFile& CreateFileOperation::GetFile() const
{
return m_file;
}
OpFileInfo::Mode CreateFileOperation::GetFileMode() const
{
return m_file_mode;
}
const CreateFileOperation::PathComponentList&
CreateFileOperation::GetPathComponents() const
{
return m_components;
}
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
//
// Copyright (C) 1995-2004 Opera Software AS. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
#ifndef BT_GLOBALS_H
#define BT_GLOBALS_H
// ----------------------------------------------------
#include "adjunct/m2/src/engine/module.h"
#include "adjunct/m2/src/util/buffer.h"
#include "adjunct/desktop_util/adt/oplist.h"
#include "modules/util/OpHashTable.h"
#include "modules/util/adt/opvector.h"
#include <openssl/evp.h>
#include <openssl/sha.h>
//#include "bt-info.h"
//#define BT_FILELOGGING_ENABLED // only enabled if set in the opera6.ini file
#define BT_UPLOAD_DESTRICTION // when defined, will enforce a dynamic upload speed restriction (if enabled in prefs)
#define BT_UPLOAD_FIXED_RESTRICTION
//#define BT_UPLOAD_DISABLED // when defined, will not create a listening socket
//#define DEBUG_BT_TRANSFERPANEL // used in retail builds to add information to the transfer panel
#ifndef _MACINTOSH_
#ifdef _DEBUG
#define DEBUG_BT_TORRENT
#define DEBUG_BT_RESOURCE_TRACKING
//#define DEBUG_BT_RESOURCES
//#define DEBUG_BT_UPLOAD
//#define DEBUG_BT_DOWNLOAD
//#define DEBUG_BT_PROFILING
//#define DEBUG_BT_FILEPROFILING
#define DEBUG_BT_FILEACCESS
//#define DEBUG_BT_HAVE
//#define DEBUG_BT_CHOKING
#define DEBUG_BT_TRACKER
//#define DEBUG_BT_SOCKETS
//#define DEBUG_BT_THROTTLE
//#define DEBUG_BT_BLOCKSELECTION
//#define DEBUG_BT_PEERSPEED
//#define DEBUG_BT_CONNECT
//#define DEBUG_BT_DISKCACHE
#endif
#endif
class P2PFilePartPool;
class Transfers;
class BTServerConnector;
class BTPacketPool;
class Downloads;
class BTFileLogging;
class P2PFiles;
class BTInfo;
class BTResourceTracker;
class P2PGlobalData
{
public:
OP_STATUS Init();
void Destroy();
P2PFilePartPool *m_P2PFilePartPool;
BTPacketPool *m_PacketPool;
Transfers *m_Transfers;
BTServerConnector *m_BTServerConnector;
Downloads *m_Downloads;
P2PFiles *m_P2PFiles;
OpVector<BTInfo> m_PendingInfos;
#if defined(_DEBUG) && defined (MSWIN) && defined(DEBUG_BT_RESOURCE_TRACKING)
BTResourceTracker *m_BTResourceTracker;
#endif
#if defined(BT_FILELOGGING_ENABLED)
BTFileLogging *m_BTFileLogging;
#endif
};
#define g_BTResourceTracker g_P2PGlobalData.m_BTResourceTracker
#define g_Transfers g_P2PGlobalData.m_Transfers
#define g_BTServerConnector g_P2PGlobalData.m_BTServerConnector
#define g_Downloads g_P2PGlobalData.m_Downloads
#define g_PacketPool g_P2PGlobalData.m_PacketPool
#define g_P2PFilePartPool g_P2PGlobalData.m_P2PFilePartPool
#define g_BTFileLogging g_P2PGlobalData.m_BTFileLogging
#define g_P2PFiles g_P2PGlobalData.m_P2PFiles
#define g_PendingInfos g_P2PGlobalData.m_PendingInfos
#if defined(_DEBUG) && defined (MSWIN) && defined(DEBUG_BT_RESOURCE_TRACKING)
#define BT_RESOURCE_ADD(x, y) if(g_BTResourceTracker) g_BTResourceTracker->Add(UNI_L(x), (void *)y, __FILE__, __LINE__)
#define BT_RESOURCE_REMOVE(x) if(g_BTResourceTracker) g_BTResourceTracker->Remove((void *)x)
#define BT_RESOURCE_CHECKPOINT(x) if(g_BTResourceTracker) g_BTResourceTracker->Checkpoint(x)
#else
#define BT_RESOURCE_ADD(x, y)
#define BT_RESOURCE_REMOVE(x)
#define BT_RESOURCE_CHECKPOINT(x)
#endif
#endif // BT_GLOBALS_H
|
#include "ModifierGroup.h"
// -----------------------------------------------------------------------------
// CONSTRUCTOR
// -----------------------------------------------------------------------------
ModifierGroup::ModifierGroup()
{
this->show();
this->enabled(true);
}
ModifierGroup::~ModifierGroup()
{
for (std::vector<Modifier *>::iterator it = this->modifiers_.begin(); it != this->modifiers_.end(); ++it)
delete (*it);
}
// -----------------------------------------------------------------------------
// GETTERS
// -----------------------------------------------------------------------------
bool ModifierGroup::enabled()
{
return this->enabled_;
}
Modifier *ModifierGroup::modifier_at(unsigned int index)
{
return this->modifiers_[index];
}
unsigned int ModifierGroup::modifiers_count()
{
return (unsigned int) this->modifiers_.size();
}
// -----------------------------------------------------------------------------
// SETTERS
// -----------------------------------------------------------------------------
void ModifierGroup::enabled(bool status)
{
this->enabled_ = status;
}
void ModifierGroup::add_modifier(Modifier *modifier)
{
this->modifiers_.push_back(modifier);
}
void ModifierGroup::delete_modifier_at(unsigned int i)
{
delete this->modifier_at(i);
this->modifiers_.erase(this->modifiers_.begin() + i);
}
// -----------------------------------------------------------------------------
// METHODS
// -----------------------------------------------------------------------------
void ModifierGroup::apply()
{
for (unsigned int i = 0; i < this->modifiers_count(); ++i)
{
if (modifier_at(i)->enabled())
this->modifier_at(i)->apply();
}
}
void ModifierGroup::update()
{
for (unsigned int i = 0; i < this->modifiers_count(); ++i)
this->modifier_at(i)->update();
}
void ModifierGroup::show()
{
this->enabled(true);
for (unsigned int i = 0; i < this->modifiers_count(); ++i)
{
this->modifier_at(i)->show();
}
}
void ModifierGroup::hide()
{
this->enabled(false);
for (unsigned int i = 0; i < this->modifiers_count(); ++i)
{
this->modifier_at(i)->hide();
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 1995-2005 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#include "modules/display/opscreenpropertiescache.h"
#include "modules/pi/OpScreenInfo.h"
OpScreenPropertiesCache::OpScreenPropertiesCache()
: cachedForWindow(NULL)
, dirty(TRUE) //we dont have anything yet!
{
}
OpScreenProperties* OpScreenPropertiesCache::getProperties(OpWindow* window, OpPoint* point)
{
if(dirty || window != cachedForWindow || point){
//if window have changed, disconenct from old
cachedForWindow = window;
//get properties to cache
g_op_screen_info->GetProperties(&cachedProperties, cachedForWindow, point);
dirty = FALSE;
}
//return cached properties
return &cachedProperties;
}
UINT32 OpScreenPropertiesCache::getHorizontalDpi(OpWindow* window, OpPoint* point)
{
#ifdef STATIC_GLOBAL_SCREEN_DPI
return STATIC_GLOBAL_SCREEN_DPI_VALUE;
#else
return getProperties(window, point)->horizontal_dpi;
#endif
}
UINT32 OpScreenPropertiesCache::getVerticalDpi(OpWindow* window, OpPoint* point)
{
#ifdef STATIC_GLOBAL_SCREEN_DPI
return STATIC_GLOBAL_SCREEN_DPI_VALUE;
#else
return getProperties(window, point)->vertical_dpi;
#endif
}
void OpScreenPropertiesCache::markPropertiesAsDirty()
{
dirty = TRUE;
}
|
#include"matrix07.h"
#include<vector>
#include<cmath>
#include<gtest/gtest.h>
TEST(MulTest, meaningful) {
std::vector<std::vector<int>> left = {
{11, 12, 13, 14},
{21, 22, 23, 24},
{31, 32, 33, 34}
};
std::vector<std::vector<int>> right;
right.resize(4, std::vector<int>(3, 1.));
std::vector<std::vector<int>> expected = {
{50, 50, 50},
{90, 90, 90},
{130, 130, 130}
};
szeMatrix::Matrix<int> m1(left);
szeMatrix::Matrix<int> m2(right);
szeMatrix::Matrix<int> multiplied = m1.mul(m2);
ASSERT_EQ(expected.size(), multiplied.getRowCount());
ASSERT_EQ(expected[0].size(), multiplied.getColCount());
for(unsigned row=0; row<expected.size(); row++) {
for(unsigned col=0; col<expected[row].size(); col++) {
EXPECT_EQ(expected[row][col], multiplied.get(row, col));
}
}
}
TEST(MulTest, equality) {
std::vector<std::vector<double>> left = {
{11, 12, 13, 14},
{21, 22, 23, 24},
{31, 32, 33, 34}
};
std::vector<std::vector<double>> right;
right.resize(4, std::vector<double>(3, 1.));
std::vector<std::vector<double>> expected = {
{50, 50, 50},
{90, 90, 90},
{130, 130, 130}
};
szeMatrix::Matrix<double> m1(left);
szeMatrix::Matrix<double> m2(right);
szeMatrix::Matrix<double> mexp(expected);
szeMatrix::Matrix<double> multiplied = m1.mul(m2);
ASSERT_EQ(mexp.getRowCount(), multiplied.getRowCount());
ASSERT_EQ(mexp.getColCount(), multiplied.getColCount());
ASSERT_EQ(mexp, multiplied);
}
TEST(MulTest, rounding) {
std::vector<std::vector<double>> left = {
{sqrt(2.), 0.},
{0., 1./3.}
};
std::vector<std::vector<double>> right;
right.resize(2, std::vector<double>(2, 1.));
std::vector<std::vector<double>> expected = {
{1.414213562, 1.414213562},
{0.333333333, 0.333333333}
};
szeMatrix::Matrix<double> m1(left);
szeMatrix::Matrix<double> m2(right);
szeMatrix::Matrix<double> multiplied = m1.mul(m2);
ASSERT_EQ(expected.size(), multiplied.getRowCount());
ASSERT_EQ(expected[0].size(), multiplied.getColCount());
for(unsigned row=0; row<expected.size(); row++) {
for(unsigned col=0; col<expected[row].size(); col++) {
EXPECT_NEAR(expected[row][col], multiplied.get(row, col), 1e-9);
}
}
}
|
//
// Vector3D.h
// GLFW3
//
// Created by William Meaton on 07/12/2015.
// Copyright © 2015 WillMeaton.uk. All rights reserved.
#ifndef Vector3D_h
#define Vector3D_h
//A 3D vector, missing some operators but not really used in my program.
namespace Math {
class Vector3D{
public:
float x, y, z;
Vector3D(float x, float y, float z){
this->x = x;
this->y = y;
this->z = z;
}
Vector3D(){}
~Vector3D(){};
inline friend bool operator== (const Vector3D& v1, const Vector3D& v2){
if(v1.x == v2.x && v1.y == v2.y && v1.z == v2.z){
return true;
}
return false;
}
inline friend bool operator!= (const Vector3D& v1, const Vector3D& v2){
return !(v1 == v2);
}
inline friend void operator+= (Vector3D& v1, Vector3D& v2){
v1.x = v1.x + v2.x;
v1.y = v1.y + v2.y;
v1.z = v1.z + v1.z;
return;
}
inline Vector3D& operator+ (const Vector3D& v){
this->x += v.x;
this->y += v.y;
this->z += v.z;
return *this;
}
inline Vector3D& operator= (const Vector3D& v){
this->x = v.x;
this->y = v.y;
this->z = v.z;
return *this;
}
inline Vector3D& operator*(const Vector3D& v){
this->x *= v.x;
this->y *= v.y;
this->z *= v.z;
return *this;
}
inline Vector3D& operator- (const Vector3D& v) {
this->x -= v.x;
this->y -= v.y;
this->z -= v.z;
return *this;
}
inline Vector3D& operator/ (const Vector3D& v) {
this->x /= v.x;
this->y /= v.y;
this->z /= v.z;
return *this;
}
};
}
#endif /* Vector3D_h */
|
#include "utility/file.hpp"
#include "utility/tcp.h"
#include "utility/raii.hpp"
#include "utility/encryption.h"
#include <algorithm>
using std::experimental::string_view;
using namespace std;
void cut_string (std::vector<string_view>& result, string_view origin, string_view delim)
{
result.clear();
auto it = origin.begin ();
while (it != origin.end ())
{
auto pos = search (it, origin.end (), delim.begin (), delim.end ());
if (pos != it)
{
result.emplace_back (it, pos - it);
if (pos == origin.end ())
{
break;
}
}
it = (pos + static_cast<signed> (delim.length ()));
}
}
int main ()
{
auto conn = "www.baidu.com"_tcp[80];
if (!conn)
{
std::cout << "cannot connect";
return 0;
}
conn.writen ("GET / HTTP/1.0\r\n\r\n");
std::string header;
header.resize (8192);
auto len = conn.read_until(header, "\r\n\r\n");
if (len <= 0)
{
std::cout << "read until error";
return 0;
}
auto u_len = static_cast<unsigned> (len);
header.resize (u_len);
std::vector<string_view> vec_str;
cut_string (vec_str, header, "\r\n");
int i = 0;
for (auto & it : vec_str)
{
i ++;
std::cout << "line:" << i << " " << it << '\n';
}
if (!vec_str.empty ())
{
vec_str.erase(vec_str.begin ());
}
std::cout << '\n' << '\n';
std::map<std::string, std::string> header_kv;
for (auto & view :vec_str)
{
std::vector<string_view> kv;
cut_string (kv, view, ": ");
if (kv.size () == 2)
{
header_kv [kv.at(0).to_string ()] = kv.at(1).to_string ();
}
}
for (auto & it : header_kv)
{
std::cout << "key:" << it.first << " value:" << it.second << '\n';
}
auto content_length = header_kv.find ("Content-Length");
if (content_length == header_kv.end ())
{
std::cout << "no content length";
return 0;
}
auto length = std::stol (content_length->second);
std::cout << "Content-Length is " << length << '\n';
if (length < 0)
{
std::cout << "length < 0\n";
return 0;
}
auto u_length = static_cast<unsigned> (length);
std::string body;
body.resize(u_length);
conn.readn(body);
::write_buffer ("baidu.html", body);
return 0;
}
|
long long combination (int i,int j,int m,int n){
if(i==m-1&&j==n-1) return 1;
if(i>m||j>n) return 0;
else return combination(i+1,j,m,n)+combination(i,j+1,m,n);
}
long long numberOfPaths(int m, int n)
{
// Code Here
//m*n-2Cm+n-1
return combination(0,0,m,n);
}
|
"2002-01-18\n"
" - duuzo sie znowu dzialo ...\n"
|
#include "Bispectrum_Fisher_MPI.hpp"
#include "Log.hpp"
#include "wignerSymbols.h"
#include <omp.h>
#include <ctime>
#include <chrono>
#include <mpi.h>
using namespace chrono;
/*********************************/
/** Bispectrum_Fisher **/
/*********************************/
Bispectrum_Fisher::Bispectrum_Fisher(AnalysisInterface* analysis, Bispectrum_LISW* LISW, Bispectrum* NLG,\
vector<string> param_keys_considered, string fisherPath, MPI_Comm communicator)
{
this->communicator = communicator;
int r;
MPI_Comm_rank(communicator, &r);
this->rank = r;
if (rank == 0)
log<LOG_BASIC>("... Beginning Bispectrum_Fisher constructor ...");
todo_determined = false;
interpolation_done = false;
this->fisherPath = fisherPath;
model_param_keys = param_keys_considered;
this->analysis = analysis;
this->LISW = LISW;
this->NLG = NLG;
this->nu_min_CLASS = 0;
this->nu_stepsize_CLASS = 0;
this->nu_steps_CLASS = 0;
this->fiducial_params = analysis->model->give_fiducial_params();
for (int i = 0; i < model_param_keys.size(); ++i) {
string key = model_param_keys[i];
if (fiducial_params[key] == 0.0)
var_params.insert(pair<string,double>(key,0.0001));
else
var_params.insert(pair<string,double>(key,fiducial_params[key]/1000.0));
}
// Determines the largest l-mode to be computed.
lmax_CLASS = analysis->model->give_fiducial_params("lmax_Fisher_Bispectrum");
if (rank == 0)
log<LOG_BASIC>("... Bispectrum_Fisher Class initialized ...");
}
Bispectrum_Fisher::~Bispectrum_Fisher()
{}
double Bispectrum_Fisher::compute_F_matrix(double nu_min, double nu_stepsize,\
int n_points_per_thread, int n_threads, Bispectrum_Effects effects)
{
int nu_steps = n_points_per_thread * n_threads;
this->nu_steps_CLASS = nu_steps;
this->nu_min_CLASS = nu_min;
this->nu_stepsize_CLASS = nu_stepsize;
//string filename_prefix = update_runinfo(lmin, lmax, lstepsize, xstepsize);
string slash = "";
if (fisherPath.back() == '/')
slash = "";
else
slash = "/";
stringstream filename;
filename << fisherPath << slash << "Fl_";
string filename_prefix = filename.str();
// Exhaust all the possible models and interpolate them, so that the
// code is thread safe later on.
if (rank == 0)
log<LOG_BASIC>(" -> Interpolating all possible models.");
steady_clock::time_point t1 = steady_clock::now();
system_clock::time_point t11 = system_clock::now();
for (unsigned int i = 0; i < model_param_keys.size(); i++) {
int Pk = 0;
int Tb = 0;
int q = 0;
string param_key = model_param_keys[i];
if (rank == 0)
log<LOG_BASIC>("%1%") % param_key;
map<string,double> working_params = fiducial_params;
double h = this->var_params[param_key];
double x = working_params[param_key];
working_params[param_key] = x + h;
analysis->model->update(working_params, &Pk, &Tb, &q);
if (rank == 0)
log<LOG_BASIC>("model updated for Pk_i = %1%, Tb = %2%, q = %3%.") % Pk % Tb % q;
}
steady_clock::time_point t2 = steady_clock::now();
system_clock::time_point t22 = system_clock::now();
duration<double> dt = duration_cast<duration<double>>(t2-t1);
duration<double> dt2 = duration_cast<duration<double>>(t22-t11);
if (rank == 0)
{
log<LOG_BASIC>(" -----> done. T = %1%s") % dt.count();
log<LOG_BASIC>(" -> Interpolating all possible growth functions.");
}
t1 = steady_clock::now();
for (int i = 0; i < analysis->model->q_size(); i++)
{
NLG->update_D_Growth(i);
}
t2 = steady_clock::now();
dt = duration_cast<duration<double>>(t2-t1);
if (rank == 0)
log<LOG_BASIC>(" -----> done. T = %1%s") % dt.count();
// now compute F_ab's (symmetric hence = F_ba's)
for (unsigned int i = 0; i < model_param_keys.size(); i++) {
for (unsigned int j = i; j < model_param_keys.size(); j++) {
filename.str("");
string param_key1 = model_param_keys[i];
string param_key2 = model_param_keys[j];
if (rank == 0)
log<LOG_BASIC>("----> STARTING with %1% and %2%.") % param_key1.c_str() % param_key2.c_str();
filename << filename_prefix << param_key1 << "_" << param_key2 << ".dat";
int Pk_index = 0;
int Tb_index = 0;
int q_index = 0;
/*
if (param_key1 == param_key2) {
initializer(param_key1, &Pk_index, &Tb_index, &q_index);
} else {
initializer(param_key1, &Pk_index, &Tb_index, &q_index);
initializer(param_key2, &Pk_index, &Tb_index, &q_index);
}
*/
double sum = 0;
// This matrix contains the results.
mat output(nu_steps, 2);
// IMPORTANT! l has to start at 1 since Nl_bar has j_(l-1) in it!
// The following line parallelizes the code
// use #pragma omp parallel num_threads(4) private(Pk_index, Tb_index, q_index)
// to define how many threads should be used.
log<LOG_VERBOSE>("Entering Parallel regime");
//#pragma omp parallel num_threads(n_threads) private(Pk_index, Tb_index, q_index)
//{
// Pk_index = 0;
// Tb_index = 0;
// q_index = 0;
// #pragma omp for reduction (+:sum)
for (int k = 1; k <= nu_steps; ++k) {
// note: k has nothing to do with scale here, just an index!
int m = 0;
if (k == nu_steps)
m = nu_steps;
else
m = ((k-1)*n_threads) % (nu_steps - 1) + 1;
int nu = nu_min + m * nu_stepsize;
stringstream ss;
ss << "Computation of F_nu starts for nu = " << nu << "\n";
log<LOG_VERBOSE>("%1%") % ss.str().c_str();
double fnu = compute_Fnu(nu, param_key1, param_key2,\
&Pk_index, &Tb_index, &q_index, effects);
//adding results to the output matrix
output(k-1, 0) = nu;
output(k-1, 1) = fnu;
stringstream ss2;
ss2 << "fnu with nu = " << nu << " is: " << fnu << "\n";
log<LOG_VERBOSE>("%1%") % ss2.str().c_str();
sum += fnu;
}
//} // parallel end.
if (rank == 0)
{
ofstream outfile;
outfile.open(filename.str());
for (int i = 0; i < nu_steps; i++)
{
outfile << output(i,0) << " " << output(i,1) << endl;
}
outfile.close();
if (rank == 0)
log<LOG_BASIC>("Calculations done for %1% and %2%.") %\
param_key1.c_str() % param_key2.c_str();
}
}
}
log<LOG_BASIC>("rank %1% has reached the end.") % rank;
return 0;
}
double Bispectrum_Fisher::compute_Fnu(double nu, string param_key1, string param_key2,\
int *Pk_index, int *Tb_index, int *q_index, Bispectrum_Effects effects)
{
double res = 0;
int Pk_index2 = *Pk_index;
int Tb_index2 = *Tb_index;
int q_index2 = *q_index;
int n_threads = analysis->model->give_fiducial_params("n_threads_bispectrum");
int gaps = analysis->model->give_fiducial_params("gaps_bispectrum");
int stepsize = gaps + 1;
int lmodes = ceil((lmax_CLASS-2.0)/(double)stepsize);
int imax = ceil((double)lmodes/(double)n_threads) * n_threads;
//cout << "nthreads = " << n_threads << endl;
//cout << "lmodes = " << lmodes << endl;
//cout << "imax = " << imax << endl;
int modmax = (imax-1)*stepsize;//lmax_CLASS-3;// ceil((lmax_CLASS-2)/n_threads) * n_threads - 1;
double sum = 0;
int comm_size;
MPI_Comm_size(communicator, &comm_size);
// This will only be used if omp_nested is set to 1 in the constructor above.
//int n_threads_2 = analysis->model->give_fiducial_params("sub_threads");
/** READ THIS!!! -> for NLG
* ------------
*
* Similarly to before, in order to be thread safe, I need to make sure that
* each THETA interpolator has been precomputed safely before I let multiple threads
* access the vector. So that they will never be in a situation where they want to
* create a new element, thus making sure that 2 threads don't try and make the same
* vector element, or push something to the vector at the exact same time.
*
*/
if (effects == NLG_eff || effects == ALL_eff)
{
if (!interpolation_done)
{
// Update all possible THETA interpolators.
/** I am currently thinking that this should be doable on multiple cores.
* This means that I separate the lranges that each core needs to update and add
* their updated interpolator structures to local vectors.
*/
// PROTOCODE:
//
// vector<vector<THETA>> global_vec;
// # pragma omp parallel
// {
// vector<THETA> local_vec;
// # pragma omp for
// for each li lj q pk tb and q index:
// THETA interpolator = update();
// local_vec.push_back(interpolator);
//
// # pragma omp critical
// global_vec.push_back(local_vec)
// }
//
// vector<THETA> transfer;
// set transfer = global_vec; // ie. collapse it down.
// set bispectrum.THETA_interps = transfer;
// done!
if (rank == 0)
log<LOG_BASIC>("Precomputing all theta interpolators.");
//steady_clock::time_point t1 = steady_clock::now();
double zmax = (1420.4/this->nu_min_CLASS) - 1.0;
double zmin = (1420.4/(this->nu_min_CLASS + this->nu_steps_CLASS * this->nu_stepsize_CLASS) - 1.0);
double delta_z = (zmax - ((1420.4/(this->nu_min_CLASS+this->nu_stepsize_CLASS)) - 1.0));
// need to be careful that this is not repeated when doing a different parameter pair.
vector<vector<Theta>> global_vec;
if (rank == 0) {
log<LOG_BASIC>("pkz size = %1%") % analysis->model->Pkz_size();
log<LOG_BASIC>("tb size = %1%") % analysis->model->Tb_size();
log<LOG_BASIC>("q size = %1%") % analysis->model->q_size();
}
vector<Theta> local_vec;
bool calc = false;
vector<CONTAINER> vec_vals;
int message_size;
for (int l = 0; l <= lmax_CLASS; l++)
{
// This way all ranks > 0 will compute a single l mode.
// This is potentially too simple as we need to understand
// a variety of different interpolation schemes for the same l.
if (rank - 1 == l % (comm_size - 1))
{
//cout << "rank " << rank << " is now computing l = " << l<< endl;
steady_clock::time_point t11 = steady_clock::now();
calc = true;
// Doing it for li = lj, as we compute only the first term of the bispectrum for now.
// Also, for the same reason, we only need the q = 0 term.
int q = 0;
vector<double> all_res;
for (int Pk_i = 0; Pk_i < analysis->model->Pkz_size(); Pk_i++)
{
for (int Tb_i = 0; Tb_i < analysis->model->Tb_size(); Tb_i++)
{
for (int q_i = 0; q_i < analysis->model->q_size(); q_i++)
{
vector<double> interp_results = NLG->give_interp_theta_vals(l, l, q,\
Pk_i, Tb_i, q_i, zmax, zmin, delta_z);
for (int i = 0; i < interp_results.size();i++)
all_res.push_back(interp_results[i]);
}
}
}
steady_clock::time_point t22 = steady_clock::now();
duration<double> dt2 = duration_cast<duration<double>>(t22-t11);
log<LOG_BASIC>(" -> Thetas for li = lj = %1% are being interpolated. T = %2%s, rank = %3%.") %\
l % dt2.count() % rank;
double* res;
// TODO: what is size? What is res?
message_size = all_res.size();
res = new double [message_size];
for (int i = 0; i < all_res.size(); i++)
{
res[i] = all_res[i];
}
//cout << "sending 1st message rank = "<< rank << endl;
MPI_Ssend(&message_size, 1, MPI_INT, 0, 0, communicator);
//cout << "1st message sent rank = "<< rank << endl;
//cout << "sending 2nd message rank = "<< rank << endl;
MPI_Ssend(res, message_size, MPI_DOUBLE, 0, l, communicator);
//cout << "2nd message sent rank = "<< rank << endl;
delete res;
}
if (rank == 0)
{
int sender = (l % (comm_size -1)) + 1;
double* res;
MPI_Status status;
//cout << "rank " << rank << " is trying to receive l = " << l << ", from rank " << sender << endl;
MPI_Recv(&message_size, 1, MPI_INT, sender, 0, communicator, &status);
res = new double[message_size];
MPI_Recv(res, message_size, MPI_DOUBLE, sender, l, communicator, &status);
//cout << "l-mode " << l << " values received." << endl;
CONTAINER A;
A.l = l;
A.vals = new double[message_size];
for (int i = 0; i < message_size; i++)
A.vals[i] = res[i];
vec_vals.push_back(A);
delete res;
}
}
MPI_Barrier(communicator);
double* vals;
for (int l = 0; l <= lmax_CLASS; l++)
{
bool found = false;
int i = -1;
while (!found)
{
if (rank == 0)
{
i++;
if (vec_vals[i].l == l)
{
found = true;
}
if (i>10000000)
{
cout << "ERROR: infinite loop" << endl;
break;
}
}
else
found = true;
}
//if (rank == 0)
//cout << "l = " << l << " was found and will be broughtcast" << endl;
vals = new double[message_size];
if (rank == 0)
{
//cout << "values being put into contiguous memory container. message_size = " <<\
//message_size << endl;
//cout << i << " " << vec_vals[i].vals[0] << " " << vec_vals[i].vals[1] << " " <<\
// vec_vals[i].vals[2] << endl;
for (int j = 0; j < message_size; j++)
vals[j] = vec_vals[i].vals[j];
//cout << "done" << endl;
}
MPI_Bcast(vals, message_size, MPI_DOUBLE, 0, communicator);
//done on each process;
//cout << "l = " << l << " was broughtcast and will be interpolated. rank = " << rank << endl;
vector<Theta> thetas = NLG->make_interps(l, message_size, vals, zmax, zmin, delta_z);
global_vec.push_back(thetas);
delete vals;
}
//MPI_Barrier(communicator);
NLG->update_THETAS(global_vec);
//steady_clock::time_point t2 = steady_clock::now();
//duration<double> dt = duration_cast<duration<double>>(t2-t1);
log<LOG_BASIC>("rank %1% now sorting the interpolators.") % rank;
//log<LOG_BASIC>(" --> thetas are interpolated. Time taken = %1%.") % dt.count();
interpolation_done = true;
}
else
{
if (rank == 0)
log<LOG_BASIC>("Interpolation of thetas has been done before. Nothing to be done.");
}
}
//MPI_Barrier(communicator);
/** READ THIS !!!
* -------------
*
* Important, in order to be thread safe, I am computing the l1=2 case on a single core.
* This insures that all Pkz, Tb and q interpolation vectors have been exhaustively
* filled, such that later on, when I have multiple threads calling model->update(params)
* they will never have to create a new vector element. It could be that multiple threads
* would try and create the same model interpolator, which is BAD!.
**/
if (!todo_determined)
{
if (rank == 0)
log<LOG_BASIC>("Now trying to determine which modes each rank needs to compute.");
int counter = -1;
for (int l1 = 0; l1 <= lmax_CLASS; l1++)
{
int lmin = l1/2;
for (int l2 = lmin; l2 <= l1; l2++)
{
for (int l3 = 0; l3 <= l1; l3++)
{
if (l3 >= (l1-l2) and l3 <= l2)
{
if (!(l1 == l2 and l3 == 0))
{
counter++;
if (rank == counter % comm_size)
{
todo_elem todo;
todo.l1 = l1;
todo.l2 = l2;
todo.l3 = l3;
// Now each rank has it's own todo list which contains a list of (l1,l2,l3) - triplets,
// for which the rank needs to compute the Fisher_contribution.
todo_list.push_back(todo);
}
}
}
}
}
}
todo_determined = true;
log<LOG_BASIC>("rank %1% has computed its todo list, it contains %2% elements.") %\
rank % todo_list.size();
MPI_Barrier(communicator);
}
double local_sum = 0;
double global_sum = 0;
double F_res;
int mod_ref;
if (todo_list.size() < 100)
mod_ref = todo_list.size();
else if (todo_list.size() < 1000)
mod_ref = todo_list.size()/10;
else
mod_ref = todo_list.size()/100;
// each rank only computes all the modes it needs to and sums them up on their own.
for (int i = 0; i < todo_list.size(); i++)
{
//if (i % mod_ref == 0)
//{
//log<LOG_BASIC>("rank %1% is %2% \% done.") % rank % ceil((double)i/(double)todo_list.size() *100.0);
//}
F_res = Fisher_element(todo_list[i].l1,todo_list[i].l2,todo_list[i].l3,nu,param_key1,param_key2,\
&Pk_index2, &Tb_index2, &q_index2, effects);
F_res *= (2.0 * todo_list[i].l1 + 1.0) * (2.0 * todo_list[i].l2 + 1.0) * (2.0 * todo_list[i].l3 + 1.0);
local_sum += F_res;
}
// Then the data from each of these individual sums is taken and reduced on all processes.
MPI_Allreduce(&local_sum, &global_sum, 1, MPI_DOUBLE, MPI_SUM, communicator);
// each process should have the same value for global sum.
return global_sum;
}
double Bispectrum_Fisher::Fisher_element(int l1, int l2, int l3, double nu,\
string param_key1, string param_key2, int *Pk_index, int *Tb_index, int *q_index,\
Bispectrum_Effects effects)
{
// I think these should be at indecies = 0...
double Cl1 = Cl(l1,nu);
double Cl2 = Cl(l2,nu);
double Cl3 = Cl(l3,nu);
double delta_lll = 0;
if (l1 == l2 and l1 == l3)
{
delta_lll = 6.0;
}
else if (l1 == l2 or l2 == l3)
{
delta_lll = 2.0;
}
else
{
delta_lll = 1.0;
}
double frac = 1.0/(delta_lll * Cl1 * Cl2 * Cl3);
// This Wigner Symbol is actually (l1,l2,l3,m1,m2,m3) but we evaluate it at ms = 0 2l+1 times
double W3J1 = WignerSymbols::wigner3j(l1,l2,l3,0,0,0);
double mu_A = 0;
double mu_B = 0;
if (W3J1 == 0)
{
mu_A = 0;
mu_B = 0;
}
else
{
mu_A = calc_mu(l1,l2,l3,nu,param_key1, Pk_index, Tb_index, q_index, effects);
if (param_key1 == param_key2)
mu_B = mu_A;
else
mu_B = calc_mu(l1,l2,l3,nu,param_key2, Pk_index, Tb_index, q_index, effects);
}
return frac * mu_A * mu_B;
}
double Bispectrum_Fisher::Cl(int l, double nu)
{
// Noise now included
double cl = analysis->Cl(l,nu,nu,0,0,0);
double noise = analysis->Cl_noise(l, nu, nu);
//cout << cl << " --- " << noise << endl;
return cl+noise;
}
double Bispectrum_Fisher::calc_mu(int l1, int l2, int l3, double nu, string param_key,\
int *Pk_index, int *Tb_index, int *q_index, Bispectrum_Effects effects)
{
log<LOG_VERBOSE>("entered mu");
double z = (1420.4/nu) - 1.0;
map<string,double> working_params = fiducial_params;
double h = this->var_params[param_key];
double x = working_params[param_key];
//cout << param_key << " " << x << " " << h << endl;
// mat f1matrix = randu<mat>(range.size(),range.size());
// mat f2matrix = randu<mat>(range.size(),range.size());
// mat f3matrix = randu<mat>(range.size(),range.size());
// mat f4matrix = randu<mat>(range.size(),range.size());
// 5-point stencil derivative:
double B1 = 0;
double B2 = 0;
double B1_NLG = 0;
double B2_NLG = 0;
if (effects == NLG_eff)
{
working_params[param_key] = x + h;
analysis->model->update(working_params, Pk_index, Tb_index, q_index);
B1_NLG = NLG->calc_angular_B(l1,l2,l3,0,0,0,z,*Pk_index, *Tb_index, *q_index);
working_params[param_key] = x;
analysis->model->update(working_params, Pk_index, Tb_index, q_index);
B2_NLG = NLG->calc_angular_B(l1,l2,l3,0,0,0,z,*Pk_index, *Tb_index, *q_index);
//cout << B1_NLG << endl;
//cout << B2_NLG << endl;
return (B1_NLG - B2_NLG)/h;
}
else if (effects == LISW_eff)
{
working_params[param_key] = x + h;
analysis->model->update(working_params, Pk_index, Tb_index, q_index);
B1 = LISW->calc_angular_Blll_all_config(l1,l2,l3,z,z,z, *Pk_index, *Tb_index, *q_index);
working_params[param_key] = x;
analysis->model->update(working_params, Pk_index, Tb_index, q_index);
B2 = LISW->calc_angular_Blll_all_config(l1,l2,l3,z,z,z, *Pk_index, *Tb_index, *q_index);
return (B1 - B2)/h;
}
else
{
if (param_key == "lambda_LISW")
{
double BLISW = LISW->calc_angular_Blll_all_config(l1,l2,l3,z,z,z, 0, 0, 0);
return BLISW;
}
else
{
working_params[param_key] = x + h;
//#pragma omp critical
//{
analysis->model->update(working_params, Pk_index, Tb_index, q_index);
//}
B1 = LISW->calc_angular_Blll_all_config(l1,l2,l3,z,z,z, *Pk_index, *Tb_index, *q_index);
B1_NLG = NLG->calc_angular_B(l1,l2,l3,0,0,0,z,*Pk_index, *Tb_index, *q_index);
working_params[param_key] = x;
//#pragma omp critical
//{
analysis->model->update(working_params, Pk_index, Tb_index, q_index);
//}
B2 = LISW->calc_angular_Blll_all_config(l1,l2,l3,z,z,z, *Pk_index, *Tb_index, *q_index);
B2_NLG = NLG->calc_angular_B(l1,l2,l3,0,0,0,z,*Pk_index, *Tb_index, *q_index);
return (B1 - B2)/h + (B1_NLG - B2_NLG)/h;
}
}
}
vector<double> Bispectrum_Fisher::set_range(int l, double xmin, double xmax)
{
//I think here it will be a a range of zs.
vector<double> range;
//defining own lower limit.
/*(void)xmin;
double k_min = (double)l / analysis->model->r_interp(fiducial_params["zmax"]);
int steps = (xmax - k_min)/xstepsize + 1;
vector<double> range;
double new_max = 0;
for (int i = 0; i <= steps; ++i)
{
new_max = k_min + i * xstepsize;
range.push_back(new_max);
}
stringstream ss;
ss << "The range is [" << k_min << "," << new_max << "] in " << steps+1 <<\
" steps for l = " << l << ".\n";
log<LOG_VERBOSE>("%1%") % ss.str().c_str();
return range;
*/
return range;
}
|
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#ifndef cmFileTime_h
#define cmFileTime_h
#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
/** \class cmFileTime
* \brief Abstract file modification time with support for comparison with
* other file modification times.
*/
class cmFileTime
{
public:
using NSC = long long;
static constexpr NSC NsPerS = 1000000000;
cmFileTime() = default;
~cmFileTime() = default;
/**
* @brief Loads the file time of fileName from the file system
* @return true on success
*/
bool Load(std::string const& fileName);
/**
* @brief Return true if this is older than ftm
*/
bool Older(cmFileTime const& ftm) const { return (this->NS - ftm.NS) < 0; }
/**
* @brief Return true if this is newer than ftm
*/
bool Newer(cmFileTime const& ftm) const { return (ftm.NS - this->NS) < 0; }
/**
* @brief Return true if this is the same as ftm
*/
bool Equal(cmFileTime const& ftm) const { return this->NS == ftm.NS; }
/**
* @brief Return true if this is not the same as ftm
*/
bool Differ(cmFileTime const& ftm) const { return this->NS != ftm.NS; }
/**
* @brief Compare file modification times.
* @return -1, 0, +1 for this older, same, or newer than ftm.
*/
int Compare(cmFileTime const& ftm) const
{
NSC const diff = this->NS - ftm.NS;
if (diff == 0) {
return 0;
}
return (diff < 0) ? -1 : 1;
}
// -- Comparison in second resolution
/**
* @brief Return true if this is at least a second older than ftm
*/
bool OlderS(cmFileTime const& ftm) const
{
return (ftm.NS - this->NS) >= cmFileTime::NsPerS;
}
/**
* @brief Return true if this is at least a second newer than ftm
*/
bool NewerS(cmFileTime const& ftm) const
{
return (this->NS - ftm.NS) >= cmFileTime::NsPerS;
}
/**
* @brief Return true if this is within the same second as ftm
*/
bool EqualS(cmFileTime const& ftm) const
{
NSC diff = this->NS - ftm.NS;
if (diff < 0) {
diff = -diff;
}
return (diff < cmFileTime::NsPerS);
}
/**
* @brief Return true if this is older or newer than ftm by at least a second
*/
bool DifferS(cmFileTime const& ftm) const
{
NSC diff = this->NS - ftm.NS;
if (diff < 0) {
diff = -diff;
}
return (diff >= cmFileTime::NsPerS);
}
/**
* @brief Compare file modification times.
* @return -1: this at least a second older, 0: this within the same second
* as ftm, +1: this at least a second newer than ftm.
*/
int CompareS(cmFileTime const& ftm) const
{
NSC const diff = this->NS - ftm.NS;
if (diff <= -cmFileTime::NsPerS) {
return -1;
}
if (diff >= cmFileTime::NsPerS) {
return 1;
}
return 0;
}
/**
* @brief The file modification time in nanoseconds
*/
NSC GetNS() const { return this->NS; }
private:
NSC NS = 0;
};
#endif
|
/*!
* \file mpredialog.h
* \author Simon Coakley
* \date 2012
* \copyright Copyright (c) 2012 University of Sheffield
* \brief Header file for mpre dialog
*/
#ifndef MPREDIALOG_H_
#define MPREDIALOG_H_
#include <QDialog>
#include <QDialogButtonBox>
#include <QComboBox>
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <QCheckBox>
#include <QGroupBox>
#include "./mpre.h"
#include "./memorymodel.h"
#include "./condition.h"
#include "./ui_conditiondialog.h"
#include "./machine.h"
class QDialogButtonBox;
class MpreDialog : public QDialog, public Ui::ConditionDialog {
Q_OBJECT
public:
MpreDialog(Machine * agent, QString * messageType = 0, QWidget *parent = 0);
void setCondition(Condition c);
Condition getCondition();
signals:
void setVariableComboBox(int i);
void setOpComboBox(int i);
private slots:
void enableCondition(bool);
void checkedLhsAgentVariable(bool);
void checkedLhsMessageVariable(bool);
void checkedLhsValue(bool);
void checkedRhsAgentVariable(bool);
void checkedRhsMessageVariable(bool);
void checkedRhsValue(bool);
void valueClicked();
void timeClicked();
void nestedClicked();
void editLhsClicked();
void editRhsClicked();
void disableTimePhaseVariable(bool);
void disableTimePhaseValue(bool);
void levelUpClicked();
private:
void setCurrentCondition(Condition * c);
void getCurrentCondition();
QDialogButtonBox *buttonBox;
QComboBox *variable;
QComboBox * op;
QSpinBox * value;
QCheckBox * myEnabled;
QGroupBox *lhsGroup;
QGroupBox *opGroup;
QGroupBox *rhsGroup;
Condition condition;
Condition * c;
Machine * agent;
QStringList operators;
};
#endif // MPREDIALOG_H_
|
//
// Created by 송지원 on 2020/07/03.
//
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
unsigned long long a, b;
unsigned long long diff;
cin >> a >> b;
if (a > b) swap(a, b);
diff = b - a;
if (diff>0){
cout << diff -1<< '\n';
for (unsigned long long i=1; i<diff; i++){
cout << a + i <<" ";
}
}
else {
cout << 0;
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2002 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#ifdef GENERIC_PRINTING
#include "modules/dochand/win.h"
#include "modules/dochand/docman.h"
#include "modules/display/prn_dev.h"
#include "modules/display/prndevlisteners.h"
// ======================================================
// PrintListener
// ======================================================
PrintListener::PrintListener(PrintDevice* prn_dev) :
prn_dev(prn_dev)
{
}
void PrintListener::OnPrint()
{
DocumentManager* doc_man = prn_dev->GetDocumentManager();
if (doc_man)
{
Window * window = doc_man->GetWindow();
if (window)
window->PrintNextPage(window->GetPrinterInfo(FALSE));
}
}
#endif // GENERIC_PRINTING
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "Hypoxia.h"
#include "Keycard.h"
#include "EngineUtils.h"
#include "Engine/StaticMeshActor.h"
void AKeycard::BeginPlay() {
Super::BeginPlay();
for (TActorIterator<ADoor> ActorItr(GetWorld()); ActorItr; ++ActorItr)
{
if (ActorItr->ActorHasTag(Tags[0])) {
Door = *ActorItr;
UE_LOG(LogTemp, Warning, TEXT("Child: %s"), *ActorItr->GetName());
UE_LOG(LogTemp, Warning, TEXT("Parent: %s"), *GetName());
break;
}
}
}
void AKeycard::Tick(float DeltaTime) {
Super::Tick(DeltaTime);
if (Held) {
if (FVector::Dist(Door->GetActorLocation(), Item->GetComponentLocation()) < 50.0f) {
Door->Unlock();
UE_LOG(LogTemp, Warning, TEXT("Unlocking"));
}
}
}
|
#include "../include/scaledialog.h"
#include "ui_scaledialog.h"
ScaleDialog::ScaleDialog(QWidget *parent, int _w, int _h) : QDialog(parent), ui(new Ui::ScaleDialog),
width(_w), height(_h), fixRate(false),
oriWidth(_w), oriHeight(_h) {
ui->setupUi(this);
ui->spinBoxWidthAb->setMaximum(_w * 10);
ui->spinBoxWidthAb->setValue(_w);
ui->spinBoxHeightAb->setMaximum(_h * 10);
ui->spinBoxHeightAb->setValue(_h);
connect(ui->checkBoxFixRate, SIGNAL(stateChanged(int)), this, SLOT(setFixRate(int)));
connect(ui->spinBoxWidthAb, SIGNAL(valueChanged(int)), this, SLOT(setWidthAb(int)));
connect(ui->spinBoxHeightAb, SIGNAL(valueChanged(int)), this, SLOT(setHeightAb(int)));
}
ScaleDialog::~ScaleDialog() {
delete ui;
}
void ScaleDialog::setFixRate(int state) {
if (state == Qt::Checked) {
fixRate = true;
}
else {
fixRate = false;
}
}
void ScaleDialog::setWidthAb(int _w) {
if (fixRate) {
width = _w;
double fc = (double) _w / (double) oriWidth;
height = (int) (oriHeight * fc);
//ui->spinBoxHeightAb->setValue(height);
}
else {
width = _w;
}
}
void ScaleDialog::setHeightAb(int _h) {
if (fixRate) {
height = _h;
double fc = (double) _h / (double) oriHeight;
width = (int) (oriWidth * fc);
//ui->spinBoxWidthAb->setValue(width);
}
else {
width = _h;
}
}
ScaleDialog::ScalePara ScaleDialog::getScalePara(QWidget *parent, int _w, int _h) {
ScaleDialog dialog(parent, _w, _h);
ScalePara res;
if (dialog.exec() == QDialog::Accepted) {
res.width = dialog.width;
res.height = dialog.height;
if (dialog.ui->radioButton_nearest->isChecked())
dialog.type = 1;
else
dialog.type = 0;
res.type = dialog.type;
return res;
}
res.width = _w;
res.width = _h;
if (dialog.ui->radioButton_nearest->isChecked())
dialog.type = 1;
else
dialog.type = 0;
res.type = dialog.type;
return res;
}
|
// Comes from:
// https://docs.nvidia.com/cuda/curand/host-api-overview.html#host-api-example
#ifdef _WIN32
# define EXPORT __declspec(dllexport)
#else
# define EXPORT
#endif
/*
* This program uses the host CURAND API to generate 100
* pseudorandom floats.
*/
#include <cuda.h>
#include <curand.h>
#include <stdio.h>
#include <stdlib.h>
#define CUDA_CALL(x) \
do { \
if ((x) != cudaSuccess) { \
printf("Error at %s:%d\n", __FILE__, __LINE__); \
return EXIT_FAILURE; \
} \
} while (0)
#define CURAND_CALL(x) \
do { \
if ((x) != CURAND_STATUS_SUCCESS) { \
printf("Error at %s:%d\n", __FILE__, __LINE__); \
return EXIT_FAILURE; \
} \
} while (0)
EXPORT int curand_main()
{
size_t n = 100;
size_t i;
curandGenerator_t gen;
float *devData, *hostData;
/* Allocate n floats on host */
hostData = (float*)calloc(n, sizeof(float));
/* Allocate n floats on device */
CUDA_CALL(cudaMalloc((void**)&devData, n * sizeof(float)));
/* Create pseudo-random number generator */
CURAND_CALL(curandCreateGenerator(&gen, CURAND_RNG_PSEUDO_DEFAULT));
/* Set seed */
CURAND_CALL(curandSetPseudoRandomGeneratorSeed(gen, 1234ULL));
/* Generate n floats on device */
CURAND_CALL(curandGenerateUniform(gen, devData, n));
/* Copy device memory to host */
CUDA_CALL(
cudaMemcpy(hostData, devData, n * sizeof(float), cudaMemcpyDeviceToHost));
/* Cleanup */
CURAND_CALL(curandDestroyGenerator(gen));
CUDA_CALL(cudaFree(devData));
free(hostData);
return EXIT_SUCCESS;
}
|
#include "comn.h"
#ifndef CITY_FORCAST
#define CITY_FORCAST
bool israin(std::string scode);
class city_fst
{
private:
public:
CTime time;
int station_num;
//days 时次的最高最低
std::vector<double> max_t, min_t;
//2*days 时次是否报雨
std::vector<bool> israin;
city_fst(int days=2)
:israin(2*days,false)
,max_t(days,0), min_t(days,0)
{
station_num = 99999;
}
};
city_fst & read_city_fst(const std::string & sline, city_fst & cf);
#endif //CITY_FORCAST
|
#include "pch.h"
#include "ImporterBFF.h"
namespace ImporterBFF
{
//Hidden
void LoadModelFromFile(ModelBFF& model)
{
std::string fullFilePath = "../../../../Models/" + model.fileName;
std::ifstream MeshFile(fullFilePath, std::ifstream::binary);
// Failed to find file, return empty model
if (!MeshFile.is_open())
{
return;
}
MeshFile.read((char*)&model.mesh, sizeof(MeshBFF));
model.vertexArr = new VertexBFF[model.mesh.nrOfVertex];
MeshFile.read((char*)model.vertexArr, model.mesh.nrOfVertex * sizeof(VertexBFF));
// Flippa X axeln och V flr uv
for (size_t i = 0; i < model.mesh.nrOfVertex; i++)
{
model.vertexArr[i].pos[2] *= -1;
model.vertexArr[i].norm[2] *= -1;
model.vertexArr[i].uv[1] *= -1;
}
MeshFile.read((char*)&model.material, sizeof(MaterialBFF));
MeshFile.read((char*)&model.camera, sizeof(CameraBFF));
MeshFile.close();
}
//std::string Model::MeshName(Model model)
//{
// return std::to_string(material.Diffuse[0]);
//}
Manager::Manager()
{
}
Manager& Manager::GetInstance()
{
static Manager instance;
return instance;
}
void Manager::InitModelAsync(const char* fileName)
{
// Check if insertion is successful or not
if (map.find(fileName) == map.end())
{
//add to list
ModelBFF& newModel = map[fileName];
newModel.fileName = fileName;
}
}
const ModelBFF& Manager::LoadModelAsync(const char* fileName)
{
ModelBFF& newModel = map[fileName];
//load bff file
LoadModelFromFile(newModel);
newModel.loaded = true;
return newModel;
}
const ModelBFF& Manager::LoadModel(const char* fileName)
{
// Check if insertion is successful or not
if (map.find(fileName) == map.end())
{
//add to list
ModelBFF& newModel = map[fileName];
newModel.fileName = fileName;
//load bff file
LoadModelFromFile(newModel);
newModel.loaded = true;
}
return map[fileName];
}
//void Manager::printToConsole(const char* fileName)
//{
// // Check if insertion is successful or not
// if (map.find(fileName) == map.end())
// {
// std::string fullFilePath = "../../../../Models/" + (std::string)fileName;
// ModelBFF someModel;
// someModel = LoadModelFromFile(fullFilePath.c_str());
// std::wstring aString;
// aString = to_wstring(someModel.camera.pos[0]);
// OutputDebugStringW(aString.c_str());
// }
//}
Manager::~Manager()
{
}
}
|
////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
//
// Produces the MEL command "scanDagSyntax".
//
// This command plug-in provides the same functionality as scanDagCmd except
// that the syntax parsing is performed using syntax objects.
//
// The command accepts several flags:
//
// -b/-breadthFirst : Perform breadth first search
// -d/-depthFirst : Perform depth first search
// -c/-cameras : Limit the scan to cameras
// -l/-lights : Limit the scan to lights
// -n/-nurbsSurfaces : Limit the scan to NURBS surfaces
//
////////////////////////////////////////////////////////////////////////
#include <maya/MFnDagNode.h>
#include <maya/MItDag.h>
#include <maya/MObject.h>
#include <maya/MDagPath.h>
#include <maya/MPxCommand.h>
#include <maya/MSyntax.h>
#include <maya/MArgDatabase.h>
#include <maya/MStatus.h>
#include <maya/MString.h>
#include <maya/MFnPlugin.h>
#include <maya/MArgList.h>
#include <maya/MFnCamera.h>
#include <maya/MPoint.h>
#include <maya/MVector.h>
#include <maya/MMatrix.h>
#include <maya/MTransformationMatrix.h>
#include <maya/MFnLight.h>
#include <maya/MColor.h>
#include <maya/MFnNurbsSurface.h>
#include <maya/MIOStream.h>
#define kBreadthFlag "-b"
#define kBreadthFlagLong "-breadthFirst"
#define kDepthFlag "-d"
#define kDepthFlagLong "-depthFirst"
#define kCameraFlag "-c"
#define kCameraFlagLong "-cameras"
#define kLightFlag "-l"
#define kLightFlagLong "-lights"
#define kNurbsSurfaceFlag "-n"
#define kNurbsSurfaceFlagLong "-nurbsSurfaces"
#define kQuietFlag "-q"
#define kQuietFlagLong "-quiet"
class scanDagSyntax : public MPxCommand
{
public:
scanDagSyntax() {}
virtual ~scanDagSyntax();
static void* creator();
static MSyntax newSyntax();
virtual MStatus doIt(const MArgList&);
private:
MStatus parseArgs(const MArgList& args, MItDag::TraversalType& traversalType, MFn::Type& filter, bool& quiet);
MStatus doScan(const MItDag::TraversalType traversalType, MFn::Type filter, bool quiet);
void printTransformData(const MDagPath& dagPath, bool quiet);
};
scanDagSyntax::~scanDagSyntax() {}
void* scanDagSyntax::creator()
{
return new scanDagSyntax();
}
MSyntax scanDagSyntax::newSyntax()
{
MSyntax syntax;
syntax.addFlag(kBreadthFlag, kBreadthFlagLong);
syntax.addFlag(kDepthFlag, kDepthFlagLong);
syntax.addFlag(kCameraFlag, kCameraFlagLong);
syntax.addFlag(kLightFlag, kLightFlagLong);
syntax.addFlag(kNurbsSurfaceFlag, kNurbsSurfaceFlagLong);
syntax.addFlag(kQuietFlag, kQuietFlagLong);
return syntax;
}
MStatus scanDagSyntax::doIt(const MArgList& args)
{
MItDag::TraversalType traversalType = MItDag::kDepthFirst;
MFn::Type filter = MFn::kInvalid;
MStatus status;
bool quiet = false;
status = parseArgs(args, traversalType, filter, quiet);
if (!status)
{
return status;
}
return doScan(traversalType, filter, quiet);
}
MStatus scanDagSyntax::parseArgs(const MArgList & args, MItDag::TraversalType & traversalType, MFn::Type & filter, bool & quiet)
{
MStatus status;
MArgDatabase argData(syntax(), args);
//MString arg;
if (argData.isFlagSet(kBreadthFlag))
{
traversalType = MItDag::kBreadthFirst;
}
else if (argData.isFlagSet(kDepthFlag))
{
traversalType = MItDag::kDepthFirst;
}
if (argData.isFlagSet(kCameraFlag))
{
filter = MFn::kCamera;
}
else if (argData.isFlagSet(kLightFlag))
{
filter = MFn::kLight;
}
else if (argData.isFlagSet(kNurbsSurfaceFlag))
{
filter = MFn::kNurbsSurface;
}
if (argData.isFlagSet(kQuietFlag))
{
quiet = true;
}
return status;
}
MStatus scanDagSyntax::doScan(const MItDag::TraversalType traversalType, MFn::Type filter, bool quiet)
{
MStatus status;
MItDag dagIterator(traversalType, filter, &status);
if (!status)
{
status.perror("MItDag constructor");
return status;
}
if (traversalType == MItDag::kBreadthFirst)
{
if (!quiet)
{
displayInfo("Starting Breadth First scan of the DAG");
}
}
else
{
if (!quiet)
{
displayInfo("Starting Depth First scan fo the DAG");
}
}
switch (filter)
{
case MFn::kCamera:
if (!quiet)
{
displayInfo(": Filtering for Cameras");
}
break;
case MFn::kLight:
if (!quiet)
{
displayInfo(": Filtering for Lights");
}
break;
case MFn::kNurbsSurface:
if (!quiet)
{
displayInfo(": Filtering for NurbsSurfaces");
}
break;
default:
break;
}
int objectCount = 0;
for (; !dagIterator.isDone(); dagIterator.next())
{
MDagPath dagPath;
status = dagIterator.getPath(dagPath);
if (!status)
{
status.perror("MItDag::getPath");
continue;
}
MFnDagNode dagNode(dagPath, &status);
if (!status)
{
status.perror("MFnDagNode constructor");
continue;
}
if (!quiet)
{
displayInfo(dagNode.name() + ": " + dagNode.typeName());
displayInfo(" dagPath: " + dagPath.fullPathName());
}
objectCount++;
//if the object is a camera
if (dagPath.hasFn(MFn::kCamera))
{
MFnCamera camera(dagPath, &status);
if (!status)
{
status.perror("MFnCamera constructor");
continue;
}
//Get TRS
printTransformData(dagPath, quiet);
if (!quiet)
{
//displayInfo(" eyePoint: " + camera.eyePoint(MSpace::kWorld));
cout << " eyePoint: "
<< camera.eyePoint(MSpace::kWorld) << endl;
cout << " upDirection: "
<< camera.upDirection(MSpace::kWorld) << endl;
cout << " viewDirection: "
<< camera.viewDirection(MSpace::kWorld) << endl;
cout << " aspectRatio: " << camera.aspectRatio() << endl;
cout << " horizontalFilmAperture: "
<< camera.horizontalFilmAperture() << endl;
cout << " verticalFilmAperture: "
<< camera.verticalFilmAperture() << endl;
}
}
else if (dagPath.hasFn(MFn::kLight))
{
MFnLight light(dagPath, &status);
if (!status) {
status.perror("MFnLight constructor");
continue;
}
// Get the translation/rotation/scale data
printTransformData(dagPath, quiet);
// Extract some interesting Light data
MColor color;
color = light.color();
if (!quiet)
{
cout << " color: ["
<< color.r << ", "
<< color.g << ", "
<< color.b << "]\n";
}
color = light.shadowColor();
if (!quiet)
{
cout << " shadowColor: ["
<< color.r << ", "
<< color.g << ", "
<< color.b << "]\n";
cout << " intensity: " << light.intensity() << endl;
}
}
else if (dagPath.hasFn(MFn::kNurbsSurface))
{
//Finally, if the object is a NURBS surface, surface specific information is output.
MFnNurbsSurface surface(dagPath, &status);
if (!status) {
status.perror("MFnNurbsSurface constructor");
continue;
}
// Get the translation/rotation/scale data
printTransformData(dagPath, quiet);
// Extract some interesting Surface data
if (!quiet)
{
cout << " numCVs: "
<< surface.numCVsInU()
<< " * "
<< surface.numCVsInV()
<< endl;
cout << " numKnots: "
<< surface.numKnotsInU()
<< " * "
<< surface.numKnotsInV()
<< endl;
cout << " numSpans: "
<< surface.numSpansInU()
<< " * "
<< surface.numSpansInV()
<< endl;
}
}
else
{
printTransformData(dagPath, quiet);
}
} //end for
if (!quiet)
{
cout.flush();
}
setResult(objectCount); //return to mel
return MS::kSuccess;
}
void scanDagSyntax::printTransformData(const MDagPath & dagPath, bool quiet)
{
//This method simply determines the transformation information on the DAG node and prints it out.
MStatus status;
MObject transformNode = dagPath.transform(&status);
if (!status && status.statusCode() == MS::kInvalidParameter)
{
return;
}
MFnDagNode transform(transformNode, &status);
if (!status)
{
status.perror("MFnDagNode constructor");
return;
}
MTransformationMatrix matrix(transform.transformationMatrix());
if (!quiet)
{
cout << " translation: " << matrix.translation(MSpace::kWorld) << endl;
}
double threeDoubles[3];
MTransformationMatrix::RotationOrder rOrder;
matrix.getRotation(threeDoubles, rOrder, MSpace::kWorld);
if (!quiet)
{
cout << " rotation: ["
<< threeDoubles[0] << ", "
<< threeDoubles[1] << ", "
<< threeDoubles[2] << "]\n";
}
matrix.getScale(threeDoubles, MSpace::kWorld);
if (!quiet)
{
cout << " scale: ["
<< threeDoubles[0] << ", "
<< threeDoubles[1] << ", "
<< threeDoubles[2] << "]\n";
}
}
///////////////////////////////////////////////////////
MStatus initializePlugin(MObject obj)
{
MStatus status;
MFnPlugin plugin(obj, "kingmax_res@163.com | 184327932@qq.com | iJasonLee@WeChat", "2018.07.24.01", "Any");
status = plugin.registerCommand("scanDagSyntax", scanDagSyntax::creator, scanDagSyntax::newSyntax);
return status;
}
MStatus uninitializePlugin(MObject obj)
{
MStatus status;
MFnPlugin plugin(obj);
status = plugin.deregisterCommand("scanDagSyntax");
return status;
}
|
//
// Created by 钟奇龙 on 2019-05-05.
//
#include <iostream>
#include <vector>
using namespace std;
/*
* 暴力递归
*/
int process1(vector<int> arr,int index,int aim){
int res = 0;
if(index == arr.size()){
res = aim == 0 ? 1:0;
}else{
for(int i=0; i * arr[index] <= aim; ++i){
res += process1(arr,index+1,aim-arr[index]*i);
}
}
return res;
}
int coins1(vector<int> arr,int aim){
if(arr.size() == 0 || aim < 0) return 0;
return process1(arr,0,aim);
}
/*
* 暴力递归加记忆搜索
*/
int process2(vector<int> arr,int index,int aim,vector<vector<int> > &map){
int res = 0;
if(index == arr.size()){
res = aim == 0 ? 1:0;
}else{
for(int i=0; i*arr[index] <= aim; ++i){
int mapValue = map[index+1][aim-arr[index]*i];
if(mapValue != 0){
res += mapValue == -1 ? 0:mapValue;
}else{
res += process2(arr,index+1,aim-arr[index]*i,map);
}
}
}
map[index][aim] = res == 0 ? -1:res;
return res;
}
int coins2(vector<int> arr,int aim){
if(arr.size() == 0 || aim < 0) return 0;
vector<vector<int> > map(arr.size()+1,vector<int> (aim+1));
return process2(arr,0,aim,map);
}
int coins3(vector<int> arr,int aim){
if(arr.size() == 0 || aim < 0) return 0;
vector<vector<int> > dp(arr.size(),vector<int> (aim+1));
for (int i = 0; i < arr.size(); ++i) {
dp[i][0] = 1;
}
for(int j=1; j * arr[0] <= aim; ++j){
dp[0][j*arr[0]] = 1;
}
for(int i=1; i<arr.size(); ++i){
for(int j=1; j<=aim; ++j){
int num=0;
for(int k=0; j-arr[i]*k >= 0; ++k){
num += dp[i-1][j-arr[i]*k];
}
dp[i][j] = num;
}
}
return dp[arr.size()-1][aim];
}
/*
* 最优解
*/
int coins4(vector<int> arr,int aim){
if(arr.size() == 0 || aim < 0) return 0;
vector<vector<int> > dp(arr.size(),vector<int> (aim+1));
for(int i=0; i<arr.size(); ++i){
dp[i][0] = 1;
}
for(int j=1; j*arr[0] <= aim; ++j){
dp[0][j*arr[0]] = 1;
}
for(int i=1; i<arr.size(); ++i){
for(int j=1; j<=aim; ++j){
dp[i][j] = dp[i-1][j];
dp[i][j] += j-arr[i] >= 0 ? dp[i][j-arr[i]] : 0;
}
}
return dp[arr.size()-1][aim];
}
int coins5(vector<int> arr,int aim){
if(arr.size() == 0 || aim < 0) return 0;
vector<int> dp(aim+1);
for(int j=0; j * arr[0] <= aim; ++j){
dp[j*arr[0]] = 1;
}
for(int i=1; i<arr.size(); ++i){
for(int j=1; j<=aim; ++j){
dp[j] = (j-arr[i] >=0 ? dp[j-arr[i]]:0) + dp[j];
}
}
return dp[aim];
}
int main(){
vector<int> arr = {5,10,25,1};
cout<<coins1(arr,15)<<endl;
cout<<coins2(arr,15)<<endl;
cout<<coins3(arr,15)<<endl;
cout<<coins4(arr,15)<<endl;
cout<<coins5(arr,15)<<endl;
return 0;
}
|
#pragma once
#include <string>
#include "LandScape.h"
#include<iostream>
#include "Bonus.h"
#include <map>
#include "Player.h"
#include "Cell.h"
#include "Unit_type.h"
#include "GameObj.h"
class Unit: public GameObj
{
virtual std::string getName();
//std::string Name;
//std::string unit_type;
bool Deaf = 0;
int Health;
int Demage;
//std::string unitProfesion[2]{"M","C"};
//std::string unitElement[3] = {"L","A","N"};
protected:
Player& player;
std::map <LandScape, Bonus> AttackBonus;
const Cell* cell;
public:
void move(Cell*);
std::string toString();
//void unitLoad();
void setHealth(int& health);
void setDemage(int &demege);
int& getDemage();
// std::string& getName();
int& getHealth();
Player& getPlayer() const;
void setDeaf();
bool getDeaf();
bool doAction(std::string);
virtual std::map<std::string, int > getMap()=0;
Unit(int Health, int Demage, const Cell *cell, Player& player);
virtual void getAttackBonus();
void attack(Unit& unitD);
virtual ~Unit();
const Cell* getUnitCell();
//std::string getUnit_type();
};
|
//
// Created by roy on 12/24/18.
//
#include "Minus.h"
/**
* This method calculates the subtraction between left and right expressions.
* @return double value of the operation.
*/
double Minus::calculate() {
return (left->calculate() - right->calculate());
}
|
#include "Analysis.hpp"
#include "Integrator.hpp"
#include "Log.hpp"
#define NUWIDTH 10
#define LIMBERWINDOW true
IntensityMapping::IntensityMapping(ModelInterface* model)
{
this->model = model;
log<LOG_DEBUG>("-> You better be using camb_ares_2D or camb_ares as your model!");
analysisID = "IntensityMapping_analysis";
//Cls_interpolators_large = NULL;
if (model->give_fiducial_params("interp_Cls") == 0)
this->interpolating = false;
else
this->interpolating = true;
interpolate_large = true;
if (interpolating)
{
int lmin = 0;
int lmax = model->give_fiducial_params("lmax_Fisher_Bispectrum");
double nu_min = model->give_fiducial_params("Bispectrum_numin");
double nu_max = model->give_fiducial_params("Bispectrum_numax");
int nu_steps = 10;
log<LOG_BASIC>("Cls are being interpolated");
log<LOG_BASIC>("Parameters are: lmin = %1%, lmax = %2%, nu_min = %3%, nu_max = %4%, nu_steps = %5%.") %\
lmin % lmax % nu_min % nu_max % nu_steps;
make_Cl_interps(lmin, lmax, nu_min, nu_max, nu_steps);
}
else
log<LOG_BASIC>("Cls are NOT interpolated");
// Here I could include a code that precomputes the Cls between some lmin and lmax,
// and nu_min and nu_max, then it stores this in a 2D interpolator.
// I need to then create another function so that Cl(...) just returns the interpolated values.
}
IntensityMapping::IntensityMapping(ModelInterface* model, int num_params)
{
log<LOG_BASIC>(">>> Entering IntensityMapping constructor <<<");
this->model = model;
log<LOG_DEBUG>("-> You better be using camb_ares_2D or camb_ares as your model!");
analysisID = "IntensityMapping_analysis";
if (model->give_fiducial_params("interp_Cls") == 0)
this->interpolating = false;
else
this->interpolating = true;
interpolate_large = true;
lmin_CLASS = 0;
lmax_CLASS = model->give_fiducial_params("lmax_Fisher_Bispectrum");
numin_CLASS = model->give_fiducial_params("Bispectrum_numin");
numax_CLASS = model->give_fiducial_params("Bispectrum_numax");
nu_steps_CLASS = (numax_CLASS - numin_CLASS)/(double)model->give_fiducial_params("nu_stepsize");
////////////
//
log<LOG_BASIC>("... Precalculating Growth function for fast integrations ...");
log<LOG_BASIC>("... Growth function is precalculated between %1% and %2% using %3% points ...") % 0 % 100 % 1000;
auto integrand = [&](double z)
{
double H3 = this->model->Hf_interp(z);
H3 = pow(H3, 3);
return (1.0+z)/H3;
};
double I1 = integrate(integrand, 0.0, 10000.0, 1000000, simpson());
Growth_function_norm = 1.0/I1;
vector<double> zs_v, D_v;
// Should precalculate to at least z = 10000.
// Although this takes 20 seconds each run, which is annoying.
zs_v.resize(1000);
D_v.resize(1000);
// Caution: This introduces a possible memory loss
#pragma omp parallel for
for (int i = 0; i < 1000; i++)
{
double z = i*0.1;
double D = D_Growth(z);
zs_v[i] = z;
D_v[i] = D;
}
real_1d_array zs, D_pluss;
zs.setlength(zs_v.size());
D_pluss.setlength(D_v.size());
for (unsigned int i = 0; i < zs_v.size(); i++){
zs[i] = zs_v[i];
}
for (unsigned int i = 0; i < D_v.size(); i++){
D_pluss[i] = D_v[i];
}
spline1dbuildcubic(zs, D_pluss, Growth_function_interpolator);
log<LOG_BASIC>("... Writing Growth function to file ...");
ofstream file("Growing_mode.dat");
for (int i = 0; i < 1000; i++)
{
double z = i*0.1;
file << z << " " << spline1dcalc(Growth_function_interpolator, z) << endl;
}
log<LOG_BASIC>("... D_GROWTH_INTERP is prepared for q_index = 0 ...");
update_D_Growth(0);
/////////////
if (interpolating)
{
log<LOG_BASIC>("... Cls are being interpolated for the fiducial cosmology ...");
log<LOG_BASIC>("... -> parameters used: lmin = %1%, lmax = %2%, numin = %3%, numax = %4%, nu_steps = %5% ...") %\
lmin_CLASS % lmax_CLASS % numin_CLASS % numax_CLASS % nu_steps_CLASS;
make_Cl_interps(lmin_CLASS, lmax_CLASS, numin_CLASS, numax_CLASS, nu_steps_CLASS,0,0,0);
}
else
log<LOG_BASIC>("Cls are NOT interpolated");
// Here I could include a code that precomputes the Cls between some lmin and lmax,
// and nu_min and nu_max, then it stores this in a 2D interpolator.
// I need to then create another function so that Cl(...) just returns the interpolated values.
log<LOG_BASIC>("^^^ IntensityMapping class built ^^^");
}
IntensityMapping::~IntensityMapping()
{
}
const int IntensityMapping::getNumin()
{
return this->numin_CLASS;
}
const int IntensityMapping::getNusteps()
{
return this->nu_steps_CLASS;
}
const int IntensityMapping::getNumax()
{
return this->numax_CLASS;
}
const int IntensityMapping::getNustepsize()
{
return model->give_fiducial_params("nu_stepsize");
}
void IntensityMapping::make_Cl_interps(int lmin, int lmax, double nu_min, double nu_max, int nu_steps)
{
double nu_stepsize = abs(nu_max-nu_min)/(double)nu_steps;
for (int l = lmin; l <= lmax; l++)
{
vector<double> vnu, vCl;
for (int i = 0; i <= nu_steps; i++)
{
double nu = nu_min + i*nu_stepsize;
vCl.push_back(this->calc_Cl(l,nu,nu,0,0,0));
vnu.push_back(nu);
}
real_1d_array nu_arr, Cl_arr;
nu_arr.setlength(vnu.size());
Cl_arr.setlength(vCl.size());
for (unsigned int i = 0; i < vnu.size(); i++){
nu_arr[i] = vnu[i];
}
for (unsigned int i = 0; i < vCl.size(); i++){
Cl_arr[i] = vCl[i];
}
spline1dinterpolant interpolator;
spline1dbuildcubic(nu_arr, Cl_arr, interpolator);
Clnu_interpolators.push_back(interpolator);
cout << "Cl for l = " << l << " is interpolated." << endl;
}
}
int IntensityMapping::make_Cl_interps(int lmin, int lmax, double nu_min, double nu_max, int nu_steps,\
int Pk_index, int Tb_index, int q_index)
{
bool do_calc = true;
int index = -1;
for (int i = 0; i < Cls_interpolators_large.size(); i++)
{
if (Cls_interpolators_large[i].Pk_index == Pk_index &&\
Cls_interpolators_large[i].Tb_index == Tb_index &&\
Cls_interpolators_large[i].q_index == q_index)
{
do_calc = false;
index = i;
break;
}
}
if (do_calc)
{
/////////////
log<LOG_BASIC>("... Interpolating Cls for Pk_index = %1%, Tb_index = %2%, q_index = %3% ...") %\
Pk_index % Tb_index % q_index;
double nu_stepsize = abs(nu_max-nu_min)/(double)nu_steps;
vector<double> vnu, vl;
vector<double> vCls;
for (int l = lmin; l <= lmax; l++)
{
vl.push_back(l);
}
for (int i = 0; i <= nu_steps; i++)
{
double nu = nu_min + i*nu_stepsize;
vnu.push_back(nu);
}
for (int l = lmin; l <= lmax; l++)
{
for (int i = 0; i <= nu_steps; i++)
{
double nu = vnu[i];
double cl;
if (LIMBERWINDOW)
{
cl = this->Cl_limber_Window(l,nu,NUWIDTH,Pk_index,Tb_index,q_index);
}
else
{
cl = this->calc_Cl(l,nu,nu,Pk_index,Tb_index,q_index);
}
vCls.push_back(cl);
}
}
real_1d_array nu_arr, l_arr, Cl_arr;
nu_arr.setlength(vnu.size());
Cl_arr.setlength(vCls.size());
l_arr.setlength(vl.size());
for (unsigned int i = 0; i < vnu.size(); i++){
nu_arr[i] = vnu[i];
}
for (unsigned int i = 0; i < vCls.size(); i++){
Cl_arr[i] = vCls[i];
}
for (unsigned int i = 0; i < vl.size(); i++){
l_arr[i] = vl[i];
}
spline2dinterpolant interpolator;
spline2dbuildbilinearv(nu_arr, vnu.size(), l_arr, vl.size(), Cl_arr, 1, interpolator);
CL_INTERP I;
I.Pk_index = Pk_index;
I.Tb_index = Tb_index;
I.q_index = q_index;
I.interpolator = interpolator;
Cls_interpolators_large.push_back(I);
index = Cls_interpolators_large.size() - 1;
log<LOG_BASIC>("... Interpolating Cls is done ...");
/////////////
}
return index;
}
double IntensityMapping::Cl_interp(int l,double nu1)
{
return spline1dcalc(Clnu_interpolators[l], nu1);
}
double IntensityMapping::Cl_interp(int l,double nu1, int Pk_index, int Tb_index, int q_index, int index)
{
if (index < 0 || index >= Cls_interpolators_large.size())
{
cout << "ERROR: SOMETHING WENT HORRIBLY WRONG" << endl;
}
if (nu1 <= numax_CLASS && nu1 >= numin_CLASS)
{
//spline1dcalc((*Cls_interpolators_large)[l][Pk_index][Tb_index][q_index].interpolator, nu1);
//spline1dcalc(Cls_interpolators_large2[l][Pk_index][Tb_index][q_index].interpolator, nu1);
//spline2dinterpolant interp = Cls_interpolators_large[index].interpolator;
return spline2dcalc(Cls_interpolators_large[index].interpolator, nu1, l);
}
else{
cout << "INTERPOLATION ERROR MUST HAVE OCURRED" << numin_CLASS << " " << numax_CLASS << " " << nu1 << endl;
return 0;
}
}
double IntensityMapping::calc_Cl(int l, double nu1, double nu2,\
int Pk_index, int Tb_index, int q_index)
{
//This determines the lower bound of the kappa integral
double k_low = model->give_fiducial_params("kmin");
double k_high = model->give_fiducial_params("kmax");
double low = 0;
if (l < 50){
low = k_low;
} else if (l < 1000){
low = (double)l/(1.2*10000.0);
} else {
low = (double)l/(10000.0);
}
double z1 = 1420.0/nu1 - 1.0;
double z2 = 1420.0/nu2 - 1.0;
double lower_kappa_bound = 0;// = k_low;
if (z1 < 2 or z2 < 2)
{
double r1 = model->q_interp(z1,q_index);
low = (double)l/r1;
}
if (low > k_low)
lower_kappa_bound = low;
else
lower_kappa_bound = k_low;
//This determines the upper bound of the kappa integral
// set the interval size to constant 0.8 after inspection.
// This is good for l about 10000.
double higher_kappa_bound = lower_kappa_bound + 1.0;
if (z1 < 1 or z2 < 1)
{
higher_kappa_bound = lower_kappa_bound + 2;
}
// The stepsize needs to be at least 0.0001 for good coverage.
int steps = (int)(abs(higher_kappa_bound - lower_kappa_bound)/0.0001);
if (steps % 2 == 1)
++steps;
if (z1 > 5.0 or z2 > 5.0)
{
log<LOG_ERROR>("ERROR: bad z range. Cl from IM analysis method is only valid for z < 5.");
}
double dTb1 = model->T21_interp(z1, Tb_index);
double dTb2 = model->T21_interp(z2, Tb_index);
auto integrand = [&](double k)
{
double r1 = model->q_interp(z1,q_index);
double r2 = model->q_interp(z2,q_index);
//TODO: I should probably put the window function in here instead of simply jl
double jl1 = model->sph_bessel_camb(l,k*r1);//I(l, k, nu1)
double jl2 = model->sph_bessel_camb(l,k*r2);//I(l, k, nu2)
double Pdd = P(k,z1,z2, Pk_index);
return k*k*Pdd*jl1*jl2;
};
//TODO: set bias
// b = 2 (b^2 = 4) as in Hall et al. 2013
double BIAS_squared = 4.0;
//cout << lower_kappa_bound << " " << higher_kappa_bound << endl;
double integral = integrate_simps(integrand, lower_kappa_bound, higher_kappa_bound, steps);
return 2.0/(model->pi) * dTb1 * dTb2 * BIAS_squared * integral;
}
double IntensityMapping::Cl(int l, double nu1, double nu2,\
int Pk_index, int Tb_index, int q_index)
{
if (interpolating && interpolate_large)
{
int index = make_Cl_interps(lmin_CLASS, lmax_CLASS, numin_CLASS, numax_CLASS,\
nu_steps_CLASS, Pk_index, Tb_index, q_index);
// The make_... function doesn't do anything if the interpolator already exists,
// so this should be fine.
//make_Ql_interps(lmax_CLASS,numin_CLASS,numax_CLASS,Pk_index,Tb_index,q_index);
return Cl_interp(l, nu1, Pk_index, Tb_index, q_index, index);
}
else if (interpolating && Pk_index == 0 && Tb_index == 0 && q_index == 0)
{
return Cl_interp(l, nu1);
}
else
{
if (LIMBERWINDOW)
{
return Cl_limber_Window(l,nu1,nu2,NUWIDTH,Pk_index,Tb_index,q_index);
if (nu2 > nu1)
{
cout << nu1 << " " << nu2 << endl;
return Cl_limber_Window(l,nu1,nu2,NUWIDTH,Pk_index,Tb_index,q_index);
}
}
else
{
return calc_Cl(l,nu1,nu2,Pk_index, Tb_index, q_index);
}
}
}
double IntensityMapping::Cl_noise(int l, double nu1, double nu2, bool beam_incl)
{
// My thermal noise as well as my beam is now a fun
// This is the thermal noise.
if (nu1 == nu2) {
// in mk
double Tsys = model->give_fiducial_params("Tsys");
double fcover = model->give_fiducial_params("fcover");
//double lmax = model->give_fiducial_params("lmax_noise");
// size of the array.
double D = 20.0;
int lmax = 2.0 * PI * D * nu1 * 1000000.0 / model->c;
// in seconds
double t0 = model->give_fiducial_params("tau_noise");
double res = pow(2.0*model->pi,3) * Tsys*Tsys/(fcover*fcover *\
model->give_fiducial_params("df") * lmax * lmax *t0);
// Now the beam
double beam = 1;
if (beam_incl)
{
double n = 8.0 * log(2.0);
double sigma = PI/(lmax*sqrt(n));
//double sigma = PI/(1500*sqrt(n));
beam = exp(sigma*sigma*l*l);
}
// the result is in (mK)^2
return beam*res;
}
else {
return 0.0;
}
}
double IntensityMapping::Cl_limber_Window(int l, double nu, double nu_width, int Pk_index, int Tb_index, int q_index)
{
update_D_Growth(q_index);
double znu = 1420.0/nu - 1.0;
double zmin, zmax;
double delta_z = znu - (1420.4/(nu+nu_width) - 1);
int steps =100;
if (l < 20)
{
zmin = znu - 4 * delta_z;
zmax = znu + 4 * delta_z;
steps = 80;
}
else
{
zmin = znu - 2 * delta_z;
zmax = znu + 2 * delta_z;
steps = 40;
}
//
double h = model->H_interp(0, q_index) / 100.0;
//cout << h << endl;
auto integrand = [&](double z)
{
double w = Wnu_z(z, nu, nu_width);
double dTb = model->T21_interp(z, Tb_index);
double D = D_Growth_interp(z, q_index);
double r = model->q_interp(z,q_index);
double rp = abs((r - model->q_interp(z+0.0001, q_index))/0.0001);
double k = (l+0.5)/(r*h);
double P = model->Pkz_interp(k,0,Pk_index)/(h*h*h);
double ratio = w*w*dTb*dTb*D*D/(r*r*rp);
return ratio*P;
};
double integral = integrate_simps(integrand, zmin, zmax, steps);
//TODO: set bias
// b = 2 (b^2 = 4) as in Hall et al. 2013
double BIAS_squared = 4.0;
return BIAS_squared * integral;
}
double IntensityMapping::Cl_limber_Window_Olivari(int l, double nu, double nu_width, int Pk_index, int Tb_index, int q_index)
{
update_D_Growth(q_index);
double znu = 1420.0/nu - 1.0;
double numin = nu - nu_width/2.0;
double numax = nu + nu_width/2.0;
double zmin = 1420.0/numax - 1.0;
double zmax = 1420.0/numin - 1.0;
double delta_z = zmax - zmin;
int steps = 100;
double h = model->H_interp(0, q_index) / 100.0;
auto integrand = [&](double z)
{
double w = 1.0/delta_z;
double dTb = model->T21_interp(z, Tb_index);
double D = D_Growth_interp(z, q_index);
double r = model->q_interp(z,q_index);
double rp = abs((r - model->q_interp(z+0.0001, q_index))/0.0001);
double k = (l+0.5)/(r*h);
double P = model->Pkz_interp(k,0,Pk_index)/(h*h*h);
double ratio = w*w*dTb*dTb*D*D/(r*r*rp);
return ratio*P;
};
double integral = integrate_simps(integrand, zmin, zmax, steps);
//TODO: set bias
// b = 2 (b^2 = 4) as in Hall et al. 2013
double BIAS_squared = 1.0;
return BIAS_squared * integral;
}
double IntensityMapping::Cl_limber_Window(int l, double nu, double nu2, double nu_width, int Pk_index, int Tb_index, int q_index)
{
update_D_Growth(q_index);
double znu = 1420.0/nu - 1.0;
double znu2 = 1420.0/nu2 - 1.0;
double zmin, zmax;
double delta_z = znu - (1420.4/(nu+nu_width) - 1);
double delta_z2 = znu - (1420.4/(nu2+nu_width) - 1);
int steps =100;
if (l < 20)
{
zmin = znu - 8 * delta_z;
zmax = znu + 8 * delta_z;
steps = 160;
}
else
{
zmin = znu - 4 * delta_z;
zmax = znu + 4 * delta_z;
steps = 80;
}
//
auto integrand = [&](double z)
{
double w = Wnu_z(z, nu, nu_width);
double w2 = Wnu_z(z, nu2, nu_width);
double dTb = model->T21_interp(z, Tb_index);
double D = D_Growth_interp(z, q_index);
double r = model->q_interp(z,q_index);
double rp = abs((r - model->q_interp(z+0.0001, q_index))/0.0001);
double k = (l+0.5)/r;
double P = model->Pkz_interp(k,0,Pk_index);
double ratio = w*w2*dTb*dTb*D*D/(r*r*rp);
return ratio*P;
};
double integral = integrate_simps(integrand, zmin, zmax, steps);
//TODO: set bias
// b = 2 (b^2 = 4) as in Hall et al. 2013
double BIAS_squared = 4.0;
//cout << lower_kappa_bound << " " << higher_kappa_bound << endl;
// double integral2 = integrate_simps(integrand2, zmin, zmax, steps);
//cout << zmin << " " << zmax << " " << P << " " << D << " " << dTb << " " << rp << " " << r << " " << k << " " << ratio*P*4.0 << endl;
//cout << 1000000*integral2 << " " << 1000000.0*integral << endl;
// We multiply the result by 1000000 to get the Cls in microK!
return BIAS_squared * integral;
}
double IntensityMapping::Cl_Window(int l, double nu1, double nu2, double nu_width, int Pk_index, int Tb_index, int q_index)
{
return 0;
}
double IntensityMapping::Wnu_z(double z, double nu_centre, double nu_width)
{
double pi = M_PI;
double nu = 1420.4/(1.0+z);
double pre = nu/(1.0+z); // There should be a minus sign, but we used that to flip the integration around
double sigma = nu_width / 2.0;
double norm = 1.0/(sqrt(2.0*pi) * sigma);
return pre * norm * exp(-0.5*pow((nu - nu_centre)/sigma,2));
}
//TODO: Review this, make sure it is the same as for tomography2D
double IntensityMapping::Cl_foreground(int l, double nu1, double nu2, map<string,double> FG_param_values)
{
double I1 = 1-pow(log(nu1/nu2),2)/(2.0*pow(FG_param_values["extragal_ps_xi"],2));
double I2 = 1-pow(log(nu1/nu2),2)/(2.0*pow(FG_param_values["extragal_ff_xi"],2));
double I3 = 1-pow(log(nu1/nu2),2)/(2.0*pow(FG_param_values["gal_synch_xi"],2));
double I4 = 1-pow(log(nu1/nu2),2)/(2.0*pow(FG_param_values["gal_ff_xi"],2));
double nu_f = 130.0;
double Cl_nu1_1 = FG_param_values["extragal_ps_A"] *\
pow(1000.0/(double)l, FG_param_values["extragal_ps_beta"]) *\
pow(nu_f/nu1, 2*FG_param_values["extragal_ps_alpha"]);
double Cl_nu1_2 = FG_param_values["extragal_ff_A"] *\
pow(1000.0/(double)l, FG_param_values["extragal_ff_beta"]) *\
pow(nu_f/nu1, 2*FG_param_values["extragal_ff_alpha"]);
double Cl_nu1_3 = FG_param_values["gal_synch_A"] *\
pow(1000.0/(double)l, FG_param_values["gal_synch_beta"]) *\
pow(nu_f/nu1, 2*FG_param_values["gal_synch_alpha"]);
double Cl_nu1_4 = FG_param_values["gal_ff_A"] *\
pow(1000.0/(double)l, FG_param_values["gal_ff_beta"]) *\
pow(nu_f/nu1, 2*FG_param_values["gal_ff_alpha"]);
double Cl_nu2_1 = FG_param_values["extragal_ps_A"] *\
pow(1000.0/(double)l, FG_param_values["extragal_ps_beta"]) *\
pow(nu_f/nu2, 2*FG_param_values["extragal_ps_alpha"]);
double Cl_nu2_2 = FG_param_values["extragal_ff_A"] *\
pow(1000.0/(double)l, FG_param_values["extragal_ff_beta"]) *\
pow(nu_f/nu2, 2*FG_param_values["extragal_ff_alpha"]);
double Cl_nu2_3 = FG_param_values["gal_synch_A"] *\
pow(1000.0/(double)l, FG_param_values["gal_synch_beta"]) *\
pow(nu_f/nu2, 2*FG_param_values["gal_synch_alpha"]);
double Cl_nu2_4 = FG_param_values["gal_ff_A"] *\
pow(1000.0/(double)l, FG_param_values["gal_ff_beta"]) *\
pow(nu_f/nu2, 2*FG_param_values["gal_ff_alpha"]);
double CL = I1 * sqrt(Cl_nu1_1*Cl_nu2_1) + I2 * sqrt(Cl_nu1_2*Cl_nu2_2) +\
I3 * sqrt(Cl_nu1_3*Cl_nu2_3) + I4 * sqrt(Cl_nu1_4*Cl_nu2_4);
return CL;
}
double IntensityMapping::Cl_FG_deriv_analytic(int l, double nu1, double nu2, string param_key)
{
double Cl_p;
double nu_f = 130;
enum FG_PAR
{
extragal_ff_A,
extragal_ff_alpha,
extragal_ff_beta,
extragal_ff_xi,
extragal_ps_A,
extragal_ps_alpha,
extragal_ps_beta,
extragal_ps_xi,
gal_ff_A,
gal_ff_alpha,
gal_ff_beta,
gal_ff_xi,
gal_synch_A,
gal_synch_alpha,
gal_synch_beta,
gal_synch_xi,
};
FG_PAR parameter;
if (param_key == "extragal_ff_A")
parameter = extragal_ff_A;
else if (param_key == "extragal_ps_A")
parameter = extragal_ps_A;
else if (param_key == "gal_ff_A")
parameter = gal_ff_A;
else if (param_key == "gal_synch_A")
parameter = gal_synch_A;
else if (param_key == "extragal_ff_beta")
parameter = extragal_ff_beta;
else if (param_key == "extragal_ps_beta")
parameter = extragal_ps_beta;
else if (param_key == "gal_ff_beta")
parameter = gal_ff_beta;
else if (param_key == "gal_synch_beta")
parameter = gal_synch_beta;
else if (param_key == "extragal_ff_alpha")
parameter = extragal_ff_alpha;
else if (param_key == "extragal_ps_alpha")
parameter = extragal_ps_alpha;
else if (param_key == "gal_ff_alpha")
parameter = gal_ff_alpha;
else if (param_key == "gal_synch_alpha")
parameter = gal_synch_alpha;
else if (param_key == "extragal_ff_xi")
parameter = extragal_ff_xi;
else if (param_key == "extragal_ps_xi")
parameter = extragal_ps_xi;
else if (param_key == "gal_ff_xi")
parameter = gal_ff_xi;
else if (param_key == "gal_synch_xi")
parameter = gal_synch_xi;
switch (parameter) {
case extragal_ff_A:
Cl_p = 1 - pow(log(nu1/nu2), 2) / (2 * pow(FG_param_base_values["extragal_ff_xi"],2));
Cl_p *= pow(1000.0/(double)l, FG_param_base_values["extragal_ff_beta"]);
Cl_p *= pow((nu_f * nu_f) / (nu1 * nu2), FG_param_base_values["extragal_ff_alpha"]);
break;
case extragal_ps_A:
Cl_p = 1 - pow(log(nu1/nu2), 2) / (2 * pow(FG_param_base_values["extragal_ps_xi"],2));
Cl_p *= pow(1000.0/(double)l, FG_param_base_values["extragal_ps_beta"]);
Cl_p *= pow((nu_f * nu_f) / (nu1 * nu2), FG_param_base_values["extragal_ps_alpha"]);
break;
case gal_ff_A:
Cl_p = 1 - pow(log(nu1/nu2), 2) / (2 * pow(FG_param_base_values["gal_ff_xi"],2));
Cl_p *= pow(1000.0/(double)l, FG_param_base_values["gal_ff_beta"]);
Cl_p *= pow((nu_f * nu_f) / (nu1 * nu2), FG_param_base_values["gal_ff_alpha"]);
break;
case gal_synch_A:
Cl_p = 1 - pow(log(nu1/nu2), 2) / (2 * pow(FG_param_base_values["gal_synch_xi"],2));
Cl_p *= pow(1000.0/(double)l, FG_param_base_values["gal_synch_beta"]);
Cl_p *= pow((nu_f * nu_f) / (nu1 * nu2), FG_param_base_values["gal_synch_alpha"]);
break;
case extragal_ff_beta:
Cl_p = 1 - pow(log(nu1/nu2), 2) / (2 * pow(FG_param_base_values["extragal_ff_xi"],2));
Cl_p *= FG_param_base_values["extragal_ff_A"] * log(1000.0/(double)l);
Cl_p *= pow(1000.0/(double)l, FG_param_base_values["extragal_ff_beta"]);
Cl_p *= pow((nu_f * nu_f) / (nu1 * nu2), FG_param_base_values["extragal_ff_alpha"]);
break;
case extragal_ps_beta:
Cl_p = 1 - pow(log(nu1/nu2), 2) / (2 * pow(FG_param_base_values["extragal_ps_xi"],2));
Cl_p *= FG_param_base_values["extragal_ps_A"] * log(1000.0/(double)l);
Cl_p *= pow(1000.0/(double)l, FG_param_base_values["extragal_ps_beta"]);
Cl_p *= pow((nu_f * nu_f) / (nu1 * nu2), FG_param_base_values["extragal_ps_alpha"]);
break;
case gal_ff_beta:
Cl_p = 1 - pow(log(nu1/nu2), 2) / (2 * pow(FG_param_base_values["gal_ff_xi"],2));
Cl_p *= FG_param_base_values["gal_ff_A"] * log(1000.0/(double)l);
Cl_p *= pow(1000.0/(double)l, FG_param_base_values["gal_ff_beta"]);
Cl_p *= pow((nu_f * nu_f) / (nu1 * nu2), FG_param_base_values["gal_ff_alpha"]);
break;
case gal_synch_beta:
Cl_p = 1 - pow(log(nu1/nu2), 2) / (2 * pow(FG_param_base_values["gal_synch_xi"],2));
Cl_p *= FG_param_base_values["gal_synch_A"] * log(1000.0/(double)l);
Cl_p *= pow(1000.0/(double)l, FG_param_base_values["gal_synch_beta"]);
Cl_p *= pow((nu_f * nu_f) / (nu1 * nu2), FG_param_base_values["gal_synch_alpha"]);
break;
case extragal_ff_alpha:
Cl_p = 1 - pow(log(nu1/nu2), 2) / (2 * pow(FG_param_base_values["extragal_ff_xi"],2));
Cl_p *= FG_param_base_values["extragal_ff_A"] * log((nu_f * nu_f)/(nu1 * nu2));
Cl_p *= pow(1000.0/(double)l, FG_param_base_values["extragal_ff_beta"]);
Cl_p *= pow((nu_f * nu_f) / (nu1 * nu2), FG_param_base_values["extragal_ff_alpha"]);
break;
case extragal_ps_alpha:
Cl_p = 1 - pow(log(nu1/nu2), 2) / (2 * pow(FG_param_base_values["extragal_ps_xi"],2));
Cl_p *= FG_param_base_values["extragal_ps_A"] * log((nu_f * nu_f)/(nu1 * nu2));
Cl_p *= pow(1000.0/(double)l, FG_param_base_values["extragal_ps_beta"]);
Cl_p *= pow((nu_f * nu_f) / (nu1 * nu2), FG_param_base_values["extragal_ps_alpha"]);
break;
case gal_ff_alpha:
Cl_p = 1 - pow(log(nu1/nu2), 2) / (2 * pow(FG_param_base_values["gal_ff_xi"],2));
Cl_p *= FG_param_base_values["gal_ff_A"] * log((nu_f * nu_f)/(nu1 * nu2));
Cl_p *= pow(1000.0/(double)l, FG_param_base_values["gal_ff_beta"]);
Cl_p *= pow((nu_f * nu_f) / (nu1 * nu2), FG_param_base_values["gal_ff_alpha"]);
break;
case gal_synch_alpha:
Cl_p = 1 - pow(log(nu1/nu2), 2) / (2 * pow(FG_param_base_values["gal_synch_xi"],2));
Cl_p *= FG_param_base_values["gal_synch_A"] * log((nu_f * nu_f)/(nu1 * nu2));
Cl_p *= pow(1000.0/(double)l, FG_param_base_values["gal_synch_beta"]);
Cl_p *= pow((nu_f * nu_f) / (nu1 * nu2), FG_param_base_values["gal_synch_alpha"]);
break;
case extragal_ff_xi:
Cl_p = pow(log(nu1/nu2), 2) / pow(FG_param_base_values["extragal_ff_xi"], 3);
Cl_p *= FG_param_base_values["extragal_ff_A"];
Cl_p *= pow(1000.0/(double)l, FG_param_base_values["extragal_ff_beta"]);
Cl_p *= pow((nu_f * nu_f) / (nu1 * nu2), FG_param_base_values["extragal_ff_alpha"]);
break;
case extragal_ps_xi:
Cl_p = pow(log(nu1/nu2), 2) / pow(FG_param_base_values["extragal_ps_xi"], 3);
Cl_p *= FG_param_base_values["extragal_ps_A"];
Cl_p *= pow(1000.0/(double)l, FG_param_base_values["extragal_ps_beta"]);
Cl_p *= pow((nu_f * nu_f) / (nu1 * nu2), FG_param_base_values["extragal_ps_alpha"]);
break;
case gal_ff_xi:
Cl_p = pow(log(nu1/nu2), 2) / pow(FG_param_base_values["gal_ff_xi"], 3);
Cl_p *= FG_param_base_values["gal_ff_A"];
Cl_p *= pow(1000.0/(double)l, FG_param_base_values["gal_ff_beta"]);
Cl_p *= pow((nu_f * nu_f) / (nu1 * nu2), FG_param_base_values["gal_ff_alpha"]);
break;
case gal_synch_xi:
Cl_p = pow(log(nu1/nu2), 2) / pow(FG_param_base_values["gal_synch_xi"], 3);
Cl_p *= FG_param_base_values["gal_synch_A"];
Cl_p *= pow(1000.0/(double)l, FG_param_base_values["gal_synch_beta"]);
Cl_p *= pow((nu_f * nu_f) / (nu1 * nu2), FG_param_base_values["gal_synch_alpha"]);
break;
default:
log<LOG_ERROR>("Error: The FG parameter passed to the derivative function is not understood.");
log<LOG_ERROR>(" param_key = %1%.") % param_key;
Cl_p = 0;
break;
}
return Cl_p;
}
double IntensityMapping::P(double k, double z1, double z2, double Pk_index)
{
return sqrt(model->Pkz_interp(k,z1,Pk_index)*model->Pkz_interp(k,z2,Pk_index));
}
double IntensityMapping::D_Growth(double z)
{
auto integrand = [&](double zp)
{
double H3 = this->model->Hf_interp(zp);
H3 = pow(H3, 3);
return (1+zp)/H3;
};
double I1 = integrate(integrand, z, 10000.0, 100000, simpson());
double pre = Growth_function_norm * this->model->Hf_interp(z) /\
this->model->Hf_interp(0);
return pre * I1;
}
double IntensityMapping::D_Growth(double z, int q_index)
{
auto integrand = [&](double zp)
{
double H3 = this->model->H_interp(zp, q_index);
H3 = pow(H3, 3);
return (1+zp)/H3;
};
double I1 = integrate(integrand, z, 10000.0, 100000, simpson());
if (q_index >= Growth_function_norms.size())
cout << "ERROR: D(z) normalization error" << endl;
double pre = Growth_function_norms[q_index] * this->model->H_interp(z,q_index) /\
this->model->H_interp(0,q_index);
return pre * I1;
}
void IntensityMapping::update_D_Growth(int q_index)
{
bool do_calc = true;
for (int i = 0; i < growth_function_interps.size(); i++)
{
if (growth_function_interps[i].q_index == q_index)
{
do_calc = false;
}
}
if (do_calc)
{
auto integrand = [&](double z)
{
double H3 = this->model->H_interp(z,q_index);
H3 = pow(H3, 3);
return (1.0+z)/H3;
};
double I1 = integrate(integrand, 0.0, 10000.0, 1000000, simpson());
double norm = 1.0/I1;
Growth_function_norms.push_back(norm);
vector<double> zs_v, D_v;
// Should precalculate to at least z = 10000.
// Although this takes 20 seconds each run, which is annoying.
zs_v.resize(1000);
D_v.resize(1000);
#pragma omp parallel for
for (int i = 0; i < 1000; i++)
{
double z = i*0.1;
double D = D_Growth(z, q_index);
zs_v[i] = z;
D_v[i] = D;
}
real_1d_array zs, D_pluss;
zs.setlength(zs_v.size());
D_pluss.setlength(D_v.size());
for (unsigned int i = 0; i < zs_v.size(); i++){
zs[i] = zs_v[i];
}
for (unsigned int i = 0; i < D_v.size(); i++){
D_pluss[i] = D_v[i];
}
spline1dinterpolant interp;
spline1dbuildcubic(zs, D_pluss, interp);
D_INTERP D;
D.q_index = q_index;
D.interpolator = interp;
growth_function_interps.push_back(D);
log<LOG_BASIC>("... Growth function updated for q_index = %1% ...") % q_index;
}
}
double IntensityMapping::D_Growth_interp(double z, int q_index)
{
int index = -1;
for (int i = 0; i < growth_function_interps.size(); i++)
{
if (growth_function_interps[i].q_index == q_index)
{
index = i;
break;
}
}
if (index < 0)
{
cout << "ERROR: growth function in IntensityMapping gone wrong" << endl;
return 0;
}
else
{
double result = spline1dcalc(growth_function_interps[index].interpolator, z);
if (result == 0)
{
cout << "ERROR in D_GROWTH_INTERP: index = " << index << ", D(z=" << z << ") = " <<\
result << endl;
}
return result;
}
}
/** TEST CLASS **/
TEST_IntensityMapping::TEST_IntensityMapping(ModelInterface* model, int num_params)
:
IntensityMapping(model,num_params)
{}
|
#pragma once
#include "shortestPathAlgorithm.h"
#include "MyVector.h"
class DijkstraMatrixAlgorithm: public shortestPathAlgorithm
{
public:
DijkstraMatrixAlgorithm(Graph & graph);
virtual ~DijkstraMatrixAlgorithm();
virtual void startAlgorithm() final;
protected:
MyVector unvisitedVertrexVec;
virtual void relaxation(int, int) ;
virtual int getVertrexWithLeastPath() final;
virtual void relaxationForNeighborhoods(int) ;
virtual void removeVertrexFromUnvisited(int) final;
};
|
#include <iostream>
#include <vector>
using namespace std;
#define int long long
#define F first
#define S second
#define P pair<int,int>
#define pb push_back
#define endl '\n'
const int N = 3e1 + 5;
vector <int> Graph[N];
int vis[N];
int n;
vector <P> ans(N);
int row[] = {1, 0, -1, 0};
int col[] = {0, 1, 0, -1};
void dfs(int src, int dir, int len) {
vis[src] = 1;
dir = (dir + 3) % 4;
for (auto to : Graph[src]) {
if (!vis[to]) {
ans[to].F = ans[src].F + row[dir] * len;
ans[to].S = ans[src].S + col[dir] * len;
dfs(to, dir, len >> 1LL);
dir = (dir + 1) % 4;
}
}
}
void solve() {
cin >> n;
for (int i = 1; i <= n - 1; i++) {
int u, v; cin >> u >> v;
Graph[u].pb(v);
Graph[v].pb(u);
}
for (int i = 1; i <= n; i++) {
if (Graph[i].size() > 4) {
cout << "NO";
return ;
}
}
dfs(1, 0, 1LL << n);
cout << "YES" << endl;
for (int i = 1; i <= n; i++) {
cout << ans[i].F << " " << ans[i].S << endl;
}
return ;
}
int32_t main() {
ios_base:: sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
// code starts
//int t;cin>>t;while(t--)
solve();
return 0;
}
|
/**
@file
@author Nicholas Gillian <ngillian@media.mit.edu>
@version 1.0
@section LICENSE
GRT MIT License
Copyright (c) <2012> <Nicholas Gillian, Media Lab, MIT>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
GRT Custom Makefile
This example provides a basic makefile template for the GRT.
*/
//You might need to set the specific path of the GRT header relative to your project
#include <GRT/GRT.h>
using namespace GRT;
#include <fstream>
using namespace std;
int main (int argc, const char * argv[])
{
TimeSeriesClassificationData trainingData; //This will store our training data
GestureRecognitionPipeline pipeline; //This is a wrapper for our classifier and any pre/post processing modules
string dirPath = "/home/vlad/AndroidStudioProjects/DataCapture/dataSetGenerator/build";
if (!trainingData.loadDatasetFromFile(dirPath + "/acc-training-set-segmented.data")) {
printf("Cannot open training set\n");
return 0;
}
printf("Successfully opened training data set ...\n");
DTW dtw;
// LowPassFilter lpf(0.1, 1, 3);
// pipeline.setPreProcessingModule(lpf);
// DoubleMovingAverageFilter filter( 1000, 3 );
// pipeline.setPreProcessingModule(filter);
dtw.enableNullRejection( true );
//Set the null rejection coefficient to 3, this controls the thresholds for the automatic null rejection
//You can increase this value if you find that your real-time gestures are not being recognized
//If you are getting too many false positives then you should decrease this value
dtw.setNullRejectionCoeff( 5 );
// dtw.enableTrimTrainingData(true, 0.1, 90);
// dtw.setOffsetTimeseriesUsingFirstSample(true);
pipeline.setClassifier( dtw );
pipeline.train(trainingData, 5);
//You can then get then get the accuracy of how well the pipeline performed during the k-fold cross validation testing
double accuracy = pipeline.getCrossValidationAccuracy();
printf("Accuracy: %f", accuracy);
}
|
#include "core.h"
int** changec(int size, int** array, int colfor, int colfrom)
{
for (int i = 0; i < size; i++)
{
int tmp = array[i][colfor];
array[i][colfor] = array[i][colfrom];
array[i][colfrom] = tmp;
}
return array;
}
|
/**
* @file
* @copyright defined in EOTS/LICENSE.txt
*/
#include <eotio/chain/genesis_state.hpp>
// these are required to serialize a genesis_state
#include <fc/smart_ref_impl.hpp> // required for gcc in release mode
namespace eotio { namespace chain {
chain::chain_id_type genesis_state::compute_chain_id() const {
return initial_chain_id;
}
} } // namespace eotio::chain
|
#pragma once
#include"Behaviour.h"
#include"Agent.h"
class PursueBehaviour : public Behaviour
{
public:
PursueBehaviour();
virtual ~PursueBehaviour();
virtual vector2 Update(Agent* agent, float deltaTime);
virtual float GetWeight() { return weight; };
void SetTarget(Agent* target) { m_target = target;}; //set the thing we are pursuing
private:
Agent* m_target; // who are we pursuing
float Speed = 40; // how fast we move to that point
float weight = 1;
};
|
#pragma once
#include <string>
#include <map>
#include <memory>
#include <tuple>
#include <wincodec.h>
#include <d2d1_2.h>
#include "util.h"
COM_MAKE_PTR(ID2D1Bitmap);
COM_MAKE_PTR(IWICBitmapFrameDecode);
COM_MAKE_PTR(ID2D1HwndRenderTarget);
enum tint {
green,
blue,
red
};
typedef std::pair<std::string, tint> bitmap_ident;
inline
bitmap_ident make_ident(std::string const &s) {
return std::make_pair(s, green);
}
inline
bitmap_ident make_ident(std::string const &s, tint t) {
return std::make_pair(s, t);
}
struct color_value {
unsigned char b, g, r, a;
bool operator==(color_value const &other) {
return abs(b - other.b) < 10 && abs(g - other.g) < 10 && abs(r - other.r) < 10 && abs(a - other.a) < 10;
}
};
inline color_value make_color(unsigned char b, unsigned char g, unsigned char r, unsigned char a) {
color_value value = { b, g, r, a };
return value;
}
struct bound_bitmap {
unsigned hotspot_x, hotspot_y;
ID2D1BitmapPtr d2d_bitmap;
ID2D1Bitmap *get() { return d2d_bitmap; }
ID2D1Bitmap *operator->() { return d2d_bitmap; }
};
class bitmap {
static IWICImagingFactory *wic_factory;
unsigned hotspot_x, hotspot_y;
IWICBitmapFrameDecodePtr frame;
public:
bitmap();
bitmap(std::wstring const &filename);
~bitmap();
operator HCURSOR();
bound_bitmap bind(ID2D1HwndRenderTarget &render_target, tint);
};
class asset_library {
std::map<std::string, std::shared_ptr<bitmap>> bitmaps;
std::map<bitmap_ident, std::shared_ptr<bound_bitmap>> bound_bitmaps;
public:
void load();
void bind(ID2D1HwndRenderTargetPtr render_target);
bound_bitmap operator[](bitmap_ident const &ident);
};
|
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int p[300100],lazy[300100];
void build(int l,int r,int pos)
{
if (l == r)
{scanf("%d",p+pos);
return;
}
int mid = (l+r) >> 1;
build(l,mid,pos*2);
build(mid+1,r,pos*2+1);
p[pos] = p[pos*2]+p[pos*2+1];
}
void change(int l,int r,int pos,int x,int y,int w)
{
if (l >= x && r <= y)
{lazy[pos] = w;
p[pos] = w*(r-l+1);
return;
}
int mid = (l+r) >> 1;
if (lazy[pos])
{lazy[pos*2] = lazy[pos];
p[pos*2] = lazy[pos]*(mid-l+1);
lazy[pos*2+1] = lazy[pos];
p[pos*2+1] = lazy[pos]*(r-mid);
lazy[pos] = 0;
}
if (x <= mid) change(l,mid,pos*2,x,y,w);
if (y > mid) change(mid+1,r,pos*2+1,x,y,w);
p[pos] = p[pos*2]+p[pos*2+1];
}
int ask(int l,int r,int pos,int x,int y)
{int ans = 0;
if (l >= x && r <= y) return p[pos];
int mid = (l+r) >> 1;
if (lazy[pos])
{lazy[pos*2] = lazy[pos];
p[pos*2] = lazy[pos]*(mid-l+1);
lazy[pos*2+1] = lazy[pos];
p[pos*2+1] = lazy[pos]*(r-mid);
lazy[pos] = 0;
}
if (x <= mid) ans += ask(l,mid,pos*2,x,y);
if (y > mid) ans += ask(mid+1,r,pos*2+1,x,y);
return ans;
}
int main()
{int n,q;
cin >> n;
build(1,n,1);
cin >> q;
for (int i = 1;i <= q; i++)
{int t,l,r,v;
scanf("%d%d%d",&t,&l,&r);
if (t)
{scanf("%d",&v);
change(1,n,1,l,r,v);
}
else printf("%d\n",ask(1,n,1,l,r));
}
return 0;
}
|
#pragma once
#include "IPartWndProc.h"
class KeyboardWndProc : public ytyaru::Framework::WndProc::IPartWndProc
{
public:
KeyboardWndProc(void);
~KeyboardWndProc(void);
LRESULT CALLBACK PartWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL* pIsReturn);
};
|
/*
* Copyright (c) 2014-2017 Detlef Vollmann, vollmann engineering gmbh
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
#include "rectangle.hh"
#include "extgraph.hh"
namespace exercise
{
Rectangle::Rectangle(double width, double height)
: w(width)
, h(height)
{
}
void Rectangle::preparePath(cairo_t *cr, Position xy) const
{
cairo_rectangle(cr, xy.x, xy.y, w, h);
}
} // namespace exercise
|
#ifndef __POW_HPP__
#define __POW_HPP__
#include "base.hpp"
#include <math.h>
class Pow : public Base {
public:
Pow(Base* op1, Base* op2) : Base(), operand1(op1), operand2(op2) {}
std::string stringify() { return "(" + operand1->stringify() + " ** " + operand2->stringify() + ")";}
double evaluate() {
return pow(operand1->evaluate(), operand2->evaluate());
}
private:
Base* operand1;
Base* operand2;
};
#endif
|
// ************************* String functions **************************
inline int numc(char c) { return c <= 'Z' ? c - 'A' : c - 'a' + 26; }
void prefix_function(const char *s, int *pi) {
int n = strlen(s);
for (int i = 1; i < n; ++i) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j]) j = pi[j - 1];
if (s[i] == s[j]) ++j;
pi[i] = j;
}
}
void z_function(const char *st, int *z) {
int i, j = 0, r = 0, l;
z[0] = l = strlen(st);
z[l] = '#';
for (i = 1; i < l; ++i) {
if (i <= r)
z[i] = min(r - i, z[i - j]);
else
z[i] = 0;
for ( ; st[z[i]] == st[i + z[i]]; ++z[i]);
if (i + z[i] > r) {
r = i + z[i];
j = i;
}
}
}
// Lyndon decomposition and minimal cyclical shift search in O(n)
string min_cyclic_shift(string s) {
s += s;
int n = (int) s.length();
int i = 0, ans = 0;
while (i < n / 2) {
ans = i;
int j = i + 1, k = i;
while (j < n && s[k] <= s[j]) {
if (s[k] < s[j]) k = i;
else ++k;
++j;
}
while (i <= k) i += j - k;
}
return s.substr(ans, n / 2);
}
// Palindromes
int l = 0, r = -1;
for (int i = 0; i < n; ++i) {
int k = (i > r ? 1 : min(d1[l + r - i], r - i));
while (i + k < n && i - k >= 0 && s[i + k] == s[i - k]) ++k;
d1[i] = k--;
if (i + k > r) {
l = i - k;
r = i + k;
}
}
l = 0, r = -1;
for (int i = 0; i < n; ++i) {
int k = (i > r ? 0 : min(d2[l + r - i + 1], r - i + 1)) + 1;
while (i + k - 1 < n && i - k >= 0 && s[i + k - 1] == s[i - k]) ++k;
d2[i] = --k;
if (i + k - 1 > r) {
l = i - k;
r = i + k - 1;
}
}
|
// Created on: 1995-06-02
// Created by: Xavier BENVENISTE
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Approx_SameParameter_HeaderFile
#define _Approx_SameParameter_HeaderFile
#include <Adaptor3d_CurveOnSurface.hxx>
#include <Adaptor3d_Surface.hxx>
class Geom_Curve;
class Geom2d_Curve;
class Geom_Surface;
//! Approximation of a PCurve on a surface to make its
//! parameter be the same that the parameter of a given 3d
//! reference curve.
class Approx_SameParameter
{
public:
DEFINE_STANDARD_ALLOC
//! Warning: the C3D and C2D must have the same parametric domain.
Standard_EXPORT Approx_SameParameter(const Handle(Geom_Curve)& C3D,
const Handle(Geom2d_Curve)& C2D,
const Handle(Geom_Surface)& S,
const Standard_Real Tol);
//! Warning: the C3D and C2D must have the same parametric domain.
Standard_EXPORT Approx_SameParameter(const Handle(Adaptor3d_Curve)& C3D,
const Handle(Geom2d_Curve)& C2D,
const Handle(Adaptor3d_Surface)& S,
const Standard_Real Tol);
//! Warning: the C3D and C2D must have the same parametric domain.
Standard_EXPORT Approx_SameParameter(const Handle(Adaptor3d_Curve)& C3D,
const Handle(Adaptor2d_Curve2d)& C2D,
const Handle(Adaptor3d_Surface)& S,
const Standard_Real Tol);
//!@Returns .false. if calculations failed,
//! .true. if calculations succeed
Standard_Boolean IsDone() const
{
return myDone;
}
//!@Returns tolerance (maximal distance) between 3d curve
//! and curve on surface, generated by 2d curve and surface.
Standard_Real TolReached() const
{
return myTolReached;
}
//! Tells whether the original data had already the same
//! parameter up to the tolerance : in that case nothing
//! is done.
Standard_Boolean IsSameParameter() const
{
return mySameParameter;
}
//! Returns the 2D curve that has the same parameter as
//! the 3D curve once evaluated on the surface up to the
//! specified tolerance.
Handle(Geom2d_Curve) Curve2d() const
{
return myCurve2d;
}
//! Returns the 3D curve that has the same parameter as
//! the 3D curve once evaluated on the surface up to the
//! specified tolerance.
Handle(Adaptor3d_Curve) Curve3d() const
{
return myC3d;
}
//! Returns the 3D curve on surface that has the same parameter as
//! the 3D curve up to the specified tolerance.
Handle(Adaptor3d_CurveOnSurface) CurveOnSurface() const
{
return myCurveOnSurface;
}
private:
//! Internal data structure to unify access to the most actively used data.
//! This structure is not intended to be class field since
//! a lot of memory is used in intermediate computations.
struct Approx_SameParameter_Data
{
Adaptor3d_CurveOnSurface myCOnS; // Curve on surface.
Standard_Integer myNbPnt; // Number of points.
Standard_Real *myPC3d; // Parameters on 3d curve.
Standard_Real *myPC2d; // Parameters on 2d curve.
// Second data arrays. Used in loop over poles.
Standard_Real *myNewPC3d; // Parameters on 3d curve.
Standard_Real *myNewPC2d; // Parameters on 2d curve.
// Parameters ranges.
Standard_Real myC3dPF; // Curve 3d Parameter First.
Standard_Real myC3dPL; // Curve 3d Parameter Last.
Standard_Real myC2dPF; // Curve 2d Parameter First.
Standard_Real myC2dPL; // Curve 2d Parameter Last.
Standard_Real myTol; // Working tolerance.
// Swap data arrays and update number of points.
void Swap(const Standard_Integer theNewNbPoints)
{
myNbPnt = theNewNbPoints;
Standard_Real * temp;
// 3-D
temp = myPC3d;
myPC3d = myNewPC3d;
myNewPC3d = temp;
// 2-D
temp = myPC2d;
myPC2d = myNewPC2d;
myNewPC2d = temp;
}
};
Approx_SameParameter(const Approx_SameParameter &);
Approx_SameParameter& operator=(const Approx_SameParameter &);
//! Computes the pcurve (internal use only).
Standard_EXPORT void Build (const Standard_Real Tol);
//! Computes initial point distribution.
Standard_Boolean BuildInitialDistribution(Approx_SameParameter_Data &theData) const;
//! Increases initial number of samples in case of the C0 continuity.
//! Return new number of points and corresponding data arrays.
//@return true if new number of samples is good and false otherwise.
Standard_Boolean IncreaseInitialNbSamples(Approx_SameParameter_Data &theData) const;
//! Computes tangents on boundary points.
//@return true if tangents are not null and false otherwise.
Standard_Boolean ComputeTangents(const Adaptor3d_CurveOnSurface & theCOnS,
Standard_Real &theFirstTangent,
Standard_Real &theLastTangent) const;
//! Method to check same parameter state
//! and build dependency between 2d and 3d curves.
//@return true if 2d and 3d curves have same parameter state and false otherwise.
Standard_Boolean CheckSameParameter(Approx_SameParameter_Data &theData,
Standard_Real &theSqDist) const;
//! Computes interpolated values.
//!@Returns .false. if computations failed;
Standard_Boolean Interpolate(const Approx_SameParameter_Data & theData,
const Standard_Real aTangFirst,
const Standard_Real aTangLast,
TColStd_Array1OfReal & thePoles,
TColStd_Array1OfReal & theFlatKnots) const;
//! Increases number of poles in poles loop.
//@return true if poles is changed and false otherwise.
Standard_Boolean IncreaseNbPoles(const TColStd_Array1OfReal & thePoles,
const TColStd_Array1OfReal & theFlatKnots,
Approx_SameParameter_Data & theData,
Standard_Real &theBestSqTol) const;
static const Standard_Integer myNbSamples = 22; // To be consistent with "checkshape".
static const Standard_Integer myMaxArraySize = 1000;
const Standard_Real myDeltaMin; // Initialization is allowed only for integral types.
Standard_Boolean mySameParameter;
Standard_Boolean myDone;
Standard_Real myTolReached;
Handle(Geom2d_Curve) myCurve2d;
Handle(Adaptor2d_Curve2d) myHCurve2d;
Handle(Adaptor3d_Curve) myC3d;
Handle(Adaptor3d_Surface) mySurf;
Handle(Adaptor3d_CurveOnSurface) myCurveOnSurface;
};
#endif // _Approx_SameParameter_HeaderFile
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.