hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
92b3ba3d2569d188a3ef802903e6e1da29adcc6e | 2,575 | hpp | C++ | example/json_fwd.hpp | tzlaine/parser | 095aa362d777a480fffef415d27d214cd6ffec4a | [
"BSL-1.0"
] | 7 | 2020-08-29T02:10:20.000Z | 2022-03-29T20:31:59.000Z | example/json_fwd.hpp | tzlaine/parser | 095aa362d777a480fffef415d27d214cd6ffec4a | [
"BSL-1.0"
] | 16 | 2020-08-29T21:33:08.000Z | 2022-03-22T03:01:02.000Z | example/json_fwd.hpp | tzlaine/parser | 095aa362d777a480fffef415d27d214cd6ffec4a | [
"BSL-1.0"
] | 1 | 2021-09-22T08:15:57.000Z | 2021-09-22T08:15:57.000Z | // Copyright (C) 2020 T. Zachary Laine
//
// 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)
#ifndef JSON_FWD_HPP
#define JSON_FWD_HPP
#include <string>
#include <unordered_map>
#include <vector>
namespace json {
struct value;
enum class value_kind { null, boolean, number, string, object, array };
struct null_t
{
bool operator==(null_t) const noexcept { return true; }
bool operator!=(null_t) const noexcept { return false; }
bool operator<(null_t) const noexcept { return false; }
};
using array = std::vector<value>;
using object = std::unordered_map<std::string, value>;
namespace detail {
template<typename T, bool Const>
struct get_result
{
using type = T;
};
template<>
struct get_result<array, true>
{
using type = array const &;
};
template<>
struct get_result<array, false>
{
using type = array &;
};
template<>
struct get_result<object, true>
{
using type = object const &;
};
template<>
struct get_result<object, false>
{
using type = object &;
};
template<typename T, bool Const>
using get_result_t = typename get_result<T, Const>::type;
}
template<typename T>
detail::get_result_t<T, true> get(value const & v) noexcept;
template<typename T>
detail::get_result_t<T, false> get(value & v) noexcept;
std::size_t hash_append(std::size_t seed, value const & v);
std::size_t hash_append(std::size_t seed, array const & v);
std::size_t hash_append(std::size_t seed, object const & v);
namespace detail {
template<typename T>
struct get_impl;
}
}
namespace std {
template<>
struct hash<json::value>
{
using argument_type = json::value;
using result_type = size_t;
result_type operator()(argument_type const & v) const noexcept;
};
template<>
struct hash<json::object>
{
using argument_type = json::object;
using result_type = size_t;
result_type operator()(argument_type const & o) const noexcept;
};
template<>
struct hash<json::array>
{
using argument_type = json::array;
using result_type = size_t;
result_type operator()(argument_type const & a) const noexcept;
};
}
#endif
| 25 | 75 | 0.600777 | [
"object",
"vector"
] |
92b44c9d3ae30b2ccae3264388c9a277f672e05b | 5,552 | cpp | C++ | MonoNative/mscorlib/System/Runtime/Remoting/mscorlib_System_Runtime_Remoting_ObjRef.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 7 | 2015-03-10T03:36:16.000Z | 2021-11-05T01:16:58.000Z | MonoNative/mscorlib/System/Runtime/Remoting/mscorlib_System_Runtime_Remoting_ObjRef.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 1 | 2020-06-23T10:02:33.000Z | 2020-06-24T02:05:47.000Z | MonoNative/mscorlib/System/Runtime/Remoting/mscorlib_System_Runtime_Remoting_ObjRef.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | null | null | null | #include <mscorlib/System/Runtime/Remoting/mscorlib_System_Runtime_Remoting_ObjRef.h>
#include <mscorlib/System/mscorlib_System_String.h>
#include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_SerializationInfo.h>
#include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_StreamingContext.h>
namespace mscorlib
{
namespace System
{
namespace Runtime
{
namespace Remoting
{
//Public Methods
void ObjRef::GetObjectData(mscorlib::System::Runtime::Serialization::SerializationInfo info, mscorlib::System::Runtime::Serialization::StreamingContext context)
{
MonoType *__parameter_types__[2];
void *__parameters__[2];
__parameter_types__[0] = Global::GetType(typeid(info).name());
__parameter_types__[1] = Global::GetType(typeid(context).name());
__parameters__[0] = (MonoObject*)info;
__parameters__[1] = (MonoObject*)context;
Global::InvokeMethod("mscorlib", "System.Runtime.Remoting", "ObjRef", 0, NULL, "GetObjectData", __native_object__, 2, __parameter_types__, __parameters__, NULL);
}
mscorlib::System::Object ObjRef::GetRealObject(mscorlib::System::Runtime::Serialization::StreamingContext context)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(context).name());
__parameters__[0] = (MonoObject*)context;
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Runtime.Remoting", "ObjRef", 0, NULL, "GetRealObject", __native_object__, 1, __parameter_types__, __parameters__, NULL);
return mscorlib::System::Object(__result__);
}
mscorlib::System::Boolean ObjRef::IsFromThisAppDomain()
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Runtime.Remoting", "ObjRef", 0, NULL, "IsFromThisAppDomain", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
mscorlib::System::Boolean ObjRef::IsFromThisProcess()
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Runtime.Remoting", "ObjRef", 0, NULL, "IsFromThisProcess", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
//Get Set Properties Methods
// Get/Set:ChannelInfo
mscorlib::System::Runtime::Remoting::IChannelInfo ObjRef::get_ChannelInfo() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Runtime.Remoting", "ObjRef", 0, NULL, "get_ChannelInfo", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::Runtime::Remoting::IChannelInfo(__result__);
}
void ObjRef::set_ChannelInfo(mscorlib::System::Runtime::Remoting::IChannelInfo value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
Global::InvokeMethod("mscorlib", "System.Runtime.Remoting", "ObjRef", 0, NULL, "set_ChannelInfo", __native_object__, 1, __parameter_types__, __parameters__, NULL);
}
// Get/Set:EnvoyInfo
mscorlib::System::Runtime::Remoting::IEnvoyInfo ObjRef::get_EnvoyInfo() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Runtime.Remoting", "ObjRef", 0, NULL, "get_EnvoyInfo", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::Runtime::Remoting::IEnvoyInfo(__result__);
}
void ObjRef::set_EnvoyInfo(mscorlib::System::Runtime::Remoting::IEnvoyInfo value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
Global::InvokeMethod("mscorlib", "System.Runtime.Remoting", "ObjRef", 0, NULL, "set_EnvoyInfo", __native_object__, 1, __parameter_types__, __parameters__, NULL);
}
// Get/Set:TypeInfo
mscorlib::System::Runtime::Remoting::IRemotingTypeInfo ObjRef::get_TypeInfo() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Runtime.Remoting", "ObjRef", 0, NULL, "get_TypeInfo", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::Runtime::Remoting::IRemotingTypeInfo(__result__);
}
void ObjRef::set_TypeInfo(mscorlib::System::Runtime::Remoting::IRemotingTypeInfo value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
Global::InvokeMethod("mscorlib", "System.Runtime.Remoting", "ObjRef", 0, NULL, "set_TypeInfo", __native_object__, 1, __parameter_types__, __parameters__, NULL);
}
// Get/Set:URI
mscorlib::System::String ObjRef::get_URI() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Runtime.Remoting", "ObjRef", 0, NULL, "get_URI", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::String(__result__);
}
void ObjRef::set_URI(mscorlib::System::String value)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(value).name());
__parameters__[0] = (MonoObject*)value;
Global::InvokeMethod("mscorlib", "System.Runtime.Remoting", "ObjRef", 0, NULL, "set_URI", __native_object__, 1, __parameter_types__, __parameters__, NULL);
}
}
}
}
}
| 44.416 | 192 | 0.715058 | [
"object"
] |
92b467b8681c1c03ab586093e9f377a8f45a27fd | 4,113 | cpp | C++ | aws-cpp-sdk-s3/source/model/ListObjectsV2Result.cpp | bswhite1/aws-sdk-cpp | a050168cf8f7f6ea920d52894eaad186953cb27b | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-s3/source/model/ListObjectsV2Result.cpp | bswhite1/aws-sdk-cpp | a050168cf8f7f6ea920d52894eaad186953cb27b | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-s3/source/model/ListObjectsV2Result.cpp | bswhite1/aws-sdk-cpp | a050168cf8f7f6ea920d52894eaad186953cb27b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/s3/model/ListObjectsV2Result.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <utility>
using namespace Aws::S3::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
using namespace Aws;
ListObjectsV2Result::ListObjectsV2Result() :
m_isTruncated(false),
m_maxKeys(0),
m_encodingType(EncodingType::NOT_SET),
m_keyCount(0)
{
}
ListObjectsV2Result::ListObjectsV2Result(const Aws::AmazonWebServiceResult<XmlDocument>& result) :
m_isTruncated(false),
m_maxKeys(0),
m_encodingType(EncodingType::NOT_SET),
m_keyCount(0)
{
*this = result;
}
ListObjectsV2Result& ListObjectsV2Result::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
const XmlDocument& xmlDocument = result.GetPayload();
XmlNode resultNode = xmlDocument.GetRootElement();
if(!resultNode.IsNull())
{
XmlNode isTruncatedNode = resultNode.FirstChild("IsTruncated");
if(!isTruncatedNode.IsNull())
{
m_isTruncated = StringUtils::ConvertToBool(StringUtils::Trim(isTruncatedNode.GetText().c_str()).c_str());
}
XmlNode contentsNode = resultNode.FirstChild("Contents");
if(!contentsNode.IsNull())
{
XmlNode contentsMember = contentsNode;
while(!contentsMember.IsNull())
{
m_contents.push_back(contentsMember);
contentsMember = contentsMember.NextNode("Contents");
}
}
XmlNode nameNode = resultNode.FirstChild("Name");
if(!nameNode.IsNull())
{
m_name = nameNode.GetText();
}
XmlNode prefixNode = resultNode.FirstChild("Prefix");
if(!prefixNode.IsNull())
{
m_prefix = prefixNode.GetText();
}
XmlNode delimiterNode = resultNode.FirstChild("Delimiter");
if(!delimiterNode.IsNull())
{
m_delimiter = delimiterNode.GetText();
}
XmlNode maxKeysNode = resultNode.FirstChild("MaxKeys");
if(!maxKeysNode.IsNull())
{
m_maxKeys = StringUtils::ConvertToInt32(StringUtils::Trim(maxKeysNode.GetText().c_str()).c_str());
}
XmlNode commonPrefixesNode = resultNode.FirstChild("CommonPrefixes");
if(!commonPrefixesNode.IsNull())
{
XmlNode commonPrefixesMember = commonPrefixesNode;
while(!commonPrefixesMember.IsNull())
{
m_commonPrefixes.push_back(commonPrefixesMember);
commonPrefixesMember = commonPrefixesMember.NextNode("CommonPrefixes");
}
}
XmlNode encodingTypeNode = resultNode.FirstChild("EncodingType");
if(!encodingTypeNode.IsNull())
{
m_encodingType = EncodingTypeMapper::GetEncodingTypeForName(StringUtils::Trim(encodingTypeNode.GetText().c_str()).c_str());
}
XmlNode keyCountNode = resultNode.FirstChild("KeyCount");
if(!keyCountNode.IsNull())
{
m_keyCount = StringUtils::ConvertToInt32(StringUtils::Trim(keyCountNode.GetText().c_str()).c_str());
}
XmlNode continuationTokenNode = resultNode.FirstChild("ContinuationToken");
if(!continuationTokenNode.IsNull())
{
m_continuationToken = continuationTokenNode.GetText();
}
XmlNode nextContinuationTokenNode = resultNode.FirstChild("NextContinuationToken");
if(!nextContinuationTokenNode.IsNull())
{
m_nextContinuationToken = nextContinuationTokenNode.GetText();
}
XmlNode startAfterNode = resultNode.FirstChild("StartAfter");
if(!startAfterNode.IsNull())
{
m_startAfter = startAfterNode.GetText();
}
}
return *this;
}
| 32.132813 | 129 | 0.710917 | [
"model"
] |
92bdc01af7df746e338f16212870dab51a1f6a35 | 9,556 | hpp | C++ | libs/EL/EventLoop.hpp | CP-Panizza/REG2.0 | 581389f3f93b60ee4288629e04f852f73230bcff | [
"MIT"
] | null | null | null | libs/EL/EventLoop.hpp | CP-Panizza/REG2.0 | 581389f3f93b60ee4288629e04f852f73230bcff | [
"MIT"
] | null | null | null | libs/EL/EventLoop.hpp | CP-Panizza/REG2.0 | 581389f3f93b60ee4288629e04f852f73230bcff | [
"MIT"
] | null | null | null | //
// Created by cmj on 20-4-15.
//
#ifndef EVENTLOOP_EVENTLOOP_H
#define EVENTLOOP_EVENTLOOP_H
#include <functional>
#define MAXLINE 4096
#define MAX_COUNT 1024
#include "../../socket_header.h"
#include <string.h>
#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <vector>
#include "Event.hpp"
#include "CusEvent.hpp"
#include "TimeEvent.hpp"
#include "../../util.h"
#define pvoid void *
struct MiddleData {
#ifndef _WIN64
int fd;
MiddleData(int fd, const Event::CallBack &callBack) : fd(fd), callBack(callBack) {}
#else
SOCKET fd;
MiddleData(SOCKET fd, const Event::CallBack &callBack) : fd(fd), callBack(callBack) {}
#endif
Event::CallBack callBack;
};
class EventLoop {
public:
EventManger *customEventManger;
Event *events;
TimeEventManeger *timeEventManeger;
int cut_index; //事件列表分割线
bool running;
EventLoop() {
cut_index = MAX_COUNT;
};
void InitEvents() {
this->events = new Event[MAX_COUNT + 1];
}
void InitEventManger(){
this->customEventManger = new EventManger;
}
void InitTimeEventManeger(){
this->timeEventManeger = new TimeEventManeger;
}
void ShutDown(){
running = false;
std::cout << "[INFO]>> Server is shutdown" << std::endl;
exit(-1);
}
#ifndef _WIN64
int epoll_fd;
void CreateEpoll() throw(std::runtime_error) {
epoll_fd = epoll_create1(EPOLL_CLOEXEC);
if (epoll_fd == -1) {
throw std::runtime_error("[INIT_ERROR]>> create epoll faile");
}
}
//为fd挂载tcp处理函数
void LoadEventMap(int fd, Event::CallBack call_back) {
Event *accepter = &this->events[cut_index--];
accepter->data = new MiddleData(fd, call_back);
accepter->SetSrcFd(epoll_fd);
accepter->customEventManger = this->customEventManger;
accepter->el = this;
accepter->Set(fd, EPOLLIN, std::bind(&EventLoop::Accept, this, std::placeholders::_1));
}
//卸载fd上的tcp处理函数
void UnLoadEventMap(int fd, std::function<void(Event *ev)> unload_call_back){
for (int i = 0; i <= MAX_COUNT; ++i) {
auto ev = &this->events[i];
if(ev->fd == fd){
ev->ClearBuffer();
ev->Del();
ev->callBack = nullptr;
unload_call_back(ev);
}
}
}
void Accept(Event *ev) {
MiddleData *data_ptr = (MiddleData *) ev->data;
int i;
for (i = 0; i < cut_index; ++i) {
if (this->events[i].statu == EventStatu::Free) break;
}
if (i == cut_index) {
std::cout << "[warning]>> max events limited" << std::endl;
return;
}
int connfd = accept(data_ptr->fd, NULL, NULL);
if (connfd < 0) {
std::cout << "[ERROR]>> accept err" << std::endl;
return;
}
setnonblocking(connfd);
auto e = &this->events[i];
e->SetSrcFd(epoll_fd);
e->customEventManger = this->customEventManger;
e->el = this;
e->Set(connfd, EPOLLIN, data_ptr->callBack);
}
void Run() {
struct epoll_event epoll_events[MAX_COUNT + 1];
int i;
running = true;
while (running) {
struct timeval tv;
long now_sec, now_ms;
TimeEvent *te = this->timeEventManeger->GetNearestEvent();
if(te){
GetTime(&now_sec, &now_ms);
tv.tv_sec = te->when_sec - now_sec;
if(te->when_ms < now_ms){
tv.tv_usec = (te->when_ms + 1000 - now_ms)*1000;
tv.tv_sec--;
} else {
tv.tv_usec = (te->when_ms - now_ms)*1000;
}
if(tv.tv_sec < 0) tv.tv_sec = 0;
if(tv.tv_usec < 0) tv.tv_usec = 0;
} else {
tv.tv_sec = 0;
tv.tv_usec = 0;
}
int nfd = epoll_wait(this->epoll_fd, epoll_events, MAX_COUNT + 1, (tv.tv_sec*1000 + tv.tv_usec/1000));
for (i = 0; i < nfd; ++i) {
((Event *) epoll_events[i].data.ptr)->Call();
}
//处理自定义事件
this->customEventManger->ProcEvents();
//处理时间事件
this->timeEventManeger->ProcTimeEvent();
}
}
#else
public:
FDS fds;
void InitFDS(){
FD_ZERO(&fds.read_fd);
FD_ZERO(&fds.write_fd);
FD_ZERO(&fds._read_fd);
FD_ZERO(&fds._read_fd);
}
void LoadEventMap(SOCKET fd, Event::CallBack call_back) {
Event *accepter = &this->events[cut_index--];
accepter->data = new MiddleData(fd, call_back);
accepter->SetSrcFd(&fds);
accepter->customEventManger = this->customEventManger;
accepter->el = this;
accepter->Set(fd, SelectEvent::Read, std::bind(&EventLoop::Accept, this, std::placeholders::_1));
}
void Accept(Event *ev) {
auto *data_ptr = (MiddleData *) ev->data;
int i;
for (i = 0; i < cut_index; ++i) {
if (this->events[i].statu == EventStatu::Free) break;
}
if (i == cut_index) {
std::cout << "[warning]>> max events limited" << std::endl;
return;
}
SOCKET connfd = accept(data_ptr->fd, NULL, NULL);
if (connfd < 0) {
std::cout << "[ERROR]>> accept err" << std::endl;
return;
}
printf("accept a clinet %d\n", connfd);
if (setnonblocking(connfd) == -1) {
printf("[ERROR]>> clinet %d set nonblock err\n", connfd);
closesocket(connfd);
return;
}
auto e = &this->events[i];
e->SetSrcFd(&this->fds);
e->customEventManger = this->customEventManger;
e->el = this;
e->Set(connfd, SelectEvent::Read, data_ptr->callBack);
}
int GetEventByFd(int s) {
int i;
for (i = 0; i <= MAX_COUNT; ++i) {
if (this->events[i].fd == s && this->events[i].statu == EventStatu::Using) break;
}
if (i > MAX_COUNT) {
std::cout << "[warning]>> max events limited" << std::endl;
return -1;
} else {
return i;
}
}
void Run() {
int ret;
running = true;
while (running) {
FD_ZERO(&this->fds._write_fd);
FD_ZERO(&this->fds._read_fd);
this->fds._read_fd = this->fds.read_fd;
this->fds._write_fd = this->fds.write_fd;
struct timeval tv;
long now_sec, now_ms;
TimeEvent *te = this->timeEventManeger->GetNearestEvent();
if(te){
GetTime(&now_sec, &now_ms);
tv.tv_sec = te->when_sec - now_sec;
if(te->when_ms < now_ms){
tv.tv_usec = (te->when_ms + 1000 - now_ms)*1000;
tv.tv_sec--;
} else {
tv.tv_usec = (te->when_ms - now_ms)*1000;
}
if(tv.tv_sec < 0) tv.tv_sec = 0;
if(tv.tv_usec < 0) tv.tv_usec = 0;
} else {
tv.tv_sec = 0;
tv.tv_usec = 0;
}
ret = select(0, &this->fds._read_fd, &this->fds._write_fd, NULL, &tv);//最后一个参数为NULL,一直等待,直到有数据过来,客户端断开也会触发读/写状态,然后判断recv返回值是否为0,为0这说明客户端断开连接
if (ret == SOCKET_ERROR) {
printf("[ERROR]>> select err!");
WSACleanup();
exit(-1);
}
if (ret > 0) {
for (int j = 0; j < this->fds._read_fd.fd_count; ++j) {
SOCKET s = this->fds._read_fd.fd_array[j];
if(FD_ISSET(s, &this->fds._read_fd)){
int index = GetEventByFd(s);
if (index == -1) {
printf("[ERROR]>> find Event Err!");
WSACleanup();
exit(-1);
}
(&this->events[index])->Call();
}
}
for (int k = 0; k < this->fds._write_fd.fd_count; ++k) {
SOCKET s = this->fds._write_fd.fd_array[k];
if(FD_ISSET(s, &this->fds._write_fd)){
int index = GetEventByFd(s);
if (index == -1) {
printf("[ERROR]>> find Event Err!");
WSACleanup();
exit(-1);
}
(&this->events[index])->Call();
}
}
// for (int i = 0; i <= MAX_COUNT; ++i) {
// if (FD_ISSET(i, &this->fds._read_fd) || FD_ISSET(i, &this->fds._write_fd)) {
// int index = GetEventByFd(i);
// if (index == -1) {
// printf("[ERROR]>> find Event Err!");
// WSACleanup();
// exit(-1);
// }
// (&this->events[index])->Call();
// }
// }
}
//处理自定义事件
this->customEventManger->ProcEvents();
//处理时间事件
this->timeEventManeger->ProcTimeEvent();
}
}
#endif
};
#endif //EVENTLOOP_EVENTLOOP_H
| 26.470914 | 152 | 0.477606 | [
"vector"
] |
92bde3ee90448fcbfc529d4255503effff5175e3 | 1,214 | cpp | C++ | source/82.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | 2 | 2017-02-28T11:39:13.000Z | 2019-12-07T17:23:20.000Z | source/82.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | null | null | null | source/82.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | null | null | null | //
// 82.cpp
// LeetCode
//
// Created by Narikbi on 14.04.17.
// Copyright © 2017 app.leetcode.kz. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <cmath>
#include <numeric>
#include <unordered_map>
#include <sstream>
#include <unordered_set>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* deleteDuplicates(ListNode* head) {
ListNode fakeNode(0);
fakeNode.next = head;
head = &fakeNode;
ListNode *tail = head;
bool dups = false;
for (ListNode *p = head->next; p && p->next; p = p->next) {
if (dups == false && p->val == p->next->val) {
dups = true;
continue;
}
if (dups == true && p->val != p->next->val) {
dups = false;
tail->next = p->next;
continue;
}
if (!dups) {
tail = p;
}
}
if (dups == true){
tail->next = NULL;
}
return head->next;
}
| 17.852941 | 63 | 0.526359 | [
"vector"
] |
92d62a1777648fb8f2412d003f4758f890510b1d | 52,533 | cpp | C++ | src/theory/quantifiers/ce_guided_single_inv.cpp | FabianWolff/cvc4-debian | e38afe6cb10bdb79f0bae398b9605e4deae7578f | [
"BSL-1.0"
] | null | null | null | src/theory/quantifiers/ce_guided_single_inv.cpp | FabianWolff/cvc4-debian | e38afe6cb10bdb79f0bae398b9605e4deae7578f | [
"BSL-1.0"
] | null | null | null | src/theory/quantifiers/ce_guided_single_inv.cpp | FabianWolff/cvc4-debian | e38afe6cb10bdb79f0bae398b9605e4deae7578f | [
"BSL-1.0"
] | null | null | null | /********************* */
/*! \file ce_guided_single_inv.cpp
** \verbatim
** Top contributors (to current version):
** Andrew Reynolds, Tim King
** This file is part of the CVC4 project.
** Copyright (c) 2009-2016 by the authors listed in the file AUTHORS
** in the top-level source directory) and their institutional affiliations.
** All rights reserved. See the file COPYING in the top-level source
** directory for licensing information.\endverbatim
**
** \brief utility for processing single invocation synthesis conjectures
**
**/
#include "theory/quantifiers/ce_guided_single_inv.h"
#include "expr/datatype.h"
#include "options/quantifiers_options.h"
#include "theory/quantifiers/ce_guided_instantiation.h"
#include "theory/quantifiers/ce_guided_single_inv_ei.h"
#include "theory/quantifiers/first_order_model.h"
#include "theory/quantifiers/quant_util.h"
#include "theory/quantifiers/term_database.h"
#include "theory/quantifiers/trigger.h"
#include "theory/theory_engine.h"
using namespace CVC4;
using namespace CVC4::kind;
using namespace CVC4::theory;
using namespace CVC4::theory::quantifiers;
using namespace std;
namespace CVC4 {
bool CegqiOutputSingleInv::doAddInstantiation( std::vector< Node >& subs ) {
return d_out->doAddInstantiation( subs );
}
bool CegqiOutputSingleInv::isEligibleForInstantiation( Node n ) {
return d_out->isEligibleForInstantiation( n );
}
bool CegqiOutputSingleInv::addLemma( Node n ) {
return d_out->addLemma( n );
}
CegConjectureSingleInv::CegConjectureSingleInv(QuantifiersEngine* qe,
CegConjecture* p)
: d_qe(qe),
d_parent(p),
d_sip(new SingleInvocationPartition),
d_sol(new CegConjectureSingleInvSol(qe)),
d_ei(NULL),
d_cosi(new CegqiOutputSingleInv(this)),
d_cinst(NULL),
d_c_inst_match_trie(NULL),
d_has_ites(true) {
// third and fourth arguments set to (false,false) until we have solution
// reconstruction for delta and infinity
d_cinst = new CegInstantiator(d_qe, d_cosi, false, false);
if (options::incrementalSolving()) {
d_c_inst_match_trie = new inst::CDInstMatchTrie(qe->getUserContext());
}
if (options::cegqiSingleInvPartial()) {
d_ei = new CegEntailmentInfer(qe, d_sip);
}
}
CegConjectureSingleInv::~CegConjectureSingleInv() {
if (d_c_inst_match_trie) {
delete d_c_inst_match_trie;
}
delete d_cinst;
delete d_cosi;
if (d_ei) {
delete d_ei;
}
delete d_sol; // (new CegConjectureSingleInvSol(qe)),
delete d_sip; // d_sip(new SingleInvocationPartition),
}
void CegConjectureSingleInv::getInitialSingleInvLemma( std::vector< Node >& lems ) {
Assert( d_si_guard.isNull() );
//single invocation guard
d_si_guard = Rewriter::rewrite( NodeManager::currentNM()->mkSkolem( "G", NodeManager::currentNM()->booleanType() ) );
d_si_guard = d_qe->getValuation().ensureLiteral( d_si_guard );
AlwaysAssert( !d_si_guard.isNull() );
d_qe->getOutputChannel().requirePhase( d_si_guard, true );
if( !d_single_inv.isNull() ) {
//make for new var/sk
d_single_inv_var.clear();
d_single_inv_sk.clear();
Node inst;
if( d_single_inv.getKind()==FORALL ){
for( unsigned i=0; i<d_single_inv[0].getNumChildren(); i++ ){
std::stringstream ss;
ss << "k_" << d_single_inv[0][i];
Node k = NodeManager::currentNM()->mkSkolem( ss.str(), d_single_inv[0][i].getType(), "single invocation function skolem" );
d_single_inv_var.push_back( d_single_inv[0][i] );
d_single_inv_sk.push_back( k );
d_single_inv_sk_index[k] = i;
}
inst = d_single_inv[1].substitute( d_single_inv_var.begin(), d_single_inv_var.end(), d_single_inv_sk.begin(), d_single_inv_sk.end() );
}else{
inst = d_single_inv;
}
inst = TermDb::simpleNegate( inst );
Trace("cegqi-si") << "Single invocation initial lemma : " << inst << std::endl;
//register with the instantiator
Node ginst = NodeManager::currentNM()->mkNode( OR, d_si_guard.negate(), inst );
lems.push_back( ginst );
//make and register the instantiator
if( d_cinst ){
delete d_cinst;
}
d_cinst = new CegInstantiator( d_qe, d_cosi, false, false );
d_cinst->registerCounterexampleLemma( lems, d_single_inv_sk );
}
}
void CegConjectureSingleInv::initialize( Node q ) {
Assert( d_quant.isNull() );
Assert( options::cegqiSingleInvMode()!=CEGQI_SI_MODE_NONE );
//initialize data
d_quant = q;
//process
Trace("cegqi-si") << "Initialize cegqi-si for " << q << std::endl;
// conj -> conj*
std::map< Node, std::vector< Node > > children;
// conj X prog -> inv*
std::map< Node, std::map< Node, std::vector< Node > > > prog_invoke;
std::vector< Node > progs;
std::map< Node, std::map< Node, bool > > contains;
bool is_syntax_restricted = false;
for( unsigned i=0; i<q[0].getNumChildren(); i++ ){
progs.push_back( q[0][i] );
//check whether all types have ITE
TypeNode tn = q[0][i].getType();
d_qe->getTermDatabaseSygus()->registerSygusType( tn );
if( !d_qe->getTermDatabaseSygus()->sygusToBuiltinType( tn ).isBoolean() ){
if( !d_qe->getTermDatabaseSygus()->hasKind( tn, ITE ) ){
d_has_ites = false;
}
}
Assert( tn.isDatatype() );
const Datatype& dt = ((DatatypeType)(tn).toType()).getDatatype();
Assert( dt.isSygus() );
if( !dt.getSygusAllowAll() ){
is_syntax_restricted = true;
}
}
//abort if not aggressive
bool singleInvocation = true;
if( options::cegqiSingleInvMode()==CEGQI_SI_MODE_USE && is_syntax_restricted ){
singleInvocation = false;
Trace("cegqi-si") << "...grammar is restricted, do not use single invocation techniques." << std::endl;
}else{
Node qq = q[1];
if( q[1].getKind()==NOT && q[1][0].getKind()==FORALL ){
qq = q[1][0][1];
}else{
qq = TermDb::simpleNegate( qq );
}
//remove the deep embedding
std::map< Node, Node > visited;
std::vector< TypeNode > types;
std::vector< Node > order_vars;
std::map< Node, Node > single_inv_app_map;
int type_valid = 0;
qq = removeDeepEmbedding( qq, progs, types, type_valid, visited );
Trace("cegqi-si-debug") << "- Remove deep embedding, got : " << qq << ", type valid = " << type_valid << std::endl;
if( type_valid==0 ){
//process the single invocation-ness of the property
d_sip->init( types, qq );
Trace("cegqi-si") << "- Partitioned to single invocation parts : " << std::endl;
d_sip->debugPrint( "cegqi-si" );
//map from program to bound variables
for( unsigned j=0; j<progs.size(); j++ ){
Node prog = progs[j];
std::map< Node, Node >::iterator it_nsi = d_nsi_op_map.find( prog );
if( it_nsi!=d_nsi_op_map.end() ){
Node op = it_nsi->second;
std::map< Node, Node >::iterator it_fov = d_sip->d_func_fo_var.find( op );
if( it_fov!=d_sip->d_func_fo_var.end() ){
Node pv = it_fov->second;
Assert( d_sip->d_func_inv.find( op )!=d_sip->d_func_inv.end() );
Node inv = d_sip->d_func_inv[op];
single_inv_app_map[prog] = inv;
Trace("cegqi-si") << " " << pv << ", " << inv << " is associated with program " << prog << std::endl;
d_prog_to_sol_index[prog] = order_vars.size();
order_vars.push_back( pv );
}
}else{
//does not mention the function
}
}
//reorder the variables
Assert( d_sip->d_func_vars.size()==order_vars.size() );
d_sip->d_func_vars.clear();
d_sip->d_func_vars.insert( d_sip->d_func_vars.begin(), order_vars.begin(), order_vars.end() );
//check if it is single invocation
if( !d_sip->d_conjuncts[1].empty() ){
singleInvocation = false;
if( options::cegqiSingleInvPartial() ){
//this enables partially single invocation techniques
d_nsingle_inv = d_sip->getNonSingleInvocation();
d_nsingle_inv = TermDb::simpleNegate( d_nsingle_inv );
d_full_inv = d_sip->getFullSpecification();
d_full_inv = TermDb::simpleNegate( d_full_inv );
singleInvocation = true;
}else if( options::sygusInvTemplMode() != SYGUS_INV_TEMPL_MODE_NONE ){
//if we are doing invariant templates, then construct the template
std::map< Node, bool > has_inv;
std::map< Node, std::vector< Node > > inv_pre_post[2];
for( unsigned i=0; i<d_sip->d_conjuncts[2].size(); i++ ){
std::vector< Node > disjuncts;
Node func;
int pol = -1;
Trace("cegqi-inv") << "INV process " << d_sip->d_conjuncts[2][i] << std::endl;
d_sip->extractInvariant( d_sip->d_conjuncts[2][i], func, pol, disjuncts );
if( pol>=0 ){
Assert( d_nsi_op_map_to_prog.find( func )!=d_nsi_op_map_to_prog.end() );
Node prog = d_nsi_op_map_to_prog[func];
Trace("cegqi-inv") << "..." << ( pol==0 ? "pre" : "post" ) << "-condition for " << prog << "." << std::endl;
Node c = disjuncts.empty() ? d_qe->getTermDatabase()->d_false : ( disjuncts.size()==1 ? disjuncts[0] : NodeManager::currentNM()->mkNode( OR, disjuncts ) );
c = pol==0 ? TermDb::simpleNegate( c ) : c;
Trace("cegqi-inv-debug") << "...extracted : " << c << std::endl;
inv_pre_post[pol][prog].push_back( c );
has_inv[prog] = true;
}else{
Trace("cegqi-inv") << "...no status." << std::endl;
}
}
Trace("cegqi-inv") << "Constructing invariant templates..." << std::endl;
//now, contruct the template for the invariant(s)
std::map< Node, Node > prog_templ;
for( std::map< Node, bool >::iterator iti = has_inv.begin(); iti != has_inv.end(); ++iti ){
Node prog = iti->first;
Trace("cegqi-inv") << "...for " << prog << "..." << std::endl;
Trace("cegqi-inv") << " args : ";
for( unsigned j=0; j<d_sip->d_si_vars.size(); j++ ){
std::stringstream ss;
ss << "i_" << j;
Node v = NodeManager::currentNM()->mkBoundVar( ss.str(), d_sip->d_si_vars[j].getType() );
d_prog_templ_vars[prog].push_back( v );
Trace("cegqi-inv") << v << " ";
}
Trace("cegqi-inv") << std::endl;
Node pre = inv_pre_post[0][prog].empty() ? NodeManager::currentNM()->mkConst( false ) :
( inv_pre_post[0][prog].size()==1 ? inv_pre_post[0][prog][0] : NodeManager::currentNM()->mkNode( OR, inv_pre_post[0][prog] ) );
d_trans_pre[prog] = pre.substitute( d_sip->d_si_vars.begin(), d_sip->d_si_vars.end(), d_prog_templ_vars[prog].begin(), d_prog_templ_vars[prog].end() );
Node post = inv_pre_post[1][prog].empty() ? NodeManager::currentNM()->mkConst( true ) :
( inv_pre_post[1][prog].size()==1 ? inv_pre_post[1][prog][0] : NodeManager::currentNM()->mkNode( AND, inv_pre_post[1][prog] ) );
d_trans_post[prog] = post.substitute( d_sip->d_si_vars.begin(), d_sip->d_si_vars.end(), d_prog_templ_vars[prog].begin(), d_prog_templ_vars[prog].end() );
Trace("cegqi-inv") << " precondition : " << d_trans_pre[prog] << std::endl;
Trace("cegqi-inv") << " postcondition : " << d_trans_post[prog] << std::endl;
Node invariant = single_inv_app_map[prog];
invariant = invariant.substitute( d_sip->d_si_vars.begin(), d_sip->d_si_vars.end(), d_prog_templ_vars[prog].begin(), d_prog_templ_vars[prog].end() );
Trace("cegqi-inv") << " invariant : " << invariant << std::endl;
//construct template
Node templ;
if( options::sygusInvTemplMode() == SYGUS_INV_TEMPL_MODE_PRE ){
//templ = NodeManager::currentNM()->mkNode( AND, NodeManager::currentNM()->mkNode( OR, d_trans_pre[prog], invariant ), d_trans_post[prog] );
templ = NodeManager::currentNM()->mkNode( OR, d_trans_pre[prog], invariant );
}else{
Assert( options::sygusInvTemplMode() == SYGUS_INV_TEMPL_MODE_POST );
//templ = NodeManager::currentNM()->mkNode( OR, d_trans_pre[prog], NodeManager::currentNM()->mkNode( AND, d_trans_post[prog], invariant ) );
templ = NodeManager::currentNM()->mkNode( AND, d_trans_post[prog], invariant );
}
visited.clear();
templ = addDeepEmbedding( templ, visited );
Trace("cegqi-inv") << " template : " << templ << std::endl;
prog_templ[prog] = templ;
}
Node bd = d_sip->d_conjuncts[2].size()==1 ? d_sip->d_conjuncts[2][0] : NodeManager::currentNM()->mkNode( AND, d_sip->d_conjuncts[2] );
visited.clear();
bd = addDeepEmbedding( bd, visited );
Trace("cegqi-inv") << " body : " << bd << std::endl;
bd = substituteInvariantTemplates( bd, prog_templ, d_prog_templ_vars );
Trace("cegqi-inv-debug") << " templ-subs body : " << bd << std::endl;
//make inner existential
std::vector< Node > new_var_bv;
for( unsigned j=0; j<d_sip->d_si_vars.size(); j++ ){
std::stringstream ss;
ss << "ss_" << j;
new_var_bv.push_back( NodeManager::currentNM()->mkBoundVar( ss.str(), d_sip->d_si_vars[j].getType() ) );
}
bd = bd.substitute( d_sip->d_si_vars.begin(), d_sip->d_si_vars.end(), new_var_bv.begin(), new_var_bv.end() );
Assert( q[1].getKind()==NOT && q[1][0].getKind()==FORALL );
for( unsigned j=0; j<q[1][0][0].getNumChildren(); j++ ){
new_var_bv.push_back( q[1][0][0][j] );
}
if( !new_var_bv.empty() ){
Node bvl = NodeManager::currentNM()->mkNode( BOUND_VAR_LIST, new_var_bv );
bd = NodeManager::currentNM()->mkNode( FORALL, bvl, bd ).negate();
}
//make outer universal
bd = NodeManager::currentNM()->mkNode( FORALL, q[0], bd );
bd = Rewriter::rewrite( bd );
Trace("cegqi-inv") << " rtempl-subs body : " << bd << std::endl;
d_quant = bd;
}
}else{
//we are fully single invocation
}
}else{
Trace("cegqi-si") << "...property is not single invocation, involves functions with different argument sorts." << std::endl;
singleInvocation = false;
}
}
if( singleInvocation ){
d_single_inv = d_sip->getSingleInvocation();
d_single_inv = TermDb::simpleNegate( d_single_inv );
if( !d_sip->d_func_vars.empty() ){
Node pbvl = NodeManager::currentNM()->mkNode( BOUND_VAR_LIST, d_sip->d_func_vars );
d_single_inv = NodeManager::currentNM()->mkNode( FORALL, pbvl, d_single_inv );
}
//now, introduce the skolems
for( unsigned i=0; i<d_sip->d_si_vars.size(); i++ ){
Node v = NodeManager::currentNM()->mkSkolem( "a", d_sip->d_si_vars[i].getType(), "single invocation arg" );
d_single_inv_arg_sk.push_back( v );
}
d_single_inv = d_single_inv.substitute( d_sip->d_si_vars.begin(), d_sip->d_si_vars.end(), d_single_inv_arg_sk.begin(), d_single_inv_arg_sk.end() );
Trace("cegqi-si") << "Single invocation formula is : " << d_single_inv << std::endl;
if( options::cbqiPreRegInst() && d_single_inv.getKind()==FORALL ){
//just invoke the presolve now
d_cinst->presolve( d_single_inv );
}
if( !isFullySingleInvocation() ){
//initialize information as next single invocation conjecture
initializeNextSiConjecture();
Trace("cegqi-si") << "Non-single invocation formula is : " << d_nsingle_inv << std::endl;
Trace("cegqi-si") << "Full specification is : " << d_full_inv << std::endl;
//add full specification lemma : will use for testing infeasibility/deriving entailments
d_full_guard = Rewriter::rewrite( NodeManager::currentNM()->mkSkolem( "GF", NodeManager::currentNM()->booleanType() ) );
d_full_guard = d_qe->getValuation().ensureLiteral( d_full_guard );
AlwaysAssert( !d_full_guard.isNull() );
d_qe->getOutputChannel().requirePhase( d_full_guard, true );
Node fbvl;
if( !d_sip->d_all_vars.empty() ){
fbvl = NodeManager::currentNM()->mkNode( BOUND_VAR_LIST, d_sip->d_all_vars );
}
//should construct this conjunction directly since miniscoping is disabled
std::vector< Node > flem_c;
for( unsigned i=0; i<d_sip->d_conjuncts[2].size(); i++ ){
Node flemi = d_sip->d_conjuncts[2][i];
if( !fbvl.isNull() ){
flemi = NodeManager::currentNM()->mkNode( FORALL, fbvl, flemi );
}
flem_c.push_back( flemi );
}
Node flem = flem_c.empty() ? d_qe->getTermDatabase()->d_true : ( flem_c.size()==1 ? flem_c[0] : NodeManager::currentNM()->mkNode( AND, flem_c ) );
flem = NodeManager::currentNM()->mkNode( OR, d_full_guard.negate(), flem );
flem = Rewriter::rewrite( flem );
Trace("cegqi-lemma") << "Cegqi::Lemma : full specification " << flem << std::endl;
d_qe->getOutputChannel().lemma( flem );
}
}else{
Trace("cegqi-si") << "Formula is not single invocation." << std::endl;
if( options::cegqiSingleInvAbort() ){
Notice() << "Property is not single invocation." << std::endl;
exit( 0 );
}
}
}
Node CegConjectureSingleInv::substituteInvariantTemplates( Node n, std::map< Node, Node >& prog_templ, std::map< Node, std::vector< Node > >& prog_templ_vars ) {
if( n.getKind()==APPLY_UF && n.getNumChildren()>0 ){
std::map< Node, Node >::iterator it = prog_templ.find( n[0] );
if( it!=prog_templ.end() ){
std::vector< Node > children;
for( unsigned i=1; i<n.getNumChildren(); i++ ){
children.push_back( n[i] );
}
std::map< Node, std::vector< Node > >::iterator itv = prog_templ_vars.find( n[0] );
Assert( itv!=prog_templ_vars.end() );
Assert( children.size()==itv->second.size() );
Node newc = it->second.substitute( itv->second.begin(), itv->second.end(), children.begin(), children.end() );
return newc;
}
}
bool childChanged = false;
std::vector< Node > children;
for( unsigned i=0; i<n.getNumChildren(); i++ ){
Node nn = substituteInvariantTemplates( n[i], prog_templ, prog_templ_vars );
children.push_back( nn );
childChanged = childChanged || ( nn!=n[i] );
}
if( childChanged ){
if( n.getMetaKind() == kind::metakind::PARAMETERIZED ){
children.insert( children.begin(), n.getOperator() );
}
return NodeManager::currentNM()->mkNode( n.getKind(), children );
}else{
return n;
}
}
Node CegConjectureSingleInv::removeDeepEmbedding( Node n, std::vector< Node >& progs, std::vector< TypeNode >& types, int& type_valid,
std::map< Node, Node >& visited ) {
std::map< Node, Node >::iterator itv = visited.find( n );
if( itv!=visited.end() ){
return itv->second;
}else{
std::vector< Node > children;
bool childChanged = false;
for( unsigned i=0; i<n.getNumChildren(); i++ ){
Node ni = removeDeepEmbedding( n[i], progs, types, type_valid, visited );
childChanged = childChanged || n[i]!=ni;
children.push_back( ni );
}
Node ret;
if( n.getKind()==APPLY_UF ){
Assert( n.getNumChildren()>0 );
if( std::find( progs.begin(), progs.end(), n[0] )!=progs.end() ){
std::map< Node, Node >::iterator it = d_nsi_op_map.find( n[0] );
Node op;
if( it==d_nsi_op_map.end() ){
bool checkTypes = !types.empty();
std::vector< TypeNode > argTypes;
for( unsigned j=1; j<n.getNumChildren(); j++ ){
TypeNode tn = n[j].getType();
argTypes.push_back( tn );
if( checkTypes ){
if( j>=types.size()+1 || tn!=types[j-1] ){
type_valid = -1;
}
}else{
types.push_back( tn );
}
}
TypeNode ft = argTypes.empty() ? n.getType() : NodeManager::currentNM()->mkFunctionType( argTypes, n.getType() );
std::stringstream ss2;
ss2 << "O_" << n[0];
op = NodeManager::currentNM()->mkSkolem( ss2.str(), ft, "was created for non-single invocation reasoning" );
d_prog_to_eval_op[n[0]] = n.getOperator();
d_nsi_op_map[n[0]] = op;
d_nsi_op_map_to_prog[op] = n[0];
Trace("cegqi-si-debug2") << "Make operator " << op << " for " << n[0] << std::endl;
}else{
op = it->second;
}
children[0] = d_nsi_op_map[n[0]];
ret = NodeManager::currentNM()->mkNode( APPLY_UF, children );
}
}
if( ret.isNull() ){
ret = n;
if( childChanged ){
if( n.getMetaKind() == kind::metakind::PARAMETERIZED ){
children.insert( children.begin(), n.getOperator() );
}
ret = NodeManager::currentNM()->mkNode( n.getKind(), children );
}
}
visited[n] = ret;
return ret;
}
}
Node CegConjectureSingleInv::addDeepEmbedding( Node n, std::map< Node, Node >& visited ) {
std::map< Node, Node >::iterator itv = visited.find( n );
if( itv!=visited.end() ){
return itv->second;
}else{
std::vector< Node > children;
bool childChanged = false;
for( unsigned i=0; i<n.getNumChildren(); i++ ){
Node ni = addDeepEmbedding( n[i], visited );
childChanged = childChanged || n[i]!=ni;
children.push_back( ni );
}
Node ret;
if( n.getKind()==APPLY_UF ){
Node op = n.getOperator();
std::map< Node, Node >::iterator it = d_nsi_op_map_to_prog.find( op );
if( it!=d_nsi_op_map_to_prog.end() ){
Node prog = it->second;
children.insert( children.begin(), prog );
Assert( d_prog_to_eval_op.find( prog )!=d_prog_to_eval_op.end() );
children.insert( children.begin(), d_prog_to_eval_op[prog] );
ret = NodeManager::currentNM()->mkNode( APPLY_UF, children );
}
}
if( ret.isNull() ){
ret = n;
if( childChanged ){
if( n.getMetaKind() == kind::metakind::PARAMETERIZED ){
children.insert( children.begin(), n.getOperator() );
}
ret = NodeManager::currentNM()->mkNode( n.getKind(), children );
}
}
visited[n] = ret;
return ret;
}
}
void CegConjectureSingleInv::initializeNextSiConjecture() {
Trace("cegqi-nsi") << "NSI : initialize next candidate conjecture..." << std::endl;
if( d_single_inv.isNull() ){
if( d_ei->getEntailedConjecture( d_single_inv, d_single_inv_exp ) ){
Trace("cegqi-nsi") << "NSI : got : " << d_single_inv << std::endl;
Trace("cegqi-nsi") << "NSI : exp : " << d_single_inv_exp << std::endl;
}else{
Trace("cegqi-nsi") << "NSI : failed to construct next conjecture." << std::endl;
Notice() << "Incomplete due to --cegqi-si-partial." << std::endl;
exit( 10 );
}
}else{
//initial call
Trace("cegqi-nsi") << "NSI : have : " << d_single_inv << std::endl;
Assert( d_single_inv_exp.isNull() );
}
d_si_guard = Node::null();
d_ns_guard = Rewriter::rewrite( NodeManager::currentNM()->mkSkolem( "GS", NodeManager::currentNM()->booleanType() ) );
d_ns_guard = d_qe->getValuation().ensureLiteral( d_ns_guard );
AlwaysAssert( !d_ns_guard.isNull() );
d_qe->getOutputChannel().requirePhase( d_ns_guard, true );
d_lemmas_produced.clear();
if( options::incrementalSolving() ){
delete d_c_inst_match_trie;
d_c_inst_match_trie = new inst::CDInstMatchTrie( d_qe->getUserContext() );
}else{
d_inst_match_trie.clear();
}
Trace("cegqi-nsi") << "NSI : initialize next candidate conjecture, ns guard = " << d_ns_guard << std::endl;
Trace("cegqi-nsi") << "NSI : conjecture is " << d_single_inv << std::endl;
}
bool CegConjectureSingleInv::doAddInstantiation( std::vector< Node >& subs ){
std::stringstream siss;
if( Trace.isOn("cegqi-si-inst-debug") || Trace.isOn("cegqi-engine") ){
siss << " * single invocation: " << std::endl;
for( unsigned j=0; j<d_single_inv_sk.size(); j++ ){
Assert( d_sip->d_fo_var_to_func.find( d_single_inv[0][j] )!=d_sip->d_fo_var_to_func.end() );
Node op = d_sip->d_fo_var_to_func[d_single_inv[0][j]];
Assert( d_nsi_op_map_to_prog.find( op )!=d_nsi_op_map_to_prog.end() );
Node prog = d_nsi_op_map_to_prog[op];
siss << " * " << prog;
siss << " (" << d_single_inv_sk[j] << ")";
siss << " -> " << subs[j] << std::endl;
}
}
bool alreadyExists;
if( options::incrementalSolving() ){
alreadyExists = !d_c_inst_match_trie->addInstMatch( d_qe, d_single_inv, subs, d_qe->getUserContext() );
}else{
alreadyExists = !d_inst_match_trie.addInstMatch( d_qe, d_single_inv, subs );
}
Trace("cegqi-si-inst-debug") << siss.str();
Trace("cegqi-si-inst-debug") << " * success = " << !alreadyExists << std::endl;
if( alreadyExists ){
return false;
}else{
Trace("cegqi-engine") << siss.str() << std::endl;
Assert( d_single_inv_var.size()==subs.size() );
Node lem = d_single_inv[1].substitute( d_single_inv_var.begin(), d_single_inv_var.end(), subs.begin(), subs.end() );
if( d_qe->getTermDatabase()->containsVtsTerm( lem ) ){
Trace("cegqi-engine-debug") << "Rewrite based on vts symbols..." << std::endl;
lem = d_qe->getTermDatabase()->rewriteVtsSymbols( lem );
}
Trace("cegqi-engine-debug") << "Rewrite..." << std::endl;
lem = Rewriter::rewrite( lem );
Trace("cegqi-si") << "Single invocation lemma : " << lem << std::endl;
if( std::find( d_lemmas_produced.begin(), d_lemmas_produced.end(), lem )==d_lemmas_produced.end() ){
d_curr_lemmas.push_back( lem );
d_lemmas_produced.push_back( lem );
d_inst.push_back( std::vector< Node >() );
d_inst.back().insert( d_inst.back().end(), subs.begin(), subs.end() );
}
return true;
}
}
bool CegConjectureSingleInv::isEligibleForInstantiation( Node n ) {
return n.getKind()!=SKOLEM || std::find( d_single_inv_arg_sk.begin(), d_single_inv_arg_sk.end(), n )!=d_single_inv_arg_sk.end();
}
bool CegConjectureSingleInv::addLemma( Node n ) {
d_curr_lemmas.push_back( n );
return true;
}
bool CegConjectureSingleInv::check( std::vector< Node >& lems ) {
if( !d_single_inv.isNull() ) {
if( !d_ns_guard.isNull() ){
//if partially single invocation, check if we have constructed a candidate by refutation
bool value;
if( d_qe->getValuation().hasSatValue( d_ns_guard, value ) ) {
if( !value ){
//construct candidate solution
Trace("cegqi-nsi") << "NSI : refuted current candidate conjecture, construct corresponding solution..." << std::endl;
d_ns_guard = Node::null();
std::map< Node, Node > lams;
for( unsigned i=0; i<d_quant[0].getNumChildren(); i++ ){
Node prog = d_quant[0][i];
int rcons;
Node sol = getSolution( i, prog.getType(), rcons, false );
Trace("cegqi-nsi") << " solution for " << prog << " : " << sol << std::endl;
//make corresponding lambda
std::map< Node, Node >::iterator it_nso = d_nsi_op_map.find( prog );
if( it_nso!=d_nsi_op_map.end() ){
lams[it_nso->second] = sol;
}else{
Assert( false );
}
}
//now, we will check if this candidate solution satisfies the non-single-invocation portion of the specification
Node inst = d_sip->getSpecificationInst( 1, lams );
Trace("cegqi-nsi") << "NSI : specification instantiation : " << inst << std::endl;
inst = TermDb::simpleNegate( inst );
std::vector< Node > subs;
for( unsigned i=0; i<d_sip->d_all_vars.size(); i++ ){
subs.push_back( NodeManager::currentNM()->mkSkolem( "kv", d_sip->d_all_vars[i].getType(), "created for verifying nsi" ) );
}
Assert( d_sip->d_all_vars.size()==subs.size() );
inst = inst.substitute( d_sip->d_all_vars.begin(), d_sip->d_all_vars.end(), subs.begin(), subs.end() );
Trace("cegqi-nsi") << "NSI : verification : " << inst << std::endl;
Trace("cegqi-lemma") << "Cegqi::Lemma : verification lemma : " << inst << std::endl;
d_qe->addLemma( inst );
/*
Node finst = d_sip->getFullSpecification();
finst = finst.substitute( d_sip->d_all_vars.begin(), d_sip->d_all_vars.end(), subs.begin(), subs.end() );
Trace("cegqi-nsi") << "NSI : check refinement : " << finst << std::endl;
Node finst_lem = NodeManager::currentNM()->mkNode( OR, d_full_guard.negate(), finst );
Trace("cegqi-lemma") << "Cegqi::Lemma : verification, refinement lemma : " << inst << std::endl;
d_qe->addLemma( finst_lem );
*/
return true;
}else{
//currently trying to construct candidate by refutation (by d_cinst->check below)
}
}else{
//should be assigned a SAT value
Assert( false );
}
}else if( !isFullySingleInvocation() ){
//create next candidate conjecture
Assert( d_ei!=NULL );
//construct d_single_inv
d_single_inv = Node::null();
initializeNextSiConjecture();
return true;
}
d_curr_lemmas.clear();
//call check for instantiator
d_cinst->check();
//add lemmas
//add guard if not fully single invocation
if( !isFullySingleInvocation() ){
Assert( !d_ns_guard.isNull() );
for( unsigned i=0; i<d_curr_lemmas.size(); i++ ){
lems.push_back( NodeManager::currentNM()->mkNode( OR, d_ns_guard.negate(), d_curr_lemmas[i] ) );
}
}else{
lems.insert( lems.end(), d_curr_lemmas.begin(), d_curr_lemmas.end() );
}
return !lems.empty();
}else{
return false;
}
}
Node CegConjectureSingleInv::constructSolution( std::vector< unsigned >& indices, unsigned i, unsigned index, std::map< Node, Node >& weak_imp ) {
Assert( index<d_inst.size() );
Assert( i<d_inst[index].size() );
unsigned uindex = indices[index];
if( index==indices.size()-1 ){
return d_inst[uindex][i];
}else{
Node cond = d_lemmas_produced[uindex];
//weaken based on unsat core
std::map< Node, Node >::iterator itw = weak_imp.find( cond );
if( itw!=weak_imp.end() ){
cond = itw->second;
}
cond = TermDb::simpleNegate( cond );
Node ite1 = d_inst[uindex][i];
Node ite2 = constructSolution( indices, i, index+1, weak_imp );
return NodeManager::currentNM()->mkNode( ITE, cond, ite1, ite2 );
}
}
//TODO: use term size?
struct sortSiInstanceIndices {
CegConjectureSingleInv* d_ccsi;
int d_i;
bool operator() (unsigned i, unsigned j) {
if( d_ccsi->d_inst[i][d_i].isConst() && !d_ccsi->d_inst[j][d_i].isConst() ){
return true;
}else{
return false;
}
}
};
Node CegConjectureSingleInv::postProcessSolution( Node n ){
/*
////remove boolean ITE (not allowed for sygus comp 2015)
if( n.getKind()==ITE && n.getType().isBoolean() ){
Node n1 = postProcessSolution( n[1] );
Node n2 = postProcessSolution( n[2] );
return NodeManager::currentNM()->mkNode( OR, NodeManager::currentNM()->mkNode( AND, n[0], n1 ),
NodeManager::currentNM()->mkNode( AND, n[0].negate(), n2 ) );
}else{
*/
bool childChanged = false;
Kind k = n.getKind();
if( n.getKind()==INTS_DIVISION_TOTAL ){
k = INTS_DIVISION;
childChanged = true;
}else if( n.getKind()==INTS_MODULUS_TOTAL ){
k = INTS_MODULUS;
childChanged = true;
}
std::vector< Node > children;
for( unsigned i=0; i<n.getNumChildren(); i++ ){
Node nn = postProcessSolution( n[i] );
children.push_back( nn );
childChanged = childChanged || nn!=n[i];
}
if( childChanged ){
if( n.hasOperator() && k==n.getKind() ){
children.insert( children.begin(), n.getOperator() );
}
return NodeManager::currentNM()->mkNode( k, children );
}else{
return n;
}
}
Node CegConjectureSingleInv::getSolution( unsigned sol_index, TypeNode stn, int& reconstructed, bool rconsSygus ){
Assert( d_sol!=NULL );
Assert( !d_lemmas_produced.empty() );
const Datatype& dt = ((DatatypeType)(stn).toType()).getDatatype();
Node varList = Node::fromExpr( dt.getSygusVarList() );
Node prog = d_quant[0][sol_index];
std::vector< Node > vars;
Node s;
if( d_prog_to_sol_index.find( prog )==d_prog_to_sol_index.end() ){
s = d_qe->getTermDatabase()->getEnumerateTerm( TypeNode::fromType( dt.getSygusType() ), 0 );
}else{
Trace("csi-sol") << "Get solution for " << prog << ", with skolems : ";
sol_index = d_prog_to_sol_index[prog];
d_sol->d_varList.clear();
Assert( d_single_inv_arg_sk.size()==varList.getNumChildren() );
for( unsigned i=0; i<d_single_inv_arg_sk.size(); i++ ){
Trace("csi-sol") << d_single_inv_arg_sk[i] << " ";
//if( varList[i].getType().isBoolean() ){
// //TODO force boolean term conversion mode
// Node c = NodeManager::currentNM()->mkConst(BitVector(1u, 1u));
// vars.push_back( d_single_inv_arg_sk[i].eqNode( c ) );
//}else{
vars.push_back( d_single_inv_arg_sk[i] );
//}
d_sol->d_varList.push_back( varList[i] );
}
Trace("csi-sol") << std::endl;
//construct the solution
Trace("csi-sol") << "Sort solution return values " << sol_index << std::endl;
bool useUnsatCore = false;
std::vector< Node > active_lemmas;
//minimize based on unsat core, if possible
std::map< Node, Node > weak_imp;
if( options::cegqiSolMinCore() ){
if( options::cegqiSolMinInst() ){
if( d_qe->getUnsatCoreLemmas( active_lemmas, weak_imp ) ){
useUnsatCore = true;
}
}else{
if( d_qe->getUnsatCoreLemmas( active_lemmas ) ){
useUnsatCore = true;
}
}
}
Assert( d_lemmas_produced.size()==d_inst.size() );
std::vector< unsigned > indices;
for( unsigned i=0; i<d_lemmas_produced.size(); i++ ){
bool incl = true;
if( useUnsatCore ){
incl = std::find( active_lemmas.begin(), active_lemmas.end(), d_lemmas_produced[i] )!=active_lemmas.end();
}
if( incl ){
Assert( sol_index<d_inst[i].size() );
indices.push_back( i );
}
}
Trace("csi-sol") << "...included " << indices.size() << " / " << d_lemmas_produced.size() << " instantiations." << std::endl;
Assert( !indices.empty() );
//sort indices based on heuristic : currently, do all constant returns first (leads to simpler conditions)
// TODO : to minimize solution size, put the largest term last
sortSiInstanceIndices ssii;
ssii.d_ccsi = this;
ssii.d_i = sol_index;
std::sort( indices.begin(), indices.end(), ssii );
Trace("csi-sol") << "Construct solution" << std::endl;
s = constructSolution( indices, sol_index, 0, weak_imp );
Assert( vars.size()==d_sol->d_varList.size() );
s = s.substitute( vars.begin(), vars.end(), d_sol->d_varList.begin(), d_sol->d_varList.end() );
}
d_orig_solution = s;
//simplify the solution
Trace("csi-sol") << "Solution (pre-simplification): " << d_orig_solution << std::endl;
s = d_sol->simplifySolution( s, stn );
Trace("csi-sol") << "Solution (post-simplification): " << s << std::endl;
return reconstructToSyntax( s, stn, reconstructed, rconsSygus );
}
Node CegConjectureSingleInv::reconstructToSyntax( Node s, TypeNode stn, int& reconstructed, bool rconsSygus ) {
d_solution = s;
const Datatype& dt = ((DatatypeType)(stn).toType()).getDatatype();
//reconstruct the solution into sygus if necessary
reconstructed = 0;
if( options::cegqiSingleInvReconstruct() && !dt.getSygusAllowAll() && !stn.isNull() && rconsSygus ){
d_sol->preregisterConjecture( d_orig_conjecture );
d_sygus_solution = d_sol->reconstructSolution( s, stn, reconstructed );
if( reconstructed==1 ){
Trace("csi-sol") << "Solution (post-reconstruction into Sygus): " << d_sygus_solution << std::endl;
}
}else{
Trace("csi-sol") << "Post-process solution..." << std::endl;
Node prev = d_solution;
d_solution = postProcessSolution( d_solution );
if( prev!=d_solution ){
Trace("csi-sol") << "Solution (after post process) : " << d_solution << std::endl;
}
}
if( Trace.isOn("csi-sol") ){
//debug solution
if( !d_sol->debugSolution( d_solution ) ){
Trace("csi-sol") << "WARNING : solution " << d_solution << " contains free constants." << std::endl;
//exit( 47 );
}else{
//exit( 49 );
}
}
if( Trace.isOn("cegqi-stats") ){
int tsize, itesize;
tsize = 0;itesize = 0;
d_sol->debugTermSize( d_orig_solution, tsize, itesize );
Trace("cegqi-stats") << tsize << " " << itesize << " ";
tsize = 0;itesize = 0;
d_sol->debugTermSize( d_solution, tsize, itesize );
Trace("cegqi-stats") << tsize << " " << itesize << " ";
if( !d_sygus_solution.isNull() ){
tsize = 0;itesize = 0;
d_sol->debugTermSize( d_sygus_solution, tsize, itesize );
Trace("cegqi-stats") << tsize << " - ";
}else{
Trace("cegqi-stats") << "null ";
}
Trace("cegqi-stats") << std::endl;
}
Node sol;
if( reconstructed==1 ){
sol = d_sygus_solution;
}else{
sol = d_solution;
}
//make into lambda
if( !dt.getSygusVarList().isNull() ){
Node varList = Node::fromExpr( dt.getSygusVarList() );
return NodeManager::currentNM()->mkNode( LAMBDA, varList, sol );
}else{
return sol;
}
}
bool CegConjectureSingleInv::needsCheck() {
if( options::cegqiSingleInvMode()==CEGQI_SI_MODE_ALL_ABORT ){
if( !d_has_ites ){
return d_inst.empty();
}
}
return true;
}
void CegConjectureSingleInv::preregisterConjecture( Node q ) {
d_orig_conjecture = q;
}
bool SingleInvocationPartition::init( Node n ) {
//first, get types of arguments for functions
std::vector< TypeNode > typs;
std::map< Node, bool > visited;
if( inferArgTypes( n, typs, visited ) ){
return init( typs, n );
}else{
Trace("si-prt") << "Could not infer argument types." << std::endl;
return false;
}
}
bool SingleInvocationPartition::inferArgTypes( Node n, std::vector< TypeNode >& typs, std::map< Node, bool >& visited ) {
if( visited.find( n )==visited.end() ){
visited[n] = true;
if( n.getKind()!=FORALL ){
//if( TermDb::hasBoundVarAttr( n ) ){
if( n.getKind()==d_checkKind ){
for( unsigned i=0; i<n.getNumChildren(); i++ ){
typs.push_back( n[i].getType() );
}
return true;
}else{
for( unsigned i=0; i<n.getNumChildren(); i++ ){
if( inferArgTypes( n[i], typs, visited ) ){
return true;
}
}
}
//}
}
}
return false;
}
bool SingleInvocationPartition::init( std::vector< TypeNode >& typs, Node n ){
Assert( d_arg_types.empty() );
Assert( d_si_vars.empty() );
d_arg_types.insert( d_arg_types.end(), typs.begin(), typs.end() );
for( unsigned j=0; j<d_arg_types.size(); j++ ){
std::stringstream ss;
ss << "s_" << j;
Node si_v = NodeManager::currentNM()->mkBoundVar( ss.str(), d_arg_types[j] );
d_si_vars.push_back( si_v );
}
Trace("si-prt") << "Process the formula..." << std::endl;
process( n );
return true;
}
void SingleInvocationPartition::process( Node n ) {
Assert( d_si_vars.size()==d_arg_types.size() );
Trace("si-prt") << "SingleInvocationPartition::process " << n << std::endl;
Trace("si-prt") << "Get conjuncts..." << std::endl;
std::vector< Node > conj;
if( collectConjuncts( n, true, conj ) ){
Trace("si-prt") << "...success." << std::endl;
for( unsigned i=0; i<conj.size(); i++ ){
std::vector< Node > si_terms;
std::vector< Node > si_subs;
Trace("si-prt") << "Process conjunct : " << conj[i] << std::endl;
//do DER on conjunct
Node cr = TermDb::getQuantSimplify( conj[i] );
if( cr!=conj[i] ){
Trace("si-prt-debug") << "...rewritten to " << cr << std::endl;
}
std::map< Node, bool > visited;
// functions to arguments
std::vector< Node > args;
std::vector< Node > terms;
std::vector< Node > subs;
bool singleInvocation = true;
bool ngroundSingleInvocation = false;
if( processConjunct( cr, visited, args, terms, subs ) ){
for( unsigned j=0; j<terms.size(); j++ ){
si_terms.push_back( subs[j] );
si_subs.push_back( d_func_fo_var[subs[j].getOperator()] );
}
std::map< Node, Node > subs_map;
std::map< Node, Node > subs_map_rev;
std::vector< Node > funcs;
//normalize the invocations
if( !terms.empty() ){
Assert( terms.size()==subs.size() );
cr = cr.substitute( terms.begin(), terms.end(), subs.begin(), subs.end() );
}
std::vector< Node > children;
children.push_back( cr );
terms.clear();
subs.clear();
Trace("si-prt") << "...single invocation, with arguments: " << std::endl;
for( unsigned j=0; j<args.size(); j++ ){
Trace("si-prt") << args[j] << " ";
if( args[j].getKind()==BOUND_VARIABLE && std::find( terms.begin(), terms.end(), args[j] )==terms.end() ){
terms.push_back( args[j] );
subs.push_back( d_si_vars[j] );
}else{
children.push_back( d_si_vars[j].eqNode( args[j] ).negate() );
}
}
Trace("si-prt") << std::endl;
cr = children.size()==1 ? children[0] : NodeManager::currentNM()->mkNode( OR, children );
Assert( terms.size()==subs.size() );
cr = cr.substitute( terms.begin(), terms.end(), subs.begin(), subs.end() );
Trace("si-prt-debug") << "...normalized invocations to " << cr << std::endl;
//now must check if it has other bound variables
std::vector< Node > bvs;
TermDb::getBoundVars( cr, bvs );
if( bvs.size()>d_si_vars.size() ){
Trace("si-prt") << "...not ground single invocation." << std::endl;
ngroundSingleInvocation = true;
singleInvocation = false;
}else{
Trace("si-prt") << "...ground single invocation : success." << std::endl;
}
}else{
Trace("si-prt") << "...not single invocation." << std::endl;
singleInvocation = false;
//rename bound variables with maximal overlap with si_vars
std::vector< Node > bvs;
TermDb::getBoundVars( cr, bvs );
std::vector< Node > terms;
std::vector< Node > subs;
for( unsigned j=0; j<bvs.size(); j++ ){
TypeNode tn = bvs[j].getType();
Trace("si-prt-debug") << "Fit bound var #" << j << " : " << bvs[j] << " with si." << std::endl;
for( unsigned k=0; k<d_si_vars.size(); k++ ){
if( tn==d_arg_types[k] ){
if( std::find( subs.begin(), subs.end(), d_si_vars[k] )==subs.end() ){
terms.push_back( bvs[j] );
subs.push_back( d_si_vars[k] );
Trace("si-prt-debug") << " ...use " << d_si_vars[k] << std::endl;
break;
}
}
}
}
Assert( terms.size()==subs.size() );
cr = cr.substitute( terms.begin(), terms.end(), subs.begin(), subs.end() );
}
cr = Rewriter::rewrite( cr );
Trace("si-prt") << ".....got si=" << singleInvocation << ", result : " << cr << std::endl;
d_conjuncts[2].push_back( cr );
TermDb::getBoundVars( cr, d_all_vars );
if( singleInvocation ){
//replace with single invocation formulation
Assert( si_terms.size()==si_subs.size() );
cr = cr.substitute( si_terms.begin(), si_terms.end(), si_subs.begin(), si_subs.end() );
cr = Rewriter::rewrite( cr );
Trace("si-prt") << ".....si version=" << cr << std::endl;
d_conjuncts[0].push_back( cr );
}else{
d_conjuncts[1].push_back( cr );
if( ngroundSingleInvocation ){
d_conjuncts[3].push_back( cr );
}
}
}
}else{
Trace("si-prt") << "...failed." << std::endl;
}
}
bool SingleInvocationPartition::collectConjuncts( Node n, bool pol, std::vector< Node >& conj ) {
if( ( !pol && n.getKind()==OR ) || ( pol && n.getKind()==AND ) ){
for( unsigned i=0; i<n.getNumChildren(); i++ ){
if( !collectConjuncts( n[i], pol, conj ) ){
return false;
}
}
}else if( n.getKind()==NOT ){
return collectConjuncts( n[0], !pol, conj );
}else if( n.getKind()==FORALL ){
return false;
}else{
if( !pol ){
n = TermDb::simpleNegate( n );
}
Trace("si-prt") << "Conjunct : " << n << std::endl;
conj.push_back( n );
}
return true;
}
bool SingleInvocationPartition::processConjunct( Node n, std::map< Node, bool >& visited, std::vector< Node >& args,
std::vector< Node >& terms, std::vector< Node >& subs ) {
std::map< Node, bool >::iterator it = visited.find( n );
if( it!=visited.end() ){
return true;
}else{
bool ret = true;
//if( TermDb::hasBoundVarAttr( n ) ){
for( unsigned i=0; i<n.getNumChildren(); i++ ){
if( !processConjunct( n[i], visited, args, terms, subs ) ){
ret = false;
}
}
if( ret ){
if( n.getKind()==d_checkKind ){
if( std::find( terms.begin(), terms.end(), n )==terms.end() ){
Node f = n.getOperator();
//check if it matches the type requirement
if( isAntiSkolemizableType( f ) ){
if( args.empty() ){
//record arguments
for( unsigned i=0; i<n.getNumChildren(); i++ ){
args.push_back( n[i] );
}
}else{
//arguments must be the same as those already recorded
for( unsigned i=0; i<n.getNumChildren(); i++ ){
if( args[i]!=n[i] ){
Trace("si-prt-debug") << "...bad invocation : " << n << " at arg " << i << "." << std::endl;
ret = false;
break;
}
}
}
if( ret ){
terms.push_back( n );
subs.push_back( d_func_inv[f] );
}
}else{
Trace("si-prt-debug") << "... " << f << " is a bad operator." << std::endl;
ret = false;
}
}
}
}
//}
visited[n] = ret;
return ret;
}
}
bool SingleInvocationPartition::isAntiSkolemizableType( Node f ) {
std::map< Node, bool >::iterator it = d_funcs.find( f );
if( it!=d_funcs.end() ){
return it->second;
}else{
TypeNode tn = f.getType();
bool ret = false;
if( tn.getNumChildren()==d_arg_types.size()+1 ){
ret = true;
std::vector< Node > children;
children.push_back( f );
//TODO: permutations of arguments
for( unsigned i=0; i<d_arg_types.size(); i++ ){
children.push_back( d_si_vars[i] );
if( tn[i]!=d_arg_types[i] ){
ret = false;
break;
}
}
if( ret ){
Node t = NodeManager::currentNM()->mkNode( d_checkKind, children );
d_func_inv[f] = t;
d_inv_to_func[t] = f;
std::stringstream ss;
ss << "F_" << f;
Node v = NodeManager::currentNM()->mkBoundVar( ss.str(), tn.getRangeType() );
d_func_fo_var[f] = v;
d_fo_var_to_func[v] = f;
d_func_vars.push_back( v );
}
}
d_funcs[f] = ret;
return ret;
}
}
Node SingleInvocationPartition::getConjunct( int index ) {
return d_conjuncts[index].empty() ? NodeManager::currentNM()->mkConst( true ) :
( d_conjuncts[index].size()==1 ? d_conjuncts[index][0] : NodeManager::currentNM()->mkNode( AND, d_conjuncts[index] ) );
}
Node SingleInvocationPartition::getSpecificationInst( Node n, std::map< Node, Node >& lam, std::map< Node, Node >& visited ) {
std::map< Node, Node >::iterator it = visited.find( n );
if( it!=visited.end() ){
return it->second;
}else{
bool childChanged = false;
std::vector< Node > children;
for( unsigned i=0; i<n.getNumChildren(); i++ ){
Node nn = getSpecificationInst( n[i], lam, visited );
children.push_back( nn );
childChanged = childChanged || ( nn!=n[i] );
}
Node ret;
if( n.getKind()==d_checkKind ){
std::map< Node, Node >::iterator itl = lam.find( n.getOperator() );
if( itl!=lam.end() ){
Assert( itl->second[0].getNumChildren()==children.size() );
std::vector< Node > terms;
std::vector< Node > subs;
for( unsigned i=0; i<itl->second[0].getNumChildren(); i++ ){
terms.push_back( itl->second[0][i] );
subs.push_back( children[i] );
}
ret = itl->second[1].substitute( terms.begin(), terms.end(), subs.begin(), subs.end() );
ret = Rewriter::rewrite( ret );
}
}
if( ret.isNull() ){
ret = n;
if( childChanged ){
if( n.getMetaKind() == kind::metakind::PARAMETERIZED ){
children.insert( children.begin(), n.getOperator() );
}
ret = NodeManager::currentNM()->mkNode( n.getKind(), children );
}
}
return ret;
}
}
Node SingleInvocationPartition::getSpecificationInst( int index, std::map< Node, Node >& lam ) {
Node conj = getConjunct( index );
std::map< Node, Node > visited;
return getSpecificationInst( conj, lam, visited );
}
void SingleInvocationPartition::extractInvariant( Node n, Node& func, int& pol, std::vector< Node >& disjuncts ) {
std::map< Node, bool > visited;
extractInvariant2( n, func, pol, disjuncts, true, visited );
}
void SingleInvocationPartition::extractInvariant2( Node n, Node& func, int& pol, std::vector< Node >& disjuncts, bool hasPol, std::map< Node, bool >& visited ) {
if( visited.find( n )==visited.end() && pol!=-2 ){
Trace("cegqi-inv-debug2") << "Extract : " << n << " " << hasPol << ", pol = " << pol << std::endl;
visited[n] = true;
if( n.getKind()==OR && hasPol ){
for( unsigned i=0; i<n.getNumChildren(); i++ ){
extractInvariant2( n[i], func, pol, disjuncts, true, visited );
}
}else{
if( hasPol ){
bool lit_pol = n.getKind()!=NOT;
Node lit = n.getKind()==NOT ? n[0] : n;
std::map< Node, Node >::iterator it = d_inv_to_func.find( lit );
if( it!=d_inv_to_func.end() ){
if( pol==-1 ){
pol = lit_pol ? 0 : 1;
func = it->second;
}else{
//mixing multiple invariants
pol = -2;
}
return;
}else{
disjuncts.push_back( n );
}
}
//if another part mentions UF or a free variable, then fail
if( n.getKind()==APPLY_UF ){
Node op = n.getOperator();
if( d_funcs.find( op )!=d_funcs.end() ){
pol = -2;
return;
}
}else if( n.getKind()==BOUND_VARIABLE && std::find( d_si_vars.begin(), d_si_vars.end(), n )==d_si_vars.end() ){
pol = -2;
return;
}
for( unsigned i=0; i<n.getNumChildren(); i++ ){
extractInvariant2( n[i], func, pol, disjuncts, false, visited );
}
}
}
}
void SingleInvocationPartition::debugPrint( const char * c ) {
Trace(c) << "Single invocation variables : ";
for( unsigned i=0; i<d_si_vars.size(); i++ ){
Trace(c) << d_si_vars[i] << " ";
}
Trace(c) << std::endl;
Trace(c) << "Functions : " << std::endl;
for( std::map< Node, bool >::iterator it = d_funcs.begin(); it != d_funcs.end(); ++it ){
Trace(c) << " " << it->first << " : ";
if( it->second ){
Trace(c) << d_func_inv[it->first] << " " << d_func_fo_var[it->first] << std::endl;
}else{
Trace(c) << "not incorporated." << std::endl;
}
}
for( unsigned i=0; i<4; i++ ){
Trace(c) << ( i==0 ? "Single invocation" : ( i==1 ? "Non-single invocation" : ( i==2 ? "All" : "Non-ground single invocation" ) ) );
Trace(c) << " conjuncts: " << std::endl;
for( unsigned j=0; j<d_conjuncts[i].size(); j++ ){
Trace(c) << " " << (j+1) << " : " << d_conjuncts[i][j] << std::endl;
}
}
Trace(c) << std::endl;
}
}
| 40.50347 | 169 | 0.586907 | [
"vector"
] |
92d86a9291ae295e5057e85b114783935319fa07 | 1,355 | hpp | C++ | model copy/boost/statistics/model/wrap/include.hpp | rogard/boost_sandbox_statistics | 16aacbc716a31a9f7bb6c535b1c90dc343282a23 | [
"BSL-1.0"
] | null | null | null | model copy/boost/statistics/model/wrap/include.hpp | rogard/boost_sandbox_statistics | 16aacbc716a31a9f7bb6c535b1c90dc343282a23 | [
"BSL-1.0"
] | null | null | null | model copy/boost/statistics/model/wrap/include.hpp | rogard/boost_sandbox_statistics | 16aacbc716a31a9f7bb6c535b1c90dc343282a23 | [
"BSL-1.0"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// statistics::model::wrap::include.hpp //
// //
// Copyright 2009 Erwann Rogard. 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) //
///////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_STATISTICS_MODEL_WRAP_INCLUDE_HPP_ER_2009
#define BOOST_STATISTICS_MODEL_WRAP_INCLUDE_HPP_ER_2009
#include <boost/statistics/model/wrap/unary/covariate.hpp>
#include <boost/statistics/model/wrap/unary/model.hpp>
#include <boost/statistics/model/wrap/unary/prior.hpp>
#include <boost/statistics/model/wrap/unary/response.hpp>
#include <boost/statistics/model/wrap/unary/covariates.hpp>
#include <boost/statistics/model/wrap/unary/responses.hpp>
#include <boost/statistics/model/wrap/aggregate/data.hpp>
#include <boost/statistics/model/wrap/aggregate/dataset.hpp>
#include <boost/statistics/model/wrap/aggregate/model_parameter.hpp>
#include <boost/statistics/model/wrap/aggregate/model_dataset.hpp>
#include <boost/statistics/model/wrap/aggregate/prior_model_dataset.hpp>
#endif | 56.458333 | 79 | 0.616974 | [
"model"
] |
2bae8f432744a58117cd251d479c43d25ba5f3a7 | 19,846 | cc | C++ | chrome/browser/browser_accessibility.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | 11 | 2015-03-20T04:08:08.000Z | 2021-11-15T15:51:36.000Z | chrome/browser/browser_accessibility.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/browser_accessibility.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/browser_accessibility.h"
#include "base/logging.h"
#include "chrome/browser/browser_accessibility_manager.h"
using webkit_glue::WebAccessibility;
HRESULT BrowserAccessibility::Initialize(int iaccessible_id, int routing_id,
int process_id, HWND parent_hwnd) {
// Check input parameters. Root id is 1000, to avoid conflicts with the ids
// used by MSAA.
if (!parent_hwnd || iaccessible_id < 1000)
return E_INVALIDARG;
iaccessible_id_ = iaccessible_id;
routing_id_ = routing_id;
process_id_ = process_id;
parent_hwnd_ = parent_hwnd;
// Mark instance as active.
instance_active_ = true;
return S_OK;
}
HRESULT BrowserAccessibility::accDoDefaultAction(VARIANT var_id) {
if (!instance_active()) {
// Instance no longer active, fail gracefully.
// TODO(klink): Once we have MSAA events, change these fails to having
// BrowserAccessibilityManager firing the right event.
return E_FAIL;
}
if (var_id.vt != VT_I4)
return E_INVALIDARG;
if (!RequestAccessibilityInfo(WebAccessibility::FUNCTION_DODEFAULTACTION,
var_id, NULL, NULL)) {
return E_FAIL;
}
if (!response().return_code)
return S_FALSE;
return S_OK;
}
STDMETHODIMP BrowserAccessibility::accHitTest(LONG x_left, LONG y_top,
VARIANT* child) {
if (!instance_active()) {
// Instance no longer active, fail gracefully.
return E_FAIL;
}
if (!child)
return E_INVALIDARG;
if (!parent_hwnd_) {
// Parent HWND needed for coordinate conversion.
return E_FAIL;
}
// Convert coordinates to test from screen into client window coordinates, to
// maintain sandbox functionality on renderer side.
POINT p = {x_left, y_top};
::ScreenToClient(parent_hwnd_, &p);
if (!RequestAccessibilityInfo(WebAccessibility::FUNCTION_HITTEST,
EmptyVariant(), p.x, p.y)) {
return E_FAIL;
}
if (!response().return_code) {
// The point is outside of the object's boundaries.
child->vt = VT_EMPTY;
return S_FALSE;
}
if (response().output_long1 == -1) {
if (CreateInstance(IID_IAccessible, response().object_id,
reinterpret_cast<void**>(&child->pdispVal)) == S_OK) {
child->vt = VT_DISPATCH;
// Increment the reference count for the retrieved interface.
child->pdispVal->AddRef();
} else {
return E_NOINTERFACE;
}
} else {
child->vt = VT_I4;
child->lVal = response().output_long1;
}
return S_OK;
}
STDMETHODIMP BrowserAccessibility::accLocation(LONG* x_left, LONG* y_top,
LONG* width, LONG* height,
VARIANT var_id) {
if (!instance_active()) {
// Instance no longer active, fail gracefully.
return E_FAIL;
}
if (var_id.vt != VT_I4 || !x_left || !y_top || !width || !height ||
!parent_hwnd_) {
return E_INVALIDARG;
}
if (!RequestAccessibilityInfo(WebAccessibility::FUNCTION_LOCATION, var_id,
NULL, NULL)) {
return E_FAIL;
}
POINT top_left = {0, 0};
// Find the top left corner of the containing window in screen coords, and
// adjust the output position by this amount.
::ClientToScreen(parent_hwnd_, &top_left);
*x_left = response().output_long1 + top_left.x;
*y_top = response().output_long2 + top_left.y;
*width = response().output_long3;
*height = response().output_long4;
return S_OK;
}
STDMETHODIMP BrowserAccessibility::accNavigate(LONG nav_dir, VARIANT start,
VARIANT* end) {
if (!instance_active()) {
// Instance no longer active, fail gracefully.
return E_FAIL;
}
if (start.vt != VT_I4 || !end)
return E_INVALIDARG;
if ((nav_dir == NAVDIR_LASTCHILD || nav_dir == NAVDIR_FIRSTCHILD) &&
start.lVal != CHILDID_SELF) {
// MSAA states that navigating to first/last child can only be from self.
return E_INVALIDARG;
}
if (nav_dir == NAVDIR_DOWN || nav_dir == NAVDIR_UP ||
nav_dir == NAVDIR_LEFT || nav_dir == NAVDIR_RIGHT) {
// Directions not implemented, matching Mozilla and IE.
return E_INVALIDARG;
}
if (!RequestAccessibilityInfo(WebAccessibility::FUNCTION_NAVIGATE, start,
nav_dir, NULL)) {
return E_FAIL;
}
if (!response().return_code) {
// No screen element was found in the specified direction.
end->vt = VT_EMPTY;
return S_FALSE;
}
if (response().output_long1 == -1) {
if (CreateInstance(IID_IAccessible, response().object_id,
reinterpret_cast<void**>(&end->pdispVal)) == S_OK) {
end->vt = VT_DISPATCH;
// Increment the reference count for the retrieved interface.
end->pdispVal->AddRef();
} else {
return E_NOINTERFACE;
}
} else {
end->vt = VT_I4;
end->lVal = response().output_long1;
}
return S_OK;
}
STDMETHODIMP BrowserAccessibility::get_accChild(VARIANT var_child,
IDispatch** disp_child) {
if (!instance_active()) {
// Instance no longer active, fail gracefully.
return E_FAIL;
}
if (var_child.vt != VT_I4 || !disp_child)
return E_INVALIDARG;
// If var_child is the parent, remain with the same IDispatch.
if (var_child.lVal == CHILDID_SELF && iaccessible_id_ != 1000)
return S_OK;
if (!RequestAccessibilityInfo(WebAccessibility::FUNCTION_GETCHILD, var_child,
NULL, NULL)) {
return E_FAIL;
}
if (!response().return_code) {
// When at a leaf, children are handled by the parent object.
*disp_child = NULL;
return S_FALSE;
}
// Retrieve the IUnknown interface for the parent view, and assign the
// IDispatch returned.
if (CreateInstance(IID_IAccessible, response().object_id,
reinterpret_cast<void**>(disp_child)) == S_OK) {
// Increment the reference count for the retrieved interface.
(*disp_child)->AddRef();
return S_OK;
} else {
return E_NOINTERFACE;
}
}
STDMETHODIMP BrowserAccessibility::get_accChildCount(LONG* child_count) {
if (!instance_active()) {
// Instance no longer active, fail gracefully.
return E_FAIL;
}
if (!child_count)
return E_INVALIDARG;
if (!RequestAccessibilityInfo(WebAccessibility::FUNCTION_CHILDCOUNT,
EmptyVariant(), NULL, NULL)) {
return E_FAIL;
}
*child_count = response().output_long1;
return S_OK;
}
STDMETHODIMP BrowserAccessibility::get_accDefaultAction(VARIANT var_id,
BSTR* def_action) {
if (!instance_active()) {
// Instance no longer active, fail gracefully.
return E_FAIL;
}
if (var_id.vt != VT_I4 || !def_action)
return E_INVALIDARG;
if (!RequestAccessibilityInfo(WebAccessibility::FUNCTION_DEFAULTACTION,
var_id, NULL, NULL)) {
return E_FAIL;
}
if (!response().return_code) {
// No string found.
return S_FALSE;
}
*def_action = SysAllocString(response().output_string.c_str());
DCHECK(*def_action);
return S_OK;
}
STDMETHODIMP BrowserAccessibility::get_accDescription(VARIANT var_id,
BSTR* desc) {
if (!instance_active()) {
// Instance no longer active, fail gracefully.
return E_FAIL;
}
if (var_id.vt != VT_I4 || !desc)
return E_INVALIDARG;
if (!RequestAccessibilityInfo(WebAccessibility::FUNCTION_DESCRIPTION, var_id,
NULL, NULL)) {
return E_FAIL;
}
if (!response().return_code) {
// No string found.
return S_FALSE;
}
*desc = SysAllocString(response().output_string.c_str());
DCHECK(*desc);
return S_OK;
}
STDMETHODIMP BrowserAccessibility::get_accFocus(VARIANT* focus_child) {
if (!instance_active()) {
// Instance no longer active, fail gracefully.
return E_FAIL;
}
if (!focus_child)
return E_INVALIDARG;
if (!RequestAccessibilityInfo(WebAccessibility::FUNCTION_GETFOCUSEDCHILD,
EmptyVariant(), NULL, NULL)) {
return E_FAIL;
}
if (!response().return_code) {
// The window that contains this object is not the active window.
focus_child->vt = VT_EMPTY;
return S_FALSE;
}
if (response().output_long1 == -1) {
if (CreateInstance(IID_IAccessible, response().object_id,
reinterpret_cast<void**>(&focus_child->pdispVal)) == S_OK) {
focus_child->vt = VT_DISPATCH;
// Increment the reference count for the retrieved interface.
focus_child->pdispVal->AddRef();
} else {
return E_NOINTERFACE;
}
} else {
focus_child->vt = VT_I4;
focus_child->lVal = response().output_long1;
}
return S_OK;
}
STDMETHODIMP BrowserAccessibility::get_accHelp(VARIANT var_id, BSTR* help) {
if (!instance_active()) {
// Instance no longer active, fail gracefully.
return E_FAIL;
}
if (var_id.vt != VT_I4 || !help)
return E_INVALIDARG;
if (!RequestAccessibilityInfo(WebAccessibility::FUNCTION_HELPTEXT, var_id,
NULL, NULL)) {
return E_FAIL;
}
if (!response().return_code || response().output_string.empty()) {
// No string found.
return S_FALSE;
}
*help = SysAllocString(response().output_string.c_str());
DCHECK(*help);
return S_OK;
}
STDMETHODIMP BrowserAccessibility::get_accKeyboardShortcut(VARIANT var_id,
BSTR* acc_key) {
if (!instance_active()) {
// Instance no longer active, fail gracefully.
return E_FAIL;
}
if (var_id.vt != VT_I4 || !acc_key)
return E_INVALIDARG;
if (!RequestAccessibilityInfo(WebAccessibility::FUNCTION_KEYBOARDSHORTCUT,
var_id, NULL, NULL)) {
return E_FAIL;
}
if (!response().return_code) {
// No string found.
return S_FALSE;
}
*acc_key = SysAllocString(response().output_string.c_str());
DCHECK(*acc_key);
return S_OK;
}
STDMETHODIMP BrowserAccessibility::get_accName(VARIANT var_id, BSTR* name) {
if (!instance_active()) {
// Instance no longer active, fail gracefully.
return E_FAIL;
}
if (var_id.vt != VT_I4 || !name)
return E_INVALIDARG;
if (!RequestAccessibilityInfo(WebAccessibility::FUNCTION_NAME, var_id, NULL,
NULL)) {
return E_FAIL;
}
if (!response().return_code) {
// No string found.
return S_FALSE;
}
*name = SysAllocString(response().output_string.c_str());
DCHECK(*name);
return S_OK;
}
STDMETHODIMP BrowserAccessibility::get_accParent(IDispatch** disp_parent) {
if (!instance_active()) {
// Instance no longer active, fail gracefully.
return E_FAIL;
}
if (!disp_parent || !parent_hwnd_)
return E_INVALIDARG;
// Root node's parent is the containing HWND's IAccessible.
if (iaccessible_id_ == 1000) {
// For an object that has no parent (e.g. root), point the accessible parent
// to the default implementation.
HRESULT hr =
::CreateStdAccessibleObject(parent_hwnd_, OBJID_WINDOW,
IID_IAccessible,
reinterpret_cast<void**>(disp_parent));
if (!SUCCEEDED(hr)) {
*disp_parent = NULL;
return S_FALSE;
}
return S_OK;
}
if (!RequestAccessibilityInfo(WebAccessibility::FUNCTION_GETPARENT,
EmptyVariant(), NULL, NULL)) {
return E_FAIL;
}
if (!response().return_code) {
// No parent exists for this object.
return S_FALSE;
}
// Retrieve the IUnknown interface for the parent view, and assign the
// IDispatch returned.
if (CreateInstance(IID_IAccessible, response().object_id,
reinterpret_cast<void**>(disp_parent)) == S_OK) {
// Increment the reference count for the retrieved interface.
(*disp_parent)->AddRef();
return S_OK;
} else {
return E_NOINTERFACE;
}
}
STDMETHODIMP BrowserAccessibility::get_accRole(VARIANT var_id, VARIANT* role) {
if (!instance_active()) {
// Instance no longer active, fail gracefully.
return E_FAIL;
}
if (var_id.vt != VT_I4 || !role)
return E_INVALIDARG;
if (!RequestAccessibilityInfo(WebAccessibility::FUNCTION_ROLE, var_id, NULL,
NULL)) {
return E_FAIL;
}
role->vt = VT_I4;
role->lVal = MSAARole(response().output_long1);
return S_OK;
}
STDMETHODIMP BrowserAccessibility::get_accState(VARIANT var_id,
VARIANT* state) {
if (!instance_active()) {
// Instance no longer active, fail gracefully.
return E_FAIL;
}
if (var_id.vt != VT_I4 || !state)
return E_INVALIDARG;
if (!RequestAccessibilityInfo(WebAccessibility::FUNCTION_STATE, var_id, NULL,
NULL)) {
return E_FAIL;
}
state->vt = VT_I4;
state->lVal = MSAAState(response().output_long1);
return S_OK;
}
STDMETHODIMP BrowserAccessibility::get_accValue(VARIANT var_id, BSTR* value) {
if (!instance_active()) {
// Instance no longer active, fail gracefully.
return E_FAIL;
}
if (var_id.vt != VT_I4 || !value)
return E_INVALIDARG;
if (!RequestAccessibilityInfo(WebAccessibility::FUNCTION_VALUE, var_id, NULL,
NULL)) {
return E_FAIL;
}
if (!response().return_code || response().output_string.empty()) {
// No string found.
return S_FALSE;
}
*value = SysAllocString(response().output_string.c_str());
DCHECK(*value);
return S_OK;
}
STDMETHODIMP BrowserAccessibility::get_accHelpTopic(BSTR* help_file,
VARIANT var_id,
LONG* topic_id) {
if (help_file)
*help_file = NULL;
if (topic_id)
*topic_id = static_cast<LONG>(-1);
return E_NOTIMPL;
}
STDMETHODIMP BrowserAccessibility::get_accSelection(VARIANT* selected) {
if (selected)
selected->vt = VT_EMPTY;
return E_NOTIMPL;
}
STDMETHODIMP BrowserAccessibility::CreateInstance(REFIID iid,
int iaccessible_id,
void** interface_ptr) {
return BrowserAccessibilityManager::GetInstance()->
CreateAccessibilityInstance(iid, iaccessible_id, routing_id_,
process_id_, parent_hwnd_, interface_ptr);
}
bool BrowserAccessibility::RequestAccessibilityInfo(int iaccessible_func_id,
VARIANT var_id, LONG input1,
LONG input2) {
// Create and populate IPC message structure, for retrieval of accessibility
// information from the renderer.
WebAccessibility::InParams in_params;
in_params.object_id = iaccessible_id_;
in_params.function_id = iaccessible_func_id;
in_params.child_id = var_id.lVal;
in_params.input_long1 = input1;
in_params.input_long2 = input2;
return BrowserAccessibilityManager::GetInstance()->
RequestAccessibilityInfo(&in_params, routing_id_, process_id_);
}
const WebAccessibility::OutParams& BrowserAccessibility::response() {
return BrowserAccessibilityManager::GetInstance()->response();
}
long BrowserAccessibility::MSAARole(long browser_accessibility_role) {
switch (browser_accessibility_role) {
case WebAccessibility::ROLE_APPLICATION:
return ROLE_SYSTEM_APPLICATION;
case WebAccessibility::ROLE_CELL:
return ROLE_SYSTEM_CELL;
case WebAccessibility::ROLE_CHECKBUTTON:
return ROLE_SYSTEM_CHECKBUTTON;
case WebAccessibility::ROLE_COLUMN:
return ROLE_SYSTEM_COLUMN;
case WebAccessibility::ROLE_COLUMNHEADER:
return ROLE_SYSTEM_COLUMNHEADER;
case WebAccessibility::ROLE_DOCUMENT:
return ROLE_SYSTEM_DOCUMENT;
case WebAccessibility::ROLE_GRAPHIC:
return ROLE_SYSTEM_GRAPHIC;
case WebAccessibility::ROLE_GROUPING:
return ROLE_SYSTEM_GROUPING;
case WebAccessibility::ROLE_LINK:
return ROLE_SYSTEM_LINK;
case WebAccessibility::ROLE_LIST:
case WebAccessibility::ROLE_LISTBOX:
return ROLE_SYSTEM_LIST;
case WebAccessibility::ROLE_LISTITEM:
return ROLE_SYSTEM_LISTITEM;
case WebAccessibility::ROLE_MENUBAR:
return ROLE_SYSTEM_MENUBAR;
case WebAccessibility::ROLE_MENUITEM:
return ROLE_SYSTEM_MENUITEM;
case WebAccessibility::ROLE_MENUPOPUP:
return ROLE_SYSTEM_MENUPOPUP;
case WebAccessibility::ROLE_OUTLINE:
return ROLE_SYSTEM_OUTLINE;
case WebAccessibility::ROLE_PAGETABLIST:
return ROLE_SYSTEM_PAGETABLIST;
case WebAccessibility::ROLE_PROGRESSBAR:
return ROLE_SYSTEM_PROGRESSBAR;
case WebAccessibility::ROLE_PUSHBUTTON:
return ROLE_SYSTEM_PUSHBUTTON;
case WebAccessibility::ROLE_RADIOBUTTON:
return ROLE_SYSTEM_RADIOBUTTON;
case WebAccessibility::ROLE_ROW:
return ROLE_SYSTEM_ROW;
case WebAccessibility::ROLE_ROWHEADER:
return ROLE_SYSTEM_ROWHEADER;
case WebAccessibility::ROLE_SEPARATOR:
return ROLE_SYSTEM_SEPARATOR;
case WebAccessibility::ROLE_SLIDER:
return ROLE_SYSTEM_SLIDER;
case WebAccessibility::ROLE_STATICTEXT:
return ROLE_SYSTEM_STATICTEXT;
case WebAccessibility::ROLE_STATUSBAR:
return ROLE_SYSTEM_STATUSBAR;
case WebAccessibility::ROLE_TABLE:
return ROLE_SYSTEM_TABLE;
case WebAccessibility::ROLE_TEXT:
return ROLE_SYSTEM_TEXT;
case WebAccessibility::ROLE_TOOLBAR:
return ROLE_SYSTEM_TOOLBAR;
case WebAccessibility::ROLE_TOOLTIP:
return ROLE_SYSTEM_TOOLTIP;
case WebAccessibility::ROLE_CLIENT:
default:
// This is the default role for MSAA.
return ROLE_SYSTEM_CLIENT;
}
}
long BrowserAccessibility::MSAAState(long browser_accessibility_state) {
long state = 0;
if ((browser_accessibility_state >> WebAccessibility::STATE_CHECKED) & 1)
state |= STATE_SYSTEM_CHECKED;
if ((browser_accessibility_state >> WebAccessibility::STATE_FOCUSABLE) & 1)
state |= STATE_SYSTEM_FOCUSABLE;
if ((browser_accessibility_state >> WebAccessibility::STATE_FOCUSED) & 1)
state |= STATE_SYSTEM_FOCUSED;
if ((browser_accessibility_state >> WebAccessibility::STATE_HOTTRACKED) & 1)
state |= STATE_SYSTEM_HOTTRACKED;
if ((browser_accessibility_state >>
WebAccessibility::STATE_INDETERMINATE) & 1) {
state |= STATE_SYSTEM_INDETERMINATE;
}
if ((browser_accessibility_state >> WebAccessibility::STATE_LINKED) & 1)
state |= STATE_SYSTEM_LINKED;
if ((browser_accessibility_state >>
WebAccessibility::STATE_MULTISELECTABLE) & 1) {
state |= STATE_SYSTEM_MULTISELECTABLE;
}
if ((browser_accessibility_state >> WebAccessibility::STATE_OFFSCREEN) & 1)
state |= STATE_SYSTEM_OFFSCREEN;
if ((browser_accessibility_state >> WebAccessibility::STATE_PRESSED) & 1)
state |= STATE_SYSTEM_PRESSED;
if ((browser_accessibility_state >> WebAccessibility::STATE_PROTECTED) & 1)
state |= STATE_SYSTEM_PROTECTED;
if ((browser_accessibility_state >> WebAccessibility::STATE_READONLY) & 1)
state |= STATE_SYSTEM_READONLY;
if ((browser_accessibility_state >> WebAccessibility::STATE_TRAVERSED) & 1)
state |= STATE_SYSTEM_TRAVERSED;
if ((browser_accessibility_state >> WebAccessibility::STATE_UNAVAILABLE) & 1)
state |= STATE_SYSTEM_UNAVAILABLE;
return state;
}
| 29.357988 | 80 | 0.657412 | [
"object"
] |
2bb65efeadfe1069d791530c4653f556ab1bf5f8 | 29,576 | cpp | C++ | UI/Dialogs/BaseDialog.cpp | stephenegriffin/mfcmapi | bffbff6da9a8c292891568159c8088aac9b2052c | [
"MIT"
] | 655 | 2016-10-13T20:18:52.000Z | 2022-03-28T21:25:14.000Z | UI/Dialogs/BaseDialog.cpp | stephenegriffin/mfcmapi | bffbff6da9a8c292891568159c8088aac9b2052c | [
"MIT"
] | 285 | 2016-10-18T19:03:31.000Z | 2022-03-10T11:02:33.000Z | UI/Dialogs/BaseDialog.cpp | stephenegriffin/mfcmapi | bffbff6da9a8c292891568159c8088aac9b2052c | [
"MIT"
] | 129 | 2016-10-14T14:27:24.000Z | 2022-03-30T12:34:01.000Z | #include <StdAfx.h>
#include <UI/Dialogs/BaseDialog.h>
#include <UI/FakeSplitter.h>
#include <core/mapi/cache/mapiObjects.h>
#include <UI/ParentWnd.h>
#include <UI/Controls/SortList/SingleMAPIPropListCtrl.h>
#include <UI/Dialogs/Editors/Editor.h>
#include <UI/Dialogs/Editors/HexEditor.h>
#include <UI/Dialogs/MFCUtilityFunctions.h>
#include <UI/UIFunctions.h>
#include <UI/Dialogs/AboutDlg.h>
#include <core/mapi/adviseSink.h>
#include <core/mapi/extraPropTags.h>
#include <Msi.h>
#include <core/smartview/SmartView.h>
#include <core/mapi/cache/globalCache.h>
#include <UI/Dialogs/ContentsTable/MainDlg.h>
#include <UI/Dialogs/Editors/DbgView.h>
#include <UI/Dialogs/Editors/Options.h>
#include <Windows.h>
#include <malloc.h>
#include <core/mapi/version.h>
#include <UI/addinui.h>
#include <core/utility/registry.h>
#include <core/utility/strings.h>
#include <core/utility/output.h>
#include <core/interpret/flags.h>
#include <core/mapi/mapiFunctions.h>
namespace dialog
{
static std::wstring CLASS = L"CBaseDialog";
CBaseDialog::CBaseDialog(
_In_ std::shared_ptr<cache::CMapiObjects> lpMapiObjects, // Pass NULL to create a new m_lpMapiObjects,
const ULONG ulAddInContext)
{
TRACE_CONSTRUCTOR(CLASS);
m_szTitle = strings::loadstring(IDS_BASEDIALOG);
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = EC_D(HICON, AfxGetApp()->LoadIcon(IDR_MAINFRAME));
// Let the parent know we have a status bar so we can draw our border correctly
SetStatusHeight(GetSystemMetrics(SM_CXSIZEFRAME) + ui::GetTextHeight(::GetDesktopWindow()));
m_lpParent = ui::GetParentWnd();
if (m_lpParent) m_lpParent->AddRef();
m_ulAddInContext = ulAddInContext;
m_lpMapiObjects = std::make_shared<cache::CMapiObjects>(lpMapiObjects);
}
CBaseDialog::~CBaseDialog()
{
TRACE_DESTRUCTOR(CLASS);
const auto hMenu = ::GetMenu(this->m_hWnd);
if (hMenu)
{
ui::DeleteMenuEntries(hMenu);
DestroyMenu(hMenu);
}
CWnd::DestroyWindow();
OnNotificationsOff();
if (m_lpParent) m_lpParent->Release();
}
STDMETHODIMP_(ULONG) CBaseDialog::AddRef()
{
const auto lCount = InterlockedIncrement(&m_cRef);
TRACE_ADDREF(CLASS, lCount);
output::DebugPrint(output::dbgLevel::RefCount, L"CBaseDialog::AddRef(\"%ws\")\n", m_szTitle.c_str());
return lCount;
}
STDMETHODIMP_(ULONG) CBaseDialog::Release()
{
const auto lCount = InterlockedDecrement(&m_cRef);
TRACE_RELEASE(CLASS, lCount);
output::DebugPrint(output::dbgLevel::RefCount, L"CBaseDialog::Release(\"%ws\")\n", m_szTitle.c_str());
if (!lCount) delete this;
return lCount;
}
BEGIN_MESSAGE_MAP(CBaseDialog, CMyDialog)
ON_WM_ACTIVATE()
ON_WM_INITMENU()
ON_WM_MENUSELECT()
ON_WM_SIZE()
ON_COMMAND(ID_OPTIONS, OnOptions)
ON_COMMAND(ID_OPENMAINWINDOW, OnOpenMainWindow)
ON_COMMAND(ID_MYHELP, OnHelp)
ON_COMMAND(ID_NOTIFICATIONSOFF, OnNotificationsOff)
ON_COMMAND(ID_NOTIFICATIONSON, OnNotificationsOn)
ON_COMMAND(ID_DISPATCHNOTIFICATIONS, OnDispatchNotifications)
ON_MESSAGE(WM_MFCMAPI_UPDATESTATUSBAR, msgOnUpdateStatusBar)
ON_MESSAGE(WM_MFCMAPI_CLEARSINGLEMAPIPROPLIST, msgOnClearSingleMAPIPropList)
END_MESSAGE_MAP()
LRESULT CBaseDialog::WindowProc(const UINT message, const WPARAM wParam, const LPARAM lParam)
{
switch (message)
{
case WM_COMMAND:
{
const auto idFrom = LOWORD(wParam);
// idFrom is the menu item selected
if (HandleMenu(idFrom)) return S_OK;
break;
}
case WM_PAINT:
// Paint the status, then let the rest draw itself.
ui::DrawStatus(
m_hWnd,
GetStatusHeight(),
getStatusMessage(statusPane::data1),
getStatusWidth(statusPane::data1),
getStatusMessage(statusPane::data2),
getStatusWidth(statusPane::data2),
getStatusMessage(statusPane::infoText));
break;
}
return CMyDialog::WindowProc(message, wParam, lParam);
}
BOOL CBaseDialog::OnInitDialog()
{
UpdateTitleBarText();
setStatusWidth(statusPane::data1, 0);
setStatusWidth(statusPane::data2, 0);
setStatusWidth(statusPane::infoText, -1);
SetIcon(m_hIcon, false); // Set small icon - large icon isn't used
m_lpFakeSplitter.Init(m_hWnd);
m_lpPropDisplay = new controls::sortlistctrl::CSingleMAPIPropListCtrl(&m_lpFakeSplitter, this, m_lpMapiObjects);
if (m_lpPropDisplay) m_lpFakeSplitter.SetPaneTwo(m_lpPropDisplay->GetSafeHwnd());
return false;
}
void CBaseDialog::CreateDialogAndMenu(
const UINT nIDMenuResource,
const UINT uiClassMenuResource,
const UINT uidClassMenuTitle)
{
output::DebugPrintEx(
output::dbgLevel::CreateDialog, CLASS, L"CreateDialogAndMenu", L"id = 0x%X\n", nIDMenuResource);
m_lpszTemplateName = MAKEINTRESOURCE(IDD_BLANK_DIALOG);
DisplayParentedDialog(0);
HMENU hMenu = nullptr;
if (nIDMenuResource)
{
hMenu = ::LoadMenu(nullptr, MAKEINTRESOURCE(nIDMenuResource));
}
else
{
hMenu = CreateMenu();
}
const auto hMenuOld = ::GetMenu(m_hWnd);
if (hMenuOld) DestroyMenu(hMenuOld);
::SetMenu(m_hWnd, hMenu);
AddMenu(hMenu, IDR_MENU_PROPERTY, IDS_PROPERTYMENU, static_cast<unsigned>(-1));
AddMenu(hMenu, uiClassMenuResource, uidClassMenuTitle, static_cast<unsigned>(-1));
m_ulAddInMenuItems = ui::addinui::ExtendAddInMenu(hMenu, m_ulAddInContext);
AddMenu(hMenu, IDR_MENU_TOOLS, IDS_TOOLSMENU, static_cast<unsigned>(-1));
const auto hSub = GetSubMenu(hMenu, 0);
::AppendMenu(hSub, MF_SEPARATOR, NULL, nullptr);
auto szExit = strings::loadstring(IDS_EXIT);
AppendMenuW(hSub, MF_ENABLED | MF_STRING, IDCANCEL, szExit.c_str());
// Make sure the menu background is filled in the right color
auto mi = MENUINFO{};
mi.cbSize = sizeof(MENUINFO);
mi.fMask = MIM_BACKGROUND;
mi.hbrBack = GetSysBrush(ui::uiColor::Background);
SetMenuInfo(hMenu, &mi);
ui::ConvertMenuOwnerDraw(hMenu, true);
// We're done - force our new menu on screen
DrawMenuBar();
}
_Check_return_ bool CBaseDialog::HandleMenu(const WORD wMenuSelect)
{
output::DebugPrint(
output::dbgLevel::Menu, L"CBaseDialog::HandleMenu wMenuSelect = 0x%X = %u\n", wMenuSelect, wMenuSelect);
switch (wMenuSelect)
{
case ID_HEXEDITOR:
OnHexEditor();
return true;
case ID_DBGVIEW:
editor::DisplayDbgView();
return true;
case ID_COMPAREENTRYIDS:
OnCompareEntryIDs();
return true;
case ID_OPENENTRYID:
OnOpenEntryID({});
return true;
case ID_COMPUTESTOREHASH:
OnComputeStoreHash();
return true;
case ID_COPY:
HandleCopy();
return true;
case ID_PASTE:
static_cast<void>(HandlePaste());
return true;
case ID_OUTLOOKVERSION:
OnOutlookVersion();
return true;
}
if (HandleAddInMenu(wMenuSelect)) return true;
if (m_lpPropDisplay) return m_lpPropDisplay->HandleMenu(wMenuSelect);
return false;
}
void CBaseDialog::OnInitMenu(_In_opt_ CMenu* pMenu)
{
const auto bMAPIInitialized = cache::CGlobalCache::getInstance().bMAPIInitialized();
if (pMenu)
{
if (m_lpPropDisplay) m_lpPropDisplay->InitMenu(pMenu);
pMenu->EnableMenuItem(ID_NOTIFICATIONSON, DIM(bMAPIInitialized && !m_lpBaseAdviseSink));
pMenu->CheckMenuItem(ID_NOTIFICATIONSON, CHECK(m_lpBaseAdviseSink));
pMenu->EnableMenuItem(ID_NOTIFICATIONSOFF, DIM(m_lpBaseAdviseSink));
pMenu->EnableMenuItem(ID_DISPATCHNOTIFICATIONS, DIM(bMAPIInitialized));
}
CMyDialog::OnInitMenu(pMenu);
}
// Checks flags on add-in menu items to ensure they should be enabled
// Override to support context sensitive scenarios
void CBaseDialog::EnableAddInMenus(
_In_ HMENU hMenu,
const ULONG ulMenu,
_In_ LPMENUITEM /*lpAddInMenu*/,
const UINT uiEnable)
{
if (hMenu) EnableMenuItem(hMenu, ulMenu, uiEnable);
}
// Help strings can be found in mfcmapi.rc2
// Will preserve the existing text in the right status pane, restoring it when we stop displaying menus
void CBaseDialog::OnMenuSelect(const UINT nItemID, const UINT nFlags, HMENU /*hSysMenu*/)
{
if (!m_bDisplayingMenuText)
{
m_szMenuDisplacedText = getStatusMessage(statusPane::infoText);
}
if (nItemID && !(nFlags & (MF_SEPARATOR | MF_POPUP)))
{
UpdateStatusBarText(statusPane::infoText, nItemID); // This will LoadString the menu help text for us
m_bDisplayingMenuText = true;
}
else
{
m_bDisplayingMenuText = false;
}
if (!m_bDisplayingMenuText)
{
UpdateStatusBarText(statusPane::infoText, m_szMenuDisplacedText);
}
}
_Check_return_ bool
CBaseDialog::HandleKeyDown(const UINT nChar, const bool bShift, const bool bCtrl, const bool bMenu)
{
output::DebugPrintEx(
output::dbgLevel::Menu,
CLASS,
L"HandleKeyDown",
L"nChar = 0x%0X, bShift = 0x%X, bCtrl = 0x%X, bMenu = 0x%X\n",
nChar,
bShift,
bCtrl,
bMenu);
if (bMenu) return false;
switch (nChar)
{
case 'H':
if (bCtrl)
{
OnHexEditor();
return true;
}
break;
case 'D':
if (bCtrl)
{
editor::DisplayDbgView();
return true;
}
break;
case VK_F1:
DisplayAboutDlg(this);
return true;
case 'S':
if (bCtrl && m_lpPropDisplay)
{
m_lpPropDisplay->SavePropsToXML();
return true;
}
break;
case VK_DELETE:
OnDeleteSelectedItem();
return true;
case 'X':
if (bCtrl)
{
OnDeleteSelectedItem();
return true;
}
break;
case 'C':
if (bCtrl && !bShift)
{
HandleCopy();
return true;
}
break;
case 'V':
if (bCtrl)
{
static_cast<void>(HandlePaste());
return true;
}
break;
case 'O':
if (bCtrl)
{
OnOptions();
return true;
}
break;
case VK_F5:
if (!bCtrl)
{
OnRefreshView();
return true;
}
break;
case VK_ESCAPE:
OnEscHit();
return true;
case VK_RETURN:
output::DebugPrint(output::dbgLevel::Menu, L"CBaseDialog::HandleKeyDown posting ID_DISPLAYSELECTEDITEM\n");
PostMessage(WM_COMMAND, ID_DISPLAYSELECTEDITEM, NULL);
return true;
}
return false;
}
// prevent dialog from disappearing on Enter
void CBaseDialog::OnOK()
{
// Now that my controls capture VK_ENTER...this is unneeded...keep it just in case.
}
void CBaseDialog::OnCancel()
{
ShowWindow(SW_HIDE);
if (m_lpPropDisplay) m_lpPropDisplay->Release();
m_lpPropDisplay = nullptr;
Release();
}
void CBaseDialog::OnEscHit()
{
output::DebugPrintEx(output::dbgLevel::Generic, CLASS, L"OnEscHit", L"Not implemented\n");
}
void CBaseDialog::OnOptions()
{
const bool ulNiceNamesBefore = registry::doColumnNames;
const bool ulSuppressNotFoundBefore = registry::suppressNotFound;
const auto bNeedPropRefresh = editor::DisplayOptionsDlg(this);
const auto bNiceNamesChanged = ulNiceNamesBefore != registry::doColumnNames;
const auto bSuppressNotFoundChanged = ulSuppressNotFoundBefore != registry::suppressNotFound;
auto bResetColumns = false;
if (bNiceNamesChanged || bSuppressNotFoundChanged)
{
// We check if this worked so we don't refresh the prop list after resetting the top pane
// But, if we're a tree view, this won't work at all, so we'll still want to reset props if needed
bResetColumns = static_cast<bool>(::SendMessage(m_hWnd, WM_MFCMAPI_RESETCOLUMNS, 0, 0));
}
if (!bResetColumns && bNeedPropRefresh)
{
if (m_lpPropDisplay) m_lpPropDisplay->RefreshMAPIPropList();
}
}
void CBaseDialog::OnOpenMainWindow()
{
auto pMain = new CMainDlg(m_lpMapiObjects);
if (pMain) pMain->OnOpenMessageStoreTable();
}
void CBaseDialog::HandleCopy() { output::DebugPrintEx(output::dbgLevel::Generic, CLASS, L"HandleCopy", L"\n"); }
_Check_return_ bool CBaseDialog::HandlePaste()
{
output::DebugPrintEx(output::dbgLevel::Generic, CLASS, L"HandlePaste", L"\n");
const auto ulStatus = cache::CGlobalCache::getInstance().GetBufferStatus();
if (m_lpPropDisplay && ulStatus & BUFFER_PROPTAG && ulStatus & BUFFER_SOURCEPROPOBJ)
{
m_lpPropDisplay->OnPasteProperty();
return true;
}
return false;
}
void CBaseDialog::OnHelp() { DisplayAboutDlg(this); }
void CBaseDialog::OnDeleteSelectedItem()
{
output::DebugPrintEx(
output::dbgLevel::DeleteSelectedItem, CLASS, L"OnDeleteSelectedItem", L" Not Implemented\n");
}
void CBaseDialog::OnRefreshView()
{
output::DebugPrintEx(output::dbgLevel::Generic, CLASS, L"OnRefreshView", L" Not Implemented\n");
}
void CBaseDialog::OnUpdateSingleMAPIPropListCtrl(
_In_opt_ LPMAPIPROP lpMAPIProp,
_In_opt_ sortlistdata::sortListData* lpListData) const
{
output::DebugPrintEx(
output::dbgLevel::Generic, CLASS, L"OnUpdateSingleMAPIPropListCtrl", L"Setting item %p\n", lpMAPIProp);
if (m_lpPropDisplay)
{
m_lpPropDisplay->SetDataSource(lpMAPIProp, lpListData, m_bIsAB);
}
}
void CBaseDialog::AddMenu(HMENU hMenuBar, const UINT uiResource, const UINT uidTitle, const UINT uiPos)
{
auto hMenuToAdd = ::LoadMenu(nullptr, MAKEINTRESOURCE(uiResource));
if (hMenuBar && hMenuToAdd)
{
auto szTitle = strings::loadstring(uidTitle);
InsertMenuW(
hMenuBar, uiPos, MF_BYPOSITION | MF_POPUP, reinterpret_cast<UINT_PTR>(hMenuToAdd), szTitle.c_str());
if (IDR_MENU_PROPERTY == uiResource)
{
static_cast<void>(ui::addinui::ExtendAddInMenu(hMenuToAdd, MENU_CONTEXT_PROPERTY));
}
}
}
void CBaseDialog::OnActivate(const UINT nState, _In_ CWnd* pWndOther, const BOOL bMinimized)
{
CMyDialog::OnActivate(nState, pWndOther, bMinimized);
if (nState == 1 && !bMinimized) EC_B_S(RedrawWindow());
}
void CBaseDialog::SetStatusWidths() noexcept
{
const auto iData1 = !getStatusMessage(statusPane::data1).empty();
const auto iData2 = !getStatusMessage(statusPane::data2).empty();
auto sizeData1 = SIZE{};
auto sizeData2 = SIZE{};
if (iData1 || iData2)
{
const auto hdc = ::GetDC(m_hWnd);
if (hdc)
{
const auto hfontOld = SelectObject(hdc, ui::GetSegoeFontBold());
if (iData1)
{
sizeData1 = ui::GetTextExtentPoint32(hdc, getStatusMessage(statusPane::data1));
}
if (iData2)
{
sizeData2 = ui::GetTextExtentPoint32(hdc, getStatusMessage(statusPane::data2));
}
SelectObject(hdc, hfontOld);
::ReleaseDC(m_hWnd, hdc);
}
}
const auto nSpacing = GetSystemMetrics(SM_CXEDGE);
auto iWidthData1 = 0;
auto iWidthData2 = 0;
if (sizeData1.cx) iWidthData1 = sizeData1.cx + 4 * nSpacing;
if (sizeData2.cx) iWidthData2 = sizeData2.cx + 4 * nSpacing;
setStatusWidth(statusPane::data1, iWidthData1);
setStatusWidth(statusPane::data2, iWidthData2);
setStatusWidth(statusPane::infoText, -1);
auto rcStatus = RECT{};
::GetClientRect(m_hWnd, &rcStatus);
rcStatus.top = rcStatus.bottom - GetStatusHeight();
// Tell the window it needs to paint
::RedrawWindow(m_hWnd, &rcStatus, nullptr, RDW_INVALIDATE | RDW_UPDATENOW);
}
void CBaseDialog::OnSize(UINT /* nType*/, const int cx, const int cy)
{
auto hdwp = WC_D(HDWP, BeginDeferWindowPos(1));
if (hdwp)
{
const auto iHeight = GetStatusHeight();
const auto iNewCY = cy - iHeight;
auto rcStatus = RECT{};
::GetClientRect(m_hWnd, &rcStatus);
if (rcStatus.bottom - rcStatus.top > iHeight)
{
rcStatus.top = rcStatus.bottom - iHeight;
}
// Tell the status bar it needs repainting
::InvalidateRect(m_hWnd, &rcStatus, false);
if (m_lpFakeSplitter && m_lpFakeSplitter.m_hWnd)
{
hdwp =
EC_D(HDWP, DeferWindowPos(hdwp, m_lpFakeSplitter.m_hWnd, nullptr, 0, 0, cx, iNewCY, SWP_NOZORDER));
}
WC_B_S(EndDeferWindowPos(hdwp));
}
}
void CBaseDialog::UpdateStatusBarText(const statusPane nPos, _In_ const std::wstring& szMsg)
{
if (nPos < statusPane::numPanes) setStatusMessage(nPos, szMsg);
SetStatusWidths();
}
void __cdecl CBaseDialog::UpdateStatusBarText(const statusPane nPos, const UINT uidMsg)
{
UpdateStatusBarText(nPos, uidMsg, strings::emptystring, strings::emptystring, strings::emptystring);
}
void __cdecl CBaseDialog::UpdateStatusBarText(const statusPane nPos, UINT const uidMsg, ULONG const ulParam1)
{
auto szParam1 = std::to_wstring(ulParam1);
UpdateStatusBarText(nPos, uidMsg, szParam1, strings::emptystring, strings::emptystring);
}
void __cdecl CBaseDialog::UpdateStatusBarText(
statusPane const nPos,
UINT uidMsg,
const std::wstring& szParam1,
const std::wstring& szParam2,
const std::wstring& szParam3)
{
std::wstring szStatBarString;
// MAPI Load paths take special handling
if (uidMsg >= ID_LOADMAPIMENUMIN && uidMsg <= ID_LOADMAPIMENUMAX)
{
auto mii = MENUITEMINFOW{};
mii.cbSize = sizeof(MENUITEMINFO);
mii.fMask = MIIM_DATA;
WC_B_S(GetMenuItemInfoW(::GetMenu(m_hWnd), uidMsg, false, &mii));
if (mii.dwItemData)
{
const auto lme = reinterpret_cast<ui::LPMENUENTRY>(mii.dwItemData);
szStatBarString = strings::formatmessage(IDS_LOADMAPISTATUS, lme->m_pName.c_str());
}
}
else
{
const auto lpAddInMenu = ui::addinui::GetAddinMenuItem(m_hWnd, uidMsg);
if (lpAddInMenu && lpAddInMenu->szHelp)
{
szStatBarString = lpAddInMenu->szHelp;
}
else
{
szStatBarString = strings::formatmessage(uidMsg, szParam1.c_str(), szParam2.c_str(), szParam3.c_str());
}
}
UpdateStatusBarText(nPos, szStatBarString);
}
void CBaseDialog::UpdateTitleBarText(_In_ const std::wstring& szMsg) const
{
SetTitle(strings::formatmessage(IDS_TITLEBARMESSAGE, m_szTitle.c_str(), szMsg.c_str()));
}
void CBaseDialog::UpdateTitleBarText() const
{
SetTitle(strings::formatmessage(IDS_TITLEBARPLAIN, m_szTitle.c_str()));
}
void CBaseDialog::UpdateStatus(HWND hWndHost, const statusPane pane, const std::wstring& status) noexcept
{
static_cast<void>(::SendMessage(
hWndHost, WM_MFCMAPI_UPDATESTATUSBAR, static_cast<WPARAM>(pane), reinterpret_cast<LPARAM>(status.c_str())));
}
// WM_MFCMAPI_UPDATESTATUSBAR
_Check_return_ LRESULT CBaseDialog::msgOnUpdateStatusBar(WPARAM wParam, LPARAM const lParam)
{
const auto iPane = static_cast<statusPane>(wParam);
const std::wstring szStr = reinterpret_cast<LPWSTR>(lParam);
UpdateStatusBarText(iPane, szStr);
return S_OK;
}
// WM_MFCMAPI_CLEARSINGLEMAPIPROPLIST
_Check_return_ LRESULT CBaseDialog::msgOnClearSingleMAPIPropList(WPARAM /*wParam*/, LPARAM /*lParam*/)
{
OnUpdateSingleMAPIPropListCtrl(nullptr, nullptr);
return S_OK;
}
void CBaseDialog::OnHexEditor() { new editor::CHexEditor(m_lpMapiObjects); }
void CBaseDialog::OnOutlookVersion()
{
editor::CEditor MyEID(this, IDS_OUTLOOKVERSIONTITLE, NULL, CEDITOR_BUTTON_OK);
const auto szVersionString = version::GetOutlookVersionString();
MyEID.AddPane(viewpane::TextPane::CreateMultiLinePane(0, IDS_OUTLOOKVERSIONPROMPT, szVersionString, true));
static_cast<void>(MyEID.DisplayDialog());
}
void CBaseDialog::OnOpenEntryID(_In_ const SBinary& lpBin)
{
if (!m_lpMapiObjects) return;
editor::CEditor MyEID(this, IDS_OPENEID, IDS_OPENEIDPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL);
MyEID.AddPane(
viewpane::TextPane::CreateSingleLinePane(0, IDS_EID, strings::BinToHexString(&lpBin, false), false));
const auto lpMDB = m_lpMapiObjects->GetMDB(); // do not release
MyEID.AddPane(viewpane::CheckPane::Create(1, IDS_USEMDB, lpMDB != nullptr, lpMDB == nullptr));
auto lpAB = m_lpMapiObjects->GetAddrBook(false); // do not release
if (lpAB)
MyEID.AddPane(viewpane::CheckPane::Create(2, IDS_USEAB, true, lpAB == nullptr));
else
MyEID.AddPane(viewpane::CheckPane::Create(2, IDS_USEAB, false, lpAB == nullptr));
const auto lpMAPISession = m_lpMapiObjects->GetSession(); // do not release
MyEID.AddPane(viewpane::CheckPane::Create(3, IDS_SESSION, lpMAPISession != nullptr, lpMAPISession == nullptr));
MyEID.AddPane(viewpane::CheckPane::Create(4, IDS_PASSMAPIMODIFY, false, false));
MyEID.AddPane(viewpane::CheckPane::Create(5, IDS_PASSMAPINOCACHE, false, false));
MyEID.AddPane(viewpane::CheckPane::Create(6, IDS_PASSMAPICACHEONLY, false, false));
MyEID.AddPane(viewpane::CheckPane::Create(7, IDS_EIDBASE64ENCODED, false, false));
MyEID.AddPane(viewpane::CheckPane::Create(8, IDS_ATTEMPTIADDRBOOKDETAILSCALL, false, lpAB == nullptr));
MyEID.AddPane(viewpane::CheckPane::Create(9, IDS_EIDISCONTAB, false, false));
if (!MyEID.DisplayDialog()) return;
// Get the entry ID as a binary
const auto bin = MyEID.GetBinary(0, MyEID.GetCheck(7));
auto sBin = SBinary{static_cast<ULONG>(bin.size()), const_cast<BYTE*>(bin.data())};
if (MyEID.GetCheck(9))
{
static_cast<void>(mapi::UnwrapContactEntryID(sBin.cb, sBin.lpb, &sBin.cb, &sBin.lpb));
}
if (MyEID.GetCheck(8) && lpAB) // Do IAddrBook->Details here
{
auto ulUIParam = reinterpret_cast<ULONG_PTR>(m_hWnd);
EC_H_CANCEL_S(lpAB->Details(
&ulUIParam,
nullptr,
nullptr,
sBin.cb,
reinterpret_cast<LPENTRYID>(sBin.lpb),
nullptr,
nullptr,
nullptr,
DIALOG_MODAL)); // API doesn't like unicode
}
else
{
ULONG ulObjType = NULL;
auto lpUnk = mapi::CallOpenEntry<LPUNKNOWN>(
MyEID.GetCheck(1) ? lpMDB : nullptr,
MyEID.GetCheck(2) ? lpAB : nullptr,
nullptr,
MyEID.GetCheck(3) ? lpMAPISession : nullptr,
sBin.cb,
reinterpret_cast<LPENTRYID>(sBin.lpb),
nullptr,
(MyEID.GetCheck(4) ? MAPI_MODIFY : MAPI_BEST_ACCESS) | (MyEID.GetCheck(5) ? MAPI_NO_CACHE : 0) |
(MyEID.GetCheck(6) ? MAPI_CACHE_ONLY : 0),
&ulObjType);
if (lpUnk)
{
auto szFlags = smartview::InterpretNumberAsStringProp(ulObjType, PR_OBJECT_TYPE);
output::DebugPrint(
output::dbgLevel::Generic,
L"OnOpenEntryID: Got object (%p) of type 0x%08X = %ws\n",
lpUnk,
ulObjType,
szFlags.c_str());
auto lpTemp = mapi::safe_cast<LPMAPIPROP>(lpUnk);
if (lpTemp)
{
WC_H_S(DisplayObject(lpTemp, ulObjType, objectType::hierarchy, this));
lpTemp->Release();
}
lpUnk->Release();
}
}
}
void CBaseDialog::OnCompareEntryIDs()
{
if (!m_lpMapiObjects) return;
auto lpMDB = m_lpMapiObjects->GetMDB(); // do not release
auto lpMAPISession = m_lpMapiObjects->GetSession(); // do not release
auto lpAB = m_lpMapiObjects->GetAddrBook(false); // do not release
editor::CEditor MyEIDs(
this, IDS_COMPAREEIDS, IDS_COMPAREEIDSPROMPTS, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL);
MyEIDs.AddPane(viewpane::TextPane::CreateSingleLinePane(0, IDS_EID1, false));
MyEIDs.AddPane(viewpane::TextPane::CreateSingleLinePane(1, IDS_EID2, false));
UINT uidDropDown[] = {IDS_DDMESSAGESTORE, IDS_DDSESSION, IDS_DDADDRESSBOOK};
MyEIDs.AddPane(
viewpane::DropDownPane::Create(2, IDS_OBJECTFORCOMPAREEID, _countof(uidDropDown), uidDropDown, true));
MyEIDs.AddPane(viewpane::CheckPane::Create(3, IDS_EIDBASE64ENCODED, false, false));
if (!MyEIDs.DisplayDialog()) return;
if (0 == MyEIDs.GetDropDown(2) && !lpMDB || 1 == MyEIDs.GetDropDown(2) && !lpMAPISession ||
2 == MyEIDs.GetDropDown(2) && !lpAB)
{
error::ErrDialog(__FILE__, __LINE__, IDS_EDCOMPAREEID);
return;
}
// Get the entry IDs as a binary
const auto bin1 = MyEIDs.GetBinary(0, MyEIDs.GetCheck(3));
auto sBin1 = SBinary{static_cast<ULONG>(bin1.size()), const_cast<BYTE*>(bin1.data())};
const auto bin2 = MyEIDs.GetBinary(1, MyEIDs.GetCheck(3));
auto sBin2 = SBinary{static_cast<ULONG>(bin2.size()), const_cast<BYTE*>(bin2.data())};
auto hRes = S_OK;
ULONG ulResult = NULL;
switch (MyEIDs.GetDropDown(2))
{
case 0: // Message Store
hRes = EC_MAPI(lpMDB->CompareEntryIDs(
sBin1.cb,
reinterpret_cast<LPENTRYID>(sBin1.lpb),
sBin2.cb,
reinterpret_cast<LPENTRYID>(sBin2.lpb),
NULL,
&ulResult));
break;
case 1: // Session
hRes = EC_MAPI(lpMAPISession->CompareEntryIDs(
sBin1.cb,
reinterpret_cast<LPENTRYID>(sBin1.lpb),
sBin2.cb,
reinterpret_cast<LPENTRYID>(sBin2.lpb),
NULL,
&ulResult));
break;
case 2: // Address Book
hRes = EC_MAPI(lpAB->CompareEntryIDs(
sBin1.cb,
reinterpret_cast<LPENTRYID>(sBin1.lpb),
sBin2.cb,
reinterpret_cast<LPENTRYID>(sBin2.lpb),
NULL,
&ulResult));
break;
}
if (SUCCEEDED(hRes))
{
auto szResult = strings::loadstring(ulResult ? IDS_TRUE : IDS_FALSE);
const auto szRet = strings::formatmessage(IDS_COMPAREEIDBOOL, ulResult, szResult.c_str());
editor::CEditor Result(this, IDS_COMPAREEIDSRESULT, NULL, CEDITOR_BUTTON_OK);
Result.SetPromptPostFix(szRet);
static_cast<void>(Result.DisplayDialog());
}
}
void CBaseDialog::OnComputeStoreHash()
{
editor::CEditor MyStoreEID(
this, IDS_COMPUTESTOREHASH, IDS_COMPUTESTOREHASHPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL);
MyStoreEID.AddPane(viewpane::TextPane::CreateSingleLinePane(0, IDS_STOREEID, false));
MyStoreEID.AddPane(viewpane::CheckPane::Create(1, IDS_EIDBASE64ENCODED, false, false));
MyStoreEID.AddPane(viewpane::TextPane::CreateSingleLinePane(2, IDS_FILENAME, false));
MyStoreEID.AddPane(viewpane::CheckPane::Create(3, IDS_PUBLICFOLDERSTORE, false, false));
if (!MyStoreEID.DisplayDialog()) return;
// Get the entry ID as a binary
const auto bin = MyStoreEID.GetBinary(0, MyStoreEID.GetCheck(1));
auto sBin = SBinary{static_cast<ULONG>(bin.size()), const_cast<BYTE*>(bin.data())};
const auto dwHash = mapi::ComputeStoreHash(
sBin.cb, sBin.lpb, nullptr, MyStoreEID.GetStringW(2).c_str(), MyStoreEID.GetCheck(3));
const auto szHash = strings::formatmessage(IDS_STOREHASHVAL, dwHash);
editor::CEditor Result(this, IDS_STOREHASH, NULL, CEDITOR_BUTTON_OK);
Result.SetPromptPostFix(szHash);
static_cast<void>(Result.DisplayDialog());
}
void CBaseDialog::OnNotificationsOn()
{
if (m_lpBaseAdviseSink || !m_lpMapiObjects) return;
auto lpMDB = m_lpMapiObjects->GetMDB(); // do not release
auto lpMAPISession = m_lpMapiObjects->GetSession(); // do not release
auto lpAB = m_lpMapiObjects->GetAddrBook(false); // do not release
editor::CEditor MyData(
this, IDS_NOTIFICATIONS, IDS_NOTIFICATIONSPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL);
MyData.SetPromptPostFix(flags::AllFlagsToString(flagNotifEventType, true));
MyData.AddPane(viewpane::TextPane::CreateSingleLinePane(0, IDS_EID, false));
MyData.AddPane(viewpane::TextPane::CreateSingleLinePane(1, IDS_ULEVENTMASK, false));
MyData.SetHex(1, fnevNewMail);
UINT uidDropDown[] = {IDS_DDMESSAGESTORE, IDS_DDSESSION, IDS_DDADDRESSBOOK};
MyData.AddPane(
viewpane::DropDownPane::Create(2, IDS_OBJECTFORADVISE, _countof(uidDropDown), uidDropDown, true));
if (MyData.DisplayDialog())
{
if (0 == MyData.GetDropDown(2) && !lpMDB || 1 == MyData.GetDropDown(2) && !lpMAPISession ||
2 == MyData.GetDropDown(2) && !lpAB)
{
error::ErrDialog(__FILE__, __LINE__, IDS_EDADVISE);
return;
}
const auto bin = MyData.GetBinary(0, false);
auto sBin = SBinary{static_cast<ULONG>(bin.size()), const_cast<BYTE*>(bin.data())};
// don't actually care if the returning lpEntryID is NULL - Advise can work with that
m_lpBaseAdviseSink = new (std::nothrow) mapi::adviseSink(m_hWnd, nullptr);
auto hRes = S_OK;
if (m_lpBaseAdviseSink)
{
switch (MyData.GetDropDown(2))
{
case 0:
hRes = EC_MAPI(lpMDB->Advise(
sBin.cb,
reinterpret_cast<LPENTRYID>(sBin.lpb),
MyData.GetHex(1),
static_cast<IMAPIAdviseSink*>(m_lpBaseAdviseSink),
&m_ulBaseAdviseConnection));
m_lpBaseAdviseSink->SetAdviseTarget(lpMDB);
m_ulBaseAdviseObjectType = MAPI_STORE;
break;
case 1:
hRes = EC_MAPI(lpMAPISession->Advise(
sBin.cb,
reinterpret_cast<LPENTRYID>(sBin.lpb),
MyData.GetHex(1),
static_cast<IMAPIAdviseSink*>(m_lpBaseAdviseSink),
&m_ulBaseAdviseConnection));
m_ulBaseAdviseObjectType = MAPI_SESSION;
break;
case 2:
hRes = EC_MAPI(lpAB->Advise(
sBin.cb,
reinterpret_cast<LPENTRYID>(sBin.lpb),
MyData.GetHex(1),
static_cast<IMAPIAdviseSink*>(m_lpBaseAdviseSink),
&m_ulBaseAdviseConnection));
m_lpBaseAdviseSink->SetAdviseTarget(lpAB);
m_ulBaseAdviseObjectType = MAPI_ADDRBOOK;
break;
}
if (SUCCEEDED(hRes))
{
if (0 == MyData.GetDropDown(2) && lpMDB)
{
mapi::ForceRop(lpMDB);
}
}
else // if we failed to advise, then we don't need the advise sink object
{
if (m_lpBaseAdviseSink) m_lpBaseAdviseSink->Release();
m_lpBaseAdviseSink = nullptr;
m_ulBaseAdviseObjectType = NULL;
m_ulBaseAdviseConnection = NULL;
}
}
}
}
void CBaseDialog::OnNotificationsOff()
{
if (m_ulBaseAdviseConnection && m_lpMapiObjects)
{
switch (m_ulBaseAdviseObjectType)
{
case MAPI_SESSION:
{
auto lpMAPISession = m_lpMapiObjects->GetSession(); // do not release
if (lpMAPISession) EC_MAPI_S(lpMAPISession->Unadvise(m_ulBaseAdviseConnection));
break;
}
case MAPI_STORE:
{
auto lpMDB = m_lpMapiObjects->GetMDB(); // do not release
if (lpMDB) EC_MAPI_S(lpMDB->Unadvise(m_ulBaseAdviseConnection));
break;
}
case MAPI_ADDRBOOK:
{
auto lpAB = m_lpMapiObjects->GetAddrBook(false); // do not release
if (lpAB) EC_MAPI_S(lpAB->Unadvise(m_ulBaseAdviseConnection));
break;
}
}
}
if (m_lpBaseAdviseSink) m_lpBaseAdviseSink->Release();
m_lpBaseAdviseSink = nullptr;
m_ulBaseAdviseObjectType = NULL;
m_ulBaseAdviseConnection = NULL;
}
void CBaseDialog::OnDispatchNotifications() { EC_MAPI_S(HrDispatchNotifications(NULL)); }
_Check_return_ bool CBaseDialog::HandleAddInMenu(const WORD wMenuSelect)
{
output::DebugPrintEx(
output::dbgLevel::AddInPlumbing, CLASS, L"HandleAddInMenu", L"wMenuSelect = 0x%08X\n", wMenuSelect);
return false;
}
_Check_return_ std::shared_ptr<cache::CMapiObjects> CBaseDialog::GetMapiObjects() const noexcept
{
return m_lpMapiObjects;
}
} // namespace dialog | 29.605606 | 114 | 0.718556 | [
"object"
] |
2bbfdb9b5e223d0d15ba7f6320874714827cee97 | 7,567 | hpp | C++ | opengl/src/Rendering/ImageEffects/DepthOfFieldImageEffect.hpp | hhsaez/crimild | e3efee09489939338df55e8af9a1f9ddc01301f7 | [
"BSD-3-Clause"
] | 36 | 2015-03-12T10:42:36.000Z | 2022-01-12T04:20:40.000Z | opengl/src/Rendering/ImageEffects/DepthOfFieldImageEffect.hpp | hhsaez/crimild | e3efee09489939338df55e8af9a1f9ddc01301f7 | [
"BSD-3-Clause"
] | 1 | 2015-12-17T00:25:43.000Z | 2016-02-20T12:00:57.000Z | opengl/src/Rendering/ImageEffects/DepthOfFieldImageEffect.hpp | hhsaez/crimild | e3efee09489939338df55e8af9a1f9ddc01301f7 | [
"BSD-3-Clause"
] | 6 | 2017-06-17T07:57:53.000Z | 2019-04-09T21:11:24.000Z | /*
* Copyright (c) 2013, Hernan Saez
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CRIMILD_GL3_RENDERING_IMAGE_EFFECT_DEPTH_OF_FIELD_
#define CRIMILD_GL3_RENDERING_IMAGE_EFFECT_DEPTH_OF_FIELD_
#include <Rendering/ImageEffects/ImageEffect.hpp>
#include <Rendering/ShaderProgram.hpp>
#include <Rendering/ShaderUniformImpl.hpp>
namespace crimild {
namespace opengl {
class DepthOfFieldImageEffect : public ImageEffect {
public:
class DoFBlurShaderProgram : public ShaderProgram {
public:
DoFBlurShaderProgram( void );
virtual ~DoFBlurShaderProgram( void );
void setOrientation( int value ) { _uOrientation->setValue( value ); }
int getOrientation( void ) { return _uOrientation->getValue(); }
void setTexelSize( const Vector2f &value ) { _uTexelSize->setValue( value ); }
Vector2f getTexelSize( void ) { return _uTexelSize->getValue(); }
void setBlurCoefficient( float value ) { _uBlurCoefficient->setValue( value ); }
float getBlurCoefficient( void ) { return _uBlurCoefficient->getValue(); }
void setFocusDistance( float value ) { _uFocusDistance->setValue( value ); }
float getFocusDistance( void ) { return _uFocusDistance->getValue(); }
void setPPM( float value ) { _uPPM->setValue( value ); }
float getPPM( void ) { return _uPPM->getValue(); }
void setNear( float value ) { _uNear->setValue( value ); }
float getNear( void ) { return _uNear->getValue(); }
void setFar( float value ) { _uFar->setValue( value ); }
float getFar( void ) { return _uFar->getValue(); }
private:
SharedPointer< IntUniform > _uOrientation;
SharedPointer< Vector2fUniform > _uTexelSize;
SharedPointer< FloatUniform > _uBlurCoefficient;
SharedPointer< FloatUniform > _uFocusDistance;
SharedPointer< FloatUniform > _uPPM;
SharedPointer< FloatUniform > _uNear;
SharedPointer< FloatUniform > _uFar;
};
class DoFCompositeShaderProgram : public ShaderProgram {
public:
DoFCompositeShaderProgram( void );
virtual ~DoFCompositeShaderProgram( void );
void setBlurCoefficient( float value ) { _uBlurCoefficient->setValue( value ); }
float getBlurCoefficient( void ) { return _uBlurCoefficient->getValue(); }
void setFocusDistance( float value ) { _uFocusDistance->setValue( value ); }
float getFocusDistance( void ) { return _uFocusDistance->getValue(); }
void setPPM( float value ) { _uPPM->setValue( value ); }
float getPPM( void ) { return _uPPM->getValue(); }
void setNear( float value ) { _uNear->setValue( value ); }
float getNear( void ) { return _uNear->getValue(); }
void setFar( float value ) { _uFar->setValue( value ); }
float getFar( void ) { return _uFar->getValue(); }
private:
SharedPointer< IntUniform > _uOrientation;
SharedPointer< Vector2fUniform > _uTexelSize;
SharedPointer< FloatUniform > _uBlurCoefficient;
SharedPointer< FloatUniform > _uFocusDistance;
SharedPointer< FloatUniform > _uPPM;
SharedPointer< FloatUniform > _uNear;
SharedPointer< FloatUniform > _uFar;
};
public:
DepthOfFieldImageEffect( void );
explicit DepthOfFieldImageEffect( int resolution );
virtual ~DepthOfFieldImageEffect( void );
virtual void compute( crimild::Renderer *renderer, Camera *camera ) override;
virtual void apply( crimild::Renderer *renderer, crimild::Camera *camera ) override;
int getResolution( void ) const { return _resolution; }
float getFocalDistance( void ) { return _focalDistance->getValue(); }
void setFocalDistance( float value ) { _focalDistance->setValue( value ); }
float getFocusDistance( void ) { return _focusDistance->getValue(); }
void setFocusDistance( float value ) { _focusDistance->setValue( value ); }
float getFStop( void ) { return _fStop->getValue(); }
void setFStop( float value ) { _fStop->setValue( value ); }
float getAperture( void ) { return _aperture->getValue(); }
void setAperture( float value ) { _aperture->setValue( value ); }
private:
int _resolution;
SharedPointer< FloatUniform > _focalDistance; //< in millimeters
SharedPointer< FloatUniform > _focusDistance; //< in millimeters
SharedPointer< FloatUniform > _fStop; //< in millimeters
SharedPointer< FloatUniform > _aperture; //< in millimeters
private:
DoFBlurShaderProgram *getBlurProgram( void ) { return crimild::get_ptr( _dofBlurProgram ); }
DoFCompositeShaderProgram *getCompositeProgram( void ) { return crimild::get_ptr( _dofCompositeProgram ); }
private:
SharedPointer< DoFBlurShaderProgram > _dofBlurProgram;
SharedPointer< DoFCompositeShaderProgram > _dofCompositeProgram;
private:
FrameBufferObject *getAuxFBO( int index ) { return crimild::get_ptr( _auxFBOs[ index ] ); }
private:
std::vector< SharedPointer< FrameBufferObject >> _auxFBOs;
};
}
}
#endif
| 48.197452 | 119 | 0.61266 | [
"vector"
] |
2bc2743394b6efcbbaf428b79189994936a8a2e8 | 365 | cpp | C++ | nodes/control/PositionControlNode_px4_yawrate.cpp | larics/uav_ros_control | ec71445054ad148a8feb57ab59d9cbeca04c9f0d | [
"BSD-3-Clause"
] | 1 | 2020-03-19T09:10:07.000Z | 2020-03-19T09:10:07.000Z | nodes/control/PositionControlNode_px4_yawrate.cpp | lmark1/uav_ros_control | 5a00210e6c5418ad34da6fabea6e3bbcf6fbcf7c | [
"BSD-3-Clause"
] | 4 | 2021-01-12T15:30:54.000Z | 2021-05-27T23:28:09.000Z | nodes/control/PositionControlNode_px4_yawrate.cpp | lmark1/uav_ros_control | 5a00210e6c5418ad34da6fabea6e3bbcf6fbcf7c | [
"BSD-3-Clause"
] | 1 | 2020-03-20T17:23:15.000Z | 2020-03-20T17:23:15.000Z | #include <uav_ros_control/control/CascadePID.hpp>
int main(int argc, char **argv)
{
ros::init(argc, argv, "position_control_node");
ros::NodeHandle nh;
// Initialize distance control object
std::shared_ptr<uav_controller::CascadePID> carrotRefObj{
new uav_controller::CascadePID(nh)
};
uav_controller::runDefault_yawrate_px4(*carrotRefObj, nh);
} | 26.071429 | 60 | 0.750685 | [
"object"
] |
2bc6b29cbada25d6c2cc95a4196d6254abacbec5 | 8,803 | cpp | C++ | branch/old_angsys/angsys_beta3/source/platform/platform.desktop/source/input/controller.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | branch/old_angsys/angsys_beta3/source/platform/platform.desktop/source/input/controller.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | branch/old_angsys/angsys_beta3/source/platform/platform.desktop/source/input/controller.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | #include "pch.h"
#include <ang/platform/win32/controller.h>
#include "event_args.h"
#include <Xinput.h>
using namespace ang;
using namespace ang::platform;
using namespace ang::platform::input;
struct controller::handle
{
uint id = 0;
events::event_listener digital_input_event;
events::event_listener analog_input_event;
XINPUT_STATE last_state;
handle(controller* ptr)
: digital_input_event(ptr, [](events::core_msg_t msg) { return msg == (events::core_msg_t)events::core_msg::contorller_button_change; })
, analog_input_event(ptr, [](events::core_msg_t msg) { return msg == (events::core_msg_t)events::core_msg::contorller_analog_change; })
{
}
};
controller::controller(uint id)
: m_handle(null)
{
m_handle = new handle(this);
m_handle->id = id;
}
controller::~controller()
{
delete m_handle;
m_handle = null;
}
ANG_IMPLEMENT_OBJECT_RUNTIME_INFO(ang::platform::input::controller);
ANG_IMPLEMENT_OBJECT_CLASS_INFO(ang::platform::input::controller, object, icontroller);
ANG_IMPLEMENT_OBJECT_QUERY_INTERFACE(ang::platform::input::controller, object, icontroller);
uint controller::get_device_id_property(base_property<uint>const* prop)
{
return field_to_parent(&controller::device_id, prop)->get_controller_id();
}
controller_buttons_state_t controller::get_state_property(base_property<controller_buttons_state_t>const* prop)
{
return field_to_parent(&controller::state, prop)->get_state();
}
analog_input_value_t controller::get_triggers_property(base_property<analog_input_value_t>const* prop)
{
return field_to_parent(&controller::triggers, prop)->get_triggers();
}
thumb_stick_value_t controller::get_left_thumb_stick_property(base_property<thumb_stick_value_t>const* prop)
{
return field_to_parent(&controller::left_thumb_stick, prop)->get_left_thumb_stick();
}
thumb_stick_value_t controller::get_right_thumb_stick_property(base_property<thumb_stick_value_t>const* prop)
{
return field_to_parent(&controller::right_thumb_stick, prop)->get_right_thumb_stick();
}
events::event_token_t controller::add_digital_input_event(events::base_event* prop, events::event_t e)
{
return field_to_parent(&controller::digital_input_event, prop)->add_analog_input_event(e);
}
bool controller::remove_digital_input_event(events::base_event* prop, events::event_token_t token)
{
return field_to_parent(&controller::digital_input_event, prop)->remove_digital_input_event(token);
}
events::event_token_t controller::add_analog_input_event(events::base_event* prop, events::event_t e)
{
return field_to_parent(&controller::analog_input_event, prop)->add_analog_input_event(e);
}
bool controller::remove_analog_input_event(events::base_event* prop, events::event_token_t token)
{
return field_to_parent(&controller::analog_input_event, prop)->remove_analog_input_event(token);
}
uint controller::get_controller_id()const
{
return m_handle->id;
}
controller_buttons_state_t controller::get_state()const
{
return controller_buttons_state(m_handle->last_state.Gamepad.wButtons);
}
thumb_stick_value_t controller::get_left_thumb_stick()const
{
return { (float)max(-1, m_handle->last_state.Gamepad.sThumbLX / 32767.0), (float)max(-1, m_handle->last_state.Gamepad.sThumbLY / 32767.0) };
}
thumb_stick_value_t controller::get_right_thumb_stick()const
{
return { (float)max(-1, m_handle->last_state.Gamepad.sThumbRX / 32767.0), (float)max(-1, m_handle->last_state.Gamepad.sThumbRY / 32767.0) };
}
analog_input_value_t controller::get_triggers()const
{
return { (float)m_handle->last_state.Gamepad.bRightTrigger / 255.0f, (float)m_handle->last_state.Gamepad.sThumbRY / 255.0f };
}
events::event_token_t controller::add_digital_input_event(events::event_t e)
{
return m_handle->digital_input_event += e;
}
bool controller::remove_digital_input_event(events::event_token_t token)
{
return m_handle->digital_input_event -= token;
}
events::event_token_t controller::add_analog_input_event(events::event_t e)
{
return m_handle->analog_input_event += e;
}
bool controller::remove_analog_input_event(events::event_token_t token)
{
return m_handle->analog_input_event -= token;
}
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
struct controller_manager::handle
{
stack_array<collections::pair<controller_status_t, XINPUT_STATE>, 4> m_states;
stack_array<controller_t, 4> m_controllers;
events::event_listener m_controller_connected_event;
events::event_listener m_controller_disconnected_event;
handle(controller_manager* ptr)
: m_controller_connected_event(ptr, [](events::core_msg_t msg) { return msg == (events::core_msg_t)events::core_msg::controller_status_change; })
, m_controller_disconnected_event(ptr, [](events::core_msg_t msg) { return msg == (events::core_msg_t)events::core_msg::controller_status_change; })
{
for (collections::pair<controller_status_t, XINPUT_STATE>& item : m_states)
ZeroMemory(&item.value, sizeof(XINPUT_STATE));
}
};
controller_manager::controller_manager()
: m_handle(null)
{
m_handle = new handle(this);
uint i = 0;
for (controller_t& item : m_handle->m_controllers)
item = new controller(i++);
}
controller_manager::~controller_manager()
{
delete m_handle;
m_handle = null;
}
ANG_IMPLEMENT_OBJECT_RUNTIME_INFO(ang::platform::input::controller_manager);
ANG_IMPLEMENT_OBJECT_CLASS_INFO(ang::platform::input::controller_manager, object, icontroller_manager);
ANG_IMPLEMENT_OBJECT_QUERY_INTERFACE(ang::platform::input::controller_manager, object, icontroller_manager);
icontroller_t controller_manager::get_controller(uint id)const
{
return m_handle->m_controllers[id];
}
events::event_token_t controller_manager::add_controller_connected_event(events::event_t e)
{
return m_handle->m_controller_connected_event += e;
}
bool controller_manager::remove_controller_connected_event(events::event_token_t token)
{
return m_handle->m_controller_connected_event -= token;
}
events::event_token_t controller_manager::add_controller_disconnected_event(events::event_t e)
{
return m_handle->m_controller_disconnected_event += e;
}
bool controller_manager::remove_controller_disconnected_event(events::event_token_t token)
{
return m_handle->m_controller_disconnected_event -= token;
}
array_view<const controller_t> controller_manager::get_controller_property(base_property<array_view<const controller_t>> const* prop)
{
return to_array((controller_t const*)field_to_parent(&controller_manager::contoller, prop)->m_handle->m_controllers.data(), 4);
}
events::event_token_t controller_manager::add_controller_connected_event(events::base_event* prop, events::event_t e)
{
return field_to_parent(&controller_manager::controller_connected_event, prop)->add_controller_connected_event(e);
}
bool controller_manager::remove_controller_connected_event(events::base_event* prop, events::event_token_t token)
{
return field_to_parent(&controller_manager::controller_connected_event, prop)->remove_controller_connected_event(token);
}
events::event_token_t controller_manager::add_controller_disconnected_event(events::base_event* prop, events::event_t e)
{
return field_to_parent(&controller_manager::controller_disconnected_event, prop)->add_controller_disconnected_event(e);
}
bool controller_manager::remove_controller_disconnected_event(events::base_event* prop, events::event_token_t token)
{
return field_to_parent(&controller_manager::controller_disconnected_event, prop)->remove_controller_disconnected_event(token);
}
void controller_manager::update()
{
XINPUT_STATE state;
ZeroMemory(&state, sizeof(XINPUT_STATE));
for (uint i = 0; i < 4; i++)
{
if (XInputGetState(i, &state) == ERROR_SUCCESS)
{
if (m_handle->m_states[i].key == controller_status::disconnected) {
m_handle->m_states[i].key = controller_status::connected;
m_handle->m_controllers[i]->m_handle->last_state = state;
events::icontroller_status_args_t args = new events::controller_status_args(
events::message(events::core_msg::controller_status_change),
m_handle->m_controllers[i],
m_handle->m_states[i].key);
try { m_handle->m_controller_connected_event(args.get()); }
catch (...) { }
}
else
{
}
}
else if (m_handle->m_states[i].key != controller_status::disconnected)
{
m_handle->m_states[i].key = controller_status::disconnected;
events::icontroller_status_args_t args = new events::controller_status_args(
events::message(events::core_msg::controller_status_change),
m_handle->m_controllers[i],
m_handle->m_states[i].key
);
try { m_handle->m_controller_disconnected_event(args.get()); }
catch (...) { }
}
}
}
//////////////////////////////////////////////////////////////////////////////////////// | 33.988417 | 150 | 0.767693 | [
"object"
] |
2bcb1ef0aa06a91a95a3dd876c44b8510140abc0 | 718 | cpp | C++ | Module strings/KMP (prefix).cpp | Vinatorul/AandDS | b41f628c39103d8f3a060dee1e0e839b226cb9d2 | [
"CC0-1.0"
] | 5 | 2020-03-01T19:32:00.000Z | 2020-03-07T10:55:48.000Z | Module strings/KMP (prefix).cpp | Vinatorul/AandDS | b41f628c39103d8f3a060dee1e0e839b226cb9d2 | [
"CC0-1.0"
] | null | null | null | Module strings/KMP (prefix).cpp | Vinatorul/AandDS | b41f628c39103d8f3a060dee1e0e839b226cb9d2 | [
"CC0-1.0"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<int> prefix_function(string &s) {
vector<int> P(s.size());
P[0] = 0;
for (int i = 0; i < s.size() - 1; i++) {
int j = P[i];
while (j > 0 && s[i + 1] != s[j]) {
j = P[j - 1];
}
if (s[i + 1] == s[j]) {
P[i + 1] = j + 1;
} else {
P[i + 1] = 0;
}
}
return P;
}
int main() {
string s, t;
cin >> s >> t;
string t_s = t + "&" + s;
vector<int> P = prefix_function(t_s);
for (int i = 0; i < P.size(); i++) {
if (P[i] == t.size()) {
cout << i - 2 * t.size() << ' ';
}
}
return 0;
}
| 20.514286 | 44 | 0.380223 | [
"vector"
] |
2bd314918f8f53741ad4634ba9faba832cbfba2d | 4,442 | hpp | C++ | nplus1/include/np1/rel/detail/merge_sort.hpp | AnthonyNystrom/r17 | a73f5faf07a554c9c693074192b34be834f3106c | [
"Apache-2.0"
] | 1 | 2015-11-05T21:40:47.000Z | 2015-11-05T21:40:47.000Z | nplus1/include/np1/rel/detail/merge_sort.hpp | AnthonyNystrom/r17 | a73f5faf07a554c9c693074192b34be834f3106c | [
"Apache-2.0"
] | null | null | null | nplus1/include/np1/rel/detail/merge_sort.hpp | AnthonyNystrom/r17 | a73f5faf07a554c9c693074192b34be834f3106c | [
"Apache-2.0"
] | null | null | null | // Copyright 2012 Matthew Nourse and n plus 1 computing pty limited unless otherwise noted.
// Please see LICENSE file for details.
#ifndef NP1_NP1_REL_DETAIL_MERGE_SORT_HPP
#define NP1_NP1_REL_DETAIL_MERGE_SORT_HPP
#include "np1/rel/record_ref.hpp"
#include <vector>
namespace np1 {
namespace rel {
namespace detail {
/**
* Merge sort is useful because it's stable (keeps entries in same relative
* order), reliable (cf Quicksort, which on some inputs is awful) and has
* good locality-of-reference properties. We pretend that the data is a
* linked list to avoid allocating extra space apart from that which is required
* by the linked list itself. This code based on
* http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.c by Simon
* Tatham.
*/
class merge_sort {
private:
struct list_element {
list_element() : next(0) {}
explicit list_element(const record_ref &rec) : next(0), r(rec) {}
list_element *next;
record_ref r;
};
public:
merge_sort() : m_head(0) {}
/// Add an element into the sorter's internal workings.
void insert(const record_ref &r) { m_list.push_back(list_element(r)); }
/// Sort the internally-stored list.
template <typename Less_Than>
void sort(Less_Than less_than) {
if (!fixup_list_pointers()) {
// No work to do.
return;
}
list_element *p = 0;
list_element *q = 0;
list_element *e = 0;
list_element *tail = 0;
ssize_t insize, nmerges, psize, qsize, i;
insize = 1;
while (1) {
p = m_head;
m_head = 0;
tail = 0;
nmerges = 0; /* count number of merges we do in this pass */
while (p) {
nmerges++; /* there exists a merge to be done */
/* step `insize' places along from p */
q = p;
psize = 0;
for (i = 0; i < insize; i++) {
psize++;
q = q->next;
if (!q) {
break;
}
}
/* if q hasn't fallen off end, we have two lists to merge */
qsize = insize;
/* now we have two lists; merge them */
while ((psize > 0) || (qsize > 0 && q)) {
/* decide whether next element of merge comes from p or q */
if (psize == 0) {
/* p is empty; e must come from q. */
e = q; q = q->next; qsize--;
} else if (qsize == 0 || !q) {
/* q is empty; e must come from p. */
e = p; p = p->next; psize--;
} else if (!less_than(q->r, p->r)) {
/* First element of p is lower (or same);
* e must come from p. */
e = p; p = p->next; psize--;
} else {
/* First element of q is lower; e must come from q. */
e = q; q = q->next; qsize--;
}
/* add the next element to the merged list */
if (tail) {
tail->next = e;
} else {
m_head = e;
}
tail = e;
}
/* now p has stepped `insize' places along, and q has too */
p = q;
}
tail->next = NULL;
/* If we have done only one merge, we're finished. */
if (nmerges <= 1) /* allow for nmerges==0, the empty list case */
return;
/* Otherwise repeat, merging lists twice the size */
insize *= 2;
}
}
/**
* Must ONLY be called after sort().
*/
template <typename Callback>
void walk_sorted(Callback callback) const {
const list_element *list = m_head;
while (list) {
callback(list->r);
list = list->next;
}
}
void clear() {
m_list.clear();
m_head = 0;
}
bool empty() { return m_list.empty(); }
private:
/// Disable copy.
merge_sort(const merge_sort &other);
merge_sort &operator = (const merge_sort &other);
private:
bool fixup_list_pointers() {
if (m_list.empty()) {
m_head = 0;
return false;
}
std::vector<list_element>::iterator i = m_list.begin();
std::vector<list_element>::iterator iz = m_list.end();
std::vector<list_element>::iterator next_i;
m_head = i;
while (true) {
next_i = i + 1;
if (next_i != iz) {
i->next = next_i;
} else {
return true;
}
i = next_i;
}
NP1_ASSERT(false, "Unreachable");
return false;
}
private:
list_element *m_head;
std::vector<list_element> m_list;
};
} // namespaces
}
}
#endif
| 23.88172 | 91 | 0.555155 | [
"vector"
] |
2bd59869cdf30620c4dfd68ff6344c3a3f14e4a0 | 11,124 | cxx | C++ | main/dbaccess/source/ui/browser/dsbrowserDnD.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/dbaccess/source/ui/browser/dsbrowserDnD.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/dbaccess/source/ui/browser/dsbrowserDnD.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbui.hxx"
#include "dbexchange.hxx"
#include "dbtreelistbox.hxx"
#include "dbtreemodel.hxx"
#include "dbtreeview.hxx"
#include "dbu_brw.hrc"
#include "dbustrings.hrc"
#include "QEnumTypes.hxx"
#include "UITools.hxx"
#include "unodatbr.hxx"
/** === begin UNO includes === **/
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/sdb/CommandType.hpp>
#include <com/sun/star/sdbc/XConnection.hpp>
/** === end UNO includes === **/
#include <connectivity/dbexception.hxx>
#include <connectivity/dbtools.hxx>
#include <cppuhelper/exc_hlp.hxx>
#include <svtools/treelist.hxx>
#include <svx/dataaccessdescriptor.hxx>
#include <tools/diagnose_ex.h>
#include <functional>
// .........................................................................
namespace dbaui
{
// .........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::form;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::i18n;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::datatransfer;
using namespace ::dbtools;
using namespace ::svx;
// -----------------------------------------------------------------------------
TransferableHelper* SbaTableQueryBrowser::implCopyObject( SvLBoxEntry* _pApplyTo, sal_Int32 _nCommandType, sal_Bool _bAllowConnection )
{
try
{
::rtl::OUString aName = GetEntryText( _pApplyTo );
::rtl::OUString aDSName = getDataSourceAcessor( m_pTreeView->getListBox().GetRootLevelParent( _pApplyTo ) );
ODataClipboard* pData = NULL;
SharedConnection xConnection;
if ( CommandType::QUERY != _nCommandType )
{
if ( _bAllowConnection && !ensureConnection( _pApplyTo, xConnection) )
return NULL;
pData = new ODataClipboard(aDSName, _nCommandType, aName, xConnection, getNumberFormatter(), getORB());
}
else
pData = new ODataClipboard(aDSName, _nCommandType, aName, getNumberFormatter(), getORB());
// the owner ship goes to ODataClipboards
return pData;
}
catch(const SQLException& )
{
showError( SQLExceptionInfo( ::cppu::getCaughtException() ) );
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
return NULL;
}
// -----------------------------------------------------------------------------
sal_Int8 SbaTableQueryBrowser::queryDrop( const AcceptDropEvent& _rEvt, const DataFlavorExVector& _rFlavors )
{
// check if we're a table or query container
SvLBoxEntry* pHitEntry = m_pTreeView->getListBox().GetEntry( _rEvt.maPosPixel );
if ( pHitEntry ) // no drop if no entry was hit ....
{
// it must be a container
EntryType eEntryType = getEntryType( pHitEntry );
SharedConnection xConnection;
if ( eEntryType == etTableContainer && ensureConnection( pHitEntry, xConnection ) && xConnection.is() )
{
Reference<XChild> xChild(xConnection,UNO_QUERY);
Reference<XStorable> xStore(xChild.is() ? getDataSourceOrModel(xChild->getParent()) : Reference<XInterface>(),UNO_QUERY);
// check for the concrete type
if ( xStore.is() && !xStore->isReadonly() && ::std::find_if(_rFlavors.begin(),_rFlavors.end(),TAppSupportedSotFunctor(E_TABLE,sal_True)) != _rFlavors.end())
return DND_ACTION_COPY;
}
}
return DND_ACTION_NONE;
}
// -----------------------------------------------------------------------------
sal_Int8 SbaTableQueryBrowser::executeDrop( const ExecuteDropEvent& _rEvt )
{
SvLBoxEntry* pHitEntry = m_pTreeView->getListBox().GetEntry( _rEvt.maPosPixel );
EntryType eEntryType = getEntryType( pHitEntry );
if (!isContainer(eEntryType))
{
DBG_ERROR("SbaTableQueryBrowser::executeDrop: what the hell did queryDrop do?");
// queryDrop shoud not have allowed us to reach this situation ....
return DND_ACTION_NONE;
}
// a TransferableDataHelper for accessing the dropped data
TransferableDataHelper aDroppedData(_rEvt.maDropEvent.Transferable);
// reset the data of the previous async drop (if any)
if ( m_nAsyncDrop )
Application::RemoveUserEvent(m_nAsyncDrop);
m_nAsyncDrop = 0;
m_aAsyncDrop.aDroppedData.clear();
m_aAsyncDrop.nType = E_TABLE;
m_aAsyncDrop.nAction = _rEvt.mnAction;
m_aAsyncDrop.bError = sal_False;
m_aAsyncDrop.bHtml = sal_False;
m_aAsyncDrop.pDroppedAt = NULL;
m_aAsyncDrop.aUrl = ::rtl::OUString();
// loop through the available formats and see what we can do ...
// first we have to check if it is our own format, if not we have to copy the stream :-(
if ( ODataAccessObjectTransferable::canExtractObjectDescriptor(aDroppedData.GetDataFlavorExVector()) )
{
m_aAsyncDrop.aDroppedData = ODataAccessObjectTransferable::extractObjectDescriptor(aDroppedData);
m_aAsyncDrop.pDroppedAt = pHitEntry;
// asyncron because we some dialogs and we aren't allowed to show them while in D&D
m_nAsyncDrop = Application::PostUserEvent(LINK(this, SbaTableQueryBrowser, OnAsyncDrop));
return DND_ACTION_COPY;
}
else
{
SharedConnection xDestConnection;
if ( ensureConnection( pHitEntry, xDestConnection )
&& xDestConnection.is()
&& m_aTableCopyHelper.copyTagTable( aDroppedData, m_aAsyncDrop, xDestConnection )
)
{
m_aAsyncDrop.pDroppedAt = pHitEntry;
// asyncron because we some dialogs and we aren't allowed to show them while in D&D
m_nAsyncDrop = Application::PostUserEvent(LINK(this, SbaTableQueryBrowser, OnAsyncDrop));
return DND_ACTION_COPY;
}
}
return DND_ACTION_NONE;
}
// -----------------------------------------------------------------------------
sal_Bool SbaTableQueryBrowser::requestDrag( sal_Int8 /*_nAction*/, const Point& _rPosPixel )
{
// get the affected list entry
// ensure that the entry which the user clicked at is selected
SvLBoxEntry* pHitEntry = m_pTreeView->getListBox().GetEntry( _rPosPixel );
if (!pHitEntry)
// no drag of no entry was hit ....
return sal_False;
// it must be a query/table
EntryType eEntryType = getEntryType( pHitEntry );
if (!isObject(eEntryType))
return DND_ACTION_NONE;
TransferableHelper* pTransfer = implCopyObject( pHitEntry, ( etTableOrView == eEntryType ) ? CommandType::TABLE : CommandType::QUERY);
Reference< XTransferable> xEnsureDelete = pTransfer;
if (pTransfer)
pTransfer->StartDrag( &m_pTreeView->getListBox(), DND_ACTION_COPY );
return NULL != pTransfer;
}
// -----------------------------------------------------------------------------
IMPL_LINK(SbaTableQueryBrowser, OnCopyEntry, void*, /*NOTINTERESIN*/)
{
SvLBoxEntry* pSelected = m_pTreeView->getListBox().FirstSelected();
if( isEntryCopyAllowed( pSelected ) )
copyEntry( pSelected );
return 0;
}
// -----------------------------------------------------------------------------
sal_Bool SbaTableQueryBrowser::isEntryCopyAllowed(SvLBoxEntry* _pEntry) const
{
EntryType eType = getEntryType(_pEntry);
return ( eType == etTableOrView || eType == etQuery );
}
// -----------------------------------------------------------------------------
void SbaTableQueryBrowser::copyEntry(SvLBoxEntry* _pEntry)
{
TransferableHelper* pTransfer = NULL;
Reference< XTransferable> aEnsureDelete;
EntryType eType = getEntryType(_pEntry);
pTransfer = implCopyObject( _pEntry, eType == etQuery ? CommandType::QUERY : CommandType::TABLE);
aEnsureDelete = pTransfer;
if (pTransfer)
pTransfer->CopyToClipboard(getView());
}
// -----------------------------------------------------------------------------
IMPL_LINK( SbaTableQueryBrowser, OnAsyncDrop, void*, /*NOTINTERESTEDIN*/ )
{
m_nAsyncDrop = 0;
::vos::OGuard aSolarGuard( Application::GetSolarMutex() );
::osl::MutexGuard aGuard( getMutex() );
if ( m_aAsyncDrop.nType == E_TABLE )
{
SharedConnection xDestConnection;
if ( ensureConnection( m_aAsyncDrop.pDroppedAt, xDestConnection ) && xDestConnection.is() )
{
SvLBoxEntry* pDataSourceEntry = m_pTreeView->getListBox().GetRootLevelParent(m_aAsyncDrop.pDroppedAt);
m_aTableCopyHelper.asyncCopyTagTable( m_aAsyncDrop, getDataSourceAcessor( pDataSourceEntry ), xDestConnection );
}
}
m_aAsyncDrop.aDroppedData.clear();
return 0L;
}
// -----------------------------------------------------------------------------
void SbaTableQueryBrowser::clearTreeModel()
{
if (m_pTreeModel)
{
// clear the user data of the tree model
SvLBoxEntry* pEntryLoop = m_pTreeModel->First();
while (pEntryLoop)
{
DBTreeListUserData* pData = static_cast<DBTreeListUserData*>(pEntryLoop->GetUserData());
if(pData)
{
pEntryLoop->SetUserData(NULL);
Reference< XContainer > xContainer(pData->xContainer, UNO_QUERY);
if (xContainer.is())
xContainer->removeContainerListener(this);
if ( pData->xConnection.is() )
{
DBG_ASSERT( impl_isDataSourceEntry( pEntryLoop ), "SbaTableQueryBrowser::clearTreeModel: no data source entry, but a connection?" );
// connections are to be stored *only* at the data source entries
impl_releaseConnection( pData->xConnection );
}
delete pData;
}
pEntryLoop = m_pTreeModel->Next(pEntryLoop);
}
}
m_pCurrentlyDisplayed = NULL;
}
// .........................................................................
} // namespace dbaui
// .........................................................................
| 38.09589 | 160 | 0.625315 | [
"model"
] |
2bd5fef4f5758bbceed65fe7d51125c8272f9a7e | 3,832 | hh | C++ | src/tagger/TrellisColumn.hh | Traubert/FinnPos | 8a5184237a854e60e422bf3e5ef1de7b04bf962e | [
"Apache-2.0"
] | 36 | 2015-05-09T14:30:58.000Z | 2021-04-20T11:24:01.000Z | src/tagger/TrellisColumn.hh | Traubert/FinnPos | 8a5184237a854e60e422bf3e5ef1de7b04bf962e | [
"Apache-2.0"
] | 4 | 2016-04-19T20:27:21.000Z | 2020-03-09T09:07:45.000Z | src/tagger/TrellisColumn.hh | Traubert/FinnPos | 8a5184237a854e60e422bf3e5ef1de7b04bf962e | [
"Apache-2.0"
] | 10 | 2015-05-16T13:16:31.000Z | 2020-06-15T00:12:06.000Z | /**
* @file TrellisColumn.hh
* @Author Miikka Silfverberg
* @brief Class for representing the columns of a Trellis.
*/
///////////////////////////////////////////////////////////////////////////////
// //
// (C) Copyright 2014, University of Helsinki //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// http://www.apache.org/licenses/LICENSE-2.0 //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// //
///////////////////////////////////////////////////////////////////////////////
#ifndef HEADER_TrellisColumn_hh
#define HEADER_TrellisColumn_hh
#include <vector>
#include "ParamTable.hh"
#include "Word.hh"
#include "TrellisCell.hh"
#include "exceptions.hh"
#include "TaggerOptions.hh"
float expsumlog(float x, float y);
class TrellisColumn
{
public:
TrellisColumn(unsigned int boundary_label,
unsigned int beam_width = -1,
Degree sublabel_order = SECOND,
Degree model_order = SECOND);
void set_ncol(TrellisColumn * pcol);
void set_word(const Word &word, int plabels);
void compute_fw(const ParamTable &pt);
void compute_bw(const ParamTable &pt);
void compute_viterbi(const ParamTable &pt);
float get_fw(unsigned int plabel_index,
unsigned int label_index) const;
float get_bw(unsigned int plabel_index,
unsigned int label_index) const;
float get_viterbi(unsigned int plabel_index,
unsigned int label_index) const;
unsigned int get_label_count(void) const;
void set_labels(LabelVector &res);
TrellisCell &get_cell(unsigned int plabel_index,
unsigned int label_index);
const TrellisCell &get_cell(unsigned int plabel_index,
unsigned int label_index) const;
void set_beam_mass(float mass);
void set_beam(unsigned int beam);
private:
TrellisColumn * pcol;
TrellisColumn * ncol;
const Word * word;
unsigned int boundary_label;
unsigned int beam_width;
bool use_adaptive_beam;
float beam_mass;
unsigned int label_count;
unsigned int plabel_count;
Degree sublabel_order;
Degree model_order;
std::vector<TrellisCell> cells;
std::vector<TrellisCell*> cells_in_beam;
TrellisCell * get_beam_cell(unsigned int i);
unsigned int beam_cell_count(void);
void reserve(unsigned int label_count);
unsigned int get_label(unsigned int label_index) const;
unsigned int get_plabel(unsigned int plabel_index) const;
unsigned int get_pplabel(unsigned int pplabel_index) const;
unsigned int get_nlabel(unsigned int nlabel_index) const;
float get_emission_score(const ParamTable &pt,
unsigned int label_index) const;
float get_transition_bw_score(const ParamTable &pt,
unsigned int plabel_index,
unsigned int label_index) const;
float get_transition_fw_score(const ParamTable &pt,
unsigned int label_index,
unsigned int plabel_index) const;
void set_viterbi_tr_score(const ParamTable &pt,
unsigned int plabel_index,
unsigned int label_index);
};
#endif // HEADER_TrellisColumn_hh
| 31.933333 | 79 | 0.62761 | [
"vector"
] |
2bde1929147afbdbe414afb40c1a040fe7bac2d4 | 6,794 | cpp | C++ | Tracking/Viterbi/ViterbiTrackLinking.cpp | klezm/BaxterAlgorithms | fafcd6a7a14c95edf815098fde7588e1ee2c5eda | [
"MIT"
] | null | null | null | Tracking/Viterbi/ViterbiTrackLinking.cpp | klezm/BaxterAlgorithms | fafcd6a7a14c95edf815098fde7588e1ee2c5eda | [
"MIT"
] | null | null | null | Tracking/Viterbi/ViterbiTrackLinking.cpp | klezm/BaxterAlgorithms | fafcd6a7a14c95edf815098fde7588e1ee2c5eda | [
"MIT"
] | null | null | null | // Create the precompiler definition MATLAB in to compile mex file. Otherwise a standalone executable for for debugging will be generated.
#include "ArraySave.h"
#include "CellTrellis.h"
#include "LogStream.h"
#include "Tree.h"
#include <string>
#include <sstream>
// Matlab types and functions.
#include "mex.h"
#include "matrix.h"
using namespace std;
/* Function that interfaces with Matlab. "/" is used instead of "\" in path
* names as "\" does not work on mac and linux. Windows does not care.
*
* Inputs:
* int nrhs - Number of inputs.
* mxArray *prhs[0] - Array with detection counts per frame.
* mxArray *prhs[1] - Count events.
* mxArray *prhs[2] - Migration events.
* mxArray *prhs[3] - Mitosis events.
* mxArray *prhs[4] - Apoptosis events.
* mxArray *prhs[5] - Appearance events.
* mxArray *prhs[6] - Disappearnace events.
* mxArray *prhs[7] - If this is != 0, there will be a single idle state in the
* trellis instead of one for appearing and one for disappearing
* cells.
* mxArray *prhs[8] - Maximum score increase for a migration.
* mxArray *prhs[9] - Path where intermediate results can be saved as binary
* files. It it left empty, no intermediate files are saved.
* mxArray *prhs[10] - Folder to save intermediate results to.
*
* Outputs:
* int nlhs - Number of outputs
* mxArray *plhs[0] - Detection numbers for all cells
* mxArray *plhs[1] - Mitosis relationships between cells.
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
// Check the number of input and output arguments
if (nrhs != 11) {
mexErrMsgTxt("Must have 11 input arguments");
}
if (nlhs != 3) {
mexErrMsgTxt("Must have 2 output arguments");
}
lout << "Running ViterbiTrackLinking from Matlab." << endl << endl;
// Get inputs
double *numDetsA = mxGetPr(prhs[0]);
double *countA = mxGetPr(prhs[1]);
double *migA = mxGetPr(prhs[2]);
double *mitA = mxGetPr(prhs[3]);
double *apoA = mxGetPr(prhs[4]);
double *appearA = mxGetPr(prhs[5]);
double *disappearA = mxGetPr(prhs[6]);
bool singleIdleState = (*mxGetPr(prhs[7]) != 0);
double maxMigScore = *mxGetPr(prhs[8]);
char iterationPath[1000];
mxGetString(prhs[9], iterationPath, 1000);
bool saveIterationFiles = mxGetNumberOfElements(prhs[9]) > 0;
char logFilePath[1000];
mxGetString(prhs[10], logFilePath, 1000);
bool saveLogFile = mxGetNumberOfElements(prhs[10]) > 0;
// Get the dimensions of the inputs.
const int *countSize = (int*) mxGetDimensions(prhs[1]);
const int *migSize = (int*) mxGetDimensions(prhs[2]);
const int *mitSize = (int*) mxGetDimensions(prhs[3]);
const int *apoSize = (int*) mxGetDimensions(prhs[4]);
const int *appearSize = (int*) mxGetDimensions(prhs[5]);
const int *disappearSize = (int*) mxGetDimensions(prhs[6]);
int tMax = (int) mxGetNumberOfElements(prhs[0]); // Allow numDetsA to be either row or column vector.
int maxCount = countSize[1]-3; // first element is t, second is detection index and the third is the debris probability
int numMigs = migSize[0];
int numMits = mitSize[0];
int numApos = apoSize[0];
int numAppear = appearSize[0];
int numDisappear = disappearSize[0];
if (saveLogFile) {
lout.OpenFile(logFilePath);
}
// Create a trellis graph that will be used to solve the tracknig problem.
CellTrellis cellTrellis(singleIdleState, tMax, maxCount, numMigs, numMits, numApos, numAppear, numDisappear,
numDetsA, countA, migA, mitA, apoA, appearA, disappearA, maxMigScore);
// Add cells iteratively until as long as the score increases.
int iter = 1;
int addedCells = 0;
Tree *tree = cellTrellis.GetTree();
while (true) {
tree->SetIteration(iter);
lout << "Iteration " << iter << endl;
addedCells = cellTrellis.AddCell();
// No modifications were made in the last iteration.
if (addedCells == 0) {
break;
}
if (saveIterationFiles) {
// Save tracking matrices after each iterations, so that the algorithm steps
// can be looked at later.
double *cellArray = new double[tMax*tree->GetNumCells()];
double *divArray = new double[tree->GetNumCells()*2];
double *deathArray = new double[tree->GetNumCells()];
tree->GetCells(cellArray, divArray, deathArray);
// Detection indices.
int cellArrayDims[2];
cellArrayDims[0] = tMax;
cellArrayDims[1] = tree->GetNumCells();
stringstream cellArrayPath;
cellArrayPath << iterationPath << "/cellArray" << setw(5) << setfill('0') << iter << ".bin";
// Cell divisions.
int divArrayDims[2];
divArrayDims[0] = tree->GetNumCells();
divArrayDims[1] = 2;
stringstream divArrayPath;
divArrayPath << iterationPath << "/divArray" << setw(5) << setfill('0') << iter << ".bin";
// Cell deaths.
int deathArrayDims[2];
deathArrayDims[0] = tree->GetNumCells();
deathArrayDims[1] = 1;
stringstream deathArrayPath;
deathArrayPath << iterationPath << "/deathArray" << setw(5) << setfill('0') << iter << ".bin";
// Iterations when the cells were created.
double *iterArray = new double[tMax*tree->GetNumCells()];
tree->GetIterations(iterArray);
int iterArrayDims[2];
iterArrayDims[0] = tMax;
iterArrayDims[1] = tree->GetNumCells();
stringstream iterArrayPath;
iterArrayPath << iterationPath << "/iterationArray" << setw(5) << setfill('0') << iter << ".bin";
ArraySave::Save<double>(2, cellArrayDims, cellArray, cellArrayPath.str().c_str());
ArraySave::Save<double>(2, divArrayDims, divArray, divArrayPath.str().c_str());
ArraySave::Save<double>(2, deathArrayDims, deathArray, deathArrayPath.str().c_str());
ArraySave::Save<double>(2, iterArrayDims, iterArray, iterArrayPath.str().c_str());
delete[] cellArray;
delete[] divArray;
delete[] deathArray;
delete[] iterArray;
}
iter++;
}
tree->Print();
lout << endl; // Empty line after all outputs.
// Output.
plhs[0] = mxCreateDoubleMatrix(tMax, tree->GetNumCells(), mxREAL);
plhs[1] = mxCreateDoubleMatrix(tree->GetNumCells(), 2, mxREAL);
plhs[2] = mxCreateDoubleMatrix(tree->GetNumCells(), 1, mxREAL);
double *cellA = mxGetPr(plhs[0]);
double *divA = mxGetPr(plhs[1]);
double *deathA = mxGetPr(plhs[2]);
tree->GetCells(cellA, divA, deathA);
if (saveLogFile) {
lout.CloseFile();
}
return;
} | 37.955307 | 138 | 0.634678 | [
"vector"
] |
2bec19900ffec3c83cdb1419c9e66413eb0cfa6c | 716 | cpp | C++ | online_judges/atcoder/contests/abc203/c/c.cpp | miaortizma/competitive-programming | ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc | [
"MIT"
] | 2 | 2018-02-20T14:44:57.000Z | 2018-02-20T14:45:03.000Z | online_judges/atcoder/contests/abc203/c/c.cpp | miaortizma/competitive-programming | ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc | [
"MIT"
] | null | null | null | online_judges/atcoder/contests/abc203/c/c.cpp | miaortizma/competitive-programming | ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc | [
"MIT"
] | null | null | null | /* Generated by powerful Codeforces Tool
* You can download the binary file in here https://github.com/xalanq/cf-tool (Windows, macOS, Linux)
* Author: mia_ortizma
* Time: 2021-05-30 07:07:36
**/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main()
{
cin.tie(0), cout.sync_with_stdio(0);
ll N, K;
cin >> N >> K;
vector<pll> friends(N);
ll A, B;
for (int i = 0; i < N; ++i) {
cin >> A >> B;
friends[i] = { A, B };
}
sort(friends.begin(), friends.end());
ll cur = K;
for (auto& [a, b] : friends) {
if (a <= cur) {
cur += b;
}
else {
break;
}
}
cout << cur;
return 0;
}
| 18.358974 | 101 | 0.562849 | [
"vector"
] |
2bec6bd671d435b9cedaae4e422ea6f17e9fef49 | 2,882 | cpp | C++ | FHC/2020_qual/A.cpp | igarash1/Competitive-Programming | ec118931d658492ae22f778dcd3800c70e0b1c4e | [
"MIT"
] | null | null | null | FHC/2020_qual/A.cpp | igarash1/Competitive-Programming | ec118931d658492ae22f778dcd3800c70e0b1c4e | [
"MIT"
] | null | null | null | FHC/2020_qual/A.cpp | igarash1/Competitive-Programming | ec118931d658492ae22f778dcd3800c70e0b1c4e | [
"MIT"
] | null | null | null | //
// Created by Koki Igarashi on 7/26/20.
//
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
typedef int Int;
typedef pair<Int,Int> pii;
typedef pair<Int,double> pid;
typedef pair<double,double> pdd;
typedef pair<Int,pii> pip;
typedef pair<double,Int> pdp;
typedef vector<Int> veci;
typedef vector<double> vecd;
typedef vector<int> veci;
typedef vector<ll> vecll;
typedef vector<double> vecd;
typedef vector<pii> vecpii;
typedef vector<veci> mati;
typedef vector<vecd> matd;
#define A first
#define B second
#define PB(x) push_back(x)
#define EB(x) emplace_back(x)
#define ALL(x) x.begin(),x.end()
#define SZ(x) (x).size()
#define CLR(x) memset(x,0,sizeof x)
#define pdebug() printf("%d\n",__LINE__)
#define REP(i,a,b) for(int i = (a);i <= (b);i++)
#define FORO(i,n) REP(i,0,(int)n-1)
#define FORI(i,n) REP(i,1,(int)n)
#define FORIT(i,t) for(auto i = t.begin();i != t.end();i++)
#define eps 1e-6
#define sqr(x) ((x)*(x))
#define dist(_a,_b) sqrt(sqr(_a.A-_b.A)+sqr(_a.B-_b.B))
#define norm(_a) sqrt(sqr(_a.A)+sqr(_a.B))
template<typename T>void getMin(T &a,T b) { if(a > b) a = b; }
template<typename T>void getMax(T &a,T b) { if(a < b) a = b; }
template<typename T> vector<T> getVector(const int n) { return vector<T>(n); }
template<typename T> vector<T> getVector(const int n, const T a) { return vector<T>(n, a); }
template<typename T> vector<T> getEmptyVector() { return vector<T>(); }
template<typename T> void appendAll(vector<T> &a, vector<T> b) { a.insert(a.end(), b.begin(), b.end()); }
// #define X first
// #define Y second
const int dx[4] = {1, -1, 0, 0};
const int dy[4] = {0, 0, 1, -1};
const ll MOD = 1000000007;
const int MAXN = 1<<17;
const int inf = 1<<28;
const int NIL = -inf;
int popcount(int x) { return __builtin_popcount(x); }
#define DUMP(a) do { std::cout << #a " = " << (a) << ", "; } while(false)
#define DUMPLN(a) do { std::cout << #a " = " << (a) << std::endl; } while(false)
int N;
string I, O;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int T;
cin >> T;
FORI(t, T) {
cin >> N;
cin >> I >> O;
solve();
cout << "Case #" << t << ":\n";
FORO(i, N) {
string ans(N, 'N');
FORO(j, N) {
if(i == j) {
ans[j] = 'Y';
}
if(I[j] != 'N' && j > 0 && ans[j - 1] == 'Y' && O[j - 1] == 'Y') {
ans[j] = 'Y';
continue;
}
}
for(int j = N - 2;j >= 0;j--) {
if(i == j) {
ans[j] = 'Y';
}
if(I[j] != 'N' && ans[j + 1] == 'Y' && O[j + 1] == 'Y') {
ans[j] = 'Y';
continue;
}
}
cout << ans << endl;
}
}
return 0;
} | 30.659574 | 105 | 0.519778 | [
"vector"
] |
2bf33494d540100285dac0721ba77d3555394051 | 3,678 | cpp | C++ | DearPyGui/src/core/AppItems/plots/mvLabelSeries.cpp | NamWoo/DearPyGui | da4a3c7a0dbb3d5dfd8b0a7991521890ddd3e513 | [
"MIT"
] | null | null | null | DearPyGui/src/core/AppItems/plots/mvLabelSeries.cpp | NamWoo/DearPyGui | da4a3c7a0dbb3d5dfd8b0a7991521890ddd3e513 | [
"MIT"
] | null | null | null | DearPyGui/src/core/AppItems/plots/mvLabelSeries.cpp | NamWoo/DearPyGui | da4a3c7a0dbb3d5dfd8b0a7991521890ddd3e513 | [
"MIT"
] | null | null | null | #include <utility>
#include "mvLabelSeries.h"
#include "mvCore.h"
#include "mvApp.h"
#include "mvItemRegistry.h"
#include "mvImPlotThemeScope.h"
namespace Marvel {
void mvLabelSeries::InsertParser(std::map<std::string, mvPythonParser>* parsers)
{
mvPythonParser parser(mvPyDataType::String, "Undocumented function", { "Plotting", "Widgets" });
mvAppItem::AddCommonArgs(parser);
parser.removeArg("width");
parser.removeArg("height");
parser.removeArg("callback");
parser.removeArg("callback_data");
parser.removeArg("enabled");
parser.addArg<mvPyDataType::Double>("x");
parser.addArg<mvPyDataType::Double>("y");
parser.addArg<mvPyDataType::Integer>("x_offset", mvArgType::KEYWORD_ARG);
parser.addArg<mvPyDataType::Integer>("y_offset", mvArgType::KEYWORD_ARG);
parser.addArg<mvPyDataType::Integer>("axis", mvArgType::KEYWORD_ARG, "0");
parser.addArg<mvPyDataType::Bool>("contribute_to_bounds", mvArgType::KEYWORD_ARG, "True");
parser.addArg<mvPyDataType::Bool>("vertical", mvArgType::KEYWORD_ARG, "False");
parser.finalize();
parsers->insert({ s_command, parser });
}
mvLabelSeries::mvLabelSeries(const std::string& name)
: mvSeriesBase(name)
{
}
void mvLabelSeries::draw(ImDrawList* drawlist, float x, float y)
{
ScopedID id;
mvImPlotThemeScope scope(this);
switch (m_axis)
{
case ImPlotYAxis_1:
ImPlot::SetPlotYAxis(ImPlotYAxis_1);
break;
case ImPlotYAxis_2:
ImPlot::SetPlotYAxis(ImPlotYAxis_2);
break;
case ImPlotYAxis_3:
ImPlot::SetPlotYAxis(ImPlotYAxis_3);
break;
default:
break;
}
static const std::vector<double>* xptr;
static const std::vector<double>* yptr;
xptr = &(*m_value.get())[0];
yptr = &(*m_value.get())[1];
ImPlot::PlotText(m_label.c_str(), (*xptr)[0], (*yptr)[0], m_vertical,
ImVec2((float)m_xoffset, (float)m_yoffset));
}
void mvLabelSeries::handleSpecificRequiredArgs(PyObject* dict)
{
if (!mvApp::GetApp()->getParsers()[s_command].verifyRequiredArguments(dict))
return;
for (int i = 0; i < PyTuple_Size(dict); i++)
{
PyObject* item = PyTuple_GetItem(dict, i);
switch (i)
{
case 0:
(*m_value)[0] = ToDoubleVect(item);
break;
case 1:
(*m_value)[1] = ToDoubleVect(item);
break;
default:
break;
}
}
resetMaxMins();
calculateMaxMins();
}
void mvLabelSeries::handleSpecificKeywordArgs(PyObject* dict)
{
if (dict == nullptr)
return;
if (PyObject* item = PyDict_GetItemString(dict, "axis")) m_axis = (ImPlotYAxis_)ToInt(item);
if (PyObject* item = PyDict_GetItemString(dict, "contribute_to_bounds")) m_contributeToBounds = ToBool(item);
if (PyObject* item = PyDict_GetItemString(dict, "vertical")) m_vertical = ToBool(item);
if (PyObject* item = PyDict_GetItemString(dict, "x_offset")) m_xoffset = ToInt(item);
if (PyObject* item = PyDict_GetItemString(dict, "y_offset")) m_yoffset = ToInt(item);
bool valueChanged = false;
if (PyObject* item = PyDict_GetItemString(dict, "x")) { valueChanged = true; (*m_value)[0] = ToDoubleVect(item); }
if (PyObject* item = PyDict_GetItemString(dict, "y")) { valueChanged = true; (*m_value)[1] = ToDoubleVect(item); }
if (valueChanged)
{
resetMaxMins();
calculateMaxMins();
}
}
void mvLabelSeries::getSpecificConfiguration(PyObject* dict)
{
if (dict == nullptr)
return;
PyDict_SetItemString(dict, "axis", ToPyInt(m_axis));
PyDict_SetItemString(dict, "contribute_to_bounds", ToPyBool(m_contributeToBounds));
PyDict_SetItemString(dict, "vertical", ToPyBool(m_vertical));
PyDict_SetItemString(dict, "x_offset", ToPyInt(m_xoffset));
PyDict_SetItemString(dict, "y_offset", ToPyInt(m_yoffset));
}
} | 27.044118 | 116 | 0.7031 | [
"vector"
] |
2bf5005150cc21dbe1d40cba67a179616c2523c8 | 21,378 | cpp | C++ | src/chainparams.cpp | Real-E-Coin/REC | 148063bd6afe431c565f3ae3e75f010b11b3d4e8 | [
"MIT"
] | 1 | 2021-12-30T23:58:45.000Z | 2021-12-30T23:58:45.000Z | src/chainparams.cpp | Real-E-Coin/REC | 148063bd6afe431c565f3ae3e75f010b11b3d4e8 | [
"MIT"
] | null | null | null | src/chainparams.cpp | Real-E-Coin/REC | 148063bd6afe431c565f3ae3e75f010b11b3d4e8 | [
"MIT"
] | 1 | 2022-01-10T22:13:20.000Z | 2022-01-10T22:13:20.000Z | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2020 The PIVX developers
// Copyright (c) 2021 The Real E Coin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "chainparamsseeds.h"
#include "consensus/merkle.h"
#include "util.h"
#include "utilstrencodings.h"
#include <boost/assign/list_of.hpp>
#include <assert.h>
static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
CMutableTransaction txNew;
txNew.nVersion = 1;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = genesisReward;
txNew.vout[0].scriptPubKey = genesisOutputScript;
CBlock genesis;
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock.SetNull();
genesis.nVersion = nVersion;
genesis.nTime = nTime;
genesis.nBits = nBits;
genesis.nNonce = nNonce;
genesis.hashMerkleRoot = BlockMerkleRoot(genesis);
return genesis;
}
/**
* Build the genesis block. Note that the output of the genesis coinbase cannot
* be spent as it did not originally exist in the database.
*
* CBlock(hash=00000ffd590b14, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=e0028e, nTime=1390095618, nBits=1e0ffff0, nNonce=28917698, vtx=1)
* CTransaction(hash=e0028e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
* CTxIn(COutPoint(000000, -1), coinbase 04ffff001d01044c5957697265642030392f4a616e2f3230313420546865204772616e64204578706572696d656e7420476f6573204c6976653a204f76657273746f636b2e636f6d204973204e6f7720416363657074696e6720426974636f696e73)
* CTxOut(nValue=50.00000000, scriptPubKey=0xA9037BAC7050C479B121CF)
* vMerkleTree: e0028e
*/
static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
const char* pszTimestamp = "US Federal Reserve Looking to Hire a Manager to Research Stablecoins and CBDCs";
const CScript genesisOutputScript = CScript() << ParseHex("04f5b8143f86ad8ac63791fbbdb8f0b91a6da87c8c693a95f6c2a16c063ea796a7960b8029a904767bc671d5cfe716a2dd2e13b86182e1064a0eea7bf863636363") << OP_CHECKSIG;
return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward);
}
/**
* Main network
*/
/**
* What makes a good checkpoint block?
* + Is surrounded by blocks with reasonable timestamps
* (no blocks before with a timestamp after, none after with
* timestamp before)
* + Contains no strange transactions
*/
static Checkpoints::MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
(0, uint256("0x000006de50d3f5fd8dd4153d21cc2ec49f463639bd547ce69f61e0162b33fc5c"))
(287, uint256("0x00000023df79204da4287e7265263dd02b5c79dac30ffdda3dda28101ee86d6d"))
(1164, uint256("0x0000002a7cf0e7a9ca51591d0606aae9f29dc1a99b3d831857f2541dc93f6b93"))
(2593, uint256("0x7d34f237da67a782aa1022118198038ca99529557cbace9447da6f688ec7f966"))
(8137, uint256("0x86b96be517534a928247a04a1fad1ba16b14c2143a3b4d1e92ee98ff77dba4ea"))
(11106, uint256("0x43cb6894b7cdfb6786cf31b20e45f2e176053d6ad6132fb15b8b9c40eaec0ab1"))
(20687, uint256("0xa60ebe9e24188b585ef7a7337aa968253eab27746d3eb5449babbeaa31a48f70"))
;
static const Checkpoints::CCheckpointData data = {
&mapCheckpoints,
1614926475, // * UNIX timestamp of last checkpoint block
40205, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the UpdateTip debug.log lines)
720 // * estimated number of transactions per day after checkpoint
};
static Checkpoints::MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
(0, uint256S("0x001"));
static const Checkpoints::CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1591225230,
3501914,
3000 };
static Checkpoints::MapCheckpoints mapCheckpointsRegtest =
boost::assign::map_list_of(0, uint256S("0x001"));
static const Checkpoints::CCheckpointData dataRegtest = {
&mapCheckpointsRegtest,
1454124731,
0,
100 };
class CMainParams : public CChainParams
{
public:
CMainParams()
{
networkID = CBaseChainParams::MAIN;
strNetworkID = "main";
genesis = CreateGenesisBlock(1611990000, 1710090, 0x1e0ffff0, 1, 0);
consensus.hashGenesisBlock = genesis.GetHash();
assert(consensus.hashGenesisBlock == uint256S("000006de50d3f5fd8dd4153d21cc2ec49f463639bd547ce69f61e0162b33fc5c"));
assert(genesis.hashMerkleRoot == uint256S("d348fed0a50b7c3beb953506ad82a9d880c7a95d496bddac5775ba6ebd8c66b2"));
consensus.fPowAllowMinDifficultyBlocks = false;
consensus.powLimit = ~UINT256_ZERO >> 20; // Real_E_Coin starting difficulty is 1 / 2^12
consensus.posLimitV1 = ~UINT256_ZERO >> 24;
consensus.posLimitV2 = ~UINT256_ZERO >> 20;
consensus.nBudgetCycleBlocks = 9999999; // approx. 1 every 30 days
consensus.nBudgetFeeConfirmations = 6; // Number of confirmations for the finalization fee
consensus.nCoinbaseMaturity = 60;
consensus.nFutureTimeDriftPoW = 7200;
consensus.nFutureTimeDriftPoS = 180;
consensus.nMasternodeCountDrift = 20; // num of MN we allow the see-saw payments to be off by
consensus.nMaxMoneyOut = 100000000000 * COIN;
consensus.nPoolMaxTransactions = 3;
consensus.nProposalEstablishmentTime = 60 * 60 * 24; // must be at least a day old to make it into a budget
consensus.nStakeMinAge = 60 * 60;
consensus.nStakeMinDepth = 60;
consensus.nTargetTimespan = 40 * 60;
consensus.nTargetTimespanV2 = 30 * 60;
consensus.nTargetSpacing = 2 * 60;
consensus.nTimeSlotLength = 15;
// spork keys
consensus.strSporkPubKey = "047d2d7950788fa3c9ea01d65d799634c6a667d45fbc4cb827a1065328c804ade13c8457bdcadeae8d7d2c42a1664ca5805c4518f4f588a1e65ae65b4add323fc3";
consensus.strSporkPubKeyOld = "047d2d7950788fa3c9ea01d65d799634c6a667d45fbc4cb827a1065328c804ade13c8457bdcadeae8d7d2c42a1664ca5805c4518f4f588a1e65ae65b4add323fc3";
consensus.nTime_EnforceNewSporkKey = 1599195600; //!> Friday, 4 September 2020 5:00:00 AM GMT
consensus.nTime_RejectOldSporkKey = 1599285600; //!> Saturday, 5 September 2020 6:00:00 AM GMT
// Network upgrades
consensus.vUpgrades[Consensus::BASE_NETWORK].nActivationHeight =
Consensus::NetworkUpgrade::ALWAYS_ACTIVE;
consensus.vUpgrades[Consensus::UPGRADE_TESTDUMMY].nActivationHeight =
Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT;
consensus.vUpgrades[Consensus::UPGRADE_POS].nActivationHeight = 1601;
consensus.vUpgrades[Consensus::UPGRADE_POS_V2].nActivationHeight = 1;
consensus.vUpgrades[Consensus::UPGRADE_BIP65].nActivationHeight = 1900;
consensus.vUpgrades[Consensus::UPGRADE_V3_4].nActivationHeight = 1601;
consensus.vUpgrades[Consensus::UPGRADE_V4_0].nActivationHeight = 1700;
consensus.vUpgrades[Consensus::UPGRADE_V5_DUMMY].nActivationHeight =
Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT;
consensus.vUpgrades[Consensus::UPGRADE_BIP65].hashActivationBlock =
uint256S("0x");
consensus.vUpgrades[Consensus::UPGRADE_V3_4].hashActivationBlock =
uint256S("0x");
consensus.vUpgrades[Consensus::UPGRADE_V4_0].hashActivationBlock =
uint256S("0x");
/**
* The message start string is designed to be unlikely to occur in normal data.
* The characters are rarely used upper ASCII, not valid as UTF-8, and produce
* a large 4-byte int at any alignment.
*/
pchMessageStart[0] = 0xcb;
pchMessageStart[1] = 0x1c;
pchMessageStart[2] = 0xb7;
pchMessageStart[3] = 0xd2;
nDefaultPort = 2620;
// Note that of those with the service bits flag, most only support a subset of possible options
vSeeds.push_back(CDNSSeedData("92.222.109.154", "92.222.109.154", true));
vSeeds.push_back(CDNSSeedData("2001:41d0:8:3cca::54", "2001:41d0:8:3cca::54", true));
vSeeds.push_back(CDNSSeedData("92.222.109.155", "92.222.109.155", true));
vSeeds.push_back(CDNSSeedData("2001:41d0:8:3cca::55", "2001:41d0:8:3cca::55", true));
vSeeds.push_back(CDNSSeedData("92.222.109.144", "92.222.109.144", true));
vSeeds.push_back(CDNSSeedData("2001:41d0:8:3cca::44", "2001:41d0:8:3cca::44", true));
vSeeds.push_back(CDNSSeedData("92.222.109.145", "92.222.109.145", true));
vSeeds.push_back(CDNSSeedData("2001:41d0:8:3cca::45", "2001:41d0:8:3cca::45", true));
vSeeds.push_back(CDNSSeedData("92.222.109.146", "92.222.109.146", true));
vSeeds.push_back(CDNSSeedData("2001:41d0:8:3cca::46", "2001:41d0:8:3cca::46", true));
vSeeds.push_back(CDNSSeedData("92.222.109.147", "92.222.109.147", true));
vSeeds.push_back(CDNSSeedData("2001:41d0:8:3cca::47", "2001:41d0:8:3cca::47", true));
vSeeds.push_back(CDNSSeedData("92.222.109.148", "92.222.109.148", true));
vSeeds.push_back(CDNSSeedData("2001:41d0:8:3cca::48", "2001:41d0:8:3cca::48", true));
vSeeds.push_back(CDNSSeedData("92.222.109.149", "92.222.109.149", true));
vSeeds.push_back(CDNSSeedData("2001:41d0:8:3cca::49", "2001:41d0:8:3cca::49", true));
vSeeds.push_back(CDNSSeedData("92.222.109.150", "92.222.109.150", true));
vSeeds.push_back(CDNSSeedData("2001:41d0:8:3cca::50", "2001:41d0:8:3cca::50", true));
vSeeds.push_back(CDNSSeedData("92.222.109.151", "92.222.109.151", true));
vSeeds.push_back(CDNSSeedData("2001:41d0:8:3cca::51", "2001:41d0:8:3cca::51", true));
vSeeds.push_back(CDNSSeedData("92.222.109.152", "92.222.109.152", true));
vSeeds.push_back(CDNSSeedData("2001:41d0:8:3cca::52", "2001:41d0:8:3cca::52", true));
vSeeds.push_back(CDNSSeedData("92.222.109.153", "92.222.109.153", true));
vSeeds.push_back(CDNSSeedData("2001:41d0:8:3cca::53", "2001:41d0:8:3cca::53", true));
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 60); // R
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 13);
base58Prefixes[STAKING_ADDRESS] = std::vector<unsigned char>(1, 33); // E
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 212);
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >();
// BIP44 coin type is from https://github.com/satoshilabs/slips/blob/master/slip-0044.md
base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x80)(0x00)(0x00)(0xde).convert_to_container<std::vector<unsigned char> >();
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main));
// Sapling
bech32HRPs[SAPLING_PAYMENT_ADDRESS] = "ps";
bech32HRPs[SAPLING_FULL_VIEWING_KEY] = "pviews";
bech32HRPs[SAPLING_INCOMING_VIEWING_KEY] = "pivks";
bech32HRPs[SAPLING_EXTENDED_SPEND_KEY] = "p-secret-spending-key-main";
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
return data;
}
};
static CMainParams mainParams;
/**
* Testnet (v3)
*/
class CTestNetParams : public CMainParams
{
public:
CTestNetParams()
{
networkID = CBaseChainParams::TESTNET;
strNetworkID = "test";
genesis = CreateGenesisBlock(1454124731, 2402015, 0x1e0ffff0, 1, 250 * COIN);
consensus.hashGenesisBlock = genesis.GetHash();
//assert(consensus.hashGenesisBlock == uint256S("0x0000041e482b9b9691d98eefb48473405c0b8ec31b76df3797c74a78680ef818"));
//assert(genesis.hashMerkleRoot == uint256S("0x1b2ef6e2f28be914103a277377ae7729dcd125dfeb8bf97bd5964ba72b6dc39b"));
consensus.fPowAllowMinDifficultyBlocks = true;
consensus.powLimit = ~UINT256_ZERO >> 20; // Real_E_Coin starting difficulty is 1 / 2^12
consensus.posLimitV1 = ~UINT256_ZERO >> 24;
consensus.posLimitV2 = ~UINT256_ZERO >> 20;
consensus.nBudgetCycleBlocks = 144; // approx 10 cycles per day
consensus.nBudgetFeeConfirmations = 3; // (only 8-blocks window for finalization on testnet)
consensus.nCoinbaseMaturity = 15;
consensus.nFutureTimeDriftPoW = 7200;
consensus.nFutureTimeDriftPoS = 180;
consensus.nMasternodeCountDrift = 4; // num of MN we allow the see-saw payments to be off by
consensus.nMaxMoneyOut = 43199500 * COIN;
consensus.nPoolMaxTransactions = 2;
consensus.nProposalEstablishmentTime = 60 * 5; // at least 5 min old to make it into a budget
consensus.nStakeMinAge = 60 * 60;
consensus.nStakeMinDepth = 100;
consensus.nTargetTimespan = 40 * 60;
consensus.nTargetTimespanV2 = 30 * 60;
consensus.nTargetSpacing = 1 * 60;
consensus.nTimeSlotLength = 15;
// spork keys
consensus.strSporkPubKey = "04E88BB455E2A04E65FCC41D88CD367E9CCE1F5A409BE94D8C2B4B35D223DED9C8E2F4E061349BA3A38839282508066B6DC4DB72DD432AC4067991E6BF20176127";
consensus.strSporkPubKeyOld = "04A8B319388C0F8588D238B9941DC26B26D3F9465266B368A051C5C100F79306A557780101FE2192FE170D7E6DEFDCBEE4C8D533396389C0DAFFDBC842B002243C";
consensus.nTime_EnforceNewSporkKey = 1566860400; //!> August 26, 2019 11:00:00 PM GMT
consensus.nTime_RejectOldSporkKey = 1569538800; //!> September 26, 2019 11:00:00 PM GMT
// Network upgrades
consensus.vUpgrades[Consensus::BASE_NETWORK].nActivationHeight =
Consensus::NetworkUpgrade::ALWAYS_ACTIVE;
consensus.vUpgrades[Consensus::UPGRADE_TESTDUMMY].nActivationHeight =
Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT;
consensus.vUpgrades[Consensus::UPGRADE_POS].nActivationHeight = 201;
consensus.vUpgrades[Consensus::UPGRADE_POS_V2].nActivationHeight = 51197;
consensus.vUpgrades[Consensus::UPGRADE_BIP65].nActivationHeight = 851019;
consensus.vUpgrades[Consensus::UPGRADE_V3_4].nActivationHeight = 1214000;
consensus.vUpgrades[Consensus::UPGRADE_V4_0].nActivationHeight = 1347000;
consensus.vUpgrades[Consensus::UPGRADE_V5_DUMMY].nActivationHeight =
Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT;
consensus.vUpgrades[Consensus::UPGRADE_BIP65].hashActivationBlock =
uint256S("0xc54b3e7e8b710e4075da1806adf2d508ae722627d5bcc43f594cf64d5eef8b30");
consensus.vUpgrades[Consensus::UPGRADE_V3_4].hashActivationBlock =
uint256S("0x1822577176173752aea33d1f60607cefe9e0b1c54ebaa77eb40201a385506199");
consensus.vUpgrades[Consensus::UPGRADE_V4_0].hashActivationBlock =
uint256S("0x30c173ffc09a13f288bf6e828216107037ce5b79536b1cebd750a014f4939882");
/**
* The message start string is designed to be unlikely to occur in normal data.
* The characters are rarely used upper ASCII, not valid as UTF-8, and produce
* a large 4-byte int at any alignment.
*/
pchMessageStart[0] = 0x45;
pchMessageStart[1] = 0x76;
pchMessageStart[2] = 0x65;
pchMessageStart[3] = 0xba;
nDefaultPort = 51474;
vFixedSeeds.clear();
vSeeds.clear();
// nodes with support for servicebits filtering should be at the top
vSeeds.push_back(CDNSSeedData("fuzzbawls.pw", "real_e_coin-testnet.seed.fuzzbawls.pw", true));
vSeeds.push_back(CDNSSeedData("fuzzbawls.pw", "real_e_coin-testnet.seed2.fuzzbawls.pw", true));
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 139); // Testnet real_e_coin addresses start with 'x' or 'y'
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 19); // Testnet real_e_coin script addresses start with '8' or '9'
base58Prefixes[STAKING_ADDRESS] = std::vector<unsigned char>(1, 73); // starting with 'W'
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 239); // Testnet private keys start with '9' or 'c' (Bitcoin defaults)
// Testnet real_e_coin BIP32 pubkeys start with 'DRKV'
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x3a)(0x80)(0x61)(0xa0).convert_to_container<std::vector<unsigned char> >();
// Testnet real_e_coin BIP32 prvkeys start with 'DRKP'
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x3a)(0x80)(0x58)(0x37).convert_to_container<std::vector<unsigned char> >();
// Testnet real_e_coin BIP44 coin type is '1' (All coin's testnet default)
base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x80)(0x00)(0x00)(0x01).convert_to_container<std::vector<unsigned char> >();
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test));
// Sapling
bech32HRPs[SAPLING_PAYMENT_ADDRESS] = "ptestsapling";
bech32HRPs[SAPLING_FULL_VIEWING_KEY] = "pviewtestsapling";
bech32HRPs[SAPLING_INCOMING_VIEWING_KEY] = "bcktestsapling";
bech32HRPs[SAPLING_EXTENDED_SPEND_KEY] = "p-secret-spending-key-test";
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
return dataTestnet;
}
};
static CTestNetParams testNetParams;
/**
* Regression test
*/
class CRegTestParams : public CTestNetParams
{
public:
CRegTestParams()
{
networkID = CBaseChainParams::REGTEST;
strNetworkID = "regtest";
genesis = CreateGenesisBlock(1454124731, 2402015, 0x1e0ffff0, 1, 250 * COIN);
consensus.hashGenesisBlock = genesis.GetHash();
//assert(consensus.hashGenesisBlock == uint256S("0x0000041e482b9b9691d98eefb48473405c0b8ec31b76df3797c74a78680ef818"));
//assert(genesis.hashMerkleRoot == uint256S("0x1b2ef6e2f28be914103a277377ae7729dcd125dfeb8bf97bd5964ba72b6dc39b"));
consensus.fPowAllowMinDifficultyBlocks = true;
consensus.powLimit = ~UINT256_ZERO >> 20; // Real_E_Coin starting difficulty is 1 / 2^12
consensus.posLimitV1 = ~UINT256_ZERO >> 24;
consensus.posLimitV2 = ~UINT256_ZERO >> 20;
consensus.nBudgetCycleBlocks = 144; // approx 10 cycles per day
consensus.nBudgetFeeConfirmations = 3; // (only 8-blocks window for finalization on regtest)
consensus.nCoinbaseMaturity = 100;
consensus.nFutureTimeDriftPoW = 7200;
consensus.nFutureTimeDriftPoS = 180;
consensus.nMasternodeCountDrift = 4; // num of MN we allow the see-saw payments to be off by
consensus.nMaxMoneyOut = 43199500 * COIN;
consensus.nPoolMaxTransactions = 2;
consensus.nProposalEstablishmentTime = 60 * 5; // at least 5 min old to make it into a budget
consensus.nStakeMinAge = 0;
consensus.nStakeMinDepth = 2;
consensus.nTargetTimespan = 40 * 60;
consensus.nTargetTimespanV2 = 30 * 60;
consensus.nTargetSpacing = 1 * 60;
consensus.nTimeSlotLength = 15;
/* Spork Key for RegTest:
WIF private key: 932HEevBSujW2ud7RfB1YF91AFygbBRQj3de3LyaCRqNzKKgWXi
private key hex: bd4960dcbd9e7f2223f24e7164ecb6f1fe96fc3a416f5d3a830ba5720c84b8ca
Address: yCvUVd72w7xpimf981m114FSFbmAmne7j9
*/
consensus.strSporkPubKey = "043969b1b0e6f327de37f297a015d37e2235eaaeeb3933deecd8162c075cee0207b13537618bde640879606001a8136091c62ec272dd0133424a178704e6e75bb7";
consensus.strSporkPubKeyOld = "";
consensus.nTime_EnforceNewSporkKey = 0;
consensus.nTime_RejectOldSporkKey = 0;
// Network upgrades
consensus.vUpgrades[Consensus::BASE_NETWORK].nActivationHeight =
Consensus::NetworkUpgrade::ALWAYS_ACTIVE;
consensus.vUpgrades[Consensus::UPGRADE_TESTDUMMY].nActivationHeight =
Consensus::NetworkUpgrade::NO_ACTIVATION_HEIGHT;
consensus.vUpgrades[Consensus::UPGRADE_POS].nActivationHeight = 251;
consensus.vUpgrades[Consensus::UPGRADE_POS_V2].nActivationHeight = 251;
consensus.vUpgrades[Consensus::UPGRADE_BIP65].nActivationHeight =
Consensus::NetworkUpgrade::ALWAYS_ACTIVE;
consensus.vUpgrades[Consensus::UPGRADE_V3_4].nActivationHeight = 251;
consensus.vUpgrades[Consensus::UPGRADE_V4_0].nActivationHeight =
Consensus::NetworkUpgrade::ALWAYS_ACTIVE;
consensus.vUpgrades[Consensus::UPGRADE_V5_DUMMY].nActivationHeight = 300;
/**
* The message start string is designed to be unlikely to occur in normal data.
* The characters are rarely used upper ASCII, not valid as UTF-8, and produce
* a large 4-byte int at any alignment.
*/
pchMessageStart[0] = 0xa1;
pchMessageStart[1] = 0xcf;
pchMessageStart[2] = 0x7e;
pchMessageStart[3] = 0xac;
nDefaultPort = 51476;
vFixedSeeds.clear(); //! Testnet mode doesn't have any fixed seeds.
vSeeds.clear(); //! Testnet mode doesn't have any DNS seeds.
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
return dataRegtest;
}
void UpdateNetworkUpgradeParameters(Consensus::UpgradeIndex idx, int nActivationHeight)
{
assert(idx > Consensus::BASE_NETWORK && idx < Consensus::MAX_NETWORK_UPGRADES);
consensus.vUpgrades[idx].nActivationHeight = nActivationHeight;
}
};
static CRegTestParams regTestParams;
static CChainParams* pCurrentParams = 0;
const CChainParams& Params()
{
assert(pCurrentParams);
return *pCurrentParams;
}
CChainParams& Params(CBaseChainParams::Network network)
{
switch (network) {
case CBaseChainParams::MAIN:
return mainParams;
case CBaseChainParams::TESTNET:
return testNetParams;
case CBaseChainParams::REGTEST:
return regTestParams;
default:
assert(false && "Unimplemented network");
return mainParams;
}
}
void SelectParams(CBaseChainParams::Network network)
{
SelectBaseParams(network);
pCurrentParams = &Params(network);
}
bool SelectParamsFromCommandLine()
{
CBaseChainParams::Network network = NetworkIdFromCommandLine();
if (network == CBaseChainParams::MAX_NETWORK_TYPES)
return false;
SelectParams(network);
return true;
}
void UpdateNetworkUpgradeParameters(Consensus::UpgradeIndex idx, int nActivationHeight)
{
regTestParams.UpdateNetworkUpgradeParameters(idx, nActivationHeight);
}
| 45.974194 | 241 | 0.772336 | [
"vector"
] |
2bfda7d69c7b26a7179ca4591f8ddc0c1a484b7c | 1,149 | cpp | C++ | BOJ/14000~14999/14267.cpp | shinkeonkim/today-ps | f3e5e38c5215f19579bb0422f303a9c18c626afa | [
"Apache-2.0"
] | 2 | 2020-01-29T06:54:41.000Z | 2021-11-07T13:23:27.000Z | BOJ/14000~14999/14267.cpp | shinkeonkim/Today_PS | bb0cda0ee1b9c57e1cfa38355e29d0f1c6167a44 | [
"Apache-2.0"
] | null | null | null | BOJ/14000~14999/14267.cpp | shinkeonkim/Today_PS | bb0cda0ee1b9c57e1cfa38355e29d0f1c6167a44 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
#define for1(s,n) for(int i = s; i < n; i++)
#define for1j(s,n) for(int j = s; j < n; j++)
#define foreach(k) for(auto i : k)
#define foreachj(k) for(auto j : k)
#define pb(a) push_back(a)
#define sz(a) a.size()
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
typedef vector <int> iv1;
typedef vector <vector<int>> iv2;
typedef vector <ll> llv1;
typedef unsigned int uint;
typedef vector <ull> ullv1;
typedef vector <vector <ull>> ullv2;
ll N, M;
ll ar[110000];
ll tree[110000];
llv1 children[110000];
ll D[110000];
ll parent;
void dfs(ll current, ll weight) {
D[current] = ar[current] + weight;
for(auto i : children[current]) {
dfs(i, weight + ar[current]);
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> N >> M;
for1(0, N) {
cin >> tree[i];
if(tree[i] == -1) {
parent = i;
}
else children[tree[i]-1].pb(i);
}
for1(0, M) {
ll a, b;
cin >> a >> b;
ar[a-1] += b;
}
dfs(parent, 0);
for1(0, N) {
cout << D[i] << " ";
}
} | 19.810345 | 45 | 0.543081 | [
"vector"
] |
92017b1c0a1c3333b7168c84dec3890f85fe0903 | 852 | hpp | C++ | src/gui/text_button.hpp | fiddleplum/ve | 1e45de0488d593069032714ebe67725f468054f8 | [
"MIT"
] | null | null | null | src/gui/text_button.hpp | fiddleplum/ve | 1e45de0488d593069032714ebe67725f468054f8 | [
"MIT"
] | 16 | 2016-12-27T16:57:09.000Z | 2017-04-30T23:34:58.000Z | src/gui/text_button.hpp | fiddleplum/ve | 1e45de0488d593069032714ebe67725f468054f8 | [
"MIT"
] | null | null | null | #pragma once
#include "gui/widget.hpp"
#include "util/ptr.hpp"
namespace ve
{
class TextButton : public Widget
{
public:
// Constructor.
TextButton(Ptr<render::Scene> const & scene, Ptr<render::Shader> const & shader);
// Internal to gui. Returns the depth.
float getDepth() const override;
// Internal to gui. Sets the depth.
void setDepth(float depth) override;
// Returns the bounds.
Recti getBounds() const override;
// Internal to gui. Sets the bounds of the sprite.
void setBounds(Recti bounds) override;
// Internal to gui. Called when the user moves the cursor within the widget or out of the widget.
void onCursorPositionChanged(std::optional<Vector2i> cursorPosition) override;
// Internal to gui. Updates the text button.
void update(float dt) override;
// Virtual destructor.
~TextButton();
};
} | 24.342857 | 99 | 0.715962 | [
"render"
] |
920befaf291784b0f9ac50166b60f8d0d87bb472 | 834 | cpp | C++ | source/core/entry/GearEnv.cpp | Johnny-Martin/Gear | 2c5cf5c10c700e3ee7f89011c9a2ec4851d4d9e3 | [
"MIT"
] | null | null | null | source/core/entry/GearEnv.cpp | Johnny-Martin/Gear | 2c5cf5c10c700e3ee7f89011c9a2ec4851d4d9e3 | [
"MIT"
] | null | null | null | source/core/entry/GearEnv.cpp | Johnny-Martin/Gear | 2c5cf5c10c700e3ee7f89011c9a2ec4851d4d9e3 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "GearEnv.h"
map<string, UIObject*> GearEnv::m_rootObjMap{};
HRESULT GearEnv::Init()
{
RenderManager::Init();
return S_OK;
}
HRESULT GearEnv::UnInit()
{
RenderManager::UnInit();
DestoryAllRootObject();
return S_OK;
}
bool GearEnv::AddRootObject(UIObject* pObj)
{
auto spObjName = pObj->GetAttrValue("id");
if (!spObjName || spObjName->empty()){
ERR("AddRootObj error: can not get object id");
return false;
}
auto it = m_rootObjMap.find(*spObjName);
if (it != m_rootObjMap.end()){
ERR("AddRootObj error: repetitive object id");
return false;
}
m_rootObjMap[*spObjName] = pObj;
return true;
}
void GearEnv::DestoryAllRootObject()
{
auto it = m_rootObjMap.begin();
while (it != m_rootObjMap.end())
{
delete it->second;
m_rootObjMap.erase(it);
it = m_rootObjMap.begin();
}
} | 19.857143 | 49 | 0.691847 | [
"object"
] |
92133d9b91a0d05858b69274fab87fc7ff799cd2 | 46,026 | cpp | C++ | src/gpu/text/GrTextBlob.cpp | Ghaker/my-skia | c1150db5e1cec1de2d6ce4df2e92146730e0ed53 | [
"BSD-3-Clause"
] | null | null | null | src/gpu/text/GrTextBlob.cpp | Ghaker/my-skia | c1150db5e1cec1de2d6ce4df2e92146730e0ed53 | [
"BSD-3-Clause"
] | null | null | null | src/gpu/text/GrTextBlob.cpp | Ghaker/my-skia | c1150db5e1cec1de2d6ce4df2e92146730e0ed53 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkColorFilter.h"
#include "include/gpu/GrContext.h"
#include "include/private/SkTemplates.h"
#include "src/codec/SkMasks.h"
#include "src/core/SkAutoMalloc.h"
#include "src/core/SkMaskFilterBase.h"
#include "src/core/SkMatrixProvider.h"
#include "src/core/SkPaintPriv.h"
#include "src/core/SkStrikeSpec.h"
#include "src/gpu/GrBlurUtils.h"
#include "src/gpu/GrClip.h"
#include "src/gpu/GrStyle.h"
#include "src/gpu/geometry/GrStyledShape.h"
#include "src/gpu/ops/GrAtlasTextOp.h"
#include "src/gpu/text/GrAtlasManager.h"
#include "src/gpu/text/GrStrikeCache.h"
#include "src/gpu/text/GrTextBlob.h"
#include "src/gpu/text/GrTextTarget.h"
#include <cstddef>
#include <new>
// -- GrTextBlob::Key ------------------------------------------------------------------------------
GrTextBlob::Key::Key() { sk_bzero(this, sizeof(Key)); }
bool GrTextBlob::Key::operator==(const GrTextBlob::Key& other) const {
return 0 == memcmp(this, &other, sizeof(Key));
}
// -- GrTextBlob::PathGlyph ------------------------------------------------------------------------
GrTextBlob::PathGlyph::PathGlyph(const SkPath& path, SkPoint origin)
: fPath(path)
, fOrigin(origin) {}
// -- GrTextBlob::SubRun ---------------------------------------------------------------------------
GrTextBlob::SubRun::SubRun(SubRunType type, GrTextBlob* textBlob, const SkStrikeSpec& strikeSpec,
GrMaskFormat format, SkRect vertexBounds,
const SkSpan<VertexData>& vertexData)
: fBlob{textBlob}
, fType{type}
, fMaskFormat{format}
, fStrikeSpec{strikeSpec}
, fVertexBounds{vertexBounds}
, fVertexData{vertexData} {
SkASSERT(fType != kTransformedPath);
}
GrTextBlob::SubRun::SubRun(GrTextBlob* textBlob, const SkStrikeSpec& strikeSpec)
: fBlob{textBlob}
, fType{kTransformedPath}
, fMaskFormat{kA8_GrMaskFormat}
, fStrikeSpec{strikeSpec}
, fVertexBounds{SkRect::MakeEmpty()}
, fVertexData{SkSpan<VertexData>{}} { }
void GrTextBlob::SubRun::resetBulkUseToken() { fBulkUseToken.reset(); }
GrDrawOpAtlas::BulkUseTokenUpdater* GrTextBlob::SubRun::bulkUseToken() { return &fBulkUseToken; }
GrMaskFormat GrTextBlob::SubRun::maskFormat() const { return fMaskFormat; }
size_t GrTextBlob::SubRun::vertexStride() const {
switch (this->maskFormat()) {
case kA8_GrMaskFormat:
return this->hasW() ? sizeof(Mask3DVertex) : sizeof(Mask2DVertex);
case kARGB_GrMaskFormat:
return this->hasW() ? sizeof(ARGB3DVertex) : sizeof(ARGB2DVertex);
default:
SkASSERT(!this->hasW());
return sizeof(Mask2DVertex);
}
SkUNREACHABLE;
}
size_t GrTextBlob::SubRun::quadOffset(size_t index) const {
return index * kVerticesPerGlyph * this->vertexStride();
}
template <typename Rect>
static auto ltbr(const Rect& r) {
return std::make_tuple(r.left(), r.top(), r.right(), r.bottom());
}
void GrTextBlob::SubRun::fillVertexData(
void *vertexDst, int offset, int count,
GrColor color, const SkMatrix& drawMatrix, SkPoint drawOrigin, SkIRect clip) const {
SkMatrix matrix = drawMatrix;
matrix.preTranslate(drawOrigin.x(), drawOrigin.y());
auto transformed2D = [&](auto dst, SkScalar dstPadding, SkScalar srcPadding) {
SkScalar strikeToSource = fStrikeSpec.strikeToSourceRatio();
SkPoint inset = {dstPadding, dstPadding};
for (auto[quad, vertexData] : SkMakeZip(dst, fVertexData.subspan(offset, count))) {
auto[glyph, pos, rect] = vertexData;
auto [l, t, r, b] = rect;
SkPoint sLT = (SkPoint::Make(l, t) + inset) * strikeToSource + pos,
sRB = (SkPoint::Make(r, b) - inset) * strikeToSource + pos;
SkPoint lt = matrix.mapXY(sLT.x(), sLT.y()),
lb = matrix.mapXY(sLT.x(), sRB.y()),
rt = matrix.mapXY(sRB.x(), sLT.y()),
rb = matrix.mapXY(sRB.x(), sRB.y());
auto[al, at, ar, ab] = glyph.grGlyph->fAtlasLocator.getUVs(srcPadding);
quad[0] = {lt, color, {al, at}}; // L,T
quad[1] = {lb, color, {al, ab}}; // L,B
quad[2] = {rt, color, {ar, at}}; // R,T
quad[3] = {rb, color, {ar, ab}}; // R,B
}
};
auto transformed3D = [&](auto dst, SkScalar dstPadding, SkScalar srcPadding) {
SkScalar strikeToSource = fStrikeSpec.strikeToSourceRatio();
SkPoint inset = {dstPadding, dstPadding};
auto mapXYZ = [&](SkScalar x, SkScalar y) {
SkPoint pt{x, y};
SkPoint3 result;
matrix.mapHomogeneousPoints(&result, &pt, 1);
return result;
};
for (auto[quad, vertexData] : SkMakeZip(dst, fVertexData.subspan(offset, count))) {
auto[glyph, pos, rect] = vertexData;
auto [l, t, r, b] = rect;
SkPoint sLT = (SkPoint::Make(l, t) + inset) * strikeToSource + pos,
sRB = (SkPoint::Make(r, b) - inset) * strikeToSource + pos;
SkPoint3 lt = mapXYZ(sLT.x(), sLT.y()),
lb = mapXYZ(sLT.x(), sRB.y()),
rt = mapXYZ(sRB.x(), sLT.y()),
rb = mapXYZ(sRB.x(), sRB.y());
auto[al, at, ar, ab] = glyph.grGlyph->fAtlasLocator.getUVs(srcPadding);
quad[0] = {lt, color, {al, at}}; // L,T
quad[1] = {lb, color, {al, ab}}; // L,B
quad[2] = {rt, color, {ar, at}}; // R,T
quad[3] = {rb, color, {ar, ab}}; // R,B
}
};
auto direct2D = [&](auto dst, SkIRect* clip) {
// Rectangles in device space
SkPoint originInDeviceSpace = matrix.mapXY(0, 0);
for (auto[quad, vertexData] : SkMakeZip(dst, fVertexData.subspan(offset, count))) {
auto[glyph, pos, rect] = vertexData;
auto[l, t, r, b] = rect;
auto[fx, fy] = pos + originInDeviceSpace;
auto[al, at, ar, ab] = glyph.grGlyph->fAtlasLocator.getUVs(0);
if (clip == nullptr) {
SkScalar dx = SkScalarRoundToScalar(fx),
dy = SkScalarRoundToScalar(fy);
auto[dl, dt, dr, db] = SkRect::MakeLTRB(l + dx, t + dy, r + dx, b + dy);
quad[0] = {{dl, dt}, color, {al, at}}; // L,T
quad[1] = {{dl, db}, color, {al, ab}}; // L,B
quad[2] = {{dr, dt}, color, {ar, at}}; // R,T
quad[3] = {{dr, db}, color, {ar, ab}}; // R,B
} else {
int dx = SkScalarRoundToInt(fx),
dy = SkScalarRoundToInt(fy);
SkIRect devIRect = SkIRect::MakeLTRB(l + dx, t + dy, r + dx, b + dy);
SkScalar dl, dt, dr, db;
uint16_t tl, tt, tr, tb;
if (!clip->containsNoEmptyCheck(devIRect)) {
if (SkIRect clipped; clipped.intersect(devIRect, *clip)) {
int lD = clipped.left() - devIRect.left();
int tD = clipped.top() - devIRect.top();
int rD = clipped.right() - devIRect.right();
int bD = clipped.bottom() - devIRect.bottom();
int indexLT, indexRB;
std::tie(dl, dt, dr, db) = ltbr(clipped);
std::tie(tl, tt, indexLT) =
GrDrawOpAtlas::UnpackIndexFromTexCoords(al, at);
std::tie(tr, tb, indexRB) =
GrDrawOpAtlas::UnpackIndexFromTexCoords(ar, ab);
std::tie(tl, tt) =
GrDrawOpAtlas::PackIndexInTexCoords(tl + lD, tt + tD, indexLT);
std::tie(tr, tb) =
GrDrawOpAtlas::PackIndexInTexCoords(tr + rD, tb + bD, indexRB);
} else {
// TODO: omit generating any vertex data for fully clipped glyphs ?
std::tie(dl, dt, dr, db) = std::make_tuple(0, 0, 0, 0);
std::tie(tl, tt, tr, tb) = std::make_tuple(0, 0, 0, 0);
}
} else {
std::tie(dl, dt, dr, db) = ltbr(devIRect);
std::tie(tl, tt, tr, tb) = std::tie(al, at, ar, ab);
}
quad[0] = {{dl, dt}, color, {tl, tt}}; // L,T
quad[1] = {{dl, db}, color, {tl, tb}}; // L,B
quad[2] = {{dr, dt}, color, {tr, tt}}; // R,T
quad[3] = {{dr, db}, color, {tr, tb}}; // R,B
}
}
};
switch (fType) {
case kDirectMask: {
if (clip.isEmpty()) {
if (this->maskFormat() != kARGB_GrMaskFormat) {
using Quad = Mask2DVertex[4];
SkASSERT(sizeof(Quad) == this->vertexStride() * kVerticesPerGlyph);
direct2D((Quad*) vertexDst, nullptr);
} else {
using Quad = ARGB2DVertex[4];
SkASSERT(sizeof(Quad) == this->vertexStride() * kVerticesPerGlyph);
direct2D((Quad*) vertexDst, nullptr);
}
} else {
if (this->maskFormat() != kARGB_GrMaskFormat) {
using Quad = Mask2DVertex[4];
SkASSERT(sizeof(Quad) == this->vertexStride() * kVerticesPerGlyph);
direct2D((Quad*) vertexDst, &clip);
} else {
using Quad = ARGB2DVertex[4];
SkASSERT(sizeof(Quad) == this->vertexStride() * kVerticesPerGlyph);
direct2D((Quad*) vertexDst, &clip);
}
}
break;
}
case kTransformedMask: {
if (!this->hasW()) {
if (this->maskFormat() == GrMaskFormat::kARGB_GrMaskFormat) {
using Quad = ARGB2DVertex[4];
SkASSERT(sizeof(Quad) == this->vertexStride() * kVerticesPerGlyph);
transformed2D((Quad*) vertexDst, 0, 1);
} else {
using Quad = Mask2DVertex[4];
SkASSERT(sizeof(Quad) == this->vertexStride() * kVerticesPerGlyph);
transformed2D((Quad*) vertexDst, 0, 1);
}
} else {
if (this->maskFormat() == GrMaskFormat::kARGB_GrMaskFormat) {
using Quad = ARGB3DVertex[4];
SkASSERT(sizeof(Quad) == this->vertexStride() * kVerticesPerGlyph);
transformed3D((Quad*) vertexDst, 0, 1);
} else {
using Quad = Mask3DVertex[4];
SkASSERT(sizeof(Quad) == this->vertexStride() * kVerticesPerGlyph);
transformed3D((Quad*) vertexDst, 0, 1);
}
}
break;
}
case kTransformedSDFT: {
if (!this->hasW()) {
using Quad = Mask2DVertex[4];
SkASSERT(sizeof(Quad) == this->vertexStride() * kVerticesPerGlyph);
transformed2D((Quad*) vertexDst, SK_DistanceFieldInset, SK_DistanceFieldInset);
} else {
using Quad = Mask3DVertex[4];
SkASSERT(sizeof(Quad) == this->vertexStride() * kVerticesPerGlyph);
transformed3D((Quad*) vertexDst, SK_DistanceFieldInset, SK_DistanceFieldInset);
}
break;
}
case kTransformedPath:
SK_ABORT("Paths don't generate vertex data.");
}
}
// Note: this method is only used with SkAtlasTextTarget. The SkAtlasTextTarget only uses SDF,
// and does the rectangle transforms on the GPU. For the normal text execution path see
// fillVertexData.
void GrTextBlob::SubRun::fillTextTargetVertexData(
Mask3DVertex vertexDst[][4], int offset, int count, GrColor color, SkPoint origin) const {
SkScalar strikeToSource = fStrikeSpec.strikeToSourceRatio();
SkPoint inset = {SK_DistanceFieldInset, SK_DistanceFieldInset};
for (auto[dst, vertexData] : SkMakeZip(vertexDst, fVertexData.subspan(offset, count))) {
auto[glyph, pos, rect] = vertexData;
auto [l, t, r, b] = rect;
SkPoint sLT = (SkPoint::Make(l, t) + inset) * strikeToSource + pos + origin,
sRB = (SkPoint::Make(r, b) - inset) * strikeToSource + pos + origin;
SkPoint3 lt = SkPoint3{sLT.x(), sLT.y(), 1.f},
lb = SkPoint3{sLT.x(), sRB.y(), 1.f},
rt = SkPoint3{sRB.x(), sLT.y(), 1.f},
rb = SkPoint3{sRB.x(), sRB.y(), 1.f};
auto[al, at, ar, ab] = glyph.grGlyph->fAtlasLocator.getUVs(SK_DistanceFieldInset);
dst[0] = {lt, color, {al, at}}; // L,T
dst[1] = {lb, color, {al, ab}}; // L,B
dst[2] = {rt, color, {ar, at}}; // R,T
dst[3] = {rb, color, {ar, ab}}; // R,B
}
}
int GrTextBlob::SubRun::glyphCount() const {
return fVertexData.count();
}
bool GrTextBlob::SubRun::drawAsDistanceFields() const { return fType == kTransformedSDFT; }
bool GrTextBlob::SubRun::drawAsPaths() const { return fType == kTransformedPath; }
bool GrTextBlob::SubRun::needsTransform() const {
return fType == kTransformedPath ||
fType == kTransformedMask ||
fType == kTransformedSDFT;
}
bool GrTextBlob::SubRun::needsPadding() const {
return fType == kTransformedPath || fType == kTransformedMask;
}
bool GrTextBlob::SubRun::hasW() const {
if (fType == kTransformedSDFT) {
return fBlob->hasPerspective() || fBlob->forceWForDistanceFields();
} else if (fType == kTransformedMask || fType == kTransformedPath) {
return fBlob->hasPerspective();
}
// The viewMatrix is implicitly SkMatrix::I when drawing kDirectMask, because it is not
// used.
return false;
}
void GrTextBlob::SubRun::prepareGrGlyphs(GrStrikeCache* strikeCache) {
if (fStrike) {
return;
}
fStrike = fStrikeSpec.findOrCreateGrStrike(strikeCache);
for (auto& tmp : fVertexData) {
tmp.glyph.grGlyph = fStrike->getGlyph(tmp.glyph.packedGlyphID);
}
}
SkRect GrTextBlob::SubRun::deviceRect(const SkMatrix& drawMatrix, SkPoint drawOrigin) const {
SkRect outBounds = fVertexBounds;
if (this->needsTransform()) {
// if the glyph needs transformation offset the by the new origin, and map to device space.
outBounds.offset(drawOrigin);
outBounds = drawMatrix.mapRect(outBounds);
} else {
SkPoint offset = drawMatrix.mapXY(drawOrigin.x(), drawOrigin.y());
// The vertex bounds are already {0, 0} based, so just add the new origin offset.
outBounds.offset(offset);
// Due to floating point numerical inaccuracies, we have to round out here
outBounds.roundOut();
}
return outBounds;
}
GrGlyph* GrTextBlob::SubRun::grGlyph(int i) const {
return fVertexData[i].glyph.grGlyph;
}
void GrTextBlob::SubRun::setUseLCDText(bool useLCDText) { fUseLCDText = useLCDText; }
bool GrTextBlob::SubRun::hasUseLCDText() const { return fUseLCDText; }
void GrTextBlob::SubRun::setAntiAliased(bool antiAliased) { fAntiAliased = antiAliased; }
bool GrTextBlob::SubRun::isAntiAliased() const { return fAntiAliased; }
const SkStrikeSpec& GrTextBlob::SubRun::strikeSpec() const { return fStrikeSpec; }
auto GrTextBlob::SubRun::MakePaths(
const SkZip<SkGlyphVariant, SkPoint>& drawables,
const SkFont& runFont,
const SkStrikeSpec& strikeSpec,
GrTextBlob* blob,
SkArenaAlloc* alloc) -> SubRun* {
SubRun* subRun = alloc->make<SubRun>(blob, strikeSpec);
subRun->setAntiAliased(runFont.hasSomeAntiAliasing());
for (auto [variant, pos] : drawables) {
subRun->fPaths.emplace_back(*variant.path(), pos);
}
return subRun;
};
auto GrTextBlob::SubRun::MakeSDFT(
const SkZip<SkGlyphVariant, SkPoint>& drawables,
const SkFont& runFont,
const SkStrikeSpec& strikeSpec,
GrTextBlob* blob,
SkArenaAlloc* alloc) -> SubRun* {
SubRun* subRun = SubRun::InitForAtlas(
kTransformedSDFT, drawables, strikeSpec, kA8_GrMaskFormat, blob, alloc);
subRun->setUseLCDText(runFont.getEdging() == SkFont::Edging::kSubpixelAntiAlias);
subRun->setAntiAliased(runFont.hasSomeAntiAliasing());
return subRun;
}
auto GrTextBlob::SubRun::MakeDirectMask(
const SkZip<SkGlyphVariant, SkPoint>& drawables,
const SkStrikeSpec& strikeSpec,
GrMaskFormat format,
GrTextBlob* blob,
SkArenaAlloc* alloc) -> SubRun* {
return SubRun::InitForAtlas(kDirectMask, drawables, strikeSpec, format, blob, alloc);
}
auto GrTextBlob::SubRun::MakeTransformedMask(
const SkZip<SkGlyphVariant, SkPoint>& drawables,
const SkStrikeSpec& strikeSpec,
GrMaskFormat format,
GrTextBlob* blob,
SkArenaAlloc* alloc) -> SubRun* {
return SubRun::InitForAtlas(kTransformedMask, drawables, strikeSpec, format, blob, alloc);
}
void GrTextBlob::SubRun::insertSubRunOpsIntoTarget(GrTextTarget* target,
const SkSurfaceProps& props,
const SkPaint& paint,
const SkPMColor4f& filteredColor,
const GrClip* clip,
const SkMatrixProvider& deviceMatrix,
SkPoint drawOrigin) {
if (this->drawAsPaths()) {
SkPaint runPaint{paint};
runPaint.setAntiAlias(this->isAntiAliased());
// If there are shaders, blurs or styles, the path must be scaled into source
// space independently of the CTM. This allows the CTM to be correct for the
// different effects.
GrStyle style(runPaint);
bool needsExactCTM = runPaint.getShader()
|| style.applies()
|| runPaint.getMaskFilter();
// Calculate the matrix that maps the path glyphs from their size in the strike to
// the graphics source space.
SkScalar scale = this->fStrikeSpec.strikeToSourceRatio();
SkMatrix strikeToSource = SkMatrix::Scale(scale, scale);
strikeToSource.postTranslate(drawOrigin.x(), drawOrigin.y());
if (!needsExactCTM) {
for (const auto& pathPos : this->fPaths) {
const SkPath& path = pathPos.fPath;
const SkPoint pos = pathPos.fOrigin; // Transform the glyph to source space.
SkMatrix pathMatrix = strikeToSource;
pathMatrix.postTranslate(pos.x(), pos.y());
SkPreConcatMatrixProvider strikeToDevice(deviceMatrix, pathMatrix);
GrStyledShape shape(path, paint);
target->drawShape(clip, runPaint, strikeToDevice, shape);
}
} else {
// Transform the path to device because the deviceMatrix must be unchanged to
// draw effect, filter or shader paths.
for (const auto& pathPos : this->fPaths) {
const SkPath& path = pathPos.fPath;
const SkPoint pos = pathPos.fOrigin;
// Transform the glyph to source space.
SkMatrix pathMatrix = strikeToSource;
pathMatrix.postTranslate(pos.x(), pos.y());
SkPath deviceOutline;
path.transform(pathMatrix, &deviceOutline);
deviceOutline.setIsVolatile(true);
GrStyledShape shape(deviceOutline, paint);
target->drawShape(clip, runPaint, deviceMatrix, shape);
}
}
} else {
int glyphCount = this->glyphCount();
if (0 == glyphCount) {
return;
}
bool skipClip = false;
SkIRect clipRect = SkIRect::MakeEmpty();
SkRect rtBounds = SkRect::MakeWH(target->width(), target->height());
SkRRect clipRRect = SkRRect::MakeRect(rtBounds);
GrAA aa;
// We can clip geometrically if we're not using SDFs or transformed glyphs,
// and we have an axis-aligned rectangular non-AA clip
if (!this->drawAsDistanceFields() &&
!this->needsTransform() &&
(!clip || (clip->isRRect(rtBounds, &clipRRect, &aa) &&
clipRRect.isRect() && GrAA::kNo == aa))) {
// We only need to do clipping work if the subrun isn't contained by the clip
SkRect subRunBounds = this->deviceRect(deviceMatrix.localToDevice(), drawOrigin);
if (!clipRRect.getBounds().contains(subRunBounds)) {
// If the subrun is completely outside, don't add an op for it
if (!clipRRect.getBounds().intersects(subRunBounds)) {
return;
} else {
clipRRect.getBounds().round(&clipRect);
}
}
skipClip = true;
}
auto op = this->makeOp(deviceMatrix, drawOrigin, clipRect,
paint, filteredColor, props, target);
if (op != nullptr) {
target->addDrawOp(skipClip ? nullptr : clip, std::move(op));
}
}
}
std::unique_ptr<GrAtlasTextOp> GrTextBlob::SubRun::makeOp(const SkMatrixProvider& matrixProvider,
SkPoint drawOrigin,
const SkIRect& clipRect,
const SkPaint& paint,
const SkPMColor4f& filteredColor,
const SkSurfaceProps& props,
GrTextTarget* target) {
GrPaint grPaint;
target->makeGrPaint(this->maskFormat(), paint, matrixProvider, &grPaint);
if (this->drawAsDistanceFields()) {
// TODO: Can we be even smarter based on the dest transfer function?
return GrAtlasTextOp::MakeDistanceField(target->getContext(),
std::move(grPaint),
this,
matrixProvider.localToDevice(),
drawOrigin,
clipRect,
filteredColor,
target->colorInfo().isLinearlyBlended(),
SkPaintPriv::ComputeLuminanceColor(paint),
props);
} else {
return GrAtlasTextOp::MakeBitmap(target->getContext(),
std::move(grPaint),
this,
matrixProvider.localToDevice(),
drawOrigin,
clipRect,
filteredColor);
}
}
auto GrTextBlob::SubRun::InitForAtlas(SubRunType type,
const SkZip<SkGlyphVariant, SkPoint>& drawables,
const SkStrikeSpec& strikeSpec,
GrMaskFormat format,
GrTextBlob* blob,
SkArenaAlloc* alloc) -> SubRun* {
size_t vertexCount = drawables.size();
using Data = VertexData;
SkRect bounds = SkRectPriv::MakeLargestInverted();
auto initializer = [&, strikeToSource=strikeSpec.strikeToSourceRatio()](size_t i) {
auto [variant, pos] = drawables[i];
SkGlyph* skGlyph = variant;
int16_t l = skGlyph->left();
int16_t t = skGlyph->top();
int16_t r = l + skGlyph->width();
int16_t b = t + skGlyph->height();
SkPoint lt = SkPoint::Make(l, t) * strikeToSource + pos,
rb = SkPoint::Make(r, b) * strikeToSource + pos;
bounds.joinNonEmptyArg(SkRect::MakeLTRB(lt.x(), lt.y(), rb.x(), rb.y()));
return Data{{skGlyph->getPackedID()}, pos, {l, t, r, b}};
};
SkSpan<Data> vertexData{
alloc->makeInitializedArray<Data>(vertexCount, initializer), vertexCount};
SubRun* subRun = alloc->make<SubRun>(type, blob, strikeSpec, format, bounds, vertexData);
return subRun;
}
// -- GrTextBlob -----------------------------------------------------------------------------------
void GrTextBlob::operator delete(void* p) { ::operator delete(p); }
void* GrTextBlob::operator new(size_t) { SK_ABORT("All blobs are created by placement new."); }
void* GrTextBlob::operator new(size_t, void* p) { return p; }
GrTextBlob::~GrTextBlob() = default;
sk_sp<GrTextBlob> GrTextBlob::Make(const SkGlyphRunList& glyphRunList,
const SkMatrix& drawMatrix,
GrColor color,
bool forceWForDistanceFields) {
// The difference in alignment from the storage of VertexData to SubRun;
constexpr size_t alignDiff = alignof(SubRun) - alignof(SubRun::VertexData);
constexpr size_t vertexDataToSubRunPadding = alignDiff > 0 ? alignDiff : 0;
size_t arenaSize = sizeof(SubRun::VertexData) * glyphRunList.totalGlyphCount()
+ glyphRunList.runCount() * (sizeof(SubRun) + vertexDataToSubRunPadding);
size_t allocationSize = sizeof(GrTextBlob) + arenaSize;
void* allocation = ::operator new (allocationSize);
SkColor initialLuminance = SkPaintPriv::ComputeLuminanceColor(glyphRunList.paint());
sk_sp<GrTextBlob> blob{new (allocation) GrTextBlob{
arenaSize, drawMatrix, glyphRunList.origin(),
color, initialLuminance, forceWForDistanceFields}};
return blob;
}
void GrTextBlob::setupKey(const GrTextBlob::Key& key, const SkMaskFilterBase::BlurRec& blurRec,
const SkPaint& paint) {
fKey = key;
if (key.fHasBlur) {
fBlurRec = blurRec;
}
if (key.fStyle != SkPaint::kFill_Style) {
fStrokeInfo.fFrameWidth = paint.getStrokeWidth();
fStrokeInfo.fMiterLimit = paint.getStrokeMiter();
fStrokeInfo.fJoin = paint.getStrokeJoin();
}
}
const GrTextBlob::Key& GrTextBlob::GetKey(const GrTextBlob& blob) { return blob.fKey; }
uint32_t GrTextBlob::Hash(const GrTextBlob::Key& key) { return SkOpts::hash(&key, sizeof(Key)); }
bool GrTextBlob::hasDistanceField() const {
return SkToBool(fTextType & kHasDistanceField_TextType);
}
bool GrTextBlob::hasBitmap() const { return SkToBool(fTextType & kHasBitmap_TextType); }
bool GrTextBlob::hasPerspective() const { return fInitialMatrix.hasPerspective(); }
void GrTextBlob::setHasDistanceField() { fTextType |= kHasDistanceField_TextType; }
void GrTextBlob::setHasBitmap() { fTextType |= kHasBitmap_TextType; }
void GrTextBlob::setMinAndMaxScale(SkScalar scaledMin, SkScalar scaledMax) {
// we init fMaxMinScale and fMinMaxScale in the constructor
fMaxMinScale = std::max(scaledMin, fMaxMinScale);
fMinMaxScale = std::min(scaledMax, fMinMaxScale);
}
bool GrTextBlob::mustRegenerate(const SkPaint& paint, bool anyRunHasSubpixelPosition,
const SkMaskFilterBase::BlurRec& blurRec,
const SkMatrix& drawMatrix, SkPoint drawOrigin) {
// If we have LCD text then our canonical color will be set to transparent, in this case we have
// to regenerate the blob on any color change
// We use the grPaint to get any color filter effects
if (fKey.fCanonicalColor == SK_ColorTRANSPARENT &&
fInitialLuminance != SkPaintPriv::ComputeLuminanceColor(paint)) {
return true;
}
if (fInitialMatrix.hasPerspective() != drawMatrix.hasPerspective()) {
return true;
}
/** This could be relaxed for blobs with only distance field glyphs. */
if (fInitialMatrix.hasPerspective() && !SkMatrixPriv::CheapEqual(fInitialMatrix, drawMatrix)) {
return true;
}
// We only cache one masked version
if (fKey.fHasBlur &&
(fBlurRec.fSigma != blurRec.fSigma || fBlurRec.fStyle != blurRec.fStyle)) {
return true;
}
// Similarly, we only cache one version for each style
if (fKey.fStyle != SkPaint::kFill_Style &&
(fStrokeInfo.fFrameWidth != paint.getStrokeWidth() ||
fStrokeInfo.fMiterLimit != paint.getStrokeMiter() ||
fStrokeInfo.fJoin != paint.getStrokeJoin())) {
return true;
}
// Mixed blobs must be regenerated. We could probably figure out a way to do integer scrolls
// for mixed blobs if this becomes an issue.
if (this->hasBitmap() && this->hasDistanceField()) {
// Identical view matrices and we can reuse in all cases
return !(SkMatrixPriv::CheapEqual(fInitialMatrix, drawMatrix) &&
drawOrigin == fInitialOrigin);
}
if (this->hasBitmap()) {
if (fInitialMatrix.getScaleX() != drawMatrix.getScaleX() ||
fInitialMatrix.getScaleY() != drawMatrix.getScaleY() ||
fInitialMatrix.getSkewX() != drawMatrix.getSkewX() ||
fInitialMatrix.getSkewY() != drawMatrix.getSkewY()) {
return true;
}
// TODO(herb): this is not needed for full pixel glyph choice, but is needed to adjust
// the quads properly. Devise a system that regenerates the quads from original data
// using the transform to allow this to be used in general.
// We can update the positions in the text blob without regenerating the whole
// blob, but only for integer translations.
// Calculate the translation in source space to a translation in device space by mapping
// (0, 0) through both the initial matrix and the draw matrix; take the difference.
SkMatrix initialMatrix{fInitialMatrix};
initialMatrix.preTranslate(fInitialOrigin.x(), fInitialOrigin.y());
SkPoint initialDeviceOrigin{0, 0};
initialMatrix.mapPoints(&initialDeviceOrigin, 1);
SkMatrix completeDrawMatrix{drawMatrix};
completeDrawMatrix.preTranslate(drawOrigin.x(), drawOrigin.y());
SkPoint drawDeviceOrigin{0, 0};
completeDrawMatrix.mapPoints(&drawDeviceOrigin, 1);
SkPoint translation = drawDeviceOrigin - initialDeviceOrigin;
if (!SkScalarIsInt(translation.x()) || !SkScalarIsInt(translation.y())) {
return true;
}
} else if (this->hasDistanceField()) {
// A scale outside of [blob.fMaxMinScale, blob.fMinMaxScale] would result in a different
// distance field being generated, so we have to regenerate in those cases
SkScalar newMaxScale = drawMatrix.getMaxScale();
SkScalar oldMaxScale = fInitialMatrix.getMaxScale();
SkScalar scaleAdjust = newMaxScale / oldMaxScale;
if (scaleAdjust < fMaxMinScale || scaleAdjust > fMinMaxScale) {
return true;
}
}
// It is possible that a blob has neither distanceField nor bitmaptext. This is in the case
// when all of the runs inside the blob are drawn as paths. In this case, we always regenerate
// the blob anyways at flush time, so no need to regenerate explicitly
return false;
}
void GrTextBlob::insertOpsIntoTarget(GrTextTarget* target,
const SkSurfaceProps& props,
const SkPaint& paint,
const SkPMColor4f& filteredColor,
const GrClip* clip,
const SkMatrixProvider& deviceMatrix,
SkPoint drawOrigin) {
for (SubRun* subRun = fFirstSubRun; subRun != nullptr; subRun = subRun->fNextSubRun) {
subRun->insertSubRunOpsIntoTarget(target, props, paint, filteredColor, clip, deviceMatrix,
drawOrigin);
}
}
const GrTextBlob::Key& GrTextBlob::key() const { return fKey; }
size_t GrTextBlob::size() const { return fSize; }
template<typename AddSingleMaskFormat>
void GrTextBlob::addMultiMaskFormat(
AddSingleMaskFormat addSingle,
const SkZip<SkGlyphVariant, SkPoint>& drawables,
const SkStrikeSpec& strikeSpec) {
this->setHasBitmap();
if (drawables.empty()) { return; }
auto glyphSpan = drawables.get<0>();
SkGlyph* glyph = glyphSpan[0];
GrMaskFormat format = GrGlyph::FormatFromSkGlyph(glyph->maskFormat());
size_t startIndex = 0;
for (size_t i = 1; i < drawables.size(); i++) {
glyph = glyphSpan[i];
GrMaskFormat nextFormat = GrGlyph::FormatFromSkGlyph(glyph->maskFormat());
if (format != nextFormat) {
auto sameFormat = drawables.subspan(startIndex, i - startIndex);
SubRun* subRun = addSingle(sameFormat, strikeSpec, format, this, &fAlloc);
this->insertSubRun(subRun);
format = nextFormat;
startIndex = i;
}
}
auto sameFormat = drawables.last(drawables.size() - startIndex);
SubRun* subRun = addSingle(sameFormat, strikeSpec, format, this, &fAlloc);
this->insertSubRun(subRun);
}
GrTextBlob::GrTextBlob(size_t allocSize,
const SkMatrix& drawMatrix,
SkPoint origin,
GrColor color,
SkColor initialLuminance,
bool forceWForDistanceFields)
: fSize{allocSize}
, fInitialMatrix{drawMatrix}
, fInitialOrigin{origin}
, fForceWForDistanceFields{forceWForDistanceFields}
, fColor{color}
, fInitialLuminance{initialLuminance}
, fAlloc{SkTAddOffset<char>(this, sizeof(GrTextBlob)), allocSize, allocSize/2} { }
void GrTextBlob::insertSubRun(SubRun* subRun) {
if (fFirstSubRun == nullptr) {
fFirstSubRun = subRun;
fLastSubRun = subRun;
} else {
fLastSubRun->fNextSubRun = subRun;
fLastSubRun = subRun;
}
}
void GrTextBlob::processDeviceMasks(const SkZip<SkGlyphVariant, SkPoint>& drawables,
const SkStrikeSpec& strikeSpec) {
this->addMultiMaskFormat(SubRun::MakeDirectMask, drawables, strikeSpec);
}
void GrTextBlob::processSourcePaths(const SkZip<SkGlyphVariant, SkPoint>& drawables,
const SkFont& runFont,
const SkStrikeSpec& strikeSpec) {
this->setHasBitmap();
SubRun* subRun = SubRun::MakePaths(drawables, runFont, strikeSpec, this, &fAlloc);
this->insertSubRun(subRun);
}
void GrTextBlob::processSourceSDFT(const SkZip<SkGlyphVariant, SkPoint>& drawables,
const SkStrikeSpec& strikeSpec,
const SkFont& runFont,
SkScalar minScale,
SkScalar maxScale) {
this->setHasDistanceField();
this->setMinAndMaxScale(minScale, maxScale);
SubRun* subRun = SubRun::MakeSDFT(drawables, runFont, strikeSpec, this, &fAlloc);
this->insertSubRun(subRun);
}
void GrTextBlob::processSourceMasks(const SkZip<SkGlyphVariant, SkPoint>& drawables,
const SkStrikeSpec& strikeSpec) {
this->addMultiMaskFormat(SubRun::MakeTransformedMask, drawables, strikeSpec);
}
auto GrTextBlob::firstSubRun() const -> SubRun* { return fFirstSubRun; }
bool GrTextBlob::forceWForDistanceFields() const { return fForceWForDistanceFields; }
// -- Adding a mask to an atlas ----------------------------------------------------------------
// expands each bit in a bitmask to 0 or ~0 of type INT_TYPE. Used to expand a BW glyph mask to
// A8, RGB565, or RGBA8888.
template <typename INT_TYPE>
static void expand_bits(INT_TYPE* dst,
const uint8_t* src,
int width,
int height,
int dstRowBytes,
int srcRowBytes) {
for (int i = 0; i < height; ++i) {
int rowWritesLeft = width;
const uint8_t* s = src;
INT_TYPE* d = dst;
while (rowWritesLeft > 0) {
unsigned mask = *s++;
for (int i = 7; i >= 0 && rowWritesLeft; --i, --rowWritesLeft) {
*d++ = (mask & (1 << i)) ? (INT_TYPE)(~0UL) : 0;
}
}
dst = reinterpret_cast<INT_TYPE*>(reinterpret_cast<intptr_t>(dst) + dstRowBytes);
src += srcRowBytes;
}
}
static void get_packed_glyph_image(
const SkGlyph& glyph, int dstRB, GrMaskFormat expectedMaskFormat, void* dst) {
const int width = glyph.width();
const int height = glyph.height();
const void* src = glyph.image();
SkASSERT(src != nullptr);
GrMaskFormat grMaskFormat = GrGlyph::FormatFromSkGlyph(glyph.maskFormat());
if (grMaskFormat == expectedMaskFormat) {
int srcRB = glyph.rowBytes();
// Notice this comparison is with the glyphs raw mask format, and not its GrMaskFormat.
if (glyph.maskFormat() != SkMask::kBW_Format) {
if (srcRB != dstRB) {
const int bbp = GrMaskFormatBytesPerPixel(expectedMaskFormat);
for (int y = 0; y < height; y++) {
memcpy(dst, src, width * bbp);
src = (const char*) src + srcRB;
dst = (char*) dst + dstRB;
}
} else {
memcpy(dst, src, dstRB * height);
}
} else {
// Handle 8-bit format by expanding the mask to the expected format.
const uint8_t* bits = reinterpret_cast<const uint8_t*>(src);
switch (expectedMaskFormat) {
case kA8_GrMaskFormat: {
uint8_t* bytes = reinterpret_cast<uint8_t*>(dst);
expand_bits(bytes, bits, width, height, dstRB, srcRB);
break;
}
case kA565_GrMaskFormat: {
uint16_t* rgb565 = reinterpret_cast<uint16_t*>(dst);
expand_bits(rgb565, bits, width, height, dstRB, srcRB);
break;
}
default:
SK_ABORT("Invalid GrMaskFormat");
}
}
} else if (grMaskFormat == kA565_GrMaskFormat && expectedMaskFormat == kARGB_GrMaskFormat) {
// Convert if the glyph uses a 565 mask format since it is using LCD text rendering
// but the expected format is 8888 (will happen on macOS with Metal since that
// combination does not support 565).
static constexpr SkMasks masks{
{0b1111'1000'0000'0000, 11, 5}, // Red
{0b0000'0111'1110'0000, 5, 6}, // Green
{0b0000'0000'0001'1111, 0, 5}, // Blue
{0, 0, 0} // Alpha
};
const int a565Bpp = GrMaskFormatBytesPerPixel(kA565_GrMaskFormat);
const int argbBpp = GrMaskFormatBytesPerPixel(kARGB_GrMaskFormat);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
uint16_t color565 = 0;
memcpy(&color565, src, a565Bpp);
uint32_t colorRGBA = GrColorPackRGBA(masks.getRed(color565),
masks.getGreen(color565),
masks.getBlue(color565),
0xFF);
memcpy(dst, &colorRGBA, argbBpp);
src = (char*)src + a565Bpp;
dst = (char*)dst + argbBpp;
}
}
} else {
// crbug:510931
// Retrieving the image from the cache can actually change the mask format. This case is
// very uncommon so for now we just draw a clear box for these glyphs.
const int bpp = GrMaskFormatBytesPerPixel(expectedMaskFormat);
for (int y = 0; y < height; y++) {
sk_bzero(dst, width * bpp);
dst = (char*)dst + dstRB;
}
}
}
using VR = GrTextBlob::VertexRegenerator;
// returns true if glyph successfully added to texture atlas, false otherwise. If the glyph's
// mask format has changed, then add_glyph_to_atlas will draw a clear box. This will almost never
// happen.
// TODO we can handle some of these cases if we really want to, but the long term solution is to
// get the actual glyph image itself when we get the glyph metrics.
GrDrawOpAtlas::ErrorCode VR::addGlyphToAtlas(const SkGlyph& skGlyph, GrGlyph* grGlyph) {
SkASSERT(grGlyph != nullptr);
SkASSERT(skGlyph.image() != nullptr);
GrMaskFormat expectedMaskFormat = fFullAtlasManager->resolveMaskFormat(fSubRun->maskFormat());
int bytesPerPixel = GrMaskFormatBytesPerPixel(expectedMaskFormat);
SkASSERT(!fSubRun->needsPadding() || skGlyph.maskFormat() != SkMask::kSDF_Format);
// Add 1 pixel padding around grGlyph if needed.
const int width = fSubRun->needsPadding() ? skGlyph.width() + 2 : skGlyph.width();
const int height = fSubRun->needsPadding() ? skGlyph.height() + 2 : skGlyph.height();
int rowBytes = width * bytesPerPixel;
size_t size = height * rowBytes;
// Temporary storage for normalizing grGlyph image.
SkAutoSMalloc<1024> storage(size);
void* dataPtr = storage.get();
if (fSubRun->needsPadding()) {
sk_bzero(dataPtr, size);
// Advance in one row and one column.
dataPtr = (char*)(dataPtr) + rowBytes + bytesPerPixel;
}
get_packed_glyph_image(skGlyph, rowBytes, expectedMaskFormat, dataPtr);
return fFullAtlasManager->addToAtlas(fResourceProvider,
fUploadTarget,
expectedMaskFormat,
width,
height,
storage.get(),
&grGlyph->fAtlasLocator);
}
// -- GrTextBlob::VertexRegenerator ----------------------------------------------------------------
GrTextBlob::VertexRegenerator::VertexRegenerator(GrResourceProvider* resourceProvider,
GrTextBlob::SubRun* subRun,
GrDeferredUploadTarget* uploadTarget,
GrAtlasManager* fullAtlasManager)
: fResourceProvider(resourceProvider)
, fUploadTarget(uploadTarget)
, fFullAtlasManager(fullAtlasManager)
, fSubRun(subRun) { }
std::tuple<bool, int> GrTextBlob::VertexRegenerator::updateTextureCoordinates(
const int begin, const int end) {
SkASSERT(fSubRun->isPrepared());
SkBulkGlyphMetricsAndImages metricsAndImages{fSubRun->strikeSpec()};
// Update the atlas information in the GrStrike.
auto code = GrDrawOpAtlas::ErrorCode::kSucceeded;
auto tokenTracker = fUploadTarget->tokenTracker();
int i = begin;
for (; i < end; i++) {
GrGlyph* grGlyph = fSubRun->grGlyph(i);
SkASSERT(grGlyph != nullptr);
if (!fFullAtlasManager->hasGlyph(fSubRun->maskFormat(), grGlyph)) {
const SkGlyph& skGlyph = *metricsAndImages.glyph(grGlyph->fPackedID);
if (skGlyph.image() == nullptr) {
return {false, 0};
}
code = this->addGlyphToAtlas(skGlyph, grGlyph);
if (code != GrDrawOpAtlas::ErrorCode::kSucceeded) {
break;
}
}
fFullAtlasManager->addGlyphToBulkAndSetUseToken(
fSubRun->bulkUseToken(), fSubRun->maskFormat(), grGlyph,
tokenTracker->nextDrawToken());
}
int glyphsPlacedInAtlas = i - begin;
return {code != GrDrawOpAtlas::ErrorCode::kError, glyphsPlacedInAtlas};
}
std::tuple<bool, int> GrTextBlob::VertexRegenerator::regenerate(int begin, int end) {
uint64_t currentAtlasGen = fFullAtlasManager->atlasGeneration(fSubRun->maskFormat());
if (fSubRun->fAtlasGeneration != currentAtlasGen) {
// Calculate the texture coordinates for the vertexes during first use (fAtlasGeneration
// is set to kInvalidAtlasGeneration) or the atlas has changed in subsequent calls..
fSubRun->resetBulkUseToken();
auto [success, glyphsPlacedInAtlas] = this->updateTextureCoordinates(begin, end);
// Update atlas generation if there are no more glyphs to put in the atlas.
if (success && begin + glyphsPlacedInAtlas == fSubRun->glyphCount()) {
// Need to get the freshest value of the atlas' generation because
// updateTextureCoordinates may have changed it.
fSubRun->fAtlasGeneration = fFullAtlasManager->atlasGeneration(fSubRun->maskFormat());
}
return {success, glyphsPlacedInAtlas};
} else {
// The atlas hasn't changed, so our texture coordinates are still valid.
if (end == fSubRun->glyphCount()) {
// The atlas hasn't changed and the texture coordinates are all still valid. Update
// all the plots used to the new use token.
fFullAtlasManager->setUseTokenBulk(*fSubRun->bulkUseToken(),
fUploadTarget->tokenTracker()->nextDrawToken(),
fSubRun->maskFormat());
}
return {true, end - begin};
}
}
| 45.035225 | 100 | 0.572372 | [
"geometry",
"shape",
"transform"
] |
9213c10bd08c59254d57559271b1c3308c7c5f00 | 5,153 | cpp | C++ | test/nymph_test_client/nymph_test_client.cpp | martinmoene/NymphRPC | 99974556dddccf4143e214705b4b0f1529127e0c | [
"BSD-3-Clause"
] | 52 | 2018-05-31T16:54:59.000Z | 2022-02-15T20:55:07.000Z | test/nymph_test_client/nymph_test_client.cpp | martinmoene/NymphRPC | 99974556dddccf4143e214705b4b0f1529127e0c | [
"BSD-3-Clause"
] | 6 | 2019-11-22T10:58:47.000Z | 2021-08-01T08:05:04.000Z | test/nymph_test_client/nymph_test_client.cpp | martinmoene/NymphRPC | 99974556dddccf4143e214705b4b0f1529127e0c | [
"BSD-3-Clause"
] | 10 | 2019-09-11T05:44:12.000Z | 2021-11-21T13:01:40.000Z | /*
nymph_test_client.cpp - Test client application using the NymphRPC library.
Revision 0
Features:
-
Notes:
-
2017/06/24, Maya Posch : Initial version.
(c) Nyanko.ws
*/
#include "../../src/nymph.h"
#include <iostream>
#include <vector>
void logFunction(int level, std::string logStr) {
std::cout << level << " - " << logStr << std::endl;
}
// Callback to register with the server.
// This callback will be called once by the server and then discarded. This is
// useful for one-off events, but can also be used for callbacks during the
// life-time of the client.
void callbackFunction(uint32_t session, NymphMessage* msg, void* data) {
std::cout << "Client callback function called.\n";
// Remove the callback.
NymphRemoteServer::removeCallback("helloCallbackFunction");
msg->discard();
}
int main() {
// Initialise the remote client instance.
long timeout = 5000; // 5 seconds.
NymphRemoteServer::init(logFunction, NYMPH_LOG_LEVEL_TRACE, timeout);
// Connect to the remote server.
uint32_t handle;
std::string result;
if (!NymphRemoteServer::connect("localhost", 4004, handle, 0, result)) {
std::cout << "Connecting to remote server failed: " << result << std::endl;
NymphRemoteServer::disconnect(handle, result);
NymphRemoteServer::shutdown();
return 1;
}
// Send message and wait for response.
//values.push_back(new NymphString("Hello World!"));
std::vector<NymphType*> values;
std::string hello = "Hello World!";
values.push_back(new NymphType(&hello));
NymphType* returnValue = 0;
if (!NymphRemoteServer::callMethod(handle, "helloFunction", values, returnValue, result)) {
std::cout << "Error calling remote method: " << result << std::endl;
NymphRemoteServer::disconnect(handle, result);
NymphRemoteServer::shutdown();
return 1;
}
std::string response(returnValue->getChar(), returnValue->string_length());
std::cout << "Response string: " << response << std::endl;
delete returnValue;
// Register callback and send message with its ID to the server. Then wait
// for the callback to be called.
NymphRemoteServer::registerCallback("callbackFunction", callbackFunction, 0);
values.clear();
std::string cbStr = "callbackFunction";
values.push_back(new NymphType(&cbStr));
returnValue = 0;
if (!NymphRemoteServer::callMethod(handle, "helloCallbackFunction", values, returnValue, result)) {
std::cout << "Error calling remote method: " << result << std::endl;
NymphRemoteServer::disconnect(handle, result);
NymphRemoteServer::shutdown();
return 1;
}
if (!returnValue->getBool()) {
std::cout << "Remote method returned false. " << result << std::endl;
NymphRemoteServer::disconnect(handle, result);
NymphRemoteServer::shutdown();
return 1;
}
delete returnValue;
// Request array with integers.
returnValue = 0;
values.clear();
if (!NymphRemoteServer::callMethod(handle, "arrayFunction", values, returnValue, result)) {
std::cout << "Error calling remote method: " << result << std::endl;
NymphRemoteServer::disconnect(handle, result);
NymphRemoteServer::shutdown();
return 1;
}
// Print out values in vector.
std::vector<NymphType*>* numbers = returnValue->getArray();
std::cout << "Got numbers: ";
for (int i = 0; i < numbers->size(); i++) {
std::cout << i << ":" << (uint16_t) (*numbers)[i]->getUint8() << " ";
}
std::cout << "." << std::endl;
delete returnValue;
// Request struct with all basic types (integers, floats).
returnValue = 0;
if (!NymphRemoteServer::callMethod(handle, "structFunction", values, returnValue, result)) {
std::cout << "Error calling remote method: " << result << std::endl;
NymphRemoteServer::disconnect(handle, result);
NymphRemoteServer::shutdown();
return 1;
}
// Print out the values.
std::map<std::string, NymphPair>* pairs = returnValue->getStruct();
std::cout << "Pairs: " << std::endl;
NymphPair ref = (*pairs)["Boolean"];
std::cout << "Boolean: " << ref.value->getBool() << std::endl;
ref = (*pairs)["Uint8"];
std::cout << "Uint8: " << (uint16_t) ref.value->getUint8() << std::endl;
ref = (*pairs)["Int8"];
std::cout << "Int8: " << (int16_t) ref.value->getInt8() << std::endl;
ref = (*pairs)["Uint16"];
std::cout << "Uint16: " << ref.value->getUint16() << std::endl;
ref = (*pairs)["Int16"];
std::cout << "Int16: " << ref.value->getInt16() << std::endl;
ref = (*pairs)["Uint32"];
std::cout << "Uint32: " << ref.value->getUint32() << std::endl;
ref = (*pairs)["Int32"];
std::cout << "Int32: " << ref.value->getInt32() << std::endl;
ref = (*pairs)["Uint64"];
std::cout << "Uint64: " << ref.value->getUint64() << std::endl;
ref = (*pairs)["Int64"];
std::cout << "Int64: " << ref.value->getInt64() << std::endl;
ref = (*pairs)["Float"];
std::cout << "Float: " << ref.value->getFloat() << std::endl;
ref = (*pairs)["Double"];
std::cout << "Double: " << ref.value->getDouble() << std::endl;
delete returnValue;
std::cout << "Test completed." << std::endl;
std::cout << "Shutting down client...\n";
// Shutdown.
NymphRemoteServer::disconnect(handle, result);
NymphRemoteServer::shutdown();
return 0;
}
| 30.856287 | 100 | 0.662139 | [
"vector"
] |
9216a96cdf5af3b9d3c65943f4ce4824d3e68f26 | 5,197 | cpp | C++ | examples/tutorial/least-squares.cpp | denis14/ViennaCL-1.5.2 | fec808905cca30196e10126681611bdf8da5297a | [
"MIT"
] | null | null | null | examples/tutorial/least-squares.cpp | denis14/ViennaCL-1.5.2 | fec808905cca30196e10126681611bdf8da5297a | [
"MIT"
] | null | null | null | examples/tutorial/least-squares.cpp | denis14/ViennaCL-1.5.2 | fec808905cca30196e10126681611bdf8da5297a | [
"MIT"
] | null | null | null | /* =========================================================================
Copyright (c) 2010-2014, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
Portions of this software are copyright by UChicago Argonne, LLC.
-----------------
ViennaCL - The Vienna Computing Library
-----------------
Project Head: Karl Rupp rupp@iue.tuwien.ac.at
(A list of authors and contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
============================================================================= */
/*
*
* Tutorial: Least Squares problem for matrices from ViennaCL or Boost.uBLAS (least-squares.cpp and least-squares.cu are identical, the latter being required for compilation using CUDA nvcc)
*
* See Example 2 at http://tutorial.math.lamar.edu/Classes/LinAlg/QRDecomposition.aspx for a reference solution.
*
*/
// activate ublas support in ViennaCL
#define VIENNACL_WITH_UBLAS
//
// include necessary system headers
//
#include <iostream>
//
// Boost includes
//
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/lu.hpp>
#include <boost/numeric/ublas/io.hpp>
//
// ViennaCL includes
//
#include "viennacl/vector.hpp"
#include "viennacl/matrix.hpp"
#include "viennacl/matrix_proxy.hpp"
#include "viennacl/linalg/qr.hpp"
#include "viennacl/linalg/lu.hpp"
/*
* Tutorial: Least Squares problem for matrices from ViennaCL or Boost.uBLAS
*
* See Example 2 at http://tutorial.math.lamar.edu/Classes/LinAlg/QRDecomposition.aspx for a reference solution.
*/
int main (int, const char **)
{
typedef float ScalarType; //feel free to change this to 'double' if supported by your hardware
typedef boost::numeric::ublas::matrix<ScalarType> MatrixType;
typedef boost::numeric::ublas::vector<ScalarType> VectorType;
typedef viennacl::matrix<ScalarType, viennacl::column_major> VCLMatrixType;
typedef viennacl::vector<ScalarType> VCLVectorType;
//
// Create vectors and matrices with data, cf. http://tutorial.math.lamar.edu/Classes/LinAlg/QRDecomposition.aspx
//
VectorType ublas_b(4);
ublas_b(0) = -4;
ublas_b(1) = 2;
ublas_b(2) = 5;
ublas_b(3) = -1;
MatrixType ublas_A(4, 3);
MatrixType Q = boost::numeric::ublas::zero_matrix<ScalarType>(4, 4);
MatrixType R = boost::numeric::ublas::zero_matrix<ScalarType>(4, 3);
ublas_A(0, 0) = 2; ublas_A(0, 1) = -1; ublas_A(0, 2) = 1;
ublas_A(1, 0) = 1; ublas_A(1, 1) = -5; ublas_A(1, 2) = 2;
ublas_A(2, 0) = -3; ublas_A(2, 1) = 1; ublas_A(2, 2) = -4;
ublas_A(3, 0) = 1; ublas_A(3, 1) = -1; ublas_A(3, 2) = 1;
//
// Setup the matrix in ViennaCL:
//
VCLVectorType vcl_b(ublas_b.size());
VCLMatrixType vcl_A(ublas_A.size1(), ublas_A.size2());
viennacl::copy(ublas_b, vcl_b);
viennacl::copy(ublas_A, vcl_A);
//////////// Part 1: Use Boost.uBLAS for all computations ////////////////
std::cout << "--- Boost.uBLAS ---" << std::endl;
std::vector<ScalarType> ublas_betas = viennacl::linalg::inplace_qr(ublas_A); //computes the QR factorization
// compute modified RHS of the minimization problem:
// b' := Q^T b
viennacl::linalg::inplace_qr_apply_trans_Q(ublas_A, ublas_betas, ublas_b);
// Final step: triangular solve: Rx = b'', where b'' are the first three entries in b'
// We only need the upper left square part of A, which defines the upper triangular matrix R
boost::numeric::ublas::range ublas_range(0, 3);
boost::numeric::ublas::matrix_range<MatrixType> ublas_R(ublas_A, ublas_range, ublas_range);
boost::numeric::ublas::vector_range<VectorType> ublas_b2(ublas_b, ublas_range);
boost::numeric::ublas::inplace_solve(ublas_R, ublas_b2, boost::numeric::ublas::upper_tag());
std::cout << "Result: " << ublas_b2 << std::endl;
//////////// Part 2: Use ViennaCL types for BLAS 3 computations, but use Boost.uBLAS for the panel factorization ////////////////
std::cout << "--- ViennaCL (hybrid implementation) ---" << std::endl;
std::vector<ScalarType> hybrid_betas = viennacl::linalg::inplace_qr(vcl_A);
// compute modified RHS of the minimization problem:
// b := Q^T b
viennacl::linalg::inplace_qr_apply_trans_Q(vcl_A, hybrid_betas, vcl_b);
// Final step: triangular solve: Rx = b'.
// We only need the upper part of A such that R is a square matrix
viennacl::range vcl_range(0, 3);
viennacl::matrix_range<VCLMatrixType> vcl_R(vcl_A, vcl_range, vcl_range);
viennacl::vector_range<VCLVectorType> vcl_b2(vcl_b, vcl_range);
viennacl::linalg::inplace_solve(vcl_R, vcl_b2, viennacl::linalg::upper_tag());
std::cout << "Result: " << vcl_b2 << std::endl;
//
// That's it.
//
std::cout << "!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!" << std::endl;
return EXIT_SUCCESS;
}
| 35.841379 | 191 | 0.646142 | [
"vector"
] |
92176d86c27bac3efa32bb5551144a3b85be2806 | 53,335 | cc | C++ | fpga_interchange/site_router.cc | trabucayre/nextpnr | 8a9fb810369aeb5eed128ef4e7d4de456ef1ec8f | [
"0BSD"
] | null | null | null | fpga_interchange/site_router.cc | trabucayre/nextpnr | 8a9fb810369aeb5eed128ef4e7d4de456ef1ec8f | [
"0BSD"
] | null | null | null | fpga_interchange/site_router.cc | trabucayre/nextpnr | 8a9fb810369aeb5eed128ef4e7d4de456ef1ec8f | [
"0BSD"
] | null | null | null | /*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2021 Symbiflow Authors
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "nextpnr.h"
#include "design_utils.h"
#include "dynamic_bitarray.h"
#include "log.h"
#include "site_routing_cache.h"
#include "site_arch.h"
#include "site_arch.impl.h"
#include <queue>
NEXTPNR_NAMESPACE_BEGIN
bool verbose_site_router(const Context *ctx) { return ctx->debug; }
bool verbose_site_router(const SiteArch *ctx) { return verbose_site_router(ctx->ctx); }
void SiteRouter::bindBel(CellInfo *cell)
{
auto result = cells_in_site.emplace(cell);
NPNR_ASSERT(result.second);
dirty = true;
}
void SiteRouter::unbindBel(CellInfo *cell)
{
NPNR_ASSERT(cells_in_site.erase(cell) == 1);
dirty = true;
}
bool check_initial_wires(const Context *ctx, SiteInformation *site_info)
{
// Propagate from BEL pins to first wire, checking for trivial routing
// conflicts.
dict<WireId, NetInfo *> wires;
for (CellInfo *cell : site_info->cells_in_site) {
BelId bel = cell->bel;
for (const auto &pin_pair : cell->cell_bel_pins) {
if (!cell->ports.count(pin_pair.first))
continue;
const PortInfo &port = cell->ports.at(pin_pair.first);
if (port.net == nullptr)
continue;
for (IdString bel_pin_name : pin_pair.second) {
BelPin bel_pin;
bel_pin.bel = bel;
bel_pin.pin = bel_pin_name;
WireId wire = ctx->getBelPinWire(bel_pin.bel, bel_pin.pin);
auto result = wires.emplace(wire, port.net);
if (!result.second) {
// This wire is already in use, make sure the net bound is
// the same net, otherwise there is a trivial net
// conflict.
const NetInfo *other_net = result.first->second;
if (other_net != port.net) {
// We have a direct net conflict at the BEL pin,
// immediately short circuit the site routing check.
if (verbose_site_router(ctx)) {
log_info("Direct net conflict detected for cell %s:%s at bel %s, net %s != %s\n",
cell->name.c_str(ctx), cell->type.c_str(ctx), ctx->nameOfBel(cell->bel),
port.net->name.c_str(ctx), other_net->name.c_str(ctx));
}
return false;
}
}
}
}
}
return true;
}
static bool is_invalid_site_port(const SiteArch *ctx, const SiteNetInfo *net, const SitePip &pip)
{
// Blocked ports
auto fnd_rsv = ctx->blocked_site_ports.find(pip.pip);
if (fnd_rsv != ctx->blocked_site_ports.end() && !fnd_rsv->second.count(net->net))
return true;
// Synthetic pips
SyntheticType type = ctx->pip_synthetic_type(pip);
PhysicalNetlist::PhysNetlist::NetType net_type = ctx->ctx->get_net_type(net->net);
bool is_invalid = false;
if (type == SYNTH_GND) {
is_invalid = net_type != PhysicalNetlist::PhysNetlist::NetType::GND;
} else if (type == SYNTH_VCC) {
is_invalid = net_type != PhysicalNetlist::PhysNetlist::NetType::VCC;
}
return is_invalid;
}
struct SiteExpansionLoop
{
RouteNodeStorage *const node_storage;
SiteExpansionLoop(RouteNodeStorage *node_storage) : node_storage(node_storage)
{
NPNR_ASSERT(node_storage != nullptr);
}
void clear()
{
node_storage->free_nodes(used_nodes);
used_nodes.clear();
solution.clear();
net_driver = SiteWire();
}
virtual ~SiteExpansionLoop() { node_storage->free_nodes(used_nodes); }
// Storage for nodes
std::vector<size_t> used_nodes;
bool expand_result;
SiteWire net_driver;
pool<SiteWire> net_users;
SiteRoutingSolution solution;
Node new_node(const SiteWire &wire, const SitePip &pip, const Node *parent)
{
Node node = node_storage->alloc_node();
used_nodes.push_back(node.get_index());
node->wire = wire;
node->pip = pip;
if (parent != nullptr) {
node->parent = (*parent).get_index();
node->flags = (*parent)->flags;
node->depth = (*parent)->depth + 1;
}
if (pip.type == SitePip::SITE_PORT) {
// Site ports should always have a parent!
NPNR_ASSERT(parent != nullptr);
if (wire.type == SiteWire::SITE_PORT_SINK) {
NPNR_ASSERT((*parent)->wire.type == SiteWire::SITE_WIRE);
NPNR_ASSERT(node->can_leave_site());
node->mark_left_site();
node->mark_left_site_after_entering();
} else if (wire.type == SiteWire::SITE_PORT_SOURCE) {
// This is a backward walk, so this is considered entering
// the site.
NPNR_ASSERT((*parent)->wire.type == SiteWire::SITE_WIRE);
NPNR_ASSERT(node->can_enter_site());
node->mark_entered_site();
} else {
// See if this is a forward or backward walk.
NPNR_ASSERT(wire.type == SiteWire::SITE_WIRE);
if ((*parent)->wire.type == SiteWire::SITE_PORT_SINK) {
// This is a backward walk, so this is considered leaving
// the site.
NPNR_ASSERT(node->can_leave_site());
node->mark_left_site();
node->mark_left_site_after_entering();
} else {
NPNR_ASSERT((*parent)->wire.type == SiteWire::SITE_PORT_SOURCE);
NPNR_ASSERT(node->can_enter_site());
node->mark_entered_site();
}
}
}
return node;
}
// Expand from wire specified, always downhill.
bool expand_net(const SiteArch *ctx, SiteRoutingCache *site_routing_cache, const SiteNetInfo *net)
{
if (net->driver == net_driver && net->users == net_users) {
return expand_result;
}
clear();
net_driver = net->driver;
net_users = net->users;
if (site_routing_cache->get_solution(ctx, *net, &solution)) {
expand_result = true;
return expand_result;
}
if (verbose_site_router(ctx)) {
log_info("Expanding net %s from %s\n", ctx->nameOfNet(net), ctx->nameOfWire(net->driver));
}
auto node = new_node(net->driver, SitePip(), /*parent=*/nullptr);
pool<SiteWire> targets;
targets.insert(net->users.begin(), net->users.end());
if (verbose_site_router(ctx)) {
log_info("%zu targets:\n", targets.size());
for (auto &target : targets) {
log_info(" - %s\n", ctx->nameOfWire(target));
}
}
int32_t max_depth = 0;
int32_t max_depth_seen = 0;
std::vector<Node> nodes_to_expand;
nodes_to_expand.push_back(node);
std::vector<size_t> completed_routes;
while (!nodes_to_expand.empty()) {
Node parent_node = nodes_to_expand.back();
nodes_to_expand.pop_back();
max_depth_seen = std::max(max_depth_seen, parent_node->depth);
for (SitePip pip : ctx->getPipsDownhill(parent_node->wire)) {
if (is_invalid_site_port(ctx, net, pip)) {
if (verbose_site_router(ctx)) {
log_info("Pip %s is not a valid site port for net %s, skipping\n", ctx->nameOfPip(pip),
ctx->nameOfNet(net));
}
continue;
}
SiteWire wire = ctx->getPipDstWire(pip);
if (pip.type == SitePip::SITE_PORT) {
if (wire.type == SiteWire::SITE_PORT_SINK) {
if (!parent_node->can_leave_site()) {
// This path has already left the site once, don't leave it again!
if (verbose_site_router(ctx)) {
log_info("%s is not a valid PIP for this path because it has already left the site\n",
ctx->nameOfPip(pip));
}
continue;
}
} else {
NPNR_ASSERT(parent_node->wire.type == SiteWire::SITE_PORT_SOURCE);
if (!parent_node->can_enter_site()) {
// This path has already entered the site once,
// don't enter it again!
if (verbose_site_router(ctx)) {
log_info(
"%s is not a valid PIP for this path because it has already entered the site\n",
ctx->nameOfPip(pip));
}
continue;
}
}
}
auto wire_iter = ctx->wire_to_nets.find(wire);
if (wire_iter != ctx->wire_to_nets.end() && wire_iter->second.net != net) {
if (verbose_site_router(ctx)) {
log_info("Wire %s is already tied to net %s, not exploring for net %s\n", ctx->nameOfWire(wire),
ctx->nameOfNet(wire_iter->second.net), ctx->nameOfNet(net));
}
continue;
}
auto node = new_node(wire, pip, &parent_node);
if (!node->is_valid_node()) {
if (verbose_site_router(ctx)) {
log_info(
"%s is not a valid PIP for this path because it has left the site after entering it.\n",
ctx->nameOfPip(pip));
}
continue;
}
if (targets.count(wire)) {
completed_routes.push_back(node.get_index());
max_depth = std::max(max_depth, node->depth);
}
nodes_to_expand.push_back(node);
}
}
// Make sure expansion reached all targets, otherwise this site is
// already unroutable!
solution.clear();
solution.store_solution(ctx, node_storage, net->driver, completed_routes);
bool verify = solution.verify(ctx, *net);
if (!verify)
return false;
for (size_t route : completed_routes) {
SiteWire wire = node_storage->get_node(route)->wire;
targets.erase(wire);
}
if (targets.empty()) {
site_routing_cache->add_solutions(ctx, *net, solution);
}
// Return nodes back to the storage system.
node_storage->free_nodes(used_nodes);
used_nodes.clear();
expand_result = targets.empty();
return expand_result;
}
size_t num_solutions() const { return solution.num_solutions(); }
const SiteWire &solution_sink(size_t idx) const { return solution.solution_sink(idx); }
std::vector<SitePip>::const_iterator solution_begin(size_t idx) const { return solution.solution_begin(idx); }
std::vector<SitePip>::const_iterator solution_end(size_t idx) const { return solution.solution_end(idx); }
bool solution_inverted(size_t idx) const { return solution.solution_inverted(idx); }
bool solution_can_invert(size_t idx) const { return solution.solution_can_invert(idx); }
};
void print_current_state(const SiteArch *site_arch)
{
const Context *ctx = site_arch->ctx;
auto &cells_in_site = site_arch->site_info->cells_in_site;
const CellInfo *cell = *cells_in_site.begin();
BelId bel = cell->bel;
const auto &bel_data = bel_info(ctx->chip_info, bel);
const auto &site_inst = site_inst_info(ctx->chip_info, bel.tile, bel_data.site);
log_info("Site %s\n", site_inst.name.get());
log_info(" Cells in site:\n");
for (CellInfo *cell : cells_in_site) {
log_info(" - %s (%s) => %s\n", cell->name.c_str(ctx), cell->type.c_str(ctx), ctx->nameOfBel(cell->bel));
}
log_info(" Nets in site:\n");
for (auto &net_pair : site_arch->nets) {
auto *net = net_pair.first;
log_info(" - %s, pins in site:\n", net->name.c_str(ctx));
if (net->driver.cell && cells_in_site.count(net->driver.cell)) {
log_info(" - %s/%s (%s)\n", net->driver.cell->name.c_str(ctx), net->driver.port.c_str(ctx),
net->driver.cell->type.c_str(ctx));
}
for (const auto user : net->users) {
if (user.cell && cells_in_site.count(user.cell)) {
log_info(" - %s/%s (%s)\n", user.cell->name.c_str(ctx), user.port.c_str(ctx),
user.cell->type.c_str(ctx));
}
}
}
log_info(" Consumed wires:\n");
for (auto &wire_pair : site_arch->wire_to_nets) {
const SiteWire &site_wire = wire_pair.first;
if (site_wire.type != SiteWire::SITE_WIRE) {
continue;
}
WireId wire = site_wire.wire;
const NetInfo *net = wire_pair.second.net->net;
log_info(" - %s is bound to %s\n", ctx->nameOfWire(wire), net->name.c_str(ctx));
}
}
struct PossibleSolutions
{
bool tested = false;
SiteNetInfo *net = nullptr;
std::vector<SitePip>::const_iterator pips_begin;
std::vector<SitePip>::const_iterator pips_end;
bool inverted = false;
bool can_invert = false;
PhysicalNetlist::PhysNetlist::NetType prefered_constant_net_type = PhysicalNetlist::PhysNetlist::NetType::SIGNAL;
};
bool test_solution(SiteArch *ctx, SiteNetInfo *net, std::vector<SitePip>::const_iterator pips_begin,
std::vector<SitePip>::const_iterator pips_end)
{
bool valid = true;
std::vector<SitePip>::const_iterator good_pip_end = pips_begin;
std::vector<SitePip>::const_iterator iter = pips_begin;
SitePip pip;
while (iter != pips_end) {
pip = *iter;
if (!ctx->bindPip(pip, net)) {
valid = false;
break;
}
++iter;
good_pip_end = iter;
}
// Unwind a bad solution
if (!valid) {
for (auto iter = pips_begin; iter != good_pip_end; ++iter) {
ctx->unbindPip(*iter);
}
} else {
NPNR_ASSERT(net->driver == ctx->getPipSrcWire(pip));
}
return valid;
}
void remove_solution(SiteArch *ctx, std::vector<SitePip>::const_iterator pips_begin,
std::vector<SitePip>::const_iterator pips_end)
{
for (auto iter = pips_begin; iter != pips_end; ++iter) {
ctx->unbindPip(*iter);
}
}
struct SolutionPreference
{
const SiteArch *ctx;
const std::vector<PossibleSolutions> &solutions;
SolutionPreference(const SiteArch *ctx, const std::vector<PossibleSolutions> &solutions)
: ctx(ctx), solutions(solutions)
{
}
bool non_inverting_preference(const PossibleSolutions &lhs, const PossibleSolutions &rhs) const
{
// If the LHS is non-inverting and the RHS is inverting, then put the
// LHS first.
if (!lhs.inverted && rhs.inverted) {
return true;
}
// Better to have a path that can invert over a path that has no
// option to invert.
return (!lhs.can_invert) < (!rhs.can_invert);
}
bool inverting_preference(const PossibleSolutions &lhs, const PossibleSolutions &rhs) const
{
// If the LHS is inverting and the RHS is non-inverting, then put the
// LHS first (because this is the inverting preferred case).
if (lhs.inverted && !rhs.inverted) {
return true;
}
// Better to have a path that can invert over a path that has no
// option to invert.
return (!lhs.can_invert) < (!rhs.can_invert);
}
bool operator()(size_t lhs_solution_idx, size_t rhs_solution_idx) const
{
const PossibleSolutions &lhs = solutions.at(lhs_solution_idx);
const PossibleSolutions &rhs = solutions.at(rhs_solution_idx);
NPNR_ASSERT(lhs.net == rhs.net);
PhysicalNetlist::PhysNetlist::NetType net_type = ctx->ctx->get_net_type(lhs.net->net);
if (net_type == PhysicalNetlist::PhysNetlist::NetType::SIGNAL) {
return non_inverting_preference(lhs, rhs);
}
// All GND/VCC nets use out of site sources. Local constant sources
// are still connected via synthetic edges to the global GND/VCC
// network.
NPNR_ASSERT(lhs.net->driver.type == SiteWire::OUT_OF_SITE_SOURCE);
bool lhs_match_preference = net_type == lhs.prefered_constant_net_type;
bool rhs_match_preference = net_type == rhs.prefered_constant_net_type;
if (lhs_match_preference && !rhs_match_preference) {
// Prefer solutions where the net type already matches the
// prefered constant type.
return true;
}
if (!lhs_match_preference && rhs_match_preference) {
// Prefer solutions where the net type already matches the
// prefered constant type. In this case the RHS is better, which
// means that RHS < LHS, hence false here.
return false;
}
NPNR_ASSERT(lhs_match_preference == rhs_match_preference);
if (!lhs_match_preference) {
// If the net type does not match the preference, then prefer
// inverted solutions.
return inverting_preference(lhs, rhs);
} else {
// If the net type does match the preference, then prefer
// non-inverted solutions.
return non_inverting_preference(lhs, rhs);
}
}
};
static bool find_solution_via_backtrack(SiteArch *ctx, std::vector<PossibleSolutions> *solutions,
std::vector<std::vector<size_t>> sinks_to_solutions,
const std::vector<SiteWire> &sinks, bool explain)
{
std::vector<uint8_t> routed_sinks;
std::vector<size_t> solution_indicies;
routed_sinks.resize(sinks_to_solutions.size(), 0);
solution_indicies.resize(sinks_to_solutions.size(), 0);
// Scan solutions, and remove any solutions that are invalid immediately
//
// Note: This result cannot be cached because some solutions may be
// placement dependent.
for (size_t solution_idx = 0; solution_idx < solutions->size(); ++solution_idx) {
PossibleSolutions &solution = (*solutions)[solution_idx];
if (verbose_site_router(ctx) || explain) {
log_info("Testing solution %zu\n", solution_idx);
}
if (test_solution(ctx, solution.net, solution.pips_begin, solution.pips_end)) {
if (verbose_site_router(ctx) || explain) {
log_info("Solution %zu is good\n", solution_idx);
}
remove_solution(ctx, solution.pips_begin, solution.pips_end);
} else {
if (verbose_site_router(ctx) || explain) {
log_info("Solution %zu is not useable\n", solution_idx);
}
solution.tested = true;
}
}
// Sort sinks_to_solutions so that preferred solutions are tested earlier
// than less preferred solutions.
//
// See SolutionPreference implementation for details.
for (size_t sink_idx = 0; sink_idx < sinks_to_solutions.size(); ++sink_idx) {
std::vector<size_t> &solutions_for_sink = sinks_to_solutions.at(sink_idx);
std::stable_sort(solutions_for_sink.begin(), solutions_for_sink.end(), SolutionPreference(ctx, *solutions));
if (verbose_site_router(ctx) || explain) {
log_info("Solutions for sink %s (%zu)\n", ctx->nameOfWire(sinks.at(sink_idx)), sink_idx);
for (size_t solution_idx : solutions_for_sink) {
const PossibleSolutions &solution = solutions->at(solution_idx);
log_info("%zu: inverted = %d, can_invert = %d, tested = %d\n", solution_idx, solution.inverted,
solution.can_invert, solution.tested);
for (auto iter = solution.pips_begin; iter != solution.pips_end; ++iter) {
log_info(" - %s\n", ctx->nameOfPip(*iter));
}
}
}
}
// Sort solutions by the number of possible solutions first. This allows
// the backtrack to avoid the wide searches first.
// First create a tuple vector of (sink_idx, number of valid solutions for sink).
std::vector<std::pair<size_t, size_t>> solution_order;
for (size_t sink_idx = 0; sink_idx < sinks_to_solutions.size(); ++sink_idx) {
size_t solution_count = 0;
for (size_t solution_idx : sinks_to_solutions[sink_idx]) {
if (!(*solutions)[solution_idx].tested) {
solution_count += 1;
}
}
if (solution_count == 0) {
if (verbose_site_router(ctx) || explain) {
log_info("Sink %s has no solution in site\n", ctx->nameOfWire(sinks.at(sink_idx)));
}
return false;
}
solution_order.emplace_back(sink_idx, solution_count);
}
// Actually sort so that sinks with fewer valid solutions are tested
// earlier.
std::sort(solution_order.begin(), solution_order.end(),
[](const std::pair<size_t, size_t> &a, const std::pair<size_t, size_t> &b) -> bool {
return a.second < b.second;
});
std::vector<size_t> solution_stack;
solution_stack.reserve(sinks_to_solutions.size());
if (verbose_site_router(ctx)) {
log_info("Solving via backtrack with %zu solutions and %zu sinks\n", solutions->size(),
sinks_to_solutions.size());
}
// Simple backtrack explorer:
// - Apply the next solution at stack index.
// - If solution is valid, push solution onto stack, and advance stack
// index at solution 0.
// - If solution is not valid, pop the stack.
// - At this level of the stack, advance to the next solution. If
// there are not more solutions at this level, pop again.
// - If stack is now empty, mark root solution as tested and invalid.
// If root of stack has no more solutions, no solution is possible.
while (true) {
// Which sink is next to be tested?
size_t sink_idx = solution_order[solution_stack.size()].first;
size_t next_solution_to_test = solution_indicies[sink_idx];
if (verbose_site_router(ctx) || explain) {
log_info("next %zu : %zu (of %zu)\n", sink_idx, next_solution_to_test, sinks_to_solutions[sink_idx].size());
}
if (next_solution_to_test >= sinks_to_solutions[sink_idx].size()) {
// We have exausted all solutions at this level of the stack!
if (solution_stack.empty()) {
// Search is done, failed!!!
if (verbose_site_router(ctx) || explain) {
log_info("No solution found via backtrack with %zu solutions and %zu sinks\n", solutions->size(),
sinks_to_solutions.size());
}
return false;
} else {
// This level of the stack is completely tapped out, pop back
// to the next level up.
size_t sink_idx = solution_order[solution_stack.size() - 1].first;
size_t solution_idx = solution_stack.back();
if (verbose_site_router(ctx) || explain) {
log_info("pop %zu : %zu\n", sink_idx, solution_idx);
}
solution_stack.pop_back();
// Remove the now tested bad solution at the previous level of
// the stack.
auto &solution = solutions->at(solution_idx);
remove_solution(ctx, solution.pips_begin, solution.pips_end);
// Because we had to pop up the stack, advance the index at
// the level below us and start again.
solution_indicies[sink_idx] += 1;
continue;
}
}
size_t solution_idx = sinks_to_solutions[sink_idx].at(next_solution_to_test);
auto &solution = solutions->at(solution_idx);
if (solution.tested) {
// This solution was already determined to be no good, skip it.
if (verbose_site_router(ctx) || explain) {
log_info("skip %zu : %zu\n", sink_idx, solution_idx);
}
solution_indicies[sink_idx] += 1;
continue;
}
if (verbose_site_router(ctx) || explain) {
log_info("test %zu : %zu\n", sink_idx, solution_idx);
}
if (!test_solution(ctx, solution.net, solution.pips_begin, solution.pips_end)) {
// This solution was no good, try the next one at this level of
// the stack.
solution_indicies[sink_idx] += 1;
} else {
// This solution was good, push onto the stack.
if (verbose_site_router(ctx) || explain) {
log_info("push %zu : %zu\n", sink_idx, solution_idx);
}
solution_stack.push_back(solution_idx);
if (solution_stack.size() == sinks_to_solutions.size()) {
// Found a valid solution, done!
if (verbose_site_router(ctx)) {
log_info("Solved via backtrack with %zu solutions and %zu sinks\n", solutions->size(),
sinks_to_solutions.size());
}
return true;
} else {
// Because we pushing to a new level of stack, restart the
// search at this level.
sink_idx = solution_order[solution_stack.size()].first;
solution_indicies[sink_idx] = 0;
}
}
}
// Unreachable!!!
NPNR_ASSERT(false);
}
static bool route_site(SiteArch *ctx, SiteRoutingCache *site_routing_cache, RouteNodeStorage *node_storage,
bool explain)
{
// Overview:
// - Starting from each site net source, expand the site routing graph
// and record all reachable sinks.
// - Note: This step is cachable and is being cached. This cache
// behaving well is critical to the performance of route_site.
// - Convert site expansion solutions into flat solution map.
// - Use backtrack algorithm to find conflict free solution to route site.
//
std::vector<SiteExpansionLoop *> expansions;
expansions.reserve(ctx->nets.size());
for (auto &net_pair : ctx->nets) {
if (net_pair.first->driver.cell == nullptr)
continue;
SiteNetInfo *net = &net_pair.second;
if (net->net->loop == nullptr) {
net->net->loop = new SiteExpansionLoop(node_storage);
}
expansions.push_back(net->net->loop);
SiteExpansionLoop *router = expansions.back();
if (!router->expand_net(ctx, site_routing_cache, net)) {
if (verbose_site_router(ctx) || explain) {
log_info("Net %s expansion failed to reach all users, site is unroutable!\n", ctx->nameOfNet(net));
}
return false;
}
}
// Convert solutions into a flat solution set.
// Create a flat sink list and map.
std::vector<SiteWire> sinks;
dict<SiteWire, size_t> sink_map;
size_t number_solutions = 0;
for (const auto *expansion : expansions) {
number_solutions += expansion->num_solutions();
for (const SiteWire &unrouted_sink : expansion->net_users) {
auto result = sink_map.emplace(unrouted_sink, sink_map.size());
NPNR_ASSERT(result.second);
sinks.push_back(unrouted_sink);
}
}
if (sink_map.empty()) {
// All nets are trivially routed!
return true;
}
std::vector<PossibleSolutions> solutions;
solutions.reserve(number_solutions);
// Create a map from flat sink index to flat solution index.
std::vector<std::vector<size_t>> sinks_to_solutions;
sinks_to_solutions.resize(sink_map.size());
// Actually flatten solutions.
for (const auto *expansion : expansions) {
for (size_t idx = 0; idx < expansion->num_solutions(); ++idx) {
SiteWire wire = expansion->solution_sink(idx);
auto begin = expansion->solution_begin(idx);
auto end = expansion->solution_end(idx);
NPNR_ASSERT(begin != end);
size_t sink_idx = sink_map.at(wire);
sinks_to_solutions.at(sink_idx).push_back(solutions.size());
solutions.emplace_back();
auto &solution = solutions.back();
solution.net = ctx->wire_to_nets.at(wire).net;
solution.pips_begin = begin;
solution.pips_end = end;
solution.inverted = expansion->solution_inverted(idx);
solution.can_invert = expansion->solution_can_invert(idx);
for (auto iter = begin; iter != end; ++iter) {
const SitePip &site_pip = *iter;
NPNR_ASSERT(ctx->getPipDstWire(site_pip) == wire);
wire = ctx->getPipSrcWire(site_pip);
// If there is a input site port, mark on the solution what the
// prefered constant net type is for this site port.
if (site_pip.type == SitePip::SITE_PORT && wire.type == SiteWire::SITE_PORT_SOURCE) {
solution.prefered_constant_net_type = ctx->prefered_constant_net_type(site_pip);
}
}
NPNR_ASSERT(expansion->net_driver == wire);
}
}
return find_solution_via_backtrack(ctx, &solutions, sinks_to_solutions, sinks, explain);
}
void check_routing(const SiteArch &site_arch)
{
for (auto &net_pair : site_arch.nets) {
const NetInfo *net = net_pair.first;
if (net->driver.cell == nullptr)
continue;
const SiteNetInfo &net_info = net_pair.second;
for (const auto &user : net_info.users) {
NPNR_ASSERT(site_arch.wire_to_nets.at(user).net->net == net);
SiteWire cursor = user;
while (cursor != net_info.driver) {
auto iter = net_info.wires.find(cursor);
if (iter == net_info.wires.end()) {
log_error("Wire %s has no pip, but didn't reach driver wire %s\n", site_arch.nameOfWire(cursor),
site_arch.nameOfWire(net_info.driver));
}
const SitePip &site_pip = iter->second.pip;
cursor = site_arch.getPipSrcWire(site_pip);
}
NPNR_ASSERT(cursor == net_info.driver);
NPNR_ASSERT(site_arch.wire_to_nets.at(cursor).net->net == net);
}
}
}
static void apply_simple_routing(Context *ctx, const SiteArch &site_arch, NetInfo *net, const SiteNetInfo *site_net,
const SiteWire &user)
{
SiteWire wire = user;
while (wire != site_net->driver) {
SitePip site_pip = site_net->wires.at(wire).pip;
NPNR_ASSERT(site_arch.getPipDstWire(site_pip) == wire);
if (site_pip.type == SitePip::SITE_PIP || site_pip.type == SitePip::SITE_PORT) {
NetInfo *bound_net = ctx->getBoundPipNet(site_pip.pip);
if (bound_net == nullptr) {
ctx->bindPip(site_pip.pip, net, STRENGTH_PLACER);
} else {
NPNR_ASSERT(bound_net == net);
}
}
wire = site_arch.getPipSrcWire(site_pip);
}
}
static void apply_constant_routing(Context *ctx, const SiteArch &site_arch, NetInfo *net, const SiteNetInfo *site_net)
{
IdString gnd_net_name(ctx->chip_info->constants->gnd_net_name);
NetInfo *gnd_net = ctx->nets.at(gnd_net_name).get();
IdString vcc_net_name(ctx->chip_info->constants->vcc_net_name);
NetInfo *vcc_net = ctx->nets.at(vcc_net_name).get();
// This function is designed to operate only on the gnd or vcc net, and
// assumes that the GND and VCC nets have been unified.
NPNR_ASSERT(net == vcc_net || net == gnd_net);
for (auto &user : site_net->users) {
bool is_path_inverting = false, path_can_invert = false;
SiteWire wire = user;
PipId inverting_pip;
while (wire != site_net->driver) {
SitePip pip = site_net->wires.at(wire).pip;
NPNR_ASSERT(site_arch.getPipDstWire(pip) == wire);
if (site_arch.isInverting(pip)) {
// FIXME: Should be able to handle the general case of
// multiple inverters, but that is harder (and annoying). Also
// most sites won't allow for a double inversion, so just
// disallow for now.
NPNR_ASSERT(!is_path_inverting);
is_path_inverting = true;
NPNR_ASSERT(pip.type == SitePip::SITE_PIP);
inverting_pip = pip.pip;
}
if (site_arch.canInvert(pip)) {
path_can_invert = true;
NPNR_ASSERT(pip.type == SitePip::SITE_PIP);
inverting_pip = pip.pip;
}
wire = site_arch.getPipSrcWire(pip);
}
if (!is_path_inverting && !path_can_invert) {
// This routing is boring, use base logic.
apply_simple_routing(ctx, site_arch, net, site_net, user);
continue;
}
NPNR_ASSERT(inverting_pip != PipId());
// This net is going to become two nets.
// The portion of the net prior to the inverter is going to be bound
// to the opposite net. For example, if the original net was gnd_net,
// the portion prior to the inverter will not be the vcc_net.
//
// A new cell will be generated to sink the connection from the
// opposite net.
NetInfo *net_before_inverter;
if (net == gnd_net) {
net_before_inverter = vcc_net;
} else {
NPNR_ASSERT(net == vcc_net);
net_before_inverter = gnd_net;
}
// First find a name for the new cell
int count = 0;
CellInfo *new_cell = nullptr;
while (true) {
std::string new_cell_name = stringf("%s_%s.%d", net->name.c_str(ctx), site_arch.nameOfWire(user), count);
IdString new_cell_id = ctx->id(new_cell_name);
if (ctx->cells.count(new_cell_id)) {
count += 1;
} else {
new_cell = ctx->createCell(new_cell_id, ctx->id("$nextpnr_inv"));
break;
}
}
auto &tile_type = loc_info(ctx->chip_info, inverting_pip);
auto &pip_data = tile_type.pip_data[inverting_pip.index];
NPNR_ASSERT(pip_data.site != -1);
auto &bel_data = tile_type.bel_data[pip_data.bel];
BelId inverting_bel;
inverting_bel.tile = inverting_pip.tile;
inverting_bel.index = pip_data.bel;
IdString in_port(bel_data.ports[pip_data.extra_data]);
NPNR_ASSERT(bel_data.types[pip_data.extra_data] == PORT_IN);
IdString id_I = ctx->id("I");
new_cell->addInput(id_I);
new_cell->cell_bel_pins[id_I].push_back(in_port);
new_cell->bel = inverting_bel;
new_cell->belStrength = STRENGTH_PLACER;
ctx->tileStatus.at(inverting_bel.tile).boundcells[inverting_bel.index] = new_cell;
connect_port(ctx, net_before_inverter, new_cell, id_I);
// The original BEL pin is now routed, but only through the inverter.
// Because the cell/net model doesn't allow for multiple source pins
// and the fact that the portion of the net after the inverter is
// currently routed, all BEL pins on this site wire are going to be
// masked from the router.
NPNR_ASSERT(user.type == SiteWire::SITE_WIRE);
ctx->mask_bel_pins_on_site_wire(net, user.wire);
// Bind wires and pips to the two nets.
bool after_inverter = true;
wire = user;
while (wire != site_net->driver) {
SitePip site_pip = site_net->wires.at(wire).pip;
NPNR_ASSERT(site_arch.getPipDstWire(site_pip) == wire);
if (site_arch.isInverting(site_pip) || site_arch.canInvert(site_pip)) {
NPNR_ASSERT(after_inverter);
after_inverter = false;
// Because this wire is just after the inverter, bind it to
// the net without the pip, as this is a "source".
NPNR_ASSERT(wire.type == SiteWire::SITE_WIRE);
ctx->bindWire(wire.wire, net, STRENGTH_PLACER);
} else {
if (site_pip.type == SitePip::SITE_PIP || site_pip.type == SitePip::SITE_PORT) {
if (after_inverter) {
ctx->bindPip(site_pip.pip, net, STRENGTH_PLACER);
} else {
ctx->bindPip(site_pip.pip, net_before_inverter, STRENGTH_PLACER);
}
}
}
wire = site_arch.getPipSrcWire(site_pip);
}
}
}
static void apply_routing(Context *ctx, const SiteArch &site_arch, pool<std::pair<IdString, int32_t>> &lut_thrus)
{
IdString gnd_net_name(ctx->chip_info->constants->gnd_net_name);
NetInfo *gnd_net = ctx->nets.at(gnd_net_name).get();
IdString vcc_net_name(ctx->chip_info->constants->vcc_net_name);
NetInfo *vcc_net = ctx->nets.at(vcc_net_name).get();
for (auto &net_pair : site_arch.nets) {
NetInfo *net = net_pair.first;
const SiteNetInfo *site_net = &net_pair.second;
if (net == gnd_net || net == vcc_net) {
apply_constant_routing(ctx, site_arch, net, site_net);
} else {
// If the driver wire is a site wire, bind it.
if (site_net->driver.type == SiteWire::SITE_WIRE) {
WireId driver_wire = site_net->driver.wire;
if (ctx->getBoundWireNet(driver_wire) != net) {
ctx->bindWire(driver_wire, net, STRENGTH_PLACER);
}
}
for (auto &wire_pair : site_net->wires) {
const SitePip &site_pip = wire_pair.second.pip;
if (site_pip.type != SitePip::SITE_PIP && site_pip.type != SitePip::SITE_PORT) {
continue;
}
auto &pip_data = pip_info(ctx->chip_info, site_pip.pip);
BelId bel;
bel.tile = site_pip.pip.tile;
bel.index = pip_data.bel;
const auto &bel_data = bel_info(ctx->chip_info, bel);
// Detect and store LUT thrus for allowance check during routing
if (bel_data.lut_element != -1) {
WireId src_wire = ctx->getPipSrcWire(site_pip.pip);
for (BelPin bel_pin : ctx->getWireBelPins(src_wire)) {
if (bel_pin.bel != bel)
continue;
lut_thrus.insert(std::make_pair(bel_pin.pin, bel_pin.bel.index));
break;
}
}
ctx->bindPip(site_pip.pip, net, STRENGTH_PLACER);
}
}
}
}
static bool map_luts_in_site(const SiteInformation &site_info, pool<std::pair<IdString, IdString>> *blocked_wires)
{
const Context *ctx = site_info.ctx;
const std::vector<LutElement> &lut_elements = ctx->lut_elements.at(site_info.tile_type);
std::vector<LutMapper> lut_mappers;
lut_mappers.reserve(lut_elements.size());
for (size_t i = 0; i < lut_elements.size(); ++i) {
lut_mappers.push_back(LutMapper(lut_elements[i]));
}
for (CellInfo *cell : site_info.cells_in_site) {
if (cell->lut_cell.pins.empty()) {
continue;
}
BelId bel = cell->bel;
const auto &bel_data = bel_info(ctx->chip_info, bel);
if (bel_data.lut_element != -1) {
lut_mappers[bel_data.lut_element].cells.push_back(cell);
}
}
blocked_wires->clear();
for (LutMapper lut_mapper : lut_mappers) {
if (lut_mapper.cells.empty()) {
continue;
}
pool<const LutBel *, hash_ptr_ops> blocked_luts;
if (!lut_mapper.remap_luts(ctx, &blocked_luts)) {
return false;
}
for (const LutBel *lut_bel : blocked_luts) {
blocked_wires->emplace(std::make_pair(lut_bel->name, lut_bel->output_pin));
}
}
return true;
}
// Block outputs of unavailable LUTs to prevent site router from using them.
static void block_lut_outputs(SiteArch *site_arch, const pool<std::pair<IdString, IdString>> &blocked_wires)
{
const Context *ctx = site_arch->site_info->ctx;
auto &tile_info = ctx->chip_info->tile_types[site_arch->site_info->tile_type];
for (const auto &bel_pin_pair : blocked_wires) {
IdString bel_name = bel_pin_pair.first;
IdString bel_pin = bel_pin_pair.second;
int32_t bel_index = -1;
for (int32_t i = 0; i < tile_info.bel_data.ssize(); i++) {
if (tile_info.bel_data[i].site == site_arch->site_info->site &&
tile_info.bel_data[i].name == bel_name.index) {
bel_index = i;
break;
}
}
NPNR_ASSERT(bel_index != -1);
BelId bel;
bel.tile = site_arch->site_info->tile;
bel.index = bel_index;
SiteWire lut_output_wire = site_arch->getBelPinWire(bel, bel_pin);
site_arch->bindWire(lut_output_wire, &site_arch->blocking_site_net);
}
}
// Block wires corresponding to dedicated interconnections that are not
// exposed to the general interconnect.
// These wires cannot be chosen for the first element in a BEL chain, as they
// would result in an unroutability error.
static void block_cluster_wires(SiteArch *site_arch)
{
const Context *ctx = site_arch->site_info->ctx;
auto &cells_in_site = site_arch->site_info->cells_in_site;
for (auto &cell : cells_in_site) {
if (cell->cluster == ClusterId())
continue;
if (ctx->getClusterRootCell(cell->cluster) != cell)
continue;
Cluster cluster = ctx->clusters.at(cell->cluster);
uint32_t cluster_id = cluster.index;
auto &cluster_data = cluster_info(ctx->chip_info, cluster_id);
if (cluster_data.chainable_ports.size() == 0)
continue;
IdString cluster_chain_input(cluster_data.chainable_ports[0].cell_sink);
if (cluster_chain_input == IdString())
continue;
auto &cell_bel_pins = cell->cell_bel_pins.at(cluster_chain_input);
for (auto &bel_pin : cell_bel_pins) {
SiteWire bel_pin_wire = site_arch->getBelPinWire(cell->bel, bel_pin);
site_arch->bindWire(bel_pin_wire, &site_arch->blocking_site_net);
}
}
}
// Reserve site ports that are on dedicated rather than general interconnect
static void reserve_site_ports(SiteArch *site_arch)
{
const Context *ctx = site_arch->site_info->ctx;
site_arch->blocked_site_ports.clear();
for (PipId in_pip : site_arch->input_site_ports) {
pool<NetInfo *, hash_ptr_ops> dedicated_nets;
const int max_iters = 100;
std::queue<WireId> visit_queue;
pool<WireId> already_visited;
WireId src = ctx->getPipSrcWire(in_pip);
visit_queue.push(src);
already_visited.insert(src);
int iter = 0;
while (!visit_queue.empty() && iter++ < max_iters) {
WireId next = visit_queue.front();
visit_queue.pop();
for (auto bp : ctx->getWireBelPins(next)) {
// Bel pins could mean dedicated routes
CellInfo *bound = ctx->getBoundBelCell(bp.bel);
if (bound == nullptr)
continue;
// Need to find the corresponding cell pin
for (auto &port : bound->ports) {
if (port.second.net == nullptr)
continue;
for (auto bel_pin : ctx->getBelPinsForCellPin(bound, port.first)) {
if (bel_pin == bp.pin)
dedicated_nets.insert(port.second.net);
}
}
}
for (auto pip : ctx->getPipsUphill(next)) {
WireId next_src = ctx->getPipSrcWire(pip);
if (already_visited.count(next_src))
continue;
visit_queue.push(next_src);
already_visited.insert(next_src);
}
}
if (iter < max_iters) {
if (ctx->debug)
log_info("Blocking PIP %s\n", ctx->nameOfPip(in_pip));
// If we didn't search up to the iteration limit, assume this node is not reachable from general routing
site_arch->blocked_site_ports[in_pip] = dedicated_nets;
}
}
}
// Recursively visit downhill PIPs until a SITE_PORT_SINK is reached.
// Marks all PIPs for all valid paths.
static bool visit_downhill_pips(const SiteArch *site_arch, const SiteWire &site_wire, std::vector<PipId> &valid_pips)
{
bool valid_path_exists = false;
for (SitePip site_pip : site_arch->getPipsDownhill(site_wire)) {
const SiteWire &dst_wire = site_arch->getPipDstWire(site_pip);
if (dst_wire.type == SiteWire::SITE_PORT_SINK) {
valid_pips.push_back(site_pip.pip);
return true;
}
bool path_ok = visit_downhill_pips(site_arch, dst_wire, valid_pips);
valid_path_exists |= path_ok;
if (path_ok) {
valid_pips.push_back(site_pip.pip);
}
}
return valid_path_exists;
}
// Checks all downhill PIPs starting from driver wires.
// All valid PIPs are stored and returned in a vector.
static void check_downhill_pips(Context *ctx, const SiteArch *site_arch, std::vector<PipId> &valid_pips)
{
auto &cells_in_site = site_arch->site_info->cells_in_site;
for (auto &net_pair : site_arch->nets) {
NetInfo *net = net_pair.first;
const SiteNetInfo *site_net = &net_pair.second;
if (net->driver.cell && cells_in_site.count(net->driver.cell)) {
const SiteWire &site_wire = site_net->driver;
visit_downhill_pips(site_arch, site_wire, valid_pips);
}
}
}
bool SiteRouter::checkSiteRouting(const Context *ctx, const TileStatus &tile_status) const
{
// Overview:
// - Make sure all cells in site satisfy the constraints.
// - Ensure that the LUT equation elements in the site are legal
// - Check that the site is routable.
// Because site routing checks are expensive, cache them.
// SiteRouter::bindBel/unbindBel should correctly invalid the cache by
// setting dirty=true.
if (!dirty) {
return site_ok;
}
dirty = false;
// Empty sites are trivially correct.
if (cells_in_site.size() == 0) {
site_ok = true;
return site_ok;
}
site_ok = false;
// Make sure all cells in this site belong!
auto iter = cells_in_site.begin();
NPNR_ASSERT((*iter)->bel != BelId());
auto tile = (*iter)->bel.tile;
if (verbose_site_router(ctx)) {
log_info("Checking site routing for site %s\n", ctx->get_site_name(tile, site));
}
for (CellInfo *cell : cells_in_site) {
// All cells in the site must be placed.
NPNR_ASSERT(cell->bel != BelId());
// Sanity check that all cells in this site are part of the same site.
NPNR_ASSERT(tile == cell->bel.tile);
NPNR_ASSERT(site == bel_info(ctx->chip_info, cell->bel).site);
// As a first pass make sure each assigned cell in site is valid by
// constraints.
if (!ctx->is_cell_valid_constraints(cell, tile_status, verbose_site_router(ctx))) {
if (verbose_site_router(ctx)) {
log_info("Sanity check failed, cell_type %s at %s has an invalid constraints, so site is not good\n",
cell->type.c_str(ctx), ctx->nameOfBel(cell->bel));
}
site_ok = false;
return site_ok;
}
}
SiteInformation site_info(ctx, tile, site, cells_in_site);
pool<std::pair<IdString, IdString>> blocked_wires;
if (!map_luts_in_site(site_info, &blocked_wires)) {
site_ok = false;
return site_ok;
}
// Push from cell pins to the first WireId from each cell pin.
//
// If a site wire conflict occurs here, the site is trivially unroutable.
if (!check_initial_wires(ctx, &site_info)) {
site_ok = false;
return site_ok;
}
// Construct a model of the site routing that is suitable for routing
// algorithms.
SiteArch site_arch(&site_info);
// SiteArch::archcheck is a good sanity check on SiteArch and the chipdb,
// but isn't cheap, so disabled for now.
//
// site_arch.archcheck();
block_lut_outputs(&site_arch, blocked_wires);
block_cluster_wires(&site_arch);
// Do a detailed routing check to see if the site has at least 1 valid
// routing solution.
site_ok = route_site(&site_arch, &ctx->site_routing_cache, &ctx->node_storage, /*explain=*/false);
if (verbose_site_router(ctx)) {
if (site_ok) {
log_info("Site %s is routable\n", ctx->get_site_name(tile, site));
} else {
log_info("Site %s is not routable\n", ctx->get_site_name(tile, site));
}
}
if (site_ok) {
check_routing(site_arch);
}
return site_ok;
}
void SiteRouter::bindSiteRouting(Context *ctx)
{
NPNR_ASSERT(!dirty);
NPNR_ASSERT(site_ok);
// Make sure all cells in this site belong!
auto iter = cells_in_site.begin();
NPNR_ASSERT((*iter)->bel != BelId());
auto tile = (*iter)->bel.tile;
auto &tile_type = loc_info(ctx->chip_info, (*iter)->bel);
// Unbind all bound site wires
WireId wire;
wire.tile = tile;
for (size_t wire_index = 0; wire_index < tile_type.wire_data.size(); ++wire_index) {
const TileWireInfoPOD &wire_data = tile_type.wire_data[wire_index];
if (wire_data.site != this->site) {
continue;
}
wire.index = wire_index;
NetInfo *net = ctx->getBoundWireNet(wire);
if (net == nullptr) {
continue;
}
auto &pip_map = net->wires.at(wire);
if (pip_map.strength <= STRENGTH_STRONG) {
ctx->unbindWire(wire);
}
}
SiteInformation site_info(ctx, tile, site, cells_in_site);
pool<std::pair<IdString, IdString>> blocked_wires;
NPNR_ASSERT(map_luts_in_site(site_info, &blocked_wires));
SiteArch site_arch(&site_info);
block_lut_outputs(&site_arch, blocked_wires);
block_cluster_wires(&site_arch);
reserve_site_ports(&site_arch);
NPNR_ASSERT(route_site(&site_arch, &ctx->site_routing_cache, &ctx->node_storage, /*explain=*/false));
check_routing(site_arch);
apply_routing(ctx, site_arch, lut_thrus);
check_downhill_pips(ctx, &site_arch, valid_pips);
if (verbose_site_router(ctx)) {
print_current_state(&site_arch);
}
}
void SiteRouter::explain(const Context *ctx) const
{
NPNR_ASSERT(!dirty);
if (site_ok) {
return;
}
// Make sure all cells in this site belong!
auto iter = cells_in_site.begin();
NPNR_ASSERT((*iter)->bel != BelId());
auto tile = (*iter)->bel.tile;
SiteInformation site_info(ctx, tile, site, cells_in_site);
SiteArch site_arch(&site_info);
bool route_status = route_site(&site_arch, &ctx->site_routing_cache, &ctx->node_storage, /*explain=*/true);
if (!route_status) {
print_current_state(&site_arch);
}
}
ArchNetInfo::~ArchNetInfo() { delete loop; }
Arch::~Arch()
{
for (auto &net_pair : nets) {
if (net_pair.second->loop) {
net_pair.second->loop->clear();
}
}
}
NEXTPNR_NAMESPACE_END
| 37.480675 | 120 | 0.589688 | [
"vector",
"model"
] |
921be0947bee5f18f35774d297c2ac97a9be7a5d | 5,954 | cpp | C++ | engine/src/wolf.content_pipeline/wavefront/obj.cpp | SiminBadri/Wolf.Engine | 3da04471ec26e162e1cbb7cc88c7ce37ee32c954 | [
"BSL-1.0",
"Apache-2.0",
"libpng-2.0"
] | 1 | 2020-07-15T13:14:26.000Z | 2020-07-15T13:14:26.000Z | engine/src/wolf.content_pipeline/wavefront/obj.cpp | foroughmajidi/Wolf.Engine | f08a8cbd519ca2c70b1c8325250dc9af7ac4c498 | [
"BSL-1.0",
"Apache-2.0",
"libpng-2.0"
] | null | null | null | engine/src/wolf.content_pipeline/wavefront/obj.cpp | foroughmajidi/Wolf.Engine | f08a8cbd519ca2c70b1c8325250dc9af7ac4c498 | [
"BSL-1.0",
"Apache-2.0",
"libpng-2.0"
] | null | null | null | #include "w_cpipeline_pch.h"
#include "obj.h"
#define TINYOBJLOADER_IMPLEMENTATION
#include "tiny_obj_loader.h"
#include <w_thread_pool.h>
#include <sstream>
using namespace wolf::system;
using namespace wolf::content_pipeline;
using namespace wolf::content_pipeline::wavefront;
void obj::write(
_In_ std::vector<w_vertex_struct>& pVerticesData,
_In_ std::vector<uint32_t>& pIndicesData,
_In_z_ const std::string& pOutputFilePath)
{
const std::string _trace_info = "w_wavefront_obj::write";
w_thread_pool _thread_pool;
_thread_pool.allocate(2);
std::array<float, 3> _pos_floats;
std::array<float, 3> _nor_floats;
std::array<float, 2> _uv_floats;
std::vector<std::array<float, 3>> _pos;
std::vector<std::array<float, 3>> _nor;
std::vector<std::array<float, 2>> _uv;
std::stringstream _v;
std::stringstream _vn;
std::stringstream _vt;
std::stringstream _f;
_v << "#vertices" << std::endl;
_vt << "#texture coords" << std::endl;
_vn << "#normals" << std::endl;
_f << "#faces" << std::endl;
int _v_i[3], _vn_i[3], _vt_i[3], _face_index = 0;
for (size_t i = 0; i < pIndicesData.size(); ++i)
{
auto _index = pIndicesData[i];
auto _vertex = &(pVerticesData[_index]);
if (!_vertex)
{
V(W_FAILED,
w_log_type::W_ERROR,
"vertex does not have memory. trace info: {}",
_trace_info);
continue;
}
//vertex position in first thread
_thread_pool.add_job_for_thread(0, [&]()
{
_pos_floats[0] = _vertex->position[0];
_pos_floats[1] = _vertex->position[1];
_pos_floats[2] = _vertex->position[2];
auto _iter_pos = std::find(_pos.begin(), _pos.end(), _pos_floats);
if (_iter_pos == _pos.end())
{
_pos.push_back(_pos_floats);
_v_i[_face_index] = _pos.size();
_v << "v " << _pos_floats[0] << " " << _pos_floats[1] << " " << _pos_floats[2] << std::endl;
}
else
{
_v_i[_face_index] = std::distance(_pos.begin(), _iter_pos) + 1;
}
});
//write normal and uv in another thread
_thread_pool.add_job_for_thread(1, [&]()
{
_uv_floats[0] = _vertex->uv[0];
_uv_floats[1] = _vertex->uv[1];
auto _iter_uv = std::find(_uv.begin(), _uv.end(), _uv_floats);
if (_iter_uv == _uv.end())
{
_uv.push_back(_uv_floats);
_vt_i[_face_index] = _uv.size();
_vt << "vt " << _uv_floats[0] << " " << _uv_floats[1] << std::endl;
}
else
{
_vt_i[_face_index] = std::distance(_uv.begin(), _iter_uv) + 1;
}
_nor_floats[0] = _vertex->normal[0];
_nor_floats[1] = _vertex->normal[1];
_nor_floats[2] = _vertex->normal[2];
auto _iter_nor = std::find(_nor.begin(), _nor.end(), _nor_floats);
if (_iter_nor == _nor.end())
{
_nor.push_back(_nor_floats);
_vn_i[_face_index] = _nor.size();
_vn << "vn " << _nor_floats[0] << " " << _nor_floats[1] << " " << _nor_floats[2] << std::endl;
}
else
{
_vn_i[_face_index] = std::distance(_nor.begin(), _iter_nor) + 1;
}
});
_thread_pool.wait_all();
_face_index++;
if (_face_index == 3)
{
_face_index = 0;
_f << "f " << _v_i[0] << "/" << _vt_i[0] << "/" << _vn_i[0] << "\t" <<
_v_i[1] << "/" << _vt_i[1] << "/" << _vn_i[1] << "\t" <<
_v_i[2] << "/" << _vt_i[2] << "/" << _vn_i[2] << std::endl;
}
}
_v.flush();
_vn.flush();
_vt.flush();
_f.flush();
wolf::system::io::write_text_file(
pOutputFilePath.c_str(),
("# Wavefront OBJ file\r\n# Created by the Wolf.Engine\r\n" +
_v.str() + "\r\n" +
_vt.str() + "\r\n" +
_vn.str() + "\r\n" +
_f.str() + "\r\n").c_str());
//release resources
_thread_pool.release();
_pos.clear();
_nor.clear();
_uv.clear();
_v.clear();
_vn.clear();
_vt.clear();
_f.clear();
}
W_RESULT obj::read(
_Inout_ std::vector<w_vertex_struct>& pVerticesData,
_Inout_ std::vector<uint32_t>& pIndicesData,
//_Inout_ std::vector<float>& pJustVertexPosition,
_In_z_ const std::string& pInputFilePath)
{
const std::string _trace_info = "w_wavefront_obj::read";
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
//std::vector<tinyobj::material_t> materials;
std::string _err;
bool _hr = tinyobj::LoadObj(&attrib, &shapes, nullptr, &_err, pInputFilePath.c_str());
if (!_hr)
{
V(W_FAILED,
w_log_type::W_ERROR,
"error on loading object model: {} with followinf error info: {}. trace info: {}",
pInputFilePath,
_err,
_trace_info);
return W_FAILED;
}
pVerticesData.clear();
pIndicesData.clear();
//pJustVertexPosition.clear();
for (size_t s = 0; s < shapes.size(); s++)
{
// Loop over faces(polygon)
size_t index_offset = 0;
for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++)
{
int fv = shapes[s].mesh.num_face_vertices[f];
// Loop over vertices in the face.
for (size_t v = 0; v < fv; v++)
{
w_vertex_struct _vertex;
// access to vertex
auto _idx = shapes[s].mesh.indices[index_offset + v];
auto _vx = attrib.vertices[3 * _idx.vertex_index + 0];
auto _vy = attrib.vertices[3 * _idx.vertex_index + 1];
auto _vz = attrib.vertices[3 * _idx.vertex_index + 2];
auto _nx = attrib.normals[3 * _idx.normal_index + 0];
auto _ny = attrib.normals[3 * _idx.normal_index + 1];
auto _nz = attrib.normals[3 * _idx.normal_index + 2];
auto _tx = attrib.texcoords[2 * _idx.texcoord_index + 0];
auto _ty = attrib.texcoords[2 * _idx.texcoord_index + 1];
_vertex.vertex_index = (uint32_t)_idx.vertex_index;
_vertex.position[0] = _vx;
_vertex.position[1] = _vy;
_vertex.position[2] = _vz;
_vertex.normal[0] = _nx;
_vertex.normal[1] = _ny;
_vertex.normal[2] = _nz;
_vertex.uv[0] = _tx;
_vertex.uv[1] = _ty;
pVerticesData.push_back(_vertex);
pIndicesData.push_back(index_offset + v);
/*pJustVertexPosition.push_back(_vx);
pJustVertexPosition.push_back(_vy);
pJustVertexPosition.push_back(_vz);*/
}
index_offset += fv;
// per-face material
//shapes[s].mesh.material_ids[f];
}
}
return W_PASSED;
} | 25.886957 | 98 | 0.631676 | [
"mesh",
"object",
"vector",
"model"
] |
9223844398767b29f59ba714cfde786e5c23c801 | 17,196 | cpp | C++ | src/graphics/tcContainerGui.cpp | dhanin/friendly-bassoon | fafcfd3921805baddc1889dc0ee2fa367ad882f8 | [
"BSD-3-Clause"
] | 2 | 2021-11-17T10:59:38.000Z | 2021-11-17T10:59:45.000Z | src/graphics/tcContainerGui.cpp | dhanin/nws | 87a3f24a7887d84b9884635064b48d456b4184e2 | [
"BSD-3-Clause"
] | null | null | null | src/graphics/tcContainerGui.cpp | dhanin/nws | 87a3f24a7887d84b9884635064b48d456b4184e2 | [
"BSD-3-Clause"
] | null | null | null | /**
** @file tcContainerGui.cpp
*/
/*
** Copyright (c) 2014, GCBLUE PROJECT
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
**
** 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
**
** 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
**
** 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from
** this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
** NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
** COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
** IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdwx.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "tcContainerGui.h"
#include "common/tinyxml.h"
#include "tcGeometry.h"
#include "tcDragStatus.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
BEGIN_EVENT_TABLE(tcContainerGui, tcXmlWindow)
EVT_COMMAND(86, wxEVT_COMMAND_BUTTON_CLICKED, tcContainerGui::OnCloseCommand)
END_EVENT_TABLE()
void tcContainerSlot::ClearItem()
{
SetItem(0);
}
boost::shared_ptr<tcGeometry> tcContainerSlot::GetIcon()
{
if (item == 0)
{
boost::shared_ptr<tcGeometry> nullIcon((tcGeometry*)0);
return nullIcon;
}
else if (!useSmallIcon)
{
return item->GetIcon();
}
else
{
return item->GetIconSmall();
}
}
tcContainerItem* tcContainerSlot::GetItem() const
{
return item;
}
bool tcContainerSlot::IsEmpty() const
{
return item == 0;
}
bool tcContainerSlot::IsMouseOver() const
{
return isMouseOver;
}
bool tcContainerSlot::IsSelected() const
{
return isSelected;
}
bool tcContainerSlot::IsUpdated() const
{
return updated;
}
void tcContainerSlot::SetItem(tcContainerItem* item_)
{
if (item == item_) return;
if (item != 0)
{
delete item;
}
item = item_;
}
void tcContainerSlot::SetMouseOver(bool state)
{
isMouseOver = state;
}
void tcContainerSlot::SetSelected(bool state)
{
isSelected = state;
}
void tcContainerSlot::SetUpdated(bool state)
{
updated = state;
}
void tcContainerSlot::SetUseSmallIcon(bool state)
{
useSmallIcon = state;
}
tcContainerSlot::tcContainerSlot()
: item(0),
updated(false),
isMouseOver(false),
useSmallIcon(false),
isSelected(false)
{
}
tcContainerSlot::tcContainerSlot(const tcContainerSlot& src)
: loc(src.loc),
item(src.item),
updated(src.updated),
isMouseOver(src.isMouseOver),
useSmallIcon(src.useSmallIcon),
isSelected(src.isSelected)
{
}
tcContainerSlot::~tcContainerSlot()
{
}
//------------------------------------------------------------------------------
tc3DWindow2* tcContainerGui::parent = 0;
std::list<tcContainerGui*> tcContainerGui::openContainers;
void tcContainerGui::CloseAll()
{
for (std::list<tcContainerGui*>::iterator iter = openContainers.begin();
iter != openContainers.end(); ++iter)
{
(*iter)->DestroyWindow();
}
}
/**
* Set all slots to not selected
*/
void tcContainerGui::DeselectAllSlots()
{
size_t nSlots = slots.size();
for (size_t n=0; n<nSlots; n++)
{
slots[n].SetSelected(false);
}
}
void tcContainerGui::SetParent(tc3DWindow2* win)
{
parent = win;
}
void tcContainerGui::AddSlot(tcRect& loc, IconSize iconSize)
{
tcContainerSlot slot;
slot.loc = loc;
slot.item = 0;
slot.updated = false;
if (iconSize == SMALL_ICON_SIZE)
{
slot.SetUseSmallIcon(true);
}
slots.push_back(slot);
}
void tcContainerGui::ClearSlots()
{
size_t nSlots = slots.size();
for (size_t n=0; n<nSlots; n++)
{
if (slots[n].item != 0) delete slots[n].item;
}
slots.clear();
}
/**
* Performs linear search for item
* @returns item with matching id or 0 if not found
*/
tcContainerItem* tcContainerGui::GetItem(long id)
{
wxASSERT(id != 0);
size_t nSlots = slots.size();
for (size_t n=0; n<nSlots; n++)
{
if (tcContainerItem* item = slots[n].GetItem())
{
if (item->IdMatches(id)) return item;
}
}
return 0;
}
size_t tcContainerGui::GetNumSlots() const
{
return slots.size();
}
tcContainerItem* tcContainerGui::GetParentItem() const
{
return parentItem;
}
/**
* @return selected slot indices
*/
const std::vector<size_t>& tcContainerGui::GetSelected() const
{
static std::vector<size_t> selectedIdx;
selectedIdx.clear();
size_t nSlots = slots.size();
for (size_t n=0; n<nSlots; n++)
{
if (slots[n].IsSelected())
{
selectedIdx.push_back(n);
}
}
return selectedIdx;
}
void tcContainerGui::Draw()
{
StartDraw();
size_t nSlots = slots.size();
for (size_t n=0; n<nSlots; n++)
{
tcContainerSlot& slot = slots[n];
DrawRectangleR(slot.loc, Vec4(1, 1, 0, 1), tc3DWindow2::FILL_OFF);
}
DrawSelectionBox();
FinishDraw();
}
void tcContainerGui::DrawSelectionBox()
{
if (draggingSelectionBox)
{
float w = float(mousePoint.x-selectionBoxStart.x);
float h = float(mousePoint.y-selectionBoxStart.y);
DrawRectangleR(float(selectionBoxStart.x), float(selectionBoxStart.y), w, h,
Vec4(1, 1, 1, 1), tc3DWindow2::FILL_OFF);
}
}
/**
* @param slotIdx index of slot that is receiving drop
* @param items vector of pointer to dropped item(s)
* Method for dropping into a container GUI slot
*/
void tcContainerGui::HandleDrop(size_t slotIdx, const std::vector<tcContainerItem*>& items)
{
}
/**
* @param item pointer to dropped item
* Method for dropping into a container GUI window (not over slot)
*/
void tcContainerGui::HandleDropWindow(const std::vector<tcContainerItem*>& items)
{
}
void tcContainerGui::OnChar(wxKeyEvent& event)
{
long keycode = event.GetKeyCode();
switch (keycode)
{
case WXK_ESCAPE:
{
DestroyWindow();
if (parentItem)
{
// clear this gui from parent item so we don't try to delete twice
parentItem->SetGui(0);
}
}
break;
default:
event.Skip();
}
}
/**
* Close and destroy window at next safe opportunity
*/
void tcContainerGui::OnCloseCommand(wxCommandEvent& event)
{
DestroyWindow();
if (parentItem)
{
// clear this gui from parent item so we don't try to delete twice
parentItem->SetGui(0);
}
}
void tcContainerGui::OnLButtonDown(wxMouseEvent& event)
{
/* check if cursor is over a non-empty slot, if so
** arm drag with slot idx */
wxPoint point = event.GetPosition();
float x = (float)point.x;
float y = (float)point.y;
isLButtonDown = true;
if ((point.y <= 20) || (point.y >= mnHeight))
{
windowDragOn = true;
// position in parent's frame of mouse pointer
windowDragPoint = wxPoint(mrectWindow.GetLeft() + point.x, mrectWindow.GetBottom() + point.y);
CaptureMouse();
return;
}
dragIsArmed = false;
protectDeselectIdx = 999;
size_t selectedSlot;
bool foundSlot = SlotContainingPoint(point, selectedSlot);
if (!foundSlot)
{ // start drag box
draggingSelectionBox = true;
selectionBoxStart = point;
mousePoint = point;
}
bool controlDown = event.ControlDown(); // ctrl to select one slot at a time
if (!controlDown)
{
// if we didn't click on a selected slot, clear all previous selections
if (!foundSlot || !slots[selectedSlot].IsSelected())
{
for (size_t k=0; k<slots.size(); k++)
{
slots[k].SetSelected(false);
}
}
if (foundSlot && !slots[selectedSlot].IsEmpty())
{
slots[selectedSlot].SetSelected(true);
dragIsArmed = true;
}
}
else // when ctrl down, add slots to selected on left down, remove them on left up
{
if (foundSlot && (!slots[selectedSlot].IsEmpty()) && (!slots[selectedSlot].IsSelected()))
{
if (!slots[selectedSlot].IsSelected())
{
protectDeselectIdx = selectedSlot;
}
slots[selectedSlot].SetSelected(true);
dragIsArmed = true;
}
}
}
void tcContainerGui::OnLButtonDClick(wxMouseEvent& event)
{
dragIsArmed = false;
protectDeselectIdx = 999;
std::vector<size_t> selectedSlots = GetSelected();
for (size_t n=0; n<selectedSlots.size(); n++)
{
slots[selectedSlots[n]].SetSelected(false);
}
}
void tcContainerGui::OnLButtonUp(wxMouseEvent& event)
{
isLButtonDown = false;
windowDragOn = false;
ReleaseMouse();
wxPoint point = event.GetPosition();
if (draggingSelectionBox)
{
for (size_t k=0; k<slots.size(); k++)
{
slots[k].SetSelected(false);
}
std::vector<size_t> selectedSlots = SlotsInDragBox();
for (size_t k=0; k<selectedSlots.size(); k++)
{
slots[selectedSlots[k]].SetSelected(true);
}
draggingSelectionBox = false;
return;
}
size_t selectedSlot;
bool foundSlot = SlotContainingPoint(point, selectedSlot);
dragIsArmed = false;
tcDragStatus* dragStatus = tcDragStatus::Get();
if (dragStatus->IsDragging())
{
std::vector<tcContainerItem*> containerItems = dragStatus->GetDraggedItems();
if (containerItems.size() > 0)
{
/* check if cursor is over an empty slot, if so
** handle drag (drop) */
if (foundSlot)
{
wxASSERT(selectedSlot < slots.size());
containerItems[0]->SetQuantity(dragStatus->GetQuantity());
HandleDrop(selectedSlot, containerItems);
}
else
{
containerItems[0]->SetQuantity(dragStatus->GetQuantity());
HandleDropWindow(containerItems);
}
}
// clear drag
dragStatus->StopDrag();
}
else if (event.ControlDown()) // check for de-selecting a slot on left button up with CTRL pressed
{
if (foundSlot && (slots[selectedSlot].IsSelected()) && (selectedSlot != protectDeselectIdx))
{
slots[selectedSlot].SetSelected(false);
}
}
}
void tcContainerGui::OnLeaveWindow(wxMouseEvent& event)
{
// clear mouseover state since OnMouseMove sometimes not called before leaving window
size_t nSlots = slots.size();
for (size_t n=0; n<nSlots; n++)
{
slots[n].SetMouseOver(false);
}
}
/**
* Update mouseover status of slots
*/
void tcContainerGui::OnMouseMove(wxMouseEvent& event)
{
wxPoint point = event.GetPosition();
mousePoint = point;
UpdateWindowDrag(point);
// update mouseover status of all slots
float x = (float)point.x;
float y = (float)point.y;
size_t nSlots = slots.size();
bool foundSlot = false;
for (size_t n=0; n<nSlots; n++)
{
if (!foundSlot && !draggingSelectionBox)
{
slots[n].SetMouseOver(slots[n].loc.ContainsPoint(x, y));
}
else
{
slots[n].SetMouseOver(false);
}
}
// check for start of a drag operation
if (!dragIsArmed) return;
// start drag
std::vector<size_t> selectedSlots = GetSelected();
std::vector<tcContainerItem*> items;
for (size_t n=0; n<selectedSlots.size(); n++)
{
tcContainerItem* item = slots[selectedSlots[n]].GetItem();
if (item != 0)
{
items.push_back(item);
}
}
if (items.size() == 0)
{
return;
}
tcDragStatus* dragStatus = tcDragStatus::Get();
dragStatus->StartDrag(this, items);
dragIsArmed = false;
tcSound::Get()->PlayEffect("Thuck");
}
void tcContainerGui::RegisterGui()
{
openContainers.push_back(this);
}
void tcContainerGui::UnregisterGui()
{
std::list<tcContainerGui*>::iterator iter =
find(openContainers.begin(), openContainers.end(), this);
if (iter != openContainers.end())
{
openContainers.erase(iter);
}
else
{
fprintf(stderr, "tcContainerGui::UnregisterGui - not found in registry %s\n",
wxWindow::GetName().c_str());
}
}
void tcContainerGui::UpdateWindowDrag(const wxPoint& pos)
{
if (!windowDragOn) return;
// position in parent's frame of mouse pointer
wxPoint current = wxPoint(mrectWindow.GetLeft() + pos.x, mrectWindow.GetBottom() + pos.y);
if (current != windowDragPoint)
{
wxPoint delta = current - windowDragPoint;
int xmove = mrectWindow.GetLeft() + delta.x;
int ymove = mrectWindow.GetTop() + delta.y;
tc3DWindow2::MoveWindow(xmove, ymove);
windowDragPoint = current;
}
}
void tcContainerGui::SetParentItem(tcContainerItem* item)
{
parentItem = item;
}
/**
* @return true if point <pos> is over a slot
* @param slotIdx set to index of containing slot
*/
bool tcContainerGui::SlotContainingPoint(const wxPoint& point, size_t& slotIdx) const
{
float x = (float)point.x;
float y = (float)point.y;
size_t nSlots = slots.size();
bool foundSlot = false;
for (size_t n=0; (n<nSlots)&&(!foundSlot); n++)
{
if (slots[n].loc.ContainsPoint(x, y))
{
slotIdx = n;
return true;
}
}
slotIdx = 999;
return false;
}
/**
* @return true if point <pos> is over a slot
* @param slotIdx set to index of containing slot
*/
const std::vector<size_t>& tcContainerGui::SlotsInDragBox() const
{
static std::vector<size_t> result;
result.clear();
tcRect box;
box.left = float(std::min(selectionBoxStart.x, mousePoint.x));
box.right = float(std::max(selectionBoxStart.x, mousePoint.x));
box.bottom = float(std::min(selectionBoxStart.y, mousePoint.y));
box.top = float(std::max(selectionBoxStart.y, mousePoint.y));
size_t nSlots = slots.size();
for (size_t n=0; n<nSlots; n++)
{
if (box.ContainsPoint(slots[n].loc.XCenter(), slots[n].loc.YCenter()))
{
result.push_back(n);
}
}
return result;
}
/**
* static method SetParent must be called first
*/
tcContainerGui::tcContainerGui(const wxPoint& pos, const wxString& configFile, const wxString& name)
: tcXmlWindow(parent, pos, wxSize(10, 10), configFile, name, parent),
drawCount(0),
dragIsArmed(false),
parentItem(0),
isLButtonDown(false),
windowDragOn(false),
protectDeselectIdx(999),
draggingSelectionBox(false)
{
// put gui window on top
SetBaseRenderBin(parent->GetBaseRenderBin() + windowLayer*10);
wxWindow::Raise();
tc3DWindow2::SetStencilLayer(windowLayer-3); // assumes windowLayer starts at 4
windowLayer++;
TiXmlNode* root = config->FirstChild("Window");
if (!root)
{
fprintf(stderr, "tcContainerGui::tcContainerGui - Missing top level <Window> tag\n");
return;
}
TiXmlNode* current = root;
/*
TiXmlElement* elt = current->ToElement();
// background image
std::string imageName = elt->Attribute("BackgroundImage");
if (imageName.size() > 2)
{
LoadBackgroundImage(imageName.c_str());
}
// size of window
int xmlWidth, xmlHeight;
elt->Attribute("Width", &xmlWidth);
elt->Attribute("Height", &xmlHeight);
SetSize(pos.x, pos.y, xmlWidth, xmlHeight); // set all size params
*/
// add slots
current = root->FirstChild("Slot");
while (current)
{
int x = 0;
int y = 0;
int size = 0;
TiXmlElement* elt = current->ToElement();
elt->Attribute("X", &x);
elt->Attribute("Y", &y);
elt->Attribute("Size", &size);
tcRect loc;
loc.Set(x, x+size, y, y+size);
AddSlot(loc);
current = current->NextSibling("Slot");
}
SetUseRenderSurface(true);
SetRenderSurfaceUpdateInterval(4);
SetActive(true);
RegisterGui();
#ifdef _DEBUG
fprintf(stdout, "tcContainerGui::tcContainerGui - %s, %d slots\n", name.c_str(),
slots.size());
#endif
SetBorderDraw(true);
}
tcContainerGui::~tcContainerGui()
{
if (parentItem)
{
parentItem->SetGui(0);
}
for (size_t n=0; n<slots.size(); n++)
{
if (!slots[n].IsEmpty())
{
slots[n].ClearItem();
}
}
windowLayer--;
UnregisterGui();
tcDragStatus* dragStatus = tcDragStatus::Get();
if (dragStatus->IsDragging() && (dragStatus->GetItemGui() == this))
{
dragStatus->StopDrag();
}
}
| 22.478431 | 146 | 0.640323 | [
"vector"
] |
92261b0308a50a4bfce25f53ffb67baafb7c4484 | 5,014 | cpp | C++ | Sources/blocks/CascadeClassifier.cpp | Petititi/imGraph | 068890ffe2f8fa1fb51bc95b8d9296cc79737fac | [
"BSD-3-Clause"
] | 2 | 2015-01-12T11:27:45.000Z | 2015-03-25T18:24:38.000Z | Sources/blocks/CascadeClassifier.cpp | Petititi/imGraph | 068890ffe2f8fa1fb51bc95b8d9296cc79737fac | [
"BSD-3-Clause"
] | 30 | 2015-01-07T11:59:07.000Z | 2015-04-24T13:02:01.000Z | Sources/blocks/CascadeClassifier.cpp | Petititi/imGraph | 068890ffe2f8fa1fb51bc95b8d9296cc79737fac | [
"BSD-3-Clause"
] | 1 | 2018-12-20T12:18:18.000Z | 2018-12-20T12:18:18.000Z | #ifdef _WIN32
#pragma warning(disable:4503)
#pragma warning(push)
#pragma warning(disable:4996 4251 4275 4800 4190 4244)
#endif
#include <vector>
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#ifdef _WIN32
#pragma warning(pop)
#endif
#include "Block.h"
#include "ParamValidator.h"
using std::vector;
using cv::Mat;
using std::string;
using namespace std;
namespace charliesoft
{
BLOCK_BEGIN_INSTANTIATION(CascadeClassifier);
protected:
cv::CascadeClassifier face_cascade;
string cascades_filename;
BLOCK_END_INSTANTIATION(CascadeClassifier, AlgoType::imgProcess, BLOCK__CASCADECLASSIFIER_NAME);
BEGIN_BLOCK_INPUT_PARAMS(CascadeClassifier);
//Add parameters, with following parameters:
ADD_PARAMETER(toBeLinked, Matrix, "BLOCK__CASCADECLASSIFIER_IN_IMAGE", "BLOCK__CASCADECLASSIFIER_IN_IMAGE_HELP");
ADD_PARAMETER(userConstant, FilePath, "BLOCK__CASCADECLASSIFIER_IN_CASCADE_FILE", "BLOCK__CASCADECLASSIFIER_IN_CASCADE_FILE_HELP");
ADD_PARAMETER_FULL(userConstant, Float, "BLOCK__CASCADECLASSIFIER_IN_SCALE_FACTOR", "BLOCK__CASCADECLASSIFIER_IN_SCALE_FACTOR_HELP", 1.1);
ADD_PARAMETER_FULL(userConstant, Int, "BLOCK__CASCADECLASSIFIER_IN_MIN_NEIGHBORS", "BLOCK__CASCADECLASSIFIER_IN_MIN_NEIGHBORS_HELP", 3);
ADD_PARAMETER_FULL(userConstant, Int, "BLOCK__CASCADECLASSIFIER_IN_MIN_WIDTH", "BLOCK__CASCADECLASSIFIER_IN_MIN_WIDTH_HELP", 60);
ADD_PARAMETER_FULL(userConstant, Int, "BLOCK__CASCADECLASSIFIER_IN_MIN_HEIGHT", "BLOCK__CASCADECLASSIFIER_IN_MIN_HEIGHT_HELP", 60);
ADD_PARAMETER(notUsed, Int, "BLOCK__CASCADECLASSIFIER_IN_MAX_WIDTH", "BLOCK__CASCADECLASSIFIER_IN_MAX_WIDTH_HELP");
ADD_PARAMETER(notUsed, Int, "BLOCK__CASCADECLASSIFIER_IN_MAX_HEIGHT", "BLOCK__CASCADECLASSIFIER_IN_MAX_HEIGHT_HELP");
END_BLOCK_PARAMS();
BEGIN_BLOCK_OUTPUT_PARAMS(CascadeClassifier);
ADD_PARAMETER(toBeLinked, Matrix, "BLOCK__CASCADECLASSIFIER_OUT_IMAGE", "BLOCK__CASCADECLASSIFIER_OUT_IMAGE_HELP");
ADD_PARAMETER(notUsed, Int, "BLOCK__CASCADECLASSIFIER_OUT_OBJECTS", "BLOCK__CASCADECLASSIFIER_OUT_OBJECTS_HELP");
END_BLOCK_PARAMS();
BEGIN_BLOCK_SUBPARAMS_DEF(CascadeClassifier);
END_BLOCK_PARAMS();
CascadeClassifier::CascadeClassifier() :Block("BLOCK__CASCADECLASSIFIER_NAME", true){
_myInputs["BLOCK__CASCADECLASSIFIER_IN_IMAGE"].addValidator({ new ValNeeded() });
_myInputs["BLOCK__CASCADECLASSIFIER_IN_CASCADE_FILE"].addValidator({ new ValNeeded(), new ValFileExist(), new ValFileTypes("XML (*.xml)")});
};
bool CascadeClassifier::run(bool oneShot){
if (_myInputs["BLOCK__CASCADECLASSIFIER_IN_IMAGE"].isDefaultValue())
return false;
if (cascades_filename != _myInputs["BLOCK__CASCADECLASSIFIER_IN_CASCADE_FILE"].get<string>()) {
if (boost::filesystem::exists(_myInputs["BLOCK__CASCADECLASSIFIER_IN_CASCADE_FILE"].get<string>())) {
cascades_filename = _myInputs["BLOCK__CASCADECLASSIFIER_IN_CASCADE_FILE"].get<string>();
face_cascade.load(cascades_filename);
}
}
if (face_cascade.empty())
return false;
cv::Size minSize,maxSize;
if (_myInputs["BLOCK__CASCADECLASSIFIER_IN_MIN_WIDTH"].get<int>() > 0 || _myInputs["BLOCK__CASCADECLASSIFIER_IN_MIN_HEIGHT"].get<int>() > 0) {
minSize = cv::Size(_myInputs["BLOCK__CASCADECLASSIFIER_IN_MIN_WIDTH"].get<int>(), _myInputs["BLOCK__CASCADECLASSIFIER_IN_MIN_HEIGHT"].get<int>());
}
if (_myInputs["BLOCK__CASCADECLASSIFIER_IN_MAX_WIDTH"].get<int>() > 0 || _myInputs["BLOCK__CASCADECLASSIFIER_IN_MAX_HEIGHT"].get<int>() > 0) {
maxSize = cv::Size(_myInputs["BLOCK__CASCADECLASSIFIER_IN_MAX_WIDTH"].get<int>(), _myInputs["BLOCK__CASCADECLASSIFIER_IN_MAX_HEIGHT"].get<int>());
}
cv::Mat output = _myInputs["BLOCK__CASCADECLASSIFIER_IN_IMAGE"].get<cv::Mat>().clone();
//convert captured image to gray scale and equalize
cv::cvtColor(output, output, CV_BGR2GRAY);
cv::equalizeHist(output, output);
//create a vector array to store the face found
std::vector<cv::Rect> faces;
//find faces and store them in the vector array
face_cascade.detectMultiScale(output, faces, _myInputs["BLOCK__CASCADECLASSIFIER_IN_SCALE_FACTOR"].get<float>(), _myInputs["BLOCK__CASCADECLASSIFIER_IN_MIN_NEIGHBORS"].get<int>(), CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_SCALE_IMAGE, minSize, maxSize);
cv::Mat mask = cv::Mat::zeros(output.size(), CV_8UC1);
//draw a rectangle for all found faces in the vector array on the original image
for (unsigned int i = 0; i < faces.size(); i++)
{
mask(faces[i]) = 1;
}
if (!output.empty())
{
_myOutputs["BLOCK__CASCADECLASSIFIER_OUT_IMAGE"] = mask;
_myOutputs["BLOCK__CASCADECLASSIFIER_OUT_OBJECTS"] = (int)(faces.size());
}
return !output.empty();
};
}; | 48.211538 | 257 | 0.735939 | [
"vector"
] |
9232196a34a4de95eee5a28f717372535064b171 | 19,145 | cpp | C++ | gaap/src/v20180529/model/DomainRuleSet.cpp | datalliance88/tencentcloud-sdk-cpp | fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c | [
"Apache-2.0"
] | null | null | null | gaap/src/v20180529/model/DomainRuleSet.cpp | datalliance88/tencentcloud-sdk-cpp | fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c | [
"Apache-2.0"
] | null | null | null | gaap/src/v20180529/model/DomainRuleSet.cpp | datalliance88/tencentcloud-sdk-cpp | fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/gaap/v20180529/model/DomainRuleSet.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Gaap::V20180529::Model;
using namespace rapidjson;
using namespace std;
DomainRuleSet::DomainRuleSet() :
m_domainHasBeenSet(false),
m_ruleSetHasBeenSet(false),
m_certificateIdHasBeenSet(false),
m_certificateAliasHasBeenSet(false),
m_clientCertificateIdHasBeenSet(false),
m_clientCertificateAliasHasBeenSet(false),
m_basicAuthConfIdHasBeenSet(false),
m_basicAuthHasBeenSet(false),
m_basicAuthConfAliasHasBeenSet(false),
m_realServerCertificateIdHasBeenSet(false),
m_realServerAuthHasBeenSet(false),
m_realServerCertificateAliasHasBeenSet(false),
m_gaapCertificateIdHasBeenSet(false),
m_gaapAuthHasBeenSet(false),
m_gaapCertificateAliasHasBeenSet(false),
m_realServerCertificateDomainHasBeenSet(false)
{
}
CoreInternalOutcome DomainRuleSet::Deserialize(const Value &value)
{
string requestId = "";
if (value.HasMember("Domain") && !value["Domain"].IsNull())
{
if (!value["Domain"].IsString())
{
return CoreInternalOutcome(Error("response `DomainRuleSet.Domain` IsString=false incorrectly").SetRequestId(requestId));
}
m_domain = string(value["Domain"].GetString());
m_domainHasBeenSet = true;
}
if (value.HasMember("RuleSet") && !value["RuleSet"].IsNull())
{
if (!value["RuleSet"].IsArray())
return CoreInternalOutcome(Error("response `DomainRuleSet.RuleSet` is not array type"));
const Value &tmpValue = value["RuleSet"];
for (Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
RuleInfo item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_ruleSet.push_back(item);
}
m_ruleSetHasBeenSet = true;
}
if (value.HasMember("CertificateId") && !value["CertificateId"].IsNull())
{
if (!value["CertificateId"].IsString())
{
return CoreInternalOutcome(Error("response `DomainRuleSet.CertificateId` IsString=false incorrectly").SetRequestId(requestId));
}
m_certificateId = string(value["CertificateId"].GetString());
m_certificateIdHasBeenSet = true;
}
if (value.HasMember("CertificateAlias") && !value["CertificateAlias"].IsNull())
{
if (!value["CertificateAlias"].IsString())
{
return CoreInternalOutcome(Error("response `DomainRuleSet.CertificateAlias` IsString=false incorrectly").SetRequestId(requestId));
}
m_certificateAlias = string(value["CertificateAlias"].GetString());
m_certificateAliasHasBeenSet = true;
}
if (value.HasMember("ClientCertificateId") && !value["ClientCertificateId"].IsNull())
{
if (!value["ClientCertificateId"].IsString())
{
return CoreInternalOutcome(Error("response `DomainRuleSet.ClientCertificateId` IsString=false incorrectly").SetRequestId(requestId));
}
m_clientCertificateId = string(value["ClientCertificateId"].GetString());
m_clientCertificateIdHasBeenSet = true;
}
if (value.HasMember("ClientCertificateAlias") && !value["ClientCertificateAlias"].IsNull())
{
if (!value["ClientCertificateAlias"].IsString())
{
return CoreInternalOutcome(Error("response `DomainRuleSet.ClientCertificateAlias` IsString=false incorrectly").SetRequestId(requestId));
}
m_clientCertificateAlias = string(value["ClientCertificateAlias"].GetString());
m_clientCertificateAliasHasBeenSet = true;
}
if (value.HasMember("BasicAuthConfId") && !value["BasicAuthConfId"].IsNull())
{
if (!value["BasicAuthConfId"].IsString())
{
return CoreInternalOutcome(Error("response `DomainRuleSet.BasicAuthConfId` IsString=false incorrectly").SetRequestId(requestId));
}
m_basicAuthConfId = string(value["BasicAuthConfId"].GetString());
m_basicAuthConfIdHasBeenSet = true;
}
if (value.HasMember("BasicAuth") && !value["BasicAuth"].IsNull())
{
if (!value["BasicAuth"].IsInt64())
{
return CoreInternalOutcome(Error("response `DomainRuleSet.BasicAuth` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_basicAuth = value["BasicAuth"].GetInt64();
m_basicAuthHasBeenSet = true;
}
if (value.HasMember("BasicAuthConfAlias") && !value["BasicAuthConfAlias"].IsNull())
{
if (!value["BasicAuthConfAlias"].IsString())
{
return CoreInternalOutcome(Error("response `DomainRuleSet.BasicAuthConfAlias` IsString=false incorrectly").SetRequestId(requestId));
}
m_basicAuthConfAlias = string(value["BasicAuthConfAlias"].GetString());
m_basicAuthConfAliasHasBeenSet = true;
}
if (value.HasMember("RealServerCertificateId") && !value["RealServerCertificateId"].IsNull())
{
if (!value["RealServerCertificateId"].IsString())
{
return CoreInternalOutcome(Error("response `DomainRuleSet.RealServerCertificateId` IsString=false incorrectly").SetRequestId(requestId));
}
m_realServerCertificateId = string(value["RealServerCertificateId"].GetString());
m_realServerCertificateIdHasBeenSet = true;
}
if (value.HasMember("RealServerAuth") && !value["RealServerAuth"].IsNull())
{
if (!value["RealServerAuth"].IsInt64())
{
return CoreInternalOutcome(Error("response `DomainRuleSet.RealServerAuth` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_realServerAuth = value["RealServerAuth"].GetInt64();
m_realServerAuthHasBeenSet = true;
}
if (value.HasMember("RealServerCertificateAlias") && !value["RealServerCertificateAlias"].IsNull())
{
if (!value["RealServerCertificateAlias"].IsString())
{
return CoreInternalOutcome(Error("response `DomainRuleSet.RealServerCertificateAlias` IsString=false incorrectly").SetRequestId(requestId));
}
m_realServerCertificateAlias = string(value["RealServerCertificateAlias"].GetString());
m_realServerCertificateAliasHasBeenSet = true;
}
if (value.HasMember("GaapCertificateId") && !value["GaapCertificateId"].IsNull())
{
if (!value["GaapCertificateId"].IsString())
{
return CoreInternalOutcome(Error("response `DomainRuleSet.GaapCertificateId` IsString=false incorrectly").SetRequestId(requestId));
}
m_gaapCertificateId = string(value["GaapCertificateId"].GetString());
m_gaapCertificateIdHasBeenSet = true;
}
if (value.HasMember("GaapAuth") && !value["GaapAuth"].IsNull())
{
if (!value["GaapAuth"].IsInt64())
{
return CoreInternalOutcome(Error("response `DomainRuleSet.GaapAuth` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_gaapAuth = value["GaapAuth"].GetInt64();
m_gaapAuthHasBeenSet = true;
}
if (value.HasMember("GaapCertificateAlias") && !value["GaapCertificateAlias"].IsNull())
{
if (!value["GaapCertificateAlias"].IsString())
{
return CoreInternalOutcome(Error("response `DomainRuleSet.GaapCertificateAlias` IsString=false incorrectly").SetRequestId(requestId));
}
m_gaapCertificateAlias = string(value["GaapCertificateAlias"].GetString());
m_gaapCertificateAliasHasBeenSet = true;
}
if (value.HasMember("RealServerCertificateDomain") && !value["RealServerCertificateDomain"].IsNull())
{
if (!value["RealServerCertificateDomain"].IsString())
{
return CoreInternalOutcome(Error("response `DomainRuleSet.RealServerCertificateDomain` IsString=false incorrectly").SetRequestId(requestId));
}
m_realServerCertificateDomain = string(value["RealServerCertificateDomain"].GetString());
m_realServerCertificateDomainHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void DomainRuleSet::ToJsonObject(Value &value, Document::AllocatorType& allocator) const
{
if (m_domainHasBeenSet)
{
Value iKey(kStringType);
string key = "Domain";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_domain.c_str(), allocator).Move(), allocator);
}
if (m_ruleSetHasBeenSet)
{
Value iKey(kStringType);
string key = "RuleSet";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_ruleSet.begin(); itr != m_ruleSet.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(Value(kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
if (m_certificateIdHasBeenSet)
{
Value iKey(kStringType);
string key = "CertificateId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_certificateId.c_str(), allocator).Move(), allocator);
}
if (m_certificateAliasHasBeenSet)
{
Value iKey(kStringType);
string key = "CertificateAlias";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_certificateAlias.c_str(), allocator).Move(), allocator);
}
if (m_clientCertificateIdHasBeenSet)
{
Value iKey(kStringType);
string key = "ClientCertificateId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_clientCertificateId.c_str(), allocator).Move(), allocator);
}
if (m_clientCertificateAliasHasBeenSet)
{
Value iKey(kStringType);
string key = "ClientCertificateAlias";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_clientCertificateAlias.c_str(), allocator).Move(), allocator);
}
if (m_basicAuthConfIdHasBeenSet)
{
Value iKey(kStringType);
string key = "BasicAuthConfId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_basicAuthConfId.c_str(), allocator).Move(), allocator);
}
if (m_basicAuthHasBeenSet)
{
Value iKey(kStringType);
string key = "BasicAuth";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_basicAuth, allocator);
}
if (m_basicAuthConfAliasHasBeenSet)
{
Value iKey(kStringType);
string key = "BasicAuthConfAlias";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_basicAuthConfAlias.c_str(), allocator).Move(), allocator);
}
if (m_realServerCertificateIdHasBeenSet)
{
Value iKey(kStringType);
string key = "RealServerCertificateId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_realServerCertificateId.c_str(), allocator).Move(), allocator);
}
if (m_realServerAuthHasBeenSet)
{
Value iKey(kStringType);
string key = "RealServerAuth";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_realServerAuth, allocator);
}
if (m_realServerCertificateAliasHasBeenSet)
{
Value iKey(kStringType);
string key = "RealServerCertificateAlias";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_realServerCertificateAlias.c_str(), allocator).Move(), allocator);
}
if (m_gaapCertificateIdHasBeenSet)
{
Value iKey(kStringType);
string key = "GaapCertificateId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_gaapCertificateId.c_str(), allocator).Move(), allocator);
}
if (m_gaapAuthHasBeenSet)
{
Value iKey(kStringType);
string key = "GaapAuth";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_gaapAuth, allocator);
}
if (m_gaapCertificateAliasHasBeenSet)
{
Value iKey(kStringType);
string key = "GaapCertificateAlias";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_gaapCertificateAlias.c_str(), allocator).Move(), allocator);
}
if (m_realServerCertificateDomainHasBeenSet)
{
Value iKey(kStringType);
string key = "RealServerCertificateDomain";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_realServerCertificateDomain.c_str(), allocator).Move(), allocator);
}
}
string DomainRuleSet::GetDomain() const
{
return m_domain;
}
void DomainRuleSet::SetDomain(const string& _domain)
{
m_domain = _domain;
m_domainHasBeenSet = true;
}
bool DomainRuleSet::DomainHasBeenSet() const
{
return m_domainHasBeenSet;
}
vector<RuleInfo> DomainRuleSet::GetRuleSet() const
{
return m_ruleSet;
}
void DomainRuleSet::SetRuleSet(const vector<RuleInfo>& _ruleSet)
{
m_ruleSet = _ruleSet;
m_ruleSetHasBeenSet = true;
}
bool DomainRuleSet::RuleSetHasBeenSet() const
{
return m_ruleSetHasBeenSet;
}
string DomainRuleSet::GetCertificateId() const
{
return m_certificateId;
}
void DomainRuleSet::SetCertificateId(const string& _certificateId)
{
m_certificateId = _certificateId;
m_certificateIdHasBeenSet = true;
}
bool DomainRuleSet::CertificateIdHasBeenSet() const
{
return m_certificateIdHasBeenSet;
}
string DomainRuleSet::GetCertificateAlias() const
{
return m_certificateAlias;
}
void DomainRuleSet::SetCertificateAlias(const string& _certificateAlias)
{
m_certificateAlias = _certificateAlias;
m_certificateAliasHasBeenSet = true;
}
bool DomainRuleSet::CertificateAliasHasBeenSet() const
{
return m_certificateAliasHasBeenSet;
}
string DomainRuleSet::GetClientCertificateId() const
{
return m_clientCertificateId;
}
void DomainRuleSet::SetClientCertificateId(const string& _clientCertificateId)
{
m_clientCertificateId = _clientCertificateId;
m_clientCertificateIdHasBeenSet = true;
}
bool DomainRuleSet::ClientCertificateIdHasBeenSet() const
{
return m_clientCertificateIdHasBeenSet;
}
string DomainRuleSet::GetClientCertificateAlias() const
{
return m_clientCertificateAlias;
}
void DomainRuleSet::SetClientCertificateAlias(const string& _clientCertificateAlias)
{
m_clientCertificateAlias = _clientCertificateAlias;
m_clientCertificateAliasHasBeenSet = true;
}
bool DomainRuleSet::ClientCertificateAliasHasBeenSet() const
{
return m_clientCertificateAliasHasBeenSet;
}
string DomainRuleSet::GetBasicAuthConfId() const
{
return m_basicAuthConfId;
}
void DomainRuleSet::SetBasicAuthConfId(const string& _basicAuthConfId)
{
m_basicAuthConfId = _basicAuthConfId;
m_basicAuthConfIdHasBeenSet = true;
}
bool DomainRuleSet::BasicAuthConfIdHasBeenSet() const
{
return m_basicAuthConfIdHasBeenSet;
}
int64_t DomainRuleSet::GetBasicAuth() const
{
return m_basicAuth;
}
void DomainRuleSet::SetBasicAuth(const int64_t& _basicAuth)
{
m_basicAuth = _basicAuth;
m_basicAuthHasBeenSet = true;
}
bool DomainRuleSet::BasicAuthHasBeenSet() const
{
return m_basicAuthHasBeenSet;
}
string DomainRuleSet::GetBasicAuthConfAlias() const
{
return m_basicAuthConfAlias;
}
void DomainRuleSet::SetBasicAuthConfAlias(const string& _basicAuthConfAlias)
{
m_basicAuthConfAlias = _basicAuthConfAlias;
m_basicAuthConfAliasHasBeenSet = true;
}
bool DomainRuleSet::BasicAuthConfAliasHasBeenSet() const
{
return m_basicAuthConfAliasHasBeenSet;
}
string DomainRuleSet::GetRealServerCertificateId() const
{
return m_realServerCertificateId;
}
void DomainRuleSet::SetRealServerCertificateId(const string& _realServerCertificateId)
{
m_realServerCertificateId = _realServerCertificateId;
m_realServerCertificateIdHasBeenSet = true;
}
bool DomainRuleSet::RealServerCertificateIdHasBeenSet() const
{
return m_realServerCertificateIdHasBeenSet;
}
int64_t DomainRuleSet::GetRealServerAuth() const
{
return m_realServerAuth;
}
void DomainRuleSet::SetRealServerAuth(const int64_t& _realServerAuth)
{
m_realServerAuth = _realServerAuth;
m_realServerAuthHasBeenSet = true;
}
bool DomainRuleSet::RealServerAuthHasBeenSet() const
{
return m_realServerAuthHasBeenSet;
}
string DomainRuleSet::GetRealServerCertificateAlias() const
{
return m_realServerCertificateAlias;
}
void DomainRuleSet::SetRealServerCertificateAlias(const string& _realServerCertificateAlias)
{
m_realServerCertificateAlias = _realServerCertificateAlias;
m_realServerCertificateAliasHasBeenSet = true;
}
bool DomainRuleSet::RealServerCertificateAliasHasBeenSet() const
{
return m_realServerCertificateAliasHasBeenSet;
}
string DomainRuleSet::GetGaapCertificateId() const
{
return m_gaapCertificateId;
}
void DomainRuleSet::SetGaapCertificateId(const string& _gaapCertificateId)
{
m_gaapCertificateId = _gaapCertificateId;
m_gaapCertificateIdHasBeenSet = true;
}
bool DomainRuleSet::GaapCertificateIdHasBeenSet() const
{
return m_gaapCertificateIdHasBeenSet;
}
int64_t DomainRuleSet::GetGaapAuth() const
{
return m_gaapAuth;
}
void DomainRuleSet::SetGaapAuth(const int64_t& _gaapAuth)
{
m_gaapAuth = _gaapAuth;
m_gaapAuthHasBeenSet = true;
}
bool DomainRuleSet::GaapAuthHasBeenSet() const
{
return m_gaapAuthHasBeenSet;
}
string DomainRuleSet::GetGaapCertificateAlias() const
{
return m_gaapCertificateAlias;
}
void DomainRuleSet::SetGaapCertificateAlias(const string& _gaapCertificateAlias)
{
m_gaapCertificateAlias = _gaapCertificateAlias;
m_gaapCertificateAliasHasBeenSet = true;
}
bool DomainRuleSet::GaapCertificateAliasHasBeenSet() const
{
return m_gaapCertificateAliasHasBeenSet;
}
string DomainRuleSet::GetRealServerCertificateDomain() const
{
return m_realServerCertificateDomain;
}
void DomainRuleSet::SetRealServerCertificateDomain(const string& _realServerCertificateDomain)
{
m_realServerCertificateDomain = _realServerCertificateDomain;
m_realServerCertificateDomainHasBeenSet = true;
}
bool DomainRuleSet::RealServerCertificateDomainHasBeenSet() const
{
return m_realServerCertificateDomainHasBeenSet;
}
| 30.879032 | 153 | 0.706764 | [
"vector",
"model"
] |
923769df9e660f55c82f837a1de6bbfa6ac379ec | 2,013 | cc | C++ | chromeos/login/auth/challenge_response/cert_utils_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chromeos/login/auth/challenge_response/cert_utils_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chromeos/login/auth/challenge_response/cert_utils_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/login/auth/challenge_response/cert_utils.h"
#include <string>
#include <vector>
#include "base/hash/sha1.h"
#include "base/memory/ref_counted.h"
#include "chromeos/login/auth/challenge_response_key.h"
#include "net/cert/x509_certificate.h"
#include "net/test/cert_test_util.h"
#include "net/test/test_certificate_data.h"
#include "net/test/test_data_directory.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
using KeySignatureAlgorithm = ChallengeResponseKey::SignatureAlgorithm;
namespace {
class ChallengeResponseCertUtilsTest : public testing::Test {
protected:
void SetUp() override {
certificate_ =
net::ImportCertFromFile(net::GetTestCertsDirectory(), "nist.der");
ASSERT_TRUE(certificate_);
}
const net::X509Certificate& certificate() const { return *certificate_; }
private:
scoped_refptr<net::X509Certificate> certificate_;
};
} // namespace
TEST_F(ChallengeResponseCertUtilsTest, Success) {
const std::vector<KeySignatureAlgorithm> kSignatureAlgorithms = {
KeySignatureAlgorithm::kRsassaPkcs1V15Sha512,
KeySignatureAlgorithm::kRsassaPkcs1V15Sha256};
ChallengeResponseKey challenge_response_key;
ASSERT_TRUE(ExtractChallengeResponseKeyFromCert(
certificate(), kSignatureAlgorithms, &challenge_response_key));
EXPECT_EQ(base::SHA1HashString(challenge_response_key.public_key_spki_der()),
std::string(kNistSPKIHash, kNistSPKIHash + base::kSHA1Length));
EXPECT_EQ(challenge_response_key.signature_algorithms(),
kSignatureAlgorithms);
}
TEST_F(ChallengeResponseCertUtilsTest, EmptyAlgorithmsFailure) {
ChallengeResponseKey challenge_response_key;
EXPECT_FALSE(ExtractChallengeResponseKeyFromCert(
certificate(), {} /* signature_algorithms */, &challenge_response_key));
}
} // namespace chromeos
| 31.952381 | 79 | 0.77844 | [
"vector"
] |
9238032867216ac84a53623e619762f3772f091a | 2,050 | hpp | C++ | sources/CastlesStrategy/Client/Ingame/FogOfWarManager.hpp | KonstantinTomashevich/castles-strategy | 5e57119ba7701e0f1f9c8d84ffb45abb6ad33a21 | [
"MIT"
] | null | null | null | sources/CastlesStrategy/Client/Ingame/FogOfWarManager.hpp | KonstantinTomashevich/castles-strategy | 5e57119ba7701e0f1f9c8d84ffb45abb6ad33a21 | [
"MIT"
] | null | null | null | sources/CastlesStrategy/Client/Ingame/FogOfWarManager.hpp | KonstantinTomashevich/castles-strategy | 5e57119ba7701e0f1f9c8d84ffb45abb6ad33a21 | [
"MIT"
] | null | null | null | #pragma once
#include <Urho3D/Core/Context.h>
#include <Urho3D/Graphics/Texture2D.h>
namespace CastlesStrategy
{
const float DEFAULT_FOG_OF_WAR_UPDATE_DELAY = 1.0f / 60.0f;
const Urho3D::String FOG_OF_WAR_MASK_TEXTURE_RESOURCE_NAME ("FogOfWarMask");
const Urho3D::Color DEFAULT_UNDER_FOG_OF_WAR_MASK_COLOR (0.35f, 0.35f, 0.35f, 1.0f);
const Urho3D::Color DEFAULT_VISIBLE_MASK_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
const Urho3D::IntVector2 DEFAULT_FOG_OF_WAR_MASK_SIZE (512, 512);
class IngameActivity;
class FogOfWarManager : public Urho3D::Object
{
URHO3D_OBJECT (FogOfWarManager, Object)
public:
explicit FogOfWarManager (IngameActivity *owner);
virtual ~FogOfWarManager ();
void SetupFogOfWarMask (const Urho3D::IntVector2 &maskSize, const Urho3D::Vector2 &mapSize);
void Update (float timeStep);
float GetUpdateDelay () const;
void SetUpdateDelay (float updateDelay);
Urho3D::Texture2D *GetFogOfWarMaskTexture () const;
const Urho3D::Color &GetUnderFogColor () const;
void SetUnderFogColor (const Urho3D::Color &underFogColor);
const Urho3D::Color &GetVisibleColor () const;
void SetVisibleColor (const Urho3D::Color &visibleColor);
bool IsFogOfWarEnabled () const;
void SetFogOfWarEnabled (bool fogOfWarEnabled);
private:
void UpdateFogOfWarMap ();
void ReleaseImageAndTexture ();
// TODO: It's not a best way, later think about better solutions.
void UpdateMaterialsShaderParameters ();
// TODO: It's not a best way, later think about better solutions.
void ResetText3DMaterials ();
/// Bresenham's procedure.
void MakeEllipseVisible (int centerX, int centerY, int width, int height);
void MakeLineVisible (int minX, int maxX, int y);
IngameActivity *owner_;
float updateDelay_;
float untilNextUpdate_;
Urho3D::Image *fogOfWarMaskImage_;
Urho3D::SharedPtr <Urho3D::Texture2D> fogOfWarMaskTexture_;
Urho3D::Color underFogColor_;
Urho3D::Color visibleColor_;
Urho3D::Vector2 mapUnitSize_;
bool fogOfWarEnabled_;
};
}
| 33.606557 | 96 | 0.745854 | [
"object"
] |
9240024ec4ac09725295e234fa43a4dd49479d29 | 1,643 | cpp | C++ | Old/Graphs/Trees/treecountsubtree.cpp | JanaSabuj/CodingLibrary | 92bc141ae327ce01b480fde7a10ffb0be0ba401d | [
"MIT"
] | 14 | 2020-05-17T18:31:32.000Z | 2021-02-04T03:56:30.000Z | Old/Graphs/Trees/treecountsubtree.cpp | JanaSabuj/cppdump | 92bc141ae327ce01b480fde7a10ffb0be0ba401d | [
"MIT"
] | null | null | null | Old/Graphs/Trees/treecountsubtree.cpp | JanaSabuj/cppdump | 92bc141ae327ce01b480fde7a10ffb0be0ba401d | [
"MIT"
] | 2 | 2020-05-27T10:42:36.000Z | 2021-02-02T11:59:04.000Z | /*--------------------------"SABUJ-JANA"------"JADAVPUR UNIVERSITY"--------*/
/*-------------------------------@greenindia-----------------------------------*/
/*---------------------- Magic. Do not touch.-----------------------------*/
/*------------------------------God is Great/\---------------------------------*/
#include <bits/stdc++.h>
using namespace std;
#define crap ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
//cout<<fixed<<showpoint<<setprecision(12)<<ans<<endl;
#define dbg(x) cerr << #x << " = " << x << endl
#define endl "\n"
#define int long long int
#define double long double
#define pb push_back
#define mp make_pair
#define PI acos(-1)
const int INF=1e9+5;//billion
#define MAX 100007
string alpha="abcdefghijklmnopqrstuvwxyz";
//power (a^b)%m
int power(int a,int b,int m){int ans=1;while(b){if(b&1)ans=(ans*a)%m;b/=2;a=(a*a)%m;}return ans;}
//tree
vector<int> adj[1000];
int subtree[1000];
void dfs(int s, int e){
cout<<s<<" ";
subtree[s]=1;
for(auto u: adj[s]){
//children
if(u!=e){
dfs(u,s);
subtree[s]+=subtree[u];
}
}
}
signed main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
freopen("error.txt", "w", stderr);
crap;
int n;
cin>>n;
int edge=n-1;
memset(subtree,0,sizeof(0));
while(edge--){
int x,y;
cin>>x>>y;
adj[x].pb(y);
adj[y].pb(x);
}
dfs(1,0);
cout<<endl;
for(int i=1; i<=n; i++){
cout<<subtree[i]<<" ";
}
return 0;
}
| 22.202703 | 99 | 0.457699 | [
"vector"
] |
9240f1e4a4142ca50f7f7f555231f02fbacbaf75 | 9,802 | cpp | C++ | asst6_hil00/skeleton.cpp | hibalubbad/hiba.baddie | 69001ad56c8a51f6e36a802bae061128d9fd5a71 | [
"MIT"
] | null | null | null | asst6_hil00/skeleton.cpp | hibalubbad/hiba.baddie | 69001ad56c8a51f6e36a802bae061128d9fd5a71 | [
"MIT"
] | null | null | null | asst6_hil00/skeleton.cpp | hibalubbad/hiba.baddie | 69001ad56c8a51f6e36a802bae061128d9fd5a71 | [
"MIT"
] | null | null | null | //this is just a skeleton. It does not compile without your partial or full solution
//it might contains some syntax error. it is given just as a starter
#include <iostream>
#include <fstream>
using namespace std;
// Define the song (node) class
class Song{
private:
string artist;
string title;
Song* next;
public:
// define a constructor to initialize artist and title but next to null
Song(string artist,string title){
this->artist =artist;
this->title = title;
this->next = NULL;
}
// define a constructor to initialize artist, title, and next to another song object
Song(string artist,string title,Song* next){
this->artist =artist;
this->title = title;
this->next = new Song;
}
// define a deafault constructor
Song(){
this->artist ="";
this->title = "";
this->next = NULL;
}
string getArtist(){
return artist;
}
string getTitle(){
return title;
}
//print the object in a format Artist: artist \nTitle: title such as
//Artist: The Beatles
//Title: The Fool on the Hill
friend ostream& operator <<(ostream& outs, Song& song);
// compareTo two song objects first by artist and then by title
//return 0 if they are equal
//return <0 if this object is smaller than other
//return > 0 if this object is greater than other
int compareTo(Song* other){
if(artist < other->artist)
return -1;
else if (artist > other->artist)
return 1;
else{
if (title < other->title)
return -1;
else if(title < other->title)
return 1;
else
return 0;
}
}
friend class SongList;
};
ostream& operator <<(ostream& outs, Song& song){
outs<< "Artist: "<< song.getArtist()<<endl<<"Title: "<< song.getTitle()<<endl;
return outs;
}
// Define a songList class
class SongList{
private:
Song* head;
int numSongs;
public:
SongList():head(NULL), numSongs(0) {};
// This method reads data from a file and populates the list
// songs.txt has the following format:
// Artist: ...
// Title: ....
// empty line
// Artist: ...
// Title: ...
// empty line ... and so on
void readFile (string aFile){
ifstream fin("songs.txt");
string artist;
string title;
//fin.ignore(7);
while(getline(fin,artist)){
fin.ignore(7);
getline(fin,title);
addSong(artist,title);
numSongs++;
fin.ignore(9);
}
}
// This method adds a song to the list while maintaining its sorted order in the list
// node should be created and added in the right position
void addSong (string artist, string title){
Song* s = new Song(artist,title);
if(head == NULL)
head = s;
else if(s->compareTo(head) < 0){
s->next = head;
head = s;
} else{
Song* current = head;
while (s->compareTo(current->next)== -1 && current->next != NULL) {
current = current->next;
}
s->next = current->next;
current->next = s;
}
}
// This method deletes all songs by an artist
void deleteByArtist (string artist){
Song *current = head;
if (head->artist==artist){
head = head->next;
delete current;
current=NULL;
}
else{
while(current->next !=NULL){
if(current->next->artist == artist){
Song* temp = current->next;
current->next=current->next->next;
delete temp;
}
else
current = current ->next;
}
}
}
// This method should return a song list that contains all songs by an artist
// without deleting them from the main SongList object.
SongList * getSongsByArtist (string artist){
Song *v = head;
SongList *list = new SongList();
while(v!= NULL){
v= v->next;
if(v->artist == artist){
list->addSong(v->artist,v->title);
}
}
return list;
}
// This method deletes a given song
void deleteByTitle (string title){
Song *current = head;
if (head->title==title){
head = head->next;
delete current;
current=NULL;
}
else{
while(current->next !=NULL){
if(current->next->title == title){
Song* temp = current->next;
current->next=current->next->next;
delete temp;
}
else
current = current ->next;
}
}
}
// This method returns a song object matching the given title
//without deleting the song from the main list. It returns NULL if the object does not exist
Song* getByTitle (string title){
Song *current = head;
while (current != NULL) {
if (current->title == title) {
Song* result = new Song(current->artist,current->title);
return result;
}else{
current = current->next;
}
}
return NULL; //in case the song does not exist
}
// This method searches for all songs by an artist and displays them
void searchByArtist (string artist){
SongList * song = getSongsByArtist(artist);
Song * v = song->head;
if(v==NULL)
cout<<"no songs found by the artist";
else{
while(v->next!=NULL){
cout<<v<<endl;
v=v->next;
}
}
}
// This method searches for a given song and displays it
void searchByTitle (string title){
cout << (*getByTitle(title));
}
// This method displays all entries in the collection
void displayCatalog (){
Song *v= head;
while(v!=NULL){
cout<<*v<<endl;
v= v->next;
}
}
// This method over-writes the file
void writeFile (){
ofstream myfile ;
myfile.open("songs.txt");
Song *v= head;
while(v!=NULL){
myfile<<*v<<endl;
v= v->next;
}
myfile.close();
}
};
void displayMenue(){
cout<< "Song Catalog Menu\n1. Import songs from a file\n2. Add a song\n3. Delete a song\n4. Search for a song\n5. Get a song by title\n6. Get all songs by artist\n7. Display all songs\n8. Exit program\nEnter selection (1 - 8):\n";
}
int main()
{
SongList* list= new SongList();
displayMenue();
int userInput;
cin >> userInput;
string artist;
string title;
string choice;
while (userInput!=8){
string emptyLine;
getline(cin,emptyLine); // to drop the \n line which is generated by userInput
if (userInput==1){
cout << "Please insert the file name: " ;
string fileName;
cin >> fileName;
list->readFile(fileName);
cout << "------------------------------------------" << endl << endl;
}else if (userInput==2){
cout<< "Enter Artist: ";
getline(cin, artist);
cout << "Enter Title: ";
getline(cin , title);
list->addSong(artist,title);
cout<< "Song has been added successfuly!" << endl;
cout << "------------------------------------------" << endl << endl;
}else if (userInput==3){
cout << "Delete by artist or title (A or T): ";
getline(cin,choice);
if(choice.compare("A")==0){
cout << "Enter Artist name: ";
getline(cin,artist);
list->deleteByArtist(artist);
}else{
// means delete by Title
cout << "Enter Title: ";
getline(cin,title);
list->deleteByTitle(title);
}
cout << "------------------------------------------" << endl << endl;
}else if (userInput==4){
cout << "Search by Artist or Title (A or T): ";
getline (cin,choice);
if( choice.compare("A")==0){
cout << "Enter Artist: ";
getline(cin,artist);
list->searchByArtist(artist);
}else{
// means by Title
cout << "Enter Title: ";
getline(cin,title);
list->searchByTitle(title);
}
cout << "------------------------------------------" << endl << endl;
}else if (userInput==5){
cout << "Enter Title: ";
getline(cin,title);
Song* song= list->getByTitle(title);
if (song==NULL)
cout << "No Match found!" << endl;
else
//cout << song->toString()<< endl;
cout << "------------------------------------------" << endl << endl;
}else if (userInput==6){
cout << "Enter Artist: ";
getline(cin,artist);
SongList* newList=list->getSongsByArtist(artist);
if (newList==NULL)
cout<< "No Match found!" <<endl;
else
newList->displayCatalog();
cout << "------------------------------------------" << endl << endl;
}else if (userInput==7){
list->displayCatalog();
cout << "------------------------------------------" << endl << endl;
}
displayMenue();
cin >> userInput;
if (userInput==8)
list->writeFile();
}
return 0;
}
| 29.70303 | 235 | 0.495103 | [
"object"
] |
92430cecd22ebefbd38b6d783754ddebd4ef5248 | 1,930 | cc | C++ | examples/ssl_socket/ssl_server.cc | vai-hhn/wampcc | ac206f60028406ea8af4c295e11cbc7de67cf2ad | [
"MIT"
] | 70 | 2017-03-09T12:45:30.000Z | 2021-12-31T20:34:40.000Z | examples/ssl_socket/ssl_server.cc | vai-hhn/wampcc | ac206f60028406ea8af4c295e11cbc7de67cf2ad | [
"MIT"
] | 54 | 2017-04-15T23:02:08.000Z | 2021-04-13T08:44:25.000Z | examples/ssl_socket/ssl_server.cc | vai-hhn/wampcc | ac206f60028406ea8af4c295e11cbc7de67cf2ad | [
"MIT"
] | 30 | 2017-06-02T14:12:28.000Z | 2021-12-06T07:28:48.000Z | /*
* Copyright (c) 2017 Darren Smith
*
* wampcc is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "wampcc/wampcc.h"
#include <algorithm>
using namespace wampcc;
/* Store of client connections. For this simple demo we dont have any code
* which deletes the sockets once they have closed. */
std::vector<std::unique_ptr<ssl_socket>> connections;
std::promise<void> exit_command_received;
/* Called on the kernel's IO thread when the server socket has accepted a new
* client socket. */
void on_ssl_accept(std::unique_ptr<ssl_socket>& client, uverr ec)
{
if (client)
{
ssl_socket* sk = client.get();
client->start_read(
[sk](char* src, size_t n) {
if (strncmp(src, "EXIT", 4)==0)
return exit_command_received.set_value();
std::reverse(src, src+n);
sk->write(src, n);
},
[sk](uverr){ sk->close(); });
connections.push_back(std::move(client));
}
}
int main(int argc, char** argv)
{
try {
if (argc < 2)
throw std::runtime_error("arguments must be: PORT");
/* Create the wampcc kernel, configured to support SSL. */
config conf;
conf.ssl.enable = true;
conf.ssl.certificate_file="server.crt";
conf.ssl.private_key_file="server.key";
kernel the_kernel(conf, logger::console());
/* Create an SSL socket, which will operate in server mode, via the call to
* listen. */
ssl_socket ssl_server(&the_kernel);
auto fut = ssl_server.listen("", argv[1], on_ssl_accept,
tcp_socket::addr_family::inet4);
if (auto e = fut.get())
throw std::runtime_error(std::string("listen failed: ")+e.message());
/* Suspend main thread */
exit_command_received.get_future().wait();
}
catch (const std::exception& e) {
std::cout << e.what() << std::endl;
return 1;
}
}
| 26.438356 | 79 | 0.640415 | [
"vector"
] |
924a344d1f0d411b7c4cc18dc33eb89f48a9c06f | 1,379 | cpp | C++ | semestral_project/src/event_setters.cpp | patrotom/pa2 | 900f6541017ad0e644f5a34d6a52b5ea438d0f5c | [
"MIT"
] | null | null | null | semestral_project/src/event_setters.cpp | patrotom/pa2 | 900f6541017ad0e644f5a34d6a52b5ea438d0f5c | [
"MIT"
] | null | null | null | semestral_project/src/event_setters.cpp | patrotom/pa2 | 900f6541017ad0e644f5a34d6a52b5ea438d0f5c | [
"MIT"
] | null | null | null | #include "event.h"
//--------------------------
void Event::setSummary ( string Summary ) { m_Summary = Summary; }
//--------------------------
void Event::setClass ( string Class ) { m_Class = Class; }
//--------------------------
void Event::setCategories ( vector<string> Categories ) { m_Categories = Categories; }
//--------------------------
void Event::setDuty ( bool Duty ) { m_Duty = Duty; }
//--------------------------
void Event::setMoveable ( bool Moveable ) { m_Moveable = Moveable; }
//--------------------------
void Event::setLimit ( int Limit ) { m_Limit = Limit; }
//--------------------------
void Event::setFrom ( Date_Time From ) { m_From = From; }
//--------------------------
void Event::setTo ( Date_Time To ) { m_To = To; }
//--------------------------
void Event::setUID ( size_t UID ) { m_UID = UID; }
//--------------------------
void Event::setrUID ( size_t rUID ) { return; }
//--------------------------
void Event::setfUID ( size_t fUID ) { return; }
//--------------------------
void Event::setSharedWith ( vector<string> SharedWith ) { m_SharedWith = SharedWith; }
//--------------------------
void Event::setType ( int Ind ) { m_Ind = Ind; }
//==========================
void Event_R::setrUID ( size_t rUID ) { m_rUID = rUID; }
//--------------------------
void Event_R::setfUID ( size_t fUID ) { m_fUID = fUID; }
//--------------------------
| 41.787879 | 86 | 0.453952 | [
"vector"
] |
924b797470b5276883ffc68a8dfd183cf731f45d | 6,849 | cpp | C++ | src/game/shared/utils/shared_utils.cpp | JoelTroch/halflife-unified-sdk | 0ebf7fbde22c346e202fdb26445d7470395eda2a | [
"Unlicense"
] | 31 | 2021-12-04T20:42:48.000Z | 2022-03-11T14:16:50.000Z | src/game/shared/utils/shared_utils.cpp | JoelTroch/halflife-unified-sdk | 0ebf7fbde22c346e202fdb26445d7470395eda2a | [
"Unlicense"
] | 79 | 2021-12-11T10:07:30.000Z | 2022-03-28T10:09:44.000Z | src/game/shared/utils/shared_utils.cpp | JoelTroch/halflife-unified-sdk | 0ebf7fbde22c346e202fdb26445d7470395eda2a | [
"Unlicense"
] | 8 | 2021-12-10T18:19:10.000Z | 2022-03-16T07:49:20.000Z | /***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#include <string>
#include "cbase.h"
#include "shared_utils.h"
#include "CStringPool.h"
#ifndef CLIENT_DLL
#include "CMapState.h"
#include "CServerLibrary.h"
#endif
CStringPool g_StringPool;
string_t ALLOC_STRING(const char* str)
{
return MAKE_STRING(g_StringPool.Allocate(str));
}
string_t ALLOC_ESCAPED_STRING(const char* str)
{
if (!str)
{
ALERT(at_warning, "nullptr string passed to ALLOC_ESCAPED_STRING\n");
return MAKE_STRING("");
}
std::string converted{str};
for (std::size_t index = 0; index < converted.length();)
{
if (converted[index] == '\\')
{
if (index + 1 >= converted.length())
{
ALERT(at_warning, "Incomplete escape character encountered in ALLOC_ESCAPED_STRING\n\tOriginal string: \"%s\"\n", str);
break;
}
const char next = converted[index + 1];
converted.erase(index, 1);
//TODO: support all escape characters
if (next == 'n')
{
converted[index] = '\n';
}
}
++index;
}
return ALLOC_STRING(converted.c_str());
}
void ClearStringPool()
{
//This clears the pool and frees memory
g_StringPool = CStringPool{};
}
void Con_Printf(const char* format, ...)
{
static char buffer[8192];
va_list list;
va_start(list, format);
const int result = vsnprintf(buffer, std::size(buffer), format, list);
if (result >= 0 && static_cast<std::size_t>(result) < std::size(buffer))
{
g_engfuncs.pfnServerPrint(buffer);
}
else
{
g_engfuncs.pfnServerPrint("Error logging message\n");
}
va_end(list);
}
bool COM_GetParam(const char* name, const char** next)
{
return g_engfuncs.pfnCheckParm(name, next) != 0;
}
bool COM_HasParam(const char* name)
{
return g_engfuncs.pfnCheckParm(name, nullptr) != 0;
}
const char* COM_Parse(const char* data)
{
int c;
int len;
len = 0;
com_token[0] = 0;
if (!data)
return nullptr;
// skip whitespace
skipwhite:
while ((c = *data) <= ' ')
{
if (c == 0)
return nullptr; // end of file;
data++;
}
// skip // comments
if (c == '/' && data[1] == '/')
{
while ('\0' != *data && *data != '\n')
data++;
goto skipwhite;
}
// handle quoted strings specially
if (c == '\"')
{
data++;
while (true)
{
c = *data++;
if (c == '\"' || '\0' == c)
{
com_token[len] = 0;
return data;
}
com_token[len] = c;
len++;
}
}
// parse single characters
if (c == '{' || c == '}' || c == ')' || c == '(' || c == '\'' || c == ',')
{
com_token[len] = c;
len++;
com_token[len] = 0;
return data + 1;
}
// parse a regular word
do
{
com_token[len] = c;
data++;
len++;
c = *data;
if (c == '{' || c == '}' || c == ')' || c == '(' || c == '\'' || c == ',')
break;
} while (c > 32);
com_token[len] = 0;
return data;
}
bool COM_TokenWaiting(const char* buffer)
{
for (const char* p = buffer; '\0' != *p && *p != '\n'; ++p)
{
if (0 == isspace(*p) || 0 != isalnum(*p))
return true;
}
return false;
}
static unsigned int glSeed = 0;
unsigned int seed_table[256] =
{
28985, 27138, 26457, 9451, 17764, 10909, 28790, 8716, 6361, 4853, 17798, 21977, 19643, 20662, 10834, 20103,
27067, 28634, 18623, 25849, 8576, 26234, 23887, 18228, 32587, 4836, 3306, 1811, 3035, 24559, 18399, 315,
26766, 907, 24102, 12370, 9674, 2972, 10472, 16492, 22683, 11529, 27968, 30406, 13213, 2319, 23620, 16823,
10013, 23772, 21567, 1251, 19579, 20313, 18241, 30130, 8402, 20807, 27354, 7169, 21211, 17293, 5410, 19223,
10255, 22480, 27388, 9946, 15628, 24389, 17308, 2370, 9530, 31683, 25927, 23567, 11694, 26397, 32602, 15031,
18255, 17582, 1422, 28835, 23607, 12597, 20602, 10138, 5212, 1252, 10074, 23166, 19823, 31667, 5902, 24630,
18948, 14330, 14950, 8939, 23540, 21311, 22428, 22391, 3583, 29004, 30498, 18714, 4278, 2437, 22430, 3439,
28313, 23161, 25396, 13471, 19324, 15287, 2563, 18901, 13103, 16867, 9714, 14322, 15197, 26889, 19372, 26241,
31925, 14640, 11497, 8941, 10056, 6451, 28656, 10737, 13874, 17356, 8281, 25937, 1661, 4850, 7448, 12744,
21826, 5477, 10167, 16705, 26897, 8839, 30947, 27978, 27283, 24685, 32298, 3525, 12398, 28726, 9475, 10208,
617, 13467, 22287, 2376, 6097, 26312, 2974, 9114, 21787, 28010, 4725, 15387, 3274, 10762, 31695, 17320,
18324, 12441, 16801, 27376, 22464, 7500, 5666, 18144, 15314, 31914, 31627, 6495, 5226, 31203, 2331, 4668,
12650, 18275, 351, 7268, 31319, 30119, 7600, 2905, 13826, 11343, 13053, 15583, 30055, 31093, 5067, 761,
9685, 11070, 21369, 27155, 3663, 26542, 20169, 12161, 15411, 30401, 7580, 31784, 8985, 29367, 20989, 14203,
29694, 21167, 10337, 1706, 28578, 887, 3373, 19477, 14382, 675, 7033, 15111, 26138, 12252, 30996, 21409,
25678, 18555, 13256, 23316, 22407, 16727, 991, 9236, 5373, 29402, 6117, 15241, 27715, 19291, 19888, 19847};
unsigned int U_Random()
{
glSeed *= 69069;
glSeed += seed_table[glSeed & 0xff];
return (++glSeed & 0x0fffffff);
}
void U_Srand(unsigned int seed)
{
glSeed = seed_table[seed & 0xff];
}
/*
=====================
UTIL_SharedRandomLong
=====================
*/
int UTIL_SharedRandomLong(unsigned int seed, int low, int high)
{
unsigned int range;
U_Srand((int)seed + low + high);
range = high - low + 1;
if (0 == (range - 1))
{
return low;
}
else
{
int offset;
int rnum;
rnum = U_Random();
offset = rnum % range;
return (low + offset);
}
}
/*
=====================
UTIL_SharedRandomFloat
=====================
*/
float UTIL_SharedRandomFloat(unsigned int seed, float low, float high)
{
//
unsigned int range;
U_Srand((int)seed + *(int*)&low + *(int*)&high);
U_Random();
U_Random();
range = high - low;
if (0 == range)
{
return low;
}
else
{
int tensixrand;
float offset;
tensixrand = U_Random() & 65535;
offset = (float)tensixrand / 65536.0;
return (low + offset * range);
}
}
const char* UTIL_CheckForGlobalModelReplacement(const char* s)
{
#ifndef CLIENT_DLL
//Check if there is global model replacement needed.
//TODO: try to avoid allocating here (EASTL fixed_string could help)
const std::string searchString{s};
ToLower(searchString);
const auto& map = g_Server.GetMapState()->m_GlobalModelReplacement;
if (auto it = map.find(searchString); it != map.end())
{
s = it->second.c_str();
}
#endif
return s;
}
int UTIL_PrecacheModel(const char* s)
{
s = UTIL_CheckForGlobalModelReplacement(s);
return g_engfuncs.pfnPrecacheModel(s);
}
| 21.951923 | 123 | 0.635567 | [
"object",
"model"
] |
924f4a7a67dcc9ad39863ce2ca58eacf686728b0 | 4,744 | cpp | C++ | Opengl-Toolkit/ShaderProgram.cpp | Ultranull/visualglfwtest | 41b759d40463c4e9108b2f044144421c16450907 | [
"MIT"
] | 1 | 2019-02-18T22:20:13.000Z | 2019-02-18T22:20:13.000Z | Opengl-Toolkit/ShaderProgram.cpp | Ultranull/visualglfwtest | 41b759d40463c4e9108b2f044144421c16450907 | [
"MIT"
] | null | null | null | Opengl-Toolkit/ShaderProgram.cpp | Ultranull/visualglfwtest | 41b759d40463c4e9108b2f044144421c16450907 | [
"MIT"
] | null | null | null | #include "ShaderProgram.h"
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
string readFile(const char *file) {//FIX! place in a header as a util
string content;
ifstream stream(file);
if (stream.is_open()) {
stringstream ss;
ss << stream.rdbuf();
content = ss.str();
stream.close();
}
else {
printf("Failed to open %s\n", file);
return "";
}
return content;
}
bool compileshader(const char* file, GLuint id) {
GLint result = GL_FALSE;
int infoLogLength;
printf("Compiling shader: %s\n", file);
string content = readFile(file);
if (content.compare("") == 0) { return NULL; }
char const * src = content.c_str();
const GLint length = content.size();
glShaderSource(id, 1, &src, &length);
glCompileShader(id);
glGetShaderiv(id, GL_COMPILE_STATUS, &result);
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &infoLogLength);
if (infoLogLength > 1) {
vector<char> errormessage(infoLogLength + 1);
glGetShaderInfoLog(id, infoLogLength, NULL, &errormessage[0]);
printf("%s compile error:\n\t%s\n", file, &errormessage[0]);
return false;
}
return true;
}
GLuint loadshaders(const char *vertexfile, const char *fragmentfile) {
GLuint vertexID = glCreateShader(GL_VERTEX_SHADER);
GLuint fragmentID = glCreateShader(GL_FRAGMENT_SHADER);
GLint result = GL_FALSE;
int infoLogLength;
if (!compileshader(vertexfile, vertexID)) { return NULL; }
if (!compileshader(fragmentfile, fragmentID)) { return NULL; }
printf("linking program\n");
GLuint programID = glCreateProgram();
glAttachShader(programID, vertexID);
glAttachShader(programID, fragmentID);
glLinkProgram(programID);
glGetProgramiv(programID, GL_LINK_STATUS, &result);
glGetProgramiv(programID, GL_INFO_LOG_LENGTH, &infoLogLength);
if (infoLogLength > 1) {
vector<char> errormessage(infoLogLength + 1);
glGetProgramInfoLog(programID, infoLogLength, NULL, &errormessage[0]);
printf("link error:\n%s\n", &errormessage[0]);
return NULL;
}
glDetachShader(programID, vertexID);
glDetachShader(programID, fragmentID);
glDeleteShader(vertexID);
glDeleteShader(fragmentID);
return programID;
}
GLuint loadshaders(const char *vertexfile, const char *fragmentfile, const char *geometryfile) {
GLuint vertexID = glCreateShader(GL_VERTEX_SHADER);
GLuint fragmentID = glCreateShader(GL_FRAGMENT_SHADER);
GLuint geometryID = glCreateShader(GL_GEOMETRY_SHADER);
GLint result = GL_FALSE;
int infoLogLength;
if (!compileshader(vertexfile, vertexID)) { return NULL; }
if (!compileshader(fragmentfile, fragmentID)) { return NULL; }
if (!compileshader(geometryfile, geometryID)) { return NULL; }
printf("linking program\n");
GLuint programID = glCreateProgram();
glAttachShader(programID, vertexID);
glAttachShader(programID, fragmentID);
glAttachShader(programID, geometryID);
glLinkProgram(programID);
glGetProgramiv(programID, GL_LINK_STATUS, &result);
glGetProgramiv(programID, GL_INFO_LOG_LENGTH, &infoLogLength);
if (infoLogLength > 1) {
vector<char> errormessage(infoLogLength + 1);
glGetProgramInfoLog(programID, infoLogLength, NULL, &errormessage[0]);
printf("link error:\n%s\n", &errormessage[0]);
return NULL;
}
glDetachShader(programID, vertexID);
glDetachShader(programID, fragmentID);
glDetachShader(programID, geometryID);
glDeleteShader(vertexID);
glDeleteShader(fragmentID);
glDeleteShader(geometryID);
return programID;
}
ShaderProgram::ShaderProgram(std::string vert, std::string frag) {
programID = loadshaders(vert.c_str(), frag.c_str());
if (programID == NULL) {
getchar();
exit(-1);
}
}
ShaderProgram::ShaderProgram(std::string vert, std::string frag, std::string geom) {
programID = loadshaders(vert.c_str(), frag.c_str(),geom.c_str());
if (programID == NULL) {
getchar();
exit(-1);
}
}
ShaderProgram::~ShaderProgram() {
}
void ShaderProgram::cleanup() {
glDeleteProgram(programID);
}
void ShaderProgram::setUniformVec3(std::string name, glm::vec3 v) {
GLuint id = glGetUniformLocation(programID, name.c_str());
if (id == -1)return;
glUniform3f(id, v.x, v.y, v.z);
}
void ShaderProgram::setUniformMat4(std::string name, glm::mat4 m) {
GLuint id = glGetUniformLocation(programID, name.c_str());
if (id == -1)return;
glUniformMatrix4fv(id, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniformf(std::string name, float f) {
GLuint id = glGetUniformLocation(programID, name.c_str());
if (id == -1)return;
glUniform1f(id, f);
}
void ShaderProgram::setUniformi(std::string name, int i) {
GLuint id = glGetUniformLocation(programID, name.c_str());
if (id == -1)return;
glUniform1i(id, i);
}
void ShaderProgram::bind() {
glUseProgram(programID);
}
GLuint ShaderProgram::getProgramID() {
return programID;
}
| 27.581395 | 96 | 0.732293 | [
"vector"
] |
9254af011c4f6978039cdcaca8fd2661ad228852 | 1,602 | hpp | C++ | header/sem_analyzer.hpp | MatheusCTeixeira/Compiler | f9f75d6a1a092b8dcef11af6eac4e1ff59d9f6a0 | [
"MIT"
] | null | null | null | header/sem_analyzer.hpp | MatheusCTeixeira/Compiler | f9f75d6a1a092b8dcef11af6eac4e1ff59d9f6a0 | [
"MIT"
] | null | null | null | header/sem_analyzer.hpp | MatheusCTeixeira/Compiler | f9f75d6a1a092b8dcef11af6eac4e1ff59d9f6a0 | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
#include <iostream>
#include <utility>
#include <stack>
#include <unordered_map>
#include "lex_analyzer.hpp"
#include "infix_to_prefix.hpp"
namespace comp
{
struct var_table
{
std::string m_name;
int m_value;
int m_scope;
};
enum class DECLARATION_TYPE{ NOT_DECLARED = 0, DECLARED_OUTER_SCOPE, DECLARED_IN_SCOPE};
class sem_analyzer
{
public:
sem_analyzer();
~sem_analyzer();
bool has_error() const;
void process(std::vector<lex_analyzer::token_type> tokens);
void print_log() const;
protected:
private:
DECLARATION_TYPE already_declared(std::string var_name) const;
void begin_scope(lex_analyzer::token_type token);
void end_scope(lex_analyzer::token_type token);
void process_declaration(lex_analyzer::token_type token); /* Switch beetween process_(re)declaration_(*) */
void process_declaration_in_scope(lex_analyzer::token_type token);
void process_declaration_outer_scope(lex_analyzer::token_type token);
void process_no_declared(lex_analyzer::token_type token);
void process_reference(lex_analyzer::token_type token);
void process_reference_valid(lex_analyzer::token_type token);
void process_reference_invalid(lex_analyzer::token_type token);
void process_div_by_zero(lex_analyzer::token_type token);
std::vector<std::string> m_log;
std::unordered_map<std::string, std::stack<std::string>> m_var_table;
bool m_has_error = false;
};
} | 28.105263 | 115 | 0.696629 | [
"vector"
] |
925ae6bd373439d2c0eb6b19bd690a577f54b1c4 | 5,925 | cpp | C++ | sample/gl/icp/main.cpp | sanko-shoko/simplesp | 6a71022dbb9a304e5a68d60885a04906dc78913a | [
"MIT"
] | 24 | 2017-09-07T16:08:33.000Z | 2022-02-26T16:32:48.000Z | sample/gl/icp/main.cpp | sanko-shoko/simplesp | 6a71022dbb9a304e5a68d60885a04906dc78913a | [
"MIT"
] | null | null | null | sample/gl/icp/main.cpp | sanko-shoko/simplesp | 6a71022dbb9a304e5a68d60885a04906dc78913a | [
"MIT"
] | 8 | 2018-11-30T02:53:24.000Z | 2021-05-18T06:30:42.000Z | #define SP_USE_IMGUI 1
#include "simplesp.h"
#include "spex/spgl.h"
using namespace sp;
static bool ShowText(const char *text, const ImVec2 &pos, const ImVec4 &col = ImVec4(1.f, 1.f, 1.f, 1.f), const float scale = 1.f) {
char name[32] = { 0 };
const int maxv = 100;
for (int i = 0; i < maxv; i++) {
sprintf(name, "##showtext%04d", i);
const ImGuiWindow* window = ImGui::FindWindowByName(name);
if (window == NULL || window->Active == false) {
break;
}
}
ImGui::PushStyleColor(ImGuiCol_Text, col);
{
ImGui::Begin(name, NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoBackground);
const float backup = ImGui::GetFontSize();
ImGui::SetWindowFontScale(scale);
ImGui::SetWindowPos(pos, ImGuiCond_Always);
ImGui::Text(text);
ImGui::SetWindowFontScale(backup);
ImGui::End();
}
ImGui::PopStyleColor(1);
return true;
}
class ICPGUI : public BaseWindowIMGUI {
// camera
CamParam m_cam;
// image
Mem2<Col3> m_img;
// model
Mem1<Mesh3> m_model;
// data A
Mem<VecPD3> m_dataA;
Pose m_poseA;
// data B (target)
Mem<VecPD3> m_dataB;
Pose m_poseB;
int m_it;
private:
void help() {
printf("[points] : controlled by mouse\n");
printf("'a' key : render target (points)\n");
printf("'s' key : render target (depth map)\n");
printf("'d' key : calc ICP\n");
printf("\n");
}
virtual void init() {
help();
m_cam = getCamParam(640, 480);
m_model = loadBunny(SP_DATA_DIR "/stanford/bun_zipper.ply");
SP_ASSERT(m_model.size() > 0);
m_poseA = getPose(getVec3(0.0, 0.0, getModelDistance(m_model, m_cam)));
m_dataA = getModelPoint(m_model);
reset();
}
void reset() {
m_it = 0;
}
virtual void keyFun(int key, int scancode, int action, int mods) {
if (m_key[GLFW_KEY_A] == 1) {
m_dataB = Mem1<VecPD3>(m_dataA.size());
for (int i = 0; i < m_dataB.size(); i++) {
m_dataB[i] = m_poseA * m_dataA[i];
}
m_poseB = m_poseA;
reset();
}
if (m_key[GLFW_KEY_S] == 1) {
m_dataB = Mem2<VecPD3>(m_cam.dsize);
m_dataB.zero();
renderVecPD(m_dataB, m_cam, m_poseA, m_model);
const double distance = getModelDistance(m_model, m_cam);
const double radius = getModelRadius(m_model);
cnvDepthToImg(m_img, m_dataB, distance - 2 * radius, distance + 2 * radius);
m_poseB = m_poseA;
reset();
}
if (m_key[GLFW_KEY_D] > 0 && m_dataB.size() > 0) {
// point to point
if (m_dataB.dim == 1) {
calcICP(m_poseA, m_dataB, m_dataA, 1);
}
// point to 2d map
if (m_dataB.dim == 2) {
calcICP(m_poseA, m_cam, m_dataB, m_dataA, 1);
}
m_it++;
}
}
virtual void display() {
glClearColor(0.10f, 0.12f, 0.12f, 0.00f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// render dataB
{
if (m_dataB.dim == 1) {
glLoadView3D(m_cam, m_viewPos, m_viewScale);
glPointSize(5.f);
glBegin(GL_POINTS);
glColor3f(0.2f, 0.2f, 0.7f);
for (int i = 0; i < m_dataB.size(); i++) {
glVertex(m_dataB[i].pos);
}
glEnd();
}
if (m_dataB.dim == 2) {
glLoadView2D(m_cam, m_viewPos, m_viewScale);
glTexImg(m_img);
}
}
// render dataA
{
glLoadView3D(m_cam, m_viewPos, m_viewScale);
glClear(GL_DEPTH_BUFFER_BIT);
{
glLoadMatrix(m_poseA);
// render points
glPointSize(3.f);
glBegin(GL_POINTS);
glColor3f(0.2f, 0.7f, 0.2f);
for (int i = 0; i < m_dataA.size(); i++) {
glVertex(m_dataA[i].pos);
}
glEnd();
}
{
glLoadMatrix(m_poseA);
glLineWidth(2.f);
glBegin(GL_LINES);
glAxis(50.0);
glEnd();
}
}
{
const Mat vmat = glGetViewMat(m_cam.dsize, m_viewPos, m_viewScale);
if (m_dataA.size() > 0) {
const Vec2 pix = vmat * mulCam(m_cam, prjVec(m_poseA.pos));
const string str = string("data A (points)");
ShowText(str.c_str(), ImVec2(float(pix.x + 100.0), float(pix.y - 120.0)), ImVec4(1.f, 1.f, 0.f, 1.f), 1.4f);
}
if(m_dataB.size() > 0){
const Vec2 pix = vmat * mulCam(m_cam, prjVec(m_poseB.pos));
const string str = string("data B ") + ((m_dataB.dim == 1) ? "(points)" : "(depth map)");
ShowText(str.c_str(), ImVec2(float(pix.x - 220.0), float(pix.y + 120.0)), ImVec4(0.f, 1.f, 1.f, 1.f), 1.4f);
}
if (m_it > 0) {
const string str = "icp iteration :" + to_string(m_it);
ShowText(str.c_str(), ImVec2(90.f, 70.f), ImVec4(1.f, 1.f, 1.f, 1.f), 1.4f);
}
}
}
virtual void mousePos(double x, double y) {
if (controlPose(m_poseA, m_mouse, m_wcam, m_viewScale) == true) {
reset();
}
}
virtual void mouseScroll(double x, double y) {
if (controlPose(m_poseA, m_mouse, m_wcam, m_viewScale) == true) {
reset();
}
}
};
int main(){
ICPGUI win;
win.execute("icp", 800, 600);
return 0;
} | 26.809955 | 132 | 0.49519 | [
"render",
"model"
] |
925c9606d9b92fa530dd874c5c6026a1543d778a | 3,396 | cpp | C++ | problems/symbol-table/IntervalTree.cpp | rahulpawar1489/Algorithms | bdf26092f141526b7f3147772732bfbfb4fe1a17 | [
"MIT"
] | 1 | 2022-01-02T12:17:19.000Z | 2022-01-02T12:17:19.000Z | problems/symbol-table/IntervalTree.cpp | rahulpawar1489/Algorithms | bdf26092f141526b7f3147772732bfbfb4fe1a17 | [
"MIT"
] | null | null | null | problems/symbol-table/IntervalTree.cpp | rahulpawar1489/Algorithms | bdf26092f141526b7f3147772732bfbfb4fe1a17 | [
"MIT"
] | 1 | 2021-03-27T18:42:13.000Z | 2021-03-27T18:42:13.000Z | // https://www.geeksforgeeks.org/interval-tree/
// https://iq.opengenus.org/interval-tree/
#include <iostream>
#include <vector>
#include <climits>
class Interval
{
private:
int low;
int high;
public:
Interval() { }
Interval(int l, int h) : low(l), high(h) {}
int getLow() { return low; }
int getHigh() { return high; }
void setLow(int l) { low = l; }
void setHigh(int h) { high = h; }
bool overlap(Interval& other)
{
if (this->low <= other.low && other.low <= this->high) {
return true;
}
return false;
}
};
class IntervalTree
{
private:
class Node
{
public:
Interval interval;
int max;
Node* left;
Node* right;
Node(Interval inter) : left{nullptr}, right{nullptr}
{
interval.setLow(inter.getLow());
interval.setHigh(inter.getHigh());
max = inter.getHigh();
}
};
Node* root;
void inorder(Node* node, std::vector<Node*>& path)
{
if (node == nullptr) {
return;
}
inorder(node->left, path);
path.push_back(node);
inorder(node->right, path);
}
void print(std::vector<Node*>& path)
{
for (auto node : path) {
std::cout << "[" << node->interval.getLow() << ", " << node->interval.getHigh() << "]"
<< " max = " << node->max << "\n";
}
}
Node* insert(Node* node, Interval& interval)
{
if (node == nullptr) {
return new Node(interval);
}
if (interval.getLow() < node->interval.getLow()) {
node->left = insert(node->left, interval);
} else {
node->right = insert(node->right, interval);
}
if (node->max < interval.getHigh()) {
node->max = interval.getHigh();
}
return node;
}
Node* search(Node* node, Interval& interval)
{
if (node == nullptr) {
return nullptr;
}
if (interval.overlap(node->interval)) {
return node;
}
if (node->left != nullptr && node->left->max >= interval.getLow()) {
return search(node->left, interval);
}
return search(node->right, interval);
}
public:
IntervalTree() : root{nullptr} { }
IntervalTree(std::vector<Interval>& intervals) : root{nullptr}
{
for (auto interval : intervals) {
root = insert(root, interval);
}
}
void inorder()
{
std::vector<Node*> path;
inorder(root, path);
print(path);
}
void search(Interval& interval)
{
if (root == nullptr) {
return;
}
Node* node = search(root, interval);
if (node == nullptr) {
std::cout << " No overlapping interval\n";
} else {
std::cout << " Overlaps with [" << node->interval.getLow() << ", " << node->interval.getHigh() << "]\n";
}
}
};
int main()
{
std::vector<Interval> intervals {{15, 20}, {10, 30}, {17, 19},
{5, 20}, {12, 15}, {30, 40}};
IntervalTree tree(intervals);
std::cout << "Inorder : \n";
tree.inorder();
Interval x {5, 6};
std::cout << "Searching for interval [" << x.getLow() << "," << x.getHigh() << "]";
tree.search(x);
return 0;
}
| 22.490066 | 116 | 0.496172 | [
"vector"
] |
925eeadb8905b989bf8c587161f6d065a253326a | 1,837 | cpp | C++ | 2018/day-06/6a.cpp | Valokoodari/advent-of-code | c664987f739e0b07ddad34bad87d56768556a5a5 | [
"MIT"
] | 2 | 2021-12-27T18:59:11.000Z | 2022-01-10T02:31:36.000Z | 2018/day-06/6a.cpp | Valokoodari/advent-of-code-2019 | c664987f739e0b07ddad34bad87d56768556a5a5 | [
"MIT"
] | null | null | null | 2018/day-06/6a.cpp | Valokoodari/advent-of-code-2019 | c664987f739e0b07ddad34bad87d56768556a5a5 | [
"MIT"
] | 2 | 2021-12-23T17:29:10.000Z | 2021-12-24T03:21:49.000Z | #include <iostream>
#include <string>
#include <vector>
int a, s, sc;
int size = 360;
std::string c;
std::vector<int> d, e;
std::vector<std::vector<int>> cs;
std::vector<std::vector<int>> map(size);
int main() {
freopen("6_input", "r", stdin);
freopen("6a_output", "w", stdout);
for (int i = 0; i < map.size(); i++) {
map[i].resize(size);
for (int j = 0; j < map[i].size(); j++) {
map[i][j] = 0;
}
}
while (std::getline(std::cin, c)) {
a = c.find(",");
cs.push_back({stoi(c.substr(0, a)), stoi(c.substr(a + 1, c.size() - a - 1))});
}
for (int i = 0; i < map.size(); i++) {
for (int j = 0; j < map[i].size(); j++) {
d = {};
s = size * 2;
sc = 0;
for (int k = 0; k < cs.size(); k++) {
d.push_back(abs(i-cs[k][0]) + abs(j-cs[k][1]));
if (d[k] < s) {
s = d[k];
sc = k + 1;
}
}
for (int k = 0; k < d.size(); k++) {
if (k == sc - 1)
continue;
if (d[k] == s) {
sc = 0;
break;
}
}
map[i][j] = sc;
}
}
for (int i = 0; i <= cs.size(); i++) {
e.push_back(0);
}
d = e;
for (int i = 0; i < map.size(); i++) {
for (int j = 0; j < map[i].size(); j++) {
if (i > 1 && j > 1 && i < map.size() - 1 && j < map[i].size() - 1) {
d[map[i][j]]++;
}
e[map[i][j]]++;
}
}
s = 0;
for (int i = 1; i < d.size(); i++) {
if (d[i] != e[i])
d[i] = 0;
if (s < d[i])
s = d[i];
}
std::cout << s << "\n";
return 0;
} | 23.551282 | 86 | 0.331519 | [
"vector"
] |
1782b525dbefcaec4398f222f381106be82ae87a | 3,179 | cpp | C++ | prj/src/dno.cpp | Jakub-Czerniak/ZadanieDron | 89b2fafbba58582b5bb1380dc36c77b066077e67 | [
"MIT"
] | null | null | null | prj/src/dno.cpp | Jakub-Czerniak/ZadanieDron | 89b2fafbba58582b5bb1380dc36c77b066077e67 | [
"MIT"
] | null | null | null | prj/src/dno.cpp | Jakub-Czerniak/ZadanieDron | 89b2fafbba58582b5bb1380dc36c77b066077e67 | [
"MIT"
] | null | null | null | #include "dno.hh"
dno::dno(Wektor3D srodek,double x)
{
Srodek=srodek;
X=x;
}
bool dno::Czy_Kolizja(InterfejsDrona *InDr)
{
double R=InDr->Get_R();
Wektor3D C=InDr->Get_C();
if(Srodek[2]+R<=C[2])
{
return false;
}
std::cout<<"Dno Kolizja"<< std::endl;
return true;
}
void dno::rysuj()
{
ID= api->draw_surface(vector<vector<Point3D> > {{
drawNS::Point3D(-X+Srodek[0],-X+Srodek[1],Srodek[2]), drawNS::Point3D(-X+Srodek[0],-0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(-X+Srodek[0],0+Srodek[1],Srodek[2]), drawNS::Point3D(-X+Srodek[0],0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(-X+Srodek[0],X+Srodek[1],Srodek[2])
},{
drawNS::Point3D(-0.75*X+Srodek[0],-X+Srodek[1],Srodek[2]), drawNS::Point3D(-0.75*X+Srodek[0],-0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(-0.75*X+Srodek[0],0+Srodek[1],Srodek[2]), drawNS::Point3D(-0.75*X+Srodek[0],0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(-0.75*X+Srodek[0],X+Srodek[1],Srodek[2])
},{
drawNS::Point3D(-0.5*X+Srodek[0],-X+Srodek[1],Srodek[2]), drawNS::Point3D(-0.5*X+Srodek[0],-0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(-0.5*X+Srodek[0],0+Srodek[1],Srodek[2]), drawNS::Point3D(-0.5*X+Srodek[0],0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(-0.5*X+Srodek[0],X+Srodek[1],Srodek[2])
},{
drawNS::Point3D(-0.25*X+Srodek[0],-X+Srodek[1],Srodek[2]), drawNS::Point3D(-0.25*X+Srodek[0],-0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(-0.25*X+Srodek[0],0+Srodek[1],Srodek[2]), drawNS::Point3D(-0.25*X+Srodek[0],0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(-0.25*X+Srodek[0],X+Srodek[1],Srodek[2])
},{
drawNS::Point3D(-0+Srodek[0],-X+Srodek[1],Srodek[2]), drawNS::Point3D(-0+Srodek[0],-0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(-0+Srodek[0],0+Srodek[1],Srodek[2]), drawNS::Point3D(-0+Srodek[0],0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(-0+Srodek[0],X+Srodek[1],Srodek[2])
},{
drawNS::Point3D(0.25*X+Srodek[0],-X+Srodek[1],Srodek[2]), drawNS::Point3D(0.25*X+Srodek[0],-0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(0.25*X+Srodek[0],0+Srodek[1],Srodek[2]), drawNS::Point3D(0.25*X+Srodek[0],0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(0.25*X+Srodek[0],X+Srodek[1],Srodek[2])
},{
drawNS::Point3D(0.5*X+Srodek[0],-X+Srodek[1],Srodek[2]), drawNS::Point3D(0.5*X+Srodek[0],-0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(0.5*X+Srodek[0],0+Srodek[1],Srodek[2]), drawNS::Point3D(0.5*X+Srodek[0],0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(0.5*X+Srodek[0],X+Srodek[1],Srodek[2])
},{
drawNS::Point3D(0.75*X+Srodek[0],-X+Srodek[1],Srodek[2]), drawNS::Point3D(0.75*X+Srodek[0],-0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(0.75*X+Srodek[0],0+Srodek[1],Srodek[2]), drawNS::Point3D(0.75*X+Srodek[0],0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(0.75*X+Srodek[0],X+Srodek[1],Srodek[2])
},{
drawNS::Point3D(X+Srodek[0],-X+Srodek[1],Srodek[2]), drawNS::Point3D(X+Srodek[0],-0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(X+Srodek[0],0+Srodek[1],Srodek[2]), drawNS::Point3D(X+Srodek[0],0.5*X+Srodek[1],Srodek[2]), drawNS::Point3D(X+Srodek[0],X+Srodek[1],Srodek[2])
}},"grey");
} | 73.930233 | 307 | 0.619063 | [
"vector"
] |
1783830afb0214c7c15d68726b51e6e015aeb4c0 | 3,433 | cpp | C++ | aws-cpp-sdk-wafv2/source/model/IPSet.cpp | grujicbr/aws-sdk-cpp | bdd43c178042f09c6739645e3f6cd17822a7c35c | [
"Apache-2.0"
] | 1 | 2020-03-11T05:36:20.000Z | 2020-03-11T05:36:20.000Z | aws-cpp-sdk-wafv2/source/model/IPSet.cpp | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-wafv2/source/model/IPSet.cpp | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/wafv2/model/IPSet.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace WAFV2
{
namespace Model
{
IPSet::IPSet() :
m_nameHasBeenSet(false),
m_idHasBeenSet(false),
m_aRNHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_iPAddressVersion(IPAddressVersion::NOT_SET),
m_iPAddressVersionHasBeenSet(false),
m_addressesHasBeenSet(false)
{
}
IPSet::IPSet(JsonView jsonValue) :
m_nameHasBeenSet(false),
m_idHasBeenSet(false),
m_aRNHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_iPAddressVersion(IPAddressVersion::NOT_SET),
m_iPAddressVersionHasBeenSet(false),
m_addressesHasBeenSet(false)
{
*this = jsonValue;
}
IPSet& IPSet::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Name"))
{
m_name = jsonValue.GetString("Name");
m_nameHasBeenSet = true;
}
if(jsonValue.ValueExists("Id"))
{
m_id = jsonValue.GetString("Id");
m_idHasBeenSet = true;
}
if(jsonValue.ValueExists("ARN"))
{
m_aRN = jsonValue.GetString("ARN");
m_aRNHasBeenSet = true;
}
if(jsonValue.ValueExists("Description"))
{
m_description = jsonValue.GetString("Description");
m_descriptionHasBeenSet = true;
}
if(jsonValue.ValueExists("IPAddressVersion"))
{
m_iPAddressVersion = IPAddressVersionMapper::GetIPAddressVersionForName(jsonValue.GetString("IPAddressVersion"));
m_iPAddressVersionHasBeenSet = true;
}
if(jsonValue.ValueExists("Addresses"))
{
Array<JsonView> addressesJsonList = jsonValue.GetArray("Addresses");
for(unsigned addressesIndex = 0; addressesIndex < addressesJsonList.GetLength(); ++addressesIndex)
{
m_addresses.push_back(addressesJsonList[addressesIndex].AsString());
}
m_addressesHasBeenSet = true;
}
return *this;
}
JsonValue IPSet::Jsonize() const
{
JsonValue payload;
if(m_nameHasBeenSet)
{
payload.WithString("Name", m_name);
}
if(m_idHasBeenSet)
{
payload.WithString("Id", m_id);
}
if(m_aRNHasBeenSet)
{
payload.WithString("ARN", m_aRN);
}
if(m_descriptionHasBeenSet)
{
payload.WithString("Description", m_description);
}
if(m_iPAddressVersionHasBeenSet)
{
payload.WithString("IPAddressVersion", IPAddressVersionMapper::GetNameForIPAddressVersion(m_iPAddressVersion));
}
if(m_addressesHasBeenSet)
{
Array<JsonValue> addressesJsonList(m_addresses.size());
for(unsigned addressesIndex = 0; addressesIndex < addressesJsonList.GetLength(); ++addressesIndex)
{
addressesJsonList[addressesIndex].AsString(m_addresses[addressesIndex]);
}
payload.WithArray("Addresses", std::move(addressesJsonList));
}
return payload;
}
} // namespace Model
} // namespace WAFV2
} // namespace Aws
| 22.292208 | 117 | 0.721526 | [
"model"
] |
178cf75c8e9d942012d2a8eac65ef9bfdbbf0e55 | 2,382 | cpp | C++ | ABC/ABC070/D.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | 1 | 2021-06-01T17:13:44.000Z | 2021-06-01T17:13:44.000Z | ABC/ABC070/D.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | null | null | null | ABC/ABC070/D.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | null | null | null | //#include <cassert>
//#include <cstdio>
//#include <cmath>
//#include <iostream>
//#include <sstream>
//#include <string>
//#include <vector>
//#include <map>
//#include <queue>
//#include <algorithm>
//
//const int MOD = 1000000007, INF = 1111111111;
//using namespace std;
//using lint = long long;
//
//template <class T>
//ostream &operator<<(ostream &os, const vector<T> &vec) {
// for (int i = 0; i < (int)vec.size(); i++) {
// os << vec[i] << (i + 1 == vec.size() ? "" : " ");
// }
// return os;
//}
//
//#ifdef _DEBUG
//template <class Head>
//void dump(const char* str, Head &&h) { cerr << str << " = " << h << "\n"; };
//template <class Head, class... Tail>
//void dump(const char* str, Head &&h, Tail &&... t) {
// while (*str != ',') cerr << *str++; cerr << " = " << h << "\n";
// dump(str + 1, t...);
//}
//#define DMP(...) dump(#__VA_ARGS__, __VA_ARGS__)
//#else
//#define DMP(...) ((void)0)
//#endif
//
//template<class T = lint>
//struct Edge {
// int to;
// T cost;
// Edge() {}
// Edge(int to, T cost) : to(to), cost(cost) {}
// bool operator>(const Edge &r) const { return this->cost > r.cost; }
//};
//
//template<class T>
//vector<T> Dijkstra(vector<vector<Edge<T>>> &edges, int st) {
//
// int V = (int)edges.size();
// const T INF = numeric_limits<T>::max();
// vector<T> cost(V, INF);
// cost[st] = 0;
//
// priority_queue<Edge<T>, vector<Edge<T>>, greater<Edge<T>>> p_que;
// p_que.emplace(st, cost[st]);
//
// while (!p_que.empty()) {
//
// Edge<T> now(p_que.top().to, p_que.top().cost);
// p_que.pop();
//
// if (cost[now.to] < now.cost) continue;
// for (const Edge<T> &e : edges[now.to]) {
// T tmp_cost = now.cost + e.cost;
// if (cost[e.to] > tmp_cost) {
// cost[e.to] = tmp_cost;
// p_que.emplace(e.to, cost[e.to]);
// }
// }
// }
//
// return cost; // min cost to vertex idx from st
//}
//
//
//int main() {
//
// cin.tie(nullptr);
// ios::sync_with_stdio(false);
//
// int N;
// cin >> N;
//
// vector<vector<Edge<lint>>> edges(N);
// for (int i = 0; i < N - 1; i++) {
// int a, b;
// lint c;
// cin >> a >> b >> c;
// a--, b--;
// edges[a].emplace_back(b, c);
// edges[b].emplace_back(a, c);
// }
//
// int Q, K;
// cin >> Q >> K;
// auto distK = Dijkstra(edges, K - 1);
//
// for (int i = 0; i < Q; i++) {
// int x, y;
// cin >> x >> y;
// x--, y--;
// cout << distK[x] + distK[y] << "\n";
// }
//
// return 0;
//} | 22.471698 | 78 | 0.52225 | [
"vector"
] |
178fa513f6cd9e5cd1815d971a99f5b89af5ca39 | 6,513 | cpp | C++ | examples/TimeTBB.cpp | kvmanohar22/gtsam | 8194b931fe07fb1bd346cdcf116a35f9c4e208ba | [
"BSD-3-Clause"
] | 14 | 2019-12-11T18:33:57.000Z | 2022-01-04T04:52:45.000Z | examples/TimeTBB.cpp | kvmanohar22/gtsam | 8194b931fe07fb1bd346cdcf116a35f9c4e208ba | [
"BSD-3-Clause"
] | 6 | 2019-10-30T21:17:33.000Z | 2020-02-18T18:47:40.000Z | examples/TimeTBB.cpp | kvmanohar22/gtsam | 8194b931fe07fb1bd346cdcf116a35f9c4e208ba | [
"BSD-3-Clause"
] | 5 | 2020-01-09T16:24:50.000Z | 2021-09-24T11:10:49.000Z | /* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file TimeTBB.cpp
* @brief Measure task scheduling overhead in TBB
* @author Richard Roberts
* @date November 6, 2013
*/
#include <gtsam/global_includes.h>
#include <gtsam/base/Matrix.h>
#include <boost/assign/list_of.hpp>
#include <map>
#include <iostream>
using namespace std;
using namespace gtsam;
using boost::assign::list_of;
#ifdef GTSAM_USE_TBB
#include <tbb/tbb.h>
#undef max // TBB seems to include windows.h and we don't want these macros
#undef min
static const DenseIndex numberOfProblems = 1000000;
static const DenseIndex problemSize = 4;
typedef Eigen::Matrix<double, problemSize, problemSize> FixedMatrix;
/* ************************************************************************* */
struct ResultWithThreads
{
typedef map<int, double>::value_type value_type;
map<int, double> grainSizesWithoutAllocation;
map<int, double> grainSizesWithAllocation;
};
typedef map<int, ResultWithThreads> Results;
/* ************************************************************************* */
struct WorkerWithoutAllocation
{
vector<double>& results;
WorkerWithoutAllocation(vector<double>& results) : results(results) {}
void operator()(const tbb::blocked_range<size_t>& r) const
{
for(size_t i = r.begin(); i != r.end(); ++i)
{
FixedMatrix m1 = FixedMatrix::Random();
FixedMatrix m2 = FixedMatrix::Random();
FixedMatrix prod = m1 * m2;
results[i] = prod.norm();
}
}
};
/* ************************************************************************* */
map<int, double> testWithoutMemoryAllocation()
{
// A function to do some matrix operations without allocating any memory
// Now call it
vector<double> results(numberOfProblems);
const vector<size_t> grainSizes = list_of(1)(10)(100)(1000);
map<int, double> timingResults;
for(size_t grainSize: grainSizes)
{
tbb::tick_count t0 = tbb::tick_count::now();
tbb::parallel_for(tbb::blocked_range<size_t>(0, numberOfProblems), WorkerWithoutAllocation(results));
tbb::tick_count t1 = tbb::tick_count::now();
cout << "Without memory allocation, grain size = " << grainSize << ", time = " << (t1 - t0).seconds() << endl;
timingResults[(int)grainSize] = (t1 - t0).seconds();
}
return timingResults;
}
/* ************************************************************************* */
struct WorkerWithAllocation
{
vector<double>& results;
WorkerWithAllocation(vector<double>& results) : results(results) {}
void operator()(const tbb::blocked_range<size_t>& r) const
{
tbb::cache_aligned_allocator<double> allocator;
for(size_t i = r.begin(); i != r.end(); ++i)
{
double *m1data = allocator.allocate(problemSize * problemSize);
Eigen::Map<Matrix> m1(m1data, problemSize, problemSize);
double *m2data = allocator.allocate(problemSize * problemSize);
Eigen::Map<Matrix> m2(m2data, problemSize, problemSize);
double *proddata = allocator.allocate(problemSize * problemSize);
Eigen::Map<Matrix> prod(proddata, problemSize, problemSize);
m1 = Eigen::Matrix4d::Random(problemSize, problemSize);
m2 = Eigen::Matrix4d::Random(problemSize, problemSize);
prod = m1 * m2;
results[i] = prod.norm();
allocator.deallocate(m1data, problemSize * problemSize);
allocator.deallocate(m2data, problemSize * problemSize);
allocator.deallocate(proddata, problemSize * problemSize);
}
}
};
/* ************************************************************************* */
map<int, double> testWithMemoryAllocation()
{
// A function to do some matrix operations with allocating memory
// Now call it
vector<double> results(numberOfProblems);
const vector<size_t> grainSizes = list_of(1)(10)(100)(1000);
map<int, double> timingResults;
for(size_t grainSize: grainSizes)
{
tbb::tick_count t0 = tbb::tick_count::now();
tbb::parallel_for(tbb::blocked_range<size_t>(0, numberOfProblems), WorkerWithAllocation(results));
tbb::tick_count t1 = tbb::tick_count::now();
cout << "With memory allocation, grain size = " << grainSize << ", time = " << (t1 - t0).seconds() << endl;
timingResults[(int)grainSize] = (t1 - t0).seconds();
}
return timingResults;
}
/* ************************************************************************* */
int main(int argc, char* argv[])
{
cout << "numberOfProblems = " << numberOfProblems << endl;
cout << "problemSize = " << problemSize << endl;
const vector<int> numThreads = list_of(1)(4)(8);
Results results;
for(size_t n: numThreads)
{
cout << "With " << n << " threads:" << endl;
tbb::task_scheduler_init init((int)n);
results[(int)n].grainSizesWithoutAllocation = testWithoutMemoryAllocation();
results[(int)n].grainSizesWithAllocation = testWithMemoryAllocation();
cout << endl;
}
cout << "Summary of results:" << endl;
for(const Results::value_type& threads_result: results)
{
const int threads = threads_result.first;
const ResultWithThreads& result = threads_result.second;
if(threads != 1)
{
for(const ResultWithThreads::value_type& grainsize_time: result.grainSizesWithoutAllocation)
{
const int grainsize = grainsize_time.first;
const double speedup = results[1].grainSizesWithoutAllocation[grainsize] / grainsize_time.second;
cout << threads << " threads, without allocation, grain size = " << grainsize << ", speedup = " << speedup << endl;
}
for(const ResultWithThreads::value_type& grainsize_time: result.grainSizesWithAllocation)
{
const int grainsize = grainsize_time.first;
const double speedup = results[1].grainSizesWithAllocation[grainsize] / grainsize_time.second;
cout << threads << " threads, with allocation, grain size = " << grainsize << ", speedup = " << speedup << endl;
}
}
}
return 0;
}
#else
/* ************************************************************************* */
int main(int argc, char* argv [])
{
cout << "GTSAM is compiled without TBB, please compile with TBB to use this program." << endl;
return 0;
}
#endif
| 33.060914 | 123 | 0.613082 | [
"vector"
] |
1792d19e9b2112f5fcd10edd4b5babf91374e5fb | 1,469 | cpp | C++ | src/Customs/FirstBossLifeScript.cpp | fgagamedev/voID | 37cd56fe2878d036c36dafcf595e48ed85408d02 | [
"MIT"
] | null | null | null | src/Customs/FirstBossLifeScript.cpp | fgagamedev/voID | 37cd56fe2878d036c36dafcf595e48ed85408d02 | [
"MIT"
] | null | null | null | src/Customs/FirstBossLifeScript.cpp | fgagamedev/voID | 37cd56fe2878d036c36dafcf595e48ed85408d02 | [
"MIT"
] | null | null | null | /**
@file FirstBossLifeScript.cpp
@brief Manage the first boss life.
@copyright MIT License.
*/
#include "Customs/FirstBossLifeScript.hpp"
#include "Globals/EngineGlobals.hpp"
/**
@brief Constructor of the FirstBossLifeScript class.
*/
FirstBossLifeScript::FirstBossLifeScript(GameObject *owner) : Script(owner) {
}
/**
@brief Start the script that control the life of the first boss.
*/
void FirstBossLifeScript::Start() {
// Define the position of life bar.
position = GetOwner()->GetPosition();
GetOwner()->SetZoomProportion(Vector(0,0));
}
/**
@brief Control the lifebar of the first boss.
*/
void FirstBossLifeScript::ComponentUpdate() {
// Update the life bar of the boss with every attack he takes.
auto firstBossLifeRenderer = (RectangleRenderer*)GetOwner()->
GetComponent("RectangleRenderer");
int actualLife = firstBossLifeRenderer->GetWidth();
if (hit && actualLife > 0) {
cout << "hit" << endl;
cout << actualLife << endl;
firstBossLifeRenderer->SetWidth(actualLife - 10);
hit = false;
}
if (actualLife <= 0) {
FirstBossController::GetInstance()->ActivateCreditsAnimation();
FirstBossController::GetInstance()->DeactivateLifeBars();
}
}
/**
@brief Set the position of the first boss's lifebar.
*/
void FirstBossLifeScript::FixedComponentUpdate() {
position->m_x = 650;
position->m_y = 10;
}
| 26.709091 | 77 | 0.663036 | [
"vector"
] |
179327f762b00920520eb82b3eecb2645bf13ad7 | 721 | cpp | C++ | C++/961. N-RepeatedElementInSize2NArray.cpp | josh-dp/LeetCode-Solutions | ef790260b8e390f207461e3ee1d79fd59d8b2258 | [
"MIT"
] | 263 | 2020-10-05T18:47:29.000Z | 2022-03-31T19:44:46.000Z | C++/961. N-RepeatedElementInSize2NArray.cpp | josh-dp/LeetCode-Solutions | ef790260b8e390f207461e3ee1d79fd59d8b2258 | [
"MIT"
] | 1,264 | 2020-10-05T18:13:05.000Z | 2022-03-31T23:16:35.000Z | C++/961. N-RepeatedElementInSize2NArray.cpp | josh-dp/LeetCode-Solutions | ef790260b8e390f207461e3ee1d79fd59d8b2258 | [
"MIT"
] | 760 | 2020-10-05T18:22:51.000Z | 2022-03-29T06:06:20.000Z | /*
Problem 961 - N-Repeated Element in Size 2N Array
You are given an integer array nums with the following properties:
nums.length == 2 * n.
nums contains n + 1 unique elements.
Exactly one element of nums is repeated n times.
Return the element that is repeated n times.
*/
class Solution {
public:
int repeatedNTimes(vector<int>& nums) {
// Iterate over nums
for(int i=0; i<nums.size(); i++) {
for(int j=i+1; j<nums.size(); j++) {
// If we find a repeated num (only one number must appear more than once): it is the answer
if(nums[i] == nums[j]) {
return nums[i];
}
}
}
return 0;
}
}; | 28.84 | 107 | 0.565881 | [
"vector"
] |
179494c41308dd6fae69dafe0db7bc52f7efa447 | 646 | hpp | C++ | src/sprite.hpp | catsocks/sdl-grassland | 7d040a69a7daa97f025a8a572fa76c955a07859d | [
"CC0-1.0"
] | null | null | null | src/sprite.hpp | catsocks/sdl-grassland | 7d040a69a7daa97f025a8a572fa76c955a07859d | [
"CC0-1.0"
] | null | null | null | src/sprite.hpp | catsocks/sdl-grassland | 7d040a69a7daa97f025a8a572fa76c955a07859d | [
"CC0-1.0"
] | null | null | null | #pragma once
#include <SDL.h>
#include "tileset.hpp"
class Sprite {
const Tileset &tileset;
Rect2Di tile_rect;
int tile_variant{};
public:
// The defintion of Tile and the value of tile_variant_count is determined
// by the format of the character tilesets.
enum class Tile { front, left, right, back };
// For each tile in Tile there are 3 variants.
static const int tile_variant_count = 3;
Sprite(const Tileset &tileset);
void set_tile(Tile tile, int variant = 0);
void rotate_tile(Tile tile);
void render(SDL_Renderer *renderer, const Rect2Df &dest) const;
private:
Tile tile{};
};
| 21.533333 | 78 | 0.684211 | [
"render"
] |
1799f416b7a5590e2056bda09b2e3a05d4ca56ff | 18,789 | cc | C++ | ash/app_list/app_list_presenter_impl.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ash/app_list/app_list_presenter_impl.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ash/app_list/app_list_presenter_impl.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-03-07T14:20:02.000Z | 2021-03-07T14:20:02.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/app_list/app_list_presenter_impl.h"
#include <utility>
#include "ash/app_list/app_list_metrics.h"
#include "ash/app_list/app_list_view_delegate.h"
#include "ash/app_list/views/app_list_main_view.h"
#include "ash/app_list/views/apps_container_view.h"
#include "ash/app_list/views/contents_view.h"
#include "ash/app_list/views/search_box_view.h"
#include "ash/public/cpp/app_list/app_list_features.h"
#include "ash/public/cpp/app_list/app_list_switches.h"
#include "ash/public/cpp/app_list/app_list_types.h"
#include "ash/public/cpp/metrics_util.h"
#include "ash/public/cpp/pagination/pagination_model.h"
#include "ash/public/cpp/shell_window_ids.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/user_metrics.h"
#include "base/optional.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/window.h"
#include "ui/compositor/animation_throughput_reporter.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/display/screen.h"
#include "ui/display/types/display_constants.h"
#include "ui/gfx/presentation_feedback.h"
#include "ui/gfx/transform.h"
#include "ui/gfx/transform_util.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/core/transient_window_manager.h"
#include "ui/wm/public/activation_client.h"
namespace ash {
namespace {
constexpr std::array<int, 6> kIdsOfContainersThatWontHideAppList = {
kShellWindowId_AppListContainer, kShellWindowId_HomeScreenContainer,
kShellWindowId_MenuContainer, kShellWindowId_SettingBubbleContainer,
kShellWindowId_ShelfBubbleContainer, kShellWindowId_ShelfContainer,
};
inline ui::Layer* GetLayer(views::Widget* widget) {
return widget->GetNativeView()->layer();
}
// Callback from the compositor when it presented a valid frame. Used to
// record UMA of input latency.
void DidPresentCompositorFrame(base::TimeTicks event_time_stamp,
bool is_showing,
const gfx::PresentationFeedback& feedback) {
const base::TimeTicks present_time = feedback.timestamp;
if (present_time.is_null() || event_time_stamp.is_null() ||
present_time < event_time_stamp) {
return;
}
const base::TimeDelta input_latency = present_time - event_time_stamp;
if (is_showing) {
UMA_HISTOGRAM_TIMES(kAppListShowInputLatencyHistogram, input_latency);
} else {
UMA_HISTOGRAM_TIMES(kAppListHideInputLatencyHistogram, input_latency);
}
}
// Implicit animation observer that runs a scoped closure runner, and deletes
// itself when the observed implicit animations complete.
class CallbackRunnerLayerAnimationObserver
: public ui::ImplicitAnimationObserver {
public:
explicit CallbackRunnerLayerAnimationObserver(
base::ScopedClosureRunner closure_runner)
: closure_runner_(std::move(closure_runner)) {}
~CallbackRunnerLayerAnimationObserver() override = default;
// ui::ImplicitAnimationObserver:
void OnImplicitAnimationsCompleted() override {
closure_runner_.RunAndReset();
delete this;
}
private:
base::ScopedClosureRunner closure_runner_;
};
} // namespace
AppListPresenterImpl::AppListPresenterImpl(
std::unique_ptr<AppListPresenterDelegate> delegate)
: delegate_(std::move(delegate)) {
DCHECK(delegate_);
delegate_->SetPresenter(this);
}
AppListPresenterImpl::~AppListPresenterImpl() {
Dismiss(base::TimeTicks());
// Ensures app list view goes before the controller since pagination model
// lives in the controller and app list view would access it on destruction.
if (view_) {
view_->GetAppsPaginationModel()->RemoveObserver(this);
if (view_->GetWidget())
view_->GetWidget()->CloseNow();
}
CHECK(!IsInObserverList());
}
aura::Window* AppListPresenterImpl::GetWindow() const {
return is_target_visibility_show_ && view_
? view_->GetWidget()->GetNativeWindow()
: nullptr;
}
void AppListPresenterImpl::Show(AppListViewState preferred_state,
int64_t display_id,
base::TimeTicks event_time_stamp) {
if (is_target_visibility_show_) {
// Launcher is always visible on the internal display when home launcher is
// enabled in tablet mode.
if (delegate_->IsTabletMode() || display_id == GetDisplayId())
return;
Dismiss(event_time_stamp);
}
if (!delegate_->GetRootWindowForDisplayId(display_id)) {
LOG(ERROR) << "Root window does not exist for display: " << display_id;
return;
}
is_target_visibility_show_ = true;
OnVisibilityWillChange(GetTargetVisibility(), display_id);
RequestPresentationTime(display_id, event_time_stamp);
if (!view_) {
// Note |delegate_| outlives the AppListView.
AppListView* view = new AppListView(delegate_->GetAppListViewDelegate());
delegate_->Init(view, display_id);
SetView(view);
view_->GetWidget()->GetNativeWindow()->TrackOcclusionState();
}
delegate_->ShowForDisplay(preferred_state, display_id);
OnVisibilityChanged(GetTargetVisibility(), display_id);
}
void AppListPresenterImpl::Dismiss(base::TimeTicks event_time_stamp) {
if (!is_target_visibility_show_)
return;
// If the app list target visibility is shown, there should be an existing
// view.
DCHECK(view_);
is_target_visibility_show_ = false;
RequestPresentationTime(GetDisplayId(), event_time_stamp);
// Hide the active window if it is a transient descendant of |view_|'s widget.
aura::Window* window = view_->GetWidget()->GetNativeWindow();
aura::Window* active_window =
::wm::GetActivationClient(window->GetRootWindow())->GetActiveWindow();
if (active_window) {
aura::Window* transient_parent =
::wm::TransientWindowManager::GetOrCreate(active_window)
->transient_parent();
while (transient_parent) {
if (window == transient_parent) {
active_window->Hide();
break;
}
transient_parent =
::wm::TransientWindowManager::GetOrCreate(transient_parent)
->transient_parent();
}
}
// The dismissal may have occurred in response to the app list losing
// activation. Otherwise, our widget is currently active. When the animation
// completes we'll hide the widget, changing activation. If a menu is shown
// before the animation completes then the activation change triggers the menu
// to close. By deactivating now we ensure there is no activation change when
// the animation completes and any menus stay open.
if (view_->GetWidget()->IsActive())
view_->GetWidget()->Deactivate();
delegate_->OnClosing();
OnVisibilityWillChange(GetTargetVisibility(), GetDisplayId());
view_->SetState(AppListViewState::kClosed);
base::RecordAction(base::UserMetricsAction("Launcher_Dismiss"));
}
void AppListPresenterImpl::SetViewVisibility(bool visible) {
if (!view_)
return;
view_->SetVisible(visible);
view_->search_box_view()->SetVisible(visible);
}
bool AppListPresenterImpl::HandleCloseOpenFolder() {
return is_target_visibility_show_ && view_ && view_->HandleCloseOpenFolder();
}
ShelfAction AppListPresenterImpl::ToggleAppList(
int64_t display_id,
AppListShowSource show_source,
base::TimeTicks event_time_stamp) {
bool request_fullscreen = show_source == kSearchKeyFullscreen ||
show_source == kShelfButtonFullscreen;
// Dismiss or show based on the target visibility because the show/hide
// animation can be reversed.
if (is_target_visibility_show_ && GetDisplayId() == display_id) {
if (request_fullscreen) {
if (view_->app_list_state() == AppListViewState::kPeeking) {
view_->SetState(AppListViewState::kFullscreenAllApps);
return SHELF_ACTION_APP_LIST_SHOWN;
} else if (view_->app_list_state() == AppListViewState::kHalf) {
view_->SetState(AppListViewState::kFullscreenSearch);
return SHELF_ACTION_APP_LIST_SHOWN;
}
}
Dismiss(event_time_stamp);
return SHELF_ACTION_APP_LIST_DISMISSED;
}
Show(request_fullscreen ? AppListViewState::kFullscreenAllApps
: AppListViewState::kPeeking,
display_id, event_time_stamp);
return SHELF_ACTION_APP_LIST_SHOWN;
}
bool AppListPresenterImpl::IsVisibleDeprecated() const {
return delegate_->IsVisible(GetDisplayId());
}
bool AppListPresenterImpl::IsAtLeastPartiallyVisible() const {
const auto* window = GetWindow();
return window &&
window->occlusion_state() == aura::Window::OcclusionState::VISIBLE;
}
bool AppListPresenterImpl::GetTargetVisibility() const {
return is_target_visibility_show_;
}
void AppListPresenterImpl::UpdateYPositionAndOpacity(float y_position_in_screen,
float background_opacity) {
if (!is_target_visibility_show_)
return;
if (view_)
view_->UpdateYPositionAndOpacity(y_position_in_screen, background_opacity);
}
void AppListPresenterImpl::EndDragFromShelf(AppListViewState app_list_state) {
if (view_)
view_->EndDragFromShelf(app_list_state);
}
void AppListPresenterImpl::ProcessMouseWheelOffset(
const gfx::Point& location,
const gfx::Vector2d& scroll_offset_vector) {
if (view_)
view_->HandleScroll(location, scroll_offset_vector, ui::ET_MOUSEWHEEL);
}
void AppListPresenterImpl::UpdateScaleAndOpacityForHomeLauncher(
float scale,
float opacity,
base::Optional<TabletModeAnimationTransition> transition,
UpdateHomeLauncherAnimationSettingsCallback callback) {
if (!view_)
return;
ui::Layer* layer = view_->GetWidget()->GetNativeWindow()->layer();
if (!delegate_->IsTabletMode()) {
// In clamshell mode, set the opacity of the AppList immediately to
// instantly hide it. Opacity of the AppList is reset when it is shown
// again.
layer->SetOpacity(opacity);
return;
}
if (layer->GetAnimator()->is_animating()) {
layer->GetAnimator()->StopAnimating();
// Reset the animation metrics reporter when the animation is interrupted.
view_->ResetTransitionMetricsReporter();
}
base::Optional<ui::ScopedLayerAnimationSettings> settings;
if (!callback.is_null()) {
settings.emplace(layer->GetAnimator());
callback.Run(&settings.value());
// Disable suggestion chips blur during animations to improve performance.
base::ScopedClosureRunner blur_disabler =
view_->app_list_main_view()
->contents_view()
->apps_container_view()
->DisableSuggestionChipsBlur();
// The observer will delete itself when the animations are completed.
settings->AddObserver(
new CallbackRunnerLayerAnimationObserver(std::move(blur_disabler)));
}
// The animation metrics reporter will run for opacity and transform
// animations separately - to avoid reporting duplicated values, add the
// reported for transform animation only.
layer->SetOpacity(opacity);
base::Optional<ui::AnimationThroughputReporter> reporter;
if (settings.has_value() && transition.has_value()) {
view_->OnTabletModeAnimationTransitionNotified(*transition);
reporter.emplace(settings->GetAnimator(),
metrics_util::ForSmoothness(
view_->GetStateTransitionMetricsReportCallback()));
}
gfx::Transform transform =
gfx::GetScaleTransform(gfx::Rect(layer->size()).CenterPoint(), scale);
layer->SetTransform(transform);
}
void AppListPresenterImpl::ShowEmbeddedAssistantUI(bool show) {
if (view_)
view_->app_list_main_view()->contents_view()->ShowEmbeddedAssistantUI(show);
}
bool AppListPresenterImpl::IsShowingEmbeddedAssistantUI() const {
if (view_) {
return view_->app_list_main_view()
->contents_view()
->IsShowingEmbeddedAssistantUI();
}
return false;
}
void AppListPresenterImpl::SetExpandArrowViewVisibility(bool show) {
if (view_) {
view_->app_list_main_view()->contents_view()->SetExpandArrowViewVisibility(
show);
}
}
void AppListPresenterImpl::OnTabletModeChanged(bool started) {
if (started) {
if (GetTargetVisibility())
view_->OnTabletModeChanged(true);
} else {
if (IsVisibleDeprecated())
view_->OnTabletModeChanged(false);
}
}
////////////////////////////////////////////////////////////////////////////////
// AppListPresenterImpl, private:
void AppListPresenterImpl::SetView(AppListView* view) {
DCHECK(view_ == nullptr);
DCHECK(is_target_visibility_show_);
view_ = view;
views::Widget* widget = view_->GetWidget();
widget->AddObserver(this);
aura::client::GetFocusClient(widget->GetNativeView())->AddObserver(this);
view_->GetAppsPaginationModel()->AddObserver(this);
// Sync the |onscreen_keyboard_shown_| in case |view_| is not initiated when
// the on-screen is shown.
view_->set_onscreen_keyboard_shown(delegate_->GetOnScreenKeyboardShown());
}
void AppListPresenterImpl::ResetView() {
if (!view_)
return;
views::Widget* widget = view_->GetWidget();
widget->RemoveObserver(this);
GetLayer(widget)->GetAnimator()->RemoveObserver(this);
aura::client::GetFocusClient(widget->GetNativeView())->RemoveObserver(this);
view_->GetAppsPaginationModel()->RemoveObserver(this);
view_ = nullptr;
}
int64_t AppListPresenterImpl::GetDisplayId() const {
views::Widget* widget = view_ ? view_->GetWidget() : nullptr;
if (!widget)
return display::kInvalidDisplayId;
return display::Screen::GetScreen()
->GetDisplayNearestView(widget->GetNativeView())
.id();
}
void AppListPresenterImpl::OnVisibilityChanged(bool visible,
int64_t display_id) {
delegate_->OnVisibilityChanged(visible, display_id);
}
void AppListPresenterImpl::OnVisibilityWillChange(bool visible,
int64_t display_id) {
delegate_->OnVisibilityWillChange(visible, display_id);
}
////////////////////////////////////////////////////////////////////////////////
// AppListPresenterImpl, aura::client::FocusChangeObserver implementation:
void AppListPresenterImpl::OnWindowFocused(aura::Window* gained_focus,
aura::Window* lost_focus) {
if (!view_ || !is_target_visibility_show_)
return;
int gained_focus_container_id = kShellWindowId_Invalid;
if (gained_focus) {
gained_focus_container_id = gained_focus->id();
const aura::Window* container =
delegate_->GetContainerForWindow(gained_focus);
if (container)
gained_focus_container_id = container->id();
}
aura::Window* applist_window = view_->GetWidget()->GetNativeView();
const aura::Window* applist_container = applist_window->parent();
// An AppList dialog window, or a child window of the system tray, may
// take focus from the AppList window. Don't consider this a visibility
// change since the app list is still visible for the most part.
const bool gained_focus_hides_app_list =
gained_focus_container_id != kShellWindowId_Invalid &&
!base::Contains(kIdsOfContainersThatWontHideAppList,
gained_focus_container_id);
const bool app_list_gained_focus = applist_window->Contains(gained_focus);
const bool app_list_lost_focus =
gained_focus ? gained_focus_hides_app_list
: (lost_focus && applist_container->Contains(lost_focus));
// Either the app list has just gained focus, in which case it is already
// visible or will very soon be, or it has neither gained nor lost focus
// and it might still be partially visible just because the focused window
// doesn't occlude it completely.
const bool visible = app_list_gained_focus ||
(IsAtLeastPartiallyVisible() && !app_list_lost_focus);
if (delegate_->IsTabletMode()) {
if (visible != delegate_->IsVisible(GetDisplayId())) {
if (app_list_gained_focus)
view_->OnHomeLauncherGainingFocusWithoutAnimation();
OnVisibilityChanged(visible, GetDisplayId());
}
}
if (app_list_gained_focus)
base::RecordAction(base::UserMetricsAction("AppList_WindowFocused"));
if (app_list_lost_focus && !switches::ShouldNotDismissOnBlur() &&
!delegate_->IsTabletMode()) {
Dismiss(base::TimeTicks());
}
}
////////////////////////////////////////////////////////////////////////////////
// AppListPresenterImpl, ui::ImplicitAnimationObserver implementation:
void AppListPresenterImpl::OnImplicitAnimationsCompleted() {
StopObservingImplicitAnimations();
// This class observes the closing animation only.
OnVisibilityChanged(GetTargetVisibility(), GetDisplayId());
if (is_target_visibility_show_) {
view_->GetWidget()->Activate();
} else {
// Hide the widget so it can be re-shown without re-creating it.
view_->GetWidget()->Hide();
delegate_->OnClosed();
}
}
////////////////////////////////////////////////////////////////////////////////
// AppListPresenterImpl, views::WidgetObserver implementation:
void AppListPresenterImpl::OnWidgetDestroying(views::Widget* widget) {
DCHECK_EQ(view_->GetWidget(), widget);
if (is_target_visibility_show_)
Dismiss(base::TimeTicks());
ResetView();
}
void AppListPresenterImpl::OnWidgetDestroyed(views::Widget* widget) {
delegate_->OnClosed();
}
void AppListPresenterImpl::OnWidgetVisibilityChanged(views::Widget* widget,
bool visible) {
DCHECK_EQ(view_->GetWidget(), widget);
OnVisibilityChanged(visible, GetDisplayId());
}
////////////////////////////////////////////////////////////////////////////////
// AppListPresenterImpl, PaginationModelObserver implementation:
void AppListPresenterImpl::TotalPagesChanged(int previous_page_count,
int new_page_count) {}
void AppListPresenterImpl::SelectedPageChanged(int old_selected,
int new_selected) {
current_apps_page_ = new_selected;
}
void AppListPresenterImpl::RequestPresentationTime(
int64_t display_id,
base::TimeTicks event_time_stamp) {
if (event_time_stamp.is_null())
return;
aura::Window* root_window = delegate_->GetRootWindowForDisplayId(display_id);
if (!root_window)
return;
ui::Compositor* compositor = root_window->layer()->GetCompositor();
if (!compositor)
return;
compositor->RequestPresentationTimeForNextFrame(
base::BindOnce(&DidPresentCompositorFrame, event_time_stamp,
is_target_visibility_show_));
}
} // namespace ash
| 35.251407 | 80 | 0.706211 | [
"model",
"transform"
] |
17a309993a13b97b0a52367991c51e88d7f6c249 | 28,222 | hpp | C++ | include/Teisko/LateralChromaticAberration.hpp | intel/image-quality-and-characterization-utilities | ef58f9aea906e6453b8cec4a891104d16dd44f93 | [
"BSD-3-Clause"
] | 8 | 2019-04-10T14:21:16.000Z | 2020-11-13T06:26:22.000Z | include/Teisko/LateralChromaticAberration.hpp | intel/image-quality-and-characterization-utilities | ef58f9aea906e6453b8cec4a891104d16dd44f93 | [
"BSD-3-Clause"
] | null | null | null | include/Teisko/LateralChromaticAberration.hpp | intel/image-quality-and-characterization-utilities | ef58f9aea906e6453b8cec4a891104d16dd44f93 | [
"BSD-3-Clause"
] | 6 | 2019-04-30T11:39:08.000Z | 2021-02-17T11:38:29.000Z | /*
* Copyright (c) 2019, Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Intel Corporation nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#define NOMINMAX
#include "Teisko/Algorithm/DelaunayTriangulation.hpp"
#include "Teisko/Algorithm/LinearSpace.hpp"
#include "Teisko/Image/API.hpp" // bayer_image_s
#include "Teisko/LensShading.hpp" // use lensshading_grid as container
#include <cstdint>
#include <vector>
namespace Teisko
{
// Domain specific algorithms for Lateral Chromatic Aberration Characterization
using lca_grid = lensshading_grid<double>;
/// Structure to hold + calculate center of green feature and
/// relative displacements of red/blue feature centroids
struct lca_feature_s
{
point_xy green; // centroid of green feature
point_xy diff_blue; // calculated blue difference at point
point_xy diff_red; // calculated red difference at point
double area = 0; // area of feature
lca_feature_s() = default;
lca_feature_s(double a, point_xy r, point_xy g, point_xy b)
: green(g), diff_blue(b - g), diff_red(r - g), area(a) { }
// returns reference to the payload by index
// - helps current implementation of filtering outliers
// - int x should be in range 0..3
double& operator[](int x)
{
double *ptrs[4] = { &diff_blue.x, &diff_blue.y, &diff_red.x, &diff_red.y };
return *(ptrs[x & 3]);
}
// Pairwise scaling of feature
// Used in barycentric interpolation: a * feature_a + b * feature_b + c * feature_c
lca_feature_s operator *(const double x) {
auto copy = *this;
copy.area *= x;
copy.green *= x;
copy.diff_blue *= x;
copy.diff_red *= x;
return copy;
}
// Pairwise sum of features
lca_feature_s operator +(const lca_feature_s &other) {
auto copy = *this;
copy.area += other.area;
copy.green += other.green;
copy.diff_blue += other.diff_blue;
copy.diff_red += other.diff_red;
return copy;
}
};
/// How to use:
/// Step 1) lca_characterization implementation;
/// Step 2) for (auto &i : my_images) implementation += i;
/// - throws if image sizes mismatch
/// Step 3) auto output = implementation.collect();
class lca_characterization
{
public:
roi_point center() { return _center; }
roi_point cell_size() { return _cell_size; }
lca_characterization() : _init_done(false) {}
/// Add image to model -- returns the newly added features
std::vector<lca_feature_s> operator += (bayer_image_s<uint16_t> &image)
{
if (image._layout.is_dp_4x2_sensor())
{
preprocessor_s preprocessor;
preprocessor.saturation = 65535;
preprocessor.preprocess_reduce_dp_sensor(image);
}
validate_image_size(image._img.size());
return add_image(image);
}
/// Collect results
/// - should we try to remove outliers by proximity before averaging?
/// `remove_outliers_by_median(9)`
lca_grid collect()
{
// remove_outliers_by_median(9);
auto output = average_results();
remove_outliers_by_median_on_regular_grid(output);
return output;
}
private:
bool _init_done = false; // Guard for allowing image size initialize only once
roi_point _center; // Optical center -- half of image dimensions
roi_point _cell_size; // Power of Two cell size producing max 64x64 grid
roi_point _dims; // Dimensions of the images (after 4x2->2x2 collapsing)
// Called to assign image size related parameters on first run
// and then to check that succeeding images are of the same size
void validate_image_size(roi_point size)
{
if (_init_done)
{
if (_dims == size)
return;
throw std::runtime_error("Image size mismatch");
}
const int max_grid_dims = 64;
auto max_items = (size - 1) / (max_grid_dims - 1);
_init_done = true;
_dims = size;
_center = _dims / 2;
_cell_size = {
static_cast<int>(next_power_of_two(max_items._x)),
static_cast<int>(next_power_of_two(max_items._y))
};
}
std::vector<std::vector<lca_feature_s>> _features;
// Check if a feature is valid in LCA context
// - by area
// - by perimeter to area ratio (i.e. being simple enough)
// - the maximum area/perimeter^2 ratio is for circle -- so we don't want to limit those
// in the other end there are very thin ellipses or line segments or very complex shapes
bool is_valid(region_props &feature, double max_area)
{
const double minimum_area = max_area * (0.5e-4);
const double maximum_area = max_area * (8e-3);
const double magic = 4.0 * 3.141592653589793; // 4*pi -- that's area/perimeter^2 limit for circle
if (feature.area < minimum_area || feature.area > maximum_area)
return false;
auto ratio = magic * feature.area / (feature.perimeter * feature.perimeter);
return ratio > 0.5; // empirical constant 0.5 for regular enough shape
}
// Quantifies image by threshold after edge detection
// - horizontal + vertical filtering with 9 tap kernel
void gradient_threshold(image<uint16_t> &img, double threshold = 0.4)
{
// from matlab where W = normalized magnitude between 0..1 from hypot(img conv h, img conv h')
// W = W.^(1./rolloffFactor); %% rolloffFactor = 3
// W = (1 - W). / (1 + W);
// W(W < weightCutoff) = floorOfW;
// result = W < threshold
// we don't calculate sqrt of horizontal and vertical gradients, so we have to scale by
// exponent of six...
double y = std::pow(std::abs(threshold - 1) / (threshold + 1), 6);
auto temp_dst = image<int>(img.size());
auto temp_src = img.make_borders(4, 4, 4, 4, REPLICATE);
auto center = temp_src.region(temp_dst.size(), roi_point(4));
int stride = temp_src._skip_y;
int max_level = 0;
temp_dst.foreach([stride, &max_level](int &dst, uint16_t &src)
{
uint16_t *s = &src;
int v =
(s[stride * 4] - s[-stride * 4]) * 1228 +
(s[stride * 3] - s[-stride * 3]) * 2210 +
(s[stride * 2] - s[-stride * 2]) * 2752 +
(s[stride * 1] - s[-stride * 1]) * 2002; // sum = 8192
int h =
(s[4] - s[-4]) * 1228 +
(s[3] - s[-3]) * 2210 +
(s[2] - s[-2]) * 2752 +
(s[1] - s[-1]) * 2002;
v /= 16384; // max sum of 'v' is +-65535 * 8192
h /= 16384; // -- we have to divide by 2 in order of not to overflow 'dst'
dst = v*v + h*h;
if (dst > max_level)
max_level = dst;
}, center);
max_level = std::lround(y * max_level);
img.foreach([max_level](uint16_t &dst, int &src) { dst = src >= max_level; }, temp_dst);
}
std::vector<region_props> get_valid_features(image<uint16_t> &channel)
{
std::vector<double> gaussian_7x7 = { 0.0702, 0.1311, 0.1907, 0.2161, 0.1907, 0.1311, 0.0702 };
auto resampled = channel.convert_to(); // take a copy
filter_separable(resampled, gaussian_7x7, REPLICATE);
gradient_threshold(resampled, 0.4);
auto count = bwlabel(resampled);
int labels = 0;
std::vector<region_props> features;
features.reserve(count);
auto dimensions = resampled.size();
double max_area = dimensions._x * dimensions._y;
for (int y = 0; y < dimensions._y; y++)
{
for (int x = 0; x < dimensions._x; x++)
{
if (resampled(y, x) == labels + 1)
{
++labels;
auto feature = get_regionprops(resampled, roi_point(x, y));
if (is_valid(feature, max_area))
features.push_back(feature);
}
}
}
std::sort(features.begin(), features.end(), [](const region_props &a, const region_props &b)
{
return a.centroid_x < b.centroid_x;
});
return features;
}
// Given coarsely found set of green features locate the corresponding features
// from each color plane using Otsu thresholding
// - discard all newly found features touching the bounding box
// or with blue to green / red to green magnitude larger than 7 pixels
std::vector<lca_feature_s> find_matching_features(
bayer_image_s<uint16_t> &bayer,
image<uint16_t> &green,
std::vector<region_props> &green_features)
{
auto clamp_point = [](roi_point p, roi_point size)
{
return roi_point(std::max(std::min(size._x - 1, p._x), 0),
std::max(std::min(size._y - 1, p._y), 0));
};
auto max_abs_distance = [](point_xy a, point_xy b)
{
auto diff = a - b;
return std::max(std::abs(diff.x), std::abs(diff.y));
};
auto red = demosaic_bilinear(bayer, color_info_e::red);
auto blue = demosaic_bilinear(bayer, color_info_e::blue);
auto size = green.size();
auto margin = roi_point(15);
quantizer q_red, q_blue, q_green;
double max_area = size._x * size._y;
auto current_set_of_features = std::vector<lca_feature_s>();
for (auto &g : green_features)
{
auto top_left = clamp_point(g.top_left - margin, size);
auto roi_size = clamp_point(g.bot_right + margin, size) - top_left + 1;
auto centroid_coarse = roi_point(g.centroid_x, g.centroid_y) - top_left;
// Quantize each matching region (with reusing the histogram / context)
auto bitonal_g = q_green(green.region(roi_size, top_left));
auto bitonal_b = q_blue(blue.region(roi_size, top_left));
auto bitonal_r = q_red(red.region(roi_size, top_left));
// Require that the center of the original feature has been quantized to zero (a hole)
if (bitonal_g(centroid_coarse) != 0 ||
bitonal_b(centroid_coarse) != 0 ||
bitonal_r(centroid_coarse) != 0)
continue;
auto props_green = get_regionprops(bitonal_g, centroid_coarse);
auto props_blue = get_regionprops(bitonal_b, centroid_coarse);
auto props_red = get_regionprops(bitonal_r, centroid_coarse);
// re-check that the region properties are within expected in all color channels
if (!is_valid(props_green, max_area) ||
!is_valid(props_blue, max_area) ||
!is_valid(props_red, max_area))
continue;
// Check that the areas are within +-25% of the median area
// and that the centroids are located withing the maximum distance
double area[3] = { props_green.area, props_red.area, props_blue.area };
std::sort(area, area + 3);
auto centroid_g = point_xy(props_green.centroid_x + top_left._x, props_green.centroid_y + top_left._y);
auto centroid_r = point_xy(props_red.centroid_x + top_left._x, props_red.centroid_y + top_left._y);
auto centroid_b = point_xy(props_blue.centroid_x + top_left._x, props_blue.centroid_y + top_left._y);
const double max_distance = 7.0;
const double max_area_ratio = 1.25; // allows one area to be 25% larger than the other
if (area[0] * max_area_ratio < area[1] || area[1] * max_area_ratio < area[2] ||
max_abs_distance(centroid_g, centroid_r) > max_distance ||
max_abs_distance(centroid_g, centroid_b) > max_distance)
continue;
// else add the item to found items
current_set_of_features.emplace_back(area[1], centroid_r, centroid_g, centroid_b);
}
return current_set_of_features;
}
// Locates the green features and their difference to red and blue features
std::vector<lca_feature_s> add_image(bayer_image_s<uint16_t> &img)
{
auto resampled_green = demosaic_bilinear(img, color_info_e::green);
auto green_features = get_valid_features(resampled_green);
auto new_features = find_matching_features(img, resampled_green, green_features);
_features.push_back(new_features);
return new_features;
}
uint32_t next_power_of_two(uint32_t a)
{
if (a == 0)
return 1;
// Two examples: a1 = 10000000 a2 = 100000011 (a1 is already power of two, a2 isn't)
--a; // 01111111 100000010 after subtraction
a |= a >> 1; // 01111111 110000011 after a |= a >> 1
a |= a >> 2; // 01111111 111100011 after next stage
a |= a >> 4; // 01111111 111111111 after oring in groups of four
a |= a >> 8; // each iteration closes 1,2,4,8,..16 intermediate zeros/holes in the variable
a |= a >> 16; // at this point all zeros have vanished, a is of form 0000...111111
return ++a; // 10000000 1000000000 Only one bit set!
}
struct heap_element_s
{
double distance;
lca_feature_s *p;
bool operator <(heap_element_s &other) { return distance < other.distance; }
heap_element_s() : distance(0.0), p(nullptr) { }
heap_element_s(lca_feature_s *ptr, point_xy point)
: distance(norm2(ptr->green - point))
, p(ptr) { }
};
// With starting point of left_idx == right_idx (within vec)
// adds the N closest neighbors of the middle elements to a heap
// - adjusts the "left_idx" and "right_idx"
void init_heap(std::vector<heap_element_s> &heap, std::vector<lca_feature_s*> &vec,
size_t &left_idx, size_t &right_idx, point_xy point)
{
auto n = heap.size();
auto len = vec.size();
for (size_t k = 0; k < n;)
{
if (left_idx - 1 < len)
{
heap[k++] = heap_element_s(vec[--left_idx], point);
if (k == n)
break;
}
if (right_idx + 1 < len)
heap[k++] = heap_element_s(vec[++right_idx], point);
}
std::make_heap(heap.begin(), heap.end());
}
// `idx` is the last item added to heap (or points outside the vector)
void trial_add(std::vector<heap_element_s> &heap, std::vector<lca_feature_s*> &vec, size_t &idx, point_xy p)
{
auto len = vec.size();
// we scan from "middle" index to left or right
// until we face an element whose X distance is greater than Kth smallest distance
// - after this point there are no more better candidates on that direction
if (idx >= len || (vec[idx]->green.x - p.x) * (vec[idx]->green.x - p.x) > heap.front().distance)
{
idx = len;
return;
}
heap_element_s trial(vec[idx], p);
if (trial.distance < heap.front().distance)
{
std::pop_heap(heap.begin(), heap.end()); // moves the largest to the end
heap.back() = trial; // replaces the largest element
std::push_heap(heap.begin(), heap.end()); // rearranges the heap
}
}
// Removes outliers from the full set of data
// Steps 1) sort all items by x-coordinate
// 2) for each value, locate the N nearest neighbours
// - because the set is sorted, we can stop moving left/right
// after there can not come any improvement
// 3) calculate the median of absolute difference to median of set
// - reject the sample, if its more than 3 sigma away from the median
// 4) After all samples are processed, fill the data
// Also considered: put all samples in 2D grid (multimap, hash table)
// - then scan in a spiral path until no advances can be made
void remove_outliers_by_median(size_t n)
{
// Sort all features in all images by x-coordinate
std::vector<lca_feature_s*> vec;
for (auto &image : _features)
for (auto &f : image)
vec.emplace_back(&f);
std::sort(vec.begin(), vec.end(), [](lca_feature_s *a, lca_feature_s *b)
{
return a->green.x < b->green.x;
});
auto len = vec.size();
if (len < n)
return;
struct replacements
{
lca_feature_s* what;
int parameter;
double value;
replacements(lca_feature_s* p, int channel, double val) : what(p), parameter(channel), value(val) { }
};
std::vector<replacements> outliers;
// Create a heap to store pointers and distances of N closest items to each point in the set
std::vector<heap_element_s> heap(n - 1);
std::vector<double> parameter(n);
std::vector<double> distance(n);
for (size_t i = 0; i < len; i++)
{
auto left_idx = i;
auto right_idx = i;
init_heap(heap, vec, left_idx, right_idx, vec[i]->green);
// Add items from left and right
while (left_idx < len || right_idx < len)
{
trial_add(heap, vec, --left_idx, vec[i]->green);
trial_add(heap, vec, ++right_idx, vec[i]->green);
}
double three_sigma = 4.447806655516805;
for (int p = 0; p < 4; p++)
{
parameter[0] = (*vec[i])[p];
for (size_t k = 1; k < n; k++)
parameter[k] = (*heap[k-1].p)[p];
std::sort(parameter.begin(), parameter.end());
for (size_t k = 0; k < n; k++)
distance[k] = std::abs(parameter[k] - parameter[3]);
std::sort(distance.begin(), distance.end());
if (std::abs((*vec[i])[p] - parameter[n / 2]) > three_sigma * distance[n / 2])
outliers.emplace_back(vec[i], p, parameter[n/2]);
}
}
// and then we replace
for (auto &rep : outliers)
(*rep.what)[rep.parameter] = rep.value;
}
// Takes 3x3 neighbors replacing each bx, by, rx, ry
// by the local median if the point is judged an outlier
// - when 'x' needs to be replaced, we replace also the corresponding 'y'
// and vice versa
void remove_outliers_by_median_on_regular_grid(lca_grid &grid)
{
for (int ch = 0; ch < grid.channels; ch += 2)
{
auto copy_x = grid[ch].make_borders(1, 1, 1, 1, REPLICATE);
auto copy_y = grid[ch+1].make_borders(1, 1, 1, 1, REPLICATE);
int stride = copy_x._skip_y;
int offset = grid.width * grid.height;
grid[ch].foreach([offset, stride](double &dst, double &src_x, double &src_y)
{
double three_sigma = 4.447806655516805;
double *dx = &dst;
double *dy = &dst + offset;
double *sx = &src_x;
double *sy = &src_y;
point_xy values[9];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
values[i * 3 + j].x = sx[i * stride + j];
values[i * 3 + j].y = sy[i * stride + j];
}
}
// Sort values by x
std::sort(values, values + 9, [](point_xy a, point_xy b) { return a.x < b.x; });
double median_x = values[4].x;
double diffs[9];
for (int i = 0; i < 9; i++)
diffs[i] = std::abs(values[i].x - median_x);
std::sort(diffs, diffs + 9);
double median_abs_diff_x = diffs[4];
if (std::abs(*dx - median_x) > three_sigma * median_abs_diff_x)
{
for (int i = 0; i < 9; i++)
if (i != 4 && values[i].x == *dx)
{
values[i].x = median_x;
break;
}
*dx = median_x;
*dy = values[4].y;
}
// Sort values by y
std::sort(values, values + 9, [](point_xy a, point_xy b) { return a.y < b.y; });
double median_y = values[4].y;
for (int i = 0; i < 9; i++)
diffs[i] = std::abs(values[i].y - median_y);
std::sort(diffs, diffs + 9);
double median_abs_diff_y = diffs[4];
if (std::abs(*dy - median_y) > three_sigma * median_abs_diff_y)
{
for (int i = 0; i < 9; i++)
if (i != 4 && values[i].y == *dy)
{
values[i].y = median_y;
break;
}
*dy = median_y;
*dx = values[4].x;
}
}, copy_x, copy_y);
}
}
// Interpolates each separate characterization (one per image) on a regular grid
// Combines the interpolations for final grid
lca_grid average_results()
{
if (_dims._x == 0 || _dims._y == 0 || _features.size() == 0 || _cell_size._x == 0 || _cell_size._y == 0)
return{};
// Calculates the grid size so that it has a pow of two spacing and max 64 items per dimension
auto grid_dims = 1 + (_dims + _cell_size - 2) / _cell_size;
auto elements = grid_dims._x * grid_dims._y;
auto grid = std::vector<lca_feature_s>(elements);
auto best_distance = std::vector<double>(elements, std::numeric_limits<double>::infinity());
auto best_area = std::vector<double>(elements, 0.0);
// resample separate files/images with scattered_interpolator
// - accumulate the interpolated sample points to grid
for (auto &i : _features)
{
if (i.size() == 0)
continue;
std::vector<point_xy> points;
points.reserve(i.size());
for (auto &p : i)
points.emplace_back(p.green);
auto x_vec = linear_space(0.0, (double)_cell_size._x * (grid_dims._x - 1), grid_dims._x);
auto y_vec = linear_space(0.0, (double)_cell_size._y * (grid_dims._y - 1), grid_dims._y);
// Interpolate the data
auto weights = scattered_interpolation(points, x_vec, y_vec);
auto interpolated_grid = barycentric_interpolation(i, weights);
for (int j = 0; j < elements; j++)
{
auto &w = weights[j];
auto &lca_data = interpolated_grid[j];
// Select the largest feature by area to represent the inside convex hull sample
// - alternative: accumulate total area, then normalize
if (w.v.a != w.v.b)
{
if (lca_data.area > best_area[j])
{
best_area[j] = lca_data.area;
grid[j] = lca_data;
}
}
// else select the closest point to represent outside the convex hull sample
else if (best_area[j] == 0)
{
int y = j / grid_dims._x;
int x = j % grid_dims._x;
auto distance = norm2(points[w.v.a] - point_xy(x_vec[x], y_vec[y]));
if (distance < best_distance[j])
{
best_distance[j] = distance;
grid[j] = lca_data;
}
}
}
}
// convert the array of struct to struct of arrays
auto result = lca_grid(grid_dims._x, grid_dims._y, 4);
for (int ch = 0; ch < 4; ch++)
{
auto *p = &result.grid[ch * elements];
for (int j = 0; j < elements; j++)
p[j] = grid[j][ch];
}
return result;
}
};
} | 44.165884 | 119 | 0.51598 | [
"shape",
"vector",
"model"
] |
17b3e1c2e430435644d1f0f32772e6ffd0c20327 | 3,247 | cpp | C++ | graph/MFMC(Dijkstra).cpp | jasonfan0328/algorithm | 3769a03c5c530381e3ee08c416c3593c96ee966c | [
"CC0-1.0"
] | 3 | 2021-05-03T01:14:04.000Z | 2021-05-05T05:47:56.000Z | graph/MFMC(Dijkstra).cpp | jason-fxz/algorithm | 3769a03c5c530381e3ee08c416c3593c96ee966c | [
"CC0-1.0"
] | null | null | null | graph/MFMC(Dijkstra).cpp | jason-fxz/algorithm | 3769a03c5c530381e3ee08c416c3593c96ee966c | [
"CC0-1.0"
] | null | null | null | #include <bits/stdc++.h>
#define fi first
#define se second
template<typename _Tp>
inline void red(_Tp &x) {
x = 0; bool fg = 0; char ch = getchar();
while (ch < '0' || ch > '9') {if (ch == '-') fg ^= 1; ch = getchar();}
while (ch >= '0' && ch <= '9') x = (x << 1) + (x << 3) + (_Tp)(ch ^ 48), ch = getchar();
if (fg) x = -x;
}
template<typename _Tp> bool umax(_Tp &x, _Tp y) {return (x < y) ? (x = y, true) : (false);}
template<typename _Tp> bool umin(_Tp &x, _Tp y) {return (x > y) ? (x = y, true) : (false);}
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int inf = 0x3f3f3f3f;
int n, m, s, t;
struct networkflow {
static const int N = 5010, M = 100010;
int head[N], pnt[M], fl[M], nxt[M], cst[M], pre[N], lst[N], E = -1;
int dis[N], h[N]; bool vis[N];
int minc, maxf, n;
void init(int _n) {
memset(head, -1, sizeof(head)); E = -1; n = _n;
}
void adde(int u, int v, int f, int c) {
++E; pnt[E] = v; nxt[E] = head[u]; head[u] = E; fl[E] = f; cst[E] = c;
++E; pnt[E] = u; nxt[E] = head[v]; head[v] = E; fl[E] = 0; cst[E] = -c;
}
bool SPFA(int S, int T) {
memset(dis, 0x3f, sizeof(dis));
memset(vis, 0, sizeof(vis));
dis[S] = 0; vis[S] = 1; queue<int> q; q.push(S);
while (!q.empty()) {
int u = q.front(); q.pop();
vis[u] = 0;
for (int i = head[u]; i != -1; i = nxt[i]) {
int v = pnt[i];
if (fl[i] > 0 && dis[u] + cst[i] < dis[v]) {
dis[v] = dis[u] + cst[i]; pre[v] = u; lst[v] = i;
if (!vis[v]) q.push(v), vis[v] = 1;
}
}
}
return dis[T] < inf;
}
void work(int S, int T) {
for (int i = 0; i <= n; ++i) h[i] += dis[i];
int flow = inf;
for (int u = T; u != S; u = pre[u]) flow = min(flow, fl[lst[u]]);
maxf += flow; minc += flow * h[T];
for (int u = T; u != S; u = pre[u]) {
fl[lst[u]] -= flow;
fl[lst[u] ^ 1] += flow;
}
}
bool Dij(int S, int T) {
priority_queue<P, vector<P>, greater<P> > q;
memset(dis, 0x3f, sizeof(dis));
memset(vis, 0, sizeof(vis));
dis[S] = 0; q.push({0, S});
while (!q.empty()) {
int u = q.top().se; q.pop();
if (vis[u]) continue; vis[u] = 1;
for (int i = head[u]; i != -1; i = nxt[i]) {
int v = pnt[i];
if (fl[i] > 0 && dis[v] > dis[u] + cst[i] + h[u] - h[v]) {
dis[v] = dis[u] + cst[i] + h[u] - h[v];
pre[v] = u; lst[v] = i;
q.push({dis[v], v});
}
}
}
return dis[T] < inf;
}
void MFMC(int S, int T) {
minc = maxf = 0;
memset(h, 0, sizeof(h));
if (SPFA(S, T)) work(S, T);
else return ;
while (Dij(S, T)) work(S, T);
}
} G;
int main() {
red(n); red(m); red(s); red(t);
G.init(n);
for (int i = 1; i <= m; ++i) {
int a, b, c, d; red(a); red(b); red(c); red(d);
G.adde(a, b, c, d);
}
G.MFMC(s, t);
printf("%d %d\n", G.maxf, G.minc);
return 0;
} | 34.542553 | 92 | 0.414844 | [
"vector"
] |
17b5b7a7e2bf2bacbf7411af12aaa83e366b029e | 1,835 | cpp | C++ | Core/src/Snake.cpp | WSeegers/-toy-nibbler | 3458001b76eb616feedc9f234910324dc265e1a4 | [
"MIT"
] | null | null | null | Core/src/Snake.cpp | WSeegers/-toy-nibbler | 3458001b76eb616feedc9f234910324dc265e1a4 | [
"MIT"
] | 1 | 2019-08-06T09:56:57.000Z | 2019-08-06T09:56:57.000Z | Core/src/Snake.cpp | WSeegers/-toy-nibbler | 3458001b76eb616feedc9f234910324dc265e1a4 | [
"MIT"
] | null | null | null | #include "Snake.hpp"
#include <algorithm>
const Vec2i Snake::_up(0, -1);
const Vec2i Snake::_left(-1, 0);
const Vec2i Snake::_down(0, 1);
const Vec2i Snake::_right(1, 0);
Snake::Snake()
: _body({Vec2i(0, 0), Vec2i(0, 0), Vec2i(0, 0), Vec2i(0, 0)}),
_nextDirection(Snake::_right),
_direction(Snake::_right) {}
const Body
&
Snake::body() const
{
return this->_body;
}
void Snake::update()
{
static int frames = 0;
if (frames++ % this->_moveDelay)
return;
Vec2i head = this->_body.back();
this->_direction = this->_nextDirection;
if (this->_grow)
{
this->_body.push_back(head + this->_direction);
this->_grow = false;
}
else
{
std::rotate(
this->_body.begin(),
this->_body.begin() + 1,
this->_body.end());
this->_body.back() = head + this->_direction;
}
if (isColliding() && this->onCollide)
this->onCollide();
}
bool Snake::isColliding()
{
Vec2i &head = this->_body.back();
Vec2i *found = std::find(this->_body.begin(), this->_body.end(), head)
.base();
return !(found == &head);
}
void Snake::grow() { this->_grow = true; }
void Snake::up()
{
if (this->_direction.x)
this->_nextDirection = Snake::_up;
}
void Snake::left()
{
if (this->_direction.y)
this->_nextDirection = Snake::_left;
}
void Snake::down()
{
if (this->_direction.x)
this->_nextDirection = Snake::_down;
}
void Snake::right()
{
if (this->_direction.y)
this->_nextDirection = Snake::_right;
}
void Snake::render(IRenderer &renderer) const
{
for (const auto cell : this->_body)
{
renderer.setCellColour(cell.x, cell.y, this->_bodyCol);
}
Vec2i head = this->_body.back();
renderer.setCellColour(head.x, head.y, this->_headCol);
}
Vec2i Snake::head() { return this->_body.back(); }
void Snake::setPosition(Vec2i position)
{
for (Vec2i &p : this->_body)
p = position;
};
| 17.815534 | 71 | 0.637602 | [
"render"
] |
17b694fce046bd2f8df9d3c3dab1a81dc51302f0 | 9,009 | hpp | C++ | src/core/bvh/BinaryBvh.hpp | chaosink/tungsten | 88ea02044dbaf20472a8173b6752460b50c096d8 | [
"Apache-2.0",
"Unlicense"
] | 1,655 | 2015-01-12T13:05:37.000Z | 2022-03-31T13:37:57.000Z | src/core/bvh/BinaryBvh.hpp | chaosink/tungsten | 88ea02044dbaf20472a8173b6752460b50c096d8 | [
"Apache-2.0",
"Unlicense"
] | 65 | 2015-01-13T08:34:28.000Z | 2021-06-08T05:07:58.000Z | src/core/bvh/BinaryBvh.hpp | chaosink/tungsten | 88ea02044dbaf20472a8173b6752460b50c096d8 | [
"Apache-2.0",
"Unlicense"
] | 190 | 2015-01-12T14:53:05.000Z | 2022-03-30T17:30:00.000Z | #ifndef BINARYBVH_HPP_
#define BINARYBVH_HPP_
#include "BvhBuilder.hpp"
#include "math/Box.hpp"
#include "math/Vec.hpp"
#include "sse/SimdUtils.hpp"
#include "IntTypes.hpp"
namespace Tungsten {
#include "AlignedAllocator.hpp"
typedef Vec<float4, 3> Vec3pf;
namespace Bvh {
class BinaryBvh
{
template<typename T> using aligned_vector = std::vector<T, AlignedAllocator<T, 64>>;
Vec3pf transpose(const Vec3f &p) const
{
return Vec3pf(float4(p.x()), float4(p.y()), float4(p.z()));
}
class TinyBvhNode
{
union PointerOrIndex {
TinyBvhNode *node;
uint64 index;
};
Vec3pf _box;
PointerOrIndex _lChild;
PointerOrIndex _rChild;
public:
const Vec3pf &bbox() const
{
return _box;
}
void setJointBbox(const Box3f &lbox, const Box3f &rbox)
{
_box = Vec3pf(
float4(lbox.min().x(), rbox.min().x(), lbox.max().x(), rbox.max().x()),
float4(lbox.min().y(), rbox.min().y(), lbox.max().y(), rbox.max().y()),
float4(lbox.min().z(), rbox.min().z(), lbox.max().z(), rbox.max().z())
);
}
uint32 primIndex() const
{
return _lChild.index & 0xFFFFFFFFU;
}
uint32 childCount() const
{
return _lChild.index >> 32;
}
void setPrimIndex(uint32 count, uint32 idx)
{
_lChild.index = (uint64(count) << 32) | uint64(idx);
}
TinyBvhNode *lChild()
{
return _lChild.node;
}
const TinyBvhNode *lChild() const
{
return _lChild.node;
}
void setLchild(TinyBvhNode *child)
{
_lChild.node = child;
}
TinyBvhNode *rChild()
{
return _rChild.node;
}
const TinyBvhNode *rChild() const
{
return _rChild.node;
}
void setRchild(TinyBvhNode *child)
{
_rChild.node = child;
}
bool isLeaf() const
{
return _rChild.node == nullptr;
}
bool isNode() const
{
return _rChild.node != nullptr;
}
};
int _depth;
aligned_vector<TinyBvhNode> _nodes;
std::vector<uint32> _primIndices;
Box3f _bounds;
uint32 recursiveBuild(const NaiveBvhNode *node, uint32 head, uint32 &tail, uint32 &primIndex,
std::vector<uint32> &primIndices, uint32 maxPrimsPerLeaf)
{
if (node->isLeaf()) {
_nodes[head].setJointBbox(node->bbox(), node->bbox());
_nodes[head].setPrimIndex(1, primIndex);
_nodes[head].setRchild(nullptr);
primIndices[primIndex++] = node->id();
return 1;
} else {
int childIdx = tail;
_nodes[head].setJointBbox(node->child(0)->bbox(), node->child(1)->bbox());
_nodes[head].setLchild(&_nodes[childIdx + 0]);
_nodes[head].setRchild(&_nodes[childIdx + 1]);
tail += 2;
uint32 lPrims = recursiveBuild(node->child(0), childIdx + 0, tail, primIndex, primIndices, maxPrimsPerLeaf);
uint32 rPrims = recursiveBuild(node->child(1), childIdx + 1, tail, primIndex, primIndices, maxPrimsPerLeaf);
if (lPrims + rPrims <= maxPrimsPerLeaf) {
_nodes[head].setPrimIndex(lPrims + rPrims, _nodes[childIdx].primIndex());
_nodes[head].setRchild(nullptr);
tail = childIdx;
}
return lPrims + rPrims;
}
}
bool bboxIntersection(const Box3f &box, const Vec3f &o, const Vec3f &d, float &tMin, float &tMax) const
{
Vec3f invD = 1.0f/d;
Vec3f relMin((box.min() - o));
Vec3f relMax((box.max() - o));
float ttMin = tMin, ttMax = tMax;
for (int i = 0; i < 3; ++i) {
if (invD[i] >= 0.0f) {
ttMin = max(ttMin, relMin[i]*invD[i]);
ttMax = min(ttMax, relMax[i]*invD[i]);
} else {
ttMax = min(ttMax, relMin[i]*invD[i]);
ttMin = max(ttMin, relMax[i]*invD[i]);
}
}
if (ttMin <= ttMax) {
tMin = ttMin;
tMax = ttMax;
return true;
}
return false;
}
public:
BinaryBvh(PrimVector prims, int maxPrimsPerLeaf)
{
size_t count = prims.size();
if (prims.empty()) {
_depth = 0;
_nodes.push_back(TinyBvhNode());
_nodes.back().setJointBbox(Box3f(), Box3f());
_nodes.back().setRchild(&_nodes.back());
} else {
BvhBuilder builder(2);
builder.build(std::move(prims));
_primIndices.resize(count);
_nodes.resize(builder.numNodes());
_depth = builder.depth();
_bounds = builder.root()->bbox();
uint32 tail = 1, primIndex = 0;
recursiveBuild(builder.root().get(), 0, tail, primIndex, _primIndices, maxPrimsPerLeaf);
builder.root().reset();
_nodes.resize(tail);
}
}
template<typename LAMBDA>
void trace(Ray &ray, LAMBDA intersector) const
{
struct StackNode
{
const TinyBvhNode *node;
float tMin;
void set(const TinyBvhNode *n, float t)
{
node = n;
tMin = t;
}
};
StackNode *stack = reinterpret_cast<StackNode *>(alloca((_depth + 1)*sizeof(StackNode)));
StackNode *stackPtr = stack;
const TinyBvhNode *node = &_nodes[0];
float tMin = ray.nearT(), tMax = ray.farT();
if (!bboxIntersection(_bounds, ray.pos(), ray.dir(), tMin, tMax))
return;
const float4 signMask(_mm_castsi128_ps(_mm_set_epi32(0x80000000, 0x80000000, 0x00000000, 0x00000000)));
const __m128i keepNearFar = _mm_set_epi8(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0);
const __m128i swapNearFar = _mm_set_epi8( 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8);
const __m128i xMask = ray.dir().x() >= 0.0f ? keepNearFar : swapNearFar;
const __m128i yMask = ray.dir().y() >= 0.0f ? keepNearFar : swapNearFar;
const __m128i zMask = ray.dir().z() >= 0.0f ? keepNearFar : swapNearFar;
const Vec3pf rayO(transpose(ray.pos()));
const Vec3pf invDir = float4(1.0f)/transpose(ray.dir());
const Vec3pf invNegDir(invDir.x() ^ signMask, invDir.y() ^ signMask, invDir.z() ^ signMask);
uint32 start, count;
float4 nearFar(ray.nearT(), ray.nearT(), -ray.farT(), -ray.farT());
while (true) {
while (node->isNode()) {
const Vec3pf tNearFar = Vec3pf(
float4(_mm_castsi128_ps(_mm_shuffle_epi8(_mm_castps_si128((node->bbox().x() - rayO.x()).raw()), xMask))),
float4(_mm_castsi128_ps(_mm_shuffle_epi8(_mm_castps_si128((node->bbox().y() - rayO.y()).raw()), yMask))),
float4(_mm_castsi128_ps(_mm_shuffle_epi8(_mm_castps_si128((node->bbox().z() - rayO.z()).raw()), zMask)))
)*invNegDir;
float4 minMax = max(tNearFar.x(), tNearFar.y(), tNearFar.z(), nearFar);
minMax ^= signMask;
float4 maxMin(_mm_castsi128_ps(_mm_shuffle_epi8(_mm_castps_si128(minMax.raw()), swapNearFar)));
bool4 hit = minMax <= maxMin;
bool intersectsL = hit[0];
bool intersectsR = hit[1];
if (intersectsL && intersectsR) {
if (minMax[0] < minMax[1]) {
stackPtr++->set(node->rChild(), minMax[1]);
node = node->lChild();
tMin = minMax[0];
} else {
stackPtr++->set(node->lChild(), minMax[0]);
node = node->rChild();
tMin = minMax[1];
}
} else if (intersectsL) {
node = node->lChild();
tMin = minMax[0];
} else if (intersectsR) {
node = node->rChild();
tMin = minMax[1];
} else {
goto pop;
}
}
start = node->primIndex();
count = node->childCount();
for (uint32 i = start; i < start + count; ++i)
intersector(ray, _primIndices[i], tMin, node->bbox());
tMax = min(tMax, ray.farT());
nearFar[2] = nearFar[3] = -tMax;
pop:
if (stackPtr-- == stack)
return;
node = stackPtr->node;
tMin = stackPtr->tMin;
if (tMax < tMin)
goto pop;
}
}
};
}
}
#endif /* BINARYBVH_HPP_ */
| 30.958763 | 125 | 0.50605 | [
"vector"
] |
17b7490a890c3370ec7f79c3f721a46bda344594 | 1,458 | hpp | C++ | src/trace/D3DCodegen/Generator/DXHGenerator.hpp | attila-sim/attila-sim | a64b57240b4e10dc4df7f21eff0232b28df09532 | [
"BSD-3-Clause"
] | 23 | 2016-01-14T04:47:13.000Z | 2022-01-13T14:02:08.000Z | src/trace/D3DCodegen/Generator/DXHGenerator.hpp | attila-sim/attila-sim | a64b57240b4e10dc4df7f21eff0232b28df09532 | [
"BSD-3-Clause"
] | 2 | 2018-03-25T14:39:20.000Z | 2022-03-18T05:11:21.000Z | src/trace/D3DCodegen/Generator/DXHGenerator.hpp | attila-sim/attila-sim | a64b57240b4e10dc4df7f21eff0232b28df09532 | [
"BSD-3-Clause"
] | 17 | 2016-02-13T05:35:35.000Z | 2022-03-24T16:05:40.000Z | /**************************************************************************
*
* Copyright (c) 2002 - 2011 by Computer Architecture Department,
* Universitat Politecnica de Catalunya.
* All rights reserved.
*
* The contents of this file may not be disclosed to third parties,
* copied or duplicated in any form, in whole or in part, without the
* prior permission of the authors, Computer Architecture Department
* and Universitat Politecnica de Catalunya.
*
*/
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "stdafx.h"
////////////////////////////////////////////////////////////////////////////////
namespace dxcodegen
{
namespace Config
{
class GeneratorConfiguration;
}
namespace Items
{
class ClassDescription;
}
namespace Generator
{
class IGenerator;
class ClassGenerator;
class DXHGenerator
{
public:
DXHGenerator(Config::GeneratorConfiguration& config);
~DXHGenerator();
void AddClasses(std::vector<Items::ClassDescription>& classes);
void GenerateCode();
protected:
Config::GeneratorConfiguration& m_config;
std::string m_pathGeneration;
std::vector<IGenerator*>* m_lstGenerators;
void CreateGenerationPath();
void SetGenerationPath(const std::string& path);
};
}
}
////////////////////////////////////////////////////////////////////////////////
| 23.142857 | 80 | 0.537037 | [
"vector"
] |
17b93969f816160764d2c92aa56ee4fc3fdc5a3e | 3,924 | cpp | C++ | plugins/dali-script-v8/src/rendering/sampler-wrapper.cpp | tizenorg/platform.core.uifw.dali-toolkit | 146486a8c7410a2f2a20a6d670145fe855672b96 | [
"Apache-2.0"
] | null | null | null | plugins/dali-script-v8/src/rendering/sampler-wrapper.cpp | tizenorg/platform.core.uifw.dali-toolkit | 146486a8c7410a2f2a20a6d670145fe855672b96 | [
"Apache-2.0"
] | null | null | null | plugins/dali-script-v8/src/rendering/sampler-wrapper.cpp | tizenorg/platform.core.uifw.dali-toolkit | 146486a8c7410a2f2a20a6d670145fe855672b96 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2015 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include "sampler-wrapper.h"
// INTERNAL INCLUDES
#include <v8-utils.h>
#include <dali-wrapper.h>
#include <shared/api-function.h>
#include <shared/object-template-helper.h>
#include <rendering/sampler-api.h>
namespace Dali
{
namespace V8Plugin
{
v8::Persistent<v8::ObjectTemplate> SamplerWrapper::mSamplerTemplate;
namespace
{
/**
* Contains a list of all functions that can be called
*/
const ApiFunction SamplerFunctionTable[]=
{
/**************************************
* Sampler API (in order of sampler.h)
**************************************/
{ "SetFilterMode", SamplerApi::SetFilterMode },
{ "SetWrapMode", SamplerApi::SetWrapMode },
};
const unsigned int SamplerFunctionTableCount = sizeof(SamplerFunctionTable)/sizeof(SamplerFunctionTable[0]);
} //un-named space
SamplerWrapper::SamplerWrapper( const Sampler& sampler, GarbageCollectorInterface& gc )
: BaseWrappedObject( BaseWrappedObject::SAMPLER , gc )
{
mSampler = sampler;
}
v8::Handle<v8::Object> SamplerWrapper::WrapSampler(v8::Isolate* isolate, const Sampler& sampler )
{
v8::EscapableHandleScope handleScope( isolate );
v8::Local<v8::ObjectTemplate> objectTemplate;
objectTemplate = GetSamplerTemplate( isolate);
// create an instance of the template
v8::Local<v8::Object> localObject = objectTemplate->NewInstance();
// create the Sampler wrapper
SamplerWrapper* pointer = new SamplerWrapper( sampler, Dali::V8Plugin::DaliWrapper::Get().GetDaliGarbageCollector() );
// assign the JavaScript object to the wrapper.
pointer->SetJavascriptObject( isolate, localObject );
return handleScope.Escape( localObject );
}
v8::Local<v8::ObjectTemplate> SamplerWrapper::GetSamplerTemplate( v8::Isolate* isolate)
{
v8::EscapableHandleScope handleScope( isolate );
v8::Local<v8::ObjectTemplate> objectTemplate;
if( mSamplerTemplate.IsEmpty() )
{
objectTemplate = MakeSamplerTemplate( isolate );
mSamplerTemplate.Reset( isolate, objectTemplate );
}
else
{
// get the object template
objectTemplate = v8::Local<v8::ObjectTemplate>::New( isolate, mSamplerTemplate );
}
return handleScope.Escape( objectTemplate );
}
v8::Handle<v8::ObjectTemplate> SamplerWrapper::MakeSamplerTemplate( v8::Isolate* isolate )
{
v8::EscapableHandleScope handleScope( isolate );
v8::Local<v8::ObjectTemplate> objTemplate = v8::ObjectTemplate::New();
objTemplate->SetInternalFieldCount( BaseWrappedObject::FIELD_COUNT );
// add our function properties
ObjectTemplateHelper::InstallFunctions( isolate, objTemplate, SamplerFunctionTable, SamplerFunctionTableCount );
return handleScope.Escape( objTemplate );
}
void SamplerWrapper::NewSampler( const v8::FunctionCallbackInfo< v8::Value >& args)
{
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handleScope( isolate);
if(!args.IsConstructCall())
{
DALI_SCRIPT_EXCEPTION( isolate, "Sampler constructor called without 'new'");
return;
}
Dali::Sampler sampler = SamplerApi::New( args );
if(sampler)
{
v8::Local<v8::Object> localObject = WrapSampler( isolate, sampler );
args.GetReturnValue().Set( localObject );
}
}
Sampler SamplerWrapper::GetSampler()
{
return mSampler;
}
} // namespace V8Plugin
} // namespace Dali
| 28.028571 | 121 | 0.717125 | [
"object"
] |
17bded3b76bc9788142dbe79fbd18f182f3dc1d6 | 61 | cxx | C++ | base/fs/utils/ntlib/src/object.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/fs/utils/ntlib/src/object.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/fs/utils/ntlib/src/object.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | #include "pch.cxx"
#include "..\..\ulib\src\object.cxx"
| 20.333333 | 38 | 0.590164 | [
"object"
] |
17bf4f8e84711e369d9958bf2f164346029352bb | 711 | cpp | C++ | Aruco.Net/Board.cpp | horizongir/aruco.net | 1a085b917e2ec89f1c34568e509005e35f3a3223 | [
"MIT"
] | null | null | null | Aruco.Net/Board.cpp | horizongir/aruco.net | 1a085b917e2ec89f1c34568e509005e35f3a3223 | [
"MIT"
] | null | null | null | Aruco.Net/Board.cpp | horizongir/aruco.net | 1a085b917e2ec89f1c34568e509005e35f3a3223 | [
"MIT"
] | null | null | null | #include "StdAfx.h"
#include "Board.h"
using namespace System::Runtime::InteropServices;
Aruco::Net::Board::Board(const aruco::Board &board, float likelihood):
board(new aruco::Board(board)),
markers(gcnew List<Marker ^>(board.size())),
likelihood(likelihood)
{
std::vector<aruco::Marker>::const_iterator it;
for (it = board.begin(); it < board.end(); it++)
{
markers->Add(gcnew Marker(*it));
}
}
Aruco::Net::Board::!Board()
{
delete board;
}
cli::array<double> ^ Aruco::Net::Board::GetGLModelViewMatrix()
{
cli::array<double> ^result = gcnew cli::array<double>(16);
cli::pin_ptr<double> modelView = &result[0];
board->glGetModelViewMatrix(modelView);
return result;
} | 24.517241 | 71 | 0.670886 | [
"vector"
] |
17c677fb96601facc086d4adf1a7db04e0915a45 | 2,467 | hpp | C++ | ige/include/ige/plugin/UiPlugin.hpp | Arcahub/ige | b9f61209c924c7b683d2429a07e76251e6eb7b1b | [
"MIT"
] | 3 | 2021-06-05T00:36:50.000Z | 2022-02-27T10:23:53.000Z | ige/include/ige/plugin/UiPlugin.hpp | Arcahub/ige | b9f61209c924c7b683d2429a07e76251e6eb7b1b | [
"MIT"
] | 11 | 2021-05-08T22:00:24.000Z | 2021-11-11T22:33:43.000Z | ige/include/ige/plugin/UiPlugin.hpp | Arcahub/ige | b9f61209c924c7b683d2429a07e76251e6eb7b1b | [
"MIT"
] | 4 | 2021-05-20T12:41:23.000Z | 2021-11-09T14:19:18.000Z | #ifndef A3879050_3E91_426B_BD37_E5E44D0860BD
#define A3879050_3E91_426B_BD37_E5E44D0860BD
#include "ige/core/App.hpp"
#include "ige/ecs/Entity.hpp"
#include "ige/ecs/Resources.hpp"
#include "ige/ecs/World.hpp"
#include "ige/plugin/input/Mouse.hpp"
#include <cstdint>
#include <functional>
#include <glm/vec2.hpp>
#include <utility>
#include <vector>
namespace ige::plugin::ui {
namespace event {
struct MouseEvent {
glm::vec2 pos;
glm::vec2 absolute_pos;
};
struct MouseDown : public MouseEvent {
input::MouseButton button;
};
struct MouseUp : public MouseEvent {
input::MouseButton button;
};
struct MouseClick : public MouseEvent {
input::MouseButton button;
};
struct MouseScroll : public MouseEvent {
glm::vec2 delta;
};
struct MouseEnter : public MouseEvent {
};
struct MouseLeave : public MouseEvent {
};
struct MouseMove : public MouseEvent {
};
}
class EventTarget {
public:
template <typename T>
using Callback
= std::function<void(ecs::World&, const ecs::EntityId&, const T&)>;
template <typename T>
EventTarget& on(Callback<T>&& callback) &
{
add_callback<T>(std::forward<Callback<T>>(callback));
return *this;
}
template <typename T>
EventTarget on(Callback<T>&& callback) &&
{
return std::move(on<T>(std::forward<Callback<T>>(callback)));
}
template <typename T>
void trigger(ecs::World& world, const ecs::EntityId& entity, const T& event)
{
trigger_callbacks<T>(world, entity, event);
}
private:
template <typename T>
using CallbackVector = std::vector<Callback<T>>;
template <typename T>
void add_callback(Callback<T> callback)
{
auto& cb_vector = m_callbacks.get_or_emplace<CallbackVector<T>>();
cb_vector.emplace_back(std::forward<Callback<T>>(callback));
}
template <typename T>
void trigger_callbacks(
ecs::World& world, const ecs::EntityId& entity, const T& event)
{
if (auto callbacks = m_callbacks.get<CallbackVector<T>>()) {
for (auto& callback : *callbacks) {
callback(world, entity, event);
}
}
}
ecs::Resources m_callbacks;
};
class UiPlugin : public core::App::Plugin {
public:
void plug(core::App::Builder&) const override;
};
}
#endif /* A3879050_3E91_426B_BD37_E5E44D0860BD */
| 22.427273 | 80 | 0.6364 | [
"vector"
] |
17c6c467cd34b367e7e241316669d20a3637b52e | 4,900 | cc | C++ | src/extensions/far/farscript.cc | entn-at/openfst | 10ab103134b1872e475800fd5ea37747d1c0c858 | [
"Apache-2.0"
] | 336 | 2018-11-06T14:03:32.000Z | 2022-03-31T00:48:03.000Z | src/extensions/far/farscript.cc | entn-at/openfst | 10ab103134b1872e475800fd5ea37747d1c0c858 | [
"Apache-2.0"
] | 43 | 2017-07-13T21:04:44.000Z | 2022-02-16T19:47:53.000Z | src/extensions/far/farscript.cc | entn-at/openfst | 10ab103134b1872e475800fd5ea37747d1c0c858 | [
"Apache-2.0"
] | 77 | 2018-11-07T06:43:10.000Z | 2021-12-10T04:16:43.000Z | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Definitions of 'scriptable' versions of FAR operations, that is,
// those that can be called with FstClass-type arguments.
#include <fst/extensions/far/farscript.h>
#include <fst/extensions/far/far.h>
#include <fst/script/script-impl.h>
namespace fst {
namespace script {
void FarCompileStrings(const std::vector<string> &in_fnames,
const string &out_fname, const string &arc_type,
const string &fst_type, const FarType &far_type,
int32 generate_keys, FarEntryType fet, FarTokenType tt,
const string &symbols_fname,
const string &unknown_symbol, bool keep_symbols,
bool initial_symbols, bool allow_negative_labels,
const string &key_prefix, const string &key_suffix) {
FarCompileStringsArgs args(in_fnames, out_fname, fst_type, far_type,
generate_keys, fet, tt, symbols_fname,
unknown_symbol, keep_symbols, initial_symbols,
allow_negative_labels, key_prefix, key_suffix);
Apply<Operation<FarCompileStringsArgs>>("FarCompileStrings", arc_type, &args);
}
void FarCreate(const std::vector<string> &in_fnames, const string &out_fname,
const string &arc_type, const int32 generate_keys,
const FarType &far_type, const string &key_prefix,
const string &key_suffix) {
FarCreateArgs args(in_fnames, out_fname, generate_keys, far_type, key_prefix,
key_suffix);
Apply<Operation<FarCreateArgs>>("FarCreate", arc_type, &args);
}
bool FarEqual(const string &filename1, const string &filename2,
const string &arc_type, float delta, const string &begin_key,
const string &end_key) {
FarEqualInnerArgs args(filename1, filename2, delta, begin_key, end_key);
FarEqualArgs args_with_retval(args);
Apply<Operation<FarEqualArgs>>("FarEqual", arc_type, &args_with_retval);
return args_with_retval.retval;
}
void FarExtract(const std::vector<string> &ifilenames, const string &arc_type,
int32 generate_filenames, const string &keys,
const string &key_separator, const string &range_delimiter,
const string &filename_prefix, const string &filename_suffix) {
FarExtractArgs args(ifilenames, generate_filenames, keys, key_separator,
range_delimiter, filename_prefix, filename_suffix);
Apply<Operation<FarExtractArgs>>("FarExtract", arc_type, &args);
}
void FarInfo(const std::vector<string> &filenames, const string &arc_type,
const string &begin_key, const string &end_key,
const bool list_fsts) {
FarInfoArgs args(filenames, begin_key, end_key, list_fsts);
Apply<Operation<FarInfoArgs>>("FarInfo", arc_type, &args);
}
void GetFarInfo(const std::vector<string> &filenames, const string &arc_type,
const string &begin_key, const string &end_key,
const bool list_fsts, FarInfoData *data) {
GetFarInfoArgs args(filenames, begin_key, end_key, list_fsts, data);
Apply<Operation<GetFarInfoArgs>>("GetFarInfo", arc_type, &args);
}
bool FarIsomorphic(const string &filename1, const string &filename2,
const string &arc_type, float delta, const string &begin_key,
const string &end_key) {
FarIsomorphicInnerArgs args(filename1, filename2, delta, begin_key, end_key);
FarIsomorphicArgs args_with_retval(args);
Apply<Operation<FarIsomorphicArgs>>("FarIsomorphic", arc_type,
&args_with_retval);
return args_with_retval.retval;
}
void FarPrintStrings(const std::vector<string> &ifilenames,
const string &arc_type, const FarEntryType entry_type,
const FarTokenType token_type, const string &begin_key,
const string &end_key, const bool print_key,
const bool print_weight, const string &symbols_fname,
const bool initial_symbols, const int32 generate_filenames,
const string &filename_prefix,
const string &filename_suffix) {
FarPrintStringsArgs args(ifilenames, entry_type, token_type, begin_key,
end_key, print_key, print_weight, symbols_fname,
initial_symbols, generate_filenames, filename_prefix,
filename_suffix);
Apply<Operation<FarPrintStringsArgs>>("FarPrintStrings", arc_type, &args);
}
// Instantiate all templates for common arc types.
REGISTER_FST_FAR_OPERATIONS(StdArc);
REGISTER_FST_FAR_OPERATIONS(LogArc);
REGISTER_FST_FAR_OPERATIONS(Log64Arc);
} // namespace script
} // namespace fst
| 47.572816 | 80 | 0.672245 | [
"vector"
] |
17c9d03ef33eab90f68732b3d4e9188c108842ab | 981 | cpp | C++ | Codeforces/C1082.cpp | amrfahmyy/Problem-Solving | 4c7540a1df3c4be206fc6dc6c77d754b513b314f | [
"Apache-2.0"
] | null | null | null | Codeforces/C1082.cpp | amrfahmyy/Problem-Solving | 4c7540a1df3c4be206fc6dc6c77d754b513b314f | [
"Apache-2.0"
] | null | null | null | Codeforces/C1082.cpp | amrfahmyy/Problem-Solving | 4c7540a1df3c4be206fc6dc6c77d754b513b314f | [
"Apache-2.0"
] | 1 | 2021-04-02T14:20:11.000Z | 2021-04-02T14:20:11.000Z | #include <bits/stdc++.h>
#define SLAY ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define PI 3.141592653589793238
#define ll long long
#define pii pair<int , int>
#define pll pair<long long , long long>
#define INPUT freopen(".txt", "r", stdin);
using namespace std;
int dx[] = { 0 , 0 , 1 , -1};
int dy[] = { 1 , -1 , 0 , 0};
int getmod(int x, int y , int mod ){return (((x - y)%mod)+mod)%mod;}
int main(){SLAY
int _=1 , tc=1;
// cin>>_;
while(_--){
ll n,a,b,c,m;
ll ans=0;
cin>>n>>m;
vector< vector<ll> >table(m+1);
vector< ll >cands(n,0);
for(int i = 0;i<n ; i++){
ll r ,s;
cin>>s>>r;
table[s].push_back(r);
}
for(int i = 1;i<=m;i++){
sort(table[i].rbegin(),table[i].rend());
ll pre=0;
for(int j = 0;j<table[i].size();j++){
pre+=table[i][j];
table[i][j] = pre;
if(pre>0)cands[j]+=pre;
}
}
for(int i = 0;i<n;i++){
ans = max((ll)ans,(ll)cands[i]);
}
cout<<ans;
cout<<endl;
}
return 0;
}
| 21.326087 | 71 | 0.541284 | [
"vector"
] |
17cbe81b367c9179e73e254e9faebb6b6113f3d7 | 21,736 | cc | C++ | src/HashTableTest.cc | rohankumardubey/ramcloud | 3a30ba5edc4a81d5e12ab20fda0360cb9bacf50f | [
"0BSD"
] | 5 | 2015-11-14T16:49:06.000Z | 2019-09-03T13:21:30.000Z | src/HashTableTest.cc | rohankumardubey/ramcloud | 3a30ba5edc4a81d5e12ab20fda0360cb9bacf50f | [
"0BSD"
] | null | null | null | src/HashTableTest.cc | rohankumardubey/ramcloud | 3a30ba5edc4a81d5e12ab20fda0360cb9bacf50f | [
"0BSD"
] | 1 | 2018-02-25T11:16:27.000Z | 2018-02-25T11:16:27.000Z | /* Copyright (c) 2009-2010 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "TestUtil.h"
#include "HashTable.h"
namespace RAMCloud {
class TestObject {
public:
TestObject() : _key1(0), _key2(0) {}
TestObject(uint64_t key1, uint64_t key2) : _key1(key1), _key2(key2) {}
uint64_t key1() const { return _key1; }
uint64_t key2() const { return _key2; }
uint64_t _key1, _key2;
};
typedef HashTable<TestObject*> TestObjectMap;
/**
* Unit tests for HashTable::PerfDistribution.
*/
class HashTablePerfDistributionTest : public ::testing::Test {
public:
HashTablePerfDistributionTest() {}
DISALLOW_COPY_AND_ASSIGN(HashTablePerfDistributionTest);
};
TEST_F(HashTablePerfDistributionTest, constructor) {
RAMCloud::TestObjectMap::PerfDistribution d;
EXPECT_EQ(~0UL, d.min);
EXPECT_EQ(0UL, d.max);
EXPECT_EQ(0UL, d.binOverflows);
EXPECT_EQ(0UL, d.bins[0]);
EXPECT_EQ(0UL, d.bins[1]);
EXPECT_EQ(0UL, d.bins[2]);
}
TEST_F(HashTablePerfDistributionTest, storeSample) {
TestObjectMap::PerfDistribution d;
// You can't use EXPECT_TRUE here because it tries to take a
// reference to BIN_WIDTH. See 10.4.6.2 Member Constants of The C++
// Programming Language by Bjarne Stroustrup for more about static
// constant integers.
EXPECT_TRUE(10 == TestObjectMap::PerfDistribution::BIN_WIDTH); // NOLINT
d.storeSample(3);
EXPECT_EQ(3UL, d.min);
EXPECT_EQ(3UL, d.max);
EXPECT_EQ(0UL, d.binOverflows);
EXPECT_EQ(1UL, d.bins[0]);
EXPECT_EQ(0UL, d.bins[1]);
EXPECT_EQ(0UL, d.bins[2]);
d.storeSample(3);
d.storeSample(d.NBINS * d.BIN_WIDTH + 40);
d.storeSample(12);
d.storeSample(78);
EXPECT_EQ(3UL, d.min);
EXPECT_EQ(d.NBINS * d.BIN_WIDTH + 40, d.max);
EXPECT_EQ(1UL, d.binOverflows);
EXPECT_EQ(2UL, d.bins[0]);
EXPECT_EQ(1UL, d.bins[1]);
EXPECT_EQ(0UL, d.bins[2]);
}
/**
* Unit tests for HashTable::Entry.
*/
class HashTableEntryTest : public ::testing::Test {
public:
HashTableEntryTest() {}
/**
* Return whether fields make it through #HashTable::Entry::pack() and
* #HashTable::Entry::unpack() successfully.
* \param hash
* See #HashTable::Entry::pack().
* \param chain
* See #HashTable::Entry::pack().
* \param ptr
* See #HashTable::Entry::pack().
* \return
* Whether the fields out of #HashTable::Entry::unpack() are the same.
*/
static bool
packable(uint64_t hash, bool chain, uint64_t ptr)
{
TestObjectMap::Entry e;
TestObjectMap::Entry::UnpackedEntry in;
TestObjectMap::Entry::UnpackedEntry out;
in.hash = hash;
in.chain = chain;
in.ptr = ptr;
e.pack(in.hash, in.chain, in.ptr);
out = e.unpack();
return (in.hash == out.hash &&
in.chain == out.chain &&
in.ptr == out.ptr);
}
DISALLOW_COPY_AND_ASSIGN(HashTableEntryTest);
};
TEST_F(HashTableEntryTest, size) {
EXPECT_EQ(8U, sizeof(TestObjectMap::Entry));
}
// also tests unpack
TEST_F(HashTableEntryTest, pack) {
// first without normal cases
EXPECT_TRUE(packable(0x0000UL, false, 0x000000000000UL));
EXPECT_TRUE(packable(0xffffUL, true, 0x7fffffffffffUL));
EXPECT_TRUE(packable(0xffffUL, false, 0x7fffffffffffUL));
EXPECT_TRUE(packable(0xa257UL, false, 0x3cdeadbeef98UL));
// and now test the exception cases of pack()
TestObjectMap::Entry e;
EXPECT_THROW(e.pack(0, false, 0xffffffffffffUL), Exception);
}
// No tests for test_unpack, since test_pack tested it.
TEST_F(HashTableEntryTest, clear) {
TestObjectMap::Entry e;
e.value = 0xdeadbeefdeadbeefUL;
e.clear();
TestObjectMap::Entry::UnpackedEntry out;
out = e.unpack();
EXPECT_EQ(0UL, out.hash);
EXPECT_FALSE(out.chain);
EXPECT_EQ(0UL, out.ptr);
}
TEST_F(HashTableEntryTest, trivial_clear) {
TestObjectMap::Entry e;
e.value = 0xdeadbeefdeadbeefUL;
e.clear();
TestObjectMap::Entry f;
f.value = 0xdeadbeefdeadbeefUL;
f.pack(0, false, 0);
EXPECT_EQ(e.value, f.value);
}
TEST_F(HashTableEntryTest, setReferent) {
TestObjectMap::Entry e;
e.value = 0xdeadbeefdeadbeefUL;
e.setReferent(0xaaaaUL, reinterpret_cast<TestObject*>(
0x7fffffffffffUL));
TestObjectMap::Entry::UnpackedEntry out;
out = e.unpack();
EXPECT_EQ(0xaaaaUL, out.hash);
EXPECT_FALSE(out.chain);
EXPECT_EQ(0x7fffffffffffUL, out.ptr);
}
TEST_F(HashTableEntryTest, setChainPointer) {
TestObjectMap::Entry e;
e.value = 0xdeadbeefdeadbeefUL;
{
TestObjectMap::CacheLine *cl;
cl = reinterpret_cast<TestObjectMap::CacheLine*>(
0x7fffffffffffUL);
e.setChainPointer(cl);
}
TestObjectMap::Entry::UnpackedEntry out;
out = e.unpack();
EXPECT_EQ(0UL, out.hash);
EXPECT_TRUE(out.chain);
EXPECT_EQ(0x7fffffffffffUL, out.ptr);
}
TEST_F(HashTableEntryTest, isAvailable) {
TestObjectMap::Entry e;
e.clear();
EXPECT_TRUE(e.isAvailable());
e.setChainPointer(reinterpret_cast<TestObjectMap::CacheLine*>(
0x1UL));
EXPECT_FALSE(e.isAvailable());
e.setReferent(0UL, reinterpret_cast<TestObject*>(0x1UL));
EXPECT_FALSE(e.isAvailable());
e.clear();
EXPECT_TRUE(e.isAvailable());
}
TEST_F(HashTableEntryTest, getReferent) {
TestObjectMap::Entry e;
TestObject *o =
reinterpret_cast<TestObject*>(0x7fffffffffffUL);
e.setReferent(0xaaaaUL, o);
EXPECT_EQ(o, e.getReferent());
}
TEST_F(HashTableEntryTest, getChainPointer) {
TestObjectMap::CacheLine *cl;
cl = reinterpret_cast<TestObjectMap::CacheLine*>(0x7fffffffffffUL);
TestObjectMap::Entry e;
e.setChainPointer(cl);
EXPECT_EQ(cl, e.getChainPointer());
e.clear();
EXPECT_TRUE(NULL == e.getChainPointer());
e.setReferent(0UL, reinterpret_cast<TestObject*>(0x1UL));
EXPECT_TRUE(NULL == e.getChainPointer());
}
TEST_F(HashTableEntryTest, hashMatches) {
TestObjectMap::Entry e;
e.clear();
EXPECT_TRUE(!e.hashMatches(0UL));
e.setChainPointer(reinterpret_cast<TestObjectMap::CacheLine*>(
0x1UL));
EXPECT_TRUE(!e.hashMatches(0UL));
e.setReferent(0UL, reinterpret_cast<TestObject*>(0x1UL));
EXPECT_TRUE(e.hashMatches(0UL));
EXPECT_TRUE(!e.hashMatches(0xbeefUL));
e.setReferent(0xbeefUL, reinterpret_cast<TestObject*>(0x1UL));
EXPECT_TRUE(!e.hashMatches(0UL));
EXPECT_TRUE(e.hashMatches(0xbeefUL));
EXPECT_TRUE(!e.hashMatches(0xfeedUL));
}
/**
* Unit tests for HashTable.
*/
class HashTableTest : public ::testing::Test {
public:
HashTableTest() { }
// convenient abbreviation
#define seven (TestObjectMap::ENTRIES_PER_CACHE_LINE - 1)
/**
* Insert an array of values into a single-bucket hash table.
* \param[in] ht
* A hash table with a single bucket.
* \param[in] values
* An array of values to add to the bucket (in order). These need not
* be initialized and will be set counting up from 0.
* \param[in] tableId
* The table ID to use for each object inserted.
* \param[in] numEnt
* The number of values in \a values.
* \param[in] cacheLines
* An array of cache lines to back the bucket with.
* \param[in] numCacheLines
* The number of cache lines in \a cacheLines.
*/
void insertArray(TestObjectMap *ht, TestObject *values, uint64_t tableId,
uint64_t numEnt,
LargeBlockOfMemory<TestObjectMap::CacheLine> *cacheLines,
uint64_t numCacheLines)
{
TestObjectMap::CacheLine *cl;
// chain all the cache lines
cl = &cacheLines->get()[0];
while (cl < &cacheLines->get()[numCacheLines - 1]) {
cl->entries[seven].setChainPointer(cl + 1);
cl++;
}
// fill in the "log" entries
for (uint64_t i = 0; i < numEnt; i++) {
values[i]._key1 = tableId;
values[i]._key2 = i;
uint64_t littleHash;
(void) ht->findBucket(0, i, &littleHash);
TestObjectMap::Entry *entry;
if (0 < i && i == numEnt - 1 && i % seven == 0)
entry = &cacheLines->get()[i / seven - 1].entries[seven];
else
entry = &cacheLines->get()[i / seven].entries[i % seven];
entry->setReferent(littleHash, &values[i]);
}
ht->buckets.swap(*cacheLines);
}
/**
* Common setup code for the lookupEntry and insert tests.
* This mostly declares variables on the stack, so it's a macro.
* \li \a numEnt is set to \a _numEnt
* \li \a numCacheLines is the number of cache lines used to hold the
* entries.
* \li \a ht is a hash table of one bucket.
* \li \a values is an array of \a numEnt objects.
* \param _tableId
* The table id to use for all objects placed in the hashtable.
* \param _numEnt
* The number of entries to place in the hashtable.
*/
#define SETUP(_tableId, _numEnt) \
uint64_t tableId = _tableId; \
uint64_t numEnt = _numEnt; \
uint64_t numCacheLines; \
numCacheLines = ((numEnt + TestObjectMap::ENTRIES_PER_CACHE_LINE - 2) /\
(TestObjectMap::ENTRIES_PER_CACHE_LINE - 1));\
if (numCacheLines == 0) \
numCacheLines = 1; \
TestObjectMap ht(1); \
TestObject values[numEnt]; \
LargeBlockOfMemory<TestObjectMap::CacheLine> _cacheLines( \
numCacheLines * sizeof(TestObjectMap::CacheLine)); \
insertArray(&ht, values, tableId, numEnt, &_cacheLines, numCacheLines); \
#define NULL_OBJECT (static_cast<TestObject*>(NULL))
/**
* Find an entry in a single-bucket hash table by position.
* \param[in] ht
* A hash table with a single bucket.
* \param[in] x
* The number of the cache line in the chain, starting from 0.
* \param[in] y
* The number of the entry in the cache line, starting from 0.
* \return
* The entry at \a x and \a y in the only bucket of \a ht.
*/
TestObjectMap::Entry& entryAt(TestObjectMap *ht, uint64_t x,
uint64_t y)
{
TestObjectMap::CacheLine *cl = &ht->buckets.get()[0];
while (x > 0) {
cl = cl->entries[seven].getChainPointer();
x--;
}
return cl->entries[y];
}
/**
* Ensure an entry in a single-bucket hash table contains a given pointer.
* \param[in] ht
* A hash table with a single bucket.
* \param[in] x
* The number of the cache line in the chain, starting from 0.
* \param[in] y
* The number of the entry in the cache line, starting from 0.
* \param[in] ptr
* The pointer that we expect to find at the given position.
*/
void assertEntryIs(TestObjectMap *ht, uint64_t x, uint64_t y,
TestObject *ptr)
{
uint64_t littleHash;
(void) ht->findBucket(0, ptr->key2(), &littleHash);
TestObjectMap::Entry& entry = entryAt(ht, x, y);
EXPECT_TRUE(entry.hashMatches(littleHash));
EXPECT_EQ(ptr, entry.getReferent());
}
TestObjectMap::Entry *findBucketAndLookupEntry(TestObjectMap *ht,
uint64_t tableId,
uint64_t objectId)
{
uint64_t secondaryHash;
TestObjectMap::CacheLine *bucket;
bucket = ht->findBucket(0, objectId, &secondaryHash);
return ht->lookupEntry(bucket, secondaryHash, tableId, objectId);
}
DISALLOW_COPY_AND_ASSIGN(HashTableTest);
};
TEST_F(HashTableTest, constructor) {
TestObjectMap ht(16);
for (uint32_t i = 0; i < 16; i++) {
for (uint32_t j = 0; j < ht.entriesPerCacheLine(); j++)
EXPECT_TRUE(ht.buckets.get()[i].entries[j].isAvailable());
}
}
TEST_F(HashTableTest, constructor_truncate) {
// This is effectively testing nearestPowerOfTwo.
EXPECT_EQ(1UL, TestObjectMap(1).numBuckets);
EXPECT_EQ(2UL, TestObjectMap(2).numBuckets);
EXPECT_EQ(2UL, TestObjectMap(3).numBuckets);
EXPECT_EQ(4UL, TestObjectMap(4).numBuckets);
EXPECT_EQ(4UL, TestObjectMap(5).numBuckets);
EXPECT_EQ(4UL, TestObjectMap(6).numBuckets);
EXPECT_EQ(4UL, TestObjectMap(7).numBuckets);
EXPECT_EQ(8UL, TestObjectMap(8).numBuckets);
}
TEST_F(HashTableTest, destructor) {
}
TEST_F(HashTableTest, simple) {
TestObjectMap ht(1024);
TestObject a(0, 0);
TestObject b(0, 10);
EXPECT_EQ(NULL_OBJECT, ht.lookup(0, 0));
ht.replace(&a);
EXPECT_EQ(const_cast<TestObject*>(&a),
ht.lookup(0, 0));
EXPECT_EQ(NULL_OBJECT, ht.lookup(0, 10));
ht.replace(&b);
EXPECT_EQ(const_cast<TestObject*>(&b),
ht.lookup(0, 10));
EXPECT_EQ(const_cast<TestObject*>(&a),
ht.lookup(0, 0));
}
TEST_F(HashTableTest, multiTable) {
TestObjectMap ht(1024);
TestObject a(0, 0);
TestObject b(1, 0);
TestObject c(0, 1);
EXPECT_EQ(NULL_OBJECT, ht.lookup(0, 0));
EXPECT_EQ(NULL_OBJECT, ht.lookup(1, 0));
EXPECT_EQ(NULL_OBJECT, ht.lookup(0, 1));
ht.replace(&a);
ht.replace(&b);
ht.replace(&c);
EXPECT_EQ(const_cast<TestObject*>(&a),
ht.lookup(0, 0));
EXPECT_EQ(const_cast<TestObject*>(&b),
ht.lookup(1, 0));
EXPECT_EQ(const_cast<TestObject*>(&c),
ht.lookup(0, 1));
}
/**
* Ensure that #RAMCloud::HashTable::hash() generates hashes using the full
* range of bits.
*/
TEST_F(HashTableTest, hash) {
uint64_t observedBits = 0UL;
srand(1);
for (uint32_t i = 0; i < 50; i++) {
uint64_t input1 = generateRandom();
uint64_t input2 = generateRandom();
observedBits |= TestObjectMap::hash(input1, input2);
}
EXPECT_EQ(~0UL, observedBits);
}
TEST_F(HashTableTest, findBucket) {
TestObjectMap ht(1024);
TestObjectMap::CacheLine *bucket;
uint64_t hashValue;
uint64_t secondaryHash;
bucket = ht.findBucket(0, 4327, &secondaryHash);
hashValue = TestObjectMap::hash(0, 4327);
EXPECT_EQ(static_cast<uint64_t>(bucket - ht.buckets.get()),
(hashValue & 0x0000ffffffffffffffffUL) % 1024);
EXPECT_EQ(secondaryHash, hashValue >> 48);
}
/**
* Test #RAMCloud::HashTable::lookupEntry() when the object ID is not
* found.
*/
TEST_F(HashTableTest, lookupEntry_notFound) {
{
SETUP(0, 0);
EXPECT_EQ(static_cast<TestObjectMap::Entry*>(NULL),
findBucketAndLookupEntry(&ht, 0, 1));
EXPECT_EQ(1UL, ht.getPerfCounters().lookupEntryCalls);
EXPECT_LT(0U, ht.getPerfCounters().lookupEntryCycles);
EXPECT_LT(0U, ht.getPerfCounters().lookupEntryDist.max);
}
{
SETUP(0, TestObjectMap::ENTRIES_PER_CACHE_LINE * 5);
EXPECT_EQ(static_cast<TestObjectMap::Entry*>(NULL),
findBucketAndLookupEntry(&ht, 0, numEnt + 1));
EXPECT_EQ(5UL, ht.getPerfCounters().lookupEntryChainsFollowed);
}
}
/**
* Test #RAMCloud::HashTable::lookupEntry() when the object ID is found in
* the first entry of the first cache line.
*/
TEST_F(HashTableTest, lookupEntry_cacheLine0Entry0) {
SETUP(0, 1);
EXPECT_EQ(&entryAt(&ht, 0, 0),
findBucketAndLookupEntry(&ht, 0, 0));
}
/**
* Test #RAMCloud::HashTable::lookupEntry() when the object ID is found in
* the last entry of the first cache line.
*/
TEST_F(HashTableTest, lookupEntry_cacheLine0Entry7) {
SETUP(0, TestObjectMap::ENTRIES_PER_CACHE_LINE);
EXPECT_EQ(&entryAt(&ht, 0, seven),
findBucketAndLookupEntry(&ht, 0, seven));
}
/**
* Test #RAMCloud::HashTable::lookupEntry() when the object ID is found in
* the first entry of the third cache line.
*/
TEST_F(HashTableTest, lookupEntry_cacheLine2Entry0) {
SETUP(0, TestObjectMap::ENTRIES_PER_CACHE_LINE * 5);
// with 8 entries per cache line:
// cl0: [ k00, k01, k02, k03, k04, k05, k06, cl1 ]
// cl1: [ k07, k09, k09, k10, k11, k12, k13, cl2 ]
// cl2: [ k14, k15, k16, k17, k18, k19, k20, cl3 ]
// ...
EXPECT_EQ(&entryAt(&ht, 2, 0),
findBucketAndLookupEntry(&ht, 0, seven * 2));
}
/**
* Test #RAMCloud::HashTable::lookupEntry() when there is a hash collision
* with another Entry.
*/
TEST_F(HashTableTest, lookupEntry_hashCollision) {
SETUP(0, 1);
EXPECT_EQ(&entryAt(&ht, 0, 0),
findBucketAndLookupEntry(&ht, 0, 0));
EXPECT_LT(0U, ht.getPerfCounters().lookupEntryDist.max);
values[0]._key2 = 0x43324890UL;
EXPECT_EQ(static_cast<TestObjectMap::Entry*>(NULL),
findBucketAndLookupEntry(&ht, 0, 0));
EXPECT_EQ(1UL, ht.getPerfCounters().lookupEntryHashCollisions);
}
TEST_F(HashTableTest, lookup) {
TestObjectMap ht(1);
TestObject *v = new TestObject(0, 83UL);
EXPECT_EQ(NULL_OBJECT, ht.lookup(0, 83UL));
ht.replace(v);
EXPECT_EQ(const_cast<TestObject*>(v),
ht.lookup(0, 83UL));
delete v;
}
TEST_F(HashTableTest, remove) {
TestObject * ptr;
TestObjectMap ht(1);
EXPECT_TRUE(!ht.remove(0, 83UL));
TestObject *v = new TestObject(0, 83UL);
ht.replace(v);
EXPECT_TRUE(ht.remove(0, 83UL, &ptr));
EXPECT_EQ(v, ptr);
EXPECT_EQ(NULL_OBJECT, ht.lookup(0, 83UL));
EXPECT_TRUE(!ht.remove(0, 83UL));
delete v;
}
TEST_F(HashTableTest, replace_normal) {
TestObject* replaced;
TestObjectMap ht(1);
TestObject *v = new TestObject(0, 83UL);
TestObject *w = new TestObject(0, 83UL);
EXPECT_TRUE(!ht.replace(v));
EXPECT_EQ(1UL, ht.getPerfCounters().replaceCalls);
EXPECT_LT(0U, ht.getPerfCounters().replaceCycles);
EXPECT_EQ(const_cast<TestObject*>(v),
ht.lookup(0, 83UL));
EXPECT_TRUE(ht.replace(v));
EXPECT_EQ(const_cast<TestObject*>(v),
ht.lookup(0, 83UL));
EXPECT_TRUE(ht.replace(w, &replaced));
EXPECT_EQ(v, replaced);
EXPECT_EQ(const_cast<TestObject*>(w),
ht.lookup(0, 83UL));
delete v;
delete w;
}
/**
* Test #RAMCloud::HashTable::replace() when the object ID is new and the
* first entry of the first cache line is available.
*/
TEST_F(HashTableTest, replace_cacheLine0Entry0) {
SETUP(0, 0);
TestObject v(0, 83UL);
ht.replace(&v);
assertEntryIs(&ht, 0, 0, &v);
}
/**
* Test #RAMCloud::HashTable::replace() when the object ID is new and the
* last entry of the first cache line is available.
*/
TEST_F(HashTableTest, replace_cacheLine0Entry7) {
SETUP(0, TestObjectMap::ENTRIES_PER_CACHE_LINE - 1);
TestObject v(0, 83UL);
ht.replace(&v);
assertEntryIs(&ht, 0, seven, &v);
}
/**
* Test #RAMCloud::HashTable::replace() when the object ID is new and the
* first entry of the third cache line is available. The third cache line
* is already chained onto the second.
*/
TEST_F(HashTableTest, replace_cacheLine2Entry0) {
SETUP(0, TestObjectMap::ENTRIES_PER_CACHE_LINE * 2);
ht.buckets.get()[2].entries[0].clear();
ht.buckets.get()[2].entries[1].clear();
TestObject v(0, 83UL);
ht.replace(&v);
assertEntryIs(&ht, 2, 0, &v);
EXPECT_EQ(2UL, ht.getPerfCounters().insertChainsFollowed);
}
/**
* Test #RAMCloud::HashTable::replace() when the object ID is new and the
* first and only cache line is full. The second cache line needs to be
* allocated.
*/
TEST_F(HashTableTest, replace_cacheLineFull) {
SETUP(0, TestObjectMap::ENTRIES_PER_CACHE_LINE);
TestObject v(0, 83UL);
ht.replace(&v);
EXPECT_TRUE(entryAt(&ht, 0, seven).getChainPointer() != NULL);
EXPECT_TRUE(entryAt(&ht, 0, seven).getChainPointer() !=
&ht.buckets.get()[1]);
assertEntryIs(&ht, 1, 0, &values[seven]);
assertEntryIs(&ht, 1, 1, &v);
}
struct ForEachTestStruct {
ForEachTestStruct() : _key1(0), _key2(0), count(0) {}
uint64_t key1() const { return _key1; }
uint64_t key2() const { return _key2; }
uint64_t _key1, _key2, count;
};
/**
* Callback used by test_forEach().
*/
static void
test_forEach_callback(ForEachTestStruct *p, void *cookie)
{
EXPECT_EQ(cookie, reinterpret_cast<void *>(57));
const_cast<ForEachTestStruct *>(p)->count++;
}
/**
* Simple test for #RAMCloud::HashTable::forEach(), ensuring that it
* properly traverses multiple buckets and chained cachelines.
*/
TEST_F(HashTableTest, forEach) {
HashTable<ForEachTestStruct*> ht(2);
ForEachTestStruct checkoff[256];
memset(checkoff, 0, sizeof(checkoff));
for (uint32_t i = 0; i < arrayLength(checkoff); i++) {
checkoff[i]._key1 = 0;
checkoff[i]._key2 = i;
ht.replace(&checkoff[i]);
}
uint64_t t = ht.forEach(test_forEach_callback,
reinterpret_cast<void *>(57));
EXPECT_EQ(arrayLength(checkoff), t);
for (uint32_t i = 0; i < arrayLength(checkoff); i++)
EXPECT_EQ(1U, checkoff[i].count);
}
} // namespace RAMCloud
| 31.54717 | 79 | 0.643495 | [
"object"
] |
17ccb23e96cdc4dfa820b4c59f425444e8588269 | 14,853 | hpp | C++ | base_view.hpp | EDAII/Lista3_LucasMaciel_2019.1 | 9ea8b268bc08913bd88a9bb1588a3dfff8f6e6d9 | [
"MIT"
] | 1 | 2019-04-15T02:08:01.000Z | 2019-04-15T02:08:01.000Z | base_view.hpp | EDAII/Lista3_LucasMaciel_2019.1 | 9ea8b268bc08913bd88a9bb1588a3dfff8f6e6d9 | [
"MIT"
] | null | null | null | base_view.hpp | EDAII/Lista3_LucasMaciel_2019.1 | 9ea8b268bc08913bd88a9bb1588a3dfff8f6e6d9 | [
"MIT"
] | 1 | 2019-07-13T14:51:42.000Z | 2019-07-13T14:51:42.000Z | #ifndef COLORMAP_H
#define COLORMAP_H
#include <SFML/Graphics.hpp>
#include <SFML/Graphics/Color.hpp>
#include <cmath>
#include <string>
#include <map>
#define my_colormap (ColorMap::get_instance())
class ColorMap
{
private:
std::map<char, sf::Color> mapa;
ColorMap()
{
mapa['r'] = sf::Color::Red;
mapa['g'] = sf::Color::Green;
mapa['b'] = sf::Color::Blue;
mapa['y'] = sf::Color::Yellow;
mapa['c'] = sf::Color::Cyan;
mapa['m'] = sf::Color::Magenta;
mapa['w'] = sf::Color::White;
mapa['k'] = sf::Color::Black;
}
public:
static ColorMap *get_instance()
{
static ColorMap map;
return ↦
}
std::string color_list()
{
std::string colors;
char c[2];
c[1] = '\0';
for (const std::pair<char, sf::Color> &p : mapa)
{
c[0] = p.first;
colors.append(c);
}
return colors;
}
void set(char color, int R, int G, int B)
{
mapa[color] = sf::Color(R, G, B);
}
sf::Color get(char color)
{
auto it = mapa.find(color);
if (it == mapa.end())
return sf::Color::White;
return it->second;
}
bool exists(char color)
{
return (mapa.find(color) != mapa.end());
}
//void update(const sf::Keyboard::Key key, char *cor);
char sf2char(sf::Keyboard::Key key)
{
if (key >= sf::Keyboard::A and key <= sf::Keyboard::Z)
return key - sf::Keyboard::A + 'a';
if (key >= sf::Keyboard::Num0 and key <= sf::Keyboard::Num9)
return key - sf::Keyboard::Num0 + '0';
if (key >= sf::Keyboard::Numpad0 and key <= sf::Keyboard::Num9)
return key - sf::Keyboard::Numpad0 + '0';
return '0';
}
};
#endif // COLORMAP_H
//#############################################################################
#ifndef SFLINE_H
#define SFLINE_H
#include <SFML/Graphics.hpp>
class dsLine : public sf::Drawable
{
public:
dsLine(const sf::Vector2f &point1, const sf::Vector2f &point2,
float thickness = 1.0, sf::Color color = sf::Color::Red) : _begin(point1), _end(point2), _color(color), _thickness(thickness)
{
update_vertices();
}
sf::Vector2f get_begin()
{
return _begin;
}
sf::Vector2f get_end()
{
return _end;
}
float get_thickness()
{
return _thickness;
}
sf::Color get_color()
{
return _color;
}
void set_color(sf::Color color)
{
this->_color = color;
update_vertices();
}
void set_end(sf::Vector2f end)
{
this->_end = end;
update_vertices();
}
void set_begin(sf::Vector2f begin)
{
this->_begin = begin;
update_vertices();
}
void set_thickness(float thickness)
{
_thickness = thickness;
update_vertices();
}
void draw(sf::RenderTarget &target, sf::RenderStates states) const
{
(void)states;
target.draw(_vertices, 4, sf::Quads);
}
private:
sf::Vector2f _begin;
sf::Vector2f _end;
sf::Vertex _vertices[4];
sf::Color _color;
float _thickness;
void update_vertices()
{
sf::Vector2f direction = _end - _begin;
sf::Vector2f unitDirection = direction / std::sqrt(direction.x * direction.x + direction.y * direction.y);
sf::Vector2f unitPerpendicular(-unitDirection.y, unitDirection.x);
sf::Vector2f offset = (_thickness / 2.f) * unitPerpendicular;
_vertices[0].position = _begin + offset;
_vertices[1].position = _end + offset;
_vertices[2].position = _end - offset;
_vertices[3].position = _begin - offset;
for (int i = 0; i < 4; ++i)
_vertices[i].color = _color;
}
};
#endif // SFLINE_H
//####################################################################################
#ifndef SFTEXT_H
#define SFTEXT_H
#include <SFML/Graphics.hpp>
#include <iostream>
class sfText : public sf::Text
{
public:
sfText(sf::Vector2f pos, std::string texto, sf::Color color = sf::Color::White, int size = 16)
{
this->setFont(*this->get_default_font());
this->setFillColor(color);
this->setOutlineColor(color);
this->setPosition(pos);
this->setString(texto);
this->setCharacterSize(size);
}
private:
static sf::Font *get_default_font()
{
const std::string _path = "font.ttf";
static sf::Font font;
static bool init = true;
if (init)
{
init = false;
if (!font.loadFromFile(_path))
std::cerr << "Font " << _path << " nao encontrada." << std::endl;
}
return &font;
}
};
#endif // SFTEXT_H
#ifndef MYWINDOW_H
#define MYWINDOW_H
#include <vector>
#include <SFML/Graphics.hpp>
class MyWindow : public sf::RenderWindow
{
private:
static const int altura = 600;
static const int largura = 800;
public:
MyWindow() : sf::RenderWindow(sf::VideoMode(largura, altura), "QXCODE ED")
{
this->setFramerateLimit(30);
}
void processar_close_resize(const sf::Event &evt)
{
if (evt.type == sf::Event::Closed)
this->close();
if (evt.type == sf::Event::Resized)
this->setView(sf::View(sf::FloatRect(0, 0, evt.size.width, evt.size.height)));
}
};
#endif // MYWINDOW_H
//################################################################################
#ifndef MBUFFER_H
#define MBUFFER_H
#include <list>
#include <iostream>
using namespace std;
template <typename T>
class MBuffer
{
private:
uint _indice;
uint _first;
uint _max_size; //maximo a frente ou atras
int _count_swap;
string _name_method;
typename std::list<T>::iterator _it;
std::list<T> _list;
public:
MBuffer(uint max_size, T first, string name_method = "")
{
//inserindo uma funcao vazia que nao faz nada so pra inicializar
//os indices e o vetor
_list.push_back(first);
_it = _list.begin();
_indice = 0;
_first = 0;
_max_size = max_size;
_count_swap = 0;
_name_method = name_method;
}
void set_max_size(uint size)
{
_max_size = size;
}
bool exists(uint indice)
{
if (indice >= _first)
if (indice < _first + _list.size())
return true;
return false;
}
bool go_to(uint indice)
{
if (exists(indice))
{
if (indice > pos_actual())
{
go_foward(indice - pos_actual());
}
if (indice < pos_actual())
{
go_back(pos_actual() - indice);
return true;
}
return true;
}
return false;
}
void push(const T &t)
{
_list.push_back(t);
if (size() > (int)_max_size)
{
_list.pop_front();
_first++;
if (_indice > 0)
_indice--;
else
_indice = 0;
}
}
bool is_full()
{
return _list.size() >= _max_size;
}
int size()
{
return _list.size();
}
const T &get_it()
{
return *_it;
}
// uint pos_first(){
// return _first;
// }
uint pos_actual()
{
return _first + _indice;
}
int get_count_swap()
{
return _count_swap;
}
string get_name_method()
{
return _name_method;
}
uint pos_last()
{
return _first + _list.size() - 1;
}
//se nao conseguiu andar pra frente eh porque nao conseguiu dar todos
//os passos por falta de estados
bool go_foward(uint steps, int count_swap = 0)
{
if (_indice + steps < _list.size())
{
_indice += steps;
if (count_swap != 0)
_count_swap = count_swap;
std::advance(_it, steps);
return true;
}
return false;
}
void go_last()
{
_indice = _list.size() - 1;
_it = std::prev(_list.end());
}
bool go_back(uint steps)
{
if (_indice >= steps)
{
_indice -= steps;
while (steps--)
_it = std::prev(_it);
return true;
}
return false;
}
void go_first()
{
_indice = 0;
_it = _list.begin();
}
};
#endif // MBUFFER_H
//#####################################################################
#ifndef MPLAYER_H
#define MPLAYER_H
#include <iostream>
#include <string>
#include <cmath>
#include <list>
#include <queue>
#include <array>
#include <SFML/Graphics.hpp>
using namespace std;
using namespace sf;
// #define my_player (MPlayer::get_instance())
class MPlayer
{
private:
sf::Clock _clock;
MBuffer<sf::Texture> _buffer;
ColorMap *cmap = ColorMap::get_instance();
bool _return_to_main{false};
bool _finished{false};
int _destiny{0}; //proximo estado a ser mostrado
MyWindow *_mywindow;
vector<string> _texts_colors;
string _colors;
public:
sf::Color color_back{sf::Color::Black};
sf::Color color_front{sf::Color::White};
const uint offset_up = 40;
bool autoplay{false};
int jump{1}; //define o tamanho do salto
MPlayer(MyWindow *mywindow,
string name_method = (char *)"",
vector<string> texts_colors = {},
string colors = "") : _buffer(100, sf::Texture(), name_method)
{
_colors = colors;
_texts_colors = texts_colors;
_mywindow = mywindow;
}
//Espera a janela ser fechada
//se estava esperando um salto de varios estados,
//volta a mostrar o estado atual
virtual void wait()
{
_finished = true;
show();
}
//Altera o tamanho do buffer
virtual void set_buffer_size(uint size)
{
_buffer.set_max_size(size);
}
//Funcao utilizada pelo pintor para salvar os estado
virtual void _push(const sf::Texture &texture, int count_swap = 0)
{
if (_mywindow->isOpen())
{
_buffer.push(texture);
_buffer.go_foward(1, count_swap);
show();
}
}
virtual void show()
{
if (!_finished)
{
if (!_buffer.go_to(_destiny))
return;
}
else
{
if (_destiny > (int)_buffer.pos_last())
{
_destiny = _buffer.pos_last();
_buffer.go_last();
autoplay = false;
}
}
_return_to_main = false;
while (_mywindow->isOpen())
{
if (!_finished)
if (_return_to_main)
return;
if (autoplay)
walk(jump);
process_input();
_mywindow->clear(color_back);
auto sprite = sf::Sprite(_buffer.get_it());
auto wsize = _mywindow->getSize();
auto ssizex = sprite.getLocalBounds().width;
auto ssizey = sprite.getLocalBounds().height;
sprite.setScale(sf::Vector2f(wsize.x / (float)ssizex, wsize.y / (float)ssizey));
_mywindow->draw(sprite);
print_label();
_mywindow->display();
}
}
private:
//processa a entrada do usuario
void process_input()
{
sf::Event evt;
while (_mywindow->pollEvent(evt))
{
_mywindow->processar_close_resize(evt);
if (evt.type == sf::Event::KeyPressed)
{
if (evt.key.code == sf::Keyboard::Right)
{
walk(jump);
}
else if (evt.key.code == sf::Keyboard::Left)
{
walk(-jump);
}
else if (evt.key.code == sf::Keyboard::Return)
{
autoplay = !autoplay;
}
else if (evt.key.code == sf::Keyboard::Up)
{
jump *= 2;
}
else if (evt.key.code == sf::Keyboard::Down)
{
if (jump > 1)
jump /= 2;
}
}
}
}
//mostra os comandos na parte superior da tela
void print_label()
{
std::string title_left = " Jump|Swaps|Atual ";
char estado[200];
sprintf(estado, "%4d |%4d |%4d ",
jump, _buffer.get_count_swap(), _buffer.pos_actual());
_mywindow->draw(sfText(sf::Vector2f(0, 0), title_left, color_front));
std::string state;
state = estado;
if (_finished)
state += "(Finalizado!)";
else
state += "(Processando)";
_mywindow->draw(sfText(sf::Vector2f(0, 20), state, color_front));
std::string title_right = " Step Move | Speed | Autoplay";
std::string teclas = " Left/Right | Up/Down | Enter ";
std::string autoOp = " ###";
auto dim = _mywindow->getSize();
float width = sfText(sf::Vector2f(0, 0), title_right).getLocalBounds().width;
_mywindow->draw(sfText(sf::Vector2f(dim.x - width - 10, 0), title_right, color_front));
_mywindow->draw(sfText(sf::Vector2f(dim.x - width - 10, 15), teclas, color_front));
sf::Color colorAuto = sf::Color::Red;
if (autoplay)
colorAuto = sf::Color::Green;
_mywindow->draw(sfText(sf::Vector2f(dim.x - width - 10, 15), autoOp, colorAuto));
_mywindow->draw(dsLine(sf::Vector2f(0, 40), sf::Vector2f(dim.x, 40), 1, color_front));
// nome do metodo
_mywindow->draw(sfText(sf::Vector2f(0, 50), _buffer.get_name_method(), color_front));
// glossario de cores
for (int k = 0; k < _texts_colors.size(); k++)
_mywindow->draw(sfText(sf::Vector2f(k * 120, 65), _texts_colors[k], cmap->get(_colors[k])));
}
//anda nos estados para frente e para trás chamando métodos do buffer
void walk(int step)
{
int atual = _buffer.pos_actual();
_destiny = atual + step;
if (_destiny > (int)_buffer.pos_last())
if (_finished)
_destiny = _buffer.pos_last();
if (step > 0)
{
if (!_buffer.go_to(_destiny))
{
_return_to_main = true;
return;
}
}
else
{
if (!_buffer.go_to(_destiny))
{
_buffer.go_first();
}
}
}
};
#endif //MPLAYER_H | 23.879421 | 136 | 0.512758 | [
"vector"
] |
17e3fe0f1dedccdee2133b5d2d55746f449f76ba | 14,047 | hpp | C++ | include/hipipe/core/utility/tuple.hpp | iterait/hipipe | c2a6cc13857dce93e5ae3f76a86e8f029ca3f921 | [
"BSL-1.0",
"MIT"
] | 16 | 2018-10-08T09:00:14.000Z | 2021-07-11T12:35:09.000Z | include/hipipe/core/utility/tuple.hpp | iterait/hipipe | c2a6cc13857dce93e5ae3f76a86e8f029ca3f921 | [
"BSL-1.0",
"MIT"
] | 19 | 2018-09-26T13:55:40.000Z | 2019-08-28T13:47:04.000Z | include/hipipe/core/utility/tuple.hpp | iterait/hipipe | c2a6cc13857dce93e5ae3f76a86e8f029ca3f921 | [
"BSL-1.0",
"MIT"
] | null | null | null | /****************************************************************************
* hipipe library
* Copyright (c) 2017, Cognexa Solutions s.r.o.
* Copyright (c) 2018, Iterait a.s.
* Author(s) Filip Matzner
*
* This file is distributed under the MIT License.
* See the accompanying file LICENSE.txt for the complete license agreement.
****************************************************************************/
/// \defgroup Tuple Tuple and variadic template utilites.
#ifndef HIPIPE_CORE_TUPLE_UTILS_HPP
#define HIPIPE_CORE_TUPLE_UTILS_HPP
#include <range/v3/core.hpp>
#include <range/v3/range/conversion.hpp>
#include <range/v3/range/primitives.hpp>
#include <experimental/tuple>
#include <ostream>
#include <type_traits>
#include <vector>
namespace hipipe::utility {
namespace rg = ranges;
/// \ingroup Tuple
/// \brief Get the first index of a type in a variadic template list
///
/// The first template argument is the argument to be searched.
/// The rest of the arguments is the variadic template.
///
/// Example:
/// \code
/// variadic_find<int, int, double, double>::value == 0
/// variadic_find<double, int, double, double>::value == 1
/// variadic_find<float, int, double, float>::value == 2
/// \endcode
template<typename T1, typename T2, typename... Ts>
struct variadic_find : std::integral_constant<std::size_t, variadic_find<T1, Ts...>{}+1> {
};
template<typename T, typename... Ts>
struct variadic_find<T, T, Ts...> : std::integral_constant<std::size_t, 0> {
};
/// \ingroup Tuple
/// \brief Wrap variadic template pack in a tuple if there is more than one type.
///
/// Example:
/// \code
/// static_assert(std::is_same_v<maybe_tuple<int, double>, std::tuple<int, double>>);
/// static_assert(std::is_same_v<maybe_tuple<int>, int>);
/// static_assert(std::is_same_v<maybe_tuple<>, std::tuple<>>);
/// \endcode
template<std::size_t N, typename... Ts>
struct maybe_tuple_impl {
using type = std::tuple<Ts...>;
};
template<typename T>
struct maybe_tuple_impl<1, T> {
using type = T;
};
template<typename... Ts>
using maybe_tuple = typename maybe_tuple_impl<sizeof...(Ts), Ts...>::type;
/// \ingroup Tuple
/// \brief Add a number to all values in std::index_sequence.
///
/// Example:
/// \code
/// std::is_same<decltype(plus<2>(std::index_sequence<1, 3, 4>{})),
/// std::index_sequence<3, 5, 6>>;
/// \endcode
template<std::size_t Value, std::size_t... Is>
constexpr std::index_sequence<(Value + Is)...> plus(std::index_sequence<Is...>)
{
return {};
}
/// \ingroup Tuple
/// \brief Make std::index_sequence with the given offset.
///
/// Example:
/// \code
/// std::is_same<decltype(make_offset_index_sequence<3, 4>()),
/// std::index_sequence<3, 4, 5, 6>>;
/// \endcode
template <std::size_t Offset, std::size_t N>
using make_offset_index_sequence = decltype(plus<Offset>(std::make_index_sequence<N>{}));
// tuple_for_each //
namespace detail {
template<typename Fun, typename Tuple, std::size_t... Is>
constexpr Fun tuple_for_each_impl(Tuple&& tuple, Fun&& fun, std::index_sequence<Is...>)
{
(..., (std::invoke(fun, std::get<Is>(std::forward<Tuple>(tuple)))));
return fun;
}
} // namespace detail
/// \ingroup Tuple
/// \brief Apply a function on each element of a tuple.
///
/// The order of application is from the first to the last element.
///
/// Example:
/// \code
/// auto tpl = std::make_tuple(5, 2.);
/// tuple_for_each(tpl, [](auto& val) { std::cout << val << '\n'; });
/// \endcode
///
/// \returns The function after application.
template<typename Tuple, typename Fun>
constexpr auto tuple_for_each(Tuple&& tuple, Fun&& fun)
{
constexpr std::size_t tuple_size = std::tuple_size<std::decay_t<Tuple>>::value;
return detail::tuple_for_each_impl(std::forward<Tuple>(tuple),
std::forward<Fun>(fun),
std::make_index_sequence<tuple_size>{});
}
// tuple_transform //
namespace detail {
template<typename Tuple, typename Fun, std::size_t... Is>
constexpr auto tuple_transform_impl(Tuple&& tuple, Fun&& fun, std::index_sequence<Is...>)
{
return std::make_tuple(std::invoke(fun, std::get<Is>(std::forward<Tuple>(tuple)))...);
}
} // end namespace detail
/// \ingroup Tuple
/// \brief Transform each element of a tuple.
///
/// The order of application is unspecified.
///
/// Example:
/// \code
/// auto t1 = std::make_tuple(0, 10L, 5.);
/// auto t2 = tuple_transform(t1, [](const auto &v) { return v + 1; });
/// static_assert(std::is_same<std::tuple<int, long, double>, decltype(t2)>{});
/// assert(t2 == std::make_tuple(0 + 1, 10L + 1, 5. + 1));
/// \endcode
///
/// \returns The transformed tuple.
template<typename Tuple, typename Fun>
constexpr auto tuple_transform(Tuple&& tuple, Fun&& fun)
{
constexpr std::size_t tuple_size = std::tuple_size<std::decay_t<Tuple>>::value;
return detail::tuple_transform_impl(std::forward<Tuple>(tuple),
std::forward<Fun>(fun),
std::make_index_sequence<tuple_size>{});
}
/// \ingroup Tuple
/// \brief Check whether a tuple contains a given type.
template<typename T, typename Tuple = void>
struct tuple_contains;
template<typename T, typename... Types>
struct tuple_contains<T, std::tuple<Types...>>
: std::disjunction<std::is_same<std::decay_t<T>, std::decay_t<Types>>...> {
};
/// \ingroup Tuple
/// \brief Tuple pretty printing to std::ostream.
template<typename Tuple, size_t... Is>
std::ostream& tuple_print(std::ostream& out, const Tuple& tuple, std::index_sequence<Is...>)
{
out << "(";
(..., (out << (Is == 0 ? "" : ", ") << std::get<Is>(tuple)));
out << ")";
return out;
}
/// \ingroup Tuple
/// \brief Tuple pretty printing to std::ostream.
template<typename... Ts>
std::ostream& operator<<(std::ostream& out, const std::tuple<Ts...>& tuple)
{
return utility::tuple_print(out, tuple, std::make_index_sequence<sizeof...(Ts)>{});
}
// unzip //
namespace detail {
// wrap each type of a tuple in std::vector, i.e., make a tuple of empty vectors
template<typename Tuple, std::size_t... Is>
auto vectorize_tuple(std::index_sequence<Is...>)
{
return std::make_tuple(std::vector<std::tuple_element_t<Is, std::decay_t<Tuple>>>()...);
}
// push elements from the given tuple to the corresponding vectors in a tuple of vectors
template<typename ToR, typename Tuple, std::size_t... Is>
void push_unzipped(ToR& tuple_of_ranges, Tuple&& tuple, std::index_sequence<Is...>)
{
(..., (std::get<Is>(tuple_of_ranges).push_back(std::get<Is>(std::forward<Tuple>(tuple)))));
}
// if the size of the given range is known, return it, otherwise return 0
CPP_template(class Rng)(requires rg::sized_range<Rng>)
std::size_t safe_reserve_size(Rng&& rng)
{
return rg::size(rng);
}
CPP_template(class Rng)(requires (!rg::sized_range<Rng>))
std::size_t safe_reserve_size(Rng&& rng)
{
return 0;
}
template<typename Rng>
auto unzip_impl(Rng& range_of_tuples)
{
using tuple_type = rg::range_value_t<Rng>;
constexpr auto tuple_size = std::tuple_size<tuple_type>{};
constexpr auto indices = std::make_index_sequence<tuple_size>{};
std::size_t reserve_size = detail::safe_reserve_size(range_of_tuples);
auto tuple_of_ranges = detail::vectorize_tuple<tuple_type>(indices);
utility::tuple_for_each(
tuple_of_ranges, [reserve_size](auto& rng) { rng.reserve(reserve_size); });
for (auto& v : range_of_tuples) {
detail::push_unzipped(tuple_of_ranges, std::move(v), indices);
}
return tuple_of_ranges;
}
} // namespace detail
/// \ingroup Tuple
/// \brief Unzips a range of tuples to a tuple of std::vectors.
///
/// Example:
/// \code
/// std::vector<std::tuple<int, double>> data{};
/// data.emplace_back(1, 5.);
/// data.emplace_back(2, 6.);
/// data.emplace_back(3, 7.);
///
/// std::vector<int> va;
/// std::vector<double> vb;
/// std::tie(va, vb) = unzip(data);
/// \endcode
CPP_template(class Rng)(requires rg::range<Rng> && (!rg::view_<Rng>))
auto unzip(Rng range_of_tuples)
{
// copy the given container and move elements out of it
return detail::unzip_impl(range_of_tuples);
}
/// Specialization of unzip function for views.
CPP_template(class Rng)(requires rg::view_<Rng>)
auto unzip(Rng view_of_tuples)
{
return utility::unzip(rg::to_vector(view_of_tuples));
}
// maybe unzip //
namespace detail {
template<bool Enable>
struct unzip_if_impl
{
template<typename Rng>
static decltype(auto) impl(Rng&& rng)
{
return utility::unzip(std::forward<Rng>(rng));
}
};
template<>
struct unzip_if_impl<false>
{
template<typename Rng>
static Rng&& impl(Rng&& rng)
{
return std::forward<Rng>(rng);
}
};
} // namespace detail
/// \ingroup Tuple
/// \brief Unzips a range of tuples to a tuple of ranges if a constexpr condition holds.
///
/// This method is enabled or disabled by its first template parameter.
/// If disabled, it returns identity. If enabled, it returns the same
/// thing as unzip() would return.
///
/// Example:
/// \code
/// std::vector<std::tuple<int, double>> data{};
/// data.emplace_back(1, 5.);
/// data.emplace_back(2, 6.);
/// data.emplace_back(3, 7.);
///
/// std::vector<int> va;
/// std::vector<double> vb;
/// std::tie(va, vb) = unzip_if<true>(data);
///
/// std::vector<int> vc = unzip_if<false>(va);
/// \endcode
template<bool Enable, typename RangeT>
decltype(auto) unzip_if(RangeT&& range)
{
return detail::unzip_if_impl<Enable>::impl(std::forward<RangeT>(range));
}
// maybe untuple //
namespace detail {
template<std::size_t Size>
struct maybe_untuple_impl
{
template<typename Tuple>
static Tuple&& impl(Tuple&& tuple)
{
return std::forward<Tuple>(tuple);
}
};
template<>
struct maybe_untuple_impl<1>
{
template<typename Tuple>
static decltype(auto) impl(Tuple&& tuple)
{
return std::get<0>(std::forward<Tuple>(tuple));
}
};
} // namespace detail
/// \ingroup Tuple
/// \brief Extract a value from a tuple if the tuple contains only a single value.
///
/// If the tuple contains zero or more than one element, this is an identity.
///
/// Example:
/// \code
/// std::tuple<int, double> t1{1, 3.};
/// auto t2 = maybe_untuple(t1);
/// static_assert(std::is_same_v<decltype(t2), std::tuple<int, double>>);
///
/// std::tuple<int> t3{1};
/// auto t4 = maybe_untuple(t3);
/// static_assert(std::is_same_v<decltype(t4), int>);
///
/// int i = 1;
/// std::tuple<int&> t5{i};
/// auto& t6 = maybe_untuple(t5);
/// static_assert(std::is_same_v<decltype(t6), int&>);
/// t6 = 2;
/// BOOST_TEST(i == 2);
/// \endcode
template<typename Tuple>
decltype(auto) maybe_untuple(Tuple&& tuple)
{
constexpr std::size_t tuple_size = std::tuple_size<std::decay_t<Tuple>>::value;
return detail::maybe_untuple_impl<tuple_size>::impl(std::forward<Tuple>(tuple));
}
// times with index //
namespace detail {
template<typename Fun, std::size_t... Is>
constexpr Fun times_with_index_impl(Fun&& fun, std::index_sequence<Is...>)
{
(..., (std::invoke(fun, std::integral_constant<std::size_t, Is>{})));
return fun;
}
} // namespace detail
/// \ingroup Tuple
/// \brief Repeat a function N times in compile time.
///
/// Example:
/// \code
/// auto tpl = std::make_tuple(1, 0.25, 'a');
///
/// times_with_index<3>([&tpl](auto index) {
/// ++std::get<index>(tpl);
/// });
/// assert(tpl == std::make_tuple(2, 1.25, 'b'));
/// \endcode
template<std::size_t N, typename Fun>
constexpr Fun times_with_index(Fun&& fun)
{
return detail::times_with_index_impl(std::forward<Fun>(fun), std::make_index_sequence<N>{});
}
/// \ingroup Tuple
/// \brief Similar to tuple_for_each(), but with index available.
///
/// Example:
/// \code
/// auto tpl = std::make_tuple(1, 2.);
///
/// tuple_for_each_with_index(tpl, [](auto& val, auto index) {
/// val += index;
/// });
///
/// assert(tpl == std::make_tuple(1, 3.));
/// \endcode
template <typename Tuple, typename Fun>
constexpr auto tuple_for_each_with_index(Tuple&& tuple, Fun&& fun)
{
return utility::times_with_index<std::tuple_size<std::decay_t<Tuple>>{}>(
[&fun, &tuple](auto index) {
std::invoke(fun, std::get<index>(tuple), index);
});
}
// transform with index //
namespace detail {
template <typename Fun, typename Tuple, std::size_t... Is>
constexpr auto tuple_transform_with_index_impl(Tuple&& tuple, Fun&& fun,
std::index_sequence<Is...>)
{
return std::make_tuple(std::invoke(fun, std::get<Is>(std::forward<Tuple>(tuple)),
std::integral_constant<std::size_t, Is>{})...);
}
} // namespace detail
/// \ingroup Tuple
/// \brief Similar to tuple_transform(), but with index available.
///
/// Example:
/// \code
/// auto tpl = std::make_tuple(1, 0.25, 'a');
///
/// auto tpl2 = tuple_transform_with_index(tpl, [](auto&& elem, auto index) {
/// return elem + index;
/// });
///
/// assert(tpl2 == std::make_tuple(1, 1.25, 'c'));
/// \endcode
template <typename Tuple, typename Fun>
constexpr auto tuple_transform_with_index(Tuple&& tuple, Fun&& fun)
{
return detail::tuple_transform_with_index_impl(
std::forward<Tuple>(tuple), std::forward<Fun>(fun),
std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>{}>{});
}
} // namespace hipipe::utility
#endif
| 29.887234 | 99 | 0.618637 | [
"vector",
"transform"
] |
17e5c0ef95366ed58fcccc80c0a0819edbfbd5d6 | 882 | cpp | C++ | atcoder/abc084/C/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 8 | 2020-12-23T07:54:53.000Z | 2021-11-23T02:46:35.000Z | atcoder/abc084/C/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2020-11-07T13:22:29.000Z | 2020-12-20T12:54:00.000Z | atcoder/abc084/C/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2021-01-16T03:40:10.000Z | 2021-01-16T03:40:10.000Z | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
int N;
vector<int> C, S, F;
vector<ll> solve() {
vector<ll> ans(N, 0);
for (int i = 0; i < N; ++i) {
ll t = 0;
for (int j = i; j < N - 1; ++j) {
if (t < S[j]) {
t = S[j];
t += C[j];
} else {
ll r = (F[j] - (t - S[j]) % F[j]) % F[j];
t += r;
t += C[j];
}
}
ans[i] = t;
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> N;
C.assign(N - 1, 0);
S.assign(N - 1, 0);
F.assign(N - 1, 0);
for (int i = 0; i < N - 1; ++i) {
cin >> C[i] >> S[i] >> F[i];
}
auto ans = solve();
for (int i = 0; i < N; ++i) {
cout << ans[i] << endl;
}
return 0;
} | 18.765957 | 57 | 0.351474 | [
"vector"
] |
17e6a19cbd93617cf2acbd47f50cf7d4514f704d | 5,667 | hpp | C++ | SU2-Quantum/Common/include/toolboxes/geometry_toolbox.hpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | null | null | null | SU2-Quantum/Common/include/toolboxes/geometry_toolbox.hpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | null | null | null | SU2-Quantum/Common/include/toolboxes/geometry_toolbox.hpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | 1 | 2021-12-03T06:40:08.000Z | 2021-12-03T06:40:08.000Z | /*!
* \file geometry_toolbox.hpp
* \brief Collection of common lightweight geometry-oriented methods.
* \version 7.0.6 "Blackbird"
*
* SU2 Project Website: https://su2code.github.io
*
* The SU2 Project is maintained by the SU2 Foundation
* (http://su2foundation.org)
*
* Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md)
*
* SU2 is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* SU2 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with SU2. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
namespace GeometryToolbox {
/*! \return ||a-b||^2 */
template<class T, typename Int>
inline T SquaredDistance(Int nDim, const T* a, const T* b) {
T d(0);
for(Int i = 0; i < nDim; i++) d += pow(a[i]-b[i], 2);
return d;
}
/*! \return ||a-b|| */
template<class T, typename Int>
inline T Distance(Int nDim, const T* a, const T* b) {
return sqrt(SquaredDistance(nDim, a, b));
}
/*! \brief d = a-b */
template<class T, typename Int>
inline void Distance(Int nDim, const T* a, const T* b, T* d) {
for(Int i = 0; i < nDim; i++) d[i] = a[i] - b[i];
}
/*! \return a.b */
template<class T, typename Int>
inline T DotProduct(Int nDim, const T* a, const T* b) {
T d(0);
for (Int i = 0; i < nDim; ++i) d += a[i]*b[i];
return d;
}
/*! \return ||a||^2 */
template<class T, typename Int>
inline T SquaredNorm(Int nDim, const T* a) {
return DotProduct(nDim, a, a);
}
/*! \return ||a|| */
template<class T, typename Int>
inline T Norm(Int nDim, const T* a) {
return sqrt(SquaredNorm(nDim, a));
}
/*! \brief c = a x b */
template<class T>
inline void CrossProduct(const T* a, const T* b, T* c) {
c[0] = a[1]*b[2] - a[2]*b[1];
c[1] = a[2]*b[0] - a[0]*b[2];
c[2] = a[0]*b[1] - a[1]*b[0];
}
/*!
* \brief Compute the coordinate (c) where the line defined by coordinate l0 and
* direction d intersects the plane defined by point p0 and normal n.
* \return The intersection distance.
*/
template<class T, int nDim>
inline T LinePlaneIntersection(const T* l0, const T* d, const T* p0, const T* n, T* c) {
T dist[nDim] = {0.0};
Distance(nDim, p0, l0, dist);
T alpha = DotProduct(nDim, dist, n) / DotProduct(nDim, d, n);
for (int iDim = 0; iDim < nDim; ++iDim)
c[iDim] = l0[iDim] + alpha * d[iDim];
return fabs(alpha) * Norm(nDim,d);
}
/*!
* \brief Compute the coordinate (c) where point p1 intersects the plane defined
* by point p0 and normal n if projected perpendicular to it.
* \return The normal distance.
*/
template<class T, int nDim>
inline T PointPlaneProjection(const T* p1, const T* p0, const T* n, T* c) {
return LinePlaneIntersection<T,nDim>(p1, n, p0, n, c);
}
/*! \brief Set U as the normal to a 2D line defined by coords[iPoint][iDim]. */
template<class T, class U>
inline void LineNormal(const T& coords, U* normal) {
normal[0] = coords[0][1] - coords[1][1];
normal[1] = coords[1][0] - coords[0][0];
}
/*! \brief Normal vector of a triangle, cross product of two sides. */
template<class T, class U>
inline void TriangleNormal(const T& coords, U* normal) {
U a[3], b[3];
for (int iDim = 0; iDim < 3; iDim++) {
a[iDim] = coords[1][iDim] - coords[0][iDim];
b[iDim] = coords[2][iDim] - coords[0][iDim];
}
CrossProduct(a, b, normal);
normal[0] *= 0.5; normal[1] *= 0.5; normal[2] *= 0.5;
}
/*! \brief Normal vector of a quadrilateral, cross product of the two diagonals. */
template<class T, class U>
inline void QuadrilateralNormal(const T& coords, U* normal) {
U a[3], b[3];
for (int iDim = 0; iDim < 3; iDim++) {
a[iDim] = coords[2][iDim] - coords[0][iDim];
b[iDim] = coords[3][iDim] - coords[1][iDim];
}
CrossProduct(a, b, normal);
normal[0] *= 0.5; normal[1] *= 0.5; normal[2] *= 0.5;
}
/*!
* \brief Compute a 3D rotation matrix.
* \note The implicit ordering is rotation about the x, y, and then z axis.
*/
template<class Scalar, class Matrix>
inline void RotationMatrix(Scalar theta, Scalar phi, Scalar psi, Matrix& mat) {
Scalar cosTheta = cos(theta); Scalar cosPhi = cos(phi); Scalar cosPsi = cos(psi);
Scalar sinTheta = sin(theta); Scalar sinPhi = sin(phi); Scalar sinPsi = sin(psi);
mat[0][0] = cosPhi*cosPsi;
mat[1][0] = cosPhi*sinPsi;
mat[2][0] = -sinPhi;
mat[0][1] = sinTheta*sinPhi*cosPsi - cosTheta*sinPsi;
mat[1][1] = sinTheta*sinPhi*sinPsi + cosTheta*cosPsi;
mat[2][1] = sinTheta*cosPhi;
mat[0][2] = cosTheta*sinPhi*cosPsi + sinTheta*sinPsi;
mat[1][2] = cosTheta*sinPhi*sinPsi - sinTheta*cosPsi;
mat[2][2] = cosTheta*cosPhi;
}
/*! \brief Compute a 2D rotation matrix. */
template<class Scalar, class Matrix>
inline void RotationMatrix(Scalar psi, Matrix& mat) {
Scalar cosPsi = cos(psi);
Scalar sinPsi = sin(psi);
mat[0][0] = cosPsi; mat[0][1] =-sinPsi;
mat[1][0] = sinPsi; mat[1][1] = cosPsi;
}
/*! \brief Apply a rotation matrix (R) about origin (O) to a point at
* distance (d) from it to obtain new coordinate (c). */
template<class Scalar, int nDim>
inline void Rotate(const Scalar R[][nDim], const Scalar* O, const Scalar* d, Scalar* c) {
for (int iDim = 0; iDim < nDim; ++iDim) {
c[iDim] = O[iDim];
for (int k = 0; k < nDim; ++k) c[iDim] += R[iDim][k] * d[k];
}
}
}
| 30.304813 | 89 | 0.64108 | [
"geometry",
"vector",
"3d"
] |
17f14caabaabbedd63425dcf99ab2f5d7093c451 | 9,955 | cpp | C++ | src/openms/source/CHEMISTRY/EnzymaticDigestion.cpp | mrurik/OpenMS | 3bf48247423dc28a7df7b12b72fbc7751965c321 | [
"Zlib",
"Apache-2.0"
] | 1 | 2018-03-06T14:12:09.000Z | 2018-03-06T14:12:09.000Z | src/openms/source/CHEMISTRY/EnzymaticDigestion.cpp | mrurik/OpenMS | 3bf48247423dc28a7df7b12b72fbc7751965c321 | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/openms/source/CHEMISTRY/EnzymaticDigestion.cpp | mrurik/OpenMS | 3bf48247423dc28a7df7b12b72fbc7751965c321 | [
"Zlib",
"Apache-2.0"
] | null | null | null | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2016.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow, Xiao Liang $
// $Authors: Marc Sturm, Chris Bielow$
// --------------------------------------------------------------------------
#include <OpenMS/CHEMISTRY/EnzymaticDigestion.h>
#include <OpenMS/CHEMISTRY/EnzymesDB.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <boost/regex.hpp>
#include <iostream>
using namespace std;
namespace OpenMS
{
const std::string EnzymaticDigestion::NamesOfSpecificity[] = {"full", "semi", "none"};
EnzymaticDigestion::EnzymaticDigestion() :
missed_cleavages_(0),
enzyme_(*EnzymesDB::getInstance()->getEnzyme("Trypsin")),
specificity_(SPEC_FULL)
{
}
EnzymaticDigestion::EnzymaticDigestion(const EnzymaticDigestion& rhs) :
missed_cleavages_(rhs.missed_cleavages_),
enzyme_(rhs.enzyme_),
specificity_(rhs.specificity_)
{
}
/// Assignment operator
EnzymaticDigestion& EnzymaticDigestion::operator=(const EnzymaticDigestion& rhs)
{
if (this != &rhs)
{
missed_cleavages_ = rhs.missed_cleavages_;
enzyme_ = rhs.enzyme_;
specificity_ = rhs.specificity_;
}
return *this;
}
Size EnzymaticDigestion::getMissedCleavages() const
{
return missed_cleavages_;
}
void EnzymaticDigestion::setMissedCleavages(Size missed_cleavages)
{
missed_cleavages_ = missed_cleavages;
}
void EnzymaticDigestion::setEnzyme(const String enzyme_name)
{
enzyme_ = *EnzymesDB::getInstance()->getEnzyme(enzyme_name);
}
String EnzymaticDigestion::getEnzymeName() const
{
return enzyme_.getName();
}
EnzymaticDigestion::Specificity EnzymaticDigestion::getSpecificityByName(const String& name)
{
for (Size i = 0; i < SIZE_OF_SPECIFICITY; ++i)
{
if (name == NamesOfSpecificity[i]) return Specificity(i);
}
return SIZE_OF_SPECIFICITY;
}
EnzymaticDigestion::Specificity EnzymaticDigestion::getSpecificity() const
{
return specificity_;
}
void EnzymaticDigestion::setSpecificity(Specificity spec)
{
specificity_ = spec;
}
std::vector<Size> EnzymaticDigestion::tokenize_(const String& s) const
{
std::vector<Size> pep_positions;
Size pos = 0;
boost::regex re(enzyme_.getRegEx());
if (enzyme_.getRegEx() != "()") // if it's not "no cleavage"
{
boost::sregex_token_iterator i(s.begin(), s.end(), re, -1);
boost::sregex_token_iterator j;
while (i != j)
{
pep_positions.push_back(pos);
pos += (i++)->length();
}
}
else
{
pep_positions.push_back(pos);
}
return pep_positions;
}
bool EnzymaticDigestion::isValidProduct(const AASequence& protein, Size pep_pos, Size pep_length, bool methionine_cleavage)
{
if (pep_pos >= protein.size())
{
LOG_WARN << "Error: start of peptide is beyond end of protein!" << endl;
return false;
}
else if (pep_pos + pep_length > protein.size())
{
LOG_WARN << "Error: end of peptide is beyond end of protein!" << endl;
return false;
}
else if (pep_length == 0 || protein.size() == 0)
{
LOG_WARN << "Error: peptide or protein must not be empty!" << endl;
return false;
}
if (specificity_ == SPEC_NONE)
{
return true; // we don't care about terminal ends
}
else // either SPEC_SEMI or SPEC_FULL
{
bool spec_c = false, spec_n = false;
std::vector<Size> pep_positions = tokenize_(protein.toUnmodifiedString());
// test each end
if (pep_pos == 0 ||
std::find(pep_positions.begin(), pep_positions.end(), pep_pos) != pep_positions.end())
{
spec_n = true;
}
// if allow methionine cleavage at the protein start position
if (pep_pos == 1 && methionine_cleavage && protein.getResidue((Size)0).getOneLetterCode() == "M")
{
spec_n = true;
}
if (pep_pos + pep_length == protein.size() ||
std::find(pep_positions.begin(), pep_positions.end(), pep_pos + pep_length) != pep_positions.end())
{
spec_c = true;
}
if (spec_n && spec_c)
{
return true; // if both are fine, its definitely valid
}
else if ((specificity_ == SPEC_SEMI) && (spec_n || spec_c))
{
return true; // one only for SEMI
}
else
{
return false;
}
}
}
Size EnzymaticDigestion::peptideCount(const AASequence& protein)
{
std::vector<Size> pep_positions = tokenize_(protein.toUnmodifiedString());
Size count = pep_positions.size();
// missed cleavages
Size sum = count;
for (Size i = 1; i < count; ++i)
{
if (i > missed_cleavages_) break;
sum += count - i;
}
return sum;
}
void EnzymaticDigestion::digest(const AASequence& protein, vector<AASequence>& output) const
{
// initialization
output.clear();
// naive cleavage sites
Size missed_cleavages = missed_cleavages_;
std::vector<Size> pep_positions = tokenize_(protein.toUnmodifiedString());
Size count = pep_positions.size();
Size begin = pep_positions[0];
for (Size i = 1; i < count; ++i)
{
output.push_back(protein.getSubsequence(begin, pep_positions[i] - begin));
begin = pep_positions[i];
}
output.push_back(protein.getSubsequence(begin, protein.size() - begin));
//missed cleavages
if (pep_positions.size() > 0 && missed_cleavages_ != 0) //there is at least one cleavage site!
{
//generate fragments with missed cleavages
for (Size i = 1; ((i <= missed_cleavages) && (count > i)); ++i)
{
begin = pep_positions[0];
for (Size j = 1; j < count - i; ++j)
{
output.push_back(protein.getSubsequence(begin, pep_positions[j + i] - begin));
begin = pep_positions[j];
}
output.push_back(protein.getSubsequence(begin, protein.size() - begin));
}
}
}
void EnzymaticDigestion::digestUnmodifiedString(const StringView sequence, std::vector<StringView>& output, Size min_length, Size max_length) const
{
// initialization
output.clear();
// naive cleavage sites
std::vector<Size> pep_positions = tokenize_(sequence.getString());
Size count = pep_positions.size();
// disable max length filter by setting to maximum length
if (max_length == 0)
{
max_length = sequence.size();
}
// no cleavage sites? return full string
if (count == 0)
{
if (sequence.size() >= min_length && sequence.size() <= max_length)
{
output.push_back(sequence);
}
return;
}
for (Size i = 1; i != count; ++i)
{
// add if cleavage product larger then min length
Size l = pep_positions[i] - pep_positions[i - 1];
if (l >= min_length && l <= max_length)
{
output.push_back(sequence.substr(pep_positions[i - 1], pep_positions[i] - 1));
}
}
// add last cleavage product (need to add because end is not a cleavage site) if larger then min length
Size l = sequence.size() - pep_positions[count - 1];
if (l >= min_length && l <= max_length)
{
output.push_back(sequence.substr(pep_positions[count - 1], sequence.size() - 1));
}
// generate fragments with missed cleavages
for (Size i = 1; ((i <= missed_cleavages_) && (i < count)); ++i)
{
for (Size j = 1; j < count - i; ++j)
{
Size l = pep_positions[j + i] - pep_positions[j - 1];
if (l >= min_length && l <= max_length)
{
output.push_back(sequence.substr(pep_positions[j - 1], pep_positions[j + i] - 1));
}
}
// add last cleavage product (need to add because end is not a cleavage site)
Size l = sequence.size() - pep_positions[count - i - 1];
if (l >= min_length && l <= max_length)
{
output.push_back(sequence.substr(pep_positions[count - i - 1], sequence.size() - 1 ));
}
}
}
} //namespace
| 32.42671 | 149 | 0.6222 | [
"vector"
] |
17f1c5490d0ce5c2441bc1045545ee2ab18fe411 | 480 | cpp | C++ | Array/283_Move-Zeroes.cpp | YunWGui/LeetCode | 2587eca22195ec7d9263227554467ec4010cfe05 | [
"MIT"
] | null | null | null | Array/283_Move-Zeroes.cpp | YunWGui/LeetCode | 2587eca22195ec7d9263227554467ec4010cfe05 | [
"MIT"
] | null | null | null | Array/283_Move-Zeroes.cpp | YunWGui/LeetCode | 2587eca22195ec7d9263227554467ec4010cfe05 | [
"MIT"
] | null | null | null | /*
Title:
283. Move Zeroes
283. 移动零
Address:
https://leetcode-cn.com/problems/move-zeroes/
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int idx = 0;
for ( int i = 0; i < (int)nums.size(); ++i ) {
if ( nums[i] != 0 ) {
swap( nums[i], nums[idx++] );
}
}
}
};
int main()
{
return 0;
} | 15 | 54 | 0.5 | [
"vector"
] |
17f9132162ba6e5b33d4c9620ad7385766938dfb | 1,894 | cc | C++ | sandboxed_api/proto_helper.cc | 0xgpapad/sandboxed-api | 7004d59150c9fbfaa3e5fd1872affffd1ab14fe8 | [
"Apache-2.0"
] | 1 | 2022-02-10T10:38:30.000Z | 2022-02-10T10:38:30.000Z | sandboxed_api/proto_helper.cc | 0xgpapad/sandboxed-api | 7004d59150c9fbfaa3e5fd1872affffd1ab14fe8 | [
"Apache-2.0"
] | null | null | null | sandboxed_api/proto_helper.cc | 0xgpapad/sandboxed-api | 7004d59150c9fbfaa3e5fd1872affffd1ab14fe8 | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "sandboxed_api/proto_helper.h"
#include "absl/status/status.h"
namespace sapi {
namespace internal {
absl::Status DeserializeProto(const char* data, size_t len,
google::protobuf::Message& output) {
ProtoArg envelope;
if (!envelope.ParseFromArray(data, len)) {
return absl::InternalError("Unable to parse proto from array");
}
auto pb_data = envelope.protobuf_data();
if (!output.ParseFromArray(pb_data.data(), pb_data.size())) {
return absl::InternalError("Unable to parse proto from envelope data");
}
return absl::OkStatus();
}
} // namespace internal
absl::StatusOr<std::vector<uint8_t>> SerializeProto(
const google::protobuf::Message& proto) {
// Wrap protobuf in a envelope so that we know the name of the protobuf
// structure when deserializing in the sandboxee.
ProtoArg proto_arg;
proto_arg.set_protobuf_data(proto.SerializeAsString());
proto_arg.set_full_name(proto.GetDescriptor()->full_name());
std::vector<uint8_t> serialized_proto(proto_arg.ByteSizeLong());
if (!proto_arg.SerializeToArray(serialized_proto.data(),
serialized_proto.size())) {
return absl::InternalError("Unable to serialize proto to array");
}
return serialized_proto;
}
} // namespace sapi
| 33.821429 | 75 | 0.715417 | [
"vector"
] |
aa00d2ba124870409261c166cc51c81e109285cf | 4,174 | cpp | C++ | self_driving/ImpulseEngine-fix/main.cpp | zaqwes8811/coordinator-tasks | 7f63fdf613eff5d441a3c2c7b52d2a3d02d9736a | [
"MIT"
] | null | null | null | self_driving/ImpulseEngine-fix/main.cpp | zaqwes8811/coordinator-tasks | 7f63fdf613eff5d441a3c2c7b52d2a3d02d9736a | [
"MIT"
] | 15 | 2015-03-07T12:46:41.000Z | 2015-04-11T09:08:36.000Z | self_driving/ImpulseEngine-fix/main.cpp | zaqwes8811/micro-apps | 7f63fdf613eff5d441a3c2c7b52d2a3d02d9736a | [
"MIT"
] | null | null | null | /*
Copyright (c) 2013 Randy Gaul http://RandyGaul.net
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "Precompiled.h"
#include "TrafficModelHelper.h"
#include "TrafficModel.h"
#include "ImageZoneDescription.h"
#include <iostream>
#include <mathfu/utilities.h>
#include <mathfu/matrix.h>
#include <mathfu/vector.h>
#include <mathfu/glsl_mappings.h>
#include <memory>
#include <string>
#include <sstream>
#include <iostream>
// https://google.github.io/mathfu/mathfu_guide_matrices.html#mathfu_guide_matrices_declaration
#define ESC_KEY 27
using namespace std;
using namespace mathfu;
static mat2 g_p_mat;
Clock g_clock;
bool g_frameStepping = false;
bool g_canStep = false;
vec2 g_screen;
vec2 g_world;
static int fps = 22;
static TrafficModel* model = new TrafficModelEasyYDim(fps,
Restrictions::dflt_count_x_gridpoints,
Restrictions::dflt_count_y_gridpoints, 0xa123);
static BaseScene* g_scene = new SceneNoGravity(1.0f / 60.0f, 10);
//========================================================
void __render_string( int32 x, int32 y, const char *s )
{
glColor3f(0.5f, 0.5f, 0.9f);
glRasterPos2i(x, y);
uint32 l = (uint32) std::strlen(s);
for( uint32 i = 0; i < l; ++i )
glutBitmapCharacter( GLUT_BITMAP_9_BY_15, *(s + i));
}
void render_string( int32 x, int32 y, string s )
{
__render_string(x, y, s.c_str());
}
void passive_mouse_func( int x, int y )
{
vec2 point(x, y);
g_screen = g_p_mat * point;
// world
g_world = g_screen;
mat2 mirror_y(1, 0, 0, -1);
vec2 v(mirror_y * g_world);
mat2 rotate_90(0, -1, 1, 0);
vec2 v1(rotate_90 * v);
vec2 move_vec(80, 30);
g_world = v1 + move_vec;
}
void click_mouse_func( int button, int state, int x, int y )
{
passive_mouse_func(x, y);
}
void draw_cursor()
{
stringstream ss;
ss << g_world[0] << "," << g_world(1);
render_string(g_screen[0], g_screen[1], ss.str());
Mark m(vec2_ie(30, 80));
m.draw();
}
void phy_loop_func( void )
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// My event
draw_cursor();
// Source event
static double s_accumulator = 0;
// Different time mechanisms for Linux and Windows
s_accumulator += g_clock.Elapsed()
/ static_cast<double>(boost::chrono::duration_cast<clock_freq>(
boost::chrono::seconds(1)).count());
g_clock.Start();
s_accumulator = clamp(0.0f, 0.1f, s_accumulator);
while( s_accumulator >= dt ){
if( !g_frameStepping )
g_scene->Step();
else{
if( g_canStep ){
g_scene->Step();
g_canStep = false;
}
}
s_accumulator -= dt;
}
g_clock.Stop();
g_scene->Render();
glutSwapBuffers();
}
//========================================================
int main( int argc, char** argv )
{
float max_img_x_px = 450;
float max_img_y_px = 800;
float max_img_x_m = 60;
float max_img_y_m = 107;
g_p_mat = mat2(max_img_x_m / max_img_x_px, 0.0f, 0.0f,
max_img_y_m / max_img_y_px);
glutInit(&argc, argv);
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE);
glutInitWindowSize(450, 800);
glutCreateWindow("RadarView");
glutDisplayFunc(phy_loop_func);
glutMouseFunc(click_mouse_func);
glutIdleFunc(phy_loop_func);
glutPassiveMotionFunc(passive_mouse_func);
glMatrixMode( GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0, max_img_x_m, max_img_y_m, 0);
glMatrixMode( GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
srand(1);
glutMainLoop();
return 0;
}
| 24.698225 | 95 | 0.700527 | [
"render",
"vector",
"model"
] |
aa01e21da343f8223e08f85445ff87bc5c6335dd | 3,112 | hpp | C++ | include/lexical_analyzer/DFA_Builder.hpp | Hamada14/JavaCompiler | ee01fdf3d4ef667fc8bebbdf1691391460dd0b16 | [
"MIT"
] | null | null | null | include/lexical_analyzer/DFA_Builder.hpp | Hamada14/JavaCompiler | ee01fdf3d4ef667fc8bebbdf1691391460dd0b16 | [
"MIT"
] | null | null | null | include/lexical_analyzer/DFA_Builder.hpp | Hamada14/JavaCompiler | ee01fdf3d4ef667fc8bebbdf1691391460dd0b16 | [
"MIT"
] | null | null | null | #ifndef DFA_BUILDER_HPP_INCLUDED
#define DFA_BUILDER_HPP_INCLUDED
#include "DFA.hpp"
#include "Graph.hpp"
#include "NFA.hpp"
#include "State.hpp"
#include "Print.hpp"
#include <climits>
#include <cstring>
#include <iostream>
#include <map>
#include <stack>
#include <stdio.h>
#include <unordered_map>
#include <unordered_set>
/*
the main class in building DFA
input of the class is NFA with the graph, start node and end node
output is a DFA accepting the same expressions as input NFA
*/
class DFA_Builder
{
private:
/*
NFA Graph which is processed in the class
*/
Graph* nfa_graph;
/*
start node of the graph
*/
int start_node;
/*
end node of the graph
*/
int end_node;
/*
determine if epsillon closure for a node is computed
*/
unordered_map<int, bool> epsillon_computed;
/*
epsillon closure of each node of the NFA graph
*/
unordered_map<int, unordered_set<int> >* epsillon;
/*
stack which hold states that should be built in the DFA
*/
stack<State*> stk;
/*
taken array to mark visited states
*/
unordered_map<int, bool> taken;
/*
array to check if a state is formed before or not
*/
map<set<int>, int>* is_a_state;
/*
function to compute the epsillon closure of a certain node
*/
void solve_epsillon(int v);
/*
A DFS function which get epsillon closure for a certain node
*/
void get_epsillon_closure(int v, unordered_set<int>* result);
/*
Main algorithm of forming DFA
start with the state of the start node of the graph
pushing all possible states to the graph
*/
void subset_construction(DFA& ret);
/*
a functions to get all possible transitions in a graph
*/
vector<string> get_possible_transitions();
/*
search all possible transitions for a certain transitions and the add the epsillon closure
of it to the graph
*/
void search_transtion(int node_id, State* next, string trans);
/*
connect two states if the is a valid edge between 'em in the graph
or add edge to PHI state otherwise
*/
void connect_edge(
State* cur_state, State* next, DFA& ret, string transition, vector<int>& data);
/*
helper function which pushes a state to the stack if this state is not pushed before
*/
void push_state(State* state);
/*
helper function to set attributes of a certain state
*/
void set_state(State* state);
public:
/*
Constructor of the class
*/
DFA_Builder(NFA* nfa)
{
this->nfa_graph = nfa->get_graph();
this->start_node = nfa->get_start_node();
this->end_node = nfa->get_end_node();
epsillon = new unordered_map<int, unordered_set<int> >;
is_a_state = new map<set<int>, int>;
}
/*
factory of the class which runs the steps of the algorithm,
build the graph and return DFA
*/
DFA* get_DFA();
};
#endif // DFA_BUILDER_HPP_INCLUDED
| 26.372881 | 98 | 0.636247 | [
"vector"
] |
aa0278e6bd66c49c10473d715cae2b425f02192b | 729 | cpp | C++ | day15.cpp | tamastokes/AdventOfCode2020 | a2350bf9c735b36a23ca63506d337efdfb2552fc | [
"MIT"
] | null | null | null | day15.cpp | tamastokes/AdventOfCode2020 | a2350bf9c735b36a23ca63506d337efdfb2552fc | [
"MIT"
] | null | null | null | day15.cpp | tamastokes/AdventOfCode2020 | a2350bf9c735b36a23ca63506d337efdfb2552fc | [
"MIT"
] | null | null | null | #include <unordered_map>
#include <vector>
#include <iostream>
int main()
{
std::vector<int> v{0,6,1,7,2,19,20};
std::unordered_map<int,int> m;
for (int i=0; i<v.size()-1; ++i){
m[v[i]] = i+1;
}
int curr = v.back();
for (int i=v.size(); i<30000000; ++i)
{
int next;
auto occurance = m.find(curr);
if (occurance == m.end())
{
next = 0;
}
else
{
int last = occurance->second;
int diff = i - last;
next = diff;
}
m[curr] = i;
curr = next;
if (i % 100000 == 0){
std::cout << i << std::endl;
}
}
std::cout << curr << std::endl;
}
| 19.702703 | 42 | 0.421125 | [
"vector"
] |
aa076ef8c9490d46054fb2155b4da204da42076e | 9,353 | cpp | C++ | d-collide/narrowphase/spheretriangleintersector.cpp | ColinGilbert/d-collide | 8adb354d52e7ee49705ca2853d50a6a879f3cd49 | [
"BSD-3-Clause"
] | 6 | 2015-12-08T05:38:03.000Z | 2021-04-09T13:45:59.000Z | d-collide/narrowphase/spheretriangleintersector.cpp | ColinGilbert/d-collide | 8adb354d52e7ee49705ca2853d50a6a879f3cd49 | [
"BSD-3-Clause"
] | null | null | null | d-collide/narrowphase/spheretriangleintersector.cpp | ColinGilbert/d-collide | 8adb354d52e7ee49705ca2853d50a6a879f3cd49 | [
"BSD-3-Clause"
] | null | null | null | /*******************************************************************************
* Copyright (C) 2007 by the members of PG 510, University of Dortmund: *
* d-collide-users@lists.sourceforge.net *
* Andreas Beckermann, Christian Bode, Marcel Ens, Sebastian Ens, *
* Martin Fassbach, Maximilian Hegele, Daniel Haus, Oliver Horst, *
* Gregor Jochmann, Timo Loist, Marcel Nienhaus and Marc Schulz *
* *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are met:*
* - Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* - Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* - Neither the name of the PG510 nor the names of its contributors may be *
* used to endorse or promote products derived from this software without *
* specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER *
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR *
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF *
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE *
*******************************************************************************/
#include "spheretriangleintersector.h"
#include "d-collide/math/plane.h"
#include "d-collide/math/vector.h"
#include "d-collide/math/matrix.h"
#include "d-collide/shapes/mesh/triangle.h"
#include "d-collide/shapes/mesh/vertex.h"
#include "d-collide/shapes/sphere.h"
#include "d-collide/proxy.h"
#include "d-collide/collisioninfo.h"
#include "d-collide/debugstream.h"
namespace dcollide {
CollisionInfo* SphereTriangleIntersector::getIntersection(const Sphere* sphere,
const Triangle* triangle,
Proxy* triangleProxy) {
const dcollide::array<Vertex*,3> vertices = triangle->getVertices();
Vector3 sphereCenter = sphere->getProxy()->getWorldTransformation().getPosition();
//Using plane constructor with point-on plane and normal
Plane triPlane(triangle->getWorldCoordinatesNormalVector(), vertices[0]->getWorldPosition(),false);
//GJ: i assume that this is the signed distance
real distanceSpherePlane = triPlane.calculateDistance(sphereCenter);
if (fabs(distanceSpherePlane) > sphere->getRadius()) {
return 0;
}
//dcollide::debug () << "sphere penetrates the triangle plane";
//The sphere penetrates the triangle plane.
//Now check if the projection is in the triangle
Vector3 projection = sphereCenter - triPlane.getNormal() * distanceSpherePlane;
real u; //u and v will be set by triangle->containsPoint()
real v;
triangle->containsPoint(projection, true, false, &u, &v);
// Check if point is in triangle
//return (u > 0) && (v > 0) && (u + v < 1)
//dcollide::debug() << " u = " << u << ", v = " << v;
if (u > 0) {
if (v > 0) {
if (u + v <1) {
//dcollide::debug() << "sphere-triangle face collision";
//face collision
CollisionInfo* coll = new CollisionInfo();
coll->collisionPoint = projection;
coll->normal = triPlane.getNormal();
coll->penetrationDepth = sphere->getRadius() - distanceSpherePlane;
coll->penetratedProxy = triangleProxy;
coll->penetratedTriangle = const_cast<Triangle*>(triangle);
coll->penetratingProxy = sphere->getProxy();
return coll;
} else {
//outside of edge12
return testEdge(vertices[1]->getWorldPosition(), triangle->getEdge12(),
sphereCenter, triangle, triangleProxy, sphere);
}
}else {
//outside out edge02
return testEdge(vertices[0]->getWorldPosition(), triangle->getEdge02(),
sphereCenter, triangle, triangleProxy, sphere);
}
} else {
//outside of edge01
return testEdge(vertices[0]->getWorldPosition(), triangle->getEdge01(),
sphereCenter, triangle, triangleProxy, sphere);
}
return 0;
}
CollisionInfo* SphereTriangleIntersector::testEdge(const Vector3& edgeStart, const Vector3& edgeDir,
const Vector3& sphereCenter,
const Triangle* triangle, Proxy* triangleProxy, const Sphere* sphere){
//compute parameter t of "foot point" on ray which is closest to the sphere center
//if t is in [0,1], we could have an edge collision
//ray =
//
// footpoint (on ray) F = edgeStart + t * edgeDir
// minimal distance: skalar product (footpoint - sphereCenter) * edgeDir = 0
// => edgeDirX * (edgeStartX + t*edgeDirX - sphereCenterX)
// +edgeDirY * (edgeStartY + t*edgeDirY - sphereCenterY)
// +edgeDirZ * (edgeStartZ + t*edgeDirZ - sphereCenterZ) = 0
//
// solving for t yields
// t=( edgeDirZ*sphereCenterZ
// +edgeDirY*sphereCenterY
// +edgeDirX*sphereCenterX
// -edgeDirZ*edgeStartZ
// -edgeDirY*edgeStartY
// -edgeDirX*edgeStartX)
// /
// (edgeDirZ^2+edgeDirY^2+edgeDirX^2)
real t = ( edgeDir.getZ() * sphereCenter.getZ()
+edgeDir.getY() * sphereCenter.getY()
+edgeDir.getX() * sphereCenter.getX()
-edgeDir.getZ() * edgeStart.getZ()
-edgeDir.getY() * edgeStart.getY()
-edgeDir.getX() * edgeStart.getX()
)/(
edgeDir.getZ() * edgeDir.getZ()
+edgeDir.getY() * edgeDir.getY()
+edgeDir.getX() * edgeDir.getX()
);
if (t>0){
if (t<=1) {
//closest point is on edge, compare distance with radius
//compute footpoint
Vector3 footpoint = edgeStart + edgeDir * t;
real distance = (sphereCenter - footpoint).length();
if (distance < sphere->getRadius()) {
//edge collision
CollisionInfo* coll = new CollisionInfo();
coll->collisionPoint = footpoint;
coll->normal = sphereCenter - footpoint;
coll->normal.normalize();
coll->penetrationDepth = sphere->getRadius() - distance;
coll->penetratedProxy = triangleProxy;
coll->penetratedTriangle = const_cast<Triangle*>(triangle);
coll->penetratingProxy = sphere->getProxy();
return coll;
}
}else{
//check vertex collision with edgeEnd
return testVertex(edgeStart+edgeDir, sphereCenter, triangle, triangleProxy, sphere);
}
} else {
//check vertex collision with edgeStart
return testVertex(edgeStart, sphereCenter, triangle, triangleProxy, sphere);
}
return 0;
}
/*!
* \brief create a collision if the vertex is within the sphere
*
*/
CollisionInfo* SphereTriangleIntersector::testVertex(const Vector3& vertex,
const Vector3& sphereCenter,
const Triangle* triangle, Proxy* triangleProxy, const Sphere* sphere){
//this is really basic, just a simple point-in triangle test
Vector3 connection = sphereCenter - vertex;
real distance = connection.length();
if (distance < sphere->getRadius()) {
//vertex collision
CollisionInfo* coll = new CollisionInfo();
coll->collisionPoint = vertex;
coll->normal = connection;
coll->normal.normalize();
coll->penetrationDepth = sphere->getRadius() - distance;
coll->penetratedProxy = triangleProxy;
coll->penetratedTriangle = const_cast<Triangle*>(triangle);
coll->penetratingProxy = sphere->getProxy();
return coll;
}
return 0;
}
}//end namespace
/*
* vim: et sw=4 ts=4
*/
| 46.073892 | 103 | 0.575858 | [
"mesh",
"vector"
] |
aa09df65b6c5e71a4a2c80b213414f827cfb0de7 | 13,236 | cc | C++ | skiko/src/nativeJsMain/cpp/common_interop.cc | smallshen/skiko | 6eaa4ba6b3bf2cff1eaa92f63adb5c7b02c5bd8d | [
"Apache-2.0"
] | null | null | null | skiko/src/nativeJsMain/cpp/common_interop.cc | smallshen/skiko | 6eaa4ba6b3bf2cff1eaa92f63adb5c7b02c5bd8d | [
"Apache-2.0"
] | null | null | null | skiko/src/nativeJsMain/cpp/common_interop.cc | smallshen/skiko | 6eaa4ba6b3bf2cff1eaa92f63adb5c7b02c5bd8d | [
"Apache-2.0"
] | null | null | null | #include "common.h"
#include "src/utils/SkUTF.h"
#include "include/core/SkImageInfo.h"
#include "TextStyle.h"
#include <stdio.h>
KLong packTwoInts(int32_t a, int32_t b) {
return (uint64_t (a) << 32) | b;
}
KLong packIPoint(SkIPoint p) {
return packTwoInts(p.fX, p.fY);
}
KLong packISize(SkISize p) {
return packTwoInts(p.fWidth, p.fHeight);
}
namespace skija {
namespace SamplingMode {
SkSamplingOptions unpack(KLong val) {
if (0x8000000000000000 & val) {
val = val & 0x7FFFFFFFFFFFFFFF;
float* ptr = reinterpret_cast<float*>(&val);
return SkSamplingOptions(SkCubicResampler {ptr[1], ptr[0]});
} else {
int32_t filter = (int32_t) ((val >> 32) & 0xFFFFFFFF);
int32_t mipmap = (int32_t) (val & 0xFFFFFFFF);
return SkSamplingOptions(static_cast<SkFilterMode>(filter), static_cast<SkMipmapMode>(mipmap));
}
}
SkSamplingOptions unpackFrom2Ints(KInt samplingModeVal1, KInt samplingModeVal2) {
if (0x80000000 & samplingModeVal1) {
uint64_t val1 = samplingModeVal1 & 0x7FFFFFFF;
uint64_t val = (val1 << 32) | samplingModeVal2;
float* ptr = reinterpret_cast<float*>(&val);
return SkSamplingOptions(SkCubicResampler {ptr[1], ptr[0]});
} else {
int32_t filter = samplingModeVal1;
int32_t mipmap = samplingModeVal2;
return SkSamplingOptions(static_cast<SkFilterMode>(filter), static_cast<SkMipmapMode>(mipmap));
}
}
}
namespace FontFeature {
std::vector<SkShaper::Feature> fromIntArray(KInt* array, KInt featuresLen) {
std::vector<SkShaper::Feature> features(featuresLen);
for (int i = 0; i < featuresLen; ++i) {
int j = i * 4;
features[i] = {
static_cast<SkFourByteTag>(array[j]),
static_cast<uint32_t>(array[j + 1]),
static_cast<size_t>(array[j + 2]),
static_cast<size_t>(array[j + 3])
};
}
return features;
}
void writeToIntArray(std::vector<skia::textlayout::FontFeature> features, int* resultArr) {
for (int i = 0; i < features.size(); ++i) {
int j = i * 2;
resultArr[j] = skija::FontFeature::FourByteTag::fromString(features[i].fName);
resultArr[j + 1] = features[i].fValue;;
}
}
namespace FourByteTag {
int fromString(SkString str) {
int code1 = (int)str[0];
int code2 = (int)str[1];
int code3 = (int)str[2];
int code4 = (int)str[3];
return (code1 & 0xFF << 24) | (code2 & 0xFF << 16) | (code3 & 0xFF << 8) | (code4 & 0xFF);
}
}
}
namespace shaper {
namespace ShapingOptions {
std::vector<SkShaper::Feature> getFeaturesFromIntsArray(KInt* featuresArray, KInt featuresLen) {
return skija::FontFeature::fromIntArray(featuresArray, featuresLen);
}
}
std::shared_ptr<UBreakIterator> graphemeBreakIterator(SkString& text) {
UErrorCode status = U_ZERO_ERROR;
ICUUText utext(utext_openUTF8(nullptr, text.c_str(), text.size(), &status));
if (U_FAILURE(status)) {
SkDEBUGF("utext_openUTF8 error: %s", u_errorName(status));
return nullptr;
}
std::shared_ptr<UBreakIterator> graphemeIter(
ubrk_open(static_cast<UBreakIteratorType>(UBreakIteratorType::UBRK_CHARACTER), uloc_getDefault(), nullptr, 0, &status),
[](UBreakIterator* p) { ubrk_close(p); }
);
if (U_FAILURE(status)) {
SkDEBUGF("ubrk_open error: %s", u_errorName(status));
return nullptr;
}
ubrk_setUText(graphemeIter.get(), utext.get(), &status);
if (U_FAILURE(status)) {
SkDEBUGF("ubrk_setUText error: %s", u_errorName(status));
return nullptr;
}
return graphemeIter;
}
}
}
skija::UtfIndicesConverter::UtfIndicesConverter(const char* chars8, size_t len8):
fStart8(chars8),
fPtr8(chars8),
fEnd8(chars8 + len8),
fPos16(0)
{}
skija::UtfIndicesConverter::UtfIndicesConverter(const SkString& str):
skija::UtfIndicesConverter::UtfIndicesConverter(str.c_str(), str.size())
{}
size_t skija::UtfIndicesConverter::from16To8(uint32_t i16) {
if (i16 >= fPos16) {
// if new i16 >= last fPos16, continue from where we started
} else {
fPtr8 = fStart8;
fPos16 = 0;
}
while (fPtr8 < fEnd8 && fPos16 < i16) {
SkUnichar u = SkUTF::NextUTF8(&fPtr8, fEnd8);
fPos16 += (uint32_t) SkUTF::ToUTF16(u);
}
return fPtr8 - fStart8;
}
uint32_t skija::UtfIndicesConverter::from8To16(size_t i8) {
if (i8 >= (size_t) (fPtr8 - fStart8)) {
// if new i8 >= last fPtr8, continue from where we started
} else {
fPtr8 = fStart8;
fPos16 = 0;
}
while (fPtr8 < fEnd8 && (size_t) (fPtr8 - fStart8) < i8) {
SkUnichar u = SkUTF::NextUTF8(&fPtr8, fEnd8);
fPos16 += (uint32_t) SkUTF::ToUTF16(u);
}
return fPos16;
}
void TODO(const char* message) {
printf("TODO: %s\n", message);
fflush(stdout);
abort();
}
std::unique_ptr<SkMatrix> skMatrix(KFloat* matrixArray) {
if (matrixArray == nullptr)
return std::unique_ptr<SkMatrix>(nullptr);
else {
KFloat* m = matrixArray;
SkMatrix* ptr = new SkMatrix();
ptr->setAll(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8]);
return std::unique_ptr<SkMatrix>(ptr);
}
}
std::unique_ptr<SkM44> skM44(KFloat* matrixArray) {
if (matrixArray == nullptr)
return std::unique_ptr<SkM44>(nullptr);
else {
KFloat* m = matrixArray;
SkM44* ptr = new SkM44(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]);
return std::unique_ptr<SkM44>(ptr);
}
}
SkString skString(KInteropPointer s) {
char* str = reinterpret_cast<char *>(s);
if (str == nullptr) {
return SkString();
} else {
return SkString(str);
}
}
std::vector<SkString> skStringVector(KInteropPointerArray arr, KInt len) {
if (arr == nullptr) {
return std::vector<SkString>(0);
} else {
std::vector<SkString> res(len);
char** strings = reinterpret_cast<char**>(arr);
for (KInt i = 0; i < len; ++i) {
res[i] = skString(strings[i]);
}
return res;
}
}
namespace skija {
namespace Rect {
void copyToInterop(const SkRect& rect, KInteropPointer pointer) {
float* ltrb = reinterpret_cast<float*>(pointer);
if (ltrb != nullptr) {
ltrb[0] = rect.left();
ltrb[1] = rect.top();
ltrb[2] = rect.right();
ltrb[3] = rect.bottom();
}
}
}
namespace RRect {
void copyToInterop(const SkRRect& rect, KInteropPointer pointer) {
float* ltrb = reinterpret_cast<float*>(pointer);
if (ltrb != nullptr) {
ltrb[0] = rect.rect().left();
ltrb[1] = rect.rect().top();
ltrb[2] = rect.rect().right();
ltrb[3] = rect.rect().bottom();
ltrb[4] = rect.radii(SkRRect::kUpperLeft_Corner).x();
ltrb[5] = rect.radii(SkRRect::kUpperLeft_Corner).y();
ltrb[6] = rect.radii(SkRRect::kUpperRight_Corner).x();
ltrb[7] = rect.radii(SkRRect::kUpperRight_Corner).y();
ltrb[8] = rect.radii(SkRRect::kLowerRight_Corner).x();
ltrb[9] = rect.radii(SkRRect::kLowerRight_Corner).y();
ltrb[10] = rect.radii(SkRRect::kLowerLeft_Corner).x();
ltrb[11] = rect.radii(SkRRect::kLowerLeft_Corner).y();
}
}
}
namespace Point {
void copyToInterop(const SkPoint& point, KInteropPointer pointer) {
float* xy = reinterpret_cast<float*>(pointer);
if (xy != nullptr) {
xy[0] = point.x();
xy[1] = point.y();
}
}
}
namespace RRect {
SkRRect toSkRRect(KFloat left, KFloat top, KFloat right, KFloat bottom, KFloat* radii, KInt radiiSize) {
SkRect rect {left, top, right, bottom};
SkRRect rrect = SkRRect::MakeEmpty();
switch (radiiSize) {
case 1:
rrect.setRectXY(rect, radii[0], radii[0]);
break;
case 2:
rrect.setRectXY(rect, radii[0], radii[1]);
break;
case 4: {
SkVector vradii[4] = {{radii[0], radii[0]}, {radii[1], radii[1]}, {radii[2], radii[2]}, {radii[3], radii[3]}};
rrect.setRectRadii(rect, vradii);
break;
}
case 8: {
SkVector vradii[4] = {{radii[0], radii[1]}, {radii[2], radii[3]}, {radii[4], radii[5]}, {radii[6], radii[7]}};
rrect.setRectRadii(rect, vradii);
break;
}
}
return rrect;
}
}
namespace FontStyle {
SkFontStyle fromKotlin(KInt style) {
return SkFontStyle(style & 0xFFFF, (style >> 16) & 0xFF, static_cast<SkFontStyle::Slant>((style >> 24) & 0xFF));
}
KInt toKotlin(const SkFontStyle& fs) {
return (static_cast<int>(fs.slant()) << 24)| (fs.width() << 16) | fs.weight();
}
}
namespace ImageInfo {
void writeImageInfoForInterop(SkImageInfo imageInfo, KInt* imageInfoResult, KNativePointer* colorSpacePtrsArray) {
imageInfoResult[0] = imageInfo.width();
imageInfoResult[1] = imageInfo.height();
imageInfoResult[2] = static_cast<int>(imageInfo.colorType());
imageInfoResult[3] = static_cast<int>(imageInfo.alphaType());
colorSpacePtrsArray[0] = imageInfo.refColorSpace().release();
}
}
namespace SurfaceProps {
std::unique_ptr<SkSurfaceProps> toSkSurfaceProps(KInt* surfacePropsInts) {
if (surfacePropsInts == nullptr) {
return std::unique_ptr<SkSurfaceProps>(nullptr);
}
int flags = surfacePropsInts[0];
SkPixelGeometry geom = static_cast<SkPixelGeometry>(surfacePropsInts[1]);
return std::make_unique<SkSurfaceProps>(flags, geom);
}
}
namespace IRect {
std::unique_ptr<SkIRect> toSkIRect(KInt* rectInts) {
if (rectInts == nullptr)
return std::unique_ptr<SkIRect>(nullptr);
else {
return std::unique_ptr<SkIRect>(new SkIRect{
rectInts[0], rectInts[1], rectInts[2], rectInts[3]
});
}
}
}
namespace AnimationFrameInfo {
static void copyToInteropAtIndex(const SkCodec::FrameInfo& info, KInt* repr, size_t index) {
repr += (index * 11);
repr[0] = info.fRequiredFrame;
repr[1] = info.fDuration;
repr[2] = static_cast<KInt>(info.fFullyReceived);
repr[3] = static_cast<KInt>(info.fAlphaType);
repr[4] = static_cast<KInt>(info.fHasAlphaWithinBounds);
repr[5] = static_cast<KInt>(info.fDisposalMethod);
repr[6] = static_cast<KInt>(info.fBlend);
repr[7] = info.fFrameRect.left();
repr[8] = info.fFrameRect.top();
repr[9] = info.fFrameRect.right();
repr[10] = info.fFrameRect.bottom();
}
void copyToInterop(const SkCodec::FrameInfo& info, KInteropPointer dst) {
KInt* repr = reinterpret_cast<KInt*>(dst);
copyToInteropAtIndex(info, repr, 0);
}
void copyToInterop(const std::vector<SkCodec::FrameInfo>& infos, KInteropPointer dst) {
KInt* repr = reinterpret_cast<KInt*>(dst);
size_t i = 0;
for (const auto& info : infos) {
copyToInteropAtIndex(info, repr, i++);
}
}
}
namespace svg {
namespace SVGLength {
void copyToInterop(const SkSVGLength& length, KInteropPointer dst) {
KInt* result = reinterpret_cast<KInt*>(dst);
result[0] = rawBits(length.value());
result[1] = static_cast<KInt>(length.unit());
}
}
namespace SVGPreserveAspectRatio {
void copyToInterop(const SkSVGPreserveAspectRatio& aspectRatio, KInteropPointer dst) {
KInt* result = reinterpret_cast<KInt*>(dst);
result[0] = static_cast<KInt>(aspectRatio.fAlign);
result[1] = static_cast<KInt>(aspectRatio.fScale);
}
}
}
}
| 35.580645 | 135 | 0.5445 | [
"vector"
] |
aa0a61c4ccfc0f2dfba70c9c0f81efd364ca3dc4 | 773 | cpp | C++ | PhysicsExample/Source/PhysicsExample/CubeA.cpp | EduTeachers/UnrealEngine4-SampleCode | 80e8f0fe3c2bb930856d4f6a478bf0bdc51878d5 | [
"MIT"
] | 4 | 2022-01-20T18:14:00.000Z | 2022-02-24T14:45:47.000Z | PhysicsExample/Source/PhysicsExample/CubeA.cpp | EduTeachers/UnrealEngine4-SampleCode | 80e8f0fe3c2bb930856d4f6a478bf0bdc51878d5 | [
"MIT"
] | null | null | null | PhysicsExample/Source/PhysicsExample/CubeA.cpp | EduTeachers/UnrealEngine4-SampleCode | 80e8f0fe3c2bb930856d4f6a478bf0bdc51878d5 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "CubeA.h"
// Sets default values
ACubeA::ACubeA()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
StaticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>("Mesh");
SetRootComponent(StaticMeshComponent);
}
// Called when the game starts or when spawned
void ACubeA::BeginPlay()
{
Super::BeginPlay();
if (IsValid(StaticMeshComponent))
{
StaticMeshComponent->AddImpulse(FVector(0, 0, 1000));
StaticMeshComponent->AddAngularImpulseInDegrees(FVector(0, 10000, 0));
}
}
// Called every frame
void ACubeA::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
| 23.424242 | 114 | 0.751617 | [
"mesh"
] |
aa0d368957137b4b0fb57928ddd15f1189151616 | 10,332 | cc | C++ | chrome/browser/cart/commerce_hint_service.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/browser/cart/commerce_hint_service.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | chrome/browser/cart/commerce_hint_service.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/cart/commerce_hint_service.h"
#include <map>
#include <memory>
#include "base/metrics/histogram_functions.h"
#include "base/time/time.h"
#include "chrome/browser/cart/cart_db_content.pb.h"
#include "chrome/browser/cart/cart_features.h"
#include "chrome/browser/cart/cart_service.h"
#include "chrome/browser/cart/cart_service_factory.h"
#include "chrome/browser/optimization_guide/optimization_guide_keyed_service.h"
#include "chrome/browser/optimization_guide/optimization_guide_keyed_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "components/search/ntp_features.h"
#include "components/ukm/content/source_url_recorder.h"
#include "content/public/browser/document_service.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_user_data.h"
#include "crypto/random.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
namespace cart {
namespace {
// TODO(crbug/1164236): support multiple cart systems in the same domain.
// Returns eTLB+1 domain.
std::string GetDomain(const GURL& url) {
return net::registry_controlled_domains::GetDomainAndRegistry(
url, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
}
void ConstructCartProto(cart_db::ChromeCartContentProto* proto,
const GURL& navigation_url,
std::vector<mojom::ProductPtr> products) {
const std::string& domain = GetDomain(navigation_url);
proto->set_key(domain);
proto->set_merchant(domain);
proto->set_merchant_cart_url(navigation_url.spec());
proto->set_timestamp(base::Time::Now().ToDoubleT());
for (auto& product : products) {
if (product->image_url.spec().size() != 0) {
proto->add_product_image_urls(product->image_url.spec());
}
if (!product->product_id.empty()) {
cart_db::ChromeCartProductProto product_proto;
product_proto.set_product_id(std::move(product->product_id));
cart_db::ChromeCartProductProto* added_product =
proto->add_product_infos();
*added_product = std::move(product_proto);
}
}
}
} // namespace
// Implementation of the Mojo CommerceHintObserver. This is called by the
// renderer to notify the browser that a commerce hint happens.
class CommerceHintObserverImpl
: public content::DocumentService<mojom::CommerceHintObserver> {
public:
explicit CommerceHintObserverImpl(
content::RenderFrameHost* render_frame_host,
mojo::PendingReceiver<mojom::CommerceHintObserver> receiver,
base::WeakPtr<CommerceHintService> service)
: DocumentService(render_frame_host, std::move(receiver)),
binding_url_(render_frame_host->GetLastCommittedURL()),
service_(std::move(service)) {}
~CommerceHintObserverImpl() override = default;
void OnAddToCart(const absl::optional<GURL>& cart_url,
const std::string& product_id) override {
DVLOG(1) << "Received OnAddToCart in the browser process on "
<< binding_url_;
if (!service_ || !binding_url_.SchemeIsHTTPOrHTTPS())
return;
service_->OnAddToCart(binding_url_, cart_url, product_id);
}
void OnVisitCart() override {
DVLOG(1) << "Received OnVisitCart in the browser process";
if (!service_ || !binding_url_.SchemeIsHTTPOrHTTPS())
return;
service_->OnAddToCart(binding_url_, binding_url_);
}
void OnCartProductUpdated(std::vector<mojom::ProductPtr> products) override {
DVLOG(1) << "Received OnCartProductUpdated in the browser process, with "
<< products.size() << " product(s).";
if (!service_ || !binding_url_.SchemeIsHTTPOrHTTPS())
return;
if (products.empty()) {
service_->OnRemoveCart(binding_url_);
} else {
service_->OnCartUpdated(binding_url_, std::move(products));
}
}
void OnVisitCheckout() override {
DVLOG(1) << "Received OnVisitCheckout in the browser process";
if (!service_ || !binding_url_.SchemeIsHTTPOrHTTPS())
return;
service_->OnRemoveCart(binding_url_);
}
void OnPurchase() override {
DVLOG(1) << "Received OnPurchase in the browser process";
if (!service_ || !binding_url_.SchemeIsHTTPOrHTTPS())
return;
service_->OnRemoveCart(binding_url_);
}
void OnFormSubmit(bool is_purchase) override {
DVLOG(1) << "Received OnFormSubmit in the browser process";
if (!service_ || !binding_url_.SchemeIsHTTPOrHTTPS())
return;
service_->OnFormSubmit(binding_url_, is_purchase);
}
void OnWillSendRequest(bool is_addtocart) override {
DVLOG(1) << "Received OnWillSendRequest in the browser process";
if (!service_ || !binding_url_.SchemeIsHTTPOrHTTPS())
return;
service_->OnWillSendRequest(binding_url_, is_addtocart);
}
void OnNavigation(const GURL& url, OnNavigationCallback callback) override {
std::move(callback).Run(service_->ShouldSkip(url));
}
private:
GURL binding_url_;
base::WeakPtr<CommerceHintService> service_;
};
CommerceHintService::CommerceHintService(content::WebContents* web_contents)
: content::WebContentsUserData<CommerceHintService>(*web_contents) {
DCHECK(!web_contents->GetBrowserContext()->IsOffTheRecord());
Profile* profile =
Profile::FromBrowserContext(web_contents->GetBrowserContext());
service_ = CartServiceFactory::GetInstance()->GetForProfile(profile);
optimization_guide_decider_ =
OptimizationGuideKeyedServiceFactory::GetForProfile(profile);
if (optimization_guide_decider_) {
optimization_guide_decider_->RegisterOptimizationTypes(
{optimization_guide::proto::SHOPPING_PAGE_PREDICTOR});
}
}
CommerceHintService::~CommerceHintService() = default;
content::WebContents* CommerceHintService::WebContents() {
return &GetWebContents();
}
void CommerceHintService::BindCommerceHintObserver(
content::RenderFrameHost* host,
mojo::PendingReceiver<mojom::CommerceHintObserver> receiver) {
// The object is bound to the lifetime of |host| and the mojo
// connection. See DocumentService for details.
new CommerceHintObserverImpl(host, std::move(receiver),
weak_factory_.GetWeakPtr());
}
bool CommerceHintService::ShouldSkip(const GURL& url) {
if (!optimization_guide_decider_) {
return false;
}
optimization_guide::OptimizationMetadata metadata;
auto decision = optimization_guide_decider_->CanApplyOptimization(
url, optimization_guide::proto::SHOPPING_PAGE_PREDICTOR, &metadata);
DVLOG(1) << "SHOPPING_PAGE_PREDICTOR = " << static_cast<int>(decision);
return optimization_guide::OptimizationGuideDecision::kFalse == decision;
}
void CommerceHintService::OnAddToCart(const GURL& navigation_url,
const absl::optional<GURL>& cart_url,
const std::string& product_id) {
if (ShouldSkip(navigation_url))
return;
absl::optional<GURL> validated_cart = cart_url;
if (cart_url && GetDomain(*cart_url) != GetDomain(navigation_url)) {
DVLOG(1) << "Reject cart URL with different eTLD+1 domain.";
validated_cart = absl::nullopt;
}
// When rule-based discount is enabled, do not accept cart page URLs from
// partner merchants as there could be things like discount tokens in them.
if (service_->IsCartDiscountEnabled() &&
cart_features::IsRuleDiscountPartnerMerchant(navigation_url) &&
product_id.empty()) {
validated_cart = absl::nullopt;
}
cart_db::ChromeCartContentProto proto;
std::vector<mojom::ProductPtr> products;
if (!product_id.empty()) {
mojom::ProductPtr product_ptr(mojom::Product::New());
product_ptr->product_id = product_id;
products.push_back(std::move(product_ptr));
}
ConstructCartProto(&proto, navigation_url, std::move(products));
service_->AddCart(GetDomain(navigation_url), validated_cart,
std::move(proto));
}
void CommerceHintService::OnRemoveCart(const GURL& url) {
service_->DeleteCart(url, false);
}
void CommerceHintService::OnCartUpdated(
const GURL& cart_url,
std::vector<mojom::ProductPtr> products) {
if (ShouldSkip(cart_url))
return;
absl::optional<GURL> validated_cart = cart_url;
// When rule-based discount is enabled, do not accept cart page URLs from
// partner merchants as there could be things like discount tokens in them.
if (service_->IsCartDiscountEnabled() &&
cart_features::IsRuleDiscountPartnerMerchant(cart_url)) {
validated_cart = absl::nullopt;
}
cart_db::ChromeCartContentProto proto;
ConstructCartProto(&proto, cart_url, std::move(products));
service_->AddCart(proto.key(), validated_cart, std::move(proto));
}
void CommerceHintService::OnFormSubmit(const GURL& navigation_url,
bool is_purchase) {
if (ShouldSkip(navigation_url))
return;
uint8_t bytes[1];
crypto::RandBytes(bytes);
bool report_truth = bytes[0] & 0x1;
bool random = (bytes[0] >> 1) & 0x1;
bool reported = report_truth ? is_purchase : random;
ukm::builders::Shopping_FormSubmitted(
ukm::GetSourceIdForWebContentsDocument(&GetWebContents()))
.SetIsTransaction(reported)
.Record(ukm::UkmRecorder::Get());
base::UmaHistogramBoolean("Commerce.Carts.FormSubmitIsTransaction", reported);
}
void CommerceHintService::OnWillSendRequest(const GURL& navigation_url,
bool is_addtocart) {
if (ShouldSkip(navigation_url))
return;
uint8_t bytes[1];
crypto::RandBytes(bytes);
bool report_truth = bytes[0] & 0x1;
bool random = (bytes[0] >> 1) & 0x1;
bool reported = report_truth ? is_addtocart : random;
ukm::builders::Shopping_WillSendRequest(
ukm::GetSourceIdForWebContentsDocument(&GetWebContents()))
.SetIsAddToCart(reported)
.Record(ukm::UkmRecorder::Get());
base::UmaHistogramBoolean("Commerce.Carts.XHRIsAddToCart", reported);
}
WEB_CONTENTS_USER_DATA_KEY_IMPL(CommerceHintService);
} // namespace cart
| 38.125461 | 87 | 0.723868 | [
"object",
"vector"
] |
aa0f2ef2dde74453ed7dfa1df4dfd1aa8547ed03 | 3,515 | hpp | C++ | strings/suff-automaton.hpp | dendi239/algorithms-data-structures | 43db1aa8340f8ef9669bcb26894884f4bc420def | [
"MIT"
] | 10 | 2020-02-02T23:53:04.000Z | 2022-02-14T02:55:14.000Z | strings/suff-automaton.hpp | dendi239/algorithms-data-structures | 43db1aa8340f8ef9669bcb26894884f4bc420def | [
"MIT"
] | 2 | 2020-09-02T12:27:48.000Z | 2021-05-04T00:10:44.000Z | strings/suff-automaton.hpp | dendi239/algorithms-data-structures | 43db1aa8340f8ef9669bcb26894884f4bc420def | [
"MIT"
] | 1 | 2020-04-30T23:16:08.000Z | 2020-04-30T23:16:08.000Z | #pragma once
#include <string>
#include <map>
#include <unordered_map>
#include <vector>
template <class Key, class Value>
struct FastCheapMap {
bool count(Key key) const {
auto it = std::lower_bound(data_.begin(), data_.end(), std::pair{key, Value{}});
return it != data_.end() && it->first == key;
}
Value operator[](Key key) const {
auto it = std::lower_bound(data_.begin(), data_.end(), std::pair{key, Value{}});
if (it == data_.end()) {
return Value{};
} else {
return it->second;
}
}
Value &operator[](Key key) {
auto it = std::lower_bound(data_.begin(), data_.end(), std::pair{key, Value{}});
if (it == data_.end() || it->first != key) {
data_.emplace_back(key, Value{});
std::sort(data_.begin(), data_.end());
return (*this)[key];
}
return it->second;
}
auto begin() const { return data_.begin(); }
auto end() const { return data_.end(); }
private:
std::vector<std::pair<Key, Value>> data_;
};
class SuffAutomaton {
public:
explicit SuffAutomaton(std::string_view str = "") : nodes(1), last(0) {
nodes.reserve(2 * str.size());
for (auto ch : str) { Append(ch); }
}
size_t Size() const { return nodes.size(); }
void Print() const;
void Append(char ch);
bool Contains(std::string_view str) const;
private:
struct Node {
int len = 0, link = -1;
FastCheapMap<char, int> next;
};
friend struct SuffAutomatonIntersector;
friend struct MaxStringFinder;
friend int NumberVertices(const SuffAutomaton &automaton);
friend int GetTarget(const SuffAutomaton &automaton, std::pair<char, int> edge);
friend const auto &OutgoingEdges(const SuffAutomaton &automaton, int node);
std::vector<Node> nodes;
int last;
};
int NumberVertices(const SuffAutomaton &automaton) {
return automaton.nodes.size();
}
int GetTarget(const SuffAutomaton &automaton, std::pair<char, int> edge) {
return edge.second;
}
const auto &OutgoingEdges(const SuffAutomaton &automaton, int node) {
return automaton.nodes[node].next;
}
void SuffAutomaton::Print() const {
for (size_t node = 0; node < nodes.size(); ++node) {
std::cerr << "len " << node << " = " << nodes[node].len << '\n';
for (auto [symb, next] : nodes[node].next) {
std::cerr << node << " " << symb << " " << next << "\n";
}
}
std::cerr << std::endl;
}
void SuffAutomaton::Append(char ch) {
int new_id = static_cast<int>(nodes.size());
nodes.push_back(Node());
nodes.back().len = nodes[last].len + 1;
int node;
for (node = last; node != -1; node = nodes[node].link) {
if (nodes[node].next.count(ch)) {
break;
} else {
nodes[node].next[ch] = new_id;
}
}
if (node == -1) {
nodes[new_id].link = 0;
last = new_id;
return;
}
auto possible = nodes[node].next[ch];
if (nodes[possible].len == nodes[node].len + 1) {
nodes[new_id].link = possible;
last = new_id;
return;
}
auto actual = static_cast<int>(nodes.size());
nodes.push_back(nodes[possible]);
nodes.back().len = nodes[node].len + 1;
for (auto it = node; it != -1 && nodes[it].next[ch] == possible; it = nodes[it].link) {
nodes[it].next[ch] = actual;
}
nodes[possible].link = nodes[new_id].link = actual;
last = new_id;
}
bool SuffAutomaton::Contains(std::string_view str) const {
int node = 0;
for (auto ch : str) {
if (nodes[node].next.count(ch)) {
node = nodes[node].next[ch];
} else {
return false;
}
}
return true;
}
| 24.58042 | 89 | 0.611949 | [
"vector"
] |
aa10ebf4b70069a28854e7e70a41d1ad6d02fa95 | 504 | hpp | C++ | src/strap/common/core/class_indexed_data.hpp | likr/strap | 387162116bab2031e8855f8c686560d7e656b417 | [
"MIT"
] | null | null | null | src/strap/common/core/class_indexed_data.hpp | likr/strap | 387162116bab2031e8855f8c686560d7e656b417 | [
"MIT"
] | null | null | null | src/strap/common/core/class_indexed_data.hpp | likr/strap | 387162116bab2031e8855f8c686560d7e656b417 | [
"MIT"
] | null | null | null | #ifndef STRAP_COMMON_CORE_CLASS_INDEXED_DATA_HPP_
#define STRAP_COMMON_CORE_CLASS_INDEXED_DATA_HPP_
#include <vector>
namespace strap {
template<typename T>
class ClassIndexedData
{
public:
ClassIndexedData();
ClassIndexedData(const int m);
ClassIndexedData(const int m, const T& init);
int m() const;
T& get(const int i);
const T& get(const int i) const;
private:
std::vector<T> data_;
};
} // namespace strap
#include "class_indexed_data-inl.hpp"
#endif /* end of include guard */
| 18 | 49 | 0.744048 | [
"vector"
] |
aa14c0856d41946e84e7b6324b509e9985433370 | 7,218 | hpp | C++ | doc/quickbook/oglplus/quickref/sampler.hpp | highfidelity/oglplus | c5fb7cc21869cb9555cfa2a7e28ea6bc6491d11e | [
"BSL-1.0"
] | 2 | 2017-06-09T00:28:35.000Z | 2017-06-09T00:28:43.000Z | doc/quickbook/oglplus/quickref/sampler.hpp | highfidelity/oglplus | c5fb7cc21869cb9555cfa2a7e28ea6bc6491d11e | [
"BSL-1.0"
] | null | null | null | doc/quickbook/oglplus/quickref/sampler.hpp | highfidelity/oglplus | c5fb7cc21869cb9555cfa2a7e28ea6bc6491d11e | [
"BSL-1.0"
] | 8 | 2017-01-30T22:06:41.000Z | 2020-01-14T17:24:36.000Z | /*
* Copyright 2014-2015 Matus Chochlik. 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)
*/
//[oglplus_sampler_common
namespace oglplus {
template <>
class __ObjCommonOps<__tag_Sampler>
: public __SamplerName
{
public:
typedef __TextureUnitSelector Target; /*<
Sampler bind target.
>*/
static __SamplerName Binding(__TextureUnitSelector target); /*<
Returns the sampler currently bound to the specified [^target].
See [glfunc GetIntegerv].
>*/
static void Bind(__TextureUnitSelector target, __SamplerName sampler); /*<
Binds the specified [^sampler] to the specified [^target].
See [glfunc BindSampler].
>*/
void Bind(__TextureUnitSelector target) const; /*<
Binds [^this] sampler to the specified [^target].
See [glfunc BindSampler].
>*/
};
//]
//[oglplus_sampler_1
template <>
class __ObjectOps<__tag_DirectState, __tag_Sampler>
: public __ObjZeroOps<__tag_DirectState, __tag_Sampler> /*<
Indirectly inherits from __ObjCommonOps_Sampler.
>*/
{
public:
__Vector<GLfloat, 4> BorderColor(__TypeTag<GLfloat>) const; /*<
Returns the currently set border color of this sampler object.
See [glfunc GetSamplerParameter], [glconst TEXTURE_BORDER_COLOR].
>*/
__Vector<GLuint, 4> BorderColor(__TypeTag<GLuint>) const;
__Vector<GLint, 4> BorderColor(__TypeTag<GLint>) const;
void BorderColor(__Vector<GLfloat, 4> color); /*<
Sets the border color for this sampler object.
See [glfunc SamplerParameter], [glconst TEXTURE_BORDER_COLOR].
>*/
void BorderColor(__Vector<GLuint, 4> color);
void BorderColor(__Vector<GLint, 4> color);
__TextureCompareMode CompareMode(void) const; /*<
Returns the currently set texture compare mode of this sampler object.
See [glfunc GetSamplerParameter], [glconst TEXTURE_COMPARE_MODE].
>*/
void CompareMode(__TextureCompareMode mode); /*<
Sets the texture compare mode for this sampler object.
See [glfunc SamplerParameter], [glconst TEXTURE_COMPARE_MODE].
>*/
__CompareFunction CompareFunc(void) const; /*<
Returns the currently set texture compare function of this sampler object.
See [glfunc GetSamplerParameter], [glconst TEXTURE_COMPARE_FUNC].
>*/
void CompareFunc(__CompareFunction func); /*<
Sets the texture compare mode for this sampler object.
See [glfunc SamplerParameter], [glconst TEXTURE_COMPARE_FUNC].
>*/
__TextureMinFilter MinFilter(void) const; /*<
Returns the currently set texture minnification filter of this
sampler object.
See [glfunc GetSamplerParameter], [glconst TEXTURE_MIN_FILTER].
>*/
void MinFilter(__TextureMinFilter filter); /*<
Sets the texture minnification filter for this sampler object.
See [glfunc SamplerParameter], [glconst TEXTURE_MIN_FILTER].
>*/
__TextureMagFilter MagFilter(void) const; /*<
Returns the currently set texture magnification filter of this
sampler object.
See [glfunc GetSamplerParameter], [glconst TEXTURE_MAG_FILTER].
>*/
void MagFilter(__TextureMagFilter filter); /*<
Sets the texture magnification filter for this sampler object.
See [glfunc SamplerParameter], [glconst TEXTURE_MAG_FILTER].
>*/
void Filter(__TextureFilter filter) const; /*<
Sets both the minification and the magnification filter for
this sampler object.
See [glfunc SamplerParameter], [glconst TEXTURE_MIN_FILTER],
[glconst TEXTURE_MAG_FILTER].
>*/
//]
//[oglplus_sampler_2
__TextureWrap Wrap(__TextureWrapCoord coord) const; /*<
Returns the currently set texture wrap mode on the specified
[^coord] of this sampler object.
See [glfunc GetSamplerParameter].
>*/
void Wrap(__TextureWrapCoord coord, __TextureWrap mode) /*<
Sets the texture wrap mode on the specified [^coord]
for this sampler object.
See [glfunc SamplerParameter].
>*/
__TextureWrap WrapS(void) const; /*<
Returns the currently set texture wrap mode on the [^S], [^T] and [^R]
coordinates of this sampler object.
See [glfunc GetSamplerParameter],
[glconst TEXTURE_WRAP_S],
[glconst TEXTURE_WRAP_T],
[glconst TEXTURE_WRAP_R].
>*/
TextureWrap WrapT(void) const;
TextureWrap WrapR(void) const;
void WrapS(__TextureWrap mode); /*<
Sets the texture wrap mode on the [^S], [^T] and [^R]
coordinates for this sampler object.
See [glfunc SamplerParameter],
[glconst TEXTURE_WRAP_S],
[glconst TEXTURE_WRAP_T],
[glconst TEXTURE_WRAP_R].
>*/
void WrapT(TextureWrap mode);
void WrapR(TextureWrap mode);
GLfloat LODBias(void) const; /*<
Returns the currently set texture level-of-detail bias value
of this sampler object.
See [glfunc GetSamplerParameter], [glconst TEXTURE_LOD_BIAS].
>*/
void LODBias(GLfloat value); /*<
Sets the texture level-of-detail bias value for this sampler object.
See [glfunc SamplerParameter], [glconst TEXTURE_LOD_BIAS].
>*/
GLfloat MinLOD(void) const; /*<
Returns the currently set minimum texture level-of-detail value
of this sampler object.
See [glfunc GetSamplerParameter], [glconst TEXTURE_MIN_LOD].
>*/
void MinLOD(GLfloat value); /*<
Sets the minimal texture level-of-detail value for this sampler object.
See [glfunc SamplerParameter], [glconst TEXTURE_MIN_LOD].
>*/
GLfloat MaxLOD(void) const; /*<
Returns the currently set maximum texture level-of-detail value
of this sampler object.
See [glfunc GetSamplerParameter], [glconst TEXTURE_MAX_LOD].
>*/
void MaxLOD(GLfloat value); /*<
Sets the maximal texture level-of-detail value for this sampler object.
See [glfunc SamplerParameter], [glconst TEXTURE_MAX_LOD].
>*/
#if GL_ARB_seamless_cubemap_per_texture
__Boolean Seamless(void) const; /*<
Returns the value of the seamless-cube map setting of this
sampler object.
See [glfunc GetSamplerParameter], [glconst TEXTURE_CUBE_MAP_SEAMLESS].
>*/
void Seamless(__Boolean enable); /*<
Sets the seamless cubemap setting for this sampler object.
See [glfunc SamplerParameter], [glconst TEXTURE_CUBE_MAP_SEAMLESS].
>*/
#endif
};
//]
//[oglplus_sampler_def
typedef ObjectOps<__tag_DirectState, __tag_Sampler>
SamplerOps;
typedef __Object<SamplerOps> Sampler;
typedef __ObjectZero<__ObjZeroOps<__tag_DirectState, __tag_Sampler>>
NoSampler;
//]
//[oglplus_sampler_sugar
struct SamplerOpsAndSlot { };
SamplerOpsAndSlot operator | (
SamplerOps& sam,
GLuint slot
);
SamplerOps& operator << (
SamplerOps& sam,
__TextureUnitSelector tus
); /*< Bind >*/
SamplerOps& operator << (
SamplerOps& sam,
__TextureFilter filter
); /*< Filter >*/
SamplerOps& operator << (
SamplerOps& sam,
__TextureMinFilter filter
); /*< MinFilter >*/
SamplerOps& operator << (
SamplerOps& sam,
__TextureMagFilter filter
); /*< MagFilter >*/
SamplerOps& operator << (
SamplerOps& sam,
__TextureCompareMode mode
); /*< CompareMode >*/
SamplerOps& operator << (
SamplerOps& sam,
__CompareFunction func
); /*< CompareFunc >*/
{
sam.CompareFunc(func);
return sam;
}
SamplerOps& operator << (
SamplerOps& sam,
__TextureWrap wrap
); /*< Wrap mode on all coordinates >*/
SamplerOps& operator << (
SamplerOpsAndSlot sas,
__TextureWrap wrap
); /*< Wrap mode on the i-th coordinate >*/
template <typename T>
SamplerOps& operator << (
SamplerOps& sam,
const Vector<T, 4>& col
); /*< Border color >*/
} // namespace oglplus
//]
| 28.872 | 75 | 0.752147 | [
"object",
"vector"
] |
aa21dae40e8776091ec6b484841e721ac1542a22 | 865 | cpp | C++ | 0094_BinaryTreeInorderTraversal(iterative).cpp | taro-masuda/leetcode | 39739e9fec7c66513b114c740ef982ccc09dc39f | [
"MIT"
] | null | null | null | 0094_BinaryTreeInorderTraversal(iterative).cpp | taro-masuda/leetcode | 39739e9fec7c66513b114c740ef982ccc09dc39f | [
"MIT"
] | null | null | null | 0094_BinaryTreeInorderTraversal(iterative).cpp | taro-masuda/leetcode | 39739e9fec7c66513b114c740ef982ccc09dc39f | [
"MIT"
] | 1 | 2020-03-18T05:23:40.000Z | 2020-03-18T05:23:40.000Z | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> DFS(TreeNode* root) {
vector<int> out;
if (root == NULL) return out;
set<TreeNode*> visited;
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode* cur = s.top();
if (cur->left != NULL && visited.find(cur->left) == visited.end()) {s.push(cur->left); continue;}
else {out.push_back(cur->val); visited.insert(cur); s.pop();}
if (cur->right != NULL) s.push(cur->right);
}
return out;
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> out = DFS(root);
return out;
}
};
| 26.212121 | 109 | 0.521387 | [
"vector"
] |
aa223ac960de6e77842411c364a19701af3b31f7 | 11,439 | cpp | C++ | src/gui/gl/treerenderer.cpp | mhough/braingl | 53e2078adc10731ee62feec11dcb767c4c6c0d35 | [
"MIT"
] | 5 | 2016-03-17T07:02:11.000Z | 2021-12-12T14:43:58.000Z | src/gui/gl/treerenderer.cpp | mhough/braingl | 53e2078adc10731ee62feec11dcb767c4c6c0d35 | [
"MIT"
] | null | null | null | src/gui/gl/treerenderer.cpp | mhough/braingl | 53e2078adc10731ee62feec11dcb767c4c6c0d35 | [
"MIT"
] | 3 | 2015-10-29T15:21:01.000Z | 2020-11-25T09:41:21.000Z | /*
* TreeRenderer.cpp
*
* Created on: 17.09.2013
* @author Ralph Schurade
*/
#include "treerenderer.h"
#include "../gl/glfunctions.h"
#include "../../algos/tree.h"
#include "../../data/enums.h"
#include "../../data/models.h"
#include "../../data/vptr.h"
#include "../../data/datasets/datasettree.h"
#include <QDebug>
#include <QGLShaderProgram>
#include "math.h"
TreeRenderer::TreeRenderer( QString name, Tree* tree ) :
m_name( name ),
m_tree( tree ),
vboIds( new GLuint[ 2 ] ),
m_width( 0 ),
m_height( 0 ),
m_dirty( true ),
m_colorIndex( 0 ),
m_selected( -1 ),
m_numLeaves( 0 ),
m_pi( 3.14159265358979323846 ),
m_radius( 500.0f )
{
}
TreeRenderer::~TreeRenderer()
{
}
void TreeRenderer::init()
{
initializeOpenGLFunctions();
glGenBuffers( 2, vboIds );
}
void TreeRenderer::initGL()
{
}
void TreeRenderer::draw( QMatrix4x4 mvpMatrix )
{
if( m_dirty )
{
initGeometry();
}
if ( !m_tree )
{
return;
}
GLFunctions::getShader( "line" )->bind();
GLFunctions::getShader( "line" )->setUniformValue( "mvp_matrix", mvpMatrix );
// Tell OpenGL which VBOs to use
glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 0 ] );
// Draw cube geometry using indices from VBO 0
// Tell OpenGL programmable pipeline how to locate vertex position data
int vertexLocation = GLFunctions::getShader( "line" )->attributeLocation( "a_position" );
GLFunctions::getShader( "line" )->enableAttributeArray( vertexLocation );
glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, 0, 0 );
// Tell OpenGL which VBOs to use
glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
// Draw cube geometry using indices from VBO 1
int colorLocation = GLFunctions::getShader( "line" )->attributeLocation( "a_color" );
GLFunctions::getShader( "line" )->enableAttributeArray( colorLocation );
glVertexAttribPointer( colorLocation, 4, GL_FLOAT, GL_FALSE, 0, 0 );
// Draw cube geometry using indices from VBO 0
glDrawArrays( GL_LINES, 0 , m_verts.size() / 2 );
}
void TreeRenderer::initGeometry()
{
m_verts.clear();
m_colors.clear();
m_numLeaves = m_tree->getNumLeaves();
initGeometryRec( m_tree, 0, m_numLeaves );
//initGeometryCircleRec( m_tree, 0, m_numLeaves );
// Transfer vertex data to VBO 3
glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 0 ] );
glBufferData( GL_ARRAY_BUFFER, m_verts.size() * sizeof( float ), m_verts.data(), GL_STATIC_DRAW );
// Transfer vertex data to VBO 3
glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
glBufferData( GL_ARRAY_BUFFER, m_colors.size() * sizeof( float ), m_colors.data(), GL_STATIC_DRAW );
m_dirty = false;
}
void TreeRenderer::initGeometryRec( Tree* tree, int left, int right )
{
QList<Tree*> children = tree->getChildren();
int offset = 0;
for ( int i = 0; i < children.size(); ++i )
{
Tree* child = children[i];
int size = child->getNumLeaves();
if ( size > 1 )
{
m_verts.push_back( left + ( right - left ) / 2 );
m_verts.push_back( tree->getValue() );
m_verts.push_back( 0.0 );
m_verts.push_back( left + offset + size / 2 );
m_verts.push_back( tree->getValue() );
m_verts.push_back( 0.0 );
m_verts.push_back( left + offset + size / 2 );
m_verts.push_back( tree->getValue() );
m_verts.push_back( 0.0 );
m_verts.push_back( left + offset + size / 2 );
m_verts.push_back( child->getValue() );
m_verts.push_back( 0.0 );
QColor color = tree->getColor( m_colorIndex );
if ( tree->getId() == m_selected )
{
QColor color1 = tree->getColor( 1 );
m_colors.push_back( color1.redF() );
m_colors.push_back( color1.greenF() );
m_colors.push_back( color1.blueF() );
m_colors.push_back( 1.0 );
m_colors.push_back( color1.redF() );
m_colors.push_back( color1.greenF() );
m_colors.push_back( color1.blueF() );
m_colors.push_back( 1.0 );
}
else
{
m_colors.push_back( color.redF() );
m_colors.push_back( color.greenF() );
m_colors.push_back( color.blueF() );
m_colors.push_back( 1.0 );
m_colors.push_back( color.redF() );
m_colors.push_back( color.greenF() );
m_colors.push_back( color.blueF() );
m_colors.push_back( 1.0 );
}
m_colors.push_back( color.redF() );
m_colors.push_back( color.greenF() );
m_colors.push_back( color.blueF() );
m_colors.push_back( 1.0 );
m_colors.push_back( color.redF() );
m_colors.push_back( color.greenF() );
m_colors.push_back( color.blueF() );
m_colors.push_back( 1.0 );
}
else
{
m_verts.push_back( left + ( right - left ) / 2 );
m_verts.push_back( tree->getValue() );
m_verts.push_back( 0.0 );
m_verts.push_back( left + offset + size / 2 );
m_verts.push_back( child->getValue() );
m_verts.push_back( 0.0 );
QColor color = tree->getColor( m_colorIndex );
m_colors.push_back( color.redF() );
m_colors.push_back( color.greenF() );
m_colors.push_back( color.blueF() );
m_colors.push_back( 1.0 );
m_colors.push_back( color.redF() );
m_colors.push_back( color.greenF() );
m_colors.push_back( color.blueF() );
m_colors.push_back( 1.0 );
}
initGeometryRec( child, left + offset, left + offset + size );
offset += size;
}
}
void TreeRenderer::initGeometryCircleRec( Tree* tree, int left, int right )
{
QList<Tree*> children = tree->getChildren();
int offset = 0;
for ( int i = 0; i < children.size(); ++i )
{
Tree* child = children[i];
int size = child->getNumLeaves();
if ( size > 1 )
{
float deg = ( (double)( left + ( right - left ) / 2 ) / (double)m_numLeaves ) * m_pi * 2.0;
float x = sin( deg ) * ( ( 1.0 - tree->getValue() ) * m_radius );
float y = cos( deg ) * ( ( 1.0 - tree->getValue() ) * m_radius );;
m_verts.push_back( x );
m_verts.push_back( y );
m_verts.push_back( 0.0 );
deg = ( (double)( left + offset + size / 2 ) / (double)m_numLeaves ) * m_pi * 2.0;
x = sin( deg ) * ( ( 1.0 - tree->getValue() ) * m_radius );
y = cos( deg ) * ( ( 1.0 - tree->getValue() ) * m_radius );;
m_verts.push_back( x );
m_verts.push_back( y );
m_verts.push_back( 0.0 );
deg = ( (double)( left + offset + size / 2 ) / (double)m_numLeaves ) * m_pi * 2.0;
x = sin( deg ) * ( ( 1.0 - tree->getValue() ) * m_radius );
y = cos( deg ) * ( ( 1.0 - tree->getValue() ) * m_radius );;
m_verts.push_back( x );
m_verts.push_back( y );
m_verts.push_back( 0.0 );
deg = ( (double)( left + offset + size / 2 ) / (double)m_numLeaves ) * m_pi * 2.0;
x = sin( deg ) * ( ( 1.0 - child->getValue() ) * m_radius );
y = cos( deg ) * ( ( 1.0 - child->getValue() ) * m_radius );;
m_verts.push_back( x );
m_verts.push_back( y );
m_verts.push_back( 0.0 );
QColor color = tree->getColor( m_colorIndex );
if ( tree->getId() == m_selected )
{
QColor color1 = tree->getColor( 1 );
m_colors.push_back( color1.redF() );
m_colors.push_back( color1.greenF() );
m_colors.push_back( color1.blueF() );
m_colors.push_back( 1.0 );
m_colors.push_back( color1.redF() );
m_colors.push_back( color1.greenF() );
m_colors.push_back( color1.blueF() );
m_colors.push_back( 1.0 );
}
else
{
m_colors.push_back( color.redF() );
m_colors.push_back( color.greenF() );
m_colors.push_back( color.blueF() );
m_colors.push_back( 1.0 );
m_colors.push_back( color.redF() );
m_colors.push_back( color.greenF() );
m_colors.push_back( color.blueF() );
m_colors.push_back( 1.0 );
}
m_colors.push_back( color.redF() );
m_colors.push_back( color.greenF() );
m_colors.push_back( color.blueF() );
m_colors.push_back( 1.0 );
m_colors.push_back( color.redF() );
m_colors.push_back( color.greenF() );
m_colors.push_back( color.blueF() );
m_colors.push_back( 1.0 );
}
else
{
float deg = ( (double)( left + ( right - left ) / 2 ) / (double)m_numLeaves ) * m_pi * 2.0;
float x = sin( deg ) * ( ( 1.0 - tree->getValue() ) * m_radius );
float y = cos( deg ) * ( ( 1.0 - tree->getValue() ) * m_radius );;
m_verts.push_back( x * ( ( 1.0 - tree->getValue() ) * m_radius ) );
m_verts.push_back( y * ( ( 1.0 - tree->getValue() ) * m_radius ) );
m_verts.push_back( 0.0 );
m_verts.push_back( x * ( ( 1.0 - child->getValue() ) * m_radius ) );
m_verts.push_back( y * ( ( 1.0 - child->getValue() ) * m_radius ) );
m_verts.push_back( 0.0 );
QColor color = tree->getColor( m_colorIndex );
m_colors.push_back( color.redF() );
m_colors.push_back( color.greenF() );
m_colors.push_back( color.blueF() );
m_colors.push_back( 1.0 );
m_colors.push_back( color.redF() );
m_colors.push_back( color.greenF() );
m_colors.push_back( color.blueF() );
m_colors.push_back( 1.0 );
}
initGeometryCircleRec( child, left + offset, left + offset + size );
offset += size;
}
}
void TreeRenderer::resizeGL( int width, int height )
{
m_width = width;
m_height = height;
}
void TreeRenderer::leftMouseDown( int x, int y )
{
}
void TreeRenderer::leftMouseDrag( int x, int y )
{
leftMouseDown( x, y );
}
void TreeRenderer::setShaderVars()
{
}
void TreeRenderer::mouseWheel( int step )
{
// m_zoom += step;
// m_zoom = qMax( 1, m_zoom );
}
void TreeRenderer::middleMouseDown( int x, int y )
{
// m_moveXOld = m_moveX;
// m_moveYOld = m_moveY;
// m_middleDownX = x;
// m_middleDownY = y;
}
void TreeRenderer::middleMouseDrag( int x, int y )
{
// m_moveX = m_moveXOld - ( m_middleDownX - x );
// m_moveY = m_moveYOld + m_middleDownY - y;
}
void TreeRenderer::update()
{
m_dirty = true;
}
| 32.776504 | 104 | 0.524958 | [
"geometry"
] |
aa22b69bc1f3700bdaa078969536653c70f1e76f | 828 | cpp | C++ | OIandACM/OJ/LeetCode/first/easy-53-最大子序和.cpp | ASC8384/MyCodeSnippets | aa74afa85672601bd25bf625590f26ac909b2042 | [
"CC0-1.0"
] | 8 | 2019-08-09T14:28:13.000Z | 2021-02-23T03:22:15.000Z | OIandACM/OJ/LeetCode/first/easy-53-最大子序和.cpp | ASC8384/MyCodeSnippets | aa74afa85672601bd25bf625590f26ac909b2042 | [
"CC0-1.0"
] | null | null | null | OIandACM/OJ/LeetCode/first/easy-53-最大子序和.cpp | ASC8384/MyCodeSnippets | aa74afa85672601bd25bf625590f26ac909b2042 | [
"CC0-1.0"
] | 4 | 2019-08-16T12:00:41.000Z | 2019-11-29T12:01:17.000Z | /*
* @lc app=leetcode.cn id=53 lang=cpp
*
* [53] 最大子序和
*
* https://leetcode-cn.com/problems/maximum-subarray/description/
*
* algorithms
* Easy (50.21%)
* Likes: 1845
* Dislikes: 0
* Total Accepted: 207.6K
* Total Submissions: 413.3K
* Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]'
*
* 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
*
* 示例:
*
* 输入: [-2,1,-3,4,-1,2,1,-5,4],
* 输出: 6
* 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
*
*
* 进阶:
*
* 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
*
*/
// @lc code=start
class Solution {
public:
int maxSubArray(vector<int> &nums) {
int ll = nums.size();
if(ll == 0)
return 0;
int ans = nums[0];
int tmp = nums[0];
for(int i = 1; i < ll; i++) {
tmp = max(tmp + nums[i], nums[i]);
ans = max(ans, tmp);
}
return max(ans, tmp);
}
};
// @lc code=end
| 17.25 | 65 | 0.560386 | [
"vector"
] |
aa22f3dcb4d0eb16daabc945bbc9333f44b5e25d | 4,672 | hpp | C++ | src/ngraph/runtime/intelgpu/intelgpu_op_batchnorm.hpp | srinivasputta/ngraph | 7506133fff4a8e5c25914a8370a567c4da5b53be | [
"Apache-2.0"
] | null | null | null | src/ngraph/runtime/intelgpu/intelgpu_op_batchnorm.hpp | srinivasputta/ngraph | 7506133fff4a8e5c25914a8370a567c4da5b53be | [
"Apache-2.0"
] | null | null | null | src/ngraph/runtime/intelgpu/intelgpu_op_batchnorm.hpp | srinivasputta/ngraph | 7506133fff4a8e5c25914a8370a567c4da5b53be | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include <CPP/topology.hpp>
#include "ngraph/shape.hpp"
#include "ngraph/type/element_type.hpp"
namespace ngraph
{
namespace runtime
{
namespace intelgpu
{
// This implements BatchNorm nGraph operation
// nGraph uses channels in this operation but clDNN uses full input data
void do_batch_norm_operation(cldnn::topology& topology,
const std::string& output_name,
const element::Type& output_type,
double eps,
const std::string& input_name,
const Shape& input_shape,
const std::string& gamma_name,
const std::string& beta_name,
const std::string& mean_name,
const std::string& variance_name);
// This creates mean of the input matrix by Channel axis
void do_create_mean(cldnn::topology& topology,
const std::string& output_name,
const element::Type& output_type,
const std::string& input_name,
const Shape& input_shape,
bool backward);
// This creates variance of the input matrix by Channel axis
void do_create_variance(cldnn::topology& topology,
const std::string& output_name,
const element::Type& output_type,
const std::string& input_name,
const Shape& input_shape,
const std::string& mean_name);
// This creates variance backprop of the input matrix by Channel axis
void do_create_variance_back(cldnn::topology& topology,
const std::string& output_name,
const element::Type& output_type,
double eps,
const std::string& input_name,
const Shape& input_shape,
const std::string& mean_name,
const std::string& variance_name,
const std::string& delta_name);
// This function uses "shape" parameter as input or output Shape
// Shape of all other calculated as first axis from the left
// Example: output[ 4, 3, 2, 8 ] means out_gamma[ 3 ]
void do_batch_norm_backprop_operation(cldnn::topology& topology,
const Shape& shape,
const element::Type& type,
const std::string& gamma_name,
const std::string& beta_name,
const std::string& input_name,
const std::string& mean_name,
const std::string& variance_name,
const std::string& delta_name,
double eps,
const std::string& output_name,
const std::string& output_gamma_name,
const std::string& output_beta_name);
}
}
}
| 52.494382 | 87 | 0.444349 | [
"shape"
] |
aa289892fcef9410488c8701e16cd9cbc039c988 | 27,066 | cpp | C++ | test/structure/math/polynom_modx_test.cpp | plamenko/altruct | e16fc162043933fbe282fe01a44e0c908df4f612 | [
"MIT"
] | 66 | 2016-10-18T20:37:09.000Z | 2021-11-28T09:56:41.000Z | test/structure/math/polynom_modx_test.cpp | plamenko/altruct | e16fc162043933fbe282fe01a44e0c908df4f612 | [
"MIT"
] | null | null | null | test/structure/math/polynom_modx_test.cpp | plamenko/altruct | e16fc162043933fbe282fe01a44e0c908df4f612 | [
"MIT"
] | 4 | 2018-02-11T17:56:03.000Z | 2019-01-18T15:41:15.000Z | #include "altruct/algorithm/collections/collections.h"
#include "altruct/algorithm/math/fft.h"
#include "altruct/structure/math/polynom.h"
#include "altruct/structure/math/modulo.h"
#include "structure_test_util.h"
#include "gtest/gtest.h"
using namespace std;
using namespace altruct::math;
using namespace altruct::collections;
using namespace altruct::test_util;
namespace {
typedef moduloX<int> modx;
typedef polynom<modx> polyx;
const int M = 1012924417;
vector<moduloX<int>> to_modx(int M, const vector<int>& v) {
return transform(v, [&](int a) {
return moduloX<int>(a, M);
});
}
polyx make_polyx(int M, const vector<int>& v) {
polyx p(to_modx(M, v));
p.ZERO_COEFF = modx(0, M);
return p;
}
}
namespace altruct {
namespace math {
template<>
struct polynom_mul<modx> {
static void _mul_fft(modx* pr, int lr, const modx* p1, int l1, const modx* p2, int l2) {
// We can do FFT because of a suitable modulus; 198 ^ (1 << 21) == 1 (mod 1012924417)
// For a general modulus, we would need to compute several convolutions,
// each with a suitable modulus, and then combine the results with CRT.
// Alternatively, one can use complex numbers and break down the input
// coefficients into 16bit or 11bit words for precission to suffice.
auto r = convolution<modx>(p1, p1 + l1 + 1, p2, p2 + l2 + 1, modx(198, M), 1 << 21);
r.resize(lr + 1, modx(0, M)); copy(r.begin(), r.end(), pr);
}
static void impl(modx* pr, int lr, const modx* p1, int l1, const modx* p2, int l2) {
if (l2 < 16) {
polyx::_mul_long(pr, lr, p1, l1, p2, l2);
} else if (int64_t(l1) * l2 < 300000) {
polyx::_mul_karatsuba(pr, lr, p1, l1, p2, l2);
} else {
_mul_fft(pr, lr, p1, l1, p2, l2);
}
}
};
}
}
TEST(polynom_modx_test, constructor) {
const vector<modx> c = to_modx(1009, { 1, 2, 3, 4 });
polyx p0;
EXPECT_EQ(to_modx(1, { 0 }), p0.c);
EXPECT_EQ(0, p0.ZERO_COEFF.v);
EXPECT_EQ(1, p0.ZERO_COEFF.M());
polyx p1(modx(5, 1009));
EXPECT_EQ(to_modx(1009, { 5 }), p1.c);
EXPECT_EQ(0, p1.ZERO_COEFF.v);
EXPECT_EQ(1009, p1.ZERO_COEFF.M());
polyx q1(5);
EXPECT_EQ((vector<modx>{ 5 }), q1.c);
EXPECT_EQ(0, q1.ZERO_COEFF.v);
EXPECT_EQ(1, q1.ZERO_COEFF.M());
polyx p2(c);
EXPECT_EQ(c, p2.c);
EXPECT_EQ(0, p2.ZERO_COEFF.v);
EXPECT_EQ(1009, p2.ZERO_COEFF.M());
polyx p3(p2);
EXPECT_EQ(c, p3.c);
EXPECT_EQ(0, p3.ZERO_COEFF.v);
EXPECT_EQ(1009, p3.ZERO_COEFF.M());
polyx p4(c.begin(), c.end());
EXPECT_EQ(c, p4.c);
EXPECT_EQ(0, p4.ZERO_COEFF.v);
EXPECT_EQ(1009, p4.ZERO_COEFF.M());
polyx p5(&c[0], &c[0] + c.size());
EXPECT_EQ(c, p5.c);
EXPECT_EQ(0, p5.ZERO_COEFF.v);
EXPECT_EQ(1009, p5.ZERO_COEFF.M());
polyx p6(c.end(), c.end());
EXPECT_EQ((vector<modx> { }), p6.c);
EXPECT_EQ(0, p6.ZERO_COEFF.v);
EXPECT_EQ(1, p6.ZERO_COEFF.M());
polyx p7{ modx(1, 1009), modx(2, 1009), modx(3, 1009), modx(4, 1009) };
EXPECT_EQ(c, p7.c);
EXPECT_EQ(0, p7.ZERO_COEFF.v);
EXPECT_EQ(1009, p7.ZERO_COEFF.M());
polyx q7{}; // this calls default constructor!
EXPECT_EQ(to_modx(1, { 0 }), q7.c);
EXPECT_EQ(0, q7.ZERO_COEFF.v);
EXPECT_EQ(1, q7.ZERO_COEFF.M());
polyx p8(to_modx(1009, { 1, 2, 3, 4 }));
EXPECT_EQ(c, p8.c);
EXPECT_EQ(0, p8.ZERO_COEFF.v);
EXPECT_EQ(1009, p8.ZERO_COEFF.M());
polyx q8(to_modx(1009, {}));
EXPECT_EQ(to_modx(1, {}), q8.c);
EXPECT_EQ(0, q8.ZERO_COEFF.v);
EXPECT_EQ(1, q8.ZERO_COEFF.M());
polyx p9(make_polyx(1009, { 1, 2, 3, 4 }));
EXPECT_EQ(c, p9.c);
EXPECT_EQ(0, p9.ZERO_COEFF.v);
EXPECT_EQ(1009, p9.ZERO_COEFF.M());
polyx q9(polyx(c.end(), c.end()));
EXPECT_EQ(to_modx(1, {}), q9.c);
EXPECT_EQ(0, q9.ZERO_COEFF.v);
EXPECT_EQ(1, q9.ZERO_COEFF.M());
}
TEST(polynom_modx_test, swap) {
auto p1 = make_polyx(1009, { 1, 2, 3, 4 });
auto p2 = make_polyx(1003, { 5, 6, 7 });
p1.swap(p2);
EXPECT_EQ(to_modx(1003, { 5, 6, 7 }), p1.c);
EXPECT_EQ(0, p1.ZERO_COEFF.v);
EXPECT_EQ(1003, p1.ZERO_COEFF.M());
EXPECT_EQ(to_modx(1009, { 1, 2, 3, 4 }), p2.c);
EXPECT_EQ(0, p2.ZERO_COEFF.v);
EXPECT_EQ(1009, p2.ZERO_COEFF.M());
}
TEST(polynom_modx_test, shrink_to_fit) {
auto p = make_polyx(1009, { 1, 2, 3, 4, 0, 0 });
EXPECT_EQ(6, p.c.size());
p.shrink_to_fit();
EXPECT_EQ(4, p.c.size());
EXPECT_EQ(to_modx(1009, { 1, 2, 3, 4 }), p.c);
}
TEST(polynom_modx_test, reserve) {
auto p = make_polyx(1009, { 1, 2, 3, 4 });
EXPECT_EQ(4, p.c.size());
p.reserve(6);
EXPECT_EQ(6, p.c.size());
EXPECT_EQ(to_modx(1009, { 1, 2, 3, 4, 0, 0 }), p.c);
}
TEST(polynom_modx_test, resize) {
auto p = make_polyx(1009, { 1, 2, 3, 4, 5 });
EXPECT_EQ(5, p.c.size());
p.resize(3);
EXPECT_EQ(3, p.c.size());
EXPECT_EQ(to_modx(1009, { 1, 2, 3 }), p.c);
p.resize(6);
EXPECT_EQ(6, p.c.size());
EXPECT_EQ(to_modx(1009, { 1, 2, 3, 0, 0, 0 }), p.c);
}
TEST(polynom_modx_test, size) {
auto p = make_polyx(1009, { 1, 2, 3, 4 });
EXPECT_EQ(4, p.size());
}
TEST(polynom_modx_test, at) {
const auto p = make_polyx(1009, { 2, 3, 5, 7 });
EXPECT_EQ(modx(2, 1009), p.at(0));
EXPECT_EQ(modx(7, 1009), p.at(3));
EXPECT_EQ(modx(0, 1009), p.at(4));
EXPECT_EQ(modx(0, 1009), p.at(100));
EXPECT_EQ(4, p.size());
}
TEST(polynom_modx_test, operator_const_brackets) {
const auto p = make_polyx(1009, { 2, 3, 5, 7 });
EXPECT_EQ(modx(2, 1009), p[0]);
EXPECT_EQ(modx(7, 1009), p[3]);
EXPECT_EQ(modx(0, 1009), p[4]);
EXPECT_EQ(modx(0, 1009), p[100]);
EXPECT_EQ(4, p.size());
}
TEST(polynom_modx_test, operator_brackets) {
auto p = make_polyx(1009, {});
p[3] = modx(3, 1009);
EXPECT_EQ(modx(0, 1009), p[0]);
EXPECT_EQ(modx(0, 1009), p[4]);
EXPECT_EQ(modx(3, 1009), p[3]);
EXPECT_EQ(modx(0, 1009), p[4]);
EXPECT_EQ(modx(0, 1009), p[100]);
EXPECT_EQ(101, p.size());
}
TEST(polynom_modx_test, degree) {
const auto p1 = make_polyx(1009, {});
EXPECT_EQ(0, p1.deg());
const auto p2 = make_polyx(1009, { 4 });
EXPECT_EQ(0, p2.deg());
const auto p3 = make_polyx(1009, { 0, 3 });
EXPECT_EQ(1, p3.deg());
const auto p4 = make_polyx(1009, { 2, 3, 5, 7 });
EXPECT_EQ(3, p4.deg());
const auto p5 = make_polyx(1009, { 2, 3, 5, 7, 0, 0 });
EXPECT_EQ(3, p5.deg());
}
TEST(polynom_modx_test, lowest) {
const auto p1 = make_polyx(1009, {});
EXPECT_EQ(0, p1.lowest());
const auto p2 = make_polyx(1009, { 4 });
EXPECT_EQ(0, p2.lowest());
const auto p3 = make_polyx(1009, { 0, 3 });
EXPECT_EQ(1, p3.lowest());
const auto p4 = make_polyx(1009, { 2, 3, 5, 7 });
EXPECT_EQ(0, p4.lowest());
const auto p5 = make_polyx(1009, { 0, 0, 2, 3, 5, 7 });
EXPECT_EQ(2, p5.lowest());
}
TEST(polynom_modx_test, leading_coefficient) {
const auto p1 = make_polyx(1009, {});
EXPECT_EQ(modx(0, 1), p1.leading_coeff());
const auto p2 = make_polyx(1009, { 4 });
EXPECT_EQ(modx(4, 1009), p2.leading_coeff());
const auto p3 = make_polyx(1009, { 0, 3 });
EXPECT_EQ(modx(3, 1009), p3.leading_coeff());
const auto p4 = make_polyx(1009, { 2, 3, 5, 7 });
EXPECT_EQ(modx(7, 1009), p4.leading_coeff());
const auto p5 = make_polyx(1009, { 2, 3, 5, 7, 0, 0 });
EXPECT_EQ(modx(7, 1009), p5.leading_coeff());
}
TEST(polynom_modx_test, is_power) {
auto p1 = make_polyx(1009, {});
EXPECT_FALSE(p1.is_power());
const auto p2 = make_polyx(1009, { 4 });
EXPECT_FALSE(p2.is_power());
const auto p3 = make_polyx(1009, { 1 });
EXPECT_TRUE(p3.is_power());
const auto p4 = make_polyx(1009, { 0, 0, 0, 3 });
EXPECT_FALSE(p4.is_power());
const auto p5 = make_polyx(1009, { 0, 0, 0, 1 });
EXPECT_TRUE(p5.is_power());
const auto p6 = make_polyx(1009, { 0, 0, 0, 1, 0 });
EXPECT_TRUE(p6.is_power());
}
TEST(polynom_modx_test, cmp) {
const auto p0 = make_polyx(1009, {});
const auto p1 = make_polyx(1009, { 4 });
const auto p2 = make_polyx(1009, { 1, 3, 5, 7 });
const auto p3 = make_polyx(1009, { 2, 3, 5, 7 });
const auto p4 = make_polyx(1009, { 2, 3, 5, 7, 0, 0 });
const auto p5 = make_polyx(1009, { 2, 3, 6, 7 });
EXPECT_EQ(0, polyx::cmp(p0, p0));
EXPECT_EQ(-1, polyx::cmp(p0, p1));
EXPECT_EQ(+1, polyx::cmp(p1, p0));
EXPECT_EQ(0, polyx::cmp(p1, p1));
EXPECT_EQ(-1, polyx::cmp(p0, p2));
EXPECT_EQ(+1, polyx::cmp(p2, p0));
EXPECT_EQ(-1, polyx::cmp(p1, p2));
EXPECT_EQ(+1, polyx::cmp(p2, p1));
EXPECT_EQ(0, polyx::cmp(p2, p2));
EXPECT_EQ(-1, polyx::cmp(p2, p3));
EXPECT_EQ(+1, polyx::cmp(p3, p2));
EXPECT_EQ(0, polyx::cmp(p3, p4));
EXPECT_EQ(0, polyx::cmp(p4, p3));
EXPECT_EQ(-1, polyx::cmp(p4, p5));
EXPECT_EQ(+1, polyx::cmp(p5, p4));
}
TEST(polynom_modx_test, neg) {
const auto p0 = make_polyx(1009, {});
const auto p1 = make_polyx(1009, { 4 });
const auto p2 = make_polyx(1009, { 1, -3, 5, 7 });
const auto p3 = make_polyx(1009, { 2, 3, 5, -7, 0, 0 });
polyx pr;
polyx::neg(pr, p0);
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::neg(pr, p1);
EXPECT_EQ(make_polyx(1009, { -4 }), pr);
polyx::neg(pr, p2);
EXPECT_EQ(make_polyx(1009, { -1, 3, -5, -7 }), pr);
polyx::neg(pr, p3);
EXPECT_EQ(make_polyx(1009, { -2, -3, -5, 7 }), pr);
// inplace
polyx::neg(pr, pr);
EXPECT_EQ(make_polyx(1009, { 2, 3, 5, -7 }), pr);
}
TEST(polynom_modx_test, add) {
const auto p0 = make_polyx(1009, {});
const auto p1 = make_polyx(1009, { 4 });
const auto p2 = make_polyx(1009, { 1, -3, 5, 7 });
const auto p3 = make_polyx(1009, { 2, 3, 5, -7, 0, 0 });
polyx pr;
polyx::add(pr, p0, p0);
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::add(pr, p0, p1);
EXPECT_EQ(make_polyx(1009, { 4 }), pr);
polyx::add(pr, p1, p0);
EXPECT_EQ(make_polyx(1009, { 4 }), pr);
polyx::add(pr, p1, p1);
EXPECT_EQ(make_polyx(1009, { 8 }), pr);
polyx::add(pr, p0, p2);
EXPECT_EQ(make_polyx(1009, { 1, -3, 5, 7 }), pr);
polyx::add(pr, p2, p0);
EXPECT_EQ(make_polyx(1009, { 1, -3, 5, 7 }), pr);
polyx::add(pr, p1, p2);
EXPECT_EQ(make_polyx(1009, { 5, -3, 5, 7 }), pr);
polyx::add(pr, p2, p1);
EXPECT_EQ(make_polyx(1009, { 5, -3, 5, 7 }), pr);
polyx::add(pr, p2, p3);
EXPECT_EQ(make_polyx(1009, { 3, 0, 10 }), pr);
polyx::add(pr, p3, p2);
EXPECT_EQ(make_polyx(1009, { 3, 0, 10 }), pr);
polyx::add(pr, p3, p3);
EXPECT_EQ(make_polyx(1009, { 4, 6, 10, -14 }), pr);
// inplace
pr = to_modx(1009, { 4, 6, 10, -14 });
polyx::add(pr, pr, p1);
EXPECT_EQ(make_polyx(1009, { 8, 6, 10, -14 }), pr);
polyx::add(pr, p1, pr);
EXPECT_EQ(make_polyx(1009, { 12, 6, 10, -14 }), pr);
polyx::add(pr, pr, pr);
EXPECT_EQ(make_polyx(1009, { 24, 12, 20, -28 }), pr);
}
TEST(polynom_modx_test, sub) {
const auto p0 = make_polyx(1009, {});
const auto p1 = make_polyx(1009, { 4 });
const auto p2 = make_polyx(1009, { 1, -3, 5, 7 });
const auto p3 = make_polyx(1009, { 2, 3, 5, -7, 0, 0 });
polyx pr;
polyx::sub(pr, p0, p0);
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::sub(pr, p0, p1);
EXPECT_EQ(make_polyx(1009, { -4 }), pr);
polyx::sub(pr, p1, p0);
EXPECT_EQ(make_polyx(1009, { 4 }), pr);
polyx::sub(pr, p1, p1);
EXPECT_EQ(make_polyx(1009, { }), pr);
polyx::sub(pr, p0, p2);
EXPECT_EQ(make_polyx(1009, { -1, 3, -5, -7 }), pr);
polyx::sub(pr, p2, p0);
EXPECT_EQ(make_polyx(1009, { 1, -3, 5, 7 }), pr);
polyx::sub(pr, p1, p2);
EXPECT_EQ(make_polyx(1009, { 3, 3, -5, -7 }), pr);
polyx::sub(pr, p2, p1);
EXPECT_EQ(make_polyx(1009, { -3, -3, 5, 7 }), pr);
polyx::sub(pr, p2, p3);
EXPECT_EQ(make_polyx(1009, { -1, -6, 0, 14 }), pr);
polyx::sub(pr, p3, p2);
EXPECT_EQ(make_polyx(1009, { 1, 6, 0, -14 }), pr);
polyx::sub(pr, p3, p3);
EXPECT_EQ(make_polyx(1009, { }), pr);
// inplace
pr = to_modx(1009, { 1, 6, 10, -14 });
polyx::sub(pr, pr, p1);
EXPECT_EQ(make_polyx(1009, { -3, 6, 10, -14 }), pr);
polyx::sub(pr, p1, pr);
EXPECT_EQ(make_polyx(1009, { 7, -6, -10, +14 }), pr);
polyx::sub(pr, pr, pr);
EXPECT_EQ(make_polyx(1009, {}), pr);
}
TEST(polynom_modx_test, mul) {
const auto p0 = make_polyx(1009, {});
const auto p1 = make_polyx(1009, { 4 });
const auto p2 = make_polyx(1009, { 1, -3, 5, 7 });
const auto p3 = make_polyx(1009, { 2, 3, 5, -7, 0, 0 });
polyx pr;
polyx::mul(pr, p0, p0);
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::mul(pr, p0, p1);
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::mul(pr, p1, p0);
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::mul(pr, p1, p1);
EXPECT_EQ(make_polyx(1009, { 16 }), pr);
polyx::mul(pr, p0, p2);
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::mul(pr, p2, p0);
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::mul(pr, p1, p2);
EXPECT_EQ(make_polyx(1009, { 4, -12, 20, 28 }), pr);
polyx::mul(pr, p2, p1);
EXPECT_EQ(make_polyx(1009, { 4, -12, 20, 28 }), pr);
polyx::mul(pr, p2, p3);
EXPECT_EQ(make_polyx(1009, { 2, -3, 6, 7, 67, 0, -49 }), pr);
polyx::mul(pr, p3, p2);
EXPECT_EQ(make_polyx(1009, { 2, -3, 6, 7, 67, 0, -49 }), pr);
polyx::mul(pr, p3, p3);
EXPECT_EQ(make_polyx(1009, { 4, 12, 29, 2, -17, -70, 49 }), pr);
// inplace
pr = make_polyx(1009, { 2, 3, 5, -7 });
polyx::mul(pr, pr, p1);
EXPECT_EQ(make_polyx(1009, { 8, 12, 20, -28 }), pr);
polyx::mul(pr, p1, pr);
EXPECT_EQ(make_polyx(1009, { 32, 48, 80, -112 }), pr);
polyx::mul(pr, pr, pr);
EXPECT_EQ(make_polyx(1009, { 1024, 3072, 7424, 512, -4352, -17920, 12544 }), pr);
}
template<typename P, typename F>
void do_mul(F mul, P& pr, const P& p1, const P& p2, int lr = -1) {
int l1 = p1.deg(), l2 = p2.deg(); if (lr < 0) lr = l1 + l2;
pr.resize(lr + 1, p1.ZERO_COEFF);
mul(pr.c.data(), lr, p1.c.data(), l1, p2.c.data(), l2);
}
TEST(polynom_modx_test, mul_size) {
auto p1 = make_polyx(M, {}); for (int l = 100; l >= 0; l--) p1[l] = modx(l, M) * (l + 1) / 2;
auto p2 = make_polyx(M, {}); for (int l = 80; l >= 0; l--) p2[l] = modx(l, M) * 3 + 5;
auto q11 = p1 * p1;
auto q12 = p1 * p2;
polyx q_long; do_mul(polyx::_mul_long, q_long, p1, p2);
EXPECT_EQ(q12, q_long);
polyx q_long_inplace = p1; do_mul(polyx::_mul_long, q_long_inplace, q_long_inplace, q_long_inplace);
EXPECT_EQ(q11, q_long_inplace);
polyx q_kar; do_mul(polyx::_mul_karatsuba, q_kar, p1, p2);
EXPECT_EQ(q12, q_kar);
polyx q_kar_inplace = p1; do_mul(polyx::_mul_karatsuba, q_kar_inplace, q_kar_inplace, q_kar_inplace);
EXPECT_EQ(q11, q_kar_inplace);
polyx q_fft; do_mul(polynom_mul<modx>::_mul_fft, q_fft, p1, p2);
EXPECT_EQ(q12, q_fft);
polyx q_fft_inplace = p1; do_mul(polynom_mul<modx>::_mul_fft, q_fft_inplace, q_fft_inplace, q_fft_inplace);
EXPECT_EQ(q11, q_fft_inplace);
polyx q11_150(q11.c.begin(), q11.c.begin() + 150 + 1);
polyx q12_150(q12.c.begin(), q12.c.begin() + 150 + 1);
polyx q_long_150; do_mul(polyx::_mul_long, q_long_150, p1, p2, 150);
EXPECT_EQ(q12_150, q_long_150);
polyx q_long_inplace_150 = p1; do_mul(polyx::_mul_long, q_long_inplace_150, q_long_inplace_150, q_long_inplace_150, 150);
EXPECT_EQ(q11_150, q_long_inplace_150);
polyx q_kar_150; do_mul(polyx::_mul_karatsuba, q_kar_150, p1, p2, 150);
EXPECT_EQ(q12_150, q_kar_150);
polyx q_kar_inplace_150 = p1; do_mul(polyx::_mul_karatsuba, q_kar_inplace_150, q_kar_inplace_150, q_kar_inplace_150, 150);
EXPECT_EQ(q11_150, q_kar_inplace_150);
polyx q_fft_150; do_mul(polynom_mul<modx>::_mul_fft, q_fft_150, p1, p2, 150);
EXPECT_EQ(q12_150, q_fft_150);
polyx q_fft_inplace_150 = p1; do_mul(polynom_mul<modx>::_mul_fft, q_fft_inplace_150, q_fft_inplace_150, q_fft_inplace_150, 150);
EXPECT_EQ(q11_150, q_fft_inplace_150);
}
TEST(polynom_modx_test, quot_rem) {
const auto p0 = make_polyx(1009, {});
const auto p1 = make_polyx(1009, { 6 });
const auto p2 = make_polyx(1009, { 1, -3, 0, -2, 0, 0 });
const auto p3 = make_polyx(1009, { 12, 18, 30, -42, 36, 0, 24, 0 });
polyx pr;
polyx::quot_rem(pr, p0, p1);
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::quot_rem(pr, p0, p2);
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::quot_rem(pr, p1, p1);
EXPECT_EQ(make_polyx(1009, { 1 }), pr);
polyx::quot_rem(pr, p1, p2);
EXPECT_EQ(make_polyx(1009, { 6 }), pr);
polyx::quot_rem(pr, p3, p1);
EXPECT_EQ(make_polyx(1009, { 2, 3, 5, -7, 6, 0, 4 }), pr);
polyx::quot_rem(pr, p3, p2);
EXPECT_EQ(make_polyx(1009, {-3, 63, 30, 15, 0, 0, -12}), pr);
polyx::quot_rem(pr, p2, p3);
EXPECT_EQ(make_polyx(1009, { 1, -3, 0, -2 }), pr);
// inplace
pr = p3;
polyx::quot_rem(pr, pr, p2);
EXPECT_EQ(make_polyx(1009, {-3, 63, 30, 15, 0, 0, -12}), pr);
pr = p2;
polyx::quot_rem(pr, pr, p3);
EXPECT_EQ(make_polyx(1009, { 1, -3, 0, -2 }), pr);
pr = p3;
polyx::quot_rem(pr, pr, p3);
EXPECT_EQ(make_polyx(1009, { 0, 0, 0, 0, 0, 0, 1 }), pr);
}
TEST(polynom_modx_test, div) {
const auto p0 = make_polyx(1009, {});
const auto p1 = make_polyx(1009, { 6 });
const auto p2 = make_polyx(1009, { 1, -3, 0, -2, 0, 0 });
const auto p3 = make_polyx(1009, { 12, 18, 30, -42, 36, 0, 24, 0 });
polyx pr;
polyx::div(pr, p0, p1);
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::div(pr, p0, p2);
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::div(pr, p1, p1);
EXPECT_EQ(make_polyx(1009, { 1 }), pr);
polyx::div(pr, p1, p2);
EXPECT_EQ(make_polyx(1009, { }), pr);
polyx::div(pr, p3, p1);
EXPECT_EQ(make_polyx(1009, { 2, 3, 5, -7, 6, 0, 4 }), pr);
polyx::div(pr, p3, p2);
EXPECT_EQ(make_polyx(1009, { 15, 0, 0, -12}), pr);
polyx::div(pr, p2, p3);
EXPECT_EQ(make_polyx(1009, {}), pr);
// inplace
pr = p3;
polyx::div(pr, pr, p2);
EXPECT_EQ(make_polyx(1009, { 15, 0, 0, -12}), pr);
pr = p2;
polyx::div(pr, pr, p3);
EXPECT_EQ(make_polyx(1009, {}), pr);
pr = p3;
polyx::div(pr, pr, p3);
EXPECT_EQ(make_polyx(1009, { 1 }), pr);
}
TEST(polynom_modx_test, mod) {
const auto p0 = make_polyx(1009, {});
const auto p1 = make_polyx(1009, { 6 });
const auto p2 = make_polyx(1009, { 1, -3, 0, -2, 0, 0 });
const auto p3 = make_polyx(1009, { 12, 18, 30, -42, 36, 0, 24, 0 });
polyx pr;
polyx::mod(pr, p0, p1);
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::mod(pr, p0, p2);
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::mod(pr, p1, p1);
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::mod(pr, p1, p2);
EXPECT_EQ(make_polyx(1009, { 6 }), pr);
polyx::mod(pr, p3, p1);
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::mod(pr, p3, p2);
EXPECT_EQ(make_polyx(1009, {-3, 63, 30 }), pr);
polyx::mod(pr, p2, p3);
EXPECT_EQ(make_polyx(1009, { 1, -3, 0, -2 }), pr);
// inplace
pr = p3;
polyx::mod(pr, pr, p2);
EXPECT_EQ(make_polyx(1009, {-3, 63, 30 }), pr);
pr = p2;
polyx::mod(pr, pr, p3);
EXPECT_EQ(make_polyx(1009, { 1, -3, 0, -2 }), pr);
pr = p3;
polyx::mod(pr, pr, p3);
EXPECT_EQ(make_polyx(1009, { 0, 0, 0, 0, 0, 0 }), pr);
}
TEST(polynom_modx_test, muls) {
const auto p0 = make_polyx(1009, {});
const auto p1 = make_polyx(1009, { 4 });
const auto p2 = make_polyx(1009, { 1, -3, 5, 7 });
const auto p3 = make_polyx(1009, { 2, 3, 5, -7, 0, 0 });
polyx pr;
polyx::mul(pr, p0, modx(11, 1009));
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::mul(pr, p1, modx(11, 1009));
EXPECT_EQ(make_polyx(1009, { 44 }), pr);
polyx::mul(pr, p2, modx(11, 1009));
EXPECT_EQ(make_polyx(1009, { 11, -33, 55, 77 }), pr);
polyx::mul(pr, p3, modx(11, 1009));
EXPECT_EQ(make_polyx(1009, { 22, 33, 55, -77 }), pr);
// inplace
pr = make_polyx(1009, { 2, 3, 5, -7 });
polyx::mul(pr, pr, modx(11, 1009));
EXPECT_EQ(make_polyx(1009, { 22, 33, 55, -77 }), pr);
}
TEST(polynom_modx_test, divs) {
const auto p0 = make_polyx(1009, {});
const auto p1 = make_polyx(1009, { 44 });
const auto p2 = make_polyx(1009, { 11, -33, 55, 77 });
const auto p3 = make_polyx(1009, { 22, 33, 55, -77, 0, 0 });
polyx pr;
polyx::div(pr, p0, modx(11, 1009));
EXPECT_EQ(make_polyx(1009, {}), pr);
polyx::div(pr, p1, modx(11, 1009));
EXPECT_EQ(make_polyx(1009, { 4 }), pr);
polyx::div(pr, p2, modx(11, 1009));
EXPECT_EQ(make_polyx(1009, { 1, -3, 5, 7 }), pr);
polyx::div(pr, p3, modx(11, 1009));
EXPECT_EQ(make_polyx(1009, { 2, 3, 5, -7 }), pr);
// inplace
pr = make_polyx(1009, { 22, 33, 55, -77 });
polyx::div(pr, pr, modx(11, 1009));
EXPECT_EQ(make_polyx(1009, { 2, 3, 5, -7 }), pr);
}
TEST(polynom_modx_test, operators_comparison) {
const auto p1 = make_polyx(1009, { 4 });
const auto p2 = make_polyx(1009, { 1, 3, 5, 7 });
const auto p3 = make_polyx(1009, { 1, 3, 5, 7, 0, 0, 0 });
ASSERT_COMPARISON_OPERATORS(0, p1, p1);
ASSERT_COMPARISON_OPERATORS(0, p2, p2);
ASSERT_COMPARISON_OPERATORS(0, p3, p3);
ASSERT_COMPARISON_OPERATORS(-1, p1, p2);
ASSERT_COMPARISON_OPERATORS(+1, p2, p1);
ASSERT_COMPARISON_OPERATORS(0, p2, p3);
ASSERT_COMPARISON_OPERATORS(0, p3, p2);
}
TEST(polynom_modx_test, operators_arithmetic) {
const auto p1 = make_polyx(1009, { 4, 1 });
const auto p2 = make_polyx(1009, { 1, -3, 5, 7 });
const auto p3 = make_polyx(1009, { 11, -33, 55, 77 });
EXPECT_EQ(make_polyx(1009, { 5, -2, 5, 7 }), p1 + p2);
EXPECT_EQ(make_polyx(1009, { 3, 4, -5, -7 }), p1 - p2);
EXPECT_EQ(make_polyx(1009, { -1, 3, -5, -7 }), -p2);
EXPECT_EQ(make_polyx(1009, { 4, -11, 17, 33, 7 }), p1 * p2);
EXPECT_EQ(make_polyx(1009, { }), p1 / p2);
EXPECT_EQ(make_polyx(1009, { 4, 1 }), p1 % p2);
EXPECT_EQ(make_polyx(1009, { 5, -2, 5, 7 }), p2 + p1);
EXPECT_EQ(make_polyx(1009, { -3, -4, 5, 7 }), p2 - p1);
EXPECT_EQ(make_polyx(1009, { -4, -1 }), -p1);
EXPECT_EQ(make_polyx(1009, { 4, -11, 17, 33, 7 }), p2 * p1);
EXPECT_EQ(make_polyx(1009, { 89, -23, 7 }), p2 / p1);
EXPECT_EQ(make_polyx(1009, { -355 }), p2 % p1);
EXPECT_EQ(make_polyx(1009, { 11, -33, 55, 77 }), p2 * modx(11, 1009));
EXPECT_EQ(make_polyx(1009, { 1, -3, 5, 7 }), p3 / modx(11, 1009));
}
TEST(polynom_modx_test, operators_inplace) {
const auto p1 = make_polyx(1009, { 4, 1 });
const auto p2 = make_polyx(1009, { 1, -3, 5, 7 });
const auto p3 = make_polyx(1009, { 11, -33, 55, 77 });
polyx pr;
pr = p1; pr += p2;
EXPECT_EQ(make_polyx(1009, { 5, -2, 5, 7 }), pr);
pr = p1; pr -= p2;
EXPECT_EQ(make_polyx(1009, { 3, 4, -5, -7 }), pr);
pr = p1; pr *= p2;
EXPECT_EQ(make_polyx(1009, { 4, -11, 17, 33, 7 }), pr);
pr = p1; pr /= p2;
EXPECT_EQ(make_polyx(1009, { }), pr);
pr = p1; pr %= p2;
EXPECT_EQ(make_polyx(1009, { 4, 1 }), pr);
pr = p2; pr += p1;
EXPECT_EQ(make_polyx(1009, { 5, -2, 5, 7 }), pr);
pr = p2; pr -= p1;
EXPECT_EQ(make_polyx(1009, { -3, -4, 5, 7 }), pr);
pr = p2; pr *= p1;
EXPECT_EQ(make_polyx(1009, { 4, -11, 17, 33, 7 }), pr);
pr = p2; pr /= p1;
EXPECT_EQ(make_polyx(1009, { 89, -23, 7 }), pr);
pr = p2; pr %= p1;
EXPECT_EQ(make_polyx(1009, { -355 }), pr);
pr = p2; pr *= modx(11, 1009);
EXPECT_EQ(make_polyx(1009, { 11, -33, 55, 77 }), pr);
pr = p3; pr /= modx(11, 1009);
EXPECT_EQ(make_polyx(1009, { 1, -3, 5, 7 }), pr);
}
TEST(polynom_modx_test, operators_inplace_self) {
const auto p1 = make_polyx(1009, { 2, -3, 5, 7 });
polyx pr;
pr = p1; pr += pr;
EXPECT_EQ(make_polyx(1009, { 4, -6, 10, 14 }), pr);
pr = p1; pr -= pr;
EXPECT_EQ(make_polyx(1009, { 0, 0, 0, 0 }), pr);
pr = p1; pr *= pr;
EXPECT_EQ(make_polyx(1009, { 4, -12, 29, -2, -17, 70, 49 }), pr);
pr = p1; pr %= pr;
EXPECT_EQ(make_polyx(1009, { 0, 0, 0 }), pr);
pr = p1; pr /= pr;
EXPECT_EQ(make_polyx(1009, { 1 }), pr);
}
TEST(polynom_modx_test, eval) {
const auto p1 = make_polyx(1009, { 7, 5, -3, 2 });
vector<modx> ve1;
for (int x = -3; x <= 4; x++) {
ve1.push_back(p1.eval(modx(x, 1009)));
}
EXPECT_EQ(to_modx(1009, {-89, -31, -3, 7, 11, 21, 49, 107}), ve1);
}
TEST(polynom_modx_test, derivative) {
const auto p1 = make_polyx(1009, { 7, 5, -3, 4 });
const auto pd = p1.derivative();
EXPECT_EQ(make_polyx(1009, { 5, -6, 12 }), pd);
}
TEST(polynom_modx_test, integral) {
const auto p = make_polyx(1009, { 7, 8, 15, -4, 20 });
const auto pi0 = p.integral();
const auto pi3 = p.integral(3);
EXPECT_EQ(make_polyx(1009, { 0, 7, 4, 5, -1, 4 }), pi0);
EXPECT_EQ(make_polyx(1009, { 3, 7, 4, 5, -1, 4 }), pi3);
}
TEST(polynom_modx_test, casts) {
polyx p1{ { 2, 1009 }, { 3, 1009 }, { 5, 1009 } };
EXPECT_EQ(2, p1[0].v);
EXPECT_EQ(1009, p1[0].M());
EXPECT_EQ(3, p1[1].v);
EXPECT_EQ(1009, p1[1].M());
EXPECT_EQ(5, p1[2].v);
EXPECT_EQ(1009, p1[2].M());
EXPECT_EQ(0, p1[3].v);
EXPECT_EQ(1009, p1[3].M());
EXPECT_EQ(2, p1.deg());
polyx e0 = zeroT<polyx>::of(p1);
EXPECT_EQ(0, e0[0].v);
EXPECT_EQ(1009, e0[0].M());
EXPECT_EQ(0, e0.deg());
polyx e1 = identityT<polyx>::of(p1);
EXPECT_EQ(1, e1[0].v);
EXPECT_EQ(1009, e1[0].M());
EXPECT_EQ(0, e1.deg());
const polyx p2 = castOf<polyx>(p1);
EXPECT_EQ(2, p2[0].v);
EXPECT_EQ(1009, p2[0].M());
EXPECT_EQ(3, p2[1].v);
EXPECT_EQ(1009, p2[1].M());
EXPECT_EQ(5, p2[2].v);
EXPECT_EQ(1009, p2[2].M());
EXPECT_EQ(0, p2[3].v);
EXPECT_EQ(1009, p2[3].M());
EXPECT_EQ(2, p2.deg());
const polyx p3 = castOf(e1, p1);
EXPECT_EQ(2, p3[0].v);
EXPECT_EQ(1009, p3[0].M());
EXPECT_EQ(3, p3[1].v);
EXPECT_EQ(1009, p3[1].M());
EXPECT_EQ(5, p3[2].v);
EXPECT_EQ(1009, p3[2].M());
EXPECT_EQ(0, p3[3].v);
EXPECT_EQ(1009, p3[3].M());
EXPECT_EQ(2, p3.deg());
const polyx p4 = castOf(e1, 4);
EXPECT_EQ(4, p4[0].v);
EXPECT_EQ(1009, p4[0].M());
EXPECT_EQ(0, p4[1].v);
EXPECT_EQ(1009, p4[1].M());
EXPECT_EQ(0, p4.deg());
}
| 37.178571 | 133 | 0.559706 | [
"vector",
"transform"
] |
aa2a0551370a488885c0dbca92b4071486d60855 | 6,455 | cpp | C++ | build/moc_bitcoingui.cpp | JTAG-Romney/BatCoin | 7747f34bc023843b124b5f378cde89bbf8787ff6 | [
"MIT"
] | 6 | 2021-02-20T05:01:15.000Z | 2021-03-09T20:04:12.000Z | build/moc_bitcoingui.cpp | kevinmarks/indiecreddit | 6d8ab6053bc02401eaa793d6bff08eb03ae14938 | [
"MIT"
] | null | null | null | build/moc_bitcoingui.cpp | kevinmarks/indiecreddit | 6d8ab6053bc02401eaa793d6bff08eb03ae14938 | [
"MIT"
] | 6 | 2015-11-30T18:21:22.000Z | 2021-07-13T17:00:26.000Z | /****************************************************************************
** Meta object code from reading C++ file 'bitcoingui.h'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.5)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/qt/bitcoingui.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'bitcoingui.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.5. 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
static const uint qt_meta_data_BitcoinGUI[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
27, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
11, 34, 40, 40, 0x0a,
41, 63, 40, 40, 0x0a,
82, 102, 40, 40, 0x0a,
118, 143, 40, 40, 0x0a,
150, 178, 40, 40, 0x0a,
198, 219, 40, 40, 0x0a,
239, 258, 40, 40, 0x0a,
265, 40, 40, 40, 0x08,
284, 40, 40, 40, 0x08,
301, 40, 40, 40, 0x08,
319, 40, 40, 40, 0x08,
341, 40, 40, 40, 0x08,
364, 40, 40, 40, 0x08,
384, 412, 40, 40, 0x08,
417, 40, 40, 40, 0x28,
438, 412, 40, 40, 0x08,
468, 40, 40, 40, 0x28,
491, 40, 40, 40, 0x08,
508, 40, 40, 40, 0x08,
523, 564, 40, 40, 0x08,
581, 143, 40, 40, 0x08,
601, 40, 40, 40, 0x08,
616, 40, 40, 40, 0x08,
635, 40, 40, 40, 0x08,
650, 678, 40, 40, 0x08,
692, 40, 40, 40, 0x28,
716, 40, 40, 40, 0x08,
0 // eod
};
static const char qt_meta_stringdata_BitcoinGUI[] = {
"BitcoinGUI\0setNumConnections(int)\0"
"count\0\0setNumBlocks(int,int)\0"
"count,countOfPeers\0setMining(bool,int)\0"
"mining,hashrate\0setEncryptionStatus(int)\0"
"status\0error(QString,QString,bool)\0"
"title,message,modal\0askFee(qint64,bool*)\0"
"nFeeRequired,payFee\0handleURI(QString)\0"
"strURI\0gotoOverviewPage()\0gotoMiningPage()\0"
"gotoHistoryPage()\0gotoAddressBookPage()\0"
"gotoReceiveCoinsPage()\0gotoSendCoinsPage()\0"
"gotoSignMessageTab(QString)\0addr\0"
"gotoSignMessageTab()\0gotoVerifyMessageTab(QString)\0"
"gotoVerifyMessageTab()\0optionsClicked()\0"
"aboutClicked()\0incomingTransaction(QModelIndex,int,int)\0"
"parent,start,end\0encryptWallet(bool)\0"
"backupWallet()\0changePassphrase()\0"
"unlockWallet()\0showNormalIfMinimized(bool)\0"
"fToggleHidden\0showNormalIfMinimized()\0"
"toggleHidden()\0"
};
void BitcoinGUI::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
BitcoinGUI *_t = static_cast<BitcoinGUI *>(_o);
switch (_id) {
case 0: _t->setNumConnections((*reinterpret_cast< int(*)>(_a[1]))); break;
case 1: _t->setNumBlocks((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 2: _t->setMining((*reinterpret_cast< bool(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 3: _t->setEncryptionStatus((*reinterpret_cast< int(*)>(_a[1]))); break;
case 4: _t->error((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2])),(*reinterpret_cast< bool(*)>(_a[3]))); break;
case 5: _t->askFee((*reinterpret_cast< qint64(*)>(_a[1])),(*reinterpret_cast< bool*(*)>(_a[2]))); break;
case 6: _t->handleURI((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 7: _t->gotoOverviewPage(); break;
case 8: _t->gotoMiningPage(); break;
case 9: _t->gotoHistoryPage(); break;
case 10: _t->gotoAddressBookPage(); break;
case 11: _t->gotoReceiveCoinsPage(); break;
case 12: _t->gotoSendCoinsPage(); break;
case 13: _t->gotoSignMessageTab((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 14: _t->gotoSignMessageTab(); break;
case 15: _t->gotoVerifyMessageTab((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 16: _t->gotoVerifyMessageTab(); break;
case 17: _t->optionsClicked(); break;
case 18: _t->aboutClicked(); break;
case 19: _t->incomingTransaction((*reinterpret_cast< const QModelIndex(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break;
case 20: _t->encryptWallet((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 21: _t->backupWallet(); break;
case 22: _t->changePassphrase(); break;
case 23: _t->unlockWallet(); break;
case 24: _t->showNormalIfMinimized((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 25: _t->showNormalIfMinimized(); break;
case 26: _t->toggleHidden(); break;
default: ;
}
}
}
const QMetaObjectExtraData BitcoinGUI::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject BitcoinGUI::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_BitcoinGUI,
qt_meta_data_BitcoinGUI, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &BitcoinGUI::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *BitcoinGUI::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *BitcoinGUI::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_BitcoinGUI))
return static_cast<void*>(const_cast< BitcoinGUI*>(this));
return QMainWindow::qt_metacast(_clname);
}
int BitcoinGUI::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 27)
qt_static_metacall(this, _c, _id, _a);
_id -= 27;
}
return _id;
}
QT_END_MOC_NAMESPACE
| 39.601227 | 171 | 0.602014 | [
"object"
] |
a8f41ef5f440bb17342b0f8ca18bcd7ee3a13013 | 37,837 | cpp | C++ | third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | /*
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
* Copyright (C) 2008, 2010 Nokia Corporation and/or its subsidiary(-ies)
* Copyright (C) 2007 Alp Toker <alp@atoker.com>
* Copyright (C) 2008 Eric Seidel <eric@webkit.org>
* Copyright (C) 2008 Dirk Schulze <krit@webkit.org>
* Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
* Copyright (C) 2012, 2013 Intel Corporation. All rights reserved.
* Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "modules/canvas2d/CanvasRenderingContext2D.h"
#include "bindings/core/v8/ExceptionMessages.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ExceptionStatePlaceholder.h"
#include "bindings/modules/v8/RenderingContext.h"
#include "core/CSSPropertyNames.h"
#include "core/css/StylePropertySet.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/AXObjectCache.h"
#include "core/dom/StyleEngine.h"
#include "core/events/Event.h"
#include "core/events/MouseEvent.h"
#include "core/frame/Settings.h"
#include "core/html/TextMetrics.h"
#include "core/html/canvas/CanvasFontCache.h"
#include "core/layout/LayoutBox.h"
#include "core/layout/LayoutTheme.h"
#include "modules/canvas2d/CanvasStyle.h"
#include "modules/canvas2d/HitRegion.h"
#include "modules/canvas2d/Path2D.h"
#include "platform/fonts/FontCache.h"
#include "platform/graphics/DrawLooperBuilder.h"
#include "platform/graphics/ExpensiveCanvasHeuristicParameters.h"
#include "platform/graphics/ImageBuffer.h"
#include "platform/graphics/StrokeData.h"
#include "platform/graphics/skia/SkiaUtils.h"
#include "platform/text/BidiTextRun.h"
#include "public/platform/Platform.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkImageFilter.h"
#include "wtf/MathExtras.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/typed_arrays/ArrayBufferContents.h"
namespace blink {
static const char defaultFont[] = "10px sans-serif";
static const char inherit[] = "inherit";
static const char rtl[] = "rtl";
static const char ltr[] = "ltr";
static const double TryRestoreContextInterval = 0.5;
static const unsigned MaxTryRestoreContextAttempts = 4;
static const double cDeviceScaleFactor = 1.0; // Canvas is device independent
static bool contextLostRestoredEventsEnabled()
{
return RuntimeEnabledFeatures::experimentalCanvasFeaturesEnabled();
}
// Drawing methods need to use this instead of SkAutoCanvasRestore in case overdraw
// detection substitutes the recording canvas (to discard overdrawn draw calls).
class CanvasRenderingContext2DAutoRestoreSkCanvas {
STACK_ALLOCATED();
public:
explicit CanvasRenderingContext2DAutoRestoreSkCanvas(CanvasRenderingContext2D* context)
: m_context(context)
, m_saveCount(0)
{
ASSERT(m_context);
SkCanvas* c = m_context->drawingCanvas();
if (c) {
m_saveCount = c->getSaveCount();
}
}
~CanvasRenderingContext2DAutoRestoreSkCanvas()
{
SkCanvas* c = m_context->drawingCanvas();
if (c)
c->restoreToCount(m_saveCount);
m_context->validateStateStack();
}
private:
Member<CanvasRenderingContext2D> m_context;
int m_saveCount;
};
CanvasRenderingContext2D::CanvasRenderingContext2D(HTMLCanvasElement* canvas, const CanvasContextCreationAttributes& attrs, Document& document)
: CanvasRenderingContext(canvas)
, m_hasAlpha(attrs.alpha())
, m_contextLostMode(NotLostContext)
, m_contextRestorable(true)
, m_tryRestoreContextAttemptCount(0)
, m_dispatchContextLostEventTimer(this, &CanvasRenderingContext2D::dispatchContextLostEvent)
, m_dispatchContextRestoredEventTimer(this, &CanvasRenderingContext2D::dispatchContextRestoredEvent)
, m_tryRestoreContextEventTimer(this, &CanvasRenderingContext2D::tryRestoreContextEvent)
, m_pruneLocalFontCacheScheduled(false)
{
if (document.settings() && document.settings()->antialiasedClips2dCanvasEnabled())
m_clipAntialiasing = AntiAliased;
setShouldAntialias(true);
ThreadState::current()->registerPreFinalizer(this);
}
void CanvasRenderingContext2D::setCanvasGetContextResult(RenderingContext& result)
{
result.setCanvasRenderingContext2D(this);
}
void CanvasRenderingContext2D::unwindStateStack()
{
if (size_t stackSize = m_stateStack.size()) {
if (SkCanvas* skCanvas = canvas()->existingDrawingCanvas()) {
while (--stackSize)
skCanvas->restore();
}
}
}
CanvasRenderingContext2D::~CanvasRenderingContext2D() { }
void CanvasRenderingContext2D::dispose()
{
if (m_pruneLocalFontCacheScheduled)
Platform::current()->currentThread()->removeTaskObserver(this);
}
void CanvasRenderingContext2D::validateStateStack()
{
#if ENABLE(ASSERT)
SkCanvas* skCanvas = canvas()->existingDrawingCanvas();
if (skCanvas && m_contextLostMode == NotLostContext) {
ASSERT(static_cast<size_t>(skCanvas->getSaveCount()) == m_stateStack.size());
}
#endif
}
bool CanvasRenderingContext2D::isAccelerated() const
{
if (!canvas()->hasImageBuffer())
return false;
return canvas()->buffer()->isAccelerated();
}
void CanvasRenderingContext2D::stop()
{
if (!isContextLost()) {
// Never attempt to restore the context because the page is being torn down.
loseContext(SyntheticLostContext);
}
}
bool CanvasRenderingContext2D::isContextLost() const
{
return m_contextLostMode != NotLostContext;
}
void CanvasRenderingContext2D::loseContext(LostContextMode lostMode)
{
if (m_contextLostMode != NotLostContext)
return;
m_contextLostMode = lostMode;
if (m_contextLostMode == SyntheticLostContext && canvas()) {
canvas()->discardImageBuffer();
}
m_dispatchContextLostEventTimer.startOneShot(0, BLINK_FROM_HERE);
}
void CanvasRenderingContext2D::didSetSurfaceSize()
{
if (!m_contextRestorable)
return;
// This code path is for restoring from an eviction
// Restoring from surface failure is handled internally
ASSERT(m_contextLostMode != NotLostContext && !canvas()->hasImageBuffer());
if (canvas()->buffer()) {
if (contextLostRestoredEventsEnabled()) {
m_dispatchContextRestoredEventTimer.startOneShot(0, BLINK_FROM_HERE);
} else {
// legacy synchronous context restoration.
reset();
m_contextLostMode = NotLostContext;
}
}
}
DEFINE_TRACE(CanvasRenderingContext2D)
{
visitor->trace(m_hitRegionManager);
CanvasRenderingContext::trace(visitor);
BaseRenderingContext2D::trace(visitor);
SVGResourceClient::trace(visitor);
}
void CanvasRenderingContext2D::dispatchContextLostEvent(Timer<CanvasRenderingContext2D>*)
{
if (canvas() && contextLostRestoredEventsEnabled()) {
Event* event = Event::createCancelable(EventTypeNames::contextlost);
canvas()->dispatchEvent(event);
if (event->defaultPrevented()) {
m_contextRestorable = false;
}
}
// If RealLostContext, it means the context was not lost due to surface failure
// but rather due to a an eviction, which means image buffer exists.
if (m_contextRestorable && m_contextLostMode == RealLostContext) {
m_tryRestoreContextAttemptCount = 0;
m_tryRestoreContextEventTimer.startRepeating(TryRestoreContextInterval, BLINK_FROM_HERE);
}
}
void CanvasRenderingContext2D::tryRestoreContextEvent(Timer<CanvasRenderingContext2D>* timer)
{
if (m_contextLostMode == NotLostContext) {
// Canvas was already restored (possibly thanks to a resize), so stop trying.
m_tryRestoreContextEventTimer.stop();
return;
}
DCHECK(m_contextLostMode == RealLostContext);
if (canvas()->hasImageBuffer() && canvas()->buffer()->restoreSurface()) {
m_tryRestoreContextEventTimer.stop();
dispatchContextRestoredEvent(nullptr);
}
if (++m_tryRestoreContextAttemptCount > MaxTryRestoreContextAttempts) {
// final attempt: allocate a brand new image buffer instead of restoring
canvas()->discardImageBuffer();
m_tryRestoreContextEventTimer.stop();
if (canvas()->buffer())
dispatchContextRestoredEvent(nullptr);
}
}
void CanvasRenderingContext2D::dispatchContextRestoredEvent(Timer<CanvasRenderingContext2D>*)
{
if (m_contextLostMode == NotLostContext)
return;
reset();
m_contextLostMode = NotLostContext;
if (contextLostRestoredEventsEnabled()) {
Event* event(Event::create(EventTypeNames::contextrestored));
canvas()->dispatchEvent(event);
}
}
void CanvasRenderingContext2D::reset()
{
validateStateStack();
unwindStateStack();
m_stateStack.resize(1);
m_stateStack.first() = CanvasRenderingContext2DState::create();
m_path.clear();
SkCanvas* c = canvas()->existingDrawingCanvas();
if (c) {
c->resetMatrix();
c->clipRect(SkRect::MakeWH(canvas()->width(), canvas()->height()), SkRegion::kReplace_Op);
}
validateStateStack();
}
void CanvasRenderingContext2D::restoreCanvasMatrixClipStack(SkCanvas* c) const
{
restoreMatrixClipStack(c);
}
bool CanvasRenderingContext2D::shouldAntialias() const
{
return state().shouldAntialias();
}
void CanvasRenderingContext2D::setShouldAntialias(bool doAA)
{
modifiableState().setShouldAntialias(doAA);
}
void CanvasRenderingContext2D::scrollPathIntoView()
{
scrollPathIntoViewInternal(m_path);
}
void CanvasRenderingContext2D::scrollPathIntoView(Path2D* path2d)
{
scrollPathIntoViewInternal(path2d->path());
}
void CanvasRenderingContext2D::scrollPathIntoViewInternal(const Path& path)
{
if (!state().isTransformInvertible() || path.isEmpty())
return;
canvas()->document().updateStyleAndLayoutIgnorePendingStylesheets();
LayoutObject* renderer = canvas()->layoutObject();
LayoutBox* layoutBox = canvas()->layoutBox();
if (!renderer || !layoutBox)
return;
// Apply transformation and get the bounding rect
Path transformedPath = path;
transformedPath.transform(state().transform());
FloatRect boundingRect = transformedPath.boundingRect();
// Offset by the canvas rect
LayoutRect pathRect(boundingRect);
IntRect canvasRect = layoutBox->absoluteContentBox();
pathRect.moveBy(canvasRect.location());
renderer->scrollRectToVisible(
pathRect, ScrollAlignment::alignCenterAlways, ScrollAlignment::alignTopAlways);
// TODO: should implement "inform the user" that the caret and/or
// selection the specified rectangle of the canvas. See http://crbug.com/357987
}
void CanvasRenderingContext2D::clearRect(double x, double y, double width, double height)
{
BaseRenderingContext2D::clearRect(x, y, width, height);
if (m_hitRegionManager) {
FloatRect rect(x, y, width, height);
m_hitRegionManager->removeHitRegionsInRect(rect, state().transform());
}
}
void CanvasRenderingContext2D::didDraw(const SkIRect& dirtyRect)
{
if (dirtyRect.isEmpty())
return;
if (ExpensiveCanvasHeuristicParameters::BlurredShadowsAreExpensive && state().shouldDrawShadows() && state().shadowBlur() > 0) {
ImageBuffer* buffer = canvas()->buffer();
if (buffer)
buffer->setHasExpensiveOp();
}
canvas()->didDraw(SkRect::Make(dirtyRect));
}
bool CanvasRenderingContext2D::stateHasFilter()
{
return state().hasFilter(canvas(), canvas()->size(), this);
}
SkImageFilter* CanvasRenderingContext2D::stateGetFilter()
{
return state().getFilter(canvas(), canvas()->size(), this);
}
void CanvasRenderingContext2D::snapshotStateForFilter()
{
// The style resolution required for fonts is not available in frame-less documents.
if (!canvas()->document().frame())
return;
modifiableState().setFontForFilter(accessFont());
}
SkCanvas* CanvasRenderingContext2D::drawingCanvas() const
{
if (isContextLost())
return nullptr;
return canvas()->drawingCanvas();
}
SkCanvas* CanvasRenderingContext2D::existingDrawingCanvas() const
{
return canvas()->existingDrawingCanvas();
}
void CanvasRenderingContext2D::disableDeferral(DisableDeferralReason reason)
{
canvas()->disableDeferral(reason);
}
AffineTransform CanvasRenderingContext2D::baseTransform() const
{
return canvas()->baseTransform();
}
String CanvasRenderingContext2D::font() const
{
if (!state().hasRealizedFont())
return defaultFont;
canvas()->document().canvasFontCache()->willUseCurrentFont();
StringBuilder serializedFont;
const FontDescription& fontDescription = state().font().getFontDescription();
if (fontDescription.style() == FontStyleItalic)
serializedFont.append("italic ");
if (fontDescription.weight() == FontWeightBold)
serializedFont.append("bold ");
if (fontDescription.variantCaps() == FontDescription::SmallCaps)
serializedFont.append("small-caps ");
serializedFont.appendNumber(fontDescription.computedPixelSize());
serializedFont.append("px");
const FontFamily& firstFontFamily = fontDescription.family();
for (const FontFamily* fontFamily = &firstFontFamily; fontFamily; fontFamily = fontFamily->next()) {
if (fontFamily != &firstFontFamily)
serializedFont.append(',');
// FIXME: We should append family directly to serializedFont rather than building a temporary string.
String family = fontFamily->family();
if (family.startsWith("-webkit-"))
family = family.substring(8);
if (family.contains(' '))
family = "\"" + family + "\"";
serializedFont.append(' ');
serializedFont.append(family);
}
return serializedFont.toString();
}
void CanvasRenderingContext2D::setFont(const String& newFont)
{
// The style resolution required for rendering text is not available in frame-less documents.
if (!canvas()->document().frame())
return;
canvas()->document().updateStyleAndLayoutTreeForNode(canvas());
// The following early exit is dependent on the cache not being empty
// because an empty cache may indicate that a style change has occured
// which would require that the font be re-resolved. This check has to
// come after the layout tree update to flush pending style changes.
if (newFont == state().unparsedFont() && state().hasRealizedFont() && m_fontsResolvedUsingCurrentStyle.size() > 0)
return;
CanvasFontCache* canvasFontCache = canvas()->document().canvasFontCache();
// Map the <canvas> font into the text style. If the font uses keywords like larger/smaller, these will work
// relative to the canvas.
RefPtr<ComputedStyle> fontStyle;
const ComputedStyle* computedStyle = canvas()->ensureComputedStyle();
if (computedStyle) {
HashMap<String, Font>::iterator i = m_fontsResolvedUsingCurrentStyle.find(newFont);
if (i != m_fontsResolvedUsingCurrentStyle.end()) {
ASSERT(m_fontLRUList.contains(newFont));
m_fontLRUList.remove(newFont);
m_fontLRUList.add(newFont);
modifiableState().setFont(i->value, canvas()->document().styleEngine().fontSelector());
} else {
MutableStylePropertySet* parsedStyle = canvasFontCache->parseFont(newFont);
if (!parsedStyle)
return;
fontStyle = ComputedStyle::create();
FontDescription elementFontDescription(computedStyle->getFontDescription());
// Reset the computed size to avoid inheriting the zoom factor from the <canvas> element.
elementFontDescription.setComputedSize(elementFontDescription.specifiedSize());
fontStyle->setFontDescription(elementFontDescription);
fontStyle->font().update(fontStyle->font().getFontSelector());
canvas()->document().ensureStyleResolver().computeFont(fontStyle.get(), *parsedStyle);
m_fontsResolvedUsingCurrentStyle.add(newFont, fontStyle->font());
ASSERT(!m_fontLRUList.contains(newFont));
m_fontLRUList.add(newFont);
pruneLocalFontCache(canvasFontCache->hardMaxFonts()); // hard limit
schedulePruneLocalFontCacheIfNeeded(); // soft limit
modifiableState().setFont(fontStyle->font(), canvas()->document().styleEngine().fontSelector());
}
} else {
Font resolvedFont;
if (!canvasFontCache->getFontUsingDefaultStyle(newFont, resolvedFont))
return;
modifiableState().setFont(resolvedFont, canvas()->document().styleEngine().fontSelector());
}
// The parse succeeded.
String newFontSafeCopy(newFont); // Create a string copy since newFont can be deleted inside realizeSaves.
modifiableState().setUnparsedFont(newFontSafeCopy);
}
void CanvasRenderingContext2D::schedulePruneLocalFontCacheIfNeeded()
{
if (m_pruneLocalFontCacheScheduled)
return;
m_pruneLocalFontCacheScheduled = true;
Platform::current()->currentThread()->addTaskObserver(this);
}
void CanvasRenderingContext2D::didProcessTask()
{
Platform::current()->currentThread()->removeTaskObserver(this);
// This should be the only place where canvas() needs to be checked for nullness
// because the circular refence with HTMLCanvasElement mean the canvas and the
// context keep each other alive as long as the pair is referenced the task
// observer is the only persisten refernce to this object that is not traced,
// so didProcessTask() may be call at a time when the canvas has been garbage
// collected but not the context.
if (!canvas())
return;
// The rendering surface needs to be prepared now because it will be too late
// to create a layer once we are in the paint invalidation phase.
canvas()->prepareSurfaceForPaintingIfNeeded();
pruneLocalFontCache(canvas()->document().canvasFontCache()->maxFonts());
m_pruneLocalFontCacheScheduled = false;
}
void CanvasRenderingContext2D::pruneLocalFontCache(size_t targetSize)
{
if (targetSize == 0) {
// Short cut: LRU does not matter when evicting everything
m_fontLRUList.clear();
m_fontsResolvedUsingCurrentStyle.clear();
return;
}
while (m_fontLRUList.size() > targetSize) {
m_fontsResolvedUsingCurrentStyle.remove(m_fontLRUList.first());
m_fontLRUList.removeFirst();
}
}
void CanvasRenderingContext2D::styleDidChange(const ComputedStyle* oldStyle, const ComputedStyle& newStyle)
{
if (oldStyle && oldStyle->font() == newStyle.font())
return;
pruneLocalFontCache(0);
}
void CanvasRenderingContext2D::filterNeedsInvalidation()
{
state().clearResolvedFilter();
}
bool CanvasRenderingContext2D::originClean() const
{
return canvas()->originClean();
}
void CanvasRenderingContext2D::setOriginTainted()
{
return canvas()->setOriginTainted();
}
int CanvasRenderingContext2D::width() const
{
return canvas()->width();
}
int CanvasRenderingContext2D::height() const
{
return canvas()->height();
}
bool CanvasRenderingContext2D::hasImageBuffer() const
{
return canvas()->hasImageBuffer();
}
ImageBuffer* CanvasRenderingContext2D::imageBuffer() const
{
return canvas()->buffer();
}
bool CanvasRenderingContext2D::parseColorOrCurrentColor(Color& color, const String& colorString) const
{
return ::blink::parseColorOrCurrentColor(color, colorString, canvas());
}
std::pair<Element*, String> CanvasRenderingContext2D::getControlAndIdIfHitRegionExists(const LayoutPoint& location)
{
if (hitRegionsCount() <= 0)
return std::make_pair(nullptr, String());
LayoutBox* box = canvas()->layoutBox();
FloatPoint localPos = box->absoluteToLocal(FloatPoint(location), UseTransforms);
if (box->hasBorderOrPadding())
localPos.move(-box->contentBoxOffset());
localPos.scale(canvas()->width() / box->contentWidth(), canvas()->height() / box->contentHeight());
HitRegion* hitRegion = hitRegionAtPoint(localPos);
if (hitRegion) {
Element* control = hitRegion->control();
if (control && canvas()->isSupportedInteractiveCanvasFallback(*control))
return std::make_pair(hitRegion->control(), hitRegion->id());
return std::make_pair(nullptr, hitRegion->id());
}
return std::make_pair(nullptr, String());
}
String CanvasRenderingContext2D::getIdFromControl(const Element* element)
{
if (hitRegionsCount() <= 0)
return String();
if (HitRegion* hitRegion = m_hitRegionManager->getHitRegionByControl(element))
return hitRegion->id();
return String();
}
String CanvasRenderingContext2D::textAlign() const
{
return textAlignName(state().getTextAlign());
}
void CanvasRenderingContext2D::setTextAlign(const String& s)
{
TextAlign align;
if (!parseTextAlign(s, align))
return;
if (state().getTextAlign() == align)
return;
modifiableState().setTextAlign(align);
}
String CanvasRenderingContext2D::textBaseline() const
{
return textBaselineName(state().getTextBaseline());
}
void CanvasRenderingContext2D::setTextBaseline(const String& s)
{
TextBaseline baseline;
if (!parseTextBaseline(s, baseline))
return;
if (state().getTextBaseline() == baseline)
return;
modifiableState().setTextBaseline(baseline);
}
static inline TextDirection toTextDirection(CanvasRenderingContext2DState::Direction direction, HTMLCanvasElement* canvas, const ComputedStyle** computedStyle = 0)
{
const ComputedStyle* style = (computedStyle || direction == CanvasRenderingContext2DState::DirectionInherit) ? canvas->ensureComputedStyle() : nullptr;
if (computedStyle)
*computedStyle = style;
switch (direction) {
case CanvasRenderingContext2DState::DirectionInherit:
return style ? style->direction() : LTR;
case CanvasRenderingContext2DState::DirectionRTL:
return RTL;
case CanvasRenderingContext2DState::DirectionLTR:
return LTR;
}
ASSERT_NOT_REACHED();
return LTR;
}
String CanvasRenderingContext2D::direction() const
{
if (state().getDirection() == CanvasRenderingContext2DState::DirectionInherit)
canvas()->document().updateStyleAndLayoutTreeForNode(canvas());
return toTextDirection(state().getDirection(), canvas()) == RTL ? rtl : ltr;
}
void CanvasRenderingContext2D::setDirection(const String& directionString)
{
CanvasRenderingContext2DState::Direction direction;
if (directionString == inherit)
direction = CanvasRenderingContext2DState::DirectionInherit;
else if (directionString == rtl)
direction = CanvasRenderingContext2DState::DirectionRTL;
else if (directionString == ltr)
direction = CanvasRenderingContext2DState::DirectionLTR;
else
return;
if (state().getDirection() == direction)
return;
modifiableState().setDirection(direction);
}
void CanvasRenderingContext2D::fillText(const String& text, double x, double y)
{
trackDrawCall(FillText);
drawTextInternal(text, x, y, CanvasRenderingContext2DState::FillPaintType);
}
void CanvasRenderingContext2D::fillText(const String& text, double x, double y, double maxWidth)
{
trackDrawCall(FillText);
drawTextInternal(text, x, y, CanvasRenderingContext2DState::FillPaintType, &maxWidth);
}
void CanvasRenderingContext2D::strokeText(const String& text, double x, double y)
{
trackDrawCall(StrokeText);
drawTextInternal(text, x, y, CanvasRenderingContext2DState::StrokePaintType);
}
void CanvasRenderingContext2D::strokeText(const String& text, double x, double y, double maxWidth)
{
trackDrawCall(StrokeText);
drawTextInternal(text, x, y, CanvasRenderingContext2DState::StrokePaintType, &maxWidth);
}
TextMetrics* CanvasRenderingContext2D::measureText(const String& text)
{
TextMetrics* metrics = TextMetrics::create();
// The style resolution required for rendering text is not available in frame-less documents.
if (!canvas()->document().frame())
return metrics;
canvas()->document().updateStyleAndLayoutTreeForNode(canvas());
const Font& font = accessFont();
TextDirection direction;
if (state().getDirection() == CanvasRenderingContext2DState::DirectionInherit)
direction = determineDirectionality(text);
else
direction = toTextDirection(state().getDirection(), canvas());
TextRun textRun(text, 0, 0, TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion, direction, false);
textRun.setNormalizeSpace(true);
FloatRect textBounds = font.selectionRectForText(textRun, FloatPoint(), font.getFontDescription().computedSize(), 0, -1, true);
// x direction
metrics->setWidth(font.width(textRun));
metrics->setActualBoundingBoxLeft(-textBounds.x());
metrics->setActualBoundingBoxRight(textBounds.maxX());
// y direction
const FontMetrics& fontMetrics = font.getFontMetrics();
const float ascent = fontMetrics.floatAscent();
const float descent = fontMetrics.floatDescent();
const float baselineY = getFontBaseline(fontMetrics);
metrics->setFontBoundingBoxAscent(ascent - baselineY);
metrics->setFontBoundingBoxDescent(descent + baselineY);
metrics->setActualBoundingBoxAscent(-textBounds.y() - baselineY);
metrics->setActualBoundingBoxDescent(textBounds.maxY() + baselineY);
// Note : top/bottom and ascend/descend are currently the same, so there's no difference
// between the EM box's top and bottom and the font's ascend and descend
metrics->setEmHeightAscent(0);
metrics->setEmHeightDescent(0);
metrics->setHangingBaseline(-0.8f * ascent + baselineY);
metrics->setAlphabeticBaseline(baselineY);
metrics->setIdeographicBaseline(descent + baselineY);
return metrics;
}
void CanvasRenderingContext2D::drawTextInternal(const String& text, double x, double y, CanvasRenderingContext2DState::PaintType paintType, double* maxWidth)
{
// The style resolution required for rendering text is not available in frame-less documents.
if (!canvas()->document().frame())
return;
// accessFont needs the style to be up to date, but updating style can cause script to run,
// (e.g. due to autofocus) which can free the canvas (set size to 0, for example), so update
// style before grabbing the drawingCanvas.
canvas()->document().updateStyleAndLayoutTreeForNode(canvas());
SkCanvas* c = drawingCanvas();
if (!c)
return;
if (!std::isfinite(x) || !std::isfinite(y))
return;
if (maxWidth && (!std::isfinite(*maxWidth) || *maxWidth <= 0))
return;
// Currently, SkPictureImageFilter does not support subpixel text anti-aliasing, which
// is expected when !m_hasAlpha, so we need to fall out of display list mode when
// drawing text to an opaque canvas
// crbug.com/583809
if (!m_hasAlpha && !isAccelerated())
canvas()->disableDeferral(DisableDeferralReasonSubPixelTextAntiAliasingSupport);
const Font& font = accessFont();
if (!font.primaryFont())
return;
const FontMetrics& fontMetrics = font.getFontMetrics();
// FIXME: Need to turn off font smoothing.
const ComputedStyle* computedStyle = 0;
TextDirection direction = toTextDirection(state().getDirection(), canvas(), &computedStyle);
bool isRTL = direction == RTL;
bool override = computedStyle ? isOverride(computedStyle->unicodeBidi()) : false;
TextRun textRun(text, 0, 0, TextRun::AllowTrailingExpansion, direction, override);
textRun.setNormalizeSpace(true);
// Draw the item text at the correct point.
FloatPoint location(x, y + getFontBaseline(fontMetrics));
double fontWidth = font.width(textRun);
bool useMaxWidth = (maxWidth && *maxWidth < fontWidth);
double width = useMaxWidth ? *maxWidth : fontWidth;
TextAlign align = state().getTextAlign();
if (align == StartTextAlign)
align = isRTL ? RightTextAlign : LeftTextAlign;
else if (align == EndTextAlign)
align = isRTL ? LeftTextAlign : RightTextAlign;
switch (align) {
case CenterTextAlign:
location.setX(location.x() - width / 2);
break;
case RightTextAlign:
location.setX(location.x() - width);
break;
default:
break;
}
// The slop built in to this mask rect matches the heuristic used in FontCGWin.cpp for GDI text.
TextRunPaintInfo textRunPaintInfo(textRun);
textRunPaintInfo.bounds = FloatRect(location.x() - fontMetrics.height() / 2,
location.y() - fontMetrics.ascent() - fontMetrics.lineGap(),
width + fontMetrics.height(),
fontMetrics.lineSpacing());
if (paintType == CanvasRenderingContext2DState::StrokePaintType)
inflateStrokeRect(textRunPaintInfo.bounds);
CanvasRenderingContext2DAutoRestoreSkCanvas stateRestorer(this);
if (useMaxWidth) {
drawingCanvas()->save();
drawingCanvas()->translate(location.x(), location.y());
// We draw when fontWidth is 0 so compositing operations (eg, a "copy" op) still work.
drawingCanvas()->scale((fontWidth > 0 ? (width / fontWidth) : 0), 1);
location = FloatPoint();
}
draw(
[&font, this, &textRunPaintInfo, &location](SkCanvas* c, const SkPaint* paint) // draw lambda
{
font.drawBidiText(c, textRunPaintInfo, location, Font::UseFallbackIfFontNotReady, cDeviceScaleFactor, *paint);
},
[](const SkIRect& rect) // overdraw test lambda
{
return false;
},
textRunPaintInfo.bounds, paintType);
}
const Font& CanvasRenderingContext2D::accessFont()
{
if (!state().hasRealizedFont())
setFont(state().unparsedFont());
canvas()->document().canvasFontCache()->willUseCurrentFont();
return state().font();
}
int CanvasRenderingContext2D::getFontBaseline(const FontMetrics& fontMetrics) const
{
switch (state().getTextBaseline()) {
case TopTextBaseline:
return fontMetrics.ascent();
case HangingTextBaseline:
// According to http://wiki.apache.org/xmlgraphics-fop/LineLayout/AlignmentHandling
// "FOP (Formatting Objects Processor) puts the hanging baseline at 80% of the ascender height"
return (fontMetrics.ascent() * 4) / 5;
case BottomTextBaseline:
case IdeographicTextBaseline:
return -fontMetrics.descent();
case MiddleTextBaseline:
return -fontMetrics.descent() + fontMetrics.height() / 2;
case AlphabeticTextBaseline:
default:
// Do nothing.
break;
}
return 0;
}
void CanvasRenderingContext2D::setIsHidden(bool hidden)
{
if (canvas()->hasImageBuffer())
canvas()->buffer()->setIsHidden(hidden);
if (hidden) {
pruneLocalFontCache(0);
}
}
bool CanvasRenderingContext2D::isTransformInvertible() const
{
return state().isTransformInvertible();
}
WebLayer* CanvasRenderingContext2D::platformLayer() const
{
return canvas()->buffer() ? canvas()->buffer()->platformLayer() : 0;
}
void CanvasRenderingContext2D::getContextAttributes(Canvas2DContextAttributes& attrs) const
{
attrs.setAlpha(m_hasAlpha);
}
void CanvasRenderingContext2D::drawFocusIfNeeded(Element* element)
{
drawFocusIfNeededInternal(m_path, element);
}
void CanvasRenderingContext2D::drawFocusIfNeeded(Path2D* path2d, Element* element)
{
drawFocusIfNeededInternal(path2d->path(), element);
}
void CanvasRenderingContext2D::drawFocusIfNeededInternal(const Path& path, Element* element)
{
if (!focusRingCallIsValid(path, element))
return;
// Note: we need to check document->focusedElement() rather than just calling
// element->focused(), because element->focused() isn't updated until after
// focus events fire.
if (element->document().focusedElement() == element) {
scrollPathIntoViewInternal(path);
drawFocusRing(path);
}
// Update its accessible bounds whether it's focused or not.
updateElementAccessibility(path, element);
}
bool CanvasRenderingContext2D::focusRingCallIsValid(const Path& path, Element* element)
{
ASSERT(element);
if (!state().isTransformInvertible())
return false;
if (path.isEmpty())
return false;
if (!element->isDescendantOf(canvas()))
return false;
return true;
}
void CanvasRenderingContext2D::drawFocusRing(const Path& path)
{
m_usageCounters.numDrawFocusCalls++;
if (!drawingCanvas())
return;
SkColor color = LayoutTheme::theme().focusRingColor().rgb();
const int focusRingWidth = 5;
drawPlatformFocusRing(path.getSkPath(), drawingCanvas(), color, focusRingWidth);
// We need to add focusRingWidth to dirtyRect.
StrokeData strokeData;
strokeData.setThickness(focusRingWidth);
SkIRect dirtyRect;
if (!computeDirtyRect(path.strokeBoundingRect(strokeData), &dirtyRect))
return;
didDraw(dirtyRect);
}
void CanvasRenderingContext2D::updateElementAccessibility(const Path& path, Element* element)
{
element->document().updateStyleAndLayoutIgnorePendingStylesheets();
AXObjectCache* axObjectCache = element->document().existingAXObjectCache();
LayoutBoxModelObject* lbmo = canvas()->layoutBoxModelObject();
LayoutObject* renderer = canvas()->layoutObject();
if (!axObjectCache || !lbmo || !renderer)
return;
// Get the transformed path.
Path transformedPath = path;
transformedPath.transform(state().transform());
// Offset by the canvas rect, taking border and padding into account.
IntRect canvasRect = renderer->absoluteBoundingBoxRect();
canvasRect.move(lbmo->borderLeft() + lbmo->paddingLeft(), lbmo->borderTop() + lbmo->paddingTop());
LayoutRect elementRect = enclosingLayoutRect(transformedPath.boundingRect());
elementRect.moveBy(canvasRect.location());
axObjectCache->setCanvasObjectBounds(element, elementRect);
}
void CanvasRenderingContext2D::addHitRegion(const HitRegionOptions& options, ExceptionState& exceptionState)
{
if (options.id().isEmpty() && !options.control()) {
exceptionState.throwDOMException(NotSupportedError, "Both id and control are null.");
return;
}
if (options.control() && !canvas()->isSupportedInteractiveCanvasFallback(*options.control())) {
exceptionState.throwDOMException(NotSupportedError, "The control is neither null nor a supported interactive canvas fallback element.");
return;
}
Path hitRegionPath = options.hasPath() ? options.path()->path() : m_path;
SkCanvas* c = drawingCanvas();
if (hitRegionPath.isEmpty() || !c || !state().isTransformInvertible()
|| !c->getClipDeviceBounds(0)) {
exceptionState.throwDOMException(NotSupportedError, "The specified path has no pixels.");
return;
}
hitRegionPath.transform(state().transform());
if (state().hasClip()) {
hitRegionPath.intersectPath(state().getCurrentClipPath());
if (hitRegionPath.isEmpty())
exceptionState.throwDOMException(NotSupportedError, "The specified path has no pixels.");
}
if (!m_hitRegionManager)
m_hitRegionManager = HitRegionManager::create();
// Remove previous region (with id or control)
m_hitRegionManager->removeHitRegionById(options.id());
m_hitRegionManager->removeHitRegionByControl(options.control());
HitRegion* hitRegion = HitRegion::create(hitRegionPath, options);
Element* element = hitRegion->control();
if (element && element->isDescendantOf(canvas()))
updateElementAccessibility(hitRegion->path(), hitRegion->control());
m_hitRegionManager->addHitRegion(hitRegion);
}
void CanvasRenderingContext2D::removeHitRegion(const String& id)
{
if (m_hitRegionManager)
m_hitRegionManager->removeHitRegionById(id);
}
void CanvasRenderingContext2D::clearHitRegions()
{
if (m_hitRegionManager)
m_hitRegionManager->removeAllHitRegions();
}
HitRegion* CanvasRenderingContext2D::hitRegionAtPoint(const FloatPoint& point)
{
if (m_hitRegionManager)
return m_hitRegionManager->getHitRegionAtPoint(point);
return nullptr;
}
unsigned CanvasRenderingContext2D::hitRegionsCount() const
{
if (m_hitRegionManager)
return m_hitRegionManager->getHitRegionsCount();
return 0;
}
} // namespace blink
| 35.295709 | 163 | 0.713323 | [
"object",
"transform"
] |
a8ff3c73de466e0f84bdc693e747b63e742f0423 | 6,666 | cpp | C++ | src/examples/Applets/App_PolyDepthSorting.cpp | pasenau/VisualizationLibrary | 2fcf1808475aebd4862f40377754be62a7f77a52 | [
"BSD-2-Clause"
] | 1 | 2017-06-29T18:25:11.000Z | 2017-06-29T18:25:11.000Z | src/examples/Applets/App_PolyDepthSorting.cpp | pasenau/VisualizationLibrary | 2fcf1808475aebd4862f40377754be62a7f77a52 | [
"BSD-2-Clause"
] | null | null | null | src/examples/Applets/App_PolyDepthSorting.cpp | pasenau/VisualizationLibrary | 2fcf1808475aebd4862f40377754be62a7f77a52 | [
"BSD-2-Clause"
] | 1 | 2021-01-01T10:43:33.000Z | 2021-01-01T10:43:33.000Z | /**************************************************************************************/
/* */
/* Visualization Library */
/* http://visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2017, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#include "BaseDemo.hpp"
#include <vlGraphics/DepthSortCallback.hpp>
#include <vlGraphics/Geometry.hpp>
#include <vlGraphics/Light.hpp>
class App_PolyDepthSorting: public BaseDemo
{
public:
App_PolyDepthSorting(const vl::String& filename): mFileName(filename) {}
void initEvent()
{
vl::Log::notify(appletInfo());
/* bind Transform */
mTransform_Left = new vl::Transform;
mTransform_Right = new vl::Transform;
rendering()->as<vl::Rendering>()->transform()->addChild( mTransform_Left.get() );
rendering()->as<vl::Rendering>()->transform()->addChild( mTransform_Right.get() );
/* define the Effect to be used */
vl::ref<vl::Effect> effect = new vl::Effect;
/* enable depth test and lighting */
effect->shader()->enable(vl::EN_DEPTH_TEST);
/* enable lighting and material properties */
effect->shader()->setRenderState( new vl::Light, 0 );
effect->shader()->enable(vl::EN_LIGHTING);
effect->shader()->gocMaterial()->setDiffuse( vl::fvec4(1.0f,1.0f,1.0f,0.5f) );
effect->shader()->gocLightModel()->setTwoSide(true);
/* enable alpha blending */
effect->shader()->enable(vl::EN_BLEND);
/* load the object*/
vl::ref<vl::Geometry> geom_no_sort;
vl::ref<vl::Geometry> geom_sorted;
vl::ref<vl::ResourceDatabase> res_db;
res_db = vl::loadResource(mFileName); if ( res_db && res_db->count<vl::Geometry>() ) geom_no_sort = res_db->get<vl::Geometry>(0);
res_db = vl::loadResource(mFileName); if ( res_db && res_db->count<vl::Geometry>() ) geom_sorted = res_db->get<vl::Geometry>(0);
if (!geom_no_sort->normalArray())
geom_no_sort->computeNormals();
if (!geom_sorted->normalArray())
geom_sorted->computeNormals();
/*
if you want you can do
geom_sorted->setDisplayListEnabled(true);
or
geom_sorted->setBufferObjectEnabled(true);
but note that in this case the DepthSortCallback will schedule an update of the BufferObject or of the display list
at every frame! This will almost centainly make the use of BufferObjects or display lists useful if not harmful, performance-wise.
*/
/* add the two objects to the scene manager */
vl::ref<vl::Actor> actor_no_sort = sceneManager()->tree()->addActor( geom_no_sort.get(), effect.get(), mTransform_Left.get() );
vl::ref<vl::Actor> actor_sort = sceneManager()->tree()->addActor( geom_sorted.get(), effect.get(), mTransform_Right.get() );
/* install the vl::DepthSortCallback that will depth-sort each primitive of the Actor upon rendering */
actor_sort->actorEventCallbacks()->push_back( new vl::DepthSortCallback );
/* compute the appropriate offset to be used in updateTransforms() */
geom_no_sort->computeBounds();
geom_sorted->computeBounds();
mOffset = float( (geom_no_sort->boundingSphere().radius() + geom_sorted->boundingSphere().radius()) * 0.5 );
/* positions the two objects next to one another */
updateTransforms();
/* Position the camera to nicely see the objects in the scene.
You must call this function after having positioned your objects in the scene! */
trackball()->adjustView( sceneManager(), vl::vec3(0,0,1), vl::vec3(0,1,0), 1.0f );
}
void updateTransforms()
{
vl::real degrees = vl::Time::currentTime() * 45.0f;
vl::mat4 matrix = vl::mat4::getRotation( degrees, 0,1,0 );
mTransform_Left->setLocalMatrix( vl::mat4::getTranslation(-mOffset,0,0) * matrix );
mTransform_Right->setLocalMatrix(vl::mat4::getTranslation(+mOffset,0,0) * matrix );
}
void updateScene() { updateTransforms(); }
protected:
vl::ref<vl::Transform> mTransform_Left;
vl::ref<vl::Transform> mTransform_Right;
float mOffset;
vl::String mFileName;
};
// Have fun!
BaseDemo* Create_App_PolyDepthSorting(const vl::String& filename) { return new App_PolyDepthSorting(filename); }
| 51.674419 | 136 | 0.564506 | [
"geometry",
"object",
"transform"
] |
d11531d7cdad73cdf2587a81601807cf4ee959e3 | 400 | cpp | C++ | 10768.cpp | jaemin2682/BAEKJOON_ONLINE_JUDGE | 0d5c6907baee61e1fabdbcd96ea473079a9475ed | [
"MIT"
] | null | null | null | 10768.cpp | jaemin2682/BAEKJOON_ONLINE_JUDGE | 0d5c6907baee61e1fabdbcd96ea473079a9475ed | [
"MIT"
] | null | null | null | 10768.cpp | jaemin2682/BAEKJOON_ONLINE_JUDGE | 0d5c6907baee61e1fabdbcd96ea473079a9475ed | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <memory.h>
#include <math.h>
#include <queue>
using namespace std;
int main() {
int month, day;
cin >> month >> day;
if (month > 2) cout << "After";
else if (month < 2) cout << "Before";
else {
if (day > 18) cout << "After";
else if (day < 18) cout << "Before";
else cout << "Special";
}
return 0;
} | 18.181818 | 38 | 0.6075 | [
"vector"
] |
d12619fd216c1b8d4522147621512196a40a4cc4 | 910 | cpp | C++ | GY/Cup.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | GY/Cup.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | GY/Cup.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | #include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<cctype>
#include<ctime>
#include<iostream>
#include<string>
#include<map>
#include<queue>
#include<set>
#include<vector>
#include<iomanip>
#include<bitset>
#include<algorithm>
#define ll long long
#define double long double
using namespace std;
double clp=1e-10;
int main(){
ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--){
double r,R,h,H,v,h2,a,v2,r2,w=acos(-1.0);
cin>>r>>R>>H>>v;
if(R!=r){
h2=H*r/(R-r);
double l=0,ri=H;
while(ri-l>clp){
h=(l+ri)/2;
//r2=h/H*(R-r)+r;
r2=(h2+H-h)*R/h2;
v2=(h*w*(r*r+r*r2+r2*r2))/3.0;
if(v2>v) ri=h;
else l=h;
}
cout<<fixed<<setprecision(6)<<l<<endl;
}
else{
double l=0,ri=H;
while(ri-l>clp){
h=(l+ri)/2;
v2=h*w*r*r;
if(v2>v) ri=h;
else l=h;
}
cout<<fixed<<setprecision(6)<<l<<endl;
}
}
return 0;
}
| 16.851852 | 43 | 0.584615 | [
"vector"
] |
d132808752d5f04caecd8eeb7294da4381ceee66 | 774 | cpp | C++ | Angle.cpp | pannous/mark | 335a66070a9e186a17fed8ae8537cefa45827e63 | [
"MIT"
] | 1 | 2019-01-19T13:10:01.000Z | 2019-01-19T13:10:01.000Z | Angle.cpp | pannous/mark | 335a66070a9e186a17fed8ae8537cefa45827e63 | [
"MIT"
] | null | null | null | Angle.cpp | pannous/mark | 335a66070a9e186a17fed8ae8537cefa45827e63 | [
"MIT"
] | null | null | null | //
// Created by me on 18.05.20.
//
#define _main_
#include "mark.cpp"
//
//It has clean syntax with FULLY-TYPE data model (like JSON or even better)
//It is generic and EXTENSIBLE (like XML or even better)
//It has built-in MIXED CONTENT support (like HTML5 or even better)
//It supportsHIGH-ORDER COMPOSITION (like S-expressions or even better)
int main(int argp, char **argv) {
register_global_signal_exception_handler();
try {
auto s = "hello world"_;
init();
// test();
testCurrent();
return 42;
} catch (chars err) {
printf("\nERROR\n");
printf("%s", err);
} catch (String err) {
printf("\nERROR\n");
printf("%s", err.data);
} catch (SyntaxError *err) {
printf("\nERROR\n");
printf("%s", err->data);
}
usleep(1000000000);
return -1;
}
| 21.5 | 75 | 0.658915 | [
"model"
] |
d134b1bf0e92cea4590865a11065bef485a77e40 | 5,799 | cpp | C++ | clients/cpp-pistache-server/generated/model/PipelineRunNode.cpp | PankTrue/swaggy-jenkins | aca35a7cca6e1fcc08bd399e05148942ac2f514b | [
"MIT"
] | 23 | 2017-08-01T12:25:26.000Z | 2022-01-25T03:44:11.000Z | clients/cpp-pistache-server/generated/model/PipelineRunNode.cpp | PankTrue/swaggy-jenkins | aca35a7cca6e1fcc08bd399e05148942ac2f514b | [
"MIT"
] | 35 | 2017-06-14T03:28:15.000Z | 2022-02-14T10:25:54.000Z | clients/cpp-pistache-server/generated/model/PipelineRunNode.cpp | PankTrue/swaggy-jenkins | aca35a7cca6e1fcc08bd399e05148942ac2f514b | [
"MIT"
] | 11 | 2017-08-31T19:00:20.000Z | 2021-12-19T12:04:12.000Z | /**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* OpenAPI spec version: 1.1.1
* Contact: blah@cliffano.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "PipelineRunNode.h"
namespace org {
namespace openapitools {
namespace server {
namespace model {
PipelineRunNode::PipelineRunNode()
{
m__class = "";
m__classIsSet = false;
m_DisplayName = "";
m_DisplayNameIsSet = false;
m_DurationInMillis = 0;
m_DurationInMillisIsSet = false;
m_EdgesIsSet = false;
m_Id = "";
m_IdIsSet = false;
m_Result = "";
m_ResultIsSet = false;
m_StartTime = "";
m_StartTimeIsSet = false;
m_State = "";
m_StateIsSet = false;
}
PipelineRunNode::~PipelineRunNode()
{
}
void PipelineRunNode::validate()
{
// TODO: implement validation
}
nlohmann::json PipelineRunNode::toJson() const
{
nlohmann::json val = nlohmann::json::object();
if(m__classIsSet)
{
val["_class"] = ModelBase::toJson(m__class);
}
if(m_DisplayNameIsSet)
{
val["displayName"] = ModelBase::toJson(m_DisplayName);
}
if(m_DurationInMillisIsSet)
{
val["durationInMillis"] = m_DurationInMillis;
}
{
nlohmann::json jsonArray;
for( auto& item : m_Edges )
{
jsonArray.push_back(ModelBase::toJson(item));
}
if(jsonArray.size() > 0)
{
val["edges"] = jsonArray;
}
}
if(m_IdIsSet)
{
val["id"] = ModelBase::toJson(m_Id);
}
if(m_ResultIsSet)
{
val["result"] = ModelBase::toJson(m_Result);
}
if(m_StartTimeIsSet)
{
val["startTime"] = ModelBase::toJson(m_StartTime);
}
if(m_StateIsSet)
{
val["state"] = ModelBase::toJson(m_State);
}
return val;
}
void PipelineRunNode::fromJson(nlohmann::json& val)
{
if(val.find("_class") != val.end())
{
setClass(val.at("_class"));
}
if(val.find("displayName") != val.end())
{
setDisplayName(val.at("displayName"));
}
if(val.find("durationInMillis") != val.end())
{
setDurationInMillis(val.at("durationInMillis"));
}
{
m_Edges.clear();
nlohmann::json jsonArray;
if(val.find("edges") != val.end())
{
for( auto& item : val["edges"] )
{
if(item.is_null())
{
m_Edges.push_back( PipelineRunNodeedges() );
}
else
{
PipelineRunNodeedges newItem;
newItem.fromJson(item);
m_Edges.push_back( newItem );
}
}
}
}
if(val.find("id") != val.end())
{
setId(val.at("id"));
}
if(val.find("result") != val.end())
{
setResult(val.at("result"));
}
if(val.find("startTime") != val.end())
{
setStartTime(val.at("startTime"));
}
if(val.find("state") != val.end())
{
setState(val.at("state"));
}
}
std::string PipelineRunNode::getClass() const
{
return m__class;
}
void PipelineRunNode::setClass(std::string const& value)
{
m__class = value;
m__classIsSet = true;
}
bool PipelineRunNode::classIsSet() const
{
return m__classIsSet;
}
void PipelineRunNode::unset_class()
{
m__classIsSet = false;
}
std::string PipelineRunNode::getDisplayName() const
{
return m_DisplayName;
}
void PipelineRunNode::setDisplayName(std::string const& value)
{
m_DisplayName = value;
m_DisplayNameIsSet = true;
}
bool PipelineRunNode::displayNameIsSet() const
{
return m_DisplayNameIsSet;
}
void PipelineRunNode::unsetDisplayName()
{
m_DisplayNameIsSet = false;
}
int32_t PipelineRunNode::getDurationInMillis() const
{
return m_DurationInMillis;
}
void PipelineRunNode::setDurationInMillis(int32_t const value)
{
m_DurationInMillis = value;
m_DurationInMillisIsSet = true;
}
bool PipelineRunNode::durationInMillisIsSet() const
{
return m_DurationInMillisIsSet;
}
void PipelineRunNode::unsetDurationInMillis()
{
m_DurationInMillisIsSet = false;
}
std::vector<PipelineRunNodeedges>& PipelineRunNode::getEdges()
{
return m_Edges;
}
bool PipelineRunNode::edgesIsSet() const
{
return m_EdgesIsSet;
}
void PipelineRunNode::unsetEdges()
{
m_EdgesIsSet = false;
}
std::string PipelineRunNode::getId() const
{
return m_Id;
}
void PipelineRunNode::setId(std::string const& value)
{
m_Id = value;
m_IdIsSet = true;
}
bool PipelineRunNode::idIsSet() const
{
return m_IdIsSet;
}
void PipelineRunNode::unsetId()
{
m_IdIsSet = false;
}
std::string PipelineRunNode::getResult() const
{
return m_Result;
}
void PipelineRunNode::setResult(std::string const& value)
{
m_Result = value;
m_ResultIsSet = true;
}
bool PipelineRunNode::resultIsSet() const
{
return m_ResultIsSet;
}
void PipelineRunNode::unsetResult()
{
m_ResultIsSet = false;
}
std::string PipelineRunNode::getStartTime() const
{
return m_StartTime;
}
void PipelineRunNode::setStartTime(std::string const& value)
{
m_StartTime = value;
m_StartTimeIsSet = true;
}
bool PipelineRunNode::startTimeIsSet() const
{
return m_StartTimeIsSet;
}
void PipelineRunNode::unsetStartTime()
{
m_StartTimeIsSet = false;
}
std::string PipelineRunNode::getState() const
{
return m_State;
}
void PipelineRunNode::setState(std::string const& value)
{
m_State = value;
m_StateIsSet = true;
}
bool PipelineRunNode::stateIsSet() const
{
return m_StateIsSet;
}
void PipelineRunNode::unsetState()
{
m_StateIsSet = false;
}
}
}
}
}
| 19.859589 | 91 | 0.629074 | [
"object",
"vector",
"model"
] |
d13749fd0be5dfaaba9b7da0201d8df98f4bf507 | 11,572 | hpp | C++ | Viewer/ecflowUI/src/VNode.hpp | ecmwf/ecflow | 2498d0401d3d1133613d600d5c0e0a8a30b7b8eb | [
"Apache-2.0"
] | 11 | 2020-08-07T14:42:45.000Z | 2021-10-21T01:59:59.000Z | Viewer/ecflowUI/src/VNode.hpp | CoollRock/ecflow | db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d | [
"Apache-2.0"
] | 10 | 2020-08-07T14:36:27.000Z | 2022-02-22T06:51:24.000Z | Viewer/ecflowUI/src/VNode.hpp | CoollRock/ecflow | db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d | [
"Apache-2.0"
] | 6 | 2020-08-07T14:34:38.000Z | 2022-01-10T12:06:27.000Z | //============================================================================
// Copyright 2009-2020 ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
//============================================================================
#ifndef VNODE_HPP_
#define VNODE_HPP_
#include <vector>
#include <set>
#include <QColor>
#include <QStringList>
#include "Aspect.hpp"
#include "Node.hpp"
#include "VItem.hpp"
class AttributeFilter;
class IconFilter;
class ServerHandler;
class TriggerCollector;
class TriggeredScanner;
class VAttributeType;
class VServer;
class VServerSettings;
class VNodeTriggerData;
class VNodeInternalState
{
public:
VNodeInternalState() : tryNo_(0), flag_(0) {}
unsigned char tryNo_;
unsigned char flag_;
};
//Describes the major changes during an update
class VNodeChange
{
public:
VNodeChange() : cachedAttrNum_(-1), attrNum_(-1), cachedNodeNum_(-1),
nodeNum_(-1), nodeAddAt_(-1), nodeRemoveAt_(-1),
ignore_(false), rescan_(false) {}
int cachedAttrNum_;
int attrNum_;
int cachedNodeNum_;
int nodeNum_;
int nodeAddAt_;
int nodeRemoveAt_;
bool ignore_;
bool rescan_;
};
//Describes the major changes during an update
class VServerChange
{
public:
VServerChange() : suiteNum_(0), attrNum_(0) {} //, totalNum_(0) {}
int suiteNum_;
int attrNum_;
//int totalNum_;
};
class VServerCache
{
public:
std::vector<Variable> vars_;
std::vector<Variable> genVars_;
ecf::Flag flag_;
void clear() {
vars_.clear();
genVars_.clear();
flag_.reset();
}
};
class VNode : public VItem
{
friend class VServer;
friend class VLabelAttr;
friend class VMeterAttr;
friend class VEventAttr;
friend class VRepeatAttr;
friend class VTriggerAttr;
friend class VLimitAttr;
friend class VLimiterAttr;
friend class VLateAttr;
friend class VTimeAttr;
friend class VDateAttr;
friend class VGenVarAttr;
friend class VUserVarAttr;
public:
VNode(VNode* parent,node_ptr);
~VNode() override;
enum SortMode {ParentToChildSort,ChildToParentSort};
VServer *root() const override;
ServerHandler* server() const override;
virtual VNode* suite() const;
const ecf::Calendar& calendar() const;
node_ptr node() const {return node_;}
VNode* isNode() const override {return const_cast<VNode*>(this);}
bool isTopLevel() const override;
//Attributes
const std::vector<VAttribute*>& attr() const {return attr_;}
virtual const std::vector<VAttribute*>& attrForSearch() {return attr_;}
int attrNum(AttributeFilter* filter=nullptr) const;
VAttribute* attribute(int,AttributeFilter *filter=nullptr) const;
VAttribute* attributeForType(int,VAttributeType*) const;
int indexOfAttribute(const VAttribute* a, AttributeFilter *filter) const;
VAttribute* findAttribute(QStringList aData);
VAttribute* findAttribute(const std::string& typeName,const std::string& name);
VAttribute* findAttribute(VAttributeType* type,const std::string& name);
int numOfChildren() const { return static_cast<int>(children_.size());}
VNode* childAt(int index) const;
int indexOfChild(const VNode* vn) const;
int indexOfChild(node_ptr n) const;
VNode* findChild(const std::string& name) const;
void collect(std::vector<VNode*>& vec) const;
void collectAbortedTasks(std::vector<VNode*>& vec) const;
//Get all the variables
virtual int variablesNum() const;
virtual int genVariablesNum() const;
virtual void variables(std::vector<Variable>& vars) const;
virtual void genVariables(std::vector<Variable>& genVars) const;
virtual std::string genVariable(const std::string& key) const;
virtual std::string findVariable(const std::string& key,bool substitute=false) const;
virtual bool substituteVariableValue(std::string& val) const;
virtual void collectInheritedVariableNames(std::set<std::string>& vars) const;
//Find a variable in the given node or in its ancestors. Both the variables and the
//generated variables are searched.
virtual std::string findInheritedVariable(const std::string& key,bool substitute=false) const;
std::string fullPath() const override;
virtual std::string absNodePath() const;
bool pathEndMatch(const std::string &relPath) const;
bool sameName(const std::string& name) const;
bool sameContents(VItem* item) const override;
std::string strName() const override;
QString name() const override;
std::string serverName() const;
virtual QString stateName();
virtual QString serverStateName();
virtual QString defaultStateName();
virtual bool isDefaultStateComplete();
virtual bool isSuspended() const;
virtual bool isAborted() const;
virtual bool isSubmitted() const;
virtual bool isActive() const;
virtual QColor stateColour() const;
virtual QColor realStateColour() const;
virtual QColor stateFontColour() const;
virtual QColor typeFontColour() const;
virtual int tryNo() const;
virtual void internalState(VNodeInternalState&) {}
bool hasAccessed() const;
std::vector<VNode*> ancestors(SortMode sortMode);
VNode* ancestorAt(int idx,SortMode sortMode);
virtual std::string flagsAsStr() const;
virtual bool isFlagSet(ecf::Flag::Type f) const;
int index() const {return index_;}
const std::string& nodeType();
virtual QString toolTip();
virtual void why(std::vector<std::string>& bottomUp,
std::vector<std::string>& topDown) const;
virtual void why(std::vector<std::string>& theReasonWhy) const {}
const std::string& abortedReason() const;
void statusChangeTime(QString&) const;
unsigned int statusChangeTime() const;
bool userLogServer(std::string& host,std::string& port);
bool logServer(std::string& host,std::string& port);
void triggerExpr(std::string&,std::string&) const;
void triggers(TriggerCollector*);
void triggered(TriggerCollector* tlc,TriggeredScanner* scanner=nullptr);
void clearTriggerData();
void addTriggeredData(VItem* n);
void addTriggeredData(VItem* a,VAttribute* n);
void triggeredByEvent(const std::string& name,std::vector<std::string>& triggeredVec,TriggeredScanner* scanner);
QString nodeMenuMode() const override;
QString defStatusNodeMenuMode() const override;
virtual void print();
protected:
void clear();
void addChild(VNode*);
void removeChild(VNode*);
void scanAttr();
void rescanAttr();
void findAttributes(VAttributeType*,std::vector<VAttribute*>& v);
VNode* find(const std::vector<std::string>& pathVec);
virtual void check(VServerSettings* conf,bool) {}
virtual void check(VServerSettings* conf,const VNodeInternalState&) {}
void setIndex(int i) {index_=i;}
VAttribute* getLimit(const std::string& name);
static void triggersInChildren(VNode *n,VNode* nn,TriggerCollector* tlc);
static void triggeredByChildren(VNode *n,VNode* parent,TriggerCollector* tlc);
node_ptr node_;
std::vector<VNode*> children_;
mutable std::vector<VAttribute*> attr_;
int index_;
VNodeTriggerData* data_;
};
class VSuiteNode : public VNode
{
public:
VSuiteNode(VNode* parent,node_ptr node) : VNode(parent,node) {}
VSuiteNode* isSuite() const override {return const_cast<VSuiteNode*>(this);}
const std::string& typeName() const override;
};
class VFamilyNode : public VNode
{
public:
VFamilyNode(VNode* parent,node_ptr node) : VNode(parent,node) {}
VFamilyNode* isFamily() const override {return const_cast<VFamilyNode*>(this);}
const std::string& typeName() const override;
};
class VAliasNode : public VNode
{
public:
VAliasNode(VNode* parent,node_ptr node) : VNode(parent,node) {}
VAliasNode* isAlias() const override {return const_cast<VAliasNode*>(this);}
const std::string& typeName() const override;
};
//This is the root node representing the Server.
class VServer : public VNode
{
friend class ServerHandler;
friend class VNode;
public:
explicit VServer(ServerHandler*);
~VServer() override;
ServerHandler* server() const override {return server_;}
VNode* suite() const override {return nullptr;}
bool isEmpty() const { return numOfChildren() == 0;}
bool isTopLevel() const override {return false;}
VServer* isServer() const override {return const_cast<VServer*>(this);}
VNode* isNode() const override {return nullptr;}
int totalNum() const {return totalNum_;}
int totalNumOfTopLevel(int) const;
int totalNumOfTopLevel(VNode*) const;
int totalNumOfTopLevel(const std::string&) const;
const std::vector<VAttribute*>& attrForSearch() override;
VNode* toVNode(const Node* nc) const;
void beginUpdate(VNode* node,const std::vector<ecf::Aspect::Type>& aspect,VNodeChange&);
void endUpdate(VNode* node,const std::vector<ecf::Aspect::Type>& aspect,const VNodeChange&);
void beginUpdate(const std::vector<ecf::Aspect::Type>& aspect);
VNode* nodeAt(int) const;
const std::vector<VNode*>& nodes() const {return nodes_;}
const std::string& typeName() const override;
QString toolTip() override;
//From VNode
std::string absNodePath() const override {return "/";}
QString stateName() override;
QString defaultStateName() override;
QString serverStateName() override;
bool isSuspended() const override;
QColor stateColour() const override;
QColor stateFontColour() const override;
std::string strName() const override;
int tryNo() const override {return 0;}
void suites(std::vector<std::string>&);
VNode* find(const std::string& fullPath);
//Get all the variables
int variablesNum() const override;
int genVariablesNum() const override;
void variables(std::vector<Variable>& vars) const override;
void genVariables(std::vector<Variable>& genVars) const override;
std::string genVariable(const std::string& key) const override;
//Find a variable in the Defs. Both the user_variables and the
//server variables are searched.
std::string findVariable(const std::string& key,bool substitute=false) const override;
std::string findInheritedVariable(const std::string& key,bool substitute=false) const override;
bool substituteVariableValue(std::string& val) const override;
std::string flagsAsStr() const override;
bool isFlagSet(ecf::Flag::Type f) const override;
void why(std::vector<std::string>& theReasonWhy) const override;
QString logOrCheckpointError() const;
bool triggeredScanned() const {return triggeredScanned_;}
void print() override;
protected:
//Clear contents and rebuild the whole tree.
void beginScan(VServerChange&);
void endScan();
void setTriggeredScanned(bool b) {triggeredScanned_=b;}
void clearNodeTriggerData();
private:
void clear();
//void clear(VNode*);
void scan(VNode*,bool);
void deleteNode(VNode* node,bool);
void updateCache();
void updateCache(defs_ptr defs);
ServerHandler* server_;
int totalNum_;
std::vector<int> totalNumInChild_;
std::vector<VNode*> nodes_;
bool triggeredScanned_;
VServerCache cache_;
std::vector<Variable> prevGenVars_;
ecf::Flag prevFlag_;
std::vector<VAttribute*> attrForSearch_;
std::map<std::string,VNodeInternalState> prevNodeState_;
};
#endif
| 31.445652 | 116 | 0.715175 | [
"vector"
] |
d13b7a71e7395dfc40f15003cf0d97341a769e85 | 7,383 | cpp | C++ | src/openms/source/ANALYSIS/OPENSWATH/ChromatogramExtractor.cpp | tomas-pluskal/openms | 136ec9057435f6d45d65a8e1465b2a6cff9621a8 | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/openms/source/ANALYSIS/OPENSWATH/ChromatogramExtractor.cpp | tomas-pluskal/openms | 136ec9057435f6d45d65a8e1465b2a6cff9621a8 | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/openms/source/ANALYSIS/OPENSWATH/ChromatogramExtractor.cpp | tomas-pluskal/openms | 136ec9057435f6d45d65a8e1465b2a6cff9621a8 | [
"Zlib",
"Apache-2.0"
] | null | null | null | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2015.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#include <OpenMS/ANALYSIS/OPENSWATH/ChromatogramExtractor.h>
namespace OpenMS
{
void ChromatogramExtractor::prepare_coordinates(std::vector< OpenSwath::ChromatogramPtr > & output_chromatograms,
std::vector< ExtractionCoordinates > & coordinates,
OpenMS::TargetedExperiment & transition_exp_used,
const double rt_extraction_window, const bool ms1) const
{
// hash of the peptide reference containing all transitions
typedef std::map<String, std::vector<const ReactionMonitoringTransition*> > PeptideTransitionMapType;
PeptideTransitionMapType peptide_trans_map;
for (Size i = 0; i < transition_exp_used.getTransitions().size(); i++)
{
peptide_trans_map[transition_exp_used.getTransitions()[i].getPeptideRef()].push_back(&transition_exp_used.getTransitions()[i]);
}
// Determine iteration size (nr peptides or nr transitions)
Size itersize;
if (ms1) {itersize = transition_exp_used.getPeptides().size();}
else {itersize = transition_exp_used.getTransitions().size();}
for (Size i = 0; i < itersize; i++)
{
OpenSwath::ChromatogramPtr s(new OpenSwath::Chromatogram);
output_chromatograms.push_back(s);
ChromatogramExtractor::ExtractionCoordinates coord;
TargetedExperiment::Peptide pep;
OpenMS::ReactionMonitoringTransition transition;
if (ms1)
{
pep = transition_exp_used.getPeptides()[i];
transition = (*peptide_trans_map[pep.id][0]);
coord.mz = transition.getPrecursorMZ();
coord.id = pep.id;
}
else
{
transition = transition_exp_used.getTransitions()[i];
pep = transition_exp_used.getPeptideByRef(transition.getPeptideRef());
coord.mz = transition.getProductMZ();
coord.id = transition.getNativeID();
}
if (pep.rts.empty() || pep.rts[0].getCVTerms()["MS:1000896"].empty())
{
// we don't have retention times -> this is only a problem if we actually
// wanted to use the RT limit feature.
if (rt_extraction_window < 0)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, __PRETTY_FUNCTION__,
"Error: Peptide " + pep.id + " does not have normalized retention times (term 1000896) which are necessary to perform an RT-limited extraction");
}
coord.rt_end = -1;
coord.rt_start = 0;
}
else
{
double rt = pep.rts[0].getCVTerms()["MS:1000896"][0].getValue().toString().toDouble();
coord.rt_start = rt - rt_extraction_window / 2.0;
coord.rt_end = rt + rt_extraction_window / 2.0;
}
coordinates.push_back(coord);
}
// sort result
std::sort(coordinates.begin(), coordinates.end(), ChromatogramExtractor::ExtractionCoordinates::SortExtractionCoordinatesByMZ);
}
bool ChromatogramExtractor::outsideExtractionWindow_(const ReactionMonitoringTransition& transition, double current_rt,
const TransformationDescription& trafo, double rt_extraction_window)
{
if (rt_extraction_window < 0)
{
return false;
}
// Get the expected retention time, apply the RT-transformation
// (which describes the normalization) and then take the difference.
// Note that we inverted the transformation in the beginning because
// we want to transform from normalized to real RTs here and not the
// other way round.
double expected_rt = PeptideRTMap_[transition.getPeptideRef()];
double de_normalized_experimental_rt = trafo.apply(expected_rt);
if (current_rt < de_normalized_experimental_rt - rt_extraction_window / 2.0 ||
current_rt > de_normalized_experimental_rt + rt_extraction_window / 2.0 )
{
return true;
}
return false;
}
int ChromatogramExtractor::getFilterNr_(String filter)
{
if (filter == "tophat")
{
return 1;
}
else if (filter == "bartlett")
{
return 2;
}
else
{
throw Exception::IllegalArgument(__FILE__, __LINE__, __PRETTY_FUNCTION__,
"Filter either needs to be tophat or bartlett");
}
}
void ChromatogramExtractor::populatePeptideRTMap_(OpenMS::TargetedExperiment& transition_exp, double rt_extraction_window)
{
// Store the peptide retention times in an intermediate map
PeptideRTMap_.clear();
for (Size i = 0; i < transition_exp.getPeptides().size(); i++)
{
const TargetedExperiment::Peptide& pep = transition_exp.getPeptides()[i];
if (pep.rts.empty() || pep.rts[0].getCVTerms()["MS:1000896"].empty())
{
// we don't have retention times -> this is only a problem if we actually
// wanted to use the RT limit feature.
if (rt_extraction_window >= 0)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, __PRETTY_FUNCTION__,
"Error: Peptide " + pep.id + " does not have normalized retention times (term 1000896) which are necessary to perform an RT-limited extraction");
}
continue;
}
PeptideRTMap_[pep.id] = pep.rts[0].getCVTerms()["MS:1000896"][0].getValue().toString().toDouble();
}
}
}
| 43.429412 | 190 | 0.646892 | [
"vector",
"transform"
] |
d149de5288530597e01e00b5d72f1efa206c75f4 | 6,728 | cc | C++ | libsrc/pylith/feassemble/ConstraintSimple.cc | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | null | null | null | libsrc/pylith/feassemble/ConstraintSimple.cc | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | null | null | null | libsrc/pylith/feassemble/ConstraintSimple.cc | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | null | null | null | // -*- C++ -*-
//
// ----------------------------------------------------------------------
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University of Chicago
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2016 University of California, Davis
//
// See COPYING for license information.
//
// ----------------------------------------------------------------------
//
#include <portinfo>
#include "pylith/feassemble/ConstraintSimple.hh" // implementation of object methods
#include "spatialdata/units/Nondimensional.hh" // USES Nondimensional
#include "pylith/topology/Mesh.hh" // USES Mesh
#include "pylith/topology/Field.hh" // USES Field
#include "pylith/problems/ObserversPhysics.hh" // USES ObserversPhysics
#include "pylith/problems/Physics.hh" // USES Physics
#include "pylith/utils/EventLogger.hh" // USES EventLogger
#include "pylith/utils/journals.hh" // USES PYLITH_JOURNAL_*
#include <cassert> // USES assert()
#include <stdexcept> // USES std::runtime_error
// ---------------------------------------------------------------------------------------------------------------------
// Default constructor.
pylith::feassemble::ConstraintSimple::ConstraintSimple(pylith::problems::Physics* const physics) :
Constraint(physics),
_fn(NULL) {
GenericComponent::setName("constraintSimple");
} // constructor
// ---------------------------------------------------------------------------------------------------------------------
// Destructor.
pylith::feassemble::ConstraintSimple::~ConstraintSimple(void) {
deallocate();
} // destructor
// ---------------------------------------------------------------------------------------------------------------------
// Set constraint kernel.
void
pylith::feassemble::ConstraintSimple::setUserFn(const PetscUserFieldFunc fn) {
_fn = fn;
} // setSimple
// ---------------------------------------------------------------------------------------------------------------------
// Initialize constraint domain. Update observers.
void
pylith::feassemble::ConstraintSimple::initialize(const pylith::topology::Field& solution) {
PYLITH_METHOD_BEGIN;
PYLITH_JOURNAL_DEBUG("intialize(solution="<<solution.getLabel()<<")");
assert(_physics);
_observers = NULL;
PetscErrorCode err = 0;
PetscDM dm = solution.dmMesh();
PetscDMLabel label;
PetscDS ds = NULL;
void* context = NULL;
const PylithInt labelId = 1;
PetscInt i_field = -1;
PetscInt *closure = NULL;
PetscIS pointIS;
const PetscInt *points;
PetscInt point, cStart, cEnd, clSize;
err = DMGetLabel(dm, _constraintLabel.c_str(), &label);PYLITH_CHECK_ERROR(err);
err = DMLabelGetStratumIS(label, labelId, &pointIS);PYLITH_CHECK_ERROR(err);
err = ISGetIndices(pointIS, &points);PYLITH_CHECK_ERROR(err);
point = points[0];
err = ISRestoreIndices(pointIS, &points);PYLITH_CHECK_ERROR(err);
err = ISDestroy(&pointIS);PYLITH_CHECK_ERROR(err);
err = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);PYLITH_CHECK_ERROR(err);
err = DMPlexGetTransitiveClosure(dm, point, PETSC_FALSE, &clSize, &closure);PYLITH_CHECK_ERROR(err);
for (int cl = 0; cl < clSize*2; cl += 2) {
PetscDS cds;
const PetscInt q = closure[cl];
PetscInt Nf;
if ((q < cStart) || (q >= cEnd)) { continue;}
err = DMGetCellDS(dm, q, &cds);PYLITH_CHECK_ERROR(err);
err = PetscDSGetNumFields(cds, &Nf);PYLITH_CHECK_ERROR(err);
for (int f = 0; f < Nf; ++f) {
PetscObject disc;
const char *name;
err = PetscDSGetDiscretization(cds, f, &disc);PYLITH_CHECK_ERROR(err);
err = PetscObjectGetName(disc, &name);PYLITH_CHECK_ERROR(err);
if (_subfieldName == std::string(name)) {ds = cds;i_field = f;break;}
}
}
if (!ds) {
std::ostringstream msg;
msg << "INTERNAL ERROR in ConstraintSimple::initialize()\nCould not find a DS with a field named ''" << _subfieldName << "' in solution";
throw std::logic_error(msg.str());
}
err = DMPlexRestoreTransitiveClosure(solution.dmMesh(), point, PETSC_FALSE, &clSize, &closure);PYLITH_CHECK_ERROR(err);
err = DMGetLabel(solution.dmMesh(), _constraintLabel.c_str(), &label);PYLITH_CHECK_ERROR(err);
err = PetscDSAddBoundary(ds, DM_BC_ESSENTIAL, _constraintLabel.c_str(), label, 1, &labelId, i_field,
_constrainedDOF.size(), &_constrainedDOF[0], (void (*)(void))_fn, NULL, context, NULL);
PYLITH_CHECK_ERROR(err);
err = DMViewFromOptions(dm, NULL, "-constraint_simple_dm_view");PYLITH_CHECK_ERROR(err);
{
PetscInt Nds;
err = DMGetNumDS(dm, &Nds);PYLITH_CHECK_ERROR(err);
for (int s = 0; s < Nds; ++s) {
err = DMGetRegionNumDS(dm, s, NULL, NULL, &ds);PYLITH_CHECK_ERROR(err);
err = PetscObjectViewFromOptions((PetscObject) ds, NULL, "-constraint_simple_ds_view");PYLITH_CHECK_ERROR(err);
}
}
PYLITH_METHOD_END;
} // initialize
// ---------------------------------------------------------------------------------------------------------------------
// Set constrained values in solution field.
void
pylith::feassemble::ConstraintSimple::setSolution(pylith::topology::Field* solution,
const double t) {
PYLITH_METHOD_BEGIN;
PYLITH_JOURNAL_DEBUG("setSolution(solution="<<solution->getLabel()<<", t="<<t<<")");
assert(solution);
PetscErrorCode err = 0;
PetscDM dmSoln = solution->dmMesh();
// Get label for constraint.
PetscDMLabel dmLabel = NULL;
err = DMGetLabel(dmSoln, _constraintLabel.c_str(), &dmLabel);PYLITH_CHECK_ERROR(err);
void* context = NULL;
const int labelId = 1;
const int fieldIndex = solution->subfieldInfo(_subfieldName.c_str()).index;
const PylithInt numConstrained = _constrainedDOF.size();
assert(solution->localVector());
err = DMPlexLabelAddCells(dmSoln, dmLabel);PYLITH_CHECK_ERROR(err);
err = DMPlexInsertBoundaryValuesEssential(dmSoln, t, fieldIndex, numConstrained, &_constrainedDOF[0], dmLabel, 1,
&labelId, _fn, context, solution->localVector());PYLITH_CHECK_ERROR(err);
err = DMPlexLabelClearCells(dmSoln, dmLabel);PYLITH_CHECK_ERROR(err);
pythia::journal::debug_t debug(GenericComponent::getName());
if (debug.state()) {
PYLITH_JOURNAL_DEBUG("Displaying solution field");
solution->view("solution field");
} // if
PYLITH_METHOD_END;
} // setSolution
// End of file
| 39.810651 | 145 | 0.600327 | [
"mesh",
"object"
] |
d14cc431ce13b1ff9e22bb6d086c6c048b912e82 | 1,190 | cpp | C++ | cpp/3sum-closest/main.cpp | miRoox/Leetcode | 4c2be3b3499b9fddd7a4467b8fe440b6170d86e5 | [
"MIT"
] | 1 | 2022-01-20T06:05:03.000Z | 2022-01-20T06:05:03.000Z | cpp/3sum-closest/main.cpp | miRoox/Leetcode | 4c2be3b3499b9fddd7a4467b8fe440b6170d86e5 | [
"MIT"
] | null | null | null | cpp/3sum-closest/main.cpp | miRoox/Leetcode | 4c2be3b3499b9fddd7a4467b8fe440b6170d86e5 | [
"MIT"
] | null | null | null | #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"
#include <vector>
using std::vector;
#include <algorithm>
#include <limits>
#include <cmath>
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
std::sort(nums.begin(), nums.end());
int result = 0;
int min_diff = std::numeric_limits<int>::max();
int last = static_cast<int>(nums.size()-1);
for (int i=0; i<last; ++i) {
int j = i+1;
int k = last;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum < target) {
++j;
} else if (sum > target) {
--k;
} else {
return target;
}
int diff = std::abs(sum-target);
if (diff < min_diff) {
min_diff = diff;
result = sum;
}
}
}
return result;
}
};
TEST_CASE("Solution") {
Solution sol;
SUBCASE("basic") {
vector<int> nums{-1,2,1,-4};
CHECK(sol.threeSumClosest(nums, 1) == 2);
}
}
| 25.319149 | 56 | 0.448739 | [
"vector"
] |
d1506200b2a0ca1d5f28fd8f59bc3e7229abc32e | 11,845 | cc | C++ | authpolicy/platform_helper.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 4 | 2020-07-24T06:54:16.000Z | 2021-06-16T17:13:53.000Z | authpolicy/platform_helper.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2021-04-02T17:35:07.000Z | 2021-04-02T17:35:07.000Z | authpolicy/platform_helper.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2020-11-04T22:31:45.000Z | 2020-11-04T22:31:45.000Z | // Copyright 2016 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "authpolicy/platform_helper.h"
#include <fcntl.h>
#include <linux/capability.h>
#include <poll.h>
#include <sys/capability.h>
#include <sys/prctl.h>
#include <sysexits.h>
#include <cstdint>
#include <sys/ioctl.h>
#include <algorithm>
#include <vector>
#include <base/files/file_path.h>
#include <base/files/file_util.h>
namespace authpolicy {
namespace {
// Size limit on the total number of bytes to read from a pipe.
const size_t kMaxReadSize = 16 * 1024 * 1024; // 16 MB
// The size of the buffer used to read from a pipe.
const size_t kBufferSize = PIPE_BUF; // ~4 Kb on my system
// Timeout used for poll()ing pipes.
const int kPollTimeoutMilliseconds = 30000;
// Creates a non-blocking local pipe and returns the read and the write end.
bool CreatePipe(base::ScopedFD* pipe_read_end, base::ScopedFD* pipe_write_end) {
int pipe_fd[2];
if (!base::CreateLocalNonBlockingPipe(pipe_fd)) {
LOG(ERROR) << "Failed to create pipe";
return false;
}
pipe_read_end->reset(pipe_fd[0]);
pipe_write_end->reset(pipe_fd[1]);
return true;
}
// Reads up to |kBufferSize| bytes from the file descriptor |src_fd| and appends
// them to |dst_str|. Sets |done| to true iff the whole file was read
// successfully. Might block if |src_fd| is a blocking pipe. Returns false on
// error.
bool ReadPipe(int src_fd, std::string* dst_str, bool* done) {
*done = false;
char buffer[kBufferSize];
const ssize_t bytes_read = HANDLE_EINTR(read(src_fd, buffer, kBufferSize));
if (bytes_read < 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
PLOG(ERROR) << "read() from fd " << src_fd << " failed";
return false;
}
if (bytes_read == 0)
*done = true;
else if (bytes_read > 0)
dst_str->append(buffer, bytes_read);
return true;
}
// Splices (copies) as much as possible data from the file descriptor |src_fd|
// to |dst_fd|. Sets |done| to true iff the whole |src_fd| file was spliced
// successfully. Might block if |src_fd| or |dst_fd| are blocking pipes. Returns
// false on error.
bool SplicePipe(int dst_fd, int src_fd, bool* done) {
*done = false;
const int flags = SPLICE_F_NONBLOCK | SPLICE_F_MORE | SPLICE_F_MOVE;
const ssize_t bytes_written =
HANDLE_EINTR(splice(src_fd, nullptr, dst_fd, nullptr, INT_MAX, flags));
if (bytes_written < 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
PLOG(ERROR) << "splice() " << src_fd << " failed";
return false;
}
if (bytes_written == 0)
*done = true;
return true;
}
// Writes as much as possible from |src_str|, beginning at position |src_pos|,
// to the file descriptor |dst_fd|. Sets |done| to true iff the whole string
// was written successfully. Handles blocking |dst_fd|. Returns false on error.
// On success, increases |src_pos| by the number of bytes written.
bool WritePipe(int dst_fd,
const std::string& src_str,
size_t* src_pos,
bool* done) {
DCHECK_LE(*src_pos, src_str.size());
// Writing 0 bytes might not be well defined, so early out in this case.
if (*src_pos == src_str.size()) {
*done = true;
return true;
}
*done = false;
const ssize_t bytes_written = HANDLE_EINTR(
write(dst_fd, src_str.data() + *src_pos, src_str.size() - *src_pos));
if (bytes_written < 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
PLOG(ERROR) << "write() to " << dst_fd << " failed";
return false;
}
if (bytes_written > 0) {
*src_pos += bytes_written;
DCHECK_LE(*src_pos, src_str.size());
}
if (*src_pos == src_str.size())
*done = true;
return true;
}
} // namespace
bool ReadPipeToString(int fd, std::string* out) {
char buffer[kBufferSize];
size_t total_read = 0;
while (total_read < kMaxReadSize) {
const ssize_t bytes_read = HANDLE_EINTR(
read(fd, buffer, std::min(kBufferSize, kMaxReadSize - total_read)));
if (bytes_read < 0)
return false;
if (bytes_read == 0)
return true;
total_read += bytes_read;
out->append(buffer, bytes_read);
}
// Size limit hit. Do one more read to check if the file size is exactly
// kMaxReadSize bytes.
return HANDLE_EINTR(read(fd, buffer, 1)) == 0;
}
base::ScopedFD ReadFileToPipe(const base::FilePath& path) {
base::ScopedFD pipe_read_end, pipe_write_end;
if (!authpolicy::CreatePipe(&pipe_read_end, &pipe_write_end))
return base::ScopedFD();
bool done = false;
base::ScopedFD file_fd(open(path.value().c_str(), O_RDONLY | O_NONBLOCK));
if (!file_fd.is_valid()) {
PLOG(ERROR) << "Failed to open file '" << path.value() << "'";
return base::ScopedFD();
}
// Splice twice. The first splice reads the whole file, but doesn't set
// |done|. The second splice sets |done| to true.
if (!SplicePipe(pipe_write_end.get(), file_fd.get(), &done) ||
!SplicePipe(pipe_write_end.get(), file_fd.get(), &done)) {
return base::ScopedFD();
}
if (!done) {
LOG(ERROR) << "Failed to splice the whole pipe in one go";
return base::ScopedFD();
}
return pipe_read_end;
}
bool PerformPipeIo(int stdin_fd,
int stdout_fd,
int stderr_fd,
int input_fd,
const std::string& input_str,
std::string* stdout,
std::string* stderr) {
// Make sure pipes get closed when exiting the scope.
base::ScopedFD stdin_scoped_fd(stdin_fd);
base::ScopedFD stdout_scoped_fd(stdout_fd);
base::ScopedFD stderr_scoped_fd(stderr_fd);
size_t input_str_pos = 0;
bool splicing_input_fd = (input_fd != -1);
while (stdin_scoped_fd.is_valid() || stdout_scoped_fd.is_valid() ||
stderr_scoped_fd.is_valid()) {
// Note that closed files (*_scoped_fd.get() == -1) are ignored.
const int kIndexStdin = 0, kIndexStdout = 1, kIndexStderr = 2;
const char* kPipeNames[] = {"stdin", "stdout", "stderr"};
const int kPollCount = 3;
struct pollfd poll_fds[kPollCount];
poll_fds[kIndexStdin] = {stdin_scoped_fd.get(), POLLOUT, 0};
poll_fds[kIndexStdout] = {stdout_scoped_fd.get(), POLLIN, 0};
poll_fds[kIndexStderr] = {stderr_scoped_fd.get(), POLLIN, 0};
const int poll_result =
HANDLE_EINTR(poll(poll_fds, kPollCount, kPollTimeoutMilliseconds));
if (poll_result < 0) {
PLOG(ERROR) << "poll() failed";
return false;
}
// Treat POLLNVAL as an error for all pipes.
for (int n : {kIndexStdin, kIndexStdout, kIndexStderr}) {
if ((poll_fds[n].revents & POLLNVAL) == 0)
continue;
LOG(ERROR) << "POLLNVAL for " << kPipeNames[n];
return false;
}
// Special case: POLLERR can legitimately happen on the child process'
// stdin if it already exited. Do not treat that as an error unless
// there was data the parent process wanted to send to the child
// process.
for (int n : {kIndexStdin, kIndexStdout, kIndexStderr}) {
if ((poll_fds[n].revents & POLLERR) == 0)
continue;
if (n == kIndexStdin) {
if (!splicing_input_fd && input_str.size() == input_str_pos) {
VLOG(1) << "Ignoring POLLERR for stdin.";
stdin_scoped_fd.reset();
continue;
}
LOG(ERROR) << "Child process stdin closed due to POLLERR when "
<< "there was still data to write.";
}
LOG(ERROR) << "POLLERR for " << kPipeNames[n];
return false;
}
// Should only happen on timeout. Log a warning here, so we get at least a
// log if the process is stale.
if (poll_result == 0)
LOG(WARNING) << "poll() timed out. Process might be stale.";
// Read stdout to the stdout string.
if (stdout_scoped_fd.is_valid() &&
(poll_fds[kIndexStdout].revents & (POLLIN | POLLHUP))) {
bool done = false;
if (!ReadPipe(stdout_scoped_fd.get(), stdout, &done))
return false;
else if (done)
stdout_scoped_fd.reset();
}
// Read stderr to the stderr string.
if (stderr_scoped_fd.is_valid() &&
(poll_fds[kIndexStderr].revents & (POLLIN | POLLHUP))) {
bool done = false;
if (!ReadPipe(stderr_scoped_fd.get(), stderr, &done))
return false;
else if (done)
stderr_scoped_fd.reset();
}
if (stdin_scoped_fd.is_valid() && poll_fds[kIndexStdin].revents & POLLOUT) {
bool done = false;
if (splicing_input_fd) {
// Splice input_fd to stdin_scoped_fd.
if (!SplicePipe(stdin_scoped_fd.get(), input_fd, &done))
return false;
else if (done)
splicing_input_fd = false;
} else {
// Write input_str to stdin_scoped_fd.
if (!WritePipe(stdin_scoped_fd.get(), input_str, &input_str_pos, &done))
return false;
else if (done)
stdin_scoped_fd.reset();
}
}
// Check size limits.
if (stdout->size() > kMaxReadSize || stderr->size() > kMaxReadSize) {
LOG(ERROR) << "Hit size limit";
return false;
}
}
return true;
}
base::ScopedFD DuplicatePipe(int src_fd) {
base::ScopedFD pipe_read_end, pipe_write_end;
if (!authpolicy::CreatePipe(&pipe_read_end, &pipe_write_end))
return base::ScopedFD();
if (HANDLE_EINTR(
tee(src_fd, pipe_write_end.get(), INT_MAX, SPLICE_F_NONBLOCK)) <= 0) {
PLOG(ERROR) << "Failed to duplicate pipe";
return base::ScopedFD();
}
return pipe_read_end;
}
base::ScopedFD WriteStringToPipe(const std::string& str) {
base::ScopedFD pipe_read_end, pipe_write_end;
if (!authpolicy::CreatePipe(&pipe_read_end, &pipe_write_end))
return base::ScopedFD();
if (!base::WriteFileDescriptor(pipe_write_end.get(), str.data(),
str.size())) {
LOG(ERROR) << "Failed to write string to pipe";
return base::ScopedFD();
}
return pipe_read_end;
}
base::ScopedFD WriteStringAndPipeToPipe(const std::string& str, int fd) {
base::ScopedFD pipe_read_end, pipe_write_end;
if (!authpolicy::CreatePipe(&pipe_read_end, &pipe_write_end))
return base::ScopedFD();
if (!base::WriteFileDescriptor(pipe_write_end.get(), str.data(),
str.size())) {
LOG(ERROR) << "Failed to write string to pipe";
return base::ScopedFD();
}
if (HANDLE_EINTR(tee(fd, pipe_write_end.get(), INT_MAX, SPLICE_F_NONBLOCK)) <=
0) {
PLOG(ERROR) << "Failed to duplicate pipe";
return base::ScopedFD();
}
return pipe_read_end;
}
uid_t GetEffectiveUserId() {
return geteuid();
}
bool SetSavedUserAndDropCaps(uid_t saved_uid) {
// Only set the saved UID, keep the other ones.
if (setresuid(-1, -1, saved_uid)) {
PLOG(ERROR) << "setresuid failed";
return false;
}
// Drop capabilities from bounding set.
if (prctl(PR_CAPBSET_DROP, CAP_SETUID) ||
prctl(PR_CAPBSET_DROP, CAP_SETPCAP)) {
PLOG(ERROR) << "Failed to drop caps from bounding set";
return false;
}
// Clear capabilities.
cap_t caps = cap_get_proc();
if (!caps || cap_clear_flag(caps, CAP_INHERITABLE) ||
cap_clear_flag(caps, CAP_EFFECTIVE) ||
cap_clear_flag(caps, CAP_PERMITTED) || cap_set_proc(caps)) {
PLOG(ERROR) << "Clearing caps failed";
return false;
}
return true;
}
ScopedSwitchToSavedUid::ScopedSwitchToSavedUid() {
uid_t real_uid, effective_uid;
CHECK_EQ(0, getresuid(&real_uid, &effective_uid, &saved_uid_));
CHECK(real_uid == effective_uid);
real_and_effective_uid_ = real_uid;
CHECK_EQ(0, setresuid(saved_uid_, saved_uid_, real_and_effective_uid_));
}
ScopedSwitchToSavedUid::~ScopedSwitchToSavedUid() {
CHECK_EQ(0, setresuid(real_and_effective_uid_, real_and_effective_uid_,
saved_uid_));
}
} // namespace authpolicy
| 32.994429 | 80 | 0.652005 | [
"vector"
] |
d151b0f8d4a9162080ac4fb5352c0fc1995d9808 | 1,845 | hpp | C++ | src/maths/geometry/plane.hpp | otgaard/zap | d50e70b5baf5f0fbf7a5a98d80c4d1bcc6166215 | [
"MIT"
] | 8 | 2016-04-24T21:02:59.000Z | 2021-11-14T20:37:17.000Z | src/maths/geometry/plane.hpp | otgaard/zap | d50e70b5baf5f0fbf7a5a98d80c4d1bcc6166215 | [
"MIT"
] | null | null | null | src/maths/geometry/plane.hpp | otgaard/zap | d50e70b5baf5f0fbf7a5a98d80c4d1bcc6166215 | [
"MIT"
] | 1 | 2018-06-09T19:51:38.000Z | 2018-06-09T19:51:38.000Z | //
// Created by Darren Otgaar on 2016/08/07.
//
#ifndef ZAP_PLANE_HPP
#define ZAP_PLANE_HPP
#include <maths/maths.hpp>
#include <maths/geometry/ray.hpp>
namespace zap { namespace maths { namespace geometry {
template <typename T>
struct plane {
using vector = vec3<T>;
using real = T;
plane() = default;
plane(real a, real b, real c, real d) : a(a), b(b), c(c), d(d) { }
plane(const plane& rhs) = default;
plane(const vector& O, const vector& n) { *this = make_plane(O, n); }
static plane make_plane(const vector& O, const vector& n) {
plane P;
const auto N = !n.is_unit() ? maths::normalise(n) : n;
P.a = N.x; P.b = N.y; P.c = N.z;
P.d = -dot(O, N);
return P;
}
static plane make_plane(const vector& P0, const vector& P1, const vector& P2) {
const auto N = maths::normalise(cross(P1 - P0, P2 - P0));
return make_plane(P0, N);
}
plane& operator=(const plane& rhs) = default;
real distance(const vector& P0) const {
return a * P0.x + b * P0.y + c * P0.z + d;
}
plane& normalise() {
const auto inv_d = T(1) / std::sqrt<T>(a*a + b*b + c*c);
a *= inv_d; b *= inv_d; c *= inv_d; d *= inv_d;
return *this;
}
const vector origin() const {
const vector O(0, 0, 0);
return O - distance(O)*normal();
}
const vector normal() const { return vector(a, b, c); }
real a, b, c, d;
};
using plane3f = plane<float>;
using plane3d = plane<double>;
template <typename T>
T distance(const plane<T>& P, const typename plane<T>::vector& P0) {
return P.distance(P0);
}
template <typename T>
T intersection(const plane<T>& P, const ray<typename plane<T>::vector>& R) {
return dot((P.origin() - R.O), P.normal())/dot(R.d, P.normal());
}
}}}
#endif //ZAP_PLANE_HPP
| 24.932432 | 83 | 0.580488 | [
"geometry",
"vector"
] |
d156ac3292ef0883fe43dc772275abef12c9a882 | 2,510 | cpp | C++ | examples/assert.cpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | examples/assert.cpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | examples/assert.cpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2018.
// 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 <fcppt/exception.hpp>
#include <fcppt/text.hpp>
#include <fcppt/assert/exception.hpp>
#include <fcppt/assert/information.hpp>
#include <fcppt/assert/make_message.hpp>
#include <fcppt/assert/post_message.hpp>
#include <fcppt/assert/pre.hpp>
#include <fcppt/assert/throw.hpp>
#include <fcppt/assert/unreachable.hpp>
#include <fcppt/io/cerr.hpp>
namespace
{
bool
other_function();
bool
other_function()
{
return false;
}
//! [assert_pre_post]
void
library_function(
int const _parameter
)
{
// Assert a precondition without a message
FCPPT_ASSERT_PRE(
_parameter < 10
);
bool const some_value(
other_function()
);
// Assert a postcondition with a message
FCPPT_ASSERT_POST_MESSAGE(
some_value,
fcppt::assert_::exception,
FCPPT_TEXT("other_function failed")
);
}
// ![assert_pre_post]
// ![assert_unreachable]
enum class food
{
apple,
banana,
potato,
bread
};
// Check if a given kind of food is a fruit
bool
is_fruit(
food const _value
)
{
// Handle every possible enumerator
switch(
_value
)
{
case food::apple:
case food::banana:
return true;
case food::potato:
case food::bread:
return false;
}
// This should never be reached
FCPPT_ASSERT_UNREACHABLE;
}
// ![assert_unreachable]
// ![assert_throw]
// Define an exception that can be constructed from an
// fcppt::assert_::information
class my_exception
{
public:
explicit
my_exception(
fcppt::assert_::information const &_info
)
:
info_(
_info
)
{
}
fcppt::assert_::information const &
info() const
{
return info_;
}
private:
fcppt::assert_::information info_;
};
void
throwing_function()
{
// Throw an object of my_exception if other_function returns false
FCPPT_ASSERT_THROW(
other_function(),
my_exception
);
}
void
test_function()
try
{
throwing_function();
}
catch(
my_exception const &_exception
)
{
// fcppt::assert_::make_message can be used to turn an
// fcppt::assert_::information into a string.
fcppt::io::cerr()
<<
fcppt::assert_::make_message(
_exception.info()
)
<< FCPPT_TEXT('\n');
}
// ![assert_throw]
}
int
main()
try
{
library_function(
5
);
is_fruit(
food::apple
);
test_function();
}
catch(
fcppt::exception const &_error
)
{
fcppt::io::cerr()
<< _error.string()
<< FCPPT_TEXT('\n');
}
| 14.852071 | 67 | 0.7 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.