blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ce361841765d1a812517c08fea7d6e6f224df231 | 88ae8695987ada722184307301e221e1ba3cc2fa | /media/capture/video/chromeos/mock_video_capture_client.cc | fd38373927c3864806b60e564389d83ada585cb6 | [
"BSD-3-Clause"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 3,238 | cc | // Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/capture/video/chromeos/mock_video_capture_client.h"
#include <string>
#include <utility>
using testing::_;
using testing::Invoke;
namespace media {
namespace unittest_internal {
MockVideoCaptureClient::MockVideoCaptureClient() {
ON_CALL(*this, OnError(_, _, _))
.WillByDefault(Invoke(this, &MockVideoCaptureClient::DumpError));
}
MockVideoCaptureClient::~MockVideoCaptureClient() {
if (quit_cb_) {
std::move(quit_cb_).Run();
}
}
void MockVideoCaptureClient::SetFrameCb(base::OnceClosure frame_cb) {
frame_cb_ = std::move(frame_cb);
}
void MockVideoCaptureClient::SetQuitCb(base::OnceClosure quit_cb) {
quit_cb_ = std::move(quit_cb);
}
void MockVideoCaptureClient::DumpError(media::VideoCaptureError,
const base::Location& location,
const std::string& message) {
DPLOG(ERROR) << location.ToString() << " " << message;
}
void MockVideoCaptureClient::OnIncomingCapturedData(
const uint8_t* data,
int length,
const VideoCaptureFormat& format,
const gfx::ColorSpace& color_space,
int rotation,
bool flip_y,
base::TimeTicks reference_time,
base::TimeDelta timestamp,
int frame_feedback_id) {
ASSERT_GT(length, 0);
ASSERT_TRUE(data);
if (frame_cb_)
std::move(frame_cb_).Run();
}
void MockVideoCaptureClient::OnIncomingCapturedGfxBuffer(
gfx::GpuMemoryBuffer* buffer,
const VideoCaptureFormat& frame_format,
int clockwise_rotation,
base::TimeTicks reference_time,
base::TimeDelta timestamp,
int frame_feedback_id) {
ASSERT_TRUE(buffer);
ASSERT_GT(buffer->GetSize().width() * buffer->GetSize().height(), 0);
if (frame_cb_)
std::move(frame_cb_).Run();
}
void MockVideoCaptureClient::OnIncomingCapturedExternalBuffer(
CapturedExternalVideoBuffer buffer,
std::vector<CapturedExternalVideoBuffer> scaled_buffers,
base::TimeTicks reference_time,
base::TimeDelta timestamp,
gfx::Rect visible_rect) {
if (frame_cb_)
std::move(frame_cb_).Run();
}
// Trampoline methods to workaround GMOCK problems with std::unique_ptr<>.
VideoCaptureDevice::Client::ReserveResult
MockVideoCaptureClient::ReserveOutputBuffer(
const gfx::Size& dimensions,
VideoPixelFormat format,
int frame_feedback_id,
VideoCaptureDevice::Client::Buffer* buffer) {
DoReserveOutputBuffer();
NOTREACHED() << "This should never be called";
return ReserveResult::kSucceeded;
}
void MockVideoCaptureClient::OnIncomingCapturedBuffer(
Buffer buffer,
const VideoCaptureFormat& format,
base::TimeTicks reference_time,
base::TimeDelta timestamp) {
DoOnIncomingCapturedBuffer();
}
void MockVideoCaptureClient::OnIncomingCapturedBufferExt(
Buffer buffer,
const VideoCaptureFormat& format,
const gfx::ColorSpace& color_space,
base::TimeTicks reference_time,
base::TimeDelta timestamp,
gfx::Rect visible_rect,
const VideoFrameMetadata& additional_metadata) {
DoOnIncomingCapturedVideoFrame();
}
} // namespace unittest_internal
} // namespace media
| [
"jengelh@inai.de"
] | jengelh@inai.de |
ab3e1fb1d31c4a5b1e403bef5f41de92a39c7573 | 77ee25aae73961b5abdb9d742dd29459b8816d41 | /cpp/platform/base/error_code_recorder.cc | fad626bb786cc8f46c7232da063d04b0909b04f6 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | ciaraspissed/nearby-connections | eabaff88177289d3b15274fc4ed2e745fe022802 | 233c5f533771c4004bac87a49cbc9f0137d80bfb | refs/heads/master | 2023-08-12T14:43:09.092255 | 2021-09-16T20:18:26 | 2021-09-16T20:19:03 | 407,859,947 | 2 | 0 | Apache-2.0 | 2021-09-18T12:54:05 | 2021-09-18T12:54:04 | null | UTF-8 | C++ | false | false | 4,799 | cc | // Copyright 2020 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 "platform/base/error_code_recorder.h"
#include "platform/base/logging.h"
#include "proto/errorcode/error_code_enums.proto.h"
namespace location {
namespace nearby {
using ::location::nearby::errorcode::proto::CommonError;
using ::location::nearby::errorcode::proto::CONNECT;
using ::location::nearby::errorcode::proto::ConnectError;
using ::location::nearby::errorcode::proto::Description;
using ::location::nearby::errorcode::proto::DISCONNECT;
using ::location::nearby::errorcode::proto::DisconnectError;
using ::location::nearby::errorcode::proto::Event;
using ::location::nearby::errorcode::proto::START_ADVERTISING;
using ::location::nearby::errorcode::proto::START_DISCOVERING;
using ::location::nearby::errorcode::proto::START_LISTENING_INCOMING_CONNECTION;
using ::location::nearby::errorcode::proto::StartAdvertisingError;
using ::location::nearby::errorcode::proto::StartDiscoveringError;
using ::location::nearby::errorcode::proto::
StartListeningIncomingConnectionError;
using ::location::nearby::errorcode::proto::STOP_ADVERTISING;
using ::location::nearby::errorcode::proto::STOP_DISCOVERING;
using ::location::nearby::errorcode::proto::STOP_LISTENING_INCOMING_CONNECTION;
using ::location::nearby::errorcode::proto::StopAdvertisingError;
using ::location::nearby::errorcode::proto::StopDiscoveringError;
using ::location::nearby::errorcode::proto::
StopListeningIncomingConnectionError;
using ::location::nearby::proto::connections::Medium;
// Default static no-op listener
ErrorCodeRecorder::ErrorCodeListener ErrorCodeRecorder::listener_ =
[](const ErrorCodeParams&) {};
void ErrorCodeRecorder::LogErrorCode(Medium medium, Event event, int error,
Description description,
const std::string& pii_message,
const std::string& connection_token) {
NEARBY_LOGS(INFO) << "ErrorCodeRecorder LogErrorCode";
ErrorCodeParams params = BuildErrorCodeParams(
medium, event, error, description, pii_message, connection_token);
listener_(params);
}
ErrorCodeParams ErrorCodeRecorder::BuildErrorCodeParams(
Medium medium, Event event, int error, Description description,
const std::string& pii_message, const std::string& connection_token) {
ErrorCodeParams params = {.medium = medium,
.event = event,
.description = description,
.pii_message = pii_message,
.connection_token = connection_token};
if (errorcode::proto::CommonError_IsValid(error)) {
params.common_error = static_cast<CommonError>(error);
params.is_common_error = true;
} else {
params.is_common_error = false;
switch (event) {
case START_ADVERTISING:
params.start_advertising_error =
static_cast<StartAdvertisingError>(error);
break;
case STOP_ADVERTISING:
params.stop_advertising_error =
static_cast<StopAdvertisingError>(error);
break;
case START_LISTENING_INCOMING_CONNECTION:
params.start_listening_incoming_connection_error =
static_cast<StartListeningIncomingConnectionError>(error);
break;
case STOP_LISTENING_INCOMING_CONNECTION:
params.stop_listening_incoming_connection_error =
static_cast<StopListeningIncomingConnectionError>(error);
break;
case START_DISCOVERING:
params.start_discovering_error =
static_cast<StartDiscoveringError>(error);
break;
case STOP_DISCOVERING:
params.stop_discovering_error =
static_cast<StopDiscoveringError>(error);
break;
case CONNECT:
params.connect_error = static_cast<ConnectError>(error);
break;
case DISCONNECT:
params.disconnect_error = static_cast<DisconnectError>(error);
break;
// Set the error as unknown if undefined event passed in.
default:
params.common_error = errorcode::proto::UNKNOWN_ERROR;
params.is_common_error = true;
break;
}
}
return params;
}
} // namespace nearby
} // namespace location
| [
"copybara-worker@google.com"
] | copybara-worker@google.com |
fc44336763e2d88e95f5fb3cc9649868d638321a | ca94010aea48ed4db12bfcdd71cafa55bac452f1 | /Common/MatlabDlg.cpp | ce631dc1fb001380b1a5bef5c6a23741bd3ba8b5 | [] | no_license | zhangzhi7216/RadarSim | 87542e0919289d10fdf574836f098b84078194fe | fcab2181bfa7cdde78a939a8e0d8917e3f3ce47c | refs/heads/master | 2020-05-28T01:02:59.469055 | 2015-06-03T07:40:28 | 2015-06-03T07:40:28 | 34,791,114 | 1 | 0 | null | 2015-04-29T11:54:35 | 2015-04-29T11:54:35 | null | GB18030 | C++ | false | false | 19,212 | cpp | #include "StdAfx.h"
#include "MatlabDlg.h"
using namespace MatlabHelper;
static char s_Msg[256];
CMatlabDlg::CMatlabDlg(const char *fileName,
const char *planeTrue,
const char *targetTrue,
const char *targetFusion,
const char *targetFilter,
const char *globalVar)
: m_FileName(fileName)
, m_PlaneTrue(planeTrue)
, m_TargetTrue(targetTrue)
, m_TargetFusion(targetFusion)
, m_TargetFilter(targetFilter)
, m_GlobalVar(globalVar)
, m_PlaneTrueInput(NULL)
, m_TargetTrueInput(NULL)
, m_TargetFusionInput(NULL)
, m_TargetFilterInput(NULL)
, m_GlobalVarInput(NULL)
, m_Size(50)
, m_Thread(NULL)
, m_Engine(NULL)
, m_HasRan(false)
{
}
CMatlabDlg::~CMatlabDlg(void)
{
Stop();
if (engClose(m_Engine))
{
AfxMessageBox(TEXT("Close engine engine WTF!"));
}
}
void CMatlabDlg::Show()
{
// Run();
if (m_Thread != 0)
{
// m_ThreadLock.Unlock();
}
else
{
Run();
}
}
void CMatlabDlg::Hide()
{
Stop();
// m_ThreadLock.Lock();
}
void CMatlabDlg::Stop()
{
m_HasRan = false;
// m_ThreadLock.Lock();
if (m_Thread)
{
if (!TerminateThread(m_Thread, 0))
{
AfxMessageBox(TEXT("Close thread WTF!"));
}
m_Thread = 0;
}
// m_Lock.Unlock();
if (m_PlaneTrueInput)
{
DestroyArray(m_PlaneTrueInput);
m_PlaneTrueInput = NULL;
}
if (m_TargetTrueInput)
{
DestroyArray(m_TargetTrueInput);
m_TargetTrueInput = NULL;
}
if (m_TargetFusionInput)
{
DestroyArray(m_TargetFusionInput);
m_TargetFusionInput = NULL;
}
if (m_TargetFilterInput)
{
DestroyArray(m_TargetFilterInput);
m_TargetFilterInput = NULL;
}
if (m_GlobalVarInput)
{
DestroyArray(m_GlobalVarInput);
m_GlobalVarInput = NULL;
}
}
void CMatlabDlg::Reset()
{
Stop();
if (m_PlaneTrueInput)
{
DestroyArray(m_PlaneTrueInput);
m_PlaneTrueInput = NULL;
}
if (m_TargetTrueInput)
{
DestroyArray(m_TargetTrueInput);
m_TargetTrueInput = NULL;
}
if (m_TargetFusionInput)
{
DestroyArray(m_TargetFusionInput);
m_TargetFusionInput = NULL;
}
if (m_TargetFilterInput)
{
DestroyArray(m_TargetFilterInput);
m_TargetFilterInput = NULL;
}
if (m_GlobalVarInput)
{
DestroyArray(m_GlobalVarInput);
m_GlobalVarInput = NULL;
}
m_PlaneTrueDatas.clear();
m_TargetTrueDatas.clear();
m_TargetFusionDatas.clear();
m_TargetFilterDatas.clear();
}
void CMatlabDlg::Run()
{
m_HasRan = true;
// m_Lock.Lock();
if (m_PlaneTrueInput == NULL) m_PlaneTrueInput = CreateDoubleArray(m_PlaneTrueDatas.size(), m_Size * MATLAB_DRAW_TRUE_DATA_SIZE, (const unsigned char *)NULL, 0, 0);
if (m_TargetTrueInput == NULL) m_TargetTrueInput = CreateDoubleArray(m_TargetTrueDatas.size(), m_Size * MATLAB_DRAW_TRUE_DATA_SIZE, (const unsigned char *)NULL, 0, 0);
if (m_TargetFusionInput == NULL) m_TargetFusionInput = CreateDoubleArray(m_TargetFusionDatas.size(), m_Size * MATLAB_DRAW_FUSION_DATA_SIZE, (const unsigned char *)NULL, 0, 0);
if (m_TargetFilterInput == NULL) m_TargetFilterInput = CreateDoubleArray(m_TargetFilterDatas.size(), m_Size * MATLAB_DRAW_FUSION_DATA_SIZE, (const unsigned char *)NULL, 0, 0);
if (m_GlobalVarInput == NULL) m_GlobalVarInput = CreateDoubleArray(PLANE_COUNT + TARGET_COUNT_MAX, GLOBAL_VAR_FRAME_SIZE, (const unsigned char *)NULL, 0, 0);
double *data = mxGetPr(m_PlaneTrueInput);
for (int plane = 0; plane < m_PlaneTrueDatas.size(); ++plane)
{
for (int pos = 0; pos < m_PlaneTrueDatas[plane].size(); ++pos)
{
data[(pos * MATLAB_DRAW_TRUE_DATA_SIZE + 0) * m_PlaneTrueDatas.size() + plane] = m_PlaneTrueDatas[plane][pos].X;
data[(pos * MATLAB_DRAW_TRUE_DATA_SIZE + 1) * m_PlaneTrueDatas.size() + plane] = m_PlaneTrueDatas[plane][pos].Y;
data[(pos * MATLAB_DRAW_TRUE_DATA_SIZE + 2) * m_PlaneTrueDatas.size() + plane] = m_PlaneTrueDatas[plane][pos].Z;
}
}
data = mxGetPr(m_TargetTrueInput);
for (int target = 0; target < m_TargetTrueDatas.size(); ++target)
{
for (int pos = 0; pos < m_TargetTrueDatas[target].size(); ++pos)
{
data[(pos * MATLAB_DRAW_TRUE_DATA_SIZE + 0) * m_TargetTrueDatas.size() + target] = m_TargetTrueDatas[target][pos].X;
data[(pos * MATLAB_DRAW_TRUE_DATA_SIZE + 1) * m_TargetTrueDatas.size() + target] = m_TargetTrueDatas[target][pos].Y;
data[(pos * MATLAB_DRAW_TRUE_DATA_SIZE + 2) * m_TargetTrueDatas.size() + target] = m_TargetTrueDatas[target][pos].Z;
}
}
data = mxGetPr(m_TargetFusionInput);
for (int target = 0; target < m_TargetFusionDatas.size(); ++target)
{
for (int pos = 0; pos < m_TargetFusionDatas[target].size(); ++pos)
{
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 0) * m_TargetFusionDatas.size() + target] = m_TargetFusionDatas[target][pos].m_Pos.X;
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 1) * m_TargetFusionDatas.size() + target] = m_TargetFusionDatas[target][pos].m_Pos.Y;
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 2) * m_TargetFusionDatas.size() + target] = m_TargetFusionDatas[target][pos].m_Pos.Z;
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 3) * m_TargetFusionDatas.size() + target] = m_TargetFusionDatas[target][pos].m_Vel.X;
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 4) * m_TargetFusionDatas.size() + target] = m_TargetFusionDatas[target][pos].m_Vel.Y;
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 5) * m_TargetFusionDatas.size() + target] = m_TargetFusionDatas[target][pos].m_Vel.Z;
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 6) * m_TargetFusionDatas.size() + target] = m_TargetFusionDatas[target][pos].m_Acc.X;
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 7) * m_TargetFusionDatas.size() + target] = m_TargetFusionDatas[target][pos].m_Acc.Y;
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 8) * m_TargetFusionDatas.size() + target] = m_TargetFusionDatas[target][pos].m_Acc.Z;
}
}
data = mxGetPr(m_TargetFilterInput);
for (int target = 0; target < m_TargetFilterDatas.size(); ++target)
{
for (int pos = 0; pos < m_TargetFilterDatas[target].size(); ++pos)
{
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 0) * m_TargetFilterDatas.size() + target] = m_TargetFilterDatas[target][pos].m_Pos.X;
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 1) * m_TargetFilterDatas.size() + target] = m_TargetFilterDatas[target][pos].m_Pos.Y;
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 2) * m_TargetFilterDatas.size() + target] = m_TargetFilterDatas[target][pos].m_Pos.Z;
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 3) * m_TargetFilterDatas.size() + target] = m_TargetFilterDatas[target][pos].m_Vel.X;
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 4) * m_TargetFilterDatas.size() + target] = m_TargetFilterDatas[target][pos].m_Vel.Y;
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 5) * m_TargetFilterDatas.size() + target] = m_TargetFilterDatas[target][pos].m_Vel.Z;
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 6) * m_TargetFilterDatas.size() + target] = m_TargetFilterDatas[target][pos].m_Acc.X;
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 7) * m_TargetFilterDatas.size() + target] = m_TargetFilterDatas[target][pos].m_Acc.Y;
data[(pos * MATLAB_DRAW_FUSION_DATA_SIZE + 8) * m_TargetFilterDatas.size() + target] = m_TargetFilterDatas[target][pos].m_Acc.Z;
}
}
data = mxGetPr(m_GlobalVarInput);
for (int i = 0; i < PLANE_COUNT + TARGET_COUNT_MAX; ++i)
{
for (int j = 0; j < GLOBAL_VAR_FRAME_SIZE; ++j)
{
data[j * (PLANE_COUNT + TARGET_COUNT_MAX) + i] = g_GlobalVar[i].m_G[j];
}
}
m_Thread = CreateThread(NULL,
10 * 1024 * 1024,
MatlabRun,
(LPVOID)this,
CREATE_SUSPENDED,
0);
SetThreadPriority(m_Thread, THREAD_PRIORITY_NORMAL);
ResumeThread(m_Thread);
// MatlabRunSync();
// m_Lock.Unlock();
}
void CMatlabDlg::MatlabRunSync()
{
// m_Lock.Lock();
if (!(m_Engine = engOpen(NULL)))
{
AfxMessageBox(TEXT("打开Matlab引擎错误"));
}
else
{
if (engSetVisible(m_Engine, false))
{
AfxMessageBox(TEXT("Hide engine WTF!"));
}
else
{
engOutputBuffer(m_Engine, s_Msg, 256);
}
}
int result = 0;
wchar_t buf[MAX_PATH];
GetCurrentDirectory(MAX_PATH, buf);
wstring wsCurPath(buf);
string curPath(wsCurPath.begin(), wsCurPath.end());
string cmd = "cd \'" + curPath + "\\bin\'";
result = engEvalString(m_Engine, cmd.c_str());
if (result)
{
AfxMessageBox(TEXT("Cd engine WTF!"));
}
// while (true)
// {
/*
cmd += "clear";
result = engEvalString(m_Engine, cmd.c_str());
if (result)
{
AfxMessageBox(TEXT("Call clear engine WTF!"));
}
*/
result = engPutVariable(m_Engine, m_PlaneTrue, m_PlaneTrueInput);
if (result)
{
AfxMessageBox(TEXT("Put var 1 engine WTF!"));
}
result = engPutVariable(m_Engine, m_TargetTrue, m_TargetTrueInput);
if (result)
{
AfxMessageBox(TEXT("Put var 2 engine WTF!"));
}
result = engPutVariable(m_Engine, m_TargetFusion, m_TargetFusionInput);
if (result)
{
AfxMessageBox(TEXT("Put var 3 engine WTF!"));
}
result = engPutVariable(m_Engine, m_TargetFilter, m_TargetFilterInput);
if (result)
{
AfxMessageBox(TEXT("Put var 4 engine WTF!"));
}
result = engPutVariable(m_Engine, m_GlobalVar, m_GlobalVarInput);
if (result)
{
AfxMessageBox(TEXT("Put var 5 engine WTF!"));
}
cmd = m_FileName;
cmd += "(";
cmd += m_PlaneTrue;
cmd += ", ";
cmd += m_TargetTrue;
cmd += ", ";
cmd += m_TargetFusion;
cmd += ", ";
cmd += m_TargetFilter;
cmd += ", ";
cmd += m_GlobalVar;
cmd += ")";
result = engEvalString(m_Engine, cmd.c_str());
if (result)
{
AfxMessageBox(TEXT("Call func engine WTF!"));
}
if (result)
{
// break;
}
// Sleep(1);
// }
// m_Lock.Unlock();
m_Engine = 0;
/*
m_Lock.Lock();
m_Thread = 0;
m_Lock.Unlock();
return result;
*/
}
DWORD WINAPI CMatlabDlg::MatlabRun(LPVOID lparam)
{
CMatlabDlg *dlg = (CMatlabDlg *)lparam;
// dlg->m_ThreadLock.Lock();
if (!(dlg->m_Engine = engOpen(NULL)))
{
AfxMessageBox(TEXT("打开Matlab引擎错误"));
}
else
{
if (engSetVisible(dlg->m_Engine, false))
{
AfxMessageBox(TEXT("Hide engine WTF!"));
}
else
{
engOutputBuffer(dlg->m_Engine, s_Msg, 256);
}
}
int result = 0;
wchar_t buf[MAX_PATH];
GetCurrentDirectory(MAX_PATH, buf);
wstring wsCurPath(buf);
string curPath(wsCurPath.begin(), wsCurPath.end());
string cmd = "cd \'" + curPath + "\\bin\'";
result = engEvalString(dlg->m_Engine, cmd.c_str());
if (result)
{
AfxMessageBox(TEXT("Cd engine WTF!"));
}
// dlg->m_ThreadLock.Unlock();
while (true)
{
/*
cmd += "clear";
result = engEvalString(dlg->m_Engine, cmd.c_str());
if (result)
{
AfxMessageBox(TEXT("Call clear engine WTF!"));
}
*/
// dlg->m_ThreadLock.Lock();
result = engPutVariable(dlg->m_Engine, dlg->m_PlaneTrue, dlg->m_PlaneTrueInput);
if (result)
{
// AfxMessageBox(TEXT("Put var 1 engine WTF!"));
continue;
}
result = engPutVariable(dlg->m_Engine, dlg->m_TargetTrue, dlg->m_TargetTrueInput);
if (result)
{
// AfxMessageBox(TEXT("Put var 2 engine WTF!"));
continue;
}
result = engPutVariable(dlg->m_Engine, dlg->m_TargetFusion, dlg->m_TargetFusionInput);
if (result)
{
// AfxMessageBox(TEXT("Put var 3 engine WTF!"));
continue;
}
result = engPutVariable(dlg->m_Engine, dlg->m_TargetFilter, dlg->m_TargetFilterInput);
if (result)
{
// AfxMessageBox(TEXT("Put var 4 engine WTF!"));
continue;
}
result = engPutVariable(dlg->m_Engine, dlg->m_GlobalVar, dlg->m_GlobalVarInput);
if (result)
{
// AfxMessageBox(TEXT("Put var 5 engine WTF!"));
continue;
}
cmd = dlg->m_FileName;
cmd += "(";
cmd += dlg->m_PlaneTrue;
cmd += ", ";
cmd += dlg->m_TargetTrue;
cmd += ", ";
cmd += dlg->m_TargetFusion;
cmd += ", ";
cmd += dlg->m_TargetFilter;
cmd += ", ";
cmd += dlg->m_GlobalVar;
cmd += ")";
result = engEvalString(dlg->m_Engine, cmd.c_str());
if (result)
{
continue;
}
// dlg->m_ThreadLock.Unlock();
Sleep(1);
}
/*
if (engClose(dlg->m_Engine))
{
AfxMessageBox(TEXT("Close engine engine WTF!"));
}
dlg->m_Engine = 0;
*/
// dlg->m_Lock.Lock();
dlg->m_Thread = 0;
// dlg->m_Lock.Unlock();
return result;
}
void CMatlabDlg::Update()
{
}
void CMatlabDlg::AddPlane(Plane &plane)
{
m_PlaneTrueDatas.push_back(Path());
}
void CMatlabDlg::AddTarget(Target &target)
{
m_TargetTrueDatas.push_back(Path());
m_TargetFusionDatas.push_back(vector<TrueDataFrame>());
m_TargetFilterDatas.push_back(vector<TrueDataFrame>());
}
void CMatlabDlg::SetSize(int size)
{
m_Size = size;
}
void CMatlabDlg::AddPlaneTrueData(int plane, Position pos)
{
if (m_PlaneTrueDatas[plane].size() >= m_Size)
{
return;
}
// m_Lock.Lock();
if (m_PlaneTrueInput)
{
double *data = mxGetPr(m_PlaneTrueInput);
data[(m_PlaneTrueDatas[plane].size() * MATLAB_DRAW_TRUE_DATA_SIZE + 0) * m_PlaneTrueDatas.size() + plane] = pos.X;
data[(m_PlaneTrueDatas[plane].size() * MATLAB_DRAW_TRUE_DATA_SIZE + 1) * m_PlaneTrueDatas.size() + plane] = pos.Y;
data[(m_PlaneTrueDatas[plane].size() * MATLAB_DRAW_TRUE_DATA_SIZE + 2) * m_PlaneTrueDatas.size() + plane] = pos.Z;
}
m_PlaneTrueDatas[plane].push_back(pos);
// m_Lock.Unlock();
}
void CMatlabDlg::AddTargetTrueData(int target, Position pos)
{
if (m_TargetTrueDatas[target].size() >= m_Size)
{
return;
}
// m_Lock.Lock();
if (m_TargetTrueInput)
{
double *data = mxGetPr(m_TargetTrueInput);
data[(m_TargetTrueDatas[target].size() * MATLAB_DRAW_TRUE_DATA_SIZE + 0) * m_TargetTrueDatas.size() + target] = pos.X;
data[(m_TargetTrueDatas[target].size() * MATLAB_DRAW_TRUE_DATA_SIZE + 1) * m_TargetTrueDatas.size() + target] = pos.Y;
data[(m_TargetTrueDatas[target].size() * MATLAB_DRAW_TRUE_DATA_SIZE + 2) * m_TargetTrueDatas.size() + target] = pos.Z;
}
m_TargetTrueDatas[target].push_back(pos);
// m_Lock.Unlock();
}
void CMatlabDlg::AddTargetFusionData(int target, const TrueDataFrame &frame)
{
if (m_TargetFusionDatas[target].size() >= m_Size)
{
return;
}
// m_Lock.Lock();
if (m_TargetFusionInput)
{
double *data = mxGetPr(m_TargetFusionInput);
data[(m_TargetFusionDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 0) * m_TargetFusionDatas.size() + target] = frame.m_Pos.X;
data[(m_TargetFusionDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 1) * m_TargetFusionDatas.size() + target] = frame.m_Pos.Y;
data[(m_TargetFusionDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 2) * m_TargetFusionDatas.size() + target] = frame.m_Pos.Z;
data[(m_TargetFusionDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 3) * m_TargetFusionDatas.size() + target] = frame.m_Vel.X;
data[(m_TargetFusionDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 4) * m_TargetFusionDatas.size() + target] = frame.m_Vel.Y;
data[(m_TargetFusionDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 5) * m_TargetFusionDatas.size() + target] = frame.m_Vel.Z;
data[(m_TargetFusionDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 6) * m_TargetFusionDatas.size() + target] = frame.m_Acc.X;
data[(m_TargetFusionDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 7) * m_TargetFusionDatas.size() + target] = frame.m_Acc.Y;
data[(m_TargetFusionDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 8) * m_TargetFusionDatas.size() + target] = frame.m_Acc.Z;
}
m_TargetFusionDatas[target].push_back(frame);
// m_Lock.Unlock();
}
void CMatlabDlg::AddTargetFilterData(int target, const TrueDataFrame &frame)
{
if (m_TargetFilterDatas[target].size() >= m_Size)
{
return;
}
// m_Lock.Lock();
if (m_TargetFilterInput)
{
double *data = mxGetPr(m_TargetFilterInput);
data[(m_TargetFilterDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 0) * m_TargetFilterDatas.size() + target] = frame.m_Pos.X;
data[(m_TargetFilterDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 1) * m_TargetFilterDatas.size() + target] = frame.m_Pos.Y;
data[(m_TargetFilterDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 2) * m_TargetFilterDatas.size() + target] = frame.m_Pos.Z;
data[(m_TargetFilterDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 3) * m_TargetFilterDatas.size() + target] = frame.m_Vel.X;
data[(m_TargetFilterDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 4) * m_TargetFilterDatas.size() + target] = frame.m_Vel.Y;
data[(m_TargetFilterDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 5) * m_TargetFilterDatas.size() + target] = frame.m_Vel.Z;
data[(m_TargetFilterDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 6) * m_TargetFilterDatas.size() + target] = frame.m_Acc.X;
data[(m_TargetFilterDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 7) * m_TargetFilterDatas.size() + target] = frame.m_Acc.Y;
data[(m_TargetFilterDatas[target].size() * MATLAB_DRAW_FUSION_DATA_SIZE + 8) * m_TargetFilterDatas.size() + target] = frame.m_Acc.Z;
}
m_TargetFilterDatas[target].push_back(frame);
// m_Lock.Unlock();
}
void CMatlabDlg::UpdateGlobalVar()
{
// m_Lock.Lock();
if (m_GlobalVarInput)
{
double *data = mxGetPr(m_GlobalVarInput);
int m = mxGetM(m_GlobalVarInput);
int n = mxGetN(m_GlobalVarInput);
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
g_GlobalVar[i].m_G[j] = data[j * m + i];
}
}
}
// m_Lock.Unlock();
} | [
"zanmato1984@gmail.com"
] | zanmato1984@gmail.com |
e8fc80254293c10f9ef6119d39380c7cce49f4b3 | 0ecf2d067e8fe6cdec12b79bfd68fe79ec222ffd | /chrome/browser/ui/autofill/save_card_bubble_controller_impl_browsertest.cc | 1fdfd33910effd350fe21b53e0b9dfd5b3842d29 | [
"BSD-3-Clause"
] | permissive | yachtcaptain23/browser-android-tabs | e5144cee9141890590d6d6faeb1bdc5d58a6cbf1 | a016aade8f8333c822d00d62738a922671a52b85 | refs/heads/master | 2021-04-28T17:07:06.955483 | 2018-09-26T06:22:11 | 2018-09-26T06:22:11 | 122,005,560 | 0 | 0 | NOASSERTION | 2019-05-17T19:37:59 | 2018-02-19T01:00:10 | null | UTF-8 | C++ | false | false | 4,418 | cc | // Copyright 2017 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/ui/autofill/save_card_bubble_controller_impl.h"
#include <memory>
#include "base/json/json_reader.h"
#include "base/macros.h"
#include "base/test/scoped_feature_list.h"
#include "base/values.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/test/test_browser_dialog.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/ui_base_features.h"
namespace autofill {
class SaveCardBubbleControllerImplTest : public DialogBrowserTest {
public:
SaveCardBubbleControllerImplTest() {}
void SetUpCommandLine(base::CommandLine* command_line) override {
DialogBrowserTest::SetUpCommandLine(command_line);
scoped_feature_list_.InitAndEnableFeature(features::kExperimentalUi);
}
std::unique_ptr<base::DictionaryValue> GetTestLegalMessage() {
std::unique_ptr<base::Value> value(base::JSONReader::Read(
"{"
" \"line\" : [ {"
" \"template\": \"The legal documents are: {0} and {1}.\","
" \"template_parameter\" : [ {"
" \"display_text\" : \"Terms of Service\","
" \"url\": \"http://www.example.com/tos\""
" }, {"
" \"display_text\" : \"Privacy Policy\","
" \"url\": \"http://www.example.com/pp\""
" } ]"
" } ]"
"}"));
base::DictionaryValue* dictionary;
value->GetAsDictionary(&dictionary);
return dictionary->CreateDeepCopy();
}
// DialogBrowserTest:
void ShowUi(const std::string& name) override {
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
// Do lazy initialization of SaveCardBubbleControllerImpl. Alternative:
// invoke via ChromeAutofillClient.
SaveCardBubbleControllerImpl::CreateForWebContents(web_contents);
controller_ = SaveCardBubbleControllerImpl::FromWebContents(web_contents);
DCHECK(controller_);
// Behavior depends on the test case name (not the most robust, but it will
// do).
if (name == "Local") {
controller_->ShowBubbleForLocalSave(test::GetCreditCard(),
base::DoNothing());
} else {
bool should_request_name_from_user =
name == "Server_WithCardholderNameTextfield";
controller_->ShowBubbleForUpload(
test::GetMaskedServerCard(), GetTestLegalMessage(),
should_request_name_from_user, base::DoNothing());
}
}
SaveCardBubbleControllerImpl* controller() { return controller_; }
private:
SaveCardBubbleControllerImpl* controller_ = nullptr;
base::test::ScopedFeatureList scoped_feature_list_;
DISALLOW_COPY_AND_ASSIGN(SaveCardBubbleControllerImplTest);
};
// Invokes a bubble asking the user if they want to save a credit card locally.
IN_PROC_BROWSER_TEST_F(SaveCardBubbleControllerImplTest, InvokeUi_Local) {
ShowAndVerifyUi();
}
// Invokes a bubble asking the user if they want to save a credit card to the
// server.
IN_PROC_BROWSER_TEST_F(SaveCardBubbleControllerImplTest, InvokeUi_Server) {
ShowAndVerifyUi();
}
// Invokes a bubble asking the user if they want to save a credit card to the
// server, with an added textfield for entering/confirming cardholder name.
IN_PROC_BROWSER_TEST_F(SaveCardBubbleControllerImplTest,
InvokeUi_Server_WithCardholderNameTextfield) {
ShowAndVerifyUi();
}
// Tests that opening a new tab will hide the save card bubble.
IN_PROC_BROWSER_TEST_F(SaveCardBubbleControllerImplTest, NewTabHidesDialog) {
ShowUi("Local");
EXPECT_NE(nullptr, controller()->save_card_bubble_view());
// Open a new tab page in the foreground.
ui_test_utils::NavigateToURLWithDisposition(
browser(), GURL(chrome::kChromeUINewTabURL),
WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB |
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
EXPECT_EQ(nullptr, controller()->save_card_bubble_view());
}
} // namespace autofill
| [
"artem@brave.com"
] | artem@brave.com |
ed81edecec54c1243a2b302019919af06be944f3 | 17210b90a6700efc3440410493fe423255084d5f | /02Vareshchuk/Main.cpp | e84d8acd439f3eaf5bff290e0c0aa23195af9d8a | [] | no_license | vrshchk/pp_cpp | 9c5e5c9b4f7dfdb57f21a4733088efd666aa3b38 | e213d616fd3dfb2b081202e1c7e6c8d304d75944 | refs/heads/main | 2023-02-02T08:56:16.502920 | 2020-12-21T09:53:06 | 2020-12-21T09:53:06 | 317,041,849 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 880 | cpp | #include "Header.h"
#include <iostream>
#include <chrono>
using namespace std;
int main()
{
using namespace std::chrono;
time_point<system_clock> start, end;
start = system_clock::now();
cout << "Result for iterative power(30,431): " << power(30, 83) << endl;
end = system_clock::now();
duration<double> elapsed_seconds = end - start;
time_t end_time = system_clock::to_time_t(end);
cout << "time needed: " << elapsed_seconds.count() << "s\n\n";
start = system_clock::now();
cout << "Result for recursive power(30,431): " << recPower(30, 83) << endl;
end = system_clock::now();
elapsed_seconds = end - start;
end_time = system_clock::to_time_t(end);
cout << "time needed: " << elapsed_seconds.count() << "s\n\n";
cout << "(iterative) 20 in power 51: " << power(20, 51) << "\n";
cout << "(quick) 20 in power 51: " << quickPower(2, 51) << "\n";
return 0;
} | [
"maryvaresh12@gmail.com"
] | maryvaresh12@gmail.com |
494369cca0b444f3bbc1ddc49b833d15ab62e152 | 950cf2c2171b5435522852e2815325b7ef7a66ff | /camera.h | 817238ee86233720e70198a9551d81efd68b2a92 | [] | no_license | jsksjs/ImEd-Demo | b7f959cd45b45ddf7eb0caa1bbe6c561e6c1cd00 | 50a98e0b2cb4c2263538397ea73ec08e0a04f5cc | refs/heads/master | 2020-04-11T10:52:51.452965 | 2018-12-17T02:22:23 | 2018-12-17T02:22:23 | 161,729,287 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 427 | h | #ifndef CAMERA_H
#define CAMERA_H
#include <QMatrix4x4>
#include <QVector3D>
class Camera
{
public:
Camera(const QVector3D &pos, const float left, const float right, const float bottom, const float top, const float nearPlane, const float farPlane);
QMatrix4x4 GetViewProjection() const;
private:
QMatrix4x4 m_ortho;
QVector3D m_position;
QVector3D m_forward;
QVector3D m_up;
};
#endif // CAMERA_H
| [
"jsksjs12@live.com"
] | jsksjs12@live.com |
74aabcea60e25d66dac6cfa7930e4bba8698fb93 | f24e7daff602a5e3f2b4909721548a9f84598a56 | /topcoder/Single-Round-Match-653/450/driver.cc | 3dca8851ec955491a70f9f9c0bafcdd66f163036 | [] | no_license | permin/Olymp | 05b594e8c09adb04c1aa065ba6dd7f2dae8f4d6e | 51ac43fcbcc14136ed718481f64e09036f10ddf8 | refs/heads/master | 2021-01-18T23:04:00.491119 | 2017-03-08T22:22:25 | 2017-03-08T22:22:25 | 23,457,833 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,877 | cc |
#include "Singing.cc"
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <sys/time.h>
#include <vector>
const static double __EPSILON = 1e-9;
static double __time = 0.0;
static void __timer_start()
{
struct timeval tv;
if (gettimeofday(&tv, NULL) == 0)
{
__time = double(tv.tv_sec) * 1000.0 + double(tv.tv_usec) * 0.001;
}
}
static double __timer_stop()
{
double start = __time;
__timer_start();
return __time - start;
}
static void __eat_whitespace(std::istream& in)
{
while (in.good() && std::isspace(in.peek())) in.get();
}
std::ostream& operator << (std::ostream& out, const std::string& str)
{
out << '"' << str.c_str() << '"';
return out;
}
std::istream& operator >> (std::istream& in, std::string& str)
{
__eat_whitespace(in);
int c;
if (in.good() && (c = in.get()) == '"')
{
std::ostringstream s;
while (in.good() && (c = in.get()) != '"')
{
s.put(char(c));
}
str = s.str();
}
return in;
}
template <class T>
std::istream& operator >> (std::istream& in, std::vector<T>& vec)
{
__eat_whitespace(in);
int c;
if (in.good() && (c = in.get()) == '{')
{
__eat_whitespace(in);
vec.clear();
while (in.good() && (c = in.get()) != '}')
{
if (c != ',') in.putback(static_cast<char>(c));
T t;
in >> t;
__eat_whitespace(in);
vec.push_back(t);
}
}
return in;
}
template <class T>
bool __equals(const T& actual, const T& expected)
{
return actual == expected;
}
bool __equals(double actual, double expected)
{
if (std::abs(actual - expected) < __EPSILON)
{
return true;
}
else
{
double minimum = std::min(expected * (1.0 - __EPSILON), expected * (1.0 + __EPSILON));
double maximum = std::max(expected * (1.0 - __EPSILON), expected * (1.0 + __EPSILON));
return actual > minimum && actual < maximum;
}
}
bool __equals(const std::vector<double>& actual, const std::vector<double>& expected)
{
if (actual.size() != expected.size())
{
return false;
}
for (size_t i = 0; i < actual.size(); ++i)
{
if (!__equals(actual[i], expected[i]))
{
return false;
}
}
return true;
}
int main(int argc, char** )
{
bool __abort_on_fail = false;
int __pass = 0;
int __fail = 0;
if (1 < argc) __abort_on_fail = true;
std::cout << "TAP version 13" << std::endl;
std::cout.flush();
std::ifstream __in("testcases.txt");
for(;;)
{
int __testnum = __pass + __fail + 1;
int __expected;
int N;
int low;
int high;
vector <int> pitch;
__in >> __expected >> N >> low >> high >> pitch;
if (!__in.good()) break;
std::cout << "===============Test " << __testnum<< "==================\n";
std::cout << "input for test: " << N << ", " << low << ", " << high << ", " << pitch << std::endl;
std::cout.flush();
__timer_start();
Singing __object;
int __actual = __object.solve(N, low, high, pitch);
double __t = __timer_stop();
std::cout << "test completed in " << __t << "ms" << std::endl;
std::cout.flush();
if (__equals(__actual, __expected))
{
std::cout << "\033[1;32mOK\033[0m";
++__pass;
}
else
{
std::cout << "\033[1;31mWA\033[0m";
++__fail;
}
std::cout << " - " << __actual << " must equal " << __expected << std::endl;
std::cout.flush();
if (__abort_on_fail && 0 < __fail) std::abort();
}
std::cout << "===============Total==================\n";
std::cout << "1.." << (__pass + __fail) << std::endl
<< "Passed: \033[1;32m" << __pass << "\033[0m" << std::endl
<< "Failed: \033[1;31m" << __fail << "\033[0m" << std::endl;
if (__fail == 0)
{
std::cout << std::endl
<< "\033[1;32mNice!\033[0m DON'T FORGET TO COMPILE REMOTELY BEFORE SUBMITTING!\n" << std::endl;
} else {
std::cout << "\n"
<< "\033[1;31mWrong answer\033[0m"<<"\n" << std::endl;
}
return __fail;
}
// vim:ft=cpp:noet:ts=8
| [
"rodion.permin@gmail.com"
] | rodion.permin@gmail.com |
f92660c97b170e01500e95eb57bcad2b9bf7171d | 7ed28dffc9e1287cf504fdef5967a85fe9f564e7 | /geometry/library/counter_clockwise.cpp | 019a0955edd043012c8e2a40494168a4f87c2221 | [
"MIT"
] | permissive | Takumi1122/data-structure-algorithm | 0d9cbb921315c94d559710181cdf8e3a1b8e62e5 | 6b9f26e4dbba981f034518a972ecfc698b86d837 | refs/heads/master | 2021-06-29T20:30:37.464338 | 2021-04-17T02:01:44 | 2021-04-17T02:01:44 | 227,387,243 | 0 | 0 | null | 2020-02-23T12:27:52 | 2019-12-11T14:37:49 | C++ | UTF-8 | C++ | false | false | 5,326 | cpp | #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
// 反時計回り Counter-Clockwise
/*
参考リンク
AIZU ONLINE JUDGE
https://onlinejudge.u-aizu.ac.jp/problems/CGL_1_C
*/
////////////////////////////
// 基本要素 (点, 線分)
////////////////////////////
using DD = double;
const DD INF = 1LL << 60; // to be set appropriately
const DD EPS = 1e-10; // to be set appropriately
const DD PI = acosl(-1.0);
DD torad(int deg) { return (DD)(deg)*PI / 180; }
DD todeg(DD ang) { return ang * 180 / PI; }
/* Point */
struct Point {
DD x, y;
Point(DD x = 0.0, DD y = 0.0) : x(x), y(y) {}
friend ostream &operator<<(ostream &s, const Point &p) {
return s << '(' << p.x << ", " << p.y << ')';
}
};
inline Point operator+(const Point &p, const Point &q) {
return Point(p.x + q.x, p.y + q.y);
}
inline Point operator-(const Point &p, const Point &q) {
return Point(p.x - q.x, p.y - q.y);
}
inline Point operator*(const Point &p, DD a) { return Point(p.x * a, p.y * a); }
inline Point operator*(DD a, const Point &p) { return Point(a * p.x, a * p.y); }
inline Point operator*(const Point &p, const Point &q) {
return Point(p.x * q.x - p.y * q.y, p.x * q.y + p.y * q.x);
}
inline Point operator/(const Point &p, DD a) { return Point(p.x / a, p.y / a); }
inline Point conj(const Point &p) { return Point(p.x, -p.y); }
inline Point rot(const Point &p, DD ang) {
return Point(cos(ang) * p.x - sin(ang) * p.y,
sin(ang) * p.x + cos(ang) * p.y);
}
inline Point rot90(const Point &p) { return Point(-p.y, p.x); }
inline DD cross(const Point &p, const Point &q) {
return p.x * q.y - p.y * q.x;
}
inline DD dot(const Point &p, const Point &q) { return p.x * q.x + p.y * q.y; }
inline DD norm(const Point &p) { return dot(p, p); }
inline DD abs(const Point &p) { return sqrt(dot(p, p)); }
inline DD amp(const Point &p) {
DD res = atan2(p.y, p.x);
if (res < 0) res += PI * 2;
return res;
}
inline bool eq(const Point &p, const Point &q) { return abs(p - q) < EPS; }
inline bool operator<(const Point &p, const Point &q) {
return (abs(p.x - q.x) > EPS ? p.x < q.x : p.y < q.y);
}
inline bool operator>(const Point &p, const Point &q) {
return (abs(p.x - q.x) > EPS ? p.x > q.x : p.y > q.y);
}
inline Point operator/(const Point &p, const Point &q) {
return p * conj(q) / norm(q);
}
/* Line */
struct Line : vector<Point> {
Line(Point a = Point(0.0, 0.0), Point b = Point(0.0, 0.0)) {
this->push_back(a);
this->push_back(b);
}
friend ostream &operator<<(ostream &s, const Line &l) {
return s << '{' << l[0] << ", " << l[1] << '}';
}
};
////////////////////////////
// 円や直線の交差判定, 距離
////////////////////////////
/*
ccw を用いている
P: point
L: Line
S: Segment
distancePL は、「点」と「直線」の距離
distancePS は、「点」と「線分」の距離
*/
int ccw_for_dis(const Point &a, const Point &b, const Point &c) {
if (cross(b - a, c - a) > EPS) return 1;
if (cross(b - a, c - a) < -EPS) return -1;
if (dot(b - a, c - a) < -EPS) return 2;
if (norm(b - a) < norm(c - a) - EPS) return -2;
return 0;
}
Point proj(const Point &p, const Line &l) {
DD t = dot(p - l[0], l[1] - l[0]) / norm(l[1] - l[0]);
return l[0] + (l[1] - l[0]) * t;
}
Point refl(const Point &p, const Line &l) { return p + (proj(p, l) - p) * 2; }
bool isinterPL(const Point &p, const Line &l) {
return (abs(p - proj(p, l)) < EPS);
}
bool isinterPS(const Point &p, const Line &s) {
return (ccw_for_dis(s[0], s[1], p) == 0);
}
bool isinterLL(const Line &l, const Line &m) {
return (abs(cross(l[1] - l[0], m[1] - m[0])) > EPS ||
abs(cross(l[1] - l[0], m[0] - l[0])) < EPS);
}
bool isinterSS(const Line &s, const Line &t) {
if (eq(s[0], s[1])) return isinterPS(s[0], t);
if (eq(t[0], t[1])) return isinterPS(t[0], s);
return (ccw_for_dis(s[0], s[1], t[0]) * ccw_for_dis(s[0], s[1], t[1]) <= 0 &&
ccw_for_dis(t[0], t[1], s[0]) * ccw_for_dis(t[0], t[1], s[1]) <= 0);
}
DD distancePL(const Point &p, const Line &l) { return abs(p - proj(p, l)); }
DD distancePS(const Point &p, const Line &s) {
Point h = proj(p, s);
if (isinterPS(h, s)) return abs(p - h);
return min(abs(p - s[0]), abs(p - s[1]));
}
DD distanceLL(const Line &l, const Line &m) {
if (isinterLL(l, m))
return 0;
else
return distancePL(m[0], l);
}
DD distanceSS(const Line &s, const Line &t) {
if (isinterSS(s, t))
return 0;
else
return min(min(distancePS(s[0], t), distancePS(s[1], t)),
min(distancePS(t[0], s), distancePS(t[1], s)));
}
int main() {
DD x0, y0, x1, y1;
cin >> x0 >> y0 >> x1 >> y1;
int q;
cin >> q;
rep(i, q) {
DD x2, y2;
cin >> x2 >> y2;
int type = ccw_for_dis(Point(x0, y0), Point(x1, y1), Point(x2, y2));
switch (type) {
case 1: {
cout << "COUNTER_CLOCKWISE" << endl;
continue;
}
case -1: {
cout << "CLOCKWISE" << endl;
continue;
}
case 2: {
cout << "ONLINE_BACK" << endl;
continue;
}
case -2: {
cout << "ONLINE_FRONT" << endl;
continue;
}
case 0: {
cout << "ON_SEGMENT" << endl;
continue;
}
}
}
} | [
"takumi221b4869@gmail.com"
] | takumi221b4869@gmail.com |
a6f3a61b6cdf2ce1ed163e47ce6c3dfe3641ccb5 | 625397e7810efcfd4bb325e01ffea96dd2026cbd | /Source/UnrealPong/PaddlePawn.cpp | 14ecc7053231bea8bd2a0641c636c5fc17146d80 | [] | no_license | piandpower/UnrealPong | 16f058951ae3dca747fb679fe6531f4f529e9c00 | 52997bbb94e1038f1c555e489a5f8ff47b48a80b | refs/heads/master | 2021-01-18T14:49:37.574355 | 2016-07-27T06:52:01 | 2016-07-27T06:52:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,697 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "unrealpong.h"
#include "PaddlePawn.h"
// Sets default values
APaddlePawn::APaddlePawn()
{
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
PaddleMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMeshComponent"));
PaddleCollider = CreateDefaultSubobject<UBoxComponent>(TEXT("BoxCollision"));
PaddleMeshComponent->AttachToComponent(RootComponent, FAttachmentTransformRules::SnapToTargetIncludingScale);
PaddleCollider->AttachToComponent(PaddleMeshComponent, FAttachmentTransformRules::SnapToTargetIncludingScale);
}
// Called when the game starts or when spawned
void APaddlePawn::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void APaddlePawn::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
}
// Called to bind functionality to input
void APaddlePawn::SetupPlayerInputComponent(class UInputComponent* InputComponent)
{
Super::SetupPlayerInputComponent(InputComponent);
InputComponent->BindAxis("P1Up", this, &APaddlePawn::MoveUp);
InputComponent->BindAxis("P1Down", this, &APaddlePawn::MoveDown);
}
void APaddlePawn::MoveUp(float value)
{
FVector ActorLocation = GetActorLocation();
ActorLocation.X += value * MoveSpeed;
if (ActorLocation.X > MaxX) {
ActorLocation.X = MaxX;
}
SetActorLocation(ActorLocation);
}
void APaddlePawn::MoveDown(float value)
{
FVector ActorLocation = GetActorLocation();
ActorLocation.X -= value * MoveSpeed;
if (ActorLocation.X < MinX) {
ActorLocation.X = MinX;
}
SetActorLocation(ActorLocation);
}
| [
"morten@sneftrup.net"
] | morten@sneftrup.net |
27eb47009e83b2047d9f37140532ef80fd6d579a | b8499de1a793500b47f36e85828f997e3954e570 | /v2_3/build/Android/Debug/app/src/main/include/Uno.Float4x4.h | 1c10f7283b8e22a7f1df0c61104e70da98fac546 | [] | no_license | shrivaibhav/boysinbits | 37ccb707340a14f31bd57ea92b7b7ddc4859e989 | 04bb707691587b253abaac064317715adb9a9fe5 | refs/heads/master | 2020-03-24T05:22:21.998732 | 2018-07-26T20:06:00 | 2018-07-26T20:06:00 | 142,485,250 | 0 | 0 | null | 2018-07-26T20:03:22 | 2018-07-26T19:30:12 | C++ | UTF-8 | C++ | false | false | 2,561 | h | // This file was generated based on C:/Users/Vaibhav/AppData/Local/Fusetools/Packages/UnoCore/1.9.0/Source/Uno/Float4x4.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Object.h>
namespace g{namespace Uno{struct Float4;}}
namespace g{namespace Uno{struct Float4x4;}}
namespace g{
namespace Uno{
// public intrinsic struct Float4x4 :8
// {
uStructType* Float4x4_typeof();
void Float4x4__ctor__fn(Float4x4* __this, float* m11, float* m12, float* m13, float* m14, float* m21, float* m22, float* m23, float* m24, float* m31, float* m32, float* m33, float* m34, float* m41, float* m42, float* m43, float* m44);
void Float4x4__Equals_fn(Float4x4* __this, uType* __type, uObject* o, bool* __retval);
void Float4x4__GetHashCode_fn(Float4x4* __this, uType* __type, int32_t* __retval);
void Float4x4__get_Identity_fn(Float4x4* __retval);
void Float4x4__get_Item_fn(Float4x4* __this, int32_t* index, ::g::Uno::Float4* __retval);
void Float4x4__set_Item_fn(Float4x4* __this, int32_t* index, ::g::Uno::Float4* value);
void Float4x4__New1_fn(float* m11, float* m12, float* m13, float* m14, float* m21, float* m22, float* m23, float* m24, float* m31, float* m32, float* m33, float* m34, float* m41, float* m42, float* m43, float* m44, Float4x4* __retval);
void Float4x4__ToString_fn(Float4x4* __this, uType* __type, uString** __retval);
struct Float4x4
{
float M11;
float M12;
float M13;
float M14;
float M21;
float M22;
float M23;
float M24;
float M31;
float M32;
float M33;
float M34;
float M41;
float M42;
float M43;
float M44;
void ctor_(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44);
bool Equals(uType* __type, uObject* o) { bool __retval; return Float4x4__Equals_fn(this, __type, o, &__retval), __retval; }
int32_t GetHashCode(uType* __type) { int32_t __retval; return Float4x4__GetHashCode_fn(this, __type, &__retval), __retval; }
::g::Uno::Float4 Item(int32_t index);
void Item(int32_t index, ::g::Uno::Float4 value);
uString* ToString(uType* __type) { uString* __retval; return Float4x4__ToString_fn(this, __type, &__retval), __retval; }
};
Float4x4 Float4x4__New1(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44);
Float4x4 Float4x4__Identity();
// }
}} // ::g::Uno
| [
"shubhamanandoist@gmail.com"
] | shubhamanandoist@gmail.com |
0b821466ed6c3c1f89555ecb00390f3c9f1db8f7 | 58f46a28fc1b58f9cd4904c591b415c29ab2842f | /chromium-courgette-redacted-29.0.1547.57/content/browser/renderer_host/render_widget_host_view_guest.h | 448ea3ef919aa281628e25244ea08e8856646c50 | [
"BSD-3-Clause"
] | permissive | bbmjja8123/chromium-1 | e739ef69d176c636d461e44d54ec66d11ed48f96 | 2a46d8855c48acd51dafc475be7a56420a716477 | refs/heads/master | 2021-01-16T17:50:45.184775 | 2015-03-20T18:38:11 | 2015-03-20T18:42:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,468 | h | // Copyright (c) 2012 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.
#ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_GUEST_H_
#define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_GUEST_H_
#include <vector>
#include "base/memory/scoped_ptr.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/common/content_export.h"
#include "ui/base/events/event.h"
#include "ui/base/gestures/gesture_recognizer.h"
#include "ui/base/gestures/gesture_types.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/vector2d_f.h"
#include "webkit/common/cursors/webcursor.h"
#if defined(TOOLKIT_GTK)
#include "webkit/plugins/npapi/gtk_plugin_container_manager.h"
#endif // defined(TOOLKIT_GTK)
namespace content {
class RenderWidgetHost;
class RenderWidgetHostImpl;
class BrowserPluginGuest;
struct NativeWebKeyboardEvent;
// -----------------------------------------------------------------------------
// See comments in render_widget_host_view.h about this class and its members.
// This version is for the webview plugin which handles a lot of the
// functionality in a diffent place and isn't platform specific.
//
// Some elements that are platform specific will be deal with by delegating
// the relevant calls to the platform view.
// -----------------------------------------------------------------------------
class CONTENT_EXPORT RenderWidgetHostViewGuest
: public RenderWidgetHostViewBase,
public ui::GestureConsumer,
public ui::GestureEventHelper {
public:
RenderWidgetHostViewGuest(RenderWidgetHost* widget,
BrowserPluginGuest* guest,
RenderWidgetHostView* platform_view);
virtual ~RenderWidgetHostViewGuest();
// RenderWidgetHostView implementation.
virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
virtual void InitAsChild(gfx::NativeView parent_view) OVERRIDE;
virtual RenderWidgetHost* GetRenderWidgetHost() const OVERRIDE;
virtual void SetSize(const gfx::Size& size) OVERRIDE;
virtual void SetBounds(const gfx::Rect& rect) OVERRIDE;
virtual gfx::NativeView GetNativeView() const OVERRIDE;
virtual gfx::NativeViewId GetNativeViewId() const OVERRIDE;
virtual gfx::NativeViewAccessible GetNativeViewAccessible() OVERRIDE;
virtual bool HasFocus() const OVERRIDE;
virtual bool IsSurfaceAvailableForCopy() const OVERRIDE;
virtual void Show() OVERRIDE;
virtual void Hide() OVERRIDE;
virtual bool IsShowing() OVERRIDE;
virtual gfx::Rect GetViewBounds() const OVERRIDE;
virtual void SetBackground(const SkBitmap& background) OVERRIDE;
#if defined(OS_WIN) && !defined(USE_AURA)
virtual void SetClickthroughRegion(SkRegion* region) OVERRIDE;
#endif
#if defined(OS_WIN) && defined(USE_AURA)
virtual gfx::NativeViewAccessible AccessibleObjectFromChildId(long child_id)
OVERRIDE;
#endif
// RenderWidgetHostViewPort implementation.
virtual void InitAsPopup(RenderWidgetHostView* parent_host_view,
const gfx::Rect& pos) OVERRIDE;
virtual void InitAsFullscreen(
RenderWidgetHostView* reference_host_view) OVERRIDE;
virtual void WasShown() OVERRIDE;
virtual void WasHidden() OVERRIDE;
virtual void MovePluginWindows(
const gfx::Vector2d& scroll_offset,
const std::vector<webkit::npapi::WebPluginGeometry>& moves) OVERRIDE;
virtual void Focus() OVERRIDE;
virtual void Blur() OVERRIDE;
virtual void UpdateCursor(const WebCursor& cursor) OVERRIDE;
virtual void SetIsLoading(bool is_loading) OVERRIDE;
virtual void TextInputTypeChanged(ui::TextInputType type,
bool can_compose_inline) OVERRIDE;
virtual void ImeCancelComposition() OVERRIDE;
virtual void ImeCompositionRangeChanged(
const ui::Range& range,
const std::vector<gfx::Rect>& character_bounds) OVERRIDE;
virtual void DidUpdateBackingStore(
const gfx::Rect& scroll_rect,
const gfx::Vector2d& scroll_delta,
const std::vector<gfx::Rect>& copy_rects,
const ui::LatencyInfo& latency_info) OVERRIDE;
virtual void RenderViewGone(base::TerminationStatus status,
int error_code) OVERRIDE;
virtual void Destroy() OVERRIDE;
virtual void WillDestroyRenderWidget(RenderWidgetHost* rwh) {}
virtual void SetTooltipText(const string16& tooltip_text) OVERRIDE;
virtual void SelectionBoundsChanged(
const ViewHostMsg_SelectionBounds_Params& params) OVERRIDE;
virtual void ScrollOffsetChanged() OVERRIDE;
virtual BackingStore* AllocBackingStore(const gfx::Size& size) OVERRIDE;
virtual void CopyFromCompositingSurface(
const gfx::Rect& src_subrect,
const gfx::Size& dst_size,
const base::Callback<void(bool, const SkBitmap&)>& callback) OVERRIDE;
virtual void CopyFromCompositingSurfaceToVideoFrame(
const gfx::Rect& src_subrect,
const scoped_refptr<media::VideoFrame>& target,
const base::Callback<void(bool)>& callback) OVERRIDE;
virtual bool CanCopyToVideoFrame() const OVERRIDE;
virtual void OnAcceleratedCompositingStateChange() OVERRIDE;
virtual void AcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params,
int gpu_host_id) OVERRIDE;
virtual void AcceleratedSurfacePostSubBuffer(
const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params,
int gpu_host_id) OVERRIDE;
virtual void OnSwapCompositorFrame(
scoped_ptr<cc::CompositorFrame> frame) OVERRIDE;
virtual void AcceleratedSurfaceSuspend() OVERRIDE;
virtual void AcceleratedSurfaceRelease() OVERRIDE;
virtual bool HasAcceleratedSurface(const gfx::Size& desired_size) OVERRIDE;
virtual void SetHasHorizontalScrollbar(
bool has_horizontal_scrollbar) OVERRIDE;
virtual void SetScrollOffsetPinning(
bool is_pinned_to_left, bool is_pinned_to_right) OVERRIDE;
virtual gfx::Rect GetBoundsInRootWindow() OVERRIDE;
virtual gfx::GLSurfaceHandle GetCompositingSurface() OVERRIDE;
#if defined(OS_WIN) || defined(USE_AURA)
virtual void ProcessAckedTouchEvent(
const TouchEventWithLatencyInfo& touch,
InputEventAckState ack_result) OVERRIDE;
#endif // defined(OS_WIN) || defined(USE_AURA)
virtual bool LockMouse() OVERRIDE;
virtual void UnlockMouse() OVERRIDE;
virtual void GetScreenInfo(WebKit::WebScreenInfo* results) OVERRIDE;
virtual void OnAccessibilityNotifications(
const std::vector<AccessibilityHostMsg_NotificationParams>&
params) OVERRIDE;
#if defined(OS_MACOSX)
// RenderWidgetHostView implementation.
virtual void SetActive(bool active) OVERRIDE;
virtual void SetTakesFocusOnlyOnMouseDown(bool flag) OVERRIDE;
virtual void SetWindowVisibility(bool visible) OVERRIDE;
virtual void WindowFrameChanged() OVERRIDE;
virtual void ShowDefinitionForSelection() OVERRIDE;
virtual bool SupportsSpeech() const OVERRIDE;
virtual void SpeakSelection() OVERRIDE;
virtual bool IsSpeaking() const OVERRIDE;
virtual void StopSpeaking() OVERRIDE;
// RenderWidgetHostViewPort implementation.
virtual void AboutToWaitForBackingStoreMsg() OVERRIDE;
virtual bool PostProcessEventForPluginIme(
const NativeWebKeyboardEvent& event) OVERRIDE;
#endif // defined(OS_MACOSX)
#if defined(OS_ANDROID)
// RenderWidgetHostViewPort implementation.
virtual void ShowDisambiguationPopup(const gfx::Rect& target_rect,
const SkBitmap& zoomed_bitmap) OVERRIDE;
virtual void HasTouchEventHandlers(bool need_touch_events) OVERRIDE;
#endif // defined(OS_ANDROID)
#if defined(TOOLKIT_GTK)
virtual GdkEventButton* GetLastMouseDown() OVERRIDE;
virtual gfx::NativeView BuildInputMethodsGtkMenu() OVERRIDE;
#endif // defined(TOOLKIT_GTK)
#if defined(OS_WIN) && !defined(USE_AURA)
virtual void WillWmDestroy() OVERRIDE;
#endif // defined(OS_WIN) && !defined(USE_AURA)
#if defined(OS_WIN) && defined(USE_AURA)
virtual void SetParentNativeViewAccessible(
gfx::NativeViewAccessible accessible_parent) OVERRIDE;
#endif
// Overridden from ui::GestureEventHelper.
virtual bool DispatchLongPressGestureEvent(ui::GestureEvent* event) OVERRIDE;
virtual bool DispatchCancelTouchEvent(ui::TouchEvent* event) OVERRIDE;
protected:
friend class RenderWidgetHostView;
private:
// Destroys this view without calling |Destroy| on |platform_view_|.
void DestroyGuestView();
// Builds and forwards a WebKitGestureEvent to the renderer.
bool ForwardGestureEventToRenderer(ui::GestureEvent* gesture);
// Process all of the given gestures (passes them on to renderer)
void ProcessGestures(ui::GestureRecognizer::Gestures* gestures);
// The model object.
RenderWidgetHostImpl* host_;
BrowserPluginGuest *guest_;
bool is_hidden_;
gfx::Size size_;
// The platform view for this RenderWidgetHostView.
// RenderWidgetHostViewGuest mostly only cares about stuff related to
// compositing, the rest are directly forwared to this |platform_view_|.
RenderWidgetHostViewPort* platform_view_;
#if defined(OS_WIN) || defined(USE_AURA)
scoped_ptr<ui::GestureRecognizer> gesture_recognizer_;
#endif // defined(OS_WIN) || defined(USE_AURA)
DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewGuest);
};
} // namespace content
#endif // CHROME_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_VIEW_GUEST_H_
| [
"Khilan.Gudka@cl.cam.ac.uk"
] | Khilan.Gudka@cl.cam.ac.uk |
aca1f7b45493141e714151c5d93e0fff0e04b259 | 684c9beb8bd972daeabe5278583195b9e652c0c5 | /src/starboard/common/thread_collision_warner.cc | 5a9e853c3b10527845be40eb3669d67f56a0d9fa | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | elgamar/cobalt-clone | a7d4e62630218f0d593fa74208456dd376059304 | 8a7c8792318a721e24f358c0403229570da8402b | refs/heads/master | 2022-11-27T11:30:31.314891 | 2018-10-26T15:54:41 | 2018-10-26T15:55:22 | 159,339,577 | 2 | 4 | null | 2022-11-17T01:03:37 | 2018-11-27T13:27:44 | C++ | UTF-8 | C++ | false | false | 2,011 | cc | // Copyright (c) 2010 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 "starboard/common/thread_collision_warner.h"
#include "starboard/atomic.h"
#include "starboard/log.h"
#include "starboard/thread.h"
#include "starboard/types.h"
namespace starboard {
void DCheckAsserter::warn() {
SB_NOTREACHED() << "Thread Collision";
}
static SbAtomic32 CurrentThread() {
const SbThreadId current_thread_id = SbThreadGetId();
// We need to get the thread id into an atomic data type. This might be a
// truncating conversion, but any loss-of-information just increases the
// chance of a false negative, not a false positive.
const SbAtomic32 atomic_thread_id =
static_cast<SbAtomic32>(current_thread_id);
return atomic_thread_id;
}
void ThreadCollisionWarner::EnterSelf() {
// If the active thread is 0 then I'll write the current thread ID
// if two or more threads arrive here only one will succeed to
// write on valid_thread_id_ the current thread ID.
SbAtomic32 current_thread_id = CurrentThread();
int previous_value =
SbAtomicNoBarrier_CompareAndSwap(&valid_thread_id_, 0, current_thread_id);
if (previous_value != 0 && previous_value != current_thread_id) {
// gotcha! a thread is trying to use the same class and that is
// not current thread.
asserter_->warn();
}
SbAtomicNoBarrier_Increment(&counter_, 1);
}
void ThreadCollisionWarner::Enter() {
SbAtomic32 current_thread_id = CurrentThread();
if (SbAtomicNoBarrier_CompareAndSwap(&valid_thread_id_, 0,
current_thread_id) != 0) {
// gotcha! another thread is trying to use the same class.
asserter_->warn();
}
SbAtomicNoBarrier_Increment(&counter_, 1);
}
void ThreadCollisionWarner::Leave() {
if (SbAtomicBarrier_Increment(&counter_, -1) == 0) {
SbAtomicNoBarrier_Store(&valid_thread_id_, 0);
}
}
} // namespace starboard
| [
"aabtop@google.com"
] | aabtop@google.com |
4acdbdb9f1cb2d5be512f126510f2dd4e96a1a67 | 9bdffba3a8b84aca95c7907aa8e47a085b0ada8e | /src/main/simulator/notification/Notification.cpp | c48814b4a81af7402b30fc81aa85ad4587d13a95 | [] | no_license | alejandromarcu/quenas | 9a8ca96c7d27299f894e33897ca60b107acba4b0 | f2aad975f011f29d81584de2a708057ae86d3ec6 | refs/heads/master | 2021-01-17T06:24:30.125651 | 2016-06-18T21:51:30 | 2016-06-18T21:51:30 | 61,453,712 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,808 | cpp | #include <string>
#include <iostream>
#include <fstream>
#include <map>
#include "Command.h"
#include "Notification.h"
#include "Simulator.h"
#include "TypeFilter.h"
#include "Exceptions.h"
namespace simulator {
namespace notification {
using namespace simulator::command;
using namespace simulator;
using namespace std;
//---------------------------------------------------------------------
//----------------------------< XMLFormatter >-------------------------
//---------------------------------------------------------------------
/**
* @brief Format a query result in XML.
*
* @param qr the query result to be formatted.
* @result qr formatted in XML.
*/
string XMLFormatter::format(QueryResult *qr)
{
return formatMultiValue(qr, 1);
}
/**
* @brief Set the name of the XSLT stylesheet to use.
*
* @param name XSLT stylesheet to use.
*/
void XMLFormatter::setStylesheet(const string &name)
{
stylesheet = name;
}
/**
* @brief Writes the start tag for XML: <simulation>
*
* @return "<simulation>"
*/
string XMLFormatter::start()
{
string s;
if (stylesheet != "") s = "<?xml-stylesheet type=\"text/xsl\" href=\"" + stylesheet + "\"?>\n";
return s + "<simulation>\n";
}
/**
* @brief Writes the end tag for XML: </simulation>
*
* @return "</simulation>"
*/
string XMLFormatter::finish()
{
return "</simulation>\n";
}
/**
* @brief Format a multi value in XML.
* All the values contained in the multi value are formatted and concatenated.
*
* @param value the value to format.
* @param indentationLevel indentation level to make XML look nice.
* @return the multi value formatted in xml.
*/
string XMLFormatter::formatMultiValue(MultiValue *value, int indentationLevel)
{
MultiValue::TProperties prop = value->getProperties();
string output;
string indent0, indent;
for (int i=1; i< indentationLevel; i++)
indent0 += " ";
indent = indent0 + " ";
string id = value->getId() == ""? "" : " id=\"" + value->getId() + "\"";
output += indent0 + "<" + value->getName() + id + ">\n";
for (int i = 0; i < prop.size(); i++)
{
pair<string, TValue*> p = prop[i];
StringValue *sv = dynamic_cast<StringValue *>(p.second);
if (sv != NULL) {
output += indent + "<" + p.first + ">";
output += sv->getValue();
output += "</" + p.first + ">\n";
} else {
MultiValue *mv = dynamic_cast<MultiValue *>(p.second);
if (mv != NULL) {
output += formatMultiValue(mv, indentationLevel+1);
} else {
BinaryValue *bv = dynamic_cast<BinaryValue *>(p.second);
if (bv != NULL) {
output += indent + "<" + p.first + ">\n";
output += formatBinaryValue(*bv, indentationLevel +1) + indent;
output += "</" + p.first + ">\n";
}
}
}
}
output += indent0 + "</" + value->getName() + ">\n";
return output;
}
/**
* @brief Format a binary value in XML, creating a tag for every 16 bytes.
*
* @param bv binary value to format
* @param indentationLevel indentation level to make XML look nice.
* @return the binary value formatted in xml.
*/
string XMLFormatter::formatBinaryValue(const BinaryValue &bv, int indentationLevel)
{
VB data = bv.getValue();
string indent;
for (int i=0; i< indentationLevel; i++)
indent += " ";
string output = "";
for (int i = 0; i < data.size(); i++) {
if ((i % 16) == 0) {
if (i > 0) output += "</bytes>\n";
if (i < (data.size() -1)) {
int to = i + 15;
if ((data.size() - 1) < to) to = data.size() - 1;
output += indent + "<bytes from=\"" + toStr(i) + "\" to=\"" + toStr(to) + "\">";
}
}
output += toHex(data[i]);
if ((i % 16) != 15) output += " ";
}
output += "</bytes>\n";
return output;
}
/**
* @brief Run a command.
*
* @param function function to run.
*/
TCommandResult *XMLFormatter::runCommand(const Function &function)
{
if (function.getName() == "setStylesheet")
{
setStylesheet(function.getStringParam(0));
return this;
}
}
/**
* @brief Get the name of this object.
*
* @return "XMLFormatter"
*/
string XMLFormatter::getName() const
{
return "XMLFormatter";
}
//---------------------------------------------------------------------
//-----------------------------< MultiValue >--------------------------
//---------------------------------------------------------------------
/**
* @brief Create a Multi Value
*
* @param name name of the object
* @param id id of the object
*/
MultiValue::MultiValue(const string &name, const string &id) : name(name), id(id)
{
}
/**
* @brief Destroy the MultiValue object, returning the property values.
*/
MultiValue::~MultiValue()
{
for (int i=0; i < properties.size(); i++)
{
if (properties[i].second != NULL) delete properties[i].second;
}
}
/**
* @brief Return stored properties.
*
* @return stored properties.
*/
const MultiValue::TProperties &MultiValue::getProperties() const
{
return properties;
}
/**
* @brief Insert a new key-value property.
*
* @param key name of the property.
* @param value value of the property.
*/
void MultiValue::insert(const string &key, TValue *value)
{
properties.push_back(make_pair(key, value));
}
/**
* @brief Insert a new key-value property, where value is a string.
*
* @param key name of the property.
* @param value string value of the property.
*/
void MultiValue::insert(const string &key, const string &value)
{
insert(key, new StringValue(value));
}
/**
* @brief Get the name of this MultiValue.
*
* @return the name of this MultiValue.
*/
string MultiValue::getName() const
{
return name;
}
/**
* @brief Get the id of this MultiValue.
*
* @return the id of this MultiValue.
*/
string MultiValue::getId() const
{
return id;
}
//---------------------------------------------------------------------
//-----------------------------< QueryResult >-------------------------
//---------------------------------------------------------------------
/**
* @brief Create an empty query result.
*
* @param name name of the query result.
* @param time time when the query was done; if no specified, current time is used.
*/
QueryResult::QueryResult(const string &name, Time time) : MultiValue(name)
{
this->time = time.getValue() < 0? Simulator::getInstance()->getTime() : time;
}
/**
* @brief Create an empty query result.
*
* @param name name of the query result.
* @param id id of the object
* @param time time when the query was done; if no specified, current time is used.
*/
QueryResult::QueryResult(const string &name, const string &id, Time time) : MultiValue(name, id)
{
this->time = time.getValue() < 0? Simulator::getInstance()->getTime() : time;
}
/**
* @brief Create a query result containing one property.
*
* @param name name of the query result.
* @param propName name of the property in the query result.
* @param propValue value of the property in the query result.
* @param time time when the query was done; if no specified, current time is used.
*/
QueryResult::QueryResult(const string &name, const string &propName, const string &propValue, Time time) : MultiValue(name)
{
this->time = time.getValue() < 0 ? Simulator::getInstance()->getTime() : time;
insert(propName, propValue);
}
/**
* @brief Return the name of the query result.
*
* @return the name of the query result.
*/
Time QueryResult::getTime() const
{
return time;
}
//---------------------------------------------------------------------
//-----------------------------< Notificator >-------------------------
//---------------------------------------------------------------------
/**
* @brief Create a notificator that uses XMLFormatter for formatting and
* that writes to sdt out.
*/
Notificator::Notificator()
{
formatter = new XMLFormatter();
filename = "";
file = NULL;
}
/**
* @brief Destroy the Notificator, closing the file if it wasn't closed.
*/
Notificator::~Notificator()
{
if (file != NULL) close();
}
/**
* @brief Format a query result and write it to file.
*
* @param qr the query result to format.
*/
void Notificator::write(QueryResult *qr)
{
if (file == NULL) open();
*file << formatter->format(qr);
}
/**
* @brief Open the file and writes formatters's start string.
* If the filename is emtpy, standard output is used.
*/
void Notificator::open()
{
if (filename == "") {
file = &std::cout;
} else {
file = new ofstream(filename.c_str());
}
*file << formatter->start();
}
/**
* @brief Write formatter's finish string and closes the file.
*/
void Notificator::close()
{
if (file == NULL) return;
*file << formatter->finish();
delete file;
file = NULL;
}
/**
* @brief Set the formatter to be used.
*
* @param formatter formatter to be used.
*/
void Notificator::setFormatter(TFormatter *formatter)
{
this->formatter = formatter;
}
/**
* @brief Return the used formatter.
*
* @return the used formatter.
*/
TFormatter *Notificator::getFormatter() const
{
return formatter;
}
/**
* @brief Set the name of the output file, closing the previous file.
*
* @param fname name of the output file or emtpy ("") to use std output.
*/
void Notificator::setFilename(const string &fname)
{
close();
filename = fname;
}
}
}
| [
"Alejandro Marcu"
] | Alejandro Marcu |
5745f6966ae47ecc84c6525171bd6c6af0b120f0 | e20087104206b48e86cdf135145cd8d2f3c665e3 | /__unit_tests/gv_base_unit_test/unit_test_gv_id.hpp | 4f1da0a1c012b6666d8eeef8a2b3cb1a83cc70ea | [
"MIT"
] | permissive | dragonsn/gv_game_engine | 5929ecdadf0403ac68b74130ecf9f72b62ddd624 | 92595a63148d15a989859c93223a55168a1861b5 | refs/heads/master | 2022-11-19T01:48:46.783547 | 2022-11-08T10:24:45 | 2022-11-08T10:24:45 | 159,043,827 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 712 | hpp | namespace unit_test_gv_id
{
void main(gvt_array< gv_string >& args)
{
{
gv_id id0, id1, id2;
id0 = "abc";
GV_TEST_PRINT_VAR(id0, test_log());
GV_TEST_PRINT_VAR(id0.get_refcount(), test_log());
{
gv_id id3(id0);
GV_TEST_PRINT_VAR(id3, test_log());
GV_TEST_PRINT_VAR(id3.get_refcount(), test_log());
}
id1 = "abc";
GV_TEST_PRINT_VAR(id1, test_log());
GV_TEST_PRINT_VAR(id1.get_refcount(), test_log());
id2 = "cba";
GV_TEST_PRINT_VAR(id2, test_log());
GV_TEST_PRINT_VAR(id2.get_refcount(), test_log());
GV_ASSERT(id1 == id0);
GV_ASSERT(!(id1 == id2));
}
{
gv_string_tmp s("DFDF");
;
gv_string_tmp s2;
s >> s2;
gv_id id;
s >> id;
}
gv_id::static_purge();
}
}
| [
"shennan.dragon@gmail.com"
] | shennan.dragon@gmail.com |
1a43e38493e880c6ac8f53e4ff22364a2279d785 | ff9fcdf33334efa28142b3a6b8cbb8602dd72c8d | /src/qt/openuridialog.cpp | ac4d3d181a132812cfd654174378323c3a79b0e6 | [
"MIT"
] | permissive | drivercoin/drivercoin | 8bd188d4d9166636bf6a36c413ba2bba1d49489d | 21b25e1028f6eed121d5d97b3dc113ed4f84f7ed | refs/heads/master | 2021-01-10T12:22:08.125585 | 2015-10-20T16:12:32 | 2015-10-20T16:12:32 | 44,398,313 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,244 | cpp | // Copyright (c) 2011-2013 The Drivercoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "openuridialog.h"
#include "ui_openuridialog.h"
#include "guiutil.h"
#include "walletmodel.h"
#include <QUrl>
OpenURIDialog::OpenURIDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OpenURIDialog)
{
ui->setupUi(this);
#if QT_VERSION >= 0x040700
ui->uriEdit->setPlaceholderText("drivercoin:");
#endif
}
OpenURIDialog::~OpenURIDialog()
{
delete ui;
}
QString OpenURIDialog::getURI()
{
return ui->uriEdit->text();
}
void OpenURIDialog::accept()
{
SendCoinsRecipient rcp;
if(GUIUtil::parseDrivercoinURI(getURI(), &rcp))
{
/* Only accept value URIs */
QDialog::accept();
} else {
ui->uriEdit->setValid(false);
}
}
void OpenURIDialog::on_selectFileButton_clicked()
{
QString filename = GUIUtil::getOpenFileName(this, tr("Select payment request file to open"), "", "", NULL);
if(filename.isEmpty())
return;
QUrl fileUri = QUrl::fromLocalFile(filename);
ui->uriEdit->setText("drivercoin:?r=" + QUrl::toPercentEncoding(fileUri.toString()));
}
| [
"betazp17@hotmail.com"
] | betazp17@hotmail.com |
f84e066166484cba848374359ba1273235b2571b | ad0eedd1c69d71963b9a306be4f4c6d8f7650f93 | /lib/packet/unsuback.cc | b3153b72de8f57a9357e504905cec2084ce23a84 | [
"MIT"
] | permissive | srishina/mqtt.cc | d216c06f2ab4058b7f04da364f93835928b5643e | c6ccd33a468a8c66f8c656f1a038a718081c95a0 | refs/heads/main | 2023-03-10T15:17:10.478118 | 2021-03-03T19:20:23 | 2021-03-03T19:20:23 | 337,473,109 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,396 | cc | #include "unsuback.h"
#include "codec.h"
#include "packet.h"
#include "properties.h"
namespace packet {
UnsubAckEncoder::UnsubAckEncoder(UnsubAckPacket sp) : unsubackPkt(sp) {}
std::vector<uint8_t> UnsubAckEncoder::encode() const {
uint32_t propertySize = this->propertySize();
// calculate the remaining length
// 2 = packet ID
uint32_t remainingLength =
2 + propertySize + EncodedVarUint32::size(propertySize) +
uint32_t(this->unsubackPkt.second.reasonCodes.size());
Encoder enc(remainingLength + 1 + EncodedVarUint32::size(remainingLength));
enc.write(static_cast<uint8_t>(
static_cast<uint32_t>(ControlPacket::Type::UNSUBACK) << 4));
enc.writeVarUint32(remainingLength);
enc.write(this->unsubackPkt.first);
this->encodeProperties(enc, propertySize);
for (const auto rc : this->unsubackPkt.second.reasonCodes) {
enc.write(static_cast<uint8_t>(rc));
}
return enc.getBuffer();
}
uint32_t UnsubAckEncoder::propertySize() const {
if (!this->unsubackPkt.second.properties) {
return 0;
}
const mqtt::UnsubAck::Properties& props =
*this->unsubackPkt.second.properties;
uint32_t propertySize = 0;
propertySize += Property::size(props.reasonString);
return propertySize;
}
void UnsubAckEncoder::encodeProperties(Encoder& enc,
uint32_t propertySize) const {
enc.writeVarUint32(propertySize);
if (this->unsubackPkt.second.properties) {
const mqtt::UnsubAck::Properties& props =
*this->unsubackPkt.second.properties;
Property::encode(enc, Property::ID::ReasonStringID, props.reasonString);
}
}
UnsubAckPacket UnsubAckDecoder::decode(std::vector<uint8_t> buffer) {
uint32_t remainingLen = uint32_t(buffer.size());
Decoder dec(buffer);
return UnsubAckDecoder::decode(dec, remainingLen);
}
UnsubAckPacket UnsubAckDecoder::decode(Decoder& dec, uint32_t remainingLen) {
uint16_t packetID = dec.read<uint16_t>();
mqtt::UnsubAck sa;
auto result = UnsubAckDecoder::decodeProperties(dec);
sa.properties = result.first;
remainingLen -= (2 + result.second);
const std::vector<uint8_t> reasonCodes =
dec.readBinaryDataNoLen(remainingLen);
sa.reasonCodes.resize(reasonCodes.size());
for (size_t i = 0; i < reasonCodes.size(); ++i) {
sa.reasonCodes[i] =
static_cast<mqtt::UnsubAck::ReasonCode>(reasonCodes[i]);
}
return {packetID, sa};
}
std::pair<std::shared_ptr<mqtt::UnsubAck::Properties>, uint32_t>
UnsubAckDecoder::decodeProperties(Decoder& dec) {
uint32_t propertySize = dec.read<uint32_t, true>();
uint32_t consumed = EncodedVarUint32::size(propertySize) + propertySize;
std::shared_ptr<mqtt::UnsubAck::Properties> props;
if (propertySize > 0) {
props = std::make_shared<mqtt::UnsubAck::Properties>();
}
while (propertySize > 0) {
uint32_t val = dec.read<uint32_t, true>();
propertySize -= EncodedVarUint32::size(val);
Property::ID id = static_cast<Property::ID>(val);
switch (id) {
case Property::ID::ReasonStringID:
propertySize -= Property::decode(dec, id, props->reasonString);
break;
default:
throwInvalidPropertyID(id, "UNSUBACK");
}
}
return {props, consumed};
}
} // namespace packet
| [
"52798705+srishina@users.noreply.github.com"
] | 52798705+srishina@users.noreply.github.com |
e9c9e52660a3104ba41bbf47773174aee4178405 | 13135d1f82bd8a3ca34b8b2a99dd7f335493e3a9 | /src/bitcoinrpc.cpp | 78f39a32bce067327eb12f18b0d65c0ab68f5484 | [
"MIT"
] | permissive | tujiu/testcoin | 46dc215138e71a96e8013336226988978d16cc98 | cf6345688d414cd7bc5d8bb890aabcdb44efc9b9 | refs/heads/master | 2016-09-16T04:46:15.862856 | 2014-03-17T03:10:07 | 2014-03-17T03:10:07 | 17,355,184 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 116,082 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 The Litecoin Developers
// Copyright (c) 2013 adam m.
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "wallet.h"
#include "db.h"
#include "walletdb.h"
#include "net.h"
#include "init.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#undef printf
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
#define printf OutputDebugStringF
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
void ThreadRPCServer2(void* parg);
static std::string strRPCUserColonPass;
static int64 nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
extern Value getconnectioncount(const Array& params, bool fHelp); // in rpcnet.cpp
extern Value getpeerinfo(const Array& params, bool fHelp);
extern Value dumpprivkey(const Array& params, bool fHelp); // in rpcdump.cpp
extern Value importprivkey(const Array& params, bool fHelp);
extern Value getrawtransaction(const Array& params, bool fHelp); // in rcprawtransaction.cpp
extern Value listunspent(const Array& params, bool fHelp);
extern Value createrawtransaction(const Array& params, bool fHelp);
extern Value decoderawtransaction(const Array& params, bool fHelp);
extern Value signrawtransaction(const Array& params, bool fHelp);
extern Value sendrawtransaction(const Array& params, bool fHelp);
const Object emptyobj;
void ThreadRPCServer3(void* parg);
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (v.type() != t)
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(-3, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (v.type() == null_type)
throw JSONRPCError(-3, strprintf("Missing %s", t.first.c_str()));
if (v.type() != t.second)
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(-3, err);
}
}
}
double GetDifficulty(const CBlockIndex* blockindex = NULL)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL)
{
if (pindexBest == NULL)
return 1.0;
else
blockindex = pindexBest;
}
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > 84000000.0)
throw JSONRPCError(-3, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(-3, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
std::string
HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
std::string
HelpRequiringPassphrase()
{
return pwalletMain->IsCrypted()
? "\nrequires wallet passphrase to be set with walletpassphrase first"
: "";
}
void
EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
int confirms = wtx.GetDepthInMainChain();
entry.push_back(Pair("confirmations", confirms));
if (confirms)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
}
entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const Value& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(-11, "Invalid account name");
return strAccount;
}
Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex)
{
Object result;
result.push_back(Pair("hash", block.GetHash().GetHex()));
CMerkleTx txGen(block.vtx[0]);
txGen.SetMerkleBranch(&block);
result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
Array txs;
BOOST_FOREACH(const CTransaction&tx, block.vtx)
txs.push_back(tx.GetHash().GetHex());
result.push_back(Pair("tx", txs));
result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime()));
result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce));
result.push_back(Pair("bits", HexBits(block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
if (blockindex->pnext)
result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
return result;
}
/// Note: This interface may still be subject to change.
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"stop\n"
"Stop TestCoin server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "TestCoin server has now stopped running!";
}
Value getblockcount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockcount\n"
"Returns the number of blocks in the longest block chain.");
return nBestHeight;
}
Value getdifficulty(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getdifficulty\n"
"Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");
return GetDifficulty();
}
// Litecoin: Return average network hashes per second based on last number of blocks.
Value GetNetworkHashPS(int lookup) {
if (pindexBest == NULL)
return 0;
// If lookup is -1, then use blocks since last difficulty change.
if (lookup <= 0)
lookup = pindexBest->nHeight % 2016 + 1;
// If lookup is larger than chain, then set it to chain length.
if (lookup > pindexBest->nHeight)
lookup = pindexBest->nHeight;
CBlockIndex* pindexPrev = pindexBest;
for (int i = 0; i < lookup; i++)
pindexPrev = pindexPrev->pprev;
double timeDiff = pindexBest->GetBlockTime() - pindexPrev->GetBlockTime();
double timePerBlock = timeDiff / lookup;
return (boost::int64_t)(((double)GetDifficulty() * pow(2.0, 32)) / timePerBlock);
}
Value getnetworkhashps(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnetworkhashps [blocks]\n"
"Returns the estimated network hashes per second based on the last 120 blocks.\n"
"Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.");
return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120);
}
Value getgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getgenerate\n"
"Returns true or false.");
return GetBoolArg("-gen");
}
Value setgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setgenerate <generate> [genproclimit]\n"
"<generate> is true or false to turn generation on or off.\n"
"Generation is limited to [genproclimit] processors, -1 is unlimited.");
bool fGenerate = true;
if (params.size() > 0)
fGenerate = params[0].get_bool();
if (params.size() > 1)
{
int nGenProcLimit = params[1].get_int();
mapArgs["-genproclimit"] = itostr(nGenProcLimit);
if (nGenProcLimit == 0)
fGenerate = false;
}
mapArgs["-gen"] = (fGenerate ? "1" : "0");
GenerateBitcoins(fGenerate, pwalletMain);
return Value::null;
}
Value gethashespersec(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"gethashespersec\n"
"Returns a recent hashes per second performance measurement while generating.");
if (GetTimeMillis() - nHPSTimerStart > 8000)
return (boost::int64_t)0;
return (boost::int64_t)dHashesPerSec;
}
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
CService addrProxy;
GetProxy(NET_IPV4, addrProxy);
Object obj;
obj.push_back(Pair("version", (int)CLIENT_VERSION));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (addrProxy.IsValid() ? addrProxy.ToStringIPPort() : string())));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("testnet", fTestNet));
obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", pwalletMain->GetKeyPoolSize()));
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue)));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime / 1000));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
Object obj;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("generate", GetBoolArg("-gen")));
obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("testnet", fTestNet));
return obj;
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress [account]\n"
"Returns a new TestCoin address for receiving payments. "
"If [account] is specified (recommended), it is added to the address book "
"so payments received with the address will be credited to [account].");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(-12, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey;
scriptPubKey.SetDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false))
throw JSONRPCError(-12, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount);
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress <account>\n"
"Returns the current TestCoin address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
Value ret;
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount <testcoin address> <account>\n"
"Sets the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(-5, "Invalid TestCoin address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()];
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBookName(address.Get(), strAccount);
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount <testcoin address>\n"
"Returns the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(-5, "Invalid TestCoin address");
string strAccount;
map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
strAccount = (*mi).second;
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount <account>\n"
"Returns the list of addresses for the given account.");
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
Value settxfee(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"settxfee <amount>\n"
"<amount> is a real and is rounded to the nearest 0.00000001");
// Amount
int64 nAmount = 0;
if (params[0].get_real() != 0.0)
nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
nTransactionFee = nAmount;
return true;
}
Value setmininput(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"setmininput <amount>\n"
"<amount> is a real and is rounded to the nearest 0.00000001");
// Amount
int64 nAmount = 0;
if (params[0].get_real() != 0.0)
nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
nMinimumInputValue = nAmount;
return true;
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress <testcoin address> <amount> [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(-5, "Invalid TestCoin address");
// Amount
int64 nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
if (pwalletMain->IsLocked())
throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(-4, strError);
return wtx.GetHash().GetHex();
}
Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage <testcoin address> <message>\n"
"Sign a message with the private key of an address");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(-3, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(-3, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(-4, "Private key not available");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
throw JSONRPCError(-5, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <testcoin address> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(-3, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(-3, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(-5, "Malformed base64 encoding");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CKey key;
if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig))
return false;
return (key.GetPubKey().GetID() == keyID);
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress <testcoin address> [minconf=1]\n"
"Returns the total amount received by <testcoin address> in transactions with at least [minconf] confirmations.");
// TestCoin address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
CScript scriptPubKey;
if (!address.IsValid())
throw JSONRPCError(-5, "Invalid TestCoin address");
scriptPubKey.SetDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook)
{
const CTxDestination& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
setAddress.insert(address);
}
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount <account> [minconf=1]\n"
"Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress;
GetAccountAddresses(strAccount, setAddress);
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
int64 nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
continue;
int64 nGenerated, nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nGenerated, nReceived, nSent, nFee);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
nBalance += nReceived;
nBalance += nGenerated - nSent - nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
int64 GetAccountBalance(const string& strAccount, int nMinDepth)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getbalance [account] [minconf=1]\n"
"If [account] is not specified, returns the server's total available balance.\n"
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' should always return the same number.
int64 nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
continue;
int64 allGeneratedImmature, allGeneratedMature, allFee;
allGeneratedImmature = allGeneratedMature = allFee = 0;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
nBalance += r.second;
}
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent)
nBalance -= r.second;
nBalance -= allFee;
nBalance += allGeneratedMature;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
return ValueFromAmount(nBalance);
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
"Move from one account in your wallet to another.");
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
int64 nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(-20, "database error");
int64 nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(-20, "database error");
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom <fromaccount> <to testcoin address> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(-5, "Invalid TestCoin address");
int64 nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (nAmount > nBalance)
throw JSONRPCError(-6, "Account has insufficient funds");
// Send
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(-4, strError);
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, int64> > vecSend;
int64 totalAmount = 0;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(-5, string("Invalid TestCoin address:")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(-6, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
int64 nFeeRequired = 0;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
if (!fCreated)
{
if (totalAmount + nFeeRequired > pwalletMain->GetBalance())
throw JSONRPCError(-6, "Insufficient funds");
throw JSONRPCError(-4, "Transaction creation failed");
}
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(-4, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
Value addmultisigaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"Add a nrequired-to-sign multisignature address to the wallet\"\n"
"each key is a TestCoin address or hex-encoded public key\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %d keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
// Case 1: TestCoin address and we have full public key:
CBitcoinAddress address(ks);
if (address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks.c_str()));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks.c_str()));
if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey))
throw runtime_error(" Invalid public key: "+ks);
}
// Case 2: hex public key
else if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey))
throw runtime_error(" Invalid public key: "+ks);
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
// Construct using pay-to-script-hash:
CScript inner;
inner.SetMultisig(nRequired, pubkeys);
CScriptID innerID = inner.GetID();
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
struct tallyitem
{
int64 nAmount;
int nConf;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
}
}
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
int64 nAmount = 0;
int nConf = std::numeric_limits<int>::max();
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
}
else
{
Object obj;
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
int64 nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
Object obj;
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaddress [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include addresses that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"address\" : receiving address\n"
" \"account\" : the account of the receiving address\n"
" \"amount\" : total amount received by the address\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaccount [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include accounts that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"account\" : the account of the receiving addresses\n"
" \"amount\" : total amount received by addresses with this account\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, true);
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
int64 nGeneratedImmature, nGeneratedMature, nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
bool fAllAccounts = (strAccount == string("*"));
// Generated blocks assigned to account ""
if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == ""))
{
Object entry;
entry.push_back(Pair("account", string("")));
if (nGeneratedImmature)
{
entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan"));
entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature)));
}
else
{
entry.push_back(Pair("category", "generate"));
entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature)));
}
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
{
Object entry;
entry.push_back(Pair("account", strSentAccount));
entry.push_back(Pair("address", CBitcoinAddress(s.first).ToString()));
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first];
if (fAllAccounts || (account == strAccount))
{
Object entry;
entry.push_back(Pair("account", account));
entry.push_back(Pair("address", CBitcoinAddress(r.first).ToString()));
entry.push_back(Pair("category", "receive"));
entry.push_back(Pair("amount", ValueFromAmount(r.second)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listtransactions [account] [count=10] [from=0]\n"
"Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
if (nCount < 0)
throw JSONRPCError(-8, "Negative count");
if (nFrom < 0)
throw JSONRPCError(-8, "Negative from");
Array ret;
CWalletDB walletdb(pwalletMain->strWalletFile);
// First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef multimap<int64, TxPair > TxItems;
TxItems txByTime;
// Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
// would make this much faster for applications that do this a lot.
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
CWalletTx* wtx = &((*it).second);
txByTime.insert(make_pair(wtx->GetTxTime(), TxPair(wtx, (CAccountingEntry*)0)));
}
list<CAccountingEntry> acentries;
walletdb.ListAccountCreditDebit(strAccount, acentries);
BOOST_FOREACH(CAccountingEntry& entry, acentries)
{
txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
}
// iterate backwards until we have nCount items to return:
for (TxItems::reverse_iterator it = txByTime.rbegin(); it != txByTime.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
Array::iterator first = ret.begin();
std::advance(first, nFrom);
Array::iterator last = ret.begin();
std::advance(last, nFrom+nCount);
if (last != ret.end()) ret.erase(last, ret.end());
if (first != ret.begin()) ret.erase(ret.begin(), first);
std::reverse(ret.begin(), ret.end()); // Return oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"listaccounts [minconf=1]\n"
"Returns Object that has account names as keys, account balances as values.");
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
map<string, int64> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first)) // This address belongs to me
mapAccountBalances[entry.second] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64 nGeneratedImmature, nGeneratedMature, nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second;
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
mapAccountBalances[""] += nGeneratedMature;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
else
mapAccountBalances[""] += r.second;
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
Value listsinceblock(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock [blockhash] [target-confirmations]\n"
"Get all transactions in blocks since block [blockhash], or all transactions if omitted");
CBlockIndex *pindex = NULL;
int target_confirms = 1;
if (params.size() > 0)
{
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
pindex = CBlockLocator(blockId).GetBlockIndex();
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(-8, "Invalid parameter");
}
int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;
Array transactions;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain() < depth)
ListTransactions(tx, "*", 0, true, transactions);
}
uint256 lastblock;
if (target_confirms == 1)
{
lastblock = hashBestChain;
}
else
{
int target_height = pindexBest->nHeight + 1 - target_confirms;
CBlockIndex *block;
for (block = pindexBest;
block && block->nHeight > target_height;
block = block->pprev) { }
lastblock = block ? block->GetBlockHash() : 0;
}
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"gettransaction <txid>\n"
"Get detailed information about in-wallet transaction <txid>");
uint256 hash;
hash.SetHex(params[0].get_str());
Object entry;
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(-5, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
int64 nCredit = wtx.GetCredit();
int64 nDebit = wtx.GetDebit();
int64 nNet = nCredit - nDebit;
int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
Array details;
ListTransactions(wtx, "*", 0, false, details);
entry.push_back(Pair("details", details));
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet <destination>\n"
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
string strDest = params[0].get_str();
BackupWallet(*pwalletMain, strDest);
return Value::null;
}
Value keypoolrefill(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"keypoolrefill\n"
"Fills the keypool."
+ HelpRequiringPassphrase());
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool();
if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100))
throw JSONRPCError(-4, "Error refreshing keypool.");
return Value::null;
}
void ThreadTopUpKeyPool(void* parg)
{
// Make this thread recognisable as the key-topping-up thread
RenameThread("bitcoin-key-top");
pwalletMain->TopUpKeyPool();
}
void ThreadCleanWalletPassphrase(void* parg)
{
// Make this thread recognisable as the wallet relocking thread
RenameThread("bitcoin-lock-wa");
int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000;
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
if (nWalletUnlockTime == 0)
{
nWalletUnlockTime = nMyWakeTime;
do
{
if (nWalletUnlockTime==0)
break;
int64 nToSleep = nWalletUnlockTime - GetTimeMillis();
if (nToSleep <= 0)
break;
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
Sleep(nToSleep);
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
} while(1);
if (nWalletUnlockTime)
{
nWalletUnlockTime = 0;
pwalletMain->Lock();
}
}
else
{
if (nWalletUnlockTime < nMyWakeTime)
nWalletUnlockTime = nMyWakeTime;
}
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
delete (int64*)parg;
}
Value walletpassphrase(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
if (!pwalletMain->IsLocked())
throw JSONRPCError(-17, "Error: Wallet is already unlocked.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() > 0)
{
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect.");
}
else
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
CreateThread(ThreadTopUpKeyPool, NULL);
int64* pnSleepTime = new int64(params[1].get_int64());
CreateThread(ThreadCleanWalletPassphrase, pnSleepTime);
return Value::null;
}
Value walletpassphrasechange(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect.");
return Value::null;
}
Value walletlock(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"Removes the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return Value::null;
}
Value encryptwallet(const Array& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(-15, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(-16, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; TestCoin server stopping, restart to run with encrypted wallet";
}
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey.Raw())));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <testcoin address>\n"
"Return information about <testcoin address>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = IsMine(*pwalletMain, dest);
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
Value getworkex(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getworkex [data, coinbase]\n"
"If [data, coinbase] is not specified, returns extended work data.\n"
);
if (vNodes.empty())
throw JSONRPCError(-9, "TestCoin server is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "TestCoin server is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock;
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
nTransactionsUpdatedLast = nTransactionsUpdated;
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(reservekey);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
vNewBlock.push_back(pblock);
}
// Update nTime
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Prebuild hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
CTransaction coinbaseTx = pblock->vtx[0];
std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
Object result;
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << coinbaseTx;
result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
Array merkle_arr;
printf("DEBUG: merkle size %i\n", merkle.size());
BOOST_FOREACH(uint256 merkleh, merkle) {
printf("%s\n", merkleh.ToString().c_str());
merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
}
result.push_back(Pair("merkle", merkle_arr));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
vector<unsigned char> coinbase;
if(params.size() == 2)
coinbase = ParseHex(params[1].get_str());
if (vchData.size() != 128)
throw JSONRPCError(-8, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
if(coinbase.size() == 0)
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
else
CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(-9, "TestCoin server is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "TestCoin server is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
nTransactionsUpdatedLast = nTransactionsUpdated;
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(reservekey);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
vNewBlock.push_back(pblock);
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Prebuild hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
result.push_back(Pair("algorithm", "scrypt:1024,1,1")); // specify that we should use the scrypt algorithm
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(-8, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblocktemplate [params]\n"
"If [params] does not contain a \"data\" key, returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"If [params] does contain a \"data\" key, tries to solve the block and returns null if it was successful (and \"rejected\" if not)\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
const Object& oparam = params[0].get_obj();
std::string strMode;
{
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else
if (find_value(oparam, "data").type() == null_type)
strMode = "template";
else
strMode = "submit";
}
if (strMode == "template")
{
if (vNodes.empty())
throw JSONRPCError(-9, "TestCoin server is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "TestCoin server is downloading blocks...");
static CReserveKey reservekey(pwalletMain);
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
nTransactionsUpdatedLast = nTransactionsUpdated;
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
if(pblock)
delete pblock;
pblock = CreateNewBlock(reservekey);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
CTxDB txdb("r");
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
Array deps;
BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
{
if (setTxIndex.count(inp.first))
deps.push_back(setTxIndex[inp.first]);
}
entry.push_back(Pair("depends", deps));
int64_t nSigOps = tx.GetLegacySigOpCount();
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
entry.push_back(Pair("sigops", nSigOps));
}
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", HexBits(pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
else
if (strMode == "submit")
{
// Parse parameters
CDataStream ssBlock(ParseHex(find_value(oparam, "data").get_str()), SER_NETWORK, PROTOCOL_VERSION);
CBlock pblock;
ssBlock >> pblock;
bool fAccepted = ProcessBlock(NULL, &pblock);
return fAccepted ? Value::null : "rejected";
}
throw JSONRPCError(-8, "Invalid mode");
}
Value getrawmempool(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getrawmempool\n"
"Returns all transaction ids in memory pool.");
vector<uint256> vtxid;
mempool.queryHashes(vtxid);
Array a;
BOOST_FOREACH(const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
Value getblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblockhash <index>\n"
"Returns hash of block in best-block-chain at <index>.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
return pblockindex->phashBlock->GetHex();
}
Value getblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblock <hash>\n"
"Returns details of a block with given block-hash.");
std::string strHash = params[0].get_str();
uint256 hash(strHash);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(-5, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex, true);
return blockToJSON(block, pblockindex);
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name function safe mode?
// ------------------------ ----------------------- ----------
{ "help", &help, true },
{ "stop", &stop, true },
{ "getblockcount", &getblockcount, true },
{ "getconnectioncount", &getconnectioncount, true },
{ "getpeerinfo", &getpeerinfo, true },
{ "getdifficulty", &getdifficulty, true },
{ "getnetworkhashps", &getnetworkhashps, true },
{ "getgenerate", &getgenerate, true },
{ "setgenerate", &setgenerate, true },
{ "gethashespersec", &gethashespersec, true },
{ "getinfo", &getinfo, true },
{ "getmininginfo", &getmininginfo, true },
{ "getnewaddress", &getnewaddress, true },
{ "getaccountaddress", &getaccountaddress, true },
{ "setaccount", &setaccount, true },
{ "getaccount", &getaccount, false },
{ "getaddressesbyaccount", &getaddressesbyaccount, true },
{ "sendtoaddress", &sendtoaddress, false },
{ "getreceivedbyaddress", &getreceivedbyaddress, false },
{ "getreceivedbyaccount", &getreceivedbyaccount, false },
{ "listreceivedbyaddress", &listreceivedbyaddress, false },
{ "listreceivedbyaccount", &listreceivedbyaccount, false },
{ "backupwallet", &backupwallet, true },
{ "keypoolrefill", &keypoolrefill, true },
{ "walletpassphrase", &walletpassphrase, true },
{ "walletpassphrasechange", &walletpassphrasechange, false },
{ "walletlock", &walletlock, true },
{ "encryptwallet", &encryptwallet, false },
{ "validateaddress", &validateaddress, true },
{ "getbalance", &getbalance, false },
{ "move", &movecmd, false },
{ "sendfrom", &sendfrom, false },
{ "sendmany", &sendmany, false },
{ "addmultisigaddress", &addmultisigaddress, false },
{ "getrawmempool", &getrawmempool, true },
{ "getblock", &getblock, false },
{ "getblockhash", &getblockhash, false },
{ "gettransaction", &gettransaction, false },
{ "listtransactions", &listtransactions, false },
{ "signmessage", &signmessage, false },
{ "verifymessage", &verifymessage, false },
{ "getwork", &getwork, true },
{ "getworkex", &getworkex, true },
{ "listaccounts", &listaccounts, false },
{ "settxfee", &settxfee, false },
{ "setmininput", &setmininput, false },
{ "getblocktemplate", &getblocktemplate, true },
{ "listsinceblock", &listsinceblock, false },
{ "dumpprivkey", &dumpprivkey, false },
{ "importprivkey", &importprivkey, false },
{ "listunspent", &listunspent, false },
{ "getrawtransaction", &getrawtransaction, false },
{ "createrawtransaction", &createrawtransaction, false },
{ "decoderawtransaction", &decoderawtransaction, false },
{ "signrawtransaction", &signrawtransaction, false },
{ "sendrawtransaction", &sendrawtransaction, false },
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: testcoin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want posix (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == 401)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: testcoin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == 200) cStatus = "OK";
else if (nStatus == 400) cStatus = "Bad Request";
else if (nStatus == 403) cStatus = "Forbidden";
else if (nStatus == 404) cStatus = "Not Found";
else if (nStatus == 500) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %d\r\n"
"Content-Type: application/json\r\n"
"Server: testcoin-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return 500;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
loop
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Read header
int nLen = ReadHTTPHeader(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return 500;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return nStatus;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return strUserPass == strRPCUserColonPass;
}
//
// JSON-RPC protocol. TestCoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = 500;
int code = find_value(objError, "code").get_int();
if (code == -32600) nStatus = 400;
else if (code == -32601) nStatus = 404;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Chech whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ThreadRPCServer(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));
// Make this thread recognisable as the RPC listener
RenameThread("bitcoin-rpclist");
try
{
vnThreadsRunning[THREAD_RPCLISTENER]++;
ThreadRPCServer2(parg);
vnThreadsRunning[THREAD_RPCLISTENER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_RPCLISTENER]--;
PrintException(&e, "ThreadRPCServer()");
} catch (...) {
vnThreadsRunning[THREAD_RPCLISTENER]--;
PrintException(NULL, "ThreadRPCServer()");
}
printf("ThreadRPCServer exited\n");
}
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
vnThreadsRunning[THREAD_RPCLISTENER]++;
// Immediately start accepting new connections, except when we're canceled or our socket is closed.
if (error != asio::error::operation_aborted
&& acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn
&& !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(403, "", false) << std::flush;
delete conn;
}
// start HTTP client thread
else if (!CreateThread(ThreadRPCServer3, conn)) {
printf("Failed to create RPC server client thread\n");
delete conn;
}
vnThreadsRunning[THREAD_RPCLISTENER]--;
}
void ThreadRPCServer2(void* parg)
{
printf("ThreadRPCServer started\n");
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if (mapArgs["-rpcpassword"] == "")
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use testcoin";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n %s\n"
"It is recommended you use the following random password:\n"
"rpcuser=testcoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
_("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
StartShutdown();
return;
}
const bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
if (fUseSSL)
{
context.set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 55883));
boost::signals2::signal<void ()> StopRequests;
try
{
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
boost::system::error_code v6_only_error;
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, context, fUseSSL);
// Cancel outstanding listen-requests for this acceptor when shutting down
StopRequests.connect(signals2::slot<void ()>(
static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
.track(acceptor));
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, context, fUseSSL);
// Cancel outstanding listen-requests for this acceptor when shutting down
StopRequests.connect(signals2::slot<void ()>(
static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
.track(acceptor));
}
}
catch(boost::system::system_error &e)
{
uiInterface.ThreadSafeMessageBox(strprintf(_("An error occured while setting up the RPC port %i for listening: %s"), endpoint.port(), e.what()),
_("Error"), CClientUIInterface::OK | CClientUIInterface::MODAL);
StartShutdown();
return;
}
vnThreadsRunning[THREAD_RPCLISTENER]--;
while (!fShutdown)
io_service.run_one();
vnThreadsRunning[THREAD_RPCLISTENER]++;
StopRequests();
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(-32600, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(-32600, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(-32600, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(-32600, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(-32700, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
static CCriticalSection cs_THREAD_RPCHANDLER;
void ThreadRPCServer3(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer3(parg));
// Make this thread recognisable as the RPC handler
RenameThread("bitcoin-rpchand");
{
LOCK(cs_THREAD_RPCHANDLER);
vnThreadsRunning[THREAD_RPCHANDLER]++;
}
AcceptedConnection *conn = (AcceptedConnection *) parg;
bool fRun = true;
loop {
if (fShutdown || !fRun)
{
conn->close();
delete conn;
{
LOCK(cs_THREAD_RPCHANDLER);
--vnThreadsRunning[THREAD_RPCHANDLER];
}
return;
}
map<string, string> mapHeaders;
string strRequest;
ReadHTTP(conn->stream(), mapHeaders, strRequest);
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(401, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DOS the user really
shouldn't have their RPC port exposed.*/
if (mapArgs["-rpcpassword"].size() < 20)
Sleep(250);
conn->stream() << HTTPReply(401, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(-32700, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(-32700, "Top-level object parse error");
conn->stream() << HTTPReply(200, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(-32700, e.what()), jreq.id);
break;
}
}
delete conn;
{
LOCK(cs_THREAD_RPCHANDLER);
vnThreadsRunning[THREAD_RPCHANDLER]--;
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(-32601, "Method not found");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(-2, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(-1, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "55883")))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive reply
map<string, string> mapHeaders;
string strReply;
int nStatus = ReadHTTP(stream, mapHeaders, strReply);
if (nStatus == 401)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value)
{
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
value = value2.get_value<T>();
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "setmininput" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (std::exception& e)
{
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...)
{
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
| [
"tujiulong@163.com"
] | tujiulong@163.com |
223ddb7fab4b319842f70aba13114b56e631171a | 3ecce7ff41b6416df296c34d7a0f720e936310f1 | /SklepTui/Sale.h | 2d28c79f6171391d894cc2349eca1338f9a2e8fc | [] | no_license | KonradKacperDomian/CashRegisterSimulator | 6606db906d87ccb6b659ec4b9637cec057c416a7 | 45016c4586d2778bd5fbdcad4f1d878301bd0a4c | refs/heads/master | 2023-03-31T04:30:54.430361 | 2020-06-23T21:00:43 | 2020-06-23T21:00:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 203 | h | #pragma once
#include "DailyRaport.h"
#include "ProductListManager.h"
class Sale
{
public:
void displayMenu();
void menuChooser(ProductListManager&, DailyRaport&);
void replacement(DailyRaport&);
};
| [
"k.domian@stud.elka.pw.edu.pl"
] | k.domian@stud.elka.pw.edu.pl |
f6f3828bf4205a01b03959f03b51dbed07541052 | 59c47e1f8b2738fc2b824462e31c1c713b0bdcd7 | /002-Qt_widget_Concerning/000-Qt-widget-project/WindowsAPP/BST_IDE/global/ui/bggen.h | 8c4f018e2c4030dcc662c7b1d0c6832f87ca1d5f | [] | no_license | casterbn/Qt_project | 8efcc46e75e2bbe03dc4aeaafeb9e175fb7b04ab | 03115674eb3612e9dc65d4fd7bcbca9ba27f691c | refs/heads/master | 2021-10-19T07:27:24.550519 | 2019-02-19T05:26:22 | 2019-02-19T05:26:22 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,149 | h | #ifndef BASEBGGEN_H
#define BASEBGGEN_H
#include "global.h"
class BaseBgGen : public QObject
{
Q_OBJECT
public:
BaseBgGen(QObject *parent = 0);
void SetFocus(bool pFocus);
void SetTitle(QString pTitle);
void SetFullScreen(bool pEnable);
void Resize(QSize pSize);
void Refresh();
void SetPattern(int pPattern) {m_Pattern = pPattern;}
public:
QBrush m_BgBrush, m_FgBrush,
m_BGlowBrush, //>@底部光晕
m_TGlassBrush, m_TGlassBrush2, //>@顶部玻璃磨砂效果
m_LightBrush; //>@选中高亮效果
QColor m_BgPenColor, m_FgPenColor;
QRect m_BgRect, m_FgRect,
m_BGlowRect, //>@底部光晕
m_TGlassRect, //>@顶部玻璃磨砂效果
m_LightRect; //>@选中高亮效果
QString m_Content;
QFont m_ContentFont;
QColor m_ContentColor;
QImage m_Image;
bool m_Focus;
bool m_FullScreen;
int m_Pattern;
};
#endif // BASEBGGEN_H
| [
"1343726739@qq.com"
] | 1343726739@qq.com |
6f1391fdf2ce1899fc0e95a8330a3bd0d3461d3b | ce817e3fb2a27f076f8fb348bb692f5a060c8fc8 | /src/loam_velodyne/src/different_modules/subMap.h | df7e891fcd1484862eae393b7365ea17aaab6027 | [
"BSD-3-Clause"
] | permissive | DriftingTimmy/slam_code | 88ede432e093787aab405b44595fc78c0f9e396f | 20e2b2720f8662c96dd9beb1ec8d8c733f9dd6d2 | refs/heads/master | 2020-03-31T17:36:55.349265 | 2018-11-09T07:57:44 | 2018-11-09T07:57:44 | 152,427,981 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,578 | h | //
// Created by timmy on 17-9-21.
//
#ifndef PROJECT_SUBMAP_H
#define PROJECT_SUBMAP_H
//#include <opencv2/highgui/highgui.hpp>
//#include "opencv2/video/tracking.hpp"
#include <nav_msgs/Odometry.h>
#include <opencv/cv.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <ros/ros.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/PointCloud2.h>
#include <tf/transform_datatypes.h>
#include <tf/transform_broadcaster.h>
#include <message_filters/subscriber.h>
#include <message_filters/synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <message_filters/time_synchronizer.h>
typedef pcl::PointXYZ Point;
typedef pcl::PointXYZI PointI;
typedef pcl::PointCloud<pcl::PointXYZ> PointCloud;
typedef message_filters::sync_policies::ApproximateTime
<sensor_msgs::PointCloud2,sensor_msgs::Imu> slamSyncPolicy;
class SubMap{
public:
SubMap(ros::NodeHandle nh,
ros::NodeHandle private_nh);
~SubMap() {}
message_filters::Subscriber<sensor_msgs::PointCloud2> *featurePoints_sub;
message_filters::Subscriber<sensor_msgs::Imu> *imu_sub;
message_filters::Synchronizer<slamSyncPolicy> *sync_;
void callback(const sensor_msgs::PointCloud2ConstPtr& pointcloud_msg,
const sensor_msgs::ImuConstPtr& imu_msg);
private:
PointCloud pointCloud_;
nav_msgs::Odometry odometry_;
};
Eigen::Matrix4f NdtMatch(PointCloud lastPointCloud,
PointCloud curPointCloud);
Eigen::Matrix4f ICPMatch(PointCloud lastPointCloud,
PointCloud curPointCloud);
Eigen::Matrix4f TransformToTransformation(float x, float y, float z,
float translation_x,
float translation_y,
float translation_z);
void AddSubmap(PointCloud Pointcloud, Eigen::Vector3d Pose);
void DetectLoop(PointCloud Pointcloud, Eigen::Vector3d Pose);
void InsertToSubmap(PointCloud pointcloud);
void imuTransHandler(sensor_msgs::PointCloud2 ImuMsg);
void imuHandler(const sensor_msgs::Imu::ConstPtr& imuIn);
Eigen::Vector3f PoseEstimate(Eigen::Vector3f PoseLast,
Eigen::Vector3f tf_ndt,
Eigen::Vector3f tf_imu);
//struct Pose
//{
// double x;
// double y;
// double z;
// double roll;
// double pitch;
// double yaw;
//};
#endif //PROJECT_SUBMAP_H
| [
"lxneverfail@gmail.com"
] | lxneverfail@gmail.com |
358d099e55e60b1240da735a3cef95e2b6792613 | 4c23be1a0ca76f68e7146f7d098e26c2bbfb2650 | /ic8h18/0.004/C4H8CHO4-2 | 436bd9608509b4a27ccddd46b07d7aa3b7fb5ada | [] | no_license | labsandy/OpenFOAM_workspace | a74b473903ddbd34b31dc93917e3719bc051e379 | 6e0193ad9dabd613acf40d6b3ec4c0536c90aed4 | refs/heads/master | 2022-02-25T02:36:04.164324 | 2019-08-23T02:27:16 | 2019-08-23T02:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 842 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.004";
object C4H8CHO4-2;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 1.97571e-11;
boundaryField
{
boundary
{
type empty;
}
}
// ************************************************************************* //
| [
"jfeatherstone123@gmail.com"
] | jfeatherstone123@gmail.com | |
292a148bd3acc5620d1eac22d7e3b0d3b46b0771 | 80ce41145cae41a57ee55ee03c230f110e209c39 | /tests/metron_good/if_with_compound.h | 621e3294ace158bc6712a41639da1a8a2f00094c | [
"MIT"
] | permissive | fengjixuchui/Metron | 2d2abcfc1b9191d2950116082fd5b04d5476ee1b | 49093c2fa734a856e1ebb78e240d8b6dbae8cc8a | refs/heads/master | 2023-03-16T16:03:18.688900 | 2023-02-01T06:28:59 | 2023-02-01T06:28:59 | 494,727,930 | 0 | 0 | MIT | 2023-02-01T06:29:00 | 2022-05-21T08:43:57 | C++ | UTF-8 | C++ | false | false | 411 | h | #include "metron_tools.h"
// If statements whose sub-blocks contain submodule calls _must_ use {}.
class Submod {
public:
void tock(logic<8> arg) {
tick(arg);
}
private:
void tick(logic<8> arg) {
my_reg = my_reg + arg;
}
logic<8> my_reg;
};
class Module {
public:
void tock() {
if (1) {
submod.tock(72);
}
else {
submod.tock(36);
}
}
Submod submod;
};
| [
"aappleby@gmail.com"
] | aappleby@gmail.com |
8373d14c516a8d11e046bd34e1edc82c3cb370dc | edf34060a2d23b47d3876643a8b302673feb10a6 | /windows/runner/main.cpp | ff7e5952af282303120b58b364bb3bb24b990882 | [] | no_license | shashwatxx/volv_test1 | 1c502af7afa521db8465bd9ee066c6f67f425552 | 3c3d993d71d4770b7f3a0e315f794fd4c6e20936 | refs/heads/main | 2023-08-14T12:26:33.457815 | 2021-10-11T10:35:50 | 2021-10-11T10:35:50 | 415,103,491 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,270 | cpp | #include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#include "flutter_window.h"
#include "utils.h"
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t *command_line, _In_ int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
}
// Initialize COM, so that it is available for use in the library and/or
// plugins.
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
flutter::DartProject project(L"data");
std::vector<std::string> command_line_arguments =
GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
FlutterWindow window(project);
Win32Window::Point origin(10, 10);
Win32Window::Size size(1280, 720);
if (!window.CreateAndShow(L"volv_testi", origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
::MSG msg;
while (::GetMessage(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
::CoUninitialize();
return EXIT_SUCCESS;
}
| [
"shashwatmishra2111@gmail.com"
] | shashwatmishra2111@gmail.com |
3710898ffb37589515ae94dc8f716a58716170e2 | 246adb4a5f28684fefd90324a13557940755d4d5 | /lab01/lab01/TransferMoorToMellee.h | df5a4944866e2c598c4ba5c275098049524af5bb | [] | no_license | AnatolyKorablyov/SEANS | 7f3cc8486eacd6da8dccef99df43a6dbd329925f | 9f2aa8f863208e4aeaa373ddc27a9c5fbafa08b2 | refs/heads/master | 2021-03-24T10:22:12.930538 | 2016-06-08T20:56:18 | 2016-06-08T20:56:18 | 59,008,326 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 261 | h | #pragma once
#include "MelleeStatesment.h"
#include "MooraStatesment.h"
#include <vector>
class CTransferMoorToMellee
{
public:
CTransferMoorToMellee(CMooraStatesment & moorData);
CMelleeStatesment m_resultMellee;
std::vector<CStateMelee> vectorStates;
};
| [
"anatoly5432@gmail.com"
] | anatoly5432@gmail.com |
78bbe9843b402d6398e1e368b872c147d9436402 | 5fc00bda5ba1a09ef39e14ec2cf601b3d8aae967 | /CorrsAndSysts/test/CorrsAndSysts.cpp | 7a0de358fa1f6b94171338d40d13bc4ba1c8def3 | [] | no_license | tibristo/mva | d982ec92c3569f5bf55f57ef177ed201bc1f764e | a7d35ef02bfce2bec2b3cdaf729d68b203ee0ce8 | refs/heads/master | 2021-01-25T07:19:27.266029 | 2013-11-04T20:41:23 | 2013-11-04T20:41:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 50,503 | cpp | #include <boost/python.hpp>
#include "CorrsAndSysts.hpp"
#include <algorithm>
#include <cmath>
#include <Python.h>
#include <TVector2.h>
using namespace boost::python;
/*
* See header file for description
*
*/
CorrsAndSysts::CorrsAndSysts(TString name, bool draw) :
m_debug(0),
m_zero(false),
m_one(false),
m_two(false),
m_seven(false),
m_eight(false)
{
m_draw = draw;
// set analysis basesd on contentes of name
if(name.Contains("Zero") || name.Contains("zero") || name.Contains("ZERO")) { m_zero = true; }
if(name.Contains("One") || name.Contains("one") || name.Contains("ONE")) { m_one = true; }
if(name.Contains("Two") || name.Contains("two") || name.Contains("TWO")) { m_two = true; }
// check lepton selection chosen correctly
if((m_zero && m_one) || (m_zero && m_two) || (m_one && m_two)) {
std::cout << "CorrsAndSysts initialized for multiple analyses" << std::endl;
exit(-1);
}
if(!m_zero && !m_one && !m_two) {
std::cout << "CorrsAndSysts initialized for none of the analyses" << std::endl;
exit(-1);
}
// set year
if(name.Contains("7TeV")) { m_seven = true; }
if(name.Contains("8TeV")) { m_eight = true; }
// check year is set correctly
if(m_seven && m_eight) {
std::cout << "CorrsAndSysts initialized for 7 and 8 TeV" << std::endl;
exit(-1);
}
if(!m_seven && !m_eight) {
std::cout << "CorrsAndSysts initialized for neither 7 nor 8 TeV" << std::endl;
exit(-1);
}
// write some stuff so users can be confident they did this correctly
std::cout << "Initalize CorrsAndSysts for ";
if(m_zero) { std::cout << "Zero"; }
if(m_one) { std::cout << "One"; }
if(m_two) { std::cout << "Two"; }
std::cout << " Lepton ";
if(m_seven) { std::cout << "7"; }
if(m_eight) { std::cout << "8"; }
std::cout << " TeV analysis" << std::endl;
// initalize the corrections and systematics
Initialize();
} // CorrsAndSysts
CorrsAndSysts::CorrsAndSysts(int channel, int year, bool draw) :
m_debug(0),
m_zero(false),
m_one(false),
m_two(false),
m_seven(false),
m_eight(false)
{
m_draw = draw;
switch(channel) {
case 0:
m_zero = true;
break;
case 1:
m_one = true;
break;
case 2:
m_two = true;
break;
default:
std::cout << "CorrsAndSysts initialized for none of the analyses" << std::endl;
exit(-1);
}
switch(year) {
case 2011:
m_seven = true;
break;
case 2012:
m_eight = true;
break;
default:
std::cout << "CorrsAndSysts initialized for neither 7 nor 8 TeV" << std::endl;
exit(-1);
}
// write some stuff so users can be confident they did this correctly
std::cout << "Initalize CorrsAndSysts for ";
if(m_zero) { std::cout << "Zero"; }
if(m_one) { std::cout << "One"; }
if(m_two) { std::cout << "Two"; }
std::cout << " Lepton ";
if(m_seven) { std::cout << "7"; }
if(m_eight) { std::cout << "8"; }
std::cout << " TeV analysis" << std::endl;
// initalize the corrections and systematics
Initialize();
} // CorrsAndSysts
CorrsAndSysts::~CorrsAndSysts() {
delete m_h_WHlvbbNLOEWKCorrection;
delete m_h_ZHllbbNLOEWKCorrection;
delete m_h_ZHvvbbNLOEWKCorrection;
delete m_h_WpTCorrection;
delete m_h_ZpTCorrection;
delete m_h_WDeltaPhiCorrection2Jet;
delete m_h_WDeltaPhiCorrection3Jet;
delete m_h_ZDeltaPhiCorrection;
delete m_h_topPtCorrection;
delete m_h_SysWbbPtW;
delete m_h_SysStopPt;
delete m_h_SysWccPtW;
delete m_h_SysWllPtW;
delete m_h_SysZbbPtZ;
delete m_h_SysZccPtZ;
delete m_h_SysZllPtZ;
delete m_h_SysTheoryWHlvbbPt;
delete m_h_SysTheoryZHllbbPt;
delete m_h_SysTheoryZHvvbbPt;
delete m_f_WDPhiCorr;
delete m_f_ZDPhiCorr;
delete m_f_SysZbbMbb;
delete m_f_SysWbbMbb;
delete m_f_SysTopMbb;
delete m_f_SysStopMbb;
delete m_f_SysWMbb;
delete m_f_SysZMbb;
}
void CorrsAndSysts::Initialize() {
// initialize the mappings to event types
m_typeNames["WHlvbb"] = CAS::WHlvbb;
m_typeNames["ZHllbb"] = CAS::ZHllbb;
m_typeNames["ZHvvbb"] = CAS::ZHvvbb;
m_typeNames["WlvH"] = CAS::WHlvbb;
m_typeNames["ZllH"] = CAS::ZHllbb;
m_typeNames["ZvvH"] = CAS::ZHvvbb;
m_typeNames["signalWH"] = CAS::WHlvbb;
m_typeNames["signalZHll"] = CAS::ZHllbb;
m_typeNames["signalZHvv"] = CAS::ZHvvbb;
m_typeNames["Wb"] = CAS::Wb;
m_typeNames["Wbb"] = CAS::Wb;
m_typeNames["Wbc"] = CAS::Wb;
m_typeNames["Wbl"] = CAS::Wb;
m_typeNames["Wc"] = CAS::Wc;
m_typeNames["Wcl"] = CAS::Wc;
m_typeNames["Wcc"] = CAS::Wcc;
m_typeNames["Wl"] = CAS::Wl;
m_typeNames["Wll"] = CAS::Wl;
m_typeNames["Zb"] = CAS::Zb;
m_typeNames["Zbb"] = CAS::Zb;
m_typeNames["Zbc"] = CAS::Zb;
m_typeNames["Zbl"] = CAS::Zb;
m_typeNames["Zc"] = CAS::Zc;
m_typeNames["Zcc"] = CAS::Zc;
m_typeNames["Zcl"] = CAS::Zc;
m_typeNames["Zl"] = CAS::Zl;
m_typeNames["Zll"] = CAS::Zl;
m_typeNames["top"] = CAS::ttbar;
m_typeNames["ttbar"] = CAS::ttbar;
m_typeNames["stop"] = CAS::stop;
m_typeNames["WW"] = CAS::diboson;
m_typeNames["WZ"] = CAS::diboson;
m_typeNames["ZZ"] = CAS::diboson;
m_systNames[CAS::Nominal] = "";
m_systNames[CAS::SysTheoryHPt] = "SysTheoryHPt";
m_systNames[CAS::SysTopPt] = "SysTopPt";
m_systNames[CAS::SysStopPt] = "SysStopPt";
m_systNames[CAS::SysWbbPtW] = "SysWbbPtW";
m_systNames[CAS::SysWccPtW] = "SysWccPtW";
m_systNames[CAS::SysZbbPtZ] = "SysZbbPtZ";
m_systNames[CAS::SysZccPtZ] = "SysZccPtZ";
m_systNames[CAS::SysWllPtW] = "SysWllPtW";
m_systNames[CAS::SysZllPtZ] = "SysZllPtZ";
m_systNames[CAS::SysTopMbb] = "SysTopMbb";
m_systNames[CAS::SysStopMbb] = "SysStopMbb";
m_systNames[CAS::SysZbbMbb] = "SysZbbMbb";
m_systNames[CAS::SysWbbMbb] = "SysWbbMbb";
m_systNames[CAS::SysZMbb] = "SysZMbb";
m_systNames[CAS::SysWMbb] = "SysWMbb";
m_systNames[CAS::SysWDPhi] = "SysWDPhi";
m_systNames[CAS::SysWccDPhi] = "SysWccDPhi";
m_systNames[CAS::SysWbDPhi] = "SysWbDPhi";
m_systNames[CAS::SysZDPhi] = "SysZDPhi";
m_systNames[CAS::SysZcDPhi] = "SysZcDPhi";
m_systNames[CAS::SysZbDPhi] = "SysZbDPhi";
m_varNames[CAS::Up] = "Up";
m_varNames[CAS::Do] = "Do";
m_binNames[CAS::None] = "";
m_binNames[CAS::Any] = "";
m_binNames[CAS::Bin0] = "Bin0";
m_binNames[CAS::Bin1] = "Bin1";
m_binNames[CAS::Bin2] = "Bin2";
m_binNames[CAS::Bin3] = "Bin3";
m_binNames[CAS::Bin4] = "Bin4";
m_systFromNames = Utils::reverseMap<CAS::Systematic, std::string>(m_systNames);
m_varFromNames = Utils::reverseMap<CAS::SysVar, std::string>(m_varNames);
// resolve ambiguity
m_binFromNames = Utils::reverseMap<CAS::SysBin, std::string>(m_binNames);
m_binFromNames[""] = CAS::Any;
// V pT bins. For now 5 bins as in cut-based
pTbins[0] = 0.;
pTbins[1] = 90.e3;
pTbins[2] = 120.e3;
pTbins[3] = 160.e3;
pTbins[4] = 200.e3;
pTbins[5] = 500.e3;
/*********************************************
*
* CORRECTIONS
* These should be applied to the nominal
*
* Below the histograms which contain the
* values of the correction are created
*
*********************************************/
// signal NLO EW corrections
m_h_WHlvbbNLOEWKCorrection = new TH1F("WHlvbbpTCorr","WHlvbbpTCorr",95 ,25.e3, 500.e3);
m_h_WHlvbbNLOEWKCorrection->SetDirectory(0);
m_h_ZHllbbNLOEWKCorrection = new TH1F("ZHllbbpTCorr","ZHllbbpTCorr",95 ,25.e3, 500.e3);
m_h_ZHllbbNLOEWKCorrection->SetDirectory(0);
m_h_ZHvvbbNLOEWKCorrection = new TH1F("ZHvvbbpTCorr","ZHvvbbpTCorr",95 ,25.e3, 500.e3);
m_h_ZHvvbbNLOEWKCorrection->SetDirectory(0);
// numbers from Jason
if(m_seven) {
Float_t a_whlvbbcorr[95] = {0.00224198, -0.000370526, -0.00169178, -0.00189401, -0.00200129, -0.00301404, -0.00325795, -0.0041637, -0.00587139, -0.00739039, -0.00917371, -0.0112332, -0.0134147, -0.0152704, -0.0175308, -0.0194987, -0.021615, -0.0233439, -0.0251813, -0.0278489, -0.0296617, -0.0324331, -0.0347805, -0.0362031, -0.0376821, -0.0403375, -0.042188, -0.0439056, -0.045399, -0.0482114, -0.0505533, -0.0524687, -0.0556041, -0.0565102, -0.0585783, -0.0618502, -0.0639255, -0.0660007, -0.068076, -0.0701513, -0.0722265, -0.0743018, -0.0763771, -0.0784523, -0.0805276, -0.0826029, -0.0846781, -0.0867534, -0.0888287, -0.0909039, -0.0929792, -0.0950545, -0.0971297, -0.099205, -0.10128, -0.103356, -0.105431, -0.107506, -0.109581, -0.111657, -0.113732, -0.115807, -0.117882, -0.119958, -0.122033, -0.124108, -0.126183, -0.128259, -0.130334, -0.132409, -0.134485, -0.13656, -0.138635, -0.14071, -0.142786, -0.144861, -0.146936, -0.149011, -0.151087, -0.153162, -0.155237, -0.157312, -0.159388, -0.161463, -0.163538, -0.165614, -0.167689, -0.169764, -0.171839, -0.173915, -0.17599, -0.178065, -0.18014, -0.182216, -0.184291};
Utils::FillTH1F(95, a_whlvbbcorr, m_h_WHlvbbNLOEWKCorrection, m_allHists);
Float_t a_zhllbbcorr[95] = {0.000369691, -0.00311954, -0.00814806, -0.0101356, -0.0133924, -0.015624, -0.0188796, -0.0212749, -0.0233653, -0.0254506, -0.0270923, -0.028222, -0.0284564, -0.0287463, -0.0294866, -0.031416, -0.0304275, -0.0317627, -0.0329827, -0.0322219, -0.0339739, -0.0323855, -0.0329175, -0.0336001, -0.033455, -0.0350176, -0.0341059, -0.0383008, -0.0375261, -0.0404764, -0.0405512, -0.0410093, -0.0432318, -0.0475565, -0.0498079, -0.0470666, -0.0544329, -0.0534824, -0.055241, -0.0582209, -0.0604063, -0.0625916, -0.064777, -0.0669624, -0.0691477, -0.0713331, -0.0735185, -0.0757038, -0.0778892, -0.0800746, -0.0822599, -0.0844453, -0.0866307, -0.088816, -0.0910014, -0.0931868, -0.0953721, -0.0975575, -0.0997429, -0.101928, -0.104114, -0.106299, -0.108484, -0.11067, -0.112855, -0.11504, -0.117226, -0.119411, -0.121597, -0.123782, -0.125967, -0.128153, -0.130338, -0.132523, -0.134709, -0.136894, -0.139079, -0.141265, -0.14345, -0.145636, -0.147821, -0.150006, -0.152192, -0.154377, -0.156562, -0.158748, -0.160933, -0.163119, -0.165304, -0.167489, -0.169675, -0.17186, -0.174045, -0.176231, -0.178416};
Utils::FillTH1F(95, a_zhllbbcorr, m_h_ZHllbbNLOEWKCorrection, m_allHists);
Float_t a_zhvvbbcorr[95] = {0.0148102, 0.0137398, 0.0127929, 0.0117756, 0.011091, 0.0100978, 0.0094288, 0.0083615, 0.00791759, 0.00740715, 0.00712286, 0.00672918, 0.00662655, 0.00650805, 0.00671416, 0.00694015, 0.00738593, 0.00741676, 0.00850807, 0.00886493, 0.010138, 0.011426, 0.0122657, 0.0125201, 0.01283, 0.0127657, 0.0135671, 0.0126575, 0.0118711, 0.0115731, 0.0104059, 0.0108386, 0.00905639, 0.00774211, 0.00647519, 0.00545708, 0.00377601, 0.00251831, 0.00148805, 5.26677e-06, -0.00186611, -0.0037375, -0.00560888, -0.00748026, -0.00935164, -0.011223, -0.0130944, -0.0149658, -0.0168372, -0.0187085, -0.0205799, -0.0224513, -0.0243227, -0.0261941, -0.0280655, -0.0299368, -0.0318082, -0.0336796, -0.035551, -0.0374224, -0.0392937, -0.0411651, -0.0430365, -0.0449079, -0.0467793, -0.0486507, -0.050522, -0.0523934, -0.0542648, -0.0561362, -0.0580076, -0.0598789, -0.0617503, -0.0636217, -0.0654931, -0.0673645, -0.0692359, -0.0711072, -0.0729786, -0.07485, -0.0767214, -0.0785928, -0.0804641, -0.0823355, -0.0842069, -0.0860783, -0.0879497, -0.0898211, -0.0916924, -0.0935638, -0.0954352, -0.0973066, -0.099178, -0.101049, -0.102921};
Utils::FillTH1F(95, a_zhvvbbcorr, m_h_ZHvvbbNLOEWKCorrection, m_allHists);
}
else if(m_eight) {
Float_t a_whlvbbcorr[95] = {0.00200484, -9.13928e-05, -0.00219974, -0.00202884, -0.00219318, -0.00299564, -0.00336771, -0.00409143, -0.0059936, -0.00750034, -0.00881597, -0.0111589, -0.0135328, -0.0151878, -0.0178145, -0.0189559, -0.0215716, -0.0233429, -0.0250507, -0.0278028, -0.0291708, -0.0319617, -0.0341056, -0.0365647, -0.0381327, -0.0399857, -0.0405974, -0.0444237, -0.0454833, -0.0482596, -0.0486239, -0.0534461, -0.0539187, -0.0559509, -0.0596689, -0.0610085, -0.0633554, -0.0639406, -0.0672306, -0.0699078, -0.0719664, -0.0740249, -0.0760835, -0.078142, -0.0802005, -0.0822591, -0.0843176, -0.0863761, -0.0884347, -0.0904932, -0.0925517, -0.0946103, -0.0966688, -0.0987273, -0.100786, -0.102844, -0.104903, -0.106961, -0.10902, -0.111079, -0.113137, -0.115196, -0.117254, -0.119313, -0.121371, -0.12343, -0.125488, -0.127547, -0.129605, -0.131664, -0.133722, -0.135781, -0.13784, -0.139898, -0.141957, -0.144015, -0.146074, -0.148132, -0.150191, -0.152249, -0.154308, -0.156366, -0.158425, -0.160483, -0.162542, -0.1646, -0.166659, -0.168718, -0.170776, -0.172835, -0.174893, -0.176952, -0.17901, -0.181069, -0.183127};
Utils::FillTH1F(95, a_whlvbbcorr, m_h_WHlvbbNLOEWKCorrection, m_allHists);
Float_t a_zhllbbcorr[95] = {0.000664024, -0.00357095, -0.00767076, -0.00967366, -0.0134844, -0.0157148, -0.0181885, -0.0209647, -0.0232788, -0.0252373, -0.0265634, -0.0275069, -0.0285776, -0.0281683, -0.0294206, -0.0299975, -0.0308047, -0.0311716, -0.030913, -0.0324821, -0.0323192, -0.0324639, -0.0319356, -0.0322621, -0.0331146, -0.0338905, -0.0345189, -0.0358591, -0.0358407, -0.040018, -0.0396389, -0.0407177, -0.0445103, -0.0441406, -0.0471215, -0.0463301, -0.0513777, -0.0536773, -0.0546446, -0.0568508, -0.0590333, -0.0612157, -0.0633981, -0.0655805, -0.067763, -0.0699454, -0.0721278, -0.0743103, -0.0764927, -0.0786751, -0.0808575, -0.08304, -0.0852224, -0.0874048, -0.0895872, -0.0917697, -0.0939521, -0.0961345, -0.098317, -0.100499, -0.102682, -0.104864, -0.107047, -0.109229, -0.111412, -0.113594, -0.115776, -0.117959, -0.120141, -0.122324, -0.124506, -0.126689, -0.128871, -0.131053, -0.133236, -0.135418, -0.137601, -0.139783, -0.141965, -0.144148, -0.14633, -0.148513, -0.150695, -0.152878, -0.15506, -0.157242, -0.159425, -0.161607, -0.16379, -0.165972, -0.168155, -0.170337, -0.172519, -0.174702, -0.176884};
Utils::FillTH1F(95, a_zhllbbcorr, m_h_ZHllbbNLOEWKCorrection, m_allHists);
Float_t a_zhvvbbcorr[95] = {0.0146846, 0.0136521, 0.0125801, 0.0117771, 0.010976, 0.00989665, 0.00929942, 0.00836484, 0.00781992, 0.00733247, 0.00688885, 0.00666833, 0.0063354, 0.00637412, 0.00662595, 0.0069015, 0.00716689, 0.00760953, 0.00823267, 0.00914484, 0.00960494, 0.0110894, 0.0122241, 0.0127155, 0.0126892, 0.0125873, 0.01278, 0.0128243, 0.0118519, 0.0116125, 0.0102697, 0.00960959, 0.00929141, 0.00807739, 0.00588976, 0.00522135, 0.00365527, 0.00214147, 0.000569382, 0.000322672, -0.0015679, -0.00345846, -0.00534903, -0.0072396, -0.00913017, -0.0110207, -0.0129113, -0.0148019, -0.0166924, -0.018583, -0.0204736, -0.0223641, -0.0242547, -0.0261453, -0.0280358, -0.0299264, -0.031817, -0.0337076, -0.0355981, -0.0374887, -0.0393793, -0.0412698, -0.0431604, -0.045051, -0.0469415, -0.0488321, -0.0507227, -0.0526132, -0.0545038, -0.0563944, -0.0582849, -0.0601755, -0.0620661, -0.0639566, -0.0658472, -0.0677378, -0.0696283, -0.0715189, -0.0734095, -0.0753001, -0.0771906, -0.0790812, -0.0809718, -0.0828623, -0.0847529, -0.0866435, -0.088534, -0.0904246, -0.0923152, -0.0942057, -0.0960963, -0.0979869, -0.0998774, -0.101768, -0.103659};
Utils::FillTH1F(95, a_zhvvbbcorr, m_h_ZHvvbbNLOEWKCorrection, m_allHists);
}
// W, Z and top backgrounds pT corrections
m_h_WpTCorrection = new TH1F("WpTCorr","WpTCorr",5 ,pTbins);
m_h_WpTCorrection->SetDirectory(0);
m_h_ZpTCorrection = new TH1F("ZpTCorr","ZpTCorr",5 ,pTbins);
m_h_ZpTCorrection->SetDirectory(0);
Float_t a_wcorr[5] = {0.02, 0.00, 0.01, -0.01, -0.05};
Utils::FillTH1F(5, a_wcorr, m_h_WpTCorrection, m_allHists);
Float_t a_zcorr[5] = {0.00, -0.01, 0.00, 0.00, -0.03};
Utils::FillTH1F(5, a_zcorr, m_h_ZpTCorrection, m_allHists);
// W, backgrounds DeltaPhi corrections
m_h_WDeltaPhiCorrection2Jet = new TH1F("WDeltaPhiCorr2Jet","WDeltaPhiCorr2Jet", 16, 0, 3.2);
m_h_WDeltaPhiCorrection2Jet->SetDirectory(0);
m_h_WDeltaPhiCorrection3Jet = new TH1F("WDeltaPhiCorr3Jet","WDeltaPhiCorr3Jet", 16, 0, 3.2);
m_h_WDeltaPhiCorrection3Jet->SetDirectory(0);
// numbers from Garabed. 26/05/2013
Float_t a_wlcorr2Jet[16] = { -0.15044, -0.137197, -0.105746, -0.112105, -0.097855,
-0.096983, -0.064647, -0.041897, -0.02896, -0.026313, 0.01495, 0.03721, 0.05588, 0.07741,
0.0809799, 0.06379 };
Utils::FillTH1F(16, a_wlcorr2Jet, m_h_WDeltaPhiCorrection2Jet, m_allHists);
Float_t a_wlcorr3Jet[16] = { -0.092645, -0.093605, -0.074694, -0.055558, -0.045499,
-0.055228, -0.059025, -0.026597, -0.024518, -0.00629598, 0.01531, 0.04161, 0.04169, 0.02874,
0.03457, 0.0127701 };
Utils::FillTH1F(16, a_wlcorr3Jet, m_h_WDeltaPhiCorrection3Jet, m_allHists);
// parameterized line for 2 and 3 Jets
m_f_WDPhiCorr = new TF1("f_WDPhiCorr","([0] + [1] * x) * (x<=2.52) + ([2] + [3]*x + [4]*x*x) * (x>2.52) - 1", 0, 3.2);
m_f_WDPhiCorr->SetParameter(0, 0.820954);
m_f_WDPhiCorr->SetParameter(1, 0.0965);
m_f_WDPhiCorr->SetParameter(2, -0.130413);
m_f_WDPhiCorr->SetParameter(3, +0.849834);
m_f_WDPhiCorr->SetParameter(4, -0.149133);
Utils::SaveHist(m_f_WDPhiCorr, m_allHists);
// Z, backgrounds DeltaPhi corrections
m_h_ZDeltaPhiCorrection = new TH1F("ZDeltaPhiCorr","ZDeltaPhiCorr", 16, 0, 3.2);
m_h_ZDeltaPhiCorrection->SetDirectory(0);
// numbers from Kevin. 12/04/2013
Float_t a_zlcorr[16] = { -0.0800548, -0.0816269, -0.0432947, -0.0479725, -0.0516307,
-0.0438293, -0.0204907, 0.00574154, 0.0169727, 0.057972, 0.0232869, 0.0621223, 0.0584892,
0.0631624, 0.0652384, 0.0596382 };
Utils::FillTH1F(16, a_zlcorr, m_h_ZDeltaPhiCorrection, m_allHists);
// parameterized line for 2 and 3 Jets
// f(dphi) = (Norm*0.9189 + 0.0675*dPhi)
m_f_ZDPhiCorr = new TF1("f_ZDPhiCorr","[0] + [1] * x - 1", 0, 3.2);
m_f_ZDPhiCorr->SetParameter(0, 0.880);
m_f_ZDPhiCorr->SetParameter(1, 0.0675);
Utils::SaveHist(m_f_ZDPhiCorr, m_allHists);
// top pT correction. Yuji 18/05/13
// From https://cds.cern.ch/record/1470588/ Figure 46
// update on 27/05/13 for error to be 50% of the correction
Float_t topPtCorr[7] = { 0.05128, 0.0288, -0.000898004, -0.024253, -0.08489, -0.170377, -0.247117 };
Float_t topPtCorrBins[8] = { 0, 50.e3, 100.e3, 150.e3, 200.e3, 250.e3, 350.e3, 800.e3 };
/*
float normTopPt = 100000./99833.4;
for( int i=0; i<7; i++) {
topPtCorr[i] *= normTopPt;
}
*/
m_h_topPtCorrection = new TH1F("topPtCorrection", "topPtCorrection", 7, topPtCorrBins);
m_h_topPtCorrection->SetDirectory(0);
Utils::FillTH1F( 7, topPtCorr, m_h_topPtCorrection, m_allHists );
/*********************************************
*
* SYSTEMATICS
* These should be applied to the nominal
*
* Below the histograms which contain the
* values of the correction are created
*
*********************************************/
m_h_SysTheoryWHlvbbPt = new TH1F("SysTheoryWHlvbbPt", "SysTheoryWHlvbbPt", 95, 25.e3, 500.e3);
m_h_SysTheoryWHlvbbPt->SetDirectory(0);
m_h_SysTheoryZHllbbPt = new TH1F("SysTheoryZHllbbPt", "SysTheoryZHllbbPt", 95, 25.e3, 500.e3);
m_h_SysTheoryZHllbbPt->SetDirectory(0);
m_h_SysTheoryZHvvbbPt = new TH1F("SysTheoryZHvvbbPt", "SysTheoryZHvvbbPt", 95, 25.e3, 500.e3);
m_h_SysTheoryZHvvbbPt->SetDirectory(0);
if(m_seven) {
Float_t hw7_errors[95] = {0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.0201801, 0.0207736, 0.0213758, 0.0219865, 0.0226059, 0.0232338, 0.0238704, 0.0245155, 0.0251693, 0.0258317, 0.0265027, 0.0271822, 0.0278704, 0.0285672, 0.0292726, 0.0299866, 0.0307092, 0.0314403, 0.0321801, 0.0329285, 0.0336855, 0.0344511, 0.0352254, 0.0360082, 0.0367996, 0.0375996, 0.0384082, 0.0392254, 0.0400513, 0.0408857, 0.0417287, 0.0425803, 0.0434406, 0.0443094, 0.0451869, 0.0460729, 0.0469675, 0.0478708, 0.0487827, 0.0497031, 0.0506322, 0.0515698, 0.0525161, 0.053471, 0.0544344, 0.0554065, 0.0563872, 0.0573764, 0.0583743, 0.0593808, 0.0603959, 0.0614196, 0.0624519, 0.0634928, 0.0645423, 0.0656004};
Utils::FillTH1F(95, hw7_errors, m_h_SysTheoryWHlvbbPt, m_allHists);
Float_t hll7_errors[95] = {0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.0203477, 0.0209749, 0.0216116, 0.0222579, 0.0229137, 0.023579, 0.0242538, 0.0249381, 0.025632, 0.0263354, 0.0270483, 0.0277707, 0.0285026, 0.0292441, 0.0299951, 0.0307556, 0.0315256, 0.0323051, 0.0330942, 0.0338928, 0.0347009, 0.0355185, 0.0363457, 0.0371823, 0.0380285, 0.0388842, 0.0397495, 0.0406242, 0.0415085, 0.0424023, 0.0433056, 0.0442184, 0.0451408, 0.0460727, 0.0470141, 0.047965, 0.0489254, 0.0498954, 0.0508749, 0.0518639, 0.0528624, 0.0538704};
Utils::FillTH1F(95, hll7_errors, m_h_SysTheoryZHllbbPt, m_allHists);
Float_t hnn7_errors[95] = {0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.0202857, 0.0208312, 0.0213839, 0.0219438, 0.022511, 0.0230854, 0.023667, 0.0242559, 0.024852};
Utils::FillTH1F(95, hnn7_errors, m_h_SysTheoryZHvvbbPt, m_allHists);
}
else if(m_eight) {
Float_t hw8_errors[95] = {0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.0201193, 0.0207066, 0.0213024, 0.0219067, 0.0225194, 0.0231405, 0.0237701, 0.0244082, 0.0250547, 0.0257096, 0.026373, 0.0270449, 0.0277252, 0.0284139, 0.0291111, 0.0298168, 0.0305309, 0.0312534, 0.0319844, 0.0327239, 0.0334718, 0.0342281, 0.0349929, 0.0357662, 0.0365479, 0.037338, 0.0381367, 0.0389437, 0.0397592, 0.0405832, 0.0414156, 0.0422564, 0.0431057, 0.0439635, 0.0448297, 0.0457044, 0.0465875, 0.047479, 0.048379, 0.0492875, 0.0502044, 0.0511298, 0.0520636, 0.0530058, 0.0539565, 0.0549157, 0.0558833, 0.0568594, 0.0578439, 0.0588369, 0.0598383, 0.0608481, 0.0618664, 0.0628932, 0.0639284, 0.0649721};
Utils::FillTH1F(95, hw8_errors, m_h_SysTheoryWHlvbbPt, m_allHists);
Float_t hll8_errors[95] = {0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.0205646, 0.0211945, 0.021834, 0.022483, 0.0231415, 0.0238095, 0.024487, 0.025174, 0.0258705, 0.0265765, 0.027292, 0.028017, 0.0287516, 0.0294956, 0.0302491, 0.0310122, 0.0317847, 0.0325667, 0.0333583, 0.0341594, 0.0349699, 0.03579, 0.0366195, 0.0374586, 0.0383072, 0.0391653, 0.0400329, 0.0409099, 0.0417965, 0.0426926, 0.0435982, 0.0445134, 0.045438, 0.0463721, 0.0473157, 0.0482688, 0.0492315, 0.0502036, 0.0511852, 0.0521764, 0.053177};
Utils::FillTH1F(95, hll8_errors, m_h_SysTheoryZHllbbPt, m_allHists);
Float_t hnn8_errors[95] = {0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.0202975, 0.0208415, 0.0213928, 0.0219513, 0.0225169, 0.0230898, 0.0236698, 0.0242571, 0.0248515};
Utils::FillTH1F(95, hnn8_errors, m_h_SysTheoryZHvvbbPt, m_allHists);
}
m_h_SysStopPt = new TH1F("SysStopPt", "SysStopPt", 5, pTbins);
m_h_SysStopPt->SetDirectory(0);
m_h_SysWbbPtW = new TH1F("SysWbbPtW", "SysWbbPtW", 5, pTbins);
m_h_SysWbbPtW->SetDirectory(0);
m_h_SysWccPtW = new TH1F("SysWccPtW", "SysWccPtW", 5, pTbins);
m_h_SysWccPtW->SetDirectory(0);
m_h_SysWllPtW = new TH1F("SysWllPtW", "SysWllPtW", 5, pTbins);
m_h_SysWllPtW->SetDirectory(0);
m_h_SysZbbPtZ = new TH1F("SysZbbPtZ", "SysZbbPtZ", 5, pTbins);
m_h_SysZbbPtZ->SetDirectory(0);
m_h_SysZccPtZ = new TH1F("SysZccPtZ", "SysZccPtZ", 5, pTbins);
m_h_SysZccPtZ->SetDirectory(0);
m_h_SysZllPtZ = new TH1F("SysZllPtZ", "SysZllPtZ", 5, pTbins);
m_h_SysZllPtZ->SetDirectory(0);
Float_t a_SysStopPt[5] = { 0.02, 0.00, 0.01, -0.01, -0.05};
Utils::FillTH1F(5, a_SysStopPt, m_h_SysStopPt, m_allHists);
Float_t a_SysWbbPtW[5] = { 0.02, 0.00, 0.01, -0.01, -0.05}; // same as stop
Utils::FillTH1F(5, a_SysWbbPtW, m_h_SysWbbPtW, m_allHists);
Float_t a_SysWccPtW[5] = { 0.02, 0.00, 0.01, -0.01, -0.05}; // same as stop
Utils::FillTH1F(5, a_SysWccPtW, m_h_SysWccPtW, m_allHists);
Float_t a_SysWllPtW[5] = { 0.02, 0.00, 0.01, -0.01, -0.05}; // same as stop
Utils::FillTH1F(5, a_SysWllPtW, m_h_SysWllPtW, m_allHists);
Float_t a_SysZbbPtW[5] = { 0.00, -0.01, 0.00, 0.00, -0.03};
Utils::FillTH1F(5, a_SysZbbPtW, m_h_SysZbbPtZ, m_allHists);
Float_t a_SysZccPtW[5] = { 0.00, -0.01, 0.00, 0.00, -0.03}; // same as Zbb
Utils::FillTH1F(5, a_SysZccPtW, m_h_SysZccPtZ, m_allHists);
Float_t a_SysZllPtW[5] = { 0.00, -0.01, 0.00, 0.00, -0.03}; // same as Zbb
Utils::FillTH1F(5, a_SysZllPtW, m_h_SysZllPtZ, m_allHists);
// Continuus systematics
m_f_SysZbbMbb = new TF1("f_SysZbbMbb","[0] * (x/1.e3 - [1])", 0, pTbins[5]);
m_f_SysZbbMbb->SetParameter(0, 0.001);
m_f_SysZbbMbb->SetParameter(1, 100.);
m_f_SysWbbMbb = new TF1("f_SysWbbMbb","[0] + [1] * x/1.e3", 0, pTbins[5]);
m_f_SysWbbMbb->SetParameter(0, 0.19);
m_f_SysWbbMbb->SetParameter(1, -0.0017);
m_f_SysTopMbb = new TF1("f_SysTopMbb","[0] + [1] * x/1.e3", 0, pTbins[5]);
m_f_SysTopMbb->SetParameter(0, 0.05);
m_f_SysTopMbb->SetParameter(1, -3.4e-4);
m_f_SysStopMbb = new TF1("f_SysStopMbb","[0] + [1] * x/1.e3", 0, pTbins[5]);
m_f_SysStopMbb->SetParameter(0, 0.19); // same as Wbb
m_f_SysStopMbb->SetParameter(1, -0.0017);
m_f_SysWMbb = new TF1("f_SysWMbb","[0] + [1] * TMath::Log(x) + [2] * pow(TMath::Log(x), 2)", 0, pTbins[5]);
m_f_SysWMbb->SetParameter(0, -2.3);
m_f_SysWMbb->SetParameter(1, 3.1e-01);
m_f_SysWMbb->SetParameter(2, -9.7e-03);
m_f_SysZMbb = new TF1("f_SysZMbb","[0] * (x/1.e3 - [1])", 0, pTbins[5]);
m_f_SysZMbb->SetParameter(0, 0.001); // same as Zbb
m_f_SysZMbb->SetParameter(1, 100.);
Utils::SaveHist(m_f_SysZbbMbb, m_allHists);
Utils::SaveHist(m_f_SysWbbMbb, m_allHists);
Utils::SaveHist(m_f_SysTopMbb, m_allHists);
Utils::SaveHist(m_f_SysStopMbb, m_allHists);
Utils::SaveHist(m_f_SysWMbb, m_allHists);
Utils::SaveHist(m_f_SysZMbb, m_allHists);
if(m_draw) {
TString fname("CorrsAndSysts_");
if(m_zero) { fname.Append("Zero"); }
if(m_one) { fname.Append("One"); }
if(m_two) { fname.Append("Two"); }
fname.Append("Lep_");
if(m_seven) { fname.Append("7"); }
if(m_eight) { fname.Append("8"); }
fname.Append("TeV.root");
WriteHistsToFile(fname);
}
} // Initialize
CAS::EventType CorrsAndSysts::GetEventType(TString name) {
if( m_typeNames.find(name.Data()) == m_typeNames.end() ) {
std::cout << "CorrsAndSysts::ERROR - unknown event type " << name << std::endl;
exit(-1);
}
return m_typeNames[name.Data()];
} // GetEventType
CAS::SysBin CorrsAndSysts::GetSysBin(float vpt) {
if(vpt < pTbins[0]) {
std::cout << "CorrsAndSysts::ERROR - V pT " << vpt << " is smaller than lowest bin boundary " << pTbins[0] << std::endl;
}
if(vpt < pTbins[1]) { return CAS::Bin0; }
if(vpt < pTbins[2]) { return CAS::Bin1; }
if(vpt < pTbins[3]) { return CAS::Bin2; }
if(vpt < pTbins[4]) { return CAS::Bin3; }
return CAS::Bin4;
} // GetSysBin
/*********************************************
*
* CORRECTIONS continued - functions below
*
*********************************************/
float CorrsAndSysts::Get_HiggsNLOEWKCorrection(CAS::EventType type, float VpT) {
float scale=0;
switch(type) {
case CAS::WHlvbb:
scale = Utils::GetScale(VpT, m_h_WHlvbbNLOEWKCorrection);
break;
case CAS::ZHllbb:
scale = Utils::GetScale(VpT, m_h_ZHllbbNLOEWKCorrection);
break;
case CAS::ZHvvbb:
scale = Utils::GetScale(VpT, m_h_ZHvvbbNLOEWKCorrection);
break;
default:
scale=0;
break;
}
return 1+scale;
}
float CorrsAndSysts::Get_BkgpTCorrection(CAS::EventType type, float VpT) {
std::cout << "CorrsAndSysts::WARNING - Get_BkgpTCorrection deprecated!" << std::endl;
return 1;
float scale=0;
switch(type) {
case CAS::Wl: case CAS::Wb: case CAS::Wc: case CAS::Wcc: case CAS::stop:
scale = Utils::GetScale(VpT, m_h_WpTCorrection);
break;
case CAS::Zb: case CAS::Zc: case CAS::Zl:
scale = Utils::GetScale(VpT, m_h_ZpTCorrection);
break;
default:
scale=0;
break;
}
return 1+scale;
}
float CorrsAndSysts::Get_ToppTCorrection(CAS::EventType type, float avgTopPt) {
if (type != CAS::ttbar) { return 1; }
float scale = Utils::GetScale(avgTopPt, m_h_topPtCorrection);
return 1+scale;
}
float CorrsAndSysts::Get_BkgDeltaPhiCorrection(CAS::EventType type, float DeltaPhi, int njet) {
DeltaPhi = fabs(TVector2::Phi_mpi_pi(DeltaPhi));
float scale=0;
switch(type) {
case CAS::Wl:
case CAS::Wc:
case CAS::Wcc:
case CAS::Wb:
/*
if(njet == 2) {
scale = Utils::GetScale(DeltaPhi, m_h_WDeltaPhiCorrection2Jet);
} else {
scale = Utils::GetScale(DeltaPhi, m_h_WDeltaPhiCorrection3Jet);
}
*/
scale = m_f_WDPhiCorr->Eval(DeltaPhi);
break;
case CAS::Zl:
case CAS::Zc:
case CAS::Zb:
//scale = Utils::GetScale(DeltaPhi, m_h_ZDeltaPhiCorrection);
scale = m_f_ZDPhiCorr->Eval(DeltaPhi);
break;
default:
scale=0;
break;
}
return 1+scale;
}
/*********************************************
*
* SYSTEMATICS continued - functions below
*
*********************************************/
float CorrsAndSysts::Get_SystematicWeight(CAS::EventType type, float VpT, float Mbb, float avgTopPt, float DeltaPhi, int njet,
CAS::Systematic sys, CAS::SysVar var, CAS::SysBin bin) {
DeltaPhi = fabs(TVector2::Phi_mpi_pi(DeltaPhi));
// no systematics
if(sys == CAS::Nominal)
return 1;
if(sys == CAS::PTBINNED || sys == CAS::CONTINUOUS) {
std::cout << "CorrsAndSysts::ERROR Using a systematic enum which should not be used" << std::endl;
exit(-1);
}
if(bin == CAS::None) {
std::cout << "CorrsAndSysts: no indication of type of binning given for systematics ! Exiting..." << std::endl;
exit(-1);
}
// sanity check: binned / continuous systematics
if(sys < CAS::CONTINUOUS && bin == CAS::Any) {
std::cout << "CorrsAndSysts: asked no binning for a systematic which is binned ! Exiting..." << std::endl;
exit(-1);
}
if(sys >= CAS::CONTINUOUS && sys < CAS::LAST && bin != CAS::Any) {
std::cout << "CorrsAndSysts: asked specific bin for a systematic which is not binned ! Exiting..." << std::endl;
exit(-1);
}
// for binned systematics, check if the pT bin matches. else return 1
if(sys > CAS::PTBINNED && sys < CAS::CONTINUOUS) {
int ptbin = m_h_WpTCorrection->FindBin(VpT) - 1;
if(ptbin != bin)
return 1;
}
float scale = 0;
int sgn = 2*var-1;
float unc_scale = 0.5;
switch(sys) {
case CAS::SysTheoryHPt:
switch(type) {
case CAS::WHlvbb:
scale = Utils::GetScale(VpT, m_h_SysTheoryWHlvbbPt);
break;
case CAS::ZHllbb:
scale = Utils::GetScale(VpT, m_h_SysTheoryZHllbbPt);
break;
case CAS::ZHvvbb:
scale = Utils::GetScale(VpT, m_h_SysTheoryZHvvbbPt);
break;
default:
return 1;
}
break;
case CAS::SysTopPt:
if(type != CAS::ttbar) { return 1; }
scale = Utils::GetScale(avgTopPt, m_h_topPtCorrection);
scale = .5*scale/(1+scale); // DO is 50% of correction, UP is 150%
break;
case CAS::SysStopPt:
return 1;
if(type != CAS::stop)
return 1;
scale = unc_scale * m_h_SysStopPt->GetBinContent(bin+1);
break;
case CAS::SysWbbPtW:
std::cout << "CorrsAndSysts::WARNING - requested systematic deprecated!" << std::endl;
return 1;
if(type != CAS::Wb)
return 1;
scale = unc_scale * m_h_SysWbbPtW->GetBinContent(bin+1);
break;
case CAS::SysWccPtW:
std::cout << "CorrsAndSysts::WARNING - requested systematic deprecated!" << std::endl;
return 1;
if(type != CAS::Wc && type != CAS::Wcc)
return 1;
scale = unc_scale * m_h_SysWccPtW->GetBinContent(bin+1);
break;
case CAS::SysZbbPtZ:
std::cout << "CorrsAndSysts::WARNING - requested systematic deprecated!" << std::endl;
return 1;
if(type != CAS::Zb)
return 1;
scale = unc_scale * m_h_SysZbbPtZ->GetBinContent(bin+1);
break;
case CAS::SysZccPtZ:
std::cout << "CorrsAndSysts::WARNING - requested systematic deprecated!" << std::endl;
return 1;
if(type != CAS::Zc)
return 1;
scale = unc_scale * m_h_SysZccPtZ->GetBinContent(bin+1);
break;
case CAS::SysWllPtW:
std::cout << "CorrsAndSysts::WARNING - requested systematic deprecated!" << std::endl;
return 1;
if(type != CAS::Wl)
return 1;
scale = unc_scale * m_h_SysWllPtW->GetBinContent(bin+1);
break;
case CAS::SysZllPtZ:
std::cout << "CorrsAndSysts::WARNING - requested systematic deprecated!" << std::endl;
return 1;
if(type != CAS::Zl)
return 1;
scale = unc_scale * m_h_SysZllPtZ->GetBinContent(bin+1);
break;
// now continuus systematics
case CAS::SysZbbMbb:
if(type != CAS::Zb)
return 1;
scale = m_f_SysZbbMbb->Eval(Mbb);
break;
case CAS::SysWbbMbb:
if(type != CAS::Wb && type != CAS::Wcc)
return 1;
scale = m_f_SysWbbMbb->Eval(Mbb);
break;
case CAS::SysWMbb:
if(type != CAS::Wl && type != CAS::Wc)
return 1;
scale = m_f_SysWMbb->Eval(Mbb);
break;
case CAS::SysTopMbb:
if(type != CAS::ttbar)
return 1;
scale = m_f_SysTopMbb->Eval(Mbb);
break;
case CAS::SysStopMbb:
if(type != CAS::stop)
return 1;
scale = m_f_SysStopMbb->Eval(Mbb);
break;
case CAS::SysZMbb:
if(type != CAS::Zl && type != CAS::Zc)
return 1;
scale = m_f_SysZMbb->Eval(Mbb);
break;
case CAS::SysWDPhi:
if(type != CAS::Wl && type !=CAS::Wc)
return 1;
/*
if(njet == 2) {
scale = Utils::GetScale(DeltaPhi, m_h_WDeltaPhiCorrection2Jet);
} else {
scale = Utils::GetScale(DeltaPhi, m_h_WDeltaPhiCorrection3Jet);
}
*/
scale = m_f_WDPhiCorr->Eval(DeltaPhi);
scale = .5*scale/(1+scale); // DO is 50% of correction, UP is 150%
break;
case CAS::SysWccDPhi:
if(type != CAS::Wcc)
return 1;
/*
if(njet == 2) {
scale = Utils::GetScale(DeltaPhi, m_h_WDeltaPhiCorrection2Jet);
} else {
scale = Utils::GetScale(DeltaPhi, m_h_WDeltaPhiCorrection3Jet);
}
*/
scale = m_f_WDPhiCorr->Eval(DeltaPhi);
scale = .5*scale/(1+scale); // DO is 50% of correction, UP is 150%
break;
case CAS::SysWbDPhi:
if(type != CAS::Wb)
return 1;
/*
if(njet == 2) {
scale = Utils::GetScale(DeltaPhi, m_h_WDeltaPhiCorrection2Jet);
} else {
scale = Utils::GetScale(DeltaPhi, m_h_WDeltaPhiCorrection3Jet);
}
*/
scale = m_f_WDPhiCorr->Eval(DeltaPhi);
scale = .5*scale/(1+scale); // DO is 50% of correction, UP is 150%
break;
case CAS::SysZDPhi:
if(type != CAS::Zl)
return 1;
//scale = Utils::GetScale(DeltaPhi, m_h_ZDeltaPhiCorrection);
scale = m_f_ZDPhiCorr->Eval(DeltaPhi);
scale = .5*scale/(1+scale); // DO is 50% of correction, UP is 150%
break;
case CAS::SysZcDPhi:
if(type != CAS::Zc)
return 1;
//scale = Utils::GetScale(DeltaPhi, m_h_ZDeltaPhiCorrection);
scale = m_f_ZDPhiCorr->Eval(DeltaPhi);
scale = .5*scale/(1+scale); // DO is 50% of correction, UP is 150%
break;
case CAS::SysZbDPhi:
if(type != CAS::Zb)
return 1;
//scale = Utils::GetScale(DeltaPhi, m_h_ZDeltaPhiCorrection);
scale = m_f_ZDPhiCorr->Eval(DeltaPhi);
scale = .5*scale/(1+scale); // DO is 50% of correction, UP is 150%
break;
default:
return 1;
break;
}
// generic case: symmetric uncertainties
scale*=sgn;
return 1+scale;
} // Get_SystematicWeight
// if using this function
// need to have Up or Do as the last two characters of the syst name
// the string Bin in the name if necessary
float CorrsAndSysts::Get_SystematicWeight(CAS::EventType type, float VpT, float Mbb, float avgTopPt, float DeltaPhi, int njet, TString sysName) {
CAS::Systematic sys;
CAS::SysBin bin;
CAS::SysVar var;
GetSystFromName(sysName, sys, bin, var);
return Get_SystematicWeight(type, VpT, Mbb, avgTopPt, DeltaPhi, njet, sys, var, bin);
}
// if using this function
// need to have Up or Do as the last two characters of the syst name
// the string Bin in the name if necessary
void CorrsAndSysts::GetSystFromName(TString name, CAS::Systematic& sys, CAS::SysBin& bin, CAS::SysVar& var) {
var = m_varFromNames[name(name.Length()-2, 2).Data()];
name.Remove(name.Length()-2);
if(name.Contains("Bin")) {
bin = m_binFromNames[name(name.Length()-4, 4).Data()];
name.Remove(name.Length()-4);
}
else {
bin = CAS::Any;
}
sys = m_systFromNames[name.Data()];
}
void CorrsAndSysts::WriteHistsToFile(TString fname) {
TFile *file = new TFile(fname,"RECREATE");
for(std::map<TString,TObject*>::iterator hists=m_allHists.begin(); hists!=m_allHists.end(); hists++) {
hists->second->Write();
}
file->Close();
delete file;
} // WriteHistsToFile
/*
*
* UTILITY FUNCTIONS
*
*/
namespace Utils {
TH1F* BuildTH1F(std::vector<Double_t> contents, TString hname, float min, float max, std::map<TString, TObject*>& hists) {
TH1F* tmp = new TH1F(hname,hname,contents.size(),min,max);
for(unsigned int i = 1; i<contents.size()+1; i++) {
tmp->SetBinContent(i, contents[i-1]);
}
if(tmp->GetBinContent( tmp->GetNbinsX()+1 ) == 0) {
tmp->SetBinContent( tmp->GetNbinsX()+1, tmp->GetBinContent( tmp->GetNbinsX() ) );
}
SaveHist(tmp,hists);
return tmp;
}
void FillTH1F(std::vector<Float_t> contents, TH1F* h, std::map<TString, TObject*>& hists) {
if( contents.size() != static_cast<unsigned int>(h->GetNbinsX()) ){
std::cout << "CorrsAndSysts: filling the histogram " << h->GetName() << " with a wrong number of bins" << std::endl;
exit(-1);
}
for(int i=0; i<h->GetNbinsX(); i++) {
h->SetBinContent(i+1, contents[i]);
}
if(h->GetBinContent( h->GetNbinsX()+1 ) == 0) {
h->SetBinContent( h->GetNbinsX()+1, h->GetBinContent( h->GetNbinsX() ) );
}
SaveHist(h,hists);
}
void FillTH1F(int len, Float_t* contents, TH1F* h, std::map<TString, TObject*>& hists) {
if( len != h->GetNbinsX() ){
std::cout << "CorrsAndSysts: filling the histogram " << h->GetName() << " with a wrong number of bins" << std::endl;
exit(-1);
}
for(int i=0; i<h->GetNbinsX(); i++) {
h->SetBinContent(i+1, contents[i]);
}
if(h->GetBinContent( h->GetNbinsX()+1 ) == 0) {
h->SetBinContent( h->GetNbinsX()+1, h->GetBinContent( h->GetNbinsX() ) );
}
SaveHist(h,hists);
}
void SaveHist(TObject* h, std::map<TString, TObject*>& hists) {
if(hists.find(h->GetName()) != hists.end()) {
std::cout << "CorrsAndSysts::ERROR - non-unique name of histogram/function is being used - please correct" << std::endl;
exit(-1);
}
hists[h->GetName()] = h;
} //SaveHist
inline float GetScale(float value, TH1F* h) {
return h->GetBinContent( h->FindBin(value) );
}
}
// Systematics on distributions
// float Get_SystematicWeight(CAS::EventType type, float VpT, float Mbb, float avgTopPt, float DeltaPhi, int njet, CAS::Systematic sys=CAS::Nominal, CAS::SysVar var=CAS::Up, CAS::SysBin bin=CAS::None);
// float Get_SystematicWeight(CAS::EventType type, float VpT, float Mbb, float avgTopPt, float DeltaPhi, int njet, TString sysName);
/*
inline float Get_SystematicWeight(TString evtType, float VpT, float Mbb, float avgTopPt, float DeltaPhi, int njet, CAS::Systematic sys, CAS::SysVar var, CAS::SysBin bin)
{ return Get_SystematicWeight(m_typeNames[evtType.Data()], VpT, Mbb, avgTopPt, DeltaPhi, njet, sys, var, bin); }
inline float Get_SystematicWeight(TString evtType, float VpT, float Mbb, float avgTopPt, float DeltaPhi, int njet, TString sysName)
{ return Get_SystematicWeight(m_typeNames[evtType.Data()], VpT, Mbb, avgTopPt, DeltaPhi, njet, sysName); }
*/
//void (Utils::*FillTH1Fx1)(std::vector<Float_t>, ROOT::TH1F*, std::map<TString, ROOT::TObject*>&) = &Utils::FillTH1F;
//void (Utils::*FillTH1Fx2)(int, Float_t*, ROOT::TH1F*, std::map<TString, ROOT::TObject*>&) = &Utils::FillTH1F;
float (CorrsAndSysts::*Get_HiggsNLOEWKCorrectionx1)(CAS::EventType, float) = &CorrsAndSysts::Get_HiggsNLOEWKCorrection;
float (CorrsAndSysts::*Get_HiggsNLOEWKCorrectionx2)(TString, float) = &CorrsAndSysts::Get_HiggsNLOEWKCorrection; //inline
float (CorrsAndSysts::*Get_BkgpTCorrectionx1)(CAS::EventType, float) = &CorrsAndSysts::Get_BkgpTCorrection;
float (CorrsAndSysts::*Get_BkgpTCorrectionx2)(TString, float) = &CorrsAndSysts::Get_BkgpTCorrection;//inline
float (CorrsAndSysts::*Get_ToppTCorrectionx1)(CAS::EventType, float) = &CorrsAndSysts::Get_ToppTCorrection;
float (CorrsAndSysts::*Get_ToppTCorrectionx2)(TString, float) = &CorrsAndSysts::Get_ToppTCorrection;//inline
float (CorrsAndSysts::*Get_BkgDeltaPhiCorrectionx1)(CAS::EventType, float, int) = &CorrsAndSysts::Get_BkgDeltaPhiCorrection;
float (CorrsAndSysts::*Get_BkgDeltaPhiCorrectionx2)(TString, float, int) = &CorrsAndSysts::Get_BkgDeltaPhiCorrection;//inline
//float (CorrsAndSysts::*Get_SystematicWeightx1)(CAS::EventType, float, float, float, float, int, CAS::Systematic, CAS::SysVar, CAS::SysBin) = &CorrsAndSysts::Get_SystematicWeight; // default values need to be included!
float (CorrsAndSysts::*Get_SystematicWeightx2)(CAS::EventType, float, float, float, float, int, TString) = &CorrsAndSysts::Get_SystematicWeight;
float (CorrsAndSysts::*Get_SystematicWeightx3)(TString, float, float, float, float, int, CAS::Systematic, CAS::SysVar, CAS::SysBin) = &CorrsAndSysts::Get_SystematicWeight; //inline
float (CorrsAndSysts::*Get_SystematicWeightx4)(TString, float, float, float, float, int, TString) = &CorrsAndSysts::Get_SystematicWeight; //inline
BOOST_PYTHON_MODULE(CorrsAndSysts_ext)
{
{
scope CAS = class_<DummyCAS>("CAS");
enum_<CAS::EventType>("EventType")
.value("WHlvbb",CAS::WHlvbb)
.value("ZHllbb",CAS::ZHllbb)
.value("ZHvvbb",CAS::ZHvvbb)
.value("Wb",CAS::Wb)
.value("Wc",CAS::Wc)
.value("Wcc",CAS::Wcc)
.value("Wl",CAS::Wl)
.value("Zb",CAS::Zb)
.value("Zc",CAS::Zc)
.value("Zl",CAS::Zl)
.value("ttbar",CAS::ttbar)
.value("stop",CAS::stop)
.value("diboson",CAS::diboson)
.value("NONAME",CAS::NONAME);
enum_<CAS::SysVar>("SysVar")
.value("Do",CAS::Do)
.value("Up",CAS::Up);
enum_<CAS::SysBin>("SysBin")
.value("None",CAS::None) // default
.value("Any",CAS::Any) // means no binning -> used for continuous systematics
.value("Bin0",CAS::Bin0)
.value("Bin1",CAS::Bin1)
.value("Bin2",CAS::Bin2)
.value("Bin3",CAS::Bin3)
.value("Bin4",CAS::Bin4) // pT bins for binned systematics
.value("NOTDEFINED",CAS::NOTDEFINED);
enum_<CAS::Systematic>("Systematic") // only systematics affecting the shape are relevant to this tool
.value("Nominal",CAS::Nominal)
// the following are binned in pT (5 bins") independent systematics)
.value("PTBINNED",CAS::PTBINNED)
.value("SysStopPt",CAS::SysStopPt)
.value("SysWbbPtW",CAS::SysWbbPtW)
.value("SysWccPtW",CAS::SysWccPtW)
.value("SysZbbPtZ",CAS::SysZbbPtZ)
.value("SysZccPtZ",CAS::SysZccPtZ)
.value("SysWllPtW",CAS::SysWllPtW)
.value("SysZllPtZ",CAS::SysZllPtZ)
// the following are continuous (thus correlated in pT)
.value("CONTINUOUS",CAS::CONTINUOUS)
.value("SysTheoryHPt",CAS::SysTheoryHPt)
.value("SysTopPt",CAS::SysTopPt)
.value("SysTopMbb",CAS::SysTopMbb)
.value("SysStopMbb",CAS::SysStopMbb)
.value("SysZbbMbb",CAS::SysZbbMbb)
.value("SysWbbMbb",CAS::SysWbbMbb)
.value("SysZMbb",CAS::SysZMbb)
.value("SysWMbb",CAS::SysWMbb)
.value("SysWDPhi",CAS::SysWDPhi)
.value("SysWccDPhi",CAS::SysWccDPhi)
.value("SysWbDPhi",CAS::SysWbDPhi)
.value("SysZDPhi",CAS::SysZDPhi)
.value("SysZcDPhi",CAS::SysZcDPhi)
.value("SysZbDPhi",CAS::SysZbDPhi)
.value("LAST",CAS::LAST);
}
//scope b = class_<CorrsAndSysts>("b");
scope c = class_<CorrsAndSysts>("CorrsAndSysts",init<TString,bool>())
.def(init<int, int, bool>())
//.def("Initialize", &CorrsAndSysts::Initialize)
.def("SetDebug", &CorrsAndSysts::SetDebug)//inline
.def("WriteHistsToFile", &CorrsAndSysts::WriteHistsToFile)
.def("Get_HiggsNLOEWKCorrection", Get_HiggsNLOEWKCorrectionx1)
.def("Get_HiggsNLOEWKCorrection", Get_HiggsNLOEWKCorrectionx2)//inline
.def("Get_BkgpTCorrection", Get_BkgpTCorrectionx1)
.def("Get_BkgpTCorrection", Get_BkgpTCorrectionx2)//inline
.def("Get_ToppTCorrection", Get_ToppTCorrectionx1)
.def("Get_ToppTCorrection", Get_ToppTCorrectionx2)//inline
.def("Get_BkgDeltaPhiCorrection", Get_BkgDeltaPhiCorrectionx1)
.def("Get_BkgDeltaPhiCorrection", Get_BkgDeltaPhiCorrectionx2)
.def("Get_SystematicWeight", &CorrsAndSysts::Get_SystematicWeight0)
.def("Get_SystematicWeight", &CorrsAndSysts::Get_SystematicWeight1)
.def("Get_SystematicWeight", &CorrsAndSysts::Get_SystematicWeight2)
.def("Get_SystematicWeight", &CorrsAndSysts::Get_SystematicWeight3)
.def("Get_SystematicWeight", Get_SystematicWeightx2)
.def("Get_SystematicWeight", Get_SystematicWeightx3)//inline
.def("Get_SystematicWeight", Get_SystematicWeightx4)//inline
.def("Get_SystName", &CorrsAndSysts::GetSystName)//inline
.def("GetSystFromName", &CorrsAndSysts::GetSystFromName)//inline
.def("GetEventType", &CorrsAndSysts::GetEventType)
.def("GetSysBin", &CorrsAndSysts::GetSysBin)
/*.def_readwrite("m_debug", &CorrsAndSysts::m_debug)
.def_readwrite("m_draw", &CorrsAndSysts::m_draw)
.def_readwrite("m_zero", &CorrsAndSysts::m_zero)
.def_readwrite("m_one", &CorrsAndSysts::m_one)
.def_readwrite("m_two", &CorrsAndSysts::m_two)
.def_readwrite("m_seven", &CorrsAndSysts::m_seven)
.def_readwrite("m_eight", &CorrsAndSysts::m_eight)
.def_readwrite("pTbins", &CorrsAndSysts::pTbins)*/
//.def_readwrite("m_typeNames", &CorrsAndSysts::m_typeNames)
//.def_readwrite("m_systNames", &CorrsAndSysts::m_systNames)
//.def_readwrite("m_varNames", &CorrsAndSysts::m_varNames)
//.def_readwrite("m_binNames", &CorrsAndSysts::m_binNames)
//.def_readwrite("m_systFromNames", &CorrsAndSysts::m_systFromNames)
//.def_readwrite("m_varFromNames", &CorrsAndSysts::m_varFromNames)
//.def_readwrite("m_binFromNames", &CorrsAndSysts::m_binFromNames)
//.def_readwrite("m_allHists", &CorrsAndSysts::m_allHists)
/*.def_readwrite("m_h_WHlvbbNLOEWKCorrection", &CorrsAndSysts::m_h_WHlvbbNLOEWKCorrection)
.def_readwrite("m_h_ZHllbbNLOEWKCorrection", &CorrsAndSysts::m_h_ZHllbbNLOEWKCorrection)
.def_readwrite("m_h_ZHvvbbNLOEWKCorrection", &CorrsAndSysts::m_h_ZHvvbbNLOEWKCorrection)
.def_readwrite("m_h_WpTCorrection", &CorrsAndSysts::m_h_WpTCorrection)
.def_readwrite("m_h_ZpTCorrection", &CorrsAndSysts::m_h_ZpTCorrection)
.def_readwrite("m_h_WDeltaPhiCorrection2Jet", &CorrsAndSysts::m_h_WDeltaPhiCorrection2Jet)
.def_readwrite("m_h_WDeltaPhiCorrection3Jet", &CorrsAndSysts::m_h_WDeltaPhiCorrection3Jet)
.def_readwrite("m_h_ZDeltaPhiCorrection", &CorrsAndSysts::m_h_ZDeltaPhiCorrection)
.def_readwrite("m_h_topPtCorrection", &CorrsAndSysts::m_h_topPtCorrection)
*/
// binned systematics
/*.def_readwrite("m_h_SysWbbPtW", &CorrsAndSysts::m_h_SysWbbPtW)
.def_readwrite("m_h_SysStopPt", &CorrsAndSysts::m_h_SysStopPt)
.def_readwrite("m_h_SysWccPtW", &CorrsAndSysts::m_h_SysWccPtW)
.def_readwrite("m_h_SysWllPtW", &CorrsAndSysts::m_h_SysWllPtW)
.def_readwrite("m_h_SysZbbPtZ", &CorrsAndSysts::m_h_SysZbbPtZ)
.def_readwrite("m_h_SysZccPtZ", &CorrsAndSysts::m_h_SysZccPtZ)
.def_readwrite("m_h_SysZllPtZ", &CorrsAndSysts::m_h_SysZllPtZ)
// continuous systematics
.def_readwrite("m_h_SysTheoryWHlvbbPt", &CorrsAndSysts::m_h_SysTheoryWHlvbbPt)
.def_readwrite("m_h_SysTheoryZHllbbPt", &CorrsAndSysts::m_h_SysTheoryZHllbbPt)
.def_readwrite("m_h_SysTheoryZHvvbbPt", &CorrsAndSysts::m_h_SysTheoryZHvvbbPt)
.def_readwrite("m_f_WDPhiCorr", &CorrsAndSysts::m_f_WDPhiCorr)
.def_readwrite("m_f_ZDPhiCorr", &CorrsAndSysts::m_f_ZDPhiCorr)
.def_readwrite("m_f_SysZbbMbb", &CorrsAndSysts::m_f_SysZbbMbb)
.def_readwrite("m_f_SysWbbMbb", &CorrsAndSysts::m_f_SysWbbMbb)
.def_readwrite("m_f_SysTopMbb", &CorrsAndSysts::m_f_SysTopMbb)
.def_readwrite("m_f_SysStopMbb", &CorrsAndSysts::m_f_SysStopMbb)
.def_readwrite("m_f_SysWMbb", &CorrsAndSysts::m_f_SysWMbb)
.def_readwrite("m_f_SysZMbb", &CorrsAndSysts::m_f_SysZMbb)*/
;
/*scope utils = class_<Utils>("Utils")
.def("BuildTH1F", &Utils::BuildTH1F)
.def("FillTH1F", &Utils::FillTH1Fx1)
.def("FillTH1F", &Utils::FillTH1Fx2)
.def("GetScale", &Utils::GetScale)//inline
;//.def("reverseMap")*/
// use TH* to store weights ; seems easier to maintain if ever we need e.g 2-d corrections
// corrections
};
| [
"tim@bristow.za.net"
] | tim@bristow.za.net |
a10de9170b2def0089ee5f9dbc6caae25fbc0a6a | c05bc1c96979107eeb1d1463a7fc01b5144452c8 | /SRT/Servers/SRTMinorServo/include/MinorServoBossImpl.h | 151820859a1b606b7956ee9d4380ec813d2bbeb2 | [] | no_license | discos/discos | 1587604ae737d8301f10011d21bfa012dd3c411f | 87dc57a160f3b122af46a9927ee6abb62fdf4159 | refs/heads/master | 2023-08-30T21:39:55.339786 | 2023-06-21T13:39:20 | 2023-06-21T13:39:20 | 87,530,078 | 4 | 4 | null | 2023-09-07T07:57:43 | 2017-04-07T09:37:08 | C++ | UTF-8 | C++ | false | false | 19,803 | h | /*******************************************************************************\
* Author Infos
* ============
* Name: Marco Buttu
* E-mail: mbuttu@oa-cagliari.inaf.it
* Personal Web: http://www.pypeople.com/
\*******************************************************************************/
#ifndef __MINORSERVOBOSSIMPL_H__
#define __MINORSERVOBOSSIMPL_H__
#ifndef __cplusplus
#error This is a C++ include file and cannot be used from plain C
#endif
#include <baciCharacteristicComponentImpl.h>
#include <baciSmartPropertyPointer.h>
#include <baciROpattern.h>
#include <baciROuLongLong.h>
#include <baciROstring.h>
#include <acsncSimpleSupplier.h>
#include <enumpropROImpl.h>
#include <ComponentErrors.h>
#include <ManagementErrors.h>
#include <MinorServoErrors.h>
#include <WPServoImpl.h>
#include <MinorServoErrors.h>
#include <MinorServoS.h>
#include <MinorServoBossS.h>
#include "SetupThread.h"
#include "ParkThread.h"
#include "TrackingThread.h"
#include "ScanThread.h"
#include "MSBossPublisher.h"
#include "MSParameters.h"
#include "MSBossConfiguration.h"
#include <SP_parser.h>
using namespace baci;
struct VerboseStatusFlags {
bool *is_initialized;
bool is_parking;
};
class MinorServoBossImpl: public CharacteristicComponentImpl, public virtual POA_MinorServo::MinorServoBoss {
public:
MinorServoBossImpl(const ACE_CString &CompName, maci::ContainerServices *containerServices);
virtual ~MinorServoBossImpl();
/**
* @throw ComponentErrors::CouldntGetComponentExImpl, ManagementErrors::ConfigurationErrorEx
*/
virtual void initialize() throw (
ComponentErrors::CouldntGetComponentExImpl,
ManagementErrors::ConfigurationErrorExImpl
);
virtual void execute() throw (ComponentErrors::MemoryAllocationExImpl);
/**
* Called by the container before destroying the server in a normal situation.
* This function takes charge of releasing all resources.
*/
virtual void cleanUp();
/**
* Called by the container in case of error or emergency situation.
* This function tries to free all resources even though there is no warranty that the function
* is completely executed before the component is destroyed.
*/
virtual void aboutToAbort();
/**
* This method implements the command line interpreter. The interpreter allows to ask for services or to issue commands
* to the sub-system by human readable command lines.
* @param cmd string that contains the command line
* @param answer string containing the answer to the command
* @return the result of the command : true if successful
* @throw CORBA::SystemException
*/
virtual CORBA::Boolean command(const char *cmd, CORBA::String_out answer) throw (CORBA::SystemException);
/**
* This method is used to stow the minor servo. Only for a configured system.
* @throw CORBA::SystemExcpetion
* @throw ManagementErrors::ParkingErrorEx
*/
virtual void park() throw (CORBA::SystemException, ManagementErrors::ParkingErrorEx);
void parkImpl() throw (ManagementErrors::ParkingErrorExImpl);
/** Return true if the elevation tracking is enabled */
bool isElevationTrackingEn();
/** Is the system tracking the commanded position? */
bool isTracking();
/** Return true when the system is performing a setup */
bool isStarting();
/** Return true when we are using the ASACTIVE configuration */
bool isASConfiguration();
/** Return true if the the servo position is changing by depending of the elevation */
bool isElevationTracking();
/** Return true when the system is performing a park */
bool isParking();
/** Return true when the system is ready */
bool isReady();
/** Return true when the system is performing a scan */
bool isScanning();
/** Return true if a scan is active. To get the system in tracking, perform a stopScan() */
bool isScanActive();
/**
* This method will be used to configure the MinorServoBoss before starting an observation
* @param config mnemonic code of the required configuration
* @throw CORBA::SystemException
* @throw ManagementErrors::ConfigurationErrorEx
*/
virtual void setup(const char *config) throw (CORBA::SystemException, ManagementErrors::ConfigurationErrorEx);
void setupImpl(const char *config) throw (ManagementErrors::ConfigurationErrorExImpl);
/**
* Turn the elevation tracking of minor servos on
* @throw ManagementErrors::ConfigurationErrorEx
*/
void turnTrackingOn() throw (ManagementErrors::ConfigurationErrorEx);
/**
* Turn the elevation tracking of minor servos off. After that, the system is not ready
* @throw ManagementErrors::ConfigurationErrorEx
*/
void turnTrackingOff() throw (ManagementErrors::ConfigurationErrorEx);
/** Return the actual configuration */
char * getActualSetup();
/** Return the commanded configuration */
char * getCommandedSetup();
/**
* Return a reference to status property (ROpattern)
*
* @return pointer to ROpattern status property
* @throw CORBA::SystemException
*/
virtual Management::ROTSystemStatus_ptr status() throw (CORBA::SystemException);
virtual Management::ROTBoolean_ptr ready() throw (CORBA::SystemException);
virtual ACS::ROstring_ptr actualSetup() throw (CORBA::SystemException);
virtual ACS::ROstring_ptr motionInfo() throw (CORBA::SystemException);
virtual Management::ROTBoolean_ptr starting() throw (CORBA::SystemException);
virtual Management::ROTBoolean_ptr asConfiguration() throw (CORBA::SystemException);
virtual Management::ROTBoolean_ptr elevationTrack() throw (CORBA::SystemException);
virtual Management::ROTBoolean_ptr scanActive() throw (CORBA::SystemException);
virtual Management::ROTBoolean_ptr scanning() throw (CORBA::SystemException);
virtual Management::ROTBoolean_ptr tracking() throw (CORBA::SystemException);
/**
* Return a reference to verbose status property (ROpattern)
*
* @return pointer to ROpattern verbose status property
* @throw CORBA::SystemException
*/
// virtual ACS::ROpattern_ptr verbose_status() throw (CORBA::SystemException);
/**
* Check if the scan is achievable (IDL interface)
*
* @param starting_time the time the scan will start
* @param msScanInfo structure containing the description of the scan to be executed
* @param antennaInfo auxiliary information from the antenna
* @param msParameters auxiliary information computed at run time by the subsystem
*
* @return true if the scan is achievable
* @throw ManagementErrors::ConfigurationErrorEx, ManagementErrors::SubscanErrorEx
*/
virtual CORBA::Boolean checkScan(
const ACS::Time starting_time,
const MinorServo::MinorServoScan & msScanInfo,
const Antenna::TRunTimeParameters & antennaInfo,
MinorServo::TRunTimeParameters_out msParameters
) throw (MinorServoErrors::MinorServoErrorsEx, ComponentErrors::ComponentErrorsEx);
/**
* Check if the scan is achievable (implementation)
*
* @param starting_time the time the scan will start
* @param msScanInfo structure containing the description of the scan to be executed
* @param antennaInfo auxiliary information from the antenna
* @param msParameters auxiliary information computed at run time by the subsystem
*
* @return true if the scan is achievable
* @throw MinorServoErrors::MinorServoErrorsEx,
* @throw ComponentErrors::ComponentErrorsEx
*/
virtual CORBA::Boolean checkScanImpl(
const ACS::Time starting_time,
const MinorServo::MinorServoScan & msScanInfo,
const Antenna::TRunTimeParameters & antennaInfo,
MinorServo::TRunTimeParameters_out msParameters
) throw (MinorServoErrors::MinorServoErrorsEx, ComponentErrors::ComponentErrorsEx);
/**
* Start the scan of one axis of a MinorServo target.
*
* @param starting_time the time the scan will start
* @param msScanInfo structure containing the description of the scan to be executed
* @param antennaInfo auxiliary information from the antenna
*
* @throw MinorServoErrors::MinorServoErrorsEx,
* @throw ComponentErrors::ComponentErrorsEx
*/
virtual void startScan(
ACS::Time & startingTime,
const MinorServo::MinorServoScan & scan,
const Antenna::TRunTimeParameters & antennaInfo
) throw (MinorServoErrors::MinorServoErrorsEx, ComponentErrors::ComponentErrorsEx);
virtual void closeScan(ACS::Time& timeToStop) throw (
MinorServoErrors::MinorServoErrorsEx,
ComponentErrors::ComponentErrorsEx);
void startScanImpl(
ACS::Time & startingTime,
const MinorServo::MinorServoScan & scan,
const Antenna::TRunTimeParameters & antennaInfo
) throw (MinorServoErrors::MinorServoErrorsEx, ComponentErrors::ComponentErrorsEx);
/** Return the central position of the axis involved in the scan */
CORBA::Double getCentralScanPosition() throw (
MinorServoErrors::MinorServoErrorsEx,
ComponentErrors::ComponentErrorsEx
);
/** Return the code of the axis involved in the scan */
char * getScanAxis();
/**
* Clear the user offset of a servo (or all servos)
*
* @param servo a string:
* * the servo name
* * "ALL" to clear the user offset of all servos
*
* @throw MinorServoErrors::MinorServoErrorsEx,
* @throw ComponentErrors::ComponentErrorsEx
*/
void clearUserOffset(const char *servo) throw (
MinorServoErrors::MinorServoErrorsEx,
ComponentErrors::ComponentErrorsEx);
/** Clear all the offsets. This method is called when the user gives a clearOffsets from the operator input */
void clearOffsetsFromOI() throw (MinorServoErrors::OperationNotPermittedExImpl);
/**
* Set the user offset of the servo
*
* @param axis_code the axis code (for instance: SRP_TZ, GRF_TZ, ecc.)
* @param double the offset
*
* @throw MinorServoErrors::MinorServoErrorsEx,
* @throw ComponentErrors::ComponentErrorsEx
*/
void setUserOffset(const char * axis_code, const double offset)
throw (MinorServoErrors::MinorServoErrorsEx, ComponentErrors::ComponentErrorsEx);
/** Set the user offset. This method is called when the user gives a clearOffsets from the operator input */
void setUserOffsetFromOI(const char * axis_code, const double & offset)
throw (MinorServoErrors::OperationNotPermittedExImpl);
vector<double> getOffsetImpl(string offset_type)
throw (MinorServoErrors::OperationNotPermittedExImpl, ManagementErrors::ConfigurationErrorExImpl);
/**
* Return the user offset of the system, in the same order of getAxesInfo()
*
* @return offset the user offset of the system, in the same order of getAxesInfo()
*
* @throw MinorServoErrors::MinorServoErrorsEx,
* @throw ComponentErrors::ComponentErrorsEx
*/
ACS::doubleSeq * getUserOffset()
throw (MinorServoErrors::MinorServoErrorsEx, ComponentErrors::ComponentErrorsEx);
/**
* Clear the system offset of a servo (or all servos)
*
* @param servo a string:
* * the servo name
* * "ALL" to clear the system offset of all servos
*
* @throw MinorServoErrors::MinorServoErrorsEx,
* @throw ComponentErrors::ComponentErrorsEx
*/
void clearSystemOffset(const char *servo)
throw (MinorServoErrors::MinorServoErrorsEx, ComponentErrors::ComponentErrorsEx);
/**
* Set the system offset of the servo
*
* @param axis_code the axis code (for instance: SRP_TZ, GRF_TZ, ecc.)
* @param double the offset
*
* @throw MinorServoErrors::MinorServoErrorsEx,
* @throw ComponentErrors::ComponentErrorsEx
*/
void setSystemOffset(const char * axis_code, const double offset)
throw (MinorServoErrors::MinorServoErrorsEx, ComponentErrors::ComponentErrorsEx);
/**
* Return the system offset, in the same order of getAxesInfo()
*
* @return offset the system offset
*
* @throw MinorServoErrors::MinorServoErrorsEx,
* @throw ComponentErrors::ComponentErrorsEx
*/
ACS::doubleSeq * getSystemOffset()
throw (MinorServoErrors::MinorServoErrorsEx, ComponentErrors::ComponentErrorsEx);
/** Return the active axes names and related units
*
* @param axes a sequence of active axes. For instance:
* ("SRP_XT", "SRP_YT", "SRP_ZT", "SRP_XR", "SRP_YR", "SRP_ZR", "GFR_ZR")
* @param units a sequence of strings, each one is the unit of the corresponding axis.
* For instance: ("mm", "mm", "mm", "degree", "degree", "degree", "mm")
*
* @throw MinorServoErrors::MinorServoErrorsEx,
* @throw ComponentErrors::ComponentErrorsEx
*/
void getAxesInfo(ACS::stringSeq_out axes, ACS::stringSeq_out units) throw (
CORBA::SystemException,
MinorServoErrors::MinorServoErrorsEx,
ComponentErrors::ComponentErrorsEx);
/** Return the positions of the active axes
*
* @param time the time related to the positin we want to retrieve
* @return a sequence of positions, in the same order of the axes parameter of getAxesInfo()
* @throw MinorServoErrors::MinorServoErrorsEx,
* @throw ComponentErrors::ComponentErrorsEx
* @throw ComponentErrors::UnexpectedEx
*/
ACS::doubleSeq * getAxesPosition(ACS::Time) throw (
CORBA::SystemException,
MinorServoErrors::MinorServoErrorsEx,
ComponentErrors::ComponentErrorsEx);
/** Set the elevation tracking flag to "ON" or "OFF"
*
* @param value "ON" or "OFF"
* @throw MinorServoErrors::MinorServoErrorsEx if the input is different from "ON" or "OFF"
*/
void setElevationTracking(const char * value) throw (
MinorServoErrors::MinorServoErrorsEx,
ComponentErrors::ComponentErrorsEx
);
void setElevationTrackingImpl(const char * value) throw (ManagementErrors::ConfigurationErrorExImpl);
void setASConfiguration(const char * value) throw (
MinorServoErrors::MinorServoErrorsEx,
ComponentErrors::ComponentErrorsEx
);
void setASConfigurationImpl(const char * value) throw (ManagementErrors::ConfigurationErrorExImpl);
private:
ContainerServices *m_services;
/** The last configuration c-string of setup method */
CString m_config;
SimpleParser::CParser<MinorServoBossImpl> *m_parser;
/** The CDB slaves attribute. Every slave is a Minor Servo to control */
CString m_cdb_slaves;
/** Vector of MinorServos on whith we can enable the elevation tracking */
map<string, bool> m_tracking_list;
/** Vector of intermediary positions needed to perform a scan */
vector<ScanPosition> m_scan_pos;
MSBossConfiguration * m_configuration;
/** Map of component references */
map<string, MinorServo::WPServo_var> m_component_refs;
/** Status property */
baci::SmartPropertyPointer< ROEnumImpl<ACS_ENUM_T(Management::TSystemStatus), POA_Management::ROTSystemStatus> > m_status;
baci::SmartPropertyPointer< ROEnumImpl<ACS_ENUM_T(Management::TBoolean),POA_Management::ROTBoolean> > m_ready;
baci::SmartPropertyPointer<baci::ROstring> m_actualSetup;
baci::SmartPropertyPointer<baci::ROstring> m_motionInfo;
baci::SmartPropertyPointer< ROEnumImpl<ACS_ENUM_T(Management::TBoolean),POA_Management::ROTBoolean> > m_starting;
baci::SmartPropertyPointer< ROEnumImpl<ACS_ENUM_T(Management::TBoolean),POA_Management::ROTBoolean> > m_asConfiguration;
baci::SmartPropertyPointer< ROEnumImpl<ACS_ENUM_T(Management::TBoolean),POA_Management::ROTBoolean> > m_elevationTrack;
baci::SmartPropertyPointer< ROEnumImpl<ACS_ENUM_T(Management::TBoolean),POA_Management::ROTBoolean> > m_scanActive;
baci::SmartPropertyPointer< ROEnumImpl<ACS_ENUM_T(Management::TBoolean),POA_Management::ROTBoolean> > m_scanning;
baci::SmartPropertyPointer< ROEnumImpl<ACS_ENUM_T(Management::TBoolean),POA_Management::ROTBoolean> > m_tracking;
/** Store the value of the property */
Management::TSystemStatus m_status_value;
/** Verbose status property */
// SmartPropertyPointer<ROpattern> m_verbose_status;
/** Struct of verbose status flags used by SubsystemVStatusDevIO (awful practice) */
VerboseStatusFlags m_vstatus_flags;
/**
* Return a vector of minor servo to control
* @return vector of minor servo to control
*/
vector<string> get_slaves();
/** @var commanded configuration */
string m_commanded_conf;
/** @var actual configuration */
string m_actual_conf;
/** @var last servo scanned */
string m_servo_scanned;
/** @var thread parameters */
static MSThreadParameters m_thread_params;
TrackingThread *m_tracking_thread_ptr;
SetupThread *m_setup_thread_ptr;
ParkThread *m_park_thread_ptr;
ScanThread *m_scan_thread_ptr;
MSBossPublisher *m_publisher_thread_ptr;
/** This is the pointer to the notification channel */
nc::SimpleSupplier *m_nchannel;
bool slave_exists(string sname);
bool isParked() throw (ManagementErrors::ConfigurationErrorEx);
void clearOffset(const char *servo, string offset_type) throw (
MinorServoErrors::MinorServoErrorsEx,
ComponentErrors::ComponentErrorsEx);
/**
* Set the offset (Implementation)
*
* @param comp_name the component name
* @param doubleSeq offset sequence of user offsets to add to the position; one offset for each axis
* @throw MinorServoErrors::OperationNotPermittedExImpl
* @throw MinorServoErrors::ConfigurationErrorExImpl
*/
void setOffsetImpl(string comp_name, double offset, string offset_type)
throw (MinorServoErrors::MinorServoErrorsEx, ComponentErrors::ComponentErrorsEx);
ACS::doubleSeq * getOffset(const char *servo, string offset_type)
throw (MinorServoErrors::OperationNotPermittedEx);
/** Return the minumun starting time **/
ACS::Time getMinScanStartingTime(
double & range,
const string axis_code,
const double elevation,
double & acceleration,
double & max_speed)
throw (ManagementErrors::ConfigurationErrorExImpl, ManagementErrors::SubscanErrorExImpl);
void operator=(const MinorServoBossImpl &);
};
/**
* Return a doubleSeq of positions to set
* @param comp_name string component name
* @param token string that contains the polynomial coefficients
* @return doubleSeq of positions to set
*/
ACS::doubleSeq get_positions(string comp_name, string token, const MSThreadParameters *const params)
throw (ManagementErrors::ConfigurationErrorExImpl);
/**
* Return a doubleSeq of positions to set
* @param token string that contains the component name
* @return string the component name
*/
string get_component_name(string token);
/** Return the minimum time needed to move for range mm, with given acceleration and maximum speed */
ACS::Time get_min_time(double range, double acceleration, double max_speed);
#endif
| [
"mbuttu@oa-cagliari.inaf.it"
] | mbuttu@oa-cagliari.inaf.it |
d96cb33b399639c94818140741435e0a957896de | 08cbeb3db9317e892dc3ec683e4fbf9c3b0e86ac | /abc/016/c.cpp | 46268ed688a6c4596129987489a846bbb322caba | [] | no_license | wonda-tea-coffee/atcoder | 0b7a8907d6b859e7b65bbf2829fb861e080e671a | 5282f9915da773df3fd27c8570690d912b0bbd90 | refs/heads/master | 2020-12-21T09:57:41.187968 | 2020-04-19T12:33:48 | 2020-05-02T14:49:48 | 236,391,204 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,366 | cpp | #include <algorithm>
#include <bitset>
#include <cassert>
#include <cmath>
#include <ctime>
#include <cstring>
#include <functional>
#include <iostream>
#include <iomanip>
#include <limits>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <regex>
#include <vector>
#define fix(n) cout<<fixed<<setprecision(n)
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define all(a) (a).begin(), (a).end()
#define sort(a) sort(all(a))
#define uniq(a) sort(a);(a).erase(unique(all(a), (a).end())
#define reverse(a) reverse(all(a))
#define ctos(c) string(1, (c))
#define out(d) cout << (d)
#define outl(d) std::cout<<(d)<<"\n"
#define YES() cout << "YES" << endl
#define NO() cout << "NO" << endl
#define Yes() cout << "Yes" << endl
#define No() cout << "No" << endl
#define ceil(x, y) ((x + y - 1) / (y))
#define debug(x) cerr << #x << ": " << (x) << '\n'
#define debug2(x, y) cerr << #x << ": " << (x) << ", " << #y << ": " << (y) << '\n'
#define debug3(x, y, z) cerr << #x << ": " << (x) << ", " << #y << ": " << (y) << ", " << #z << ": " << (z) << '\n'
#define dbg(v) for (size_t _ = 0; _ < v.size(); ++_){ cerr << #v << "[" << _ << "] : " << v[_] << '\n'; }
#define pb push_back
#define fst first
#define int long long
using namespace std;
using ll = long long;
using ld = long double;
using P = pair<ll,ll>;
const ll MOD = 1000000007; // 10^9 + 7
const int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
const int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
void solve() {
int n, m; cin >> n >> m;
const int MAX = 10;
bool rel[MAX + 1][MAX + 1] = {false};
rep(i, m) {
int a, b; cin >> a >> b;
rel[a][b] = true;
rel[b][a] = true;
}
for (int i = 1; i <= n; i++) {
set<int> friends;
for (int j = 1; j <= n; j++) {
if (!rel[i][j]) continue;
for (int k = 1; k <= n; k++) {
if (rel[j][k]) friends.insert(k);
}
}
// 自身を除外
friends.erase(i);
// 直接の友達を除外
for (int j = 1; j <= n; j++)
if (rel[i][j]) friends.erase(j);
outl(friends.size());
}
}
signed main() {
cin.tie(0);
ios::sync_with_stdio(false);
srand((unsigned)time(NULL));
fix(12);
solve();
}
| [
"rikita.ishikawa@crowdworks.co.jp"
] | rikita.ishikawa@crowdworks.co.jp |
4efceb85b914442f0c210dc4d275b3b5ebbd6708 | 068b8d90a558cffcfe4db2f38ed7d56e0757ccf8 | /docs/eNBSP SDK_V4.861/SDK/ISO 19794-4/Windows/Sample C++/NExportRawToISO_Test/NExportRawToISO_Test.h | 7d3b929c8e87d80086cacbdb249f2579bf395276 | [] | no_license | jgckruger/ongonline | 0d95ef2952e01ce80aaa54c49ad0ed875d008bca | c4880c115a79845e73c142b48aef29d8a843f3da | refs/heads/dev | 2020-12-25T13:51:15.380971 | 2016-01-22T18:47:10 | 2016-01-22T18:47:10 | 52,030,506 | 2 | 0 | null | 2016-02-18T18:53:36 | 2016-02-18T18:53:36 | null | UTF-8 | C++ | false | false | 1,429 | h | // NExportRawToISO_Test.h : main header file for the NEXPORTRAWTOISO_TEST application
//
#if !defined(AFX_NEXPORTRAWTOISO_TEST_H__1DEAAE03_4406_4E6B_B8B1_631F0D4EC58A__INCLUDED_)
#define AFX_NEXPORTRAWTOISO_TEST_H__1DEAAE03_4406_4E6B_B8B1_631F0D4EC58A__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CNExportRawToISO_TestApp:
// See NExportRawToISO_Test.cpp for the implementation of this class
//
class CNExportRawToISO_TestApp : public CWinApp
{
public:
CNExportRawToISO_TestApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CNExportRawToISO_TestApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CNExportRawToISO_TestApp)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_NEXPORTRAWTOISO_TEST_H__1DEAAE03_4406_4E6B_B8B1_631F0D4EC58A__INCLUDED_)
| [
"ademir.mazer.jr@gmail.com"
] | ademir.mazer.jr@gmail.com |
bc845cf5a2ec7afc0d4a507b6c4779528535462d | ae2ae838e9b80a102af5fa0a362aedc42177b252 | /mod.nickserv/SAYCommand.cc | 1aa3c6beef0b95b58bf3008a517d4e1024d32f52 | [] | no_license | NetGamers/ng-p | 83ce8e0a5d0a429f99ce6abb2ccb27585e069a43 | eaf139ebdd12fe864b027a618386fa0357f4b779 | refs/heads/master | 2021-01-20T05:32:01.960393 | 2011-08-29T20:07:10 | 2011-08-29T20:07:10 | 2,210,784 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 802 | cc | /*
* SAYCommand.cc
*
* 20020130 - Jeekay - Initial version
*/
#include <string>
#include "StringTokenizer.h"
#include "nickserv.h"
#include "levels.h"
#include "Network.h"
namespace gnuworld
{
namespace nserv
{
using std::string;
bool SAYCommand::Exec( iClient* theClient, const string& Message )
{
StringTokenizer st( Message );
if(st.size() < 3)
{
Usage(theClient);
return true;
}
int admLevel = bot->getAdminAccessLevel(theClient);
if(admLevel < level::say)
{
return false;
} // Not enough access
Channel* theChan = Network->findChannel(st[1]);
if(!theChan)
{
bot->Notice(theClient, "Channel not found");
return false;
} // Channel doesnt exist
bot->Message(st[1], st.assemble(2).c_str());
return true;
} // SAYCommand::Exec
} // namespace nserv
} // namespace gnuworld
| [
"jeekay"
] | jeekay |
ecd2740ac1f90d71c4396a167804733dedcddd1c | 1b9a3a103c4fc50d51f2d14b1216b479e3ec5b7e | /src/tileseteditor.cpp | f89aabbab919f09ddd69e588e5cd13fd124bb999 | [] | no_license | habeascorpse/Luawar | e5a1c3cf686ebea4d6d102d3d9380f4a9edfc785 | 09c3c995b4873f08e48bda148b8443706711aeb0 | refs/heads/master | 2021-01-01T16:05:56.174549 | 2012-05-21T15:01:59 | 2012-05-21T15:01:59 | 4,394,437 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,421 | cpp | /***************************************************************************
* Copyright (C) 2009 by Alan de Oliveira Silva, Thiago Luiz Rodrigues, Gabriel Vedana Queiroz *
* habeas_corpse@yahoo.com.br *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "tileseteditor.h"
namespace Editors {
// this is a Default constructor of Editor
TileSetEditor::TileSetEditor(string fileTileset,string fileImage,CoreObjects* core)
{
// init the resources
render = core->render;
event = core->event;
this->initResources();
// try to open tileset, if failcreate new tileset
this->fileTileset = fileTileset;
this->fileImage = fileImage;
this->imgInformation = Render::Video::LoadBMP("../images/tilesets/informationteditor.png");
for (i = 0;i<TILESET_X;i++) {
for (j = 0;j<TILESET_Y;j++) {
tileSet->setProperty(i,j,0);
}
}
if ((this->tileSet->loadTileset(fileTileset.c_str())) == ERROR) {
this->X = TILESET_X;
this->Y = TILESET_Y;
if (tileSet->setImgFile(this->fileImage)== SUCCESS){
if (tileSet->saveTileset(this->fileTileset) == SUCCESS){
cout<<"TileSet save with success"<<endl;
}
}
}
// if file exist, open tileset and put all properties
else {
this->X = TILESET_X;
this->Y = TILESET_Y;
}
// create the Surfaces
this->imgTile = Render::Video::LoadBMP(this->tileSet->getImgFile().c_str());
if(this->imgTile == NULL){
this->imgTile = Render::Video::LoadBMP("../images/tilesets/errortset.png");
}
//Register pkg of Tileset
this->pkgTile = new Render::Package;
this->pkgTile->img = this->imgTile;
this->pkgTile->destRect = NULL;
this->pkgTile->srcRect = NULL;
this->pkgTile->number = 2;
this->render->priority->addPackage(this->pkgTile);
//RegisterPkg of Information
this->pkgInf = new Render::Package;
this->pkgInf->img = this->imgInformation;
this->pkgInf->destRect = NULL;
this->pkgInf->srcRect = NULL;
this->pkgInf->number = 3;
this->render->priority->addPackage(this->pkgInf);
SDL_WM_SetCaption("TileSet Editor","../images/ico.bmp");
SDL_WM_SetIcon(SDL_LoadBMP("../images/ico.bmp"),NULL);
top->add(label);
render->priority->addPackage(&pkgGui);
}
// Destructor that clear all resources
TileSetEditor::~TileSetEditor()
{
delete tileSet;
delete pkgInf;
delete pkgTile;
render->priority->removePackage(pkgGui.number);
SDL_FreeSurface(pkgGui.img);
delete label;
delete font;
delete top;
delete gui;
delete input;
delete graphics;
delete imageLoader;
}
// This function initialize all resources the need to
// do, it is: Event, Video, Map.
void TileSetEditor::initResources() {
tileSet = new Scenario::Tileset();
// define the size of rectangle that the map goes to occupy
this->tileSrcRect.x = 0;
this->tileSrcRect.y = 0;
this->tileSrcRect.w = DF_WIDTH - sizeTsetVideoX;
this->tileSrcRect.h = DF_HEIGHT;
// set the positions of scrolling map
this->cursorY = 0;
this->cursorX = 0;
// Initializations of Guichan
pkgGui.destRect = NULL;
pkgGui.number = 100;
pkgGui.srcRect = NULL;
pkgGui.img = Render::Video::CreateSurface(640 ,480,DF_DEPTH);
SDL_EnableUNICODE(1);
imageLoader = new gcn::SDLImageLoader();
gcn::Image::setImageLoader(imageLoader);
graphics = new gcn::SDLGraphics();
graphics->setTarget(pkgGui.img);
input = new gcn::SDLInput();
font = new gcn::ImageFont("../images/Font/font.png", " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-+/():;%&`'*#=[]");
gcn::Widget::setGlobalFont(font);
gui = new gcn::Gui();
gui->setGraphics(graphics);
gui->setInput(input);
top = new gcn::Container();
top->setDimension(gcn::Rectangle(sizeTsetVideoX, 0, 640, 480));
gui->setTop(top);
//Map
label = new gcn::Label("Valor do Tileset:");
label->setPosition(100, 200);
}
// Draw grid of tile
void TileSetEditor::drawGridTile() {
int i,j, sizetx,sizety;
sizetx = sizeTsetVideoX;
sizety = DF_HEIGHT;
SDL_Rect destRect;
for (i = 0;i<TILESET_X;i++) {
destRect.x = (i + 1) * TILE_SIZE;
destRect.y = 0;
destRect.w = 2;
destRect.h = sizety;
SDL_FillRect(this->imgTile,&destRect,91);
}
for (j = 0;j<TILESET_Y;j++) {
destRect.x = 0;
destRect.y = (j + 1) * TILE_SIZE;
destRect.w = sizetx;
destRect.h = 2;
SDL_FillRect(this->imgTile,&destRect,91);
}
}
// this function analyze the events into Action
// and make all actions necessary
void TileSetEditor::eventAnalyzer() {
while (event->action.firstAction() != 0) {
if (event->action.firstAction() == ACT_EXIT) {
this->quit = true;
event->action.removeAction();
}
// Save the tileSet
if (event->action.firstAction() == ACT_FIRE) {
if (tileSet->setImgFile(this->fileImage)== SUCCESS){
if (tileSet->saveTileset(this->fileTileset) == SUCCESS){
cout<<"TileSet save with success"<<endl;
label->setCaption("Tileset salvo!");
}
}
event->action.removeAction();
}
if (event->action.firstAction() == ACT_MOUSECL_LEFT) {
this->clipBoard = 0;
mousex = (event->event.button.x / TILE_SIZE);
mousey = (event->event.button.y / TILE_SIZE);
// verify if the mouse is on Tileset Box
if ((event->event.button.x) <= this->sizeTsetVideoX) {
this->clipBoard = Scenario::Tileset::matrixToBase8(mousex,mousey);
cout <<"Clipboard antes = "<<this->clipBoard<<endl;
this->clipBoard = this->tileSet->getProperty(this->clipBoard) +1;
//pass base positive
if(clipBoard < 0){
this->clipBoard = this->clipBoard * -1;
}
cout <<"Clipboard depois = "<<this->clipBoard<<endl;
this->tileSet->setProperty(mousex,mousey,this->clipBoard);
stringstream stream;
stream <<"Valor:"<<this->clipBoard;
label->setCaption(stream.str());
//print in sreen
event->action.removeAction();
}
}
if (event->action.firstAction() == ACT_MOUSECL_RIGHT ) {
// verify if the mouse is on Tileset Box
if ((event->event.button.x) <= this->sizeTsetVideoX) {
this->clipBoard = Scenario::Tileset::matrixToBase8(mousex,mousey);
cout <<"Clipboard antes = "<<this->clipBoard<<endl;
this->clipBoard = this->tileSet->getProperty(this->clipBoard) -1;
if(clipBoard < 0){
clipBoard = 0;
}
cout <<"Clipboard depois= "<<this->clipBoard<<endl;
this->tileSet->setProperty(mousex,mousey,this->clipBoard);
stringstream stream;
stream <<"Valor:"<<this->clipBoard;
label->setCaption(stream.str());
event->action.removeAction();
}
}
// if the action does not compatible, then remove
if (event->action.firstAction() != 0) {
event->action.removeAction();
}
}
}
void TileSetEditor::loop() {
this->drawGridTile();
this->quit = false;
while (this->quit == false) {
event->capture();
eventAnalyzer();
gui->logic();
pthread_mutex_lock(&render->priority->videoMutex);
gui->draw();
pthread_mutex_unlock(&render->priority->videoMutex);
SDL_Delay(50);
}
this->render->priority->removePackage(this->pkgTile->number);
this->render->priority->removePackage(this->pkgInf->number);
SDL_FreeSurface(this->imgInformation);
SDL_FreeSurface(this->imgTile);
}
}
| [
"alan@dev-mine.(none)"
] | alan@dev-mine.(none) |
e752cb64b9f50b3a344962964e0e563f3dc2d13c | 7bf1f0f4507fb8285be393b3a2bd6fa6b6debb9e | /shadow/core/helper.cpp | bb2896927339d4176cef9f5fa70ba9e83cf108b6 | [
"Apache-2.0"
] | permissive | junluan/shadow | f376d28d51030c8010c2926949f23462710c9845 | 067d1c51d7c38bc1c985008a2e2e1599bbf11a8c | refs/heads/master | 2021-07-06T12:31:51.218310 | 2021-05-24T06:20:40 | 2021-05-24T06:20:40 | 54,448,369 | 20 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 6,185 | cpp | #include "helper.hpp"
#include "util/log.hpp"
namespace Shadow {
template <typename T>
ArgumentHelper::ArgumentHelper(const T& def) {
for (const auto& arg : def.arg()) {
CHECK(!HasArgument(arg.name()))
<< "Duplicated argument name: " << arg.name()
<< " found in def: " << def.name();
arguments_[arg.name()] = arg;
}
}
template ArgumentHelper::ArgumentHelper(const shadow::NetParam&);
template ArgumentHelper::ArgumentHelper(const shadow::OpParam&);
template <>
ArgumentHelper::ArgumentHelper(
const std::map<std::string, shadow::Argument>& arguments) {
arguments_ = arguments;
}
bool ArgumentHelper::HasArgument(const std::string& name) const {
return arguments_.count(name) > 0;
}
#define INSTANTIATE_SINGLE_ARGUMENT(fieldname, T) \
template <> \
T ArgumentHelper::GetSingleArgument<T>(const std::string& name, \
const T& default_value) const { \
if (!HasArgument(name)) { \
return default_value; \
} \
CHECK(arguments_.at(name).has_##fieldname()); \
return arguments_.at(name).fieldname(); \
} \
template <> \
void ArgumentHelper::AddSingleArgument<T>(const std::string& name, \
const T& value) { \
CHECK(!HasArgument(name)) << "Duplicated argument name: " << name; \
arguments_[name] = {}; \
arguments_[name].set_name(name); \
arguments_[name].set_##fieldname(value); \
}
INSTANTIATE_SINGLE_ARGUMENT(s_f, float);
INSTANTIATE_SINGLE_ARGUMENT(s_i, int);
INSTANTIATE_SINGLE_ARGUMENT(s_i, bool);
INSTANTIATE_SINGLE_ARGUMENT(s_s, std::string);
#undef INSTANTIATE_SINGLE_ARGUMENT
#define INSTANTIATE_REPEATED_ARGUMENT(fieldname, T) \
template <> \
std::vector<T> ArgumentHelper::GetRepeatedArgument<T>( \
const std::string& name, const std::vector<T>& default_value) const { \
if (!HasArgument(name)) { \
return default_value; \
} \
std::vector<T> values; \
for (auto v : arguments_.at(name).fieldname()) { \
values.push_back(v); \
} \
return values; \
} \
template <> \
void ArgumentHelper::AddRepeatedArgument<T>(const std::string& name, \
const std::vector<T>& value) { \
CHECK(!HasArgument(name)) << "Duplicated argument name: " << name; \
arguments_[name] = {}; \
arguments_[name].set_name(name); \
for (auto v : value) { \
arguments_[name].add_##fieldname(v); \
} \
}
INSTANTIATE_REPEATED_ARGUMENT(v_f, float);
INSTANTIATE_REPEATED_ARGUMENT(v_i, int);
INSTANTIATE_REPEATED_ARGUMENT(v_i, bool);
INSTANTIATE_REPEATED_ARGUMENT(v_s, std::string);
#undef INSTANTIATE_REPEATED_ARGUMENT
#define INSTANTIATE_ADD_SINGLE_ARGUMENT(fieldname, P, T) \
void add_##fieldname(P* param, const std::string& name, const T& value) { \
auto* arg = param->add_arg(); \
arg->set_name(name); \
arg->set_##fieldname(value); \
}
INSTANTIATE_ADD_SINGLE_ARGUMENT(s_f, shadow::NetParam, float);
INSTANTIATE_ADD_SINGLE_ARGUMENT(s_i, shadow::NetParam, int);
INSTANTIATE_ADD_SINGLE_ARGUMENT(s_i, shadow::NetParam, bool);
INSTANTIATE_ADD_SINGLE_ARGUMENT(s_s, shadow::NetParam, std::string);
INSTANTIATE_ADD_SINGLE_ARGUMENT(s_f, shadow::OpParam, float);
INSTANTIATE_ADD_SINGLE_ARGUMENT(s_i, shadow::OpParam, int);
INSTANTIATE_ADD_SINGLE_ARGUMENT(s_i, shadow::OpParam, bool);
INSTANTIATE_ADD_SINGLE_ARGUMENT(s_s, shadow::OpParam, std::string);
#undef INSTANTIATE_ADD_SINGLE_ARGUMENT
#define INSTANTIATE_ADD_REPEATED_ARGUMENT(fieldname, P, T) \
void add_##fieldname(P* param, const std::string& name, \
const std::vector<T>& value) { \
auto* arg = param->add_arg(); \
arg->set_name(name); \
for (auto v : value) { \
arg->add_##fieldname(v); \
} \
}
INSTANTIATE_ADD_REPEATED_ARGUMENT(v_f, shadow::NetParam, float);
INSTANTIATE_ADD_REPEATED_ARGUMENT(v_i, shadow::NetParam, int);
INSTANTIATE_ADD_REPEATED_ARGUMENT(v_i, shadow::NetParam, bool);
INSTANTIATE_ADD_REPEATED_ARGUMENT(v_s, shadow::NetParam, std::string);
INSTANTIATE_ADD_REPEATED_ARGUMENT(v_f, shadow::OpParam, float);
INSTANTIATE_ADD_REPEATED_ARGUMENT(v_i, shadow::OpParam, int);
INSTANTIATE_ADD_REPEATED_ARGUMENT(v_i, shadow::OpParam, bool);
INSTANTIATE_ADD_REPEATED_ARGUMENT(v_s, shadow::OpParam, std::string);
#undef INSTANTIATE_ADD_REPEATED_ARGUMENT
} // namespace Shadow
| [
"mutate@aliyun.com"
] | mutate@aliyun.com |
3060598cc2798ab8bec7b28336bf8616a65ce619 | 93a55012cd09a3a0019a7876dac9c3362655c079 | /Tetrix/OPERATOR.cpp | a8fdb683bb4fbac1c0be38a0efa973c9677eaf43 | [] | no_license | Cheukyin/Tetris | 291cd385472b40538740afa4c352c21870c0e385 | 0596929ffaf4c8de060f90bc3c5a7125538b1970 | refs/heads/master | 2016-09-11T00:17:28.781721 | 2013-09-30T15:40:14 | 2013-09-30T15:40:14 | 13,219,526 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 508 | cpp | #include <OPERATOR.h>
Coord::Coord()
{
x=0;
y=0;
}
Coord::Coord(int a1,int a2)
{
x=a1;
y=a2;
}
Matrix_2nd_Order::Matrix_2nd_Order()
{
}
Matrix_2nd_Order::Matrix_2nd_Order(int a11, int a12, int a21, int a22)
{
a[0][0]=a11;
a[0][1]=a12;
a[1][0]=a21;
a[1][1]=a22;
}
Coord Matrix_2nd_Order::operator *(const Coord * t) const
{
Coord result;
result.x=a[0][0]*t->x+a[0][1]*t->y;
result.y=a[1][0]*t->x+a[1][1]*t->y;
return result;
}
| [
"cheukyinyip0077@gmail.com"
] | cheukyinyip0077@gmail.com |
82f3651837647ebc7d1bdd9cb5faef7e7a3fcbc4 | c96044805d7e30806696ecb482582c25d290f114 | /src/dota/event/dota_player_show_killcam.h | 23b10f773ad3157c993c1fa3e7b549547ffcc0bb | [] | no_license | exjam/dota2-replay-cpp | f49fbbac2b2d29da22d236a1e8469f2477a8d494 | a0c445d4b591e354395eb662281445bb5bbb01c9 | refs/heads/master | 2021-03-12T21:22:25.915447 | 2015-02-12T23:39:22 | 2015-02-12T23:39:22 | 28,197,953 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 235 | h | #pragma once
#include <cstdint>
#include "event.h"
namespace dota
{
namespace event
{
struct dota_player_show_killcam
{
uint8_t nodes;
int16_t player;
};
}
DeclareGameEvent(dota_player_show_killcam);
}
| [
"james.benton2@gmail.com"
] | james.benton2@gmail.com |
d66ef62b96ad35147968fc368aef54605277debc | 9160d5980d55c64c2bbc7933337e5e1f4987abb0 | /base/src/sgpp/base/operation/hash/OperationSecondMomentBspline.cpp | 2700d89153c15d2ef25d05671be638ce43ad37eb | [
"LicenseRef-scancode-generic-exception",
"BSD-3-Clause"
] | permissive | SGpp/SGpp | 55e82ecd95ac98efb8760d6c168b76bc130a4309 | 52f2718e3bbca0208e5e08b3c82ec7c708b5ec06 | refs/heads/master | 2022-08-07T12:43:44.475068 | 2021-10-20T08:50:38 | 2021-10-20T08:50:38 | 123,916,844 | 68 | 44 | NOASSERTION | 2022-06-23T08:28:45 | 2018-03-05T12:33:52 | C++ | UTF-8 | C++ | false | false | 3,269 | cpp | // Copyright (C) 2008-today The SG++ project
// This file is part of the SG++ project. For conditions of distribution and
// use, please see the copyright notice provided with SG++ or at
// sgpp.sparsegrids.org
#include <sgpp/base/operation/hash/OperationSecondMomentBspline.hpp>
#include <sgpp/base/grid/type/BsplineGrid.hpp>
#include <sgpp/base/exception/application_exception.hpp>
#include <sgpp/base/tools/GaussLegendreQuadRule1D.hpp>
#include <sgpp/globaldef.hpp>
#include <algorithm>
namespace sgpp {
namespace base {
double OperationSecondMomentBspline::doQuadrature(DataVector& alpha, DataMatrix* bounds) {
// handle bounds
GridStorage& storage = grid->getStorage();
size_t numDims = storage.getDimension();
// check if the boundaries are given in the right shape
if (bounds != nullptr && (bounds->getNcols() != 2 || bounds->getNrows() != numDims)) {
throw application_exception(
"OperationSecondMomentBspline::doQuadrature - bounds matrix has the wrong shape");
}
size_t p = dynamic_cast<sgpp::base::BsplineGrid*>(grid)->getDegree();
double pDbl = static_cast<double>(p);
double res = 0;
double tmpres = 1;
base::index_t index;
double indexDbl;
base::level_t level;
double xlower = 0.0;
double xupper = 0.0;
const size_t pp1h = (p + 1) >> 1; // (p + 1) / 2
const double pp1hDbl = static_cast<double>(pp1h);
const size_t quadOrder = static_cast<size_t>(ceil(pDbl / 2.)) + 2;
base::SBasis& basis = const_cast<base::SBasis&>(grid->getBasis());
base::DataVector coordinates;
base::DataVector weights;
base::GaussLegendreQuadRule1D gauss;
gauss.getLevelPointsAndWeightsNormalized(quadOrder, coordinates, weights);
for (GridStorage::grid_map_iterator iter = storage.begin(); iter != storage.end(); iter++) {
tmpres = 1.;
for (size_t dim = 0; dim < storage.getDimension(); dim++) {
index = iter->first->getIndex(dim);
indexDbl = static_cast<double>(index);
level = iter->first->getLevel(dim);
double hInv = static_cast<double>(1 << level);
xlower = bounds == nullptr ? 0.0 : bounds->get(dim, 0);
xupper = bounds == nullptr ? 1.0 : bounds->get(dim, 1);
double width = xupper - xlower;
size_t start = ((index > pp1h) ? 0 : (pp1h - index));
size_t stop = static_cast<size_t>(std::min(pDbl, hInv + pp1hDbl - indexDbl - 1));
double scaling = 1./hInv; // for a single Bspline section
double sum_1d_secondMoment = 0.;
double sum_1d_firstMoment = 0.;
for (size_t n = start; n <= stop; n++) {
double offset = scaling * static_cast<double>(n + index - pp1h);
for (size_t c = 0; c < quadOrder; c++) {
const double x = offset + scaling * coordinates[c];
sum_1d_secondMoment += weights[c] * x * x * basis.eval(level, index, x);
sum_1d_firstMoment += weights[c] * x * basis.eval(level, index, x);
}
}
sum_1d_secondMoment *= scaling;
sum_1d_firstMoment *= scaling;
tmpres *=
width * width * sum_1d_secondMoment
+ 2 * width * xlower * sum_1d_firstMoment
+ xlower * xlower * basis.getIntegral(level, index);
}
res += alpha.get(iter->second) * tmpres;
}
return res;
}
} // namespace base
} // namespace sgpp
| [
"schroeji@studi.informatik.uni-stuttgart.de"
] | schroeji@studi.informatik.uni-stuttgart.de |
61af36ed946868e4d623b2af3c73b6703145bd22 | e30546ed8e712149f8303d4bc7342db9b38b3b9a | /HSBColor/src/ofApp.cpp | 96ca0dbbd406ab22774da4471169e5cfce66fd5b | [] | no_license | Makcime/TraitImage | f63d20c62d9628ff02d56192f6e80dd40bebd8c6 | 29088be1ab69009e8abfe6c1b4e53931a81926fe | refs/heads/master | 2021-01-06T20:42:24.129822 | 2016-01-07T16:54:58 | 2016-01-07T16:54:58 | 42,639,703 | 0 | 0 | null | 2015-11-24T18:48:26 | 2015-09-17T06:45:55 | Makefile | UTF-8 | C++ | false | false | 5,590 | cpp | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
base_tdf.loadImage("images/tdf_1972_poster.jpg");
level = 1;
red_lev = 1;
computeGrayScale(&tdf_eq_base , "images/tdf_1972_poster.jpg", level);
computeGrayScale(&tdf_eq , "images/tdf_1972_poster.jpg", level);
keepRed(&tdf_red, "images/tdf_1972_poster.jpg", red_lev);
keepRedHsb(&tdf_red_hsb, "images/tdf_1972_poster.jpg", red_lev);
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
base_tdf.draw(0, 0);
tdf_red.draw(400, 0);
tdf_red_hsb.draw(800, 0);
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch (key)
{
case OF_KEY_UP:
level++;
if (level > 255){ level = 255;}
computeGrayScale(&tdf_eq, "images/tdf_1972_poster.jpg", level);
printf("level : %d\n", 256 / level);
break;
case OF_KEY_DOWN:
level--;
if (level < 1){ level = 1;}
computeGrayScale(&tdf_eq, "images/tdf_1972_poster.jpg", level);
printf("level : %d\n", 256 / level);
break;
case OF_KEY_RIGHT:
red_lev+=0.1;
if (level > 255){ level = 255;}
keepRed(&tdf_red, "images/tdf_1972_poster.jpg", red_lev);
printf("red_level : %f\n", red_lev);
break;
case OF_KEY_LEFT:
red_lev-=0.1;
if (level < 1){ level = 1;}
keepRed(&tdf_red, "images/tdf_1972_poster.jpg", red_lev);
break;
default:
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
//--------------------------------------------------------------
void ofApp::computeGrayScale( ofImage *img, char * path, int lev){
img->loadImage(path);
// tdf.setImageType(OF_IMAGE_GRAYSCALE); // now I am grayscale;
//Getting pointer to pixel array of tdf
unsigned char *data = img->getPixels();
//Calculate number of pixel components
int components = img->bpp / 8;
//Modify pixel array
for (int y=0; y<img->height; y++) {
for (int x=0; x<img->width; x++) {
//Read pixel (x,y) color components
int index = components * (x + img->width * y);
int red = data[ index ];
int green = data[ index + 1 ];
int blue = data[ index + 2 ];
int eq = 0.299 * red + 0.587 * green + 0.114 * blue;
eq -= eq % lev;
//Set red
data[ index + RED] = eq ;
//Set green
data[ index + GREEN ] = eq;
//Set blue
data[ index + BLUE] = eq;
}
}
//Calling img.update() to apply changes
img->update();
}
void ofApp::keepRed(ofImage *img, char * path, float t){
img->loadImage(path);
// tdf.setImageType(OF_IMAGE_GRAYSCALE); // now I am grayscale;
//Getting pointer to pixel array of tdf
unsigned char *data = img->getPixels();
//Calculate number of pixel components
int components = img->bpp / 8;
//Modify pixel array
for (int y=0; y<img->height; y++) {
for (int x=0; x<img->width; x++) {
//Read pixel (x,y) color components
int index = components * (x + img->width * y);
int red = data[ index ];
int green = data[ index + 1 ];
int blue = data[ index + 2 ];
int eq = 0.299 * red + 0.587 * green + 0.114 * blue;
if (!((float)red > (float)green * t && (float)red > (float)blue * t)){
//Set red
data[ index + RED] = eq ;
//Set green
data[ index + GREEN ] = eq;
//Set blue
data[ index + BLUE] = eq;
}
}
}
//Calling img.update() to apply changes
img->update();
}
void ofApp::keepRedHsb(ofImage *img, char * path, float t){
img->loadImage(path);
// tdf.setImageType(OF_IMAGE_GRAYSCALE); // now I am grayscale;
//Getting pointer to pixel array of tdf
unsigned char *data = img->getPixels();
//Calculate number of pixel components
int components = img->bpp / 8;
//Modify pixel array
for (int y=0; y<img->height; y++) {
for (int x=0; x<img->width; x++) {
//Read pixel (x,y) color components
int index = components * (x + img->width * y);
int red = data[ index ];
int green = data[ index + 1 ];
int blue = data[ index + 2 ];
int eq = 0.299 * red + 0.587 * green + 0.114 * blue;
col_hsb.set(red, green, blue);
float h = col_hsb.getHue();
if (h > 25){
//Set red
data[ index + RED] = eq ;
//Set green
data[ index + GREEN ] = eq;
//Set blue
data[ index + BLUE] = eq;
}
}
}
//Calling img.update() to apply changes
img->update();
}
| [
"marlier.maxime@gmail.com"
] | marlier.maxime@gmail.com |
41eccaa63458a9e15ebf652065889a071edd883a | f38bccb8daa57e09b18b86865b6b14537e976e3d | /Lilu/Sources/kern_iokit.cpp | a24fce1352869519ebb4a454078d1bb0dbf24557 | [
"BSD-3-Clause"
] | permissive | 935713827/Lilu | 776734706a2e4cc5266a49c05b2a14a8e203c45e | 36512f9f2b378a1ca4bec76caa453898a786e31b | refs/heads/master | 2021-05-05T10:52:13.624087 | 2017-09-21T18:05:48 | 2017-09-21T18:05:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,690 | cpp | //
// kern_iokit.cpp
// Lilu
//
// Copyright © 2016-2017 vit9696. All rights reserved.
//
#include <Headers/kern_config.hpp>
#include <Headers/kern_compat.hpp>
#include <Headers/kern_iokit.hpp>
#include <Headers/kern_util.hpp>
#include <Headers/kern_patcher.hpp>
#include "Library/LegacyIOService.h"
#include <libkern/c++/OSSerialize.h>
#include <IOKit/IORegistryEntry.h>
#include <IOKit/IODeviceTreeSupport.h>
namespace WIOKit {
OSSerialize *getProperty(IORegistryEntry *entry, const char *property) {
auto value = entry->getProperty(property);
if (value) {
auto s = OSSerialize::withCapacity(PAGE_SIZE);
if (value->serialize(s)) {
return s;
} else {
SYSLOG("iokit @ failed to serialise %s property", property);
s->release();
}
} else {
DBGLOG("iokit @ failed to get %s property", property);
}
return nullptr;
}
int getComputerModel() {
char model[64];
if (getComputerInfo(model, sizeof(model), nullptr, 0) && model[0] != '\0') {
if (strstr(model, "Book", strlen("Book")))
return ComputerModel::ComputerLaptop;
else
return ComputerModel::ComputerDesktop;
}
return ComputerModel::ComputerAny;
}
bool getComputerInfo(char *model, size_t modelsz, char *board, size_t boardsz) {
auto entry = IORegistryEntry::fromPath("/", gIODTPlane);
if (entry) {
if (model && modelsz > 0) {
auto data = OSDynamicCast(OSData, entry->getProperty("model"));
if (data && data->getLength() > 0) {
lilu_os_strlcpy(model, static_cast<const char *>(data->getBytesNoCopy()), modelsz);
} else {
DBGLOG("iokit @ failed to get valid model property");
model[0] = '\0';
}
}
if (board && boardsz > 0) {
auto data = OSDynamicCast(OSData, entry->getProperty("board-id"));
if (data && data->getLength() > 0) {
lilu_os_strlcpy(board, static_cast<const char *>(data->getBytesNoCopy()), boardsz);
} else {
DBGLOG("iokit @ failed to get valid board-id property");
board[0] = '\0';
}
}
entry->release();
return true;
}
DBGLOG("iokit @ failed to get DT entry");
return false;
}
IORegistryEntry *findEntryByPrefix(const char *path, const char *prefix, const IORegistryPlane *plane, bool (*proc)(void *, IORegistryEntry *), bool brute, void *user) {
auto entry = IORegistryEntry::fromPath(path, plane);
if (entry) {
auto res = findEntryByPrefix(entry, prefix, plane, proc, brute, user);
entry->release();
return res;
}
DBGLOG("iokit @ failed to get %s entry", path);
return nullptr;
}
IORegistryEntry *findEntryByPrefix(IORegistryEntry *entry, const char *prefix, const IORegistryPlane *plane, bool (*proc)(void *, IORegistryEntry *), bool brute, void *user) {
bool found {false};
IORegistryEntry *res {nullptr};
size_t bruteCount {0};
do {
bruteCount++;
auto iterator = entry->getChildIterator(plane);
if (iterator) {
size_t len = strlen(prefix);
while ((res = OSDynamicCast(IORegistryEntry, iterator->getNextObject())) != nullptr) {
const char *resname = res->getName();
//DBGLOG("iokit @ iterating over %s", resname);
if (!strncmp(prefix, resname, len)) {
found = proc ? proc(user, res) : true;
if (found) {
if (bruteCount > 1)
DBGLOG("iokit @ bruted %s value in %lu attempts", prefix, bruteCount);
if (!proc) {
break;
}
}
}
}
iterator->release();
} else {
SYSLOG("iokit @ failed to iterate over entry");
return nullptr;
}
} while (brute && bruteCount < bruteMax && !found);
if (!found)
DBGLOG("iokit @ failed to find %s", prefix);
return proc ? nullptr : res;
}
}
| [
"vit9696@users.noreply.github.com"
] | vit9696@users.noreply.github.com |
57c73edf4ce443e0b70ea7c914ee684b4e024786 | a92b18defb50c5d1118a11bc364f17b148312028 | /src/prod/src/data/txnreplicator/loggingreplicator/TestLogRecords.h | c8748042eede56eac327445a5235d0270fef85d0 | [
"MIT"
] | permissive | KDSBest/service-fabric | 34694e150fde662286e25f048fb763c97606382e | fe61c45b15a30fb089ad891c68c893b3a976e404 | refs/heads/master | 2023-01-28T23:19:25.040275 | 2020-11-30T11:11:58 | 2020-11-30T11:11:58 | 301,365,601 | 1 | 0 | MIT | 2020-11-30T11:11:59 | 2020-10-05T10:05:53 | null | UTF-8 | C++ | false | false | 3,190 | h | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace LoggingReplicatorTests
{
class TestLogRecords
: public Data::Utilities::IAsyncEnumerator<Data::LogRecordLib::LogRecord::SPtr>
, public KObject<TestLogRecords>
, public KShared<TestLogRecords>
{
K_FORCE_SHARED(TestLogRecords);
K_SHARED_INTERFACE_IMP(IDisposable)
K_SHARED_INTERFACE_IMP(IAsyncEnumerator)
public: // Statics
static SPtr Create(
__in KAllocator & allocator);
public: // Test APIs.
ULONG GetCount() const;
ULONG GetLogicalLogRecordCount() const;
TxnReplicator::Epoch GetLastEpoch();
FABRIC_SEQUENCE_NUMBER GetLSN();
Data::LogRecordLib::IndexingLogRecord::SPtr GetLastIndexingLogRecord();
Data::LogRecordLib::BackupLogRecord::SPtr GetLastBackupLogRecord();
Data::LogRecordLib::LogRecord::SPtr GetLastLogRecord();
void InitializeWithNewLogRecords();
void PopulateWithRandomRecords(
__in ULONG32 count,
__in_opt bool includeBackup = true,
__in_opt bool includeUpdateEpoch = false);
void AddAtomicOperationLogRecord();
void AddAtomicRedoOperationLogRecord();
Data::LogRecordLib::BackupLogRecord::SPtr AddBackupLogRecord();
void AddBackupLogRecord(
__in Data::LogRecordLib::BackupLogRecord & backupLogRecord);
void AddUpdateEpochLogRecord();
Data::LogRecordLib::BarrierLogRecord::SPtr AddBarrierLogRecord();
void Truncate(
__in FABRIC_SEQUENCE_NUMBER lsn,
__in bool inclusive);
Data::LogRecordLib::ProgressVector::SPtr CopyProgressVector() const;
public: // IAsyncEnumerator
Data::LogRecordLib::LogRecord::SPtr GetCurrent();
ktl::Awaitable<bool> MoveNextAsync(
__in ktl::CancellationToken const & cancellationToken);
void Reset();
public: // IDisposable
void Dispose();
private:
LONG32 currentIndex_ = -1;
volatile LONG64 dataLossNumber_ = 0;
volatile LONG64 configurationNumber_ = 0;
volatile FABRIC_SEQUENCE_NUMBER currentLSN_ = 1;
volatile LONG64 primaryReplicaId_ = 1;
Data::LogRecordLib::ProgressVector::SPtr progressVectorSPtr_ = nullptr;
Data::LogRecordLib::BackupLogRecord::SPtr lastBackupLogRecordSPtr_ = nullptr;
Data::LogRecordLib::BarrierLogRecord::SPtr lastBarrierLogRecordSPtr_ = nullptr;
Data::LogRecordLib::IndexingLogRecord::SPtr lastIndexingLogRecordSPtr_ = nullptr;
Data::LogRecordLib::PhysicalLogRecord::SPtr lastPhysicalLogRecordSPtr = nullptr;
Data::Utilities::OperationData::CSPtr mockPayLoad_;
Data::LogRecordLib::InvalidLogRecords::SPtr const invalidLogRecords_;
KArray<Data::LogRecordLib::LogRecord::SPtr> logRecords_;
Common::Random random_;
};
}
| [
"noreply-sfteam@microsoft.com"
] | noreply-sfteam@microsoft.com |
2d29d849b5e19f37cbca79a5413df2754dbcceeb | 34e9318a626225a79b142b80298370b5d5114eeb | /insertion_sort.cpp | 31405768e19a6d7e81fe56998a12da81ac68ca87 | [] | no_license | Vasav-Y/Cpp-and-DSA-Course-by-Apna-College | eb61abe370655a2a52efad6ab41e404632c7ca94 | 95ef59044fbbf6796b2b9e5ba71b33e148ef23eb | refs/heads/main | 2023-09-04T05:58:45.538042 | 2021-11-09T16:16:00 | 2021-11-09T16:16:00 | 409,480,413 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 748 | cpp | /* INSERTION SORT */
/* Insert an element from unsorted array to its correct position in sorted array */
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter the size of the array : ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array : " << endl;
for (int k = 0; k < n; k++)
{
cin >> arr[k];
}
for (int i = 1; i < n; i++)
{
int current = arr[i];
int j = i -1;
while(arr[j]>current && j>=0)
{
arr[j+1] = arr[j];
j--;
}
arr[j+1] = current;
}
cout << "Elements of array after sorting are : ";
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
return 0;
} | [
"vasav2002@gmail.com"
] | vasav2002@gmail.com |
9ff43ddb87067f796a72c607fe6a7430ab0a457c | b081cb2c14c69be0c5e0feb437c5f8a50be70787 | /level/tile/CactusTile.h | 60b1f27f72519bd3318013f0f92d2abd72cc3f91 | [] | no_license | konchunas/minicraft-psp | 9747239fb941ecd67ac90ec47a4b61b7b42e9b6d | 532a935da0253f7820dd75ce87012db649fe0b75 | refs/heads/master | 2020-04-13T14:35:25.467035 | 2015-01-09T21:52:26 | 2015-01-09T21:52:26 | 13,645,390 | 9 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 525 | h | #ifndef CACTUSTILE_H_
#define CACTUSTILE_H_
#include "Tile.h"
class Level;
class Entity;
class Screen;
class CactusTile : public Tile {
public:
CactusTile(int id);
virtual ~CactusTile();
void render(Screen * screen, Level * level, int x, int y);
bool mayPass(Level * level, int x, int y, Entity * e);
void hurt(Level * level, int x, int y, Mob * source, int dmg, int attackDir);
void bumpedInto(Level * level, int x, int y, Entity * entity);
void tick(Level * level, int xt, int yt);
};
#endif /* CACTUSTILE_H_ */
| [
"konchunas@trueconf.ru"
] | konchunas@trueconf.ru |
92adffbd4b3eb0e870478017e621d7d6cc99f35a | dd7b00f36fd78fc3426454f1c99968e1aa00efd3 | /libraries/Math/Vector3.h | 43023f7272cd8274175f0e3ec875893966a8625b | [] | no_license | cuav/MAAT | 3a9eff4e5ed877fd56c8429478ada2e467dcfe4a | 4fe1b8ec868e3cfdc0ecf7ce96c35740bd3e6629 | refs/heads/master | 2020-06-02T09:09:52.607898 | 2015-10-13T07:22:48 | 2015-10-13T07:22:48 | 42,920,864 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,976 | h | #ifndef VECTOR3_H
#define VECTOR3_H
#include <math.h>
#include <stdlib.h>
#include "rotations.h"
#define HALF_SQRT_2 0.70710678118654757
template <typename T>
class Vector3
{
public:
T x, y, z;
// trivial ctor
Vector3<T>()
{
x = y = z = 0;
}
// setting ctor
Vector3<T>(const T x0, const T y0, const T z0): x(x0), y(y0), z(z0) {}
// function call operator
void operator ()(const T x0, const T y0, const T z0)
{
x= x0;
y= y0;
z= z0;
}
/*
T& operator[](uint8_t idx)
{
switch (idx)
{
case 0:
return x;
case 1:
return y;
case 2:
return z;
default:
return x;
}
}*/
// test for equality
bool operator ==(const Vector3<T> &v)
{
return (x==v.x && y==v.y && z==v.z);
}
// test for inequality
bool operator !=(const Vector3<T> &v)
{
return (x!=v.x || y!=v.y || z!=v.z);
}
// negation
Vector3<T> operator -(void) const
{
return Vector3<T>(-x,-y,-z);
}
// addition
Vector3<T> operator +(const Vector3<T> &v) const
{
return Vector3<T>(x+v.x, y+v.y, z+v.z);
}
// subtraction
Vector3<T> operator -(const Vector3<T> &v) const
{
return Vector3<T>(x-v.x, y-v.y, z-v.z);
}
// uniform scaling
Vector3<T> operator *(const T num) const
{
Vector3<T> temp(*this);
return temp*=num;
}
// uniform scaling
Vector3<T> operator /(const T num) const
{
Vector3<T> temp(*this);
return temp/=num;
}
// addition
Vector3<T> &operator +=(const Vector3<T> &v)
{
x+=v.x;
y+=v.y;
z+=v.z;
return *this;
}
// subtraction
Vector3<T> &operator -=(const Vector3<T> &v)
{
x-=v.x;
y-=v.y;
z-=v.z;
return *this;
}
// uniform scaling
Vector3<T> &operator *=(const T num)
{
x*=num;
y*=num;
z*=num;
return *this;
}
// uniform scaling
Vector3<T> &operator /=(const T num)
{
x/=num;
y/=num;
z/=num;
return *this;
}
// dot product
T operator *(const Vector3<T> &v) const
{
return x*v.x + y*v.y + z*v.z;
}
// cross product
Vector3<T> operator ^(const Vector3<T> &v) const
{
Vector3<T> temp(y*v.z - z*v.y, z*v.x - x*v.z, x*v.y - y*v.x);
return temp;
}
void add(const T& x, const T& y, const T& z)
{
this->x += x;
this->y += y;
this->z += z;
}
// gets the length of this vector squared
T length_squared() const
{
return (T)(*this * *this);
}
// gets the length of this vector
float length() const
{
return (T)sqrt(*this * *this);
}
// normalizes this vector
void normalize()
{
*this/=length();
}
// zero the vector
void zero()
{
x = y = z = 0.0;
}
// returns the normalized version of this vector
Vector3<T> normalized() const
{
return *this/length();
}
// reflects this vector about n
void reflect(const Vector3<T> &n)
{
Vector3<T> orig(*this);
project(n);
*this= *this*2 - orig;
}
// projects this vector onto v
void project(const Vector3<T> &v)
{
*this= v * (*this * v)/(v*v);
}
// returns this vector projected onto v
Vector3<T> projected(const Vector3<T> &v)
{
return v * (*this * v)/(v*v);
}
// computes the angle between 2 arbitrary vectors
T angle(const Vector3<T> &v1, const Vector3<T> &v2)
{
return (T)acosf((v1*v2) / (v1.length()*v2.length()));
}
// computes the angle between 2 arbitrary normalized vectors
T angle_normalized(const Vector3<T> &v1, const Vector3<T> &v2)
{
return (T)acosf(v1*v2);
}
// check if any elements are NAN
bool is_nan(void)
{
return isnan(x) || isnan(y) || isnan(z);
}
// check if any elements are infinity
bool is_inf(void)
{
return isinf(x) || isinf(y) || isinf(z);
}
// rotate by a standard rotation
void rotate(enum Rotation rotation)
{
T tmp;
switch (rotation)
{
case ROTATION_NONE:
case ROTATION_MAX:
return;
case ROTATION_YAW_45:
{
tmp = HALF_SQRT_2*(x - y);
y = HALF_SQRT_2*(x + y);
x = tmp;
return;
}
case ROTATION_YAW_90:
{
tmp = x;
x = -y;
y = tmp;
return;
}
case ROTATION_YAW_135:
{
tmp = -HALF_SQRT_2*(x + y);
y = HALF_SQRT_2*(x - y);
x = tmp;
return;
}
case ROTATION_YAW_180:
x = -x;
y = -y;
return;
case ROTATION_YAW_225:
{
tmp = HALF_SQRT_2*(y - x);
y = -HALF_SQRT_2*(x + y);
x = tmp;
return;
}
case ROTATION_YAW_270:
{
tmp = x;
x = y;
y = -tmp;
return;
}
case ROTATION_YAW_315:
{
tmp = HALF_SQRT_2*(x + y);
y = HALF_SQRT_2*(y - x);
x = tmp;
return;
}
case ROTATION_ROLL_180:
{
y = -y;
z = -z;
return;
}
case ROTATION_ROLL_180_YAW_45:
{
tmp = HALF_SQRT_2*(x + y);
y = HALF_SQRT_2*(x - y);
x = tmp;
z = -z;
return;
}
case ROTATION_ROLL_180_YAW_90:
{
tmp = x;
x = y;
y = tmp;
z = -z;
return;
}
case ROTATION_ROLL_180_YAW_135:
{
tmp = HALF_SQRT_2*(y - x);
y = HALF_SQRT_2*(y + x);
x = tmp;
z = -z;
return;
}
case ROTATION_PITCH_180:
{
x = -x;
z = -z;
return;
}
case ROTATION_ROLL_180_YAW_225:
{
tmp = -HALF_SQRT_2*(x + y);
y = HALF_SQRT_2*(y - x);
x = tmp;
z = -z;
return;
}
case ROTATION_ROLL_180_YAW_270:
{
tmp = x;
x = -y;
y = -tmp;
z = -z;
return;
}
case ROTATION_ROLL_180_YAW_315:
{
tmp = HALF_SQRT_2*(x - y);
y = -HALF_SQRT_2*(x + y);
x = tmp;
z = -z;
return;
}
}
}
};
typedef Vector3<float> Vector3f;
typedef Vector3<int16_t> Vector3i;
#endif
| [
"admin@cuav.net"
] | admin@cuav.net |
2e02238147a4ce8f07f89511e5d23c6d45b1cdb9 | 6b0344f06cfe9241e5d10aef24552949063de391 | /deps/imgui_impl/imgui_impl_opengl3.cpp | 956574d4a44d512e9e53dc7e59636a92664e4df3 | [] | no_license | knut0815/Pong3D | 7c606251537f63269be96151c8e052dffd062de5 | a715ebc7fc5f742568187e77cf6718ceeb606edd | refs/heads/master | 2023-03-19T07:32:28.924765 | 2021-03-11T14:21:12 | 2021-03-11T14:21:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,559 | cpp | // dear imgui: Renderer for modern OpenGL with shaders / programmatic pipeline
// - Desktop GL: 2.x 3.x 4.x
// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
// This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..)
// Implemented features:
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as
// void*/ImTextureID. Read the FAQ about ImTextureID! [x] Renderer: Desktop GL only:
// Support for large meshes (64k+ vertices) with 16-bit indices.
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an
// example of using this. If you are new to dear imgui, read examples/README.txt and read
// the documentation at the top of imgui.cpp. https://github.com/ocornut/imgui
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2020-07-10: OpenGL: Added support for glad2 OpenGL loader.
// 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX.
// 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting
// projection matrix. 2020-04-12: OpenGL: Fixed context version check mistakenly testing
// for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset. 2020-03-24:
// OpenGL: Added support for glbinding 2.x OpenGL loader. 2020-01-07: OpenGL: Added
// support for glbinding 3.x OpenGL loader. 2019-10-25: OpenGL: Using a combination of GL
// define and runtime GL version to decide whether to use glDrawElementsBaseVertex(). Fix
// building with pre-3.2 GL loaders. 2019-09-22: OpenGL: Detect default GL loader using
// __has_include compiler facility. 2019-09-16: OpenGL: Tweak initialization code to
// allow application calling ImGui_ImplOpenGL3_CreateFontsTexture() before the first
// NewFrame() call. 2019-05-29: OpenGL: Desktop GL only: Added support for large mesh
// (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. 2019-04-30:
// OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset
// render state. 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the
// render loop. 2019-03-15: OpenGL: Added a dummy GL call + comments in
// ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early.
// 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0).
// 2019-02-20: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read
// GL_CLIP_ORIGIN even if defined by the headers/loader. 2019-02-11: OpenGL: Projecting
// clipping rectangles correctly using draw_data->FramebufferScale to allow
// multi-viewports for retina display. 2019-02-01: OpenGL: Using GLSL 410 shaders for any
// version over 410 (e.g. 430, 450). 2018-11-30: Misc: Setting up io.BackendRendererName
// so it can be displayed in the About Window. 2018-11-13: OpenGL: Support for GL 4.5's
// glClipControl(GL_UPPER_LEFT) / GL_CLIP_ORIGIN. 2018-08-29: OpenGL: Added support for
// more OpenGL loaders: glew and glad, with comments indicative that any loader can be
// used. 2018-08-09: OpenGL: Default to OpenGL ES 3 on iOS and Android. GLSL version
// default to "#version 300 ES". 2018-07-30: OpenGL: Support for GLSL 300 ES and 410
// core. Fixes for Emscripten compilation. 2018-07-10: OpenGL: Support for more GLSL
// versions (based on the GLSL version string). Added error output when shaders fail to
// compile/link. 2018-06-08: Misc: Extracted imgui_impl_opengl3.cpp/.h away from the old
// combined GLFW/SDL+OpenGL3 examples. 2018-06-08: OpenGL: Use draw_data->DisplayPos and
// draw_data->DisplaySize to setup projection matrix and clipping rectangle. 2018-05-25:
// OpenGL: Removed unnecessary backup/restore of GL_ELEMENT_ARRAY_BUFFER_BINDING since
// this is part of the VAO state. 2018-05-14: OpenGL: Making the call to glBindSampler()
// optional so 3.2 context won't fail if the function is a NULL pointer. 2018-03-06:
// OpenGL: Added const char* glsl_version parameter to ImGui_ImplOpenGL3_Init() so user
// can override the GLSL version e.g. "#version 150". 2018-02-23: OpenGL: Create the VAO
// in the render function so the setup can more easily be used with multiple shared GL
// context. 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed
// ImGui_ImplSdlGL3_RenderDrawData() in the .h file so you can call it yourself.
// 2018-01-07: OpenGL: Changed GLSL shader version from 330 to 150.
// 2017-09-01: OpenGL: Save and restore current bound sampler. Save and restore current
// polygon mode. 2017-05-01: OpenGL: Fixed save and restore of current blend func state.
// 2017-05-01: OpenGL: Fixed save and restore of current GL_ACTIVE_TEXTURE.
// 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
// 2016-07-29: OpenGL: Explicitly setting GL_UNPACK_ROW_LENGTH to reduce issues because
// SDL changes it. (#752)
//----------------------------------------
// OpenGL GLSL GLSL
// version version string
//----------------------------------------
// 2.0 110 "#version 110"
// 2.1 120 "#version 120"
// 3.0 130 "#version 130"
// 3.1 140 "#version 140"
// 3.2 150 "#version 150"
// 3.3 330 "#version 330 core"
// 4.0 400 "#version 400 core"
// 4.1 410 "#version 410 core"
// 4.2 420 "#version 410 core"
// 4.3 430 "#version 430 core"
// ES 2.0 100 "#version 100" = WebGL 1.0
// ES 3.0 300 "#version 300 es" = WebGL 2.0
//----------------------------------------
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui_impl_opengl3.h"
#include "../imgui/imgui.h"
#include <stdio.h>
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
// Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have.
#if defined(IMGUI_IMPL_OPENGL_ES2) || defined(IMGUI_IMPL_OPENGL_ES3) || \
!defined(GL_VERSION_3_2)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET 0
#else
#define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET 1
#endif
// OpenGL Data
static GLuint g_GlVersion = 0; // Extracted at runtime using GL_MAJOR_VERSION,
// GL_MINOR_VERSION queries (e.g. 320 for GL 3.2)
static char g_GlslVersionString[32] =
""; // Specified by user or detected based on compile time GL settings.
static GLuint g_FontTexture = 0;
static GLuint g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
static GLint g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; // Uniforms location
static GLuint g_AttribLocationVtxPos = 0, g_AttribLocationVtxUV = 0,
g_AttribLocationVtxColor = 0; // Vertex attributes location
static unsigned int g_VboHandle = 0, g_ElementsHandle = 0;
// Functions
bool ImGui_ImplOpenGL3_Init(const char* glsl_version)
{
// Query for GL version (e.g. 320 for GL 3.2)
#if !defined(IMGUI_IMPL_OPENGL_ES2)
GLint major, minor;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
g_GlVersion = (GLuint)(major * 100 + minor * 10);
#else
g_GlVersion = 200; // GLES 2
#endif
// Setup back-end capabilities flags
ImGuiIO& io = ImGui::GetIO();
io.BackendRendererName = "imgui_impl_opengl3";
#if IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
if (g_GlVersion >= 320)
io.BackendFlags |=
ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the
// ImDrawCmd::VtxOffset field,
// allowing for large meshes.
#endif
// Store GLSL version string so we can refer to it later in case we recreate
// shaders. Note: GLSL version is NOT the same as GL version. Leave this to NULL
// if unsure.
#if defined(IMGUI_IMPL_OPENGL_ES2)
if (glsl_version == NULL)
glsl_version = "#version 100";
#elif defined(IMGUI_IMPL_OPENGL_ES3)
if (glsl_version == NULL)
glsl_version = "#version 300 es";
#elif defined(__APPLE__)
if (glsl_version == NULL)
glsl_version = "#version 150";
#else
if (glsl_version == NULL)
glsl_version = "#version 130";
#endif
IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(g_GlslVersionString));
strcpy(g_GlslVersionString, glsl_version);
strcat(g_GlslVersionString, "\n");
// Dummy construct to make it easily visible in the IDE and debugger which GL loader
// has been selected. The code actually never uses the 'gl_loader' variable! It is
// only here so you can read it! If auto-detection fails or doesn't select the same GL
// loader file as used by your application, you are likely to get a crash below. You
// can explicitly select a loader by using '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in
// imconfig.h or compiler command-line.
const char* gl_loader = "Unknown";
IM_UNUSED(gl_loader);
#if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W)
gl_loader = "GL3W";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW)
gl_loader = "GLEW";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD)
gl_loader = "GLAD";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2)
gl_loader = "GLAD2";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2)
gl_loader = "glbinding2";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3)
gl_loader = "glbinding3";
#elif defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM)
gl_loader = "custom";
#else
gl_loader = "none";
#endif
// Make a dummy GL call (we don't actually need the result)
// IF YOU GET A CRASH HERE: it probably means that you haven't initialized the OpenGL
// function loader used by this code. Desktop OpenGL 3/4 need a function loader. See
// the IMGUI_IMPL_OPENGL_LOADER_xxx explanation above.
GLint current_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, ¤t_texture);
return true;
}
void ImGui_ImplOpenGL3_Shutdown()
{
ImGui_ImplOpenGL3_DestroyDeviceObjects();
}
void ImGui_ImplOpenGL3_NewFrame()
{
if (!g_ShaderHandle)
ImGui_ImplOpenGL3_CreateDeviceObjects();
}
static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width,
int fb_height, GLuint vertex_array_object)
{
// Setup render state: alpha-blending enabled, no face culling, no depth testing,
// scissor enabled, polygon fill
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
#ifdef GL_POLYGON_MODE
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
#endif
// Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT)
bool clip_origin_lower_left = true;
#if defined(GL_CLIP_ORIGIN) && !defined(__APPLE__)
GLenum current_clip_origin = 0;
glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)¤t_clip_origin);
if (current_clip_origin == GL_UPPER_LEFT)
clip_origin_lower_left = false;
#endif
// Setup viewport, orthographic projection matrix
// Our visible imgui space lies from draw_data->DisplayPos (top left) to
// draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0)
// for single viewport apps.
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
float L = draw_data->DisplayPos.x;
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
float T = draw_data->DisplayPos.y;
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
if (!clip_origin_lower_left) {
float tmp = T;
T = B;
B = tmp;
} // Swap top and bottom if origin is upper left
const float ortho_projection[4][4] = {
{2.0f / (R - L), 0.0f, 0.0f, 0.0f},
{0.0f, 2.0f / (T - B), 0.0f, 0.0f},
{0.0f, 0.0f, -1.0f, 0.0f},
{(R + L) / (L - R), (T + B) / (B - T), 0.0f, 1.0f},
};
glUseProgram(g_ShaderHandle);
glUniform1i(g_AttribLocationTex, 0);
glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
#ifdef GL_SAMPLER_BINDING
glBindSampler(0, 0); // We use combined texture/sampler state. Applications using
// GL 3.3 may set that otherwise.
#endif
(void)vertex_array_object;
#ifndef IMGUI_IMPL_OPENGL_ES2
glBindVertexArray(vertex_array_object);
#endif
// Bind vertex/index buffers and setup attributes for ImDrawVert
glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
glEnableVertexAttribArray(g_AttribLocationVtxPos);
glEnableVertexAttribArray(g_AttribLocationVtxUV);
glEnableVertexAttribArray(g_AttribLocationVtxColor);
glVertexAttribPointer(g_AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE,
sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos));
glVertexAttribPointer(g_AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE,
sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv));
glVertexAttribPointer(g_AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE,
sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col));
}
// OpenGL3 Render function.
// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can
// now call this directly from your main loop) Note that this implementation is little
// overcomplicated because we are saving/setting up/restoring every OpenGL state
// explicitly, in order to be able to run within any OpenGL engine that doesn't do so.
void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen
// coordinates != framebuffer coordinates)
int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
if (fb_width <= 0 || fb_height <= 0)
return;
// Backup GL state
GLenum last_active_texture;
glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture);
glActiveTexture(GL_TEXTURE0);
GLuint last_program;
glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program);
GLuint last_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture);
#ifdef GL_SAMPLER_BINDING
GLuint last_sampler;
glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler);
#endif
GLuint last_array_buffer;
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer);
#ifndef IMGUI_IMPL_OPENGL_ES2
GLuint last_vertex_array_object;
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object);
#endif
#ifdef GL_POLYGON_MODE
GLint last_polygon_mode[2];
glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
#endif
GLint last_viewport[4];
glGetIntegerv(GL_VIEWPORT, last_viewport);
GLint last_scissor_box[4];
glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
GLenum last_blend_src_rgb;
glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb);
GLenum last_blend_dst_rgb;
glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb);
GLenum last_blend_src_alpha;
glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha);
GLenum last_blend_dst_alpha;
glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha);
GLenum last_blend_equation_rgb;
glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb);
GLenum last_blend_equation_alpha;
glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha);
GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
// Setup desired GL state
// Recreate the VAO every time (this is to easily allow multiple GL contexts to be
// rendered to. VAO are not shared among GL contexts) The renderer would actually work
// without any VAO bound, but then our VertexAttrib calls would overwrite the default
// one currently bound.
GLuint vertex_array_object = 0;
#ifndef IMGUI_IMPL_OPENGL_ES2
glGenVertexArrays(1, &vertex_array_object);
#endif
ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height,
vertex_array_object);
// Will project scissor/clipping rectangles into framebuffer space
ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
ImVec2 clip_scale =
draw_data
->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
// Render command lists
for (int n = 0; n < draw_data->CmdListsCount; n++) {
const ImDrawList* cmd_list = draw_data->CmdLists[n];
// Upload vertex/index buffers
glBufferData(GL_ARRAY_BUFFER,
(GLsizeiptr)cmd_list->VtxBuffer.Size * (int)sizeof(ImDrawVert),
(const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
(GLsizeiptr)cmd_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx),
(const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW);
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) {
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback != NULL) {
// User callback, registered via ImDrawList::AddCallback()
// (ImDrawCallback_ResetRenderState is a special callback value used by
// the user to request the renderer to reset render state.)
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height,
vertex_array_object);
else
pcmd->UserCallback(cmd_list, pcmd);
}
else {
// Project scissor/clipping rectangles into framebuffer space
ImVec4 clip_rect;
clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x;
clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y;
clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x;
clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y;
if (clip_rect.x < fb_width && clip_rect.y < fb_height &&
clip_rect.z >= 0.0f && clip_rect.w >= 0.0f) {
// Apply scissor/clipping rectangle
glScissor((int)clip_rect.x, (int)(fb_height - clip_rect.w),
(int)(clip_rect.z - clip_rect.x),
(int)(clip_rect.w - clip_rect.y));
// Bind texture, Draw
glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
#if IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
if (g_GlVersion >= 320)
glDrawElementsBaseVertex(
GL_TRIANGLES, (GLsizei)pcmd->ElemCount,
sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
(void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)),
(GLint)pcmd->VtxOffset);
else
#endif
glDrawElements(
GL_TRIANGLES, (GLsizei)pcmd->ElemCount,
sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
(void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)));
}
}
}
}
// Destroy the temporary VAO
#ifndef IMGUI_IMPL_OPENGL_ES2
glDeleteVertexArrays(1, &vertex_array_object);
#endif
// Restore modified GL state
glUseProgram(last_program);
glBindTexture(GL_TEXTURE_2D, last_texture);
#ifdef GL_SAMPLER_BINDING
glBindSampler(0, last_sampler);
#endif
glActiveTexture(last_active_texture);
#ifndef IMGUI_IMPL_OPENGL_ES2
glBindVertexArray(last_vertex_array_object);
#endif
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha,
last_blend_dst_alpha);
if (last_enable_blend)
glEnable(GL_BLEND);
else
glDisable(GL_BLEND);
if (last_enable_cull_face)
glEnable(GL_CULL_FACE);
else
glDisable(GL_CULL_FACE);
if (last_enable_depth_test)
glEnable(GL_DEPTH_TEST);
else
glDisable(GL_DEPTH_TEST);
if (last_enable_scissor_test)
glEnable(GL_SCISSOR_TEST);
else
glDisable(GL_SCISSOR_TEST);
#ifdef GL_POLYGON_MODE
glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]);
#endif
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2],
(GLsizei)last_viewport[3]);
glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2],
(GLsizei)last_scissor_box[3]);
}
bool ImGui_ImplOpenGL3_CreateFontsTexture()
{
// Build texture atlas
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(
&pixels, &width,
&height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is
// so small) because it is more likely to be compatible with user's
// existing shaders. If your ImTextureId represent a higher-level
// concept than just a GL texture id, consider calling
// GetTexDataAsAlpha8() instead to save on GPU memory.
// Upload texture to graphics system
GLint last_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGenTextures(1, &g_FontTexture);
glBindTexture(GL_TEXTURE_2D, g_FontTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#ifdef GL_UNPACK_ROW_LENGTH
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
#endif
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
pixels);
// Store our identifier
io.Fonts->TexID = (ImTextureID)(intptr_t)g_FontTexture;
// Restore state
glBindTexture(GL_TEXTURE_2D, last_texture);
return true;
}
void ImGui_ImplOpenGL3_DestroyFontsTexture()
{
if (g_FontTexture) {
ImGuiIO& io = ImGui::GetIO();
glDeleteTextures(1, &g_FontTexture);
io.Fonts->TexID = 0;
g_FontTexture = 0;
}
}
// If you get an error please report on github. You may try different GL context version
// or GLSL version. See GL<>GLSL version table at the top of this file.
static bool CheckShader(GLuint handle, const char* desc)
{
GLint status = 0, log_length = 0;
glGetShaderiv(handle, GL_COMPILE_STATUS, &status);
glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length);
if ((GLboolean)status == GL_FALSE)
fprintf(stderr,
"ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile %s!\n",
desc);
if (log_length > 1) {
ImVector<char> buf;
buf.resize((int)(log_length + 1));
glGetShaderInfoLog(handle, log_length, NULL, (GLchar*)buf.begin());
fprintf(stderr, "%s\n", buf.begin());
}
return (GLboolean)status == GL_TRUE;
}
// If you get an error please report on GitHub. You may try different GL context version
// or GLSL version.
static bool CheckProgram(GLuint handle, const char* desc)
{
GLint status = 0, log_length = 0;
glGetProgramiv(handle, GL_LINK_STATUS, &status);
glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length);
if ((GLboolean)status == GL_FALSE)
fprintf(stderr,
"ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link %s! (with "
"GLSL '%s')\n",
desc, g_GlslVersionString);
if (log_length > 1) {
ImVector<char> buf;
buf.resize((int)(log_length + 1));
glGetProgramInfoLog(handle, log_length, NULL, (GLchar*)buf.begin());
fprintf(stderr, "%s\n", buf.begin());
}
return (GLboolean)status == GL_TRUE;
}
bool ImGui_ImplOpenGL3_CreateDeviceObjects()
{
// Backup GL state
GLint last_texture, last_array_buffer;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
#ifndef IMGUI_IMPL_OPENGL_ES2
GLint last_vertex_array;
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
#endif
// Parse GLSL version string
int glsl_version = 130;
sscanf(g_GlslVersionString, "#version %d", &glsl_version);
const GLchar* vertex_shader_glsl_120 =
"uniform mat4 ProjMtx;\n"
"attribute vec2 Position;\n"
"attribute vec2 UV;\n"
"attribute vec4 Color;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_130 =
"uniform mat4 ProjMtx;\n"
"in vec2 Position;\n"
"in vec2 UV;\n"
"in vec4 Color;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_300_es =
"precision mediump float;\n"
"layout (location = 0) in vec2 Position;\n"
"layout (location = 1) in vec2 UV;\n"
"layout (location = 2) in vec4 Color;\n"
"uniform mat4 ProjMtx;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_410_core =
"layout (location = 0) in vec2 Position;\n"
"layout (location = 1) in vec2 UV;\n"
"layout (location = 2) in vec4 Color;\n"
"uniform mat4 ProjMtx;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* fragment_shader_glsl_120 =
"#ifdef GL_ES\n"
" precision mediump float;\n"
"#endif\n"
"uniform sampler2D Texture;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_130 =
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_300_es =
"precision mediump float;\n"
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"layout (location = 0) out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_410_core =
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"uniform sampler2D Texture;\n"
"layout (location = 0) out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
// Select shaders matching our GLSL versions
const GLchar* vertex_shader = NULL;
const GLchar* fragment_shader = NULL;
if (glsl_version < 130) {
vertex_shader = vertex_shader_glsl_120;
fragment_shader = fragment_shader_glsl_120;
}
else if (glsl_version >= 410) {
vertex_shader = vertex_shader_glsl_410_core;
fragment_shader = fragment_shader_glsl_410_core;
}
else if (glsl_version == 300) {
vertex_shader = vertex_shader_glsl_300_es;
fragment_shader = fragment_shader_glsl_300_es;
}
else {
vertex_shader = vertex_shader_glsl_130;
fragment_shader = fragment_shader_glsl_130;
}
// Create shaders
const GLchar* vertex_shader_with_version[2] = {g_GlslVersionString, vertex_shader};
g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(g_VertHandle, 2, vertex_shader_with_version, NULL);
glCompileShader(g_VertHandle);
CheckShader(g_VertHandle, "vertex shader");
const GLchar* fragment_shader_with_version[2] = {g_GlslVersionString,
fragment_shader};
g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(g_FragHandle, 2, fragment_shader_with_version, NULL);
glCompileShader(g_FragHandle);
CheckShader(g_FragHandle, "fragment shader");
g_ShaderHandle = glCreateProgram();
glAttachShader(g_ShaderHandle, g_VertHandle);
glAttachShader(g_ShaderHandle, g_FragHandle);
glLinkProgram(g_ShaderHandle);
CheckProgram(g_ShaderHandle, "shader program");
g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
g_AttribLocationVtxPos = (GLuint)glGetAttribLocation(g_ShaderHandle, "Position");
g_AttribLocationVtxUV = (GLuint)glGetAttribLocation(g_ShaderHandle, "UV");
g_AttribLocationVtxColor = (GLuint)glGetAttribLocation(g_ShaderHandle, "Color");
// Create buffers
glGenBuffers(1, &g_VboHandle);
glGenBuffers(1, &g_ElementsHandle);
ImGui_ImplOpenGL3_CreateFontsTexture();
// Restore modified GL state
glBindTexture(GL_TEXTURE_2D, last_texture);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
#ifndef IMGUI_IMPL_OPENGL_ES2
glBindVertexArray(last_vertex_array);
#endif
return true;
}
void ImGui_ImplOpenGL3_DestroyDeviceObjects()
{
if (g_VboHandle) {
glDeleteBuffers(1, &g_VboHandle);
g_VboHandle = 0;
}
if (g_ElementsHandle) {
glDeleteBuffers(1, &g_ElementsHandle);
g_ElementsHandle = 0;
}
if (g_ShaderHandle && g_VertHandle) {
glDetachShader(g_ShaderHandle, g_VertHandle);
}
if (g_ShaderHandle && g_FragHandle) {
glDetachShader(g_ShaderHandle, g_FragHandle);
}
if (g_VertHandle) {
glDeleteShader(g_VertHandle);
g_VertHandle = 0;
}
if (g_FragHandle) {
glDeleteShader(g_FragHandle);
g_FragHandle = 0;
}
if (g_ShaderHandle) {
glDeleteProgram(g_ShaderHandle);
g_ShaderHandle = 0;
}
ImGui_ImplOpenGL3_DestroyFontsTexture();
} | [
"mhopson@hotmail.co.uk"
] | mhopson@hotmail.co.uk |
62eaffed03920d48e90647449003d0914c7ba59c | e217eaf05d0dab8dd339032b6c58636841aa8815 | /external/Oklabi/Util/J_Eingabe.cpp | 67e7ae2a2345fbc6216bafd8aa438c06733b375a | [] | no_license | bigdoods/OpenInfraPlatform | f7785ebe4cb46e24d7f636e1b4110679d78a4303 | 0266e86a9f25f2ea9ec837d8d340d31a58a83c8e | refs/heads/master | 2021-01-21T03:41:20.124443 | 2016-01-26T23:20:21 | 2016-01-26T23:20:21 | 57,377,206 | 0 | 1 | null | 2016-04-29T10:38:19 | 2016-04-29T10:38:19 | null | ISO-8859-1 | C++ | false | false | 4,725 | cpp | /*****************************************************************************
* $Id: J_Eingabe.cpp 2013-01-24 15:00:00 vogelsang $
* $Paket: Oklabi-Util $
*
* Projekt: OKSTRA Klassenbibliothek
* Realisiert: C++ API zum "Objektkatalog für das Straßen- und Verkehrswesen"
* Autor: Arnold Vogelsang, vogelsang@interactive-instruments.de
*
******************************************************************************
* Copyright (c) 2010-2013, Bundesanstalt für Straßenwesen
*
* Erstellt durch interactive instruments GmbH, Bonn
*
* Die Nutzungsbestimmungen für die Software und die zugehörigen Bestandteile
* sind unter folgender Adresse einsehbar:
* http://www.okstra.de/oklabi/Lizenz/Nutzung.txt
*
* Der Hinweis auf das Copyright und die Lizenzbestimmungen ist in allen
* Kopien der Software oder wesentlichen Bestandteilen daraus aufzunehmen.
*
* Die Erklärungen zum Gewährleistungsausschluß und zur Haftungsbegrenzung
* befinden sich bei den Nutzungsbestimmungen.
*
* 2012-07-27 Interface umbenannt
* 2012-10-15 Aufräumen bei Programmende
* 2013-01-24 Zeichenkodierung
*
****************************************************************************/
#include "OklabiMgd.h"
#include "J_Eingabe.h"
#include "Umgebung.h"
using namespace Oklabi;
using namespace std;
void* CALLBACK _J_Eingabe_Erzeuge(void* JNIEnv, void* JOBJECT)
{
return J_Eingabe::Erzeuge(JNIEnv, JOBJECT);
}
static bool istInitialisiert = OklabiJava::Registriere("J_Eingabe", &_J_Eingabe_Erzeuge);
void J_Eingabe::Registriere()
{
OklabiJava::Registriere("J_Eingabe", &_J_Eingabe_Erzeuge);
}
J_Eingabe::J_Eingabe(void* JNIEnv, void* JOBJECT) : OklabiJava(JNIEnv,JOBJECT),
m_pCallbackEingabeOeffne(0), m_pCallbackEingabeSchliesse(0), m_pCallbackEingabeLiesZeichen(0), m_pCallbackEingabeGibAnzahl(0),
m_pCallbackEingabeIstBeendet(0), m_pCallbackEingabeIstGueltig(0), m_pCallbackEingabeZumAnfang(0)
{
}
J_Eingabe::~J_Eingabe()
{
}
Eingabe* J_Eingabe::Erzeuge(void* JNIEnv, void* JOBJECT)
{
return new J_Eingabe(JNIEnv, JOBJECT);
}
Text J_Eingabe::GibKlassenname() const
{
return "J_Eingabe";
}
Text J_Eingabe::GibBeschreibung() const
{
return "J_Eingabe";
}
void J_Eingabe::Oeffne()
{
if (m_pCallbackEingabeOeffne)
{
m_pCallbackEingabeOeffne(m_JNIEnv, m_JOBJECT, "Eingabe", "Oeffne");
}
}
void J_Eingabe::Schliesse()
{
if (m_pCallbackEingabeSchliesse)
{
m_pCallbackEingabeSchliesse(m_JNIEnv, m_JOBJECT, "Eingabe", "Schliesse");
}
}
int J_Eingabe::LiesZeichen()
{
if (m_pCallbackEingabeLiesZeichen)
{
return m_pCallbackEingabeLiesZeichen(m_JNIEnv, m_JOBJECT, "Eingabe", "LiesZeichen");
}
return Oklabi::eof;
}
size_t J_Eingabe::GibAnzahl()
{
if (m_pCallbackEingabeGibAnzahl)
{
return (size_t)m_pCallbackEingabeGibAnzahl(m_JNIEnv, m_JOBJECT, "Eingabe", "GibAnzahl");
}
return 0;
}
size_t J_Eingabe::GibZeilen()
{
// TODO: Ausfüllen
return 0;
}
bool J_Eingabe::IstBeendet()
{
if (m_pCallbackEingabeIstBeendet)
{
return m_pCallbackEingabeIstBeendet(m_JNIEnv, m_JOBJECT, "Eingabe", "IstBeendet");
}
return 0;
}
void J_Eingabe::SetzeKodierung(eKodierung eKod)
{
Eingabe::SetzeKodierung(eKod);
if (m_pCallbackEingabeSetzeKodierung)
{
return m_pCallbackEingabeSetzeKodierung(m_JNIEnv, m_JOBJECT, "Eingabe", "SetzeKodierung", eKod);
}
}
bool J_Eingabe::IstGueltig()
{
if (m_pCallbackEingabeIstGueltig)
{
return m_pCallbackEingabeIstGueltig(m_JNIEnv, m_JOBJECT, "Eingabe", "IstGueltig");
}
return 0;
}
void J_Eingabe::ZumAnfang()
{
if (m_pCallbackEingabeZumAnfang)
{
m_pCallbackEingabeZumAnfang(m_JNIEnv, m_JOBJECT, "Eingabe", "ZumAnfang");
}
}
void SetzeCallbackEingabeJava(void* pObj,
void (CALLBACK* fctOeffne)(void*, void*, const char*, const char*),
void (CALLBACK* fctSchliesse)(void*, void*, const char*, const char*),
int (CALLBACK* fctLiesZeichen)(void*, void*, const char*, const char*),
int (CALLBACK* fctGibAnzahl)(void*, void*, const char*, const char*),
bool (CALLBACK* fctIstBeendet)(void*, void*, const char*, const char*),
bool (CALLBACK* fctIstGueltig)(void*, void*, const char*, const char*),
void (CALLBACK* fctZumAnfang)(void*, void*, const char*, const char*),
void (CALLBACK* fctSetzeKodierung)(void*, void*, const char*, const char*, eKodierung))
{
if (pObj)
{
J_Eingabe* pInp = (J_Eingabe*)pObj;
pInp->m_pCallbackEingabeOeffne = fctOeffne;
pInp->m_pCallbackEingabeSchliesse = fctSchliesse;
pInp->m_pCallbackEingabeLiesZeichen = fctLiesZeichen;
pInp->m_pCallbackEingabeGibAnzahl = fctGibAnzahl;
pInp->m_pCallbackEingabeIstBeendet = fctIstBeendet;
pInp->m_pCallbackEingabeIstGueltig = fctIstGueltig;
pInp->m_pCallbackEingabeZumAnfang = fctZumAnfang;
pInp->m_pCallbackEingabeSetzeKodierung = fctSetzeKodierung;
}
}
| [
"planung.cms.bv@tum.de"
] | planung.cms.bv@tum.de |
750b058adc4b0ee470479e825da01aaddbfa9e4f | 0a5645154953b0a09d3f78753a1711aaa76928ff | /common/c/nbui/src/android_ndk/template/NBUITemplateInstantiator.cpp | d495ec4de1e27c83c05d59e279cc007d1aae3c2c | [] | no_license | GENIVI/navigation-next | 3a6f26063350ac8862b4d0e2e9d3522f6f249328 | cb8f7ec5ec4c78ef57aa573315b75960b2a5dd36 | refs/heads/master | 2023-08-04T17:44:45.239062 | 2023-07-25T19:22:19 | 2023-07-25T19:22:19 | 116,230,587 | 17 | 11 | null | 2018-05-18T20:00:38 | 2018-01-04T07:43:22 | C++ | UTF-8 | C++ | false | false | 3,303 | cpp | /*
Copyright (c) 2018, TeleCommunication Systems, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the TeleCommunication Systems, Inc., 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 TELECOMMUNICATION SYSTEMS, INC.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.
*/
/*!--------------------------------------------------------------------------
@file NBUITemplateInistantiator.cpp
@defgroup nbui
Description: Implementation of NBUITemplateInistantiator for iOS.
*/
/*
(C) Copyright 2012 by TeleCommunications Systems, Inc.
The information contained herein is confidential, proprietary to
TeleCommunication Systems, Inc., and considered a trade secret as defined
in section 499C of the penal code of the State of California. Use of this
information by anyone other than authorized employees of TeleCommunication
Systems is granted only under a written non-disclosure agreement, expressly
prescribing the scope and manner of such use.
--------------------------------------------------------------------------*/
/*! @{ */
#include "NBUITemplateInstantiator.h"
#include "pinbubbleresolverandroid.h"
#include "TrafficBubbleProvider.h"
void NBUI_InstantiateTemplates(nbmap::MapServicesConfigurationImpl* configInstance,
NB_Context* context,
shared_ptr<nbmap::PinManager>& pinManager,
nbmap::PinCushion*& pinCushion)
{
if (!configInstance)
{
return;
}
shared_ptr<nbmap::PinBubbleResolver> pinBubbleResolver(new PinBubbleResolverAndroid);
shared_ptr<nbmap::TrafficBubbleProvider> trafficBubbleProvider(new nbmap::TrafficBubbleProvider);
configInstance->CreateAndSpecifyManagers(context,
pinManager,
pinCushion,
pinBubbleResolver,
trafficBubbleProvider);
}
/*! @} */
| [
"caavula@telecomsys.com"
] | caavula@telecomsys.com |
e0b27736eae7e95bcbe0ed7e5ef78e4b65c9288c | e8f271cc7db3fc7aa237ee6c86021b854cd85488 | /turtlebot_navigation_ws/devel/include/networkanalysis_msgs/pingactionGoal.h | fc7b6b05c3da251c45aec3ec73cda03e959bf711 | [] | no_license | ElliWhite/turtlebot2_wss | e14caba73feae01b365dd367918ed3fa9089a531 | 48c1486d8b7450bea99acf4fc5de619a8c9c0188 | refs/heads/master | 2022-01-09T22:36:50.764256 | 2019-05-03T11:17:02 | 2019-05-03T11:17:02 | 177,111,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,525 | h | // Generated by gencpp from file networkanalysis_msgs/pingactionGoal.msg
// DO NOT EDIT!
#ifndef NETWORKANALYSIS_MSGS_MESSAGE_PINGACTIONGOAL_H
#define NETWORKANALYSIS_MSGS_MESSAGE_PINGACTIONGOAL_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace networkanalysis_msgs
{
template <class ContainerAllocator>
struct pingactionGoal_
{
typedef pingactionGoal_<ContainerAllocator> Type;
pingactionGoal_()
: inp(false) {
}
pingactionGoal_(const ContainerAllocator& _alloc)
: inp(false) {
(void)_alloc;
}
typedef uint8_t _inp_type;
_inp_type inp;
typedef boost::shared_ptr< ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator> const> ConstPtr;
}; // struct pingactionGoal_
typedef ::networkanalysis_msgs::pingactionGoal_<std::allocator<void> > pingactionGoal;
typedef boost::shared_ptr< ::networkanalysis_msgs::pingactionGoal > pingactionGoalPtr;
typedef boost::shared_ptr< ::networkanalysis_msgs::pingactionGoal const> pingactionGoalConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace networkanalysis_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'networkanalysis_msgs': ['/home/elliottwhite/turtlebot2_wss/turtlebot_navigation_ws/src/tradr-msgs/networkanalysis_msgs/msg', '/home/elliottwhite/turtlebot2_wss/turtlebot_navigation_ws/devel/share/networkanalysis_msgs/msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator> >
{
static const char* value()
{
return "705bdfa3e0e08abae54f3acdf06f1a9d";
}
static const char* value(const ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x705bdfa3e0e08abaULL;
static const uint64_t static_value2 = 0xe54f3acdf06f1a9dULL;
};
template<class ContainerAllocator>
struct DataType< ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator> >
{
static const char* value()
{
return "networkanalysis_msgs/pingactionGoal";
}
static const char* value(const ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator> >
{
static const char* value()
{
return "# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\
#goal definition\n\
bool inp\n\
";
}
static const char* value(const ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.inp);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct pingactionGoal_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::networkanalysis_msgs::pingactionGoal_<ContainerAllocator>& v)
{
s << indent << "inp: ";
Printer<uint8_t>::stream(s, indent + " ", v.inp);
}
};
} // namespace message_operations
} // namespace ros
#endif // NETWORKANALYSIS_MSGS_MESSAGE_PINGACTIONGOAL_H
| [
"elliott.white@students.plymouth.ac.uk"
] | elliott.white@students.plymouth.ac.uk |
05f663949e9aabd45cb6e609624242d89f5f4d00 | b28305dab0be0e03765c62b97bcd7f49a4f8073d | /chrome/browser/extensions/api/autofill_private/autofill_private_api.cc | 3fea3a1c3f1af17309d8d4f0f5969c597bb86a33 | [
"BSD-3-Clause"
] | permissive | svarvel/browser-android-tabs | 9e5e27e0a6e302a12fe784ca06123e5ce090ced5 | bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f | refs/heads/base-72.0.3626.105 | 2020-04-24T12:16:31.442851 | 2019-08-02T19:15:36 | 2019-08-02T19:15:36 | 171,950,555 | 1 | 2 | NOASSERTION | 2019-08-02T19:15:37 | 2019-02-21T21:47:44 | null | UTF-8 | C++ | false | false | 22,929 | cc | // Copyright 2015 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/extensions/api/autofill_private/autofill_private_api.h"
#include <stddef.h>
#include <utility>
#include "base/guid.h"
#include "base/metrics/user_metrics.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/api/autofill_private/autofill_util.h"
#include "chrome/common/extensions/api/autofill_private.h"
#include "components/autofill/content/browser/content_autofill_driver.h"
#include "components/autofill/content/browser/content_autofill_driver_factory.h"
#include "components/autofill/core/browser/autofill_manager.h"
#include "components/autofill/core/browser/autofill_profile.h"
#include "components/autofill/core/browser/form_data_importer.h"
#include "components/autofill/core/browser/local_card_migration_manager.h"
#include "components/autofill/core/browser/personal_data_manager.h"
#include "components/autofill/core/common/autofill_features.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/extension_function.h"
#include "extensions/browser/extension_function_registry.h"
#include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_ui.h"
#include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_ui_component.h"
#include "third_party/libaddressinput/src/cpp/include/libaddressinput/localization.h"
#include "ui/base/l10n/l10n_util.h"
namespace autofill_private = extensions::api::autofill_private;
namespace addressinput = i18n::addressinput;
namespace {
static const char kSettingsOrigin[] = "Chrome settings";
static const char kErrorDataUnavailable[] = "Autofill data unavailable.";
// TODO(crbug.com/903594): This does basically the same thing as
// components/autofill/core/browser/autofill_address_util.cc, we
// should refactor to use a single code path for this.
// Fills |components| with the address UI components that should be used to
// input an address for |country_code| when UI BCP 47 language code is
// |ui_language_code|.
void PopulateAddressComponents(
const std::string& country_code,
const std::string& ui_language_code,
autofill_private::AddressComponents* address_components) {
DCHECK(address_components);
i18n::addressinput::Localization localization;
localization.SetGetter(l10n_util::GetStringUTF8);
std::string best_address_language_code;
std::vector<addressinput::AddressUiComponent> components =
i18n::addressinput::BuildComponents(
country_code,
localization,
ui_language_code,
&best_address_language_code);
if (components.empty()) {
static const char kDefaultCountryCode[] = "US";
components = i18n::addressinput::BuildComponents(
kDefaultCountryCode,
localization,
ui_language_code,
&best_address_language_code);
}
address_components->language_code = best_address_language_code;
DCHECK(!components.empty());
autofill_private::AddressComponentRow* row = nullptr;
for (size_t i = 0; i < components.size(); ++i) {
if (components[i].field == ::i18n::addressinput::ORGANIZATION &&
!base::FeatureList::IsEnabled(
autofill::features::kAutofillEnableCompanyName)) {
continue;
}
if (!row ||
components[i - 1].length_hint ==
addressinput::AddressUiComponent::HINT_LONG ||
components[i].length_hint ==
addressinput::AddressUiComponent::HINT_LONG) {
address_components->components.push_back(
autofill_private::AddressComponentRow());
row = &address_components->components.back();
}
autofill_private::AddressComponent component;
component.field_name = components[i].name;
switch (components[i].field) {
case i18n::addressinput::COUNTRY:
component.field =
autofill_private::AddressField::ADDRESS_FIELD_COUNTRY_CODE;
break;
case i18n::addressinput::ADMIN_AREA:
component.field =
autofill_private::AddressField::ADDRESS_FIELD_ADDRESS_LEVEL_1;
break;
case i18n::addressinput::LOCALITY:
component.field =
autofill_private::AddressField::ADDRESS_FIELD_ADDRESS_LEVEL_2;
break;
case i18n::addressinput::DEPENDENT_LOCALITY:
component.field =
autofill_private::AddressField::ADDRESS_FIELD_ADDRESS_LEVEL_3;
break;
case i18n::addressinput::SORTING_CODE:
component.field =
autofill_private::AddressField::ADDRESS_FIELD_SORTING_CODE;
break;
case i18n::addressinput::POSTAL_CODE:
component.field =
autofill_private::AddressField::ADDRESS_FIELD_POSTAL_CODE;
break;
case i18n::addressinput::STREET_ADDRESS:
component.field =
autofill_private::AddressField::ADDRESS_FIELD_ADDRESS_LINES;
break;
case i18n::addressinput::ORGANIZATION:
component.field =
autofill_private::AddressField::ADDRESS_FIELD_COMPANY_NAME;
break;
case i18n::addressinput::RECIPIENT:
component.field =
autofill_private::AddressField::ADDRESS_FIELD_FULL_NAME;
break;
}
switch (components[i].length_hint) {
case addressinput::AddressUiComponent::HINT_LONG:
component.is_long_field = true;
break;
case addressinput::AddressUiComponent::HINT_SHORT:
component.is_long_field = false;
break;
}
row->row.push_back(std::move(component));
}
}
// Searches the |list| for the value at |index|. If this value is present in
// any of the rest of the list, then the item (at |index|) is removed. The
// comparison of phone number values is done on normalized versions of the phone
// number values.
void RemoveDuplicatePhoneNumberAtIndex(
size_t index, const std::string& country_code, base::ListValue* list) {
base::string16 new_value;
if (!list->GetString(index, &new_value)) {
NOTREACHED() << "List should have a value at index " << index;
return;
}
bool is_duplicate = false;
std::string app_locale = g_browser_process->GetApplicationLocale();
for (size_t i = 0; i < list->GetSize() && !is_duplicate; ++i) {
if (i == index)
continue;
base::string16 existing_value;
if (!list->GetString(i, &existing_value)) {
NOTREACHED() << "List should have a value at index " << i;
continue;
}
is_duplicate = autofill::i18n::PhoneNumbersMatch(
new_value, existing_value, country_code, app_locale);
}
if (is_duplicate)
list->Remove(index, nullptr);
}
} // namespace
namespace extensions {
////////////////////////////////////////////////////////////////////////////////
// AutofillPrivateSaveAddressFunction
AutofillPrivateSaveAddressFunction::AutofillPrivateSaveAddressFunction()
: chrome_details_(this) {}
AutofillPrivateSaveAddressFunction::~AutofillPrivateSaveAddressFunction() {}
ExtensionFunction::ResponseAction AutofillPrivateSaveAddressFunction::Run() {
std::unique_ptr<api::autofill_private::SaveAddress::Params> parameters =
api::autofill_private::SaveAddress::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(parameters.get());
autofill::PersonalDataManager* personal_data =
autofill::PersonalDataManagerFactory::GetForProfile(
chrome_details_.GetProfile());
if (!personal_data || !personal_data->IsDataLoaded())
return RespondNow(Error(kErrorDataUnavailable));
api::autofill_private::AddressEntry* address = ¶meters->address;
// If a profile guid is specified, get a copy of the profile identified by it.
// Otherwise create a new one.
std::string guid = address->guid ? *address->guid : "";
const bool use_existing_profile = !guid.empty();
const autofill::AutofillProfile* existing_profile = nullptr;
if (use_existing_profile) {
existing_profile = personal_data->GetProfileByGUID(guid);
if (!existing_profile)
return RespondNow(Error(kErrorDataUnavailable));
}
autofill::AutofillProfile profile =
existing_profile
? *existing_profile
: autofill::AutofillProfile(base::GenerateGUID(), kSettingsOrigin);
// Strings from JavaScript use UTF-8 encoding. This container is used as an
// intermediate container for functions which require UTF-16 strings.
std::vector<base::string16> string16Container;
if (address->full_names) {
std::string full_name;
if (!address->full_names->empty())
full_name = address->full_names->at(0);
profile.SetInfo(autofill::AutofillType(autofill::NAME_FULL),
base::UTF8ToUTF16(full_name),
g_browser_process->GetApplicationLocale());
}
if (address->company_name) {
profile.SetRawInfo(
autofill::COMPANY_NAME,
base::UTF8ToUTF16(*address->company_name));
}
if (address->address_lines) {
profile.SetRawInfo(
autofill::ADDRESS_HOME_STREET_ADDRESS,
base::UTF8ToUTF16(*address->address_lines));
}
if (address->address_level1) {
profile.SetRawInfo(
autofill::ADDRESS_HOME_STATE,
base::UTF8ToUTF16(*address->address_level1));
}
if (address->address_level2) {
profile.SetRawInfo(
autofill::ADDRESS_HOME_CITY,
base::UTF8ToUTF16(*address->address_level2));
}
if (address->address_level3) {
profile.SetRawInfo(
autofill::ADDRESS_HOME_DEPENDENT_LOCALITY,
base::UTF8ToUTF16(*address->address_level3));
}
if (address->postal_code) {
profile.SetRawInfo(
autofill::ADDRESS_HOME_ZIP,
base::UTF8ToUTF16(*address->postal_code));
}
if (address->sorting_code) {
profile.SetRawInfo(
autofill::ADDRESS_HOME_SORTING_CODE,
base::UTF8ToUTF16(*address->sorting_code));
}
if (address->country_code) {
profile.SetRawInfo(
autofill::ADDRESS_HOME_COUNTRY,
base::UTF8ToUTF16(*address->country_code));
}
if (address->phone_numbers) {
std::string phone;
if (!address->phone_numbers->empty())
phone = address->phone_numbers->at(0);
profile.SetRawInfo(autofill::PHONE_HOME_WHOLE_NUMBER,
base::UTF8ToUTF16(phone));
}
if (address->email_addresses) {
std::string email;
if (!address->email_addresses->empty())
email = address->email_addresses->at(0);
profile.SetRawInfo(autofill::EMAIL_ADDRESS, base::UTF8ToUTF16(email));
}
if (address->language_code)
profile.set_language_code(*address->language_code);
if (use_existing_profile) {
personal_data->UpdateProfile(profile);
} else {
personal_data->AddProfile(profile);
}
return RespondNow(NoArguments());
}
////////////////////////////////////////////////////////////////////////////////
// AutofillPrivateGetCountryListFunction
AutofillPrivateGetCountryListFunction::AutofillPrivateGetCountryListFunction()
: chrome_details_(this) {}
AutofillPrivateGetCountryListFunction::
~AutofillPrivateGetCountryListFunction() {}
ExtensionFunction::ResponseAction AutofillPrivateGetCountryListFunction::Run() {
autofill::PersonalDataManager* personal_data =
autofill::PersonalDataManagerFactory::GetForProfile(
chrome_details_.GetProfile());
// Return an empty list if data is not loaded.
if (!(personal_data && personal_data->IsDataLoaded())) {
autofill_util::CountryEntryList empty_list;
return RespondNow(ArgumentList(
api::autofill_private::GetCountryList::Results::Create(empty_list)));
}
autofill_util::CountryEntryList country_list =
autofill_util::GenerateCountryList(*personal_data);
return RespondNow(ArgumentList(
api::autofill_private::GetCountryList::Results::Create(country_list)));
}
////////////////////////////////////////////////////////////////////////////////
// AutofillPrivateGetAddressComponentsFunction
AutofillPrivateGetAddressComponentsFunction::
~AutofillPrivateGetAddressComponentsFunction() {}
ExtensionFunction::ResponseAction
AutofillPrivateGetAddressComponentsFunction::Run() {
std::unique_ptr<api::autofill_private::GetAddressComponents::Params>
parameters =
api::autofill_private::GetAddressComponents::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(parameters.get());
autofill_private::AddressComponents components;
PopulateAddressComponents(
parameters->country_code,
g_browser_process->GetApplicationLocale(),
&components);
return RespondNow(OneArgument(components.ToValue()));
}
////////////////////////////////////////////////////////////////////////////////
// AutofillPrivateGetAddressListFunction
AutofillPrivateGetAddressListFunction::AutofillPrivateGetAddressListFunction()
: chrome_details_(this) {}
AutofillPrivateGetAddressListFunction::
~AutofillPrivateGetAddressListFunction() {}
ExtensionFunction::ResponseAction AutofillPrivateGetAddressListFunction::Run() {
autofill::PersonalDataManager* personal_data =
autofill::PersonalDataManagerFactory::GetForProfile(
chrome_details_.GetProfile());
DCHECK(personal_data && personal_data->IsDataLoaded());
autofill_util::AddressEntryList address_list =
autofill_util::GenerateAddressList(*personal_data);
base::RecordAction(base::UserMetricsAction("AutofillAddressesViewed"));
return RespondNow(ArgumentList(
api::autofill_private::GetAddressList::Results::Create(address_list)));
}
////////////////////////////////////////////////////////////////////////////////
// AutofillPrivateSaveCreditCardFunction
AutofillPrivateSaveCreditCardFunction::AutofillPrivateSaveCreditCardFunction()
: chrome_details_(this) {}
AutofillPrivateSaveCreditCardFunction::
~AutofillPrivateSaveCreditCardFunction() {}
ExtensionFunction::ResponseAction AutofillPrivateSaveCreditCardFunction::Run() {
std::unique_ptr<api::autofill_private::SaveCreditCard::Params> parameters =
api::autofill_private::SaveCreditCard::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(parameters.get());
autofill::PersonalDataManager* personal_data =
autofill::PersonalDataManagerFactory::GetForProfile(
chrome_details_.GetProfile());
if (!personal_data || !personal_data->IsDataLoaded())
return RespondNow(Error(kErrorDataUnavailable));
api::autofill_private::CreditCardEntry* card = ¶meters->card;
// If a card guid is specified, get a copy of the card identified by it.
// Otherwise create a new one.
std::string guid = card->guid ? *card->guid : "";
const bool use_existing_card = !guid.empty();
const autofill::CreditCard* existing_card = nullptr;
if (use_existing_card) {
existing_card = personal_data->GetCreditCardByGUID(guid);
if (!existing_card)
return RespondNow(Error(kErrorDataUnavailable));
}
autofill::CreditCard credit_card =
existing_card
? *existing_card
: autofill::CreditCard(base::GenerateGUID(), kSettingsOrigin);
if (card->name) {
credit_card.SetRawInfo(autofill::CREDIT_CARD_NAME_FULL,
base::UTF8ToUTF16(*card->name));
}
if (card->card_number) {
credit_card.SetRawInfo(
autofill::CREDIT_CARD_NUMBER,
base::UTF8ToUTF16(*card->card_number));
}
if (card->expiration_month) {
credit_card.SetRawInfo(
autofill::CREDIT_CARD_EXP_MONTH,
base::UTF8ToUTF16(*card->expiration_month));
}
if (card->expiration_year) {
credit_card.SetRawInfo(
autofill::CREDIT_CARD_EXP_4_DIGIT_YEAR,
base::UTF8ToUTF16(*card->expiration_year));
}
if (use_existing_card) {
personal_data->UpdateCreditCard(credit_card);
} else {
personal_data->AddCreditCard(credit_card);
base::RecordAction(base::UserMetricsAction("AutofillCreditCardsAdded"));
}
return RespondNow(NoArguments());
}
////////////////////////////////////////////////////////////////////////////////
// AutofillPrivateRemoveEntryFunction
AutofillPrivateRemoveEntryFunction::AutofillPrivateRemoveEntryFunction()
: chrome_details_(this) {}
AutofillPrivateRemoveEntryFunction::~AutofillPrivateRemoveEntryFunction() {}
ExtensionFunction::ResponseAction AutofillPrivateRemoveEntryFunction::Run() {
std::unique_ptr<api::autofill_private::RemoveEntry::Params> parameters =
api::autofill_private::RemoveEntry::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(parameters.get());
autofill::PersonalDataManager* personal_data =
autofill::PersonalDataManagerFactory::GetForProfile(
chrome_details_.GetProfile());
if (!personal_data || !personal_data->IsDataLoaded())
return RespondNow(Error(kErrorDataUnavailable));
personal_data->RemoveByGUID(parameters->guid);
return RespondNow(NoArguments());
}
////////////////////////////////////////////////////////////////////////////////
// AutofillPrivateValidatePhoneNumbersFunction
AutofillPrivateValidatePhoneNumbersFunction::
~AutofillPrivateValidatePhoneNumbersFunction() {}
ExtensionFunction::ResponseAction
AutofillPrivateValidatePhoneNumbersFunction::Run() {
std::unique_ptr<api::autofill_private::ValidatePhoneNumbers::Params>
parameters =
api::autofill_private::ValidatePhoneNumbers::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(parameters.get());
api::autofill_private::ValidatePhoneParams* params = ¶meters->params;
// Extract the phone numbers into a ListValue.
std::unique_ptr<base::ListValue> phone_numbers(new base::ListValue);
phone_numbers->AppendStrings(params->phone_numbers);
RemoveDuplicatePhoneNumberAtIndex(params->index_of_new_number,
params->country_code, phone_numbers.get());
return RespondNow(OneArgument(std::move(phone_numbers)));
}
////////////////////////////////////////////////////////////////////////////////
// AutofillPrivateMaskCreditCardFunction
AutofillPrivateMaskCreditCardFunction::AutofillPrivateMaskCreditCardFunction()
: chrome_details_(this) {}
AutofillPrivateMaskCreditCardFunction::
~AutofillPrivateMaskCreditCardFunction() {}
ExtensionFunction::ResponseAction AutofillPrivateMaskCreditCardFunction::Run() {
std::unique_ptr<api::autofill_private::MaskCreditCard::Params> parameters =
api::autofill_private::MaskCreditCard::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(parameters.get());
autofill::PersonalDataManager* personal_data =
autofill::PersonalDataManagerFactory::GetForProfile(
chrome_details_.GetProfile());
if (!personal_data || !personal_data->IsDataLoaded())
return RespondNow(Error(kErrorDataUnavailable));
personal_data->ResetFullServerCard(parameters->guid);
return RespondNow(NoArguments());
}
////////////////////////////////////////////////////////////////////////////////
// AutofillPrivateGetCreditCardListFunction
AutofillPrivateGetCreditCardListFunction::
AutofillPrivateGetCreditCardListFunction()
: chrome_details_(this) {}
AutofillPrivateGetCreditCardListFunction::
~AutofillPrivateGetCreditCardListFunction() {}
ExtensionFunction::ResponseAction
AutofillPrivateGetCreditCardListFunction::Run() {
autofill::PersonalDataManager* personal_data =
autofill::PersonalDataManagerFactory::GetForProfile(
chrome_details_.GetProfile());
DCHECK(personal_data && personal_data->IsDataLoaded());
autofill_util::CreditCardEntryList credit_card_list =
autofill_util::GenerateCreditCardList(*personal_data);
base::RecordAction(base::UserMetricsAction("AutofillCreditCardsViewed"));
return RespondNow(
ArgumentList(api::autofill_private::GetCreditCardList::Results::Create(
credit_card_list)));
}
////////////////////////////////////////////////////////////////////////////////
// AutofillPrivateMigrateCreditCardsFunction
AutofillPrivateMigrateCreditCardsFunction::
AutofillPrivateMigrateCreditCardsFunction()
: chrome_details_(this) {}
AutofillPrivateMigrateCreditCardsFunction::
~AutofillPrivateMigrateCreditCardsFunction() {}
ExtensionFunction::ResponseAction
AutofillPrivateMigrateCreditCardsFunction::Run() {
autofill::PersonalDataManager* personal_data =
autofill::PersonalDataManagerFactory::GetForProfile(
chrome_details_.GetProfile());
// Get the web contents to get autofill manager.
content::WebContents* web_contents = GetSenderWebContents();
if (!personal_data || !personal_data->IsDataLoaded() || !web_contents)
return RespondNow(Error(kErrorDataUnavailable));
// Get the AutofillManager from the web contents. AutofillManager has a
// pointer to its AutofillClient which owns FormDataImporter.
autofill::AutofillManager* autofill_manager =
autofill::ContentAutofillDriverFactory::FromWebContents(web_contents)
->DriverForFrame(web_contents->GetMainFrame())
->autofill_manager();
if (!autofill_manager || !autofill_manager->client())
return RespondNow(Error(kErrorDataUnavailable));
// Get the FormDataImporter from AutofillClient. FormDataImporter owns
// LocalCardMigrationManager.
autofill::FormDataImporter* form_data_importer =
autofill_manager->client()->GetFormDataImporter();
if (!form_data_importer)
return RespondNow(Error(kErrorDataUnavailable));
// Get local card migration manager from form data importer.
autofill::LocalCardMigrationManager* local_card_migration_manager =
form_data_importer->local_card_migration_manager();
if (!local_card_migration_manager)
return RespondNow(Error(kErrorDataUnavailable));
// Since we already check the migration requirements on the settings page, we
// don't check the migration requirements again.
local_card_migration_manager->GetMigratableCreditCards();
local_card_migration_manager->AttemptToOfferLocalCardMigration(
/*is_from_settings_page=*/true);
return RespondNow(NoArguments());
}
////////////////////////////////////////////////////////////////////////////////
// AutofillPrivateLogServerCardLinkClickedFunction
AutofillPrivateLogServerCardLinkClickedFunction::
AutofillPrivateLogServerCardLinkClickedFunction()
: chrome_details_(this) {}
AutofillPrivateLogServerCardLinkClickedFunction::
~AutofillPrivateLogServerCardLinkClickedFunction() {}
ExtensionFunction::ResponseAction
AutofillPrivateLogServerCardLinkClickedFunction::Run() {
autofill::PersonalDataManager* personal_data =
autofill::PersonalDataManagerFactory::GetForProfile(
chrome_details_.GetProfile());
if (!personal_data || !personal_data->IsDataLoaded())
return RespondNow(Error(kErrorDataUnavailable));
personal_data->LogServerCardLinkClicked();
return RespondNow(NoArguments());
}
} // namespace extensions
| [
"artem@brave.com"
] | artem@brave.com |
41d46e07a81f6eb3cbd87ea45233e3fe049ced66 | 5357b5c8c396d2c4b380c1f8352869a7297127e1 | /projects/PathosEngine/src/pathos/text/text_actor.h | 4ec370f251145ec65049125f3864b88a08357696 | [
"MIT"
] | permissive | codeonwort/pathosengine | fc024ff0e4e9054b59c937ea51cd8100393c4f1b | 70b5e07b5c597a1e164b4d4564d50ed65652218f | refs/heads/master | 2023-07-06T17:19:50.633526 | 2023-07-01T16:15:45 | 2023-07-01T16:15:53 | 48,979,867 | 27 | 0 | MIT | 2023-07-01T08:51:40 | 2016-01-04T06:51:24 | C | UTF-8 | C++ | false | false | 356 | h | #pragma once
#include "pathos/scene/actor.h"
#include <string>
namespace pathos {
class TextMeshComponent;
class TextMeshActor : public Actor {
public:
TextMeshActor();
void setText(const wchar_t* text);
void setColor(float r, float g, float b);
void setFont(const std::string& tag);
private:
TextMeshComponent* textComponent;
};
}
| [
"codeonwort@gmail.com"
] | codeonwort@gmail.com |
615f06cf24a1c306f103496d48c7348bd7f518be | a92dbfc152d506f87988fec5abb90150fbde0a26 | /6-g2o/include/slam_base.h | 469d9ed7e10aac9196dec31258005afbffaab6eb | [] | no_license | kinglintianxia/rgbd-slam-lets-do-it | 9a3114ceb975349442cb88667f3d1fc7f60a3df6 | ed5f360bd9988f68390f67687fe654f21597ea95 | refs/heads/master | 2021-05-11T22:10:37.536153 | 2018-04-22T15:26:20 | 2018-04-22T15:26:20 | 117,487,578 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,965 | h | # pragma once
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
// Eigen
#include <Eigen/Core>
#include <Eigen/Geometry>
// OpenCV
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/eigen.hpp>
#include <opencv2/calib3d/calib3d.hpp>
// PCL
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/common/transforms.h>
#include <pcl/filters/voxel_grid.h>
typedef pcl::PointXYZRGBA PointT;
typedef pcl::PointCloud<PointT> pointcloud;
// Camera intrinsic
struct CAMERA_INTRINSIC_PARAMETERS
{
double cx, cy;
double fx, fy;
double scale; // camera scale facotr default:1000
};
// Image frame
struct Frame
{
cv::Mat color;
cv::Mat depth;
cv::Mat desp;
std::vector<cv::KeyPoint> kp;
};
// Result of pnp
struct Result_of_pnp
{
cv::Mat rvect;
cv::Mat tvect;
int inliers;
};
// Parameter reader
class ParameterReader
{
public:
// Constructor
ParameterReader(std::string filename)
{
std::ifstream fin(filename.c_str());
if(!fin)
std::cout <<"filename does not exist!" << std::endl;
while(!fin.eof())
{
std::string str;
getline(fin, str);
// jump comment line
if(str[0] == '#')
continue;
int position = str.find("=");
if(position == -1)
continue;
else
{
std::string key = str.substr(0, position);
std::string value = str.substr(position+1, str.length());
data[key] = value;
}
if(!fin.good())
break;
}
}
// Get data method
std::string get_data(std::string key)
{
std::map<std::string, std::string>::iterator iter = data.find(key);
if(iter == data.end())
{
std::cout << "Can not find key: " << key << std::endl;
return std::string("Not found.");
}
else
return iter->second;
}
private:
std::string file_name_;
std::map<std::string, std::string> data;
};
pointcloud::Ptr image_to_pointcloud(Frame frame, CAMERA_INTRINSIC_PARAMETERS camera);
cv::Point3f point2d_to_3d(cv::Point3f point, CAMERA_INTRINSIC_PARAMETERS camera);
// Compute keypoints and descriptors
void compute_keypoints_descriptors(Frame& frame, std::string det, std::string des);
// Get result of motion
Result_of_pnp estimate_motion(Frame frame1, Frame frame2, CAMERA_INTRINSIC_PARAMETERS camera);
// cvMat to Eigen
Eigen::Isometry3d cvMat2eigen(Result_of_pnp result);
// Get camera parameter
void get_cam_param(ParameterReader reader, CAMERA_INTRINSIC_PARAMETERS& camera);
// Joint point cloud
pointcloud::Ptr joint_pointcloud(pointcloud::Ptr origin, Frame newframe, Eigen::Isometry3d trans, CAMERA_INTRINSIC_PARAMETERS camera, ParameterReader read);
| [
"wangliujun_bit@163.com"
] | wangliujun_bit@163.com |
059023ef5bb61f8c0755b1a868a62f3b83f260cb | 64e4fabf9b43b6b02b14b9df7e1751732b30ad38 | /src/chromium/gen/gen_combined/third_party/perfetto/protos/perfetto/common/commit_data_request.pb.h | f8666fe0d45b1ed70ade8fafdd73f7c2df9f1e7f | [
"BSD-3-Clause"
] | permissive | ivan-kits/skia-opengl-emscripten | 8a5ee0eab0214c84df3cd7eef37c8ba54acb045e | 79573e1ee794061bdcfd88cacdb75243eff5f6f0 | refs/heads/master | 2023-02-03T16:39:20.556706 | 2020-12-25T14:00:49 | 2020-12-25T14:00:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 41,675 | h | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: perfetto/common/commit_data_request.proto
#ifndef PROTOBUF_INCLUDED_perfetto_2fcommon_2fcommit_5fdata_5frequest_2eproto
#define PROTOBUF_INCLUDED_perfetto_2fcommon_2fcommit_5fdata_5frequest_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 3005000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3005001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
// @@protoc_insertion_point(includes)
#define PROTOBUF_INTERNAL_EXPORT_protobuf_perfetto_2fcommon_2fcommit_5fdata_5frequest_2eproto
namespace protobuf_perfetto_2fcommon_2fcommit_5fdata_5frequest_2eproto {
// Internal implementation detail -- do not use these members.
struct TableStruct {
static const ::google::protobuf::internal::ParseTableField entries[];
static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
static const ::google::protobuf::internal::ParseTable schema[4];
static const ::google::protobuf::internal::FieldMetadata field_metadata[];
static const ::google::protobuf::internal::SerializationTable serialization_table[];
static const ::google::protobuf::uint32 offsets[];
};
} // namespace protobuf_perfetto_2fcommon_2fcommit_5fdata_5frequest_2eproto
namespace perfetto {
namespace protos {
class CommitDataRequest;
class CommitDataRequestDefaultTypeInternal;
extern CommitDataRequestDefaultTypeInternal _CommitDataRequest_default_instance_;
class CommitDataRequest_ChunkToPatch;
class CommitDataRequest_ChunkToPatchDefaultTypeInternal;
extern CommitDataRequest_ChunkToPatchDefaultTypeInternal _CommitDataRequest_ChunkToPatch_default_instance_;
class CommitDataRequest_ChunkToPatch_Patch;
class CommitDataRequest_ChunkToPatch_PatchDefaultTypeInternal;
extern CommitDataRequest_ChunkToPatch_PatchDefaultTypeInternal _CommitDataRequest_ChunkToPatch_Patch_default_instance_;
class CommitDataRequest_ChunksToMove;
class CommitDataRequest_ChunksToMoveDefaultTypeInternal;
extern CommitDataRequest_ChunksToMoveDefaultTypeInternal _CommitDataRequest_ChunksToMove_default_instance_;
} // namespace protos
} // namespace perfetto
namespace google {
namespace protobuf {
template<> ::perfetto::protos::CommitDataRequest* Arena::CreateMaybeMessage<::perfetto::protos::CommitDataRequest>(Arena*);
template<> ::perfetto::protos::CommitDataRequest_ChunkToPatch* Arena::CreateMaybeMessage<::perfetto::protos::CommitDataRequest_ChunkToPatch>(Arena*);
template<> ::perfetto::protos::CommitDataRequest_ChunkToPatch_Patch* Arena::CreateMaybeMessage<::perfetto::protos::CommitDataRequest_ChunkToPatch_Patch>(Arena*);
template<> ::perfetto::protos::CommitDataRequest_ChunksToMove* Arena::CreateMaybeMessage<::perfetto::protos::CommitDataRequest_ChunksToMove>(Arena*);
} // namespace protobuf
} // namespace google
namespace perfetto {
namespace protos {
// ===================================================================
class CommitDataRequest_ChunksToMove : public ::google::protobuf::MessageLite /* @@protoc_insertion_point(class_definition:perfetto.protos.CommitDataRequest.ChunksToMove) */ {
public:
CommitDataRequest_ChunksToMove();
virtual ~CommitDataRequest_ChunksToMove();
CommitDataRequest_ChunksToMove(const CommitDataRequest_ChunksToMove& from);
inline CommitDataRequest_ChunksToMove& operator=(const CommitDataRequest_ChunksToMove& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
CommitDataRequest_ChunksToMove(CommitDataRequest_ChunksToMove&& from) noexcept
: CommitDataRequest_ChunksToMove() {
*this = ::std::move(from);
}
inline CommitDataRequest_ChunksToMove& operator=(CommitDataRequest_ChunksToMove&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
inline const ::std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline ::std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const CommitDataRequest_ChunksToMove& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const CommitDataRequest_ChunksToMove* internal_default_instance() {
return reinterpret_cast<const CommitDataRequest_ChunksToMove*>(
&_CommitDataRequest_ChunksToMove_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
GOOGLE_ATTRIBUTE_NOINLINE void Swap(CommitDataRequest_ChunksToMove* other);
friend void swap(CommitDataRequest_ChunksToMove& a, CommitDataRequest_ChunksToMove& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline CommitDataRequest_ChunksToMove* New() const final {
return CreateMaybeMessage<CommitDataRequest_ChunksToMove>(NULL);
}
CommitDataRequest_ChunksToMove* New(::google::protobuf::Arena* arena) const final {
return CreateMaybeMessage<CommitDataRequest_ChunksToMove>(arena);
}
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)
final;
void CopyFrom(const CommitDataRequest_ChunksToMove& from);
void MergeFrom(const CommitDataRequest_ChunksToMove& from);
void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
void DiscardUnknownFields();
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(CommitDataRequest_ChunksToMove* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::std::string GetTypeName() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// optional uint32 page = 1;
bool has_page() const;
void clear_page();
static const int kPageFieldNumber = 1;
::google::protobuf::uint32 page() const;
void set_page(::google::protobuf::uint32 value);
// optional uint32 chunk = 2;
bool has_chunk() const;
void clear_chunk();
static const int kChunkFieldNumber = 2;
::google::protobuf::uint32 chunk() const;
void set_chunk(::google::protobuf::uint32 value);
// optional uint32 target_buffer = 3;
bool has_target_buffer() const;
void clear_target_buffer();
static const int kTargetBufferFieldNumber = 3;
::google::protobuf::uint32 target_buffer() const;
void set_target_buffer(::google::protobuf::uint32 value);
// @@protoc_insertion_point(class_scope:perfetto.protos.CommitDataRequest.ChunksToMove)
private:
void set_has_page();
void clear_has_page();
void set_has_chunk();
void clear_has_chunk();
void set_has_target_buffer();
void clear_has_target_buffer();
::google::protobuf::internal::InternalMetadataWithArenaLite _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::uint32 page_;
::google::protobuf::uint32 chunk_;
::google::protobuf::uint32 target_buffer_;
friend struct ::protobuf_perfetto_2fcommon_2fcommit_5fdata_5frequest_2eproto::TableStruct;
};
// -------------------------------------------------------------------
class CommitDataRequest_ChunkToPatch_Patch : public ::google::protobuf::MessageLite /* @@protoc_insertion_point(class_definition:perfetto.protos.CommitDataRequest.ChunkToPatch.Patch) */ {
public:
CommitDataRequest_ChunkToPatch_Patch();
virtual ~CommitDataRequest_ChunkToPatch_Patch();
CommitDataRequest_ChunkToPatch_Patch(const CommitDataRequest_ChunkToPatch_Patch& from);
inline CommitDataRequest_ChunkToPatch_Patch& operator=(const CommitDataRequest_ChunkToPatch_Patch& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
CommitDataRequest_ChunkToPatch_Patch(CommitDataRequest_ChunkToPatch_Patch&& from) noexcept
: CommitDataRequest_ChunkToPatch_Patch() {
*this = ::std::move(from);
}
inline CommitDataRequest_ChunkToPatch_Patch& operator=(CommitDataRequest_ChunkToPatch_Patch&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
inline const ::std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline ::std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const CommitDataRequest_ChunkToPatch_Patch& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const CommitDataRequest_ChunkToPatch_Patch* internal_default_instance() {
return reinterpret_cast<const CommitDataRequest_ChunkToPatch_Patch*>(
&_CommitDataRequest_ChunkToPatch_Patch_default_instance_);
}
static constexpr int kIndexInFileMessages =
1;
GOOGLE_ATTRIBUTE_NOINLINE void Swap(CommitDataRequest_ChunkToPatch_Patch* other);
friend void swap(CommitDataRequest_ChunkToPatch_Patch& a, CommitDataRequest_ChunkToPatch_Patch& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline CommitDataRequest_ChunkToPatch_Patch* New() const final {
return CreateMaybeMessage<CommitDataRequest_ChunkToPatch_Patch>(NULL);
}
CommitDataRequest_ChunkToPatch_Patch* New(::google::protobuf::Arena* arena) const final {
return CreateMaybeMessage<CommitDataRequest_ChunkToPatch_Patch>(arena);
}
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)
final;
void CopyFrom(const CommitDataRequest_ChunkToPatch_Patch& from);
void MergeFrom(const CommitDataRequest_ChunkToPatch_Patch& from);
void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
void DiscardUnknownFields();
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(CommitDataRequest_ChunkToPatch_Patch* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::std::string GetTypeName() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// optional bytes data = 2;
bool has_data() const;
void clear_data();
static const int kDataFieldNumber = 2;
const ::std::string& data() const;
void set_data(const ::std::string& value);
#if LANG_CXX11
void set_data(::std::string&& value);
#endif
void set_data(const char* value);
void set_data(const void* value, size_t size);
::std::string* mutable_data();
::std::string* release_data();
void set_allocated_data(::std::string* data);
// optional uint32 offset = 1;
bool has_offset() const;
void clear_offset();
static const int kOffsetFieldNumber = 1;
::google::protobuf::uint32 offset() const;
void set_offset(::google::protobuf::uint32 value);
// @@protoc_insertion_point(class_scope:perfetto.protos.CommitDataRequest.ChunkToPatch.Patch)
private:
void set_has_offset();
void clear_has_offset();
void set_has_data();
void clear_has_data();
::google::protobuf::internal::InternalMetadataWithArenaLite _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::internal::ArenaStringPtr data_;
::google::protobuf::uint32 offset_;
friend struct ::protobuf_perfetto_2fcommon_2fcommit_5fdata_5frequest_2eproto::TableStruct;
};
// -------------------------------------------------------------------
class CommitDataRequest_ChunkToPatch : public ::google::protobuf::MessageLite /* @@protoc_insertion_point(class_definition:perfetto.protos.CommitDataRequest.ChunkToPatch) */ {
public:
CommitDataRequest_ChunkToPatch();
virtual ~CommitDataRequest_ChunkToPatch();
CommitDataRequest_ChunkToPatch(const CommitDataRequest_ChunkToPatch& from);
inline CommitDataRequest_ChunkToPatch& operator=(const CommitDataRequest_ChunkToPatch& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
CommitDataRequest_ChunkToPatch(CommitDataRequest_ChunkToPatch&& from) noexcept
: CommitDataRequest_ChunkToPatch() {
*this = ::std::move(from);
}
inline CommitDataRequest_ChunkToPatch& operator=(CommitDataRequest_ChunkToPatch&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
inline const ::std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline ::std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const CommitDataRequest_ChunkToPatch& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const CommitDataRequest_ChunkToPatch* internal_default_instance() {
return reinterpret_cast<const CommitDataRequest_ChunkToPatch*>(
&_CommitDataRequest_ChunkToPatch_default_instance_);
}
static constexpr int kIndexInFileMessages =
2;
GOOGLE_ATTRIBUTE_NOINLINE void Swap(CommitDataRequest_ChunkToPatch* other);
friend void swap(CommitDataRequest_ChunkToPatch& a, CommitDataRequest_ChunkToPatch& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline CommitDataRequest_ChunkToPatch* New() const final {
return CreateMaybeMessage<CommitDataRequest_ChunkToPatch>(NULL);
}
CommitDataRequest_ChunkToPatch* New(::google::protobuf::Arena* arena) const final {
return CreateMaybeMessage<CommitDataRequest_ChunkToPatch>(arena);
}
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)
final;
void CopyFrom(const CommitDataRequest_ChunkToPatch& from);
void MergeFrom(const CommitDataRequest_ChunkToPatch& from);
void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
void DiscardUnknownFields();
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(CommitDataRequest_ChunkToPatch* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::std::string GetTypeName() const final;
// nested types ----------------------------------------------------
typedef CommitDataRequest_ChunkToPatch_Patch Patch;
// accessors -------------------------------------------------------
// repeated .perfetto.protos.CommitDataRequest.ChunkToPatch.Patch patches = 4;
int patches_size() const;
void clear_patches();
static const int kPatchesFieldNumber = 4;
::perfetto::protos::CommitDataRequest_ChunkToPatch_Patch* mutable_patches(int index);
::google::protobuf::RepeatedPtrField< ::perfetto::protos::CommitDataRequest_ChunkToPatch_Patch >*
mutable_patches();
const ::perfetto::protos::CommitDataRequest_ChunkToPatch_Patch& patches(int index) const;
::perfetto::protos::CommitDataRequest_ChunkToPatch_Patch* add_patches();
const ::google::protobuf::RepeatedPtrField< ::perfetto::protos::CommitDataRequest_ChunkToPatch_Patch >&
patches() const;
// optional uint32 target_buffer = 1;
bool has_target_buffer() const;
void clear_target_buffer();
static const int kTargetBufferFieldNumber = 1;
::google::protobuf::uint32 target_buffer() const;
void set_target_buffer(::google::protobuf::uint32 value);
// optional uint32 writer_id = 2;
bool has_writer_id() const;
void clear_writer_id();
static const int kWriterIdFieldNumber = 2;
::google::protobuf::uint32 writer_id() const;
void set_writer_id(::google::protobuf::uint32 value);
// optional uint32 chunk_id = 3;
bool has_chunk_id() const;
void clear_chunk_id();
static const int kChunkIdFieldNumber = 3;
::google::protobuf::uint32 chunk_id() const;
void set_chunk_id(::google::protobuf::uint32 value);
// optional bool has_more_patches = 5;
bool has_has_more_patches() const;
void clear_has_more_patches();
static const int kHasMorePatchesFieldNumber = 5;
bool has_more_patches() const;
void set_has_more_patches(bool value);
// @@protoc_insertion_point(class_scope:perfetto.protos.CommitDataRequest.ChunkToPatch)
private:
void set_has_target_buffer();
void clear_has_target_buffer();
void set_has_writer_id();
void clear_has_writer_id();
void set_has_chunk_id();
void clear_has_chunk_id();
void set_has_has_more_patches();
void clear_has_has_more_patches();
::google::protobuf::internal::InternalMetadataWithArenaLite _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::perfetto::protos::CommitDataRequest_ChunkToPatch_Patch > patches_;
::google::protobuf::uint32 target_buffer_;
::google::protobuf::uint32 writer_id_;
::google::protobuf::uint32 chunk_id_;
bool has_more_patches_;
friend struct ::protobuf_perfetto_2fcommon_2fcommit_5fdata_5frequest_2eproto::TableStruct;
};
// -------------------------------------------------------------------
class CommitDataRequest : public ::google::protobuf::MessageLite /* @@protoc_insertion_point(class_definition:perfetto.protos.CommitDataRequest) */ {
public:
CommitDataRequest();
virtual ~CommitDataRequest();
CommitDataRequest(const CommitDataRequest& from);
inline CommitDataRequest& operator=(const CommitDataRequest& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
CommitDataRequest(CommitDataRequest&& from) noexcept
: CommitDataRequest() {
*this = ::std::move(from);
}
inline CommitDataRequest& operator=(CommitDataRequest&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
inline const ::std::string& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline ::std::string* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const CommitDataRequest& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const CommitDataRequest* internal_default_instance() {
return reinterpret_cast<const CommitDataRequest*>(
&_CommitDataRequest_default_instance_);
}
static constexpr int kIndexInFileMessages =
3;
GOOGLE_ATTRIBUTE_NOINLINE void Swap(CommitDataRequest* other);
friend void swap(CommitDataRequest& a, CommitDataRequest& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline CommitDataRequest* New() const final {
return CreateMaybeMessage<CommitDataRequest>(NULL);
}
CommitDataRequest* New(::google::protobuf::Arena* arena) const final {
return CreateMaybeMessage<CommitDataRequest>(arena);
}
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)
final;
void CopyFrom(const CommitDataRequest& from);
void MergeFrom(const CommitDataRequest& from);
void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
void DiscardUnknownFields();
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(CommitDataRequest* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::std::string GetTypeName() const final;
// nested types ----------------------------------------------------
typedef CommitDataRequest_ChunksToMove ChunksToMove;
typedef CommitDataRequest_ChunkToPatch ChunkToPatch;
// accessors -------------------------------------------------------
// repeated .perfetto.protos.CommitDataRequest.ChunksToMove chunks_to_move = 1;
int chunks_to_move_size() const;
void clear_chunks_to_move();
static const int kChunksToMoveFieldNumber = 1;
::perfetto::protos::CommitDataRequest_ChunksToMove* mutable_chunks_to_move(int index);
::google::protobuf::RepeatedPtrField< ::perfetto::protos::CommitDataRequest_ChunksToMove >*
mutable_chunks_to_move();
const ::perfetto::protos::CommitDataRequest_ChunksToMove& chunks_to_move(int index) const;
::perfetto::protos::CommitDataRequest_ChunksToMove* add_chunks_to_move();
const ::google::protobuf::RepeatedPtrField< ::perfetto::protos::CommitDataRequest_ChunksToMove >&
chunks_to_move() const;
// repeated .perfetto.protos.CommitDataRequest.ChunkToPatch chunks_to_patch = 2;
int chunks_to_patch_size() const;
void clear_chunks_to_patch();
static const int kChunksToPatchFieldNumber = 2;
::perfetto::protos::CommitDataRequest_ChunkToPatch* mutable_chunks_to_patch(int index);
::google::protobuf::RepeatedPtrField< ::perfetto::protos::CommitDataRequest_ChunkToPatch >*
mutable_chunks_to_patch();
const ::perfetto::protos::CommitDataRequest_ChunkToPatch& chunks_to_patch(int index) const;
::perfetto::protos::CommitDataRequest_ChunkToPatch* add_chunks_to_patch();
const ::google::protobuf::RepeatedPtrField< ::perfetto::protos::CommitDataRequest_ChunkToPatch >&
chunks_to_patch() const;
// optional uint64 flush_request_id = 3;
bool has_flush_request_id() const;
void clear_flush_request_id();
static const int kFlushRequestIdFieldNumber = 3;
::google::protobuf::uint64 flush_request_id() const;
void set_flush_request_id(::google::protobuf::uint64 value);
// @@protoc_insertion_point(class_scope:perfetto.protos.CommitDataRequest)
private:
void set_has_flush_request_id();
void clear_has_flush_request_id();
::google::protobuf::internal::InternalMetadataWithArenaLite _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::perfetto::protos::CommitDataRequest_ChunksToMove > chunks_to_move_;
::google::protobuf::RepeatedPtrField< ::perfetto::protos::CommitDataRequest_ChunkToPatch > chunks_to_patch_;
::google::protobuf::uint64 flush_request_id_;
friend struct ::protobuf_perfetto_2fcommon_2fcommit_5fdata_5frequest_2eproto::TableStruct;
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// CommitDataRequest_ChunksToMove
// optional uint32 page = 1;
inline bool CommitDataRequest_ChunksToMove::has_page() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void CommitDataRequest_ChunksToMove::set_has_page() {
_has_bits_[0] |= 0x00000001u;
}
inline void CommitDataRequest_ChunksToMove::clear_has_page() {
_has_bits_[0] &= ~0x00000001u;
}
inline void CommitDataRequest_ChunksToMove::clear_page() {
page_ = 0u;
clear_has_page();
}
inline ::google::protobuf::uint32 CommitDataRequest_ChunksToMove::page() const {
// @@protoc_insertion_point(field_get:perfetto.protos.CommitDataRequest.ChunksToMove.page)
return page_;
}
inline void CommitDataRequest_ChunksToMove::set_page(::google::protobuf::uint32 value) {
set_has_page();
page_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.CommitDataRequest.ChunksToMove.page)
}
// optional uint32 chunk = 2;
inline bool CommitDataRequest_ChunksToMove::has_chunk() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void CommitDataRequest_ChunksToMove::set_has_chunk() {
_has_bits_[0] |= 0x00000002u;
}
inline void CommitDataRequest_ChunksToMove::clear_has_chunk() {
_has_bits_[0] &= ~0x00000002u;
}
inline void CommitDataRequest_ChunksToMove::clear_chunk() {
chunk_ = 0u;
clear_has_chunk();
}
inline ::google::protobuf::uint32 CommitDataRequest_ChunksToMove::chunk() const {
// @@protoc_insertion_point(field_get:perfetto.protos.CommitDataRequest.ChunksToMove.chunk)
return chunk_;
}
inline void CommitDataRequest_ChunksToMove::set_chunk(::google::protobuf::uint32 value) {
set_has_chunk();
chunk_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.CommitDataRequest.ChunksToMove.chunk)
}
// optional uint32 target_buffer = 3;
inline bool CommitDataRequest_ChunksToMove::has_target_buffer() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void CommitDataRequest_ChunksToMove::set_has_target_buffer() {
_has_bits_[0] |= 0x00000004u;
}
inline void CommitDataRequest_ChunksToMove::clear_has_target_buffer() {
_has_bits_[0] &= ~0x00000004u;
}
inline void CommitDataRequest_ChunksToMove::clear_target_buffer() {
target_buffer_ = 0u;
clear_has_target_buffer();
}
inline ::google::protobuf::uint32 CommitDataRequest_ChunksToMove::target_buffer() const {
// @@protoc_insertion_point(field_get:perfetto.protos.CommitDataRequest.ChunksToMove.target_buffer)
return target_buffer_;
}
inline void CommitDataRequest_ChunksToMove::set_target_buffer(::google::protobuf::uint32 value) {
set_has_target_buffer();
target_buffer_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.CommitDataRequest.ChunksToMove.target_buffer)
}
// -------------------------------------------------------------------
// CommitDataRequest_ChunkToPatch_Patch
// optional uint32 offset = 1;
inline bool CommitDataRequest_ChunkToPatch_Patch::has_offset() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void CommitDataRequest_ChunkToPatch_Patch::set_has_offset() {
_has_bits_[0] |= 0x00000002u;
}
inline void CommitDataRequest_ChunkToPatch_Patch::clear_has_offset() {
_has_bits_[0] &= ~0x00000002u;
}
inline void CommitDataRequest_ChunkToPatch_Patch::clear_offset() {
offset_ = 0u;
clear_has_offset();
}
inline ::google::protobuf::uint32 CommitDataRequest_ChunkToPatch_Patch::offset() const {
// @@protoc_insertion_point(field_get:perfetto.protos.CommitDataRequest.ChunkToPatch.Patch.offset)
return offset_;
}
inline void CommitDataRequest_ChunkToPatch_Patch::set_offset(::google::protobuf::uint32 value) {
set_has_offset();
offset_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.CommitDataRequest.ChunkToPatch.Patch.offset)
}
// optional bytes data = 2;
inline bool CommitDataRequest_ChunkToPatch_Patch::has_data() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void CommitDataRequest_ChunkToPatch_Patch::set_has_data() {
_has_bits_[0] |= 0x00000001u;
}
inline void CommitDataRequest_ChunkToPatch_Patch::clear_has_data() {
_has_bits_[0] &= ~0x00000001u;
}
inline void CommitDataRequest_ChunkToPatch_Patch::clear_data() {
data_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_data();
}
inline const ::std::string& CommitDataRequest_ChunkToPatch_Patch::data() const {
// @@protoc_insertion_point(field_get:perfetto.protos.CommitDataRequest.ChunkToPatch.Patch.data)
return data_.GetNoArena();
}
inline void CommitDataRequest_ChunkToPatch_Patch::set_data(const ::std::string& value) {
set_has_data();
data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:perfetto.protos.CommitDataRequest.ChunkToPatch.Patch.data)
}
#if LANG_CXX11
inline void CommitDataRequest_ChunkToPatch_Patch::set_data(::std::string&& value) {
set_has_data();
data_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:perfetto.protos.CommitDataRequest.ChunkToPatch.Patch.data)
}
#endif
inline void CommitDataRequest_ChunkToPatch_Patch::set_data(const char* value) {
GOOGLE_DCHECK(value != NULL);
set_has_data();
data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:perfetto.protos.CommitDataRequest.ChunkToPatch.Patch.data)
}
inline void CommitDataRequest_ChunkToPatch_Patch::set_data(const void* value, size_t size) {
set_has_data();
data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:perfetto.protos.CommitDataRequest.ChunkToPatch.Patch.data)
}
inline ::std::string* CommitDataRequest_ChunkToPatch_Patch::mutable_data() {
set_has_data();
// @@protoc_insertion_point(field_mutable:perfetto.protos.CommitDataRequest.ChunkToPatch.Patch.data)
return data_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* CommitDataRequest_ChunkToPatch_Patch::release_data() {
// @@protoc_insertion_point(field_release:perfetto.protos.CommitDataRequest.ChunkToPatch.Patch.data)
if (!has_data()) {
return NULL;
}
clear_has_data();
return data_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void CommitDataRequest_ChunkToPatch_Patch::set_allocated_data(::std::string* data) {
if (data != NULL) {
set_has_data();
} else {
clear_has_data();
}
data_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), data);
// @@protoc_insertion_point(field_set_allocated:perfetto.protos.CommitDataRequest.ChunkToPatch.Patch.data)
}
// -------------------------------------------------------------------
// CommitDataRequest_ChunkToPatch
// optional uint32 target_buffer = 1;
inline bool CommitDataRequest_ChunkToPatch::has_target_buffer() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void CommitDataRequest_ChunkToPatch::set_has_target_buffer() {
_has_bits_[0] |= 0x00000001u;
}
inline void CommitDataRequest_ChunkToPatch::clear_has_target_buffer() {
_has_bits_[0] &= ~0x00000001u;
}
inline void CommitDataRequest_ChunkToPatch::clear_target_buffer() {
target_buffer_ = 0u;
clear_has_target_buffer();
}
inline ::google::protobuf::uint32 CommitDataRequest_ChunkToPatch::target_buffer() const {
// @@protoc_insertion_point(field_get:perfetto.protos.CommitDataRequest.ChunkToPatch.target_buffer)
return target_buffer_;
}
inline void CommitDataRequest_ChunkToPatch::set_target_buffer(::google::protobuf::uint32 value) {
set_has_target_buffer();
target_buffer_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.CommitDataRequest.ChunkToPatch.target_buffer)
}
// optional uint32 writer_id = 2;
inline bool CommitDataRequest_ChunkToPatch::has_writer_id() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void CommitDataRequest_ChunkToPatch::set_has_writer_id() {
_has_bits_[0] |= 0x00000002u;
}
inline void CommitDataRequest_ChunkToPatch::clear_has_writer_id() {
_has_bits_[0] &= ~0x00000002u;
}
inline void CommitDataRequest_ChunkToPatch::clear_writer_id() {
writer_id_ = 0u;
clear_has_writer_id();
}
inline ::google::protobuf::uint32 CommitDataRequest_ChunkToPatch::writer_id() const {
// @@protoc_insertion_point(field_get:perfetto.protos.CommitDataRequest.ChunkToPatch.writer_id)
return writer_id_;
}
inline void CommitDataRequest_ChunkToPatch::set_writer_id(::google::protobuf::uint32 value) {
set_has_writer_id();
writer_id_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.CommitDataRequest.ChunkToPatch.writer_id)
}
// optional uint32 chunk_id = 3;
inline bool CommitDataRequest_ChunkToPatch::has_chunk_id() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void CommitDataRequest_ChunkToPatch::set_has_chunk_id() {
_has_bits_[0] |= 0x00000004u;
}
inline void CommitDataRequest_ChunkToPatch::clear_has_chunk_id() {
_has_bits_[0] &= ~0x00000004u;
}
inline void CommitDataRequest_ChunkToPatch::clear_chunk_id() {
chunk_id_ = 0u;
clear_has_chunk_id();
}
inline ::google::protobuf::uint32 CommitDataRequest_ChunkToPatch::chunk_id() const {
// @@protoc_insertion_point(field_get:perfetto.protos.CommitDataRequest.ChunkToPatch.chunk_id)
return chunk_id_;
}
inline void CommitDataRequest_ChunkToPatch::set_chunk_id(::google::protobuf::uint32 value) {
set_has_chunk_id();
chunk_id_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.CommitDataRequest.ChunkToPatch.chunk_id)
}
// repeated .perfetto.protos.CommitDataRequest.ChunkToPatch.Patch patches = 4;
inline int CommitDataRequest_ChunkToPatch::patches_size() const {
return patches_.size();
}
inline void CommitDataRequest_ChunkToPatch::clear_patches() {
patches_.Clear();
}
inline ::perfetto::protos::CommitDataRequest_ChunkToPatch_Patch* CommitDataRequest_ChunkToPatch::mutable_patches(int index) {
// @@protoc_insertion_point(field_mutable:perfetto.protos.CommitDataRequest.ChunkToPatch.patches)
return patches_.Mutable(index);
}
inline ::google::protobuf::RepeatedPtrField< ::perfetto::protos::CommitDataRequest_ChunkToPatch_Patch >*
CommitDataRequest_ChunkToPatch::mutable_patches() {
// @@protoc_insertion_point(field_mutable_list:perfetto.protos.CommitDataRequest.ChunkToPatch.patches)
return &patches_;
}
inline const ::perfetto::protos::CommitDataRequest_ChunkToPatch_Patch& CommitDataRequest_ChunkToPatch::patches(int index) const {
// @@protoc_insertion_point(field_get:perfetto.protos.CommitDataRequest.ChunkToPatch.patches)
return patches_.Get(index);
}
inline ::perfetto::protos::CommitDataRequest_ChunkToPatch_Patch* CommitDataRequest_ChunkToPatch::add_patches() {
// @@protoc_insertion_point(field_add:perfetto.protos.CommitDataRequest.ChunkToPatch.patches)
return patches_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::perfetto::protos::CommitDataRequest_ChunkToPatch_Patch >&
CommitDataRequest_ChunkToPatch::patches() const {
// @@protoc_insertion_point(field_list:perfetto.protos.CommitDataRequest.ChunkToPatch.patches)
return patches_;
}
// optional bool has_more_patches = 5;
inline bool CommitDataRequest_ChunkToPatch::has_has_more_patches() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void CommitDataRequest_ChunkToPatch::set_has_has_more_patches() {
_has_bits_[0] |= 0x00000008u;
}
inline void CommitDataRequest_ChunkToPatch::clear_has_has_more_patches() {
_has_bits_[0] &= ~0x00000008u;
}
inline void CommitDataRequest_ChunkToPatch::clear_has_more_patches() {
has_more_patches_ = false;
clear_has_has_more_patches();
}
inline bool CommitDataRequest_ChunkToPatch::has_more_patches() const {
// @@protoc_insertion_point(field_get:perfetto.protos.CommitDataRequest.ChunkToPatch.has_more_patches)
return has_more_patches_;
}
inline void CommitDataRequest_ChunkToPatch::set_has_more_patches(bool value) {
set_has_has_more_patches();
has_more_patches_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.CommitDataRequest.ChunkToPatch.has_more_patches)
}
// -------------------------------------------------------------------
// CommitDataRequest
// repeated .perfetto.protos.CommitDataRequest.ChunksToMove chunks_to_move = 1;
inline int CommitDataRequest::chunks_to_move_size() const {
return chunks_to_move_.size();
}
inline void CommitDataRequest::clear_chunks_to_move() {
chunks_to_move_.Clear();
}
inline ::perfetto::protos::CommitDataRequest_ChunksToMove* CommitDataRequest::mutable_chunks_to_move(int index) {
// @@protoc_insertion_point(field_mutable:perfetto.protos.CommitDataRequest.chunks_to_move)
return chunks_to_move_.Mutable(index);
}
inline ::google::protobuf::RepeatedPtrField< ::perfetto::protos::CommitDataRequest_ChunksToMove >*
CommitDataRequest::mutable_chunks_to_move() {
// @@protoc_insertion_point(field_mutable_list:perfetto.protos.CommitDataRequest.chunks_to_move)
return &chunks_to_move_;
}
inline const ::perfetto::protos::CommitDataRequest_ChunksToMove& CommitDataRequest::chunks_to_move(int index) const {
// @@protoc_insertion_point(field_get:perfetto.protos.CommitDataRequest.chunks_to_move)
return chunks_to_move_.Get(index);
}
inline ::perfetto::protos::CommitDataRequest_ChunksToMove* CommitDataRequest::add_chunks_to_move() {
// @@protoc_insertion_point(field_add:perfetto.protos.CommitDataRequest.chunks_to_move)
return chunks_to_move_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::perfetto::protos::CommitDataRequest_ChunksToMove >&
CommitDataRequest::chunks_to_move() const {
// @@protoc_insertion_point(field_list:perfetto.protos.CommitDataRequest.chunks_to_move)
return chunks_to_move_;
}
// repeated .perfetto.protos.CommitDataRequest.ChunkToPatch chunks_to_patch = 2;
inline int CommitDataRequest::chunks_to_patch_size() const {
return chunks_to_patch_.size();
}
inline void CommitDataRequest::clear_chunks_to_patch() {
chunks_to_patch_.Clear();
}
inline ::perfetto::protos::CommitDataRequest_ChunkToPatch* CommitDataRequest::mutable_chunks_to_patch(int index) {
// @@protoc_insertion_point(field_mutable:perfetto.protos.CommitDataRequest.chunks_to_patch)
return chunks_to_patch_.Mutable(index);
}
inline ::google::protobuf::RepeatedPtrField< ::perfetto::protos::CommitDataRequest_ChunkToPatch >*
CommitDataRequest::mutable_chunks_to_patch() {
// @@protoc_insertion_point(field_mutable_list:perfetto.protos.CommitDataRequest.chunks_to_patch)
return &chunks_to_patch_;
}
inline const ::perfetto::protos::CommitDataRequest_ChunkToPatch& CommitDataRequest::chunks_to_patch(int index) const {
// @@protoc_insertion_point(field_get:perfetto.protos.CommitDataRequest.chunks_to_patch)
return chunks_to_patch_.Get(index);
}
inline ::perfetto::protos::CommitDataRequest_ChunkToPatch* CommitDataRequest::add_chunks_to_patch() {
// @@protoc_insertion_point(field_add:perfetto.protos.CommitDataRequest.chunks_to_patch)
return chunks_to_patch_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::perfetto::protos::CommitDataRequest_ChunkToPatch >&
CommitDataRequest::chunks_to_patch() const {
// @@protoc_insertion_point(field_list:perfetto.protos.CommitDataRequest.chunks_to_patch)
return chunks_to_patch_;
}
// optional uint64 flush_request_id = 3;
inline bool CommitDataRequest::has_flush_request_id() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void CommitDataRequest::set_has_flush_request_id() {
_has_bits_[0] |= 0x00000001u;
}
inline void CommitDataRequest::clear_has_flush_request_id() {
_has_bits_[0] &= ~0x00000001u;
}
inline void CommitDataRequest::clear_flush_request_id() {
flush_request_id_ = GOOGLE_ULONGLONG(0);
clear_has_flush_request_id();
}
inline ::google::protobuf::uint64 CommitDataRequest::flush_request_id() const {
// @@protoc_insertion_point(field_get:perfetto.protos.CommitDataRequest.flush_request_id)
return flush_request_id_;
}
inline void CommitDataRequest::set_flush_request_id(::google::protobuf::uint64 value) {
set_has_flush_request_id();
flush_request_id_ = value;
// @@protoc_insertion_point(field_set:perfetto.protos.CommitDataRequest.flush_request_id)
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// @@protoc_insertion_point(namespace_scope)
} // namespace protos
} // namespace perfetto
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_INCLUDED_perfetto_2fcommon_2fcommit_5fdata_5frequest_2eproto
| [
"trofimov_d_a@magnit.ru"
] | trofimov_d_a@magnit.ru |
b5aaaa9472d5c5ea4060e32255d0fa741a38ad73 | 45e48f3e27843cb31179cd03c62b908c82e8ae60 | /solver/src/Stone.cpp | e07785b9dfeb89e122f8a4a7a029194c1bd58735 | [] | no_license | knct-densan/procon26 | 94c43c4baaad3ee5724d9119e4307a483e663b2c | c7064fd66ef78fcd3364fc93688f4320156e2b14 | refs/heads/master | 2020-07-25T17:20:14.439043 | 2015-10-12T05:44:07 | 2015-10-12T05:44:07 | 44,086,183 | 3 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,313 | cpp | #include <cassert>
#include <cstring>
#include "../include/Stone.h"
#include "../include/utils/Util.h"
namespace solver
{
Stone::Stone()
{
_setup = false;
std::memset(_stone, 0, sizeof(_stone));
}
Status Stone::get(int x, int y) const
{
assert(0 <= x && x < 10 && 0 <= y && y < 10);
assert(_setup);
return get(true, Direction::UL, x, y);
}
Status Stone::get(bool up, Direction dir, int x, int y) const
{
assert(0 <= x && x < 10 && 0 <= y && y < 10);
assert(_setup);
return _stone[up ? 0 : 1][(int)dir][y][x];
}
Status & Stone::set(int x, int y)
{
assert(0 <= x && x < 8 && 0 <= y && y < 8);
assert(!_setup);
return _stone[0][0][y + 1][x + 1];
}
void Stone::setup()
{
_setup = true;
markNeighbor();
makeUpDownAndDirections();
_size = 0;
for (int y = 1; y < 9; y++)
for (int x = 1; x < 9; x++)
_size += (_stone[0][0][y][x] == Status::STONE ? 1 : 0);
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 4; j++)
{
for (int y = 1; y < 9; y++)
{
for (int x = 1; x < 9; x++)
{
if (_stone[i][j][y][x] == Status::STONE)
_stonePos[i][j].push_back(Point(x, y));
}
}
}
}
}
const std::vector<Point> & Stone::stonePos(bool up, Direction dir) const
{
return _stonePos[up ? 0 : 1][(int)dir];
}
std::string Stone::dump(bool up, Direction dir)
{
std::string str = "";
for (int y = 0; y < 10; y++)
{
for (int x = 0; x < 10; x++)
str.append(StatusToString(get(up, dir, x, y)));
str.append("\n");
}
return str;
}
std::string Stone::dump()
{
return dump(true, Direction::UL);
}
int Stone::size()
{
return _size;
}
void Stone::markNeighbor()
{
// 横に見る
for (int y = 0; y < 10; y++)
{
for (int x = 0; x < 10; x++)
{
// 右側に石がある
if (0 < x)
{
if (_stone[0][0][y][x] == Status::STONE &&
_stone[0][0][y][x - 1] == Status::EMPTY
)
_stone[0][0][y][x - 1] = Status::NEIGHBOR;
}
// 左側に石がある
if (x < 9)
{
if (_stone[0][0][y][x] == Status::STONE &&
_stone[0][0][y][x + 1] == Status::EMPTY
)
_stone[0][0][y][x + 1] = Status::NEIGHBOR;
}
}
}
// 縦に見る
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
// 下側に石がある
if (0 < y)
{
if (_stone[0][0][y][x] == Status::STONE &&
_stone[0][0][y - 1][x] == Status::EMPTY
)
_stone[0][0][y - 1][x] = Status::NEIGHBOR;
}
// 上側に石がある
if (y < 9)
{
if (_stone[0][0][y][x] == Status::STONE &&
_stone[0][0][y + 1][x] == Status::EMPTY
)
_stone[0][0][y + 1][x] = Status::NEIGHBOR;
}
}
}
}
void Stone::makeUpDownAndDirections()
{
makeUpDown();
for (int i = 0; i < 2; i++)
makeDirections(i);
}
void Stone::makeUpDown()
{
// make down
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
_stone[1][0][i][j] = _stone[0][0][i][10 - j - 1];
}
void Stone::makeDirections(int key)
{
// make directions
for (int i = 1; i < 4; i++)
Stone::makeRotate(key, i - 1, i);
}
void Stone::makeRotate(int key, int from, int to)
{
for (int y = 0; y < 10; y++)
for (int x = 0; x < 10; x++)
_stone[key][to][y][x] = _stone[key][from][10 - x - 1][y];
}
} | [
"ueno122y344u@gmail.com"
] | ueno122y344u@gmail.com |
ca90d6d926cd241b1c81de4697b1b6450327216d | b9b1718a582de9a3a8a0441eb91e3bb7beacbeb9 | /Publiser-Subscriber/Publiser-Subscriber/Tablet.cpp | 710180e0a30403bbb4cbed99fcce51d2b740a118 | [] | no_license | Ramkumar-Lodhi/Design_Pattern | 7d98cc1b653f2e648bea4c5714846662fc356806 | 5c517b1d67cd86f6db9d3dc3639dfd73749fcb42 | refs/heads/master | 2022-10-10T07:59:16.652867 | 2022-10-01T14:22:44 | 2022-10-01T14:22:44 | 233,522,455 | 0 | 0 | null | 2022-10-01T14:22:45 | 2020-01-13T05:59:50 | C++ | UTF-8 | C++ | false | false | 172 | cpp | #include "Tablet.h"
void Tablet::update(float temp, float humidity) {
m_temprature = temp;
m_humidity = humidity;
std::cout << "Update " << __FUNCTION__ << std::endl;
} | [
"mitsram.lodhi@gmail.com"
] | mitsram.lodhi@gmail.com |
da3c5162c49b18630ee13babdc28a652fd901c0b | c0195988bccc960d3ab93c8087d14543a4a75a33 | /practice_linux/include/Logger.h | 8e687b1b59d252592763e5256f1c637ddd735977 | [] | no_license | DavidSungsuKim/Sungsu_Lab | addc10d6d41d223b2c1d482e6e349509efdf887e | b6e59e14aab9d12bc3af1addbbe82128d23b0b04 | refs/heads/master | 2023-08-24T23:13:52.272790 | 2023-08-09T18:26:06 | 2023-08-09T18:26:06 | 90,260,158 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 387 | h |
#ifndef __LOGGER_H__
#define __LOGGER_H__
// Forward decleration
class CLogger;
extern CLogger g_Logger;
class CLogger
{
public:
CLogger();
~CLogger();
void SetLogFilePath ( const char* aFile );
virtual void Telemetry ( const char* aString, ... );
void Telemetry2 ( const char* aFile, int aLineNo, const char* aString, ... );
private:
int m_fdLogFile;
};
#endif
| [
"sheld2@naver.com"
] | sheld2@naver.com |
97d5e76cf2938d57923465056a304b65e32318c9 | 59d26f54e985df3a0df505827b25da0c5ff586e8 | /0. Vision 2019/5. May/accepted/atc_4244_D - AtCoder Express 2_AC.cpp | 6ba68efd0cb22b267bb44a55acb08f1cb15a379a | [] | no_license | minhaz1217/My-C-Journey | 820f7b284e221eff2595611b2e86dc9e32f90278 | 3c8d998ede172e9855dc6bd02cb468d744a9cad6 | refs/heads/master | 2022-12-06T06:12:30.823678 | 2022-11-27T12:09:03 | 2022-11-27T12:09:03 | 160,788,252 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,716 | cpp | /*
Minhazul Hayat Khan
minhaz1217.github.io
Website: www.minhazul.com
EWU, Bangladesh
Problem Name:
Problem Link: https://abc106.contest.atcoder.jp/tasks/abc106_d?lang=en
Date : 17 / May / 2019
Comment: binary search.
*/
#include<bits/stdc++.h>
//#include<iostream>
using namespace std;
#define DEBUG 1
#define check(a) DEBUG==1?(cout << a << endl):null;
#define cc(a) DEBUG==1?(cout << a << endl):cout<<"";
#define msg(a,b) DEBUG==1?(cout << a << " : " << b << endl):cout<<"";
#define msg2(a,b,c) DEBUG==1?(cout << a << " : " << b << " : " << c << endl):cout<<"";
#define msg3(a,b,c,d) DEBUG==1?(cout << a << " : " << b << " : " << c << " : " << d << endl):cout<<"";
#define msg4(a,b,c,d,e) DEBUG==1?(cout << a << " : " << b << " : " << c << " : " << d << " : " << e << endl):cout<<"";
#define _INIT ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int main(){
long long int n,m,q,u,v,l,r,sum;
cin >> n >> m >> q;
vector<long long int> vec[n+2];
map<pair<long long int, long long int>,long long int > mp;
for(int i=0;i<m;i++){
cin >> u >> v;
//vec.push_back(make_pair(u,v));
vec[u].push_back(v);
}
//sort(vec.begin(),vec.end());
for(int i=1;i<=n;i++){
sort(vec[i].begin(),vec[i].end());
}
for(int l=0;l<q;l++){
cin >> u >> v;
sum = 0;
if(mp.find(make_pair(u,v)) != mp.end() ){
cout << mp[make_pair(u,v)] << endl;
continue;
}
for(int i=u;i<=v;i++){
r = upper_bound(vec[i].begin(),vec[i].end(), v)-vec[i].begin();
sum += r;
}
mp[ make_pair(u,v)] = sum;
//msg("ANS", sum)
cout << sum << endl;
}
return 0;
}
| [
"minhaz1217@users.noreply.github.com"
] | minhaz1217@users.noreply.github.com |
6af00576f0d250a7a341bc1873e3322750b96561 | 7e48d392300fbc123396c6a517dfe8ed1ea7179f | /RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/MorphTarget.gen.cpp | 403e818bac4ee0a8a5f05d773b510709379f97b5 | [] | no_license | WestRyanK/Rodent-VR | f4920071b716df6a006b15c132bc72d3b0cba002 | 2033946f197a07b8c851b9a5075f0cb276033af6 | refs/heads/master | 2021-06-14T18:33:22.141793 | 2020-10-27T03:25:33 | 2020-10-27T03:25:33 | 154,956,842 | 1 | 1 | null | 2018-11-29T09:56:21 | 2018-10-27T11:23:11 | C++ | UTF-8 | C++ | false | false | 4,870 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "Engine/Classes/Animation/MorphTarget.h"
#include "Serialization/ArchiveUObjectFromStructuredArchive.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeMorphTarget() {}
// Cross Module References
ENGINE_API UClass* Z_Construct_UClass_UMorphTarget_NoRegister();
ENGINE_API UClass* Z_Construct_UClass_UMorphTarget();
COREUOBJECT_API UClass* Z_Construct_UClass_UObject();
UPackage* Z_Construct_UPackage__Script_Engine();
ENGINE_API UClass* Z_Construct_UClass_USkeletalMesh_NoRegister();
// End Cross Module References
void UMorphTarget::StaticRegisterNativesUMorphTarget()
{
}
UClass* Z_Construct_UClass_UMorphTarget_NoRegister()
{
return UMorphTarget::StaticClass();
}
struct Z_Construct_UClass_UMorphTarget_Statics
{
static UObject* (*const DependentSingletons[])();
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_BaseSkelMesh_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_BaseSkelMesh;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_UMorphTarget_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_UObject,
(UObject* (*)())Z_Construct_UPackage__Script_Engine,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMorphTarget_Statics::Class_MetaDataParams[] = {
{ "HideCategories", "Object" },
{ "IncludePath", "Animation/MorphTarget.h" },
{ "ModuleRelativePath", "Classes/Animation/MorphTarget.h" },
};
#endif
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMorphTarget_Statics::NewProp_BaseSkelMesh_MetaData[] = {
{ "Comment", "/** USkeletalMesh that this vertex animation works on. */" },
{ "ModuleRelativePath", "Classes/Animation/MorphTarget.h" },
{ "ToolTip", "USkeletalMesh that this vertex animation works on." },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UMorphTarget_Statics::NewProp_BaseSkelMesh = { "BaseSkelMesh", nullptr, (EPropertyFlags)0x0010010000000000, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMorphTarget, BaseSkelMesh), Z_Construct_UClass_USkeletalMesh_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UMorphTarget_Statics::NewProp_BaseSkelMesh_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMorphTarget_Statics::NewProp_BaseSkelMesh_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UMorphTarget_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMorphTarget_Statics::NewProp_BaseSkelMesh,
};
const FCppClassTypeInfoStatic Z_Construct_UClass_UMorphTarget_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<UMorphTarget>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UMorphTarget_Statics::ClassParams = {
&UMorphTarget::StaticClass,
nullptr,
&StaticCppClassTypeInfo,
DependentSingletons,
nullptr,
Z_Construct_UClass_UMorphTarget_Statics::PropPointers,
nullptr,
UE_ARRAY_COUNT(DependentSingletons),
0,
UE_ARRAY_COUNT(Z_Construct_UClass_UMorphTarget_Statics::PropPointers),
0,
0x000800A0u,
METADATA_PARAMS(Z_Construct_UClass_UMorphTarget_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UMorphTarget_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_UMorphTarget()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UMorphTarget_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(UMorphTarget, 519316657);
template<> ENGINE_API UClass* StaticClass<UMorphTarget>()
{
return UMorphTarget::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_UMorphTarget(Z_Construct_UClass_UMorphTarget, &UMorphTarget::StaticClass, TEXT("/Script/Engine"), TEXT("UMorphTarget"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UMorphTarget);
IMPLEMENT_FSTRUCTUREDARCHIVE_SERIALIZER(UMorphTarget)
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| [
"west.ryan.k@gmail.com"
] | west.ryan.k@gmail.com |
7fc58b67bbbf9fa69e6c24845767246d6acc45a7 | b667f7c5ab0bfc6727890468f2e9eba9564efcff | /AppServiceSandwich/DirectoryChangeService.cpp | 251fd6bad3ad4107fe0c98982e4687b0f243ebcb | [] | no_license | peterekepeter/app-service-sandwich | c6fe39f1ef5be9ae7537c2c893a7a33152f002aa | 6299e23b62f2484ce82e34ba214d2ca8dd892853 | refs/heads/master | 2021-07-10T12:30:19.020482 | 2021-04-09T17:38:34 | 2021-04-09T17:38:34 | 88,741,825 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,234 | cpp | #include <thread>
#include "DirectoryChangeService.hpp"
void DirectoryChangeService::_init(const char* directoryPath)
{
this->signalWantToFinish = false;
this->workerThread = std::thread([this]{
while (!signalWantToFinish)
{
auto info = this->directoryChangeReader.Read();
if (info.action != ChangeInformation::Action::None)
{
this->queueMutex.lock();
queue.push(info);
this->queueMutex.unlock();
}
}
});
}
DirectoryChangeService::DirectoryChangeService(const std::string& directoryPath) : directoryChangeReader(directoryPath)
{
_init(directoryPath.c_str());
}
DirectoryChangeService::DirectoryChangeService(const char* directoryPath) : directoryChangeReader(directoryPath)
{
_init(directoryPath);
}
DirectoryChangeService::~DirectoryChangeService()
{
this->signalWantToFinish = true;
this->directoryChangeReader.CancelPendingRead();
this->workerThread.join();
}
bool DirectoryChangeService::HasChange()
{
this->queueMutex.lock();
auto hasChange = queue.size() > 0;
this->queueMutex.unlock();
return hasChange;
}
ChangeInformation DirectoryChangeService::ReadChange()
{
this->queueMutex.lock();
auto data = queue.front();
queue.pop();
this->queueMutex.unlock();
return data;
}
| [
"peterekepeter@gmail.com"
] | peterekepeter@gmail.com |
2bb13dc38875c005a0bddbdca830460776479440 | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/squid/hunk_3334.cpp | 2cab156dede89951ec3a972b84b9dac05a992452 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,762 | cpp | return false;
}
-int
-AuthDigestUserRequest::authenticated() const
-{
- if (credentials() == Ok)
- return 1;
-
- return 0;
-}
-
-/** log a digest user in
- */
-void
-AuthDigestUserRequest::authenticate(HttpRequest * request, ConnStateData * conn, http_hdr_type type)
-{
- AuthUser *auth_user;
- AuthDigestUserRequest *digest_request;
- digest_user_h *digest_user;
-
- HASHHEX SESSIONKEY;
- HASHHEX HA2 = "";
- HASHHEX Response;
-
- assert(authUser() != NULL);
- auth_user = authUser();
-
- digest_user = dynamic_cast < digest_user_h * >(auth_user);
-
- assert(digest_user != NULL);
-
- /* if the check has corrupted the user, just return */
-
- if (credentials() == Failed) {
- return;
- }
-
- digest_request = this;
-
- /* do we have the HA1 */
-
- if (!digest_user->HA1created) {
- credentials(Pending);
- return;
- }
-
- if (digest_request->nonce == NULL) {
- /* this isn't a nonce we issued */
- credentials(Failed);
- return;
- }
-
- DigestCalcHA1(digest_request->algorithm, NULL, NULL, NULL,
- authenticateDigestNonceNonceb64(digest_request->nonce),
- digest_request->cnonce,
- digest_user->HA1, SESSIONKEY);
- DigestCalcResponse(SESSIONKEY, authenticateDigestNonceNonceb64(digest_request->nonce),
- digest_request->nc, digest_request->cnonce, digest_request->qop,
- RequestMethodStr(request->method), digest_request->uri, HA2, Response);
-
- debugs(29, 9, "\nResponse = '" << digest_request->response << "'\nsquid is = '" << Response << "'");
-
- if (strcasecmp(digest_request->response, Response) != 0) {
- if (!digest_request->flags.helper_queried) {
- /* Query the helper in case the password has changed */
- digest_request->flags.helper_queried = 1;
- digest_request->credentials_ok = Pending;
- return;
- }
-
- if (digestConfig.PostWorkaround && request->method != METHOD_GET) {
- /* Ugly workaround for certain very broken browsers using the
- * wrong method to calculate the request-digest on POST request.
- * This should be deleted once Digest authentication becomes more
- * widespread and such broken browsers no longer are commonly
- * used.
- */
- DigestCalcResponse(SESSIONKEY, authenticateDigestNonceNonceb64(digest_request->nonce),
- digest_request->nc, digest_request->cnonce, digest_request->qop,
- RequestMethodStr(METHOD_GET), digest_request->uri, HA2, Response);
-
- if (strcasecmp(digest_request->response, Response)) {
- credentials(Failed);
- digest_request->flags.invalid_password = 1;
- digest_request->setDenyMessage("Incorrect password");
- return;
- } else {
- const char *useragent = request->header.getStr(HDR_USER_AGENT);
-
- static Ip::Address last_broken_addr;
- static int seen_broken_client = 0;
-
- if (!seen_broken_client) {
- last_broken_addr.SetNoAddr();
- seen_broken_client = 1;
- }
-
- if (last_broken_addr != request->client_addr) {
- debugs(29, 1, "\nDigest POST bug detected from " <<
- request->client_addr << " using '" <<
- (useragent ? useragent : "-") <<
- "'. Please upgrade browser. See Bug #630 for details.");
-
- last_broken_addr = request->client_addr;
- }
- }
- } else {
- credentials(Failed);
- digest_request->flags.invalid_password = 1;
- digest_request->setDenyMessage("Incorrect password");
- return;
- }
-
- /* check for stale nonce */
- if (!authDigestNonceIsValid(digest_request->nonce, digest_request->nc)) {
- debugs(29, 3, "authenticateDigestAuthenticateuser: user '" << digest_user->username() << "' validated OK but nonce stale");
- credentials(Failed);
- digest_request->setDenyMessage("Stale nonce");
- return;
- }
- }
-
- credentials(Ok);
-
- /* password was checked and did match */
- debugs(29, 4, "authenticateDigestAuthenticateuser: user '" << digest_user->username() << "' validated OK");
-
- /* auth_user is now linked, we reset these values
- * after external auth occurs anyway */
- auth_user->expiretime = current_time.tv_sec;
- return;
-}
-
-int
-AuthDigestUserRequest::module_direction()
-{
- switch (credentials()) {
-
- case Unchecked:
- return -1;
-
- case Ok:
-
- return 0;
-
- case Pending:
- return -1;
-
- case Failed:
-
- /* send new challenge */
- return 1;
- }
-
- return -2;
-}
-
-/* add the [proxy]authorisation header */
-void
-AuthDigestUserRequest::addHeader(HttpReply * rep, int accel)
-{
- http_hdr_type type;
-
- /* don't add to authentication error pages */
-
- if ((!accel && rep->sline.status == HTTP_PROXY_AUTHENTICATION_REQUIRED)
- || (accel && rep->sline.status == HTTP_UNAUTHORIZED))
- return;
-
- type = accel ? HDR_AUTHENTICATION_INFO : HDR_PROXY_AUTHENTICATION_INFO;
-
-#if WAITING_FOR_TE
- /* test for http/1.1 transfer chunked encoding */
- if (chunkedtest)
- return;
-
-#endif
-
- if ((digestConfig.authenticate) && authDigestNonceLastRequest(nonce)) {
- flags.authinfo_sent = 1;
- debugs(29, 9, "authDigestAddHead: Sending type:" << type << " header: 'nextnonce=\"" << authenticateDigestNonceNonceb64(nonce) << "\"");
- httpHeaderPutStrf(&rep->header, type, "nextnonce=\"%s\"", authenticateDigestNonceNonceb64(nonce));
- }
-}
-
-#if WAITING_FOR_TE
-/* add the [proxy]authorisation header */
-void
-AuthDigestUserRequest::addTrailer(HttpReply * rep, int accel)
-{
- int type;
-
- if (!auth_user_request)
- return;
-
-
- /* has the header already been send? */
- if (flags.authinfo_sent)
- return;
-
- /* don't add to authentication error pages */
- if ((!accel && rep->sline.status == HTTP_PROXY_AUTHENTICATION_REQUIRED)
- || (accel && rep->sline.status == HTTP_UNAUTHORIZED))
- return;
-
- type = accel ? HDR_AUTHENTICATION_INFO : HDR_PROXY_AUTHENTICATION_INFO;
-
- if ((digestConfig.authenticate) && authDigestNonceLastRequest(nonce)) {
- debugs(29, 9, "authDigestAddTrailer: Sending type:" << type << " header: 'nextnonce=\"" << authenticateDigestNonceNonceb64(nonce) << "\"");
- httpTrailerPutStrf(&rep->header, type, "nextnonce=\"%s\"", authenticateDigestNonceNonceb64(nonce));
- }
-}
-
-#endif
-
/* add the [www-|Proxy-]authenticate header on a 407 or 401 reply */
void
-AuthDigestConfig::fixHeader(AuthUserRequest *auth_user_request, HttpReply *rep, http_hdr_type hdrType, HttpRequest * request)
+AuthDigestConfig::fixHeader(AuthUserRequest::Pointer auth_user_request, HttpReply *rep, http_hdr_type hdrType, HttpRequest * request)
{
if (!authenticate)
return;
int stale = 0;
- if (auth_user_request) {
+ if (auth_user_request != NULL) {
AuthDigestUserRequest *digest_request;
- digest_request = dynamic_cast < AuthDigestUserRequest * >(auth_user_request);
+ digest_request = dynamic_cast<AuthDigestUserRequest*>(auth_user_request.getRaw());
assert (digest_request != NULL);
stale = !digest_request->flags.invalid_password;
| [
"993273596@qq.com"
] | 993273596@qq.com |
da4d3e111d492c83e8621ce57f5828668d42dfae | 73945c14469d40ef1728e7f080718d790a53cbb2 | /LeetCode/1_TwoSum.cpp | 50356ddfcb50a662ffc84bb967a716bebd680aec | [] | no_license | bohaoist/codex | 426d16fd0d17c3415b2a2bec0583aa7c43a332eb | 75020880e8e381362c7851b26a67f374246ea072 | refs/heads/master | 2020-07-22T08:29:59.623928 | 2019-09-19T06:28:25 | 2019-09-19T06:28:25 | 207,131,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 254 | cpp | #include <iostream>
#include <vector>
#include <windows.h>
using namespace std;
int main()
{
cout << "hedy, I love you!" << endl;
vector<int> aa;
aa.push_back(5);
cout << aa[0] << endl;
system("pause");
return 0;
}
| [
"bertrandhao@tencent.com"
] | bertrandhao@tencent.com |
6ba4de55ced84b1d7bbfc92909bbd2ff2d1a4af9 | d76e27eb665ec055cdc615650c4e55ccb735347c | /vendor/wabt-sys/wabt/src/c-writer.cc | 4039e6f95a777b596dcc96a059bdcf1cb4bb74a1 | [
"Apache-2.0",
"Unlicense",
"BSD-3-Clause",
"0BSD",
"MIT"
] | permissive | mesalock-linux/crates-io | 1f14e54708bf304750702b8a5ccafcd2f2656bf3 | 5d8a4374276778da1ef3f35c3d1f294143275fbe | refs/heads/master | 2023-03-31T11:38:04.821749 | 2021-07-04T00:19:20 | 2021-07-05T04:20:25 | 224,273,714 | 1 | 8 | Apache-2.0 | 2023-03-25T00:44:00 | 2019-11-26T19:51:24 | Python | UTF-8 | C++ | false | false | 66,366 | cc | /*
* Copyright 2017 WebAssembly Community Group participants
*
* 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 "src/c-writer.h"
#include <cctype>
#include <cinttypes>
#include <map>
#include <set>
#include "src/cast.h"
#include "src/common.h"
#include "src/ir.h"
#include "src/literal.h"
#include "src/stream.h"
#include "src/string-view.h"
#define INDENT_SIZE 2
#define UNIMPLEMENTED(x) printf("unimplemented: %s\n", (x)), abort()
namespace wabt {
namespace {
struct Label {
Label(LabelType label_type,
const std::string& name,
const BlockSignature& sig,
size_t type_stack_size,
bool used = false)
: label_type(label_type),
name(name),
sig(sig),
type_stack_size(type_stack_size),
used(used) {}
bool HasValue() const {
return label_type != LabelType::Loop && !sig.empty();
}
LabelType label_type;
const std::string& name;
const BlockSignature& sig;
size_t type_stack_size;
bool used = false;
};
template <int>
struct Name {
explicit Name(const std::string& name) : name(name) {}
const std::string& name;
};
typedef Name<0> LocalName;
typedef Name<1> GlobalName;
typedef Name<2> ExternalPtr;
typedef Name<3> ExternalRef;
struct GotoLabel {
explicit GotoLabel(const Var& var) : var(var) {}
const Var& var;
};
struct LabelDecl {
explicit LabelDecl(const std::string& name) : name(name) {}
std::string name;
};
struct GlobalVar {
explicit GlobalVar(const Var& var) : var(var) {}
const Var& var;
};
struct StackVar {
explicit StackVar(Index index, Type type = Type::Any)
: index(index), type(type) {}
Index index;
Type type;
};
struct TypeEnum {
explicit TypeEnum(Type type) : type(type) {}
Type type;
};
struct SignedType {
explicit SignedType(Type type) : type(type) {}
Type type;
};
struct ResultType {
explicit ResultType(const TypeVector& types) : types(types) {}
const TypeVector& types;
};
struct Newline {};
struct OpenBrace {};
struct CloseBrace {};
int GetShiftMask(Type type) {
switch (type) {
case Type::I32: return 31;
case Type::I64: return 63;
default: WABT_UNREACHABLE; return 0;
}
}
class CWriter {
public:
CWriter(Stream* c_stream,
Stream* h_stream,
const char* header_name,
const WriteCOptions* options)
: options_(options),
c_stream_(c_stream),
h_stream_(h_stream),
header_name_(header_name) {}
Result WriteModule(const Module&);
private:
typedef std::set<std::string> SymbolSet;
typedef std::map<std::string, std::string> SymbolMap;
typedef std::pair<Index, Type> StackTypePair;
typedef std::map<StackTypePair, std::string> StackVarSymbolMap;
void UseStream(Stream*);
void WriteCHeader();
void WriteCSource();
size_t MarkTypeStack() const;
void ResetTypeStack(size_t mark);
Type StackType(Index) const;
void PushType(Type);
void PushTypes(const TypeVector&);
void DropTypes(size_t count);
void PushLabel(LabelType,
const std::string& name,
const BlockSignature&,
bool used = false);
const Label* FindLabel(const Var& var);
bool IsTopLabelUsed() const;
void PopLabel();
static std::string AddressOf(const std::string&);
static std::string Deref(const std::string&);
static char MangleType(Type);
static std::string MangleTypes(const TypeVector&);
static std::string MangleName(string_view);
static std::string MangleFuncName(string_view,
const TypeVector& param_types,
const TypeVector& result_types);
static std::string MangleGlobalName(string_view, Type);
static std::string LegalizeName(string_view);
static std::string ExportName(string_view mangled_name);
std::string DefineName(SymbolSet*, string_view);
std::string DefineImportName(const std::string& name,
string_view module_name,
string_view mangled_field_name);
std::string DefineGlobalScopeName(const std::string&);
std::string DefineLocalScopeName(const std::string&);
std::string DefineStackVarName(Index, Type, string_view);
void Indent(int size = INDENT_SIZE);
void Dedent(int size = INDENT_SIZE);
void WriteIndent();
void WriteData(const void* src, size_t size);
void Writef(const char* format, ...);
template <typename T, typename U, typename... Args>
void Write(T&& t, U&& u, Args&&... args) {
Write(std::forward<T>(t));
Write(std::forward<U>(u));
Write(std::forward<Args>(args)...);
}
std::string GetGlobalName(const std::string&) const;
enum class WriteExportsKind {
Declarations,
Definitions,
Initializers,
};
void Write() {}
void Write(Newline);
void Write(OpenBrace);
void Write(CloseBrace);
void Write(Index);
void Write(string_view);
void Write(const LocalName&);
void Write(const GlobalName&);
void Write(const ExternalPtr&);
void Write(const ExternalRef&);
void Write(Type);
void Write(SignedType);
void Write(TypeEnum);
void Write(const Var&);
void Write(const GotoLabel&);
void Write(const LabelDecl&);
void Write(const GlobalVar&);
void Write(const StackVar&);
void Write(const ResultType&);
void Write(const Const&);
void WriteInitExpr(const ExprList&);
void InitGlobalSymbols();
std::string GenerateHeaderGuard() const;
void WriteSourceTop();
void WriteFuncTypes();
void WriteImports();
void WriteFuncDeclarations();
void WriteFuncDeclaration(const FuncDeclaration&, const std::string&);
void WriteGlobals();
void WriteGlobal(const Global&, const std::string&);
void WriteMemories();
void WriteMemory(const std::string&);
void WriteTables();
void WriteTable(const std::string&);
void WriteDataInitializers();
void WriteElemInitializers();
void WriteInitExports();
void WriteExports(WriteExportsKind);
void WriteInit();
void WriteFuncs();
void Write(const Func&);
void WriteParams();
void WriteLocals();
void WriteStackVarDeclarations();
void Write(const ExprList&);
enum class AssignOp {
Disallowed,
Allowed,
};
void WriteSimpleUnaryExpr(Opcode, const char* op);
void WriteInfixBinaryExpr(Opcode,
const char* op,
AssignOp = AssignOp::Allowed);
void WritePrefixBinaryExpr(Opcode, const char* op);
void WriteSignedBinaryExpr(Opcode, const char* op);
void Write(const BinaryExpr&);
void Write(const CompareExpr&);
void Write(const ConvertExpr&);
void Write(const LoadExpr&);
void Write(const StoreExpr&);
void Write(const UnaryExpr&);
void Write(const TernaryExpr&);
void Write(const SimdLaneOpExpr&);
void Write(const SimdShuffleOpExpr&);
const WriteCOptions* options_ = nullptr;
const Module* module_ = nullptr;
const Func* func_ = nullptr;
Stream* stream_ = nullptr;
MemoryStream func_stream_;
Stream* c_stream_ = nullptr;
Stream* h_stream_ = nullptr;
std::string header_name_;
Result result_ = Result::Ok;
int indent_ = 0;
bool should_write_indent_next_ = false;
SymbolMap global_sym_map_;
SymbolMap local_sym_map_;
StackVarSymbolMap stack_var_sym_map_;
SymbolSet global_syms_;
SymbolSet local_syms_;
SymbolSet import_syms_;
TypeVector type_stack_;
std::vector<Label> label_stack_;
};
static const char kImplicitFuncLabel[] = "$Bfunc";
static const char* s_global_symbols[] = {
// keywords
"_Alignas", "_Alignof", "asm", "_Atomic", "auto", "_Bool", "break", "case",
"char", "_Complex", "const", "continue", "default", "do", "double", "else",
"enum", "extern", "float", "for", "_Generic", "goto", "if", "_Imaginary",
"inline", "int", "long", "_Noreturn", "_Pragma", "register", "restrict",
"return", "short", "signed", "sizeof", "static", "_Static_assert", "struct",
"switch", "_Thread_local", "typedef", "union", "unsigned", "void",
"volatile", "while",
// assert.h
"assert", "static_assert",
// math.h
"abs", "acos", "acosh", "asin", "asinh", "atan", "atan2", "atanh", "cbrt",
"ceil", "copysign", "cos", "cosh", "double_t", "erf", "erfc", "exp", "exp2",
"expm1", "fabs", "fdim", "float_t", "floor", "fma", "fmax", "fmin", "fmod",
"fpclassify", "FP_FAST_FMA", "FP_FAST_FMAF", "FP_FAST_FMAL", "FP_ILOGB0",
"FP_ILOGBNAN", "FP_INFINITE", "FP_NAN", "FP_NORMAL", "FP_SUBNORMAL",
"FP_ZERO", "frexp", "HUGE_VAL", "HUGE_VALF", "HUGE_VALL", "hypot", "ilogb",
"INFINITY", "isfinite", "isgreater", "isgreaterequal", "isinf", "isless",
"islessequal", "islessgreater", "isnan", "isnormal", "isunordered", "ldexp",
"lgamma", "llrint", "llround", "log", "log10", "log1p", "log2", "logb",
"lrint", "lround", "MATH_ERREXCEPT", "math_errhandling", "MATH_ERRNO",
"modf", "nan", "NAN", "nanf", "nanl", "nearbyint", "nextafter",
"nexttoward", "pow", "remainder", "remquo", "rint", "round", "scalbln",
"scalbn", "signbit", "sin", "sinh", "sqrt", "tan", "tanh", "tgamma",
"trunc",
// stdint.h
"INT16_C", "INT16_MAX", "INT16_MIN", "int16_t", "INT32_MAX", "INT32_MIN",
"int32_t", "INT64_C", "INT64_MAX", "INT64_MIN", "int64_t", "INT8_C",
"INT8_MAX", "INT8_MIN", "int8_t", "INT_FAST16_MAX", "INT_FAST16_MIN",
"int_fast16_t", "INT_FAST32_MAX", "INT_FAST32_MIN", "int_fast32_t",
"INT_FAST64_MAX", "INT_FAST64_MIN", "int_fast64_t", "INT_FAST8_MAX",
"INT_FAST8_MIN", "int_fast8_t", "INT_LEAST16_MAX", "INT_LEAST16_MIN",
"int_least16_t", "INT_LEAST32_MAX", "INT_LEAST32_MIN", "int_least32_t",
"INT_LEAST64_MAX", "INT_LEAST64_MIN", "int_least64_t", "INT_LEAST8_MAX",
"INT_LEAST8_MIN", "int_least8_t", "INTMAX_C", "INTMAX_MAX", "INTMAX_MIN",
"intmax_t", "INTPTR_MAX", "INTPTR_MIN", "intptr_t", "PTRDIFF_MAX",
"PTRDIFF_MIN", "SIG_ATOMIC_MAX", "SIG_ATOMIC_MIN", "SIZE_MAX", "UINT16_C",
"UINT16_MAX", "uint16_t", "UINT32_C", "UINT32_MAX", "uint32_t", "UINT64_C",
"UINT64_MAX", "uint64_t", "UINT8_MAX", "uint8_t", "UINT_FAST16_MAX",
"uint_fast16_t", "UINT_FAST32_MAX", "uint_fast32_t", "UINT_FAST64_MAX",
"uint_fast64_t", "UINT_FAST8_MAX", "uint_fast8_t", "UINT_LEAST16_MAX",
"uint_least16_t", "UINT_LEAST32_MAX", "uint_least32_t", "UINT_LEAST64_MAX",
"uint_least64_t", "UINT_LEAST8_MAX", "uint_least8_t", "UINTMAX_C",
"UINTMAX_MAX", "uintmax_t", "UINTPTR_MAX", "uintptr_t", "UNT8_C",
"WCHAR_MAX", "WCHAR_MIN", "WINT_MAX", "WINT_MIN",
// stdlib.h
"abort", "abs", "atexit", "atof", "atoi", "atol", "atoll", "at_quick_exit",
"bsearch", "calloc", "div", "div_t", "exit", "_Exit", "EXIT_FAILURE",
"EXIT_SUCCESS", "free", "getenv", "labs", "ldiv", "ldiv_t", "llabs",
"lldiv", "lldiv_t", "malloc", "MB_CUR_MAX", "mblen", "mbstowcs", "mbtowc",
"qsort", "quick_exit", "rand", "RAND_MAX", "realloc", "size_t", "srand",
"strtod", "strtof", "strtol", "strtold", "strtoll", "strtoul", "strtoull",
"system", "wcstombs", "wctomb",
// string.h
"memchr", "memcmp", "memcpy", "memmove", "memset", "NULL", "size_t",
"strcat", "strchr", "strcmp", "strcoll", "strcpy", "strcspn", "strerror",
"strlen", "strncat", "strncmp", "strncpy", "strpbrk", "strrchr", "strspn",
"strstr", "strtok", "strxfrm",
// defined
"CALL_INDIRECT", "DEFINE_LOAD", "DEFINE_REINTERPRET", "DEFINE_STORE",
"DIVREM_U", "DIV_S", "DIV_U", "f32", "f32_load", "f32_reinterpret_i32",
"f32_store", "f64", "f64_load", "f64_reinterpret_i64", "f64_store", "FMAX",
"FMIN", "FUNC_EPILOGUE", "FUNC_PROLOGUE", "func_types", "I32_CLZ",
"I32_CLZ", "I32_DIV_S", "i32_load", "i32_load16_s", "i32_load16_u",
"i32_load8_s", "i32_load8_u", "I32_POPCNT", "i32_reinterpret_f32",
"I32_REM_S", "I32_ROTL", "I32_ROTR", "i32_store", "i32_store16",
"i32_store8", "I32_TRUNC_S_F32", "I32_TRUNC_S_F64", "I32_TRUNC_U_F32",
"I32_TRUNC_U_F64", "I64_CTZ", "I64_CTZ", "I64_DIV_S", "i64_load",
"i64_load16_s", "i64_load16_u", "i64_load32_s", "i64_load32_u",
"i64_load8_s", "i64_load8_u", "I64_POPCNT", "i64_reinterpret_f64",
"I64_REM_S", "I64_ROTL", "I64_ROTR", "i64_store", "i64_store16",
"i64_store32", "i64_store8", "I64_TRUNC_S_F32", "I64_TRUNC_S_F64",
"I64_TRUNC_U_F32", "I64_TRUNC_U_F64", "init", "init_elem_segment",
"init_func_types", "init_globals", "init_memory", "init_table", "LIKELY",
"MEMCHECK", "REM_S", "REM_U", "ROTL", "ROTR", "s16", "s32", "s64", "s8",
"TRAP", "TRUNC_S", "TRUNC_U", "Type", "u16", "u32", "u64", "u8", "UNLIKELY",
"UNREACHABLE", "WASM_RT_ADD_PREFIX", "wasm_rt_allocate_memory",
"wasm_rt_allocate_table", "wasm_rt_anyfunc_t", "wasm_rt_call_stack_depth",
"wasm_rt_elem_t", "WASM_RT_F32", "WASM_RT_F64", "wasm_rt_grow_memory",
"WASM_RT_I32", "WASM_RT_I64", "WASM_RT_INCLUDED_",
"WASM_RT_MAX_CALL_STACK_DEPTH", "wasm_rt_memory_t", "WASM_RT_MODULE_PREFIX",
"WASM_RT_PASTE_", "WASM_RT_PASTE", "wasm_rt_register_func_type",
"wasm_rt_table_t", "wasm_rt_trap", "WASM_RT_TRAP_CALL_INDIRECT",
"WASM_RT_TRAP_DIV_BY_ZERO", "WASM_RT_TRAP_EXHAUSTION",
"WASM_RT_TRAP_INT_OVERFLOW", "WASM_RT_TRAP_INVALID_CONVERSION",
"WASM_RT_TRAP_NONE", "WASM_RT_TRAP_OOB", "wasm_rt_trap_t",
"WASM_RT_TRAP_UNREACHABLE",
};
#define SECTION_NAME(x) s_header_##x
#include "src/prebuilt/wasm2c.include.h"
#undef SECTION_NAME
#define SECTION_NAME(x) s_source_##x
#include "src/prebuilt/wasm2c.include.c"
#undef SECTION_NAME
size_t CWriter::MarkTypeStack() const {
return type_stack_.size();
}
void CWriter::ResetTypeStack(size_t mark) {
assert(mark <= type_stack_.size());
type_stack_.erase(type_stack_.begin() + mark, type_stack_.end());
}
Type CWriter::StackType(Index index) const {
assert(index < type_stack_.size());
return *(type_stack_.rbegin() + index);
}
void CWriter::PushType(Type type) {
type_stack_.push_back(type);
}
void CWriter::PushTypes(const TypeVector& types) {
type_stack_.insert(type_stack_.end(), types.begin(), types.end());
}
void CWriter::DropTypes(size_t count) {
assert(count <= type_stack_.size());
type_stack_.erase(type_stack_.end() - count, type_stack_.end());
}
void CWriter::PushLabel(LabelType label_type,
const std::string& name,
const BlockSignature& sig,
bool used) {
label_stack_.emplace_back(label_type, name, sig, type_stack_.size(), used);
}
const Label* CWriter::FindLabel(const Var& var) {
Label* label = nullptr;
if (var.is_index()) {
// We've generated names for all labels, so we should only be using an
// index when branching to the implicit function label, which can't be
// named.
assert(var.index() + 1 == label_stack_.size());
label = &label_stack_[0];
} else {
assert(var.is_name());
for (Index i = label_stack_.size(); i > 0; --i) {
label = &label_stack_[i - 1];
if (label->name == var.name())
break;
}
}
assert(label);
label->used = true;
return label;
}
bool CWriter::IsTopLabelUsed() const {
assert(!label_stack_.empty());
return label_stack_.back().used;
}
void CWriter::PopLabel() {
label_stack_.pop_back();
}
// static
std::string CWriter::AddressOf(const std::string& s) {
return "(&" + s + ")";
}
// static
std::string CWriter::Deref(const std::string& s) {
return "(*" + s + ")";
}
// static
char CWriter::MangleType(Type type) {
switch (type) {
case Type::I32: return 'i';
case Type::I64: return 'j';
case Type::F32: return 'f';
case Type::F64: return 'd';
default: WABT_UNREACHABLE;
}
}
// static
std::string CWriter::MangleTypes(const TypeVector& types) {
if (types.empty())
return std::string("v");
std::string result;
for (auto type : types) {
result += MangleType(type);
}
return result;
}
// static
std::string CWriter::MangleName(string_view name) {
const char kPrefix = 'Z';
std::string result = "Z_";
if (!name.empty()) {
for (char c : name) {
if ((isalnum(c) && c != kPrefix) || c == '_') {
result += c;
} else {
result += kPrefix;
result += StringPrintf("%02X", static_cast<uint8_t>(c));
}
}
}
return result;
}
// static
std::string CWriter::MangleFuncName(string_view name,
const TypeVector& param_types,
const TypeVector& result_types) {
std::string sig = MangleTypes(result_types) + MangleTypes(param_types);
return MangleName(name) + MangleName(sig);
}
// static
std::string CWriter::MangleGlobalName(string_view name, Type type) {
std::string sig(1, MangleType(type));
return MangleName(name) + MangleName(sig);
}
// static
std::string CWriter::ExportName(string_view mangled_name) {
return "WASM_RT_ADD_PREFIX(" + mangled_name.to_string() + ")";
}
// static
std::string CWriter::LegalizeName(string_view name) {
if (name.empty())
return "_";
std::string result;
result = isalpha(name[0]) ? name[0] : '_';
for (size_t i = 1; i < name.size(); ++i)
result += isalnum(name[i]) ? name[i] : '_';
return result;
}
std::string CWriter::DefineName(SymbolSet* set, string_view name) {
std::string legal = LegalizeName(name);
if (set->find(legal) != set->end()) {
std::string base = legal + "_";
size_t count = 0;
do {
legal = base + std::to_string(count++);
} while (set->find(legal) != set->end());
}
set->insert(legal);
return legal;
}
string_view StripLeadingDollar(string_view name) {
if (!name.empty() && name[0] == '$') {
name.remove_prefix(1);
}
return name;
}
std::string CWriter::DefineImportName(const std::string& name,
string_view module,
string_view mangled_field_name) {
std::string mangled = MangleName(module) + mangled_field_name.to_string();
import_syms_.insert(name);
global_syms_.insert(mangled);
global_sym_map_.insert(SymbolMap::value_type(name, mangled));
return "(*" + mangled + ")";
}
std::string CWriter::DefineGlobalScopeName(const std::string& name) {
std::string unique = DefineName(&global_syms_, StripLeadingDollar(name));
global_sym_map_.insert(SymbolMap::value_type(name, unique));
return unique;
}
std::string CWriter::DefineLocalScopeName(const std::string& name) {
std::string unique = DefineName(&local_syms_, StripLeadingDollar(name));
local_sym_map_.insert(SymbolMap::value_type(name, unique));
return unique;
}
std::string CWriter::DefineStackVarName(Index index,
Type type,
string_view name) {
std::string unique = DefineName(&local_syms_, name);
StackTypePair stp = {index, type};
stack_var_sym_map_.insert(StackVarSymbolMap::value_type(stp, unique));
return unique;
}
void CWriter::Indent(int size) {
indent_ += size;
}
void CWriter::Dedent(int size) {
indent_ -= size;
assert(indent_ >= 0);
}
void CWriter::WriteIndent() {
static char s_indent[] =
" "
" ";
static size_t s_indent_len = sizeof(s_indent) - 1;
size_t to_write = indent_;
while (to_write >= s_indent_len) {
stream_->WriteData(s_indent, s_indent_len);
to_write -= s_indent_len;
}
if (to_write > 0) {
stream_->WriteData(s_indent, to_write);
}
}
void CWriter::WriteData(const void* src, size_t size) {
if (should_write_indent_next_) {
WriteIndent();
should_write_indent_next_ = false;
}
stream_->WriteData(src, size);
}
void WABT_PRINTF_FORMAT(2, 3) CWriter::Writef(const char* format, ...) {
WABT_SNPRINTF_ALLOCA(buffer, length, format);
WriteData(buffer, length);
}
void CWriter::Write(Newline) {
Write("\n");
should_write_indent_next_ = true;
}
void CWriter::Write(OpenBrace) {
Write("{");
Indent();
Write(Newline());
}
void CWriter::Write(CloseBrace) {
Dedent();
Write("}");
}
void CWriter::Write(Index index) {
Writef("%" PRIindex, index);
}
void CWriter::Write(string_view s) {
WriteData(s.data(), s.size());
}
void CWriter::Write(const LocalName& name) {
assert(local_sym_map_.count(name.name) == 1);
Write(local_sym_map_[name.name]);
}
std::string CWriter::GetGlobalName(const std::string& name) const {
assert(global_sym_map_.count(name) == 1);
auto iter = global_sym_map_.find(name);
assert(iter != global_sym_map_.end());
return iter->second;
}
void CWriter::Write(const GlobalName& name) {
Write(GetGlobalName(name.name));
}
void CWriter::Write(const ExternalPtr& name) {
bool is_import = import_syms_.count(name.name) != 0;
if (is_import) {
Write(GetGlobalName(name.name));
} else {
Write(AddressOf(GetGlobalName(name.name)));
}
}
void CWriter::Write(const ExternalRef& name) {
bool is_import = import_syms_.count(name.name) != 0;
if (is_import) {
Write(Deref(GetGlobalName(name.name)));
} else {
Write(GetGlobalName(name.name));
}
}
void CWriter::Write(const Var& var) {
assert(var.is_name());
Write(LocalName(var.name()));
}
void CWriter::Write(const GotoLabel& goto_label) {
const Label* label = FindLabel(goto_label.var);
if (label->HasValue()) {
assert(label->sig.size() == 1);
assert(type_stack_.size() >= label->type_stack_size);
Index dst = type_stack_.size() - label->type_stack_size - 1;
if (dst != 0)
Write(StackVar(dst, label->sig[0]), " = ", StackVar(0), "; ");
}
if (goto_label.var.is_name()) {
Write("goto ", goto_label.var, ";");
} else {
// We've generated names for all labels, so we should only be using an
// index when branching to the implicit function label, which can't be
// named.
Write("goto ", Var(kImplicitFuncLabel), ";");
}
}
void CWriter::Write(const LabelDecl& label) {
if (IsTopLabelUsed())
Write(label.name, ":;", Newline());
}
void CWriter::Write(const GlobalVar& var) {
assert(var.var.is_name());
Write(ExternalRef(var.var.name()));
}
void CWriter::Write(const StackVar& sv) {
Index index = type_stack_.size() - 1 - sv.index;
Type type = sv.type;
if (type == Type::Any) {
assert(index < type_stack_.size());
type = type_stack_[index];
}
StackTypePair stp = {index, type};
auto iter = stack_var_sym_map_.find(stp);
if (iter == stack_var_sym_map_.end()) {
std::string name = MangleType(type) + std::to_string(index);
Write(DefineStackVarName(index, type, name));
} else {
Write(iter->second);
}
}
void CWriter::Write(Type type) {
switch (type) {
case Type::I32: Write("u32"); break;
case Type::I64: Write("u64"); break;
case Type::F32: Write("f32"); break;
case Type::F64: Write("f64"); break;
default:
WABT_UNREACHABLE;
}
}
void CWriter::Write(TypeEnum type) {
switch (type.type) {
case Type::I32: Write("WASM_RT_I32"); break;
case Type::I64: Write("WASM_RT_I64"); break;
case Type::F32: Write("WASM_RT_F32"); break;
case Type::F64: Write("WASM_RT_F64"); break;
default:
WABT_UNREACHABLE;
}
}
void CWriter::Write(SignedType type) {
switch (type.type) {
case Type::I32: Write("s32"); break;
case Type::I64: Write("s64"); break;
default:
WABT_UNREACHABLE;
}
}
void CWriter::Write(const ResultType& rt) {
if (!rt.types.empty()) {
Write(rt.types[0]);
} else {
Write("void");
}
}
void CWriter::Write(const Const& const_) {
switch (const_.type) {
case Type::I32:
Writef("%uu", static_cast<int32_t>(const_.u32));
break;
case Type::I64:
Writef("%" PRIu64 "ull", static_cast<int64_t>(const_.u64));
break;
case Type::F32: {
// TODO(binji): Share with similar float info in interp.cc and literal.cc
if ((const_.f32_bits & 0x7f800000u) == 0x7f800000u) {
const char* sign = (const_.f32_bits & 0x80000000) ? "-" : "";
uint32_t significand = const_.f32_bits & 0x7fffffu;
if (significand == 0) {
// Infinity.
Writef("%sINFINITY", sign);
} else {
// Nan.
Writef("f32_reinterpret_i32(0x%08x) /* %snan:0x%06x */",
const_.f32_bits, sign, significand);
}
} else if (const_.f32_bits == 0x80000000) {
// Negative zero. Special-cased so it isn't written as -0 below.
Writef("-0.f");
} else {
Writef("%.9g", Bitcast<float>(const_.f32_bits));
}
break;
}
case Type::F64:
// TODO(binji): Share with similar float info in interp.cc and literal.cc
if ((const_.f64_bits & 0x7ff0000000000000ull) == 0x7ff0000000000000ull) {
const char* sign = (const_.f64_bits & 0x8000000000000000ull) ? "-" : "";
uint64_t significand = const_.f64_bits & 0xfffffffffffffull;
if (significand == 0) {
// Infinity.
Writef("%sINFINITY", sign);
} else {
// Nan.
Writef("f64_reinterpret_i64(0x%016" PRIx64 ") /* %snan:0x%013" PRIx64
" */",
const_.f64_bits, sign, significand);
}
} else if (const_.f64_bits == 0x8000000000000000ull) {
// Negative zero. Special-cased so it isn't written as -0 below.
Writef("-0.0");
} else {
Writef("%.17g", Bitcast<double>(const_.f64_bits));
}
break;
default:
WABT_UNREACHABLE;
}
}
void CWriter::WriteInitExpr(const ExprList& expr_list) {
if (expr_list.empty())
return;
assert(expr_list.size() == 1);
const Expr* expr = &expr_list.front();
switch (expr_list.front().type()) {
case ExprType::Const:
Write(cast<ConstExpr>(expr)->const_);
break;
case ExprType::GetGlobal:
Write(GlobalVar(cast<GetGlobalExpr>(expr)->var));
break;
default:
WABT_UNREACHABLE;
}
}
void CWriter::InitGlobalSymbols() {
for (const char* symbol : s_global_symbols) {
global_syms_.insert(symbol);
}
}
std::string CWriter::GenerateHeaderGuard() const {
std::string result;
for (char c : header_name_) {
if (isalnum(c) || c == '_') {
result += toupper(c);
} else {
result += '_';
}
}
result += "_GENERATED_";
return result;
}
void CWriter::WriteSourceTop() {
Write(s_source_includes);
Write(Newline(), "#include \"", header_name_, "\"", Newline());
Write(s_source_declarations);
}
void CWriter::WriteFuncTypes() {
Write(Newline());
Writef("static u32 func_types[%" PRIzd "];", module_->func_types.size());
Write(Newline(), Newline());
Write("static void init_func_types(void) {", Newline());
Index func_type_index = 0;
for (FuncType* func_type : module_->func_types) {
Index num_params = func_type->GetNumParams();
Index num_results = func_type->GetNumResults();
Write(" func_types[", func_type_index, "] = wasm_rt_register_func_type(",
num_params, ", ", num_results);
for (Index i = 0; i < num_params; ++i) {
Write(", ", TypeEnum(func_type->GetParamType(i)));
}
for (Index i = 0; i < num_results; ++i) {
Write(", ", TypeEnum(func_type->GetResultType(i)));
}
Write(");", Newline());
++func_type_index;
}
Write("}", Newline());
}
void CWriter::WriteImports() {
if (module_->imports.empty())
return;
Write(Newline());
// TODO(binji): Write imports ordered by type.
for (const Import* import : module_->imports) {
Write("/* import: '", import->module_name, "' '", import->field_name,
"' */", Newline());
Write("extern ");
switch (import->kind()) {
case ExternalKind::Func: {
const Func& func = cast<FuncImport>(import)->func;
WriteFuncDeclaration(
func.decl,
DefineImportName(
func.name, import->module_name,
MangleFuncName(import->field_name, func.decl.sig.param_types,
func.decl.sig.result_types)));
Write(";");
break;
}
case ExternalKind::Global: {
const Global& global = cast<GlobalImport>(import)->global;
WriteGlobal(global,
DefineImportName(
global.name, import->module_name,
MangleGlobalName(import->field_name, global.type)));
Write(";");
break;
}
case ExternalKind::Memory: {
const Memory& memory = cast<MemoryImport>(import)->memory;
WriteMemory(DefineImportName(memory.name, import->module_name,
MangleName(import->field_name)));
break;
}
case ExternalKind::Table: {
const Table& table = cast<TableImport>(import)->table;
WriteTable(DefineImportName(table.name, import->module_name,
MangleName(import->field_name)));
break;
}
default:
WABT_UNREACHABLE;
}
Write(Newline());
}
}
void CWriter::WriteFuncDeclarations() {
if (module_->funcs.size() == module_->num_func_imports)
return;
Write(Newline());
Index func_index = 0;
for (const Func* func : module_->funcs) {
bool is_import = func_index < module_->num_func_imports;
if (!is_import) {
Write("static ");
WriteFuncDeclaration(func->decl, DefineGlobalScopeName(func->name));
Write(";", Newline());
}
++func_index;
}
}
void CWriter::WriteFuncDeclaration(const FuncDeclaration& decl,
const std::string& name) {
Write(ResultType(decl.sig.result_types), " ", name, "(");
if (decl.GetNumParams() == 0) {
Write("void");
} else {
for (Index i = 0; i < decl.GetNumParams(); ++i) {
if (i != 0)
Write(", ");
Write(decl.GetParamType(i));
}
}
Write(")");
}
void CWriter::WriteGlobals() {
Index global_index = 0;
if (module_->globals.size() != module_->num_global_imports) {
Write(Newline());
for (const Global* global : module_->globals) {
bool is_import = global_index < module_->num_global_imports;
if (!is_import) {
Write("static ");
WriteGlobal(*global, DefineGlobalScopeName(global->name));
Write(";", Newline());
}
++global_index;
}
}
Write(Newline(), "static void init_globals(void) ", OpenBrace());
global_index = 0;
for (const Global* global : module_->globals) {
bool is_import = global_index < module_->num_global_imports;
if (!is_import) {
assert(!global->init_expr.empty());
Write(GlobalName(global->name), " = ");
WriteInitExpr(global->init_expr);
Write(";", Newline());
}
++global_index;
}
Write(CloseBrace(), Newline());
}
void CWriter::WriteGlobal(const Global& global, const std::string& name) {
Write(global.type, " ", name);
}
void CWriter::WriteMemories() {
if (module_->memories.size() == module_->num_memory_imports)
return;
Write(Newline());
assert(module_->memories.size() <= 1);
Index memory_index = 0;
for (const Memory* memory : module_->memories) {
bool is_import = memory_index < module_->num_memory_imports;
if (!is_import) {
Write("static ");
WriteMemory(DefineGlobalScopeName(memory->name));
Write(Newline());
}
++memory_index;
}
}
void CWriter::WriteMemory(const std::string& name) {
Write("wasm_rt_memory_t ", name, ";");
}
void CWriter::WriteTables() {
if (module_->tables.size() == module_->num_table_imports)
return;
Write(Newline());
assert(module_->tables.size() <= 1);
Index table_index = 0;
for (const Table* table : module_->tables) {
bool is_import = table_index < module_->num_table_imports;
if (!is_import) {
Write("static ");
WriteTable(DefineGlobalScopeName(table->name));
Write(Newline());
}
++table_index;
}
}
void CWriter::WriteTable(const std::string& name) {
Write("wasm_rt_table_t ", name, ";");
}
void CWriter::WriteDataInitializers() {
const Memory* memory = nullptr;
Index data_segment_index = 0;
if (!module_->memories.empty()) {
if (module_->data_segments.empty()) {
Write(Newline());
} else {
for (const DataSegment* data_segment : module_->data_segments) {
Write(Newline(), "static const u8 data_segment_data_",
data_segment_index, "[] = ", OpenBrace());
size_t i = 0;
for (uint8_t x : data_segment->data) {
Writef("0x%02x, ", x);
if ((++i % 12) == 0)
Write(Newline());
}
if (i > 0)
Write(Newline());
Write(CloseBrace(), ";", Newline());
++data_segment_index;
}
}
memory = module_->memories[0];
}
Write(Newline(), "static void init_memory(void) ", OpenBrace());
if (memory && module_->num_memory_imports == 0) {
uint32_t max =
memory->page_limits.has_max ? memory->page_limits.max : 65536;
Write("wasm_rt_allocate_memory(", ExternalPtr(memory->name), ", ",
memory->page_limits.initial, ", ", max, ");", Newline());
}
data_segment_index = 0;
for (const DataSegment* data_segment : module_->data_segments) {
Write("memcpy(&(", ExternalRef(memory->name), ".data[");
WriteInitExpr(data_segment->offset);
Write("]), data_segment_data_", data_segment_index, ", ",
data_segment->data.size(), ");", Newline());
++data_segment_index;
}
Write(CloseBrace(), Newline());
}
void CWriter::WriteElemInitializers() {
const Table* table = module_->tables.empty() ? nullptr : module_->tables[0];
Write(Newline(), "static void init_table(void) ", OpenBrace());
Write("uint32_t offset;", Newline());
if (table && module_->num_table_imports == 0) {
uint32_t max =
table->elem_limits.has_max ? table->elem_limits.max : UINT32_MAX;
Write("wasm_rt_allocate_table(", ExternalPtr(table->name), ", ",
table->elem_limits.initial, ", ", max, ");", Newline());
}
Index elem_segment_index = 0;
for (const ElemSegment* elem_segment : module_->elem_segments) {
Write("offset = ");
WriteInitExpr(elem_segment->offset);
Write(";", Newline());
size_t i = 0;
for (const Var& var : elem_segment->vars) {
const Func* func = module_->GetFunc(var);
Index func_type_index = module_->GetFuncTypeIndex(func->decl.type_var);
Write(ExternalRef(table->name), ".data[offset + ", i,
"] = (wasm_rt_elem_t){func_types[", func_type_index,
"], (wasm_rt_anyfunc_t)", ExternalPtr(func->name), "};", Newline());
++i;
}
++elem_segment_index;
}
Write(CloseBrace(), Newline());
}
void CWriter::WriteInitExports() {
Write(Newline(), "static void init_exports(void) ", OpenBrace());
WriteExports(WriteExportsKind::Initializers);
Write(CloseBrace(), Newline());
}
void CWriter::WriteExports(WriteExportsKind kind) {
if (module_->exports.empty())
return;
if (kind != WriteExportsKind::Initializers) {
Write(Newline());
}
for (const Export* export_ : module_->exports) {
Write("/* export: '", export_->name, "' */", Newline());
if (kind == WriteExportsKind::Declarations) {
Write("extern ");
}
std::string mangled_name;
std::string internal_name;
switch (export_->kind) {
case ExternalKind::Func: {
const Func* func = module_->GetFunc(export_->var);
mangled_name =
ExportName(MangleFuncName(export_->name, func->decl.sig.param_types,
func->decl.sig.result_types));
internal_name = func->name;
if (kind != WriteExportsKind::Initializers) {
WriteFuncDeclaration(func->decl, Deref(mangled_name));
Write(";");
}
break;
}
case ExternalKind::Global: {
const Global* global = module_->GetGlobal(export_->var);
mangled_name =
ExportName(MangleGlobalName(export_->name, global->type));
internal_name = global->name;
if (kind != WriteExportsKind::Initializers) {
WriteGlobal(*global, Deref(mangled_name));
Write(";");
}
break;
}
case ExternalKind::Memory: {
const Memory* memory = module_->GetMemory(export_->var);
mangled_name = ExportName(MangleName(export_->name));
internal_name = memory->name;
if (kind != WriteExportsKind::Initializers) {
WriteMemory(Deref(mangled_name));
}
break;
}
case ExternalKind::Table: {
const Table* table = module_->GetTable(export_->var);
mangled_name = ExportName(MangleName(export_->name));
internal_name = table->name;
if (kind != WriteExportsKind::Initializers) {
WriteTable(Deref(mangled_name));
}
break;
}
default:
WABT_UNREACHABLE;
}
if (kind == WriteExportsKind::Initializers) {
Write(mangled_name, " = ", ExternalPtr(internal_name), ";");
}
Write(Newline());
}
}
void CWriter::WriteInit() {
Write(Newline(), "void WASM_RT_ADD_PREFIX(init)(void) ", OpenBrace());
Write("init_func_types();", Newline());
Write("init_globals();", Newline());
Write("init_memory();", Newline());
Write("init_table();", Newline());
Write("init_exports();", Newline());
for (Var* var : module_->starts) {
Write(ExternalRef(module_->GetFunc(*var)->name), "();", Newline());
}
Write(CloseBrace(), Newline());
}
void CWriter::WriteFuncs() {
Index func_index = 0;
for (const Func* func : module_->funcs) {
bool is_import = func_index < module_->num_func_imports;
if (!is_import)
Write(Newline(), *func, Newline());
++func_index;
}
}
void CWriter::Write(const Func& func) {
func_ = &func;
// Copy symbols from global symbol table so we don't shadow them.
local_syms_ = global_syms_;
local_sym_map_.clear();
stack_var_sym_map_.clear();
Write("static ", ResultType(func.decl.sig.result_types), " ",
GlobalName(func.name), "(");
WriteParams();
WriteLocals();
Write("FUNC_PROLOGUE;", Newline());
stream_ = &func_stream_;
stream_->ClearOffset();
std::string label = DefineLocalScopeName(kImplicitFuncLabel);
ResetTypeStack(0);
std::string empty; // Must not be temporary, since address is taken by Label.
PushLabel(LabelType::Func, empty, func.decl.sig.result_types);
Write(func.exprs, LabelDecl(label));
PopLabel();
ResetTypeStack(0);
PushTypes(func.decl.sig.result_types);
Write("FUNC_EPILOGUE;", Newline());
if (!func.decl.sig.result_types.empty()) {
// Return the top of the stack implicitly.
Write("return ", StackVar(0), ";", Newline());
}
stream_ = c_stream_;
WriteStackVarDeclarations();
std::unique_ptr<OutputBuffer> buf = func_stream_.ReleaseOutputBuffer();
stream_->WriteData(buf->data.data(), buf->data.size());
Write(CloseBrace());
func_stream_.Clear();
func_ = nullptr;
}
void CWriter::WriteParams() {
if (func_->decl.sig.param_types.empty()) {
Write("void");
} else {
std::vector<std::string> index_to_name;
MakeTypeBindingReverseMapping(func_->decl.sig.param_types.size(),
func_->param_bindings, &index_to_name);
Indent(4);
for (Index i = 0; i < func_->GetNumParams(); ++i) {
if (i != 0) {
Write(", ");
if ((i % 8) == 0)
Write(Newline());
}
Write(func_->GetParamType(i), " ",
DefineLocalScopeName(index_to_name[i]));
}
Dedent(4);
}
Write(") ", OpenBrace());
}
void CWriter::WriteLocals() {
std::vector<std::string> index_to_name;
MakeTypeBindingReverseMapping(func_->local_types.size(),
func_->local_bindings, &index_to_name);
for (Type type : {Type::I32, Type::I64, Type::F32, Type::F64}) {
Index local_index = 0;
size_t count = 0;
for (Type local_type : func_->local_types) {
if (local_type == type) {
if (count == 0) {
Write(type, " ");
Indent(4);
} else {
Write(", ");
if ((count % 8) == 0)
Write(Newline());
}
Write(DefineLocalScopeName(index_to_name[local_index]), " = 0");
++count;
}
++local_index;
}
if (count != 0) {
Dedent(4);
Write(";", Newline());
}
}
}
void CWriter::WriteStackVarDeclarations() {
for (Type type : {Type::I32, Type::I64, Type::F32, Type::F64}) {
size_t count = 0;
for (const auto& pair : stack_var_sym_map_) {
Type stp_type = pair.first.second;
const std::string& name = pair.second;
if (stp_type == type) {
if (count == 0) {
Write(type, " ");
Indent(4);
} else {
Write(", ");
if ((count % 8) == 0)
Write(Newline());
}
Write(name);
++count;
}
}
if (count != 0) {
Dedent(4);
Write(";", Newline());
}
}
}
void CWriter::Write(const ExprList& exprs) {
for (const Expr& expr : exprs) {
switch (expr.type()) {
case ExprType::Binary:
Write(*cast<BinaryExpr>(&expr));
break;
case ExprType::Block: {
const Block& block = cast<BlockExpr>(&expr)->block;
std::string label = DefineLocalScopeName(block.label);
size_t mark = MarkTypeStack();
PushLabel(LabelType::Block, block.label, block.sig);
Write(block.exprs, LabelDecl(label));
ResetTypeStack(mark);
PopLabel();
PushTypes(block.sig);
break;
}
case ExprType::Br:
Write(GotoLabel(cast<BrExpr>(&expr)->var), Newline());
// Stop processing this ExprList, since the following are unreachable.
return;
case ExprType::BrIf:
Write("if (", StackVar(0), ") {");
DropTypes(1);
Write(GotoLabel(cast<BrIfExpr>(&expr)->var), "}", Newline());
break;
case ExprType::BrTable: {
const auto* bt_expr = cast<BrTableExpr>(&expr);
Write("switch (", StackVar(0), ") ", OpenBrace());
DropTypes(1);
Index i = 0;
for (const Var& var : bt_expr->targets) {
Write("case ", i++, ": ", GotoLabel(var), Newline());
}
Write("default: ");
Write(GotoLabel(bt_expr->default_target), Newline(), CloseBrace(),
Newline());
// Stop processing this ExprList, since the following are unreachable.
return;
}
case ExprType::Call: {
const Var& var = cast<CallExpr>(&expr)->var;
const Func& func = *module_->GetFunc(var);
Index num_params = func.GetNumParams();
Index num_results = func.GetNumResults();
assert(type_stack_.size() >= num_params);
if (num_results > 0) {
assert(num_results == 1);
Write(StackVar(num_params - 1, func.GetResultType(0)), " = ");
}
Write(GlobalVar(var), "(");
for (Index i = 0; i < num_params; ++i) {
if (i != 0) {
Write(", ");
}
Write(StackVar(num_params - i - 1));
}
Write(");", Newline());
DropTypes(num_params);
PushTypes(func.decl.sig.result_types);
break;
}
case ExprType::CallIndirect: {
const FuncDeclaration& decl = cast<CallIndirectExpr>(&expr)->decl;
Index num_params = decl.GetNumParams();
Index num_results = decl.GetNumResults();
assert(type_stack_.size() > num_params);
if (num_results > 0) {
assert(num_results == 1);
Write(StackVar(num_params, decl.GetResultType(0)), " = ");
}
assert(module_->tables.size() == 1);
const Table* table = module_->tables[0];
assert(decl.has_func_type);
Index func_type_index = module_->GetFuncTypeIndex(decl.type_var);
Write("CALL_INDIRECT(", ExternalRef(table->name), ", ");
WriteFuncDeclaration(decl, "(*)");
Write(", ", func_type_index, ", ", StackVar(0));
for (Index i = 0; i < num_params; ++i) {
Write(", ", StackVar(num_params - i));
}
Write(");", Newline());
DropTypes(num_params + 1);
PushTypes(decl.sig.result_types);
break;
}
case ExprType::Compare:
Write(*cast<CompareExpr>(&expr));
break;
case ExprType::Const: {
const Const& const_ = cast<ConstExpr>(&expr)->const_;
PushType(const_.type);
Write(StackVar(0), " = ", const_, ";", Newline());
break;
}
case ExprType::Convert:
Write(*cast<ConvertExpr>(&expr));
break;
case ExprType::Drop:
DropTypes(1);
break;
case ExprType::GetGlobal: {
const Var& var = cast<GetGlobalExpr>(&expr)->var;
PushType(module_->GetGlobal(var)->type);
Write(StackVar(0), " = ", GlobalVar(var), ";", Newline());
break;
}
case ExprType::GetLocal: {
const Var& var = cast<GetLocalExpr>(&expr)->var;
PushType(func_->GetLocalType(var));
Write(StackVar(0), " = ", var, ";", Newline());
break;
}
case ExprType::If: {
const IfExpr& if_ = *cast<IfExpr>(&expr);
Write("if (", StackVar(0), ") ", OpenBrace());
DropTypes(1);
std::string label = DefineLocalScopeName(if_.true_.label);
size_t mark = MarkTypeStack();
PushLabel(LabelType::If, if_.true_.label, if_.true_.sig);
Write(if_.true_.exprs, CloseBrace());
if (!if_.false_.empty()) {
ResetTypeStack(mark);
Write(" else ", OpenBrace(), if_.false_, CloseBrace());
}
ResetTypeStack(mark);
Write(Newline(), LabelDecl(label));
PopLabel();
PushTypes(if_.true_.sig);
break;
}
case ExprType::Load:
Write(*cast<LoadExpr>(&expr));
break;
case ExprType::Loop: {
const Block& block = cast<LoopExpr>(&expr)->block;
if (!block.exprs.empty()) {
Write(DefineLocalScopeName(block.label), ": ");
Indent();
size_t mark = MarkTypeStack();
PushLabel(LabelType::Loop, block.label, block.sig);
Write(Newline(), block.exprs);
ResetTypeStack(mark);
PopLabel();
PushTypes(block.sig);
Dedent();
}
break;
}
case ExprType::MemoryGrow: {
assert(module_->memories.size() == 1);
Memory* memory = module_->memories[0];
Write(StackVar(0), " = wasm_rt_grow_memory(", ExternalPtr(memory->name),
", ", StackVar(0), ");", Newline());
break;
}
case ExprType::MemorySize: {
assert(module_->memories.size() == 1);
Memory* memory = module_->memories[0];
PushType(Type::I32);
Write(StackVar(0), " = ", ExternalRef(memory->name), ".pages;",
Newline());
break;
}
case ExprType::Nop:
break;
case ExprType::Return:
// Goto the function label instead; this way we can do shared function
// cleanup code in one place.
Write(GotoLabel(Var(label_stack_.size() - 1)), Newline());
// Stop processing this ExprList, since the following are unreachable.
return;
case ExprType::Select: {
Type type = StackType(1);
Write(StackVar(2), " = ", StackVar(0), " ? ", StackVar(2), " : ",
StackVar(1), ";", Newline());
DropTypes(3);
PushType(type);
break;
}
case ExprType::SetGlobal: {
const Var& var = cast<SetGlobalExpr>(&expr)->var;
Write(GlobalVar(var), " = ", StackVar(0), ";", Newline());
DropTypes(1);
break;
}
case ExprType::SetLocal: {
const Var& var = cast<SetLocalExpr>(&expr)->var;
Write(var, " = ", StackVar(0), ";", Newline());
DropTypes(1);
break;
}
case ExprType::Store:
Write(*cast<StoreExpr>(&expr));
break;
case ExprType::TeeLocal: {
const Var& var = cast<TeeLocalExpr>(&expr)->var;
Write(var, " = ", StackVar(0), ";", Newline());
break;
}
case ExprType::Unary:
Write(*cast<UnaryExpr>(&expr));
break;
case ExprType::Ternary:
Write(*cast<TernaryExpr>(&expr));
break;
case ExprType::SimdLaneOp: {
Write(*cast<SimdLaneOpExpr>(&expr));
break;
}
case ExprType::SimdShuffleOp: {
Write(*cast<SimdShuffleOpExpr>(&expr));
break;
}
case ExprType::Unreachable:
Write("UNREACHABLE;", Newline());
return;
case ExprType::AtomicWait:
case ExprType::AtomicWake:
case ExprType::AtomicLoad:
case ExprType::AtomicRmw:
case ExprType::AtomicRmwCmpxchg:
case ExprType::AtomicStore:
case ExprType::IfExcept:
case ExprType::Rethrow:
case ExprType::Throw:
case ExprType::Try:
UNIMPLEMENTED("...");
break;
}
}
}
void CWriter::WriteSimpleUnaryExpr(Opcode opcode, const char* op) {
Type result_type = opcode.GetResultType();
Write(StackVar(0, result_type), " = ", op, "(", StackVar(0), ");", Newline());
DropTypes(1);
PushType(opcode.GetResultType());
}
void CWriter::WriteInfixBinaryExpr(Opcode opcode,
const char* op,
AssignOp assign_op) {
Type result_type = opcode.GetResultType();
Write(StackVar(1, result_type));
if (assign_op == AssignOp::Allowed) {
Write(" ", op, "= ", StackVar(0));
} else {
Write(" = ", StackVar(1), " ", op, " ", StackVar(0));
}
Write(";", Newline());
DropTypes(2);
PushType(result_type);
}
void CWriter::WritePrefixBinaryExpr(Opcode opcode, const char* op) {
Type result_type = opcode.GetResultType();
Write(StackVar(1, result_type), " = ", op, "(", StackVar(1), ", ",
StackVar(0), ");", Newline());
DropTypes(2);
PushType(result_type);
}
void CWriter::WriteSignedBinaryExpr(Opcode opcode, const char* op) {
Type result_type = opcode.GetResultType();
Type type = opcode.GetParamType1();
assert(opcode.GetParamType2() == type);
Write(StackVar(1, result_type), " = (", type, ")((", SignedType(type), ")",
StackVar(1), " ", op, " (", SignedType(type), ")", StackVar(0), ");",
Newline());
DropTypes(2);
PushType(result_type);
}
void CWriter::Write(const BinaryExpr& expr) {
switch (expr.opcode) {
case Opcode::I32Add:
case Opcode::I64Add:
case Opcode::F32Add:
case Opcode::F64Add:
WriteInfixBinaryExpr(expr.opcode, "+");
break;
case Opcode::I32Sub:
case Opcode::I64Sub:
case Opcode::F32Sub:
case Opcode::F64Sub:
WriteInfixBinaryExpr(expr.opcode, "-");
break;
case Opcode::I32Mul:
case Opcode::I64Mul:
case Opcode::F32Mul:
case Opcode::F64Mul:
WriteInfixBinaryExpr(expr.opcode, "*");
break;
case Opcode::I32DivS:
WritePrefixBinaryExpr(expr.opcode, "I32_DIV_S");
break;
case Opcode::I64DivS:
WritePrefixBinaryExpr(expr.opcode, "I64_DIV_S");
break;
case Opcode::I32DivU:
case Opcode::I64DivU:
WritePrefixBinaryExpr(expr.opcode, "DIV_U");
break;
case Opcode::F32Div:
case Opcode::F64Div:
WriteInfixBinaryExpr(expr.opcode, "/");
break;
case Opcode::I32RemS:
WritePrefixBinaryExpr(expr.opcode, "I32_REM_S");
break;
case Opcode::I64RemS:
WritePrefixBinaryExpr(expr.opcode, "I64_REM_S");
break;
case Opcode::I32RemU:
case Opcode::I64RemU:
WritePrefixBinaryExpr(expr.opcode, "REM_U");
break;
case Opcode::I32And:
case Opcode::I64And:
WriteInfixBinaryExpr(expr.opcode, "&");
break;
case Opcode::I32Or:
case Opcode::I64Or:
WriteInfixBinaryExpr(expr.opcode, "|");
break;
case Opcode::I32Xor:
case Opcode::I64Xor:
WriteInfixBinaryExpr(expr.opcode, "^");
break;
case Opcode::I32Shl:
case Opcode::I64Shl:
Write(StackVar(1), " <<= (", StackVar(0), " & ",
GetShiftMask(expr.opcode.GetResultType()), ");", Newline());
DropTypes(1);
break;
case Opcode::I32ShrS:
case Opcode::I64ShrS: {
Type type = expr.opcode.GetResultType();
Write(StackVar(1), " = (", type, ")((", SignedType(type), ")",
StackVar(1), " >> (", StackVar(0), " & ", GetShiftMask(type), "));",
Newline());
DropTypes(1);
break;
}
case Opcode::I32ShrU:
case Opcode::I64ShrU:
Write(StackVar(1), " >>= (", StackVar(0), " & ",
GetShiftMask(expr.opcode.GetResultType()), ");", Newline());
DropTypes(1);
break;
case Opcode::I32Rotl:
WritePrefixBinaryExpr(expr.opcode, "I32_ROTL");
break;
case Opcode::I64Rotl:
WritePrefixBinaryExpr(expr.opcode, "I64_ROTL");
break;
case Opcode::I32Rotr:
WritePrefixBinaryExpr(expr.opcode, "I32_ROTR");
break;
case Opcode::I64Rotr:
WritePrefixBinaryExpr(expr.opcode, "I64_ROTR");
break;
case Opcode::F32Min:
case Opcode::F64Min:
WritePrefixBinaryExpr(expr.opcode, "FMIN");
break;
case Opcode::F32Max:
case Opcode::F64Max:
WritePrefixBinaryExpr(expr.opcode, "FMAX");
break;
case Opcode::F32Copysign:
WritePrefixBinaryExpr(expr.opcode, "copysignf");
break;
case Opcode::F64Copysign:
WritePrefixBinaryExpr(expr.opcode, "copysign");
break;
default:
WABT_UNREACHABLE;
}
}
void CWriter::Write(const CompareExpr& expr) {
switch (expr.opcode) {
case Opcode::I32Eq:
case Opcode::I64Eq:
case Opcode::F32Eq:
case Opcode::F64Eq:
WriteInfixBinaryExpr(expr.opcode, "==", AssignOp::Disallowed);
break;
case Opcode::I32Ne:
case Opcode::I64Ne:
case Opcode::F32Ne:
case Opcode::F64Ne:
WriteInfixBinaryExpr(expr.opcode, "!=", AssignOp::Disallowed);
break;
case Opcode::I32LtS:
case Opcode::I64LtS:
WriteSignedBinaryExpr(expr.opcode, "<");
break;
case Opcode::I32LtU:
case Opcode::I64LtU:
case Opcode::F32Lt:
case Opcode::F64Lt:
WriteInfixBinaryExpr(expr.opcode, "<", AssignOp::Disallowed);
break;
case Opcode::I32LeS:
case Opcode::I64LeS:
WriteSignedBinaryExpr(expr.opcode, "<=");
break;
case Opcode::I32LeU:
case Opcode::I64LeU:
case Opcode::F32Le:
case Opcode::F64Le:
WriteInfixBinaryExpr(expr.opcode, "<=", AssignOp::Disallowed);
break;
case Opcode::I32GtS:
case Opcode::I64GtS:
WriteSignedBinaryExpr(expr.opcode, ">");
break;
case Opcode::I32GtU:
case Opcode::I64GtU:
case Opcode::F32Gt:
case Opcode::F64Gt:
WriteInfixBinaryExpr(expr.opcode, ">", AssignOp::Disallowed);
break;
case Opcode::I32GeS:
case Opcode::I64GeS:
WriteSignedBinaryExpr(expr.opcode, ">=");
break;
case Opcode::I32GeU:
case Opcode::I64GeU:
case Opcode::F32Ge:
case Opcode::F64Ge:
WriteInfixBinaryExpr(expr.opcode, ">=", AssignOp::Disallowed);
break;
default:
WABT_UNREACHABLE;
}
}
void CWriter::Write(const ConvertExpr& expr) {
switch (expr.opcode) {
case Opcode::I32Eqz:
case Opcode::I64Eqz:
WriteSimpleUnaryExpr(expr.opcode, "!");
break;
case Opcode::I64ExtendSI32:
WriteSimpleUnaryExpr(expr.opcode, "(u64)(s64)(s32)");
break;
case Opcode::I64ExtendUI32:
WriteSimpleUnaryExpr(expr.opcode, "(u64)");
break;
case Opcode::I32WrapI64:
WriteSimpleUnaryExpr(expr.opcode, "(u32)");
break;
case Opcode::I32TruncSF32:
WriteSimpleUnaryExpr(expr.opcode, "I32_TRUNC_S_F32");
break;
case Opcode::I64TruncSF32:
WriteSimpleUnaryExpr(expr.opcode, "I64_TRUNC_S_F32");
break;
case Opcode::I32TruncSF64:
WriteSimpleUnaryExpr(expr.opcode, "I32_TRUNC_S_F64");
break;
case Opcode::I64TruncSF64:
WriteSimpleUnaryExpr(expr.opcode, "I64_TRUNC_S_F64");
break;
case Opcode::I32TruncUF32:
WriteSimpleUnaryExpr(expr.opcode, "I32_TRUNC_U_F32");
break;
case Opcode::I64TruncUF32:
WriteSimpleUnaryExpr(expr.opcode, "I64_TRUNC_U_F32");
break;
case Opcode::I32TruncUF64:
WriteSimpleUnaryExpr(expr.opcode, "I32_TRUNC_U_F64");
break;
case Opcode::I64TruncUF64:
WriteSimpleUnaryExpr(expr.opcode, "I64_TRUNC_U_F64");
break;
case Opcode::I32TruncSSatF32:
case Opcode::I64TruncSSatF32:
case Opcode::I32TruncSSatF64:
case Opcode::I64TruncSSatF64:
case Opcode::I32TruncUSatF32:
case Opcode::I64TruncUSatF32:
case Opcode::I32TruncUSatF64:
case Opcode::I64TruncUSatF64:
UNIMPLEMENTED(expr.opcode.GetName());
break;
case Opcode::F32ConvertSI32:
WriteSimpleUnaryExpr(expr.opcode, "(f32)(s32)");
break;
case Opcode::F32ConvertSI64:
WriteSimpleUnaryExpr(expr.opcode, "(f32)(s64)");
break;
case Opcode::F32ConvertUI32:
case Opcode::F32DemoteF64:
WriteSimpleUnaryExpr(expr.opcode, "(f32)");
break;
case Opcode::F32ConvertUI64:
// TODO(binji): This needs to be handled specially (see
// wabt_convert_uint64_to_float).
WriteSimpleUnaryExpr(expr.opcode, "(f32)");
break;
case Opcode::F64ConvertSI32:
WriteSimpleUnaryExpr(expr.opcode, "(f64)(s32)");
break;
case Opcode::F64ConvertSI64:
WriteSimpleUnaryExpr(expr.opcode, "(f64)(s64)");
break;
case Opcode::F64ConvertUI32:
case Opcode::F64PromoteF32:
WriteSimpleUnaryExpr(expr.opcode, "(f64)");
break;
case Opcode::F64ConvertUI64:
// TODO(binji): This needs to be handled specially (see
// wabt_convert_uint64_to_double).
WriteSimpleUnaryExpr(expr.opcode, "(f64)");
break;
case Opcode::F32ReinterpretI32:
WriteSimpleUnaryExpr(expr.opcode, "f32_reinterpret_i32");
break;
case Opcode::I32ReinterpretF32:
WriteSimpleUnaryExpr(expr.opcode, "i32_reinterpret_f32");
break;
case Opcode::F64ReinterpretI64:
WriteSimpleUnaryExpr(expr.opcode, "f64_reinterpret_i64");
break;
case Opcode::I64ReinterpretF64:
WriteSimpleUnaryExpr(expr.opcode, "i64_reinterpret_f64");
break;
default:
WABT_UNREACHABLE;
}
}
void CWriter::Write(const LoadExpr& expr) {
const char* func = nullptr;
switch (expr.opcode) {
case Opcode::I32Load: func = "i32_load"; break;
case Opcode::I64Load: func = "i64_load"; break;
case Opcode::F32Load: func = "f32_load"; break;
case Opcode::F64Load: func = "f64_load"; break;
case Opcode::I32Load8S: func = "i32_load8_s"; break;
case Opcode::I64Load8S: func = "i64_load8_s"; break;
case Opcode::I32Load8U: func = "i32_load8_u"; break;
case Opcode::I64Load8U: func = "i64_load8_u"; break;
case Opcode::I32Load16S: func = "i32_load16_s"; break;
case Opcode::I64Load16S: func = "i64_load16_s"; break;
case Opcode::I32Load16U: func = "i32_load16_u"; break;
case Opcode::I64Load16U: func = "i32_load16_u"; break;
case Opcode::I64Load32S: func = "i64_load32_s"; break;
case Opcode::I64Load32U: func = "i64_load32_u"; break;
default:
WABT_UNREACHABLE;
}
assert(module_->memories.size() == 1);
Memory* memory = module_->memories[0];
Type result_type = expr.opcode.GetResultType();
Write(StackVar(0, result_type), " = ", func, "(", ExternalPtr(memory->name),
", (u64)(", StackVar(0));
if (expr.offset != 0)
Write(" + ", expr.offset);
Write("));", Newline());
DropTypes(1);
PushType(result_type);
}
void CWriter::Write(const StoreExpr& expr) {
const char* func = nullptr;
switch (expr.opcode) {
case Opcode::I32Store: func = "i32_store"; break;
case Opcode::I64Store: func = "i64_store"; break;
case Opcode::F32Store: func = "f32_store"; break;
case Opcode::F64Store: func = "f64_store"; break;
case Opcode::I32Store8: func = "i32_store8"; break;
case Opcode::I64Store8: func = "i64_store8"; break;
case Opcode::I32Store16: func = "i32_store16"; break;
case Opcode::I64Store16: func = "i64_store16"; break;
case Opcode::I64Store32: func = "i64_store32"; break;
default:
WABT_UNREACHABLE;
}
assert(module_->memories.size() == 1);
Memory* memory = module_->memories[0];
Write(func, "(", ExternalPtr(memory->name), ", (u64)(", StackVar(1));
if (expr.offset != 0)
Write(" + ", expr.offset);
Write("), ", StackVar(0), ");", Newline());
DropTypes(2);
}
void CWriter::Write(const UnaryExpr& expr) {
switch (expr.opcode) {
case Opcode::I32Clz:
WriteSimpleUnaryExpr(expr.opcode, "I32_CLZ");
break;
case Opcode::I64Clz:
WriteSimpleUnaryExpr(expr.opcode, "I64_CLZ");
break;
case Opcode::I32Ctz:
WriteSimpleUnaryExpr(expr.opcode, "I32_CTZ");
break;
case Opcode::I64Ctz:
WriteSimpleUnaryExpr(expr.opcode, "I64_CTZ");
break;
case Opcode::I32Popcnt:
WriteSimpleUnaryExpr(expr.opcode, "I32_POPCNT");
break;
case Opcode::I64Popcnt:
WriteSimpleUnaryExpr(expr.opcode, "I64_POPCNT");
break;
case Opcode::F32Neg:
case Opcode::F64Neg:
WriteSimpleUnaryExpr(expr.opcode, "-");
break;
case Opcode::F32Abs:
WriteSimpleUnaryExpr(expr.opcode, "fabsf");
break;
case Opcode::F64Abs:
WriteSimpleUnaryExpr(expr.opcode, "fabs");
break;
case Opcode::F32Sqrt:
WriteSimpleUnaryExpr(expr.opcode, "sqrtf");
break;
case Opcode::F64Sqrt:
WriteSimpleUnaryExpr(expr.opcode, "sqrt");
break;
case Opcode::F32Ceil:
WriteSimpleUnaryExpr(expr.opcode, "ceilf");
break;
case Opcode::F64Ceil:
WriteSimpleUnaryExpr(expr.opcode, "ceil");
break;
case Opcode::F32Floor:
WriteSimpleUnaryExpr(expr.opcode, "floorf");
break;
case Opcode::F64Floor:
WriteSimpleUnaryExpr(expr.opcode, "floor");
break;
case Opcode::F32Trunc:
WriteSimpleUnaryExpr(expr.opcode, "truncf");
break;
case Opcode::F64Trunc:
WriteSimpleUnaryExpr(expr.opcode, "trunc");
break;
case Opcode::F32Nearest:
WriteSimpleUnaryExpr(expr.opcode, "nearbyintf");
break;
case Opcode::F64Nearest:
WriteSimpleUnaryExpr(expr.opcode, "nearbyint");
break;
case Opcode::I32Extend8S:
case Opcode::I32Extend16S:
case Opcode::I64Extend8S:
case Opcode::I64Extend16S:
case Opcode::I64Extend32S:
UNIMPLEMENTED(expr.opcode.GetName());
break;
default:
WABT_UNREACHABLE;
}
}
void CWriter::Write(const TernaryExpr& expr) {
switch (expr.opcode) {
case Opcode::V128BitSelect: {
Type result_type = expr.opcode.GetResultType();
Write(StackVar(2, result_type), " = ", "v128.bitselect", "(", StackVar(0),
", ", StackVar(1), ", ", StackVar(2), ");", Newline());
DropTypes(3);
PushType(result_type);
break;
}
default:
WABT_UNREACHABLE;
}
}
void CWriter::Write(const SimdLaneOpExpr& expr) {
Type result_type = expr.opcode.GetResultType();
switch (expr.opcode) {
case Opcode::I8X16ExtractLaneS:
case Opcode::I8X16ExtractLaneU:
case Opcode::I16X8ExtractLaneS:
case Opcode::I16X8ExtractLaneU:
case Opcode::I32X4ExtractLane:
case Opcode::I64X2ExtractLane:
case Opcode::F32X4ExtractLane:
case Opcode::F64X2ExtractLane: {
Write(StackVar(0, result_type), " = ", expr.opcode.GetName(), "(",
StackVar(0), ", lane Imm: ", expr.val, ");", Newline());
DropTypes(1);
break;
}
case Opcode::I8X16ReplaceLane:
case Opcode::I16X8ReplaceLane:
case Opcode::I32X4ReplaceLane:
case Opcode::I64X2ReplaceLane:
case Opcode::F32X4ReplaceLane:
case Opcode::F64X2ReplaceLane: {
Write(StackVar(1, result_type), " = ", expr.opcode.GetName(), "(",
StackVar(0), ", ", StackVar(1), ", lane Imm: ", expr.val, ");",
Newline());
DropTypes(2);
break;
}
default:
WABT_UNREACHABLE;
}
PushType(result_type);
}
void CWriter::Write(const SimdShuffleOpExpr& expr) {
Type result_type = expr.opcode.GetResultType();
Write(StackVar(1, result_type), " = ", expr.opcode.GetName(), "(",
StackVar(1), " ", StackVar(0), ", lane Imm: $0x%08x %08x %08x %08x",
expr.val.v[0], expr.val.v[1], expr.val.v[2], expr.val.v[3], ")",
Newline());
DropTypes(2);
PushType(result_type);
}
void CWriter::WriteCHeader() {
stream_ = h_stream_;
std::string guard = GenerateHeaderGuard();
Write("#ifndef ", guard, Newline());
Write("#define ", guard, Newline());
Write(s_header_top);
WriteImports();
WriteExports(WriteExportsKind::Declarations);
Write(s_header_bottom);
Write(Newline(), "#endif /* ", guard, " */", Newline());
}
void CWriter::WriteCSource() {
stream_ = c_stream_;
WriteSourceTop();
WriteFuncTypes();
WriteFuncDeclarations();
WriteGlobals();
WriteMemories();
WriteTables();
WriteFuncs();
WriteDataInitializers();
WriteElemInitializers();
WriteExports(WriteExportsKind::Definitions);
WriteInitExports();
WriteInit();
}
Result CWriter::WriteModule(const Module& module) {
WABT_USE(options_);
module_ = &module;
InitGlobalSymbols();
WriteCHeader();
WriteCSource();
return result_;
}
} // end anonymous namespace
Result WriteC(Stream* c_stream,
Stream* h_stream,
const char* header_name,
const Module* module,
const WriteCOptions* options) {
CWriter c_writer(c_stream, h_stream, header_name, options);
return c_writer.WriteModule(*module);
}
} // namespace wabt
| [
"bob@mssun.me"
] | bob@mssun.me |
c2d66702a09a7927e16ee5db07aa4177aff2bf98 | d42df8e2b2c67f841f02ef32b4ebee5602d6ac73 | /Study01/Study01/CtrlButtonST.h | f2ee3502fd8def5aaf3c942e81ebb964529b2aa7 | [] | no_license | cnamQ/GrimStudy_1 | a798f2270812203ffc499182c60352af26394546 | a8723166d8db3ed66f5c15fb46730814003b30ca | refs/heads/main | 2023-08-05T03:54:49.384037 | 2021-09-27T22:56:43 | 2021-09-27T22:56:43 | 408,046,010 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,611 | h | //
// Class: CCtrlButtonST
//
// Compiler: Visual C++
// Tested on: Visual C++ 5.0
// Visual C++ 6.0
//
// Version: See GetVersionC() or GetVersionI()
//
// Created: xx/xxxx/1998
// Updated: 14/June/2001
//
// Author: Davide Calabro' davide_calabro@yahoo.com
//
#ifndef _BTNST_H
#define _BTNST_H
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// CBtnST.h : header file
//
// Comment this if you don't want that CCtrlButtonST hilights itself
// also when the window is inactive (like happens in Internet Explorer)
//#define ST_LIKEIE
// Return values
#ifndef BTNST_OK
#define BTNST_OK 0
#endif
#ifndef BTNST_INVALIDRESOURCE
#define BTNST_INVALIDRESOURCE 1
#endif
#ifndef BTNST_FAILEDMASK
#define BTNST_FAILEDMASK 2
#endif
#ifndef BTNST_INVALIDINDEX
#define BTNST_INVALIDINDEX 3
#endif
class CCtrlButtonST : public CButton
{
public:
CCtrlButtonST();
~CCtrlButtonST();
enum {ST_ALIGN_HORIZ, ST_ALIGN_VERT, ST_ALIGN_HORIZ_RIGHT};
enum { BTNST_COLOR_BK_IN = 0, // Background color when mouse is INside
BTNST_COLOR_FG_IN, // Text color when mouse is INside
BTNST_COLOR_BK_OUT, // Background color when mouse is OUTside
BTNST_COLOR_FG_OUT, // Text color when mouse is OUTside
BTNST_MAX_COLORS
};
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CCtrlButtonST)
public:
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
virtual BOOL PreTranslateMessage(MSG* pMsg);
protected:
virtual void PreSubclassWindow();
virtual LRESULT DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam);
//}}AFX_VIRTUAL
public:
DWORD SetAutoRepeat(BOOL bSet, DWORD dwMilliseconds = 100);
DWORD SetURL(LPCTSTR lpszURL);
DWORD GetColor(BYTE byColorIndex, COLORREF* crpColor);
DWORD SetColor(BYTE byColorIndex, COLORREF crColor, BOOL bRepaint = TRUE);
DWORD SetDefaultColors(BOOL bRepaint = TRUE);
int GetCheck();
void SetCheck(int nCheck, BOOL bRepaint = TRUE);
void DrawTransparent(BOOL bRepaint = FALSE);
BOOL GetDefault();
void SetTooltipText(int nId, BOOL bActivate = TRUE);
void SetTooltipText(LPCTSTR lpszText, BOOL bActivate = TRUE);
void ActivateTooltip(BOOL bEnable = TRUE);
BOOL SetBtnCursor(int nCursorId = NULL);
void SetFlatFocus(BOOL bDrawFlatFocus, BOOL bRepaint = FALSE);
void SetAlign(int nAlign);
int GetAlign();
void SetFlat(BOOL bState = TRUE);
BOOL GetFlat();
void DrawBorder(BOOL bEnable = TRUE);
DWORD SetIcon(int nIconInId, int nIconOutId = NULL);
DWORD SetIcon(HICON hIconIn, HICON hIconOut = NULL);
DWORD SetBitmaps(int nBitmapIn, COLORREF crTransColorIn, int nBitmapOut = NULL, COLORREF crTransColorOut = 0);
DWORD SetBitmaps(HBITMAP hBitmapIn, COLORREF crTransColorIn, HBITMAP hBitmapOut = NULL, COLORREF crTransColorOut = 0);
static short GetVersionI() {return 32;}
static LPCTSTR GetVersionC() {return (LPCTSTR)_T("3.2");}
protected:
//{{AFX_MSG(CCtrlButtonST)
afx_msg void OnCaptureChanged(CWnd *pWnd);
afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
afx_msg void OnKillFocus(CWnd* pNewWnd);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnSysColorChange();
afx_msg BOOL OnClicked();
afx_msg void OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized);
afx_msg void OnEnable(BOOL bEnable);
afx_msg void OnCancelMode();
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
//}}AFX_MSG
afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor);
virtual DWORD OnDrawBackground(CDC* pDC, LPCRECT pRect);
virtual DWORD OnDrawBorder(CDC* pDC, LPCRECT pRect);
BOOL m_bDrawTransparent;
BOOL m_bMouseOnButton;
BOOL m_bIsPressed;
BOOL m_bIsFocused;
BOOL m_bIsDisabled;
COLORREF m_crColors[BTNST_MAX_COLORS];
public:
bool IsPressed() { return m_bIsPressed; }
private:
void CancelHover();
void PrepareImageRect(BOOL bHasTitle, RECT* rpItem, CRect* rpTitle, BOOL bIsPressed, DWORD dwWidth, DWORD dwHeight, CRect* rpImage);
HBITMAP CreateBitmapMask(HBITMAP hSourceBitmap, DWORD dwWidth, DWORD dwHeight, COLORREF crTransColor);
void DrawTheBitmap(CDC* pDC, BOOL bHasTitle, RECT *rItem, CRect *rCaption, BOOL bIsPressed, BOOL bIsDisabled);
void FreeResources(BOOL bCheckForNULL = TRUE);
void DrawTheIcon(CDC* pDC, BOOL bHasTitle, RECT* rpItem, CRect* rpTitle, BOOL bIsPressed, BOOL bIsDisabled);
void InitToolTip();
void PaintBk(CDC* pDC);
int m_nAlign;
BOOL m_bDrawBorder;
BOOL m_bIsFlat;
BOOL m_bDrawFlatFocus;
BOOL m_bAutoRepeat;
HWND m_hWndAutoRepeat;
UINT m_nMsgAutoRepeat;
DWORD m_dwPeriodAutoRepeat;
HCURSOR m_hCursor;
CToolTipCtrl m_ToolTip;
#pragma pack(1)
typedef struct _STRUCT_ICONS
{
HICON hIcon; // Handle to icon
DWORD dwWidth; // Width of icon
DWORD dwHeight; // Height of icon
} STRUCT_ICONS;
#pragma pack()
#pragma pack(1)
typedef struct _STRUCT_BITMAPS
{
HBITMAP hBitmap; // Handle to bitmap
DWORD dwWidth; // Width of bitmap
DWORD dwHeight; // Height of bitmap
HBITMAP hMask; // Handle to mask bitmap
COLORREF crTransparent; // Transparent color
} STRUCT_BITMAPS;
#pragma pack()
STRUCT_ICONS m_csIcons[2];
STRUCT_BITMAPS m_csBitmaps[2];
CDC m_dcBk;
CBitmap m_bmpBk;
CBitmap* m_pbmpOldBk;
BOOL m_bIsDefault;
BOOL m_bIsCheckBox;
int m_nCheck;
TCHAR m_szURL[_MAX_PATH];
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedButtonResearchCurvedGlassInspectOptionOutlineBase();
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif
| [
"ccn0324@gmail.com"
] | ccn0324@gmail.com |
62e8d0faedd28f52f3a547f138c156ad5421cad4 | e92edf2c40b256e2e7fd29908264a19e65f80289 | /tests/Qt_free_lambda.cpp | 83e2c6e59ef3c874a80882f31d3b20302c83fd91 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LicenseRef-scancode-bsd-unmodified",
"ISC",
"BSD-2-Clause"
] | permissive | bmanGH/xdispatch | 7c84336722616813a0a81c5100765ed39615e1b8 | 06d31d4bd299952078f0bc067e207b1b8af411b3 | refs/heads/master | 2021-01-22T07:27:46.998071 | 2013-11-21T15:33:54 | 2013-11-21T15:33:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,239 | cpp | /*
* Qt_free_lambda.cpp
*
* Copyright (c) 2008-2009 Apple Inc.
* Copyright (c) 2011-2013 MLBA-Team.
* All rights reserved.
*
* @LICENSE_HEADER_START@
* 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.
* @LICENSE_HEADER_END@
*/
#include <QtDispatch/QtDispatch>
#include "Qt_tests.h"
static bool was_freed = false;
struct QtBeFreed2 {
QtBeFreed2() : ref_ct(new uintptr_t) {
*ref_ct = 1;
}
QtBeFreed2(const QtBeFreed2& other) : ref_ct(other.ref_ct){
dispatch_atomic_inc(ref_ct);
}
~QtBeFreed2(){
if(dispatch_atomic_dec(ref_ct) == 0) {
delete ref_ct;
was_freed = true;
}
}
void someFunction() const { /* Do nothing (tm) */ }
uintptr_t* ref_ct;
};
struct QtBeFreed {
QtBeFreed() : ref_ct(new uintptr_t) {
*ref_ct = 1;
}
QtBeFreed(const QtBeFreed& other) : ref_ct(other.ref_ct){
dispatch_atomic_inc(ref_ct);
}
~QtBeFreed(){
if(dispatch_atomic_dec(ref_ct) == 0) {
delete ref_ct;
MU_ASSERT_TRUE(was_freed);
MU_PASS("");
}
}
void someFunction() const { /* Do nothing (tm) */ }
uintptr_t* ref_ct;
};
static void Qt_dispatch_outer(){
QtBeFreed outer;
QtBeFreed2 inner;
QDispatch::globalQueue().apply( 10, QDispatchMakeIterationRunnable([=](size_t i){
inner.someFunction();
}));
QDispatch::mainQueue().async(QDispatchMakeRunnable([=]{
outer.someFunction();
}));
}
extern "C" void Qt_free_lambda(){
MU_BEGIN_TEST(Qt_free_lambda);
char* argv = QString("test").toAscii().data();
int argc = 1;
QDispatchApplication app(argc,&argv);
Qt_dispatch_outer();
app.exec();
MU_END_TEST;
}
| [
"marius@9e4c620c-c391-4b63-a7fb-4924991ea895"
] | marius@9e4c620c-c391-4b63-a7fb-4924991ea895 |
c6c9bef03895d5db0e1f32a2f61c09af8605dda4 | f4965b0f73f2ce332885a7a53fbd3ef92ed81c47 | /Pool Game v3.0/Pool Game.cpp | f567c8e6d65e807230f72ea33e39bb038a46f6b2 | [] | no_license | mengchenshang/mengchenshang | 4fd65ef70f2d65a39dae6812d282289741498e4c | 14fec42cfee843d1abbf6bfc52398d01a11f9723 | refs/heads/master | 2021-06-03T05:38:32.647334 | 2018-11-07T02:44:52 | 2018-11-07T02:44:52 | 28,816,743 | 0 | 0 | null | 2018-11-07T02:42:45 | 2015-01-05T14:51:36 | HTML | UTF-8 | C++ | false | false | 9,676 | cpp | // Pool Game.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "simulation.h"
#include<glut.h>
#include<math.h>
//cue variables
float gCueAngle = 0.0;
float gCuePower = 0.25;
bool gCueControl[4] = {false,false,false,false};
float gCueAngleSpeed = 2.0f; //radians per second
float gCuePowerSpeed = 0.25f;
float gCuePowerMax = 0.75;
float gCuePowerMin = 0.1;
float gCueBallFactor = 8.0;
bool gDoCue = true;
//camera variables
vec3 gCamPos(0.0,0.7,2.1);
vec3 gCamLookAt(0.0,0.0,0.0);
bool gCamRotate = true;
float gCamRotSpeed = 0.2;
float gCamMoveSpeed = 0.5;
bool gCamL = false;
bool gCamR = false;
bool gCamU = false;
bool gCamD = false;
bool gCamZin = false;
bool gCamZout = false;
//rendering options
#define DRAW_SOLID (0)
void DoCamera(int ms)
{
static const vec3 up(0.0,1.0,0.0);
if(gCamRotate)
{
if(gCamL)
{
vec3 camDir = (gCamLookAt - gCamPos).Normalised();
vec3 localL = up.Cross(camDir);
vec3 inc = (localL* ((gCamRotSpeed*ms)/1000.0) );
gCamLookAt = gCamPos + camDir + inc;
}
if(gCamR)
{
vec3 camDir = (gCamLookAt - gCamPos).Normalised();
vec3 localR = up.Cross(camDir);
vec3 inc = (localR* ((gCamRotSpeed*ms)/1000.0) );
gCamLookAt = gCamPos + camDir - inc;
}
if(gCamU)
{
vec3 camDir = (gCamLookAt - gCamPos).Normalised();
vec3 localR = camDir.Cross(up);
vec3 localUp = localR.Cross(camDir);
vec3 inc = (localUp* ((gCamMoveSpeed*ms)/1000.0) );
gCamLookAt = gCamPos + camDir + inc;
}
if(gCamD)
{
vec3 camDir = (gCamLookAt - gCamPos).Normalised();
vec3 localR = camDir.Cross(up);
vec3 localUp = localR.Cross(camDir);
vec3 inc = (localUp* ((gCamMoveSpeed*ms)/1000.0) );
gCamLookAt = gCamPos + camDir - inc;
}
}
else
{
if(gCamL)
{
vec3 camDir = (gCamLookAt - gCamPos).Normalised();
vec3 localL = up.Cross(camDir);
vec3 inc = (localL* ((gCamMoveSpeed*ms)/1000.0) );
gCamPos += inc;
gCamLookAt += inc;
}
if(gCamR)
{
vec3 camDir = (gCamLookAt - gCamPos).Normalised();
vec3 localR = camDir.Cross(up);
vec3 inc = (localR* ((gCamMoveSpeed*ms)/1000.0) );
gCamPos += inc;
gCamLookAt += inc;
}
if(gCamU)
{
vec3 camDir = (gCamLookAt - gCamPos).Normalised();
vec3 localR = camDir.Cross(up);
vec3 localUp = localR.Cross(camDir);
vec3 inc = (localUp* ((gCamMoveSpeed*ms)/1000.0) );
gCamPos += inc;
gCamLookAt += inc;
}
if(gCamD)
{
vec3 camDir = (gCamLookAt - gCamPos).Normalised();
vec3 localR = camDir.Cross(up);
vec3 localDown = camDir.Cross(localR);
vec3 inc = (localDown* ((gCamMoveSpeed*ms)/1000.0) );
gCamPos += inc;
gCamLookAt += inc;
}
}
if(gCamZin)
{
vec3 camDir = (gCamLookAt - gCamPos).Normalised();
vec3 inc = (camDir* ((gCamMoveSpeed*ms)/1000.0) );
gCamPos += inc;
gCamLookAt += inc;
}
if(gCamZout)
{
vec3 camDir = (gCamLookAt - gCamPos).Normalised();
vec3 inc = (camDir* ((gCamMoveSpeed*ms)/1000.0) );
gCamPos -= inc;
gCamLookAt -= inc;
}
}
void DrawCircle(vec2 v, double r, int num_segments)
{
glBegin(GL_LINE_LOOP);
for(int Q = 0; Q < num_segments; Q++)
{
float theta = 2.0f * PI * float(Q) / float(num_segments);//get the current angle
float x = 0.5*r * cosf(theta);//calculate the x component
float y = r * sinf(theta);//calculate the y component
glVertex3f(x + v.elem[0], 0.0, y + v.elem[1]);//output vertex
}
glEnd();
}
void RenderScene(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//set camera
glLoadIdentity();
gluLookAt(gCamPos(0),gCamPos(1),gCamPos(2),gCamLookAt(0),gCamLookAt(1),gCamLookAt(2),0.0f,1.0f,0.0f);
//draw the ball
glColor3f(1.0,1.0,1.0);
for(int i=0;i<NUM_BALLS;i++)
{
if(gTable.balls[i].dropped){
continue;
}
glPushMatrix();
glTranslatef(gTable.balls[i].position(0),(BALL_RADIUS/2.0),gTable.balls[i].position(1));
#if DRAW_SOLID
glutSolidSphere(gTable.balls[i].radius,32,32);
#else
glutWireSphere(gTable.balls[i].radius,12,12);
#endif
glPopMatrix();
glColor3f(0.0,0.0,1.0);
}
glColor3f(1.0,1.0,1.0);
//draw the table
glPushMatrix();
for(int i=0;i<NUM_CUSHION;i++){
glBegin(GL_LINE_LOOP);
vec2 cushion_start = gTable.cushions[i].start;
vec2 cushion_end = gTable.cushions[i].end;
glVertex3f(cushion_start.elem[0], 0.0, cushion_start.elem[1]);
glVertex3f(cushion_start.elem[0], 0.1, cushion_start.elem[1]);
glVertex3f(cushion_end.elem[0], 0.1, cushion_end.elem[1]);
glVertex3f(cushion_end.elem[0], 0.0, cushion_end.elem[1]);
glEnd();
}
//draw pockets
for(int i=0;i<NUM_POCKET;i++){
DrawCircle(gTable.pockets[i].GetCenter(), gTable.pockets[i].GetRadius(), 50);
}
//draw the cue
if(gDoCue)
{
glBegin(GL_LINES);
float cuex = sin(gCueAngle) * gCuePower;
float cuez = cos(gCueAngle) * gCuePower;
glColor3f(1.0,0.0,0.0);
glVertex3f (gTable.balls[0].position(0), (BALL_RADIUS/2.0f), gTable.balls[0].position(1));
glVertex3f ((gTable.balls[0].position(0)+cuex), (BALL_RADIUS/2.0f), (gTable.balls[0].position(1)+cuez));
glColor3f(1.0,1.0,1.0);
glEnd();
}
glPopMatrix();
glFlush();
glutSwapBuffers();
}
void SpecKeyboardFunc(int key, int x, int y)
{
switch(key)
{
case GLUT_KEY_LEFT:
{
gCueControl[0] = true;
break;
}
case GLUT_KEY_RIGHT:
{
gCueControl[1] = true;
break;
}
case GLUT_KEY_UP:
{
gCueControl[2] = true;
break;
}
case GLUT_KEY_DOWN:
{
gCueControl[3] = true;
break;
}
}
}
void SpecKeyboardUpFunc(int key, int x, int y)
{
switch(key)
{
case GLUT_KEY_LEFT:
{
gCueControl[0] = false;
break;
}
case GLUT_KEY_RIGHT:
{
gCueControl[1] = false;
break;
}
case GLUT_KEY_UP:
{
gCueControl[2] = false;
break;
}
case GLUT_KEY_DOWN:
{
gCueControl[3] = false;
break;
}
}
}
void KeyboardFunc(unsigned char key, int x, int y)
{
switch(key)
{
case(13):
{
if(gDoCue)
{
vec2 imp( (-sin(gCueAngle) * gCuePower * gCueBallFactor),
(-cos(gCueAngle) * gCuePower * gCueBallFactor));
gTable.balls[0].ApplyImpulse(imp);
}
break;
}
case(27):
{
for(int i=0;i<NUM_BALLS;i++)
{
gTable.balls[i].Reset();
}
break;
}
case(32):
{
gCamRotate = false;
break;
}
case('z'):
{
gCamL = true;
break;
}
case('c'):
{
gCamR = true;
break;
}
case('s'):
{
gCamU = true;
break;
}
case('x'):
{
gCamD = true;
break;
}
case('f'):
{
gCamZin = true;
break;
}
case('v'):
{
gCamZout = true;
break;
}
}
}
void KeyboardUpFunc(unsigned char key, int x, int y)
{
switch(key)
{
case(32):
{
gCamRotate = true;
break;
}
case('z'):
{
gCamL = false;
break;
}
case('c'):
{
gCamR = false;
break;
}
case('s'):
{
gCamU = false;
break;
}
case('x'):
{
gCamD = false;
break;
}
case('f'):
{
gCamZin = false;
break;
}
case('v'):
{
gCamZout = false;
break;
}
}
}
void ChangeSize(int w, int h) {
// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if(h == 0) h = 1;
float ratio = 1.0* w / h;
// Reset the coordinate system before modifying
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Set the viewport to be the entire window
glViewport(0, 0, w, h);
// Set the correct perspective.
gluPerspective(45,ratio,0.2,1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//gluLookAt(0.0,0.7,2.1, 0.0,0.0,0.0, 0.0f,1.0f,0.0f);
gluLookAt(gCamPos(0),gCamPos(1),gCamPos(2),gCamLookAt(0),gCamLookAt(1),gCamLookAt(2),0.0f,1.0f,0.0f);
}
void InitLights(void)
{
GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat mat_shininess[] = { 50.0 };
GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_SMOOTH);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
GLfloat light_ambient[] = { 2.0, 2.0, 2.0, 1.0 };
glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
glEnable(GL_DEPTH_TEST);
}
void UpdateScene(int ms)
{
if(gGame.ReadyNextHit()) gDoCue = true;
else gDoCue = false;
if(gDoCue)
{
if(gCueControl[0]) gCueAngle -= ((gCueAngleSpeed * ms)/1000);
if(gCueControl[1]) gCueAngle += ((gCueAngleSpeed * ms)/1000);
if (gCueAngle <0.0) gCueAngle += TWO_PI;
if (gCueAngle >TWO_PI) gCueAngle -= TWO_PI;
if(gCueControl[2]) gCuePower += ((gCuePowerSpeed * ms)/1000);
if(gCueControl[3]) gCuePower -= ((gCuePowerSpeed * ms)/1000);
if(gCuePower > gCuePowerMax) gCuePower = gCuePowerMax;
if(gCuePower < gCuePowerMin) gCuePower = gCuePowerMin;
}
DoCamera(ms);
gGame.Update(ms);
glutTimerFunc(SIM_UPDATE_MS, UpdateScene, SIM_UPDATE_MS);
glutPostRedisplay();
}
/*
int _tmain(int argc, _TCHAR* argv[]){
vec2 a1(-5,3);
vec2 a2(5, 3);
cushion c(a1, a2);
std::cout << c.normal.elem[0] << c.normal.elem[1];
}
*/
int _tmain(int argc, _TCHAR* argv[])
{
glutInit(&argc, ((char **)argv));
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE| GLUT_RGBA);
glutInitWindowPosition(0,0);
glutInitWindowSize(1000,700);
//glutFullScreen();
glutCreateWindow("MSc Workshop : Pool Game");
#if DRAW_SOLID
InitLights();
#endif
glutDisplayFunc(RenderScene);
glutTimerFunc(SIM_UPDATE_MS, UpdateScene, SIM_UPDATE_MS);
glutReshapeFunc(ChangeSize);
glutIdleFunc(RenderScene);
glutIgnoreKeyRepeat(1);
glutKeyboardFunc(KeyboardFunc);
glutKeyboardUpFunc(KeyboardUpFunc);
glutSpecialFunc(SpecKeyboardFunc);
glutSpecialUpFunc(SpecKeyboardUpFunc);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
}
| [
"shangmc812@gmail.com"
] | shangmc812@gmail.com |
14e236e5facb47ac33254b2d97abdca8a644d624 | 5beed0d7eaaed2254de2611496a286b099e29db7 | /10055_hashmat.cpp | 5787f7a179436126c79e5df3c8a60fb2a6c087df | [] | no_license | s-s-9/UVA-Codes | ff41350f18f1a746f8135755355f030ed5767083 | 7e985a3a5861ab09adf4bf08ce5a7f1e9538ffe7 | refs/heads/master | 2021-01-01T20:04:43.942824 | 2017-07-29T21:57:19 | 2017-07-29T21:57:19 | 98,763,671 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 271 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
long long int h, o;
while(scanf("%lld %lld", &h, &o)==2){
if(h>o){
printf("%lld\n", h - o);
}
else{
printf("%lld\n", o-h);
}
}
return 0;
}
| [
"ss9jo.o.o.o.oss@gmail.com"
] | ss9jo.o.o.o.oss@gmail.com |
8c0be35d17b0dc7ed95522b22ec04d052293e628 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/com/svcdlls/trksvcs/trkwks/port.cxx | c5e3b773943ef67a280c23b00e2011d0f5514349 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,447 | cxx |
// Copyright (c) 1996-1999 Microsoft Corporation
//+-------------------------------------------------------------------------
//
// Microsoft Windows
//
// File: port.cxx
//
// Contents: Code that receives notifications of moves from
// kernel.
//
// Classes:
//
// Functions:
//
//
//
// History:
//
// Notes:
//
// Codework: Security on semaphore and port objects
// _hDllReference when put in services.exe
// InitializeObjectAttributes( &oa, &name, 0, NULL, NULL /* &sd */ );
//
//--------------------------------------------------------------------------
#include "pch.cxx"
#pragma hdrstop
#include "trkwks.hxx"
#define THIS_FILE_NUMBER PORT_CXX_FILE_NO
DWORD WINAPI
PortThreadStartRoutine( LPVOID lpThreadParameter );
//+----------------------------------------------------------------------------
//
// CSystemSD::Initialize
// CSystemSD::UnInitialize
//
// Init and uninit the security descriptor that gives access only
// to System, or to System and Administrators.
//
//+----------------------------------------------------------------------------
void
CSystemSD::Initialize( ESystemSD eSystemSD )
{
// Add ACEs to the DACL in a Security Descriptor which give the
// System and Administrators full access.
_csd.Initialize();
if( SYSTEM_AND_ADMINISTRATOR == eSystemSD )
{
_csidAdministrators.Initialize( CSID::CSID_NT_AUTHORITY,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS );
_csd.AddAce( CSecDescriptor::ACL_IS_DACL, CSecDescriptor::AT_ACCESS_ALLOWED,
FILE_ALL_ACCESS, _csidAdministrators );
}
else
TrkAssert( SYSTEM_ONLY == eSystemSD );
_csidSystem.Initialize( CSID::CSID_NT_AUTHORITY, SECURITY_LOCAL_SYSTEM_RID );
_csd.AddAce( CSecDescriptor::ACL_IS_DACL, CSecDescriptor::AT_ACCESS_ALLOWED,
FILE_ALL_ACCESS, _csidSystem );
}
void
CSystemSD::UnInitialize()
{
_csidAdministrators.UnInitialize();
_csidSystem.UnInitialize();
_csd.UnInitialize();
}
//+----------------------------------------------------------------------------
//
// CPort::Initialize
//
// Create an LPC port to which the kernel will send move notifications,
// and open an event created by the kernel with which we'll signal
// our readiness to receive requests.
//
//+----------------------------------------------------------------------------
void
CPort::Initialize( CTrkWksSvc *pTrkWks,
DWORD dwThreadKeepAliveTime )
{
NTSTATUS Status;
OBJECT_ATTRIBUTES oa;
UNICODE_STRING name;
CSystemSD ssd;
DWORD dwThreadId;
__try
{
_hListenPort = NULL;
_hEvent = NULL;
_pTrkWks = pTrkWks;
_hLpcPort = NULL;
_hRegisterWaitForSingleObjectEx = NULL;
_fTerminating = FALSE;
// Create an LPC port to which the kernel will send move-notification requests
RtlInitUnicodeString( &name, TRKWKS_PORT_NAME );
ssd.Initialize();
InitializeObjectAttributes( &oa, &name, 0, NULL, ssd.operator const PSECURITY_DESCRIPTOR() );
Status = NtCreateWaitablePort(&_hListenPort, &oa,
sizeof(ULONG), // IN ULONG MaxConnectionInfoLength
sizeof(TRKWKS_PORT_REQUEST), // IN ULONG MaxMessageLength
0); // not used : IN ULONG MaxPoolUsage
if (!NT_SUCCESS(Status))
{
TrkLog(( TRKDBG_ERROR, TEXT("Couldn't create LPC connect port") ));
TrkReportInternalError( THIS_FILE_NUMBER, __LINE__, Status, TRKWKS_PORT_NAME );
TrkRaiseException(Status);
}
// Show that we need to do work in the UnInitialize method.
_fInitializeCalled = TRUE;
// Open the event which is created by the kernel for synchronization.
// We tell the kernel that we're available for move-notification requests
// by setting this event.
RtlInitUnicodeString( &name, TRKWKS_PORT_EVENT_NAME );
Status = NtOpenEvent( &_hEvent, EVENT_ALL_ACCESS, &oa );
if (!NT_SUCCESS(Status))
{
TrkReportInternalError( THIS_FILE_NUMBER, __LINE__, Status, TRKWKS_PORT_EVENT_NAME );
TrkLog(( TRKDBG_ERROR, TEXT("Couldn't open %s event"), TRKWKS_PORT_EVENT_NAME ));
TrkRaiseException(Status);
}
// Register our LPC connect port with the thread pool. When that handle signals,
// we'll run CPort::DoWork (it signals when we get any message, including
// LPC_CONNECT_REQUEST).
if( !RegisterWorkItemWithThreadPool() )
{
TrkLog(( TRKDBG_ERROR, TEXT("Failed RegisterWaitForSingleObjectEx in CPort::Initialize (%lu)"),
GetLastError() ));
TrkReportInternalError( THIS_FILE_NUMBER, __LINE__, Status, TRKREPORT_LAST_PARAM );
TrkRaiseLastError();
}
// When we receive a move notification and we get a thread from the pool,
// we'll keep that thread until we've gone idle for this amount of time.
// So if we receive several requests in a short period of time, we won't
// have to get a thread out of the pool for each.
_ThreadKeepAliveTime.QuadPart = -static_cast<LONGLONG>(dwThreadKeepAliveTime) * 10000000;
}
__finally
{
ssd.UnInitialize();
}
}
//+----------------------------------------------------------------------------
//
// CPort::RegisterWorkItemWithThreadPool
//
// Register the LPC connect port (_hListenPort) with the thread pool.
//
//+----------------------------------------------------------------------------
BOOL
CPort::RegisterWorkItemWithThreadPool()
{
// This is an execute-only-once work item, so it's inactive now.
// Delete it, specifying that there should be no completion event
// (if a completion event were used, this call would hang forever).
if( NULL != _hRegisterWaitForSingleObjectEx )
TrkUnregisterWait( _hRegisterWaitForSingleObjectEx, NULL );
// Now register it again.
_hRegisterWaitForSingleObjectEx
= TrkRegisterWaitForSingleObjectEx( _hListenPort, ThreadPoolCallbackFunction,
static_cast<PWorkItem*>(this), INFINITE,
WT_EXECUTEONLYONCE );
if( NULL == _hRegisterWaitForSingleObjectEx )
{
TrkLog(( TRKDBG_ERROR, TEXT("Failed RegisterWaitForSingleObjectEx in CPort::DoWork (%lu)"),
GetLastError() ));
return( FALSE );
}
else
TrkLog(( TRKDBG_PORT, TEXT("Registered LPC port work item") ));
return( TRUE );
}
//+----------------------------------------------------------------------------
//
// CPort::OnConnectionRequest
//
// Called when a connection request has been received. It is either
// accepted or rejected, depending on the request and the current state
// of the service.
//
// When the service is shutting down, CPort::UnInitialize posts a connection
// request with some connection information. When that connection request
// is received, it is rejected, and the pfStopPortThread is set True.
//
//+----------------------------------------------------------------------------
NTSTATUS
CPort::OnConnectionRequest( TRKWKS_PORT_CONNECT_REQUEST *pPortConnectRequest, BOOL *pfStopPortThread )
{
HANDLE hLpcPortT = NULL;
HANDLE *phLpcPort = NULL;
NTSTATUS Status = STATUS_SUCCESS;
BOOL fAccept = TRUE;
*pfStopPortThread = FALSE;
// Determine if we should accept or reject this connection request.
if( pPortConnectRequest->PortMessage.u1.s1.DataLength
>=
sizeof(pPortConnectRequest->Info) )
{
// There's extra connection info in this request. See if it's a request
// code that indicates that we should close down the port.
if( TRKWKS_RQ_EXIT_PORT_THREAD == pPortConnectRequest->Info.dwRequest )
{
fAccept = FALSE;
*pfStopPortThread = TRUE;
TrkLog(( TRKDBG_PORT, TEXT("Received port shutdown connection request") ));
}
else
{
fAccept = FALSE;
TrkLog(( TRKDBG_ERROR, TEXT("CPort: unknown Info.dwRequest (%d)"),
pPortConnectRequest->Info.dwRequest ));
}
}
else if( _fTerminating )
{
// We're shutting down, reject the request
fAccept = FALSE;
TrkLog(( TRKDBG_PORT, TEXT("Received connect request during service shutdown") ));
}
// Point phLpcPort to the real communications handle, or the dummy one used
// for rejections.
if( fAccept )
{
phLpcPort = &_hLpcPort;
// Close out any existing communication port
if( NULL != _hLpcPort )
{
NtClose( _hLpcPort );
_hLpcPort = NULL;
}
}
else
{
phLpcPort = &hLpcPortT;
}
// Accept or reject the new connection.
// In the reject case, this could create a race condition. After we make the
// NtAcceptConnectPort call, the CPort::UnInitialize thread might wake up and
// delete the CPort before this thread runs again. So, after making this
// call, we cannot touch anything in 'this'.
TrkLog(( TRKDBG_PORT, TEXT("%s connect request"),
fAccept ? TEXT("Accepting") : TEXT("Rejecting") ));
TRKWKS_PORT_REQUEST *pPortRequest = (TRKWKS_PORT_REQUEST*) pPortConnectRequest;
pPortRequest->PortMessage.u1.s1.TotalLength = sizeof(*pPortRequest);
pPortRequest->PortMessage.u1.s1.DataLength = sizeof(pPortRequest->Request); // MaxMessageLength
Status = NtAcceptConnectPort(
phLpcPort, // PortHandle,
NULL, // PortContext OPTIONAL,
&pPortRequest->PortMessage,
(BOOLEAN)fAccept, // AcceptConnection,
NULL, // ServerView OPTIONAL,
NULL); // ClientView OPTIONAL
if( !NT_SUCCESS(Status) )
{
TrkLog(( TRKDBG_ERROR, TEXT("Failed NtAcceptConnectPort(%s) %08x"),
fAccept ? TEXT("accept"):TEXT("reject"),
Status ));
goto Exit;
}
// If we rejected it, then phLpcPort was hLpcPortT, and it's just
// a dummy argument which must be present but isn't set by NtAcceptConnectPort.
TrkAssert( NULL != *phLpcPort || !fAccept );
// Wake up the client thread (unblock its call to NtConnectPort)
if( fAccept )
{
Status = NtCompleteConnectPort( _hLpcPort );
if( !NT_SUCCESS(Status) )
{
TrkLog(( TRKDBG_ERROR, TEXT("Failed NtCompleteConnectPort %08x"), Status ));
goto Exit;
}
}
Exit:
return( Status );
}
//+----------------------------------------------------------------------------
//
// CPort::DoWork
//
// This method is called by the thread pool when our LPC connect port
// (_hLpcListenPort) is signaled to indicate that a request is available.
// If the request is a connection request, we accept or reject it and continue.
// If the request is a move notification request, we send it to
// CTrkWksSvc for processing.
//
// This work item is registerd with the thread pool with the
// WT_EXECUTEONLYONCE flag, since the connection port isn't
// auto-reset. So after processing, we must
// re-register. Before doing so, or if re-registration fails,
// we keep the thread in a NtReplyWaitReceiveEx call for several
// (configurable) seconds. This way, if several requests arrive
// in a short amount of time, we don't have to thrash the thread pool.
//
// During service termination, _fTerminate is set, and a connection
// request is made by CPort::UnInitialize. This request is rejected,
// and in that case we don't re-register the connect port with the thread
// pool.
//
//+----------------------------------------------------------------------------
void
CPort::DoWork()
{
NTSTATUS Status = STATUS_SUCCESS;
TRKWKS_PORT_REQUEST PortRequest;
TRKWKS_PORT_REPLY PortReply;
PortRequest.PortMessage.u1.s1.TotalLength = sizeof(PortRequest.PortMessage);
PortRequest.PortMessage.u1.s1.DataLength = (CSHORT)0;
BOOL fReuseThread = FALSE;
// The fact that we're running indicates that there's a request
// waiting for us, and the first NtReplyWaitReceivePortEx below will
// immediately return. We loop until nothing is received for 30
// seconds.
while( TRUE )
{
BOOL fTerminating = FALSE; // TRUE => service is shutting down
BOOL fStopPortThread = FALSE; // TRUE => we should shut down this port
Status = NtReplyWaitReceivePortEx( _hListenPort, //_hLpcPort,
NULL,
NULL,
&PortRequest.PortMessage,
&_ThreadKeepAliveTime
);
// Cache a local copy of _fTerminating. In the shutdown case, there's
// a race condition where the CPort object gets deleted before this routine
// can finish. By caching this flag, we don't have to touch this 'this'
// pointer in that case, and therefore avoid the problem.
fTerminating = _fTerminating;
// If we timeed out, then let the thread return to the thread pool.
if( STATUS_TIMEOUT != Status )
{
// We didn't time out.
#if DBG
if( fReuseThread )
TrkLog(( TRKDBG_PORT, TEXT("CPort re-using thread") ));
#endif
fReuseThread = TRUE;
// Is this a request for a new connection?
if( NT_SUCCESS(Status)
&&
LPC_CONNECTION_REQUEST == PortRequest.PortMessage.u2.s2.Type )
{
TrkLog(( TRKDBG_PORT, TEXT("Received LPC connect request") ));
Status = OnConnectionRequest( (TRKWKS_PORT_CONNECT_REQUEST*) &PortRequest,
&fStopPortThread );
#if DBG
if( !NT_SUCCESS(Status) )
TrkLog(( TRKDBG_ERROR, TEXT("CPort::DoWork couldn't handle connection request %08x"), Status ));
#endif
} // if( ... LPC_CONNECTION_REQUEST == PortRequest.PortMessage.u2.s2.Type )
// Or, is this a good move notification?
else if( NT_SUCCESS(Status) && NULL != _hLpcPort )
{
// Process the move notification in CTrkWksSvc. If we're in the proces,
// though, of shutting the service down, then return the same error that
// the kernel would see if DisableKernelNotifications had been called
// in time.
if( _fTerminating )
PortReply.Reply.Status = STATUS_OBJECT_NAME_NOT_FOUND;
else
// The following doesn't raise.
PortReply.Reply.Status = _pTrkWks->OnPortNotification( &PortRequest.Request );
// Send the resulting Status back to the kernel.
PortReply.PortMessage = PortRequest.PortMessage;
PortReply.PortMessage.u1.s1.TotalLength = sizeof(PortReply);
PortReply.PortMessage.u1.s1.DataLength = sizeof(PortReply.Reply);
Status = NtReplyPort( _hLpcPort, &PortReply.PortMessage );
#if DBG
if( !NT_SUCCESS(Status) )
TrkLog(( TRKDBG_ERROR, TEXT("Failed NtReplyPort (%08x)"), Status ));
#endif
}
// Otherwise, we either got an error, or a non-connect message on an
// unconnected port.
else
{
if( NT_SUCCESS(Status) )
Status = STATUS_CONNECTION_INVALID;
TrkLog(( TRKDBG_ERROR, TEXT("CPort::PortThread - NtReplyWaitReceivePortEx failed %0X/%p"),
Status, _hLpcPort ));
}
// To be robust against some unknown bug causing thrashing, sleep
// if there was an error.
if( !NT_SUCCESS(Status) && !fTerminating && !fStopPortThread )
Sleep( 1000 );
// Unless the service is shutting down, we don't want to fall
// through and re-register yet. We should go back to the
// NtReplyWaitReceivePortEx to see if there are more requests
// or will be soon.
if( !fStopPortThread )
continue;
} // if( STATUS_TIMEOUT != Status )
// Re-register the connect port with the thread pool, unless we're supposed
// to stop the port thread.
if( fStopPortThread )
{
TrkLog(( TRKDBG_PORT, TEXT("Stopping port work item") ));
}
else
{
// If we can't re-register for some reason, just continue back to the top
// and sit in the NtReplyWaitReceiveEx for a while.
if( !RegisterWorkItemWithThreadPool() )
{
TrkLog(( TRKDBG_PORT, TEXT("Re-using port thread due to registration error (%lu)"), GetLastError() ));
continue;
}
else
TrkLog(( TRKDBG_PORT, TEXT("Returning port thread to pool") ));
}
// We're either terminating or we've successfully re-registered. In either case, we can let
// the thread go back to the pool.
break;
} // while( TRUE )
}
//+----------------------------------------------------------------------------
//
// CPort::UnInitialize
//
// Remove the LPC connect port work item from the thread pool, and
// clean everything up.
//
// To remove the work item, we can't safely call UnregisterWait, because
// we register with WT_EXECUTEONLYONCE. Thus when we call UnregisterWait,
// the wait may have already been deleted. So, instead, we attempt a connection
// to the LPC connect port, after first setting _fTerminating. This will be
// picked up on a thread pool thread in DoWork, the connection will be
// rejected, and the work item will not be re-registered.
//
//+----------------------------------------------------------------------------
void
CPort::UnInitialize()
{
if (_fInitializeCalled)
{
NTSTATUS status = STATUS_SUCCESS;
UNICODE_STRING usPortName;
OBJECT_ATTRIBUTES oa;
HANDLE hPort = NULL;
ULONG cbMaxMessage = 0;
TRKWKS_CONNECTION_INFO ConnectionInformation = { TRKWKS_RQ_EXIT_PORT_THREAD };
ULONG cbConnectionInformation = sizeof(ConnectionInformation);
_fTerminating = TRUE;
// Attempt to connect to _hLpcListenPort
RtlInitUnicodeString( &usPortName, TRKWKS_PORT_NAME );
SECURITY_QUALITY_OF_SERVICE dynamicQos;
dynamicQos.ImpersonationLevel = SecurityImpersonation;
dynamicQos.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING;
dynamicQos.EffectiveOnly = TRUE;
TrkLog(( TRKDBG_PORT, TEXT("CPort::UnInitialize doing an NtConnectPort to %s"), TRKWKS_PORT_NAME ));
status = NtConnectPort( &hPort, &usPortName, &dynamicQos, NULL, NULL,
&cbMaxMessage, &ConnectionInformation, &cbConnectionInformation );
TrkLog(( TRKDBG_PORT, TEXT("CPort::UnInitialize, NtConnectPort completed (0x%08x)"), status ));
if( NT_SUCCESS(status) )
{
TrkLog(( TRKDBG_PORT, TEXT("CPort::UnInitialize NtConnectPort unexpectedly succeeded"), status ));
if( NULL != hPort )
NtClose( hPort );
}
#if DBG
else
{
TrkAssert( NULL == hPort );
if( STATUS_PORT_CONNECTION_REFUSED != status )
TrkLog(( TRKDBG_ERROR, TEXT("CPort::UnInitialize NtConnectPort failed (%08x)"), status ));
}
#endif
// DoWork has been called and is done. Unregister the work item, waiting for the thread
// to complete.
if( NULL != _hRegisterWaitForSingleObjectEx )
TrkUnregisterWait( _hRegisterWaitForSingleObjectEx );
_hRegisterWaitForSingleObjectEx = NULL;
// Clean up the port.
if (_hLpcPort != NULL)
TrkVerify( NT_SUCCESS( NtClose(_hLpcPort) ) );
_hLpcPort = NULL;
if (_hListenPort != NULL)
TrkVerify( NT_SUCCESS( NtClose(_hListenPort) ) );
_hListenPort = NULL;
if( NULL != _hEvent )
NtClose( _hEvent );
_hEvent = NULL;
_fInitializeCalled = FALSE;
}
}
//+----------------------------------------------------------------------------
//
// CPort::EnableKernelNotifications
// CPort::DisableKernelNotifications
//
// Set/clear the event which tells nt!IopConnectLinkTrackingPort that we're
// up and ready to receive a connection.
//
//+----------------------------------------------------------------------------
void
CPort::EnableKernelNotifications()
{
NTSTATUS Status;
Status = NtSetEvent( _hEvent, NULL );
TrkVerify( NT_SUCCESS( Status ) );
}
void
CPort::DisableKernelNotifications()
{
if (_fInitializeCalled)
{
NTSTATUS Status;
Status = NtClearEvent( _hEvent );
TrkVerify( NT_SUCCESS( Status ) );
}
}
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
0edbeeb6bfa6475973e29f8ef0ebd02fdbe45f91 | 645dfb8cc3a2d7b043b07280718b0b11eeafd29c | /src/testApp.cpp | 6142eb78f60a478bf5778a74e8d9cfd702f49863 | [] | no_license | harpreets/oF-BareBones-Kinect-OpenNI | 25d1c0f50b6168bf6e0f4a4c5316160b944b7e66 | b97ee7567ec62bf4f618c60e5da0a688f272270d | refs/heads/master | 2021-07-13T20:21:52.974445 | 2017-10-07T23:49:36 | 2017-10-07T23:49:36 | 106,137,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,959 | cpp | #include "testApp.h"
//--------------------------------------------------------------
void testApp::setup(){
/************************ Kinect ***************************/
numDevices = openNIDevice[0].getNumDevices();
for(int deviceID=0;deviceID<numDevices;++deviceID){
openNIDevice[deviceID].setup();
openNIDevice[deviceID].addDepthGenerator();
openNIDevice[deviceID].addUserGenerator();
openNIDevice[deviceID].setMirror(true);
openNIDevice[deviceID].start();
}
}
//--------------------------------------------------------------
void testApp::update(){
for(int deviceID=0;deviceID<numDevices;++deviceID){
openNIDevice[deviceID].update();
}
}
//--------------------------------------------------------------
void testApp::draw(){
}
//--------------------------------------------------------------
void testApp::keyPressed(int key){
}
//--------------------------------------------------------------
void testApp::keyReleased(int key){
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo){
}
void testApp::exit(){
for(int deviceID=0;deviceID<numDevices;++deviceID){
openNIDevice[deviceID].stop();
}
} | [
"sareen@Harpreets-MacBook-Pro.local"
] | sareen@Harpreets-MacBook-Pro.local |
eb0c45d1163fb311989c3d6154257f1bbe273797 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_6560.cpp | 51d385debadd5c846f51e307953fd46a860adee4 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 83 | cpp | f(nread < 0) {
failf(data, "read: %s", strerror(errno));
rc = -1;
} | [
"993273596@qq.com"
] | 993273596@qq.com |
78e8a2f28c81322df15915a936a5cd7ca5b31c3b | 32a3d50442515749849d99ac4651b010cc84e414 | /src/hb-ot-layout-gsub-table.hh | 98f3784cf496802a465362db20457b6c8fae5990 | [
"LicenseRef-scancode-other-permissive",
"MIT-Modern-Variant",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | marklh9/harfbuzz | 9f8db83a069e08b6b408ece2bab4c52fa1271ca3 | e9416a2f629f2780fd46dc0026125b8a5386ecd1 | refs/heads/master | 2021-08-15T05:53:25.127973 | 2017-11-17T12:56:43 | 2017-11-17T12:56:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,603 | hh | /*
* Copyright © 2007,2008,2009,2010 Red Hat, Inc.
* Copyright © 2010,2012,2013 Google, Inc.
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Red Hat Author(s): Behdad Esfahbod
* Google Author(s): Behdad Esfahbod
*/
#ifndef HB_OT_LAYOUT_GSUB_TABLE_HH
#define HB_OT_LAYOUT_GSUB_TABLE_HH
#include "hb-ot-layout-gsubgpos-private.hh"
namespace OT {
struct SingleSubstFormat1
{
inline void closure (hb_closure_context_t *c) const
{
TRACE_CLOSURE (this);
Coverage::Iter iter;
for (iter.init (this+coverage); iter.more (); iter.next ())
{
/* TODO Switch to range-based API to work around malicious fonts.
* https://github.com/behdad/harfbuzz/issues/363 */
hb_codepoint_t glyph_id = iter.get_glyph ();
if (c->glyphs->has (glyph_id))
c->glyphs->add ((glyph_id + deltaGlyphID) & 0xFFFFu);
}
}
inline void collect_glyphs (hb_collect_glyphs_context_t *c) const
{
TRACE_COLLECT_GLYPHS (this);
Coverage::Iter iter;
for (iter.init (this+coverage); iter.more (); iter.next ())
{
/* TODO Switch to range-based API to work around malicious fonts.
* https://github.com/behdad/harfbuzz/issues/363 */
hb_codepoint_t glyph_id = iter.get_glyph ();
c->input->add (glyph_id);
c->output->add ((glyph_id + deltaGlyphID) & 0xFFFFu);
}
}
inline const Coverage &get_coverage (void) const
{
return this+coverage;
}
inline bool would_apply (hb_would_apply_context_t *c) const
{
TRACE_WOULD_APPLY (this);
return_trace (c->len == 1 && (this+coverage).get_coverage (c->glyphs[0]) != NOT_COVERED);
}
inline bool apply (hb_apply_context_t *c) const
{
TRACE_APPLY (this);
hb_codepoint_t glyph_id = c->buffer->cur().codepoint;
unsigned int index = (this+coverage).get_coverage (glyph_id);
if (likely (index == NOT_COVERED)) return_trace (false);
/* According to the Adobe Annotated OpenType Suite, result is always
* limited to 16bit. */
glyph_id = (glyph_id + deltaGlyphID) & 0xFFFFu;
c->replace_glyph (glyph_id);
return_trace (true);
}
inline bool serialize (hb_serialize_context_t *c,
Supplier<GlyphID> &glyphs,
unsigned int num_glyphs,
int delta)
{
TRACE_SERIALIZE (this);
if (unlikely (!c->extend_min (*this))) return_trace (false);
if (unlikely (!coverage.serialize (c, this).serialize (c, glyphs, num_glyphs))) return_trace (false);
deltaGlyphID.set (delta); /* TODO(serilaize) overflow? */
return_trace (true);
}
inline bool sanitize (hb_sanitize_context_t *c) const
{
TRACE_SANITIZE (this);
return_trace (coverage.sanitize (c, this) && deltaGlyphID.sanitize (c));
}
protected:
UINT16 format; /* Format identifier--format = 1 */
OffsetTo<Coverage>
coverage; /* Offset to Coverage table--from
* beginning of Substitution table */
INT16 deltaGlyphID; /* Add to original GlyphID to get
* substitute GlyphID */
public:
DEFINE_SIZE_STATIC (6);
};
struct SingleSubstFormat2
{
inline void closure (hb_closure_context_t *c) const
{
TRACE_CLOSURE (this);
Coverage::Iter iter;
unsigned int count = substitute.len;
for (iter.init (this+coverage); iter.more (); iter.next ())
{
if (unlikely (iter.get_coverage () >= count))
break; /* Work around malicious fonts. https://github.com/behdad/harfbuzz/issues/363 */
if (c->glyphs->has (iter.get_glyph ()))
c->glyphs->add (substitute[iter.get_coverage ()]);
}
}
inline void collect_glyphs (hb_collect_glyphs_context_t *c) const
{
TRACE_COLLECT_GLYPHS (this);
Coverage::Iter iter;
unsigned int count = substitute.len;
for (iter.init (this+coverage); iter.more (); iter.next ())
{
if (unlikely (iter.get_coverage () >= count))
break; /* Work around malicious fonts. https://github.com/behdad/harfbuzz/issues/363 */
c->input->add (iter.get_glyph ());
c->output->add (substitute[iter.get_coverage ()]);
}
}
inline const Coverage &get_coverage (void) const
{
return this+coverage;
}
inline bool would_apply (hb_would_apply_context_t *c) const
{
TRACE_WOULD_APPLY (this);
return_trace (c->len == 1 && (this+coverage).get_coverage (c->glyphs[0]) != NOT_COVERED);
}
inline bool apply (hb_apply_context_t *c) const
{
TRACE_APPLY (this);
hb_codepoint_t glyph_id = c->buffer->cur().codepoint;
unsigned int index = (this+coverage).get_coverage (glyph_id);
if (likely (index == NOT_COVERED)) return_trace (false);
if (unlikely (index >= substitute.len)) return_trace (false);
glyph_id = substitute[index];
c->replace_glyph (glyph_id);
return_trace (true);
}
inline bool serialize (hb_serialize_context_t *c,
Supplier<GlyphID> &glyphs,
Supplier<GlyphID> &substitutes,
unsigned int num_glyphs)
{
TRACE_SERIALIZE (this);
if (unlikely (!c->extend_min (*this))) return_trace (false);
if (unlikely (!substitute.serialize (c, substitutes, num_glyphs))) return_trace (false);
if (unlikely (!coverage.serialize (c, this).serialize (c, glyphs, num_glyphs))) return_trace (false);
return_trace (true);
}
inline bool sanitize (hb_sanitize_context_t *c) const
{
TRACE_SANITIZE (this);
return_trace (coverage.sanitize (c, this) && substitute.sanitize (c));
}
protected:
UINT16 format; /* Format identifier--format = 2 */
OffsetTo<Coverage>
coverage; /* Offset to Coverage table--from
* beginning of Substitution table */
ArrayOf<GlyphID>
substitute; /* Array of substitute
* GlyphIDs--ordered by Coverage Index */
public:
DEFINE_SIZE_ARRAY (6, substitute);
};
struct SingleSubst
{
inline bool serialize (hb_serialize_context_t *c,
Supplier<GlyphID> &glyphs,
Supplier<GlyphID> &substitutes,
unsigned int num_glyphs)
{
TRACE_SERIALIZE (this);
if (unlikely (!c->extend_min (u.format))) return_trace (false);
unsigned int format = 2;
int delta = 0;
if (num_glyphs) {
format = 1;
/* TODO(serialize) check for wrap-around */
delta = substitutes[0] - glyphs[0];
for (unsigned int i = 1; i < num_glyphs; i++)
if (delta != substitutes[i] - glyphs[i]) {
format = 2;
break;
}
}
u.format.set (format);
switch (u.format) {
case 1: return_trace (u.format1.serialize (c, glyphs, num_glyphs, delta));
case 2: return_trace (u.format2.serialize (c, glyphs, substitutes, num_glyphs));
default:return_trace (false);
}
}
template <typename context_t>
inline typename context_t::return_t dispatch (context_t *c) const
{
TRACE_DISPATCH (this, u.format);
if (unlikely (!c->may_dispatch (this, &u.format))) return_trace (c->no_dispatch_return_value ());
switch (u.format) {
case 1: return_trace (c->dispatch (u.format1));
case 2: return_trace (c->dispatch (u.format2));
default:return_trace (c->default_return_value ());
}
}
protected:
union {
UINT16 format; /* Format identifier */
SingleSubstFormat1 format1;
SingleSubstFormat2 format2;
} u;
};
struct Sequence
{
inline void closure (hb_closure_context_t *c) const
{
TRACE_CLOSURE (this);
unsigned int count = substitute.len;
for (unsigned int i = 0; i < count; i++)
c->glyphs->add (substitute[i]);
}
inline void collect_glyphs (hb_collect_glyphs_context_t *c) const
{
TRACE_COLLECT_GLYPHS (this);
unsigned int count = substitute.len;
for (unsigned int i = 0; i < count; i++)
c->output->add (substitute[i]);
}
inline bool apply (hb_apply_context_t *c) const
{
TRACE_APPLY (this);
unsigned int count = substitute.len;
/* Special-case to make it in-place and not consider this
* as a "multiplied" substitution. */
if (unlikely (count == 1))
{
c->replace_glyph (substitute.array[0]);
return_trace (true);
}
/* Spec disallows this, but Uniscribe allows it.
* https://github.com/behdad/harfbuzz/issues/253 */
else if (unlikely (count == 0))
{
c->buffer->delete_glyph ();
return_trace (true);
}
unsigned int klass = _hb_glyph_info_is_ligature (&c->buffer->cur()) ?
HB_OT_LAYOUT_GLYPH_PROPS_BASE_GLYPH : 0;
for (unsigned int i = 0; i < count; i++) {
_hb_glyph_info_set_lig_props_for_component (&c->buffer->cur(), i);
c->output_glyph_for_component (substitute.array[i], klass);
}
c->buffer->skip_glyph ();
return_trace (true);
}
inline bool serialize (hb_serialize_context_t *c,
Supplier<GlyphID> &glyphs,
unsigned int num_glyphs)
{
TRACE_SERIALIZE (this);
if (unlikely (!c->extend_min (*this))) return_trace (false);
if (unlikely (!substitute.serialize (c, glyphs, num_glyphs))) return_trace (false);
return_trace (true);
}
inline bool sanitize (hb_sanitize_context_t *c) const
{
TRACE_SANITIZE (this);
return_trace (substitute.sanitize (c));
}
protected:
ArrayOf<GlyphID>
substitute; /* String of GlyphIDs to substitute */
public:
DEFINE_SIZE_ARRAY (2, substitute);
};
struct MultipleSubstFormat1
{
inline void closure (hb_closure_context_t *c) const
{
TRACE_CLOSURE (this);
Coverage::Iter iter;
unsigned int count = sequence.len;
for (iter.init (this+coverage); iter.more (); iter.next ())
{
if (unlikely (iter.get_coverage () >= count))
break; /* Work around malicious fonts. https://github.com/behdad/harfbuzz/issues/363 */
if (c->glyphs->has (iter.get_glyph ()))
(this+sequence[iter.get_coverage ()]).closure (c);
}
}
inline void collect_glyphs (hb_collect_glyphs_context_t *c) const
{
TRACE_COLLECT_GLYPHS (this);
(this+coverage).add_coverage (c->input);
unsigned int count = sequence.len;
for (unsigned int i = 0; i < count; i++)
(this+sequence[i]).collect_glyphs (c);
}
inline const Coverage &get_coverage (void) const
{
return this+coverage;
}
inline bool would_apply (hb_would_apply_context_t *c) const
{
TRACE_WOULD_APPLY (this);
return_trace (c->len == 1 && (this+coverage).get_coverage (c->glyphs[0]) != NOT_COVERED);
}
inline bool apply (hb_apply_context_t *c) const
{
TRACE_APPLY (this);
unsigned int index = (this+coverage).get_coverage (c->buffer->cur().codepoint);
if (likely (index == NOT_COVERED)) return_trace (false);
return_trace ((this+sequence[index]).apply (c));
}
inline bool serialize (hb_serialize_context_t *c,
Supplier<GlyphID> &glyphs,
Supplier<unsigned int> &substitute_len_list,
unsigned int num_glyphs,
Supplier<GlyphID> &substitute_glyphs_list)
{
TRACE_SERIALIZE (this);
if (unlikely (!c->extend_min (*this))) return_trace (false);
if (unlikely (!sequence.serialize (c, num_glyphs))) return_trace (false);
for (unsigned int i = 0; i < num_glyphs; i++)
if (unlikely (!sequence[i].serialize (c, this).serialize (c,
substitute_glyphs_list,
substitute_len_list[i]))) return_trace (false);
substitute_len_list.advance (num_glyphs);
if (unlikely (!coverage.serialize (c, this).serialize (c, glyphs, num_glyphs))) return_trace (false);
return_trace (true);
}
inline bool sanitize (hb_sanitize_context_t *c) const
{
TRACE_SANITIZE (this);
return_trace (coverage.sanitize (c, this) && sequence.sanitize (c, this));
}
protected:
UINT16 format; /* Format identifier--format = 1 */
OffsetTo<Coverage>
coverage; /* Offset to Coverage table--from
* beginning of Substitution table */
OffsetArrayOf<Sequence>
sequence; /* Array of Sequence tables
* ordered by Coverage Index */
public:
DEFINE_SIZE_ARRAY (6, sequence);
};
struct MultipleSubst
{
inline bool serialize (hb_serialize_context_t *c,
Supplier<GlyphID> &glyphs,
Supplier<unsigned int> &substitute_len_list,
unsigned int num_glyphs,
Supplier<GlyphID> &substitute_glyphs_list)
{
TRACE_SERIALIZE (this);
if (unlikely (!c->extend_min (u.format))) return_trace (false);
unsigned int format = 1;
u.format.set (format);
switch (u.format) {
case 1: return_trace (u.format1.serialize (c, glyphs, substitute_len_list, num_glyphs, substitute_glyphs_list));
default:return_trace (false);
}
}
template <typename context_t>
inline typename context_t::return_t dispatch (context_t *c) const
{
TRACE_DISPATCH (this, u.format);
if (unlikely (!c->may_dispatch (this, &u.format))) return_trace (c->no_dispatch_return_value ());
switch (u.format) {
case 1: return_trace (c->dispatch (u.format1));
default:return_trace (c->default_return_value ());
}
}
protected:
union {
UINT16 format; /* Format identifier */
MultipleSubstFormat1 format1;
} u;
};
typedef ArrayOf<GlyphID> AlternateSet; /* Array of alternate GlyphIDs--in
* arbitrary order */
struct AlternateSubstFormat1
{
inline void closure (hb_closure_context_t *c) const
{
TRACE_CLOSURE (this);
Coverage::Iter iter;
unsigned int count = alternateSet.len;
for (iter.init (this+coverage); iter.more (); iter.next ())
{
if (unlikely (iter.get_coverage () >= count))
break; /* Work around malicious fonts. https://github.com/behdad/harfbuzz/issues/363 */
if (c->glyphs->has (iter.get_glyph ())) {
const AlternateSet &alt_set = this+alternateSet[iter.get_coverage ()];
unsigned int count = alt_set.len;
for (unsigned int i = 0; i < count; i++)
c->glyphs->add (alt_set[i]);
}
}
}
inline void collect_glyphs (hb_collect_glyphs_context_t *c) const
{
TRACE_COLLECT_GLYPHS (this);
Coverage::Iter iter;
unsigned int count = alternateSet.len;
for (iter.init (this+coverage); iter.more (); iter.next ())
{
if (unlikely (iter.get_coverage () >= count))
break; /* Work around malicious fonts. https://github.com/behdad/harfbuzz/issues/363 */
c->input->add (iter.get_glyph ());
const AlternateSet &alt_set = this+alternateSet[iter.get_coverage ()];
unsigned int count = alt_set.len;
for (unsigned int i = 0; i < count; i++)
c->output->add (alt_set[i]);
}
}
inline const Coverage &get_coverage (void) const
{
return this+coverage;
}
inline bool would_apply (hb_would_apply_context_t *c) const
{
TRACE_WOULD_APPLY (this);
return_trace (c->len == 1 && (this+coverage).get_coverage (c->glyphs[0]) != NOT_COVERED);
}
inline bool apply (hb_apply_context_t *c) const
{
TRACE_APPLY (this);
hb_codepoint_t glyph_id = c->buffer->cur().codepoint;
unsigned int index = (this+coverage).get_coverage (glyph_id);
if (likely (index == NOT_COVERED)) return_trace (false);
const AlternateSet &alt_set = this+alternateSet[index];
if (unlikely (!alt_set.len)) return_trace (false);
hb_mask_t glyph_mask = c->buffer->cur().mask;
hb_mask_t lookup_mask = c->lookup_mask;
/* Note: This breaks badly if two features enabled this lookup together. */
unsigned int shift = _hb_ctz (lookup_mask);
unsigned int alt_index = ((lookup_mask & glyph_mask) >> shift);
if (unlikely (alt_index > alt_set.len || alt_index == 0)) return_trace (false);
glyph_id = alt_set[alt_index - 1];
c->replace_glyph (glyph_id);
return_trace (true);
}
inline bool serialize (hb_serialize_context_t *c,
Supplier<GlyphID> &glyphs,
Supplier<unsigned int> &alternate_len_list,
unsigned int num_glyphs,
Supplier<GlyphID> &alternate_glyphs_list)
{
TRACE_SERIALIZE (this);
if (unlikely (!c->extend_min (*this))) return_trace (false);
if (unlikely (!alternateSet.serialize (c, num_glyphs))) return_trace (false);
for (unsigned int i = 0; i < num_glyphs; i++)
if (unlikely (!alternateSet[i].serialize (c, this).serialize (c,
alternate_glyphs_list,
alternate_len_list[i]))) return_trace (false);
alternate_len_list.advance (num_glyphs);
if (unlikely (!coverage.serialize (c, this).serialize (c, glyphs, num_glyphs))) return_trace (false);
return_trace (true);
}
inline bool sanitize (hb_sanitize_context_t *c) const
{
TRACE_SANITIZE (this);
return_trace (coverage.sanitize (c, this) && alternateSet.sanitize (c, this));
}
protected:
UINT16 format; /* Format identifier--format = 1 */
OffsetTo<Coverage>
coverage; /* Offset to Coverage table--from
* beginning of Substitution table */
OffsetArrayOf<AlternateSet>
alternateSet; /* Array of AlternateSet tables
* ordered by Coverage Index */
public:
DEFINE_SIZE_ARRAY (6, alternateSet);
};
struct AlternateSubst
{
inline bool serialize (hb_serialize_context_t *c,
Supplier<GlyphID> &glyphs,
Supplier<unsigned int> &alternate_len_list,
unsigned int num_glyphs,
Supplier<GlyphID> &alternate_glyphs_list)
{
TRACE_SERIALIZE (this);
if (unlikely (!c->extend_min (u.format))) return_trace (false);
unsigned int format = 1;
u.format.set (format);
switch (u.format) {
case 1: return_trace (u.format1.serialize (c, glyphs, alternate_len_list, num_glyphs, alternate_glyphs_list));
default:return_trace (false);
}
}
template <typename context_t>
inline typename context_t::return_t dispatch (context_t *c) const
{
TRACE_DISPATCH (this, u.format);
if (unlikely (!c->may_dispatch (this, &u.format))) return_trace (c->no_dispatch_return_value ());
switch (u.format) {
case 1: return_trace (c->dispatch (u.format1));
default:return_trace (c->default_return_value ());
}
}
protected:
union {
UINT16 format; /* Format identifier */
AlternateSubstFormat1 format1;
} u;
};
struct Ligature
{
inline void closure (hb_closure_context_t *c) const
{
TRACE_CLOSURE (this);
unsigned int count = component.len;
for (unsigned int i = 1; i < count; i++)
if (!c->glyphs->has (component[i]))
return;
c->glyphs->add (ligGlyph);
}
inline void collect_glyphs (hb_collect_glyphs_context_t *c) const
{
TRACE_COLLECT_GLYPHS (this);
unsigned int count = component.len;
for (unsigned int i = 1; i < count; i++)
c->input->add (component[i]);
c->output->add (ligGlyph);
}
inline bool would_apply (hb_would_apply_context_t *c) const
{
TRACE_WOULD_APPLY (this);
if (c->len != component.len)
return_trace (false);
for (unsigned int i = 1; i < c->len; i++)
if (likely (c->glyphs[i] != component[i]))
return_trace (false);
return_trace (true);
}
inline bool apply (hb_apply_context_t *c) const
{
TRACE_APPLY (this);
unsigned int count = component.len;
if (unlikely (!count)) return_trace (false);
/* Special-case to make it in-place and not consider this
* as a "ligated" substitution. */
if (unlikely (count == 1))
{
c->replace_glyph (ligGlyph);
return_trace (true);
}
bool is_mark_ligature = false;
unsigned int total_component_count = 0;
unsigned int match_length = 0;
unsigned int match_positions[HB_MAX_CONTEXT_LENGTH];
if (likely (!match_input (c, count,
&component[1],
match_glyph,
nullptr,
&match_length,
match_positions,
&is_mark_ligature,
&total_component_count)))
return_trace (false);
ligate_input (c,
count,
match_positions,
match_length,
ligGlyph,
is_mark_ligature,
total_component_count);
return_trace (true);
}
inline bool serialize (hb_serialize_context_t *c,
GlyphID ligature,
Supplier<GlyphID> &components, /* Starting from second */
unsigned int num_components /* Including first component */)
{
TRACE_SERIALIZE (this);
if (unlikely (!c->extend_min (*this))) return_trace (false);
ligGlyph = ligature;
if (unlikely (!component.serialize (c, components, num_components))) return_trace (false);
return_trace (true);
}
public:
inline bool sanitize (hb_sanitize_context_t *c) const
{
TRACE_SANITIZE (this);
return_trace (ligGlyph.sanitize (c) && component.sanitize (c));
}
protected:
GlyphID ligGlyph; /* GlyphID of ligature to substitute */
HeadlessArrayOf<GlyphID>
component; /* Array of component GlyphIDs--start
* with the second component--ordered
* in writing direction */
public:
DEFINE_SIZE_ARRAY (4, component);
};
struct LigatureSet
{
inline void closure (hb_closure_context_t *c) const
{
TRACE_CLOSURE (this);
unsigned int num_ligs = ligature.len;
for (unsigned int i = 0; i < num_ligs; i++)
(this+ligature[i]).closure (c);
}
inline void collect_glyphs (hb_collect_glyphs_context_t *c) const
{
TRACE_COLLECT_GLYPHS (this);
unsigned int num_ligs = ligature.len;
for (unsigned int i = 0; i < num_ligs; i++)
(this+ligature[i]).collect_glyphs (c);
}
inline bool would_apply (hb_would_apply_context_t *c) const
{
TRACE_WOULD_APPLY (this);
unsigned int num_ligs = ligature.len;
for (unsigned int i = 0; i < num_ligs; i++)
{
const Ligature &lig = this+ligature[i];
if (lig.would_apply (c))
return_trace (true);
}
return_trace (false);
}
inline bool apply (hb_apply_context_t *c) const
{
TRACE_APPLY (this);
unsigned int num_ligs = ligature.len;
for (unsigned int i = 0; i < num_ligs; i++)
{
const Ligature &lig = this+ligature[i];
if (lig.apply (c)) return_trace (true);
}
return_trace (false);
}
inline bool serialize (hb_serialize_context_t *c,
Supplier<GlyphID> &ligatures,
Supplier<unsigned int> &component_count_list,
unsigned int num_ligatures,
Supplier<GlyphID> &component_list /* Starting from second for each ligature */)
{
TRACE_SERIALIZE (this);
if (unlikely (!c->extend_min (*this))) return_trace (false);
if (unlikely (!ligature.serialize (c, num_ligatures))) return_trace (false);
for (unsigned int i = 0; i < num_ligatures; i++)
if (unlikely (!ligature[i].serialize (c, this).serialize (c,
ligatures[i],
component_list,
component_count_list[i]))) return_trace (false);
ligatures.advance (num_ligatures);
component_count_list.advance (num_ligatures);
return_trace (true);
}
inline bool sanitize (hb_sanitize_context_t *c) const
{
TRACE_SANITIZE (this);
return_trace (ligature.sanitize (c, this));
}
protected:
OffsetArrayOf<Ligature>
ligature; /* Array LigatureSet tables
* ordered by preference */
public:
DEFINE_SIZE_ARRAY (2, ligature);
};
struct LigatureSubstFormat1
{
inline void closure (hb_closure_context_t *c) const
{
TRACE_CLOSURE (this);
Coverage::Iter iter;
unsigned int count = ligatureSet.len;
for (iter.init (this+coverage); iter.more (); iter.next ())
{
if (unlikely (iter.get_coverage () >= count))
break; /* Work around malicious fonts. https://github.com/behdad/harfbuzz/issues/363 */
if (c->glyphs->has (iter.get_glyph ()))
(this+ligatureSet[iter.get_coverage ()]).closure (c);
}
}
inline void collect_glyphs (hb_collect_glyphs_context_t *c) const
{
TRACE_COLLECT_GLYPHS (this);
Coverage::Iter iter;
unsigned int count = ligatureSet.len;
for (iter.init (this+coverage); iter.more (); iter.next ())
{
if (unlikely (iter.get_coverage () >= count))
break; /* Work around malicious fonts. https://github.com/behdad/harfbuzz/issues/363 */
c->input->add (iter.get_glyph ());
(this+ligatureSet[iter.get_coverage ()]).collect_glyphs (c);
}
}
inline const Coverage &get_coverage (void) const
{
return this+coverage;
}
inline bool would_apply (hb_would_apply_context_t *c) const
{
TRACE_WOULD_APPLY (this);
unsigned int index = (this+coverage).get_coverage (c->glyphs[0]);
if (likely (index == NOT_COVERED)) return_trace (false);
const LigatureSet &lig_set = this+ligatureSet[index];
return_trace (lig_set.would_apply (c));
}
inline bool apply (hb_apply_context_t *c) const
{
TRACE_APPLY (this);
hb_codepoint_t glyph_id = c->buffer->cur().codepoint;
unsigned int index = (this+coverage).get_coverage (glyph_id);
if (likely (index == NOT_COVERED)) return_trace (false);
const LigatureSet &lig_set = this+ligatureSet[index];
return_trace (lig_set.apply (c));
}
inline bool serialize (hb_serialize_context_t *c,
Supplier<GlyphID> &first_glyphs,
Supplier<unsigned int> &ligature_per_first_glyph_count_list,
unsigned int num_first_glyphs,
Supplier<GlyphID> &ligatures_list,
Supplier<unsigned int> &component_count_list,
Supplier<GlyphID> &component_list /* Starting from second for each ligature */)
{
TRACE_SERIALIZE (this);
if (unlikely (!c->extend_min (*this))) return_trace (false);
if (unlikely (!ligatureSet.serialize (c, num_first_glyphs))) return_trace (false);
for (unsigned int i = 0; i < num_first_glyphs; i++)
if (unlikely (!ligatureSet[i].serialize (c, this).serialize (c,
ligatures_list,
component_count_list,
ligature_per_first_glyph_count_list[i],
component_list))) return_trace (false);
ligature_per_first_glyph_count_list.advance (num_first_glyphs);
if (unlikely (!coverage.serialize (c, this).serialize (c, first_glyphs, num_first_glyphs))) return_trace (false);
return_trace (true);
}
inline bool sanitize (hb_sanitize_context_t *c) const
{
TRACE_SANITIZE (this);
return_trace (coverage.sanitize (c, this) && ligatureSet.sanitize (c, this));
}
protected:
UINT16 format; /* Format identifier--format = 1 */
OffsetTo<Coverage>
coverage; /* Offset to Coverage table--from
* beginning of Substitution table */
OffsetArrayOf<LigatureSet>
ligatureSet; /* Array LigatureSet tables
* ordered by Coverage Index */
public:
DEFINE_SIZE_ARRAY (6, ligatureSet);
};
struct LigatureSubst
{
inline bool serialize (hb_serialize_context_t *c,
Supplier<GlyphID> &first_glyphs,
Supplier<unsigned int> &ligature_per_first_glyph_count_list,
unsigned int num_first_glyphs,
Supplier<GlyphID> &ligatures_list,
Supplier<unsigned int> &component_count_list,
Supplier<GlyphID> &component_list /* Starting from second for each ligature */)
{
TRACE_SERIALIZE (this);
if (unlikely (!c->extend_min (u.format))) return_trace (false);
unsigned int format = 1;
u.format.set (format);
switch (u.format) {
case 1: return_trace (u.format1.serialize (c,
first_glyphs,
ligature_per_first_glyph_count_list,
num_first_glyphs,
ligatures_list,
component_count_list,
component_list));
default:return_trace (false);
}
}
template <typename context_t>
inline typename context_t::return_t dispatch (context_t *c) const
{
TRACE_DISPATCH (this, u.format);
if (unlikely (!c->may_dispatch (this, &u.format))) return_trace (c->no_dispatch_return_value ());
switch (u.format) {
case 1: return_trace (c->dispatch (u.format1));
default:return_trace (c->default_return_value ());
}
}
protected:
union {
UINT16 format; /* Format identifier */
LigatureSubstFormat1 format1;
} u;
};
struct ContextSubst : Context {};
struct ChainContextSubst : ChainContext {};
struct ExtensionSubst : Extension<ExtensionSubst>
{
typedef struct SubstLookupSubTable LookupSubTable;
inline bool is_reverse (void) const;
};
struct ReverseChainSingleSubstFormat1
{
inline void closure (hb_closure_context_t *c) const
{
TRACE_CLOSURE (this);
const OffsetArrayOf<Coverage> &lookahead = StructAfter<OffsetArrayOf<Coverage> > (backtrack);
unsigned int count;
count = backtrack.len;
for (unsigned int i = 0; i < count; i++)
if (!(this+backtrack[i]).intersects (c->glyphs))
return;
count = lookahead.len;
for (unsigned int i = 0; i < count; i++)
if (!(this+lookahead[i]).intersects (c->glyphs))
return;
const ArrayOf<GlyphID> &substitute = StructAfter<ArrayOf<GlyphID> > (lookahead);
Coverage::Iter iter;
count = substitute.len;
for (iter.init (this+coverage); iter.more (); iter.next ())
{
if (unlikely (iter.get_coverage () >= count))
break; /* Work around malicious fonts. https://github.com/behdad/harfbuzz/issues/363 */
if (c->glyphs->has (iter.get_glyph ()))
c->glyphs->add (substitute[iter.get_coverage ()]);
}
}
inline void collect_glyphs (hb_collect_glyphs_context_t *c) const
{
TRACE_COLLECT_GLYPHS (this);
const OffsetArrayOf<Coverage> &lookahead = StructAfter<OffsetArrayOf<Coverage> > (backtrack);
unsigned int count;
(this+coverage).add_coverage (c->input);
count = backtrack.len;
for (unsigned int i = 0; i < count; i++)
(this+backtrack[i]).add_coverage (c->before);
count = lookahead.len;
for (unsigned int i = 0; i < count; i++)
(this+lookahead[i]).add_coverage (c->after);
const ArrayOf<GlyphID> &substitute = StructAfter<ArrayOf<GlyphID> > (lookahead);
count = substitute.len;
for (unsigned int i = 0; i < count; i++)
c->output->add (substitute[i]);
}
inline const Coverage &get_coverage (void) const
{
return this+coverage;
}
inline bool would_apply (hb_would_apply_context_t *c) const
{
TRACE_WOULD_APPLY (this);
return_trace (c->len == 1 && (this+coverage).get_coverage (c->glyphs[0]) != NOT_COVERED);
}
inline bool apply (hb_apply_context_t *c) const
{
TRACE_APPLY (this);
if (unlikely (c->nesting_level_left != HB_MAX_NESTING_LEVEL))
return_trace (false); /* No chaining to this type */
unsigned int index = (this+coverage).get_coverage (c->buffer->cur().codepoint);
if (likely (index == NOT_COVERED)) return_trace (false);
const OffsetArrayOf<Coverage> &lookahead = StructAfter<OffsetArrayOf<Coverage> > (backtrack);
const ArrayOf<GlyphID> &substitute = StructAfter<ArrayOf<GlyphID> > (lookahead);
unsigned int start_index = 0, end_index = 0;
if (match_backtrack (c,
backtrack.len, (UINT16 *) backtrack.array,
match_coverage, this,
&start_index) &&
match_lookahead (c,
lookahead.len, (UINT16 *) lookahead.array,
match_coverage, this,
1, &end_index))
{
c->buffer->unsafe_to_break_from_outbuffer (start_index, end_index);
c->replace_glyph_inplace (substitute[index]);
/* Note: We DON'T decrease buffer->idx. The main loop does it
* for us. This is useful for preventing surprises if someone
* calls us through a Context lookup. */
return_trace (true);
}
return_trace (false);
}
inline bool sanitize (hb_sanitize_context_t *c) const
{
TRACE_SANITIZE (this);
if (!(coverage.sanitize (c, this) && backtrack.sanitize (c, this)))
return_trace (false);
const OffsetArrayOf<Coverage> &lookahead = StructAfter<OffsetArrayOf<Coverage> > (backtrack);
if (!lookahead.sanitize (c, this))
return_trace (false);
const ArrayOf<GlyphID> &substitute = StructAfter<ArrayOf<GlyphID> > (lookahead);
return_trace (substitute.sanitize (c));
}
protected:
UINT16 format; /* Format identifier--format = 1 */
OffsetTo<Coverage>
coverage; /* Offset to Coverage table--from
* beginning of table */
OffsetArrayOf<Coverage>
backtrack; /* Array of coverage tables
* in backtracking sequence, in glyph
* sequence order */
OffsetArrayOf<Coverage>
lookaheadX; /* Array of coverage tables
* in lookahead sequence, in glyph
* sequence order */
ArrayOf<GlyphID>
substituteX; /* Array of substitute
* GlyphIDs--ordered by Coverage Index */
public:
DEFINE_SIZE_MIN (10);
};
struct ReverseChainSingleSubst
{
template <typename context_t>
inline typename context_t::return_t dispatch (context_t *c) const
{
TRACE_DISPATCH (this, u.format);
if (unlikely (!c->may_dispatch (this, &u.format))) return_trace (c->no_dispatch_return_value ());
switch (u.format) {
case 1: return_trace (c->dispatch (u.format1));
default:return_trace (c->default_return_value ());
}
}
protected:
union {
UINT16 format; /* Format identifier */
ReverseChainSingleSubstFormat1 format1;
} u;
};
/*
* SubstLookup
*/
struct SubstLookupSubTable
{
friend struct SubstLookup;
enum Type {
Single = 1,
Multiple = 2,
Alternate = 3,
Ligature = 4,
Context = 5,
ChainContext = 6,
Extension = 7,
ReverseChainSingle = 8
};
template <typename context_t>
inline typename context_t::return_t dispatch (context_t *c, unsigned int lookup_type) const
{
TRACE_DISPATCH (this, lookup_type);
if (unlikely (!c->may_dispatch (this, &u.sub_format))) return_trace (c->no_dispatch_return_value ());
switch (lookup_type) {
case Single: return_trace (u.single.dispatch (c));
case Multiple: return_trace (u.multiple.dispatch (c));
case Alternate: return_trace (u.alternate.dispatch (c));
case Ligature: return_trace (u.ligature.dispatch (c));
case Context: return_trace (u.context.dispatch (c));
case ChainContext: return_trace (u.chainContext.dispatch (c));
case Extension: return_trace (u.extension.dispatch (c));
case ReverseChainSingle: return_trace (u.reverseChainContextSingle.dispatch (c));
default: return_trace (c->default_return_value ());
}
}
protected:
union {
UINT16 sub_format;
SingleSubst single;
MultipleSubst multiple;
AlternateSubst alternate;
LigatureSubst ligature;
ContextSubst context;
ChainContextSubst chainContext;
ExtensionSubst extension;
ReverseChainSingleSubst reverseChainContextSingle;
} u;
public:
DEFINE_SIZE_UNION (2, sub_format);
};
struct SubstLookup : Lookup
{
inline const SubstLookupSubTable& get_subtable (unsigned int i) const
{ return Lookup::get_subtable<SubstLookupSubTable> (i); }
inline static bool lookup_type_is_reverse (unsigned int lookup_type)
{ return lookup_type == SubstLookupSubTable::ReverseChainSingle; }
inline bool is_reverse (void) const
{
unsigned int type = get_type ();
if (unlikely (type == SubstLookupSubTable::Extension))
return CastR<ExtensionSubst> (get_subtable(0)).is_reverse ();
return lookup_type_is_reverse (type);
}
inline bool apply (hb_apply_context_t *c) const
{
TRACE_APPLY (this);
return_trace (dispatch (c));
}
inline hb_closure_context_t::return_t closure (hb_closure_context_t *c) const
{
TRACE_CLOSURE (this);
c->set_recurse_func (dispatch_recurse_func<hb_closure_context_t>);
return_trace (dispatch (c));
}
inline hb_collect_glyphs_context_t::return_t collect_glyphs (hb_collect_glyphs_context_t *c) const
{
TRACE_COLLECT_GLYPHS (this);
c->set_recurse_func (dispatch_recurse_func<hb_collect_glyphs_context_t>);
return_trace (dispatch (c));
}
template <typename set_t>
inline void add_coverage (set_t *glyphs) const
{
hb_add_coverage_context_t<set_t> c (glyphs);
dispatch (&c);
}
inline bool would_apply (hb_would_apply_context_t *c,
const hb_ot_layout_lookup_accelerator_t *accel) const
{
TRACE_WOULD_APPLY (this);
if (unlikely (!c->len)) return_trace (false);
if (!accel->may_have (c->glyphs[0])) return_trace (false);
return_trace (dispatch (c));
}
static bool apply_recurse_func (hb_apply_context_t *c, unsigned int lookup_index);
inline SubstLookupSubTable& serialize_subtable (hb_serialize_context_t *c,
unsigned int i)
{ return get_subtables<SubstLookupSubTable> ()[i].serialize (c, this); }
inline bool serialize_single (hb_serialize_context_t *c,
uint32_t lookup_props,
Supplier<GlyphID> &glyphs,
Supplier<GlyphID> &substitutes,
unsigned int num_glyphs)
{
TRACE_SERIALIZE (this);
if (unlikely (!Lookup::serialize (c, SubstLookupSubTable::Single, lookup_props, 1))) return_trace (false);
return_trace (serialize_subtable (c, 0).u.single.serialize (c, glyphs, substitutes, num_glyphs));
}
inline bool serialize_multiple (hb_serialize_context_t *c,
uint32_t lookup_props,
Supplier<GlyphID> &glyphs,
Supplier<unsigned int> &substitute_len_list,
unsigned int num_glyphs,
Supplier<GlyphID> &substitute_glyphs_list)
{
TRACE_SERIALIZE (this);
if (unlikely (!Lookup::serialize (c, SubstLookupSubTable::Multiple, lookup_props, 1))) return_trace (false);
return_trace (serialize_subtable (c, 0).u.multiple.serialize (c,
glyphs,
substitute_len_list,
num_glyphs,
substitute_glyphs_list));
}
inline bool serialize_alternate (hb_serialize_context_t *c,
uint32_t lookup_props,
Supplier<GlyphID> &glyphs,
Supplier<unsigned int> &alternate_len_list,
unsigned int num_glyphs,
Supplier<GlyphID> &alternate_glyphs_list)
{
TRACE_SERIALIZE (this);
if (unlikely (!Lookup::serialize (c, SubstLookupSubTable::Alternate, lookup_props, 1))) return_trace (false);
return_trace (serialize_subtable (c, 0).u.alternate.serialize (c,
glyphs,
alternate_len_list,
num_glyphs,
alternate_glyphs_list));
}
inline bool serialize_ligature (hb_serialize_context_t *c,
uint32_t lookup_props,
Supplier<GlyphID> &first_glyphs,
Supplier<unsigned int> &ligature_per_first_glyph_count_list,
unsigned int num_first_glyphs,
Supplier<GlyphID> &ligatures_list,
Supplier<unsigned int> &component_count_list,
Supplier<GlyphID> &component_list /* Starting from second for each ligature */)
{
TRACE_SERIALIZE (this);
if (unlikely (!Lookup::serialize (c, SubstLookupSubTable::Ligature, lookup_props, 1))) return_trace (false);
return_trace (serialize_subtable (c, 0).u.ligature.serialize (c,
first_glyphs,
ligature_per_first_glyph_count_list,
num_first_glyphs,
ligatures_list,
component_count_list,
component_list));
}
template <typename context_t>
static inline typename context_t::return_t dispatch_recurse_func (context_t *c, unsigned int lookup_index);
template <typename context_t>
inline typename context_t::return_t dispatch (context_t *c) const
{ return Lookup::dispatch<SubstLookupSubTable> (c); }
inline bool sanitize (hb_sanitize_context_t *c) const
{
TRACE_SANITIZE (this);
if (unlikely (!Lookup::sanitize (c))) return_trace (false);
if (unlikely (!dispatch (c))) return_trace (false);
if (unlikely (get_type () == SubstLookupSubTable::Extension))
{
/* The spec says all subtables of an Extension lookup should
* have the same type. This is specially important if one has
* a reverse type! */
unsigned int type = get_subtable (0).u.extension.get_type ();
unsigned int count = get_subtable_count ();
for (unsigned int i = 1; i < count; i++)
if (get_subtable (i).u.extension.get_type () != type)
return_trace (false);
}
return_trace (true);
}
};
typedef OffsetListOf<SubstLookup> SubstLookupList;
/*
* GSUB -- The Glyph Substitution Table
*/
struct GSUB : GSUBGPOS
{
static const hb_tag_t tableTag = HB_OT_TAG_GSUB;
inline const SubstLookup& get_lookup (unsigned int i) const
{ return CastR<SubstLookup> (GSUBGPOS::get_lookup (i)); }
static inline void substitute_start (hb_font_t *font, hb_buffer_t *buffer);
inline bool sanitize (hb_sanitize_context_t *c) const
{
TRACE_SANITIZE (this);
if (unlikely (!GSUBGPOS::sanitize (c))) return_trace (false);
const OffsetTo<SubstLookupList> &list = CastR<OffsetTo<SubstLookupList> > (lookupList);
return_trace (list.sanitize (c, this));
}
};
void
GSUB::substitute_start (hb_font_t *font, hb_buffer_t *buffer)
{
_hb_buffer_assert_gsubgpos_vars (buffer);
const GDEF &gdef = *hb_ot_layout_from_face (font->face)->gdef;
unsigned int count = buffer->len;
for (unsigned int i = 0; i < count; i++)
{
_hb_glyph_info_set_glyph_props (&buffer->info[i], gdef.get_glyph_props (buffer->info[i].codepoint));
_hb_glyph_info_clear_lig_props (&buffer->info[i]);
buffer->info[i].syllable() = 0;
}
}
/* Out-of-class implementation for methods recursing */
/*static*/ inline bool ExtensionSubst::is_reverse (void) const
{
unsigned int type = get_type ();
if (unlikely (type == SubstLookupSubTable::Extension))
return CastR<ExtensionSubst> (get_subtable<LookupSubTable>()).is_reverse ();
return SubstLookup::lookup_type_is_reverse (type);
}
template <typename context_t>
/*static*/ inline typename context_t::return_t SubstLookup::dispatch_recurse_func (context_t *c, unsigned int lookup_index)
{
const GSUB &gsub = *(hb_ot_layout_from_face (c->face)->gsub);
const SubstLookup &l = gsub.get_lookup (lookup_index);
return l.dispatch (c);
}
/*static*/ inline bool SubstLookup::apply_recurse_func (hb_apply_context_t *c, unsigned int lookup_index)
{
const GSUB &gsub = *(hb_ot_layout_from_face (c->face)->gsub);
const SubstLookup &l = gsub.get_lookup (lookup_index);
unsigned int saved_lookup_props = c->lookup_props;
unsigned int saved_lookup_index = c->lookup_index;
c->set_lookup_index (lookup_index);
c->set_lookup_props (l.get_props ());
bool ret = l.dispatch (c);
c->set_lookup_index (saved_lookup_index);
c->set_lookup_props (saved_lookup_props);
return ret;
}
} /* namespace OT */
#endif /* HB_OT_LAYOUT_GSUB_TABLE_HH */
| [
"behdad@behdad.org"
] | behdad@behdad.org |
f0ad7c99b2bf56a9399b62676cae037be0488522 | 1bfd698b2c1f5760734dc42632fe54c65a286086 | /IfcPlusPlus/src/ifcpp/IFC4/include/IfcPropertySetDefinitionSet.h | c2d6acea2e531b2bdcf328ae0684a26c562ebedd | [] | no_license | wartburgritter0/old_IfcPlusPlus | c0bd0b784396c100d0d96fc7af6146a0325a9e1b | d0f9d81462b295990d3eb83c9c406d520840330e | refs/heads/master | 2021-05-27T21:54:14.456425 | 2014-06-03T21:23:14 | 2014-06-03T21:23:14 | 19,681,159 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,523 | h | /* -*-c++-*- IfcPlusPlus - www.ifcplusplus.com - Copyright (C) 2011 Fabian Gerold
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library 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
* OpenSceneGraph Public License for more details.
*/
#pragma once
#include <vector>
#include <map>
#include <sstream>
#include <string>
#include "ifcpp/model/shared_ptr.h"
#include "ifcpp/model/IfcPPObject.h"
#include "IfcPropertySetDefinitionSelect.h"
class IfcPropertySetDefinition;
// TYPE IfcPropertySetDefinitionSet = SET [1:?] OF IfcPropertySetDefinition;
class IfcPropertySetDefinitionSet : public IfcPropertySetDefinitionSelect
{
public:
IfcPropertySetDefinitionSet();
~IfcPropertySetDefinitionSet();
virtual const char* classname() const { return "IfcPropertySetDefinitionSet"; }
virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const;
static shared_ptr<IfcPropertySetDefinitionSet> createObjectFromStepData( const std::string& arg, const std::map<int,shared_ptr<IfcPPEntity> >& map );
std::vector<shared_ptr<IfcPropertySetDefinition> > m_vec;
};
| [
"fabian.gerold@gmail.com@06f6d6f3-f2e0-f239-6e86-ba6a5d17d3a5"
] | fabian.gerold@gmail.com@06f6d6f3-f2e0-f239-6e86-ba6a5d17d3a5 |
eb0c143b3f9a72473c1ec9a36ccfc046be63ebe7 | 48d45a6f9a36d4bc9429bf6c87dd41a4ce0932f7 | /ctranspiler.cpp | e23dc14faa42e202a563208099193b9bcf912733 | [] | no_license | nishanthkarthik/smartprixlang | 2ab1f295ca13073615854b754fa7ded3476aae0e | a9c3c4069574191c0ba388ee5a45c781710c44cd | refs/heads/master | 2021-05-06T05:05:15.887884 | 2017-12-27T07:41:59 | 2017-12-27T07:41:59 | 115,042,033 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,637 | cpp | #include "ctranspiler.h"
Transpiler::Transpiler(ostream* o, vector<Instruction>& ins)
: Emitter(o, ins)
{
c_map.emplace("EXIT", &Transpiler::transpile_c_exit);
c_map.emplace("ENDIF", &Transpiler::transpile_c_endif);
c_map.emplace("ECHO", &Transpiler::transpile_c_echo);
c_map.emplace("GOTO", &Transpiler::transpile_c_goto);
c_map.emplace("LABEL", &Transpiler::transpile_c_label);
c_map.emplace("SET", &Transpiler::transpile_c_set);
c_map.emplace("ADD", &Transpiler::transpile_c_add);
c_map.emplace("SUB", &Transpiler::transpile_c_sub);
c_map.emplace("MUL", &Transpiler::transpile_c_mul);
c_map.emplace("DIV", &Transpiler::transpile_c_div);
c_map.emplace("IF", &Transpiler::transpile_c_if);
is_arglen_valid();
parse_names();
}
void Transpiler::transpile_c()
{
emit("#include <stdlib.h>");
emit("#include <stdio.h>");
emit("int main() {");
for (auto it = varnames.begin(); it != varnames.end(); ++it)
emit("int " + *it + ";");
for (Instruction& i : insvec) {
string cmd = i.get_cmd();
if (c_map.find(cmd) != c_map.end()) {
memfuncptr m = c_map.at(cmd);
(this->*m)(i);
}
}
emit("return 0;");
emit("}");
}
void Transpiler::transpile_c_exit(Instruction& i)
{
emit("exit(0);");
}
void Transpiler::transpile_c_endif(Instruction& i)
{
emit("}");
}
void Transpiler::transpile_c_echo(Instruction& i)
{
emit("printf(\"%d\\n\", " + i.arg_at(0).get_name() + ");");
}
void Transpiler::transpile_c_goto(Instruction& i)
{
emit("goto " + i.arg_at(0).get_name() + ";");
}
void Transpiler::transpile_c_label(Instruction& i)
{
emit(i.arg_at(0).get_name() + ":");
}
void Transpiler::transpile_c_set(Instruction& i)
{
emit(i.arg_at(0).get_name() + " = " + i.arg_at(1).get_name() + ";");
}
void Transpiler::transpile_c_add(Instruction& i)
{
emit(i.arg_at(0).get_name() + " = " + i.arg_at(1).get_name() + " + " + i.arg_at(2).get_name() + ";");
}
void Transpiler::transpile_c_sub(Instruction& i)
{
emit(i.arg_at(0).get_name() + " = " + i.arg_at(1).get_name() + " - " + i.arg_at(2).get_name() + ";");
}
void Transpiler::transpile_c_mul(Instruction& i)
{
emit(i.arg_at(0).get_name() + " = " + i.arg_at(1).get_name() + " * " + i.arg_at(2).get_name() + ";");
}
void Transpiler::transpile_c_div(Instruction& i)
{
emit(i.arg_at(0).get_name() + " = " + i.arg_at(1).get_name() + " / " + i.arg_at(2).get_name() + ";");
}
void Transpiler::transpile_c_if(Instruction& i)
{
emit("if (" + i.arg_at(0).get_name() + i.arg_at(1).get_name() + i.arg_at(2).get_name() + ") {");
}
| [
"nishanthkarthik@live.com"
] | nishanthkarthik@live.com |
88a407870e9d9b4f26f7e375b9bcf1de8a295f7e | c82f01f6618c9d533719db1eb182ba6680eada28 | /2014-2015/hafiza_workspace/control_panel/src/widgets/imu_display.cpp | 77ba0762c6bb78102f79f5338193ec508c7f3c40 | [] | no_license | hajungong007/landingpad | e561fec000e42a54842450b311fd77b453cfebbe | c33e3ace8504290a6c8bafb7d6ebc7db0fc92525 | refs/heads/master | 2020-07-26T20:30:55.116505 | 2016-04-29T04:48:01 | 2016-04-29T04:48:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,760 | cpp | /*
* Copyright (c) 2011, 2012 Matt Richard, Scott K Logan.
* 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 Willow Garage, Inc. 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.
*/
/**
* \file imu_display.cpp
* \date Jan 19, 2012
* \author Matt Richard
*/
#include <QtGui>
#include "control_panel/widgets/imu_display.h"
ImuDisplay::ImuDisplay(QWidget *parent) : QWidget(parent)
{
imu_name = "IMU";
use_roll = true;
use_pitch = true;
use_yaw = true;
use_ang_vel = true;
use_lin_accel = true;
use_attitude_ind = true;
use_heading_ind = true;
createWidget();
}
ImuDisplay::ImuDisplay(const QString &name, bool show_roll, bool show_pitch,
bool show_yaw, bool show_ang_vel, bool show_lin_accel, bool show_attitude,
bool show_heading, QWidget *parent) : QWidget(parent)
{
if(name == "")
imu_name = "IMU";
else
imu_name = name;
use_roll = show_roll;
use_pitch = show_pitch;
use_yaw = show_yaw;
use_ang_vel = show_ang_vel;
use_lin_accel = show_lin_accel;
use_attitude_ind = show_attitude;
use_heading_ind = show_heading;
createWidget();
}
void ImuDisplay::createWidget()
{
int rows = 0;
// Zero all values
zeroValues();
widget_layout = new QHBoxLayout;
// Create attitude widget
if(use_attitude_ind)
{
attitude = new AttitudeIndicator;
//widget_layout->addStretch();
widget_layout->addWidget(attitude);//, 0, Qt::AlignLeft);
}
// Create heading widget
if(use_heading_ind)
{
heading = new HeadingIndicator;
widget_layout->addStretch();
widget_layout->addWidget(heading);
}
// use a grid layout for the labels
QGridLayout *data_gridlayout = new QGridLayout;
data_gridlayout->setSpacing(0);
// Create header if any labels will be displayed
if(use_roll || use_pitch || use_yaw || use_ang_vel || use_lin_accel)
{
name_label = new QLabel(imu_name);
data_gridlayout->addWidget(name_label, 0, 0, 1, 0, Qt::AlignHCenter);
rows++;
data_gridlayout->setColumnMinimumWidth(1, 100);
}
// Create roll labels
if(use_roll)
{
QLabel *roll_str = new QLabel("Roll: ");
roll_label = new QLabel;
data_gridlayout->addWidget(roll_str, rows, 0, Qt::AlignLeft);
data_gridlayout->addWidget(roll_label, rows, 1, Qt::AlignRight);
rows++;
}
// Create pitch labels
if(use_pitch)
{
QLabel *pitch_str = new QLabel("Pitch: ");
pitch_label = new QLabel;
data_gridlayout->addWidget(pitch_str, rows, 0, Qt::AlignLeft);
data_gridlayout->addWidget(pitch_label, rows, 1, Qt::AlignRight);
rows++;
}
// Create yaw labels
if(use_yaw)
{
QLabel *yaw_str = new QLabel("Yaw: ");
yaw_label = new QLabel;
data_gridlayout->addWidget(yaw_str, rows, 0, Qt::AlignLeft);
data_gridlayout->addWidget(yaw_label, rows, 1, Qt::AlignRight);
rows++;
}
// Create angular velocity labels and add to grid layout
if(use_ang_vel)
{
QLabel *ang_vel_str = new QLabel("Ang Vel: ");
ang_vel_label = new QLabel;
data_gridlayout->addWidget(ang_vel_str, rows, 0, Qt::AlignLeft);
data_gridlayout->addWidget(ang_vel_label, rows, 1, Qt::AlignRight);
rows++;
}
// Create linear acceleration labels and add to grid layout
if(use_lin_accel)
{
QLabel *lin_accel_str = new QLabel("Lin Accel: ");
lin_accel_label = new QLabel;
data_gridlayout->addWidget(lin_accel_str, rows, 0, Qt::AlignLeft);
data_gridlayout->addWidget(lin_accel_label, rows, 1, Qt::AlignRight);
rows++;
}
// Add the grid layout to the final layout
widget_layout->addStretch();
widget_layout->addLayout(data_gridlayout);
widget_layout->addStretch();
// set the layout
setLayout(widget_layout);
}
void ImuDisplay::zeroValues()
{
roll = 0.0;
pitch = 0.0;
yaw = 0.0;
angular_velocity.setX(0.0);
angular_velocity.setY(0.0);
angular_velocity.setZ(0.0);
linear_acceleration.setX(0.0);
linear_acceleration.setY(0.0);
linear_acceleration.setZ(0.0);
}
/*
void ImuDisplay::updateImuDisplay(const QQuaternion &orientation, double ori_covar[9],
const QVector3D &ang_vel, double ang_vel_covar[9],
const QVector3D &lin_accel, double lin_accel_covar[9])
{
}
*/
void ImuDisplay::updateImuDisplay(const QQuaternion &orientation)
{
double x = orientation.x();
double y = orientation.y();
double z = orientation.z();
double w = orientation.scalar();
// Calculate roll, pitch, and yaw from the quaternion
roll = atan2(2.0 * (y*z + w*x), w*w - x*x - y*y + z*z) * Globals::RAD_TO_DEG;
//roll = atan2(2.0 * (w*x + y*z), 1.0 - 2.0 * (x*x + y*y)) * Globals::RAD_TO_DEG;
pitch = asin(-2.0 * (x*z - w*y)) * Globals::RAD_TO_DEG;
//pitch = asin(2.0 * (w*y - z*x)) * Globals::RAD_TO_DEG;
yaw = atan2(2.0 * (x*y + w*z), w*w + x*x - y*y - z*z) * Globals::RAD_TO_DEG;
//yaw = atan2(2.0 * (w*z + x*y), 1.0 - 2.0 * (y*y + z*z)) * Globals::RAD_TO_DEG;
// Display roll, pitch, and yaw in integer value
if(use_roll)
roll_label->setText(QString("%1").arg((int)roll, 4, 10) + Globals::DegreesSymbol);
if(use_pitch)
pitch_label->setText(QString("%1").arg((int)pitch, 4, 10) + Globals::DegreesSymbol);
if(use_yaw)
yaw_label->setText(QString("%1").arg((int)yaw, 4, 10) + Globals::DegreesSymbol);
// Update the attitude indicator
if(use_attitude_ind)
attitude->setAttitude(roll, pitch);
// Update the heading indicator
if(use_heading_ind)
heading->setYaw(yaw);
}
void ImuDisplay::updateImuDisplay(const QQuaternion &orientation,
const QVector3D &ang_vel, const QVector3D &lin_accel)
{
updateImuDisplay(orientation);
angular_velocity = ang_vel;
linear_acceleration = lin_accel;
// Display angular velocity
if(use_ang_vel)
ang_vel_label->setText(QString("%1").arg(ang_vel.length(), 6, 'f', 1) + QString(" rad/s"));
// Display linear acceleratrion
if(use_lin_accel)
lin_accel_label->setText(QString("%1").arg(lin_accel.length(), 6, 'f', 1) + QString(" m/s^2"));
}
| [
"larry.pyeatt@sdsmt.edu"
] | larry.pyeatt@sdsmt.edu |
d95c3cb4f830584e0233d564000cd97cf524f484 | e2d7d5f206fbab246f93517b0d0c2b210cd8f3ad | /BFS-DFS/4963_island.cpp.cpp | bafb89687b2af39459d3e3283f6eeeae207667bf | [] | no_license | RuachKim/Algorithm_Practice | db5a709664f11e6ca93caae7d3de25f08c107702 | ff705a85f69de8b01a0f599ad1cbd780524fc354 | refs/heads/master | 2021-06-24T22:17:00.240171 | 2020-11-24T05:58:33 | 2020-11-24T05:58:33 | 176,079,402 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,305 | cpp | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int w,h;
int map[52][52];
int visit[52][52];
int dx[8] = {-1,1,0,0,1,-1,1,-1};
int dy[8] = {0,0,-1,1,1,-1,-1,1};
int cnt = 0;
void dfs(int x, int y){
visit[x][y] = 1;
for( int k = 0; k < 8; k++ ){
int nx = x+dx[k];
int ny = y+dy[k];
if( nx >= 0 && nx < h && ny >= 0 && ny < w ){
if(!visit[nx][ny] && map[nx][ny] == 1) dfs(nx,ny);
}
}
}
int main() {
// your code goes here
while(1){
cin >> w >> h;
if( w == 0 && h == 0)return 0;
// renew map
for( int i = 0; i < h; i++ ){
for( int j = 0; j < w; j++ )
cin >> map[i][j];
}
// visit array clear
for( int i = 0; i < h; i++ ){
for( int j = 0; j < w; j++ )
visit[i][j] = 0;
}
for( int i = 0; i < h; i++ ){
for( int j = 0; j < w; j++ ){
if( !visit[i][j] && map[i][j] == 1){
dfs(i,j);
cnt++;
}
}
}
cout << cnt << endl;
cnt = 0;
}
return 0;
}
| [
"henrykbieno@gmail.com"
] | henrykbieno@gmail.com |
92c2b23e997afccd48e6add91186af92a8efc7c2 | 9242cd141c8979963bc269a913a8f862d5cd1d68 | /FriendFace/logger.h | 3420488036b22cf0ccf25bc3df5e0b4702717747 | [] | no_license | fk-lx/FriendFace | 769ef8affee041611749c49e3e9c3d4594d9a568 | 6ed5443ac4c3946c298656ee4cf83530059ea7b4 | refs/heads/master | 2020-12-26T01:12:55.929293 | 2014-02-07T17:06:18 | 2014-02-07T17:06:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 353 | h | #ifndef LOGGER_H
#define LOGGER_H
#include <QListWidget>
#include <QString>
using namespace std;
class Logger
{
public:
void log(const QString& msg);
static Logger& getInstance();
void setLogWidget(QListWidget* logWidget);
protected:
Logger();
private:
QListWidget* logWidget;
static Logger instance;
};
#endif // LOGGER_H
| [
"mister.shelp@gmail.com"
] | mister.shelp@gmail.com |
35be35baf50eaed63c0f454e21d715afa07be1e6 | 76aa089b62d177ba85eb3d993e3e05d0af656c4f | /GeoCuts_Radius.cc | 2dc8a29c06381441f1271091ead84c3ca1d4344c | [] | no_license | sdporzioAtMicroBooNE/Gallery_Example | b1727a79a790d99833315d869cf09a71e551e71b | a2475c22100536fef5101a880fc7103cfea9481c | refs/heads/master | 2021-01-22T12:37:37.815251 | 2017-09-04T11:01:49 | 2017-09-04T11:01:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,649 | cc | #include "GeoCuts_Radius.h"
int main(int argc, char** argv){
// Settings
bool primaryOnly, endVerticesAlso;
char* inFilename = argv[1];
char* outFilename = argv[2];
double dCut = atof(argv[3]);
std::stringstream ss4(argv[4]);
ss4 >> std::boolalpha >> primaryOnly;
std::stringstream ss5(argv[5]);
ss5 >> std::boolalpha >> endVerticesAlso;
std::string anaType(argv[6]);
std::cout << "Using following settings:" << std::endl;
std::cout << "Input Filename: " << inFilename << std::endl;
std::cout << "Output Filename: " << outFilename << std::endl;
std::cout << "Distance cut: " << dCut << std::endl;
std::cout << "PrimaryOnly: " << std::boolalpha << primaryOnly << std::endl;
std::cout << "EndVerticesAlso: " << std::boolalpha << endVerticesAlso << std::endl;
std::cout << "AnalysisType: " << anaType << std::endl;
TString trackProducer("pandoraNu");
TString pfpProducer("pandoraNu");
// Initialize variables that will go in the tree
Int_t event, nTracks, nShowers, nPairs, nTrackVertices, nShowerVertices, nPotVertices, nCleanVertices, pandora_nPrimaryVertices, pandora_nCleanVertices;
std::vector<float> pairDistance, potPairDistance;
std::vector<int> pandora_primaryVertexPDG, pandora_nDaughters, pandora_nTracks, pandora_nShowers, pandora_nNearTracks, pandora_nNearShowers;
// Generate root file and tree
TFile tFile(outFilename, "RECREATE");
TTree *tTree = new TTree("Data","Data");
TTree *metaTree = new TTree("MetaData","MetaData");
metaTree->Branch("distanceCut",&dCut,"dCut/D");
metaTree->Branch("primaryOnly",&primaryOnly,"primaryOnly/O");
metaTree->Branch("endVerticesAlso",&endVerticesAlso,"endVerticesAlso/O");
metaTree->Branch("anaType",&anaType);
tTree->Branch("event",&event,"event/I");
tTree->Branch("nTracks",&nTracks,"nTracks/I");
tTree->Branch("nShowers",&nShowers,"nShowers/I");
tTree->Branch("pairDistance",&pairDistance);
tTree->Branch("nPairs",&nPairs,"nPairs/I");
tTree->Branch("nTrackVertices",&nTrackVertices,"nTrackVertices/I");
tTree->Branch("nShowerVertices",&nShowerVertices,"nShowerVertices/I");
tTree->Branch("potPairDistance",&potPairDistance);
tTree->Branch("nPotVertices",&nPotVertices,"nPotVertices/I");
tTree->Branch("nCleanVertices",&nCleanVertices,"nCleanVertices/I");
tTree->Branch("pandora_nPrimaryVertices",&pandora_nPrimaryVertices,"pandora_nPrimaryVertices/I");
tTree->Branch("pandora_primaryVertexPDG",&pandora_primaryVertexPDG);
tTree->Branch("pandora_nDaughters",&pandora_nDaughters);
tTree->Branch("pandora_nTracks",&pandora_nTracks);
tTree->Branch("pandora_nShowers",&pandora_nShowers);
tTree->Branch("pandora_nNearTracks",&pandora_nNearTracks);
tTree->Branch("pandora_nNearShowers",&pandora_nNearShowers);
tTree->Branch("pandora_nCleanVertices",&pandora_nCleanVertices,"pandora_nCleanVertices/I");
// Set producer labels
art::InputTag trackTag {trackProducer};
art::InputTag pfpTag {pfpProducer};
// Read file paths from .txt file
std::vector<std::string> filenames;
std::string file_name;
std::ifstream input_file(inFilename);
while (getline(input_file,file_name)) filenames.push_back(file_name);
// Begin event loop
for (gallery::Event ev(filenames); !ev.atEnd(); ev.next()){
//----- STEP 1 -----//
// Initialize. Get data to arrays //
// Event information
const auto& aux = ev.eventAuxiliary();
const auto& event_n = aux.id().event();
// Get PFParticles handle
const auto& pfpHandle = ev.getValidHandle< std::vector<recob::PFParticle> >(pfpTag);
// Find associations from PFP to tracks and showers
art::FindMany<recob::Track> pfp_to_track_assns(pfpHandle,ev,trackTag);
art::FindMany<recob::Shower> pfp_to_shower_assns(pfpHandle,ev,trackTag);
// Prepare track and shower vectors
std::vector<recob::Track const*> tracks;
std::vector<recob::Shower const*> showers;
std::vector<recob::PFParticle> pandora_primaryPFP;
std::vector<DecayVertex> trackVertices;
std::vector<DecayVertex> showerVertices;
// Cleaning vectors before starting loop
pairDistance.clear();
potPairDistance.clear();
// Loop through each PFP
int index = 0;
for (auto const& pfp : (*pfpHandle)){
// Generate temporary vectors to contain objects associated with pfp
std::vector<recob::Track const*> tempTrackVector;
std::vector<recob::Shower const*> tempShowerVector;
// Fill temporary vectors with objects associated with the pfp
pfp_to_track_assns.get(index,tempTrackVector);
pfp_to_shower_assns.get(index,tempShowerVector);
// Group all the primaries to analyze them later
if (pfp.IsPrimary()){
pandora_primaryPFP.push_back(pfp);
}
// Ignore (unphysical) reconstructed parents
// (e.g. "ghost" neutrinos created by PandoraNu)
else {
// Find current pfp parent and check if parent is primary (so that pfp are only secondaries, and not tertiaries, etc.), then fill the correspondending vector with the type of particle found
// tempTrackVector, tempShowerVector should always contain only ONE element; that exact track or shower (which is why .at(0)). No idea why it's a vector.
if (primaryOnly){
auto const& parent = (*pfpHandle).at(pfp.Parent());
if (parent.IsPrimary()){
if (tempTrackVector.size()!=0) tracks.push_back(tempTrackVector.at(0));
if (tempShowerVector.size()!=0) showers.push_back(tempShowerVector.at(0));
}
}
// Fill the track and shower vectors with the products associated with the pfp (in any case, regardless of their "genealogy")
else {
if (tempTrackVector.size()!=0) tracks.push_back(tempTrackVector.at(0));
if (tempShowerVector.size()!=0) showers.push_back(tempShowerVector.at(0));
}
index++; // Index loops through pfps and MUST always keep on (no ifs)
}
} // End of pfp loop
// Fill vertices vectors taking all the start and end points for tracks and start points for showers. The last two numbers (j,j) indicate only their idx in the xxxVertices vector (which is reduntant at this stage). However, later on, it will be used to identify the vertices uniquely, and the idxs from two vertices will be used to define the parent idx of the mean vertex created between them.
// For tracks
int j = 0;
for(std::vector<int>::size_type i=0; i!=tracks.size(); i++){
DecayVertex tempV1(tracks[i]->Vertex().X(),tracks[i]->Vertex().Y(),tracks[i]->Vertex().Z(),j,j);
trackVertices.push_back(tempV1);
j++;
if (endVerticesAlso){
DecayVertex tempV2(tracks[i]->End().X(),tracks[i]->End().Y(),tracks[i]->End().Z(),j,j);
trackVertices.push_back(tempV2);
j++;
}
}
// And for showers
for(std::vector<int>::size_type i=0; i!=showers.size(); i++){
DecayVertex tempV(showers[i]->ShowerStart().X(),showers[i]->ShowerStart().Y(),showers[i]->ShowerStart().Z(),i,i);
showerVertices.push_back(tempV);
}
//----- STEP 2a -----//
//----- SDP ANALYSIS -----//
// Analyze. Use arrays to get metadata //
std::vector<DecayVertex> potVertices;
std::vector<DecayVertex> cleanVertices;
// Determine all potential mean vertices that satisfy the cut. Now the previously used (j,j) index are used to define the parent vertices that originated the mean vertex.
// For track-track
if (anaType == "tt"){
for(std::vector<int>::size_type i=0; i!=trackVertices.size(); i++){
for(std::vector<int>::size_type j=i+1; j!=trackVertices.size(); j++){
DecayVertex v1 = trackVertices[i];
DecayVertex v2 = trackVertices[j];
float distance = Distance(v1,v2);
pairDistance.push_back(distance);
bool isInRadius = (distance<dCut);
if (isInRadius) {
DecayVertex v3 = MeanVertex(v1, v2);
potVertices.push_back(v3);
potPairDistance.push_back(distance);
}
}
}
// Make sure the potential mean vertices are clean (two decay vertices only in radius)
// (start with assumption that isGoodVertex == true, then if you find extra particles in radius, turn it in bad vertex. Only good vertices are saved)
for(std::vector<int>::size_type i=0; i!=potVertices.size(); i++){
DecayVertex mv = potVertices[i];
bool isGoodVertex = true;
for(std::vector<int>::size_type j=0; j!=trackVertices.size(); j++){
DecayVertex v1 = trackVertices[j];
bool isParent1 = (mv.PID1() == v1.PID1());
bool isParent2 = (mv.PID2() == v1.PID2());
bool notParent = !(isParent1 || isParent2);
bool isInRadius = (Distance(mv,v1)<dCut);
if (isInRadius && notParent) isGoodVertex = false;
}
if (isGoodVertex) cleanVertices.push_back(mv);
}
}
// And for track-shower
else if (anaType == "ts"){
for(std::vector<int>::size_type i=0; i!=trackVertices.size(); i++){
for(std::vector<int>::size_type j=0; j!=showerVertices.size(); j++){
DecayVertex v1 = trackVertices[i];
DecayVertex v2 = showerVertices[j];
float distance = Distance(v1,v2);
pairDistance.push_back(distance);
bool isInRadius = (distance<dCut);
if (isInRadius) {
DecayVertex v3 = MeanVertex(v1, v2);
potVertices.push_back(v3);
potPairDistance.push_back(distance);
}
}
}
// Make sure the potential mean vertices are clean (two decay vertices only in radius)
// (start with assumption that isGoodVertex == true, then if you find extra particles in radius, turn it in bad vertex. Only good vertices are saved)
for(std::vector<int>::size_type i=0; i!=potVertices.size(); i++){
DecayVertex mv = potVertices[i];
bool isGoodVertex = true;
for(std::vector<int>::size_type j=0; j!=trackVertices.size(); j++){
DecayVertex v1 = trackVertices[j];
bool notParent = (mv.PID1() != v1.PID1());
bool isInRadius = (Distance(mv,v1)<dCut);
if (isInRadius && notParent) isGoodVertex = false;
}
for(std::vector<int>::size_type j=0; j!=showerVertices.size(); j++){
DecayVertex v2 = showerVertices[j];
bool notParent = (mv.PID2() != v2.PID2());
bool isInRadius = (Distance(mv,v2)<dCut);
if (isInRadius && notParent) isGoodVertex = false;
}
if (isGoodVertex) cleanVertices.push_back(mv);
}
}
// Throw error if anaType wasn't right.
else {
throw std::invalid_argument("Invalid anaType. Must be 'tt' or 'ts'!");
}
// Determine other values
event = event_n;
nTracks = tracks.size();
nShowers = showers.size();
nPairs = pairDistance.size();
nTrackVertices = trackVertices.size();
nShowerVertices = showerVertices.size();
nPotVertices = potVertices.size();
nCleanVertices = cleanVertices.size();
//----- STEP 2b -----//
//----- PANDORA VERTEX ANALYSIS -----//
pandora_primaryVertexPDG.clear();
pandora_nDaughters.clear();
pandora_nTracks.clear();
pandora_nShowers.clear();
pandora_nNearTracks.clear();
pandora_nNearShowers.clear();
pandora_nCleanVertices = 0;
art::FindMany<recob::Vertex> pfp_to_vertex_assns(pfpHandle,ev,trackTag);
// Repeat same analysis as before, this time, loop through each pfparticle which is a primary, find daughters, apply geo cut
// Loop through each primary pfp
for(std::vector<int>::size_type i=0; i!=pandora_primaryPFP.size(); i++){
int temp_nTracks = 0, temp_nShowers = 0, temp_nNearTracks = 0, temp_nNearShowers = 0;
// Get primary pfp vertex, (j,j) indices don't matter anymore, so just leave them by default to 0.
recob::PFParticle pfp = pandora_primaryPFP[i];
unsigned int nDaughters = pfp.NumDaughters();
pandora_nDaughters.push_back(nDaughters);
pandora_primaryVertexPDG.push_back(pfp.PdgCode());
auto const& self_idx = pfp.Self();
std::vector<recob::Vertex const*> tempVertexVector;
pfp_to_vertex_assns.get(self_idx,tempVertexVector);
auto const& pfpVertex = tempVertexVector.at(0);
double tempCoords[3];
pfpVertex->XYZ(tempCoords);
DecayVertex v0(tempCoords[0],tempCoords[1],tempCoords[2],0,0);
if (nDaughters!=0){
for(size_t k=0; k!=nDaughters; k++){
size_t daughter_idx = pfp.Daughters().at(k);
std::vector<recob::Track const*> tempTrackVector;
std::vector<recob::Shower const*> tempShowerVector;
pfp_to_track_assns.get(daughter_idx,tempTrackVector);
pfp_to_shower_assns.get(daughter_idx,tempShowerVector);
if (tempTrackVector.size()==1){
temp_nTracks += 1;
auto const& track = tempTrackVector.at(0);
DecayVertex v1(track->Vertex().X(),track->Vertex().Y(),track->Vertex().Z(),0,0);
if (Distance(v0,v1)<dCut) temp_nNearTracks += 1;
if (endVerticesAlso){
DecayVertex v2(track->End().X(),track->End().Y(),track->End().Z(),0,0);
if (Distance(v0,v2)<dCut) temp_nNearTracks += 1;
}
}
else if (tempShowerVector.size()==1){
temp_nShowers += 1;
auto const& shower = tempShowerVector.at(0);
DecayVertex v1(shower->ShowerStart().X(),shower->ShowerStart().Y(),shower->ShowerStart().Z(),0,0);
if (Distance(v0,v1)<dCut) temp_nNearShowers += 1;
}
else{
std::cout << "What the hell?!" << std::endl;
std::cout << "Not primary has PDG: " << (*pfpHandle).at(daughter_idx).PdgCode() << " and nTracks: " << tempTrackVector.size() << std::endl;
}
}
}
if (anaType == "tt" && temp_nNearTracks==2) pandora_nCleanVertices += 1;
if (anaType == "ts" && temp_nNearTracks==1 && temp_nNearShowers==1) pandora_nCleanVertices += 1;
pandora_nTracks.push_back(temp_nTracks);
pandora_nShowers.push_back(temp_nShowers);
pandora_nNearTracks.push_back(temp_nNearTracks);
pandora_nNearShowers.push_back(temp_nNearShowers);
}// End of primary loop
// Calculate final quantities
pandora_nPrimaryVertices = pandora_primaryPFP.size();
//----- STEP 3 -----//
// Finalize. Save data to tree //
// Fill the tree after each event loop
tTree->Fill();
} // End of event loop
metaTree->Fill();
// Save to file and close
tFile.cd();
tFile.Write();
tFile.Close();
}
| [
"salvatore.porzio@postgrad.manchester.ac.uk"
] | salvatore.porzio@postgrad.manchester.ac.uk |
cfa1633a3c19c63fd918bfc625fc4771d9c1e62e | 3228ed23b07cef997713a36438629f3562557ea0 | /FaceBook HackerCup/Round1/Q4/sol.cpp | 7ac568bf27ea86662b7b268976988c1e35d58f2e | [] | no_license | Janmansh/CompetitiveProgramming | 6069c295e183c2cd18582dc4f008de8529ec7dd1 | 6d35a30a8c44fd36dc5eafe46389a071c59333a0 | refs/heads/main | 2023-08-22T10:17:40.142484 | 2021-10-15T16:20:36 | 2021-10-15T16:20:36 | 372,047,169 | 1 | 3 | null | 2021-10-04T21:01:04 | 2021-05-29T18:42:44 | C++ | UTF-8 | C++ | false | false | 1,585 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define int long long
#define pb push_back
#define mod 1000000007
#define mp make_pair
ll fact[200005];
ll powermod(ll x,ll y){
if(y==0) return 1;
ll temp = powermod( x,y/2 )%mod;
if( y%2 ){
return (((temp*temp)%mod)*x%mod);
}
return (temp*temp)%mod;
}
ll power(ll x,ll y){
if(y==0) return 1;
ll temp = power( x,y/2 );
if( y%2 ){
return (((temp*temp))*x);
}
return (temp*temp);
}
int gcd (int a, int b) {
return b ? gcd (b, a % b) : a;
}
ll inv(ll a, ll p){
return powermod(a,mod-2);
}
ll nCr(ll n, ll r, ll p){
if(r > n) return 0;
ll t1 = fact[n];
ll t2 = inv(fact[r],p);
ll t3 = inv(fact[n-r],p);
return (((t1*t2)%p)*t3)%p;
}
void solve(){
ll n,i,j,a,b,m;
cin>>n>>m>>a>>b;
vector<vector<int>>ans(n, vector<int>(m, 1));
int x = m+n-1;
if(a < x or b < x){
cout << "Impossible\n";
return;
}
cout << "Possible\n";
ans[n-1][0] = b - x + 1;
ans[n-1][m-1] = a - x + 1;
for(i=0;i<n;i++){
for(j=0;j<m;j++){
cout << ans[i][j] << " ";
}
cout << "\n";
}
return;
}
signed main(){
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
ll t=1;
cin>>t;
// srand(time(0));
// fact[0]=1;
// for(int i=1;i<200001;i++){
// fact[i]=i*fact[i-1];
// fact[i]%=mod;
// }
int x = 1;
while (t--){
cout << "Case #" << x << ": ";
x++;
solve();
}
return 0;
} | [
"janmansh.191cs205@nitk.edu.in"
] | janmansh.191cs205@nitk.edu.in |
006686027d219b976d70ba2452a51cf728996bd2 | 8cbe5c7192b19a5fbe11f0beaa39faaeda20d78e | /ProjetRNN/src/simulation/LightSensor.hpp | 8e2aa7ad4c58aef8b7ec7a48ef0c134780d8a4a1 | [] | no_license | gviejo/ANIMAT | a0395b61883f5fc23d03f42a470446dbcfa494c0 | e1a209bf13243f2d30f7425e4627df7ea8a2fed7 | refs/heads/master | 2021-01-25T07:11:47.303048 | 2014-02-11T15:27:49 | 2014-02-11T15:27:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,036 | hpp | #ifndef FASTSIM_LIGHTSENSOR_HPP_
#define FASTSIM_LIGHTSENSOR_HPP_
#include <boost/shared_ptr.hpp>
#include "Posture.hpp"
#include "Map.hpp"
#include "../tools/smart_ptr.h"
/// detect an colored illuminated switch in the given direction
/// (angle) and within the angular range. There is no range limit.
/// light sensors DONT'T SEE TROUGH OBSTACLES
class LightSensor
{
public:
LightSensor(int color, float angle, float range)
{
_color = color;
_angle = angle;
_range = range;
_activated = false;
_num = 0;
}
int update(SPTR<Posture> pos,
SPTR<Map> Map);
int get_color() const { return _color; }
float get_angle() const { return _angle; }
float get_range() const { return _range; }
bool get_activated() const { return _activated; }
unsigned int get_num() const {return _num;}
protected:
// the "color" (i.e. light identifier) detected
int _color;
//
float _angle;
//
float _range;
//
bool _activated;
// sensor number (for display only)
unsigned int _num;
};
#endif
| [
"guillaume.viejo@gmail.com"
] | guillaume.viejo@gmail.com |
7aeb850e96ae4a3db27147e42687a05ff9b7ff3b | 9f7e12fdbb9dc538f5fcb32cbaf4f593e68ce638 | /src/rpc/rpc_server.cpp | 680fb9a5098e9611bbd6c1c9f8baa90448bacd9a | [] | no_license | LISHUAI0000/dist_storage | cf69c95681d42ad3bac268d472e8478d56d1043f | 20d497bf4bc0e85ec7df562243dd3700821bbe88 | refs/heads/master | 2021-05-30T05:41:34.702343 | 2015-06-02T12:48:36 | 2015-06-02T12:48:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,516 | cpp | /***************************************************************************
*
* Copyright (c) 2014 Aishuyu. All Rights Reserved
*
**************************************************************************/
/**
* @file rpc_server.cpp
* @author aishuyu(asy5178@163.com)
* @date 2014/11/24 00:10:22
* @brief
*
**/
#include "rpc_server.h"
#include <string>
#include <google/protobuf/message.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/common.h>
#include "pub_define.h"
#include "socket_util.h"
#include "rpc_util.h"
#include "common/ds_log.h"
namespace dist_storage {
//using std::string;
#define MAXEVENTS 100
RpcServer::RpcServer() :
libev_connector_ptr_(NULL),
io_thread_ptr_(NULL),
worker_threads_ptr_(NULL) {
}
RpcServer::~RpcServer() {
for (HashMap::iterator iter = method_hashmap_.begin();
iter != method_hashmap_.end();
++iter) {
RpcMethod* rpc_method_ptr = iter->second;
if (NULL != rpc_method_ptr) {
delete rpc_method_ptr;
rpc_method_ptr = NULL;
}
}
if (NULL != worker_threads_ptr_) {
delete worker_threads_ptr_;
}
if (NULL != io_thread_ptr_) {
delete io_thread_ptr_;
}
if (NULL != libev_connector_ptr_) {
delete libev_connector_ptr_;
}
}
// initial prameters
bool RpcServer::Initialize() {
// should read from config file
// strcpy(host_, "127.0.0.1");
// strcpy(port_, "9998");
return true;
}
// Note: not thread safe in old c++
RpcServer& RpcServer::GetInstance() {
static RpcServer server_instance;
return server_instance;
}
// Registe the serverice into map
bool RpcServer::RegisteService(Service* reg_service) {
const ServiceDescriptor* descriptor = reg_service->GetDescriptor();
for (int32_t i = 0; i < descriptor->method_count(); ++i) {
const MethodDescriptor* method_desc = descriptor->method(i);
const Message* request = ®_service->GetRequestPrototype(method_desc);
const Message* response = ®_service->GetResponsePrototype(method_desc);
RpcMethod* rpc_method =
new RpcMethod(reg_service, request, response, method_desc);
uint32_t hash_code = BKDRHash(method_desc->full_name().c_str());
HashMap::iterator ret_iter = method_hashmap_.find(hash_code);
if (ret_iter == method_hashmap_.end()) {
method_hashmap_.insert(std::make_pair(hash_code, rpc_method));
} else {
delete ret_iter->second;
method_hashmap_[hash_code] = rpc_method;
}
}
return true;
}
bool RpcServer::Start(int32_t thread_num, const char* addr, const char* port) {
if (!Initialize()) {
return false;
}
DS_LOG(INFO, "Rpc server start info, thread pool num: %d, addr: %s, port: %s",
thread_num, addr, port);
libev_connector_ptr_ = new LibevConnector();
io_thread_ptr_ = new IOThread(addr, port);
worker_threads_ptr_ = new ThreadPool(thread_num);
io_thread_ptr_->Start();
worker_threads_ptr_->Start();
return true;
}
bool RpcServer::Wait() {
if (false == io_thread_ptr_->IsAlive()) {
//worker_threads_ptr_->Destroy();
return false;
}
if (NULL != io_thread_ptr_) {
io_thread_ptr_->Wait();
}
if (NULL != worker_threads_ptr_) {
worker_threads_ptr_->Wait();
}
return true;
}
bool RpcServer::RpcCall(int32_t event_fd) {
if (NULL == worker_threads_ptr_) {
return false;
}
CallBackParams* cb_params_ptr = new CallBackParams();
cb_params_ptr->event_fd = event_fd;
cb_params_ptr->rpc_server_ptr = this;
worker_threads_ptr_->Processor(RpcServer::RpcProcessor, cb_params_ptr);
return true;
}
LibevConnector* RpcServer::GetLibevConnector() {
return libev_connector_ptr_;
}
void* RpcServer::RpcProcessor(void *arg) {
CallBackParams* cb_params_ptr = (CallBackParams*) arg;
if (NULL == cb_params_ptr) {
return NULL;
}
RpcServer* rpc_serv_ptr = cb_params_ptr->rpc_server_ptr;
if (NULL == rpc_serv_ptr) {
return NULL;
}
int32_t event_fd = cb_params_ptr->event_fd;
RpcMessage recv_rpc_msg;
if (!rpc_serv_ptr->GetMethodRequest(event_fd, recv_rpc_msg)) {
//rpc_serv_ptr->ErrorSendMsg(event_fd, "get method request failed!");
return NULL;
}
uint32_t hash_code = recv_rpc_msg.head_code();
HashMap& method_hashmap = rpc_serv_ptr->method_hashmap_;
HashMap::iterator method_iter = method_hashmap.find(hash_code);
if (method_iter == method_hashmap.end() || NULL == method_iter->second) {
DS_LOG(ERROR, "Find hash code failed! request hash code is: %u", hash_code);
rpc_serv_ptr->ErrorSendMsg(event_fd, "find hash code failed!");
return NULL;
}
RpcMethod* rpc_method = method_iter->second;
Message* request = rpc_method->request->New();
if ("0" != recv_rpc_msg.body_msg() &&
!request->ParseFromString(recv_rpc_msg.body_msg())) {
DS_LOG(ERROR, "Parse body msg error!");
rpc_serv_ptr->ErrorSendMsg(event_fd, "parse body msg error!");
delete request;
return NULL;
}
const MethodDescriptor* method_desc = rpc_method->method;
Message* response = rpc_method->response->New();
rpc_method->service->CallMethod(method_desc, NULL, request, response, NULL);
if (!rpc_serv_ptr->SendFormatStringMsg(event_fd, response)) {
DS_LOG(ERROR, "Send format response failed!");
rpc_serv_ptr->ErrorSendMsg(event_fd, "send format response failed!");
}
delete request;
delete response;
delete cb_params_ptr;
}
bool RpcServer::GetMethodRequest(int32_t event_fd, RpcMessage& recv_rpc_msg) {
string msg_str;
if (RecvMsg(event_fd, msg_str) < 0) {
DS_LOG(ERROR, "Rpc server recv msg failed!");
return false;
}
if (0 == msg_str.size()) {
close(event_fd);
return false;
}
if (!recv_rpc_msg.ParseFromString(msg_str)) {
DS_LOG(ERROR, "Parse from string msg failed!");
close(event_fd);
return false;
}
return true;
}
bool RpcServer::SendFormatStringMsg(int32_t event_fd, Message* response) {
string response_str;
if (!response->SerializeToString(&response_str)) {
DS_LOG(ERROR, "Response_str SerializeToString failed!");
return false;
}
if (0 == response_str.size()) {
response_str = "0";
}
RpcMessage send_rpc_msg;
send_rpc_msg.set_head_code(SER_RETURN_SUCCU);
send_rpc_msg.set_body_msg(response_str);
string send_str;
if (!send_rpc_msg.SerializeToString(&send_str)) {
DS_LOG(ERROR, "Send_str SerializeToString failed!");
return false;
}
SendMsg(event_fd, send_str);
close(event_fd);
//fsync(event_fd);
//close(event_fd);
//fflush(event_fd);
return true;
}
bool RpcServer::ErrorSendMsg(int32_t event_fd, const string& error_msg) {
RpcMessage error_rpc_msg;
// 500 means internal error
error_rpc_msg.set_head_code(SER_INTERNAL_ERROR);
error_rpc_msg.set_body_msg(error_msg);
string err_msg_str;
if (!error_rpc_msg.SerializeToString(&err_msg_str)) {
DS_LOG(ERROR, "Send error!");
close(event_fd);
return false;
}
SendMsg(event_fd, err_msg_str);
close(event_fd);
return true;
}
} // end of namespace dist_storage
/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
| [
"asy5178@163.com"
] | asy5178@163.com |
f44eaa398632f79d42987137418aab292979f256 | fc38a55144a0ad33bd94301e2d06abd65bd2da3c | /thirdparty/cgal/CGAL-4.13/include/CGAL/Mesh_2/Lipschitz_sizing_field_2.h | 810deb938cb486ecb7525b77086e4a4e4cb376e6 | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LGPL-2.0-or-later",
"LGPL-3.0-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-commercial-license",
"LGPL-3.0-only",
"GPL-3.0-only",
"LGPL-2.1-or-later",
"LicenseRef-scancode-proprietary-license",
"Licens... | permissive | bobpepin/dust3d | 20fc2fa4380865bc6376724f0843100accd4b08d | 6dcc6b1675cb49ef3fac4a58845f9c9025aa4c9f | refs/heads/master | 2022-11-30T06:00:10.020207 | 2020-08-09T09:54:29 | 2020-08-09T09:54:29 | 286,051,200 | 0 | 0 | MIT | 2020-08-08T13:45:15 | 2020-08-08T13:45:14 | null | UTF-8 | C++ | false | false | 7,492 | h | // Copyright (c) 2013 INRIA Sophia-Antipolis (France),
// 2014-2015 GeometryFactory (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
// You can redistribute it and/or modify it under the terms of the GNU
// General Public License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id$
// SPDX-License-Identifier: GPL-3.0+
//
//
// Author(s) : Lakulish Antani, Christophe Delage, Jane Tournois, Pierre Alliez
//
#ifndef CGAL_LIPSCHITZ_SIZING_FIELD_2_H
#define CGAL_LIPSCHITZ_SIZING_FIELD_2_H
#include <CGAL/license/Mesh_2.h>
#include <CGAL/disable_warnings.h>
#include <list>
#include <CGAL/basic.h>
#include <CGAL/squared_distance_2.h>
#include <CGAL/Delaunay_triangulation_2.h>
#include <CGAL/Orthogonal_k_neighbor_search.h>
#include <CGAL/Search_traits_2.h>
#include <CGAL/Apollonius_graph_2.h>
#include <CGAL/Apollonius_graph_traits_2.h>
#include <CGAL/Mesh_2/Sizing_field_2.h>
namespace CGAL
{
template <typename Tr>
class Lipschitz_sizing_field_2
: public virtual Sizing_field_2<Tr>
{
public:
typedef typename Tr::Geom_traits Geom_traits;
typedef typename Geom_traits::Point_2 Point;
typedef Delaunay_triangulation_2<Geom_traits> Delaunay_triangulation;
typedef typename Delaunay_triangulation::All_faces_iterator Face_iterator;
typedef typename Delaunay_triangulation::Finite_vertices_iterator Vertex_iterator;
typedef typename Delaunay_triangulation::Face_circulator Face_circulator;
typedef Search_traits_2<Geom_traits> Tree_traits;
typedef Orthogonal_k_neighbor_search<Tree_traits> Neighbor_search;
typedef typename Neighbor_search::Tree Search_tree;
typedef Apollonius_graph_traits_2<Geom_traits> Apollonius_traits;
typedef Apollonius_graph_2<Apollonius_traits> Apollonius_graph;
typedef typename Apollonius_traits::Site_2 Site;
public:
typedef std::list<Site> Site_set_2;
public:
// comparison functor for sorting sites
class Compare_site_2
{
public:
bool operator ()(Site s1, Site s2)
{
return (s1.weight() > s2.weight());
}
};
public:
// default constructor: empty point set and K = 1.0
Lipschitz_sizing_field_2()
: K(1.0)
{
sites = Site_set_2();
generate_delaunay();
extract_poles();
generate_sites();
generate_apollonius();
}
// constructor with point set and K as parameters
template <typename InputIterator>
Lipschitz_sizing_field_2(InputIterator first,
InputIterator beyond,
const double k = 1.0)
: K(k)
{
#ifdef CGAL_MESH_2_OPTIMIZER_VERBOSE
std::cout << "Building sizing field..." << std::flush;
#endif
points = std::list<Point>(first, beyond);
generate_delaunay();
extract_poles();
generate_sites();
generate_apollonius();
#ifdef CGAL_MESH_2_OPTIMIZER_VERBOSE
std::cout << "done." << std::endl;
#endif
}
// constructor from a triangulation
Lipschitz_sizing_field_2(Tr& tr, const double k = 1.0)
: K(k)
{
#ifdef CGAL_MESH_2_OPTIMIZER_VERBOSE
std::cout << "Building sizing field..." << std::flush;
#endif
points = std::list<Point>(tr.points_begin(), tr.points_end());
generate_delaunay();
extract_poles();
generate_sites();
generate_apollonius();
#ifdef CGAL_MESH_2_OPTIMIZER_VERBOSE
std::cout << "done." << std::endl;
#endif
}
// assignment operator, copies point set and K
Lipschitz_sizing_field_2& operator =(const Lipschitz_sizing_field_2& f)
{
points.clear();
if(!poles.empty())
poles.clear();
if(!sites.empty())
sites.clear();
dt.clear();
ag.clear();
points = f.points;
K = f.K;
generate_delaunay();
extract_poles();
generate_sites();
generate_apollonius();
return *this;
}
double operator()(const Point& p) const
{
if(points.empty() || points.size() == 1)
return K;
Site ns = (*ag.nearest_neighbor(p)).site();
return K * weighted_distance(p, ns);
}
void set_K(double k)
{
K = k;
}
double get_K()
{
return K;
}
std::list<Point>& get_poles()
{
return poles;
}
protected:
double K;
Site_set_2 sites;
std::list<Point> points;
std::list<Point> poles;
Apollonius_graph ag;
Delaunay_triangulation dt;
// generate the delaunay triangulation (for voronoi diagram)
void generate_delaunay()
{
if(points.empty())
return;
for(typename std::list<Point>::iterator ppi = points.begin();
ppi != points.end();ppi++)
dt.insert(*ppi);
}
// pole extraction
void extract_poles()
{
if (points.empty())
return;
Vertex_iterator vi;
for (vi = dt.finite_vertices_begin(); vi != dt.finite_vertices_end(); vi++)
{
Face_circulator fc = dt.incident_faces(vi);
Face_circulator c = fc;
std::list<Point> vv;
if (fc != NULL)
{
do
{
if (!dt.is_infinite(c) && dt.triangle(c).area() != 0)
vv.push_back(dt.dual(c));
} while (++c != fc);
}
// find the farthest voronoi vertex from this point
typename std::list<Point>::iterator maxp = vv.begin();
for (typename std::list<Point>::iterator pi = vv.begin(); pi != vv.end(); pi++)
{
if (squared_distance(*pi, (*vi).point()) > squared_distance(*maxp, (*vi).point()))
{
maxp = pi;
}
}
poles.push_back(*maxp);
// find the farthest voronoi vertex from this point in the other half-plane
typename std::list<Point>::iterator maxp2 = vv.begin();
for (typename std::list<Point>::iterator pi = vv.begin(); pi != vv.end(); pi++)
{
if (angle((Point) *pi, (Point) (*vi).point(), (Point) *maxp) == OBTUSE &&
squared_distance(*pi, (*vi).point()) > squared_distance(*maxp2, (*vi).point()))
{
maxp2 = pi;
}
}
poles.push_back(*maxp2);
}
}
void generate_sites()
{
if(poles.empty())
return;
Search_tree tree_poles(poles.begin(), poles.end());
Search_tree tree_points(points.begin(), points.end());
for(typename std::list<Point>::iterator pi = points.begin();
pi != points.end();
pi++)
{
// estimate lfs (distance to medial axis estimate)
Neighbor_search search_poles(tree_poles, *pi, 1);
double lfs = std::sqrt((search_poles.begin())->second);
// compute distance to nearest input point
Neighbor_search search_points(tree_points, *pi, 2); // notice 2
typename Neighbor_search::iterator it = search_points.begin();
it++; // the first one is...itself
double d = std::sqrt(it->second);
// take min(lfs,distance to nearest point) as sizing
double sizing = (std::min)(lfs,d);
sites.push_back(Site(*pi, -sizing / K));
}
}
// generate apollonius graph
// first sorting the sites in decreasing order of weights
void generate_apollonius()
{
if(sites.empty())
return;
sites.sort(Compare_site_2());
ag.insert(sites.begin(),sites.end());
}
double weighted_distance(const Point p,
const Site s) const
{
return std::sqrt(squared_distance(p, s.point())) - s.weight();
}
};
}//namespace CGAL
#include <CGAL/enable_warnings.h>
#endif //CGAL_LIPSCHITZ_SIZING_FIELD_2_H
| [
"huxingyi@msn.com"
] | huxingyi@msn.com |
5d4a57cbf90346bc5d59e96530dc7c08196dab40 | 606a7e79a80524333e083d862b385166967786d9 | /include/Materials/Material.h | 46e16127adeb92c9bb751e55a9d30d724b30ef91 | [] | no_license | chrisgilbertjr/raytracer | c4eb2c9362121fe11a5ed612c0c6c9dd7e0dafa2 | c99a9411a329a2ee6a5ed4adc7eede15d5aa0e62 | refs/heads/master | 2021-01-21T14:07:50.190815 | 2016-06-02T02:17:44 | 2016-06-02T02:17:44 | 47,533,048 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,665 | h |
#ifndef MATERIAL_H
#define MATERIAL_H
#include "..\Core\Color.h"
/// @defgroup Material Material
/// @{
/// forward declaration
struct ShadeRecord;
/// base class for all materials
class Material
{
protected:
Color m_color; /// base color for materials
public:
/// constructor
Material();
/// copy constructor
Material(const Material& material);
/// destructor
virtual ~Material();
/// copy assignment operator
Material& operator=(Material material);
/// deep copy of the object
virtual Material* Clone() const;
/// compute the color given a shade record
virtual Color Shade(ShadeRecord& record) const;
/// compute the color given a shade record for area lighting
virtual Color AreaLightShade(ShadeRecord& record) const;
/// compute the color given a shade record for path tracing
virtual Color PathShade(ShadeRecord& record) const;
/// get the emmisive color of the material
virtual Color GetEmmisive() const;
/// get the materials base color
Color GetColor() const;
/// set the materials base color
void SetColor(const Color& color);
};
/// --------------------------------------------------------------------------- GetColor
inline Color
Material::GetColor() const
{
return m_color;
}
/// --------------------------------------------------------------------------- SetColor
inline void
Material::SetColor(const Color& color)
{
m_color = color;
}
/// --------------------------------------------------------------------------- EOF
/// @}
#endif | [
"gilbertchris123@gmail.com"
] | gilbertchris123@gmail.com |
b8059e5b8788a68ffacc104ec30eb8a9b2678c2e | dac5254630fefae851da7c843dcab7f6a6af9703 | /Plug-ins/vCardAdbkIO/sources/CVCardEngine.cp | 17ca2133b0fb0d0de74f40ea0ddd4211ee704ad2 | [
"Apache-2.0"
] | permissive | gpreviato/Mulberry-Mail | dd4e3618468fff36361bd2aeb0a725593faa0f8d | ce5c56ca7044e5ea290af8d3d2124c1d06f36f3a | refs/heads/master | 2021-01-20T03:31:39.515653 | 2017-09-21T13:09:55 | 2017-09-21T13:09:55 | 18,178,314 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,616 | cp | /*
Copyright (c) 2007 Cyrus Daboo. 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.
*/
// CVCardEngine.cp
//
// Copyright 2006, Cyrus Daboo. All Rights Reserved.
//
// Created: 01-Aug-2002
// Author: Cyrus Daboo
// Platforms: Mac OS, Win32, Unix
//
// Description:
// This class implements a generic vCard I/O engine.
//
// History:
// 01-Aug-2002: Created initial header and implementation.
//
#include "CVCardEngine.h"
#include "CVCard.h"
#include "CStringUtils.h"
// Read a single vCard address from the input stream
bool CVCardEngine::ReadOne(std::istream& in, CAdbkIOPluginDLL::SAdbkIOPluginAddress& addr)
{
// Create vCard
CVCard vCard;
// Read in vCard and look for specific items
if (vCard.Read(in))
{
addr.mName = vCard.CountItems("FN") ? ::strdup(vCard.GetValue("FN")) : NULL;
addr.mNickName = vCard.CountItems("NICKNAME") ? ::strdup(vCard.GetValue("NICKNAME")) : NULL;
addr.mEmail = vCard.CountItems("EMAIL", "TYPE", "INTERNET") ? ::strdup(vCard.GetValue("EMAIL", "TYPE", "INTERNET")) :
(vCard.CountItems("EMAIL") ? ::strdup(vCard.GetValue("EMAIL")) : NULL);
addr.mCompany = vCard.CountItems("ORG") ? ::strdup(vCard.GetValue("ORG")) : NULL;
addr.mAddress = vCard.CountItems("ADR", "TYPE", "POSTAL") ? ::strdup(vCard.GetValue("ADR", "TYPE", "POSTAL")) :
(vCard.CountItems("ADR") ? ::strdup(vCard.GetValue("ADR")) : NULL);
cdstrmap phonework;
phonework.insert(cdstrmap::value_type("TYPE", "WORK"));
phonework.insert(cdstrmap::value_type("TYPE", "VOICE"));
addr.mPhoneWork = vCard.CountItems("TEL", phonework) ? ::strdup(vCard.GetValue("TEL", phonework)) : NULL;
cdstrmap phonehome;
phonehome.insert(cdstrmap::value_type("TYPE", "HOME"));
phonehome.insert(cdstrmap::value_type("TYPE", "VOICE"));
addr.mPhoneHome = vCard.CountItems("TEL", phonehome) ? ::strdup(vCard.GetValue("TEL", phonehome)) : NULL;
addr.mFax = vCard.CountItems("TEL", "TYPE", "FAX") ? ::strdup(vCard.GetValue("TEL", "TYPE", "FAX")) : NULL;
addr.mURL = vCard.CountItems("URL") ? ::strdup(vCard.GetValue("URL")) : NULL;
addr.mNotes = vCard.CountItems("NOTE") ? ::strdup(vCard.GetValue("NOTE")) : NULL;
// Make full name valid by copying something
if (!addr.mName)
{
if (addr.mCompany)
addr.mName = ::strdup(addr.mCompany);
else if (addr.mNickName)
addr.mName = ::strdup(addr.mNickName);
else if (addr.mEmail)
addr.mName = ::strdup(addr.mEmail);
}
return true;
}
return false;
}
// Write a single vCard address to the output stream
void CVCardEngine::WriteOne(std::ostream& out, const CAdbkIOPluginDLL::SAdbkIOPluginAddress& addr)
{
// Creat vcard object and add appropriate fields
CVCard vcard;
vcard.AddItem("FN", addr.mName);
if (addr.mNickName && ::strlen(addr.mNickName))
vcard.AddItem("NICKNAME", addr.mNickName);
if (addr.mEmail && ::strlen(addr.mEmail))
{
CVCardItem& item = vcard.AddItem("EMAIL", addr.mEmail);
item.AddParam("TYPE", "INTERNET");
item.AddParam("TYPE", "PREF");
}
// Add an "N" item only if name is different than the company
if (::strcmpnocase(addr.mName, addr.mCompany))
vcard.AddItem("N", addr.mName);
if (addr.mCompany && ::strlen(addr.mCompany))
vcard.AddItem("ORG", addr.mCompany);
if (addr.mAddress && ::strlen(addr.mAddress))
{
CVCardItem& item = vcard.AddItem("ADR", addr.mAddress);
item.AddParam("TYPE", "POSTAL");
}
if (addr.mPhoneWork && ::strlen(addr.mPhoneWork))
{
CVCardItem& item = vcard.AddItem("TEL", addr.mPhoneWork);
item.AddParam("TYPE", "WORK");
item.AddParam("TYPE", "VOICE");
}
if (addr.mPhoneHome && ::strlen(addr.mPhoneHome))
{
CVCardItem& item = vcard.AddItem("TEL", addr.mPhoneHome);
item.AddParam("TYPE", "HOME");
item.AddParam("TYPE", "VOICE");
}
if (addr.mFax && ::strlen(addr.mFax))
{
CVCardItem& item = vcard.AddItem("TEL", addr.mFax);
item.AddParam("TYPE", "FAX");
}
if (addr.mURL && ::strlen(addr.mURL))
vcard.AddItem("URL", addr.mURL);
if (addr.mNotes && ::strlen(addr.mNotes))
vcard.AddItem("NOTE", addr.mNotes);
// Write the vCard object
vcard.Write(out);
}
| [
"svnusers@a91246af-f21b-0410-bd1c-c3c7fc455132"
] | svnusers@a91246af-f21b-0410-bd1c-c3c7fc455132 |
05cc39f43b5fe63e89ca10f2266d5c7cec48be9a | c6b3e60a3db8e30270db498fa8cc72d25efb984e | /src/proj/projections/urmfps.cpp | 6bc7493f950c8f72204e4d0d689ef70955c58bad | [
"MIT"
] | permissive | mdsumner/libproj | 3aa1dc9d3cba9a4b083de0162c9e323b8bccf034 | b815df5411ae6a660fc0e99bd458d601c37c38f6 | refs/heads/master | 2023-08-19T04:20:38.102110 | 2021-10-06T11:54:25 | 2021-10-06T11:54:25 | 285,718,735 | 0 | 0 | null | 2020-08-07T02:32:32 | 2020-08-07T02:32:31 | null | UTF-8 | C++ | false | false | 2,321 | cpp | #define PJ_LIB__
#include <errno.h>
#include <math.h>
#include "R-libproj/proj.h"
#include "R-libproj/proj_internal.h"
PROJ_HEAD(urmfps, "Urmaev Flat-Polar Sinusoidal") "\n\tPCyl, Sph\n\tn=";
PROJ_HEAD(wag1, "Wagner I (Kavraisky VI)") "\n\tPCyl, Sph";
namespace { // anonymous namespace
struct pj_opaque {
double n, C_y;
};
} // anonymous namespace
#define C_x 0.8773826753
#define Cy 1.139753528477
static PJ_XY urmfps_s_forward (PJ_LP lp, PJ *P) { /* Spheroidal, forward */
PJ_XY xy = {0.0, 0.0};
lp.phi = aasin (P->ctx,static_cast<struct pj_opaque*>(P->opaque)->n * sin (lp.phi));
xy.x = C_x * lp.lam * cos (lp.phi);
xy.y = static_cast<struct pj_opaque*>(P->opaque)->C_y * lp.phi;
return xy;
}
static PJ_LP urmfps_s_inverse (PJ_XY xy, PJ *P) { /* Spheroidal, inverse */
PJ_LP lp = {0.0, 0.0};
xy.y /= static_cast<struct pj_opaque*>(P->opaque)->C_y;
lp.phi = aasin(P->ctx, sin (xy.y) / static_cast<struct pj_opaque*>(P->opaque)->n);
lp.lam = xy.x / (C_x * cos (xy.y));
return lp;
}
static PJ *setup(PJ *P) {
static_cast<struct pj_opaque*>(P->opaque)->C_y = Cy / static_cast<struct pj_opaque*>(P->opaque)->n;
P->es = 0.;
P->inv = urmfps_s_inverse;
P->fwd = urmfps_s_forward;
return P;
}
PJ *PROJECTION(urmfps) {
struct pj_opaque *Q = static_cast<struct pj_opaque*>(calloc (1, sizeof (struct pj_opaque)));
if (nullptr==Q)
return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/);
P->opaque = Q;
if (!pj_param(P->ctx, P->params, "tn").i )
{
proj_log_error(P, _("Missing parameter n."));
return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG);
}
Q->n = pj_param(P->ctx, P->params, "dn").f;
if (Q->n <= 0. || Q->n > 1.)
{
proj_log_error(P, _("Invalid value for n: it should be in ]0,1] range."));
return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE);
}
return setup(P);
}
PJ *PROJECTION(wag1) {
struct pj_opaque *Q = static_cast<struct pj_opaque*>(calloc (1, sizeof (struct pj_opaque)));
if (nullptr==Q)
return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/);
P->opaque = Q;
static_cast<struct pj_opaque*>(P->opaque)->n = 0.8660254037844386467637231707;
return setup(P);
}
| [
"dewey@fishandwhistle.net"
] | dewey@fishandwhistle.net |
232a5acda68c5f78e41935b98bd5d16aa7b5a2d4 | 1834c0796ee324243f550357c67d8bcd7c94de17 | /SDK/TCF_ClothingSystemRuntimeInterface_functions.cpp | 738d8c8f19db9befaa182d7cd1f5bc1ad3a09a2b | [] | no_license | DarkCodez/TCF-SDK | ce41cc7dab47c98b382ad0f87696780fab9898d2 | 134a694d3f0a42ea149a811750fcc945437a70cc | refs/heads/master | 2023-08-25T20:54:04.496383 | 2021-10-25T11:26:18 | 2021-10-25T11:26:18 | 423,337,506 | 1 | 0 | null | 2021-11-01T04:31:21 | 2021-11-01T04:31:20 | null | UTF-8 | C++ | false | false | 7,704 | cpp | // The Cycle Frontier (1.X) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "TCF_ClothingSystemRuntimeInterface_classes.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.SetAnimDriveSpringStiffness
// (FUNC_Native, FUNC_Public, FUNC_BlueprintCallable)
// Parameters:
// float InStiffness (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic)
void UClothingSimulationInteractor::SetAnimDriveSpringStiffness(float InStiffness)
{
static auto fn = UObject::FindObject<UFunction>("Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.SetAnimDriveSpringStiffness");
struct
{
float InStiffness;
} params;
params.InStiffness = InStiffness;
UObject::ProcessEvent(fn, ¶ms);
}
// Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.PhysicsAssetUpdated
// (FUNC_Native, FUNC_Public, FUNC_BlueprintCallable)
void UClothingSimulationInteractor::PhysicsAssetUpdated()
{
static auto fn = UObject::FindObject<UFunction>("Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.PhysicsAssetUpdated");
struct
{
} params;
UObject::ProcessEvent(fn, ¶ms);
}
// Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.GetSimulationTime
// (FUNC_Native, FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintPure, FUNC_Const)
// Parameters:
// float ReturnValue (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic)
float UClothingSimulationInteractor::GetSimulationTime()
{
static auto fn = UObject::FindObject<UFunction>("Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.GetSimulationTime");
struct
{
float ReturnValue;
} params;
UObject::ProcessEvent(fn, ¶ms);
return params.ReturnValue;
}
// Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.GetNumSubsteps
// (FUNC_Native, FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintPure, FUNC_Const)
// Parameters:
// int ReturnValue (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic)
int UClothingSimulationInteractor::GetNumSubsteps()
{
static auto fn = UObject::FindObject<UFunction>("Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.GetNumSubsteps");
struct
{
int ReturnValue;
} params;
UObject::ProcessEvent(fn, ¶ms);
return params.ReturnValue;
}
// Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.GetNumKinematicParticles
// (FUNC_Native, FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintPure, FUNC_Const)
// Parameters:
// int ReturnValue (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic)
int UClothingSimulationInteractor::GetNumKinematicParticles()
{
static auto fn = UObject::FindObject<UFunction>("Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.GetNumKinematicParticles");
struct
{
int ReturnValue;
} params;
UObject::ProcessEvent(fn, ¶ms);
return params.ReturnValue;
}
// Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.GetNumIterations
// (FUNC_Native, FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintPure, FUNC_Const)
// Parameters:
// int ReturnValue (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic)
int UClothingSimulationInteractor::GetNumIterations()
{
static auto fn = UObject::FindObject<UFunction>("Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.GetNumIterations");
struct
{
int ReturnValue;
} params;
UObject::ProcessEvent(fn, ¶ms);
return params.ReturnValue;
}
// Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.GetNumDynamicParticles
// (FUNC_Native, FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintPure, FUNC_Const)
// Parameters:
// int ReturnValue (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic)
int UClothingSimulationInteractor::GetNumDynamicParticles()
{
static auto fn = UObject::FindObject<UFunction>("Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.GetNumDynamicParticles");
struct
{
int ReturnValue;
} params;
UObject::ProcessEvent(fn, ¶ms);
return params.ReturnValue;
}
// Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.GetNumCloths
// (FUNC_Native, FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintPure, FUNC_Const)
// Parameters:
// int ReturnValue (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic)
int UClothingSimulationInteractor::GetNumCloths()
{
static auto fn = UObject::FindObject<UFunction>("Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.GetNumCloths");
struct
{
int ReturnValue;
} params;
UObject::ProcessEvent(fn, ¶ms);
return params.ReturnValue;
}
// Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.EnableGravityOverride
// (FUNC_Native, FUNC_Public, FUNC_HasOutParms, FUNC_HasDefaults, FUNC_BlueprintCallable)
// Parameters:
// struct FVector InVector (CPF_ConstParm, CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReferenceParm, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic)
void UClothingSimulationInteractor::EnableGravityOverride(const struct FVector& InVector)
{
static auto fn = UObject::FindObject<UFunction>("Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.EnableGravityOverride");
struct
{
struct FVector InVector;
} params;
params.InVector = InVector;
UObject::ProcessEvent(fn, ¶ms);
}
// Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.DisableGravityOverride
// (FUNC_Native, FUNC_Public, FUNC_BlueprintCallable)
void UClothingSimulationInteractor::DisableGravityOverride()
{
static auto fn = UObject::FindObject<UFunction>("Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.DisableGravityOverride");
struct
{
} params;
UObject::ProcessEvent(fn, ¶ms);
}
// Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.ClothConfigUpdated
// (FUNC_Native, FUNC_Public, FUNC_BlueprintCallable)
void UClothingSimulationInteractor::ClothConfigUpdated()
{
static auto fn = UObject::FindObject<UFunction>("Function ClothingSystemRuntimeInterface.ClothingSimulationInteractor.ClothConfigUpdated");
struct
{
} params;
UObject::ProcessEvent(fn, ¶ms);
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"30532128+pubgsdk@users.noreply.github.com"
] | 30532128+pubgsdk@users.noreply.github.com |
01fa296485eddf9c176ff0199094bead2dadbede | 029289b9c0cc5175ab390f4dd13d73dc9637fa52 | /asd_core/src/log.cpp | bcc9ff074660cacc4f6dffb77513c9cd113a0ded | [] | no_license | wlsgur0726/asd | fa698a2774e1ff20754d6d8b81d5d3ad612838a4 | bbf36e7372856ea846fdf13ad71c7a467a58d244 | refs/heads/master | 2020-04-16T14:17:12.526237 | 2018-11-15T03:38:49 | 2018-11-15T03:38:49 | 38,921,232 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,260 | cpp | #include "stdafx.h"
#include "asd/log.h"
#include "asd/datetime.h"
#include <fcntl.h>
#if defined(asd_Platform_Windows)
# include <io.h>
#
#else
# include <sys/stat.h>
#
#endif
namespace asd
{
#if defined(asd_Platform_Windows)
#define asd_CCS ",ccs=UTF-16LE"
inline FILE* fopen(const FChar* a_path,
const FChar* a_mode)
{
FILE* fp;
if (0 != _wfopen_s(&fp, a_path, a_mode))
fp = nullptr;
return fp;
}
inline bool Flush(FILE* a_fp)
{
if (fflush(a_fp) != 0)
return false;
int fd = _fileno(a_fp);
if (fd == -1)
return false;
HANDLE handle = (HANDLE)_get_osfhandle(fd);
if (handle == INVALID_HANDLE_VALUE)
return false;
return FlushFileBuffers(handle) != FALSE;
}
#else
#define asd_CCS
inline bool Flush(FILE* a_fp)
{
if (fflush(a_fp) != 0)
return false;
int fd = fileno(a_fp);
if (fd == -1)
return false;
return fsync(fd) == 0;
}
#endif
auto Logger_writer_option = []()
{
ThreadPoolOption option;
option.ThreadCount = 1;
option.UseNotifier = true;
return option;
};
Logger::Logger()
: m_writer(Logger_writer_option())
{
m_writer.Start();
Init(_F(""), _F("log"));
}
Logger::~Logger()
{
m_writer.Stop();
}
std::shared_ptr<FILE> Logger::RefreshLogFile(const Date& a_today)
{
if (a_today != m_today) {
m_today = a_today;
asd_mkdir(m_outDir);
FString fn = FString::Format(_F("{}{}_{:04d}-{:02d}-{:02d}.txt"),
m_outDir, m_logName,
a_today.Year(), a_today.Month(), a_today.Day());
FILE* fp = fopen(fn, _F("a" asd_CCS));
if (fp != nullptr)
m_logFile.reset(fp, [](FILE* a_fp) { fclose(a_fp); });
}
return m_logFile;
}
void Logger::SetGenHeadDelegate(GenText&& a_delegate)
{
auto lock = GetLock(m_lock);
if (a_delegate == nullptr)
m_genHead.reset();
else
m_genHead.reset(new GenText(std::move(a_delegate)));
}
void Logger::SetGenTailDelegate(GenText&& a_delegate)
{
auto lock = GetLock(m_lock);
if (a_delegate == nullptr)
m_genTail.reset();
else
m_genTail.reset(new GenText(std::move(a_delegate)));
}
void Logger::PushLog(asd::Log&& a_log)
{
auto lock = GetLock(m_lock);
asd::Log* log = m_logObjPool.Alloc();
*log = std::move(a_log);
m_writer.Push([this, log]()
{
Print(log);
});
}
void Logger::Print(asd::Log* a_log)
{
auto lock = GetLock(m_lock);
asd::Log log = std::move(*a_log);
m_logObjPool.Free(a_log);
auto logNumber = ++m_logNumber;
auto genHead = m_genHead;
auto genTail = m_genTail;
DateTime now = DateTime::Now();
auto fp = RefreshLogFile(now.m_date);
int e = fp!=nullptr ? 0 : errno;
lock.unlock();
FString msg;
if (genHead != nullptr)
msg = (*genHead)(logNumber, now);
msg << ConvToF(log);
if (genTail != nullptr)
msg << (*genTail)(logNumber, now);
if (log.m_file != nullptr)
msg << _F(" (") << ConvToF(log.m_file) << _F(':') << log.m_line << _F(")\n");
msg << _F('\n');
if (fp != nullptr) {
if (asd::fputs(msg, fp.get()) < 0)
e = errno;
else if (log.m_flush) {
if (Flush(fp.get()) == false)
e = errno;
}
}
if (log.m_console != nullptr)
asd::fputs(msg, log.m_console);
if (log.m_sync != nullptr) {
log.m_sync->m_errno = e;
log.m_sync->m_event.Post();
}
}
}
| [
"wlsgur0726@naver.com"
] | wlsgur0726@naver.com |
b5b41be00f118193c053004822d59fe6f4b888a1 | b5ee7131ce7fc906accf761fbded47737e51b274 | /BetterMUD/BetterMUD/entities/Region.h | c7c9282076c0e933b92ff578f9829a03b956c398 | [] | no_license | JeffM2501/bettermud | 1116072276ba029e1d5cd17c6b760e6da4e0c9b6 | 3d8ac9f22c8c7b7f383bf0399828f46602dfe519 | refs/heads/master | 2021-07-16T09:14:30.507875 | 2021-03-28T20:52:08 | 2021-03-28T20:52:08 | 90,657,600 | 0 | 0 | null | 2017-05-08T18:01:51 | 2017-05-08T18:01:51 | null | UTF-8 | C++ | false | false | 935 | h | // MUD Programming
// Ron Penton
// (C)2003
// Region.h - This file contains the region entity type,
// regions contain collections of rooms.
//
//
#ifndef BETTERMUDREGION_H
#define BETTERMUDREGION_H
#include <string>
#include "BasicLib/BasicLib.h"
#include "Entity.h"
#include "LogicEntity.h"
#include "Room.h"
#include "Portal.h"
namespace BetterMUD
{
class Region :
public LogicEntity,
public DataEntity,
public HasCharacters,
public HasItems,
public HasRooms,
public HasPortals
{
public:
// disk access functions
void Save( std::ostream& p_stream );
void Load( std::istream& p_stream );
std::string& Diskname() { return m_diskname; }
void SetDiskname( const std::string& p_name ) { m_diskname = p_name; }
protected:
std::string m_diskname;
}; // end class Region
} // end namespace BetterMUD
#endif
| [
"constructible.truth@gmail.com"
] | constructible.truth@gmail.com |
34780afd4fab0ccf94d2c639484e89e0f44c01d8 | 10b4db1d4f894897b5ee435780bddfdedd91caf7 | /thrift/compiler/test/fixtures/mcpp2-compare/gen-cpp2/enums_fatal_service.h | b3e5d34c54267635926a77fd07349a70f1a4efe9 | [
"Apache-2.0"
] | permissive | SammyEnigma/fbthrift | 04f4aca77a64c65f3d4537338f7fbf3b8214e06a | 31d7b90e30de5f90891e4a845f6704e4c13748df | refs/heads/master | 2021-11-11T16:59:04.628193 | 2021-10-12T11:19:22 | 2021-10-12T11:20:27 | 211,245,426 | 1 | 0 | Apache-2.0 | 2021-07-15T21:12:07 | 2019-09-27T05:50:42 | C++ | UTF-8 | C++ | false | false | 328 | h | /**
* Autogenerated by Thrift for src/enums.thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated @nocommit
*/
#pragma once
#include "thrift/compiler/test/fixtures/mcpp2-compare/gen-cpp2/enums_types.h"
namespace facebook { namespace ns { namespace qwerty {
}}} // facebook::ns::qwerty
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
98f228c7f6bc15cd6229de40022b07bc13230614 | e91e4f5c80f0ca6b549ab74464724772d1dc063f | /Code/ModelData/modelDataBaseExtend.cpp | 7ccd046db2be8c47b9fa723bd13207e01f900004 | [
"BSD-3-Clause"
] | permissive | hobama002/FastCAE_Linux | c41bd8ca9a2672543aa3b729d3d6efc30fdd6641 | a95b9b6d22ce3e09bdf8eb690ca5a53bc75ca204 | refs/heads/master | 2022-04-15T17:54:21.194669 | 2020-04-11T03:05:07 | 2020-04-11T03:05:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,365 | cpp | #include "modelDataBaseExtend.h"
#include "BCBase/BCBase.h"
#include <QDomElement>
#include <assert.h>
#include "simulationSettingBase.h"
#include "solverSettingBase.h"
#include "ConfigOptions/ConfigOptions.h"
#include "ConfigOptions/DataConfig.h"
#include "ConfigOptions/PostCurve.h"
#include "ConfigOptions/PostConfig.h"
#include "ConfigOptions/PostConfigInfo.h"
#include "ConfigOptions/ObserverConfig.h"
#include "ConfigOptions/ParameterObserver.h"
#include "DataProperty/PropertyBase.h"
#include "DataProperty/PropertyString.h"
#include "DataProperty/ParameterInt.h"
#include "DataProperty/ParameterBool.h"
#include "DataProperty/ParameterDouble.h"
#include "DataProperty/ParameterSelectable.h"
#include "DataProperty/ParameterString.h"
#include "DataProperty/ParameterPath.h"
#include "DataProperty/ParameterTable.h"
#include <QDebug>
namespace ModelData
{
ModelDataBaseExtend::ModelDataBaseExtend(ProjectTreeType type)
: ModelDataBase(type)
{
ConfigOption::DataConfig* dataconfig = ConfigOption::ConfigOption::getInstance()->getDataConfig();
QList<ConfigOption::PostCurve*> monitorCurves = dataconfig->getMonitorCurves(_treeType);
_monitorFiles = dataconfig->getMonitorFile(_treeType);
for (int i = 0; i < monitorCurves.size(); ++i)
{
ConfigOption::PostCurve* p = new ConfigOption::PostCurve;
p->copy(monitorCurves.at(i));
_monitorCurves.append(p);
}
}
ModelDataBaseExtend::~ModelDataBaseExtend()
{
QList<DataProperty::DataBase*> datalist = _configData.values();
for (int i = 0; i < datalist.size(); ++i)
{
DataProperty::DataBase* d = datalist.at(i);
delete d;
}
_configData.clear();
for (int i = 0; i < _observerList.size(); ++i)
{
auto obs = _observerList.at(i);
delete obs;
}
_observerList.clear();
}
void ModelDataBaseExtend::appendReport(QString report)
{
_reportList.append(report);
}
int ModelDataBaseExtend::getReportCount()
{
return _reportList.size();
}
void ModelDataBaseExtend::removeReportAt(int index)
{
assert(index >= 0 && index < _reportList.size());
_reportList.removeAt(index);
}
QString ModelDataBaseExtend::getReportAt(int index)
{
assert(index >= 0 && index < _reportList.size());
return _reportList.at(index);
}
QDomElement& ModelDataBaseExtend::writeToProjectFile(QDomDocument* doc, QDomElement* e)
{
QDomElement element = ModelDataBase::writeToProjectFile(doc, e);
QDomElement materialele = doc->createElement("Material");
QList<int> setidlist = _setMaterial.keys();
for (int i = 0; i < setidlist.size(); ++i)
{
int setid = setidlist.at(i);
int materialid = _setMaterial.value(setid);
QDomElement mc = doc->createElement("MaterialInfo");
QDomAttr setattr = doc->createAttribute("SetID");
QDomAttr materialattr = doc->createAttribute("MaterialID");
setattr.setValue(QString::number(setid));
materialattr.setValue(QString::number(materialid));
mc.setAttributeNode(setattr);
mc.setAttributeNode(materialattr);
materialele.appendChild(mc);
}
element.appendChild(materialele);
QDomElement configele = doc->createElement("ConfigData");
QList<DataProperty::DataBase*> datalist = _configData.values();
for (int i = 0; i < datalist.size(); ++i)
{
DataProperty::DataBase* d = datalist.at(i);
const int id = _configData.key(d);
QDomElement dataele = doc->createElement("Data");
dataele.setAttribute("ID", id);
// QString name = d->getName();
// dataele.setAttribute("TreeNode", name);
d->writeParameters(doc, &dataele);
configele.appendChild(dataele);
}
element.appendChild(configele);
QDomElement ele = doc->createElement("Report");
for (int i = 0; i < _reportList.size(); ++i)
{
QDomElement textele = doc->createElement("Path");
QString text = _reportList.at(i);
QDomText textdom = doc->createTextNode(text);
textele.appendChild(textdom);
ele.appendChild(textele);
}
element.appendChild(ele);
return element;
}
void ModelDataBaseExtend::writeToProjectFile1(QDomDocument* doc, QDomElement* e)
{
ModelDataBase::writeToProjectFile1(doc, e);
QDomElement materialele = doc->createElement("Material");
QList<int> setidlist = _setMaterial.keys();
for (int i = 0; i < setidlist.size(); ++i)
{
int setid = setidlist.at(i);
int materialid = _setMaterial.value(setid);
QDomElement mc = doc->createElement("MaterialInfo");
QDomAttr setattr = doc->createAttribute("SetID");
QDomAttr materialattr = doc->createAttribute("MaterialID");
setattr.setValue(QString::number(setid));
materialattr.setValue(QString::number(materialid));
mc.setAttributeNode(setattr);
mc.setAttributeNode(materialattr);
materialele.appendChild(mc);
}
e->appendChild(materialele);
QDomElement configele = doc->createElement("ConfigData");
QList<DataProperty::DataBase*> datalist = _configData.values();
for (int i = 0; i < datalist.size(); ++i)
{
DataProperty::DataBase* d = datalist.at(i);
const int id = _configData.key(d);
QDomElement dataele = doc->createElement("Data");
dataele.setAttribute("ID", id);
d->writeParameters(doc, &dataele);
configele.appendChild(dataele);
}
e->appendChild(configele);
QDomElement ele = doc->createElement("Report");
for (int i = 0; i < _reportList.size(); ++i)
{
QDomElement textele = doc->createElement("Path");
QString text = _reportList.at(i);
QDomText textdom = doc->createTextNode(text);
textele.appendChild(textdom);
ele.appendChild(textele);
}
e->appendChild(ele);
}
void ModelDataBaseExtend::readDataFromProjectFile(QDomElement* e)
{
ModelDataBase::readDataFromProjectFile(e);
QDomNodeList materialList = e->elementsByTagName("MaterialInfo");
for (int i = 0; i < materialList.size(); ++i)
{
QDomElement ele = materialList.at(i).toElement();
QString ssetid = ele.attribute("SetID");
QString smaterialID = ele.attribute("MaterialID");
int setid = ssetid.toInt();
int maid = smaterialID.toInt();
this->setMaterial(setid, maid);
}
QDomNodeList configdata = e->elementsByTagName("ConfigData");
if (configdata.size() == 1)
{
QDomElement cele = configdata.at(0).toElement();
QDomNodeList datalist = cele.elementsByTagName("Data");
for (int i = 0; i < datalist.size(); ++i)
{
QDomElement ele = datalist.at(i).toElement();
QString sid = ele.attribute("ID");
// QString sname = ele.attribute("TreeNode");
const int id = sid.toInt();
DataProperty::DataBase* d = new DataProperty::DataBase;
d->setModuleType(DataProperty::Module_Model);
d->setID(_id);
// d->setName(sname);
d->readParameters(&ele);
if (_configData.contains(id))
{
DataProperty::DataBase* dd = _configData.value(id);
if (dd != nullptr) delete dd;
}
_configData[id] = d;
}
}
QDomNodeList reportNodelist = e->elementsByTagName("Report");
if (reportNodelist.size() == 1)
{
QDomElement element = reportNodelist.at(0).toElement();
QDomNodeList pathlist = element.elementsByTagName("Path");
const int n = pathlist.size();
for (int i = 0; i < n; ++i)
{
QDomElement ele = pathlist.at(i).toElement();
QString p = ele.text();
_reportList.append(p);
}
}
this->registerObserver();
}
void ModelDataBaseExtend::writeToSolverXML(QDomDocument* doc, QDomElement* e)
{
this->writeToProjectFile(doc, e);
}
void ModelDataBaseExtend::setMaterial(int setID, int materialID)
{
if ((!_componentIDList.contains(setID)) || materialID <= 0) return;
_setMaterial[setID] = materialID;
}
int ModelDataBaseExtend::getMaterialID(int setid)
{
int m = -1;
if (_setMaterial.contains(setid))
{
m = _setMaterial.value(setid);
}
return m;
}
bool ModelDataBaseExtend::isMaterialSetted(int setid)
{
bool s = false;
if (_setMaterial.contains(setid))
{
if (_setMaterial.value(setid) >= 0)
s = true;
}
return s;
}
void ModelDataBaseExtend::removeMaterial(int setid)
{
if (_setMaterial.contains(setid))
{
_setMaterial.remove(setid);
}
}
void ModelDataBaseExtend::setMeshSetList(QList<int> ids)
{
QList<int> old = _componentIDList;
QList<int> removeid;
for (auto id : old)
if (!ids.contains(id)) removeid.append(id);
for (int id : removeid)
{
if (_setMaterial.contains(id))
_setMaterial.remove(id);
for (auto bc : _bcList)
{
if (bc->getMeshSetID() == id)
{
_bcList.removeOne(bc);
delete bc;
break;
}
}
}
ModelDataBase::setMeshSetList(ids);
}
void ModelDataBaseExtend::removeMeshSetAt(int index)
{
assert(index >= 0 && index < _componentIDList.size());
int id = _componentIDList.at(index);
if (isMaterialSetted(id))
{
removeMaterial(id);
}
ModelDataBase::removeMeshSetAt(index);
}
void ModelDataBaseExtend::copyFormConfig()
{
ConfigOption::DataConfig* dataconfig = ConfigOption::ConfigOption::getInstance()->getDataConfig();
QHash<int, DataProperty::DataBase*> configList = dataconfig->getConfigData(_treeType);
QList<int> ids = configList.keys();
for (int i = 0; i < ids.size(); ++i)
{
const int id = ids.at(i);
DataProperty::DataBase* d = configList.value(id);
DataProperty::DataBase* newdata = new DataProperty::DataBase;
newdata->setModuleType(DataProperty::Module_Model);
newdata->copy(d);
newdata->setID(_id);
_configData[id] = newdata;
}
_monitorFiles = dataconfig->getMonitorFile(_treeType);
// _monitorCurves = dataconfig->getMonitorCurves(_treeType);
ModelDataBase::copyFormConfig();
this->registerObserver();
}
QList<ConfigOption::PostCurve*> ModelDataBaseExtend::getMonitorCurves()
{
return _monitorCurves;
}
ConfigOption::PostCurve* ModelDataBaseExtend::getMonitorCurveAt(const int index)
{
assert(index >= 0 && index < _monitorCurves.size());
return _monitorCurves.at(index);
}
void ModelDataBaseExtend::appendConfigData(int dataID, DataProperty::DataBase* data)
{
if (data == nullptr) return;
if (_configData.contains(dataID))
{
DataProperty::DataBase* d = _configData.value(dataID);
delete d;
_configData.remove(dataID);
}
_configData[dataID] = data;
}
DataProperty::DataBase* ModelDataBaseExtend::getConfigData(int dataID)
{
return _configData.value(dataID);
}
int ModelDataBaseExtend::getConfigDataCount(){
return _configData.count();
}
// QString ModelDataBaseExtend::getMonitorList()
// {
// return _monitor;
// }
QStringList ModelDataBaseExtend::getMonitorFile()
{
return _monitorFiles;
}
QStringList ModelDataBaseExtend::getAbsoluteMonitorFile()
{
QStringList s;
QString path = this->getPath();
for (int i = 0; i < _monitorFiles.size(); ++i)
{
QString ss = path + "/MonitorFiles/" + _monitorFiles.at(i);
s.append(ss);
}
return s;
}
QStringList ModelDataBaseExtend::getMonitorVariables(QString f)
{
QStringList v;
for (int i = 0; i < _monitorCurves.size(); ++i)
{
ConfigOption::PostCurve* c = _monitorCurves.at(i);
QString file = c->getFile();
if (!f.endsWith(file)) continue;
QString x = c->getXVariable();
QString y = c->getYVariable();
if (!v.contains(x)) v.append(x);
if (!v.contains(y)) v.append(y);
}
return v;
}
QStringList ModelDataBaseExtend::getPost2DFiles()
{
ConfigOption::PostConfigInfo* info = ConfigOption::ConfigOption::getInstance()->getPostConfig()->getPostConfigInfo(_treeType);
QStringList s;
if (info != nullptr)
s = info->getPost2DFile();
return s;
}
QStringList ModelDataBaseExtend::getAbsolutePost2DFiles()
{
QStringList s = this->getPost2DFiles();
QStringList f;
QString path = this->getPath() + "/Result/";
for (int i = 0; i < s.size(); ++i)
{
f.append(path + s.at(i));
}
return f;
}
QStringList ModelDataBaseExtend::getPost2DVariables(QString f)
{
ConfigOption::PostConfigInfo* info = ConfigOption::ConfigOption::getInstance()->getPostConfig()->getPostConfigInfo(_treeType);
QStringList s;
if (info != nullptr)
s = info->get2DVariables(f);
return s;
}
QString ModelDataBaseExtend::getPost3DFile()
{
ConfigOption::PostConfigInfo* info = ConfigOption::ConfigOption::getInstance()->getPostConfig()->getPostConfigInfo(_treeType);
if (info != nullptr)
return info->getPost3DFile();
return "";
}
void ModelDataBaseExtend::get3DScalars(QStringList &node, QStringList &ele)
{
ConfigOption::PostConfigInfo* info = ConfigOption::ConfigOption::getInstance()->getPostConfig()->getPostConfigInfo(_treeType);
if (info != nullptr)
{
node = info->getNodeScalarVariable();
ele = info->getCellScalarVariable();
}
}
void ModelDataBaseExtend::get3DVector(QStringList &node, QStringList &ele)
{
ConfigOption::PostConfigInfo* info = ConfigOption::ConfigOption::getInstance()->getPostConfig()->getPostConfigInfo(_treeType);
if (info != nullptr)
{
node = info->getNodeVectorVariable();
ele = info->getCellVectorVariable();
}
}
void ModelDataBaseExtend::appendScalarVariable(QString v)
{
_scalarVariable.append(v);
}
void ModelDataBaseExtend::removeScalarVariable(int index)
{
if (index < 0 || index >= _scalarVariable.size()) return;
_scalarVariable.removeAt(index);
}
QStringList ModelDataBaseExtend::getScalarVariable()
{
return _scalarVariable;
}
void ModelDataBaseExtend::appendVectorVariable(QString v)
{
_vectorVariable.append(v);
}
void ModelDataBaseExtend::removeVectorVariable(int index)
{
if (index < 0 || index >= _vectorVariable.size()) return;
_vectorVariable.removeAt(index);
}
QStringList ModelDataBaseExtend::getVectorVariable()
{
return _vectorVariable;
}
void ModelDataBaseExtend::apppendPlotCurve(ConfigOption::PostCurve* c)
{
_postCurves.append(c);
}
QList<ConfigOption::PostCurve*> ModelDataBaseExtend::getPlotCurves()
{
return _postCurves;
}
void ModelDataBaseExtend::removePlotCurve(int index)
{
_postCurves.removeAt(index);
}
bool ModelDataBaseExtend::isPostCurveExist(QString name)
{
for (int i = 0; i < _postCurves.size(); ++i)
{
ConfigOption::PostCurve* c = _postCurves.at(i);
QString n = c->getDescribe();
if (n == name) return true;
}
return false;
}
void ModelDataBaseExtend::clearPlotCurve()
{
for (int i = 0; i < _postCurves.size(); ++i)
{
ConfigOption::PostCurve* c = _postCurves.at(i);
delete c;
}
_postCurves.clear();
}
void ModelDataBaseExtend::clear3DVariable()
{
_scalarVariable.clear();
_vectorVariable.clear();
}
DataProperty::ParameterBase* ModelDataBaseExtend::getParameterByName(QString name)
{
DataProperty::ParameterBase* P = nullptr;
P = ModelDataBase::getParameterByName(name);
if (P != nullptr) return P;
QList<DataProperty::DataBase*> dataList = _configData.values();
for (int i = 0; i < dataList.size(); ++i)
{
auto d = dataList.at(i);
P = d->getParameterByName(name);
if (P != nullptr)
break;
}
return P;
}
void ModelDataBaseExtend::removeParameter(DataProperty::ParameterBase* p)
{
QList<DataProperty::DataBase*> dataList = _configData.values();
for (int i = 0; i < dataList.size(); ++i)
{
auto d = dataList.at(i);
d->removeParameter(p);
}
ModelDataBase::removeParameter(p);
}
void ModelDataBaseExtend::removeParameterGroup(DataProperty::ParameterGroup* g)
{
QList<DataProperty::DataBase*> dataList = _configData.values();
for (int i = 0; i < dataList.size(); ++i)
{
auto d = dataList.at(i);
d->removeParameterGroup(g);
}
ModelDataBase::removeParameterGroup(g);
}
DataProperty::ParameterGroup* ModelDataBaseExtend::getParameterGroupByName(QString name)
{
DataProperty::ParameterGroup* g = nullptr;
g = ModelDataBase::getParameterGroupByName(name);
if (g != nullptr) return g;
QList<DataProperty::DataBase*> dataList = _configData.values();
for (int i = 0; i < dataList.size(); ++i)
{
auto d = dataList.at(i);
g = d->getParameterGroupByName(name);
if (g != nullptr)
break;
}
return g;
}
void ModelDataBaseExtend::registerObserver()
{
QList<ConfigOption::ParameterObserver*> obslist = ConfigOption::ConfigOption::getInstance()->getObseverConfig()->getObserverList(_treeType);
const int n = obslist.size();
for (int i = 0; i < n; ++i)
{
ConfigOption::ParameterObserver* obs = obslist.at(i)->copy();
if (obs == nullptr) continue;
_observerList.append(obs);
QStringList activePara = obs->getActiveParameterNames();
for (int i = 0; i < activePara.size(); ++i)
{
QString name = activePara.at(i);
qDebug() << name;
auto para = this->getParameterByName(name);
if (para == nullptr)
{
obs->removeConfigActive(name);
}
else
{
obs->appendDataActive(name, para);
para->appendObserver(obs);
}
}
QStringList followPara = obs->getFollowParameterNames();
for (int i = 0; i < followPara.size(); ++i)
{
QString name = followPara.at(i);
auto para = this->getParameterByName(name);
if (para == nullptr)
{
obs->removeConfigFollow(name);
}
else
obs->appendDataFollow(name, para);
}
QStringList followgroup = obs->getFollowGroupNames();
for (int i = 0; i < followgroup.size(); ++i)
{
QString name = followgroup.at(i);
auto para = this->getParameterGroupByName(name);
if (para == nullptr)
{
obs->removeConfigFollow(name);
}
else
obs->appendDataFollowGroup(name, para);
}
obs->observe();
}
}
void ModelDataBaseExtend::dataToStream(QDataStream* datas){
*datas << _name << _id << _treeType;
QList<DataProperty::DataBase*> datalist = _configData.values();
for (int i = 0; i < datalist.count();++i)
{
DataProperty::DataBase* data = datalist.at(i);
data->dataToStream(datas);
}
}
void ModelDataBaseExtend::generateParaInfo()
{
DataBase::generateParaInfo();
QList<DataProperty::DataBase*> datalist = _configData.values();
for (int i = 0; i < datalist.size(); ++i)
{
DataProperty::DataBase* data = datalist.at(i);
data->generateParaInfo();
}
ModelDataBase::generateParaInfo();
}
void ModelDataBaseExtend::setPost2DWindow(Post::Post2DWindowInterface* p2d)
{
_post2DWindow = p2d;
}
Post::Post2DWindowInterface* ModelDataBaseExtend::getPost2DWindow()
{
return _post2DWindow;
}
void ModelDataBaseExtend::setPost3DWindow(Post::Post3DWindowInterface* p3d)
{
_post3DWindow = p3d;
}
Post::Post3DWindowInterface* ModelDataBaseExtend::getPost3DWindow()
{
return _post3DWindow;
}
} | [
"l”ibaojunqd@foxmail.com“"
] | l”ibaojunqd@foxmail.com“ |
6669b36b7049a08583f258d5b9efbd2fd350d954 | f1bd4937a6b123107cfc3ac40c27f2cfad335be1 | /include/wrappers/fence.h | b60dd865ac08d90595429ed5ca101988f291947c | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | b0urb4k1/Anvil | ac66fedf9eaa23a8ef27724d3f4df2b5dff0e066 | fc2fbc61cee5da0c0eae1cda20a7b34c70784c78 | refs/heads/master | 2021-01-12T02:53:24.839902 | 2016-09-08T19:47:56 | 2016-09-08T19:47:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,378 | h | //
// Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/** Implements a wrapper for a single Vulkan fence. Implemented in order to:
*
* - simplify life-time management of fences.
* - simplify fence usage.
* - let ObjectTracker detect leaking fence instances.
*
* The wrapper is NOT thread-safe.
**/
#ifndef WRAPPERS_FENCE_H
#define WRAPPERS_FENCE_H
#include "misc/types.h"
namespace Anvil
{
/* Wrapper class for Vulkan fences */
class Fence
{
public:
/* Public functions */
/** TODO */
virtual ~Fence();
/** Creates a new Fence instance.
*
* Creates a single Vulkan fence instance and registers the object in Object Tracker.
*
* @param device_ptr Device to use.
* @param create_signalled true if the fence should be created as a signalled entity.
* False to make it unsignalled at creation time.
*/
static std::shared_ptr<Fence> create(std::weak_ptr<Anvil::Device> device_ptr,
bool create_signalled);
/** Retrieves a raw handle to the underlying Vulkan fence instance */
VkFence get_fence() const
{
return m_fence;
}
/** Retrieves a pointer to the raw handle to the underlying Vulkan fence instance */
const VkFence* get_fence_ptr()
{
m_possibly_set = true;
return &m_fence;
}
/** Tells whether the fence is signalled at the time of the call.
*
* @return true if the fence is set, false otherwise.
**/
bool is_set() const;
/** Resets the specified Vulkan Fence, if set. If the fence is not set, this function is a nop.
*
* @return true if the function executed successfully, false otherwise.
**/
bool reset();
/** Resets the specified number of Vulkan fences.
*
* This function is expected to be more efficient than calling reset() for @param n_fences
* times, assuming @param n_fences is larger than 1.
*
* @param n_fences Number of Fence instances accessible under @param fences.
* @param fences An array of @param n_fences Fence instances to reset. Must not be nullptr,
* unless @param n_fences is 0.
*
* @return true if the function executed successfully, false otherwise.
**/
static bool reset_fences(const uint32_t n_fences,
Fence* fences);
private:
/* Private functions */
/** Constructor.
*
* Please see documentation of create() for specification
*/
Fence(std::weak_ptr<Anvil::Device> device_ptr,
bool create_signalled);
Fence (const Fence&);
Fence& operator=(const Fence&);
void release_fence();
/* Private variables */
std::weak_ptr<Anvil::Device> m_device_ptr;
VkFence m_fence;
bool m_possibly_set;
};
}; /* namespace Anvil */
#endif /* WRAPPERS_FENCE_H */ | [
"jstewart-amd@users.noreply.github.com"
] | jstewart-amd@users.noreply.github.com |
43b591c79d9a4356e89638ffff07d6a5f8f66ec4 | 5c7fef617f91339715a3215cc7064012618b1354 | /03_ThirdVtk/ExampleOrg/qscalarstocolors.h | 76c09620a41264384a5d21c6674aaf4ab3441b83 | [] | no_license | dezbracaty/Qt-Vtk | bbe429fd87a9e90f72d7342fb98b9578fa25808d | d9f7597b680c41f5bec4efd472d1b58cecb1c2bd | refs/heads/master | 2023-08-26T10:31:50.961019 | 2021-08-18T08:36:01 | 2021-08-18T08:36:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,102 | h | #ifndef QSCALARSTOCOLORS_H
#define QSCALARSTOCOLORS_H
#include <QWidget>
#include "QVTKOpenGLNativeWidget.h" //新版本,旧版QVTKWidget
#include "vtkAutoInit.h"
#include "vtkChartXY.h"
#include "vtkColorTransferFunction.h"
#include "vtkCompositeTransferFunctionItem.h"
#include "vtkContextScene.h"
#include "vtkContextView.h"
#include "vtkFloatArray.h"
#include "vtkGenericOpenGLRenderWindow.h"
#include "vtkMath.h"
#include "vtkNew.h"
#include "vtkPiecewiseFunction.h"
#include "vtkPlot.h"
#include "vtkQtTableView.h"
#include "vtkRenderer.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkTimerLog.h"
#include <QResizeEvent>
namespace Ui {
class QScalarsToColors;
}
class QScalarsToColors : public QWidget
{
Q_OBJECT
public:
explicit QScalarsToColors(QWidget *parent = 0);
~QScalarsToColors();
void resizeEvent(QResizeEvent *event)override;
private:
Ui::QScalarsToColors *ui;
QVTKOpenGLNativeWidget *qvtkWidget = nullptr;
vtkNew<vtkGenericOpenGLRenderWindow> renderWindow;
vtkNew<vtkContextView> view;
};
#endif // QSCALARSTOCOLORS_H
| [
"Jianwei1992@foxmail.com"
] | Jianwei1992@foxmail.com |
df575214e84b0d57c111574e57f57d38be214e9b | 02c3e21f963e4801d89324e7214ed1cac2604ff7 | /uxn/patl/impl/algorithm.hpp | e1bf7cac13a3d84ce866c604ac80ed818ffe90a3 | [
"BSD-3-Clause"
] | permissive | jnorthrup/patl | 591f99509f8d355a6ebc2c6eaa5dd7ab4cb84f89 | 6409b0ae1fdb5d307662ac35602796b9bd54e762 | refs/heads/master | 2022-11-09T07:54:31.946130 | 2022-10-14T19:27:05 | 2022-10-14T19:27:05 | 2,289,901 | 25 | 12 | null | 2020-03-16T14:53:27 | 2011-08-29T17:17:30 | C++ | UTF-8 | C++ | false | false | 13,969 | hpp | /*-
| This source code is part of PATL (Practical Algorithm Template Library)
| Released under the BSD License (http://www.opensource.org/licenses/bsd-license.php)
| Copyright (c) 2005, 2007..2009, Roman S. Klyujkov (uxnuxn AT gmail.com)
|
| trie_set, trie_map, suffix_set, suffix_map template containers, v0.x
| Based on PATRICIA trie
| Key features: STL-compatible, high performance with non-scalar keys
| Compile with: MSVC 2003/2005/2008/2010, G++ 3.x
|
| algorithm P class template
-*/
#ifndef PATL_IMPL_ALGORITHM_HPP
#define PATL_IMPL_ALGORITHM_HPP
#include "../config.hpp"
#include "trivial.hpp"
namespace uxn
{
namespace patl
{
namespace impl
{
#define SELF static_cast<this_t*>(this)
#define CSELF static_cast<const this_t*>(this)
template <typename T, typename This, typename Container, word_t N = 0>
class algorithm_generic
: public algorithm_generic<T, This, Container, 0>
{
typedef This this_t;
typedef algorithm_generic<T, This, Container, 0> super;
public:
typedef Container cont_type;
typedef typename T::key_type key_type;
typedef typename T::value_type value_type;
typedef typename T::node_type node_type;
/// zero-init default ctor
explicit algorithm_generic(const cont_type *cont = 0)
: super(cont)
{
}
/// simple init ctor
algorithm_generic(const cont_type *cont, const node_type *q, word_t qid)
: super(cont, q, qid)
{
}
/// compact init ctor
algorithm_generic(const cont_type *cont, word_t qq)
: super(cont, qq)
{
}
/// one run of the classical algorithm P
void run(const key_type &key)
{
while (!CSELF->get_qtag())
{
// TODO
/*if ((get_p()->get_skip() >> N) != (get_q()->get_skip() >> N) &&
cont_->)
else*/
iterate_by_key(key);
}
}
/// one run of the classical algorithm P limited by prefix length
void run(const key_type &key, word_t prefixLen)
{
while (!CSELF->get_qtag() && CSELF->get_p()->get_skip() < prefixLen)
iterate_by_key(key);
}
};
/**
* Base class of algorithms & iterator's state store
* Algorithm P, described in Knuth's TAOCP, vol. 3, put in a basis
*/
template <typename T, typename This, typename Container>
class algorithm_generic<T, This, Container, 0>
{
typedef This this_t;
typedef typename T::bit_compare bit_compare;
typedef typename T::allocator_type allocator_type;
public:
typedef Container cont_type;
typedef typename T::key_type key_type;
typedef typename T::value_type value_type;
typedef typename T::node_type node_type;
private:
typedef const value_type *const_pointer;
typedef const value_type &const_reference;
typedef value_type *pointer;
typedef value_type &reference;
typedef word_t size_type;
public:
/// zero-init default ctor
explicit algorithm_generic(const cont_type *cont = 0)
: cont_(cont)
#ifdef PATL_ALIGNHACK
, qq_(0)
#else
, q_(0)
, qid_(0)
#endif
{
}
/// simple init ctor
algorithm_generic(const cont_type *cont, const node_type *q, word_t qid)
: cont_(cont)
#ifdef PATL_ALIGNHACK
, qq_(qid | reinterpret_cast<word_t>(q))
#else
, q_(const_cast<node_type*>(q))
, qid_(qid)
#endif
{
}
/// compact init ctor
algorithm_generic(const cont_type *cont, word_t qq)
: cont_(cont)
#ifdef PATL_ALIGNHACK
, qq_(qq)
#else
, q_(reinterpret_cast<node_type*>(qq & ~word_t(1)))
, qid_(qq & word_t(1))
#endif
{
}
/// return compact representation of algorithm state
word_t compact() const
{
return
#ifdef PATL_ALIGNHACK
qq_;
#else
qid_ | reinterpret_cast<word_t>(q_);
#endif
}
/// equality op
bool operator==(const this_t &right) const
{
return
#ifdef PATL_ALIGNHACK
qq_ == right.qq_;
#else
q_ == right.q_ && qid_ == right.qid_;
#endif
}
bool operator!=(const this_t &pal) const
{
return !(*this == pal);
}
/// return sibling of algorithm
this_t sibling() const
{
return CSELF->construct(get_q(), word_t(1) ^ get_qid());
}
/// toggle index i.e. convert algorithm to its sibling
void toggle()
{
#ifdef PATL_ALIGNHACK
qq_ ^= word_t(1);
#else
qid_ ^= word_t(1);
#endif
}
/// return real prefix length in bits
/// NOTE maybe it must be in node_generic
word_t get_prefix_length() const
{
return get_qtag() ? ~word_t(0) : get_p()->get_skip();
}
bit_compare bit_comp() const
{
return cont_->bit_comp();
}
/// this code guarantee amortized linear time for suffix indexing
word_t mismatch_suffix(
const key_type key,
/// number of bits in key that certainly match with one exists in trie
word_t skip)
{
const bit_compare bcmp = bit_comp();
// until we achieved the leaf
while (!get_qtag())
{
const word_t skip_cur = get_p()->get_skip();
if (skip <= skip_cur)
{
const key_type exist_key = CSELF->get_key();
for (; skip != skip_cur; ++skip)
{
// if we discover mismatch in bits - immediately return its number
if (bcmp.get_bit(key, skip) != bcmp.get_bit(exist_key, skip))
return skip;
}
++skip;
}
iterate_by_key(key);
}
return align_down<bit_compare::bit_size>(skip) +
bcmp.bit_mismatch(
key + skip / bit_compare::bit_size,
CSELF->get_key() + skip / bit_compare::bit_size);
}
#if 0 // obsolete
/// analogue to mismatch, for suffix_cont
template <bool Huge>
class mismatch_suffix;
/// classical algorithm P for search place for insert new node
template <>
class mismatch_suffix<false>
{
mismatch_suffix &operator=(const mismatch_suffix&);
public:
mismatch_suffix(this_t &pal)
: pal_(pal)
{
}
/**
* this code faster than one in mismatch_suffix<true>
* may used with small suffix_conts
*/
word_t operator()(
const key_type &key,
/// number of bits in key that certainly match with available in trie
word_t skip)
{
const bit_compare bit_comp = pal_.bit_comp();
// trie traverse to the leaves
pal_.run(key);
// compute skip as the number of first mismatching bit
skip = align_down<bit_compare::bit_size>(skip) +
bit_comp.bit_mismatch(
key + skip / bit_compare::bit_size,
pal_.get_key() + skip / bit_compare::bit_size);
// trie ascend to the inserting place
pal_.ascend(skip);
return skip; // new node mismatching bit number
}
private:
this_t &pal_;
};
#endif
/// function determine highest node back-referenced from current subtree; O(log n)
const node_type *get_subtree_node() const
{
const node_type
*cur = get_q(),
*parent = CSELF->get_parent(cur);
word_t id = get_qid();
while (
parent &&
id != bit_comp().get_bit(CSELF->get_key(cur), cur->get_skip()))
{
id = cur->get_parent_id();
cur = parent;
parent = CSELF->get_parent(cur);
}
return cur;
}
/// add new node into trie at current position; O(1)
void add(node_type *r, word_t b, word_t prefixLen)
{
// add new node into trie
CSELF->set_parentid(r, get_q(), get_qid());
if (!get_qtag())
CSELF->set_parentid(get_p(), r, word_t(1) ^ b);
CSELF->set_xlinktag(r, b, r, 1);
CSELF->set_xlinktag(r, word_t(1) ^ b, get_p(), get_qtag());
r->set_skip(prefixLen);
CSELF->set_xlinktag(get_q(), get_qid(), r, 0);
}
/**
* erase current node from trie; O(1)
* \return pointer to erased node for cleanup
*/
node_type *erase()
{
// p-node back-referenced from q-node (q-tag == 1)
// q- & p-node may be the same
node_type
*q = get_q(),
*p = get_p();
// p-brother is the sibling of p-node
const word_t
p_brother_id = word_t(1) ^ get_qid(),
p_brother_tag = q->get_xtag(p_brother_id);
node_type *p_brother = CSELF->get_xlink(q, p_brother_id);
// take the parent of q-node
const word_t q_parent_id = q->get_parent_id();
node_type *q_parent = CSELF->get_parent(q);
// if q-parent exist i.e. q-node isn't the root
if (q_parent)
{
// replace q-node with p-brother
CSELF->set_xlinktag(q_parent, q_parent_id, p_brother, p_brother_tag);
if (!p_brother_tag)
CSELF->set_parentid(p_brother, q_parent, q_parent_id);
}
// if p- & q-nodes is not the same
if (q != p)
{
// replace p-node with q-node
q->set_all_but_value(p);
// correct p-parent, if one exist
node_type *p_parent = CSELF->get_parent(p);
if (p_parent)
CSELF->set_xlinktag(p_parent, p->get_parent_id(), q, 0);
// correct p-node children
if (!p->get_xtag(0))
CSELF->set_parentid(CSELF->get_xlink(p, 0), q, 0);
if (!p->get_xtag(1))
CSELF->set_parentid(CSELF->get_xlink(p, 1), q, 1);
}
//
return p;
}
/// find node with nearest key and return the number of first mismatching bit
word_t mismatch(
const key_type &key,
word_t prefixLen = ~word_t(0))
{
const bit_compare bcmp(bit_comp());
const word_t len = get_min(prefixLen, bcmp.bit_length(key));
if (len == ~word_t(0))
run(key);
else
run(key, len);
const word_t l = bcmp.bit_mismatch(key, SELF->get_key());
if (l != ~word_t(0))
ascend(l);
return l;
}
/// ascend to parent node
void ascend()
{
node_type *q = get_q();
init(CSELF->get_parent(q), q->get_parent_id());
}
/// trie ascend to the lowest node whose prefix less or equal than prefix length
void ascend(sword_t prefixLen)
{
for (; static_cast<sword_t>(get_q()->get_skip()) > prefixLen; ascend()) ;
}
/// trie ascend to the lowest node whose prefix less than prefix length
void ascend_less(sword_t prefixLen)
{
for (; static_cast<sword_t>(get_q()->get_skip()) >= prefixLen; ascend()) ;
}
/// one run of the classical algorithm P
void run(const key_type &key)
{
while (!get_qtag())
iterate_by_key(key);
}
/// one run of the classical algorithm P limited by prefix length
void run(const key_type &key, word_t prefixLen)
{
while (!get_qtag() && get_p()->get_skip() < prefixLen)
iterate_by_key(key);
}
/// one iteration of the classical algorithm P
void iterate(word_t side)
{
init(get_p(), side);
}
/// one iteration of the classical algorithm P driven by given key
void iterate_by_key(const key_type &key)
{
iterate(bit_comp().get_bit(key, get_p()->get_skip()));
}
/// init function
void init(const node_type *q, word_t qid)
{
#ifdef PATL_ALIGNHACK
qq_ = qid | reinterpret_cast<word_t>(q);
#else
q_ = const_cast<node_type*>(q);
qid_ = qid;
#endif
}
/// compact init function
void init(word_t qq)
{
#ifdef PATL_ALIGNHACK
qq_ = qq;
#else
q_ = reinterpret_cast<node_type*>(qq & ~word_t(1));
qid_ = qq & word_t(1);
#endif
}
/// return p-node
const node_type *get_p() const
{
return CSELF->get_xlink(get_q(), get_qid());
}
node_type *get_p()
{
return CSELF->get_xlink(get_q(), get_qid());
}
/// return q-tag
word_t get_qtag() const
{
return get_q()->get_xtag(get_qid());
}
/// return q-node
const node_type *get_q() const
{
#ifdef PATL_ALIGNHACK
return reinterpret_cast<node_type*>(qq_ & ~word_t(1));
#else
return q_;
#endif
}
node_type *get_q()
{
#ifdef PATL_ALIGNHACK
return reinterpret_cast<node_type*>(qq_ & ~word_t(1));
#else
return q_;
#endif
}
/// return distiction bit
word_t get_qid() const
{
#ifdef PATL_ALIGNHACK
return qq_ & word_t(1);
#else
return qid_;
#endif
}
bool the_end() const
{
const node_type *q = get_q();
return get_qid() && !(q && CSELF->get_parent(q));
}
const cont_type *cont() const
{
return cont_;
}
protected:
const cont_type *cont_;
private:
#ifdef PATL_ALIGNHACK
/// compact representation of algorithm state with distinction bit in lsb
word_t qq_;
#else
/// q-node
node_type *q_;
/// distinction bit
word_t qid_;
#endif
};
#undef SELF
#undef CSELF
} // namespace impl
} // namespace patl
} // namespace uxn
#endif
| [
"uxnuxn@ac5c578c-d34d-0410-9547-55c0b358f148"
] | uxnuxn@ac5c578c-d34d-0410-9547-55c0b358f148 |
eb21a629dfd1e63a23eba44a279ae3d3612b8e10 | 9461d901b55f46bd4f0b64b8bfb2b2dfddf593f1 | /Book/problem_solving/ch14_1/main.cpp | 4d5d0a5db46e7aadc902ec5afaa1cfdf890adda6 | [
"MIT"
] | permissive | coder137/CPP-Repo | e50f03443a4a50e2c74991badeee53778ca9791b | caa06829195f9ab3fc35b312ecc7db1ebcaf26c7 | refs/heads/master | 2022-03-09T07:34:58.212073 | 2022-03-02T06:36:04 | 2022-03-02T06:36:04 | 193,908,386 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,067 | cpp | #include <iostream>
#include <vector>
using namespace std;
/// [printVector]
void printVector(const vector<int> &list)
{
cout << "[";
for (int v : list)
{
cout << v << ",";
}
cout << "]" << endl;
}
/// Without passing mid, low OR high values
/// index if found
/// -1 if not found
int binarySearch(const vector<int> &list, int value, int offset = 0)
{
int first = 0;
int last = list.size() - 1;
// Vector is empty
if (last < 0)
return -1;
int mid = first + last / 2;
int check = list[mid];
cout << mid << endl;
if (value == check)
return offset + mid;
if (value > check)
first = mid + 1;
else
last = mid - 1;
// Make a new vector
vector<int> v;
for (int i = first; i <= last; i++)
{
v.push_back(list[i]);
}
// ? debugging (print vector)
printVector(v);
return binarySearch(v, value, first + offset);
}
int main()
{
vector<int> orderedList = {0, 3, 5, 9, 24, 45, 59, 123, 569, 123545};
int binaryIndex = binarySearch(orderedList, 45);
cout << "Index: " << binaryIndex << endl;
}
| [
"coder137@gmail.com"
] | coder137@gmail.com |
cd5862fd33f45fdaedfd4595c91e3f0fa584a2b6 | 98f1081af58b5099ef3b3a8fb0706da89c707d05 | /arduino/version07/maya/fakeCounter.h | 4d895ac73b4cf0138895c4225997c45ce0fbb341 | [] | no_license | MrPerfekt/Maya | d143044d724091bc07cacd660f67dc3e12a8b6d4 | bea5f28d08ee1d0fab12a43a53d082ce1380f014 | refs/heads/master | 2021-01-11T18:49:24.908076 | 2017-01-21T10:02:13 | 2017-01-21T10:02:13 | 79,633,767 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 238 | h | #ifndef FAKE_COUNTER
#define FAKE_COUNTER
#include "Arduino.h"
#include "positionerCounter.h"
class FakeCounter : public PositionerCounter {
public:
FakeCounter(void (*notifyFunction)());
void init();
void update();
};
#endif
| [
"grubi@edumail.at"
] | grubi@edumail.at |
1e93a0bc3dc587dfba6c0ecddce2abfcf7ea4d74 | c0b38d5a55b4789efcf149496c2570085d3cf617 | /dyplsapi/src/model/ReleaseSecretNoRequest.cc | 794519a4051807961a423ae2f7ebe566877073c4 | [
"Apache-2.0"
] | permissive | wuwenfeng09/aliyun-openapi-cpp-sdk | a14a2ddb0a5f24a2228cf4362a3416c9e2d5179a | 3b52186538a98794dcaaa1596a6921e389aafe05 | refs/heads/master | 2021-01-03T07:16:09.867302 | 2020-02-12T01:43:06 | 2020-02-12T01:43:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,494 | cc | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/dyplsapi/model/ReleaseSecretNoRequest.h>
using AlibabaCloud::Dyplsapi::Model::ReleaseSecretNoRequest;
ReleaseSecretNoRequest::ReleaseSecretNoRequest() :
RpcServiceRequest("dyplsapi", "2017-05-25", "ReleaseSecretNo")
{
setMethod(HttpRequest::Method::Post);
}
ReleaseSecretNoRequest::~ReleaseSecretNoRequest()
{}
long ReleaseSecretNoRequest::getResourceOwnerId()const
{
return resourceOwnerId_;
}
void ReleaseSecretNoRequest::setResourceOwnerId(long resourceOwnerId)
{
resourceOwnerId_ = resourceOwnerId;
setCoreParameter("ResourceOwnerId", std::to_string(resourceOwnerId));
}
std::string ReleaseSecretNoRequest::getResourceOwnerAccount()const
{
return resourceOwnerAccount_;
}
void ReleaseSecretNoRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount)
{
resourceOwnerAccount_ = resourceOwnerAccount;
setCoreParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
long ReleaseSecretNoRequest::getOwnerId()const
{
return ownerId_;
}
void ReleaseSecretNoRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setCoreParameter("OwnerId", std::to_string(ownerId));
}
std::string ReleaseSecretNoRequest::getAccessKeyId()const
{
return accessKeyId_;
}
void ReleaseSecretNoRequest::setAccessKeyId(const std::string& accessKeyId)
{
accessKeyId_ = accessKeyId;
setCoreParameter("AccessKeyId", accessKeyId);
}
std::string ReleaseSecretNoRequest::getPoolKey()const
{
return poolKey_;
}
void ReleaseSecretNoRequest::setPoolKey(const std::string& poolKey)
{
poolKey_ = poolKey;
setCoreParameter("PoolKey", poolKey);
}
std::string ReleaseSecretNoRequest::getSecretNo()const
{
return secretNo_;
}
void ReleaseSecretNoRequest::setSecretNo(const std::string& secretNo)
{
secretNo_ = secretNo;
setCoreParameter("SecretNo", secretNo);
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
9628abf7ea0ebb9598144d3779edc62622e264c2 | 356ca0e5d593832f6b766ce70a7edb209d463b23 | /oxref/store/insert.cc | 03ae6fd30e855d5f5ff0a59733eb82cfb2d0c62f | [] | no_license | fbb-git/oxref | dc5631033953b1b5b7a7fbf4a2120340da5d1e9b | 60bddcf36617cc34612becddb6ae1e83b71a29b7 | refs/heads/master | 2021-05-04T06:34:33.369266 | 2018-06-25T12:59:56 | 2018-06-25T12:59:56 | 41,297,715 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 990 | cc | #include "store.ih"
void Store::insert(ostream &out, string const &name, bool doSelect) const
{
auto iter = d_defIdx.begin();
auto end = d_defIdx.end();
Pattern namePattern;
if (not doSelect)
namePattern.setPattern(name);
while (true)
{
iter = doSelect ?
find_if(
iter, end,
[&](size_t idx)
{
return string(d_xrefData[idx].name()).find(name)
== 0;
}
)
:
find_if(
iter, end,
[&](size_t idx)
{
return namePattern << d_xrefData[idx].symbol();
}
);
if (iter == end)
break;
insertDefined(*iter, out, d_xrefData);
++iter;
}
}
| [
"f.b.brokken@rug.nl"
] | f.b.brokken@rug.nl |
ede49cda94ec2ef4001962d82948d4165d7d8f5f | a1470adb693157d40289caf586e14d5e441a4c96 | /자습/99.혼자 공부/STL -Leet code/1.cpp | ce89893994b77e40730d8f2a063bc7fabd256432 | [] | no_license | Catoblespa/MyVSC_Note | 2ac43750febfc201c0c87f4718b6d2e69c4d8e1a | 64056a66c46dcb2ceb38571f8b318735dd22d87d | refs/heads/master | 2020-05-24T07:49:51.374911 | 2019-11-15T10:52:11 | 2019-11-15T10:52:11 | 187,169,913 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,801 | cpp | #include <iostream>
#include <time.h>
#include <string>
#include <vector> //STL Vector
#include <list> //STL List
#include <algorithm> //STL 알고리즘 헤더
#include <functional> //STL 전역 함수 헤더
#include <iterator> //여러 종류의 반복자의 정의 담음.
#include <deque> //STL deque 정의 헤더
#include <set> //STL 연관컨테이너 set
#include <map> //STL 연관컨테이너 map
#include <stack> //STL 컨테이너 어댑터 stack
#include <queue> ////STL 컨테이너 어댑터 queue
#include <array>
#include <numeric> //수치 관련 알고리즘 . STL이 아닌 C+라이브러리에 포함되어 있다.
#define randomize() srand((unsigned)time(NULL)) // srand 매크로
#define random(n) (rand() % (n)) // rand 매크로.
using namespace std;
/*
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1]
*/
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> temp;
int iA=-1, iB=-1;
for (int i = 0; i < nums.size(); i++)
{
for (int j = i+1; j < nums.size(); j++)
{
if (target == nums[i] + nums[j])
{
iA = i;
iB = j;
//cout << iA << ", " << iB << endl;
break;
}
}
}
if (-1 == iA)
{
cout << "찾을 수 없음" << endl;
}
temp.push_back(nums[iA]);
temp.push_back(nums[iB]);
return temp;
}
int main()
{
vector<int> vi;
vi.push_back(2);
vi.push_back(7);
vi.push_back(11);
vi.push_back(15);
vector<int> sum = twoSum(vi, 9);
cout << sum[0] << "+" << sum[1] << ":" << sum[0] + sum[1] << endl;
return 0;
} | [
"a4ka2@naver.com"
] | a4ka2@naver.com |
6a31a60e590ccb1f560a81eb87ddb927c5757c82 | 51f741281bbb358a66d85619a84f71edab8ed755 | /src/zmq/zmqpublishnotifier.cpp | 392b9c7ceb6dbc91d91be01baf3e234504c703a6 | [
"MIT"
] | permissive | Mythicaler/Smartcoin-core | d345ba934d041af378ca723b458c2cf232373196 | b71825c9501a7782b146d613cf1cc0ea0a22da8a | refs/heads/master | 2020-04-06T17:04:30.388678 | 2018-12-03T09:09:17 | 2018-12-03T09:09:17 | 157,645,583 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,531 | cpp | // Copyright (c) 2015 The Bitcoin Core 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 "zmqpublishnotifier.h"
#include "validation.h"
#include "util.h"
#include "rpc/server.h"
static std::multimap<std::string, CZMQAbstractPublishNotifier*> mapPublishNotifiers;
static const char *MSG_HASHBLOCK = "hashblock";
static const char *MSG_HASHTX = "hashtx";
static const char *MSG_RAWBLOCK = "rawblock";
static const char *MSG_RAWTX = "rawtx";
// Internal function to send multipart message
static int zmq_send_multipart(void *sock, const void* data, size_t size, ...)
{
va_list args;
va_start(args, size);
while (1)
{
zmq_msg_t msg;
int rc = zmq_msg_init_size(&msg, size);
if (rc != 0)
{
zmqError("Unable to initialize ZMQ msg");
return -1;
}
void *buf = zmq_msg_data(&msg);
memcpy(buf, data, size);
data = va_arg(args, const void*);
rc = zmq_msg_send(&msg, sock, data ? ZMQ_SNDMORE : 0);
if (rc == -1)
{
zmqError("Unable to send ZMQ msg");
zmq_msg_close(&msg);
return -1;
}
zmq_msg_close(&msg);
if (!data)
break;
size = va_arg(args, size_t);
}
return 0;
}
bool CZMQAbstractPublishNotifier::Initialize(void *pcontext)
{
assert(!psocket);
// check if address is being used by other publish notifier
std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator i = mapPublishNotifiers.find(address);
if (i==mapPublishNotifiers.end())
{
psocket = zmq_socket(pcontext, ZMQ_PUB);
if (!psocket)
{
zmqError("Failed to create socket");
return false;
}
int rc = zmq_bind(psocket, address.c_str());
if (rc!=0)
{
zmqError("Failed to bind address");
zmq_close(psocket);
return false;
}
// register this notifier for the address, so it can be reused for other publish notifier
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
else
{
LogPrint("zmq", "zmq: Reusing socket for address %s\n", address);
psocket = i->second->psocket;
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
}
void CZMQAbstractPublishNotifier::Shutdown()
{
assert(psocket);
int count = mapPublishNotifiers.count(address);
// remove this notifier from the list of publishers using this address
typedef std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator iterator;
std::pair<iterator, iterator> iterpair = mapPublishNotifiers.equal_range(address);
for (iterator it = iterpair.first; it != iterpair.second; ++it)
{
if (it->second==this)
{
mapPublishNotifiers.erase(it);
break;
}
}
if (count == 1)
{
LogPrint("zmq", "Close socket at address %s\n", address);
int linger = 0;
zmq_setsockopt(psocket, ZMQ_LINGER, &linger, sizeof(linger));
zmq_close(psocket);
}
psocket = 0;
}
bool CZMQAbstractPublishNotifier::SendMessage(const char *command, const void* data, size_t size)
{
assert(psocket);
/* send three parts, command & data & a LE 4byte sequence number */
unsigned char msgseq[sizeof(uint32_t)];
WriteLE32(&msgseq[0], nSequence);
int rc = zmq_send_multipart(psocket, command, strlen(command), data, size, msgseq, (size_t)sizeof(uint32_t), (void*)0);
if (rc == -1)
return false;
/* increment memory only sequence number after sending */
nSequence++;
return true;
}
bool CZMQPublishHashBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
uint256 hash = pindex->GetBlockHash();
LogPrint("zmq", "zmq: Publish hashblock %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHBLOCK, data, 32);
}
bool CZMQPublishHashTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint("zmq", "zmq: Publish hashtx %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHTX, data, 32);
}
bool CZMQPublishRawBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
LogPrint("zmq", "zmq: Publish rawblock %s\n", pindex->GetBlockHash().GetHex());
const Consensus::Params& consensusParams = Params().GetConsensus();
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
{
LOCK(cs_main);
CBlock block;
if(!ReadBlockFromDisk(block, pindex, consensusParams))
{
zmqError("Can't read block from disk");
return false;
}
ss << block;
}
return SendMessage(MSG_RAWBLOCK, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint("zmq", "zmq: Publish rawtx %s\n", hash.GetHex());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ss << transaction;
return SendMessage(MSG_RAWTX, &(*ss.begin()), ss.size());
}
| [
"senior.dev32@gmail.com"
] | senior.dev32@gmail.com |
f608f93edd3f02007e8b8afa43b228f49795de24 | 5f838b81ed9ebd2cfeb26d41b76d3002c0184682 | /sdk/src/ble/gap/blegapcommand.h | 1160637b23f8f4ff8266f8b264b775b7df6c8bc8 | [] | no_license | tamvh/vng | 655db7654450cab087bc18fef14c2be83ae59985 | 6fa94cc468dd3d3a9d50df9bbfdf840fbc8b53e9 | refs/heads/master | 2021-06-10T19:13:42.156093 | 2017-02-13T09:30:18 | 2017-02-13T09:30:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 276 | h | #ifndef BLEGAPCOMMAND_H
#define BLEGAPCOMMAND_H
#include <core/corecommand.h>
namespace iot {
namespace ble {
namespace gap {
class Command: public core::Command
{
public:
Command();
};
} // namespace gap
} // namespace ble
} // namespace iot
#endif // BLEGAPCOMMAND_H
| [
"huytamuit@gmail.com"
] | huytamuit@gmail.com |
c73fd4a0cdd2981763b40bf1e925845abf5bb455 | 353b92f9866fa6b63af9e2c85354cb6531964912 | /Structural/Boost.KeyValueFlyweight/key_value_flyweights.cpp | fccb7e5f13b4278219fcbf19b5f1b9ba3ce0f751 | [] | no_license | Pi03k/cpp-dp | c090edc47c05572c714a9dd8df417d550336c749 | 56cf244ef3408d3a05623e597185397d18c5177a | refs/heads/master | 2021-05-07T14:53:01.688002 | 2017-11-09T09:05:27 | 2017-11-10T15:05:40 | 109,949,455 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,195 | cpp | #include <boost/flyweight.hpp>
#include <boost/flyweight/key_value.hpp>
#include <iostream>
#include <iterator>
#include <random>
#include <vector>
using namespace std;
using namespace boost;
using Bitmap = vector<char>;
class Sprite
{
Bitmap bitmap_;
const string filename_;
public:
Sprite(const string& filename) : filename_{ filename }
{
cout << "Creating a sprite: " << filename_ << endl;
load_from_file();
}
void render(int x, int y) const
{
cout << "rendering ";
copy(bitmap_.begin(), bitmap_.end(), ostream_iterator<char>{ cout });
cout << " mem_address(" << this << ") at " << x << ", " << y << endl;
}
const string& filename() const
{
return filename_;
}
private:
void load_from_file()
{
copy(filename_.begin(), filename_.end(), back_inserter(bitmap_));
}
};
struct SpriteKeyExtractor
{
const string& operator()(const Sprite& s) const
{
return s.filename();
}
};
using SpriteFlyweight = flyweight<flyweights::key_value<string, Sprite, SpriteKeyExtractor> >;
constexpr const char* filenames[] = { "%", "#", "@" };
class GameBoard
{
vector<SpriteFlyweight> sprites_;
const int sprites_count_;
public:
GameBoard(int sprites_count) : sprites_count_{ sprites_count }
{
}
void init_sprites(int seed)
{
cout << "Initializing sprites on board:\n";
mt19937_64 rnd_engine{ seed };
uniform_int_distribution<> rnd_gen{ 0, 2 };
for (int i = 0; i < sprites_count_; ++i)
{
int index = rnd_gen(rnd_engine);
sprites_.emplace_back(filenames[index]);
}
}
void render(int seed)
{
mt19937_64 rnd_engine{ seed };
uniform_int_distribution<> rnd_gen{ 0, 100 };
for (const Sprite& sprite : sprites_)
{
int x = rnd_gen(rnd_engine);
int y = rnd_gen(rnd_engine);
sprite.render(x, y);
}
}
};
int main()
{
GameBoard game_board(20);
game_board.init_sprites(13);
cout << "\n\n";
game_board.render(665);
cout << "\n\n";
game_board.render(665);
}
| [
"pi03k87@gmail.com"
] | pi03k87@gmail.com |
4dd93a7b7169932cba76e0d143cf4fc165f759c3 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/base/cluster/resdll/spooler/splsvc/splsvc.cxx | b92816e75906c301d31143120717318842d2bcb8 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 48,940 | cxx | /*++
Copyright (c) 1992-1997 Microsoft Corporation
All rights reserved.
Module Name:
splsvc.c
Abstract:
Resource DLL for Spooler
Author:
Albert Ting (albertt) 17-Sept-1996
Based on resdll\genapp
Revision History:
--*/
#include "precomp.hxx"
#pragma hdrstop
#include "splsvc.hxx"
#include "spooler.hxx"
#include "clusinfo.hxx"
#include "cleanup.hxx"
#include "clusrtl.h"
MODULE_DEBUG_INIT( DBG_ERROR|DBG_WARN|DBG_TRACE, DBG_ERROR );
#define MAX_SPOOLER 60
#define MAX_GROUP_NAME_LENGTH 120
#define SPOOLER_TERMINATE // Kill the spooler on terminate if pending offline.
#define SplSvcLogEvent ClusResLogEvent
#define SplSvcSetResourceStatus ClusResSetResourceStatus
#define NET_NAME_RESOURCE_NAME CLUS_RESTYPE_NAME_NETNAME
#define PARAM_NAME__DEFAULTSPOOLDIRECTORY CLUSREG_NAME_PRTSPOOL_DEFAULT_SPOOL_DIR
#define PARAM_NAME__JOBCOMPLETIONTIMEOUT CLUSREG_NAME_PRTSPOOL_TIMEOUT
#define KEY_NAME__DEFAULTSPOOLDIRECTORY L"Printers"
#define KEY_NAME__JOBCOMPLETIONTIMEOUT NULL
#define PARAM_MIN__JOBCOMPLETIONTIMEOUT 0
#define PARAM_MAX__JOBCOMPLETIONTIMEOUT ((DWORD) -1)
#define PARAM_DEFAULT_JOBCOMPLETIONTIMEOUT 160
typedef struct _SPOOLER_PARAMS {
LPWSTR DefaultSpoolDirectory;
DWORD JobCompletionTimeout;
} SPOOLER_PARAMS, *PSPOOLER_PARAMS;
//
// Properties
//
RESUTIL_PROPERTY_ITEM
SplSvcResourcePrivateProperties[] = {
{ PARAM_NAME__DEFAULTSPOOLDIRECTORY, KEY_NAME__DEFAULTSPOOLDIRECTORY, CLUSPROP_FORMAT_SZ, 0, 0, 0, RESUTIL_PROPITEM_REQUIRED, FIELD_OFFSET(SPOOLER_PARAMS,DefaultSpoolDirectory) },
{ PARAM_NAME__JOBCOMPLETIONTIMEOUT, KEY_NAME__JOBCOMPLETIONTIMEOUT, CLUSPROP_FORMAT_DWORD, PARAM_DEFAULT_JOBCOMPLETIONTIMEOUT, PARAM_MIN__JOBCOMPLETIONTIMEOUT, PARAM_MAX__JOBCOMPLETIONTIMEOUT, 0, FIELD_OFFSET(SPOOLER_PARAMS,JobCompletionTimeout) },
{ 0 }
};
//
// Lock to protect the ProcessInfo table
//
CRITICAL_SECTION gProcessLock;
//
// Global count of spooler resource instances.
//
UINT gcSpoolerInfo;
extern CLRES_FUNCTION_TABLE SplSvcFunctionTable;
#define PSPOOLERINFO_FROM_RESID(resid) ((PSPOOLER_INFORMATION)resid)
#define RESID_FROM_SPOOLERINFO(pSpoolerInfo) ((RESID)pSpoolerInfo)
//
// Forward prototypes.
//
#ifdef __cplusplus
extern "C"
#endif
BOOLEAN
WINAPI
SplSvcDllEntryPoint(
IN HINSTANCE DllHandle,
IN DWORD Reason,
IN LPVOID Reserved
);
RESID
WINAPI
SplSvcOpen(
IN LPCWSTR ResourceName,
IN HKEY ResourceKey,
IN RESOURCE_HANDLE ResourceHandle
);
VOID
WINAPI
SplSvcClose(
IN RESID Resid
);
DWORD
WINAPI
SplSvcOnline(
IN RESID Resid,
IN OUT PHANDLE EventHandle
);
DWORD
WINAPI
SplSvcOffline(
IN RESID Resid
);
VOID
WINAPI
SplSvcTerminate(
IN RESID Resource
);
BOOL
WINAPI
SplSvcIsAlive(
IN RESID Resource
);
BOOL
WINAPI
SplSvcLooksAlive(
IN RESID Resource
);
DWORD
SplSvcGetPrivateResProperties(
IN OUT PSPOOLER_INFORMATION ResourceEntry,
OUT PVOID OutBuffer,
IN DWORD OutBufferSize,
OUT LPDWORD BytesReturned
);
DWORD
SplSvcValidatePrivateResProperties(
IN OUT PSPOOLER_INFORMATION ResourceEntry,
IN PVOID InBuffer,
IN DWORD InBufferSize,
OUT PSPOOLER_PARAMS Params
);
DWORD
SplSvcSetPrivateResProperties(
IN OUT PSPOOLER_INFORMATION ResourceEntry,
IN PVOID InBuffer,
IN DWORD InBufferSize
);
PSPOOLER_INFORMATION
pNewSpoolerInfo(
LPCTSTR pszResource,
RESOURCE_HANDLE ResourceHandle,
PSET_RESOURCE_STATUS_ROUTINE SetResourceStatus,
PLOG_EVENT_ROUTINE LogEvent
)
{
PSPOOLER_INFORMATION pSpoolerInfo = NULL;
LPTSTR pszResourceNew = NULL;
pSpoolerInfo = (PSPOOLER_INFORMATION)LocalAlloc(
LPTR,
sizeof( SPOOLER_INFORMATION ));
if( !pSpoolerInfo ){
goto Fail;
}
pszResourceNew = (LPTSTR)LocalAlloc(
LMEM_FIXED,
( lstrlen( pszResource ) + 1 )
* sizeof( TCHAR ));
if( !pszResourceNew ){
goto Fail;
}
StringCchCopy(pszResourceNew,
lstrlen(pszResource) + 1,
pszResource );
pSpoolerInfo->pfnLogEvent = LogEvent;
pSpoolerInfo->ResourceHandle = ResourceHandle;
pSpoolerInfo->pfnSetResourceStatus = SetResourceStatus;
pSpoolerInfo->pszResource = pszResourceNew;
pSpoolerInfo->pszName = NULL;
pSpoolerInfo->pszAddress = NULL;
return pSpoolerInfo;
Fail:
if( pszResourceNew ){
LocalFree( (HLOCAL)pszResourceNew );
}
if( pSpoolerInfo ){
LocalFree( (HLOCAL)pSpoolerInfo );
}
return NULL;
}
VOID
vDeleteSpoolerInfo(
PSPOOLER_INFORMATION pSpoolerInfo
)
{
if( !pSpoolerInfo ){
return;
}
SPLASSERT( !pSpoolerInfo->cRef );
//
// Shut down everything.
//
if( pSpoolerInfo->pszName ){
LocalFree( (HLOCAL)pSpoolerInfo->pszName );
}
if( pSpoolerInfo->pszAddress ){
LocalFree( (HLOCAL)pSpoolerInfo->pszAddress );
}
if( pSpoolerInfo->pszResource ){
LocalFree( (HLOCAL)pSpoolerInfo->pszResource );
}
LocalFree( (HLOCAL)pSpoolerInfo );
}
BOOL
Init(
VOID
)
{
BOOL bRet = FALSE;
if(bRet = InitializeCriticalSectionAndSpinCount(&gProcessLock,0x80000000))
{
bRet = bSplLibInit();
}
return bRet;
}
BOOLEAN
WINAPI
SplSvcDllEntryPoint(
IN HINSTANCE DllHandle,
IN DWORD Reason,
IN LPVOID Reserved
)
{
UNREFERENCED_PARAMETER(DllHandle);
UNREFERENCED_PARAMETER(Reserved);
switch( Reason ) {
case DLL_PROCESS_ATTACH:
if( !Init() ){
DBGMSG( DBG_ERROR, ( "DllEntryPoint: failed to init\n" ));
return FALSE;
}
break;
case DLL_PROCESS_DETACH:
DeleteCriticalSection(&gProcessLock);
break;
default:
break;
}
return TRUE;
}
/********************************************************************
Required exports and function table entries used by clustering.
********************************************************************/
/********************************************************************
Resource DLL functions.
********************************************************************/
BOOL
bSplRegCopyTree(
IN HKEY hClusterKey,
IN HKEY hLocalKey
)
/*++
Routine Description:
Recursives copies every key and value from under hLocalKey to hClusterKey
Arguments:
hClusterKey - handle to the cluster registry (destination)
hLocalKey - handle to the local registry (source)
Return Value:
TRUE - success
FALSE - failure
--*/
{
BOOL bStatus = FALSE;
DWORD dwError, dwIndex, cbValueName, cbData, cbKeyName, dwType;
DWORD cbMaxSubKeyLen, cbMaxValueNameLen, cValues, cSubKeys, cbMaxValueLen;
LPBYTE lpValueName = NULL, lpData = NULL, lpKeyName = NULL;
HKEY hLocalSubKey = NULL, hClusterSubKey = NULL;
//
// Retrieve the max buffer sizes required for the copy
//
dwError = RegQueryInfoKey( hLocalKey, NULL, NULL, NULL, &cSubKeys,
&cbMaxSubKeyLen, NULL, &cValues,
&cbMaxValueNameLen, &cbMaxValueLen,
NULL, NULL );
if( dwError ){
SetLastError( dwError );
goto CleanUp;
}
//
// Add for the terminating NULL character
//
++cbMaxSubKeyLen;
++cbMaxValueNameLen;
//
// Allocate the buffers
//
lpValueName = (LPBYTE) LocalAlloc( LMEM_FIXED, cbMaxValueNameLen * sizeof(WCHAR) );
lpData = (LPBYTE) LocalAlloc( LMEM_FIXED, cbMaxValueLen );
lpKeyName = (LPBYTE) LocalAlloc( LMEM_FIXED, cbMaxSubKeyLen * sizeof(WCHAR) );
if( !lpValueName || !lpData || !lpKeyName){
goto CleanUp;
}
//
// Copy all the values in the current key
//
for (dwIndex = 0; dwIndex < cValues; ++ dwIndex) {
cbValueName = cbMaxValueNameLen;
cbData = cbMaxValueLen;
//
// Retrieve the value name and the data
//
dwError = RegEnumValue( hLocalKey, dwIndex, (LPWSTR) lpValueName, &cbValueName,
NULL, &dwType, lpData, &cbData );
if( dwError ){
SetLastError( dwError );
goto CleanUp;
}
//
// Set the value in the cluster registry
//
dwError = ClusterRegSetValue( hClusterKey, (LPWSTR) lpValueName, dwType,
lpData, cbData );
if( dwError ){
SetLastError( dwError );
goto CleanUp;
}
}
//
// Recursively copies all the subkeys
//
for (dwIndex = 0; dwIndex < cSubKeys; ++ dwIndex) {
cbKeyName = cbMaxSubKeyLen;
//
// Retrieve the key name
//
dwError = RegEnumKeyEx( hLocalKey, dwIndex, (LPWSTR) lpKeyName, &cbKeyName,
NULL, NULL, NULL, NULL );
if( dwError ){
SetLastError( dwError );
goto CleanUp;
}
//
// Open local subkey
//
if( dwError = RegOpenKeyEx( hLocalKey, (LPWSTR) lpKeyName, 0,
KEY_READ, &hLocalSubKey ) ){
SetLastError( dwError );
goto CleanUp;
}
//
// Create the cluster subkey
//
if(( dwError = ClusterRegOpenKey( hClusterKey, (LPWSTR) lpKeyName,
KEY_READ|KEY_WRITE,
&hClusterSubKey)) == ERROR_FILE_NOT_FOUND )
{
if( dwError = ClusterRegCreateKey( hClusterKey, (LPWSTR) lpKeyName,
0,KEY_READ|KEY_WRITE,
NULL, &hClusterSubKey, NULL ) )
{
SetLastError( dwError );
goto CleanUp;
}
}
//
// Copy the subkey tree
//
if( !bSplRegCopyTree( hClusterSubKey, hLocalSubKey ) ){
goto CleanUp;
}
//
// Close the registry handle
//
RegCloseKey( hLocalSubKey );
ClusterRegCloseKey( hClusterSubKey );
hLocalSubKey = NULL;
hClusterSubKey = NULL;
}
bStatus = TRUE;
CleanUp:
if( lpValueName ){
LocalFree( lpValueName );
}
if( lpData ){
LocalFree( lpData );
}
if( lpKeyName ){
LocalFree( lpKeyName );
}
if( hLocalSubKey ){
RegCloseKey( hLocalSubKey );
}
if( hClusterSubKey ){
ClusterRegCloseKey( hClusterSubKey );
}
return bStatus;
}
BOOL
bUpdateRegPort(
IN HKEY hClusterKey,
OUT LPBOOL pbRegUpdated
)
/*++
Routine Description:
Moves Port data from the local to the cluster registry
Arguments:
hClusterKey - handle to the cluster registry
pbRegUpdated - flag to indicate if the registry was updated
Return Value:
TRUE - success
FALSE - failure
--*/
{
BOOL bStatus = FALSE;
DWORD dwError, dwType, dwValue, dwSize;
HKEY hLocalLPR = NULL, hClusterLPR = NULL;
WCHAR szLocalLPRKey[] = L"System\\CurrentControlSet\\Control\\Print\\Monitors\\LPR Port";
WCHAR szClusterLPRKey[] = L"Monitors\\LPR Port";
WCHAR szSplVersion[] = L"Spooler Version";
//
// Initialize the bRegUpdate flag
//
*pbRegUpdated = FALSE;
//
// Check if ports have been migrated already
//
dwSize = sizeof(DWORD);
if( dwError = ClusterRegQueryValue( hClusterKey, szSplVersion, &dwType,
(LPBYTE) &dwValue, &dwSize ) ){
if( dwError != ERROR_FILE_NOT_FOUND ){
SetLastError( dwError );
return FALSE;
}
} else {
if( dwValue == 1 ){
return TRUE;
}
}
//
// Open the local LPR Port key, if any
//
if( dwError = RegOpenKeyEx( HKEY_LOCAL_MACHINE, szLocalLPRKey, 0,
KEY_READ, &hLocalLPR ) ){
//
// LPR Port key was not found
//
if( dwError == ERROR_FILE_NOT_FOUND ){
bStatus = TRUE;
} else {
SetLastError( dwError );
}
goto CleanUp;
}
//
// Create the LPR Port key on the cluster registry
//
if(( dwError = ClusterRegOpenKey( hClusterKey, szClusterLPRKey,
KEY_READ|KEY_WRITE,
&hClusterLPR ) ) == ERROR_FILE_NOT_FOUND)
{
if( dwError = ClusterRegCreateKey( hClusterKey, szClusterLPRKey,
0,KEY_READ|KEY_WRITE,
NULL, &hClusterLPR, NULL ) )
{
SetLastError( dwError );
goto CleanUp;
}
}
else if ( dwError )
{
SetLastError( dwError );
goto CleanUp;
}
bStatus = bSplRegCopyTree( hClusterLPR, hLocalLPR );
if( bStatus ){
//
// Create a value in the cluster to avoid repeated copying of the port data
//
dwValue = 1;
dwSize = sizeof(dwValue);
ClusterRegSetValue( hClusterKey, szSplVersion, REG_DWORD,
(LPBYTE) &dwValue, dwSize );
*pbRegUpdated = TRUE;
}
CleanUp:
if( hLocalLPR ){
RegCloseKey( hLocalLPR );
}
if( hClusterLPR ){
ClusterRegCloseKey( hClusterLPR );
}
return bStatus;
}
RESID
WINAPI
SplSvcOpen(
IN LPCWSTR ResourceName,
IN HKEY ResourceKey,
IN RESOURCE_HANDLE ResourceHandle
)
/*++
Routine Description:
Opens the spooler resource. This will start the spooler
service if necessary.
Arguments:
ResourceName - supplies the resource name
ResourceKey - supplies a handle to the resource's cluster registry key
ResourceHandle - the resource handle to be supplied with SetResourceStatus
is called.
Return Value:
RESID of created resource
Zero on failure
--*/
{
PSPOOLER_INFORMATION pSpoolerInfo = NULL;
BOOL bTooMany = FALSE, bRegUpdated;
HKEY parametersKey = NULL;
DWORD status;
HCLUSTER hCluster;
UNREFERENCED_PARAMETER(ResourceKey);
vEnterSem();
DBGMSG( DBG_WARN, ( ">>> Open: called\n" ));
if( gcSpoolerInfo == MAX_SPOOLER ){
bTooMany = TRUE;
status = ERROR_ALLOTTED_SPACE_EXCEEDED;
goto FailLeave;
}
//
// Open the Parameters key for this resource.
//
status = ClusterRegOpenKey( ResourceKey,
CLUSREG_KEYNAME_PARAMETERS,
KEY_READ,
¶metersKey );
if ( status != ERROR_SUCCESS || parametersKey == NULL ) {
(SplSvcLogEvent)(
ResourceHandle,
LOG_ERROR,
L"Unable to open parameters key for resource '%1!ws!'. Error: %2!u!.\n",
ResourceName,
status );
goto FailLeave;
}
//
// Move the ports data from local to cluster registry
//
if( !bUpdateRegPort( parametersKey, &bRegUpdated ) ){
(SplSvcLogEvent)(
ResourceHandle,
LOG_WARNING,
L"LPR Port settings could not be moved to cluster registry.\n" );
DBGMSG( DBG_WARN, ( "Port settings could not be moved to cluster registry" ));
}
//
// Find a free index in the process info table for this new app.
//
pSpoolerInfo = pNewSpoolerInfo( ResourceName,
ResourceHandle,
SplSvcSetResourceStatus,
SplSvcLogEvent );
if( !pSpoolerInfo ){
status = ERROR_ALLOTTED_SPACE_EXCEEDED;
goto FailLeave;
}
//
// Save the name of the resource.
//
hCluster = OpenCluster( NULL );
if ( !hCluster ) {
status = GetLastError();
goto FailLeave;
}
pSpoolerInfo->hResource = OpenClusterResource( hCluster,
ResourceName );
status = GetLastError();
CloseCluster( hCluster );
if ( pSpoolerInfo->hResource == NULL ) {
goto FailLeave;
}
pSpoolerInfo->eState = kOpen;
pSpoolerInfo->ParametersKey = parametersKey;
vAddRef( pSpoolerInfo );
++gcSpoolerInfo;
vLeaveSem();
DBGMSG( DBG_WARN,
( "Open: return %x\n", RESID_FROM_SPOOLERINFO( pSpoolerInfo )));
return RESID_FROM_SPOOLERINFO(pSpoolerInfo);
FailLeave:
vLeaveSem();
if( bTooMany ){
(SplSvcLogEvent)(
ResourceHandle,
LOG_ERROR,
L"Too many spoolers.\n" );
DBGMSG( DBG_WARN, ( "SplSvcOpen: Too many spoolers.\n" ));
} else {
(SplSvcLogEvent)(
ResourceHandle,
LOG_ERROR,
L"Failed to create new spooler. Error: %1!u!.\n",
GetLastError() );
DBGMSG( DBG_ERROR, ( "SplSvcOpen: Unable to create spooler %d\n",
GetLastError()));
}
if ( parametersKey != NULL ) {
ClusterRegCloseKey( parametersKey );
}
if ( pSpoolerInfo && (pSpoolerInfo->hResource != NULL) ) {
CloseClusterResource( pSpoolerInfo->hResource );
}
vDeleteSpoolerInfo( pSpoolerInfo );
SetLastError( status );
return (RESID)0;
}
VOID
WINAPI
SplSvcClose(
IN RESID Resid
)
/*++
Routine Description:
Close down the open spooler resource ID. Note that we'll leave
the spooler running, since it always should be running.
Arguments:
Resource - supplies resource id to be closed
Return Value:
--*/
{
PSPOOLER_INFORMATION pSpoolerInfo;
DBGMSG( DBG_WARN, ( ">>> Close: called %x\n", Resid ));
pSpoolerInfo = PSPOOLERINFO_FROM_RESID( Resid );
//
// If resource is still online, terminate it.
//
if( pSpoolerInfo->eState == kOnline ){
SplSvcTerminate( Resid );
}
vEnterSem();
--gcSpoolerInfo;
pSpoolerInfo->eState = kClose;
vLeaveSem();
if (pSpoolerInfo->hResource != NULL ) {
CloseClusterResource( pSpoolerInfo->hResource );
}
if (pSpoolerInfo->ParametersKey != NULL ) {
ClusterRegCloseKey( pSpoolerInfo->ParametersKey );
}
vDecRef( pSpoolerInfo );
}
DWORD
WINAPI
SplSvcOnline(
IN RESID Resid,
IN OUT PHANDLE EventHandle
)
/*++
Routine Description:
Online the spooler resource.
This always completes asynchronously with ERROR_IO_PENDING.
Arguments:
Resource - supplies resource id to be brought online
EventHandle - supplies a pointer to a handle to signal on error.
Return Value:
In success case, this returns ERROR_IO_PENDING, else win32
error code.
--*/
{
BOOL bStatus;
DWORD Status = ERROR_IO_PENDING;
PSPOOLER_INFORMATION pSpoolerInfo;
UNREFERENCED_PARAMETER( EventHandle );
DBGMSG( DBG_WARN, ( ">>> Online: called %x\n", Resid ));
pSpoolerInfo = PSPOOLERINFO_FROM_RESID( Resid );
//
// Rpc to the spooler to initiate Online.
//
bStatus = SpoolerOnline( pSpoolerInfo );
if( !bStatus ){
Status = GetLastError();
SPLASSERT( Status );
(pSpoolerInfo->pfnLogEvent)(
pSpoolerInfo->ResourceHandle,
LOG_ERROR,
L"Unable to online spooler resource. Error: %1!u!.\n",
Status );
DBGMSG( DBG_ERROR, ( "SplSvcOnline: Unable to online spooler\n" ));
}
return Status;
}
DWORD
WINAPI
SplSvcOffline(
IN RESID Resid
)
/*++
Routine Description:
Offline the spooler resource.
Arguments:
Resid - supplies the resource to be taken offline
Return Value:
In success case, this returns ERROR_IO_PENDING, else win32
error code.
--*/
{
PSPOOLER_INFORMATION pSpoolerInfo;
DBGMSG( DBG_WARN, ( ">>> Offline: called %x\n", Resid ));
pSpoolerInfo = PSPOOLERINFO_FROM_RESID( Resid );
vEnterSem();
pSpoolerInfo->ClusterResourceState = ClusterResourceOffline;
vLeaveSem();
return(SpoolerOffline(pSpoolerInfo));
}
VOID
WINAPI
SplSvcTerminate(
IN RESID Resid
)
/*++
Routine Description:
Terminate and restart the spooler--no waiting.
Arguments:
Resid - supplies resource id to be terminated
Return Value:
--*/
{
PSPOOLER_INFORMATION pSpoolerInfo;
DBGMSG( DBG_WARN, ( ">>> Terminate: called %x\n", Resid ));
pSpoolerInfo = PSPOOLERINFO_FROM_RESID( Resid );
vEnterSem();
pSpoolerInfo->ClusterResourceState = ClusterResourceFailed;
vLeaveSem();
SpoolerTerminate(pSpoolerInfo);
return;
}
BOOL
WINAPI
SplSvcIsAlive(
IN RESID Resid
)
/*++
Routine Description:
IsAlive routine for Generice Applications resource.
Arguments:
Resource - supplies the resource id to be polled.
Return Value:
TRUE - Resource is alive and well
FALSE - Resource is toast.
--*/
{
PSPOOLER_INFORMATION pSpoolerInfo;
pSpoolerInfo = PSPOOLERINFO_FROM_RESID( Resid );
return SpoolerIsAlive( pSpoolerInfo );
}
BOOL
WINAPI
SplSvcLooksAlive(
IN RESID Resid
)
/*++
Routine Description:
LooksAlive routine for Generic Applications resource.
Arguments:
Resource - supplies the resource id to be polled.
Return Value:
TRUE - Resource looks like it is alive and well
FALSE - Resource looks like it is toast.
--*/
{
PSPOOLER_INFORMATION pSpoolerInfo;
pSpoolerInfo = PSPOOLERINFO_FROM_RESID( Resid );
return SpoolerLooksAlive( pSpoolerInfo );
}
DWORD
SplSvcGetRequiredDependencies(
OUT PVOID OutBuffer,
IN DWORD OutBufferSize,
OUT LPDWORD BytesReturned
)
/*++
Routine Description:
Processes the CLCTL_GET_REQUIRED_DEPENDENCIES control function
for resources of type Print Spooler.
Arguments:
OutBuffer - Supplies a pointer to the output buffer to be filled in.
OutBufferSize - Supplies the size, in bytes, of the available space
pointed to by OutBuffer.
BytesReturned - Returns the number of bytes of OutBuffer actually
filled in by the resource. If OutBuffer is too small, BytesReturned
contains the total number of bytes for the operation to succeed.
Return Value:
ERROR_SUCCESS - The function completed successfully.
ERROR_MORE_DATA - The output buffer is too small to return the data.
BytesReturned contains the required size.
Win32 error code - The function failed.
--*/
{
typedef struct DEP_DATA {
CLUSPROP_RESOURCE_CLASS storageEntry;
CLUSPROP_SZ_DECLARE( netnameEntry, sizeof(NET_NAME_RESOURCE_NAME) / sizeof(WCHAR) );
CLUSPROP_SYNTAX endmark;
} DEP_DATA, *PDEP_DATA;
PDEP_DATA pdepdata = (PDEP_DATA)OutBuffer;
DWORD status;
*BytesReturned = sizeof(DEP_DATA);
if ( OutBufferSize < sizeof(DEP_DATA) ) {
if ( OutBuffer == NULL ) {
status = ERROR_SUCCESS;
} else {
status = ERROR_MORE_DATA;
}
} else {
ZeroMemory( pdepdata, sizeof(DEP_DATA) );
pdepdata->storageEntry.Syntax.dw = CLUSPROP_SYNTAX_RESCLASS;
pdepdata->storageEntry.cbLength = sizeof(DWORD);
pdepdata->storageEntry.rc = CLUS_RESCLASS_STORAGE;
pdepdata->netnameEntry.Syntax.dw = CLUSPROP_SYNTAX_NAME;
pdepdata->netnameEntry.cbLength = sizeof(NET_NAME_RESOURCE_NAME);
StringCchCopyW( pdepdata->netnameEntry.sz,
COUNTOF(pdepdata->netnameEntry.sz),
NET_NAME_RESOURCE_NAME );
pdepdata->endmark.dw = CLUSPROP_SYNTAX_ENDMARK;
status = ERROR_SUCCESS;
}
return status;
} // SplSvcGetRequiredDependencies
DWORD
SplSvcResourceControl(
IN RESID ResourceId,
IN DWORD ControlCode,
IN PVOID InBuffer,
IN DWORD InBufferSize,
OUT PVOID OutBuffer,
IN DWORD OutBufferSize,
OUT LPDWORD BytesReturned
)
/*++
Routine Description:
ResourceControl routine for Print Spooler resources.
Perform the control request specified by ControlCode on the specified
resource.
Arguments:
ResourceId - Supplies the resource id for the specific resource.
ControlCode - Supplies the control code that defines the action
to be performed.
InBuffer - Supplies a pointer to a buffer containing input data.
InBufferSize - Supplies the size, in bytes, of the data pointed
to by InBuffer.
OutBuffer - Supplies a pointer to the output buffer to be filled in.
OutBufferSize - Supplies the size, in bytes, of the available space
pointed to by OutBuffer.
BytesReturned - Returns the number of bytes of OutBuffer actually
filled in by the resource. If OutBuffer is too small, BytesReturned
contains the total number of bytes for the operation to succeed.
Return Value:
ERROR_SUCCESS - The function completed successfully.
ERROR_INVALID_FUNCTION - The requested control code is not supported.
In some cases, this allows the cluster software to perform the work.
Win32 error code - The function failed.
--*/
{
DWORD status;
PSPOOLER_INFORMATION pSpoolerInfo;
DWORD required;
LPWSTR pszResourceNew;
pSpoolerInfo = PSPOOLERINFO_FROM_RESID( ResourceId );
switch ( ControlCode ) {
case CLUSCTL_RESOURCE_UNKNOWN:
*BytesReturned = 0;
status = ERROR_SUCCESS;
break;
case CLUSCTL_RESOURCE_REMOVE_OWNER:
case CLUSCTL_RESOURCE_ADD_OWNER:
case CLUSCTL_RESOURCE_INSTALL_NODE:
{
status = CleanClusterSpoolerData(pSpoolerInfo->hResource, static_cast<LPCWSTR>(InBuffer));
break;
}
case CLUSCTL_RESOURCE_GET_PRIVATE_PROPERTY_FMTS:
status = ResUtilGetPropertyFormats( SplSvcResourcePrivateProperties,
OutBuffer,
OutBufferSize,
BytesReturned,
&required );
if ( status == ERROR_MORE_DATA ) {
*BytesReturned = required;
}
break;
case CLUSCTL_RESOURCE_SET_NAME:
pszResourceNew = (LPWSTR)LocalAlloc(
LMEM_FIXED,
( lstrlenW( (LPWSTR)InBuffer ) + 1 )
* sizeof( WCHAR ));
if ( pszResourceNew ) {
LocalFree( (HLOCAL)pSpoolerInfo->pszResource );
StringCchCopyW( pszResourceNew,
( lstrlenW( (LPWSTR)InBuffer ) + 1 ),
(LPWSTR)InBuffer );
pSpoolerInfo->pszResource = (LPTSTR)pszResourceNew;
status = ERROR_SUCCESS;
} else {
status = GetLastError();
}
break;
case CLUSCTL_RESOURCE_GET_REQUIRED_DEPENDENCIES:
status = SplSvcGetRequiredDependencies( OutBuffer,
OutBufferSize,
BytesReturned
);
break;
case CLUSCTL_RESOURCE_ENUM_PRIVATE_PROPERTIES:
status = ResUtilEnumProperties( SplSvcResourcePrivateProperties,
(LPWSTR) OutBuffer,
OutBufferSize,
BytesReturned,
&required );
if ( status == ERROR_MORE_DATA ) {
*BytesReturned = required;
}
break;
case CLUSCTL_RESOURCE_GET_PRIVATE_PROPERTIES:
status = SplSvcGetPrivateResProperties( pSpoolerInfo,
OutBuffer,
OutBufferSize,
BytesReturned );
break;
case CLUSCTL_RESOURCE_VALIDATE_PRIVATE_PROPERTIES:
status = SplSvcValidatePrivateResProperties( pSpoolerInfo,
InBuffer,
InBufferSize,
NULL );
break;
case CLUSCTL_RESOURCE_SET_PRIVATE_PROPERTIES:
status = SplSvcSetPrivateResProperties( pSpoolerInfo,
InBuffer,
InBufferSize );
break;
case CLUSCTL_RESOURCE_CLUSTER_VERSION_CHANGED:
{
LPWSTR pszResourceGuid = NULL;
//
// Retreive the guid of the spooler resource
//
if ((status = GetIDFromName(pSpoolerInfo->hResource, &pszResourceGuid)) == ERROR_SUCCESS)
{
status = SpoolerWriteClusterUpgradedKey(pszResourceGuid);
LocalFree(pszResourceGuid);
}
}
break;
case CLUSCTL_RESOURCE_DELETE:
{
//
// First we delete the driver repository on the cluster disk
//
if ((status = CleanPrinterDriverRepository(pSpoolerInfo->ParametersKey)) == ERROR_SUCCESS)
{
LPWSTR pszResourceGuid = NULL;
//
// Now we delete any data stored by the cluster spooler on the local node
// Retreive the guid of the spooler resource
//
if ((status = GetIDFromName(pSpoolerInfo->hResource, &pszResourceGuid)) == ERROR_SUCCESS)
{
status = CleanUnusedClusDriverRegistryKey(pszResourceGuid);
//
// We do not care about the result of this function
//
CleanUnusedClusDriverDirectory(pszResourceGuid);
LocalFree(pszResourceGuid);
}
}
break;
}
default:
status = ERROR_INVALID_FUNCTION;
break;
}
return(status);
} // SplSvcResourceControl
DWORD
SplSvcResourceTypeControl(
IN LPCWSTR ResourceTypeName,
IN DWORD ControlCode,
IN PVOID InBuffer,
IN DWORD InBufferSize,
OUT PVOID OutBuffer,
IN DWORD OutBufferSize,
OUT LPDWORD BytesReturned
)
/*++
Routine Description:
ResourceTypeControl routine for Print Spooler resources.
Perform the control request specified by ControlCode.
Arguments:
ResourceTypeName - Supplies the name of the resource type.
ControlCode - Supplies the control code that defines the action
to be performed.
InBuffer - Supplies a pointer to a buffer containing input data.
InBufferSize - Supplies the size, in bytes, of the data pointed
to by InBuffer.
OutBuffer - Supplies a pointer to the output buffer to be filled in.
OutBufferSize - Supplies the size, in bytes, of the available space
pointed to by OutBuffer.
BytesReturned - Returns the number of bytes of OutBuffer actually
filled in by the resource. If OutBuffer is too small, BytesReturned
contains the total number of bytes for the operation to succeed.
Return Value:
ERROR_SUCCESS - The function completed successfully.
ERROR_INVALID_FUNCTION - The requested control code is not supported.
In some cases, this allows the cluster software to perform the work.
Win32 error code - The function failed.
--*/
{
DWORD status;
DWORD required;
switch ( ControlCode ) {
case CLUSCTL_RESOURCE_TYPE_UNKNOWN:
*BytesReturned = 0;
status = ERROR_SUCCESS;
break;
case CLUSCTL_RESOURCE_TYPE_GET_PRIVATE_RESOURCE_PROPERTY_FMTS:
status = ResUtilGetPropertyFormats( SplSvcResourcePrivateProperties,
OutBuffer,
OutBufferSize,
BytesReturned,
&required );
if ( status == ERROR_MORE_DATA ) {
*BytesReturned = required;
}
break;
case CLUSCTL_RESOURCE_TYPE_GET_REQUIRED_DEPENDENCIES:
status = SplSvcGetRequiredDependencies( OutBuffer,
OutBufferSize,
BytesReturned
);
break;
case CLUSCTL_RESOURCE_TYPE_ENUM_PRIVATE_PROPERTIES:
status = ResUtilEnumProperties( SplSvcResourcePrivateProperties,
(LPWSTR) OutBuffer,
OutBufferSize,
BytesReturned,
&required );
if ( status == ERROR_MORE_DATA ) {
*BytesReturned = required;
}
break;
case CLUSCTL_RESOURCE_TYPE_STARTING_PHASE2:
{
//
// We could launch CleanSpoolerUnusedFilesAndKeys in a seprate thread.
// But in that case we'd need to bump up the ref count on the DLL
// and have CleanSpoolerUnusedFilesAndKeys call FreeLibraryAndExitThread.
// CleanSpoolerUnusedFilesAndKeys usually takes 100 to 200 milliseconds
// to complete. When the function has to do extenisve clean up, then it
// can take up to 500 milliseconds. So there is no compelling reason to
// call the function in a separate thread. For more details see bug 473820.
//
status = CleanSpoolerUnusedFilesAndKeys();
break;
}
default:
status = ERROR_INVALID_FUNCTION;
break;
}
return(status);
} // SplSvcResourceTypeControl
DWORD
SplSvcGetPrivateResProperties(
IN OUT PSPOOLER_INFORMATION ResourceEntry,
OUT PVOID OutBuffer,
IN DWORD OutBufferSize,
OUT LPDWORD BytesReturned
)
/*++
Routine Description:
Processes the CLUSCTL_RESOURCE_GET_PRIVATE_PROPERTIES control
function for resources of type Print Spooler.
Arguments:
ResourceEntry - Supplies the resource entry on which to operate.
OutBuffer - Supplies a pointer to the output buffer to be filled in.
OutBufferSize - Supplies the size, in bytes, of the available space
pointed to by OutBuffer.
BytesReturned - Returns the number of bytes of OutBuffer actually
filled in by the resource. If OutBuffer is too small, BytesReturned
contains the total number of bytes for the operation to succeed.
Return Value:
ERROR_SUCCESS - The function completed successfully.
ERROR_NOT_ENOUGH_MEMORY - An error occurred allocating memory.
Win32 error code - The function failed.
--*/
{
DWORD status;
DWORD required;
*BytesReturned = 0;
//
// Clear the output buffer
//
ZeroMemory( OutBuffer, OutBufferSize );
//
// Get the common properties.
//
status = ResUtilGetAllProperties( ResourceEntry->ParametersKey,
SplSvcResourcePrivateProperties,
OutBuffer,
OutBufferSize,
BytesReturned,
&required );
if ( *BytesReturned == 0 ) {
*BytesReturned = required;
}
return(status);
} // SplSvcGetPrivateResProperties
DWORD
SplSvcValidateUniqueProperties(
IN HRESOURCE hSelf,
IN HRESOURCE hResource,
IN PVOID GroupName
)
/*++
Routine Description:
Callback function to validate that a resources properties are unique.
For the SplSvc resource we must ensure that only one print spooler
resource exists in a group.
We will never be called for the resource we are creating, only for
other resources of the same type.
Arguments:
hSelf - A handle to the original resource.
hResource - A handle to a resource of the same Type. Check against this
to make sure the new properties do not conflict.
lpszGroupName - The name of the Group the creating resource is in.
Return Value:
ERROR_SUCCESS - The function completed successfully, only one print
spooler in the given group.
ERROR_OBJECT_ALREADY_EXISTS - The name is not unique (i.e., already have
a print spooler in that group).
A Win32 error code on other failure.
--*/
{
WCHAR groupName[MAX_GROUP_NAME_LENGTH + 1];
DWORD groupNameSize = MAX_GROUP_NAME_LENGTH * sizeof(WCHAR);
CLUSTER_RESOURCE_STATE resourceState;
LPWSTR lpszGroupName = (LPWSTR)GroupName;
UNREFERENCED_PARAMETER(hSelf);
groupName[0] = L'\0';
resourceState = GetClusterResourceState( hResource,
NULL,
0,
groupName,
&groupNameSize );
if ( !*groupName ) {
return(GetLastError());
}
if ( lstrcmpiW( lpszGroupName, groupName ) == 0 ) {
return(ERROR_OBJECT_ALREADY_EXISTS);
}
return( ERROR_SUCCESS );
} // SplSvcValidateUniqueProperties
DWORD
SplSvcValidatePrivateResProperties(
IN OUT PSPOOLER_INFORMATION ResourceEntry,
IN PVOID InBuffer,
IN DWORD InBufferSize,
OUT PSPOOLER_PARAMS Params
)
/*++
Routine Description:
Processes the CLUSCTL_RESOURCE_VALIDATE_PRIVATE_PROPERTIES control
function for resources of type Print Spooler.
Arguments:
ResourceEntry - Supplies the resource entry on which to operate.
InBuffer - Supplies a pointer to a buffer containing input data.
InBufferSize - Supplies the size, in bytes, of the data pointed
to by InBuffer.
Params - Supplies the parameter block to fill in.
Return Value:
ERROR_SUCCESS - The function completed successfully.
ERROR_INVALID_PARAMETER - The data is formatted incorrectly.
ERROR_NOT_ENOUGH_MEMORY - An error occurred allocating memory.
Win32 error code - The function failed.
--*/
{
DWORD status;
SPOOLER_PARAMS currentProps;
SPOOLER_PARAMS newProps;
PSPOOLER_PARAMS pParams = NULL;
WCHAR groupName[MAX_GROUP_NAME_LENGTH + 1];
DWORD groupNameSize = MAX_GROUP_NAME_LENGTH * sizeof(WCHAR);
CLUSTER_RESOURCE_STATE resourceState;
LPWSTR nameOfPropInError;
//
// Check if there is input data.
//
if ( (InBuffer == NULL) ||
(InBufferSize < sizeof(DWORD)) ) {
return(ERROR_INVALID_DATA);
}
//
// Capture the current set of private properties from the registry.
//
ZeroMemory( ¤tProps, sizeof(currentProps) );
status = ResUtilGetPropertiesToParameterBlock(
ResourceEntry->ParametersKey,
SplSvcResourcePrivateProperties,
(LPBYTE) ¤tProps,
FALSE, /*CheckForRequiredProperties*/
&nameOfPropInError
);
if ( status != ERROR_SUCCESS ) {
(SplSvcLogEvent)(
ResourceEntry->ResourceHandle,
LOG_ERROR,
L"Unable to read the '%1' property. Error: %2!u!.\n",
(nameOfPropInError == NULL ? L"" : nameOfPropInError),
status );
goto FnExit;
}
//
// Duplicate the resource parameter block.
//
if ( Params == NULL ) {
pParams = &newProps;
} else {
pParams = Params;
}
ZeroMemory( pParams, sizeof(SPOOLER_PARAMS) );
status = ResUtilDupParameterBlock( (LPBYTE) pParams,
(LPBYTE) ¤tProps,
SplSvcResourcePrivateProperties );
if ( status != ERROR_SUCCESS ) {
return(status);
}
//
// Parse and validate the properties.
//
status = ResUtilVerifyPropertyTable( SplSvcResourcePrivateProperties,
NULL,
TRUE, // Allow unknowns
InBuffer,
InBufferSize,
(LPBYTE) pParams );
if ( status == ERROR_SUCCESS ) {
//
// Validate the Default Spool Directory
//
if ( pParams->DefaultSpoolDirectory &&
!ResUtilIsPathValid( pParams->DefaultSpoolDirectory ) ) {
status = ERROR_INVALID_PARAMETER;
goto FnExit;
}
//
// Make sure there is only one print spooler in this group.
//
resourceState = GetClusterResourceState( ResourceEntry->hResource,
NULL,
0,
groupName,
&groupNameSize );
if ( !*groupName ) {
status = GetLastError();
goto FnExit;
}
status = ResUtilEnumResources(ResourceEntry->hResource,
CLUS_RESTYPE_NAME_PRTSPLR,
SplSvcValidateUniqueProperties,
(PVOID)groupName);
if (status != ERROR_SUCCESS) {
goto FnExit;
}
}
FnExit:
//
// Cleanup our parameter block.
//
if ( ( (status != ERROR_SUCCESS)
&& (pParams != NULL) )
|| ( pParams == &newProps )
) {
ResUtilFreeParameterBlock( (LPBYTE) pParams,
(LPBYTE) ¤tProps,
SplSvcResourcePrivateProperties );
}
ResUtilFreeParameterBlock(
(LPBYTE) ¤tProps,
NULL,
SplSvcResourcePrivateProperties
);
return(status);
} // SplSvcValidatePrivateResProperties
DWORD
SplSvcSetPrivateResProperties(
IN OUT PSPOOLER_INFORMATION ResourceEntry,
IN PVOID InBuffer,
IN DWORD InBufferSize
)
/*++
Routine Description:
Processes the CLUSCTL_RESOURCE_SET_PRIVATE_PROPERTIES control function
for resources of type Print Spooler.
Arguments:
ResourceEntry - Supplies the resource entry on which to operate.
InBuffer - Supplies a pointer to a buffer containing input data.
InBufferSize - Supplies the size, in bytes, of the data pointed
to by InBuffer.
Return Value:
ERROR_SUCCESS - The function completed successfully.
ERROR_INVALID_PARAMETER - The data is formatted incorrectly.
ERROR_NOT_ENOUGH_MEMORY - An error occurred allocating memory.
Win32 error code - The function failed.
--*/
{
DWORD status;
// SPOOLER_PARAMS params;
//
// Parse the properties so they can be validated together.
// This routine does individual property validation.
//
status = SplSvcValidatePrivateResProperties( ResourceEntry,
InBuffer,
InBufferSize,
NULL /*¶ms*/ );
if ( status != ERROR_SUCCESS ) {
return(status);
}
//
// Save the parameter values.
//
status = ResUtilSetPropertyTable( ResourceEntry->ParametersKey,
SplSvcResourcePrivateProperties,
NULL,
TRUE, // Allow unknowns
InBuffer,
InBufferSize,
NULL );
// status = ResUtilSetPropertyParameterBlock( ResourceEntry->ParametersKey,
// SplSvcResourcePrivateProperties,
// NULL,
// (LPBYTE) ¶ms,
// InBuffer,
// InBufferSize,
// (LPBYTE) &ResourceEntry->Params );
// ResUtilFreeParameterBlock( (LPBYTE) ¶ms,
// (LPBYTE) &ResourceEntry->Params,
// SplSvcResourcePrivateProperties );
//
// If the resource is online, return a non-success status.
//
if (status == ERROR_SUCCESS) {
if ( (ResourceEntry->eState == kOnline) ||
(ResourceEntry->eState == kOnlinePending) ) {
status = ERROR_RESOURCE_PROPERTIES_STORED;
} else {
status = ERROR_SUCCESS;
}
}
return(status);
} // SplSvcSetPrivateResProperties
/********************************************************************
Utility functions
********************************************************************/
VOID
vEnterSem(
VOID
)
{
EnterCriticalSection( &gProcessLock );
}
VOID
vLeaveSem(
VOID
)
{
LeaveCriticalSection( &gProcessLock );
}
VOID
vAddRef(
PSPOOLER_INFORMATION pSpoolerInfo
)
{
vEnterSem();
++pSpoolerInfo->cRef;
vLeaveSem();
}
VOID
vDecRef(
PSPOOLER_INFORMATION pSpoolerInfo
)
{
UINT uRef;
SPLASSERT( pSpoolerInfo->cRef );
vEnterSem();
uRef = --pSpoolerInfo->cRef;
vLeaveSem();
if( !uRef ){
vDeleteSpoolerInfo( pSpoolerInfo );
}
}
//***********************************************************
//
// Define Function Table
//
//***********************************************************
CLRES_V1_FUNCTION_TABLE( SplSvcFunctionTable,
CLRES_VERSION_V1_00,
SplSvc,
NULL,
NULL,
SplSvcResourceControl,
SplSvcResourceTypeControl );
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
9f68101e9f474b02bfb8d4bb1b0ca1529512b5aa | c6c30441b9e6d26bdee72d51dd21860d4899be55 | /Linked List using c/Singly Circular Linked List/helperfile.cpp | 1aa7c9e0f384d3bd04c28afb59e4e0dfb7b94a9d | [] | no_license | Maggi87/Data-Structure | f137a2f520b634048fbad12d548ace2fcfc71d62 | a8a918a48e50101c7bca6f36fe9ea6a3c18b3c4d | refs/heads/master | 2021-09-27T03:01:56.522532 | 2018-11-05T19:51:03 | 2018-11-05T19:51:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,537 | cpp | #include"myheader.h"
void Displayf(PNODE head)
{
printf("\n\n Forword Direction\n");
while(head!=NULL)
{
printf("|%d|->",head->data);
head = head->next;
}
printf("NULL \n\n");
}
void Displayb(PNODE head)
{
printf("\n\nBackword Direction \n");
while(head->next!=NULL)
{
head = head->next;
}
while(head!=NULL)
{
printf("|%d|->",head->data);
head = head->prev;
}
printf("NULL \n\n");
}
int Count(PNODE head)
{
int iCnt = 0;
while(head!=NULL)
{
iCnt++;
head = head->next;
}
return iCnt;
}
void InsertFirst(PPNODE head,int iValue)
{
PNODE newn = NULL;
newn = (PNODE)malloc(sizeof(NODE));
newn->data = iValue;
newn->next = NULL;
newn->prev = NULL;
if(*head == NULL)
{
*head = newn;
}
else
{
newn->next = *head;
(*head)->prev = newn;
*head = newn;
}
}
void InsertLast(PPNODE head,int iValue)
{
PNODE newn = NULL;
PNODE temp = *head;
newn = (PNODE)malloc(sizeof(NODE));
newn->data = iValue;
newn->next = NULL;
newn->prev = NULL;
if(*head == NULL)
{
*head = newn;
}
else
{
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = newn;
newn->prev = temp;
}
}
void InsertAtPos(PPNODE head,int iValue,int iPos)
{
PNODE newn = NULL;
PNODE temp = *head;
int i = 0;
int iSize = Count(*head);
if((iPos<1)&&(iPos+1))
{
return;
}
else if(iPos == 1)
{
InsertFirst(head,iValue);
}
else if(iPos == iSize+1)
{
InsertLast(head,iValue);
}
else
{
newn = (PNODE)malloc(sizeof(NODE));
newn->data = iValue;
newn->next = NULL;
newn->prev = NULL;
for(i=1;i<=iPos-2;i++)
{
temp = temp->next;
}
newn->next = temp->next;
temp->next = newn;
newn->next->prev = newn;
newn->prev = temp;
}
}
void DeleteFirst(PPNODE head)
{
if(*head == NULL)
{
return;
}
else if((*head)->next == NULL)
{
free(*head);
*head = NULL;
}
else
{
*head = (*head)->next;
free((*head)->prev);
(*head)->prev = NULL;
}
}
void DeleteLast(PPNODE head)
{
PNODE temp = *head;
if(*head == NULL)
{
return;
}
else
{
while(temp->next->next!=NULL)
{
temp = temp->next;
}
free(temp->next);
temp->next = NULL;
}
}
void DeleteAtPos(PPNODE head, int iPos)
{
PNODE temp = *head;
int i = 0;
int iSize = Count(*head);
if((iPos<1)&&(iPos>iSize))
{
return;
}
else if(iPos == 1)
{
DeleteFirst(head);
}
else if(iPos == iSize)
{
DeleteLast(head);
}
else
{
for(i=1;i<=iPos-2;i++)
{
temp = temp -> next;
}
temp->next = temp->next->next;
free(temp->next->prev);
temp->next->prev = temp;
}
} | [
"dattaprasad.ingle@rlard.com"
] | dattaprasad.ingle@rlard.com |
d9b0bc8d2c67898d45c05087357f05b66ad6868c | 2eff78350ab8bae88a3b5b5155ec523ca82e58bc | /Compiler/wlc/include/EntryPoint.h | 3d8a087496dd16b506af9c66bec83708faf8e964 | [
"BSD-2-Clause"
] | permissive | meilj/GKC | 1a7339736bc2226c7cc4f5a798f7eb7ec53c3ba0 | cc90ce73d1ffb330ef541932f762e4e42ea50323 | refs/heads/master | 2021-01-24T03:18:54.129388 | 2018-02-26T13:48:45 | 2018-02-26T13:48:45 | 17,059,635 | 0 | 0 | BSD-2-Clause | 2018-02-26T13:48:46 | 2014-02-21T15:03:14 | C++ | UTF-8 | C++ | false | false | 5,888 | h | /*
** Copyright (c) 2013, Xin YUAN, courses of Zhejiang University
** All rights reserved.
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the 2-Clause BSD License.
**
** Author contact information:
** yxxinyuan@zju.edu.cn
**
*/
/*
This file contains entry point function.
*/
////////////////////////////////////////////////////////////////////////////////
#ifndef __ENTRY_POINT_H__
#define __ENTRY_POINT_H__
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
namespace GKC {
////////////////////////////////////////////////////////////////////////////////
// version
inline
void _PrintVersion() throw()
{
ConsoleHelper::PrintConstStringArray(DECLARE_CONST_STRING_ARRAY_TYPE(CharS)(g_const_array_version::GetAddress(), g_const_array_version::GetCount()));
}
// help
inline
void _PrintHelp() throw()
{
ConsoleHelper::PrintConstStringArray(DECLARE_CONST_STRING_ARRAY_TYPE(CharS)(g_const_array_help::GetAddress(), g_const_array_help::GetCount()));
}
// tools
inline
bool _CheckFileExtension(const ConstStringS& str, const ConstStringS& strExt, uintptr& uPos) throw()
{
if( !FsPathHelper::FindExtensionStart(str, uPos) )
return false;
return ConstStringCompareTrait<ConstStringS>::IsEQ(
ConstStringS(ConstArrayHelper::GetInternalPointer(str) + uPos, str.GetCount() - uPos),
strExt);
}
//compile single file
inline
int _Cmd_CompileSingleFile(const ConstArray<ConstStringS>& args)
{
uintptr uArgCount = args.GetCount();
if( uArgCount > 4 ) {
_PrintVersion();
_PrintHelp();
return 1;
}
StringS strSrc(StringHelper::MakeEmptyString<CharS>(MemoryHelper::GetCrtMemoryManager()));
StringUtilHelper::MakeString(args[2].get_Value(), strSrc);
StringS strDest(StringHelper::MakeEmptyString<CharS>(MemoryHelper::GetCrtMemoryManager()));
{
uintptr uPos;
//source
if( !_CheckFileExtension(StringUtilHelper::To_ConstString(strSrc), DECLARE_TEMP_CONST_STRING(ConstStringS, _S(".w")), uPos) ) {
ConsoleHelper::WriteLine(DECLARE_TEMP_CONST_STRING(ConstStringS, _S("Command error: The source file name must have the extension \".w\"!")));
return 1;
}
//destination
if( uArgCount == 4 ) {
//extension
ConstStringS c_strDest(args[3].get_Value());
if( !_CheckFileExtension(c_strDest, DECLARE_TEMP_CONST_STRING(ConstStringS, _S(".wo")), uPos) ) {
ConsoleHelper::WriteLine(DECLARE_TEMP_CONST_STRING(ConstStringS, _S("Command error: The destination file name must have the extension \".wo\"!")));
return 1;
}
StringUtilHelper::MakeString(c_strDest, strDest);
}
else {
strDest = StringHelper::Clone(strSrc);
FsPathHelper::RemoveExtension(uPos, strDest);
StringUtilHelper::Insert(uPos, DECLARE_TEMP_CONST_STRING(ConstStringS, _S(".wo")), strDest);
}
} //end block
//file names
FsPathHelper::ConvertPathStringToPlatform(strSrc);
FsPathHelper::ConvertPathStringToPlatform(strDest);
_PrintVersion();
//process
return _Compile_Single_File(strSrc, strDest) ? 0 : 2;
}
//process project file
inline
int _Cmd_ProcessProjectFile(const ConstArray<ConstStringS>& args)
{
uintptr uArgCount = args.GetCount();
if( uArgCount > 4 ) {
_PrintVersion();
_PrintHelp();
return 1;
}
StringS strSrc(StringHelper::MakeEmptyString<CharS>(MemoryHelper::GetCrtMemoryManager()));
StringUtilHelper::MakeString(args[2].get_Value(), strSrc);
StringS strDest(StringHelper::MakeEmptyString<CharS>(MemoryHelper::GetCrtMemoryManager()));
{
uintptr uPos;
//source
if( !_CheckFileExtension(StringUtilHelper::To_ConstString(strSrc), DECLARE_TEMP_CONST_STRING(ConstStringS, _S(".wp")), uPos) ) {
ConsoleHelper::WriteLine(DECLARE_TEMP_CONST_STRING(ConstStringS, _S("Command error: The project file name must have the extension \".wp\"!")));
return 1;
}
//destination
if( uArgCount == 4 ) {
StringUtilHelper::MakeString(args[3].get_Value(), strDest);
}
else {
if( !FileManagementHelper::GetCurrentDirectory(strDest) ) {
ConsoleHelper::WriteLine(DECLARE_TEMP_CONST_STRING(ConstStringS, _S("Command error: The current directory cannot be obtained!")));
return 1;
}
FsPathHelper::AppendSeparator(strDest);
StringUtilHelper::Append(DECLARE_TEMP_CONST_STRING(ConstStringS, _S("build")), strDest);
}
} //end block
//directory/file names
FsPathHelper::ConvertPathStringToPlatform(strSrc);
FsPathHelper::ConvertPathStringToPlatform(strDest);
//create directory
if( !FileManagementHelper::ForceDirectory(strDest) ) {
ConsoleHelper::WriteLine(DECLARE_TEMP_CONST_STRING(ConstStringS, _S("Command error: The destination directory cannot be created!")));
return 1;
}
_PrintVersion();
//process
return _Process_Project_File(strSrc, strDest) ? 0 : 2;
}
// ProgramEntryPoint
class ProgramEntryPoint
{
public:
static int ConsoleMain(const ConstArray<ConstStringS>& args, const ConstArray<ConstStringS>& env)
{
uintptr uArgCount = args.GetCount();
//args
if( uArgCount <= 2 ) {
_PrintVersion();
_PrintHelp();
return 1;
}
int ret = 0;
//-c
if( ConstStringCompareTrait<ConstStringS>::IsEQ(args[1].get_Value(), DECLARE_TEMP_CONST_STRING(ConstStringS, _S("-c"))) ) {
ret = _Cmd_CompileSingleFile(args);
}
//-p
else if( ConstStringCompareTrait<ConstStringS>::IsEQ(args[1].get_Value(), DECLARE_TEMP_CONST_STRING(ConstStringS, _S("-p"))) ) {
ret = _Cmd_ProcessProjectFile(args);
}
else {
ConsoleHelper::WriteLine(DECLARE_TEMP_CONST_STRING(ConstStringS, _S("Command error: Invalid parameters!")));
return 1;
}
return ret;
}
};
////////////////////////////////////////////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////
#endif
////////////////////////////////////////////////////////////////////////////////
| [
"yxxinyuan@zju.edu.cn"
] | yxxinyuan@zju.edu.cn |
5b82146b0121c44ba4104e998ebeb367079f7cd7 | 2da48b07fa9c017408103bf27698a7bca06dc0d2 | /utt/include/common.hpp | b7ca479f77dd62b69c0c4b957dc2f7a4f54a8cf1 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"MIT"
] | permissive | HristoStaykov/concord-bft | bdb0b91ffc3f91f0fba6723dcf3161f0f3200be2 | 64729dfdb93ca914a47b61b331bc64802eb31caf | refs/heads/master | 2023-06-28T10:34:43.186358 | 2022-09-28T10:47:37 | 2022-09-28T10:47:37 | 243,783,141 | 0 | 0 | null | 2020-02-28T14:38:35 | 2020-02-28T14:38:34 | null | UTF-8 | C++ | false | false | 1,809 | hpp | // UTT
//
// Copyright (c) 2020-2022 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache 2.0 license (the "License").
// You may not use this product except in compliance with the Apache 2.0
// License.
//
// This product may include a number of subcomponents with separate copyright
// notices and license terms. Your use of these subcomponents is subject to the
// terms and conditions of the sub-component's license, as noted in the LICENSE
// file.
#pragma once
#include "commitment.hpp"
#include "UTTParams.hpp"
#include "types.hpp"
#include <memory>
#include <vector>
#include <map>
namespace libutt {
class CommKey;
}
namespace libutt::api {
class Utils {
/**
* @brief Implements some common operations
*
*/
public:
/**
* @brief Aggregate the shared signatures for a given signature
*
* @param n The total number of coinsSigner replicas in the system
* @param rsigs A map of <signer ID, Signature> of a threshold collected signatures
* @return types::Signature The combined signature
*/
static types::Signature aggregateSigShares(uint32_t n, const std::map<uint32_t, types::Signature>& rsigs);
/**
* @brief un-blind a signature randomness
*
* @param p The shared global UTT parameters
* @param t The signature type (one of REGISTRATION or COIN)
* @param randomness A vector of randoms known only by the client
* @param sig The signature to un-blind
* @return types::Signature
*/
static types::Signature unblindSignature(const UTTParams& p,
Commitment::Type t,
const std::vector<types::CurvePoint>& randomness,
const types::Signature& sig);
};
} // namespace libutt::api | [
"edzhurov@vmware.com"
] | edzhurov@vmware.com |
9f73cfe537bd1b2f376dc0421a4133ab78e7e6b4 | 88f1a6c0edec551996d026ecd13d9f0f51425307 | /devel/include/my_project_test/ctr_can_MT4000.h | 7032ba93b74eb7846b57d532baa186151d555649 | [] | no_license | Gorlen-boot/Pro-UIF | 57b5b788f19da104c26abc6807951fb41327d5e8 | 81e0f85aaa3bf2d1d5c3df881435e0a5342d3eb6 | refs/heads/master | 2022-12-15T08:56:43.941989 | 2020-09-04T03:27:32 | 2020-09-04T03:27:32 | 290,709,731 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,125 | h | // Generated by gencpp from file my_project_test/ctr_can_MT4000.msg
// DO NOT EDIT!
#ifndef MY_PROJECT_TEST_MESSAGE_CTR_CAN_MT4000_H
#define MY_PROJECT_TEST_MESSAGE_CTR_CAN_MT4000_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace my_project_test
{
template <class ContainerAllocator>
struct ctr_can_MT4000_
{
typedef ctr_can_MT4000_<ContainerAllocator> Type;
ctr_can_MT4000_()
: driveMode_b(false)
, throttle(0.0)
, electronic_break(0.0)
, hydraulic_break(0.0)
, steerAngle(0.0)
, park_b(false)
, loadBrake_b(false)
, gear(0)
, dump_bed(0.0)
, powerSupply_b(false)
, engine_b(false)
, turtle_b(false)
, lubricate_b(false)
, firePrevent_b(false)
, emergencyBrake_b(false)
, lighting_b(false)
, horn_b(false)
, leftLamp_b(false)
, rightLamp_b(false)
, bothLamp_b(false) {
}
ctr_can_MT4000_(const ContainerAllocator& _alloc)
: driveMode_b(false)
, throttle(0.0)
, electronic_break(0.0)
, hydraulic_break(0.0)
, steerAngle(0.0)
, park_b(false)
, loadBrake_b(false)
, gear(0)
, dump_bed(0.0)
, powerSupply_b(false)
, engine_b(false)
, turtle_b(false)
, lubricate_b(false)
, firePrevent_b(false)
, emergencyBrake_b(false)
, lighting_b(false)
, horn_b(false)
, leftLamp_b(false)
, rightLamp_b(false)
, bothLamp_b(false) {
(void)_alloc;
}
typedef uint8_t _driveMode_b_type;
_driveMode_b_type driveMode_b;
typedef float _throttle_type;
_throttle_type throttle;
typedef float _electronic_break_type;
_electronic_break_type electronic_break;
typedef float _hydraulic_break_type;
_hydraulic_break_type hydraulic_break;
typedef float _steerAngle_type;
_steerAngle_type steerAngle;
typedef uint8_t _park_b_type;
_park_b_type park_b;
typedef uint8_t _loadBrake_b_type;
_loadBrake_b_type loadBrake_b;
typedef int16_t _gear_type;
_gear_type gear;
typedef float _dump_bed_type;
_dump_bed_type dump_bed;
typedef uint8_t _powerSupply_b_type;
_powerSupply_b_type powerSupply_b;
typedef uint8_t _engine_b_type;
_engine_b_type engine_b;
typedef uint8_t _turtle_b_type;
_turtle_b_type turtle_b;
typedef uint8_t _lubricate_b_type;
_lubricate_b_type lubricate_b;
typedef uint8_t _firePrevent_b_type;
_firePrevent_b_type firePrevent_b;
typedef uint8_t _emergencyBrake_b_type;
_emergencyBrake_b_type emergencyBrake_b;
typedef uint8_t _lighting_b_type;
_lighting_b_type lighting_b;
typedef uint8_t _horn_b_type;
_horn_b_type horn_b;
typedef uint8_t _leftLamp_b_type;
_leftLamp_b_type leftLamp_b;
typedef uint8_t _rightLamp_b_type;
_rightLamp_b_type rightLamp_b;
typedef uint8_t _bothLamp_b_type;
_bothLamp_b_type bothLamp_b;
typedef boost::shared_ptr< ::my_project_test::ctr_can_MT4000_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::my_project_test::ctr_can_MT4000_<ContainerAllocator> const> ConstPtr;
}; // struct ctr_can_MT4000_
typedef ::my_project_test::ctr_can_MT4000_<std::allocator<void> > ctr_can_MT4000;
typedef boost::shared_ptr< ::my_project_test::ctr_can_MT4000 > ctr_can_MT4000Ptr;
typedef boost::shared_ptr< ::my_project_test::ctr_can_MT4000 const> ctr_can_MT4000ConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::my_project_test::ctr_can_MT4000_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::my_project_test::ctr_can_MT4000_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace my_project_test
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'my_project_test': ['/home/workSpace/Pro-UIF-master/src/my_project_test/msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::my_project_test::ctr_can_MT4000_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::my_project_test::ctr_can_MT4000_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::my_project_test::ctr_can_MT4000_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::my_project_test::ctr_can_MT4000_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::my_project_test::ctr_can_MT4000_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::my_project_test::ctr_can_MT4000_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::my_project_test::ctr_can_MT4000_<ContainerAllocator> >
{
static const char* value()
{
return "d067cd566f42a2ca961103e47afa30a8";
}
static const char* value(const ::my_project_test::ctr_can_MT4000_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xd067cd566f42a2caULL;
static const uint64_t static_value2 = 0x961103e47afa30a8ULL;
};
template<class ContainerAllocator>
struct DataType< ::my_project_test::ctr_can_MT4000_<ContainerAllocator> >
{
static const char* value()
{
return "my_project_test/ctr_can_MT4000";
}
static const char* value(const ::my_project_test::ctr_can_MT4000_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::my_project_test::ctr_can_MT4000_<ContainerAllocator> >
{
static const char* value()
{
return "## topic name : \"ros_to_can_MT4000\"\n\
###############\n\
bool driveMode_b #自动模式开关 0:人工驾驶 1:自动驾驶\n\
float32 throttle #油门踏板指令 0-100\n\
float32 electronic_break #电制动踏板指令 0-100\n\
float32 hydraulic_break #液压制动踏板指令 0-100\n\
float32 steerAngle #前轮转向角度[-350,250],1=0.1度,左转为正数最大25度,右转为负数最值为-35度\n\
bool park_b # 驻车制动, 0 无动作, 1 动作\n\
bool loadBrake_b # 装载制动, 0 无动作, 1 动作\n\
int16 gear #档位指令 0:空挡 1:前进档 2:倒车档\n\
###############\n\
float32 dump_bed #货箱举升高度指令 0-100\n\
bool powerSupply_b # 断电指令, 0 无动作, 1 动作\n\
bool engine_b # 发送机熄火指令, 0 无动作, 1 动作\n\
bool turtle_b # 龟速模式, 0 无动作, 1 动作\n\
bool lubricate_b # 强制润滑, 0 无动作, 1 动作\n\
bool firePrevent_b # 消防, 0 无动作, 1 动作\n\
bool emergencyBrake_b # 紧急制动, 0 无动作, 1 动作\n\
bool lighting_b # 照明, 0 无动作, 1 动作\n\
bool horn_b # 喇叭, 0 无动作, 1 动作\n\
bool leftLamp_b\n\
bool rightLamp_b # 转向灯, 0 无动作, 1 动作\n\
bool bothLamp_b # 双闪, 0 无动作, 1 动作\n\
";
}
static const char* value(const ::my_project_test::ctr_can_MT4000_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::my_project_test::ctr_can_MT4000_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.driveMode_b);
stream.next(m.throttle);
stream.next(m.electronic_break);
stream.next(m.hydraulic_break);
stream.next(m.steerAngle);
stream.next(m.park_b);
stream.next(m.loadBrake_b);
stream.next(m.gear);
stream.next(m.dump_bed);
stream.next(m.powerSupply_b);
stream.next(m.engine_b);
stream.next(m.turtle_b);
stream.next(m.lubricate_b);
stream.next(m.firePrevent_b);
stream.next(m.emergencyBrake_b);
stream.next(m.lighting_b);
stream.next(m.horn_b);
stream.next(m.leftLamp_b);
stream.next(m.rightLamp_b);
stream.next(m.bothLamp_b);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct ctr_can_MT4000_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::my_project_test::ctr_can_MT4000_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::my_project_test::ctr_can_MT4000_<ContainerAllocator>& v)
{
s << indent << "driveMode_b: ";
Printer<uint8_t>::stream(s, indent + " ", v.driveMode_b);
s << indent << "throttle: ";
Printer<float>::stream(s, indent + " ", v.throttle);
s << indent << "electronic_break: ";
Printer<float>::stream(s, indent + " ", v.electronic_break);
s << indent << "hydraulic_break: ";
Printer<float>::stream(s, indent + " ", v.hydraulic_break);
s << indent << "steerAngle: ";
Printer<float>::stream(s, indent + " ", v.steerAngle);
s << indent << "park_b: ";
Printer<uint8_t>::stream(s, indent + " ", v.park_b);
s << indent << "loadBrake_b: ";
Printer<uint8_t>::stream(s, indent + " ", v.loadBrake_b);
s << indent << "gear: ";
Printer<int16_t>::stream(s, indent + " ", v.gear);
s << indent << "dump_bed: ";
Printer<float>::stream(s, indent + " ", v.dump_bed);
s << indent << "powerSupply_b: ";
Printer<uint8_t>::stream(s, indent + " ", v.powerSupply_b);
s << indent << "engine_b: ";
Printer<uint8_t>::stream(s, indent + " ", v.engine_b);
s << indent << "turtle_b: ";
Printer<uint8_t>::stream(s, indent + " ", v.turtle_b);
s << indent << "lubricate_b: ";
Printer<uint8_t>::stream(s, indent + " ", v.lubricate_b);
s << indent << "firePrevent_b: ";
Printer<uint8_t>::stream(s, indent + " ", v.firePrevent_b);
s << indent << "emergencyBrake_b: ";
Printer<uint8_t>::stream(s, indent + " ", v.emergencyBrake_b);
s << indent << "lighting_b: ";
Printer<uint8_t>::stream(s, indent + " ", v.lighting_b);
s << indent << "horn_b: ";
Printer<uint8_t>::stream(s, indent + " ", v.horn_b);
s << indent << "leftLamp_b: ";
Printer<uint8_t>::stream(s, indent + " ", v.leftLamp_b);
s << indent << "rightLamp_b: ";
Printer<uint8_t>::stream(s, indent + " ", v.rightLamp_b);
s << indent << "bothLamp_b: ";
Printer<uint8_t>::stream(s, indent + " ", v.bothLamp_b);
}
};
} // namespace message_operations
} // namespace ros
#endif // MY_PROJECT_TEST_MESSAGE_CTR_CAN_MT4000_H
| [
"wa198361@163.com"
] | wa198361@163.com |
8fb96f10e6e8b2da60efeb90b9d84dbb8559b841 | d2973f38d84ea50dbaf83369fd200c13e1591a3c | /Two Buttons.cpp | 4fb9f76c88645b2c3d5f3b03ae6d10ca6230b075 | [] | no_license | ShahriarDhruvo/Online-Programming-Problems-Solutions | c8ce392c9b4bec6805e18d37fb11c9f2200622a5 | 472fdb16480181ea3600b839ab402ef976294886 | refs/heads/master | 2020-05-30T08:50:07.345342 | 2020-04-02T15:20:32 | 2020-04-02T15:20:32 | 189,627,403 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 337 | cpp | #include <bits/stdc++.h>
#define FastIO ios_base::sync_with_stdio(false)
using namespace std;
int main()
{
//FastIO;
int n, m, l, count = 0;
cin >> n >> m;
while(n < m) {
if(m%2) m++;
else m /= 2;
count++;
}
count = count + n - m;
cout << count << "\n";
return 0;
}
| [
"shahriarelahi3062@gmail.com"
] | shahriarelahi3062@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.