text
stringlengths 8
6.88M
|
|---|
// Created on: 2007-05-14
// Created by: data exchange team
// Copyright (c) 2007-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 Units_Operators_HeaderFile
#define Units_Operators_HeaderFile
#include <Units_Token.hxx>
#include <Units_Quantity.hxx>
Standard_EXPORT Standard_Boolean operator ==(const Handle(Units_Quantity)&,const Standard_CString);
Standard_EXPORT Standard_Boolean operator ==(const Handle(Units_Token)&,const Standard_CString);
Standard_EXPORT Standard_Boolean operator ==(const Handle(Units_Unit)&,const Standard_CString);
Standard_EXPORT Handle(Units_Dimensions) operator *(const Handle(Units_Dimensions)&,const Handle(Units_Dimensions)&);
Standard_EXPORT Handle(Units_Dimensions) operator /(const Handle(Units_Dimensions)&,const Handle(Units_Dimensions)&);
Standard_EXPORT Handle(Units_Dimensions) pow(const Handle(Units_Dimensions)&,const Standard_Real);
Standard_EXPORT Handle(Units_Token) pow(const Handle(Units_Token)&,const Handle(Units_Token)&);
Standard_EXPORT Handle(Units_Token) pow(const Handle(Units_Token)&,const Standard_Real);
Standard_EXPORT Handle(Units_Token) operator +(const Handle(Units_Token)&,const Standard_Integer);
Standard_EXPORT Handle(Units_Token) operator +(const Handle(Units_Token)&,const Handle(Units_Token)&);
Standard_EXPORT Handle(Units_Token) operator -(const Handle(Units_Token)&,const Handle(Units_Token)&);
Standard_EXPORT Handle(Units_Token) operator *(const Handle(Units_Token)&,const Handle(Units_Token)&);
Standard_EXPORT Handle(Units_Token) operator /(const Handle(Units_Token)&,const Handle(Units_Token)&);
Standard_EXPORT Standard_Boolean operator !=(const Handle(Units_Token)&,const Standard_CString);
Standard_EXPORT Standard_Boolean operator <=(const Handle(Units_Token)&,const Standard_CString);
Standard_EXPORT Standard_Boolean operator >(const Handle(Units_Token)&,const Standard_CString);
Standard_EXPORT Standard_Boolean operator >(const Handle(Units_Token)&,const Handle(Units_Token)&);
Standard_EXPORT Standard_Boolean operator >=(const Handle(Units_Token)&,const Handle(Units_Token)&);
#endif
|
#pragma once
#include <vector>
#include <set>
#include <Core/Exception.h>
#include <Lattice2D.h>
/*
* Class that computes topological order of vertices in a lattice
* The lattice/graph must be a directed acyclic graph (DAG).
* else it throws an exception
*/
namespace PyMesh
{
namespace LatticeAlgorithms
{
namespace TopologicalOrder
{
std::vector<unsigned int> compute_full(const Lattice2D::Ptr& lattice);
std::vector<unsigned int> compute(const Lattice2D::Ptr& lattice, const std::set<unsigned int>& edge_indices);
}
}
}
|
#include <nan.h>
#include "webp/encode.h"
#include "webp/decode.h"
#include "./util.hpp"
void Util::formatWebPConfig(WebPConfig *config, v8::Local<v8::Object> obj)
{
if (!(obj->Get(Nan::New<v8::String>("lossless").ToLocalChecked())->IsUndefined()))
config->lossless = obj->Get(Nan::New<v8::String>("lossless").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("quality").ToLocalChecked())->IsUndefined()))
config->quality = (float)obj->Get(Nan::New<v8::String>("quality").ToLocalChecked())->NumberValue();
if (!(obj->Get(Nan::New<v8::String>("method").ToLocalChecked())->IsUndefined()))
config->method = obj->Get(Nan::New<v8::String>("method").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("target_size").ToLocalChecked())->IsUndefined()))
config->target_size = obj->Get(Nan::New<v8::String>("target_size").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("target_PSNR").ToLocalChecked())->IsUndefined()))
config->target_PSNR = (float)obj->Get(Nan::New<v8::String>("target_PSNR").ToLocalChecked())->NumberValue();
if (!(obj->Get(Nan::New<v8::String>("segments").ToLocalChecked())->IsUndefined()))
config->segments = obj->Get(Nan::New<v8::String>("segments").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("sns_strength").ToLocalChecked())->IsUndefined()))
config->sns_strength = obj->Get(Nan::New<v8::String>("sns_strength").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("filter_strength").ToLocalChecked())->IsUndefined()))
config->filter_strength = obj->Get(Nan::New<v8::String>("filter_strength").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("filter_sharpness").ToLocalChecked())->IsUndefined()))
config->filter_sharpness = obj->Get(Nan::New<v8::String>("filter_sharpness").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("filter_type").ToLocalChecked())->IsUndefined()))
config->filter_type = obj->Get(Nan::New<v8::String>("filter_type").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("autofilter").ToLocalChecked())->IsUndefined()))
config->autofilter = obj->Get(Nan::New<v8::String>("autofilter").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("alpha_compression").ToLocalChecked())->IsUndefined()))
config->alpha_compression = obj->Get(Nan::New<v8::String>("alpha_compression").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("alpha_filtering").ToLocalChecked())->IsUndefined()))
config->alpha_filtering = obj->Get(Nan::New<v8::String>("alpha_filtering").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("alpha_quality").ToLocalChecked())->IsUndefined()))
config->alpha_quality = obj->Get(Nan::New<v8::String>("alpha_quality").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("pass").ToLocalChecked())->IsUndefined()))
config->pass = obj->Get(Nan::New<v8::String>("pass").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("show_compressed").ToLocalChecked())->IsUndefined()))
config->show_compressed = obj->Get(Nan::New<v8::String>("show_compressed").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("preprocessing").ToLocalChecked())->IsUndefined()))
config->preprocessing = obj->Get(Nan::New<v8::String>("preprocessing").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("partitions").ToLocalChecked())->IsUndefined()))
config->partitions = obj->Get(Nan::New<v8::String>("partitions").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("partition_limit").ToLocalChecked())->IsUndefined()))
config->partition_limit = obj->Get(Nan::New<v8::String>("partition_limit").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("emulate_jpeg_size").ToLocalChecked())->IsUndefined()))
config->emulate_jpeg_size = obj->Get(Nan::New<v8::String>("emulate_jpeg_size").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("thread_level").ToLocalChecked())->IsUndefined()))
config->thread_level = obj->Get(Nan::New<v8::String>("thread_level").ToLocalChecked())->Uint32Value();
if (!(obj->Get(Nan::New<v8::String>("low_memory").ToLocalChecked())->IsUndefined()))
config->low_memory = obj->Get(Nan::New<v8::String>("low_memory").ToLocalChecked())->Uint32Value();
}
|
#include "mouselabel.h"
MouseLabel::MouseLabel(QWidget* parent):
QLabel(parent)
{
}
void MouseLabel::mousePressEvent(QMouseEvent *ev)
{
this->x = ev->x();
this->y = ev->y();
emit Mouse_Pressed();
}
void MouseLabel::mouseDoubleClickEvent(QMouseEvent *ev)
{
emit Mouse_DoubleClick();
}
void MouseLabel::leaveEvent(QEvent *ev)
{
emit Mouse_Left();
}
MouseLabel::~MouseLabel()
{
}
|
#include "Configurator.h"
#include <QFile>
#include <QMap>
#include <QPair>
#include <QString>
#include <QTextStream>
// :: Constants ::
const QString CONFIG_FILE_NAME = "config.ini";
const QString HOST_NAME_KEY = "HOST_NAME";
const QString PORT_KEY = "PORT";
const QString DEFAULT_HOST_NAME = "localhost";
#ifdef QT_DEBUG
const QString DEFAULT_PORT = "51971";
#else
const QString DEFAULT_PORT = "5000";
#endif
// :: Static fields ::
QMap<QString, QString> Configurator::m_configurations {
{HOST_NAME_KEY, DEFAULT_HOST_NAME},
{PORT_KEY, DEFAULT_PORT}
};
// :: Public methods ::
void Configurator::readConfigurations() {
QFile file(CONFIG_FILE_NAME);
if(file.open(QIODevice::ReadOnly)) {
QTextStream fstream(&file);
while(!fstream.atEnd()) {
QString line = fstream.readLine();
auto keyValue = handleLine(line);
QMap<QString, QString>::iterator iter;
iter = m_configurations.find(keyValue.first);
if(iter != m_configurations.end()) {
*iter = keyValue.second;
}
}
file.close();
} else {
writeDefaultConfigurationsFile();
}
}
QString Configurator::getHostName() {
return m_configurations[HOST_NAME_KEY];
}
int Configurator::getPort() {
return m_configurations[PORT_KEY].toInt();
}
// :: Private methods ::
QPair<QString, QString> Configurator::handleLine(QString line) {
QString key, value;
line = line.trimmed();
int separatorPos = line.indexOf('=');
if(separatorPos < 0) {
// Попробуем найти хотя бы пробел
separatorPos = line.indexOf(' ');
if(separatorPos < 0) {
line.clear();
}
}
key = value = line;
key.remove(separatorPos, line.size());
value.remove(0, separatorPos + 1);
return qMakePair(key.trimmed(), value.trimmed());
}
void Configurator::writeDefaultConfigurationsFile() {
QFile file(CONFIG_FILE_NAME);
file.open(QIODevice::WriteOnly);
QTextStream fstream(&file);
auto iter = m_configurations.cbegin();
while(iter != m_configurations.cend()) {
fstream << iter.key() << " = " << *iter << "\r\n";
iter++;
}
file.close();
}
|
#ifndef _Configure_H
#define _Configure_H
#include <time.h>
#include <unistd.h>
#include <string>
#include "Typedef.h"
typedef struct _checkHost
{
char host[32];
short port;
}checkHost;
#define MAX_ALLOC_NUM 8
class Configure
{
public:
static Configure* getInstance() {
static Configure * configure = NULL;
if(configure==NULL)
configure = new Configure();
return configure;
}
int parse_args(int argc, char *argv[]);
int read_conf(const char file[256]);
void printConf();
//***********************************************************
public:
short server_id; //服务器ID
short level;//服务器等级
//监听Server
char listen_address[64];
short port; // 服务器端口;
int server_priority; // 优先权
char alloc_ip[64];
short alloc_port;
short numplayer;
char mysql_ip[64];
short mysql_port;
//日志上报
char log_server_ip[64];
int log_server_port;
int isLogReport;
int m_loglevel;
std::string m_logRemoteIp;
UINT16 m_logRemotePort;
char round_ip[64];
short round_port;
//控制进入桌子
short contrllevel;
//第一轮最大倍数
short maxmulone;
//第二轮最大倍数
short maxmultwo;
//上报IP
char report_ip[64];
//日志
char logfile[64];
char loglevel[12];
int monitor_time;//监控时间
int keeplive_time;//存活时间
int max_table;
int max_user;
//下注的超时时间
int betcointime;
//大于两个人准备其中有人没有准备,然后倒计时把没准备的人踢出,并且游戏开始
int tablestarttime;
//超时踢出没准备用户
short kicktime;
short loserate;
time_t starttime; //服务器启动时间
time_t lasttime; //最近活动时间
//下低注就超时几次之后就把他踢出
short timeoutCount;
short fraction;
//屏蔽词服务器
char word_server_ip[64];
short word_server_port;
//udp服务器ip和端口
char udp_ip[64];
short udp_port;
//redis服务器ip和端口 获取任务的配置信息
char redis_ip[64];
short redis_port;
//redis服务器ip和端口 储存用户的任务历史信息
char redis_tip[64];
short redis_tport;
//redis服务器ip和端口 保存用户的新手任务信息
char redis_nip[64];
short redis_nport;
//redis服务器ip和端口 局数任务用到的redis端口
char taskredis_ip[64];
short taskredis_port;
//掉线玩家数据
char offline_redis_ip[64];
short offline_redis_port;
//简单任务的发放局数条件
short esayTaskCount;
short esayRandNum;
short esayTaskRand;
//当天前n局
short curBeforeCount;
//当天前N局游戏获取简单任务的概率
short esayTaskProbability;
//获得乐劵通知的个数条件
short getIngotNoti1;
short getIngotNoti2;
short getIngotNoti3;
short robotTabNum1;
short robotTabNum2;
short robotTabNum3;
int rewardcoin;
int rewardroll;
short rewardRate;
//赢取金币小喇叭发送
int wincoin1;
int wincoin2;
int wincoin3;
int wincoin4;
checkHost CheckInGame[10];
//redis服务器ip和端口 运维数据用到的redis端口
char operation_redis_ip[64];
short operation_redis_port;
private:
Configure();
};
#endif
|
//
// Motor.h
// SAD
//
// Created by Marquez, Richard A on 4/9/15.
// Copyright (c) 2015 Richard Marquez. All rights reserved.
//
#pragma once
#include <Arduino.h>
class Motor {
private:
int enablePin;
int controlPin1;
int controlPin2;
public:
Motor(int enablePin = -1, int controlPin1 = -1, int controlPin2 = -1);
void stop();
void setSpeed(int speed);
void accelerate();
void reverse();
};
|
/*
* LSST Data Management System
* Copyright 2014-2015 AURA/LSST.
*
* This product includes software developed by the
* LSST Project (http://www.lsst.org/).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the LSST License Statement and
* the GNU General Public License along with this program. If not,
* see <https://www.lsstcorp.org/LegalNotices/>.
*/
/// \file
/// \brief This file contains the Circle class implementation.
#include "Circle.h"
#include <ostream>
#include "Box.h"
#include "ConvexPolygon.h"
#include "Ellipse.h"
namespace lsst {
namespace sg {
double Circle::squaredChordLengthFor(Angle a) {
if (a.asRadians() < 0.0) {
return -1.0;
}
if (a.asRadians() >= PI) {
return 4.0;
}
double s = sin(0.5 * a);
return 4.0 * s * s;
}
Angle Circle::openingAngleFor(double squaredChordLength) {
// Note: the maximum error in the opening angle (and circle bounding box
// width) computations is ~ 2 * MAX_ASIN_ERROR.
if (squaredChordLength < 0.0) {
return Angle(-1.0);
}
if (squaredChordLength >= 4.0) {
return Angle(PI);
}
return Angle(2.0 * std::asin(0.5 * std::sqrt(squaredChordLength)));
}
bool Circle::contains(Circle const & x) const {
if (isFull() || x.isEmpty()) {
return true;
}
if (isEmpty() || x.isFull()) {
return false;
}
NormalizedAngle cc(_center, x._center);
return _openingAngle >
cc + x._openingAngle + 4.0 * Angle(MAX_ASIN_ERROR);
}
bool Circle::isDisjointFrom(Circle const & x) const {
if (isEmpty() || x.isEmpty()) {
return true;
}
if (isFull() || x.isFull()) {
return false;
}
NormalizedAngle cc(_center, x._center);
return cc > _openingAngle + x._openingAngle +
4.0 * Angle(MAX_ASIN_ERROR);
}
Circle & Circle::clipTo(UnitVector3d const & x) {
*this = contains(x) ? Circle(x) : empty();
return *this;
}
Circle & Circle::clipTo(Circle const & x) {
if (isEmpty() || x.isFull()) {
return *this;
}
if (isFull() || x.isEmpty()) {
*this = x;
return *this;
}
Angle a = _openingAngle;
Angle b = x._openingAngle;
NormalizedAngle cc(_center, x._center);
if (cc > a + b + 4.0 * Angle(MAX_ASIN_ERROR)) {
// This circle is disjoint from x.
*this = empty();
return *this;
}
// The circles (nearly) intersect, or one contains the other.
// For now, take the easy route and just use the smaller of
// the two circles as a bound on their intersection.
//
// TODO(smm): Compute the minimal bounding circle.
if (b < a) {
*this = x;
}
return *this;
}
Circle & Circle::expandTo(UnitVector3d const & x) {
// For any circle c and unit vector x, c.expandTo(x).contains(x)
// should return true.
if (isEmpty()) {
*this = Circle(x);
} else if (!contains(x)) {
// Compute the normal vector for the plane defined by _center and x.
UnitVector3d n = UnitVector3d::orthogonalTo(_center, x);
// The minimal bounding circle (MBC) includes unit vectors on the plane
// with normal n that span from _center.rotatedAround(n, -_openingAngle)
// to x. The MBC center is the midpoint of this interval.
NormalizedAngle cx(_center, x);
Angle o = 0.5 * (cx + _openingAngle);
Angle r = 0.5 * (cx - _openingAngle);
// Rotate _center by angle r around n to obtain the MBC center. This is
// done using Rodriques' formula, simplified by taking advantage of the
// orthogonality of _center and n.
_center = UnitVector3d(_center * cos(r) + n.cross(_center) * sin(r));
_squaredChordLength = squaredChordLengthFor(o + Angle(MAX_ASIN_ERROR));
_openingAngle = o + Angle(MAX_ASIN_ERROR);
}
return *this;
}
Circle & Circle::expandTo(Circle const & x) {
if (isEmpty() || x.isFull()) {
*this = x;
return *this;
}
if (x.isEmpty() || isFull()) {
return *this;
}
NormalizedAngle cc(_center, x._center);
if (cc + x._openingAngle + 4.0 * Angle(MAX_ASIN_ERROR) <= _openingAngle) {
// This circle contains x.
return *this;
}
if (cc + _openingAngle + 4.0 * Angle(MAX_ASIN_ERROR) <= x._openingAngle) {
// x contains this circle.
*this = x;
return *this;
}
// The circles intersect or are disjoint.
Angle o = 0.5 * (cc + _openingAngle + x._openingAngle);
if (o + 2.0 * Angle(MAX_ASIN_ERROR) >= Angle(PI)) {
*this = full();
return *this;
}
// Compute the normal vector for the plane defined by the circle centers.
UnitVector3d n = UnitVector3d::orthogonalTo(_center, x._center);
// The minimal bounding circle (MBC) includes unit vectors on the plane
// with normal n that span from _center.rotatedAround(n, -_openingAngle)
// to x._center.rotatedAround(n, x._openingAngle). The MBC center is the
// midpoint of this interval.
Angle r = o - _openingAngle;
// Rotate _center by angle r around n to obtain the MBC center. This is
// done using Rodriques' formula, simplified by taking advantage of the
// orthogonality of _center and n.
_center = UnitVector3d(_center * cos(r) + n.cross(_center) * sin(r));
_squaredChordLength = squaredChordLengthFor(o + Angle(MAX_ASIN_ERROR));
_openingAngle = o + Angle(MAX_ASIN_ERROR);
return *this;
}
Circle & Circle::dilateBy(Angle r) {
if (!isEmpty() && !isFull() &&
(r.asRadians() > 0.0 || r.asRadians() < 0.0)) {
Angle o = _openingAngle + r;
_squaredChordLength = squaredChordLengthFor(o);
_openingAngle = o;
}
return *this;
}
Circle & Circle::complement() {
if (isEmpty()) {
// The complement of an empty circle is a full circle.
_squaredChordLength = 4.0;
_openingAngle = Angle(PI);
} else if (isFull()) {
// The complement of a full circle is an empty circle.
_squaredChordLength = -1.0;
_openingAngle = Angle(-1.0);
} else {
_center = -_center;
_squaredChordLength = 4.0 - _squaredChordLength;
_openingAngle = Angle(PI) - _openingAngle;
}
return *this;
}
Box Circle::getBoundingBox() const {
LonLat c(_center);
Angle h = _openingAngle + 2.0 * Angle(MAX_ASIN_ERROR);
NormalizedAngle w(Box::halfWidthForCircle(h, c.getLat()) +
Angle(MAX_ASIN_ERROR));
return Box(c, w, h);
}
int Circle::relate(UnitVector3d const & v) const {
if (contains(v)) {
return CONTAINS | INTERSECTS;
} else if (isEmpty()) {
return DISJOINT | WITHIN;
}
return DISJOINT;
}
int Circle::relate(Box const & b) const {
// Box-Circle relations are implemented by Box.
return invertSpatialRelations(b.relate(*this));
}
int Circle::relate(Circle const & c) const {
if (isEmpty()) {
if (c.isEmpty()) {
return CONTAINS | DISJOINT | WITHIN;
}
return DISJOINT | WITHIN;
} else if (c.isEmpty()) {
return CONTAINS | DISJOINT;
}
// Neither circle is empty.
if (isFull()) {
if (c.isFull()) {
return CONTAINS | INTERSECTS | WITHIN;
}
return CONTAINS | INTERSECTS;
} else if (c.isFull()) {
return INTERSECTS | WITHIN;
}
// Neither circle is full.
NormalizedAngle cc(_center, c._center);
if (cc > _openingAngle + c._openingAngle + 4.0 * Angle(MAX_ASIN_ERROR)) {
return DISJOINT;
}
int rel = INTERSECTS;
if (cc + c._openingAngle + 4.0 * Angle(MAX_ASIN_ERROR) <= _openingAngle) {
rel |= CONTAINS;
} else if (cc + _openingAngle + 4.0 * Angle(MAX_ASIN_ERROR) <=
c._openingAngle) {
rel |= WITHIN;
}
return rel;
}
int Circle::relate(ConvexPolygon const & p) const {
// ConvexPolygon-Circle relations are implemented by ConvexPolygon.
return invertSpatialRelations(p.relate(*this));
}
int Circle::relate(Ellipse const & e) const {
// Ellipse-Circle relations are implemented by Ellipse.
return invertSpatialRelations(e.relate(*this));
}
std::ostream & operator<<(std::ostream & os, Circle const & c) {
return os << "Circle(" << c.getCenter() << ", "
<< c.getSquaredChordLength() << ')';
}
}} // namespace lsst::sg
|
#include "StdAfx.h"
#include "HappyDay.h"
CHappyDay::CHappyDay(void)
{
}
CHappyDay::~CHappyDay(void)
{
}
int CHappyDay::Hello(void)
{
printf("happy day123\n");
return 0;
}
|
//
// Created by tudom on 2019-12-21.
//
#pragma once
#include <boost/preprocessor/stringize.hpp>
#define LIBNM_INCLUDE_HEADER(header) \
BOOST_PP_STRINGIZE(../include/libnm/header)
#define LIBNM_INCLUDE_HEADER_N(header) \
BOOST_PP_STRINGIZE(../../include/libnm/header)
|
#include <iostream>
#include <algorithm>
#include <numeric>
#include <string>
#include <vector>
using namespace std;
using ll = long long;
int main() {
int N, K;
cin >> N >> K;
int a[N];
for (int i = 0; i < N; ++i) cin >> a[i];
string S;
cin >> S;
S.push_back('$');
vector<ll> damage;
ll ans = 0;
for (int i = 0; i < N; ++i) {
damage.push_back(a[i]);
if (S[i] != S[i + 1]) {
sort(damage.rbegin(), damage.rend());
ans += accumulate(damage.begin(), damage.begin() + min((int)damage.size(), K), 0LL);
damage.clear();
}
}
cout << ans << endl;
return 0;
}
|
#define _ALLOW_MSC_VER_MISMATCH
#include "LimitedCounter.h"
#include "RoundupCounter.h"
using namespace std;
void UseCounter(Counter *counter, int increment) {
for (int i = 0; i < increment; i++) {
counter->operator++();
//++(*counter);
}
}
int main() {
LimitedCounter counterA(0, 5);
RoundupCounter counterB(0, 5);
UseCounter(&counterA, 8); UseCounter(&counterB, 8);
cout << "Counter A: " << counterA << endl; // output should be 5
cout << "Counter B: " << counterB << endl; // output should be 2
CounterUser *c = new CounterUser();
c->IncrementBy(12);
delete c;
return 0;
}
|
#ifndef YL_BAAR_CONSUMERMGR
#define YL_BAAR_CONSUMERMGR
#include <ndn-cxx/face.hpp>
#include <thread>
#include <mutex>
#include <string>
#include <vector>
#include <map>
#include "consumer.h"
using namespace ndn;
class ConsumerMgr
{
public:
ConsumerMgr();
~ConsumerMgr();
private:
static ConsumerMgr* pConsumerMgr;
public:
static ConsumerMgr* Instance();
public:
int MakeCSMHanderPool();
//Jerry: 20180305 mod this function ,market was got by ed-algorithm
Consumer * getConsumer(string& market);
void ReleaseCsm(Consumer * pCsm);
// int MakeCSMPool();
// Consumer * GetCsm(std::string market);
// void putCsm(Consumer * pCsm);
private:
enum CSM_STATUS{STATUS_IDLE = 1, STATUS_BUY = 2};
typedef struct
{
CSM_STATUS nCsmStatus;
Consumer * pCsm;
} CSMHANDLER;
std::vector<CSMHANDLER *> m_vCsm;
std::map<Consumer *, int> m_CsmPtr2Index;
std::mutex m_mutex;
std::map<string, int> market2inuse;
// std::vector<Consumer *> m_vecCsm;
// std::mutex m_vecCmMtx;
};
#endif /* #ifndef YL_BAAR_CONSUMERMGR */
|
#pragma once
#include "../../Toolbox/Toolbox.h"
#include "../Vector/Vector3.h"
namespace ae
{
/// \ingroup math
/// <summary>
/// 3D sphere represented by a center and a radius.
/// </summary>
class AERO_CORE_EXPORT Sphere
{
public:
/// <summary>Build a sphere with a center and a radius.</summary>
/// <param name="_Center">The center of the sphere.</param>
/// <param name="_Radius">The radius of the sphere.</param>
Sphere( const Vector3& _Center = Vector3::Zero, float _Radius = 1.0f );
/// <summary>Set the center of the sphere.</summary>
/// <param name="_Center">The new center of the sphere.</param>
void SetCenter( const Vector3& _Center );
/// <summary>Retrieve the center of the sphere.</summary>
/// <returns>The center of the sphere.</returns>
const Vector3& GetCenter() const;
/// <summary>Set the radius of the sphere.</summary>
/// <param name="_Radius">The new radius of the sphere.</param>
void SetRadius( float _Radius );
/// <summary>Retrieve the radius of the sphere.</summary>
/// <returns>The radius of the sphere.</returns>
float GetRadius() const;
/// <summary>
/// Test if the sphere is intersecting the <paramref name="_Other"/> sphere.<para/>
/// Intersection occurs if the spheres touch each others or if one contains the other one.
/// </summary>
/// <param name="_Other">The other sphere to do the intersection test with.</param>
/// <param name="_WithBoundaries">
/// If True, the surface of the sphere is considered.<para/>
/// That means, if the <paramref name="_Other"/> touch the calling sphere just on
/// the surface without going in the function will return True. <para/>
/// If this parameter is set to False, then the function will return False
/// if the intersection is on an the surface.
/// </param>
/// <param name="_UseSquaredLength">
/// If True the squared length will be used to process the distance between the spheres.<para/>
/// It will be faster but could lead to lack of precision.<para/>
/// Otherwise, the euclidean length will be used.
/// </param>
/// <returns>True if the sphere are intersecting each other, false otherwise.</returns>
Bool Intersects( const Sphere& _Other, Bool _WithBoundaries = True, Bool _UseSquaredLength = True ) const;
/// <summary>
/// Test if the sphere contains the <paramref name="_Other"/> sphere. <para/>
/// This occurs when the other sphere is completly inside the calling one.
/// </summary>
/// <param name="_Other">The other sphere to test if it is inside the calling one.</param>
/// <param name="_WithBoundaries">
/// If True, the surface of the sphere is considered.<para/>
/// That means, if the <paramref name="_Other"/> will be considered contained
/// even if it touches the surface of the calling one. <para/>
/// If this parameter is set to False, then the function will return False
/// if the <paramref name="_Other"/> touches the surface of the calling one.
/// </param>
/// <param name="_UseSquaredLength">
/// If True the squared length will be used to process the distance between the spheres.<para/>
/// It will be faster but could lead to lack of precision.<para/>
/// Otherwise, the euclidean length will be used.
/// </param>
/// <returns>True if the <paramref name="_Other"/> sphere is inside the calling one, false otherwise.</returns>
Bool Contains( const Sphere& _Other, Bool _WithBoundaries = True, Bool _UseSquaredLength = True ) const;
/// <summary>
/// Test if the sphere contains the <paramref name="_Point"/>. <para/>
/// This occurs when the point is inside the sphere.
/// </summary>
/// <param name="_Point">The to test if it is inside the sphere.</param>
/// <param name="_WithBoundaries">
/// If True, the surface of the sphere is considered.<para/>
/// That means, if the <paramref name="_Point"/> will be considered contained
/// even if it touches the surface of the sphere. <para/>
/// If this parameter is set to False, then the function will return False
/// if the <paramref name="_Point"/> touches the surface of the sphere.
/// </param>
/// <param name="_UseSquaredLength">
/// If True the squared length will be used to process the distance between the sphere and the point.<para/>
/// It will be faster but could lead to lack of precision.<para/>
/// Otherwise, the euclidean length will be used.
/// </param>
/// <returns>True if the <paramref name="_Point"/> is inside the calling one, false otherwise.</returns>
Bool Contains( const Vector3& _Point, Bool _WithBoundaries = True, Bool _UseSquaredLength = True ) const;
private:
/// <summary>The center of the sphere.</summary>
Vector3 m_Center;
/// <summary>The radius of the sphere.</summary>
float m_Radius;
};
} // ae
|
#ifndef CLIENTAFFICH_H
#define CLIENTAFFICH_H
#include <QDialog>
namespace Ui {
class clientaffich;
}
class clientaffich : public QDialog
{
Q_OBJECT
public:
explicit clientaffich(QWidget *parent = 0);
~clientaffich();
private slots:
void on_personneview_activated(const QModelIndex &index);
private:
Ui::clientaffich *ui;
};
#endif // CLIENTAFFICH_H
|
#pragma once
#include "GlobalHeader.h"
#include "Nutrient.h" // fa::NutrientType
#include <mylibs/container.hpp> // pl::HashMap
#include <utility> // std::pair
#include <initializer_list> // std::initializer_list
#include <iterator> // std::inserter
namespace fa {
//! a table of nutrients
class NutrientTableImpl final {
public:
using this_type = NutrientTableImpl;
using key_type = NutrientType;
using value_type = Nutrient;
using const_pointer = value_type const *;
using NutrientAmount = Amount;
using container_type = pl::HashMap<const_pointer, NutrientAmount>;
using pair = container_type::value_type;
// contains all the nutrients; to be used as a static member of NutrientTableImpl
class NutrientPool final {
public:
using this_type = NutrientPool;
using container_type = pl::HashMap<key_type, value_type>;
NutrientPool(std::initializer_list<value_type>) noexcept;
const_pointer getNutrient(key_type nutrientType) const;
friend OStream &operator<<(OStream &os, this_type const &obj);
private:
container_type container_;
}; // END of class NutrientPool
NutrientTableImpl() noexcept;
/* construct from a list of NutrientType enumerators and the respective amount of that nutrient,
Do not put more than one of each NutrientType in here! */
NutrientTableImpl(std::initializer_list<std::pair<key_type, NutrientAmount>>);
this_type &operator=(this_type const &) = delete;
this_type &operator=(this_type &&) = delete;
NutrientTableImpl(this_type const &) = default;
NutrientTableImpl(this_type &&) = default;
//! adds two NutrientTableImpls; returns the new NutrientTableImpl
friend this_type operator+(this_type const &, this_type const &);
friend this_type operator-(this_type const &, this_type const &);
//! multiplies the amounts of a NutrientTableImpl and returns the resulting NutrientTableImpl
friend this_type operator*(this_type const &, Amount::value_type);
friend this_type operator/(this_type const &, Amount::value_type);
//! creates a new NutrientTableImpl consisting just of the Macro nutrients
this_type getMacroNutrients() const; // creates an empty container_type, copy_ifs the
this_type getMicroNutrients() const; // macro/micro stuff creates a new this_type by
// move constructing it from that container_type just
// created using that private constructor down below
//! returns a pair of a pointer to the nutrient requested and the corresponding amount of this table
pair getNutrient(key_type nutrientType) const;
//! does some unknown thing in mysterious ways
pl::HashSet<key_type, const_pointer> getPercentages() const; // TODO: Implement this; I have no idea how to. I reckon the return type is incorrect too.
//! prints a NutrientTableImpl to an OStream
friend OStream &operator<<(OStream &os, this_type const &obj);
friend bool operator==(this_type const &lhs, this_type const &rhs) noexcept;
friend bool operator!=(this_type const &lhs, this_type const &rhs) noexcept;
private:
//! creates a new NutrientTableImpl that only contains the nutrients that satisfy the UnaryPredicate
template <class UnaryPredicate>
this_type createFilteredTable(UnaryPredicate &&filter) const {
container_type newContainer{ };
pl::copy_if(cont_, std::inserter(newContainer, std::begin(newContainer)), [&filter](auto &&pair) {
return filter(*(pair.first));
});
return this_type{ std::move(newContainer) };
}
/*! creates a new NutrientTableImpl that contains all the nutrients of lhs and rhs;
if a nutrient from rhs exists in lhs the
Amount used for that nutrient is
the result of the BinaryOp
applied to the Amount in lhs and rhs for the nutrient in question.*/
template <class BinaryOp>
static this_type insertOrBinaryOpAssign(this_type const &lhs, this_type const &rhs, BinaryOp &&binaryOp) {
auto retVal = lhs;
for (auto &&e : rhs.cont_) {
auto it = retVal.cont_.find(e.first);
if (it == std::end(retVal.cont_)) { // not found
retVal.cont_.insert(e);
} else { // found
it->second = binaryOp(it->second, e.second);
}
}
return retVal;
}
//! creates a new NutrientTableImpl that is a copy of table having had UnaryOp applied to its amounts.
template <class UnaryOp>
static this_type unaryOpTheAmounts(this_type const &table, UnaryOp &&unaryOp) {
auto newContainer = table;
for (auto &&e : newContainer.cont_) {
e.second = unaryOp(e.second);
}
return newContainer;
}
//! the NutrientPool that contains all nutrients.
static NutrientPool const nutrientPool;
explicit NutrientTableImpl(container_type &&); // construct from an rvalue HashMap
container_type cont_;
}; // END of class NutrientTableImpl
} // END of namespace fa
|
#include<bits/stdc++.h>
using namespace std;
main()
{
char main[500], op[500], s1[500];
while(cin>>main)
{
int i, len, count=1, a, b;
len = strlen(main);
for(a=0; a<len; a++)
{
s1[a] = main[a];
}
s1[a] = '\0';
while(count>=1)
{
for(i=0; i<len; i++)
{
if(i==0)
op[i] = s1[len-1];
else
op[i] = s1[i-1];
}
op[i]='\0';
if(strcmp(op,main)==0)
break;
else
{
count++;
for(b=0; b<len; b++)
s1[b] = op[b];
}
s1[b] = '\0';
}
cout<<count<<endl;
}
return 0;
}
|
/*
* 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.
*/
#pragma once
#include <quic/QuicConstants.h>
#include <quic/codec/ConnectionIdAlgo.h>
#include <quic/codec/QuicReadCodec.h>
#include <quic/codec/QuicWriteCodec.h>
#include <quic/codec/Types.h>
#include <quic/common/BufAccessor.h>
#include <quic/congestion_control/CongestionController.h>
#include <quic/congestion_control/PacketProcessor.h>
#include <quic/congestion_control/ThrottlingSignalProvider.h>
#include <quic/handshake/HandshakeLayer.h>
#include <quic/logging/QLogger.h>
#include <quic/observer/SocketObserverTypes.h>
#include <quic/state/AckEvent.h>
#include <quic/state/AckStates.h>
#include <quic/state/LossState.h>
#include <quic/state/OutstandingPacket.h>
#include <quic/state/PacketEvent.h>
#include <quic/state/PendingPathRateLimiter.h>
#include <quic/state/QuicConnectionStats.h>
#include <quic/state/QuicStreamGroupRetransmissionPolicy.h>
#include <quic/state/QuicStreamManager.h>
#include <quic/state/QuicTransportStatsCallback.h>
#include <quic/state/StreamData.h>
#include <quic/state/TransportSettings.h>
#include <folly/Optional.h>
#include <folly/io/IOBuf.h>
#include <folly/io/async/DelayedDestruction.h>
#include <quic/common/QuicAsyncUDPSocketWrapper.h>
#include <chrono>
#include <list>
#include <numeric>
#include <queue>
namespace quic {
struct NetworkData {
TimePoint receiveTimePoint;
std::vector<Buf> packets;
size_t totalData{0};
NetworkData() = default;
NetworkData(Buf&& buf, const TimePoint& receiveTime)
: receiveTimePoint(receiveTime) {
if (buf) {
totalData = buf->computeChainDataLength();
packets.emplace_back(std::move(buf));
}
}
NetworkData(std::vector<Buf>&& packetBufs, const TimePoint& receiveTime)
: receiveTimePoint(receiveTime),
packets(std::move(packetBufs)),
totalData(0) {
for (const auto& buf : packets) {
totalData += buf->computeChainDataLength();
}
}
std::unique_ptr<folly::IOBuf> moveAllData() && {
std::unique_ptr<folly::IOBuf> buf;
for (size_t i = 0; i < packets.size(); ++i) {
if (buf) {
buf->prependChain(std::move(packets[i]));
} else {
buf = std::move(packets[i]);
}
}
return buf;
}
};
struct NetworkDataSingle {
Buf data;
TimePoint receiveTimePoint;
size_t totalData{0};
NetworkDataSingle() = default;
NetworkDataSingle(
std::unique_ptr<folly::IOBuf> buf,
const TimePoint& receiveTime)
: data(std::move(buf)), receiveTimePoint(receiveTime) {
if (data) {
totalData += data->computeChainDataLength();
}
}
};
struct OutstandingsInfo {
// Sent packets which have not been acked. These are sorted by PacketNum.
std::deque<OutstandingPacketWrapper> packets;
// All PacketEvents of this connection. If a OutstandingPacketWrapper doesn't
// have an associatedEvent or if it's not in this set, there is no need to
// process its frames upon ack or loss.
folly::F14FastSet<PacketEvent, PacketEventHash> packetEvents;
// Number of outstanding packets not including cloned
EnumArray<PacketNumberSpace, uint64_t> packetCount{};
// Number of packets are clones or cloned.
EnumArray<PacketNumberSpace, uint64_t> clonedPacketCount{};
// Number of packets currently declared lost.
uint64_t declaredLostCount{0};
// Number of outstanding inflight DSR packet. That is, when a DSR packet is
// declared lost, this counter will be decreased.
uint64_t dsrCount{0};
// Number of packets outstanding and not declared lost.
uint64_t numOutstanding() {
CHECK_GE(packets.size(), declaredLostCount);
return packets.size() - declaredLostCount;
}
// Total number of cloned packets.
uint64_t numClonedPackets() {
return clonedPacketCount[PacketNumberSpace::Initial] +
clonedPacketCount[PacketNumberSpace::Handshake] +
clonedPacketCount[PacketNumberSpace::AppData];
}
void reset() {
packets.clear();
packetEvents.clear();
packetCount = {};
clonedPacketCount = {};
declaredLostCount = 0;
dsrCount = 0;
}
};
class AppLimitedTracker {
public:
using Clock = std::chrono::steady_clock;
/**
* Mark the connection as application limited.
*/
void setAppLimited() {
DCHECK(!isAppLimited_);
isAppLimited_ = true;
appLimitedStartTime_ = Clock::now();
}
/**
* Mark the connection as not being application limited.
*/
void setNotAppLimited() {
DCHECK(isAppLimited_);
isAppLimited_ = false;
totalAppLimitedTime_ +=
std::chrono::duration_cast<std::chrono::microseconds>(
Clock::now() - appLimitedStartTime_);
}
/**
* Returns whether the connection has been marked as application limited.
*/
bool isAppLimited() {
return isAppLimited_;
}
/**
* Returns total time connection has spent application limited.
*
* If connection is currently application limited, the time in the current
* application limited period is included.
*/
std::chrono::microseconds getTotalAppLimitedTime() {
if (isAppLimited_) {
return std::chrono::duration_cast<std::chrono::microseconds>(
Clock::now() - appLimitedStartTime_) +
totalAppLimitedTime_;
}
return totalAppLimitedTime_;
}
private:
// Total time spent application limited, excluding now.
std::chrono::microseconds totalAppLimitedTime_{0us};
// Whether we're currently application limited.
// Initialize to true since all connections start off application limited.
bool isAppLimited_{true};
// When we last became application limited.
// Initialize to now() since all connections start off application limited.
Clock::time_point appLimitedStartTime_{Clock::now()};
};
struct Pacer {
virtual ~Pacer() = default;
/**
* API for CongestionController to notify Pacer the latest cwnd value in bytes
* and connection RTT so that Pacer can recalculate pacing rates.
* Note the third parameter is here for testing purposes.
*/
virtual void refreshPacingRate(
uint64_t cwndBytes,
std::chrono::microseconds rtt,
TimePoint currentTime = Clock::now()) = 0;
/**
* Set the pacers rate to the given value in Bytes per second
*/
virtual void setPacingRate(uint64_t rateBps) = 0;
/**
* Set an upper limit on the rate this pacer can use.
* - If the pacer is currently using a faster pace, it will be brought down to
* maxRateBytesPerSec.
* - If refreshPacingRate or setPacingRate are called with a value
* greater than maxRateBytesPerSec, maxRateBytesPerSec will be used instead.
*/
virtual void setMaxPacingRate(uint64_t maxRateBytesPerSec) = 0;
/**
* Resets the pacer, which should have the effect of the next write
* happening immediately.
*/
virtual void reset() = 0;
/**
* Set the factor by which to multiply the RTT before determining the
* inter-burst interval. E.g. a numerator of 1 and a denominator of 2
* would effectively double the pacing rate.
*/
virtual void setRttFactor(uint8_t numerator, uint8_t denominator) = 0;
/**
* API for Trnasport to query the interval before next write
*/
[[nodiscard]] virtual std::chrono::microseconds getTimeUntilNextWrite(
TimePoint currentTime = Clock::now()) const = 0;
/**
* API for Transport to query a recalculated batch size based on currentTime
* and previously scheduled write time. The batch size is how many packets the
* transport can write out per eventbase loop.
*
* currentTime: The caller is expected to pass in a TimePoint value so that
* the Pacer can compensate the timer drift.
*/
virtual uint64_t updateAndGetWriteBatchSize(TimePoint currentTime) = 0;
/**
* Getter API of the most recent write batch size.
*/
virtual uint64_t getCachedWriteBatchSize() const = 0;
virtual void onPacketSent() = 0;
virtual void onPacketsLoss() = 0;
virtual void setExperimental(bool experimental) = 0;
};
struct PacingRate {
std::chrono::microseconds interval{0us};
uint64_t burstSize{0};
struct Builder {
Builder&& setInterval(std::chrono::microseconds interval) &&;
Builder&& setBurstSize(uint64_t burstSize) &&;
PacingRate build() &&;
private:
std::chrono::microseconds interval_{0us};
uint64_t burstSize_{0};
};
private:
PacingRate(std::chrono::microseconds interval, uint64_t burstSize);
};
struct QuicCryptoStream : public QuicStreamLike {
~QuicCryptoStream() override = default;
};
struct QuicCryptoState {
// Stream to exchange the initial cryptographic material.
QuicCryptoStream initialStream;
// Stream to exchange the one rtt key material.
QuicCryptoStream handshakeStream;
// Stream to exchange handshake data encrypted with 1-rtt keys.
QuicCryptoStream oneRttStream;
};
struct ConnectionCloseEvent {
TransportErrorCode errorCode;
std::string reasonPhrase;
PacketNum packetSequenceNum;
};
struct RstStreamEvent {
RstStreamEvent(StreamId id, uint64_t offset, ApplicationErrorCode error)
: stream(id), byteOffset(offset), errorCode(error) {}
StreamId stream;
uint64_t byteOffset;
ApplicationErrorCode errorCode;
};
using Resets = folly::F14FastMap<StreamId, RstStreamFrame>;
using FrameList = std::vector<QuicSimpleFrame>;
class CongestionControllerFactory;
class LoopDetectorCallback;
class PendingPathRateLimiter;
struct ReadDatagram {
ReadDatagram(TimePoint recvTimePoint, BufQueue data)
: receiveTimePoint_{recvTimePoint}, buf_{std::move(data)} {}
[[nodiscard]] TimePoint receiveTimePoint() const noexcept {
return receiveTimePoint_;
}
[[nodiscard]] BufQueue& bufQueue() noexcept {
return buf_;
}
[[nodiscard]] const BufQueue& bufQueue() const noexcept {
return buf_;
}
// Move only to match BufQueue behavior
ReadDatagram(ReadDatagram&& other) noexcept = default;
ReadDatagram& operator=(ReadDatagram&& other) = default;
ReadDatagram(const ReadDatagram&) = delete;
ReadDatagram& operator=(const ReadDatagram&) = delete;
private:
TimePoint receiveTimePoint_;
BufQueue buf_;
};
struct QuicConnectionStateBase : public folly::DelayedDestruction {
virtual ~QuicConnectionStateBase() override = default;
explicit QuicConnectionStateBase(QuicNodeType type) : nodeType(type) {}
// Accessor to output buffer for continuous memory GSO writes
BufAccessor* bufAccessor{nullptr};
std::unique_ptr<Handshake> handshakeLayer;
// Crypto stream
std::unique_ptr<QuicCryptoState> cryptoState;
// Connection Congestion controller
std::unique_ptr<CongestionController> congestionController;
std::vector<std::shared_ptr<PacketProcessor>> packetProcessors;
std::shared_ptr<ThrottlingSignalProvider> throttlingSignalProvider;
// Pacer
std::unique_ptr<Pacer> pacer;
// Congestion Controller factory to create specific impl of cc algorithm
std::shared_ptr<CongestionControllerFactory> congestionControllerFactory;
std::unique_ptr<QuicStreamManager> streamManager;
// When server receives early data attempt without valid source address token,
// server will limit bytes in flight to avoid amplification attack.
// This limit should be cleared and set back to max after CFIN is received.
folly::Optional<uint64_t> writableBytesLimit;
std::unique_ptr<PendingPathRateLimiter> pathValidationLimiter;
// Outstanding packets, packet events, and associated counters wrapped in one
// class
OutstandingsInfo outstandings;
// The read codec to decrypt and decode packets.
std::unique_ptr<QuicReadCodec> readCodec;
// Initial header cipher.
std::unique_ptr<PacketNumberCipher> initialHeaderCipher;
// Handshake header cipher.
std::unique_ptr<PacketNumberCipher> handshakeWriteHeaderCipher;
// One rtt write header cipher.
std::unique_ptr<PacketNumberCipher> oneRttWriteHeaderCipher;
// Write cipher for 1-RTT data
std::unique_ptr<Aead> oneRttWriteCipher;
// Write cipher for packets with initial keys.
std::unique_ptr<Aead> initialWriteCipher;
// Write cipher for packets with handshake keys.
std::unique_ptr<Aead> handshakeWriteCipher;
// Time at which the connection started.
// TODO(bschlinker): For clients, this should be set when connect starts.
TimePoint connectionTime;
// The received active_connection_id_limit transport parameter from the peer.
uint64_t peerActiveConnectionIdLimit{0};
// The destination connection id used in client's initial packet.
folly::Optional<ConnectionId> clientChosenDestConnectionId;
// The source connection id used in client's initial packet.
folly::Optional<ConnectionId> clientConnectionId;
// The current server chosen connection id.
folly::Optional<ConnectionId> serverConnectionId;
// Connection ids issued by self.
std::vector<ConnectionIdData> selfConnectionIds;
// Connection ids issued by peer - to be used as destination ids.
std::vector<ConnectionIdData> peerConnectionIds;
// Connection ids to be unbinded soon (server only)
folly::Optional<SmallVec<ConnectionId, 5>> connIdsRetiringSoon;
// ConnectionIdAlgo implementation to encode and decode ConnectionId with
// various info, such as routing related info.
ConnectionIdAlgo* connIdAlgo{nullptr};
// Negotiated version.
folly::Optional<QuicVersion> version;
// Original advertised version. Only meaningful to clients.
// TODO: move to client only conn state.
folly::Optional<QuicVersion> originalVersion;
// Original address used by the peer when first establishing the connection.
folly::SocketAddress originalPeerAddress;
// Current peer address.
folly::SocketAddress peerAddress;
// Local address. INADDR_ANY if not set.
folly::Optional<folly::SocketAddress> localAddress;
// Local error on the connection.
folly::Optional<QuicError> localConnectionError;
// Error sent on the connection by the peer.
folly::Optional<QuicError> peerConnectionError;
// Supported versions in order of preference. Only meaningful to clients.
// TODO: move to client only conn state.
std::vector<QuicVersion> supportedVersions;
// The endpoint attempts to create a new self connection id with sequence
// number and stateless reset token for itself, and if successful, returns it
// and updates the connection's state to ensure its peer can use it.
virtual folly::Optional<ConnectionIdData> createAndAddNewSelfConnId() {
return folly::none;
}
uint64_t nextSelfConnectionIdSequence{0};
struct PendingEvents {
Resets resets;
folly::Optional<PathChallengeFrame> pathChallenge;
FrameList frames;
std::vector<KnobFrame> knobs;
// Number of probing packets to send after PTO
EnumArray<PacketNumberSpace, uint8_t> numProbePackets{};
FOLLY_NODISCARD bool anyProbePackets() const {
return numProbePackets[PacketNumberSpace::Initial] +
numProbePackets[PacketNumberSpace::Handshake] +
numProbePackets[PacketNumberSpace::AppData];
}
// true: schedule timeout if not scheduled
// false: cancel scheduled timeout
bool schedulePathValidationTimeout{false};
// If we should schedule a new Ack timeout, if it's not already scheduled
bool scheduleAckTimeout{false};
// Whether a connection level window update is due to send
bool connWindowUpdate{false};
// If there is a pending loss detection alarm update
bool setLossDetectionAlarm{false};
bool cancelPingTimeout{false};
bool notifyPingReceived{false};
// close transport when the next packet number reaches kMaxPacketNum
bool closeTransport{false};
// To send a ping frame
bool sendPing{false};
// Do we need to send data blocked frame when connection is blocked.
bool sendDataBlocked{false};
// Send an immediate ack frame (requesting an ack)
bool requestImmediateAck{false};
};
PendingEvents pendingEvents;
LossState lossState;
// This contains the ack and packet number related states for all three
// packet number spaces.
AckStates ackStates;
struct ConnectionFlowControlState {
// The size of the connection flow control window.
uint64_t windowSize{0};
// The max data we have advertised to the peer.
uint64_t advertisedMaxOffset{0};
// The max data the peer has advertised on the connection.
// This is set to 0 initially so that we can't send any data until we know
// the peer's flow control offset.
uint64_t peerAdvertisedMaxOffset{0};
// The sum of the min(read offsets) of all the streams on the conn.
uint64_t sumCurReadOffset{0};
// The sum of the max(offset) observed on all the streams on the conn.
uint64_t sumMaxObservedOffset{0};
// The sum of write offsets of all the streams, only including the offsets
// written on the wire.
uint64_t sumCurWriteOffset{0};
// The sum of length of data in all the stream buffers.
uint64_t sumCurStreamBufferLen{0};
// The packet number in which we got the last largest max data.
folly::Optional<PacketNum> largestMaxOffsetReceived;
// The following are advertised by the peer, and are set to zero initially
// so that we cannot send any data until we know the peer values.
// The initial max stream offset for peer-initiated bidirectional streams.
uint64_t peerAdvertisedInitialMaxStreamOffsetBidiLocal{0};
// The initial max stream offset for local-initiated bidirectional streams.
uint64_t peerAdvertisedInitialMaxStreamOffsetBidiRemote{0};
// The initial max stream offset for unidirectional streams.
uint64_t peerAdvertisedInitialMaxStreamOffsetUni{0};
// Time at which the last flow control update was sent by the transport.
folly::Optional<TimePoint> timeOfLastFlowControlUpdate;
};
// Current state of flow control.
ConnectionFlowControlState flowControlState;
// The outstanding path challenge
folly::Optional<PathChallengeFrame> outstandingPathValidation;
// Settings for transports.
TransportSettings transportSettings;
// Value of the negotiated ack delay exponent.
uint64_t peerAckDelayExponent{kDefaultAckDelayExponent};
// The value of the peer's min_ack_delay, for creating ACK_FREQUENCY and
// IMMEDIATE_ACK frames.
folly::Optional<std::chrono::microseconds> peerMinAckDelay;
// Idle timeout advertised by the peer. Initially sets it to the maximum value
// until the handshake sets the timeout.
std::chrono::milliseconds peerIdleTimeout{kMaxIdleTimeout};
// The max UDP packet size we will be sending, limited by both the received
// max_packet_size in Transport Parameters and PMTU
uint64_t udpSendPacketLen{kDefaultUDPSendPacketLen};
// Peer-advertised max UDP payload size, stored as an opportunistic value to
// use when receiving the forciblySetUdpPayloadSize transport knob param
uint64_t peerMaxUdpPayloadSize{kDefaultUDPSendPacketLen};
struct PacketSchedulingState {
StreamId nextScheduledControlStream{0};
};
PacketSchedulingState schedulingState;
// QLogger for this connection
std::shared_ptr<QLogger> qLogger;
// Track stats for various server events
QuicTransportStatsCallback* statsCallback{nullptr};
// Debug information. Currently only used to debug busy loop of Transport
// WriteLooper.
struct WriteDebugState {
bool needsWriteLoopDetect{false};
uint64_t currentEmptyLoopCount{0};
WriteDataReason writeDataReason{WriteDataReason::NO_WRITE};
NoWriteReason noWriteReason{NoWriteReason::WRITE_OK};
std::string schedulerName;
};
struct ReadDebugState {
uint64_t loopCount{0};
NoReadReason noReadReason{NoReadReason::READ_OK};
};
WriteDebugState writeDebugState;
ReadDebugState readDebugState;
std::shared_ptr<LoopDetectorCallback> loopDetectorCallback;
// Measure rtt between pathchallenge & path response frame
// Use this measured rtt as init rtt (from Transport Settings)
TimePoint pathChallengeStartTime;
/**
* Eerie data app params functions.
*/
folly::Function<bool(const folly::Optional<std::string>&, const Buf&) const>
earlyDataAppParamsValidator;
folly::Function<Buf()> earlyDataAppParamsGetter;
/**
* Selects a previously unused peer-issued connection id to use.
* If there are no available ids return false and don't change anything.
* Return true if replacement succeeds.
*/
bool retireAndSwitchPeerConnectionIds();
// SocketObserverContainer
//
// Stored as a weak_ptr to ensure that delayed destruction of
// QuicConnectionStateBase does not prevent the SocketObserverContainer
// from being destroyed.
std::weak_ptr<SocketObserverContainer> observerContainer;
/**
* Returns the SocketObserverContainer or nullptr if not available.
*/
SocketObserverContainer* getSocketObserverContainer() const {
if (const auto observerContainerLocked = observerContainer.lock()) {
return observerContainerLocked.get();
}
return nullptr;
}
// Recent ACK events, for use in processCallbacksAfterNetworkData.
// Holds the ACK events generated during the last round of ACK processing.
std::vector<AckEvent> lastProcessedAckEvents;
// Type of node owning this connection (client or server).
QuicNodeType nodeType;
// Whether or not we received a new packet before a write.
bool receivedNewPacketBeforeWrite{false};
// Whether we've set the transporot parameters from transportSettings yet.
bool transportParametersEncoded{false};
// Whether a connection can be paced based on its handshake and close states.
// For example, we may not want to pace a connection that's still handshaking.
bool canBePaced{false};
// Tracking of application limited time.
AppLimitedTracker appLimitedTracker;
// Monotonically increasing counter that is incremented each time there is a
// write on this socket (writeSocketData() is called), This is used to
// identify specific outstanding packets (based on writeCount and packetNum)
// in the Observers, to construct Write Blocks
uint64_t writeCount{0};
// Number of DSR packets sent by this connection.
uint64_t dsrPacketCount{0};
// Whether we successfully used 0-RTT keys in this connection.
bool usedZeroRtt{false};
// Number of probe packets that were writableBytesLimited
uint64_t numProbesWritableBytesLimited{0};
struct DatagramState {
uint32_t maxReadFrameSize{kDefaultMaxDatagramFrameSize};
uint32_t maxWriteFrameSize{kDefaultMaxDatagramFrameSize};
uint32_t maxReadBufferSize{kDefaultMaxDatagramsBuffered};
uint32_t maxWriteBufferSize{kDefaultMaxDatagramsBuffered};
// Buffers Incoming Datagrams
std::deque<ReadDatagram> readBuffer;
// Buffers Outgoing Datagrams
std::deque<BufQueue> writeBuffer;
};
DatagramState datagramState;
// Peer max stream groups advertised.
folly::Optional<uint64_t> peerAdvertisedMaxStreamGroups;
// Sequence number to use for the next ACK_FREQUENCY frame
uint64_t nextAckFrequencyFrameSequenceNumber{0};
// GSO supported on conn.
folly::Optional<bool> gsoSupported;
folly::Optional<AckReceiveTimestampsConfig>
maybePeerAckReceiveTimestampsConfig;
bool peerAdvertisedKnobFrameSupport{false};
// Retransmission policies map.
folly::F14FastMap<StreamGroupId, QuicStreamGroupRetransmissionPolicy>
retransmissionPolicies;
struct SocketCmsgsState {
folly::Optional<folly::SocketOptionMap> additionalCmsgs;
// The write count which this SocketCmsgs state is intended for.
// This is used to make sure this cmsgs list does not end up used
// for multiple writes.
uint64_t targetWriteCount;
};
SocketCmsgsState socketCmsgsState;
};
std::ostream& operator<<(std::ostream& os, const QuicConnectionStateBase& st);
struct AckStateVersion {
uint64_t initialAckStateVersion{kDefaultIntervalSetVersion};
uint64_t handshakeAckStateVersion{kDefaultIntervalSetVersion};
uint64_t appDataAckStateVersion{kDefaultIntervalSetVersion};
AckStateVersion(
uint64_t initialVersion,
uint64_t handshakeVersion,
uint64_t appDataVersion);
AckStateVersion() = default;
bool operator==(const AckStateVersion& other) const;
bool operator!=(const AckStateVersion& other) const;
};
using LossVisitor = std::function<
void(QuicConnectionStateBase&, RegularQuicWritePacket&, bool)>;
} // namespace quic
|
#pragma once
#include <string>
#include <map>
#include <vector>
#include "Geometry.h"
class Camera;
enum class RectType {
anchor,
attack,
damage
};
struct ActionRect {
RectType rt;//アクションタイプ
Rect rc;//アクション矩形
};
///切り抜き情報
struct CutInfo {
Rect rc;//切り抜き矩形
Position2 center; //中心点
int duration;//表示時間
std::vector<ActionRect> actrects;
};//28バイト+16バイト
typedef std::vector<CutInfo> CutInfoes_t;
struct ActionInfo {
bool isLoop; //ループ情報
CutInfoes_t cuts; //カット情報配列
};
struct ActionData {
std::string imgFilePath;//画像ファイルのパス
std::map<std::string, ActionInfo> actInfo;//アクション情報
};
///キャラクター基底クラス
class CharacterObject
{
protected:
const Camera& _camera;
bool _isTurn;
ActionData _actionData;
std::string _nowName;//「今」のアクション名
int _nowCutIdx;//「今」表示中のカット番号
unsigned int _frame;//そのカット番号における経過フレーム
//アニメーションの変更
void ChangeAction(const char* name);
//アニメーションのフレームを1進める
bool ProceedAnimationFrame();
//アクションデータ読み込み
void readActfile(const char* actionPath);
//キャラの描画
void Draw(int& Img);
void DebugDraw();
public:
Position2f _pos;
///矩形の表示場所
Rect GetActuralRectForAction(const Rect& _rec) const;
const std::vector<ActionRect>& GetActionRects() const;
const Position2f& GetPos() const;
void Copy(const CharacterObject& c);
CharacterObject(const Camera& c);
virtual ~CharacterObject();
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2011-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef MAC_OPENGL_CONTEXT_H__
#define MAC_OPENGL_CONTEXT_H__
class OpenGLContextWrapper
{
public:
static void* GetSharedContext();
static void* InitSharedContext();
static void SetSharedContextAsCurrent();
static void* GetCurrentContext();
static void SetContextAsCurrent(void* ctx);
static void Uninitialize();
};
#endif /* !MAC_OPENGL_CONTEXT_H__ */
|
/*****************************************************************************************************************
* File Name : NaivePatternMatching.h
* File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\tutorials\nptel\DSAndAlgo\lecture17\NaivePatternMatching.h
* Created on : Jan 15, 2014 :: 1:44:56 AM
* Author : AVINASH
* Testing Status : TODO
* URL : TODO
*****************************************************************************************************************/
/************************************************ Namespaces ****************************************************/
using namespace std;
using namespace __gnu_cxx;
/************************************************ User Includes *************************************************/
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <utility>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <hash_map>
#include <stack>
#include <queue>
#include <limits.h>
#include <programming/ds/tree.h>
#include <programming/ds/linkedlist.h>
#include <programming/utils/treeutils.h>
#include <programming/utils/llutils.h>
/************************************************ User defined constants *******************************************/
#define null NULL
/************************************************* Main code ******************************************************/
#ifndef NAIVEPATTERNMATCHING_H_
#define NAIVEPATTERNMATCHING_H_
vector<unsigned int> searchForPattern(char *text,char *pattern){
vector<unsigned int> indexes;
char *textCrawler = text,*patternCrawler = pattern,*innerTextCrawler;
while(textCrawler != NULL){
patternCrawler = pattern;
innerTextCrawler = textCrawler;
while(innerTextCrawler != NULL && patternCrawler != NULL){
innerTextCrawler++;
patternCrawler++;
}
if(innerTextCrawler == patternCrawler){
}
textCrawler++;
}
}
#endif /* NAIVEPATTERNMATCHING_H_ */
/************************************************* End code *******************************************************/
|
#include "debouncer.h"
#define MAX_TEMP 30
#define MIN_TEMP 10
#define DEFAULT_TEMP 23
DebouncedEncoder::DebouncedEncoder(int clockPin, int dataPin) :
encoder(clockPin, dataPin),
reading(DEFAULT_TEMP),
oldPosition(0),
changed(false),
lastChangeTime(millis()) {
}
void DebouncedEncoder::update() {
int32_t newPosition = encoder.read();
if (newPosition != oldPosition) {
char report[256];
sprintf(report, "Check: old: %d, new: %d, now: %ld, prev: %ld", oldPosition, newPosition, millis(), lastChangeTime);
lastChangeTime = millis();
Serial.println(report);
changed = true;
if ((newPosition - oldPosition) > 1 && reading < MAX_TEMP) {
Serial.println("Incremented");
++reading;
} else if ((newPosition - oldPosition) < -1 && reading > MIN_TEMP) {
Serial.println("Decremented");
--reading;
}
} else {
changed = false;
}
oldPosition = newPosition;
}
int DebouncedEncoder::value() {
return reading;
}
bool DebouncedEncoder::hasChanged() {
return changed;
}
long DebouncedEncoder::lastChanged() {
return lastChangeTime;
}
|
#include "Maizefield.h"
#include "repast_hpc/Properties.h"
#include "repast_hpc/SharedContext.h"
#include "repast_hpc/SharedDiscreteSpace.h"
#include "repast_hpc/GridComponents.h"
#include "repast_hpc/Random.h"
#include <string>
#include <vector>
#include <boost/mpi.hpp>
#include <stdio.h>
MaizeField::MaizeField(repast::AgentId MaizeFieldID,float data1,float data2, double q):MaizeFieldID(MaizeFieldID), data1(data1), data2(data2), q(q)
{
// initialise maizefield
getAttributes(data1,data2); // read in constants from properties file
repast::DoubleUniformGenerator gen = repast::Random::instance()->createUniDoubleGenerator(0, sigmaahv); // initialise random number generator
pastsig = gen.next();
}
void MaizeField::getAttributes(float data1,float data2)
{
// reads in the attributes for yield calculations from prop files
Ha = data1;
sigmaahv = data2;
}
void MaizeField::MaizeProduction(int yieldFromFile)
{
repast::DoubleUniformGenerator gen1 = repast::Random::instance()->createUniDoubleGenerator(0, 1); // initialise random number generator
repast::DoubleUniformGenerator gen2 = repast::Random::instance()->createUniDoubleGenerator(0, sigmaahv); // initialise random number generator
double q1 = gen1.next();
y = yieldFromFile;
//std::cout<<"yieldFromFile: "<<yieldFromFile<<std::endl;
//std::cout<<"Ha "<<Ha<<std::endl;
BY = y*q1*Ha; // calculate base yield
if(tick == 1)
{
sig = pastsig;
}
else
{
sig = gen2.next();
}
H0 = BY * (1 + sig); // calculate household harvest
pastsig = sig;
currentYield = H0; //set current yield to household yield.
//std::cout<<"sig From Space = "<<sig<<std::endl;
//std::cout<<"currentYield "<< currentYield<<std::endl;
//std::cout<<"Calculated Current Yield = "<<currentYield<<std::endl;
}
MaizeField::~MaizeField()
{
//delete Maizeprops;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
*
* Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* Espen Sand
*/
#include "core/pch.h"
#include "X11SkinElement.h"
#include "modules/skin/OpSkin.h"
#include "modules/display/vis_dev.h"
#include "modules/pi/OpSystemInfo.h"
#include "modules/pi/ui/OpUiInfo.h"
// Elements and order must match NativeType in header file
static const char* s_native_types[] =
{
"Push Button Skin",
"Push Default Button Skin",
"Toolbar Button Skin",
"Selector Button Skin",
"Menu Skin",
"Menu Button Skin",
"Menu Right Arrow",
"Menu Separator Skin",
"Popup Menu Skin",
"Popup Menu Button Skin",
"Header Button Skin",
"Link Button Skin",
"Tab Button Skin",
"Pagebar Button Skin",
"Caption Minimize Button Skin",
"Caption Close Button Skin",
"Caption Restore Button Skin",
"Checkbox Skin",
"Radio Button Skin",
"Dropdown Skin",
"Dropdown Button Skin",
"Dropdown Left Button Skin",
"Dropdown Edit Skin",
"Edit Skin",
"MultilineEdit Skin",
"Browser Skin",
"Progressbar Skin",
"Start Skin",
"Search Skin",
"Treeview Skin",
"Listbox Skin",
"Checkmark",
"Bullet",
"Window Skin",
"Browser Window Skin",
"Dialog Skin",
"Dialog Page Skin",
"Dialog Tab Page Skin",
"Dialog Button Border Skin",
"Tabs Skin",
"Hotlist Skin",
"Hotlist Selector Skin",
"Hotlist Splitter Skin",
"Hotlist Panel Header Skin",
"Scrollbar Horizontal Skin",
"Scrollbar Horizontal Knob Skin",
"Scrollbar Horizontal Left Skin",
"Scrollbar Horizontal Right Skin",
"Scrollbar Vertical Skin",
"Scrollbar Vertical Knob Skin",
"Scrollbar Vertical Up Skin",
"Scrollbar Vertical Down Skin",
"Slider Horizontal Track",
"Slider Horizontal Knob",
"Slider Vertical Track",
"Slider Vertical Knob",
"Status Skin",
"Mainbar Skin",
"Mainbar Button Skin",
"Personalbar Skin",
"Pagebar Skin",
"Addressbar Skin",
"Navigationbar Skin",
"Viewbar Skin",
"Mailbar Skin",
"Chatbar Skin",
"Cycler Skin",
"Progress Document Skin",
"Progress Images Skin",
"Progress Total Skin",
"Progress Speed Skin",
"Progress Elapsed Skin",
"Progress Status Skin",
"Progress General Skin",
"Progress Clock Skin",
"Progress Empty Skin",
"Progress Full Skin",
"Identify As Skin",
"Dialog Warning",
"Dialog Error",
"Dialog Question",
"Dialog Info",
"Speed Dial Widget Skin",
"Horizontal Separator",
"Vertical Separator",
"Disclosure Triangle Skin",
"Sort Ascending",
"Sort Descending",
"Pagebar Close Button Skin",
"Notifier Close Button Skin",
"Tooltip Skin",
"Notifier Skin",
"Extender Button Skin",
"Listitem Skin",
NULL,
};
#define CHECKMARK_SIZE 11
#define MAX_MENU_IMAGE_SIZE 22
#define SLIDER_HORIZONTAL_KNOB_HEIGHT 19
#define SLIDER_HORIZONTAL_KNOB_WIDTH 9
namespace NativeSkinConstants
{
enum ArrowDirection { ARROW_UP, ARROW_DOWN, ARROW_LEFT, ARROW_RIGHT };
enum BorderOmission { BORDER_OMIT_TOP=1, BORDER_OMIT_BOTTOM=2 };
};
X11SkinElement::X11SkinElement(OpSkin* skin, const OpStringC8& name, SkinType type, SkinSize size)
:OpSkinElement(skin, name, type, size)
{
m_native_type = NATIVE_NOT_SUPPORTED;
if (size != SKINSIZE_DEFAULT)
return;
for (UINT32 i = 0; s_native_types[i]; i++)
{
if (name.CompareI(s_native_types[i]) == 0)
{
NativeType native_type = (NativeType) (i + 1);
switch (native_type)
{
case NATIVE_PAGEBAR:
case NATIVE_MAINBAR:
case NATIVE_PERSONALBAR:
case NATIVE_ADDRESSBAR:
case NATIVE_NAVIGATIONBAR:
case NATIVE_VIEWBAR:
case NATIVE_PAGEBAR_BUTTON:
{
if (type == SKINTYPE_DEFAULT || type == SKINTYPE_BOTTOM)
{
m_native_type = native_type;
}
break;
}
default:
{
if (type == SKINTYPE_DEFAULT)
{
m_native_type = native_type;
}
break;
}
}
break;
}
}
}
X11SkinElement::~X11SkinElement()
{
}
OP_STATUS X11SkinElement::GetTextColor(UINT32* color, INT32 state)
{
switch (m_native_type)
{
case NATIVE_MENU_BUTTON:
// This is the menu bar button. We want same colors as in popup menu
if (state & (SKINSTATE_SELECTED|SKINSTATE_HOVER))
*color = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TEXT_SELECTED);
else if (state & SKINSTATE_DISABLED)
*color = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TEXT_DISABLED);
else
*color = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_UI_MENU);
return OpStatus::OK;
}
return OpSkinElement::GetTextColor(color, state);
}
OP_STATUS X11SkinElement::GetSize(INT32* width, INT32* height, INT32 state)
{
switch (m_native_type)
{
case NATIVE_SLIDER_HORIZONTAL_TRACK:
{
*height = 4;
return OpStatus::OK;
}
case NATIVE_SLIDER_VERTICAL_TRACK:
{
*width = 4;
return OpStatus::OK;
}
case NATIVE_SLIDER_HORIZONTAL_KNOB:
{
*width = SLIDER_HORIZONTAL_KNOB_WIDTH;
*height = SLIDER_HORIZONTAL_KNOB_HEIGHT;
return OpStatus::OK;
}
case NATIVE_SLIDER_VERTICAL_KNOB:
{
*width = SLIDER_HORIZONTAL_KNOB_HEIGHT;
*height = SLIDER_HORIZONTAL_KNOB_WIDTH;
return OpStatus::OK;
}
case NATIVE_CHECKMARK:
case NATIVE_BULLET:
{
*width = CHECKMARK_SIZE;
*height = CHECKMARK_SIZE;
return OpStatus::OK;
}
case NATIVE_MENU_SEPARATOR:
{
*width = 4; // Should the separator be vertical
*height = 4;
return OpStatus::OK;
}
case NATIVE_DISCLOSURE_TRIANGLE:
{
*width = 22;
*height = 22;
return OpStatus::OK;
}
case NATIVE_SORT_ASCENDING:
case NATIVE_SORT_DESCENDING:
*width = 11;
*height = 11;
return OpStatus::OK;
case NATIVE_PAGEBAR_CLOSE_BUTTON:
case NATIVE_NOTIFIER_CLOSE_BUTTON:
*width = 11;
*height = 11;
return OpStatus::OK;
}
return OpSkinElement::GetSize(width, height, state);
}
OP_STATUS X11SkinElement::GetMargin(INT32* left, INT32* top, INT32* right, INT32* bottom, INT32 state)
{
switch (m_native_type)
{
case NATIVE_TAB_BUTTON:
// Required to achieve overlapping buttons and expected look
*left = -2;
*right = -2;
*bottom = -2;
return OpStatus::OK;
case NATIVE_MAINBAR_BUTTON:
*right = 2;
return OpStatus::OK;
}
return OpSkinElement::GetMargin(left, top, right, bottom, state);
}
OP_STATUS X11SkinElement::GetPadding(INT32* left, INT32* top, INT32* right, INT32* bottom, INT32 state)
{
switch (m_native_type)
{
case NATIVE_TAB_BUTTON:
*left = 10;
*top = 6;
*right = 10;
*bottom = 3;
return OpStatus::OK;
case NATIVE_DIALOG_TAB_PAGE:
*left = 10;
*top = 10;
*right = 10;
*bottom = 10;
return OpStatus::OK;
case NATIVE_DIALOG:
*left = 10;
*top = 10;
*right = 10;
*bottom = 10;
return OpStatus::OK;
case NATIVE_DIALOG_BUTTON_BORDER:
*left = 5;
*top = 10;
*right = 0;
*bottom = 0;
return OpStatus::OK;
case NATIVE_MAINBAR_BUTTON:
*left = 4;
*top = 3;
*right = 5;
*bottom = 4;
return OpStatus::OK;
}
return OpSkinElement::GetPadding(left, top, right, bottom, state);
}
OP_STATUS X11SkinElement::GetSpacing(INT32* spacing, INT32 state)
{
switch (m_native_type)
{
case NATIVE_MAINBAR_BUTTON:
*spacing = 2;
return OpStatus::OK;
}
return OpSkinElement::GetSpacing(spacing, state);
}
void X11SkinElement::OverrideDefaults(OpSkinElement::StateElement* se)
{
// Sizes (required with yaml)
switch (m_native_type)
{
case NATIVE_PUSH_DEFAULT_BUTTON:
case NATIVE_PUSH_BUTTON:
if (se->m_width < 110)
se->m_width = 110;
if (se->m_height < 25)
se->m_height = 25;
break;
}
// Margins
switch (m_native_type)
{
case NATIVE_DIALOG:
se->m_padding_bottom = se->m_padding_left = se->m_padding_right = se->m_padding_top = 10;
break;
case NATIVE_TOOLBAR_BUTTON:
case NATIVE_TAB_BUTTON:
case NATIVE_PAGEBAR_BUTTON:
case NATIVE_LIST_ITEM:
case NATIVE_DIALOG_BUTTON_BORDER:
case NATIVE_DROPDOWN_BUTTON:
case NATIVE_DROPDOWN_LEFT_BUTTON:
case NATIVE_DROPDOWN_EDIT:
// don't change anything for these
break;
default:
// Default margins for all others
se->m_margin_bottom = se->m_margin_left = se->m_margin_right = se->m_margin_top = 7;
}
}
OP_STATUS X11SkinElement::Draw(VisualDevice* vd, OpRect rect, INT32 state, DrawArguments args)
{
if (m_native_type == NATIVE_NOT_SUPPORTED)
return OpSkinElement::Draw(vd, rect, state, args);
UINT32 bgcol = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BACKGROUND);
UINT32 fgcol = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TEXT);
UINT32 gray = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BUTTON);
UINT32 lgray = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BUTTON_LIGHT);
UINT32 dgray = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BUTTON_DARK);
UINT32 dgray2 = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BUTTON_VERYDARK);
UINT32 uibg = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_UI_BACKGROUND);
UINT32 docbg = colorManager->GetBackgroundColor(); // This color can be changed from Prefs dialog
switch (m_native_type)
{
case NATIVE_PUSH_DEFAULT_BUTTON:
case NATIVE_PUSH_BUTTON:
case NATIVE_PAGEBAR_BUTTON:
case NATIVE_HEADER_BUTTON:
{
if (state & SKINSTATE_DISABLED)
fgcol = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TEXT_DISABLED);
if (m_native_type == NATIVE_PUSH_DEFAULT_BUTTON)
{
vd->SetColor32(dgray2);
vd->DrawRect(rect);
rect = rect.InsetBy(1, 1);
}
if (state & SKINSTATE_SELECTED)
vd->SetColor32(lgray);
else
vd->SetColor32(gray);
vd->FillRect(rect);
if (state & (SKINSTATE_PRESSED | SKINSTATE_SELECTED))
{
// sunken
Draw3DBorder(vd, dgray, lgray, rect);
Draw3DBorder(vd, dgray2, gray, rect.InsetBy(1, 1));
}
else
{
// raised
DrawFrame(vd, lgray, dgray, dgray2, rect);
}
break;
}
case NATIVE_MAINBAR_BUTTON:
{
OpSkinElement::Draw(vd, rect, state, args); // or should we call this one on default and remove same call above?
break;
}
case NATIVE_SELECTOR_BUTTON:
{
if (state & (SKINSTATE_PRESSED | SKINSTATE_SELECTED))
{
vd->SetColor32(dgray);
vd->FillRect(rect);
Draw3DBorder(vd, dgray, lgray, rect);
Draw3DBorder(vd, dgray2, gray, rect.InsetBy(1, 1));
}
else if (state & SKINSTATE_HOVER)
{
Draw3DBorder(vd, gray, dgray2, rect);
Draw3DBorder(vd, lgray, dgray, rect.InsetBy(1, 1));
}
break;
}
case NATIVE_POPUP_MENU_BUTTON:
{
if ((state & SKINSTATE_HOVER) && !(state & SKINSTATE_DISABLED))
{
vd->SetColor32(g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BACKGROUND_SELECTED));
vd->FillRect(rect);
}
if (state & (SKINSTATE_PRESSED|SKINSTATE_SELECTED))
{
// SKINSTATE_PRESSED specifies checked element, SKINSTATE_SELECTED specifies radio element
OpRect r(rect.x, rect.y, MAX_MENU_IMAGE_SIZE, rect.height);
int x = r.width > CHECKMARK_SIZE ? (r.width - CHECKMARK_SIZE) / 2 : 0;
int y = r.height > CHECKMARK_SIZE ? (r.height - CHECKMARK_SIZE) / 2 : 0;
r = r.InsetBy(x,y);
if(state & SKINSTATE_PRESSED)
DrawCheckMark(vd, fgcol, r);
else
DrawBullet(vd, fgcol, r);
}
}
break;
case NATIVE_MENU_BUTTON:
if (state & (SKINSTATE_PRESSED | SKINSTATE_SELECTED | SKINSTATE_HOVER))
{
vd->SetColor32(g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BACKGROUND_SELECTED));
vd->FillRect(rect);
Draw3DBorder(vd, dgray, lgray, rect);
}
break;
case NATIVE_TOOLBAR_BUTTON:
case NATIVE_LINK_BUTTON:
{
if (m_native_type == NATIVE_HEADER_BUTTON ||
state & (SKINSTATE_PRESSED | SKINSTATE_SELECTED | SKINSTATE_HOVER))
{
vd->SetColor32(gray);
vd->FillRect(rect);
if (state & (SKINSTATE_PRESSED | SKINSTATE_SELECTED))
Draw3DBorder(vd, dgray, lgray, rect);
else
Draw3DBorder(vd, lgray, dgray, rect.InsetBy(1, 1));
}
break;
}
case NATIVE_MENU:
{
vd->SetColor32(uibg);
vd->FillRect(rect);
break;
}
case NATIVE_POPUP_MENU:
{
vd->SetColor32(uibg);
vd->FillRect(rect);
vd->SetColor32(lgray);
vd->DrawLine(rect.TopLeft(), rect.width, TRUE);
vd->DrawLine(rect.TopLeft(), rect.height, FALSE);
vd->SetColor32(dgray);
vd->DrawLine(OpPoint(rect.x, rect.height-1), rect.width, TRUE);
vd->DrawLine(OpPoint(rect.x+rect.width-1, rect.y), rect.height, FALSE);
break;
}
case NATIVE_MENU_RIGHT_ARROW:
{
if (state & SKINSTATE_DISABLED)
vd->SetColor32(g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TEXT_DISABLED));
else if (state & SKINSTATE_HOVER)
vd->SetColor32(g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TEXT_SELECTED));
else
vd->SetColor32(g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_UI_MENU));
DrawArrow(vd, rect, (state & SKINSTATE_RTL) ? NativeSkinConstants::ARROW_LEFT : NativeSkinConstants::ARROW_RIGHT);
break;
}
case NATIVE_MENU_SEPARATOR:
{
vd->SetColor32(dgray);
int y = rect.y+(rect.height-2)/2;
int x = rect.x+2;
int w = rect.width-4;
vd->DrawLine(OpPoint(x, y), w, TRUE);
vd->SetColor32(lgray);
vd->DrawLine(OpPoint(x, y+1), w, TRUE);
break;
}
case NATIVE_CHECKMARK:
{
DrawCheckMark(vd, fgcol, rect);
break;
}
case NATIVE_BULLET:
{
DrawBullet(vd, fgcol, rect);
break;
}
case NATIVE_RADIO_BUTTON:
{
if (state & SKINSTATE_DISABLED)
{
fgcol = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TEXT_DISABLED);
bgcol = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BACKGROUND_DISABLED);
}
vd->BeginClipping(OpRect(rect.x, rect.y, rect.width-3, rect.height-3));
vd->SetColor32(dgray);
vd->FillEllipse(rect);
vd->EndClipping();
vd->BeginClipping(OpRect(rect.x+3, rect.y+3, rect.width-3, rect.height-3));
vd->SetColor32(lgray);
vd->FillEllipse(rect);
vd->EndClipping();
rect = rect.InsetBy(1, 1);
vd->BeginClipping(OpRect(rect.x, rect.y, rect.width-2, rect.height-2));
vd->SetColor32(dgray2);
vd->FillEllipse(rect);
vd->EndClipping();
vd->BeginClipping(OpRect(rect.x+2, rect.y+2, rect.width-2, rect.height-2));
vd->SetColor32(uibg);
vd->FillEllipse(rect);
vd->EndClipping();
vd->SetColor32(bgcol);
vd->FillEllipse(rect.InsetBy(1, 1));
if (state & SKINSTATE_SELECTED)
DrawBullet(vd, fgcol, rect);
break;
}
case NATIVE_CHECKBOX:
{
if (state & SKINSTATE_DISABLED)
{
fgcol = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TEXT_DISABLED);
bgcol = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BACKGROUND_DISABLED);
}
else if (state & SKINSTATE_PRESSED)
{
bgcol = gray;
}
vd->SetColor32(bgcol);
vd->FillRect(rect);
Draw3DBorder(vd, dgray, lgray, rect);
Draw3DBorder(vd, dgray2, uibg, rect.InsetBy(1, 1));
if (state & SKINSTATE_INDETERMINATE)
{
DrawIndeterminate(vd, fgcol, rect);
}
else if (state & SKINSTATE_SELECTED)
{
// Center checkmark
OpRect r(rect);
int x = (r.width-CHECKMARK_SIZE)/2 -1;
int y = (r.height-CHECKMARK_SIZE)/2;
r.x += x;
r.y += y;
r.width = CHECKMARK_SIZE;
r.height = CHECKMARK_SIZE;
DrawCheckMark(vd, fgcol, r);
}
break;
}
case NATIVE_EDIT:
case NATIVE_MULTILINE_EDIT:
case NATIVE_LISTBOX:
case NATIVE_START:
case NATIVE_SEARCH:
case NATIVE_TREEVIEW:
case NATIVE_DROPDOWN:
case NATIVE_DROPDOWN_EDIT:
{
if (state & SKINSTATE_DISABLED)
{
fgcol = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TEXT_DISABLED);
bgcol = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BACKGROUND_DISABLED);
}
vd->SetColor32(bgcol);
vd->FillRect(rect);
Draw3DBorder(vd, dgray, lgray, rect);
Draw3DBorder(vd, dgray2, uibg, rect.InsetBy(1, 1));
break;
}
case NATIVE_HOTLIST_SELECTOR:
{
Draw3DBorder(vd, dgray, lgray, rect);
Draw3DBorder(vd, dgray2, gray, rect.InsetBy(1, 1));
break;
}
case NATIVE_BROWSER:
{
Draw3DBorder(vd, dgray, lgray, rect);
Draw3DBorder(vd, dgray2, gray, rect.InsetBy(1, 1));
break;
}
case NATIVE_HORIZONTAL_SEPARATOR:
{
vd->SetColor(uibg);
vd->FillRect(rect);
vd->SetColor32(dgray);
vd->DrawLine(OpPoint(rect.x, rect.y), rect.width, TRUE);
vd->SetColor32(lgray);
vd->DrawLine(OpPoint(rect.x, rect.y+1), rect.width, TRUE);
break;
}
case NATIVE_VERTICAL_SEPARATOR:
{
vd->SetColor(uibg);
vd->FillRect(rect);
vd->SetColor32(dgray);
vd->DrawLine(OpPoint(rect.x, rect.y), rect.height, FALSE);
vd->SetColor32(lgray);
vd->DrawLine(OpPoint(rect.x, rect.y+1), rect.height, FALSE);
break;
}
case NATIVE_SPEEDDIAL:
{
vd->SetColor(docbg);
vd->FillRect(rect);
break;
}
case NATIVE_DIALOG:
case NATIVE_HOTLIST:
case NATIVE_BROWSER_WINDOW:
{
vd->SetColor(uibg);
vd->FillRect(rect);
break;
}
case NATIVE_WINDOW:
{
vd->SetColor(uibg);
vd->FillRect(rect);
vd->SetColor32(dgray);
vd->DrawLine(OpPoint(rect.x, rect.y+rect.height-2), rect.width, TRUE);
vd->SetColor32(lgray);
vd->DrawLine(OpPoint(rect.x, rect.y+rect.height-1), rect.width, TRUE);
break;
}
case NATIVE_DIALOG_TAB_PAGE:
{
rect.y -= 1;
rect.height += 1;
// We must fill the rectangle. When we drag a button from the Appearance
// dialog it gets initialized with this skin as a background.
vd->SetColor(uibg);
vd->FillRect(rect);
DrawFrame(vd, lgray, dgray, dgray2, rect);
break;
}
case NATIVE_TABS:
{
// Draws the entire background area of the tab buttons. We only want to draw the
// line at the bottom (the same as the top line of frame in NATIVE_DIALOG_TAB_PAGE)
rect.y = rect.height - 1;
rect.height = 1;
DrawTopFrameLine(vd, lgray, dgray, dgray2, rect);
break;
}
case NATIVE_TAB_BUTTON:
{
if (!(state & SKINSTATE_SELECTED))
{
rect.x += 2;
rect.width -= 4;
}
vd->SetColor32(uibg);
vd->FillRect(rect);
if (!(state & SKINSTATE_SELECTED))
{
rect.y += 2;
rect.height -= 2;
}
DrawTab(vd, lgray, dgray, dgray2, rect, state & SKINSTATE_SELECTED);
break;
}
case NATIVE_CAPTION_MINIMIZE_BUTTON:
{
break;
}
case NATIVE_CAPTION_CLOSE_BUTTON:
{
break;
}
case NATIVE_CAPTION_RESTORE_BUTTON:
{
break;
}
case NATIVE_SCROLLBAR_HORIZONTAL:
case NATIVE_SCROLLBAR_VERTICAL:
{
UINT32 scrollbgcol = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_SCROLLBAR_BACKGROUND);
vd->SetColor32(scrollbgcol);
vd->FillRect(rect);
break;
}
case NATIVE_SCROLLBAR_HORIZONTAL_KNOB:
case NATIVE_SCROLLBAR_VERTICAL_KNOB:
{
if (state & SKINSTATE_DISABLED)
{
UINT32 scrollbgcol = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_SCROLLBAR_BACKGROUND);
vd->SetColor32(scrollbgcol);
vd->FillRect(rect);
}
else
{
Draw3DBorder(vd, gray, dgray2, rect);
Draw3DBorder(vd, lgray, dgray, rect.InsetBy(1, 1));
vd->SetColor32(gray);
vd->FillRect(rect.InsetBy(2, 2));
}
break;
}
case NATIVE_SCROLLBAR_HORIZONTAL_LEFT:
DrawDirectionButton(vd, rect, NativeSkinConstants::ARROW_LEFT, state, fgcol, gray, lgray, dgray, dgray2);
break;
case NATIVE_SCROLLBAR_HORIZONTAL_RIGHT:
DrawDirectionButton(vd, rect, NativeSkinConstants::ARROW_RIGHT, state, fgcol, gray, lgray, dgray, dgray2);
break;
case NATIVE_SCROLLBAR_VERTICAL_UP:
DrawDirectionButton(vd, rect, NativeSkinConstants::ARROW_UP, state, fgcol, gray, lgray, dgray, dgray2);
break;
case NATIVE_SCROLLBAR_VERTICAL_DOWN:
DrawDirectionButton(vd, rect, NativeSkinConstants::ARROW_DOWN, state, fgcol, gray, lgray, dgray, dgray2);
break;
case NATIVE_DROPDOWN_BUTTON:
case NATIVE_DROPDOWN_LEFT_BUTTON:
rect.x += m_native_type == NATIVE_DROPDOWN_BUTTON ? -2 : 2;
rect.y += 2;
rect.height -= 4;
DrawDirectionButton(vd, rect, NativeSkinConstants::ARROW_DOWN, state, fgcol, gray, lgray, dgray, dgray2);
break;
case NATIVE_STATUS:
{
Draw3DBorder(vd, dgray, lgray, rect);
break;
}
case NATIVE_HOTLIST_PANEL_HEADER:
case NATIVE_HOTLIST_SPLITTER:
case NATIVE_MAINBAR:
case NATIVE_PERSONALBAR:
case NATIVE_PAGEBAR:
case NATIVE_ADDRESSBAR:
case NATIVE_NAVIGATIONBAR:
case NATIVE_MAILBAR:
case NATIVE_CHATBAR:
case NATIVE_VIEWBAR:
{
if (GetType() == SKINTYPE_BOTTOM)
break;
vd->SetColor32(dgray);
vd->DrawLine(OpPoint(rect.x, rect.y+rect.height-2), rect.width, TRUE);
vd->SetColor32(lgray);
vd->DrawLine(OpPoint(rect.x, rect.y+rect.height-1), rect.width, TRUE);
break;
}
case NATIVE_CYCLER:
{
Draw3DBorder(vd, gray, dgray2, rect);
break;
}
case NATIVE_PROGRESS_IMAGES:
case NATIVE_PROGRESS_SPEED:
case NATIVE_PROGRESS_ELAPSED:
case NATIVE_PROGRESS_STATUS:
case NATIVE_PROGRESS_GENERAL:
case NATIVE_PROGRESS_CLOCK:
case NATIVE_PROGRESS_EMPTY:
case NATIVE_PROGRESS_FULL:
case NATIVE_IDENTIFY_AS:
{
UINT32 color;
if (m_native_type == NATIVE_PROGRESS_FULL)
color = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BACKGROUND_SELECTED);
else
color = gray;
vd->SetColor(color);
vd->FillRect(rect);
Draw3DBorder(vd, dgray, lgray, rect);
break;
}
case NATIVE_DISCLOSURE_TRIANGLE:
{
vd->SetColor32(gray);
vd->FillRect(rect);
int direction = state & SKINSTATE_SELECTED ? NativeSkinConstants::ARROW_DOWN : NativeSkinConstants::ARROW_RIGHT;
if (!(state & SKINSTATE_DISABLED))
{
vd->SetColor32(fgcol);
DrawArrow(vd, rect, direction);
}
else
{
rect.x ++;
rect.y ++;
vd->SetColor32(lgray);
DrawArrow(vd, rect, direction);
rect.x --;
rect.y --;
vd->SetColor32(dgray);
DrawArrow(vd, rect, direction);
}
break;
}
case NATIVE_SORT_ASCENDING:
{
vd->SetColor32(fgcol);
DrawArrow(vd, rect, NativeSkinConstants::ARROW_UP);
break;
}
case NATIVE_SORT_DESCENDING:
{
vd->SetColor32(fgcol);
DrawArrow(vd, rect, NativeSkinConstants::ARROW_DOWN);
break;
}
case NATIVE_TOOLTIP:
case NATIVE_NOTIFIER:
{
Draw3DBorder(vd, dgray2, dgray2, rect);
vd->SetColor32(g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TOOLTIP_BACKGROUND));
vd->FillRect(rect.InsetBy(1, 1));
break;
}
case NATIVE_PAGEBAR_CLOSE_BUTTON:
{
if( state & SKINSTATE_HOVER)
{
vd->SetColor32(lgray);
vd->FillRect(rect);
}
DrawCloseCross(vd, dgray2, rect);
break;
}
case NATIVE_NOTIFIER_CLOSE_BUTTON:
{
if( state & SKINSTATE_HOVER)
{
vd->SetColor32(lgray);
vd->FillRect(rect);
}
DrawCloseCross(vd, dgray2, rect);
break;
}
case NATIVE_LIST_ITEM:
{
if(state & SKINSTATE_SELECTED)
{
vd->SetColor32(g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BACKGROUND_SELECTED));
vd->FillRect(rect);
}
break;
}
case NATIVE_SLIDER_HORIZONTAL_TRACK:
{
int c = rect.height/2 - 1;
vd->SetColor32(gray);
vd->DrawLine(OpPoint(rect.x, rect.y+c), rect.width-1, TRUE);
if (!(state & SKINSTATE_DISABLED))
vd->SetColor32(dgray);
vd->DrawLine(OpPoint(rect.x, rect.y+c+1), rect.width-1, TRUE);
break;
}
case NATIVE_SLIDER_VERTICAL_TRACK:
{
int c = rect.width/2 - 1;
vd->SetColor32(gray);
vd->DrawLine(OpPoint(rect.x+c, rect.y), rect.height-1, FALSE);
if (!(state & SKINSTATE_DISABLED))
vd->SetColor32(dgray);
vd->DrawLine(OpPoint(rect.x+c+1, rect.y), rect.height-1, FALSE);
break;
}
case NATIVE_SLIDER_HORIZONTAL_KNOB:
case NATIVE_SLIDER_VERTICAL_KNOB:
{
OpRect r(rect);
if (m_native_type==NATIVE_SLIDER_HORIZONTAL_KNOB)
{
if (r.height > SLIDER_HORIZONTAL_KNOB_HEIGHT)
{
int c = r.y + r.height/2;
r.y = c - SLIDER_HORIZONTAL_KNOB_HEIGHT/2;
r.height = SLIDER_HORIZONTAL_KNOB_HEIGHT;
}
}
if (state & SKINSTATE_DISABLED)
{
Draw3DBorder(vd, gray, gray, r);
Draw3DBorder(vd, lgray, dgray, r.InsetBy(1, 1));
}
else
{
Draw3DBorder(vd, gray, dgray2, r);
Draw3DBorder(vd, lgray, dgray, r.InsetBy(1, 1));
}
vd->SetColor32(gray);
vd->FillRect(r.InsetBy(2, 2));
break;
}
}
return OpStatus::OK;
}
void X11SkinElement::DrawDirectionButton(VisualDevice *vd, OpRect rect, int dir, INT32 state,
UINT32 fgcol, UINT32 gray, UINT32 lgray, UINT32 dgray, UINT32 dgray2)
{
vd->SetColor32(gray);
vd->FillRect(rect);
if (state & SKINSTATE_PRESSED)
{
vd->SetColor32(dgray);
vd->DrawRect(rect);
rect.x++;
rect.y++;
}
else
{
Draw3DBorder(vd, gray, dgray2, rect);
Draw3DBorder(vd, lgray, dgray, rect.InsetBy(1, 1));
}
// Draw arrow
if (!(state & SKINSTATE_DISABLED))
{
vd->SetColor32(fgcol);
DrawArrow(vd, rect, dir);
}
else
{
rect.x ++;
rect.y ++;
vd->SetColor32(lgray);
DrawArrow(vd, rect, dir);
rect.x --;
rect.y --;
vd->SetColor32(dgray);
DrawArrow(vd, rect, dir);
}
}
void X11SkinElement::DrawArrow(VisualDevice *vd, const OpRect &rect, int direction)
{
static INT32 arrow_offset[4] = { 3, 2, 1, 0 }; ///< Offset of the arrow scanline
static INT32 arrow_length[4] = { 1, 3, 5, 7 }; ///< Length of the arrow scanline
int minsize = MIN(rect.width, rect.height);
int x = rect.x + rect.width/2;
int y = rect.y + rect.height/2;
int levels = 4;
if (minsize < 9)
levels = 2;
else if (minsize < 11)
levels = 3;
if (direction == NativeSkinConstants::ARROW_UP || direction == NativeSkinConstants::ARROW_DOWN)
{
x -= arrow_length[levels-1]/2;
y -= levels/2;
}
else
{
x -= levels/2;
y -= arrow_length[levels-1]/2;
}
if (direction == NativeSkinConstants::ARROW_UP)
{
for (int i=0; i<levels; i++)
vd->DrawLine(OpPoint(x+arrow_offset[i], y+i), arrow_length[i], TRUE);
}
else if (direction == NativeSkinConstants::ARROW_DOWN)
{
for (int i=0; i<levels; i++)
vd->DrawLine(OpPoint(x+arrow_offset[i], y+4-i), arrow_length[i], TRUE);
}
else if (direction == NativeSkinConstants::ARROW_LEFT)
{
for (int i=0; i<levels; i++)
vd->DrawLine(OpPoint(x+i, y+arrow_offset[i]), arrow_length[i], FALSE);
}
else if (direction == NativeSkinConstants::ARROW_RIGHT)
{
for (int i=0; i<levels; i++)
vd->DrawLine(OpPoint(x+4-i, y+arrow_offset[i]), arrow_length[i], FALSE);
}
}
void X11SkinElement::Draw3DBorder(VisualDevice *vd, UINT32 lcolor, UINT32 dcolor, OpRect rect, int omissions)
{
if (omissions & NativeSkinConstants::BORDER_OMIT_TOP)
{
rect.y --;
rect.height ++;
}
if (omissions & NativeSkinConstants::BORDER_OMIT_BOTTOM)
rect.height ++;
vd->SetColor32(lcolor);
if (!(omissions & NativeSkinConstants::BORDER_OMIT_TOP))
vd->DrawLine(OpPoint(rect.x, rect.y), rect.width-1, TRUE);
vd->DrawLine(OpPoint(rect.x, rect.y), rect.height-1, FALSE);
vd->SetColor32(dcolor);
if (!(omissions & NativeSkinConstants::BORDER_OMIT_BOTTOM))
vd->DrawLine(OpPoint(rect.x, rect.y + rect.height - 1), rect.width, TRUE);
vd->DrawLine(OpPoint(rect.x + rect.width - 1, rect.y), rect.height, FALSE);
}
void X11SkinElement::DrawCheckMark(VisualDevice *vd, UINT32 color, const OpRect &rect)
{
vd->SetColor32(color);
int x1 = rect.x + 3;
int y1 = rect.y + 5;
int x2 = x1 + 2;
int y2 = y1 + 2;
vd->DrawLine(OpPoint(x1, y1), OpPoint(x2, y2), 1);
vd->DrawLine(OpPoint(x1, y1 + 1), OpPoint(x2, y2 + 1), 1);
vd->DrawLine(OpPoint(x1, y1 + 2), OpPoint(x2, y2 + 2), 1);
vd->DrawLine(OpPoint(x2, y2), OpPoint(x2 + 5, y2 - 5), 1);
vd->DrawLine(OpPoint(x2, y2 + 1), OpPoint(x2 + 5, y2 - 5 + 1), 1);
vd->DrawLine(OpPoint(x2, y2 + 2), OpPoint(x2 + 5, y2 - 5 + 2), 1);
}
void X11SkinElement::DrawIndeterminate(VisualDevice *vd, UINT32 color, const OpRect &rect)
{
vd->SetColor32(color);
int x1 = rect.x + 3;
int y1 = (rect.y + rect.height - 2) / 2;
int x2 = rect.width - 4;
vd->DrawLine(OpPoint(x1, y1), OpPoint(x2, y1), 2);
}
void X11SkinElement::DrawBullet(VisualDevice *vd, UINT32 color, const OpRect &rect)
{
vd->SetColor32(color);
vd->FillEllipse(rect.InsetBy(3, 3));
}
void X11SkinElement::DrawCloseCross(VisualDevice *vd, UINT32 color, const OpRect &rect)
{
vd->SetColor32(color);
int x1 = rect.x + 1;
int y1 = rect.y + 1;
int x2 = x1 + rect.width - 2;
int y2 = y1 + rect.height - 3;
vd->DrawLine(OpPoint(x1, y1), OpPoint(x2-1, y2), 1);
vd->DrawLine(OpPoint(x1+1, y1), OpPoint(x2, y2), 1);
vd->DrawLine(OpPoint(x1, y2-1), OpPoint(x2-1, y1-1), 1);
vd->DrawLine(OpPoint(x1+1, y2-1), OpPoint(x2, y1-1), 1);
}
void X11SkinElement::DrawFrame(VisualDevice *vd, UINT32 lcolor, UINT32 dcolor1, UINT32 dcolor2, const OpRect &rect)
{
int x1 = rect.x;
int y1 = rect.y;
vd->SetColor32(lcolor);
vd->DrawLine(OpPoint(x1, y1), rect.width-1, TRUE);
vd->DrawLine(OpPoint(x1, y1), rect.height-1, FALSE);
vd->SetColor32(dcolor1);
vd->DrawLine(OpPoint(x1+rect.width-2, y1+1), rect.height-2, FALSE);
vd->DrawLine(OpPoint(x1+1, y1+rect.height-2), rect.width-2, TRUE);
vd->SetColor32(dcolor2);
vd->DrawLine(OpPoint(x1+rect.width-1, y1), rect.height, FALSE);
vd->DrawLine(OpPoint(x1, y1+rect.height-1), rect.width, TRUE);
}
void X11SkinElement::DrawTopFrameLine(VisualDevice *vd, UINT32 lcolor, UINT32 dcolor1, UINT32 dcolor2, const OpRect &rect)
{
int x1 = rect.x;
int y1 = rect.y;
vd->SetColor32(lcolor);
vd->DrawLine(OpPoint(x1, y1), rect.width-1, TRUE);
vd->SetColor32(dcolor2);
vd->DrawLine(OpPoint(x1+rect.width-1, y1), 1, TRUE);
}
void X11SkinElement::DrawTab(VisualDevice *vd, UINT32 lcolor, UINT32 dcolor1, UINT32 dcolor2, const OpRect &rect, BOOL is_active)
{
int x1 = rect.x;
int y1 = rect.y;
int x2 = x1 + rect.width - 1;
vd->SetColor32(lcolor);
vd->DrawLine(OpPoint(x1+2, y1), rect.width-4, TRUE);
vd->DrawLine(OpPoint(x1+1, y1+1), 1, TRUE);
vd->DrawLine(OpPoint(x1, y1+2), rect.height-2, FALSE);
vd->SetColor32(dcolor2);
vd->DrawLine(OpPoint(x2-1, y1+1), 1, TRUE);
vd->DrawLine(OpPoint(x2, y1+2), rect.height-2, FALSE);
vd->SetColor32(dcolor1);
vd->DrawLine(OpPoint(x2-1, y1+2), rect.height-2, FALSE);
if(!is_active)
{
vd->SetColor32(lcolor);
vd->DrawLine(OpPoint(x1, y1+rect.height-1), rect.width, TRUE);
}
}
|
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup() {
ofSetFrameRate(60);
ofSetWindowTitle("openFrameworks");
ofBackground(239);
ofSetLineWidth(2);
ofEnableDepthTest();
}
//--------------------------------------------------------------
void ofApp::update() {
}
//--------------------------------------------------------------
void ofApp::draw() {
vector<ofColor> base_color_list;
ofColor color;
vector<int> hex_list = { 0xef476f, 0xffd166, 0x06d6a0, 0x118ab2, 0x073b4c };
for (auto hex : hex_list) {
color.setHex(hex);
base_color_list.push_back(color);
}
int color_index = 0;
this->cam.begin();
for (int radius = 30; radius <= 300; radius += 10) {
ofMesh mesh, frame;
frame.setMode(ofPrimitiveMode::OF_PRIMITIVE_LINES);
auto deg_max = ofMap(ofNoise(radius * 0.005 + ofGetFrameNum() * 0.015), 0, 1, 0, 450);
if (deg_max > 360) { deg_max = 360; }
for (int deg = 0; deg < deg_max; deg += 1) {
auto location = glm::vec2(radius * cos(deg * DEG_TO_RAD), radius * sin(deg * DEG_TO_RAD));
mesh.addVertex(glm::vec3(location, -30));
mesh.addVertex(glm::vec3(location, 30));
frame.addVertex(glm::vec3(location, -30));
frame.addVertex(glm::vec3(location, 30));
if (deg > 0) {
mesh.addIndex(mesh.getNumVertices() - 1); mesh.addIndex(mesh.getNumVertices() - 2); mesh.addIndex(mesh.getNumVertices() - 4);
mesh.addIndex(mesh.getNumVertices() - 1); mesh.addIndex(mesh.getNumVertices() - 3); mesh.addIndex(mesh.getNumVertices() - 4);
frame.addIndex(frame.getNumVertices() - 1); frame.addIndex(frame.getNumVertices() - 3);
frame.addIndex(frame.getNumVertices() - 2); frame.addIndex(frame.getNumVertices() - 4);
}
mesh.addColor(base_color_list[color_index]);
mesh.addColor(base_color_list[color_index]);
frame.addColor(ofColor(39));
frame.addColor(ofColor(39));
}
frame.addIndex(0); frame.addIndex(1);
frame.addIndex(frame.getNumVertices() - 1); frame.addIndex(frame.getNumVertices() - 2);
mesh.draw();
frame.drawWireframe();
color_index = (color_index + 1) % base_color_list.size();
}
this->cam.end();
}
//--------------------------------------------------------------
int main() {
ofSetupOpenGL(720, 720, OF_WINDOW);
ofRunApp(new ofApp());
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** 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.
**
*/
#include "core/pch.h"
#include "modules/display/vis_dev.h"
#ifdef _PLUGIN_SUPPORT_
OP_STATUS CoreViewContainer::AddPluginArea(const OpRect& rect, ClipViewEntry* entry)
{
if (rect.IsEmpty())
return OpStatus::OK;
PluginAreaIntersection *info = OP_NEW(PluginAreaIntersection, ());
if (!info)
return OpStatus::ERR_NO_MEMORY;
info->entry = entry;
info->rect = rect;
OP_STATUS status = info->visible_region.Set(info->rect);
if (OpStatus::IsError(status))
{
OP_DELETE(info);
return status;
}
info->Into(&plugin_intersections);
return OpStatus::OK;
}
void CoreViewContainer::UpdateAndDeleteAllPluginAreas(const OpRect &rect)
{
while (plugin_intersections.First())
{
PluginAreaIntersection *info = (PluginAreaIntersection*) plugin_intersections.First();
UpdatePluginArea(rect, info);
info->Out();
OP_DELETE(info);
}
}
void CoreViewContainer::UpdatePluginArea(const OpRect &rect, PluginAreaIntersection* info)
{
// Make info relative to the plugin
int plugin_x = info->rect.x;
int plugin_y = info->rect.y;
for(int i = 0; i < info->visible_region.num_rects; i++)
{
info->visible_region.rects[i].x -= plugin_x;
info->visible_region.rects[i].y -= plugin_y;
}
OpRect clip_rect = rect;
clip_rect.x -= plugin_x;
clip_rect.y -= plugin_y;
info->rect.x = 0;
info->rect.y = 0;
OpRect plugin_rect = info->rect;
info->visible_region.CoalesceRects();
// Calculate the visible area of the plugin and set it on its view.
//
// We may have painted only a part of the area which intersects with the plugin.
// Theirfore we can only update the plugins visibility region with changes done to that part.
// This is done in the following way:
// 1. Exclude the clip_rect from the "work region"* to assume full visibility on that painted area.
// 2. Include rectangles we know are visible, also only for the painted area
//
// This will cause the work_region to be fragmented and change a lot when we get multiple OnPaint on fractions of the area (that may
// even happen during the same screen validation). To get rid of fragmentation so we can see of the region differ from the "final region"*,
// we will do this:
// 1. Create a inverted region (Represent the covered area instead of the non-covered)
// 2. Recreate "work_region" from the inverted region to again represent the non-covered area. Now it will be as optimal as it can be.
// Note: There's no guarantee that the actual representation of the region will be the same as the final region, even if the area it represents
// is the exact same (due to order of rectangles). This will sometimes cause updates that is not needed.
//
// * "work region" Region used to calculate the new visible region and compared to final region.
// * "final region" Region that is currently on the plugin. Compared to the work region to detect changes.
BgRegion &vis_region = info->visible_region;
BgRegion &final_region = info->entry->GetClipView()->m_visible_region;
// Create the work region from the current final_region
BgRegion work_region;
RETURN_VOID_IF_ERROR(work_region.Set(final_region));
// Update the work_region with the changes we did in this paint pass.
// Feed it with scaled coordinates since final_region is also scaled.
RETURN_VOID_IF_ERROR(work_region.ExcludeRect(clip_rect, FALSE));
for(int i = 0; i < vis_region.num_rects; i++)
{
OpRect r = vis_region.rects[i];
r.IntersectWith(clip_rect);
if (!r.IsEmpty())
{
RETURN_VOID_IF_ERROR(work_region.IncludeRect(r));
}
}
work_region.CoalesceRects();
// Invert so we get a "overlap region"
BgRegion inverted_region;
RETURN_VOID_IF_ERROR(inverted_region.Set(plugin_rect));
for(int i = 0; i < work_region.num_rects; i++)
{
RETURN_VOID_IF_ERROR(inverted_region.ExcludeRect(work_region.rects[i], FALSE));
}
// Invert back from the overlap region so work_region is a optimal visibility region.
RETURN_VOID_IF_ERROR(work_region.Set(plugin_rect));
for(int i = 0; i < inverted_region.num_rects; i++)
{
RETURN_VOID_IF_ERROR(work_region.ExcludeRect(inverted_region.rects[i], FALSE));
}
// The plugin may be partly outside of its owning CoreView (partly scrolled out of view)
// So get the cliprect from the ClipView and exclude it from the work region.
OpRect view_clip_rect = info->entry->GetClipView()->GetClipRect();
if (view_clip_rect.IsEmpty())
work_region.Reset();
else
{
OpRect top(0, 0, plugin_rect.width, view_clip_rect.y);
OpRect bottom(0, view_clip_rect.y + view_clip_rect.height, plugin_rect.width, plugin_rect.height - (view_clip_rect.y + view_clip_rect.height));
OpRect left(0, 0, view_clip_rect.x, plugin_rect.height);
OpRect right(view_clip_rect.x + view_clip_rect.width, 0, plugin_rect.width - (view_clip_rect.x + view_clip_rect.width), plugin_rect.height);
if (!top.IsEmpty())
RETURN_VOID_IF_ERROR(work_region.ExcludeRect(top, FALSE));
if (!bottom.IsEmpty())
RETURN_VOID_IF_ERROR(work_region.ExcludeRect(bottom, FALSE));
if (!left.IsEmpty())
RETURN_VOID_IF_ERROR(work_region.ExcludeRect(left, FALSE));
if (!right.IsEmpty())
RETURN_VOID_IF_ERROR(work_region.ExcludeRect(right, FALSE));
}
// If the work_region differs, update the clipviews OpView and final_region to cut the plugin according to the new visibility.
if (!work_region.Equals(final_region) ||
// If visibility regions are empty, the overlap region might still differ (f.ex if the zoom has changed, the viewsize will have changed)
// so always enter then. SetCustomOverlapRegion will bail out if it is equal anyway.
(work_region.num_rects == 0 && final_region.num_rects == 0))
{
// Invert to overlap-region and set it
BgRegion rgn;
RETURN_VOID_IF_ERROR(rgn.Set(plugin_rect));
for(int i = 0; i < work_region.num_rects; i++)
{
RETURN_VOID_IF_ERROR(rgn.ExcludeRect(work_region.rects[i], FALSE));
}
RETURN_VOID_IF_ERROR(info->entry->GetOpView()->SetCustomOverlapRegion(rgn.rects, rgn.num_rects));
// The work region is now in use, so update final_region to it
RETURN_VOID_IF_ERROR(final_region.Set(work_region));
}
}
void CoreViewContainer::CoverPluginArea(const OpRect& rect)
{
if (rect.IsEmpty())
return;
// Exclude the rect from any intersecting plugins visible region.
PluginAreaIntersection* info = (PluginAreaIntersection*) plugin_intersections.First();
while (info)
{
if (info->visible_region.bounding_rect.Intersecting(rect))
{
if (OpStatus::IsError(info->visible_region.ExcludeRect(rect, FALSE)))
return;
}
info = (PluginAreaIntersection*) info->Suc();
}
}
void CoreViewContainer::RemoveAllPluginAreas()
{
while (plugin_intersections.First())
{
PluginAreaIntersection* info = (PluginAreaIntersection*) plugin_intersections.First();
info->Out();
OP_DELETE(info);
}
}
void CoreViewContainer::RemovePluginArea(ClipViewEntry* entry)
{
PluginAreaIntersection* info = (PluginAreaIntersection*) plugin_intersections.First();
while (info)
{
PluginAreaIntersection* next = static_cast<PluginAreaIntersection*>(info->Suc());
if (info->entry == entry)
{
info->Out();
OP_DELETE(info);
}
info = next;
}
}
BOOL CoreViewContainer::HasPluginArea()
{
return plugin_intersections.First() ? TRUE : FALSE;
}
#endif // _PLUGIN_SUPPORT_
|
class Solution {
public:
void reverseWord(string &s, int i, int j){
while(i < j){
swap(s[i], s[j]);
++i;
--j;
}
}
void reverseWords(string &s) {
int n = s.size(), i = 0, j = 0;
//reverseWord(s, 0, n-1);
reverse(s.begin(), s.end());
int start = 0, pos = 0, end = 0;
for(i = 0; i < n; ++i){
if(s[i] != ' '){
if(pos != 0) s[pos++] = ' ';
j = i;
while(j < n && s[j] != ' '){
s[pos++] = s[j++];
}
int len = j-i;
//reverseWord(s, pos-len, pos-1);
reverse(s.begin()+pos-len, s.begin()+pos);
i = j;
}
}
s.erase(s.begin()+pos, s.end());
}
};
|
#pragma once
#include <list>
#include <Poco/Mutex.h>
#include <Poco/SharedPtr.h>
#include "loop/StoppableRunnable.h"
#include "loop/StoppableLoop.h"
#include "util/Loggable.h"
namespace BeeeOn {
class LoopRunner : public StoppableLoop, public Loggable {
public:
typedef Poco::SharedPtr<LoopRunner> Ptr;
LoopRunner();
~LoopRunner();
void addRunnable(StoppableRunnable::Ptr runnable);
void addLoop(StoppableLoop::Ptr loop);
void setAutoStart(bool enable);
/**
* @brief Set whether stopAll() should run in parallel.
*/
void setStopParallel(bool parallel);
void start() override;
void stop() override;
void autoStart();
protected:
/**
* @brief Wrapper around StoppableLoop that allows to
* stop it from inside a thread.
*/
class Stopper : public Poco::Runnable, Loggable {
public:
Stopper();
Stopper(StoppableLoop::Ptr loop);
void run() override;
private:
StoppableLoop::Ptr m_loop;
};
/**
* @brief Stop all loop in reverse order. If the property stopParallel
* is true then the loops are stopped in parallel (multiple threads).
*
* If there is an issue with starting threads, the loops that were not
* stopped in parallel are stopped sequentially as a fallback.
*/
void stopAll(std::list<Stopper> &list);
/**
* @brief Stops the given list of loops in parallel. Loops that have been
* stopped are removed from the list.
*/
void stopParallel(std::list<Stopper> &list);
private:
bool m_autoStart;
bool m_stopParallel;
Poco::FastMutex m_lock;
std::list<StoppableLoop::Ptr> m_loops;
std::list<Stopper> m_started;
};
}
|
/**
\file Avoid.hpp
\author UnBeatables
\date LARC2018
\name Avoid
*/
#pragma once
/*
* Avoid inherited from BehaviorBase.
*/
#include <BehaviorBase.hpp>
/**
\brief This class is responsable for robot`s behavior of avoiding bumping in other robots.
*/
class Avoid : public BehaviorBase
{
private:
static Avoid *instance;
public:
/**
\brief Class constructor.
\details Inicialize class parameters.
*/
Avoid();
/**
\brief Sets Avoid as current instance.
\return Current instance.
*/
static BehaviorBase* Behavior();
/**
\brief This function determines Avoid transition.
\details Transitions to lastBehavior if sonar is detecting no presence.
\param _ub void pointer for UnBoard.
\return Transition state.
*/
BehaviorBase* transition(void*);
/**
\brief This function is responsable for robot`s action when the sonar detects object.
\details The robot will move right if object is in the left, will move left if object is in the right
and will not move if object is in the middle.
\param _ub void pointer for UnBoard.
*/
void action(void*);
};
|
/*******************************************************************************
* filename: C_RobustFunctionalNetwork.hpp
* description: Derived class for robust functional networks
* author: Moritz Beber
* created: 2010-07-05
* copyright: Jacobs University Bremen. All rights reserved.
*******************************************************************************
*
******************************************************************************/
#ifndef _C_ROBUSTFUNCTIONALNETWORK_HPP
#define _C_ROBUSTFUNCTIONALNETWORK_HPP
/*******************************************************************************
* Includes
******************************************************************************/
// project
#include "C_FlowDistributionNetwork.hpp"
#include "C_RobustParameterManager.hpp"
/*******************************************************************************
* Declarations
******************************************************************************/
namespace rfn {
class RobustFunctionalNetwork: public FlowDistributionNetwork {
protected:
/* Data Members */
bool _robust_changed;
double _robustness;
RobustParameterManager* _robust_parameters;
public:
/* Constructors & Destructor */
RobustFunctionalNetwork();
RobustFunctionalNetwork(const RobustFunctionalNetwork& c);
virtual ~RobustFunctionalNetwork();
// polymorphic "copy constructors"
virtual FlowDistributionNetwork* clone() = 0;
/* Operators */
virtual FlowDistributionNetwork& operator=(const FlowDistributionNetwork& a);
virtual FlowDistributionNetwork& operator=(FlowDistributionNetwork& a);
RobustFunctionalNetwork& operator=(const RobustFunctionalNetwork& a);
RobustFunctionalNetwork& operator=(RobustFunctionalNetwork& a);
/* Member Functions */
// save this object to a binary stream
virtual void write_to_binary_stream(bfsys::ofstream& out,
const unsigned long iteration);
// read this object from a binary stream
virtual unsigned long read_from_binary_stream(bfsys::ifstream& in);
// change the network
virtual void mutate()
{
this->_changed = true;
this->_robust_changed = true;
this->_mutation->mutate(this->_network);
}
// get and if necessary compute robustness
double robustness();
// removes unused nodes
virtual void prune()
{
FlowDistributionNetwork::prune();
this->_robust_changed = true;
}
protected:
/* Internal Functions */
virtual void compute_robustness() = 0;
}; // class RobustFunctionalNetwork
} // namespace rfn
#endif // _C_ROBUSTFUNCTIONALNETWORK_HPP
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#include <map>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <numeric>
#include <bitset>
#include <deque>
const long long LINF = (5e18);
const int INF = (1<<30);
#define EPS 1e-6
const int MOD = 1000000007;
using namespace std;
class TheSwap {
public:
typedef pair<int, int> P;
map<P, int> memo;
vector<int> make(int n) {
vector<int> res;
while (n > 0) {
res.push_back(n%10);
n /= 10;
}
return res;
}
int value(vector<int> &v) {
int res = 0;
int N = (int)v.size();
int d = 1;
for (int i=0; i<N; ++i) {
res += d*v[i];
d *= 10;
}
return res;
}
int go(vector<int> &V, int K) {
int n = value(V);
if (K == 0) {
return n;
}
if ( memo.count(P(n,K)) ) {
return memo[P(n,K)];
}
int a = -1;
int N =(int)V.size();
for (int i=N-1; i>=0; --i) {
for (int j=i-1; j>=0; --j) {
if (i == N-1 && V[j] == 0) {
continue;
}
swap(V[i], V[j]);
a = max(a, go(V, K-1));
swap(V[j], V[i]);
}
}
return memo[P(n,K)] = a;
}
int findMax(int n, int k) {
vector<int> V(make(n));
return go(V, k);
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 16375; int Arg1 = 1; int Arg2 = 76315; verify_case(0, Arg2, findMax(Arg0, Arg1)); }
void test_case_1() { int Arg0 = 432; int Arg1 = 1; int Arg2 = 423; verify_case(1, Arg2, findMax(Arg0, Arg1)); }
void test_case_2() { int Arg0 = 90; int Arg1 = 4; int Arg2 = -1; verify_case(2, Arg2, findMax(Arg0, Arg1)); }
void test_case_3() { int Arg0 = 5; int Arg1 = 2; int Arg2 = -1; verify_case(3, Arg2, findMax(Arg0, Arg1)); }
void test_case_4() { int Arg0 = 436659; int Arg1 = 2; int Arg2 = 966354; verify_case(4, Arg2, findMax(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
TheSwap ___test;
___test.run_test(-1);
}
// END CUT HERE
|
//
// Player.cpp
// Polygons
//
// Created by Italo Ricardo Geske on 2021/05/16.
// Copyright © 2021 Italo Ricardo Geske. All rights reserved.
//
#include <stdio.h>
#include "Player.h"
Player::Player() {
name = "";
}
Player::Player (std::string name, bool isPlayer) {
this->name = name;
this->isPlayer = isPlayer;
}
std::string Player::GetName() {
return name;
}
bool Player::IsPlayer() {
return isPlayer;
}
|
#include <time.h>
#include <iostream>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <cstring>
#include <fstream>
#include <cstdio>
using namespace std;
const double P=3.0;//平均每个桶装的元素个数的上限 ,实测貌似1.0效果比较好
int E;//目前使用了哈希值的前 E 位来分组
int R;//实际装入本哈希表的元素总数
int N;//目前使用的桶的个数
/*
操作过程中,始终维护两个性质
1. R/N <= P 可以推出 max(N) = max(R/P) = maxn/P 所以,所需链表的个数为 maxn/P
2. 2^(E-1) <= N < 2^E
*/
int p2[35];//记录2的各个次方 p2[i]=2^i
int mask[35]; //记录掩码 mask[i]=p2[i]-1
bool ERROR;//错误信息
string tohex(const string& str)
{
string ret;
static const char *hex="0123456789ABCDEF";
for(int i=0;i!=str.size();++i)
{
ret.push_back(hex[(str[i]>>4)&0xf]);
ret.push_back( hex[str[i]&0xf]);
}
return ret;
}
int getnum(string str)
{
int ret = 0;
int tempret = 0;
for(int i=0;i<str.size();i++)
{
if(str[i] >= 'A' && str[i] <= 'Z')
tempret = str[i]-'A' + 10;
else
tempret = str[i] -'0';
if(i % 2 == 0)
ret += tempret * 16;
else
ret += tempret;
}
return ret;
}
vector<string> split(string str,string pattern)
{
std::string::size_type pos;
std::vector<std::string> result;
str+=pattern;//扩展字符串以方便操作
int size=str.size();
for(int i=0; i<size; i++)
{
pos=str.find(pattern,i);
if(pos<size)
{
std::string s=str.substr(i,pos-i);
result.push_back(s);
i=pos+pattern.size()-1;
}
}
return result;
}
int make_hash(int x){//32位哈希函数
return x*2654435769;
}
bool hashEq(int x,int y){//判断x与y在当前条件下属不属于一个桶
return (x&mask[E])==(y&mask[E]);
}
//
int currentHash(int Hash){//当前哈希值
Hash=Hash&mask[E];
return Hash < N ? Hash : Hash&mask[E-1];
}
struct ListNode{//链表节点定义
int Hash;//32位哈希值,根据Key计算,通常为 hash(Key)
int Key;//键值,唯一
string Value;//键值Key对应的值
ListNode *next;//指向链表中的下一节点,或者为空
bool flag=false;//是否被查询过
//构造函数
ListNode(){}
ListNode(int H,int K,string V):Hash(H),Key(K),Value(V){}
};
struct List{//链表定义
ListNode *Head;//头指针
//构造函数 析构函数
List():Head(NULL){}
~List(){clear();}
//插入函数
void Insert(int H,int K,string V){
Insert(new ListNode(H,K,V));
}
void Insert(ListNode *temp){
temp->next=Head;
Head=temp;
}
//转移函数
void Transfer(int H,List *T){//将本链表中,Hash值掩码之后为H的元素加入到链表T中去。
ListNode *temp,*p;
while(Head && hashEq(Head->Hash,H)){
temp=Head;
Head=Head->next;
T->Insert(temp);
}
p=Head;
while(p&&p->next){
if(hashEq(p->next->Hash,H)){
temp=p->next;
p->next=p->next->next;
T->Insert(temp);
}
else p=p->next;
}
}
//寻找函数
string Find(int Key){
ERROR=false;
ListNode *temp=Head;
if(!temp)
{
return "sorry";
}
vector<string> value = split(temp->Value,", ");
while(temp){
if(temp->Key==Key&&temp->flag == false) {
temp->flag = true;
return temp->Value;
}
temp=temp->next;
}
return "sorry";
}
void Show(){
ListNode *temp=Head;
//cout <<"当前桶:"<<endl;
//cout << temp->Value<<endl;
while(temp){
cout <<temp->Value<<endl;
//vector<string> result = split(temp->Value,",");
temp=temp->next;
}
}
//释放申请空间
void clear(){
while(Head){
ListNode *temp=Head;
Head=Head->next;
delete temp;
}
}
}L[100000005];
//初始化
void Init(){
p2[0]=1;
for(int i=1;i<=32;++i) p2[i]=p2[i-1]<<1;
for(int i=0;i<=32;++i) mask[i]=p2[i]-1;
E=1;N=1;R=0;L[0]=List();
}
//调整
void Adjust(){
while((double)R/N > P){
//将属于N的信息加入List[N]
L[N&mask[E-1]].Transfer(N,&L[N]);
//更正 N 和 E
if(++N >= p2[E]) ++E;
L[N]=List();
}
}
//插入
void Insert(int Hash,int Key,string Value){
//插入元素
L[currentHash(Hash)].Insert(Hash,Key,Value);
++R;
//调整 N 和 E
Adjust();
}
//寻找
string Find(int Hash,int Key){
return L[currentHash(Hash)].Find(Key);
}
//释放所有
void FreeAll(){
for(int i=0;i<N;++i) L[i].clear();
}
//显示
void ShowList(){
//OUT3(E,R,N);
for(int i=0;i<N;++i){
//printf("%d:",i);
cout<<"桶"<< i <<":"<<endl;
L[i].Show();
// printf("\n");
}
}
int main(){
Init();
//Insert(hash(key),);
cout<<"查询1:查询借书证号是66的用户所有借书记录"<<endl;
//C++读取文件
ifstream infile;
infile.open("borrows.txt");
if(!infile) cout<<"error"<<endl;
vector<string> ve;
string line;//保存读入的每一行
while(getline(infile,line)) //按空格读取,遇到空白符结束
{
ve.push_back(line);
}
//cout << "共读入的记录条数:" << ve.size() << endl;
//按照借书证号整
cout<<"建立索引"<<endl;
clock_t start, endt;
start = clock();
for(int i=0;i<ve.size();i++) {
// 为文件建立索引
string this_line = ve[i];
//cout << "this line:"<< this_line<<endl;
vector<string> kkkey = split(ve[i],", ");
int key = atoi(kkkey[1].c_str());
int w = make_hash(key);
Insert(w,key,this_line);
}
endt = clock();
double use_time = (double)(endt - start) / CLOCKS_PER_SEC;
clock_t first,last;
cout << "--------------------------"<<endl;
//ShowList();
cout<<"借书证号是66的用户所有借书记录:"<<endl;
first = clock();
int query = make_hash(66);
string a;
do
{
a = Find(query,66);
if (a!="sorry")
{
cout << a <<endl;
}
} while (a!="sorry");
last = clock();
double custom_time = (double)(last - first) /CLOCKS_PER_SEC;
cout << "--------------------------"<<endl;
cout << "建立索引用的时间"<<use_time<<"秒"<<endl;
cout<<"查询用时"<<custom_time<<"秒"<<endl;
ve.clear();
infile.close();
FreeAll();
cout<<endl<<"查询2:查询出版社编号是77的所有图书"<<endl;
//C++读取文件
infile.open("books.txt");
if(!infile) cout<<"error"<<endl;
while(getline(infile,line)) //按空格读取,遇到空白符结束
{
ve.push_back(line);
}
//cout << "共读入的记录条数:" << ve.size() << endl;
//按照出版社整
cout<<"建立索引"<<endl;
start = clock();
for(int i=0;i<ve.size();i++) {
// 为文件建立索引
string this_line = ve[i];
//cout << "this line:"<< this_line<<endl;
vector<string> kkkey = split(ve[i],", ");
int key = atoi(kkkey[5].c_str());
int w = make_hash(key);
Insert(w,key,this_line);
}
endt = clock();
use_time = (double)(endt - start) / CLOCKS_PER_SEC;
//ShowList();
cout << "--------------------------"<<endl;
cout<<"出版社编号是77的所有图书:"<<endl;
first = clock();
query = make_hash(77);
do
{
a = Find(query,77);
if (a!="sorry")
{
cout << a <<endl;
}
} while (a!="sorry");
last = clock();
custom_time = (double)(last - first) /CLOCKS_PER_SEC;
cout << "--------------------------"<<endl;
cout << "建立索引用的时间"<<use_time<<"秒"<<endl;
cout<<"查询用时"<<custom_time<<"秒"<<endl;
ve.clear();
FreeAll();
infile.close();
cout<<endl<<"查询3:查询中国文学类别的图书共有多少本"<<endl;
//C++读取文件
infile.open("books.txt");
if(!infile) cout<<"error"<<endl;
while(getline(infile,line)) //按空格读取,遇到空白符结束
{
ve.push_back(line);
}
//为了减少tohex和getnum的时间 先把所有类型放在map
string typelist[6]={"中国文学", "外国文学", "计算机", "英语", "工具书", "儿童读物"};
map<string,int> type_int;
for(int i = 0;i<6;i++)
{
type_int[typelist[i]] = getnum(tohex(typelist[i]));
}
//按照出版社整
cout<<"建立索引"<<endl;
start = clock();
for(int i=0;i<ve.size();i++) {
// 为文件建立索引
string this_line = ve[i];
//cout << "this line:"<< this_line<<endl;
vector<string> kkkey = split(ve[i],", ");
int key = type_int[kkkey[4]];
int w = make_hash(key);
Insert(w,key,this_line);
}
endt = clock();
use_time = (double)(endt - start) / CLOCKS_PER_SEC;
//ShowList();
cout << "--------------------------"<<endl;
cout<<"中国文学类别的图书:"<<endl;
int total=0;
first = clock();
query = make_hash(type_int["中国文学"]);
do
{
a = Find(query,type_int["中国文学"]);
if (a!="sorry")
{
cout << a <<endl;
total++;
}
} while (a!="sorry");
last = clock();
custom_time = (double)(last - first) /CLOCKS_PER_SEC;
cout << "共"<<total <<"本"<<endl;
cout << "--------------------------"<<endl;
cout << "建立索引用的时间"<<use_time<<"秒"<<endl;
cout<<"查询用时"<<custom_time<<"秒"<<endl;
ve.clear();
FreeAll();
infile.close();
cout<<endl<<"查询4:查询在2019/06/15哪本书被借出最多"<<endl;
//C++读取文件
infile.open("borrows.txt");
if(!infile) cout<<"error"<<endl;
while(getline(infile,line)) //按空格读取,遇到空白符结束
{
ve.push_back(line);
}
//先把时间变成int 2019*365+m*30+days
//查询在这天借的书
cout<< "建立索引"<<endl;
start = clock();
for(int i=0;i<ve.size();i++) {
// 为文件建立索引
string this_line = ve[i];
//cout << "this line:"<< this_line<<endl;
vector<string> kkkey = split(ve[i],", ");
vector<string> days = split(kkkey[4],"/");
int long_time = stoi(days[0])*365 + (stoi(days[1])-1)*30 + stoi(days[2]);
int key = long_time;
int w = make_hash(key);
Insert(w,key,this_line);
}
endt = clock();
use_time = (double)(endt - start) / CLOCKS_PER_SEC;
//int keys = 736935+150+15; 2019/6/15 737100
//ShowList();
map<string,int> book_times;//存储了每本书借的数量
cout << "--------------------------"<<endl;
cout << "2019/06/15的所有借书记录"<<endl;
first = clock();
query = make_hash(737100);
do
{
a = Find(query,737100);
if (a!="sorry")
{
cout << a <<endl;
vector<string> result = split(a,", ");
//统计数量
map<string,int>::iterator iter = book_times.find(result[2]);
if(iter!=book_times.end())
{
int temp = iter->second;
temp += 1;
book_times[iter->first] = temp;
}
else
{
book_times[result[2]]=1;
}
}
} while (a!="sorry");
last = clock();
int maxt = 0;
string bookid;
//map<string,int>::iterator fin;
for(map<string,int>::iterator iter=book_times.begin(); iter!=book_times.end();iter++)
{
if(iter->second > maxt)
{
maxt = iter->second;
bookid = iter->first;
}
}
custom_time = (double)(last - first) /CLOCKS_PER_SEC;
cout <<"号码为"<<bookid<<"的书在该天被借次数最多,有"<<maxt<<"次。"<<endl;
cout << "--------------------------"<<endl;
cout << "建立索引用的时间"<<use_time<<"秒"<<endl;
cout<<"查询用时"<<custom_time<<"秒"<<endl;
ve.clear();
FreeAll();
infile.close();
//查询西游记的书的id放在vector中
//查询这天借的书id(result[2])在vector_西游记中的人id(result[1]) 放进vector_personid
//去user表建立索引 按照personid建立 查询电话号码OK
//string bookss[12]={"红楼梦", "三国演义", "西游记", "水浒传", "百年孤独", "悲惨世界", "数据库系统概念", "算法导论", "计算机网络", "研究生英语", "新华字典", "牛津英汉词典"};
//map<string, int > book_list;
// for (int i = 0;i<12;i++)
// {
// book_list[bookss[i]]=i;
// }
cout<<endl<<"查询5:查询在2019/08/23借了西游记的所有用户的电话"<<endl;
//查询有多少个西游记 把所有的ID放在xiyou_id中
infile.open("books.txt");
if(!infile) cout<<"error"<<endl;
while(getline(infile,line))
{
ve.push_back(line);
}
vector<string> xiyou_id; //存所有叫西游记的书的id
for(int i=0;i<ve.size();i++) {
string this_line = ve[i];
vector<string> kkkey = split(ve[i],", ");
if(kkkey[1]=="西游记")
{
xiyou_id.push_back(kkkey[0]);
}
}
ve.clear();
FreeAll();
infile.close();
//给索书号建索引
infile.open("borrows.txt");
if(!infile) cout<<"error"<<endl;
while(getline(infile,line)) //按空格读取,遇到空白符结束
{
ve.push_back(line);
}
//cout << "共读入的记录条数:" << ve.size() << endl;
//按照索书号建立索引
cout<<"建立索引"<<endl;
start = clock();
for(int i=0;i<ve.size();i++) {
// 为文件建立索引
string this_line = ve[i];
//cout << "this line:"<< this_line<<endl;
vector<string> kkkey = split(ve[i],", ");
int key = stoi(kkkey[2]);
int w = make_hash(key);
Insert(w,key,this_line);
}
endt = clock();
use_time = (double)(endt - start) / CLOCKS_PER_SEC;
//ShowList();
vector<string> borr_xiyou_id;
//查询每个西游记 并记录符合时间的记录id
cout << "--------------------------"<<endl;
cout << "所有借了西游记的借书记录:"<<endl;
first = clock();
for(int i=0; i<xiyou_id.size(); i++)
{
query = make_hash(stoi(xiyou_id[i]));
do
{
a = Find(query,stoi(xiyou_id[i]));
if (a!="sorry")
{
cout << a <<endl;
vector<string> tempp = split(a,", ");
if(tempp[4]=="2019/08/23")
borr_xiyou_id.push_back(tempp[1]);//borr_xiyou_id存的都是符合时间的借了西游记的人
}
} while (a!="sorry");
}
last = clock();
custom_time = (double)(last - first) /CLOCKS_PER_SEC;
ve.clear();
FreeAll();
infile.close();
//为user用id建立索引
//C++读取文件
infile.open("users.txt");
if(!infile) cout<<"error"<<endl;
while(getline(infile,line)) //按空格读取,遇到空白符结束
{
ve.push_back(line);
}
//cout << "共读入的记录条数:" << ve.size() << endl;
//给users建立索引
start = clock();
for(int i=0;i<ve.size();i++) {
// 为文件建立索引
string this_line = ve[i];
//cout << "this line:"<< this_line<<endl;
vector<string> kkkey = split(ve[i],", ");
int key = stoi(kkkey[0]);
int w = make_hash(key);
Insert(w,key,this_line);
}
endt = clock();
use_time += (double)(endt - start) / CLOCKS_PER_SEC; //两个索引的时间
cout<<"在2019/08/23借西游记的用户的信息:"<<endl;
//ShowList();
first = clock();
for(int i=0; i<borr_xiyou_id.size(); i++)
{
query = make_hash(stoi(borr_xiyou_id[i]));
do
{
a = Find(query,stoi(borr_xiyou_id[i]));
if (a!="sorry")
{
cout << a <<endl;
}
} while (a!="sorry");
}
last = clock();
cout << "--------------------------"<<endl;
custom_time += (double)(last - first) /CLOCKS_PER_SEC;
cout << "建立索引用的时间"<<use_time<<"秒"<<endl;
cout << "查询用时"<<custom_time<<"秒"<<endl;
ve.clear();
FreeAll();
infile.close();
}
|
/*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler (Cyril.Soler@imag.fr)
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - contact@libqglviewer.com
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#ifndef _VRENDER_PARSERGL_H
#define _VRENDER_PARSERGL_H
// This class implements the conversion from OpenGL feedback buffer into more
// usable data structures such as points, segments, and polygons (See Primitive.h)
#include <vector>
#include "Primitive.h"
namespace vrender
{
class ParserGL
{
public:
void parseFeedbackBuffer( GLfloat *,
int size,
std::vector<PtrPrimitive>& primitive_tab,
VRenderParams& vparams) ;
void printStats() const ;
inline GLfloat xmin() const { return _xmin ; }
inline GLfloat ymin() const { return _ymin ; }
inline GLfloat zmin() const { return _zmin ; }
inline GLfloat xmax() const { return _xmax ; }
inline GLfloat ymax() const { return _ymax ; }
inline GLfloat zmax() const { return _zmax ; }
private:
int nb_lines ;
int nb_polys ;
int nb_points ;
int nb_degenerated_lines ;
int nb_degenerated_polys ;
int nb_degenerated_points ;
GLfloat _xmin ;
GLfloat _ymin ;
GLfloat _zmin ;
GLfloat _xmax ;
GLfloat _ymax ;
GLfloat _zmax ;
};
}
#endif
|
/*Header file for cc_tic_tac_toe::game_node.*/
#ifndef __CC_TIC_TAC_TOE_GAME_NODE__
#define __CC_TIC_TAC_TOE_GAME_NODE__
#include "cc/tic_tac_toe/board.h"
#include <set>
namespace cc_tic_tac_toe {
class GameNode {
public:
GameNode();
~GameNode();
const Board& get_board() {
return board_;
}
void set_board(const Board& board);
void emit();
void debug_print();
void debug_print_level();
void add_child(GameNode* child_node);
void add_parent(GameNode* parent_node);
void compute_node_score();
bool get_current_player_can_prevent_loss() {
return current_player_can_prevent_loss_;
}
bool get_current_player_can_force_victory() {
return current_player_can_force_victory_;
}
bool is_terminal_node() {
return 0 == VSIZE(children_);
}
// Note that the actual board may be "equivalent" to the board_ field, but not
// necessarily equal to it.
Position get_position_for_best_move(const Board& actual_board);
private:
friend class GameNodeTest;
Board board_;
std::set<GameNode*> children_;
std::set<GameNode*> parents_;
bool current_player_can_prevent_loss_;
bool current_player_can_force_victory_;
DISALLOW_COPY_AND_ASSIGN(GameNode);
};
} // cc_tic_tac_toe
#endif // __CC_TIC_TAC_TOE_GAME_NODE__
|
#ifndef VECTOR2_HPP
#define VECTOR2_HPP
#include "Configuration.hpp"
#include "Math.hpp"
#include <iosfwd>
namespace mm
{
template <typename T = precision_t>
struct v2_t
{
T x;
T y;
T lengthSq() const;
T length() const;
T angle() const;
v2_t<T> normalize() const;
v2_t<T> rotate(T radians) const;
v2_t<T> rotateCW90() const;
v2_t<T> rotateCCW90() const;
T& operator[](u32 index);
const T& operator[](u32 index) const;
static_assert(std::is_same<T, f32>::value ||
std::is_same<T, f64>::value ||
std::is_same<T, s32>::value ||
std::is_same<T, s64>::value,
"Invalid template type for [v2_t]");
};
/// Operators implementation
template <typename T = precision_t>
static inline v2_t<T> operator+(v2_t<T> vec)
{
return {+vec.x, +vec.y};
}
template <typename T = precision_t>
static inline v2_t<T> operator+(v2_t<T> left, v2_t<T> right)
{
return {left.x + right.x, left.y + right.y};
}
template <typename T = precision_t>
static inline void operator+=(v2_t<T>& left, v2_t<T> right)
{
left.x += right.x;
left.y += right.y;
}
template <typename T = precision_t>
static inline v2_t<T> operator-(v2_t<T> vec)
{
return {-vec.x, -vec.y};
}
template <typename T = precision_t>
static inline v2_t<T> operator-(v2_t<T> left, v2_t<T> right)
{
return {left.x - right.x, left.y - right.y};
}
template <typename T = precision_t>
static inline void operator-=(v2_t<T>& left, v2_t<T> right)
{
left.x -= right.x;
left.y -= right.y;
}
template <typename T = precision_t>
static inline v2_t<T> operator*(v2_t<T> left, v2_t<T> right)
{
return {left.x * right.x, left.y * right.y};
}
template <typename T = precision_t>
static inline void operator*=(v2_t<T>& left, v2_t<T> right)
{
left.x *= right.x;
left.y *= right.y;
}
template <typename T = precision_t>
static inline v2_t<T> operator*(v2_t<T> left, T right)
{
return {left.x * right, left.y * right};
}
template <typename T = precision_t>
static inline v2_t<T> operator*(T left, v2_t<T> right)
{
return {left * right.x, left * right.y};
}
template <typename T = precision_t>
static inline void operator*=(v2_t<T>& left, T right)
{
left.x *= right;
left.y *= right;
}
template <typename T = precision_t>
static inline v2_t<T> operator/(v2_t<T> left, v2_t<T> right)
{
return {left.x / right.x, left.y / right.y};
}
template <typename T = precision_t>
static inline void operator/=(v2_t<T>& left, v2_t<T> right)
{
left.x /= right.x;
left.y /= right.y;
}
template <typename T = precision_t>
static inline v2_t<T> operator/(v2_t<T> left, T right)
{
return {left.x / right, left.y / right};
}
template <typename T = precision_t>
static inline void operator/=(v2_t<T>& left, T right)
{
left.x /= right;
left.y /= right;
}
/// Indexing operators
template <typename T>
inline T& v2_t<T>::operator[](u32 index)
{
assert(index < 2);
return (static_cast<T*>(this) + index);
}
template <typename T>
inline const T& v2_t<T>::operator[](u32 index) const
{
assert(index < 2);
return (static_cast<T*>(this) + index);
}
/// Comparison operators
template <typename T = precision_t>
static inline bool operator==(v2_t<T> left, v2_t<T> right)
{
return (left.x == right.x) && (left.y == right.y);
}
template <typename T = precision_t>
static inline bool operator!=(v2_t<T> left, v2_t<T> right)
{
return (left.x != right.x) || (left.y != right.y);
}
/// Stream operators
template <typename T = precision_t>
static inline std::ostream& operator<<(std::ostream& stream, v2_t<T> vec)
{
stream << '(' << vec.x << ',' << vec.y << ')';
return stream;
}
/// Member functions implementation
template<typename T = precision_t>
inline T v2_t<T>::lengthSq() const
{
return (x * x) + (y * y);
}
template <typename T = precision_t>
inline T v2_t<T>::length() const
{
return mm::sqrt((x * x) + (y * y));
}
template <typename T = precision_t>
inline T v2_t<T>::angle() const
{
return mm::atan2(y, x);
}
template<typename T = precision_t>
inline v2_t<T> v2_t<T>::normalize() const
{
return (*this) / length();
}
template <typename T = precision_t>
inline v2_t<T> v2_t<T>::rotate(T radians) const
{
auto sin = mm::sin(radians);
auto cos = mm::cos(radians);
return {x * cos - y * sin, x * sin + y * cos};
}
template <typename T = precision_t>
inline v2_t<T> v2_t<T>::rotateCW90() const
{
return {y, -x};
}
template <typename T = precision_t>
inline v2_t<T> v2_t<T>::rotateCCW90() const
{
return {-y, x};
}
/// Utility functions implementation
template <typename T = precision_t>
static inline T dot(v2_t<T> right, v2_t<T> left)
{
return (right.x * left.x) + (right.y * left.y);
}
template <typename T = precision_t>
static inline T distance(v2_t<T> right, v2_t<T> left)
{
return (right - left).length();
}
template <typename T = precision_t>
static inline v2_t<T> reflect(v2_t<T> vec, v2_t<T> normal)
{
return T(-2) * dot(vec, normal) * normal + vec;
}
template <typename T = precision_t>
static inline v2_t<T> clamp(v2_t<T> min, v2_t<T> max, v2_t<T> value)
{
return {clamp(min.x, max.x, value.x), clamp(min.y, max.y, value.y)};
}
}
// Export default precision type as [vec2]
using vec2 = mm::v2_t<precision_t>;
#endif // VECTOR2_HPP
|
// Copyright (c) 2019, tlblanc <tlblanc1490 at gmail dot com>
#ifndef VALUE_PARSER_H_
#define VALUE_PARSER_H_
#include <stddef.h>
#include <stdint.h>
#include <chrono>
#include <functional>
#include <string>
using ParseFunc = std::function<bool(const char *s,
size_t len,
size_t maxlen,
void *value)>;
struct Parser final {
public:
static const char kString[];
static const char kBool[];
static const char kInt32[];
static const char kInt64[];
static const char kUInt32[];
static const char kUInt64[];
static const char kDuration[];
static Parser string_parser(char *ptr) noexcept = delete;
static Parser string_parser(char *ptr, size_t len) noexcept;
static Parser string_parser(std::string *ptr) noexcept;
static Parser bool_parser(bool *ptr) noexcept;
static Parser int32_parser(int32_t *ptr) noexcept;
static Parser uint32_parser(uint32_t *ptr) noexcept;
static Parser int64_parser(int64_t *ptr) noexcept;
static Parser uint64_parser(uint64_t *ptr) noexcept;
static Parser duration_parser(std::chrono::nanoseconds *ptr) noexcept;
~Parser() = default;
Parser(void *value,
size_t len,
bool expects_arg,
ParseFunc parse_func) noexcept
: m_ptr(value),
m_len(len),
m_expects_arg(expects_arg),
m_parse_func(parse_func) { }
static void init(Parser *parser,
void *ptr,
size_t len,
bool expects_arg,
ParseFunc parse_func) noexcept {
parser->m_ptr = ptr;
parser->m_len = len;
parser->m_expects_arg = expects_arg;
parser->m_parse_func = parse_func;
}
bool set(const char *s, size_t size) noexcept {
return m_parse_func(s, size, m_len, m_ptr);
}
void *get() const noexcept {
return m_ptr;
}
bool expects_arg() const noexcept {
return m_expects_arg;
}
private:
void *m_ptr;
size_t m_len;
bool m_expects_arg;
ParseFunc m_parse_func;
};
bool parse_func_string(const char *s,
size_t len,
size_t maxlen,
void *value) noexcept;
bool parse_func_charray(const char *s,
size_t len,
size_t maxlen,
void *value) noexcept;
bool parse_func_bool(const char *s,
size_t len,
size_t maxlen,
void *value) noexcept;
bool parse_func_int32(const char *s,
size_t len,
size_t maxlen,
void *value) noexcept;
bool parse_func_int64(const char *s,
size_t len,
size_t maxlen,
void *value) noexcept;
bool parse_func_uint32(const char *s,
size_t len,
size_t maxlen,
void *value) noexcept;
bool parse_func_uint64(const char *s,
size_t len,
size_t maxlen,
void *value) noexcept;
bool parse_func_duration(const char *s,
size_t len,
size_t maxlen,
void *value) noexcept;
bool parse_string(char *value,
const char *s,
size_t len) noexcept = delete;
bool parse_string(std::string *value,
const char *s,
size_t len) noexcept;
bool parse_charray(char *value,
size_t maxlen,
const char *s,
size_t len) noexcept;
bool parse_bool(bool *value,
const char *s,
size_t len) noexcept;
bool parse_int32(int32_t *value,
const char *s,
size_t len) noexcept;
bool parse_int64(int64_t *value,
const char *s,
size_t len) noexcept;
bool parse_uint32(uint32_t *value,
const char *s,
size_t len) noexcept;
bool parse_uint64(uint64_t *value,
const char *s,
size_t len) noexcept;
bool parse_duration(std::chrono::nanoseconds *value,
const char *s,
size_t len) noexcept;
#endif // VALUE_PARSER_H_
|
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/epoll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <iostream>
#include <thread>
#include <msg_exception.hpp>
#include <worker.hpp>
#include <epoll_event_listener.hpp>
namespace event {
void epoll_event_listener::dispatcher(int fd) {
std::cout << "event to dispatch in thread " << std::this_thread::get_id() << "\n";
}
epoll_event_listener::epoll_event_listener(int maxevents) {
maxevents_ = maxevents;
keep_running_ = 1;
efd_ = epoll_create1(0);
if (efd_ == -1)
throw util::msg_exception(strerror(errno));
events_ = (struct epoll_event*) calloc(maxevents, sizeof(struct epoll_event));
}
void epoll_event_listener::add_listening_socket(int sfd) {
sfd_ = sfd;
register_event(EPOLLIN | EPOLLET, sfd_);
}
void epoll_event_listener::register_event(uint32_t events, int fd) {
event_.data.fd = fd;
event_.events = events;
epoll_ctl(efd_, EPOLL_CTL_ADD, fd, &event_);
}
void epoll_event_listener::shutdown() {
std::cout << "shutting down\n";
keep_running_ = 0;
}
void epoll_event_listener::listen() {
int n, i, newfd;
while (keep_running_ == 1) {
n = epoll_wait(efd_, events_, maxevents_, -1);
for (i=0; i<n; i++) {
if (events_[i].data.fd == sfd_) {
newfd = accept(sfd_, NULL, NULL);
register_event(EPOLLIN | EPOLLET, newfd);
std::cout << "event on listening socket at thread " << std::this_thread::get_id() << "\n";
} else {
dispatcher(events_[i].data.fd);
}
}
}
}
void epoll_event_listener::del_fd(int fd) {}
}
|
#include "RogueState.h"
RogueState::RogueState(const std::string& name, int health, int damage) : UnitState (name, health, health, damage) {}
RogueState::~RogueState() {}
|
#include <iostream>
#include <vector>
#include <sstream>
#include <cmath>
#include <algorithm>
using namespace std;
vector<size_t> it;
vector<vector<size_t>> ss;
size_t d, k, mod;
void dfs(size_t v, stringstream &res) {
while (it[v] < ss[v].size()) {
dfs(ss[v][it[v]++], res);
}
res << v % d;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin >> d >> k;
if (k == 1) {
for (size_t i = 0; i < d; i++)
cout << i;
return 0;
}
it = vector<size_t>((size_t) pow(d, k - 1));
mod = (size_t) pow(d, k - 1);
ss = vector<vector<size_t>>(mod);
for (size_t i = 0; i < mod * d; i++) {
ss[i / d].push_back(i % mod);
}
stringstream result;
for (size_t i = 0; i < k - 2; i++)
cout << 0;
dfs(0, result);
string str = result.str();
reverse(str.begin(), str.end());
cout << str;
return 0;
}
|
/*
* RotatingService.cpp
*
* Created on: 30/11/2019
* Author: frank
*/
#include "RotatingService.h"
RotatingService::RotatingService(MotorDc *motor) {
this->motorA = motor;
}
void RotatingService::motorTurnOn(){
this->motorA->setPortA(1);
this->motorA->setPortB(0);
this->motorA->setDutyCicle(this->motorA->getDutyCicle());
this->motorA->enableOperation();
}
void RotatingService::motorTurnOff(){
this->motorA->setPortA(0);
this->motorA->setPortB(0);
this->motorA->disableOperation();
this->motorA->setDutyCicle(0);
}
void RotatingService::motorPause(){
this->motorA->setPortA(0); // desligado pq o cooler nao freia.
this->motorA->setPortB(0);
}
|
#include<bits/stdc++.h>
using namespace std;
void kSortedArray(int input[],int n,int k){
priority_queue<int> pq;
for(int i=0;i<k;i++){ //Push first k elements into the priority queue.
pq.push(input[i]);
}
int j = 0; //Determines the element to this index.
for(int i=k;i<n;i++){
input[j] = pq.top();
pq.pop();
pq.push(input[i]);
j++;
} //After this for loop our n - k array is sorted.
while(!pq.empty()){
input[j] = pq.top();
pq.pop();
j++;
}
}
int main(){
int a[] = {12,15,7,4,9};
int k = 3;
kSortedArray(a,5,k);
for(int i=0;i<5;i++){
cout << a[i] << " ";
}
cout << endl;
return 0;
}
|
void GetNext(char* p,int next[])
{
int pLen = strlen(p);
next[0] = -1;
int k = -1;
int j = 0;
while (j < pLen - 1)
{
//p[k]表示前缀,p[j]表示后缀
if (k == -1 || p[j] == p[k])
{
++k;
++j;
next[j] = k;
}
else
{
k = next[k];
}
}
}
|
//===-- client/tcp-data-client.hh - TcpDataClient class ---------*- C++ -*-===//
//
// ODB Library
// Author: Steven Lariau
//
//===----------------------------------------------------------------------===//
///
/// \file
/// TcpDataClient class definition
///
//===----------------------------------------------------------------------===//
#pragma once
#include "abstract-data-client.hh"
#include <string>
namespace odb {
/// Send debugguer commands using TCP protocol
/// More infos about protocol in mess/tcp-transfer.hh
class TCPDataClient : public AbstractDataClient {
public:
TCPDataClient(const std::string &hostname, int port);
~TCPDataClient() override;
bool connect() override;
bool send_data(const SerialOutBuff &os) override;
bool recv_data(SerialInBuff &is) override;
private:
std::string _hostname;
int _port;
int _fd;
};
} // namespace odb
|
//使用するヘッダーファイル
#include "GameL\DrawFont.h"
#include "GameL\WinInputs.h"
#include "GameL\SceneManager.h"
#include "GameL\DrawTexture.h"
#include "SceneMain.h"
#include "GameHead.h"
#include "ObjED.h"
//使用するネームスペース
using namespace GameL;
//イニシャライズ
void CObjED::Init()
{
m_y = 0.0;
m_key_flag = true;
}
//アクション
void CObjED::Action()
{
}
//ドロー
void CObjED::Draw()
{
//描写カラー情報
float c[4] = { 1.0f,1.0f,1.0f,1.0f, };
float bl[4] = { 0.7f,0.7f,0.7f,1.0f };
RECT_F src;//描写元切り取り位置
RECT_F dst;//描写先表示位置
//切り取り位置の設定
src.m_top = 0.0f;
src.m_left = 0.0f;
src.m_right = 1600.0f;
src.m_bottom = 909.0f;
//表示位置の設定
dst.m_top = 0.0f;
dst.m_left = 0.0f;
dst.m_right = 1600.0f;
dst.m_bottom = 920.0f;
//0番目に登録したグラフィックをsrc・dst・cの情報を元に描写
Draw::Draw(3, &src, &dst, bl, 0.0f);
float p[4] = { 1,1,1,1 };
if (Input::GetVKey(VK_RETURN) == true)
{
m_y -= 3.0f;
}
else
{
m_y -= 0.6f;
}
Font::StrDraw(L"いくつもの苦難を乗り越え見事サメを倒したスターチェリーは、", GAME_CLEAR_X, GAME_CLEAR_Y + m_y + 400, GAME_CLEAR_FONT_SIZE, p);
Font::StrDraw(L"サメの口の中に乙姫様らしき影がある事を知り、", GAME_CLEAR_X, GAME_CLEAR_Y + m_y + 450, GAME_CLEAR_FONT_SIZE, p);
Font::StrDraw(L"サメの口の中から乙姫様を引きずり出しました。", GAME_CLEAR_X, GAME_CLEAR_Y + m_y + 500, GAME_CLEAR_FONT_SIZE, p);
Font::StrDraw(L"スターチェリーは安全な場所まで乙姫様を運び、", GAME_CLEAR_X, GAME_CLEAR_Y + m_y + 600, GAME_CLEAR_FONT_SIZE, p);
Font::StrDraw(L"竜宮城の外にスターチェリーは助けを呼びに行きました。", GAME_CLEAR_X, GAME_CLEAR_Y + m_y + 650, GAME_CLEAR_FONT_SIZE, p);
Font::StrDraw(L"その後乙姫様は、竜宮城の皆に助けられました。", GAME_CLEAR_X, GAME_CLEAR_Y + m_y + 700, GAME_CLEAR_FONT_SIZE, p);
Font::StrDraw(L"暴れていたサメが倒れたことで、", GAME_CLEAR_X, GAME_CLEAR_Y + m_y + 800, GAME_CLEAR_FONT_SIZE, p);
Font::StrDraw(L"竜宮城で操られていた魚たちが続々と意識を取り戻しました。", GAME_CLEAR_X, GAME_CLEAR_Y + m_y + 850, GAME_CLEAR_FONT_SIZE, p);
Font::StrDraw(L"スターチェリーはこの時以来、乙姫様を助けた英雄として、", GAME_CLEAR_X, GAME_CLEAR_Y + m_y + 950, GAME_CLEAR_FONT_SIZE, p);
Font::StrDraw(L"竜宮城に名が知れ渡るようになり、", GAME_CLEAR_X, GAME_CLEAR_Y + m_y + 1000, GAME_CLEAR_FONT_SIZE, p);
Font::StrDraw(L"乙姫様専属の付き人として竜宮城で暮らすようになりました。", GAME_CLEAR_X, GAME_CLEAR_Y + m_y + 1050, GAME_CLEAR_FONT_SIZE, p);
Font::StrDraw(L"END", GAME_CLEAR_X, GAME_CLEAR_Y + m_y + 1200, GAME_CLEAR_FONT_SIZE, p);
Font::StrDraw(L"※Enterキーでタイトルへ※", GAME_CLEAR_X, GAME_CLEAR_Y + m_y + 1300, GAME_CLEAR_FONT_SIZE, p);
if (Input::GetVKey(VK_RETURN) == true)
{
Scene::SetScene(new CSceneTitle());
}
}
|
/****************************************************************************
** Meta object code from reading C++ file 'CLoginDialog.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.3.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../CLoginDialog.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'CLoginDialog.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.3.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_CLoginDialog_t {
QByteArrayData data[12];
char stringdata[96];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_CLoginDialog_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_CLoginDialog_t qt_meta_stringdata_CLoginDialog = {
{
QT_MOC_LITERAL(0, 0, 12),
QT_MOC_LITERAL(1, 13, 5),
QT_MOC_LITERAL(2, 19, 0),
QT_MOC_LITERAL(3, 20, 2),
QT_MOC_LITERAL(4, 23, 11),
QT_MOC_LITERAL(5, 35, 13),
QT_MOC_LITERAL(6, 49, 8),
QT_MOC_LITERAL(7, 58, 6),
QT_MOC_LITERAL(8, 65, 4),
QT_MOC_LITERAL(9, 70, 8),
QT_MOC_LITERAL(10, 79, 5),
QT_MOC_LITERAL(11, 85, 10)
},
"CLoginDialog\0login\0\0id\0clientLogin\0"
"msgSendResult\0nMsghead\0result\0info\0"
"msgError\0error\0msgLoginIn"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_CLoginDialog[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
5, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 39, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
4, 0, 42, 2, 0x08 /* Private */,
5, 3, 43, 2, 0x08 /* Private */,
9, 2, 50, 2, 0x08 /* Private */,
11, 0, 55, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void, QMetaType::QString, 3,
// slots: parameters
QMetaType::Void,
QMetaType::Void, QMetaType::Int, QMetaType::Bool, QMetaType::QString, 6, 7, 8,
QMetaType::Void, QMetaType::Int, QMetaType::QString, 6, 10,
QMetaType::Void,
0 // eod
};
void CLoginDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
CLoginDialog *_t = static_cast<CLoginDialog *>(_o);
switch (_id) {
case 0: _t->login((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 1: _t->clientLogin(); break;
case 2: _t->msgSendResult((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2])),(*reinterpret_cast< const QString(*)>(_a[3]))); break;
case 3: _t->msgError((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break;
case 4: _t->msgLoginIn(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (CLoginDialog::*_t)(const QString & );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CLoginDialog::login)) {
*result = 0;
}
}
}
}
const QMetaObject CLoginDialog::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_CLoginDialog.data,
qt_meta_data_CLoginDialog, qt_static_metacall, 0, 0}
};
const QMetaObject *CLoginDialog::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *CLoginDialog::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_CLoginDialog.stringdata))
return static_cast<void*>(const_cast< CLoginDialog*>(this));
if (!strcmp(_clname, "Ui::CLoginDialog"))
return static_cast< Ui::CLoginDialog*>(const_cast< CLoginDialog*>(this));
return QDialog::qt_metacast(_clname);
}
int CLoginDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 5)
qt_static_metacall(this, _c, _id, _a);
_id -= 5;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 5)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 5;
}
return _id;
}
// SIGNAL 0
void CLoginDialog::login(const QString & _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
QT_END_MOC_NAMESPACE
|
/* -*- 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.
*
* @author Adam Minchinton
*/
#ifndef RESOURCE_FOLDERS_H
#define RESOURCE_FOLDERS_H
class OpDesktopResources;
namespace ResourceFolders
{
/**
* Sets all of the folders inside the OperaInitInfo structure
* before they are passed to the opera->Init call
*
* @param pinfo pointer to the opera init info
* @param desktop_resources pointer to the desktop resources; can be NULL
* @param profile_name pointer to profile folder to use instead of the
* standard "Opera" one
*
* @return OpStatus::OK if it deletes everything
*/
OP_STATUS SetFolders(OperaInitInfo *pinfo, OpDesktopResources* desktop_resources = NULL, const uni_char *profile_name = NULL);
/**
* Set region-based folders inside the OperaInitInfo structure.
*
* @param pinfo pointer to the opera init info
* @param region name of the region
* @param language name of language
* @param default_language name of the default language for the region
*
* @return OpStatus::OK on success, OpStatus::ERR_NO_MEMORY on error
*/
OP_STATUS SetRegionFolders(OperaInitInfo *pinfo, OpStringC region, OpStringC language, OpStringC default_language);
/**
* Gets a folder from an opfilefolder making sure to take into account
* any parent relationships. This needs to be used before opera->Init call
* before there is a g_folder_manager
*
* @param opfolder OpFolder to get
* @param pinfo pointer to the opera init info
* @param folder returns full path to the opfolder
*
* @return OpStatus::OK if it deletes everything
*/
OP_STATUS GetFolder(OpFileFolder opfilefolder, OperaInitInfo *pinfo, OpString &folder);
/**
* Compares 2 paths, ignoring any trailing slashes.
*
* @param path1 Full path of the file/folder to be checked
* @param path2 Full path of the file/folder to be checked
* @param identical On return, will be set to TRUE, if the paths point to the same file/folder. Undefined if the function returns an error.
*
* @return OpStatus::OK if the comparison succeeded (independent of the result of that comparison).
*/
OP_STATUS ComparePaths(const OpStringC &path1, const OpStringC &path2, BOOL &identical);
};
#endif // RESOURCE_FOLDERS_H
|
#include "stdafx.h"
#include "MapTool.h"
MapTool::MapTool()
{
}
MapTool::~MapTool()
{
}
|
#include <RHReliableDatagram.h>
#include <SPI.h>
#include <RH_RF69.h>
#if defined(__AVR_ATmega32U4__) // Feather 32u4 w/Radio
#define RFM69_CS 8
#define RFM69_INT 7
#define RFM69_RST 4
#define LED 13
#define radio() rf69(RFM69_CS, RFM69_INT)
#else
#define RFM69_RST 0
#define LED 13
#define radio() rf69
#endif
#define RF69_FREQ 915.0
#define CLIENT_ADDRESS 1
#define SERVER_ADDRESS 0
class RFM69 : private RH_RF69
{
public:
RFM69();
// function prototypes
void publishSensorReading();
void initRadio(void);
void sendMessage(char *message, uint8_t length);
void waitForMessage();
/**************************************************************
* Function: publishLogMsg
* ------------------------------------------------------------
* summary: sends log messages over serial
* parameters: string msg
* return: void
**************************************************************/
void publishLogMsg(String msg);
private:
/**************************************************************
* Function: blink
* ------------------------------------------------------------
* summary: Function fr configuring LED blinking
* parameters:
* byte PIN: The pin for the LED
* byte DELAY_MS: Delay between LED blinks
* byte loops: Number of led blinks
* return: void
**************************************************************/
void blink(byte PIN, byte DELAY_MS, byte loops);
};
|
#include<iostream>
using namespace std;
int main() {
int i,j,n;
int opc;
cout<<"Elija una opcion: 1.Linea, 2-Rectangulo, 3-Triangulo"<<endl;
cin>>opc;
switch (opc) {
case 1:
cout<<"Ingrese la longitud de la linea: "<<endl;
cin >> n;
for(i=1; i<=n; i++){
cout << "*";
}
cout << "" << endl;
break;
case 2:
int m;
cout<<"Ingrese la base del rectangulo: "<<endl;
cin>>m;
cout<<"Ingrese la altura del rectangulo: "<<endl;
cin>>n;
for(i=1; i<=n; i++){
for(j=1; j<=m; j++){
cout<<"*";
}
cout<<endl;
}
break;
case 3:
cout<<"Ingrese la base del triangulo: "<<endl;
cin>>n;
for(i=n; i>0; i--) {
for(j=0; j<i ; j++) {
cout<<"*";
}
cout<<endl;
}
break;
default:
cout << "Acción inválida" << endl;
}
return 0;
}
|
#include "Token.h"
Token::Token(std::string type, std::string val) : type(std::move(type)), val(std::move(val)) {}
const std::string &Token::getType() const {
return type;
}
void Token::setType(const std::string &type) {
this->type = type;
}
const std::string &Token::getVal() const {
return val;
}
void Token::setVal(const std::string &val) {
this->val = val;
}
|
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <fstream>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
struct Shape {
virtual std::string str() const = 0;
};
struct Circle : Shape {
float radius;
Circle() {}
Circle(float radius)
: radius(radius)
{}
std::string str() const override {
std::ostringstream oss;
oss << "a circle of radius " << radius;
return oss.str();
}
};
struct Square : Shape {
float side;
Square() {}
Square(float side) : side(side) {}
std::string str() const override {
std::ostringstream oss;
oss << "a square with side " << side;
return oss.str();
}
};
struct ColoredShape : Shape {
Shape &shape;
std::string color;
ColoredShape(Shape &shape, std::string const& color)
: shape(shape), color(color)
{}
std::string str() const override {
std::ostringstream oss;
oss << shape.str() << " has the color " << color;
return oss.str();
}
};
struct TransparentShape : Shape {
Shape &shape;
uint8_t transparency;
TransparentShape(Shape &shape, uint8_t transparency)
: shape(shape), transparency(transparency)
{}
std::string str() const override {
std::ostringstream oss;
oss << shape.str() << " has "
<< static_cast<float>(transparency) / 255.f * 100.f
<< "% transparency";
return oss.str();
}
};
// mixin inheritance
template<typename T>
struct ColoredShape2 : T {
static_assert(std::is_base_of<Shape, T>::value,
"template argument must be a Shape");
std::string color;
ColoredShape2() {}
//
template<typename ... Args>
ColoredShape2(std::string const& color, Args ... args)
: T(std::forward<Args>(args)...), color(color)
{}
std::string str() const override {
std::ostringstream oss;
oss << T::str() << " has the color " << color << std::endl;
return oss.str();
}
};
template<typename T>
struct TransparentShape2 : T {
uint8_t transparency;
TransparentShape2() {}
template<typename ... Args>
TransparentShape2(uint8_t const transparency, Args ... args)
: transparency{transparency}, T(std::forward<Args>(args)...)
{}
std::string str() const override {
std::ostringstream oss;
oss << T::str() << " has "
<< static_cast<float>(transparency) / 255.f * 100.f
<< "% transparency";
return oss.str();
}
};
int main() {
Square square{5};
ColoredShape red_square{square, "red"};
std::cout << square.str() << std::endl << red_square.str() << std::endl;
TransparentShape my_square {red_square, 51};
std::cout << my_square.str() << std::endl;
ColoredShape2<Circle> green_circle {"green", 5};
std::cout << green_circle.str() << std::endl;
TransparentShape2<ColoredShape2<Square>> square_tmp{51, "blue", 10};
std::cout << square_tmp.str() << std::endl;
return 0;
}
|
// Copyright (c) 2016 Agustin Berge
//
// SPDX-License-Identifier: BSL-1.0
// 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 <pika/config.hpp>
#include <pika/iterator_support/traits/is_range.hpp>
#include <pika/testing.hpp>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
void array_range()
{
using range = int[3];
PIKA_TEST_MSG((pika::traits::is_range<range>::value == true), "array");
PIKA_TEST_MSG((pika::traits::is_range<range const>::value == true), "array-const");
}
///////////////////////////////////////////////////////////////////////////////
struct member
{
int x;
int* begin() { return &x; }
int const* begin() const { return &x; }
int* end() { return &x + 1; }
int const* end() const { return &x + 1; }
};
void member_range()
{
using range = member;
PIKA_TEST_MSG((pika::traits::is_range<range>::value == true), "member-const");
PIKA_TEST_MSG((pika::traits::is_range<range const>::value == true), "member-const");
}
///////////////////////////////////////////////////////////////////////////////
namespace adl {
struct free
{
int x;
};
int* begin(free& r) { return &r.x; }
int const* begin(free const& r) { return &r.x; }
int* end(free& r) { return &r.x + 1; }
int const* end(free const& r) { return &r.x + 1; }
} // namespace adl
void adl_range()
{
using range = adl::free;
PIKA_TEST_MSG((pika::traits::is_range<range>::value == true), "adl-const");
PIKA_TEST_MSG((pika::traits::is_range<range const>::value == true), "adl-const");
}
///////////////////////////////////////////////////////////////////////////////
void vector_range()
{
using range = std::vector<int>;
PIKA_TEST_MSG((pika::traits::is_range<range>::value == true), "vector");
PIKA_TEST_MSG((pika::traits::is_range<range const>::value == true), "vector-const");
}
///////////////////////////////////////////////////////////////////////////////
int main()
{
{
array_range();
member_range();
adl_range();
vector_range();
}
return 0;
}
|
#include "VnaSweepTest.h"
// RsaToolbox
#include "Test.h"
using namespace RsaToolbox;
// Qt
#include <QTest>
VnaSweepTest::VnaSweepTest(QObject *parent) :
VnaTestClass(parent)
{
}
VnaSweepTest::VnaSweepTest(RsaToolbox::ConnectionType type, const QString &address, QObject *parent) :
VnaTestClass(type, address, parent)
{
}
VnaSweepTest::~VnaSweepTest()
{
}
// Setup
void VnaSweepTest::initTestCase() {
QString path;
path = "%1/VnaSweepTest/%2/Logs";
path = path.arg(SOURCE_DIR);
if (isZvaFamily())
path = path.arg("ZVA");
else if (isZnbFamily())
path = path.arg("ZNB");
else
path = path.arg("UNKNOWN");
_logDir.setPath(path);
_logFilenames << "1 - Basic Sweep Test.txt";
_initTestCase();
}
void VnaSweepTest::init() {
// Connect, preset:
// Ch1, Trc1, diagram 1
_init();
// Ch2, Trc2
_vna->createChannel(2);
_vna->createTrace("Trc2", 2);
_vna->trace("Trc2").setDiagram(1);
// Ch3, Trc3
_vna->createChannel(3);
_vna->createTrace("Trc3", 3);
_vna->trace("Trc3").setDiagram(1);
// Ch4, Trc4
_vna->createChannel(4);
_vna->createTrace("Trc4", 4);
_vna->trace("Trc4").setDiagram(1);
}
// Tests
void VnaSweepTest::basic() {
_vna->manualSweepOn();
_vna->pause();
rememberData();
QTest::qSleep(250 /*ms*/);
QVERIFY(isNoNewData());
_vna->channel(2).startSweep();
_vna->pause();
QVERIFY(isNewDataOnlyInChannel(2));
rememberData();
_vna->continuousSweepOn();
QTest::qSleep(250 /*ms*/);
QVERIFY(isAllNewData());
rememberData();
QTest::qSleep(250 /*ms*/);
QVERIFY(isAllNewData());
_vna->manualSweepOn();
_vna->pause();
rememberData();
QTest::qSleep(250 /*ms*/);
QVERIFY(isNoNewData());
_vna->startSweeps();
_vna->pause();
QVERIFY(isAllNewData());
rememberData();
QTest::qSleep(250 /*ms*/);
QVERIFY(isNoNewData());
if (!_vna->properties().isZvaFamily()) {
_vna->channel(2).continuousSweepOn();
QTest::qSleep(250 /*ms*/);
QVERIFY(isNewDataOnlyInChannel(2));
rememberData();
QTest::qSleep(250 /*ms*/);
QVERIFY(isNewDataOnlyInChannel(2));
}
QVERIFY(!_vna->isError());
}
QList<ComplexRowVector> VnaSweepTest::retrieveData() {
QList<ComplexRowVector> newData;
newData << _vna->trace("Trc1").y();
newData << _vna->trace("Trc2").y();
newData << _vna->trace("Trc3").y();
newData << _vna->trace("Trc4").y();
return newData;
}
void VnaSweepTest::rememberData() {
_data = retrieveData();
}
bool VnaSweepTest::isNewDataOnlyInChannel(uint channel) {
QList<ComplexRowVector> newData = retrieveData();
QList<uint> channels;
channels << 1 << 2 << 3 << 4;
foreach(const uint c, channels) {
const int i = c - 1;
if (c == channel) {
// Should be new
if (newData[i] == _data[i])
return false;
}
else {
// Should be same
if (newData[i] != _data[i])
return false;
}
}
return true;
}
bool VnaSweepTest::isAllNewData() {
QList<ComplexRowVector> newData = retrieveData();
QList<uint> channels;
channels << 1 << 2 << 3 << 4;
foreach(const uint c, channels) {
const uint i = c - 1;
// Should be new
if (newData[i] == _data[i])
return false;
}
return true;
}
bool VnaSweepTest::isNoNewData() {
QList<ComplexRowVector> newData = retrieveData();
QList<uint> channels;
channels << 1 << 2 << 3 << 4;
foreach(const uint c, channels) {
const uint i = c - 1;
// Should be same
if (newData[i] != _data[i])
return false;
}
return true;
}
|
//
// Created by Vladimir on 3/30/2020.
//
#ifndef COP_3530__ALGORITHMS__TREE_H
#define COP_3530__ALGORITHMS__TREE_H
// Class declarations go here, and is implemented in the .cpp file
class tree {
};
#endif //COP_3530__ALGORITHMS__TREE_H
|
#include <iostream>
#include <vector>
int main() {
std::vector<char> text;
std::vector<char> newText;
char buffer;
std::cout << "enter your text, for stop ener 0" << std::endl;
do {
std::cin >> buffer;
text.insert(text.end(), buffer);
} while ('0' != buffer);
unsigned int size = text.size();
for (int i = 0; i < size; ++i) {
if('A' < text[i] || 'z' < text[i]) {
newText.insert(newText.end(), text[i]);
}
}
for (int i = 0; i < newText.size(); ++i) {
std::cout << newText[i];
}
std::cout << std::endl;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) Opera Software ASA 1999-2005
*
* Library for standalone builds of the HTML5 parser.
* NOTE! Some parts are specific to MS Windows.
*/
#include "core/pch.h"
#include "modules/util/uniprntf.h"
#include "modules/util/adt/bytebuffer.h"
#include "modules/logdoc/src/html5/standalone/standalone.h"
#include <stdio.h>
#include <sys/types.h>
#ifndef OP_ASSERT
void OP_ASSERT( int x )
{
if (!x)
{
assert(x);
}
}
#endif
void *operator new(size_t size, TLeave)
{
void *p = ::operator new(size);
if (p == NULL)
LEAVE(OpStatus::ERR_NO_MEMORY);
return p;
}
#if defined USE_CXX_EXCEPTIONS && defined _DEBUG
void operator delete( void *loc, TLeave ) { /* just to shut up the compiler */ }
#endif
#ifndef MSWIN
#include <new>
void *operator new[](size_t size, TLeave)
{
void *p = ::operator new[](size, std::nothrow);
if (p == NULL)
LEAVE(OpStatus::ERR_NO_MEMORY);
return p;
}
#endif
#ifndef NOT_A_CHARACTER
# define NOT_A_CHARACTER 0xFFFD
#endif // NOT_A_CHARACTER
OP_STATUS UniSetStrN(uni_char* &str, const uni_char* val, int len)
{
uni_char *new_str = NULL;
if (val)
{
new_str = OP_NEWA(uni_char, len + 1);
if (!new_str)
return OpStatus::ERR_NO_MEMORY;
uni_strncpy(new_str, val, len);
new_str[len] = 0;
}
else
OP_DELETEA(str);
str = new_str;
return OpStatus::OK;
}
void*
OperaModule::operator new(size_t nbytes, OperaModule* m)
{
return m;
}
void
Opera::InitL()
{
OperaInitInfo x;
#ifdef STDLIB_MODULE_REQUIRED
new (&stdlib_module) StdlibModule();
stdlib_module.InitL(x);
#endif
}
void
Opera::Destroy()
{
#ifdef STDLIB_MODULE_REQUIRED
stdlib_module.Destroy();
#endif
}
Opera::~Opera()
{
Destroy();
}
/** Convert Unicode encoded as UTF-8 to UTF-16 */
class Ragnarok_UTF8toUTF16Converter
{
public:
Ragnarok_UTF8toUTF16Converter();
int Convert(const void *src, int len, void *dest, int maxlen, int *read);
private:
int m_charSplit; ///< Bytes left in UTF8 character, -1 if in ASCII
int m_sequence; ///< Type of current UTF8 sequence (total length - 2)
UINT32 m_ucs; ///< Current ucs character being decoded
UINT16 m_surrogate; ///< Surrogate left to insert in next iteration
};
Ragnarok_UTF8toUTF16Converter::Ragnarok_UTF8toUTF16Converter()
: m_charSplit(-1), m_surrogate(0)
{
}
#ifdef DEBUG_ENABLE_SYSTEM_OUTPUT
# if defined WIN32
# define WRITE_OUT(buf, count) fwrite(buf, sizeof(char), count, stdout)
# elif defined UNIX
# define WRITE_OUT(buf, count) write(1, buf, count)
# endif // WIN32/UNIX
extern "C"
void dbg_systemoutput(const uni_char* str)
{
unsigned char buffer[2048]; /* ARRAY OK 2011-09-08 danielsp */
Ragnarok_UTF16toUTF8Converter conv;
int read = 0;
int input_size = uni_strlen(str) * sizeof(uni_char);
for (; input_size > 0; input_size -= read, str += read / sizeof(uni_char))
{
int length = conv.Convert(str, input_size, buffer, 2048, &read);
WRITE_OUT(buffer, length);
}
}
extern char* g_logfilename;
#define DEBUG_LOGFILE_BUFFER_SIZE 8192
extern "C"
void dbg_logfileoutput(const char* str, int len)
{
/*
static int fd = -1;
static int buffer_size = 0;
static char buffer[DEBUG_LOGFILE_BUFFER_SIZE + 100]; // ARRAY OK 2008-05-13 mortenro
// Open logfile for writing if needed (and possible)
if ( fd < 0 && g_logfilename != 0 )
fd = open(g_logfilename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
// Append to the buffer during startup and for small strings
if ( len < 128 || fd < 0 )
{
if ( buffer_size + len < DEBUG_LOGFILE_BUFFER_SIZE )
{
op_memcpy(buffer + buffer_size, str, len);
buffer_size += len;
len = 0;
}
else if ( fd < 0 && buffer_size < DEBUG_LOGFILE_BUFFER_SIZE )
{
// Oops, buffer overflowed during startup - give warning
const char* w = "\nWARNING: Parts of initial log was dropped\n";
int ws = op_strlen(w);
op_memcpy(buffer + buffer_size, w, ws);
buffer_size += ws;
}
}
// Flush buffer for each new line, or when needed for large data
if ( fd >= 0 )
{
if ( buffer_size > 0 && (buffer[buffer_size - 1] == '\n' || len > 0) )
{
write(fd, buffer, buffer_size);
buffer_size = 0;
}
if ( len > 0 )
write(fd, str, len);
}
*/
}
#endif // DEBUG_ENABLE_SYSTEM_OUTPUT
#define IS_SURROGATE(x) ((x & 0xF800) == 0xD800)
#ifndef NOT_A_CHARACTER
# define NOT_A_CHARACTER 0xFFFD
#endif // NOT_A_CHARACTER
static inline void
MakeSurrogate(UINT32 ucs, uni_char &high, uni_char &low)
{
OP_ASSERT(ucs >= 0x10000UL && ucs <= 0x10FFFFUL);
// Surrogates spread out the bits of the UCS value shifted down by 0x10000
ucs -= 0x10000;
high = 0xD800 | uni_char(ucs >> 10); // 0xD800 -- 0xDBFF
low = 0xDC00 | uni_char(ucs & 0x03FF); // 0xDC00 -- 0xDFFF
}
int
Ragnarok_UTF8toUTF16Converter::Convert(const void *src, int len, void *dest, int maxlen, int *read_ext)
{
register const unsigned char *input = reinterpret_cast<const unsigned char *>(src);
const unsigned char *input_start = input;
const unsigned char *input_end = input_start + len;
maxlen &= ~1; // Make sure destination size is always even
if (!maxlen)
{
if (read_ext) *read_ext = 0;
return 0;
}
register uni_char *output = reinterpret_cast<uni_char *>(dest);
uni_char *output_start = output;
uni_char *output_end =
reinterpret_cast<uni_char *>(reinterpret_cast<char *>(dest) + maxlen);
/** Length of UTF-8 sequences for initial byte */
static const UINT8 utf8_len[256] =
{
/* 00-0F */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
/* 10-1F */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
/* 20-2F */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
/* 30-3F */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
/* 40-4F */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
/* 50-5F */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
/* 60-6F */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
/* 70-7F */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
/* 80-8F */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // tail
/* 90-9F */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // tail
/* A0-AF */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // tail
/* B0-BF */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // tail
/* C0-CF */ 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
/* D0-DF */ 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
/* E0-EF */ 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
/* F0-FF */ 4,4,4,4,4,4,4,4,5,5,5,5,6,6,0,0,
};
/** Bit masks for first UTF-8 byte */
static const UINT8 utf8_mask[5] =
{
0x1F, 0x0F, 0x07, 0x03, 0x01
};
/** Low boundary of UTF-8 sequences */
static const UINT32 low_boundary[5] =
{
0x80, 0x800, 0x10000, 0x200000, 0x4000000
};
int written = 0;
if (m_surrogate)
{
if (output)
{
*(output ++) = m_surrogate;
}
else
{
written = sizeof (uni_char);
}
m_surrogate = 0;
}
// Work on the input buffer one byte at a time, and output when
// we have a completed Unicode character
if (output)
{
// Decode the UTF-8 string; duplicates code below, decoupling
// them is a speed optimization.
while (input < input_end && output < output_end)
{
register unsigned char current = *input;
// Check if we are in the middle of an escape (this works
// across buffers)
if (m_charSplit >= 0)
{
if (m_charSplit > 0 && (current & 0xC0) == 0x80)
{
// If current is 10xxxxxx, we continue to shift bits.
m_ucs <<= 6;
m_ucs |= current & 0x3F;
++ input;
-- m_charSplit;
}
else if (m_charSplit > 0)
{
// If current is not 10xxxxxx and we expected more input,
// this is an illegal character, so we trash it and continue.
*(output ++) = NOT_A_CHARACTER;
m_charSplit = -1;
}
if (0 == m_charSplit)
{
// We are finished. We do not consume any more characters
// until next iteration.
if (m_ucs < low_boundary[m_sequence] || IS_SURROGATE(m_ucs))
{
// Overlong UTF-8 sequences and surrogates are ill-formed,
// and must not be interpreted as valid characters
*output = NOT_A_CHARACTER;
}
else if (m_ucs >= 0x10000 && m_ucs <= 0x10FFFF)
{
// UTF-16 supports this non-BMP range using surrogates
uni_char high, low;
MakeSurrogate(m_ucs, high, low);
*(output ++) = high;
if (output == output_end)
{
m_surrogate = low;
m_charSplit = -1;
written = (output - output_start) * sizeof (uni_char);
if (read_ext) *read_ext = input - input_start;
return written;
}
*output = low;
}
else if (m_ucs >> (sizeof(uni_char) * 8))
{
// Non-representable character
*output = NOT_A_CHARACTER;
}
else
{
*output = static_cast<uni_char>(m_ucs);
}
++ output;
-- m_charSplit; // = -1
}
}
else
{
switch (utf8_len[current])
{
case 1:
// This is a US-ASCII character
*(output ++) = static_cast<uni_char>(*input);
written += sizeof (uni_char);
break;
// UTF-8 escapes all have high-bit set
case 2: // 110xxxxx 10xxxxxx
case 3: // 1110xxxx 10xxxxxx 10xxxxxx
case 4: // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx (outside BMP)
case 5: // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx (outside Unicode)
case 6: // 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx (outside Unicode)
m_charSplit = utf8_len[current] - 1;
m_sequence = m_charSplit - 1;
m_ucs = current & utf8_mask[m_sequence];
break;
case 0: // Illegal UTF-8
*(output ++) = NOT_A_CHARACTER;
break;
}
++ input;
}
}
// Calculate number of bytes written
written = (output - output_start) * sizeof (uni_char);
}
else
{
// Just count the number of bytes needed; duplicates code above,
// decoupling them is a speed optimization.
while (input < input_end && written < maxlen)
{
register unsigned char current = *input;
// Check if we are in the middle of an escape (this works
// across buffers)
if (m_charSplit >= 0)
{
if (m_charSplit > 0 && (current & 0xC0) == 0x80)
{
// If current is 10xxxxxx, we continue to shift bits.
++ input;
-- m_charSplit;
}
else if (m_charSplit > 0)
{
// If current is not 10xxxxxx and we expected more input,
// this is an illegal character, so we trash it and continue.
m_charSplit = -1;
}
if (0 == m_charSplit)
{
// We are finished. We do not consume any more characters
// until next iteration.
if (low_boundary[m_sequence] > 0xFFFF)
{
// Surrogate
// Overestimates ill-formed characters
written += 2 * sizeof (uni_char);
}
else
{
written += sizeof (uni_char);
}
-- m_charSplit; // = -1
}
}
else
{
switch (utf8_len[current])
{
case 1:
// This is a US-ASCII character
written += sizeof (uni_char);
break;
// UTF-8 escapes all have high-bit set
case 2: // 110xxxxx 10xxxxxx
case 3: // 1110xxxx 10xxxxxx 10xxxxxx
case 4: // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx (outside BMP)
case 5: // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx (outside Unicode)
case 6: // 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx (outside Unicode)
m_charSplit = utf8_len[current] - 1;
m_sequence = m_charSplit - 1;
break;
case 0: // Illegal UTF-8
written += sizeof (uni_char);
break;
}
++ input;
}
}
}
if (read_ext) *read_ext = input - input_start;
return written;
}
int Ragnarok_UTF16toUTF8Converter::Convert(const void *src, unsigned len, void *dest,
int maxlen, int *read_ext)
{
int read,written;
const uni_char *source = reinterpret_cast<const uni_char *>(src);
char *output = reinterpret_cast<char *>(dest);
len &= ~1; // Make sure source size is always even
for (read = 0, written = 0; read * sizeof(uni_char) < len && written < maxlen; read ++)
{
if (m_surrogate || Unicode::IsLowSurrogate(*source))
{
if (m_surrogate && Unicode::IsLowSurrogate(*source))
{
if (written + 4 > maxlen)
break;
// Second half of a surrogate
// Calculate UCS-4 character
UINT32 ucs4char = Unicode::DecodeSurrogate(m_surrogate, *source);
// U+10000 - U+10FFFF
written += 4;
(*output++) = static_cast<char>(0xF0 | ((ucs4char & 0x1C0000) >> 18));
(*output++) = static_cast<char>(0x80 | ((ucs4char & 0x3F000) >> 12));
(*output++) = static_cast<char>(0x80 | ((ucs4char & 0xFC0) >> 6));
(*output++) = static_cast<char>(0x80 | (ucs4char & 0x3F) );
}
else
{
// Either we have a high surrogate without a low surrogate,
// or a low surrogate on its own. Anyway this is an illegal
// UTF-16 sequence.
if (written + 3 > maxlen)
break;
written += 3;
(*output++) = static_cast<char>(static_cast<unsigned char>(0xEF)); // U+FFFD - replacement character
(*output++) = static_cast<char>(static_cast<unsigned char>(0xBF));
(*output++) = static_cast<char>(static_cast<unsigned char>(0xBD));
}
m_surrogate = 0;
}
else if (*source < 128)
{
(*output++) = static_cast<char>(*source);
written ++;
}
else if (*source < 2048)
{
if (written + 2 > maxlen)
break;
written += 2;
(*output++) = static_cast<char>(0xC0 | ((*source & 0x07C0) >> 6));
(*output++) = static_cast<char>(0x80 | (*source & 0x003F));
}
else if (Unicode::IsHighSurrogate(*source))
{
// High surrogate area, should be followed by a low surrogate
m_surrogate = *source;
}
else
{ // up to U+FFFF
if (written + 3 > maxlen)
break;
written += 3;
(*output++) = static_cast<char>(0xE0 | ((*source & 0xF000) >> 12));
(*output++) = static_cast<char>(0x80 | ((*source & 0x0FC0) >> 6));
(*output++) = static_cast<char>(0x80 | (*source & 0x003F));
}
source++;
}
*read_ext = read * sizeof(uni_char);
m_num_converted += read;
return written;
}
OP_STATUS
read_stdin(ByteBuffer &bbuf)
{
char buf[2048]; /* ARRAY OK 2011-09-08 danielsp */
uni_char buf16[2048]; /* ARRAY OK 2011-09-08 danielsp */
bbuf.Clear();
Ragnarok_UTF8toUTF16Converter conv;
int l = 0, r;
for (;;)
{
int k = fread(buf + l, 1, sizeof(buf) - l, stdin);
if (k <= 0) break;
l += k;
int w = conv.Convert(buf, l, buf16, sizeof buf16, &r);
if (r != l)
op_memmove(buf, buf + r, l - r);
l -= r;
#if 0
// Replace NULs with 0xDFFF which are handled the same later, as tempbuffer doesn't handle NULs
for (uni_char* c = buf16; c < buf16 + w / sizeof(uni_char); c++)
if (*c == 0)
*c = 0xDFFF;
#endif // 0
if (OpStatus::IsError(bbuf.AppendBytes(reinterpret_cast<const char*>(buf16), w)))
return OpStatus::ERR_NO_MEMORY;
}
bbuf.Append2(0); // terminate string
return OpStatus::OK;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2007-2012 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#ifdef SCOPE_SUPPORT
#include "modules/scope/src/scope_manager.h"
#include "modules/scope/src/scope_service.h"
#include "modules/scope/src/scope_network.h"
#include "modules/scope/src/scope_tp_message.h"
#include "modules/scope/src/scope_transport.h"
#include "modules/protobuf/src/protobuf_message.h"
#include "modules/scope/src/scope_default_message.h"
#include "modules/scope/src/scope_network.h"
#include "modules/xmlutils/xmlfragment.h"
/* OpScopeService */
/* Error messages */
/*static*/
const uni_char *
OpScopeService::GetInvalidStatusFieldText()
{
return UNI_L("Status field must not be set for calls");
}
/*static*/
const uni_char *
OpScopeService::GetIncorrectServiceText()
{
return UNI_L("Message was sent to incorrect service");
}
/*static*/
const uni_char *
OpScopeService::GetCommandNotFoundText()
{
return UNI_L("The command ID was not found");
}
/*static*/
const uni_char *
OpScopeService::GetInitAsyncCommandFailedText()
{
return UNI_L("Async command could not be initialized");
}
/*static*/
const uni_char *
OpScopeService::GetParseCommandMessageFailedText()
{
return UNI_L("Unknown error while parsing command message");
}
/*static*/
const uni_char *
OpScopeService::GetCommandExecutionFailedText()
{
return UNI_L("Unknown error while executing command");
}
/*static*/
const uni_char *
OpScopeService::GetCommandResponseFailedText()
{
return UNI_L("Unknown error while sending response");
}
/* Code */
OpScopeService::OpScopeService(const uni_char* name, OpScopeServiceManager *service_manager, ControlType control)
: name(name)
, manager(NULL)
, is_enabled(control == CONTROL_MANUAL ? FALSE : TRUE)
, client(NULL)
, is_response_sent(FALSE)
, control(control)
{
if (service_manager)
service_manager->RegisterService(this);
}
OpScopeService::~OpScopeService()
{
async_commands.Clear();
if (GetManager())
GetManager()->UnregisterService(this);
if (GetControlType() == CONTROL_MANUAL && IsEnabled())
OpStatus::Ignore(Disable());
}
/* virtual */
OP_STATUS
OpScopeService::OnPostInitialization()
{
return OpStatus::OK;
}
/* virtual */
OP_STATUS
OpScopeService::OnServiceEnabled()
{
return OpStatus::OK;
}
/* virtual */
OP_STATUS
OpScopeService::OnServiceDisabled()
{
return OpStatus::OK;
}
OP_STATUS
OpScopeService::Enable()
{
OP_ASSERT(!IsEnabled());
// Special case for always-enabled services
if (GetControlType() == CONTROL_FORCED)
return OpStatus::OK;
if (IsEnabled())
return OpStatus::ERR;
SetIsEnabled(TRUE);
async_commands.Clear(); // Remove any active async commands
if (OpStatus::IsError(OnServiceEnabled()))
{
SetIsEnabled(FALSE);
return OpStatus::ERR;
}
return OpStatus::OK;
}
OP_STATUS
OpScopeService::Disable()
{
OP_ASSERT(IsEnabled());
// Special case for always-enabled services
if (GetControlType() == CONTROL_FORCED)
return OpStatus::OK;
if (!IsEnabled())
return OpStatus::ERR;
SetIsEnabled(FALSE);
async_commands.Clear(); // Remove any active async commands
return OnServiceDisabled();
}
/* virtual */
OP_STATUS
OpScopeService::OnReceive( OpScopeClient *client, const OpScopeTPMessage &msg )
{
OP_ASSERT(this->client == client);
is_response_sent = FALSE;
RETURN_IF_ERROR(current_command.Copy(msg));
command_error.SetStatus(OpScopeTPHeader::OK);
OP_STATUS status = DoReceive(client, msg);
is_response_sent = FALSE;
OpScopeTPHeader tmp_header;
RETURN_IF_ERROR(current_command.Copy(tmp_header));
// Check if the command or any sub-calls sets a command error, if so send this to the client
// If response is already sent we cannot report any kind of error
// TODO: Perhaps use the scope.OnError event for this?
if (command_error.GetStatus() != OpScopeTPHeader::OK && !IsResponseSent())
{
RETURN_IF_ERROR(SendError(client, msg, command_error));
return OpStatus::OK;
}
return status;
}
OP_STATUS
OpScopeService::SetCommandError(OpScopeTPHeader::MessageStatus status, const uni_char *description, int line, int col, int offset)
{
OP_ASSERT(status != OpScopeTPHeader::OK);
OpScopeTPError temp(status, description, line, col, offset);
RETURN_IF_ERROR(command_error.Copy(temp));
return OpStatus::ERR;
}
OP_STATUS
OpScopeService::SetCommandError(const OpScopeTPError &error)
{
OP_ASSERT(error.GetStatus() != OpScopeTPHeader::OK);
RETURN_IF_ERROR(command_error.Copy(error));
return OpStatus::ERR;
}
OP_STATUS
OpScopeService::ReportCommandStatus(OP_STATUS status)
{
OP_ASSERT(OpStatus::IsError(status));
OpScopeTPError error;
error.SetStatus(OpScopeTPMessage::InternalError);
if (OpStatus::IsMemoryError(status))
{
error.SetStatus(OpScopeTPMessage::OutOfMemory);
error.SetStaticDescription(UNI_L("Service encountered OOM while decoding incoming request"));
}
else if (status == OpStatus::ERR_NO_SUCH_RESOURCE)
error.SetStaticDescription(UNI_L("Unable to find the specified resource"));
else if (status == OpStatus::ERR_OUT_OF_RANGE)
error.SetStaticDescription(UNI_L("Input out of range"));
else if (status == OpStatus::ERR_PARSING_FAILED)
error.SetStaticDescription(UNI_L("Parsing failed while executing command"));
else if (status == OpStatus::ERR_NO_DISK)
error.SetStaticDescription(UNI_L("Disk is full"));
else if (status == OpStatus::ERR_NO_ACCESS)
error.SetStaticDescription(UNI_L("Attempting to write a read-only entity"));
else if (status == OpStatus::ERR_NOT_DELAYED)
error.SetStaticDescription(UNI_L("Posted message was not delayed"));
else if (status == OpStatus::ERR_FILE_NOT_FOUND)
error.SetStaticDescription(UNI_L("File not found or could not be opened"));
else if (status == OpStatus::ERR_BAD_FILE_NUMBER)
error.SetStaticDescription(UNI_L("Wrong socket or file ID"));
else if (status == OpStatus::ERR_NULL_POINTER)
error.SetStaticDescription(UNI_L("Encountered a null pointer"));
else if (status == OpStatus::ERR_NOT_SUPPORTED)
error.SetStaticDescription(UNI_L("Unsupported operation"));
else
error.SetStaticDescription(GetCommandExecutionFailedText());
return SetCommandError(error);
}
OP_STATUS
OpScopeService::FormatCommandError(OpScopeTPError &error, uni_char *buffer, size_t count, const uni_char *format, ...)
{
va_list arg_ptr;
va_start(arg_ptr, format);
int result = uni_vsnprintf(buffer, count, format, arg_ptr);
va_end(arg_ptr);
if (result != 0)
RETURN_IF_ERROR(error.SetDescription(buffer));
return result == 0 ? OpStatus::ERR : OpStatus::OK;
}
/* virtual */
OP_STATUS
OpScopeService::DoReceive( OpScopeClient *, const OpScopeTPMessage & )
{
// TODO: Remove this implementation
return OpStatus::OK;
}
OP_STATUS
OpScopeService::SendAsyncError( unsigned int async_tag, const OpScopeTPError &error_data )
{
AsyncCommand *async_command = GetAsyncCommand(async_tag);
RETURN_VALUE_IF_NULL(async_command, OpStatus::ERR_NO_SUCH_RESOURCE);
OP_ASSERT(client != NULL);
if (!client)
{
CleanupAsyncCommand(async_tag);
return OpStatus::ERR_NULL_POINTER;
}
OpAutoPtr<OpScopeTPMessage> out_msg;
OP_STATUS status = OpScopeTPMessage::Clone(out_msg, async_command->header);
CleanupAsyncCommand(async_tag);
RETURN_IF_ERROR(status);
RETURN_IF_ERROR(client->SerializeError(*out_msg.get(), error_data, out_msg->Type()));
return client->Receive(out_msg);
}
OP_STATUS
OpScopeService::SendAsyncError(unsigned async_tag, unsigned responseID, OP_STATUS command_status)
{
if (!OpStatus::IsError(command_status))
return OpStatus::OK;
AsyncCommand *async_command = GetAsyncCommand(async_tag);
RETURN_VALUE_IF_NULL(async_command, OpStatus::ERR_NO_SUCH_RESOURCE);
OP_ASSERT(client != NULL);
if (!client)
{
CleanupAsyncCommand(async_tag);
return OpStatus::ERR_NULL_POINTER;
}
// Only STP/1 can receive errors
if (client->GetHost()->GetVersion() < 1)
{
CleanupAsyncCommand(async_tag);
return OpStatus::OK;
}
OpScopeTPError error;
error.SetStatus(OpScopeTPMessage::InternalError);
OpAutoPtr<OpScopeTPMessage> error_message;
OP_STATUS status = OpScopeTPMessage::Clone(error_message, async_command->header);
CleanupAsyncCommand(async_tag);
RETURN_IF_ERROR(status);
if (OpStatus::IsMemoryError(command_status))
{
// TODO: Perhaps the error message should be statically (or pre-) allocated to avoid allocation problems when sending it out
error.SetStatus(OpScopeTPMessage::OutOfMemory);
error.SetStaticDescription(UNI_L("OOM while executing command"));
}
else if (command_status == OpStatus::ERR_PARSING_FAILED)
error.SetStaticDescription(UNI_L("Parsing failed while executing command"));
else if (command_status == OpStatus::ERR_NULL_POINTER)
error.SetStaticDescription(UNI_L("Null pointer while executing command"));
else if (command_status == OpStatus::ERR_NOT_SUPPORTED)
error.SetStaticDescription(UNI_L("Unsupported action encountered while executing command"));
else
error.SetStaticDescription(UNI_L("Internal error while executing command"));
RETURN_IF_ERROR(client->SerializeError(*error_message.get(), error, error_message->Type()));
return client->Receive(error_message);
}
OP_STATUS
OpScopeService::SendError( OpScopeClient *client, const OpScopeTPMessage &orig_message, const OpScopeTPError &error_data )
{
OP_ASSERT(client != NULL);
if (client == NULL)
return OpStatus::ERR_NULL_POINTER;
OpAutoPtr<OpScopeTPMessage> outmsg;
RETURN_IF_ERROR(OpScopeTPMessage::Clone(outmsg, orig_message, FALSE));
outmsg->SetVersion(OpScopeTPMessage::Version_1);
outmsg->SetServiceName(GetName());
RETURN_IF_ERROR(client->SerializeError(*outmsg.get(), error_data, orig_message.Type()));
RETURN_IF_ERROR(client->Receive(outmsg));
is_response_sent = TRUE;
return OpStatus::OK;
}
OP_STATUS
OpScopeService::SerializeResponse(OpScopeClient *client, OpAutoPtr<OpScopeTPMessage> &out, const OpScopeTPHeader &original, const OpProtobufInstanceProxy &proxy, unsigned int responseID)
{
OP_ASSERT(client != NULL);
if (client == NULL)
return OpStatus::ERR_NULL_POINTER;
RETURN_IF_ERROR(OpScopeTPMessage::Clone(out, original));
out->SetTransportType(OpScopeTPMessage::STP_Response);
RETURN_IF_ERROR(out->SetServiceName(GetName()));
out->SetCommandID(responseID);
OP_STATUS status = client->Serialize(*out.get(), proxy, original.Type());
if (OpStatus::IsError(status))
{
// Failed to serialize the message, report the error
// This will cause an error message to be sent back to the client
return ReportCommandStatus(status);
}
return OpStatus::OK;
}
OP_STATUS
OpScopeService::SendResponse( OpScopeClient *client, const OpScopeTPHeader &original, const OpProtobufInstanceProxy &proxy )
{
OP_ASSERT(client != NULL);
if (client == NULL)
return OpStatus::ERR_NULL_POINTER;
OpAutoPtr<OpScopeTPMessage> out_msg;
RETURN_IF_ERROR(SerializeResponse(client, out_msg, original, proxy, original.CommandID()));
RETURN_IF_ERROR(client->Receive(out_msg));
is_response_sent = TRUE;
return OpStatus::OK;
}
OP_STATUS
OpScopeService::SendAsyncResponse( unsigned int async_tag, const OpProtobufInstanceProxy &proxy, unsigned int responseID )
{
AsyncCommand *async_command = GetAsyncCommand(async_tag);
RETURN_VALUE_IF_NULL(async_command, OpStatus::ERR_NO_SUCH_RESOURCE);
OP_ASSERT(client != NULL);
OP_STATUS status = OpStatus::ERR_NULL_POINTER;
if (client)
{
OpAutoPtr<OpScopeTPMessage> out_msg;
status = SerializeResponse(client, out_msg, async_command->header, proxy, responseID);
if (OpStatus::IsSuccess(status))
{
status = client->Receive(out_msg);
is_response_sent = TRUE;
}
}
CleanupAsyncCommand(async_tag);
return status;
}
OP_STATUS
OpScopeService::SendEvent( const OpProtobufInstanceProxy &proxy, unsigned int responseID )
{
OP_ASSERT(client);
if (client == NULL)
return OpStatus::ERR_NULL_POINTER;
OpScopeTPMessage::MessageType type = client->GetMessageType();
OpScopeTPHeader::MessageVersion version = OpScopeTPHeader::DefaultVersion;
OpAutoPtr<OpScopeTPMessage> out_msg(OP_NEW(OpScopeTPMessage ,(OpScopeTPMessage::STP_Event, GetName(), responseID, OpScopeTPMessage::OK, 0, version)));
RETURN_OOM_IF_NULL(out_msg.get());
out_msg->SetCommandID(responseID);
client->Serialize(*out_msg.get(), proxy, type);
RETURN_IF_ERROR(client->Receive(out_msg));
return OpStatus::OK;
}
/*static*/
OpScopeTPHeader::MessageStatus
OpScopeService::ErrorCode(OP_STATUS status)
{
if (OpStatus::IsSuccess(status))
return OpScopeTPHeader::OK;
switch (status)
{
case OpStatus::ERR_NO_MEMORY:
return OpScopeTPHeader::OutOfMemory;
case OpStatus::ERR:
case OpStatus::ERR_PARSING_FAILED:
return OpScopeTPHeader::BadRequest;
default:
return OpScopeTPHeader::InternalError;
}
}
OP_STATUS
OpScopeService::InitAsyncCommand(const OpScopeTPHeader &header, unsigned &async_tag)
{
unsigned tag = 1;
AsyncCommand *async_command = async_commands.First();
if (async_command)
{
unsigned min_tag = UINT_MAX, max_tag = 1;
for (; async_command; async_command = async_command->Suc())
{
min_tag = MIN(min_tag, async_command->tag);
max_tag = MAX(max_tag, async_command->tag);
}
tag = min_tag > 1 ? min_tag - 1 : max_tag + 1;
}
OP_ASSERT(tag < UINT_MAX && tag >= 1);
async_command = OP_NEW(AsyncCommand, (tag));
RETURN_OOM_IF_NULL(async_command);
RETURN_IF_ERROR(async_command->Construct(header));
async_command->Into(&async_commands);
async_tag = tag;
return OpStatus::OK;
}
void
OpScopeService::CleanupAsyncCommand(unsigned async_tag)
{
AsyncCommand *async_command = GetAsyncCommand(async_tag);
if (async_command)
{
async_command->Out();
OP_DELETE(async_command);
}
}
OpScopeService::AsyncCommand *
OpScopeService::GetAsyncCommand(unsigned async_tag)
{
for (AsyncCommand *async_command = async_commands.First(); async_command; async_command = async_command->Suc())
{
if (async_command->tag == async_tag)
return async_command;
}
return NULL;
}
OP_STATUS
OpScopeService::ParseMessage( OpScopeClient *client, const OpScopeTPMessage &msg, OpProtobufInstanceProxy &proxy )
{
OpScopeTPError error;
OP_STATUS status = client->Parse(msg, proxy, error);
if (error.GetStatus() != OpScopeTPHeader::OK)
SetCommandError(error);
return status;
}
/*virtual*/
OpScopeService::EnumIDRange
OpScopeService::GetEnumIDs() const
{
// Default is to return an empty range
return EnumIDRange(NULL, 0);
}
/*virtual*/
unsigned
OpScopeService::GetEnumCount() const
{
// Service has no enums by default
return 0;
}
/*virtual*/
BOOL
OpScopeService::HasEnum(unsigned enum_id) const
{
return FALSE;
}
/*virtual*/
OP_STATUS
OpScopeService::GetEnum(unsigned enum_id, const uni_char *&name, unsigned &value_count) const
{
// Service has no enums by default
return OpStatus::ERR_NO_SUCH_RESOURCE;
}
/*virtual*/
OP_STATUS
OpScopeService::GetEnumValue(unsigned enum_id, unsigned idx, const uni_char *&value_name, unsigned &value_number) const
{
// Service has no enums by default
return OpStatus::ERR_NO_SUCH_RESOURCE;
}
/* virtual */ void
OpScopeService::FilterChanged()
{
}
/* virtual */ void
OpScopeService::WindowClosed(Window *window)
{
}
void
OpScopeService::SilentError(OP_STATUS status)
{
if(OpStatus::IsMemoryError(status))
g_memory_manager->RaiseCondition(status);
}
/* OpScopeMetaService */
OpScopeMetaService::OpScopeMetaService(const uni_char* id, OpScopeServiceManager *manager)
: OpScopeService(id, manager, CONTROL_FORCED)
{
}
/* virtual */
OpScopeMetaService::~OpScopeMetaService()
{
}
/* virtual */ const char *
OpScopeMetaService::GetVersionString() const
{
return "0.0";
}
/* virtual */ int
OpScopeMetaService::GetMajorVersion() const
{
return 0;
}
/* virtual */ int
OpScopeMetaService::GetMinorVersion() const
{
return 0;
}
/* virtual */ const char *
OpScopeMetaService::GetPatchVersion() const
{
return "0";
}
#endif // SCOPE_SUPPORT
|
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<vector<int>> res;
vector<vector<int>> permute(vector<int>& nums) {
//基本思想:典型的递归回溯法,递归回溯找寻所有可能结果保存到res
//对于每一个当前位置i,我们可以将其于之后的任意位置交换,然后继续处理位置i+1,直到处理到最后一位。
Recursion(nums, 0);
return res;
}
void Recursion(vector<int> nums, int cnt)
{
//cnt计数cur中元素个数,当等于nums.size(),将当前的一种组合cur保存到res
if (cnt == nums.size())
{
res.push_back(nums);
return;
}
//循环nums所有元素
for (int i = cnt; i < nums.size(); i++)
{
swap(nums[i],nums[cnt]);
Recursion(nums, cnt + 1);
swap(nums[i],nums[cnt]);
}
return;
}
};
class Solution1 {
public:
vector<vector<int>> res;
vector<vector<int>> permute(vector<int>& nums) {
//基本思想:典型的递归回溯法,递归回溯找寻所有可能结果保存到res
//cur保存当前某一种可能的组合情况,cnt计数cur中元素个数,当等于nums.size(),将当前的一种组合cur保存到res
vector<int> cur;
Recursion(nums, cur, 0);
return res;
}
void Recursion(vector<int> nums, vector<int> cur,int cnt)
{
//cnt计数cur中元素个数,当等于nums.size(),将当前的一种组合cur保存到res
if (cnt == nums.size())
{
res.push_back(cur);
return;
}
//循环nums所有元素
for (int i = 0; i < nums.size(); i++)
{
int flag = 0;
//看当前nums中的元素nums[i]是否存在cur中,若存在cur中flag=1继续循环看nums下一个元素,若不存在加入cur,cnt+1,递归找下一个元素
for (auto& r : cur)
{
if (r == nums[i])
{
flag = 1;
break;
}
}
if (flag == 0)
{
cur.push_back(nums[i]);
Recursion(nums, cur, cnt + 1);
//回溯弹出刚刚加入的元素nums[i]
cur.pop_back();
}
}
return;
}
};
int main()
{
Solution solute;
vector<vector<int>> res;
vector<int> nums = { 1,2,3 };
res = solute.permute(nums);
for (int i = 0; i < res.size(); i++)
{
for (int j = 0; j < res[i].size(); j++)
cout << res[i][j] << " ";
cout << endl;
}
return 0;
}
|
#ifndef CURRENTDATE_H
#define CURRENTDATE_H
#include <QDialog>
namespace Ui {
class currentDate;
}
class currentDate : public QDialog
{
Q_OBJECT
public:
explicit currentDate(QWidget *parent = nullptr);
~currentDate();
bool if_closed();
QVariant date_fin();
private slots:
void onEdit_Pushed();
void onCancel_Pushed();
private:
Ui::currentDate *ui;
bool if_can = false;
QVariant *input;
};
#endif // CURRENTDATE_H
|
#include "pit.h"
#include <iostream>
using namespace std;
void Pit::percept(int player_index, int size, bool has_gold){
int side_length = sqrt(size);
if(player_index == 0 && (index == player_index + 1 || index == player_index + side_length || index == player_index + side_length + 1)){
cout << "\tYou feel a breeze." << endl;
}else if(player_index == side_length - 1 && (index == player_index - 1 || index == player_index + side_length || index == player_index + side_length - 1)){
cout << "\tYou feel a breeze." << endl;
}else if(player_index == size - 1 && (index == player_index - side_length || index == player_index - side_length - 1 || index == player_index - 1)){
cout << "\tYou feel a breeze." << endl;
}else if(player_index == size - side_length && (index == player_index + 1 || index == player_index - side_length || index == player_index - side_length + 1)){
cout << "\tYou feel a breeze." << endl;
}else if(player_index % side_length == 0 && (index == player_index - side_length || index == player_index - side_length + 1 || index == player_index + 1 || index == player_index + side_length || index == player_index + side_length + 1)){
cout << "\tYou feel a breeze." << endl;
}else if(player_index > 0 && player_index < sqrt(size) - 1 && ((index >= player_index - side_length - 1 && index <= player_index - side_length + 1) || (index >= player_index + side_length - 1 && index <= player_index + side_length + 1) || index == player_index - 1 || index == player_index + 1)){
cout << "\tYou feel a breeze." << endl;
}else if((player_index + 1) % side_length == 0 && (index == player_index - side_length || index == player_index - side_length - 1 || index == player_index - 1 || index == player_index + side_length || index == player_index + side_length - 1)){
cout << "\tYou feel a breeze." << endl;
}else if(player_index > size - side_length && player_index < size - 1 && ((index >= player_index - side_length - 1 && index <= player_index - side_length + 1) || (index >= player_index + side_length - 1 && index <= player_index + side_length + 1) || index == player_index - 1 || index == player_index + 1)){
cout << "\tYou feel a breeze." << endl;
}else if(player_index != 0 && player_index != side_length - 1 && player_index != size - 1 && player_index != size - side_length && player_index % side_length != 0 && player_index > side_length && (player_index + 1) % side_length != 0 && player_index < size - side_length){
if(index >= player_index - side_length - 1 && index <= player_index - side_length + 1 || index >= player_index + side_length - 1 && index <= player_index + side_length + 1 || index == player_index - 1 || index == player_index + 1){
cout << "\tYou feel a breeze." << endl;
}
}
}
int Pit::encounter(int player_index){
cout << "The tunnel door opens up into a massive pit and you fall in. You have died." << endl;
return -2;
}
int Pit::get_event(){
return 3;
}
void Pit::set_index(int new_index){
index = new_index;
}
|
#include "StdAfx.h"
#include "FEBattleField.h"
#include <algorithm>
using namespace std;
FEBattleField::FEBattleField(int numberOfPlayers, int height, int width, FEStatViewer* statViewer) : Dungeon(height, width)
{
activeUnit = nullptr;
cursorX = 0;
cursorY = 0;
moveCounter = 0;
flashCounter = 0;
currentTurn = 0;
numPlayers = numberOfPlayers;
unitsOnField = 0;
unitCounts = new LinkedList<FEUnit>*[numberOfPlayers];
factionAIs = new FEAIInterface*[numberOfPlayers];
for(int counter = 0; counter < numberOfPlayers; counter++)
{
unitCounts[counter] = new LinkedList<FEUnit>();
factionAIs[counter] = nullptr;
}
attackMode = false;
statWindow = statViewer;
unitsToMove = new LinkedList<FEUnit>();
terrainObjects = new int*[width];
for (int i = 0; i < width; i++)
terrainObjects[i] = new int[height];
}
FEBattleField::~FEBattleField(void)
{
for(int counter = 0; counter < numPlayers; counter++)
{
delete unitCounts[counter];
delete factionAIs;
}
delete unitCounts;
}
ColorChar FEBattleField::getColorChar(int x, int y)
{
ColorChar retVal = contents[x + y * width]->getColorChar();
if(x == cursorX && y == cursorY && flashCounter > 10)
{
retVal.color = 56; //black on white
}
else if(activeUnit != nullptr)
{
if(attackMode)
{
if(getDistance(activeUnit->getMyX(), activeUnit->getMyY(), x, y) <= activeUnit->getRange() &&
(!contents[x + y * width]->hasOccupant() || static_cast<FEUnit*>(contents[x + y * width]->getOccupant())->getTeam() != activeUnit->getTeam()))
{
retVal.color = (retVal.color % 8) + 40; //angry background
}
}
else
{
//blue field can be moved to
if(!contents[y * width + x]->hasOccupant() && getDistance(activeUnit->getMyX(), activeUnit->getMyY(), x, y) <= activeUnit->getStats().move)
{
retVal.color = (retVal.color % 8) + 24; //cyan background
}
else if(getDistance(activeUnit->getMyX(), activeUnit->getMyY(), x, y) <= activeUnit->getStats().move + activeUnit->getRange() &&
(!contents[x + y * width]->hasOccupant() || static_cast<FEUnit*>(contents[x + y * width]->getOccupant())->getTeam() != activeUnit->getTeam()))
{
retVal.color = (retVal.color % 8) + 40; //angry background
}
}
}
return retVal;
}
bool FEBattleField::enter(Creature* newCreature, int x, int y)
{
//TODO: check that newCreature is a FE creature, somehow
/* if(typeid (newCreature) != typeid(FEUnit*)) //extensions should be allowed; I'll have to rewrite this check
{
return false;
}*/
bool attempt = Dungeon::enter(newCreature, x, y);
if(!attempt)
{
return false;
}
unitsOnField++;
unitCounts[(static_cast <FEUnit*>(newCreature))->getTeam()]->insert(static_cast <FEUnit*>(newCreature));
if((static_cast <FEUnit*>(newCreature))->getTeam() == currentTurn)
{
unitsToMove->insert(static_cast <FEUnit*>(newCreature));
}
return true;
}
void FEBattleField::exit(int x, int y)
{
if(contents[x + y * width]->getOccupant() != nullptr)
{
if(contents[x + y * width]->getOccupant() == activeUnit)
{
finishMoving();
}
totalUnits--;
unitCounts[static_cast<FEUnit*>(contents[x + y * width]->getOccupant())->getTeam()]->remove(static_cast<FEUnit*>(contents[x + y * width]->getOccupant()));
unitsToMove->remove(static_cast<FEUnit*>(contents[x + y * width]->getOccupant()));
}
Dungeon::exit(x, y);
}
void FEBattleField::takeInput(char in) //finish this function
{
if(moveCounter > 8 && factionAIs[currentTurn] == nullptr)
{
moveCounter = 0;
//if there's a num key, move the cursor
if(in >= '1' && in <= '9')
{
if(in % 3 == 1)
{
cursorX--;
cursorX = max(cursorX, 0);
}
else if(in % 3 == 0)
{
cursorX++;
cursorX = min(cursorX, width - 1);
}
if(in < '4')
{
cursorY++;
cursorY = min(cursorY, height - 1);
}
else if(in > '6')
{
cursorY--;
cursorY = max(cursorY, 0);
}
//if we moused over a unit, display it
if(contents[width * cursorY + cursorX]->hasOccupant())
{
statWindow->setUnit(static_cast<FEUnit*>(contents[width * cursorY + cursorX]->getOccupant()));
}
}
else if(in == 'a') //select
{
//if no unit is selected, select the unit in the current cell
if(activeUnit == nullptr)
{
if(contents[cursorX + cursorY * width]->hasOccupant())
{
activeUnit = static_cast<FEUnit*> (contents[cursorX + cursorY * width]->getOccupant());
if(!activeUnit->getIsActive() || activeUnit->getTeam() != currentTurn)
{
activeUnit = nullptr; //can't select inactive units
}
}
}
else if(attackMode)
{
//try to attack the unit at the indicated location
if(canAttack(activeUnit, cursorX, cursorY))
{
activeUnit->attack(static_cast<FEUnit*>(contents[cursorX + cursorY * width]->getOccupant()), false);
finishMoving();
}
}
else //a unit is selected, so try to move to the indicated location
{
//first check if there is enough range
if(canMove(activeUnit, cursorX, cursorY))
{
if(activeUnit->getMyLocation()->tryToMoveToCell(contents[cursorX + cursorY * width], false))
{
attackMode = true;
}
}
}
}
else if(in == 'b') //cancel
{
if(attackMode)
{
finishMoving();
}
}
}
}
void FEBattleField::step()
{
flashCounter = (flashCounter + 1) % 15;
moveCounter++;
if(moveCounter >= 24 && factionAIs[currentTurn] != nullptr)
{
FEMoveOrder thisOrder = factionAIs[currentTurn]->getNextMove(this, unitsToMove);
//execute the order
activeUnit = thisOrder.unitToMove;
if(canMove(activeUnit, thisOrder.endX, thisOrder.endY))
{
activeUnit->getMyLocation()->tryToMoveToCell(contents[thisOrder.endX + thisOrder.endY * width], false);
}
if(thisOrder.attackTarget != nullptr && canAttack(activeUnit, thisOrder.attackTarget->getMyX(), thisOrder.attackTarget->getMyY()))
{
activeUnit->attack(thisOrder.attackTarget, false);
}
finishMoving();
}
}
inline int FEBattleField::getDistance(int xStart, int yStart, int xEnd, int yEnd)
{
return abs(xStart - xEnd) + abs(yStart - yEnd);
}
void FEBattleField::finishMoving()
{
if(activeUnit != nullptr)
{
activeUnit->deactivate();
unitsToMove->remove(activeUnit);
}
attackMode = false;
activeUnit = nullptr;
//check if there are any activeUnits left of the current team
bool anyUnitsLeft = false;
forEach(FEUnit, counter, unitCounts[currentTurn]->getFirst())
{
if(counter->first->getIsActive())
{
anyUnitsLeft = true;
break;
}
}
if(!anyUnitsLeft) //no units left to move so advance the turn
{
//make all inactive units active
forEach(FEUnit, counter, unitCounts[currentTurn]->getFirst())
{
counter->first->activate();
}
do
{
currentTurn = (currentTurn + 1) % numPlayers;
}
while(unitCounts[currentTurn]->getFirst() == nullptr); //skip the turns of anyone with no units
delete unitsToMove;
unitsToMove = unitCounts[currentTurn]->copyList();
}
}
inline bool FEBattleField::canMove(FEUnit* movingUnit, int x, int y)
{
return getDistance(movingUnit->getMyX(), movingUnit->getMyY(), x, y) <= movingUnit->getStats().move;
}
inline bool FEBattleField::canAttack(FEUnit* attackingUnit, int x, int y)
{
return getDistance(attackingUnit->getMyX(), attackingUnit->getMyY(), x, y) <= attackingUnit->getRange() &&
contents[x + y * width]->hasOccupant() &&
static_cast<FEUnit*>(contents[x + y * width]->getOccupant())->getTeam() != attackingUnit->getTeam();
}
void FEBattleField::setAI(FEAIInterface* newAI, int faction)
{
factionAIs[faction] = newAI;
}
LinkedList<FEUnit>* FEBattleField::getPlayerUnits()
{
return unitCounts[0];
}
LinkedList<FEUnit>* FEBattleField::getAIUnits()
{
return unitCounts[1];
}
int FEBattleField::InitTerrain(int map[], int x, int y)
{
if (x != width || y != height)
return -1;
else {
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++) {
if (map[i*y+j] == 1) {
terrainObjects[i][j] = map[i*y+j];
// this->enter(new FEUnit('X', 2, 2, new StatBlock(), 0, ITEM, 0, 0, "Rock"), i, j);
}
}
}
}
|
#include "test.h"
TEST_BOTH(01_creation_destruction) {
// Checks simple reference counting of a variable
Float value(1234);
(void) value;
}
TEST_BOTH(02_fill_and_print) {
/// Checks array initialization from a given pointer, jitc_memset(), and stringification
jitc_log(Info, " int8_t: %s", full<Array< int8_t>>(-111, 5).str());
jitc_log(Info, " uint8_t: %s", full<Array< uint8_t>>( 222, 5).str());
jitc_log(Info, " int16_t: %s", full<Array< int16_t>>(-1111, 5).str());
jitc_log(Info, "uint16_t: %s", full<Array<uint16_t>>( 2222, 5).str());
jitc_log(Info, " int32_t: %s", full<Array< int32_t>>(-1111111111, 5).str());
jitc_log(Info, "uint32_t: %s", full<Array<uint32_t>>( 2222222222, 5).str());
jitc_log(Info, " int64_t: %s", full<Array< int64_t>>(-1111111111111111111, 5).str());
jitc_log(Info, "uint64_t: %s", full<Array<uint64_t>>( 2222222222222222222, 5).str());
jitc_log(Info, " float: %s", full<Array< float>>(1.f / 3.f, 5).str());
jitc_log(Info, " double: %s", full<Array< double>>(1.0 / 3.0, 5).str());
}
TEST_LLVM(03_eval_scalar) {
/// Checks that we can evaluate a simple kernel, and that kernels are reused
Float value(1234);
set_label(value, "my_value");
jitc_log(Info, "value=%s", value.str());
value = Float(1234);
set_label(value, "my_value");
jitc_log(Info, "value=%s", value.str());
}
TEST_BOTH(04_eval_scalar_csa) {
/// Checks common subexpression elimination
Float value_1(1234),
value_2(1235),
value_3(1234),
value_4 = value_1 + value_2,
value_5 = value_1 + value_3,
value_6 = value_1 + value_2;
jitc_eval(value_1, value_2, value_3, value_4, value_5, value_6);
jitc_log(Info, "value_1=%s", value_1.str());
jitc_log(Info, "value_2=%s", value_2.str());
jitc_log(Info, "value_3=%s", value_3.str());
jitc_log(Info, "value_4=%s", value_4.str());
jitc_log(Info, "value_5=%s", value_5.str());
jitc_log(Info, "value_6=%s", value_6.str());
}
TEST_BOTH(05_argument_out) {
/// Test kernels with very many outputs that exceed the max. size of the CUDA parameter list
scoped_set_log_level ssll(LogLevel::Info);
/* With reduced log level */ {
Int32 value[1024];
for (int i = 1; i < 1024; i *= 3) {
Int32 out = 0;
for (int j = 0; j < i; ++j) {
value[j] = j;
out += value[j].schedule();
}
jitc_log(Info, "value=%s vs %u", out.str(), i * (i - 1) / 2);
}
}
}
TEST_BOTH(06_argument_inout) {
/// Test kernels with very many inputs that exceed the max. size of the CUDA parameter list
scoped_set_log_level ssll(LogLevel::Info);
/* With reduced log level */ {
Int32 value[1024];
for (int i = 1; i < 1024; i *= 3) {
Int32 out = 0;
for (int j = 0; j < i; ++j) {
if (!value[j].valid())
value[j] = j;
out += value[j].schedule();
}
jitc_log(Info, "value=%s vs %u", out.str(), i * (i - 1) / 2);
}
}
}
TEST_BOTH(07_arange) {
/// Tests arange, and dispatch to parallel streams
UInt32 x = arange<UInt32>(1024);
UInt32 y = arange<UInt32>(3, 512, 7);
jitc_schedule(x, y);
jitc_log(Info, "value=%s", x.str());
jitc_log(Info, "value=%s", y.str());
using Int64 = Array<int64_t>;
Int64 x2 = arange<Int64>(1024);
Int64 y2 = arange<Int64>(-3, 506, 7);
jitc_schedule(x2, y2);
jitc_log(Info, "value=%s", x2.str());
jitc_log(Info, "value=%s", y2.str());
}
TEST_BOTH(08_conv) {
/* UInt32 */ {
auto src = arange<Array<uint32_t>>(1024);
Array<uint32_t> x_u32(src);
Array<int32_t> x_i32(src);
Array<uint64_t> x_u64(src);
Array<int64_t> x_i64(src);
Array<float> x_f32(src);
Array<double> x_f64(src);
jitc_schedule(x_u32, x_i32, x_u64, x_i64, x_f32, x_f64);
jitc_log(Info, "value=%s", x_u32.str());
jitc_log(Info, "value=%s", x_i32.str());
jitc_log(Info, "value=%s", x_u64.str());
jitc_log(Info, "value=%s", x_i64.str());
jitc_log(Info, "value=%s", x_f32.str());
jitc_log(Info, "value=%s", x_f64.str());
}
/* Int32 */ {
auto src = arange<Array<int32_t>>(1024) - 512;
Array<int32_t> x_i32(src);
Array<int64_t> x_i64(src);
Array<float> x_f32(src);
Array<double> x_f64(src);
jitc_schedule(x_i32, x_i64, x_f32, x_f64);
jitc_log(Info, "value=%s", x_i32.str());
jitc_log(Info, "value=%s", x_i64.str());
jitc_log(Info, "value=%s", x_f32.str());
jitc_log(Info, "value=%s", x_f64.str());
}
/* UInt64 */ {
auto src = arange<Array<uint64_t>>(1024);
Array<uint32_t> x_u32(src);
Array<int32_t> x_i32(src);
Array<uint64_t> x_u64(src);
Array<int64_t> x_i64(src);
Array<float> x_f32(src);
Array<double> x_f64(src);
jitc_schedule(x_u32, x_i32, x_u64, x_i64, x_f32, x_f64);
jitc_log(Info, "value=%s", x_u32.str());
jitc_log(Info, "value=%s", x_i32.str());
jitc_log(Info, "value=%s", x_u64.str());
jitc_log(Info, "value=%s", x_i64.str());
jitc_log(Info, "value=%s", x_f32.str());
jitc_log(Info, "value=%s", x_f64.str());
}
/* Int64 */ {
auto src = arange<Array<int64_t>>(1024) - 512;
Array<int32_t> x_i32(src);
Array<int64_t> x_i64(src);
Array<float> x_f32(src);
Array<double> x_f64(src);
jitc_schedule(x_i32, x_i64, x_f32, x_f64);
jitc_log(Info, "value=%s", x_i32.str());
jitc_log(Info, "value=%s", x_i64.str());
jitc_log(Info, "value=%s", x_f32.str());
jitc_log(Info, "value=%s", x_f64.str());
}
/* Float */ {
auto src = arange<Array<float>>(1024) - 512;
Array<int32_t> x_i32(src);
Array<int64_t> x_i64(src);
Array<float> x_f32(src);
Array<double> x_f64(src);
jitc_schedule(x_i32, x_i64, x_f32, x_f64);
jitc_log(Info, "value=%s", x_i32.str());
jitc_log(Info, "value=%s", x_i64.str());
jitc_log(Info, "value=%s", x_f32.str());
jitc_log(Info, "value=%s", x_f64.str());
}
/* Double */ {
auto src = arange<Array<double>>(1024) - 512;
Array<int32_t> x_i32(src);
Array<int64_t> x_i64(src);
Array<float> x_f32(src);
Array<double> x_f64(src);
jitc_schedule(x_i32, x_i64, x_f32, x_f64);
jitc_log(Info, "value=%s", x_i32.str());
jitc_log(Info, "value=%s", x_i64.str());
jitc_log(Info, "value=%s", x_f32.str());
jitc_log(Info, "value=%s", x_f64.str());
}
}
TEST_BOTH(09_fma) {
/* Float case */ {
Float a(1, 2, 3, 4);
Float b(3, 8, 1, 5);
Float c(9, 1, 3, 0);
Float d = fmadd(a, b, c);
Float e = fmadd(d, b, -c);
jitc_schedule(d, e);
jitc_log(Info, "value=%s", d.str());
jitc_log(Info, "value=%s", e.str());
}
using Double = Array<double>;
/* Double case */ {
Double a(1, 2, 3, 4);
Double b(3, 8, 1, 5);
Double c(9, 1, 3, 0);
Double d = fmadd(a, b, c);
Double e = fmadd(d, b, -c);
jitc_schedule(d, e);
jitc_log(Info, "value=%s", d.str());
jitc_log(Info, "value=%s", e.str());
}
}
TEST_BOTH(10_sqrt) {
Float x = sqrt(arange<Float>(10));
jitc_log(Info, "value=%s", x.str());
}
TEST_BOTH(11_mask) {
Float x = arange<Float>(10);
auto mask = x > 5;
x = select(mask, -x, x);
jitc_schedule(mask, x);
jitc_log(Info, "value=%s", x.str());
jitc_log(Info, "mask=%s", mask.str());
Float y = select(mask, Float(1.f), Float(2.f));
jitc_log(Info, "value_2=%s", y.str());
Array<bool> mask_scalar_t = true;
Array<bool> mask_scalar_f = false;
jitc_eval(mask_scalar_t, mask_scalar_f);
Float a = select(mask_scalar_t, x, Float(0));
Float b = select(mask_scalar_f, x, Float(0));
jitc_schedule(a, b);
jitc_log(Info, "value_3=%s", a.str());
jitc_log(Info, "value_4=%s", b.str());
}
TEST_BOTH(12_binop) {
UInt32 a(1, 1234);
Float b(1.f, 1234.f);
Array<bool> c(true, false);
a = ~a;
b = ~b;
c = ~c;
jitc_schedule(a, b, c);
jitc_log(Info, "XOR: value_1=%s", a.str());
jitc_log(Info, "XOR: value_2=%s", b.str());
jitc_log(Info, "XOR: value_3=%s", c.str());
a = ~a;
b = ~b;
c = ~c;
jitc_schedule(a, b, c);
jitc_log(Info, "XOR2: value_1=%s", a.str());
jitc_log(Info, "XOR2: value_2=%s", b.str());
jitc_log(Info, "XOR2: value_3=%s", c.str());
int32_t x = 0x7fffffff;
float y;
memcpy(&y, &x, 4);
UInt32 a2(0, 0xFFFFFFFF);
Float b2(0.f, y);
Array<bool> c2(false, true);
auto a3 = a | a2;
auto b3 = b | b2;
auto c3 = c | c2;
jitc_schedule(a3, b3, c3);
jitc_log(Info, "OR: value_1=%s", a3.str());
jitc_log(Info, "OR: value_2=%s", b3.str());
jitc_log(Info, "OR: value_3=%s", c3.str());
auto a4 = a & a2;
auto b4 = b & b2;
auto c4 = c & c2;
jitc_schedule(a4, b4, c4);
jitc_log(Info, "AND: value_1=%s", a4.str());
jitc_log(Info, "AND: value_2=%s", b4.str());
jitc_log(Info, "AND: value_3=%s", c4.str());
auto a5 = a ^ a2;
auto b5 = b ^ b2;
auto c5 = c ^ c2;
jitc_schedule(a5, b5, c5);
jitc_log(Info, "XOR: value_1=%s", a5.str());
jitc_log(Info, "XOR: value_2=%s", b5.str());
jitc_log(Info, "XOR: value_3=%s", c5.str());
}
TEST_BOTH(14_scatter_gather) {
Int32 l = (-arange<Int32>(1024)).schedule();
UInt32 index = UInt32(34, 62, 75, 2);
Int32 value = gather(l, index);
jitc_log(Info, "%s", value.str());
jitc_log(Info, "%s", l.str());
scatter(l, value * 3, index);
value = gather(l, index);
jitc_log(Info, "%s", value.str());
jitc_log(Info, "%s", l.str());
}
TEST_BOTH(15_round) {
/* Single precision */ {
Float x(.4f, .5f, .6f, -.4f, -.5f, -.6f);
Float x_f = floor(x),
x_c = ceil(x),
x_t = trunc(x),
x_r = round(x),
x_mi = min(x_f, x_c),
x_ma = max(x_f, x_c);
jitc_schedule(x_f, x_c, x_t, x_r, x_mi, x_ma);
jitc_log(Info, "floor: %s", x_f.str());
jitc_log(Info, "ceil: %s", x_c.str());
jitc_log(Info, "trunc: %s", x_t.str());
jitc_log(Info, "round: %s", x_r.str());
jitc_log(Info, "min: %s", x_mi.str());
jitc_log(Info, "max: %s", x_ma.str());
}
/* Double precision */ {
using Double = Array<double>;
Double x(.4f, .5f, .6f, -.4f, -.5f, -.6f);
Double x_f = floor(x),
x_c = ceil(x),
x_t = trunc(x),
x_r = round(x),
x_mi = min(x_f, x_c),
x_ma = max(x_f, x_c);
jitc_schedule(x_f, x_c, x_t, x_r, x_mi, x_ma);
jitc_log(Info, "floor: %s", x_f.str());
jitc_log(Info, "ceil: %s", x_c.str());
jitc_log(Info, "trunc: %s", x_t.str());
jitc_log(Info, "round: %s", x_r.str());
jitc_log(Info, "min: %s", x_mi.str());
jitc_log(Info, "max: %s", x_ma.str());
}
}
TEST_LLVM(16_pointer_registry) {
const char *key_1 = "MyKey1";
const char *key_2 = "MyKey2";
jitc_assert(jitc_registry_get_max(key_1) == 0u);
jitc_assert(jitc_registry_get_max(key_2) == 0u);
uint32_t id_1 = jitc_registry_put(key_1, (void *) 0xA);
jitc_assert(jitc_registry_get_max(key_1) == 1u);
jitc_assert(jitc_registry_get_max(key_2) == 0u);
uint32_t id_2 = jitc_registry_put(key_1, (void *) 0xB);
jitc_assert(jitc_registry_get_max(key_1) == 2u);
jitc_assert(jitc_registry_get_max(key_2) == 0u);
uint32_t id_a = jitc_registry_put(key_2, (void *) 0xC);
jitc_assert(jitc_registry_get_max(key_1) == 2u);
jitc_assert(jitc_registry_get_max(key_2) == 1u);
uint32_t id_3 = jitc_registry_put(key_1, (void *) 0xD);
jitc_assert(jitc_registry_get_max(key_1) == 3u);
jitc_assert(jitc_registry_get_max(key_2) == 1u);
jitc_registry_trim(); // should be a no-op
jitc_assert(id_1 == 1u);
jitc_assert(id_2 == 2u);
jitc_assert(id_a == 1u);
jitc_assert(id_3 == 3u);
jitc_assert(jitc_registry_get_domain((void *) 0xA) == key_1);
jitc_assert(jitc_registry_get_domain((void *) 0xB) == key_1);
jitc_assert(jitc_registry_get_domain((void *) 0xC) == key_2);
jitc_assert(jitc_registry_get_domain((void *) 0xD) == key_1);
jitc_assert(jitc_registry_get_id((void *) 0xA) == 1u);
jitc_assert(jitc_registry_get_id((void *) 0xB) == 2u);
jitc_assert(jitc_registry_get_id((void *) 0xC) == 1u);
jitc_assert(jitc_registry_get_id((void *) 0xD) == 3u);
jitc_assert(jitc_registry_get_ptr(key_1, 1) == (void *) 0xA);
jitc_assert(jitc_registry_get_ptr(key_1, 2) == (void *) 0xB);
jitc_assert(jitc_registry_get_ptr(key_2, 1) == (void *) 0xC);
jitc_assert(jitc_registry_get_ptr(key_1, 3) == (void *) 0xD);
jitc_assert(jitc_registry_get_max(key_1) == 3u);
jitc_assert(jitc_registry_get_max(key_2) == 1u);
jitc_registry_remove((void *) 0xA);
jitc_registry_remove((void *) 0xB);
jitc_registry_remove((void *) 0xC);
id_1 = jitc_registry_put(key_1, (void *) 0xE);
id_2 = jitc_registry_put(key_1, (void *) 0xF);
id_a = jitc_registry_put(key_1, (void *) 0x1);
jitc_assert(id_1 == 2u);
jitc_assert(id_2 == 1u);
jitc_assert(id_a == 4u);
jitc_assert(jitc_registry_get_domain((void *) 0xE) == key_1);
jitc_assert(jitc_registry_get_domain((void *) 0xF) == key_1);
jitc_assert(jitc_registry_get_domain((void *) 0x1) == key_1);
jitc_assert(jitc_registry_get_id((void *) 0xE) == 2u);
jitc_assert(jitc_registry_get_id((void *) 0xF) == 1u);
jitc_assert(jitc_registry_get_id((void *) 0x1) == 4u);
jitc_assert(jitc_registry_get_ptr(key_1, 1) == (void *) 0xF);
jitc_assert(jitc_registry_get_ptr(key_1, 2) == (void *) 0xE);
jitc_assert(jitc_registry_get_ptr(key_1, 3) == (void *) 0xD);
jitc_assert(jitc_registry_get_ptr(key_1, 4) == (void *) 0x1);
jitc_registry_remove((void *) 0xD);
jitc_registry_remove((void *) 0xE);
jitc_registry_remove((void *) 0xF);
jitc_assert(jitc_registry_get_max(key_1) == 4u);
jitc_assert(jitc_registry_get_max(key_2) == 1u);
jitc_registry_trim();
jitc_registry_remove((void *) 0x1);
jitc_assert(jitc_registry_get_max(key_1) == 4u);
jitc_assert(jitc_registry_get_max(key_2) == 0u);
jitc_registry_trim();
jitc_assert(jitc_registry_get_max(key_1) == 0u);
jitc_assert(jitc_registry_get_max(key_2) == 0u);
}
TEST_BOTH(17_scatter_gather_mask) {
using Mask = Array<bool>;
Int32 l = arange<Int32>(1022);
set_label(l, "l");
Mask result = neq(l & Int32(1), 0);
set_label(result, "result");
Int32 l2 = arange<Int32>(510);
set_label(l2, "l2");
Mask even = gather(result, l2*2);
set_label(even, "even");
Mask odd = gather(result, l2*2 + 1);
set_label(odd, "odd");
jitc_log(Info, "Mask : %s", result.str());
jitc_log(Info, "Even : %s", even.str());
jitc_log(Info, "Odd : %s", odd.str());
scatter(result, odd, l2 * 2);
scatter(result, even, l2 * 2 + 1);
jitc_log(Info, "Mask: %s", result.str());
}
TEST_BOTH(18_mask_propagation) {
using Mask = Array<bool>;
Mask t(true), f(false), g(true, false);
jitc_assert( t.is_literal_one());
jitc_assert(!t.is_literal_zero());
jitc_assert(!f.is_literal_one());
jitc_assert( f.is_literal_zero());
jitc_assert(!g.is_literal_one());
jitc_assert(!g.is_literal_zero());
jitc_assert((t && f).is_literal_zero());
jitc_assert((f && t).is_literal_zero());
jitc_assert((g && f).is_literal_zero());
jitc_assert((f && g).is_literal_zero());
jitc_assert((t || f).is_literal_one());
jitc_assert((f || t).is_literal_one());
jitc_assert((t || g).is_literal_one());
jitc_assert((g || t).is_literal_one());
jitc_assert((t ^ f).is_literal_one());
jitc_assert((f ^ t).is_literal_one());
jitc_assert((f ^ g).index() == g.index());
jitc_assert((g ^ f).index() == g.index());
UInt32 a(1, 2), b(3, 4);
jitc_assert(select(f, a, b).index() == b.index());
jitc_assert(select(t, a, b).index() == a.index());
}
TEST_BOTH(19_register_ptr) {
uint32_t idx_1 = jitc_var_copy_ptr((const void *) 0x01, 0),
idx_2 = jitc_var_copy_ptr((const void *) 0x02, 0),
idx_3 = jitc_var_copy_ptr((const void *) 0x01, 0);
jitc_assert(idx_1 == 1);
jitc_assert(idx_2 == 2);
jitc_assert(idx_3 == 1);
jitc_var_dec_ref_ext(idx_1);
jitc_var_dec_ref_ext(idx_2);
jitc_var_dec_ref_ext(idx_3);
idx_1 = jitc_var_copy_ptr((const void *) 0x01, 0);
jitc_assert(idx_1 == 3);
jitc_var_dec_ref_ext(idx_1);
}
TEST_BOTH(20_reinterpret_cast) {
UInt32 result = reinterpret_array<UInt32>(Float(1.f, 2.f, 3.f));
jitc_log(Info, "As integer: %s", result.str());
Float result2 = reinterpret_array<Float>(result);
jitc_log(Info, "As float: %s", result2.str());
}
TEST_BOTH(21_shifts) {
UInt32 x(1234, (uint32_t) -1234);
Int32 y(1234, -1234);
UInt32 xs1 = x >> 1, xs2 = x << 1;
Int32 ys1 = y >> 1, ys2 = y << 1;
jitc_schedule(xs1, xs2, ys1, ys2);
jitc_log(Info, "xs1 : %s", xs1.str());
jitc_log(Info, "xs2 : %s", xs2.str());
jitc_log(Info, "ys1 : %s", ys1.str());
jitc_log(Info, "ys2 : %s", ys2.str());
}
TEST_BOTH(22_and_or_mask) {
using Mask = Array<bool>;
UInt32 x(0, 1);
Int32 y(0, 1);
Float z(0.f, 1.f);
Mask m(true, false);
UInt32 x_o = x | m, x_a = x & m;
Int32 y_o = y | m, y_a = y & m;
Float z_o = z | m, z_a = z & m;
z_o = abs(z_o);
jitc_schedule(x_o, x_a, y_o, y_a, z_o, z_a);
jitc_log(Info, "x_o : %s", x_o.str());
jitc_log(Info, "x_a : %s", x_a.str());
jitc_log(Info, "y_o : %s", y_o.str());
jitc_log(Info, "y_a : %s", y_a.str());
jitc_log(Info, "z_o : %s", z_o.str());
jitc_log(Info, "z_a : %s", z_a.str());
m = Mask(true);
x_o = x | m; x_a = x & m;
y_o = y | m; y_a = y & m;
z_o = z | m; z_a = z & m;
z_o = abs(z_o);
jitc_schedule(x_o, x_a, y_o, y_a, z_o, z_a);
jitc_log(Info, "x_o : %s", x_o.str());
jitc_log(Info, "x_a : %s", x_a.str());
jitc_log(Info, "y_o : %s", y_o.str());
jitc_log(Info, "y_a : %s", y_a.str());
jitc_log(Info, "z_o : %s", z_o.str());
jitc_log(Info, "z_a : %s", z_a.str());
m = Mask(false);
x_o = x | m; x_a = x & m;
y_o = y | m; y_a = y & m;
z_o = z | m; z_a = z & m;
jitc_schedule(x_o, x_a, y_o, y_a, z_o, z_a);
jitc_log(Info, "x_o : %s", x_o.str());
jitc_log(Info, "x_a : %s", x_a.str());
jitc_log(Info, "y_o : %s", y_o.str());
jitc_log(Info, "y_a : %s", y_a.str());
jitc_log(Info, "z_o : %s", z_o.str());
jitc_log(Info, "z_a : %s", z_a.str());
}
template <typename T, typename T2, typename S = typename T::Value>
T poly2(const T &x, const T2 &c0, const T2 &c1, const T2 &c2) {
T x2 = x * x;
return fmadd(x2, S(c2), fmadd(x, S(c1), S(c0)));
}
template <typename Value, typename Mask, typename Int>
void sincos_approx(const Value &x, Value &s_out, Value &c_out) {
/* Joint sine & cosine function approximation based on CEPHES.
Excellent accuracy in the domain |x| < 8192
Redistributed under a BSD license with permission of the author, see
https://github.com/deepmind/torch-cephes/blob/master/LICENSE.txt
- sin (in [-8192, 8192]):
* avg abs. err = 6.61896e-09
* avg rel. err = 1.37888e-08
-> in ULPs = 0.166492
* max abs. err = 5.96046e-08
(at x=-8191.31)
* max rel. err = 1.76826e-06
-> in ULPs = 19
(at x=-6374.29)
- cos (in [-8192, 8192]):
* avg abs. err = 6.59965e-09
* avg rel. err = 1.37432e-08
-> in ULPs = 0.166141
* max abs. err = 5.96046e-08
(at x=-8191.05)
* max rel. err = 3.13993e-06
-> in ULPs = 47
(at x=-6199.93)
*/
using Scalar = float;
Value xa = abs(x);
/* Scale by 4/Pi and get the integer part */
Int j(xa * Scalar(1.2732395447351626862));
/* Map zeros to origin; if (j & 1) j += 1 */
j = (j + uint32_t(1)) & uint32_t(~1u);
/* Cast back to a floating point value */
Value y(j);
// Determine sign of result
uint32_t Shift = sizeof(Scalar) * 8 - 3;
Value sign_sin = reinterpret_array<Value>(j << Shift) ^ x;
Value sign_cos = reinterpret_array<Value>((~(j - uint32_t(2))) << Shift);
// Extended precision modular arithmetic
y = xa - y * Scalar(0.78515625)
- y * Scalar(2.4187564849853515625e-4)
- y * Scalar(3.77489497744594108e-8);
Value z = y * y, s, c;
z |= eq(xa, std::numeric_limits<Scalar>::infinity());
s = poly2(z, -1.6666654611e-1,
8.3321608736e-3,
-1.9515295891e-4) * z;
c = poly2(z, 4.166664568298827e-2,
-1.388731625493765e-3,
2.443315711809948e-5) * z;
s = fmadd(s, y, y);
c = fmadd(c, z, fmadd(z, Scalar(-0.5), Scalar(1)));
Mask polymask(eq(j & uint32_t(2), Int(0)));
s_out = mulsign(select(polymask, s, c), sign_sin);
c_out = mulsign(select(polymask, c, s), sign_cos);
}
TEST_BOTH(23_sincos) {
using Mask = Array<bool>;
Float x = linspace<Float>(0, 1, 10);
Float xs, xc;
sincos_approx<Float, Mask, Int32>(x, xs, xc);
jitc_log(Info, "xs : %s", xs.str());
jitc_log(Info, "xc : %s", xc.str());
}
TEST_BOTH(24_bitop) {
UInt32 v(0, 1, 1234, 0xFFFFFFFF);
UInt32 v_pop = popcnt(v),
v_lz = lzcnt(v),
v_tz = tzcnt(v);
jitc_schedule(v_pop, v_lz, v_tz);
jitc_log(Info, "orig : %s", v.str());
jitc_log(Info, "pop : %s", v_pop.str());
jitc_log(Info, "lz : %s", v_tz.str());
jitc_log(Info, "tz : %s", v_lz.str());
}
TEST_LLVM(25_wide_intrinsics) {
jitc_llvm_set_target("skylake", "+avx2", 32);
Float a = arange<Float>(64);
Float b = arange<Float>(64) + 0.1f;
Float c = max(a, b);
Float d = fmadd(a, b, c);
auto mask = eq(b, c);
jitc_schedule(c, d, mask);
jitc_log(Info, "value=%s", c.str());
jitc_log(Info, "value=%s", d.str());
jitc_assert(all(mask));
jitc_llvm_set_target("skylake", "", 8);
}
TEST_LLVM(26_avx512_intrinsics, "avx512") {
jitc_llvm_set_target("skylake-avx512", "+avx512f,+avx512dq,+avx512vl", 32);
Float a = arange<Float>(64);
Float b = arange<Float>(64) + 0.1f;
Float c = max(a, b);
Float d = fmadd(a, b, c);
auto mask = eq(b, c);
jitc_schedule(c, d, mask);
jitc_log(Info, "value=%s", c.str());
jitc_log(Info, "value=%s", d.str());
jitc_assert(all(mask));
jitc_llvm_set_target("skylake", "", 8);
}
TEST_BOTH(27_avx512_intrinsics_round2int, "avx512") {
using Int64 = Array<int64_t>;
using UInt64 = Array<uint64_t>;
using Double = Array<double>;
jitc_llvm_set_target("skylake-avx512", "+avx512f,+avx512dq,+avx512vl", 32);
Float f(-1.1, -0.6f, -0.5f, -0.4f, 0.4f, 0.5f, 0.6f, 1.1, (float) 0xffffffff);
Double d(f);
jitc_eval();
{
auto f_i32 = ceil2int<Int32> (f);
auto f_u32 = ceil2int<UInt32>(f);
auto f_i64 = ceil2int<Int64> (f);
auto f_u64 = ceil2int<UInt64>(f);
auto d_i32 = ceil2int<Int32> (d);
auto d_u32 = ceil2int<UInt32>(d);
auto d_i64 = ceil2int<Int64> (d);
auto d_u64 = ceil2int<UInt64>(d);
jitc_schedule(f_i32, f_u32, f_i64, f_u64, d_i32, d_u32, d_i64, d_u64);
jitc_log(Info, "input=%s", f.str());
jitc_log(Info, "ceil_f_i32=%s", f_i32.str());
jitc_log(Info, "ceil_f_i64=%s", f_i64.str());
jitc_log(Info, "ceil_d_i32=%s", d_i32.str());
jitc_log(Info, "ceil_d_i64=%s", d_i64.str());
jitc_log(Info, "ceil_f_u32=%s", f_u32.str());
jitc_log(Info, "ceil_f_u64=%s", f_u64.str());
jitc_log(Info, "ceil_d_u32=%s", d_u32.str());
jitc_log(Info, "ceil_d_u64=%s", d_u64.str());
}
{
auto f_i32 = floor2int<Int32> (f);
auto f_u32 = floor2int<UInt32>(f);
auto f_i64 = floor2int<Int64> (f);
auto f_u64 = floor2int<UInt64>(f);
auto d_i32 = floor2int<Int32> (d);
auto d_u32 = floor2int<UInt32>(d);
auto d_i64 = floor2int<Int64> (d);
auto d_u64 = floor2int<UInt64>(d);
jitc_schedule(f_i32, f_u32, f_i64, f_u64, d_i32, d_u32, d_i64, d_u64);
jitc_log(Info, "input=%s", f.str());
jitc_log(Info, "floor_f_i32=%s", f_i32.str());
jitc_log(Info, "floor_f_i64=%s", f_i64.str());
jitc_log(Info, "floor_d_i32=%s", d_i32.str());
jitc_log(Info, "floor_d_i64=%s", d_i64.str());
jitc_log(Info, "floor_f_u32=%s", f_u32.str());
jitc_log(Info, "floor_f_u64=%s", f_u64.str());
jitc_log(Info, "floor_d_u32=%s", d_u32.str());
jitc_log(Info, "floor_d_u64=%s", d_u64.str());
}
{
auto f_i32 = trunc2int<Int32> (f);
auto f_u32 = trunc2int<UInt32>(f);
auto f_i64 = trunc2int<Int64> (f);
auto f_u64 = trunc2int<UInt64>(f);
auto d_i32 = trunc2int<Int32> (d);
auto d_u32 = trunc2int<UInt32>(d);
auto d_i64 = trunc2int<Int64> (d);
auto d_u64 = trunc2int<UInt64>(d);
jitc_schedule(f_i32, f_u32, f_i64, f_u64, d_i32, d_u32, d_i64, d_u64);
jitc_log(Info, "input=%s", f.str());
jitc_log(Info, "trunc_f_i32=%s", f_i32.str());
jitc_log(Info, "trunc_f_i64=%s", f_i64.str());
jitc_log(Info, "trunc_d_i32=%s", d_i32.str());
jitc_log(Info, "trunc_d_i64=%s", d_i64.str());
jitc_log(Info, "trunc_f_u32=%s", f_u32.str());
jitc_log(Info, "trunc_f_u64=%s", f_u64.str());
jitc_log(Info, "trunc_d_u32=%s", d_u32.str());
jitc_log(Info, "trunc_d_u64=%s", d_u64.str());
}
{
auto f_i32 = round2int<Int32> (f);
auto f_u32 = round2int<UInt32>(f);
auto f_i64 = round2int<Int64> (f);
auto f_u64 = round2int<UInt64>(f);
auto d_i32 = round2int<Int32> (d);
auto d_u32 = round2int<UInt32>(d);
auto d_i64 = round2int<Int64> (d);
auto d_u64 = round2int<UInt64>(d);
jitc_schedule(f_i32, f_u32, f_i64, f_u64, d_i32, d_u32, d_i64, d_u64);
jitc_log(Info, "input=%s", f.str());
jitc_log(Info, "round_f_i32=%s", f_i32.str());
jitc_log(Info, "round_f_i64=%s", f_i64.str());
jitc_log(Info, "round_d_i32=%s", d_i32.str());
jitc_log(Info, "round_d_i64=%s", d_i64.str());
jitc_log(Info, "round_f_u32=%s", f_u32.str());
jitc_log(Info, "round_f_u64=%s", f_u64.str());
jitc_log(Info, "round_d_u32=%s", d_u32.str());
jitc_log(Info, "round_d_u64=%s", d_u64.str());
}
jitc_llvm_set_target("skylake", "", 8);
}
TEST_BOTH(28_scatter_add, "avx512") {
jitc_llvm_set_target("skylake-avx512", "+avx512f,+avx512dq,+avx512vl,+avx512cd", 16);
using Double = Array<double>;
{
Float target = zero<Float>(16);
UInt32 index(0, 1, 2, 0, 4, 5, 6, 7, 8, 9, 10, 2, 3, 0, 0);
scatter_add(target, Float(1), index);
jitc_log(Info, "target=%s", target.str());
}
{
Float target = zero<Float>(16);
UInt32 index(0, 1, 2, 0, 4, 5, 6, 7, 8, 9, 10, 10, 2, 3, 0, 0);
scatter_add(target, Float(1), index);
jitc_log(Info, "target=%s", target.str());
}
{
Double target = zero<Double>(16);
UInt32 index(0, 1, 2, 0, 4, 5, 6, 7, 8, 9, 10, 2, 3, 0, 0);
scatter_add(target, Double(1), index);
jitc_log(Info, "target=%s", target.str());
}
{
Double target = zero<Double>(16);
UInt32 index(0, 1, 2, 0, 4, 5, 6, 7, 8, 9, 10, 10, 2, 3, 0, 0);
scatter_add(target, Double(1), index);
jitc_log(Info, "target=%s", target.str());
}
{
Float target = zero<Float>(16);
auto mask = arange<Float>(15) < 8.f;
UInt32 index(0, 1, 2, 0, 4, 5, 6, 7, 8, 9, 10, 2, 3, 0, 0);
scatter_add(target, Float(1), index, mask);
jitc_log(Info, "target=%s", target.str());
}
{
Float target = zero<Float>(16);
auto mask = arange<Float>(16) < 8.f;
UInt32 index(0, 1, 2, 0, 4, 5, 6, 7, 8, 9, 10, 10, 2, 3, 0, 0);
scatter_add(target, Float(1), index, mask);
jitc_log(Info, "target=%s", target.str());
}
{
Double target = zero<Double>(16);
auto mask = arange<Double>(15) < 8.f;
UInt32 index(0, 1, 2, 0, 4, 5, 6, 7, 8, 9, 10, 2, 3, 0, 0);
scatter_add(target, Double(1), index, mask);
jitc_log(Info, "target=%s", target.str());
}
{
Double target = zero<Double>(16);
UInt32 index(0, 1, 2, 0, 4, 5, 6, 7, 8, 9, 10, 10, 2, 3, 0, 0);
auto mask = arange<Double>(16) < 8.f;
scatter_add(target, Double(1), index, mask);
jitc_log(Info, "target=%s", target.str());
}
jitc_llvm_set_target("skylake", "", 8);
}
TEST_BOTH(29_arithmetic_propagation) {
{
UInt32 z(0), o(1);
jitc_assert( z.is_literal_zero());
jitc_assert(!z.is_literal_one());
jitc_assert(!o.is_literal_zero());
jitc_assert( o.is_literal_one());
UInt32 a = o + z;
UInt32 b = o * z;
jitc_assert(a.index() == o.index());
jitc_assert(b.index() == z.index());
}
{
using Int64 = Array<int64_t>;
Int64 z(0), o(1);
jitc_assert( z.is_literal_zero());
jitc_assert(!z.is_literal_one());
jitc_assert(!o.is_literal_zero());
jitc_assert( o.is_literal_one());
Int64 a = o + z;
Int64 b = o * z;
jitc_assert(a.index() == o.index());
jitc_assert(b.index() == z.index());
}
{
Float z(0), o(1);
jitc_assert( z.is_literal_zero());
jitc_assert(!z.is_literal_one());
jitc_assert(!o.is_literal_zero());
jitc_assert( o.is_literal_one());
Float a = o + z;
Float b = o * z;
jitc_assert(a.index() == o.index());
jitc_assert(b.index() == z.index());
}
{
using Double = Array<double>;
Double z(0), o(1);
jitc_assert( z.is_literal_zero());
jitc_assert(!z.is_literal_one());
jitc_assert(!o.is_literal_zero());
jitc_assert( o.is_literal_one());
Double a = o + z;
Double b = o * z;
jitc_assert(a.index() == o.index());
jitc_assert(b.index() == z.index());
}
}
TEST_BOTH(30_scatter_ordering) {
UInt32 x = zero<UInt32>(16),
y = x + 1;
UInt32 indices = UInt32(2, 4, 6);
scatter(x, UInt32(1), indices);
UInt32 z = x + 1;
jitc_log(Info, "x:%s", x.str());
jitc_log(Info, "y:%s", y.str());
jitc_log(Info, "z:%s", z.str());
}
TEST_BOTH(31_vcall) {
const char *domain = "MyKey";
uint32_t i0 = jitc_registry_put(domain, (void *) 0xA);
uint32_t i1 = jitc_registry_put(domain, (void *) 0xB);
uint32_t i2 = jitc_registry_put(domain, (void *) 0xC);
UInt32 pointers(i1, 0u, i1, i2, 0u, i1, i0, i0, i1, i2);
std::vector<std::pair<void *, UInt32>> perm = vcall(domain, pointers);
std::vector<std::pair<void *, UInt32>> perm_2 = vcall(domain, pointers);
jitc_assert(perm.size() == 4 && perm_2.size() == 4);
jitc_assert(perm[1].second.index() == perm_2[1].second.index());
jitc_assert(perm[2].second.index() == perm_2[2].second.index());
jitc_assert(perm[3].second.index() == perm_2[3].second.index());
jitc_assert(perm[1].first == (void *) 0x0A && perm_2[1].first == (void *) 0x0A);
jitc_assert(perm[2].first == (void *) 0x0B && perm_2[2].first == (void *) 0x0B);
jitc_assert(perm[3].first == (void *) 0x0C && perm_2[3].first == (void *) 0x0C);
jitc_assert(perm[0].second == UInt32(1, 4));
jitc_assert(perm[1].second == UInt32(6, 7));
jitc_assert(perm[2].second == UInt32(0, 2, 5, 8));
jitc_assert(perm[3].second == UInt32(3, 9));
jitc_registry_remove((void *) 0xA);
jitc_registry_remove((void *) 0xB);
jitc_registry_remove((void *) 0xC);
}
TEST_BOTH(32_sign_extension) {
int32_t i32 = -1;
uint32_t u32 = i32;
int64_t i64 = i32;
uint64_t u64 = i32;
using Int64 = Array<int64_t>;
using UInt64 = Array<uint64_t>;
Int32 a_i32(i32);
UInt32 a_u32(i32);
Int64 a_i64(i32);
UInt64 a_u64(i32);
jitc_assert(a_i32 == i32);
jitc_assert(a_u32 == u32);
jitc_assert(a_i64 == i64);
jitc_assert(a_u64 == u64);
}
TEST_BOTH(33_minmax_int) {
UInt32 s(2), l(3);
UInt32 minval = min(s, l);
UInt32 maxval = max(s, l);
jitc_eval(minval, maxval);
jitc_assert(minval == s);
jitc_assert(maxval == l);
}
TEST_BOTH(34_resize) {
{
UInt32 x = 1;
x += 1;
x.resize(3);
jitc_log(Info, "%s", x.str());
}
{
UInt32 x = 1, y = 1;
y = x + y;
x.resize(3);
jitc_log(Info, "%s", x.str());
}
{
UInt32 x = 1;
x.eval();
x.resize(3);
jitc_log(Info, "%s", x.str());
}
}
TEST_LLVM(35_pointer_registry_attribute) {
const char *domain = "MyKey";
for (int i = 1; i < 36; ++i)
jitc_registry_put(domain, (void *) (uintptr_t) i);
for (int i = 1; i < 36; ++i) {
float value = (float) i;
jitc_registry_set_attr((void *) (uintptr_t) i, "my_value", &value, sizeof(float));
}
float *ptr = (float *) jitc_registry_attr_data(domain, "my_value");
for (int i = 1; i < 36; ++i)
jitc_assert(ptr[jitc_registry_get_id((void *) (uintptr_t) i)] == i);
for (int i = 35; i >= 1; --i) {
float value = -(float) i;
jitc_registry_set_attr((void *) (uintptr_t) i, "my_value", &value, sizeof(float));
}
for (int i = 1; i < 36; ++i)
jitc_assert(ptr[jitc_registry_get_id((void *) (uintptr_t) i)] == -i);
for (int i = 35; i >= 10; --i)
jitc_registry_remove((void *) (uintptr_t) i);
jitc_registry_trim();
for (int i = 9; i >= 1; --i)
jitc_registry_remove((void *) (uintptr_t) i);
jitc_registry_trim();
#if !defined(_WIN32)
/// MSVC with /EHsc doesn't seem to like it if we throw a C++ exception through a C interface
bool success;
try {
ptr = (float *) jitc_registry_attr_data(domain, "my_value");
success = false;
} catch (...) {
success = true;
}
jitc_assert(success);
#endif
}
|
#ifndef _GUARD_BLOCK_SYSTEM_H
#define _GUARD_BLOCK_SYSTEM_H
#include <initializer_list>
#include <ostream>
#include <vector>
#include "perm.h"
#include "perm_group.h"
#include "perm_set.h"
namespace cgtl
{
class BlockSystem
{
friend std::ostream &operator<<(std::ostream &os, BlockSystem const &bs);
public:
struct Block : public std::vector<unsigned>
{
Block()
: std::vector<unsigned>()
{}
Block(std::initializer_list<unsigned> block)
: std::vector<unsigned>(block)
{}
Block permuted(Perm const &perm) const
{
Block res;
for (unsigned x : *this)
res.push_back(perm[x]);
return res;
}
Block shifted(unsigned shift) const
{
Block res;
for (unsigned x : *this)
res.push_back(x + shift);
return res;
}
Block unified(Block const &other) const
{
Block res;
res.resize(size() + other.size());
auto it = std::set_union(begin(), end(),
other.begin(), other.end(),
res.begin());
res.resize(it - res.begin());
return res;
}
};
using BlockIndices = std::vector<unsigned>;
using const_iterator = std::vector<Block>::const_iterator;
unsigned degree() const { return _degree; }
unsigned size() const { return static_cast<unsigned>(_blocks.size()); }
bool trivial() const;
Block const& operator[](unsigned i) const;
const_iterator begin() const;
const_iterator end() const;
unsigned block_index(unsigned x) const;
PermSet block_permuter(PermSet const &generators) const;
static PermSet block_stabilizers(PermSet const &generators,
Block const &block);
static BlockSystem minimal(PermSet const &generators,
std::vector<unsigned> const &initial_block);
static std::vector<BlockSystem> non_trivial(PermGroup const &pg,
bool assume_transitivity = false);
private:
template<typename IT>
BlockSystem(IT first, IT last)
: _blocks(first, last)
{
_degree = 0u;
for (IT it = first; it != last; ++it) {
for (unsigned x : *it)
_degree = std::max(_degree, x);
}
_block_indices = std::vector<unsigned>(_degree);
for (unsigned i = 0u; i < size(); ++i) {
for (unsigned x : (*this)[i])
_block_indices[x - 1u] = i;
}
assert_blocks();
assert_block_indices();
}
BlockSystem(BlockIndices const &block_indices);
void assert_blocks() const;
void assert_block_indices() const;
static bool is_block(PermSet const &generators, Block const &block);
static BlockSystem from_block(PermSet const &generators, Block const &block);
static unsigned minimal_find_rep(unsigned k,
std::vector<unsigned> &classpath);
static bool minimal_merge_classes(unsigned k1,
unsigned k2,
std::vector<unsigned> &classpath,
std::vector<unsigned> &cardinalities,
std::vector<unsigned> &queue);
static void minimal_compress_classpath(std::vector<unsigned> &classpath);
static std::vector<BlockSystem> non_trivial_transitive(PermGroup const &pg);
static std::vector<BlockSystem> non_trivial_non_transitive(PermGroup const &pg);
static std::vector<Block> non_trivial_find_representatives(
PermSet const &generators,
std::vector<std::vector<BlockSystem>> const &partial_blocksystems,
std::vector<unsigned> const &domain_offsets);
static std::vector<BlockSystem> non_trivial_from_representatives(
PermSet const &generators,
std::vector<Block> const &representatives);
unsigned _degree;
std::vector<Block> _blocks;
std::vector<unsigned> _block_indices;
};
std::ostream &operator<<(std::ostream &os, BlockSystem const &bs);
} // namespace cgtl
#endif // _GUARD_BLOCK_SYSTEM_H
|
// 两种操作 m = s; s = s +s
// s = s + m
// 从一个初始字符串'a'长到固定长度需要多少次运算
#include <iostream>
#include <queue>
#include <map>
using namespace std;
typedef pair<int,int> pii;
map<pair<int,int> , int > mp;
int main()
{
int n;
cin>>n;
queue<pii> q;
q.push(make_pair(1, 1));
mp[make_pair(1,1)]=0;
while(!q.empty())
{
pii pr = q.front();
q.pop();
if(pr.first == n)
{
cout<<mp[pr]<<endl;
exit(0);
}
pii t=pr;
t.second = t.first; t.first*=2;
if(!mp.count(t))
{
q.push(t);
mp[t] = mp[pr]+1;
}
t=pr;
t.first=t.first+t.second;
if(!mp.count(t))
{
q.push(t);
mp[t] = mp[pr]+1;
}
}
return 0;
}
|
#pragma once
#include "Cell.h"
class WaterCell : public Cell
{
public:
WaterCell() : Cell(char(178)) {}
virtual ~WaterCell() {}
WaterCell(size_t Row, size_t Column) : Cell(Row, Column, char(178)) {}
WaterCell(const WaterCell& other) : Cell(other) {}
virtual Cell* Clone() const { return new WaterCell(*this); }
};
|
#include "vwindow.h"
#include "ui_vwindow.h"
vWindow::vWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::vWindow)
{
ui->setupUi(this);
//connect signals/slots
connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(closeDB()));
connect(ui->tableView, SIGNAL(pressed(QModelIndex)), this, SLOT(chooseTable(QModelIndex)));
connect(ui->actionConnect_via_ODBC, SIGNAL(triggered()), this, SLOT(login()));
connect(ui->actionExit, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(ui->actionExport_to_CSV, SIGNAL(triggered()), this, SLOT(exportCSV()));
connect(ui->queryButton, SIGNAL(pressed()), this, SLOT(queryDatabase()));
//model with field info
fieldModel = new QSqlQueryModel(this);
//model with table info
model = new QSqlQueryModel(this);
//attempt to open DB
db = QSqlDatabase::addDatabase("QODBC");
//attempt to login database
login();
/*
//only for when testing w/o ODBC connection
this->show();
*/
}
vWindow::~vWindow()
{
db.close();
delete ui;
//delete model;
//delete fieldModel;
}
void vWindow::slotAcceptUserLogin(QString &databaseName, QString &DSN)
{
//qDebug() << databaseName << DSN;
currentDSN = DSN;
currentDBname = databaseName;
db.setDatabaseName(DSN);
QString testQry = tr("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='%1'").arg(databaseName);
//qDebug() << testQry;
if(db.open())
{
ui->label_DSN->setText(DSN);
ui->label_database->setText(databaseName);
//"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='netflix'"
model->setQuery(testQry);
ui->tableView->setModel(model);
this->show();
chooseTable(model->index(0,0));
}
else
{
int ret = QMessageBox::warning(this, tr("Connect to ODBC"), tr("Failure: %1").arg(db.lastError().text()), QMessageBox::Cancel);
db.close();
login();
}
}
void vWindow::closeDB()
{
db.close();
}
void vWindow::chooseTable(QModelIndex item)
{
currentTableName = model->data(item).toString();
//qDebug() << data << item;
ui->label_table->setText(currentTableName);
QString qry = tr("SELECT * FROM %1").arg(currentTableName);
fieldModel->setQuery(qry);
ui->tableView_2->setModel(fieldModel);
//qDebug() << qry;
}
void vWindow::login()
{
//login
LoginDialog* loginDialog = new LoginDialog( this );
connect( loginDialog,
SIGNAL(acceptLogin(QString&,QString&)),
this,
SLOT(slotAcceptUserLogin(QString&,QString&)));
connect(loginDialog, SIGNAL(aborted()), this, SLOT(loginAborted()));
loginDialog->exec();
}
void vWindow::reLogin()
{
//clear old data
model->clear();
fieldModel->clear();
db.removeDatabase(currentDBname);
//login
login();
}
void vWindow::exportCSV()
{
//get field names from SQL table
QStringList fieldNames = getFieldNames();
/*
//test field names (for w/o ODBC connection)
QStringList testList;
testList.append("First");
testList.append("Second");
testList.append("Third");
testList.append("Fourth");
testList.append("Fifth");
testList.append("Sixth");
*/
//open field mapping dialog
mapWindow *mapper = new mapWindow(currentDSN, currentDBname, fieldNames, fieldModel, this);
mapper->show();
}
QStringList vWindow::getFieldNames()
{
//get number of columns
int colCount = fieldModel->columnCount();
//collect field names and return
QStringList fNames;
for(int i = 0; i < colCount; i++)
{
fNames.append(fieldModel->headerData(i,Qt::Horizontal).toString());
}
return fNames;
}
void vWindow::loginAborted()
{
if(!this->isVisible())
this->show();
}
void vWindow::queryDatabase()
{
if(!currentDBname.isEmpty() && !currentDSN.isEmpty())
{
queryWindow *query = new queryWindow(currentDSN, currentDBname, currentTableName, this);
query->show();
}
else
QMessageBox::warning(this, tr("Query Database"), tr("Failure: No ODBC Connection"), QMessageBox::Cancel);
}
|
/*
* main2.cpp
*
* Created on: Dec 1, 2019
* Author: lucas
*/
#include <list>
#include "mbed.h" // Librería mbed
#include "FreeRTOS.h" // Definiciones principales de FreeRTOS
#include "task.h" // Funciones para el control de las tareas
#include "semphr.h" // Semaforos y mutex
#include "definitions.h"
#include "STR.h"
#include "STRTask.h"
// Funciones
void thread1(void*);
void eatCpu(TickType_t ticks);
void useSharedResource(TickType_t duration);
// Variables globales
Serial pc(USBTX, USBRX); // tx, rx
std::list<Task> selectedTasks;
SemaphoreHandle_t xSemaphore = 0;
int main() {
// Creacion de tareas
selectedTasks.push_back(Task("t1", 3, 2, 4, 4));
selectedTasks.push_back(Task("t2", 2, 1, 5, 5));
selectedTasks.push_back(Task("t3", 1, 1, 6, 6));
// Initializes the trace recorder, but does not start the tracing.
vTraceEnable( TRC_INIT);
// Creacion del mutex
xSemaphore = xSemaphoreCreateMutex(); // @suppress("Function cannot be resolved")
int index = 0;
pc.printf("Cargando tareas...\n\r");
// Creacion de tareas
for (Task task : selectedTasks) {
xTaskCreate(thread1, task.getName(), 256, (void*) index,
task.getPriority(), NULL);
index++;
}
pc.printf("Tareas cargadas...\n\r");
// Starts the tracing.
vTraceEnable( TRC_START);
pc.printf("Comenzando Scheduler...\n\r");
vTaskStartScheduler();
for (;;)
;
}
void thread1(void *params) {
int index = (int) params;
// Recuperar la tarea en ejecucion
std::list<Task>::const_iterator it = selectedTasks.begin();
std::advance(it, index);
const Task *currentTask = &(*it);
TickType_t previous = 0;
for (;;) {
pc.printf("Ejecutando tarea %s\n\r", currentTask->getName());
if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) { // @suppress("Invalid arguments")
pc.printf("La tarea %s hace uso del recurso compartido\n\r",
currentTask->getName());
useSharedResource(currentTask->getC() * 1000);
xSemaphoreGive(xSemaphore); // @suppress("Invalid arguments")
}
// Bloquearse hasta la proxima instancia
vTaskDelayUntil(&previous, currentTask->getT() * 1000);
}
}
void eatCpu(TickType_t ticks) {
TickType_t current = 0;
TickType_t previousTicks = 0;
TickType_t currentTicks = xTaskGetTickCount();
while (current < ticks) {
currentTicks = xTaskGetTickCount();
if (previousTicks < currentTicks) {
current++;
previousTicks = currentTicks;
}
}
}
void useSharedResource(TickType_t duration) {
eatCpu(duration);
}
|
#ifndef BLOCKCHAIN_BLOCK_H
#define BLOCKCHAIN_BLOCK_H
#include <cstdint>
#include <iostream>
#include <ctime>
#include <sstream>
#include <vector>
#include <iterator>
#include "Transaction.h"
using namespace std;
class Block {
public:
string previousHash;
Block(vector<Transaction> transactions);
string GetHash();
void MineBlock(uint32_t difficulty);
private:
int64_t _nonce;
vector<Transaction> _transactions;
string _hash;
time_t _time;
string _CalculateHash() const;
};
#endif //BLOCKCHAIN_BLOCK_H
|
#include "QFrameLessWidget_Alime.h"
#include <QLayout>
#include <QPushButton>
#include <QListWidget>
#include <QLabel>
#include <QProgressBar>
CLASSREGISTER(QFrameLessWidget_Alime)
QFrameLessWidget_Alime::QFrameLessWidget_Alime(QWidget *parent)
: Alime_ContentWidget(parent)
{
QHBoxLayout* contentLayout = new QHBoxLayout(this);
QWidget* leftContent = new QWidget(this);
QWidget* rightContent = new QWidget(this);
contentLayout->addWidget(leftContent);
contentLayout->addWidget(rightContent);
contentLayout->setMargin(0);
contentLayout->setSpacing(0);
contentLayout->setStretch(0, 1);
contentLayout->setStretch(1, 4);
leftContent->setObjectName("leftContent");
//leftContent->setFixedWidth(240);
rightContent->setObjectName("rightContent");
QVBoxLayout* leftLayout = new QVBoxLayout(leftContent);
leftLayout->setMargin(0);
QPushButton* btn01 = new QPushButton("click me");
btn01->setObjectName("btnBoard");
btn01->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
leftLayout->addWidget(btn01);
QPushButton* btn02 = new QPushButton("click me");
btn02->setObjectName("btnBoard");
leftLayout->addWidget(btn02);
btn02->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QPushButton* btn03= new QPushButton("click me");
btn03->setObjectName("btnBoard");
btn03->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
leftLayout->addWidget(btn03);
QPushButton* btn04 = new QPushButton("click me");
btn04->setObjectName("btnBoard");
btn04->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
leftLayout->addWidget(btn04);
QVBoxLayout* vbox = new QVBoxLayout(rightContent);
//vbox->setMargin(20);//setMargin只有box才能用,指定box到父widget的边距
vbox->setContentsMargins(10, 0, 0, 0);//
vbox->setSpacing(0);
setContentsMargins(10, 10, 10, 10);//这一句是widget内部所有内容的边距
vbox->addWidget(new QPushButton("fuck1"));
vbox->addWidget(new QPushButton("fuck2"));
vbox->addStretch(1);
}
#include <QPainter>
#include <QPainterPath>
void QFrameLessWidget_Alime::paintEvent(QPaintEvent* event)
{
//Alime_ContentWidget::paintEvent(event);
QPainter painter(this);
painter.drawLine(80, 100, 650, 500);
painter.setPen(Qt::red);
painter.drawRect(10, 10, 100, 400);
painter.setPen(QPen(Qt::green, 5));
painter.setBrush(Qt::blue);
painter.drawEllipse(50, 150, 400, 200);
QBrush brush;
brush.setStyle(Qt::SolidPattern);
brush.setColor(QColor(255,0,0));
painter.setPen(Qt::DotLine);
painter.setBrush(brush);
painter.drawEllipse(0,0,
200, 200);
painter.setRenderHint(QPainter::Antialiasing);
QPainterPath path;
auto w = width();
path.addEllipse(w / 2, height() / 2, width(), height());
painter.setClipPath(path);
painter.drawPixmap(QRect(width() / 2, height() / 2, width(), height()),
QPixmap(":/images/min-128.png"));
}
|
#include <bits/stdc++.h>
using namespace std;
#define f first
#define s second
#define pb push_back
#define rep(i, begin, end) \
for (__typeof(end) i = (begin) - ((begin) > (end)); \
i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define db(x) cout << '>' << #x << ':' << x << endl;
#define sz(x) ((int)(x).size())
#define newl cout << "\n"
#define ll long long int
#define vi vector<int>
#define vll vector<long long>
#define vvll vector<vll>
#define pll pair<long long, long long>
#define fast_io() \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
const int mxN = 2e5 + 5;
const int mxM = 2e5 + 7;
const int lg = 22;
ll n, m, tc, q;
ll arr[4*mxN+5];
ll pref[4*mxN+5];
struct node {
vector<ll> v = {};
vector<ll> vp = {};
};
node seg[4*mxN+5];
void build(ll i, ll l, ll r) {
if(l == r) {
seg[i].v.pb(arr[l]);
seg[i].vp.pb(arr[l]);
return;
}
ll m = (l+r)/2;
build(i<<1, l, m);
build(i<<1^1, m+1, r);
node temp = seg[i<<1];
for(auto x:seg[i<<1^1].v) {
ll prev = temp.v.back();
auto y = x;
if(prev - x > 0) y += abs(prev-x);
temp.v.pb(y);
temp.vp.pb(y+temp.vp.back());
}
seg[i] = temp;
}
pair<ll, ll> query(ll ql, ll qr, ll i, ll l, ll r) {
if(qr < l|| r < ql) {
return {0, 0};
}
if(ql <= l && r <= qr) {
return {seg[i].v.back(), seg[i].vp.back()};
}
ll m = (l+r)/2;
auto left = query(ql, qr, i<<1, l, m);
auto right = query(ql, qr, i<<1^1, m+1, r);
// combine;
ll mergesum = 0;
int z = min(r, qr) - (m+1) + 1;
if(z <= 0) return {max(left.f, right.f), left.s+right.s};
auto it = lower_bound(seg[i<<1^1].v.begin(), seg[i<<1^1].v.begin()+(z-1), left.f);
int ind = it-seg[i<<1^1].v.begin();
if(ind >= 0 && ind < z) {
while(ind >= 0 && seg[i<<1^1].v[ind] >= left.f) ind--;
}
// ind last el < left.f;
if(ind >= 0) {
mergesum = (ind+1)*left.f - (ind >= 0 ? seg[i<<1^1].vp[ind] : 0);
}
return {max(left.f, right.f), left.s +right.s + mergesum};
}
ll qry(ll ql, ll qr) {
auto [mx, sum] = query(ql, qr, 1, 1, n);
return sum - (pref[qr]-pref[ql-1]);
}
int main() {
fast_io();
#ifndef ONLINE_JUDGE
freopen("../input.txt", "r", stdin);
freopen("../output.txt", "w", stdout);
#endif
cin>>n>>q;
rep(i, 1, n+1) {
cin>>arr[i];
pref[i] = pref[i-1]+arr[i];
}
build(1, 1, n);
while(q--) {
ll a, b; cin>>a>>b;
ll ans = qry(a, b);
cout<<ans;
newl;
}
return 0;
}
|
/* -*- 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 Arjan van Leeuwen (arjanl)
*/
#ifndef MOCK_CUPS_FUNCTIONS_H
#define MOCK_CUPS_FUNCTIONS_H
#ifdef SELFTEST
#include "platforms/quix/printing/CupsFunctions.h"
class MockCupsFunctions : public CupsFunctions
{
public:
MockCupsFunctions()
: printfile_dest(0)
, printfile_file(0)
, printfile_job(0)
{
s_functions = this;
cupsPrintFile = &PrintFile;
}
static int PrintFile(const char* destname, const char* filename, const char* title, int num_options, cups_option_t* options)
{
s_functions->printfile_dest = destname;
s_functions->printfile_file = filename;
s_functions->printfile_job = title;
for (int i = 0; i < num_options; i++)
{
Option* option = OP_NEW(Option, ());
option->name.Set(options[i].name);
option->value.Set(options[i].value);
s_functions->printfile_options.Add(option);
}
return 1;
}
const char* GetOptionValue(const char* name)
{
for (unsigned i = 0; i < printfile_options.GetCount(); i++)
{
if (printfile_options.Get(i)->name.Compare(name) == 0)
return printfile_options.Get(i)->value.CStr();
}
return 0;
}
const char* printfile_dest;
const char* printfile_file;
const char* printfile_job;
private:
struct Option
{
OpString8 name;
OpString8 value;
};
OpAutoVector<Option> printfile_options;
static MockCupsFunctions* s_functions;
};
MockCupsFunctions* MockCupsFunctions::s_functions = 0;
#endif // SELFTEST
#endif // MOCK_CUPS_FUNCTIONS_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef VEGAIMAGE_H
#define VEGAIMAGE_H
#ifdef VEGA_SUPPORT
#include "modules/libvega/vegafill.h"
#include "modules/libvega/vegatransform.h"
#include "modules/libvega/src/vegabackend.h"
#include "modules/libvega/src/vegaswbuffer.h"
enum VEGAImageBufferFlags
{
// NOTE: An opacity value will be stored in the lower 8 bits, so
// don't store flags there.
BUF_NONE = 0,
BUF_OPAQUE = 1 << 8,
BUF_PREMULTIPLIED = 1 << 9
};
class VEGABackingStore;
#ifdef USE_PREMULTIPLIED_ALPHA
#define DEFAULT_PREMULTIPLIED true
#else
#define DEFAULT_PREMULTIPLIED false
#endif // USE_PREMULTIPLIED_ALPHA
class VEGAImage : public VEGAFill
{
public:
VEGAImage();
~VEGAImage();
virtual OP_STATUS prepare();
virtual void apply(VEGAPixelAccessor color, struct VEGASpanInfo& span);
virtual void complete();
#ifdef VEGA_OPPAINTER_SUPPORT
static OP_STATUS drawImage(VEGASWBuffer* buf, int dx, int dy, int width, int height,
VEGASWBuffer* srcbuf, const struct VEGADrawImageInfo& imginfo,
unsigned flags);
/** Determine if this VEGAImage (in its current configuration) can
* be simplified to a blit-operation for the destination rectangle
* set in diinfo. */
bool simplifiesToBlit(struct VEGADrawImageInfo& diinfo, bool tilingSupported);
#ifdef VEGA_USE_BLITTER_FOR_NONPIXELALIGNED_IMAGES
/** Check if this VEGAImage can be sent to the blitter. */
bool allowBlitter(VEGA_FIX dstx, VEGA_FIX dsty, VEGA_FIX dstw, VEGA_FIX dsth) const;
#endif // VEGA_USE_BLITTER_FOR_NONPIXELALIGNED_IMAGES
/** Fills in the src-rect of diinfo based on the dst-rect and the
current ransform. No validation of the src-rect is performed,
so it might be zero-sized or point outside of the image.
Width and height of this image is returned as well */
bool prepareDrawImageInfo(struct VEGADrawImageInfo& diinfo, int& width, int& height, bool checkIfGridAligned);
#endif // VEGA_OPPAINTER_SUPPORT
OP_STATUS init(OpBitmap* bmp);
OP_STATUS init(VEGABackingStore* store, bool premultiplied = DEFAULT_PREMULTIPLIED);
#ifdef VEGA_3DDEVICE
/** Mainly for internal usage (creating image from intermediate render target etc). */
OP_STATUS init(VEGA3dTexture* tex, bool premultiplied = DEFAULT_PREMULTIPLIED);
#endif // VEGA_3DDEVICE
static void calcTransforms(const struct VEGADrawImageInfo& imginfo, VEGATransform& trans, VEGATransform& itrans, const VEGATransform* ctm = NULL);
virtual void setTransform(const VEGATransform& pathTrans, const VEGATransform& invPathTrans)
{
VEGAFill::setTransform(pathTrans, invPathTrans);
is_aligned_and_nonscaled = invPathTrans.isAlignedAndNonscaled();
is_simple_translation = invPathTrans.isIntegralTranslation();
if (is_simple_translation)
{
int_xlat_x = VEGA_TRUNCFIXTOINT(invPathTransform[2]);
int_xlat_y = VEGA_TRUNCFIXTOINT(invPathTransform[5]);
}
}
#ifdef VEGA_3DDEVICE
virtual VEGA3dTexture* getTexture();
#endif // VEGA_3DDEVICE
/** Limits the visible area of an image. Rendering
* outside this area will give undefined results,
* so be carefull when using this. */
OP_STATUS limitArea(int left, int top, int right, int bottom);
bool hasPremultipliedAlpha() { return is_premultiplied_alpha; }
void makePremultiplied();
bool isImage() const { return true; }
#ifdef VEGA_OPPAINTER_SUPPORT
bool isOpaque() const { return is_opaque; }
void setOpaque(bool opaque) { is_opaque = opaque; }
bool isIndexed() const { return !!backingstore->IsIndexed(); }
VEGASWBuffer* GetSWBuffer(){return &imgbuf;}
#endif // VEGA_OPPAINTER_SUPPORT
VEGABackingStore* GetBackingStore() { return backingstore; }
private:
void applyAligned(VEGAPixelAccessor color, int sx, int sy, unsigned length);
#ifdef VEGA_OPPAINTER_SUPPORT
static void drawAligned(VEGASWBuffer* buf, int dx, int dy, int width, int height,
VEGASWBuffer* srcbuf, int sx, int sy, unsigned flags);
static void drawScaledNearest(VEGASWBuffer* buf, int dx, int dy, int width, int height,
VEGASWBuffer* srcbuf, const struct VEGAImageSamplerParams& params,
unsigned flags);
static OP_STATUS drawScaledBilinear(VEGASWBuffer* buf, int dx, int dy, int width, int height,
VEGASWBuffer* srcbuf, const struct VEGAImageSamplerParams& params,
unsigned flags);
static void drawAlignedIndexed(VEGASWBuffer* buf, int dx, int dy, int width, int height,
VEGASWBuffer* srcbuf, int sx, int sy,
unsigned flags);
static void drawScaledNearestIndexed(VEGASWBuffer* buf, int dx, int dy, int width, int height,
VEGASWBuffer* srcbuf, const struct VEGAImageSamplerParams& params,
unsigned flags);
static OP_STATUS drawScaledBilinearIndexed(VEGASWBuffer* buf, int dx, int dy, int width, int height,
VEGASWBuffer* srcbuf, const struct VEGAImageSamplerParams& params,
unsigned flags);
#endif // VEGA_OPPAINTER_SUPPORT
void releaseBuffers();
VEGABackingStore* backingstore;
VEGASWBuffer imgbuf;
bool imgbuf_need_free;
bool is_premultiplied_alpha;
bool is_aligned_and_nonscaled;
bool is_simple_translation;
bool is_opaque;
OpBitmap* bitmap;
int int_xlat_x;
int int_xlat_y;
#ifdef VEGA_3DDEVICE
VEGA3dTexture* texture;
#endif // VEGA_3DDEVICE
};
#undef DEFAULT_PREMULTIPLIED
// Sufficient tolerance - should be deduced from the rasterizer accuracy (which is variable :/)
#define VEGA_GRID_TOLERANCE (VEGA_INTTOFIX(1) / 32)
static inline bool IsGridAligned(VEGA_FIX x, VEGA_FIX y)
{
return
VEGA_ABS(x - VEGA_TRUNCFIX(x)) < VEGA_GRID_TOLERANCE &&
VEGA_ABS(y - VEGA_TRUNCFIX(y)) < VEGA_GRID_TOLERANCE;
}
#endif // VEGA_SUPPORT
#endif // VEGAIMAGE_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; 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.
*/
#include "core/pch.h"
#include "adjunct/desktop_util/file_chooser/file_chooser_fun.h"
#include "modules/prefs/prefsmanager/collections/pc_files.h"
#include "modules/viewers/viewers.h"
OP_STATUS FileChooserUtil::SavePreferencePath(const DesktopFileChooserRequest::Action action, const DesktopFileChooserResult& result)
{
#ifndef PREFS_NO_WRITE
if (result.files.GetCount() > 0 && result.files.Get(0)->HasContent())
{
OpFileFolder folder = OPFILE_OPEN_FOLDER;
if (action == DesktopFileChooserRequest::ACTION_FILE_SAVE ||
action == DesktopFileChooserRequest::ACTION_FILE_SAVE_PROMPT_OVERWRITE)
folder = OPFILE_SAVE_FOLDER;
OpFile file;
RETURN_IF_ERROR(file.Construct(*result.files.Get(0)));
OpString directory;
OpFileInfo::Mode mode;
RETURN_IF_ERROR(file.GetMode(mode));
if(mode == OpFileInfo::DIRECTORY)
RETURN_IF_ERROR(directory.Set(file.GetFullPath()));
else
RETURN_IF_ERROR(file.GetDirectory(directory));
TRAPD(rc, g_pcfiles->WriteDirectoryL(folder, directory));
if (OpStatus::IsError(rc))
return rc;
}
#endif
return OpStatus::OK;
}
OP_STATUS FileChooserUtil::CopySettings(const DesktopFileChooserRequest& src, DesktopFileChooserRequest*& copy)
{
OpAutoPtr<DesktopFileChooserRequest> tmp(OP_NEW(DesktopFileChooserRequest, ()));
if (!tmp.get())
return OpStatus::ERR_NO_MEMORY;
OP_STATUS rc = copy->caption.Set(src.caption);
if (OpStatus::IsSuccess(rc))
{
rc = copy->initial_path.Set(src.initial_path);
if (OpStatus::IsSuccess(rc))
{
for (UINT32 i = 0; i < src.extension_filters.GetCount(); i++)
{
OpFileSelectionListener::MediaType* filter = src.extension_filters.Get(i);
rc = CopyAddMediaType(filter, &tmp.get()->extension_filters, FALSE);
if (OpStatus::IsError(rc))
break;
}
}
}
if (OpStatus::IsError(rc))
return rc;
copy = tmp.release();
copy->action = src.action;
copy->initial_filter = src.initial_filter;
copy->get_selected_filter = src.get_selected_filter;
copy->fixed_filter = src.fixed_filter;
return OpStatus::OK;
}
INT32 FileChooserUtil::FindExtension(const OpStringC& ext, OpVector<OpFileSelectionListener::MediaType>* filters)
{
OpString extension;
extension.Set(ext);
if (extension.Find(UNI_L("*.")) == KNotFound)
extension.Insert(0 , UNI_L("*."));
if (filters)
{
for (UINT32 i = 0; i < filters->GetCount(); i++)
{
OpFileSelectionListener::MediaType* filter = filters->Get(i);
for (UINT32 j = 0; j < filter->file_extensions.GetCount(); j++)
{
OpString s;
if (filter->file_extensions.Get(j)->Find(UNI_L("*.")) == KNotFound)
{
s.Set(UNI_L("*."));
s.Append(filter->file_extensions.Get(j)->CStr());
}
else
{
s.Set(filter->file_extensions.Get(j)->CStr());
}
if (extension.CompareI(s) == 0)
{
return i;
}
}
}
}
return -1;
}
void FileChooserUtil::Reset(DesktopFileChooserRequest& request)
{
request.action = DesktopFileChooserRequest::ACTION_FILE_OPEN;
request.caption.Empty();
request.initial_path.Empty();
request.extension_filters.DeleteAll();
request.initial_filter = 0;
request.get_selected_filter = FALSE;
request.fixed_filter = FALSE;
}
OP_STATUS FileChooserUtil::AppendExtensionInfo(OpFileSelectionListener::MediaType& media_type)
{
if (media_type.media_type.Find(UNI_L("(")) != KNotFound)
return OpStatus::OK;
RETURN_IF_ERROR(media_type.media_type.Append(UNI_L(" (")));
if (!media_type.file_extensions.GetCount())
RETURN_IF_ERROR(media_type.media_type.Append(UNI_L("*.*")));
else
{
for (UINT32 i = 0; i < media_type.file_extensions.GetCount(); i++)
{
if (i > 0)
RETURN_IF_ERROR(media_type.media_type.Append(UNI_L(",")));
RETURN_IF_ERROR(media_type.media_type.Append(media_type.file_extensions.Get(i)->CStr()));
}
}
return media_type.media_type.Append(UNI_L(")"));
}
OP_STATUS FileChooserUtil::GetInitialExtension(const DesktopFileChooserRequest &request, OpString& initial_extension)
{
if ((UINT32)request.initial_filter > request.extension_filters.GetCount())
return OpStatus::ERR;
else
return initial_extension.Set(*request.extension_filters.Get(request.initial_filter)->file_extensions.Get(0));
}
OP_STATUS FileChooserUtil::SetExtensionFilter(const uni_char* string_filter, OpAutoVector<OpFileSelectionListener::MediaType> * extension_filters)
{
OpFileSelectionListener::MediaType* ext_filter;
OP_STATUS rc = OpStatus::OK;
OpString* filter;
const uni_char * begin_interval = string_filter;
const uni_char * end_interval = string_filter ? uni_strchr(string_filter, '|') : NULL;
extension_filters->DeleteAll();
while(begin_interval && end_interval && end_interval > begin_interval)
{
ext_filter = OP_NEW(OpFileSelectionListener::MediaType, ());
if (!ext_filter)
return OpStatus::ERR_NO_MEMORY;
rc = ext_filter->media_type.Append(begin_interval, end_interval - begin_interval);
if (OpStatus::IsError(rc))
{
OP_DELETE(ext_filter);
return rc;
}
begin_interval = end_interval + 1;
end_interval = uni_strchr(begin_interval, '|');
if (end_interval && end_interval > begin_interval)
{
end_interval = uni_strpbrk(begin_interval, UNI_L("|;"));
while (begin_interval && end_interval && end_interval > begin_interval)
{
filter = OP_NEW(OpString, ());
if (!filter)
{
OP_DELETE(ext_filter);
return OpStatus::ERR_NO_MEMORY;
}
rc = filter->Append(begin_interval, end_interval - begin_interval);
if (OpStatus::IsError(rc))
{
OP_DELETE(ext_filter);
OP_DELETE(filter);
return rc;
}
rc = ext_filter->file_extensions.Add(filter);
if (OpStatus::IsError(rc))
{
OP_DELETE(ext_filter);
OP_DELETE(filter);
return rc;
}
begin_interval = end_interval + 1;
if (*end_interval == '|')
break;
else
end_interval = uni_strpbrk(begin_interval, UNI_L("|;"));
}
}
rc = extension_filters->Add(ext_filter);
if (OpStatus::IsError(rc))
{
OP_DELETE(ext_filter);
end_interval = NULL;
}
end_interval = uni_strchr(begin_interval, '|');
}
return rc;
}
OP_STATUS FileChooserUtil::AddMediaType(const OpFileSelectionListener::MediaType* filter, OpAutoVector<OpFileSelectionListener::MediaType>* list, BOOL add_asterix_dot)
{
if (!filter)
return OpStatus::OK;
OpFileSelectionListener::MediaType* filter_copy = OP_NEW(OpFileSelectionListener::MediaType, ());
if (!filter_copy || OpStatus::IsError(filter_copy->media_type.Set(filter->media_type)))
{
OP_DELETE(filter_copy);
return OpStatus::ERR_NO_MEMORY;
}
for (UINT32 i = 0; i < filter->file_extensions.GetCount(); i++)
{
OpString* s = OP_NEW(OpString,());
if (!s || OpStatus::IsError(s->Set(*filter->file_extensions.Get(i))))
{
OP_DELETE(filter_copy);
OP_DELETE(s);
return OpStatus::ERR_NO_MEMORY;
}
if (add_asterix_dot && s->Compare(UNI_L("*")) && s->Compare(UNI_L("*."), 2))
{
if (OpStatus::IsError(s->Insert(0, UNI_L("*."))))
{
OP_DELETE(filter_copy);
OP_DELETE(s);
return OpStatus::ERR_NO_MEMORY;
}
}
if (OpStatus::IsError(filter_copy->file_extensions.Add(s)))
{
OP_DELETE(filter_copy);
OP_DELETE(s);
return OpStatus::ERR_NO_MEMORY;
}
}
if (OpStatus::IsError(list->Add(filter_copy)))
{
OP_DELETE(filter_copy);
return OpStatus::ERR_NO_MEMORY;
}
return OpStatus::OK;
}
INT32 FindExtension(const OpStringC& extension, OpVector<OpFileSelectionListener::MediaType>* filters)
{
return FileChooserUtil::FindExtension(extension, filters);
}
void ResetDesktopFileChooserRequest(DesktopFileChooserRequest& request)
{
FileChooserUtil::Reset(request);
}
OP_STATUS ExtendMediaTypeWithExtensionInfo(OpFileSelectionListener::MediaType& media_type)
{
return FileChooserUtil::AppendExtensionInfo(media_type);
}
OP_STATUS GetInitialExtension(const DesktopFileChooserRequest& request, OpString& extension)
{
return FileChooserUtil::GetInitialExtension(request, extension);
}
OP_STATUS StringFilterToExtensionFilter(const uni_char* string_filter, OpAutoVector<OpFileSelectionListener::MediaType> * extension_filters)
{
return FileChooserUtil::SetExtensionFilter(string_filter, extension_filters);
}
OP_STATUS CopyAddMediaType(const OpFileSelectionListener::MediaType* filter, OpAutoVector<OpFileSelectionListener::MediaType>* list, BOOL add_asterix_dot)
{
return FileChooserUtil::AddMediaType(filter, list, add_asterix_dot);
}
|
// RotatedEllipseIntersectDlg.cpp : implementation file
//
#include "stdafx.h"
#include "RotatedEllipseIntersect.h"
#include "RotatedEllipseIntersectDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CRotatedEllipseIntersectDlg dialog
CRotatedEllipseIntersectDlg::CRotatedEllipseIntersectDlg(CWnd* pParent /*=NULL*/)
: CDialog(CRotatedEllipseIntersectDlg::IDD, pParent)
{
ellipse.dRadiusX = 100;
ellipse.dRadiusY = 50;
ellipse.ptCenter.x = 200;
ellipse.ptCenter.y = 200;
ellipse.dAngle = 30;
line.pt1.x = 0;
line.pt1.y = 50;
line.pt2.x = 300;
line.pt2.y = 500;
pt1.x = 0;
pt1.y = 0;
pt2.x = 0;
pt2.y = 0;
bTouches;
bIntersects;
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CRotatedEllipseIntersectDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_ERX, ellipse.dRadiusX);
DDX_Text(pDX, IDC_ERY, ellipse.dRadiusY);
DDX_Text(pDX, IDC_EAR, ellipse.dAngle);
DDX_Text(pDX, IDC_ECX, ellipse.ptCenter.x);
DDX_Text(pDX, IDC_ECY, ellipse.ptCenter.y);
DDX_Text(pDX, IDC_L1X, line.pt1.x);
DDX_Text(pDX, IDC_L1Y, line.pt1.y);
DDX_Text(pDX, IDC_L2X, line.pt2.x);
DDX_Text(pDX, IDC_L2Y, line.pt2.y);
DDX_Text(pDX, IDC_R1X, pt1.x);
DDX_Text(pDX, IDC_R1Y, pt1.y);
DDX_Text(pDX, IDC_R2X, pt2.x);
DDX_Text(pDX, IDC_R2Y, pt2.y);
//{{AFX_DATA_MAP(CRotatedEllipseIntersectDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CRotatedEllipseIntersectDlg, CDialog)
//{{AFX_MSG_MAP(CRotatedEllipseIntersectDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_MOUSEMOVE()
ON_WM_LBUTTONUP()
ON_WM_LBUTTONDOWN()
ON_BN_CLICKED(IDC_RECALC, OnRecalc)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CRotatedEllipseIntersectDlg message handlers
BOOL CRotatedEllipseIntersectDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
OnRecalc();
return TRUE; // return TRUE unless you set the focus to a control
}
void CRotatedEllipseIntersectDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CRotatedEllipseIntersectDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
CClientDC dc(this); // device context for painting
CGdiObject *pBrushOld = dc.SelectStockObject(NULL_BRUSH);
for (int x = 0; x < 6; ++ x)
{
CPen pen(PS_DOT, 1, RGB(100, 100, 100));
CPen *pPenOld = dc.SelectObject(&pen);
dc.MoveTo(50+100*x, 50);
dc.LineTo(50+100*x,550);
dc.MoveTo( 50, 50+100*x);
dc.LineTo(550, 50+100*x);
dc.SelectObject(pPenOld);
}
DrawRotatedEllipse(&dc, ellipse, 50, 50);
dc.Ellipse( 50+(int)ellipse.ptCenter.x-2, 50+(int)ellipse.ptCenter.y-2,
50+(int)ellipse.ptCenter.x+2, 50+(int)ellipse.ptCenter.y+2);
dc.MoveTo(50+(int)line.pt1.x, 50+(int)line.pt1.y);
dc.LineTo(50+(int)line.pt2.x, 50+(int)line.pt2.y);
if (bIntersects || bTouches)
{
CPen pen(PS_SOLID, 1, RGB(255, 0, 0));
CPen *pPenOld = dc.SelectObject(&pen);
dc.Ellipse( 50+(int)pt2.x-7, 50+(int)pt2.y-7,
50+(int)pt2.x+7, 50+(int)pt2.y+7);
dc.Ellipse( 50+(int)pt1.x-5, 50+(int)pt1.y-5,
50+(int)pt1.x+5, 50+(int)pt1.y+5);
dc.SelectObject(pPenOld);
}
dc.SelectObject(pBrushOld);
}
}
HCURSOR CRotatedEllipseIntersectDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CRotatedEllipseIntersectDlg::OnMouseMove(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CDialog::OnMouseMove(nFlags, point);
}
void CRotatedEllipseIntersectDlg::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CDialog::OnLButtonUp(nFlags, point);
}
void CRotatedEllipseIntersectDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CDialog::OnLButtonDown(nFlags, point);
}
void CRotatedEllipseIntersectDlg::OnRecalc()
{
UpdateData();
bTouches = false;
bIntersects = IntersectEllipseWithLine(ellipse, line, pt1, pt2, bTouches);
if (!bIntersects)
{
pt1.x = pt1.y = pt2.x = pt2.y = 0;
}
UpdateData(FALSE);
Invalidate();
}
|
#include "eccezioni.h"
string eccezioni::to_string_error() const{
return error;
}
|
#include <cstddef>
#include <cstdio>
#include "macs.hpp"
#include "macs-internals.hpp"
using namespace macs;
using namespace macs::internals;
using namespace macs::types;
namespace macs
{
namespace internals
{
shader *basic_vertex_shader;
program *basic_pipeline;
}
}
shader::shader(type t)
{
id = glCreateShader(static_cast<int>(t));
dbgprintf("[sh%u] Is %s shader.\n", id, (t == vertex) ? "vertex" : "fragment");
}
shader::~shader(void)
{
glDeleteShader(id);
delete src;
dbgprintf("[sh%u] Deleted.\n", id);
}
void shader::load(const char *srcb)
{
glShaderSource(id, 1, &srcb, NULL);
dbgprintf("[sh%u] Loaded shader from source\n", id);
src = strdup(srcb);
}
void shader::load(FILE *fp)
{
fseek(fp, 0, SEEK_END);
long length = ftell(fp);
rewind(fp);
char *mem = new char[length + 1];
fread(mem, 1, length, fp);
mem[length] = 0;
glShaderSource(id, 1, const_cast<const char **>(&mem), NULL);
src = strdup(mem);
delete mem;
dbgprintf("[sh%u] Loaded shader from file\n", id);
}
bool shader::compile(void)
{
glCompileShader(id);
int status;
glGetShaderiv(id, GL_COMPILE_STATUS, &status);
if (status == GL_TRUE)
dbgprintf("[sh%u] Compilation successful.\n", id);
else
dbgprintf("[sh%u] Compilation failed.\n", id);
int illen;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &illen);
if (illen > 1)
{
char *msg = new char[illen + 1];
glGetShaderInfoLog(id, illen, NULL, msg);
msg[illen] = 0; // inb4 implementation bug
if (status == GL_TRUE)
dbgprintf("[sh%u] Shader compile message: %s", id, msg);
else
{
fprintf(stderr, "[sh%u] Shader compile message: %s", id, msg);
fprintf(stderr, "[sh%u] Shader source was:\n", id);
const char *s = src;
int line = 1;
while (*s)
{
fprintf(stderr, "%4i ", line);
while (*s && (*s != '\n'))
fputc(*(s++), stderr);
fputc('\n', stderr);
line++;
if (*s)
s++;
}
}
delete msg;
}
return status == GL_TRUE;
}
program::program(void)
{
id = glCreateProgram();
dbgprintf("[pr%u] Created.\n", id);
}
program::~program(void)
{
glDeleteProgram(id);
dbgprintf("[pr%u] Deleted.\n", id);
}
void program::attach(shader *sh)
{
glAttachShader(id, sh->id);
dbgprintf("[pr%u] Attached shader sh%u.\n", id, sh->id);
}
bool program::link(void)
{
glLinkProgram(id);
int status;
glGetProgramiv(id, GL_LINK_STATUS, &status);
if (status == GL_TRUE)
dbgprintf("[pr%u] Linking successful.\n", id);
else
dbgprintf("[pr%u] Linking failed.\n", id);
int illen;
glGetProgramiv(id, GL_INFO_LOG_LENGTH, &illen);
if (illen > 1)
{
char *msg = new char[illen + 1];
glGetShaderInfoLog(id, illen, NULL, msg);
msg[illen] = 0; // inb4 implementation bug
if (status == GL_TRUE)
dbgprintf("[pr%u] Program link message: %s", id, msg);
else
fprintf(stderr, "[pr%u] Program link message: %s", id, msg);
delete msg;
}
return status == GL_TRUE;
}
void program::use(void)
{
glUseProgram(id);
// dbgprintf("[pr%u] Active.\n", id);
}
prg_uniform program::uniform(const char *name)
{
return prg_uniform(glGetUniformLocation(id, name));
}
prg_uniform::prg_uniform(unsigned uni_id):
id(uni_id)
{
}
void prg_uniform::operator=(const in *o) throw(exc::invalid_type, exc::texture_not_assigned)
{
switch (o->i_type)
{
case in::t_texture:
case in::t_texture_array:
for (int i = 0; i < tex_units; i++)
{
if ((*tmu_mgr)[i] == o)
{
glUniform1i(id, i);
return;
}
}
throw exc::tex_na;
case in::t_vec4:
glUniform4fv(id, 1, (**static_cast<const named<vec4> *>(o)).d);
return;
case in::t_vec3:
glUniform3fv(id, 1, (**static_cast<const named<vec3> *>(o)).d);
return;
case in::t_vec2:
glUniform2fv(id, 1, (**static_cast<const named<vec2> *>(o)).d);
return;
case in::t_mat4:
glUniformMatrix4fv(id, 1, false, (**static_cast<const named<mat4> *>(o)).d);
return;
case in::t_mat3:
glUniformMatrix3fv(id, 1, false, (**static_cast<const named<mat3> *>(o)).d);
return;
case in::t_float:
glUniform1f(id, **static_cast<const named<float> *>(o));
return;
case in::t_bool:
glUniform1i(id, **static_cast<const named<bool> *>(o));
return;
}
throw exc::inv_type;
}
|
#include "stdafx.h"
#include "TypeInQuestion.h"
#include "TypeInQuestionView.h"
#include "TypeInQuestionState.h"
using namespace qp;
CTypeInQuestionView::CTypeInQuestionView(ITypeInQuestionStatePtr const& questionState, std::ostream & outputStream, std::istream & inputStream)
:CQuestionView(questionState, outputStream, inputStream)
,m_questionState(questionState)
{
}
CTypeInQuestionView::~CTypeInQuestionView()
{
}
void CTypeInQuestionView::ShowDetails()
{
auto & outputStream = GetOutputStream();
std::string userAnswer = m_questionState->GetUserAnswer();
if (!userAnswer.empty())
{
outputStream << "Your answer: '";
outputStream << userAnswer << "'\n";
}
if (m_questionState->Submitted())
{
auto const& review = m_questionState->GetReview();
if (!review.AnswerIsCorrect())
{
outputStream << "Right answer(s): ";
std::set<std::string> const& answers = m_questionState->GetConcreteQuestion()->GetAnswers();
for (auto i : answers)
{
outputStream << "'" << i << "'\n";
}
}
}
}
void CTypeInQuestionView::ShowPrompt()
{
auto & outputStream = GetOutputStream();
if (m_questionState->Submitted())
{
outputStream << "Press Enter to go to the next question or type 'exit': ";
}
else
{
outputStream << "Enter an answer or type 'submit' or 'skip': ";
}
}
void CTypeInQuestionView::ShowReview()
{
auto & outputStream = GetOutputStream();
auto const& review = m_questionState->GetReview();
if (review.AnswerIsCorrect())
{
outputStream << "Answer is correct. Score: " << review.GetAwardedScore() << "\n";
}
else
{
outputStream << "Answer is not correct.\n";
}
}
bool CTypeInQuestionView::ProcessString(std::string const& inputString)
{
if (!CQuestionView::ProcessString(inputString))
{
if (inputString == "")
{
return false;
}
else
{
m_onAnswerEntered(inputString);
}
}
return true;
}
Connection CTypeInQuestionView::DoOnAnswerEntered(const OnAnswerEnteredSlotType & answerEnteredHandler)
{
return m_onAnswerEntered.connect(answerEnteredHandler);
}
|
#pragma once
#include <string>
std::string say_hello();
std::string say_goodbye();
|
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
This example code is in the public domain.
*/
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
const int ena = 9;
const int in1 = 8;
const int in2 = 7;
const int enb = 3;
const int in3 = 5;
const int in4 = 4;
const int x_joystick = A0;
const int y_joystick = A1;
const int joystick_low = 0;
const int joystick_high = 1023;
const int motorLow = 0;
const int motorHigh = 255;
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(ena, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(enb, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
}
void demo1(){
digitalWrite(ena, HIGH);
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
analogWrite(ena, 200);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
analogWrite(enb, 200);
delay(2000);
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
delay(2000);
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
}
void demo2(){
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
for(int i=0; i <256 ; ++i){
analogWrite(ena, i);
analogWrite(enb, i);
delay(20);
}
for(int i=255; i > 0 ; --i){
analogWrite(ena, i);
analogWrite(enb, i);
delay(20);
}
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
}
void joystick_motor(){
int xreading = analogRead(x_joystick);
int yreading = analogRead(y_joystick);
}
void loop() {
demo1();
delay(1000);
demo2();
delay(1000);
}
|
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*-
*
* Copyright (C) 1995-2005 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#ifdef XPATH_SUPPORT
#include "modules/xpath/src/xpscan.h"
#include "modules/xpath/src/xpstep.h"
XPath_Scan::XPath_Scan (XPath_XMLTreeAccessorFilter **filters, unsigned filters_count)
: filters (filters),
filters_count (filters_count),
current_nodes (0)
{
}
XMLTreeAccessor::Node *
XPath_Scan::Prepare (XMLTreeAccessor *tree, XMLTreeAccessor::Node *origin)
{
filters[current_index]->SetFilter (tree);
if (current_index != 0)
{
for (unsigned index = current_index; index != 0;)
if (XMLTreeAccessor::Node *node = current_nodes[--index])
{
tree->SetStopAtFilter (node);
break;
}
}
if (XMLTreeAccessor::Node *last_match = current_nodes[current_index])
return last_match;
else
return origin;
}
XMLTreeAccessor::Node *
XPath_Scan::Handle (XMLTreeAccessor *tree, XMLTreeAccessor::Node *result, BOOL &finished)
{
tree->ResetFilters ();
finished = FALSE;
if ((current_nodes[current_index] = result) != 0)
{
if (current_index + 1 == filters_count)
return result;
else
{
++current_index;
return 0;
}
}
else if (++current_index == filters_count)
{
while (current_index != 0)
if (current_nodes[--current_index])
{
XMLTreeAccessor::Node *node = current_nodes[current_index];
for (unsigned index = current_index + 1; index < filters_count; ++index)
current_nodes[index] = node;
return node;
}
finished = TRUE;
return 0;
}
else
return 0;
}
/* static */ XPath_Scan *
XPath_Scan::MakeL (XPath_XMLTreeAccessorFilter **filters, unsigned filters_count)
{
XPath_Scan *scan = OP_NEW_L (XPath_Scan, (filters, filters_count));
scan->current_nodes = OP_NEWA (XMLTreeAccessor::Node *, filters_count);
if (!scan->current_nodes)
{
OP_DELETE (scan);
LEAVE (OpStatus::ERR_NO_MEMORY);
}
scan->Reset ();
return scan;
}
XPath_Scan::~XPath_Scan ()
{
OP_DELETEA (current_nodes);
}
XMLTreeAccessor::Node *
XPath_Scan::GetParent (XMLTreeAccessor *tree, XMLTreeAccessor::Node *child)
{
if (initial)
{
initial = FALSE;
XMLTreeAccessor::Node *parent = tree->GetParent (child);
for (unsigned index = 0; index < filters_count; ++index)
{
filters[index]->SetFilter (tree);
BOOL include = tree->FilterNode (parent);
tree->ResetFilters ();
if (include)
return parent;
}
}
return 0;
}
XMLTreeAccessor::Node *
XPath_Scan::GetAncestor (XMLTreeAccessor *tree, XMLTreeAccessor::Node *descendant)
{
XMLTreeAccessor::Node *node;
BOOL finished;
while (!(node = Handle (tree, tree->GetAncestor (Prepare (tree, descendant)), finished)) && !finished);
return node;
}
XMLTreeAccessor::Node *
XPath_Scan::GetAncestorOrSelf (XMLTreeAccessor *tree, XMLTreeAccessor::Node *descendant)
{
if (initial)
{
initial = FALSE;
for (unsigned index = 0; index < filters_count; ++index)
{
filters[index]->SetFilter (tree);
BOOL include = tree->FilterNode (descendant);
tree->ResetFilters ();
if (include)
return descendant;
}
}
return GetAncestor (tree, descendant);
}
XMLTreeAccessor::Node *
XPath_Scan::GetPrecedingSibling (XMLTreeAccessor *tree, XMLTreeAccessor::Node *sibling)
{
XMLTreeAccessor::Node *node;
BOOL finished;
while (!(node = Handle (tree, tree->GetPreviousSibling (Prepare (tree, sibling)), finished)) && !finished);
return node;
}
XMLTreeAccessor::Node *
XPath_Scan::GetChild (XMLTreeAccessor *tree, XMLTreeAccessor::Node *parent)
{
XMLTreeAccessor::Node *node;
BOOL finished;
do
{
XMLTreeAccessor::Node *origin = Prepare (tree, parent);
if (origin == parent)
node = tree->GetFirstChild (origin);
else
node = tree->GetNextSibling (origin);
}
while (!(node = Handle (tree, node, finished)) && !finished);
return node;
}
XMLTreeAccessor::Node *
XPath_Scan::GetDescendant (XMLTreeAccessor *tree, XMLTreeAccessor::Node *ancestor)
{
XMLTreeAccessor::Node *node;
BOOL finished;
while (!(node = Handle (tree, tree->GetNextDescendant (Prepare (tree, ancestor), ancestor), finished)) && !finished);
return node;
}
void
XPath_Scan::Reset ()
{
current_index = 0;
initial = TRUE;
op_memset (current_nodes, 0, filters_count * sizeof *current_nodes);
}
#endif // XPATH_SUPPORT
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "modules/hardcore/mem/mem_man.h"
#include "modules/display/colconv.h"
#include "modules/pi/OpBitmap.h"
#include "modules/pi/OpPainter.h"
#include "modules/img/image.h"
#ifdef VEGA_OPPAINTER_SUPPORT
#include "modules/libvega/src/oppainter/vegaopbitmap.h"
#endif
typedef UINT32 FIXED1616;
#define TO_FIXED(a) (FIXED1616)(a * 65536)
#define FROM_FIXED(a) (UINT32(a) >> 16)
#ifdef DISPLAY_FALLBACK_PAINTING
#ifdef USE_PREMULTIPLIED_ALPHA
#error "Does not support premultiplied alpha yet"
#endif // USE_PREMULTIPLIED_ALPHA
/**
// Contains a system wich examines the painter and bitmaps supported functions
// and selects the fastest way to do things. (f.eks. blitting with alpha)
// If you gets a crash in this file send me a mail (emil@opera.com)
// Uses 16.16 fixedpoint to speed things up. Especially on older machines with slow FPU's
*/
typedef void (*BlitFunctionScaled)(UINT32* src, UINT32* dst, UINT32 len, FIXED1616 dx);
typedef void (*BlitFunction)(UINT32* src, UINT32* dst, UINT32 len);
// == 8 bit deph functions =============================================
// 8bpp to 8bpp
void BlitHLineCopyScaled8(UINT32* src32, UINT32* dst32, UINT32 len, FIXED1616 dx)
{
UINT8* src8 = (UINT8*) src32;
UINT8* dst8 = (UINT8*) dst32;
FIXED1616 fx = 0;
for(UINT32 i = 0; i < len; i++)
{
*dst8 = src8[FROM_FIXED(fx)];
dst8++;
fx += dx;
}
}
// == 16 bit deph functions (BGR 565) =============================================
// 16bpp to 16bpp
void BlitHLineCopyScaled16(UINT32* src32, UINT32* dst32, UINT32 len, FIXED1616 dx)
{
UINT16* src16 = (UINT16*) src32;
UINT16* dst16 = (UINT16*) dst32;
FIXED1616 fx = 0;
for(UINT32 i = 0; i < len; i++)
{
*dst16 = src16[FROM_FIXED(fx)];
dst16++;
fx += dx;
}
}
// 16bpp to 16bpp
void BlitHLineCopy16(UINT32* src32, UINT32* dst32, UINT32 len)
{
op_memcpy(dst32, src32, len * 2);
}
// 32bpp to 16bpp
void BlitHLineAlphaScaled16(UINT32* src32, UINT32* dst32, UINT32 len, FIXED1616 dx)
{
UINT16* dst16 = (UINT16*) dst32;
FIXED1616 fx = 0;
for(UINT32 i = 0; i < len; i++)
{
UINT8* srccol = (UINT8*) &src32[FROM_FIXED(fx)];
UINT32 alpha = srccol[3];
UINT8 dstcol[3] = { COL_565_R(*dst16), COL_565_G(*dst16), COL_565_B(*dst16) };
dstcol[0] = dstcol[0] + (alpha * (srccol[0] - dstcol[0])>>8); // Blue
dstcol[1] = dstcol[1] + (alpha * (srccol[1] - dstcol[1])>>8); // Green
dstcol[2] = dstcol[2] + (alpha * (srccol[2] - dstcol[2])>>8); // Red
*dst16 = COL_8888_TO_565( (*((UINT32*)&dstcol[0])) );
dst16++;
fx += dx;
}
}
// 32bpp to 16bpp
void BlitHLineAlpha16(UINT32* src32, UINT32* dst32, UINT32 len)
{
UINT8* src = (UINT8*) src32;
UINT16* dst16 = (UINT16*) dst32;
for(UINT32 i = 0; i < len; i++)
{
UINT8 dstcol[3] = { COL_565_R(*dst16), COL_565_G(*dst16), COL_565_B(*dst16) };
UINT32 alpha = src[3];
dstcol[0] = dstcol[0] + (alpha * (src[0] - dstcol[0])>>8); // Blue
dstcol[1] = dstcol[1] + (alpha * (src[1] - dstcol[1])>>8); // Green
dstcol[2] = dstcol[2] + (alpha * (src[2] - dstcol[2])>>8); // Red
*dst16 = COL_8888_TO_565( (*((UINT32*)&dstcol[0])) );
dst16++;
src += 4;
}
}
// 32bpp to 16bpp
void BlitHLineTransparentScaled16(UINT32* src32, UINT32* dst32, UINT32 len, FIXED1616 dx)
{
UINT16* dst16 = (UINT16*) dst32;
FIXED1616 fx = 0;
for(UINT32 i = 0; i < len; i++)
{
UINT32 srccol = src32[FROM_FIXED(fx)];
if (((UINT8*)&srccol)[3]) // Check the alpha value
dst16[i] = COL_8888_TO_565( srccol );
fx += dx;
}
}
// 32bpp to 16bpp
void BlitHLineTransparent16(UINT32* src32, UINT32* dst32, UINT32 len)
{
UINT16* dst16 = (UINT16*) dst32;
for(UINT32 i = 0; i < len; i++)
{
if (((UINT8*)src32)[3]) // Check the alpha value
dst16[i] = COL_8888_TO_565( *src32 );
src32 ++;
}
}
// == 24 bit deph functions (BGR) =============================================
// 24bpp to 24bpp
void BlitHLineCopyScaled24(UINT32* src32, UINT32* dst32, UINT32 len, FIXED1616 dx)
{
UINT8* dst = (UINT8*) dst32;
FIXED1616 fx = 0;
for(UINT32 i = 0; i < len; i++)
{
UINT32 col = src32[FROM_FIXED(fx)];
dst[0] = ((UINT8*)&col)[0];
dst[1] = ((UINT8*)&col)[1];
dst[2] = ((UINT8*)&col)[2];
dst += 3;
fx += dx;
}
}
// 24bpp to 24bpp
void BlitHLineCopy24(UINT32* src32, UINT32* dst32, UINT32 len)
{
op_memcpy(dst32, src32, len * 3);
}
// 32bpp to 24bpp
void BlitHLineAlphaScaled24(UINT32* src32, UINT32* dst32, UINT32 len, FIXED1616 dx)
{
UINT8* dst = (UINT8*) dst32;
FIXED1616 fx = 0;
for(UINT32 i = 0; i < len; i++)
{
UINT8* srccol = (UINT8*) &src32[FROM_FIXED(fx)];
UINT32 alpha = srccol[3];
dst[0] = dst[0] + (alpha * (srccol[0] - dst[0])>>8); // Blue
dst[1] = dst[1] + (alpha * (srccol[1] - dst[1])>>8); // Green
dst[2] = dst[2] + (alpha * (srccol[2] - dst[2])>>8); // Red
dst += 3;
fx += dx;
}
}
// 32bpp to 24bpp
void BlitHLineAlpha24(UINT32* src32, UINT32* dst32, UINT32 len)
{
UINT8* src = (UINT8*) src32;
UINT8* dst = (UINT8*) dst32;
for(UINT32 i = 0; i < len; i++)
{
UINT32 alpha = src[3];
dst[0] = dst[0] + (alpha * (src[0] - dst[0])>>8); // Blue
dst[1] = dst[1] + (alpha * (src[1] - dst[1])>>8); // Green
dst[2] = dst[2] + (alpha * (src[2] - dst[2])>>8); // Red
dst += 3;
src += 4;
}
}
// 32bpp to 24bpp
void BlitHLineTransparentScaled24(UINT32* src32, UINT32* dst32, UINT32 len, FIXED1616 dx)
{
UINT8* dst = (UINT8*) dst32;
FIXED1616 fx = 0;
for(UINT32 i = 0; i < len; i++)
{
UINT32 col = src32[FROM_FIXED(fx)];
if (((UINT8*)&col)[3]) // Check the alpha value
{
dst[0] = ((UINT8*)&col)[0];
dst[1] = ((UINT8*)&col)[1];
dst[2] = ((UINT8*)&col)[2];
}
dst += 3;
fx += dx;
}
}
// 32bpp to 24bpp
void BlitHLineTransparent24(UINT32* src32, UINT32* dst32, UINT32 len)
{
UINT8* src8 = (UINT8*) src32;
UINT8* dst8 = (UINT8*) dst32;
for(UINT32 i = 0; i < len; i++)
{
if (src8[3]) // Check the alpha value
{
dst8[0] = src8[0];
dst8[1] = src8[1];
dst8[2] = src8[2];
}
dst8 += 3;
src8 += 4;
}
}
// == 32 bit deph functions (BGRA) =============================================
// 32bpp to 32bpp
void BlitHLineCopyScaled32(UINT32* src32, UINT32* dst32, UINT32 len, FIXED1616 dx)
{
FIXED1616 fx = 0;
for(UINT32 i = 0; i < len; i++)
{
dst32[i] = src32[FROM_FIXED(fx)];
fx += dx;
}
}
// 32bpp to 32bpp
void BlitHLineCopy32(UINT32* src32, UINT32* dst32, UINT32 len)
{
op_memcpy(dst32, src32, len * 4);
}
// 32bpp to 32bpp
void BlitHLineAlphaScaled32(UINT32* src32, UINT32* dst32, UINT32 len, FIXED1616 dx)
{
// Endianness-independent:
FIXED1616 fx = 0;
for(UINT32 i = 0; i < len; i++)
{
UINT32 *srccol = &src32[FROM_FIXED(fx)];
int alpha = *srccol >> 24;
unsigned char d = *dst32;
UINT32 blue = d + (alpha * ((*srccol & 0xff) - d)>>8);
d = *dst32 >> 8;
UINT32 green = d + (alpha * (((*srccol >> 8) & 0xff) - d)>>8);
d = *dst32 >> 16;
UINT32 red = d + (alpha * (((*srccol >> 16) & 0xff) - d)>>8);
d = *dst32 >> 24;
alpha = d + (alpha * (( 0xff) - d)>>8);
*dst32++ = blue | (green << 8) | (red << 16) | (alpha << 24);
fx += dx;
}
}
#ifdef REALLY_UGLY_COLOR_HACK
// 32bpp to 32bpp
void BlitHLineAlpha32UglyColorHack(UINT32* src32, UINT32* dst32, UINT32 len)
{
// Endianness-independent way of doing it:
for (UINT32 i=0; i<len; i++)
{
UINT32 src = *src32++;
int alpha = src >> 24;
if (*dst32 == REALLY_UGLY_COLOR)
{
if (alpha)
{
*dst32 = src;
}
*dst32++;
}
else
{
unsigned char d = *dst32;
UINT32 blue = d + (alpha * (((src ) & 0xff) - d)>>8);
d = *dst32 >> 8;
UINT32 green = d + (alpha * (((src >> 8) & 0xff) - d)>>8);
d = *dst32 >> 16;
UINT32 red = d + (alpha * (((src >> 16) & 0xff) - d)>>8);
d = *dst32 >> 24;
alpha = d + (alpha * (( 0xff) - d)>>8);
*dst32++ = blue | (green << 8) | (red << 16) | (alpha << 24);
}
}
}
#endif // REALLY_UGLY_COLOR_HACK
// 32bpp to 32bpp
void BlitHLineAlpha32(UINT32* src32, UINT32* dst32, UINT32 len)
{
// Endianness-independent way of doing it:
for (UINT32 i=0; i<len; i++)
{
UINT32 src = *src32++;
int alpha = src >> 24;
unsigned char d = *dst32;
UINT32 blue = d + (alpha * (((src ) & 0xff) - d)>>8);
d = *dst32 >> 8;
UINT32 green = d + (alpha * (((src >> 8) & 0xff) - d)>>8);
d = *dst32 >> 16;
UINT32 red = d + (alpha * (((src >> 16) & 0xff) - d)>>8);
d = *dst32 >> 24;
alpha = d + (alpha * (( 0xff) - d)>>8);
*dst32++ = blue | (green << 8) | (red << 16) | (alpha << 24);
}
}
// 32bpp to 32bpp
void BlitHLineTransparentScaled32(UINT32* src32, UINT32* dst32, UINT32 len, FIXED1616 dx)
{
// Little-endian:
FIXED1616 fx = 0;
for(UINT32 i = 0; i < len; i++)
{
UINT32 srccol = src32[FROM_FIXED(fx)];
// Wich one is fastest ?
if (srccol & 0xFF000000) // Check the alpha value, works on all machines
dst32[i] = srccol;
fx += dx;
}
}
// 32bpp to 32bpp
void BlitHLineTransparent32(UINT32* src32, UINT32* dst32, UINT32 len)
{
for(UINT32 i = 0; i < len; i++)
{
// Wich one is fastest ?
if (*src32 & 0xFF000000) // Check the alpha value, works on all machines
*dst32 = *src32;
dst32 ++;
src32 ++;
}
}
// Blits srcbitmap to dstbitmap using the given blitfunction.
void DrawBitmapClipped(OpBitmap* srcbitmap, OpBitmap* dstbitmap,
const OpRect &source,
const OpPoint &destpoint,
BlitFunction bltfunc)
{
UINT8* line = (UINT8*) dstbitmap->GetPointer();
UINT8* src = (UINT8*) srcbitmap->GetPointer();
OP_ASSERT(line != NULL);
if(line == NULL)
{
return; // Should not happen!
}
int src_bpp = srcbitmap->GetBpp();
int dst_bpp = dstbitmap->GetBpp();
int src_bypp = src_bpp == 15 ? 2 : src_bpp >> 3;
int dst_bypp = dst_bpp == 15 ? 2 : dst_bpp >> 3;
int x = destpoint.x;
int y = destpoint.y;
int src_bpl = srcbitmap->GetBytesPerLine();
src = &src[source.x * src_bypp + (source.y * src_bpl)]; // Move sourcepointer to match sourcerect
int xlen = source.width;
if(x < 0) // Clip to the left
{
src += (0-x) * src_bypp;
xlen -= 0-x;
x = 0;
}
if (x < (int)dstbitmap->Width())
{
if (x + xlen > (int)dstbitmap->Width()) // Clip to the right
{
xlen -= (x + xlen) - dstbitmap->Width();
}
// Run from top to bottom and call the horizontal blitfunction each row
int dst_h = dstbitmap->Height();
int dst_bpl = dstbitmap->GetBytesPerLine();
for (int i = 0; i < source.height; i++)
{
if (i + y >= 0 && i + y < dst_h) // Clipping
{
UINT32* dstpek = (UINT32*) &line[x * dst_bypp + (y + i) * dst_bpl];
UINT32* srcpek = (UINT32*) src;
bltfunc(srcpek, dstpek, xlen);
}
src += src_bpl;
}
}
dstbitmap->ReleasePointer();
srcbitmap->ReleasePointer();
}
// Blits srcbitmap to dstbitmap using the given blitfunction.
void DrawBitmapClippedScaled(OpBitmap* srcbitmap, OpBitmap* dstbitmap,
const OpRect &source,
const OpRect &dest,
BlitFunctionScaled bltfunc)
{
UINT8* line = (UINT8*) dstbitmap->GetPointer();
UINT8* src = (UINT8*) srcbitmap->GetPointer();
int src_bypp = srcbitmap->GetBpp() == 15 ? 2 : srcbitmap->GetBpp() >> 3;
int dst_bypp = dstbitmap->GetBpp() == 15 ? 2 : dstbitmap->GetBpp() >> 3;
int x = dest.x;
int y = dest.y;
int src_bpl = srcbitmap->GetBytesPerLine();
src = &src[source.x * src_bypp + source.y * src_bpl]; // Move sourcepointer to match sourcerect
int xlen = dest.width;
int subpixelsize = 0;
int dst_w = dstbitmap->Width();
int dst_h = dstbitmap->Height();
if (x < 0) // Clip to the left
{
int oldx = x;
src += int(float(-x) * float(source.width)/float(dest.width)) * src_bypp;
xlen -= -x;
x = 0;
// Calculate subpixel accurcy. (If an image is uupscaled and positioned on x<0, the first pixel may
// be smaller than the rest. Theirfore we need a special case for the first pixel each row.
float segmentsize = float(dest.width)/float(source.width);
float xtemp = float(-oldx) / segmentsize;
subpixelsize = (int)(segmentsize - float(xtemp - int(xtemp)) * segmentsize);
subpixelsize+=2;
if(subpixelsize == int(segmentsize))
subpixelsize = 0;
}
if(x >= dst_w) // Extreme case
{
dstbitmap->ReleasePointer();
srcbitmap->ReleasePointer();
return;
}
if (x + xlen > dst_w) // Clip to the right
{
xlen -= (x + xlen) - dst_w;
}
FIXED1616 sy = 0; // Where we are and reads pixels
FIXED1616 dx = (source.width << 16) / dest.width; //Calculate the values we must step with, in order to get
FIXED1616 dy = (source.height << 16) / dest.height; //the right pixels from the sourcebitmap.
// Run from top to bottom and call the horizontal blitfunction each row
int dst_bpl = dstbitmap->GetBytesPerLine();
for (int i = 0; i < dest.height; i++)
{
if (i + y >= 0 && i + y < dst_h) // Clipping
{
int xofs = 0;
int srcxofs = 0;
int pixels_to_blit = xlen;
BOOL skip_rest = FALSE;
if(subpixelsize != 0) // If the first pixel is smaller than the others case
{
// Make sure we don't blit more than we should
int sublength = subpixelsize;
if(sublength > xlen)
sublength = xlen;
UINT32* dstpek = (UINT32*) &line[x * dst_bypp + (y + i) * dst_bpl];
UINT32* srcpek = (UINT32*) &src[int(sy >> 16) * src_bpl];
bltfunc(srcpek, dstpek, sublength, dx);
// Offset the values, so that the rest of the pixels is placed right.
srcxofs = 1;
xofs = (int)sublength;
pixels_to_blit -= sublength;
if(pixels_to_blit <= 0)
skip_rest = TRUE;
}
if(skip_rest == FALSE) // Blit the rest
{
UINT32* dstpek = (UINT32*) &line[(x + xofs) * dst_bypp + (y + i) * dst_bpl];
UINT32* srcpek = (UINT32*) &src[srcxofs * src_bypp + int(sy >> 16) * src_bpl];
bltfunc(srcpek, dstpek, pixels_to_blit, dx);
}
}
sy += dy;
}
dstbitmap->ReleasePointer();
srcbitmap->ReleasePointer();
}
// Blits srcbitmap to dstbitmap using the given blitfunction.
OP_STATUS DrawBitmapClippedGetLine(const OpBitmap* srcbitmap, OpBitmap* dstbitmap,
const OpRect &source,
const OpPoint &destpoint,
BlitFunction bltfunc)
{
int x = destpoint.x;
int y = destpoint.y;
int xlen = source.width;
int ofs_src = source.x; // Move sourceoffset to match sourcerect
int dst_w = dstbitmap->Width();
int dst_h = dstbitmap->Height();
if(x < 0) // Clip to the left
{
ofs_src += 0-x;
xlen -= 0-x;
x = 0;
}
if (x >= dst_w) // Extreme case
{
return OpStatus::OK;
}
if(x + xlen > dst_w) // Clip to the right
{
xlen -= (x + xlen) - dst_w;
}
int src_bypp = 4;//srcbitmap->GetBpp() == 15 ? 2 : srcbitmap->GetBpp() >> 3;
int dst_bypp = 4;//dstbitmap->GetBpp() == 15 ? 2 : dstbitmap->GetBpp() >> 3;
UINT8* line = OP_NEWA(UINT8, dst_w * dst_bypp );
UINT8* src = OP_NEWA(UINT8, srcbitmap->Width() * src_bypp);
if (line == NULL || src == NULL)
{
OP_DELETEA(line);
OP_DELETEA(src);
return OpStatus::ERR_NO_MEMORY;
}
BOOL src_has_alpha_or_is_transparent = srcbitmap->HasAlpha() || srcbitmap->IsTransparent();
// Run from top to bottom and call the horizontal blitfunction each row
for(int i = 0; i < source.height; i++)
{
if (i + y >= 0 && i + y < dst_h) // Clipping
{
if(src_has_alpha_or_is_transparent)
dstbitmap->GetLineData(line, y + i);
srcbitmap->GetLineData(src, i + source.y);
UINT32* dstpek = (UINT32*) &line[x * dst_bypp];
UINT32* srcpek = (UINT32*) &src[ofs_src * src_bypp];
bltfunc(srcpek, dstpek, xlen);
dstbitmap->AddLine(line, y + i);
}
}
OP_DELETEA(line);
OP_DELETEA(src);
return OpStatus::OK;
}
// Blits srcbitmap to dstbitmap using the given blitfunction.
OP_STATUS DrawBitmapClippedScaledGetLine(const OpBitmap* srcbitmap, OpBitmap* dstbitmap,
const OpRect &source,
const OpRect &dest,
BlitFunctionScaled bltfunc)
{
int x = dest.x;
int y = dest.y;
int ofs_src = source.x; // Move sourceoffset to match sourcerect
int xlen = dest.width;
int dst_w = dstbitmap->Width();
int dst_h = dstbitmap->Height();
if (x < 0) // Clip to the left
{
ofs_src += int(float(0-x) * float(source.width)/float(dest.width));
xlen -= 0-x;
x = 0;
}
if (x >= dst_w) // Extreme case
{
return OpStatus::OK;
}
if (x + xlen > dst_w) // Clip to the right
{
xlen -= (x + xlen) - dst_w;
}
FIXED1616 sy = 0; // Where we are and reads pixels
FIXED1616 dx = (source.width << 16) / dest.width; //Calculate the values we must step with, in order to get
FIXED1616 dy = (source.height << 16) / dest.height; //the right pixels from the sourcebitmap.
int src_bypp = 4;//srcbitmap->GetBpp() == 15 ? 2 : srcbitmap->GetBpp() >> 3;
int dst_bypp = 4;//dstbitmap->GetBpp() == 15 ? 2 : dstbitmap->GetBpp() >> 3;
UINT8* line = OP_NEWA(UINT8, dst_w * dst_bypp);
UINT8* src = OP_NEWA(UINT8, srcbitmap->Width() * src_bypp);
if (src == NULL || line == NULL)
{
OP_DELETEA(line);
OP_DELETEA(src);
return OpStatus::ERR_NO_MEMORY;
}
BOOL src_has_alpha_or_is_transparent = srcbitmap->HasAlpha() || srcbitmap->IsTransparent();
// Run from top to bottom and call the horizontal blitfunction each row
for (int i = 0; i < dest.height; i++)
{
if (i + y >= 0 && i + y < dst_h) // Clipping
{
if(src_has_alpha_or_is_transparent)
dstbitmap->GetLineData(line, y + i);
srcbitmap->GetLineData(src, source.y + int(sy >> 16));
UINT32* dstpek = (UINT32*) &line[x * dst_bypp];
UINT32* srcpek = (UINT32*) &src[ofs_src * src_bypp];
bltfunc(srcpek, dstpek, xlen, dx);
dstbitmap->AddLine(line, y + i);
}
sy += dy;
}
OP_DELETEA(line);
OP_DELETEA(src);
return OpStatus::OK;
}
BlitFunctionScaled SelectBlitFunctionScaled(BOOL is_transparent, BOOL has_alpha, int dst_bpp)
{
if (dst_bpp == 32)
{
if (has_alpha)
return BlitHLineAlphaScaled32;
else if (is_transparent)
return BlitHLineTransparentScaled32;
else
return BlitHLineCopyScaled32;
}
else if (dst_bpp == 24)
{
if (has_alpha)
return BlitHLineAlphaScaled24;
else if (is_transparent)
return BlitHLineTransparentScaled24;
else
return BlitHLineCopyScaled24;
}
else if (dst_bpp == 16)
{
if (has_alpha)
return BlitHLineAlphaScaled16;
else if (is_transparent)
return BlitHLineTransparentScaled16;
else
return BlitHLineCopyScaled16;
}
else if (dst_bpp == 8)
{
return BlitHLineCopyScaled8;
}
return 0; // PANIC!
}
BlitFunction SelectBlitFunction(BOOL is_transparent, BOOL has_alpha, int dst_bpp, BOOL destination_has_alpha)
{
if (dst_bpp == 32)
{
if (has_alpha)
#ifdef REALLY_UGLY_COLOR_HACK
return destination_has_alpha ? BlitHLineAlpha32UglyColorHack : BlitHLineAlpha32;
#else
return BlitHLineAlpha32;
#endif
else if (is_transparent)
return BlitHLineTransparent32;
else
return BlitHLineCopy32;
}
else if (dst_bpp == 24)
{
if (has_alpha)
return BlitHLineAlpha24;
else if (is_transparent)
return BlitHLineTransparent24;
else
return BlitHLineCopy24;
}
else if (dst_bpp == 16)
{
if (has_alpha)
return BlitHLineAlpha16;
else if (is_transparent)
return BlitHLineTransparent16;
else
return BlitHLineCopy16;
}
return 0; // PANIC!
}
BlitFunction SelectBlitFunction(BOOL is_transparent, BOOL has_alpha, int dst_bpp)
{
return SelectBlitFunction(is_transparent, has_alpha, dst_bpp, FALSE);
}
// *Internal blit*
// Creating a backgroundbitmap from the painter. Blits the sourcebitmap to it, and blits it back to the painter.
OP_STATUS BlitImage_UsingBackgroundAndPointer(OpPainter* painter, OpBitmap* bitmap,
const OpRect &source, const OpRect &dest,
BOOL is_transparent, BOOL has_alpha)
{
BOOL needscale = TRUE;
if (dest.width == source.width && dest.height == source.height)
// if (dest.width * painter->GetScale() == source.width && dest.height * painter->GetScale() == source.height)
{
needscale = FALSE;
}
OpBitmap* screenbitmap = painter->CreateBitmapFromBackground(dest);
if (screenbitmap == NULL)
{
return OpStatus::ERR_NO_MEMORY;
}
UINT8 bpp = screenbitmap->GetBpp();
BOOL use_pointer = bitmap->GetBpp() == 32 && bitmap->Supports(OpBitmap::SUPPORTS_POINTER) && screenbitmap->Supports(OpBitmap::SUPPORTS_POINTER);
if (needscale)
{
OpRect dest2(0,0,dest.width,dest.height);
if (use_pointer) // Access memory directly
{
DrawBitmapClippedScaled(bitmap, screenbitmap,
source,
dest2,
SelectBlitFunctionScaled(is_transparent, has_alpha, bpp));
}
else // AddLine, GetLineData
{
OP_STATUS err = DrawBitmapClippedScaledGetLine(bitmap, screenbitmap, source, dest2, SelectBlitFunctionScaled(is_transparent, has_alpha, 32));
if (OpStatus::IsError(err))
{
OP_DELETE(screenbitmap);
return err;
}
}
}
else
{
BOOL destination_has_alpha = FALSE;
if (painter->IsUsingOffscreenbitmap() && painter->GetOffscreenBitmap()->HasAlpha())
destination_has_alpha = TRUE;
if (use_pointer) // Access memory directly
{
DrawBitmapClipped(bitmap, screenbitmap, source, OpPoint(0,0), SelectBlitFunction(is_transparent, has_alpha, bpp, destination_has_alpha));
}
else // AddLine, GetLineData
{
OP_STATUS err = DrawBitmapClippedGetLine(bitmap, screenbitmap, source, OpPoint(0,0), SelectBlitFunction(is_transparent, has_alpha, 32, destination_has_alpha));
if (OpStatus::IsError(err))
{
OP_DELETE(screenbitmap);
return err;
}
}
}
// Blit the result back to the screen
painter->DrawBitmap(screenbitmap, OpPoint(dest.x, dest.y));
OP_DELETE(screenbitmap);
return OpStatus::OK;
}
#endif // DISPLAY_FALLBACK_PAINTING
OpBitmap* GetEffectBitmap(OpBitmap* bitmap, INT32 effect, INT32 effect_value)
{
if (!effect || bitmap == NULL || bitmap->GetBytesPerLine() == 0)
{
return bitmap;
}
int width = bitmap->Width();
int height = bitmap->Height();
OpBitmap* temp_bitmap = NULL;
if (OpStatus::IsError(OpBitmap::Create(&temp_bitmap, width, height)))
{
return bitmap;
}
BOOL support_pointer = FALSE;
if (bitmap->GetBpp() == 32 && temp_bitmap->GetBpp() == 32 &&
bitmap->Supports(OpBitmap::SUPPORTS_POINTER) &&
temp_bitmap->Supports(OpBitmap::SUPPORTS_POINTER))
{
support_pointer = TRUE;
}
if (effect & (Image::EFFECT_DISABLED | Image::EFFECT_GLOW | Image::EFFECT_BLEND))
{
int colorfactor[3] = { DISPLAY_GLOW_COLOR_FACTOR };
int glow_r = effect_value * colorfactor[0] / 255;
int glow_g = effect_value * colorfactor[1] / 255;
int glow_b = effect_value * colorfactor[2] / 255;
int lineOffset = 0;
if (support_pointer)
{
temp_bitmap->ForceAlpha();
}
UINT8* src_line;
UINT8* dst_line;
if (support_pointer)
{
src_line = (UINT8*) bitmap->GetPointer();
dst_line = (UINT8*) temp_bitmap->GetPointer();
lineOffset = bitmap->GetBytesPerLine();
}
else
{
src_line = OP_NEWA(UINT8, width * 4);
dst_line = src_line;
}
if (!src_line || !dst_line)
{
g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY);
OP_DELETE(temp_bitmap);
return bitmap;
}
for (int y=0; y<height; y++)
{
if (!support_pointer)
{
bitmap->GetLineData(src_line, y);
}
UINT32* src = (UINT32*) src_line;
UINT32* dst = (UINT32*) dst_line;
for (int x=0; x<width; x++)
{
UINT32 color = *src;
if (effect & Image::EFFECT_DISABLED)
{
#ifdef USE_PREMULTIPLIED_ALPHA
color = ((color >> 1) & 0x7f7f7f7f);
#else
color = ((color >> 1) & 0xff000000) | (color & 0x00ffffff);
#endif
}
if (effect & Image::EFFECT_GLOW)
{
int r = (color >> 16) & 0xff;
int g = (color >> 8) & 0xff;
int b = (color >> 0) & 0xff;
#ifdef USE_PREMULTIPLIED_ALPHA
int a = (color >> 24) & 0xff;
r += (glow_r*a)/255;
r = MIN(a, r);
g += (glow_g*a)/255;
g = MIN(a, g);
b += (glow_b*a)/255;
b = MIN(a, b);
#else // !USE_PREMULTIPLIED_ALPHA
r += glow_r;
r = MIN(255, r);
g += glow_g;
g = MIN(255, g);
b += glow_b;
b = MIN(255, b);
#endif // !USE_PREMULTIPLIED_ALPHA
color = (color & 0xff000000) | (r << 16) | (g << 8) | b;
}
if (effect & Image::EFFECT_BLEND)
{
#ifdef USE_PREMULTIPLIED_ALPHA
UINT32 dstcol = (((color >> 24) * effect_value / 100) << 24);
dstcol |= ((((color >> 16)&0xff) * effect_value / 100) << 16);
dstcol |= ((((color >> 8)&0xff) * effect_value / 100) << 8);
dstcol |= ((color&0xff) * effect_value / 100);
color = dstcol;
#else // !USE_PREMULTIPLIED_ALPHA
color = (((color >> 24) * effect_value / 100) << 24) | (color & 0x00ffffff);
#endif // !USE_PREMULTIPLIED_ALPHA
}
*dst = color;
++src;
++dst;
}
if (support_pointer)
{
src_line += lineOffset;
dst_line += lineOffset;
}
else
{
temp_bitmap->AddLine(dst_line, y);
}
}
if (support_pointer)
{
bitmap->ReleasePointer();
temp_bitmap->ReleasePointer();
}
else
{
OP_DELETEA(src_line);
}
}
return temp_bitmap;
}
// Makes a bigger bitmap if the size is very small. (To optimize)
OpBitmap* CreateTileOptimizedBitmap(OpBitmap* srcbitmap, INT32 new_width, INT32 new_height)
{
OpBitmap* dstbitmap = NULL;
int new_w = new_width;
int new_h = new_height;
int src_w = srcbitmap->Width();
int src_h = srcbitmap->Height();
BOOL src_transparent = srcbitmap->IsTransparent();
BOOL src_alpha = srcbitmap->HasAlpha();
#ifdef VEGA_OPPAINTER_SUPPORT
if (OpStatus::IsError(OpBitmap::Create(&dstbitmap, new_w, new_h, src_transparent, src_alpha, 0, 0)))
return srcbitmap;
int i, j;
for(j = 0; j < new_h; j += src_h)
{
for(i = 0; i < new_w; i += src_w)
{
OP_STATUS err = OpStatus::OK;
if (i+src_w > new_w || j+src_h > new_h)
err = ((VEGAOpBitmap*)dstbitmap)->CopyRect(OpPoint(i, j), OpRect(0,0,new_w-i,new_h-j), srcbitmap);
else
err = ((VEGAOpBitmap*)dstbitmap)->CopyRect(OpPoint(i, j), OpRect(0,0,src_w,src_h), srcbitmap);
if (OpStatus::IsError(err))
{
OP_DELETE(dstbitmap);
return srcbitmap;
}
}
}
#else // !VEGA_OPPAINTER_SUPPORT
if(!srcbitmap->Supports(OpBitmap::SUPPORTS_POINTER))
{
if (OpStatus::IsError(OpBitmap::Create(&dstbitmap, new_w, new_h, src_transparent, src_alpha, 0, 0, TRUE)))
return srcbitmap;
if (src_alpha || src_transparent)
{
#ifdef DEBUG_ENABLE_OPASSERT
BOOL rc =
#endif
dstbitmap->SetColor(NULL, TRUE, NULL);
OP_ASSERT(rc); // Always true for all_transparent == TRUE
}
OpPainter* painter = dstbitmap->GetPainter();
if(painter)
{
int i, j;
for(j = 0; j < new_h; j += src_h)
{
for(i = 0; i < new_w; i += src_w)
{
painter->DrawBitmap(srcbitmap, OpPoint(i, j));
}
}
dstbitmap->ReleasePainter();
}
}
else
{
UINT32 src_bytes_per_line = srcbitmap->GetBytesPerLine();
OP_STATUS status = OpBitmap::Create(&dstbitmap, new_w, new_h, src_transparent, src_alpha);
if (OpStatus::IsError(status))
{
OP_DELETE(dstbitmap);
return srcbitmap;
}
UINT8* src = (UINT8*) srcbitmap->GetPointer();
UINT8* dst = (UINT8*) dstbitmap->GetPointer();
int src_bpp = srcbitmap->GetBpp();
int dst_bpp = dstbitmap->GetBpp();
int src_bypp = src_bpp == 15 ? 2 : src_bpp >> 3;
int dst_bypp = dst_bpp == 15 ? 2 : dst_bpp >> 3;
int dst_h = dstbitmap->Height();
UINT32 dst_bytes_per_line = dstbitmap->GetBytesPerLine();
for (int j = 0; j < new_h; j++)
{
UINT8* srcpek = &src[(j % src_h) * src_bytes_per_line];
UINT8* dstpek = &dst[(j % dst_h) * dst_bytes_per_line];
for (int i = 0; i < new_w; i += src_w)
{
op_memcpy(&dstpek[i * dst_bypp], srcpek, src_w * src_bypp);
}
}
srcbitmap->ReleasePointer();
dstbitmap->ReleasePointer();
}
#endif // !VEGA_OPPAINTER_SUPPORT
return dstbitmap;
}
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#include <map>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <numeric>
#include <bitset>
const long long LINF = (1e11);
const int INF = (1<<30);
#define EPS 1e-6
const int MOD = 10007;
using namespace std;
class ElectionFraudDiv2 {
public:
string IsFraudulent(vector <int> percentages)
{
int N = (int)percentages.size();
const int voters = 10000;
int total_lower = 0;
int total_upper = 0;
for (int i=0; i<N; ++i) {
int p = percentages[i];
int lower = -1;
int upper = 0;
for (int x=0; x<=voters; ++x) {
if ((100*x+voters/2)/voters == p) {
if (lower == -1) {
lower = x;
}
upper = x;
}
}
if (lower == -1) {
return "YES";
}
total_lower += lower;
total_upper += upper;
}
return total_lower <= voters && voters <= total_upper ? "NO" : "YES";
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {100}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "NO"; verify_case(0, Arg1, IsFraudulent(Arg0)); }
void test_case_1() { int Arr0[] = {34, 34, 34}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "YES"; verify_case(1, Arg1, IsFraudulent(Arg0)); }
void test_case_2() { int Arr0[] = {12, 12, 12, 12, 12, 12, 12, 12}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "YES"; verify_case(2, Arg1, IsFraudulent(Arg0)); }
void test_case_3() { int Arr0[] = {13, 13, 13, 13, 13, 13, 13, 13}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "NO"; verify_case(3, Arg1, IsFraudulent(Arg0)); }
void test_case_4() { int Arr0[] = {0, 1, 100}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "NO"; verify_case(4, Arg1, IsFraudulent(Arg0)); }
void test_case_5() { int Arr0[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "NO"; verify_case(5, Arg1, IsFraudulent(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
ElectionFraudDiv2 ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include "CMessageEventMediator.h"
CMessageEventMediator::CMessageEventMediator(QObject *parent)
: QObject(parent)
{
}
CMessageEventMediator::~CMessageEventMediator()
{
}
|
#include "CancelEvent.h"
CancelEvent::CancelEvent(int et, int id):Event(et,id)
{
}
void CancelEvent::setTimestep(int t)
{
Timestep =t>0?t:0;
}
int CancelEvent::getTimestep() const
{
return Timestep;
}
void CancelEvent::setID(int d)
{
OrderID =( d > 0 && d < 1000) ? d : 0;
}
int CancelEvent::GetID() const
{
return OrderID;
}
void CancelEvent::Execute(Restaurant* pRest)
{
pRest->Delete_Order(OrderID);
}
|
#pragma once
#include<string>
#include"communication.h"
#include"../../json/include/json.h"
class dataImpl
{
public:
dataImpl(){}
std::string querySwitch();
bool parseSwitch(const std::string& message);
bool putPowerInfo(int power);
std::string getPowerInfo(int power);
private:
std::string toStr(int num);
private:
communication communicator;
Json::Reader reader;
Json::FastWriter writer;
};
|
#include "error_form.h"
using namespace mmcomplex;
void error_form::show_error(error_code code)
{
edit_message->Text = L"Код ошибки: " + code + L"\r\n";
switch (code)
{
case LISTINIMISSING:
edit_message->Text += "Файл list.ini не найден!";
break;
}
}
void error_form::button_ok_Click(System::Object^ sender, System::EventArgs^ e)
{
Application::Exit();
}
|
#pragma once
#include <maya/MPxCommand.h>
namespace NeoBards
{
class ThirdClass : public MPxCommand
{
public:
ThirdClass();
~ThirdClass();
MStatus doIt(const MArgList& args);
static void* creator();
private:
};
ThirdClass::ThirdClass()
{
}
ThirdClass::~ThirdClass()
{
}
}
|
#pragma once
#include <Windows.h>
#include <string>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include "CHSOggVorbisReader.hpp"
template<typename T=char> struct THSOggVorbisCommentDataTemplate {
std::basic_string<T> Name;
std::basic_string<T> BaseName;
std::basic_string<T> Value;
};
using THSOggVorbisCommentDataA = THSOggVorbisCommentDataTemplate<char>;
using THSOggVorbisCommentDataW = THSOggVorbisCommentDataTemplate<wchar_t>;
template<typename T=char> class CHSOggVorbisCommentReaderBaseTemplate {
public:
using TStdString = std::basic_string<T>;
using TCommentData = THSOggVorbisCommentDataTemplate<T>;
using TStdMapArray = std::unordered_map<TStdString , TStdString>;
using TStdVectorArray = std::vector<TCommentData>;
protected:
static bool IsUTF8 ( char *lpText , int length ) {
int size = length;
if ( lpText == nullptr )return false;
if ( size == -1 ) size = static_cast< int >( strlen ( lpText ) );
int utf8_subsize = 0;
bool utf8_subcheck = true;
for ( int i = 0; i < size; i++ ) {
unsigned char c = lpText [ i ];
//0xF0〜0xFDならUTF-8
if ( ( c >= 0xF0 ) && ( c <= 0xFD ) ) return true;
//0x80〜0x9FならShift-JIS上で次のバイトと合わせての全角文字
if ( ( c >= 0x80 ) && ( c <= 0x9F ) ) return false;
//0xA0〜0xC1はShift-JISの半角カタカナ
if ( ( c >= 0xA0 ) && ( c <= 0xC1 ) ) return false;
utf8_subsize = 0;
if ( ( c >= 0xC2 ) && ( c <= 0xDF ) ) utf8_subsize = 1;
if ( ( c >= 0xE0 ) && ( c <= 0xEF ) ) utf8_subsize = 2;
if ( utf8_subsize > 0 ) {
utf8_subcheck = true;
for ( int j = 1; ( j <= utf8_subsize ) && ( ( i + j ) < size ); j++ ) {
unsigned char v = lpText [ i + j ];
if( ( ( v >= 0x80 ) && ( v <= 0xBF ) ) == false ) {
utf8_subcheck = false;
break;
}
}
if ( utf8_subcheck ) return true;
}
}
return false;
}
virtual TStdString ToLower ( TStdString base ) = 0;
protected:
TStdMapArray CommentMapArray;
TStdVectorArray CommentVectorArray;
TStdString Vender;
virtual TStdString ToStdString ( char *pCommentString , int length ) = 0;
virtual void AddCommentData ( TStdString Comment , int index ) = 0;
public:
template <typename U> void From ( CHSOggVorbisReaderBaseTemplate<U> &Reader ) {
this->From ( Reader.GetVorbisComment ( ) );
}
void From ( vorbis_comment vc ) {
CommentMapArray.clear ( );
CommentVectorArray.resize ( vc.comments );
Vender = this->ToStdString ( vc.vendor , -1 );
TStdString str;
for ( int i = 0; i < vc.comments; i++ ) {
str = this->ToStdString ( vc.user_comments [ i ] , vc.comment_lengths [ i ] );
this->AddCommentData ( str , i);
}
}
TCommentData operator[](unsigned int index ) {
if ( index >= CommentVectorArray.size ( ) ) {
TCommentData cd;
cd.Name = "";
cd.BaseName = "";
cd.Value = "";
return cd;
}
return CommentVectorArray.at ( index );
}
TStdString operator()( TStdString Name ) {
auto it = CommentMapArray.find ( this->ToLower ( Name ) );
if ( it == CommentMapArray.end ( ) ) {
TStdString s;
s.clear ( );
return s;
}
return it->second;
}
TStdString GetVendor ( void ) {
return this->Vender;
}
TStdMapArray GetMapArray ( void ) {
return this->CommentMapArray;
}
TStdVectorArray GetVectorArray ( void ) {
return this->CommentVectorArray;
}
size_t Count ( ) {
return CommentVectorArray.size ( );
}
};
using CHSOggVorbisCommentReaderBaseA = CHSOggVorbisCommentReaderBaseTemplate<char>;
using CHSOggVorbisCommentReaderBaseW = CHSOggVorbisCommentReaderBaseTemplate<wchar_t>;
class CHSOggVorbisCommentReaderA : public CHSOggVorbisCommentReaderBaseA {
private:
TStdString ToLower ( TStdString base ) {
TStdString out = base;
std::transform ( out.cbegin ( ) , out.cend ( ) , out.begin ( ) , tolower );
return out;
}
TStdString ToStdString ( char *pCommentString , int length ) {
TStdString str;
size_t len;
if ( pCommentString != nullptr ) {
len = ( length >= 0 ) ? length : strlen ( pCommentString );
if ( len != 0 ) {
if ( this->IsUTF8 ( pCommentString , len ) == false ) {
str = pCommentString;
} else {
wchar_t *lpwideStr;
char *lpmbcsStr;
char *pInput = pCommentString;
int InputSize = ( int ) len;
//UTF8→Unicode
int wcharsize = MultiByteToWideChar ( CP_UTF8 , 0 , pInput , InputSize , nullptr , 0 );
lpwideStr = new wchar_t [ wcharsize + 1 ];
*( lpwideStr + wcharsize ) = '\0';
MultiByteToWideChar ( CP_UTF8 , 0 , pInput , InputSize , lpwideStr , wcharsize );
//Unicode->MBCS(Shift-JIS)
int mbcs_size = WideCharToMultiByte ( CP_ACP , 0 , lpwideStr , -1 , nullptr , 0 , nullptr , nullptr );
lpmbcsStr = new char [ mbcs_size + 1 ];
*( lpmbcsStr + mbcs_size ) = '\0';
WideCharToMultiByte ( CP_ACP , 0 , lpwideStr , -1 , lpmbcsStr , mbcs_size , nullptr , nullptr );
delete [ ]lpwideStr;
str = lpmbcsStr;
delete [ ]lpmbcsStr;
}
}
}
return str;
}
void AddCommentData ( TStdString Comment , int index) {
size_t pos = Comment.find ( "=" );
TCommentData Data;
Data.BaseName = Comment.substr ( 0 , pos );
Data.Name = this->ToLower ( Data.BaseName );
Data.Value = Comment.substr ( pos + 1 );
// printf ( "Add(A)[%d] \"%s\" : \"%s\"\n" , Data.Value.length ( ) ,Data.Name.c_str ( ) , Data.Value.substr(0,100).c_str() );
this->CommentMapArray [ Data.Name ] = Data.Value;
this->CommentVectorArray [ index ] = Data;
}
public:
CHSOggVorbisCommentReaderA ( ) {
}
template <typename U> CHSOggVorbisCommentReaderA ( CHSOggVorbisReaderBaseTemplate<U> &Reader ) {
this->From ( Reader );
}
CHSOggVorbisCommentReaderA ( vorbis_comment vc ) {
this->From ( vc );
}
};
class CHSOggVorbisCommentReaderW : public CHSOggVorbisCommentReaderBaseW {
private:
TStdString ToLower ( TStdString base ) {
TStdString out = base;
std::transform ( out.cbegin ( ) , out.cend ( ) , out.begin ( ) , towlower );
return out;
}
TStdString ToStdString ( char *pCommentString , int length ) {
TStdString str;
size_t len;
if ( pCommentString != nullptr ) {
len = ( length >= 0 ) ? length : strlen ( pCommentString );
wchar_t *lpwideStr;
char *pInput = pCommentString;
int InputSize = ( int ) len;
if ( len != 0 ) {
if ( this->IsUTF8 ( pCommentString , len ) == false ) {
//MBCS(Shift-JIS)→Unicode
int wcharsize = MultiByteToWideChar ( CP_ACP , 0 , pInput , InputSize , nullptr , 0 );
lpwideStr = new wchar_t [ wcharsize + 1 ];
*( lpwideStr + wcharsize ) = '\0';
MultiByteToWideChar ( CP_ACP , 0 , pInput , InputSize , lpwideStr , wcharsize );
} else {
//UTF8→Unicode
int wcharsize = MultiByteToWideChar ( CP_UTF8 , 0 , pInput , InputSize , nullptr , 0 );
lpwideStr = new wchar_t [ wcharsize + 1 ];
*( lpwideStr + wcharsize ) = '\0';
MultiByteToWideChar ( CP_UTF8 , 0 , pInput , InputSize , lpwideStr , wcharsize );
}
str = lpwideStr;
delete [ ]lpwideStr;
}
}
return str;
}
void AddCommentData ( TStdString Comment , int index ) {
size_t pos = Comment.find ( L"=" );
TCommentData Data;
Data.BaseName = Comment.substr ( 0 , pos );
Data.Name = this->ToLower ( Data.BaseName );
Data.Value = Comment.substr ( pos + 1 );
//wprintf ( L"Add(W)[%d] \"%s\" : \"%s\"\n" , Data.Value.length(), Data.Name.c_str ( ) , Data.Value.c_str ( ) );
this->CommentMapArray [ Data.Name ] = Data.Value;
this->CommentVectorArray [ index ] = Data;
}
public:
CHSOggVorbisCommentReaderW ( ) {
}
template <typename U> CHSOggVorbisCommentReaderW ( CHSOggVorbisReaderBaseTemplate<U> &Reader ) {
this->From ( Reader );
}
CHSOggVorbisCommentReaderW ( vorbis_comment vc ) {
this->From ( vc );
}
};
|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
const int maxn = 100 + 6;
int a[maxn];
int b, e;
int k;
int main() {
int m;
cin >> m;
while(m--) {
int cnt = 0;
cin >> b >> e;
for(int i = b; i <= e; i++) {
int num, c;
while(!num) {
c = (num % 2);
a[k] = c;
num = num / 2;
k++;
// for(i--; i >= 0; i--) {
// cout << a[i];
// cout << endl;
// }
for(int i = 0; i < k; i++) {
if(a[i] == 1) cnt++;
cout << cnt << endl;
}
}
}
}
return 0;
}
|
#include "Npc.h"
#include "Map.h"
#include "Globals.h"
#include <algorithm>
#include "NPCManager.h"
#include "ObjectManager.h"
Npc::Npc(unsigned int a_id, unsigned int a_tileId, const std::string& a_path, unsigned int zone)
: m_currentState{NONE}, m_nextState{EXPLORING}, m_id{a_id}, m_goal{}, m_hasGoal{false}, m_path{a_tileId}, m_nextActions{}, m_historyTiles{a_tileId}, m_turnCount{0}, m_zone{zone}
{
#ifdef BOT_LOGIC_DEBUG_NPC
m_logger.Init(a_path, "Npc_" + std::to_string(m_id) + ".log");
#endif
BOT_LOGIC_NPC_LOG(m_logger, "Configure", true);
};
void Npc::update()
{
++m_turnCount;
BOT_LOGIC_NPC_LOG(m_logger, "\nTurn #" + std::to_string(m_turnCount) + "\n\tCurrent Tile : " + std::to_string(getCurrentTileId()), true);
updatePath();
BOT_LOGIC_NPC_LOG(m_logger, "\tEntering State Machine : ", true);
do
{
//Set npc behaviour according to their state
m_currentState = m_nextState;
switch(m_currentState)
{
case(MOVING):
followPath();
break;
case(WAITING):
wait();
break;
case(EXPLORING):
explore();
break;
case(INTERACTING):
interact();
break;
case(ARRIVED):
m_nextState = ARRIVED;
m_currentState = ARRIVED;
if(getCurrentTileId() == m_goal)
{
Map::get()->getNode(getCurrentTileId())->setType(Node::OCCUPIED);
BOT_LOGIC_NPC_LOG(m_logger, "\tI am out, i am on my goal !", true);
NPCManager::get()->getNpcUpdateBT().addNpcToRemove(m_id);
}
break;
}
} while(m_currentState != m_nextState);
}
bool Npc::stopEverything()
{
// deleting actions
for(std::vector< Action* >::iterator it = m_nextActions.begin(); it != m_nextActions.end(); ++it)
{
delete (*it);
}
m_nextActions.clear();
return true;
}
void Npc::stopMoving()
{
// separate move and interact actions
auto it = std::partition(std::begin(m_nextActions),
std::end(m_nextActions),
[](const Action* curAction) { return curAction->actionType != Action_Move; });
// deleting move actions
for(std::vector< Action* >::iterator itDelete = it; itDelete != m_nextActions.end(); ++itDelete)
{
delete (*itDelete);
}
m_nextActions.erase(it, std::end(m_nextActions));
}
void Npc::stopInteract()
{
// separate move and interact actions
auto it = std::partition(std::begin(m_nextActions),
std::end(m_nextActions),
[](const Action* curAction) { return curAction->actionType != Action_Interact; });
// deleting interact actions
for(std::vector< Action* >::iterator itDelete = it; itDelete != m_nextActions.end(); ++itDelete)
{
delete (*itDelete);
}
m_nextActions.erase(it, std::end(m_nextActions));
}
void Npc::unstackActions()
{
while(m_nextActions.size())
{
Action* curAction{m_nextActions.back()};
switch(curAction->actionType)
{
case Action_None:
// Do nothing
break;
case Action_Move:
//Go on
moveForwardOnPath();
break;
case Action_Interact:
// TODO - do nothing atm
break;
}
m_nextActions.pop_back();
}
}
void Npc::calculPath()
{
if(!hasGoal())
{
return;
}
std::vector<unsigned> path = Map::get()->getNpcPath(getCurrentTileId(), m_goal, {Node::FORBIDDEN, Node::OCCUPIED});
if(path.size() <= 0)
{
m_hasGoal = false;
return;
}
m_path = path;
}
bool Npc::updatePath()
{
BOT_LOGIC_NPC_LOG(m_logger, "\tUpdating Path ", true);
DisplayVector("\t\tOld path: ", m_path);
Map* mapManager = Map::get();
if(m_path.size() > 1)
{
unsigned int currentTile = getCurrentTileId();
unsigned int nextTile = getNextPathTile();
EDirection dir = mapManager->getNextDirection(currentTile, nextTile);
EDirection invDir = static_cast<EDirection>((dir + 4) % 8);
if(mapManager->getNode(currentTile)->isBlockedByDoor(dir) || mapManager->getNode(nextTile)->isBlockedByDoor(invDir))
{
m_nextState = INTERACTING;
return true;
}
if(!mapManager->canMoveOnTile(currentTile, nextTile))
{
auto newPath = mapManager->getNpcPath(getCurrentTileId(), m_goal, {Node::FORBIDDEN, Node::OCCUPIED});
if(newPath.size() > 0)
{
if(newPath.size() > 30 && m_hasGoal)
{
BOT_LOGIC_NPC_LOG(m_logger, "\t\tTo path to the goal is to long... don't want to go there", true);
m_hasGoal = false;
m_path = {currentTile};
return true;
}
m_path = newPath;
DisplayVector("\t\tPath Updated : ", m_path);
return true;
}
}
}
//unsigned int saveCurrentTile{m_path.back()};
//unsigned int oldTileId{m_path.back()};
//Map* mapManager = Map::get();
//for(auto reverseIter = m_path.rbegin(); reverseIter != m_path.rend(); ++reverseIter)
//{
// if(!mapManager->canMoveOnTile(oldTileId, (*reverseIter)))
// {
// auto newPath = mapManager->getNpcPath(getCurrentTileId(), m_goal, {Node::FORBIDDEN, Node::OCCUPIED});
// if(newPath.size() > 0)
// {
// if(newPath.size() > 30 && m_hasGoal)
// {
// BOT_LOGIC_NPC_LOG(m_logger, "\t\tTo path to the goal is to long... don't want to go there", true);
// m_hasGoal = false;
// m_path = {saveCurrentTile};
// break;
// }
// m_path = newPath;
// DisplayVector("\t\tPath Updated : ", m_path);
// return true;
// }
// else
// {
// BOT_LOGIC_NPC_LOG(m_logger, "\t\tCan't access the goal this turn, just wait, can't go from " + std::to_string(oldTileId) + " to " + std::to_string((*reverseIter)), true);
// m_nextState = WAITING;
// return true;
// }
// }
// oldTileId = (*reverseIter);
//}
BOT_LOGIC_NPC_LOG(m_logger, "\t\tNo update needed", true);
m_nextState = EXPLORING;
return false;
}
int Npc::getNextPathTile() const
{
if(m_path.size() == 1)
{
return -1; // empty path, only contains current tile
}
unsigned int index = m_path[m_path.size() - 2];
return index;
}
void Npc::setCurrentTile(unsigned tile_id)
{
if(getCurrentTileId() == tile_id)
{
return;
}
Map* myMap = Map::get();
myMap->getNode(m_path.back())->setNpcIdOnNode(-1);
m_path.push_back(tile_id);
myMap->getNode(tile_id)->setNpcIdOnNode(m_id);
}
void Npc::explore()
{
BOT_LOGIC_NPC_LOG(m_logger, "-Explore", true);
if(hasGoal())
{
BOT_LOGIC_NPC_LOG(m_logger, "\tNPC have a goal : " + std::to_string(m_goal), true);
DisplayVector("\tNpc base path :", m_path);
m_nextState = MOVING;
return;
}
Map* mapPtr = Map::get();
// Get the most influenced tile near the NPC
int bestTile = mapPtr->getNearInfluencedTile(getCurrentTileId());
// If we have not a best choice around us, let see a little bit futher
if(bestTile < 0)
{
// TODO - Try to get the most influent tile around us in range of 2 instead of looking for a non visited tile
// Get all non visited tiles
std::vector<unsigned> nonVisitedTiles = std::move(mapPtr->getNonVisitedTile());
DisplayVector("\t-Looking for the non visited tiles : ", nonVisitedTiles);
if(nonVisitedTiles.size() == 0)
{
BOT_LOGIC_NPC_LOG(m_logger, "\tNPC need to explore the door", true);
m_nextState = INTERACTING;
return;
}
for(unsigned index : nonVisitedTiles)
{
// Test if we can have a good path to this tile
std::vector<unsigned> temp = std::move(mapPtr->getNpcPath(getCurrentTileId(), index,
{Node::NodeType::FORBIDDEN, Node::NodeType::NONE, Node::NodeType::OCCUPIED}));
// If we got a good path, let's configure this
if(!temp.empty())
{
m_path = std::move(temp);
m_target = index;
m_nextState = MOVING;
break;
}
}
}
else
{
// Set the best tile in path and push the action
unsigned int bestTileUnsigned = bestTile;
m_path = {bestTileUnsigned, getCurrentTileId()};
m_historyTiles.push_back(bestTile);
m_nextActions.push_back(new Move{m_id, mapPtr->getNextDirection(getCurrentTileId(), getNextPathTile())});
BOT_LOGIC_NPC_LOG(m_logger, std::move("Deplacement vers " + std::to_string(bestTile)), true);
m_nextState = EXPLORING;
}
}
void Npc::followPath()
{
if(getCurrentTileId() == m_goal && m_hasGoal)
{
m_nextState = ARRIVED;
return;
}
if(m_path.size() <= 1 || getCurrentTileId() == m_target && !hasGoal())
{
m_nextState = EXPLORING;
return;
}
BOT_LOGIC_NPC_LOG(m_logger, "-FollowPath", true);
unsigned int nextTile = getNextPathTile();
m_nextActions.push_back(new Move{m_id, Map::get()->getNextDirection(getCurrentTileId(), nextTile)});
BOT_LOGIC_NPC_LOG(m_logger, "\tDeplacement vers " + std::to_string(nextTile), true);
m_nextState = MOVING;
}
void Npc::wait()
{
BOT_LOGIC_NPC_LOG(m_logger, "-Wait", true);
m_nextState = WAITING;
}
void Npc::interact()
{
BOT_LOGIC_NPC_LOG(m_logger, "-Interact", true);
auto cObjects = ObjectManager::get()->getAllObjectsOnTile(getCurrentTileId());
auto nObjects = ObjectManager::get()->getAllObjectsOnTile(getNextPathTile());
ObjectRef myDoor;
for(auto object : cObjects)
{
if(object->getType() == Object::DOOR)
{
myDoor = object;
}
}
for(auto object : nObjects)
{
if(object->getType() == Object::DOOR)
{
myDoor = object;
}
}
if(myDoor == ObjectRef())
{
m_nextActions.push_back(new Interact{m_id, 0, Interaction_SearchHiddenDoor});
BOT_LOGIC_NPC_LOG(m_logger, "\tTry open hidden door", true);
return;
}
if(myDoor->isActive())
{
m_nextState = MOVING;
return;
}
m_nextActions.push_back(new Interact{m_id, myDoor->getId(), Interaction_OpenDoor});
BOT_LOGIC_NPC_LOG(m_logger, "\tOpen door : " + std::to_string(myDoor->getId()), true);
myDoor->setIsActive(true);
}
template<class T>
void Npc::DisplayVector(std::string info, const std::vector<T> v)
{
std::string s{""};
for(T u : v)
{
s += std::to_string(u) + " ";
}
BOT_LOGIC_NPC_LOG(m_logger, info + s, true);
}
|
// Created on: 2004-05-11
// Created by: Sergey ZARITCHNY <szy@opencascade.com>
// Copyright (c) 2004-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 _BinTools_HeaderFile
#define _BinTools_HeaderFile
#include <BinTools_FormatVersion.hxx>
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Real.hxx>
#include <Message_ProgressRange.hxx>
class TopoDS_Shape;
//! Tool to keep shapes in binary format
class BinTools
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT static Standard_OStream& PutReal (Standard_OStream& OS, const Standard_Real& theValue);
Standard_EXPORT static Standard_OStream& PutShortReal (Standard_OStream& OS, const Standard_ShortReal& theValue);
Standard_EXPORT static Standard_OStream& PutInteger (Standard_OStream& OS, const Standard_Integer theValue);
Standard_EXPORT static Standard_OStream& PutBool (Standard_OStream& OS, const Standard_Boolean theValue);
Standard_EXPORT static Standard_OStream& PutExtChar (Standard_OStream& OS, const Standard_ExtCharacter theValue);
Standard_EXPORT static Standard_IStream& GetReal (Standard_IStream& IS, Standard_Real& theValue);
Standard_EXPORT static Standard_IStream& GetShortReal (Standard_IStream& IS, Standard_ShortReal& theValue);
Standard_EXPORT static Standard_IStream& GetInteger (Standard_IStream& IS, Standard_Integer& theValue);
Standard_EXPORT static Standard_IStream& GetBool (Standard_IStream& IS, Standard_Boolean& theValue);
Standard_EXPORT static Standard_IStream& GetExtChar (Standard_IStream& IS, Standard_ExtCharacter& theValue);
//! Writes the shape to the stream in binary format BinTools_FormatVersion_CURRENT.
//! This alias writes shape with triangulation data.
//! @param theShape [in] the shape to write
//! @param theStream [in][out] the stream to output shape into
//! @param theRange the range of progress indicator to fill in
static void Write (const TopoDS_Shape& theShape,
Standard_OStream& theStream,
const Message_ProgressRange& theRange = Message_ProgressRange())
{
Write (theShape, theStream, Standard_True, Standard_False,
BinTools_FormatVersion_CURRENT, theRange);
}
//! Writes the shape to the stream in binary format of specified version.
//! @param theShape [in] the shape to write
//! @param theStream [in][out] the stream to output shape into
//! @param theWithTriangles [in] flag which specifies whether to save shape with (TRUE) or without (FALSE) triangles;
//! has no effect on triangulation-only geometry
//! @param theWithNormals [in] flag which specifies whether to save triangulation with (TRUE) or without (FALSE) normals;
//! has no effect on triangulation-only geometry
//! @param theVersion [in] the BinTools format version
//! @param theRange the range of progress indicator to fill in
Standard_EXPORT static void Write(const TopoDS_Shape& theShape, Standard_OStream& theStream,
const Standard_Boolean theWithTriangles,
const Standard_Boolean theWithNormals,
const BinTools_FormatVersion theVersion,
const Message_ProgressRange& theRange = Message_ProgressRange());
//! Reads a shape from <theStream> and returns it in <theShape>.
Standard_EXPORT static void Read (TopoDS_Shape& theShape, Standard_IStream& theStream,
const Message_ProgressRange& theRange = Message_ProgressRange());
//! Writes the shape to the file in binary format BinTools_FormatVersion_CURRENT.
//! @param theShape [in] the shape to write
//! @param theFile [in] the path to file to output shape into
//! @param theRange the range of progress indicator to fill in
static Standard_Boolean Write (const TopoDS_Shape& theShape,
const Standard_CString theFile,
const Message_ProgressRange& theRange = Message_ProgressRange())
{
return Write (theShape, theFile, Standard_True, Standard_False,
BinTools_FormatVersion_CURRENT, theRange);
}
//! Writes the shape to the file in binary format of specified version.
//! @param theShape [in] the shape to write
//! @param theFile [in] the path to file to output shape into
//! @param theWithTriangles [in] flag which specifies whether to save shape with (TRUE) or without (FALSE) triangles;
//! has no effect on triangulation-only geometry
//! @param theWithNormals [in] flag which specifies whether to save triangulation with (TRUE) or without (FALSE) normals;
//! has no effect on triangulation-only geometry
//! @param theVersion [in] the BinTools format version
//! @param theRange the range of progress indicator to fill in
Standard_EXPORT static Standard_Boolean Write (const TopoDS_Shape& theShape,
const Standard_CString theFile,
const Standard_Boolean theWithTriangles,
const Standard_Boolean theWithNormals,
const BinTools_FormatVersion theVersion,
const Message_ProgressRange& theRange = Message_ProgressRange());
//! Reads a shape from <theFile> and returns it in <theShape>.
Standard_EXPORT static Standard_Boolean Read
(TopoDS_Shape& theShape, const Standard_CString theFile,
const Message_ProgressRange& theRange = Message_ProgressRange());
};
#endif // _BinTools_HeaderFile
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- */
#ifndef ES_TYPEDARRAY_BUILTINS_H
#define ES_TYPEDARRAY_BUILTINS_H
#include "modules/ecmascript/carakan/src/object/es_typedarray.h"
class ES_ArrayBufferBuiltins
{
public:
static BOOL ES_CALLING_CONVENTION constructor_construct(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
enum
{
ES_ArrayBufferBuiltins_length = 0,
ES_ArrayBufferBuiltins_byteLength,
ES_ArrayBufferBuiltins_constructor,
ES_ArrayBufferBuiltins_slice,
ES_ArrayBufferBuiltinsCount,
ES_ArrayBufferBuiltinsCount_LAST_PROPERTY = ES_ArrayBufferBuiltinsCount
};
static void PopulateGlobalObject(ES_Context *context, ES_Global_Object *global_object);
static void PopulatePrototypeClass(ES_Context *context, ES_Class_Singleton *prototype_class);
static void PopulatePrototype(ES_Context *context, ES_Global_Object *global_object, ES_Object *prototype);
static BOOL ES_CALLING_CONVENTION slice(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
};
class ES_TypedArrayBuiltins
{
public:
static BOOL ES_CALLING_CONVENTION constructor_construct_Int8(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION constructor_construct_Uint8(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION constructor_construct_Uint8Clamped(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION constructor_construct_Int16(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION constructor_construct_Uint16(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION constructor_construct_Int32(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION constructor_construct_Uint32(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION constructor_construct_Float32(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION constructor_construct_Float64(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
enum
{
ES_TypedArrayBuiltins_length = 0,
ES_TypedArrayBuiltins_buffer,
ES_TypedArrayBuiltins_byteLength,
ES_TypedArrayBuiltins_byteOffset,
ES_TypedArrayBuiltins_constructor,
ES_TypedArrayBuiltins_set,
ES_TypedArrayBuiltins_subarray,
ES_TypedArrayBuiltinsCount,
ES_TypedArrayBuiltinsCount_LAST_PROPERTY = ES_TypedArrayBuiltinsCount
};
static void PopulateGlobalObject(ES_Context *context, ES_Global_Object *global_object);
static void PopulatePrototypeClass(ES_Context *context, ES_Class_Singleton *prototype_class);
static void PopulatePrototype(ES_Context *context, ES_Global_Object *global_object, ES_Object *prototype, ES_TypedArray::Kind kind);
static BOOL ES_CALLING_CONVENTION set(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION subarray(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
private:
typedef BOOL (ES_CALLING_CONVENTION ConstructorFun)(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static ConstructorFun *GetConstructorFunction(ES_TypedArray::Kind kind);
};
/** DataView is the heterogeneous view of an ArrayBuffer, providing methods
for indexing the buffer at any of the supported basic types. */
class ES_DataViewBuiltins
{
public:
static BOOL ES_CALLING_CONVENTION constructor_call(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
/**< 'DataView()' */
static BOOL ES_CALLING_CONVENTION constructor_construct(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
/**< 'new DataView()' */
static void PopulateGlobalObject(ES_Context *context, ES_Global_Object *global_object);
static void PopulatePrototypeClass(ES_Context *context, ES_Class_Singleton *prototype_class);
static void PopulatePrototype(ES_Context *context, ES_Global_Object *global_object, ES_Object *prototype);
enum
{
ES_DataViewBuiltins_length = 0,
ES_DataViewBuiltins_buffer,
ES_DataViewBuiltins_byteOffset,
ES_DataViewBuiltins_byteLength,
ES_DataViewBuiltins_constructor,
ES_DataViewBuiltins_getInt8,
ES_DataViewBuiltins_getUint8,
ES_DataViewBuiltins_getInt16,
ES_DataViewBuiltins_getUint16,
ES_DataViewBuiltins_getInt32,
ES_DataViewBuiltins_getUint32,
ES_DataViewBuiltins_getFloat32,
ES_DataViewBuiltins_getFloat64,
ES_DataViewBuiltins_setInt8,
ES_DataViewBuiltins_setUint8,
ES_DataViewBuiltins_setInt16,
ES_DataViewBuiltins_setUint16,
ES_DataViewBuiltins_setInt32,
ES_DataViewBuiltins_setUint32,
ES_DataViewBuiltins_setFloat32,
ES_DataViewBuiltins_setFloat64,
ES_DataViewBuiltinsCount,
ES_DataViewBuiltinsCount_LAST_PROPERTY = ES_DataViewBuiltinsCount
};
static BOOL ES_CALLING_CONVENTION getInt8(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION getUint8(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION getInt16(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION getUint16(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION getInt32(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION getUint32(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION getFloat32(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION getFloat64(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION setInt8(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION setUint8(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION setInt16(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION setUint16(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION setInt32(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION setUint32(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION setFloat32(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION setFloat64(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
};
#endif // ES_TYPEDARRAY_BUILTINS_H
|
class Solution {
public:
int jumpFloor(int number) {
if(number < 2){
return number;
}
int n1 = 1;
int n2 = 2;
for(int i=3; i<=number; ++i){
int temp = n1+n2;
n1 = n2;
n2 = temp;
}
return n2;
}
};
|
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@gmail.com *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#ifdef ANDROID
#include <android/input.h>
#include "AndroidInputDispatcher.h"
#include "Logging.h"
namespace Event {
bool AndroidInputDispatcher::pollAndDispatch (Model::IModel *m, Event::EventIndex const &modeliIndex, Event::PointerInsideIndex *pointerInsideIndex)
{
}
bool AndroidInputDispatcher::dispatch (Model::IModel *m, EventIndex const &modeliIndex, PointerInsideIndex *pointerInsideIndex, void *platformDependentData)
{
AInputEvent *androidEvent = static_cast <AInputEvent *> (platformDependentData);
logEvent (androidEvent);
return true;
}
void AndroidInputDispatcher::reset ()
{
}
IEvent *AndroidInputDispatcher::translate (void *platformDependentEvent)
{
return NULL;
}
} /* namespace Event */
#endif
|
#include <iostream>
// Add to class vector:
// Create objects of type double
// Copy objects with assignment and initialization
// Any quanity of elements
// Safe memory used and clean
// Use [] to access to element
class vector
{
int sz; // Number of elements
double* elem; // Pointer to first element
public:
explicit vector(int s); // Constructor
vector(const std::initializer_list<double>& lst); // initialization list
~vector() //Destructor
{
delete[] elem;
}
vector(const vector&); // Constructor copy
vector& operator= (const vector&); // Copy assignment
vector(vector&& a); // Constructor move
vector& operator= (vector&&); // Move assignment
int size() const { return sz; } // size()
double& operator[] (int n) { return elem[n]; } // v[]
double& operator[] (int n) const { return elem[n]; } // const v[]
};
vector::vector(int s)
: sz{ s }, elem{ new double[s] }
{
for (int i = 0; i < s; ++i)
elem[i] = 0;
}
vector::vector(const std::initializer_list<double>& lst)
: sz{ int(lst.size()) }, elem{ new double[sz] }
{
std::copy(lst.begin(), lst.end(), elem);
}
vector::vector(const vector& arg)
: sz{ arg.sz }, elem{ new double[arg.sz] }
{
std::copy(arg.elem, arg.elem + sz, elem);
}
vector& vector::operator= (const vector& arg)
{
if (&arg == this)
return *this;
double* buffer = new double[arg.sz];
std::copy(arg.elem, arg.elem + arg.sz, buffer);
delete[] elem;
elem = buffer;
sz = arg.sz;
return *this;
}
vector::vector(vector&& a)
: sz{ a.sz }, elem{ a.elem }
{
a.sz = 0;
a.elem = nullptr;
}
vector& vector::operator= (vector&& a)
{
delete[] elem;
elem = a.elem;
sz = a.sz;
a.elem = nullptr;
a.sz = 0;
return *this;
}
int main()
{
vector v0 = { 1.1, 4.5, 6,9 };
for (int i = 0; i < v0.size(); ++i)
std::cout << v0[i] << " ";
std::cout << std::endl;
vector v(10);
for (int i = 0; i < v.size(); ++i)
v[i] = i;
vector v2 = v;
// for (int i = 0; i < v2.size(); ++i)
// std::cout << v2[i] << ' ';
v[3] = v2[1];
int size = v.size();
return 0;
}
|
#include "prac4.h"
#include "ui_prac4.h"
#include"speech.h"
prac4::prac4(QWidget *parent) :
QDialog(parent),
ui(new Ui::prac4)
{
ui->setupUi(this);
}
prac4::~prac4()
{
delete ui;
}
void prac4::on_pushButton_clicked()
{
hide();
speech s;
s.setModal(true);
s.exec();
}
|
#ifndef PLANILLA_H
#define PLANILLA_H
using namespace std;
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
class Planilla {
string resultado;
string datosSalida;
string lineaPersonas;
string lineaNomina;
string lineaHorasTrabajadas;
int idEmpleadoPersonas;
string nombre;
string apellido;
string correo;
int tipoEmpleado;
int idSupervisor;
int idEmpleadoNomina;
float pagoMensualBruto;
int idEmpleadoHorasTrabajadas;
float montoPorHora;
int horasLaboradas;
string lineaEmpleado;
float montoAPagarPlanilla;
float impuestosPlanilla;
public:
Planilla();
string calcularPlanillaPago(string linea);
string calcularPagoPorNomina(int idEmpleado, int idSupervisor, string nombreEmpleado, string apellidoEmpleado);
string calcularPagoPorHorasTrabajadas(int idEmpleado, int idSupervisor, string nombreEmpleado, string apellidoEmpleado);
};
#endif
|
/**
* created: 2013-4-6 23:47
* filename: FKEncDec
* author: FreeKnight
* Copyright (C):
* purpose:
*/
//------------------------------------------------------------------------
#pragma once
//------------------------------------------------------------------------
#include <stdlib.h>
#include "FKMd5Ex.h"
#include "FKDes.h"
#include "FKCrc16.h"
#include "FKCrc32.h"
//------------------------------------------------------------------------
#define RC5_8_ROUNDS 8
//------------------------------------------------------------------------
class CEncrypt
{
public:
CEncrypt();
enum encMethod{
ENCDEC_NONE=0,
ENCDEC_RC5=1,
ENCDEC_DES=2,
ENCDEC_FORCE_DWORD=0x7fffffff,
};
void random_key_des(DES_cblock *ret);
void set_key_des(const_DES_cblock *key);
void set_key_rc5(const unsigned char *data, int nLen, int rounds = RC5_8_ROUNDS);
int encdec(void *data, unsigned int nLen, bool enc);
void setEncMethod(encMethod method);
encMethod getEncMethod() const;
private:
void DES_encrypt1(DES_LONG *data, DES_key_schedule *ks, int enc);
int encdec_des(unsigned char *data, unsigned int nLen, bool enc);
private:
encMethod method;
DES_key_schedule key_des;
bool haveKey_des;
};
//------------------------------------------------------------------------
|
#include "stackdbl.h"
StackDbl::StackDbl()
{
}
StackDbl::~StackDbl()
{
}
bool StackDbl::empty() const
{
return list_.empty();
}
void StackDbl::push(const double& val)
{
list_.insert(0, val);
}
double const & StackDbl::top() const
{
return list_.get(0);
}
void StackDbl::pop()
{
if( ! list_.empty() ){
list_.remove(0);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.