blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b20cf5c1b10d9ccd3089996857187522f7ed4387 | 9d364070c646239b2efad7abbab58f4ad602ef7b | /platform/external/chromium_org/content/plugin/webplugin_proxy.h | 5124ade68a8e2c38e33323f6ecc0fdbd5bf339f6 | [
"BSD-3-Clause"
] | permissive | denix123/a32_ul | 4ffe304b13c1266b6c7409d790979eb8e3b0379c | b2fd25640704f37d5248da9cc147ed267d4771c2 | refs/heads/master | 2021-01-17T20:21:17.196296 | 2016-08-16T04:30:53 | 2016-08-16T04:30:53 | 65,786,970 | 0 | 2 | null | 2020-03-06T22:00:52 | 2016-08-16T04:15:54 | null | UTF-8 | C++ | false | false | 6,910 | 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_PLUGIN_WEBPLUGIN_PROXY_H_
#define CONTENT_PLUGIN_WEBPLUGIN_PROXY_H_
#include <string>
#include "base/containers/hash_tables.h"
#include "base/memory/ref_counted.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_cftyperef.h"
#endif
#include "base/memory/scoped_ptr.h"
#include "base/memory/shared_memory.h"
#include "base/memory/weak_ptr.h"
#include "base/timer/timer.h"
#include "content/child/npapi/webplugin.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_sender.h"
#include "skia/ext/refptr.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "url/gurl.h"
#include "ui/gl/gpu_preference.h"
#include "ui/surface/transport_dib.h"
struct PluginMsg_FetchURL_Params;
namespace content {
class PluginChannel;
class WebPluginDelegateImpl;
#if defined(OS_MACOSX)
class WebPluginAcceleratedSurfaceProxy;
#endif
class WebPluginProxy : public WebPlugin,
public IPC::Sender {
public:
WebPluginProxy(PluginChannel* channel,
int route_id,
const GURL& page_url,
int host_render_view_routing_id);
virtual ~WebPluginProxy();
void set_delegate(WebPluginDelegateImpl* d) { delegate_ = d; }
virtual void SetWindow(gfx::PluginWindowHandle window) OVERRIDE;
virtual void SetAcceptsInputEvents(bool accepts) OVERRIDE;
virtual void WillDestroyWindow(gfx::PluginWindowHandle window) OVERRIDE;
virtual void CancelResource(unsigned long id) OVERRIDE;
virtual void Invalidate() OVERRIDE;
virtual void InvalidateRect(const gfx::Rect& rect) OVERRIDE;
virtual NPObject* GetWindowScriptNPObject() OVERRIDE;
virtual NPObject* GetPluginElement() OVERRIDE;
virtual bool FindProxyForUrl(const GURL& url,
std::string* proxy_list) OVERRIDE;
virtual void SetCookie(const GURL& url,
const GURL& first_party_for_cookies,
const std::string& cookie) OVERRIDE;
virtual std::string GetCookies(const GURL& url,
const GURL& first_party_for_cookies) OVERRIDE;
virtual void HandleURLRequest(const char* url,
const char* method,
const char* target,
const char* buf,
unsigned int len,
int notify_id,
bool popups_allowed,
bool notify_redirects) OVERRIDE;
void UpdateGeometry(const gfx::Rect& window_rect,
const gfx::Rect& clip_rect,
const TransportDIB::Handle& windowless_buffer0,
const TransportDIB::Handle& windowless_buffer1,
int windowless_buffer_index);
virtual void CancelDocumentLoad() OVERRIDE;
virtual void InitiateHTTPRangeRequest(
const char* url, const char* range_info, int range_request_id) OVERRIDE;
virtual void DidStartLoading() OVERRIDE;
virtual void DidStopLoading() OVERRIDE;
virtual void SetDeferResourceLoading(unsigned long resource_id,
bool defer) OVERRIDE;
virtual bool IsOffTheRecord() OVERRIDE;
virtual void ResourceClientDeleted(
WebPluginResourceClient* resource_client) OVERRIDE;
virtual void URLRedirectResponse(bool allow, int resource_id) OVERRIDE;
virtual bool CheckIfRunInsecureContent(const GURL& url) OVERRIDE;
#if defined(OS_WIN)
void SetWindowlessData(HANDLE pump_messages_event,
gfx::NativeViewId dummy_activation_window);
#endif
#if defined(OS_MACOSX)
virtual void FocusChanged(bool focused) OVERRIDE;
virtual void StartIme() OVERRIDE;
virtual WebPluginAcceleratedSurface*
GetAcceleratedSurface(gfx::GpuPreference gpu_preference) OVERRIDE;
virtual void AcceleratedPluginEnabledRendering() OVERRIDE;
virtual void AcceleratedPluginAllocatedIOSurface(int32 width,
int32 height,
uint32 surface_id) OVERRIDE;
virtual void AcceleratedPluginSwappedIOSurface() OVERRIDE;
#endif
virtual bool Send(IPC::Message* msg) OVERRIDE;
WebPluginResourceClient* GetResourceClient(int id);
int GetRendererId();
int host_render_view_routing_id() const {
return host_render_view_routing_id_;
}
void Paint(const gfx::Rect& rect);
void DidPaint();
void OnResourceCreated(int resource_id, WebPluginResourceClient* client);
#if defined(OS_WIN) && !defined(USE_AURA)
void UpdateIMEStatus();
#endif
private:
class SharedTransportDIB : public base::RefCounted<SharedTransportDIB> {
public:
explicit SharedTransportDIB(TransportDIB* dib);
TransportDIB* dib() { return dib_.get(); }
private:
friend class base::RefCounted<SharedTransportDIB>;
~SharedTransportDIB();
scoped_ptr<TransportDIB> dib_;
};
void OnPaint(const gfx::Rect& damaged_rect);
#if defined(OS_WIN)
void CreateCanvasFromHandle(const TransportDIB::Handle& dib_handle,
const gfx::Rect& window_rect,
skia::RefPtr<SkCanvas>* canvas);
#elif defined(OS_MACOSX)
static void CreateDIBAndCGContextFromHandle(
const TransportDIB::Handle& dib_handle,
const gfx::Rect& window_rect,
scoped_ptr<TransportDIB>* dib_out,
base::ScopedCFTypeRef<CGContextRef>* cg_context_out);
#endif
void SetWindowlessBuffers(const TransportDIB::Handle& windowless_buffer0,
const TransportDIB::Handle& windowless_buffer1,
const gfx::Rect& window_rect);
#if defined(OS_MACOSX)
CGContextRef windowless_context() const {
return windowless_contexts_[windowless_buffer_index_].get();
}
#else
skia::RefPtr<SkCanvas> windowless_canvas() const {
return windowless_canvases_[windowless_buffer_index_];
}
#endif
typedef base::hash_map<int, WebPluginResourceClient*> ResourceClientMap;
ResourceClientMap resource_clients_;
scoped_refptr<PluginChannel> channel_;
int route_id_;
NPObject* window_npobject_;
NPObject* plugin_element_;
WebPluginDelegateImpl* delegate_;
gfx::Rect damaged_rect_;
bool waiting_for_paint_;
GURL page_url_;
int windowless_buffer_index_;
#if defined(OS_MACOSX)
scoped_ptr<TransportDIB> windowless_dibs_[2];
base::ScopedCFTypeRef<CGContextRef> windowless_contexts_[2];
scoped_ptr<WebPluginAcceleratedSurfaceProxy> accelerated_surface_;
#else
skia::RefPtr<SkCanvas> windowless_canvases_[2];
#endif
int host_render_view_routing_id_;
base::WeakPtrFactory<WebPluginProxy> weak_factory_;
};
}
#endif
| [
"allegrant@mail.ru"
] | allegrant@mail.ru |
2579feed33a3affe2a76e0e519eaaedb5ce8befe | 4b8296335e4fa1a38264fef02f430d3b57884cce | /third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.cc | 08b8f0b071fbeae6273eb8f73d71c5285ff2542c | [
"BSD-3-Clause",
"BSD-2-Clause",
"LGPL-2.1-only",
"LGPL-2.0-only",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] | permissive | coxchris502/chromium | 07ad6d930123bbf6e1754fe1820505f21d719fcd | f786352782a89d148a10d7bdd8ef3d0a86497926 | refs/heads/master | 2022-11-06T23:54:53.001812 | 2020-07-03T14:54:27 | 2020-07-03T14:54:27 | 276,935,925 | 1 | 0 | BSD-3-Clause | 2020-07-03T15:49:58 | 2020-07-03T15:49:57 | null | UTF-8 | C++ | false | false | 11,308 | 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 "third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.h"
#include "third_party/blink/renderer/core/dom/node.h"
#include "third_party/blink/renderer/core/layout/geometry/logical_size.h"
#include "third_party/blink/renderer/core/layout/geometry/physical_rect.h"
#include "third_party/blink/renderer/core/layout/layout_text_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_text_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_ink_overflow.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
namespace blink {
namespace {
struct SameSizeAsNGPhysicalTextFragment : NGPhysicalFragment {
void* pointers[3];
unsigned offsets[2];
};
static_assert(sizeof(NGPhysicalTextFragment) ==
sizeof(SameSizeAsNGPhysicalTextFragment),
"NGPhysicalTextFragment should stay small");
} // anonymous namespace
NGPhysicalTextFragment::NGPhysicalTextFragment(
PassKey key,
const NGPhysicalTextFragment& source,
unsigned start_offset,
unsigned end_offset,
scoped_refptr<const ShapeResultView> shape_result)
: NGPhysicalFragment(
source.GetMutableLayoutObject(),
source.StyleVariant(),
source.IsHorizontal()
? PhysicalSize{shape_result->SnappedWidth(), source.Size().height}
: PhysicalSize{source.Size().width, shape_result->SnappedWidth()},
kFragmentText,
static_cast<unsigned>(source.TextType())),
text_(source.text_),
text_offset_(start_offset, end_offset),
shape_result_(std::move(shape_result)) {
DCHECK_GE(text_offset_.start, source.StartOffset());
DCHECK_LE(text_offset_.end, source.EndOffset());
DCHECK(shape_result_ || IsFlowControl()) << *this;
base_or_resolved_direction_ = source.base_or_resolved_direction_;
ink_overflow_computed_or_mathml_paint_info_ = false;
}
NGPhysicalTextFragment::NGPhysicalTextFragment(NGTextFragmentBuilder* builder)
: NGPhysicalFragment(builder,
kFragmentText,
static_cast<unsigned>(builder->text_type_)),
text_(builder->text_),
text_offset_(builder->text_offset_),
shape_result_(std::move(builder->shape_result_)) {
DCHECK(shape_result_ || IsFlowControl()) << *this;
base_or_resolved_direction_ =
static_cast<unsigned>(builder->ResolvedDirection());
ink_overflow_computed_or_mathml_paint_info_ = false;
}
bool NGPhysicalTextFragment::IsGeneratedText() const {
if (UNLIKELY(TextType() == NGTextType::kLayoutGenerated))
return true;
return GetLayoutObject()->IsStyleGenerated();
}
LayoutUnit NGPhysicalTextFragment::InlinePositionForOffset(
unsigned offset,
LayoutUnit (*round_function)(float),
AdjustMidCluster adjust_mid_cluster) const {
return NGFragmentItem(*this).InlinePositionForOffset(
Text(), offset, round_function, adjust_mid_cluster);
}
// TODO(yosin): We should move |NGFragmentItem::InlinePositionForOffset" to
// "ng_fragment_item.cc"
// Compute the inline position from text offset, in logical coordinate relative
// to this fragment.
LayoutUnit NGFragmentItem::InlinePositionForOffset(
StringView text,
unsigned offset,
LayoutUnit (*round_function)(float),
AdjustMidCluster adjust_mid_cluster) const {
DCHECK_GE(offset, StartOffset());
DCHECK_LE(offset, EndOffset());
DCHECK_EQ(text.length(), TextLength());
offset -= StartOffset();
if (TextShapeResult()) {
// TODO(layout-dev): Move caret position out of ShapeResult and into a
// separate support class that can take a ShapeResult or ShapeResultView.
// Allows for better code separation and avoids the extra copy below.
return round_function(
TextShapeResult()->CreateShapeResult()->CaretPositionForOffset(
offset, text, adjust_mid_cluster));
}
// This fragment is a flow control because otherwise ShapeResult exists.
DCHECK(IsFlowControl());
DCHECK_EQ(1u, text.length());
if (!offset || UNLIKELY(IsRtl(Style().Direction())))
return LayoutUnit();
return IsHorizontal() ? Size().width : Size().height;
}
// TODO(yosin): We should move |NGFragmentItem::InlinePositionForOffset" to
// "ng_fragment_item.cc"
LayoutUnit NGFragmentItem::InlinePositionForOffset(StringView text,
unsigned offset) const {
return InlinePositionForOffset(text, offset, LayoutUnit::FromFloatRound,
AdjustMidCluster::kToEnd);
}
LayoutUnit NGPhysicalTextFragment::InlinePositionForOffset(
unsigned offset) const {
return NGFragmentItem(*this).InlinePositionForOffset(Text(), offset);
}
std::pair<LayoutUnit, LayoutUnit>
NGPhysicalTextFragment::LineLeftAndRightForOffsets(unsigned start_offset,
unsigned end_offset) const {
return NGFragmentItem(*this).LineLeftAndRightForOffsets(Text(), start_offset,
end_offset);
}
// TODO(yosin): We should move |NGFragmentItem::InlinePositionForOffset" to
// "ng_fragment_item.cc"
std::pair<LayoutUnit, LayoutUnit> NGFragmentItem::LineLeftAndRightForOffsets(
StringView text,
unsigned start_offset,
unsigned end_offset) const {
DCHECK_LE(start_offset, EndOffset());
DCHECK_GE(start_offset, StartOffset());
DCHECK_LE(end_offset, EndOffset());
const LayoutUnit start_position =
InlinePositionForOffset(text, start_offset, LayoutUnit::FromFloatFloor,
AdjustMidCluster::kToStart);
const LayoutUnit end_position = InlinePositionForOffset(
text, end_offset, LayoutUnit::FromFloatCeil, AdjustMidCluster::kToEnd);
// Swap positions if RTL.
return (UNLIKELY(start_position > end_position))
? std::make_pair(end_position, start_position)
: std::make_pair(start_position, end_position);
}
PhysicalRect NGPhysicalTextFragment::LocalRect(unsigned start_offset,
unsigned end_offset) const {
return NGFragmentItem(*this).LocalRect(Text(), start_offset, end_offset);
}
// TODO(yosin): We should move |NGFragmentItem::InlinePositionForOffset" to
// "ng_fragment_item.cc"
PhysicalRect NGFragmentItem::LocalRect(StringView text,
unsigned start_offset,
unsigned end_offset) const {
if (start_offset == StartOffset() && end_offset == EndOffset())
return LocalRect();
LayoutUnit start_position, end_position;
std::tie(start_position, end_position) =
LineLeftAndRightForOffsets(text, start_offset, end_offset);
const LayoutUnit inline_size = end_position - start_position;
switch (GetWritingMode()) {
case WritingMode::kHorizontalTb:
return {start_position, LayoutUnit(), inline_size, Size().height};
case WritingMode::kVerticalRl:
case WritingMode::kVerticalLr:
case WritingMode::kSidewaysRl:
return {LayoutUnit(), start_position, Size().width, inline_size};
case WritingMode::kSidewaysLr:
return {LayoutUnit(), Size().height - end_position, Size().width,
inline_size};
}
NOTREACHED();
return {};
}
PhysicalRect NGPhysicalTextFragment::SelfInkOverflow() const {
if (!ink_overflow_computed_or_mathml_paint_info_)
ComputeSelfInkOverflow();
if (ink_overflow_)
return ink_overflow_->self_ink_overflow;
return LocalRect();
}
void NGPhysicalTextFragment::ComputeSelfInkOverflow() const {
ink_overflow_computed_or_mathml_paint_info_ = true;
if (UNLIKELY(!shape_result_)) {
ink_overflow_ = nullptr;
return;
}
base::Optional<PhysicalRect> ink_overflow =
NGInkOverflow::ComputeTextInkOverflow(PaintInfo(), Style(), Size());
if (!ink_overflow) {
ink_overflow_.reset();
return;
}
if (ink_overflow_)
ink_overflow_->self_ink_overflow = *ink_overflow;
else
ink_overflow_ = std::make_unique<NGSelfInkOverflow>(*ink_overflow);
}
scoped_refptr<const NGPhysicalTextFragment>
NGPhysicalTextFragment::CloneAsHiddenForPaint() const {
NGTextFragmentBuilder builder(*this);
builder.SetIsHiddenForPaint(true);
return builder.ToTextFragment();
}
scoped_refptr<const NGPhysicalTextFragment> NGPhysicalTextFragment::TrimText(
unsigned new_start_offset,
unsigned new_end_offset) const {
DCHECK(shape_result_);
DCHECK_GE(new_start_offset, StartOffset());
DCHECK_GT(new_end_offset, new_start_offset);
DCHECK_LE(new_end_offset, EndOffset());
scoped_refptr<ShapeResultView> new_shape_result = ShapeResultView::Create(
shape_result_.get(), new_start_offset, new_end_offset);
return base::AdoptRef(
new NGPhysicalTextFragment(PassKey(), *this, new_start_offset,
new_end_offset, std::move(new_shape_result)));
}
unsigned NGPhysicalTextFragment::TextOffsetForPoint(
const PhysicalOffset& point) const {
const ComputedStyle& style = Style();
const LayoutUnit& point_in_line_direction =
style.IsHorizontalWritingMode() ? point.left : point.top;
if (const ShapeResultView* shape_result = TextShapeResult()) {
// TODO(layout-dev): Move caret logic out of ShapeResult into separate
// support class for code health and to avoid this copy.
return shape_result->CreateShapeResult()->CaretOffsetForHitTest(
point_in_line_direction.ToFloat(), Text(), BreakGlyphs) +
StartOffset();
}
// Flow control fragments such as forced line break, tabulation, soft-wrap
// opportunities, etc. do not have ShapeResult.
DCHECK(IsFlowControl());
// Zero-inline-size objects such as newline always return the start offset.
LogicalSize size = Size().ConvertToLogical(style.GetWritingMode());
if (!size.inline_size)
return StartOffset();
// Sized objects such as tabulation returns the next offset if the given point
// is on the right half.
LayoutUnit inline_offset = IsLtr(ResolvedDirection())
? point_in_line_direction
: size.inline_size - point_in_line_direction;
DCHECK_EQ(1u, TextLength());
return inline_offset <= size.inline_size / 2 ? StartOffset() : EndOffset();
}
UBiDiLevel NGPhysicalTextFragment::BidiLevel() const {
// TODO(xiaochengh): Make the implementation more efficient with, e.g.,
// binary search and/or LayoutNGText::InlineItems().
const auto& items = InlineItemsOfContainingBlock();
const NGInlineItem* containing_item = std::find_if(
items.begin(), items.end(), [this](const NGInlineItem& item) {
return item.StartOffset() <= StartOffset() &&
item.EndOffset() >= EndOffset();
});
DCHECK(containing_item);
DCHECK_NE(containing_item, items.end());
return containing_item->BidiLevel();
}
} // namespace blink
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
3b89723ccd62ef72a54e4e1e930fe31278d36d23 | dda0ee560d1cff47d9eaf0599e1f5d491765ec7b | /Lab4/task2/tests/tests.cpp | 31b0f2827b9ddfe3bd4bfef355f8503023fe0eb3 | [] | no_license | DenisTuxvatullin/Person | a380f6e479d76ea30890b3d482681943fb747659 | e4fa03043fc99b6b9e7ffe9c5da07d4a396f5935 | refs/heads/master | 2020-06-10T15:54:02.219806 | 2017-04-13T13:07:23 | 2017-04-13T13:07:23 | 75,945,695 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 2,071 | cpp | // tests.cpp: определяет точку входа для консольного приложения.
//
#include "stdafx.h"
#include "../task2/Student.h"
using namespace std;
static const string NAME = "STUDENT POLITEHA";
static const int STUDY_YEAR = 2;
static const int AGE = 12;
static const int WEIGHT = 50;
static const int GROWTH = 150;
static const string UNAME = "PGTU";
struct UniverFixture
{
CUniversity univer;
UniverFixture()
:univer(UNAME)
{
}
};
struct StudentFixture
{
CStudent student;
StudentFixture()
:student(NAME, true, AGE, WEIGHT, GROWTH, nullptr, STUDY_YEAR)
{
}
};
BOOST_FIXTURE_TEST_SUITE(StudentTest, StudentFixture)
BOOST_AUTO_TEST_CASE(StudentDefaultParams)
{
BOOST_CHECK_EQUAL(student.GetAge(), AGE);
BOOST_CHECK_EQUAL(student.GetGrowth(), GROWTH);
BOOST_CHECK_EQUAL(student.GetWeight(), WEIGHT);
BOOST_CHECK_EQUAL(student.GetYearOfStudy(), STUDY_YEAR);
BOOST_CHECK_EQUAL(student.GetName(), NAME);
BOOST_CHECK_EQUAL(student.IsMale(), true);
}
BOOST_AUTO_TEST_CASE(StudentWithChangedParams)
{
auto universityNew = std::make_shared<CUniversity>("VolgaVolgatech");
student.SetName("Student");
BOOST_CHECK_EQUAL(student.GetName(), "Student");
student.SetAge(20);
student.SetGrowth(180);
student.SetWeight(70);
student.SetYearOfStudy(3);
student.SetUniversity(universityNew);
BOOST_CHECK_EQUAL(student.GetAge(), 20);
BOOST_CHECK_EQUAL(student.GetWeight(), 70);
BOOST_CHECK_EQUAL(student.GetGrowth(), 180);
BOOST_CHECK_EQUAL(student.GetUniversity(), universityNew);
BOOST_CHECK(student.IsMale());
BOOST_CHECK_EQUAL(student.GetYearOfStudy(), 3);
BOOST_CHECK_EQUAL(universityNew->GetName(), "VolgaVolgatech");
}
BOOST_AUTO_TEST_SUITE_END()
//////////////////////////////////////////////////////////
BOOST_FIXTURE_TEST_SUITE(UniverTest, UniverFixture)
BOOST_AUTO_TEST_CASE(UniverDefaultParams)
{
BOOST_CHECK_EQUAL(univer.GetName(), UNAME);
}
BOOST_AUTO_TEST_CASE(UniverWithChangedParams)
{
univer.SetName("MGTU");
BOOST_CHECK_EQUAL(univer.GetName(), "MGTU");
}
BOOST_AUTO_TEST_SUITE_END()
| [
"den44icc@mail.ru"
] | den44icc@mail.ru |
7d1d361acfbcab265c0b685aa91b0e15432f8240 | ca0e996c1aa0fa02401eca7dfb6dc4eb210a69a2 | /analysis/run_simu.cpp | 59efb71e35ec018dd1fefecabacebd8821e08bd3 | [] | no_license | zhanglianhao/qt | de569d1e34ad6519f6cdb0258d6e14ba5efddab1 | 97f04780ef06cfcc5d3c3697d77b81e11b4658cc | refs/heads/master | 2021-09-25T14:33:55.191537 | 2018-10-23T02:04:09 | 2018-10-23T02:04:09 | 154,247,443 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 51,862 | cpp | #include "run_simu.h"
#include <math.h>
#include "analysis.h"
#include "mainwindow.h"
Run_Simu::Run_Simu(QWidget *parent,moudel_group* group,double time_length,double time_step,bool real_flag) : QMainWindow(parent),simulation_group(group)
{
time.simu_time=time_length;
time.simu_step=time_step;
time.simu_count_max=int(time.simu_time/time.simu_step);
this->flag_real=real_flag;
init();
}
void Run_Simu::init()
{
statusBar_init();
setAutoFillBackground(true);//必须有这条语句
setPalette(QPalette(QColor(100,150,200)));//设置背景颜色
connect(&mDataTimer, SIGNAL(timeout()), this, SLOT(timerSlot()));
for(int i=0;i<ui->x_count;i++)
{
time_label.push_back(new QLabel(this));
time_label[time_label.size()-1]->setGeometry(ui->x_start+ui->x_axia_precision*ui->x_interval_point*i,ui->y_start+2,ui->x_axia_precision*ui->x_interval_point-3,20);
}
for(int i=0;i<this->ui->y_count;i++)
{
value_label.push_back(new QLabel(this));
value_label[value_label.size()-1]->setGeometry(ui->x_start-40,ui->y_start-12-ui->y_axis_length/ui->y_count*(i+1),35,20);
value_label.push_back(new QLabel(this));
value_label[value_label.size()-1]->setGeometry(ui->x_start-40,ui->y_start-12+ui->y_axis_length/ui->y_count*(i+1),35,20);
}
}
void Run_Simu::statusBar_init()
{
statusBar=new QStatusBar(this);
statusBar->setObjectName(QStringLiteral("statusBar"));
this->setStatusBar(statusBar);
start_stop=new QPushButton(this);
start_stop->setVisible(true);
start_stop->setText("运行");
connect(start_stop, &QAbstractButton::clicked, this, &Run_Simu::simu_run);
run_stop_state=true;
}
void Run_Simu::simu_run()
{
if(this->real_flag==true)
{
this->parent->statr_message("Currently is in connection state",1000);
return;
}
if(run_stop_state==true)
{
run_stop_state=false;
start_stop->setText("停止");
mDataTimer.stop();
}
else
{
run_stop_state=true;
start_stop->setText("运行");
mDataTimer.start(10);
}
}
bool Run_Simu::getstate()
{
return this->run_stop_state;
}
void Run_Simu::statusBar_show()
{
this->statusBar->showMessage("save",1000);
}
void Run_Simu::timerSlot()
{
//qint64 time_before=QTime::currentTime().msec();
time_before=QDateTime::currentDateTime().time();//QDateTime比Qtime获取毫秒级时间更精确
//qDebug()<<time_before<<1;
if(time.simu_count<=time.simu_count_max)
{
for(int i=0;i<this->moudle_generator->group.size();i++)
{
//qDebug()<<QDateTime::currentDateTime();
//this->simulation_group->group[0]->output_number[0]=i;
output_generator(this->moudle_generator->group[i],time.simu_count);
run_simulation(this->moudle_generator->group[i]);
//qDebug()<<QDateTime::currentDateTime();
//qDebug()<<"\n";
}
/*
for(int i=0;i<this->moudle_socket->group.size();i++)
{
run_socket(this->moudle_socket->group[i]);
}
*/
time.simu_count++;
this->draw_point_flag=true;
}
//qDebug()<<QDateTime::currentDateTime()<<1;
update();
if(time.simu_count>time.simu_count_max)
{
run_end_flag=true;//仿真结束
this->real_flag=false;
int index=this->parent->run_to_mainwindow(this);
if(index!=-1)//运行结束,断开所有客户端连接
{
if(this->parent->mainwindow_group[index]->sys_flag->socket_main!=nullptr)
this->parent->mainwindow_group[index]->sys_flag->socket_main->disconnectFromHost();
this->parent->mainwindow_group[index]->disconnect_input(0);
}
//mDataTimer.stop();
mDataTimer.start(100);
}
else if(time.simu_count==time.simu_count_max)//是否保存数据
{
this->save_graph_date();
}
else
{
if(this->flag_real==true)
mDataTimer.start(int(time.simu_step*1000));
else
mDataTimer.start(10);
clear_save_flag();//清save标志
//qDebug()<<QTime::currentTime().msec();
}
}
void Run_Simu::change()
{
QPushButton* button=qobject_cast<QPushButton*>(sender());
int index=this->ui->graph_group.indexOf(button);
if(this->moudle_graph->group[index]->grapg_flag==false)
{
this->moudle_graph->group[index]->grapg_flag=true;
remove_shadow(button);
}
else
{
this->moudle_graph->group[index]->grapg_flag=false;
set_shadow(button);
}
update();
}
void Run_Simu::mousePressEvent(QMouseEvent* event)
{
this->parent->run_current=this;
QPoint point=this->mapFromGlobal(event->globalPos());
QRect rect(ui->x_start,ui->y_start-ui->y_axis_length,ui->x_length,ui->y_axis_length*2);
this->setFocusPolicy(Qt::StrongFocus);
if(this->ui->start_drag)
{
if(rect.contains(point))
{
this->time.time_drag=this->time.time_temp;
this->ui->drag_x_start=point.x();
}
}
}//按下
void Run_Simu::mouseMoveEvent(QMouseEvent* event)
{
QPoint point=this->mapFromGlobal(event->globalPos());
if(this->ui->start_drag)
{
if((this->time.time_temp-point.x()+this->ui->drag_x_start)>=((ui->x_count-1)*ui->x_interval_point)&&(this->time.time_temp-point.x()+this->ui->drag_x_start)<=this->time.simu_count)
{
this->time.time_drag=this->time.time_temp-point.x()+this->ui->drag_x_start;
update();
}
}
}//按下移动
void Run_Simu::mouseReleaseEvent(QMouseEvent* event)
{
if(this->ui->start_drag)
{
this->time.time_temp=this->time.time_drag;
}
}//松开
void Run_Simu::keyReleaseEvent(QKeyEvent *event)
{
}
void Run_Simu::keyPressEvent(QKeyEvent *event)
{
if(event->key()==Qt::Key_Z)
{
if(this->ui->start_drag)
{
this->ui->start_drag=false;
update();
}
else
{
if(this->time.simu_count>((ui->x_count-1)*ui->x_interval_point))
this->ui->start_drag=true;
}
}
if(event->modifiers() == Qt::ControlModifier&&(event->key() == Qt::Key_S))
{
this->save_graph_date();
}
}
void Run_Simu::wheelEvent(QWheelEvent* event)
{
if(check_focus()==-1)
return;
//qDebug()<<this->ui->x_axia_precision;
if(event->delta()>0)//缩小
{
//qDebug()<<(time.time_drag-((ui->x_count-1)*ui->x_interval_point))<<time.time_drag;
if(this->ui->x_axia_precision>1)
{
this->ui->x_axia_precision--;
while(this->ui->x_interview_length%this->ui->x_axia_precision!=0)
{
this->ui->x_axia_precision--;
if(this->ui->x_axia_precision==1)
break;
}
if(!(this->ui->start_drag&&time.time_drag-((ui->x_count-1)*this->ui->x_interview_length/this->ui->x_axia_precision)<0))
{
this->ui->x_interval_point=this->ui->x_interview_length/this->ui->x_axia_precision;
}
}
}
else if(event->delta()<0)//放大
{
if(this->ui->x_axia_precision<this->ui->x_interview_length)
{
this->ui->x_axia_precision++;
while(this->ui->x_interview_length%this->ui->x_axia_precision!=0)
{
this->ui->x_axia_precision++;
if(this->ui->x_axia_precision==this->ui->x_interview_length)
break;
}
this->ui->x_interval_point=this->ui->x_interview_length/this->ui->x_axia_precision;
}
}
}
void Run_Simu::paintEvent(QPaintEvent *)
{
//qDebug()<<QDateTime::currentDateTime()<<2;
QPainter painter(this);//painter画笔只能是从属于当前类
// if(draw_point_flag)
// {
update_size();
check_focus();
if(this->draw_point_flag==true||this->time.simu_count>this->time.simu_count_max)
{
check_data();
if(this->ui->start_drag!=true)
{
if(this->time.simu_count<((ui->x_count-1)*ui->x_interval_point))
get_max(0,this->time.simu_count);
else
get_max(this->time.simu_count-((ui->x_count-1)*ui->x_interval_point-1),this->time.simu_count);
}
else
{
get_max(this->time.time_drag-((ui->x_count-1)*ui->x_interval_point-1),this->time.time_drag);
}
for(int i=0;i<this->moudle_graph->group.size();i++)
{
if(i==0)
painter.setPen(QPen(Qt::black,2));
else if(i==1)
painter.setPen(QPen(Qt::red,2));
else if(i==2)
painter.setPen(QPen(Qt::green,2));
else if(i==3)
painter.setPen(QPen(Qt::yellow,2));
painter.drawLine(ui->graph_group[i]->x()-1,ui->graph_group[i]->y()+ui->graph_group[i]->height()/2,ui->graph_group[i]->x()-30,ui->graph_group[i]->y()+ui->graph_group[i]->height()/2);
//qDebug()<< this->moudle_graph->group.size();
if(this->moudle_graph->group[i]->grapg_flag==true&&this->moudle_graph->group[i]->graph_value.size()!=0)
{
//for(int j=0;j<this->moudle_graph->group[i]->graph_value.size();j++)
if(this->ui->start_drag!=true)
{
time.time_drag=time.simu_count;
this->time.time_temp=this->time.simu_count;
}
int x_pos=0;
for(int j=(time.time_drag-((ui->x_count-1)*ui->x_interval_point))>=0?(time.time_drag-((ui->x_count-1)*ui->x_interval_point)):0;j<time.time_drag;j++)
{
//qDebug()<<200-int(this->moudle_graph->group[i]->graph_value[j]);
if(this->ui->start_drag!=true)
{
if(x_pos==0)
{
painter.drawLine(ui->x_start+ui->x_axia_precision*x_pos,ui->y_start-int(this->moudle_graph->group[i]->graph_value[j]/this->value_limit*this->ui->y_axis_length),ui->x_start+ui->x_axia_precision*x_pos,ui->y_start-int(this->moudle_graph->group[i]->graph_value[j]/this->value_limit*this->ui->y_axis_length+1));
}
else
painter.drawLine(ui->x_start+ui->x_axia_precision*x_pos,ui->y_start-int(this->moudle_graph->group[i]->graph_value[j]/this->value_limit*this->ui->y_axis_length),ui->x_start+ui->x_axia_precision*(x_pos-1),ui->y_start-int(this->moudle_graph->group[i]->graph_value[j-1]/this->value_limit*this->ui->y_axis_length+1));
}
else
{
if(x_pos==0)
{
painter.drawLine(ui->x_start+ui->x_axia_precision*x_pos,ui->y_start-int(this->moudle_graph->group[i]->graph_value[j]/this->value_limit*this->ui->y_axis_length),ui->x_start+ui->x_axia_precision*x_pos,ui->y_start-int(this->moudle_graph->group[i]->graph_value[j]/this->value_limit*this->ui->y_axis_length+1));
}
else
painter.drawLine(ui->x_start+ui->x_axia_precision*x_pos,ui->y_start-int(this->moudle_graph->group[i]->graph_value[j]/this->value_limit*this->ui->y_axis_length),ui->x_start+ui->x_axia_precision*(x_pos-1),ui->y_start-int(this->moudle_graph->group[i]->graph_value[j-1]/this->value_limit*this->ui->y_axis_length+1));
}
x_pos++;
//painter.drawLine(10,100,100,100);
}
//当前时刻value显示及动画
if(this->check_focus()==-1||this->check_focus()>=this->moudle_graph->group[i]->graph_value.size())
{
this->ui->current_value[i]->setText("");
}
else
{
painter.setPen(Qt::PenStyle::DashLine);
int start=(time.time_drag-((ui->x_count-1)*ui->x_interval_point))>=0?(time.time_drag-((ui->x_count-1)*ui->x_interval_point)):0;
this->ui->current_value[i]->setText(QString::number(this->moudle_graph->group[i]->graph_value[start+this->check_focus()]));
// qDebug()<<this->moudle_graph->group[i]->graph_value[start+this->check_focus()];
painter.drawLine(ui->x_start+ui->x_axia_precision*this->check_focus(),ui->y_start-ui->y_axis_length,ui->x_start+ui->x_axia_precision*this->check_focus(),ui->y_start+ui->y_axis_length);
painter.drawLine(ui->x_start,ui->y_start-int(this->moudle_graph->group[i]->graph_value[start+this->check_focus()]/this->value_limit*this->ui->y_axis_length),ui->x_start+ui->x_length,ui->y_start-int(this->moudle_graph->group[i]->graph_value[start+this->check_focus()]/this->value_limit*this->ui->y_axis_length));
}
}
}
if(this->moudle_graph->group.size()!=0)
{
//qDebug()<<moudle_graph->group[0]->graph_value.size();
painter.setPen(QPen(Qt::black,2));
if(this->moudle_graph->group[0]->graph_value.size()<((ui->x_count-1)*ui->x_interval_point))
{
int temp=0;
for(int j=0;j<this->moudle_graph->group[0]->graph_value.size();j++)
{
this->time_label[j/ui->x_interval_point]->setText(QString::number(j/ui->x_interval_point*ui->x_interval_point*this->time.simu_step));
temp=j/ui->x_interval_point;
}
for(int i=temp+1;i<this->time_label.size();i++)
this->time_label[i]->setText("");
}
else
{
for(int j=0;j<ui->x_count;j++)
{
if(this->ui->start_drag!=true)
this->time_label[j]->setText(QString::number((this->time.simu_count-((ui->x_count-1)*ui->x_interval_point)+ui->x_interval_point*j)*this->time.simu_step));
else
this->time_label[j]->setText(QString::number((this->time.time_drag-((ui->x_count-1)*ui->x_interval_point)+ui->x_interval_point*j)*this->time.simu_step));
}
}
for(int j=0;j<ui->x_count;j++)
{
painter.drawLine(ui->x_start+j*ui->x_interval_point*ui->x_axia_precision,ui->y_start,ui->x_start+j*ui->x_interval_point*ui->x_axia_precision,ui->y_start+3);
}
for(int i=0;i<this->ui->y_count;i++)
{
this->value_label[i*2]->setText(QString::number(this->value_limit/this->ui->y_count*(i+1)));
painter.drawLine(this->ui->x_start,this->ui->y_start-this->ui->y_axis_length/this->ui->y_count*(i+1),this->ui->x_start-3,this->ui->y_start-this->ui->y_axis_length/this->ui->y_count*(i+1));
this->value_label[i*2+1]->setText(QString::number(-1*this->value_limit/this->ui->y_count*(i+1)));
painter.drawLine(this->ui->x_start,this->ui->y_start+this->ui->y_axis_length/this->ui->y_count*(i+1),this->ui->x_start-3,this->ui->y_start+this->ui->y_axis_length/this->ui->y_count*(i+1));
}
}
painter.drawLine(this->ui->x_start,this->ui->y_start,this->ui->x_start+this->ui->x_length,this->ui->y_start);
painter.drawLine(this->ui->x_start+this->ui->x_length+3,this->ui->y_start,this->ui->x_start+this->ui->x_length,this->ui->y_start-3);
painter.drawLine(this->ui->x_start+this->ui->x_length+3,this->ui->y_start,this->ui->x_start+this->ui->x_length,this->ui->y_start+3);
painter.drawLine(this->ui->x_start,this->ui->y_start-this->ui->y_axis_length-this->ui->y_invalid,this->ui->x_start+this->ui->x_length,this->ui->y_start-this->ui->y_axis_length-this->ui->y_invalid);
painter.drawLine(this->ui->x_start,this->ui->y_start+this->ui->y_axis_length+this->ui->y_invalid,this->ui->x_start+this->ui->x_length,this->ui->y_start+this->ui->y_axis_length+this->ui->y_invalid);
painter.drawLine(this->ui->x_start+this->ui->x_length+3,this->ui->y_start+this->ui->y_invalid+this->ui->y_axis_length,this->ui->x_start+this->ui->x_length+3,this->ui->y_start-this->ui->y_invalid-this->ui->y_axis_length);
painter.drawLine(this->ui->x_start,this->ui->y_start-this->ui->y_invalid-this->ui->y_axis_length,this->ui->x_start,this->ui->y_start+this->ui->y_invalid+this->ui->y_axis_length);
painter.drawLine(this->ui->x_start,this->ui->y_start-this->ui->y_invalid-this->ui->y_axis_length,this->ui->x_start-3,this->ui->y_start-this->ui->y_axis_length-this->ui->y_invalid+3);
painter.drawLine(this->ui->x_start,this->ui->y_start-this->ui->y_invalid-this->ui->y_axis_length,this->ui->x_start+3,this->ui->y_start-this->ui->y_axis_length-this->ui->y_invalid+3);
//this->draw_point_flag=false;
// }
//qDebug()<<QDateTime::currentDateTime()<<3;
if(this->time.simu_count<=this->time.simu_count_max)
{
//mDataTimer.start(int(time.simu_step*1000-time_before.msecsTo(QDateTime::currentDateTime().time())));//下次仿真时间为仿真步距减去上次程序运行时间与绘图时间
//mDataTimer.start(int(time.simu_step*1000));
//this->draw_point_flag=false;
//qDebug()<<QDateTime::currentDateTime()<<2;
}
else
{
//qDebug()<<QDateTime::currentDateTime();//计算实际仿真时间与设定仿真时间差
}
}
}
void Run_Simu::moudle_relation()
{
//qDebug()<<QThread::currentThreadId();
relation_init();
struct moudle_relation moudlee;
for(int i=0;i<this->simulation_group->group.size();i++)
{
Simulation_Moudle* moudle=this->simulation_group->group[i];
for(int m=0;m<moudle->output.size();m++)
{
moudle_param* param=moudle->output[m];
for(int n=0;n<param->connect_line.size();n++)
{
Line* linee=param->connect_line[n];
for(int j=0;j<linee->endbutton.size();j++)
{
moudlee.moudle=this->simulation_group->findwithbutton(linee->endbutton[j]);
moudlee.index=linee->endindex[j];
moudle->output[m]->next.push_back(moudlee);
}
}
}
}
detect_loop();//闭环检测
clear_process_value();
form();
form_graph();
qDebug()<<check_signal();//信号完整性检测
for(int i=0;i<this->moudle_graph->group.size();i++)
{
this->save_complete.push_back(false);
this->url.push_back("");
}//图表保存标志位初始化
/* for(int i=0;i<this->simulation_group->group.size();i++)
{
Simulation_Moudle* moudle=this->simulation_group->group[i];
for(int m=0;m<moudle->output.size();m++)
{
moudle_param* param=moudle->output[m];
for(int n=0;n<param->next.size();n++)
qDebug()<<param->next[n].moudle->id;
qDebug()<<"a";
}
qDebug()<<"a"<<"a";
}
*/
}
bool Run_Simu::check_signal()
{
for(int i=0;i<this->simulation_group->group.size();i++)
{
Simulation_Moudle* moudle=this->simulation_group->group[i];
for(int j=0;j<moudle->input_size;j++)//检查模块输入引脚是否信号完整
{
moudle_param* param=moudle->input[j];
if(param->connect_line.size()!=0)
{
for(int m=0;m<param->connect_line.size();m++)
{
if(param->connect_line[m]->startbutton.size()==0)
{
return false;
}
}
}
else
{
return false;
}
}
for(int j=0;j<moudle->output_size;j++)//检查模块输出引脚是否信号完整
{
moudle_param* param=moudle->output[j];
if(param->connect_line.size()!=0)
{
for(int m=0;m<param->connect_line.size();m++)
{
if(param->connect_line[m]->endbutton.size()==0)
{
return false;
}
}
}
else
{
return false;
}
}
}
return true;
}
void Run_Simu::relation_init()
{
for(int i=0;i<this->simulation_group->group.size();i++)
{
Simulation_Moudle* moudle=this->simulation_group->group[i];
for(int m=0;m<moudle->output.size();m++)
{
int count=moudle->output[m]->next.size();
for(int n=0;n<count;n++)
moudle->output[m]->next.removeAt(0);
}
int count=moudle->input_flag.size();
for(int i=0;i<count;i++)
{
moudle->input_flag.removeAt(0);
moudle->input_number.removeAt(0);
moudle->input_loop.removeAt(0);
}
count=moudle->output_flag.size();
for(int i=0;i<count;i++)
{
moudle->output_flag.removeAt(0);
moudle->output_number.removeAt(0);
}
for(int i=0;i<moudle->input_size;i++)
{
moudle->input_flag.push_back(false);
moudle->input_number.push_back(0);
moudle->input_loop.push_back(false);
}
for(int i=0;i<moudle->output_size;i++)
{
moudle->output_flag.push_back(false);
moudle->output_number.push_back(0);
}
moudle->loop_flag=false;
}
}
void Run_Simu::detect_loop()
{
for(int i=0;i<this->simulation_group->group.size();i++)
{
for(int j=0;j<this->simulation_group->group.size();j++)
{
this->simulation_group->group[j]->loop_flag=false;
}
loop_check(this->simulation_group->group[i],0);
}
for(int i=0;i<this->simulation_group->group.size();i++)
{
Simulation_Moudle* moudle=this->simulation_group->group[i];
for(int j=0;j<moudle->input_loop.size();j++)
if(moudle->input_loop[j]==true)
qDebug()<<i<<" "<<j;
}
}
void Run_Simu::loop_check(Simulation_Moudle* moudle,int index)
{
if(moudle->loop_flag)
{
moudle->input_loop[index]=true;
return;
}
moudle->loop_flag=true;
for(int m=0;m<moudle->output.size();m++)
{
moudle_param* param=moudle->output[m];
for(int n=0;n<param->next.size();n++)
{
loop_check(param->next[n].moudle,param->next[n].index);
}
}
}
void Run_Simu::realtime_simulation()
{
graph_button();
qDebug()<<QDateTime::currentDateTime();//计算实际仿真时间与设定仿真时间差
mDataTimer.start(10);
}
void Run_Simu::output_generator(Simulation_Moudle* moudle,int time)
{
for(int i=0;i<moudle->output_size;i++)
{
if(moudle->index==0)//斜坡
{
moudle->output_number[i]=moudle->param[0]*time*this->time.simu_step;
}
else if(moudle->index==1)//阶跃
{
moudle->output_number[i]=moudle->param[0];
}
else if(moudle->index==2)//正弦
{
moudle->output_number[i]=moudle->param[0]*sin(time*moudle->param[1]*this->time.simu_step);
}
else if(moudle->index==3)//方波
{
if(this->time.simu_count%int(moudle->param[0]/2/this->time.simu_step)==0)
{
if(int(moudle->param[2])==1)
{
moudle->param[2]=0;
moudle->output_number[i]=moudle->param[1];
}
else
{
moudle->param[2]=1;
moudle->output_number[i]=0;
}
}
}
else if(moudle->index==4)//三角波
{
double bias=(moudle->param[0]/this->time.simu_step)/(moudle->param[0]/this->time.simu_step-1)-1;
moudle->output_number[i]=double(this->time.simu_count%int(moudle->param[0]/this->time.simu_step))/int(moudle->param[0]/this->time.simu_step)*((moudle->param[1]-moudle->param[2])*(1+bias))+moudle->param[2];
}
else if(moudle->index==5)//分段折线波
{
if(int(moudle->param[2])<=(moudle->time_sequence.size()-1)&&this->time.simu_count>=moudle->time_sequence[int(moudle->param[2])]/this->time.simu_step)
{
if(moudle->param[2]<=moudle->value_sequence.size()-1)
moudle->output_number[i]=moudle->value_sequence[int(moudle->param[2])];
else
moudle->output_number[i]=0;
moudle->param[2]+=1;
}
else
{
moudle->output_number[i]=0;
}
}
else if(moudle->index==6)//分段矩形波
{
}
else if(moudle->index==7)//随机信号
{
moudle->output_number[i]=double(rand())/RAND_MAX*(moudle->param[1]-moudle->param[0])+moudle->param[0];
}
//moudle->output_number[i]=moudle->param[2]*sin(time*0.01);
moudle->graph_value.push_back(moudle->output_number[i]);
}
}
void Run_Simu::run_socket(Simulation_Moudle* moudle)
{
if(moudle->bind_interface->front<moudle->bind_interface->receive_data.size())
{
for(int i=0;i<moudle->output_number.size();i++)
moudle->output_number[i]=moudle->bind_interface->receive_data[moudle->bind_interface->front];
run_simulation(moudle);
moudle->bind_interface->front++;
}
}
void Run_Simu::run_simulation(Simulation_Moudle* moudle)
{
for(int j=0;j<moudle->output.size();j++)
{
moudle_param* param=moudle->output[j];
for(int m=0;m<param->next.size();m++)
{
if(check_input(param->next[m].moudle,param->next[m].index,moudle->output_number[j]))
{
run_simulation(param->next[m].moudle);
}
}
}
}
bool Run_Simu::check_input(Simulation_Moudle* moudle,int index,double value)
{
bool flag=true;
moudle->input_flag[index]=true;
moudle->input_number[index]=value;
for(int i=0;i<moudle->input_flag.size();i++)
{
if(moudle->input_flag[i]!=true&&moudle->input_loop[i]!=true)
{
flag=false;
break;
}
}
if(flag)
{
for(int i=0;i<moudle->input_flag.size();i++)
moudle->input_flag[i]=false;
calculation(moudle);
return true;
}
return false;
}
void Run_Simu::calculation(Simulation_Moudle* moudle)
{
double value=0;
for(int i=0;i<moudle->input_number.size();i++)
{
value+=moudle->input_number[i];
}
if(moudle->output_number.size()!=0)
{
if(moudle->index==12)//惯性
{
double k1=0,k2=0,k3=0,k4=0;
for(int i=0;i<moudle->output_number.size();i++)
{
//y'=(x-y)/k
//moudle->output_number[i]=value;
//四阶龙格-库塔算法
/*
if(this->time.simu_count==0)
{
moudle->output_number[0]=0;
}
else
{
k1=(this->time.simu_step*this->time.simu_count-moudle->output_number[0])/moudle->param[1];
k2=(this->time.simu_step*this->time.simu_count+0.5*this->time.simu_step-(moudle->output_number[0]+k1*this->time.simu_step/2))/moudle->param[1];
k3=(this->time.simu_step*this->time.simu_count+0.5*this->time.simu_step-(moudle->output_number[0]+k2*this->time.simu_step/2))/moudle->param[1];
k4=(this->time.simu_step*this->time.simu_count+this->time.simu_step-(moudle->output_number[0]+k3*this->time.simu_step))/moudle->param[1];
moudle->output_number[0]=moudle->output_number[0]+this->time.simu_step*(k1+2*k2+2*k3+k4)/6;
}
*/
//改进欧拉算法
double temp;
temp=moudle->output_number[0]/moudle->param[0];
moudle->output_number[0]=temp+this->time.simu_step*(moudle->param[2]-temp)/moudle->param[1];
moudle->output_number[0]=temp+this->time.simu_step/2*(moudle->param[2]-temp+value-moudle->output_number[0])/moudle->param[1];
//moudle->output_number[i]=(moudle->param[1]*moudle->output_number[i]+moudle->param[0]*value)/(1+moudle->param[1]);
// moudle->output_number[i]=value*(1-exp(-1/moudle->param[1]*this->time.simu_step*this->time.simu_count));
/* moudle->process_value.push_back(moudle->output_number[0]);
if(moudle->process_value.size()>=101)
{
moudle->process_value.removeAt(0);
}
//QThread::sleep(1);
//Sleep(1000);
*/
moudle->param[2]=value;//使用前需要清零
//qDebug()<<moudle->output_number[0]<<moudle->id;
}
moudle->output_number[0]=moudle->output_number[0]*moudle->param[0];
}
else if(moudle->index==13)//n阶惯性
{
for(int i=0;i<moudle->output_number.size();i++)
{
for(int j=0;j<int(moudle->param[2]);j++)
{
//改进欧拉算法
moudle->output_number[0]=moudle->temp[j]+this->time.simu_step*(moudle->param_temp[j]-moudle->temp[j])/moudle->param[1];
moudle->output_number[0]=moudle->temp[j]+this->time.simu_step/2*(moudle->param_temp[j]-moudle->temp[j]+value-moudle->output_number[0])/moudle->param[1];
moudle->param_temp[j]=value;//使用前需要清零
moudle->temp[j]=moudle->output_number[0];
value=moudle->output_number[0];
}
moudle->output_number[0]=moudle->output_number[0]*moudle->param[0];
}
}
else if(moudle->index==8)//常数
{
moudle->output_number[0]=moudle->param[0]*value;
}
else if(moudle->index==9)//延时
{
moudle->process_value.push_back(value);
if(moudle->process_value.size()>=moudle->param[0]/this->time.simu_step)
{
moudle->output_number[0]=moudle->process_value[0];
moudle->process_value.removeAt(0);
}
else
{
moudle->output_number[0]=0;
}
}
else if(moudle->index==10)//积分
{
moudle->output_number[0]+=value*moudle->param[0]*time.simu_step;
}
else if(moudle->index==11)//微分
{
double temp=value;
moudle->output_number[0]=(value-moudle->param[0])/time.simu_step;
moudle->param[0]=temp;
}
else if(moudle->index==19)//倒数
{
if(int(value)!=0)
moudle->output_number[0]=1/value;
else
moudle->output_number[0]=0;
}
else if(moudle->index==20)//正三角
{
if(int(moudle->param[0])==0)
{
moudle->output_number[0]=sin(value);
}
else if(int(moudle->param[0])==1)
moudle->output_number[0]=cos(value);
else if(int(moudle->param[0])==2)
moudle->output_number[0]=tan(value);
}
else if(moudle->index==21)//反三角
{
if(int(moudle->param[0])==0)
moudle->output_number[0]=asin(value);
else if(int(moudle->param[0])==1)
moudle->output_number[0]=acos(value);
else if(int(moudle->param[0])==2)
moudle->output_number[0]=atan(value);
}
else if(moudle->index==22)//绝对值
{
moudle->output_number[0]=abs(value);
}
else if(moudle->index==23)//绝符号
{
moudle->output_number[0]=value>0?1:(value==0.0?0:-1);
}
else if(moudle->index==24)//自然对数 e
{
if(value>0)
moudle->output_number[0]=log(value);
else
moudle->output_number[0]=value;
}
else if(moudle->index==25)//常用对数 10
{
if(value>0)
moudle->output_number[0]=log10(value);
else
moudle->output_number[0]=value;
}
else if(moudle->index==26)//指数e
{
moudle->output_number[0]=exp(value);
}
else if(moudle->index==27)//幂函数
{
moudle->output_number[0]=pow(value,int(moudle->param[0]));
}
else if(moudle->index==28)//开方
{
if(value>=0)
moudle->output_number[0]=sqrt(value);
else
moudle->output_number[0]=value;
}
else if(moudle->index==29)//加法器
{
moudle->output_number[0]=value;
}
else if(moudle->index==30)//乘法器
{
if(int(moudle->param[0])==0)
moudle->output_number[0]=moudle->input_number[0]*moudle->input_number[1];
else if(int(moudle->param[0])==1&&int(moudle->input_number[1])!=0)
{
moudle->output_number[0]=moudle->input_number[0]/moudle->input_number[1];
}
}
else if(moudle->index==31)//比例偏置 kx+b
{
moudle->output_number[0]=moudle->param[0]*value+moudle->param[1];
}
else if(moudle->index==32)//逻辑运算> <
{
if(int(moudle->param[0])==0)
moudle->output_number[0]=(moudle->input_number[0]>moudle->input_number[1]);
else if(int(moudle->param[0])==1)
moudle->output_number[0]=(moudle->input_number[0]<moudle->input_number[1]);
else if(int(moudle->param[0])==2)
moudle->output_number[0]=(int(moudle->input_number[0])==int(moudle->input_number[1]));
else if(int(moudle->param[0])==3)
moudle->output_number[0]=(int(moudle->input_number[0])&&int(moudle->input_number[1]));
else if(int(moudle->param[0])==4)
moudle->output_number[0]=(int(moudle->input_number[0])||int(moudle->input_number[1]));
else if(int(moudle->param[0])==5)
{
if(int(moudle->input_number[0])!=0)
moudle->output_number[0]=0;
else
moudle->output_number[0]=1;
}
}
else if(moudle->index==33)//逻辑& | ~
{
if(int(moudle->param[0])==0)
moudle->output_number[0]=(int(moudle->input_number[0])&int(moudle->input_number[1]));
else if(int(moudle->param[0])==1)
moudle->output_number[0]=(int(moudle->input_number[0])|int(moudle->input_number[1]));
else if(int(moudle->param[0])==2)
moudle->output_number[0]=(~int(moudle->input_number[0]));
}
else if(moudle->index==34)//取最值
{
if(int(moudle->param[1])==0) //最大值
{
double max=moudle->input_number[0];
for(int i=1;i<moudle->input_number.size();i++)
{
if(max<moudle->input_number[i])
max=moudle->input_number[i];
}
moudle->output_number[0]=max;
}
else if(int(moudle->param[1])==1) //MIN
{
double min=moudle->input_number[0];
for(int i=1;i<moudle->input_number.size();i++)
{
if(min>moudle->input_number[i])
min=moudle->input_number[i];
}
moudle->output_number[0]=min;
}
}
else if(moudle->index==35)//出多选一
{
if(int(moudle->input_number[1])<moudle->output_size)
{
for(int i=0;i<moudle->output_size;i++)
{
if(i==int(moudle->input_number[1]))
moudle->output_number[i]=moudle->input_number[0];
else
moudle->output_number[i]=0;
}
}
else
{
for(int i=0;i<moudle->output_size;i++)
{
moudle->output_number[i]=0;
}
}
}
else if(moudle->index==36)//入多选一
{
if(int(moudle->input_number[moudle->input_size-1])<moudle->input_size-1)
moudle->output_number[0]=moudle->input_number[int(moudle->input_number[moudle->input_size-1])];
else
moudle->output_number[0]=0;
}
else if(moudle->index==38)//接口模块专属
{
for(int m=0;m<moudle->output_number.size();m++)
moudle->output_number[m]=value;
}
else if(moudle->index==39)//tag_bind模块专属
{
for(int m=0;m<moudle->output_number.size();m++)
moudle->output_number[m]=value;
}
}
else
{
if(moudle->index==38)//接口模块专属
{
if(moudle->bind_interface->output_success==true)//是否与服务器连接成功
{
QString str=QString::number(value);
moudle->bind_interface->output_socket->write(str.toLatin1(),str.length());
}
else
{
QString str=QString::number(moudle->bind_interface->output_ip[0])+"."+QString::number(moudle->bind_interface->output_ip[1])+"."+QString::number(moudle->bind_interface->output_ip[2])+"."+QString::number(moudle->bind_interface->output_ip[3]);
parent->statr_message(moudle->name+" output reconnect from local to "+str+":"+QString::number(moudle->bind_interface->output_port),1000);
QHostAddress ip(str);
moudle->bind_interface->output_socket->connectToHost(ip,quint16(moudle->bind_interface->output_port));
return;
}
}
else if(moudle->index==39)//tag_bind模块专属
{
if(this->window_parent->sys_flag->success_flag==false)//断开连接
{
this->parent->statr_message("main_socket connect failed,try to reconnect",1000);
//this->window_parent->reconnect_main_socket();
return;
}
this->window_parent->sys_flag->finish_socket->output[moudle->socket_id_output]=true;
this->window_parent->sys_flag->output_buf+=(moudle->tag_bind->output_tag+" "+QString::number(value));
//this->window_parent->sys_flag->output_bind_count--;
int m=0;
for(m=0;m<this->window_parent->sys_flag->finish_socket->output.size();m++)
{
if(this->window_parent->sys_flag->finish_socket->output[m]==false)
break;
}
if(m==this->window_parent->sys_flag->finish_socket->output.size())//所有输出至外部接口的数据打包完成 开始发送
{
this->window_parent->sys_flag->output_bind_count=this->window_parent->sys_flag->output_bind.size();
this->window_parent->sys_flag->socket_main->write(this->window_parent->sys_flag->output_buf.toLatin1(),this->window_parent->sys_flag->output_buf.size());
this->window_parent->sys_flag->output_buf="";
this->window_parent->send_clock->stop();
this->window_parent->clear_finish_flag(1);
}
}
else if(moudle->index==37)//图表
moudle->graph_value.push_back(value);
/*
if(moudle->graph_value.size()>=101)
{
moudle->graph_value.removeAt(0);
}
*/
//qDebug()<<value;
}
// qDebug()<<moudle->output_number[0];
}
void Run_Simu::clear_process_value()
{
for(int i=0;i<this->simulation_group->group.size();i++)
{
int count=this->simulation_group->group[i]->process_value.size();
for(int j=0;j<count;j++)
this->simulation_group->group[i]->process_value.removeAt(0);
}
for(int i=0;i<this->simulation_group->group.size();i++)
{
if(this->simulation_group->group[i]->index==5)//清楚分段折线序列数据
{
Simulation_Moudle* moudle=this->simulation_group->group[i];//过程数据清零
moudle->param[2]=0;
}
else if(this->simulation_group->group[i]->index==11)//微分环节
{
Simulation_Moudle* moudle=this->simulation_group->group[i];//过程数据清零
moudle->param[0]=0;
}
else if(this->simulation_group->group[i]->index==12)//一阶惯性环节
{
Simulation_Moudle* moudle=this->simulation_group->group[i];//过程数据清零
moudle->param[2]=0;
}
else if(this->simulation_group->group[i]->index==13||this->simulation_group->group[i]->index==14||this->simulation_group->group[i]->index==15)//高阶环节中间值清零
{
int count=this->simulation_group->group[i]->param_temp.size();
for(int j=0;j<count;j++)
{
this->simulation_group->group[i]->param_temp.removeAt(0);
this->simulation_group->group[i]->temp.removeAt(0);
}
for(int j=0;j<this->simulation_group->group[i]->param[2];j++)
{
this->simulation_group->group[i]->param_temp.push_back(0);
this->simulation_group->group[i]->temp.push_back(0);
}
}
else if(this->simulation_group->group[i]->index==38)//接口模块专属
{
this->simulation_group->group[i]->bind_interface->front=0;
this->simulation_group->group[i]->bind_interface->receive_data.clear();
}
}
}
void Run_Simu::form()
{
delete this->moudle_generator;
this->moudle_generator=new moudel_group();
for(int i=0;i<this->simulation_group->group.size();i++)
if(this->simulation_group->group[i]->index==0||this->simulation_group->group[i]->index==1||this->simulation_group->group[i]->index==2||this->simulation_group->group[i]->index==3||this->simulation_group->group[i]->index==4||this->simulation_group->group[i]->index==5||this->simulation_group->group[i]->index==6||this->simulation_group->group[i]->index==7)
this->moudle_generator->group.push_back(this->simulation_group->group[i]);
for(int i=0;i<this->moudle_generator->group.size();i++)
{
int count=this->moudle_generator->group[i]->graph_value.size();
for(int j=0;j<count;j++)
this->moudle_generator->group[i]->graph_value.removeAt(0);//原始信号数据清零
}
moudle_socket->group.clear();//输入实物模块
for(int i=0;i<this->simulation_group->group.size();i++)
if(this->simulation_group->group[i]->index==38&&this->simulation_group->group[i]->bind_interface->input_flag==true&&this->simulation_group->group[i]->bind_interface->output_flag==false)//输入接入实物,输出为虚拟仿真
this->moudle_socket->group.push_back(this->simulation_group->group[i]);
}
void Run_Simu::form_graph()
{
delete this->moudle_graph;
this->moudle_graph=new moudel_group();
for(int i=0;i<this->simulation_group->group.size();i++)
if(this->simulation_group->group[i]->index==37)
this->moudle_graph->group.push_back(this->simulation_group->group[i]);
for(int i=0;i<this->moudle_graph->group.size();i++)
{
int count=this->moudle_graph->group[i]->graph_value.size();
for(int j=0;j<count;j++)
this->moudle_graph->group[i]->graph_value.removeAt(0);//仿真数据清零
}
}
void Run_Simu::graph_button()
{
QPushButton* button;
QLabel* label;
int count=this->ui->graph_group.size();
for(int i=0;i<count;i++)
{
delete this->ui->graph_group[0];
this->ui->graph_group.removeAt(0);
this->ui->current_value.removeAt(0);
}
for(int i=0;i<this->moudle_graph->group.size();i++)
{
this->moudle_graph->group[i]->grapg_flag=true;
button=new QPushButton(this);
button->setObjectName("&plot"+QString::number(i));
button->setText(this->moudle_graph->group[i]->name);
button->setGeometry(this->width()-160,50*i,50,30);
button->setVisible(true);
connect(button, &QAbstractButton::clicked, this, &Run_Simu::change);
this->ui->graph_group.push_back(button);
label=new QLabel(this);
label->setGeometry(button->x()+button->width(),button->y(),button->width(),button->height());
label->setVisible(true);
this->ui->current_value.push_back(label);
}
}
void Run_Simu::get_max(int start,int end)
{
this->value_min=0;
this->value_max=0;
this->value_limit=0;
for(int i=0;i<this->moudle_graph->group.size();i++)
{
Simulation_Moudle* moudle=this->moudle_graph->group[i];
if(moudle->grapg_flag==true&&moudle->graph_value.size()!=0)
{
for(int j=start;j<end;j++)
{
double value=moudle->graph_value[j];
if(value<this->value_min)
{
this->value_min=value;
}
if(value>this->value_max)
this->value_max=value;
//qDebug()<<this->value_limit;
}
}
}
if(qAbs(this->value_min)>qAbs(this->value_max))
{
this->value_limit=qAbs(this->value_min);
}
else
{
this->value_limit=qAbs(this->value_max);
}
}
void Run_Simu::loadmindindow(QMdiSubWindow* midwindow)
{
this->midwindow=midwindow;
this->midwindow->resize(ui->x_axia_precision*ui->x_interval_point*(ui->x_count-1)+200+ui->x_start,400);
this->resize(ui->x_axia_precision*ui->x_interval_point*(ui->x_count-1)+200+ui->x_start,400);
}
void Run_Simu::update_size()//坐标系自适应窗口大小
{
this->resize(this->midwindow->size().width(),this->midwindow->size().height()-60);
//if((this->width()-200-this->ui->x_start)%(ui->x_count-1)!=0)//确保x轴分度为整数
// return;
//qDebug()<<11;
//if((this->width()-200-this->ui->x_start)/(ui->x_count-1)%this->ui->x_interval_point!=0)
// return;
this->ui->y_start=this->height()/2;
//x_axia_precision*x_interval_point*(x_count-1)
//this->ui->x_length=this->ui->x_axia_precision*this->ui->x_interval_point*(this->ui->x_count-1);
this->ui->y_axis_length=this->height()/2-80;
this->ui->x_axia_precision=(this->width()-200-this->ui->x_start)/(ui->x_count-1)/ui->x_interval_point;
if(this->ui->x_axia_precision==0)
{
this->ui->x_axia_precision=1;
ui->x_interval_point=(this->width()-200-this->ui->x_start)/(ui->x_count-1);
}
this->ui->x_length=this->ui->x_axia_precision*this->ui->x_interval_point*(this->ui->x_count-1);
this->ui->x_interview_length=this->ui->x_length/(ui->x_count-1);
for(int i=0;i<ui->x_count;i++)
{
time_label[i]->setGeometry(ui->x_start+ui->x_axia_precision*ui->x_interval_point*i,ui->y_start+2,ui->x_axia_precision*ui->x_interval_point-3,20);
}
for(int i=0;i<this->ui->y_count;i++)
{
value_label[i*2]->setGeometry(ui->x_start-40,ui->y_start-12-ui->y_axis_length/ui->y_count*(i+1),35,20);
value_label[i*2+1]->setGeometry(ui->x_start-40,ui->y_start-12+ui->y_axis_length/ui->y_count*(i+1),35,20);
}
for(int i=0;i<this->moudle_graph->group.size();i++)
{
this->ui->graph_group[i]->setGeometry(this->width()-160,50*i+40,50,30);
this->ui->current_value[i]->setGeometry(this->ui->graph_group[i]->x()+this->ui->graph_group[i]->width()+10,this->ui->graph_group[i]->y(),this->ui->graph_group[i]->width(),this->ui->graph_group[i]->height());
}
start_stop->setGeometry(this->width()-160,0,50,30);//设定仿真按钮位置
}
int Run_Simu::check_focus()
{
QRect rect(ui->x_start,ui->y_start-ui->y_axis_length,ui->x_length,ui->y_axis_length*2);
if(rect.contains(this->mapFromGlobal(QCursor::pos())))
{
return (this->mapFromGlobal(QCursor::pos()).x()-this->ui->x_start)/this->ui->x_axia_precision;
}
return -1;
}
void Run_Simu::check_data()
{
//适用与半实物仿真时,如果网络输出传输周期较长(低于仿真步距),就是需要将中间时间差内的数据清零
for(int i=0;i<this->moudle_graph->group.size();i++)
{
Simulation_Moudle* moudle=this->moudle_graph->group[i];
if(moudle->graph_value.size()<this->time.simu_count)
{
if(this->time.simu_count==1)
{
moudle->graph_value.push_back(0);
}
else
{
int count=moudle->graph_value.size();
for(int j=0;j<this->time.simu_count-count;j++)
{
moudle->graph_value.push_back(moudle->graph_value[moudle->graph_value.size()-1]);
}
}
//qDebug()<<moudle->graph_value.size()<<time.simu_count;
}
}
}
void Run_Simu::set_shadow(QWidget *widget)
{
QGraphicsDropShadowEffect *shadow_effect = new QGraphicsDropShadowEffect(this);
shadow_effect->setOffset(5, 5);
shadow_effect->setColor(QColor(50, 50, 50));
shadow_effect->setBlurRadius(8);
widget->setGraphicsEffect(shadow_effect);
}
void Run_Simu::remove_shadow(QWidget *widget)
{
QGraphicsDropShadowEffect *shadow_effect = new QGraphicsDropShadowEffect(this);
shadow_effect->setOffset(5, 5);
shadow_effect->setColor(QColor(255, 255, 255));
shadow_effect->setBlurRadius(8);
widget->setGraphicsEffect(shadow_effect);
}
void Run_Simu::clear_save_flag()
{
for(int i=0;i<this->save_complete.size();i++)
this->save_complete[i]=false;
}
void Run_Simu::save_graph_date()
{
int count=this->graph_name.size();
for(int i=0;i<count;i++)
{
this->graph_name.removeAt(0);
}
for(int i=0;i<this->moudle_graph->group.size();i++)
{
this->graph_name.push_back(this->moudle_graph->group[i]->name);
}
if(this->real_flag==false&&this->run_stop_state)
this->mDataTimer.stop();//关闭仿真
this->parent->save_graph_date();
if(this->real_flag==false&&this->run_stop_state)
this->mDataTimer.start(10);//开启仿真
}
void Run_Simu::save_data(QFile* file,int index)
{
//QFile* file=new QFile("data.txt");
if(!file->open(QIODevice::WriteOnly | QIODevice::Text))
{
qDebug()<<"error";
return;
}
//仿真数据写入格式
//仿真数据大小
//仿真步距
//仿真数据
file->write(QByteArray::number(this->moudle_graph->group[index]->graph_value.size()));
file->write("\n");
file->write(QByteArray::number(this->time.simu_step));
file->write("\n");
for(int i=0;i<this->moudle_graph->group[index]->graph_value.size();i++)
{
file->write(QByteArray::number(this->moudle_graph->group[index]->graph_value[i]));
file->write("\n");
}
file->close();
}
| [
"xgf13469@163.com"
] | xgf13469@163.com |
0eaa587e87a45539479be2f5151923729456f80f | 053309314b081dcb3fca08fc5ea15e6e8596141d | /day11/source/yjh/string.cpp | a2c53ea86418f8046c3b99c083f573050837e22a | [] | no_license | cppascalinux/jinanjixun | a6283e1bbdc4cac938131e8061a8b5290f6bb1dc | 555a95c7baf940c38236ac559f0a2c11a34edd0c | refs/heads/master | 2020-05-29T14:46:31.982813 | 2019-06-14T07:14:19 | 2019-06-14T07:14:19 | 189,192,981 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,436 | cpp | #include <cstdio>
#include <cctype>
#include <cstring>
#include <algorithm>
#define maxn 9000005
inline int read() {
int d=0;char ch=getchar();while(!isdigit(ch))ch=getchar();
while(isdigit(ch)){d=d*10+ch-48,ch=getchar();}return d;
}
inline int popcnt(int x) {
int ans = 0; while(x) ++ans, x -= x&-x;
return ans;
}
int n, k, q;
int s[maxn];
int sa[maxn], rk[maxn], tp[maxn], tax[maxn];
int m;
inline void rsort() {
for(int i = 1; i <= m; ++i) tax[i] = 0;
for(int i = 1; i <= n; ++i) ++tax[rk[i]];
for(int i = 1; i <= m; ++i) tax[i] += tax[i-1];
for(int i = n; i >= 1; --i) sa[tax[rk[tp[i]]]--] = tp[i];
}
void getsa() {
m = 2;
for(int i = 1; i <= n; ++i) rk[i] = s[i]+1, tp[i] = i;
rsort();
for(int p = 0, w = 1; p < n && w <= n; m = p, w <<= 1) {
p = 0;
for(int i = n-w+1; i <= n; ++i) tp[++p] = i;
for(int i = 1; i <= n; ++i)
if(sa[i] > w) tp[++p] = sa[i]-w;
rsort();
std::swap(rk, tp);
rk[sa[1]] = p = 1;
for(int i = 2; i <= n; ++i)
rk[sa[i]] = (tp[sa[i]] == tp[sa[i-1]] && (sa[i]+w > n ? -1 : tp[sa[i]+w]) == (sa[i-1]+w > n ? -1 : tp[sa[i-1]+w])) ? p : ++p;
}
}
int main() {
freopen("string.in", "r", stdin);
freopen("string.out", "w", stdout);
k = read(), q = read();
n = 1<<k;
for(int i = 0; i < n; ++i)
s[i+1] = popcnt(i)&1;
getsa();
for(int i = 1; i <= n; ++i) {
int p = read();
printf("%d ", sa[p]-1);
}
return 0;
}
| [
"cppascalinux@gmail.com"
] | cppascalinux@gmail.com |
90bbd48b5678228fc562a472a5e7cae6b22a9b47 | e785ba2c2ad3619c526e84b1a980791615461a97 | /inflate.cpp | c9408f84e9ecf4bd8036cd01b416f4510fe05b78 | [] | no_license | dilkas/usaco | 82183fb26a6b8c098028b40c43890becab5a8396 | 5d0e46df263d234fab1233194081317df734e508 | refs/heads/master | 2021-01-21T04:55:21.898692 | 2016-07-14T12:01:31 | 2016-07-14T12:01:31 | 26,331,099 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 598 | cpp | /*
ID: paulius10
PROG: inflate
LANG: C++
*/
#include <fstream>
using namespace std;
int main() {
ifstream fin("inflate.in");
int M, N;
fin >> M >> N;
int points[N];
int minutes[N];
for (int i = 0; i < N; i++) fin >> points[i] >> minutes[i];
fin.close();
int max[M + 1];
for (int m = 0; m <= M; m++) {
max[m] = 0;
for (int i = 0; i < N; i++) {
if (minutes[i] <= m) {
int p = points[i] + max[m - minutes[i]];
if (p > max[m]) max[m] = p;
}
}
}
ofstream fout("inflate.out");
fout << max[M] << endl;
fout.close();
return 0;
}
| [
"paulius.dilkas@gmail.com"
] | paulius.dilkas@gmail.com |
40873c4f6be6e4961e803ed1865fad9abc8ca8aa | a5054df3fa38dbf5c7c03d8721f9bcfe04db570f | /DisplayLib/OpenGL-ES2/GLMacOSX.h | c2840141563fe39c442cb20bfabadba543448b24 | [
"MIT"
] | permissive | Bjohh/SuperPlay | 850a5baa3f114ea65b8ed4629bdff9c0e4c040e9 | e2d33cb52635251cd3f180b73f5fb08944940d18 | refs/heads/master | 2023-03-16T20:27:49.749763 | 2020-12-09T19:58:16 | 2020-12-09T19:58:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 764 | h | // This code is part of the Super Play Library (http://www.superplay.info),
// and may only be used under the terms contained in the LICENSE file,
// included with the Super Play Library.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
#pragma once
#include <OpenGL/gl.h>
NAMESPACE(SPlay)
class GLPlatform
{
public:
// Constructor
GLPlatform();
// Destructor
virtual ~GLPlatform();
// Create
static GLPlatform* create();
// Initialize
bool initialize();
// Close platform
void close();
// Render
bool swapBuffers();
private:
};
ENDNAMESPACE
| [
"cdoty@rastersoft.net"
] | cdoty@rastersoft.net |
4e5b9533f0b524404ce3489bf7fa431156b42a08 | 364447971631437542a0240cfc1725eabecccc57 | /Userland/Libraries/LibCrypto/ASN1/PEM.h | 8a201c05d132b0d9f47be25b71fcff83e4989eff | [
"BSD-2-Clause"
] | permissive | Jicgiebcden/serenity | aeb749fd18edb0191f5631b467ec7cd6a0e4eefb | f54a6d273e04f1739950c86dfcb026d746454f6a | refs/heads/master | 2023-04-15T06:30:41.710696 | 2021-04-22T10:38:44 | 2021-04-22T11:05:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 277 | h | /*
* Copyright (c) 2020, Ali Mohammad Pur <ali.mpfard@gmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Span.h>
#include <LibCrypto/ASN1/ASN1.h>
#include <LibCrypto/ASN1/DER.h>
namespace Crypto {
ByteBuffer decode_pem(ReadonlyBytes);
}
| [
"kling@serenityos.org"
] | kling@serenityos.org |
369676208aac1a61375eaece30fe81a4eec31dc2 | f571e7892e0b992a6be9ba3656dc3fe484c8cf44 | /MSRA_proposal_wifi_log/code/code/mista_src/utilities.cpp | c04f129c8c2ab722fc3c142788baf9f683ff1b31 | [
"Apache-2.0"
] | permissive | YoojuShin/revisit | d9be5233b0b02e20afe471e8373cbfa4a1be0174 | 945f12c8458a0d6511e183e8efdc77315bfe857c | refs/heads/master | 2021-06-11T21:55:55.084382 | 2017-01-16T06:53:24 | 2017-01-16T06:53:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 220 | cpp | #include "utilities.h"
int MAX_INTEGER=(int)floor(pow((float)2,(int)(8*sizeof(int)-2)));
void launch_error(const char *msg)
{
cerr << "\n################\nERROR: " << msg << "\n################\n";
exit(-1);
};
| [
"yooju24@gmail.com"
] | yooju24@gmail.com |
c11f15e3ea087ee6b1cca4558a4048b1a7beec41 | 5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e | /main/source/src/core/scoring/func/Func.fwd.hh | d00a33be656c0bc881e69ea240b8a3495f37b991 | [] | no_license | MedicaicloudLink/Rosetta | 3ee2d79d48b31bd8ca898036ad32fe910c9a7a28 | 01affdf77abb773ed375b83cdbbf58439edd8719 | refs/heads/master | 2020-12-07T17:52:01.350906 | 2020-01-10T08:24:09 | 2020-01-10T08:24:09 | 232,757,729 | 2 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 990 | hh | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: license@uw.edu.
/// @file
/// @brief
#ifndef INCLUDED_core_scoring_func_Func_fwd_hh
#define INCLUDED_core_scoring_func_Func_fwd_hh
#include <utility/pointer/owning_ptr.fwd.hh>
// C++ Headers
//#include <cstdlib>
//#include <iostream>
//#include <map>
//#include <utility>
namespace core {
namespace scoring {
namespace func {
class Func;
typedef utility::pointer::shared_ptr< Func > FuncOP;
typedef utility::pointer::shared_ptr< const Func > FuncCOP;
}
}
}
#endif
| [
"36790013+MedicaicloudLink@users.noreply.github.com"
] | 36790013+MedicaicloudLink@users.noreply.github.com |
0bf774f36f57f60237d99d83785b05d209b77c63 | d94f7ac3498a900322fa64d3b5e833a1e896ef63 | /Test.cpp | deb7b6007633f1b4da0861eedd6a3eaa69ac6d9a | [
"MIT"
] | permissive | mp3guy/Stopwatch | f7e691101c0850840765e43cd46310784c2851b1 | 9137b66e2c25c6ac06ed071e4518a4472d49ffb0 | refs/heads/master | 2023-08-19T08:32:46.018922 | 2023-08-03T14:10:05 | 2023-08-03T14:10:05 | 17,517,782 | 30 | 14 | null | 2022-03-03T15:37:29 | 2014-03-07T15:12:16 | C++ | UTF-8 | C++ | false | false | 808 | cpp | #include <chrono>
#include <thread>
#include "Stopwatch.h"
int main(int, char**) {
// This stops duplicate timings on multiple runs
Stopwatch::getInstance().setCustomSignature(32434);
while (true) {
STOPWATCH("Timing1", std::this_thread::sleep_for(std::chrono::milliseconds(10)););
TICK("Timing2");
std::this_thread::sleep_for(std::chrono::milliseconds(50));
TOCK("Timing2");
for (size_t i = 3; i < 10; i++) {
Stopwatch::getInstance().tick(
"Timing" + std::to_string(i), Stopwatch::getCurrentSystemTime());
std::this_thread::sleep_for(std::chrono::milliseconds(i));
Stopwatch::getInstance().tock(
"Timing" + std::to_string(i), Stopwatch::getCurrentSystemTime());
}
TOCK("Timing10");
Stopwatch::getInstance().sendAll();
}
}
| [
"thelucid@gmail.com"
] | thelucid@gmail.com |
904d5a10e0305179148a24f5c4b4bd4aa8514b22 | b148d8082d0ba3df28a4631030c267945b2e8624 | /src/Client/RenderEngine/RenderWindow.cpp | 7092947c0c2eac148b846b69420c1f56e67b415d | [] | no_license | vividos/MultiplayerOnlineGame | eff8d816ffdef03d3c1781a677ec712c847636cd | cc9b0963fa1ad80428efcfd4bcf4e8d45d22176e | refs/heads/master | 2020-05-18T16:46:36.682075 | 2019-10-25T21:51:29 | 2019-10-30T08:21:30 | 10,821,789 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,733 | cpp | //
// MultiplayerOnlineGame - multiplayer game project
// Copyright (C) 2008-2014 Michael Fink
//
/// \file RenderWindow.cpp Render engine class
//
// includes
#include "StdAfx.h"
#include "RenderWindow.hpp"
#include <SDL.h>
#include "OpenGL.hpp"
RenderWindow::RenderWindow(const CString& cszWindowCaption, unsigned int uiWidth, unsigned int uiHeight, bool bFullscreen)
{
InitVideo(cszWindowCaption, uiWidth, uiHeight, bFullscreen);
}
RenderWindow::RenderWindow(std::shared_ptr<SDL_Window> spWindow)
:m_spWindow(spWindow)
{
// output some OpenGL diagnostics
OpenGL::LogDiagnostics();
int iWidth = 0, iHeight = 0;
SDL_GetWindowSize(spWindow.get(), &iWidth, &iHeight);
ResizeView(unsigned(iWidth), unsigned(iHeight));
}
void RenderWindow::SwapBuffers()
{
ATLASSERT(OpenGL::IsRenderThread());
ATLASSERT(m_spWindow != nullptr);
SDL_GL_SwapWindow(m_spWindow.get());
}
void RenderWindow::SetFullscreen(bool bFullscreen)
{
ATLASSERT(m_spWindow != nullptr);
SDL_SetWindowFullscreen(m_spWindow.get(), bFullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0);
}
void RenderWindow::SetCaption(const CString& cszCaption)
{
ATLASSERT(m_spWindow != nullptr);
CStringA cszaCaption(cszCaption);
SDL_SetWindowTitle(m_spWindow.get(), cszaCaption);
}
void RenderWindow::SetMousePos(int xpos, int ypos)
{
ATLASSERT(m_spWindow != nullptr);
SDL_WarpMouseInWindow(m_spWindow.get(), static_cast<Uint16>(xpos), static_cast<Uint16>(ypos));
}
void RenderWindow::GetWindowSize(int& iWidth, int& iHeight) const
{
ATLASSERT(m_spWindow != nullptr);
SDL_GetWindowSize(m_spWindow.get(), &iWidth, &iHeight);
}
void RenderWindow::InitVideo(const CString& cszWindowCaption, unsigned int uiWidth, unsigned int uiHeight, bool bFullscreen)
{
// output SDL version number
{
SDL_version linked = {0};
SDL_GetVersion(&linked);
CString cszText;
cszText.Format(_T("using SDL %u.%u.%u"), linked.major, linked.minor, linked.patch);
LOG_INFO(cszText, Log::Client::Renderer);
}
// first, initialize SDL's video subsystem
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
CString cszText;
cszText.Format(_T("video initialization failed: %hs"), SDL_GetError());
LOG_ERROR(cszText, Log::Client::Renderer);
throw Exception(cszText, __FILE__, __LINE__);
}
// setup video mode
int iFlags = SDL_WINDOW_OPENGL | (bFullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0);
{
CString cszText;
cszText.Format(_T("setting video mode: %u x %u%s"),
uiWidth, uiHeight,
bFullscreen ? _T(", fullscreen") : _T(""));
LOG_INFO(cszText, Log::Client::Renderer);
}
CStringA cszaWindowCaption(cszWindowCaption);
SDL_Window* pWindow = SDL_CreateWindow(cszaWindowCaption.GetString(),
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
static_cast<int>(uiWidth),
static_cast<int>(uiHeight),
iFlags);
if (pWindow == nullptr)
{
CString cszText;
cszText.Format(_T("video mode set failed: %hs"), SDL_GetError());
LOG_ERROR(cszText, Log::Client::Renderer);
throw Exception(cszText, __FILE__, __LINE__);
}
m_spWindow.reset(pWindow, &SDL_DestroyWindow);
SDL_GLContext glcontext = SDL_GL_CreateContext(pWindow);
m_spGLCcontext.reset(glcontext, &SDL_GL_DeleteContext);
#ifndef _DEBUG
// enable vsync for release; 1 means vsync on
SDL_GL_SetSwapInterval(1);
#endif
// output some OpenGL diagnostics
OpenGL::LogDiagnostics();
ResizeView(uiWidth, uiHeight);
}
void RenderWindow::ResizeView(unsigned int uiWidth, unsigned int uiHeight)
{
// setup OpenGL viewport
glViewport(0, 0, static_cast<GLsizei>(uiWidth), static_cast<GLsizei>(uiHeight));
}
| [
"michael.fink@asamnet.de"
] | michael.fink@asamnet.de |
0270741a2aa89d7706d0f870815d9b5efbab94e8 | caef08e15257c1c1d550c98842535e1affddfcd3 | /ch6/g2o_ba_example-master/main.cpp~ | 03f326eb8ce15e579d2a18c2a2a655b7811ccb32 | [] | no_license | KF93/myslam | f796640befd269468ece4efdf00d8f4cd237a586 | ea305a8810e751d081e55d9c7c801405f37243d0 | refs/heads/master | 2021-01-23T03:04:33.978433 | 2017-05-06T01:45:40 | 2017-05-06T01:45:40 | 86,045,079 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,276 | /**
* BA Example
* Author: Xiang Gao
* Date: 2016.3
* Email: gaoxiang12@mails.tsinghua.edu.cn
*
* 在这个程序中,我们读取两张图像,进行特征匹配。然后根据匹配得到的特征,计算相机运动以及特征点的位置。这是一个典型的Bundle Adjustment,我们用g2o进行优化。
*/
// for std
#include <iostream>
// for opencv
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <boost/concept_check.hpp>
// for g2o
#include <g2o/core/sparse_optimizer.h>
#include <g2o/core/block_solver.h>
#include <g2o/core/robust_kernel.h>
#include <g2o/core/robust_kernel_impl.h>
#include <g2o/core/optimization_algorithm_levenberg.h>
#include <g2o/solvers/cholmod/linear_solver_cholmod.h>
#include <g2o/types/slam3d/se3quat.h>
#include <g2o/types/sba/types_six_dof_expmap.h>
using namespace std;
// 寻找两个图像中的对应点,像素坐标系
// 输入:img1, img2 两张图像
// 输出:points1, points2, 两组对应的2D点
int findCorrespondingPoints( const cv::Mat& img1, const cv::Mat& img2, vector<cv::Point2f>& points1, vector<cv::Point2f>& points2 );
// 相机内参
double cx = 325.5;
double cy = 253.5;
double fx = 518.0;
double fy = 519.0;
int main( int argc, char** argv )
{
// 调用格式:命令 [第一个图] [第二个图]
if (argc != 3)
{
cout<<"Usage: ba_example img1, img2"<<endl;
exit(1);
}
// 读取图像
cv::Mat img1 = cv::imread( argv[1] );
cv::Mat img2 = cv::imread( argv[2] );
// 找到对应点
vector<cv::Point2f> pts1, pts2;
if ( findCorrespondingPoints( img1, img2, pts1, pts2 ) == false )
{
cout<<"匹配点不够!"<<endl;
return 0;
}
cout<<"找到了"<<pts1.size()<<"组对应特征点。"<<endl;
// 构造g2o中的图
// 先构造求解器
g2o::SparseOptimizer optimizer;
// 使用Cholmod中的线性方程求解器
g2o::BlockSolver_6_3::LinearSolverType* linearSolver = new g2o::LinearSolverCholmod<g2o::BlockSolver_6_3::PoseMatrixType> ();
// 6*3 的参数
g2o::BlockSolver_6_3* block_solver = new g2o::BlockSolver_6_3( linearSolver );
// L-M 下降
g2o::OptimizationAlgorithmLevenberg* algorithm = new g2o::OptimizationAlgorithmLevenberg( block_solver );
optimizer.setAlgorithm( algorithm );
optimizer.setVerbose( false );
// 添加节点
// 两个位姿节点
for ( int i=0; i<2; i++ )
{
g2o::VertexSE3Expmap* v = new g2o::VertexSE3Expmap();
v->setId(i);
if ( i == 0)
v->setFixed( true ); // 第一个点固定为零
// 预设值为单位Pose,因为我们不知道任何信息
v->setEstimate( g2o::SE3Quat() );
optimizer.addVertex( v );
}
// 很多个特征点的节点
// 以第一帧为准
for ( size_t i=0; i<pts1.size(); i++ )
{
g2o::VertexSBAPointXYZ* v = new g2o::VertexSBAPointXYZ();
v->setId( 2 + i );
// 由于深度不知道,只能把深度设置为1了
double z = 1;
double x = ( pts1[i].x - cx ) * z / fx;
double y = ( pts1[i].y - cy ) * z / fy;
v->setMarginalized(true);
v->setEstimate( Eigen::Vector3d(x,y,z) );
optimizer.addVertex( v );
}
// 准备相机参数
g2o::CameraParameters* camera = new g2o::CameraParameters( fx, Eigen::Vector2d(cx, cy), 0 );
camera->setId(0);
optimizer.addParameter( camera );
// 准备边
// 第一帧
vector<g2o::EdgeProjectXYZ2UV*> edges;
for ( size_t i=0; i<pts1.size(); i++ )
{
g2o::EdgeProjectXYZ2UV* edge = new g2o::EdgeProjectXYZ2UV();
edge->setVertex( 0, dynamic_cast<g2o::VertexSBAPointXYZ*> (optimizer.vertex(i+2)) );
edge->setVertex( 1, dynamic_cast<g2o::VertexSE3Expmap*> (optimizer.vertex(0)) );
edge->setMeasurement( Eigen::Vector2d(pts1[i].x, pts1[i].y ) );
edge->setInformation( Eigen::Matrix2d::Identity() );
edge->setParameterId(0, 0);
// 核函数
edge->setRobustKernel( new g2o::RobustKernelHuber() );
optimizer.addEdge( edge );
edges.push_back(edge);
}
// 第二帧
for ( size_t i=0; i<pts2.size(); i++ )
{
g2o::EdgeProjectXYZ2UV* edge = new g2o::EdgeProjectXYZ2UV();
edge->setVertex( 0, dynamic_cast<g2o::VertexSBAPointXYZ*> (optimizer.vertex(i+2)) );
edge->setVertex( 1, dynamic_cast<g2o::VertexSE3Expmap*> (optimizer.vertex(1)) );
edge->setMeasurement( Eigen::Vector2d(pts2[i].x, pts2[i].y ) );
edge->setInformation( Eigen::Matrix2d::Identity() );
edge->setParameterId(0,0);
// 核函数
edge->setRobustKernel( new g2o::RobustKernelHuber() );
optimizer.addEdge( edge );
edges.push_back(edge);
}
cout<<"开始优化"<<endl;
optimizer.setVerbose(true);
optimizer.initializeOptimization();
optimizer.optimize(10);
cout<<"优化完毕"<<endl;
//我们比较关心两帧之间的变换矩阵
g2o::VertexSE3Expmap* v = dynamic_cast<g2o::VertexSE3Expmap*>( optimizer.vertex(1) );
Eigen::Isometry3d pose = v->estimate();
cout<<"Pose="<<endl<<pose.matrix()<<endl;
// 以及所有特征点的位置
for ( size_t i=0; i<pts1.size(); i++ )
{
g2o::VertexSBAPointXYZ* v = dynamic_cast<g2o::VertexSBAPointXYZ*> (optimizer.vertex(i+2));
cout<<"vertex id "<<i+2<<", pos = ";
Eigen::Vector3d pos = v->estimate();
cout<<pos(0)<<","<<pos(1)<<","<<pos(2)<<endl;
}
// 估计inlier的个数
int inliers = 0;
for ( auto e:edges )
{
e->computeError();
// chi2 就是 error*\Omega*error, 如果这个数很大,说明此边的值与其他边很不相符
if ( e->chi2() > 1 )
{
cout<<"error = "<<e->chi2()<<endl;
}
else
{
inliers++;
}
}
cout<<"inliers in total points: "<<inliers<<"/"<<pts1.size()+pts2.size()<<endl;
optimizer.save("ba.g2o");
return 0;
}
int findCorrespondingPoints( const cv::Mat& img1, const cv::Mat& img2, vector<cv::Point2f>& points1, vector<cv::Point2f>& points2 )
{
cv::ORB orb;
vector<cv::KeyPoint> kp1, kp2;
cv::Mat desp1, desp2;
orb( img1, cv::Mat(), kp1, desp1 );
orb( img2, cv::Mat(), kp2, desp2 );
cout<<"分别找到了"<<kp1.size()<<"和"<<kp2.size()<<"个特征点"<<endl;
cv::Ptr<cv::DescriptorMatcher> matcher = cv::DescriptorMatcher::create( "BruteForce-Hamming");
double knn_match_ratio=0.8;
vector< vector<cv::DMatch> > matches_knn;
matcher->knnMatch( desp1, desp2, matches_knn, 2 );
vector< cv::DMatch > matches;
for ( size_t i=0; i<matches_knn.size(); i++ )
{
if (matches_knn[i][0].distance < knn_match_ratio * matches_knn[i][1].distance )
matches.push_back( matches_knn[i][0] );
}
if (matches.size() <= 20) //匹配点太少
return false;
for ( auto m:matches )
{
points1.push_back( kp1[m.queryIdx].pt );
points2.push_back( kp2[m.trainIdx].pt );
}
return true;
}
| [
"kf031490@163.com"
] | kf031490@163.com | |
e7bed1b95c827fc0526421b6c4c86a0152aa897f | 3ef56b1144e1086009877e18ca602fa8bc1c5b33 | /srchybrid/TransferDlg.cpp | a2088e94a17d5dca60814a9ee20816d2b402658e | [] | no_license | rusingineer/StulleMule | 54569fc5c1d829afd755c24aa8dc248f6413f252 | a8444d55d87834e0a2ef7918a0fe428e3003c136 | refs/heads/master | 2020-04-02T05:17:54.831491 | 2010-12-25T18:43:36 | 2010-12-25T18:43:36 | 61,437,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,300 | cpp | //this file is part of eMule
//Copyright (C)2002-2010 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 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 General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include "stdafx.h"
#include "emule.h"
#include "emuleDlg.h"
#include "TransferDlg.h"
#include "TransferWnd.h"
#include "ToolbarWnd.h"
#include "OtherFunctions.h"
#include "HelpIDs.h"
#include "Preferences.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define IDBAR_DOWNLOAD_TOOLBAR (AFX_IDW_CONTROLBAR_FIRST + 32 + 2) // do NOT change that ID, if not absolutely needed (it is stored by MFC in the bar profile!)
#define DOWNLOAD_TOOLBAR_PROFILE _T("DownloadFrmBarState")
IMPLEMENT_DYNCREATE(CTransferDlg, CFrameWnd)
BEGIN_MESSAGE_MAP(CTransferDlg, CFrameWnd)
ON_WM_CREATE()
ON_WM_SHOWWINDOW()
ON_WM_SETFOCUS()
ON_WM_CLOSE()
ON_WM_SYSCOMMAND()
ON_WM_HELPINFO()
END_MESSAGE_MAP()
CTransferDlg::CTransferDlg()
{
m_pwndToolbar = new CToolbarWnd;
m_pwndTransfer = NULL;
}
CTransferDlg::~CTransferDlg()
{
delete m_pwndToolbar;
}
BOOL CTransferDlg::Create(CWnd* pParent)
{
// *) The initial size of that frame window must not exceed the window size of the
// dialog resource template of the client window (the search results window).
// *) The dialog resource template's window size (of the search results window) must not
// exceed the minimum client area of the frame window.
// Otherwise we may get scrollbars in the search results window
CRect rc(0, 0, 50, 50);
return CFrameWnd::Create(NULL, _T("Transfer"), WS_CHILD | WS_CLIPCHILDREN, rc, pParent, NULL, 0, NULL);
}
int CTransferDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
CCreateContext context;
context.m_pCurrentFrame = this;
context.m_pCurrentDoc = NULL;
context.m_pNewViewClass = RUNTIME_CLASS(CTransferWnd);
context.m_pNewDocTemplate = NULL;
m_pwndTransfer = (CTransferWnd*)CreateView(&context);
m_pwndTransfer->ModifyStyle(WS_BORDER, 0);
m_pwndTransfer->ModifyStyleEx(WS_EX_CLIENTEDGE, WS_EX_STATICEDGE);
m_pwndToolbar->Create(this, IDD_DOWNLOAD_TOOLBARS,
WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_SIZE_FIXED | CBRS_SIZE_DYNAMIC | CBRS_GRIPPER,
IDBAR_DOWNLOAD_TOOLBAR);
ASSERT( m_pwndToolbar->GetStyle() & WS_CLIPSIBLINGS );
ASSERT( m_pwndToolbar->GetStyle() & WS_CLIPCHILDREN );
m_pwndToolbar->SetWindowText(GetResString(IDS_DOWNLOADCOMMANDS));
m_pwndToolbar->EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(m_pwndToolbar, AFX_IDW_DOCKBAR_LEFT, (LPRECT)NULL);
m_pwndTransfer->SendMessage(WM_INITIALUPDATE);
LoadBarState(DOWNLOAD_TOOLBAR_PROFILE);
DockToolbarWnd(); // Too much bug reports about vanished search parameters window. Force to dock.
ShowToolbar(thePrefs.IsDownloadToolbarEnabled());
m_pwndToolbar->SetCommandTargetWnd(GetDownloadList());
Localize();
return 0;
}
void CTransferDlg::OnClose()
{
SaveBarState(DOWNLOAD_TOOLBAR_PROFILE);
CFrameWnd::OnClose();
}
void CTransferDlg::OnShowWindow(BOOL bShow, UINT nStatus)
{
CFrameWnd::OnShowWindow(bShow, nStatus);
if (m_pwndToolbar->IsFloating())
{
//ShowControlBar(m_pwndParams, bShow, TRUE);
DockToolbarWnd(); // Too much bug reports about vanished search parameters window. Force to dock.
}
}
void CTransferDlg::OnSetFocus(CWnd* pOldWnd)
{
CFrameWnd::OnSetFocus(pOldWnd);
if (m_pwndToolbar->m_hWnd)
m_pwndToolbar->SetFocus();
}
void CTransferDlg::DockToolbarWnd()
{
if (m_pwndToolbar->IsFloating())
{
UINT uMRUDockID = AFX_IDW_DOCKBAR_TOP;
if (m_pwndToolbar->m_pDockContext)
uMRUDockID = m_pwndToolbar->m_pDockContext->m_uMRUDockID;
DockControlBar(m_pwndToolbar, uMRUDockID);
}
}
void CTransferDlg::Localize()
{
m_pwndTransfer->Localize();
m_pwndToolbar->Localize();
}
void CTransferDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if (nID == SC_KEYMENU)
{
if (lParam == EMULE_HOTMENU_ACCEL)
theApp.emuledlg->SendMessage(WM_COMMAND, IDC_HOTMENU);
else
theApp.emuledlg->SendMessage(WM_SYSCOMMAND, nID, lParam);
return;
}
CFrameWnd::OnSysCommand(nID, lParam);
}
BOOL CTransferDlg::PreTranslateMessage(MSG* pMsg)
{
if (pMsg->message == WM_KEYDOWN)
{
// Don't handle Ctrl+Tab in this window. It will be handled by main window.
if (pMsg->wParam == VK_TAB && GetAsyncKeyState(VK_CONTROL) < 0)
{
// UGLY: Because this window is a 'CFrameWnd' (rather than a 'CDialog' like
// the other eMule main windows) we can not use MFC's message routing. Need
// to explicitly send that message to the main window.
theApp.emuledlg->PostMessage(pMsg->message, pMsg->wParam, pMsg->lParam);
return TRUE;
}
}
return CFrameWnd::PreTranslateMessage(pMsg);
}
BOOL CTransferDlg::OnHelpInfo(HELPINFO* /*pHelpInfo*/)
{
theApp.ShowHelp(eMule_FAQ_GUI_Transfers);
return TRUE;
}
void CTransferDlg::ShowToolbar(bool bShow)
{
if ((m_pwndToolbar->IsVisible() ? true : false) != bShow)
{
if (thePrefs.IsDownloadToolbarEnabled() || !bShow)
ShowControlBar(m_pwndToolbar, bShow ? TRUE : FALSE, TRUE);
}
}
//////////////////////////////////////////////////////////////////////
// Wrappers
void CTransferDlg::ShowQueueCount(uint32 number)
{
m_pwndTransfer->ShowQueueCount(number);
}
void CTransferDlg::UpdateFilesCount(int iCount)
{
m_pwndTransfer->UpdateFilesCount(iCount);
}
void CTransferDlg::UpdateCatTabTitles(bool force)
{
m_pwndTransfer->UpdateCatTabTitles(force);
}
void CTransferDlg::VerifyCatTabSize()
{
m_pwndTransfer->VerifyCatTabSize();
}
int CTransferDlg::AddCategoryInteractive()
{
return m_pwndTransfer->AddCategoryInteractive();
}
void CTransferDlg::SwitchUploadList()
{
m_pwndTransfer->SwitchUploadList();
}
void CTransferDlg::ResetTransToolbar(bool bShowToolbar, bool bResetLists)
{
m_pwndTransfer->ResetTransToolbar(bShowToolbar, bResetLists);
}
void CTransferDlg::SetToolTipsDelay(DWORD dwDelay)
{
m_pwndTransfer->SetToolTipsDelay(dwDelay);
}
void CTransferDlg::OnDisableList()
{
m_pwndTransfer->OnDisableList();
}
// khaos::categorymod+
int CTransferDlg::GetActiveCategory()
{
return m_pwndTransfer->GetActiveCategory();
}
// khaos::categorymod-
// ==> Design Settings [eWombat/Stulle] - Stulle
#ifdef DESIGN_SETTINGS
void CTransferDlg::SetBackgroundColor(int nStyle)
{
m_pwndTransfer->SetBackgroundColor(nStyle);
}
void CTransferDlg::OnBackcolor()
{
m_pwndTransfer->OnBackcolor();
}
#endif
// <== Design Settings [eWombat/Stulle] - Stulle
// ==> CPU/MEM usage [$ick$/Stulle] - Stulle
void CTransferDlg::ShowRessources()
{
m_pwndTransfer->ShowRessources();
}
void CTransferDlg::EnableSysInfo(bool bEnable)
{
m_pwndTransfer->EnableSysInfo(bEnable);
}
// <== CPU/MEM usage [$ick$/Stulle] - Stulle
void CTransferDlg::UpdateListCount(EWnd2 listindex, int iCount)
{
m_pwndTransfer->UpdateListCount((CTransferWnd::EWnd2)listindex, iCount);
}
int CTransferDlg::AddCategory(CString newtitle,CString newincoming,CString newcomment,CString newautocat,bool addTab)
{
return m_pwndTransfer->AddCategory(newtitle, newincoming, newcomment, newautocat, addTab);
}
CUploadListCtrl* CTransferDlg::GetUploadList()
{
return &(m_pwndTransfer->uploadlistctrl);
}
CDownloadListCtrl* CTransferDlg::GetDownloadList()
{
return &(m_pwndTransfer->downloadlistctrl);
}
CQueueListCtrl* CTransferDlg::GetQueueList()
{
return &(m_pwndTransfer->queuelistctrl);
}
CClientListCtrl* CTransferDlg::GetClientList()
{
return &(m_pwndTransfer->clientlistctrl);
}
CDownloadClientsCtrl* CTransferDlg::GetDownloadClientsList()
{
return &(m_pwndTransfer->downloadclientsctrl);
}
//////////////////////////////////////////////////////////////////
| [
"stulleamgym@gmx.net"
] | stulleamgym@gmx.net |
e0bcdcda141331ce6125ba041df4fcaee189ec8f | 2c836aefea9cbd88d2ff6b5b2682a9fda39077f7 | /Source/M3Project/UI/Defualt/AddItemListUI.h | 5d96e0bdeb85a51638511bbd3a64574844a6cd9e | [] | no_license | MinA0617/FantasyVillage | fa5e9bd340171e80321456fa49e8c4ceace0d9d4 | ce9b503446db26642bd1362d1e80420c02d0cd97 | refs/heads/master | 2023-02-05T15:36:05.404509 | 2020-12-22T21:05:43 | 2020-12-22T21:05:43 | 323,697,358 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 749 | h | #pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "AddItemUI.h"
#include "Components/VerticalBox.h"
#include "AddItemListUI.generated.h"
UCLASS()
class M3PROJECT_API UAddItemListUI : public UUserWidget
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintReadWrite, EditAnywhere) UWidgetAnimation* InitAnimation;
UPROPERTY(BlueprintReadWrite, EditAnywhere) TSubclassOf<UAddItemUI> AddItemClass;
UPROPERTY(BlueprintReadWrite, EditAnywhere) TArray<UAddItemUI*> AddItemList;
UPROPERTY(BlueprintReadWrite, EditAnywhere) UVerticalBox* VBox;
public:
void AddAddItemWidget(UItemBase* Item);
void RemoveAddItemWidget();
void TimerOut();
private:
bool IsNextAnimation;
FTimerHandle Timer[3];
};
| [
"skmj0617@gmail.com"
] | skmj0617@gmail.com |
2848ad07992f0296df5e7e85cbfc0e9057d15b14 | f14fcb49453b312deb2a811e4447606aeef57e55 | /src/rpc/rpc_server_stats_printer.h | 719a50910e56626ccdc20008609a1b65f9af1898 | [
"Apache-2.0"
] | permissive | hsaputra/smf | c92d93f06d97e77e7d6c7c063b7b6d7fc6b07ead | 61df15ec0471bfa24ad2a1ac016d26155bd62ef1 | refs/heads/master | 2021-01-25T09:04:25.112404 | 2017-06-05T02:36:59 | 2017-06-05T02:36:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 803 | h | // Copyright (c) 2016 Alexander Gallego. All rights reserved.
//
#pragma once
// seastar
#include <core/distributed.hh>
#include <core/timer.hh>
// smf
#include "rpc/rpc_server_stats.h"
namespace smf {
class rpc_server_stats_printer {
public:
using duration_t = seastar::timer<>::duration;
rpc_server_stats_printer(seastar::distributed<rpc_server_stats> *stats,
duration_t d = std::chrono::minutes(2));
void start();
seastar::future<> stop();
private:
/// \brief calls map_reduce on distributed<stats>
///
seastar::future<rpc_server_stats> aggregate_stats();
private:
seastar::timer<> timer_;
seastar::distributed<rpc_server_stats> *stats_;
duration_t period_;
};
} // namespace smf
| [
"gallego.alexx@gmail.com"
] | gallego.alexx@gmail.com |
51b62c8ee936383d05f42130f631f64030950acb | bfd3582bd1921735c9daa8b8d6a8df22eaf7c038 | /MapReduce/Projector.hpp | b8284d01dfcf9dd976a895dd195dcbdad9e8ed26 | [] | no_license | tomzzy1/MapReduce | dfb0384d2b7f8fc6d0327d3846110c831b0aabb8 | e93da8e71c604eb49e917b00a6a64d73b2e885f5 | refs/heads/master | 2023-01-08T20:47:32.346273 | 2020-11-04T05:09:23 | 2020-11-04T05:09:23 | 281,606,917 | 4 | 2 | null | 2020-07-31T03:47:13 | 2020-07-22T07:27:57 | C++ | UTF-8 | C++ | false | false | 995 | hpp | #pragma once
#include "Context.hpp"
class Projector
{
public:
Projector(std::initializer_list<int> l) : v(l) {}
Projector(const Projector&) = default;
using InputType = Table;
using SplitType = std::vector<std::vector<std::string>>;
using MapKeyType = std::vector<std::string>;
using MapValueType = std::vector<std::string>;
using ReduceKeyType = Table;
using ReduceValueType = Table;
SplitType split(const InputType& input, int size, int rank)
{
return input.split(size, rank);
}
void map(SplitType value, Context<MapKeyType, MapValueType, ReduceKeyType, ReduceValueType>& c)
{
for (auto& row : value)
{
MapValueType new_row;
for (int i : v)
{
new_row.push_back(row[i]);
}
c.write(new_row, new_row);
}
}
void reduce(MapKeyType key, std::vector<MapValueType> value,
Context<MapKeyType, MapValueType, ReduceKeyType, ReduceValueType>& c)
{
Table t;
t.push_back(std::move(value.front()));
c.write(t, t);
}
private:
std::vector<int> v;
};
| [
"tomzzy@live.com"
] | tomzzy@live.com |
bb0235bf03bb0c28186c1aecad9696d28e010690 | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/libs/metaparse/test/range.cpp | 701e905004ca400523f083a6abdc3d8f00f1dd7f | [
"BSL-1.0"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,280 | cpp | // Copyright Abel Sinkovics (abel@sinkovics.hu) 2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sstd/boost/metaparse/range.hpp>
#include <sstd/boost/metaparse/is_error.hpp>
#include <sstd/boost/metaparse/start.hpp>
#include <sstd/boost/metaparse/get_result.hpp>
#include "common.hpp"
#include <sstd/boost/mpl/equal_to.hpp>
#include <sstd/boost/mpl/apply_wrap.hpp>
#include <sstd/boost/mpl/assert.hpp>
#include <sstd/boost/mpl/char.hpp>
#include "test_case.hpp"
BOOST_METAPARSE_TEST_CASE(range)
{
using boost::metaparse::is_error;
using boost::metaparse::range;
using boost::metaparse::start;
using boost::metaparse::get_result;
using boost::mpl::apply_wrap2;
using boost::mpl::equal_to;
using boost::mpl::char_;
typedef range<char_<'0'>, char_<'9'> > digit_range;
// test_with_text
BOOST_MPL_ASSERT((is_error<apply_wrap2<digit_range, str_hello, start> >));
// test_with_number
BOOST_MPL_ASSERT((
equal_to<
get_result<apply_wrap2<digit_range, str_1983, start> >::type,
char_1
>
));
// test_with_empty_string
BOOST_MPL_ASSERT((is_error<apply_wrap2<digit_range, str_, start> >));
}
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
8785518fe140d719395a347438b20a5c31ac681d | d0b2f8361afecf9ba8ab461274f16fc019306190 | /notefilereader.h | dbf7f8c263625862b97ae1ed354eb35867ec56ab | [] | no_license | bdwgarrison/ZCWB | a6b731fcd3ab58df5e368366d0d0eaea5fcbc90e | 1bee74b308b274391cbe949c6ee62a5a77e15377 | refs/heads/master | 2021-01-01T05:51:40.986082 | 2015-02-15T21:45:36 | 2015-02-15T21:45:36 | 30,843,417 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 159 | h | #ifndef NOTEFILEREADER_H
#define NOTEFILEREADER_H
class NoteFileReader : public TextFileReader
{
public:
NoteFileReader();
};
#endif // NOTEFILEREADER_H
| [
"bdwgarrison@gmail.com"
] | bdwgarrison@gmail.com |
818ada332cab38570f6d594188d5aa4e9c8ab054 | 0f6abfdfce999eec62f8844e3bfa078faa4439e3 | /src/timedata.h | 0a26a57995b40624c8d3171a0ff5a980a0345937 | [
"MIT"
] | permissive | romamaslennikov/straks | d77c03cc2be9d19e5cb3db7f1cbe3c8e4a54e0c7 | a68d73accc16b480a267b0f83ca9f8f34cd16f64 | refs/heads/master | 2021-05-14T11:25:47.264422 | 2018-01-04T23:55:47 | 2018-01-04T23:55:47 | 116,381,232 | 1 | 0 | null | 2018-01-05T12:08:39 | 2018-01-05T12:08:38 | null | UTF-8 | C++ | false | false | 1,779 | h | // Copyright (c) 2017 STRAKS developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef STRAKS_TIMEDATA_H
#define STRAKS_TIMEDATA_H
#include <algorithm>
#include <assert.h>
#include <stdint.h>
#include <vector>
static const int64_t DEFAULT_MAX_TIME_ADJUSTMENT = 70 * 60;
class CNetAddr;
/**
* Median filter over a stream of values.
* Returns the median of the last N numbers
*/
template <typename T>
class CMedianFilter
{
private:
std::vector<T> vValues;
std::vector<T> vSorted;
unsigned int nSize;
public:
CMedianFilter(unsigned int size, T initial_value) : nSize(size)
{
vValues.reserve(size);
vValues.push_back(initial_value);
vSorted = vValues;
}
void input(T value)
{
if (vValues.size() == nSize) {
vValues.erase(vValues.begin());
}
vValues.push_back(value);
vSorted.resize(vValues.size());
std::copy(vValues.begin(), vValues.end(), vSorted.begin());
std::sort(vSorted.begin(), vSorted.end());
}
T median() const
{
int size = vSorted.size();
assert(size > 0);
if (size & 1) // Odd number of elements
{
return vSorted[size / 2];
} else // Even number of elements
{
return (vSorted[size / 2 - 1] + vSorted[size / 2]) / 2;
}
}
int size() const
{
return vValues.size();
}
std::vector<T> sorted() const
{
return vSorted;
}
};
/** Functions to keep track of adjusted P2P time */
int64_t GetTimeOffset();
int64_t GetAdjustedTime();
void AddTimeData(const CNetAddr& ip, int64_t nTime);
#endif // STRAKS_TIMEDATA_H
| [
"squbs@protonmail.com"
] | squbs@protonmail.com |
8ef427f73c792b16cfba6d330b332bda79a8850f | a1a0227d2c7f7837d43df0f1d97e33753d262566 | /src/background.cpp | 6c572dca1e1cfe0bf7ee29bf9a4166d02eaeb000 | [
"MIT"
] | permissive | olemke/radctrl | 18d806a0384755096dfeac5d04717a52e49a2184 | 871b7162555bed4a9fa3f4d2626d58244c17ee67 | refs/heads/master | 2022-12-17T19:57:41.071922 | 2020-09-28T14:48:05 | 2020-09-28T14:48:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,739 | cpp | #include "background.h"
namespace Background {
InterPoints Surface::interpPoints(
const Time newtid, const Coordinate<CoordinateType::lat> newlat,
const Coordinate<CoordinateType::lon> newlon) const noexcept {
LinearInterpPoint tidout(1, 0), latout(1, 0), lonout(1, 0);
if (tid.size() > 1) {
auto tidpos = std::find_if(tid.cbegin(), tid.cend(), [newtid](auto a) {
return not(a < newtid) and not(a == newtid);
});
auto tidlow = (tidpos == tid.cbegin()) ? tid.cbegin() : tidpos - 1;
auto tidw = (tidpos == tid.cend())
? 1.0
: Interp::weight(newtid.Seconds(), tidlow->Seconds(),
tidpos->Seconds());
tidout = LinearInterpPoint(tidw, size_t(tidlow - tid.cbegin()));
}
if (lat.size() > 1) {
auto latpos = std::find_if(lat.cbegin(), lat.cend(),
[newlat](auto a) { return newlat <= a; });
auto latlow = (latpos == lat.cbegin()) ? lat.cbegin() : latpos - 1;
auto latw = (latpos == lat.cend())
? 1.0
: Interp::weight(newlat, latlow->value(), latpos->value());
latout = LinearInterpPoint(latw, size_t(latlow - lat.cbegin()));
}
if (lon.size() > 1) {
auto lonpos = std::find_if(lon.cbegin(), lon.cend(),
[newlon](auto a) { return newlon <= a; });
auto lonlow = (lonpos == lon.cbegin()) ? lon.cbegin() : lonpos - 1;
auto lonw = (lonpos == lon.cend())
? 1.0
: Interp::weight(newlon, lonlow->value(), lonpos->value());
lonout = LinearInterpPoint(lonw, size_t(lonlow - lon.cbegin()));
}
return {tidout, latout, lonout};
}
} // namespace Background
| [
"ric.larsson@gmail.com"
] | ric.larsson@gmail.com |
89112808add20b62d4ccdf80e1e806f7b196b047 | c0d307556a46dc5782b7f527bf984f74d7b66757 | /content/renderer/service_worker/service_worker_context_client.h | 35a221380906697bb762801c94d5ea832a2c1dc9 | [
"BSD-3-Clause"
] | permissive | evertonteotonio/chromium | 1e03602a5970e361906aff6736031ab407d023da | 52706ac690c03e7285fef500206cd031450e39fd | refs/heads/master | 2023-03-12T19:58:28.024203 | 2018-06-26T16:14:36 | 2018-06-26T16:14:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,595 | h | // Copyright 2014 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_RENDERER_SERVICE_WORKER_SERVICE_WORKER_CONTEXT_CLIENT_H_
#define CONTENT_RENDERER_SERVICE_WORKER_SERVICE_WORKER_CONTEXT_CLIENT_H_
#include <stddef.h>
#include <stdint.h>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/containers/id_map.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/strings/string16.h"
#include "base/time/time.h"
#include "content/common/service_worker/controller_service_worker.mojom.h"
#include "content/common/service_worker/embedded_worker.mojom.h"
#include "content/common/service_worker/service_worker_event_dispatcher.mojom.h"
#include "content/common/service_worker/service_worker_provider.mojom.h"
#include "content/common/service_worker/service_worker_status_code.h"
#include "content/common/service_worker/service_worker_types.h"
#include "ipc/ipc_listener.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "third_party/blink/public/mojom/blob/blob_registry.mojom.h"
#include "third_party/blink/public/mojom/service_worker/service_worker.mojom.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_client.mojom.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
#include "third_party/blink/public/platform/modules/payments/payment_app.mojom.h"
#include "third_party/blink/public/platform/modules/serviceworker/web_service_worker_error.h"
#include "third_party/blink/public/web/modules/serviceworker/web_service_worker_context_client.h"
#include "third_party/blink/public/web/modules/serviceworker/web_service_worker_context_proxy.h"
#include "v8/include/v8.h"
namespace base {
class SingleThreadTaskRunner;
class TaskRunner;
}
namespace blink {
class WebDataConsumerHandle;
struct WebServiceWorkerClientQueryOptions;
class WebServiceWorkerContextProxy;
class WebServiceWorkerProvider;
class WebServiceWorkerResponse;
class WebURLResponse;
}
namespace content {
struct PlatformNotificationData;
struct PushEventPayload;
class EmbeddedWorkerInstanceClientImpl;
class ServiceWorkerNetworkProvider;
class ServiceWorkerProviderContext;
class ServiceWorkerTimeoutTimer;
class WebServiceWorkerImpl;
class WebWorkerFetchContext;
// ServiceWorkerContextClient is a "client" of a service worker execution
// context. It enables communication between the embedder and Blink's
// ServiceWorkerGlobalScope. It is created when the service worker begins
// starting up, and destroyed when the service worker stops. It is owned by
// EmbeddedWorkerInstanceClientImpl's internal WorkerWrapper class.
//
// Unless otherwise noted (here or in base class documentation), all methods are
// called on the worker thread.
class CONTENT_EXPORT ServiceWorkerContextClient
: public blink::WebServiceWorkerContextClient,
public mojom::ServiceWorkerEventDispatcher {
public:
// Returns a thread-specific client instance. This does NOT create a
// new instance.
static ServiceWorkerContextClient* ThreadSpecificInstance();
// Called on the main thread.
// |is_script_streaming| is true if the script is already installed and will
// be streamed from the browser process.
ServiceWorkerContextClient(
int embedded_worker_id,
int64_t service_worker_version_id,
const GURL& service_worker_scope,
const GURL& script_url,
bool is_starting_installed_worker,
mojom::ServiceWorkerEventDispatcherRequest dispatcher_request,
mojom::ControllerServiceWorkerRequest controller_request,
mojom::EmbeddedWorkerInstanceHostAssociatedPtrInfo instance_host,
mojom::ServiceWorkerProviderInfoForStartWorkerPtr provider_info,
std::unique_ptr<EmbeddedWorkerInstanceClientImpl> embedded_worker_client,
scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner);
~ServiceWorkerContextClient() override;
// Called on the main thread.
void set_blink_initialized_time(base::TimeTicks blink_initialized_time) {
blink_initialized_time_ = blink_initialized_time;
}
void set_start_worker_received_time(
base::TimeTicks start_worker_received_time) {
start_worker_received_time_ = start_worker_received_time;
}
// Returns the service worker object described by |info|. Creates a new object
// if needed, or else returns the existing one.
scoped_refptr<WebServiceWorkerImpl> GetOrCreateServiceWorkerObject(
blink::mojom::ServiceWorkerObjectInfoPtr info);
// WebServiceWorkerContextClient overrides.
void GetClient(
const blink::WebString& client_id,
std::unique_ptr<blink::WebServiceWorkerClientCallbacks>) override;
void GetClients(
const blink::WebServiceWorkerClientQueryOptions&,
std::unique_ptr<blink::WebServiceWorkerClientsCallbacks>) override;
void OpenNewTab(
const blink::WebURL&,
std::unique_ptr<blink::WebServiceWorkerClientCallbacks>) override;
void OpenPaymentHandlerWindow(
const blink::WebURL&,
std::unique_ptr<blink::WebServiceWorkerClientCallbacks>) override;
void SetCachedMetadata(const blink::WebURL&,
const char* data,
size_t size) override;
void ClearCachedMetadata(const blink::WebURL&) override;
void WorkerReadyForInspection() override;
void WorkerContextFailedToStart() override;
void WorkerScriptLoaded() override;
void WorkerContextStarted(
blink::WebServiceWorkerContextProxy* proxy) override;
void DidEvaluateClassicScript(bool success) override;
void DidInitializeWorkerContext(v8::Local<v8::Context> context) override;
void WillDestroyWorkerContext(v8::Local<v8::Context> context) override;
void WorkerContextDestroyed() override;
void CountFeature(blink::mojom::WebFeature feature) override;
void ReportException(const blink::WebString& error_message,
int line_number,
int column_number,
const blink::WebString& source_url) override;
void ReportConsoleMessage(int source,
int level,
const blink::WebString& message,
int line_number,
const blink::WebString& source_url) override;
void DidHandleActivateEvent(int request_id,
blink::mojom::ServiceWorkerEventStatus status,
double dispatch_event_time) override;
void DidHandleBackgroundFetchAbortEvent(
int request_id,
blink::mojom::ServiceWorkerEventStatus status,
double dispatch_event_time) override;
void DidHandleBackgroundFetchClickEvent(
int request_id,
blink::mojom::ServiceWorkerEventStatus status,
double dispatch_event_time) override;
void DidHandleBackgroundFetchFailEvent(
int request_id,
blink::mojom::ServiceWorkerEventStatus status,
double dispatch_event_time) override;
void DidHandleBackgroundFetchedEvent(
int request_id,
blink::mojom::ServiceWorkerEventStatus status,
double dispatch_event_time) override;
void DidHandleCookieChangeEvent(int request_id,
blink::mojom::ServiceWorkerEventStatus status,
double dispatch_event_time) override;
void DidHandleExtendableMessageEvent(
int request_id,
blink::mojom::ServiceWorkerEventStatus status,
double dispatch_event_time) override;
void DidHandleInstallEvent(int event_id,
blink::mojom::ServiceWorkerEventStatus status,
double event_dispatch_time) override;
void RespondToFetchEventWithNoResponse(int fetch_event_id,
double event_dispatch_time) override;
void RespondToFetchEvent(int fetch_event_id,
const blink::WebServiceWorkerResponse& response,
double event_dispatch_time) override;
void RespondToFetchEventWithResponseStream(
int fetch_event_id,
const blink::WebServiceWorkerResponse& response,
blink::WebServiceWorkerStreamHandle* web_body_as_stream,
double event_dispatch_time) override;
void DidHandleFetchEvent(int fetch_event_id,
blink::mojom::ServiceWorkerEventStatus status,
double dispatch_event_time) override;
void DidHandleNotificationClickEvent(
int request_id,
blink::mojom::ServiceWorkerEventStatus status,
double dispatch_event_time) override;
void DidHandleNotificationCloseEvent(
int request_id,
blink::mojom::ServiceWorkerEventStatus status,
double dispatch_event_time) override;
void DidHandlePushEvent(int request_id,
blink::mojom::ServiceWorkerEventStatus status,
double dispatch_event_time) override;
void DidHandleSyncEvent(int request_id,
blink::mojom::ServiceWorkerEventStatus status,
double dispatch_event_time) override;
void RespondToAbortPaymentEvent(int event_id,
bool payment_aborted,
double dispatch_event_time) override;
void DidHandleAbortPaymentEvent(int event_id,
blink::mojom::ServiceWorkerEventStatus status,
double dispatch_event_time) override;
void RespondToCanMakePaymentEvent(int event_id,
bool can_make_payment,
double dispatch_event_time) override;
void DidHandleCanMakePaymentEvent(
int event_id,
blink::mojom::ServiceWorkerEventStatus status,
double dispatch_event_time) override;
void RespondToPaymentRequestEvent(
int payment_request_id,
const blink::WebPaymentHandlerResponse& response,
double dispatch_event_time) override;
void DidHandlePaymentRequestEvent(
int payment_request_id,
blink::mojom::ServiceWorkerEventStatus status,
double dispatch_event_time) override;
std::unique_ptr<blink::WebServiceWorkerNetworkProvider>
CreateServiceWorkerNetworkProvider() override;
std::unique_ptr<blink::WebWorkerFetchContext> CreateServiceWorkerFetchContext(
blink::WebServiceWorkerNetworkProvider*) override;
std::unique_ptr<blink::WebServiceWorkerProvider> CreateServiceWorkerProvider()
override;
void PostMessageToClient(const blink::WebString& uuid,
blink::TransferableMessage message) override;
void Focus(const blink::WebString& uuid,
std::unique_ptr<blink::WebServiceWorkerClientCallbacks>) override;
void Navigate(
const blink::WebString& uuid,
const blink::WebURL&,
std::unique_ptr<blink::WebServiceWorkerClientCallbacks>) override;
void SkipWaiting(std::unique_ptr<blink::WebServiceWorkerSkipWaitingCallbacks>
callbacks) override;
void Claim(std::unique_ptr<blink::WebServiceWorkerClientsClaimCallbacks>
callbacks) override;
// Dispatches the fetch event if the worker is running normally, and queues it
// instead if the worker has already requested to be terminated by the
// browser. If queued, the event will be dispatched once the worker resumes
// normal operation (if the browser decides not to terminate it, and instead
// starts another event), or else is dropped if the worker is terminated.
//
// This method needs to be used only if the event comes directly from a
// client, which means it is coming through the ControllerServiceWorkerImpl.
void DispatchOrQueueFetchEvent(
blink::mojom::DispatchFetchEventParamsPtr params,
mojom::ServiceWorkerFetchResponseCallbackPtr response_callback,
DispatchFetchEventCallback callback);
private:
struct WorkerContextData;
class NavigationPreloadRequest;
friend class ControllerServiceWorkerImpl;
friend class ServiceWorkerContextClientTest;
friend class WebServiceWorkerImpl;
FRIEND_TEST_ALL_PREFIXES(
ServiceWorkerContextClientTest,
DispatchOrQueueFetchEvent_RequestedTerminationAndDie);
FRIEND_TEST_ALL_PREFIXES(
ServiceWorkerContextClientTest,
DispatchOrQueueFetchEvent_RequestedTerminationAndWakeUp);
FRIEND_TEST_ALL_PREFIXES(ServiceWorkerContextClientTest,
DispatchOrQueueFetchEvent_NotRequestedTermination);
// Get routing_id for sending message to the ServiceWorkerVersion
// in the browser process.
int GetRoutingID() const { return embedded_worker_id_; }
void SendWorkerStarted();
// Implements mojom::ServiceWorkerEventDispatcher.
void InitializeGlobalScope(
blink::mojom::ServiceWorkerHostAssociatedPtrInfo service_worker_host,
blink::mojom::ServiceWorkerRegistrationObjectInfoPtr registration_info)
override;
void DispatchInstallEvent(
DispatchInstallEventCallback callback) override;
void DispatchActivateEvent(DispatchActivateEventCallback callback) override;
void DispatchBackgroundFetchAbortEvent(
const std::string& developer_id,
const std::string& unique_id,
const std::vector<BackgroundFetchSettledFetch>& fetches,
DispatchBackgroundFetchAbortEventCallback callback) override;
void DispatchBackgroundFetchClickEvent(
const std::string& developer_id,
mojom::BackgroundFetchState state,
DispatchBackgroundFetchClickEventCallback callback) override;
void DispatchBackgroundFetchFailEvent(
const std::string& developer_id,
const std::string& unique_id,
const std::vector<BackgroundFetchSettledFetch>& fetches,
DispatchBackgroundFetchFailEventCallback callback) override;
void DispatchBackgroundFetchedEvent(
const std::string& developer_id,
const std::string& unique_id,
const std::vector<BackgroundFetchSettledFetch>& fetches,
DispatchBackgroundFetchedEventCallback callback) override;
void DispatchExtendableMessageEvent(
mojom::ExtendableMessageEventPtr event,
DispatchExtendableMessageEventCallback callback) override;
void DispatchFetchEvent(
blink::mojom::DispatchFetchEventParamsPtr params,
mojom::ServiceWorkerFetchResponseCallbackPtr response_callback,
DispatchFetchEventCallback callback) override;
void DispatchNotificationClickEvent(
const std::string& notification_id,
const PlatformNotificationData& notification_data,
int action_index,
const base::Optional<base::string16>& reply,
DispatchNotificationClickEventCallback callback) override;
void DispatchNotificationCloseEvent(
const std::string& notification_id,
const PlatformNotificationData& notification_data,
DispatchNotificationCloseEventCallback callback) override;
void DispatchPushEvent(const PushEventPayload& payload,
DispatchPushEventCallback callback) override;
void DispatchSyncEvent(const std::string& tag,
bool last_chance,
base::TimeDelta timeout,
DispatchSyncEventCallback callback) override;
void DispatchAbortPaymentEvent(
payments::mojom::PaymentHandlerResponseCallbackPtr response_callback,
DispatchAbortPaymentEventCallback callback) override;
void DispatchCanMakePaymentEvent(
payments::mojom::CanMakePaymentEventDataPtr event_data,
payments::mojom::PaymentHandlerResponseCallbackPtr response_callback,
DispatchCanMakePaymentEventCallback callback) override;
void DispatchPaymentRequestEvent(
payments::mojom::PaymentRequestEventDataPtr event_data,
payments::mojom::PaymentHandlerResponseCallbackPtr response_callback,
DispatchPaymentRequestEventCallback callback) override;
void DispatchCookieChangeEvent(
const net::CanonicalCookie& cookie,
::network::mojom::CookieChangeCause cause,
DispatchCookieChangeEventCallback callback) override;
void Ping(PingCallback callback) override;
void SetIdleTimerDelayToZero() override;
void OnNotificationClickEvent(
int request_id,
const std::string& notification_id,
const PlatformNotificationData& notification_data,
int action_index,
const base::NullableString16& reply);
void OnNotificationCloseEvent(
int request_id,
const std::string& notification_id,
const PlatformNotificationData& notification_data);
void OnFocusClientResponse(
int request_id,
const blink::mojom::ServiceWorkerClientInfo& client);
void OnNavigateClientResponse(
int request_id,
const blink::mojom::ServiceWorkerClientInfo& client);
void OnNavigateClientError(int request_id, const GURL& url);
// Called to resolve the FetchEvent.preloadResponse promise.
void OnNavigationPreloadResponse(
int fetch_event_id,
std::unique_ptr<blink::WebURLResponse> response,
std::unique_ptr<blink::WebDataConsumerHandle> data_consumer_handle);
// Called when the navigation preload request completed. Either
// OnNavigationPreloadComplete() or OnNavigationPreloadError() must be
// called to release the preload related resources.
void OnNavigationPreloadComplete(int fetch_event_id,
base::TimeTicks completion_time,
int64_t encoded_data_length,
int64_t encoded_body_length,
int64_t decoded_body_length);
// Called when an error occurred while receiving the response of the
// navigation preload request.
void OnNavigationPreloadError(
int fetch_event_id,
std::unique_ptr<blink::WebServiceWorkerError> error);
void SetupNavigationPreload(
int fetch_event_id,
const GURL& url,
blink::mojom::FetchEventPreloadHandlePtr preload_handle);
// Called by ServiceWorkerTimeoutTimer when a certain time has passed since
// the last task finished.
void OnIdleTimeout();
// Returns true if the worker has requested to be terminated by the browser
// process. It does this due to idle timeout.
bool RequestedTermination() const;
// Keeps the mapping from version id to ServiceWorker object.
void AddServiceWorkerObject(int64_t version_id, WebServiceWorkerImpl* worker);
void RemoveServiceWorkerObject(int64_t version_id);
bool ContainsServiceWorkerObjectForTesting(int64_t version_id);
base::WeakPtr<ServiceWorkerContextClient> GetWeakPtr();
static void ResetThreadSpecificInstanceForTesting();
void SetTimeoutTimerForTesting(
std::unique_ptr<ServiceWorkerTimeoutTimer> timeout_timer);
const int embedded_worker_id_;
const int64_t service_worker_version_id_;
const GURL service_worker_scope_;
const GURL script_url_;
// True if this service worker was already installed at worker
// startup time.
const bool is_starting_installed_worker_;
scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_;
scoped_refptr<base::TaskRunner> worker_task_runner_;
scoped_refptr<ServiceWorkerProviderContext> provider_context_;
// Not owned; |this| is destroyed when |proxy_| becomes invalid.
blink::WebServiceWorkerContextProxy* proxy_;
// These Mojo objects are bound on the worker thread.
mojom::ServiceWorkerEventDispatcherRequest pending_dispatcher_request_;
mojom::ControllerServiceWorkerRequest pending_controller_request_;
// This is bound on the main thread.
scoped_refptr<mojom::ThreadSafeEmbeddedWorkerInstanceHostAssociatedPtr>
instance_host_;
// This is passed to ServiceWorkerNetworkProvider when
// CreateServiceWorkerNetworkProvider is called.
std::unique_ptr<ServiceWorkerNetworkProvider> pending_network_provider_;
// This is valid from the ctor to WorkerContextDestroyed.
std::unique_ptr<EmbeddedWorkerInstanceClientImpl> embedded_worker_client_;
blink::mojom::BlobRegistryPtr blob_registry_;
// Initialized on the worker thread in workerContextStarted and
// destructed on the worker thread in willDestroyWorkerContext.
std::unique_ptr<WorkerContextData> context_;
base::TimeTicks blink_initialized_time_;
base::TimeTicks start_worker_received_time_;
DISALLOW_COPY_AND_ASSIGN(ServiceWorkerContextClient);
};
} // namespace content
#endif // CONTENT_RENDERER_SERVICE_WORKER_SERVICE_WORKER_CONTEXT_CLIENT_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
4b615ea552d413746ab1e4db1990562751b4a56e | fab805b73946ab8803ba71b25294de95041a5684 | /PATTERN_1.cpp | c402800ccd6c5102ecead65b0c8fe02856b39e3b | [] | no_license | 9643kavinder/Algorithms | 9d3363f79f7b6c7f6845c21acc6eb917353074b7 | b7ee2334a9fc5e24ef8a26a6fb7893f5ec32e00b | refs/heads/master | 2020-04-29T10:18:32.091954 | 2020-01-12T17:59:21 | 2020-01-12T17:59:21 | 176,057,581 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 276 | cpp | /*
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
*/
#include<iostream>
using namespace std;
int main(){
int n;
cout<<"ENTER THE NUMBER";
cin>>n;
int val =1;
for(int i=0;i<=n;i++){
int j=1;
for(j=1;j<=i;j++){
cout<<val<<" ";
val++;
}
cout<<"\n";
}
return 0;
}
| [
"[9643kavinder@gmail.com]"
] | [9643kavinder@gmail.com] |
7470d542580b705d946c20e8eb9b4d57ff239b4e | 6ca0a8f5c4d75fad8067103fd8699df8b492775d | /src/rpc/mining.cpp | 3feefa3ed6a792bfc4e6acc74a7dc5322da64fef | [
"MIT"
] | permissive | MRVofficial/MRVCoin | ab338ad072114c017795b5d9d9a5b5a8788219fc | 448b9c1bbb90f891e8822b1d9b141837f780e478 | refs/heads/master | 2023-03-02T08:49:57.378571 | 2021-02-04T04:56:06 | 2021-02-04T04:56:06 | 278,033,508 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 32,496 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
//Copyright (c) 2015-2020 The PIVX developers
//Copyright (c) 2020 The MRV Coin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "base58.h"
#include "chainparams.h"
#include "core_io.h"
#include "init.h"
#include "main.h"
#include "miner.h"
#include "net.h"
#include "pow.h"
#include "rpc/server.h"
#include "util.h"
#include "validationinterface.h"
#ifdef ENABLE_WALLET
#include "wallet/db.h"
#include "wallet/wallet.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include <univalue.h>
/**
* Return average network hashes per second based on the last 'lookup' blocks,
* or from the last difficulty change if 'lookup' is nonpositive.
* If 'height' is nonnegative, compute the estimate at the time when a given block was found.
*/
UniValue GetNetworkHashPS(int lookup, int height)
{
CBlockIndex *pb = chainActive.Tip();
if (height >= 0 && height < chainActive.Height())
pb = chainActive[height];
if (pb == NULL || !pb->nHeight)
return 0;
// If lookup is -1, then use blocks since last difficulty change.
if (lookup <= 0)
lookup = pb->nHeight % 2016 + 1;
// If lookup is larger than chain, then set it to chain length.
if (lookup > pb->nHeight)
lookup = pb->nHeight;
CBlockIndex* pb0 = pb;
int64_t minTime = pb0->GetBlockTime();
int64_t maxTime = minTime;
for (int i = 0; i < lookup; i++) {
pb0 = pb0->pprev;
int64_t time = pb0->GetBlockTime();
minTime = std::min(time, minTime);
maxTime = std::max(time, maxTime);
}
// In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
if (minTime == maxTime)
return 0;
uint256 workDiff = pb->nChainWork - pb0->nChainWork;
int64_t timeDiff = maxTime - minTime;
return (int64_t)(workDiff.getdouble() / timeDiff);
}
UniValue getnetworkhashps(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw std::runtime_error(
"getnetworkhashps ( blocks height )\n"
"\nReturns the estimated network hashes per second based on the last n blocks.\n"
"Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
"Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
"\nArguments:\n"
"1. blocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
"2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
"\nResult:\n"
"x (numeric) Hashes per second estimated\n"
"\nExamples:\n" +
HelpExampleCli("getnetworkhashps", "") + HelpExampleRpc("getnetworkhashps", ""));
LOCK(cs_main);
return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1);
}
#ifdef ENABLE_WALLET
UniValue getgenerate(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw std::runtime_error(
"getgenerate\n"
"\nReturn if the server is set to generate coins or not. The default is false.\n"
"It is set with the command line argument -gen (or mrv_coin.conf setting gen)\n"
"It can also be set with the setgenerate call.\n"
"\nResult\n"
"true|false (boolean) If the server is set to generate coins or not\n"
"\nExamples:\n" +
HelpExampleCli("getgenerate", "") + HelpExampleRpc("getgenerate", ""));
LOCK(cs_main);
return GetBoolArg("-gen", false);
}
UniValue generate(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw std::runtime_error(
"generate numblocks\n"
"\nMine blocks immediately (before the RPC call returns)\n"
"\nNote: this function can only be used on the regtest network\n"
"\nArguments:\n"
"1. numblocks (numeric, required) How many blocks to generate.\n"
"\nResult\n"
"[ blockhashes ] (array) hashes of blocks generated\n"
"\nExamples:\n"
"\nGenerate 11 blocks\n"
+ HelpExampleCli("generate", "11")
);
if (!Params().IsRegTestNet())
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "This method can only be used on regtest");
const int nGenerate = params[0].get_int();
int nHeightEnd = 0;
int nHeight = 0;
{ // Don't keep cs_main locked
LOCK(cs_main);
nHeight = chainActive.Height();
nHeightEnd = nHeight + nGenerate;
}
const int last_pow_block = Params().GetConsensus().height_last_PoW;
bool fPoS = nHeight >= last_pow_block;
if (fPoS) {
// If we are in PoS, wallet must be unlocked.
EnsureWalletIsUnlocked();
}
UniValue blockHashes(UniValue::VARR);
CReserveKey reservekey(pwalletMain);
unsigned int nExtraNonce = 0;
while (nHeight < nHeightEnd && !ShutdownRequested())
{
std::unique_ptr<CBlockTemplate> pblocktemplate(fPoS ?
CreateNewBlock(CScript(), pwalletMain, fPoS) :
CreateNewBlockWithKey(reservekey, pwalletMain));
if (!pblocktemplate.get()) break;
CBlock *pblock = &pblocktemplate->block;
if(!fPoS) {
{
LOCK(cs_main);
IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce);
}
while (pblock->nNonce < std::numeric_limits<uint32_t>::max() &&
!CheckProofOfWork(pblock->GetHash(), pblock->nBits)) {
++pblock->nNonce;
}
if (ShutdownRequested()) break;
if (pblock->nNonce == std::numeric_limits<uint32_t>::max()) continue;
}
CValidationState state;
if (!ProcessNewBlock(state, nullptr, pblock))
throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
++nHeight;
blockHashes.push_back(pblock->GetHash().GetHex());
// Check PoS if needed.
if (!fPoS) fPoS = (nHeight >= last_pow_block);
}
const int nGenerated = blockHashes.size();
if (nGenerated == 0 || (!fPoS && nGenerated < nGenerate))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new blocks");
return blockHashes;
}
UniValue setgenerate(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"setgenerate generate ( genproclimit )\n"
"\nSet 'generate' true or false to turn generation on or off.\n"
"Generation is limited to 'genproclimit' processors, -1 is unlimited.\n"
"See the getgenerate call for the current setting.\n"
"\nArguments:\n"
"1. generate (boolean, required) Set to true to turn on generation, false to turn off.\n"
"2. genproclimit (numeric, optional) Set the processor limit for when generation is on. Can be -1 for unlimited.\n"
"\nExamples:\n"
"\nSet the generation on with a limit of one processor\n" +
HelpExampleCli("setgenerate", "true 1") +
"\nCheck the setting\n" + HelpExampleCli("getgenerate", "") +
"\nTurn off generation\n" + HelpExampleCli("setgenerate", "false") +
"\nUsing json rpc\n" + HelpExampleRpc("setgenerate", "true, 1"));
if (pwalletMain == NULL)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
if (Params().IsRegTestNet())
throw JSONRPCError(RPC_INVALID_REQUEST, "Use the generate method instead of setgenerate on regtest");
bool fGenerate = true;
if (params.size() > 0)
fGenerate = params[0].get_bool();
if (fGenerate && (chainActive.Height() >= Params().GetConsensus().height_last_PoW))
throw JSONRPCError(RPC_INVALID_REQUEST, "Proof of Work phase has already ended");
int nGenProcLimit = -1;
if (params.size() > 1) {
nGenProcLimit = params[1].get_int();
if (nGenProcLimit == 0)
fGenerate = false;
}
mapArgs["-gen"] = (fGenerate ? "1" : "0");
mapArgs["-genproclimit"] = itostr(nGenProcLimit);
GenerateBitcoins(fGenerate, pwalletMain, nGenProcLimit);
return NullUniValue;
}
UniValue gethashespersec(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw std::runtime_error(
"gethashespersec\n"
"\nReturns a recent hashes per second performance measurement while generating.\n"
"See the getgenerate and setgenerate calls to turn generation on and off.\n"
"\nResult:\n"
"n (numeric) The recent hashes per second when generation is on (will return 0 if generation is off)\n"
"\nExamples:\n" +
HelpExampleCli("gethashespersec", "") + HelpExampleRpc("gethashespersec", ""));
if (GetTimeMillis() - nHPSTimerStart > 8000)
return (int64_t)0;
return (int64_t)dHashesPerSec;
}
#endif
UniValue getmininginfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw std::runtime_error(
"getmininginfo\n"
"\nReturns a json object containing mining-related information."
"\nResult:\n"
"{\n"
" \"blocks\": nnn, (numeric) The current block\n"
" \"currentblocksize\": nnn, (numeric) The last block size\n"
" \"currentblocktx\": nnn, (numeric) The last block transaction\n"
" \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
" \"errors\": \"...\" (string) Current errors\n"
" \"generate\": true|false (boolean) If the generation is on or off (see getgenerate or setgenerate calls)\n"
" \"genproclimit\": n (numeric) The processor limit for generation. -1 if no generation. (see getgenerate or setgenerate calls)\n"
" \"hashespersec\": n (numeric) The hashes per second of the generation, or 0 if no generation.\n"
" \"pooledtx\": n (numeric) The size of the mem pool\n"
" \"testnet\": true|false (boolean) If using testnet or not\n"
" \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getmininginfo", "") + HelpExampleRpc("getmininginfo", ""));
LOCK(cs_main);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("blocks", (int)chainActive.Height()));
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("genproclimit", (int)GetArg("-genproclimit", -1)));
obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("testnet", Params().NetworkID() == CBaseChainParams::TESTNET));
obj.push_back(Pair("chain", Params().NetworkIDString()));
#ifdef ENABLE_WALLET
obj.push_back(Pair("generate", getgenerate(params, false)));
obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
#endif
return obj;
}
// NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
UniValue prioritisetransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw std::runtime_error(
"prioritisetransaction <txid> <priority delta> <fee delta>\n"
"Accepts the transaction into mined blocks at a higher (or lower) priority\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id.\n"
"2. priority delta (numeric, required) The priority to add or subtract.\n"
" The transaction selection algorithm considers the tx as it would have a higher priority.\n"
" (priority of a transaction is calculated: coinage * value_in_umrv / txsize) \n"
"3. fee delta (numeric, required) The fee value (in umrv) to add (or subtract, if negative).\n"
" The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
" considers the transaction as it would have paid a higher (or lower) fee.\n"
"\nResult\n"
"true (boolean) Returns true\n"
"\nExamples:\n" +
HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000") + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000"));
LOCK(cs_main);
uint256 hash = ParseHashStr(params[0].get_str(), "txid");
CAmount nAmount = params[2].get_int64();
mempool.PrioritiseTransaction(hash, params[0].get_str(), params[1].get_real(), nAmount);
return true;
}
// NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
static UniValue BIP22ValidationResult(const CValidationState& state)
{
if (state.IsValid())
return NullUniValue;
std::string strRejectReason = state.GetRejectReason();
if (state.IsError())
throw JSONRPCError(RPC_VERIFY_ERROR, strRejectReason);
if (state.IsInvalid()) {
if (strRejectReason.empty())
return "rejected";
return strRejectReason;
}
// Should be impossible
return "valid?";
}
UniValue getblocktemplate(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"getblocktemplate ( \"jsonrequestobject\" )\n"
"\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
"It returns data needed to construct a block to work on.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
"\nArguments:\n"
"1. \"jsonrequestobject\" (string, optional) A json object in the following spec\n"
" {\n"
" \"mode\":\"template\" (string, optional) This must be set to \"template\" or omitted\n"
" \"capabilities\":[ (array, optional) A list of strings\n"
" \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
" ,...\n"
" ]\n"
" }\n"
"\n"
"\nResult:\n"
"{\n"
" \"version\" : n, (numeric) The block version\n"
" \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
" \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
" {\n"
" \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
" \"hash\" : \"xxxx\", (string) hash/id encoded in little-endian hexadecimal\n"
" \"depends\" : [ (array) array of numbers \n"
" n (numeric) transactions before this one (by 1-based index in 'transactions' list) that must be present in the final block if this one is\n"
" ,...\n"
" ],\n"
" \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in umrv); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one\n"
" \"sigops\" : n, (numeric) total number of SigOps, as counted for purposes of block limits; if key is not present, sigop count is unknown and clients MUST NOT assume there aren't any\n"
" \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
" }\n"
" ,...\n"
" ],\n"
" \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
" \"flags\" : \"flags\" (string) \n"
" },\n"
" \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in umrv)\n"
" \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
" \"target\" : \"xxxx\", (string) The hash target\n"
" \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
" \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
" ,...\n"
" ],\n"
" \"noncerange\" : \"00000000ffffffff\", (string) A range of valid nonces\n"
" \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
" \"sizelimit\" : n, (numeric) limit of block size\n"
" \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
" \"bits\" : \"xxx\", (string) compressed target of next block\n"
" \"height\" : n (numeric) The height of the next block\n"
" \"payee\" : \"xxx\", (string) required payee for the next block\n"
" \"payee_amount\" : n, (numeric) required amount to pay\n"
" \"votes\" : [\n (array) show vote candidates\n"
" { ... } (json object) vote candidate\n"
" ,...\n"
" ],\n"
" \"enforce_masternode_payments\" : true|false (boolean) true, if masternode payments are enforced\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getblocktemplate", "") + HelpExampleRpc("getblocktemplate", ""));
LOCK(cs_main);
std::string strMode = "template";
UniValue lpval = NullUniValue;
if (params.size() > 0) {
const UniValue& oparam = params[0].get_obj();
const UniValue& modeval = find_value(oparam, "mode");
if (modeval.isStr())
strMode = modeval.get_str();
else if (modeval.isNull()) {
/* Do nothing */
} else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
lpval = find_value(oparam, "longpollid");
if (strMode == "proposal") {
const UniValue& dataval = find_value(oparam, "data");
if (!dataval.isStr())
throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
CBlock block;
if (!DecodeHexBlk(block, dataval.get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
uint256 hash = block.GetHash();
BlockMap::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end()) {
CBlockIndex* pindex = mi->second;
if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
return "duplicate";
if (pindex->nStatus & BLOCK_FAILED_MASK)
return "duplicate-invalid";
return "duplicate-inconclusive";
}
CBlockIndex* const pindexPrev = chainActive.Tip();
// TestBlockValidity only supports blocks built on the current Tip
if (block.hashPrevBlock != pindexPrev->GetBlockHash())
return "inconclusive-not-best-prevblk";
CValidationState state;
TestBlockValidity(state, block, pindexPrev, false, true);
return BIP22ValidationResult(state);
}
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "MRV Coin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "MRV Coin is downloading blocks...");
static unsigned int nTransactionsUpdatedLast;
if (!lpval.isNull()) {
// Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
uint256 hashWatchedChain;
std::chrono::steady_clock::time_point checktxtime;
unsigned int nTransactionsUpdatedLastLP;
if (lpval.isStr()) {
// Format: <hashBestChain><nTransactionsUpdatedLast>
std::string lpstr = lpval.get_str();
hashWatchedChain.SetHex(lpstr.substr(0, 64));
nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
} else {
// NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
hashWatchedChain = chainActive.Tip()->GetBlockHash();
nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
}
// Release the wallet and main lock while waiting
LEAVE_CRITICAL_SECTION(cs_main);
{
checktxtime = std::chrono::steady_clock::now() + std::chrono::minutes(1);
WAIT_LOCK(g_best_block_mutex, lock);
while (g_best_block == hashWatchedChain && IsRPCRunning()) {
if (g_best_block_cv.wait_until(lock, checktxtime) == std::cv_status::timeout)
{
// Timeout: Check transactions for update
if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
break;
checktxtime += std::chrono::seconds(10);
}
}
}
ENTER_CRITICAL_SECTION(cs_main);
if (!IsRPCRunning())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
// TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
}
// Update block
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != chainActive.Tip() ||
(mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5)) {
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the chainActive.Tip() used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrevNew = chainActive.Tip();
nStart = GetTime();
// Create new block
if (pblocktemplate) {
delete pblocktemplate;
pblocktemplate = NULL;
}
CScript scriptDummy = CScript() << OP_TRUE;
pblocktemplate = CreateNewBlock(scriptDummy, pwalletMain, false);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
UpdateTime(pblock, pindexPrev);
pblock->nNonce = 0;
UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
UniValue transactions(UniValue::VARR);
std::map<uint256, int64_t> setTxIndex;
int i = 0;
for (CTransaction& tx : pblock->vtx) {
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase())
continue;
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("data", EncodeHexTx(tx)));
entry.push_back(Pair("hash", txHash.GetHex()));
UniValue deps(UniValue::VARR);
for (const CTxIn& in : tx.vin) {
if (setTxIndex.count(in.prevout.hash))
deps.push_back(setTxIndex[in.prevout.hash]);
}
entry.push_back(Pair("depends", deps));
int index_in_template = i - 1;
entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
transactions.push_back(entry);
}
UniValue aux(UniValue::VOBJ);
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = uint256().SetCompact(pblock->nBits);
static UniValue aMutable(UniValue::VARR);
if (aMutable.empty()) {
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
UniValue aVotes(UniValue::VARR);
UniValue result(UniValue::VOBJ);
result.push_back(Pair("capabilities", aCaps));
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].GetValueOut()));
result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
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", pblock->GetBlockTime()));
result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight + 1)));
result.push_back(Pair("votes", aVotes));
if (pblock->payee != CScript()) {
CTxDestination address1;
ExtractDestination(pblock->payee, address1);
result.push_back(Pair("payee", EncodeDestination(address1).c_str()));
result.push_back(Pair("payee_amount", (int64_t)pblock->vtx[0].vout[1].nValue));
} else {
result.push_back(Pair("payee", ""));
result.push_back(Pair("payee_amount", ""));
}
result.push_back(Pair("enforce_masternode_payments", true));
return result;
}
class submitblock_StateCatcher : public CValidationInterface
{
public:
uint256 hash;
bool found;
CValidationState state;
submitblock_StateCatcher(const uint256& hashIn) : hash(hashIn), found(false), state(){};
protected:
virtual void BlockChecked(const CBlock& block, const CValidationState& stateIn)
{
if (block.GetHash() != hash)
return;
found = true;
state = stateIn;
};
};
UniValue submitblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"submitblock \"hexdata\" ( \"jsonparametersobject\" )\n"
"\nAttempts to submit new block to network.\n"
"The 'jsonparametersobject' parameter is currently ignored.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
"\nArguments\n"
"1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
"2. \"jsonparametersobject\" (string, optional) object of optional parameters\n"
" {\n"
" \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n"
" }\n"
"\nResult:\n"
"\nExamples:\n" +
HelpExampleCli("submitblock", "\"mydata\"") + HelpExampleRpc("submitblock", "\"mydata\""));
CBlock block;
if (!DecodeHexBlk(block, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
if (block.vtx.empty() || !block.vtx[0].IsCoinBase()) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
}
uint256 hash = block.GetHash();
bool fBlockPresent = false;
{
LOCK(cs_main);
BlockMap::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end()) {
CBlockIndex* pindex = mi->second;
if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
return "duplicate";
if (pindex->nStatus & BLOCK_FAILED_MASK)
return "duplicate-invalid";
// Otherwise, we might only have the header - process the block before returning
fBlockPresent = true;
}
}
CValidationState state;
submitblock_StateCatcher sc(block.GetHash());
RegisterValidationInterface(&sc);
bool fAccepted = ProcessNewBlock(state, NULL, &block);
UnregisterValidationInterface(&sc);
if (fBlockPresent) {
if (fAccepted && !sc.found)
return "duplicate-inconclusive";
return "duplicate";
}
if (fAccepted) {
if (!sc.found)
return "inconclusive";
state = sc.state;
}
return BIP22ValidationResult(state);
}
UniValue estimatefee(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"estimatefee nblocks\n"
"\nEstimates the approximate fee per kilobyte\n"
"needed for a transaction to begin confirmation\n"
"within nblocks blocks.\n"
"\nArguments:\n"
"1. nblocks (numeric)\n"
"\nResult:\n"
"n : (numeric) estimated fee-per-kilobyte\n"
"\n"
"-1.0 is returned if not enough transactions and\n"
"blocks have been observed to make an estimate.\n"
"\nExample:\n" +
HelpExampleCli("estimatefee", "6"));
RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));
int nBlocks = params[0].get_int();
if (nBlocks < 1)
nBlocks = 1;
CFeeRate feeRate = mempool.estimateFee(nBlocks);
if (feeRate == CFeeRate(0))
return -1.0;
return ValueFromAmount(feeRate.GetFeePerK());
}
UniValue estimatepriority(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"estimatepriority nblocks\n"
"\nEstimates the approximate priority\n"
"a zero-fee transaction needs to begin confirmation\n"
"within nblocks blocks.\n"
"\nArguments:\n"
"1. nblocks (numeric)\n"
"\nResult:\n"
"n : (numeric) estimated priority\n"
"\n"
"-1.0 is returned if not enough transactions and\n"
"blocks have been observed to make an estimate.\n"
"\nExample:\n" +
HelpExampleCli("estimatepriority", "6"));
RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));
int nBlocks = params[0].get_int();
if (nBlocks < 1)
nBlocks = 1;
return mempool.estimatePriority(nBlocks);
}
| [
"67336175+MRVofficial@users.noreply.github.com"
] | 67336175+MRVofficial@users.noreply.github.com |
d33cfb9334f06b307646bf6dc5982ab084f5713b | 9dff465a1f2e694f8e1c85234a390c6e636b6521 | /hw4/test.cpp | feb39343bb63cb66c0f6e415d03a6bf5aa5751f8 | [] | no_license | barisayyildiz/Oop_Homeworks | fc548391b2ba8e81e2e31a51d1a1678eb06481fc | e2447dc4f7c04faaaedbce7e9d13322cc63c0c19 | refs/heads/master | 2023-03-05T13:16:45.127824 | 2021-02-12T12:51:06 | 2021-02-12T12:51:06 | 338,314,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 449 | cpp | #include <iostream>
using namespace std;
class A
{
private:
int x;
public:
class B
{
private:
int y;
public:
explicit B(int s) : y(s)
{/*left empty*/}
inline int getY()const{return y;};
inline void setY(int s){y = s;};
};
B *ptr;
inline int getX()const{return x;};
explicit A(int s, int a) : x(s), ptr(nullptr)
{
ptr = new A::B[a];
for(int i=0; i<a; i++)
{
ptr.setY(i * 10);
}
}
};
int main()
{
return 0;
}
| [
"barisayyildiz.1799@gmail.com"
] | barisayyildiz.1799@gmail.com |
a3e8e75e9507a5db0e5524ac50b17be0b32a0b79 | 774b5efb4d4996612330651ef2aae4657b008bd5 | /petfera/animal/classes/reptil/reptil.cpp | f10d3926a6e2facb1047a57d8788d86220970519 | [] | no_license | r4m0nl1m4/petfera | 596217357dabfd86cca529e477d0e12508d3a486 | 7adcae969a4d01149a7f87799406c87834b1a346 | refs/heads/master | 2021-07-21T04:00:32.658475 | 2020-10-08T20:05:01 | 2020-10-08T20:05:01 | 220,350,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 997 | cpp |
//Main for "reptil" C++ application
//Created by r4m0nl1m4 e ggorg03 26/11/2019
//Cabeçalho
#include "./reptil.h"
// contrutores
Reptil::Reptil() : Animal() {
this->_venenoso = false;
this->_tipo_veneno = "-";
}
Reptil::Reptil(int id,
string nome_cienctifico,
char sexo,
double tamanho_cm,
string dieta,
int veterinario,
int tratador,
string nome_batismo,
bool venenoso,
string tipo_veneno)
: Animal(id,
nome_cienctifico,
sexo,
tamanho_cm,
dieta,
veterinario,
tratador,
nome_batismo)
{
this->_venenoso = venenoso;
this->_tipo_veneno = tipo_veneno;
}
// destrutor
Reptil::~Reptil() { /*Usaremos o destrutor padrão*/ }
// getters
string Reptil::get_reino() { return "Reptil"; }
string Reptil::get_especificidades(){ return to_string(this->_venenoso) + ";" + this->_tipo_veneno; } | [
"ramon.ccodes@gmail.com"
] | ramon.ccodes@gmail.com |
abbd7c2c8cb89cb36a1fefc432e833e420027434 | c9dd3f5c2783ac101310091f97a998a066fb2995 | /display.cpp | 1a11de588cb46dea536b1894936564714a349230 | [] | no_license | vphungsec/Data-Structure-And-Algorithms-Official | 42c2d74985542b8e00f02b4a888143817bebd05b | e1be23a1dd8c0ca847814a794293a443975156f6 | refs/heads/master | 2023-04-09T08:56:56.889367 | 2021-04-01T19:21:33 | 2021-04-01T19:21:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,552 | cpp | int menuDisplay() {
int x=70,y=20;
OBJECR_LCT diemxy;
diemxy.x = x-20;
diemxy.y = y-2;
makeTable_Color_Type2(diemxy,18,60,187,187);
while(true){
colorText(IDCOLOR_CLEARTEXT);
gotoxy(x,y);printf("%s","Mon Hoc");
gotoxy(x,y+2);printf("%s","Lop Hoc");
gotoxy(x,y+4);printf("%s","Sinh Vien");
gotoxy(x,y+6);printf("%s","Nhap cau hoi");//In Diem Thi Trac Nghiem
gotoxy(x,y+8);printf("%s","Hieu Chinh Cau Hoi Thi");//Cau Hoi Thi
gotoxy(x,y+10);printf("%s","Thi Thu");
gotoxy(x,y+12);printf("%s","Xem Chi Tiet Bai Thi Cua Sinh Vien");
gotoxy(x,y+14);printf("%s","Xem Diem Thi Cua Mot Lop");
char c;
int arrow = -1;
W: if(kbhit()){
c = getch();
if(c==80){
arrow++;
if(arrow>7)arrow = 0;
if(arrow==0){
gotoxy(x,y+14);printf("%s","Xem Diem Thi Cua Mot Lop");
colorText(160);
gotoxy(x,y);printf("%s","Mon Hoc");
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==1){
gotoxy(x,y);printf("%s","Mon Hoc");
colorText(160);
gotoxy(x,y+2);printf("%s","Lop Hoc");
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==2){
gotoxy(x,y+2);printf("%s","Lop Hoc");
colorText(160);
gotoxy(x,y+4);printf("%s","Sinh Vien");
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==3){
gotoxy(x,y+4);printf("%s","Sinh Vien");
colorText(160);
gotoxy(x,y+6);printf("%s","Nhap cau hoi");
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==4){
gotoxy(x,y+6);printf("%s","Nhap cau hoi");
colorText(160);
gotoxy(x,y+8);printf("%s","Hieu Chinh Cau Hoi Thi");
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==5){
gotoxy(x,y+8);printf("%s","Hieu Chinh Cau Hoi Thi");
colorText(160);
gotoxy(x,y+10);printf("%s","Thi Thu");
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==6){
colorText(IDCOLOR_CLEARTEXT);
gotoxy(x,y+10);printf("%s","Thi Thu");
colorText(160);
gotoxy(x,y+12);printf("%s","Xem Chi Tiet Bai Thi Cua Sinh Vien");
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==7){
colorText(IDCOLOR_CLEARTEXT);
gotoxy(x,y+12);printf("%s","Xem Chi Tiet Bai Thi Cua Sinh Vien");
colorText(160);
gotoxy(x,y+14);printf("%s","Xem Diem Thi Cua Mot Lop");
colorText(IDCOLOR_CLEARTEXT);
}
}
if(c==72){
arrow--;
if(arrow<0)arrow = 7;
if(arrow==0){
gotoxy(x,y+2);printf("%s","Lop Hoc");
colorText(160);
gotoxy(x,y);printf("%s","Mon Hoc");
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==1){
gotoxy(x,y+4);printf("%s","Sinh Vien");
colorText(160);
gotoxy(x,y+2);printf("%s","Lop Hoc");
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==2){
gotoxy(x,y+6);printf("%s","Nhap cau hoi");
colorText(160);
gotoxy(x,y+4);printf("%s","Sinh Vien");
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==3){
gotoxy(x,y+8);printf("%s","Hieu Chinh Cau Hoi Thi");
colorText(160);
gotoxy(x,y+6);printf("%s","Nhap cau hoi");
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==4){
gotoxy(x,y+10);printf("%s","Thi Thu");
colorText(160);
gotoxy(x,y+8);printf("%s","Hieu Chinh Cau Hoi Thi");
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==5){
gotoxy(x,y+12);printf("%s","Xem Chi Tiet Bai Thi Cua Sinh Vien");
colorText(160);
gotoxy(x,y+10);printf("%s","Thi Thu");
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==6){
colorText(IDCOLOR_CLEARTEXT);
gotoxy(x,y+14);printf("%s","Xem Diem Thi Cua Mot Lop");
colorText(160);
gotoxy(x,y+12);printf("%s","Xem Chi Tiet Bai Thi Cua Sinh Vien");
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==7){
colorText(IDCOLOR_CLEARTEXT);
gotoxy(x,y);printf("%s","Mon Hoc");
colorText(160);
gotoxy(x,y+14);printf("%s","Xem Diem Thi Cua Mot Lop");
colorText(IDCOLOR_CLEARTEXT);
}
}
if(c==27){
return -1;
}
if(c==13 &&arrow!=-1){
changeScene_type1(IDCOLOR_BACKGROUND);//238
return arrow;
}
}goto W;
}
}
int menuDisplayQuanLySinhVien() {
systemCls();
int x=70,y=20;
OBJECR_LCT diemxy;
diemxy.x = x-20;
diemxy.y = y-2;
makeTable_Color_Type2(diemxy,10,60,187,187);
while(true){
colorText(IDCOLOR_CLEARTEXT);
gotoxy(x,y);printf("Them Sinh Vien");
gotoxy(x,y+2);printf("Xoa Sinh Vien");
gotoxy(x,y+4);printf("Sua Thong Tin Sinh Vien");
gotoxy(x,y+6);printf("Tim Kiem Sinh Vien");
char c;
int arrow = -1;
W: if(kbhit()){
c=getch();
if(c==80){
arrow++;
if(arrow>3) arrow=0;
if(arrow==0){
gotoxy(x,y+6);printf("Tim Kiem Sinh Vien");
colorText(160);
gotoxy(x,y);printf("Them Sinh Vien");
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==1){
gotoxy(x,y);printf("Them Sinh Vien");
colorText(160);
gotoxy(x,y+2);printf("Xoa Sinh Vien");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==2){
gotoxy(x,y+2);printf("Xoa Sinh Vien");
colorText(160);
gotoxy(x,y+4);printf("Sua Thong Tin Sinh Vien");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==3){
gotoxy(x,y+4);printf("Sua Thong Tin Sinh Vien");
colorText(160);
gotoxy(x,y+6);printf("Tim Kiem Sinh Vien");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
}
if(c==72){
arrow--;
if(arrow<0) arrow=3;
if(arrow==0){
gotoxy(x,y+2);printf("Xoa Sinh Vien");
colorText(160);
gotoxy(x,y);printf("Them Sinh Vien");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==1){
gotoxy(x,y+4);printf("Sua Thong Tin Sinh Vien");
colorText(160);
gotoxy(x,y+2);printf("Xoa Sinh Vien");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==2){
gotoxy(x,y+6);printf("Tim Kiem Sinh Vien");
colorText(160);
gotoxy(x,y+4);printf("Sua Thong Tin Sinh Vien");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==3){
gotoxy(x,y);printf("Them Sinh Vien");
colorText(160);
gotoxy(x,y+6);printf("Tim Kiem Sinh Vien");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
}
if(c==27) return -1;
if(c==13&&arrow!=-1){
changeScene_type1(IDCOLOR_BACKGROUND);//238
return arrow;
}
} goto W;
}
}
int menuDisplayQuanLyCauHoi(){
systemCls();
int x=70,y=20;
OBJECR_LCT diemxy;
diemxy.x = x-18;
diemxy.y = y-2;
makeTable_Color_Type2(diemxy,10,60,187,187);
while(true){
colorText(IDCOLOR_CLEARTEXT);
gotoxy(x,y);printf("Nhap Cau Hoi");
gotoxy(x,y+2);printf("Xoa Cau Hoi");
gotoxy(x,y+4);printf("Chinh Sua Noi Dung Cau Hoi");
gotoxy(x,y+6);printf("In Danh Sach Cau Hoi Theo Mon");
char c;
int arrow = -1;
W: if(kbhit()){
c=getch();
if(c==80){
arrow++;
if(arrow>3) arrow=0;
if(arrow==0){
gotoxy(x,y+6);printf("In Danh Sach Cau Hoi Theo Mon");
colorText(160);
gotoxy(x,y);printf("Nhap Cau Hoi");
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==1){
gotoxy(x,y);printf("Nhap Cau Hoi");
colorText(160);
gotoxy(x,y+2);printf("Xoa Cau Hoi");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==2){
gotoxy(x,y+2);printf("Xoa Cau Hoi");
colorText(160);
gotoxy(x,y+4);printf("Chinh Sua Noi Dung Cau Hoi");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==3){
gotoxy(x,y+4);printf("Chinh Sua Noi Dung Cau Hoi");
colorText(160);
gotoxy(x,y+6);printf("In Danh Sach Cau Hoi Theo Mon");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
}
if(c==72){
arrow--;
if(arrow<0) arrow=3;
if(arrow==0){
gotoxy(x,y+2);printf("Xoa Cau Hoi");
colorText(160);
gotoxy(x,y);printf("Nhap Cau Hoi");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==1){
gotoxy(x,y+4);printf("Chinh Sua Noi Dung Cau Hoi");
colorText(160);
gotoxy(x,y+2);printf("Xoa Cau Hoi");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==2){
gotoxy(x,y+6);printf("In Danh Sach Cau Hoi Theo Mon");
colorText(160);
gotoxy(x,y+4);printf("Chinh Sua Noi Dung Cau Hoi");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==3){
gotoxy(x,y);printf("Nhap Cau Hoi");
colorText(160);
gotoxy(x,y+6);printf("In Danh Sach Cau Hoi Theo Mon");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
}
if(c==27) return -1;
if(c==13&&arrow!=-1){
changeScene_type1(IDCOLOR_BACKGROUND);//238
return arrow;
}
} goto W;
}
}
//int menuDisplayQuanLyLop() {
// systemCls();
// int x=70,y=20;
// OBJECR_LCT diemxy;
// diemxy.x = x-20;
// diemxy.y = y-2;
// makeTable_Color_Type2(diemxy,12,60,187,187);
// while(true){
// colorText(IDCOLOR_CLEARTEXT);
// gotoxy(x,y);printf("%s","Xem Lop Theo Nien Khoa");
// gotoxy(x,y+2);printf("%s","Them Lop Moi");
// gotoxy(x,y+4);printf("%s","Chinh Sua Thong Tin Lop Hoc");
// gotoxy(x,y+6);printf("%s","Xoa Lop Hoc");
// gotoxy(x,y+8);printf("%s","Tra Cuu Lop Hoc");
// char c;
// int arrow = -1;
//W: if(kbhit()){
// c = getch();
// if(c==80){
// arrow++;
// if(arrow>4)arrow = 0;
// if(arrow==0){
//
// gotoxy(x,y+8);printf("%s","Tra Cuu Lop Hoc");
// colorText(160);
// gotoxy(x,y);printf("%s","Xem Lop Theo Nien Khoa");
//// whiteColor();
// colorText(IDCOLOR_CLEARTEXT);
// }
// if(arrow==1){
//
// gotoxy(x,y);printf("%s","Xem Lop Theo Nien Khoa");
// colorText(160);
// gotoxy(x,y+2);printf("%s","Them Lop Moi");
// whiteColor();colorText(IDCOLOR_CLEARTEXT);
// }
// if(arrow==2){
//
// gotoxy(x,y+2);printf("%s","Them Lop Moi");
// colorText(160);
// gotoxy(x,y+4);printf("%s","Chinh Sua Thong Tin Lop Hoc");
// whiteColor();colorText(IDCOLOR_CLEARTEXT);
// }
// if(arrow==3){
//
// gotoxy(x,y+4);printf("%s","Chinh Sua Thong Tin Lop Hoc");
// colorText(160);
// gotoxy(x,y+6);printf("%s","Xoa Lop Hoc");
// whiteColor();colorText(IDCOLOR_CLEARTEXT);
// }
// if(arrow==4){
// gotoxy(x,y+6);printf("%s","Xoa Lop Hoc");
// colorText(160);
// gotoxy(x,y+8);printf("%s","Tra Cuu Lop Hoc");
// whiteColor();colorText(IDCOLOR_CLEARTEXT);
// }
// }
// if(c==72){
// arrow--;
// if(arrow<0)arrow = 4;
//
// if(arrow==0){
//
// gotoxy(x,y+2);printf("%s","Them Lop Moi");
// colorText(160);
// gotoxy(x,y);printf("%s","Xem Lop Theo Nien Khoa");
// whiteColor();colorText(IDCOLOR_CLEARTEXT);
// }
// if(arrow==1){
//
// gotoxy(x,y+4);printf("%s","Chinh Sua Thong Tin Lop Hoc");
// colorText(160);
// gotoxy(x,y+2);printf("%s","Them Lop Moi");
// whiteColor();colorText(IDCOLOR_CLEARTEXT);
// }
// if(arrow==2){
//
// gotoxy(x,y+6);printf("%s","Xoa Lop Hoc");
// colorText(160);
// gotoxy(x,y+4);printf("%s","Chinh Sua Thong Tin Lop Hoc");
// whiteColor();colorText(IDCOLOR_CLEARTEXT);
// }
// if(arrow==3){
//
// gotoxy(x,y+8);printf("%s","Tra Cuu Lop Hoc");
// colorText(160);
// gotoxy(x,y+6);printf("%s","Xoa Lop Hoc");
// whiteColor();colorText(IDCOLOR_CLEARTEXT);
// }
// if(arrow==4){
// gotoxy(x,y);printf("%s","Xem Lop Theo Nien Khoa");
// colorText(160);
// gotoxy(x,y+8);printf("%s","Tra Cuu Lop Hoc");
// whiteColor();colorText(IDCOLOR_CLEARTEXT);
// }
//
// }
//
// if(c==27){
//
// return -1;
// }
// if(c==13 &&arrow!=-1){
// changeScene_type1(IDCOLOR_BACKGROUND);//238
// return arrow;
//
//
// }
//
// }goto W;
//
// }
//}
int menuDisplayQuanLyLop() {
systemCls();
int x=70,y=20;
OBJECR_LCT diemxy;
diemxy.x = x-20;
diemxy.y = y-2;
makeTable_Color_Type2(diemxy,12,60,187,187);
while(true){
colorText(IDCOLOR_CLEARTEXT);
gotoxy(x,y+4);printf("%s","Xem Lop Theo Nien Khoa");
gotoxy(x,y+2);printf("%s","Danh sach lop");
char c;
int arrow = -1;
W: if(kbhit()){
c = getch();
if(c==80){
arrow++;
if(arrow>1)arrow = 0;
if(arrow==0){
gotoxy(x,y+2);printf("%s","Danh sach lop");
colorText(160);
gotoxy(x,y+4);printf("%s","Xem Lop Theo Nien Khoa");
// whiteColor();
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==1){
gotoxy(x,y+4);printf("%s","Xem Lop Theo Nien Khoa");
colorText(160);
gotoxy(x,y+2);printf("%s","Danh sach lop");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
}
if(c==72){
arrow--;
if(arrow<0)arrow = 1;
if(arrow==0){
gotoxy(x,y+2);printf("%s","Danh sach lop");
colorText(160);
gotoxy(x,y+4);printf("%s","Xem Lop Theo Nien Khoa");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==1){
gotoxy(x,y+4);printf("%s","Xem Lop Theo Nien Khoa");
colorText(160);
gotoxy(x,y+2);printf("%s","Danh sach lop");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
}
if(c==27){
return -1;
}
if(c==13 &&arrow!=-1){
changeScene_type1(IDCOLOR_BACKGROUND);//238
return arrow;
}
}goto W;
}
}
int menuDisplayQuanLyMonHoc() {
systemCls();
int x=70,y=20;
OBJECR_LCT diemxy;
diemxy.x = x-20;
diemxy.y = y-2;
makeTable_Color_Type2(diemxy,12,60,187,187);
while(true){
colorText(IDCOLOR_CLEARTEXT);
gotoxy(x,y);printf("%s","Xem Chi Tiet Mon Hoc");
gotoxy(x,y+2);printf("%s","Them mon hoc");
gotoxy(x,y+4);printf("%s","Chinh sua mon hoc");
gotoxy(x,y+6);printf("%s","Xoa mon hoc");
gotoxy(x,y+8);printf("%s","Tra Cuu Mon Hoc");
char c;
int arrow = -1;
W: if(kbhit()){
c = getch();
if(c==80){
arrow++;
if(arrow>4)arrow = 0;
if(arrow==0){
gotoxy(x,y+8);printf("%s","Tra Cuu Mon Hoc");
colorText(160);
gotoxy(x,y);printf("%s","Xem Chi Tiet Mon Hoc");
// whiteColor();
colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==1){
gotoxy(x,y);printf("%s","Xem Chi Tiet Mon Hoc");
colorText(160);
gotoxy(x,y+2);printf("%s","Them mon hoc");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==2){
gotoxy(x,y+2);printf("%s","Them mon hoc");
colorText(160);
gotoxy(x,y+4);printf("%s","Chinh sua mon hoc");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==3){
gotoxy(x,y+4);printf("%s","Chinh sua mon hoc");
colorText(160);
gotoxy(x,y+6);printf("%s","Xoa mon hoc");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==4){
gotoxy(x,y+6);printf("%s","Xoa mon hoc");
colorText(160);
gotoxy(x,y+8);printf("%s","Tra Cuu Mon Hoc");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
}
if(c==72){
arrow--;
if(arrow<0)arrow = 4;
if(arrow==0){
gotoxy(x,y+2);printf("%s","Them mon hoc");
colorText(160);
gotoxy(x,y);printf("%s","Xem Chi Tiet Mon Hoc");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==1){
gotoxy(x,y+4);printf("%s","Chinh sua mon hoc");
colorText(160);
gotoxy(x,y+2);printf("%s","Them mon hoc");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==2){
gotoxy(x,y+6);printf("%s","Xoa mon hoc");
colorText(160);
gotoxy(x,y+4);printf("%s","Chinh sua mon hoc");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==3){
gotoxy(x,y+8);printf("%s","Tra Cuu Mon Hoc");
colorText(160);
gotoxy(x,y+6);printf("%s","Xoa mon hoc");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
if(arrow==4){
gotoxy(x,y);printf("%s","Xem Chi Tiet Mon Hoc");
colorText(160);
gotoxy(x,y+8);printf("%s","Tra Cuu Mon Hoc");
whiteColor();colorText(IDCOLOR_CLEARTEXT);
}
}
if(c==27){
return -1;
}
if(c==13 &&arrow!=-1){
changeScene_type1(IDCOLOR_BACKGROUND);//238
return arrow;
}
}goto W;
}
}
//---------------------------------------- menu
int menuQuanLyLop(DSLOP *dslop) {
int choise;
MENU:
choise = menuDisplayQuanLyLop();
//nhan insert
switch(choise) {
case 1:{
//nhap lop
Input_Class(dslop);
goto MENU;
}
case 0:{//tra cuu
inDSLop(dslop);
goto MENU;
}
case -1:{
break;
}
}
return 1;
}
int menuQuanLyMonHoc(DSMON *dsmon) {
int choise;
MENU: systemCls();
choise = menuDisplayQuanLyMonHoc();
switch(choise) {
case 1:{
//Xu ly Them Mon Hoc
goto MENU;
}
case 3:{
//Xu ly Xoa Mon Hoc
goto MENU;
}
case 2:{
//Xu ly Hieu chinh Mon Hoc
goto MENU;
}
case 0:{
//xem danh sach mon
break;
}
case 4:{
//tra cuu
break;
}
case -1:{
break;
}
}
return 1;
}
int menuQuanLySinhVien(DSLOP *dslop){
int choice;
MENU:
systemCls();
choice = menuDisplayQuanLySinhVien();
switch(choice){
case 0:{
Input_SV(dslop);
goto MENU;
}
case 1:{
// Delete_SV(dslop);
goto MENU;
}
case 2:{
// Edit_SV(dslop);
goto MENU;
}
case 3:{
// Search_SV(dslop);
goto MENU;
}
default: break;
}
return 1;
}
int menuQuanLyCauHoi(NODECAUHOI dscauhoi, DSMON *dsmon){
int choice;
MENU:
systemCls();
choice = menuDisplayQuanLyCauHoi();
switch(choice){
case 0:{
Input_CH(dscauhoi,dsmon);
goto MENU;
}
case 1:{
// Delete_CH(dscauhoi,dsmon);
goto MENU;
}
case 2:{
// Edit_CH(dscauhoi,dsmon);
goto MENU;
}
case 3:{
// Search_CH(dscauhoi,dsmon);
goto MENU;
}
default: break;
}
return 1;
}
int loginDisplay() {
short int x=100;
short int y=26;
char username[] = "";
char password[] = "";
systemCls();
gotoxy(x,y);
printf("Nhap username: ");
gotoxy(x,y+1);
printf("Nhap password: ");
gotoxy(x+15,y);
scanf("%s",&username);//fflush(stdin);
gotoxy(x+15,y+27);//fflush(stdin);
scanf("%s",&password);
return 1;//login thanh cong
}
int menu(DSLOP *dslop,DSMON *dsmon,NODECAUHOI dscauhoi) {
MENU: systemCls();
int choise;
choise = menuDisplay();
gotoxy(70+10,20+11);
if(choise==0){
//menuQuanLyMonHoc(dsmon);
Input_Mon(dsmon);
goto MENU;
}
if(choise==1){
menuQuanLyLop(dslop);
goto MENU;
}
if(choise==2){
// menuQuanLySinhVien(dslop);
Input_SV(dslop);
goto MENU;
}
if(choise==3){
//xu ly in diem thi trac nghiem
Input_CH(dscauhoi,dsmon);
goto MENU;
}
if(choise==4){
// systemCls();
showDSMon(dsmon,dscauhoi);
// menuQuanLyCauHoi(dscauhoi,dsmon);
goto MENU;
}
if(choise==5){
int index;
char notice[MAX] = " ";
userManual_DoExam();
THITIEP:
ACCOUNT account;
strcpy(account.tenDangNhap,"GV");
strcpy(account.password,"GV");
systemCls();
SM: index = bangMonThi(dsmon);
if(index<0){
display_GoodBye();
goto MENU;
}
if(ExistQuestion(dscauhoi,dsmon->mon[index]->mamh)==false){
strcpy(notice,"Mon nay hien tai chua co cau hoi thi.Vui long chon lai mon thi!!!");
dialog(85,0,notice);
goto SM;
}
else {
MON monThi;
strcpy(monThi.tenmh,dsmon->mon[index]->tenmh);
strcpy(monThi.mamh,dsmon->mon[index]->mamh);
moduleThiForTeacher(dslop,dscauhoi,"GV","GV","GV",monThi);
goto THITIEP;
}
goto MENU;
}
if(choise==6){
moduleDetailExam(dscauhoi,dsmon,dslop);
goto MENU;
}
if(choise==7){
showMarkOfClass(dslop,dsmon,dscauhoi);
goto MENU;
}
else{
Sleep(1000);
systemCls();
return 1;
}
}
void displayModuleDetailExam(int x,int y){
gotoxy(75,3);colorText(228);
printf("%s","XEM CHI TIET THI CUA SINH VIEN ");clearColor();
SINHVIEN sv;
NODESINHVIEN First; InitDSSV(First);
OBJECR_LCT diemxy;
diemxy.x = x+3+15+3;
diemxy.y = y+3;
makeTable_Color_Type2(diemxy,2,MAXDN+2,119,119);
colorText(IDCOLOR_CLEARTEXT);
gotoxy(x+3,y+4);printf("%s","Nhap ma sinh vien:");
}
| [
"hunghardley0199@gmail.com"
] | hunghardley0199@gmail.com |
a4d46738bee95979a1f17ed02d559461a4960e98 | d61d05748a59a1a73bbf3c39dd2c1a52d649d6e3 | /chromium/gpu/ipc/common/gpu_feature_info_struct_traits.cc | b11f7714d07bfddcc134f908e9d5a4da2498facc | [
"BSD-3-Clause"
] | permissive | Csineneo/Vivaldi | 4eaad20fc0ff306ca60b400cd5fad930a9082087 | d92465f71fb8e4345e27bd889532339204b26f1e | refs/heads/master | 2022-11-23T17:11:50.714160 | 2019-05-25T11:45:11 | 2019-05-25T11:45:11 | 144,489,531 | 5 | 4 | BSD-3-Clause | 2022-11-04T05:55:33 | 2018-08-12T18:04:37 | null | UTF-8 | C++ | false | false | 1,466 | cc | // Copyright 2018 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 "gpu/ipc/common/gpu_feature_info_struct_traits.h"
#include "build/build_config.h"
namespace mojo {
// static
bool StructTraits<gpu::mojom::GpuFeatureInfoDataView, gpu::GpuFeatureInfo>::
Read(gpu::mojom::GpuFeatureInfoDataView data, gpu::GpuFeatureInfo* out) {
std::vector<gpu::GpuFeatureStatus> info_status;
if (!data.ReadStatusValues(&info_status))
return false;
if (info_status.size() != gpu::NUMBER_OF_GPU_FEATURE_TYPES)
return false;
std::copy(info_status.begin(), info_status.end(), out->status_values);
return data.ReadEnabledGpuDriverBugWorkarounds(
&out->enabled_gpu_driver_bug_workarounds) &&
data.ReadDisabledExtensions(&out->disabled_extensions) &&
data.ReadDisabledWebglExtensions(&out->disabled_webgl_extensions) &&
data.ReadWebglPreferences(&out->webgl_preferences) &&
data.ReadAppliedGpuBlacklistEntries(
&out->applied_gpu_blacklist_entries) &&
gpu::GpuBlacklist::AreEntryIndicesValid(
out->applied_gpu_blacklist_entries) &&
data.ReadAppliedGpuDriverBugListEntries(
&out->applied_gpu_driver_bug_list_entries) &&
gpu::GpuDriverBugList::AreEntryIndicesValid(
out->applied_gpu_driver_bug_list_entries);
}
} // namespace mojo
| [
"tofu@rMBP.local"
] | tofu@rMBP.local |
b5f40f4aaa1bf48895974a811bc965c93b3b5778 | fb403458294f9ca4d0c7e5a8b1d7afcc92a5064f | /cpp/LogicalType.cpp | 1ed34e2cfdc3e7b229d1ed305138f2588644bd29 | [
"Apache-2.0"
] | permissive | TimeSeriesInsights/ParquetSharp | 297f923c5ad30d0d65c0488d368e1f999cba8200 | d0edafb2f9aded9c8407fc9369baea7a48440607 | refs/heads/master | 2020-12-05T16:49:16.325613 | 2020-07-20T11:03:47 | 2020-07-20T11:03:47 | 232,177,987 | 0 | 0 | Apache-2.0 | 2020-01-06T20:15:55 | 2020-01-06T20:15:54 | null | UTF-8 | C++ | false | false | 6,472 | cpp |
#include "cpp/ParquetSharpExport.h"
#include "CString.h"
#include "ExceptionInfo.h"
#include <parquet/types.h>
using namespace parquet;
extern "C"
{
PARQUETSHARP_EXPORT void LogicalType_Free(const std::shared_ptr<const LogicalType>* logical_type)
{
delete logical_type;
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_Type(const std::shared_ptr<const LogicalType>* logical_type, LogicalType::Type::type* type)
{
TRYCATCH(*type = (*logical_type)->type();)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_Equals(const std::shared_ptr<const LogicalType>* left, const std::shared_ptr<const LogicalType>* right, bool* equals)
{
TRYCATCH(*equals = (*left)->Equals(**right);)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_ToString(const std::shared_ptr<const LogicalType>* logical_type, const char** to_string)
{
TRYCATCH(*to_string = AllocateCString((*logical_type)->ToString());)
}
PARQUETSHARP_EXPORT void LogicalType_ToString_Free(const char* to_string)
{
FreeCString(to_string);
}
// Logical type constructors.
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_String(const std::shared_ptr<const LogicalType>** logical_type)
{
TRYCATCH(*logical_type = new std::shared_ptr<const LogicalType>(LogicalType::String());)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_Map(const std::shared_ptr<const LogicalType>** logical_type)
{
TRYCATCH(*logical_type = new std::shared_ptr<const LogicalType>(LogicalType::Map());)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_List(const std::shared_ptr<const LogicalType>** logical_type)
{
TRYCATCH(*logical_type = new std::shared_ptr<const LogicalType>(LogicalType::List());)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_Enum(const std::shared_ptr<const LogicalType>** logical_type)
{
TRYCATCH(*logical_type = new std::shared_ptr<const LogicalType>(LogicalType::Enum());)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_Decimal(const int32_t precision, const int32_t scale, const std::shared_ptr<const LogicalType>** logical_type)
{
TRYCATCH(*logical_type = new std::shared_ptr<const LogicalType>(LogicalType::Decimal(precision, scale));)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_Date(const std::shared_ptr<const LogicalType>** logical_type)
{
TRYCATCH(*logical_type = new std::shared_ptr<const LogicalType>(LogicalType::Date());)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_Time(const bool is_adjusted_to_utc, const LogicalType::TimeUnit::unit time_unit, const std::shared_ptr<const LogicalType>** logical_type)
{
TRYCATCH(*logical_type = new std::shared_ptr<const LogicalType>(LogicalType::Time(is_adjusted_to_utc, time_unit));)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_Timestamp(const bool is_adjusted_to_utc, const LogicalType::TimeUnit::unit time_unit, const std::shared_ptr<const LogicalType>** logical_type)
{
TRYCATCH(*logical_type = new std::shared_ptr<const LogicalType>(LogicalType::Timestamp(is_adjusted_to_utc, time_unit));)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_Interval(const std::shared_ptr<const LogicalType>** logical_type)
{
TRYCATCH(*logical_type = new std::shared_ptr<const LogicalType>(LogicalType::Interval());)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_Int(const int32_t bit_width, const bool is_signed, const std::shared_ptr<const LogicalType>** logical_type)
{
TRYCATCH(*logical_type = new std::shared_ptr<const LogicalType>(LogicalType::Int(bit_width, is_signed));)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_Null(const std::shared_ptr<const LogicalType>** logical_type)
{
TRYCATCH(*logical_type = new std::shared_ptr<const LogicalType>(LogicalType::Null());)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_JSON(const std::shared_ptr<const LogicalType>** logical_type)
{
TRYCATCH(*logical_type = new std::shared_ptr<const LogicalType>(LogicalType::JSON());)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_BSON(const std::shared_ptr<const LogicalType>** logical_type)
{
TRYCATCH(*logical_type = new std::shared_ptr<const LogicalType>(LogicalType::BSON());)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_UUID(const std::shared_ptr<const LogicalType>** logical_type)
{
TRYCATCH(*logical_type = new std::shared_ptr<const LogicalType>(LogicalType::UUID());)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_None(const std::shared_ptr<const LogicalType>** logical_type)
{
TRYCATCH(*logical_type = new std::shared_ptr<const LogicalType>(LogicalType::None());)
}
PARQUETSHARP_EXPORT ExceptionInfo* LogicalType_Unknown(const std::shared_ptr<const LogicalType>** logical_type)
{
TRYCATCH(*logical_type = new std::shared_ptr<const LogicalType>(LogicalType::Unknown());)
}
// Typed properties
PARQUETSHARP_EXPORT ExceptionInfo* DecimalLogicalType_Precision(const std::shared_ptr<const DecimalLogicalType>* logical_type, int32_t* precision)
{
TRYCATCH(*precision = (*logical_type)->precision();)
}
PARQUETSHARP_EXPORT ExceptionInfo* DecimalLogicalType_Scale(const std::shared_ptr<const DecimalLogicalType>* logical_type, int32_t* scale)
{
TRYCATCH(*scale = (*logical_type)->scale();)
}
PARQUETSHARP_EXPORT ExceptionInfo* TimeLogicalType_IsAdjustedToUtc(const std::shared_ptr<const TimeLogicalType>* logical_type, bool* is_adjusted_to_utc)
{
TRYCATCH(*is_adjusted_to_utc = (*logical_type)->is_adjusted_to_utc();)
}
PARQUETSHARP_EXPORT ExceptionInfo* TimeLogicalType_TimeUnit(const std::shared_ptr<const TimeLogicalType>* logical_type, LogicalType::TimeUnit::unit* time_unit)
{
TRYCATCH(*time_unit = (*logical_type)->time_unit();)
}
PARQUETSHARP_EXPORT ExceptionInfo* TimestampLogicalType_IsAdjustedToUtc(const std::shared_ptr<const TimestampLogicalType>* logical_type, bool* is_adjusted_to_utc)
{
TRYCATCH(*is_adjusted_to_utc = (*logical_type)->is_adjusted_to_utc();)
}
PARQUETSHARP_EXPORT ExceptionInfo* TimestampLogicalType_TimeUnit(const std::shared_ptr<const TimestampLogicalType>* logical_type, LogicalType::TimeUnit::unit* time_unit)
{
TRYCATCH(*time_unit = (*logical_type)->time_unit();)
}
PARQUETSHARP_EXPORT ExceptionInfo* IntLogicalType_BitWidth(const std::shared_ptr<const IntLogicalType>* logical_type, int32_t* bitWidth)
{
TRYCATCH(*bitWidth = (*logical_type)->bit_width();)
}
PARQUETSHARP_EXPORT ExceptionInfo* IntLogicalType_IsSigned(const std::shared_ptr<const IntLogicalType>* logical_type, bool* is_signed)
{
TRYCATCH(*is_signed = (*logical_type)->is_signed();)
}
}
| [
"noreply@github.com"
] | noreply@github.com |
8301169e54bf7037937f92bd1d8453ff36ee4382 | 0ebdd33aaac5191cae078a5cf89437dae99a5f5f | /GPU/GPUTracking/TPCClusterFinder/DecodeZS.h | 2a9092406102851a0ba1cab6731473787c52b7be | [] | no_license | MarekKowalski1504/AliRoot | 3a22fd2f1ac1405b7cf75e7db5d9f807291fa12f | 9886b426fac8d7b41bcb52c8760145636031bc4b | refs/heads/master | 2021-04-09T17:18:32.496413 | 2020-02-12T07:24:57 | 2020-02-12T07:27:50 | 125,853,828 | 0 | 0 | null | 2018-03-19T12:26:38 | 2018-03-19T12:26:38 | null | UTF-8 | C++ | false | false | 1,666 | h | //**************************************************************************\
//* This file is property of and copyright by the ALICE Project *\
//* ALICE Experiment at CERN, All rights reserved. *\
//* *\
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *\
//* for The ALICE HLT Project. *\
//* *\
//* Permission to use, copy, modify and distribute this software and its *\
//* documentation strictly for non-commercial purposes is hereby granted *\
//* without fee, provided that the above copyright notice appears in all *\
//* copies and that both the copyright notice and this permission notice *\
//* appear in the supporting documentation. The authors make no claims *\
//* about the suitability of this software for any purpose. It is *\
//* provided "as is" without express or implied warranty. *\
//**************************************************************************
/// \file DecodeZS.h
/// \author David Rohr
#ifndef O2_GPU_DECODE_ZS_H
#define O2_GPU_DECODE_ZS_H
#include "clusterFinderDefs.h"
#include "GPUTPCClusterFinderKernels.h"
namespace GPUCA_NAMESPACE
{
namespace gpu
{
class GPUTPCClusterFinder;
class DecodeZS
{
public:
static GPUd() void decode(GPUTPCClusterFinder& clusterer, GPUTPCClusterFinderKernels::GPUTPCSharedMemory& s, int nBlocks, int nThreads, int iBlock, int iThread);
};
} // namespace gpu
} // namespace GPUCA_NAMESPACE
#endif
| [
"noreply@github.com"
] | noreply@github.com |
86cd10af0ba098f834cfac7dc0fcabc05513dd8a | f9252139df903b0fe566d555c07562a95ce08784 | /ll/_LL_variations.md.cpp | e43ebaa1465ad5f2dacfc83b915d247b4771921c | [] | no_license | dthinkcs/cpp_dsalgo | 0f4326035dc3c3ff0916db7825a48bc8140125ee | d563a5d64884bd25a6bf2c27cc0726b6f8958bf1 | refs/heads/master | 2021-04-06T19:58:26.349318 | 2019-06-19T18:23:22 | 2019-06-19T18:23:22 | 125,250,550 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,596 | cpp | // insertHead
// LL
Node* insertHead(Node* head, int item)
{
Node* newptr = new Node(item);
newptr->next = head; // L1
head = newptr; // L2
return head;
}
// LL (cicular::this) 2 edge cases NULL, []->
Node* insertHead(Node* head, int item)
{
Node* newptr = new Node(item);
if (head == NULL)
head = newptr;
else {
// find ptr_tail
for (ptr = head; ptr->next != head; ptr = ptr->next);
newptr->next = ptr->next;
ptr->next = newptr;
head = newptr; // same as ptr->next ONLY DIFF
}
return head;
}
// DLL
DNode* insertHead(DNode* head, int item)
{
DNode* head = new DNode(item);
newptr->next = head;
newptr->prev = NULL; // L3
if (newptr->next) // L4
newptr->next->prev = newptr;
head = newptr;
return head;
}
// DLL (circular: this this)
DNode* insertHead(DNode* head, int item)
{
DNode* newptr = new DNode(item);
if (head == NULL)
{
head = newptr;
}
else
{
DNode* ptr = head->prev; // ptr_tail
newptr->next = ptr->next;
newptr->prev = ptr;
if (newptr->next)
newptr->next->prev = newptr;
ptr->next = newptr;
head = newptr; // ONLY DIFF(in circular)
}
return head;
}
// LL
Node* deleteHead(Node* head)
{
if (head == NULL)
return NULL;
else if (head->next == NULL)
{
delete head;
}
return head;
}
// LL
Node* deleteHead(Node* head)
{
if (head == NULL)
return NULL;
else
{
Node* tmp = head;
head = tmp->next;
delete tmp;
}
return head;
}
// LL (cicular:this)
Node* deleteHead(Node* head)
{
if (head == NULL)
return NULL;
else if (head->next == head)
{
delete head;
return NULL;
}
else
{
// find tail
Node* ptr;
for (ptr = head; ptr->next != head; ptr = ptr->next);
Node* tmp = ptr->next;
ptr->next = tmp->next;
delete tmp;
head = ptr->next;
}
return head;
}
// DLL
DNode* deleteHead(Node* head)
{
if (head == NULL)
return NULL;
else (head->next == NULL)
{
delete head;
return NULL;
}
else
{
DNode* tmp = head;
head = head->next;
delete tmp;
if (head)
head->prev = NULL;
}
return head;
}
// DLL Circular
DNode* deleteHead(Node* head)
{
if (head == NULL)
return NULL ;
else if (head->next == head)
{
delete head;
return NULL;
}
else
{
ptr = head->prev; // tail
DNode* tmp = ptr->next;
ptr->next = ptr->next->next;
delete tmp;
if (ptr->next)
ptr->next->prev = ptr;
head = ptr->next;
}
return head;
}
| [
"noreply@github.com"
] | noreply@github.com |
382be9560c1f615fb09dcdad3d23ffd2c5490fe0 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/mutt/gumtree/mutt_repos_function_774_mutt-1.7.2.cpp | 183d046dcbbdd607b37bcb2dfc668db241819914 | [] | 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 | 1,340 | cpp | void mutt_sasl_setup_conn (CONNECTION* conn, sasl_conn_t* saslconn)
{
SASL_DATA* sasldata = (SASL_DATA*) safe_malloc (sizeof (SASL_DATA));
/* work around sasl_getprop aliasing issues */
const void* tmp;
sasldata->saslconn = saslconn;
/* get ssf so we know whether we have to (en|de)code read/write */
sasl_getprop (saslconn, SASL_SSF, &tmp);
sasldata->ssf = tmp;
dprint (3, (debugfile, "SASL protection strength: %u\n", *sasldata->ssf));
/* Add SASL SSF to transport SSF */
conn->ssf += *sasldata->ssf;
sasl_getprop (saslconn, SASL_MAXOUTBUF, &tmp);
sasldata->pbufsize = tmp;
dprint (3, (debugfile, "SASL protection buffer size: %u\n", *sasldata->pbufsize));
/* clear input buffer */
sasldata->buf = NULL;
sasldata->bpos = 0;
sasldata->blen = 0;
/* preserve old functions */
sasldata->sockdata = conn->sockdata;
sasldata->msasl_open = conn->conn_open;
sasldata->msasl_close = conn->conn_close;
sasldata->msasl_read = conn->conn_read;
sasldata->msasl_write = conn->conn_write;
sasldata->msasl_poll = conn->conn_poll;
/* and set up new functions */
conn->sockdata = sasldata;
conn->conn_open = mutt_sasl_conn_open;
conn->conn_close = mutt_sasl_conn_close;
conn->conn_read = mutt_sasl_conn_read;
conn->conn_write = mutt_sasl_conn_write;
conn->conn_poll = mutt_sasl_conn_poll;
} | [
"993273596@qq.com"
] | 993273596@qq.com |
878d15eda99e08c05d87275a17921533eb6db8e4 | 5bdd20ae77d6d6c05bb16437deac91eec6aeb56c | /weapon.cpp | 68aa5b50b22b2ec690829496b4eab814fa98fb0d | [] | no_license | Zelgunn/StarSkweek | 710864d89f0e4aa02ca3000c620901e597de65da | 56325942509987cc984f2382151ca565c7600c80 | refs/heads/master | 2021-06-25T21:56:56.928772 | 2017-09-14T13:47:30 | 2017-09-14T13:47:30 | 44,091,543 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 955 | cpp | #include "weapon.h"
Weapon::Weapon()
{
m_reloadTime = 500;
m_lastUse = QTime::currentTime();
m_ammunitionType = 0;
}
Weapon::Weapon(const QDomElement &element)
{
m_lastUse = QTime::currentTime();
QDomNode node = element.firstChild();
QDomElement elem;
while(!node.isNull())
{
elem = node.toElement();
if(elem.tagName() == "Spec")
{
m_reloadTime = elem.attribute("reload").toInt();
m_ammunitionType = elem.attribute("ammo").toLatin1().at(0) - 'a';
}
node = node.nextSibling();
}
}
int Weapon::ammunition() const
{
return m_ammunitionType;
}
void Weapon::setAmmunition(int ammunitionType)
{
m_ammunitionType = ammunitionType;
}
int Weapon::fire()
{
int type = -1;
if(m_lastUse.msecsTo(QTime::currentTime()) >= m_reloadTime)
{
m_lastUse = QTime::currentTime();
type = m_ammunitionType;
}
return type;
}
| [
"valentin.durand.de.g@gmail.com"
] | valentin.durand.de.g@gmail.com |
4b597ff7f83a900cf4a7c901207c0fe2744aa123 | d637287a81a4508b567b0660e354233c2c02b49f | /Huffman.h | 94b9b7cffcdb9b9f2ec11f875912c304bbe8ce62 | [] | no_license | SarahHasanien/Multimedia-Project-Second-Year-CMP | 3ba0bdcaa5412b7c696836c74cf0a9272579d1fd | bcf847038ba349c567a975baf53c7f203f93df16 | refs/heads/master | 2021-01-21T21:10:30.108661 | 2017-06-29T06:20:37 | 2017-06-29T06:20:37 | 92,316,820 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,159 | h | #pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
struct Symbol {
char value;
int frequency;//i should keep the frequency in this struct as i need it to calculate the probability of each symbol
float probability;
string code;
};
struct node {
char s;
float prob;
string code;
node* right;
node* left;
};
string ReadMessage(string file);
map<char, string> makeHuffmanTree(vector<Symbol>& v,node*& tree);
//void makeHuffmanTree(vector<Symbol>& v, int g);//this integer to know if i was decoding or encoding
void CalculateProbabilities(vector<Symbol>& symbols, string message);
void makeEncodedFile(map<char, string>m, string readFile, vector<Symbol> v, string fileName);
string HuffmanEncodemain(string file)//returns the name of the encoded file
{
//first read the file that has been encoded using RLE
string s1;
//1-read the text file we want to encode
s1 = ReadMessage(file);
//2-calculate frequency and probability for each symbol in the text file we read
//make the dictonary that will have frequency of each char/symbol in the text file we read
//or just make array of symbols that carry both prob and freq for each symbol or char in the text file we read,i can also try
//to store codeword in the symbol but i'm trying
vector<Symbol> symbols;
//after that calculate freq and prob of each char in the text file we read
CalculateProbabilities(symbols, s1);
node* HuffmanTree1;
map<char, string>HuffmanMam = makeHuffmanTree(symbols, HuffmanTree1);
//string newfile = "rle2.txt";
//makeEncodedFile(HuffmanMam, s1, symbols, newfile);
makeEncodedFile(HuffmanMam, s1, symbols, file); //use this line instead of the previous two lines when encoding on the original text file we take from the RLE
cout << "step 2: huffman encoding passed well " << endl;
return "rle2.txt";////delete this after testing
}
void CalculateProbabilities(vector<Symbol>& symbols, string message) {
//now we get each char and put it in the vector of symbols
float totalNoOfChar = message.size();
int i = 0;//to traverse the message
Symbol s;
while (i < totalNoOfChar)
{
float f = 0;//to count the no of redundancies of a certain char in message
s.value = message[i];
int sizeOfS = symbols.size();
bool flag = true;
if (sizeOfS > 0)
{
for (int k = 0; k < sizeOfS; k++)
{
if (symbols[k].value == s.value)
{
//loop the bigger loop again
k = sizeOfS;
flag = false;
}
}
}
if (flag)
{
int j = 0;//new index to search message to find no of redundancies of the char i have in s
while (j < totalNoOfChar)
{
if (s.value == message[j])f++;
j++;
}
s.frequency = f;
s.probability = f / totalNoOfChar;
symbols.push_back(s);
}
i++;
}
}
string ReadMessage(string file)
{
string s;
ifstream Ftxt;
Ftxt.open(file);
if (!Ftxt)
{
cout << "error opening the file" << endl;
}
while (!Ftxt.eof())
{
Ftxt >> s;
}
return s;
}
void makeCodeWord(node* t, string c, map<char, string>&m)
{
if (t->right != NULL)makeCodeWord(t->right, c + '1', m);
if (t->left != NULL)makeCodeWord(t->left, c + '0', m);
t->code = c;
m.insert(pair<char, string>(t->s, t->code));
return;
}
bool my_comp(node* a, node* b)
{
return a->prob > b->prob;
}
map<char, string> makeHuffmanTree(vector<Symbol>& v,node*& tree)
{
//first make the tree
int size1 = v.size();
vector<node*> v2;
for (int i = 0; i < size1; i++)
{
node* n = new node;
n->left = NULL;
n->right = NULL;
n->s = v[i].value;
n->prob = v[i].probability;
v2.push_back(n);
}
//sort the tree
sort(v2.begin(), v2.end(), my_comp);
//now working on the algorithm that generates the big tree
while (v2.size() != 2)
{
node* n = new node;
n->left = v2[size1 - 1];
n->right = v2[size1 - 2];
n->prob = v2[size1 - 1]->prob + v2[size1 - 2]->prob;
v2.pop_back();
v2.pop_back();
v2.push_back(n);
size1--;
sort(v2.begin(), v2.end(), my_comp);
}
//node* tree = new node;
tree = new node;
tree->right = v2[0];
tree->left = v2[1];
//second make codeword for leaves in the tree
map<char, string>m;
makeCodeWord(tree, "", m);
//third assign codewords made to the vector of symbols we have so that each symbol will contain its codeword
//assignCodeWord(v, m);//or return the map instead and in the main we can assign codeword to vector of symbols or just use this map to
//write the encoding for each char in the file we read
//assigning each codeword to its symbol in vector v
for (int i = 0; i < v.size(); i++)
v[i].code = m[v[i].value];
//the tree should be destructed before leaving this function
//using function destruct tree
return m;
}
//a function to make the decoded file using the my dictionary
void makeEncodedFile(map<char, string>m, string readFile, vector<Symbol> v, string fileName)
{
//make a file:
ofstream Stxt;
Stxt.open(fileName);
//i should first store my dictionary in the beginning of the encoded message using the vector of symbols
//i will put each symbol with its prob beside it and i will 2fsel between each two symbols using space
//after the last symbol i will send endl to the encoded file so that i begin to enter the encoded message
for (int i = 0; i < v.size(); i++)
{
Stxt << v[i].value << v[i].probability << ' ';
}
//send endl to the encoded file after sending the whole dictionary
Stxt << '\n';
//send the encoded message
for (int i = 0; i < readFile.size(); i++)
{
Stxt << m[readFile[i]];
}
Stxt.close();
}
//functions for decoding:
void makeSymbolsVector(vector<Symbol>& v, vector<string> s);
//function to read the encoded file:
//when reading the encoded file it will differ from reading the original file as the encoded file has endl at the end of the dictionary
//and when reading endl it means that now we will read our encoded text so now we are reading only zeros and ones not symbols with their probabilities
string ReadEncodedMes(string filename, vector<Symbol>& v)
{
//this function will be the main of the decoding but i am trying here in an external function so that don't make the main messy
string s1, encoded;
vector<string> s;
//open file
ifstream Ftxt;
Ftxt.open(filename);
if (!Ftxt)
{
cout << "error opening the file" << endl;
}
while (!Ftxt.eof())
{
Ftxt >> s1;
s.push_back(s1);
}
encoded = s[s.size() - 1];
s.pop_back();
//make the vector of symbols to make the tree of symbols after that
makeSymbolsVector(v, s);
return encoded;
}
void makeSymbolsVector(vector<Symbol>& v, vector<string> s)
{
for (int i = 0; i < s.size(); i++)
{
Symbol symbol;
string str;
str = s[i];
symbol.value = str[0];
str = str.substr(1);
symbol.probability = stof(str);
v.push_back(symbol);
}
}
string HuffmanDecodingmain(string filename)//it returns the name of the decoded file
{
vector<Symbol> symbols;
//string file = "rle2.txt";
//string encodedMessage = ReadEncodedMes(file, symbols);
string encodedMessage = ReadEncodedMes(filename, symbols);
node* HuffmanTree;
makeHuffmanTree(symbols, HuffmanTree);
//make the text file to write in :
ofstream Stxt;
//Stxt.open("rle3.txt");
Stxt.open(filename); //use this line instead of the previous line when decoding on the same text file we read
//put the decoded text in the text file rle3.txt
node* ptr = new node;
ptr = HuffmanTree;
int j = 0;
while (j<encodedMessage.size())
{
bool flag = true;
for (int i = j; flag; i++)
{
if (encodedMessage[i] == '0' && ptr->left != NULL)
ptr = ptr->left;
else if (encodedMessage[i] == '1' && ptr->right != NULL)
ptr = ptr->right;
else
{
flag = false;
Stxt << ptr->s;
ptr = HuffmanTree;
j--;
}
j++;
}
}
Stxt.close();
cout << "step 2 decoding: huffman decoding passed well" << endl;
return "rle3.txt";//////delete this after testing
} | [
"noreply@github.com"
] | noreply@github.com |
8976452007a8afc1d73053258ed3ca244d9753db | ebe1eaf68b4ebe941e564ecaf536a06d625e1eda | /Engine/src/ThirdParty/NIF/include/obj/NiPSysData.h | 0b0b347097280d9b13510f9a4379eb8495d883ab | [] | no_license | przemyslaw-szymanski/x-source-engine | 54a23e9ad740f7ab1b4a439f87733c366233eb58 | 1afa8c0dea628b6a252ee40aef39c31ec99d3c97 | refs/heads/master | 2020-12-24T15:41:01.851654 | 2015-08-07T14:37:12 | 2015-08-07T14:37:12 | 13,867,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,189 | h | /* Copyright (c) 2006, NIF File Format Library and Tools
All rights reserved. Please see niflib.h for license. */
//-----------------------------------NOTICE----------------------------------//
// Some of this file is automatically filled in by a Python script. Only //
// add custom code in the designated areas or it will be overwritten during //
// the next update. //
//-----------------------------------NOTICE----------------------------------//
#ifndef _NIPSYSDATA_H_
#define _NIPSYSDATA_H_
//--BEGIN FILE HEAD CUSTOM CODE--//
//--END CUSTOM CODE--//
#include "NiRotatingParticlesData.h"
namespace Niflib {
class NiPSysData;
typedef Ref<NiPSysData> NiPSysDataRef;
/*! Particle system data. */
class NiPSysData : public NiRotatingParticlesData {
public:
/*! Constructor */
NIFLIB_API NiPSysData();
/*! Destructor */
NIFLIB_API virtual ~NiPSysData();
/*!
* A constant value which uniquly identifies objects of this type.
*/
NIFLIB_API static const Type TYPE;
/*!
* A factory function used during file reading to create an instance of this type of object.
* \return A pointer to a newly allocated instance of this type of object.
*/
NIFLIB_API static NiObject * Create();
/*!
* Summarizes the information contained in this object in English.
* \param[in] verbose Determines whether or not detailed information about large areas of data will be printed out.
* \return A string containing a summary of the information within the object in English. This is the function that Niflyze calls to generate its analysis, so the output is the same.
*/
NIFLIB_API virtual string asString( bool verbose = false ) const;
/*!
* Used to determine the type of a particular instance of this object.
* \return The type constant for the actual type of the object.
*/
NIFLIB_API virtual const Type & GetType() const;
//--BEGIN MISC CUSTOM CODE--//
//--END CUSTOM CODE--//
protected:
/*! Unknown. */
vector< array<10,float > > unknownFloats2;
/*! Unknown. */
bool hasUnknownFloats3;
/*! Unknown */
vector<float > unknownFloats1;
/*! Unknown. */
bool hasUnknownFloats4;
/*! Unknown. */
vector< array<4,float > > unknownFloats4;
/*! Unknown. */
vector< array<7,float > > unknownFloats5;
/*! Unknown. */
bool hasUnknownFloats6;
/*! Unknown. */
vector<float > unknownFloats6;
/*! Unknown. */
unsigned int unknownInt1;
public:
/*! NIFLIB_HIDDEN function. For internal use only. */
NIFLIB_HIDDEN virtual void Read( istream& in, list<unsigned int> & link_stack, const NifInfo & info );
/*! NIFLIB_HIDDEN function. For internal use only. */
NIFLIB_HIDDEN virtual void Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, const NifInfo & info ) const;
/*! NIFLIB_HIDDEN function. For internal use only. */
NIFLIB_HIDDEN virtual void FixLinks( const map<unsigned int,NiObjectRef> & objects, list<unsigned int> & link_stack, const NifInfo & info );
/*! NIFLIB_HIDDEN function. For internal use only. */
NIFLIB_HIDDEN virtual list<NiObjectRef> GetRefs() const;
};
//--BEGIN FILE FOOT CUSTOM CODE--//
//--END CUSTOM CODE--//
} //End Niflib namespace
#endif
| [
"przemek.p.szymanski@gmail.com"
] | przemek.p.szymanski@gmail.com |
593e04415b397af6ab016f205ed896eaf105bb0b | e20bbb4b4916106700791f1f880e387bf52767c0 | /darwin/random.hpp | 5f56a05128a20da625847369403ecce3d09fa4c7 | [
"Apache-2.0"
] | permissive | mikecovlee/darwin | 8ac6b4184643b89ecfe3207c987079a01dd496a5 | 000bcfd31994be860a422fe2fb11dbced408da72 | refs/heads/master | 2020-06-10T17:04:06.987576 | 2019-10-28T15:37:46 | 2019-10-28T15:37:46 | 75,928,758 | 22 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 1,457 | hpp | #pragma once
/*
* Covariant Darwin Universal Character Graphics Library
*
* 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.
*
* Copyright (C) 2018 Michael Lee(李登淳)
* Email: mikecovlee@163.com
* Github: https://github.com/mikecovlee
*/
#include <type_traits>
#include <random>
#include <ctime>
namespace darwin {
namespace random {
static std::default_random_engine random_engine(time(nullptr));
template<typename T, bool is_integral>
struct random_traits;
template<typename T>
struct random_traits<T, true> {
static T rand(T begin, T end)
{
return std::uniform_int_distribution<T>(begin, end)(random_engine);
}
};
template<typename T>
struct random_traits<T, false> {
static T rand(T begin, T end)
{
return std::uniform_real_distribution<T>(begin, end)(random_engine);
}
};
}
template<typename T>
T rand(T begin, T end)
{
return random::random_traits<T, std::is_integral<T>::value>::rand(begin, end);
}
}
| [
"mikecovlee@163.com"
] | mikecovlee@163.com |
868ffab8a8a8c920335f5c74f79845e7b5cb7635 | 57ac85ca91d0f218be2a97e41ad7f8967728e7b9 | /blazetest/src/mathtest/dmatdmatmax/M3x3bM3x3a.cpp | de9a38d051b7e81863f060b7b2977da06be40790 | [
"BSD-3-Clause"
] | permissive | AuroraDysis/blaze | b297baa6c96b77c3d32de789e0e3af27782ced77 | d5cacf64e8059ca924eef4b4e2a74fc9446d71cb | refs/heads/master | 2021-01-01T16:49:28.921446 | 2017-07-22T23:24:26 | 2017-07-22T23:24:26 | 97,930,727 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,685 | cpp | //=================================================================================================
/*!
// \file src/mathtest/dmatdmatmax/M3x3bM3x3a.cpp
// \brief Source file for the M3x3bM3x3a dense matrix/dense matrix maximum math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/StaticMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatdmatmax/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'M3x3bM3x3a'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::StaticMatrix<TypeB,3UL,3UL> M3x3b;
typedef blaze::StaticMatrix<TypeA,3UL,3UL> M3x3a;
// Creator type definitions
typedef blazetest::Creator<M3x3b> CM3x3b;
typedef blazetest::Creator<M3x3a> CM3x3a;
// Running the tests
RUN_DMATDMATMAX_OPERATION_TEST( CM3x3b(), CM3x3a() );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix maximum:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
a6da444fa35010a3d2d2231bca8104ecaf70b6a7 | 1d67419ba117b46a88fa7a4dfeae4ca1f1d1d146 | /cpp-project/ch2q5/ch2q5/stdafx.cpp | cd4b1c0b28fcc24bd258b4a81b2ea9ad1a6d00e0 | [] | no_license | anjaligeril/hw | 9a34fae1019a63d994cee3bb7d9d9d21d53d8a0e | 2e2cee917c8608cfeb6ca6a77009e74142cd795a | refs/heads/master | 2020-03-23T08:32:30.901738 | 2018-10-12T20:36:37 | 2018-10-12T20:36:37 | 141,332,849 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 284 | cpp | // stdafx.cpp : source file that includes just the standard includes
// ch2q5.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"anjali99malu@gmail.com"
] | anjali99malu@gmail.com |
e781e59bf06412df07056a9d5d7860e7ec516d6e | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5669245564223488_0/C++/Ginzaner/b.cpp | 4d2b731b66d1377becd16f316ba7d54691f45541 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,289 | cpp | #include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
#define LL long long
const LL M = 1000000007;
char in[12000];
int m[30];
int l[30];
int r[30];
int f[30];
struct cart {
char st;
char en;
char lsen;
bool hmg;
};
int main() {
int T;
scanf("%d", &T);
for(int k = 1; k <= T; k++) {
printf("Case #%d: ", k);
LL pos = 1;
int N;
scanf("%d ", &N);
memset(in, 0, sizeof(in));
fgets(in, 12000, stdin);
vector<cart> cr;
memset(m, 0, sizeof(m));
memset(l, 0, sizeof(l));
memset(r, 0, sizeof(r));
memset(f, 0, sizeof(f));
int i = 0;
int p = 0;
cart c;
c.st = 0;
c.en = 0;
c.lsen = 0;
c.hmg = true;
while(i < N) {
if(in[p] <= 'z' && in[p] >= 'a') {
if(c.st == 0) {
c.st = in[p];
l[in[p]-'a']++;
} else {
if(in[p] != c.en) {
if(c.lsen != 0) {
m[c.en-'a']++;
}
c.lsen = c.en;
c.hmg = false;
}
}
c.en = in[p];
} else {
if(c.hmg) {
l[c.en-'a']--;
f[c.en-'a']++;
} else {
r[c.en-'a']++;
cr.push_back(c);
if(c.st == c.en) pos = 0;
}
c.st = 0;
c.lsen = 0;
c.hmg = true;
i++;
}
p++;
}
/*printf("pos == %lld\n", pos);
for(int i = 0; i < 26; i++) {
printf("%c: l %d, r %d, f %d, m %d\n", (char)(i+'a'), l[i], r[i], f[i], m[i]);
}*/
for(int i = 0; i < 26; i++) {
if(l[i] > 1) pos = 0;
if(r[i] > 1) pos = 0;
if(m[i] > 0 && (l[i]+r[i]+f[i]) > 0) pos = 0;
if(m[i] > 1) pos = 0;
}
if(pos == 0) {
printf("0\n");
continue;
}
int num = (int) cr.size();
for(int i = 0; i < (int) cr.size(); i++) {
if(r[cr[i].st-'a'] > 0) {
for(int j = 0; j < (int) cr.size(); j++) {
if(i == j) continue;
if(cr[j].en == cr[i].st) {
cr[j].en = cr[i].en;
cr[i].en = 0;
break;
}
}
num--;
}
}
for(int i = 0; i < (int) cr.size(); i++) {
if(cr[i].en == cr[i].st) {
pos = 0;
}
}
if(pos == 0) {
printf("0\n");
continue;
}
for(int i = 0; i < 26; i++) {
if(f[i] > 0 && l[i]+r[i] == 0) num++;
while(f[i] > 0) {
pos = (pos*f[i])%M;
f[i]--;
}
}
while(num > 0) {
pos = (pos*num)%M;
num--;
}
printf("%lld\n", pos);
}
return 0;
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
59cb81f20f6ea2e8a16468489678a81f1a93bc0a | 091c13c7e8eca71e0cb8554e7601378543a75556 | /Core/iterators.h | 1e0f03d48358313db391d05c9fc2218daec7f72e | [] | no_license | MartinAndu/ShapeAnalysis | 8085328f0a33323827554b14d230f13b34d87e0b | cf364d5cbac2dfeb4668cf94ef9bd331b2e1899b | refs/heads/master | 2020-12-30T19:38:06.817954 | 2012-10-09T08:53:39 | 2012-10-09T08:53:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,003 | h | #ifndef _MESHLIB_ITERATORS_H_
#define _MESHLIB_ITERATORS_H_
#include <iostream>
#include <map>
#include <math.h>
#include "Solid.h"
#include "avltree.h"
#include "TopologyException.h"
namespace MeshLib{
class Vertex;
class HalfEdge;
class Edge;
class Face;
class Solid;
//sequencial iterators
//v->out halfedge
class VertexOutHalfedgeIterator
{
public:
VertexOutHalfedgeIterator( Solid::tSolid solid, Solid::tVertex & v )
{ m_solid = solid; m_vertex = v; m_halfedge = solid->vertexMostClwOutHalfEdge(v); };
~VertexOutHalfedgeIterator(){};
void operator++()
{
if( m_halfedge == NULL ) throw TopologyException("iterators");
if( m_halfedge == m_solid->vertexMostCcwOutHalfEdge(m_vertex) )
m_halfedge = NULL;
else
m_halfedge = m_solid->vertexNextCcwOutHalfEdge(m_halfedge); };
Solid::tHalfEdge value() { return m_halfedge; };
bool end(){ return m_halfedge == NULL; };
Solid::tHalfEdge operator*() { return value(); };
private:
Solid::tSolid m_solid;
Solid::tVertex m_vertex;
Solid::tHalfEdge m_halfedge;
};
//v->in halfedge
class VertexInHalfedgeIterator
{
public:
VertexInHalfedgeIterator( Solid::tSolid solid, Solid::tVertex & v )
{ m_solid = solid; m_vertex = v; m_halfedge = solid->vertexMostClwInHalfEdge(v); };
~VertexInHalfedgeIterator(){};
void operator++()
{
if( m_halfedge == NULL ) throw TopologyException("iterators");
if( m_halfedge == m_solid->vertexMostCcwInHalfEdge(m_vertex) )
m_halfedge = NULL;
else
m_halfedge = m_solid->vertexNextCcwInHalfEdge(m_halfedge);
};
Solid::tHalfEdge value() { return m_halfedge; };
bool end(){ return m_halfedge == NULL; };
Solid::tHalfEdge operator*() { return value(); };
private:
Solid::tSolid m_solid;
Solid::tVertex m_vertex;
Solid::tHalfEdge m_halfedge;
};
//v -> v
class VertexVertexIterator
{
public:
VertexVertexIterator( Solid::tVertex v )
{
//std::cout<<"\r\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
m_vertex = v;
m_halfedge = m_vertex->most_clw_out_halfedge();
};
~VertexVertexIterator(){};
void operator++()
{
if( m_halfedge == NULL ) throw TopologyException("iterators");
if( !m_vertex->boundary() )
{
if( m_halfedge != m_vertex->most_ccw_out_halfedge() )
{
m_halfedge = m_halfedge->ccw_rotate_about_source();
}
else
{
m_halfedge = NULL;
}
return;
}
if( m_vertex->boundary() )
{
if( m_halfedge == m_vertex->most_ccw_in_halfedge() )
{
m_halfedge = NULL;
return;
}
HalfEdge * he = m_halfedge->ccw_rotate_about_source();
if( he == NULL )
{
m_halfedge = m_vertex->most_ccw_in_halfedge();
}
else
{
m_halfedge = he;
}
}
return;
};
Solid::tVertex value()
{
if( !m_vertex->boundary() )
{
return m_halfedge->target();
}
if( m_halfedge != m_vertex->most_ccw_in_halfedge() )
{
return m_halfedge->target();
}
if( m_halfedge == m_vertex->most_ccw_in_halfedge() )
{
return m_halfedge->source();
}
return NULL;
};
Solid::tVertex operator*() { return value(); };
bool end(){ return m_halfedge == NULL; };
void reset() { m_halfedge = m_vertex->most_clw_out_halfedge(); };
private:
Solid::tVertex m_vertex;
Solid::tHalfEdge m_halfedge;
};
//v -> edge
class VertexEdgeIterator
{
public:
VertexEdgeIterator( Solid::tVertex v )
{
m_vertex = v;
m_halfedge = m_vertex->most_clw_out_halfedge();
};
~VertexEdgeIterator(){};
void operator++()
{
if( m_halfedge == NULL ) throw TopologyException("iterators");;
if( !m_vertex->boundary() )
{
if( m_halfedge != m_vertex->most_ccw_out_halfedge() )
{
m_halfedge = m_halfedge->ccw_rotate_about_source();
}
else
{
m_halfedge = NULL;
}
return;
}
if( m_vertex->boundary() )
{
if( m_halfedge == m_vertex->most_ccw_in_halfedge() )
{
m_halfedge = NULL;
return;
}
HalfEdge * he = m_halfedge->ccw_rotate_about_source();
if( he == NULL )
{
m_halfedge = m_vertex->most_ccw_in_halfedge();
}
else
{
m_halfedge = he;
}
}
return;
};
Solid::tEdge value()
{
if( m_halfedge == NULL ) throw TopologyException("iterators");
return m_halfedge->edge();
};
Solid::tEdge operator*() { return value(); };
bool end(){ return m_halfedge == NULL; };
void reset() { m_halfedge = m_vertex->most_clw_out_halfedge(); };
private:
Solid::tVertex m_vertex;
Solid::tHalfEdge m_halfedge;
};
// v->face
class VertexFaceIterator
{
public:
VertexFaceIterator( Solid::tVertex & v )
{
m_vertex = v;
m_halfedge = m_vertex->most_clw_out_halfedge();
};
~VertexFaceIterator(){};
void operator++()
{
if( m_halfedge == NULL ) throw TopologyException("iterators");
if( m_halfedge == m_vertex->most_ccw_out_halfedge() )
{
m_halfedge = NULL;
return;
}
m_halfedge = m_halfedge->ccw_rotate_about_source();
};
Solid::tFace value() { return m_halfedge->face(); };
Solid::tFace operator*() { return value(); };
bool end(){ return m_halfedge == NULL; };
void reset() { m_halfedge = m_vertex->most_clw_out_halfedge(); };
private:
Solid::tVertex m_vertex;
Solid::tHalfEdge m_halfedge;
};
// f -> halfedge
class FaceHalfedgeIterator
{
public:
FaceHalfedgeIterator( Solid::tFace & f )
{
m_face = f;
m_halfedge = f->halfedge();
};
~FaceHalfedgeIterator(){};
void operator++()
{
if( m_halfedge == NULL ) throw TopologyException("iterators");
m_halfedge = m_halfedge->he_next();
if( m_halfedge == m_face->halfedge() )
{
m_halfedge = NULL;
return;
};
}
Solid::tHalfEdge value() { return m_halfedge; };
Solid::tHalfEdge operator*() { return value(); };
bool end(){ return m_halfedge == NULL; };
private:
Solid::tFace m_face;
Solid::tHalfEdge m_halfedge;
};
// f -> edge
class FaceEdgeIterator
{
public:
FaceEdgeIterator( Solid::tFace & f )
{
m_face = f;
m_halfedge = f->halfedge();
};
~FaceEdgeIterator(){};
void operator++()
{
if( m_halfedge == NULL ) throw TopologyException("iterators");
m_halfedge = m_halfedge->he_next();
if( m_halfedge == m_face->halfedge() )
{
m_halfedge = NULL;
return;
};
}
Solid::tEdge value() { return m_halfedge->edge(); };
Solid::tEdge operator*() { return value(); };
bool end(){ return m_halfedge == NULL; };
private:
Solid::tFace m_face;
Solid::tHalfEdge m_halfedge;
};
// f -> vertex
class FaceVertexIterator
{
public:
FaceVertexIterator( Solid::tFace & f )
{
m_face = f;
m_halfedge = f->halfedge();
};
~FaceVertexIterator(){};
void operator++()
{
if( m_halfedge == NULL ) throw TopologyException("iterators");
m_halfedge = m_halfedge->he_next();
if( m_halfedge == m_face->halfedge() )
{
m_halfedge = NULL;
return;
};
}
Solid::tVertex value() { return m_halfedge->target(); };
Solid::tVertex operator*() { return value(); };
bool end(){ return m_halfedge == NULL; };
private:
Solid::tFace m_face;
Solid::tHalfEdge m_halfedge;
};
// solid vertices
class SolidVertexIterator
{
public:
SolidVertexIterator( Solid::tSolid solid ): m_solid(solid), m_iter( solid->m_verts )
{
}
Solid::tVertex value() { return *m_iter; };
void operator++() { ++ m_iter; };
bool end() { return m_iter.end(); }
Solid::tVertex operator*(){ return value(); };
void reset() { m_iter.reset(); };
private:
Solid::tSolid m_solid;
AVL::TreeIterator<Vertex> m_iter;
};
// solid faces
class SolidFaceIterator
{
public:
SolidFaceIterator( Solid::tSolid solid ): m_solid(solid), m_iter( solid->m_faces )
{
}
Solid::tFace value() { return *m_iter; };
void operator++() { ++ m_iter; };
bool end() { return m_iter.end(); }
Solid::tFace operator*(){ return value(); };
void reset() { m_iter.reset(); };
private:
Solid::tSolid m_solid;
AVL::TreeIterator<Face> m_iter;
};
// solid edges
class SolidEdgeIterator
{
public:
SolidEdgeIterator( Solid::tSolid solid ): m_solid(solid), m_iter( solid->m_edges )
{
}
Solid::tEdge value() { return *m_iter; };
void operator++() { ++ m_iter; };
bool end() { return m_iter.end(); }
Solid::tEdge operator*(){ return value(); };
void reset() { m_iter.reset(); };
private:
Solid::tSolid m_solid;
AVL::TreeIterator<Edge> m_iter;
};
// solid halfedges
class SolidHalfEdgeIterator
{
public:
SolidHalfEdgeIterator( Solid::tSolid solid ): m_solid(solid), m_iter( solid->m_edges ), m_id(0)
{
}
Solid::tHalfEdge value() { Solid::tEdge e = *m_iter; return e->halfedge(m_id); };
void operator++()
{
++m_id;
switch( m_id )
{
case 1:
{
Solid::tEdge e = *m_iter;
if( e->halfedge(m_id) == NULL )
{
m_id = 0;
++ m_iter;
}
}
break;
case 2:
m_id = 0;
++m_iter;
break;
}
};
bool end() { return m_iter.end(); }
Solid::tHalfEdge operator*(){ return value(); };
void reset() { m_iter.reset(); m_id = 0; };
private:
Solid::tHalfEdge m_he;
Solid::tSolid m_solid;
AVL::TreeIterator<Edge> m_iter;
int m_id;
};
} //solid
#endif
| [
"lbrito@gmail.com"
] | lbrito@gmail.com |
fdc0eb3dcaa0556af8d2397b3b88f122b0e4cbf0 | a020afdfec6fb793aea234d17ac7db5259555920 | /shared/XrSceneLib/ControllerObject.cpp | 1857cac71008b951a5aa0dad2dc2bd6e75da6a55 | [
"LicenseRef-scancode-generic-cla",
"Zlib",
"MIT",
"Apache-2.0"
] | permissive | microsoft/OpenXR-MixedReality | 3c1d34aa1a5ab9f554ee8b7d094abb40c9180356 | 65f472305206d24846701a7496befb0c104e6cb2 | refs/heads/main | 2023-09-06T08:44:14.670903 | 2023-09-05T22:07:26 | 2023-09-05T22:07:26 | 182,194,793 | 262 | 92 | MIT | 2023-09-05T22:07:28 | 2019-04-19T03:23:00 | C++ | UTF-8 | C++ | false | false | 7,367 | cpp | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "pch.h"
#include <Pbr/GltfLoader.h>
#include <SampleShared/Trace.h>
#include "PbrModelObject.h"
#include "ControllerObject.h"
#include "Context.h"
using namespace DirectX;
using namespace std::literals::chrono_literals;
namespace {
struct ControllerModel {
XrControllerModelKeyMSFT Key = 0;
std::shared_ptr<Pbr::Model> PbrModel;
std::vector<Pbr::NodeIndex_t> NodeIndices;
std::vector<XrControllerModelNodePropertiesMSFT> NodeProperties;
std::vector<XrControllerModelNodeStateMSFT> NodeStates;
};
std::unique_ptr<ControllerModel> LoadControllerModel(engine::Context& context, XrControllerModelKeyMSFT modelKey) {
std::unique_ptr<ControllerModel> model = std::make_unique<ControllerModel>();
model->Key = modelKey;
// Load the controller model as GLTF binary stream using two call idiom
uint32_t bufferSize = 0;
CHECK_XRCMD(xrLoadControllerModelMSFT(context.Session.Handle, modelKey, 0, &bufferSize, nullptr));
if (bufferSize == 0) {
return nullptr;
}
auto modelBuffer = std::make_unique<byte[]>(bufferSize);
CHECK_XRCMD(
xrLoadControllerModelMSFT(context.Session.Handle, modelKey, bufferSize, &bufferSize, modelBuffer.get()));
model->PbrModel = Gltf::FromGltfBinary(context.PbrResources, modelBuffer.get(), bufferSize);
// Read the controller model properties with two call idiom
XrControllerModelPropertiesMSFT properties{XR_TYPE_CONTROLLER_MODEL_PROPERTIES_MSFT};
properties.nodeCapacityInput = 0;
CHECK_XRCMD(xrGetControllerModelPropertiesMSFT(context.Session.Handle, modelKey, &properties));
model->NodeProperties.resize(properties.nodeCountOutput, {XR_TYPE_CONTROLLER_MODEL_NODE_PROPERTIES_MSFT});
properties.nodeProperties = model->NodeProperties.data();
properties.nodeCapacityInput = static_cast<uint32_t>(model->NodeProperties.size());
CHECK_XRCMD(xrGetControllerModelPropertiesMSFT(context.Session.Handle, modelKey, &properties));
// Compute the index of each node reported by runtime to be animated.
// The order of m_nodeIndices exactly matches the order of the nodes properties and states.
model->NodeIndices.resize(model->NodeProperties.size(), Pbr::NodeIndex_npos);
for (size_t i = 0; i < model->NodeProperties.size(); ++i) {
const auto& nodeProperty = model->NodeProperties[i];
const std::string_view parentNodeName = nodeProperty.parentNodeName;
if (const auto parentNodeIndex = model->PbrModel->FindFirstNode(parentNodeName)) {
if (const auto targetNodeIndex = model->PbrModel->FindFirstNode(nodeProperty.nodeName, *parentNodeIndex)) {
model->NodeIndices[i] = *targetNodeIndex;
}
}
}
return model;
}
// Update transforms of nodes for the animatable parts in the controller model
void UpdateControllerParts(engine::Context& context, ControllerModel& model) {
XrControllerModelStateMSFT modelState{XR_TYPE_CONTROLLER_MODEL_STATE_MSFT};
modelState.nodeCapacityInput = 0;
CHECK_XRCMD(xrGetControllerModelStateMSFT(context.Session.Handle, model.Key, &modelState));
model.NodeStates.resize(modelState.nodeCountOutput, {XR_TYPE_CONTROLLER_MODEL_STATE_MSFT});
modelState.nodeCapacityInput = static_cast<uint32_t>(model.NodeStates.size());
modelState.nodeStates = model.NodeStates.data();
CHECK_XRCMD(xrGetControllerModelStateMSFT(context.Session.Handle, model.Key, &modelState));
assert(model.NodeStates.size() == model.NodeIndices.size());
const size_t end = std::min(model.NodeStates.size(), model.NodeIndices.size());
for (size_t i = 0; i < end; i++) {
const Pbr::NodeIndex_t nodeIndex = model.NodeIndices[i];
if (nodeIndex != Pbr::NodeIndex_npos) {
Pbr::Node& node = model.PbrModel->GetNode(nodeIndex);
node.SetTransform(xr::math::LoadXrPose(model.NodeStates[i].nodePose));
}
}
}
struct ControllerObject : engine::PbrModelObject {
ControllerObject(engine::Context& context, XrPath controllerUserPath);
~ControllerObject();
void Update(engine::Context& context, const engine::FrameTime& frameTime) override;
private:
const bool m_extensionSupported;
const XrPath m_controllerUserPath;
std::unique_ptr<ControllerModel> m_model;
std::future<std::unique_ptr<ControllerModel>> m_modelLoadingTask;
};
ControllerObject::ControllerObject(engine::Context& context, XrPath controllerUserPath)
: m_extensionSupported(context.Extensions.XR_MSFT_controller_model_enabled)
, m_controllerUserPath(controllerUserPath) {
}
ControllerObject::~ControllerObject() {
// Wait for model loading task to complete before dtor complete because it captures the scene context.
if (m_modelLoadingTask.valid()) {
m_modelLoadingTask.wait();
}
}
void ControllerObject::Update(engine::Context& context, const engine::FrameTime& frameTime) {
if (!m_extensionSupported) {
return; // The current runtime doesn't support controller model extension.
}
XrControllerModelKeyStateMSFT controllerModelKeyState{XR_TYPE_CONTROLLER_MODEL_KEY_STATE_MSFT};
CHECK_XRCMD(xrGetControllerModelKeyMSFT(context.Session.Handle, m_controllerUserPath, &controllerModelKeyState));
// If a new valid model key is returned, reload the model into cache asynchronously
const bool modelKeyValid = controllerModelKeyState.modelKey != XR_NULL_CONTROLLER_MODEL_KEY_MSFT;
if (modelKeyValid && (m_model == nullptr || m_model->Key != controllerModelKeyState.modelKey)) {
// Avoid two background tasks running together. The new one will start in future update after the old one is finished.
if (!m_modelLoadingTask.valid()) {
m_modelLoadingTask = std::async(std::launch::async, [&, modelKey = controllerModelKeyState.modelKey]() {
return LoadControllerModel(context, modelKey);
});
}
}
// If controller model loading task is completed, get the result model and apply it to rendering.
if (m_modelLoadingTask.valid() && m_modelLoadingTask.wait_for(0s) == std::future_status::ready) {
try {
m_model = m_modelLoadingTask.get(); // future.valid() is reset to false after get()
} catch (...) {
sample::Trace("Unexpected failure loading controller model");
}
if (m_model) {
SetModel(m_model->PbrModel);
}
}
// If controller model is already loaded, update all node transforms
if (m_model != nullptr) {
UpdateControllerParts(context, *m_model);
}
}
} // namespace
namespace engine {
std::shared_ptr<engine::PbrModelObject> CreateControllerObject(Context& context, XrPath controllerUserPath) {
return std::make_shared<ControllerObject>(context, controllerUserPath);
}
} // namespace engine
| [
"noreply@github.com"
] | noreply@github.com |
f0d258da15357d625d6d653041b3ab81553811e2 | 23863b25cbf03b36fd2f18364ffc63b24a487bd4 | /utils.h | 69c66fbf5eb340301ebfb1cd2e5e85517d645594 | [] | no_license | amaro/remotebuf | 160571968d91167c835e6e35c9cb990b654bf1ad | 2f1d2fcbce0187aaf39cb712c34c42eb71e9677e | refs/heads/master | 2020-06-21T17:55:07.723956 | 2016-12-14T01:22:32 | 2016-12-14T01:22:32 | 74,778,210 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 407 | h | #include <iomanip>
#include <ctime>
#include <fstream>
#include <sstream>
void debug(const std::string &msg) {
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::ofstream fout("/tmp/remotebuf.log", std::ios_base::app | std::ios_base::out);
fout << std::put_time(&tm, "%d-%m-%Y %H-%M-%S") << " :: " << msg << "\n";
}
void debug(const std::stringstream &sstm) {
debug(sstm.str());
}
| [
"amaro@users.noreply.github.com"
] | amaro@users.noreply.github.com |
61383d4ddb48952d71802de75dd0ce5296ff7c5c | fe598ccec7caa6879faf0612384327a25ea27dc9 | /Algorithms/Dynamic Programming/feliperw_coin-change_solution.cpp | 772920b5b72723aaaaa28f9cdf22e35c5ba827de | [] | no_license | fenixrw/HackerRank | 49182bff67c3c146410349e1301ec89c34c3a0ee | bdaefee5b62cf21075596aa1a11c6793425b7a08 | refs/heads/master | 2020-12-02T17:50:23.705526 | 2017-07-12T05:52:10 | 2017-07-12T05:52:10 | 96,436,160 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,168 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
unsigned long long coinChange(vector<int> &c, int n, vector<vector<long long>> &dp, int i=0)
{
if(dp[i][n-1]>=0)
{
return dp[i][n-1];
}
if(n - c[i] == 0)
{
return 1;
}
else if(n - c[i] < 0)
{
return 0;
}
unsigned long long count = 0;
for(int j=i;j<c.size();j++)
{
count+= coinChange(c,n - c[i],dp,j);
}
dp[i][n-1] = count;
return count;
}
unsigned long long coinChange(vector<int> &c, int n)
{
vector<vector<long long>> dp(c.size(),vector<long long>(n));
for(int i=0;i<c.size();i++)
fill(dp[i].begin(),dp[i].end(),-1);
unsigned long long count = 0;
for(int i=0;i<c.size();i++)
count +=coinChange(c,n,dp,i);
return count;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,m;
cin >> n >> m;
vector<int> c(m);
for(int i=0;i<m;i++)
cin >> c[i];
cout << coinChange(c,n) << endl;
return 0;
}
| [
"feliperw@msn.com"
] | feliperw@msn.com |
668f5469338804022a00277cedc5ca82cdda11c5 | 3cc352b29b8042b4a9746796b851d8469ff9ff62 | /src/paths/MapUnibasesToContigs.cc | 041c371a4641794d4777e0344d22ccbd27a35e14 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | CompRD/BroadCRD | 1412faf3d1ffd9d1f9907a496cc22d59ea5ad185 | 303800297b32e993abd479d71bc4378f598314c5 | refs/heads/master | 2020-12-24T13:53:09.985406 | 2019-02-06T21:38:45 | 2019-02-06T21:38:45 | 34,069,434 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,607 | cc | ///////////////////////////////////////////////////////////////////////////////
// SOFTWARE COPYRIGHT NOTICE AGREEMENT //
// This software and its documentation are copyright (2011) by the //
// Broad Institute. All rights are reserved. This software is supplied //
// without any warranty or guaranteed support whatsoever. The Broad //
// Institute is not responsible for its use, misuse, or functionality. //
///////////////////////////////////////////////////////////////////////////////
#include "Basevector.h"
#include "Intvector.h"
#include "util/SearchFastb2Core.h"
#include "paths/MapUnibasesToContigs.h"
/**
* MapUnibasesToContigs
*/
void MapUnibasesToContigs( const int K,
const String &unibases_file,
const String &contigs_file,
const String &OUTBASE,
ostream *log )
{
// Log stream.
ofstream devnull ( "/dev/null" );
ostream &out = log ? *log : devnull;
// File names.
String kmers_file = OUTBASE + ".kmers.fastb";
String map_file = OUTBASE + ".u2c";
// Count kmers in contigs.
out << Date( ) << ": counting kmers in contigs... " << flush;
size_t nkmers = 0;
vecbvec contigs( contigs_file );
for (size_t ii=0; ii<contigs.size( ); ii++)
if ( contigs[ii].isize( ) >= K )
nkmers += contigs[ii].size( ) - K + 1;
out << ToStringAddCommas( nkmers ) << " found" << endl;
// Generate temp fastb files.
out << Date( ) << ": generating and saving temp kmers file" << endl;
vecbvec kmers;
vec<size_t> to_contig;
kmers.reserve( nkmers );
to_contig.reserve( nkmers );
for (size_t ii=0; ii<contigs.size( ); ii++) {
for (int jj=0; jj<contigs[ii].isize( ) - K + 1; jj++) {
kmers.push_back( bvec( contigs[ii], jj, K ) );
to_contig.push_back( ii );
}
}
kmers.WriteAll( kmers_file );
// Align and sort (remove rc's).
vec< triple<int64_t,int64_t,int> > aligns;
out << Date( ) << ": running SearchFastb2... " << flush;
SearchFastb2( kmers_file, unibases_file, K, &aligns, 0, -1, 0.9, False );
out << ToStringAddCommas( aligns.size( ) ) << " aligns found" << endl;
{
out << Date( ) << ": removing rc aligns, and sorting" << endl;
vec< triple<int64_t,int64_t,int> > fwaligns;
fwaligns.reserve( aligns.size( ) / 2 );
for (size_t ii=0; ii<aligns.size( ); ii++)
if ( aligns[ii].third > -1 )
fwaligns.push_back( aligns[ii] );
sort( fwaligns.begin( ), fwaligns.end( ) );
swap( fwaligns, aligns );
}
// Remove kmers file.
out << Date( ) << ": removing temp kmers file" << endl;
Remove( kmers_file );
// Generate maps.
out << Date( ) << ": generating contigs to unibases map" << endl;
vec< pair<size_t,size_t> > c2u;
for (size_t ii=0; ii<aligns.size( ); ii++) {
size_t kmer_id = aligns[ii].first;
size_t unibase_id = aligns[ii].second;
size_t contig_id = to_contig[kmer_id];
if ( c2u.size( ) < 1 ||
contig_id != c2u.back( ).first ||
unibase_id != c2u.back( ).second )
c2u.push_back( make_pair( contig_id, unibase_id ) );
}
sort( c2u.begin( ), c2u.end( ) );
c2u.erase( unique( c2u.begin( ), c2u.end( ) ), c2u.end( ) );
out << Date( ) << ": generating unibases to contigs map" << endl;
size_t n_unibases = MastervecFileObjectCount( unibases_file );
UInt64VecVec u2c( n_unibases );
for (size_t ii=0; ii<c2u.size( ); ii++)
u2c[ c2u[ii].second ].push_back( c2u[ii].first );
// Save map.
out << Date( ) << ": saving unibases to contigs map" << endl;
u2c.WriteAll( map_file );
// Done.
out << Date( ) << ": done" << endl;
}
| [
"neil.weisenfeld@gmail.com"
] | neil.weisenfeld@gmail.com |
3eaf656f41c9765f8ac214bb3d9c2ae778884d6c | 212e1db07216b32ce75557139c75b48e512da921 | /tests/TST_EnumReflect/main.cpp | 06aa1e3ef1cec2b315cb61fe5deffcd4ca80818d | [
"MIT"
] | permissive | embtom/utilsCpp | effb1dcbd98cdd2cf55cc98b6337b4500cf784e4 | fef1959497aca3f7d07b8419740be79c305c6413 | refs/heads/master | 2022-05-28T05:52:17.781185 | 2020-05-03T08:26:06 | 2020-05-03T08:26:06 | 260,857,498 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,714 | cpp | #include <gtest/gtest.h>
#include <iostream>
#include <cstring>
#include <enum_reflect.hpp>
DECLARE_ENUM(EnumTest,int, val1=4, val2=2, val3=0x20, val4=0b101, val5=052);
TEST(EnumReflect, value)
{
EnumTest a = EnumTest::val1;
EXPECT_EQ(static_cast<int>(a), 4);
a = EnumTest::val2;
EXPECT_EQ(static_cast<int>(a), 2);
a = EnumTest::val3;
EXPECT_EQ(static_cast<int>(a), 32);
a = EnumTest::val4;
EXPECT_EQ(static_cast<int>(a), 5);
a = EnumTest::val5;
EXPECT_EQ(static_cast<int>(a), 42);
}
TEST(EnumReflect, toString)
{
EnumTest a = EnumTest::val1;
EXPECT_EQ(EnumToString(a), "val1");
a = EnumTest::val2;
EXPECT_EQ(EnumToString(a), "val2");
a = EnumTest::val3;
EXPECT_EQ(EnumToString(a), "val3");
a = EnumTest::val4;
EXPECT_EQ(EnumToString(a), "val4");
a = EnumTest::val5;
EXPECT_EQ(EnumToString(a), "val5");
}
#define CLEAR_BUFFER buffer.str("");
class StdoutEnumReflect : public ::testing::Test {
protected:
StdoutEnumReflect()
{ }
~StdoutEnumReflect() override = default;
void SetUp() override
{
sbuf = std::cout.rdbuf();
// Redirect cout to our stringstream buffer or any other ostream
std::cout.rdbuf(buffer.rdbuf());
}
// Called after each unit test
void TearDown() override {
// When done redirect cout to its old self
std::cout.rdbuf(sbuf);
sbuf = nullptr;
}
// The following objects can be reused in each unit test
// This can be an ofstream as well or any other ostream
std::stringstream buffer{};
// backup of std cout streambuf
std::streambuf *sbuf {nullptr};
};
TEST_F(StdoutEnumReflect, StackOverflowTest)
{
EnumTest a = EnumTest::val1;
{
std::cout << a << std::endl;
std::string actual{buffer.str()};
EXPECT_EQ(actual,"val1\n");
CLEAR_BUFFER;
}
{
a = EnumTest::val2;
std::cout << a << std::endl;
std::string actual{buffer.str()};
EXPECT_EQ(actual,"val2\n");
CLEAR_BUFFER;
}
{
a = EnumTest::val3;
std::cout << a << std::endl;
std::string actual{buffer.str()};
EXPECT_EQ(actual,"val3\n");
CLEAR_BUFFER;
}
{
a = EnumTest::val4;
std::cout << a << std::endl;
std::string actual{buffer.str()};
EXPECT_EQ(actual,"val4\n");
CLEAR_BUFFER;
}
{
a = EnumTest::val5;
std::cout << a << std::endl;
std::string actual{buffer.str()};
EXPECT_EQ(actual,"val5\n");
CLEAR_BUFFER;
}
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | [
"t.willetal@gmail.com"
] | t.willetal@gmail.com |
48f416abfdaa62dac7d76a4fedf422dec97c47ac | 51515a1120161f49bc2724ca8d4064c9a31b1516 | /parallelAlgorithms/computePI.cpp | 3cd452395225485ec47a264c3c47923fba51b1d7 | [] | no_license | MaiconMares/Parallel-Algorithms-with-MPI | 05a4cca5984df5ef47c53f85657983ad00eb3051 | eee1ea0c454e5a2daac180b150dcdae1bd5c22bd | refs/heads/master | 2022-12-05T02:55:13.120372 | 2020-08-21T11:24:25 | 2020-08-21T11:24:34 | 269,762,859 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,403 | cpp | #include <mpi.h>
#include <iostream>
#include <math.h>
/* This algorithm doesn't use the approach manager/worker
It makes use of collecive operations instead,
allowing process 0 does some work as other processes
*/
/* When executing the compiled file you should to set the
number of subintervals as an argument
by the command line. It gonna be captured by the argv[1].
*/
double f(double x) { return (4.0/(1 + x*x)); }
int main(int argc, char *argv[])
{
int n, rank, numproces;
//PI well computed
double PI25DT = 3.141592653589793238462643;
double mypi, pi = 0.0, h, sum, x;
double startWtime = 0.0, endWtime;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &numproces);
if (rank == 0) {
startWtime = MPI_Wtime();
n = atoi(argv[1]);
}
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
h = 1.0/(double) n;
sum = 0.0;
for (int i = rank+1; i <=n; i+=numproces) {
x = h * ((double)i-0.5);
sum += f(x);
}
mypi = (double) h * sum;
MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if (rank == 0) {
endWtime = MPI_Wtime();
printf("PI is approximately %.16f, Error is %.16f\n", pi, abs(pi-PI25DT));
printf("Wall clock time = %f\n", endWtime-startWtime);
}
MPI_Finalize();
return 0;
} | [
"maiconmaresunb@gmail.com"
] | maiconmaresunb@gmail.com |
088b5b6f02f39c239ffb007a43e3746f4b6ce5bc | 1dfcc9f652efad7af993a1fee739a6932bfd7447 | /ADAMAT.cpp | 9fd564f208d79ab51b6b8633d6a092800d172fbf | [] | no_license | prernapahwa/CompetitiveProgramming | d4b6109be5d1f9baa6e33c6a55a9af88ba187170 | d4440c81e2b1e985ddabb2b04e98bc2a1f78437f | refs/heads/master | 2022-12-17T13:55:59.027638 | 2020-09-20T20:59:34 | 2020-09-20T20:59:34 | 272,957,242 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 457 | cpp | #include<iostream>
using namespace std;
int main() {
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int arr[n][n];
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
cin>>arr[i][j];
}
}
int fixed;
int count=0;
if(arr[0][1]==2) {
fixed=1;
count=0;
}
else {
fixed=0;
count=1;
}
for(int i=2;i<n;i++) {
if(arr[0][i]!=i+1) {
if(fixed==1) {
count+=2;
}
fixed=0;
}
else {
fixed=1;
}
}
cout<<count<<endl;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
184440436dc5ee05dcac434a90e513152cfa4479 | cf5cb73bfb7073d78710992c7dabf39a0aba6f09 | /src/texsphere.h | 90428d6d7f647746ef687563150a475f38b30811 | [] | no_license | hyeddana/planet | dab44ed7798eb2e08a8c2736ebd369f714b3ae81 | 8653164f46c21ed074828bb3dcd5f22c9c288aef | refs/heads/master | 2020-12-05T15:36:14.902522 | 2016-08-24T05:03:17 | 2016-08-24T05:03:17 | 66,427,271 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 764 | h | #ifndef TEXSPHERE_H
#define TEXSPHERE_H
#include "sphere.h"
#include <QFile>
#include <QImage>
#include "glm/glm.hpp" // glm::vec*, mat*, and basic glm functions
#include "glm/gtx/transform.hpp" // glm::translate, scale, rotate
#include "glm/gtc/type_ptr.hpp" // glm::value_ptr
class TexSphere
: public Sphere
{
public:
TexSphere(int tessFact, float height);
void init();
private:
void specifySection(int startRow, int startCol, int endRow, int endCol);
void calcTangBiTang(const glm::vec3 &v0, const glm::vec3 &v1, const glm::vec3 &v2,
const glm::vec2 &uv0, const glm::vec2 &uv1, const glm::vec2 &uv2,
glm::vec3 &tangent, glm::vec3 &bitangent);
};
#endif // TEXSPHERE_H
| [
"hnyeddanapudy@hotmail.com"
] | hnyeddanapudy@hotmail.com |
efd7c0f984c3c2174a03b26a956d370828c51668 | 88ae8695987ada722184307301e221e1ba3cc2fa | /extensions/browser/api/audio/audio_service_chromeos.cc | 293dd6ff15f6c981479e1243bb7cfdd3eacdc2d4 | [
"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 | 12,491 | cc | // Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "extensions/browser/api/audio/audio_service.h"
#include <stddef.h>
#include <stdint.h>
#include "base/containers/contains.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "chromeos/ash/components/audio/audio_device.h"
#include "chromeos/ash/components/audio/cras_audio_handler.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/api/audio/audio_device_id_calculator.h"
namespace extensions {
using api::audio::AudioDeviceInfo;
using ::ash::AudioDevice;
using ::ash::AudioDeviceType;
using ::ash::CrasAudioHandler;
using ::content::BrowserThread;
namespace {
api::audio::DeviceType GetAsAudioApiDeviceType(AudioDeviceType type) {
switch (type) {
case AudioDeviceType::kHeadphone:
return api::audio::DeviceType::kHeadphone;
case AudioDeviceType::kMic:
return api::audio::DeviceType::kMic;
case AudioDeviceType::kUsb:
return api::audio::DeviceType::kUsb;
case AudioDeviceType::kBluetooth:
case AudioDeviceType::kBluetoothNbMic:
return api::audio::DeviceType::kBluetooth;
case AudioDeviceType::kHdmi:
return api::audio::DeviceType::kHdmi;
case AudioDeviceType::kInternalSpeaker:
return api::audio::DeviceType::kInternalSpeaker;
case AudioDeviceType::kInternalMic:
return api::audio::DeviceType::kInternalMic;
case AudioDeviceType::kFrontMic:
return api::audio::DeviceType::kFrontMic;
case AudioDeviceType::kRearMic:
return api::audio::DeviceType::kRearMic;
case AudioDeviceType::kKeyboardMic:
return api::audio::DeviceType::kKeyboardMic;
case AudioDeviceType::kHotword:
return api::audio::DeviceType::kHotword;
case AudioDeviceType::kLineout:
return api::audio::DeviceType::kLineout;
case AudioDeviceType::kPostMixLoopback:
return api::audio::DeviceType::kPostMixLoopback;
case AudioDeviceType::kPostDspLoopback:
return api::audio::DeviceType::kPostDspLoopback;
case AudioDeviceType::kAlsaLoopback:
return api::audio::DeviceType::kAlsaLoopback;
case AudioDeviceType::kOther:
return api::audio::DeviceType::kOther;
}
NOTREACHED();
return api::audio::DeviceType::kOther;
}
} // namespace
class AudioServiceImpl : public AudioService,
public CrasAudioHandler::AudioObserver {
public:
explicit AudioServiceImpl(AudioDeviceIdCalculator* id_calculator);
AudioServiceImpl(const AudioServiceImpl&) = delete;
AudioServiceImpl& operator=(const AudioServiceImpl&) = delete;
~AudioServiceImpl() override;
// Called by listeners to this service to add/remove themselves as observers.
void AddObserver(AudioService::Observer* observer) override;
void RemoveObserver(AudioService::Observer* observer) override;
// Start to query audio device information.
void GetDevices(
const api::audio::DeviceFilter* filter,
base::OnceCallback<void(bool, DeviceInfoList)> callback) override;
void SetActiveDeviceLists(const DeviceIdList* input_devices,
const DeviceIdList* output_devives,
base::OnceCallback<void(bool)> callback) override;
void SetDeviceSoundLevel(const std::string& device_id,
int level_value,
base::OnceCallback<void(bool)> callback) override;
void SetMute(bool is_input,
bool value,
base::OnceCallback<void(bool)> callback) override;
void GetMute(bool is_input,
base::OnceCallback<void(bool, bool)> callback) override;
protected:
// CrasAudioHandler::AudioObserver overrides.
void OnOutputNodeVolumeChanged(uint64_t id, int volume) override;
void OnInputNodeGainChanged(uint64_t id, int gain) override;
void OnOutputMuteChanged(bool mute_on) override;
void OnInputMuteChanged(
bool mute_on,
CrasAudioHandler::InputMuteChangeMethod method) override;
void OnAudioNodesChanged() override;
void OnActiveOutputNodeChanged() override;
void OnActiveInputNodeChanged() override;
private:
void NotifyLevelChanged(uint64_t id, int level);
void NotifyMuteChanged(bool is_input, bool is_muted);
void NotifyDevicesChanged();
uint64_t GetIdFromStr(const std::string& id_str);
bool GetAudioNodeIdList(const DeviceIdList& ids,
bool is_input,
CrasAudioHandler::NodeIdList* node_ids);
AudioDeviceInfo ToAudioDeviceInfo(const AudioDevice& device);
// List of observers.
base::ObserverList<AudioService::Observer>::Unchecked observer_list_;
raw_ptr<CrasAudioHandler, ExperimentalAsh> cras_audio_handler_;
raw_ptr<AudioDeviceIdCalculator, ExperimentalAsh> id_calculator_;
// Note: This should remain the last member so it'll be destroyed and
// invalidate the weak pointers before any other members are destroyed.
base::WeakPtrFactory<AudioServiceImpl> weak_ptr_factory_{this};
};
AudioServiceImpl::AudioServiceImpl(AudioDeviceIdCalculator* id_calculator)
: cras_audio_handler_(CrasAudioHandler::Get()),
id_calculator_(id_calculator) {
CHECK(id_calculator_);
if (cras_audio_handler_)
cras_audio_handler_->AddAudioObserver(this);
}
AudioServiceImpl::~AudioServiceImpl() {
// The CrasAudioHandler global instance may have already been destroyed, so
// do not used the cached pointer here.
if (CrasAudioHandler::Get())
CrasAudioHandler::Get()->RemoveAudioObserver(this);
}
void AudioServiceImpl::AddObserver(AudioService::Observer* observer) {
observer_list_.AddObserver(observer);
}
void AudioServiceImpl::RemoveObserver(AudioService::Observer* observer) {
observer_list_.RemoveObserver(observer);
}
void AudioServiceImpl::GetDevices(
const api::audio::DeviceFilter* filter,
base::OnceCallback<void(bool, DeviceInfoList)> callback) {
DeviceInfoList devices_out;
if (!cras_audio_handler_) {
std::move(callback).Run(false, std::move(devices_out));
return;
}
ash::AudioDeviceList devices;
cras_audio_handler_->GetAudioDevices(&devices);
bool accept_input =
!(filter && filter->stream_types) ||
base::Contains(*filter->stream_types, api::audio::StreamType::kInput);
bool accept_output =
!(filter && filter->stream_types) ||
base::Contains(*filter->stream_types, api::audio::StreamType::kOutput);
for (const auto& device : devices) {
if (filter && filter->is_active && *filter->is_active != device.active)
continue;
if (device.is_input && !accept_input)
continue;
if (!device.is_input && !accept_output)
continue;
devices_out.push_back(ToAudioDeviceInfo(device));
}
std::move(callback).Run(true, std::move(devices_out));
}
void AudioServiceImpl::SetActiveDeviceLists(
const DeviceIdList* input_devices,
const DeviceIdList* output_devives,
base::OnceCallback<void(bool)> callback) {
DCHECK(cras_audio_handler_);
if (!cras_audio_handler_) {
std::move(callback).Run(false);
return;
}
CrasAudioHandler::NodeIdList input_nodes;
if (input_devices &&
!GetAudioNodeIdList(*input_devices, true, &input_nodes)) {
std::move(callback).Run(false);
return;
}
CrasAudioHandler::NodeIdList output_nodes;
if (output_devives &&
!GetAudioNodeIdList(*output_devives, false, &output_nodes)) {
std::move(callback).Run(false);
return;
}
bool success = true;
if (output_devives) {
success = cras_audio_handler_->SetActiveOutputNodes(output_nodes);
DCHECK(success);
}
if (input_devices) {
success = success && cras_audio_handler_->SetActiveInputNodes(input_nodes);
DCHECK(success);
}
std::move(callback).Run(success);
}
void AudioServiceImpl::SetDeviceSoundLevel(
const std::string& device_id,
int level_value,
base::OnceCallback<void(bool)> callback) {
DCHECK(cras_audio_handler_);
if (!cras_audio_handler_) {
std::move(callback).Run(false);
return;
}
const AudioDevice* device =
cras_audio_handler_->GetDeviceFromId(GetIdFromStr(device_id));
if (!device) {
std::move(callback).Run(false);
return;
}
if (level_value != -1) {
cras_audio_handler_->SetVolumeGainPercentForDevice(device->id, level_value);
std::move(callback).Run(true);
} else {
std::move(callback).Run(false);
}
}
void AudioServiceImpl::SetMute(bool is_input,
bool value,
base::OnceCallback<void(bool)> callback) {
DCHECK(cras_audio_handler_);
if (!cras_audio_handler_) {
std::move(callback).Run(false);
return;
}
if (is_input)
cras_audio_handler_->SetInputMute(
value, CrasAudioHandler::InputMuteChangeMethod::kOther);
else
cras_audio_handler_->SetOutputMute(value);
std::move(callback).Run(true);
}
void AudioServiceImpl::GetMute(bool is_input,
base::OnceCallback<void(bool, bool)> callback) {
DCHECK(cras_audio_handler_);
if (!cras_audio_handler_) {
std::move(callback).Run(false, false);
return;
}
const bool is_muted_result = is_input ? cras_audio_handler_->IsInputMuted()
: cras_audio_handler_->IsOutputMuted();
std::move(callback).Run(true, is_muted_result);
}
uint64_t AudioServiceImpl::GetIdFromStr(const std::string& id_str) {
uint64_t device_id;
if (!base::StringToUint64(id_str, &device_id))
return 0;
else
return device_id;
}
bool AudioServiceImpl::GetAudioNodeIdList(
const DeviceIdList& ids,
bool is_input,
CrasAudioHandler::NodeIdList* node_ids) {
for (const auto& device_id : ids) {
const AudioDevice* device =
cras_audio_handler_->GetDeviceFromId(GetIdFromStr(device_id));
if (!device)
return false;
if (device->is_input != is_input)
return false;
node_ids->push_back(device->id);
}
return true;
}
AudioDeviceInfo AudioServiceImpl::ToAudioDeviceInfo(const AudioDevice& device) {
AudioDeviceInfo info;
info.id = base::NumberToString(device.id);
info.stream_type = device.is_input
? extensions::api::audio::StreamType::kInput
: extensions::api::audio::StreamType::kOutput;
info.device_type = GetAsAudioApiDeviceType(device.type);
info.display_name = device.display_name;
info.device_name = device.device_name;
info.is_active = device.active;
info.level =
device.is_input
? cras_audio_handler_->GetInputGainPercentForDevice(device.id)
: cras_audio_handler_->GetOutputVolumePercentForDevice(device.id);
info.stable_device_id =
id_calculator_->GetStableDeviceId(device.stable_device_id);
return info;
}
void AudioServiceImpl::OnOutputNodeVolumeChanged(uint64_t id, int volume) {
NotifyLevelChanged(id, volume);
}
void AudioServiceImpl::OnOutputMuteChanged(bool mute_on) {
NotifyMuteChanged(false, mute_on);
}
void AudioServiceImpl::OnInputNodeGainChanged(uint64_t id, int gain) {
NotifyLevelChanged(id, gain);
}
void AudioServiceImpl::OnInputMuteChanged(
bool mute_on,
CrasAudioHandler::InputMuteChangeMethod method) {
NotifyMuteChanged(true, mute_on);
}
void AudioServiceImpl::OnAudioNodesChanged() {
NotifyDevicesChanged();
}
void AudioServiceImpl::OnActiveOutputNodeChanged() {}
void AudioServiceImpl::OnActiveInputNodeChanged() {}
void AudioServiceImpl::NotifyLevelChanged(uint64_t id, int level) {
for (auto& observer : observer_list_)
observer.OnLevelChanged(base::NumberToString(id), level);
}
void AudioServiceImpl::NotifyMuteChanged(bool is_input, bool is_muted) {
for (auto& observer : observer_list_)
observer.OnMuteChanged(is_input, is_muted);
}
void AudioServiceImpl::NotifyDevicesChanged() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
ash::AudioDeviceList devices;
cras_audio_handler_->GetAudioDevices(&devices);
DeviceInfoList device_info_list;
for (const auto& device : devices) {
device_info_list.push_back(ToAudioDeviceInfo(device));
}
for (auto& observer : observer_list_)
observer.OnDevicesChanged(device_info_list);
}
AudioService::Ptr AudioService::CreateInstance(
AudioDeviceIdCalculator* id_calculator) {
return std::make_unique<AudioServiceImpl>(id_calculator);
}
} // namespace extensions
| [
"jengelh@inai.de"
] | jengelh@inai.de |
287f91d933aebc21be8cf090e50f4fecf903ac65 | c000f95fd43802ba6e473881ae689c23691a538a | /unity-samples/Temp/il2cppOutput/il2cppOutput/UnityEngine_UnityEngine_PhysicMaterial4182154592.h | 616afbb74dab8499e98c785a49adfb4d7a97c81c | [] | no_license | peterappboy/appboy-unity-sdk | 4c17516a49a8147dee94629c3de6c39d14cf879b | 93dfd2e29c85f0221d6cd7b17150121b0b7109c3 | refs/heads/master | 2021-01-22T18:28:50.479281 | 2016-08-04T22:04:15 | 2016-08-04T22:04:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 527 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "UnityEngine_UnityEngine_Object3878351788.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.PhysicMaterial
struct PhysicMaterial_t4182154592 : public Object_t3878351788
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"wenzhi@appboy.com"
] | wenzhi@appboy.com |
3d15fa57cbb43e1690654b80eb403723e87ad9aa | 732c77430634a5dcc0db2430f05b156f02c109f0 | /Plugins/BasePlugin/Intermediate/Build/Win64/UE4Editor/Inc/BasePlugin/SkillLogic.generated.h | 8eabb86056d126058eab0b5cd608cc9fafc5549c | [] | no_license | preko96/TurnBasedPlugin | cc3fbddbfe07dfd04287ab7e5ce683cf36a5cece | 12883fe940bc748260e541d3bd10e34cdcf75d04 | refs/heads/master | 2020-03-08T04:08:18.475248 | 2018-04-07T11:40:37 | 2018-04-07T11:40:37 | 127,912,606 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,880 | h | // Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "ObjectMacros.h"
#include "ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
class ACharacter;
class USkillLogic;
#ifdef BASEPLUGIN_SkillLogic_generated_h
#error "SkillLogic.generated.h already included, missing '#pragma once' in SkillLogic.h"
#endif
#define BASEPLUGIN_SkillLogic_generated_h
#define TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_RPC_WRAPPERS \
\
DECLARE_FUNCTION(execInitalize) \
{ \
P_GET_OBJECT(ACharacter,Z_Param_InitSkillOwner); \
P_GET_OBJECT(ACharacter,Z_Param_InitSkillTarget); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->Initalize(Z_Param_InitSkillOwner,Z_Param_InitSkillTarget); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execTickTurn) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->TickTurn(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execCopy) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(USkillLogic**)Z_Param__Result=P_THIS->Copy(); \
P_NATIVE_END; \
}
#define TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_RPC_WRAPPERS_NO_PURE_DECLS \
\
DECLARE_FUNCTION(execInitalize) \
{ \
P_GET_OBJECT(ACharacter,Z_Param_InitSkillOwner); \
P_GET_OBJECT(ACharacter,Z_Param_InitSkillTarget); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->Initalize(Z_Param_InitSkillOwner,Z_Param_InitSkillTarget); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execTickTurn) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->TickTurn(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execCopy) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(USkillLogic**)Z_Param__Result=P_THIS->Copy(); \
P_NATIVE_END; \
}
#define TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesUSkillLogic(); \
friend BASEPLUGIN_API class UClass* Z_Construct_UClass_USkillLogic(); \
public: \
DECLARE_CLASS(USkillLogic, UObject, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/BasePlugin"), NO_API) \
DECLARE_SERIALIZER(USkillLogic) \
enum {IsIntrinsic=COMPILED_IN_INTRINSIC};
#define TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_INCLASS \
private: \
static void StaticRegisterNativesUSkillLogic(); \
friend BASEPLUGIN_API class UClass* Z_Construct_UClass_USkillLogic(); \
public: \
DECLARE_CLASS(USkillLogic, UObject, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/BasePlugin"), NO_API) \
DECLARE_SERIALIZER(USkillLogic) \
enum {IsIntrinsic=COMPILED_IN_INTRINSIC};
#define TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API USkillLogic(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(USkillLogic) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, USkillLogic); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(USkillLogic); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API USkillLogic(USkillLogic&&); \
NO_API USkillLogic(const USkillLogic&); \
public:
#define TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_ENHANCED_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API USkillLogic(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API USkillLogic(USkillLogic&&); \
NO_API USkillLogic(const USkillLogic&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, USkillLogic); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(USkillLogic); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(USkillLogic)
#define TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_PRIVATE_PROPERTY_OFFSET
#define TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_18_PROLOG
#define TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_PRIVATE_PROPERTY_OFFSET \
TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_RPC_WRAPPERS \
TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_INCLASS \
TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_PRIVATE_PROPERTY_OFFSET \
TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_RPC_WRAPPERS_NO_PURE_DECLS \
TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_INCLASS_NO_PURE_DECLS \
TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h_21_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID TurnBasedPlugin_master_Plugins_BasePlugin_Source_BasePlugin_Classes_SkillLogic_h
#define FOREACH_ENUM_ESKILLID(op) \
op(ESkillID::S_Alpha)
PRAGMA_ENABLE_DEPRECATION_WARNINGS
| [
"35433203+preko96@users.noreply.github.com"
] | 35433203+preko96@users.noreply.github.com |
053bb1025237ad52870103b0fe43200342a8260d | bfec72816d2dcd280c25b88993d88fbb30a15b85 | /MAMR Game Server/Server/MapGroupKernel/ItemAddition.h | cfd1046769d733c90764701a1b6089fa88ea9656 | [] | no_license | jon-karve/MAMR-Game-Server | e5e48f859d102f119eba8695c128d4ad4a270773 | e170ad89100188124e892d7caf260520e834f7d4 | refs/heads/master | 2023-03-21T18:50:59.082395 | 2020-10-23T03:57:43 | 2020-10-23T03:57:43 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,193 | h | // ItemAddition.h: interface for the CItemAddition class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_ITEMADDITION_H__4C270148_7B1D_46C5_A799_B85CF277CF6E__INCLUDED_)
#define AFX_ITEMADDITION_H__4C270148_7B1D_46C5_A799_B85CF277CF6E__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#pragma warning(disable:4786)
#include "define.h"
#include "ConstGameData.h"
#include "GameData.h"
#include "GameObj.h"
#include "Myheap.h"
#include "SingleMap64.h"
#include <vector>
using namespace std;
//////////////////////////////////////////////////////////////////////
enum ITEMADDITIONDATA
{
// ITEMADDITIONDATA_ID = 0, // 不会用到的
ITEMADDITIONDATA_TYPEID = 1, // 追加类型(与itemtype相关)
ITEMADDITIONDATA_LEVEL, // 追加等级
ITEMADDITIONDATA_LIFE, // 生命值
ITEMADDITIONDATA_ATTACK_MAX, // 最大物理攻击
ITEMADDITIONDATA_ATTACK_MIN, // 最小物理攻击
ITEMADDITIONDATA_DEFENSE, // 防御
ITEMADDITIONDATA_MGCATK_MAX, // 最大魔攻
ITEMADDITIONDATA_MGCATK_MIN, // 最小魔攻
ITEMADDITIONDATA_MAGICDEF, // 魔防
ITEMADDITIONDATA_DEXTERITY, // 敏捷
ITEMADDITIONDATA_DODGE, // 躲避
};
char szItemAdditionTable[];
typedef CGameData<ITEMADDITIONDATA,szItemAdditionTable, szID> CItemAdditionData;
// ITEMADDITIONDATA 应该增加一个ITEMADDITIONDATA_LEVEL,以此为第2个键
typedef ISingleMap64<CItemAdditionData, ITEMADDITIONDATA, ITEMADDITIONDATA_TYPEID, ITEMADDITIONDATA_LEVEL> IItemAdditionSet64;
typedef CSingleMap64<CItemAdditionData, ITEMADDITIONDATA, ITEMADDITIONDATA_TYPEID, ITEMADDITIONDATA_LEVEL> CItemAdditionSet64;
//////////////////////////////////////////////////////////////////////
class CItemAddition
{
public:
CItemAddition();
virtual ~CItemAddition();
public:
static CItemAddition* CreateNew () { return new CItemAddition; }
ULONG Release () { delete this; return 0; }
bool Create (IDatabase* pDb);
CItemAdditionData* QueryItemAddition(OBJID idType, int nLevel);
protected:
IItemAdditionSet64* m_setAddition;
MYHEAP_DECLARATION(s_heap)
};
#endif // !defined(AFX_ITEMADDITION_H__4C270148_7B1D_46C5_A799_B85CF277CF6E__INCLUDED_)
| [
"c_pollack@hotmail.com"
] | c_pollack@hotmail.com |
1389d1e6baf78584e7d90ea817ab349f77286531 | 6e1cddc7e0301178ae53ca6ae18923dd309284f5 | /app/src/main/cpp/cppsrc/i/ikey2.h | 4f236a550061104072bdb88abfd49c0aca165b05 | [
"MIT"
] | permissive | DimaBond174/android_cache | f3a945a11cb7f1956cfdb1c1c151a2d13ca1ca4e | f4ce818210c761c95258cc754ef0a573506c85f7 | refs/heads/master | 2020-05-18T04:36:56.470958 | 2019-05-27T03:08:02 | 2019-05-27T03:08:02 | 184,179,499 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,431 | h | /*
* This is the source code of SpecNet project
* It is licensed under MIT License.
*
* Copyright (c) Dmitriy Bondarenko
* feel free to contact me: specnet.messenger@gmail.com
*/
#ifndef IKEY2_H
#define IKEY2_H
#include <stdlib.h>
#include <stdint.h>
#include <string>
#define SKIPHEIGHT 5
#define SKIPHEIGHT_H 2
#define SIZEAllocLeaf 256
/*
* NSizeKey must be stored with data on which it based.
* N = bytes
* void *ptr == (Example:) std::string.data() where string.reserve(N)
*/
template<std::size_t N>
class NSizeKey {
public:
NSizeKey() { keyArray = nullptr; }
NSizeKey(void *ptr) {
setKey(ptr);
}
uint64_t *keyArray;
static constexpr int keyLongSize = ((N/sizeof(uint64_t))+ (N%sizeof(uint64_t)>0?1:0));
static constexpr int keyLongSize_1 = keyLongSize - 1;
void setKey(void *ptr) {
keyArray = static_cast<uint64_t *>(ptr);
}
int cmp(NSizeKey const & other ) {
if (keyArray) {
for (int i=0; i<keyLongSize; ++i) {
if (keyArray[i] > other.keyArray[i]) return 1;
if (keyArray[i] < other.keyArray[i]) return -1;
}
} else if (other.keyArray) {
return -1;
}
return 0;
}
int cmp(NSizeKey const * other ) {
if (keyArray) {
for (int i=0; i<keyLongSize; ++i) {
if (keyArray[i] > other->keyArray[i]) return 1;
if (keyArray[i] < other->keyArray[i]) return -1;
}
} else if (other->keyArray) {
return -1;
}
return 0;
}
uint64_t hash() const {
uint64_t re = 0;
if (keyArray) {
for (int i = 0; i < keyLongSize; ++i) {
re += keyArray[i];
}
}
return (re < 9223372036854775807ll)? re : (re >> 1);
}
};
//class TKey {
// public:
// TKey(uint64_t p0 = 0, uint64_t p1 = 0, uint64_t p2 = 0) {
// keyArray[0] = p0;
// keyArray[1] = p1;
// keyArray[2] = p2;
// }
// TKey & operator=(TKey const &rhl) {
// keyArray[0] = rhl.keyArray[0];
// keyArray[1] = rhl.keyArray[1];
// keyArray[2] = rhl.keyArray[2];
// return *this;
// }
// TKey(const TKey &rhl) {
// keyArray[0] = rhl.keyArray[0];
// keyArray[1] = rhl.keyArray[1];
// keyArray[2] = rhl.keyArray[2];
// }
// bool operator==(TKey const &rhl) const {
// return keyArray[0] == rhl.keyArray[0]
// && keyArray[1] == rhl.keyArray[1]
// && keyArray[2] == rhl.keyArray[2];
// }
// static bool do_worst_case;
// static constexpr int keyLongSize = 3;
// uint64_t keyArray[keyLongSize];
// uint64_t hash() const {
// const uint64_t re = keyArray[0] + keyArray[1] + keyArray[2];
// if (do_worst_case) {
// return (re % 1000);
// }
// return (re < 9223372036854775807ll)? re : (re >> 1);
// }
// int cmp(TKey const *other) const {
// if (keyArray[2] > other->keyArray[2]) return 1;
// if (keyArray[2] < other->keyArray[2]) return -1;
// if (keyArray[1] > other->keyArray[1]) return 1;
// if (keyArray[1] < other->keyArray[1]) return -1;
// if (keyArray[0] > other->keyArray[0]) return 1;
// if (keyArray[0] < other->keyArray[0]) return -1;
// return 0;
// }
// bool operator<(const TKey &r) const {
// if (keyArray[0] < r.keyArray[0]) return true;
// if (keyArray[0] > r.keyArray[0]) return false;
// if (keyArray[1] < r.keyArray[1]) return true;
// if (keyArray[1] > r.keyArray[1]) return false;
// if (keyArray[2] < r.keyArray[2]) return true;
// if (keyArray[2] > r.keyArray[2]) return false;
// // Otherwise both are equal
// return false;
// }
//}; // TKey
//inline uint qHash(const TKey *key, uint seed = 0)
//{
// return key->hash() ^ seed;
//}
//inline uint qHash(TKey key, uint seed = 0)
//{
// return key.hash() ^ seed;
//}
//struct THash {
// _GLIBCXX_PURE size_t
// operator()(const TKey& key) const noexcept {
// return key.hash();
// }
//};
struct ElemNSizeKey {
ElemNSizeKey() {}
ElemNSizeKey(const std::string &_data)
: data(_data) {
setKey();
}
ElemNSizeKey(const ElemNSizeKey &other) : data(other.data) {
setKey();
}
ElemNSizeKey(const ElemNSizeKey *other) : data(other->data) {
setKey();
}
ElemNSizeKey & operator=(const ElemNSizeKey &rhv) {
if (&rhv != this) {
data = rhv.data;
setKey();
}
return *this;
}
void setKey() {
len = data.length();
if (data.capacity() < key_ElemNSizeKey_size) {
data.reserve(key_ElemNSizeKey_size);
}
key.setKey(data.data());
}
static constexpr int key_ElemNSizeKey_size = 3 * sizeof(uint64_t);
NSizeKey<key_ElemNSizeKey_size> key;
std::string data;
int len;
};
//
inline int compare (const ElemNSizeKey *lhv,
const ElemNSizeKey *rhv) {
if (lhv->key.keyArray) {
for (int i = lhv->key.keyLongSize_1; i >= 0; --i) {
if (lhv->key.keyArray[i] > rhv->key.keyArray[i]) return 1;
if (lhv->key.keyArray[i] < rhv->key.keyArray[i]) return -1;
}
} else if (rhv->key.keyArray) {
return -1;
}
return lhv->data.compare(rhv->data);
}
inline uint64_t get_hash(const ElemNSizeKey *lhv) {
return lhv->key.hash();
}
#endif // IKEY2_H
| [
"bondarenkoda@gmail.com"
] | bondarenkoda@gmail.com |
b8012c53ddf1fdd25eeb611a933aff9bbf266b2a | 037d518773420f21d74079ee492827212ba6e434 | /blazetest/src/mathtest/dmatdmatadd/UDaUDa.cpp | 0f92bbb76f1b9719da9170bb7c44a9ba33d0c53d | [
"BSD-3-Clause"
] | permissive | chkob/forked-blaze | 8d228f3e8d1f305a9cf43ceaba9d5fcd603ecca8 | b0ce91c821608e498b3c861e956951afc55c31eb | refs/heads/master | 2021-09-05T11:52:03.715469 | 2018-01-27T02:31:51 | 2018-01-27T02:31:51 | 112,014,398 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,837 | cpp | //=================================================================================================
/*!
// \file src/mathtest/dmatdmatadd/UDaUDa.cpp
// \brief Source file for the UDaUDa dense matrix/dense matrix addition math test
//
// Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/UpperMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatdmatadd/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'UDaUDa'..." << std::endl;
using blazetest::mathtest::TypeA;
try
{
// Matrix type definitions
typedef blaze::UpperMatrix< blaze::DynamicMatrix<TypeA> > UDa;
// Creator type definitions
typedef blazetest::Creator<UDa> CUDa;
// Running tests with small matrices
for( size_t i=0UL; i<=9UL; ++i ) {
RUN_DMATDMATADD_OPERATION_TEST( CUDa( i ), CUDa( i ) );
}
// Running tests with large matrices
RUN_DMATDMATADD_OPERATION_TEST( CUDa( 67UL ), CUDa( 67UL ) );
RUN_DMATDMATADD_OPERATION_TEST( CUDa( 128UL ), CUDa( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix addition:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
09101d200fc3cd7f2279e32430ed79cd7563fa06 | 9fdc1cbdda5fca9a916388e81dcaf7fe3c44c17b | /src/chrono_parallel/math/svd.h | 848bbb7f56a3578dc093842da24460d912ce55e2 | [
"BSD-3-Clause"
] | permissive | StefanoZaghi1987/ChronoWheelDesigner | 473c7b4b7177532c6c0b6a7e04df03c85678c4ab | 48b0235565e6c1c08ce8b5a742bf92b0fcbd70f0 | refs/heads/master | 2021-01-22T00:29:12.900606 | 2018-01-26T15:20:01 | 2018-01-26T15:20:01 | 102,189,611 | 1 | 0 | BSD-3-Clause | 2018-01-26T15:20:02 | 2017-09-02T10:38:38 | C++ | UTF-8 | C++ | false | false | 4,931 | h | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2016 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Hammad Mazhar
// =============================================================================
//
// Description: Fast Singular Value Decomposition (SVD)
// =============================================================================
#pragma once
#include "chrono_parallel/math/matrixf.cuh"
namespace chrono {
/// @addtogroup parallel_math
/// @{
// Oliver K. Smith. 1961. Eigenvalues of a symmetric 3 × 3 matrix. Commun. ACM 4, 4 (April 1961), 168-.
// DOI=http://dx.doi.org/10.1145/355578.366316
CUDA_HOST_DEVICE static float3 Fast_Eigenvalues(const SymMat33f& A) // 24 mults, 20 adds, 1 atan2, 1 sincos, 2 sqrts
{
const float m = (1.0f) / (3.0f) * (A.x11 + A.x22 + A.x33);
const float a11 = A.x11 - m;
const float a22 = A.x22 - m;
const float a33 = A.x33 - m;
const float a12_sqr = A.x21 * A.x21;
const float a13_sqr = A.x31 * A.x31;
const float a23_sqr = A.x32 * A.x32;
const float p = (1.0f) / (6.0f) * (a11 * a11 + a22 * a22 + a33 * a33 + 2 * (a12_sqr + a13_sqr + a23_sqr));
const float q = (0.5f) * (a11 * (a22 * a33 - a23_sqr) - a22 * a13_sqr - a33 * a12_sqr) + A.x21 * A.x31 * A.x32;
const float sqrt_p = sqrtf(p);
const float disc = p * p * p - q * q;
const float phi = (1.0f) / (3.0f) * atan2f(sqrtf(fmaxf((0.0f), disc)), q);
const float c = cosf(phi);
const float s = sinf(phi);
const float sqrt_p_cos = sqrt_p * c;
const float root_three_sqrt_p_sin = sqrtf((3.0f)) * sqrt_p * s;
float3 lambda = make_float3(m + (2.0f) * sqrt_p_cos, m - sqrt_p_cos - root_three_sqrt_p_sin,
m - sqrt_p_cos + root_three_sqrt_p_sin);
Sort(lambda.z, lambda.y, lambda.x);
return lambda;
}
CUDA_HOST_DEVICE static Mat33f Fast_Eigenvectors(const SymMat33f& A, float3& lambda) {
// flip if necessary so that first eigenvalue is the most different
bool flipped = false;
float3 lambda_flip(lambda);
if (lambda.x - lambda.y < lambda.y - lambda.z) { // 2a
Swap(lambda_flip.x, lambda_flip.z);
flipped = true;
}
// get first eigenvector
const float3 v1 =
LargestColumnNormalized(CofactorMatrix(A - lambda_flip.x)); // 3a + 12m+6a + 9m+6a+1d+1s = 21m+15a+1d+1s
// form basis for orthogonal complement to v1, and reduce A to this space
const float3 v1_orthogonal = UnitOrthogonalVector(v1); // 6m+2a+1d+1s (tweak: 5m+1a+1d+1s)
const Mat32f other_v(v1_orthogonal, Cross(v1, v1_orthogonal)); // 6m+3a (tweak: 4m+1a)
const SymMat22f A_reduced = ConjugateWithTranspose(other_v, A); // 21m+12a (tweak: 18m+9a)
// find third eigenvector from A_reduced, and fill in second via cross product
// 6m+3a + 2a + 5m+2a+1d+1s = 11m+7a+1d+1s (tweak: 10m+6a+1d+1s)
const float3 v3 = other_v * LargestColumnNormalized(CofactorMatrix(A_reduced - lambda_flip.z));
const float3 v2 = Cross(v3, v1); // 6m+3a
// finish
return flipped ? Mat33f(v3.x, v3.y, v3.z, v2.x, v2.y, v2.z, -v1.x, -v1.y, -v1.z)
: Mat33f(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z, v3.x, v3.y, v3.z);
}
CUDA_HOST_DEVICE static void Fast_Solve_EigenProblem(const SymMat33f& A, float3& eigen_values, Mat33f& eigen_vectors) {
eigen_values = Fast_Eigenvalues(A);
eigen_vectors = Fast_Eigenvectors(A, eigen_values);
}
CUDA_HOST_DEVICE static void SVD(const Mat33f& A, Mat33f& U, float3& singular_values, Mat33f& V) {
const SymMat33f ATA = NormalEquationsMatrix(A);
float3 lambda;
Fast_Solve_EigenProblem(ATA, lambda, V);
if (lambda.z < 0) {
lambda = Max(lambda, (0.0f));
}
singular_values = Sqrt(lambda); // 3s
if (Determinant(A) < 0) {
singular_values.z = -singular_values.z;
}
// compute singular vectors
const float3 c0 = Normalize(A * V.col(0)); // 15m+8a+1d+1s
const float3 v1 = UnitOrthogonalVector(c0); // 6m+2a+1d+1s
const float3 v2 = Cross(c0, v1); // 6m+3a
// 6m+3a + 6m+4a + 9m+6a + 6m+2a+1d+1s = 27m+15a+1d+1s
const float3 v3 = A * V.col(1);
const float2 other_v = Normalize(make_float2(Dot(v1, v3), Dot(v2, v3)));
const float3 c1 = make_float3(v1.x * other_v.x + v2.x * other_v.y, v1.y * other_v.x + v2.y * other_v.y,
v1.z * other_v.x + v2.z * other_v.y);
const float3 c2 = Cross(c0, c1); // 6m+3a
U = Mat33f(c0.x, c0.y, c0.z, c1.x, c1.y, c1.z, c2.x, c2.y, c2.z);
}
/// @} parallel_math
} // end namespace chrono
| [
"stefano.zaghi@gamma-spa.com"
] | stefano.zaghi@gamma-spa.com |
d9bcb3b8ab10f8ed6b87d992f5bf48c2499089f3 | a6f5d608a22fb2e904c8e438d23694599d4cd8e1 | /apps-src/apps/librose/thread.cpp | 6c4fa85d571ac83dafbaf87e9ddccf0fbb00b52c | [
"BSD-2-Clause"
] | permissive | absir/Rose | ec18ad5c5a8c9d24cb4af281fbd00a2efa7285fa | 23a9f4307a27a3d4f2aceac30853d0ee69bc0f41 | refs/heads/main | 2023-02-24T20:00:47.442495 | 2021-01-31T08:03:05 | 2021-01-31T08:35:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,755 | cpp | /* $Id: thread.cpp 46186 2010-09-01 21:12:38Z silene $ */
/*
Copyright (C) 2003 - 2010 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 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.
See the COPYING file for more details.
*/
#include "global.hpp"
#include <vector>
#include "thread.hpp"
#include "base_instance.hpp"
namespace rtc {
void worker_thread::DoWork() { worker_.DoWork(); }
void worker_thread::OnWorkStart() { worker_.OnWorkStart(); }
void worker_thread::OnWorkDone() { worker_.OnWorkDone(); }
}
namespace threading {
mutex::mutex() : m_(SDL_CreateMutex())
{}
mutex::~mutex()
{
SDL_DestroyMutex(m_);
}
lock::lock(mutex& m) : m_(m)
{
SDL_mutexP(m_.m_);
}
lock::~lock()
{
SDL_mutexV(m_.m_);
}
condition::condition() : cond_(SDL_CreateCond())
{}
condition::~condition()
{
SDL_DestroyCond(cond_);
}
bool condition::wait(const mutex& m)
{
return SDL_CondWait(cond_,m.m_) == 0;
}
condition::WAIT_TIMEOUT_RESULT condition::wait_timeout(const mutex& m, unsigned int timeout)
{
const int res = SDL_CondWaitTimeout(cond_,m.m_,timeout);
switch(res) {
case 0: return WAIT_OK;
case SDL_MUTEX_TIMEDOUT: return WAIT_TIMED_OUT;
default:
// SDL_CondWaitTimeout: $SDL_GetError()
return WAIT_ERROR;
}
}
bool condition::notify_one()
{
if(SDL_CondSignal(cond_) < 0) {
// SDL_CondSignal: $SDL_GetError()
return false;
}
return true;
}
bool condition::notify_all()
{
if(SDL_CondBroadcast(cond_) < 0) {
// SDL_CondBroadcast: $SDL_GetError()
return false;
}
return true;
}
semaphore::semaphore(Uint32 initial_value) : sem_(SDL_CreateSemaphore(initial_value))
{}
semaphore::~semaphore()
{
SDL_DestroySemaphore(sem_);
}
int semaphore::wait(Uint32 timeout)
{
return SDL_SemWaitTimeout(sem_, timeout);
}
void semaphore::post()
{
SDL_SemPost(sem_);
}
}
/*
std::unique_ptr<twebrtc_send_helper::tlock> twebrtc_send_helper::get_sender_lock()
{
VALIDATE_NOT_MAIN_THREAD();
if (deconstructed_) {
return NULL;
}
std::unique_ptr<tlock> ret(new tlock(*this));
if (deconstructed_) {
// maybe deconstructed_ = true when execute below statement.
return NULL;
}
return ret;
}
*/
void twebrtc_send_helper::clear_msg()
{
VALIDATE_IN_MAIN_THREAD();
// allow repeated call
// DCHECK(!deconstructed_);
deconstructed_ = true;
while (senders_ > 0) {
// 2. wait all invoker no invoke.
instance->sdl_thread().clear_msg(phandler_);
SDL_Delay(20);
}
}
| [
"service@leagor.com"
] | service@leagor.com |
b0ed71ea3aa843dad417eb99454f3e339552e066 | d958f710817e4e5252166ea4f3aac6fde7bb6f98 | /Source/engine/load_clx.hpp | f53476e777665f95de1957408e9f1ff95a920311 | [
"LicenseRef-scancode-sustainable-use-1.0",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | BennyFranco/devilutionX | 510760daebaec65089f7e6c1c15b8e39101859d6 | 45dbe6aa611810be103e14e503fb84b59915fa33 | refs/heads/master | 2023-08-31T02:27:55.385119 | 2023-08-26T14:45:36 | 2023-08-26T14:45:36 | 174,883,838 | 2 | 6 | Unlicense | 2019-04-25T02:43:04 | 2019-03-10T21:34:16 | C++ | UTF-8 | C++ | false | false | 692 | hpp | #pragma once
#include "clx_sprite.hpp"
namespace devilution {
OwnedClxSpriteListOrSheet LoadClxListOrSheet(const char *path);
inline OwnedClxSpriteList LoadClx(const char *path)
{
return LoadClxListOrSheet(path).list();
}
inline OwnedClxSpriteSheet LoadClxSheet(const char *path)
{
return LoadClxListOrSheet(path).sheet();
}
OptionalOwnedClxSpriteListOrSheet LoadOptionalClxListOrSheet(const char *path);
inline OptionalOwnedClxSpriteList LoadOptionalClx(const char *path)
{
OptionalOwnedClxSpriteListOrSheet result = LoadOptionalClxListOrSheet(path);
if (!result)
return std::nullopt;
return std::move(*result).list();
}
} // namespace devilution
| [
"anders@jenbo.dk"
] | anders@jenbo.dk |
90a96a320042958a1d32b2160af7b70a11982c16 | f49fa0a4a14a20bf56b010a6a206ec069ef69c0d | /ch11-customizing-io/ex-09.cpp | 349af47e81c58d384e5c785b8d9d5f85d5f21082 | [] | no_license | yuichi-morisaki/cpp-p3 | ff29d7081e9cecfd0e4e3e6117f7f731de79ed11 | dc573b0660d675b17a267cac76abcea470d0d0e2 | refs/heads/main | 2023-01-30T01:20:13.768034 | 2020-12-15T03:28:00 | 2020-12-15T03:28:00 | 314,279,222 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,698 | cpp | /*
Split the binary I/O program from section 11.3.2 into two:
one program that converts an ordinary text file into binary
and one program that reads binary and converts it to text.
Test these programs by comparing a text file with what you
get by converting it to binary and back.
*/
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <vector>
using namespace std;
void error(string s1, string s2) { throw runtime_error(s1 + s2); }
char* as_bytes(char& c)
{
void* addr = &c;
return static_cast<char*>(addr);
}
int main()
try {
string bin_fname {"ex-09.bin"};
// program 1. txt => bin
{
string txt_fname {"ex-09.cpp"};
ifstream ifs {txt_fname};
if (!ifs)
error("can't open input file ", txt_fname);
ofstream ofs {bin_fname, ios_base::binary};
if (!ofs)
error("can't open output file ", bin_fname);
vector<char> v;
for (char c; ifs.get(c); ) {
v.push_back(c);
}
for (char c: v)
ofs.write(as_bytes(c), sizeof(char));
}
// program 2. bin => txt;
{
ifstream ifs {bin_fname, ios_base::binary};
if (!ifs)
error("can't open input file ", bin_fname);
string txt_fname {"ex-09-out.txt"};
ofstream ofs {txt_fname};
if (!ifs)
error("can't open output file ", txt_fname);
vector<char> v;
for (char c; ifs.read(as_bytes(c), sizeof(char)); )
v.push_back(c);
for (char c: v)
ofs.put(c);
}
return 0;
}
catch (exception& e) {
cerr << "exception: " << e.what() << '\n';
return 1;
}
| [
"yuichi.morisaki@gmail.com"
] | yuichi.morisaki@gmail.com |
56148aa78bf948fbbb3cc3f0d8236abea59e1754 | d6314f33364c36871e2fc7bd49dc0bb9355f242e | /Codeforces/Stanford/Practice 2/F.cpp | 27839f996d9025376b60ae518092a1fcdebfbe13 | [] | no_license | lucasxia01/Competitive-Programming-Problems | 26a953cc54ab55be972a79adae0bc79e8dc844e1 | a90da940a5cef6faf10efbefa241ad7e799be53a | refs/heads/master | 2022-08-31T12:29:36.715884 | 2022-08-17T04:22:56 | 2022-08-17T04:22:56 | 152,951,359 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,730 | cpp | #include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <functional>
#include <stdlib.h>
#include <time.h>
#include <complex>
#include <iterator>
#include <regex>
#include <fstream>
#include <utility>
#include <vector>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <random>
#include <chrono>
#include <cassert>
#include <climits>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pi;
typedef pair<ll,ll> pl;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<pi> vpi;
typedef vector<pl> vpl;
#define F0R(i,n) for (int i = 0; i < n; i++)
#define FOR(i,a,b) for (int i = a; i <= b; i++)
#define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--)
#define FORd(i,a,b) for (int i = (b); i >= (a); i--)
#define trav(a, x) for (auto& a : x)
#define f first
#define s second
#define mp make_pair
#define pb push_back
#define ins insert
#define lb lower_bound
#define ub upper_bound
#define sz(x) (int)x.size()
#define all(x) x.begin(), x.end()
const char nl = '\n';
const int MAX_N = 100011;
const ll INF = (1<<29) + 123;
const ll MOD = 1000000007; // 998244353
const ld PI = 4*atan((ld)1);
template <typename T> bool ckmin(T& a, const T& b) { return a > b ? a=b, 1 : 0; }
template <typename T> bool ckmax(T& a, const T& b) { return b > a ? a=b, 1 : 0; }
void dbg_out () { cerr << endl; }
template<typename Head, typename... Tail> void dbg_out (Head H, Tail... T) { cerr << H << " "; dbg_out(T...); }
// from @jacob.b.zhang :)
template<typename T> class SafeVector : public vector<T> {
public:
using vector<T>::vector;
typename vector<T>::reference operator[](size_t n) {
return vector<T>::at(n);
}
typename vector<T>::const_reference operator[](size_t n) const {
return vector<T>::at(n);
}
};
#ifdef DBG
#define dbg(desc, ...) cerr << '(' << desc << "): "; dbg_out(__VA_ARGS__);
#define vector SafeVector
#else
#define dbg(...)
#endif
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
struct minTree {
typedef int T;
static constexpr T unit = INT_MAX;
T f(T a, T b) { return min(a, b); } // (any associative fn)
vector<T> s; int n;
minTree(int n = 0, T def = unit) : s(2*n, def), n(n) {}
void update(int pos, T val) {
for (s[pos += n] = val; pos /= 2;)
s[pos] = f(s[pos * 2], s[pos * 2 + 1]);
}
T query(int b, int e) { // query [b, e)
T ra = unit, rb = unit;
for (b += n, e += n; b < e; b /= 2, e /= 2) {
if (b % 2) ra = f(ra, s[b++]);
if (e % 2) rb = f(s[--e], rb);
}
return f(ra, rb);
}
};
struct maxTree {
typedef int T;
static constexpr T unit = INT_MIN;
T f(T a, T b) { return max(a, b); } // (any associative fn)
vector<T> s; int n;
maxTree(int n = 0, T def = unit) : s(2*n, def), n(n) {}
void update(int pos, T val) {
for (s[pos += n] = val; pos /= 2;)
s[pos] = f(s[pos * 2], s[pos * 2 + 1]);
}
T query(int b, int e) { // query [b, e)
T ra = unit, rb = unit;
for (b += n, e += n; b < e; b /= 2, e /= 2) {
if (b % 2) ra = f(ra, s[b++]);
if (e % 2) rb = f(s[--e], rb);
}
return f(ra, rb);
}
};
struct sumTree {
typedef int T;
static constexpr T unit = 0;
T f(T a, T b) { return a+b; } // (any associative fn)
vector<T> s; int n;
sumTree(int n = 0, T def = unit) : s(2*n, def), n(n) {}
void update(int pos, T val) {
for (s[pos += n] = val; pos /= 2;)
s[pos] = f(s[pos * 2], s[pos * 2 + 1]);
}
T query(int b, int e) { // query [b, e)
T ra = unit, rb = unit;
for (b += n, e += n; b < e; b /= 2, e /= 2) {
if (b % 2) ra = f(ra, s[b++]);
if (e % 2) rb = f(s[--e], rb);
}
return f(ra, rb);
}
};
const int MX = 1<<20;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int t; cin >> t;
while (t--) {
ll n, m; cin >> n >> m;
string s; cin >> s;
maxTree t1(n);
minTree t2(n);
sumTree t3(n);
int total = 0;
F0R(i, n) {
int x = 1;
if (s[i] == '-') x = -1;
total += x;
t1.update(i, total);
t2.update(i, total);
t3.update(i, x);
}
F0R(i, m) {
int a, b; cin >> a >> b;
a--;
int lo = min(0, t2.query(0, a)), hi = max(0, t1.query(0, a));
int sum = t3.query(a, b);
dbg(lo, hi, sum);
if (b < n) {
ckmin(lo, t2.query(b, n)-sum);
ckmax(hi, t1.query(b, n)-sum);
}
dbg(lo, hi);
cout << hi-lo+1 << nl;
}
}
return 0;
}
| [
"lucasxia01@gmail.com"
] | lucasxia01@gmail.com |
87b699099a512c428ef12f6fdc2f8cc641c73cb9 | 51635684d03e47ebad12b8872ff469b83f36aa52 | /external/gcc-12.1.0/libstdc++-v3/testsuite/23_containers/set/85965.cc | 946a4abe84f50650b8e42e38bf916a7b6a9bd95d | [
"LGPL-2.1-only",
"GPL-3.0-only",
"GCC-exception-3.1",
"GPL-2.0-only",
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"Zlib",
"LicenseRef-scancode-public-domain"
] | permissive | zhmu/ananas | 8fb48ddfe3582f85ff39184fc7a3c58725fe731a | 30850c1639f03bccbfb2f2b03361792cc8fae52e | refs/heads/master | 2022-06-25T10:44:46.256604 | 2022-06-12T17:04:40 | 2022-06-12T17:04:40 | 30,108,381 | 59 | 8 | Zlib | 2021-09-26T17:30:30 | 2015-01-31T09:44:33 | C | UTF-8 | C++ | false | false | 1,161 | cc | // Copyright (C) 2019-2022 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// 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
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// { dg-do compile { target c++11 } }
#include <set>
struct Base { };
struct Derived; // derives from Base, but incomplete at this point
struct Foo
{
// PR libstdc++/85965
std::set<Derived*, std::less<Base*>> s;
};
std::size_t
test01(std::set<Derived*, std::less<Base*>> s)
{
// these operations should not require the comparison object
auto copy = s;
copy = s;
return s.size();
}
| [
"rink@rink.nu"
] | rink@rink.nu |
d470a558b18bfca538bd449cce7753be714203bf | 8a2b0eed5de488898f161e0cbb492aa015fe9c28 | /Kiwi-Engine/Kiwi-Engine/Core/MD5ModelFactory.cpp | 06d98e22d67f1535a0362f83eb97d0c92eb09ef5 | [] | no_license | nicoawalker/Kiwi-Engine | 5ded0273806d481381699396d9d4eb8ed2b974cd | f51c9e13ba3fddbe29ca672d96443ab091fa054b | refs/heads/master | 2021-01-20T23:27:06.419846 | 2017-11-06T22:59:32 | 2017-11-06T22:59:32 | 42,185,047 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,293 | cpp | #include "MD5ModelFactory.h"
#include "TextureFactory.h"
#include "Scene.h"
#include "EngineRoot.h"
#include "..\Graphics\DirectX.h"
#include "../Graphics/OBJImporter.h"
#include "..\Graphics\Mesh.h"
#include "../Graphics/MD5Model.h"
#include "..\Graphics\MD5Importer.h"
#include "../DirectXTK/DDSTextureLoader.h"
#include <sstream>
#include <iostream>
#include <fstream>
namespace Kiwi
{
std::wstring MD5ModelFactory::ObjectType = L"MD5Model";
void MD5ModelFactory::_CreateAsset( std::vector<std::unique_ptr<Kiwi::IAsset>>& _createdAssets, std::wstring assetName, const Kiwi::StringPair& parameters )
{
auto itr = parameters.find( L"ModelFile" );
if( itr != parameters.end() )
{
MD5Importer importer;
MD5Data data;
std::unique_ptr<MD5Model> loadedModel = nullptr;
std::wstring error = importer.Import( data, itr->second );
if( error.compare( L"" ) != 0 )
{
throw Kiwi::Exception( L"MD5ModelFactory::_CreateAsset", L"An error occured loading MD5 model \"" + assetName + L"\": " + error + L"\n" );
}
loadedModel = std::make_unique<MD5Model>( assetName, data.vertices, data.indices, data.subsets, data.joints, data.weights );
loadedModel->AddProperty( L"ModelFile", itr->second );
_createdAssets.push_back( std::move( loadedModel ) );
}
}
} | [
"nicoawalker@gmail.com"
] | nicoawalker@gmail.com |
09478208620f1aea4be44800ccdbd6b130ed5434 | 88302a33b04b1ec1b97250ee6dbcf3ddd48898a2 | /mfc_gdi_gif0/stdafx.cpp | 94c4dadf9f6e866d258e08dff767eb12e4656498 | [] | no_license | ys0uyno/mfc_gif_demo | bde5aa88e0dd6359308ac94df368f93519aee3db | b6b3b25ffb14d29e9e29f2f4367f10e26f7065f2 | refs/heads/master | 2020-03-19T23:06:24.122718 | 2018-06-12T01:46:46 | 2018-06-12T01:46:46 | 136,994,018 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 206 | cpp |
// stdafx.cpp : source file that includes just the standard includes
// mfc_gdi_gif0.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"ys0uyno@163.com"
] | ys0uyno@163.com |
bd88500f57a58fc672c465d844b04e77e7610f42 | bd7d4cbf62e25c958ce2a028835e754f4011ec77 | /01. Array/05. Move all negative numbers to beginning and positive to end with constant extra space.cpp | 416ea0c4f638b09eb5a4cea1731bf5ff48459324 | [] | no_license | sahilgoyals1999/Love-Babber-DSA-450 | fa1d817d2d2a5fec8fb179a1cf2d0b0b063e43c9 | 0052da206aca196ef8e5b043b6e70ea736aef3f7 | refs/heads/main | 2023-04-10T00:08:13.067069 | 2021-04-19T11:48:14 | 2021-04-19T11:48:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 647 | cpp | // https://www.geeksforgeeks.org/move-negative-numbers-beginning-positive-end-constant-extra-space/
// T.C => O(n), S.C => O(1)
void shiftall(int a[], int left, int right) {
while (left <= right) {
// if the left and the right elements are negative
if (a[left] < 0 && a[right] < 0) left++;
// if the left pointer element is positive and the right pointer element is negative
else if (a[left] > 0 && a[right] < 0) {
int temp = a[left];
a[left] = a[right];
a[right] = temp;
left++;
right--;
}
// if both the elements are positive
else if (a[left] > 0 && a[right] > 0) right--;
else {
left++;
right--;
}
}
} | [
"sahilgoyals1999@users.noreply.github.com"
] | sahilgoyals1999@users.noreply.github.com |
fb496c0fa26249031cc2507803923e43bf08e007 | b9f9350d744d5f653c896df22f1510fae59d6a85 | /P2_4.cpp | 4b6994c6c359845b427f0fd876472b1e80ee84d6 | [] | no_license | dxinl/EssentialCppPractice | 51424593c73859a9a307b6429c5e2657780d5e67 | c1ff8be039752e1cecbfc36c7ee0825e4f8cbf14 | refs/heads/master | 2020-03-14T15:18:54.536516 | 2018-05-02T14:44:55 | 2018-05-02T14:44:55 | 131,673,103 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 623 | cpp | #include <iostream>
#include <vector>
using namespace std;
const vector<int>* pentagonal(int size)
{
static vector<int> elems;
if (size <= 0)
return &elems;
for (int i = elems.size(); i < size; i++)
{
int tmp = i * (3 * i - 1) / 2;
cout << tmp << ' ';
elems.push_back(tmp);
}
cout << endl;
return &elems;
}
int get(const vector<int> &v, int index)
{
if (index < 0 || index >= v.size()) return -1;
return v.at(index);
}
int main()
{
const vector<int>* v = pentagonal(8);
cout << get(*v, -1) << endl;
cout << get(*v, 2) << endl;
cout << get(*v, 8) << endl;
}
| [
"907667336@qq.com"
] | 907667336@qq.com |
a29740290f75652aaffa8c1be5273c42a3f1f1ec | b89e61151aa5643caf8568c46fe216cd0bd893e7 | /third_party/myelin-arduino-hardware/samd/variants/arcflash/variant.cpp | d9e7b9017318f5c41a79f1de9a8a6b87f174d30b | [
"LGPL-2.1-or-later",
"Apache-2.0"
] | permissive | isabella232/myelin-acorn-electron-hardware | bbc37b78c5d2dd509f6ffe61f2928e4180627e67 | d0539b43ff7073ceea2f438aac671c3d81e15e17 | refs/heads/main | 2023-09-03T19:57:18.499874 | 2021-07-20T07:24:33 | 2021-07-20T07:24:33 | 417,777,280 | 0 | 0 | Apache-2.0 | 2021-10-16T09:18:33 | 2021-10-16T09:18:32 | null | UTF-8 | C++ | false | false | 18,602 | cpp | /*
Copyright (c) 2014-2015 Arduino LLC. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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 GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* + Pin number + ZERO Board pin | PIN | Label/Name | Comments (* is for default peripheral in use)
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | | Digital Low | | |
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | 0 | 0 -> RX | PA11 | | EIC/EXTINT[11] ADC/AIN[19] PTC/X[3] *SERCOM0/PAD[3] SERCOM2/PAD[3] TCC0/WO[3] TCC1/WO[1]
* | 1 | 1 <- TX | PA10 | | EIC/EXTINT[10] ADC/AIN[18] PTC/X[2] *SERCOM0/PAD[2] TCC0/WO[2] TCC1/WO[0]
* | 2 | 2 | PA14 | | EIC/EXTINT[14] SERCOM2/PAD[2] SERCOM4/PAD[2] TC3/WO[0] TCC0/WO[4]
* | 3 | ~3 | PA09 | | EIC/EXTINT[9] ADC/AIN[17] PTC/X[1] SERCOM0/PAD[1] SERCOM2/PAD[1] *TCC0/WO[1] TCC1/WO[3]
* | 4 | ~4 | PA08 | | EIC/NMI ADC/AIN[16] PTC/X[0] SERCOM0/PAD[0] SERCOM2/PAD[0] *TCC0/WO[0] TCC1/WO[2]
* | 5 | ~5 | PA15 | | EIC/EXTINT[15] SERCOM2/PAD[3] SERCOM4/PAD[3] *TC3/WO[1] TCC0/WO[5]
* | 6 | ~6 | PA20 | | EIC/EXTINT[4] PTC/X[8] SERCOM5/PAD[2] SERCOM3/PAD[2] *TCC0/WO[6]
* | 7 | 7 | PA21 | | EIC/EXTINT[5] PTC/X[9] SERCOM5/PAD[3] SERCOM3/PAD[3] TCC0/WO[7]
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | | Digital High | | |
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | 8 | ~8 | PA06 | | EIC/EXTINT[6] ADC/AIN[6] AC/AIN[2] PTC/Y[4] SERCOM0/PAD[2] *TCC1/WO[0]
* | 9 | ~9 | PA07 | | EIC/EXTINT[7] ADC/AIN[7] AC/AIN[3] PTC/Y[5] SERCOM0/PAD[3] *TCC1/WO[1]
* | 10 | ~10 | PA18 | | EIC/EXTINT[2] PTC/X[6] +SERCOM1/PAD[2] SERCOM3/PAD[2] *TC3/WO[0] TCC0/WO[2]
* | 11 | ~11 | PA16 | | EIC/EXTINT[0] PTC/X[4] +SERCOM1/PAD[0] SERCOM3/PAD[0] *TCC2/WO[0] TCC0/WO[6]
* | 12 | ~12 | PA19 | | EIC/EXTINT[3] PTC/X[7] +SERCOM1/PAD[3] SERCOM3/PAD[3] TC3/WO[1] *TCC0/WO[3]
* | 13 | ~13 | PA17 | LED | EIC/EXTINT[1] PTC/X[5] +SERCOM1/PAD[1] SERCOM3/PAD[1] *TCC2/WO[1] TCC0/WO[7]
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | | Analog Connector | | |
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | 14 | A0 | PA02 | A0 | EIC/EXTINT[2] *ADC/AIN[0] DAC/VOUT PTC/Y[0]
* | 15 | A1 | PB08 | A1 | EIC/EXTINT[8] *ADC/AIN[2] PTC/Y[14] SERCOM4/PAD[0] TC4/WO[0]
* | 16 | A2 | PB09 | A2 | EIC/EXTINT[9] *ADC/AIN[3] PTC/Y[15] SERCOM4/PAD[1] TC4/WO[1]
* | 17 | A3 | PA04 | A3 | EIC/EXTINT[4] *ADC/AIN[4] AC/AIN[0] PTC/Y[2] SERCOM0/PAD[0] TCC0/WO[0]
* | 18 | A4 | PA05 | A4 | EIC/EXTINT[5] *ADC/AIN[5] AC/AIN[1] PTC/Y[5] SERCOM0/PAD[1] TCC0/WO[1]
* | 19 | A5 | PB02 | A5 | EIC/EXTINT[2] *ADC/AIN[10] PTC/Y[8] SERCOM5/PAD[0]
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | | Wire | | |
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | 20 | SDA | PA22 | SDA | EIC/EXTINT[6] PTC/X[10] *SERCOM3/PAD[0] SERCOM5/PAD[0] TC4/WO[0] TCC0/WO[4]
* | 21 | SCL | PA23 | SCL | EIC/EXTINT[7] PTC/X[11] *SERCOM3/PAD[1] SERCOM5/PAD[1] TC4/WO[1] TCC0/WO[5]
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | |SPI (Legacy ICSP) | | |
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | 22 | 1 | PA12 | MISO | EIC/EXTINT[12] SERCOM2/PAD[0] *SERCOM4/PAD[0] TCC2/WO[0] TCC0/WO[6]
* | | 2 | | 5V0 |
* | 23 | 4 | PB10 | MOSI | EIC/EXTINT[10] *SERCOM4/PAD[2] TC5/WO[0] TCC0/WO[4]
* | 24 | 3 | PB11 | SCK | EIC/EXTINT[11] *SERCOM4/PAD[3] TC5/WO[1] TCC0/WO[5]
* | | 5 | | RESET |
* | | 6 | | GND |
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | | LEDs | | |
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | 25 | | PB03 | RX |
* | 26 | | PA27 | TX |
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | | USB | | |
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | 27 | | PA28 | USB_HOST_ENABLE | EIC/EXTINT[8]
* | 28 | | PA24 | USB_NEGATIVE | *USB/DM
* | 29 | | PA25 | USB_POSITIVE | *USB/DP
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | | EDBG | | |
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | 30 | | PB22 | EDBG_UART TX | *SERCOM5/PAD[2]
* | 31 | | PB23 | EDBG_UART RX | *SERCOM5/PAD[3]
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | 32 | | PA22 | EDBG_SDA | Pin 20 (SDA)
* | 33 | | PA23 | EDBG_SCL | Pin 21 (SCL)
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | 34 | | PA19 | EDBG_MISO | EIC/EXTINT[3] *SERCOM1/PAD[3] SERCOM3/PAD[3] TC3/WO[1] TCC0/WO[3]
* | 35 | | PA16 | EDBG_MOSI | EIC/EXTINT[0] *SERCOM1/PAD[0] SERCOM3/PAD[0] TCC2/WO[0] TCC0/WO[6]
* | 36 | | PA18 | EDBG_SS | EIC/EXTINT[2] *SERCOM1/PAD[2] SERCOM3/PAD[2] TC3/WO[0] TCC0/WO[2]
* | 37 | | PA17 | EDBG_SCK | EIC/EXTINT[1] *SERCOM1/PAD[1] SERCOM3/PAD[1] TCC2/WO[1] TCC0/WO[7]
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | 38 | ATN | PA13 | EDBG_GPIO0 | EIC/EXTINT[13] SERCOM2/PAD[1] SERCOM4/PAD[1] *TCC2/WO[1] TCC0/WO[7]
* | 39 | | PA21 | EDBG_GPIO1 | Pin 7
* | 40 | | PA06 | EDBG_GPIO2 | Pin 8
* | 41 | | PA07 | EDBG_GPIO3 | Pin 9
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | | | | |
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | | GND | | |
* | 42 | AREF | PA03 | | EIC/EXTINT[3] *[ADC|DAC]/VREFA ADC/AIN[1] PTC/Y[1]
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | |32.768KHz Crystal | | |
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
* | | | PA00 | XIN32 | EIC/EXTINT[0] SERCOM1/PAD[0] TCC2/WO[0]
* | | | PA01 | XOUT32 | EIC/EXTINT[1] SERCOM1/PAD[1] TCC2/WO[1]
* +------------+------------------+--------+-----------------+--------------------------------------------------------------------------------------------------------
*/
#include "variant.h"
/*
* Pins descriptions
*/
const PinDescription g_APinDescription[]=
{
// 0..13 - Digital pins
// ----------------------
// 0/1 - SERCOM/UART (Serial1)
{ PORTB, 9, PIO_SERCOM_ALT, (PIN_ATTR_PWM|PIN_ATTR_TIMER), ADC_Channel3, PWM4_CH1, TC4_CH1, EXTERNAL_INT_9 }, // GPIO 0 / A6 / UART RX
{ PORTB, 8, PIO_SERCOM_ALT, (PIN_ATTR_PWM|PIN_ATTR_TIMER), ADC_Channel2, PWM4_CH0, TC4_CH0, EXTERNAL_INT_8 }, // GPIO 1 / A7 / UART TX
// 2..12
// Digital Low
{ PORTB, 2, PIO_SERCOM_ALT, 0, ADC_Channel10, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_2 }, // GPIO D2 / A5 / SDA
{ PORTB, 3, PIO_SERCOM_ALT, PIN_ATTR_DIGITAL, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_3 }, // GPIO D3 / A4 / SCL
{ PORTA, 28, PIO_COM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_8 }, // GPIO D4 / Left Button
{ PORTA, 14, PIO_DIGITAL, (PIN_ATTR_DIGITAL), No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_14 }, // GPIO D5 / Right button
{ PORTA, 5, PIO_TIMER, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), ADC_Channel5, PWM0_CH1, TCC0_CH1, EXTERNAL_INT_5 }, // GPIO D6 / A1
{ PORTA, 15, PIO_TIMER, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), No_ADC_Channel, PWM3_CH1, TC3_CH1, EXTERNAL_INT_15 }, // GPIO D7 / Slide Switch
// Digital High
{ PORTB, 23, PIO_DIGITAL, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // GPIO D8 / NeoPixels
{ PORTA, 6, PIO_TIMER, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), ADC_Channel6, PWM1_CH0, TCC1_CH0, EXTERNAL_INT_6 }, // GPIO D9 / A2
{ PORTA, 7, PIO_TIMER, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), ADC_Channel7, PWM1_CH1, TCC1_CH1, EXTERNAL_INT_7 }, // GPIO D10 / A3
{ PORTA, 30, PIO_DIGITAL, PIN_ATTR_DIGITAL, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // GPIO D11 / Speaker Shutdown
{ PORTA, 2, PIO_DIGITAL, (PIN_ATTR_DIGITAL|PIN_ATTR_ANALOG), ADC_Channel0, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_2 }, // GPIO D12 / VOut / A0
// 13 (LED)
{ PORTA, 17, PIO_TIMER, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), No_ADC_Channel, PWM2_CH1, TCC2_CH1, EXTERNAL_INT_1 }, // GPIO D13 / Red LED
// 14..24 - Analog pins
// --------------------
{ PORTA, 2, PIO_ANALOG, (PIN_ATTR_DIGITAL|PIN_ATTR_ANALOG), ADC_Channel0, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_2 }, // A0 (Same as D12)
{ PORTA, 5, PIO_ANALOG, (PIN_ATTR_DIGITAL|PIN_ATTR_ANALOG), ADC_Channel5, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_5 }, // A1 (Same as D6)
{ PORTA, 6, PIO_ANALOG, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER|PIN_ATTR_ANALOG), ADC_Channel6, PWM1_CH0, TCC1_CH0, EXTERNAL_INT_6 }, // A2 (Same as D9)
{ PORTA, 7, PIO_ANALOG, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER|PIN_ATTR_ANALOG), ADC_Channel7, PWM1_CH1, TCC1_CH1, EXTERNAL_INT_7 }, // A3 (Same as D10
{ PORTB, 3, PIO_ANALOG, (PIN_ATTR_DIGITAL|PIN_ATTR_ANALOG), ADC_Channel11, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // A4 (Same as D3)
{ PORTB, 2, PIO_ANALOG, (PIN_ATTR_DIGITAL|PIN_ATTR_ANALOG), ADC_Channel10, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_2 }, // A5 (Same as D2)
{ PORTB, 9, PIO_ANALOG, (PIN_ATTR_DIGITAL|PIN_ATTR_ANALOG|PIN_ATTR_PWM|PIN_ATTR_TIMER), ADC_Channel3, PWM4_CH1, TC4_CH1, EXTERNAL_INT_9 }, // A6 (Same as D0)
{ PORTB, 8, PIO_ANALOG, (PIN_ATTR_DIGITAL|PIN_ATTR_ANALOG|PIN_ATTR_PWM|PIN_ATTR_TIMER), ADC_Channel2, PWM4_CH0, TC4_CH0, EXTERNAL_INT_8 }, // A7 (Same as D1)
{ PORTA, 11, PIO_ANALOG, (PIN_ATTR_DIGITAL|PIN_ATTR_ANALOG), ADC_Channel19, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_11 }, // A8 / Light Sensor
{ PORTA, 9, PIO_ANALOG, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER|PIN_ATTR_ANALOG), ADC_Channel17, PWM0_CH1, TCC0_CH1, EXTERNAL_INT_9 }, // A9 / Thermistor
{ PORTA, 4, PIO_ANALOG, (PIN_ATTR_DIGITAL|PIN_ATTR_ANALOG), ADC_Channel4, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_4 }, // A10 Proximity
// GPIO 25 / IR Transmit
{ PORTA, 23, PIO_DIGITAL, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), No_ADC_Channel, PWM4_CH1, TC4_CH1, EXTERNAL_INT_7 }, // GPIO D25 - IR Transmitter
// GPIO 26 / IR Remote in
{ PORTA, 12, PIO_DIGITAL, PIN_ATTR_DIGITAL, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_12 }, // GPIO D26 - IR Receiver
// GPIO 27 (LIS IRQ)
{ PORTA, 13, PIO_PWM, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM), No_ADC_Channel, PWM0_CH5, NOT_ON_TIMER, EXTERNAL_INT_13 }, // EIC/EXTINT[13] *TCC2/WO[1] TCC0/WO[7]
// GPIO 28 & 29 internal I2C (original xtal pins)
{ PORTA, 0, PIO_SERCOM_ALT, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // Internal SDA
{ PORTA, 1, PIO_SERCOM_ALT, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // Internal SCL
// GPIO 30, 31, 32 Internal SPI
{ PORTA, 16, PIO_SERCOM_ALT, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // MISO: SERCOM3/PAD[0]
{ PORTA, 21, PIO_SERCOM_ALT, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM), No_ADC_Channel, PWM0_CH7, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // SCK: SERCOM3/PAD[3]
{ PORTA, 20, PIO_SERCOM_ALT, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER_ALT), No_ADC_Channel, PWM0_CH6, TCC0_CH6, EXTERNAL_INT_4 }, // MOSI: SERCOM3/PAD[2]
// GPIO 33 (Flash CS)
{ PORTB, 22, PIO_DIGITAL, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE },
// GPIO 34 (I2S SCK)
{ PORTA, 10, PIO_DIGITAL, (PIN_ATTR_DIGITAL|PIN_ATTR_ANALOG), ADC_Channel18, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_10 },
// GPIO 35 (I2S Datain)
{ PORTA, 8, PIO_DIGITAL, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER|PIN_ATTR_ANALOG), ADC_Channel16, PWM0_CH0, TCC0_CH0, EXTERNAL_INT_NMI },
// 36..38 - USB
// --------------------
{ PORTA, 22, PIO_SERCOM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // GPIO 29 - Host USB (not used)
{ PORTA, 24, PIO_COM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // USB/DM
{ PORTA, 25, PIO_COM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // USB/DP
} ;
extern "C" {
unsigned int PINCOUNT_fn() {
return (sizeof(g_APinDescription) / sizeof(g_APinDescription[0]));
}
}
const void* g_apTCInstances[TCC_INST_NUM+TC_INST_NUM]={ TCC0, TCC1, TCC2, TC3, TC4, TC5 } ;
// Multi-serial objects instantiation
SERCOM sercom0( SERCOM0 ) ;
SERCOM sercom1( SERCOM1 ) ;
SERCOM sercom2( SERCOM2 ) ;
SERCOM sercom3( SERCOM3 ) ;
SERCOM sercom4( SERCOM4 ) ;
SERCOM sercom5( SERCOM5 ) ;
Uart Serial1( &sercom4, PIN_SERIAL1_RX, PIN_SERIAL1_TX, PAD_SERIAL1_RX, PAD_SERIAL1_TX ) ;
void SERCOM4_Handler()
{
Serial1.IrqHandler();
}
| [
"pp@myelin.nz"
] | pp@myelin.nz |
f606ffc5c87d6d3d93706ed44c1a94cd10ab008e | 08b71476193080e05a4de24fe73be1c002d04e2b | /jungol/api-problem/3071_1.cc | 0890af26ef5866c51a1e59e0008fa47029b56fe3 | [] | no_license | sency90/allCode | 7321fae92f0a733742ea6831c43ce35898b1d915 | 1e3ad5f6ba929631641d7889c57a398d89be9419 | refs/heads/master | 2022-10-23T00:32:09.833362 | 2022-09-27T16:33:31 | 2022-09-27T16:33:31 | 43,256,814 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,559 | cc | //teacher.cpp
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#define N 30000
using namespace std;
struct data {
int num, base, state;
bool operator<(const data &r) const {
if (state != r.state) return state < r.state;
return base > r.base;
}
} a[30005], b[30005];
int Min(int x, int y) { return x < y ? x : y; }
int Max(int x, int y) { return x > y ? x : y; }
void rotate(int t[4][4])
{
int i, j, tmp[4][4];
for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) {
tmp[i][j] = t[j][3 - i];
}
for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) {
t[i][j] = tmp[i][j];
}
}
int incode(int t[4][4])
{
int value = 0;
for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) {
value = value * 3 + t[i][j];
}
return value;
}
void push(int t[4][4], int p)
{
int i, j, maxh = 0, minh = 11;
int aa[4][4], bb[4][4];
for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) {
maxh = Max(maxh, t[i][j]);
minh = Min(minh, t[i][j]);
}
a[p].num = b[p].num = p;
a[p].base = minh, b[p].base = maxh;
for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) {
aa[i][j] = t[i][j] - minh;
bb[i][j] = maxh - t[i][3 - j];
}
a[p].state = incode(aa);
b[p].state = incode(bb);
for (i = 0; i < 3; i++) {
rotate(aa), rotate(bb);
a[p].state = Min(a[p].state, incode(aa));
b[p].state = Min(b[p].state, incode(bb));
}
}
void radix_sort(data a[])
{
int cnt[7500] = { 0 }, i;
data b[30005], c[30005];
for (i = 0; i < N; i++) cnt[a[i].base-1]++;
for (i = 9; i > 0; i--) cnt[i] += cnt[i + 1];
for (i = 0; i < N; i++) b[cnt[a[i].base]++] = a[i];
for (i = 0; i <= 10; i++) cnt[i] = 0;
for (i = 0; i < N; i++) cnt[b[i].state % 7000 + 1]++;
for (i = 2; i <= 7000; i++) cnt[i] += cnt[i - 1];
for (i = 0; i < N; i++) c[cnt[b[i].state % 7000]++] = b[i];
for (i = 0; i <= 7000; i++) cnt[i] = 0;
for (i = 0; i < N; i++) cnt[c[i].state / 7000 + 1]++;
for (i = 2; i <= 7000; i++) cnt[i] += cnt[i - 1];
for (i = 0; i < N; i++) a[cnt[c[i].state / 7000]++] = c[i];
}
int makeTree(int module[][4][4])
{
int ans = 0, i, an = 0, bn = 0, chk[30005] = { 0 };
for (i = 0; i < N; i++) {
push(module[i], i);
}
radix_sort(a);
radix_sort(b);
//sort(a, a + N);
//sort(b, b + N);
//while (a[an].state == 0) ans += a[an++].base;
while (an < N && bn < N) {
if (chk[a[an].num]) an++;
else if (chk[b[bn].num]) bn++;
else if (a[an].num == b[bn].num) an++;
else if (a[an].state > b[bn].state) bn++;
else if (a[an].state < b[bn].state) an++;
else {
ans += a[an].base + b[bn].base;
chk[a[an++].num] = chk[b[bn++].num] = 1;
}
}
return ans;
}
| [
"sency90@gmail.com"
] | sency90@gmail.com |
e1cc9633ec20f7c8e953c9d828a755b25acbbb43 | b1510c8a90eacc254b508ff3db249e86e524965f | /src/omicron/component/light/PointLight.cpp | 642d8bf24ad10a462526f8d2c4d042556cbe51e3 | [] | no_license | DavidSaxon/RuleCore | 724535aefb4ed33a11a7b205173860820b6a7df3 | 8614c09f14e6464236137ba4a4bcc54a575c49f0 | refs/heads/master | 2021-01-10T20:32:26.166825 | 2015-08-31T08:50:11 | 2015-08-31T08:50:11 | 41,568,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,682 | cpp | #include "PointLight.hpp"
namespace omi {
//------------------------------------------------------------------------------
// CONSTRUCTOR
//------------------------------------------------------------------------------
PointLight::PointLight(
const std::string& id,
omi::Transform* transform,
float power,
const glm::vec3& colour,
float constantAtt,
float linearAtt,
float quadraticAtt )
:
Light ( id, transform, power, colour ),
m_constantAtt ( constantAtt ),
m_linearAtt ( linearAtt ),
m_quadraticAtt( quadraticAtt )
{
}
//------------------------------------------------------------------------------
// PUBLIC MEMBER FUNCTIONS
//------------------------------------------------------------------------------
//-----------------------------------GETTERS------------------------------------
light::Type PointLight::getLightType() const
{
return light::POINT;
}
float PointLight::getConstantAtt() const
{
return m_constantAtt;
}
float PointLight::getLinearAtt() const
{
return m_linearAtt;
}
float PointLight::getQuadraticAtt() const
{
return m_quadraticAtt;
}
//-----------------------------------SETTERS------------------------------------
void PointLight::setConstantAtt( float constantAtt )
{
m_constantAtt = constantAtt;
}
void PointLight::setLinearAtt( float linearAtt )
{
m_linearAtt = linearAtt;
}
void PointLight::setQuadraticAtt( float quadraticAtt )
{
m_quadraticAtt = quadraticAtt;
}
} // namespace omi
| [
"davidesaxon@gmail.com"
] | davidesaxon@gmail.com |
feb6e1d5b7f0054745417bf1ca7c59270ef7a691 | 59471cde9fa76fca5de76a472ce7c3b14a69b2af | /talkingclock.cpp | 2708f4a719b02834d58b53cc84ec2e600b234742 | [] | no_license | sorianog/Talking-Clock | cd0149e07caa57e57026079d1c7a647c9fcc4291 | 46210678bae1b6bcc66e4a7ad8c85e74add6f504 | refs/heads/master | 2016-09-14T14:00:18.379233 | 2016-04-27T16:19:57 | 2016-04-27T16:19:57 | 56,942,849 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,962 | cpp | #include "talkingclock.h"
#include "ui_talkingclock.h"
#include <QtGui>
#include "imageviewer.h"
#include "encapsulator.h"
/**
* SE3910 Spring 2016 - Lab 6
* Author: sorianog, wattsz
*
* @brief TalkingClock::TalkingClock - The main window containg all widgets
*/
TalkingClock::TalkingClock()
{
capsule = new Encapsulator(0 , this);
setCentralWidget(capsule);
createActions();
createMenus();
setWindowTitle(tr("Talking Clock By Gerald Soriano & Zach Watts"));
resize(500, 400);
}
/**
* @brief TalkingClock::about
*/
void TalkingClock::about()
{
QMessageBox::about(this, tr("About Talking Clock"),
tr("<p>The <b>Talking Clock</b> is an application "
"created for MSOE's SE3910 - Real Time Systems class. "
"The main features of the app are viewing images,"
"displaying the current time, and speaking the time."
"</p><p>This app uses QT's Image Viewer and Digital Clock examples.</p>"));
}
/**
* @brief TalkingClock::createActions
* Connect all the necessary actions to their respective slots
*/
void TalkingClock::createActions()
{
openAct = new QAction(tr("&Open..."), this);
openAct->setShortcut(tr("Ctrl+O"));
connect(openAct, SIGNAL(triggered()), capsule->getImageViewer(), SLOT(open()));
printAct = new QAction(tr("&Print..."), this);
printAct->setShortcut(tr("Ctrl+P"));
printAct->setEnabled(false);
connect(printAct, SIGNAL(triggered()), capsule->getImageViewer(), SLOT(print()));
exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcut(tr("Ctrl+Q"));
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
zoomInAct = new QAction(tr("Zoom &In (25%)"), this);
zoomInAct->setShortcut(tr("Ctrl++"));
zoomInAct->setEnabled(false);
connect(zoomInAct, SIGNAL(triggered()), capsule->getImageViewer(), SLOT(zoomIn()));
zoomOutAct = new QAction(tr("Zoom &Out (25%)"), this);
zoomOutAct->setShortcut(tr("Ctrl+-"));
zoomOutAct->setEnabled(false);
connect(zoomOutAct, SIGNAL(triggered()), capsule->getImageViewer(), SLOT(zoomOut()));
normalSizeAct = new QAction(tr("&Normal Size"), this);
normalSizeAct->setShortcut(tr("Ctrl+S"));
normalSizeAct->setEnabled(false);
connect(normalSizeAct, SIGNAL(triggered()), capsule->getImageViewer(), SLOT(normalSize()));
fitToWindowAct = new QAction(tr("&Fit to Window"), this);
fitToWindowAct->setEnabled(false);
fitToWindowAct->setCheckable(true);
fitToWindowAct->setShortcut(tr("Ctrl+F"));
connect(fitToWindowAct, SIGNAL(triggered()), capsule->getImageViewer(), SLOT(fitToWindow()));
aboutAct = new QAction(tr("&About"), this);
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
aboutQtAct = new QAction(tr("About &Qt"), this);
connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
}
/**
* @brief TalkingClock::createMenus
* Construct the menu itmes for the main menu bar
*/
void TalkingClock::createMenus()
{
fileMenu = new QMenu(tr("&File"), this);
fileMenu->addAction(openAct);
fileMenu->addAction(printAct);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
viewMenu = new QMenu(tr("&View"), this);
viewMenu->addAction(zoomInAct);
viewMenu->addAction(zoomOutAct);
viewMenu->addAction(normalSizeAct);
viewMenu->addSeparator();
viewMenu->addAction(fitToWindowAct);
helpMenu = new QMenu(tr("&Help"), this);
helpMenu->addAction(aboutAct);
helpMenu->addAction(aboutQtAct);
menuBar()->addMenu(fileMenu);
menuBar()->addMenu(viewMenu);
menuBar()->addMenu(helpMenu);
}
/**
* @brief TalkingClock::updateActions
* Enable/disable the necessary actions
*/
void TalkingClock::updateActions()
{
zoomInAct->setEnabled(!fitToWindowAct->isChecked());
zoomOutAct->setEnabled(!fitToWindowAct->isChecked());
normalSizeAct->setEnabled(!fitToWindowAct->isChecked());
}
| [
"se3910@cs3841vm"
] | se3910@cs3841vm |
68c701c3aec260c2331a60b725f4f5a71a0dd9da | 9a1fba32fe46c41b450222e6f45408e53d9b6c23 | /tools/aapt2/XmlFlattener_test.cpp | 8915d2478b64c9eec6f3dd33bad35432b31b97a2 | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | FireHound/android_frameworks_base | 779dda285e75a615d75150b8c10c21d13fa3e731 | e9d54decbb07004f74e78b57f095f614362828b5 | refs/heads/mm | 2021-11-26T05:13:54.745879 | 2016-09-10T05:37:47 | 2016-12-18T06:50:12 | 64,948,641 | 4 | 38 | NOASSERTION | 2020-03-14T21:24:38 | 2016-08-04T16:06:28 | Java | UTF-8 | C++ | false | false | 9,555 | cpp | /*
* Copyright (C) 2015 The Android Open Source Project
*
* 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 "MockResolver.h"
#include "ResourceTable.h"
#include "ResourceValues.h"
#include "Util.h"
#include "XmlFlattener.h"
#include <androidfw/AssetManager.h>
#include <androidfw/ResourceTypes.h>
#include <gtest/gtest.h>
#include <sstream>
#include <string>
using namespace android;
namespace aapt {
namespace xml {
constexpr const char* kXmlPreamble = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
class XmlFlattenerTest : public ::testing::Test {
public:
virtual void SetUp() override {
mResolver = std::make_shared<MockResolver>(
std::make_shared<ResourceTable>(),
std::map<ResourceName, ResourceId>({
{ ResourceName{ u"android", ResourceType::kAttr, u"attr" },
ResourceId{ 0x01010000u } },
{ ResourceName{ u"android", ResourceType::kId, u"id" },
ResourceId{ 0x01020000u } },
{ ResourceName{ u"com.lib", ResourceType::kAttr, u"attr" },
ResourceId{ 0x01010001u } },
{ ResourceName{ u"com.lib", ResourceType::kId, u"id" },
ResourceId{ 0x01020001u } }}));
}
::testing::AssertionResult testFlatten(const std::string& in, ResXMLTree* outTree) {
std::stringstream input(kXmlPreamble);
input << in << std::endl;
SourceLogger logger(Source{ "test.xml" });
std::unique_ptr<Node> root = inflate(&input, &logger);
if (!root) {
return ::testing::AssertionFailure();
}
BigBuffer outBuffer(1024);
if (!flattenAndLink(Source{ "test.xml" }, root.get(), std::u16string(u"android"),
mResolver, {}, &outBuffer)) {
return ::testing::AssertionFailure();
}
std::unique_ptr<uint8_t[]> data = util::copy(outBuffer);
if (outTree->setTo(data.get(), outBuffer.size(), true) != NO_ERROR) {
return ::testing::AssertionFailure();
}
return ::testing::AssertionSuccess();
}
std::shared_ptr<IResolver> mResolver;
};
TEST_F(XmlFlattenerTest, ParseSimpleView) {
std::string input = R"EOF(
<View xmlns:android="http://schemas.android.com/apk/res/android"
android:attr="@id/id"
class="str"
style="@id/id">
</View>
)EOF";
ResXMLTree tree;
ASSERT_TRUE(testFlatten(input, &tree));
while (tree.next() != ResXMLTree::START_TAG) {
ASSERT_NE(tree.getEventType(), ResXMLTree::END_DOCUMENT);
ASSERT_NE(tree.getEventType(), ResXMLTree::BAD_DOCUMENT);
}
const StringPiece16 androidNs = u"http://schemas.android.com/apk/res/android";
const StringPiece16 attrName = u"attr";
ssize_t idx = tree.indexOfAttribute(androidNs.data(), androidNs.size(), attrName.data(),
attrName.size());
ASSERT_GE(idx, 0);
EXPECT_EQ(tree.getAttributeNameResID(idx), 0x01010000u);
EXPECT_EQ(tree.getAttributeDataType(idx), android::Res_value::TYPE_REFERENCE);
const StringPiece16 class16 = u"class";
idx = tree.indexOfAttribute(nullptr, 0, class16.data(), class16.size());
ASSERT_GE(idx, 0);
EXPECT_EQ(tree.getAttributeNameResID(idx), 0u);
EXPECT_EQ(tree.getAttributeDataType(idx), android::Res_value::TYPE_STRING);
EXPECT_EQ(tree.getAttributeData(idx), tree.getAttributeValueStringID(idx));
const StringPiece16 style16 = u"style";
idx = tree.indexOfAttribute(nullptr, 0, style16.data(), style16.size());
ASSERT_GE(idx, 0);
EXPECT_EQ(tree.getAttributeNameResID(idx), 0u);
EXPECT_EQ(tree.getAttributeDataType(idx), android::Res_value::TYPE_REFERENCE);
EXPECT_EQ((uint32_t) tree.getAttributeData(idx), 0x01020000u);
EXPECT_EQ(tree.getAttributeValueStringID(idx), -1);
while (tree.next() != ResXMLTree::END_DOCUMENT) {
ASSERT_NE(tree.getEventType(), ResXMLTree::BAD_DOCUMENT);
}
}
TEST_F(XmlFlattenerTest, ParseViewWithPackageAlias) {
std::string input = "<View xmlns:ns1=\"http://schemas.android.com/apk/res/android\"\n"
" xmlns:ns2=\"http://schemas.android.com/apk/res/android\"\n"
" ns1:attr=\"@ns2:id/id\">\n"
"</View>";
ResXMLTree tree;
ASSERT_TRUE(testFlatten(input, &tree));
while (tree.next() != ResXMLTree::END_DOCUMENT) {
ASSERT_NE(tree.getEventType(), ResXMLTree::BAD_DOCUMENT);
}
}
::testing::AssertionResult attributeNameAndValueEquals(ResXMLTree* tree, size_t index,
ResourceId nameId, ResourceId valueId) {
if (index >= tree->getAttributeCount()) {
return ::testing::AssertionFailure() << "index " << index << " is out of bounds ("
<< tree->getAttributeCount() << ")";
}
if (tree->getAttributeNameResID(index) != nameId.id) {
return ::testing::AssertionFailure()
<< "attribute at index " << index << " has ID "
<< ResourceId{ (uint32_t) tree->getAttributeNameResID(index) }
<< ". Expected ID " << nameId;
}
if (tree->getAttributeDataType(index) != Res_value::TYPE_REFERENCE) {
return ::testing::AssertionFailure() << "attribute at index " << index << " has value of "
<< "type " << std::hex
<< tree->getAttributeDataType(index) << std::dec
<< ". Expected reference (" << std::hex
<< Res_value::TYPE_REFERENCE << std::dec << ")";
}
if ((uint32_t) tree->getAttributeData(index) != valueId.id) {
return ::testing::AssertionFailure()
<< "attribute at index " << index << " has value " << "with ID "
<< ResourceId{ (uint32_t) tree->getAttributeData(index) }
<< ". Expected ID " << valueId;
}
return ::testing::AssertionSuccess();
}
TEST_F(XmlFlattenerTest, ParseViewWithShadowedPackageAlias) {
std::string input = "<View xmlns:app=\"http://schemas.android.com/apk/res/android\"\n"
" app:attr=\"@app:id/id\">\n"
" <View xmlns:app=\"http://schemas.android.com/apk/res/com.lib\"\n"
" app:attr=\"@app:id/id\"/>\n"
"</View>";
ResXMLTree tree;
ASSERT_TRUE(testFlatten(input, &tree));
while (tree.next() != ResXMLTree::START_TAG) {
ASSERT_NE(tree.getEventType(), ResXMLTree::BAD_DOCUMENT);
ASSERT_NE(tree.getEventType(), ResXMLTree::END_DOCUMENT);
}
ASSERT_TRUE(attributeNameAndValueEquals(&tree, 0u, ResourceId{ 0x01010000u },
ResourceId{ 0x01020000u }));
while (tree.next() != ResXMLTree::START_TAG) {
ASSERT_NE(tree.getEventType(), ResXMLTree::BAD_DOCUMENT);
ASSERT_NE(tree.getEventType(), ResXMLTree::END_DOCUMENT);
}
ASSERT_TRUE(attributeNameAndValueEquals(&tree, 0u, ResourceId{ 0x01010001u },
ResourceId{ 0x01020001u }));
}
TEST_F(XmlFlattenerTest, ParseViewWithLocalPackageAndAliasOfTheSameName) {
std::string input = "<View xmlns:android=\"http://schemas.android.com/apk/res/com.lib\"\n"
" android:attr=\"@id/id\"/>";
ResXMLTree tree;
ASSERT_TRUE(testFlatten(input, &tree));
while (tree.next() != ResXMLTree::START_TAG) {
ASSERT_NE(tree.getEventType(), ResXMLTree::BAD_DOCUMENT);
ASSERT_NE(tree.getEventType(), ResXMLTree::END_DOCUMENT);
}
// We expect the 'android:attr' to be converted to 'com.lib:attr' due to the namespace
// assignment.
// However, we didn't give '@id/id' a package, so it should use the default package
// 'android', and not be converted from 'android' to 'com.lib'.
ASSERT_TRUE(attributeNameAndValueEquals(&tree, 0u, ResourceId{ 0x01010001u },
ResourceId{ 0x01020000u }));
}
/*
* The device ResXMLParser in libandroidfw differentiates between empty namespace and null
* namespace.
*/
TEST_F(XmlFlattenerTest, NoNamespaceIsNotTheSameAsEmptyNamespace) {
std::string input = "<View xmlns:android=\"http://schemas.android.com/apk/res/android\"\n"
" package=\"android\"/>";
ResXMLTree tree;
ASSERT_TRUE(testFlatten(input, &tree));
while (tree.next() != ResXMLTree::START_TAG) {
ASSERT_NE(tree.getEventType(), ResXMLTree::BAD_DOCUMENT);
ASSERT_NE(tree.getEventType(), ResXMLTree::END_DOCUMENT);
}
const StringPiece16 kPackage = u"package";
EXPECT_GE(tree.indexOfAttribute(nullptr, 0, kPackage.data(), kPackage.size()), 0);
}
} // namespace xml
} // namespace aapt
| [
"adamlesinski@google.com"
] | adamlesinski@google.com |
4ea4c5434d054d70478aa4960d5b0a1a25b0461a | aea94ad9e99f813ccf0eb12ca0d34aa6a3b17163 | /expr.hh | 8ebf09b02b3ba897a1af52d79886bf0c06cfd599 | [] | no_license | prak-nv/glfdc | 478031b4ac684958ab53c29831e2399f97eb7498 | 007271a328dd1c4a5d3a6cfdb24c8621629f46c9 | refs/heads/master | 2023-05-08T01:55:50.733185 | 2021-06-01T12:06:17 | 2021-06-01T12:06:17 | 372,816,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,403 | hh | #pragma once
#include "sexpr.hh"
#include <cassert>
#include <map>
#include <vector>
namespace glfdc {
class ExprDAG;
// NB: Expr should not outlive ExprDAG, since stores index to;
struct Expr
{
const ExprDAG &dag_;
SExprRef subexpr_;
//std::string to_infix_notation() const
};
struct ExprDAG
{
std::map<uintptr_t, std::size_t> unbound_lookup_; // XXX: any mapping - rb-tree for now
std::vector<uintptr_t> unbound_values_;
std::vector<SExpr> unbound_exprs_;
std::vector<SExpr> internal_exprs_;
public:
SExprRef add_subexpr(SExpr expr)
{
auto &nodes = expr.is_unbound()? unbound_exprs_ : internal_exprs_;
size_t new_idx = nodes.size();
nodes.push_back(expr);
return expr.is_unbound()? SExprRef(LExprRef{new_idx}) : SExprRef(IExprRef{new_idx});
}
SExpr fetch(SExprRef e) const noexcept // O(1)
{
return (e.index() == 0)?
fetch(std::get<LExprRef>(e)) : fetch(std::get<IExprRef>(e));
}
SExpr fetch(LExprRef e) const noexcept
{
assert(e.index_ < unbound_exprs_.size());
return unbound_exprs_[e.index_];
}
SExpr fetch(IExprRef e) const noexcept
{
assert(e.index_ < internal_exprs_.size());
return internal_exprs_[e.index_];
}
uintptr_t get_binding(UnboundValue ubv) const noexcept // O(1)
{
assert(ubv.index_ < unbound_values_.size());
return unbound_values_[ubv.index_];
}
};
} // namespace glfdc
| [
"piotr.rak@gmail.com"
] | piotr.rak@gmail.com |
b1e18216b2ae360d85019a9ec71ee036ad781574 | fae26d601fe2b795fcd9ce40061bfb5db727ebf4 | /10191 - LongestNap/main.cpp | 918c49590331fda4427903f57c7ac8efd1255ffe | [] | no_license | phg1024/UVa | 5771caf2f9070abfab857b0b32db3a076fce7c3b | e27e4a67c80e716c87f266a68396ac5b5968345d | refs/heads/master | 2020-04-11T05:40:30.107452 | 2014-07-17T07:49:33 | 2014-07-17T07:49:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,132 | cpp | #include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
struct Time
{
Time(){}
Time(int h, int m):hh(h), mm(m){}
bool operator==(const Time& t) const
{
return hh == t.hh && mm == t.mm;
}
bool operator<(const Time& t) const
{
if( hh < t.hh ) return true;
else if( hh == t.hh )
return mm < t.mm;
else
return false;
}
int timeTo(const Time& t) const
{
return (t.hh - hh) * 60 + t.mm - mm;
}
int hh;
int mm;
friend istream& operator>>(istream& is, Time& t);
friend ostream& operator<<(ostream& os, const Time& t);
};
struct Period
{
Period(){}
Period(const Time& t1, const Time& t2):start(t1), end(t2){}
bool operator<(const Period& g) const
{
if( start == g.start )
return end < g.end;
else
return start < g.start;
}
int length() const
{
return start.timeTo(end);
}
Time start, end;
};
istream& operator>>(istream& is, Time& t)
{
char c;
is >> t.hh >> c >> t.mm;
return is;
}
ostream& operator<<(ostream& os, const Time& t)
{
os << t.hh << ':' << ((t.mm<10)?"0":"") << t.mm;
return os;
}
int main()
{
int day = 0;
int ntasks;
while( cin >> ntasks )
{
cin.ignore();
Period tasks[102];
Time start(10, 0), end(18, 0);
tasks[0] = Period(start, start);
string buf;
for(int i=1;i<=ntasks;i++)
{
Time t1, t2;
getline(cin, buf);
stringstream ss;
ss << buf;
ss >> t1 >> t2;
tasks[i] = Period(t1, t2);
}
tasks[ntasks+1] = Period(end, end);
std::sort(tasks, tasks+ntasks+2, std::less<Period>());
int longestNap = 0;
int longestIdx = 0;
for(int i=0;i<ntasks+1;i++)
{
int slot = tasks[i].end.timeTo(tasks[i+1].start);
if( slot > longestNap )
{
longestNap = slot;
longestIdx = i;
}
}
cout << "Day #" << (++day) << ": the longest nap starts at " << tasks[longestIdx].end << " and will last for ";
if( longestNap >= 60 )
{
cout << (longestNap / 60) << " hours and " << (longestNap % 60) << " minutes." << endl;
}
else
{
cout << longestNap << " minutes." << endl;
}
}
return 0;
}
| [
"peihongguo@gmail.com"
] | peihongguo@gmail.com |
78d414362044542c6828f4302cecef60d2d33366 | 68a46346d9d354626524e723f5c9c854791e0d67 | /include/AST/DeclNode.h | cf0f3d476b15b832dcac105be85ed3349371a495 | [
"MIT"
] | permissive | asksky3/StaticScript | 5c8985703ea923241d635c36a7db1f972c4f98bc | 99b07cd685ddf10074d06cfd04a6eb24a66adf5a | refs/heads/master | 2023-01-11T18:37:40.832666 | 2020-11-16T11:52:32 | 2020-11-16T11:52:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,130 | h | #pragma once
#include "AST/Node.h"
#include "AST/TypeNode.h"
#include "AST/StmtNode.h"
#include "AST/ExprNode.h"
enum class VarModifier {
Let, Const, Param
};
/// 声明节点
class DeclNode : public Node {
public:
~DeclNode() override = default;
};
/// 变量声明节点
class VarDeclNode : public DeclNode {
public:
explicit VarDeclNode();
VarDeclNode(
VarModifier modifier,
String name,
const SharedPtr<BuiltinTypeNode> &type
);
VarDeclNode(
VarModifier modifier,
String name,
const SharedPtr<BuiltinTypeNode> &type,
const SharedPtr<ExprNode> &initVal
);
~VarDeclNode() override = default;
void bindChildrenInversely() override;
void accept(const SharedPtr<ASTVisitor> &visitor) override;
bool isConstant() const;
VarModifier modifier;
String name;
SharedPtr<BuiltinTypeNode> type = nullptr;
SharedPtr<ExprNode> initVal = nullptr;
// 当前变量声明的alloca/load ir
LLVMValue *code = nullptr;
};
/// 函数参数声明节点
class ParmVarDeclNode : public VarDeclNode {
public:
ParmVarDeclNode(const String &name, const SharedPtr<BuiltinTypeNode> &type);
~ParmVarDeclNode() override = default;
void accept(const SharedPtr<ASTVisitor> &visitor) override;
};
/// 函数声明节点
class FunctionDeclNode : public DeclNode {
public:
static SharedPtrMap<String, FunctionDeclNode> getBuiltinFunctions();
FunctionDeclNode(
String name,
const SharedPtrVector<ParmVarDeclNode> ¶ms,
const SharedPtr<BuiltinTypeNode> &returnType,
const SharedPtr<CompoundStmtNode> &body
);
~FunctionDeclNode() override = default;
void bindChildrenInversely() override;
void accept(const SharedPtr<ASTVisitor> &visitor) override;
String name;
SharedPtrVector<ParmVarDeclNode> params;
SharedPtr<BuiltinTypeNode> returnType = nullptr;
SharedPtr<CompoundStmtNode> body = nullptr;
SharedPtr<Scope> internalScope = nullptr;
SharedPtr<ReturnStmtNode> refReturnStmt;
};
| [
"pyyzcwg2833@outlook.com"
] | pyyzcwg2833@outlook.com |
1a18937bb450878c43ff4e61ad504a3d6f49d2b2 | 44f04b8f2b6c0dba51f1e998985d3a9e8540715f | /Gym/100733/E/E.cpp | edf2debf44e0fcf31eaffaa150997d62d95366a1 | [] | no_license | GuessEver/ACMICPCSolutions | 2dd318a45939711eff1dd208cffc05a029b38130 | 909927778efd77ca9ec8e18aed3ff22c167d2a33 | refs/heads/master | 2020-05-18T20:52:32.359955 | 2015-11-04T08:31:43 | 2015-11-04T08:31:43 | 29,720,059 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 268 | cpp | #include <cstdio>
#include <algorithm>
#define MAXN 1000000
using namespace std;
int a[MAXN+5];
int main() {
int n, k;
scanf("%d%d", &n, &k);
for (int i = 0; i < n; i++) {
scanf("%d", a+i);
}
sort(a , a+n);
printf("%d\n", a[k-1]);
}
| [
"jiangzh777@163.com"
] | jiangzh777@163.com |
873a5185500a7481c58972fed705ef6a1b18b420 | 859f36088b8d44364a8778419818aa7860672474 | /src/slt_runtime_glfw/render/uniform.h | c13d3dcdba82072d1e03c42eb694f1a7c63fd243 | [
"BSL-1.0"
] | permissive | FrancoisChabot/slt_engine | 88856e71f966c74c70edfb3653f0981cbc2b795b | 7b84c842456c93b1062caa82b4f13d56a892aa8c | refs/heads/master | 2021-09-04T11:53:28.925590 | 2018-01-18T13:32:07 | 2018-01-18T13:32:07 | 108,151,463 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 908 | h | #ifndef SLT_RUNTIME_GLFW_UNIFORM_H
#define SLT_RUNTIME_GLFW_UNIFORM_H
#include "slt_runtime/drawing/uniform.h"
#include "slt_runtime_glfw/render/gl_includes.h"
namespace slt {
namespace render {
class GLFWUniformBlock : public slt::render::UniformBlock {
public:
GLFWUniformBlock(std::size_t size, GLuint loc)
: size_(size), location_(loc) {}
std::size_t size() const { return size_; }
GLuint location() const { return location_; }
private:
GLuint location_;
const std::size_t size_;
};
class GLFWUniformBuffer : public slt::render::UniformBuffer {
public:
GLFWUniformBuffer(std::shared_ptr<GLFWUniformBlock> b);
~GLFWUniformBuffer();
std::shared_ptr<GLFWUniformBlock> const& block() const { return block_; }
GLuint ubo() const {
return ubo_;
}
private:
std::shared_ptr<GLFWUniformBlock> block_;
GLuint ubo_;
};
}
}
#endif
| [
"francois.chabot.dev@gmail.com"
] | francois.chabot.dev@gmail.com |
5d2f74627b620e135006986c14ae7ea1764da2a3 | 0ce2b9cf1406e923890fcabf9f3b63b999949bb8 | /流媒体/RTSP/code/rtsp-publish/src/main.cpp | 8d0e54c77c4b9712d77680e20750b2b08710fdfb | [] | no_license | demon060/MultiMedia | be97d2feef469747d033229d12b73325ab00f954 | 40694666a91d5a715d8c701ccbebe7a30e64ca73 | refs/heads/main | 2023-08-30T03:45:49.259191 | 2021-10-17T23:26:31 | 2021-10-17T23:26:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,304 | cpp | #include <iostream>
#include "dlog.h"
#include "messagequeue.h"
#include "pushwork.h"
using namespace std;
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavutil/audio_fifo.h>
#include <libavutil/opt.h>
#include <libswresample/swresample.h>
}
//减少缓冲 ffplay.exe -i rtmp://xxxxxxx -fflags nobuffer
// 减少码流分析时间 ffplay.exe -i rtmp://xxxxxxx -analyzeduration 1000000 单位为微秒
// ffplay -i rtsp://192.168.2.132/live/livestream -fflags nobuffer -analyzeduration 1000000 -rtsp_transport udp
//#define RTSP_URL "rtsp://111.229.231.225/live/livestream"
#define RTSP_URL "rtsp://192.168.2.132/live/livestream"
// ffmpeg -re -i rtsp_test_hd.flv -vcodec copy -acodec copy -f flv -y rtsp://111.229.231.225/live/livestream
// ffmpeg -re -i rtsp_test_hd.flv -vcodec copy -acodec copy -f flv -y rtsp://192.168.1.12/live/livestream
//// ffmpeg -re -i 1920x832_25fps.flv -vcodec copy -acodec copy -f flv -y rtsp://111.229.231.225/live/livestream
int main() {
cout << "Hello World!" << endl;
init_logger("rtsp_push.log", S_INFO);
MessageQueue *msg_queue_ = new MessageQueue();
// for(int i = 0; i < 5; i++)
{
// LogInfo("test pushwork:%d", i);
if (!msg_queue_) {
LogError("new MessageQueue() failed");
return -1;
}
PushWork push_work(msg_queue_);
Properties properties;
// 音频test模式
properties.SetProperty("audio_test", 1); // 音频测试模式
properties.SetProperty("input_pcm_name", "buweishui_48000_2_s16le.pcm");
// 麦克风采样属性
properties.SetProperty("mic_sample_fmt", AV_SAMPLE_FMT_S16);
properties.SetProperty("mic_sample_rate", 48000);
properties.SetProperty("mic_channels", 2);
// 音频编码属性
properties.SetProperty("audio_sample_rate", 48000);
properties.SetProperty("audio_bitrate", 64 * 1024);
properties.SetProperty("audio_channels", 2);
//视频test模式
properties.SetProperty("video_test", 1);
properties.SetProperty("input_yuv_name", "720x480_25fps_420p.yuv");
// 桌面录制属性
properties.SetProperty("desktop_x", 0);
properties.SetProperty("desktop_y", 0);
properties.SetProperty("desktop_width", 720); //测试模式时和yuv文件的宽度一致
properties.SetProperty("desktop_height", 480); //测试模式时和yuv文件的高度一致
// properties.SetProperty("desktop_pixel_format", AV_PIX_FMT_YUV420P);
properties.SetProperty("desktop_fps", 25); //测试模式时和yuv文件的帧率一致
// 视频编码属性
properties.SetProperty("video_bitrate", 512 * 1024); // 设置码率
// 配置rtsp
// 1.url
// 2.udp
properties.SetProperty("rtsp_url", RTSP_URL);
properties.SetProperty("rtsp_transport", "tcp"); // udp or tcp
properties.SetProperty("rtsp_timeout", 15000);
properties.SetProperty("rtsp_max_queue_duration", 1000);
if (push_work.Init(properties) != RET_OK) {
LogError("PushWork init failed");
return -1;
}
int count = 0;
AVMessage msg;
int ret = 0;
while (true) {
// std::this_thread::sleep_for(std::chrono::milliseconds(1000));
ret = msg_queue_->msg_queue_get(&msg, 1000);
if (1 == ret) {
switch (msg.what) {
case MSG_RTSP_ERROR:
LogError("MSG_RTSP_ERROR error:%d", msg.arg1);
break;
case MSG_RTSP_QUEUE_DURATION:
LogError("MSG_RTSP_QUEUE_DURATION a:%d, v:%d", msg.arg1, msg.arg2);
break;
default:
break;
}
}
LogInfo("count:%d, ret:%d", count, ret);
if (count++ > 100) {
printf("main break\n");
break;
}
}
msg_queue_->msg_queue_abort();
}
delete msg_queue_;
LogInfo("main finish");
return 0;
}
| [
"zxsong13@gamil.com"
] | zxsong13@gamil.com |
da38fdd0baef4ba32843ec0fdc3988522e5f8ac3 | c101053b25768777e82c297b1ae42fa935f1d73e | /Day19/Day19/Day19.cpp | 0010d6c03fc0bddf9944a16f92981b739f86ae72 | [] | no_license | MBraedley/Advent-Of-Code-2019 | 2c3f1d3990108bdb14691ba84b959eb9b08015c4 | e48defc7e9706cb3161f1703e6edc4beef371954 | refs/heads/master | 2020-09-26T10:02:05.068195 | 2019-12-27T18:10:42 | 2019-12-27T18:10:42 | 226,232,453 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,564 | cpp | // Day19.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "IntcodeComputer.h"
#include "readerwriterqueue.h"
#include <iostream>
#include <deque>
int main()
{
auto input = IntcodeComputer::RaedProgram("input.txt");
auto program = input;
std::pair<std::int64_t, std::int64_t> testPoint = { 0, 0 };
std::deque<std::int64_t> inputValues;
//for (std::int64_t x = 0; x < 50; x++)
//{
// for (std::int64_t y = 0; y < 50; y++)
// {
// inputValues.push_back(x);
// inputValues.push_back(y);
// }
//}
std::int64_t count = 0;
std::int64_t totalCount = 0;
bool inTractorBeam = false;
IntcodeComputer part1(program);
part1.SetInputCallback([&]()->std::int64_t
{
std::int64_t value = inputValues.front();
inputValues.pop_front();
return value;
});
part1.SetOutputCallback([&](std::int64_t value)
{
count += value;
inTractorBeam = value == 1;
});
std::int64_t rowStart = 0;
for (std::int64_t y = 0; y < 50; y++)
{
count = 0;
for (std::int64_t x = 0; x < 50; x++)
{
if (x >= rowStart && (count == 0 || inTractorBeam))
{
inputValues.push_back(x);
inputValues.push_back(y);
part1.Reset(program);
part1.RunProgram();
std::cout << (inTractorBeam ? "#" : ".");
}
else
std::cout << ".";
}
totalCount += count;
std::cout << std::endl;
}
std::cout << totalCount << std::endl;
///////////////////////////////////////////////////////////////////
std::int64_t width = 0;
std::int64_t height = 0;
testPoint = { 1820, 1976 };
while (true)
{
inputValues.clear();
count = 0;
inTractorBeam = true;
for (std::int64_t x = testPoint.first; x < testPoint.first + 110; x++)
{
inputValues.push_back(x);
inputValues.push_back(testPoint.second);
}
while (!inputValues.empty() && inTractorBeam)
{
part1.Reset(program);
part1.RunProgram();
}
width = count;
inputValues.clear();
count = 0;
inTractorBeam = true;
for (std::int64_t y = testPoint.second; y < testPoint.second + 110; y++)
{
inputValues.push_back(testPoint.first);
inputValues.push_back(y);
}
while (!inputValues.empty() && inTractorBeam)
{
part1.Reset(program);
part1.RunProgram();
}
height = count;
inputValues.clear();
if (width == 100 && height == 100)
{
std::cout << testPoint.first * 10000 + testPoint.second;
return 0;
}
if (width == height)
{
testPoint.first++;
testPoint.second++;
}
else if (width > height)
testPoint.first++;
else
testPoint.second++;
}
}
| [
"mike.braedley@gmail.com"
] | mike.braedley@gmail.com |
d8c877589fdc23749df575563a1bb7d4b35e2d5b | c5ed2d57496cafa1b10925814b4fc670fb9d84af | /Opensankore/build-Sankore_3.1-Unnamed-Release/build/win32/release/moc/moc_UBDocumentToolsPalette.cpp | 68746a57514df56feaa1f925a35a3739a308ffdf | [] | no_license | Educabile/Ardesia | 5f5175fef5d7a15ea79469901bdd4c068cc8fec7 | 9b7b0bfe1c89e89c0ef28f93f6b1e0ac8c348230 | refs/heads/master | 2020-03-31T17:16:50.538146 | 2018-10-10T12:34:43 | 2018-10-10T12:34:43 | 152,416,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,611 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'UBDocumentToolsPalette.h'
**
** Created: Fri 4. May 12:30:56 2018
** by: The Qt Meta Object Compiler version 63 (Qt 4.8.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../../../../Sankore-3.1/src/gui/UBDocumentToolsPalette.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'UBDocumentToolsPalette.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_UBDocumentToolsPalette[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_UBDocumentToolsPalette[] = {
"UBDocumentToolsPalette\0"
};
void UBDocumentToolsPalette::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObjectExtraData UBDocumentToolsPalette::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject UBDocumentToolsPalette::staticMetaObject = {
{ &UBActionPalette::staticMetaObject, qt_meta_stringdata_UBDocumentToolsPalette,
qt_meta_data_UBDocumentToolsPalette, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &UBDocumentToolsPalette::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *UBDocumentToolsPalette::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *UBDocumentToolsPalette::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_UBDocumentToolsPalette))
return static_cast<void*>(const_cast< UBDocumentToolsPalette*>(this));
return UBActionPalette::qt_metacast(_clname);
}
int UBDocumentToolsPalette::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = UBActionPalette::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"salvatore.naddeo@€ducabile.it"
] | salvatore.naddeo@€ducabile.it |
4415098944eb80bb9a415375d7fe696a85ea7488 | 514fe7a620a7109e8c390c964a3449d4ee71a9cc | /Area of Triangle a Formula.cpp | 0186a94c808c691d49c595ace14dcc617a98adef | [] | no_license | Nikitaprobuz9/cpp | 6b407efaeeeb7fd334161b2887c5581b99684923 | ef4f5396f5d80461622e85e725421fde1bea956d | refs/heads/main | 2023-03-12T06:36:12.343554 | 2021-02-27T10:47:11 | 2021-02-27T10:47:11 | 335,940,807 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 280 | cpp | /*WAP to calculate the area of triangle*/
#include <iostream>
using namespace std;
int triangle()
{
int r, b = 12, h = 5;
r = 0.5 * b * h;
return (r);
}
int main()
{
int a =triangle();
cout << "Area of triangle is : " << a << endl; // prints !!!Hello World!!!
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
fce02c58cc7ec55bac29caf027d23283f2144bc5 | 55b5bb05ea8e287ac072d07f0745a8f88df63410 | /boost_1_59_0/libs/math/test/test_gamma.cpp | 83b7e4e2a66e441b6ab656f1ae8ed7835d421181 | [
"MIT",
"BSL-1.0"
] | permissive | lbryio/lbrycrd-dependencies | 88e187ad0b42acbfc4c13bae84dcab9338b3c830 | 48c993eb77aed55029ae66bc48d970218a357f9e | refs/heads/master | 2020-04-02T04:08:35.350210 | 2018-02-28T14:42:50 | 2018-02-28T14:42:50 | 63,198,671 | 5 | 6 | MIT | 2018-02-28T14:42:50 | 2016-07-12T23:17:26 | HTML | UTF-8 | C++ | false | false | 14,164 | cpp | // (C) Copyright John Maddock 2006.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pch_light.hpp>
#include "test_gamma.hpp"
//
// DESCRIPTION:
// ~~~~~~~~~~~~
//
// This file tests the functions tgamma and lgamma, and the
// function tgamma1pm1. There are two sets of tests, spot
// tests which compare our results with selected values computed
// using the online special function calculator at
// functions.wolfram.com, while the bulk of the accuracy tests
// use values generated with NTL::RR at 1000-bit precision
// and our generic versions of these functions.
//
// Note that when this file is first run on a new platform many of
// these tests will fail: the default accuracy is 1 epsilon which
// is too tight for most platforms. In this situation you will
// need to cast a human eye over the error rates reported and make
// a judgement as to whether they are acceptable. Either way please
// report the results to the Boost mailing list. Acceptable rates of
// error are marked up below as a series of regular expressions that
// identify the compiler/stdlib/platform/data-type/test-data/test-function
// along with the maximum expected peek and RMS mean errors for that
// test.
//
void expected_results()
{
//
// Define the max and mean errors expected for
// various compilers and platforms.
//
const char* largest_type;
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
if(boost::math::policies::digits<double, boost::math::policies::policy<> >() == boost::math::policies::digits<long double, boost::math::policies::policy<> >())
{
largest_type = "(long\\s+)?double";
}
else
{
largest_type = "long double";
}
#else
largest_type = "(long\\s+)?double";
#endif
//
// G++ on Darwin: results are just slightly worse than we might hope for
// but still pretty good:
//
add_expected_result(
".*", // compiler
".*", // stdlib
"Mac OS", // platform
largest_type, // test type(s)
"factorials", // test data group
"boost::math::tgamma", 100, 15); // test function
//
// G++ On Win32:
//
add_expected_result(
"GNU.*", // compiler
".*", // stdlib
"Win32.*", // platform
largest_type, // test type(s)
"factorials", // test data group
"boost::math::tgamma", 100, 15); // test function
add_expected_result(
"GNU.*", // compiler
".*", // stdlib
"Win32.*", // platform
"real_concept", // test type(s)
"factorials", // test data group
"boost::math::tgamma", 600, 200); // test function
add_expected_result(
"GNU.*", // compiler
".*", // stdlib
"Win32.*", // platform
"real_concept", // test type(s)
"near.*", // test data group
"boost::math::tgamma", 200, 100); // test function
//
// G++ on Linux, result vary a bit by processor type,
// on Itanium results are *much* better than listed here,
// but x86 appears to have much less accurate std::pow
// that throws off the results:
//
add_expected_result(
".*", // compiler
".*", // stdlib
"linux", // platform
largest_type, // test type(s)
"factorials", // test data group
"boost::math::tgamma", 600, 200); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"linux", // platform
largest_type, // test type(s)
"factorials", // test data group
"boost::math::lgamma", 30, 10); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"linux", // platform
largest_type, // test type(s)
"near (1|2|-10)", // test data group
"boost::math::tgamma", 10, 5); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"linux", // platform
largest_type, // test type(s)
"near (1|2|-10)", // test data group
"boost::math::lgamma", 50, 50); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"linux", // platform
largest_type, // test type(s)
"tgamma1pm1.*", // test data group
"boost::math::tgamma1pm1", 50, 15); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"linux", // platform
"real_concept", // test type(s)
"factorials", // test data group
"boost::math::tgamma", 600, 100); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"linux", // platform
"real_concept", // test type(s)
"near (0|-55)", // test data group
"boost::math::(t|l)gamma", 300, 150); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"linux", // platform
"real_concept", // test type(s)
"tgamma1pm1.*", // test data group
"boost::math::tgamma1pm1", 40, 10); // test function
//
// HP-UX results:
//
add_expected_result(
".*", // compiler
".*", // stdlib
"HP-UX", // platform
largest_type, // test type(s)
"factorials", // test data group
"boost::math::tgamma", 5, 4); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"HP-UX", // platform
largest_type, // test type(s)
"near (0|-55)", // test data group
"boost::math::tgamma", 10, 5); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"HP-UX", // platform
largest_type, // test type(s)
"near (1|2|-10)", // test data group
"boost::math::lgamma", 250, 200); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"HP-UX", // platform
"real_concept", // test type(s)
"factorials", // test data group
"boost::math::lgamma", 50, 20); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"HP-UX", // platform
"real_concept", // test type(s)
"tgamma1pm1.*", // test data group
"boost::math::tgamma1pm1", 200, 80); // test function
//
// Tru64:
//
add_expected_result(
".*Tru64.*", // compiler
".*", // stdlib
".*", // platform
"real_concept", // test type(s)
"factorials", // test data group
"boost::math::lgamma", 50, 20); // test function
//
// Sun OS:
//
add_expected_result(
".*", // compiler
".*", // stdlib
"Sun.*", // platform
largest_type, // test type(s)
"factorials", // test data group
"boost::math::tgamma", 300, 50); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"Sun.*", // platform
"real_concept", // test type(s)
"factorials", // test data group
"boost::math::tgamma", 300, 50); // test function
//
// Catch all cases come last:
//
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
largest_type, // test type(s)
"factorials", // test data group
"boost::math::tgamma", 4, 1); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
largest_type, // test type(s)
"factorials", // test data group
"boost::math::lgamma", 9, 1); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
largest_type, // test type(s)
"near (0|-55)", // test data group
"boost::math::(t|l)gamma", 200, 100); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
largest_type, // test type(s)
"near (1|2|-10)", // test data group
"boost::math::tgamma", 10, 5); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
largest_type, // test type(s)
"near (1|2|-10)", // test data group
"boost::math::lgamma", 14, 7); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
largest_type, // test type(s)
"tgamma1pm1.*", // test data group
"boost::math::tgamma1pm1", 30, 9); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
"real_concept", // test type(s)
"factorials", // test data group
"boost::math::tgamma", 600, 100); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
"real_concept", // test type(s)
"factorials", // test data group
"boost::math::lgamma", 200, 20); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
"real_concept", // test type(s)
"near.*", // test data group
"boost::math::tgamma", 300, 100); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
"real_concept", // test type(s)
"near.*", // test data group
"boost::math::lgamma", 40000000, 10000000); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
"real_concept", // test type(s)
"tgamma1pm1.*", // test data group
"boost::math::tgamma1pm1", 20, 5); // test function
//
// Finish off by printing out the compiler/stdlib/platform names,
// we do this to make it easier to mark up expected error rates.
//
std::cout << "Tests run with " << BOOST_COMPILER << ", "
<< BOOST_STDLIB << ", " << BOOST_PLATFORM << std::endl;
}
BOOST_AUTO_TEST_CASE( test_main )
{
expected_results();
BOOST_MATH_CONTROL_FP;
#ifndef BOOST_MATH_BUGGY_LARGE_FLOAT_CONSTANTS
test_spots(0.0F, "float");
#endif
test_spots(0.0, "double");
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
test_spots(0.0L, "long double");
test_spots(boost::math::concepts::real_concept(0.1), "real_concept");
#endif
#ifndef BOOST_MATH_BUGGY_LARGE_FLOAT_CONSTANTS
test_gamma(0.1F, "float");
#endif
test_gamma(0.1, "double");
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
test_gamma(0.1L, "long double");
#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS
#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))
test_gamma(boost::math::concepts::real_concept(0.1), "real_concept");
#endif
#endif
#else
std::cout << "<note>The long double tests have been disabled on this platform "
"either because the long double overloads of the usual math functions are "
"not available at all, or because they are too inaccurate for these tests "
"to pass.</note>" << std::cout;
#endif
}
| [
"jobevers@users.noreply.github.com"
] | jobevers@users.noreply.github.com |
359c3081cf1ce7e372d6a2c3ee589187a5e13a93 | 9ae2faba6b1b5fbd272cb093a9ceae41718bb348 | /Project3/Main.cpp | e684f0c36418c191379e158525224cba58f5ca09 | [] | no_license | nasiddiqui2/Student-Attendance-Management-UI | 01098e49dfb29dcd4a2822336724335d379301ab | 68af7b12962f7d758f4b16eff9da1b7cf9524156 | refs/heads/master | 2021-06-08T13:45:08.556887 | 2016-11-29T22:51:45 | 2016-11-29T22:51:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 253 | cpp | #include "Main.h"
using namespace System;
using namespace System::Windows::Forms;
[STAThread]
int main()
{
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
Application::Run(gcnew(Project3::Main));
return 0;
} | [
"nsiddiqui590@gmail.com"
] | nsiddiqui590@gmail.com |
61a2e0427723835f5ec01149a9c51cb3da1b0c46 | 1c10b37de3de1a8de1e371bb06fdd00c9d9906f3 | /week3_Q2.cpp | 4c53fecf4d4f6b0d0633cc87c08fba2c6606ac6b | [] | no_license | ananyapati/LiftOffC-Solutions | ec29b4cf1181dad1e9a30928c136599354c79f12 | 820653b1df353e4cb94e0434c4fc34b5cff5797b | refs/heads/main | 2023-03-29T11:17:26.754554 | 2021-04-04T15:14:53 | 2021-04-04T15:14:53 | 336,987,629 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 307 | cpp | #include<stdio.h>
int Fact(int n);
int main()
{
int num,Factorial;
printf("\nEnter a number:");
scanf("%d",&num);
Factorial= Fact(num);
printf("\nThe factorial of the number is:%d",Factorial);
return 0;
}
int Fact(int n)
{
int f=1,i;
for(i=1;i<=n;i++)
{
f*=i;
}
return f;
}
| [
"noreply@github.com"
] | noreply@github.com |
92ad1555496d41112d07e82178a43cae0bcfa9f6 | a2eca70a9a7f2dbf586adb9251d8ddc3ed453497 | /src/studio/gui/trees/metadatatree.cpp | 0cfc3d2749905eee4d99e518af8aff5d5900e5e6 | [] | no_license | eshikafe/wxSynfig | 03654379bfc6872cd82bfa2bbb928d4fd9f7a38f | 35573f9c125dc645b1320172bce968a4512fa8f4 | refs/heads/master | 2021-06-15T02:30:59.511757 | 2019-11-20T07:26:19 | 2019-11-20T07:26:19 | 51,330,475 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,576 | cpp | /* === S Y N F I G ========================================================= */
/*! \file metadatatree.cpp
** \brief Template File
**
** $Id$
**
** \legal
** Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
** Copyright (c) 2011 Carlos López
**
** This package is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License as
** published by the Free Software Foundation; either version 2 of
** the License, or (at your option) any later version.
**
** This package 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.
** \endlegal
*/
/* ========================================================================= */
/* === H E A D E R S ======================================================= */
#ifdef USING_PCH
# include "pch.h"
#else
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "trees/metadatatree.h"
#include <ETL/misc>
#include "general.h"
#endif
/* === U S I N G =========================================================== */
using namespace std;
using namespace etl;
using namespace synfig;
using namespace studio;
/* === M A C R O S ========================================================= */
/* === G L O B A L S ======================================================= */
/* === P R O C E D U R E S ================================================= */
/* === M E T H O D S ======================================================= */
MetaDataTree::MetaDataTree()
{
{
Gtk::TreeView::Column* column = Gtk::manage( new Gtk::TreeView::Column(_("Key")) );
cell_renderer_key = Gtk::manage( new Gtk::CellRendererText() );
column->pack_start(*cell_renderer_key,true);
column->add_attribute(cell_renderer_key->property_text(), model.key);
cell_renderer_key->signal_edited().connect(sigc::mem_fun(*this,&studio::MetaDataTree::on_edited_key));
column->set_reorderable();
column->set_resizable();
column->set_clickable();
column->set_sort_column(model.key);
append_column(*column);
}
{
Gtk::TreeView::Column* column = Gtk::manage( new Gtk::TreeView::Column(_("Data")) );
cell_renderer_data = Gtk::manage( new Gtk::CellRendererText() );
column->pack_start(*cell_renderer_data,true);
column->add_attribute(cell_renderer_data->property_text(), model.data);
cell_renderer_data->signal_edited().connect(sigc::mem_fun(*this,&studio::MetaDataTree::on_edited_data));
column->set_reorderable();
column->set_resizable();
column->set_clickable(false);
append_column(*column);
}
set_rules_hint();
add_events(Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK);
}
MetaDataTree::~MetaDataTree()
{
}
void
MetaDataTree::set_model(Glib::RefPtr<MetaDataTreeStore> metadata_tree_store)
{
metadata_tree_store_=metadata_tree_store;
Gtk::TreeView::set_model(metadata_tree_store);
}
void
MetaDataTree::set_editable(bool x)
{
editable_=x;
if(editable_)
cell_renderer_data->property_editable()=true;
else
cell_renderer_data->property_editable()=false;
}
void
MetaDataTree::on_edited_key(const Glib::ustring&path_string,synfig::String key)
{
Gtk::TreePath path(path_string);
const Gtk::TreeRow row(*(get_model()->get_iter(path)));
if(row) row[model.key]=key;
}
void
MetaDataTree::on_edited_data(const Glib::ustring&path_string,synfig::String data)
{
Gtk::TreePath path(path_string);
const Gtk::TreeRow row(*(get_model()->get_iter(path)));
if(row)row[model.data]=data;
}
| [
"eshikafe@gmail.com"
] | eshikafe@gmail.com |
fb975cb506696ddc6cf3f5b87f0c3690bfab4470 | bfb26ad296040f77fd94fa4220f41ec78507b73d | /Number theory/is_prime.cpp | 1c75d56a8100193214e3d48959bdab4dbbf47e96 | [] | no_license | mine691/procon-library | d56197f6b1b49e4dd2a4b33e4d93650d06dff3e7 | deb88d1c0c160286b209f2fcab01f3a8463768f4 | refs/heads/master | 2021-07-18T18:52:14.736672 | 2020-06-10T10:42:41 | 2020-06-10T10:42:41 | 175,916,320 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 196 | cpp | template <typename T>
bool is_prime(T N)
{
if (N < 2)
return false;
for (T i = 2; i * i <= N; ++i)
{
if (N % i == 0)
return false;
}
return true;
}
| [
"noreply@github.com"
] | noreply@github.com |
9dc3cb2a76f970168191eca2ce0a92aa1d59d5c1 | 8514036949180b1432fa8807c1435b320cfdc857 | /src/key.h | b1962ff846e9ae813017a67bb9521dd70a5e6b62 | [
"MIT"
] | permissive | msgpo/Rodentcoin | 6a212290748a8f2cace728bcb9799fc6f192c9ea | 5c2d82cd23ec3dc714dd15ba2aaa39d0b4c67914 | refs/heads/master | 2021-05-28T22:38:59.132905 | 2015-03-10T12:56:53 | 2015-03-10T12:56:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,955 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Copyright (c) 2013-2014 Rodentcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file LICENCE or http://www.opensource.org/licenses/mit-license.php
#ifndef BITCOIN_KEY_H
#define BITCOIN_KEY_H
#include <stdexcept>
#include <vector>
#include "allocators.h"
#include "serialize.h"
#include "uint256.h"
#include "util.h"
#include <openssl/ec.h> // for EC_KEY definition
// secp160k1
// const unsigned int PRIVATE_KEY_SIZE = 192;
// const unsigned int PUBLIC_KEY_SIZE = 41;
// const unsigned int SIGNATURE_SIZE = 48;
//
// secp192k1
// const unsigned int PRIVATE_KEY_SIZE = 222;
// const unsigned int PUBLIC_KEY_SIZE = 49;
// const unsigned int SIGNATURE_SIZE = 57;
//
// secp224k1
// const unsigned int PRIVATE_KEY_SIZE = 250;
// const unsigned int PUBLIC_KEY_SIZE = 57;
// const unsigned int SIGNATURE_SIZE = 66;
//
// secp256k1:
// const unsigned int PRIVATE_KEY_SIZE = 279;
// const unsigned int PUBLIC_KEY_SIZE = 65;
// const unsigned int SIGNATURE_SIZE = 72;
//
// see www.keylength.com
// script supports up to 75 for single byte push
class key_error : public std::runtime_error
{
public:
explicit key_error(const std::string& str) : std::runtime_error(str) {}
};
/** A reference to a CKey: the Hash160 of its serialized public key */
class CKeyID : public uint160
{
public:
CKeyID() : uint160(0) { }
CKeyID(const uint160 &in) : uint160(in) { }
};
/** A reference to a CScript: the Hash160 of its serialization (see script.h) */
class CScriptID : public uint160
{
public:
CScriptID() : uint160(0) { }
CScriptID(const uint160 &in) : uint160(in) { }
};
/** An encapsulated public key. */
class CPubKey {
private:
std::vector<unsigned char> vchPubKey;
friend class CKey;
public:
CPubKey() { }
CPubKey(const std::vector<unsigned char> &vchPubKeyIn) : vchPubKey(vchPubKeyIn) { }
friend bool operator==(const CPubKey &a, const CPubKey &b) { return a.vchPubKey == b.vchPubKey; }
friend bool operator!=(const CPubKey &a, const CPubKey &b) { return a.vchPubKey != b.vchPubKey; }
friend bool operator<(const CPubKey &a, const CPubKey &b) { return a.vchPubKey < b.vchPubKey; }
IMPLEMENT_SERIALIZE(
READWRITE(vchPubKey);
)
CKeyID GetID() const {
return CKeyID(Hash160(vchPubKey));
}
uint256 GetHash() const {
return Hash(vchPubKey.begin(), vchPubKey.end());
}
bool IsValid() const {
return vchPubKey.size() == 33 || vchPubKey.size() == 65;
}
bool IsCompressed() const {
return vchPubKey.size() == 33;
}
std::vector<unsigned char> Raw() const {
return vchPubKey;
}
};
// secure_allocator is defined in serialize.h
// CPrivKey is a serialized private key, with all parameters included (279 bytes)
typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
// CSecret is a serialization of just the secret parameter (32 bytes)
typedef std::vector<unsigned char, secure_allocator<unsigned char> > CSecret;
/** An encapsulated OpenSSL Elliptic Curve key (public and/or private) */
class CKey
{
protected:
EC_KEY* pkey;
bool fSet;
bool fCompressedPubKey;
void SetCompressedPubKey();
public:
void Reset();
CKey();
CKey(const CKey& b);
CKey& operator=(const CKey& b);
~CKey();
bool IsNull() const;
bool IsCompressed() const;
void MakeNewKey(bool fCompressed);
bool SetPrivKey(const CPrivKey& vchPrivKey);
bool SetSecret(const CSecret& vchSecret, bool fCompressed = false);
CSecret GetSecret(bool &fCompressed) const;
CPrivKey GetPrivKey() const;
bool SetPubKey(const CPubKey& vchPubKey);
CPubKey GetPubKey() const;
bool Sign(uint256 hash, std::vector<unsigned char>& vchSig);
// create a compact signature (65 bytes), which allows reconstructing the used public key
// The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
// The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
// 0x1D = second key with even y, 0x1E = second key with odd y
bool SignCompact(uint256 hash, std::vector<unsigned char>& vchSig);
// reconstruct public key from a compact signature
// This is only slightly more CPU intensive than just verifying it.
// If this function succeeds, the recovered public key is guaranteed to be valid
// (the signature is a valid signature of the given data for that key)
bool SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig);
bool Verify(uint256 hash, const std::vector<unsigned char>& vchSig);
// Verify a compact signature
bool VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig);
bool IsValid();
};
#endif
| [
"beetlemon.cwts@gmail.com"
] | beetlemon.cwts@gmail.com |
4f6de49b6c3dbeda8fae40424ba98db4fa927e2f | 8a55b8fe4dfa23a4ac7c8f20a0f94716faa84089 | /cpps/03/3_16.cpp | 50aa06e7be1a924c6c0555fdde1316d21ce09f9b | [
"MIT"
] | permissive | ch1huizong/lang | ff305efb31cf77bb408b3bbca0aa6c291778716e | 904d18b9364033af07933d38fd3f2e136a3cba2c | refs/heads/main | 2023-07-17T23:33:21.855082 | 2021-09-02T14:44:16 | 2021-09-02T14:44:16 | 328,067,700 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 570 | cpp | #include <iostream>
// T: 函数重载
// 编译器根据参数数目和参数类型实现重载
int sumOfSquare(int a, int b) { return a * a + b * b; }
double sumOfSquare(double a, double b) { return a * a + b * b; }
int main(int argc, char* argv[]) {
int m, n;
std::cout << "Enter two integer:";
std::cin >> m >> n;
std::cout << "Their sum of square: " << sumOfSquare(m, n) << std::endl;
double x, y;
std::cout << "Enter two real number: ";
std::cin >> x >> y;
std::cout << "Their sum of square: " << sumOfSquare(x, y) << std::endl;
return 0;
}
| [
"ch1huizong@gmail.com"
] | ch1huizong@gmail.com |
05a2e74a5027d70661c7c7e13790bfaa7f39f9b9 | dc4daf9a90f28a07c9328a980e6be154600ec1a1 | /GameProject/HelpFunctions.cpp | 62abc8878f1bef9eabc7625b99a9bf5c0f772808 | [] | no_license | kpace/simple-game-project | 923cf234bb500ed65cee6f7118a9a7d6a01e6a32 | a9ec5485ffb61729d29bbc50def4d653d15c248b | refs/heads/master | 2020-05-18T10:17:23.029940 | 2014-07-04T07:37:52 | 2014-07-04T07:37:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 300 | cpp | #include "HelpFunctions.h"
// takes char from '0' to '9'
// \return integer value
int fromCharToInt(char c)
{
int a = 0;
if(c > '0' && c < '9')
{
a = c - '0';
}
return a;
}
// formats char to lower case
void toLowerCase(char& c)
{
if(c >= 'A' || c <= 'Z')
{
c = c + ('a' - 'A');
}
} | [
"krasimirva@gmail.com"
] | krasimirva@gmail.com |
86872d9888c45fd993db0ab263bda153ee708679 | c90a56e7d7752b041fc5eb38257c5573cef346c6 | /src-win/Precision_pre.cpp | 60c799531c4fffe3904b1b97d9df0a8fc0bf1be8 | [] | no_license | random-builder/design_cadquery_ocp | a4c572a72699bad52ca5f43f30bb7c15d89072ff | 2af799a9f1b2d81fd39e519b2f73e12b34a14c0a | refs/heads/master | 2021-05-21T23:10:23.833461 | 2020-03-29T15:34:46 | 2020-03-29T15:34:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,796 | cpp |
// pybind 11 related includes
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace py = pybind11;
// Windows specific
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
// Standard Handle
#include <Standard_Handle.hxx>
// user-defined inclusion per module before includes
// includes to resolve forward declarations
// module includes
#include <Precision.hxx>
// template related includes
// user-defined pre
#include "OCP_specific.inc"
// user-defined inclusion per module
// Module definiiton
void register_Precision_enums(py::module &main_module) {
py::module m = main_module.def_submodule("Precision", R"#()#");
// user-defined inclusion per module in the body
// enums
//Python trampoline classes
// pre-register typdefs
// classes forward declarations only
py::class_<Precision , shared_ptr<Precision> >(m,"Precision",R"#(The Precision package offers a set of functions defining precision criteria for use in conventional situations when comparing two numbers. Generalities It is not advisable to use floating number equality. Instead, the difference between numbers must be compared with a given precision, i.e. : Standard_Real x1, x2 ; x1 = ... x2 = ... If ( x1 == x2 ) ... should not be used and must be written as indicated below: Standard_Real x1, x2 ; Standard_Real Precision = ... x1 = ... x2 = ... If ( Abs ( x1 - x2 ) < Precision ) ... Likewise, when ordering floating numbers, you must take the following into account : Standard_Real x1, x2 ; Standard_Real Precision = ... x1 = ... ! a large number x2 = ... ! another large number If ( x1 < x2 - Precision ) ... is incorrect when x1 and x2 are large numbers ; it is better to write : Standard_Real x1, x2 ; Standard_Real Precision = ... x1 = ... ! a large number x2 = ... ! another large number If ( x2 - x1 > Precision ) ... Precision in Cas.Cade Generally speaking, the precision criterion is not implicit in Cas.Cade. Low-level geometric algorithms accept precision criteria as arguments. As a rule, they should not refer directly to the precision criteria provided by the Precision package. On the other hand, high-level modeling algorithms have to provide the low-level geometric algorithms that they call, with a precision criteria. One way of doing this is to use the above precision criteria. Alternatively, the high-level algorithms can have their own system for precision management. For example, the Topology Data Structure stores precision criteria for each elementary shape (as a vertex, an edge or a face). When a new topological object is constructed, the precision criteria are taken from those provided by the Precision package, and stored in the related data structure. Later, a topological algorithm which analyses these objects will work with the values stored in the data structure. Also, if this algorithm is to build a new topological object, from these precision criteria, it will compute a new precision criterion for the new topological object, and write it into the data structure of the new topological object. The different precision criteria offered by the Precision package, cover the most common requirements of geometric algorithms, such as intersections, approximations, and so on. The choice of precision depends on the algorithm and on the geometric space. The geometric space may be : - a "real" 2D or 3D space, where the lengths are measured in meters, millimeters, microns, inches, etc ..., or - a "parametric" space, 1D on a curve or 2D on a surface, where lengths have no dimension. The choice of precision criteria for real space depends on the choice of the product, as it is based on the accuracy of the machine and the unit of measurement. The choice of precision criteria for parametric space depends on both the accuracy of the machine and the dimensions of the curve or the surface, since the parametric precision criterion and the real precision criterion are linked : if the curve is defined by the equation P(t), the inequation : Abs ( t2 - t1 ) < ParametricPrecision means that the parameters t1 and t2 are considered to be equal, and the inequation : Distance ( P(t2) , P(t1) ) < RealPrecision means that the points P(t1) and P(t2) are considered to be coincident. It seems to be the same idea, and it would be wonderful if these two inequations were equivalent. Note that this is rarely the case ! What is provided in this package? The Precision package provides : - a set of real space precision criteria for the algorithms, in view of checking distances and angles, - a set of parametric space precision criteria for the algorithms, in view of checking both : - the equality of parameters in a parametric space, - or the coincidence of points in the real space, by using parameter values, - the notion of infinite value, composed of a value assumed to be infinite, and checking tests designed to verify if any value could be considered as infinite. All the provided functions are very simple. The returned values result from the adaptation of the applications developed by the Open CASCADE company to Open CASCADE algorithms. The main interest of these functions lies in that it incites engineers developing applications to ask questions on precision factors. Which one is to be used in such or such case ? Tolerance criteria are context dependent. They must first choose : - either to work in real space, - or to work in parametric space, - or to work in a combined real and parametric space. They must next decide which precision factor will give the best answer to the current problem. Within an application environment, it is crucial to master precision even though this process may take a great deal of time.)#");
};
// user-defined post-inclusion per module
// user-defined post
| [
"adam.jan.urbanczyk@gmail.com"
] | adam.jan.urbanczyk@gmail.com |
7a9a0612430da35008c2af4ffd29f70f74925809 | aa13e1d93b7a8017e1e610a900bd05f6df91604f | /codechef/contests/LOCFEB16/ACRONYM.cpp | 0ba4423687cc609747a1c38da91bea5e64c049af | [] | no_license | laveesingh/Competitive-Programming | 3ce3272eab525635f9ce400f7467ee09de8b51df | 41047f47c23bc8572a1891e891a03cc3f751e588 | refs/heads/master | 2021-01-24T09:51:00.332543 | 2017-10-30T17:11:48 | 2017-10-30T17:11:48 | 52,956,650 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 674 | cpp | #include <iostream>
#include <ctype.h>
#include <vector>
using namespace std;
bool isAc(string a){
if (a.length() < 2) return false;
for (int i = 0; i < a.length(); i += 1)
if (!isupper(a[i])) return false;
return true;
}
vector<string> split(string a){
vector<string> v;
string temp = "";
for(int i = 0; i < a.length(); i += 1){
if (a[i] == ' '){
v.push_back(temp);
temp = "";
}
else temp += a[i];
}
if(temp != "") v.push_back(temp);
return v;
}
int main(void){
string a;
getline(cin, a);
vector<string> v = split(a);
int count = 0;
for (int i = 0; i < v.size(); i += 1){
if (isAc(v[i])){
count += 1;
}
}
cout << count << endl;
} | [
"laveechaudharytheone@gmail.com"
] | laveechaudharytheone@gmail.com |
c9ee533dda674e325013f45dd4d82c9091e003c3 | 3cf9e141cc8fee9d490224741297d3eca3f5feff | /C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-9854.cpp | 3364cb5f67aebb169deede2473f32d7946859a90 | [] | no_license | TeamVault/tauCFI | e0ac60b8106fc1bb9874adc515fc01672b775123 | e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10 | refs/heads/master | 2023-05-30T20:57:13.450360 | 2021-06-14T09:10:24 | 2021-06-14T09:10:24 | 154,563,655 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,512 | cpp | struct c0;
void __attribute__ ((noinline)) tester0(c0* p);
struct c0
{
bool active0;
c0() : active0(true) {}
virtual ~c0()
{
tester0(this);
active0 = false;
}
virtual void f0(){}
};
void __attribute__ ((noinline)) tester0(c0* p)
{
p->f0();
}
struct c1;
void __attribute__ ((noinline)) tester1(c1* p);
struct c1
{
bool active1;
c1() : active1(true) {}
virtual ~c1()
{
tester1(this);
active1 = false;
}
virtual void f1(){}
};
void __attribute__ ((noinline)) tester1(c1* p)
{
p->f1();
}
struct c2;
void __attribute__ ((noinline)) tester2(c2* p);
struct c2 : c1, virtual c0
{
bool active2;
c2() : active2(true) {}
virtual ~c2()
{
tester2(this);
c0 *p0_0 = (c0*)(c2*)(this);
tester0(p0_0);
c1 *p1_0 = (c1*)(c2*)(this);
tester1(p1_0);
active2 = false;
}
virtual void f2(){}
};
void __attribute__ ((noinline)) tester2(c2* p)
{
p->f2();
if (p->active1)
p->f1();
if (p->active0)
p->f0();
}
struct c3;
void __attribute__ ((noinline)) tester3(c3* p);
struct c3 : virtual c0, c1
{
bool active3;
c3() : active3(true) {}
virtual ~c3()
{
tester3(this);
c0 *p0_0 = (c0*)(c3*)(this);
tester0(p0_0);
c1 *p1_0 = (c1*)(c3*)(this);
tester1(p1_0);
active3 = false;
}
virtual void f3(){}
};
void __attribute__ ((noinline)) tester3(c3* p)
{
p->f3();
if (p->active1)
p->f1();
if (p->active0)
p->f0();
}
struct c4;
void __attribute__ ((noinline)) tester4(c4* p);
struct c4 : virtual c1, virtual c0
{
bool active4;
c4() : active4(true) {}
virtual ~c4()
{
tester4(this);
c0 *p0_0 = (c0*)(c4*)(this);
tester0(p0_0);
c1 *p1_0 = (c1*)(c4*)(this);
tester1(p1_0);
active4 = false;
}
virtual void f4(){}
};
void __attribute__ ((noinline)) tester4(c4* p)
{
p->f4();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
}
int __attribute__ ((noinline)) inc(int v) {return ++v;}
int main()
{
c0* ptrs0[25];
ptrs0[0] = (c0*)(new c0());
ptrs0[1] = (c0*)(c2*)(new c2());
ptrs0[2] = (c0*)(c3*)(new c3());
ptrs0[3] = (c0*)(c4*)(new c4());
for (int i=0;i<4;i=inc(i))
{
tester0(ptrs0[i]);
delete ptrs0[i];
}
c1* ptrs1[25];
ptrs1[0] = (c1*)(new c1());
ptrs1[1] = (c1*)(c2*)(new c2());
ptrs1[2] = (c1*)(c3*)(new c3());
ptrs1[3] = (c1*)(c4*)(new c4());
for (int i=0;i<4;i=inc(i))
{
tester1(ptrs1[i]);
delete ptrs1[i];
}
c2* ptrs2[25];
ptrs2[0] = (c2*)(new c2());
for (int i=0;i<1;i=inc(i))
{
tester2(ptrs2[i]);
delete ptrs2[i];
}
c3* ptrs3[25];
ptrs3[0] = (c3*)(new c3());
for (int i=0;i<1;i=inc(i))
{
tester3(ptrs3[i]);
delete ptrs3[i];
}
c4* ptrs4[25];
ptrs4[0] = (c4*)(new c4());
for (int i=0;i<1;i=inc(i))
{
tester4(ptrs4[i]);
delete ptrs4[i];
}
return 0;
}
| [
"ga72foq@mytum.de"
] | ga72foq@mytum.de |
6b9d272488379b65c5dcd817ff7a08f23b1b2d0c | aa69271e11cd5893f11e2ff9d54cd9489efd4f25 | /HW_4/HW_ARR_4_6.cpp | 065398b88b21cd5426659c633f68ac42455b6f19 | [] | no_license | Spautov/HW_C | d7e78a7ad6f546bc7e24c54955b46ff8fcf7fdbf | 2fb1a53a9c880a641ace3dc7e44b6cdef5dd131b | refs/heads/master | 2021-09-14T02:22:48.683838 | 2018-02-15T07:35:30 | 2018-02-15T07:35:30 | 106,203,187 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 752 | cpp | #include <iostream>
#include <stdlib.h>
#include <time.h>
#include <iomanip>
int main()
{
int big_arr[5][10];
int small_arr[5][5];
srand(time(0));
for (int i = 0; i<5; ++i)
{
for (int j = 0; j<10; ++j)
{
big_arr[i][j] = (rand() % 51);
std::cout << std:: setw(4) << big_arr[i][j];
};
std::cout << std::endl;
};
std::cout << std::endl;
std::cout << std::endl;
for (int i = 0; i<5; ++i)
{
for (int j = 0; j<5; ++j)
{
small_arr[i][j] = big_arr[i][j*2] + big_arr[i][j*2+1];
std::cout << std::setw(4) << small_arr[i][j];
};
std::cout << std::endl;
};
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
468efaaef71c28f1280c02926b44fe95bce9b49c | f65da475cc2164cb7cd0cc841251880d3b9765d8 | /alexey/Solvers/4xx/427/Solver427A.cpp | bae4e998608f9e094ed320e07366a94cc01b0d65 | [] | no_license | aeremin/Codeforces | 825c0d031c9de89e90a83721da2d36e59fbeaa4c | 3dc6ea45660d73068ced11ca5667c8ca65985d58 | refs/heads/master | 2023-06-22T15:40:51.496986 | 2023-06-18T22:05:22 | 2023-06-18T22:05:22 | 28,269,213 | 2 | 0 | null | 2019-01-03T19:06:12 | 2014-12-20T14:30:58 | C++ | UTF-8 | C++ | false | false | 1,192 | cpp | #include <Solvers/pch.h>
#include "algo/io/baseio.h"
#include "iter/range.h"
using namespace std;
// Solution for Codeforces problem http://codeforces.com/contest/427/problem/A
class Solver427A
{
public:
void run();
};
void Solver427A::run()
{
int n;
cin >> n;
int ans = 0;
int freeGuys = 0;
for (int i : range(n)) {
int t;
cin >> t;
if (t > 0) freeGuys += t;
if (t == -1) {
if (freeGuys > 0) --freeGuys;
else ++ans;
}
}
cout << ans;
}
class Solver427ATest : public ProblemTest {};
TEST_F(Solver427ATest, Example1)
{
string input = R"(3
-1 -1 1
)";
string output = R"(2
)";
setInput(input);
Solver427A().run();
EXPECT_EQ_FUZZY(getOutput(), output);
}
TEST_F(Solver427ATest, Example2)
{
string input = R"(8
1 -1 1 -1 -1 1 1 1
)";
string output = R"(1
)";
setInput(input);
Solver427A().run();
EXPECT_EQ_FUZZY(getOutput(), output);
}
TEST_F(Solver427ATest, Example3)
{
string input = R"(11
-1 -1 2 -1 -1 -1 -1 -1 -1 -1 -1
)";
string output = R"(8
)";
setInput(input);
Solver427A().run();
EXPECT_EQ_FUZZY(getOutput(), output);
}
| [
"a.eremin.msu@gmail.com"
] | a.eremin.msu@gmail.com |
4ea8145d3e43bebe69a8baefb6b57fc8d987ce1f | b3a158034526daacee4427fa2eae0b797f904924 | /Demo/PCHunter/Utils/SnmpMgr.h | 355f85fd837d4beb68affd10a64ac7b32fec2c6e | [] | no_license | 15831944/Corpse | e1785c12d620f7defd16ab0b0abb0705907815c9 | 51ca96ada1db58272fff3bdbdff165200be96191 | refs/heads/master | 2023-06-29T08:36:07.487065 | 2021-05-22T01:31:41 | 2021-05-22T01:31:41 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 880 | h | #pragma once
#include <Winsnmp.h>
class IRecvCallback
{
public:
virtual void SnmpMsgHandler(smiOID sOid, smiVALUE sValue) = 0;
};
class CSnmpMgr
{
public:
CSnmpMgr();
~CSnmpMgr();
public:
void SetRecvCallback(SNMPAPI_CALLBACK funCallback);
BOOL Init(LPCTSTR lpszDstAddr, LPCTSTR lpszCommunity);
BOOL SendSnmpMsg(LPCTSTR lpszOidInfo, smiINT sPDUType=SNMP_PDU_GETNEXT);
void SetOwner(IRecvCallback* pOwer);
BOOL ValueToString(smiVALUE sValue, CString& strDevInfo);
protected:
BOOL ReceiveMsg();
static SNMPAPI_STATUS CALLBACK SnmpCallback(HSNMP_SESSION hSession,HWND hWnd,UINT wMsg,WPARAM wParam,LPARAM lParam,LPVOID lpClientData);
protected:
CStringA m_strSrcAddr;
CStringA m_strDstAddr;
IRecvCallback* m_pRecvMsg;
smiOCTETS m_Community;
HSNMP_SESSION m_hSession; //会话句柄
HSNMP_CONTEXT m_hContext; //上下文句柄
}; | [
"Uniquers@853a975a-7e59-4707-9df1-4264b926ceb7"
] | Uniquers@853a975a-7e59-4707-9df1-4264b926ceb7 |
8308057da2273a8bd49423e82e2ad2b2eda6a1ab | 5525c618e72ed7a7709711e56f06e9db22c37cab | /src/solver/conv_asm_implicit_gemm_v4r1_dynamic.cpp | 6aaa73bc2e83823415efc8be4d3b0836ad668116 | [
"MIT"
] | permissive | pruthvistony/MIOpen | 11fd07dfff1550fc09fe924539a6392015b3212f | f34c912d2fe1cc5b28367ea441657d243be85a01 | refs/heads/master | 2022-12-29T00:40:13.243876 | 2020-08-20T18:45:27 | 2020-08-20T18:45:27 | 291,861,278 | 0 | 0 | null | 2020-09-01T01:08:26 | 2020-09-01T01:08:25 | null | UTF-8 | C++ | false | false | 22,839 | cpp | /*******************************************************************************
*
* MIT License
*
* Copyright (c) 2020 Advanced Micro Devices, Inc.
*
* 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.
*
*******************************************************************************/
#include "miopen/solver.hpp"
#include "miopen/handle.hpp"
#include <miopen/conv/invokers/impl_gemm_dynamic.hpp>
#include <miopen/generic_search.hpp>
#include <miopen/gcn_asm_utils.hpp>
#include "implicitgemm_util.hpp"
namespace miopen {
namespace solver {
static inline const std::vector<PerformanceImplicitGemmV4R1Dynamic>&
GetImplicitGemmV4R1DynamicTunables()
{
// clang-format off
static const std::vector<PerformanceImplicitGemmV4R1Dynamic> tunables = {
{ 16, 128, 16, 2, 4, 4, 4, 4, 4, 4, 16, 1, 16, 1, 4, 64},
{ 16, 128, 8, 2, 4, 4, 4, 4, 4, 4, 8, 2, 16, 1, 2, 128},
{ 8, 128, 8, 2, 4, 4, 4, 4, 4, 2, 8, 1, 8, 2, 2, 64},
{ 8, 64, 8, 2, 4, 4, 4, 2, 2, 4, 8, 1, 8, 1, 4, 16},
{ 16, 32, 4, 2, 4, 4, 1, 4, 4, 4, 4, 1, 16, 1, 4, 16},
{ 16, 16, 4, 2, 2, 2, 2, 4, 2, 4, 4, 1, 16, 1, 4, 16},
{ 8, 32, 4, 2, 2, 2, 2, 4, 4, 2, 4, 2, 8, 1, 4, 16}
};
// clang-format on
return tunables;
}
using AsmImplicitGemmKernelV4R1Fwd_t = enum {
AsmImplicitGemmV4R1 = 0,
AsmImplicitGemmV4R1_1x1 = 1,
};
static inline std::string
GetKernelNameImplicitGemmV4R1Dynamic(const PerformanceImplicitGemmV4R1Dynamic& config,
AsmImplicitGemmKernelV4R1Fwd_t kernel_type)
{
int GemmMRepeat = config.KPerBlock / (config.GemmMPerThreadSubC * config.GemmMLevel0Cluster *
config.GemmMLevel1Cluster);
int ThreadTileM = GemmMRepeat * config.GemmMPerThreadSubC;
int ThreadTileN = config.GemmNRepeat * config.GemmNPerThreadSubC;
std::string kernel_name_prefix;
if(AsmImplicitGemmV4R1 == kernel_type)
kernel_name_prefix = std::string("igemm_v4r1_dynamic_");
else // if (AsmImplicitGemmV4R1_1x1 == kernel_type)
kernel_name_prefix = std::string("igemm_v4r1_1x1_dynamic_");
return kernel_name_prefix + std::to_string(config.KPerBlock) + "x" +
std::to_string(config.BPerBlock * config.GemmNRepeat * config.GemmNPerThreadSubC) + "x" +
std::to_string(config.EPerBlock) + "_" + std::to_string(ThreadTileM) + "x" +
std::to_string(ThreadTileN) + "_" + std::to_string(config.GemmMPerThreadSubC) + "x" +
std::to_string(config.GemmMLevel0Cluster) + "x" +
std::to_string(config.GemmMLevel1Cluster) + "x" +
std::to_string(config.GemmNPerThreadSubC) + "x" +
std::to_string(config.GemmNLevel0Cluster) + "x" +
std::to_string(config.GemmNLevel1Cluster) + "_" +
std::to_string(config.InBlockCopyClusterLengths_E) + "x" +
std::to_string(config.InBlockCopyClusterLengths_N1) + "x" +
std::to_string(config.InBlockCopyClusterLengths_B) + "x" +
std::to_string(config.InBlockCopyClusterLengths_N2) + "_" +
std::to_string(config.WeiBlockCopyClusterLengths_E) + "x" +
std::to_string(config.WeiBlockCopyClusterLengths_K);
}
static inline int
GetImplicitGemmV4R1DynamicBlockSize(const PerformanceImplicitGemmV4R1Dynamic& config)
{
return config.GemmMLevel0Cluster * config.GemmNLevel0Cluster * config.GemmMLevel1Cluster *
config.GemmNLevel1Cluster;
}
static inline int
GetImplicitGemmV4R1DynamicGridSize(const ConvolutionContext& ctx,
const PerformanceImplicitGemmV4R1Dynamic& config)
{
const auto& N1 = config.GemmNRepeat;
const auto& N2 = config.GemmNPerThreadSubC;
const auto& n = ctx.batch_sz;
const auto& k = ctx.n_outputs;
const auto& ho = ctx.out_height;
const auto& wo = ctx.out_width;
const auto& b = (static_cast<std::size_t>(n) * ho * wo) / (static_cast<std::size_t>(N1) * N2);
const auto& b_per_block = config.BPerBlock;
const auto& k_per_block = config.KPerBlock;
return (b / b_per_block) * (k / k_per_block); // NOLINT
}
// Remove This function when invoker is fully re-factored
template <typename BotBufType, typename TopBufType, typename WeiBufType>
static inline int RunAndMeasureSolutionDynamicBase(miopen::Handle& profile_h,
BotBufType bot_buf,
TopBufType top_buf,
WeiBufType wei_buf,
const ConvolutionContext& ctx,
const ConvSolution& solution,
float& elapsed_time)
{
#ifdef NDEBUG
try
#endif
{
elapsed_time = float(0);
std::vector<KernelInvoke> kernels;
for(auto& k_info : solution.construction_params)
{
auto kernel = profile_h.AddKernel("",
"",
k_info.kernel_file,
k_info.kernel_name,
k_info.l_wk,
k_info.g_wk,
k_info.comp_options);
kernels.push_back(kernel);
}
float time =
conv::CallImplicitGemmDynamic(profile_h, ctx, bot_buf, top_buf, wei_buf, kernels);
elapsed_time += time;
}
#ifdef NDEBUG
catch(miopen::Exception& ex)
{
MIOPEN_LOG_WE(ex.what());
return -1;
}
#endif
return 0;
}
bool PerformanceImplicitGemmV4R1Dynamic::
operator==(const PerformanceImplicitGemmV4R1Dynamic& other) const
{
// clang-format off
return BPerBlock == other.BPerBlock
&& KPerBlock == other.KPerBlock
&& EPerBlock == other.EPerBlock
&& GemmNRepeat == other.GemmNRepeat
&& GemmMPerThreadSubC == other.GemmMPerThreadSubC
&& GemmNPerThreadSubC == other.GemmNPerThreadSubC
&& GemmMLevel0Cluster == other.GemmMLevel0Cluster
&& GemmNLevel0Cluster == other.GemmNLevel0Cluster
&& GemmMLevel1Cluster == other.GemmMLevel1Cluster
&& GemmNLevel1Cluster == other.GemmNLevel1Cluster
&& InBlockCopyClusterLengths_E == other.InBlockCopyClusterLengths_E
&& InBlockCopyClusterLengths_B == other.InBlockCopyClusterLengths_B
&& InBlockCopyClusterLengths_N1 == other.InBlockCopyClusterLengths_N1
&& InBlockCopyClusterLengths_N2 == other.InBlockCopyClusterLengths_N2
&& WeiBlockCopyClusterLengths_E == other.WeiBlockCopyClusterLengths_E
&& WeiBlockCopyClusterLengths_K == other.WeiBlockCopyClusterLengths_K;
// clang-format on
}
bool PerformanceImplicitGemmV4R1Dynamic::IsValid(const ConvolutionContext& ctx) const
{
std::size_t N = KernelBatchN(ctx);
std::size_t K = KernelOutputChannelK(ctx);
std::size_t C = KernelInputChannelC(ctx);
std::size_t Ho = KernelOutputHeightHo(ctx);
std::size_t Wo = KernelOutputWidthWo(ctx);
std::size_t Y = KernelFilterHeightY(ctx);
std::size_t X = KernelFilterWidthX(ctx);
const int N1 = GemmNRepeat;
const int N2 = GemmNPerThreadSubC;
if(N % (N1 * N2) != 0)
return false; // wrong! cannot divice N evenly among thread
const auto N0 = N / (N1 * N2);
const auto B = N0 * Ho * Wo;
const auto nonVectorizedC = C / GetEPackLength(ctx, false);
const auto E = nonVectorizedC * Y * X;
if(!(EPerBlock % InBlockCopyClusterLengths_E == 0 &&
EPerBlock % WeiBlockCopyClusterLengths_E == 0 &&
BPerBlock % InBlockCopyClusterLengths_B == 0 &&
KPerBlock % WeiBlockCopyClusterLengths_K == 0 && N1 % InBlockCopyClusterLengths_N1 == 0 &&
N2 % InBlockCopyClusterLengths_N2 == 0))
return false;
// divide block work by [K, B]
if(!(K % KPerBlock == 0 && B % BPerBlock == 0 && E % EPerBlock == 0))
return false; // wrong! cannot divice N evenly among thread
const auto KBlockWork = K / KPerBlock;
if(KBlockWork % ctx.group_counts != 0)
return false;
if((N1 * N2 * BPerBlock) % (GemmNPerThreadSubC * GemmNLevel0Cluster * GemmNLevel1Cluster) != 0)
return false;
// fp16/bfp16: doesn't support asymmetric matrix mul
if((ctx.IsFp16() || ctx.IsBfp16()) && GemmNPerThreadSubC != GemmMPerThreadSubC)
return false;
// sanity check
if((KPerBlock % (GemmMPerThreadSubC * GemmMLevel0Cluster * GemmMLevel1Cluster)) != 0)
return false;
if(GemmNRepeat !=
(N1 * N2 * BPerBlock) / (GemmNPerThreadSubC * GemmNLevel0Cluster * GemmNLevel1Cluster))
return false;
const int ThreadPerLevel1Cluster =
GemmMLevel0Cluster * GemmNLevel0Cluster * GemmMLevel1Cluster * GemmNLevel1Cluster;
const int block_size = ThreadPerLevel1Cluster;
if(block_size < 64 || block_size > 512)
return false;
if(block_size !=
InBlockCopyClusterLengths_E * InBlockCopyClusterLengths_N1 * InBlockCopyClusterLengths_B *
InBlockCopyClusterLengths_N2)
return false;
if(block_size != WeiBlockCopyClusterLengths_K * WeiBlockCopyClusterLengths_E)
return false;
const int GemmMRepeat =
KPerBlock / (GemmMPerThreadSubC * GemmMLevel0Cluster * GemmMLevel1Cluster);
if(!(GemmMRepeat == 2 && GemmNRepeat == 2))
return false;
const int InBlockCopySubLengths_E = EPerBlock / InBlockCopyClusterLengths_E;
const int InBlockCopySubLengths_B = BPerBlock / InBlockCopyClusterLengths_B;
const int WeiBlockCopySubLengths_K = KPerBlock / WeiBlockCopyClusterLengths_K;
const std::size_t lds_size = ComputeLDSRequiredSize(ctx,
BPerBlock,
KPerBlock,
EPerBlock,
GemmMPerThreadSubC,
GemmNPerThreadSubC,
InBlockCopySubLengths_B,
WeiBlockCopySubLengths_K,
GetEPackLength(ctx, false));
if(lds_size > 64 * 1024)
return false;
return (InBlockCopySubLengths_E == 1 && InBlockCopySubLengths_B == 1);
}
void PerformanceImplicitGemmV4R1Dynamic::EuristicInit(const ConvolutionContext& config)
{
auto tunables = GetImplicitGemmV4R1DynamicTunables();
auto it = std::find_if(
tunables.begin(), tunables.end(), [&](auto tunable) { return tunable.IsValid(config); });
if(it == tunables.end())
{
MIOPEN_LOG_E("All attempts failed");
assert(false);
}
Copy(*it);
}
bool PerformanceImplicitGemmV4R1Dynamic::IsValidValue() const
{
// clang-format off
return IsTwoPower<8,16>(BPerBlock)
&& IsTwoPower<16,128>(KPerBlock)
&& IsTwoPower<4,16>(EPerBlock)
&& GemmNRepeat == 2
&& IsTwoPower<2,4>(GemmMPerThreadSubC)
&& IsTwoPower<2,4>(GemmNPerThreadSubC)
&& IsTwoPower<1,4>(GemmMLevel0Cluster)
&& IsTwoPower<1,4>(GemmNLevel0Cluster)
&& IsTwoPower<1,4>(GemmMLevel1Cluster)
&& IsTwoPower<1,4>(GemmNLevel1Cluster)
&& IsTwoPower<4,16>(InBlockCopyClusterLengths_E)
&& IsTwoPower<8,16>(InBlockCopyClusterLengths_B)
&& IsTwoPower<1,2>(InBlockCopyClusterLengths_N1)
&& IsTwoPower<1,4>(InBlockCopyClusterLengths_N2)
&& IsTwoPower<1,4>(WeiBlockCopyClusterLengths_E)
&& IsTwoPower<16,128>(WeiBlockCopyClusterLengths_K); // clang-format on
}
void PerformanceImplicitGemmV4R1Dynamic::Copy(const PerformanceImplicitGemmV4R1Dynamic& other)
{
BPerBlock = other.BPerBlock;
KPerBlock = other.KPerBlock;
EPerBlock = other.EPerBlock;
GemmNRepeat = other.GemmNRepeat;
GemmMPerThreadSubC = other.GemmMPerThreadSubC;
GemmNPerThreadSubC = other.GemmNPerThreadSubC;
GemmMLevel0Cluster = other.GemmMLevel0Cluster;
GemmNLevel0Cluster = other.GemmNLevel0Cluster;
GemmMLevel1Cluster = other.GemmMLevel1Cluster;
GemmNLevel1Cluster = other.GemmNLevel1Cluster;
InBlockCopyClusterLengths_E = other.InBlockCopyClusterLengths_E;
InBlockCopyClusterLengths_N1 = other.InBlockCopyClusterLengths_N1;
InBlockCopyClusterLengths_B = other.InBlockCopyClusterLengths_B;
InBlockCopyClusterLengths_N2 = other.InBlockCopyClusterLengths_N2;
WeiBlockCopyClusterLengths_E = other.WeiBlockCopyClusterLengths_E;
WeiBlockCopyClusterLengths_K = other.WeiBlockCopyClusterLengths_K;
}
bool PerformanceImplicitGemmV4R1Dynamic::SetNextValue()
{
do
{
size_t total_kernels = GetImplicitGemmV4R1DynamicTunables().size();
PreGeneratedKernelIndex++;
if(PreGeneratedKernelIndex >= total_kernels)
return false;
Copy(GetImplicitGemmV4R1DynamicTunables()[PreGeneratedKernelIndex]);
} while(false);
return true;
}
std::string PerformanceImplicitGemmV4R1Dynamic::ToString() const
{
std::ostringstream ss;
Serialize(ss);
return ss.str();
}
PerformanceImplicitGemmV4R1Dynamic::PerformanceImplicitGemmV4R1Dynamic(bool)
: PerformanceImplicitGemmV4R1Dynamic(
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
{
// get the minimal routine
Copy(GetImplicitGemmV4R1DynamicTunables()[0]);
PreGeneratedKernelIndex = 0;
}
PerformanceImplicitGemmV4R1Dynamic::PerformanceImplicitGemmV4R1Dynamic(
int BPerBlock_,
int KPerBlock_,
int EPerBlock_,
int GemmNRepeat_,
int GemmMPerThreadSubC_,
int GemmNPerThreadSubC_,
int GemmMLevel0Cluster_,
int GemmNLevel0Cluster_,
int GemmMLevel1Cluster_,
int GemmNLevel1Cluster_,
int InBlockCopyClusterLengths_E_,
int InBlockCopyClusterLengths_N1_,
int InBlockCopyClusterLengths_B_,
int InBlockCopyClusterLengths_N2_,
int WeiBlockCopyClusterLengths_E_,
int WeiBlockCopyClusterLengths_K_)
: BPerBlock(BPerBlock_),
KPerBlock(KPerBlock_),
EPerBlock(EPerBlock_),
GemmNRepeat(GemmNRepeat_),
GemmMPerThreadSubC(GemmMPerThreadSubC_),
GemmNPerThreadSubC(GemmNPerThreadSubC_),
GemmMLevel0Cluster(GemmMLevel0Cluster_),
GemmNLevel0Cluster(GemmNLevel0Cluster_),
GemmMLevel1Cluster(GemmMLevel1Cluster_),
GemmNLevel1Cluster(GemmNLevel1Cluster_),
InBlockCopyClusterLengths_E(InBlockCopyClusterLengths_E_),
InBlockCopyClusterLengths_N1(InBlockCopyClusterLengths_N1_),
InBlockCopyClusterLengths_B(InBlockCopyClusterLengths_B_),
InBlockCopyClusterLengths_N2(InBlockCopyClusterLengths_N2_),
WeiBlockCopyClusterLengths_E(WeiBlockCopyClusterLengths_E_),
WeiBlockCopyClusterLengths_K(WeiBlockCopyClusterLengths_K_)
{
PreGeneratedKernelIndex = 0;
}
bool ConvAsmImplicitGemmV4R1DynamicFwd::IsApplicable(const ConvolutionContext& ctx) const
{
const auto device_name = ctx.GetStream().GetDeviceName();
if(!(StartsWith(device_name, "gfx900") || StartsWith(device_name, "gfx906")))
return false;
if(!ctx.direction.IsForward())
return false;
if(!ctx.Is2d())
return false;
if(!ctx.IsFp32())
return false;
if(!ctx.rmv.IsV3())
return false;
if(ctx.group_counts != 1)
return false;
auto tunables = GetImplicitGemmV4R1DynamicTunables();
return !std::none_of(
tunables.begin(), tunables.end(), [&](auto tunable) { return tunable.IsValid(ctx); });
}
bool ConvAsmImplicitGemmV4R1DynamicFwd_1x1::IsApplicable(const ConvolutionContext& ctx) const
{
const auto device_name = ctx.GetStream().GetDeviceName();
if(!(StartsWith(device_name, "gfx900") || StartsWith(device_name, "gfx906")))
return false;
if(!ctx.direction.IsForward())
return false;
if(!ctx.Is2d())
return false;
if(!ctx.IsFp32())
return false;
if(!ctx.rmv.IsV3())
return false;
if(ctx.group_counts != 1)
return false;
if((ctx.kernel_size_h != 1) || (ctx.kernel_size_w != 1))
return false;
auto tunables = GetImplicitGemmV4R1DynamicTunables();
return !std::none_of(
tunables.begin(), tunables.end(), [&](auto tunable) { return tunable.IsValid(ctx); });
}
PerformanceImplicitGemmV4R1Dynamic
ConvAsmImplicitGemmV4R1DynamicFwd::GetPerformanceConfig(const ConvolutionContext& ctx) const
{
return GetPerformanceConfigBase<PerformanceImplicitGemmV4R1Dynamic>(ctx);
}
PerformanceImplicitGemmV4R1Dynamic
ConvAsmImplicitGemmV4R1DynamicFwd_1x1::GetPerformanceConfig(const ConvolutionContext& ctx) const
{
return GetPerformanceConfigBase<PerformanceImplicitGemmV4R1Dynamic>(ctx);
}
bool ConvAsmImplicitGemmV4R1DynamicFwd::IsValidPerformanceConfig(
const ConvolutionContext& ctx, const PerformanceImplicitGemmV4R1Dynamic& c) const
{
MIOPEN_LOG_I("");
return c.IsValidValue() && c.IsValid(ctx);
}
bool ConvAsmImplicitGemmV4R1DynamicFwd_1x1::IsValidPerformanceConfig(
const ConvolutionContext& ctx, const PerformanceImplicitGemmV4R1Dynamic& c) const
{
MIOPEN_LOG_I("");
return c.IsValidValue() && c.IsValid(ctx);
}
int ConvAsmImplicitGemmV4R1DynamicFwd::RunAndMeasureSolution(miopen::Handle& profile_h,
ConstData_t bot_buf,
Data_t top_buf,
ConstData_t wei_buf,
ConstData_t bias_buf,
const ConvolutionContext& ctx,
const ConvSolution& solution,
float& elapsed_time) const
{
assert(bias_buf == nullptr);
(void)bias_buf;
return RunAndMeasureSolutionDynamicBase(
profile_h, bot_buf, top_buf, wei_buf, ctx, solution, elapsed_time);
}
int ConvAsmImplicitGemmV4R1DynamicFwd_1x1::RunAndMeasureSolution(miopen::Handle& profile_h,
ConstData_t bot_buf,
Data_t top_buf,
ConstData_t wei_buf,
ConstData_t bias_buf,
const ConvolutionContext& ctx,
const ConvSolution& solution,
float& elapsed_time) const
{
assert(bias_buf == nullptr);
(void)bias_buf;
return RunAndMeasureSolutionDynamicBase(
profile_h, bot_buf, top_buf, wei_buf, ctx, solution, elapsed_time);
}
PerformanceImplicitGemmV4R1Dynamic
ConvAsmImplicitGemmV4R1DynamicFwd::Search(const ConvolutionContext& context) const
{
return GenericSearchFwd(*this, context);
}
PerformanceImplicitGemmV4R1Dynamic
ConvAsmImplicitGemmV4R1DynamicFwd_1x1::Search(const ConvolutionContext& context) const
{
return GenericSearchFwd(*this, context);
}
static inline ConvSolution GetSolutionBase(const ConvolutionContext& ctx,
const PerformanceImplicitGemmV4R1Dynamic& config,
const AsmImplicitGemmKernelV4R1Fwd_t& kernel_type)
{
ConvSolution result;
std::string kernel_name = GetKernelNameImplicitGemmV4R1Dynamic(config, kernel_type);
int block_size = GetImplicitGemmV4R1DynamicBlockSize(config);
int grid_size = GetImplicitGemmV4R1DynamicGridSize(ctx, config);
KernelInfo kernel;
std::ostringstream options;
kernel.kernel_file = "igemm_v4r1_dynamic.s";
kernel.kernel_name = kernel_name;
kernel.g_wk.clear();
/* Note here, for API like hipHccModuleLaunchKernel(), hipExtModuleLaunchKernel()
* grid dims is in unit of work item.
* But for api like hipModuleLaunchKernel(), grid dim is in unit of block.
*/
kernel.g_wk.push_back(grid_size * block_size);
kernel.g_wk.push_back(1);
kernel.g_wk.push_back(1);
kernel.l_wk.clear();
kernel.l_wk.push_back(block_size);
kernel.l_wk.push_back(1);
kernel.l_wk.push_back(1);
GenerateClangDefsym(options, "ROCM_METADATA_VERSION", ctx.rmv.UseV3() ? 5 : 4);
kernel.comp_options = options.str();
MIOPEN_LOG_I2(kernel.kernel_file + ":" + kernel.kernel_name);
result.invoker_factory = conv::MakeImplGemmDynamicDataInvokerFactory(ctx);
result.construction_params.push_back(kernel);
return result;
}
ConvSolution ConvAsmImplicitGemmV4R1DynamicFwd::GetSolution(
const ConvolutionContext& ctx, const PerformanceImplicitGemmV4R1Dynamic& config, bool) const
{
return GetSolutionBase(ctx, config, AsmImplicitGemmV4R1);
}
ConvSolution ConvAsmImplicitGemmV4R1DynamicFwd_1x1::GetSolution(
const ConvolutionContext& ctx, const PerformanceImplicitGemmV4R1Dynamic& config, bool) const
{
return GetSolutionBase(ctx, config, AsmImplicitGemmV4R1_1x1);
}
} // namespace solver
} // namespace miopen
| [
"noreply@github.com"
] | noreply@github.com |
97fde5c586b4d025ff203fd2701dc5f81f0c685f | 747d7ff8f3adba2fc858e9bb53194b4d3d7c6461 | /src/core/nocc_worker.h | 7c3efc7fc54aa780eba2a5d7754886cd29b37f7f | [] | no_license | roccrtx/roccrtx | a13bcb29f3694a5e148340191fe2295940bb6ad1 | 4f07a450900b129be143a0915d55917cdd811a71 | refs/heads/master | 2020-03-17T10:45:04.539515 | 2018-05-15T14:07:12 | 2018-05-15T14:07:12 | 133,524,089 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,474 | h | /* The main code for bootstraping the applications */
#ifndef NOCC_OLTP_BENCH_WORKER_H
#define NOCC_OLTP_BENCH_WORKER_H
#include "all.h"
#include "./utils/thread.h"
#include "./utils/util.h"
#include "rrpc.h"
#include "commun_queue.hpp"
#include "ud_msg.h"
#include "rdma_sched.h"
#include "routine.h"
#include <vector>
#include <string>
#include <stdint.h>
using namespace rdmaio;
using namespace rdmaio::udmsg;
namespace nocc {
namespace oltp {
// abstract worker
class Worker : public ndb_thread {
public:
// communication type supported by the Worker
enum MSGER_TYPE {
UD_MSG, RC_MSG, TCP_MSG
};
Worker(int worker_id,RdmaCtrl *cm,uint64_t seed = 0)
:cm_(cm),
worker_id_(worker_id),cor_id_(0), // coroutine id inited is zero
rdma_sched_(NULL),routine_meta_(NULL),
running(false),inited(false), // not initilized, not running
msg_handler_(NULL),client_handler_(NULL),rpc_(NULL),
rand_generator_(seed) // the random generator used at this thread
{
}
// main function for each routine, shall be overwritten
virtual void worker_routine(yield_func_t &yield) = 0;
// a handler be called after exit
virtual void exit_handler() {
}
// called after change context to cor_id
virtual void change_ctx(int cor_id) {
}
// choose a NIC port to use, update use_port_
virtual int choose_rnic_port(RdmaCtrl *cm);
// init functions provided
// the init shall be called sequentially
void init_routines(int coroutines);
void init_rdma();
void create_qps(); // depends init_rdma
void create_rdma_ud_connections(int total_connections = 1);
void create_rdma_rc_connections(char *start_buffer,uint64_t total_ring_sz,uint64_t total_ring_padding);
void create_tcp_connections(util::SingleQueue *queue, int tcp_port, zmq::context_t &context);
void create_client_connections(int total_connections = 1); // depends init_rdma
// create a mapped log for logging to file (for debug)
void create_logger();
// Init Worker to a ready start status
// This is used, such as in a global barrier.
void routine_v1() {
running = true;
}
// Really start the routine
void start_routine() {
assert(inited == true);
routines_[0]();
}
// Set routine in a ending status.
// The implementation asynchronously check the ending status.
void end_routine() {
running = false;
}
// handlers communication events,
// such as: in-comming RPC request/response; RDMA operation completions
inline ALWAYS_INLINE
void events_handler() const {
if(client_handler_ != NULL)
client_handler_->poll_comps(); // poll reqs from clients
if(msg_handler_ != NULL)
msg_handler_->poll_comps(); // poll rpcs requests/replies
rdma_sched_->poll_comps(); // poll RDMA completions
}
inline ALWAYS_INLINE
void default_yield(yield_func_t &yield) {
auto cur = routine_meta_;
int next = cur->next_->id_;
cor_id_ = next;
routine_meta_ = cur->next_;
cur->yield_from_routine_list(yield);
// yield back, do some checks
assert(routine_meta_->id_ == cor_id_);
change_ctx(cor_id_);
}
// whether worker is running
inline ALWAYS_INLINE
bool running_status() const { return running; }
// whether worker has finished initilization
inline ALWAYS_INLINE
bool init_status() const { return inited; }
public:
unsigned int cor_id_;
RoutineMeta *routine_meta_;
util::fast_random rand_generator_;
protected:
RdmaCtrl *cm_;
RRpc *rpc_;
RDMA_sched *rdma_sched_;
int use_port_ = -1;
// running status
bool running;
bool inited;
const unsigned int worker_id_; // thread id of the running routine
private:
MsgHandler *msg_handler_; // communication between servers
UDMsg *client_handler_; // communication with clients
MSGER_TYPE server_type_;
coroutine_func_t *routines_ = NULL;
// coroutine related stuffs
int total_worker_coroutine;
DISABLE_COPY_AND_ASSIGN(Worker);
};
} // end namespace oltp
} // end namespace nocc
//#include "bench_worker.hpp"
#endif
| [
"wxdwfc@gmail.com"
] | wxdwfc@gmail.com |
40a4a07e4581d7d0f8d94bf7d3e52fafaacab409 | a550f7637d3d68c59fe48a97ded2fca94ec488d1 | /interview/sort/quickSort.cpp | ae030644209f8b06751a729484dcfc178ed94186 | [] | no_license | sisiwuxi/helllo-git | 457ad5531987ebdf61c9a797978ad9f9eeda7685 | 0b54e5100ad5fd03129a3b918b5bad82c31ea78a | refs/heads/master | 2023-03-08T18:12:23.066976 | 2023-02-10T11:04:41 | 2023-02-26T12:18:39 | 79,521,135 | 2 | 0 | null | 2017-01-20T03:54:41 | 2017-01-20T03:23:10 | null | UTF-8 | C++ | false | false | 1,276 | cpp | #include<iostream>
using namespace std;
void print(int a[], int n)
{
for(int j= 0; j<n; j++){
cout<<a[j] <<" ";
}
cout<<endl;
}
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
int partition(int a[], int low, int high)
{
int privotKey = a[low];//基准元素
while(low < high)
{//从表的两端交替地向中间扫描
while(low < high && a[high] >= privotKey)
--high;//从high 所指位置向前搜索,至多到low+1 位置。将比基准元素小的交换到低端
swap(&a[low], &a[high]);
while(low < high && a[low] <= privotKey )
++low;
swap(&a[low], &a[high]);
}
print(a,10);
return low;
}
void quickSort(int a[], int low, int high)
{
if(low < high)
{
int privotLoc = partition(a, low, high); //将表一分为二
quickSort(a, low, privotLoc -1); //递归对低子表递归排序
quickSort(a, privotLoc + 1, high); //递归对高子表递归排序
}
}
int main()
{
int a[10] = {3,1,5,7,2,4,9,6,10,8};
cout<<"初始值:";
print(a,10);
quickSort(a,0,9);
cout<<"结果:";
print(a,10);
}
| [
"sisiwu@sisiwu-ThinkPad-E420.(none)"
] | sisiwu@sisiwu-ThinkPad-E420.(none) |
f107ff95135cba5feedc9ebe9b523af0520eede9 | 2f814827ffab9d8d9cc23cb4c3622feb45fa5770 | /PWGCF/FLOW/GF/AliAnalysisTaskGFWFlow.cxx | 34d4eb1f37d7f3d7cf1b4711b34aca6d6d60216c | [] | permissive | urasantonio/AliPhysics | dd3a851f84674846e45f4b1fdea65700dee80223 | 8ca4a9abc72a6b94e75048d08748a1debf41873e | refs/heads/master | 2022-12-17T21:54:22.246566 | 2020-09-11T14:04:20 | 2020-09-11T14:04:20 | 268,796,481 | 1 | 0 | BSD-3-Clause | 2020-09-11T13:50:03 | 2020-06-02T12:35:23 | C++ | UTF-8 | C++ | false | false | 37,454 | cxx | /*
Author: Vytautas Vislavicius
Extention of Generic Flow (https://arxiv.org/abs/1312.3572)
*/
#include "AliAnalysisTaskGFWFlow.h"
#include "AliEventCuts.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisFilter.h"
#include "AliAnalysisUtils.h"
#include "AliVEvent.h"
#include "AliAODEvent.h"
#include "AliVTrack.h"
#include "AliAODTrack.h"
#include "AliVVertex.h"
#include "AliAODVertex.h"
#include "AliCentrality.h"
#include "AliAODMCParticle.h"
#include "AliExternalTrackParam.h"
#include "AliMultSelection.h"
#include "AliInputEventHandler.h"
#include "TList.h"
#include "TProfile.h"
#include "TH3D.h"
#include "AliEventCuts.h"
#include "TTree.h"
#include "TClonesArray.h"
#include "AliMCEvent.h"
#include "AliVParticle.h"
#include "TParticle.h"
#include "AliStack.h"
#include "AliAODMCParticle.h"
#include "AliGFWWeights.h"
#include "AliGFWCuts.h"
#include "AliGFWFlowContainer.h"
#include "TObjArray.h"
#include "TNamed.h"
#include "AliGFW.h"
#include "TRandom.h"
#include <vector>
#include "AliCollisionGeometry.h"
#include "AliGenEventHeader.h"
ClassImp(AliAnalysisTaskGFWFlow);
AliAnalysisTaskGFWFlow::AliAnalysisTaskGFWFlow():
AliAnalysisTaskSE(),
debugpar(0),
fTriggerType(AliVEvent::kINT7),
fProduceWeights(kTRUE),
fSelections(0),
fWeightList(0),
fCentMap(0),
fWeights(0),
fExtraWeights(0),
fFC(0),
fOutputTree(0),
fMCEvent(0),
fIsMC(kFALSE),
fIsTrain(kFALSE),
fPtAxis(0),
fPOIpTMin(0.2),
fPOIpTMax(20),
fRFpTMin(0.2),
fRFpTMax(3.0),
fWeightPath(""),
fWeightDir(""),
fTotFlags(15), //Total number of flags: 1 (nominal) + fTotTrackFlags + N_Event flags
fTotTrackFlags(8), //Total number of track flags (without nominal)
fRunNo(-1),
fCurrSystFlag(0),
fAddQA(kFALSE),
fQAList(0),
fBypassCalculations(kFALSE),
fMultiDist(0)
{
};
AliAnalysisTaskGFWFlow::AliAnalysisTaskGFWFlow(const char *name, Bool_t ProduceWeights, Bool_t IsMC, Bool_t IsTrain, Bool_t AddQA):
AliAnalysisTaskSE(name),
debugpar(0),
fTriggerType(AliVEvent::kINT7),
fProduceWeights(ProduceWeights),
fSelections(0),
fWeightList(0),
fCentMap(0),
fWeights(0),
fExtraWeights(0),
fFC(0),
fOutputTree(0),
fIsMC(IsMC),
fIsTrain(IsTrain),
fPtAxis(new TAxis()),
fPOIpTMin(0.2),
fPOIpTMax(20),
fRFpTMin(0.2),
fRFpTMax(3.0),
fWeightPath(""),
fWeightDir(""),
fTotFlags(15),
fTotTrackFlags(8),
fRunNo(-1),
fCurrSystFlag(0),
fAddQA(AddQA),
fQAList(0),
fBypassCalculations(kFALSE),
fMultiDist(0)
{
if(!fProduceWeights) {
if(fIsTrain) DefineInput(1,TH1D::Class());
else DefineInput(1,TList::Class());
}
DefineOutput(1,(fProduceWeights?TList::Class():AliGFWFlowContainer::Class()));
DefineOutput(2,TH1D::Class());
if(fAddQA)
DefineOutput(3,TList::Class());
};
AliAnalysisTaskGFWFlow::~AliAnalysisTaskGFWFlow() {
};
void AliAnalysisTaskGFWFlow::UserCreateOutputObjects(){
printf("**************************************\n");
printf("************ AliGFW v2 *************\n");
printf("**************************************\n");
OpenFile(1);
fTotTrackFlags = AliGFWCuts::fNTrackFlags;
fTotFlags = fTotTrackFlags+AliGFWCuts::fNEventFlags+1;
fSelections = new AliGFWCuts*[fTotFlags]; //0 for normal, the rest for systematics
for(Int_t i=0; i<fTotFlags;i++) {
fSelections[i] = new AliGFWCuts();
fSelections[i]->SetupCuts(i);
};
if(fProduceWeights) {
//Initialize selection objects
fWeightList = new TList();
fWeightList->SetName("WeightList");
fWeightList->SetOwner(kTRUE);
for(Int_t i=0;i<fTotFlags;i++) {
if(!fSelections[i]->NeedsExtraWeight()) continue;
fWeightList->Add(new AliGFWWeights());
fWeights = (AliGFWWeights*)fWeightList->Last();
fWeights->SetName(Form("weights%s",fSelections[i]->GetSystPF()));
fWeights->Init(!fIsMC,fIsMC); // AddData = !fIsMC; AddMC = fIsMC
}
} else {
//Setup the structure of FC:
TObjArray *OAforPt=new TObjArray();
//No gap:
OAforPt->Add(new TNamed("MidV22","MidV22"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidV22_pt_%i",i+1),"MidV22_pTDiff"));
OAforPt->Add(new TNamed("MidV24","MidV24"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidV24_pt_%i",i+1),"MidV24_pTDiff"));
OAforPt->Add(new TNamed("MidV26","MidV26"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidV26_pt_%i",i+1),"MidV26_pTDiff"));
OAforPt->Add(new TNamed("MidV28","MidV28"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidV28_pt_%i",i+1),"MidV28_pTDiff"));
OAforPt->Add(new TNamed("MidV32","MidV32"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidV32_pt_%i",i+1),"MidV32_pTDiff"));
OAforPt->Add(new TNamed("MidV34","MidV34"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidV34_pt_%i",i+1),"MidV34_pTDiff"));
OAforPt->Add(new TNamed("MidV42","MidV42"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidV42_pt_%i",i+1),"MidV42_pTDiff"));
OAforPt->Add(new TNamed("MidV52","MidV52"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidV52_pt_%i",i+1),"MidV52_pTDiff"));
//2SENeg:
OAforPt->Add(new TNamed("Mid2SENV22","Mid2SENV22"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("Mid2SENV22_pt_%i",i+1),"Mid2SENV22_pTDiff"));
OAforPt->Add(new TNamed("Mid2SENV24","Mid2SENV24"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("Mid2SENV24_pt_%i",i+1),"Mid2SENV24_pTDiff"));
OAforPt->Add(new TNamed("Mid2SENV26","Mid2SENV26"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("Mid2SENV26_pt_%i",i+1),"Mid2SENV26_pTDiff"));
OAforPt->Add(new TNamed("Mid2SENV28","Mid2SENV28"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("Mid2SENV28_pt_%i",i+1),"Mid2SENV28_pTDiff"));
OAforPt->Add(new TNamed("Mid2SENV32","Mid2SENV32"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("Mid2SENV32_pt_%i",i+1),"Mid2SENV32_pTDiff"));
OAforPt->Add(new TNamed("Mid2SENV42","Mid2SENV42"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("Mid2SENV42_pt_%i",i+1),"Mid2SENV42_pTDiff"));
OAforPt->Add(new TNamed("Mid2SENV52","Mid2SENV52"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("Mid2SENV52_pt_%i",i+1),"Mid2SENV52_pTDiff"));
//2SEPos:
OAforPt->Add(new TNamed("Mid2SEPV22","Mid2SEPV22"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("Mid2SEPV22_pt_%i",i+1),"Mid2SEPV22_pTDiff"));
OAforPt->Add(new TNamed("Mid2SEPV24","Mid2SEPV24"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("Mid2SEPV24_pt_%i",i+1),"Mid2SEPV24_pTDiff"));
OAforPt->Add(new TNamed("Mid2SEPV26","Mid2SEPV26"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("Mid2SEPV26_pt_%i",i+1),"Mid2SEPV26_pTDiff"));
OAforPt->Add(new TNamed("Mid2SEPV28","Mid2SEPV28"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("Mid2SEPV28_pt_%i",i+1),"Mid2SEPV28_pTDiff"));
OAforPt->Add(new TNamed("Mid2SEPV32","Mid2SEPV32"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("Mid2SEPV32_pt_%i",i+1),"Mid2SEPV32_pTDiff"));
OAforPt->Add(new TNamed("Mid2SEPV42","Mid2SEPV42"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("Mid2SEPV42_pt_%i",i+1),"Mid2SEPV42_pTDiff"));
OAforPt->Add(new TNamed("Mid2SEPV52","Mid2SEPV52"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("Mid2SEPV52_pt_%i",i+1),"Mid2SEPV52_pTDiff"));
//|eta|>0.5
OAforPt->Add(new TNamed("MidGapNV22","MidGapNV22"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidGapNV22_pt_%i",i+1),"MidGapNV22_pTDiff"));
OAforPt->Add(new TNamed("MidGapNV24","MidGapNV24"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidGapNV24_pt_%i",i+1),"MidGapNV24_pTDiff"));
OAforPt->Add(new TNamed("MidGapNV26","MidGapNV26"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidGapNV26_pt_%i",i+1),"MidGapNV26_pTDiff"));
OAforPt->Add(new TNamed("MidGapNV28","MidGapNV28"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidGapNV28_pt_%i",i+1),"MidGapNV28_pTDiff"));
OAforPt->Add(new TNamed("MidGapNV32","MidGapNV32"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidGapNV32_pt_%i",i+1),"MidGapNV32_pTDiff"));
OAforPt->Add(new TNamed("MidGapNV42","MidGapNV42"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidGapNV42_pt_%i",i+1),"MidGapNV42_pTDiff"));
OAforPt->Add(new TNamed("MidGapNV52","MidGapNV52"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidGapNV52_pt_%i",i+1),"MidGapNV52_pTDiff"));
//|eta|>0.5
OAforPt->Add(new TNamed("MidGapPV22","MidGapPV22"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidGapPV22_pt_%i",i+1),"MidGapPV22_pTDiff"));
OAforPt->Add(new TNamed("MidGapPV24","MidGapPV24"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidGapPV24_pt_%i",i+1),"MidGapPV24_pTDiff"));
OAforPt->Add(new TNamed("MidGapPV26","MidGapPV26"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidGapPV26_pt_%i",i+1),"MidGapPV26_pTDiff"));
OAforPt->Add(new TNamed("MidGapPV28","MidGapPV28"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidGapPV28_pt_%i",i+1),"MidGapPV28_pTDiff"));
OAforPt->Add(new TNamed("MidGapPV32","MidGapPV32"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidGapPV32_pt_%i",i+1),"MidGapPV32_pTDiff"));
OAforPt->Add(new TNamed("MidGapPV42","MidGapPV42"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidGapPV42_pt_%i",i+1),"MidGapPV42_pTDiff"));
OAforPt->Add(new TNamed("MidGapPV52","MidGapPV52"));
for(Int_t i=0;i<fPtAxis->GetNbins();i++)
OAforPt->Add(new TNamed(Form("MidGapPV52_pt_%i",i+1),"MidGapPV52_pTDiff"));
//Multi bins:
Double_t multibins[] = {5,10,20,30,40,50,60,70};
fFC = new AliGFWFlowContainer();
fFC->SetName(Form("FC%s",fSelections[fCurrSystFlag]->GetSystPF()));
fFC->SetXAxis(fPtAxis);
fFC->Initialize(OAforPt,7,multibins,10); //Statistics only required for nominal profiles, so do not create randomized profiles for systematics
//Powers per harmonic:
Int_t NoGap[] = {9,0,8,4,7,2,6,0,5};
Int_t WithGap[] = {5,0,2,2,3,2,4,0,5};
Int_t POIPowers[] = {2,0,2,2,2,2}; //POIs will always be with weight of 1 (or 0, for what matters)
fGFW = new AliGFW();
//Full regions
fGFW->AddRegion("poiMid",6,POIPowers,-0.8,0.8,1+fPtAxis->GetNbins(),1);
fGFW->AddRegion("refMid",9,NoGap,-0.8,0.8,1,2);
//2 subevets:
fGFW->AddRegion("poiSENeg",6,POIPowers,-0.8,0.,1+fPtAxis->GetNbins(),1);
fGFW->AddRegion("refSENeg",9,WithGap,-0.8,0.,1,2);
fGFW->AddRegion("poiSEPos",6,POIPowers,0.,0.8,1+fPtAxis->GetNbins(),1);
fGFW->AddRegion("refSEPos",9,WithGap,0.,0.8,1,2);
//With gap
fGFW->AddRegion("poiGapNeg",6,POIPowers,-0.8,-0.5,1+fPtAxis->GetNbins(),1);
fGFW->AddRegion("refGapNeg",9,WithGap,-0.8,-0.5,1,2);
fGFW->AddRegion("poiGapPos",6,POIPowers,0.5,0.8,1+fPtAxis->GetNbins(),1);
fGFW->AddRegion("refGapPos",9,WithGap,0.5,0.8,1,2);
//Overlap:
fGFW->AddRegion("olMid",9,NoGap,-0.8,0.8,1+fPtAxis->GetNbins(),4);
fGFW->AddRegion("olSENeg",9,WithGap,-0.8,0.,1+fPtAxis->GetNbins(),4);
fGFW->AddRegion("olSEPos",9,WithGap,0.,0.8,1+fPtAxis->GetNbins(),4);
fGFW->AddRegion("olGapNeg",9,WithGap,-0.8,-0.5,1+fPtAxis->GetNbins(),4);
fGFW->AddRegion("olGapPos",9,WithGap,0.5,0.8,1+fPtAxis->GetNbins(),4);
};
if(fProduceWeights) PostData(1,fWeightList);
else PostData(1,fFC);
fMultiDist = new TH1D("Multiplicity_distribution","Multiplicity distribution",100, 0, 100);
PostData(2,fMultiDist);
if(fAddQA) {
fQAList = new TList();
fQAList->SetOwner(kTRUE);
fEventCuts.AddQAplotsToList(fQAList);
PostData(3,fQAList);
};
if(!fProduceWeights) {
if(fIsTrain) {
fCentMap = (TH1D*) GetInputData(1);
if(!fCentMap) AliFatal("Could not fetch centrality map!\n");
} else {
fWeightList = (TList*) GetInputData(1);
if(!fWeightList) { AliFatal("Could not retrieve weight list!\n"); return; };
};
CreateCorrConfigs();
};
// printf("\n******************\nStarting the watch\n*****************\n");
// mywatchFill.Reset();
// mywatchStore.Reset();
// mywatch.Start(kTRUE);
};
AliMCEvent *AliAnalysisTaskGFWFlow::FetchMCEvent(Double_t &impactParameter) {
if(!fIsTrain) { AliFatal("Snap, Jim! Ain't no train here!\n"); return 0; }
AliMCEvent* ev = dynamic_cast<AliMCEvent*>(MCEvent());
if(!ev) { AliFatal("MC event not found!"); return 0; }
AliGenEventHeader *header = dynamic_cast<AliGenEventHeader*>(ev->GenEventHeader());
if(!header) { AliFatal("MC event not generated!"); return 0; }
AliCollisionGeometry* headerH;
TString genName;
TList *ltgen = (TList*)ev->GetCocktailList();
if (ltgen) {
for(auto&& listObject: *ltgen){
genName = Form("%s",listObject->GetName());
if (genName.Contains("Hijing")) {
headerH = dynamic_cast<AliCollisionGeometry*>(listObject);
break;
}
}
}
else
headerH = dynamic_cast<AliCollisionGeometry*>(ev->GenEventHeader());
if(headerH){
impactParameter = headerH->ImpactParameter();
}
return ev;
}
void AliAnalysisTaskGFWFlow::UserExec(Option_t*) {
if(fIsTrain) { //Separate sniplet for running on trains. If it's a train, then do it and be done with it.
Double_t lImpactParameter = -1;
AliMCEvent *fEv = FetchMCEvent(lImpactParameter);
if(!fEv) return;
if(lImpactParameter < 0) AliFatal("Impact parameter is negarive!\n");
Double_t l_Cent = GetCentFromIP(lImpactParameter);
fMultiDist->Fill(l_Cent);
if(l_Cent>70 || l_Cent<5) return; //not considering anything below 5% or above 70%
Int_t nTracks = fEv->GetNumberOfPrimaries();
if(nTracks < 1) { return; }
//GFW stuff:
fGFW->Clear();
for(Int_t i=0;i<nTracks;i++) {
AliMCParticle* lPart = dynamic_cast<AliMCParticle*>(fEv->GetTrack(i));
if(!lPart) { continue; };
Double_t l_pT=lPart->Pt();
Double_t l_phi=lPart->Phi();
Double_t l_eta=lPart->Eta();
Bool_t WithinPtPOI = (fPOIpTMin<l_pT) && (l_pT<fPOIpTMax); //within POI pT range
Bool_t WithinPtRF = (fRFpTMin <l_pT) && (l_pT<fRFpTMax); //within RF pT range
if(!WithinPtPOI && !WithinPtRF) continue; //if the track is not within any pT range, then continue
Int_t l_pTInd = fPtAxis->FindBin(l_pT)-1;
if(WithinPtPOI) fGFW->Fill(l_eta,l_pTInd,l_phi,1,1); //Fill POI (mask = 1). Weights are always 1
if(WithinPtRF) fGFW->Fill(l_eta,l_pTInd,l_phi,1,2); //Fit RF (mask = 2). Weights are always 1
if(WithinPtRF && WithinPtPOI) fGFW->Fill(l_eta,l_pTInd,l_phi,1,4); //Filling overlap. Weights are always 1
};
Bool_t filled;
for(Int_t l_ind=0; l_ind<corrconfigs.size(); l_ind++) {
filled = FillFCs(corrconfigs.at(l_ind),l_Cent,0);//,DisableOL);
};
PostData(1,fFC);
PostData(2,fMultiDist);
return;
}
//This part is on MC production (for weights) or data (for ordinary calculations)
AliAODEvent *fAOD = dynamic_cast<AliAODEvent*>(InputEvent());
if(!fAOD) return;
AliMultSelection *lMultSel = (AliMultSelection*)fInputEvent->FindListObject("MultSelection");
Double_t cent = lMultSel->GetMultiplicityPercentile("V0M");
if(!CheckTriggerVsCentrality(cent)) return;
if(!fProduceWeights)
if(!InitRun()) return;
if(!AcceptEvent()) return;
if(!AcceptAODVertex(fAOD)) return;
fMultiDist->Fill(cent);
if(fIsMC) {
fMCEvent = dynamic_cast<AliMCEvent *>(MCEvent());
if(!fMCEvent)
return;
};
if(fCurrSystFlag==fTotTrackFlags+4) cent = lMultSel->GetMultiplicityPercentile("CL1"); //CL1 flag is EvFlag 4 = N_TrackFlags + 4
if(fCurrSystFlag==fTotTrackFlags+5) cent = lMultSel->GetMultiplicityPercentile("CL0"); //CL0 flag is EvFlag 5 = N_TrackFlags + 5
if(cent<5) return; //Do not consider 0-5%
if(cent>70) return; //Also, peripheral cutoff
Double_t vz = fAOD->GetPrimaryVertex()->GetZ();
Int_t vtxb = GetVtxBit(fAOD);
if(!vtxb) return; //If no vertex pass, then do not consider further
if(fBypassCalculations) return;
//fFlowEvent->SetRunNumber(fAOD->GetRunNumber());
const AliAODVertex* vtx = dynamic_cast<const AliAODVertex*>(fAOD->GetPrimaryVertex());
Double_t POSvtx[] = {0.,0.,0.};
vtx->GetXYZ(POSvtx);
TClonesArray *tca = 0;
if(fProduceWeights) {
if(fIsMC) {
tca = (TClonesArray*)fInputEvent->FindListObject("mcparticles");
for(Int_t i=0;i<tca->GetEntries();i++) {
AliVParticle *lPart;
lPart = (AliAODMCParticle*)tca->At(i);
if(!AcceptParticle(lPart)) continue;
Int_t partbit = GetParticleBit(lPart);
if(!partbit) continue; //if no particle bit is set, no need to continue
Int_t combinedbit = CombineBits(vtxb,partbit);
Int_t count=0;
for(Int_t i=0;i<fTotFlags;++i)
if(fSelections[i]->NeedsExtraWeight()) {
if(combinedbit&(1<<i))
((AliGFWWeights*)fWeightList->At(count))->Fill(lPart->Phi(),lPart->Eta(),vz,lPart->Pt(),cent,2);
count++;
};
};
};
AliAODTrack *lTrack;
for(Int_t lTr=0;lTr<fAOD->GetNumberOfTracks();lTr++) {
lTrack = (AliAODTrack*)fAOD->GetTrack(lTr);
Double_t POStrk[] = {0.,0.,0.};
lTrack->GetXYZ(POStrk);
Double_t DCA[] = {0.,0.,0.};
for(Int_t i=0;i<3;i++) DCA[i] = POSvtx[i]-POStrk[i];
Double_t dcaxy = TMath::Sqrt(DCA[0]*DCA[0]+DCA[1]*DCA[1]);
Double_t lDCA[] = {TMath::Abs(DCA[2]),dcaxy};
Int_t trackbit = GetTrackBit(lTrack,lDCA);
if(!trackbit) continue; //if no track bit is set, no need to continue
Int_t combinedbit = CombineBits(vtxb,trackbit);
if(fIsMC) {
AliVParticle *lPart = (AliAODMCParticle*)tca->At(TMath::Abs(lTrack->GetLabel()));
Int_t count=0;
for(Int_t i=0;i<fTotFlags;++i)
if(fSelections[i]->NeedsExtraWeight()) {
if(combinedbit&(1<<i))
((AliGFWWeights*)fWeightList->At(count))->Fill(lPart->Phi(),lPart->Eta(),vz,lPart->Pt(),cent,1);
count++;
};
} else {
Int_t count=0;
for(Int_t i=0;i<fTotFlags;++i)
if(fSelections[i]->NeedsExtraWeight()) {
if((combinedbit&(1<<i)))
((AliGFWWeights*)fWeightList->At(count))->Fill(lTrack->Phi(),lTrack->Eta(),vz,lTrack->Pt(),cent,0);
count++;
};
};
};
PostData(1,fWeightList);
PostData(2,fMultiDist);
if(fAddQA) PostData(3,fQAList);
return;
} else {
fGFW->Clear();
AliAODTrack *lTrack;
if(!fSelections[fCurrSystFlag]->AcceptVertex(fAOD,1)) return;
// mywatchFill.Start(kFALSE);
for(Int_t lTr=0;lTr<fAOD->GetNumberOfTracks();lTr++) {
lTrack = (AliAODTrack*)fAOD->GetTrack(lTr);
//if(!AcceptAODTrack(lTrack,tca)) continue;
Double_t POStrk[] = {0.,0.,0.};
lTrack->GetXYZ(POStrk);
Double_t DCA[] = {0.,0.,0.};
for(Int_t i=0;i<3;i++) DCA[i] = POSvtx[i]-POStrk[i];
Double_t dcaxy = TMath::Sqrt(DCA[0]*DCA[0]+DCA[1]*DCA[1]);
Double_t lDCA[] = {TMath::Abs(DCA[2]),dcaxy};
if(!fSelections[fCurrSystFlag]->AcceptTrack(lTrack,lDCA) &&
!fSelections[9]->AcceptTrack(lTrack,lDCA)) continue;
Double_t l_pT=lTrack->Pt();
Bool_t WithinPtPOI = (fPOIpTMin<l_pT) && (l_pT<fPOIpTMax); //within POI pT range
Bool_t WithinPtRF = (fRFpTMin <l_pT) && (l_pT<fRFpTMax); //within RF pT range
if(!WithinPtPOI && !WithinPtRF) continue; //if the track is not within any pT range, then continue
if(!fWeights) printf("Weights do not exist!\n");
Double_t nua = fWeights->GetNUA(lTrack->Phi(),lTrack->Eta(),vz);
Double_t nue = 1; //Since doing pT-diff., we can set this to one for speed up.
//To speed up, call getter for NUA directly
//Double_t nua = fWeights->GetWeight(lTrack->Phi(),lTrack->Eta(),vz,l_pT,cent,0);
//Double_t nuaITS = fExtraWeights->GetWeight(lTrack->Phi(),lTrack->Eta(),vz,lTrack->Pt(),cent,0);
//Double_t nue = fPtAxis->GetNbins()>1?1:fWeights->GetWeight(lTrack->Phi(),lTrack->Eta(),vz,cent,l_pT,1);
if(fSelections[fCurrSystFlag]->AcceptTrack(lTrack, lDCA)) {
if(WithinPtPOI) fGFW->Fill(lTrack->Eta(),fPtAxis->FindBin(l_pT)-1,lTrack->Phi(),nua*nue,1); //Fill POI (mask = 1)
if(WithinPtRF) fGFW->Fill(lTrack->Eta(),fPtAxis->FindBin(l_pT)-1,lTrack->Phi(),nua*nue,2); //Fit RF (mask = 2)
if(WithinPtRF && WithinPtPOI) fGFW->Fill(lTrack->Eta(),fPtAxis->FindBin(l_pT)-1,lTrack->Phi(),nua*nue,4); //Filling overlap
}
/*if(fSelections[9]->AcceptTrack(lTrack, lDCA)) //No ITS for now
fGFW->Fill(lTrack->Eta(),fPtAxis->FindBin(lTrack->Pt())-1,lTrack->Phi(),nuaITS*nue,2);*/
};
TRandom rndm(0);
Double_t rndmn=rndm.Rndm();
Bool_t filled;
for(Int_t l_ind=0; l_ind<corrconfigs.size(); l_ind++) {
filled = FillFCs(corrconfigs.at(l_ind),cent,rndmn);//,DisableOL);
};
PostData(1,fFC);
PostData(2,fMultiDist);
if(fAddQA) PostData(3,fQAList);
};
};
void AliAnalysisTaskGFWFlow::Terminate(Option_t*) {
// printf("\n********* Time: %f\n**********",mywatch.RealTime());
// printf("Filling time: %f\n",mywatchFill.RealTime());
// printf("Storing time: %f\n",mywatchStore.RealTime());
};
void AliAnalysisTaskGFWFlow::SetPtBins(Int_t nBins, Double_t *bins, Double_t RFpTMin, Double_t RFpTMax) {
fPtAxis->Set(nBins, bins);
//Set pT range given by the defined pT axis
fPOIpTMin=bins[0];
fPOIpTMax=bins[nBins];
//if RF pT range is not defined, use the same as for POI
fRFpTMin=(RFpTMin<0)?fPOIpTMin:RFpTMin;
fRFpTMax=(RFpTMax<0)?fPOIpTMax:RFpTMax;
}
Bool_t AliAnalysisTaskGFWFlow::AcceptEvent() {
if(!fEventCuts.AcceptEvent(fInputEvent)) return 0;
if(fCurrSystFlag==15) if(!fEventCutsForPU.AcceptEvent(fInputEvent)) return 0; //For a tight PU cut, an additional selection
return kTRUE;
};
Bool_t AliAnalysisTaskGFWFlow::CheckTriggerVsCentrality(Double_t l_cent) {
UInt_t fSelMask = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected();
//if(!(fSelMask&fTriggerType)) return kFALSE;
Bool_t centTrigger = (fSelMask&(AliVEvent::kCentral)&fTriggerType) && l_cent>0 && l_cent<10; //fTriggerType& removed
Bool_t semiCentTri = (fSelMask&(AliVEvent::kSemiCentral)&fTriggerType) && l_cent>30 && l_cent<50; //fTriggerType& removed
Bool_t MBTrigger = (fSelMask&(AliVEvent::kMB+AliVEvent::kINT7)&fTriggerType); //fTriggerType& removed
if(centTrigger || semiCentTri || MBTrigger) return kTRUE;
return kFALSE;
}
Bool_t AliAnalysisTaskGFWFlow::AcceptAODVertex(AliAODEvent *inEv) {
const AliAODVertex* vtx = dynamic_cast<const AliAODVertex*>(inEv->GetPrimaryVertex());
if(!vtx || vtx->GetNContributors() < 1)
return kFALSE;
const AliAODVertex* vtxSPD = dynamic_cast<const AliAODVertex*>(inEv->GetPrimaryVertexSPD());
Double_t dMaxResol = 0.25; // suggested from DPG
Double_t cov[6] = {0};
vtxSPD->GetCovarianceMatrix(cov);
Double_t zRes = TMath::Sqrt(cov[5]);
if ( vtxSPD->IsFromVertexerZ() && (zRes > dMaxResol)) return kFALSE;
const Double_t aodVtxZ = vtx->GetZ();
if(TMath::Abs(aodVtxZ) > 10)
return kFALSE;
return kTRUE;
};
Bool_t AliAnalysisTaskGFWFlow::AcceptParticle(AliVParticle *mpa) {
if(!mpa->IsPhysicalPrimary()) return kFALSE;
if(mpa->Charge()==0) return kFALSE;
if(TMath::Abs(mpa->Eta())>0.8) return kFALSE;
if(mpa->Pt()<0.3) return kFALSE;
if(mpa->Pt()>20) return kFALSE;
return kTRUE;
};
Int_t AliAnalysisTaskGFWFlow::GetVtxBit(AliAODEvent *mev) {
Int_t retbit=0;
for(Int_t vtxst=fTotTrackFlags+1;vtxst<fTotFlags; vtxst++) //vtx flags are 9-14
retbit+=fSelections[vtxst]->AcceptVertex(mev,vtxst);
//PU unc. bit has been set with a wide cut. Override with a check w/ smaller cut:
Int_t PUSystFlag = 1<<(fTotTrackFlags+6);//PU syst. flag is 6-th in ev/vtx selection
//Only override if the event has passed the initial selection:
if((retbit&PUSystFlag)==PUSystFlag) //if event accepted by nominal cuts
if(!fEventCutsForPU.AcceptEvent(mev)) //Check if it gets rejected by the PU cut
retbit-=PUSystFlag; //and if so, set the PU flag to zero
retbit+=fSelections[0]->AcceptVertex(mev); //the standard one
return retbit;
};
Int_t AliAnalysisTaskGFWFlow::GetParticleBit(AliVParticle *mpa) {
Int_t retbit=0;
for(Int_t i=1;i<=fTotTrackFlags;i++)
retbit+=fSelections[i]->AcceptParticle(mpa,i);
retbit+=fSelections[0]->AcceptParticle(mpa);
return retbit;
};
Int_t AliAnalysisTaskGFWFlow::GetTrackBit(AliAODTrack* mtr, Double_t *lDCA) {
Int_t retbit=0;
for(Int_t i=1;i<=fTotTrackFlags; i++) //track flags are 1-8
retbit+=fSelections[i]->AcceptTrack(mtr,lDCA,i);
//Nominal (TPC) tracks:
retbit+=fSelections[0]->AcceptTrack(mtr,lDCA);
//Also, add the ITS tracks:
//retbit+=fSelections[12]->AcceptTrack(mtr,lDCA,12); //
return retbit;
};
Int_t AliAnalysisTaskGFWFlow::CombineBits(Int_t VtxBit, Int_t TrkBit) {
Int_t retbit=((VtxBit&1)*TrkBit | (TrkBit&1)*VtxBit);
//Also add ITS track (bit 12), if the nominal vtx bit is set:
//retbit=retbit|((VtxBit&1)*(TrkBit&(1<<13)));
return retbit;
};
Bool_t AliAnalysisTaskGFWFlow::SetInputWeightList(TList *inlist) {
if(!inlist) {
return kFALSE;
};
fWeightList = inlist;
return kTRUE;
};
Bool_t AliAnalysisTaskGFWFlow::LoadWeights(Int_t runno) { //Cannot be used when running on the trains
if(fWeightList) {
fWeights = (AliGFWWeights*)fWeightList->FindObject(Form("w%i%s",runno,fSelections[fCurrSystFlag]->NeedsExtraWeight()?
fSelections[fCurrSystFlag]->GetSystPF():""));
if(!fWeights) {
AliFatal("Weights could not be found in the list!\n");
return kFALSE;
};
fWeights->CreateNUA();
fWeights->CreateNUE();
return kTRUE;
} else {
AliFatal("Weight list (for some reason) not set!\n");
return kFALSE;
};
printf("You should not be here!\n");
return kFALSE;
//If weights not set, attempting to fetch them from pre-set directory. This will definitely fail if running on train
fWeightPath.Clear();
fWeightPath.Append(fWeightDir.Data());
fWeightPath.Append(Form("%i.root",runno));
TFile *tfWeights = TFile::Open(fWeightPath.Data());
if(!tfWeights) {
printf("Could not open %s!\n",fWeightPath.Data());
return kFALSE;
};
TList *l_List = (TList*)tfWeights->Get("OutputList");
if(!l_List) printf("\n\n\n\n\n\n**************************\n\n\n\n\n\n Could not fetch OutputList!\n\n\n\n");
TString l_weightname(fSelections[fSelections[fCurrSystFlag]->NeedsExtraWeight()?fCurrSystFlag:0]->GetSystPF());
fWeights = (AliGFWWeights*)l_List->FindObject(Form("weights%s",l_weightname.Data()));
if(!fWeights) {
printf("Could not fetch weights%s from %s!\n",fSelections[fCurrSystFlag]->GetSystPF(),fWeightPath.Data());
return kFALSE;
};
fExtraWeights = (AliGFWWeights*)tfWeights->Get(Form("weights%s",fSelections[9]->GetSystPF()));//Used for when several weights are need (e.g. ITS): (Weights*)tfWeights->Get(Form("weights%s",fSelections[12]->GetSystPF()));
tfWeights->Close();
if(!fWeights) return kFALSE;
fWeights->CreateNUA();
fWeights->CreateNUE();
if(fExtraWeights) {
fExtraWeights->CreateNUA();
fExtraWeights->CreateNUE();
};
return kTRUE;
};
Bool_t AliAnalysisTaskGFWFlow::InitRun() {
if(!fInputEvent) return kFALSE;
Int_t runno = fInputEvent->GetRunNumber();
if(fRunNo!=runno) {
if(!LoadWeights(runno))
return kFALSE;
else
fRunNo = runno;
//Run has changed; need to re-override the PU cut in AliEventCuts:
Bool_t dump1 = fEventCuts.AcceptEvent(fInputEvent);//To setup all the event cuts (automatically)
dump1 = fEventCutsForPU.AcceptEvent(fInputEvent);//To setup all the event cuts (automatically)
fEventCuts.fUseVariablesCorrelationCuts = kTRUE; //By default this is not used (for some reason?)
//Also for the PU systematics:
fEventCutsForPU.fUseVariablesCorrelationCuts = kTRUE;
fEventCutsForPU.fESDvsTPConlyLinearCut[0] = 1500; //Cut for systematic (nominal is 15 000)
};
return kTRUE;
};
Bool_t AliAnalysisTaskGFWFlow::FillFCs(TString head, TString hn, Double_t cent, Bool_t diff, Double_t rndmn) {
Double_t dnx, val;
dnx = fGFW->Calculate(hn,kTRUE).Re();
if(dnx==0) return kFALSE;
if(!diff) {
val = fGFW->Calculate(hn).Re()/dnx;
if(TMath::Abs(val)<1)
fFC->FillProfile(head.Data(),cent,val,dnx,rndmn);
return kTRUE;
};
for(Int_t i=1;i<=fPtAxis->GetNbins();i++) {
TString tss(hn);
tss.Prepend(Form("(%i) ",i-1));
dnx = fGFW->Calculate(tss,kTRUE).Re();
if(dnx==0) continue;
val = fGFW->Calculate(tss).Re()/dnx;
if(TMath::Abs(val)<1)
fFC->FillProfile(Form("%s_pt_%i",head.Data(),i),cent,val,dnx,rndmn);
};
return kTRUE;
};
Bool_t AliAnalysisTaskGFWFlow::FillFCs(AliGFW::CorrConfig corconf, Double_t cent, Double_t rndmn, Bool_t DisableOverlap) {
Double_t dnx, val;
dnx = fGFW->Calculate(corconf,0,kTRUE).Re();
if(dnx==0) return kFALSE;
if(!corconf.pTDif) {
val = fGFW->Calculate(corconf,0,kFALSE).Re()/dnx;
if(TMath::Abs(val)<1)
fFC->FillProfile(corconf.Head.Data(),cent,val,dnx,rndmn);
return kTRUE;
};
/*Int_t binDisableOLFrom = fPtAxis->GetNbins()+1;
if(DisableOverlap)
binDisableOLFrom = fPtAxis->FindBin(fRFpTMax); //To stay in the right bin*/
Bool_t NeedToDisable=kFALSE;
for(Int_t i=1;i<=fPtAxis->GetNbins();i++) {
//if(DisableOverlap) NeedToDisable=(i>=binDisableOLFrom);
dnx = fGFW->Calculate(corconf,i-1,kTRUE,NeedToDisable).Re();
if(dnx==0) continue;
val = fGFW->Calculate(corconf,i-1,kFALSE,NeedToDisable).Re()/dnx;
if(TMath::Abs(val)<1)
fFC->FillProfile(Form("%s_pt_%i",corconf.Head.Data(),i),cent,val,dnx,rndmn);
};
return kTRUE;
};
void AliAnalysisTaskGFWFlow::CreateCorrConfigs() {
// corrconfigs = new AliGFW::CorrConfig[90];
corrconfigs.push_back(GetConf("MidV22","refMid {2 -2}", kFALSE));
corrconfigs.push_back(GetConf("MidV22","poiMid refMid | olMid {2 -2}", kTRUE));
corrconfigs.push_back(GetConf("MidV24","refMid {2 2 -2 -2}", kFALSE));
corrconfigs.push_back(GetConf("MidV24","poiMid refMid | olMid {2 2 -2 -2}", kTRUE));
corrconfigs.push_back(GetConf("MidV26","refMid {2 2 2 -2 -2 -2}", kFALSE));
corrconfigs.push_back(GetConf("MidV26","poiMid refMid | olMid {2 2 2 -2 -2 -2}", kTRUE));
corrconfigs.push_back(GetConf("MidV28","refMid {2 2 2 2 -2 -2 -2 -2}", kFALSE));
corrconfigs.push_back(GetConf("MidV28","poiMid refMid | olMid {2 2 2 2 -2 -2 -2 -2}", kTRUE));
corrconfigs.push_back(GetConf("MidV32","refMid {3 -3}", kFALSE));
corrconfigs.push_back(GetConf("MidV32","poiMid refMid | olMid {3 -3}", kTRUE));
corrconfigs.push_back(GetConf("MidV34","refMid {3 3 -3 -3}", kFALSE));
corrconfigs.push_back(GetConf("MidV34","poiMid refMid | olMid {3 3 -3 -3}", kTRUE));
corrconfigs.push_back(GetConf("MidV42","refMid {4 -4}", kFALSE));
corrconfigs.push_back(GetConf("MidV42","poiMid refMid | olMid {4 -4}", kTRUE));
corrconfigs.push_back(GetConf("MidV52","poiMid refMid | olMid {5 -5}", kTRUE));
corrconfigs.push_back(GetConf("Mid2SENV22","refSENeg {2} refSEPos {-2}", kFALSE));
corrconfigs.push_back(GetConf("Mid2SENV24","refSENeg {2 2} refSEPos {-2 -2}", kFALSE));
corrconfigs.push_back(GetConf("Mid2SENV26","refSENeg {2 2 2} refSEPos {-2 -2 -2}", kFALSE));
corrconfigs.push_back(GetConf("Mid2SENV28","refSENeg {2 2 2 2} refSEPos {-2 -2 -2 -2}", kFALSE));
corrconfigs.push_back(GetConf("Mid2SENV22","poiSENeg refSENeg | olSENeg {2} refSEPos {-2}", kTRUE));
corrconfigs.push_back(GetConf("Mid2SENV24","poiSENeg refSENeg | olSENeg {2 2} refSEPos {-2 -2}", kTRUE));
corrconfigs.push_back(GetConf("Mid2SENV26","poiSENeg refSENeg | olSENeg {2 2 2} refSEPos {-2 -2 -2}", kTRUE));
corrconfigs.push_back(GetConf("Mid2SENV28","poiSENeg refSENeg | olSENeg {2 2 2 2} refSEPos {-2 -2 -2 -2}", kTRUE));
corrconfigs.push_back(GetConf("Mid2SEPV22","refSEPos {2} refSENeg {-2}", kFALSE));
corrconfigs.push_back(GetConf("Mid2SEPV24","refSEPos {2 2} refSENeg {-2 -2}", kFALSE));
corrconfigs.push_back(GetConf("Mid2SEPV26","refSEPos {2 2 2} refSENeg {-2 -2 -2}", kFALSE));
corrconfigs.push_back(GetConf("Mid2SEPV28","refSEPos {2 2 2 2} refSENeg {-2 -2 -2 -2}", kFALSE));
corrconfigs.push_back(GetConf("Mid2SEPV22","poiSEPos refSEPos | olSEPos {2} refSENeg {-2}", kTRUE));
corrconfigs.push_back(GetConf("Mid2SEPV24","poiSEPos refSEPos | olSEPos {2 2} refSENeg {-2 -2}", kTRUE));
corrconfigs.push_back(GetConf("Mid2SEPV26","poiSEPos refSEPos | olSEPos {2 2 2} refSENeg {-2 -2 -2}", kTRUE));
corrconfigs.push_back(GetConf("Mid2SEPV28","poiSEPos refSEPos | olSEPos {2 2 2 2} refSENeg {-2 -2 -2 -2}", kTRUE));
corrconfigs.push_back(GetConf("Mid2SENV32","refSENeg {3} refSEPos {-3}", kFALSE));
corrconfigs.push_back(GetConf("Mid2SENV32","poiSENeg refSENeg | olSENeg {3} refSEPos {-3}", kTRUE));
corrconfigs.push_back(GetConf("Mid2SEPV32","refSEPos {3} refSENeg {-3}", kFALSE));
corrconfigs.push_back(GetConf("Mid2SEPV32","poiSEPos refSEPos | olSEPos {3} refSENeg {-3}", kTRUE));
corrconfigs.push_back(GetConf("Mid2SENV42","refSENeg {4} refSEPos {-4}", kFALSE));
corrconfigs.push_back(GetConf("Mid2SENV42","poiSENeg refSENeg | olSENeg {4} refSEPos {-4}", kTRUE));
corrconfigs.push_back(GetConf("Mid2SEPV42","refSEPos {4} refSENeg {-4}", kFALSE));
corrconfigs.push_back(GetConf("Mid2SEPV42","poiSEPos refSEPos | olSEPos {4} refSENeg {-4}", kTRUE));
corrconfigs.push_back(GetConf("Mid2SENV52","refSENeg {5} refSEPos {-5}", kFALSE));
corrconfigs.push_back(GetConf("Mid2SENV52","poiSENeg refSENeg | olSENeg {5} refSEPos {-5}", kTRUE));
corrconfigs.push_back(GetConf("Mid2SEPV52","refSEPos {5} refSENeg {-5}", kFALSE));
corrconfigs.push_back(GetConf("Mid2SEPV52","poiSEPos refSEPos | olSEPos {5} refSENeg {-5}", kTRUE));
corrconfigs.push_back(GetConf("MidGapNV22","refGapNeg {2} refGapPos {-2}", kFALSE));
corrconfigs.push_back(GetConf("MidGapNV24","refGapNeg {2 2} refGapPos {-2 -2}", kFALSE));
corrconfigs.push_back(GetConf("MidGapNV26","refGapNeg {2 2 2} refGapPos {-2 -2 -2}", kFALSE));
corrconfigs.push_back(GetConf("MidGapNV28","refGapNeg {2 2 2 2} refGapPos {-2 -2 -2 -2}", kFALSE));
corrconfigs.push_back(GetConf("MidGapNV22","poiGapNeg refGapNeg | olGapNeg {2} refGapPos {-2}", kTRUE));
corrconfigs.push_back(GetConf("MidGapNV24","poiGapNeg refGapNeg | olGapNeg {2 2} refGapPos {-2 -2}", kTRUE));
corrconfigs.push_back(GetConf("MidGapNV26","poiGapNeg refGapNeg | olGapNeg {2 2 2} refGapPos {-2 -2 -2}", kTRUE));
corrconfigs.push_back(GetConf("MidGapNV28","poiGapNeg refGapNeg | olGapNeg {2 2 2 2} refGapPos {-2 -2 -2 -2}", kTRUE));
corrconfigs.push_back(GetConf("MidGapPV22","refGapPos {2} refGapNeg {-2}", kFALSE));
corrconfigs.push_back(GetConf("MidGapPV24","refGapPos {2 2} refGapNeg {-2 -2}", kFALSE));
corrconfigs.push_back(GetConf("MidGapPV26","refGapPos {2 2 2} refGapNeg {-2 -2 -2}", kFALSE));
corrconfigs.push_back(GetConf("MidGapPV28","refGapPos {2 2 2 2} refGapNeg {-2 -2 -2 -2}", kFALSE));
corrconfigs.push_back(GetConf("MidGapPV22","poiGapPos refGapPos | olGapPos {2} refGapNeg {-2}", kTRUE));
corrconfigs.push_back(GetConf("MidGapPV24","poiGapPos refGapPos | olGapPos {2 2} refGapNeg {-2 -2}", kTRUE));
corrconfigs.push_back(GetConf("MidGapPV26","poiGapPos refGapPos | olGapPos {2 2 2} refGapNeg {-2 -2 -2}", kTRUE));
corrconfigs.push_back(GetConf("MidGapPV28","poiGapPos refGapPos | olGapPos {2 2 2 2} refGapNeg {-2 -2 -2 -2}", kTRUE));
corrconfigs.push_back(GetConf("MidGapNV32","refGapNeg {3} refGapPos {-3}", kFALSE));
corrconfigs.push_back(GetConf("MidGapNV32","poiGapNeg refGapNeg | olGapNeg {3} refGapPos {-3}", kTRUE));
corrconfigs.push_back(GetConf("MidGapPV32","refGapPos {3} refGapNeg {-3}", kFALSE));
corrconfigs.push_back(GetConf("MidGapPV32","poiGapPos refGapPos | olGapPos {3} refGapNeg {-3}", kTRUE));
corrconfigs.push_back(GetConf("MidGapNV42","refGapNeg {4} refGapPos {-4}", kFALSE));
corrconfigs.push_back(GetConf("MidGapNV42","poiGapNeg refGapNeg | olGapNeg {4} refGapPos {-4}", kTRUE));
corrconfigs.push_back(GetConf("MidGapPV42","refGapPos {4} refGapNeg {-4}", kFALSE));
corrconfigs.push_back(GetConf("MidGapPV42","poiGapPos refGapPos | olGapPos {4} refGapNeg {-4}", kTRUE));
corrconfigs.push_back(GetConf("MidGapNV52","refGapNeg {5} refGapPos {-5}", kFALSE));
corrconfigs.push_back(GetConf("MidGapNV52","poiGapNeg refGapNeg | olGapNeg {5} refGapPos {-5}", kTRUE));
corrconfigs.push_back(GetConf("MidGapPV52","refGapPos {5} refGapNeg {-5}", kFALSE));
corrconfigs.push_back(GetConf("MidGapPV52","poiGapPos refGapPos | olGapPos {5} refGapNeg {-5}", kTRUE));
}
| [
"vytautas.vislavicius@cern.ch"
] | vytautas.vislavicius@cern.ch |
4e9df38fca2e810e98d9b0f5326098bd5e31cb1f | d2329d44c56d5170273cde838fd0d07ca43e86f4 | /explore/include/explore/frontier_search.h | e0e228e6b22b4113a107adb7d0bd24a71492350d | [
"BSD-3-Clause"
] | permissive | hrnr/m-explore | 234bc5647cf4075f3f1a5c04b033133f8901ff1a | 712bdd41027b645c9c876a4c0071478f090825ea | refs/heads/noetic-devel | 2021-11-18T01:57:00.577605 | 2021-01-07T20:52:23 | 2021-01-07T20:52:23 | 37,943,241 | 265 | 201 | NOASSERTION | 2021-08-03T13:28:53 | 2015-06-23T20:30:19 | C++ | UTF-8 | C++ | false | false | 2,403 | h | #ifndef FRONTIER_SEARCH_H_
#define FRONTIER_SEARCH_H_
#include <costmap_2d/costmap_2d.h>
namespace frontier_exploration
{
/**
* @brief Represents a frontier
*
*/
struct Frontier {
std::uint32_t size;
double min_distance;
double cost;
geometry_msgs::Point initial;
geometry_msgs::Point centroid;
geometry_msgs::Point middle;
std::vector<geometry_msgs::Point> points;
};
/**
* @brief Thread-safe implementation of a frontier-search task for an input
* costmap.
*/
class FrontierSearch
{
public:
FrontierSearch()
{
}
/**
* @brief Constructor for search task
* @param costmap Reference to costmap data to search.
*/
FrontierSearch(costmap_2d::Costmap2D* costmap, double potential_scale,
double gain_scale, double min_frontier_size);
/**
* @brief Runs search implementation, outward from the start position
* @param position Initial position to search from
* @return List of frontiers, if any
*/
std::vector<Frontier> searchFrom(geometry_msgs::Point position);
protected:
/**
* @brief Starting from an initial cell, build a frontier from valid adjacent
* cells
* @param initial_cell Index of cell to start frontier building
* @param reference Reference index to calculate position from
* @param frontier_flag Flag vector indicating which cells are already marked
* as frontiers
* @return new frontier
*/
Frontier buildNewFrontier(unsigned int initial_cell, unsigned int reference,
std::vector<bool>& frontier_flag);
/**
* @brief isNewFrontierCell Evaluate if candidate cell is a valid candidate
* for a new frontier.
* @param idx Index of candidate cell
* @param frontier_flag Flag vector indicating which cells are already marked
* as frontiers
* @return true if the cell is frontier cell
*/
bool isNewFrontierCell(unsigned int idx,
const std::vector<bool>& frontier_flag);
/**
* @brief computes frontier cost
* @details cost function is defined by potential_scale and gain_scale
*
* @param frontier frontier for which compute the cost
* @return cost of the frontier
*/
double frontierCost(const Frontier& frontier);
private:
costmap_2d::Costmap2D* costmap_;
unsigned char* map_;
unsigned int size_x_, size_y_;
double potential_scale_, gain_scale_;
double min_frontier_size_;
};
}
#endif
| [
"laeqten@gmail.com"
] | laeqten@gmail.com |
10ba13bb834c8aaff9b85a79aab5f68026840651 | 0c67596783571beced4abaeef31e91e86e1e9b0e | /Dynamixel/Multiple_MasterSlave/MasterCode/DynamixelSerial.cpp | 7fc1056b3aeaf70570bd3cb14e77610a89e689cc | [
"Apache-2.0"
] | permissive | Maxx84/arduino-projects | 42d3d0e5b01eebc4edcff5bc5045693256a70640 | 75ee7a82b2a39db46061e661e58bf17ae7019282 | refs/heads/master | 2018-09-17T19:24:53.470347 | 2018-06-05T21:12:08 | 2018-06-05T21:12:08 | 109,765,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,087 | cpp | /*
Dynamixel.cpp - Ax-12+ Half Duplex USART Comunication
Copyright (c) 2011 Savage Electronics.
Created by Savage on 27/01/11.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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 GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************
Modifications:
25/07/2011 - Eliminado la modificacion serial para ser modificada dentro del mismo Hardware Serial.
25/07/2011 - Modificado la funcion setBD() para aceptar todas la velocidades sin PDF.
25/07/2011 - Agregada la funcion de Rotacion Continua.
26/07/2011 - Agregada la funcion begin sin seteo de Direction_Pin.
25/07/2011 - Agregada la funcion Reset.
26/07/2011 - Agregada la funcion Reg_Write en move y moveSpeed.
26/07/2011 - Agregada la funcion Action.
13/12/2011 - Arreglado el manejo y envio de variables.
22/12/2011 - Compatible con la actualizacion Arduino 1.0.
10/01/2012 - Utilizacion de Macros y eliminacion codigo no necesario.
11/01/2012 - Agregadas las funciones:
int setTempLimit(unsigned char ID, unsigned char Temperature);
int setAngleLimit(unsigned char ID, int CWLimit, int CCWLimit);
int setVoltageLimit(unsigned char ID, unsigned char DVoltage, unsigned char UVoltage);
int setMaxTorque(unsigned char ID, int MaxTorque);
int setSRL(unsigned char ID, unsigned char SRL);
int setRDT(unsigned char ID, unsigned char RDT);
int setLEDAlarm(unsigned char ID, unsigned char LEDAlarm);
int setShutdownAlarm(unsigned char ID, unsigned char SALARM);
int setCMargin(unsigned char ID, unsigned char CWCMargin, unsigned char CCWCMargin);
int setCSlope(unsigned char ID, unsigned char CWCSlope, unsigned char CCWCSlope);
15/01/2012 - Agregadas las funciones:
int setPunch(unsigned char ID, int Punch);
int moving(unsigned char ID);
int lockRegister(unsigned char ID);
int RWStatus(unsigned char ID);
int readSpeed(unsigned char ID);
int readLoad(unsigned char ID);
TODO:
FUNCION SYNCWRITE.
*****************************************************************************
Contact: savageelectronics@gmail.com
Web: http://savageelectrtonics.blogspot.com/
Autor: Josue Alejandro Savage
*/
#if defined(ARDUINO) && ARDUINO >= 100 // Arduino IDE Version
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "DynamixelSerial.h"
// Macro for the selection of the Serial Port
#define sendData(args) (Serial.write(args)) // Write Over Serial
#define availableData() (Serial.available()) // Check Serial Data Available
#define readData() (Serial.read()) // Read Serial Data
#define peekData() (Serial.peek()) // Peek Serial Data
#define beginCom(args) (Serial.begin(args)) // Begin Serial Comunication
#define endCom() (Serial.end()) // End Serial Comunication
// Macro for Timing
#define delayus(args) (delayMicroseconds(args)) // Delay Microseconds
// Macro for Comunication Flow Control
#define setDPin(DirPin,Mode) (pinMode(DirPin,Mode)) // Select the Switch to TX/RX Mode Pin
#define switchCom(DirPin,Mode) (digitalWrite(DirPin,Mode)) // Switch to TX/RX Mode
// Private Methods //////////////////////////////////////////////////////////////
int DynamixelClass::read_error(void)
{
Time_Counter = 0;
while((availableData() < 5) & (Time_Counter < TIME_OUT)){ // Wait for Data
Time_Counter++;
delayus(1000);
}
while (availableData() > 0){
Incoming_Byte = readData();
if ( (Incoming_Byte == 255) & (peekData() == 255) ){
readData(); // Start Bytes
readData(); // Ax-12 ID
readData(); // Length
Error_Byte = readData(); // Error
return (Error_Byte);
}
}
return (-1); // No Ax Response
}
// Public Methods //////////////////////////////////////////////////////////////
void DynamixelClass::begin(long baud, unsigned char directionPin)
{
Direction_Pin = directionPin;
setDPin(Direction_Pin,OUTPUT);
beginCom(baud);
}
void DynamixelClass::begin(long baud)
{
beginCom(baud);
}
void DynamixelClass::end()
{
endCom();
}
int DynamixelClass::reset(unsigned char ID)
{
Checksum = (~(ID + AX_RESET_LENGTH + AX_RESET))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START);
sendData(AX_START);
sendData(ID);
sendData(AX_RESET_LENGTH);
sendData(AX_RESET);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error());
}
int DynamixelClass::ping(unsigned char ID)
{
Checksum = (~(ID + AX_READ_DATA + AX_PING))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START);
sendData(AX_START);
sendData(ID);
sendData(AX_READ_DATA);
sendData(AX_PING);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error());
}
int DynamixelClass::setID(unsigned char ID, unsigned char newID)
{
Checksum = (~(ID + AX_ID_LENGTH + AX_WRITE_DATA + AX_ID + newID))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_ID_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_ID);
sendData(newID);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
int DynamixelClass::setBD(unsigned char ID, long baud)
{
unsigned char Baud_Rate = (2000000/baud) - 1;
Checksum = (~(ID + AX_BD_LENGTH + AX_WRITE_DATA + AX_BAUD_RATE + Baud_Rate))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_BD_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_BAUD_RATE);
sendData(Baud_Rate);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
int DynamixelClass::move(unsigned char ID, int Position)
{
char Position_H,Position_L;
Position_H = Position >> 8; // 16 bits - 2 x 8 bits variables
Position_L = Position;
Checksum = (~(ID + AX_GOAL_LENGTH + AX_WRITE_DATA + AX_GOAL_POSITION_L + Position_L + Position_H))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_GOAL_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_GOAL_POSITION_L);
sendData(Position_L);
sendData(Position_H);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
int DynamixelClass::moveSpeed(unsigned char ID, int Position, int Speed)
{
char Position_H,Position_L,Speed_H,Speed_L;
Position_H = Position >> 8;
Position_L = Position; // 16 bits - 2 x 8 bits variables
Speed_H = Speed >> 8;
Speed_L = Speed; // 16 bits - 2 x 8 bits variables
Checksum = (~(ID + AX_GOAL_SP_LENGTH + AX_WRITE_DATA + AX_GOAL_POSITION_L + Position_L + Position_H + Speed_L + Speed_H))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_GOAL_SP_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_GOAL_POSITION_L);
sendData(Position_L);
sendData(Position_H);
sendData(Speed_L);
sendData(Speed_H);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
int DynamixelClass::setEndless(unsigned char ID, bool Status)
{
if ( Status ) {
char AX_CCW_AL_LT = 0; // Changing the CCW Angle Limits for Full Rotation.
Checksum = (~(ID + AX_GOAL_LENGTH + AX_WRITE_DATA + AX_CCW_ANGLE_LIMIT_L))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_GOAL_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_CCW_ANGLE_LIMIT_L );
sendData(AX_CCW_AL_LT);
sendData(AX_CCW_AL_LT);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return(read_error());
}
else
{
turn(ID,0,0);
Checksum = (~(ID + AX_GOAL_LENGTH + AX_WRITE_DATA + AX_CCW_ANGLE_LIMIT_L + AX_CCW_AL_L + AX_CCW_AL_H))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_GOAL_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_CCW_ANGLE_LIMIT_L);
sendData(AX_CCW_AL_L);
sendData(AX_CCW_AL_H);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
}
int DynamixelClass::turn(unsigned char ID, bool SIDE, int Speed)
{
if (SIDE == 0){ // Move Left///////////////////////////
char Speed_H,Speed_L;
Speed_H = Speed >> 8;
Speed_L = Speed; // 16 bits - 2 x 8 bits variables
Checksum = (~(ID + AX_SPEED_LENGTH + AX_WRITE_DATA + AX_GOAL_SPEED_L + Speed_L + Speed_H))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_SPEED_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_GOAL_SPEED_L);
sendData(Speed_L);
sendData(Speed_H);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return(read_error()); // Return the read error
}
else
{ // Move Rigth////////////////////
char Speed_H,Speed_L;
Speed_H = (Speed >> 8) + 4;
Speed_L = Speed; // 16 bits - 2 x 8 bits variables
Checksum = (~(ID + AX_SPEED_LENGTH + AX_WRITE_DATA + AX_GOAL_SPEED_L + Speed_L + Speed_H))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_SPEED_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_GOAL_SPEED_L);
sendData(Speed_L);
sendData(Speed_H);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return(read_error()); // Return the read error
}
}
int DynamixelClass::moveRW(unsigned char ID, int Position)
{
char Position_H,Position_L;
Position_H = Position >> 8; // 16 bits - 2 x 8 bits variables
Position_L = Position;
Checksum = (~(ID + AX_GOAL_LENGTH + AX_REG_WRITE + AX_GOAL_POSITION_L + Position_L + Position_H))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_GOAL_LENGTH);
sendData(AX_REG_WRITE);
sendData(AX_GOAL_POSITION_L);
sendData(Position_L);
sendData(Position_H);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
int DynamixelClass::moveSpeedRW(unsigned char ID, int Position, int Speed)
{
char Position_H,Position_L,Speed_H,Speed_L;
Position_H = Position >> 8;
Position_L = Position; // 16 bits - 2 x 8 bits variables
Speed_H = Speed >> 8;
Speed_L = Speed; // 16 bits - 2 x 8 bits variables
Checksum = (~(ID + AX_GOAL_SP_LENGTH + AX_REG_WRITE + AX_GOAL_POSITION_L + Position_L + Position_H + Speed_L + Speed_H))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_GOAL_SP_LENGTH);
sendData(AX_REG_WRITE);
sendData(AX_GOAL_POSITION_L);
sendData(Position_L);
sendData(Position_H);
sendData(Speed_L);
sendData(Speed_H);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
void DynamixelClass::action()
{
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(BROADCAST_ID);
sendData(AX_ACTION_LENGTH);
sendData(AX_ACTION);
sendData(AX_ACTION_CHECKSUM);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
}
int DynamixelClass::torqueStatus( unsigned char ID, bool Status)
{
Checksum = (~(ID + AX_TORQUE_LENGTH + AX_WRITE_DATA + AX_TORQUE_ENABLE + Status))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_TORQUE_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_TORQUE_ENABLE);
sendData(Status);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
int DynamixelClass::ledStatus(unsigned char ID, bool Status)
{
Checksum = (~(ID + AX_LED_LENGTH + AX_WRITE_DATA + AX_LED + Status))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_LED_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_LED);
sendData(Status);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
int DynamixelClass::readTemperature(unsigned char ID)
{
Checksum = (~(ID + AX_TEM_LENGTH + AX_READ_DATA + AX_PRESENT_TEMPERATURE + AX_BYTE_READ))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START);
sendData(AX_START);
sendData(ID);
sendData(AX_TEM_LENGTH);
sendData(AX_READ_DATA);
sendData(AX_PRESENT_TEMPERATURE);
sendData(AX_BYTE_READ);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
Temperature_Byte = -1;
Time_Counter = 0;
while((availableData() < 6) & (Time_Counter < TIME_OUT)){
Time_Counter++;
delayus(1000);
}
while (availableData() > 0){
Incoming_Byte = readData();
if ( (Incoming_Byte == 255) & (peekData() == 255) ){
readData(); // Start Bytes
readData(); // Ax-12 ID
readData(); // Length
if( (Error_Byte = readData()) != 0 ) // Error
return (Error_Byte*(-1));
Temperature_Byte = readData(); // Temperature
}
}
return (Temperature_Byte); // Returns the read temperature
}
int DynamixelClass::readPosition(unsigned char ID)
{
Checksum = (~(ID + AX_POS_LENGTH + AX_READ_DATA + AX_PRESENT_POSITION_L + AX_BYTE_READ_POS))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START);
sendData(AX_START);
sendData(ID);
sendData(AX_POS_LENGTH);
sendData(AX_READ_DATA);
sendData(AX_PRESENT_POSITION_L);
sendData(AX_BYTE_READ_POS);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
Position_Long_Byte = -1;
Time_Counter = 0;
while((availableData() < 7) & (Time_Counter < TIME_OUT)){
Time_Counter++;
delayus(1000);
}
while (availableData() > 0){
Incoming_Byte = readData();
if ( (Incoming_Byte == 255) & (peekData() == 255) ){
readData(); // Start Bytes
readData(); // Ax-12 ID
readData(); // Length
if( (Error_Byte = readData()) != 0 ) // Error
return (Error_Byte*(-1));
Position_Low_Byte = readData(); // Position Bytes
Position_High_Byte = readData();
Position_Long_Byte = Position_High_Byte << 8;
Position_Long_Byte = Position_Long_Byte + Position_Low_Byte;
}
}
return (Position_Long_Byte); // Returns the read position
}
int DynamixelClass::readVoltage(unsigned char ID)
{
Checksum = (~(ID + AX_VOLT_LENGTH + AX_READ_DATA + AX_PRESENT_VOLTAGE + AX_BYTE_READ))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START);
sendData(AX_START);
sendData(ID);
sendData(AX_VOLT_LENGTH);
sendData(AX_READ_DATA);
sendData(AX_PRESENT_VOLTAGE);
sendData(AX_BYTE_READ);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
Voltage_Byte = -1;
Time_Counter = 0;
while((availableData() < 6) & (Time_Counter < TIME_OUT)){
Time_Counter++;
delayus(1000);
}
while (availableData() > 0){
Incoming_Byte = readData();
if ( (Incoming_Byte == 255) & (peekData() == 255) ){
readData(); // Start Bytes
readData(); // Ax-12 ID
readData(); // Length
if( (Error_Byte = readData()) != 0 ) // Error
return (Error_Byte*(-1));
Voltage_Byte = readData(); // Voltage
}
}
return (Voltage_Byte); // Returns the read Voltage
}
int DynamixelClass::setTempLimit(unsigned char ID, unsigned char Temperature)
{
Checksum = (~(ID + AX_TL_LENGTH +AX_WRITE_DATA+ AX_LIMIT_TEMPERATURE + Temperature))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START);
sendData(AX_START);
sendData(ID);
sendData(AX_TL_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_LIMIT_TEMPERATURE);
sendData(Temperature);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error());
}
int DynamixelClass::setVoltageLimit(unsigned char ID, unsigned char DVoltage, unsigned char UVoltage)
{
Checksum = (~(ID + AX_VL_LENGTH +AX_WRITE_DATA+ AX_DOWN_LIMIT_VOLTAGE + DVoltage + UVoltage))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START);
sendData(AX_START);
sendData(ID);
sendData(AX_VL_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_DOWN_LIMIT_VOLTAGE);
sendData(DVoltage);
sendData(UVoltage);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error());
}
int DynamixelClass::setAngleLimit(unsigned char ID, int CWLimit, int CCWLimit)
{
char CW_H,CW_L,CCW_H,CCW_L;
CW_H = CWLimit >> 8;
CW_L = CWLimit; // 16 bits - 2 x 8 bits variables
CCW_H = CCWLimit >> 8;
CCW_L = CCWLimit;
Checksum = (~(ID + AX_VL_LENGTH +AX_WRITE_DATA+ AX_CW_ANGLE_LIMIT_L + CW_H + CW_L + AX_CCW_ANGLE_LIMIT_L + CCW_H + CCW_L))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START);
sendData(AX_START);
sendData(ID);
sendData(AX_CCW_CW_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_CW_ANGLE_LIMIT_L);
sendData(CW_L);
sendData(CW_H);
sendData(AX_CCW_ANGLE_LIMIT_L);
sendData(CCW_L);
sendData(CCW_H);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error());
}
int DynamixelClass::setMaxTorque(unsigned char ID, int MaxTorque)
{
char MaxTorque_H,MaxTorque_L;
MaxTorque_H = MaxTorque >> 8; // 16 bits - 2 x 8 bits variables
MaxTorque_L = MaxTorque;
Checksum = (~(ID + AX_MT_LENGTH + AX_WRITE_DATA + AX_MAX_TORQUE_L + MaxTorque_L + MaxTorque_H))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_MT_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_MAX_TORQUE_L);
sendData(MaxTorque_L);
sendData(MaxTorque_H);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
int DynamixelClass::setSRL(unsigned char ID, unsigned char SRL)
{
Checksum = (~(ID + AX_SRL_LENGTH + AX_WRITE_DATA + AX_RETURN_LEVEL + SRL))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_SRL_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_RETURN_LEVEL);
sendData(SRL);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
int DynamixelClass::setRDT(unsigned char ID, unsigned char RDT)
{
Checksum = (~(ID + AX_RDT_LENGTH + AX_WRITE_DATA + AX_RETURN_DELAY_TIME + (RDT/2)))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_RDT_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_RETURN_DELAY_TIME);
sendData((RDT/2));
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
int DynamixelClass::setLEDAlarm(unsigned char ID, unsigned char LEDAlarm)
{
Checksum = (~(ID + AX_LEDALARM_LENGTH + AX_WRITE_DATA + AX_ALARM_LED + LEDAlarm))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_LEDALARM_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_ALARM_LED);
sendData(LEDAlarm);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
int DynamixelClass::setTorqueEnable(unsigned char ID, unsigned char torqueEnable)
{
Checksum = (~(ID + AX_TORQUE_LENGTH + AX_WRITE_DATA + AX_TORQUE_ENABLE + torqueEnable))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_TORQUE_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_TORQUE_ENABLE);
sendData(torqueEnable);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
int DynamixelClass::setShutdownAlarm(unsigned char ID, unsigned char SALARM)
{
Checksum = (~(ID + AX_SALARM_LENGTH + AX_ALARM_SHUTDOWN + AX_ALARM_LED + SALARM))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_SALARM_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_ALARM_SHUTDOWN);
sendData(SALARM);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
int DynamixelClass::setCMargin(unsigned char ID, unsigned char CWCMargin, unsigned char CCWCMargin)
{
Checksum = (~(ID + AX_CM_LENGTH +AX_WRITE_DATA+ AX_CW_COMPLIANCE_MARGIN + CWCMargin + AX_CCW_COMPLIANCE_MARGIN + CCWCMargin))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START);
sendData(AX_START);
sendData(ID);
sendData(AX_CM_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_CW_COMPLIANCE_MARGIN);
sendData(CWCMargin);
sendData(AX_CCW_COMPLIANCE_MARGIN);
sendData(CCWCMargin);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error());
}
int DynamixelClass::setCSlope(unsigned char ID, unsigned char CWCSlope, unsigned char CCWCSlope)
{
Checksum = (~(ID + AX_CS_LENGTH +AX_WRITE_DATA+ AX_CW_COMPLIANCE_SLOPE + CWCSlope + AX_CCW_COMPLIANCE_SLOPE + CCWCSlope))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START);
sendData(AX_START);
sendData(ID);
sendData(AX_CS_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_CW_COMPLIANCE_SLOPE);
sendData(CWCSlope);
sendData(AX_CCW_COMPLIANCE_SLOPE);
sendData(CCWCSlope);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error());
}
int DynamixelClass::setPunch(unsigned char ID, int Punch)
{
char Punch_H,Punch_L;
Punch_H = Punch >> 8; // 16 bits - 2 x 8 bits variables
Punch_L = Punch;
Checksum = (~(ID + AX_PUNCH_LENGTH + AX_WRITE_DATA + AX_PUNCH_L + Punch_L + Punch_H))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_PUNCH_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_PUNCH_L);
sendData(Punch_L);
sendData(Punch_H);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
int DynamixelClass::moving(unsigned char ID)
{
Checksum = (~(ID + AX_MOVING_LENGTH + AX_READ_DATA + AX_MOVING + AX_BYTE_READ))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START);
sendData(AX_START);
sendData(ID);
sendData(AX_MOVING_LENGTH);
sendData(AX_READ_DATA);
sendData(AX_MOVING);
sendData(AX_BYTE_READ);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
Moving_Byte = -1;
Time_Counter = 0;
while((availableData() < 6) & (Time_Counter < TIME_OUT)){
Time_Counter++;
delayus(1000);
}
while (availableData() > 0){
Incoming_Byte = readData();
if ( (Incoming_Byte == 255) & (peekData() == 255) ){
readData(); // Start Bytes
readData(); // Ax-12 ID
readData(); // Length
if( (Error_Byte = readData()) != 0 ) // Error
return (Error_Byte*(-1));
Moving_Byte = readData(); // Temperature
}
}
return (Moving_Byte); // Returns the read temperature
}
int DynamixelClass::lockRegister(unsigned char ID)
{
Checksum = (~(ID + AX_LR_LENGTH + AX_WRITE_DATA + AX_LOCK + LOCK))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START); // Send Instructions over Serial
sendData(AX_START);
sendData(ID);
sendData(AX_LR_LENGTH);
sendData(AX_WRITE_DATA);
sendData(AX_LOCK);
sendData(LOCK);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
return (read_error()); // Return the read error
}
int DynamixelClass::RWStatus(unsigned char ID)
{
Checksum = (~(ID + AX_RWS_LENGTH + AX_READ_DATA + AX_REGISTERED_INSTRUCTION + AX_BYTE_READ))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START);
sendData(AX_START);
sendData(ID);
sendData(AX_RWS_LENGTH);
sendData(AX_READ_DATA);
sendData(AX_REGISTERED_INSTRUCTION);
sendData(AX_BYTE_READ);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
RWS_Byte = -1;
Time_Counter = 0;
while((availableData() < 6) & (Time_Counter < TIME_OUT)){
Time_Counter++;
delayus(1000);
}
while (availableData() > 0){
Incoming_Byte = readData();
if ( (Incoming_Byte == 255) & (peekData() == 255) ){
readData(); // Start Bytes
readData(); // Ax-12 ID
readData(); // Length
if( (Error_Byte = readData()) != 0 ) // Error
return (Error_Byte*(-1));
RWS_Byte = readData(); // Temperature
}
}
return (RWS_Byte); // Returns the read temperature
}
int DynamixelClass::readSpeed(unsigned char ID)
{
Checksum = (~(ID + AX_POS_LENGTH + AX_READ_DATA + AX_PRESENT_SPEED_L + AX_BYTE_READ_POS))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START);
sendData(AX_START);
sendData(ID);
sendData(AX_POS_LENGTH);
sendData(AX_READ_DATA);
sendData(AX_PRESENT_SPEED_L);
sendData(AX_BYTE_READ_POS);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
Speed_Long_Byte = -1;
Time_Counter = 0;
while((availableData() < 7) & (Time_Counter < TIME_OUT)){
Time_Counter++;
delayus(1000);
}
while (availableData() > 0){
Incoming_Byte = readData();
if ( (Incoming_Byte == 255) & (peekData() == 255) ){
readData(); // Start Bytes
readData(); // Ax-12 ID
readData(); // Length
if( (Error_Byte = readData()) != 0 ) // Error
return (Error_Byte*(-1));
Speed_Low_Byte = readData(); // Position Bytes
Speed_High_Byte = readData();
Speed_Long_Byte = Speed_High_Byte << 8;
Speed_Long_Byte = Speed_Long_Byte + Speed_Low_Byte;
}
}
return (Speed_Long_Byte); // Returns the read position
}
int DynamixelClass::readLoad(unsigned char ID)
{
Checksum = (~(ID + AX_POS_LENGTH + AX_READ_DATA + AX_PRESENT_LOAD_L + AX_BYTE_READ_POS))&0xFF;
switchCom(Direction_Pin,Tx_MODE);
sendData(AX_START);
sendData(AX_START);
sendData(ID);
sendData(AX_POS_LENGTH);
sendData(AX_READ_DATA);
sendData(AX_PRESENT_LOAD_L);
sendData(AX_BYTE_READ_POS);
sendData(Checksum);
delayus(TX_DELAY_TIME);
switchCom(Direction_Pin,Rx_MODE);
Load_Long_Byte = -1;
Time_Counter = 0;
while((availableData() < 7) & (Time_Counter < TIME_OUT)){
Time_Counter++;
delayus(1000);
}
while (availableData() > 0){
Incoming_Byte = readData();
if ( (Incoming_Byte == 255) & (peekData() == 255) ){
readData(); // Start Bytes
readData(); // Ax-12 ID
readData(); // Length
if( (Error_Byte = readData()) != 0 ) // Error
return (Error_Byte*(-1));
Load_Low_Byte = readData(); // Position Bytes
Load_High_Byte = readData();
Load_Long_Byte = Load_High_Byte << 8;
Load_Long_Byte = Load_Long_Byte + Load_Low_Byte;
}
}
return (Load_Long_Byte); // Returns the read position
}
DynamixelClass Dynamixel; | [
"massimo.vespignani@gmail.com"
] | massimo.vespignani@gmail.com |
22fb64c4e1b0b0d3746ee89fc3f0e1d163682369 | aa095611e30d7e61c1bfdca88a22e0981d272641 | /Leetcode/Leetcode Daily/April/1st May21.cpp | adc3a9c67eaed4585c798e48778616f16aaeadc5 | [] | no_license | hmnt007/CPP-Pogramming | de6787728a5786d6548c6db8b6d3c68a57c0c7c4 | b691a5b88dd1f291fa191c2d84535d1e2d62e11a | refs/heads/master | 2023-08-24T04:54:17.166172 | 2021-10-03T06:22:06 | 2021-10-03T06:22:06 | 209,529,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,687 | cpp | class TrieNode {
public:
TrieNode* children[26] = {nullptr};
vector<int> vals;
};
class WordFilter {
private:
TrieNode *pTrie, *sTrie;
public:
WordFilter(vector<string>& words) {
pTrie = new TrieNode();
sTrie = new TrieNode();
for (int index = 0; index < words.size(); index++) {
string word = words[index];
insert(word, index, pTrie);
reverse(word.begin(), word.end());
insert(word, index, sTrie);
}
}
void insert(string word, int index, TrieNode* trie) {
for (auto c : word) {
int cval = c - 'a';
if (!trie->children[cval])
trie->children[cval] = new TrieNode();
trie = trie->children[cval];
trie->vals.push_back(index);
}
}
vector<int>* retrieve(string str, TrieNode* trie) {
for (auto c : str) {
trie = trie->children[c-'a'];
if (!trie) return nullptr;
}
return &trie->vals;
}
int f(string pre, string suf) {
vector<int>* pVals = retrieve(pre, pTrie);
reverse(suf.begin(), suf.end());
vector<int>* sVals = retrieve(suf, sTrie);
int svix = sVals->size() - 1, pvix = pVals->size() - 1;
while (~svix && ~pvix) {
int sVal = (*sVals)[svix], pVal = (*pVals)[pvix];
if (sVal == pVal) return sVal;
if (sVal > pVal) svix--;
else pvix--;
}
return -1;
}
};
/**
* Your WordFilter object will be instantiated and called as such:
* WordFilter* obj = new WordFilter(words);
* int param_1 = obj->f(prefix,suffix);
*/
| [
"noreply@github.com"
] | noreply@github.com |
5ff6b00a12096724fa14c1b1f5b31b8a76744672 | 1e4d33c09b59978a4b114a50c241882d55b38305 | /enigma/tests/test_plugboard.t.h | 40ddecf654568c91c86ef1cc8124c73384792c6e | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | gremmie/cpp-enigma | 25dceb48c05e46c4fd4bd4a4fff9a5d9dc95d8c1 | 389b0e8636875ee13fb31bc44587fcdf5be53741 | refs/heads/master | 2022-11-16T18:06:49.030362 | 2012-07-12T01:26:15 | 2012-07-12T01:26:15 | 276,726,968 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,042 | h | // Copyright (C) 2012 by Brian Neal.
// This file is part of Cpp-Enigma, the Enigma Machine simulation.
// Cpp-Enigma is released under the MIT License (see License.txt).
//
// test_plugboard.t.h - Unit tests for the plugboard class.
#include <algorithm>
#include <cxxtest/TestSuite.h>
#include "plugboard.h"
using namespace enigma;
class plugboard_test_suite : public CxxTest::TestSuite
{
public:
void test_bad_settings()
{
// too many
TS_ASSERT_THROWS(plugboard("AB CD EF GH IJ KL MN OP QR ST UV"), plugboard_error);
TS_ASSERT_THROWS(plugboard("18/26 17/4 21/6 3/16 19/14 22/7 8/1 12/25 5/9 10/15 2/20"),
plugboard_error);
// duplicate
TS_ASSERT_THROWS(plugboard("AB CD EF GH IJ KL MN OF QR ST"), plugboard_error);
TS_ASSERT_THROWS(plugboard("AB CD EF GH IJ KL MN FP QR ST"), plugboard_error);
TS_ASSERT_THROWS(plugboard("18/26 17/4 21/6 3/16 19/14 22/3 8/1 12/25"), plugboard_error);
// invalid
TS_ASSERT_THROWS(plugboard("A2 CD EF GH IJ KL MN FP QR ST"), plugboard_error);
TS_ASSERT_THROWS(plugboard("AB CD EF *H IJ KL MN FP QR ST"), plugboard_error);
TS_ASSERT_THROWS(plugboard("ABCD EF GH IJKLMN OP"), plugboard_error);
TS_ASSERT_THROWS(plugboard("A-D EF GH OP"), plugboard_error);
TS_ASSERT_THROWS(plugboard("A"), plugboard_error);
TS_ASSERT_THROWS(plugboard("9"), plugboard_error);
TS_ASSERT_THROWS(plugboard("1*/26 17/4 21/6 3/16 19/14 22/3 8/1 12/25"), plugboard_error);
TS_ASSERT_THROWS(plugboard("18/26 17/4 2A/6 3/16 19/14 22/3 8/1 12/25"), plugboard_error);
TS_ASSERT_THROWS(plugboard("100/2"), plugboard_error);
TS_ASSERT_THROWS(plugboard("T/C"), plugboard_error);
}
void test_valid_settings()
{
TS_ASSERT_THROWS_NOTHING(plugboard{});
TS_ASSERT_THROWS_NOTHING(plugboard{""});
TS_ASSERT_THROWS_NOTHING(plugboard(plugboard::pair_vector{}));
TS_ASSERT_THROWS_NOTHING(plugboard{"AB CD EF GH IJ KL MN OP QR ST"});
TS_ASSERT_THROWS_NOTHING(plugboard{"CD EF GH IJ KL MN OP QR ST"});
TS_ASSERT_THROWS_NOTHING(plugboard{"EF GH IJ KL MN OP QR ST"});
TS_ASSERT_THROWS_NOTHING(plugboard{" GH "});
TS_ASSERT_THROWS_NOTHING(plugboard{"18/26 17/4 21/6 3/16 19/14 22/7 8/1 12/25 5/9 10/15"});
TS_ASSERT_THROWS_NOTHING(plugboard{"18/26 17/4"});
TS_ASSERT_THROWS_NOTHING(plugboard{" 18/26 "});
}
void test_default_wiring()
{
plugboard p;
for (int i = 0; i < 26; ++i)
{
TS_ASSERT_EQUALS(i, p.signal(i));
}
}
void test_wiring()
{
std::vector<std::string> settings{"AB CD EF GH IJ KL MN OP QR ST",
"1/2 3/4 5/6 7/8 9/10 11/12 13/14 15/16 17/18 19/20"};
for (const auto& setting : settings)
{
plugboard p{setting};
for (int n = 0; n < 26; ++n)
{
if (n < 20)
{
if (n % 2 == 0)
{
TS_ASSERT_EQUALS(p.signal(n), n + 1);
}
else
{
TS_ASSERT_EQUALS(p.signal(n), n - 1);
}
}
else
{
TS_ASSERT_EQUALS(p.signal(n), n);
}
}
}
}
void test_wiring2()
{
std::string stecker{"AV BS CG DL FU HZ IN KM OW RX"};
plugboard p{stecker};
plugboard::pair_vector pairs{p.get_pairs()};
plugboard::pair_vector expected_pairs{
{0, 21}, {1, 18}, {2, 6}, {3, 11}, {5, 20},
{7, 25}, {8, 13}, {10, 12}, {14, 22}, {17, 23}
};
TS_ASSERT_EQUALS(expected_pairs, pairs);
std::map<int, int> wiring;
for (const auto& p : pairs)
{
wiring.insert(p);
wiring.insert(std::make_pair(p.second, p.first));
}
for (int n = 0; n < 26; ++n)
{
auto iter = wiring.find(n);
if (iter != wiring.end())
{
TS_ASSERT_EQUALS(p.signal(n), iter->second);
}
else
{
TS_ASSERT_EQUALS(p.signal(n), n);
}
}
}
void test_army_str()
{
std::string stecker{"AB CD EF GH IJ KL MN OP QR ST"};
plugboard p{stecker};
TS_ASSERT_EQUALS(stecker, p.army_str());
}
void test_navy_str()
{
std::string stecker{"1/2 3/4 5/6 7/8 9/10 11/12 13/14 15/16 17/18 19/20"};
plugboard p{stecker};
TS_ASSERT_EQUALS(stecker, p.navy_str());
}
void test_get_wiring()
{
plugboard pb;
auto w(pb.get_wiring());
for (int i = 0; i < 26; ++i)
{
TS_ASSERT_EQUALS(w[i], i);
}
pb.connect(0, 1);
pb.connect(8, 20);
pb.connect(24, 25);
for (int i = 0; i < 26; ++i)
{
w[i] = i;
}
std::swap(w[0], w[1]);
std::swap(w[8], w[20]);
std::swap(w[24], w[25]);
auto w1(pb.get_wiring());
for (int i = 0; i < 26; ++i)
{
TS_ASSERT_EQUALS(w[i], w1[i]);
}
}
void test_set_wiring()
{
alpha_int_array w;
for (int i = 0; i < 26; ++i)
{
w[i] = i;
}
std::swap(w[0], w[1]);
std::swap(w[8], w[20]);
std::swap(w[24], w[25]);
plugboard pb;
pb.set_wiring(w);
auto w2 = pb.get_wiring();
TS_ASSERT_EQUALS(w, w2);
}
void test_is_wired()
{
plugboard pb;
pb.connect(0, 25);
pb.connect(4, 18);
for (int i = 0; i < 26; ++i)
{
if (i == 0 || i == 25 || i == 4 || i == 18)
{
TS_ASSERT(pb.is_wired(i));
}
else
{
TS_ASSERT(!pb.is_wired(i));
}
}
}
void test_is_free()
{
plugboard pb;
pb.connect(0, 25);
pb.connect(4, 18);
for (int i = 0; i < 26; ++i)
{
if (i == 0 || i == 25 || i == 4 || i == 18)
{
TS_ASSERT(!pb.is_free(i));
}
else
{
TS_ASSERT(pb.is_free(i));
}
}
}
void test_disconnect()
{
plugboard pb;
pb.connect(0, 25);
pb.connect(4, 18);
pb.disconnect(0);
pb.disconnect(18);
for (int i = 0; i < 26; ++i)
{
TS_ASSERT(pb.is_free(i));
}
}
void test_disconnect2()
{
plugboard pb;
for (int i = 0; i < 26; ++i)
{
pb.disconnect(i);
}
for (int i = 0; i < 26; ++i)
{
TS_ASSERT(pb.is_free(i));
}
}
void test_connect()
{
plugboard pb;
pb.connect(2, 4);
pb.connect(17, 20);
for (int i = 0; i < 26; ++i)
{
if (i == 2 || i == 4 || i == 17 || i == 20)
{
TS_ASSERT(pb.is_wired(i));
}
else
{
TS_ASSERT(pb.is_free(i));
}
}
pb.connect(20, 25);
for (int i = 0; i < 26; ++i)
{
if (i == 2 || i == 4 || i == 25 || i == 20)
{
TS_ASSERT(pb.is_wired(i));
}
else
{
TS_ASSERT(pb.is_free(i));
}
}
}
void test_is_connected()
{
plugboard pb;
pb.connect(5, 7);
pb.connect(1, 20);
TS_ASSERT(pb.is_connected(5, 7));
TS_ASSERT(pb.is_connected(1, 20));
for (int i = 0; i < 26; ++i)
{
if (i == 7)
{
TS_ASSERT(pb.is_connected(5, i));
}
else
{
TS_ASSERT(!pb.is_connected(5, i));
}
if (i == 1)
{
TS_ASSERT(pb.is_connected(20, i));
}
else
{
TS_ASSERT(!pb.is_connected(20, i));
}
}
}
void test_unplug_all()
{
plugboard pb;
pb.connect(5, 7);
pb.connect(1, 20);
pb.connect(18, 24);
pb.unplug_all();
for (int i = 0; i < 26; ++i)
{
TS_ASSERT(pb.is_free(i));
}
pb.unplug_all();
for (int i = 0; i < 26; ++i)
{
TS_ASSERT(pb.is_free(i));
}
}
};
| [
"gremmie@users.noreply.github.com"
] | gremmie@users.noreply.github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.