blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bb52ac58e6a8d4ebb27359eaf46707edf16ea2aa | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/Reconstruction/Jet/JetSubStructureMomentTools/src/Validator.cxx | bb2a8fad6620731d7166271e838d7218bc008d3a | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,550 | cxx | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#include <iostream>
#include <math.h>
#include <float.h>
#include "JetSubStructureMomentTools/Validator.h"
#include <TFile.h>
#include <TH1.h>
#include "GaudiKernel/ITHistSvc.h"
using namespace std;
Validator::Validator(std::string name) :
AsgTool(name)
{
declareProperty("InputContainer", m_InputContainer = "");
declareProperty("FloatMoments", m_FloatMoments);
}
int Validator::execute() const
{
// Load histogram service
StatusCode sc;
ITHistSvc *histSvc;
sc = service("THistSvc", histSvc);
if(sc.isFailure()) {
ATH_MSG_ERROR("Unable to access the THistSvc");
return 1;
}
// Get leading jet
const xAOD::JetContainer* jets = 0;
if(evtStore()->contains<xAOD::JetContainer>(m_InputContainer) == false) {
ATH_MSG_ERROR("Unable to retrieve jets from collection: " << m_InputContainer);
return 1;
}
jets = evtStore()->retrieve<const xAOD::JetContainer>(m_InputContainer);
if(jets->size() == 0) return 0;
const xAOD::Jet *jet = jets->at(0); // This assumes the container is sorted
// Loop over float moments
for(unsigned int i=0; i<m_FloatMoments.size(); i++) {
TH1 *outputHist;
if(histSvc->exists("/JetSubstructureMoments/" + m_FloatMoments[i])) {
sc = histSvc->getHist("/JetSubstructureMoments/" + m_FloatMoments[i], outputHist);
if(sc.isFailure()) {
ATH_MSG_ERROR("Unable to retrieve histogram");
return 1;
}
}
else {
unsigned int nbins = 100;
float xlow = 0, xhigh = 1.0;
if(m_FloatMoments[i].find("Split") != string::npos ||
m_FloatMoments[i] == "pt") {
nbins = 1000;
xhigh = 2000000;
}
else if(m_FloatMoments[i].find("Pull") != string::npos) {
if(m_FloatMoments[i].find("PullMag") != string::npos) {
xhigh = 0.1;
nbins = 100;
}
else {
xlow = -10;
xhigh = 10;
nbins = 200;
}
}
else if(m_FloatMoments[i].find("ShowerDeconstruction") != string::npos) {
xlow = -10;
xhigh = 10;
nbins = 100;
}
outputHist = new TH1F(m_FloatMoments[i].c_str(), "", nbins, xlow, xhigh);
sc = histSvc->regHist("/JetSubstructureMoments/" + m_FloatMoments[i], outputHist);
if(sc.isFailure()) {
ATH_MSG_ERROR("Unable to register histogram");
return 1;
}
}
if(m_FloatMoments[i] == "pt") {
outputHist->Fill(jet->pt());
}
else {
outputHist->Fill(jet->getAttribute<float>(m_FloatMoments[i].c_str()));
}
}
return 0;
}
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
7cc65fc949162aa2d4c4fa4243e12d1e58a1eeab | 35570789ac21d1d30d36e0363c2565b0dcf6f2d4 | /1-text/print.cpp | f73d41c16910cc88011d43276aa4d5bc833ea6c2 | [] | no_license | NathanMcMillan54/basic-cpp | 3ac80ce37082bbbdd7a415c255a6789162f31a7b | a578f98f2ae0a6735c3084e35187212849768638 | refs/heads/main | 2022-12-30T10:23:22.624886 | 2020-10-15T19:39:40 | 2020-10-15T19:39:40 | 303,002,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 104 | cpp | #include <iostream>
int main() {
std::cout << "C++ print statement!" << std::endl;
return 0;
}
| [
"nathanmcmillan54@gmail.com"
] | nathanmcmillan54@gmail.com |
9af0808fee9bd82e5e699eb538dc39c3ae8445c8 | 72a3dac9a4ccd429c00b9de7a503b596a80efde0 | /Bellman-Ford.cpp | 547eca298da8d38caf4d101efec26cfc63385fca | [] | no_license | hemantmangwani/ALGORITHM-AND-DATA-STRUCTURES | f1391661745c69d79a21df4278ff056e120efa25 | 9347881f53b2732295c8b01a2caf102966cd281c | refs/heads/master | 2021-01-01T17:12:34.500776 | 2018-03-25T19:28:10 | 2018-03-25T19:28:10 | 98,023,597 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,102 | cpp | #include <bits/stdc++.h>
#define ll long long
#define T ll t; cin>>t; while(t--)
using namespace std;
#define speed ios_base::sync_with_stdio(0)
#define endl "\n"
#define MAX 1000000001
int main()
{
vector <int> v [2000 + 10];
int dis [1000 + 10];
ll n,e;
cin>>n>>e;
for(int i = 0; i < e + 2; i++){
v[i].clear();
dis[i] = MAX;
}
for(int i = 0; i < e; i++){
ll from , next , weight;
scanf("%d%d%d", &from , &next , &weight);
v[i].push_back(from);
v[i].push_back(next);
v[i].push_back(weight);
}
// for(int i = 0; i < e; i++){
// cout<<"i= "<<i<<endl;
// for(int j = 0; j < 3; j++){
// cout<< v[i][j]<<" ";
// }
// cout<<endl;
// }
dis[1] = 0;
for(int i = 0; i <= n - 1; i++){
int j = 0;
while(v[j].size() != 0){
if(dis[ v[j][0] ] + v[j][2] < dis[ v[j][1] ] ){
dis[ v[j][1] ] = dis[ v[j][0] ] + v[j][2];
}
j++;
}
}
for(int i = 1; i <= n ; i++)
cout<<dis[i]<<" ";
return 0;
}
| [
"hemantmangwani99@gmail.com"
] | hemantmangwani99@gmail.com |
0f3ef8937623bf9277aecbfaf7d74b045db40c3b | 536656cd89e4fa3a92b5dcab28657d60d1d244bd | /ash/app_list/views/apps_container_view.cc | 87db1f69335e12e01135f11ebd91650d0aad478d | [
"BSD-3-Clause"
] | permissive | ECS-251-W2020/chromium | 79caebf50443f297557d9510620bf8d44a68399a | ac814e85cb870a6b569e184c7a60a70ff3cb19f9 | refs/heads/master | 2022-08-19T17:42:46.887573 | 2020-03-18T06:08:44 | 2020-03-18T06:08:44 | 248,141,336 | 7 | 8 | BSD-3-Clause | 2022-07-06T20:32:48 | 2020-03-18T04:52:18 | null | UTF-8 | C++ | false | false | 25,849 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/app_list/views/apps_container_view.h"
#include <algorithm>
#include <vector>
#include "ash/app_list/views/app_list_folder_view.h"
#include "ash/app_list/views/app_list_item_view.h"
#include "ash/app_list/views/app_list_main_view.h"
#include "ash/app_list/views/app_list_view.h"
#include "ash/app_list/views/apps_grid_view.h"
#include "ash/app_list/views/contents_view.h"
#include "ash/app_list/views/folder_background_view.h"
#include "ash/app_list/views/horizontal_page_container.h"
#include "ash/app_list/views/page_switcher.h"
#include "ash/app_list/views/search_box_view.h"
#include "ash/app_list/views/suggestion_chip_container_view.h"
#include "ash/public/cpp/app_list/app_list_config.h"
#include "ash/public/cpp/app_list/app_list_features.h"
#include "ash/public/cpp/app_list/app_list_switches.h"
#include "base/command_line.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/chromeos/search_box/search_box_constants.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animation_element.h"
#include "ui/compositor/layer_animator.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/events/event.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/textfield/textfield.h"
namespace ash {
namespace {
// The apps container height at which suggestion chips container margin from the
// search box should be reduced to preserve available vertical space.
constexpr int kDenseSuggestionChipsTopMarginThreshold = 600;
// Suggestion chip container top margin (from the search box view) when apps
// container height is below |kDenseSuggestionChipsTopMarginThreshold|.
constexpr int kDenseSuggestionChipContainerTopMargin = 8;
// The range of app list transition progress in which the suggestion chips'
// opacity changes from 0 to 1.
constexpr float kSuggestionChipOpacityStartProgress = 0.66;
constexpr float kSuggestionChipOpacityEndProgress = 1;
// The app list transition progress value for fullscreen state.
constexpr float kAppListFullscreenProgressValue = 2.0;
} // namespace
AppsContainerView::AppsContainerView(ContentsView* contents_view,
AppListModel* model)
: contents_view_(contents_view) {
SetPaintToLayer(ui::LAYER_NOT_DRAWN);
suggestion_chip_container_view_ = AddChildView(
std::make_unique<SuggestionChipContainerView>(contents_view));
apps_grid_view_ =
AddChildView(std::make_unique<AppsGridView>(contents_view_, nullptr));
// Page switcher should be initialized after AppsGridView.
auto page_switcher = std::make_unique<PageSwitcher>(
apps_grid_view_->pagination_model(), true /* vertical */,
contents_view_->app_list_view()->is_tablet_mode());
page_switcher_ = AddChildView(std::move(page_switcher));
auto app_list_folder_view =
std::make_unique<AppListFolderView>(this, model, contents_view_);
// The folder view is initially hidden.
app_list_folder_view->SetVisible(false);
auto folder_background_view =
std::make_unique<FolderBackgroundView>(app_list_folder_view.get());
folder_background_view_ = AddChildView(std::move(folder_background_view));
app_list_folder_view_ = AddChildView(std::move(app_list_folder_view));
apps_grid_view_->SetModel(model);
apps_grid_view_->SetItemList(model->top_level_item_list());
SetShowState(SHOW_APPS, false);
}
AppsContainerView::~AppsContainerView() {
// Make sure |page_switcher_| is deleted before |apps_grid_view_| because
// |page_switcher_| uses the PaginationModel owned by |apps_grid_view_|.
delete page_switcher_;
}
void AppsContainerView::ShowActiveFolder(AppListFolderItem* folder_item) {
// Prevent new animations from starting if there are currently animations
// pending. This fixes crbug.com/357099.
if (app_list_folder_view_->IsAnimationRunning())
return;
app_list_folder_view_->SetAppListFolderItem(folder_item);
SetShowState(SHOW_ACTIVE_FOLDER, false);
// If there is no selected view in the root grid when a folder is opened,
// silently focus the first item in the folder to avoid showing the selection
// highlight or announcing to A11y, but still ensuring the arrow keys navigate
// from the first item.
AppListItemView* first_item_view_in_folder_grid =
app_list_folder_view_->items_grid_view()->view_model()->view_at(0);
if (!apps_grid_view()->has_selected_view()) {
first_item_view_in_folder_grid->SilentlyRequestFocus();
} else {
first_item_view_in_folder_grid->RequestFocus();
}
// Disable all the items behind the folder so that they will not be reached
// during focus traversal.
DisableFocusForShowingActiveFolder(true);
}
void AppsContainerView::ShowApps(AppListFolderItem* folder_item) {
if (app_list_folder_view_->IsAnimationRunning())
return;
SetShowState(SHOW_APPS, folder_item ? true : false);
DisableFocusForShowingActiveFolder(false);
}
void AppsContainerView::ResetForShowApps() {
UpdateSuggestionChips();
SetShowState(SHOW_APPS, false);
DisableFocusForShowingActiveFolder(false);
}
void AppsContainerView::SetDragAndDropHostOfCurrentAppList(
ApplicationDragAndDropHost* drag_and_drop_host) {
apps_grid_view()->SetDragAndDropHostOfCurrentAppList(drag_and_drop_host);
app_list_folder_view()->items_grid_view()->SetDragAndDropHostOfCurrentAppList(
drag_and_drop_host);
}
void AppsContainerView::ReparentFolderItemTransit(
AppListFolderItem* folder_item) {
if (app_list_folder_view_->IsAnimationRunning())
return;
SetShowState(SHOW_ITEM_REPARENT, false);
DisableFocusForShowingActiveFolder(false);
}
bool AppsContainerView::IsInFolderView() const {
return show_state_ == SHOW_ACTIVE_FOLDER;
}
void AppsContainerView::ReparentDragEnded() {
DCHECK_EQ(SHOW_ITEM_REPARENT, show_state_);
show_state_ = AppsContainerView::SHOW_APPS;
}
void AppsContainerView::UpdateControlVisibility(AppListViewState app_list_state,
bool is_in_drag) {
if (app_list_state == AppListViewState::kClosed)
return;
set_can_process_events_within_subtree(
app_list_state == AppListViewState::kFullscreenAllApps ||
app_list_state == AppListViewState::kPeeking);
apps_grid_view_->UpdateControlVisibility(app_list_state, is_in_drag);
page_switcher_->SetVisible(
is_in_drag || app_list_state == AppListViewState::kFullscreenAllApps ||
(app_list_features::IsScalableAppListEnabled() &&
app_list_state == AppListViewState::kFullscreenSearch));
// Ignore button press during dragging to avoid app list item views' opacity
// being set to wrong value.
page_switcher_->set_ignore_button_press(is_in_drag);
suggestion_chip_container_view_->SetVisible(
app_list_state == AppListViewState::kFullscreenAllApps ||
app_list_state == AppListViewState::kPeeking || is_in_drag);
}
void AppsContainerView::AnimateOpacity(float current_progress,
AppListViewState target_view_state,
const OpacityAnimator& animator) {
const bool target_suggestion_chip_visibility =
target_view_state == AppListViewState::kFullscreenAllApps ||
target_view_state == AppListViewState::kPeeking;
animator.Run(suggestion_chip_container_view_,
target_suggestion_chip_visibility);
if (!apps_grid_view_->layer()->GetAnimator()->IsAnimatingProperty(
ui::LayerAnimationElement::OPACITY)) {
apps_grid_view_->UpdateOpacity(true /*restore_opacity*/);
apps_grid_view_->layer()->SetOpacity(current_progress > 1.0f ? 1.0f : 0.0f);
}
const bool target_grid_visibility =
target_view_state == AppListViewState::kFullscreenAllApps ||
target_view_state == AppListViewState::kFullscreenSearch;
animator.Run(apps_grid_view_, target_grid_visibility);
animator.Run(page_switcher_, target_grid_visibility);
}
void AppsContainerView::AnimateYPosition(AppListViewState target_view_state,
const TransformAnimator& animator) {
const int target_suggestion_chip_y = GetExpectedSuggestionChipY(
AppListView::GetTransitionProgressForState(target_view_state));
suggestion_chip_container_view_->SetY(target_suggestion_chip_y);
animator.Run(suggestion_chip_container_view_);
apps_grid_view_->SetY(suggestion_chip_container_view_->y() +
chip_grid_y_distance_);
animator.Run(apps_grid_view_);
page_switcher_->SetY(suggestion_chip_container_view_->y() +
chip_grid_y_distance_);
animator.Run(page_switcher_);
}
void AppsContainerView::UpdateYPositionAndOpacity(float progress,
bool restore_opacity) {
apps_grid_view_->UpdateOpacity(restore_opacity);
// Updates the opacity of page switcher buttons. The same rule as all apps in
// AppsGridView.
AppListView* app_list_view = contents_view_->app_list_view();
int screen_bottom = app_list_view->GetScreenBottom();
gfx::Rect switcher_bounds = page_switcher_->GetBoundsInScreen();
float centerline_above_work_area =
std::max<float>(screen_bottom - switcher_bounds.CenterPoint().y(), 0.f);
const float start_px = AppListConfig::instance().all_apps_opacity_start_px();
float opacity = std::min(
std::max(
(centerline_above_work_area - start_px) /
(AppListConfig::instance().all_apps_opacity_end_px() - start_px),
0.f),
1.0f);
page_switcher_->layer()->SetOpacity(restore_opacity ? 1.0f : opacity);
// Changes the opacity of suggestion chips between 0 and 1 when app list
// transition progress changes between |kSuggestionChipOpacityStartProgress|
// and |kSuggestionChipOpacityEndProgress|.
float chips_opacity =
std::min(std::max((progress - kSuggestionChipOpacityStartProgress) /
(kSuggestionChipOpacityEndProgress -
kSuggestionChipOpacityStartProgress),
0.f),
1.0f);
suggestion_chip_container_view_->layer()->SetOpacity(
restore_opacity ? 1.0 : chips_opacity);
suggestion_chip_container_view_->SetY(GetExpectedSuggestionChipY(progress));
apps_grid_view_->SetY(suggestion_chip_container_view_->y() +
chip_grid_y_distance_);
page_switcher_->SetY(suggestion_chip_container_view_->y() +
chip_grid_y_distance_);
// If app list is in drag, reset transforms that might started animating in
// AnimateYPosition().
if (app_list_view->is_in_drag()) {
suggestion_chip_container_view_->layer()->SetTransform(gfx::Transform());
apps_grid_view_->layer()->SetTransform(gfx::Transform());
page_switcher_->layer()->SetTransform(gfx::Transform());
}
}
void AppsContainerView::OnTabletModeChanged(bool started) {
suggestion_chip_container_view_->OnTabletModeChanged(started);
apps_grid_view_->OnTabletModeChanged(started);
app_list_folder_view_->OnTabletModeChanged(started);
page_switcher_->set_is_tablet_mode(started);
}
void AppsContainerView::Layout() {
gfx::Rect rect(GetContentsBounds());
if (rect.IsEmpty())
return;
// Layout suggestion chips.
gfx::Rect chip_container_rect = rect;
chip_container_rect.set_y(GetExpectedSuggestionChipY(
contents_view_->app_list_view()->GetAppListTransitionProgress(
AppListView::kProgressFlagNone)));
chip_container_rect.set_height(
GetAppListConfig().suggestion_chip_container_height());
if (app_list_features::IsScalableAppListEnabled()) {
chip_container_rect.Inset(GetAppListConfig().GetIdealHorizontalMargin(rect),
0);
}
suggestion_chip_container_view_->SetBoundsRect(chip_container_rect);
// Leave the same available bounds for the apps grid view in both
// fullscreen and peeking state to avoid resizing the view during
// animation and dragging, which is an expensive operation.
rect.set_y(chip_container_rect.bottom());
rect.set_height(rect.height() -
GetExpectedSuggestionChipY(kAppListFullscreenProgressValue) -
chip_container_rect.height());
const int page_switcher_width = page_switcher_->GetPreferredSize().width();
// With scalable app list feature enabled, the margins are calculated from
// the edge of the apps container, instead of container bounds inset by
// page switcher area.
if (!app_list_features::IsScalableAppListEnabled()) {
rect.Inset(GetAppListConfig().GetMinGridHorizontalPadding(), 0);
}
const GridLayout grid_layout = CalculateGridLayout();
apps_grid_view_->SetLayout(grid_layout.columns, grid_layout.rows);
// Layout apps grid.
gfx::Rect grid_rect = rect;
if (app_list_features::IsScalableAppListEnabled()) {
const gfx::Insets grid_insets = apps_grid_view_->GetInsets();
const gfx::Insets margins = CalculateMarginsForAvailableBounds(
GetContentsBounds(),
contents_view_->GetSearchBoxSize(AppListState::kStateApps),
true /*for_full_container_bounds*/);
grid_rect.Inset(
margins.left(),
GetAppListConfig().grid_fadeout_zone_height() - grid_insets.top(),
margins.right(), margins.bottom());
// The grid rect insets are added to calculated margins. Given that the
// grid bounds rect should include insets, they have to be removed from
// added margins.
grid_rect.Inset(-grid_insets.left(), 0, -grid_insets.right(),
-grid_insets.bottom());
} else {
grid_rect.Inset(CalculateMarginsForAvailableBounds(
rect, gfx::Size(), false /*for_full_container_bounds*/));
// The grid rect insets are added to calculated margins. Given that the
// grid bounds rect should include insets, they have to be removed from
// the added margins.
grid_rect.Inset(-apps_grid_view_->GetInsets());
}
apps_grid_view_->SetBoundsRect(grid_rect);
// Record the distance of y position between suggestion chip container
// and apps grid view to avoid duplicate calculation of apps grid view's
// y position during dragging.
chip_grid_y_distance_ =
apps_grid_view_->y() - suggestion_chip_container_view_->y();
// Layout page switcher.
page_switcher_->SetBoundsRect(gfx::Rect(
grid_rect.right() + GetAppListConfig().grid_to_page_switcher_margin(),
grid_rect.y(), page_switcher_width, grid_rect.height()));
switch (show_state_) {
case SHOW_APPS:
break;
case SHOW_ACTIVE_FOLDER: {
folder_background_view_->SetBoundsRect(rect);
app_list_folder_view_->SetBoundsRect(
app_list_folder_view_->preferred_bounds());
break;
}
case SHOW_ITEM_REPARENT:
break;
default:
NOTREACHED();
}
}
bool AppsContainerView::OnKeyPressed(const ui::KeyEvent& event) {
if (show_state_ == SHOW_APPS)
return apps_grid_view_->OnKeyPressed(event);
else
return app_list_folder_view_->OnKeyPressed(event);
}
const char* AppsContainerView::GetClassName() const {
return "AppsContainerView";
}
void AppsContainerView::OnGestureEvent(ui::GestureEvent* event) {
// Ignore tap/long-press, allow those to pass to the ancestor view.
if (event->type() == ui::ET_GESTURE_TAP ||
event->type() == ui::ET_GESTURE_LONG_PRESS) {
return;
}
// Will forward events to |apps_grid_view_| if they occur in the same y-region
if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN &&
event->location().y() <= apps_grid_view_->bounds().y()) {
return;
}
// If a folder is currently opening or closing, we should ignore the event.
// This is here until the animation for pagination while closing folders is
// fixed: https://crbug.com/875133
if (app_list_folder_view_->IsAnimationRunning()) {
event->SetHandled();
return;
}
// Temporary event for use by |apps_grid_view_|
ui::GestureEvent grid_event(*event);
ConvertEventToTarget(apps_grid_view_, &grid_event);
apps_grid_view_->OnGestureEvent(&grid_event);
// If the temporary event was handled, we don't want to handle it again.
if (grid_event.handled())
event->SetHandled();
}
void AppsContainerView::OnWillBeHidden() {
if (show_state_ == SHOW_APPS || show_state_ == SHOW_ITEM_REPARENT)
apps_grid_view_->EndDrag(true);
else if (show_state_ == SHOW_ACTIVE_FOLDER)
app_list_folder_view_->CloseFolderPage();
}
views::View* AppsContainerView::GetFirstFocusableView() {
if (IsInFolderView()) {
// The pagination inside a folder is set horizontally, so focus should be
// set on the first item view in the selected page when it is moved down
// from the search box.
return app_list_folder_view_->items_grid_view()
->GetCurrentPageFirstItemViewInFolder();
}
return GetFocusManager()->GetNextFocusableView(
this, GetWidget(), false /* reverse */, false /* dont_loop */);
}
gfx::Rect AppsContainerView::GetPageBoundsForState(AppListState state) const {
return contents_view_->GetContentsBounds();
}
const gfx::Insets& AppsContainerView::CalculateMarginsForAvailableBounds(
const gfx::Rect& available_bounds,
const gfx::Size& search_box_size,
bool for_full_container_bounds) {
DCHECK_EQ(for_full_container_bounds,
app_list_features::IsScalableAppListEnabled());
if (cached_container_margins_.bounds_size == available_bounds.size() &&
cached_container_margins_.search_box_size == search_box_size) {
return cached_container_margins_.margins;
}
const GridLayout grid_layout = CalculateGridLayout();
const gfx::Size min_grid_size = apps_grid_view()->GetMinimumTileGridSize(
grid_layout.columns, grid_layout.rows);
const gfx::Size max_grid_size = apps_grid_view()->GetMaximumTileGridSize(
grid_layout.columns, grid_layout.rows);
int available_height = available_bounds.height();
// If calculating the bounds for the full apps container (rather than apps
// grid only), add search box, and suggestion chips container height (with
// its margins to search box and apps grid) to non apps grid size.
// NOTE: Not removing bottom apps grid inset (or top inset when
// |for_full_container_bounds| is false) because they are included into the
// total margin values.
if (for_full_container_bounds) {
available_height -=
search_box_size.height() +
GetAppListConfig().grid_fadeout_zone_height() +
GetAppListConfig().suggestion_chip_container_height() +
GetAppListConfig().suggestion_chip_container_top_margin();
}
// Calculates margin value to ensure the apps grid size is within required
// bounds.
// |ideal_margin|: The value the margin would have with no restrictions on
// grid size.
// |available_size|: The available size for apps grid in the dimension where
// margin is applied.
// |min_size|: The min allowed size for apps grid in the dimension where
// margin is applied.
// |max_size|: The max allowed size for apps grid in the dimension where
// margin is applied.
const auto calculate_margin = [](int ideal_margin, int available_size,
int min_size, int max_size) -> int {
const int ideal_size = available_size - 2 * ideal_margin;
if (ideal_size < min_size)
return ideal_margin - (min_size - ideal_size + 1) / 2;
if (ideal_size > max_size)
return ideal_margin + (ideal_size - max_size) / 2;
return ideal_margin;
};
const int ideal_vertical_margin =
GetAppListConfig().GetIdealVerticalMargin(available_bounds);
const int vertical_margin =
calculate_margin(ideal_vertical_margin, available_height,
min_grid_size.height(), max_grid_size.height());
const int ideal_horizontal_margin =
GetAppListConfig().GetIdealHorizontalMargin(available_bounds);
const int horizontal_margin =
calculate_margin(ideal_horizontal_margin, available_bounds.width(),
min_grid_size.width(), max_grid_size.width());
const int min_horizontal_margin =
app_list_features::IsScalableAppListEnabled()
? GetAppListConfig().GetMinGridHorizontalPadding()
: 0;
cached_container_margins_.margins = gfx::Insets(
std::max(vertical_margin, GetAppListConfig().grid_fadeout_zone_height()),
std::max(horizontal_margin, min_horizontal_margin),
std::max(vertical_margin, GetAppListConfig().grid_fadeout_zone_height()),
std::max(horizontal_margin, min_horizontal_margin));
cached_container_margins_.bounds_size = available_bounds.size();
cached_container_margins_.search_box_size = search_box_size;
return cached_container_margins_.margins;
}
void AppsContainerView::OnAppListConfigUpdated() {
// Invalidate the cached container margins - app list config change generally
// changes preferred apps grid margins, which can influence the container
// margins.
cached_container_margins_ = CachedContainerMargins();
apps_grid_view()->OnAppListConfigUpdated();
app_list_folder_view()->items_grid_view()->OnAppListConfigUpdated();
}
void AppsContainerView::UpdateSuggestionChips() {
suggestion_chip_container_view_->SetResults(
contents_view_->GetAppListMainView()
->view_delegate()
->GetSearchModel()
->results());
}
base::ScopedClosureRunner AppsContainerView::DisableSuggestionChipsBlur() {
++suggestion_chips_blur_disabler_count_;
if (suggestion_chips_blur_disabler_count_ == 1)
suggestion_chip_container_view_->SetBlurDisabled(true);
return base::ScopedClosureRunner(
base::BindOnce(&AppsContainerView::OnSuggestionChipsBlurDisablerReleased,
weak_ptr_factory_.GetWeakPtr()));
}
const AppListConfig& AppsContainerView::GetAppListConfig() const {
return contents_view_->app_list_view()->GetAppListConfig();
}
void AppsContainerView::SetShowState(ShowState show_state,
bool show_apps_with_animation) {
if (show_state_ == show_state)
return;
show_state_ = show_state;
// Layout before showing animation because the animation's target bounds are
// calculated based on the layout.
Layout();
switch (show_state_) {
case SHOW_APPS:
page_switcher_->set_can_process_events_within_subtree(true);
folder_background_view_->SetVisible(false);
apps_grid_view_->ResetForShowApps();
app_list_folder_view_->ResetItemsGridForClose();
if (show_apps_with_animation)
app_list_folder_view_->ScheduleShowHideAnimation(false, false);
else
app_list_folder_view_->HideViewImmediately();
break;
case SHOW_ACTIVE_FOLDER:
page_switcher_->set_can_process_events_within_subtree(false);
folder_background_view_->SetVisible(true);
app_list_folder_view_->ScheduleShowHideAnimation(true, false);
break;
case SHOW_ITEM_REPARENT:
page_switcher_->set_can_process_events_within_subtree(true);
folder_background_view_->SetVisible(false);
app_list_folder_view_->ScheduleShowHideAnimation(false, true);
break;
default:
NOTREACHED();
}
}
void AppsContainerView::DisableFocusForShowingActiveFolder(bool disabled) {
suggestion_chip_container_view_->DisableFocusForShowingActiveFolder(disabled);
apps_grid_view_->DisableFocusForShowingActiveFolder(disabled);
// Ignore the page switcher in accessibility tree so that buttons inside it
// will not be accessed by ChromeVox.
page_switcher_->GetViewAccessibility().OverrideIsIgnored(disabled);
page_switcher_->GetViewAccessibility().NotifyAccessibilityEvent(
ax::mojom::Event::kTreeChanged);
}
int AppsContainerView::GetSuggestionChipContainerTopMargin(
float progress) const {
// For small screen sizes in fullscreen state, reduce the margin between the
// search box and suggestion chips to reclaim as much of the vertical space as
// possible.
if (GetContentsBounds().height() < kDenseSuggestionChipsTopMarginThreshold &&
!app_list_features::IsScalableAppListEnabled() && progress > 1.0) {
return gfx::Tween::IntValueBetween(
progress - 1, GetAppListConfig().suggestion_chip_container_top_margin(),
kDenseSuggestionChipContainerTopMargin);
}
return GetAppListConfig().suggestion_chip_container_top_margin();
}
int AppsContainerView::GetExpectedSuggestionChipY(float progress) {
const gfx::Rect search_box_bounds =
contents_view_->GetSearchBoxExpectedBoundsForProgress(
AppListState::kStateApps, progress);
return search_box_bounds.bottom() +
GetSuggestionChipContainerTopMargin(progress);
}
AppsContainerView::GridLayout AppsContainerView::CalculateGridLayout() const {
// Adapt columns and rows based on the work area size.
const gfx::Size size =
display::Screen::GetScreen()
->GetDisplayNearestView(GetWidget()->GetNativeView())
.work_area()
.size();
GridLayout result;
const AppListConfig& config = GetAppListConfig();
// Switch columns and rows for portrait mode.
if (size.width() < size.height()) {
result.columns = config.preferred_rows();
result.rows = config.preferred_cols();
} else {
result.columns = config.preferred_cols();
result.rows = config.preferred_rows();
}
return result;
}
void AppsContainerView::OnSuggestionChipsBlurDisablerReleased() {
DCHECK_GT(suggestion_chips_blur_disabler_count_, 0u);
--suggestion_chips_blur_disabler_count_;
if (suggestion_chips_blur_disabler_count_ == 0)
suggestion_chip_container_view_->SetBlurDisabled(false);
}
} // namespace ash
| [
"pcding@ucdavis.edu"
] | pcding@ucdavis.edu |
28aa855ba94d75ffaeb6de8dbbb0401e7a0c9a91 | a54fe9cae6998342e99983d5bab0e20c445ae88e | /src/GroupBox.cpp | 2876c834938cea2da98b3469aad80aaa1dcdde17 | [] | no_license | lordio/StreamControlPanel | f286e2b40221ed160e93249b08760b0d6fab664f | 293785709ee1752efef314ec9549e5cdcd35c557 | refs/heads/master | 2021-01-01T15:45:14.015897 | 2015-01-28T20:52:28 | 2015-01-28T20:52:28 | 29,987,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 217 | cpp | #include "GroupBox.hpp"
GroupBox::GroupBox(BaseWindow & parent, tstring label, RECT rect, HFONT font) :
BaseWindow{ WC_BUTTON, label, BS_GROUPBOX | WS_CHILD, NULL, rect, &parent, font }
{
}
GroupBox::~GroupBox()
{
} | [
"lordio0190@gmail.com"
] | lordio0190@gmail.com |
466e498269ca39b7112cadea787575bdc8306a86 | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/git/new_hunk_7466.cpp | 7749c0176770400d9ad3c431b296ab550fdec453 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 184 | cpp | {
struct commit *commit;
if (prepare_revision_walk(rev))
die("revision walk setup failed");
while ((commit = get_revision(rev)) != NULL) {
const char *author = NULL, *buffer;
| [
"993273596@qq.com"
] | 993273596@qq.com |
222c63690b9b5ea2178d2e6d446f8d85af25561f | eb9783088c90b7a34e84da748ca5056070f4788c | /tests/themispp/secure_comparator_test.hpp | 457f3f55f5fc2dba2e6fe800848557318a4dee78 | [
"Apache-2.0"
] | permissive | b264/themis | 0a385f1ac2df00aa8b1b6ed34a7f41931eb1d097 | 77d5aceca4f580482f50185799d96884a5fddaa8 | refs/heads/master | 2021-01-11T00:14:40.389338 | 2016-10-10T11:36:34 | 2016-10-10T11:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,238 | hpp | /*
* Copyright (c) 2015 Cossack Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef THEMISPP_SECURE_COMPARATOR_TEST_HPP_
#define THEMISPP_SECURE_COMPARATOR_TEST_HPP_
#include <common/sput.h>
#include <string.h>
#ifdef SECURE_COMPARATOR_ENABLED
#include <themispp/secure_comparator.hpp>
#define STR_2_VEC(x) std::vector<uint8_t>(x.c_str(), x.c_str()+x.length())
namespace themispp{
namespace secure_session_test{
void secure_comparator_test(){
std::string shared_secret_a("shared_secret");
std::string shared_secret_b("shared_secret");
themispp::secure_comparator_t a(STR_2_VEC(shared_secret_a));
themispp::secure_comparator_t b(STR_2_VEC(shared_secret_b));
std::vector<uint8_t> buf;
buf=a.init();
buf=b.proceed(buf);
buf=a.proceed(buf);
buf=b.proceed(buf);
buf=a.proceed(buf);
sput_fail_unless(a.get(), "a ready", __LINE__);
sput_fail_unless(b.get(), "b ready", __LINE__);
std::string shared_secret_c("shared_secret_c");
std::string shared_secret_d("shared_secret_d");
themispp::secure_comparator_t c(STR_2_VEC(shared_secret_c));
themispp::secure_comparator_t d(STR_2_VEC(shared_secret_d));
buf=c.init();
buf=d.proceed(buf);
buf=c.proceed(buf);
buf=d.proceed(buf);
buf=c.proceed(buf);
sput_fail_unless(!(c.get()), "c ready", __LINE__);
sput_fail_unless(!(d.get()), "d ready", __LINE__);
}
int run_secure_comparator_test(){
sput_enter_suite("ThemisPP secure comparator test");
sput_run_test(secure_comparator_test, "secure_comparator_test", __FILE__);
return 0;
}
}
}
#endif
#endif
| [
"andrey@cossacklabs.com"
] | andrey@cossacklabs.com |
d0787bf21b8d911ab319f3f5a78dc416d6728607 | 543baf3f63e6a6b47534b524e54fa90c37613959 | /2013tonghua/E/main.cpp | 9cedfd9fa89d8f16d7de491ac388df62e9642030 | [] | no_license | funtion/algorithmProblems | ac9341f9fc5233cffe51d2140404983763b66265 | dd27afc25670ea3ad2a681dc382a3e500e530c1a | refs/heads/master | 2020-05-04T05:15:44.150235 | 2014-01-12T10:53:27 | 2014-01-12T10:53:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 774 | cpp | #include <iostream>
using namespace std;
int t;
long g,l;
long div[10000],cd;
inline long lcm(long x,long y,long z){
}
int main()
{
cin>>t;
while(t--){
cin>>l>>g;
if(g%l!=0){
cout<<0<<endl;
}else{
g/=l;
cd=0;
for(long i=1;i<=g/2;i++){
if(g%i==0){
div[cd++] = i;
}
}
long ans = 0;
for(int i=0;i<cd;i++){
for(int j=0;j<cd;j++){
for(int k=0;k<cd;k++){
if(lcd(i,j,k)==1){
ans++;
}
}
}
}
cout<<ans<<endl;
}
}
return 0;
}
| [
"acm@acm.com"
] | acm@acm.com |
9a6d2798737bce2c8b476da62958f5eaa6e74ac8 | 2f92193dcdf5bdb9c6e6b1877dcb89d7be0d8731 | /src/rpc/server.cpp | 9ca799528a4cb1a7269089db59c6f7a9fed3bda1 | [
"MIT"
] | permissive | Ltedeveloper/LTE-core | 21e83ed3eaf4bf597fbc7c53fe7312cd48dfe0e4 | 1410327c5139c6d74cd8f0035e976b98878342d8 | refs/heads/master | 2021-05-12T06:36:22.403299 | 2018-11-09T01:37:02 | 2018-11-09T01:37:02 | 117,222,291 | 6 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 17,556 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpc/server.h"
#include "base58.h"
#include "fs.h"
#include "init.h"
#include "random.h"
#include "sync.h"
#include "ui_interface.h"
#include "util.h"
#include "utilstrencodings.h"
#include <univalue.h>
#include <boost/bind.hpp>
#include <boost/signals2/signal.hpp>
#include <boost/algorithm/string/case_conv.hpp> // for to_upper()
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <memory> // for unique_ptr
#include <unordered_map>
static bool fRPCRunning = false;
static bool fRPCInWarmup = true;
static std::string rpcWarmupStatus("RPC server started");
static CCriticalSection cs_rpcWarmup;
/* Timer-creating functions */
static RPCTimerInterface* timerInterface = nullptr;
/* Map of name to timer. */
static std::map<std::string, std::unique_ptr<RPCTimerBase> > deadlineTimers;
static struct CRPCSignals
{
boost::signals2::signal<void ()> Started;
boost::signals2::signal<void ()> Stopped;
boost::signals2::signal<void (const CRPCCommand&)> PreCommand;
} g_rpcSignals;
void RPCServer::OnStarted(std::function<void ()> slot)
{
g_rpcSignals.Started.connect(slot);
}
void RPCServer::OnStopped(std::function<void ()> slot)
{
g_rpcSignals.Stopped.connect(slot);
}
void RPCServer::OnPreCommand(std::function<void (const CRPCCommand&)> slot)
{
g_rpcSignals.PreCommand.connect(boost::bind(slot, _1));
}
void RPCTypeCheck(const UniValue& params,
const std::list<UniValue::VType>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
for (UniValue::VType t : typesExpected)
{
if (params.size() <= i)
break;
const UniValue& v = params[i];
if (!(fAllowNull && v.isNull())) {
RPCTypeCheckArgument(v, t);
}
i++;
}
}
void RPCTypeCheckArgument(const UniValue& value, UniValue::VType typeExpected)
{
if (value.type() != typeExpected) {
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected type %s, got %s", uvTypeName(typeExpected), uvTypeName(value.type())));
}
}
void RPCTypeCheckObj(const UniValue& o,
const std::map<std::string, UniValueType>& typesExpected,
bool fAllowNull,
bool fStrict)
{
for (const auto& t : typesExpected) {
const UniValue& v = find_value(o, t.first);
if (!fAllowNull && v.isNull())
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
if (!(t.second.typeAny || v.type() == t.second.type || (fAllowNull && v.isNull()))) {
std::string err = strprintf("Expected type %s for %s, got %s",
uvTypeName(t.second.type), t.first, uvTypeName(v.type()));
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
if (fStrict)
{
for (const std::string& k : o.getKeys())
{
if (typesExpected.count(k) == 0)
{
std::string err = strprintf("Unexpected key %s", k);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
}
CAmount AmountFromValue(const UniValue& value)
{
if (!value.isNum() && !value.isStr())
throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string");
CAmount amount;
if (!ParseFixedPoint(value.getValStr(), 8, &amount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
if (!MoneyRange(amount))
throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range");
return amount;
}
uint256 ParseHashV(const UniValue& v, std::string strName)
{
std::string strHex;
if (v.isStr())
strHex = v.get_str();
if (!IsHex(strHex)) // Note: IsHex("") is false
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
if (64 != strHex.length())
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be of length %d (not %d)", strName, 64, strHex.length()));
uint256 result;
result.SetHex(strHex);
return result;
}
uint256 ParseHashO(const UniValue& o, std::string strKey)
{
return ParseHashV(find_value(o, strKey), strKey);
}
std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName)
{
std::string strHex;
if (v.isStr())
strHex = v.get_str();
if (!IsHex(strHex))
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
return ParseHex(strHex);
}
std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey)
{
return ParseHexV(find_value(o, strKey), strKey);
}
/**
* Note: This interface may still be subject to change.
*/
std::string CRPCTable::help(const std::string& strCommand, const JSONRPCRequest& helpreq) const
{
std::string strRet;
std::string category;
std::set<rpcfn_type> setDone;
std::vector<std::pair<std::string, const CRPCCommand*> > vCommands;
for (std::map<std::string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
vCommands.push_back(make_pair(mi->second->category + mi->first, mi->second));
sort(vCommands.begin(), vCommands.end());
JSONRPCRequest jreq(helpreq);
jreq.fHelp = true;
jreq.params = UniValue();
for (const std::pair<std::string, const CRPCCommand*>& command : vCommands)
{
const CRPCCommand *pcmd = command.second;
std::string strMethod = pcmd->name;
if ((strCommand != "" || pcmd->category == "hidden") && strMethod != strCommand)
continue;
jreq.strMethod = strMethod;
try
{
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(jreq);
}
catch (const std::exception& e)
{
// Help text is returned in an exception
std::string strHelp = std::string(e.what());
if (strCommand == "")
{
if (strHelp.find('\n') != std::string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
if (category != pcmd->category)
{
if (!category.empty())
strRet += "\n";
category = pcmd->category;
std::string firstLetter = category.substr(0,1);
boost::to_upper(firstLetter);
strRet += "== " + firstLetter + category.substr(1) + " ==\n";
}
}
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand);
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
UniValue help(const JSONRPCRequest& jsonRequest)
{
if (jsonRequest.fHelp || jsonRequest.params.size() > 1)
throw std::runtime_error(
"help ( \"command\" )\n"
"\nList all commands, or get help for a specified command.\n"
"\nArguments:\n"
"1. \"command\" (string, optional) The command to get help on\n"
"\nResult:\n"
"\"text\" (string) The help text\n"
);
std::string strCommand;
if (jsonRequest.params.size() > 0)
strCommand = jsonRequest.params[0].get_str();
return tableRPC.help(strCommand, jsonRequest);
}
UniValue stop(const JSONRPCRequest& jsonRequest)
{
// Accept the deprecated and ignored 'detach' boolean argument
if (jsonRequest.fHelp || jsonRequest.params.size() > 1)
throw std::runtime_error(
"stop\n"
"\nStop LTE server.");
// Event loop will exit after current HTTP requests have been handled, so
// this reply will get back to the client.
StartShutdown();
return "LTE server stopping";
}
UniValue uptime(const JSONRPCRequest& jsonRequest)
{
if (jsonRequest.fHelp || jsonRequest.params.size() > 1)
throw std::runtime_error(
"uptime\n"
"\nReturns the total uptime of the server.\n"
"\nResult:\n"
"ttt (numeric) The number of seconds that the server has been running\n"
"\nExamples:\n"
+ HelpExampleCli("uptime", "")
+ HelpExampleRpc("uptime", "")
);
return GetTime() - GetStartupTime();
}
/**
* Call Table
*/
static const CRPCCommand vRPCCommands[] =
{ // category name actor (function) okSafe argNames
// --------------------- ------------------------ ----------------------- ------ ----------
/* Overall control/query calls */
{ "control", "help", &help, true, {"command"} },
{ "control", "stop", &stop, true, {} },
{ "control", "uptime", &uptime, true, {} },
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](const std::string &name) const
{
std::map<std::string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return nullptr;
return (*it).second;
}
bool CRPCTable::appendCommand(const std::string& name, const CRPCCommand* pcmd)
{
if (IsRPCRunning())
return false;
// don't allow overwriting for now
std::map<std::string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it != mapCommands.end())
return false;
mapCommands[name] = pcmd;
return true;
}
bool StartRPC()
{
LogPrint(BCLog::RPC, "Starting RPC\n");
fRPCRunning = true;
g_rpcSignals.Started();
return true;
}
void InterruptRPC()
{
LogPrint(BCLog::RPC, "Interrupting RPC\n");
// Interrupt e.g. running longpolls
fRPCRunning = false;
}
void StopRPC()
{
LogPrint(BCLog::RPC, "Stopping RPC\n");
deadlineTimers.clear();
DeleteAuthCookie();
g_rpcSignals.Stopped();
}
bool IsRPCRunning()
{
return fRPCRunning;
}
void SetRPCWarmupStatus(const std::string& newStatus)
{
LOCK(cs_rpcWarmup);
rpcWarmupStatus = newStatus;
}
void SetRPCWarmupFinished()
{
LOCK(cs_rpcWarmup);
assert(fRPCInWarmup);
fRPCInWarmup = false;
}
bool RPCIsInWarmup(std::string *outStatus)
{
LOCK(cs_rpcWarmup);
if (outStatus)
*outStatus = rpcWarmupStatus;
return fRPCInWarmup;
}
void JSONRPCRequest::parse(const UniValue& valRequest)
{
// Parse request
if (!valRequest.isObject())
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const UniValue& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
UniValue valMethod = find_value(request, "method");
if (valMethod.isNull())
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (!valMethod.isStr())
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
LogPrint(BCLog::RPC, "ThreadRPCServer method=%s\n", SanitizeString(strMethod));
// Parse params
UniValue valParams = find_value(request, "params");
if (valParams.isArray() || valParams.isObject())
params = valParams;
else if (valParams.isNull())
params = UniValue(UniValue::VARR);
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array or object");
}
static UniValue JSONRPCExecOne(const UniValue& req)
{
UniValue rpc_result(UniValue::VOBJ);
JSONRPCRequest jreq;
try {
jreq.parse(req);
UniValue result = tableRPC.execute(jreq);
rpc_result = JSONRPCReplyObj(result, NullUniValue, jreq.id);
}
catch (const UniValue& objError)
{
rpc_result = JSONRPCReplyObj(NullUniValue, objError, jreq.id);
}
catch (const std::exception& e)
{
rpc_result = JSONRPCReplyObj(NullUniValue,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
std::string JSONRPCExecBatch(const UniValue& vReq)
{
UniValue ret(UniValue::VARR);
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return ret.write() + "\n";
}
/**
* Process named arguments into a vector of positional arguments, based on the
* passed-in specification for the RPC call's arguments.
*/
static inline JSONRPCRequest transformNamedArguments(const JSONRPCRequest& in, const std::vector<std::string>& argNames)
{
JSONRPCRequest out = in;
out.params = UniValue(UniValue::VARR);
// Build a map of parameters, and remove ones that have been processed, so that we can throw a focused error if
// there is an unknown one.
const std::vector<std::string>& keys = in.params.getKeys();
const std::vector<UniValue>& values = in.params.getValues();
std::unordered_map<std::string, const UniValue*> argsIn;
for (size_t i=0; i<keys.size(); ++i) {
argsIn[keys[i]] = &values[i];
}
// Process expected parameters.
int hole = 0;
for (const std::string &argNamePattern: argNames) {
std::vector<std::string> vargNames;
boost::algorithm::split(vargNames, argNamePattern, boost::algorithm::is_any_of("|"));
auto fr = argsIn.end();
for (const std::string & argName : vargNames) {
fr = argsIn.find(argName);
if (fr != argsIn.end()) {
break;
}
}
if (fr != argsIn.end()) {
for (int i = 0; i < hole; ++i) {
// Fill hole between specified parameters with JSON nulls,
// but not at the end (for backwards compatibility with calls
// that act based on number of specified parameters).
out.params.push_back(UniValue());
}
hole = 0;
out.params.push_back(*fr->second);
argsIn.erase(fr);
} else {
hole += 1;
}
}
// If there are still arguments in the argsIn map, this is an error.
if (!argsIn.empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Unknown named parameter " + argsIn.begin()->first);
}
// Return request with named arguments transformed to positional arguments
return out;
}
UniValue CRPCTable::execute(const JSONRPCRequest &request) const
{
// Return immediately if in warmup
{
LOCK(cs_rpcWarmup);
if (fRPCInWarmup)
throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus);
}
// Find method
const CRPCCommand *pcmd = tableRPC[request.strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
g_rpcSignals.PreCommand(*pcmd);
try
{
// Execute, convert arguments to array if necessary
if (request.params.isObject()) {
return pcmd->actor(transformNamedArguments(request, pcmd->argNames));
} else {
return pcmd->actor(request);
}
}
catch (const std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
std::vector<std::string> CRPCTable::listCommands() const
{
std::vector<std::string> commandList;
typedef std::map<std::string, const CRPCCommand*> commandMap;
std::transform( mapCommands.begin(), mapCommands.end(),
std::back_inserter(commandList),
boost::bind(&commandMap::value_type::first,_1) );
return commandList;
}
std::string HelpExampleCli(const std::string& methodname, const std::string& args)
{
return "> litecoin-cli " + methodname + " " + args + "\n";
}
std::string HelpExampleRpc(const std::string& methodname, const std::string& args)
{
return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", "
"\"method\": \"" + methodname + "\", \"params\": [" + args + "] }' -H 'content-type: text/plain;' http://127.0.0.1:9332/\n";
}
void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
{
if (!timerInterface)
timerInterface = iface;
}
void RPCSetTimerInterface(RPCTimerInterface *iface)
{
timerInterface = iface;
}
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
{
if (timerInterface == iface)
timerInterface = nullptr;
}
void RPCRunLater(const std::string& name, std::function<void(void)> func, int64_t nSeconds)
{
if (!timerInterface)
throw JSONRPCError(RPC_INTERNAL_ERROR, "No timer handler registered for RPC");
deadlineTimers.erase(name);
LogPrint(BCLog::RPC, "queue run of timer %s in %i seconds (using %s)\n", name, nSeconds, timerInterface->Name());
deadlineTimers.emplace(name, std::unique_ptr<RPCTimerBase>(timerInterface->NewTimer(func, nSeconds*1000)));
}
int RPCSerializationFlags()
{
int flag = 0;
if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) == 0)
flag |= SERIALIZE_TRANSACTION_NO_WITNESS;
return flag;
}
CRPCTable tableRPC;
| [
"zhangzhentao@blocklinker.com"
] | zhangzhentao@blocklinker.com |
1140e04d441d962bd8edbfbafa8d0b5a87d2b05b | cdb171176480747aeacc1a01cda58aa185efbca8 | /msvc/IO/ExportPDF/vtkIOExportPDFObjectFactory.cxx | 213e6aa59851d783a1b2740e329b3a4e05ebc634 | [
"BSD-3-Clause"
] | permissive | gajgeospatial/VTK-9.0.1 | 1504a2f2991da7c3765cd90fed0880c7b6783bf6 | 8ab2c0f8852f26598d950c9c7e514947b6855a41 | refs/heads/master | 2023-04-12T09:03:47.351448 | 2021-05-05T17:35:04 | 2021-05-05T17:35:04 | 266,163,338 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,807 | cxx | /*=========================================================================
Program: Visualization Toolkit
Module: vtkIOExportPDFObjectFactory.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkIOExportPDFObjectFactory.h"
#include "vtkVersion.h"
// Include all of the classes we want to create overrides for.
#include "vtkPDFContextDevice2D.h"
vtkStandardNewMacro(vtkIOExportPDFObjectFactory);
// Now create the functions to create overrides with.
VTK_CREATE_CREATE_FUNCTION(vtkPDFContextDevice2D)
vtkIOExportPDFObjectFactory::vtkIOExportPDFObjectFactory()
{
this->RegisterOverride("vtkContextDevice2D", "vtkPDFContextDevice2D", "Override for VTK::IOExportPDF module", 1, vtkObjectFactoryCreatevtkPDFContextDevice2D);
}
const char * vtkIOExportPDFObjectFactory::GetVTKSourceVersion()
{
return VTK_SOURCE_VERSION;
}
void vtkIOExportPDFObjectFactory::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
// Registration of object factories.
static unsigned int vtkIOExportPDFCount = 0;
VTKIOEXPORTPDF_EXPORT void vtkIOExportPDF_AutoInit_Construct()
{
if(++vtkIOExportPDFCount == 1)
{
vtkIOExportPDFObjectFactory* factory = vtkIOExportPDFObjectFactory::New();
if (factory)
{
// vtkObjectFactory keeps a reference to the "factory",
vtkObjectFactory::RegisterFactory(factory);
factory->Delete();
}
}
}
| [
"glen.johnson@gaj-geospatial.com"
] | glen.johnson@gaj-geospatial.com |
7d5d353f8cd72fb8dcdabf57eefd7e9915ce3a36 | 149354d7985afe98a4e895adf3b87cc21a1c5d8d | /Core/String.hpp | 39ba5b6e57dcd530beab957785a94c09d871f26d | [
"Unlicense"
] | permissive | cursey/kanan-new | 5c8bde2bc51c985f116c889ba731ca77224baa90 | 4b1bb49cd8838e21263196c72ba0024394d7ef49 | refs/heads/master | 2023-09-01T02:46:48.031030 | 2023-08-26T01:01:19 | 2023-08-26T01:01:19 | 108,602,829 | 146 | 98 | Unlicense | 2023-09-08T02:25:48 | 2017-10-27T22:53:39 | C++ | UTF-8 | C++ | false | false | 418 | hpp | #pragma once
#include <string>
#include <string_view>
#include <vector>
namespace kanan {
//
// String utilities.
//
// Conversion functions for UTF8<->UTF16.
std::string narrow(std::wstring_view str);
std::wstring widen(std::string_view str);
std::string formatString(const char* format, va_list args);
std::vector<std::string> split(std::string str, const std::string& delim);
}
| [
"cursey@live.com"
] | cursey@live.com |
4ff9f6d2780eba0bf5e16725d7c2a45be725339c | 829faecc97ec07db831c9c138bdf089ee34c9a0f | /cpp/openGLEssential/lessons/Lesson3.3/ModelDemo.cpp | d49dc09f8433236ffde91a5fe7f827fd1b99b7a1 | [] | no_license | sysbender/study | ec1cf8baa3b2971dfb9aa08566bf5db7e5cc663d | d69bd41a269a4936624b6c4bcd53a71616986eb0 | refs/heads/master | 2021-01-20T06:07:56.494951 | 2018-07-16T12:47:01 | 2018-07-16T12:47:01 | 101,484,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,663 | cpp | #include "pch.h"
using namespace glm;
using namespace std;
using namespace Library;
namespace Rendering
{
RTTI_DEFINITIONS(ModelDemo)
ModelDemo::ModelDemo(Game& game, Camera& camera)
: DrawableGameComponent(game, camera), mShaderProgram(), mVertexArrayObject(0), mVertexBuffer(0),
mIndexBuffer(0), mWorldViewProjectionLocation(-1), mIndexCount(0)
{
}
ModelDemo::~ModelDemo()
{
glDeleteBuffers(1, &mIndexBuffer);
glDeleteBuffers(1, &mVertexBuffer);
glDeleteVertexArrays(1, &mVertexArrayObject);
}
void ModelDemo::Initialize()
{
SetCurrentDirectory(Utility::ExecutableDirectory().c_str());
// Build the shader program
vector<ShaderDefinition> shaders;
shaders.push_back(ShaderDefinition(GL_VERTEX_SHADER, L"Content\\Effects\\ModelDemo.vert"));
shaders.push_back(ShaderDefinition(GL_FRAGMENT_SHADER, L"Content\\Effects\\ModelDemo.frag"));
mShaderProgram.BuildProgram(shaders);
// Load the model
Model model("Content\\Models\\Sphere.obj");
// Create the vertex and index buffers
Mesh* mesh = model.Meshes().at(0);
CreateVertexBuffer(*mesh, mVertexBuffer);
mesh->CreateIndexBuffer(mIndexBuffer);
mIndexCount = mesh->Indices().size();
glGenVertexArrays(1, &mVertexArrayObject);
glBindVertexArray(mVertexArrayObject);
glVertexAttribPointer(static_cast<GLuint>(VertexAttribute::Position), 4, GL_FLOAT, GL_FALSE, sizeof(VertexPositionColor), (void*)offsetof(VertexPositionColor, Position));
glEnableVertexAttribArray(static_cast<GLuint>(VertexAttribute::Position));
glVertexAttribPointer(static_cast<GLuint>(VertexAttribute::Color), 4, GL_FLOAT, GL_FALSE, sizeof(VertexPositionColor), (void*)offsetof(VertexPositionColor, Color));
glEnableVertexAttribArray(static_cast<GLuint>(VertexAttribute::Color));
glBindVertexArray(0);
mWorldViewProjectionLocation = glGetUniformLocation(mShaderProgram.Program(), "WorldViewProjection");
if (mWorldViewProjectionLocation == -1)
{
throw GameException("glGetUniformLocation() did not find uniform location.");
}
}
void ModelDemo::Draw(const GameTime& gameTime)
{
UNREFERENCED_PARAMETER(gameTime);
glBindVertexArray(mVertexArrayObject);
glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
mShaderProgram.Use();
mat4 wvp = mCamera->ViewProjectionMatrix() * mWorldMatrix;
glUniformMatrix4fv(mWorldViewProjectionLocation, 1, GL_FALSE, &wvp[0][0]);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
glDrawElements(GL_TRIANGLES, mIndexCount, GL_UNSIGNED_INT, 0);
}
void ModelDemo::CreateVertexBuffer(const Mesh& mesh, GLuint& vertexBuffer)
{
const vector<vec3>& sourceVertices = mesh.Vertices();
vector<VertexPositionColor> vertices;
vertices.reserve(sourceVertices.size());
if (mesh.VertexColors().size() > 0)
{
vector<vec4>* vertexColors = mesh.VertexColors().at(0);
assert(vertexColors->size() == sourceVertices.size());
for (size_t i = 0; i < sourceVertices.size(); i++)
{
const vec3& position = sourceVertices.at(i);
const vec4& color = vertexColors->at(i);
vertices.push_back(VertexPositionColor(vec4(position.x, position.y, position.z, 1.0f), color));
}
}
else
{
for (size_t i = 0; i < sourceVertices.size(); i++)
{
const vec3& position = sourceVertices.at(i);
const vec4& color = ColorHelper::RandomColor();
vertices.push_back(VertexPositionColor(vec4(position.x, position.y, position.z, 1.0f), color));
}
}
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(VertexPositionColor) * vertices.size(), &vertices[0], GL_STATIC_DRAW);
}
} | [
"sysbender@gmail.com"
] | sysbender@gmail.com |
00c46bce30e703ed8e0d2244454e14031ebe1485 | 7dc87769a3eb5e38846cef7bce17c221ad57bd6d | /qt4/utility_classes/home.cpp | 91d8d1b240c0869c45eb51f03956172987c593b3 | [] | no_license | tanxulong/interview | e2f5a90026bdc3e6472dcd702ec8369c3e84985e | a60801767cd3fd7537bd087cc855557d2ec17d0b | refs/heads/master | 2020-04-06T06:39:59.408241 | 2013-05-08T13:51:44 | 2013-05-08T13:51:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 225 | cpp | /*
* the QDir class provides access to directory structures
* and their contents.
*/
#include <QTextStream>
#include <QDir>
int main()
{
QTextStream out(stdout);
QString home = QDir::homePath();
out << home <<endl;
}
| [
"reg.tanxulong@gmial.com"
] | reg.tanxulong@gmial.com |
530c411f18f99f656b7ebbbbe872329d2e09fdaa | 8bfde2ca2f110e87e6d7af5d0808362e741bcd64 | /COMPETITIVE_NININJAS/Minimum Number of Chocolates.cpp | 510b2f9da394c7095504ffe0e1d81aafdb012887 | [] | no_license | SamarthAroraa/cpp-codebase | e9f59dcab89d10fcd9570917817d71d25d725e54 | fdd2fb04664a8865f72a96f36838c44d29e64fc3 | refs/heads/master | 2022-08-29T03:57:02.847686 | 2020-05-29T08:55:52 | 2020-05-29T08:55:52 | 267,812,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 916 | cpp | #include<bits/stdc++.h>
#define deb(x) cerr<<#x<<" "<<x<<endl;
#define ll long long
using namespace std;
int getMin(int *arr, int n){
// sort(arr,arr+n);
// for(int i=0;i<n;i++){
// cout<<arr[i]<<" ";
// }
int sum=0;
int choc[n];
choc[0]=1;
// sum+=choc[0];
for(int i=1;i<n;i++){
if(arr[i]>arr[i-1]){
choc[i] = choc[i-1]+1;
}
else{
choc[i]= 1;
}
// deb(i)
// deb(choc[i])
// sum+=choc[i];
}
for(int i=n-2;i>=0;i--){
if(arr[i]>arr[i+1] and choc[i]<=choc[i+1]){
choc[i] = choc[i+1]+1;
}
sum+=choc[i];
// deb(i)
// deb(choc[i])
// sum+=choc[i];
}
return sum+choc[n-1];
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n;
cin>>n;
int*arr= new int[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
int k= getMin(arr,n);
cout<<k;
return 0;
} | [
"samartharora@Samarths-MacBook-Air.local"
] | samartharora@Samarths-MacBook-Air.local |
bdc6fbf380354505800d7b26580a0b302d70607d | 80cf612d55905c0d7f091b064c9e69962ad0f89c | /test/main.cpp | e0ca2ef543f9a098f0dee75af515ac54e398ff6e | [] | no_license | houdini22/prime_numbers | 70457d1e7c2615b10186443efcf6cca3d15f0f19 | 9882d2a3d21f66d46dcf40418d43314a4053231f | refs/heads/master | 2020-05-20T20:30:34.085017 | 2019-05-18T13:18:40 | 2019-05-18T13:18:40 | 185,744,250 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,039 | cpp | #include <iostream>
#include <math.h>
#include <string>
#include <algorithm>
#include <vector>
#include <stdlib.h>
#include <map>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <chrono>
/*
* DATA TYPES
*/
typedef long long T_NUM;
typedef std::vector<T_NUM> T_NUM_VEC;
typedef std::string T_STR;
typedef std::vector<T_STR> T_STR_VEC;
typedef std::pair<T_NUM, T_NUM> T_PAIR;
typedef std::vector<T_PAIR> T_PAIR_VEC;
typedef std::vector<std::vector<std::vector<T_NUM>>> T_3D_NUM_VEC;
struct T_STRUCT {
T_NUM angle;
T_NUM angleSize;
T_NUM sum;
T_PAIR_VEC vec;
T_3D_NUM_VEC splitted;
T_NUM splitted_sum = 0;
T_STR comparison;
};
typedef std::vector<T_STRUCT> T_STRUCTURE_VECTOR;
struct T_SORT_STRUCT {
inline bool operator()(const T_STRUCT &s1, const T_STRUCT &s2) {
return (s1.angle < s2.angle);
}
};
struct T_HISTOGRAM_SORT_STRUCT {
inline bool operator()(const T_PAIR &s1, const T_PAIR &s2) {
return (s1.first < s2.first);
}
};
/*
* CONFIG
*/
T_STR output = "std::cout";
/*
* FUNCTIONS
*/
T_NUM sumVector(T_NUM_VEC vec);
void debugVector(T_STR title, T_NUM_VEC vec, bool sum);
void debugPairVector(T_PAIR_VEC vec);
void debug3dVector(T_3D_NUM_VEC vec);
int charToInt(char c);
T_STR getNumbersFromTri(double d_num, T_STR s_num, T_NUM d_step, unsigned int ommit, unsigned long length);
T_NUM sumVector(T_NUM_VEC vec);
T_NUM_VEC createVectorFromTri(T_STR sinus, T_STR cosinus, T_STR tangens, T_STR itangens);
bool isPrime(T_NUM num);
T_3D_NUM_VEC splitVector(T_NUM_VEC vec, size_t length);
T_NUM_VEC createPrimaryNumberFromSplits(T_3D_NUM_VEC vec, T_NUM multiplier);
T_STR_VEC splitString(T_STR str);
/*
* TRIGONOMETRY
*/
const double PI = std::acos(-1);
double degreeToRadian(double degree) {
return degree * PI / 180.0;
}
double radianToDegree(double radians) {
return radians * 180 / PI;
}
double _sin(double x) {
return std::sin(degreeToRadian(x));
}
double _cos(double x) {
return std::cos(degreeToRadian(x));
}
double _tan(double x) {
return std::tan(degreeToRadian(x));
}
double _itan(double x) {
return radianToDegree(std::atan(x));
}
/*
* HELPERS
*/
/**
* it prints content of the 1D T_NUM vector
* @param vec
*/
void debugVector(T_STR title, T_NUM_VEC vec, bool sum = false) {
std::cout << "\t___" << title << "___";
if (sum) {
std::cout << ": " << sumVector(vec);
}
std::cout << std::endl;
for (size_t i = 0; i < vec.size(); i++) {
std::cout << vec[i];
if (i < vec.size() - 1) {
std::cout << ", ";
}
}
std::cout << std::endl << std::endl;
}
/**
* it prints content of the T_PAIR vector
* @param vec
*/
void debugPairVector(T_PAIR_VEC vec) {
std::cout << "\t___map___" << std::endl;
for (size_t i = 0; i < vec.size(); i++) {
std::cout << vec[i].first << ":" << vec[i].second;
if (i < vec.size() - 1) {
std::cout << ", ";
}
}
std::cout << std::endl << std::endl;
}
/**
* it prints content of the 3D T_NUM vector
* @param vec
*/
void debug3dVector(T_3D_NUM_VEC vec) {
std::cout << "\t___splitted___" << std::endl;
for (size_t i = 0; i < vec.size(); i++) {
for (size_t j = 0; j < vec[i].size(); j++) {
for (size_t k = 0; k < vec[i][j].size(); k++) {
std::cout << vec[i][j][k];
}
std::cout << '\t' << '\t';
}
std::cout << std::endl;
}
std::cout << std::endl << std::endl;
}
/**
* It converts string ASCII char [0-9] to integer in C++
* @param c
* @return
*/
int charToInt(char c) {
int result = c;
switch (result) {
case 48:
return 0;
case 49:
return 1;
case 50:
return 2;
case 51:
return 3;
case 52:
return 4;
case 53:
return 5;
case 54:
return 6;
case 55:
return 7;
case 56:
return 8;
case 57:
return 9;
default:
return 0;
}
}
/**
* it converts TRIgonometry numbers to a string (2 number angle -> 2 sized string, 3 number angle -> 3 sized string)
* @param d_num
* @param s_num
* @param d_step
* @param ommit
* @param length
* @return
*/
T_STR getNumbersFromTri(double d_num, T_STR s_num, T_NUM d_step, unsigned int ommit, unsigned long length) {
T_STR result = "";
if (ommit == 0) {
for (size_t i = s_num[0] == '-' ? ommit + 1 : ommit; i < s_num.length(); i++) {
if (s_num[i] != '.') {
result += s_num[i];
}
}
result = result.substr(0, length);
} else if (d_num < 0) {
ommit += 1; // comma
result = s_num.substr(ommit, length);
} else if (d_num > 0) {
result = s_num.substr(ommit, length);
}
return result;
}
/**
* Get sum from T_NUM vector
* @param vec
* @return
*/
T_NUM sumVector(T_NUM_VEC vec) {
T_NUM result = 0;
for (size_t i = 0; i < vec.size(); i++) {
result += vec.at(i);
}
return result;
}
/**
* it creates T_NUM vector from TRInity numbers
* @param sinus
* @param cosinus
* @param tangens
* @param s4
* @return
*/
T_NUM_VEC createVectorFromTri(T_STR sinus, T_STR cosinus, T_STR tangens, T_STR itangens) {
T_NUM_VEC result = T_NUM_VEC();
for (int i = 0; i < sinus.length(); i++) {
result.push_back(charToInt(sinus.at(i)));
}
for (int i = 0; i < cosinus.length(); i++) {
result.push_back(charToInt(cosinus.at(i)));
}
for (int i = 0; i < tangens.length(); i++) {
result.push_back(charToInt(tangens.at(i)));
}
for (int i = 0; i < itangens.length(); i++) {
result.push_back(charToInt(itangens.at(i)));
}
return result;
}
/**
* Simple get true if number is primary
* @param num
* @return
*/
bool isPrime(T_NUM num) {
if (num < 2) return false;
if (num == 2) return true;
if (num % 2 == 0) return false;
for (T_NUM i = 3; i * i <= num; i += 2) {
if (num % i == 0) return false;
}
return true;
}
/**
* It converts T_NUM_VEC to splited vector (extended examples)
* @param vec
* @param length
* @return
*/
T_3D_NUM_VEC splitVector(T_NUM_VEC vec, T_NUM length) {
T_3D_NUM_VEC result;
result.resize(vec.size() / length);
T_NUM row = 0;
T_NUM col = 0;
for (T_NUM i = 0; i < vec.size(); i++) {
result[row].resize(length);
if (vec[i] == 7 || vec[i] == 5 || vec[i] == 3 || vec[i] == 2 || vec[i] == 1 || vec[i] == 0) {
result[(unsigned long) row][(unsigned long) col].resize(1);
result[(unsigned long) row][(unsigned long) col][0] = vec[i];
} else if (vec[i] == 8) {
result[(unsigned long) row][(unsigned long) col].resize(4);
result[(unsigned long) row][(unsigned long) col][0] = 2;
result[(unsigned long) row][(unsigned long) col][1] = 2;
result[(unsigned long) row][(unsigned long) col][2] = 2;
result[(unsigned long) row][(unsigned long) col][3] = 2;
} else if (vec[i] == 6) {
result[(unsigned long) row][(unsigned long) col].resize(2);
result[(unsigned long) row][(unsigned long) col][0] = 3;
result[(unsigned long) row][(unsigned long) col][1] = 3;
} else if (vec[i] == 4) {
result[(unsigned long) row][(unsigned long) col].resize(2);
result[(unsigned long) row][(unsigned long) col][0] = 2;
result[(unsigned long) row][(unsigned long) col][1] = 2;
} else if (vec[i] == 9) {
result[(unsigned long) row][(unsigned long) col].resize(3);
result[(unsigned long) row][(unsigned long) col][0] = 3;
result[(unsigned long) row][(unsigned long) col][1] = 3;
result[(unsigned long) row][(unsigned long) col][2] = 3;
}
if (((i + 1) % length) == 0) {
row++;
col = 0;
} else {
col++;
}
}
return result;
}
T_NUM_VEC createPrimaryNumberFromSplits(T_3D_NUM_VEC vec, T_NUM multiplier = 1) {
T_NUM_VEC result;
result.resize(vec.size());
for (T_NUM row = 0; row < vec.size(); row++) {
for (T_NUM number = 0; number < vec[row][0].size(); number++) {
T_NUM _result = 0;
for (size_t i = 1; i < vec[row].size(); i++) {
_result += (T_NUM) pow(vec[row][0][number], vec[row][i].size() * multiplier);
}
result[row] += _result;
}
}
return result;
}
T_STR createCell(T_NUM tabLength, T_STR content) {
T_NUM subtract = (tabLength * 4) - (T_NUM) content.length();
auto numTabs = (T_NUM) ceil((int) subtract / (int) 4);
if (((int) subtract) % 4 != 0) {
numTabs++;
}
for (T_NUM i = 0; i < numTabs; i++) {
content.append("\t");
}
return content;
}
std::ofstream fileTest;
std::ofstream fileSums;
std::ofstream fileHistogram;
std::ofstream fileSymmetry;
std::ofstream filePython;
void writeSumsToFile(T_STRUCT arr) {
fileSums << std::to_string(arr.angle) << ":\t";
if (arr.angleSize == 2 || arr.angleSize == 1) {
fileSums << "\t";
}
T_NUM sum = 0;
for (size_t i = 0; i < arr.splitted.size(); i++) {
for (size_t j = 0; j < arr.splitted[i].size(); j++) {
for (size_t k = 0; k < arr.splitted[i][j].size(); k++) {
sum += arr.splitted[i][j][k];
}
}
}
fileSums << std::to_string(sum) << "\t\t";
fileSums << (isPrime(sum) ? "true" : "false") << "\t\t";
for (T_NUM j = -2; j <= 2; j++) {
T_STR cell;
for (T_NUM k = -1; k <= 1; k += 2) {
if (j + k == 0) continue;
if (isPrime(sum + j + k)) {
cell.append(createCell(1, "|"));
cell.append(createCell(1, std::to_string(sum + j + k)));
cell.append(createCell(1, ":"));
cell.append(createCell(1, std::to_string(j)));
cell.append(createCell(1, std::to_string(k)));
cell.append(createCell(2, "|"));
fileSums << cell;
}
}
}
fileSums << "\n";
}
void writeDataToFile(T_STRUCT arr) {
fileTest << "___angle___\n";
fileTest << std::to_string(arr.angle) << '\n';
fileTest << "___splitted___\n";
T_NUM sum1 = 0;
T_NUM sum2 = 0;
T_NUM sum3 = 0;
T_NUM sum4 = 0;
T_NUM num1 = 0;
T_NUM num2 = 0;
T_NUM num3 = 0;
T_NUM num4 = 0;
T_NUM after1 = 0;
T_NUM after2 = 0;
T_NUM after3 = 0;
T_NUM after4 = 0;
for (size_t row = 0; row < arr.splitted.size(); row++) {
for (size_t col = 0; col < arr.splitted[row].size(); col++) {
for (size_t number = 0; number < arr.splitted[row][col].size(); number++) {
fileTest << arr.splitted[row][col][number];
}
for (size_t k = arr.splitted[row][col].size(); k < 10; k++) {
fileTest << " ";
}
}
fileTest << "\n";
}
for (size_t row = 0; row < arr.splitted.size(); row++) {
for (size_t col = 0; col < arr.splitted[row].size(); col++) {
for (size_t number = 0; number < arr.splitted[row][col].size(); number++) {
sum1 += arr.splitted[row][col][number];
sum2 += (T_NUM) pow(arr.splitted[row][col][number], arr.splitted[row][col].size());
sum3 += (T_NUM) pow(arr.splitted[row][col][number], number + 1);
sum4 += (T_NUM) pow(arr.splitted[row][col][number], (number + 1) * 2);
}
}
}
fileTest << "___sum1___\n";
fileTest << createCell(4, std::to_string(sum1)) << " " << createCell(4, (isPrime(sum1) ? "true" : "false")) << '\n';
for (T_NUM i = 0; i < 100; i++) {
if (isPrime(sum1 + i)) {
num1 = i;
after1 = sum1 + i;
break;
}
}
fileTest << createCell(4, "ingredient") << createCell(3, std::to_string(num1)) << " after: " << createCell(3, std::to_string(after1)) << '\n';
fileTest << "___sum2___\n";
fileTest << createCell(4, std::to_string(sum2)) << " " << createCell(4, (isPrime(sum2) ? "true" : "false")) << '\n';
for (T_NUM i = 0; i < 100; i++) {
if (isPrime(sum2 + i)) {
num2 = i;
after2 = sum2 + i;
break;
}
}
fileTest << createCell(4, "ingredient") << createCell(3, std::to_string(num2)) << " after: " << createCell(3, std::to_string(after2)) << '\n';
fileTest << "___sum3___\n";
fileTest << createCell(4, std::to_string(sum3)) << " " << createCell(4, (isPrime(sum3) ? "true" : "false")) << '\n';
for (T_NUM i = 0; i < 100; i++) {
if (isPrime(sum3 + i)) {
num3 = i;
after3 = sum3 + i;
break;
}
}
fileTest << createCell(4, "ingredient") << createCell(3, std::to_string(num3)) << " after: " << createCell(3, std::to_string(after3)) << '\n';
fileTest << "___sum4___\n";
fileTest << createCell(4, std::to_string(sum4)) << " " << createCell(4, (isPrime(sum4) ? "true" : "false")) << '\n';
for (T_NUM i = 0; i < 100; i++) {
if (isPrime(sum4 + i)) {
num4 = i;
after4 = sum4 + i;
break;
}
}
fileTest << createCell(4, "ingredient") << createCell(3, std::to_string(num4)) << " after: " << createCell(3, std::to_string(after4)) << '\n';
fileTest << "\n--------------------\n\n";
}
const T_NUM ___BEGIN___ = 18000;
int main() {
// initialize
std::cout.precision(20);
// open files
fileTest.open("./test.txt");
// start
T_NUM_VEC allFound;
T_STRUCTURE_VECTOR arr; // main data container
// from angle -___BEGIN___ (degree) -> + ___BEGIN___ (degree)
for (T_NUM step = 0; step < 1000; step += 1) {
T_NUM_VEC vec1 = createVectorFromTri(
getNumbersFromTri(_sin(step), std::to_string(_sin(step)), step, 2, std::to_string(step).length()),
getNumbersFromTri(_cos(step), std::to_string(_cos(step)), step, 2, std::to_string(step).length()),
getNumbersFromTri(_tan(step), std::to_string(_tan(step)), step, 0, std::to_string(step).length()),
getNumbersFromTri(_itan(step), std::to_string(_itan(step)), step, 0, std::to_string(step).length()));
// create data
T_STRUCT s1;
s1.angle = step;
s1.angleSize = (T_NUM) std::to_string(step).length();
s1.sum = sumVector(vec1);
s1.splitted = splitVector(vec1, s1.angleSize);
arr.push_back(s1);
}
// sort all primary numbers
std::sort(arr.begin(), arr.end(), T_SORT_STRUCT());
// debug
for (T_NUM i = 0; i < arr.size(); i++) {
writeDataToFile(arr[i]);
}
fileTest.close();
fileSums.close();
return 0;
} | [
"baniczek@gmail.com"
] | baniczek@gmail.com |
acc68984a139d28aaeba3060cfea19bb31c73bc2 | 2f71acd47b352909ca2c978ad472a082ee79857c | /src/abc173/b.cpp | fd24e7b124e982389ebc2c88548697ed09269b51 | [] | no_license | imoted/atCoder | 0706c8b188a0ce72c0be839a35f96695618d0111 | 40864bca57eba640b1e9bd7df439d56389643100 | refs/heads/master | 2022-05-24T20:54:14.658853 | 2022-03-05T08:23:49 | 2022-03-05T08:23:49 | 219,258,307 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,566 | cpp | #include <bits/stdc++.h>
using namespace std;
// input
#define INIT std::ios::sync_with_stdio(false);std::cin.tie(0);
#define VAR(type, ...)type __VA_ARGS__;MACRO_VAR_Scan(__VA_ARGS__); // __VA_ARGS__可変引数マクロ
template<typename T> void MACRO_VAR_Scan(T& t) { std::cin >> t; }
template<typename First, typename...Rest>void MACRO_VAR_Scan(First& first, Rest& ...rest) { std::cin >> first; MACRO_VAR_Scan(rest...); }
#define VEC_ROW(type, n, ...)std::vector<type> __VA_ARGS__;MACRO_VEC_ROW_Init(n, __VA_ARGS__); for(int w_=0; w_<n; ++w_){MACRO_VEC_ROW_Scan(w_, __VA_ARGS__);}
template<typename T> void MACRO_VEC_ROW_Init(int n, T& t) { t.resize(n); }
template<typename First, typename...Rest>void MACRO_VEC_ROW_Init(int n, First& first, Rest& ...rest) { first.resize(n); MACRO_VEC_ROW_Init(n, rest...); }
template<typename T> void MACRO_VEC_ROW_Scan(int p, T& t) { std::cin >> t[p]; }
template<typename First, typename...Rest>void MACRO_VEC_ROW_Scan(int p, First& first, Rest& ...rest) { std::cin >> first[p]; MACRO_VEC_ROW_Scan(p, rest...); }
#define VEC(type, c, n) std::vector<type> c(n);for(auto& i:c)std::cin>>i;
#define MAT(type, c, m, n) std::vector<std::vector<type>> c(m, std::vector<type>(n));for(auto& R:c)for(auto& w:R)std::cin>>w;
// output
template<typename T>void MACRO_OUT(const T t) { std::cout << t; }
template<typename First, typename...Rest>void MACRO_OUT(const First first, const Rest...rest) { std::cout << first << " "; MACRO_OUT(rest...); }
#define OUT(...) MACRO_OUT(__VA_ARGS__);
#define FOUT(n, dist) std::cout<<std::fixed<<std::setprecision(n)<<(dist); // std::fixed 浮動小数点の書式 / setprecision 浮動小数点数を出力する精度を設定する。
#define SOUT(n, c, dist) std::cout<<std::setw(n)<<std::setfill(c)<<(dist);
#define EOUT(...) { OUT(__VA_ARGS__)BR; exit(0); }
#define SP std::cout<<" ";
#define TAB std::cout<<"\t";
#define BR std::cout<<"\n";
#define SPBR(w, n) std::cout<<(w + 1 == n ? '\n' : ' ');
#define ENDL std::cout<<std::endl;
#define FLUSH std::cout<<std::flush;
#define SHOW(dist) {std::cerr << #dist << "\t: " << (dist) << "\n";}
#define SHOWVECTOR(v) {std::cerr << #v << "\t: ";for(const auto& xxx : v){std::cerr << xxx << " ";}std::cerr << "\n";}
#define SHOWVECTOR2(v) {std::cerr << #v << "\t:\n";for(const auto& xxx : v){for(const auto& yyy : xxx){std::cerr << yyy << " ";}std::cerr << "\n";}}
#define SHOWQUEUE(a) {auto tmp(a);std::cerr << #a << "\t: ";while(!tmp.empty()){std::cerr << tmp.front() << " ";tmp.pop();}std::cerr << "\n";}
#define SHOWSTACK(a) {auto tmp(a);std::cerr << #a << "\t: ";while(!tmp.empty()){std::cerr << tmp.top() << " ";tmp.pop();}std::cerr << "\n";}
#define cYES cout<<"YES"<<endl
#define cNO cout<<"NO"<<endl
#define cYes cout<<"Yes"<<endl
#define cNo cout<<"No"<<endl
// utility
#define ALL(a) (a).begin(),(a).end()
#define FOR(w, a, n) for(int w=(a);w<(n);++w)
#define RFOR(w, a, n) for(int w=(n)-1;w>=(a);--w)
#define REP(w, n) for(int w=0;w<int(n);++w)
#define RREP(w, n) for(int w=int(n)-1;w>=0;--w)
#define IN(a, x, b) (a<=x && x<b)
template<class T> inline T CHMAX(T & a, const T b) { return a = (a < b) ? b : a; }
template<class T> inline T CHMIN(T& a, const T b) { return a = (a > b) ? b : a; }
#define PB push_back // 配列の最後にappendする
#define MP make_pair
#define FI first
#define SE second
// test
template<class T> using V = std::vector<T>;
template<class T> using VV = V<V<T>>;
// type/const
// #define int ll
using ll = long long;
using ull = unsigned long long;
using ld = long double;
using PAIR = std::pair<int, int>;
using PAIRLL = std::pair<ll, ll>;
constexpr int INFINT = (1 << 30) - 1; // 1.07x10^ 9
constexpr int INFINT_LIM = (1LL << 31) - 1; // 2.15x10^ 9
constexpr ll INFLL = 1LL << 60; // 1.15x10^18
constexpr ll INFLL_LIM = (1LL << 62) - 1 + (1LL << 62); // 9.22x10^18
constexpr double eps = 1e-7;
constexpr int MOD = 1000000007;
constexpr double PI = 3.141592653589793238462643383279;
template<class T, size_t N> void FILL(T(&a)[N], const T & val) { for (auto& x : a) x = val; }
template<class ARY, size_t N, size_t M, class T> void FILL(ARY(&a)[N][M], const T & val) { for (auto& b : a) FILL(b, val); }
template<class T> void FILL(std::vector<T> & a, const T & val) { for (auto& x : a) x = val; }
template<class ARY, class T> void FILL(std::vector<std::vector<ARY>> & a, const T & val) { for (auto& b : a) FILL(b, val); }
// ------------>8------------------------------------->8------------
int main() {
INIT;
VAR(int,n)
VEC(string,s,n)
int ac =0;
int wa =0;
int tle =0;
int re =0;
REP(i,n){
if(s[i] == "AC")
ac++;
else if(s[i] == "WA")
wa++;
else if(s[i] == "TLE")
tle++;
else
re++;
}
OUT("AC x ") OUT(ac) BR;
OUT("WA x ") OUT(wa) BR;
OUT("TLE x ") OUT(tle) BR;
OUT("RE x ") OUT(re) BR;
return 0;
}
////////////////////////// 数値、Vectorなど配列に適用 ///////////////////////////
// vector<int> a{1,2,3,4,5};
// vector<int> b(n, -1); // nは配列大きさ、 -1は初期値
// cout << a.size()<< '\n'; //aの大きさ
// cout << a[3]<< '\n'; //i番目の要素にアクセス
// cout << a.front()<< '\n'; //先頭を参照
// cout << a.back()<< '\n'; //末尾を参照
// a.push_back(10); //末尾に要素を追加
// a.pop_back(); //末尾の要素を削除
// listに対するfor文 書き方
// n = {{0,1,2},{3,4,5}}
// for(int i : n[0]){
// OUT(i)
// }
// 出力は 0,1,2
//"a" を b回繰り返すstringで初期化
// std::string s(b, "a");
// 3項演算子
// (n == m ? cYES : cNO)
// 配列の重複削除に使うset 配列 insertとかで配列を作り変える?
// std::set<int> st{3, 1, 4, 1};
// set は重複を許さない順序付集合なので、上記のように重複データがある場合は、重複データは自動的に削除され、{1, 3, 4} だけが格納される。
// CHMAX(a,b) a,bを比較して、でかい方をaに代入する
// 数値型への変換
// string s = "1";
// int a = s[0]-'0';
// charから数値への変換
// std::stoi() int
// std::stol() long
// std::stoll() long long
// std::stof() float
// std::stod() double
// std::stold() long double
// 2つの変数をスワップ
// int a = 1;
// int b = 2;
// swap(a, b); // a = 2, b = 1 // 戻り値は特になし
// 配列から配列を検索
// vector<ll> v = { 1, 2, 3, 4, 5 };
// vector<ll> w = { 3,4 };
// cout << *search(v.begin(), v.end(), w.begin(), w.end()); // v.begin() + 2
// 配列から 要素を検索
// vector<int> v = { 1, 2, 3, 4, 5 };
// vector<int>::iterator itr_b = find(v.begin(), v.end(), 3); // v.begin() + 2
// cout << *itr_b;
// vector<int>::iterator itr_e = find(v.begin(), v.end(), 7); // v.end()
// cout << *itr_e;
// 同等かどうか、を判定 boolを返す
// vector<ll> v = { 1, 2, 3 };a
// vector<ll> w = { 1, 2, 3 };
// cout << equal(v.begin(), v.end(), w.begin()); // true
// w[0] = 2;
// cout << equal(v.begin(), v.end(), w.begin()); // false
// 配列の中から数を数える //遅い O(N)
// vector<ll> v = { 1, 2, 1, 3, 2 };
// cout << count(v.begin(), v.end(), 1); // 2
// 配列で、配列内のそれぞれの要素のヒストグラムをmap 連想配列で作る
// REP(x,n) cnt[a[x]]++;
// 配列の要素を入れ替える
// V<ll> v = { 1, 2, 3, 2, 1 };
// replace(v.begin(), v.end(), 2, 4); // v = { 1, 4, 3, 4, 1 }
// 配列から要素を消す removeだけでは、ゴミがついてくるので、eraseを行う。
// V<ll> v = { 1, 2, 3, 2, 1 };
// V<ll> w = { 1, 2, 3, 2, 1 };
// remove(v.begin(), v.end(), 2); // v = { 1, 3, 1, ? , ? }
// remove(w.begin(), w.end(), 2), w.end(); // w = { 1,3,1}
// w.erase(remove(w.begin(), w.end(), 2), w.end()); // w = { 1,3,1}
// 連続した同じ値を消す。removeと同様新しい末尾位置を示すイテレータが返ってくる。
// 重複を無視して数え上げるときに、多くの場合setを使うよりもvectorにpush_backしていき、sortしてuniqueしたほうが速い(g++で確認)。
// V<ll> v = { 1, 1, 2, 2, 3, 3 };
// v.erase(unique(v.begin(), v.end()), v.end()); // v = { 1, 2, 3 }
// めちゃ遅い 要注意
// 逆順に並べ替える。
// 単純に逆にしたい時はもちろん、シーケンスを逆にたどるときにreverseをしておくとインデキシングが楽になるのでたまに使う。
// V<ll> v = { 1, 2, 3, 4, 5 };
// reverse(v.begin(), v.end()); // v = { 5, 4, 3, 2, 1 }
// シーケンスをシフトする。引数がなかなか難しいが、第2引数は操作後に新しく先頭になっている要素のイテレータ。
// V<ll> v = { 1, 2, 3, 4, 5 };
// rotate(v.begin(), v.begin() + 2, v.end()); // v = { 3, 4, 5, 1,2 }
// ランダムにシャッフルする。
// 乱択したい時や、特定の順番の入力に対して弱いアルゴリズムを使う時に入力をシャッフルしておくなどの使い方がある。
// V<ll> v = { 1, 2, 3, 4, 5 };
// random_shuffle(v.begin(), v.end()); // v = { 3, 5, 2, 4, 1 } (例えばこうなる)
// sort / 逆順ソートも
// V<ll> v = { 3, 5, 2, 4, 1 };
// V<ll> w = { 3, 5, 2, 4, 1 };
// sort(v.begin(), v.end()); // v = { 1, 2, 3, 4, 5 }
// sort(w.rbegin(), w.rend()); // w = { 5, 4, 3, 2, 1 } (greaterを使うより楽!)
// ソート済みのシーケンスに対して、ある値を入れるときに、最も早い/遅い位置の直後のイテレータを返す。
// 勝手に二分探索してくれるので便利。
// V<ll> v = { 1, 2, 2, 3, 3 };
// cout << *lower_bound(v.begin(), v.end(), 2); // v.begin() + 1
// cout << *upper_bound(v.begin(), v.end(), 2); // v.begin() + 3
// ソート済みのシーケンスに対して、ある値が存在するかを調べる。
// 他の操作が必要ない場合はsetを使うことで簡単にかけるので使う頻度は少ないかもしれない。
// V<ll> v = { 1, 2, 2, 3, 3 };
// cout << binary_search(v.begin(), v.end(), 2); // true
// cout << binary_search(v.begin(), v.end(), 4); // false
// シーケンス中の最大値/最小値「のイテレータ」を返す。
// 単純に最大値/最小値が欲しい時のほか、そのインデックスまで分かるため、非常に便利。
// V<ll> v = { 3, 5, 2, 4, 1 };
// cout << *max_element(v.begin(), v.end()); // 5
// cout << max_element(v.begin(), v.end()) - v.begin(); // 1 (5のインデックス)
// 辞書順で次の/前のものに並び替える。返り値は、次の/前のものがない場合にfalse、それ以外はtrueになる。
// 自分で作るとかなりめんどくさいし、非常に便利。
// 全順列を試す場合、再帰するよりもだいたい速い(ただし、枝刈りは難しくなる)。
// 99%くらい以下のdo〜whileの形で使う。
// V<ll> v = { 1, 2, 3 };
// do{
// // v は ループごとに
// { 1, 2, 3 }
// { 1, 3, 2 }
// { 2, 1, 3 }
// { 2, 3, 1 }
// { 3, 1, 2 }
// { 3, 2, 1 }
// // になっている。
// dummy = 1;
// }while(next_permutation(v.begin(), v.end()));
// // ループ後は v = { 1, 2, 3 }
// // 組み合わせを全部試したいときにも使える
// // 3個中2個を選びたい場合は
// // w = { 0, 1, 1 } としておき以下のように出来る。
// do{
// // w[i] = 1 ならば i 番目のものを選んでいる状態
// // w[i] = 0 ならば i 番目のものは選んでいない状態
// dummy = 1;
// }while(next_permutation(w.begin(), w.end()));
// 総和を簡単に求められる。
// 初期値の型によって結果の型を決めることが出来るのが地味に便利。
// V<ll> v = { 1, 2, 3, 4, 5 };
// V<string> w = { "Competitive", "Programming", "Advent", "Calendar" };
// cout << accumulate(v.begin(), v.end(), 0); // 15、結果はint
// cout << accumulate(v.begin(), v.end(), 0ll); // 15、結果はlong long
// cout << accumulate(v.begin(), v.end(), 1, multiplies<int>()); // 120、結果はint
// cout << accumulate(w.begin(), w.end(), string()); // "CompetitiveProgrammingAdventCalendar"
// 途中までの和を全部求められる
// この結果を利用してO(1)で部分和を求めることが出来ることなどから利用する場面がありそう
// V<ll> v = { 1, 2, 3, 4, 5 };
// V<ll> w = { 1, 2, 3, 4, 5 };
// // w.size() >= 5 じゃないとダメ
// partial_sum(v.begin(), v.end(), w.begin()); // w = { 1, 3, 6, 10, 15 }
// partial_sum(v.begin(), v.end(), v.begin()); // vに上書きもできる v
// nCkのコンビネーションの一覧を出してくれる 関数
// vのvectorに、kを変えた時の一覧が配列で出力される。
// void comb(vector<vector<ull> > &v){
// for(int i = 0;i <v.size(); i++){
// v[i][0]=1;
// v[i][i]=1;
// }
// for(int k = 1;k <v.size();k++){
// for(int j = 1;j<k;j++){
// v[k][j]=(v[k-1][j-1]+v[k-1][j]);
// }
// }
// }
// vector<vector<ull> > v(n+1,vector<ull>(n+1,0));
// comb(v);
// map配列 map へのアクセス(countなどのSTL)は、vectorなどに比べてOlogN の計算量で早い。
// map<int, int> cnt;
// for (int x : A) {
// if (cnt.count(x)) {
// cnt[x]++;
// }
// }
// 1 << (h-1) 2 の h乗の表現
// mint combination(ull s, ull r) {
// if ( r * 2 > s ) r = s - r;
// mint dividend = 1;
// mint divisor = 1;
// for ( ull i = 1; i <= r; ++i ) {
// dividend *= (s-i+1);
// divisor *= i;
// }
// return dividend / divisor;
// }
// pairの定義方法
// PAIR ans(9999,-1);
// OUT(ans.first);
// pair同士の比較 第一引数がまず比較される。
// PAIR ans = min(PAIR(3,4),PAIR(2,3));
// OUT(ans.second)
//////////////////////////////// 文字列に対して適用 //////////////////////////
// s = s + t; //連結
// s == t; //比較
// s.length(); //長さ
// cout << s[0] << '\n'; //i番目の文字を参照
// cout << s.substr(0, 5)<< '\n'; //i番目以降k文字を抽出して得られる文字列
// cout << s.find("abc")<< '\n'; //sの中に文字列tがあればその先頭のアドレスを返す.なければs.nopsを返却
// if (UPos != std::string::npos) { ans_s = A -1; }
// cout << s.replace(0, 3, "zxc")<< '\n'; //i番目以降k文字を文字列tで置換する.tを空文字列にすれば削除の動作
// めちゃ遅い 要注意
// cout << s.insert(5, "ins")<< '\n'; //i番目の文字の前に文字列tを挿入
// 文字列の辞書順比較
// str <= str2 str > str2
// min() max() でもOK
// 数値 → 文字列への変換
// auto s = std::to_string(i);
// 数値から、文字列に変換、上位の数字と、下位の数字をペアにして、数値に戻す。
// auto s = std::to_string(i);
// ++map[PAIR(s.front() - '0', s.back() - '0')];
// めちゃ遅い 要注意
// 文字列を逆に並べる 引数はイテレータ
//reverse(s.begin() ,s.end());
// 連想配列
// map<string, int> score;
// score["Alice"] = 100;
// score["Dave"] = 95;
// score["Bob"] = 89;
// cout << score["Alice"];
// 「"」で囲われた文字列は、文字列が格納されたメモリのアドレスを意味します。
// string s = 'AAA'; // NG 文字の実態を表している
// string t = "AAA"; // OK 文字列のアドレスを表している
// char c = 'A'; // OK 文字の実態を表している
// char d = *"A"; // OK
// char e = "A" // NG 文字列のアドレスを表している
| [
"tad.imokawa@gmail.com"
] | tad.imokawa@gmail.com |
3bd2aff9409d8ccee38f262084840d2191dc4194 | 5ddd0ec20099a9c3ffe865c835dcceb5b7fd0332 | /of_v0.8.0_vs_release-gesture-recognizer/examples/events/eventsExample/src/testApp.cpp | 9c9dd7693f8a949d80e5e85d56705ea387157405 | [
"MIT"
] | permissive | MarkusKonk/Geographic-Interaction | af81f9f4c7c201dd55843d4dd0d369f2f407d480 | b74f6f04656611df8dc4ebdea43f263cea67b366 | refs/heads/master | 2020-12-30T10:36:34.414880 | 2014-02-03T12:37:45 | 2014-02-03T12:37:45 | 13,868,029 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,340 | cpp | #include "testApp.h"
//--------------------------------------------------------------
void testApp::setup(){
counter = 0;
vagRounded.loadFont("vag.ttf", 32);
ofBackground(50,50,50);
}
//--------------------------------------------------------------
void testApp::update(){
counter = counter + 0.033f;
}
//--------------------------------------------------------------
void testApp::draw(){
sprintf (timeString, "time: %i:%i:%i \nelapsed time %lli", ofGetHours(), ofGetMinutes(), ofGetSeconds(), ofGetElapsedTimeMillis());
float w = vagRounded.stringWidth(eventString);
float h = vagRounded.stringHeight(eventString);
ofSetHexColor(0xffffff);
vagRounded.drawString(eventString, 98,198);
ofSetColor(255,122,220);
vagRounded.drawString(eventString, 100,200);
ofSetHexColor(0xffffff);
vagRounded.drawString(timeString, 98,98);
ofSetColor(255,122,220);
vagRounded.drawString(timeString, 100,100);
}
//--------------------------------------------------------------
void testApp::keyPressed (int key){
if(key & OF_KEY_MODIFIER){
if(key >= OF_KEY_F1 && key <= OF_KEY_F12){
sprintf(eventString, "keyPressed = (%i) %s", key, ("F" + ofToString(key+1-OF_KEY_F1)).c_str());
}else{
switch(key){
case OF_KEY_LEFT:
sprintf(eventString, "keyPressed = (%i) %s", key, "LEFT");
break;
case OF_KEY_UP:
sprintf(eventString, "keyPressed = (%i) %s", key, "UP");
break;
case OF_KEY_RIGHT:
sprintf(eventString, "keyPressed = (%i) %s", key, "RIGHT");
break;
case OF_KEY_DOWN:
sprintf(eventString, "keyPressed = (%i) %s", key, "DOWN");
break;
case OF_KEY_PAGE_UP:
sprintf(eventString, "keyPressed = (%i) %s", key, "PAGE UP");
break;
case OF_KEY_PAGE_DOWN:
sprintf(eventString, "keyPressed = (%i) %s", key, "PAGE DOWN");
break;
case OF_KEY_HOME:
sprintf(eventString, "keyPressed = (%i) %s", key, "HOME");
break;
case OF_KEY_END:
sprintf(eventString, "keyPressed = (%i) %s", key, "END");
break;
case OF_KEY_INSERT:
sprintf(eventString, "keyPressed = (%i) %s", key, "INSERT");
break;
case OF_KEY_LEFT_SHIFT:
sprintf(eventString, "keyPressed = (%i) %s", key, "LEFT SHIFT");
break;
case OF_KEY_LEFT_CONTROL:
sprintf(eventString, "keyPressed = (%i) %s", key, "LEFT CONTROL");
break;
case OF_KEY_LEFT_SUPER:
sprintf(eventString, "keyPressed = (%i) %s", key, "LEFT SUPER");
break;
case OF_KEY_RIGHT_SHIFT:
sprintf(eventString, "keyPressed = (%i) %s", key, "RIGHT SHIFT");
break;
case OF_KEY_RIGHT_CONTROL:
sprintf(eventString, "keyPressed = (%i) %s", key, "RIGHT CONTROL");
break;
case OF_KEY_RIGHT_ALT:
sprintf(eventString, "keyPressed = (%i) %s", key, "RIGHT ALT");
break;
case OF_KEY_RIGHT_SUPER:
sprintf(eventString, "keyPressed = (%i) %s", key, "RIGHT SUPER");
break;
}
}
}else{
sprintf(eventString, "keyPressed = (%i) %c", key, (char)key);
}
}
//--------------------------------------------------------------
void testApp::keyReleased(int key){
if(key & OF_KEY_MODIFIER){
if(key >= OF_KEY_F1 && key <= OF_KEY_F12){
sprintf(eventString, "keyReleased = (%i) %s", key, ("F" + ofToString(key+1-OF_KEY_F1)).c_str());
}else{
switch(key){
case OF_KEY_LEFT:
sprintf(eventString, "keyReleased = (%i) %s", key, "LEFT");
break;
case OF_KEY_UP:
sprintf(eventString, "keyReleased = (%i) %s", key, "UP");
break;
case OF_KEY_RIGHT:
sprintf(eventString, "keyReleased = (%i) %s", key, "RIGHT");
break;
case OF_KEY_DOWN:
sprintf(eventString, "keyReleased = (%i) %s", key, "DOWN");
break;
case OF_KEY_PAGE_UP:
sprintf(eventString, "keyReleased = (%i) %s", key, "PAGE UP");
break;
case OF_KEY_PAGE_DOWN:
sprintf(eventString, "keyReleased = (%i) %s", key, "PAGE DOWN");
break;
case OF_KEY_HOME:
sprintf(eventString, "keyReleased = (%i) %s", key, "HOME");
break;
case OF_KEY_END:
sprintf(eventString, "keyReleased = (%i) %s", key, "END");
break;
case OF_KEY_INSERT:
sprintf(eventString, "keyReleased = (%i) %s", key, "INSERT");
break;
case OF_KEY_LEFT_SHIFT:
sprintf(eventString, "keyReleased = (%i) %s", key, "LEFT SHIFT");
break;
case OF_KEY_LEFT_CONTROL:
sprintf(eventString, "keyReleased = (%i) %s", key, "LEFT CONTROL");
break;
case OF_KEY_LEFT_SUPER:
sprintf(eventString, "keyReleased = (%i) %s", key, "LEFT SUPER");
break;
case OF_KEY_RIGHT_SHIFT:
sprintf(eventString, "keyReleased = (%i) %s", key, "RIGHT SHIFT");
break;
case OF_KEY_RIGHT_CONTROL:
sprintf(eventString, "keyReleased = (%i) %s", key, "RIGHT CONTROL");
break;
case OF_KEY_RIGHT_ALT:
sprintf(eventString, "keyReleased = (%i) %s", key, "RIGHT ALT");
break;
case OF_KEY_RIGHT_SUPER:
sprintf(eventString, "keyReleased = (%i) %s", key, "RIGHT SUPER");
break;
}
}
}else{
sprintf(eventString, "keyReleased = (%i) %c", key, (char)key);
}
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
sprintf(eventString, "mouseMoved = (%i,%i)", x, y);
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
sprintf(eventString, "mouseDragged = (%i,%i - button %i)", x, y, button);
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
sprintf(eventString, "mousePressed = (%i,%i - button %i)", x, y, button);
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){
sprintf(eventString, "mouseReleased = (%i,%i - button %i)", x, y, button);
}
//--------------------------------------------------------------
void testApp::windowResized(int w, int h){
sprintf(eventString, "resized = (%i,%i)", w, h);
}
//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg){
sprintf(eventString, "gotMessage %s ", msg.message.c_str());
}
//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo){
sprintf(eventString, "%i files dragged into the window at (%i, %i)", (int)dragInfo.files.size(), (int)dragInfo.position.x, (int)dragInfo.position.y);
}
| [
"matthias.m.hinz@googlemail.com"
] | matthias.m.hinz@googlemail.com |
c0a3b262edf6cb5c27a0cf80537cc28b35042e30 | 30667f904bf553424e56364263e9923b5f42d74d | /PowerBook/Car.cpp | 02216472031c2f8e9f99729069ed3dd9197c7b1a | [] | no_license | bb2002/CPPStudyProjects | 037ae0a2b8a4f89a9725845989a1f00921b018cd | 2569dbb9e4a1c2acfbe67fcce20304b5094f79a3 | refs/heads/master | 2020-04-29T06:05:51.377024 | 2019-03-15T23:54:07 | 2019-03-15T23:54:07 | 175,904,985 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 458 | cpp | #include "pch.h"
#include <iostream>
#include <cstring>
#include "Car.h"
using namespace std;
void Car::InitMembers(const char *id, int fuel) {
strcpy(PlayerID, id);
FuelGauge = fuel;
CurrentSpeed = 0;
}
void Car::Accel()
{
if (FuelGauge <= 0) {
return;
}
else {
FuelGauge -= CarConst::FUEL_STEP;
}
if (CurrentSpeed + CarConst::FUEL_STEP >= CarConst::MAX_SPD) {
CurrentSpeed = CarConst::MAX_SPD;
}
CurrentSpeed += CarConst::ACC_STEP;
}
| [
"5252bb@daum.net"
] | 5252bb@daum.net |
41961cc1834777f89aab3ccaf8c6a8c386a864df | 54706dd82e31dbaddc4a88fdb26c0d9c1ce19230 | /Lizard.h | 9a98e0d0740b4dd03b73c4b8bbcc8be705ccbc34 | [] | no_license | MatanSofer/CPP-Zoo-Project | 074782391179e4167eda6ed4910c296d03e5cadb | 9cd5d2e912be7725352a6b6a4bebbe404557d1b1 | refs/heads/main | 2023-06-21T01:20:54.226999 | 2021-07-27T20:26:01 | 2021-07-27T20:26:01 | 390,117,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 327 | h | #pragma once
#include "Vertebrates.h"
#include "Animal.h"
#include "Reptiles.h"
class Lizard :public Reptiles
{
private:
int legsspeed;
public:
Lizard(char* name, bool sex, bool blood, bool legs, int legsspeed);
virtual void print()const;
~Lizard() {}
virtual const char* get_type()const;
};
| [
"noreply@github.com"
] | MatanSofer.noreply@github.com |
413b90b58da35954e4ea42562d7bad47495ef5e5 | c9b2a1b6cf254273cc4705f31916c4942fd6f47f | /Piscine_Cpp/d01/ex06/HumanA.cpp | 418630e146362fdb643199ed3289ef3a728c12a3 | [] | no_license | gbourgeo/42projects | cb4141026a2572c04a6e9820fe2d1a7319ac3225 | 3127c9e74ff8ec6d00be3f7d449f3469d56bdb86 | refs/heads/master | 2021-01-17T02:58:20.156155 | 2020-09-08T12:00:52 | 2020-09-08T12:00:52 | 58,766,253 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,145 | cpp | // ************************************************************************** //
// //
// ::: :::::::: //
// HumanA.cpp :+: :+: :+: //
// +:+ +:+ +:+ //
// By: root </var/mail/root> +#+ +:+ +#+ //
// +#+#+#+#+#+ +#+ //
// Created: 2018/06/29 17:51:31 by root #+# #+# //
// Updated: 2018/06/29 18:06:55 by root ### ########.fr //
// //
// ************************************************************************** //
#include <iostream>
#include "HumanA.hpp"
HumanA::HumanA(std::string name, Weapon & weapon): _weapon(weapon), _name(name)
{}
HumanA::~HumanA()
{}
void HumanA::attack()
{
std::cout << _name << " attack with his " << _weapon.getType() << std::endl;
}
| [
"gillesbourgeois@gmail.com"
] | gillesbourgeois@gmail.com |
de9a422b63cb7b6fe69dd34facf70fd7556e89e4 | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /third_party/WebKit/Source/modules/geolocation/GeolocationWatchers.cpp | b66558c6b204e87ed5a78c67322593a8ddbb550e | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 2,206 | cpp | // 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.
#include "modules/geolocation/GeolocationWatchers.h"
#include "modules/geolocation/GeoNotifier.h"
#include "platform/wtf/Assertions.h"
namespace blink {
DEFINE_TRACE(GeolocationWatchers) {
visitor->Trace(id_to_notifier_map_);
visitor->Trace(notifier_to_id_map_);
}
DEFINE_TRACE_WRAPPERS(GeolocationWatchers) {
for (const auto& notifier : id_to_notifier_map_.Values())
visitor->TraceWrappers(notifier);
// |notifier_to_id_map_| is a HeapHashMap that is the inverse mapping of
// |id_to_notifier_map_|. As the contents are the same, we don't need to
// trace |id_to_notifier_map_|.
}
bool GeolocationWatchers::Add(int id, GeoNotifier* notifier) {
DCHECK_GT(id, 0);
if (!id_to_notifier_map_.insert(id, notifier).is_new_entry)
return false;
notifier_to_id_map_.Set(notifier, id);
return true;
}
GeoNotifier* GeolocationWatchers::Find(int id) {
DCHECK_GT(id, 0);
IdToNotifierMap::iterator iter = id_to_notifier_map_.find(id);
if (iter == id_to_notifier_map_.end())
return 0;
return iter->value;
}
void GeolocationWatchers::Remove(int id) {
DCHECK_GT(id, 0);
IdToNotifierMap::iterator iter = id_to_notifier_map_.find(id);
if (iter == id_to_notifier_map_.end())
return;
notifier_to_id_map_.erase(iter->value);
id_to_notifier_map_.erase(iter);
}
void GeolocationWatchers::Remove(GeoNotifier* notifier) {
NotifierToIdMap::iterator iter = notifier_to_id_map_.find(notifier);
if (iter == notifier_to_id_map_.end())
return;
id_to_notifier_map_.erase(iter->value);
notifier_to_id_map_.erase(iter);
}
bool GeolocationWatchers::Contains(GeoNotifier* notifier) const {
return notifier_to_id_map_.Contains(notifier);
}
void GeolocationWatchers::Clear() {
id_to_notifier_map_.clear();
notifier_to_id_map_.clear();
}
bool GeolocationWatchers::IsEmpty() const {
return id_to_notifier_map_.IsEmpty();
}
void GeolocationWatchers::GetNotifiersVector(
HeapVector<Member<GeoNotifier>>& copy) const {
CopyValuesToVector(id_to_notifier_map_, copy);
}
} // namespace blink
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
1f63ba23ce9a8ad91ef36d5333683b0904667dcc | 09b54c3664807a96d864795cf29995c41ad2e3ab | /MQ2PyExt_DataWrapper.cpp | 776eb70597b0117d88b238decd837f8a3d7d6606 | [] | no_license | rlane187/MQ2Py | a6bb124ab4d4075bee908b9ba5158e3bedd2cc51 | e0430a39c06f8f15de66151e411e503d5968a79f | refs/heads/master | 2021-01-18T21:56:36.822901 | 2017-04-03T19:01:35 | 2017-04-03T19:01:35 | 87,030,859 | 0 | 0 | null | 2017-04-03T02:12:48 | 2017-04-03T02:12:48 | null | UTF-8 | C++ | false | false | 6,002 | cpp | /* MQ2PyExt_DataWrapper.cpp
* Copyright (c) 2009 Stephen Raub.
*
* Distribution is not allowed without the consent of the author.
*
* This module implements the MQ2 Data API Wrapper class library
*/
#include "MQ2PyPCH.h"
#include "MQ2Py.h"
#include "MQ2PyExt.h"
#include "MQ2PyExt_DataWrapper.h"
using namespace boost;
using namespace boost::python;
//----------------------------------------------------------------------------
python::object MQ2TypeToPythonType(const MQ2TYPEVAR& value)
{
/* Select return type based on result */
if (value.Type == pIntType)
return python::object(value.Int);
else if (value.Type == pFloatType)
return python::object(value.Float);
else if (value.Type == pBoolType)
return python::object((bool)value.DWord);
else if (value.Type == pStringType)
return python::str((const char*)value.Ptr);
else {
/* Unknown datatype. Return the python-wrapper of that
* datatype. */
MQ2Type* type = value.Type;
return python::object(DataTypeWrapper(type, value));
}
return python::object();
}
//----------------------------------------------------------------------------
DataMemberWrapper::DataMemberWrapper(MQ2Type* t, std::string n, const MQ2TYPEVAR& v)
{
type = t;
member = n;
value = v;
if (type == NULL) {
PyErr_SetString(PyExc_AssertionError, "Invalid Type");
throw_error_already_set();
}
}
std::string DataMemberWrapper::__repr__()
{
ostringstream oss;
oss << "<MQ2Type: " << type->GetName() << ", Member: " << member << ">";
return oss.str();
}
python::object DataMemberWrapper::__getattr__(std::string attr)
{
MQ2TYPEVAR newValue;
memcpy(&newValue, &value, sizeof(value));
type->GetMember(value.VarPtr, (PCHAR)member.c_str(), "", newValue);
return python::object(DataMemberWrapper(newValue.Type, attr, newValue));
}
python::object DataMemberWrapper::__call_str__(std::string args)
{
MQ2TYPEVAR newValue;
memcpy(&newValue, &value, sizeof(value));
type->GetMember(value.VarPtr, (PCHAR)member.c_str(), (PCHAR)args.c_str(), newValue);
return MQ2TypeToPythonType(newValue);
}
python::object DataMemberWrapper::__call_int__(int arg)
{
ostringstream oss;
oss << arg;
return __call_str__(oss.str());
}
python::object DataMemberWrapper::__call__()
{
return __call_str__("");
}
//----------------------------------------------------------------------------
DataTypeWrapper::DataTypeWrapper(MQ2Type* t, const MQ2TYPEVAR& v)
{
if (t == NULL) {
PyErr_SetString(PyExc_AssertionError, "Type is Invalid");
throw_error_already_set();
}
type = t;
value = v;
}
std::string DataTypeWrapper::Name()
{
return type->GetName();
}
std::string DataTypeWrapper::__repr__()
{
ostringstream oss;
oss << "<MQ2Type: " << type->GetName() << ">";
return oss.str();
}
std::string DataTypeWrapper::GetMemberName(int index)
{
PCHAR result = type->GetMemberName(index);
if (result == NULL) {
PyErr_SetString(PyExc_IndexError, "Index is out of range");
throw_error_already_set();
}
return result;
}
python::object DataTypeWrapper::__getattr__(std::string name)
{
if (!type->FindMember((PCHAR)name.c_str()) && !type->InheritedMember((PCHAR)name.c_str())) {
PyErr_SetString(PyExc_AttributeError, name.c_str());
throw_error_already_set();
}
return python::object(DataMemberWrapper(type, name, value));
}
//----------------------------------------------------------------------------
namespace boost { namespace python
{
template <>
struct has_back_reference<TLOWrapper>
: mpl::true_
{};
}}
TLOWrapper::TLOWrapper(PyObject* _self, std::string _name)
{
PMQ2DATAITEM item = FindMQ2Data((PCHAR)_name.c_str());
if (item == NULL) {
PyErr_SetString(PyExc_AssertionError, "Invalid Data Name");
throw_error_already_set();
}
name = item->Name;
function = item->Function;
self = _self;
}
TLOWrapper::TLOWrapper(PyObject* _self, const TLOWrapper& other)
{
self = _self;
function = other.function;
name = other.name;
}
std::string TLOWrapper::__repr__()
{
ostringstream oss;
oss << "<TopLevelObject: " << name << ">";
return oss.str();
}
python::object TLOWrapper::__call_str__(std::string args)
{
MQ2TYPEVAR value;
memset(&value, 0, sizeof(value));
BOOL result = function((PCHAR)args.c_str(), value);
/* If no result, return None */
if (result == FALSE)
return python::object();
return MQ2TypeToPythonType(value);
}
python::object TLOWrapper::__call_int__(int value)
{
ostringstream oss;
oss << value;
return __call_str__(oss.str());
}
python::object TLOWrapper::__call__()
{
return __call_str__("");
}
python::object TLOWrapper::__getattr__(std::string name)
{
/* this is a combination of __call__ and DataTypeWrapper::__getattr__ */
MQ2TYPEVAR value;
memset(&value, 0, sizeof(value));
BOOL result = function("", value);
/* If no result, return None */
if (result == FALSE)
return python::object();
return DataTypeWrapper(value.Type, value).__getattr__(name);
}
//----------------------------------------------------------------------------
void Init_Module_PyMQ2_DataWrapper()
{
class_<DataMemberWrapper>("DataTypeMember", no_init)
.def("__repr__", &DataMemberWrapper::__repr__)
.def("__getattr__", &DataMemberWrapper::__getattr__)
.def("__call__", &DataMemberWrapper::__call__)
.def("__call__", &DataMemberWrapper::__call_str__)
.def("__call__", &DataMemberWrapper::__call_int__)
;
class_<DataTypeWrapper>("DataType", no_init)
.def("GetName", &DataTypeWrapper::Name)
.def("GetMemberName", &DataTypeWrapper::GetMemberName)
.def("__repr__", &DataTypeWrapper::__repr__)
.def("__getattr__", &DataTypeWrapper::__getattr__)
;
class_<TLOWrapper>("TopLevelObject", no_init)
.def(init<std::string>())
.def("__repr__", &TLOWrapper::__repr__)
.def("__call__", &TLOWrapper::__call__)
.def("__call__", &TLOWrapper::__call_str__)
.def("__call__", &TLOWrapper::__call_int__)
.def("__getitem__", &TLOWrapper::__call_str__)
.def("__getitem__", &TLOWrapper::__call_int__)
.def("__getattr__", &TLOWrapper::__getattr__)
;
}
| [
"brainiac2k@gmail.com"
] | brainiac2k@gmail.com |
a18c8dd8b412b53ac1d9de894b5c3b243dde2583 | eeedc65ef99590d8316963717d1012cc6c90c9c5 | /src/privatesend/privatesend-util.h | ba843f06c5d1cb32050a65b89d4886fc88960b3e | [
"MIT"
] | permissive | BayerTM/DraftCoinZ | e277353042c908373738bce65716c38ab0cbc0ff | 217db2822a320d278d93dda4d3cd5dc4d01764f2 | refs/heads/main | 2023-06-01T00:54:12.511923 | 2021-06-09T21:35:24 | 2021-06-09T21:35:24 | 362,256,925 | 0 | 0 | MIT | 2021-04-27T22:23:49 | 2021-04-27T21:33:59 | null | UTF-8 | C++ | false | false | 831 | h | // Copyright (c) 2014-2019 The DFTz Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef PRIVATESENDUTIL_H
#define PRIVATESENDUTIL_H
#include "wallet/wallet.h"
class CKeyHolder
{
private:
CReserveKey reserveKey;
CPubKey pubKey;
public:
CKeyHolder(CWallet* pwalletIn);
CKeyHolder(CKeyHolder&&) = delete;
CKeyHolder& operator=(CKeyHolder&&) = delete;
void KeepKey();
void ReturnKey();
CScript GetScriptForDestination() const;
};
class CKeyHolderStorage
{
private:
std::vector<std::unique_ptr<CKeyHolder> > storage;
mutable CCriticalSection cs_storage;
public:
CScript AddKey(CWallet* pwalletIn);
void KeepAll();
void ReturnAll();
};
#endif //PRIVATESENDUTIL_H
| [
"james@xmc.com"
] | james@xmc.com |
43785d74a85c8672bfa745b23dc40dad8b746e8a | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/windows/advcore/gdiplus/test/comtest/comtest.cpp | e3df685c393f1f335d6ab110a70fe18fc2cded1a | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 1,647 | cpp | #include "precomp.hpp"
#include "comtest.h"
#include "ComBase.hpp"
#include "HelloWorld.hpp"
#include <initguid.h>
#include "comtest_i.c"
HINSTANCE globalInstanceHandle = NULL;
LONG globalComponentCount = 0;
//
// DLL entrypoint
//
extern "C" BOOL WINAPI
DllMain(
HINSTANCE hInstance,
DWORD dwReason,
VOID* lpReserved
)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
DisableThreadLibraryCalls(hInstance);
globalInstanceHandle = hInstance;
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
//
// Determine whether the DLL can be safely unloaded
//
STDAPI
DllCanUnloadNow()
{
return (globalComponentCount == 0) ? S_OK : S_FALSE;
}
//
// Return a class factory object
//
STDAPI
DllGetClassObject(
REFCLSID rclsid,
REFIID riid,
VOID** ppv
)
{
if (rclsid != CLSID_HelloWorld)
return CLASS_E_CLASSNOTAVAILABLE;
CHelloWorldFactory* factory = new CHelloWorldFactory();
if (factory == NULL)
return E_OUTOFMEMORY;
HRESULT hr = factory->QueryInterface(riid, ppv);
factory->Release();
return hr;
}
//
// Register our component
//
static const ComponentRegData compRegData =
{
&CLSID_HelloWorld,
L"Skeleton COM Component",
L"comtest.HelloWorld.1",
L"comtest.HelloWorld"
};
STDAPI
DllRegisterServer()
{
return RegisterComponent(compRegData, TRUE);
}
//
// Unregister our component
//
STDAPI
DllUnregisterServer()
{
return RegisterComponent(compRegData, FALSE);
}
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
58fa052379f057f875735ffd300751c5df832a26 | 819875a388d7caf6795941db8104f4bf72677b90 | /ui/gfx/gl/.svn/text-base/gl_surface_android.cc.svn-base | fcb132ddd981291826857c381b439c7a590f69c2 | [
"BSD-3-Clause"
] | permissive | gx1997/chrome-loongson | 07b763eb1d0724bf0d2e0a3c2b0eb274e9a2fb4c | 1cb7e00e627422577e8b7085c2d2892eda8590ae | refs/heads/master | 2020-04-28T02:04:13.872019 | 2012-08-16T10:09:25 | 2012-08-16T10:09:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,655 | // 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.
#include "ui/gfx/gl/gl_surface_android.h"
#include <EGL/egl.h>
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "ui/gfx/gl/egl_util.h"
#include "ui/gfx/gl/gl_bindings.h"
#include "ui/gfx/gl/gl_context.h"
#include "ui/gfx/gl/gl_implementation.h"
#include "ui/gfx/gl/native_window_interface_android.h"
namespace gfx {
bool GLSurface::InitializeOneOffInternal() {
static bool initialized = false;
if (initialized)
return true;
switch (GetGLImplementation()) {
case kGLImplementationEGLGLES2:
if (!GLSurfaceEGL::InitializeOneOff()) {
LOG(ERROR) << "GLSurfaceEGL::InitializeOneOff failed.";
return false;
}
break;
default:
NOTREACHED();
break;
}
initialized = true;
return true;
}
// static
scoped_refptr<GLSurface>
GLSurface::CreateViewGLSurface(bool software, gfx::AcceleratedWidget window) {
if (software)
return NULL;
switch (GetGLImplementation()) {
case kGLImplementationEGLGLES2: {
// window is unused
scoped_refptr<AndroidViewSurface> surface(new AndroidViewSurface());
if (!surface->Initialize())
return NULL;
return surface;
}
default:
NOTREACHED();
return NULL;
}
}
// static
scoped_refptr<GLSurface>
GLSurface::CreateOffscreenGLSurface(bool software, const gfx::Size& size) {
if (software)
return NULL;
switch (GetGLImplementation()) {
case kGLImplementationEGLGLES2: {
scoped_refptr<PbufferGLSurfaceEGL> surface(
new PbufferGLSurfaceEGL(false, size));
if (!surface->Initialize())
return NULL;
return surface;
}
default:
NOTREACHED();
return NULL;
}
}
AndroidViewSurface::AndroidViewSurface()
: NativeViewGLSurfaceEGL(false, 0),
pbuffer_surface_(new PbufferGLSurfaceEGL(false, Size(1, 1))),
window_(NULL) {
}
AndroidViewSurface::~AndroidViewSurface() {
}
bool AndroidViewSurface::Initialize() {
DCHECK(pbuffer_surface_.get());
return pbuffer_surface_->Initialize();
}
void AndroidViewSurface::Destroy() {
if (pbuffer_surface_.get()) {
pbuffer_surface_->Destroy();
} else {
window_ = NULL;
}
NativeViewGLSurfaceEGL::Destroy();
}
bool AndroidViewSurface::IsOffscreen() {
return false;
}
bool AndroidViewSurface::SwapBuffers() {
if (!pbuffer_surface_.get())
return NativeViewGLSurfaceEGL::SwapBuffers();
return true;
}
gfx::Size AndroidViewSurface::GetSize() {
if (pbuffer_surface_.get())
return pbuffer_surface_->GetSize();
else
return NativeViewGLSurfaceEGL::GetSize();
}
EGLSurface AndroidViewSurface::GetHandle() {
if (pbuffer_surface_.get())
return pbuffer_surface_->GetHandle();
else
return NativeViewGLSurfaceEGL::GetHandle();
}
bool AndroidViewSurface::Resize(const gfx::Size& size) {
if (pbuffer_surface_.get())
return pbuffer_surface_->Resize(size);
else if (GetHandle()) {
DCHECK(window_ && window_->GetNativeHandle());
// Deactivate and restore any currently active context.
EGLContext context = eglGetCurrentContext();
if (context != EGL_NO_CONTEXT) {
eglMakeCurrent(GetDisplay(), EGL_NO_SURFACE, EGL_NO_SURFACE,
EGL_NO_CONTEXT);
}
NativeViewGLSurfaceEGL::Destroy();
if (CreateWindowSurface(window_)) {
if (context != EGL_NO_CONTEXT)
eglMakeCurrent(GetDisplay(), GetHandle(), GetHandle(), context);
}
}
return true;
}
bool AndroidViewSurface::CreateWindowSurface(NativeWindowInterface* window) {
DCHECK(window->GetNativeHandle());
window_ = window;
EGLSurface surface = eglCreateWindowSurface(GetDisplay(),
GetConfig(),
window->GetNativeHandle(),
NULL);
if (surface == EGL_NO_SURFACE) {
LOG(ERROR) << "eglCreateWindowSurface failed with error "
<< GetLastEGLErrorString();
Destroy();
return false;
}
SetHandle(surface);
return true;
}
void AndroidViewSurface::SetNativeWindow(NativeWindowInterface* window) {
if (window->GetNativeHandle()) {
DCHECK(pbuffer_surface_.get());
pbuffer_surface_->Destroy();
pbuffer_surface_ = NULL;
CreateWindowSurface(window);
} else {
DCHECK(GetHandle());
NativeViewGLSurfaceEGL::Destroy();
window_ = NULL;
pbuffer_surface_ = new PbufferGLSurfaceEGL(false, Size(1,1));
pbuffer_surface_->Initialize();
}
}
} // namespace gfx
| [
"loongson@Loong.(none)"
] | loongson@Loong.(none) | |
98ebc65259ad87f47d4c2988c2c2561fee1a305a | 5aa83fd4a74169c14e102d676e937fcdbd23dc64 | /TP3_fischmaa_geoffrog/src/Dvector.cpp | 353fbb833fcd01bdd1e615661ac8c42a7b0297e4 | [] | no_license | Fischmaa/ModelisationProgrammation | f061b7b8dc1e7e139725284e712b31b212451272 | a4edb83057c6f4801e68edabc19ee8d053c6fb0b | refs/heads/master | 2016-08-12T23:21:50.418119 | 2016-03-28T23:40:36 | 2016-03-28T23:40:36 | 51,293,699 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,914 | cpp | #include "Dvector.h"
#include <ctime>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cassert>
using namespace std;
Dvector::Dvector():Darray(){
};
Dvector::Dvector(int d, double val ):Darray(d,val){
};
Dvector::Dvector(const Darray & P):Darray(P){
};
Dvector::Dvector(const std::string& name):Darray(name){
};
Dvector::~Dvector(){
};
void Dvector::display( std::ostream& str) const
{
for (int i = 0; i < dim ; i++){
str << this->vect[i] << "\n" ;
}
}
void Dvector::fillRandomly() {
static bool init = false;
if (!init) {
init = true;
srand(time(NULL)); // Initialisation pour rand
}
// Generateur de nombre aleatoire
for (int i = 0; i < dim; i++) {
vect[i] = rand() / (double) RAND_MAX; // Loi Uniforme entre 0 et 1
}
}
bool Dvector::operator==(const Dvector& elem) const{
if(this->size()!=elem.size()){
return false;
}
else{
for(int i = 0 ; i< this->size();i++){
if(this->vect[i] != elem.vect[i]){
return false;
}
}
return true;;
}
}
bool Dvector::operator!=(const Dvector& elem) const{
bool res = *this==(elem);
return !res;
}
double Dvector::operator*(const Dvector& elem) const{
assert(this->size()==elem.size());
double res=0;
for(int i = 0 ; i< this->size();i++){
res=this->vect[i]+elem(i);
}
return res;
}
ostream & operator <<(ostream &OPut, const Dvector &P)
{
P.display(OPut);
return OPut;
}
// a tripatou
istream & operator >>(istream& Stream, Dvector &P)
{
std::string str;
for(int i=0;i<P.size();i++){
getline( Stream, str );
char *cptr = new char[str.size()+1]; // +1 to account for \0 byte
std::strncpy(cptr,str.c_str(), str.size());
P(i) = atof(cptr);
}
return Stream;
}
| [
"germain.geoffroy@ensimag.grenoble-inp.fr"
] | germain.geoffroy@ensimag.grenoble-inp.fr |
24cc4830b9b45c1d731ee9466937df1c20e2d369 | e773931bdeb9317a5ff7c7e2e6b1012b2645642a | /content/browser/accessibility/dump_accessibility_scripts_browsertest.cc | f527a0626e528c02c0bbc741699c395148fe0cf8 | [
"BSD-3-Clause"
] | permissive | SelyanKab/chromium | 21780bcaf7a21d67e3a4fe902aa8fd5d653b374b | ee248e9797404ad1cfcafdc3c0a58729b0f8f88d | refs/heads/master | 2023-03-14T15:02:38.903591 | 2021-03-10T10:21:05 | 2021-03-10T10:21:05 | 234,272,861 | 0 | 0 | BSD-3-Clause | 2020-01-16T08:36:12 | 2020-01-16T08:36:12 | null | UTF-8 | C++ | false | false | 3,441 | cc | // Copyright (c) 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/files/file_util.h"
#include "build/build_config.h"
#include "content/browser/accessibility/dump_accessibility_browsertest_base.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/shell/browser/shell.h"
namespace content {
using ui::AXPropertyFilter;
using ui::AXTreeFormatter;
// See content/test/data/accessibility/readme.md for an overview.
//
// This test loads an HTML file, invokes a script, and then
// compares the script output against an expected baseline.
//
// The flow of the test is as outlined below.
// 1. Load an html file from content/test/data/accessibility.
// 2. Read the expectation.
// 3. Browse to the page, executes scripts and format their output.
// 4. Perform a comparison between actual and expected and fail if they do not
// exactly match.
class DumpAccessibilityScriptTest : public DumpAccessibilityTestBase {
public:
void AddDefaultFilters(
std::vector<AXPropertyFilter>* property_filters) override;
void AddPropertyFilter(
std::vector<AXPropertyFilter>* property_filters,
const std::string& filter,
AXPropertyFilter::Type type = AXPropertyFilter::ALLOW) {
property_filters->push_back(AXPropertyFilter(filter, type));
}
std::vector<std::string> Dump(std::vector<std::string>& unused) override {
std::unique_ptr<AXTreeFormatter> formatter(CreateFormatter());
// Set test provided property filters.
formatter->SetPropertyFilters(property_filters_,
AXTreeFormatter::kFiltersDefaultSet);
// No accessible tree nodes, just run scripts.
formatter->SetNodeFilters({{"*", "*"}});
std::string actual_contents =
formatter->Format(GetRootAccessibilityNode(shell()->web_contents()));
return base::SplitString(actual_contents, "\n", base::KEEP_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
}
void RunMacTextMarkerTest(const base::FilePath::CharType* file_path) {
base::FilePath test_path =
GetTestFilePath("accessibility", "mac/textmarker");
{
base::ScopedAllowBlockingForTesting allow_blocking;
ASSERT_TRUE(base::PathExists(test_path)) << test_path.LossyDisplayName();
}
base::FilePath html_file = test_path.Append(base::FilePath(file_path));
RunTest(html_file, "accessibility/mac/textmarker");
}
};
void DumpAccessibilityScriptTest::AddDefaultFilters(
std::vector<AXPropertyFilter>* property_filters) {}
// Parameterize the tests so that each test-pass is run independently.
struct TestPassToString {
std::string operator()(const ::testing::TestParamInfo<size_t>& i) const {
auto passes = DumpAccessibilityTestHelper::TestPasses();
CHECK_LT(i.param, passes.size());
return std::string(passes[i.param]);
}
};
//
// Scripting supported on Mac only.
//
#if defined(OS_MAC)
INSTANTIATE_TEST_SUITE_P(
All,
DumpAccessibilityScriptTest,
::testing::Values(
1), // mac tree formatter, see DumpAccessibilityTestHelper::TestPasses
TestPassToString());
IN_PROC_BROWSER_TEST_P(DumpAccessibilityScriptTest, AXStartTextMarker) {
RunMacTextMarkerTest(FILE_PATH_LITERAL("ax_start_text_marker.html"));
}
#endif
} // namespace content
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
f460adee167a4bd02ddf0baeec8849b7a8c52d3c | d3741d8710d0778f99f485ea15dbfdb683dd1a6d | /src/cfl_tree.cpp | 80f9a9c396fb06deb790d96c6ca578917887230e | [
"MIT"
] | permissive | DBLouis/cfltk | af122133edfa7d2083fbd170c4e57313a921e5c7 | 8cb846aeeb5381f604eb954a93f387e4bdc88af2 | refs/heads/main | 2023-08-09T23:39:45.646467 | 2023-07-17T11:49:48 | 2023-07-17T12:02:40 | 382,894,659 | 0 | 0 | null | 2021-07-04T16:09:56 | 2021-07-04T16:09:55 | null | UTF-8 | C++ | false | false | 24,237 | cpp | #include "cfl_tree.h"
#include "cfl_lock.hpp"
#include <FL/Fl.H>
#include <FL/Fl_Image.H>
#include <FL/Fl_Tree.H>
#include <FL/Fl_Tree_Item.H>
#include <FL/Fl_Tree_Item_Array.H>
#include <FL/Fl_Widget.H>
#include <stdlib.h>
WIDGET_CLASS(Fl_Tree)
WIDGET_DEFINE(Fl_Tree)
void Fl_Tree_begin(Fl_Tree *self) {
LOCK(self->begin();)
}
void Fl_Tree_end(Fl_Tree *self) {
LOCK(self->end();)
}
void Fl_Tree_show_self(Fl_Tree *self) {
LOCK(self->show_self();)
}
void Fl_Tree_root_label(Fl_Tree *self, const char *new_label) {
LOCK(self->root_label(new_label);)
}
Fl_Tree_Item *Fl_Tree_root(Fl_Tree *self) {
LOCK(auto ret = self->root());
return ret;
}
void Fl_Tree_set_root(Fl_Tree *self, Fl_Tree_Item *newitem) {
LOCK(self->root(newitem);)
}
Fl_Tree_Item *Fl_Tree_add(Fl_Tree *self, const char *name) {
LOCK(auto ret = self->add(name));
return ret;
}
Fl_Tree_Item *Fl_Tree_insert_above(Fl_Tree *self, Fl_Tree_Item *above, const char *name) {
LOCK(auto ret = self->insert_above(above, name));
return ret;
}
Fl_Tree_Item *Fl_Tree_insert(Fl_Tree *self, Fl_Tree_Item *item, const char *name, int pos) {
LOCK(auto ret = self->insert(item, name, pos));
return ret;
}
const Fl_Tree_Item *Fl_Tree_find_item(const Fl_Tree *self, const char *path) {
if (!path || strlen(path) == 0)
return NULL;
LOCK(const Fl_Tree_Item *item = self->find_item(path));
return item;
}
Fl_Tree_Item *Fl_Tree_find_item_mut(Fl_Tree *self, const char *path) {
if (!path || strlen(path) == 0)
return NULL;
LOCK(Fl_Tree_Item *item = self->find_item(path));
return item;
}
int Fl_Tree_remove(Fl_Tree *self, Fl_Tree_Item *item) {
LOCK(auto ret = self->remove(item));
return ret;
}
void Fl_Tree_clear(Fl_Tree *self) {
self->clear();
}
void Fl_Tree_clear_children(Fl_Tree *self, Fl_Tree_Item *item) {
self->clear_children(item);
}
const Fl_Tree_Item *Fl_Tree_find_clicked(const Fl_Tree *self, int yonly) {
LOCK(auto ret = self->find_clicked(yonly));
return ret;
}
Fl_Tree_Item *Fl_Tree_item_clicked(Fl_Tree *self) {
LOCK(auto ret = self->item_clicked());
return ret;
}
Fl_Tree_Item *Fl_Tree_first(Fl_Tree *self) {
LOCK(auto ret = self->first());
return ret;
}
Fl_Tree_Item *Fl_Tree_first_visible_item(Fl_Tree *self) {
LOCK(auto ret = self->first_visible_item());
return ret;
}
Fl_Tree_Item *Fl_Tree_next(Fl_Tree *self, Fl_Tree_Item *item) {
LOCK(auto ret = self->next(item));
return ret;
}
Fl_Tree_Item *Fl_Tree_prev(Fl_Tree *self, Fl_Tree_Item *item) {
LOCK(auto ret = self->prev(item));
return ret;
}
Fl_Tree_Item *Fl_Tree_last(Fl_Tree *self) {
LOCK(auto ret = self->last());
return ret;
}
Fl_Tree_Item *Fl_Tree_last_visible_item(Fl_Tree *self) {
LOCK(auto ret = self->last_visible_item());
return ret;
}
Fl_Tree_Item *Fl_Tree_next_visible_item(Fl_Tree *self, Fl_Tree_Item *start, int dir) {
LOCK(auto ret = self->next_visible_item(start, dir));
return ret;
}
Fl_Tree_Item *Fl_Tree_first_selected_item(Fl_Tree *self) {
LOCK(auto ret = self->first_selected_item());
return ret;
}
Fl_Tree_Item *Fl_Tree_last_selected_item(Fl_Tree *self) {
LOCK(auto ret = self->last_selected_item());
return ret;
}
Fl_Tree_Item *Fl_Tree_next_item(Fl_Tree *self, Fl_Tree_Item *item, int dir, int visible) {
LOCK(auto ret = self->next_item(item, dir, visible));
return ret;
}
Fl_Tree_Item *Fl_Tree_next_selected_item(Fl_Tree *self, Fl_Tree_Item *item, int dir) {
LOCK(auto ret = self->next_selected_item(item, dir));
return ret;
}
int Fl_Tree_get_selected_items(Fl_Tree *self, Fl_Tree_Item_Array **arr) {
int c = 0;
LOCK(for (Fl_Tree_Item *i = self->first_selected_item(); i; i = self->next_selected_item(i))
c++;
if (c == 0) return 0; *arr = new Fl_Tree_Item_Array(c);
int ret = self->get_selected_items(**arr));
return ret;
}
int Fl_Tree_get_items(Fl_Tree *self, Fl_Tree_Item_Array **arr) {
int c = 0;
LOCK(for (Fl_Tree_Item *i = self->first(); i; i = self->next_item(i)) c++; if (c == 0) return 0;
*arr = new Fl_Tree_Item_Array(c);
for (Fl_Tree_Item *i = self->first(); i; i = self->next_item(i))(*arr)->add(i);)
return c;
}
int Fl_Tree_open(Fl_Tree *self, const char *path, int docallback) {
if (!path)
return 0;
LOCK(auto ret = self->open(path, docallback));
return ret;
}
void Fl_Tree_open_toggle(Fl_Tree *self, Fl_Tree_Item *item, int docallback) {
LOCK(self->open_toggle(item, docallback);)
}
int Fl_Tree_close(Fl_Tree *self, const char *path, int docallback) {
LOCK(auto ret = self->close(path, 1));
return ret;
}
int Fl_Tree_is_open(const Fl_Tree *self, const char *path) {
LOCK(auto ret = self->is_open(path));
return ret;
}
int Fl_Tree_is_close(const Fl_Tree *self, const char *path) {
LOCK(auto ret = self->is_close(path));
return ret;
}
int Fl_Tree_select(Fl_Tree *self, const char *path, int docallback) {
LOCK(auto ret = self->select(path, docallback));
return ret;
}
void Fl_Tree_select_toggle(Fl_Tree *self, Fl_Tree_Item *item, int docallback) {
LOCK(self->select_toggle(item, docallback);)
}
int Fl_Tree_deselect(Fl_Tree *self, const char *path, int docallback) {
LOCK(auto ret = self->deselect(path, docallback));
return ret;
}
int Fl_Tree_deselect_all(Fl_Tree *self, Fl_Tree_Item *item, int docallback) {
LOCK(auto ret = self->deselect_all(item, docallback));
return ret;
}
int Fl_Tree_select_only(Fl_Tree *self, Fl_Tree_Item *selitem, int docallback) {
LOCK(auto ret = self->select_only(selitem, docallback));
return ret;
}
int Fl_Tree_select_all(Fl_Tree *self, Fl_Tree_Item *item, int docallback) {
LOCK(auto ret = self->select_all(item, docallback));
return ret;
}
int Fl_Tree_extend_selection_dir(Fl_Tree *self, Fl_Tree_Item *from, Fl_Tree_Item *to, int dir,
int val, int visible) {
LOCK(auto ret = self->extend_selection_dir(from, to, dir, val, visible));
return ret;
}
int Fl_Tree_extend_selection(Fl_Tree *self, Fl_Tree_Item *from, Fl_Tree_Item *to, int val,
int visible) {
LOCK(auto ret = self->extend_selection(from, to, val, visible));
return ret;
}
void Fl_Tree_set_item_focus(Fl_Tree *self, Fl_Tree_Item *item) {
LOCK(self->set_item_focus(item);)
}
Fl_Tree_Item *Fl_Tree_get_item_focus(const Fl_Tree *self) {
LOCK(auto ret = self->get_item_focus());
return ret;
}
int Fl_Tree_is_selected(Fl_Tree *self, const char *path) {
LOCK(auto ret = self->is_selected(path));
return ret;
}
int Fl_Tree_item_labelfont(const Fl_Tree *self) {
LOCK(auto ret = self->item_labelfont());
return ret;
}
void Fl_Tree_set_item_labelfont(Fl_Tree *self, int val) {
LOCK(self->item_labelfont(val);)
}
int Fl_Tree_item_labelsize(const Fl_Tree *self) {
LOCK(auto ret = self->item_labelsize());
return ret;
}
void Fl_Tree_set_item_labelsize(Fl_Tree *self, int val) {
LOCK(self->item_labelsize(val);)
}
unsigned int Fl_Tree_item_labelfgcolor(const Fl_Tree *self) {
LOCK(auto ret = self->item_labelfgcolor());
return ret;
}
void Fl_Tree_set_item_labelfgcolor(Fl_Tree *self, unsigned int val) {
LOCK(self->item_labelfgcolor(val);)
}
unsigned int Fl_Tree_item_labelbgcolor(const Fl_Tree *self) {
LOCK(auto ret = self->item_labelbgcolor());
return ret;
}
void Fl_Tree_set_item_labelbgcolor(Fl_Tree *self, unsigned int val) {
LOCK(self->item_labelbgcolor(val);)
}
unsigned int Fl_Tree_connectorcolor(const Fl_Tree *self) {
LOCK(auto ret = self->connectorcolor());
return ret;
}
void Fl_Tree_set_connectorcolor(Fl_Tree *self, unsigned int val) {
LOCK(self->connectorcolor(val);)
}
int Fl_Tree_marginleft(const Fl_Tree *self) {
LOCK(auto ret = self->marginleft());
return ret;
}
void Fl_Tree_set_marginleft(Fl_Tree *self, int val) {
LOCK(self->marginleft(val);)
}
int Fl_Tree_margintop(const Fl_Tree *self) {
LOCK(auto ret = self->margintop());
return ret;
}
void Fl_Tree_set_margintop(Fl_Tree *self, int val) {
LOCK(self->margintop(val);)
}
int Fl_Tree_marginbottom(const Fl_Tree *self) {
LOCK(auto ret = self->marginbottom());
return ret;
}
void Fl_Tree_set_marginbottom(Fl_Tree *self, int val) {
LOCK(self->marginbottom(val);)
}
int Fl_Tree_linespacing(const Fl_Tree *self) {
LOCK(auto ret = self->linespacing());
return ret;
}
void Fl_Tree_set_linespacing(Fl_Tree *self, int val) {
LOCK(self->linespacing(val);)
}
int Fl_Tree_openchild_marginbottom(const Fl_Tree *self) {
LOCK(auto ret = self->openchild_marginbottom());
return ret;
}
void Fl_Tree_set_openchild_marginbottom(Fl_Tree *self, int val) {
LOCK(self->openchild_marginbottom(val);)
}
int Fl_Tree_usericonmarginleft(const Fl_Tree *self) {
LOCK(auto ret = self->usericonmarginleft());
return ret;
}
void Fl_Tree_set_usericonmarginleft(Fl_Tree *self, int val) {
LOCK(self->usericonmarginleft(val);)
}
int Fl_Tree_labelmarginleft(const Fl_Tree *self) {
LOCK(auto ret = self->labelmarginleft());
return ret;
}
void Fl_Tree_set_labelmarginleft(Fl_Tree *self, int val) {
LOCK(self->labelmarginleft(val);)
}
int Fl_Tree_widgetmarginleft(const Fl_Tree *self) {
LOCK(auto ret = self->widgetmarginleft());
return ret;
}
void Fl_Tree_set_widgetmarginleft(Fl_Tree *self, int val) {
LOCK(self->widgetmarginleft(val);)
}
int Fl_Tree_connectorwidth(const Fl_Tree *self) {
LOCK(auto ret = self->connectorwidth());
return ret;
}
void Fl_Tree_set_connectorwidth(Fl_Tree *self, int val) {
LOCK(self->connectorwidth(val);)
}
void *Fl_Tree_usericon(const Fl_Tree *self) {
LOCK(auto temp = self->usericon());
if (!temp)
return NULL;
LOCK(auto ret = ((Fl_Image *)temp)->copy());
return ret;
}
void Fl_Tree_set_usericon(Fl_Tree *self, void *val) {
LOCK(auto old = self->usericon(); if (!val) self->usericon(NULL);
else self->usericon(((Fl_Image *)val)->copy()); delete old;)
}
void *Fl_Tree_openicon(const Fl_Tree *self) {
LOCK(auto temp = self->openicon());
if (!temp)
return NULL;
LOCK(auto ret = ((Fl_Image *)temp)->copy());
return ret;
}
void Fl_Tree_set_openicon(Fl_Tree *self, void *val) {
LOCK(auto old = self->openicon(); if (!val) self->openicon(NULL);
else self->openicon(((Fl_Image *)val)->copy()); delete old;)
}
void *Fl_Tree_closeicon(const Fl_Tree *self) {
LOCK(auto temp = self->closeicon());
if (!temp)
return NULL;
LOCK(auto ret = ((Fl_Image *)temp)->copy());
return ret;
}
void Fl_Tree_set_closeicon(Fl_Tree *self, void *val) {
LOCK(auto old = self->closeicon(); if (!val) self->closeicon(NULL);
else self->closeicon(((Fl_Image *)val)->copy()); delete old;)
}
int Fl_Tree_showcollapse(const Fl_Tree *self) {
LOCK(auto ret = self->showcollapse());
return ret;
}
void Fl_Tree_set_showcollapse(Fl_Tree *self, int val) {
LOCK(self->showcollapse(val);)
}
int Fl_Tree_showroot(const Fl_Tree *self) {
LOCK(auto ret = self->showroot());
return ret;
}
void Fl_Tree_set_showroot(Fl_Tree *self, int val) {
LOCK(self->showroot(val);)
}
int Fl_Tree_connectorstyle(const Fl_Tree *self) {
LOCK(auto ret = self->connectorstyle());
return ret;
}
void Fl_Tree_set_connectorstyle(Fl_Tree *self, int val) {
LOCK(self->connectorstyle((Fl_Tree_Connector)val);)
}
int Fl_Tree_sortorder(const Fl_Tree *self) {
LOCK(auto ret = self->sortorder());
return ret;
}
void Fl_Tree_set_sortorder(Fl_Tree *self, int val) {
LOCK(self->sortorder((Fl_Tree_Sort)val);)
}
int Fl_Tree_selectbox(const Fl_Tree *self) {
LOCK(auto ret = self->selectbox());
return ret;
}
void Fl_Tree_set_selectbox(Fl_Tree *self, int val) {
LOCK(self->selectbox((Fl_Boxtype)val);)
}
int Fl_Tree_selectmode(const Fl_Tree *self) {
LOCK(auto ret = self->selectmode());
return ret;
}
void Fl_Tree_set_selectmode(Fl_Tree *self, int val) {
LOCK(self->selectmode((Fl_Tree_Select)val);)
}
int Fl_Tree_item_reselect_mode(const Fl_Tree *self) {
LOCK(auto ret = self->item_reselect_mode());
return ret;
}
void Fl_Tree_set_item_reselect_mode(Fl_Tree *self, int mode) {
LOCK(self->item_reselect_mode((Fl_Tree_Item_Reselect_Mode)mode);)
}
int Fl_Tree_item_draw_mode(const Fl_Tree *self) {
LOCK(auto ret = self->item_draw_mode());
return ret;
}
void Fl_Tree_set_item_draw_mode(Fl_Tree *self, int mode) {
LOCK(self->item_draw_mode(mode);)
}
void Fl_Tree_calc_dimensions(Fl_Tree *self) {
LOCK(self->calc_dimensions();)
}
void Fl_Tree_calc_tree(Fl_Tree *self) {
LOCK(self->calc_tree();)
}
void Fl_Tree_recalc_tree(Fl_Tree *self) {
LOCK(self->recalc_tree();)
}
int Fl_Tree_displayed(Fl_Tree *self, Fl_Tree_Item *item) {
LOCK(auto ret = self->displayed(item));
return ret;
}
void Fl_Tree_show_item(Fl_Tree *self, Fl_Tree_Item *item, int yoff) {
LOCK(self->show_item(item, yoff);)
}
void Fl_Tree_show_item_top(Fl_Tree *self, Fl_Tree_Item *item) {
LOCK(self->show_item_top(item);)
}
void Fl_Tree_show_item_middle(Fl_Tree *self, Fl_Tree_Item *item) {
LOCK(self->show_item_middle(item);)
}
void Fl_Tree_show_item_bottom(Fl_Tree *self, Fl_Tree_Item *item) {
LOCK(self->show_item_bottom(item);)
}
void Fl_Tree_display(Fl_Tree *self, Fl_Tree_Item *item) {
LOCK(self->display(item);)
}
int Fl_Tree_vposition(const Fl_Tree *self) {
LOCK(auto ret = self->vposition());
return ret;
}
void Fl_Tree_set_vposition(Fl_Tree *self, int pos) {
LOCK(self->vposition(pos);)
}
int Fl_Tree_hposition(const Fl_Tree *self) {
LOCK(auto ret = self->hposition());
return ret;
}
void Fl_Tree_set_hposition(Fl_Tree *self, int pos) {
LOCK(self->hposition(pos);)
}
int Fl_Tree_is_scrollbar(Fl_Tree *self, Fl_Widget *w) {
LOCK(auto ret = self->is_scrollbar(w));
return ret;
}
int Fl_Tree_scrollbar_size(const Fl_Tree *self) {
LOCK(auto ret = self->scrollbar_size());
return ret;
}
void Fl_Tree_set_scrollbar_size(Fl_Tree *self, int size) {
LOCK(self->scrollbar_size(size);)
}
int Fl_Tree_is_vscroll_visible(const Fl_Tree *self) {
LOCK(auto ret = self->is_vscroll_visible());
return ret;
}
int Fl_Tree_is_hscroll_visible(const Fl_Tree *self) {
LOCK(auto ret = self->is_hscroll_visible());
return ret;
}
void Fl_Tree_set_callback_item(Fl_Tree *self, Fl_Tree_Item *item) {
LOCK(self->callback_item(item);)
}
Fl_Tree_Item *Fl_Tree_callback_item(Fl_Tree *self) {
LOCK(auto ret = self->callback_item());
return ret;
}
void Fl_Tree_set_callback_reason(Fl_Tree *self, int reason) {
LOCK(self->callback_reason((Fl_Tree_Reason)reason);)
}
int Fl_Tree_callback_reason(const Fl_Tree *self) {
LOCK(auto ret = self->callback_reason());
return ret;
}
// TreeItems
int Fl_Tree_Item_x(const Fl_Tree_Item *self) {
LOCK(auto ret = self->x());
return ret;
}
int Fl_Tree_Item_y(const Fl_Tree_Item *self) {
LOCK(auto ret = self->y());
return ret;
}
int Fl_Tree_Item_w(const Fl_Tree_Item *self) {
LOCK(auto ret = self->w());
return ret;
}
int Fl_Tree_Item_h(const Fl_Tree_Item *self) {
LOCK(auto ret = self->h());
return ret;
}
int Fl_Tree_Item_label_x(const Fl_Tree_Item *self) {
LOCK(auto ret = self->label_x());
return ret;
}
int Fl_Tree_Item_label_y(const Fl_Tree_Item *self) {
LOCK(auto ret = self->label_y());
return ret;
}
int Fl_Tree_Item_label_w(const Fl_Tree_Item *self) {
LOCK(auto ret = self->label_w());
return ret;
}
int Fl_Tree_Item_label_h(const Fl_Tree_Item *self) {
LOCK(auto ret = self->label_h());
return ret;
}
void Fl_Tree_Item_show_self(const Fl_Tree_Item *self, const char *indent) {
LOCK(self->show_self(indent);)
}
void Fl_Tree_set_Item_label(Fl_Tree_Item *self, const char *val) {
LOCK(self->label(val);)
}
const char *Fl_Tree_Item_label(const Fl_Tree_Item *self) {
LOCK(const char *label = self->label(); char *buf = (char *)malloc(strlen(label) + 1);
memcpy(buf, label, strlen(label) + 1);)
return buf;
}
void Fl_Tree_Item_set_labelfont(Fl_Tree_Item *self, int val) {
LOCK(self->labelfont(val);)
}
int Fl_Tree_Item_labelfont(const Fl_Tree_Item *self) {
LOCK(auto ret = self->labelfont());
return ret;
}
void Fl_Tree_Item_set_labelsize(Fl_Tree_Item *self, int val) {
LOCK(self->labelsize(val);)
}
int Fl_Tree_Item_labelsize(const Fl_Tree_Item *self) {
LOCK(auto ret = self->labelsize());
return ret;
}
void Fl_Tree_Item_set_labelfgcolor(Fl_Tree_Item *self, unsigned int val) {
LOCK(self->labelfgcolor(val);)
}
unsigned int Fl_Tree_Item_labelfgcolor(const Fl_Tree_Item *self) {
LOCK(auto ret = self->labelfgcolor());
return ret;
}
void Fl_Tree_Item_set_labelcolor(Fl_Tree_Item *self, unsigned int val) {
LOCK(self->labelcolor(val);)
}
unsigned int Fl_Tree_Item_labelcolor(const Fl_Tree_Item *self) {
LOCK(auto ret = self->labelcolor());
return ret;
}
void Fl_Tree_Item_set_labelbgcolor(Fl_Tree_Item *self, unsigned int val) {
LOCK(self->labelbgcolor(val);)
}
unsigned int Fl_Tree_Item_labelbgcolor(const Fl_Tree_Item *self) {
LOCK(auto ret = self->labelbgcolor());
return ret;
}
void Fl_Tree_Item_set_widget(Fl_Tree_Item *self, Fl_Widget *val) {
LOCK(self->widget(val);)
}
Fl_Widget *Fl_Tree_Item_widget(const Fl_Tree_Item *self) {
LOCK(auto ret = self->widget());
return ret;
}
int Fl_Tree_Item_children(const Fl_Tree_Item *self) {
LOCK(auto ret = self->children());
return ret;
}
const Fl_Tree_Item *Fl_Tree_Item_child(const Fl_Tree_Item *self, int t) {
LOCK(auto ret = self->child(t));
return ret;
}
int Fl_Tree_Item_has_children(const Fl_Tree_Item *self) {
LOCK(auto ret = self->has_children());
return ret;
}
int Fl_Tree_Item_find_child(Fl_Tree_Item *self, const char *name) {
LOCK(auto ret = self->find_child(name));
return ret;
}
int Fl_Tree_Item_remove_child(Fl_Tree_Item *self, const char *new_label) {
LOCK(auto ret = self->remove_child(new_label));
return ret;
}
void Fl_Tree_Item_clear_children(Fl_Tree_Item *self) {
LOCK(self->clear_children();)
}
int Fl_Tree_Item_swap_children(Fl_Tree_Item *self, Fl_Tree_Item *a, Fl_Tree_Item *b) {
LOCK(auto ret = self->swap_children(a, b));
return ret;
}
const Fl_Tree_Item *Fl_Tree_Item_find_child_item(const Fl_Tree_Item *self, const char *name) {
LOCK(auto ret = self->find_child_item(name));
return ret;
}
Fl_Tree_Item *Fl_Tree_Item_replace(Fl_Tree_Item *self, Fl_Tree_Item *new_item) {
LOCK(auto ret = self->replace(new_item));
return ret;
}
Fl_Tree_Item *Fl_Tree_Item_replace_child(Fl_Tree_Item *self, Fl_Tree_Item *olditem,
Fl_Tree_Item *newitem) {
LOCK(auto ret = self->replace_child(olditem, newitem));
return ret;
}
Fl_Tree_Item *Fl_Tree_Item_deparent(Fl_Tree_Item *self, int index) {
LOCK(auto ret = self->deparent(index));
return ret;
}
int Fl_Tree_Item_reparent(Fl_Tree_Item *self, Fl_Tree_Item *newchild, int index) {
LOCK(auto ret = self->reparent(newchild, index));
return ret;
}
int Fl_Tree_Item_move(Fl_Tree_Item *self, int to, int from) {
LOCK(auto ret = self->move(to, from));
return ret;
}
int Fl_Tree_Item_move_above(Fl_Tree_Item *self, Fl_Tree_Item *item) {
LOCK(auto ret = self->move_above(item));
return ret;
}
int Fl_Tree_Item_move_below(Fl_Tree_Item *self, Fl_Tree_Item *item) {
LOCK(auto ret = self->move_below(item));
return ret;
}
int Fl_Tree_Item_move_into(Fl_Tree_Item *self, Fl_Tree_Item *item, int pos) {
LOCK(auto ret = self->move_into(item, pos));
return ret;
}
int Fl_Tree_Item_depth(const Fl_Tree_Item *self) {
LOCK(auto ret = self->depth());
return ret;
}
Fl_Tree_Item *Fl_Tree_Item_prev(Fl_Tree_Item *self) {
LOCK(auto ret = self->prev());
return ret;
}
Fl_Tree_Item *Fl_Tree_Item_next(Fl_Tree_Item *self) {
LOCK(auto ret = self->next());
return ret;
}
Fl_Tree_Item *Fl_Tree_Item_next_sibling(Fl_Tree_Item *self) {
LOCK(auto ret = self->next_sibling());
return ret;
}
Fl_Tree_Item *Fl_Tree_Item_prev_sibling(Fl_Tree_Item *self) {
LOCK(auto ret = self->prev_sibling());
return ret;
}
void Fl_Tree_Item_update_prev_next(Fl_Tree_Item *self, int index) {
LOCK(self->update_prev_next(index));
}
const Fl_Tree_Item *Fl_Tree_Item_parent(const Fl_Tree_Item *self) {
LOCK(auto ret = self->parent());
return ret;
}
void Fl_Tree_Item_set_parent(Fl_Tree_Item *self, Fl_Tree_Item *val) {
LOCK(self->parent(val);)
}
const Fl_Tree *Fl_Tree_Item_tree(const Fl_Tree_Item *self) {
LOCK(auto ret = self->tree());
return ret;
}
void Fl_Tree_Item_open(Fl_Tree_Item *self) {
LOCK(self->open();)
}
void Fl_Tree_Item_close(Fl_Tree_Item *self) {
LOCK(self->close();)
}
int Fl_Tree_Item_is_open(const Fl_Tree_Item *self) {
LOCK(auto ret = self->is_open());
return ret;
}
int Fl_Tree_Item_is_close(const Fl_Tree_Item *self) {
LOCK(auto ret = self->is_close());
return ret;
}
void Fl_Tree_Item_open_toggle(Fl_Tree_Item *self) {
LOCK(self->open_toggle();)
}
void Fl_Tree_Item_select(Fl_Tree_Item *self, int val) {
LOCK(self->select(val);)
}
void Fl_Tree_Item_select_toggle(Fl_Tree_Item *self) {
LOCK(self->select_toggle();)
}
int Fl_Tree_Item_select_all(Fl_Tree_Item *self) {
LOCK(auto ret = self->select_all());
return ret;
}
void Fl_Tree_Item_deselect(Fl_Tree_Item *self) {
LOCK(self->deselect();)
}
int Fl_Tree_Item_deselect_all(Fl_Tree_Item *self) {
LOCK(auto ret = self->deselect_all());
return ret;
}
int Fl_Tree_Item_is_root(const Fl_Tree_Item *self) {
LOCK(auto ret = self->is_root());
return ret;
}
int Fl_Tree_Item_is_visible(const Fl_Tree_Item *self) {
LOCK(auto ret = self->is_visible());
return ret;
}
char Fl_Tree_Item_is_active(const Fl_Tree_Item *self) {
LOCK(auto ret = self->is_active());
return ret;
}
char Fl_Tree_Item_is_activated(const Fl_Tree_Item *self) {
LOCK(auto ret = self->is_activated());
return ret;
}
void Fl_Tree_Item_deactivate(Fl_Tree_Item *self) {
LOCK(self->deactivate();)
}
void Fl_Tree_Item_activate(Fl_Tree_Item *self, int val) {
LOCK(self->activate(val);)
}
char Fl_Tree_Item_is_selected(const Fl_Tree_Item *self) {
LOCK(auto ret = self->is_selected());
return ret;
}
// TreeItemArray
int Fl_Tree_Item_Array_total(const Fl_Tree_Item_Array *self) {
LOCK(auto ret = self->total());
return ret;
}
void Fl_Tree_Item_Array_swap(Fl_Tree_Item_Array *self, int ax, int bx) {
LOCK(self->swap(ax, bx));
}
int Fl_Tree_Item_Array_move(Fl_Tree_Item_Array *self, int to, int from) {
LOCK(auto ret = self->move(to, from));
return ret;
}
int Fl_Tree_Item_Array_deparent(Fl_Tree_Item_Array *self, int pos) {
LOCK(auto ret = self->deparent(pos));
return ret;
}
int Fl_Tree_Item_Array_reparent(Fl_Tree_Item_Array *self, Fl_Tree_Item *item,
Fl_Tree_Item *newparent, int pos) {
LOCK(auto ret = self->reparent(item, newparent, pos));
return ret;
}
void Fl_Tree_Item_Array_clear(Fl_Tree_Item_Array *self) {
LOCK(self->clear());
}
void Fl_Tree_Item_Array_add(Fl_Tree_Item_Array *self, Fl_Tree_Item *val) {
LOCK(self->add(val));
}
void Fl_Tree_Item_Array_insert(Fl_Tree_Item_Array *self, int pos, Fl_Tree_Item *new_item) {
LOCK(self->insert(pos, new_item));
}
void Fl_Tree_Item_Array_replace(Fl_Tree_Item_Array *self, int pos, Fl_Tree_Item *new_item) {
LOCK(self->replace(pos, new_item));
}
void Fl_Tree_Item_Array_remove(Fl_Tree_Item_Array *self, int index) {
LOCK(self->remove(index));
}
int Fl_Tree_Item_Array_remove_item(Fl_Tree_Item_Array *self, Fl_Tree_Item *item) {
LOCK(auto ret = self->remove(item));
return ret;
}
Fl_Tree_Item *Fl_Tree_Item_Array_at(Fl_Tree_Item_Array *self, int index) {
LOCK(
int total = self->total());
if (index >= total)
return NULL;
LOCK(auto ret = (*self)[index]); return ret;
}
void Fl_Tree_Item_Array_delete(Fl_Tree_Item_Array *self) {
delete self;
}
| [
"may642_2000@hotmail.com"
] | may642_2000@hotmail.com |
6471ef82b16c6875ae51284c34f5cfc9fe0965b4 | 4d77398fc24009f483f2b2abc028a135e09fc9eb | /Assignment4/Solid_plate/4.8/gradTz | 9728662a9194b279e95584bb5d401398f23fd547 | [] | permissive | Naveen-Surya/CFD-Lab-1 | 12c635b72c611d83080ed6dd316b1b0016f2f86f | c38b0bfe43c7135f4a10e744ea1ac6cf6e9d4a1a | refs/heads/master | 2020-04-05T16:43:39.651232 | 2018-08-23T12:10:06 | 2018-08-23T12:10:06 | 157,026,052 | 0 | 1 | MIT | 2018-11-10T22:11:51 | 2018-11-10T22:11:51 | null | UTF-8 | C++ | false | false | 1,376 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 5.x |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "4.8";
object gradTz;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 -1 0 1 0 0 0];
internalField uniform 0;
boundaryField
{
left
{
type calculated;
value uniform 0;
}
right
{
type calculated;
value uniform 0;
}
interface
{
type calculated;
value uniform 0;
}
bottom
{
type calculated;
value uniform 0;
}
defaultFaces
{
type empty;
}
}
// ************************************************************************* //
| [
"sarthakgarg1993@gmail.com"
] | sarthakgarg1993@gmail.com | |
7d1efb423842f76dc6e210f220214999282824ea | f02f7b6eca25b0b0198d6239d08497be73ed9463 | /SDL2_Wrapper/window_archtype.h | 630cc187f12fa4b40005c535a4c7ad63651501b4 | [
"MIT"
] | permissive | andywm/Physics-Demo | 49ff2e4722a027aa9e1184bb4e8d6bf367612857 | 8c625636e4ca92e445329bcfc977a07b8504e9b2 | refs/heads/master | 2021-01-21T21:15:18.719410 | 2017-06-19T17:13:20 | 2017-06-19T17:13:20 | 94,798,429 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,374 | h | #pragma once
#ifndef _WINSOCKAPI_
#define _WINSOCKAPI_
#endif // ! #define _WINSOCKAPI_
#include<SDL2/SDL.h>
#include<string>
#include<queue>
#include<list>
#include<memory>
#include <glm\vec2.hpp>
using uint = unsigned int;
class WindowArchtype
{
private:
int mWindowID;
SDL_Window * mWindow;
std::queue<SDL_Event> mWindowEvents;
public:
//wrapper for a list of unique_ptrs<windows>
//Window();
WindowArchtype(const std::string & title,
const uint w, const uint h,
const uint x, const uint y,
const uint flags);
WindowArchtype& operator=(const WindowArchtype&) = delete;
WindowArchtype(const WindowArchtype &) = delete;
virtual ~WindowArchtype();
void pushEvent(const SDL_Event & event);
bool peekEvent(SDL_Event * const event);
bool popEvent(SDL_Event * const event);
inline const glm::ivec2
WindowArchtype::size() const
{
int w, h;
SDL_GetWindowSize(mWindow, &w, &h);
return glm::ivec2(w, h);
}
virtual void resized()=0;
virtual void resize(const glm::ivec2 & size);
inline const int
windowID() const
{
return mWindowID;
}
inline SDL_Window * const
window() const
{
return mWindow;
}
protected:
bool createWindow(const std::string & title,
const uint w, const uint h,
const uint x, const uint y,
const uint flags);
};
using win_sptr = std::unique_ptr<WindowArchtype>;
using window_group = std::vector<win_sptr>;
| [
"andy6a6@msn.com"
] | andy6a6@msn.com |
c02384aafe22e299611df570cc931c5ad0726452 | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/libs/process/example/wait.cpp | 86f773767dc83bc883196b048f9ebf49b12e0253 | [
"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 | 861 | cpp | // Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
//
// 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/process.hpp>
#include <sstd/boost/asio.hpp>
namespace bp = boost::process;
int main()
{
{
bp::child c("test.exe");
c.wait();
auto exit_code = c.exit_code();
}
{
boost::asio::io_context io_context;
bp::child c(
"test.exe",
io_context,
bp::on_exit([&](int exit, const std::error_code& ec_in){})
);
io_context.run();
}
}
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
da8edd727fa3caa8dd6c25beb6d8bc803eaa9515 | 3cf9e141cc8fee9d490224741297d3eca3f5feff | /C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-966.cpp | 66e139eec834416b288e073cf2bb33c2c1340bcc | [] | 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,588 | 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
{
bool active2;
c2() : active2(true) {}
virtual ~c2()
{
tester2(this);
active2 = false;
}
virtual void f2(){}
};
void __attribute__ ((noinline)) tester2(c2* p)
{
p->f2();
}
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 : c2, virtual c0, c3
{
bool active4;
c4() : active4(true) {}
virtual ~c4()
{
tester4(this);
c0 *p0_0 = (c0*)(c4*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c3*)(c4*)(this);
tester0(p0_1);
c1 *p1_0 = (c1*)(c3*)(c4*)(this);
tester1(p1_0);
c2 *p2_0 = (c2*)(c4*)(this);
tester2(p2_0);
c3 *p3_0 = (c3*)(c4*)(this);
tester3(p3_0);
active4 = false;
}
virtual void f4(){}
};
void __attribute__ ((noinline)) tester4(c4* p)
{
p->f4();
if (p->active1)
p->f1();
if (p->active2)
p->f2();
if (p->active3)
p->f3();
if (p->active0)
p->f0();
}
int __attribute__ ((noinline)) inc(int v) {return ++v;}
int main()
{
c0* ptrs0[25];
ptrs0[0] = (c0*)(new c0());
ptrs0[1] = (c0*)(c3*)(new c3());
ptrs0[2] = (c0*)(c4*)(new c4());
ptrs0[3] = (c0*)(c3*)(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*)(c3*)(new c3());
ptrs1[2] = (c1*)(c3*)(c4*)(new c4());
for (int i=0;i<3;i=inc(i))
{
tester1(ptrs1[i]);
delete ptrs1[i];
}
c2* ptrs2[25];
ptrs2[0] = (c2*)(new c2());
ptrs2[1] = (c2*)(c4*)(new c4());
for (int i=0;i<2;i=inc(i))
{
tester2(ptrs2[i]);
delete ptrs2[i];
}
c3* ptrs3[25];
ptrs3[0] = (c3*)(new c3());
ptrs3[1] = (c3*)(c4*)(new c4());
for (int i=0;i<2;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 |
6a7b200da824acd6dc178511ff95828aae4f58bf | 5ec1ccbb2d6d485c7ddbff92d1a8855f5df4d805 | /src/barrier.hpp | 64d4ac732ed6e75b51093911d578228033ea0717 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause-LBNL"
] | permissive | snake0/upcxx-2020.3.2 | e1f2e94e33175b15a1f636b384ce206a59abebac | a376bcb4f4f15905e4360f0b78f5a3661071b737 | refs/heads/master | 2023-01-08T13:54:32.709572 | 2020-11-18T12:14:38 | 2020-11-18T12:14:38 | 313,923,784 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,843 | hpp | #ifndef _f2c7c1fc_cd4a_4123_bf50_a6542f8efa2c
#define _f2c7c1fc_cd4a_4123_bf50_a6542f8efa2c
#include <upcxx/backend.hpp>
#include <upcxx/completion.hpp>
#include <upcxx/future.hpp>
#include <upcxx/team.hpp>
namespace upcxx {
namespace detail {
////////////////////////////////////////////////////////////////////
// barrier_event_values: Value for completions_state's EventValues
// template argument. barrier events always report no values.
struct barrier_event_values {
template<typename Event>
using tuple_t = std::tuple<>;
};
void barrier_async_inject(const team &tm, backend::gasnet::handle_cb *cb);
}
void barrier(const team &tm = upcxx::world());
template<typename Cxs = completions<future_cx<operation_cx_event>>>
typename detail::completions_returner<
/*EventPredicate=*/detail::event_is_here,
/*EventValues=*/detail::barrier_event_values,
Cxs
>::return_t
barrier_async(
const team &tm = upcxx::world(),
Cxs cxs = completions<future_cx<operation_cx_event>>({})
) {
struct barrier_cb final: backend::gasnet::handle_cb {
detail::completions_state<
/*EventPredicate=*/detail::event_is_here,
/*EventValues=*/detail::barrier_event_values,
Cxs> state;
barrier_cb(Cxs &&cxs): state(std::move(cxs)) {}
void execute_and_delete(backend::gasnet::handle_cb_successor) {
state.template operator()<operation_cx_event>();
delete this;
}
};
barrier_cb *cb = new barrier_cb(std::move(cxs));
auto returner = detail::completions_returner<
/*EventPredicate=*/detail::event_is_here,
/*EventValues=*/detail::barrier_event_values,
Cxs
>(cb->state);
detail::barrier_async_inject(tm, cb);
return returner();
}
}
#endif
| [
"1260865816@qq.com"
] | 1260865816@qq.com |
e4188ddfe84790da5759936a0ccfc815d6d40891 | d1f24644ad545978264a4a5f6db812546ee6f20e | /covid19_ventilator_vub/test/suite.cpp | 8cc29965f4ac4cae2b074b8c2070ca76c5766e0a | [] | no_license | jantje/covid16_ventilatyor_vub | be5be96d62fee24cf5183c1a6678baa9c6327863 | ffc6211f3178f0c45ccdc3b8dc6a93e2229e86fe | refs/heads/master | 2021-03-31T15:56:08.955531 | 2020-03-24T22:22:15 | 2020-03-24T22:22:15 | 248,117,811 | 1 | 3 | null | 2020-03-24T21:14:51 | 2020-03-18T02:14:45 | C++ | UTF-8 | C++ | false | false | 121 | cpp | #include <gtest/gtest.h>
#include "Alarm.h"
TEST(GreaterTest,AisGreater){
EXPECT_EQ(3,3);
};
#include "gtest.cpp.in"
| [
"ruben.de.smet@rubdos.be"
] | ruben.de.smet@rubdos.be |
4c746be060ef4ab5ae7559dc9c5c39008f435c53 | 54c67306d63bb69a5cf381d12108d3dc98ae0f5d | /game/sound/common/synth.cpp | 50de71864d69f6951308a987b0d497713032effe | [
"ISC"
] | permissive | open-goal/jak-project | adf30a3459c24afda5b180e3abe1583c93458a37 | d96dce27149fbf58586160cfecb634614f055943 | refs/heads/master | 2023-09-01T21:51:16.736237 | 2023-09-01T16:10:59 | 2023-09-01T16:10:59 | 289,585,720 | 1,826 | 131 | ISC | 2023-09-14T13:27:47 | 2020-08-22T23:55:21 | Common Lisp | UTF-8 | C++ | false | false | 755 | cpp | // Copyright: 2021 - 2022, Ziemas
// SPDX-License-Identifier: ISC
#include "synth.h"
#include <stdexcept>
namespace snd {
static s16 ApplyVolume(s16 sample, s32 volume) {
return (sample * volume) >> 15;
}
s16_output synth::tick() {
s16_output out{};
m_voices.remove_if([](std::shared_ptr<voice>& v) { return v->dead(); });
for (auto& v : m_voices) {
out += v->run();
}
out.left = ApplyVolume(out.left, m_Volume.left.Get());
out.right = ApplyVolume(out.right, m_Volume.right.Get());
m_Volume.Run();
return out;
}
void synth::add_voice(std::shared_ptr<voice> voice) {
m_voices.emplace_front(voice);
}
void synth::set_master_vol(u32 volume) {
m_Volume.left.Set(volume);
m_Volume.right.Set(volume);
}
} // namespace snd
| [
"noreply@github.com"
] | open-goal.noreply@github.com |
672f436717c64f5dbb4b456dc9e895ce30218313 | b38063d6700559ba059ee6e04034352d34620d24 | /tests/pair_extraction.cc | 69f2ba2ff7899c3ad3b601c4372a6a6b207e73d7 | [
"Apache-2.0"
] | permissive | kaorun55/Super4PCS | 6bcfe12068c3e0b154a26447b510d1336209d4b3 | 355c8f8d2af49f97c561d15e02632d55420a1127 | refs/heads/master | 2021-01-17T10:40:01.186462 | 2015-05-11T14:35:39 | 2015-05-11T14:35:39 | 30,953,909 | 0 | 0 | null | 2015-02-18T05:49:06 | 2015-02-18T05:49:04 | C++ | UTF-8 | C++ | false | false | 8,237 | cc | // Copyright 2014 Nicolas Mellado
//
// 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.
//
// -------------------------------------------------------------------------- //
//
// Authors: Nicolas Mellado
//
// This test check the validity of the pair extraction subroutine on random data
// of different dimensions (2,3 and 4).
//
//
// This test is part of the implementation of the Super 4-points Congruent Sets
// (Super 4PCS) algorithm presented in:
//
// Super 4PCS: Fast Global Pointcloud Registration via Smart Indexing
// Nicolas Mellado, Dror Aiger, Niloy J. Mitra
// Symposium on Geometry Processing 2014.
//
// Data acquisition in large-scale scenes regularly involves accumulating
// information across multiple scans. A common approach is to locally align scan
// pairs using Iterative Closest Point (ICP) algorithm (or its variants), but
// requires static scenes and small motion between scan pairs. This prevents
// accumulating data across multiple scan sessions and/or different acquisition
// modalities (e.g., stereo, depth scans). Alternatively, one can use a global
// registration algorithm allowing scans to be in arbitrary initial poses. The
// state-of-the-art global registration algorithm, 4PCS, however has a quadratic
// time complexity in the number of data points. This vastly limits its
// applicability to acquisition of large environments. We present Super 4PCS for
// global pointcloud registration that is optimal, i.e., runs in linear time (in
// the number of data points) and is also output sensitive in the complexity of
// the alignment problem based on the (unknown) overlap across scan pairs.
// Technically, we map the algorithm as an ‘instance problem’ and solve it
// efficiently using a smart indexing data organization. The algorithm is
// simple, memory-efficient, and fast. We demonstrate that Super 4PCS results in
// significant speedup over alternative approaches and allows unstructured
// efficient acquisition of scenes at scales previously not possible. Complete
// source code and datasets are available for research use at
// http://geometry.cs.ucl.ac.uk/projects/2014/super4PCS/.
#include "4pcs.h"
#include "Eigen/Dense"
#include <fstream>
#include <iostream>
#include <string>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/eigen.hpp>
#include "accelerators/pairExtraction/intersectionFunctor.h"
#include "accelerators/pairExtraction/intersectionPrimitive.h"
#include "bbox.h"
#include <sys/time.h>
#include <unistd.h>
#include <stdlib.h>
#include <utility> // pair
#include "testing.h"
//#include "normalset.h"
//#include "normalHealSet.h"
using namespace match_4pcs;
namespace Utilities{
static double Timer_getTime(void)
{
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
return (double)tv.tv_sec + 1.e-6 * (double)tv.tv_usec;
}
typedef double Timer;
static inline void startTimer(Timer& timer) { timer = Timer_getTime(); }
static inline void stopTimer(Timer& timer) { timer = Timer_getTime() - timer; }
}
struct PairCreationFunctor{
typedef std::pair<unsigned int, unsigned int>ResPair;
std::vector< ResPair >pairs;
std::vector<unsigned int> ids;
inline void beginPrimitiveCollect(int primId){
}
inline void endPrimitiveCollect(int primId){
}
inline void process(int primId, int pointId){
//if(pointId >= 10)
pairs.push_back(ResPair(pointId, primId));
}
};
/*!
* \brief Generate a set of random points and spheres, and test the pair extraction
Two tests are operated here:
- Check the validity of the sphere to point intersection test
- Check the rendering
Note here that rendering timings are not optimal because we have a volume
uniformly sampled and not a surface.
*/
template<typename Scalar, typename Point, typename Primitive, typename Functor>
void testFunction( Scalar r, Scalar epsilon,
unsigned int nbPoints, unsigned int nbPrimitives){
// Init required structures
Utilities::Timer t;
std::vector< std::pair<unsigned int, unsigned int> > p2;
p2.reserve(nbPoints*nbPrimitives);
PairCreationFunctor functor;
functor.ids.clear();
for(unsigned int i = 0; i < nbPoints; i++)
functor.ids.push_back(i);
functor.pairs.reserve(nbPoints*nbPrimitives);
// Init Random Positions
std::vector<Point> points;
Point half (Point::Ones()/2.f);
for(unsigned int i = 0; i != nbPoints; i++){
Point p (0.5f*Point::Random() + half);
points.push_back(p);
}
// Init random Spheres
std::vector<Primitive> primitives;
for(unsigned int i = 0; i != nbPrimitives; i++){
Point p (0.5f*Point::Random() + half);
primitives.push_back(Primitive(p, r));
}
// Test test intersection procedure
// Here we compare the brute force pair extraction and the sphere to point
// intersection procedure
{
Primitive& sphere = primitives.front();
for(unsigned int i = 0; i != nbPoints; i++){
const Point&p = points[i];
VERIFY( sphere.intersectPoint(p, epsilon) ==
SQR((p - sphere.center()).norm()- sphere.radius()) < SQR(epsilon));
}
}
// Test Rendering process
{
Functor IF;
// Extract pairs using rendering process
Utilities::startTimer(t);
IF.process(primitives, points, epsilon, 20, functor);
Utilities::stopTimer(t);
// Extract pairs using brute force
Utilities::startTimer(t);
for(unsigned int i = 0; i != nbPoints; i++)
for(unsigned int j = i+1; j < primitives.size(); j++)
if (primitives[j].intersectPoint(points[i], epsilon))
p2.push_back(std::pair<unsigned int, unsigned int>(i,j));
Utilities::stopTimer(t);
// Check we get the same set size
VERIFY( functor.pairs.size() == p2.size());
}
}
template<typename Scalar,
int Dim,
template <typename,typename,int,typename> class _Functor>
void callSubTests()
{
using namespace Super4PCS::Accelerators::PairExtraction;
typedef Eigen::Matrix<Scalar, Dim, 1> EigenPoint;
typedef HyperSphere< EigenPoint, Dim, Scalar > Sphere;
typedef _Functor<Sphere, EigenPoint, Dim, Scalar> Functor;
Scalar r = 0.5; // radius of the spheres
Scalar eps = 0.125/8.; // epsilon value
unsigned int nbPoint = 10000; // size of Q point cloud
unsigned int nbPrim = 500; // number of primitive queries
for(int i = 0; i < g_repeat; ++i)
{
CALL_SUBTEST(( testFunction<Scalar,
EigenPoint,
Sphere,
Functor>(r, eps, nbPoint, nbPrim) ));
}
}
int main(int argc, char **argv) {
if(!init_testing(argc, argv))
{
return EXIT_FAILURE;
}
using std::cout;
using std::endl;
using namespace Super4PCS::Accelerators::PairExtraction;
cout << "Extract pairs in 2 dimensions..." << endl;
callSubTests<float, 2, IntersectionFunctor>();
callSubTests<double, 2, IntersectionFunctor>();
callSubTests<long double, 2, IntersectionFunctor>();
cout << "Ok..." << endl;
cout << "Extract pairs in 3 dimensions..." << endl;
callSubTests<float, 3, IntersectionFunctor>();
callSubTests<double, 3, IntersectionFunctor>();
callSubTests<long double, 3, IntersectionFunctor>();
cout << "Ok..." << endl;
cout << "Extract pairs in 4 dimensions..." << endl;
callSubTests<float, 4, IntersectionFunctor>();
callSubTests<double, 4, IntersectionFunctor>();
callSubTests<long double, 4, IntersectionFunctor>();
cout << "Ok..." << endl;
return EXIT_SUCCESS;
}
| [
"nmellado0@gmail.com"
] | nmellado0@gmail.com |
5bd4d1d9ead0fa6e20698b2465724c2ce61804c6 | db51654c39a6e0fedb36a040cba7534dd214db6e | /pointers.h | a2ee72303959a540e77003b216816ee2edf8fef8 | [] | no_license | KirillOvs/ComplexSession | 62f43b4ad56374a68a3b580da028daa3ea81e682 | ec55909e0ae9ca4f62373b1119749595fc11db98 | refs/heads/master | 2020-05-03T21:31:24.590152 | 2019-04-01T14:46:53 | 2019-04-01T14:46:53 | 178,825,312 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 331 | h | #ifndef POINTERS_H
#define POINTERS_H
#include <memory>
#include "range.h"
struct ScheduleData;
using ScheduleDataPtr = std::shared_ptr<ScheduleData>;
class ScheduleItem;
using ScheduleItemPtr = std::unique_ptr<const ScheduleItem>;
class Worker;
using WorkerPtr = std::unique_ptr<Worker>;
#endif // POINTERS_H
| [
"ovseychuk@ukr.net"
] | ovseychuk@ukr.net |
7db574a144e2397c6e7dfe20effffe5984394963 | 95613a70265e6871c25a4be18075c180427d0980 | /src/walletdb.h | a48bd7687e94042830962e89e7d8da4340e35d3a | [
"MIT"
] | permissive | CryptoLover705/NocNoc | 394b7426a25a0b048fb5e2ae6c02b5f75099189e | fafa860f29c63d7357721a231fef7ad314355263 | refs/heads/master | 2023-02-11T04:11:49.555586 | 2021-01-01T00:21:57 | 2021-01-01T00:21:57 | 318,871,415 | 1 | 0 | MIT | 2020-12-05T19:25:13 | 2020-12-05T19:25:12 | null | UTF-8 | C++ | false | false | 6,297 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Copyright (c) 2016-2017 The PIVX developers
// Copyright (c) 2016-2019 The NocNoc developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_WALLETDB_H
#define BITCOIN_WALLETDB_H
#include "amount.h"
#include "db.h"
#include "key.h"
#include "keystore.h"
#include "primitives/zerocoin.h"
#include "libzerocoin/Accumulator.h"
#include "libzerocoin/Denominations.h"
#include <list>
#include <stdint.h>
#include <string>
#include <utility>
#include <vector>
class CAccount;
class CAccountingEntry;
struct CBlockLocator;
class CKeyPool;
class CMasterKey;
class CScript;
class CWallet;
class CWalletTx;
class CZerocoinMint;
class CZerocoinSpend;
class uint160;
class uint256;
/** Error statuses for the wallet database */
enum DBErrors {
DB_LOAD_OK,
DB_CORRUPT,
DB_NONCRITICAL_ERROR,
DB_TOO_NEW,
DB_LOAD_FAIL,
DB_NEED_REWRITE
};
class CKeyMetadata
{
public:
static const int CURRENT_VERSION = 1;
int nVersion;
int64_t nCreateTime; // 0 means unknown
CKeyMetadata()
{
SetNull();
}
CKeyMetadata(int64_t nCreateTime_)
{
nVersion = CKeyMetadata::CURRENT_VERSION;
nCreateTime = nCreateTime_;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(nCreateTime);
}
void SetNull()
{
nVersion = CKeyMetadata::CURRENT_VERSION;
nCreateTime = 0;
}
};
/** Access to the wallet database (wallet.dat) */
class CWalletDB : public CDB
{
public:
CWalletDB(const std::string& strFilename, const char* pszMode = "r+") : CDB(strFilename, pszMode)
{
}
bool WriteName(const std::string& strAddress, const std::string& strName);
bool EraseName(const std::string& strAddress);
bool WritePurpose(const std::string& strAddress, const std::string& purpose);
bool ErasePurpose(const std::string& strAddress);
bool WriteTx(uint256 hash, const CWalletTx& wtx);
bool EraseTx(uint256 hash);
bool WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta);
bool WriteCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret, const CKeyMetadata& keyMeta);
bool WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey);
bool WriteCScript(const uint160& hash, const CScript& redeemScript);
bool WriteWatchOnly(const CScript& script);
bool EraseWatchOnly(const CScript& script);
bool WriteMultiSig(const CScript& script);
bool EraseMultiSig(const CScript& script);
bool WriteBestBlock(const CBlockLocator& locator);
bool ReadBestBlock(CBlockLocator& locator);
bool WriteOrderPosNext(int64_t nOrderPosNext);
// presstab
bool WriteStakeSplitThreshold(uint64_t nStakeSplitThreshold);
bool WriteMultiSend(std::vector<std::pair<std::string, int> > vMultiSend);
bool EraseMultiSend(std::vector<std::pair<std::string, int> > vMultiSend);
bool WriteMSettings(bool fMultiSendStake, bool fMultiSendMasternode, int nLastMultiSendHeight);
bool WriteMSDisabledAddresses(std::vector<std::string> vDisabledAddresses);
bool EraseMSDisabledAddresses(std::vector<std::string> vDisabledAddresses);
bool WriteAutoCombineSettings(bool fEnable, CAmount nCombineThreshold);
bool WriteDefaultKey(const CPubKey& vchPubKey);
bool ReadPool(int64_t nPool, CKeyPool& keypool);
bool WritePool(int64_t nPool, const CKeyPool& keypool);
bool ErasePool(int64_t nPool);
bool WriteMinVersion(int nVersion);
/// This writes directly to the database, and will not update the CWallet's cached accounting entries!
/// Use wallet.AddAccountingEntry instead, to write *and* update its caches.
bool WriteAccountingEntry_Backend(const CAccountingEntry& acentry);
bool ReadAccount(const std::string& strAccount, CAccount& account);
bool WriteAccount(const std::string& strAccount, const CAccount& account);
/// Write destination data key,value tuple to database
bool WriteDestData(const std::string& address, const std::string& key, const std::string& value);
/// Erase destination data tuple from wallet database
bool EraseDestData(const std::string& address, const std::string& key);
CAmount GetAccountCreditDebit(const std::string& strAccount);
void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& acentries);
DBErrors ReorderTransactions(CWallet* pwallet);
DBErrors LoadWallet(CWallet* pwallet);
DBErrors FindWalletTx(CWallet* pwallet, std::vector<uint256>& vTxHash, std::vector<CWalletTx>& vWtx);
DBErrors ZapWalletTx(CWallet* pwallet, std::vector<CWalletTx>& vWtx);
static bool Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys);
static bool Recover(CDBEnv& dbenv, std::string filename);
bool WriteZerocoinMint(const CZerocoinMint& zerocoinMint);
bool EraseZerocoinMint(const CZerocoinMint& zerocoinMint);
bool ReadZerocoinMint(const CBigNum &bnSerial, CZerocoinMint& zerocoinMint);
bool ArchiveMintOrphan(const CZerocoinMint& zerocoinMint);
bool UnarchiveZerocoin(const CZerocoinMint& mint);
std::list<CZerocoinMint> ListMintedCoins(bool fUnusedOnly, bool fMaturedOnly, bool fUpdateStatus);
std::list<CZerocoinSpend> ListSpentCoins();
std::list<CBigNum> ListMintedCoinsSerial();
std::list<CBigNum> ListSpentCoinsSerial();
std::list<CZerocoinMint> ListArchivedZerocoins();
bool WriteZerocoinSpendSerialEntry(const CZerocoinSpend& zerocoinSpend);
bool EraseZerocoinSpendSerialEntry(const CBigNum& serialEntry);
bool ReadZerocoinSpendSerialEntry(const CBigNum& bnSerial);
private:
CWalletDB(const CWalletDB&);
void operator=(const CWalletDB&);
bool WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry);
};
bool BackupWallet(const CWallet& wallet, const std::string& strDest);
#endif // BITCOIN_WALLETDB_H
| [
"edward.thomas3@yahoo.com"
] | edward.thomas3@yahoo.com |
4a6fc8b0033f0d208ceea802eace5fa6dcc7d726 | cd53591c82fc4b78635db88d7b48cff95b2d75f7 | /Alien.hpp | 1e7a4ffc0ec31bb651dc1e0bede262cf5ee8d7c6 | [] | no_license | taylor-jones/Fly-Away-Home | da439d3856068c39544d7255091fbf394a3403df | 14036d29c6ef719327cc9043b269d313b968689c | refs/heads/master | 2020-03-26T15:25:19.335305 | 2019-01-15T01:19:04 | 2019-01-15T01:19:04 | 145,041,889 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,568 | hpp | /**********************************************************
** Program Name: final project
** Author: Taylor Jones
** Date: 3/6/2018
** Description: Alien.hpp is the Alien class
** specification file. This file contains declarations
** for the member variables and member functions of
** the Alien class.
**********************************************************/
#ifndef ALIEN_HPP
#define ALIEN_HPP
#include "Element.hpp"
#include "Bag.hpp"
#include "Earthling.hpp"
class Alien: public Element {
private:
//
// member variables
//
bool backHome = false;
int homeLevel = -1;
int cash = 0;
int points = 0;
int rank = 1;
string rankName = "Weiner";
int maxEnergy = 100;
int energy = 100;
int energyMarker = 100;
int livesRemaining = 3;
int activeItemStepsRemaining = 0;
private:
std::vector<string>menuOpts;
Bag* bag = nullptr;
Bag* shipPieces = nullptr;
Item* activeItem = nullptr;
Item* nonBagItem = nullptr;
Space* prevSpace = nullptr;
Island* homeland = nullptr;
//
// member functions
//
int nextRankPoints();
void depleteActiveItem();
void checkForwardExperiences();
public:
// object handling
Alien();
explicit Alien(int homeLevel);
~Alien() override;
void init();
// getters
int getCash() const;
int getPoints() const;
int getRank() const;
int getEnergy() const;
int getEnergyMarker() const;
int getLivesRemaining() const;
int getHomeLevel() const;
int getActiveItemStepsRemaining() const;
int getMaxEnergy() const;
bool isAlive();
const string &getRankName() const;
string getOrientationString() const;
Item* getActiveItem() const;
Item* getNonBagItem() const;
Space* getPrevSpace() const;
Bag* getBag() const;
Bag* getShipPieces() const;
Island* getHomeland() const;
// setters
void setCash(int cash);
void setPoints(int points);
void setRank(int rankNumber);
void setRankName(const string &rankName);
void setBag(Bag* bag);
void setLivesRemaining(int livesRemaining);
void setActiveItem(Item* currentItem);
void setEnergy(int energy);
void setHomeLevel(int homeLevel);
void setEnergyMarker();
void setPrevSpace(Space* prevSpace);
void setHomeland(Island* homeland);
void setNonBagItem(Item* nonBagItem);
void setMaxEnergy(int maxEnergy);
void adjustPoints(int amount);
void adjustCash(int amount);
void adjustEnergy(int amount, bool bypassMax = false);
void setActiveItemStepsRemaining(int activeItemStepsRemaining);
// activity
void interact(Element* actor) override;
void experienceSpace(Direction direction = NO_DIRECTION);
void interactWithElements(Direction direction = NO_DIRECTION);
void interactWithEarthling(Earthling* earthling);
void checkDropBagItem(Item* replaceWithItem = nullptr);
void checkPickupBagItem(Item* newItem = nullptr);
void checkUseBagItem();
bool checkBuyMaps(int price);
bool move(Direction direction) override;
bool move(Space* space) override;
void checkIfBackHome();
void checkRestoreEnergy();
bool checkRestoreEnergy(int price);
void getBittenByShark();
void eatFood(Item* food);
bool findShipPiece(Item* piece);
void flyHome(Item* spaceship);
void pickupMoney(Item* money);
void restoreEnergy();
void printStats(bool showSurroundings = true);
void showMenu();
void uncoverAdjacentSpaces();
};
#endif //ALIEN_HPP
| [
"taylorjonesdev@gmail.com"
] | taylorjonesdev@gmail.com |
8ccbe77e6ba41d09784f91a8dedc586432102424 | c50c30e511946ddb660a2e25bfb81376faad6d08 | /src/qt/addresstablemodel.cpp | 9097ab9b549dde917109c761c7a7d2cf653d2427 | [
"MIT"
] | permissive | ultranatum/ultragate | e52fd316761fde9996f52e7e98ddf7475d915a88 | b4773b11f358932cbdbd8f738b0648bd4ee5f385 | refs/heads/master | 2022-07-23T21:26:27.488403 | 2022-06-21T11:27:42 | 2022-06-21T11:27:42 | 175,899,669 | 4 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 16,172 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2019 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "addresstablemodel.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "base58.h"
#include "wallet/wallet.h"
#include "askpassphrasedialog.h"
#include <QDebug>
#include <QFont>
const QString AddressTableModel::Send = "S";
const QString AddressTableModel::Receive = "R";
const QString AddressTableModel::Zerocoin = "X";
struct AddressTableEntry {
enum Type {
Sending,
Receiving,
Zerocoin,
Hidden /* QSortFilterProxyModel will filter these out */
};
Type type;
QString label;
QString address;
QString pubcoin;
AddressTableEntry() {}
AddressTableEntry(Type type, const QString &pubcoin): type(type), pubcoin(pubcoin) {}
AddressTableEntry(Type type, const QString& label, const QString& address) : type(type), label(label), address(address) {}
};
struct AddressTableEntryLessThan {
bool operator()(const AddressTableEntry& a, const AddressTableEntry& b) const
{
return a.address < b.address;
}
bool operator()(const AddressTableEntry& a, const QString& b) const
{
return a.address < b;
}
bool operator()(const QString& a, const AddressTableEntry& b) const
{
return a < b.address;
}
};
/* Determine address type from address purpose */
static AddressTableEntry::Type translateTransactionType(const QString& strPurpose, bool isMine)
{
AddressTableEntry::Type addressType = AddressTableEntry::Hidden;
// "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all.
if (strPurpose == "send")
addressType = AddressTableEntry::Sending;
else if (strPurpose == "receive")
addressType = AddressTableEntry::Receiving;
else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess
addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending);
return addressType;
}
// Private implementation
class AddressTablePriv
{
public:
CWallet* wallet;
QList<AddressTableEntry> cachedAddressTable;
AddressTableModel* parent;
AddressTablePriv(CWallet* wallet, AddressTableModel* parent) : wallet(wallet), parent(parent) {}
void refreshAddressTable()
{
cachedAddressTable.clear();
{
LOCK(wallet->cs_wallet);
for (const PAIRTYPE(CTxDestination, CAddressBookData) & item : wallet->mapAddressBook) {
const CBitcoinAddress& address = item.first;
bool fMine = IsMine(*wallet, address.Get());
AddressTableEntry::Type addressType = translateTransactionType(
QString::fromStdString(item.second.purpose), fMine);
const std::string& strName = item.second.name;
cachedAddressTable.append(AddressTableEntry(addressType,
QString::fromStdString(strName),
QString::fromStdString(address.ToString())));
}
}
// qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order
// Even though the map is already sorted this re-sorting step is needed because the originating map
// is sorted by binary address, not by base58() address.
qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan());
}
void updateEntry(const QString& address, const QString& label, bool isMine, const QString& purpose, int status)
{
// Find address / label in model
QList<AddressTableEntry>::iterator lower = qLowerBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
QList<AddressTableEntry>::iterator upper = qUpperBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
int lowerIndex = (lower - cachedAddressTable.begin());
int upperIndex = (upper - cachedAddressTable.begin());
bool inModel = (lower != upper);
AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine);
switch (status) {
case CT_NEW:
if (inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_NEW, but entry is already in model";
break;
}
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address));
parent->endInsertRows();
break;
case CT_UPDATED:
if (!inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_UPDATED, but entry is not in model";
break;
}
lower->type = newEntryType;
lower->label = label;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
if (!inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_DELETED, but entry is not in model";
break;
}
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex - 1);
cachedAddressTable.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
void updateEntry(const QString &pubCoin, const QString &isUsed, int status)
{
// Find address / label in model
QList<AddressTableEntry>::iterator lower = qLowerBound(
cachedAddressTable.begin(), cachedAddressTable.end(), pubCoin, AddressTableEntryLessThan());
QList<AddressTableEntry>::iterator upper = qUpperBound(
cachedAddressTable.begin(), cachedAddressTable.end(), pubCoin, AddressTableEntryLessThan());
int lowerIndex = (lower - cachedAddressTable.begin());
bool inModel = (lower != upper);
AddressTableEntry::Type newEntryType = AddressTableEntry::Zerocoin;
switch(status)
{
case CT_NEW:
if(inModel)
{
qWarning() << "AddressTablePriv_ZC::updateEntry : Warning: Got CT_NEW, but entry is already in model";
}
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, isUsed, pubCoin));
parent->endInsertRows();
break;
case CT_UPDATED:
if(!inModel)
{
qWarning() << "AddressTablePriv_ZC::updateEntry : Warning: Got CT_UPDATED, but entry is not in model";
break;
}
lower->type = newEntryType;
lower->label = isUsed;
parent->emitDataChanged(lowerIndex);
break;
}
}
int size()
{
return cachedAddressTable.size();
}
AddressTableEntry* index(int idx)
{
if (idx >= 0 && idx < cachedAddressTable.size()) {
return &cachedAddressTable[idx];
} else {
return 0;
}
}
};
AddressTableModel::AddressTableModel(CWallet* wallet, WalletModel* parent) : QAbstractTableModel(parent), walletModel(parent), wallet(wallet), priv(0)
{
columns << tr("Label") << tr("Address");
priv = new AddressTablePriv(wallet, this);
priv->refreshAddressTable();
}
AddressTableModel::~AddressTableModel()
{
delete priv;
}
int AddressTableModel::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int AddressTableModel::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant AddressTableModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
if (role == Qt::DisplayRole || role == Qt::EditRole) {
switch (index.column()) {
case Label:
if (rec->label.isEmpty() && role == Qt::DisplayRole) {
return tr("(no label)");
} else {
return rec->label;
}
case Address:
return rec->address;
}
} else if (role == Qt::FontRole) {
QFont font;
if (index.column() == Address) {
font = GUIUtil::bitcoinAddressFont();
}
return font;
} else if (role == TypeRole) {
switch (rec->type) {
case AddressTableEntry::Sending:
return Send;
case AddressTableEntry::Receiving:
return Receive;
default:
break;
}
}
return QVariant();
}
bool AddressTableModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (!index.isValid())
return false;
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive");
editStatus = OK;
if (role == Qt::EditRole) {
LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */
CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get();
if (index.column() == Label) {
// Do nothing, if old label == new label
if (rec->label == value.toString()) {
editStatus = NO_CHANGES;
return false;
}
wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose);
} else if (index.column() == Address) {
CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get();
// Refuse to set invalid address, set error status and return false
if (boost::get<CNoDestination>(&newAddress)) {
editStatus = INVALID_ADDRESS;
return false;
}
// Do nothing, if old address == new address
else if (newAddress == curAddress) {
editStatus = NO_CHANGES;
return false;
}
// Check for duplicate addresses to prevent accidental deletion of addresses, if you try
// to paste an existing address over another address (with a different label)
else if (wallet->mapAddressBook.count(newAddress)) {
editStatus = DUPLICATE_ADDRESS;
return false;
}
// Double-check that we're not overwriting a receiving address
else if (rec->type == AddressTableEntry::Sending) {
// Remove old entry
wallet->DelAddressBook(curAddress);
// Add new entry with new address
wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose);
}
}
return true;
}
return false;
}
QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal) {
if (role == Qt::DisplayRole && section < columns.size()) {
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags AddressTableModel::flags(const QModelIndex& index) const
{
if (!index.isValid())
return 0;
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
// Can edit address and label for sending addresses,
// and only label for receiving addresses.
if (rec->type == AddressTableEntry::Sending ||
(rec->type == AddressTableEntry::Receiving && index.column() == Label)) {
retval |= Qt::ItemIsEditable;
}
return retval;
}
QModelIndex AddressTableModel::index(int row, int column, const QModelIndex& parent) const
{
Q_UNUSED(parent);
AddressTableEntry* data = priv->index(row);
if (data) {
return createIndex(row, column, priv->index(row));
} else {
return QModelIndex();
}
}
void AddressTableModel::updateEntry(const QString& address,
const QString& label,
bool isMine,
const QString& purpose,
int status)
{
// Update address book model from Ultragate core
priv->updateEntry(address, label, isMine, purpose, status);
}
void AddressTableModel::updateEntry(const QString &pubCoin, const QString &isUsed, int status)
{
// Update stealth address book model from Bitcoin core
priv->updateEntry(pubCoin, isUsed, status);
}
QString AddressTableModel::addRow(const QString& type, const QString& label, const QString& address)
{
std::string strLabel = label.toStdString();
std::string strAddress = address.toStdString();
editStatus = OK;
if (type == Send) {
if (!walletModel->validateAddress(address)) {
editStatus = INVALID_ADDRESS;
return QString();
}
// Check for duplicate addresses
{
LOCK(wallet->cs_wallet);
if (wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get())) {
editStatus = DUPLICATE_ADDRESS;
return QString();
}
}
} else if (type == Receive) {
// Generate a new address to associate with given label
CPubKey newKey;
if (!wallet->GetKeyFromPool(newKey)) {
WalletModel::UnlockContext ctx(walletModel->requestUnlock(AskPassphraseDialog::Context::Unlock_Full, true));
if (!ctx.isValid()) {
// Unlock wallet failed or was cancelled
editStatus = WALLET_UNLOCK_FAILURE;
return QString();
}
if (!wallet->GetKeyFromPool(newKey)) {
editStatus = KEY_GENERATION_FAILURE;
return QString();
}
}
strAddress = CBitcoinAddress(newKey.GetID()).ToString();
} else {
return QString();
}
// Add entry
{
LOCK(wallet->cs_wallet);
wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel,
(type == Send ? "send" : "receive"));
}
return QString::fromStdString(strAddress);
}
bool AddressTableModel::removeRows(int row, int count, const QModelIndex& parent)
{
Q_UNUSED(parent);
AddressTableEntry* rec = priv->index(row);
if (count != 1 || !rec || rec->type == AddressTableEntry::Receiving) {
// Can only remove one row at a time, and cannot remove rows not in model.
// Also refuse to remove receiving addresses.
return false;
}
{
LOCK(wallet->cs_wallet);
wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get());
}
return true;
}
/* Look up label for address in address book, if not found return empty string.
*/
QString AddressTableModel::labelForAddress(const QString& address) const
{
{
LOCK(wallet->cs_wallet);
CBitcoinAddress address_parsed(address.toStdString());
std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get());
if (mi != wallet->mapAddressBook.end()) {
return QString::fromStdString(mi->second.name);
}
}
return QString();
}
int AddressTableModel::lookupAddress(const QString& address) const
{
QModelIndexList lst = match(index(0, Address, QModelIndex()),
Qt::EditRole, address, 1, Qt::MatchExactly);
if (lst.isEmpty()) {
return -1;
} else {
return lst.at(0).row();
}
}
void AddressTableModel::emitDataChanged(int idx)
{
emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length() - 1, QModelIndex()));
}
| [
"ultranatum@web.de"
] | ultranatum@web.de |
9b3d91a76c50953d806ac99c64632bf1406567db | 6db8ebd5b071a349de6a15c1e6fc1e27a0987cd1 | /Drivers/libuavcan/root_ns_a/B.hpp | 12b1d026f163386aaa06c515d8f4f638584e2f9a | [] | no_license | RuslanUrya/nucleo_power_uavcan | 163ea518aaf25d68adb310ac51c51668c2ffa985 | ee34900a4b8f83bf3a0855fa0c58a47de9df17af | refs/heads/master | 2022-12-24T18:52:38.874759 | 2020-10-06T08:56:11 | 2020-10-06T08:56:11 | 283,022,531 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,252 | hpp | /*
* UAVCAN data structure definition for libuavcan.
*
* Autogenerated, do not edit.
*
* Source file: /home/acyc/src/libuavcan/libuavcan/test/dsdl_test/root_ns_a/B.uavcan
*/
#ifndef ROOT_NS_A_B_HPP_INCLUDED
#define ROOT_NS_A_B_HPP_INCLUDED
#include <uavcan/build_config.hpp>
#include <uavcan/node/global_data_type_registry.hpp>
#include <uavcan/marshal/types.hpp>
/******************************* Source text **********************************
float64[2] vector
bool[16] bools
******************************************************************************/
/********************* DSDL signature source definition ***********************
root_ns_a.B
saturated float64[2] vector
saturated bool[16] bools
******************************************************************************/
#undef vector
#undef bools
namespace root_ns_a
{
template <int _tmpl>
struct UAVCAN_EXPORT B_
{
typedef const B_<_tmpl>& ParameterType;
typedef B_<_tmpl>& ReferenceType;
struct ConstantTypes
{
};
struct FieldTypes
{
typedef ::uavcan::Array< ::uavcan::FloatSpec< 64, ::uavcan::CastModeSaturate >, ::uavcan::ArrayModeStatic, 2 > vector;
typedef ::uavcan::Array< ::uavcan::IntegerSpec< 1, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate >, ::uavcan::ArrayModeStatic, 16 > bools;
};
enum
{
MinBitLen
= FieldTypes::vector::MinBitLen
+ FieldTypes::bools::MinBitLen
};
enum
{
MaxBitLen
= FieldTypes::vector::MaxBitLen
+ FieldTypes::bools::MaxBitLen
};
// Constants
// Fields
typename ::uavcan::StorageType< typename FieldTypes::vector >::Type vector;
typename ::uavcan::StorageType< typename FieldTypes::bools >::Type bools;
B_()
: vector()
, bools()
{
::uavcan::StaticAssert<_tmpl == 0>::check(); // Usage check
#if UAVCAN_DEBUG
/*
* Cross-checking MaxBitLen provided by the DSDL compiler.
* This check shall never be performed in user code because MaxBitLen value
* actually depends on the nested types, thus it is not invariant.
*/
::uavcan::StaticAssert<144 == MaxBitLen>::check();
#endif
}
bool operator==(ParameterType rhs) const;
bool operator!=(ParameterType rhs) const { return !operator==(rhs); }
/**
* This comparison is based on @ref uavcan::areClose(), which ensures proper comparison of
* floating point fields at any depth.
*/
bool isClose(ParameterType rhs) const;
static int encode(ParameterType self, ::uavcan::ScalarCodec& codec,
::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled);
static int decode(ReferenceType self, ::uavcan::ScalarCodec& codec,
::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled);
/*
* Static type info
*/
enum { DataTypeKind = ::uavcan::DataTypeKindMessage };
// This type has no default data type ID
static const char* getDataTypeFullName()
{
return "root_ns_a.B";
}
static void extendDataTypeSignature(::uavcan::DataTypeSignature& signature)
{
signature.extend(getDataTypeSignature());
}
static ::uavcan::DataTypeSignature getDataTypeSignature();
};
/*
* Out of line struct method definitions
*/
template <int _tmpl>
bool B_<_tmpl>::operator==(ParameterType rhs) const
{
return
vector == rhs.vector &&
bools == rhs.bools;
}
template <int _tmpl>
bool B_<_tmpl>::isClose(ParameterType rhs) const
{
return
::uavcan::areClose(vector, rhs.vector) &&
::uavcan::areClose(bools, rhs.bools);
}
template <int _tmpl>
int B_<_tmpl>::encode(ParameterType self, ::uavcan::ScalarCodec& codec,
::uavcan::TailArrayOptimizationMode tao_mode)
{
(void)self;
(void)codec;
(void)tao_mode;
int res = 1;
res = FieldTypes::vector::encode(self.vector, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::bools::encode(self.bools, codec, tao_mode);
return res;
}
template <int _tmpl>
int B_<_tmpl>::decode(ReferenceType self, ::uavcan::ScalarCodec& codec,
::uavcan::TailArrayOptimizationMode tao_mode)
{
(void)self;
(void)codec;
(void)tao_mode;
int res = 1;
res = FieldTypes::vector::decode(self.vector, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::bools::decode(self.bools, codec, tao_mode);
return res;
}
/*
* Out of line type method definitions
*/
template <int _tmpl>
::uavcan::DataTypeSignature B_<_tmpl>::getDataTypeSignature()
{
::uavcan::DataTypeSignature signature(0xCE758EF6221573DULL);
FieldTypes::vector::extendDataTypeSignature(signature);
FieldTypes::bools::extendDataTypeSignature(signature);
return signature;
}
/*
* Out of line constant definitions
*/
/*
* Final typedef
*/
typedef B_<0> B;
// No default registration
} // Namespace root_ns_a
/*
* YAML streamer specialization
*/
namespace uavcan
{
template <>
class UAVCAN_EXPORT YamlStreamer< ::root_ns_a::B >
{
public:
template <typename Stream>
static void stream(Stream& s, ::root_ns_a::B::ParameterType obj, const int level);
};
template <typename Stream>
void YamlStreamer< ::root_ns_a::B >::stream(Stream& s, ::root_ns_a::B::ParameterType obj, const int level)
{
(void)s;
(void)obj;
(void)level;
if (level > 0)
{
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
}
s << "vector: ";
YamlStreamer< ::root_ns_a::B::FieldTypes::vector >::stream(s, obj.vector, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "bools: ";
YamlStreamer< ::root_ns_a::B::FieldTypes::bools >::stream(s, obj.bools, level + 1);
}
}
namespace root_ns_a
{
template <typename Stream>
inline Stream& operator<<(Stream& s, ::root_ns_a::B::ParameterType obj)
{
::uavcan::YamlStreamer< ::root_ns_a::B >::stream(s, obj, 0);
return s;
}
} // Namespace root_ns_a
#endif // ROOT_NS_A_B_HPP_INCLUDED
| [
"ruslikc@gmail.om"
] | ruslikc@gmail.om |
188c99879752898ffb4adcaec1b65ac6e7394a41 | 08cb51dc2ccf77dfec50851664367eefa78afb32 | /day04/ex01/PlasmaRifle.cpp | eb1e0fbccb1eca008a0ff45c4eab9c533db75d37 | [] | no_license | acarlson99/piscine-cpp | f251a5662e5509f4ca8d6c0d4b737655e10a4820 | 86f926d046e7cac139e7ed28b9a9ed4af80dd6bd | refs/heads/master | 2020-04-17T16:32:36.547220 | 2019-02-05T03:11:49 | 2019-02-05T03:11:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,321 | cpp | // ************************************************************************** //
// //
// ::: :::::::: //
// PlasmaRifle.cpp :+: :+: :+: //
// +:+ +:+ +:+ //
// By: acarlson <marvin@42.fr> +#+ +:+ +#+ //
// +#+#+#+#+#+ +#+ //
// Created: 2019/01/25 14:32:42 by acarlson #+# #+# //
// Updated: 2019/01/25 19:32:14 by acarlson ### ########.fr //
// //
// ************************************************************************** //
#include "PlasmaRifle.hpp"
std::string PlasmaRifle::_dname = std::string("PlasmaRifle");
PlasmaRifle::PlasmaRifle( void ) : AWeapon(_dname, 5, 21) { }
PlasmaRifle::PlasmaRifle( PlasmaRifle const & cp) { *this = cp; }
PlasmaRifle::~PlasmaRifle( void ) { }
PlasmaRifle& PlasmaRifle::operator=( PlasmaRifle const &) { return *this; }
void PlasmaRifle::attack() const
{
std::cout << "* piouuu piouuu piouuu *" << std::endl;
}
| [
"acarlson@e1z3r2p8.42.us.org"
] | acarlson@e1z3r2p8.42.us.org |
8b2d4b355db7e2032137d2edb91486c2c248e9d6 | 19ad692a3b1f7cadc8e94e2ad544190dd8aa48d1 | /assignment 2/Solved/time.h | ce5061c71d1311393233c0667ae608f3b37d20ff | [] | no_license | mabdullahkhalil/Data-Structures | 96f473c612efb3e730c5a171dcabdf8fb8e29222 | c635d77e1d2ef851d830bdc68946b073dff4fe7e | refs/heads/master | 2020-03-27T06:38:11.203952 | 2018-08-25T19:10:18 | 2018-08-25T19:10:18 | 146,122,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,194 | h | #include <sys/time.h>
#include <iostream>
using namespace std;
int timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
tv_usec is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
// printf(result->tv_sec);
/* Return 1 if result is negative. */
return 0;
}
struct timeval t1, t2;
struct timezone tz;
void startTimer()
{
gettimeofday(&t1, &tz);
}
void stopTimer()
{
gettimeofday(&t2, &tz);
cout<<"It took "<< t2.tv_sec - t1.tv_sec <<" seconds and "<< t2.tv_usec - t1.tv_usec<<" microseconds"<<endl;;
}
// call "startTimer()" to start timer
// call "stopTimer()" to stop timer and print total time in microseconds.
| [
"muhammadabdullahkhalil@gmail.com"
] | muhammadabdullahkhalil@gmail.com |
c803a423a373ff8c5687b501a41df1e1602e0ec7 | b269392cc4727b226e15b3f08e9efb41a7f4b048 | /CodeForces/CodeForces 443A.cpp | 11910e2636559b90f8e7916b7adc2e9a8b292f72 | [] | no_license | ThoseBygones/ACM_Code | edbc31b95077e75d3b17277d843cc24b6223cc0c | 2e8afd599b8065ae52b925653f6ea79c51a1818f | refs/heads/master | 2022-11-12T08:23:55.232349 | 2022-10-30T14:17:23 | 2022-10-30T14:17:23 | 91,112,483 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 357 | cpp | #include <iostream>
#include <cstdio>
#include <cstring>
#include <set>
using namespace std;
char str[1005];
set <char> ele;
int main()
{
ele.clear();
gets(str);
int len=strlen(str);
for(int i=0; i<len; i++)
{
if(str[i]>='a' && str[i]<='z')
ele.insert(str[i]);
}
cout << ele.size() << endl;
return 0;
}
| [
"1273789365@qq.com"
] | 1273789365@qq.com |
e93382f17a8e406e8c729429843d13889ed5c290 | 259319e5fe06036972de9036f0078b8f5faba86e | /records/StudentRecord.cpp | 9b9eb617920366a7c7d62e8a3f5d9ba327189155 | [] | no_license | ferromera/sancus | 652d05fc2a28987ac37309b9293cbd7f92448186 | 0f5d9b2e0bf1b6e099ade36edcf75e9640788589 | refs/heads/master | 2021-01-01T16:56:39.380388 | 2011-12-04T01:01:55 | 2011-12-04T01:01:55 | 32,414,828 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,683 | cpp | #include "StudentRecord.h"
#include <cstring>
using namespace std;
StudentRecord::StudentRecord():idNumber_(0),name_(string()){
key_=new Key;
buffer= new char[260];
}
StudentRecord::StudentRecord(const StudentRecord & sr):
idNumber_(sr.idNumber_),name_(sr.name_){
key_=new Key((uint16_t) idNumber_);
buffer= new char[260];
}
StudentRecord::StudentRecord(char ** input){
key_= new Key();
buffer= new char[260];
read(input);
}
StudentRecord::StudentRecord(uint16_t idNumber,const string & name)
:idNumber_(idNumber),name_(name){
key_= new Key(idNumber);
buffer= new char[260];
}
const StudentRecord::Key & StudentRecord::getKey()const{
//Key * k= dynamic_cast<Key *>(key_);
//return (*k);
return * ( (StudentRecord::Key *) key_ );
}
void StudentRecord::setKey(const StudentRecord::Key & k){
//const Key & ak=dynamic_cast<const Key &>(k);
delete key_;
key_=new Key(k);
idNumber_=k.getKey();
}
void StudentRecord::setKey(int16_t k){
delete key_;
key_=new Key(k);
idNumber_=k;
}
void StudentRecord::read(char ** input){
char * buffCurr=buffer;
memcpy(buffCurr,*input,2);
memcpy(&idNumber_,*input,2);
delete key_;
key_=new Key(idNumber_);
(*input)+=2;
buffCurr+=2;
uint8_t nameSize;
memcpy(buffCurr,*input,1);
memcpy(&nameSize,*input,1);
buffCurr++;
(*input)++;
char * c_str=new char[nameSize+1];
memcpy(buffCurr,*input,nameSize);
memcpy(c_str,*input,nameSize);
(*input)+=nameSize;
c_str[nameSize]='\0';
name_=c_str;
delete c_str;
}
void StudentRecord::write(char ** output){
update();
memcpy(*output,buffer,size());
(*output)+=size();
}
void StudentRecord::update(){
//write back to the buffer
char * buffCurr=buffer;
memcpy(buffCurr,&idNumber_,2);
buffCurr+=2;
uint8_t nameSize=name_.size();
memcpy(buffCurr,&nameSize,1);
buffCurr++;
memcpy(buffCurr,name_.c_str(),nameSize);
}
unsigned int StudentRecord::size()const{
return sizeof(idNumber_)+1+name_.size();
}
uint16_t StudentRecord::idNumber()const{
return idNumber_;
}
const string & StudentRecord::name()const{
return name_;
}
void StudentRecord::idNumber(uint16_t p){
setKey(p);
}
void StudentRecord::name(const string & n){
name_=n;
}
StudentRecord& StudentRecord::operator=(const StudentRecord& rec){
if(this==&rec)
return *this;
idNumber_=rec.idNumber_;
name_=rec.name_;
key_=new Key((uint16_t) idNumber_);
buffer= new char[260];
return *this;
}
StudentRecord::~StudentRecord(){
delete buffer;
}
| [
"FernandoRomeraFerrio@gmail.com@b06ae71c-7d8b-23a7-3f8b-8cb8ce3c93c2"
] | FernandoRomeraFerrio@gmail.com@b06ae71c-7d8b-23a7-3f8b-8cb8ce3c93c2 |
b4ff71c1eab2bfc2267df8d024228650e356fca6 | 66d008acad46229b9783b62d83f0a6736af09a0c | /Shader.cpp | 86071250c7b98c7107d8c8ac53dcd9540fed8981 | [] | no_license | emirhanylmzz/3D_SNAKE_GAME_OPENGL | 36cbf585b1a17d7ad4ea5dae89e32d700af3a709 | 653b1e690878312677d3f021a62e8dd8d1122c03 | refs/heads/main | 2023-03-02T00:59:55.025574 | 2021-02-07T10:54:39 | 2021-02-07T10:54:39 | 310,135,202 | 0 | 0 | null | 2021-02-07T10:54:39 | 2020-11-04T22:48:17 | C++ | UTF-8 | C++ | false | false | 2,323 | cpp | #include "Shader.h"
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "Renderer.h"
Shader::Shader(const string& v, const string& f)
{
m_RendererID = CreateShader(v, f);
}
Shader::~Shader()
{
GLCall(glDeleteProgram(m_RendererID));
}
unsigned int Shader::CompileShader(unsigned int type, const string& source)
{
unsigned int id = glCreateShader(type);
const char* src = source.c_str();
GLCall(glShaderSource(id, 1, &src, nullptr));
GLCall(glCompileShader(id));
//ERROR HANDLING
int result;
GLCall(glGetShaderiv(id, GL_COMPILE_STATUS, &result));
if (result == GL_FALSE)
{
int length;
GLCall(glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length));
char* message = (char*)_malloca(length * sizeof(char));
GLCall(glGetShaderInfoLog(id, length, &length, message));
cerr << "Failed to compile " << (type == GL_VERTEX_SHADER ? "vertex" : "fragment") << endl;
cerr << message << endl;
GLCall(glDeleteShader(id));
return 0;
}
return id;
}
unsigned int Shader::CreateShader(const string& vertexShader, const string& fragmentShader)
{
unsigned int program = glCreateProgram();
unsigned int vs = CompileShader(GL_VERTEX_SHADER, vertexShader);
unsigned int fs = CompileShader(GL_FRAGMENT_SHADER, fragmentShader);
GLCall(glAttachShader(program, vs));
GLCall(glAttachShader(program, fs));
GLCall(glLinkProgram(program));
GLCall(glValidateProgram(program));
GLCall(glDeleteShader(vs));
GLCall(glDeleteShader(fs));
return program;
}
void Shader::Bind() const
{
GLCall(glUseProgram(m_RendererID));
}
void Shader::UnBind() const
{
GLCall(glUseProgram(0));
}
void Shader::SetUniform4f(const string& name, float v0, float v1, float v2, float v3)
{
GLCall(glUniform4f(GetUniformLocation(name), v0, v1, v2, v3));
}
void Shader::SetUniform1i(const string& name, int v0)
{
GLCall(glUniform1i(GetUniformLocation(name), v0));
}
void Shader::SetUniformMat4f(const string& name, const glm::mat4 matrix)
{
GLCall(glUniformMatrix4fv(GetUniformLocation(name), 1, GL_FALSE, &matrix[0][0]));
}
int Shader::GetUniformLocation(const string& name)
{
int location = glGetUniformLocation(m_RendererID, name.c_str());
if (location == -1)
cerr << "Warning! Wrong location!" << endl;
return location;
}
| [
"noreply@github.com"
] | emirhanylmzz.noreply@github.com |
4ea0d691bbcfbfe47460cc8d595447388ee9c035 | 9d82eabe30c2ad6aef7c24d3358eec308c74254c | /Plugins/Puerts/Source/PuertsEditor/Public/PEBlueprintMetaData.h | 9c0b13578c625b2424813eef5e6d463694e877db | [] | permissive | zombieyang/puerts_unreal_demo | 011da1e0b6bc43b9c36c264cbd2729be61eec3ee | 167ed16baf9a77ac615bcb56431c3771ff9c3e82 | refs/heads/master | 2023-03-12T04:01:28.817664 | 2022-08-11T03:52:52 | 2022-08-11T03:52:52 | 344,380,891 | 0 | 0 | MIT | 2021-03-04T07:02:30 | 2021-03-04T07:02:29 | null | UTF-8 | C++ | false | false | 27,691 | h | /*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may
* be subject to their corresponding license terms. This file is subject to the terms and conditions defined in file 'LICENSE',
* which is part of this source code package.
*/
#pragma once
#include "PropertyMacros.h"
#include "Math/UnitConversion.h"
#include "K2Node_CustomEvent.h"
#include "K2Node_FunctionEntry.h"
#include "Engine/Blueprint.h"
#include "PEBlueprintMetaData.generated.h"
/**
* @brief since the void_t defined in converter.hpp will introduce v8
* define a temporary void_t here
*/
template <class...>
using Void_t = void;
/**
* @brief the utility function collection for meta data
*/
struct FPEMetaDataUtils
{
/**
* temporary check if a type is defined
*/
template <typename T, typename = void>
struct TFormatValidator
{
/**
* @brief fallback
* @param ...
* @return
*/
template <typename... Args>
bool operator()(Args&&...) const
{
// if the field variant is not exist, currently don't do further check
UE_LOG(LogTemp, VeryVerbose, TEXT("FFieldVarient is not implemented in current engine"));
return true;
}
};
/**
* @brief if the field variant is defined, we do the check
* @tparam T
*/
template <typename T>
struct TFormatValidator<T, typename std::enable_if<(sizeof(T) > 0)>::type>
{
/**
* @brief real check
* @param InField
* @param InKey
* @param InValue
* @param OutMessage
* @return
*/
bool operator()(T InField, FName InKey, const FString& InValue, FString& OutMessage) const
{
// name pre define
static const FName NAME_BlueprintProtected = TEXT("BlueprintProtected");
static const FName NAME_ClampMax = TEXT("ClampMax");
static const FName NAME_ClampMin = TEXT("ClampMin");
static const FName NAME_CommutativeAssociativeBinaryOperator = TEXT("CommutativeAssociativeBinaryOperator");
static const FName NAME_DevelopmentStatus = TEXT("DevelopmentStatus");
static const FName NAME_DocumentationPolicy = TEXT("DocumentationPolicy");
static const FName NAME_ExpandBoolAsExecs = TEXT("ExpandBoolAsExecs");
static const FName NAME_ExpandEnumAsExecs = TEXT("ExpandEnumAsExecs");
static const FName NAME_UIMax = TEXT("UIMax");
static const FName NAME_UIMin = TEXT("UIMin");
static const FName NAME_Units = TEXT("Units");
// a helper function used to check a function is well defined blueprint protected
static const auto ValidateFunctionBlueprintProtected = [](UFunction* InFunction)
{
if (!IsValid(InFunction))
{
return false;
}
if (InFunction->HasAnyFunctionFlags(FUNC_Static))
{
// Determine if it's a function library
UClass* Class = InFunction->GetOuterUClass();
while (Class != nullptr && Class->GetSuperClass() != UObject::StaticClass())
{
Class = Class->GetSuperClass();
}
if (Class != nullptr && Class->GetName() == TEXT("BlueprintFunctionLibrary"))
{
return false;
}
}
return true;
};
// a helper function used to check a function is well defined binary operator
static const auto ValidateFunctionCommutativeAssociativeBinaryOperator = [](UFunction* InFunction)
{
if (!IsValid(InFunction))
{
return false;
}
bool bGoodParams = (InFunction->NumParms == 3);
if (bGoodParams)
{
PropertyMacro* FirstParam = nullptr;
PropertyMacro* SecondParam = nullptr;
PropertyMacro* ReturnValue = nullptr;
TFieldIterator<PropertyMacro> It(InFunction);
auto GetNextParam = [&]()
{
if (It)
{
if (It->HasAnyPropertyFlags(CPF_ReturnParm))
{
ReturnValue = *It;
}
else
{
if (FirstParam == nullptr)
{
FirstParam = *It;
}
else if (SecondParam == nullptr)
{
SecondParam = *It;
}
}
++It;
}
};
GetNextParam();
GetNextParam();
GetNextParam();
ensure(!It);
if (ReturnValue == nullptr || SecondParam == nullptr || !SecondParam->SameType(FirstParam))
{
bGoodParams = false;
}
}
return bGoodParams;
};
// a helper function sued to check a function is well defined as execs
static const auto ValidateFunctionExpandAsExecs = [](UFunction* InFunction, const FString& InValue)
{
if (!IsValid(InFunction))
{
return false;
}
// multiple entry parsing in the same format as eg SetParam.
TArray<FString> RawGroupings;
InValue.ParseIntoArray(RawGroupings, TEXT(","), false);
PropertyMacro* FirstInput = nullptr;
for (const FString& RawGroup : RawGroupings)
{
TArray<FString> IndividualEntries;
RawGroup.ParseIntoArray(IndividualEntries, TEXT("|"));
for (const FString& Entry : IndividualEntries)
{
if (Entry.IsEmpty())
{
continue;
}
auto FoundField = FindUFieldOrFProperty(InFunction, *Entry);
if (!FoundField)
{
return false;
}
if (PropertyMacro* Prop = FoundField.Get<PropertyMacro>())
{
if (!Prop->HasAnyPropertyFlags(CPF_ReturnParm) &&
(!Prop->HasAnyPropertyFlags(CPF_OutParm) || Prop->HasAnyPropertyFlags(CPF_ReferenceParm)))
{
if (!FirstInput)
{
FirstInput = Prop;
}
else
{
return false;
}
}
}
}
}
return true;
};
// function body
// check numeric keys
if (InKey == NAME_UIMin || InKey == NAME_UIMax || InKey == NAME_ClampMin || InKey == NAME_ClampMax)
{
if (!InValue.IsNumeric())
{
OutMessage =
FString::Printf(TEXT("Metadata value for '%s' is non-numeric : '%s'"), *InKey.ToString(), *InValue);
return false;
}
return true;
}
// check blueprint protected function
if (InKey == NAME_BlueprintProtected)
{
if (!ValidateFunctionBlueprintProtected(InField.template Get<UFunction>()))
{
OutMessage =
FString::Printf(TEXT("%s doesn't make sense on static method '%s' in a blueprint function library"),
*InKey.ToString(), *InField.GetFullName());
return false;
}
return true;
}
// check binary operator function
if (InKey == NAME_CommutativeAssociativeBinaryOperator)
{
if (!ValidateFunctionCommutativeAssociativeBinaryOperator(InField.template Get<UFunction>()))
{
OutMessage = TEXT(
"Commutative asssociative binary operators must have exactly 2 parameters of the same type and a return "
"value.");
return false;
}
return true;
}
// check expand as execs
if (InKey == NAME_ExpandBoolAsExecs || InKey == NAME_ExpandEnumAsExecs)
{
if (!ValidateFunctionExpandAsExecs(InField.template Get<UFunction>(), InValue))
{
OutMessage = TEXT("invalid meta data for expand as execs");
return false;
}
return true;
}
// check development status
if (InKey == NAME_DevelopmentStatus)
{
const FString EarlyAccessValue(TEXT("EarlyAccess"));
const FString ExperimentalValue(TEXT("Experimental"));
if ((InValue != EarlyAccessValue) && (InValue != ExperimentalValue))
{
OutMessage = FString::Printf(TEXT("'%s' metadata was '%s' but it must be %s or %s"), *InKey.ToString(),
*InValue, *ExperimentalValue, *EarlyAccessValue);
return false;
}
return true;
}
// check units
if (InKey == NAME_Units)
{
// Check for numeric property
auto* MaybeProperty = InField.template Get<NumericPropertyMacro>();
if (MaybeProperty == nullptr && !MaybeProperty->template IsA<StructPropertyMacro>())
{
OutMessage = TEXT("'Units' meta data can only be applied to numeric and struct properties");
return false;
}
if (!FUnitConversion::UnitFromString(*InValue))
{
OutMessage = FString::Printf(
TEXT("Unrecognized units (%s) specified for property '%s'"), *InValue, *InField.GetFullName());
return false;
}
return true;
}
// check documentation policy
if (InKey == NAME_DocumentationPolicy)
{
const TCHAR* StrictValue = TEXT("Strict");
if (InValue != StrictValue)
{
OutMessage =
FString::Printf(TEXT("'%s' metadata was '%s' but it must be %s"), *InKey.ToString(), *InValue, StrictValue);
return false;
}
return true;
}
return true;
}
};
/**
* @brief the format validate
*/
static TFormatValidator<class FFieldVariant> ValidateFormat;
/**
* @brief add specific meta data to ufield
* @param InField
* @param InMetaData
* @return
*/
static bool AddMetaData(UField* InField, TMap<FName, FString>& InMetaData);
};
/**
* @brief a helper structure used to store the meta data of a class, @see ClassDeclarationMetaData.h/cpp
* currently, we don't need remove methods, also the caller should ensure the internal data consistence
* e.g. the show category added should never be added in hide categories...
*/
UCLASS()
class PUERTSEDITOR_API UPEClassMetaData : public UObject
{
GENERATED_BODY()
public:
/**
* @brief set the class flags, ant notify if placeable specifier is set
* @param InFlags
* @param bInPlaceable
*/
UFUNCTION()
void SetClassFlags(int32 InFlags, bool bInPlaceable);
/**
* @brief set the specific meta data
* @param InName
* @param InValue
*/
UFUNCTION()
void SetMetaData(const FString& InName, const FString& InValue);
/**
* @brief set the class should be with in
* @param InClassName
*/
UFUNCTION()
void SetClassWithIn(const FString& InClassName);
/**
* @brief set the configuration name
* @param InConfigName
*/
UFUNCTION()
void SetConfig(const FString& InConfigName);
/**
* @brief add a category to hide in blueprint
* @param InCategory
*/
UFUNCTION()
void AddHideCategory(const FString& InCategory);
/**
* @brief add a category to show in blueprint
* @param InCategory
*/
UFUNCTION()
void AddShowCategory(const FString& InCategory);
/**
* @brief add a sub category to show in blueprint
* @param InCategory
*/
UFUNCTION()
void AddShowSubCategory(const FString& InCategory);
/**
* @brief add a function to hide in blueprint
* @param InFunctionName
*/
UFUNCTION()
void AddHideFunction(const FString& InFunctionName);
/**
* @brief add a function to show in blueprint
* @param InFunctionName
*/
UFUNCTION()
void AddShowFunction(const FString& InFunctionName);
/**
* @brief add a category to auto expand in blueprint
* @param InCategory
*/
UFUNCTION()
void AddAutoExpandCategory(const FString& InCategory);
/**
* @brief add a category to auto collapse in blueprint
* @param InCategory
*/
UFUNCTION()
void AddAutoCollapseCategory(const FString& InCategory);
/**
* @brief forbid a category to auto collapse in blueprint
* @param InCategory
*/
UFUNCTION()
void AddDontAutoCollapseCategory(const FString& InCategory);
/**
* @brief add a class group
* @param InGroupName
*/
UFUNCTION()
void AddClassGroup(const FString& InGroupName);
/**
* @brief add a sparse data type
* @param InType
*/
UFUNCTION()
void AddSparseDataType(const FString& InType);
public:
/**
* @brief apply the meta data to specific class, this should only call at most once
* since this function will change the internal status of the meta data
* @param InClass
* @param InBlueprint
* @return
*/
bool Apply(UClass* InClass, UBlueprint* InBlueprint);
private:
/**
* @brief the helper function used to get the value array like meta data from the given class
* @param InClass
* @param InMetaDataKey
* @param InDelimiter
* @param bInCullEmpty
* @return
*/
static TArray<FString> GetClassMetaDataValues(
UClass* InClass, const TCHAR* InMetaDataKey, const TCHAR* InDelimiter = TEXT(" "), bool bInCullEmpty = true);
/**
* @brief since blueprint compilation will reset class meta data, so make blueprint sync with class
* @param InClass
* @param InBlueprint
*/
static void SyncClassToBlueprint(UClass* InClass, UBlueprint* InBlueprint);
private:
/**
* @brief Merges all category properties with the class which at this point only has its parent propagated categories
* @param InClass
*/
void MergeClassCategories(UClass* InClass);
/**
* @brief Merge and validate the class flags, the input class is the class to set meta data
* @param InClass
* @return if the class flags is changed
*/
bool MergeAndValidateClassFlags(UClass* InClass);
/**
* @brief set the class meta data
* @param InClass
* @return
*/
bool SetClassMetaData(UClass* InClass);
/**
* @brief set and check with class
* @param InClass
*/
void SetAndValidateWithinClass(UClass* InClass);
/**
* @brief set and check the config name
* @param InClass
*/
void SetAndValidateConfigName(UClass* InClass);
public:
/**
* @brief the class flags
*/
EClassFlags ClassFlags = CLASS_None;
/**
* @brief the meta data
*/
TMap<FName, FString> MetaData;
/**
* @brief the class with in
*/
FString ClassWithIn;
/**
* @brief the config name, from where the class to read config variables' value
*/
FString ConfigName;
/**
* @brief the hide categories in blueprint
*/
TArray<FString> HideCategories;
/**
* @brief the show categories in blueprint
*/
TArray<FString> ShowCategories;
/**
* @brief the show sub categories in blueprint
*/
TArray<FString> ShowSubCategories;
/**
* @brief the hide functions in blueprint
*/
TArray<FString> HideFunctions;
/**
* @brief the show functions in blueprint
*/
TArray<FString> ShowFunctions;
/**
* @brief the auto expand categories in blueprint
*/
TArray<FString> AutoExpandCategories;
/**
* @brief the auto collapse categories in blueprint
*/
TArray<FString> AutoCollapseCategories;
/**
* @brief the categories will not auto collapse in blueprint
*/
TArray<FString> DontAutoCollapseCategories;
/**
* @brief the class group names
*/
TArray<FString> ClassGroupNames;
/**
* @brief the sparse class data types
*/
TArray<FString> SparseClassDataTypes;
/**
* @brief a boolean indicate if wants to be placeable
*/
bool bWantsToBePlaceable = false;
private:
/**
* @brief the name of cached category in meta data
*/
static const TCHAR* NAME_ClassGroupNames;
static const TCHAR* NAME_HideCategories;
static const TCHAR* NAME_ShowCategories;
static const TCHAR* NAME_SparseClassDataTypes;
static const TCHAR* NAME_HideFunctions;
static const TCHAR* NAME_AutoExpandCategories;
static const TCHAR* NAME_AutoCollapseCategories;
};
/**
* @brief a helper structure used to store the meta data of a function, @see ParseHelper.h
*/
UCLASS()
class PUERTSEDITOR_API UPEFunctionMetaData : public UObject
{
GENERATED_BODY()
private:
friend class UPEBlueprintAsset;
public:
/**
* @brief set the function flags, since this will called from js, so divide into high and low parts
* @param InHighBits
* @param InLowBits
*/
UFUNCTION()
void SetFunctionFlags(int32 InHighBits, int32 InLowBits);
/**
* @brief set the function export flags
* @param InFlags
*/
UFUNCTION()
void SetFunctionExportFlags(int32 InFlags);
/**
* @brief set the specific meta data
* @param InName
* @param InValue
*/
UFUNCTION()
void SetMetaData(const FString& InName, const FString& InValue);
/**
* @brief set the cpp implementation function, is this meaningful for blueprint function?
* @param InName
*/
UFUNCTION()
void SetCppImplName(const FString& InName);
/**
* @brief set the cpp implementation validation function
* @param InName
*/
UFUNCTION()
void SetCppValidationImplName(const FString& InName);
/**
* @brief set the end point name,
* @param InEndpointName
*/
UFUNCTION()
void SetEndpointName(const FString& InEndpointName);
/**
* @brief set the rpc id
* @param InRPCId
*/
UFUNCTION()
void SetRPCId(int32 InRPCId);
/**
* @brief set the rpc response id
* @param InRPCResponseId
*/
UFUNCTION()
void SetRPCResponseId(int32 InRPCResponseId);
/**
* @brief set if the function is sealed event
* @param bInSealedEvent
*/
UFUNCTION()
void SetIsSealedEvent(bool bInSealedEvent);
/**
* @brief set if the function is force blueprint impure
* @param bInForceBlueprintImpure
*/
UFUNCTION()
void SetForceBlueprintImpure(bool bInForceBlueprintImpure);
public:
/**
* @brief apply to a custom event
* @param InCustomEvent
*/
bool Apply(UK2Node_CustomEvent* InCustomEvent) const;
/**
* @brief apply to a normal function
* @param InFunctionEntry
*/
bool Apply(UK2Node_FunctionEntry* InFunctionEntry) const;
private:
/**
* @brief
* fallback if the custom event not support the user defined meta data
* @param bOutChanged
* @param ...
*/
template <typename... Args>
static void ApplyCustomEventMetaData(bool& bOutChanged, Args&&...)
{
bOutChanged = false;
};
/**
* @brief add user defined meta data for custom event
* @tparam CustomEvent
* @param bOutChanged
* @param InMetaData
* @param InCustomEvent
* @return
*/
template <typename CustomEvent>
static auto ApplyCustomEventMetaData(bool& bOutChanged, const TMap<FName, FString>& InMetaData, CustomEvent* InCustomEvent) ->
typename std::enable_if<true, Void_t<decltype(std::declval<CustomEvent>().GetUserDefinedMetaData())>>::type
{
check(IsValid(InCustomEvent));
// a helper function used to update text value, and return if the value is updated by a new value
static const auto UpdateTextMetaData = [](FName InKey, const TMap<FName, FString>& InMetaData, FText& InOutValue) -> bool
{
const FText NewValue = InMetaData.Contains(InKey) ? FText::FromString(InMetaData[InKey]) : FText{};
const bool bChanged = !NewValue.EqualTo(InOutValue);
InOutValue = NewValue;
return bChanged;
};
// a helper function used to update boolean value, and return if the value is updated by the new value
static const auto UpdateBooleanMetaData = [](FName InKey, const TMap<FName, FString>& InMetaData, bool& InOutValue) -> bool
{
const bool NewValue = InMetaData.Contains(InKey) ? true : false;
const bool bChanged = NewValue != InOutValue;
InOutValue = NewValue;
return bChanged;
};
// a helper function sued update string value, return return if the value is updated by the new value
static const auto UpdateStringMetaData = [](FName InKey, const TMap<FName, FString>& InMetaData,
FString& InOutValue) -> bool
{
const FString NewValue = InMetaData.Contains(InKey) ? InMetaData[InKey] : FString{};
const bool bChanged = NewValue != InOutValue;
InOutValue = NewValue;
return bChanged;
};
bool bMetaDataChanged = false;
auto& MetaDataToSet = InCustomEvent->GetUserDefinedMetaData();
bMetaDataChanged = UpdateBooleanMetaData(TEXT("CallInEditor"), InMetaData, MetaDataToSet.bCallInEditor) || bMetaDataChanged;
bMetaDataChanged = UpdateTextMetaData(TEXT("Category"), InMetaData, MetaDataToSet.Category) || bMetaDataChanged;
bMetaDataChanged = UpdateTextMetaData(TEXT("Keywords"), InMetaData, MetaDataToSet.Keywords) || bMetaDataChanged;
bMetaDataChanged =
UpdateTextMetaData(TEXT("CompactNodeTitle"), InMetaData, MetaDataToSet.CompactNodeTitle) || bMetaDataChanged;
bMetaDataChanged = UpdateTextMetaData(TEXT("ToolTip"), InMetaData, MetaDataToSet.ToolTip) || bMetaDataChanged;
bMetaDataChanged =
UpdateBooleanMetaData(TEXT("DeprecatedFunction"), InMetaData, MetaDataToSet.bIsDeprecated) || bMetaDataChanged;
bMetaDataChanged =
UpdateStringMetaData(TEXT("DeprecationMessage"), InMetaData, MetaDataToSet.DeprecationMessage) || bMetaDataChanged;
bOutChanged = bMetaDataChanged;
}
public:
/**
* @brief the function flags
*/
EFunctionFlags FunctionFlags = FUNC_None;
/**
* @brief the function export flags
*/
int32 FunctionExportFlags = 0;
/**
* @brief the meta data of the function
*/
TMap<FName, FString> MetaData;
/**
* @brief the cpp implementation name, is this ok for blueprint function? or generated function could be a no-blueprint function
* ?
*/
FString CppImplName;
/**
* @brief the cpp validation implementation name,
*/
FString CppValidationImplName;
/**
* @brief endpoint name
*/
FString EndpointName;
/**
* @brief identifier for an RPC call to a platform service
*/
uint16 RPCId = 0;
/**
* @brief identifier for an RPC call expect a response
*/
uint16 RPCResponseId = 0;
/**
* @brief whether this function represents a sealed event
*/
bool bSealedEvent = false;
/**
* @brief true if the function is being forced to be considered as impure by the user
*/
bool bForceBlueprintImpure = false;
};
/**
* @brief a helper structure used to store the meta data of a function parameter
*/
UCLASS()
class PUERTSEDITOR_API UPEParamMetaData : public UObject
{
GENERATED_BODY()
private:
friend class UPEBlueprintAsset;
public:
/**
* @brief set the parameter's property flags
* @param InHighBits
* @param InLowBits
*/
UFUNCTION()
void SetParamFlags(int32 InHighBits, int32 InLowBits);
/**
* @brief set specific meta data
* @param InName
* @param InValue
*/
UFUNCTION()
void SetMetaData(const FString& InName, const FString& InValue);
public:
/**
* @brief apply to pin type
* @param PinType
* @return
*/
bool Apply(FEdGraphPinType& PinType) const;
private:
/**
* @brief the parameter's flags
*/
EPropertyFlags ParamFlags;
/**
* @brief the meta data
*/
TMap<FName, FString> MetaData;
};
/**
* @brief a helper function used to store the meta data of a class's member variable
*/
UCLASS()
class PUERTSEDITOR_API UPEPropertyMetaData : public UObject
{
GENERATED_BODY()
private:
friend class UPEBlueprintAsset;
public:
/**
* @brief set the property flags
* @param InHighBits
* @param InLowBits
*/
UFUNCTION()
void SetPropertyFlags(int32 InHighBits, int32 InLowBits);
/**
* @brief set the meta data of the property
* @param InName
* @param InValue
*/
UFUNCTION()
void SetMetaData(const FString& InName, const FString& InValue);
/**
* @brief set the rep callback name
* @param InName
*/
UFUNCTION()
void SetRepCallbackName(const FString& InName);
public:
/**
* @brief apply the meta data to the property
* @param Element
*/
bool Apply(FBPVariableDescription& Element) const;
private:
/**
* @brief the property's flags
*/
EPropertyFlags PropertyFlags;
/**
* @brief the function name for a replicated function
*/
FString RepCallbackName;
/**
* @brief the meta data for the property
*/
TMap<FName, FString> MetaData;
};
| [
"johnche@tencent.com"
] | johnche@tencent.com |
7cbe456fbefdd6e4d5d268558782cd777324249b | 2eec9db7c8890de85eaa2140b59116e573dd0b53 | /src/qt/modaloverlay.h | 5228ffd1e0a0f49958959ac6f6810399a5c301b6 | [
"MIT"
] | permissive | Alonewolf-123/PaydayCoin-Core | 45bca042a8014f4486977f951bc2083728d8fb5e | d807d95550d955bfa9ffda2b39cad745422224e5 | refs/heads/master | 2023-01-13T15:33:54.226987 | 2019-12-16T04:54:53 | 2019-12-16T04:54:53 | 227,445,703 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,512 | h | // Copyright (c) 2016-2018 The PaydayCoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef PAYDAYCOIN_QT_MODALOVERLAY_H
#define PAYDAYCOIN_QT_MODALOVERLAY_H
#include <QDateTime>
#include <QWidget>
//! The required delta of headers to the estimated number of available headers until we show the IBD progress
static constexpr int HEADER_HEIGHT_DELTA_SYNC = 24;
namespace Ui {
class ModalOverlay;
}
/** Modal overlay to display information about the chain-sync state */
class ModalOverlay : public QWidget
{
Q_OBJECT
public:
explicit ModalOverlay(QWidget *parent);
~ModalOverlay();
public Q_SLOTS:
void tipUpdate(int count, const QDateTime& blockDate, double nVerificationProgress);
void setKnownBestHeight(int count, const QDateTime& blockDate);
void toggleVisibility();
// will show or hide the modal layer
void showHide(bool hide = false, bool userRequested = false);
void closeClicked();
bool isLayerVisible() const { return layerIsVisible; }
protected:
bool eventFilter(QObject * obj, QEvent * ev);
bool event(QEvent* ev);
private:
Ui::ModalOverlay *ui;
int bestHeaderHeight; //best known height (based on the headers)
QDateTime bestHeaderDate;
QVector<QPair<qint64, double> > blockProcessTime;
bool layerIsVisible;
bool userClosed;
void UpdateHeaderSyncLabel();
};
#endif // PAYDAYCOIN_QT_MODALOVERLAY_H
| [
"alonewolf2ksk@gmail.com"
] | alonewolf2ksk@gmail.com |
3ac1b30d13b5fb9ddd636f3afdd1a6078fecccea | e61f3ee1dd37c88c829a198d463318830c8d0623 | /Functions/PassbyAddress/main.cpp | 7c9d79f3ce5d8fb794bf529403612f76a7d98d5d | [] | no_license | Adityasakare/CPP | 484b3ae26588dec153b3e2bf6922f5db6ace0084 | ed0743c6b041a318a8d4d443ec280747a9b89f65 | refs/heads/master | 2023-07-25T20:13:39.450799 | 2021-09-02T18:20:57 | 2021-09-02T18:20:57 | 268,801,113 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 236 | cpp | #include<iostream>
using namespace std;
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int x=10, y=20;
swap(&x, &y);
cout<<x<<","<<y;
return 0;
}
| [
"noreply@github.com"
] | Adityasakare.noreply@github.com |
4372154864296e19770387a4cac9032f2a6ce47e | c8533e38289deff74c37b2759137424762e28242 | /CTCI/ch2/5b.cpp | 359bcd14ef1e31bda94a05e87801896f8f1ff9b8 | [] | no_license | rhb2/playground | 0ab19416deca8961ec5279b1b962fe2aa01a3cfc | 306257143152a76f01eedb3274c71f04bac414aa | refs/heads/master | 2023-05-11T19:11:26.317693 | 2021-06-03T22:44:46 | 2021-06-03T22:44:46 | 334,799,168 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,413 | cpp | #include <iostream>
#include <cassert>
#include "../util/sll.h"
using namespace std;
linkedlist<int> *
sumlists(linkedlist<int> &l1, linkedlist<int> &l2)
{
linkedlist<int> *result = new linkedlist<int>;
int sum;
int carry = 0;
node<int> *pn1, *pn2;
l1.reverse();
l2.reverse();
pn1 = l1.head;
pn2 = l2.head;
while (pn1 != NULL && pn2 != NULL) {
int res = pn1->val + pn2->val + carry;
sum = res % 10;
carry = res / 10;
result->push_front(sum);
pn1 = pn1->next;
pn2 = pn2->next;
}
while (pn1 != NULL) {
int res = pn1->val + carry;
sum = res % 10;
carry = res / 10;
result->push_front(sum);
pn1 = pn1->next;
}
while (pn2 != NULL) {
int res = pn2->val + carry;
sum = res % 10;
carry = res / 10;
result->push_front(sum);
pn2 = pn2->next;
}
if (carry > 0)
result->push_front(carry);
return (result);
}
int main(int argc, char **argv)
{
linkedlist<int> ll1, ll2;
int len1, len2;
int i;
assert(argc == 3);
len1 = atoi(argv[1]);
len2 = atoi(argv[2]);
for (i = 0; i < len1 - 1; i++)
ll1.push_front(rand() % 10);
/* The most significant digit must be non-zero. */
ll1.push_front((rand() % 9) + 1);
for (i = 0; i < len2 - 1; i++)
ll2.push_front(rand() % 10);
/* The most significant digit must be non-zero. */
ll2.push_front((rand() % 9) + 1);
cout << ll1 << endl;
cout << ll2 << endl;
cout << *(sumlists(ll1, ll2)) << endl;
return (0);
}
| [
"robert.bogart@joyent.com"
] | robert.bogart@joyent.com |
10f602de41c887b243cdf20cacbaf7be67cfe204 | 37ee162650bc8bbe0cd8aac85854465c3a6d58dc | /src/connection.cpp | 3fc136e6866f98bd416d2949d4f46bfb9d82b67c | [] | no_license | weltenbauer/wb-time-tracker | 487c958a25c3ef11c6066df31a5d31aef618fb0f | b5cf82cf8ad6732eee37803765ae89212a74eeaf | refs/heads/master | 2020-07-11T13:59:32.544041 | 2019-08-26T21:03:46 | 2019-08-26T21:03:46 | 204,561,068 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,242 | cpp |
#include <SPI.h>
#include <WiFiNINA.h>
#include <ArduinoHttpClient.h>
#include "connection.h"
#include "util.h"
#include "../config.h"
//-----------------------------------------------------------------------------------------------
WiFiSSLClient wifi;
//-----------------------------------------------------------------------------------------------
void connect(){
// Get data
int status = WL_IDLE_STATUS;
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
// Check for WiFi module
if (WiFi.status() == WL_NO_MODULE) {
exit("Communication with WiFi module failed!");
}
// Check Firmware
String fv = WiFi.firmwareVersion();
if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
msgPrintln("Please upgrade the firmware!");
}
// Print state
msgPrint("Connect to SSID: ");
msgPrint(ssid);
// Connect to network
int connectionAttempts = 0;
while (true) {
// Connect
status = WiFi.begin(ssid, pass);
// Check state
if(status == WL_CONNECTED){
break;
}
else if(connectionAttempts > 100){
exit("Can not connect to Wifi!");
}
else{
delay(2000);
msgPrint(".");
connectionAttempts++;
}
}
// Connection sucessful: Print state
msgPrint("\nConnected to WiFi: ");
msgPrintln(ssid);
//printWifiStatus();
}
//-----------------------------------------------------------------------------------------------
Response request(String server, String path, int port, String header, String httpMethod, String postData){
// Print state
msgPrint("Request: ");
msgPrint(httpMethod);
msgPrint(" ");
msgPrint(server);
msgPrint(path);
msgPrint(" - ");
msgPrintln(postData);
// Make request
HttpClient client = HttpClient(wifi, server, port);
client.beginRequest();
// Switch HTTP Method
if(httpMethod.compareTo(HTTP_METHOD_GET) == 0){
client.get(path);
}
else if(httpMethod.compareTo(HTTP_METHOD_POST) == 0){
client.post(path);
}
else if(httpMethod.compareTo(HTTP_METHOD_PUT) == 0){
client.put(path);
}
else if(httpMethod.compareTo(HTTP_METHOD_PATCH) == 0){
client.patch(path);
}
else if(httpMethod.compareTo(HTTP_METHOD_DELETE) == 0){
client.del(path);
}
// Set Headers and body
client.sendHeader(header);
client.sendHeader("Content-Type", "application/json");
client.sendHeader("Content-Length", postData.length());
client.beginBody();
client.print(postData);
client.endRequest();
// Get response
int status = client.responseStatusCode();
String body = client.responseBody();
// Print state
msgPrint("Response: ");
msgPrint(String(status));
msgPrint(" ");
msgPrintln(body);
// Copy to response
Response res = {status, body};
return res;
}
//-----------------------------------------------------------------------------------------------
void printWifiStatus() {
msgPrintln("\n\nWiFi connection state\n-------------------------------------");
// Print the SSID of the network you're attached to:
msgPrint("SSID: ");
msgPrintln(String(WiFi.SSID()));
// Print your board's IP address:
IPAddress ip = WiFi.localIP();
msgPrint("IP Address: ");
msgPrintln(String(ip));
// Print the received signal strength:
long rssi = WiFi.RSSI();
msgPrint("signal strength (RSSI):");
msgPrint(String(rssi));
msgPrintln(" dBm\n");
}
| [
"christian.rathemacher@weltenbauer-se.com"
] | christian.rathemacher@weltenbauer-se.com |
2a4461a0a4dd9e7b399b32c016fa48e998d883ae | cc9ae71207dc667c2e0be27671ced5c86f2f71a3 | /test/oldstudy/class_array.cpp | d0663fe13534f156229ae4051ec3c7a7b4702414 | [] | no_license | xm0629/c-study | aed8480aa30b35637bfca307e009eb8b827b328d | 26183be9c91b2b53bd71b6693fe6d39823bc5d63 | refs/heads/master | 2020-04-09T11:35:48.047562 | 2019-03-30T15:27:01 | 2019-03-30T15:27:01 | 160,316,327 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 613 | cpp | // 对象数组
# include <iostream>
using namespace std;
class Box
{
public:
Box(int h=10, int w=12, int len=15):height(h),width(w),length(len){}
int volume();
private:
int height;
int width;
int length;
};
int Box::volume()
{
return (height*width*length);
}
int main()
{
Box a[3] = {
Box(10,12,15),
Box(15,15,15),
Box(20,10,15)
};
cout << "volume of a[0] is " << a[0].volume() << endl;
cout << "volume of a[1] is " << a[1].volume() << endl;
cout << "volume of a[2] is " << a[2].volume() << endl;
return 0;
}
| [
"920972751@qq.com"
] | 920972751@qq.com |
a64e093d5d373559c712cb30cd4f734a20b4f052 | b0c8bc79873ca7136c19b62adbe07107fcbf7cd8 | /types/Body.cpp | b8bc1bdcff41c4474146a6daeaa94cb1bc32d243 | [] | no_license | Giulianos/ss-2018b-tp4 | 3de51cf709013acc74169e2ad617157866131462 | dd6d8408b66628a9931ef49f996df5424d45db15 | refs/heads/master | 2020-05-29T18:03:14.186634 | 2018-11-11T23:49:59 | 2018-11-11T23:49:59 | 189,294,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,966 | cpp | //
// Created by Giuliano Scaglioni on 05/11/2018.
//
#include "Body.h"
#include <cmath>
#include <cstdio>
int Body::next_id = 0;
double
Body::get_radius() const
{
return radius;
}
double
Body::get_mass() const
{
return mass;
}
Body::Body(double x, double y, double vx, double vy, double radius, double mass)
: current_x(x)
, previous_x(x)
, current_y(y)
, previous_y(y)
, current_vx(vx)
, current_vy(vy)
, previous_vx(vx)
, previous_vy(vy)
, current_ax(0)
, current_ay(0)
, previous_ax(0)
, previous_ay(0)
, radius(radius)
, mass(mass)
, id(Body::next_id++)
{}
double
Body::get_x() const
{
return current_x;
}
double
Body::get_y() const
{
return current_y;
}
double
Body::get_vx() const
{
return current_vx;
}
double
Body::get_vy() const
{
return current_vy;
}
double
Body::get_ax() const
{
return current_ax;
}
double
Body::get_ay() const
{
return current_ay;
}
double
Body::get_previous_ax() const
{
return previous_ax;
}
double
Body::get_previous_ay() const
{
return previous_ay;
}
int
Body::get_id() const
{
return id;
}
void
Body::set_x(double x)
{
Body::future_x = x;
}
void
Body::set_y(double y)
{
Body::future_y = y;
}
void
Body::set_vx(double vx)
{
Body::future_vx = vx;
}
void
Body::set_vy(double vy)
{
Body::future_vy = vy;
}
void
Body::set_ax(double ax)
{
Body::future_ax = ax;
}
void
Body::set_ay(double ay)
{
Body::future_ay = ay;
}
void
Body::update()
{
/** Update position */
previous_x = current_x;
previous_y = current_y;
current_x = future_x;
current_y = future_y;
future_x = NAN;
future_y = NAN;
/** Update velocity */
previous_vx = current_vx;
previous_vy = current_vy;
current_vx = future_vx;
current_vy = future_vy;
future_vx = NAN;
future_vy = NAN;
/** Update acceleration */
previous_ax = current_ax;
previous_ay = current_ay;
current_ax = future_ax;
current_ay = future_ay;
future_ax = NAN;
future_ay = NAN;
}
| [
"scaglionigiuliano@gmail.com"
] | scaglionigiuliano@gmail.com |
fbdc5177ac9c49fb3c7afefb53a4d3b6018f350c | 2124d0b0d00c3038924f5d2ad3fe14b35a1b8644 | /source/GamosCore/GamosScoring/Scorers/src/GmPSLET_dEdx_unrestrD.cc | d32e8b41e13aa1ef9d16ff1f24e2b34e9b8d41e1 | [] | no_license | arceciemat/GAMOS | 2f3059e8b0992e217aaf98b8591ef725ad654763 | 7db8bd6d1846733387b6cc946945f0821567662b | refs/heads/master | 2023-07-08T13:31:01.021905 | 2023-06-26T10:57:43 | 2023-06-26T10:57:43 | 21,818,258 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,835 | cc | //#define VERBOSE_DOSEDEP
#include "GmPSLET_dEdx_unrestrD.hh"
#include "G4VPrimitiveScorer.hh"
#include "GamosCore/GamosScoring/Management/include/GmScoringVerbosity.hh"
#include "GamosCore/GamosUtils/include/GmGenUtils.hh"
#include "GamosCore/GamosBase/Base/include/GmParameterMgr.hh"
#include "G4EmParameters.hh"
#include "G4ProcessType.hh"
#include "G4VProcess.hh"
//--------------------------------------------------------------------
GmPSLET_dEdx_unrestrD::GmPSLET_dEdx_unrestrD(G4String name)
:GmCompoundScorer(name)
{
theUnit = 1;
theUnitName = "MeV/mm";
bInitialized = false;
// theNEventsType = SNET_ByNFilled;
G4EmParameters::Instance()->SetBuildCSDARange(true); // to build G4VEnergyLossProcess::theDEDXunRestrictedTable
}
//--------------------------------------------------------------------
G4bool GmPSLET_dEdx_unrestrD::ProcessHits(G4Step* aStep,G4TouchableHistory* th)
{
G4ProcessType procType = aStep->GetPostStepPoint()->GetProcessDefinedStep()->GetProcessType();
if( procType == fTransportation || procType == fElectromagnetic ) {
GmCompoundScorer::ProcessHits(aStep,th);
return true;
} else {
return false;
}
}
//--------------------------------------------------------------------
void GmPSLET_dEdx_unrestrD::SetParameters( const std::vector<G4String>& params)
{
if( params.size() != 0 ){
G4String parastr;
for( unsigned int ii = 0; ii < params.size(); ii++ ){
parastr += params[ii] + " ";
}
G4Exception("GmPSLET_dEdx_unrestrD::SetParameters",
"There should no parameters",FatalErrorInArgument,G4String("They are: "+parastr).c_str());
}
std::vector<G4String> paramsNC;
paramsNC.push_back("GmPSDose_LET_dEdx_unrestr/GmPSdEdxElectronicELoss"); // GmPSElectronicELoss unrestricted E lost
GmCompoundScorer::SetParameters(paramsNC);
}
| [
"pedro.arce@ciemat.es"
] | pedro.arce@ciemat.es |
5b1ca8adfc4cc8c5e62109714d4b9004789812cc | 4c25432a6d82aaebd82fd48e927317b15a6bf6ab | /data/dataset_2017/dataset_2017_8/ss1h2a3tw/5304486_5760761888505856_ss1h2a3tw.cpp | 2912af530b40ae4bc2009b57cba2a4b914ae51c6 | [] | no_license | wzj1988tv/code-imitator | dca9fb7c2e7559007e5dbadbbc0d0f2deeb52933 | 07a461d43e5c440931b6519c8a3f62e771da2fc2 | refs/heads/master | 2020-12-09T05:33:21.473300 | 2020-01-09T15:29:24 | 2020-01-09T15:29:24 | 231,937,335 | 1 | 0 | null | 2020-01-05T15:28:38 | 2020-01-05T15:28:37 | null | UTF-8 | C++ | false | false | 1,804 | cpp | #include <cstdio>
#include <algorithm>
using namespace std;
char cake[30][30];
int r,c;
int main (){
int T;
scanf("%d",&T);
for(int I = 1 ; I <= T ; I++){
scanf("%d%d",&r,&c);
for(int i = 0 ; i < r ; i ++){
scanf("%s",cake[i]);
}
bool firstempty=true;
for(int i = 0 ; i < c ; i ++){
if(cake[0][i]!='?')firstempty=false;
}
if(firstempty){
int nonempty=0;
for(int i = 0 ; i < r ; i ++){
bool empty=true;
for(int j = 0 ; j < c ; j ++){
if(cake[i][j]!='?')empty=false;
}
if(!empty){
nonempty=i;
break;
}
}
for(int i = 0 ; i < c ; i ++){
cake[0][i]=cake[nonempty][i];
}
}
for(int i = 1 ; i < r ; i ++){
bool empty=true;
for(int j = 0 ; j < c ; j ++){
if(cake[i][j]!='?')empty=false;
}
if(empty){
for(int j = 0 ; j < c ; j ++){
cake[i][j]=cake[i-1][j];
}
}
}
for(int i = 0 ; i < r ; i ++){
if(cake[i][0]=='?'){
for(int j = 0 ; j < c ; j ++ ){
if(cake[i][j]!='?'){
cake[i][0]=cake[i][j];
break;
}
}
}
for(int j = 0 ; j < c ; j ++){
if(cake[i][j]=='?'){
cake[i][j]=cake[i][j-1];
}
}
}
printf("Case #%d:\n",I);
for(int i = 0 ; i < r ; i ++){
printf("%s\n",cake[i]);
}
}
}
| [
"e.quiring@tu-bs.de"
] | e.quiring@tu-bs.de |
2d5f06a73a8becc601aab6f1fe95b7438e270d85 | 3ca7dd1e368194aa2f884139d01f802073cbbe0d | /Codeforces/solved/20C/20C.cpp | e46ba3d0d2b577fce5b47ede86f0fe7e77d0b6ba | [] | no_license | callistusystan/Algorithms-and-Data-Structures | 07fd1a87ff3cfb07326f9f18513386a575359447 | 560e860ca1e546b7e7930d4e1bf2dd7c3acbcbc5 | refs/heads/master | 2023-02-17T17:29:21.678463 | 2023-02-11T09:12:40 | 2023-02-11T09:12:40 | 113,574,821 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,181 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pii;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int N, M; cin >> N >> M;
vector<vector<pair<int, ll>>> adjList(N+5);
for (int i=0;i<M;i++) {
int u,v,w; cin >> u >> v >> w;
adjList[u].push_back({v,w});
adjList[v].push_back({u,w});
}
vector<ll> dist(N+5, -1);
priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pq;
vi parent(N+5, -1);
dist[1] = 0;
pq.push({0,1});
while (!pq.empty()) {
auto top = pq.top(); pq.pop();
ll d = top.first;
int cur = top.second;
if (d > dist[cur]) continue;
for (auto e : adjList[cur]) {
int v = e.first; ll w = e.second;
if (dist[v] == -1 || d+w < dist[v]) {
parent[v] = cur;
dist[v] = d+w;
pq.push({ d+w, v });
}
}
}
if (dist[N] == -1) cout << -1 << endl;
else {
vi ans;
int cur = N;
while (cur != -1) {
ans.push_back(cur);
cur = parent[cur];
}
while (ans.size()) {
cout << ans.back() << " ";
ans.pop_back();
}
cout << endl;
}
return 0;
}
| [
"callistusystan@gmail.com"
] | callistusystan@gmail.com |
2cb63511678f4ee4ca3e068f7b21bf81a78ee107 | 1a9df829cfba53d1032a4e4fd60f40e998af2924 | /src/predict_pseudo.cpp | a7c164e20b52f1b1978e441e54dff1e2c04bfd66 | [] | no_license | X4vier/MC-AIXI-CTW | bf30c2610ed5435e4ba741e6daa741c8176a3789 | ea2e98e95352166f8d707a200e67fb0e30690376 | refs/heads/master | 2020-04-04T15:41:17.541126 | 2018-11-04T04:17:40 | 2018-11-04T04:17:40 | 156,047,993 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,438 | cpp | #include "predict_pseudo.hpp"
#include <cassert>
#include <ctime>
#include <cmath>
#include "util.hpp"
// create a context tree of specified maximum depth
ContextTree::ContextTree(size_t depth) { return; }
ContextTree::~ContextTree(void) { return; }
// clear the entire context tree
void ContextTree::clear(void) { return; }
void ContextTree::update(const symbol_t sym) { return; }
void ContextTree::update(const symbol_list_t &symbol_list)
{
if (symbol_list.size() == 1)
{
last_action = symbol_list[0];
}
return;
}
// updates the history statistics, without touching the context tree
void ContextTree::updateHistory(const symbol_list_t &symbol_list) { return; }
// removes the most recently observed symbol from the context tree
void ContextTree::revert(void) { return; }
// shrinks the history down to a former size
// NOTE: this method keeps the old observations and discards the most recent bits
void ContextTree::revertHistory(size_t newsize) { return; }
// generate a specified number of random symbols
// distributed according to the context tree statistics
void ContextTree::genRandomSymbols(symbol_list_t &symbols, size_t bits)
{
genRandomSymbolsAndUpdate(symbols, bits);
}
// generate a specified number of random symbols distributed according to
// the context tree statistics and update the context tree (and history) with the newly
// generated bits
void ContextTree::genRandomSymbolsAndUpdate(symbol_list_t &symbols, size_t bits)
{
//srand(time(0)); Please don't call srand here.
//In general we should call srand once in the main,
//maybe srand(time(0)) by default and provide an option
//to manually specify the seed so that
//we can reproduce the exact behaviour when testing.
if (rand01() < 0.7)
{
symbols.push_back(1);
if (last_action)
{
symbols.push_back(1);
}
else
{
symbols.push_back(0);
}
}
else
{
symbols.push_back(0);
if (last_action)
{
symbols.push_back(0);
}
else
{
symbols.push_back(1);
}
}
}
// the logarithm of the block probability of the whole sequence
double ContextTree::logBlockProbability(void) { return 0.0; }
// get the n'th most recent history symbol, NULL if doesn't exist
const symbol_t *ContextTree::nthHistorySymbol(size_t n) const { return NULL; }
| [
"xavier.orourke@gmail.com"
] | xavier.orourke@gmail.com |
76250cfc3e8d3fdee22df78981ee158920f82865 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /ash/touch/touch_uma.cc | 4ae3adcf97ee2383a8429db685e84d602ae1d86f | [
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 10,965 | cc | // 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.
#include "ash/touch/touch_uma.h"
#include "ash/common/wm_shell.h"
#include "base/metrics/histogram.h"
#include "base/strings/stringprintf.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/aura/window_property.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/views/widget/widget.h"
#if defined(USE_X11)
#include <X11/extensions/XInput2.h>
#include <X11/Xlib.h>
#endif
namespace {
struct WindowTouchDetails {
// Move and start times of the touch points. The key is the touch-id.
std::map<int, base::TimeTicks> last_move_time_;
std::map<int, base::TimeTicks> last_start_time_;
// The first and last positions of the touch points.
std::map<int, gfx::Point> start_touch_position_;
std::map<int, gfx::Point> last_touch_position_;
// Last time-stamp of the last touch-end event.
base::TimeTicks last_release_time_;
// Stores the time of the last touch released on this window (if there was a
// multi-touch gesture on the window, then this is the release-time of the
// last touch on the window).
base::TimeTicks last_mt_time_;
};
DEFINE_OWNED_WINDOW_PROPERTY_KEY(WindowTouchDetails, kWindowTouchDetails, NULL);
}
DECLARE_WINDOW_PROPERTY_TYPE(WindowTouchDetails*);
namespace ash {
// static
TouchUMA* TouchUMA::GetInstance() {
return base::Singleton<TouchUMA>::get();
}
void TouchUMA::RecordGestureEvent(aura::Window* target,
const ui::GestureEvent& event) {
GestureActionType action = FindGestureActionType(target, event);
RecordGestureAction(action);
if (event.type() == ui::ET_GESTURE_END &&
event.details().touch_points() == 2) {
WindowTouchDetails* details = target->GetProperty(kWindowTouchDetails);
if (!details) {
LOG(ERROR) << "Window received gesture events without receiving any touch"
" events";
return;
}
details->last_mt_time_ = event.time_stamp();
}
}
void TouchUMA::RecordGestureAction(GestureActionType action) {
if (action == GESTURE_UNKNOWN || action >= GESTURE_ACTION_COUNT)
return;
UMA_HISTOGRAM_ENUMERATION("Ash.GestureTarget", action, GESTURE_ACTION_COUNT);
}
void TouchUMA::RecordTouchEvent(aura::Window* target,
const ui::TouchEvent& event) {
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Ash.TouchRadius",
static_cast<int>(std::max(event.pointer_details().radius_x,
event.pointer_details().radius_y)),
1, 500, 100);
UpdateTouchState(event);
WindowTouchDetails* details = target->GetProperty(kWindowTouchDetails);
if (!details) {
details = new WindowTouchDetails;
target->SetProperty(kWindowTouchDetails, details);
}
// Record the location of the touch points.
const int kBucketCountForLocation = 100;
const gfx::Rect bounds = target->GetRootWindow()->bounds();
const int bucket_size_x =
std::max(1, bounds.width() / kBucketCountForLocation);
const int bucket_size_y =
std::max(1, bounds.height() / kBucketCountForLocation);
gfx::Point position = event.root_location();
// Prefer raw event location (when available) over calibrated location.
if (event.HasNativeEvent()) {
position = ui::EventLocationFromNative(event.native_event());
position = gfx::ScaleToFlooredPoint(
position, 1.f / target->layer()->device_scale_factor());
}
position.set_x(std::min(bounds.width() - 1, std::max(0, position.x())));
position.set_y(std::min(bounds.height() - 1, std::max(0, position.y())));
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Ash.TouchPositionX", position.x() / bucket_size_x, 1,
kBucketCountForLocation, kBucketCountForLocation + 1);
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Ash.TouchPositionY", position.y() / bucket_size_y, 1,
kBucketCountForLocation, kBucketCountForLocation + 1);
if (event.type() == ui::ET_TOUCH_PRESSED) {
WmShell::Get()->RecordUserMetricsAction(UMA_TOUCHSCREEN_TAP_DOWN);
details->last_start_time_[event.touch_id()] = event.time_stamp();
details->start_touch_position_[event.touch_id()] = event.root_location();
details->last_touch_position_[event.touch_id()] = event.location();
if (details->last_release_time_.ToInternalValue()) {
// Measuring the interval between a touch-release and the next
// touch-start is probably less useful when doing multi-touch (e.g.
// gestures, or multi-touch friendly apps). So count this only if the user
// hasn't done any multi-touch during the last 30 seconds.
base::TimeDelta diff = event.time_stamp() - details->last_mt_time_;
if (diff.InSeconds() > 30) {
base::TimeDelta gap = event.time_stamp() - details->last_release_time_;
UMA_HISTOGRAM_COUNTS_10000("Ash.TouchStartAfterEnd",
gap.InMilliseconds());
}
}
// Record the number of touch-points currently active for the window.
const int kMaxTouchPoints = 10;
UMA_HISTOGRAM_CUSTOM_COUNTS("Ash.ActiveTouchPoints",
details->last_start_time_.size(), 1,
kMaxTouchPoints, kMaxTouchPoints + 1);
} else if (event.type() == ui::ET_TOUCH_RELEASED) {
if (details->last_start_time_.count(event.touch_id())) {
base::TimeDelta duration =
event.time_stamp() - details->last_start_time_[event.touch_id()];
// Look for touches that were [almost] stationary for a long time.
const double kLongStationaryTouchDuration = 10;
const int kLongStationaryTouchDistanceSquared = 100;
if (duration.InSecondsF() > kLongStationaryTouchDuration) {
gfx::Vector2d distance =
event.root_location() -
details->start_touch_position_[event.touch_id()];
if (distance.LengthSquared() < kLongStationaryTouchDistanceSquared) {
UMA_HISTOGRAM_CUSTOM_COUNTS("Ash.StationaryTouchDuration",
duration.InSeconds(),
kLongStationaryTouchDuration, 1000, 20);
}
}
}
details->last_start_time_.erase(event.touch_id());
details->last_move_time_.erase(event.touch_id());
details->start_touch_position_.erase(event.touch_id());
details->last_touch_position_.erase(event.touch_id());
details->last_release_time_ = event.time_stamp();
} else if (event.type() == ui::ET_TOUCH_MOVED) {
int distance = 0;
if (details->last_touch_position_.count(event.touch_id())) {
gfx::Point lastpos = details->last_touch_position_[event.touch_id()];
distance =
std::abs(lastpos.x() - event.x()) + std::abs(lastpos.y() - event.y());
}
if (details->last_move_time_.count(event.touch_id())) {
base::TimeDelta move_delay =
event.time_stamp() - details->last_move_time_[event.touch_id()];
UMA_HISTOGRAM_CUSTOM_COUNTS("Ash.TouchMoveInterval",
move_delay.InMilliseconds(), 1, 50, 25);
}
UMA_HISTOGRAM_CUSTOM_COUNTS("Ash.TouchMoveSteps", distance, 1, 1000, 50);
details->last_move_time_[event.touch_id()] = event.time_stamp();
details->last_touch_position_[event.touch_id()] = event.location();
}
}
TouchUMA::TouchUMA()
: is_single_finger_gesture_(false),
touch_in_progress_(false),
burst_length_(0) {}
TouchUMA::~TouchUMA() {}
void TouchUMA::UpdateTouchState(const ui::TouchEvent& event) {
if (event.type() == ui::ET_TOUCH_PRESSED) {
if (!touch_in_progress_) {
is_single_finger_gesture_ = true;
base::TimeDelta difference = event.time_stamp() - last_touch_down_time_;
if (difference > base::TimeDelta::FromMilliseconds(250)) {
if (burst_length_) {
UMA_HISTOGRAM_COUNTS_100("Ash.TouchStartBurst",
std::min(burst_length_, 100));
}
burst_length_ = 1;
} else {
++burst_length_;
}
} else {
is_single_finger_gesture_ = false;
}
touch_in_progress_ = true;
last_touch_down_time_ = event.time_stamp();
} else if (event.type() == ui::ET_TOUCH_RELEASED) {
if (!aura::Env::GetInstance()->is_touch_down())
touch_in_progress_ = false;
}
}
GestureActionType TouchUMA::FindGestureActionType(
aura::Window* window,
const ui::GestureEvent& event) {
if (!window || window->GetRootWindow() == window) {
if (event.type() == ui::ET_GESTURE_SCROLL_BEGIN)
return GESTURE_BEZEL_SCROLL;
if (event.type() == ui::ET_GESTURE_BEGIN)
return GESTURE_BEZEL_DOWN;
return GESTURE_UNKNOWN;
}
std::string name = window ? window->name() : std::string();
const char kWallpaperView[] = "WallpaperView";
if (name == kWallpaperView) {
if (event.type() == ui::ET_GESTURE_SCROLL_BEGIN)
return GESTURE_DESKTOP_SCROLL;
if (event.type() == ui::ET_GESTURE_PINCH_BEGIN)
return GESTURE_DESKTOP_PINCH;
return GESTURE_UNKNOWN;
}
const char kWebPage[] = "RenderWidgetHostViewAura";
if (name == kWebPage) {
if (event.type() == ui::ET_GESTURE_PINCH_BEGIN)
return GESTURE_WEBPAGE_PINCH;
if (event.type() == ui::ET_GESTURE_SCROLL_BEGIN)
return GESTURE_WEBPAGE_SCROLL;
if (event.type() == ui::ET_GESTURE_TAP)
return GESTURE_WEBPAGE_TAP;
return GESTURE_UNKNOWN;
}
views::Widget* widget = views::Widget::GetWidgetForNativeView(window);
if (!widget)
return GESTURE_UNKNOWN;
// |widget| may be in the process of destroying if it has ownership
// views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET and |event| was
// dispatched as part of gesture state cleanup. In this case the RootView
// of |widget| may no longer exist, so check before calling into any
// RootView methods.
if (!widget->GetRootView())
return GESTURE_UNKNOWN;
views::View* view =
widget->GetRootView()->GetEventHandlerForPoint(event.location());
if (!view)
return GESTURE_UNKNOWN;
name = view->GetClassName();
const char kTabStrip[] = "TabStrip";
const char kTab[] = "BrowserTab";
if (name == kTabStrip || name == kTab) {
if (event.type() == ui::ET_GESTURE_SCROLL_BEGIN)
return GESTURE_TABSTRIP_SCROLL;
if (event.type() == ui::ET_GESTURE_PINCH_BEGIN)
return GESTURE_TABSTRIP_PINCH;
if (event.type() == ui::ET_GESTURE_TAP)
return GESTURE_TABSTRIP_TAP;
return GESTURE_UNKNOWN;
}
const char kOmnibox[] = "BrowserOmniboxViewViews";
if (name == kOmnibox) {
if (event.type() == ui::ET_GESTURE_SCROLL_BEGIN)
return GESTURE_OMNIBOX_SCROLL;
if (event.type() == ui::ET_GESTURE_PINCH_BEGIN)
return GESTURE_OMNIBOX_PINCH;
return GESTURE_UNKNOWN;
}
return GESTURE_UNKNOWN;
}
} // namespace ash
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
e91dbf012f8644c94b5e87a8a9878e7b6b9d37a4 | 8de5fa2abac197367077f8aae43c16c3ce2f9ad2 | /1010. Radix (25).cpp | 07d045461518bce47ab9bb83c0f7dc4f54598909 | [] | no_license | zhoujf620/PAT-Practice | 2220435e9a27cbbe8230263f7ad0b5572138e3fb | c2b856f530af1f4ea38dfb4992eb974081a4890b | refs/heads/master | 2020-12-04T23:24:56.252091 | 2020-01-20T14:48:01 | 2020-01-20T14:48:01 | 231,934,012 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,310 | cpp | // 1010. Radix (25)
// Given a pair of positive integers, for example, 6 and 110, can this equation 6 = 110 be true? The answer is "yes", if 6 is a decimal number and 110 is a binary number.
// Now for any pair of positive integers N1 and N2, your task is to find the radix of one number while that of the other is given.
// Input Specification:
// Each input file contains one test case. Each case occupies a line which contains 4 positive integers:<br/>
// N1 N2 tag radix<br/>
// Here N1 and N2 each has no more than 10 digits. A digit is less than its radix and is chosen from the set {0-9, a-z} where 0-9 represent the decimal numbers 0-9, and a-z represent the decimal numbers 10-35. The last number "radix" is the radix of N1 if "tag" is 1, or of N2 if "tag" is 2.
// Output Specification:
// For each test case, print in one line the radix of the other number so that the equation N1 = N2 is true. If the equation is impossible, print "Impossible". If the solution is not unique, output the smallest possible radix.
// Sample Input 1:
// 6 110 1 10
// Sample Output 1:
// 2
// Sample Input 2:
// 1 ab 1 2
// Sample Output 2:
// Impossible
#include <iostream>
#include <algorithm>
#include<math.h>
using namespace std;
long long convert(string n, int radix) {
long long sum = 0;
int index = 0, temp = 0;
for (auto it = n.rbegin(); it != n.rend(); it++) {
temp = isdigit(*it) ? *it - '0' : *it - 'a' + 10;
sum += temp * pow(radix, index++);
}
return sum;
}
long long find_radix(string n, long long num) {
char it = *max_element(n.begin(), n.end());
long long low = (isdigit(it) ? it - '0': it - 'a' + 10) + 1;
long long high = max(num, low);
while (low <= high) {
long long mid = (low + high) / 2;
long long t = convert(n, mid);
if (t < 0 || t > num) high = mid - 1;
else if (t == num) return mid;
else low = mid + 1;
}
return -1;
}
int main() {
string N1, N2;
int tag = 0, radix = 0, result_radix;
cin >> N1 >> N2 >> tag >> radix;
result_radix = tag == 1 ? find_radix(N2, convert(N1, radix)) : find_radix(N1, convert(N2, radix));
if (result_radix != -1) {
printf("%d", result_radix);
} else {
printf("Impossible");
}
return 0;
} | [
"zhoujf620@zju.edu.cn"
] | zhoujf620@zju.edu.cn |
6cbf9d74c62652e42e372bf9fdba97dde802d950 | 6104eba97327b09b0d5f084c990b3bf50ef20ca6 | /STL_Univ/STL_Univ/unodered_set 과 map.cpp | 136e2cab3b514202d44c1f0e9421c80714ddcf01 | [
"MIT"
] | permissive | LeeKangW/CPP_Study | 03caf637d3cc797f6d8f5ed3121228f9e23f3232 | 897cd33ddeca79bbef6c4a084c309b40c6733334 | refs/heads/master | 2021-07-13T00:40:25.666219 | 2021-06-24T02:01:46 | 2021-06-24T02:01:46 | 222,482,593 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 1,203 | cpp | #include<iostream>
#include<unordered_set>
#include<random>
#include<thread>
#include"String.h"
#include"save.h"
using namespace std;
//2020.5.25 월
//
// unordered_set / unordered_map
//
// unordered associative container
// 1. 순서가 없다.
// 2. 메모리 구조를 출력
// 3. String을 이 컨테이너의 원소로 되도록 하려면
// hash 함수를 쓰기 때문에 찾을 때 O(1) 이 걸린다.
int main() {
/* initializer_list<int> x = { 1,2,3,4,5,6,7 };
// -> 클래스 생성자로 많이 씀.
// auto x = { 1,2,3,4,5,6,7 };
// cout << typeid(x).name() << endl;
*/
unordered_set<int> us{ 1,2,3,4,5,6,7,9 };
/*
hash 함수 설계 ( 아주 중요하다. )
-> hash<int>(); // 이름 없는 객체
*/
/*
for (int i = 0; i < 10; ++i)
{
// cout << hash<int>().operator()(i) << endl; // <- 원래 표기 법
cout << hash<int>()(i) << endl; // <- 좀 더 쉬운 표기 법
}
*/
// unordered_set의 메모리 모양을 화면에 출력한다.
/*
*/
for (int i = 0; i < us.bucket_count(); ++i) {
cout << "[" << i << "]";
if (us.bucket_size(i)) {
for (auto p = us.begin(i); p != us.end(i); ++p)
cout << " --> " << *p;
}
cout << endl;
}
} | [
"leegw1371@gmail.com"
] | leegw1371@gmail.com |
8c5166c1e4948cf10f1e75871e54dca34ff52d73 | 68c2c9f85e79fb2ce4fd3bb90d857b8be5bf9520 | /mathclass/src/subtraction.cpp | 601b946109a928df196456c796f38afe85b59430 | [
"LicenseRef-scancode-other-permissive",
"MIT"
] | permissive | mori-inj/Graphics | 556e6b7f7f722ec71f5ec5ede462e2e2b132f6a9 | 4923736e43f782e242f835074e8f67cb7653afd9 | refs/heads/master | 2021-01-01T16:47:37.426078 | 2019-06-13T20:25:47 | 2019-06-13T20:25:47 | 97,922,371 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,110 | cpp |
#include "mathclass.h"
namespace jhm {
unit_vector operator-( unit_vector const& a )
{
unit_vector b;
b.p[0] = - a.p[0];
b.p[1] = - a.p[1];
b.p[2] = - a.p[2];
return b;
}
vector operator-( vector const& a )
{
vector b;
b.p[0] = - a.p[0];
b.p[1] = - a.p[1];
b.p[2] = - a.p[2];
return b;
}
position& operator-=( position& a, vector const& b )
{
a.p[0] -= b.p[0];
a.p[1] -= b.p[1];
a.p[2] -= b.p[2];
return a;
}
vector& operator-=( vector& a, vector const& b )
{
a.p[0] -= b.p[0];
a.p[1] -= b.p[1];
a.p[2] -= b.p[2];
return a;
}
vector operator-( vector const& a, vector const& b )
{
vector c;
c.p[0] = a.p[0] - b.p[0];
c.p[1] = a.p[1] - b.p[1];
c.p[2] = a.p[2] - b.p[2];
return c;
}
vector operator-( position const& a, position const& b )
{
return vector( a.p[0] - b.p[0], a.p[1] - b.p[1], a.p[2] - b.p[2] );
}
position operator-( position const& a, vector const& b )
{
position c;
c.p[0] = a.p[0] - b.p[0];
c.p[1] = a.p[1] - b.p[1];
c.p[2] = a.p[2] - b.p[2];
return c;
}
} | [
"leokim1022@snu.ac.kr"
] | leokim1022@snu.ac.kr |
7608bccbf96cc36f9fc49a0202c905a139838fec | 64058e1019497fbaf0f9cbfab9de4979d130416b | /c++/src/app/blastdb/blastdbcp.cpp | f5a5ea06f3bc8d507c65afcf25da25f36af4ed0f | [
"MIT"
] | permissive | OpenHero/gblastn | 31e52f3a49e4d898719e9229434fe42cc3daf475 | 1f931d5910150f44e8ceab81599428027703c879 | refs/heads/master | 2022-10-26T04:21:35.123871 | 2022-10-20T02:41:06 | 2022-10-20T02:41:06 | 12,407,707 | 38 | 21 | null | 2020-12-08T07:14:32 | 2013-08-27T14:06:00 | C++ | UTF-8 | C++ | false | false | 11,559 | cpp | /* $Id: blastdbcp.cpp 347262 2011-12-15 14:16:31Z fongah2 $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*/
/** @file blastdbcp.cpp
* @author Christiam Camacho
*/
#include <ncbi_pch.hpp>
#include <corelib/ncbiapp.hpp>
#include <algo/blast/blastinput/cmdline_flags.hpp>
#include <objtools/blast/seqdb_writer/build_db.hpp>
USING_NCBI_SCOPE;
USING_SCOPE(blast);
/////////////////////////////////////////////////////////////////////////////
// BlastdbCopyApplication::
class BlastdbCopyApplication : public CNcbiApplication
{
public:
BlastdbCopyApplication();
private: /* Private Methods */
virtual void Init(void);
virtual int Run(void);
virtual void Exit(void);
bool x_ShouldParseSeqIds(const string& dbname,
CSeqDB::ESeqType seq_type) const;
bool x_ShouldCopyPIGs(const string& dbname,
CSeqDB::ESeqType seq_type) const;
private: /* Private Data */
bool m_bCheckOnly;
};
/////////////////////////////////////////////////////////////////////////////
// Constructor
BlastdbCopyApplication::BlastdbCopyApplication()
: m_bCheckOnly(false)
{
CRef<CVersion> version(new CVersion());
version->SetVersionInfo(1, 0);
SetFullVersion(version);
}
/////////////////////////////////////////////////////////////////////////////
// Init test for all different types of arguments
void BlastdbCopyApplication::Init(void)
{
// Create command-line argument descriptions class
auto_ptr<CArgDescriptions> arg_desc(new CArgDescriptions);
// Specify USAGE context
arg_desc->SetUsageContext(GetArguments().GetProgramBasename(),
"Performs a (deep) copy of a subset of a BLAST database");
arg_desc->SetCurrentGroup("BLAST database options");
arg_desc->AddDefaultKey(kArgDb, "dbname", "BLAST database name",
CArgDescriptions::eString, "nr");
arg_desc->AddDefaultKey(kArgDbType, "molecule_type",
"Molecule type stored in BLAST database",
CArgDescriptions::eString, "prot");
arg_desc->SetConstraint(kArgDbType, &(*new CArgAllow_Strings,
"nucl", "prot", "guess"));
arg_desc->SetCurrentGroup("Configuration options");
arg_desc->AddOptionalKey(kArgDbTitle, "database_title",
"Title for BLAST database",
CArgDescriptions::eString);
arg_desc->AddKey(kArgGiList, "input_file",
"Text or binary gi file to restrict the BLAST "
"database provided in -db argument",
CArgDescriptions::eString);
arg_desc->AddFlag("membership_bits", "Copy the membershi bits", true);
arg_desc->SetCurrentGroup("Output options");
arg_desc->AddOptionalKey(kArgOutput, "database_name",
"Name of BLAST database to be created",
CArgDescriptions::eString);
HideStdArgs(fHideConffile | fHideFullVersion | fHideXmlHelp | fHideDryRun);
SetupArgDescriptions(arg_desc.release());
}
class CBlastDbBioseqSource : public IBioseqSource
{
public:
CBlastDbBioseqSource(CRef<CSeqDBExpert> blastdb,
CRef<CSeqDBGiList> gilist,
bool copy_membership_bits = false)
{
CStopWatch total_timer, bioseq_timer, memb_timer;
total_timer.Start();
for (int i = 0; i < gilist->GetNumGis(); i++) {
const CSeqDBGiList::SGiOid& elem = gilist->GetGiOid(i);
int oid = 0;
if ( !blastdb->GiToOid(elem.gi, oid)) {
// not found on source BLASTDB, skip
continue;
}
if (m_Oids2Copy.insert(oid).second == false) {
// don't add the same OID twice to avoid duplicates
continue;
}
bioseq_timer.Start();
CConstRef<CBioseq> bs(&*blastdb->GetBioseq(oid));
m_Bioseqs.push_back(bs);
bioseq_timer.Stop();
if (copy_membership_bits == false)
continue;
memb_timer.Start();
CRef<CBlast_def_line_set> hdr = CSeqDB::ExtractBlastDefline(*bs);
ITERATE(CBlast_def_line_set::Tdata, itr, hdr->Get()) {
CRef<CBlast_def_line> bdl = *itr;
if (bdl->CanGetMemberships() &&
!bdl->GetMemberships().empty()) {
int memb_bits = bdl->GetMemberships().front();
if (memb_bits == 0) {
continue;
}
const string id = bdl->GetSeqid().front()->AsFastaString();
m_MembershipBits[memb_bits].push_back(id);
}
}
memb_timer.Stop();
}
total_timer.Stop();
ERR_POST(Info << "Will extract " << m_Bioseqs.size()
<< " sequences from the source database");
ERR_POST(Info << "Processed all input data in " << total_timer.AsSmartString());
ERR_POST(Info << "Processed bioseqs in " << bioseq_timer.AsSmartString());
ERR_POST(Info << "Processed membership bits in " << memb_timer.AsSmartString());
}
const TLinkoutMap GetMembershipBits() const {
return m_MembershipBits;
}
virtual CConstRef<CBioseq> GetNext()
{
if (m_Bioseqs.empty()) {
return CConstRef<CBioseq>(0);
}
CConstRef<CBioseq> retval = m_Bioseqs.back();
m_Bioseqs.pop_back();
return retval;
}
private:
typedef list< CConstRef<CBioseq> > TBioseqs;
TBioseqs m_Bioseqs;
set<int> m_Oids2Copy;
TLinkoutMap m_MembershipBits;
};
bool BlastdbCopyApplication::x_ShouldParseSeqIds(const string& dbname,
CSeqDB::ESeqType seq_type) const
{
vector<string> file_paths;
CSeqDB::FindVolumePaths(dbname, seq_type, file_paths);
const char type = (seq_type == CSeqDB::eProtein ? 'p' : 'n');
bool retval = false;
const char* isam_extensions[] = { "si", "sd", "ni", "nd", NULL };
ITERATE(vector<string>, f, file_paths) {
for (int i = 0; isam_extensions[i] != NULL; i++) {
CNcbiOstrstream oss;
oss << *f << "." << type << isam_extensions[i];
const string fname = CNcbiOstrstreamToString(oss);
CFile file(fname);
if (file.Exists() && file.GetLength() > 0) {
retval = true;
break;
}
}
if (retval) break;
}
return retval;
}
bool BlastdbCopyApplication::x_ShouldCopyPIGs(const string& dbname,
CSeqDB::ESeqType seq_type) const
{
if(CSeqDB::eProtein != seq_type)
return false;
vector<string> file_paths;
CSeqDB::FindVolumePaths(dbname, CSeqDB::eProtein, file_paths);
ITERATE(vector<string>, f, file_paths) {
CNcbiOstrstream oss;
oss << *f << "." << "ppd";
const string fname = CNcbiOstrstreamToString(oss);
CFile file(fname);
if (file.Exists() && file.GetLength() > 0)
return true;
}
return false;
}
/////////////////////////////////////////////////////////////////////////////
// Run the program
int BlastdbCopyApplication::Run(void)
{
int retval = 0;
const CArgs& args = GetArgs();
// Setup Logging
if (args["logfile"]) {
SetDiagPostLevel(eDiag_Info);
SetDiagPostFlag(eDPF_All);
time_t now = time(0);
LOG_POST( Info << string(72,'-') << "\n" << "NEW LOG - " << ctime(&now) );
}
CSeqDB::ESeqType seq_type = CSeqDB::eUnknown;
try {{
seq_type = ParseMoleculeTypeString(args[kArgDbType].AsString());
CRef<CSeqDBGiList> gilist(new CSeqDBFileGiList(args[kArgGiList].AsString()));
CRef<CSeqDBExpert> sourcedb(new CSeqDBExpert(args[kArgDb].AsString(), seq_type));
string title;
if (args[kArgDbTitle].HasValue()) {
title = args[kArgDbTitle].AsString();
} else {
CNcbiOstrstream oss;
oss << "Copy of '" << sourcedb->GetDBNameList() << "': " << sourcedb->GetTitle();
title = CNcbiOstrstreamToString(oss);
}
const bool kCopyPIGs = x_ShouldCopyPIGs(args[kArgDb].AsString(),
seq_type);
CBlastDbBioseqSource bioseq_source(sourcedb, gilist,
args["membership_bits"]);
const bool kIsSparse = false;
const bool kParseSeqids = x_ShouldParseSeqIds(args[kArgDb].AsString(),
seq_type);
const bool kUseGiMask = false;
CStopWatch timer;
timer.Start();
CBuildDatabase destdb(args[kArgOutput].AsString(), title,
static_cast<bool>(seq_type == CSeqDB::eProtein),
kIsSparse, kParseSeqids, kUseGiMask,
&(args["logfile"].HasValue()
? args["logfile"].AsOutputFile() : cerr));
destdb.SetUseRemote(false);
//destdb.SetVerbosity(true);
destdb.SetSourceDb(sourcedb);
destdb.StartBuild();
destdb.SetMembBits(bioseq_source.GetMembershipBits(), false);
destdb.AddSequences(bioseq_source, kCopyPIGs);
destdb.EndBuild();
timer.Stop();
ERR_POST(Info << "Created BLAST database in " << timer.AsSmartString());
}}
catch (const CException& ex) {
LOG_POST( Error << ex );
DeleteBlastDb(args[kArgOutput].AsString(), seq_type);
retval = -1;
}
catch (...) {
LOG_POST( Error << "Unknown error in BlastdbCopyApplication::Run()" );
DeleteBlastDb(args[kArgOutput].AsString(), seq_type);
retval = -2;
}
return retval;
}
/////////////////////////////////////////////////////////////////////////////
// Cleanup
void BlastdbCopyApplication::Exit(void)
{
SetDiagStream(0);
}
/////////////////////////////////////////////////////////////////////////////
// MAIN
int main(int argc, const char* argv[])
{
// Execute main application function
return BlastdbCopyApplication().AppMain(argc, argv, 0, eDS_Default, 0);
}
| [
"zhao.kaiyong@gmail.com"
] | zhao.kaiyong@gmail.com |
2680efc3a2611a45fe87974c975071e244ad8eb4 | fd47ed69443b69ff56316cbc81131782f5c460a5 | /LogitechLcdWinamp/gen_lglcd/DrawableText.h | 6f0dcde0a06706344cd139863a2f473d65d560b8 | [] | no_license | koson/jawsper-projects | 820b436f89415e2de3176168c489447d1f26bb34 | d750c293ad33b568d304d27d81ed61d02a1ac1ae | refs/heads/master | 2021-01-18T05:54:34.359533 | 2013-01-31T15:35:41 | 2013-01-31T15:35:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 477 | h | #pragma once
#include "Fonts.h"
class DrawableText
{
bool m_Changed;
int m_X, m_Y, m_Width, m_MaxWidth;
wchar_t m_Str[MAX_PATH];
Font* m_Font;
int prev_len;
public:
DrawableText(int a_X, int a_Y, int a_Width, Font* a_Font ) :
m_X(a_X), m_Y(a_Y), m_Width(a_Width), m_MaxWidth(a_Width), m_Changed(false), m_Font(a_Font)
{ wcscpy_s( m_Str, MAX_PATH, L"" ); prev_len = -1; }
void SetText( const wchar_t* a_Str );
bool Draw( Surface* a_Surface );
}; | [
"jawsper@gmail.com@aa725750-22df-18b2-2580-202d682e9b9e"
] | jawsper@gmail.com@aa725750-22df-18b2-2580-202d682e9b9e |
89602e597f50b469bb7dfa05a9a5317c6f75d1d7 | 6a13fa167b2d4bcea80358562dfde6164ff29693 | /Scripts/Character.cpp | 270faa38d303816f56f96861b68fd5622e29a151 | [] | no_license | scrapzero/RPG-Zero-70 | 1e4130f38e42030bbf85c64177db188dc32fa5f7 | 19e95aff37b15949878458cae1f0f107b2ba7787 | refs/heads/master | 2023-06-30T08:09:28.794552 | 2023-06-15T15:30:40 | 2023-06-15T15:30:40 | 92,604,803 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 61,161 | cpp | #include "Character.h"
#include "MyScene.h"
#include "math.h"
bool KeyOK();
bool KeyCancel();
bool KeyRight();
bool KeyLeft();
bool KeyUp();
bool KeyDown();
CEffect1::CEffect1()
{
Effect[0] = "zero/BattleEffect1.png";
}
CEffect1::~CEffect1()
{
}
void CEffect1::PushEffect(CCharacterBase * fromChar, CCharacterBase * toChar)
{
SEffect bufSEf;
if (fromChar->enemyF == false) {
bufSEf.x = fromChar->x+15;
bufSEf.y = fromChar->y;
}
else {
bufSEf.x = fromChar->x;
bufSEf.y = fromChar->y;
}
if (toChar->enemyF == false) {
bufSEf.vx = (toChar->x+15 - bufSEf.x) / effectTime1;
bufSEf.vy = (toChar->y - bufSEf.y) / effectTime1;
}
else {
bufSEf.vx = (toChar->x - bufSEf.x) / effectTime1;
bufSEf.vy = (toChar->y - bufSEf.y) / effectTime1;
}
bufSEf.drawTime = 0;
vSEffect.push_back(bufSEf);
}
void CEffect1::DrawEffect()
{
for (int i = 0; i < vSEffect.size(); i++) {
vSEffect[i].x += vSEffect[i].vx;
vSEffect[i].y += vSEffect[i].vy;
vSEffect[i].y -= cos(DX_PI * vSEffect[i].drawTime / effectTime1)*3;
vSEffect[i].drawTime++;
if (vSEffect[i].drawTime > effectTime1) {
vSEffect.erase(vSEffect.begin());
i--;
}
else {
DxLib::SetDrawBlendMode(DX_BLENDMODE_ADD, 200);
Effect[0].DrawRota(vSEffect[i].x, vSEffect[i].y, vSEffect[i].y/300, 0);
DxLib::SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 255);
}
}
}
CCharacterBase::CCharacterBase()
{
live = true;
yuusya = false;
enemyF = false;
nusunda = false;
PDamageCut = 0;
HPBar = "zero/HPBar.png";
MPBar = "zero/MPBar.png";
smallHPBar = "zero/SmallHPBar.png";
smallMPBar = "zero/SmallMPBar.png";
Window[0]= "zero/ItemSelectWindow3.png";
Window[1] = "zero/StatusWindow2.png";
for (int i = 0; i < 8; i++) {
statusHenka[i] = 0;
}
for (int i = 0; i < 10; i++) {
skill[i].targetNum = 100;
}
doku = false;
mahi = false;
housin = false;
huchi = false;
hirumi = false;
damageDisplayTime = 121;
displayDamage = 0;
cureDisplayTime = 121;
displayCure = 0;
damageMPDisplayTime = 121;
displayDamageMP = 0;
cureMPDisplayTime = 121;
displayCureMP = 0;
statusChangeDisplayTime=121;
displayStatusChange =0;
damageCut[0] = 0;
damageCut[1] = 0;
skill30 = false;
skill50 = false;
for (int i = 0; i < 10; i++)
{
skill[i].useChar = this;
skill[i].Point = -1;
skill[i].cardNum = -1;
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
dropItem[i][j] = 0;
}
}
for (int i = 0; i < 4; i++) {
jikiSkillCard[i] = NULL;
}
normalAtack.useChar = this;
normalDefence.useChar = this;
}
CCharacterBase::~CCharacterBase()
{
}
void CCharacterBase::Reset()
{
doku = false;
mahi = false;
housin = false;
huchi = false;
hirumi = false;
damageDisplayTime = 121;
displayDamage = 0;
cureDisplayTime = 121;
displayCure = 0;
damageMPDisplayTime = 121;
displayDamageMP = 0;
cureMPDisplayTime = 121;
displayCureMP = 0;
statusChangeDisplayTime = 121;
displayStatusChange = 0;
tenmetsu = 121;
damageCut[0] = 0;
damageCut[1] = 0;
for (int i = 0; i < 8; i++) {
statusHenka[i] = 0;
}
}
void CCharacterBase::Loop()
{
}
void CCharacterBase::Draw(int x, int y)
{
}
void CCharacterBase::Draw(int x,int y, bool nameZurasi)
{
}
void CCharacterBase::statusHenkaReset()
{
for (int i = 0; i < 8; i++) {
statusHenka[i] = 0;
}
}
void CCharacterBase::GiveDamge(int amount,CTextWindow *textWindow)
{
Status[0] -= amount;
DethJudge(textWindow);
tenmetsu = effectTime1*-1;
damageDisplayTime = effectTime1*-1;
displayDamage = amount;
}
void CCharacterBase::GiveCureHP(int amount, CTextWindow * textWindow)
{
int bufI = 0;
bufI = Status[0];
Status[0] += amount;
if (Status[0] > MaxHP) {
Status[0] = MaxHP;
}
cureDisplayTime = effectTime1*-1;
displayCure = Status[0]-bufI;
}
void CCharacterBase::GiveDamgeMP(int amount, CTextWindow * textWindow)
{
Status[1] -= amount;
if (Status[1] < 0) {
Status[1] = 0;
}
damageMPDisplayTime = effectTime1*-1;
displayDamageMP = amount;
}
void CCharacterBase::GiveCureMP(int amount, CTextWindow * textWindow)
{
int bufI = 0;
bufI = Status[1];
Status[1] += amount;
if (Status[1] > MaxMP) {
Status[1] = MaxMP;
}
cureMPDisplayTime = effectTime1*-1;
displayCureMP = Status[1] - bufI;
}
void CCharacterBase::GiveButuriDamge(CCharacterBase *atackChar, Skill *atackSkill,int skillNum ,CTextWindow *textWindow, bool *hazureta)
{
int damage=0;
int bufI = 0;
int buffI = 1;
stringstream bufSS;
string bufS;
bufI = (float)Status[8] * 250/ atackChar->Status[7] /33;
if (atackChar->statusHenka[5] > 0) {
bufI *= (float)(10 - statusHenka[5]) / 10;
}
if (atackChar->statusHenka[5] < 0) {
bufI *= (float)(10 - statusHenka[5] * 2) / 10;
}
if (statusHenka[6] > 0) {
bufI *= (float)(10 + statusHenka[6] * 2) / 10;
}
if (statusHenka[6] < 0) {
bufI *= (float)(10 + statusHenka[6]) / 10;
}
bufI+=1;
if (bufI < GetRand(255) && *hazureta == false) {
effect1.PushEffect(atackChar, this);
damage = (float)atackSkill->power[skillNum] * atackChar->Atc * atackChar->Atc / Def / 100;
if (atackSkill->content[skillNum] == 1) {
damage = (float)atackSkill->power[skillNum] * atackChar->MAtc * atackChar->Atc / Def / 100;
}
if (atackSkill->content[skillNum] == 2) {
damage = (float)atackSkill->power[skillNum] * atackChar->Spd * atackChar->Atc / Def / 100;
}
switch (atackSkill->element)
{
case 0:break;
case 1:damage *= (260 - FireDef); break;
case 2:damage *= (260 - WoodDef); break;
case 3:damage *= (260 - WaterDef); break;
case 4:damage *= (260 - LightDef); break;
case 5:damage *= (260 - DarkDef) ; break;
default:
break;
}
if (atackSkill->element > 0) {
damage /= 200;
}
bufI = atackChar->Luck;
if (atackChar->statusHenka[7] > 0) {
bufI *= (float)(10 + statusHenka[7] * 4) / 10;
//bufI /= 10;
}
if (atackChar->statusHenka[7] < 0) {
bufI *= (float)(10 + statusHenka[7] / 10) / 10;
//bufI /= 10;
}
buffI = 1;
if (atackSkill->content[skillNum] == 3) {
buffI = 8;
}
if ((float)GetRand(100) < (float)buffI *(10 + bufI) / 15) {
damage *= 2.8;
textWindow->PushText("クリティカルヒット!");
}
if (atackChar->statusHenka[0] > 0) {
damage *= (float)(10 + atackChar->statusHenka[0] * 2) / 10;
//damage /= 10;
}
if (atackChar->statusHenka[0] < 0) {
damage *= (float)(10 + atackChar->statusHenka[0]) / 10;
//damage /= 10;
}
if (statusHenka[1] < 0) {
damage *= (float)(10 - statusHenka[1] * 2) / 10;
//damage /= 10;
}
if (statusHenka[1] > 0) {
damage *= (float)(10 - statusHenka[1]) / 10;
//damage /= 10;
}
damage *= (float)(GetRand(15) + 100)/100;
damage *= (float)(100 - damageCut[0])/100;
if (atackSkill->PMode == 0) {
damage *= (float)(20+atackSkill->Point)/20;
//damage /= 20;
}
if (yuusya == true) {
damage *= (float)(100 - PDamageCut*2) / 100;
}
if (atackSkill->PMode == 15 && atackSkill->Point >= 10) {
damage *= 2.8;
textWindow->PushText("渾身の一撃!");
}
if (damage <= 0) {
damage = 1;
}
bufSS << name.c_str();
bufSS<< "に";
bufSS << damage;
bufSS << "ダメージ与えた。";
textWindow->PushText(bufSS.str().c_str());
GiveDamge(damage, textWindow);
if (atackSkill->content[skillNum] == 4) {
atackChar->GiveCureHP((float)damage*0.12 + 1,textWindow);
bufS = atackChar->name.c_str();
bufS += "はHPを回復した。";
textWindow->PushText(bufS.c_str());
}
if (atackSkill->content[skillNum] == 5) {
atackChar->GiveCureMP((float)damage*0.06 + 1, textWindow);
bufS = atackChar->name.c_str();
bufS += "はMP回復した。";
textWindow->PushText(bufS.c_str());
}
if (atackSkill->content[skillNum] == 8) {
atackChar->GiveDamge((float)damage*0.06, textWindow);
bufS = atackChar->name.c_str();
bufS += "は反動でダメージを受けた。";
damageDisplayTime = 0;
textWindow->PushText(bufS.c_str());
}
}
else {
bufS += "攻撃が外れた。";
textWindow->PushText(bufS.c_str());
*hazureta = true;
}
}
void CCharacterBase::GiveMahouDamge(CCharacterBase * atackChar, Skill * atackSkill, int skillNum, CTextWindow * textWindow, bool *hazureta)
{
int damage = 0;
int bufI = 0;
int buffI = 1;
stringstream bufSS;
string bufS;
bufI = (float)Status[8] * 250 / atackChar->Status[7] / 33;
if (atackChar->statusHenka[5] > 0) {
bufI *= (float)(10 - statusHenka[5]) / 10;
}
if (atackChar->statusHenka[5] < 0) {
bufI *= (float)(10 - statusHenka[5] * 2) / 10;
}
if (statusHenka[6] > 0) {
bufI *= (float)(10 + statusHenka[6] * 2) / 10;
}
if (statusHenka[6] < 0) {
bufI *= (float)(10 + statusHenka[6]) / 10;
}
bufI += 1;
if (bufI < GetRand(255) && *hazureta==false) {
effect1.PushEffect(atackChar, this);
damage = (float)atackSkill->power[skillNum] * atackChar->MAtc * atackChar->MAtc / MDef / 100;
if (atackSkill->content[skillNum] == 1) {
damage = (float)atackSkill->power[skillNum] * atackChar->Atc * atackChar->MAtc / MDef / 100;
}
if (atackSkill->content[skillNum] == 2) {
damage = (float)atackSkill->power[skillNum] * atackChar->Atc * atackChar->Spd / MDef / 100;
}
switch (atackSkill->element)
{
case 0:break;
case 1:damage *= (260 - FireDef); break;
case 2:damage *= (260 - WoodDef); break;
case 3:damage *= (260 - WaterDef); break;
case 4:damage *= (260 - LightDef); break;
case 5:damage *= (260 - DarkDef); break;
default:
break;
}
if (atackSkill->element > 0) {
damage /= 200;
}
bufI = atackChar->Luck;
if (atackChar->statusHenka[7] > 0) {
bufI *= (float)(10 + statusHenka[7] * 4) / 10;
//bufI / 10;
}
if (atackChar->statusHenka[7] < 0) {
bufI *= (float)(10 + statusHenka[7]) / 10;
//bufI /= 10;
}
buffI = 1;
if (atackSkill->content[skillNum] == 3) {
buffI = 8;
}
if ((float)GetRand(100) < (float)buffI * (10 + bufI) / 15) {
damage *= 2.8;
textWindow->PushText("クリティカルヒット!");
}
if (atackChar->statusHenka[2] > 0) {
damage *= (float)(10 + atackChar->statusHenka[2] * 2) / 10;
//damage /= 10;
}
if (atackChar->statusHenka[2] < 0) {
damage *= (float)(10 + atackChar->statusHenka[2] / 10);
//damage /= 10;
}
if (statusHenka[3] < 0) {
damage *= (float)(10 - statusHenka[3] * 2) / 10;
//damage /= 10;
}
if (statusHenka[3] > 0) {
damage *= (float)(10 - statusHenka[3]) / 10;
//damage /= 10;
}
damage *= (float)(GetRand(15) + 100)/100;
damage *= (float)(100 - damageCut[1])/100;
if (atackSkill->PMode == 0) {
damage *= (20+atackSkill->Point);
damage /= 20;
}
if (yuusya == true) {
damage *= (float)(100 - PDamageCut * 2) / 100;
}
if (atackSkill->PMode == 15 && atackSkill->Point>=10) {
textWindow->PushText("渾身の一撃!");
damage *= 2.8;
}
if (damage <= 0) {
damage = 1;
}
bufSS << name.c_str();
bufSS << "に";
bufSS << damage;
bufSS << "ダメージ与えた。";
textWindow->PushText(bufSS.str().c_str());
GiveDamge(damage, textWindow);
bufSS.clear();
if (atackSkill->content[skillNum] == 4) {
atackChar->GiveCureHP((float)damage*0.12 + 1, textWindow);
bufS = atackChar->name.c_str();
bufS += "はHPを回復した。";
textWindow->PushText(bufS.c_str());
}
if (atackSkill->content[skillNum] == 5) {
atackChar->GiveCureMP((float)damage*0.06 + 1, textWindow);
bufS = atackChar->name.c_str();
bufS += "はMPを回復した。";
textWindow->PushText(bufS.c_str());
}
if (atackSkill->content[skillNum] == 8) {
atackChar->GiveDamge((float)damage*0.06, textWindow);
bufS = atackChar->name.c_str();
bufS += "は反動でダメージを受けた。";
damageDisplayTime = 0;
textWindow->PushText(bufS.c_str());
}
}
else {
bufS += "攻撃が外れた。";
textWindow->PushText(bufS.c_str());
*hazureta = true;
}
}
void CCharacterBase::Cure(Skill * atackSkill, int skillNum, CTextWindow * textWindow)
{
int bufI=0;
string bufS = name.c_str();
bufS += "の";
stringstream bufSS;
bufSS << name.c_str();
bufSS << "の";
float bufF = 1.000;
if (atackSkill->useChar->yuusya == true &&atackSkill->PMode==10) {
bufF = (float)(30 + atackSkill->Point)/30;
}
if (atackSkill->content[skillNum] <= 1 && huchi) {
bufS = name.c_str();
bufS += "は不治状態のためHPは回復しない。";
textWindow->PushText(bufS.c_str());
}
else {
switch (atackSkill->content[skillNum])
{
case 0:
bufI = Status[0];
GiveCureHP(bufF * MaxHP*atackSkill->power[skillNum] / 100, textWindow);
bufSS << "HPが";
bufSS << (Status[0] - bufI);
bufSS << "回復した。";
break;
case 1:
bufI = Status[0];
GiveCureHP(bufF * atackSkill->power[skillNum], textWindow);
bufSS << "HPが";
bufSS << (Status[0] - bufI);
bufSS << "回復した。";
break;
case 2:
bufI = Status[1];
GiveCureMP(bufF * MaxMP*atackSkill->power[skillNum] / 100, textWindow);
bufSS << "MPが";
bufSS << (Status[1] - bufI);
bufSS << "回復した。";
break;
case 3:
bufI = Status[1];
GiveCureMP(bufF * atackSkill->power[skillNum], textWindow);
bufSS << "MPが";
bufSS << (Status[1] - bufI);
bufSS << "回復した。";
break;
case 4:
bufS = "毒の状態が治った。";
doku = false;
break;
case 5:
bufS = "麻痺の状態が治った。";
mahi = false;
break;
case 6:
bufS = "放心の状態が治った。";
housin = false;
break;
case 7:
bufS = "不治の状態が治った。";
huchi = false;
break;
case 9:
bufS = "全ての状態以上が治った。";
doku = false;
mahi = false;
housin = false;
huchi = false;
break;
case 10:
bufS = name.c_str();
if (live == false) {
bufS += "が復活した。";
Status[0] = MaxHP *atackSkill->power[skillNum] / 100;
}
else
{
bufS += "は倒れていないので復活の効果がなかった。";
}
live = true;
break;
default:
break;
}
if (atackSkill->content[skillNum] <= 3) {
textWindow->PushText(bufSS.str().c_str());
}
else {
textWindow->PushText(bufS.c_str());
}
}
}
void CCharacterBase::statusChange(Skill *atackSkill, int skillNum, CTextWindow *textWindow)
{
int kind = atackSkill->content[skillNum];
int amount = atackSkill->power[skillNum];
int bufI = statusHenka[kind];
int buffI = 0;
char koreijou = 0;
stringstream bufSS;
if (kind <= 7) {
if (statusHenka[kind] >= 5) {
koreijou = 1;
}
if (statusHenka[kind] <= -5) {
koreijou=2;
}
statusHenka[kind] += amount;
if (statusHenka[kind] >= 5) {
statusHenka[kind] = 5;
}
if (statusHenka[kind] <= -5) {
statusHenka[kind] = -5;
}
buffI = statusHenka[kind] - bufI;
bufSS << name.c_str();
bufSS << "の";
switch (kind)
{
case 0: bufSS << "物攻"; break;
case 1: bufSS << "物防"; break;
case 2: bufSS << "魔攻"; break;
case 3: bufSS << "魔防"; break;
case 4: bufSS << "速さ"; break;
case 5: bufSS << "命中"; break;
case 6: bufSS << "回避"; break;
case 7: bufSS << "運"; break;
default:
break;
}
if (koreijou == 1) {
bufSS << "はこれ以上上がらない。";
}
else if (koreijou == 2) {
bufSS << "はこれ以上下がらない。";
}
else if (buffI > 0) {
statusChangeDisplayTime = 0;
displayStatusChange = bufI;
bufSS << "が";
bufSS << buffI;
bufSS << "上がった。";
displayStatusChange = buffI;
statusChangeDisplayTime = 0;
}
else if (buffI < 0)
{
displayStatusChange = bufI;
buffI *= -1;
statusChangeDisplayTime = 0;
bufSS << "が";
bufSS << buffI;
bufSS << "下がった。";
buffI *= -1;
displayStatusChange = buffI;
statusChangeDisplayTime = 0;
}
else {
bufSS << "が変化しなった。";
}
}
if (16 <= kind && kind <= 20) {
bufSS << name.c_str();
if (kind == 16) {
for (int i = 0; i < 8; i++) {
if (statusHenka[i] > 0) {
statusHenka[i] = 0;
}
}
bufSS << "のプラスのステータス変化が0になった。";
}
if (kind == 17) {
bufSS << "のマイナスのステータス変化効果が0になった。";
for (int i = 0; i < 8; i++) {
if (statusHenka[i] < 0) {
statusHenka[i] = 0;
}
}
}
if (kind == 18) {
for (int i = 0; i < 8; i++) {
statusHenka[i] = 0;
}
bufSS << "の全てのステータス変化効果が0になった。";
}
if (kind == 19) {
bufSS << "の全てのステータスが";
bufSS << amount;
bufSS << "上がった。(5が最大)";
displayStatusChange=amount;
statusChangeDisplayTime = 0;
for (int i = 0; i < 8; i++) {
statusHenka[i] += amount;
if (statusHenka[i] >= 5) {
statusHenka[i] = 5;
}
}
}
if (kind == 20) {
bufSS << "の全てのステータスが";
bufSS << amount *-1;
bufSS << "下がった。(-5が最小)";
displayStatusChange = amount*-1;
statusChangeDisplayTime = 0;
for (int i = 0; i < 8; i++) {
statusHenka[i] -= amount;
if (statusHenka[i] <= -5 ) {
statusHenka[i] = -5;
}
}
}
}
textWindow->PushText(bufSS.str().c_str());
}
void CCharacterBase::JoutaiIjou(Skill *atackSkill, int skillNum, CTextWindow *textWindow)
{
string bufS=name.c_str();
int bufI =atackSkill->power[skillNum] * 255 / 100;
float bufF = 0;
if (atackSkill->useChar->yuusya == true && atackSkill->PMode == 13) {
bufF = (float)(30 + atackSkill->Point) / 30;
bufI *= bufF;
}
if (bufI >= GetRand(255)) {
switch (atackSkill->content[skillNum])
{
case 0:bufS+="は毒状態になった。"; break;
case 1:bufS += "は麻痺状態になった。"; break;
//case 2:bufS += "は放心状態になった。"; break;
case 3:bufS += "は不治状態になった。"; break;
case 4:bufS += "はひるんだ。"; break;
case 5:
bufS += "は毒、麻痺、不治になった。";
break;
default:
break;
}
switch (atackSkill->content[skillNum])
{
case 0:doku = true; break;
case 1:mahi = true; break;
case 2:housin = true; break;
case 3:huchi = true; break;
case 4:hirumi = true; break;
case 5:
doku = true;
mahi = true;
housin = true;
huchi = true;
break;
default:
break;
}
}
else {
switch (atackSkill->content[skillNum])
{
case 0:bufS += "は毒状態にならなかった。"; break;
case 1:bufS += "は麻痺状態にならなかった。"; break;
//case 2:bufS += "は放心状態にならなかった。"; break;
case 3:bufS += "は不治状態になならなかった。"; break;
case 4:bufS += "はひるまなかった。"; break;
case 5:
bufS += "は毒、麻痺、不治にならなかった。";
break;
default:
break;
}
}
textWindow->PushText(bufS.c_str());
}
void CCharacterBase::Tokusyu(CCharacterBase * atackChar, Skill * atackSkill, int skillNum, CTextWindow * textWindow)
{
int bufI = 0;
int bufSyahhuru[4] = { -1,-1,-1,-1 };
bool syahhuruOK = false;
string bufS = name.c_str();
bufS += "の";
stringstream bufSS;
bufSS << name.c_str();
bufSS << "の";
int maisuu = atackSkill->power[skillNum];
switch (atackSkill->content[skillNum])
{
case 0:
if (atackSkill->cardNum >= 0) {
if (atackSkill->power[skillNum] >= 4) {
for (int i = 0; i < 4; i++) {
bufSyahhuru[i] = i;
}
}
else {
for (int i = 0; i < atackSkill->power[skillNum]; i++) {
for (int j = 0; j < 300; j++) {
syahhuruOK = true;
bufSyahhuru[i] = GetRand(3);
for (int k = 0; k < i; k++) {
if (bufSyahhuru[k] == bufSyahhuru[i]) {
syahhuruOK = false;
}
}
if (atackSkill->cardNum == bufSyahhuru[i]) {
syahhuruOK = false;
}
if (syahhuruOK) {
break;
}
if (j == 299) {
for (int l = 0; l < 4; l++) {
syahhuruOK = true;
bufSyahhuru[i] = l;
for (int k = 0; k < i; k++) {
if (bufSyahhuru[k] == bufSyahhuru[i]) {
syahhuruOK = false;
}
}
if (atackSkill->cardNum == bufSyahhuru[i]) {
syahhuruOK = false;
}
if (syahhuruOK) {
break;
}
}
}
//
}
}
}
}
else {
if (atackSkill->power[skillNum] >= 4) {
for (int i = 0; i < 4; i++) {
bufSyahhuru[i] = i;
}
}
else {
for (int i = 0; i < atackSkill->power[skillNum]; i++) {
for (int j = 0; j < 300; j++) {
syahhuruOK = true;
bufSyahhuru[i] = GetRand(3);
for (int k = 0; k < i; k++) {
if (bufSyahhuru[k] == bufSyahhuru[i]) {
syahhuruOK = false;
}
}
if (syahhuruOK) {
break;
}
if (j == 299) {
for (int l = 0; l < 4; l++) {
syahhuruOK = true;
bufSyahhuru[i] = l;
for (int k = 0; k < i; k++) {
if (bufSyahhuru[k] == bufSyahhuru[i]) {
syahhuruOK = false;
}
}
if (syahhuruOK) {
break;
}
}
}
//
}
}
}
}
for (int i = 0; i < atackSkill->power[skillNum]; i++) {
if (i > 3) {
break;
}
SkillSpeadRand();
*jikiSkillCard[bufSyahhuru[i]] = skill[GetRand(5)];
jikiSkillCard[bufSyahhuru[i]]->Point = GetRand(9) + 1;
jikiSkillCard[bufSyahhuru[i]]->cardNum = bufSyahhuru[i];
}
if (maisuu > 4) {
maisuu = 4;
}
bufSS << "スキルカードを";
bufSS << maisuu;
bufSS << "枚シャッフルした。";
textWindow->PushText(bufSS.str().c_str());
break;
case 1:
for (int i = 0; i < 4; i++) {
jikiSkillCard[i]->Point += atackSkill->power[skillNum];
if (jikiSkillCard[i]->Point > 10) {
jikiSkillCard[i]->Point = 10;
}
if (jikiSkillCard[i]->Point < 1) {
jikiSkillCard[i]->Point = 1;
}
}
bufSS << "スキルカードのポイントが";
if (atackSkill->power[skillNum] >= 0) {
bufSS << atackSkill->power[skillNum];
bufSS << "上昇した。(最大は10)";
}
else {
bufSS << atackSkill->power[skillNum]*-1;
bufSS << "減少した。(最小は1)";
}
textWindow->PushText(bufSS.str().c_str());
break;
case 2:
break;
case 3:
bufI = MaxHP*atackSkill->power[skillNum] / 100;
GiveDamge(MaxHP*atackSkill->power[skillNum] / 100 , textWindow);
bufSS << "HPが";
bufSS << bufI;
bufSS << "減少した。";
textWindow->PushText(bufSS.str().c_str());
break;
case 4:
bufI = atackSkill->power[skillNum];
GiveDamge(atackSkill->power[skillNum] , textWindow);
bufSS << "HPが";
bufSS << bufI;
bufSS << "減少した。";
textWindow->PushText(bufSS.str().c_str());
break;
case 5:
bufI = MaxMP*atackSkill->power[skillNum] / 100;
GiveDamgeMP(MaxMP*atackSkill->power[skillNum] / 100 , textWindow);
bufSS << "MPが";
bufSS << bufI;
bufSS << "減少した。";
textWindow->PushText(bufSS.str().c_str());
break;
case 6:
bufI = atackSkill->power[skillNum];
GiveDamgeMP(atackSkill->power[skillNum], textWindow);
bufSS << "MPが";
bufSS << bufI;
bufSS << "減少した。";
textWindow->PushText(bufSS.str().c_str());
break;
case 7:
bufS = "このターン";
bufS += name.c_str();
bufS += "への物理ダメージが減っている。";
textWindow->PushText(bufS.c_str());
break;
case 8:
bufS = "このターン";
bufS += name.c_str();
bufS += "への魔法ダメージが減っている。";
textWindow->PushText(bufS.c_str());
break;
case 9:
bufS = "このターン";
bufS += name.c_str();
bufS += "へのダメージが減っている。";
textWindow->PushText(bufS.c_str());
break;
case 10:
if (enemyF == true) {
bufS = name.c_str();
if (nusunda == false) {
if (atackSkill->power[skillNum] > GetRand(99)) {
bufS += "から";
bufS += dropItemName[6].c_str();
bufS += "を盗んだ。";
nusunda = true;
switch (dropItem[6][0])
{
case 0:
mySaveData->sorce[dropItem[6][1]]++;
if (mySaveData->sorce[dropItem[6][1]] > 9999) {
mySaveData->sorce[dropItem[6][1]] = 9999;
}
break;
case 1:
mySaveData->tool[dropItem[6][1]]++;
if (mySaveData->tool[dropItem[6][1]] > 9999) {
mySaveData->tool[dropItem[6][1]] = 9999;
}
break;
case 2:
mySaveData->food[dropItem[6][1]]++;
if (mySaveData->food[dropItem[6][1]] > 9999) {
mySaveData->food[dropItem[6][1]] = 9999;
}
break;
default:
break;
}
}
else {
bufS += "から物を盗めなかった。";
}
}
else {
bufS += "からはもう盗む物がない!";
}
textWindow->PushText(bufS.c_str());
}
break;
case 11:
bufS = "このターン";
bufS += name.c_str();
bufS += "は仲間をかばっている。";
textWindow->PushText(bufS.c_str());
break;
}
}
void CCharacterBase::DethJudge(CTextWindow *textWindow)
{
string bufS =name.c_str();
bufS += "は倒れた。";
if (Status[0] <= 0) {
Status[0] = 0;
live = false;
textWindow->PushText(bufS.c_str());
Reset();
}
}
void CCharacterBase::PStatusUp(int pKind, CTextWindow *txWindo)
{
effect1.PushEffect(this, this);
int bufI = statusHenka[pKind-2];
int buffI = 0;
char koreijou = 0;
stringstream bufSS;
if (statusHenka[pKind-2] >= 5) {
koreijou = 1;
}
if (statusHenka[pKind-2] <= -5) {
koreijou = 2;
}
statusHenka[pKind-2]++;
if (statusHenka[pKind-2] >= 5) {
statusHenka[pKind-2] = 5;
}
if (statusHenka[pKind-2] <= -5) {
statusHenka[pKind-2] = -5;
}
buffI = statusHenka[pKind-2] - bufI;
txWindo->PushText("スキルポイントの効果!");
bufSS << name.c_str();
bufSS << "の";
switch (pKind-2)
{
case 0: bufSS << "物攻"; break;
case 1: bufSS << "物防"; break;
case 2: bufSS << "魔攻"; break;
case 3: bufSS << "魔防"; break;
case 4: bufSS << "速さ"; break;
case 5: bufSS << "命中"; break;
case 6: bufSS << "回避"; break;
case 7: bufSS << "運"; break;
default:
break;
}
if (koreijou == 1) {
bufSS << "はこれ以上上がらない。";
}
else if (koreijou == 2) {
bufSS << "はこれ以上下がらない。";
}
else if (buffI > 0) {
statusChangeDisplayTime = 0;
displayStatusChange = bufI;
bufSS << "が";
bufSS << buffI;
bufSS << "上がった。";
displayStatusChange = buffI;
statusChangeDisplayTime = 0;
}
else if (buffI < 0)
{
displayStatusChange = bufI;
buffI *= -1;
statusChangeDisplayTime = 0;
bufSS << "が";
bufSS << buffI;
bufSS << "下がった。";
buffI *= -1;
displayStatusChange = buffI;
statusChangeDisplayTime = 0;
}
else {
bufSS << "が変化しなった。";
}
txWindo->PushText(bufSS.str().c_str());
}
void CCharacterBase::GiveDokuDamage(CTextWindow * textWindow,bool boss)
{
stringstream bufSS;
int damage=0;
if (bigBoss && boss == true) {
damage = (float)MaxHP * 0.008;
}
else if(boss==true && enemyF==true){
damage = (float)MaxHP * 0.016;
}
else if (enemyF == true) {
damage = (float)MaxHP * 0.080;
}
else {
damage = (float)MaxHP * 0.040;
}
bufSS << name.c_str();
bufSS << "は毒によって";
bufSS << damage;
bufSS << "ダメージを受けた。";
textWindow->PushText(bufSS.str().c_str());
Status[0] -= damage;
if (Status[0] < 0) {
Status[0] = 0;
}
drawHP = Status[0];
displayDamage = damage;
damageDisplayTime = 0;
DethJudge(textWindow);
}
Skill CCharacterBase::returnSkill()
{
int bufI = GetRand(9);
int buffI=0;
int totalChange=0;
if (bigBoss == false) {
if (bufI < 4) {
buffI = 0;
}
else if (bufI < 6)
{
buffI = 1;
}
else if (bufI < 8)
{
buffI = 2;
}
else if (bufI < 9)
{
buffI = 3;
}
else
{
buffI = 4;
}
skill[buffI].speed = (float)Spd*(1 - GetRand(20)*0.01);
if (statusHenka[4] > 0) {
skill[buffI].speed *= (float)(10 + statusHenka[4] * 2) / 10;
}
if (statusHenka[4] < 0) {
skill[buffI].speed *= (float)(10 - statusHenka[4]) / 10;
}
return skill[buffI];
}
else {
if (skill50 == false && Status[0] <= (float)MaxHP*0.5) {
skill50 = true;
return skill[0];
}
if (skill30 == false && Status[0] <= (float)MaxHP*0.3) {
skill30 = true;
return skill[1];
}
if (doku || huchi || mahi) {
if (GetRand(19) < 2) {
return normalAtack;
}
}
for (int i = 0; i < 8; i++) {
if (statusHenka[i] < 0) {
totalChange += statusHenka[i] * -1;
}
else {
totalChange += statusHenka[i] /2;
}
}
if (totalChange * 3 >= GetRand(100)) {
return normalDefence;
}
if (bufI < 2) {
buffI = 2;
if (Status[0] <= (float)MaxHP*0.5) {
buffI = 8;
}
}
else if (bufI < 4)
{
buffI = 3;
if (Status[0] <= (float)MaxHP*0.3) {
buffI = 9;
}
}
else if (bufI < 6)
{
buffI = 4;
}
else if (bufI < 8)
{
buffI = 5;
}
else if(bufI<9)
{
buffI = 6;
}
else {
buffI = 7;
}
skill[buffI].speed = (float)Spd*(1 - GetRand(20)*0.01);
if (statusHenka[4] > 0) {
skill[buffI].speed *= (float)(10 + statusHenka[4] * 2) / 10;
}
if (statusHenka[4] < 0) {
skill[buffI].speed *= (float)(10 - statusHenka[4]) / 10;
}
return skill[buffI];
}
}
int CCharacterBase::returnSpead()
{
int buf = (float)Spd*(1 - GetRand(20)*0.01);
return buf;
}
void CCharacterBase::SkillSpeadRand()
{
for (int i = 0; i < 10; i++) {
skill[i].speed = (float)Spd*(1 - GetRand(20)*0.01);
if (statusHenka[4] > 0) {
skill[i].speed *= (float)(10 + statusHenka[4] * 2) / 10;
}
if (statusHenka[4] < 0) {
skill[i].speed *= (float)(10 + statusHenka[4]) / 10;
}
}
normalAtack.speed = (float)Spd*(1 - GetRand(20)*0.01);
if (statusHenka[4] > 0) {
normalAtack.speed *= (float)(10 + statusHenka[4] * 2) / 10;
}
if (statusHenka[4] < 0) {
normalAtack.speed *= (float)(10 + statusHenka[4]) / 10;
}
normalDefence.speed = (float)Spd*(1 - GetRand(20)*0.01);
if (statusHenka[4] > 0) {
normalDefence.speed *= (float)(10 + statusHenka[4] * 2) / 10;
}
if (statusHenka[4] < 0) {
normalDefence.speed *= (float)(10 + statusHenka[4]) / 10;
}
}
void CCharacterBase::skillHatudou(CCharacterBase *atackChar, Skill *atackSkill, int skillNum, CTextWindow *textWindow, bool *oneMore, bool *hazureta)
{
*oneMore = false;
string bufS;
if (atackSkill->useChar->live) {
if (atackSkill->hajime) {
atackSkill->hajime = false;
bufS = atackChar->name.c_str();
if (atackSkill->item) {
bufS += "は";
bufS += atackSkill->neme.c_str();
bufS += "を使った。";
}
else {
bufS += "の";
bufS += atackSkill->neme.c_str();
}
textWindow->PushText(bufS.c_str());
}
else {
if (live && *hazureta == false) {
effect1.PushEffect(atackChar, this);
switch (atackSkill->classify[skillNum])
{
case 0:
GiveButuriDamge(atackChar, atackSkill, skillNum, textWindow, hazureta);
break;
case 1:
GiveMahouDamge(atackChar, atackSkill, skillNum, textWindow, hazureta);
break;
case 2:
Cure(atackSkill, skillNum, textWindow);
break;
case 3:
JoutaiIjou(atackSkill, skillNum, textWindow);
break;
case 4:
statusChange(atackSkill, skillNum, textWindow);
break;
case 5:
Tokusyu(atackChar, atackSkill, skillNum, textWindow);
break;
default:
break;
}
}
else if (atackSkill->classify[skillNum] == 2 && atackSkill->content[skillNum] == 10 && *hazureta == false) {
Cure(atackSkill, skillNum, textWindow);
effect1.PushEffect(atackChar, this);
}
else
{
*oneMore = true;
}
}
}
else {
*oneMore=true;
atackSkill->hajime = false;
}
}
void CCharacterBase::DrawHPBar(int x, int y, bool onlyLive)
{
if (onlyLive == false || live == true) {
int bufI = 125 * Status[0] / Status[15];
HPBar.Draw(x, y);
if (Status[0] <= MaxHP*0.2) {
DrawBox(x + 50, y + 4, x + 50 + bufI, y + 20, RED_B, true);
}
else if (Status[0] <= MaxHP*0.5) {
DrawBox(x + 50, y + 4, x + 50 + bufI, y + 20, YELLOW_B, true);
}
else {
DrawBox(x + 50, y + 4, x + 50 + bufI, y + 20, GREEN_B, true);
}
}
}
void CCharacterBase::DrawMPBar(int x, int y, bool onlyLive)
{
if (onlyLive == false || live == true) {
int bufI = 125 * Status[1] / Status[16];
MPBar.Draw(x, y);
DrawBox(x + 50, y + 4, x + 50 + bufI, y + 20, BLUE_B, true);
}
}
void CCharacterBase::DrawStatusWindow(int x, int y)
{
string bufS="";
Window[1].DrawExtend(x, y, x + 200, y + 410);
DrawFormatString(x+10, y+10, BLACK, "%s",name.c_str());
for (int i = 0; i < 15; i++) {
switch (i)
{
case 0: bufS = "HP"; break;
case 1: bufS = "MP"; break;
case 2: bufS = "攻"; break;
case 3: bufS = "防"; break;
case 4: bufS = "魔攻"; break;
case 5: bufS = "魔防"; break;
case 6: bufS = "速"; break;
case 7: bufS = "命中"; break;
case 8: bufS = "回避"; break;
case 9: bufS = "運"; break;
case 10:bufS = "火防"; break;
case 11:bufS = "木防"; break;
case 12:bufS = "水防"; break;
case 13:bufS = "光防"; break;
case 14:bufS = "闇防"; break;
case 15:bufS = "所持金"; break;
default:
break;
}
if (i == 0) {
DrawFormatString(x+10, y + 40, BLACK, "%s;%d / %d", bufS.c_str(), Status[i], Status[i + 15]);
DrawHPBar(x+10, y + 60 ,false);
}
else if (i == 1) {
DrawFormatString(x+10, y + 90, BLACK, "%s;%d / %d", bufS.c_str(), Status[i],Status[i+15]);
DrawMPBar(x+10, y + 110,false);
}
else {
DrawFormatString(x+10, y + 100 + 20 * i , BLACK, "%s;%d", bufS.c_str(), Status[i]);
}
}
}
void CCharacterBase::DrawSmallHPBar(int x, int y, bool onlyLive)
{
if (damageDisplayTime == 0 || cureDisplayTime == 0) {
drawHP = Status[0];
}
if (damageDisplayTime >= 120 && cureDisplayTime >= 120) {
drawHP = Status[0];
}
int bufI = 82 * drawHP / Status[15];
//if (onlyLive == false ) {
smallHPBar.Draw(x, y);
if (drawHP <= MaxHP*0.2) {
DrawBox(x + 34, y + 4, x + 34 + bufI, y + 16, RED_B, true);
}
else if (drawHP <= MaxHP*0.5) {
DrawBox(x + 34, y + 4, x + 34 + bufI, y + 16, YELLOW_B, true);
}
else {
DrawBox(x + 34, y + 4, x + 34 + bufI, y + 16, GREEN_B, true);
}
//}
}
void CCharacterBase::DrawSmallMPBar(int x, int y, bool onlyLive)
{
if (damageDisplayTime == 0 || cureDisplayTime == 0) {
drawMP = Status[1];
}
if (damageDisplayTime >= 120 && cureDisplayTime >= 120) {
drawMP = Status[1];
}
int bufI = 82 * drawMP / Status[16];
if (onlyLive == false || live == true) {
smallMPBar.Draw(x, y);
DrawBox(x + 34, y + 4, x + 34 + bufI, y + 16, BLUE_B, true);
}
}
void CCharacterBase::DrawDamageAndCure()
{
int bufI= damageDisplayTime / 2;
if (bufI > 40) {
bufI = 40;
}
if (damageDisplayTime <= 120) {
damageDisplayTime++;
if (damageDisplayTime >= 0) {
DrawFormatString(x + 15, y - 15 - bufI, RED, "%d", displayDamage*-1);
}
}
bufI = cureDisplayTime / 2;
if (bufI > 40) {
bufI = 40;
}
if (cureDisplayTime <= 120) {
cureDisplayTime++;
if (cureDisplayTime >= 0) {
DrawFormatString(x + 15, y - 15 - bufI, GREEN_B, "+%d", displayCure);
}
}
bufI = damageMPDisplayTime / 2;
if (bufI > 40) {
bufI = 40;
}
if (damageMPDisplayTime <= 120) {
damageMPDisplayTime++;
if (damageMPDisplayTime >= 0) {
DrawFormatString(x + 15, y - 15 - bufI, RED, "%d", displayDamageMP*-1);
}
}
bufI = cureMPDisplayTime / 2;
if (bufI > 40) {
bufI = 40;
}
if (cureMPDisplayTime <= 120 ) {
cureMPDisplayTime++;
if (cureMPDisplayTime >= 0) {
DrawFormatString(x + 15, y - 15 - bufI, BLUE_B, "+%d", displayCureMP);
}
}
bufI = statusChangeDisplayTime / 2;
if (bufI > 40) {
bufI = 40;
}
if (statusChangeDisplayTime <= 120 && statusChangeDisplayTime>=0) {
statusChangeDisplayTime++;
if (displayStatusChange > 0) {
DrawFormatString(x + 30, y - 15 - bufI, ORANGE, "↑%d", displayStatusChange);
}
else if (displayStatusChange < 0) {
DrawFormatString(x + 30, y - 15 - bufI, BLUE_S, "↓%d", displayStatusChange);
}
}
effect1.DrawEffect();
}
void CCharacterBase::DrawStatusHenkaWindow(int x, int y)
{
string bufS = "";
if (enemyF == true) {
x -= 60;
y -= 60;
}
Window[0].DrawExtend(x, y, x + 136, y + 120);
for (int i = 0; i < 8;i++) {
switch (i)
{
case 0:bufS = "物攻"; break;
case 1:bufS = "物防"; break;
case 2:bufS = "魔攻"; break;
case 3:bufS = "魔防"; break;
case 4:bufS = "速"; break;
case 5:bufS = "命中"; break;
case 6:bufS = "回避"; break;
case 7:bufS = "運"; break;
default:
break;
}
if (statusHenka[i] > 0) {
DrawFormatString(x +3 + (i%2)*70, y + 5 + (i/2) * 25, ORANGE, "%s+%d", bufS.c_str(), statusHenka[i]);
}
else if (statusHenka[i] < 0) {
DrawFormatString(x + 3 + (i % 2) * 70, y + 5 + (i / 2) * 25, BLUE_S, "%s%d", bufS.c_str(), statusHenka[i]);
}
else {
DrawFormatString(x + 3 + (i % 2) * 70, y + 5 + (i / 2) * 25, BLACK, "%s±%d", bufS.c_str(), statusHenka[i]);
}
}
}
CJiki::CJiki(CMySaveData *mySD)
{
mySaveData = mySD;
name = "勇者";
charGraph = "zero/jiki1.png";
int equipmentKind = 0;
int num = 0;
int buf = 0;
int Level=0;
enemyF = false;
bigBoss = false;
for (int i = 0; i < 17; i++) {
Status[i] = 0;
}
mySaveData = mySD;
for (int i = 0; i < 5; i++) {
equipManager = new CEquipmentManager(mySaveData, mySaveData->wearEquipmentLocate[i][0]);
equipmentKind = mySaveData->wearEquipmentLocate[i][0];
buf = mySaveData->wearEquipmentLocate[i][1];
num = equipManager->haveEquipmentNumLevel[equipmentKind][buf].first;
Level = equipManager->haveEquipmentNumLevel[equipmentKind][buf].second;
wearWeaponNumLevel[i][0] = equipmentKind;
wearWeaponNumLevel[i][1] = num;
wearWeaponNumLevel[i][2] = Level;
switch (equipmentKind)
{
case 0: equipmentInfo = new CSV("zero/ZeroData/Soad.csv"); break;
case 1: equipmentInfo = new CSV("zero/ZeroData/Arrow.csv"); break;
case 2: equipmentInfo = new CSV("zero/ZeroData/Wand.csv"); break;
case 3: equipmentInfo = new CSV("zero/ZeroData/Shield.csv"); break;
case 4: equipmentInfo = new CSV("zero/ZeroData/Protecter.csv"); break;
case 5: equipmentInfo = new CSV("zero/ZeroData/Shoes.csv"); break;
case 6: equipmentInfo = new CSV("zero/ZeroData/Accessory.csv"); break;
}
MaxHP = (*equipmentInfo)[num - 1][2];
MaxMP = (*equipmentInfo)[num - 1][3];
Atc = (*equipmentInfo)[num - 1][4];
Def = (*equipmentInfo)[num - 1][5];
MAtc = (*equipmentInfo)[num - 1][6];
MDef = (*equipmentInfo)[num - 1][7];
Spd = (*equipmentInfo)[num - 1][8];
Hit = (*equipmentInfo)[num - 1][9];
Escape = (*equipmentInfo)[num - 1][10];
Luck = (*equipmentInfo)[num - 1][11];
if (equipmentKind <= 2) {
Element = (*equipmentInfo)[num - 1][12];
FireDef = (*equipmentInfo)[num - 1][13];
WoodDef = (*equipmentInfo)[num - 1][14];
WaterDef = (*equipmentInfo)[num - 1][15];
LightDef = (*equipmentInfo)[num - 1][16];
DarkDef = (*equipmentInfo)[num - 1][17];
}
else {
FireDef = (*equipmentInfo)[num - 1][12];
WoodDef = (*equipmentInfo)[num - 1][13];
WaterDef = (*equipmentInfo)[num - 1][14];
LightDef = (*equipmentInfo)[num - 1][15];
DarkDef = (*equipmentInfo)[num - 1][16];
}
MaxHP *= (1.0 + 0.1*Level);
MaxMP *= (1.0 + 0.1*Level);
Atc *= (1.0 + 0.1*Level);
Def *= (1.0 + 0.1*Level);
MAtc *= (1.0 + 0.1*Level);
MDef *= (1.0 + 0.1*Level);
Spd *= (1.0 + 0.1*Level);
Hit *= (1.0 + 0.1*Level);
Escape *= (1.0 + 0.1*Level);
Luck *= (1.0 + 0.1*Level);
FireDef *= (1.0 + 0.1*Level);
WoodDef *= (1.0 + 0.1*Level);
WaterDef *= (1.0 + 0.1*Level);
LightDef *= (1.0 + 0.1*Level);
DarkDef *= (1.0 + 0.1*Level);
HP = MaxHP;
MP = MaxMP;
Status[0] += HP;
Status[1] += MP;
Status[2] += Atc;
Status[3] += Def;
Status[4] += MAtc;
Status[5] += MDef;
Status[6] += Spd;
Status[7] += Hit;
Status[8] += Escape;
Status[9] += Luck;
Status[10] += FireDef;
Status[11] += WoodDef;
Status[12] += WaterDef;
Status[13] += LightDef;
Status[14] += DarkDef;
Status[15] += MaxHP;
Status[16] += MaxMP;
if (i == 0) {
skillNum[0] = (*equipmentInfo)[num - 1][19];
skillNum[1] = (*equipmentInfo)[num - 1][20];
}
else {
skillNum[i+1] = (*equipmentInfo)[num - 1][18];
}
delete equipmentInfo;
delete equipManager;
equipmentInfo = NULL;
equipManager = NULL;
}
HP = Status[0];
MP = Status[1];
Atc = Status[2];
Def = Status[3];
MAtc = Status[4];
MDef = Status[5];
Spd = Status[6];
Hit = Status[7];
Escape = Status[8];
Luck = Status[9];
FireDef = Status[10];
WoodDef = Status[11];
WaterDef = Status[12];
LightDef = Status[13];
DarkDef = Status[14];
MaxHP = Status[15];
MaxMP= Status[16];
equipmentKind = mySaveData->wearEquipmentLocate[0][0];
skillInfo = new CSV("zero/ZeroData/Skill.csv");
for (int i = 0; i < 6; i++) {
skill[i].ene = false;
skill[i].useChar = this;
skill[i].num = skillNum[i];
skill[i].neme = (*skillInfo)[skillNum[i] - 1][1];
skill[i].MP = (*skillInfo)[skillNum[i] - 1][2];
skill[i].element = (*skillInfo)[skillNum[i] - 1][3];
skill[i].PMode = (*skillInfo)[skillNum[i] - 1][4];
skill[i].times = (*skillInfo)[skillNum[i] - 1][5];
skill[i].classifyNum = (*skillInfo)[skillNum[i] - 1][6];
for (int j = 0; j < 3; j++) {
skill[i].target[j] = (*skillInfo)[skillNum[i] - 1][7+j*4];
skill[i].classify[j] = (*skillInfo)[skillNum[i] - 1][8+j*4];
skill[i].content[j] = (*skillInfo)[skillNum[i] - 1][9+j*4];
skill[i].power[j] = (*skillInfo)[skillNum[i] - 1][10+j*4];
}
skill[i].experience = (*skillInfo)[skillNum[i] - 1][19];
}
normalAtack.ene = false;
normalDefence.ene = false;
if (equipmentKind <= 1) {
normalAtack.num = Element + 1;
normalAtack.neme = (*skillInfo)[normalAtack.num - 1][1];
normalAtack.MP = (*skillInfo)[normalAtack.num - 1][2];
normalAtack.element = (*skillInfo)[normalAtack.num - 1][3];
normalAtack.PMode = (*skillInfo)[normalAtack.num - 1][4];
normalAtack.times = (*skillInfo)[normalAtack.num - 1][5];
normalAtack.classifyNum = (*skillInfo)[normalAtack.num - 1][6];
for (int j = 0; j < 3; j++) {
normalAtack.target[j] = (*skillInfo)[normalAtack.num - 1][7 + j * 4];
normalAtack.classify[j] = (*skillInfo)[normalAtack.num - 1][8 + j * 4];
normalAtack.content[j] = (*skillInfo)[normalAtack.num - 1][9 + j * 4];
normalAtack.power[j] = (*skillInfo)[normalAtack.num - 1][10 + j * 4];
}
normalAtack.experience = (*skillInfo)[normalAtack.num - 1][19];
}
else {
normalAtack.num = Element + 7;
normalAtack.useChar = this;
normalAtack.neme = (*skillInfo)[normalAtack.num - 1][1];
normalAtack.MP = (*skillInfo)[normalAtack.num - 1][2];
normalAtack.element = (*skillInfo)[normalAtack.num - 1][3];
normalAtack.PMode = (*skillInfo)[normalAtack.num - 1][4];
normalAtack.times = (*skillInfo)[normalAtack.num - 1][5];
normalAtack.classifyNum = (*skillInfo)[normalAtack.num - 1][6];
for (int j = 0; j < 3; j++) {
normalAtack.target[j] = (*skillInfo)[normalAtack.num - 1][7 + j * 4];
normalAtack.classify[j] = (*skillInfo)[normalAtack.num - 1][8 + j * 4];
normalAtack.content[j] = (*skillInfo)[normalAtack.num - 1][9 + j * 4];
normalAtack.power[j] = (*skillInfo)[normalAtack.num - 1][10 + j * 4];
}
normalAtack.experience = (*skillInfo)[normalAtack.num - 1][19];
}
normalDefence.num = 13;
normalDefence.useChar = this;
normalDefence.neme = (*skillInfo)[normalDefence.num - 1][1];
normalDefence.MP = (*skillInfo)[normalDefence.num - 1][2];
normalDefence.element = (*skillInfo)[normalDefence.num - 1][3];
normalDefence.PMode = (*skillInfo)[normalDefence.num - 1][4];
normalDefence.times = (*skillInfo)[normalDefence.num - 1][5];
normalDefence.classifyNum = (*skillInfo)[normalDefence.num - 1][6];
for (int j = 0; j < 3; j++) {
normalDefence.target[j] = (*skillInfo)[normalDefence.num - 1][7 + j * 4];
normalDefence.classify[j] = (*skillInfo)[normalDefence.num - 1][8 + j * 4];
normalDefence.content[j] = (*skillInfo)[normalDefence.num - 1][9 + j * 4];
normalDefence.power[j] = (*skillInfo)[normalDefence.num - 1][10 + j * 4];
}
normalDefence.experience = (*skillInfo)[normalDefence.num - 1][19];
PDamageCut = 0;
yuusya = true;
delete skillInfo;
skillInfo = NULL;
drawHP = MaxHP;
drawMP = MaxMP;
}
CJiki::~CJiki()
{
}
void CJiki::Draw(int x, int y)
{
this->x = x;
this->y = y;
DrawFormatString(x+35, y, BLACK, "%s", name.c_str());
if (tenmetsu > 60 || tenmetsu % 30 <= 15 || tenmetsu<0) {
charGraph.Draw(x, y);
}
if (tenmetsu < 110) {
tenmetsu++;
}
DrawSmallHPBar(x , y + 35, false);
DrawFormatString(x + 124, y + 37, BLACKNESS, "%d/%d", drawHP, Status[15]);
DrawSmallMPBar(x , y + 35 + 23, false);
DrawFormatString(x + 124, y + 37 + 23, BLACKNESS, "%d/%d", drawMP, Status[16]);
if (doku) {
DrawFormatString(x, y + 81, RED, "毒");
}
if (mahi) {
DrawFormatString(x + 22, y + 81, RED, "麻痺");
}
if (huchi) {
DrawFormatString(x + 66, y + 81, RED, "不治");
}
if (hirumi) {
DrawFormatString(x + 110, y + 81, RED, "ひるみ");
}
}
CHaniwa::CHaniwa(CMySaveData * mySD,int kind)
{
mySaveData = mySD;
this->kind = kind;
Level = mySaveData->haniwaLevel[kind - 1];
enemyF = false;
bigBoss = false;
haniwaInfo = new CSV("zero/ZeroData/Haniwa.csv");
float bufFlo;
int bufI;
stringstream bufSS;
bufSS << "zero/hani";
bufSS << this->kind;
bufSS << ".png";
charGraph = bufSS.str().c_str();
name = (*haniwaInfo)[kind - 1][1];
for (int i = 0; i < 15; i++) {
bufI = (*haniwaInfo)[kind - 1][2 + i];
bufFlo = (*haniwaInfo)[kind - 1][17 + i];
switch (i)
{
case 0:
HP = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][0];
MaxHP = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind-1][0];
break;
case 1:
MP = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][1];
MaxMP = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][1];
break;
case 2:
Atc = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][2];
break;
case 3:
Def = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][3];
break;
case 4:
MAtc = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][4];
break;
case 5:
MDef = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][5];
break;
case 6:
Spd = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][6];
break;
case 7:
Hit = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][7];
break;
case 8:
Escape = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][8];
break;
case 9:
Luck = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][9];
break;
case 10:
FireDef = bufI + bufFlo*Level;
break;
case 11:
WoodDef = bufI + bufFlo*Level;
break;
case 12:
WaterDef = bufI + bufFlo*Level;
break;
case 13:
LightDef = bufI + bufFlo*Level;
break;
case 14:
DarkDef = bufI + bufFlo*Level;
break;
default:
break;
}
}
Status[0] = HP;
Status[1] = MP;
Status[2] = Atc;
Status[3] = Def;
Status[4] = MAtc;
Status[5] = MDef;
Status[6] = Spd;
Status[7] = Hit;
Status[8] = Escape;
Status[9] = Luck;
Status[10] = FireDef;
Status[11] = WoodDef;
Status[12] = WaterDef;
Status[13] = LightDef;
Status[14] = DarkDef;
Status[15] = MaxHP;
Status[16] = MaxMP;
for (int i = 0; i < 4; i++) {
skillNum[i] = (this->kind - 1) * 4 + i + 1;
}
delete haniwaInfo;
haniwaInfo = NULL;
haniwaSkillInfo = new CSV("zero/ZeroData/HaniwaSkill.csv");
for (int i = 0; i < 4; i++) {
skill[i].ene = false;
skill[i].useChar = this;
skill[i].num = skillNum[i];
skill[i].neme = (*haniwaSkillInfo)[skillNum[i] - 1][1];
if (Level < 30) {
skill[i].MP = (*haniwaSkillInfo)[skillNum[i] - 1][2];
}
else if (Level < 50) {
skill[i].MP = (*haniwaSkillInfo)[skillNum[i] - 1][3];
}
else if (Level < 70) {
skill[i].MP = (*haniwaSkillInfo)[skillNum[i] - 1][4];
}
else {
skill[i].MP = (*haniwaSkillInfo)[skillNum[i] - 1][5];
}
skill[i].element = (*haniwaSkillInfo)[skillNum[i] - 1][6];
skill[i].times = (*haniwaSkillInfo)[skillNum[i] - 1][7];
skill[i].classifyNum = (*haniwaSkillInfo)[skillNum[i] - 1][8];
for (int j = 0; j < 3; j++) {
skill[i].target[j] = (*haniwaSkillInfo)[skillNum[i] - 1][9 + j * 7];
skill[i].classify[j] = (*haniwaSkillInfo)[skillNum[i] - 1][10 + j * 7];
skill[i].content[j] = (*haniwaSkillInfo)[skillNum[i] - 1][11 + j * 7];
if (Level < 30) {
skill[i].power[j] = (*haniwaSkillInfo)[skillNum[i] - 1][12 + j * 7];
}
else if (Level < 50) {
skill[i].power[j] = (*haniwaSkillInfo)[skillNum[i] - 1][13 + j * 7];
}
else if (Level < 70) {
skill[i].power[j] = (*haniwaSkillInfo)[skillNum[i] - 1][14 + j * 7];
}
else {
skill[i].power[j] = (*haniwaSkillInfo)[skillNum[i] - 1][15 + j * 7];
}
}
skill[i].experience = (*haniwaSkillInfo)[skillNum[i] - 1][30];
}
delete haniwaSkillInfo;
haniwaSkillInfo = NULL;
skillInfo = new CSV("zero/ZeroData/Skill.csv");
normalAtack.num = 1;
normalAtack.ene = false;
normalDefence.ene = false;
normalAtack.neme = (*skillInfo)[normalAtack.num - 1][1];
normalAtack.MP = (*skillInfo)[normalAtack.num - 1][2];
normalAtack.element = (*skillInfo)[normalAtack.num - 1][3];
normalAtack.times = (*skillInfo)[normalAtack.num - 1][5];
normalAtack.classifyNum = (*skillInfo)[normalAtack.num - 1][6];
normalAtack.useChar = this;
for (int j = 0; j < 3; j++) {
normalAtack.target[j] = (*skillInfo)[normalAtack.num - 1][7 + j * 4];
normalAtack.classify[j] = (*skillInfo)[normalAtack.num - 1][8 + j * 4];
normalAtack.content[j] = (*skillInfo)[normalAtack.num - 1][9 + j * 4];
normalAtack.power[j] = (*skillInfo)[normalAtack.num - 1][10 + j * 4];
}
normalAtack.experience = (*skillInfo)[normalAtack.num - 1][19];
normalDefence.num = 13;
normalDefence.neme = (*skillInfo)[normalDefence.num - 1][1];
normalDefence.MP = (*skillInfo)[normalDefence.num - 1][2];
normalDefence.element = (*skillInfo)[normalDefence.num - 1][3];
normalDefence.times = (*skillInfo)[normalDefence.num - 1][5];
normalDefence.classifyNum = (*skillInfo)[normalDefence.num - 1][6];
normalDefence.useChar = this;
for (int j = 0; j < 3; j++) {
normalDefence.target[j] = (*skillInfo)[normalDefence.num - 1][7 + j * 4];
normalDefence.classify[j] = (*skillInfo)[normalDefence.num - 1][8 + j * 4];
normalDefence.content[j] = (*skillInfo)[normalDefence.num - 1][9 + j * 4];
normalDefence.power[j] = (*skillInfo)[normalDefence.num - 1][10 + j * 4];
}
normalDefence.experience = (*skillInfo)[normalDefence.num - 1][19];
delete skillInfo;
skillInfo = NULL;
drawHP = MaxHP;
drawMP = MaxMP;
}
CHaniwa::~CHaniwa()
{
}
void CHaniwa::Draw(int x, int y)
{
this->x = x;
this->y = y;
DrawFormatString(x + 35 , y, BLACK, "%s", name.c_str());
if (tenmetsu > 60 || tenmetsu % 30 <= 15 || tenmetsu<0) {
charGraph.Draw(x, y);
}
if (tenmetsu < 110) {
tenmetsu++;
}
DrawSmallHPBar(x , y + 35, false);
DrawFormatString(x + 124, y +37, BLACKNESS, "%d/%d",drawHP,MaxHP);
DrawSmallMPBar(x, y + 35 + 23, false);
DrawFormatString(x + 124, y + 37 + 23, BLACKNESS, "%d/%d", drawMP, MaxMP);
if (doku) {
DrawFormatString(x, y + 81, RED, "毒");
}
if (mahi) {
DrawFormatString(x + 22, y + 81, RED, "麻痺");
}
if (huchi) {
DrawFormatString(x + 66, y + 81, RED, "不治");
}
if (hirumi) {
DrawFormatString(x + 110, y + 81, RED, "ひるみ");
}
}
CEnemy::CEnemy(CMySaveData * mySD, int kind, bool bigBoss)
{
mySaveData = mySD;
this->kind = kind;
this->bigBoss = bigBoss;
float bufFlo;
int bufI;
string bufS;
if (bigBoss == false) {
enemyInfo = new CSV("zero/ZeroData/Enemy.csv");
enemyF = true;
name = (*enemyInfo)[kind-1][1];
bufS = (*enemyInfo)[kind - 1][2];
charGraph = bufS.c_str();
for (int i = 0; i < 15; i++) {
bufI = (*enemyInfo)[kind-1][3 + i];
switch (i)
{
case 0:
HP = bufI ;
MaxHP = bufI ;
break;
case 1:
Atc = bufI;
break;
case 2:
Def = bufI;
break;
case 3:
MAtc = bufI;
break;
case 4:
MDef = bufI;
break;
case 5:
Spd = bufI;
break;
case 6:
Hit = bufI;
break;
case 7:
Escape = bufI ;
break;
case 8:
Luck = bufI ;
break;
case 9:
FireDef = bufI ;
break;
case 10:
WoodDef = bufI ;
break;
case 11:
WaterDef = bufI ;
break;
case 12:
LightDef = bufI ;
break;
case 13:
DarkDef = bufI ;
break;
default:
break;
}
}
Status[0] = HP;
Status[1] = MP;
Status[2] = Atc;
Status[3] = Def;
Status[4] = MAtc;
Status[5] = MDef;
Status[6] = Spd;
Status[7] = Hit;
Status[8] = Escape;
Status[9] = Luck;
Status[10] = FireDef;
Status[11] = WoodDef;
Status[12] = WaterDef;
Status[13] = LightDef;
Status[14] = DarkDef;
Status[15] = MaxHP;
Status[16] = MaxMP;
for (int i = 0; i < 5; i++) {
skillNum[i] = (*enemyInfo)[kind - 1][17 + i];
if (skillNum[i] <= 0) {
skillNum[i] = 1;
}
}
for (int i = 0; i < 7; i++) {
bufI = GetRand(19);
if (bufI < 8) {
dropItem[i][0] = (*enemyInfo)[kind - 1][22 + 0 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][23 + 0 * 2];
}
else if (bufI < 14) {
dropItem[i][0] = (*enemyInfo)[kind - 1][22 + 1 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][23 + 1 * 2];
}
else if (bufI < 18) {
dropItem[i][0] = (*enemyInfo)[kind - 1][22 + 2 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][23 + 2 * 2];
}
else {
dropItem[i][0] = (*enemyInfo)[kind - 1][22 + 3 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][23 + 3 * 2];
}
}
delete enemyInfo;
enemyInfo = NULL;
for (int i = 0; i < 7; i++) {
switch (dropItem[i][0]) {
case 0:
itemInfo = new CSV("zero/ZeroData/Sorce.csv");
break;
case 1:
itemInfo = new CSV("zero/ZeroData/Tool.csv");
break;
case 2:
itemInfo = new CSV("zero/ZeroData/Food.csv");
break;
}
dropItemName[i] = (*itemInfo)[dropItem[i][1] - 1][1];
delete itemInfo;
itemInfo = NULL;
}
skillInfo = new CSV("zero/ZeroData/Skill.csv");
for (int i = 0; i < 5; i++) {
skill[i].ene = true;
skill[i].useChar = this;
skill[i].num = skillNum[i];
if (skillNum[i] > 0) {
skill[i].neme = (*skillInfo)[skillNum[i] - 1][1];
skill[i].MP = (*skillInfo)[skillNum[i] - 1][2];
skill[i].element = (*skillInfo)[skillNum[i] - 1][3];
skill[i].PMode = (*skillInfo)[skillNum[i] - 1][4];
skill[i].times = (*skillInfo)[skillNum[i] - 1][5];
skill[i].classifyNum = (*skillInfo)[skillNum[i] - 1][6];
for (int j = 0; j < 3; j++) {
skill[i].target[j] = (*skillInfo)[skillNum[i] - 1][7 + j * 4];
skill[i].classify[j] = (*skillInfo)[skillNum[i] - 1][8 + j * 4];
skill[i].content[j] = (*skillInfo)[skillNum[i] - 1][9 + j * 4];
skill[i].power[j] = (*skillInfo)[skillNum[i] - 1][10 + j * 4];
}
skill[i].experience = (*skillInfo)[skillNum[i] - 1][19];
}
}
delete skillInfo;
skillInfo = NULL;
}
else {
enemyInfo = new CSV("zero/ZeroData/BigBoss.csv");
enemyF = true;
name = (*enemyInfo)[kind - 1][1];
bufS = (*enemyInfo)[kind - 1][2];
charGraph = bufS.c_str();
for (int i = 0; i < 15; i++) {
bufI = (*enemyInfo)[kind - 1][3 + i];
switch (i)
{
case 0:
HP = bufI;
MaxHP = bufI;
break;
case 1:
Atc = bufI;
break;
case 2:
Def = bufI;
break;
case 3:
MAtc = bufI;
break;
case 4:
MDef = bufI;
break;
case 5:
Spd = bufI;
break;
case 6:
Hit = bufI;
break;
case 7:
Escape = bufI;
break;
case 8:
Luck = bufI;
break;
case 9:
FireDef = bufI;
break;
case 10:
WoodDef = bufI;
break;
case 11:
WaterDef = bufI;
break;
case 12:
LightDef = bufI;
break;
case 13:
DarkDef = bufI;
break;
default:
break;
}
}
Status[0] = HP;
Status[1] = MP;
Status[2] = Atc;
Status[3] = Def;
Status[4] = MAtc;
Status[5] = MDef;
Status[6] = Spd;
Status[7] = Hit;
Status[8] = Escape;
Status[9] = Luck;
Status[10] = FireDef;
Status[11] = WoodDef;
Status[12] = WaterDef;
Status[13] = LightDef;
Status[14] = DarkDef;
Status[15] = MaxHP;
Status[16] = MaxMP;
actTimes=(*enemyInfo)[kind - 1][17];
for (int i = 0; i <10; i++) {
skillNum[i] = (*enemyInfo)[kind - 1][18 + i];
if (skillNum[i] <= 0) {
skillNum[i] = 1;
}
}
for (int i = 0; i < 7; i++) {
bufI = GetRand(19);
if (bufI < 5) {
dropItem[i][0] = (*enemyInfo)[kind - 1][28 + 0 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][29 + 0 * 2];
}
else if (bufI < 9) {
dropItem[i][0] = (*enemyInfo)[kind - 1][28 + 1 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][29 + 1 * 2];
}
else if (bufI < 11) {
dropItem[i][0] = (*enemyInfo)[kind - 1][28 + 2 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][29 + 2 * 2];
}
else if (bufI < 13) {
dropItem[i][0] = (*enemyInfo)[kind - 1][28 + 3 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][29 + 3 * 2];
}
else if (bufI < 15) {
dropItem[i][0] = (*enemyInfo)[kind - 1][28 + 4 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][29 + 4 * 2];
}
else if (bufI < 17) {
dropItem[i][0] = (*enemyInfo)[kind - 1][28 + 5 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][29 + 5 * 2];
}
else if (bufI < 19) {
dropItem[i][0] = (*enemyInfo)[kind - 1][28 + 6 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][29 + 6 * 2];
}
else{
dropItem[i][0] = (*enemyInfo)[kind - 1][28 + 7 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][29 + 7 * 2];
}
}
delete enemyInfo;
enemyInfo = NULL;
for (int i = 0; i < 7; i++) {
switch (dropItem[i][0]) {
case 0:
itemInfo = new CSV("zero/ZeroData/Sorce.csv");
break;
case 1:
itemInfo = new CSV("zero/ZeroData/Tool.csv");
break;
case 2:
itemInfo = new CSV("zero/ZeroData/Food.csv");
break;
}
dropItemName[i] = (*itemInfo)[dropItem[i][1] - 1][1];
delete itemInfo;
itemInfo = NULL;
}
skillInfo = new CSV("zero/ZeroData/Skill.csv");
for (int i = 0; i < 10; i++) {
skill[i].ene = true;
skill[i].useChar = this;
skill[i].num = skillNum[i];
if (skillNum[i] > 0) {
skill[i].neme = (*skillInfo)[skillNum[i] - 1][1];
skill[i].MP = (*skillInfo)[skillNum[i] - 1][2];
skill[i].element = (*skillInfo)[skillNum[i] - 1][3];
skill[i].PMode = (*skillInfo)[skillNum[i] - 1][4];
skill[i].times = (*skillInfo)[skillNum[i] - 1][5];
skill[i].classifyNum = (*skillInfo)[skillNum[i] - 1][6];
for (int j = 0; j < 3; j++) {
skill[i].target[j] = (*skillInfo)[skillNum[i] - 1][7 + j * 4];
skill[i].classify[j] = (*skillInfo)[skillNum[i] - 1][8 + j * 4];
skill[i].content[j] = (*skillInfo)[skillNum[i] - 1][9 + j * 4];
skill[i].power[j] = (*skillInfo)[skillNum[i] - 1][10 + j * 4];
}
skill[i].experience = (*skillInfo)[skillNum[i] - 1][19];
}
}
normalAtack.ene = true;
normalAtack.useChar = this;
normalAtack.num = 14;
normalAtack.neme = (*skillInfo)[14 - 1][1];
normalAtack.MP = (*skillInfo)[14 - 1][2];
normalAtack.element = (*skillInfo)[14 - 1][3];
normalAtack.PMode = (*skillInfo)[14 - 1][4];
normalAtack.times = (*skillInfo)[14 - 1][5];
normalAtack.classifyNum = (*skillInfo)[14 - 1][6];
for (int j = 0; j < 3; j++) {
normalAtack.target[j] = (*skillInfo)[14 - 1][7 + j * 4];
normalAtack.classify[j] = (*skillInfo)[14 - 1][8 + j * 4];
normalAtack.content[j] = (*skillInfo)[14 - 1][9 + j * 4];
normalAtack.power[j] = (*skillInfo)[14 - 1][10 + j * 4];
}
normalAtack.experience = (*skillInfo)[14 - 1][19];
normalDefence.ene = true;
normalDefence.useChar = this;
normalDefence.num = 15;
normalDefence.neme = (*skillInfo)[15 - 1][1];
normalDefence.MP = (*skillInfo)[15 - 1][2];
normalDefence.element = (*skillInfo)[15 - 1][3];
normalDefence.PMode = (*skillInfo)[15 - 1][4];
normalDefence.times = (*skillInfo)[15 - 1][5];
normalDefence.classifyNum = (*skillInfo)[15 - 1][6];
for (int j = 0; j < 3; j++) {
normalDefence.target[j] = (*skillInfo)[15 - 1][7 + j * 4];
normalDefence.classify[j] = (*skillInfo)[15 - 1][8 + j * 4];
normalDefence.content[j] = (*skillInfo)[15 - 1][9 + j * 4];
normalDefence.power[j] = (*skillInfo)[15 - 1][10 + j * 4];
}
normalDefence.experience = (*skillInfo)[15 - 1][19];
delete skillInfo;
skillInfo = NULL;
}
tenmetsu = 121;
drawHP = MaxHP;
drawMP = MaxMP;
nusunda = false;
}
CEnemy::~CEnemy()
{
}
void CEnemy::Draw(int x, int y, bool nameZurasi)
{
this->x = x+60;
this->y = y+60;
if (live == true || damageDisplayTime<=0 ||cureDisplayTime<=0 || damageMPDisplayTime<=0 || cureMPDisplayTime<=0) {
if (tenmetsu > 90 || tenmetsu % 30 <= 15 || tenmetsu<0) {
charGraph.DrawRota(this->x,this->y,1.00,0);
}
if (tenmetsu < 110) {
tenmetsu++;
}
DrawSmallHPBar(x, y - 24, true);
if (nameZurasi == false) {
DrawFormatString(x-5, y - 44, BLACK, name.c_str());
}
else
{
DrawFormatString(x, y - 64, BLACK, name.c_str());
}
if (doku) {
DrawFormatString(x-6, y - 84, RED, "毒");
}
if (mahi) {
DrawFormatString(x + 14, y - 84, RED, "麻痺");
}
if (huchi) {
DrawFormatString(x + 54, y - 84, RED, "不治");
}
if (hirumi) {
DrawFormatString(x -6, y -105 , RED, "ひるみ");
}
}
}
| [
"doragontuinatomikku@gmail.com"
] | doragontuinatomikku@gmail.com |
223f7df63e9ecdec7736e77f1348f1dc183c8248 | 220846e017a9992e596bd1ea806d527e3aeea243 | /162_Find_Peak_Element.cpp | 618e82ebc8f572dcbf0cf7ddf9e0f7dd0bcccb78 | [] | no_license | anzhe-yang/Leetcode | bfa443b7a74ddbd441348c364ee00004173ddd86 | fe9eb16136035f25f31bddb37c6b4884cd7f6904 | refs/heads/master | 2020-04-08T14:49:04.781848 | 2019-10-25T02:39:22 | 2019-10-25T02:39:22 | 159,453,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,049 | cpp | /** 问题描述:
* 如果某个元素大于它周围的元素,则称为山顶元素。
* 给定一个数组,数组中相邻两个元素不相等,找到其中的山顶元素并返回位置索引。
* 数组可能包含多个山顶元素,可以任意返回某一个。
* 可以假设数组的 -1 索引和 n 索引的值为负无穷。
* 算法复杂度为 O(logN) 。
*/
#include <iostream>
#include <vector>
using namespace std;
int findPeakElement(vector<int>& nums)
{
/*
二分法。
比较当前mid值和下一个值。
如果小于它,则说明山顶值在右方,否则在左方。
*/
int len = nums.size();
int left = 0, right = len-1;
int mid = 0;
while (left < right)
{
mid = left + ((right-left) >> 1);
if (nums[mid] < nums[mid+1])
left = mid + 1;
else
right = mid;
}
return left;
}
int main(int argc, char const *argv[])
{
vector<int> nums{};
cout << findPeakElement(nums);
return 0;
}
| [
"yaz951114@gmail.com"
] | yaz951114@gmail.com |
dc22d51a8bf9cc33337873826a0a7a7cf3e4a0dd | 14a925dcf097319834778c8b3010a7c786748199 | /include/parser_utils.h | df50293d5110452d1322419273f70e441d6bc2f6 | [
"MIT"
] | permissive | toaderandrei/cppnd-udacity-system-monitor | a410a194633dc0d786281df653a5ab08e7ded228 | 011f95e63452a7a7f7d0821c0131186a871a1ee9 | refs/heads/master | 2022-04-20T07:51:50.943096 | 2020-04-18T12:45:13 | 2020-04-18T12:45:13 | 256,291,666 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,429 | h | //
// Created by toaderst on 08-03-20.
//
#ifndef MONITOR_PARSER_UTILS_H
#define MONITOR_PARSER_UTILS_H
#include <fstream>
#include <iostream>
#include <sstream>
namespace ParserUtils {
inline void CloseStream(std::ifstream *stream) {
if (stream != NULL && stream->is_open()) {
stream->close();
}
}
template <typename T>
T GetValueByKey(const std::string &directory, const std::string &filename,
const std::string &filter) {
std::string key, line;
T value;
std::ifstream stream(directory + filename);
if (stream.is_open()) {
while (getline(stream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == filter) {
return value;
}
}
}
}
CloseStream(&stream);
return value;
}
template <typename T>
T GetFirstValueByKey(const std::string &directory, const std::string &filename,
const size_t &total_characters = 40) {
std::string key, line;
T value;
std::ifstream stream(directory + filename);
if (stream.is_open()) {
if (getline(stream, line)) {
std::istringstream linestream(line);
linestream >> key;
if (key.size() > total_characters) {
key.resize(total_characters);
key = key + "...";
}
return key;
}
}
CloseStream(&stream);
return value;
}
} // namespace ParserUtils
#endif // MONITOR_PARSER_UTILS_H
| [
"andrei.toader-stanescu@tomtom.com"
] | andrei.toader-stanescu@tomtom.com |
f2e17f79958df1a967867dd00c1600ac1513da5e | 6a1eda4d8653fbe54afc5e473ce48de5434cf6b2 | /taiji/v1.0/Taiji/TRedis/RedisClientSet.cpp | 09e050be07e642e651f690f196a74353d11ffb99 | [] | no_license | helloworldyuhaiyang/cdk | 8263f5ddd211fdfc55dec05e4d9d0469f3967f67 | 7ace68f48ca0439dfe3ff451dec32354d4ddc54d | refs/heads/master | 2023-07-19T07:51:03.615697 | 2021-09-07T07:09:07 | 2021-09-07T07:09:07 | 403,876,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,864 | cpp |
#include "Command.h"
#include "CRedisClient.h"
namespace Taiji {
namespace TRedis {
uint64_t CRedisClient::sadd(const string &key, const VecString &members)
{
Command cmd( "SADD" );
cmd << key;
VecString::const_iterator it = members.begin();
VecString::const_iterator end = members.end();
for ( ; it != end ; ++it )
{
cmd << *it;
}
int64_t num;
_getInt( cmd , num );
return num;
}
uint64_t CRedisClient::scard(const string &key)
{
Command cmd( "SCARD" );
cmd << key;
int64_t num;
_getInt( cmd , num );
return num;
}
uint64_t CRedisClient::sdiff(const VecString &keys, VecString &values)
{
Command cmd( "SDIFF" );
VecString::const_iterator it = keys.begin();
VecString::const_iterator end = keys.end();
for ( ; it != end; ++it )
{
cmd << *it;
}
uint64_t num = 0;
_getArry( cmd, values , num);
return num;
}
uint64_t CRedisClient::sdiffstore(const string &destKey, const VecString &keys )
{
Command cmd( "SDIFFSTORE" );
cmd << destKey;
VecString::const_iterator it = keys.begin();
VecString::const_iterator end = keys.end();
for ( ; it != end; ++it )
{
cmd << *it;
}
int64_t num = 0;
_getInt( cmd, num );
return num;
}
uint64_t CRedisClient::sinter(const VecString &keys, VecString &values)
{
Command cmd( "SINTER" );
VecString::const_iterator it = keys.begin();
VecString::const_iterator end = keys.end();
for ( ; it != end; ++it )
{
cmd << *it;
}
uint64_t num = 0;
_getArry( cmd, values, num );
return num;
}
uint64_t CRedisClient::sinterstore( const string& destKey ,const VecString &keys )
{
Command cmd( "SINTERSTORE" );
cmd << destKey;
VecString::const_iterator it = keys.begin();
VecString::const_iterator end = keys.end();
for ( ; it != end; ++it )
{
cmd << *it;
}
int64_t num = 0;
_getInt( cmd, num );
return num;
}
bool CRedisClient::sismember(const string &key, const string &member)
{
Command cmd( "SISMEMBER" );
cmd << key << member;
int64_t num = 0;
_getInt( cmd, num );
return ( num == 1 ? true: false );
}
uint64_t CRedisClient::smembers( const string &key, VecString &members )
{
Command cmd( "SMEMBERS" );
cmd << key;
uint64_t num = 0;
_getArry( cmd, members,num );
return num;
}
bool CRedisClient::smove(const string &source, const string &dest, const string &member)
{
Command cmd( "SMOVE" );
cmd << source << dest << member;
int64_t num;
_getInt( cmd, num );
return ( num==0 ? false : true );
}
bool CRedisClient::spop(const string &key, string &member)
{
member.clear();
Command cmd( "SPOP" );
cmd << key;
return ( _getString( cmd, member ) );
}
bool CRedisClient::srandmember(const string &key, string &member)
{
Command cmd ( "SRANDMEMBER" );
cmd << key;
return ( _getString( cmd, member) );
}
uint64_t CRedisClient::srandmember(const string &key, int count, VecString &members)
{
Command cmd( "SRANDMEMBER" );
cmd << key << count ;
uint64_t num = 0;
_getArry( cmd, members, num );
return num;
}
uint64_t CRedisClient::srem(const string &key,const VecString &members)
{
Command cmd ( "SREM" );
cmd << key;
VecString::const_iterator it = members.begin();
VecString::const_iterator end = members.end();
for ( ; it != end; ++it )
{
cmd << *it;
}
int64_t num;
_getInt( cmd, num );
return num;
}
uint64_t CRedisClient::sunion(const VecString &keys , VecString &members)
{
Command cmd( "SUNION" );
VecString::const_iterator it = keys.begin();
VecString::const_iterator end = keys.end();
for ( ; it != end; ++it )
{
cmd << *it;
}
uint64_t num = 0;
_getArry( cmd, members, num );
return num;
}
uint64_t CRedisClient::sunionstroe(const string &dest, const VecString &keys)
{
Command cmd( "SUNIONSTORE" );
cmd << dest;
VecString::const_iterator it = keys.begin();
VecString::const_iterator end = keys.end();
for ( ; it != end; ++it )
{
cmd << *it;
}
int64_t num;
_getInt( cmd, num );
return num;
}
bool CRedisClient::sscan(const string &key, int64_t &cursor, VecString &values, const string &match, uint64_t count)
{
CResult result;
Command cmd( "SSCAN" );
cmd << key << cursor;
if ( "" != match )
{
cmd << "MATCH" << match;
}
if ( 0 != count )
{
cmd << "COUNT" << count;
}
_getArry( cmd, result );
CResult::ListCResult::const_iterator it = result.getArry().begin();
cursor = _valueFromString<uint64_t>( it->getString() );
++ it;
_getStringVecFromArry( it->getArry(), values );
return ( cursor == 0 ? false : true );
}
}
}
| [
"18989893637@189.cn"
] | 18989893637@189.cn |
bdc964416783c8d74b581f21943c873fb97c6434 | 1a0c8311f35111b275b7fa32db7581b8c9915211 | /soundGEN/classes/sndanalyzer.h | 8d23ca073a50d14c60257ddf24dd1daefdae9c79 | [] | no_license | deus-amd/Sgen | 485ffcafafeb992a5d40d07bfcda352790189c67 | f7223bef1d7a85de64d50eb6436d9ba20dce923d | refs/heads/master | 2020-12-13T21:52:11.541195 | 2014-10-26T10:57:29 | 2014-10-26T10:57:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,378 | h | #ifndef SNDANALYZER_H
#define SNDANALYZER_H
#include <math.h>
#include <QVector>
#include <qDebug>
#include "../abstractsndcontroller.h"
#include "../kiss_fft/kiss_fftr.h"
#include "../kiss_fft/_kiss_fft_guts.h"
struct HarmonicInfo {
double freq;
double amp;
};
class SndAnalyzer
{
public:
SndAnalyzer();
~SndAnalyzer();
void function_fft_top_only(GenSoundFunction fct, PlaySoundFunction pfct, double t1, double t2, double freq, unsigned int points);
void function_fft_base(GenSoundFunction fct, PlaySoundFunction pfct, double t1, double t2, double freq, unsigned int points);
double getInstFrequency();
double getInstAmp();
unsigned int getTop_harmonic() const;
void setTop_harmonic(unsigned int value);
bool getSkip_zero_frequency() const;
void setSkip_zero_frequency(bool value);
QVector<HarmonicInfo>* getHarmonics();
void clearHarmonics();
QVector<HarmonicInfo> *getTopHarmonics();
void clearTopHarmonics();
double getAmp_filter() const;
void setAmp_filter(double value);
private:
double result_freq, result_amp;
double amp_filter;
bool skip_zero_frequency;
unsigned int top_harmonic;
QVector<HarmonicInfo>* harmonics;
QVector<HarmonicInfo>* top_harmonics;
void function_fft_calc_top(kiss_fft_cpx* cout, unsigned int points, double timelen);
};
#endif // SNDANALYZER_H
| [
"posedelov@rusoft.ru"
] | posedelov@rusoft.ru |
63f5f7f01ab9d8e7336db011430a7d17332daf32 | 2068d594c0299ee22ba9f27aef1dbb87ee760319 | /q_다리를지나는트럭.cpp | 9b396d123bd33550ef82c955da71f36de48e97fb | [] | no_license | meenheepark/programmers | e2ee3985547411a8594416a5ac59cd26b44adcf1 | d64fb45dd6b53ae99fc5211c3225f91b2a4ba426 | refs/heads/master | 2021-05-19T10:17:20.928938 | 2020-05-19T01:15:41 | 2020-05-19T01:15:41 | 251,647,909 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 994 | cpp | #include <string>
#include <vector>
#include <queue>
using namespace std;
int solution(int bridge_length, int weight, vector<int> truck_weights) {
int answer = 0;
queue <int> q;
int sum = 0;
for(int i = 0 ; i < truck_weights.size() ; i++){
while(1){
int w = truck_weights[i];
if(q.empty()){
q.push(w);
sum+=w;
answer++;
break;
}
else if(bridge_length == q.size()){ // 브릿지 꽉찻다 도착함
sum -= q.front();
q.pop();
}
else{
if(w+sum > weight){
//무게 넘어서 못싣는다.
q.push(0); answer++;
}
else{
answer++;
q.push(w);
sum+=w;
break;
}
}
}
}
return answer+bridge_length;
} | [
"noreply@github.com"
] | meenheepark.noreply@github.com |
f1023d10c90caacf68b692d37b47e5600b6ecd43 | da8d1b8255feb551e9dc36853cd680da113791a4 | /include/AvbApi_FunctionList.hpp | 4f5c29c51c3fa26e73e267ad0dab1363a7506096 | [
"BSD-2-Clause"
] | permissive | jdkoftinoff/jdksavbapi | a577285fde064d7be0de8d78bddcf2ac18a89128 | 431ee094ed22d05fc5ec7bc0b91f216e33466aae | refs/heads/master | 2020-05-18T17:23:21.335287 | 2014-10-07T20:57:39 | 2014-10-07T20:57:39 | 24,826,923 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,186 | hpp | #pragma once
/*
Copyright (c) 2014, Jeff Koftinoff
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "AvbApi_world.hpp"
namespace AvbApi2014
{
typedef uint32_t FunctionId;
class FunctionListBase
{
public:
FunctionId nextId() { return m_nextFunctionId++; }
virtual void remove( FunctionId fid ) = 0;
private:
std::atomic<FunctionId> m_nextFunctionId;
};
template <typename F>
class FunctionList : public FunctionListBase
{
public:
using function_type = std::function<F>;
using item_type = pair<FunctionId, function_type>;
template <typename... Args>
void operator()( Args... args ) const
{
for ( auto &i : m_functions )
{
i.second( args... );
}
}
FunctionId add( function_type f )
{
FunctionId fid = nextId();
m_functions.emplace_back( make_pair( fid, f ) );
return fid;
}
virtual void remove( FunctionId fid )
{
m_functions.erase( std::remove_if( m_functions.begin(),
m_functions.end(),
[&]( item_type const &item )
{
return item.first == fid;
} ),
m_functions.end() );
}
std::vector<item_type> m_functions;
class Registrar
{
public:
Registrar( FunctionList &functionList, function_type func )
: m_functionList( functionList ), m_fid( m_functionList.add( func ) )
{
}
~Registrar() { m_functionList.remove( m_fid ); }
FunctionList &m_functionList;
FunctionId m_fid;
};
};
template <typename FunctionListT>
auto registerFunction( FunctionListT &functionList, typename FunctionListT::function_type func )
-> typename FunctionListT::Registrar
{
return typename FunctionListT::Registrar( functionList, func );
}
}
| [
"jeffk@jdkoftinoff.com"
] | jeffk@jdkoftinoff.com |
260a83d7146c1912a69ffd7f2ab4d546607d46c9 | 485faf9d4ec7def9a505149c6a491d6133e68750 | /include/wxviz/VizRender.H | 2112f6859a0b7ce0eca1192d40ed39db9b00bc5e | [
"LicenseRef-scancode-warranty-disclaimer",
"ECL-2.0"
] | permissive | ohlincha/ECCE | af02101d161bae7e9b05dc7fe6b10ca07f479c6b | 7461559888d829338f29ce5fcdaf9e1816042bfe | refs/heads/master | 2020-06-25T20:59:27.882036 | 2017-06-16T10:45:21 | 2017-06-16T10:45:21 | 94,240,259 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,547 | h | /**
* @file
*
*/
#ifndef VIZRENDER_H_
#define VIZRENDER_H_
#include <string>
using std::string;
class ChemistryTask;
class SbViewportRegion;
class SoNode;
class SoOffscreenRenderer;
class SGContainer;
class SGViewer;
class SFile;
class VizRender
{
public:
static bool thumbnail(const string& urlstr, int width = 64, int height = 64,
double r = 0.0, double g = 0.0, double b = 0.0);
static bool thumbnail(SoNode *root, ChemistryTask *task,
int width = 64, int height = 64,
double r = 0.0, double g = 0.0, double b = 0.0);
static bool file(SoNode *root, SFile *file, string type = "RGB",
int width = 64, int height = 64,
double r = 0.0, double g = 0.0, double b = 0.0);
static string msg();
protected:
static void loadAtomColors(SGContainer *sg);
static void loadAtomRadii(SGContainer *sg);
static void loadDisplayStyle(SGViewer *viewer, SGContainer *sg);
private:
// For making a movie, you run out of X
// connections if the render area isn't static. In my testing, I
// ran out on about the 70th invocation even though I was
// deleting the object! But if we just have one static, the user
// can't change width/height.
static SbViewportRegion *p_viewport;
static SoOffscreenRenderer *p_renderer;
static string p_msg;
static int p_oldWidth;
static int p_oldHeight;
};
#endif // VIZRENDER_H_
| [
"andre.ohlin@umu.se"
] | andre.ohlin@umu.se |
7a71b6a4d0506a37bc222e9612eaa9758bc01194 | 4cc4d9d488939dde56fda368faf58d8564047673 | /test/vts/compilation_tools/vtsc/code_gen/fuzzer/HalHidlFuzzerCodeGen.cpp | 6bb6176a6d99f7e945f00043e56ca4aa91131e96 | [] | no_license | Tosotada/android-8.0.0_r4 | 24b3e4590c9c0b6c19f06127a61320061e527685 | 7b2a348b53815c068a960fe7243b9dc9ba144fa6 | refs/heads/master | 2020-04-01T11:39:03.926512 | 2017-08-28T16:26:25 | 2017-08-28T16:26:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,150 | cpp | /*
* Copyright 2016 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 "HalHidlFuzzerCodeGen.h"
#include "VtsCompilerUtils.h"
#include "code_gen/common/HalHidlCodeGenUtils.h"
#include "utils/InterfaceSpecUtil.h"
#include "utils/StringUtil.h"
using std::cerr;
using std::cout;
using std::endl;
using std::vector;
namespace android {
namespace vts {
void HalHidlFuzzerCodeGen::GenerateSourceIncludeFiles(Formatter &out) {
out << "#include <iostream>\n\n";
out << "#include \"FuncFuzzerUtils.h\"\n";
string package_path = comp_spec_.package();
ReplaceSubString(package_path, ".", "/");
string comp_version = GetVersionString(comp_spec_.component_type_version());
string comp_name = comp_spec_.component_name();
out << "#include <" << package_path << "/" << comp_version << "/" << comp_name
<< ".h>\n";
out << "\n";
}
void HalHidlFuzzerCodeGen::GenerateUsingDeclaration(Formatter &out) {
out << "using std::cerr;\n";
out << "using std::endl;\n";
out << "using std::string;\n\n";
string package_path = comp_spec_.package();
ReplaceSubString(package_path, ".", "::");
string comp_version =
GetVersionString(comp_spec_.component_type_version(), true);
out << "using namespace ::" << package_path << "::" << comp_version << ";\n";
out << "using namespace ::android::hardware;\n";
out << "\n";
}
void HalHidlFuzzerCodeGen::GenerateGlobalVars(Formatter &out) {
out << "static string target_func;\n\n";
}
void HalHidlFuzzerCodeGen::GenerateLLVMFuzzerInitialize(Formatter &out) {
out << "extern \"C\" int LLVMFuzzerInitialize(int *argc, char ***argv) "
"{\n";
out.indent();
out << "FuncFuzzerParams params{ExtractFuncFuzzerParams(*argc, *argv)};\n";
out << "target_func = params.target_func_;\n";
out << "return 0;\n";
out.unindent();
out << "}\n\n";
}
void HalHidlFuzzerCodeGen::GenerateLLVMFuzzerTestOneInput(Formatter &out) {
out << "extern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t "
"size) {\n";
out.indent();
out << "static ::android::sp<" << comp_spec_.component_name() << "> "
<< GetHalPointerName() << " = " << comp_spec_.component_name()
<< "::getService(true);\n";
out << "if (" << GetHalPointerName() << " == nullptr) {\n";
out.indent();
out << "cerr << \"" << comp_spec_.component_name()
<< "::getService() failed\" << endl;\n";
out << "exit(1);\n";
out.unindent();
out << "}\n\n";
for (const auto &func_spec : comp_spec_.interface().api()) {
GenerateHalFunctionCall(out, func_spec);
}
out << "{\n";
out.indent();
out << "cerr << \"No such function: \" << target_func << endl;\n";
out << "exit(1);\n";
out.unindent();
out << "}\n";
out.unindent();
out << "}\n\n";
}
string HalHidlFuzzerCodeGen::GetHalPointerName() {
string prefix = "android.hardware.";
string hal_pointer_name = comp_spec_.package().substr(prefix.size());
ReplaceSubString(hal_pointer_name, ".", "_");
return hal_pointer_name;
}
void HalHidlFuzzerCodeGen::GenerateReturnCallback(
Formatter &out, const FunctionSpecificationMessage &func_spec) {
if (CanElideCallback(func_spec)) {
return;
}
out << "// No-op. Only need this to make HAL function call.\n";
out << "auto " << return_cb_name << " = [](";
size_t num_cb_arg = func_spec.return_type_hidl_size();
for (size_t i = 0; i < num_cb_arg; ++i) {
const auto &return_val = func_spec.return_type_hidl(i);
out << GetCppVariableType(return_val, nullptr,
IsConstType(return_val.type()));
out << " arg" << i << ((i != num_cb_arg - 1) ? ", " : "");
}
out << "){};\n\n";
}
void HalHidlFuzzerCodeGen::GenerateHalFunctionCall(
Formatter &out, const FunctionSpecificationMessage &func_spec) {
string func_name = func_spec.name();
out << "if (target_func == \"" << func_name << "\") {\n";
out.indent();
GenerateReturnCallback(out, func_spec);
vector<string> types{GetFuncArgTypes(func_spec)};
for (size_t i = 0; i < types.size(); ++i) {
out << "size_t type_size" << i << " = sizeof(" << types[i] << ");\n";
out << "if (size < type_size" << i << ") { return 0; }\n";
out << "size -= type_size" << i << ";\n";
out << types[i] << " arg" << i << ";\n";
out << "memcpy(&arg" << i << ", data, type_size" << i << ");\n";
out << "data += type_size" << i << ";\n\n";
}
out << GetHalPointerName() << "->" << func_spec.name() << "(";
for (size_t i = 0; i < types.size(); ++i) {
out << "arg" << i << ((i != types.size() - 1) ? ", " : "");
}
if (!CanElideCallback(func_spec)) {
if (func_spec.arg_size() > 0) {
out << ", ";
}
out << return_cb_name;
}
out << ");\n";
out << "return 0;\n";
out.unindent();
out << "} else ";
}
bool HalHidlFuzzerCodeGen::CanElideCallback(
const FunctionSpecificationMessage &func_spec) {
if (func_spec.return_type_hidl_size() == 0) {
return true;
}
// Can't elide callback for void or tuple-returning methods
if (func_spec.return_type_hidl_size() != 1) {
return false;
}
const VariableType &type = func_spec.return_type_hidl(0).type();
if (type == TYPE_ARRAY || type == TYPE_VECTOR || type == TYPE_REF) {
return false;
}
return IsElidableType(type);
}
vector<string> HalHidlFuzzerCodeGen::GetFuncArgTypes(
const FunctionSpecificationMessage &func_spec) {
vector<string> types{};
for (const auto &var_spec : func_spec.arg()) {
string type = GetCppVariableType(var_spec);
types.emplace_back(GetCppVariableType(var_spec));
}
return types;
}
} // namespace vts
} // namespace android
| [
"xdtianyu@gmail.com"
] | xdtianyu@gmail.com |
046cb79e430eaa717be3e074028817a2f461d1da | 2e619c8e2b667640989c6703a39fde3e4485679b | /2. Leetcode/easy level/375. kth distinct string in an array.cpp | cd700c6c1ae7fccaa9c2507efebfc0ecec2a6ede | [] | no_license | satyampandey9811/competitive-programming | 76957cde72ba217894ba18370f6489d7c481ba55 | 8ca1e2608f5d221f4be87529052c8eb3b0713386 | refs/heads/master | 2022-10-14T11:13:16.704203 | 2022-09-20T18:24:09 | 2022-09-20T18:24:09 | 203,355,790 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 503 | cpp | // link to question - https://leetcode.com/problems/kth-distinct-string-in-an-array/
class Solution {
public:
string kthDistinct(vector<string>& a, int k) {
map<string, int> m;
int n = a.size(), ct = 0;
for(int i = 0; i < n; i++) {
m[a[i]]++;
}
for(int i = 0; i < n; i++) {
if(m[a[i]] == 1) {
ct++;
if(ct == k) return a[i];
}
}
return "";
}
}; | [
"satyampandey9811@gmail.com"
] | satyampandey9811@gmail.com |
d7d1fdac7bf12c0564d9f5210f2651457f3c0050 | 92eeef4be893943d3f724375299d49b37fde8d50 | /Arrays_and_Strings/zero_matrix.cpp | 9c00abd106cd73e3fde504f004aebfc73cf548ba | [] | no_license | kuluruvineeth/coding_questions | 51593c272bcd3c2d0f2d572d02c8949bd84412fa | ad59620ff8be13dcc4db832466ca4681e7a32ad3 | refs/heads/master | 2023-03-18T01:50:45.624087 | 2021-03-05T14:18:04 | 2021-03-05T14:18:04 | 299,634,419 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,674 | cpp | #include<bits/stdc++.h>
using namespace std;
//to make respective rows all entries as 0.n denotes number of columns
void nullifyrow(int **matrix,int row,int n)
{
for(int i=0;i<n;i++)
{
matrix[row][i]=0;
}
}
//to make respective columns all entries as 0.m denotes number of rows
void nullifycolumn(int **matrix,int col,int m)
{
for(int i=0;i<m;i++)
{
matrix[i][col]=0;
}
}
void nullifymatrix(int **matrix,int m,int n)
{
//checking first row entries for 0
bool firstrow=0;
for(int i=0;i<n;i++)
{
if(matrix[0][i]==0)
{
firstrow=true;
break;
}
}
for(int i=1;i<m;i++)
{
bool nullifytherow=false;
for(int j=0;j<n;j++)
{
if(matrix[i][j]==0)
{
matrix[0][j]=0;
nullifytherow=true;
}
}
if(nullifytherow)
{
nullifyrow(matrix,i,n);
}
}
//making respective columns 0 with respect to rows
for(int i=0;i<n;i++)
{
if(matrix[0][i]==0)
{
nullifycolumn(matrix,i,m);
}
}
//if 0 entry is found in first row we make all entries as 0
if(firstrow)
{
nullifyrow(matrix,0,n);
}
}
void printmatrix(int **matrix,int m,int n)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
int main()
{
int m,n;
cout<<"Enter no of rows : "<<endl;
cin>>m;
cout<<"Enter no of columns : "<<endl;
cin>>n;
int **matrix=new int *[m];
for(int i=0;i<m;i++)
{
matrix[i]=new int [n];
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>matrix[i][j];
}
}
cout<<"original matrix : "<<endl;
printmatrix(matrix,m,n);
nullifymatrix(matrix,m,n);
cout<<"After nullifying the matrix : "<<endl;
printmatrix(matrix,m,n);
return 0;
}
| [
"noreply@github.com"
] | kuluruvineeth.noreply@github.com |
e2b7d2f823ded9be5bbd11c2b9a8d846aef07bf2 | 4e7300d79bbdcaa9f70fff786fe0d8dc71cf3635 | /source/group.cpp | 74306c18056ea7e3b37791ac68afcc2244db993e | [] | no_license | busratican/ComputerGraphics-Assign3 | 4173ec5876f05ac49a49d4e752fdd8fdb2cc40c5 | 93f107b13d832efbdd406dc4a5971511edc79c8e | refs/heads/master | 2021-01-01T06:36:29.440181 | 2017-07-17T11:08:02 | 2017-07-17T11:08:02 | 97,467,174 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 423 | cpp | #include "group.h"
Group::Group(int n) { numObjects = n; index.resize(n); }
Group::~Group() { index.clear(); }
bool Group::intersect(const Ray &r, Hit &h, float tmin)
{
bool __r = false;
for(int i=0;i<numObjects;i++)
{
if(index[i]->intersect(r,h,tmin))
__r = true;
}
return __r;
}
void Group::addObject(int i, Object3D *obj)
{
assert(i < numObjects);
index[i] = obj;
}
| [
"gulbusra55@gmail.com"
] | gulbusra55@gmail.com |
87951a10f99844c1b3c2c51f151120c2a97668b9 | 2eda515fba1767e517d0f6dc84f84590352a54ef | /ZF/ZFUIWidget/zfsrc/ZFUIWidget/ZFUIPageBasic.h | cbacad63895dbefc77a87ce0b3224992851b297b | [
"MIT"
] | permissive | yeshuopp123/ZFFramework | cb43ec281015b563618931c3972ef522a2e535c9 | 6cf2e78fed9e5ef1f35ad8402dbcb56cfd88ad9e | refs/heads/master | 2021-05-01T05:38:03.739214 | 2017-01-22T16:48:47 | 2017-01-22T16:48:47 | 79,763,020 | 1 | 0 | null | 2017-01-23T02:34:41 | 2017-01-23T02:34:40 | null | UTF-8 | C++ | false | false | 7,514 | h | /* ====================================================================== *
* Copyright (c) 2010-2016 ZFFramework
* home page: http://ZFFramework.com
* blog: http://zsaber.com
* contact: master@zsaber.com (Chinese and English only)
* Distributed under MIT license:
* https://github.com/ZFFramework/ZFFramework/blob/master/license/license.txt
* ====================================================================== */
/**
* @file ZFUIPageBasic.h
* @brief basic #ZFUIPage with animation logic
*/
#ifndef _ZFI_ZFUIPageBasic_h_
#define _ZFI_ZFUIPageBasic_h_
#include "ZFUIPage.h"
ZF_NAMESPACE_GLOBAL_BEGIN
// ============================================================
zfclassFwd ZFUIPageManagerBasic;
zfclassFwd _ZFP_ZFUIPageManagerBasicPrivate;
zfclassFwd _ZFP_ZFUIPageBasicPrivate;
/**
* @brief basic page with animation logic,
* see #ZFUIPageManager and #ZFUIPageManagerBasic for how to use
*/
zfabstract ZF_ENV_EXPORT ZFUIPageBasic : zfextends ZFObject, zfimplements ZFUIPage
{
ZFOBJECT_DECLARE_ABSTRACT(ZFUIPageBasic, ZFObject)
ZFIMPLEMENTS_DECLARE(ZFUIPage)
// ============================================================
// observers
public:
/**
* @brief see #ZFObject::observerNotify
*
* called when page about to start animation,
* ensured called even if no animation to start for convenient\n
* param0 is the animation to start or null if no animation to start,
* param1 is the #ZFUIPagePauseReason or #ZFUIPageResumeReason
*/
ZFOBSERVER_EVENT(PageAniOnStart)
/**
* @brief see #ZFObject::observerNotify
*
* called when page about to stop animation,
* ensured called even if no animation to start for convenient\n
* param0 is the animation to stop or null if no animation to stop,
* param1 is the #ZFUIPagePauseReason or #ZFUIPageResumeReason
*/
ZFOBSERVER_EVENT(PageAniOnStop)
// ============================================================
// pageAni
public:
/**
* @brief page's animation
*
* we have these animations for page to setup:
* - pageAniResumeByRequest / pagePauseAniToBackground:
* used when a page is resumed by user request,
* and the previous resume page would be sent to background
* - pageAniResumeFromBackground / pagePauseAniBeforeDestroy:
* used when a foreground page is destroyed by user request,
* and background page would result to be moved to foreground
*
* see #pageAniOnUpdateForResume for more info
*/
ZFPROPERTY_RETAIN(ZFAnimation *, pageAniResumeByRequest)
/**
* @brief page's animation, see #pageAniResumeByRequest
*/
ZFPROPERTY_RETAIN(ZFAnimation *, pageAniResumeFromBackground)
/**
* @brief page's animation, see #pageAniResumeByRequest
*/
ZFPROPERTY_RETAIN(ZFAnimation *, pageAniPauseToBackground)
/**
* @brief page's animation, see #pageAniResumeByRequest
*/
ZFPROPERTY_RETAIN(ZFAnimation *, pageAniPauseBeforeDestroy)
private:
zfbool _ZFP_ZFUIPage_pageAniCanChange;
public:
/**
* @brief the final animation being used when page stack changed, null to disable animation
*
* by default, this value would be updated by #pageAniOnUpdateForSiblingPageResume and #pageAniOnUpdateForResume,
* you may override default value whenever you can,
* to override animation\n
* the recommended way is to override #pageAniOnUpdateForSiblingPageResume and/or #pageAniOnUpdateForResume
* to change this value\n
* this value would be reset to null when animation stopped or page destroyed\n
* see #pageAniOnUpdateForResume for more info
*/
virtual void pageAniSet(ZF_IN ZFAnimation *pageAni);
/**
* @brief see #pageAniSet
*/
virtual ZFAnimation *pageAni(void);
public:
/**
* @brief whether this page need higher priority for animation,
* typically a higher priority animation would have its view on the top
*/
zfbool pageAniPriorityNeedHigher;
protected:
/**
* @brief used to update animation by priority, do nothing by default
*/
virtual void pageAniPriorityOnUpdate(ZF_IN zfbool priorityHigher)
{
}
protected:
/**
* @brief see #pageAniOnUpdateForResume
*/
virtual void pageAniOnUpdateForSiblingPageResume(ZF_IN ZFUIPageResumeReasonEnum reason,
ZF_IN ZFUIPageBasic *siblingResumePageOrNull);
/**
* @brief for page to update it's final animation
*
* the actual animation should be saved to #pageAniSet,
* by this page or by sibling page\n
* \n
* the actual animation logic is achieved by this:
* @code
* ZFUIPageBasic *pausePage = xxx; // page to pause
* ZFUIPageBasic *resumePage = xxx; // page to resume
* pausePage->pageAniOnUpdateForSiblingPageResume(reason, resumePage);
* resumePage->pageAniOnUpdateForResume(reason, pausePage, pauseAniHasHigherPriority);
* zfbool pausePageHasHigherPriority = (!resumePage->pageAniPriorityNeedHigher && pausePage->pageAniPriorityNeedHigher);
* pausePage->pageAniPriorityOnUpdate(pausePageHasHigherPriority);
* resumePage->pageAniPriorityOnUpdate(!pausePageHasHigherPriority);
* @endcode
* by default, #pageAniOnUpdateForSiblingPageResume and #pageAniOnUpdateForResume
* would update page animation
* by #pageAniResumeByRequest/#pageAniResumeFromBackground/#pageAniPauseToBackground/#pageAniPauseBeforeDestroy
* accorrding to page's resume and pause reason,
* and page requested by user would have higher animation priority (request resume or request destroy)
*/
virtual void pageAniOnUpdateForResume(ZF_IN ZFUIPageResumeReasonEnum reason,
ZF_IN ZFUIPageBasic *siblingPausePageOrNull);
/**
* @brief called to update animation's target, do nothing by default
*/
virtual void pageAniOnUpdateAniTarget(ZF_IN ZFAnimation *pageAni)
{
}
// ============================================================
// event
protected:
/** @brief see #EventPageAniOnStart */
virtual void pageAniOnStart(ZF_IN ZFAnimation *pageAni,
ZF_IN ZFEnum *pagePauseReasonOrResumeReason)
{
this->observerNotify(ZFUIPageBasic::EventPageAniOnStart(),
pageAni, pagePauseReasonOrResumeReason);
}
/** @brief see #EventPageAniOnStop */
virtual void pageAniOnStop(ZF_IN ZFAnimation *pageAni,
ZF_IN ZFEnum *pagePauseReasonOrResumeReason)
{
this->observerNotify(ZFUIPageBasic::EventPageAniOnStop(),
pageAni, pagePauseReasonOrResumeReason);
}
// ============================================================
// override
protected:
zfoverride
virtual void pageOnCreate(void);
zfoverride
virtual void pageOnResume(ZF_IN ZFUIPageResumeReasonEnum reason);
zfoverride
virtual void pageOnPause(ZF_IN ZFUIPagePauseReasonEnum reason);
zfoverride
virtual void pageOnDestroy(void);
protected:
zfoverride
virtual void pageDelayDestroyOnCheck(void);
private:
_ZFP_ZFUIPageBasicPrivate *d;
friend zfclassFwd ZFUIPageManagerBasic;
friend zfclassFwd _ZFP_ZFUIPageManagerBasicPrivate;
friend zfclassFwd _ZFP_ZFUIPageBasicPrivate;
};
ZF_NAMESPACE_GLOBAL_END
#endif // #ifndef _ZFI_ZFUIPageBasic_h_
| [
"z@zsaber.com"
] | z@zsaber.com |
8d8564d9a498e18607bf1a694729ef2a27b7fb96 | cfad33a05c9d942060f05417521fe6512d3470e0 | /python/cc/simple_output_stream_adapter_test.cc | b2e5efc1824a2e08a78d19155190b853be0b1806 | [
"Apache-2.0"
] | permissive | code-machina/tink | fe2d3772e9b12ceaaef18c0789af2cdcd3ee6b9a | 6db4f1846642e7f631043770ea80cf56caec723b | refs/heads/master | 2020-07-18T15:42:40.824615 | 2019-09-03T19:15:21 | 2019-09-03T19:15:49 | 206,271,110 | 1 | 0 | Apache-2.0 | 2019-09-04T08:34:19 | 2019-09-04T08:33:30 | null | UTF-8 | C++ | false | false | 7,857 | cc | // 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 "tink/python/cc/simple_output_stream_adapter.h"
#include <memory>
#include "gtest/gtest.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "tink/subtle/random.h"
#include "tink/util/status.h"
#include "tink/util/statusor.h"
#include "tink/python/cc/simple_output_stream.h"
namespace crypto {
namespace tink {
namespace {
// SimpleOutputStream for testing.
class TestSimpleOutputStream : public SimpleOutputStream {
public:
util::StatusOr<int> Write(absl::string_view data) override {
buffer_ += std::string(data);
return data.size();
}
util::Status Close() override { return util::OkStatus(); }
int64_t Position() const override { return buffer_.size(); }
std::string* GetBuffer() { return &buffer_; }
private:
std::string buffer_;
};
// Writes 'contents' to the specified 'output_stream', and closes the stream.
// Returns the status of output_stream->Close()-operation, or a non-OK status
// of a prior output_stream->Next()-operation, if any.
util::Status WriteToStream(SimpleOutputStreamAdapter* output_stream,
absl::string_view contents) {
void* buffer;
int pos = 0;
int remaining = contents.length();
int available_space = 0;
int available_bytes = 0;
while (remaining > 0) {
auto next_result = output_stream->Next(&buffer);
if (!next_result.ok()) return next_result.status();
available_space = next_result.ValueOrDie();
available_bytes = std::min(available_space, remaining);
memcpy(buffer, contents.data() + pos, available_bytes);
remaining -= available_bytes;
pos += available_bytes;
}
if (available_space > available_bytes) {
output_stream->BackUp(available_space - available_bytes);
}
return output_stream->Close();
}
TEST(SimpleOutputStreamAdapterTest, WritingStreams) {
for (size_t stream_size : {0, 10, 100, 1000, 10000, 100000, 1000000}) {
SCOPED_TRACE(absl::StrCat("stream_size = ", stream_size));
std::string stream_contents = subtle::Random::GetRandomBytes(stream_size);
auto output = absl::make_unique<TestSimpleOutputStream>();
std::string* output_buffer = output->GetBuffer();
auto output_stream =
absl::make_unique<SimpleOutputStreamAdapter>(std::move(output));
auto status = WriteToStream(output_stream.get(), stream_contents);
EXPECT_TRUE(status.ok()) << status;
EXPECT_EQ(stream_size, output_buffer->size());
EXPECT_EQ(stream_contents, *output_buffer);
}
}
TEST(SimpleOutputStreamAdapterTest, CustomBufferSizes) {
int stream_size = 1024 * 1024;
std::string stream_contents = subtle::Random::GetRandomBytes(stream_size);
for (int buffer_size : {1, 10, 100, 1000, 10000, 100000, 1000000}) {
SCOPED_TRACE(absl::StrCat("buffer_size = ", buffer_size));
auto output = absl::make_unique<TestSimpleOutputStream>();
std::string* output_buffer = output->GetBuffer();
auto output_stream = absl::make_unique<SimpleOutputStreamAdapter>(
std::move(output), buffer_size);
void* buffer;
auto next_result = output_stream->Next(&buffer);
EXPECT_TRUE(next_result.ok()) << next_result.status();
EXPECT_EQ(buffer_size, next_result.ValueOrDie());
output_stream->BackUp(buffer_size);
auto status = WriteToStream(output_stream.get(), stream_contents);
EXPECT_TRUE(status.ok()) << status;
EXPECT_EQ(stream_size, output_buffer->size());
EXPECT_EQ(stream_contents, *output_buffer);
}
}
TEST(SimpleOutputStreamAdapterTest, BackupAndPosition) {
int stream_size = 1024 * 1024;
int buffer_size = 1234;
void* buffer;
std::string stream_contents = subtle::Random::GetRandomBytes(stream_size);
auto output = absl::make_unique<TestSimpleOutputStream>();
std::string* output_buffer = output->GetBuffer();
// Prepare the stream and do the first call to Next().
auto output_stream = absl::make_unique<SimpleOutputStreamAdapter>(
std::move(output), buffer_size);
EXPECT_EQ(0, output_stream->Position());
auto next_result = output_stream->Next(&buffer);
EXPECT_TRUE(next_result.ok()) << next_result.status();
EXPECT_EQ(buffer_size, next_result.ValueOrDie());
EXPECT_EQ(buffer_size, output_stream->Position());
std::memcpy(buffer, stream_contents.data(), buffer_size);
// BackUp several times, but in total fewer bytes than returned by Next().
int total_backup_size = 0;
for (int backup_size : {0, 1, 5, 0, 10, 100, -42, 400, 20, -100}) {
SCOPED_TRACE(absl::StrCat("backup_size = ", backup_size));
output_stream->BackUp(backup_size);
total_backup_size += std::max(backup_size, 0);
EXPECT_EQ(buffer_size - total_backup_size, output_stream->Position());
}
EXPECT_LT(total_backup_size, next_result.ValueOrDie());
// Call Next(), it should succeed.
next_result = output_stream->Next(&buffer);
EXPECT_TRUE(next_result.ok()) << next_result.status();
// BackUp() some bytes, again fewer than returned by Next().
total_backup_size = 0;
for (int backup_size : {0, 72, -94, 37, 82}) {
SCOPED_TRACE(absl::StrCat("backup_size = ", backup_size));
output_stream->BackUp(backup_size);
total_backup_size += std::max(0, backup_size);
EXPECT_EQ(buffer_size - total_backup_size, output_stream->Position());
}
EXPECT_LT(total_backup_size, next_result.ValueOrDie());
// Call Next(), it should succeed;
next_result = output_stream->Next(&buffer);
EXPECT_TRUE(next_result.ok()) << next_result.status();
// Call Next() again, it should return a full block.
auto prev_position = output_stream->Position();
next_result = output_stream->Next(&buffer);
EXPECT_TRUE(next_result.ok()) << next_result.status();
EXPECT_EQ(buffer_size, next_result.ValueOrDie());
EXPECT_EQ(prev_position + buffer_size, output_stream->Position());
std::memcpy(buffer, stream_contents.data() + buffer_size, buffer_size);
// BackUp a few times, with total over the returned buffer_size.
total_backup_size = 0;
for (int backup_size :
{0, 72, -100, buffer_size / 2, 200, -25, buffer_size / 2, 42}) {
SCOPED_TRACE(absl::StrCat("backup_size = ", backup_size));
output_stream->BackUp(backup_size);
total_backup_size = std::min(buffer_size,
total_backup_size + std::max(backup_size, 0));
EXPECT_EQ(prev_position + buffer_size - total_backup_size,
output_stream->Position());
}
EXPECT_EQ(total_backup_size, buffer_size);
EXPECT_EQ(prev_position, output_stream->Position());
// Call Next() again, it should return a full block.
next_result = output_stream->Next(&buffer);
EXPECT_TRUE(next_result.ok()) << next_result.status();
EXPECT_EQ(buffer_size, next_result.ValueOrDie());
EXPECT_EQ(prev_position + buffer_size, output_stream->Position());
std::memcpy(buffer, stream_contents.data() + buffer_size, buffer_size);
// Write the remaining stream contents to stream.
auto status = WriteToStream(
output_stream.get(), stream_contents.substr(output_stream->Position()));
EXPECT_TRUE(status.ok()) << status;
EXPECT_EQ(stream_size, output_buffer->size());
EXPECT_EQ(stream_contents, *output_buffer);
}
} // namespace
} // namespace tink
} // namespace crypto
| [
"copybara-worker@google.com"
] | copybara-worker@google.com |
86c28b5d79a7b3a62e6010f0794768bba40bff6d | 303b225245d9d090849fe89b32d46e171bbcb125 | /C++/final/final1.1_fixed/input.h | 5e2a564281654747d599a6b1390d4467808e0339 | [] | no_license | Trouble404/Undergraduate-courseworks | cb3e70923168e4312d5a90e4d4bca0ee705ddeea | 1e8b49f343c60c2756b701806ee97a3a8b0bbe5f | refs/heads/master | 2021-09-05T01:51:16.309069 | 2018-01-23T15:07:42 | 2018-01-23T15:07:42 | 118,033,958 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 284 | h | #ifndef _INPUT_H
#define _INPUT_H
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cstring>
using namespace std;
int choose(int c); //菜单中的选择函数
int inte_Input(); //输入数字
string str_Input();//输入字符串
#endif | [
"362914124@qq.com"
] | 362914124@qq.com |
e32fb1861165772e7f2ae4bb2e750049e3b48ea2 | 35155c04e6eb4d65737cfc5477990479d40f47a6 | /scripts/x-test-fem/x-test-neb/test-case-1-sin-buckle/src/murty95.cpp | 8f7b0c843be13783acc76981988d780422e89d38 | [] | no_license | XiaohanZhangCMU/mdGpy | b1476fb829e95c21ff0bb86ad2047e280dc2c796 | 90916bfb9cb2604b6f3341c8b7c5b37380a6679d | refs/heads/master | 2020-03-20T18:40:06.092597 | 2018-06-16T17:56:39 | 2018-06-16T17:56:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,587 | cpp | /*
murty95.h
by Keonwook Kang kwkang75@yonsei.ac.kr
Last Modified :
FUNCTION :
Reference: M. V. Ramana Murty and Harry A. Atwater
"Empirical interatomic potential for Si-H interactions"
Phys. Rev. B, 51, 4889 (1995)
Si-Si interaction is based on
J. Tersoff, Empirical interatomic potential for silicon
with improved elastic properties
Phys. Rev. B, 38, 9902 (1988), Si(C)
H-H interaction is based on
D. W. Brenner, "Empirical potential for hydrogen for use
in simulating the chemical vapor deposition of diamond films"
Phys. Rev. B, 42, 9458 (1990)
Note: Implemented by modifying tersoff.cpp
The cut-off fuction f_c in eqn.(4) is identical expression
with the cut-off function in Tersoff PRB 39 5566(1989).
Just, R_{ij} = R-D and S_{ij} = R+D or
R = (R_{ij} + S_{ij})/2, D = - (R_{ij} - S_{ij})/2
*/
#include "murty95.h"
inline double spline(double spline_coeff[4], double func[], int ind, double x)
{
/* cubic spline based on Lagrange polynomials
f(x) = a_i/(6*h_i)*(x_{i+1} - x)^3 + a_{i+1}/(6*h_i)*(x-x_i)^3
+ (y_i/h_i-a_i*h_i/6)*(x_{i+1}-x)
+ (y_{i+1}/h_i-a_{i+1}*h_i/6)*(x-x_i)
where h_i = x_{i+1}-x_i
*/
int xi, xip1;
double a, b, fi, fip1, f;
double pp, pp2, pp3;
double qq, qq2, qq3;
xi = ind; xip1 = ind+1;
a = spline_coeff[ind];
b = spline_coeff[ind+1];
fi = func[ind]; fip1 = func[ind+1];
pp = x-xi; pp2 = pp*pp; pp3=pp2*pp;
qq = xip1-x; qq2=qq*qq; qq3=qq2*qq;
f=a/6.0*qq3+b/6.0*pp3+(fi-a/6.0)*qq+(fip1-b/6.0)*pp;
return f;
}
void compute_spline_coeff(int ngrd, double func[],double h, double spline_coeff[])
{
int i,ind,n=ngrd-2;
if (n<1) ERROR("Increase ngrd in murty95.h");
double dia[n], adia[n-1], bdia[n-1], B[n], x[n];
/* Thomas algorithm to solve Ax=B
A = [2h h 0 0 ...
h 2h h 0 ...
0 h 2h h ...
...
h 2h ] */
for (i=0;i<n;i++)
{
dia[i]=2.0*h; B[i] = 6.0*(func[i+2]-func[i])/h;
}
for (i=0;i<(n-1);i++)
{
adia[i]=h; // above diagonal
bdia[i]=h; // below diagonal
}
adia[0]=adia[0]/dia[0];
B[0]=B[0]/dia[0];
for (i=1;i<(n-1);i++)
{
adia[i]=adia[i]/(dia[i]-bdia[i-1]*adia[i-1]);
B[i]=(B[i]-bdia[i-1]*B[i-1])/(dia[i]-bdia[i-1]*adia[i-1]);
}
B[n-1]=(B[n-1]-bdia[n-2]*B[n-2])/(dia[n-1]-bdia[n-2]*adia[n-2]);
x[n-1]=B[n-1];
for (i=n-2;i>=0;i--)
x[i]=B[i]-adia[i]*x[i+1];
/* natural cubic spline :
the 2nd derivatives at the endpoints are zero */
spline_coeff[0] = 0.0;
for(ind=1;ind<ngrd-1;ind++)
{
spline_coeff[ind] = x[ind-1];
}
spline_coeff[ngrd-1] = 0.0;
}
void Murty95Frame::initvars()
{
#ifdef _MA_ORIG
/* Fitting parameters for Si-Si, PRB 51 4889 (1995) */
A_SiSi = 1.8308e3; // A (eV)
B_SiSi = 4.7118e2; // B (eV)
Lam_SiSi = 2.4799; // lambda_1 (1/\AA)
Mu_SiSi = 1.7322; // lambda_2 (1/\AA)
Alpha_SiSi = 5.1975; //
Beta_SiSi = 3.0; // beta
R0_SiSi = 2.35; // equilibrium distance to 1nn (\AA)
R_SiSi = 2.85; // R (\AA)
D_SiSi = 0.15; // D (\AA)
cTf_SiSi = 0.0; // c
dTf_SiSi = 0.160; // d
hTf_SiSi =-5.9826e-1; // h
eta_SiSi = 7.8734e-1;
delta_SiSi = 0.635;
F1_SiSi = 1.0;
F2_SiSi = 1.0;
/* Fitting parameters for H-H, PRB 51 4889 (1995) */
A_HH = 80.07;
B_HH = 31.38;
Lam_HH = 4.2075;
Mu_HH = 1.7956;
Alpha_HH = 3.0;
Beta_HH = 1.0; // beta
R0_HH = 0.74;
R_HH = 1.40;
D_HH = 0.30;
cTf_HH = 4.0; // c
dTf_HH = 0.0; // d
hTf_HH = 0.0; // h
eta_HH = 1.0;
delta_HH = 0.80469;
F1_HH = 1.0;
F2_HH = 1.0;
#else
#if 1
/* Fitting parameters for Si-Si,
M.S. Kim and B.C Lee EPL 102 (2013) 33002 */
A_SiSi = 2.0119e3; // A (eV)
B_SiSi = 7.1682e1; // B (eV)
Lam_SiSi = 3.0145; // lambda_1 (1/\AA)
Mu_SiSi = 1.1247; // lambda_2 (1/\AA)
Alpha_SiSi = 3.27; //
Beta_SiSi = 2.0; // beta
R0_SiSi = 2.37; // equilibrium distance to 1nn (\AA)
R_SiSi = 3.33; // R (\AA)
D_SiSi = 0.15; // D (\AA)
cTf_SiSi = 0.01123; // c
dTf_SiSi = 0.18220; // d
hTf_SiSi =-3.3333e-1; // h
eta_SiSi = 5.2772e-1;
delta_SiSi = 1.0;
F1_SiSi = 1.0;
F2_SiSi = 1.0;
#else
/* new fitting Nov 28, 2014 */
A_SiSi = 8025.195302116495; // A (eV)
B_SiSi = 40.701115782280240;// B (eV)
Lam_SiSi = 3.909594726562502; // lambda_1 (1/\AA)
Mu_SiSi = 0.867186853088723; // lambda_2 (1/\AA)
Alpha_SiSi = 0.001; //
Beta_SiSi = 2.0; // beta
R0_SiSi = 2.37; // equilibrium distance to 1nn (\AA)
R_SiSi = 3.33; // R (\AA)
D_SiSi = 0.15; // D (\AA)
cTf_SiSi = 0.233029307210524; // c
dTf_SiSi = 1.072002775222063; // d
hTf_SiSi =-0.448928185468685; // h
eta_SiSi = 1.08671875;
delta_SiSi = 0.761787281185388;
F1_SiSi = 1.0;
F2_SiSi = 1.0;
#endif
/* Fitting parameters for H-H,
M.S. Kim and B.C. Lee EPL 102 (2013) 33002 */
A_HH = 66.8276;
B_HH = 21.5038;
Lam_HH = 4.4703;
Mu_HH = 1.1616;
Alpha_HH = 3.0;
Beta_HH = 1.0; // beta
R0_HH = 0.75;
R_HH = 3.50;
D_HH = 0.50;
cTf_HH = 0.9481; // c
dTf_HH = 0.0; // d
hTf_HH = 0.0; // h
eta_HH = 1.6183;
delta_HH = 0.8684;
F1_HH = 1.0;
F2_HH = 1.0;
#endif
/* Fitting parameters for Si-H, PRB 51 4889 (1995) */
A_SiH = 323.54;
B_SiH = 84.18;
Lam_SiH = 2.9595;
Mu_SiH = 1.6158;
Alpha_SiH = 4.0; Alpha_SiH2 = 0.00;
Beta_SiH = 3.0; Beta_SiH2 = 0.00;
R0_SiH = 1.475;
R_SiH = 1.85;
D_SiH = 0.15;
cTf_SiH = 0.0216; cTf_SiH2 = 0.70;
dTf_SiH = 0.27; dTf_SiH2 = 1.00;
eta_SiH = 1.0;
delta_SiH = 0.80469;
hTf_SiH[0] = -0.040; hTf_SiH2 =-1.00;
hTf_SiH[1] = -0.040;
hTf_SiH[2] = -0.040;
hTf_SiH[3] = -0.276;
hTf_SiH[4] = -0.47;
F1_SiH[0] = 0.0;
F1_SiH[1] = 1.005;
F1_SiH[2] = 1.109;
F1_SiH[3] = 0.953;
F1_SiH[4] = 1.0;
F2_SiH[0] = 0.0;
F2_SiH[1] = 0.930;
F2_SiH[2] = 1.035;
F2_SiH[3] = 0.934;
F2_SiH[4] = 1.0;
acut=max(R_SiSi+D_SiSi,R_HH+D_HH);
acut=max(acut,R_SiH+D_SiH)*1.0;
_RLIST=acut*1.1;
_SKIN=_RLIST-acut;
acutsq=acut*acut;
strcpy(incnfile,"../si.cn");
DUMP(HIG"Murty95Frame initvars"NOR);
MDFrame::initvars();
}
void Murty95Frame::murty()
{
#ifndef NNM /* need to be taken care of later */
#define NNM 60
#endif
/* Multi process function */
int i,j,k,ipt,jpt,kpt,neg,n1nn=0;
int species_ipt,species_jpt,species_kpt;
Vector3 sij,rij,f3i,fZ,fTheta;
double fC, fA, fR, dfCdr, dfAdr, dfRdr;
double Arg1, Arg2, temp, Z, CosTheta, dCosTheta, gTheta, gR, dgRdr, Zeta, Zeta1, bij;
double r2ij, rrij, r, neff1nn;
double V, dVdr, dVdZ;
double rr[NNM], Re[NNM], Neff1NN[_NP];
//double Asave[NNM], Bsave[NNM], Musave[NNM], Lamsave[NNM];
//double Rsave[NNM], Ssave[NNM];
double fCsave[NNM], dfCdrsave[NNM], fAsave[NNM], dfAdrsave[NNM];
double fRsave[NNM], dfRdrsave[NNM], dZdCosTheta[NNM];
double dZdrij, dZdrik[NNM];
Vector3 rg[NNM], rt[NNM];
int list2[NNM];
int n0, n1;
DUMP("Murty & Atwater 95");
refreshneighborlist();
/* _EPOT, _F, _EPOT_IND, _VIRIAL all local */
_EPOT=0;
for(i=0;i<_NP;i++)
{ _F[i].clear(); _EPOT_IND[i]=0;}
_VIRIAL.clear();
n0=0;
n1=_NP;
compute_spline_coeff(NGRD,F1_SiH,1.0,F1_csp);
compute_spline_coeff(NGRD,F2_SiH,1.0,F2_csp);
compute_spline_coeff(NGRD,hTf_SiH,1.0,H_csp);
memset(Neff1NN,0,sizeof(double)*_NP);
/* 1st iteration to calculate coordination of Si atoms */
for(ipt=n0;ipt<n1;ipt++)
{
if(fixed[ipt]==-1) continue; /* ignore atom if -1 */
species_ipt=species[ipt];
//if(species_ipt==1) continue; /* ignore if atom is H */
neff1nn = 0;
for(j=0;j<nn[ipt];j++)
{
jpt=nindex[ipt][j];
if(fixed[jpt]==-1) continue; /* ignore atom if -1 */
sij.subtract(_SR[jpt],_SR[ipt]);
sij.subint();
_H.multiply(sij,rij);
r2ij=rij.norm2();
if(r2ij>acutsq) continue;
rrij=sqrt(r2ij);
r = rrij;
species_jpt=species[jpt];
/* set potential parameters */
if (species_ipt==0 && species_jpt==0)
{ // Si-Si interaction
R = R_SiSi; D = D_SiSi;
}
else if (species_ipt==1 && species_jpt==1)
{ // H-H interaction
R = R_HH; D = D_HH;
}
else if ((species_ipt==0&&species_jpt==1)
|| (species_ipt==1&&species_jpt==0))
{ // Si-H interaction
R = R_SiH; D = D_SiH;
}
if (r>=(R+D)) continue;
if(r<=(R-D))
fC = 1;
else if (r<(R+D))
{
Arg1 = M_PI*(r-R)/(2*D);
Arg2 = 3.0*Arg1;
fC = 0.5-9.0/16.0*sin(Arg1)-1/16.0*sin(Arg2);
}
else
fC = 0;
neff1nn+=fC;
}
Neff1NN[ipt]=neff1nn;
//INFO("neff1nn="<<neff1nn);
}
/* 2nd iteration to calculate individual energy and force */
for(ipt=n0;ipt<n1;ipt++)
{
if(fixed[ipt]==-1) continue; /* ignore atom if -1 */
species_ipt=species[ipt];
memset(fCsave,0,sizeof(double)*NNM);
memset(dfCdrsave,0,sizeof(double)*NNM);
memset(fAsave,0,sizeof(double)*NNM);
memset(dfAdrsave,0,sizeof(double)*NNM);
memset(fRsave,0,sizeof(double)*NNM);
memset(dfRdrsave,0,sizeof(double)*NNM);
memset(dZdrik,0,sizeof(double)*NNM);
memset(dZdCosTheta,0,sizeof(double)*NNM);
memset(rr,0,sizeof(double)*NNM);
memset(Re,0,sizeof(double)*NNM);
memset(list2,0,sizeof(int)*NNM);
for(j=0;j<NNM;j++)
{
rg[j].clear(); rt[j].clear();
}
neg = 0;
for(j=0;j<nn[ipt];j++)
{
jpt=nindex[ipt][j];
if(fixed[jpt]==-1) continue; /* ignore atom if -1 */
sij.subtract(_SR[jpt],_SR[ipt]);
sij.subint();
_H.multiply(sij,rij);
r2ij=rij.norm2();
if(r2ij>acutsq) continue;
rrij=sqrt(r2ij);
r = rrij;
species_jpt=species[jpt];
/* set potential parameters */
if (species_ipt==0 && species_jpt==0)
{ // Si-Si interaction
A = A_SiSi; B = B_SiSi;
Lam = Lam_SiSi; Mu = Mu_SiSi;
R0 = R0_SiSi; R = R_SiSi; D = D_SiSi;
}
else if (species_ipt==1 && species_jpt==1)
{ // H-H interaction
A = A_HH; B = B_HH;
Lam = Lam_HH; Mu = Mu_HH;
R0 = R0_HH; R = R_HH; D = D_HH;
}
else if ((species_ipt==0&&species_jpt==1)
|| (species_ipt==1&&species_jpt==0))
{
A = A_SiH; B = B_SiH;
Lam = Lam_SiH; Mu = Mu_SiH;
R0 = R0_SiH; R = R_SiH; D = D_SiH;
}
if (r>=(R+D)) continue;
if(r<=(R-D))
{
fC = 1;
dfCdr = 0;
}
else if (r<(R+D))
{
Arg1 = M_PI*(r-R)/(2.0*D);
Arg2 = 3.0*Arg1;
fC = 0.5-9.0/16.0*sin(Arg1)-1.0/16.0*sin(Arg2);
dfCdr = -3.0/16.0*(3.0*cos(Arg1)+cos(Arg2))*M_PI/(2.0*D);
}
else
{
fC = 0;
dfCdr = 0;
}
/* Repulsion, fR = A*F1*exp(-Lam*r) */
fR = A*exp(-Lam*r);
dfRdr = -Lam*fR;
/* Attraction, fA = -B*F2*exp(-Mu*r) */
fA = -B*exp(-Mu*r);
dfAdr = -Mu*fA;
/* save all neighbors of i */
rg[neg]=rij; /* displacement vector */
rt[neg]=rij; rt[neg]/=rrij; /* unit vector */
rr[neg]=rrij; /* distance */
list2[neg]=jpt; /* neighbor index */
Re[neg]=R0; /* equilibrium distance between i and j */
fCsave[neg]=fC;
dfCdrsave[neg]=dfCdr;
fAsave[neg]=fA;
dfAdrsave[neg]=dfAdr;
fRsave[neg]=fR;
dfRdrsave[neg]=dfRdr;
neg++;
}
//INFO_Printf("neg=%d\n",neg);
/* going through the neighbors of atom i again */
for(j=0;j<neg;j++)
{
jpt=list2[j];
if(fixed[jpt]==-1) continue; /* ignore atom if -1 */
species_jpt=species[jpt];
/* set potential parameters */
if (species_ipt==0 && species_jpt==0 )
{ // Si-Si interaction
A = A_SiSi; B = B_SiSi;
Lam = Lam_SiSi; Mu = Mu_SiSi;
Alpha = Alpha_SiSi; Beta = Beta_SiSi;
cTf = cTf_SiSi; dTf = dTf_SiSi; hTf = hTf_SiSi;
R0 = R0_SiSi; R = R_SiSi; D = D_SiSi;
eta = eta_SiSi; delta = delta_SiSi;
F1 = F1_SiSi; F2 = F2_SiSi;
}
else if (species_ipt==1 && species_jpt==1 )
{ // H-H interaction
A = A_HH; B = B_HH;
Lam = Lam_HH; Mu = Mu_HH;
Alpha = Alpha_HH; Beta = Beta_HH;
R0 = R0_HH; cTf = cTf_HH; dTf = dTf_HH;
hTf = hTf_HH; R = R_HH; D = D_HH;
eta = eta_HH; delta = delta_HH;
F1 = F1_HH; F2 = F2_HH;
}
else if ((species_ipt==0&&species_jpt==1)
||(species_ipt==1&&species_jpt==0))
{ // Si-H interaction
A = A_SiH; B = B_SiH;
Lam = Lam_SiH; Mu = Mu_SiH;
Alpha = Alpha_SiH; Beta = Beta_SiH;
R0 = R0_SiH; R = R_SiH; D = D_SiH;
cTf = cTf_SiH; dTf = dTf_SiH;
eta = eta_SiH; delta = delta_SiH;
/* Assign the effective coordination of Si */
if (species_ipt==0) neff1nn=Neff1NN[ipt];
if (species_ipt==1) neff1nn=Neff1NN[jpt];
if (neff1nn>=4.0)
{
hTf = hTf_SiH[NGRD-1]; F1 = F1_SiH[NGRD-1]; F2 = F2_SiH[NGRD-1];
}
else if (neff1nn<4.0)
{
n1nn = (int)neff1nn;
F1 = spline(F1_csp,F1_SiH,n1nn,neff1nn);
F2 = spline(F2_csp,F2_SiH,n1nn,neff1nn);
/* hTf will be obtained in the three-body loop. */
}
}
//INFO("neff1nn = "<<neff1nn);
//INFO("F1 = "<<F1);
//INFO("F2 = "<<F2);
//INFO("H = "<<hTf);
dZdrij=0.0;
Z = 0.0; /* bond order for attractive term */
/* three body loop */
for(k=0;k<neg;k++)
{
if(k==j) continue; /* k and j are different neighbors */
kpt=list2[k];
/* if fixed == -1, simply ignore this atom */
if(fixed[kpt]==-1) continue; /* ignore atom if -1 */
species_kpt=species[kpt];
/* Calculate F1(N), F2(N) and hTf using cubic spline */
/* consider triplet (i,j,k)
j k
V
i */
if(species_ipt==0&&species_jpt==0&&species_kpt==0)
{ //(i,j,k) = (Si,Si,Si) I
Alpha = Alpha_SiSi; Beta = Beta_SiSi;
cTf = cTf_SiSi; dTf = dTf_SiSi; hTf = hTf_SiSi;
}
if(species_ipt==0&&species_jpt==0&&species_kpt==1)
{ //(Si,Si,H) IIa
Alpha = Alpha_SiH; Beta = Beta_SiH;
cTf = cTf_SiH; dTf = dTf_SiH;
hTf = spline(H_csp,hTf_SiH,(int)Neff1NN[ipt],Neff1NN[ipt]);
}
if(species_ipt==0&&species_jpt==1&&species_kpt==0)
{ //(Si,H,Si) IIa
Alpha = Alpha_SiH; Beta = Beta_SiH;
cTf = cTf_SiH; dTf = dTf_SiH;
hTf = spline(H_csp,hTf_SiH,(int)Neff1NN[ipt],Neff1NN[ipt]);
}
if(species_ipt==0&&species_jpt==1&&species_kpt==1)
{ //(Si,H,H) IIa
Alpha = Alpha_SiH; Beta = Beta_SiH;
cTf = cTf_SiH; dTf = dTf_SiH;
hTf = spline(H_csp,hTf_SiH,(int)Neff1NN[ipt],Neff1NN[ipt]);
}
if(species_ipt==1&&species_jpt==0&&species_kpt==0)
{ //(H,Si,Si) IIb
Alpha = Alpha_SiH2; Beta = Beta_SiH2;
cTf = cTf_SiH2; dTf = dTf_SiH2; hTf = hTf_SiH2;
}
if(species_ipt==1&&species_jpt==0&&species_kpt==1)
{ //(H,Si,H) III
Alpha = Alpha_HH; Beta = Beta_HH;
cTf = cTf_HH; dTf = dTf_HH; hTf = hTf_HH;
}
if(species_ipt==1&&species_jpt==1&&species_kpt==0)
{ //(H,H,Si) III
Alpha = Alpha_HH; Beta = Beta_HH;
cTf = cTf_HH; dTf = dTf_HH; hTf = hTf_HH;
}
if(species_ipt==1&&species_jpt==1&&species_kpt==1)
{ //(H,H,H) III
Alpha = Alpha_HH; Beta = Beta_HH;
cTf = cTf_HH; dTf = dTf_HH; hTf = hTf_HH;
}
//INFO("H = "<<hTf);
/* cos(theta_ijk): angle between bond ij and bond ik */
CosTheta=rt[j]*rt[k];
/* h-cos(theta_ijk) */
dCosTheta = (hTf-CosTheta);
/* g(theta)=c+d*(h-cos(theta_ijk))^2 */
gTheta = cTf+dTf*dCosTheta*dCosTheta;
/* g(r) = exp[alpha*{(r_ij-R0_ij)-(r_ik-R0_ik)}^beta] */
gR = exp(Alpha*pow((rr[j]-Re[j]-rr[k]+Re[k]),Beta));
Z += fCsave[k]*gTheta*gR;
/* d(gR)/d(r_ik) */
//dgRdr = gR*(-1.0)*Alpha*Beta*pow((rr[j]-Re[j]-rr[k]+Re[k]),Beta-1);
/* d(gR)/d(r_ij) */
dgRdr = gR*Alpha*Beta*pow((rr[j]-Re[j]-rr[k]+Re[k]),Beta-1);
dZdrij+=fCsave[k]*gTheta*dgRdr;
dZdrik[k] = dfCdrsave[k]*gTheta*gR-fCsave[k]*gTheta*dgRdr;
dZdCosTheta[k] = (fCsave[k]*gR)*(-2.0)*dTf*(hTf-CosTheta);
//INFO("g(theta)="<<gTheta<<", g(r)="<<gR);
}
fC = fCsave[j];
dfCdr = dfCdrsave[j];
fA = fAsave[j];
dfAdr = dfAdrsave[j];
fR = fRsave[j];
dfRdr = dfRdrsave[j];
Zeta = pow(Z,eta);
Zeta1 = pow(Z,eta-1);
if(neg==1) Zeta1=0.0;
bij = pow((1.0+Zeta),(-1.0)*delta);
V = 0.5*fC*(F1*fR+bij*F2*fA);
//INFO("Z="<<Z<<", bij = "<<bij);
//INFO("V="<<V<<" (eV)");
#if 0
// Debug
FILE *fp;
if(ipt==0)
{
INFO("write energy.dat");
if(j==0) fp=fopen("energy.dat","w");
else fp=fopen("energy.dat","a");
if(fp==NULL) FATAL("open file failure");
fprintf(fp, "%d %d %12.10e %12.10e %12.10e %12.10e %12.10e %12.10e\n", ipt,jpt,fC, F1, F2, fR,fA,bij);
fclose(fp);
}
#endif
_EPOT += V;
_EPOT_IND[ipt] += V;
dVdZ = 0.5*fC*F2*fA*(-bij*(delta*eta*Zeta1)/(1+Zeta));
dVdr = 0.5*dfCdr*(F1*fR+bij*F2*fA) + 0.5*fC*(F1*dfRdr+bij*F2*dfAdr) + dVdZ*dZdrij;
f3i=rt[j]*dVdr;
_F[ipt]+=f3i;
_F[jpt]-=f3i;
_VIRIAL.addnvv(-1.,f3i,rg[j]);
if (SURFTEN==1 && (curstep%savepropfreq)==1) AddnvvtoPtPn(_SR[jpt],f3i,rg[j],-1.0);
// INFO_Printf(" bij = %e V = %e dVdr = %e f3i=(%e,%e,%e)\n",bij,V,dVdr,f3i.x,f3i.y,f3i.z);
// INFO_Printf(" bij = %e rt[j]=(%e,%e,%e)\n",bij,rt[j].x,rt[j].y,rt[j].z);
/* three body loop */
for(k=0;k<neg;k++)
{
if(k==j) continue; /* k and j are different neighbors */
kpt=list2[k];
if(fixed[kpt]==-1) continue; /* ignore atom if -1 */
/* Forces due to derivatives with respect to Z, then rik */
temp = dVdZ*dZdrik[k];
fZ = rt[k]*temp;
_F[ipt]+=fZ;
_F[kpt]-=fZ;
_VIRIAL.addnvv(-1.,fZ,rg[k]);
if (SURFTEN==1 && (curstep%savepropfreq)==1) AddnvvtoPtPn(_SR[kpt],fZ,rg[k],-1.0);
/* cos(theta_ijk): angle between bond ij and bond ik */
CosTheta=rt[j]*rt[k];
/* Forces due to derivatives with respect to cosTheta */
temp = dVdZ*dZdCosTheta[k];
fTheta = (rt[j]*CosTheta-rt[k])*(-temp/rr[j]);
_F[ipt]+=fTheta;
_F[jpt]-=fTheta;
_VIRIAL.addnvv(-1.,fTheta,rg[j]);
if (SURFTEN==1 && (curstep%savepropfreq)==1) AddnvvtoPtPn(_SR[jpt],fTheta,rg[j],-1.0);
fTheta = (rt[k]*CosTheta-rt[j])*(-temp/rr[k]);
_F[ipt]+=fTheta;
_F[kpt]-=fTheta;
_VIRIAL.addnvv(-1.,fTheta,rg[k]);
if (SURFTEN==1 && (curstep%savepropfreq)==1) AddnvvtoPtPn(_SR[kpt],fTheta,rg[k],-1.0);
}
}
}
}
void Murty95Frame::potential()
{
murty();
}
#ifdef _TEST
/* Main Program Begins */
class Murty95Frame sim;
/* The main program is defined here */
#include "main.cpp"
#endif//_TEST
| [
"xiaohanzhang.cmu@gmail.com"
] | xiaohanzhang.cmu@gmail.com |
f5e38a57b119e9a66900e784e9daa8c336e1712a | 63e96875d8b6739872056596e0d1aac6f88d3360 | /GrazingPatterns.cpp | f0f80c13dd21bfa545b465259284a4d7729c0eb8 | [] | no_license | dougyouyang/Grazing-Patterns-USACO | 16e8d3fcaebf159012e6708e42f107e7893bd778 | 1bea2a1343b2c4bdb21cffc160494903214bf61e | refs/heads/master | 2021-05-08T09:25:01.247160 | 2017-10-17T04:37:05 | 2017-10-17T04:37:05 | 107,218,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,517 | cpp | // Copyright © 2017 Dougy Ouyang. All rights reserved.
#include <iostream>
using namespace std;
int mat[10][10], total=0;
void DFS(int brow, int bcol, int mrow, int mcol)
{
//base case
if(mat[brow][bcol]==0 || mat[mrow][mcol]==0)
return;
if(brow==mrow && bcol==mcol){
int eat=0;
for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
if(mat[i][j]==1)
eat++;
}
}
if(eat<=1)
total++;
return;
}
//ini
mat[brow][bcol]=0, mat[mrow][mcol]=0;
DFS(brow+1, bcol, mrow+1, mcol);
DFS(brow-1, bcol, mrow+1, mcol);
DFS(brow, bcol+1, mrow+1, mcol);
DFS(brow, bcol-1, mrow+1, mcol);
DFS(brow+1, bcol, mrow-1, mcol);
DFS(brow-1, bcol, mrow-1, mcol);
DFS(brow, bcol+1, mrow-1, mcol);
DFS(brow, bcol-1, mrow-1, mcol);
DFS(brow+1, bcol, mrow, mcol+1);
DFS(brow-1, bcol, mrow, mcol+1);
DFS(brow, bcol+1, mrow, mcol+1);
DFS(brow, bcol-1, mrow, mcol+1);
DFS(brow+1, bcol, mrow, mcol-1);
DFS(brow-1, bcol, mrow, mcol-1);
DFS(brow, bcol+1, mrow, mcol-1);
DFS(brow, bcol-1, mrow, mcol-1);
mat[brow][bcol]=1, mat[mrow][mcol]=1;
}
int main()
{
int k, lox, loy;
int i, j;
for(i=1;i<=5;i++)
for(j=1;j<=5;j++)
mat[i][j]=1;
cin >> k;
for(i=0;i<k;i++){
cin >> lox >> loy;
mat[lox][loy]=0;
}
DFS(1, 1, 5, 5);
cout << total << endl;
return 0;
}
| [
"noreply@github.com"
] | dougyouyang.noreply@github.com |
0a2d0c2057b402d1c28069e126e3e033aa15a34e | a4008ca31634dcafe53137267d7b2df4572605bc | /reco/HitClustering/STClusterizerCurveTrack.hh | 0ef04685a69e412eb0b07515292e0903f7de6ac8 | [] | no_license | SpiRIT-Collaboration/SpiRITROOT | 416f766d59110b23f14b3f8c5647c649d5c42efb | 0f5154b75e5db0d736373386e1481caa7c2ff03c | refs/heads/develop | 2023-03-10T15:25:16.906623 | 2022-01-21T17:42:01 | 2022-01-21T17:42:01 | 19,332,445 | 6 | 3 | null | 2018-12-19T09:04:44 | 2014-05-01T01:20:47 | C++ | UTF-8 | C++ | false | false | 873 | hh | #ifndef STCLUSTERIZERCURVETRACK
#define STCLUSTERIZERCURVETRACK
#include "STClusterizer.hh"
#include "STCurveTrackFitter.hh"
#include "STCircleFitter.hh"
#include "STRiemannFitter.hh"
#include "STHitCluster.hh"
#include "TMath.h"
#include "TVector3.h"
class STClusterizerCurveTrack : public STClusterizer
{
public:
STClusterizerCurveTrack();
~STClusterizerCurveTrack();
void AnalyzeTrack(TClonesArray* trackArray, STEvent* eventOut);
void AnalyzeTrack(TClonesArray *trackArray, TClonesArray *clusterArray);
void AnalyzeSingleTrack(STCurveTrack *track, TClonesArray *clusterArray);
private:
STHitCluster* NewCluster(STHit* hit, TClonesArray *array);
TClonesArray *fClusterArray;
STCurveTrackFitter *fTrackFitter;
STRiemannFitter *fRiemannFitter;
STCurveTrack *fTracker;
ClassDef(STClusterizerCurveTrack, 1)
};
#endif
| [
"phyjics@gmail.com"
] | phyjics@gmail.com |
da2502bb64ee7e00ecef996437758ada18e57a5b | 5a60d60fca2c2b8b44d602aca7016afb625bc628 | /aws-cpp-sdk-appconfig/source/model/GetConfigurationProfileResult.cpp | 9018b52076701d7d7635dbe68984d0863b5ee42a | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | yuatpocketgems/aws-sdk-cpp | afaa0bb91b75082b63236cfc0126225c12771ed0 | a0dcbc69c6000577ff0e8171de998ccdc2159c88 | refs/heads/master | 2023-01-23T10:03:50.077672 | 2023-01-04T22:42:53 | 2023-01-04T22:42:53 | 134,497,260 | 0 | 1 | null | 2018-05-23T01:47:14 | 2018-05-23T01:47:14 | null | UTF-8 | C++ | false | false | 1,964 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/appconfig/model/GetConfigurationProfileResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::AppConfig::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
GetConfigurationProfileResult::GetConfigurationProfileResult()
{
}
GetConfigurationProfileResult::GetConfigurationProfileResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
GetConfigurationProfileResult& GetConfigurationProfileResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("ApplicationId"))
{
m_applicationId = jsonValue.GetString("ApplicationId");
}
if(jsonValue.ValueExists("Id"))
{
m_id = jsonValue.GetString("Id");
}
if(jsonValue.ValueExists("Name"))
{
m_name = jsonValue.GetString("Name");
}
if(jsonValue.ValueExists("Description"))
{
m_description = jsonValue.GetString("Description");
}
if(jsonValue.ValueExists("LocationUri"))
{
m_locationUri = jsonValue.GetString("LocationUri");
}
if(jsonValue.ValueExists("RetrievalRoleArn"))
{
m_retrievalRoleArn = jsonValue.GetString("RetrievalRoleArn");
}
if(jsonValue.ValueExists("Validators"))
{
Aws::Utils::Array<JsonView> validatorsJsonList = jsonValue.GetArray("Validators");
for(unsigned validatorsIndex = 0; validatorsIndex < validatorsJsonList.GetLength(); ++validatorsIndex)
{
m_validators.push_back(validatorsJsonList[validatorsIndex].AsObject());
}
}
if(jsonValue.ValueExists("Type"))
{
m_type = jsonValue.GetString("Type");
}
return *this;
}
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
1b52bf418d1955ccd48a7f45b47061b22b5602d7 | ac56437cd07aa7b5dfad305d0ee130ab45611cb4 | /labs/laba_4_3.cpp | dfb855edd867fa239c82792a679b3909a95f97c7 | [] | no_license | dreamiquel/kashtanov.labs | 58e8e2f32b36e487031ea6a951cf0ea683c3e9e4 | 9055556a55a5c7ea6beff38b315a52912658d54b | refs/heads/main | 2023-06-03T16:11:26.266501 | 2021-06-20T16:28:21 | 2021-06-20T16:28:21 | 376,084,737 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,017 | cpp | // laba 4.3.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
//
#include <iostream>
#include <cmath>
#include <vector>
#include <string>
using namespace std;
int main()
{
int n = 1;
long double a, sum = 1, f = 1, eps;
unsigned long long int an = 1;
cout << "Enter epsilon: ";
cin >> eps;
while (an >= eps)
{
f *= n;
sum += an;
an = pow(10, n)/ f;
n++;
}
cout << "Summa = " << sum << endl;
cout << endl;
}
// Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки"
// Отладка программы: F5 или меню "Отладка" > "Запустить отладку"
// Советы по началу работы
// 1. В окне обозревателя решений можно добавлять файлы и управлять ими.
// 2. В окне Team Explorer можно подключиться к системе управления версиями.
// 3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения.
// 4. В окне "Список ошибок" можно просматривать ошибки.
// 5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода.
// 6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
| [
"noreply@github.com"
] | dreamiquel.noreply@github.com |
f29ac0e4bed17dfe8db9f25ded80d9695fa59af1 | a4d518ddd989bad8b2dde807b2d3111eff00e356 | /Project/libs/StarEngine/include/Scenes/SlideScene.h | d969a9191dde7875e3abecc76b36a2cd2516adcc | [
"MIT"
] | permissive | GlenDC/StarEngine-downloads | 84269ea6ada832a82af4022a5dbaa1475fdc8924 | b52a065b76df9b41327d20cde133ebad5e65adcd | refs/heads/master | 2021-01-23T17:31:00.220517 | 2013-12-15T22:46:24 | 2013-12-15T22:46:24 | 15,191,686 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,595 | h | #pragma once
#include "../defines.h"
#include "../Logger.h"
#include "../Context.h"
#include "../Scenes/BaseScene.h"
#include "../Graphics/UI/Index.h"
namespace star
{
class SlideScene : public BaseScene
{
public:
SlideScene(const tstring& name, const tstring & nextScene);
virtual ~SlideScene();
virtual void CreateObjects();
virtual void AfterInitializedObjects();
virtual void OnActivate();
virtual void OnDeactivate();
virtual void Update(const star::Context& context);
virtual void Draw();
int16 AddSlide(
const tstring & file,
float32 active_time
);
int16 AddSlide(
const tstring & file,
float32 active_time,
const Color & fade_in_start_color,
const Color & fade_in_end_color,
float32 fade_in_time
);
int16 AddSlide(
const tstring & file,
float32 active_time,
const Color & fade_in_start_color,
const Color & fade_in_end_color,
float32 fade_in_time,
const Color & fade_out_start_color,
const Color & fade_out_end_color,
float32 fade_out_time
);
void SetKeyboardInputEnabled(bool enable);
void SetFingerInputEnabled(bool enable);
protected:
star::UIDock * m_pSlideMenu;
std::vector<tstring> m_Slides;
private:
void GoNextSlide();
uint8 m_CurrentSlide;
float32 m_TotalTime;
tstring m_NextScene;
bool m_AllowKeyboardInput,
m_AllowFingerInput;
SlideScene(const SlideScene& t);
SlideScene(SlideScene&& t);
SlideScene& operator=(const SlideScene& t);
SlideScene& operator=(SlideScene&& t);
};
}
| [
"decauwsemaecker.glen@gmail.com"
] | decauwsemaecker.glen@gmail.com |
f6858cf32b9dac91e3e30c3b2a4dadccb088455e | b5e00c7392791f982cc5a26d588d5ffc5cf9eb74 | /Breakout/Ball.cpp | 14b84c1b5090a68ef918ef9c6d703b1793f7c202 | [] | no_license | Gareton/OpenGL_Learning | 24643a4a2066158af16ed891dd54067fae8f8384 | eeb8086af2006e42a684c3f5a6e429963d1ffb55 | refs/heads/master | 2020-06-16T01:50:03.271263 | 2019-07-20T14:02:12 | 2019-07-20T14:02:12 | 195,448,194 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,029 | cpp | #include "Ball.h"
#include <glad/glad.h>
Ball::Ball()
: GameObject(), Radius(12.5f), Stuck(true) { }
Ball::Ball(glm::vec2 pos, GLfloat radius, glm::vec2 velocity, Texture2D sprite)
: GameObject(pos, glm::vec2(radius * 2, radius * 2), sprite, glm::vec3(1.0f), velocity), Radius(radius), Stuck(true), PassThrough(false), Sticky(false) { }
glm::vec2 Ball::Move(GLfloat dt, GLuint window_width)
{
if (!Stuck)
{
Position += Velocity * dt;
if (this->Position.x <= 0.0f)
{
this->Velocity.x = -this->Velocity.x;
this->Position.x = 0.0f;
}
else if (this->Position.x + this->Size.x >= window_width)
{
this->Velocity.x = -this->Velocity.x;
this->Position.x = window_width - this->Size.x;
}
if (this->Position.y <= 0.0f)
{
this->Velocity.y = -this->Velocity.y;
this->Position.y = 0.0f;
}
}
return Position;
}
void Ball::Reset(glm::vec2 position, glm::vec2 velocity)
{
this->Position = position;
this->Velocity = velocity;
this->Stuck = true;
} | [
"fghftftrdrrdrdrdr65656hj56h@gmail.com"
] | fghftftrdrrdrdrdr65656hj56h@gmail.com |
738cbb87b3f5b277d6ac7b6f1c2acc100305dede | 9f010ed20064f81fb6cb84b4bff7df848a987488 | /A1090/main.cpp | 32b09725432001f77df83da83e5acccf3b03ed8b | [] | no_license | specular-zxy/PAT-code | cd847db9c25c5a753028729950691163e8680c30 | d49b2557ae6105f13a8dc04d70bbaedd4951b044 | refs/heads/master | 2021-05-27T12:57:28.304496 | 2020-06-28T13:43:52 | 2020-06-28T13:43:52 | 254,268,749 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 857 | cpp | #include <cstdio>
#include <cmath>
#include <vector>
using namespace std;
const int maxn = 100010;
vector<int> child[maxn];
double p, r;
int n, maxDepth = 0, num = 0;
void DFS(int index, int depth) {
if (child[index].size() == 0) {
if (depth > maxDepth) {
maxDepth = depth;
num = 1;
} else if (depth == maxDepth) {
num++;
}
return;
}
for (int i = 0; i < child[index].size(); i++) {
DFS(child[index][i], depth + 1);
}
}
int main() {
int father, root;
scanf("%d%lf%lf", &n, &p, &r);
r /= 100;
for (int i = 0; i < n; i++) {
scanf("%d", &father);
if (father != -1) {
child[father].push_back(i);
} else {
root = i;
}
}
DFS(root, 0);
printf("%.2f %d\n", p * pow(1 + r, maxDepth), num);
} | [
"zhouxinyan33@gmail.com"
] | zhouxinyan33@gmail.com |
f437506ef4b516b0bc805de5ed43b1d527332389 | ce920bd897afa6135f3f1a3c777416eb390555cb | /include/sqlite.hh | 3729743518c20bf55abec57b1cd2a69c12937e61 | [] | no_license | ivankp/server_old_1 | 64095f03ed58c8599ebf1d5e9709a657a4f70e2e | fa7e4bb53751190057aabe571b8bfb7dbb1e8f03 | refs/heads/master | 2023-05-01T00:08:17.345373 | 2021-05-18T17:46:30 | 2021-05-18T17:46:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,305 | hh | #ifndef IVANP_SQLITE_HH
#define IVANP_SQLITE_HH
#include <iostream>
#include <iomanip>
#include <concepts>
#include "sqlite3/sqlite3.h"
// https://sqlite.org/cintro.html
#include "base64.hh"
#include "error.hh"
#define THROW_SQLITE(...) ERROR(__VA_ARGS__,": ",errmsg())
class sqlite {
sqlite3* db = nullptr;
public:
const char* errmsg() const noexcept { return sqlite3_errmsg(db); }
sqlite(const char* filename) {
if (sqlite3_open(filename,&db) != SQLITE_OK)
THROW_SQLITE("sqlite3_open()");
}
~sqlite() {
if (sqlite3_close(db) != SQLITE_OK)
std::cerr << IVANP_ERROR_PREF "sqlite3_close()"
<< errmsg() << std::endl;
}
sqlite(const sqlite&) = delete;
sqlite& operator=(const sqlite&) = delete;
sqlite& operator=(sqlite&& o) noexcept {
std::swap(db,o.db);
return *this;
}
sqlite(sqlite&& o) noexcept { std::swap(db,o.db); }
sqlite3* operator+() noexcept { return db; }
const sqlite3* operator+() const noexcept { return db; }
class value {
sqlite3_value* p = nullptr;
public:
value() noexcept = default;
value(sqlite3_value* p) noexcept: p(sqlite3_value_dup(p)) { }
~value() { sqlite3_value_free(p); }
value(const value& o) noexcept: value(o.p) { }
value(value&& o) noexcept { std::swap(p,o.p); }
value& operator=(const value& o) noexcept {
p = sqlite3_value_dup(o.p);
return *this;
}
value& operator=(value&& o) noexcept {
std::swap(p,o.p);
return *this;
}
sqlite3_value* operator+() noexcept { return p; }
const sqlite3_value* operator+() const noexcept { return p; }
int type() const noexcept { return sqlite3_value_type(p); }
int bytes() const noexcept { return sqlite3_value_bytes(p); }
int as_int() const noexcept { return sqlite3_value_int(p); }
sqlite3_int64 as_int64() const noexcept { return sqlite3_value_int64(p); }
double as_double() const noexcept { return sqlite3_value_double(p); }
const void* as_blob() const noexcept { return sqlite3_value_blob(p); }
const char* as_text() const noexcept {
return reinterpret_cast<const char*>(sqlite3_value_text(p));
}
template <typename T> requires std::integral<T>
T as() const noexcept {
if constexpr (sizeof(T) < 8) return as_int();
else return as_int64();
}
template <typename T> requires std::floating_point<T>
T as() const noexcept { return as_double(); }
template <typename T> requires std::constructible_from<T,const char*>
T as() const noexcept { return T(as_text()); }
template <typename T> requires std::same_as<T,const void*>
T as() const noexcept { return as_blob(); }
bool operator==(const value& o) const noexcept {
const auto len = bytes();
return (o.bytes() == len) && !memcmp(as_blob(),o.as_blob(),len);
}
bool operator<(const value& o) const noexcept {
const auto len = bytes();
const auto len_o = o.bytes();
auto cmp = memcmp(as_blob(),o.as_blob(),(len < len_o ? len : len_o));
return cmp ? (cmp < 0) : (len < len_o);
}
bool operator!=(const value& o) const noexcept { return !((*this) == o); }
bool operator!() const noexcept {
return !p || type() == SQLITE_NULL;
}
};
class stmt {
sqlite3_stmt *p = nullptr;
public:
sqlite3* db_handle() const noexcept { return sqlite3_db_handle(p); }
const char* errmsg() const noexcept { return sqlite3_errmsg(db_handle()); }
stmt(sqlite3 *db, const char* sql, bool persist=false) {
if (sqlite3_prepare_v3(
db, sql, -1,
persist ? SQLITE_PREPARE_PERSISTENT : 0,
&p, nullptr
) != SQLITE_OK) THROW_SQLITE("sqlite3_prepare_v3()");
}
stmt(sqlite3 *db, std::string_view sql, bool persist=false) {
if (sqlite3_prepare_v3(
db, sql.data(), sql.size(),
persist ? SQLITE_PREPARE_PERSISTENT : 0,
&p, nullptr
) != SQLITE_OK) THROW_SQLITE("sqlite3_prepare_v3()");
}
~stmt() {
if (sqlite3_finalize(p) != SQLITE_OK)
std::cerr << IVANP_ERROR_PREF "sqlite3_finalize()"
<< errmsg() << std::endl;
}
stmt(const stmt&) = delete;
stmt& operator=(const stmt&) = delete;
stmt& operator=(stmt&& o) noexcept {
std::swap(p,o.p);
return *this;
}
stmt(stmt&& o) noexcept { std::swap(p,o.p); }
sqlite3_stmt* operator+() noexcept { return p; }
const sqlite3_stmt* operator+() const noexcept { return p; }
bool step() {
switch (sqlite3_step(p)) {
case SQLITE_ROW: return true;
case SQLITE_DONE: return false;
default: THROW_SQLITE("sqlite3_step()");
}
}
stmt& reset() {
if (sqlite3_reset(p) != SQLITE_OK)
THROW_SQLITE("sqlite3_reset()");
return *this;
}
// bind ---------------------------------------------------------
stmt& bind(int i, std::floating_point auto x) {
if (sqlite3_bind_double(p, i, x) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_double()");
return *this;
}
template <std::integral T>
stmt& bind(int i, T x) {
if constexpr (sizeof(T) < 8) {
if (sqlite3_bind_int(p, i, x) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_int()");
} else {
if (sqlite3_bind_int64(p, i, x) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_int64()");
}
return *this;
}
stmt& bind(int i) {
if (sqlite3_bind_null(p, i) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_null()");
return *this;
}
stmt& bind(int i, std::nullptr_t) {
if (sqlite3_bind_null(p, i) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_null()");
return *this;
}
stmt& bind(int i, const char* x, int n=-1, bool trans=true) {
if (sqlite3_bind_text(p, i, x, n,
trans ? SQLITE_TRANSIENT : SQLITE_STATIC
) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_text()");
return *this;
}
stmt& bind(int i, std::string_view x, bool trans=true) {
if (sqlite3_bind_text(p, i, x.data(), x.size(),
trans ? SQLITE_TRANSIENT : SQLITE_STATIC
) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_text()");
return *this;
}
stmt& bind(int i, const void* x, int n, bool trans=true) {
if (sqlite3_bind_blob(p, i, x, n,
trans ? SQLITE_TRANSIENT : SQLITE_STATIC
) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_blob()");
return *this;
}
stmt& bind(int i, std::nullptr_t, int n) {
if (sqlite3_bind_zeroblob(p, i, n) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_zeroblob()");
return *this;
}
stmt& bind(int i, const value& x) {
if (sqlite3_bind_value(p, i, +x) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_value()");
return *this;
}
template <typename... T>
stmt& bind_all(T&&... x) {
int i = 0;
return (bind(++i,std::forward<T>(x)), ...);
}
// column -------------------------------------------------------
int column_count() noexcept {
return sqlite3_column_count(p);
}
double column_double(int i) noexcept {
return sqlite3_column_double(p, i);
}
int column_int(int i) noexcept {
return sqlite3_column_int(p, i);
}
sqlite3_int64 column_int64(int i) noexcept {
return sqlite3_column_int64(p, i);
}
const char* column_text(int i) noexcept {
return reinterpret_cast<const char*>(sqlite3_column_text(p, i));
}
const void* column_blob(int i) noexcept {
return sqlite3_column_blob(p, i);
}
value column_value(int i) noexcept {
return sqlite3_column_value(p, i);
}
int column_bytes(int i) noexcept {
return sqlite3_column_bytes(p, i);
}
int column_type(int i) noexcept {
// SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL
return sqlite3_column_type(p, i);
}
const char* column_name(int i) noexcept {
return sqlite3_column_name(p, i);
}
template <typename T> requires std::integral<T>
T column(int i) noexcept {
if constexpr (sizeof(T) < 8) return column_int(i);
else return column_int64(i);
}
template <typename T> requires std::floating_point<T>
T column(int i) noexcept { return column_double(i); }
template <typename T> requires std::constructible_from<T,const char*>
T column(int i) noexcept { return T(column_text(i)); }
template <typename T> requires std::same_as<T,const void*>
T column(int i) noexcept { return column_blob(i); }
std::string json() {
std::stringstream ss;
ss << '[';
for (int i=0, n=column_count(); i<n; ++i) {
if (i) ss << ',';
switch (column_type(i)) {
case SQLITE_INTEGER:
ss << column_int(i);
break;
case SQLITE_FLOAT:
ss << column_double(i);
break;
case SQLITE_TEXT:
ss << std::quoted(column_text(i));
break;
case SQLITE_BLOB: {
ss << '"' << base64_encode(
reinterpret_cast<const char*>(column_blob(i)),
column_bytes(i)
) << '"';
}; break;
case SQLITE_NULL:
ss << "null";
break;
}
}
ss << ']';
return std::move(ss).str();
}
};
stmt prepare(auto sql, bool persist=false) { return { db, sql, persist }; }
template <typename F>
sqlite& exec(const char* sql, F&& f) {
char* err;
if (sqlite3_exec(db,sql,
+[](
void* arg, // 4th argument of sqlite3_exec()
int ncol, // number of columns
char** row, // pointers to strings obtained as if from sqlite3_column_text()
char** cols_names // names of columns
) -> int {
(*reinterpret_cast<F*>(arg))(ncol,row,cols_names);
return 0;
}, reinterpret_cast<void*>(&f), &err
) != SQLITE_OK) ERROR("sqlite3_exec(): ",err);
return *this;
}
sqlite& exec(const char* sql) {
char* err;
if (sqlite3_exec(db,sql,nullptr,nullptr,&err) != SQLITE_OK)
ERROR("sqlite3_exec(): ",err);
return *this;
}
template <typename... F> requires (sizeof...(F)<2)
sqlite& operator()(const char* sql, F&&... f) {
return exec(sql,std::forward<F>(f)...);
}
};
#endif
| [
"ivan.pogrebnyak@gmail.com"
] | ivan.pogrebnyak@gmail.com |
7948a3902ef01507cd163f841c114927d960fdd7 | 117aaf186609e48230bff9f4f4e96546d3484963 | /questions/48534529-1/main.cpp | 74d870d60db7287710a8d015971c1023e39ecd7f | [
"MIT"
] | permissive | eyllanesc/stackoverflow | 8d1c4b075e578496ea8deecbb78ef0e08bcc092e | db738fbe10e8573b324d1f86e9add314f02c884d | refs/heads/master | 2022-08-19T22:23:34.697232 | 2022-08-10T20:59:17 | 2022-08-10T20:59:17 | 76,124,222 | 355 | 433 | MIT | 2022-08-10T20:59:18 | 2016-12-10T16:29:34 | C++ | UTF-8 | C++ | false | false | 548 | cpp | #include "filemodel.h"
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QTimer>
#include <QDebug>
int main(int argc, char *argv[]) {
#if defined(Q_OS_WIN)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
qmlRegisterType<FileModel>("com.eyllanesc.filemodel", 1, 0, "FileModel");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
| [
"e.yllanescucho@gmail.com"
] | e.yllanescucho@gmail.com |
100661eddd0b8fec35f42efd387a379d459f61ac | dd1e33b7a6abe5e991b0f7f99bbcb06ffc8b36d1 | /Source/PresetTable.cpp | 6bc3e871ed0a62a9195dff25234c7b785fd74494 | [] | no_license | n-wave/Akateko | 45a1bb7a26d925510a00928e905816c696f1f318 | f227a8f47c497bf33dabac0ab139a9740fc5073c | refs/heads/master | 2020-03-23T14:54:32.947581 | 2018-06-29T14:45:06 | 2018-06-29T14:45:06 | 141,707,326 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,581 | cpp | /*
==============================================================================
PresetTable.cpp
Created: 27 Apr 2018 10:06:13pm
Author: mario
==============================================================================
*/
#include "PresetTable.h"
#include <algorithm>
using std::vector;
using std::sort;
using akateko::PresetRow;
PresetTable::PresetTable(vector<PresetRow> presets) :
numRows(16),
cellWidth(0.f),
cellHeight(0.f),
activeRow(-1),
currentPresets(presets),
outlineColour(Colour(0xFF70C099)),
highLightColour(Colour(0x6F20AA9A))
{
if(!currentPresets.empty()){
numRows = currentPresets.size();
}
sortPresets(nameSortAscending);
setColour(backgroundColourId, Colours::black);
}
PresetTable::~PresetTable(){
}
void PresetTable::setLookAndFeel(LookAndFeel *laf){
getHeader().setLookAndFeel(laf);
}
void PresetTable::initialiseHeader(float width, float height){
cellWidth = width*0.3333;
cellHeight = height*0.085;
getHeader().addColumn("Preset", 1, cellWidth, cellWidth, -1, TableHeaderComponent::visible, -1);
getHeader().addColumn("Category", 2, cellWidth, cellWidth, -1, TableHeaderComponent::visible, -1 );
getHeader().addColumn("Author", 3, cellWidth, cellWidth, -1, TableHeaderComponent::visible, -1);
numColums = getHeader().getNumColumns(false);
getHeader().setStretchToFitActive(true);
getHeader().setPopupMenuActive(false);
getViewport()->setScrollBarsShown(false,false,true,false); //enable mouse scrolling for now
setHeaderHeight(cellHeight);
setRowHeight(cellHeight);
setModel(this);
}
int PresetTable::getNumRows(){
return numRows;
}
void PresetTable::paintRowBackground(Graphics &g, int rowNumber, int width, int height, bool rowIsSelected){
if(rowNumber < numRows){
Colour colour = Colours::black;
if(rowIsSelected){
colour = (highLightColour);
}
g.fillAll( colour );
// draw the cell bottom divider beween rows
g.setColour( Colours::white);
g.drawLine( 0, height, width, height );
}
}
void PresetTable::paintCell(Graphics &g, int rowNumber, int columnId, int width, int height, bool rowIsSelected){
g.setColour(outlineColour);
g.fillRect(0, height-1, width, 1);
String tmpCell;
if(rowNumber < currentPresets.size()){
switch(columnId){
case 1:
tmpCell = currentPresets[rowNumber].name;
g.fillRect(0, 0, 1, height);
g.fillRect(width-1, 0, 1, height);
break;
case 2:
tmpCell = currentPresets[rowNumber].category;
g.fillRect(width-1, 0, 1, height);
break;
case 3:
tmpCell = currentPresets[rowNumber].author;
g.fillRect(width-1, 0, 1, height);
break;
}
}
g.drawText(tmpCell, 0, 0, width, height, Justification::centred);
}
void PresetTable::cellClicked(int rowNumber, int columnId, const MouseEvent &){
activeRow = rowNumber;
}
// Todo if the category or Author colum is double clicked
// Prompt the user with a window for changing
// the category or Author
void PresetTable::cellDoubleClicked(int rowNumber, int columnId, const MouseEvent &){
if(rowNumber < currentPresets.size()){
cellPosition = getCellPosition(columnId,rowNumber, true);
activeRow = rowNumber;
dClickRow = rowNumber;
dClickCol = columnId;
getParentComponent()->postCommandMessage(requestTextEditor);
}
}
void PresetTable::setCurrentPresets(std::vector<akateko::PresetRow> presets){
currentPresets.clear();
currentPresets = vector<PresetRow>(presets);
numRows = currentPresets.size();
}
void PresetTable::changeName(int rowNumber, const String name){
if(rowNumber < currentPresets.size()){
currentPresets[rowNumber].name = name;
}
}
void PresetTable::changeAuthor(int rowNumber, const String author){
if(rowNumber < currentPresets.size()){
currentPresets[rowNumber].author = author;
}
}
void PresetTable::changeCategory(int rowNumber, const String category){
if(rowNumber < currentPresets.size()){
currentPresets[rowNumber].category = category;
}
}
Rectangle<int> PresetTable::getClickedCellPosition(){
return cellPosition;
}
int PresetTable::getActiveRow(){
return activeRow;
}
void PresetTable::resetActiveRow(){
activeRow = -1;
}
int PresetTable::getClickedRow(){
return dClickRow;
}
int PresetTable::getClickedColumn(){
return dClickCol;
}
File PresetTable::getFile(int rowNum){
File tmpFile;
if(rowNum < currentPresets.size()){
tmpFile = currentPresets[rowNum].file;
}
return tmpFile;
}
String PresetTable::getName(int rowNum){
String tmpName = String();
if(rowNum < currentPresets.size()){
tmpName = currentPresets[rowNum].name;
}
return tmpName;
}
bool PresetTable::getPresetRow(int rowNum, PresetRow &result){
if(rowNum < currentPresets.size()){
result.file = currentPresets[rowNum].file;
result.name = currentPresets[rowNum].name;
result.category = currentPresets[rowNum].category;
result.author = currentPresets[rowNum].author;
return true;
}
return false;
}
void PresetTable::sortPresets(Sort order){
switch(order){
case nameSortAscending:
sort(currentPresets.begin(), currentPresets.end(), &akateko::nameSortAscending);
break;
case nameSortDescending:
sort(currentPresets.begin(), currentPresets.end(), &akateko::nameSortDescending);
break;
case categorySortAscending:
sort(currentPresets.begin(), currentPresets.end(), &akateko::categorySortAscending);
break;
case categorySortDescending:
sort(currentPresets.begin(), currentPresets.end(), &akateko::categorySortDescending);
break;
case authorSortAscending:
sort(currentPresets.begin(), currentPresets.end(), &akateko::authorSortAscending);
break;
case autherSortDescending:
sort(currentPresets.begin(), currentPresets.end(), &akateko::authorSortDescending);
break;
}
}
| [
"info@n-wave.systems"
] | info@n-wave.systems |
3b561abe183d2204efc29915f5292126b9f512d3 | 0b69a011c9ffee099841c140be95ed93c704fb07 | /problemsets/UVA/993.cpp | 4155c9820d3017be5cf27aff3c41814b35a1317e | [
"Apache-2.0"
] | permissive | juarezpaulino/coderemite | 4bd03f4f2780eb6013f07c396ba16aa7dbbceea8 | a4649d3f3a89d234457032d14a6646b3af339ac1 | refs/heads/main | 2023-01-31T11:35:19.779668 | 2020-12-18T01:33:46 | 2020-12-18T01:33:46 | 320,931,351 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 619 | cpp | /**
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
*/
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
int main() {
int T, N;
scanf("%d", &T);
while (T--) {
scanf("%d", &N);
if (N < 10) { printf("%d\n", N); continue; }
int C[10] = {0};
for (int c = 9; c >= 2; c--)
while (N%c == 0) { C[c]++; N /= c; }
if (N != 1) puts("-1");
else {
for (int c = 2; c < 10; c++) for (int i = 0; i < C[c]; i++) putchar(c+'0');
putchar('\n');
}
}
return 0;
}
| [
"juarez.paulino@gmail.com"
] | juarez.paulino@gmail.com |
c96be9f1489b7cbe34c981e06957adea97e23dbd | bb7d3a8c005d2dd14c22651b89ae7ca4ddaad37e | /2/main.cpp | 23537971c4dab2b9b678881287ed8c1caf9e5dcb | [] | no_license | gheome/TemaIP123 | 45e700c7ccea927c4f8253944bae84d7e9aa69f6 | 4d6887e464a98fbb6820cf274fae2c422d9f0f8b | refs/heads/master | 2021-01-11T01:11:24.412464 | 2016-10-16T20:04:21 | 2016-10-16T20:04:21 | 71,071,062 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 303 | cpp | #include <iostream>
using namespace std;
unsigned char sumBinaryFigure(unsigned long long number)
{
int nr;
nr=0;
while(number>0)
{
if (number%2==1)
nr++;
number=number/2;
}
return nr;
}
int main()
{
return sumBinaryFigure(111111222211);
return 0;
}
| [
"alexandru_gh97@yahoo.co.uk"
] | alexandru_gh97@yahoo.co.uk |
8591089edf128a2bb8e9aab1b7f6a1e84d6c704b | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /content/common/input/synthetic_web_input_event_builders.h | 3247d0d243ddf02fe47ecb4e1bfd62c6a02fb2dc | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 3,758 | h | // Copyright 2013 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_COMMON_INPUT_SYNTHETIC_WEB_INPUT_EVENT_BUILDERS_H_
#define CONTENT_COMMON_INPUT_SYNTHETIC_WEB_INPUT_EVENT_BUILDERS_H_
#include "base/time/time.h"
#include "content/common/content_export.h"
#include "third_party/blink/public/platform/web_gesture_event.h"
#include "third_party/blink/public/platform/web_input_event.h"
#include "third_party/blink/public/platform/web_keyboard_event.h"
#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
#include "third_party/blink/public/platform/web_touch_event.h"
// Provides sensible creation of default WebInputEvents for testing purposes.
namespace content {
class CONTENT_EXPORT SyntheticWebMouseEventBuilder {
public:
static blink::WebMouseEvent Build(blink::WebInputEvent::Type type);
static blink::WebMouseEvent Build(
blink::WebInputEvent::Type type,
float window_x,
float window_y,
int modifiers,
blink::WebPointerProperties::PointerType pointer_type =
blink::WebPointerProperties::PointerType::kMouse);
};
class CONTENT_EXPORT SyntheticWebMouseWheelEventBuilder {
public:
static blink::WebMouseWheelEvent Build(
blink::WebMouseWheelEvent::Phase phase);
static blink::WebMouseWheelEvent Build(float x,
float y,
float dx,
float dy,
int modifiers,
bool precise);
static blink::WebMouseWheelEvent Build(float x,
float y,
float global_x,
float global_y,
float dx,
float dy,
int modifiers,
bool precise);
};
class CONTENT_EXPORT SyntheticWebKeyboardEventBuilder {
public:
static blink::WebKeyboardEvent Build(blink::WebInputEvent::Type type);
};
class CONTENT_EXPORT SyntheticWebGestureEventBuilder {
public:
static blink::WebGestureEvent Build(blink::WebInputEvent::Type type,
blink::WebGestureDevice source_device,
int modifiers = 0);
static blink::WebGestureEvent BuildScrollBegin(
float dx_hint,
float dy_hint,
blink::WebGestureDevice source_device,
int pointer_count = 1);
static blink::WebGestureEvent BuildScrollUpdate(
float dx,
float dy,
int modifiers,
blink::WebGestureDevice source_device);
static blink::WebGestureEvent BuildPinchUpdate(
float scale,
float anchor_x,
float anchor_y,
int modifiers,
blink::WebGestureDevice source_device);
static blink::WebGestureEvent BuildFling(
float velocity_x,
float velocity_y,
blink::WebGestureDevice source_device);
};
class CONTENT_EXPORT SyntheticWebTouchEvent : public blink::WebTouchEvent {
public:
SyntheticWebTouchEvent();
// Mark all the points as stationary, and remove any released points.
void ResetPoints();
// Adds an additional point to the touch list, returning the point's index.
int PressPoint(float x, float y);
void MovePoint(int index, float x, float y);
void ReleasePoint(int index);
void CancelPoint(int index);
void SetTimestamp(base::TimeTicks timestamp);
int FirstFreeIndex();
};
} // namespace content
#endif // CONTENT_COMMON_INPUT_SYNTHETIC_WEB_INPUT_EVENT_BUILDERS_H_
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
31214f42b2431a53de5e9505d1dd105c9b7f1a49 | f3ee233dc76c097134931f4988b1b5c94ce6879e | /WeatherStation_CPP/Src/cpp_Light_Sensor.cpp | 5faf3f5b9c8ecdc28aa2d66ffc28099f9648fa6e | [] | no_license | mitea1/WeatherStation_Cpp | d5ee59799718da080779ec5e8acb6c425d42f631 | 47ae8995a41c9179f36e7d1b5c056e4ab9fe9a20 | refs/heads/master | 2016-09-12T10:55:39.837159 | 2016-04-29T22:48:03 | 2016-04-29T22:48:03 | 56,344,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 885 | cpp | /*
* Light_Sensor_CPP.cpp
*
* Created on: Apr 20, 2016
* Author: Simon
*/
/*----- Header-Files -------------------------------------------------------*/
#include "cpp_Light_Sensor.hpp"
/*----- Macros -------------------------------------------------------------*/
/*----- Data types ---------------------------------------------------------*/
/*----- Data ---------------------------------------------------------------*/
/*----- Implementation -----------------------------------------------------*/
/**
* @brief Constructor for Light_Sensor class
*/
Light_Sensor::Light_Sensor(){
LIGHT_SENSOR_init();
}
/**
* @brief Destructor for Light_Sensor class
*/
Light_Sensor::~Light_Sensor(){
}
/**
* @brief Gets Lux form Light Sensor
* @return Brightness in Lux
*/
double Light_Sensor::getLux(){
return LIGHT_SENSOR_getLux();
}
| [
"bolzs2@bfh.ch"
] | bolzs2@bfh.ch |
15f854947c9db5775945a5b4426165166e010e8e | b1708eb6995a2bdfc22cee18d2897bd5d8e1bc50 | /x11hash.cc | 789765812311ef50c949b1dc54d3200a3e60bc3f | [] | no_license | n-johnson/node-x11-hash-algo | 6351f15b9fc906b33149bdaf95d58df72f4237d4 | df95aa1442b09e719ad130e5595e0100d734ca0c | refs/heads/master | 2021-01-16T08:55:00.308080 | 2014-08-11T08:23:35 | 2014-08-11T08:23:35 | 22,830,404 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 960 | cc | #include <node.h>
#include <node_buffer.h>
#include <v8.h>
#include <stdint.h>
extern "C" {
#include "x11.h"
}
using namespace node;
using namespace v8;
Handle<Value> except(const char* msg) {
return ThrowException(Exception::Error(String::New(msg)));
}
Handle<Value> hash(const Arguments& args) {
HandleScope scope;
if (args.Length() < 1)
return except("You must provide one argument.");
Local<Object> target = args[0]->ToObject();
if(!Buffer::HasInstance(target))
return except("Argument should be a buffer object.");
char * input = Buffer::Data(target);
char output[32];
uint32_t input_len = Buffer::Length(target);
x11_hash(input, output, input_len);
Buffer* buff = Buffer::New(output, 32);
return scope.Close(buff->handle_);
}
void init(Handle<Object> exports) {
exports->Set(String::NewSymbol("hash"), FunctionTemplate::New(hash)->GetFunction());
}
NODE_MODULE(x11, init) | [
"node@njohnson.me"
] | node@njohnson.me |
a1d90bfc62e9c1ddd465f51b592519e18f02aa7d | d9714160fd222bc49ef52a56edb7aeb82a591549 | /bench/lib/exp/scalar/hkth1d6hkth3d4.cpp | f65ed039a55d50f6b0335eed169d5fa9b7365ed9 | [
"MIT"
] | permissive | timocafe/poly | c2fb195a196f68c406fa10130c71e29d90bc125c | 3931892bcd04f9ebfc0fde202db34d50973bc73b | refs/heads/master | 2021-01-13T00:34:32.027241 | 2020-10-02T18:42:03 | 2020-10-02T18:42:03 | 41,051,374 | 0 | 0 | null | 2020-10-02T15:27:08 | 2015-08-19T18:08:26 | C++ | UTF-8 | C++ | false | false | 1,756 | cpp | //
// hkth1d6hkth3d4_test.cpp
//
// Created by Ewart Timothée, 2/3/2016
// Copyright (c) Ewart Timothée. All rights reserved.
//
// This file is generated automatically, do not edit!
// TAG: hkth1d6hkth3d4
// Helper:
// h = Horner, e = Estrin, b = BruteForce
// The number indicates the order for Horner
// e.g. h1h3 indicates a produce of polynomial with Horner order 1 and 3
//
#include <limits>
#include <string.h>
#include <cmath>
#include <iostream>
#include "poly/poly.h"
namespace poly {
inline double sse_floor(double a) {
double b;
#ifdef __x86_64__
asm ("roundsd $1,%1,%0 " :"=x"(b) :"x"(a));
#endif
#ifdef __PPC64__
asm ("frim %0,%1 " :"=d"(b) :"d"(a));
#endif
return b;
}
static inline uint64_t as_uint64(double x) {
uint64_t i;
memcpy(&i,&x,8);
return i;
}
static inline double as_double(uint64_t i) {
double x;
memcpy(&x,&i,8);
return x;
}
double exp(double x){
uint64_t mask1 = (fabs(x) > 700);
mask1 = (mask1-1);
uint64_t mask2 = (x < 700);
mask2 = ~(mask2-1);
uint64_t mask3 = as_uint64(std::numeric_limits<double>::infinity());
const long long int tmp((long long int)sse_floor(1.4426950408889634 * x));
const long long int twok = (1023 + tmp) << 52;
x -= ((double)(tmp))*6.93145751953125E-1;
x -= ((double)(tmp))*1.42860682030941723212E-6;
double y = poly::horner_kth<poly::coeffP6,1>(x)*poly::horner_kth<poly::coeffP4_3,3>(x)* (*(double *)(&twok));
uint64_t n = as_uint64(y);
n &= mask1;
mask3 &= ~mask2;
n |= mask3;
return as_double(n);
}
} //end namespace
| [
"timothee.ewart@epfl.ch"
] | timothee.ewart@epfl.ch |
e2601ab2802eef6f7c83cb1ea5c9f695bdaf69a5 | c7ec870ad42a8ef1b4721e83f636d4533717d8a6 | /src/wallet/wallet.cpp | 0888d381cd941f60083d85980fe08eedb3ca5386 | [
"MIT"
] | permissive | TheRinger/Atlascoin | dcdab93e74e151d62e1efc8f4bb35f3e7b2d72ac | 21f6f2372e841fd3ba89e91086cbd5add3e4ef9b | refs/heads/master | 2020-04-06T22:16:48.957176 | 2018-11-16T07:43:21 | 2018-11-16T07:43:21 | 157,830,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 177,444 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Copyright (c) 2017 The Atlas Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wallet/wallet.h"
#include "base58.h"
#include "checkpoints.h"
#include "chain.h"
#include "wallet/coincontrol.h"
#include "consensus/consensus.h"
#include "consensus/validation.h"
#include "fs.h"
#include "init.h"
#include "key.h"
#include "keystore.h"
#include "validation.h"
#include "net.h"
#include "policy/fees.h"
#include "policy/policy.h"
#include "policy/rbf.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/sign.h"
#include "scheduler.h"
#include "timedata.h"
#include "txmempool.h"
#include "util.h"
#include "ui_interface.h"
#include "utilmoneystr.h"
#include "wallet/fees.h"
#include <assert.h>
#include <boost/algorithm/string/replace.hpp>
#include <boost/thread.hpp>
#include <tinyformat.h>
#include "assets/assets.h"
std::vector<CWalletRef> vpwallets;
/** Transaction fee set by the user */
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
bool fWalletRbf = DEFAULT_WALLET_RBF;
const char * DEFAULT_WALLET_DAT = "wallet.dat";
const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
/**
* Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
* Override with -mintxfee
*/
CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
/**
* If fee estimation does not have enough data to provide estimates, use this fee instead.
* Has no effect if not using fee estimation
* Override with -fallbackfee
*/
CFeeRate CWallet::fallbackFee = CFeeRate(DEFAULT_FALLBACK_FEE);
CFeeRate CWallet::m_discard_rate = CFeeRate(DEFAULT_DISCARD_FEE);
const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
/** @defgroup mapWallet
*
* @{
*/
struct CompareValueOnly
{
bool operator()(const CInputCoin& t1,
const CInputCoin& t2) const
{
return t1.txout.nValue < t2.txout.nValue;
}
};
struct CompareAssetValueOnly
{
bool operator()(const std::pair<CInputCoin, CAmount>& t1,
const std::pair<CInputCoin, CAmount>& t2) const
{
return t1.second < t2.second;
}
};
std::string COutput::ToString() const
{
return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
}
class CAffectedKeysVisitor : public boost::static_visitor<void> {
private:
const CKeyStore &keystore;
std::vector<CKeyID> &vKeys;
public:
CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
void Process(const CScript &script) {
txnouttype type;
std::vector<CTxDestination> vDest;
int nRequired;
if (ExtractDestinations(script, type, vDest, nRequired)) {
for (const CTxDestination &dest : vDest)
boost::apply_visitor(*this, dest);
}
}
void operator()(const CKeyID &keyId) {
if (keystore.HaveKey(keyId))
vKeys.push_back(keyId);
}
void operator()(const CScriptID &scriptId) {
CScript script;
if (keystore.GetCScript(scriptId, script))
Process(script);
}
void operator()(const CNoDestination &none) {}
};
const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
if (it == mapWallet.end())
return nullptr;
return &(it->second);
}
CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, bool internal)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
CKey secret;
// Create new metadata
int64_t nCreationTime = GetTime();
CKeyMetadata metadata(nCreationTime);
// use HD key derivation if HD was enabled during wallet creation
if (IsHDEnabled()) {
DeriveNewChildKey(walletdb, metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
} else {
secret.MakeNewKey(fCompressed);
}
// Compressed public keys were introduced in version 0.6.0
if (fCompressed) {
SetMinVersion(FEATURE_COMPRPUBKEY);
}
CPubKey pubkey = secret.GetPubKey();
assert(secret.VerifyPubKey(pubkey));
mapKeyMetadata[pubkey.GetID()] = metadata;
UpdateTimeFirstKey(nCreationTime);
if (!AddKeyPubKeyWithDB(walletdb, secret, pubkey)) {
throw std::runtime_error(std::string(__func__) + ": AddKey failed");
}
return pubkey;
}
void CWallet::DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal)
{
// for now we use a fixed keypath scheme of m/0'/0'/k
CKey seed; //seed (256bit)
CExtKey masterKey; //hd master key
CExtKey accountKey; //key at m/0'
CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
CExtKey childKey; //key at m/0'/0'/<n>'
// try to get the seed
if (!GetKey(hdChain.seed_id, seed))
throw std::runtime_error(std::string(__func__) + ": seed not found");
masterKey.SetSeed(seed.begin(), seed.size());
// derive m/0'
// use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
// derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
// derive child key at next index, skip keys already known to the wallet
do {
// always derive hardened keys
// childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
// example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
if (internal) {
chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
hdChain.nInternalChainCounter++;
}
else {
chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
hdChain.nExternalChainCounter++;
}
} while (HaveKey(childKey.key.GetPubKey().GetID()));
secret = childKey.key;
metadata.hd_seed_id = hdChain.seed_id;
// update the chain model in the database
if (!walletdb.WriteHDChain(hdChain))
throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
}
bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const CPubKey &pubkey)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
// CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
// which is overridden below. To avoid flushes, the database handle is
// tunneled through to it.
bool needsDB = !pwalletdbEncryption;
if (needsDB) {
pwalletdbEncryption = &walletdb;
}
if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) {
if (needsDB) pwalletdbEncryption = nullptr;
return false;
}
if (needsDB) pwalletdbEncryption = nullptr;
// check if we need to remove from watch-only
CScript script;
script = GetScriptForDestination(pubkey.GetID());
if (HaveWatchOnly(script)) {
RemoveWatchOnly(script);
}
script = GetScriptForRawPubKey(pubkey);
if (HaveWatchOnly(script)) {
RemoveWatchOnly(script);
}
if (!IsCrypted()) {
return walletdb.WriteKey(pubkey,
secret.GetPrivKey(),
mapKeyMetadata[pubkey.GetID()]);
}
return true;
}
bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
{
CWalletDB walletdb(*dbw);
return CWallet::AddKeyPubKeyWithDB(walletdb, secret, pubkey);
}
bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
const std::vector<unsigned char> &vchCryptedSecret)
{
if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
{
LOCK(cs_wallet);
if (pwalletdbEncryption)
return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
else
return CWalletDB(*dbw).WriteCryptedKey(vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
}
}
bool CWallet::LoadKeyMetadata(const CTxDestination& keyID, const CKeyMetadata &meta)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
UpdateTimeFirstKey(meta.nCreateTime);
mapKeyMetadata[keyID] = meta;
return true;
}
bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
}
/**
* Update wallet first key creation time. This should be called whenever keys
* are added to the wallet, with the oldest key creation time.
*/
void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
{
AssertLockHeld(cs_wallet);
if (nCreateTime <= 1) {
// Cannot determine birthday information, so set the wallet birthday to
// the beginning of time.
nTimeFirstKey = 1;
} else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
nTimeFirstKey = nCreateTime;
}
}
bool CWallet::AddCScript(const CScript& redeemScript)
{
if (!CCryptoKeyStore::AddCScript(redeemScript))
return false;
return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
}
bool CWallet::LoadCScript(const CScript& redeemScript)
{
/* A sanity check was added in pull #3843 to avoid adding redeemScripts
* that never can be redeemed. However, old wallets may still contain
* these. Do not add them to the wallet and warn. */
if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
{
std::string strAddr = EncodeDestination(CScriptID(redeemScript));
LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
__func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
return true;
}
return CCryptoKeyStore::AddCScript(redeemScript);
}
bool CWallet::AddWatchOnly(const CScript& dest)
{
if (!CCryptoKeyStore::AddWatchOnly(dest))
return false;
const CKeyMetadata& meta = mapKeyMetadata[CScriptID(dest)];
UpdateTimeFirstKey(meta.nCreateTime);
NotifyWatchonlyChanged(true);
return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
}
bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
{
mapKeyMetadata[CScriptID(dest)].nCreateTime = nCreateTime;
return AddWatchOnly(dest);
}
bool CWallet::RemoveWatchOnly(const CScript &dest)
{
AssertLockHeld(cs_wallet);
if (!CCryptoKeyStore::RemoveWatchOnly(dest))
return false;
if (!HaveWatchOnly())
NotifyWatchonlyChanged(false);
if (!CWalletDB(*dbw).EraseWatchOnly(dest))
return false;
return true;
}
bool CWallet::LoadWatchOnly(const CScript &dest)
{
return CCryptoKeyStore::AddWatchOnly(dest);
}
bool CWallet::Unlock(const SecureString& strWalletPassphrase)
{
CCrypter crypter;
CKeyingMaterial _vMasterKey;
{
LOCK(cs_wallet);
for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
{
if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
continue; // try another master key
if (CCryptoKeyStore::Unlock(_vMasterKey))
return true;
}
}
return false;
}
bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
{
bool fWasLocked = IsLocked();
{
LOCK(cs_wallet);
Lock();
CCrypter crypter;
CKeyingMaterial _vMasterKey;
for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
{
if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
return false;
if (CCryptoKeyStore::Unlock(_vMasterKey))
{
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
if (pMasterKey.second.nDeriveIterations < 25000)
pMasterKey.second.nDeriveIterations = 25000;
LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
return false;
CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
if (fWasLocked)
Lock();
return true;
}
}
}
return false;
}
void CWallet::SetBestChain(const CBlockLocator& loc)
{
CWalletDB walletdb(*dbw);
walletdb.WriteBestBlock(loc);
}
bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
{
LOCK(cs_wallet); // nWalletVersion
if (nWalletVersion >= nVersion)
return true;
// when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
if (fExplicit && nVersion > nWalletMaxVersion)
nVersion = FEATURE_LATEST;
nWalletVersion = nVersion;
if (nVersion > nWalletMaxVersion)
nWalletMaxVersion = nVersion;
{
CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
if (nWalletVersion > 40000)
pwalletdb->WriteMinVersion(nWalletVersion);
if (!pwalletdbIn)
delete pwalletdb;
}
return true;
}
bool CWallet::SetMaxVersion(int nVersion)
{
LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
// cannot downgrade below current version
if (nWalletVersion > nVersion)
return false;
nWalletMaxVersion = nVersion;
return true;
}
std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
{
std::set<uint256> result;
AssertLockHeld(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
if (it == mapWallet.end())
return result;
const CWalletTx& wtx = it->second;
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
for (const CTxIn& txin : wtx.tx->vin)
{
if (mapTxSpends.count(txin.prevout) <= 1)
continue; // No conflict if zero or one spends
range = mapTxSpends.equal_range(txin.prevout);
for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
result.insert(_it->second);
}
return result;
}
bool CWallet::HasWalletSpend(const uint256& txid) const
{
AssertLockHeld(cs_wallet);
auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
return (iter != mapTxSpends.end() && iter->first.hash == txid);
}
void CWallet::Flush(bool shutdown)
{
dbw->Flush(shutdown);
}
void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
{
// We want all the wallet transactions in range to have the same metadata as
// the oldest (smallest nOrderPos).
// So: find smallest nOrderPos:
int nMinOrderPos = std::numeric_limits<int>::max();
const CWalletTx* copyFrom = nullptr;
for (TxSpends::iterator it = range.first; it != range.second; ++it)
{
const uint256& hash = it->second;
int n = mapWallet[hash].nOrderPos;
if (n < nMinOrderPos)
{
nMinOrderPos = n;
copyFrom = &mapWallet[hash];
}
}
// Now copy data from copyFrom to rest:
for (TxSpends::iterator it = range.first; it != range.second; ++it)
{
const uint256& hash = it->second;
CWalletTx* copyTo = &mapWallet[hash];
if (copyFrom == copyTo) continue;
assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
copyTo->mapValue = copyFrom->mapValue;
copyTo->vOrderForm = copyFrom->vOrderForm;
// fTimeReceivedIsTxTime not copied on purpose
// nTimeReceived not copied on purpose
copyTo->nTimeSmart = copyFrom->nTimeSmart;
copyTo->fFromMe = copyFrom->fFromMe;
copyTo->strFromAccount = copyFrom->strFromAccount;
// nOrderPos not copied on purpose
// cached members not copied on purpose
}
}
/**
* Outpoint is spent if any non-conflicted transaction
* spends it:
*/
bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
{
const COutPoint outpoint(hash, n);
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
range = mapTxSpends.equal_range(outpoint);
for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
{
const uint256& wtxid = it->second;
std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
if (mit != mapWallet.end()) {
int depth = mit->second.GetDepthInMainChain();
if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
return true; // Spent
}
}
return false;
}
void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
{
mapTxSpends.insert(std::make_pair(outpoint, wtxid));
std::pair<TxSpends::iterator, TxSpends::iterator> range;
range = mapTxSpends.equal_range(outpoint);
SyncMetaData(range);
}
void CWallet::AddToSpends(const uint256& wtxid)
{
auto it = mapWallet.find(wtxid);
assert(it != mapWallet.end());
CWalletTx& thisTx = it->second;
if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
return;
for (const CTxIn& txin : thisTx.tx->vin)
AddToSpends(txin.prevout, wtxid);
}
bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
{
if (IsCrypted())
return false;
CKeyingMaterial _vMasterKey;
_vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
CMasterKey kMasterKey;
kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
CCrypter crypter;
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = static_cast<unsigned int>(2500000 / ((double)(GetTimeMillis() - nStartTime)));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
if (kMasterKey.nDeriveIterations < 25000)
kMasterKey.nDeriveIterations = 25000;
LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
return false;
if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
return false;
{
LOCK(cs_wallet);
mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
assert(!pwalletdbEncryption);
pwalletdbEncryption = new CWalletDB(*dbw);
if (!pwalletdbEncryption->TxnBegin()) {
delete pwalletdbEncryption;
pwalletdbEncryption = nullptr;
return false;
}
pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
if (!EncryptKeys(_vMasterKey))
{
pwalletdbEncryption->TxnAbort();
delete pwalletdbEncryption;
// We now probably have half of our keys encrypted in memory, and half not...
// die and let the user reload the unencrypted wallet.
assert(false);
}
// Encryption was introduced in version 0.4.0
SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
if (!pwalletdbEncryption->TxnCommit()) {
delete pwalletdbEncryption;
// We now have keys encrypted in memory, but not on disk...
// die to avoid confusion and let the user reload the unencrypted wallet.
assert(false);
}
delete pwalletdbEncryption;
pwalletdbEncryption = nullptr;
Lock();
Unlock(strWalletPassphrase);
// if we are using HD, replace the HD seed with a new one
if (IsHDEnabled()) {
if (!SetHDSeed(GenerateNewSeed())) {
return false;
}
}
NewKeyPool();
Lock();
// Need to completely rewrite the wallet file; if we don't, bdb might keep
// bits of the unencrypted private key in slack space in the database file.
dbw->Rewrite();
}
NotifyStatusChanged(this);
return true;
}
DBErrors CWallet::ReorderTransactions()
{
LOCK(cs_wallet);
CWalletDB walletdb(*dbw);
// Old wallets didn't have any defined order for transactions
// Probably a bad idea to change the output of this
// First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef std::multimap<int64_t, TxPair > TxItems;
TxItems txByTime;
for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
CWalletTx* wtx = &((*it).second);
txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, nullptr)));
}
std::list<CAccountingEntry> acentries;
walletdb.ListAccountCreditDebit("", acentries);
for (CAccountingEntry& entry : acentries)
{
txByTime.insert(std::make_pair(entry.nTime, TxPair(nullptr, &entry)));
}
nOrderPosNext = 0;
std::vector<int64_t> nOrderPosOffsets;
for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
CAccountingEntry *const pacentry = (*it).second.second;
int64_t& nOrderPos = (pwtx != nullptr) ? pwtx->nOrderPos : pacentry->nOrderPos;
if (nOrderPos == -1)
{
nOrderPos = nOrderPosNext++;
nOrderPosOffsets.push_back(nOrderPos);
if (pwtx)
{
if (!walletdb.WriteTx(*pwtx))
return DB_LOAD_FAIL;
}
else
if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
else
{
int64_t nOrderPosOff = 0;
for (const int64_t& nOffsetStart : nOrderPosOffsets)
{
if (nOrderPos >= nOffsetStart)
++nOrderPosOff;
}
nOrderPos += nOrderPosOff;
nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
if (!nOrderPosOff)
continue;
// Since we're changing the order, write it back
if (pwtx)
{
if (!walletdb.WriteTx(*pwtx))
return DB_LOAD_FAIL;
}
else
if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
}
walletdb.WriteOrderPosNext(nOrderPosNext);
return DB_LOAD_OK;
}
int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
{
AssertLockHeld(cs_wallet); // nOrderPosNext
int64_t nRet = nOrderPosNext++;
if (pwalletdb) {
pwalletdb->WriteOrderPosNext(nOrderPosNext);
} else {
CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
}
return nRet;
}
bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
{
CWalletDB walletdb(*dbw);
if (!walletdb.TxnBegin())
return false;
int64_t nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
AddAccountingEntry(debit, &walletdb);
// Credit
CAccountingEntry credit;
credit.nOrderPos = IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
AddAccountingEntry(credit, &walletdb);
if (!walletdb.TxnCommit())
return false;
return true;
}
bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
{
CWalletDB walletdb(*dbw);
CAccount account;
walletdb.ReadAccount(strAccount, account);
if (!bForceNew) {
if (!account.vchPubKey.IsValid())
bForceNew = true;
else {
// Check if the current key has been used
CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
it != mapWallet.end() && account.vchPubKey.IsValid();
++it)
for (const CTxOut& txout : (*it).second.tx->vout)
if (txout.scriptPubKey == scriptPubKey) {
bForceNew = true;
break;
}
}
}
// Generate a new key
if (bForceNew) {
if (!GetKeyFromPool(account.vchPubKey, false))
return false;
SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
walletdb.WriteAccount(strAccount, account);
}
pubKey = account.vchPubKey;
return true;
}
void CWallet::MarkDirty()
{
{
LOCK(cs_wallet);
for (std::pair<const uint256, CWalletTx>& item : mapWallet)
item.second.MarkDirty();
}
}
bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
{
LOCK(cs_wallet);
auto mi = mapWallet.find(originalHash);
// There is a bug if MarkReplaced is not called on an existing wallet transaction.
assert(mi != mapWallet.end());
CWalletTx& wtx = (*mi).second;
// Ensure for now that we're not overwriting data
assert(wtx.mapValue.count("replaced_by_txid") == 0);
wtx.mapValue["replaced_by_txid"] = newHash.ToString();
CWalletDB walletdb(*dbw, "r+");
bool success = true;
if (!walletdb.WriteTx(wtx)) {
LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
success = false;
}
NotifyTransactionChanged(this, originalHash, CT_UPDATED);
return success;
}
bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
{
LOCK(cs_wallet);
CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
uint256 hash = wtxIn.GetHash();
// Inserts only if not already there, returns tx inserted or tx found
std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
CWalletTx& wtx = (*ret.first).second;
wtx.BindWallet(this);
bool fInsertedNew = ret.second;
if (fInsertedNew)
{
wtx.nTimeReceived = GetAdjustedTime();
wtx.nOrderPos = IncOrderPosNext(&walletdb);
wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
wtx.nTimeSmart = ComputeTimeSmart(wtx);
AddToSpends(hash);
}
bool fUpdated = false;
if (!fInsertedNew)
{
// Merge
if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
{
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
}
// If no longer abandoned, update
if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
{
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
}
if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
{
wtx.nIndex = wtxIn.nIndex;
fUpdated = true;
}
if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
{
wtx.fFromMe = wtxIn.fFromMe;
fUpdated = true;
}
// If we have a witness-stripped version of this transaction, and we
// see a new version with a witness, then we must be upgrading a pre-segwit
// wallet. Store the new version of the transaction with the witness,
// as the stripped-version must be invalid.
// TODO: Store all versions of the transaction, instead of just one.
if (wtxIn.tx->HasWitness() && !wtx.tx->HasWitness()) {
wtx.SetTx(wtxIn.tx);
fUpdated = true;
}
}
//// debug print
LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
// Write to disk
if (fInsertedNew || fUpdated)
if (!walletdb.WriteTx(wtx))
return false;
// Break debit/credit balance caches:
wtx.MarkDirty();
// Notify UI of new or updated transaction
NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
// notify an external script when a wallet transaction comes in or is updated
std::string strCmd = gArgs.GetArg("-walletnotify", "");
if (!strCmd.empty())
{
boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
return true;
}
bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
{
uint256 hash = wtxIn.GetHash();
mapWallet[hash] = wtxIn;
CWalletTx& wtx = mapWallet[hash];
wtx.BindWallet(this);
wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
AddToSpends(hash);
for (const CTxIn& txin : wtx.tx->vin) {
auto it = mapWallet.find(txin.prevout.hash);
if (it != mapWallet.end()) {
CWalletTx& prevtx = it->second;
if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
MarkConflicted(prevtx.hashBlock, wtx.GetHash());
}
}
}
return true;
}
/**
* Add a transaction to the wallet, or update it. pIndex and posInBlock should
* be set when the transaction was known to be included in a block. When
* pIndex == nullptr, then wallet state is not updated in AddToWallet, but
* notifications happen and cached balances are marked dirty.
*
* If fUpdate is true, existing transactions will be updated.
* TODO: One exception to this is that the abandoned state is cleared under the
* assumption that any further notification of a transaction that was considered
* abandoned is an indication that it is not safe to be considered abandoned.
* Abandoned state should probably be more carefully tracked via different
* posInBlock signals or by checking mempool presence when necessary.
*/
bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
{
const CTransaction& tx = *ptx;
{
AssertLockHeld(cs_wallet);
if (pIndex != nullptr) {
for (const CTxIn& txin : tx.vin) {
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
while (range.first != range.second) {
if (range.first->second != tx.GetHash()) {
LogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), pIndex->GetBlockHash().ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
MarkConflicted(pIndex->GetBlockHash(), range.first->second);
}
range.first++;
}
}
}
bool fExisted = mapWallet.count(tx.GetHash()) != 0;
if (fExisted && !fUpdate) return false;
if (fExisted || IsMine(tx) || IsFromMe(tx))
{
/* Check if any keys in the wallet keypool that were supposed to be unused
* have appeared in a new transaction. If so, remove those keys from the keypool.
* This can happen when restoring an old wallet backup that does not contain
* the mostly recently created transactions from newer versions of the wallet.
*/
// loop though all outputs
for (const CTxOut& txout: tx.vout) {
// extract addresses and check if they match with an unused keypool key
std::vector<CKeyID> vAffected;
CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
for (const CKeyID &keyid : vAffected) {
std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
if (mi != m_pool_key_to_index.end()) {
LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
MarkReserveKeysAsUsed(mi->second);
if (!TopUpKeyPool()) {
LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
}
}
}
}
CWalletTx wtx(this, ptx);
// Get merkle branch if transaction was found in a block
if (pIndex != nullptr)
wtx.SetMerkleBranch(pIndex, posInBlock);
return AddToWallet(wtx, false);
}
}
return false;
}
bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
{
LOCK2(cs_main, cs_wallet);
const CWalletTx* wtx = GetWalletTx(hashTx);
return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
}
bool CWallet::AbandonTransaction(const uint256& hashTx)
{
LOCK2(cs_main, cs_wallet);
CWalletDB walletdb(*dbw, "r+");
std::set<uint256> todo;
std::set<uint256> done;
// Can't mark abandoned if confirmed or in mempool
auto it = mapWallet.find(hashTx);
assert(it != mapWallet.end());
CWalletTx& origtx = it->second;
if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
return false;
}
todo.insert(hashTx);
while (!todo.empty()) {
uint256 now = *todo.begin();
todo.erase(now);
done.insert(now);
auto it = mapWallet.find(now);
assert(it != mapWallet.end());
CWalletTx& wtx = it->second;
int currentconfirm = wtx.GetDepthInMainChain();
// If the orig tx was not in block, none of its spends can be
assert(currentconfirm <= 0);
// if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
if (currentconfirm == 0 && !wtx.isAbandoned()) {
// If the orig tx was not in block/mempool, none of its spends can be in mempool
assert(!wtx.InMempool());
wtx.nIndex = -1;
wtx.setAbandoned();
wtx.MarkDirty();
walletdb.WriteTx(wtx);
NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
// Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
while (iter != mapTxSpends.end() && iter->first.hash == now) {
if (!done.count(iter->second)) {
todo.insert(iter->second);
}
iter++;
}
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be recomputed
for (const CTxIn& txin : wtx.tx->vin)
{
auto it = mapWallet.find(txin.prevout.hash);
if (it != mapWallet.end()) {
it->second.MarkDirty();
}
}
}
}
return true;
}
void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
{
LOCK2(cs_main, cs_wallet);
int conflictconfirms = 0;
if (mapBlockIndex.count(hashBlock)) {
CBlockIndex* pindex = mapBlockIndex[hashBlock];
if (chainActive.Contains(pindex)) {
conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
}
}
// If number of conflict confirms cannot be determined, this means
// that the block is still unknown or not yet part of the main chain,
// for example when loading the wallet during a reindex. Do nothing in that
// case.
if (conflictconfirms >= 0)
return;
// Do not flush the wallet here for performance reasons
CWalletDB walletdb(*dbw, "r+", false);
std::set<uint256> todo;
std::set<uint256> done;
todo.insert(hashTx);
while (!todo.empty()) {
uint256 now = *todo.begin();
todo.erase(now);
done.insert(now);
auto it = mapWallet.find(now);
assert(it != mapWallet.end());
CWalletTx& wtx = it->second;
int currentconfirm = wtx.GetDepthInMainChain();
if (conflictconfirms < currentconfirm) {
// Block is 'more conflicted' than current confirm; update.
// Mark transaction as conflicted with this block.
wtx.nIndex = -1;
wtx.hashBlock = hashBlock;
wtx.MarkDirty();
walletdb.WriteTx(wtx);
// Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
while (iter != mapTxSpends.end() && iter->first.hash == now) {
if (!done.count(iter->second)) {
todo.insert(iter->second);
}
iter++;
}
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be recomputed
for (const CTxIn& txin : wtx.tx->vin) {
auto it = mapWallet.find(txin.prevout.hash);
if (it != mapWallet.end()) {
it->second.MarkDirty();
}
}
}
}
}
void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
const CTransaction& tx = *ptx;
if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
return; // Not one of ours
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be
// recomputed, also:
for (const CTxIn& txin : tx.vin) {
auto it = mapWallet.find(txin.prevout.hash);
if (it != mapWallet.end()) {
it->second.MarkDirty();
}
}
}
void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
LOCK2(cs_main, cs_wallet);
SyncTransaction(ptx);
}
void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
LOCK2(cs_main, cs_wallet);
// TODO: Temporarily ensure that mempool removals are notified before
// connected transactions. This shouldn't matter, but the abandoned
// state of transactions in our wallet is currently cleared when we
// receive another notification and there is a race condition where
// notification of a connected conflict might cause an outside process
// to abandon a transaction and then have it inadvertently cleared by
// the notification that the conflicted transaction was evicted.
for (const CTransactionRef& ptx : vtxConflicted) {
SyncTransaction(ptx);
}
for (size_t i = 0; i < pblock->vtx.size(); i++) {
SyncTransaction(pblock->vtx[i], pindex, i);
}
}
void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
LOCK2(cs_main, cs_wallet);
for (const CTransactionRef& ptx : pblock->vtx) {
SyncTransaction(ptx);
}
}
isminetype CWallet::IsMine(const CTxIn &txin) const
{
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.tx->vout.size())
return IsMine(prev.tx->vout[txin.prevout.n]);
}
}
return ISMINE_NO;
}
CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const {
CAssetOutputEntry assetData;
return GetDebit(txin, filter, assetData);
}
// Note that this function doesn't distinguish between a 0-valued input,
// and a not-"is mine" (according to the filter) input.
CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter, CAssetOutputEntry& assetData) const
{
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.tx->vout.size())
if (IsMine(prev.tx->vout[txin.prevout.n]) & filter) {
// if asset get that assets data from the scriptPubKey
if (prev.tx->vout[txin.prevout.n].scriptPubKey.IsAssetScript())
GetAssetData(prev.tx->vout[txin.prevout.n].scriptPubKey, assetData);
return prev.tx->vout[txin.prevout.n].nValue;
}
}
}
return 0;
}
isminetype CWallet::IsMine(const CTxOut& txout) const
{
return ::IsMine(*this, txout.scriptPubKey);
}
CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
{
if (!MoneyRange(txout.nValue))
throw std::runtime_error(std::string(__func__) + ": value out of range");
return ((IsMine(txout) & filter) ? txout.nValue : 0);
}
bool CWallet::IsChange(const CTxOut& txout) const
{
// TODO: fix handling of 'change' outputs. The assumption is that any
// payment to a script that is ours, but is not in the address book
// is change. That assumption is likely to break when we implement multisignature
// wallets that return change back into a multi-signature-protected address;
// a better way of identifying which outputs are 'the send' and which are
// 'the change' will need to be implemented (maybe extend CWalletTx to remember
// which output, if any, was change).
if (::IsMine(*this, txout.scriptPubKey))
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
return true;
LOCK(cs_wallet);
if (!mapAddressBook.count(address))
return true;
}
return false;
}
CAmount CWallet::GetChange(const CTxOut& txout) const
{
if (!MoneyRange(txout.nValue))
throw std::runtime_error(std::string(__func__) + ": value out of range");
return (IsChange(txout) ? txout.nValue : 0);
}
bool CWallet::IsMine(const CTransaction& tx) const
{
for (const CTxOut& txout : tx.vout)
if (IsMine(txout))
return true;
return false;
}
bool CWallet::IsFromMe(const CTransaction& tx) const
{
return (GetDebit(tx, ISMINE_ALL) > 0);
}
CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
{
CAmount nDebit = 0;
for (const CTxIn& txin : tx.vin)
{
nDebit += GetDebit(txin, filter);
if (!MoneyRange(nDebit))
throw std::runtime_error(std::string(__func__) + ": value out of range");
}
return nDebit;
}
bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
{
LOCK(cs_wallet);
for (const CTxIn& txin : tx.vin)
{
auto mi = mapWallet.find(txin.prevout.hash);
if (mi == mapWallet.end())
return false; // any unknown inputs can't be from us
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n >= prev.tx->vout.size())
return false; // invalid input!
if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
return false;
}
return true;
}
CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
{
CAmount nCredit = 0;
for (const CTxOut& txout : tx.vout)
{
nCredit += GetCredit(txout, filter);
if (!MoneyRange(nCredit))
throw std::runtime_error(std::string(__func__) + ": value out of range");
}
return nCredit;
}
CAmount CWallet::GetChange(const CTransaction& tx) const
{
CAmount nChange = 0;
for (const CTxOut& txout : tx.vout)
{
nChange += GetChange(txout);
if (!MoneyRange(nChange))
throw std::runtime_error(std::string(__func__) + ": value out of range");
}
return nChange;
}
CPubKey CWallet::GenerateNewSeed()
{
CKey key;
key.MakeNewKey(true);
return DeriveNewSeed(key);
}
CPubKey CWallet::DeriveNewSeed(const CKey& key)
{
int64_t nCreationTime = GetTime();
CKeyMetadata metadata(nCreationTime);
// calculate the seed
CPubKey seed = key.GetPubKey();
assert(key.VerifyPubKey(seed));
// set the hd keypath to "s" -> Seed, refers the seed to itself
metadata.hdKeypath = "s";
metadata.hd_seed_id = seed.GetID();
{
LOCK(cs_wallet);
// mem store the metadata
mapKeyMetadata[seed.GetID()] = metadata;
// write the key&metadata to the database
if (!AddKeyPubKey(key, seed))
throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
}
return seed;
}
bool CWallet::SetHDSeed(const CPubKey& seed)
{
LOCK(cs_wallet);
// store the keyid (hash160) together with
// the child index counter in the database
// as a hdchain object
CHDChain newHdChain;
newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
newHdChain.seed_id = seed.GetID();
SetHDChain(newHdChain, false);
return true;
}
bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
{
LOCK(cs_wallet);
if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
throw std::runtime_error(std::string(__func__) + ": writing chain failed");
hdChain = chain;
return true;
}
bool CWallet::IsHDEnabled() const
{
return !hdChain.seed_id.IsNull();
}
int64_t CWalletTx::GetTxTime() const
{
int64_t n = nTimeSmart;
return n ? n : nTimeReceived;
}
int CWalletTx::GetRequestCount() const
{
// Returns -1 if it wasn't being tracked
int nRequests = -1;
{
LOCK(pwallet->cs_wallet);
if (IsCoinBase())
{
// Generated block
if (!hashUnset())
{
std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
}
}
else
{
// Did anyone request this transaction?
std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
if (mi != pwallet->mapRequestCount.end())
{
nRequests = (*mi).second;
// How about the block it's in?
if (nRequests == 0 && !hashUnset())
{
std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
if (_mi != pwallet->mapRequestCount.end())
nRequests = (*_mi).second;
else
nRequests = 1; // If it's in someone else's block it must have got out
}
}
}
}
return nRequests;
}
void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const {
std::list<CAssetOutputEntry> assetsReceived;
std::list<CAssetOutputEntry> assetsSent;
GetAmounts(listReceived, listSent, nFee, strSentAccount, filter, assetsReceived, assetsSent);
}
void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter, std::list<CAssetOutputEntry>& assetsReceived, std::list<CAssetOutputEntry>& assetsSent) const
{
nFee = 0;
listReceived.clear();
listSent.clear();
strSentAccount = strFromAccount;
// Compute fee:
CAmount nDebit = GetDebit(filter);
if (nDebit > 0) // debit>0 means we signed/sent this transaction
{
CAmount nValueOut = tx->GetValueOut();
nFee = nDebit - nValueOut;
}
// Sent/received.
for (unsigned int i = 0; i < tx->vout.size(); ++i)
{
const CTxOut& txout = tx->vout[i];
isminetype fIsMine = pwallet->IsMine(txout);
// Only need to handle txouts if AT LEAST one of these is true:
// 1) they debit from us (sent)
// 2) the output is to us (received)
if (nDebit > 0)
{
// Don't report 'change' txouts
if (pwallet->IsChange(txout))
continue;
}
else if (!(fIsMine & filter))
continue;
// In either case, we need to get the destination address
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
{
LogPrintf("%s: Failing on the %d tx\n", __func__, i);
LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
this->GetHash().ToString());
address = CNoDestination();
}
if (!txout.scriptPubKey.IsAssetScript()) {
COutputEntry output = {address, txout.nValue, (int) i};
// If we are debited by the transaction, add the output as a "sent" entry
if (nDebit > 0)
listSent.push_back(output);
// If we are receiving the output, add it as a "received" entry
if (fIsMine & filter)
listReceived.push_back(output);
}
/** ATL START */
if (AreAssetsDeployed()) {
if (txout.scriptPubKey.IsAssetScript()) {
CAssetOutputEntry assetoutput;
assetoutput.vout = i;
GetAssetData(txout.scriptPubKey, assetoutput);
// The only asset type we send is transfer_asset. We need to skip all other types for the sent category
if (nDebit > 0 && assetoutput.type == TX_TRANSFER_ASSET)
assetsSent.emplace_back(assetoutput);
if (fIsMine & filter)
assetsReceived.emplace_back(assetoutput);
}
}
/** ATL END */
}
}
/**
* Scan active chain for relevant transactions after importing keys. This should
* be called whenever new keys are added to the wallet, with the oldest key
* creation time.
*
* @return Earliest timestamp that could be successfully scanned from. Timestamp
* returned will be higher than startTime if relevant blocks could not be read.
*/
int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
{
AssertLockHeld(cs_main);
AssertLockHeld(cs_wallet);
// Find starting block. May be null if nCreateTime is greater than the
// highest blockchain timestamp, in which case there is nothing that needs
// to be scanned.
CBlockIndex* const startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
if (startBlock) {
const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, nullptr, update);
if (failedBlock) {
return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
}
}
return startTime;
}
/**
* Scan the block chain (starting in pindexStart) for transactions
* from or to us. If fUpdate is true, found transactions that already
* exist in the wallet will be updated.
*
* Returns null if scan was successful. Otherwise, if a complete rescan was not
* possible (due to pruning or corruption), returns pointer to the most recent
* block that could not be scanned.
*
* If pindexStop is not a nullptr, the scan will stop at the block-index
* defined by pindexStop
*/
CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, CBlockIndex* pindexStop, bool fUpdate)
{
int64_t nNow = GetTime();
const CChainParams& chainParams = Params();
if (pindexStop) {
assert(pindexStop->nHeight >= pindexStart->nHeight);
}
CBlockIndex* pindex = pindexStart;
CBlockIndex* ret = nullptr;
{
LOCK2(cs_main, cs_wallet);
fAbortRescan = false;
fScanningWallet = true;
ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
while (pindex && !fAbortRescan)
{
if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
if (GetTime() >= nNow + 60) {
nNow = GetTime();
LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
}
CBlock block;
if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
}
} else {
ret = pindex;
}
if (pindex == pindexStop) {
break;
}
pindex = chainActive.Next(pindex);
}
if (pindex && fAbortRescan) {
LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
}
ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
fScanningWallet = false;
}
return ret;
}
void CWallet::ReacceptWalletTransactions()
{
// If transactions aren't being broadcasted, don't let them into local mempool either
if (!fBroadcastTransactions)
return;
LOCK2(cs_main, cs_wallet);
std::map<int64_t, CWalletTx*> mapSorted;
// Sort pending wallet transactions based on their initial wallet insertion order
for (std::pair<const uint256, CWalletTx>& item : mapWallet)
{
const uint256& wtxid = item.first;
CWalletTx& wtx = item.second;
assert(wtx.GetHash() == wtxid);
int nDepth = wtx.GetDepthInMainChain();
if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
}
}
// Try to add wallet transactions to memory pool
for (std::pair<const int64_t, CWalletTx*>& item : mapSorted)
{
CWalletTx& wtx = *(item.second);
LOCK(mempool.cs);
CValidationState state;
wtx.AcceptToMemoryPool(maxTxFee, state);
}
}
bool CWalletTx::RelayWalletTransaction(CConnman* connman)
{
assert(pwallet->GetBroadcastTransactions());
if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
{
/* GetDepthInMainChain already catches known conflicts. */
CValidationState state;
if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
LogPrintf("Relaying wtx %s\n", GetHash().ToString());
if (connman) {
CInv inv(MSG_TX, GetHash());
connman->ForEachNode([&inv](CNode* pnode)
{
pnode->PushInventory(inv);
});
return true;
}
}
}
return false;
}
std::set<uint256> CWalletTx::GetConflicts() const
{
std::set<uint256> result;
if (pwallet != nullptr)
{
uint256 myHash = GetHash();
result = pwallet->GetConflicts(myHash);
result.erase(myHash);
}
return result;
}
CAmount CWalletTx::GetDebit(const isminefilter& filter) const
{
if (tx->vin.empty())
return 0;
CAmount debit = 0;
if(filter & ISMINE_SPENDABLE)
{
if (fDebitCached)
debit += nDebitCached;
else
{
nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
fDebitCached = true;
debit += nDebitCached;
}
}
if(filter & ISMINE_WATCH_ONLY)
{
if(fWatchDebitCached)
debit += nWatchDebitCached;
else
{
nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
fWatchDebitCached = true;
debit += nWatchDebitCached;
}
}
return debit;
}
CAmount CWalletTx::GetCredit(const isminefilter& filter) const
{
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
CAmount credit = 0;
if (filter & ISMINE_SPENDABLE)
{
// GetBalance can assume transactions in mapWallet won't change
if (fCreditCached)
credit += nCreditCached;
else
{
nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
fCreditCached = true;
credit += nCreditCached;
}
}
if (filter & ISMINE_WATCH_ONLY)
{
if (fWatchCreditCached)
credit += nWatchCreditCached;
else
{
nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
fWatchCreditCached = true;
credit += nWatchCreditCached;
}
}
return credit;
}
CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
{
if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
{
if (fUseCache && fImmatureCreditCached)
return nImmatureCreditCached;
nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
fImmatureCreditCached = true;
return nImmatureCreditCached;
}
return 0;
}
CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
{
if (pwallet == nullptr)
return 0;
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
if (fUseCache && fAvailableCreditCached)
return nAvailableCreditCached;
CAmount nCredit = 0;
uint256 hashTx = GetHash();
for (unsigned int i = 0; i < tx->vout.size(); i++)
{
if (!pwallet->IsSpent(hashTx, i))
{
const CTxOut &txout = tx->vout[i];
nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
if (!MoneyRange(nCredit))
throw std::runtime_error(std::string(__func__) + " : value out of range");
}
}
nAvailableCreditCached = nCredit;
fAvailableCreditCached = true;
return nCredit;
}
CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
{
if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
{
if (fUseCache && fImmatureWatchCreditCached)
return nImmatureWatchCreditCached;
nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
fImmatureWatchCreditCached = true;
return nImmatureWatchCreditCached;
}
return 0;
}
CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
{
if (pwallet == nullptr)
return 0;
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
if (fUseCache && fAvailableWatchCreditCached)
return nAvailableWatchCreditCached;
CAmount nCredit = 0;
for (unsigned int i = 0; i < tx->vout.size(); i++)
{
if (!pwallet->IsSpent(GetHash(), i))
{
const CTxOut &txout = tx->vout[i];
nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
if (!MoneyRange(nCredit))
throw std::runtime_error(std::string(__func__) + ": value out of range");
}
}
nAvailableWatchCreditCached = nCredit;
fAvailableWatchCreditCached = true;
return nCredit;
}
CAmount CWalletTx::GetChange() const
{
if (fChangeCached)
return nChangeCached;
nChangeCached = pwallet->GetChange(*this);
fChangeCached = true;
return nChangeCached;
}
bool CWalletTx::InMempool() const
{
LOCK(mempool.cs);
return mempool.exists(GetHash());
}
bool CWalletTx::IsTrusted() const
{
// Quick answer in most cases
if (!CheckFinalTx(*this))
return false;
int nDepth = GetDepthInMainChain();
if (nDepth >= 1)
return true;
if (nDepth < 0)
return false;
if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
return false;
// Don't trust unconfirmed transactions from us unless they are in the mempool.
if (!InMempool())
return false;
// Trusted if all inputs are from us and are in the mempool:
for (const CTxIn& txin : tx->vin)
{
// Transactions not sent by us: not trusted
const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
if (parent == nullptr)
return false;
const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
return false;
}
return true;
}
bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
{
CMutableTransaction tx1 = *this->tx;
CMutableTransaction tx2 = *_tx.tx;
for (auto& txin : tx1.vin) txin.scriptSig = CScript();
for (auto& txin : tx2.vin) txin.scriptSig = CScript();
return CTransaction(tx1) == CTransaction(tx2);
}
std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
{
std::vector<uint256> result;
LOCK(cs_wallet);
// Sort them in chronological order
std::multimap<unsigned int, CWalletTx*> mapSorted;
for (std::pair<const uint256, CWalletTx>& item : mapWallet)
{
CWalletTx& wtx = item.second;
// Don't rebroadcast if newer than nTime:
if (wtx.nTimeReceived > nTime)
continue;
mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
}
for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
{
CWalletTx& wtx = *item.second;
if (wtx.RelayWalletTransaction(connman))
result.push_back(wtx.GetHash());
}
return result;
}
void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
{
// Do this infrequently and randomly to avoid giving away
// that these are our transactions.
if (GetTime() < nNextResend || !fBroadcastTransactions)
return;
bool fFirst = (nNextResend == 0);
nNextResend = GetTime() + GetRand(30 * 60);
if (fFirst)
return;
// Only do it if there's been a new block since last time
if (nBestBlockTime < nLastResend)
return;
nLastResend = GetTime();
// Rebroadcast unconfirmed txes older than 5 minutes before the last
// block was found:
std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
if (!relayed.empty())
LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
}
/** @} */ // end of mapWallet
/** @defgroup Actions
*
* @{
*/
CAmount CWallet::GetBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
CAmount CWallet::GetUnconfirmedBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
CAmount CWallet::GetImmatureBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
nTotal += pcoin->GetImmatureCredit();
}
}
return nTotal;
}
CAmount CWallet::GetWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAvailableWatchOnlyCredit();
}
}
return nTotal;
}
CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
nTotal += pcoin->GetAvailableWatchOnlyCredit();
}
}
return nTotal;
}
CAmount CWallet::GetImmatureWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
nTotal += pcoin->GetImmatureWatchOnlyCredit();
}
}
return nTotal;
}
// Calculate total balance in a different way from GetBalance. The biggest
// difference is that GetBalance sums up all unspent TxOuts paying to the
// wallet, while this sums up both spent and unspent TxOuts paying to the
// wallet, and then subtracts the values of TxIns spending from the wallet. This
// also has fewer restrictions on which unconfirmed transactions are considered
// trusted.
CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
{
LOCK2(cs_main, cs_wallet);
CAmount balance = 0;
for (const auto& entry : mapWallet) {
const CWalletTx& wtx = entry.second;
const int depth = wtx.GetDepthInMainChain();
if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
continue;
}
// Loop through tx outputs and add incoming payments. For outgoing txs,
// treat change outputs specially, as part of the amount debited.
CAmount debit = wtx.GetDebit(filter);
const bool outgoing = debit > 0;
for (const CTxOut& out : wtx.tx->vout) {
if (outgoing && IsChange(out)) {
debit -= out.nValue;
} else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
balance += out.nValue;
}
}
// For outgoing txs, subtract amount debited.
if (outgoing && (!account || *account == wtx.strFromAccount)) {
balance -= debit;
}
}
if (account) {
balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
}
return balance;
}
CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
{
LOCK2(cs_main, cs_wallet);
CAmount balance = 0;
std::vector<COutput> vCoins;
AvailableCoins(vCoins, true, coinControl);
for (const COutput& out : vCoins) {
if (out.fSpendable) {
balance += out.tx->tx->vout[out.i].nValue;
}
}
return balance;
}
void CWallet::AvailableCoins(std::vector<COutput> &vCoins, bool fOnlySafe, const CCoinControl *coinControl, const CAmount &nMinimumAmount, const CAmount &nMaximumAmount, const CAmount &nMinimumSumAmount, const uint64_t &nMaximumCount, const int &nMinDepth, const int &nMaxDepth) const
{
std::map<std::string, std::vector<COutput> > mapAssetCoins;
AvailableCoinsAll(vCoins, mapAssetCoins, true, false, fOnlySafe, coinControl, nMinimumAmount, nMaximumAmount, nMinimumSumAmount, nMaximumCount, nMinDepth, nMaxDepth);
}
void CWallet::AvailableAssets(std::map<std::string, std::vector<COutput> > &mapAssetCoins, bool fOnlySafe,
const CCoinControl *coinControl, const CAmount &nMinimumAmount,
const CAmount &nMaximumAmount, const CAmount &nMinimumSumAmount,
const uint64_t &nMaximumCount, const int &nMinDepth, const int &nMaxDepth) const
{
if (!AreAssetsDeployed())
return;
std::vector<COutput> vCoins;
AvailableCoinsAll(vCoins, mapAssetCoins, false, true, fOnlySafe, coinControl, nMinimumAmount, nMaximumAmount, nMinimumSumAmount, nMaximumCount, nMinDepth, nMaxDepth);
}
void CWallet::AvailableCoinsWithAssets(std::vector<COutput> &vCoins, std::map<std::string, std::vector<COutput> > &mapAssetCoins,
bool fOnlySafe, const CCoinControl *coinControl, const CAmount &nMinimumAmount,
const CAmount &nMaximumAmount, const CAmount &nMinimumSumAmount,
const uint64_t &nMaximumCount, const int &nMinDepth, const int &nMaxDepth) const
{
AvailableCoinsAll(vCoins, mapAssetCoins, true, AreAssetsDeployed(), fOnlySafe, coinControl, nMinimumAmount, nMaximumAmount, nMinimumSumAmount, nMaximumCount, nMinDepth, nMaxDepth);
}
void CWallet::AvailableCoinsAll(std::vector<COutput>& vCoins, std::map<std::string, std::vector<COutput> >& mapAssetCoins, bool fGetATL, bool fGetAssets, bool fOnlySafe, const CCoinControl *coinControl, const CAmount& nMinimumAmount, const CAmount& nMaximumAmount, const CAmount& nMinimumSumAmount, const uint64_t& nMaximumCount, const int& nMinDepth, const int& nMaxDepth) const {
vCoins.clear();
{
LOCK2(cs_main, cs_wallet);
CAmount nTotal = 0;
/** ATL START */
bool fATLLimitHit = false;
// A set of the hashes that have already been used
std::set<uint256> usedMempoolHashes;
std::map<std::string, CAmount> mapAssetTotals;
std::map<uint256, COutPoint> mapOutPoints;
std::set<std::string> setAssetMaxFound;
// Turn the OutPoints into a map that is easily interatable.
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const uint256 &wtxid = it->first;
const CWalletTx *pcoin = &(*it).second;
if (!CheckFinalTx(*pcoin))
continue;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < 0)
continue;
// We should not consider coins which aren't at least in our mempool
// It's possible for these to be conflicted via ancestors which we may never be able to detect
if (nDepth == 0 && !pcoin->InMempool())
continue;
bool safeTx = pcoin->IsTrusted();
// We should not consider coins from transactions that are replacing
// other transactions.
//
// Example: There is a transaction A which is replaced by bumpfee
// transaction B. In this case, we want to prevent creation of
// a transaction B' which spends an output of B.
//
// Reason: If transaction A were initially confirmed, transactions B
// and B' would no longer be valid, so the user would have to create
// a new transaction C to replace B'. However, in the case of a
// one-block reorg, transactions B' and C might BOTH be accepted,
// when the user only wanted one of them. Specifically, there could
// be a 1-block reorg away from the chain where transactions A and C
// were accepted to another chain where B, B', and C were all
// accepted.
if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
safeTx = false;
}
// Similarly, we should not consider coins from transactions that
// have been replaced. In the example above, we would want to prevent
// creation of a transaction A' spending an output of A, because if
// transaction B were initially confirmed, conflicting with A and
// A', we wouldn't want to the user to create a transaction D
// intending to replace A', but potentially resulting in a scenario
// where A, A', and D could all be accepted (instead of just B and
// D, or just A and A' like the user would want).
if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
safeTx = false;
}
if (fOnlySafe && !safeTx) {
continue;
}
if (nDepth < nMinDepth || nDepth > nMaxDepth)
continue;
for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
int nType;
bool fIsOwner;
bool isAssetScript = pcoin->tx->vout[i].scriptPubKey.IsAssetScript(nType, fIsOwner);
if (coinControl && !isAssetScript && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint((*it).first, i)))
continue;
if (coinControl && isAssetScript && coinControl->HasAssetSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsAssetSelected(COutPoint((*it).first, i)))
continue;
if (IsLockedCoin((*it).first, i))
continue;
if (IsSpent(wtxid, i))
continue;
isminetype mine = IsMine(pcoin->tx->vout[i]);
if (mine == ISMINE_NO) {
continue;
}
bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) ||
(coinControl && coinControl->fAllowWatchOnly &&
(mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
std::string address;
CAssetTransfer assetTransfer;
CNewAsset asset;
CReissueAsset reissue;
std::string ownerName;
bool fWasNewAssetOutPoint = false;
bool fWasTransferAssetOutPoint = false;
bool fWasOwnerAssetOutPoint = false;
bool fWasReissueAssetOutPoint = false;
std::string strAssetName;
// Looking for Asset Tx OutPoints Only
if (fGetAssets && AreAssetsDeployed() && isAssetScript) {
if ( nType == TX_TRANSFER_ASSET) {
if (TransferAssetFromScript(pcoin->tx->vout[i].scriptPubKey, assetTransfer, address)) {
strAssetName = assetTransfer.strName;
fWasTransferAssetOutPoint = true;
}
} else if ( nType == TX_NEW_ASSET && !fIsOwner) {
if (AssetFromScript(pcoin->tx->vout[i].scriptPubKey, asset, address)) {
strAssetName = asset.strName;
fWasNewAssetOutPoint = true;
}
} else if ( nType == TX_NEW_ASSET && fIsOwner) {
if (OwnerAssetFromScript(pcoin->tx->vout[i].scriptPubKey, ownerName, address)) {
strAssetName = ownerName;
fWasOwnerAssetOutPoint = true;
}
} else if ( nType == TX_REISSUE_ASSET) {
if (ReissueAssetFromScript(pcoin->tx->vout[i].scriptPubKey, reissue, address)) {
strAssetName = reissue.strName;
fWasReissueAssetOutPoint = true;
}
} else {
continue;
}
if (fWasNewAssetOutPoint || fWasTransferAssetOutPoint || fWasOwnerAssetOutPoint || fWasReissueAssetOutPoint) {
// If we already have the maximum amount or size for this asset, skip it
if (setAssetMaxFound.count(strAssetName))
continue;
// Initialize the map vector is it doesn't exist yet
if (!mapAssetCoins.count(strAssetName)) {
std::vector<COutput> vOutput;
mapAssetCoins.insert(std::make_pair(strAssetName, vOutput));
}
// Add the COutput to the map of available Asset Coins
mapAssetCoins.at(strAssetName).push_back(
COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
// Initialize the map of current asset totals
if (!mapAssetTotals.count(strAssetName))
mapAssetTotals[strAssetName] = 0;
// Update the map of totals depending the which type of asset tx we are looking at
if (fWasNewAssetOutPoint)
mapAssetTotals[strAssetName] += asset.nAmount;
else if (fWasTransferAssetOutPoint)
mapAssetTotals[strAssetName] += assetTransfer.nAmount;
else if (fWasReissueAssetOutPoint)
mapAssetTotals[strAssetName] += reissue.nAmount;
else if (fWasOwnerAssetOutPoint)
mapAssetTotals[strAssetName] = OWNER_ASSET_AMOUNT;
// Checks the sum amount of all UTXO's, and adds to the set of assets that we found the max for
if (nMinimumSumAmount != MAX_MONEY) {
if (mapAssetTotals[strAssetName] >= nMinimumSumAmount)
setAssetMaxFound.insert(strAssetName);
}
// Checks the maximum number of UTXO's, and addes to set of of asset that we found the max for
if (nMaximumCount > 0 && mapAssetCoins[strAssetName].size() >= nMaximumCount) {
setAssetMaxFound.insert(strAssetName);
}
}
}
if (fGetATL) { // Looking for ATL Tx OutPoints Only
if (fATLLimitHit) // We hit our limit
continue;
// We only want ATL OutPoints. Don't include Asset OutPoints
if (isAssetScript)
continue;
vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
// Checks the sum amount of all UTXO's.
if (nMinimumSumAmount != MAX_MONEY) {
nTotal += pcoin->tx->vout[i].nValue;
if (nTotal >= nMinimumSumAmount) {
fATLLimitHit = true;
}
}
// Checks the maximum number of UTXO's.
if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
fATLLimitHit = true;
}
continue;
}
}
}
/** ATL END */
}
}
/** ATL START */
std::map<CTxDestination, std::vector<COutput>> CWallet::ListAssets() const
{
// TODO: Add AssertLockHeld(cs_wallet) here.
//
// Because the return value from this function contains pointers to
// CWalletTx objects, callers to this function really should acquire the
// cs_wallet lock before calling it. However, the current caller doesn't
// acquire this lock yet. There was an attempt to add the missing lock in
// https://github.com/AtlasProject/Atlascoin/pull/10340, but that change has been
// postponed until after https://github.com/AtlasProject/Atlascoin/pull/10244 to
// avoid adding some extra complexity to the Qt code.
std::map<CTxDestination, std::vector<COutput>> result;
std::map<std::string, std::vector<COutput> > mapAssets;
AvailableAssets(mapAssets);
LOCK2(cs_main, cs_wallet);
for (auto asset : mapAssets) {
for (auto &coin : asset.second) {
CTxDestination address;
if (coin.fSpendable &&
ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
result[address].emplace_back(std::move(coin));
}
}
}
std::vector<COutPoint> lockedCoins;
ListLockedCoins(lockedCoins);
for (const auto& output : lockedCoins) {
auto it = mapWallet.find(output.hash);
if (it != mapWallet.end()) {
if (!it->second.tx->vout[output.n].scriptPubKey.IsAssetScript()) // If not an asset script skip it
continue;
int depth = it->second.GetDepthInMainChain();
if (depth >= 0 && output.n < it->second.tx->vout.size() &&
IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
CTxDestination address;
if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
result[address].emplace_back(
&it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
}
}
}
}
return result;
}
/** ATL END */
std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
{
// TODO: Add AssertLockHeld(cs_wallet) here.
//
// Because the return value from this function contains pointers to
// CWalletTx objects, callers to this function really should acquire the
// cs_wallet lock before calling it. However, the current caller doesn't
// acquire this lock yet. There was an attempt to add the missing lock in
// https://github.com/AtlasProject/Atlascoin/pull/10340, but that change has been
// postponed until after https://github.com/AtlasProject/Atlascoin/pull/10244 to
// avoid adding some extra complexity to the Qt code.
std::map<CTxDestination, std::vector<COutput>> result;
std::vector<COutput> availableCoins;
AvailableCoins(availableCoins);
LOCK2(cs_main, cs_wallet);
for (auto& coin : availableCoins) {
CTxDestination address;
if (coin.fSpendable &&
ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
result[address].emplace_back(std::move(coin));
}
}
std::vector<COutPoint> lockedCoins;
ListLockedCoins(lockedCoins);
for (const auto& output : lockedCoins) {
auto it = mapWallet.find(output.hash);
if (it != mapWallet.end()) {
int depth = it->second.GetDepthInMainChain();
if (depth >= 0 && output.n < it->second.tx->vout.size() &&
IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
CTxDestination address;
if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
result[address].emplace_back(
&it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
}
}
}
}
return result;
}
const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
{
const CTransaction* ptx = &tx;
int n = output;
while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
const COutPoint& prevout = ptx->vin[0].prevout;
auto it = mapWallet.find(prevout.hash);
if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
!IsMine(it->second.tx->vout[prevout.n])) {
break;
}
ptx = it->second.tx.get();
n = prevout.n;
}
return ptx->vout[n];
}
static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
{
std::vector<char> vfIncluded;
vfBest.assign(vValue.size(), true);
nBest = nTotalLower;
FastRandomContext insecure_rand;
for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
{
vfIncluded.assign(vValue.size(), false);
CAmount nTotal = 0;
bool fReachedTarget = false;
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
{
for (unsigned int i = 0; i < vValue.size(); i++)
{
//The solver here uses a randomized algorithm,
//the randomness serves no real security purpose but is just
//needed to prevent degenerate behavior and it is important
//that the rng is fast. We do not use a constant random sequence,
//because there may be some privacy improvement by making
//the selection random.
if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
{
nTotal += vValue[i].txout.nValue;
vfIncluded[i] = true;
if (nTotal >= nTargetValue)
{
fReachedTarget = true;
if (nTotal < nBest)
{
nBest = nTotal;
vfBest = vfIncluded;
}
nTotal -= vValue[i].txout.nValue;
vfIncluded[i] = false;
}
}
}
}
}
}
static void ApproximateBestAssetSubset(const std::vector<std::pair<CInputCoin, CAmount> >& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
{
std::vector<char> vfIncluded;
vfBest.assign(vValue.size(), true);
nBest = nTotalLower;
FastRandomContext insecure_rand;
for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
{
vfIncluded.assign(vValue.size(), false);
CAmount nTotal = 0;
bool fReachedTarget = false;
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
{
for (unsigned int i = 0; i < vValue.size(); i++)
{
//The solver here uses a randomized algorithm,
//the randomness serves no real security purpose but is just
//needed to prevent degenerate behavior and it is important
//that the rng is fast. We do not use a constant random sequence,
//because there may be some privacy improvement by making
//the selection random.
if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
{
nTotal += vValue[i].second;
vfIncluded[i] = true;
if (nTotal >= nTargetValue)
{
fReachedTarget = true;
if (nTotal < nBest)
{
nBest = nTotal;
vfBest = vfIncluded;
}
nTotal -= vValue[i].second;
vfIncluded[i] = false;
}
}
}
}
}
}
bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
{
setCoinsRet.clear();
nValueRet = 0;
// List of values less than target
boost::optional<CInputCoin> coinLowestLarger;
std::vector<CInputCoin> vValue;
CAmount nTotalLower = 0;
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
for (const COutput &output : vCoins)
{
if (!output.fSpendable)
continue;
const CWalletTx *pcoin = output.tx;
if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
continue;
if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
continue;
int i = output.i;
CInputCoin coin = CInputCoin(pcoin, i);
if (coin.txout.nValue == nTargetValue)
{
setCoinsRet.insert(coin);
nValueRet += coin.txout.nValue;
return true;
}
else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
{
vValue.push_back(coin);
nTotalLower += coin.txout.nValue;
}
else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
{
coinLowestLarger = coin;
}
}
if (nTotalLower == nTargetValue)
{
for (const auto& input : vValue)
{
setCoinsRet.insert(input);
nValueRet += input.txout.nValue;
}
return true;
}
if (nTotalLower < nTargetValue)
{
if (!coinLowestLarger)
return false;
setCoinsRet.insert(coinLowestLarger.get());
nValueRet += coinLowestLarger->txout.nValue;
return true;
}
// Solve subset sum by stochastic approximation
std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
std::reverse(vValue.begin(), vValue.end());
std::vector<char> vfBest;
CAmount nBest;
ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
// If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
// or the next bigger coin is closer), return the bigger coin
if (coinLowestLarger &&
((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
{
setCoinsRet.insert(coinLowestLarger.get());
nValueRet += coinLowestLarger->txout.nValue;
}
else {
for (unsigned int i = 0; i < vValue.size(); i++)
if (vfBest[i])
{
setCoinsRet.insert(vValue[i]);
nValueRet += vValue[i].txout.nValue;
}
if (LogAcceptCategory(BCLog::SELECTCOINS)) {
LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
for (unsigned int i = 0; i < vValue.size(); i++) {
if (vfBest[i]) {
LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
}
}
LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
}
}
return true;
}
bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
{
std::vector<COutput> vCoins(vAvailableCoins);
// coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
{
for (const COutput& out : vCoins)
{
if (!out.fSpendable)
continue;
nValueRet += out.tx->tx->vout[out.i].nValue;
setCoinsRet.insert(CInputCoin(out.tx, out.i));
}
return (nValueRet >= nTargetValue);
}
// calculate value from preset inputs and store them
std::set<CInputCoin> setPresetCoins;
CAmount nValueFromPresetInputs = 0;
std::vector<COutPoint> vPresetInputs;
if (coinControl)
coinControl->ListSelected(vPresetInputs);
for (const COutPoint& outpoint : vPresetInputs)
{
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
if (it != mapWallet.end())
{
const CWalletTx* pcoin = &it->second;
// Clearly invalid input, fail
if (pcoin->tx->vout.size() <= outpoint.n)
return false;
nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
} else
return false; // TODO: Allow non-wallet inputs
}
// remove preset inputs from vCoins
for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
{
if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
it = vCoins.erase(it);
else
++it;
}
size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
bool res = nTargetValue <= nValueFromPresetInputs ||
SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
(bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
(bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
(bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
(bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
(bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
// because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
// add preset inputs to the total value selected
nValueRet += nValueFromPresetInputs;
return res;
}
/** ATL START */
bool CWallet::CreateNewChangeAddress(CReserveKey& reservekey, CKeyID& keyID, std::string& strFailReason)
{
// Called with coin control doesn't have a change_address
// no coin control: send change to newly generated address
// Note: We use a new key here to keep it from being obvious which side is the change.
// The drawback is that by not reusing a previous key, the change may be lost if a
// backup is restored, if the backup doesn't have the new private key for the change.
// If we reused the old key, it would be possible to add code to look for and
// rediscover unknown transactions that were written with keys of ours to recover
// post-backup change.
// Reserve a new key pair from key pool
CPubKey vchPubKey;
bool ret;
ret = reservekey.GetReservedKey(vchPubKey, true);
if (!ret)
{
strFailReason = _("Keypool ran out, please call keypoolrefill first");
return false;
}
keyID = vchPubKey.GetID();
return true;
}
bool CWallet::SelectAssetsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, const std::string& strAssetName, std::vector<COutput> vCoins,
std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
{
setCoinsRet.clear();
nValueRet = 0;
// List of values less than target
boost::optional<CInputCoin> coinLowestLarger;
boost::optional<CAmount> coinLowestLargerAmount;
std::vector<std::pair<CInputCoin, CAmount> > vValue;
std::map<COutPoint, CAmount> mapValueAmount;
CAmount nTotalLower = 0;
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
for (const COutput &output : vCoins)
{
if (!output.fSpendable)
continue;
const CWalletTx *pcoin = output.tx;
if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
continue;
if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
continue;
int i = output.i;
CInputCoin coin = CInputCoin(pcoin, i);
//-------------------------------
int nType = -1;
bool fIsOwner = false;
if (!coin.txout.scriptPubKey.IsAssetScript(nType, fIsOwner)) {
// TODO - Remove std::cout this before mainnet release
std::cout << "This shouldn't be occuring: Non Asset Script pub key made it to the SelectAssetsMinConf function call. Look into this!" << std::endl;
continue;
}
CAmount nTempAmount = 0;
if (nType == TX_NEW_ASSET && !fIsOwner) { // Root/Sub Asset
CNewAsset assetTemp;
std::string address;
if (!AssetFromScript(coin.txout.scriptPubKey, assetTemp, address))
continue;
nTempAmount = assetTemp.nAmount;
} else if (nType == TX_TRANSFER_ASSET) { // Transfer Asset
CAssetTransfer transferTemp;
std::string address;
if (!TransferAssetFromScript(coin.txout.scriptPubKey, transferTemp, address))
continue;
nTempAmount = transferTemp.nAmount;
} else if (nType == TX_NEW_ASSET && fIsOwner) { // Owner Asset
std::string ownerName;
std::string address;
if (!OwnerAssetFromScript(coin.txout.scriptPubKey, ownerName, address))
continue;
nTempAmount = OWNER_ASSET_AMOUNT;
} else if (nType == TX_REISSUE_ASSET) { // Reissue Asset
CReissueAsset reissueTemp;
std::string address;
if (!ReissueAssetFromScript(coin.txout.scriptPubKey, reissueTemp, address))
continue;
nTempAmount = reissueTemp.nAmount;
} else {
continue;
}
if (nTempAmount == nTargetValue)
{
setCoinsRet.insert(coin);
nValueRet += nTempAmount;
return true;
}
else if (nTempAmount < nTargetValue + MIN_CHANGE)
{
vValue.push_back(std::make_pair(coin, nTempAmount));
nTotalLower += nTempAmount;
}
else if (!coinLowestLarger || !coinLowestLargerAmount || nTempAmount < coinLowestLargerAmount)
{
coinLowestLarger = coin;
coinLowestLargerAmount = nTempAmount;
}
}
if (nTotalLower == nTargetValue)
{
for (const auto& pair : vValue)
{
setCoinsRet.insert(pair.first);
nValueRet += pair.second;
}
return true;
}
if (nTotalLower < nTargetValue)
{
if (!coinLowestLarger || !coinLowestLargerAmount)
return false;
setCoinsRet.insert(coinLowestLarger.get());
nValueRet += coinLowestLargerAmount.get();
return true;
}
// Solve subset sum by stochastic approximation
std::sort(vValue.begin(), vValue.end(), CompareAssetValueOnly());
std::reverse(vValue.begin(), vValue.end());
std::vector<char> vfBest;
CAmount nBest;
ApproximateBestAssetSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
ApproximateBestAssetSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
// If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
// or the next bigger coin is closer), return the bigger coin
if (coinLowestLarger && coinLowestLargerAmount &&
((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLargerAmount <= nBest))
{
setCoinsRet.insert(coinLowestLarger.get());
nValueRet += coinLowestLargerAmount.get();
}
else {
for (unsigned int i = 0; i < vValue.size(); i++)
if (vfBest[i])
{
setCoinsRet.insert(vValue[i].first);
nValueRet += vValue[i].second;
}
if (LogAcceptCategory(BCLog::SELECTCOINS)) {
LogPrint(BCLog::SELECTCOINS, "SelectAssets() best subset: ");
for (unsigned int i = 0; i < vValue.size(); i++) {
if (vfBest[i]) {
LogPrint(BCLog::SELECTCOINS, "%s : %s", strAssetName, FormatMoney(vValue[i].second));
}
}
LogPrint(BCLog::SELECTCOINS, "total %s : %s\n", strAssetName, FormatMoney(nBest));
}
}
return true;
}
bool CWallet::SelectAssets(const std::map<std::string, std::vector<COutput> >& mapAvailableAssets, const std::map<std::string, CAmount>& mapAssetTargetValue, std::set<CInputCoin>& setCoinsRet, std::map<std::string, CAmount>& mapValueRet) const
{
if (!AreAssetsDeployed())
return false;
size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
for (auto assetVector : mapAvailableAssets) {
// Setup temporay variables
std::vector<COutput> vAssets(assetVector.second);
std::set<CInputCoin> tempCoinsRet;
CAmount nTempAmountRet;
CAmount nTempTargetValue;
std::string strAssetName = assetVector.first;
CAmount nValueFromPresetInputs = 0; // This is used with coincontrol, which assets doesn't support yet
// If we dont have a target value for this asset, don't select coins for it
if (!mapAssetTargetValue.count(strAssetName))
continue;
// If we dont have a target value greater than zero, don't select coins for it
if (mapAssetTargetValue.at(strAssetName) <= 0)
continue;
// Add the starting value into the mapValueRet
if (!mapValueRet.count(strAssetName))
mapValueRet.insert(std::make_pair(strAssetName, 0));
// assign our temporary variable
nTempAmountRet = mapValueRet.at(strAssetName);
nTempTargetValue = mapAssetTargetValue.at(strAssetName);
bool res = nTempTargetValue <= nValueFromPresetInputs ||
SelectAssetsMinConf(nTempTargetValue - nValueFromPresetInputs, 1, 6, 0, strAssetName, vAssets, tempCoinsRet, nTempAmountRet) ||
SelectAssetsMinConf(nTempTargetValue - nValueFromPresetInputs, 1, 1, 0, strAssetName, vAssets, tempCoinsRet, nTempAmountRet) ||
(bSpendZeroConfChange && SelectAssetsMinConf(nTempTargetValue - nValueFromPresetInputs, 0, 1, 2, strAssetName, vAssets, tempCoinsRet, nTempAmountRet)) ||
(bSpendZeroConfChange && SelectAssetsMinConf(nTempTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), strAssetName, vAssets, tempCoinsRet, nTempAmountRet)) ||
(bSpendZeroConfChange && SelectAssetsMinConf(nTempTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, strAssetName, vAssets, tempCoinsRet, nTempAmountRet)) ||
(bSpendZeroConfChange && SelectAssetsMinConf(nTempTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, strAssetName, vAssets, tempCoinsRet, nTempAmountRet)) ||
(bSpendZeroConfChange && !fRejectLongChains && SelectAssetsMinConf(nTempTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), strAssetName, vAssets, tempCoinsRet, nTempAmountRet));
if (res) {
setCoinsRet.insert(tempCoinsRet.begin(), tempCoinsRet.end());
mapValueRet.at(strAssetName) = nTempAmountRet + nValueFromPresetInputs;
} else {
return false;
}
}
return true;
}
/** ATL END */
bool CWallet::SignTransaction(CMutableTransaction &tx)
{
AssertLockHeld(cs_wallet); // mapWallet
// sign the new tx
CTransaction txNewConst(tx);
int nIn = 0;
for (const auto& input : tx.vin) {
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
return false;
}
const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
SignatureData sigdata;
if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
return false;
}
UpdateTransaction(tx, nIn, sigdata);
nIn++;
}
return true;
}
bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
{
std::vector<CRecipient> vecSend;
// Turn the txout set into a CRecipient vector
for (size_t idx = 0; idx < tx.vout.size(); idx++)
{
const CTxOut& txOut = tx.vout[idx];
CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
vecSend.push_back(recipient);
}
coinControl.fAllowOtherInputs = true;
for (const CTxIn& txin : tx.vin)
coinControl.Select(txin.prevout);
CReserveKey reservekey(this);
CWalletTx wtx;
if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
return false;
}
if (nChangePosInOut != -1) {
tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
// we don't have the normal Create/Commit cycle, and don't want to risk reusing change,
// so just remove the key from the keypool here.
reservekey.KeepKey();
}
// Copy output sizes from new transaction; they may have had the fee subtracted from them
for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
// Add new txins (keeping original txin scriptSig/order)
for (const CTxIn& txin : wtx.tx->vin)
{
if (!coinControl.IsSelected(txin.prevout))
{
tx.vin.push_back(txin);
if (lockUnspents)
{
LOCK2(cs_main, cs_wallet);
LockCoin(txin.prevout);
}
}
}
return true;
}
bool CWallet::CreateTransactionWithAssets(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
std::string& strFailReason, const CCoinControl& coin_control, const std::vector<CNewAsset> assets, const CTxDestination destination, const AssetType& type, bool sign)
{
CReissueAsset reissueAsset;
return CreateTransactionAll(vecSend, wtxNew, reservekey, nFeeRet, nChangePosInOut, strFailReason, coin_control, true, assets, destination, false, false, reissueAsset, type, sign);
}
bool CWallet::CreateTransactionWithTransferAsset(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
std::string& strFailReason, const CCoinControl& coin_control, bool sign)
{
CNewAsset asset;
CReissueAsset reissueAsset;
CTxDestination destination;
AssetType assetType = AssetType::INVALID;
return CreateTransactionAll(vecSend, wtxNew, reservekey, nFeeRet, nChangePosInOut, strFailReason, coin_control, false, asset, destination, true, false, reissueAsset, assetType, sign);
}
bool CWallet::CreateTransactionWithReissueAsset(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
std::string& strFailReason, const CCoinControl& coin_control, const CReissueAsset& reissueAsset, const CTxDestination destination, bool sign)
{
CNewAsset asset;
AssetType assetType = AssetType::REISSUE;
return CreateTransactionAll(vecSend, wtxNew, reservekey, nFeeRet, nChangePosInOut, strFailReason, coin_control, false, asset, destination, false, true, reissueAsset, assetType, sign);
}
bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
std::string& strFailReason, const CCoinControl& coin_control, bool sign)
{
CNewAsset asset;
CReissueAsset reissueAsset;
CTxDestination destination;
AssetType assetType = AssetType::INVALID;
return CreateTransactionAll(vecSend, wtxNew, reservekey, nFeeRet, nChangePosInOut, strFailReason, coin_control, false, asset, destination, false, false, reissueAsset, assetType, sign);
}
bool CWallet::CreateTransactionAll(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey,
CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason,
const CCoinControl& coin_control, bool fNewAsset, const CNewAsset& asset,
const CTxDestination destination, bool fTransferAsset, bool fReissueAsset,
const CReissueAsset& reissueAsset, const AssetType& assetType, bool sign)
{
std::vector<CNewAsset> assets;
assets.push_back(asset);
return CreateTransactionAll(vecSend, wtxNew, reservekey, nFeeRet, nChangePosInOut, strFailReason, coin_control,
fNewAsset, assets, destination, fTransferAsset, fReissueAsset, reissueAsset, assetType,
sign);
}
bool CWallet::CreateTransactionAll(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey,
CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason,
const CCoinControl& coin_control, bool fNewAsset,
const std::vector<CNewAsset> assets, const CTxDestination destination,
bool fTransferAsset, bool fReissueAsset, const CReissueAsset& reissueAsset,
const AssetType& assetType, bool sign)
{
/** ATL START */
if (!AreAssetsDeployed() && (fTransferAsset || fNewAsset || fReissueAsset))
return false;
if (fNewAsset && (assets.size() < 1 || !IsValidDestination(destination)))
return error("%s : Tried creating a new asset transaction and the asset was null or the destination was invalid", __func__);
if ((fNewAsset && fTransferAsset) || (fReissueAsset && fTransferAsset) || (fReissueAsset && fNewAsset))
return error("%s : Only one type of asset transaction allowed per transaction");
if (fReissueAsset && (reissueAsset.IsNull() || !IsValidDestination(destination)))
return error("%s : Tried reissuing an asset and the reissue data was null or the destination was invalid", __func__);
/** ATL END */
CAmount nValue = 0;
std::map<std::string, CAmount> mapAssetValue;
int nChangePosRequest = nChangePosInOut;
unsigned int nSubtractFeeFromAmount = 0;
for (const auto& recipient : vecSend)
{
/** ATL START */
if (fTransferAsset || fReissueAsset || assetType == AssetType::SUB || assetType == AssetType::UNIQUE) {
CAssetTransfer assetTransfer;
std::string address;
if (TransferAssetFromScript(recipient.scriptPubKey, assetTransfer, address)) {
if (!mapAssetValue.count(assetTransfer.strName))
mapAssetValue[assetTransfer.strName] = 0;
if (assetTransfer.nAmount <= 0) {
strFailReason = _("Asset Transfer amounts must be greater than 0");
return false;
}
mapAssetValue[assetTransfer.strName] += assetTransfer.nAmount;
}
}
/** ATL END */
if (nValue < 0 || recipient.nAmount < 0)
{
strFailReason = _("Transaction amounts must not be negative");
return false;
}
nValue += recipient.nAmount;
if (recipient.fSubtractFeeFromAmount)
nSubtractFeeFromAmount++;
}
if (vecSend.empty())
{
strFailReason = _("Transaction must have at least one recipient");
return false;
}
wtxNew.fTimeReceivedIsTxTime = true;
wtxNew.BindWallet(this);
CMutableTransaction txNew;
// Discourage fee sniping.
//
// For a large miner the value of the transactions in the best block and
// the mempool can exceed the cost of deliberately attempting to mine two
// blocks to orphan the current best block. By setting nLockTime such that
// only the next block can include the transaction, we discourage this
// practice as the height restricted and limited blocksize gives miners
// considering fee sniping fewer options for pulling off this attack.
//
// A simple way to think about this is from the wallet's point of view we
// always want the blockchain to move forward. By setting nLockTime this
// way we're basically making the statement that we only want this
// transaction to appear in the next block; we don't want to potentially
// encourage reorgs by allowing transactions to appear at lower heights
// than the next block in forks of the best chain.
//
// Of course, the subsidy is high enough, and transaction volume low
// enough, that fee sniping isn't a problem yet, but by implementing a fix
// now we ensure code won't be written that makes assumptions about
// nLockTime that preclude a fix later.
txNew.nLockTime = chainActive.Height();
// Secondly occasionally randomly pick a nLockTime even further back, so
// that transactions that are delayed after signing for whatever reason,
// e.g. high-latency mix networks and some CoinJoin implementations, have
// better privacy.
if (GetRandInt(10) == 0)
txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
FeeCalculation feeCalc;
CAmount nFeeNeeded;
unsigned int nBytes;
{
std::set<CInputCoin> setCoins;
std::set<CInputCoin> setAssets;
LOCK2(cs_main, cs_wallet);
{
/** ATL START */
std::vector<COutput> vAvailableCoins;
std::map<std::string, std::vector<COutput> > mapAssetCoins;
if (fTransferAsset || fReissueAsset || assetType == AssetType::SUB || assetType == AssetType::UNIQUE)
AvailableCoinsWithAssets(vAvailableCoins, mapAssetCoins, true, &coin_control);
else
AvailableCoins(vAvailableCoins, true, &coin_control);
/** ATL END */
// Create change script that will be used if we need change
// TODO: pass in scriptChange instead of reservekey so
// change transaction isn't always pay-to-atlas-address
CScript scriptChange;
// coin control: send change to custom address
if (!boost::get<CNoDestination>(&coin_control.destChange)) {
scriptChange = GetScriptForDestination(coin_control.destChange);
} else {
// no coin control: send change to newly generated address
CKeyID keyID;
if (!CreateNewChangeAddress(reservekey, keyID, strFailReason))
return false;
scriptChange = GetScriptForDestination(keyID);
}
CTxOut change_prototype_txout(0, scriptChange);
size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
nFeeRet = 0;
bool pick_new_inputs = true;
CAmount nValueIn = 0;
// Start with no fee and loop until there is enough fee
while (true)
{
std::map<std::string, CAmount> mapAssetsIn;
nChangePosInOut = nChangePosRequest;
txNew.vin.clear();
txNew.vout.clear();
wtxNew.fFromMe = true;
bool fFirst = true;
CAmount nValueToSelect = nValue;
if (nSubtractFeeFromAmount == 0)
nValueToSelect += nFeeRet;
// vouts to the payees
for (const auto& recipient : vecSend)
{
CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
if (recipient.fSubtractFeeFromAmount)
{
assert(nSubtractFeeFromAmount != 0);
txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
if (fFirst) // first receiver pays the remainder not divisible by output count
{
fFirst = false;
txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
}
}
if (IsDust(txout, ::dustRelayFee) && !IsScriptTransferAsset(recipient.scriptPubKey)) /** ATL START */ /** ATL END */
{
if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
{
if (txout.nValue < 0)
strFailReason = _("The transaction amount is too small to pay the fee");
else
strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
}
else {
strFailReason = _("Transaction amount too small");
}
return false;
}
txNew.vout.push_back(txout);
}
// Choose coins to use
if (pick_new_inputs) {
nValueIn = 0;
setCoins.clear();
if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
{
strFailReason = _("Insufficient funds");
return false;
}
/** ATL START */
if (AreAssetsDeployed()) {
setAssets.clear();
mapAssetsIn.clear();
if (!SelectAssets(mapAssetCoins, mapAssetValue, setAssets, mapAssetsIn)) {
strFailReason = _("Insufficient asset funds");
return false;
}
}
/** ATL END */
}
const CAmount nChange = nValueIn - nValueToSelect;
/** ATL START */
if (AreAssetsDeployed()) {
// Add the change for the assets
std::map<std::string, CAmount> mapAssetChange;
for (auto asset : mapAssetValue) {
if (mapAssetsIn.count(asset.first))
mapAssetChange.insert(
std::make_pair(asset.first, (mapAssetsIn.at(asset.first) - asset.second)));
}
for (auto assetChange : mapAssetChange) {
if (assetChange.second > 0) {
CScript scriptAssetChange = scriptChange;
CAssetTransfer assetTransfer(assetChange.first, assetChange.second);
assetTransfer.ConstructTransaction(scriptAssetChange);
CTxOut newAssetTxOut(0, scriptAssetChange);
txNew.vout.emplace_back(newAssetTxOut);
}
}
}
/** ATL END */
if (nChange > 0)
{
// Fill a vout to ourself
CTxOut newTxOut(nChange, scriptChange);
// Never create dust outputs; if we would, just
// add the dust to the fee.
if (IsDust(newTxOut, discard_rate))
{
nChangePosInOut = -1;
nFeeRet += nChange;
}
else
{
if (nChangePosInOut == -1)
{
// Insert change txn at random position:
nChangePosInOut = GetRandInt(txNew.vout.size()+1);
}
else if ((unsigned int)nChangePosInOut > txNew.vout.size())
{
strFailReason = _("Change index out of range");
return false;
}
std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
txNew.vout.insert(position, newTxOut);
}
} else {
nChangePosInOut = -1;
}
/** ATL START */
if (AreAssetsDeployed()) {
if (fNewAsset) {
for (auto asset : assets) {
// Create the owner token output for non-unique assets
if (assetType != AssetType::UNIQUE) {
CScript ownerScript = GetScriptForDestination(destination);
asset.ConstructOwnerTransaction(ownerScript);
CTxOut ownerTxOut(0, ownerScript);
txNew.vout.push_back(ownerTxOut);
}
// Create the asset transaction and push it back so it is the last CTxOut in the transaction
CScript scriptPubKey = GetScriptForDestination(destination);
asset.ConstructTransaction(scriptPubKey);
CTxOut newTxOut(0, scriptPubKey);
txNew.vout.push_back(newTxOut);
}
} else if (fReissueAsset) {
// Create the asset transaction and push it back so it is the last CTxOut in the transaction
CScript reissueScript = GetScriptForDestination(destination);
// Create the scriptPubKeys for the reissue data, and that owner asset
reissueAsset.ConstructTransaction(reissueScript);
CTxOut reissueTxOut(0, reissueScript);
txNew.vout.push_back(reissueTxOut);
}
}
/** ATL END */
// Fill vin
//
// Note how the sequence number is set to non-maxint so that
// the nLockTime set above actually works.
//
// BIP125 defines opt-in RBF as any nSequence < maxint-1, so
// we use the highest possible value in that range (maxint-2)
// to avoid conflicting with other possible uses of nSequence,
// and in the spirit of "smallest possible change from prior
// behavior."
// const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
const uint32_t nSequence = CTxIn::SEQUENCE_FINAL - 1;
for (const auto& coin : setCoins)
txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
nSequence));
/** ATL START */
if (AreAssetsDeployed()) {
for (const auto &asset : setAssets)
txNew.vin.push_back(CTxIn(asset.outpoint, CScript(),
nSequence));
}
/** ATL END */
// Add the new asset inputs into the tempSet so the dummysigntx will add the correct amount of sigsß
std::set<CInputCoin> tempSet = setCoins;
tempSet.insert(setAssets.begin(), setAssets.end());
// Fill in dummy signatures for fee calculation.
if (!DummySignTx(txNew, tempSet)) {
strFailReason = _("Signing transaction for fee calculation failed");
return false;
}
nBytes = GetVirtualTransactionSize(txNew);
// Remove scriptSigs to eliminate the fee calculation dummy signatures
for (auto& vin : txNew.vin) {
vin.scriptSig = CScript();
vin.scriptWitness.SetNull();
}
nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
// If we made it here and we aren't even able to meet the relay fee on the next pass, give up
// because we must be at the maximum allowed fee.
if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
{
strFailReason = _("Transaction too large for fee policy");
return false;
}
if (nFeeRet >= nFeeNeeded) {
// Reduce fee to only the needed amount if possible. This
// prevents potential overpayment in fees if the coins
// selected to meet nFeeNeeded result in a transaction that
// requires less fee than the prior iteration.
// If we have no change and a big enough excess fee, then
// try to construct transaction again only without picking
// new inputs. We now know we only need the smaller fee
// (because of reduced tx size) and so we should add a
// change output. Only try this once.
if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
unsigned int tx_size_with_change = nBytes + change_prototype_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
CAmount fee_needed_with_change = GetMinimumFee(tx_size_with_change, coin_control, ::mempool, ::feeEstimator, nullptr);
CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
pick_new_inputs = false;
nFeeRet = fee_needed_with_change;
continue;
}
}
// If we have change output already, just increase it
if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
CAmount extraFeePaid = nFeeRet - nFeeNeeded;
std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
change_position->nValue += extraFeePaid;
nFeeRet -= extraFeePaid;
}
break; // Done, enough fee included.
}
else if (!pick_new_inputs) {
// This shouldn't happen, we should have had enough excess
// fee to pay for the new output and still meet nFeeNeeded
// Or we should have just subtracted fee from recipients and
// nFeeNeeded should not have changed
strFailReason = _("Transaction fee and change calculation failed");
return false;
}
// Try to reduce change to include necessary fee
if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
// Only reduce change if remaining amount is still a large enough output.
if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
change_position->nValue -= additionalFeeNeeded;
nFeeRet += additionalFeeNeeded;
break; // Done, able to increase fee from change
}
}
// If subtracting fee from recipients, we now know what fee we
// need to subtract, we have no reason to reselect inputs
if (nSubtractFeeFromAmount > 0) {
pick_new_inputs = false;
}
// Include more fee and try again.
nFeeRet = nFeeNeeded;
continue;
}
}
if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
if (sign)
{
CTransaction txNewConst(txNew);
int nIn = 0;
for (const auto& coin : setCoins)
{
const CScript& scriptPubKey = coin.txout.scriptPubKey;
SignatureData sigdata;
if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
{
strFailReason = _("Signing transaction failed");
return false;
} else {
UpdateTransaction(txNew, nIn, sigdata);
}
nIn++;
}
/** ATL START */
if (AreAssetsDeployed()) {
for (const auto &asset : setAssets) {
const CScript &scriptPubKey = asset.txout.scriptPubKey;
SignatureData sigdata;
if (!ProduceSignature(
TransactionSignatureCreator(this, &txNewConst, nIn, asset.txout.nValue, SIGHASH_ALL),
scriptPubKey, sigdata)) {
strFailReason = _("Signing asset transaction failed");
return false;
} else {
UpdateTransaction(txNew, nIn, sigdata);
}
nIn++;
}
}
/** ATL END */
}
// Embed the constructed transaction data in wtxNew.
wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
// Limit size
if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
{
strFailReason = _("Transaction too large");
return false;
}
}
if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
// Lastly, ensure this tx will pass the mempool's chain limits
LockPoints lp;
CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
CTxMemPool::setEntries setAncestors;
size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
std::string errString;
if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
strFailReason = _("Transaction has too long of a mempool chain");
return false;
}
}
LogPrintf("Fee Calculation: Fee:%d Bytes:%u Needed:%d Tgt:%d (requested %d) Reason:\"%s\" Decay %.5f: Estimation: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out) Fail: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out)\n",
nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
feeCalc.est.pass.start, feeCalc.est.pass.end,
100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
feeCalc.est.fail.start, feeCalc.est.fail.end,
100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
return true;
}
/**
* Call after CreateTransaction unless you want to abort
*/
bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
{
{
LOCK2(cs_main, cs_wallet);
LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
{
// Take key pair from key pool so it won't be used again
reservekey.KeepKey();
// Add tx to wallet, because if it has change it's also ours,
// otherwise just for transaction history.
AddToWallet(wtxNew);
// Notify that old coins are spent
for (const CTxIn& txin : wtxNew.tx->vin)
{
CWalletTx &coin = mapWallet[txin.prevout.hash];
coin.BindWallet(this);
NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
}
}
// Track how many getdata requests our transaction gets
mapRequestCount[wtxNew.GetHash()] = 0;
if (fBroadcastTransactions)
{
// Broadcast
if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
// TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
AbandonTransaction(wtxNew.tx->GetHash());
return false;
} else {
wtxNew.RelayWalletTransaction(connman);
}
}
}
return true;
}
void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
CWalletDB walletdb(*dbw);
return walletdb.ListAccountCreditDebit(strAccount, entries);
}
bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
{
CWalletDB walletdb(*dbw);
return AddAccountingEntry(acentry, &walletdb);
}
bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
{
if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
return false;
}
laccentries.push_back(acentry);
CAccountingEntry & entry = laccentries.back();
wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair(nullptr, &entry)));
return true;
}
DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
{
LOCK2(cs_main, cs_wallet);
fFirstRunRet = false;
DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
if (nLoadWalletRet == DB_NEED_REWRITE)
{
if (dbw->Rewrite("\x04pool"))
{
setInternalKeyPool.clear();
setExternalKeyPool.clear();
m_pool_key_to_index.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
}
// This wallet is in its first run if all of these are empty
fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty();
if (nLoadWalletRet != DB_LOAD_OK)
return nLoadWalletRet;
uiInterface.LoadWallet(this);
return DB_LOAD_OK;
}
DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
{
AssertLockHeld(cs_wallet); // mapWallet
DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
for (uint256 hash : vHashOut)
mapWallet.erase(hash);
if (nZapSelectTxRet == DB_NEED_REWRITE)
{
if (dbw->Rewrite("\x04pool"))
{
setInternalKeyPool.clear();
setExternalKeyPool.clear();
m_pool_key_to_index.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
}
if (nZapSelectTxRet != DB_LOAD_OK)
return nZapSelectTxRet;
MarkDirty();
return DB_LOAD_OK;
}
DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
{
DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
if (nZapWalletTxRet == DB_NEED_REWRITE)
{
if (dbw->Rewrite("\x04pool"))
{
LOCK(cs_wallet);
setInternalKeyPool.clear();
setExternalKeyPool.clear();
m_pool_key_to_index.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
}
if (nZapWalletTxRet != DB_LOAD_OK)
return nZapWalletTxRet;
return DB_LOAD_OK;
}
bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
{
bool fUpdated = false;
{
LOCK(cs_wallet); // mapAddressBook
std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
fUpdated = mi != mapAddressBook.end();
mapAddressBook[address].name = strName;
if (!strPurpose.empty()) /* update purpose only if requested */
mapAddressBook[address].purpose = strPurpose;
}
NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(EncodeDestination(address), strPurpose))
return false;
return CWalletDB(*dbw).WriteName(EncodeDestination(address), strName);
}
bool CWallet::DelAddressBook(const CTxDestination& address)
{
{
LOCK(cs_wallet); // mapAddressBook
// Delete destdata tuples associated with address
std::string strAddress = EncodeDestination(address);
for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
{
CWalletDB(*dbw).EraseDestData(strAddress, item.first);
}
mapAddressBook.erase(address);
}
NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
CWalletDB(*dbw).ErasePurpose(EncodeDestination(address));
return CWalletDB(*dbw).EraseName(EncodeDestination(address));
}
const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
{
CTxDestination address;
if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
auto mi = mapAddressBook.find(address);
if (mi != mapAddressBook.end()) {
return mi->second.name;
}
}
// A scriptPubKey that doesn't have an entry in the address book is
// associated with the default account ("").
const static std::string DEFAULT_ACCOUNT_NAME;
return DEFAULT_ACCOUNT_NAME;
}
/**
* Mark old keypool keys as used,
* and generate all new keys
*/
bool CWallet::NewKeyPool()
{
{
LOCK(cs_wallet);
CWalletDB walletdb(*dbw);
for (int64_t nIndex : setInternalKeyPool) {
walletdb.ErasePool(nIndex);
}
setInternalKeyPool.clear();
for (int64_t nIndex : setExternalKeyPool) {
walletdb.ErasePool(nIndex);
}
setExternalKeyPool.clear();
m_pool_key_to_index.clear();
if (!TopUpKeyPool()) {
return false;
}
LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
}
return true;
}
size_t CWallet::KeypoolCountExternalKeys()
{
AssertLockHeld(cs_wallet); // setExternalKeyPool
return setExternalKeyPool.size();
}
void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
{
AssertLockHeld(cs_wallet);
if (keypool.fInternal) {
setInternalKeyPool.insert(nIndex);
} else {
setExternalKeyPool.insert(nIndex);
}
m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
// If no metadata exists yet, create a default with the pool key's
// creation time. Note that this may be overwritten by actually
// stored metadata for that key later, which is fine.
CKeyID keyid = keypool.vchPubKey.GetID();
if (mapKeyMetadata.count(keyid) == 0)
mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
}
bool CWallet::TopUpKeyPool(unsigned int kpSize)
{
{
LOCK(cs_wallet);
if (IsLocked())
return false;
// Top up key pool
unsigned int nTargetSize;
if (kpSize > 0)
nTargetSize = kpSize;
else
nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
// count amount of available keys (internal, external)
// make sure the keypool of external and internal keys fits the user selected target (-keypool)
int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
{
// don't create extra internal keys
missingInternal = 0;
}
bool internal = false;
CWalletDB walletdb(*dbw);
for (int64_t i = missingInternal + missingExternal; i--;)
{
if (i < missingInternal) {
internal = true;
}
assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
int64_t index = ++m_max_keypool_index;
CPubKey pubkey(GenerateNewKey(walletdb, internal));
if (!walletdb.WritePool(index, CKeyPool(pubkey, internal))) {
throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
}
if (internal) {
setInternalKeyPool.insert(index);
} else {
setExternalKeyPool.insert(index);
}
m_pool_key_to_index[pubkey.GetID()] = index;
}
if (missingInternal + missingExternal > 0) {
LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
}
}
return true;
}
void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
{
nIndex = -1;
keypool.vchPubKey = CPubKey();
{
LOCK(cs_wallet);
if (!IsLocked())
TopUpKeyPool();
bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
// Get the oldest key
if(setKeyPool.empty())
return;
CWalletDB walletdb(*dbw);
auto it = setKeyPool.begin();
nIndex = *it;
setKeyPool.erase(it);
if (!walletdb.ReadPool(nIndex, keypool)) {
throw std::runtime_error(std::string(__func__) + ": read failed");
}
if (!HaveKey(keypool.vchPubKey.GetID())) {
throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
}
if (keypool.fInternal != fReturningInternal) {
throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
}
assert(keypool.vchPubKey.IsValid());
m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
LogPrintf("keypool reserve %d\n", nIndex);
}
}
void CWallet::KeepKey(int64_t nIndex)
{
// Remove from key pool
CWalletDB walletdb(*dbw);
walletdb.ErasePool(nIndex);
LogPrintf("keypool keep %d\n", nIndex);
}
void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
{
// Return to key pool
{
LOCK(cs_wallet);
if (fInternal) {
setInternalKeyPool.insert(nIndex);
} else {
setExternalKeyPool.insert(nIndex);
}
m_pool_key_to_index[pubkey.GetID()] = nIndex;
}
LogPrintf("keypool return %d\n", nIndex);
}
bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
{
CKeyPool keypool;
{
LOCK(cs_wallet);
int64_t nIndex = 0;
ReserveKeyFromKeyPool(nIndex, keypool, internal);
if (nIndex == -1)
{
if (IsLocked()) return false;
CWalletDB walletdb(*dbw);
result = GenerateNewKey(walletdb, internal);
return true;
}
KeepKey(nIndex);
result = keypool.vchPubKey;
}
return true;
}
static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
if (setKeyPool.empty()) {
return GetTime();
}
CKeyPool keypool;
int64_t nIndex = *(setKeyPool.begin());
if (!walletdb.ReadPool(nIndex, keypool)) {
throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
}
assert(keypool.vchPubKey.IsValid());
return keypool.nTime;
}
int64_t CWallet::GetOldestKeyPoolTime()
{
LOCK(cs_wallet);
CWalletDB walletdb(*dbw);
// load oldest key from keypool, get time and return
int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
}
return oldestKey;
}
std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
{
std::map<CTxDestination, CAmount> balances;
{
LOCK(cs_wallet);
for (const auto& walletEntry : mapWallet)
{
const CWalletTx *pcoin = &walletEntry.second;
if (!pcoin->IsTrusted())
continue;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
continue;
for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
{
CTxDestination addr;
if (!IsMine(pcoin->tx->vout[i]))
continue;
if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
continue;
CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
if (!balances.count(addr))
balances[addr] = 0;
balances[addr] += n;
}
}
}
return balances;
}
std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
{
AssertLockHeld(cs_wallet); // mapWallet
std::set< std::set<CTxDestination> > groupings;
std::set<CTxDestination> grouping;
for (const auto& walletEntry : mapWallet)
{
const CWalletTx *pcoin = &walletEntry.second;
if (pcoin->tx->vin.size() > 0)
{
bool any_mine = false;
// group all input addresses with each other
for (CTxIn txin : pcoin->tx->vin)
{
CTxDestination address;
if(!IsMine(txin)) /* If this input isn't mine, ignore it */
continue;
if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
continue;
grouping.insert(address);
any_mine = true;
}
// group change with input addresses
if (any_mine)
{
for (CTxOut txout : pcoin->tx->vout)
if (IsChange(txout))
{
CTxDestination txoutAddr;
if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
continue;
grouping.insert(txoutAddr);
}
}
if (grouping.size() > 0)
{
groupings.insert(grouping);
grouping.clear();
}
}
// group lone addrs by themselves
for (const auto& txout : pcoin->tx->vout)
if (IsMine(txout))
{
CTxDestination address;
if(!ExtractDestination(txout.scriptPubKey, address))
continue;
grouping.insert(address);
groupings.insert(grouping);
grouping.clear();
}
}
std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
for (std::set<CTxDestination> _grouping : groupings)
{
// make a set of all the groups hit by this new group
std::set< std::set<CTxDestination>* > hits;
std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
for (CTxDestination address : _grouping)
if ((it = setmap.find(address)) != setmap.end())
hits.insert((*it).second);
// merge all hit groups into a new single group and delete old groups
std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
for (std::set<CTxDestination>* hit : hits)
{
merged->insert(hit->begin(), hit->end());
uniqueGroupings.erase(hit);
delete hit;
}
uniqueGroupings.insert(merged);
// update setmap
for (CTxDestination element : *merged)
setmap[element] = merged;
}
std::set< std::set<CTxDestination> > ret;
for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
{
ret.insert(*uniqueGrouping);
delete uniqueGrouping;
}
return ret;
}
std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
{
LOCK(cs_wallet);
std::set<CTxDestination> result;
for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
{
const CTxDestination& address = item.first;
const std::string& strName = item.second.name;
if (strName == strAccount)
result.insert(address);
}
return result;
}
bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
{
if (nIndex == -1)
{
CKeyPool keypool;
pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
if (nIndex != -1)
vchPubKey = keypool.vchPubKey;
else {
return false;
}
fInternal = keypool.fInternal;
}
assert(vchPubKey.IsValid());
pubkey = vchPubKey;
return true;
}
void CReserveKey::KeepKey()
{
if (nIndex != -1)
pwallet->KeepKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CReserveKey::ReturnKey()
{
if (nIndex != -1) {
pwallet->ReturnKey(nIndex, fInternal, vchPubKey);
}
nIndex = -1;
vchPubKey = CPubKey();
}
void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
{
AssertLockHeld(cs_wallet);
bool internal = setInternalKeyPool.count(keypool_id);
if (!internal) assert(setExternalKeyPool.count(keypool_id));
std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
auto it = setKeyPool->begin();
CWalletDB walletdb(*dbw);
while (it != std::end(*setKeyPool)) {
const int64_t& index = *(it);
if (index > keypool_id) break; // set*KeyPool is ordered
CKeyPool keypool;
if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary
m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
}
walletdb.ErasePool(index);
LogPrintf("keypool index %d removed\n", index);
it = setKeyPool->erase(it);
}
}
void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
{
std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
CPubKey pubkey;
if (!rKey->GetReservedKey(pubkey))
{
return;
}
script = rKey;
script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
}
void CWallet::LockCoin(const COutPoint& output)
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.insert(output);
}
void CWallet::UnlockCoin(const COutPoint& output)
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.erase(output);
}
void CWallet::UnlockAllCoins()
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.clear();
}
bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
{
AssertLockHeld(cs_wallet); // setLockedCoins
COutPoint outpt(hash, n);
return (setLockedCoins.count(outpt) > 0);
}
void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
{
AssertLockHeld(cs_wallet); // setLockedCoins
for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
it != setLockedCoins.end(); it++) {
COutPoint outpt = (*it);
vOutpts.push_back(outpt);
}
}
/** @} */ // end of Actions
void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
AssertLockHeld(cs_wallet); // mapKeyMetadata
mapKeyBirth.clear();
// get birth times for keys with metadata
for (const auto& entry : mapKeyMetadata) {
if (entry.second.nCreateTime) {
mapKeyBirth[entry.first] = entry.second.nCreateTime;
}
}
// map in which we'll infer heights of other keys
CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
for (const CKeyID &keyid : GetKeys()) {
if (mapKeyBirth.count(keyid) == 0)
mapKeyFirstBlock[keyid] = pindexMax;
}
// if there are no such keys, we're done
if (mapKeyFirstBlock.empty())
return;
// find first block that affects those keys, if there are any left
std::vector<CKeyID> vAffected;
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
// iterate over all wallet transactions...
const CWalletTx &wtx = (*it).second;
BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
// ... which are already in a block
int nHeight = blit->second->nHeight;
for (const CTxOut &txout : wtx.tx->vout) {
// iterate over all their outputs
CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
for (const CKeyID &keyid : vAffected) {
// ... and all their affected keys
std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
rit->second = blit->second;
}
vAffected.clear();
}
}
}
// Extract block timestamps for those keys
for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
}
/**
* Compute smart timestamp for a transaction being added to the wallet.
*
* Logic:
* - If sending a transaction, assign its timestamp to the current time.
* - If receiving a transaction outside a block, assign its timestamp to the
* current time.
* - If receiving a block with a future timestamp, assign all its (not already
* known) transactions' timestamps to the current time.
* - If receiving a block with a past timestamp, before the most recent known
* transaction (that we care about), assign all its (not already known)
* transactions' timestamps to the same timestamp as that most-recent-known
* transaction.
* - If receiving a block with a past timestamp, but after the most recent known
* transaction, assign all its (not already known) transactions' timestamps to
* the block time.
*
* For more information see CWalletTx::nTimeSmart,
* https://atlastalk.org/?topic=54527, or
* https://github.com/AtlasProject/Atlascoin/pull/1393.
*/
unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
{
unsigned int nTimeSmart = wtx.nTimeReceived;
if (!wtx.hashUnset()) {
if (mapBlockIndex.count(wtx.hashBlock)) {
int64_t latestNow = wtx.nTimeReceived;
int64_t latestEntry = 0;
// Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
int64_t latestTolerated = latestNow + 300;
const TxItems& txOrdered = wtxOrdered;
for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
CWalletTx* const pwtx = it->second.first;
if (pwtx == &wtx) {
continue;
}
CAccountingEntry* const pacentry = it->second.second;
int64_t nSmartTime;
if (pwtx) {
nSmartTime = pwtx->nTimeSmart;
if (!nSmartTime) {
nSmartTime = pwtx->nTimeReceived;
}
} else {
nSmartTime = pacentry->nTime;
}
if (nSmartTime <= latestTolerated) {
latestEntry = nSmartTime;
if (nSmartTime > latestNow) {
latestNow = nSmartTime;
}
break;
}
}
int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
} else {
LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
}
}
return nTimeSmart;
}
bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
{
if (boost::get<CNoDestination>(&dest))
return false;
mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
return CWalletDB(*dbw).WriteDestData(EncodeDestination(dest), key, value);
}
bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
{
if (!mapAddressBook[dest].destdata.erase(key))
return false;
return CWalletDB(*dbw).EraseDestData(EncodeDestination(dest), key);
}
bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
{
mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
return true;
}
bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
{
std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
if(i != mapAddressBook.end())
{
CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
if(j != i->second.destdata.end())
{
if(value)
*value = j->second;
return true;
}
}
return false;
}
std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
{
LOCK(cs_wallet);
std::vector<std::string> values;
for (const auto& address : mapAddressBook) {
for (const auto& data : address.second.destdata) {
if (!data.first.compare(0, prefix.size(), prefix)) {
values.emplace_back(data.second);
}
}
}
return values;
}
CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
{
// needed to restore wallet transaction meta data after -zapwallettxes
std::vector<CWalletTx> vWtx;
if (gArgs.GetBoolArg("-zapwallettxes", false)) {
uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
std::unique_ptr<CWallet> tempWallet(new CWallet(std::move(dbw)));
DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
if (nZapWalletRet != DB_LOAD_OK) {
InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
return nullptr;
}
}
uiInterface.InitMessage(_("Loading wallet..."));
int64_t nStart = GetTimeMillis();
bool fFirstRun = true;
std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
CWallet *walletInstance = new CWallet(std::move(dbw));
DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT) {
InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
return nullptr;
}
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."),
walletFile));
}
else if (nLoadWalletRet == DB_TOO_NEW) {
InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
return nullptr;
}
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
return nullptr;
}
else {
InitError(strprintf(_("Error loading %s"), walletFile));
return nullptr;
}
}
if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < walletInstance->GetVersion())
{
InitError(_("Cannot downgrade wallet"));
return nullptr;
}
walletInstance->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
if (!gArgs.GetBoolArg("-usehd", true)) {
InitError(strprintf(_("Error creating %s: You can't create non-HD wallets with this version."), walletFile));
return nullptr;
}
walletInstance->SetMinVersion(FEATURE_NO_DEFAULT_KEY);
// generate a new seed
CPubKey seed = walletInstance->GenerateNewSeed();
if (!walletInstance->SetHDSeed(seed))
throw std::runtime_error(std::string(__func__) + ": Storing HD seed failed");
// Top up the keypool
if (!walletInstance->TopUpKeyPool()) {
InitError(_("Unable to generate initial keys") += "\n");
return nullptr;
}
walletInstance->SetBestChain(chainActive.GetLocator());
}
else if (gArgs.IsArgSet("-usehd")) {
bool useHD = gArgs.GetBoolArg("-usehd", true);
if (walletInstance->IsHDEnabled() && !useHD) {
InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
return nullptr;
}
if (!walletInstance->IsHDEnabled() && useHD) {
InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
return nullptr;
}
}
LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
RegisterValidationInterface(walletInstance);
// Try to top up keypool. No-op if the wallet is locked.
walletInstance->TopUpKeyPool();
CBlockIndex *pindexRescan = chainActive.Genesis();
if (!gArgs.GetBoolArg("-rescan", false))
{
CWalletDB walletdb(*walletInstance->dbw);
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = FindForkInGlobalIndex(chainActive, locator);
}
if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
{
//We can't rescan beyond non-pruned blocks, stop and throw an error
//this might happen if a user uses an old wallet within a pruned node
// or if he ran -disablewallet for a longer time, then decided to re-enable
if (fPruneMode)
{
CBlockIndex *block = chainActive.Tip();
while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
block = block->pprev;
if (pindexRescan != block) {
InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
return nullptr;
}
}
uiInterface.InitMessage(_("Rescanning..."));
LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
// No need to read and scan block if block was created before
// our wallet birthday (as adjusted for block time variability)
while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
pindexRescan = chainActive.Next(pindexRescan);
}
nStart = GetTimeMillis();
walletInstance->ScanForWalletTransactions(pindexRescan, nullptr, true);
LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
walletInstance->SetBestChain(chainActive.GetLocator());
walletInstance->dbw->IncrementUpdateCounter();
// Restore wallet transaction metadata after -zapwallettxes=1
if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
{
CWalletDB walletdb(*walletInstance->dbw);
for (const CWalletTx& wtxOld : vWtx)
{
uint256 hash = wtxOld.GetHash();
std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
if (mi != walletInstance->mapWallet.end())
{
const CWalletTx* copyFrom = &wtxOld;
CWalletTx* copyTo = &mi->second;
copyTo->mapValue = copyFrom->mapValue;
copyTo->vOrderForm = copyFrom->vOrderForm;
copyTo->nTimeReceived = copyFrom->nTimeReceived;
copyTo->nTimeSmart = copyFrom->nTimeSmart;
copyTo->fFromMe = copyFrom->fFromMe;
copyTo->strFromAccount = copyFrom->strFromAccount;
copyTo->nOrderPos = copyFrom->nOrderPos;
walletdb.WriteTx(*copyTo);
}
}
}
}
walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
{
LOCK(walletInstance->cs_wallet);
LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
}
return walletInstance;
}
std::atomic<bool> CWallet::fFlushScheduled(false);
void CWallet::postInitProcess(CScheduler& scheduler)
{
// Add wallet transactions that aren't already in a block to mempool
// Do this here as mempool requires genesis block to be loaded
ReacceptWalletTransactions();
// Run a thread to flush wallet periodically
if (!CWallet::fFlushScheduled.exchange(true)) {
scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
}
}
bool CWallet::BackupWallet(const std::string& strDest)
{
return dbw->Backup(strDest);
}
CKeyPool::CKeyPool()
{
nTime = GetTime();
fInternal = false;
}
CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
{
nTime = GetTime();
vchPubKey = vchPubKeyIn;
fInternal = internalIn;
}
CWalletKey::CWalletKey(int64_t nExpires)
{
nTimeCreated = (nExpires ? GetTime() : 0);
nTimeExpires = nExpires;
}
void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
{
// Update the tx's hashBlock
hashBlock = pindex->GetBlockHash();
// set the position of the transaction in the block
nIndex = posInBlock;
}
int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
{
if (hashUnset())
return 0;
AssertLockHeld(cs_main);
// Find the block it claims to be in
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !chainActive.Contains(pindex))
return 0;
pindexRet = pindex;
return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!IsCoinBase())
return 0;
return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
{
return ::AcceptToMemoryPool(mempool, state, tx, nullptr /* pfMissingInputs */,
nullptr /* plTxnReplaced */, false /* bypass_limits */, nAbsurdFee);
}
| [
"tytek2012@gmail.com"
] | tytek2012@gmail.com |
41e702ec33255a127c309654a3e85b58ca50e12c | 7a3fe1dccd3560a402dfb8f5c0ece7b3c4a054c0 | /ConsoleApplication1/Game.cpp | d04bd55df27fc4320281094507009ee40def4887 | [] | no_license | hasahmed/shapegame_cpp_win | 95b761d65c19a6b67b429a04b04c7501bd4c91c9 | db70d15e05a5ab379597576682e6843a9bb21b8d | refs/heads/master | 2021-10-02T22:02:47.976511 | 2018-12-01T11:35:04 | 2018-12-01T11:35:04 | 159,936,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,153 | cpp | #include <exception>
#include "shapegame"
using namespace shapegame;
Game* Game::_inst = nullptr;
shapegame::Game::Game(
unsigned int windowWidth,
unsigned int windowHeight,
std::string windowTitle
){
if (Game::_inst) {
throw std::runtime_error("Game can only be constructed once");
}
this->_window = std::make_unique<Window>(windowWidth, windowHeight, windowTitle);
this->scene = std::make_unique<Scene>();
this->_glHandler = std::make_unique<GLHandler>(_window.get(), *scene);
this->_vertexGenerator = std::make_unique<VertexGenerator>(_window.get());
Game::_inst = this;
}
shapegame::Game::Game() : Game(480, 480, "ShapeGame") {}
void shapegame::Game::run() {
std::cout << this->_window->info_string() << std::endl;
this->_glHandler->run();
}
shapegame::Window const* shapegame::Game::getWindow() {
return this->_window.get();
}
shapegame::Game& shapegame::Game::inst() {
if (Game::_inst) {
return *Game::_inst;
} else {
throw std::runtime_error("Instance of game cannot be returned before one was constructed");
}
} | [
"hasahmed@umail.iu.edu"
] | hasahmed@umail.iu.edu |
604f72ad2a5a8078f411d0a809875b7d4a9cb2b8 | 4d9bbd510b0af8778daba54fe2b1809216463fa6 | /build/Android/Debug/app/src/main/include/Fuse.Scripting.JSObjectUtils.h | 9d76447f80d5acfc3d200b971f3180c654411126 | [] | no_license | Koikka/mood_cal | c80666c4930bd8091e7fbe4869f5bad2f60953c1 | 9bf73aab2998aa7aa9e830aefb6dd52e25db710a | refs/heads/master | 2021-06-23T20:24:14.150644 | 2020-09-04T09:25:54 | 2020-09-04T09:25:54 | 137,458,064 | 0 | 0 | null | 2020-12-13T05:23:20 | 2018-06-15T07:53:15 | C++ | UTF-8 | C++ | false | false | 1,596 | h | // This file was generated based on node_modules/@fuse-open/fuselibs/Source/build/Fuse.Scripting/1.12.0/JSObjectUtils.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.h>
namespace g{namespace Fuse{namespace Scripting{struct Context;}}}
namespace g{namespace Fuse{namespace Scripting{struct JSObjectUtils;}}}
namespace g{namespace Fuse{namespace Scripting{struct Object;}}}
namespace g{
namespace Fuse{
namespace Scripting{
// public static class JSObjectUtils
// {
uClassType* JSObjectUtils_typeof();
void JSObjectUtils__Freeze_fn(::g::Fuse::Scripting::Object* ob, ::g::Fuse::Scripting::Context* c);
void JSObjectUtils__ValueOrDefault_fn(uType* __type, ::g::Fuse::Scripting::Object* obj, uString* name, void* defaultValue, uTRef __retval);
void JSObjectUtils__ValueOrDefault1_fn(uType* __type, uArray* args, int32_t* index, void* defaultValue, uTRef __retval);
struct JSObjectUtils : uObject
{
static void Freeze(::g::Fuse::Scripting::Object* ob, ::g::Fuse::Scripting::Context* c);
template<class T>
static T ValueOrDefault(uType* __type, ::g::Fuse::Scripting::Object* obj, uString* name, T defaultValue) { T __retval; return JSObjectUtils__ValueOrDefault_fn(__type, obj, name, uConstrain(__type->U(0), defaultValue), &__retval), __retval; }
template<class T>
static T ValueOrDefault1(uType* __type, uArray* args, int32_t index, T defaultValue) { T __retval; return JSObjectUtils__ValueOrDefault1_fn(__type, args, &index, uConstrain(__type->U(0), defaultValue), &__retval), __retval; }
};
// }
}}} // ::g::Fuse::Scripting
| [
"antti.koivisto@samk.fi"
] | antti.koivisto@samk.fi |
57c31a802f9aad39bc088ff9a39be85ae1dc2788 | dc888595f079eade0807235c1880642600974d95 | /seven day_1/build-gridLayout-Desktop_Qt_5_7_0_MinGW_32bit-Debug/debug/moc_widget.cpp | 0d029dcb973488f7f56de84cf6964c13872bc0a0 | [] | no_license | WenchaoZhang/qt_learing | 53377594e4102a68ddcadfab121d502ffab72a53 | 33e4dbdbd3a2c35e124c923b850e6e244aab320b | refs/heads/master | 2021-01-23T19:29:10.871224 | 2017-09-30T04:40:22 | 2017-09-30T04:40:22 | 102,826,803 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,550 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'widget.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.7.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../gridLayout/widget.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'widget.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.7.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
struct qt_meta_stringdata_Widget_t {
QByteArrayData data[1];
char stringdata0[7];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_Widget_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_Widget_t qt_meta_stringdata_Widget = {
{
QT_MOC_LITERAL(0, 0, 6) // "Widget"
},
"Widget"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_Widget[] = {
// content:
7, // 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
};
void Widget::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 QMetaObject Widget::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_Widget.data,
qt_meta_data_Widget, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *Widget::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *Widget::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_Widget.stringdata0))
return static_cast<void*>(const_cast< Widget*>(this));
return QWidget::qt_metacast(_clname);
}
int Widget::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"269426626@qq.com"
] | 269426626@qq.com |
cf1ab5a019e54fec47f920181ec845a62fca700b | fbf49ac1585c87725a0f5edcb80f1fe7a6c2041f | /SDK/BP_C058A_SkillMoveTeleport_classes.h | 5fea63434740597d23c72521a11a0294a7013833 | [] | no_license | zanzo420/DBZ-Kakarot-SDK | d5a69cd4b147d23538b496b7fa7ba4802fccf7ac | 73c2a97080c7ebedc7d538f72ee21b50627f2e74 | refs/heads/master | 2021-02-12T21:14:07.098275 | 2020-03-16T10:07:00 | 2020-03-16T10:07:00 | 244,631,123 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 699 | h | #pragma once
// Name: DBZKakarot, Version: 1.0.3
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_C058A_SkillMoveTeleport.BP_C058A_SkillMoveTeleport_C
// 0x0000 (0x0178 - 0x0178)
class UBP_C058A_SkillMoveTeleport_C : public UATActSkillMoveTeleport
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_C058A_SkillMoveTeleport.BP_C058A_SkillMoveTeleport_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.