blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 7
100
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 260
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 11.4k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 80
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 8
9.86M
| extension
stringclasses 52
values | content
stringlengths 8
9.86M
| authors
sequencelengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dcf644a9e37ce73e56581693935d4b5fcc13b0db | fa50ab598350886d1dc3190a0f4861f637668b95 | /source/tnn/device/x86/acc/x86_deconv_layer_acc.cc | e80f4e0ed0067084f7edf0934f9cd44d09b819cc | [
"BSD-3-Clause"
] | permissive | shaundai-tencent/TNN | d3cfe79da2cb5b70cbcf6fa9a00467da529485e4 | 6913aecb193c584e3fe4fcb32508d417744827c4 | refs/heads/master | 2023-07-17T14:57:52.586520 | 2021-08-17T06:04:19 | 2021-08-17T06:04:19 | 397,153,709 | 1 | 0 | NOASSERTION | 2021-08-17T07:32:31 | 2021-08-17T07:32:30 | null | UTF-8 | C++ | false | false | 2,647 | cc | // Tencent is pleased to support the open source community by making TNN available.
//
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "tnn/device/x86/acc/x86_deconv_layer_acc.h"
#include "tnn/device/x86/acc/deconvolution/x86_deconv_layer_common.h"
#include "tnn/interpreter/layer_resource_generator.h"
namespace TNN_NS {
Status X86DeconvLayerAcc::Init(Context *context, LayerParam *param, LayerResource *resource,
const std::vector<Blob *> &inputs, const std::vector<Blob *> &outputs) {
auto conv_param = dynamic_cast<ConvLayerParam *>(param);
CHECK_PARAM_NULL(conv_param);
auto conv_resource = dynamic_cast<ConvLayerResource *>(resource);
CHECK_PARAM_NULL(conv_resource);
Status ret;
if (conv_resource->filter_handle.GetDataType() == DATA_TYPE_HALF) {
LayerResource *fp32_res = nullptr;
RETURN_ON_NEQ(ConvertHalfResource(LAYER_DECONVOLUTION, conv_resource, &fp32_res), TNN_OK);
conv_acc_f32_resource_ = std::shared_ptr<LayerResource>(fp32_res);
ret = X86LayerAcc::Init(context, param, conv_acc_f32_resource_.get(), inputs, outputs);
} else {
ret = X86LayerAcc::Init(context, param, resource, inputs, outputs);
}
if (ret != TNN_OK) {
return ret;
}
if (!conv_acc_impl_) {
conv_acc_impl_ = std::make_shared<X86DeconvLayerCommon>();
}
if (!conv_acc_impl_) {
return Status(TNNERR_NET_ERR, "Could not create conv impl_");
}
ret = conv_acc_impl_->Init(context_, param_, resource_, inputs, outputs);
// converted weights are assumed to be packed, and can be freed now
if (conv_acc_f32_resource_) {
conv_acc_f32_resource_.reset();
}
return ret;
}
Status X86DeconvLayerAcc::DoForward(const std::vector<Blob *> &inputs, const std::vector<Blob *> &outputs) {
if (conv_acc_impl_) {
return conv_acc_impl_->DoForward(inputs, outputs);
} else {
return Status(TNNERR_CONTEXT_ERR, "conv_acc_impl_ is nil");
}
}
REGISTER_X86_ACC(Deconv, LAYER_DECONVOLUTION);
} | [
"[email protected]"
] | |
c8049d9a1ec424f37c3cd1eab2b4ccdfed75eb31 | 921c689451ff3b6e472cc6ae6a34774c4f57e68b | /llvm-2.8/tools/clang/test/SemaCXX/libstdcxx_is_pod_hack.cpp | 2e9203219536e87ca258ce034d8f049e9c95c988 | [
"NCSA"
] | permissive | xpic-toolchain/xpic_toolchain | 36cae905bbf675d26481bee19b420283eff90a79 | 9e6d4276cc8145a934c31b0d3292a382fc2e5e92 | refs/heads/master | 2021-01-21T04:37:18.963215 | 2016-05-19T12:34:11 | 2016-05-19T12:34:11 | 29,474,690 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | cpp | // RUN: %clang_cc1 -fsyntax-only %s
// This is a test for an egregious hack in Clang that works around
// issues with GCC's evolution. libstdc++ 4.2.x uses __is_pod as an
// identifier (to declare a struct template like the one below), while
// GCC 4.3 and newer make __is_pod a keyword. Clang treats __is_pod as
// a keyword *unless* it is introduced following the struct keyword.
template<typename T>
struct __is_pod {
};
__is_pod<int> ipi;
| [
"helmutmanck@5227c84a-046b-4545-895e-fca5577db8e1"
] | helmutmanck@5227c84a-046b-4545-895e-fca5577db8e1 |
8403f25d3587f6134cabb371a0d8ecd44347fa7b | 8e3d8989f3930d17f3b75841e48224603b4ca4b5 | /Facebook Hacker Cup/2021/round_1/A2.cpp | 1aeeb5770c5a5026f33d9eb8030d0840fec6c37d | [] | no_license | kventinel/Contests | 83f3e034e9c512c26aec7fdfffe09b2f74a425d1 | 3abdabf4c2ae877622447b244ad7b37da9482ad9 | refs/heads/master | 2022-06-05T00:13:56.762396 | 2022-05-15T17:52:14 | 2022-05-15T17:52:14 | 92,678,307 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,252 | cpp | #include <algorithm>
#include <cstdio>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#define F first
#define S second
#define pb push_back
#define eb emplace_back
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
int MOD = 1000 * 1000 * 1000 + 7;
int main() {
ios_base::sync_with_stdio(false);
int tests;
cin >> tests;
for (int test = 1; test <= tests; ++test) {
int len;
string s;
cin >> len >> s;
int hand = -1;
ll j = -1;
ll res = 0;
for (int i = 0; i < len; ++i) {
if (s[i] == 'O') {
if (hand == 0) {
res += (j + 1) * (len - i);
}
j = i;
hand = 1;
} else if (s[i] == 'X') {
if (hand == 1) {
res += (j + 1) * (len - i);
}
j = i;
hand = 0;
}
}
cout << "Case #" << test << ": " << res % MOD << endl;
}
return 0;
}
| [
"[email protected]"
] | |
b332a1c132c391dc08ea3fd09ba5752e3b5d526a | fbc8bbdf2fcafbbcf06ea87aac99aad103dfc773 | /VTK/Rendering/OpenGL2/Testing/Cxx/TestGlyph3DMapperCellPicking.cxx | 226b2e875bbc0e84e63965d1e397f8beb37539ef | [
"BSD-3-Clause"
] | permissive | vildenst/In_Silico_Heart_Models | a6d3449479f2ae1226796ca8ae9c8315966c231e | dab84821e678f98cdd702620a3f0952699eace7c | refs/heads/master | 2020-12-02T20:50:19.721226 | 2017-07-24T17:27:45 | 2017-07-24T17:27:45 | 96,219,496 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,803 | cxx | /*=========================================================================
Program: Visualization Toolkit
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.
=========================================================================*/
// This tests vtkVisibleCellSelector, vtkExtractSelectedFrustum,
// vtkRenderedAreaPicker, and vtkInteractorStyleRubberBandPick.
//
// The command line arguments are:
// -I => run in interactive mode; unless this is used, the program will
// not allow interaction and exit
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSphereSource.h"
#include "vtkActor.h"
#include "vtkInteractorStyleRubberBandPick.h"
#include "vtkCommand.h"
#include "vtkHardwareSelector.h"
#include "vtkSelection.h"
#include "vtkIdTypeArray.h"
#include "vtkRenderedAreaPicker.h"
#include "vtkCamera.h"
#include "vtkImageActor.h"
#include "vtkPointData.h"
#include "vtkPlaneSource.h"
#include "vtkElevationFilter.h"
#include "vtkBitArray.h"
#include "vtkGlyph3DMapper.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"
#include <cassert>
static vtkRenderer *renderer = NULL;
class MyEndPickCommand : public vtkCommand
{
public:
MyEndPickCommand()
{
this->Renderer=0; // no reference counting
this->Mask=0; // no reference counting
this->DataSet=0;
}
~MyEndPickCommand() VTK_OVERRIDE
{
// empty
}
void Execute(vtkObject *vtkNotUsed(caller),
unsigned long vtkNotUsed(eventId),
void *vtkNotUsed(callData)) VTK_OVERRIDE
{
assert("pre: renderer_exists" && this->Renderer!=0);
vtkHardwareSelector *sel = vtkHardwareSelector::New();
sel->SetFieldAssociation(vtkDataObject::FIELD_ASSOCIATION_CELLS);
sel->SetRenderer(renderer);
double x0 = renderer->GetPickX1();
double y0 = renderer->GetPickY1();
double x1 = renderer->GetPickX2();
double y1 = renderer->GetPickY2();
sel->SetArea(static_cast<unsigned int>(x0),
static_cast<unsigned int>(y0),
static_cast<unsigned int>(x1),
static_cast<unsigned int>(y1));
vtkSelection *res = sel->Select();
#if 1
cerr << "x0 " << x0 << " y0 " << y0 << "\t";
cerr << "x1 " << x1 << " y1 " << y1 << endl;
res->Print(cout);
#endif
// Reset the mask to false.
vtkIdType numPoints = this->Mask->GetNumberOfTuples();
for (vtkIdType i=0; i < numPoints; i++)
{
this->Mask->SetValue(i,false);
}
vtkSelectionNode *glyphids = res->GetNode(0);
if (glyphids!=0)
{
vtkAbstractArray *abs=glyphids->GetSelectionList();
if(abs==0)
{
cout<<"abs is null"<<endl;
}
vtkIdTypeArray *ids=vtkArrayDownCast<vtkIdTypeArray>(abs);
if(ids==0)
{
cout<<"ids is null"<<endl;
}
else
{
// modify mask array with selection.
vtkIdType numSelPoints = ids->GetNumberOfTuples();
for (vtkIdType i =0; i < numSelPoints; i++)
{
vtkIdType value = ids->GetValue(i);
if (value >=0 && value < numPoints)
{
cout << "Turn On: " << value << endl;
this->Mask->SetValue(value,true);
}
else
{
cout << "Ignoring: " << value << endl;
}
}
}
}
this->DataSet->Modified();
sel->Delete();
res->Delete();
}
void SetRenderer(vtkRenderer *r)
{
this->Renderer=r;
}
vtkRenderer *GetRenderer() const
{
return this->Renderer;
}
void SetMask(vtkBitArray *m)
{
this->Mask=m;
}
void SetDataSet(vtkDataSet* ds)
{
this->DataSet = ds;
}
protected:
vtkRenderer *Renderer;
vtkBitArray *Mask;
vtkDataSet *DataSet;
};
int TestGlyph3DMapperCellPicking(int argc, char* argv[])
{
int res=1;
vtkPlaneSource *plane=vtkPlaneSource::New();
plane->SetResolution(res,res);
vtkElevationFilter *colors=vtkElevationFilter::New();
colors->SetInputConnection(plane->GetOutputPort());
plane->Delete();
colors->SetLowPoint(-1,-1,-1);
colors->SetHighPoint(0.5,0.5,0.5);
vtkSphereSource *squad=vtkSphereSource::New();
squad->SetPhiResolution(4);
squad->SetThetaResolution(6);
vtkGlyph3DMapper *glypher=vtkGlyph3DMapper::New();
// glypher->SetNestedDisplayLists(0);
glypher->SetInputConnection(colors->GetOutputPort());
colors->Delete();
glypher->SetScaleFactor(1.5);
glypher->SetSourceConnection(squad->GetOutputPort());
squad->Delete();
// selection is performed on actor1
vtkActor *glyphActor1=vtkActor::New();
glyphActor1->SetMapper(glypher);
glypher->Delete();
glyphActor1->PickableOn();
// result of selection is on actor2
vtkActor *glyphActor2=vtkActor::New();
glyphActor2->PickableOff();
colors->Update(); // make sure output is valid.
vtkDataSet *selection=colors->GetOutput()->NewInstance();
selection->ShallowCopy(colors->GetOutput());
vtkBitArray *selectionMask=vtkBitArray::New();
selectionMask->SetName("mask");
selectionMask->SetNumberOfComponents(1);
selectionMask->SetNumberOfTuples(selection->GetNumberOfPoints());
// Initially, everything is selected
vtkIdType i=0;
vtkIdType c=selectionMask->GetNumberOfTuples();
while(i<c)
{
selectionMask->SetValue(i,true);
++i;
}
selection->GetPointData()->AddArray(selectionMask);
selectionMask->Delete();
vtkGlyph3DMapper *glypher2=vtkGlyph3DMapper::New();
// glypher->SetNestedDisplayLists(0);
glypher2->SetMasking(1);
glypher2->SetMaskArray("mask");
glypher2->SetInputData(selection);
glypher2->SetScaleFactor(1.5);
glypher2->SetSourceConnection(squad->GetOutputPort());
glyphActor2->SetMapper(glypher2);
glypher2->Delete();
// Standard rendering classes
renderer = vtkRenderer::New();
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->AddRenderer(renderer);
renWin->SetMultiSamples(0);
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
//set up the view
renderer->SetBackground(0.2,0.2,0.2);
renWin->SetSize(600,300);
//use the rubber band pick interactor style
vtkRenderWindowInteractor* rwi = renWin->GetInteractor();
vtkInteractorStyleRubberBandPick *rbp =
vtkInteractorStyleRubberBandPick::New();
rwi->SetInteractorStyle(rbp);
vtkRenderedAreaPicker *areaPicker = vtkRenderedAreaPicker::New();
rwi->SetPicker(areaPicker);
renderer->AddActor(glyphActor1);
renderer->AddActor(glyphActor2);
glyphActor2->SetPosition(2,0,0);
glyphActor1->Delete();
glyphActor2->Delete();
//pass pick events to the VisibleGlyphSelector
MyEndPickCommand *cbc=new MyEndPickCommand;
cbc->SetRenderer(renderer);
cbc->SetMask(selectionMask);
cbc->SetDataSet(selection);
rwi->AddObserver(vtkCommand::EndPickEvent,cbc);
cbc->Delete();
////////////////////////////////////////////////////////////
//run the test
renderer->ResetCamera();
renderer->GetActiveCamera()->Zoom(2.0);
renWin->Render();
// areaPicker->AreaPick(0, 0, 241, 160, renderer);
areaPicker->AreaPick(233, 120, 241, 160, renderer);
cbc->Execute(NULL, 0, NULL);
renWin->Render();
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
// Cleanup
renderer->Delete();
renWin->Delete();
iren->Delete();
rbp->Delete();
areaPicker->Delete();
selection->Delete();
return !retVal;
}
| [
"vilde@Vildes-MBP"
] | vilde@Vildes-MBP |
4f8366b36e9b09056c379130adcd24f7d9ee2219 | 83f6e199e50858b993679d13291fa43cbcfb922d | /PartA/generator.h | 6ecb202c01356d837314a71fa058c48d2dd195a1 | [] | no_license | devanshdalal/The_Social_Network_Simulator_And_Analyzer | 6f6ba6f9406d508c05907354cc91074c0f50d6b1 | 9e0c042e2c42e6293eef32a5c2eca483921ae0e9 | refs/heads/master | 2021-01-13T02:02:04.803746 | 2014-07-24T06:44:12 | 2014-07-24T06:44:12 | 22,115,387 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 685 | h | /*
* Generator.h
*
* Created on: Oct 8, 2013
* Author: cs1120255
*/
#ifndef GENERATOR_H_
#define GENERATOR_H_
#include <iostream>
#include <fstream>
#include <string.h>
#include <vector>
#include<ctime>
#include <stdlib.h>
#include "setEnvironment.h"
#include "setEnvironment.h"
using namespace std;
/*! \brief It contains all the generator threads as its functions.
*
*/
class Generator{
public:
void * generateFaculty(void*); //Generates Faculty
void * generateStudent(void*); //Generates Students
void * generateCourses(void*); //Generates Courses
void * generateFriends(void*); //Generates Friends
int init(const char*,int);
};
#endif /* GENERATOR_H_ */
| [
"[email protected]"
] | |
7f043845845e3d79ef47475d6cd84975a11338ec | 52fc905b150af358e5f34a7f8e24f73893f84c35 | /segmentation/region_descriptor.cpp | 90993cd3380be510f3cef73c536a7e2102ca68d3 | [] | no_license | CognitiveRobotics/video_segment | 4a471340aab9ca81aaa2c352cae967e50de3d235 | 98a9d978f19c5d05938fc597522a90d93dc443f8 | refs/heads/master | 2021-01-18T16:16:20.208118 | 2016-01-13T00:23:19 | 2016-01-13T00:23:19 | 49,523,898 | 1 | 1 | null | 2016-01-12T19:29:35 | 2016-01-12T19:29:35 | null | UTF-8 | C++ | false | false | 28,073 | cpp | // Copyright (c) 2010-2014, The Video Segmentation Project
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the The Video Segmentation Project nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ---
#include "segmentation/region_descriptor.h"
#include <opencv2/imgproc/imgproc.hpp>
#include "base/base_impl.h"
#include "imagefilter/image_util.h"
#include "segment_util/segmentation_util.h"
#include "segmentation/segmentation_common.h"
namespace segmentation {
RegionDescriptorExtractor::~RegionDescriptorExtractor() { }
RegionDescriptor::~RegionDescriptor() { }
RegionDescriptor* RegionDescriptor::Clone() const {
RegionDescriptor* cloned = CloneImpl();
// Copy base class information.
cloned->parent_region_ = parent_region_;
return cloned;
}
DescriptorUpdaterList NonMutableUpdaters(int num_updaters) {
DescriptorUpdaterList updaters;
for (int n = 0; n < num_updaters; ++n) {
updaters.push_back(std::shared_ptr<RegionDescriptorUpdater>(new NonMutableUpdater()));
}
return updaters;
}
AppearanceExtractor::AppearanceExtractor(
int luminance_bins,
int color_bins,
int window_size,
const cv::Mat& rgb_frame,
const AppearanceExtractor* prev_extractor)
: RegionDescriptorExtractor(&typeid(*this)),
luminance_bins_(luminance_bins),
color_bins_(color_bins),
window_size_(window_size) {
lab_frame_.reset(new cv::Mat(rgb_frame.rows,
rgb_frame.cols,
CV_8UC3));
cv::cvtColor(rgb_frame, *lab_frame_, CV_BGR2Lab);
if (window_size > 0) {
if (prev_extractor) {
mean_values_ = prev_extractor->mean_values_;
}
// Compute average per-channel intensity.
cv::Scalar mean = cv::mean(*lab_frame_);
mean_values_.insert(mean_values_.begin(), cv::Point3f(mean[0], mean[1], mean[2]));
// Only store as many values as needed.
if (mean_values_.size() > window_size) {
mean_values_.resize(window_size);
}
}
}
AppearanceDescriptor3D::AppearanceDescriptor3D(int luminance_bins,
int color_bins)
: RegionDescriptor(&typeid(*this)) {
color_histogram_.reset(new ColorHistogram(luminance_bins, color_bins, SPARSE_HISTS));
}
void AppearanceDescriptor3D::AddFeatures(const Rasterization& raster,
const RegionDescriptorExtractor& extractor,
int frame_number) {
const AppearanceExtractor& appearance_extractor = extractor.As<AppearanceExtractor>();
for (const auto& scan_inter : raster.scan_inter()) {
const uint8_t* interval_ptr = appearance_extractor.LabFrame().ptr<uint8_t>(
scan_inter.y()) + 3 * scan_inter.left_x();
for (int x = scan_inter.left_x();
x <= scan_inter.right_x();
++x, interval_ptr += 3) {
color_histogram_->AddPixelInterpolated(interval_ptr);
}
}
}
float AppearanceDescriptor3D::RegionDistance(const RegionDescriptor& rhs_uncast) const {
const auto& rhs = rhs_uncast.As<AppearanceDescriptor3D>();
return color_histogram_->ChiSquareDist(*rhs.color_histogram_);
}
void AppearanceDescriptor3D::PopulatingDescriptorFinished() {
if (!is_populated_) {
#ifndef SPARSE_HISTS
color_histogram_->ConvertToSparse();
#endif
color_histogram_->NormalizeToOne();
is_populated_ = true;
}
}
void AppearanceDescriptor3D::MergeWithDescriptor(const RegionDescriptor& rhs_uncast) {
const auto& rhs = rhs_uncast.As<AppearanceDescriptor3D>();
color_histogram_->MergeWithHistogram(*rhs.color_histogram_);
}
RegionDescriptor* AppearanceDescriptor3D::CloneImpl() const {
return new AppearanceDescriptor3D(*this);
}
void AppearanceDescriptor3D::AddToRegionFeatures(RegionFeatures* descriptor) const {
}
WindowedAppearanceDescriptor::WindowedAppearanceDescriptor(int window_size,
int luminance_bins,
int color_bins)
: RegionDescriptor(&typeid(*this)),
window_size_(window_size),
luminance_bins_(luminance_bins),
color_bins_(color_bins) {
}
void WindowedAppearanceDescriptor::AddFeatures(const Rasterization& raster,
const RegionDescriptorExtractor& extractor,
int frame_number) {
const auto& appearance_extractor = extractor.As<AppearanceExtractor>();
const int global_window_idx = frame_number / window_size_;
const int window_frame = frame_number % window_size_;
if (start_window_ < 0) {
start_window_ = global_window_idx;
}
const int window_idx = global_window_idx - start_window_;
// Compact all previous windows and add new window.
if (window_idx >= windows_.size()) {
for (auto& window_ptr : windows_) {
if (window_ptr == nullptr) {
continue;
}
if (!window_ptr->is_populated) {
#if SPARSE_HISTS
window_ptr->color_hist.ConvertToSparse();
#endif
window_ptr->color_hist.NormalizeToOne();
window_ptr->is_populated = true;
}
}
windows_.resize(window_idx + 1);
}
if (windows_[window_idx] == nullptr) {
windows_[window_idx].reset(
new CalibratedHistogram(luminance_bins_,
color_bins_,
appearance_extractor.AverageValues(window_frame)));
}
ColorHistogram& histogram = windows_[window_idx]->color_hist;
cv::Point3f gain_change = GetGainChange(windows_[window_idx]->mean_values,
appearance_extractor.AverageValues(0));
for (const auto& scan_inter : raster.scan_inter()) {
const uint8_t* interval_ptr =
appearance_extractor.LabFrame().ptr<uint8_t>(scan_inter.y()) +
3 * scan_inter.left_x();
for (int x = scan_inter.left_x();
x <= scan_inter.right_x();
++x, interval_ptr += 3) {
histogram.AddPixelValuesInterpolated(
std::min(255.f, (float)interval_ptr[0] * gain_change.x),
std::min(255.f, (float)interval_ptr[1] * gain_change.y),
std::min(255.f, (float)interval_ptr[2] * gain_change.z));
}
}
}
float WindowedAppearanceDescriptor::RegionDistance(
const RegionDescriptor& rhs_uncast) const {
const WindowedAppearanceDescriptor& rhs = rhs_uncast.As<WindowedAppearanceDescriptor>();
// Determine corresponding search interval.
const int search_start = start_window();
const int search_end = end_window();
// Holds weighted average of per window distances (weighted by minimum histogram
// weight, i.e. number of samples).
double dist_sum = 0;
double weight_sum = 0;
for (int window_idx = search_start; window_idx < search_end; ++window_idx) {
const int lhs_idx = window_idx - start_window_;
// We allow for empty windows.
if (windows_[lhs_idx] == nullptr) {
LOG(WARNING) << "Empty window found, this can happen for small window sizes.";
continue;
}
const ColorHistogram& curr_hist = windows_[lhs_idx]->color_hist;
// Traverse comparison radius.
double match_weight_sum = 0;
double match_sum = 0;
for (int match_window = window_idx - compare_radius_;
match_window <= window_idx + compare_radius_;
++match_window) {
const int rhs_idx = match_window - rhs.start_window_;
if (rhs_idx < 0 || rhs_idx >= rhs.windows_.size()) {
continue;
}
if (rhs.windows_[rhs_idx] == nullptr) {
LOG(WARNING) << "Empty window found, this can happen for small window sizes.";
continue;
}
ColorHistogram* match_hist = &rhs.windows_[rhs_idx]->color_hist;
std::unique_ptr<ColorHistogram> gain_corrected_hist;
if (match_window != window_idx) {
// Build windowed gain corrected histogram, if needed.
cv::Point3f gain = GetGainChange(windows_[lhs_idx]->mean_values,
rhs.windows_[rhs_idx]->mean_values);
if (GainChangeAboveThreshold(gain, 1.1f)) {
gain_corrected_hist.reset(new ColorHistogram(
rhs.windows_[rhs_idx]->color_hist.ScaleHistogram({gain.x, gain.y,
gain.z})));
match_hist = gain_corrected_hist.get();
}
}
const float weight = std::min(curr_hist.WeightSum(), match_hist->WeightSum());
const float dist = curr_hist.ChiSquareDist(*match_hist);
DCHECK(dist >= 0.0f && dist < 1.0f + 1.0e-3f) << "Chi-Sq: " << dist;
match_weight_sum += weight;
match_sum += weight * dist;
}
dist_sum += match_sum;
weight_sum += match_weight_sum;
}
if (weight_sum > 0) {
const float result = dist_sum / weight_sum;
DCHECK(result >= 0 && result < 1.0 + 1e-3) << "Distance: " << result;
return result;
} else {
return 0.f;
}
}
void WindowedAppearanceDescriptor::PopulatingDescriptorFinished() {
for (auto& window : windows_) {
if (window != nullptr && !window->is_populated) {
#if SPARSE_HISTS
window->color_hist.ConvertToSparse();
#endif
window->color_hist.NormalizeToOne();
window->is_populated = true;
}
}
}
void WindowedAppearanceDescriptor::MergeWithDescriptor(
const RegionDescriptor& rhs_uncast) {
const WindowedAppearanceDescriptor& rhs = rhs_uncast.As<WindowedAppearanceDescriptor>();
const int max_idx = std::max(end_window(), rhs.end_window());
while (start_window() > rhs.start_window()) {
windows_.emplace(windows_.begin(), nullptr);
--start_window_;
}
while (max_idx > end_window()) {
windows_.emplace_back(nullptr);
}
// Note: Some histograms might not be allocated yet!
for (int k = start_window_; k < max_idx; ++k) {
const int lhs_idx = k - start_window();
const int rhs_idx = k - rhs.start_window();
if (windows_[lhs_idx] == nullptr) {
DCHECK(rhs.windows_[rhs_idx] != nullptr);
windows_[lhs_idx].reset(new CalibratedHistogram(*rhs.windows_[rhs_idx]));
} else {
if (rhs_idx < 0 || rhs_idx >= rhs.windows_.size()) {
continue;
}
DCHECK(rhs.windows_[rhs_idx] != nullptr);
// Both histograms are calibrated w.r.t. to the same number offset.
DCHECK(windows_[lhs_idx]->mean_values == rhs.windows_[rhs_idx]->mean_values);
windows_[lhs_idx]->color_hist.MergeWithHistogram(
rhs.windows_[rhs_idx]->color_hist);
}
}
}
RegionDescriptor* WindowedAppearanceDescriptor::CloneImpl() const {
return new WindowedAppearanceDescriptor(*this);
}
void WindowedAppearanceDescriptor::AddToRegionFeatures(RegionFeatures* descriptor) const {
}
WindowedAppearanceDescriptor::WindowedAppearanceDescriptor(
const WindowedAppearanceDescriptor& rhs)
: RegionDescriptor(&typeid(*this)),
window_size_(rhs.window_size_),
start_window_(rhs.start_window_),
compare_radius_(rhs.compare_radius_),
luminance_bins_(rhs.luminance_bins_),
color_bins_(rhs.color_bins_) {
windows_.reserve(rhs.windows_.size());
for (const auto& window_ptr : rhs.windows_) {
if (window_ptr != nullptr) {
windows_.emplace_back(new CalibratedHistogram(*window_ptr));
} else {
windows_.emplace_back(nullptr);
}
}
}
cv::Point3f WindowedAppearanceDescriptor::GetGainChange(
const cv::Point3f& anchor_mean,
const cv::Point3f& frame_mean) {
cv::Point3f gain;
gain.x = anchor_mean.x / (frame_mean.x + 1.0e-3f);
gain.y = anchor_mean.y / (frame_mean.y + 1.0e-3f);
gain.z = anchor_mean.z / (frame_mean.z + 1.0e-3f);
return gain;
}
bool WindowedAppearanceDescriptor::GainChangeAboveThreshold(
const cv::Point3f& gain_change,
float threshold) {
const float inv_threshold = 1.0 / threshold;
return !(gain_change.x <= threshold &&
gain_change.y <= threshold &&
gain_change.z <= threshold &&
gain_change.x >= inv_threshold &&
gain_change.y >= inv_threshold &&
gain_change.z >= inv_threshold);
}
float RegionSizePenalizer::RegionDistance(const RegionDescriptor& rhs_uncast) const {
const RegionSizePenalizer& rhs = dynamic_cast<const RegionSizePenalizer&>(rhs_uncast);
const int min_sz = std::min(ParentRegion()->size, rhs.ParentRegion()->size);
// Determine scale based on relation to average region size.
const float size_scale = 1.0f + penalizer_ * log(min_sz * inv_av_region_size_) / log(2);
return std::min(1.0f, size_scale);
}
void RegionSizePenalizer::UpdateDescriptor(const RegionDescriptorUpdater& base_updater) {
const RegionSizePenalizerUpdater& updater =
base_updater.As<RegionSizePenalizerUpdater>();
inv_av_region_size_ = updater.InvAverageRegionSize();
}
void RegionSizePenalizerUpdater::InitializeUpdate(const RegionInfoList& region_list) {
if (region_list.empty()) {
return;
}
vector<int> region_size;
region_size.reserve(region_list.size());
for (const auto& region_ptr : region_list) {
region_size.push_back(region_ptr->size);
}
if (region_list.empty()) {
inv_av_region_size_ = 1.0f;
return;
}
auto median = region_size.begin() + region_size.size() / 2;
std::nth_element(region_size.begin(), median, region_size.end());
if (*median > 0) {
inv_av_region_size_ = 1.0f / *median;
} else {
inv_av_region_size_ = 1.f;
}
}
FlowExtractor::FlowExtractor(int flow_bins)
: RegionDescriptorExtractor(&typeid(*this)), flow_bins_(flow_bins) {
}
FlowExtractor::FlowExtractor(int flow_bins,
const cv::Mat& flow)
: RegionDescriptorExtractor(&typeid(*this)),
flow_bins_(flow_bins),
valid_flow_(true),
flow_(flow) {
DCHECK(!flow.empty());
}
FlowDescriptor::FlowDescriptor(int flow_bins)
: RegionDescriptor(&typeid(*this)), flow_bins_(flow_bins) {
}
void FlowDescriptor::AddFeatures(const Rasterization& raster,
const RegionDescriptorExtractor& extractor,
int frame_num) {
const FlowExtractor& flow_extractor = extractor.As<FlowExtractor>();
if (!flow_extractor.HasValidFlow()) { // No flow present at current frame.
return;
}
if (start_frame_ < 0) {
// First frame.
start_frame_ = frame_num;
}
const int frame_idx = frame_num - start_frame();
while (frame_idx >= flow_histograms_.size()) {
flow_histograms_.emplace_back(nullptr);
}
if (flow_histograms_[frame_idx] == nullptr) {
flow_histograms_[frame_idx].reset(new VectorHistogram(flow_bins_));
}
for (const auto& scan_inter : raster.scan_inter()) {
const float* flow_ptr = flow_extractor.Flow().ptr<float>(scan_inter.y())
+ scan_inter.left_x() * 2;
for (int x = scan_inter.left_x(); x <= scan_inter.right_x(); ++x, flow_ptr += 2) {
flow_histograms_[frame_idx]->AddVector(flow_ptr[0], flow_ptr[1]);
}
}
}
float FlowDescriptor::RegionDistance(const RegionDescriptor& rhs_uncast) const {
const FlowDescriptor& rhs = rhs_uncast.As<FlowDescriptor>();
// Limit to valid intersection.
const int start_idx = std::max(start_frame(), rhs.start_frame());
const int end_idx = std::min(end_frame(), rhs.end_frame());
double sum = 0;
double sum_weight = 0;
for (int i = start_idx; i < end_idx; ++i) {
// Both histograms are valid within the interval.
const int lhs_idx = i - start_frame();
const int rhs_idx = i - rhs.start_frame();
DCHECK_GE(lhs_idx, 0);
DCHECK_GE(rhs_idx, 0);
if (flow_histograms_[lhs_idx] == nullptr ||
rhs.flow_histograms_[rhs_idx] == nullptr) {
continue;
}
float weight = std::min(flow_histograms_[lhs_idx]->NumVectors(),
rhs.flow_histograms_[rhs_idx]->NumVectors());
sum +=
flow_histograms_[lhs_idx]->ChiSquareDist(*rhs.flow_histograms_[rhs_idx]) * weight;
sum_weight += weight;
}
if (sum_weight > 0) {
return sum / sum_weight;
} else {
return 0;
}
}
void FlowDescriptor::PopulatingDescriptorFinished() {
if (!is_populated_) {
for(auto& hist_ptr : flow_histograms_) {
if (hist_ptr != nullptr) {
hist_ptr->NormalizeToOne();
}
}
is_populated_ = true;
}
}
void FlowDescriptor::MergeWithDescriptor(const RegionDescriptor& rhs_uncast) {
const FlowDescriptor& rhs = rhs_uncast.As<FlowDescriptor>();
const int max_frame = std::max(end_frame(), rhs.end_frame());
while (start_frame() > rhs.start_frame()) {
flow_histograms_.emplace(flow_histograms_.begin(), nullptr);
--start_frame_;
}
while (rhs.end_frame() > end_frame()) {
flow_histograms_.emplace_back(nullptr);
}
// Note: Some histograms might not be allocated yet.
for (int k = start_frame(); k < end_frame(); ++k) {
const int lhs_idx = k - start_frame();
const int rhs_idx = k - rhs.start_frame();
// If rhs histogram does not exist there is nothing to merge.
if (rhs_idx < 0 || rhs_idx >= rhs.flow_histograms_.size() ||
rhs.flow_histograms_[rhs_idx] == nullptr) {
continue;
}
if (flow_histograms_[lhs_idx] == nullptr) {
flow_histograms_[lhs_idx].reset(
new VectorHistogram(*rhs.flow_histograms_[rhs_idx]));
} else {
flow_histograms_[lhs_idx]->MergeWithHistogram(*rhs.flow_histograms_[rhs_idx]);
}
}
// Discard empty start and tail.
while (flow_histograms_.size() > 0 && flow_histograms_[0] == nullptr) {
flow_histograms_.erase(flow_histograms_.begin());
++start_frame_;
}
while (flow_histograms_.size() > 0 && flow_histograms_.back() == nullptr) {
flow_histograms_.pop_back();
}
}
RegionDescriptor* FlowDescriptor::CloneImpl() const {
return new FlowDescriptor(*this);
}
FlowDescriptor::FlowDescriptor(const FlowDescriptor& rhs)
: RegionDescriptor(&typeid(*this)),
start_frame_(rhs.start_frame_),
flow_bins_(rhs.flow_bins_),
is_populated_(rhs.is_populated_) {
flow_histograms_.reserve(flow_histograms_.size());
for (const auto& hist_ptr : rhs.flow_histograms_) {
if (hist_ptr != nullptr) {
flow_histograms_.emplace_back(new VectorHistogram(*hist_ptr));
} else {
flow_histograms_.emplace_back(nullptr);
}
}
}
/*
MatchDescriptor::MatchDescriptor() : RegionDescriptor(MATCH_DESCRIPTOR) {
}
void MatchDescriptor::Initialize(int my_id) {
my_id_ = my_id;
}
void MatchDescriptor::AddMatch(int match_id, float strength) {
CHECK(strength >= 0 && strength <= 1);
// Convert strength to distance.
strength = 1.0 - strength;
strength = std::max(strength, 0.1f);
MatchTuple new_match = { match_id, strength };
vector<MatchTuple>::iterator insert_pos = std::lower_bound(matches_.begin(),
matches_.end(),
new_match);
if(insert_pos != matches_.end() &&
insert_pos->match_id == match_id) {
CHECK_EQ(insert_pos->strength, strength)
<< "Match already present in descriptor with different strength.";
} else {
matches_.insert(insert_pos, new_match);
}
}
float MatchDescriptor::RegionDistance(const RegionDescriptor& rhs_uncast) const {
const MatchDescriptor& rhs = dynamic_cast<const MatchDescriptor&>(rhs_uncast);
MatchTuple lhs_lookup = { my_id_, 0 };
vector<MatchTuple>::const_iterator lhs_match_iter =
std::lower_bound(rhs.matches_.begin(), rhs.matches_.end(), lhs_lookup);
MatchTuple rhs_lookup = { rhs.my_id_, 0 };
vector<MatchTuple>::const_iterator rhs_match_iter =
std::lower_bound(matches_.begin(), matches_.end(), rhs_lookup);
float strength = 1;
if (lhs_match_iter != rhs.matches_.end() &&
lhs_match_iter->match_id == my_id_) {
strength = lhs_match_iter->strength;
}
if (rhs_match_iter != matches_.end() &&
rhs_match_iter->match_id == rhs.my_id_) {
if (strength != 1) {
strength = (strength + rhs_match_iter->strength) * 0.5;
// LOG(WARNING) << "One sided match found!";
} else {
strength = rhs_match_iter->strength;
}
} else {
if (strength != 1) {
// LOG(WARNING) << "One sided match found!";
}
}
return strength;
}
void MatchDescriptor::MergeWithDescriptor(const RegionDescriptor& rhs_uncast) {
const MatchDescriptor& rhs = dynamic_cast<const MatchDescriptor&>(rhs_uncast);
if (my_id_ != rhs.my_id_) {
// TODO: Think about this, no real merge! Winner takes it all.
if (rhs.matches_.size() > matches_.size()) {
if (matches_.size() > 0) {
LOG(WARNING) << "Winner takes it all strategy applied.";
}
my_id_ = rhs.my_id_;
matches_ = rhs.matches_;
}
}
}
RegionDescriptor* MatchDescriptor::CloneImpl() const {
return new MatchDescriptor(*this);
}
void MatchDescriptor::OutputToAggregated(AggregatedDescriptor* descriptor) const {
SegmentationDesc::MatchDescriptor* match =
descriptor->mutable_match();
for (vector<MatchTuple>::const_iterator tuple = matches_.begin();
tuple != matches_.end();
++tuple) {
SegmentationDesc::MatchDescriptor::MatchTuple* add_tuple = match->add_tuple();
add_tuple->set_match_id(tuple->match_id);
add_tuple->set_strength(tuple->strength);
}
}
LBPDescriptor::LBPDescriptor() : RegionDescriptor(LBP_DESCRIPTOR) {
}
void LBPDescriptor::Initialize(int frame_width, int frame_height) {
frame_width_ = frame_width;
frame_height_ = frame_height;
lbp_histograms_.resize(3);
var_histograms_.resize(3);
for (int i = 0; i < 3; ++i) {
lbp_histograms_[i].reset(new VectorHistogram(10));
var_histograms_[i].reset(new VectorHistogram(16));
}
}
void LBPDescriptor::AddSamples(const RegionScanlineRep& scanline_rep,
const vector<shared_ptr<IplImage> >& lab_inputs) {
int scan_idx = scanline_rep.top_y;
for (vector<IntervalList>::const_iterator scanline = scanline_rep.scanline.begin();
scanline != scanline_rep.scanline.end();
++scanline, ++scan_idx) {
for (int f = 0; f < 3; ++f) {
const int max_radius = 1 << f;
// Check if in bounds.
if (scan_idx < max_radius || scan_idx >= frame_height_ - max_radius) {
continue;
}
const uchar* row_ptr = RowPtr<uchar>(lab_inputs[f], scan_idx);
for (IntervalList::const_iterator interval = scanline->begin();
interval != scanline->end();
++interval) {
const uchar* interval_ptr = row_ptr + interval->first;
for (int x = interval->first; x <= interval->second; ++x, ++interval_ptr) {
if (x < max_radius || x >= frame_width_ - max_radius) {
continue;
}
}
AddLBP(interval_ptr, f, lab_inputs[f]->widthStep);
}
}
}
}
void LBPDescriptor::AddLBP(const uchar* lab_ptr, int sample_id, int width_step) {
const int threshold = 5;
const int rad = 1 << sample_id;
int directions[] = { -rad * width_step - rad, -rad * width_step,
-rad * width_step + rad, -rad,
rad, rad * width_step - rad,
rad * width_step, rad * width_step + rad };
int center_val = *lab_ptr;
int lbp = 0;
float sum = 0;
float sq_sum = 0;
for (int i = 0; i < 8; ++i) {
const int sample = (int)lab_ptr[directions[i]];
int diff = sample - center_val;
if (diff > threshold) {
lbp |= (1 << i);
}
sum += sample;
sq_sum += sample * sample;
}
// Add to LBP histogram.
lbp_histograms_[sample_id]->IncrementBin(MapLBP(lbp));
sq_sum /= 8.f;
sum /= 8.f;
// stdev is in 0 .. 128 ( = 8 * 16), usually not higher than 64 though.
const float stdev = std::sqrt(sq_sum - sum * sum) / 4.f;
var_histograms_[sample_id]->IncrementBinInterpolated(std::min(stdev, 15.f));
}
void LBPDescriptor::PopulatingDescriptorFinished() {
for (vector<shared_ptr<VectorHistogram> >::iterator h = lbp_histograms_.begin();
h != lbp_histograms_.end();
++h) {
(*h)->NormalizeToOne();
}
for (vector<shared_ptr<VectorHistogram> >::iterator h = var_histograms_.begin();
h != var_histograms_.end();
++h) {
(*h)->NormalizeToOne();
}
}
void LBPDescriptor::MergeWithDescriptor(const RegionDescriptor& rhs_uncast) {
const LBPDescriptor& rhs = dynamic_cast<const LBPDescriptor&>(rhs_uncast);
for (size_t i = 0; i < lbp_histograms_.size(); ++i) {
lbp_histograms_[i]->MergeWithHistogram(*rhs.lbp_histograms_[i]);
var_histograms_[i]->MergeWithHistogram(*rhs.var_histograms_[i]);
}
}
RegionDescriptor* LBPDescriptor::CloneImpl() const {
LBPDescriptor* new_lbp = new LBPDescriptor();
new_lbp->Initialize(frame_width_, frame_height_);
for (int i = 0; i < 3; ++i) {
new_lbp->lbp_histograms_[i].reset(new VectorHistogram(*lbp_histograms_[i]));
new_lbp->var_histograms_[i].reset(new VectorHistogram(*var_histograms_[i]));
}
return new_lbp;
}
void LBPDescriptor::OutputToAggregated(AggregatedDescriptor* descriptor) const {
for (int t = 0; t < 3; ++t) {
SegmentationDesc::TextureDescriptor* texture =
descriptor->add_texture();
const float* lbp_values = lbp_histograms_[t]->BinValues();
for (int i = 0; i < lbp_histograms_[t]->NumBins(); ++i, ++lbp_values) {
texture->add_lbp_entry(*lbp_values);
}
}
}
float LBPDescriptor::RegionDistance(const RegionDescriptor& rhs_uncast) const {
return 1;
const LBPDescriptor& rhs = dynamic_cast<const LBPDescriptor&>(rhs_uncast);
float var_dists[3];
float lbp_dists[3];
for (int i = 0; i < 3; ++i) {
var_dists[i] = var_histograms_[0]->ChiSquareDist(*rhs.var_histograms_[0]);
lbp_dists[i] = lbp_histograms_[0]->ChiSquareDist(*rhs.lbp_histograms_[0]);
}
const float var_dist =
0.2 * var_dists[0] + 0.3 * var_dists[1] + 0.5 * var_dists[2];
const float lbp_dist =
0.2 * lbp_dists[0] + 0.3 * lbp_dists[1] + 0.5 * lbp_dists[2];
return lbp_dist;
}
vector<int> LBPDescriptor::lbp_lut_;
void LBPDescriptor::ComputeLBP_LUT(int bits) {
lbp_lut_.resize(1 << bits);
for (int i = 0; i < (1 << bits); ++i) {
// Determine number of bit changes and number of 1 bits.
int ones = 0;
int changes = 0;
// Shift with last bit copied to first position and xor.
const int change_mask = i xor ((i | (i & 1) << bits) >> 1);
for (int j = 0; j < bits; ++j) {
changes += (change_mask >> j) & 1;
ones += (i >> j) & 1;
}
if (changes <= 2) {
lbp_lut_[i] = ones;
} else {
lbp_lut_[i] = bits + 1; // Special marker for non-uniform codes
// (more than two sign changes);
}
}
}
*/
} // namespace segmentation.
| [
"[email protected]"
] | |
c94ff35c3492a6d2e8c1b9395c737ebd4d9d31d4 | 790ac1487cc695724d983648464e15912c81e5cf | /CCP_plazza_2018/my.hpp | 91072bea5912ecb2e61f5530bbbd063cdd4e6c9f | [] | no_license | predatorsfr/OOP-tek-2 | cfd65272177b1aaf73b310341f9a9ca5ea48966f | 6f08b9db56d0fc816855092c24fa7cc811cb5949 | refs/heads/master | 2020-07-31T17:23:53.060424 | 2019-09-24T20:34:49 | 2019-09-24T20:34:49 | 210,692,159 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,370 | hpp | /*
** EPITECH PROJECT, 2019
** plazza
** File description:
** my.hpp
*/
#ifndef MY_HPP_
#define MY_HPP_
#include <vector>
#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sstream>
#include <algorithm>
#include <unistd.h>
#include <sys/types.h>
#include <thread>
#include <bits/stdc++.h>
#include <sys/msg.h>
#include <sys/ipc.h>
enum PizzaType
{
Regina = 1,
Margarita = 2,
Americana = 4,
Fantasia = 8
};
enum PizzaSize
{
S = 1,
M = 2,
L = 4,
XL = 8,
XXL = 16
};
/***************/
// CLASS //
/***************/
namespace ini {
class get_ready {
public:
get_ready(float, int, int);
~get_ready();
float g_arg1(void);
int g_arg2(void);
int g_arg3(void);
private:
const float _arg1;
const int _arg2;
const int _arg3;
};
class Info {
public:
int g_how(void);
void s_to_m(int);
void a_to_m(int);
int g_to_m(void);
void s_kitchen(int);
void s_chiefs(int);
void s_num(std::vector<int>);
int g_kitchen(void);
int g_chiefs(void);
std::vector<int> g_num(void);
Info();
~Info();
void init_info(const std::string);
std::vector<std::string> g_name(void);
std::vector<std::string> g_size(void);
std::vector<std::string> g_nbr(void);
private:
void tri(void);
int _how;
int _to_m;
std::vector<std::string> _name;
std::vector<std::string> _all;
std::vector<std::string> _size;
std::vector<std::string> _nbr;
std::vector<int> _num;
int _cheese;
int _egg;
int _steak;
int _mushroom;
int _ham;
int _gruyere;
int _tomato;
int _doe;
int _pizza;
int _chief;
int _kitchen;
};
}
/****************/
// FUNCTION //
/****************/
int fork(ini::Info *info, ini::get_ready get_ready);
int loop(ini::Info *info, std::string tamp, ini::get_ready get_ready);
int init_arg(std::string arg1, std::string arg2, std::string arg3);
int check_name(std::string buf);
int check_type(std::string buf, int i);
int check_size(ini::Info info, std::vector<std::string> size);
int check_nbr(ini::Info info);
#endif
| [
"[email protected]"
] | |
e23317b21cc045df75dcd3e712d6f1b7f802d40a | 460f981dfe1a05f14d2a4cdc6cc71e9ad798b785 | /3/amd64/envs/navigator/include/qt/QtDataVisualization/5.9.7/QtDataVisualization/private/qabstractdataproxy_p.h | abe1f4ce74d93ba55f3ad5e56df91bd956d6f8e3 | [
"MIT",
"Zlib",
"BSD-2-Clause",
"GPL-2.0-only",
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"LicenseRef-scancode-mit-old-style",
"dtoa",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-public-domain",
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license",
"Intel"
] | permissive | DFO-Ocean-Navigator/navigator-toolchain | d8c7351b477e66d674b50da54ec6ddc0f3a325ee | 930d26886fdf8591b51da9d53e2aca743bf128ba | refs/heads/master | 2022-11-05T18:57:30.938372 | 2021-04-22T02:02:45 | 2021-04-22T02:02:45 | 234,445,230 | 0 | 1 | BSD-3-Clause | 2022-10-25T06:46:23 | 2020-01-17T01:26:49 | C++ | UTF-8 | C++ | false | false | 2,348 | h | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Data Visualization module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 or (at your option) any later version
** approved by the KDE Free Qt Foundation. The licenses are as published by
** the Free Software Foundation and appearing in the file LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
//
// W A R N I N G
// -------------
//
// This file is not part of the QtDataVisualization API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
#ifndef QABSTRACTDATAPROXY_P_H
#define QABSTRACTDATAPROXY_P_H
#include "datavisualizationglobal_p.h"
#include "qabstractdataproxy.h"
QT_BEGIN_NAMESPACE_DATAVISUALIZATION
class QAbstract3DSeries;
class QAbstractDataProxyPrivate : public QObject
{
Q_OBJECT
public:
QAbstractDataProxyPrivate(QAbstractDataProxy *q, QAbstractDataProxy::DataType type);
virtual ~QAbstractDataProxyPrivate();
inline QAbstract3DSeries *series() { return m_series; }
virtual void setSeries(QAbstract3DSeries *series);
protected:
QAbstractDataProxy *q_ptr;
QAbstractDataProxy::DataType m_type;
QAbstract3DSeries *m_series;
private:
friend class QAbstractDataProxy;
};
QT_END_NAMESPACE_DATAVISUALIZATION
#endif
| [
"[email protected]"
] | |
ab5f65ee76b07bad47857d7e720581d8a0d4c2a3 | 8ff0c1b6daa5ebc58dda4e41300af3b3b74e56a1 | /q4.cpp | 543588e8bd8a9ca02c601e95c6a3ace47ad9b32a | [] | no_license | vridhi-sahu/nau | f8ab7c62d3b21e70064d4e211dfa156b6c1bea52 | dfde773c95e30326231540b670abbde64e831a5e | refs/heads/master | 2020-04-14T16:28:16.467275 | 2019-01-10T17:37:21 | 2019-01-10T17:37:21 | 163,952,661 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 869 | cpp | #include<stdio.h>
#include<stdlib.h>
int main()
{
int choice, a,b,sum, sub, pro,div;
while(1)
{
printf(" press 1 for summation 2 for subtraction 3 for multiplication 4 for division 5 for exit.");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter two numbers:");
scanf("%d%d",&a,&b);
sum = a + b;
printf("The sum is %d", sum);
break;
case 2:
printf("Enter two numbers:");
scanf("%d%d", &a,&b);
sub = a - b;
printf("The diff is %d", sub);
break;
case 3:
printf("Enter two numbers:");
scanf("%d%d", &a,&b);
pro = a*b;
printf("The product is is %d", pro);
break;
case 4:
printf("Enter two numbers:");
scanf("%d%d", &a,&b);
div = a/b;
printf("The quotient is %d", div);
break;
case 5: exit(1);
default : printf("invalid input");
}
} return 0;
}
| [
"[email protected]"
] | |
c055d1667bc732fc7fe1eeed4cc9b3f199710e40 | 190b724cf126d7ad819164dcc0bae7a65247cd3b | /roadRateFirst/raj.ino | 10660660ee61ceefcf3e18a10683ab997e517f9e | [] | no_license | rpshah/arduinocodes | 68f70fd1064a4e4ac448f369f376acb66fd6531d | 2d5d8bfb2636eb3d325c377e3b920794a641501b | refs/heads/master | 2021-01-19T17:16:44.494251 | 2018-03-23T05:27:54 | 2018-03-23T05:27:54 | 74,647,982 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,015 | ino | char dataBuf[1000];
///// GYROSCOPE ////
#include <SoftwareSerial.h>// import the serial library
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file
// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high
#define OUTPUT_READABLE_YAWPITCHROLL
#define OUTPUT_READABLE_QUATERNION
bool blinkState = false;
// MPU control/status vars
bool dmpReady = false; // set true if DMP init was successful
uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU
uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize; // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount; // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer
// orientation/motion vars
Quaternion q; // [w, x, y, z] quaternion container
VectorInt16 aa; // [x, y, z] accel sensor measurements
VectorInt16 aaReal; // [x, y, z] gravity-free accel sensor measurements
VectorInt16 aaWorld; // [x, y, z] world-frame accel sensor measurements
VectorFloat gravity; // [x, y, z] gravity vector
float euler[3]; // [psi, theta, phi] Euler angle container
float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector
// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00, '\r', '\n' };
// ================================================================
// === INTERRUPT DETECTION ROUTINE ===
// ================================================================
volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
mpuInterrupt = true;
}
//// ULTRASONIC /////
// defines pins numbers
const int trigPin = 8;
const int echoPin = 9;
// defines variables
long duration;
int distance;
///// LDR ///////
int LDR = A0; //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDRValue = 0; //that’s a variable to store LDR values
///// GAS SENSOR ////
const int GASInPin = A1;
int GASValue = 0;
/////////// BLUETOOTH //////////
// arduino>>bluetooth
// D11 >>> Rx
// D10 >>> Tx
SoftwareSerial Genotronex(50, 51); // RX, TX
int BluetoothData; // the data given from Computer
/////////// MOTOR DRIVER /////
int ENA = 10; //Connect on Arduino, Pin 2
int IN1 = 3; //Connect on Arduino, Pin 3
int IN2 = 4; //Connect on Arduino, Pin 4
int ENB = 5; //Connect on Arduino, Pin 5
int IN3 = 6; //Connect on Arduino, Pin 6
int IN4 = 7; //Connect on Arduino, Pin 7
void driveForward() {
digitalWrite(IN1, LOW); //Forward
digitalWrite(IN2, HIGH);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
}
void driveStop() {
digitalWrite(IN1, HIGH); //Forward
digitalWrite(IN2, HIGH);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, HIGH);
}
void setup() {
Serial.begin(9600); // Starts the serial communication
// ULTRASONIC
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
/// GYRO ///
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif
Serial.println(F("Initializing I2C devices..."));
mpu.initialize();
// verify connection
Serial.println(F("Testing device connections..."));
Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
// supply your own gyro offsets here, scaled for min sensitivity
mpu.setXGyroOffset(0);
mpu.setYGyroOffset(0);
mpu.setZGyroOffset(0);
mpu.setZAccelOffset(1688); // 1688 factory default for my test chip
// make sure it worked (returns 0 if so)
if (devStatus == 0) {
// turn on the DMP, now that it's ready
Serial.println(F("Enabling DMP..."));
mpu.setDMPEnabled(true);
// enable Arduino interrupt detection
Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
attachInterrupt(0, dmpDataReady, RISING);
mpuIntStatus = mpu.getIntStatus();
// set our DMP Ready flag so the main loop() function knows it's okay to use it
Serial.println(F("DMP ready! Waiting for first interrupt..."));
dmpReady = true;
// get expected DMP packet size for later comparison
packetSize = mpu.dmpGetFIFOPacketSize();
} else {
// ERROR!
// 1 = initial memory load failed
// 2 = DMP configuration updates failed
// (if it's going to break, usually the code will be 1)
Serial.print(F("DMP Initialization failed (code "));
Serial.print(devStatus);
Serial.println(F(")"));
}
////// BLUETOOTH /////
Genotronex.begin(9600);
///// MOTOR DRIVER ///
pinMode(ENA, OUTPUT);
pinMode(ENB, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
digitalWrite(ENA, HIGH); // Activer moteur A
digitalWrite(ENB, HIGH); // Activer moteur B
driveForward();
delay(1000);
driveStop();
}
void loop() {
// put your main code here, to run repeatedly:
//if (Genotronex.available()) {
//BluetoothData = Genotronex.read();
//if (BluetoothData == '1') { // if number 1 pressed ....
driveForward();
delay(200);
driveStop();
//}
//else{
// return;
//}
//}
//else{
//return;
//}
//// ULTRASONIC ///////////////////////////
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
sprintf(dataBuf , "%d," , distance);
Genotronex.print(dataBuf);
///// LDR ////
LDRValue = analogRead(LDR); //reads the ldr’s value through LDR
Serial.println(LDRValue); //prints the LDR values to serial monitor
delay(200); //This is the speed by which LDR sends value to arduino
sprintf(dataBuf , "%d," , LDRValue);
Genotronex.print(dataBuf);
///// GAS SENSOR //////
GASValue = analogRead(GASInPin);
Serial.println("Gas value: ");
Serial.println(GASValue);
sprintf(dataBuf , "%d," , GASValue);
Genotronex.print(dataBuf);
///// GYROSCOPE ////
// wait for MPU interrupt or extra packet(s) available
while (!mpuInterrupt && fifoCount < packetSize) {
// other program behavior stuff here
// .
// .
// .
// if you are really paranoid you can frequently test in between other
// stuff to see if mpuInterrupt is true, and if so, "break;" from the
// while() loop to immediately process the MPU data
// .
// .
// .
}
// reset interrupt flag and get INT_STATUS byte
mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();
// get current FIFO count
fifoCount = mpu.getFIFOCount();
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
Serial.println(F("FIFO overflow!"));
Genotronex.print("1,1,1");
// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else (mpuIntStatus & 0x02) {
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
// read a packet from FIFO
mpu.getFIFOBytes(fifoBuffer, packetSize);
// track FIFO count here in case there is > 1 packet available
// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;
#ifdef OUTPUT_READABLE_QUATERNION
// display quaternion values in easy matrix form: w x y z
mpu.dmpGetQuaternion(&q, fifoBuffer);
Serial.print("quat\t");
Serial.print(q.w);
Serial.print("\t");
Serial.print(q.x);
Serial.print("\t");
Serial.print(q.y);
Serial.print("\t");
Serial.println(q.z);
sprintf(dataBuf , "%f," , q.x);
Genotronex.print(dataBuf);
sprintf(dataBuf , "%f," , q.y);
Genotronex.print(dataBuf);
sprintf(dataBuf , "%f" , q.z);
Genotronex.print(dataBuf);
#endif
#ifdef OUTPUT_READABLE_EULER
// display Euler angles in degrees
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetEuler(euler, &q);
Serial.print("euler\t");
Serial.print(euler[0] * 180 / M_PI);
Serial.print("\t");
Serial.print(euler[1] * 180 / M_PI);
Serial.print("\t");
Serial.println(euler[2] * 180 / M_PI);
Genotronex.print("1,1,1");
#endif
#ifdef OUTPUT_READABLE_YAWPITCHROLL
// display Euler angles in degrees
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
Serial.print("ypr\t");
Serial.print(ypr[0] * 180 / M_PI);
Serial.print("\t");
Serial.print(ypr[1] * 180 / M_PI);
Serial.print("\t");
Serial.println(ypr[2] * 180 / M_PI);
sprintf(dataBuf,"%f,",ypr[0] * 180 / M_PI);
Genotronex.print(dataBuf);
sprintf(dataBuf,"%f,",ypr[1] * 180 / M_PI);
Genotronex.print(dataBuf);
sprintf(dataBuf,"%f,",ypr[2] * 180 / M_PI);
Genotronex.print(dataBuf);
#endif
#ifdef OUTPUT_READABLE_REALACCEL
// display real acceleration, adjusted to remove gravity
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetAccel(&aa, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
Serial.print("areal\t");
Serial.print(aaReal.x);
Serial.print("\t");
Serial.print(aaReal.y);
Serial.print("\t");
Serial.println(aaReal.z);
Genotronex.print("1,1,1");
#endif
#ifdef OUTPUT_READABLE_WORLDACCEL
// display initial world-frame acceleration, adjusted to remove gravity
// and rotated based on known orientation from quaternion
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetAccel(&aa, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
Serial.print("aworld\t");
Serial.print(aaWorld.x);
Serial.print("\t");
Serial.print(aaWorld.y);
Serial.print("\t");
Serial.println(aaWorld.z);
Genotronex.print("1,1,1");
#endif
#ifdef OUTPUT_TEAPOT
// display quaternion values in InvenSense Teapot demo format:
teapotPacket[2] = fifoBuffer[0];
teapotPacket[3] = fifoBuffer[1];
teapotPacket[4] = fifoBuffer[4];
teapotPacket[5] = fifoBuffer[5];
teapotPacket[6] = fifoBuffer[8];
teapotPacket[7] = fifoBuffer[9];
teapotPacket[8] = fifoBuffer[12];
teapotPacket[9] = fifoBuffer[13];
Serial.write(teapotPacket, 14);
teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
#endif
}
Genotronex.println("");
}
| [
"[email protected]"
] | |
16ef62861b72372cd2f91e2755b073b3363ae9d0 | cec302f1b0a1f4c41c3a0b5f9b90d4ab902005a6 | /case-studies/bzip2/src/MyEnclave/Lmbench/lat_connect.cpp | f4324d72f06d9efdc7f813db63605cb6fe7fa801 | [
"Apache-2.0"
] | permissive | kripa432/Panoply | cf4ea0f63cd3c1216f7a97bc1cf77a14afa019af | 6287e7feacc49c4bc6cc0229e793600b49545251 | refs/heads/master | 2022-09-11T15:06:22.609854 | 2020-06-03T04:51:59 | 2020-06-03T04:51:59 | 266,686,111 | 0 | 0 | null | 2020-05-25T04:53:14 | 2020-05-25T04:53:14 | null | UTF-8 | C++ | false | false | 2,784 | cpp | /*
* lat_connect.c - simple TCP connection latency test
*
* Three programs in one -
* server usage: lat_connect -s
* client usage: lat_connect [-N <repetitions>] hostname
* shutdown: lat_connect -hostname
*
* lat_connect may not be parallelized because of idiosyncracies
* with TCP connection creation. Basically, if the client tries
* to create too many connections too quickly, the system fills
* up the set of available connections with TIME_WAIT connections.
* We can only measure the TCP connection cost accurately if we
* do just a few connections. Since the parallel harness needs
* each child to run for a second, this guarantees that the
* parallel version will generate inaccurate results.
*
* Copyright (c) 1994 Larry McVoy. Distributed under the FSF GPL with
* additional restriction that results may published only if
* (1) the benchmark is unmodified, and
* (2) the version in the sccsid below is included in the report.
* Support for this development by Sun Microsystems is gratefully acknowledged.
*/
// Fix me: id is share now
// char *id = "$Id$\n";
#include "bench.h"
void latconnect_server_main(int ac, char **av);
void latconnect_client_main(int ac, char **av);
void
latconnect_doit(char *server)
{
int sock = tcp_connect(server, TCP_CONNECT, SOCKOPT_NONE);
close(sock);
}
int
latconnect_main(int ac, char **av)
{
if (ac != 2) {
fprintf(stderr, "Usage: %s -s OR %s [-]serverhost\n",
av[0], av[0]);
exit(1);
}
if (!strcmp(av[1], "-s")) {
if (fork() == 0) {
latconnect_server_main(ac, av);
}
exit(0);
} else {
latconnect_client_main(ac, av);
}
exit(0);
/* NOTREACHED */
}
void
latconnect_client_main(int ac, char **av)
{
int sock;
char *server;
char buf[256];
if (ac != 2) {
fprintf(stderr, "usage: %s host\n", av[0]);
exit(1);
}
char* av1 = strdup(av[1]);
server = av1[0] == '-' ? &av1[1] : av1;
/*
* Stop server code.
*/
if (av1[0] == '-') {
sock = tcp_connect(server, TCP_CONNECT, SOCKOPT_NONE);
write(sock, "0", 1);
close(sock);
exit(0);
/* NOTREACHED */
}
/*
* We don't want more than a few of these, they stack up in time wait.
* XXX - report an error if the clock is too shitty?
*/
BENCH(latconnect_doit(server), 0);
snprintf(buf, 256, "TCP/IP connection cost to %s", server);
micro(buf, get_n());
exit(0);
/* NOTREACHED */
}
void
latconnect_server_main(int ac, char **av)
{
int newsock, sock, n;
char c;
if (ac != 2) {
fprintf(stderr, "usage: %s -s\n", av[0]);
exit(1);
}
GO_AWAY;
sock = tcp_server(TCP_CONNECT, SOCKOPT_REUSE);
for (;;) {
newsock = tcp_accept(sock, SOCKOPT_NONE);
c = 0;
n = read(newsock, &c, 1);
if (n > 0 && c == '0') {
tcp_done(TCP_CONNECT);
exit(0);
}
close(newsock);
}
/* NOTREACHED */
}
| [
"[email protected]"
] | |
5bfcdf7c397e0bebec19bb09c04453a61ee10939 | 9030ce2789a58888904d0c50c21591632eddffd7 | /SDK/ARKSurvivalEvolved_Spindles_Character_BP_Rockwell_Summoned_classes.hpp | 2db9b07a8ddb2a360e8fc6c94875094935fc0fba | [
"MIT"
] | permissive | 2bite/ARK-SDK | 8ce93f504b2e3bd4f8e7ced184980b13f127b7bf | ce1f4906ccf82ed38518558c0163c4f92f5f7b14 | refs/heads/master | 2022-09-19T06:28:20.076298 | 2022-09-03T17:21:00 | 2022-09-03T17:21:00 | 232,411,353 | 14 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 967 | hpp | #pragma once
// ARKSurvivalEvolved (332.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Spindles_Character_BP_Rockwell_Summoned_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Spindles_Character_BP_Rockwell_Summoned.Spindles_Character_BP_Rockwell_Summoned_C
// 0x0000 (0x29D5 - 0x29D5)
class ASpindles_Character_BP_Rockwell_Summoned_C : public ASpindles_Character_BP_Rockwell_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass Spindles_Character_BP_Rockwell_Summoned.Spindles_Character_BP_Rockwell_Summoned_C");
return ptr;
}
void UserConstructionScript();
void ExecuteUbergraph_Spindles_Character_BP_Rockwell_Summoned(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
3492c1530ab36c8c402ea9f6b7c67680454e47f8 | 5ca734f1ca03d9ea92a558f18a9472cab77b1dd5 | /include/findpeaks.h | 1fbb5af602ce19a2de4d476e723430a840283651 | [] | no_license | ifapmzadu6/speech-analyzer | 20c6a9b833691348e3992fdb26d7fb2f0ec39eff | f0c842063c56b7b1a66d86564be0fbbaa9c284a1 | refs/heads/master | 2021-01-19T13:24:42.130578 | 2016-02-24T02:10:33 | 2016-02-24T02:10:33 | 39,020,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 227 | h | #pragma once
#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>
template <typename T>
class FindPeaks {
public:
static std::vector<int> finds(std::vector<T> &input);
static void tests();
};
| [
"[email protected]"
] | |
8dcc67ecfe2fae85f9bef208873156ca31de9c07 | eb6764a89076805e8ee2f5f6a5be5720ac0397b8 | /book.EOPI/2.6.cc | f5f62a6c4a37099ab1ea38754811bd5d24cc75af | [] | no_license | brooksbp/snippets | ad8fa19f505528ba47499640407b37ed928503bf | ad9d61251a9e78075af3ede5d7a2fb09a2658b80 | refs/heads/master | 2021-10-10T01:54:10.175654 | 2019-01-06T04:52:42 | 2019-01-06T04:52:42 | 1,210,248 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 867 | cc | // Implement string/integer inter-conversion functions.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string intToString(int x) {
string s;
if (x == 0) {
s.push_back('0');
return s;
}
bool negative = (x < 0);
if (negative) {
x = -x;
}
while (x) {
s.push_back('0' + (x % 10));
x /= 10;
}
if (negative) {
s.push_back('-');
}
reverse(s.begin(), s.end());
return s;
}
int stringToInt(string s) {
int idx;
bool negative;
if (s[0] == '-') {
negative = true; idx = 1;
} else {
negative = false; idx = 0;
}
int x = 0;
while (idx < s.size()) {
if (isdigit(s[idx])) {
x = x * 10 + (s[idx++] - '0');
}
}
return negative ? -x : x;
}
int main(int argc, char *argv[]) {
cout << intToString(-543);
cout << stringToInt(string("-543"));
return 0;
}
| [
"[email protected]"
] | |
15ab24f72afd69e5befb0532014fca0aa4ce2bf6 | efe2b4dedbc6bab31ffe88c271daa5463f8649f6 | /tags/libtorrent-0_14_8/src/disk_io_thread.cpp | 0af8dad5ee5039d7c9faa3ab1e65c9abfcc244d8 | [] | no_license | svn2github/libtorrent | 867c84f0c271cdc255c3e268c17db75d46010dde | 8cfe21e253d8b90086bb0b15c6c881795bf12ea1 | refs/heads/master | 2020-03-30T03:50:32.931129 | 2015-01-07T23:21:54 | 2015-01-07T23:21:54 | 17,344,601 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 33,338 | cpp | /*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/storage.hpp"
#include <deque>
#include "libtorrent/disk_io_thread.hpp"
#include "libtorrent/disk_buffer_holder.hpp"
#include <boost/scoped_array.hpp>
#ifdef _WIN32
#include <malloc.h>
#ifndef alloca
#define alloca(s) _alloca(s)
#endif
#endif
#ifdef TORRENT_DISK_STATS
#include "libtorrent/time.hpp"
#endif
namespace libtorrent
{
disk_io_thread::disk_io_thread(asio::io_service& ios, int block_size)
: m_abort(false)
, m_queue_buffer_size(0)
, m_cache_size(512) // 512 * 16kB = 8MB
, m_cache_expiry(60) // 1 minute
, m_coalesce_writes(true)
, m_coalesce_reads(true)
, m_use_read_cache(true)
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
, m_pool(block_size, 16)
#endif
, m_block_size(block_size)
, m_ios(ios)
, m_work(io_service::work(m_ios))
, m_disk_io_thread(boost::ref(*this))
{
#ifdef TORRENT_STATS
m_allocations = 0;
#endif
#ifdef TORRENT_DISK_STATS
m_log.open("disk_io_thread.log", std::ios::trunc);
#endif
#ifdef TORRENT_DEBUG
m_magic = 0x1337;
#endif
}
disk_io_thread::~disk_io_thread()
{
TORRENT_ASSERT(m_abort == true);
TORRENT_ASSERT(m_magic == 0x1337);
#ifdef TORRENT_DEBUG
m_magic = 0;
#endif
}
void disk_io_thread::join()
{
mutex_t::scoped_lock l(m_queue_mutex);
disk_io_job j;
j.action = disk_io_job::abort_thread;
m_jobs.insert(m_jobs.begin(), j);
m_signal.notify_all();
l.unlock();
m_disk_io_thread.join();
l.lock();
TORRENT_ASSERT(m_abort == true);
m_jobs.clear();
}
void disk_io_thread::get_cache_info(sha1_hash const& ih, std::vector<cached_piece_info>& ret) const
{
mutex_t::scoped_lock l(m_piece_mutex);
ret.clear();
ret.reserve(m_pieces.size());
for (cache_t::const_iterator i = m_pieces.begin()
, end(m_pieces.end()); i != end; ++i)
{
torrent_info const& ti = *i->storage->info();
if (ti.info_hash() != ih) continue;
cached_piece_info info;
info.piece = i->piece;
info.last_use = i->last_use;
info.kind = cached_piece_info::write_cache;
int blocks_in_piece = (ti.piece_size(i->piece) + (m_block_size) - 1) / m_block_size;
info.blocks.resize(blocks_in_piece);
for (int b = 0; b < blocks_in_piece; ++b)
if (i->blocks[b]) info.blocks[b] = true;
ret.push_back(info);
}
for (cache_t::const_iterator i = m_read_pieces.begin()
, end(m_read_pieces.end()); i != end; ++i)
{
torrent_info const& ti = *i->storage->info();
if (ti.info_hash() != ih) continue;
cached_piece_info info;
info.piece = i->piece;
info.last_use = i->last_use;
info.kind = cached_piece_info::read_cache;
int blocks_in_piece = (ti.piece_size(i->piece) + (m_block_size) - 1) / m_block_size;
info.blocks.resize(blocks_in_piece);
for (int b = 0; b < blocks_in_piece; ++b)
if (i->blocks[b]) info.blocks[b] = true;
ret.push_back(info);
}
}
cache_status disk_io_thread::status() const
{
mutex_t::scoped_lock l(m_piece_mutex);
return m_cache_stats;
}
void disk_io_thread::set_cache_size(int s)
{
mutex_t::scoped_lock l(m_piece_mutex);
TORRENT_ASSERT(s >= 0);
m_cache_size = s;
}
void disk_io_thread::set_cache_expiry(int ex)
{
mutex_t::scoped_lock l(m_piece_mutex);
TORRENT_ASSERT(ex > 0);
m_cache_expiry = ex;
}
// aborts read operations
void disk_io_thread::stop(boost::intrusive_ptr<piece_manager> s)
{
mutex_t::scoped_lock l(m_queue_mutex);
// read jobs are aborted, write and move jobs are syncronized
for (std::list<disk_io_job>::iterator i = m_jobs.begin();
i != m_jobs.end();)
{
if (i->storage != s)
{
++i;
continue;
}
if (i->action == disk_io_job::read)
{
if (i->callback) m_ios.post(boost::bind(i->callback, -1, *i));
m_jobs.erase(i++);
continue;
}
if (i->action == disk_io_job::check_files)
{
if (i->callback) m_ios.post(boost::bind(i->callback
, piece_manager::disk_check_aborted, *i));
m_jobs.erase(i++);
continue;
}
++i;
}
disk_io_job j;
j.action = disk_io_job::abort_torrent;
j.storage = s;
add_job(j);
}
bool range_overlap(int start1, int length1, int start2, int length2)
{
return (start1 <= start2 && start1 + length1 > start2)
|| (start2 <= start1 && start2 + length2 > start1);
}
namespace
{
// The semantic of this operator is:
// should lhs come before rhs in the job queue
bool operator<(disk_io_job const& lhs, disk_io_job const& rhs)
{
// NOTE: comparison inverted to make higher priority
// skip _in_front_of_ lower priority
if (lhs.priority > rhs.priority) return true;
if (lhs.priority < rhs.priority) return false;
if (lhs.storage.get() < rhs.storage.get()) return true;
if (lhs.storage.get() > rhs.storage.get()) return false;
if (lhs.piece < rhs.piece) return true;
if (lhs.piece > rhs.piece) return false;
if (lhs.offset < rhs.offset) return true;
// if (lhs.offset > rhs.offset) return false;
return false;
}
}
disk_io_thread::cache_t::iterator disk_io_thread::find_cached_piece(
disk_io_thread::cache_t& cache
, disk_io_job const& j, mutex_t::scoped_lock& l)
{
for (cache_t::iterator i = cache.begin()
, end(cache.end()); i != end; ++i)
{
if (i->storage != j.storage || i->piece != j.piece) continue;
return i;
}
return cache.end();
}
void disk_io_thread::flush_expired_pieces()
{
ptime now = time_now();
mutex_t::scoped_lock l(m_piece_mutex);
INVARIANT_CHECK;
for (;;)
{
cache_t::iterator i = std::min_element(
m_pieces.begin(), m_pieces.end()
, bind(&cached_piece_entry::last_use, _1)
< bind(&cached_piece_entry::last_use, _2));
if (i == m_pieces.end()) return;
int age = total_seconds(now - i->last_use);
if (age < m_cache_expiry) return;
flush_and_remove(i, l);
}
}
void disk_io_thread::free_piece(cached_piece_entry& p, mutex_t::scoped_lock& l)
{
int piece_size = p.storage->info()->piece_size(p.piece);
int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;
for (int i = 0; i < blocks_in_piece; ++i)
{
if (p.blocks[i] == 0) continue;
free_buffer(p.blocks[i]);
p.blocks[i] = 0;
--p.num_blocks;
--m_cache_stats.cache_size;
--m_cache_stats.read_cache_size;
}
}
bool disk_io_thread::clear_oldest_read_piece(
cache_t::iterator ignore
, mutex_t::scoped_lock& l)
{
INVARIANT_CHECK;
cache_t::iterator i = std::min_element(
m_read_pieces.begin(), m_read_pieces.end()
, bind(&cached_piece_entry::last_use, _1)
< bind(&cached_piece_entry::last_use, _2));
if (i != m_read_pieces.end() && i != ignore)
{
// don't replace an entry that is less than one second old
if (time_now() - i->last_use < seconds(1)) return false;
free_piece(*i, l);
m_read_pieces.erase(i);
return true;
}
return false;
}
void disk_io_thread::flush_oldest_piece(mutex_t::scoped_lock& l)
{
INVARIANT_CHECK;
// first look if there are any read cache entries that can
// be cleared
if (clear_oldest_read_piece(m_read_pieces.end(), l)) return;
cache_t::iterator i = std::min_element(
m_pieces.begin(), m_pieces.end()
, bind(&cached_piece_entry::last_use, _1)
< bind(&cached_piece_entry::last_use, _2));
if (i == m_pieces.end()) return;
flush_and_remove(i, l);
}
void disk_io_thread::flush_and_remove(disk_io_thread::cache_t::iterator e
, mutex_t::scoped_lock& l)
{
flush(e, l);
m_pieces.erase(e);
}
void disk_io_thread::flush(disk_io_thread::cache_t::iterator e
, mutex_t::scoped_lock& l)
{
INVARIANT_CHECK;
cached_piece_entry& p = *e;
int piece_size = p.storage->info()->piece_size(p.piece);
#ifdef TORRENT_DISK_STATS
m_log << log_time() << " flushing " << piece_size << std::endl;
#endif
TORRENT_ASSERT(piece_size > 0);
boost::scoped_array<char> buf;
if (m_coalesce_writes) buf.reset(new (std::nothrow) char[piece_size]);
int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;
int buffer_size = 0;
int offset = 0;
for (int i = 0; i <= blocks_in_piece; ++i)
{
if (i == blocks_in_piece || p.blocks[i] == 0)
{
if (buffer_size == 0) continue;
TORRENT_ASSERT(buf);
TORRENT_ASSERT(buffer_size <= i * m_block_size);
l.unlock();
p.storage->write_impl(buf.get(), p.piece, (std::min)(
i * m_block_size, piece_size) - buffer_size, buffer_size);
l.lock();
++m_cache_stats.writes;
// std::cerr << " flushing p: " << p.piece << " bytes: " << buffer_size << std::endl;
buffer_size = 0;
offset = 0;
continue;
}
int block_size = (std::min)(piece_size - i * m_block_size, m_block_size);
TORRENT_ASSERT(offset + block_size <= piece_size);
TORRENT_ASSERT(offset + block_size > 0);
if (!buf)
{
l.unlock();
p.storage->write_impl(p.blocks[i], p.piece, i * m_block_size, block_size);
l.lock();
++m_cache_stats.writes;
}
else
{
std::memcpy(buf.get() + offset, p.blocks[i], block_size);
offset += m_block_size;
buffer_size += block_size;
}
free_buffer(p.blocks[i]);
p.blocks[i] = 0;
TORRENT_ASSERT(p.num_blocks > 0);
--p.num_blocks;
++m_cache_stats.blocks_written;
--m_cache_stats.cache_size;
}
TORRENT_ASSERT(buffer_size == 0);
// std::cerr << " flushing p: " << p.piece << " cached_blocks: " << m_cache_stats.cache_size << std::endl;
#ifdef TORRENT_DEBUG
for (int i = 0; i < blocks_in_piece; ++i)
TORRENT_ASSERT(p.blocks[i] == 0);
#endif
}
// returns -1 on failure
int disk_io_thread::cache_block(disk_io_job& j, mutex_t::scoped_lock& l)
{
INVARIANT_CHECK;
TORRENT_ASSERT(find_cached_piece(m_pieces, j, l) == m_pieces.end());
TORRENT_ASSERT((j.offset & (m_block_size-1)) == 0);
cached_piece_entry p;
int piece_size = j.storage->info()->piece_size(j.piece);
int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;
p.piece = j.piece;
p.storage = j.storage;
p.last_use = time_now();
p.num_blocks = 1;
p.blocks.reset(new (std::nothrow) char*[blocks_in_piece]);
if (!p.blocks) return -1;
std::memset(&p.blocks[0], 0, blocks_in_piece * sizeof(char*));
int block = j.offset / m_block_size;
// std::cerr << " adding cache entry for p: " << j.piece << " block: " << block << " cached_blocks: " << m_cache_stats.cache_size << std::endl;
p.blocks[block] = j.buffer;
++m_cache_stats.cache_size;
m_pieces.push_back(p);
return 0;
}
// fills a piece with data from disk, returns the total number of bytes
// read or -1 if there was an error
int disk_io_thread::read_into_piece(cached_piece_entry& p, int start_block, mutex_t::scoped_lock& l)
{
int piece_size = p.storage->info()->piece_size(p.piece);
int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;
int end_block = start_block;
for (int i = start_block; i < blocks_in_piece
&& m_cache_stats.cache_size < m_cache_size; ++i)
{
// this is a block that is already allocated
// stop allocating and don't read more than
// what we've allocated now
if (p.blocks[i]) break;
p.blocks[i] = allocate_buffer();
// the allocation failed, break
if (p.blocks[i] == 0) break;
++p.num_blocks;
++m_cache_stats.cache_size;
++m_cache_stats.read_cache_size;
++end_block;
}
if (end_block == start_block) return -2;
// the buffer_size is the size of the buffer we need to read
// all these blocks.
const int buffer_size = (std::min)((end_block - start_block) * m_block_size
, piece_size - start_block * m_block_size);
TORRENT_ASSERT(buffer_size <= piece_size);
TORRENT_ASSERT(buffer_size + start_block * m_block_size <= piece_size);
boost::scoped_array<char> buf;
if (m_coalesce_reads) buf.reset(new (std::nothrow) char[buffer_size]);
int ret = 0;
if (buf)
{
l.unlock();
ret += p.storage->read_impl(buf.get(), p.piece, start_block * m_block_size, buffer_size);
l.lock();
if (p.storage->error()) { return -1; }
++m_cache_stats.reads;
}
int piece_offset = start_block * m_block_size;
int offset = 0;
for (int i = start_block; i < end_block; ++i)
{
int block_size = (std::min)(piece_size - piece_offset, m_block_size);
if (p.blocks[i] == 0) break;
TORRENT_ASSERT(offset <= buffer_size);
TORRENT_ASSERT(piece_offset <= piece_size);
TORRENT_ASSERT(offset + block_size <= buffer_size);
if (buf)
{
std::memcpy(p.blocks[i], buf.get() + offset, block_size);
}
else
{
l.unlock();
ret += p.storage->read_impl(p.blocks[i], p.piece, piece_offset, block_size);
if (p.storage->error()) { return -1; }
l.lock();
++m_cache_stats.reads;
}
offset += m_block_size;
piece_offset += m_block_size;
}
TORRENT_ASSERT(ret <= buffer_size);
return (ret != buffer_size) ? -1 : ret;
}
bool disk_io_thread::make_room(int num_blocks
, cache_t::iterator ignore
, mutex_t::scoped_lock& l)
{
if (m_cache_size - m_cache_stats.cache_size < num_blocks)
{
// there's not enough room in the cache, clear a piece
// from the read cache
if (!clear_oldest_read_piece(ignore, l)) return false;
}
return m_cache_size - m_cache_stats.cache_size >= num_blocks;
}
// returns -1 on read error, -2 if there isn't any space in the cache
// or the number of bytes read
int disk_io_thread::cache_read_block(disk_io_job const& j, mutex_t::scoped_lock& l)
{
INVARIANT_CHECK;
int piece_size = j.storage->info()->piece_size(j.piece);
int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;
int start_block = j.offset / m_block_size;
if (!make_room(blocks_in_piece - start_block
, m_read_pieces.end(), l)) return -2;
cached_piece_entry p;
p.piece = j.piece;
p.storage = j.storage;
p.last_use = time_now();
p.num_blocks = 0;
p.blocks.reset(new (std::nothrow) char*[blocks_in_piece]);
if (!p.blocks) return -1;
std::memset(&p.blocks[0], 0, blocks_in_piece * sizeof(char*));
int ret = read_into_piece(p, start_block, l);
if (ret < 0)
free_piece(p, l);
else
m_read_pieces.push_back(p);
return ret;
}
#ifdef TORRENT_DEBUG
void disk_io_thread::check_invariant() const
{
int cached_write_blocks = 0;
for (cache_t::const_iterator i = m_pieces.begin()
, end(m_pieces.end()); i != end; ++i)
{
cached_piece_entry const& p = *i;
TORRENT_ASSERT(p.blocks);
if (!p.storage) continue;
int piece_size = p.storage->info()->piece_size(p.piece);
int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;
int blocks = 0;
for (int k = 0; k < blocks_in_piece; ++k)
{
if (p.blocks[k])
{
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
TORRENT_ASSERT(is_disk_buffer(p.blocks[k]));
#endif
++blocks;
}
}
// TORRENT_ASSERT(blocks == p.num_blocks);
cached_write_blocks += blocks;
}
int cached_read_blocks = 0;
for (cache_t::const_iterator i = m_read_pieces.begin()
, end(m_read_pieces.end()); i != end; ++i)
{
cached_piece_entry const& p = *i;
TORRENT_ASSERT(p.blocks);
int piece_size = p.storage->info()->piece_size(p.piece);
int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;
int blocks = 0;
for (int k = 0; k < blocks_in_piece; ++k)
{
if (p.blocks[k])
{
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
TORRENT_ASSERT(is_disk_buffer(p.blocks[k]));
#endif
++blocks;
}
}
// TORRENT_ASSERT(blocks == p.num_blocks);
cached_read_blocks += blocks;
}
TORRENT_ASSERT(cached_read_blocks + cached_write_blocks == m_cache_stats.cache_size);
TORRENT_ASSERT(cached_read_blocks == m_cache_stats.read_cache_size);
// when writing, there may be a one block difference, right before an old piece
// is flushed
TORRENT_ASSERT(m_cache_stats.cache_size <= m_cache_size + 1);
}
#endif
int disk_io_thread::try_read_from_cache(disk_io_job const& j)
{
TORRENT_ASSERT(j.buffer);
mutex_t::scoped_lock l(m_piece_mutex);
if (!m_use_read_cache) return -2;
cache_t::iterator p
= find_cached_piece(m_read_pieces, j, l);
bool hit = true;
int ret = 0;
// if the piece cannot be found in the cache,
// read the whole piece starting at the block
// we got a request for.
if (p == m_read_pieces.end())
{
ret = cache_read_block(j, l);
hit = false;
if (ret < 0) return ret;
p = m_read_pieces.end();
--p;
TORRENT_ASSERT(!m_read_pieces.empty());
TORRENT_ASSERT(p->piece == j.piece);
TORRENT_ASSERT(p->storage == j.storage);
}
if (p != m_read_pieces.end())
{
// copy from the cache and update the last use timestamp
int block = j.offset / m_block_size;
int block_offset = j.offset % m_block_size;
int buffer_offset = 0;
int size = j.buffer_size;
if (p->blocks[block] == 0)
{
int piece_size = j.storage->info()->piece_size(j.piece);
int blocks_in_piece = (piece_size + m_block_size - 1) / m_block_size;
int end_block = block;
while (end_block < blocks_in_piece && p->blocks[end_block] == 0) ++end_block;
if (!make_room(end_block - block, p, l)) return -2;
ret = read_into_piece(*p, block, l);
hit = false;
if (ret < 0) return ret;
TORRENT_ASSERT(p->blocks[block]);
}
p->last_use = time_now();
while (size > 0)
{
TORRENT_ASSERT(p->blocks[block]);
int to_copy = (std::min)(m_block_size
- block_offset, size);
std::memcpy(j.buffer + buffer_offset
, p->blocks[block] + block_offset
, to_copy);
size -= to_copy;
block_offset = 0;
buffer_offset += to_copy;
++block;
}
ret = j.buffer_size;
++m_cache_stats.blocks_read;
if (hit) ++m_cache_stats.blocks_read_hit;
}
return ret;
}
void disk_io_thread::add_job(disk_io_job const& j
, boost::function<void(int, disk_io_job const&)> const& f)
{
TORRENT_ASSERT(!m_abort);
TORRENT_ASSERT(!j.callback);
TORRENT_ASSERT(j.storage);
TORRENT_ASSERT(j.buffer_size <= m_block_size);
mutex_t::scoped_lock l(m_queue_mutex);
std::list<disk_io_job>::reverse_iterator i = m_jobs.rbegin();
if (j.action == disk_io_job::read)
{
// when we're reading, we may not skip
// ahead of any write operation that overlaps
// the region we're reading
for (; i != m_jobs.rend(); i++)
{
// if *i should come before j, stop
// and insert j before i
if (*i < j) break;
// if we come across a write operation that
// overlaps the region we're reading, we need
// to stop
if (i->action == disk_io_job::write
&& i->storage == j.storage
&& i->piece == j.piece
&& range_overlap(i->offset, i->buffer_size
, j.offset, j.buffer_size))
break;
}
}
else if (j.action == disk_io_job::write)
{
for (; i != m_jobs.rend(); ++i)
{
if (*i < j)
{
if (i != m_jobs.rbegin()
&& i.base()->storage.get() != j.storage.get())
i = m_jobs.rbegin();
break;
}
}
}
// if we are placed in front of all other jobs, put it on the back of
// the queue, to sweep the disk in the same direction, and to avoid
// starvation. The exception is if the priority is higher than the
// job at the front of the queue
if (i == m_jobs.rend() && (m_jobs.empty() || j.priority <= m_jobs.back().priority))
i = m_jobs.rbegin();
std::list<disk_io_job>::iterator k = m_jobs.insert(i.base(), j);
k->callback.swap(const_cast<boost::function<void(int, disk_io_job const&)>&>(f));
if (j.action == disk_io_job::write)
m_queue_buffer_size += j.buffer_size;
TORRENT_ASSERT(j.storage.get());
m_signal.notify_all();
}
#ifdef TORRENT_DEBUG
bool disk_io_thread::is_disk_buffer(char* buffer) const
{
TORRENT_ASSERT(m_magic == 0x1337);
#ifdef TORRENT_DISABLE_POOL_ALLOCATOR
return true;
#else
mutex_t::scoped_lock l(m_pool_mutex);
#ifdef TORRENT_DISK_STATS
if (m_buf_to_category.find(buffer)
== m_buf_to_category.end()) return false;
#endif
return m_pool.is_from(buffer);
#endif
}
#endif
char* disk_io_thread::allocate_buffer()
{
mutex_t::scoped_lock l(m_pool_mutex);
TORRENT_ASSERT(m_magic == 0x1337);
#ifdef TORRENT_STATS
++m_allocations;
#endif
#ifdef TORRENT_DISABLE_POOL_ALLOCATOR
return (char*)malloc(m_block_size);
#else
m_pool.set_next_size(16);
return (char*)m_pool.ordered_malloc();
#endif
}
void disk_io_thread::free_buffer(char* buf)
{
mutex_t::scoped_lock l(m_pool_mutex);
TORRENT_ASSERT(m_magic == 0x1337);
#ifdef TORRENT_STATS
--m_allocations;
#endif
#ifdef TORRENT_DISABLE_POOL_ALLOCATOR
free(buf);
#else
m_pool.ordered_free(buf);
#endif
}
bool disk_io_thread::test_error(disk_io_job& j)
{
error_code const& ec = j.storage->error();
if (ec)
{
j.buffer = 0;
j.str = ec.message();
j.error = ec;
j.error_file = j.storage->error_file();
j.storage->clear_error();
#ifdef TORRENT_DEBUG
std::cout << "ERROR: '" << j.str << "' " << j.error_file << std::endl;
#endif
return true;
}
return false;
}
void disk_io_thread::operator()()
{
for (;;)
{
#ifdef TORRENT_DISK_STATS
m_log << log_time() << " idle" << std::endl;
#endif
mutex_t::scoped_lock jl(m_queue_mutex);
while (m_jobs.empty() && !m_abort)
m_signal.wait(jl);
if (m_abort && m_jobs.empty())
{
jl.unlock();
mutex_t::scoped_lock l(m_piece_mutex);
// flush all disk caches
for (cache_t::iterator i = m_pieces.begin()
, end(m_pieces.end()); i != end; ++i)
flush(i, l);
for (cache_t::iterator i = m_read_pieces.begin()
, end(m_read_pieces.end()); i != end; ++i)
free_piece(*i, l);
m_pieces.clear();
m_read_pieces.clear();
// release the io_service to allow the run() call to return
// we do this once we stop posting new callbacks to it.
m_work.reset();
return;
}
// if there's a buffer in this job, it will be freed
// when this holder is destructed, unless it has been
// released.
disk_buffer_holder holder(*this
, m_jobs.front().action != disk_io_job::check_fastresume
? m_jobs.front().buffer : 0);
boost::function<void(int, disk_io_job const&)> handler;
handler.swap(m_jobs.front().callback);
disk_io_job j = m_jobs.front();
m_jobs.pop_front();
m_queue_buffer_size -= j.buffer_size;
jl.unlock();
flush_expired_pieces();
int ret = 0;
TORRENT_ASSERT(j.storage || j.action == disk_io_job::abort_thread);
#ifdef TORRENT_DISK_STATS
ptime start = time_now();
#endif
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
switch (j.action)
{
case disk_io_job::abort_torrent:
{
mutex_t::scoped_lock jl(m_queue_mutex);
for (std::list<disk_io_job>::iterator i = m_jobs.begin();
i != m_jobs.end();)
{
if (i->storage != j.storage)
{
++i;
continue;
}
if (i->action == disk_io_job::check_files)
{
if (i->callback) m_ios.post(boost::bind(i->callback
, piece_manager::disk_check_aborted, *i));
m_jobs.erase(i++);
continue;
}
++i;
}
break;
}
case disk_io_job::abort_thread:
{
mutex_t::scoped_lock jl(m_queue_mutex);
for (std::list<disk_io_job>::iterator i = m_jobs.begin();
i != m_jobs.end();)
{
if (i->action == disk_io_job::read)
{
if (i->callback) m_ios.post(boost::bind(i->callback, -1, *i));
m_jobs.erase(i++);
continue;
}
if (i->action == disk_io_job::check_files)
{
if (i->callback) m_ios.post(bind(i->callback
, piece_manager::disk_check_aborted, *i));
m_jobs.erase(i++);
continue;
}
++i;
}
m_abort = true;
break;
}
case disk_io_job::read:
{
if (test_error(j))
{
ret = -1;
break;
}
#ifdef TORRENT_DISK_STATS
m_log << log_time() << " read " << j.buffer_size << std::endl;
#endif
INVARIANT_CHECK;
TORRENT_ASSERT(j.buffer == 0);
j.buffer = allocate_buffer();
TORRENT_ASSERT(j.buffer_size <= m_block_size);
if (j.buffer == 0)
{
ret = -1;
j.error = error_code(ENOMEM, get_posix_category());
j.str = j.error.message();
break;
}
disk_buffer_holder read_holder(*this, j.buffer);
ret = try_read_from_cache(j);
// -2 means there's no space in the read cache
// or that the read cache is disabled
if (ret == -1)
{
test_error(j);
break;
}
else if (ret == -2)
{
ret = j.storage->read_impl(j.buffer, j.piece, j.offset
, j.buffer_size);
if (ret < 0)
{
test_error(j);
break;
}
++m_cache_stats.blocks_read;
}
TORRENT_ASSERT(j.buffer == read_holder.get());
read_holder.release();
break;
}
case disk_io_job::write:
{
if (test_error(j))
{
ret = -1;
break;
}
#ifdef TORRENT_DISK_STATS
m_log << log_time() << " write " << j.buffer_size << std::endl;
#endif
mutex_t::scoped_lock l(m_piece_mutex);
INVARIANT_CHECK;
cache_t::iterator p
= find_cached_piece(m_pieces, j, l);
int block = j.offset / m_block_size;
TORRENT_ASSERT(j.buffer);
TORRENT_ASSERT(j.buffer_size <= m_block_size);
if (p != m_pieces.end())
{
TORRENT_ASSERT(p->blocks[block] == 0);
if (p->blocks[block])
{
free_buffer(p->blocks[block]);
--p->num_blocks;
}
p->blocks[block] = j.buffer;
++m_cache_stats.cache_size;
++p->num_blocks;
p->last_use = time_now();
}
else
{
if (cache_block(j, l) < 0)
{
ret = j.storage->write_impl(j.buffer, j.piece, j.offset, j.buffer_size);
if (ret < 0)
{
test_error(j);
break;
}
break;
}
}
// we've now inserted the buffer
// in the cache, we should not
// free it at the end
holder.release();
if (m_cache_stats.cache_size >= m_cache_size)
flush_oldest_piece(l);
break;
}
case disk_io_job::hash:
{
#ifdef TORRENT_DISK_STATS
m_log << log_time() << " hash" << std::endl;
#endif
mutex_t::scoped_lock l(m_piece_mutex);
INVARIANT_CHECK;
cache_t::iterator i
= find_cached_piece(m_pieces, j, l);
if (i != m_pieces.end())
{
flush_and_remove(i, l);
if (test_error(j))
{
ret = -1;
j.storage->mark_failed(j.piece);
break;
}
}
l.unlock();
sha1_hash h = j.storage->hash_for_piece_impl(j.piece);
if (test_error(j))
{
ret = -1;
j.storage->mark_failed(j.piece);
break;
}
ret = (j.storage->info()->hash_for_piece(j.piece) == h)?0:-2;
if (ret == -2) j.storage->mark_failed(j.piece);
break;
}
case disk_io_job::move_storage:
{
#ifdef TORRENT_DISK_STATS
m_log << log_time() << " move" << std::endl;
#endif
TORRENT_ASSERT(j.buffer == 0);
ret = j.storage->move_storage_impl(j.str);
if (ret != 0)
{
test_error(j);
break;
}
j.str = j.storage->save_path().string();
break;
}
case disk_io_job::release_files:
{
#ifdef TORRENT_DISK_STATS
m_log << log_time() << " release" << std::endl;
#endif
TORRENT_ASSERT(j.buffer == 0);
mutex_t::scoped_lock l(m_piece_mutex);
INVARIANT_CHECK;
for (cache_t::iterator i = m_pieces.begin(); i != m_pieces.end();)
{
if (i->storage == j.storage)
{
flush(i, l);
i = m_pieces.erase(i);
}
else
{
++i;
}
}
l.unlock();
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
{
mutex_t::scoped_lock l(m_pool_mutex);
TORRENT_ASSERT(m_magic == 0x1337);
m_pool.release_memory();
}
#endif
ret = j.storage->release_files_impl();
if (ret != 0) test_error(j);
break;
}
case disk_io_job::clear_read_cache:
{
#ifdef TORRENT_DISK_STATS
m_log << log_time() << " clear-cache" << std::endl;
#endif
TORRENT_ASSERT(j.buffer == 0);
mutex_t::scoped_lock l(m_piece_mutex);
INVARIANT_CHECK;
for (cache_t::iterator i = m_read_pieces.begin();
i != m_read_pieces.end();)
{
if (i->storage == j.storage)
{
free_piece(*i, l);
i = m_read_pieces.erase(i);
}
else
{
++i;
}
}
l.unlock();
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
{
mutex_t::scoped_lock l(m_pool_mutex);
m_pool.release_memory();
}
#endif
ret = 0;
break;
}
case disk_io_job::delete_files:
{
#ifdef TORRENT_DISK_STATS
m_log << log_time() << " delete" << std::endl;
#endif
TORRENT_ASSERT(j.buffer == 0);
mutex_t::scoped_lock l(m_piece_mutex);
INVARIANT_CHECK;
cache_t::iterator i = std::remove_if(
m_pieces.begin(), m_pieces.end(), bind(&cached_piece_entry::storage, _1) == j.storage);
for (cache_t::iterator k = i; k != m_pieces.end(); ++k)
{
torrent_info const& ti = *k->storage->info();
int blocks_in_piece = (ti.piece_size(k->piece) + m_block_size - 1) / m_block_size;
for (int j = 0; j < blocks_in_piece; ++j)
{
if (k->blocks[j] == 0) continue;
free_buffer(k->blocks[j]);
k->blocks[j] = 0;
--m_cache_stats.cache_size;
}
}
m_pieces.erase(i, m_pieces.end());
l.unlock();
#ifndef TORRENT_DISABLE_POOL_ALLOCATOR
{
mutex_t::scoped_lock l(m_pool_mutex);
m_pool.release_memory();
}
#endif
ret = j.storage->delete_files_impl();
if (ret != 0) test_error(j);
break;
}
case disk_io_job::check_fastresume:
{
#ifdef TORRENT_DISK_STATS
m_log << log_time() << " check fastresume" << std::endl;
#endif
lazy_entry const* rd = (lazy_entry const*)j.buffer;
TORRENT_ASSERT(rd != 0);
ret = j.storage->check_fastresume(*rd, j.str);
break;
}
case disk_io_job::check_files:
{
#ifdef TORRENT_DISK_STATS
m_log << log_time() << " check files" << std::endl;
#endif
int piece_size = j.storage->info()->piece_length();
for (int processed = 0; processed < 4 * 1024 * 1024; processed += piece_size)
{
ret = j.storage->check_files(j.piece, j.offset, j.str);
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
TORRENT_ASSERT(handler);
if (handler && ret == piece_manager::need_full_check)
m_ios.post(bind(handler, ret, j));
#ifndef BOOST_NO_EXCEPTIONS
} catch (std::exception&) {}
#endif
if (ret != piece_manager::need_full_check) break;
}
if (test_error(j))
{
ret = piece_manager::fatal_disk_error;
break;
}
TORRENT_ASSERT(ret != -2 || !j.str.empty());
// if the check is not done, add it at the end of the job queue
if (ret == piece_manager::need_full_check)
{
add_job(j, handler);
continue;
}
break;
}
case disk_io_job::save_resume_data:
{
#ifdef TORRENT_DISK_STATS
m_log << log_time() << " save resume data" << std::endl;
#endif
j.resume_data.reset(new entry(entry::dictionary_t));
j.storage->write_resume_data(*j.resume_data);
ret = 0;
break;
}
case disk_io_job::rename_file:
{
#ifdef TORRENT_DISK_STATS
m_log << log_time() << " rename file" << std::endl;
#endif
ret = j.storage->rename_file_impl(j.piece, j.str);
if (ret != 0)
{
test_error(j);
break;
}
}
}
#ifndef BOOST_NO_EXCEPTIONS
} catch (std::exception& e)
{
ret = -1;
try
{
j.str = e.what();
}
catch (std::exception&) {}
}
#endif
// if (!handler) std::cerr << "DISK THREAD: no callback specified" << std::endl;
// else std::cerr << "DISK THREAD: invoking callback" << std::endl;
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
TORRENT_ASSERT(ret != -2 || !j.str.empty()
|| j.action == disk_io_job::hash);
if (handler) m_ios.post(boost::bind(handler, ret, j));
#ifndef BOOST_NO_EXCEPTIONS
} catch (std::exception&)
{
TORRENT_ASSERT(false);
}
#endif
}
TORRENT_ASSERT(false);
}
}
| [
"arvidn@f43f7eb3-cfe1-5f9d-1b5f-e45aa6702bda"
] | arvidn@f43f7eb3-cfe1-5f9d-1b5f-e45aa6702bda |
8eb0b729c2e7b20eb0cb501b3c2e690977fa82cf | 29a4c1e436bc90deaaf7711e468154597fc379b7 | /modules/arithmetic/unit/scalar/adds.cpp | 82c1d00c310b1b969fe531ac4341e3dc8fcfb1d9 | [
"BSL-1.0"
] | permissive | brycelelbach/nt2 | 31bdde2338ebcaa24bb76f542bd0778a620f8e7c | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | refs/heads/master | 2021-01-17T12:41:35.021457 | 2011-04-03T17:37:15 | 2011-04-03T17:37:15 | 1,263,345 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,030 | cpp | //////////////////////////////////////////////////////////////////////////////
/// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
/// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI
///
/// Distributed under the Boost Software License, Version 1.0
/// See accompanying file LICENSE.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
//////////////////////////////////////////////////////////////////////////////
#define NT2_UNIT_MODULE "nt2 arithmetic toolbox - adds/scalar Mode"
//////////////////////////////////////////////////////////////////////////////
// Test behavior of arithmetic components in scalar mode
//////////////////////////////////////////////////////////////////////////////
/// created by jt the 28/11/2010
/// modified by jt the 26/03/2011
#include <boost/type_traits/is_same.hpp>
#include <nt2/sdk/functor/meta/call.hpp>
#include <nt2/sdk/unit/tests.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/memory/buffer.hpp>
#include <nt2/sdk/constant/real.hpp>
#include <nt2/sdk/constant/infinites.hpp>
#include <nt2/include/functions/ulpdist.hpp>
#include <nt2/toolbox/arithmetic/include/adds.hpp>
NT2_TEST_CASE_TPL ( adds_signed_int__2_0, NT2_INTEGRAL_SIGNED_TYPES)
{
using nt2::adds;
using nt2::tag::adds_;
typedef typename nt2::meta::as_integer<T>::type iT;
typedef typename nt2::meta::call<adds_(T,T)>::type r_t;
typedef typename nt2::meta::upgrade<T>::type u_t;
typedef T wished_r_t;
// return type conformity test
NT2_TEST( (boost::is_same < r_t, wished_r_t >::value) );
std::cout << std::endl;
double ulpd;
ulpd=0.0;
// specific values tests
NT2_TEST_EQUAL(adds(nt2::Mone<T>(), nt2::Mone<T>()), -nt2::Two<T>());
NT2_TEST_EQUAL(adds(nt2::One<T>(), nt2::One<T>()), nt2::Two<T>());
NT2_TEST_EQUAL(adds(nt2::Valmax<T>(),nt2::One<T>()), nt2::Valmax<T>());
NT2_TEST_EQUAL(adds(nt2::Valmin<T>(),nt2::Mone<T>()), nt2::Valmin<T>());
NT2_TEST_EQUAL(adds(nt2::Zero<T>(), nt2::Zero<T>()), nt2::Zero<T>());
// random verifications
static const uint32_t NR = NT2_NB_RANDOM_TEST;
{
NT2_CREATE_BUF(tab_a0,T, NR, 3*(nt2::Valmin<T>()/4), 3*(nt2::Valmax<T>()/4));
NT2_CREATE_BUF(tab_a1,T, NR, 3*(nt2::Valmin<T>()/4), 3*(nt2::Valmax<T>()/4));
double ulp0, ulpd ; ulpd=ulp0=0.0;
T a0;
T a1;
for (uint32_t j =0; j < NR; ++j )
{
std::cout << "for params "
<< " a0 = "<< u_t(a0 = tab_a0[j])
<< ", a1 = "<< u_t(a1 = tab_a1[j])
<< std::endl;
NT2_TEST_EQUAL( nt2::adds(a0,a1),nt2::adds(a0,a1));
}
}
} // end of test for signed_int_
NT2_TEST_CASE_TPL ( adds_unsigned_int__2_0, NT2_UNSIGNED_TYPES)
{
using nt2::adds;
using nt2::tag::adds_;
typedef typename nt2::meta::as_integer<T>::type iT;
typedef typename nt2::meta::call<adds_(T,T)>::type r_t;
typedef typename nt2::meta::upgrade<T>::type u_t;
typedef T wished_r_t;
// return type conformity test
NT2_TEST( (boost::is_same < r_t, wished_r_t >::value) );
std::cout << std::endl;
double ulpd;
ulpd=0.0;
// specific values tests
NT2_TEST_EQUAL(adds(nt2::One<T>(), nt2::One<T>()), nt2::Two<T>());
NT2_TEST_EQUAL(adds(nt2::Valmax<T>(),nt2::One<T>()), nt2::Valmax<T>());
NT2_TEST_EQUAL(adds(nt2::Zero<T>(), nt2::Zero<T>()), nt2::Zero<T>());
// random verifications
static const uint32_t NR = NT2_NB_RANDOM_TEST;
{
NT2_CREATE_BUF(tab_a0,T, NR, 3*(nt2::Valmin<T>()/4), 3*(nt2::Valmax<T>()/4));
NT2_CREATE_BUF(tab_a1,T, NR, 3*(nt2::Valmin<T>()/4), 3*(nt2::Valmax<T>()/4));
double ulp0, ulpd ; ulpd=ulp0=0.0;
T a0;
T a1;
for (uint32_t j =0; j < NR; ++j )
{
std::cout << "for params "
<< " a0 = "<< u_t(a0 = tab_a0[j])
<< ", a1 = "<< u_t(a1 = tab_a1[j])
<< std::endl;
NT2_TEST_EQUAL( nt2::adds(a0,a1),nt2::adds(a0,a1));
}
}
} // end of test for unsigned_int_
| [
"[email protected]"
] | |
f33f77779d896162cf68d29e8264c6763f3a3e34 | ef85c7bb57412c86d9ab28a95fd299e8411c316e | /ngraph/core/src/op/util/elementwise_args.cpp | 9a290f7fb8a96faf47439f61992a6b10c676c40f | [
"Apache-2.0"
] | permissive | SDxKeeper/dldt | 63bf19f01d8021c4d9d7b04bec334310b536a06a | a7dff0d0ec930c4c83690d41af6f6302b389f361 | refs/heads/master | 2023-01-08T19:47:29.937614 | 2021-10-22T15:56:53 | 2021-10-22T15:56:53 | 202,734,386 | 0 | 1 | Apache-2.0 | 2022-12-26T13:03:27 | 2019-08-16T13:41:06 | C++ | UTF-8 | C++ | false | false | 1,748 | cpp | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "ngraph/op/util/elementwise_args.hpp"
#include "ngraph/op/util/binary_elementwise_arithmetic.hpp"
std::tuple<ov::element::Type, ov::PartialShape> ov::op::util::validate_and_infer_elementwise_args(
Node* node,
const op::AutoBroadcastSpec& autob) {
NGRAPH_CHECK(node != nullptr, "nGraph node is empty! Cannot validate eltwise arguments.");
element::Type element_type = node->get_input_element_type(0);
PartialShape pshape = node->get_input_partial_shape(0);
if (node->get_input_size() > 1) {
for (size_t i = 1; i < node->get_input_size(); ++i) {
NODE_VALIDATION_CHECK(node,
element::Type::merge(element_type, element_type, node->get_input_element_type(i)),
"Argument element types are inconsistent.");
if (autob.m_type == op::AutoBroadcastType::NONE) {
NODE_VALIDATION_CHECK(node,
PartialShape::merge_into(pshape, node->get_input_partial_shape(i)),
"Argument shapes are inconsistent.");
} else if (autob.m_type == op::AutoBroadcastType::NUMPY || autob.m_type == op::AutoBroadcastType::PDPD) {
NODE_VALIDATION_CHECK(
node,
PartialShape::broadcast_merge_into(pshape, node->get_input_partial_shape(i), autob),
"Argument shapes are inconsistent.");
} else {
NODE_VALIDATION_CHECK(node, false, "Unsupported auto broadcast specification");
}
}
}
return std::make_tuple(element_type, pshape);
}
| [
"[email protected]"
] | |
74f8d57122bbdcf45cb13684ee72bc7326433c17 | ea5320f7d33ed3e0d50617ef4143c35d5da64152 | /C3.cpp | 07634b6d74f087a460a5d3c3476da400aba4e69d | [] | no_license | ptd910/baitapltnctuan2 | 831ae19927dc9d07f65e6494fbcb157c7ec7f40d | 9d06a939796b7e58637445663eda5bcbd0b63f63 | refs/heads/main | 2023-03-17T04:27:46.330684 | 2021-03-12T02:37:08 | 2021-03-12T02:37:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 247 | cpp | #include<iostream>
using namespace std;
int main()
{
int n;
cout << "nhap n:";cin >> n;
for(int i=1;i<=n;i++)
{
for(int j=1;j<n+i;j++)
{
if(j<n-i+1) cout << " ";
else cout << "*";
}
cout << "\n";
}
return 0;
}
| [
"[email protected]"
] | |
e854a19d24f2859ce8dfea607641664ce7418073 | 183b96661938399377e1a78d1134ec1e9370e316 | /3rdparty/lexy/include/lexy/visualize.hpp | d198a62206a79a113ab05c1adb2eaa8bc21c558f | [
"MIT",
"BSL-1.0"
] | permissive | hiter-fzq/BehaviorTree.CPP | 3b6c3804cdda71b019c05127e45f630dd0f90eaf | 5f961942d74e2f441a51a126cb6b8eb9298ff445 | refs/heads/master | 2022-11-12T11:54:30.322222 | 2022-11-03T11:28:29 | 2022-11-03T11:28:29 | 252,464,467 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,353 | hpp | // Copyright (C) 2020-2022 Jonathan Müller and lexy contributors
// SPDX-License-Identifier: BSL-1.0
#ifndef LEXY_VISUALIZE_HPP_INCLUDED
#define LEXY_VISUALIZE_HPP_INCLUDED
#include <cstdio>
#include <lexy/_detail/config.hpp>
#include <lexy/dsl/code_point.hpp>
#include <lexy/input/range_input.hpp>
#include <lexy/lexeme.hpp>
//=== visualization_options ===//
namespace lexy
{
enum visualization_flags
{
visualize_default = 0,
/// Visualization can use unicode characters.
visualize_use_unicode = 1 << 0,
/// Visualization can use ANSI color escape sequences.
visualize_use_color = 1 << 1,
/// Visualization can use Unicode symbols e.g. for newline/space instead of the code point.
visualize_use_symbols = 1 << 2,
/// Visualization can use unicode, color and symbols.
visualize_fancy = visualize_use_unicode | visualize_use_color | visualize_use_symbols,
/// Visualize space ' ' as visible character/symbol.
visualize_space = 1 << 3,
};
constexpr visualization_flags operator|(visualization_flags lhs, visualization_flags rhs) noexcept
{
return visualization_flags(int(lhs) | int(rhs));
}
/// Options that control visualization.
struct visualization_options
{
static constexpr unsigned char max_tree_depth_limit = 32;
/// Boolean flags.
visualization_flags flags = visualize_default;
/// The maximal depth when visualizing a tree.
/// Must be <= max_tree_depth_limit.
unsigned char max_tree_depth = max_tree_depth_limit;
/// The maximal width when visualizing a lexeme.
/// 0 means unlimited.
unsigned char max_lexeme_width = 0;
/// How many spaces are printed for a tab character.
/// 0 means it is printed as escaped control character.
unsigned char tab_width = 0;
constexpr bool is_set(visualization_flags f) const noexcept
{
return (flags & f) != 0;
}
constexpr visualization_options reset(visualization_flags f) const noexcept
{
auto copy = *this;
copy.flags = visualization_flags(copy.flags & ~f);
return copy;
}
friend constexpr visualization_options operator|(visualization_options lhs,
visualization_flags rhs) noexcept
{
lhs.flags = lhs.flags | rhs;
return lhs;
}
};
} // namespace lexy
//=== visualize_to ===//
namespace lexy::_detail
{
template <typename Encoding>
constexpr auto make_literal_lexeme(const typename Encoding::char_type* str, std::size_t length)
{
struct reader
{
using encoding = Encoding;
using iterator = const typename Encoding::char_type*;
};
return lexy::lexeme<reader>(str, str + length);
}
template <typename OutIt>
constexpr OutIt write_str(OutIt out, const char* str)
{
while (*str)
*out++ = *str++;
return out;
}
template <typename OutIt>
constexpr OutIt write_str(OutIt out, const LEXY_CHAR8_T* str)
{
while (*str)
*out++ = static_cast<char>(*str++);
return out;
}
template <int N = 16, typename OutIt, typename... Args>
constexpr OutIt write_format(OutIt out, const char* fmt, const Args&... args)
{
char buffer[std::size_t(N + 1)];
auto count = std::snprintf(buffer, N, fmt, args...);
LEXY_ASSERT(count <= N, "buffer not big enough");
for (auto i = 0; i != count; ++i)
*out++ = buffer[i];
return out;
}
enum class color
{
reset = 0,
bold = 1,
faint = 2,
italic = 3,
black = 30,
red = 31,
green = 32,
yellow = 33,
blue = 34,
magenta = 35,
cyan = 36,
white = 37,
};
template <color CodeHead, color... CodeTail, typename OutIt>
constexpr OutIt write_color(OutIt out, visualization_options opts)
{
if (!opts.is_set(visualize_use_color))
return out;
out = write_str(out, "\033[");
auto write_code = [](OutIt out, int code) {
if (code > 10)
{
*out++ = static_cast<char>((code / 10) + '0');
*out++ = static_cast<char>((code % 10) + '0');
}
else
{
*out++ = static_cast<char>(code + '0');
}
return out;
};
out = write_code(out, int(CodeHead));
((*out++ = ';', write_code(out, int(CodeTail))), ...);
*out++ = 'm';
return out;
}
template <typename OutIt>
constexpr OutIt write_ellipsis(OutIt out, visualization_options opts)
{
if (opts.is_set(visualize_use_unicode))
return _detail::write_str(out, u8"…");
else
return _detail::write_str(out, "...");
}
template <typename OutIt, typename Fn>
constexpr OutIt write_special_char(OutIt out, visualization_options opts, Fn inner)
{
out = _detail::write_color<_detail::color::cyan, _detail::color::faint>(out, opts);
if (opts.is_set(visualize_use_unicode))
out = _detail::write_str(out, u8"⟨");
else
out = _detail::write_str(out, "\\");
out = inner(out);
if (opts.is_set(visualize_use_unicode))
out = _detail::write_str(out, u8"⟩");
out = _detail::write_color<_detail::color::reset>(out, opts);
return out;
}
} // namespace lexy::_detail
namespace lexy
{
template <typename OutputIt>
OutputIt visualize_to(OutputIt out, lexy::code_point cp, visualization_options opts = {})
{
if (!cp.is_valid())
{
out = _detail::write_special_char(out, opts, [opts](OutputIt out) {
if (opts.is_set(visualize_use_unicode))
return _detail::write_str(out, "U+????");
else
return _detail::write_str(out, "u????");
});
return out;
}
else if (cp.is_control())
{
auto c = static_cast<int>(cp.value());
switch (c)
{
case '\0':
out = _detail::write_special_char(out, opts, [opts](OutputIt out) {
if (opts.is_set(visualize_use_unicode))
return _detail::write_str(out, "NUL");
else
return _detail::write_str(out, "0");
});
break;
case '\r':
out = _detail::write_special_char(out, opts, [opts](OutputIt out) {
if (opts.is_set(visualize_use_unicode))
return _detail::write_str(out, "CR");
else
return _detail::write_str(out, "r");
});
break;
case '\n':
if (opts.is_set(visualize_use_symbols))
{
out = _detail::write_color<_detail::color::faint>(out, opts);
out = _detail::write_str(out, u8"⏎");
out = _detail::write_color<_detail::color::reset>(out, opts);
}
else if (opts.is_set(visualize_use_unicode))
{
out = _detail::write_special_char(out, opts, [](OutputIt out) {
return _detail::write_str(out, "LF");
});
}
else
{
out = _detail::write_special_char(out, opts, [](OutputIt out) {
return _detail::write_str(out, "n");
});
}
break;
case '\t':
if (opts.tab_width > 0)
{
// We print that many space characters.
// This is recursion, but the recursive call does not recurse further.
for (auto i = 0u; i < opts.tab_width; ++i)
out = visualize_to(out, lexy::code_point(' '), opts);
}
else if (opts.is_set(visualize_use_symbols))
{
out = _detail::write_color<_detail::color::faint>(out, opts);
out = _detail::write_str(out, u8"⇨");
out = _detail::write_color<_detail::color::reset>(out, opts);
}
else if (opts.is_set(visualize_use_unicode))
{
out = _detail::write_special_char(out, opts, [](OutputIt out) {
return _detail::write_str(out, "HT");
});
}
else
{
out = _detail::write_special_char(out, opts, [](OutputIt out) {
return _detail::write_str(out, "t");
});
}
break;
default:
out = _detail::write_special_char(out, opts, [opts, c](OutputIt out) {
if (opts.is_set(visualize_use_unicode))
return _detail::write_format(out, "U+%04X", c);
else
return _detail::write_format(out, "u%04X", c);
});
break;
}
return out;
}
else if (cp.value() == ' ')
{
if (opts.is_set(visualize_space))
{
if (opts.is_set(visualize_use_symbols))
{
out = _detail::write_color<_detail::color::faint>(out, opts);
out = _detail::write_str(out, u8"␣");
out = _detail::write_color<_detail::color::reset>(out, opts);
}
else if (opts.is_set(visualize_use_unicode))
{
out = _detail::write_special_char(out, opts, [](OutputIt out) {
return _detail::write_str(out, "SP");
});
}
else
{
out = _detail::write_special_char(out, opts, [](OutputIt out) {
return _detail::write_str(out, "u0020");
});
}
}
else
{
*out++ = ' ';
}
return out;
}
else if (cp.value() == '\\')
{
if (!opts.is_set(visualize_use_unicode))
out = _detail::write_special_char(out, opts, [](OutputIt out) {
return _detail::write_str(out, "\\");
});
else
*out++ = '\\'; // Doesn't need escaping if we can use unicode.
return out;
}
else if (cp.is_ascii())
{
// ASCII, non-control character, print as-is.
*out++ = static_cast<char>(cp.value());
return out;
}
else
{
out = _detail::write_special_char(out, opts, [opts, cp](OutputIt out) {
auto c = static_cast<int>(cp.value());
if (opts.is_set(visualize_use_unicode))
return _detail::write_format(out, "U+%04X", c);
else if (cp.is_bmp())
return _detail::write_format(out, "u%04X", c);
else
return _detail::write_format(out, "U%08X", c);
});
return out;
}
}
template <typename OutputIt, typename Reader>
OutputIt visualize_to(OutputIt out, lexy::lexeme<Reader> lexeme,
[[maybe_unused]] visualization_options opts = {})
{
// We need to ensure that we're not printing more "code points" than `opts.max_lexeme_width`,
// or unlimited if `opts.max_lexeme_width == 0`.
// The trick is to count and check for `count == opts.max_lexeme_width` after increment.
[[maybe_unused]] auto write_escaped_byte = [opts](OutputIt out, unsigned char byte) {
return _detail::write_special_char(out, opts, [opts, byte](OutputIt out) {
if (opts.is_set(visualize_use_unicode))
return _detail::write_format(out, "0x%02X", byte);
else
return _detail::write_format(out, "x%02X", byte);
});
};
using encoding = typename Reader::encoding;
if constexpr (std::is_same_v<encoding, lexy::ascii_encoding> //
|| std::is_same_v<encoding, lexy::default_encoding>)
{
auto count = 0u;
for (char c : lexeme)
{
// If the character is in fact ASCII, visualize the code point.
// Otherwise, visualize as byte.
if (lexy::_detail::is_ascii(c))
out = visualize_to(out, lexy::code_point(static_cast<char32_t>(c)), opts);
else
out = write_escaped_byte(out, static_cast<unsigned char>(c));
++count;
if (count == opts.max_lexeme_width)
{
out = _detail::write_ellipsis(out, opts);
break;
}
}
return out;
}
else if constexpr (std::is_same_v<encoding, lexy::utf8_encoding> //
|| std::is_same_v<encoding, lexy::utf8_char_encoding> //
|| std::is_same_v<encoding, lexy::utf16_encoding> //
|| std::is_same_v<encoding, lexy::utf32_encoding>)
{
// Parse the individual code points, and write them out.
lexy::range_input<encoding, typename Reader::iterator> input(lexeme.begin(), lexeme.end());
auto reader = input.reader();
auto count = 0u;
while (true)
{
if (auto result = lexy::_detail::parse_code_point(reader);
result.error == lexy::_detail::cp_error::eof)
{
// No more code points in the lexeme, finish.
break;
}
else if (result.error == lexy::_detail::cp_error::success)
{
// Consume and visualize.
reader.set_position(result.end);
out = visualize_to(out, lexy::code_point(result.cp), opts);
}
else
{
// Recover from the failed code point.
auto begin = reader.position();
lexy::_detail::recover_code_point(reader, result);
auto end = reader.position();
// Visualize each skipped code unit as byte.
for (auto cur = begin; cur != end; ++cur)
{
if constexpr (std::is_same_v<encoding,
lexy::utf8_encoding> //
|| std::is_same_v<encoding, lexy::utf8_char_encoding>)
{
out = write_escaped_byte(out, static_cast<unsigned char>(*cur & 0xFF));
}
else if constexpr (std::is_same_v<encoding, lexy::utf16_encoding>)
{
auto first = static_cast<unsigned char>((*cur >> 8) & 0xFF);
auto second = static_cast<unsigned char>(*cur & 0xFF);
if (first != 0)
out = write_escaped_byte(out, first);
out = write_escaped_byte(out, second);
}
else if constexpr (std::is_same_v<encoding, lexy::utf32_encoding>)
{
auto first = static_cast<unsigned char>((*cur >> 24) & 0xFF);
auto second = static_cast<unsigned char>((*cur >> 16) & 0xFF);
auto third = static_cast<unsigned char>((*cur >> 8) & 0xFF);
auto fourth = static_cast<unsigned char>(*cur & 0xFF);
if (first != 0)
out = write_escaped_byte(out, first);
if (first != 0 || second != 0)
out = write_escaped_byte(out, second);
if (first != 0 || second != 0 || third != 0)
out = write_escaped_byte(out, third);
out = write_escaped_byte(out, fourth);
}
}
}
++count;
if (count == opts.max_lexeme_width)
{
out = _detail::write_ellipsis(out, opts);
break;
}
}
return out;
}
else if constexpr (std::is_same_v<encoding, lexy::byte_encoding>)
{
auto count = 0u;
for (auto iter = lexeme.begin(); iter != lexeme.end(); ++iter)
{
// Write each byte.
out = _detail::write_special_char(out, opts, [c = *iter](OutputIt out) {
return _detail::write_format(out, "%02X", c);
});
++count;
if (count == opts.max_lexeme_width)
{
out = _detail::write_ellipsis(out, opts);
break;
}
}
return out;
}
else
{
static_assert(lexy::_detail::error<encoding>, "unknown encoding");
return out;
}
}
template <typename OutputIt, typename Tree, typename = decltype(LEXY_DECLVAL(Tree&).traverse())>
OutputIt visualize_to(OutputIt out, const Tree& tree, visualization_options opts = {})
{
struct label_t
{
const LEXY_CHAR_OF_u8* space;
const LEXY_CHAR_OF_u8* line;
const LEXY_CHAR_OF_u8* end;
const LEXY_CHAR_OF_u8* branch;
};
auto label = opts.is_set(visualize_use_unicode) ? label_t{u8" ", u8"│ ", u8"└──", u8"├──"}
: label_t{u8" ", u8" ", u8"- ", u8"- "};
// True if the node currently opened at the depth is the last child of its parent,
// false otherwise.
bool is_last_child[visualization_options::max_tree_depth_limit] = {};
LEXY_PRECONDITION(opts.max_tree_depth <= visualization_options::max_tree_depth_limit);
// Writes the prefix using the last child information.
auto write_prefix
= [opts, label, &is_last_child](OutputIt out, std::size_t cur_depth, bool cur_is_last) {
if (cur_depth == 0)
// Root node doesn't have a prefix.
return out;
out = _detail::write_color<_detail::color::faint>(out, opts);
// We begin at depth 1, as depth 0 doesn't require a prefix.
for (auto i = 1u; i < cur_depth; ++i)
if (is_last_child[i])
// If the current node at that depth is the last child, we just indent.
out = _detail::write_str(out, label.space);
else
// Otherwise, we need to carry the line.
out = _detail::write_str(out, label.line);
// Print the final branching symbol for the current node.
if (cur_is_last)
out = _detail::write_str(out, label.end);
else
out = _detail::write_str(out, label.branch);
out = _detail::write_color<_detail::color::reset>(out, opts);
return out;
};
// Traverse and print the tree.
std::size_t cur_depth = 0;
for (auto [event, node] : tree.traverse())
{
auto last_child = node.is_last_child();
using event_t = typename decltype(tree.traverse())::event;
switch (event)
{
case event_t::enter:
if (cur_depth <= opts.max_tree_depth)
{
out = write_prefix(out, cur_depth, last_child);
out = _detail::write_color<_detail::color::bold>(out, opts);
out = _detail::write_str(out, node.kind().name());
out = _detail::write_color<_detail::color::reset>(out, opts);
if (cur_depth == opts.max_tree_depth)
{
// Print an ellipsis instead of children.
out = _detail::write_str(out, ": ");
out = _detail::write_ellipsis(out, opts);
out = _detail::write_str(out, "\n");
}
else
{
// Print a newline and prepare for children.
out = _detail::write_str(out, ":\n");
is_last_child[cur_depth] = last_child;
}
}
++cur_depth;
break;
case event_t::exit:
--cur_depth;
break;
case event_t::leaf:
if (cur_depth <= opts.max_tree_depth)
{
out = write_prefix(out, cur_depth, last_child);
out = _detail::write_color<_detail::color::bold>(out, opts);
out = _detail::write_str(out, node.kind().name());
out = _detail::write_color<_detail::color::reset>(out, opts);
if (!node.lexeme().empty())
{
out = _detail::write_str(out, ": ");
out = visualize_to(out, node.lexeme(), opts | lexy::visualize_space);
}
out = _detail::write_str(out, "\n");
}
break;
}
}
return out;
}
} // namespace lexy
//=== visualize ===//
namespace lexy
{
struct cfile_output_iterator
{
std::FILE* _file;
explicit constexpr cfile_output_iterator(std::FILE* file) : _file(file) {}
auto operator*() const noexcept
{
return *this;
}
auto operator++(int) const noexcept
{
return *this;
}
cfile_output_iterator& operator=(char c)
{
std::fputc(c, _file);
return *this;
}
};
/// Writes the visualization to the FILE.
template <typename T>
void visualize(std::FILE* file, const T& obj, visualization_options opts = {})
{
visualize_to(cfile_output_iterator{file}, obj, opts);
}
} // namespace lexy
//=== visualization_display_width ===//
namespace lexy
{
template <typename T>
std::size_t visualization_display_width(const T& obj, visualization_options opts = {})
{
struct iterator
{
std::size_t width;
iterator& operator*() noexcept
{
return *this;
}
iterator& operator++(int) noexcept
{
return *this;
}
iterator& operator=(char c)
{
// We're having ASCII or UTF-8 characters.
// All unicode characters used occupy a single cell,
// so we just need to count all code units that are not continuation bytes.
auto value = static_cast<unsigned char>(c);
if ((value & 0b1100'0000) != 0b1000'0000)
++width;
return *this;
}
};
// Disable usage of color, as they introduce additional characters that must nobe counted.
return visualize_to(iterator{0}, obj, opts.reset(visualize_use_color)).width;
}
} // namespace lexy
#endif // LEXY_VISUALIZE_HPP_INCLUDED
| [
"[email protected]"
] | |
19a5d7ae53394fb30ac98a0e7fcfc99f785c9805 | 5610d502f019f23c7c12acac44b36a1ab068c054 | /kfkfeoewqpweoqwfekqo.cpp | edd3bf8fed943f698e1d2279932c4b402810da33 | [] | no_license | elvircrn/ccppcodes | 7f301760a1cbe486f3991d394d5355483fbf27dd | b5d72b875b5082042826c86643d6f5e47ab2d768 | refs/heads/master | 2021-01-01T05:46:37.476763 | 2015-10-14T17:47:57 | 2015-10-14T17:47:57 | 44,265,359 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,393 | cpp | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <string>
#include <ctime>
#include <cstring>
#include <queue>
using namespace std;
class room
{
public:
int x, y;
int width, height;
room() { }
room(int _x, int _y, int _height, int _width) { x = _x; y = _y; height = _height; width = _width;}
};
class level
{
private:
enum block_type { NONE, ROOM, FLOOR, WALL, DOOR };
vector <vector <block_type> > matrix;
vector <vector <int> > room_index;
vector <vector <int> > priority;
vector <int> dirX = { 2, 0, -2, 0 };
vector <int> dirY = { 0, -2, 0, 2 };
vector <room> rooms;
struct edge
{
int x, y, px, py, w;
edge() { }
edge(int _x, int _y, int _w) { x = _x; y = _y; w = _w; }
edge(int _px, int _py, int _x, int _y, int _w) { px = _px; py = _py; x = _x; y = _y; w = _w; }
bool operator< (const edge &B) const
{
return w > B.w;
}
};
bool clean(int px, int py, int x, int y)
{
bool state = false;
for (int i = 0; i < 4; i++)
{
int X = x + dirX [i] / 2;
int Y = y + dirY [i] / 2;
if (X < 0 || Y < 0 || X >= height || Y >= width || (X == px && Y == py) || matrix [X] [Y] == block_type::WALL || matrix [X] [Y] == block_type::ROOM)
continue;
state |= clean(x, y, X, Y);
}
if (matrix [x] [y] == block_type::DOOR)
state = true;
else if (state == false)
matrix[x] [y] = block_type::WALL;
return state;
}
void run_prim(int x, int y)
{
vector <bool> room_set;
room_set.resize((int)rooms.size());
priority_queue<edge> Q;
generate_priority();
Q.push(edge(x, y, x, y, priority[x] [y]));
while (!Q.empty())
{
edge help = Q.top();
Q.pop();
if (matrix[help.x] [help.y] == block_type::WALL)
{
matrix[help.px] [help.py] = block_type::FLOOR;
matrix[help.x] [help.y] = block_type::FLOOR;
for (int i = 0; i < 4; i++)
{
int X = help.x + dirX[i];
int Y = help.y + dirY[i];
if (X < 0 || Y < 0 || X >= height || Y >= width)
continue;
if (matrix [X] [Y] == block_type::WALL)
Q.push(edge(help.x + dirX[i] / 2, help.y + dirY[i] / 2, X, Y, priority[X] [Y]));
else if (matrix [X] [Y] == block_type::ROOM && !room_set[room_index[X] [Y]])
{
room_set[room_index[X] [Y]] = true;
matrix[help.x + dirX[i] / 2] [help.y + dirY[i] / 2] = block_type::DOOR;
}
}
}
}
}
void generate_priority()
{
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++)
priority[i] [j] = rand();
}
void generate_halls()
{
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++)
if (i % 2 == 0 && j % 2 == 0 && matrix[i] [j] == block_type::WALL)
run_prim(i, j);
}
void set_rooms(int room_count)
{
for (int current_room = 1; current_room <= room_count; current_room++)
{
bool found(false);
int ran_height, ran_width, ran_x, ran_y, tries = 0;
while (!found)
{
while ((ran_x = (rand() % height)) % 2 != 0 || ((ran_y = (rand() % width))) % 2 != 0);
int counter = 0;
bool can(false);
while (!can)
{
if (counter++ > 1000)
break;
can = true;
ran_height = rand() % 5 + 2;
ran_width = rand() % 5 + 2;
ran_width += !(ran_width % 2);
ran_height += !(ran_height % 2);
if (ran_x + ran_height >= height - 1 || ran_y + ran_width >= width - 1)
continue;
for (int i = 0; i < ran_height; i++)
{
for (int j = 0; j < ran_width; j++)
if (matrix [ran_x + i] [ran_y + j] != block_type::WALL)
can = false;
if (!can)
break;
}
}
if (!can)
continue;
if (ran_x + ran_height >= height - 1 || ran_y + ran_width >= width - 1)
{
can = false;
continue;
}
for (int i = 0; i < ran_height; i++)
{
for (int j = 0; j < ran_width; j++)
{
matrix[ran_x + i] [ran_y + j] = block_type::ROOM;
room_index [ran_x + i] [ran_y + j] = current_room;
}
}
found = true;
break;
}
if (found)
rooms.push_back(room(ran_x, ran_y, ran_height, ran_width));
}
}
public:
int width, height;
level() { }
level(int _height, int _width)
{
init(_height, _width);
}
void init(int _height, int _width)
{
width = _width;
height = _height;
rooms.erase(rooms.begin(), rooms.end());
matrix.resize(height);
priority.resize(height);
room_index.resize(height);
for (int i = 0; i < height; i++)
{
room_index[i].resize(width);
priority[i].resize(width);
matrix[i].resize(width);
}
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++)
matrix[i] [j] = block_type::WALL;
}
void generate_dungeon(int room_count)
{
init(height, width);
set_rooms(room_count);
generate_halls();
clean(0, 0, 0, 0);
}
void print()
{
for (int i = 0; i < height; i++, printf("\n"))
for (int j = 0; j < width; j++)
if (matrix[i] [j] == block_type::ROOM)
putchar('R');
else if (matrix [i] [j] == block_type::DOOR)
putchar('D');
else if (matrix[i] [j] == block_type::FLOOR)
putchar(' ');
else
putchar(219);
}
~level()
{
for (int i = 0; i < height; i++)
{
matrix[i].erase(matrix[i].begin(), matrix[i].end());
priority[i].erase(priority[i].begin(), priority[i].end());
}
matrix.erase(matrix.begin(), matrix.end());
priority.erase(priority.begin(), priority.end());
rooms.erase(rooms.begin(), rooms.end());
room_index.erase(room_index.begin(), room_index.end());
}
};
int main()
{
srand(time(0));
level l(60, 70);
while (true)
{
l.generate_dungeon(20);
l.print();
system ("pause");
system("cls");
}
return 0;
}
| [
"[email protected]"
] | |
eb18ee9417e90c2d59dacc8074848e29fe698faa | a8c588bae9db3b73c8b6aac4deb6a914cf718a65 | /PAT-A/1050.cpp | 84fcf14462177be70eb59bd745ba88654ce83ac9 | [] | no_license | zzhhch/pat | 688f9227fe161135074c7b31e85c5a6b8ff51e1d | fd7592869be5218bb73fa572dc75d474418828c3 | refs/heads/master | 2020-03-24T11:09:31.025066 | 2019-06-03T06:29:14 | 2019-06-03T06:29:14 | 142,677,123 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 313 | cpp | #include<cstdio>
#include<cstring>
using namespace std;
int mp[130]={0};
int main()
{
char temp,a[10010];
int k=0;
while((temp=getchar())!='\n')
{
a[k++]=temp;
}
while((temp=getchar())!='\n')
{
mp[int(temp)]=1;
}
for(int i=0;i<k;i++)
{
if(mp[int(a[i])]==0)
printf("%c",a[i]);
}
return 0;
} | [
"[email protected]"
] | |
290d4e0542fc8b4683b964fe3ee214a0f1bce4b6 | 9e86daf365dd40d72db77e2751c4b45e52922d17 | /Mapping.h | 8a392f98a3e1846c4f55531331b90c4b6fa5c47b | [] | no_license | rwth-afu/HamnetPropagation | 08b586d72b9dad8b54ab01012d58ef0034a87c29 | 956a7856b09c5899c86458618e4f8037a6c32a74 | refs/heads/master | 2021-05-05T10:08:56.076948 | 2018-01-18T09:24:52 | 2018-01-18T09:24:52 | 117,960,379 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,883 | h |
#ifndef MAPPING_H_INCLUDED
#define MAPPING_H_INCLUDED
#include <iostream>
#include <math.h>
#include <fstream>
#include <vector>
#include <string.h>
#include <cstdlib>
#include <cmath>
#include <QDate>
#include <QTime>
using namespace std;
struct coord
{
double lat;
double lon;
};
struct map_index
{
int lon;
int lat;
};
struct Height_Map
{
float Range_m;
float Range_grad_N;
float Range_grad_E;
coord station_coord;
map_index station_index;
char path_to_dem[100];
char path_to_hgt[100];
char path_to_tif[100];
vector< vector<short> > map_data;
coord down_right_arcsec; //fixed
coord down_left_arcsec; //variable
coord up_right_arcsec; //variable
//ASTER (1) or SRTM (3) elevation model?
int step;
};
double great_circle_distance(coord start, coord target);
long double meter2arcsec_lon( coord start, double dist_km);
double meter2arcsec_lat(coord start, double dist_km);
//Calculate down right corner as 3-arcsec/1-arcsec steps from mid
void down_right_corner(Height_Map &map1, coord station_coord);
//Calculate down left corner as 3-arcsec/1-arcsec steps from mid
void down_left_corner(Height_Map &map1, coord station_coord);
//Calculate up right corner as 3-arcsec/1-arcsec steps from mid
void up_right_corner(Height_Map &map1, coord station_coord);
map_index arcsec2index(Height_Map &map1, coord &arcsec);
void initialize_Map (Height_Map &map1, coord station_coord);
fstream* FindDEM(Height_Map& map1, coord& down_right_arcsec);
int ReadDEM(Height_Map &map, coord& down_right_arcsec, double Resolution);
double* Path (Height_Map &map, coord pixel_arcsec, double &alpha, double &receiver_height);
int mapping(Height_Map & map1, coord & station_coord_grad, double Resolution);
#endif // MAPPING_H_INCLUDED
| [
"[email protected]"
] | |
bd4a13cb98619c9938a94971e575d29273777e91 | c76a75c5dd7484983d912fa44ab81fecedd43fcd | /cugl/include/cugl/renderer/CUSpriteShader.h | 6a51b405ae2f16310ec767c319339c46d6c129d1 | [] | no_license | apurvsethi/CUGL_AI | 224e69f394d52332e6b049b1710f47f08519d894 | 4e10e77ad7b439813c2ba564eebb4e3aa6867318 | refs/heads/master | 2021-09-22T14:19:33.472215 | 2018-09-11T02:03:14 | 2018-09-11T02:03:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,286 | h | //
// CUSpriteShader.h
// Cornell University Game Library (CUGL)
//
// This module provides the default shader for a sprite batch. You may replace
// the shader code, but all shaders must support the attributes and uniforms
// listed below.
//
// This class uses our standard shared-pointer architecture.
//
// 1. The constructor does not perform any initialization; it just sets all
// attributes to their defaults.
//
// 2. All initialization takes place via init methods, which can fail if an
// object is initialized more than once.
//
// 3. All allocation takes place via static constructors which return a shared
// pointer.
//
// CUGL zlib License:
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
// Author: Walker White
// Version: 6/23/16
#ifndef __CU_SPRITE_SHADER_H__
#define __CU_SPRITE_SHADER_H__
#include <cugl/renderer/CUShader.h>
#include <cugl/renderer/CUTexture.h>
#include <cugl/math/CUMat4.h>
namespace cugl {
/**
* This class is a GLSL shader to use with a sprite batch.
*
* This class provides you the option to use your own shader sources. However,
* any shader used with this class must have the following properties.
*
* First, it must provide three attributes corresponding to the Vertex2 class.
* These attributes must be names as follows.
*
* aPosition: The position attribute
*
* aColor: The color attribute
*
* aTexCoord: The texture coordinate attribute
*
* In addition, it must include the following two uniforms.
*
* uPerspective: The perspective matrix (combined modelview projection)
*
* uTexture: The shading texture
*
* Any other attributes or uniforms will be ignored.
*/
class SpriteShader : public Shader {
#pragma mark Values
private:
/** The shader location for the position attribute */
GLint _aPosition;
/** The shader location for the color attribute */
GLint _aColor;
/** The shader location for the texure coordinate attribute */
GLint _aTexCoord;
/** The shader location for the perspective uniform */
GLint _uPerspective;
/** The shader location for the texture uniform */
GLint _uTexture;
/** The current perspective matrix */
Mat4 _mPerspective;
/** The current shader texture */
std::shared_ptr<Texture> _mTexture;
#pragma mark -
#pragma mark Constructors
public:
/**
* Creates an uninitialized shader with no source.
*
* You must initialize the shader to add a source and compiled it.
*/
SpriteShader() : Shader(), _aPosition(-1), _aColor(-1), _aTexCoord(-1),
_uPerspective(-1), _uTexture(-1) { }
/**
* Deletes this shader, disposing all resources.
*/
~SpriteShader() { dispose(); }
/**
* Deletes the OpenGL shader and resets all attributes.
*
* You must reinitialize the shader to use it.
*/
void dispose() override;
/**
* Initializes this shader with the default vertex and fragment source.
*
* The shader will compile the vertex and fragment sources and link
* them together. When compilation is complete, the shader will not be
* bound. However, any shader that was actively bound during compilation
* also be unbound as well.
*
* @return true if initialization was successful.
*/
bool init();
/**
* Initializes this shader with the given vertex and fragment source.
*
* The shader will compile the vertex and fragment sources and link
* them together. When compilation is complete, the shader will not be
* bound. However, any shader that was actively bound during compilation
* also be unbound as well.
*
* @param vsource The source string for the vertex shader.
* @param fsource The source string for the fragment shader.
*
* @return true if initialization was successful.
*/
bool init(std::string vsource, std::string fsource) {
return init(vsource.c_str(),fsource.c_str());
}
/**
* Initializes this shader with the given vertex and fragment source.
*
* The shader will compile the vertex and fragment sources and link
* them together. When compilation is complete, the shader will not be
* bound. However, any shader that was actively bound during compilation
* also be unbound as well.
*
* @param vsource The source string for the vertex shader.
* @param fsource The source string for the fragment shader.
*
* @return true if initialization was successful.
*/
bool init(const char* vsource, const char* fsource);
#pragma mark -
#pragma mark Static Constructors
/**
* Returns a new shader with the default vertex and fragment source.
*
* The shader will compile the vertex and fragment sources and link
* them together. When compilation is complete, the shader will not be
* bound. However, any shader that was actively bound during compilation
* also be unbound as well.
*
* @return a new shader with the default vertex and fragment source.
*/
static std::shared_ptr<SpriteShader> alloc() {
std::shared_ptr<SpriteShader> result = std::make_shared<SpriteShader>();
return (result->init() ? result : nullptr);
}
/**
* Returns a new shader with the given vertex and fragment source.
*
* The shader will compile the vertex and fragment sources and link
* them together. When compilation is complete, the shader will not be
* bound. However, any shader that was actively bound during compilation
* also be unbound as well.
*
* @param vsource The source string for the vertex shader.
* @param fsource The source string for the fragment shader.
*
* @return a new shader with the given vertex and fragment source.
*/
static std::shared_ptr<SpriteShader> alloc(std::string vsource, std::string fsource) {
std::shared_ptr<SpriteShader> result = std::make_shared<SpriteShader>();
return (result->init(vsource, fsource) ? result : nullptr);
}
/**
* Returns a new shader with the given vertex and fragment source.
*
* The shader will compile the vertex and fragment sources and link
* them together. When compilation is complete, the shader will not be
* bound. However, any shader that was actively bound during compilation
* also be unbound as well.
*
* @param vsource The source string for the vertex shader.
* @param fsource The source string for the fragment shader.
*
* @return a new shader with the given vertex and fragment source.
*/
static std::shared_ptr<SpriteShader> alloc(const char* vsource, const char* fsource) {
std::shared_ptr<SpriteShader> result = std::make_shared<SpriteShader>();
return (result->init(vsource, fsource) ? result : nullptr);
}
#pragma mark -
#pragma mark Attributes
/**
* Returns the GLSL location for the position attribute
*
* This method will return -1 if the program is not initialized.
*
* @return the GLSL location for the position attribute
*/
GLint getPositionAttr() const { return _aPosition; }
/**
* Returns the GLSL location for the color attribute
*
* This method will return -1 if the program is not initialized.
*
* @return the GLSL location for the color attribute
*/
GLint getColorAttr() const { return _aColor; }
/**
* Returns the GLSL location for the texture coordinate attribute
*
* This method will return -1 if the program is not initialized.
*
* @return the GLSL location for the texture coordinate attribute
*/
GLint getTexCoodAttr() const { return _aTexCoord; }
/**
* Returns the GLSL location for the perspective matrix uniform
*
* This method will return -1 if the program is not initialized.
*
* @return the GLSL location for the perspective matrix uniform
*/
GLint getPerspectiveUni() const { return _uPerspective; }
/**
* Returns the GLSL location for the texture uniform
*
* This method will return -1 if the program is not initialized.
*
* @return the GLSL location for the testure uniform
*/
GLint getTextureUni() const { return _uTexture; }
/**
* Sets the perspective matrix to use in the shader.
*
* @param matrix The perspective matrix
*/
void setPerspective(const Mat4& matrix);
/**
* Returns the current perspective matrix in use.
*
* @return the current perspective matrix in use.
*/
const Mat4& getPerspective() { return _mPerspective; }
/**
* Sets the texture in use in the shader
*
* @param texture The shader texture
*/
void setTexture(const std::shared_ptr<Texture>& texture);
/**
* Returns the current texture in use.
*
* @return the current texture in use.
*/
std::shared_ptr<Texture> getTexture() { return _mTexture; }
/**
* Returns the current texture in use.
*
* @return the current texture in use.
*/
const std::shared_ptr<Texture>& getTexture() const { return _mTexture; }
#pragma mark -
#pragma mark Rendering
/**
* Attaches the given memory buffer to this shader.
*
* Because of limitations in OpenGL ES, we cannot draw anything without
* both a vertex buffer object and an vertex array object.
*
* @param vArray The vertex array object
* @param vBuffer The vertex buffer object
*/
void attach(GLuint vArray, GLuint vBuffer);
/**
* Binds this shader, making it active.
*
* Once bound, any OpenGL calls will then be sent to this shader.
*/
void bind() override;
/**
* Unbinds this shader, making it no longer active.
*
* Once unbound, OpenGL calls will no longer be sent to this shader.
*/
void unbind() override;
#pragma mark -
#pragma mark Compilation
protected:
/**
* Compiles this shader from the given vertex and fragment shader sources.
*
* When compilation is complete, the shader will not be bound. However,
* any shader that was actively bound during compilation also be unbound
* as well.
*
* If compilation fails, it will display error messages on the log.
*
* @return true if compilation was successful.
*/
bool compile() override;
/**
* Returns true if the GLSL variable was found in this shader.
*
* If variable is not found, it will display error messages on the log.
*
* @param variable The variable (reference) to test
* @param name The variable (name) to test
*
* @return true if the GLSL variable was found in this shader.
*/
bool validateVariable(GLint variable, const char* name);
};
}
#endif /* __CU_SPRITE_SHADER_H__ */
| [
"[email protected]"
] | |
c29356c5a9c65247e34a4d7bba7baa7974fdab3d | d12f7bf84bba8f19ffe31b630a77c55e8432a4b7 | /Trees/Boundary_Traversal_of_binary_tree/main.cpp | 18eed48e19c793f5464cd9ea343d403c556af83e | [] | no_license | shreyasmishragithub/AlgorithmsAndDataStructures | 279a6d74bbdbab211d64c7c0188f0e864b461f80 | 129a8bbaec632b52ca0463940cd8bd186cf5d285 | refs/heads/master | 2021-06-03T05:24:14.574141 | 2016-07-23T06:15:36 | 2016-07-23T06:15:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,518 | cpp | //
// main.cpp
// Boundary_Traversal_of_binary_tree
//
// Created by Nitesh Thali on 7/22/16.
// Copyright © 2016 Nitesh Thali. All rights reserved.
/*
Boundary traversal of a Binary Tree in anticlockwise fashion.*** (check implementation)
This can do done in following way.
1. print all nodes on left boundary.
2. print all leaf nodes.
3. print all nodes on right boundary.
Care should be taken not to print corner nodes twice.
*/
#include <iostream>
using namespace std;
struct Node{
int data;
Node *left, *right;
};
Node* getNode(int data)
{
Node *tmp = new Node();
tmp->data = data;
tmp->left = tmp->right = NULL;
return tmp;
}
void inorder(Node *root)
{
if(root)
{
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
}
void printLefBoundary(Node* root){
if (root == NULL)
return;
if (!root->left && !root->right)
return;
if(root->left){
cout << root->data << " ";
printLefBoundary(root->left);
}else{
cout << root->data << " ";
printLefBoundary(root->right);
}
}
void printLeafNodes(Node* root){
if (root == NULL)
return;
if (!root->left && !root->right){
cout << root->data << " ";
return;
}
printLeafNodes(root->left);
printLeafNodes(root->right);
}
void printRightBoundary(Node *root){
if (root == NULL)
return;
if (!root->left && !root->right)
return;
if(root->right){
printRightBoundary(root->right);
}else{
printRightBoundary(root->left);
}
cout << root->data << " ";
}
void printBoundary(Node* root){
cout << root->data << " ";
printLefBoundary(root->left);
printLeafNodes(root);
printRightBoundary(root->right);
}
int main(int argc, const char * argv[]) {
// insert code here...
/*
50
/ \
10 100
/ \ / \
5 20 60 150
\ / /
2 55 15
/
21
*/
Node *root = getNode(50);
root->left = getNode(10);
root->right = getNode(100);
root->left->left = getNode(5);
root->left->right = getNode(20);
root->left->left->right = getNode(2);
root->right->left = getNode(60);
root->right->right = getNode(150);
root->right->right->left = getNode(15);
root->right->right->left->left = getNode(21);
root->right->left->left = getNode(55);
printBoundary(root);
return 0;
} | [
"[email protected]"
] | |
2cd9b7124ec8e48e790d5de41a40588472d77b58 | 43a2fbc77f5cea2487c05c7679a30e15db9a3a50 | /Cpp/External (Offsets Only)/SDK/BP_prem_shop_wld_01_a_classes.h | d0cf47ecc575cdbde5f7051e3c2dfdb7b42c5f27 | [] | no_license | zH4x/SoT-Insider-SDK | 57e2e05ede34ca1fd90fc5904cf7a79f0259085c | 6bff738a1b701c34656546e333b7e59c98c63ad7 | refs/heads/main | 2023-06-09T23:10:32.929216 | 2021-07-07T01:34:27 | 2021-07-07T01:34:27 | 383,638,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,238 | h | #pragma once
// Name: SoT-Insider, Version: 1.102.2382.0
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_prem_shop_wld_01_a.BP_prem_shop_wld_01_a_C
// 0x03E0 (FullSize[0x07B0] - InheritedSize[0x03D0])
class ABP_prem_shop_wld_01_a_C : public AActor
{
public:
class UStaticMeshComponent* StaticMesh9; // 0x03D0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UPointLightComponent* PointLight1; // 0x03D8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* StaticMesh8; // 0x03E0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* StaticMesh; // 0x03E8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UPetHangoutSpotComponent* PetHangoutSpot; // 0x03F0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UCompanyRegionComponent* CompanyRegion; // 0x03F8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* tls_wld_torch_skull_b; // 0x0400(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* tls_wld_Orb_light_a; // 0x0408(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UPointLightComponent* PointLight15; // 0x0410(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class USpotLightComponent* SpotLight3; // 0x0418(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UPointLightComponent* PointLight14; // 0x0420(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UPointLightComponent* PointLight13; // 0x0428(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UPointLightComponent* PointLight12; // 0x0430(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UPointLightComponent* PointLight10; // 0x0438(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class USpotLightComponent* SpotLight2; // 0x0440(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UPointLightComponent* PointLight9; // 0x0448(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UPointLightComponent* PointLight7; // 0x0450(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class USpotLightComponent* SpotLight1; // 0x0458(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UPointLightComponent* PointLight6; // 0x0460(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UPointLightComponent* PointLight5; // 0x0468(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UPointLightComponent* PointLight3; // 0x0470(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UPointLightComponent* PointLight; // 0x0478(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class USpotLightComponent* SpotLight; // 0x0480(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* AnimalSack; // 0x0488(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Pot; // 0x0490(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Banana_Sack; // 0x0498(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Boat2; // 0x04A0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* fod_banana_01_a; // 0x04A8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Book3; // 0x04B0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Book2; // 0x04B8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UChildActorComponent* ChildActor1; // 0x04C0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* RopeExterior; // 0x04C8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UParticleSystemComponent* ParticleSystem3; // 0x04D0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Bottle5; // 0x04D8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Mannequin2; // 0x04E0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Book; // 0x04E8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Sidetable; // 0x04F0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Moneysack2; // 0x04F8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Moneysack1; // 0x0500(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* DrapesRoof; // 0x0508(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Dreamcatcher4; // 0x0510(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* WoodPole2; // 0x0518(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* WoodPole1; // 0x0520(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Ladder4; // 0x0528(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Shelf1; // 0x0530(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Bananas1; // 0x0538(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Dreamcatcher2; // 0x0540(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Ladder3; // 0x0548(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Ladder2; // 0x0550(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Platform; // 0x0558(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Ladder1; // 0x0560(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Collar1; // 0x0568(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Hooks2; // 0x0570(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Hooks1; // 0x0578(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Dreamcatcher3; // 0x0580(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Sack_Banana2; // 0x0588(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Sack_Banana; // 0x0590(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Sack_Banana3; // 0x0598(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Mannequin; // 0x05A0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* Dreamcatcher1; // 0x05A8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UChildActorComponent* BP_wil_monkey_big_04; // 0x05B0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UChildActorComponent* BP_wil_parrot_04; // 0x05B8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_shop_sign_ancient_01_a; // 0x05C0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* StaticMesh3; // 0x05C8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* cmn_bottle_01_a; // 0x05D0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* StaticMesh2; // 0x05D8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_shop_wood_box_03_a; // 0x05E0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* cmn_animal_cage_01_a; // 0x05E8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* StaticMesh1; // 0x05F0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_cls_shop_bird_cage_01_a; // 0x05F8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_cls_shp_dye_pot_01_a1; // 0x0600(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* cmn_moneybag_01_a2; // 0x0608(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* cmn_bird_cage_01_a; // 0x0610(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_prem_shop_rope_details_01_d; // 0x0618(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* StaticMesh7; // 0x0620(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* StaticMesh6; // 0x0628(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* StaticMesh5; // 0x0630(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* StaticMesh4; // 0x0638(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UParticleSystemComponent* ParticleSystem1; // 0x0640(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UPointLightComponent* PointLight8; // 0x0648(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UChildActorComponent* bp_lantern_hook_01_a; // 0x0650(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UChildActorComponent* AudioSpace; // 0x0658(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* gmp_bar_hide_01_a4; // 0x0660(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_enc_shop_sign_01_a; // 0x0668(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* cap_cage_01_a; // 0x0670(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* shp_kra_shark_rug_01_a; // 0x0678(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_pot_shop_table_wld_01_a; // 0x0680(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_pot_shop_window_01_a1; // 0x0688(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_prem_shop_wilds_details_01_a; // 0x0690(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_prem_shop_01_a; // 0x0698(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_int_large_shelf_03_a1; // 0x06A0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_int_large_shelf_03_a; // 0x06A8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* cap_cabin_books_aged_03_a; // 0x06B0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* cap_cabin_books_02_a; // 0x06B8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* cap_cabin_books_03_a; // 0x06C0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* trs_coins_01_a_coin_2; // 0x06C8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* cmn_broken_shovel_01_a; // 0x06D0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* cmn_clay_vase_01_b; // 0x06D8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* trs_plate_01_a; // 0x06E0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* gmp_dice_kra_01_a; // 0x06E8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* gmp_dice_01_e; // 0x06F0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* gmp_dice_01_d; // 0x06F8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_enc_shop_pin_board_01_a; // 0x0700(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_enc_shop_burner_pot_01_a; // 0x0708(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_int_large_sideboard_03_a; // 0x0710(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* cmn_moneybag_01_a; // 0x0718(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* cmn_step_ladder_01_a; // 0x0720(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* cmn_candle_01_e; // 0x0728(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* cap_skull_candle_01_a; // 0x0730(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_par_weathervane_01_b; // 0x0738(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_tvn_post_01_c; // 0x0740(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* cap_cabin_curtain_03_a; // 0x0748(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_int_small_shelves_01_a; // 0x0750(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_pot_shop_door_frame_01_a; // 0x0758(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_pot_shop_roof_beam_01_a; // 0x0760(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_pot_shop_chimney_01_a; // 0x0768(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_pot_gate_01_a; // 0x0770(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_pot_fence_01_a; // 0x0778(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_pot_shop_window_01_a3; // 0x0780(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_pot_hatch_01_a; // 0x0788(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_pot_shop_door_01_a; // 0x0790(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_pot_shop_window_01_a2; // 0x0798(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class UStaticMeshComponent* bld_pot_shop_window_01_a; // 0x07A0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
class USceneComponent* DefaultSceneRoot; // 0x07A8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData, NonTransactional, NoDestructor)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_prem_shop_wld_01_a.BP_prem_shop_wld_01_a_C");
return ptr;
}
void UserConstructionScript();
void AfterRead();
void BeforeDelete();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
fc5d0b8bac6b918ba211a7642889ed112c6586ff | 4465585c96656a7c31b385699690340823c27e25 | /src/gpu/gepard-path.h | 846405a6b055624945a97b9c9b6b8b20b0e4f136 | [
"BSD-2-Clause"
] | permissive | elecro/gepard | 1552f443061b4e171587f50818ef0ccf75708eab | 4f4677c1aa5a8cf336feedad2b52bf4be0740e37 | refs/heads/master | 2021-01-18T12:16:26.197832 | 2016-06-16T17:22:48 | 2016-06-16T17:22:48 | 61,559,781 | 0 | 0 | null | 2016-06-20T15:45:12 | 2016-06-20T15:45:12 | null | UTF-8 | C++ | false | false | 5,884 | h | /* Copyright (C) 2016, Gepard Graphics
* Copyright (C) 2015, Szilard Ledan <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef GEPARD_PATH_H
#define GEPARD_PATH_H
#include "gepard-types.h"
#include <iostream>
namespace gepard {
typedef enum PathElementTypes {
Undefined = 0,
MoveTo,
LineTo,
QuadraticCurve,
BezierCurve,
Arc,
CloseSubpath,
} PathElementType;
struct PathElement {
explicit PathElement() : next(nullptr), type(PathElementTypes::Undefined) {}
explicit PathElement(PathElementType type) : next(nullptr), type(type) {}
explicit PathElement(PathElementType type, FloatPoint to)
: next(nullptr)
, type(type)
, to(to)
{}
bool isMoveTo() const { return this->type == PathElementTypes::MoveTo; }
bool isCloseSubpath() const { return this->type == PathElementTypes::CloseSubpath; }
virtual std::ostream& output(std::ostream& os) const
{
return os << this->to;
}
PathElement* next;
PathElementType type;
FloatPoint to;
};
inline std::ostream& operator<<(std::ostream& os, const PathElement& ps)
{
return ps.output(os);
}
struct MoveToElement : public PathElement {
explicit MoveToElement(FloatPoint to) : PathElement(PathElementTypes::MoveTo, to) {}
std::ostream& output(std::ostream& os) const { return PathElement::output(os << "M"); }
};
struct LineToElement : public PathElement {
explicit LineToElement(FloatPoint to) : PathElement(PathElementTypes::LineTo, to) {}
std::ostream& output(std::ostream& os) const { return PathElement::output(os << "L"); }
};
struct CloseSubpathElement : public PathElement {
explicit CloseSubpathElement(FloatPoint to) : PathElement(PathElementTypes::CloseSubpath, to) {}
std::ostream& output(std::ostream& os) const { return PathElement::output(os << "Z"); }
};
struct QuadraticCurveToElement : public PathElement {
explicit QuadraticCurveToElement(FloatPoint control, FloatPoint to)
: PathElement(PathElementTypes::QuadraticCurve, to)
, control(control)
{}
std::ostream& output(std::ostream& os) const
{
return PathElement::output(os << "Q" << this->control << " ");
}
FloatPoint control;
};
struct BezierCurveToElement : public PathElement {
explicit BezierCurveToElement(FloatPoint control1, FloatPoint control2, FloatPoint to)
: PathElement(PathElementTypes::BezierCurve, to)
, control1(control1)
, control2(control2)
{}
std::ostream& output(std::ostream& os) const
{
return PathElement::output(os << "C" << this->control1 << " " << this->control2 << " ");
}
FloatPoint control1;
FloatPoint control2;
};
struct ArcElement : public PathElement {
explicit ArcElement(FloatPoint center, FloatPoint radius, Float startAngle, Float endAngle, bool antiClockwise = true)
: PathElement(PathElementTypes::Arc, FloatPoint(center.x + cos(endAngle) * radius.x, center.y + sin(endAngle) * radius.y))
, center(center)
, radius(radius)
, startAngle(startAngle)
, endAngle(endAngle)
, antiClockwise(antiClockwise)
{
ASSERT(radius.x >= 0 && radius.y >= 0);
}
std::ostream& output(std::ostream& os) const
{
// TODO(szledan): generate SVG representation
os << "A";
return PathElement::output(os);
}
FloatPoint center;
FloatPoint radius;
Float startAngle;
Float endAngle;
bool antiClockwise;
};
struct PathData {
explicit PathData()
: _firstElement(nullptr)
, _lastElement(nullptr)
, _lastMoveToElement(nullptr)
{}
void addMoveToElement(FloatPoint);
void addLineToElement(FloatPoint);
void addQuadaraticCurveToElement(FloatPoint, FloatPoint);
void addBezierCurveToElement(FloatPoint, FloatPoint, FloatPoint);
void addArcElement(FloatPoint, FloatPoint, Float, Float, bool = true);
void addArcToElement(const FloatPoint&, const FloatPoint&, const Float&);
void addCloseSubpathElement();
#ifndef NDEBUG
void dump();
#endif
PathElement* firstElement() const { return _firstElement; }
PathElement* lastElement() const { return _lastElement; }
private:
Region<> _region;
PathElement* _firstElement;
PathElement* _lastElement;
PathElement* _lastMoveToElement;
};
/* Path */
class Path {
public:
explicit Path()
{}
PathData& pathData() { return _pathData; }
void fillPath();
private:
PathData _pathData;
};
} // namespace gepard
#endif // GEPARD_PATH_H
| [
"[email protected]"
] | |
244fd1e83724a5257be5bcd671e3479e64bb6f67 | aca4214cbe2c766dd32c1ad659b38e6fb956ded4 | /ios/web/public/test/response_providers/string_response_provider.h | e5a0f9e18c9130c5f0ff0652b0031bf913363b47 | [
"BSD-3-Clause"
] | permissive | weiliangc/chromium | 5b04562d1c3ae93d4ab56872fcb728e74129bbb7 | 357396ffe3cc7ace113783f25e088d08e615b08b | refs/heads/master | 2022-11-18T01:01:44.411877 | 2016-12-19T18:39:38 | 2016-12-19T18:42:00 | 71,932,761 | 1 | 0 | null | 2016-10-25T19:44:10 | 2016-10-25T19:44:10 | null | UTF-8 | C++ | false | false | 1,206 | h | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef IOS_WEB_PUBLIC_TEST_RESPONSE_PROVIDERS_STRING_RESPONSE_PROVIDER_H_
#define IOS_WEB_PUBLIC_TEST_RESPONSE_PROVIDERS_STRING_RESPONSE_PROVIDER_H_
#include <string>
#include "base/macros.h"
#include "ios/web/public/test/response_providers/data_response_provider.h"
namespace web {
// A response provider that returns a string for all requests. Used for testing
// purposes.
class StringResponseProvider : public web::DataResponseProvider {
public:
explicit StringResponseProvider(const std::string& response_body);
// web::DataResponseProvider methods.
bool CanHandleRequest(const Request& request) override;
void GetResponseHeadersAndBody(
const Request& request,
scoped_refptr<net::HttpResponseHeaders>* headers,
std::string* response_body) override;
private:
// The string that is returned in the response body.
std::string response_body_;
DISALLOW_COPY_AND_ASSIGN(StringResponseProvider);
};
} // namespace web
#endif // IOS_WEB_PUBLIC_TEST_RESPONSE_PROVIDERS_STRING_RESPONSE_PROVIDER_H_
| [
"[email protected]"
] | |
b517d0ac80f200030f9766063fe246752c8ead1d | 164251f42dcd2d652984f6f6da550466988763b9 | /Technical Prototype/source/Character.hpp | 4a917f02993a129638a79965a78dbf8617bf59c6 | [] | no_license | Gnuck/mymagicmansion | d1f6129278d769603b9d8b5aec75e9d5a1599970 | 453c2a170ce19a438dbbbf83743c74933fdf6d0e | refs/heads/master | 2021-01-20T06:30:28.796344 | 2017-08-26T19:44:29 | 2017-08-26T19:44:29 | 101,438,881 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,284 | hpp | //
// GameModel.cpp
// RocketDemo
//
// Created by Jiacong Xu on 3/16/17.
// Copyright © 2017 Game Design Initiative at Cornell. All rights reserved.
//
#ifndef __CHARACTER_H__
#define __CHARACTER_H__
#include <cugl/cugl.h>
#include <cugl/2d/physics/CUBoxObstacle.h>
#include <cugl/2d/physics/CUCapsuleObstacle.h>
#include <cugl/2d/CUWireNode.h>
#include <list>
/** For the character's body in relation to its texture */
#define NODE_X_OFFSET 0.05
#define CHAR_SIZE_FACTOR 0.35
/** The number of frames for the walking animation */
#define WALKING_FRAMES 8
#define WALKING_FACTOR 5
/** The number of frames for the falling animation */
#define FALLING_FRAMES 6
#define FALLING_FACTOR 4
#define END_FALLING_FACTOR 2
/** The number of frames for the climbing animation */
#define CLIMBING_FRAMES 8
#define CLIMBING_FACTOR 5
/** The number of frames for the pick up object animation */
#define PICKUP_FRAMES 4
#define PICKUP_FACTOR 5
#define EXCLAMATION_FRAMES 1
using namespace cugl;
/**
This is our character in the game. We extend it from a box2d physics object so
that physics event listeners can grab this object straight away, as opposed to,
for example, checking physics object tag then grabbing a static character
reference.
*/
class Character : public cugl::CapsuleObstacle {
private:
/**
This macro disables the copy constructor (not allowed on physics objects)
*/
CU_DISALLOW_COPY_AND_ASSIGN(Character);
// The character's physics body size. This might not be the same as the
// animations.
cugl::Vec2 charSize = cugl::Vec2(0.525, .733333);
//cugl::Vec2 charSize = cugl::Vec2(0.895, 1.25); //1/4 tile height
//NOT IMPLEMENTED IN CURRENT METHOD. May be useful later so keeping.
// Raycast: there are two points for raycasting, one a little above the
// character and one below. If both hits, then we are facing a wall. If only
// one hits, then we are facing stairs, and we climb. This is assuming we
// are facing right. Otherwise negate x component.
cugl::Vec2 topRayOffset = cugl::Vec2(charSize.x, charSize.y * 0.9) / 2;
cugl::Vec2 botRayOffset = cugl::Vec2(charSize.x, -charSize.y * 0.9) / 2;
bool topHit = false;
bool botHit = false;
// Raycast: One point for raycasting located a littel below the character.
float rayLength = 0.1;
/**
Whether the character is facing the wall. This is mainly for movement.
*/
bool facingWall;
/**
Whether the character is facing stairs. This is mainly for movement.
*/
bool facingStairs;
/**
The horizontal movement speed of the character.
*/
float moveSpeed = 1.0;
float climbSpeed = 1.0;
/** To slow down the animations */
int walkingFrames;
int fallingFrames;
int climbingFrames;
int pickupFrames;
/** To initialize animation nodes */
void initAnimation();
public:
/**
The scene graph node for the Dude.
*/
std::shared_ptr<cugl::PolygonNode> node;
/**
The animation nodes */
std::shared_ptr<cugl::AnimationNode> walking_node;
std::shared_ptr<cugl::AnimationNode> falling_node;
std::shared_ptr<cugl::AnimationNode> climbing_node;
std::shared_ptr<cugl::AnimationNode> pickup_node;
std::shared_ptr<cugl::AnimationNode> current_node;
std::shared_ptr<cugl::AnimationNode> exclamation_node;
/**
Whether the character is facing right. This affects character's movement
and animations.
*/
bool facingRight;
/**
The scene graph Rectangle container
*/
Rect container;
/**
True if character has reached goal door. False otherwise.
*/
bool hitGoal = false;
/**
List of collectables obtained by the character
*/
std::list<std::string> collected;
/**
The degenerate constructor that calls just its parent.
*/
Character() : CapsuleObstacle() {
}
/**
Destroys this Character, releasing all resources.
*/
~Character() {
}
/**
Initializes a character at the given position in world coordinates. The
box2d world object and node object should have the same coordinates. Assigns
a number to the character to figure out its texture
*/
bool init(cugl::Vec2 pos, bool facingRight);
/**
Creates and initializes a character at the given position in world
coordinates. The box2d world object and node object should have the same
coordinates.
*/
static std::shared_ptr<Character> alloc(cugl::Vec2 pos, bool facingRight) {
std::shared_ptr<Character> result = std::make_shared<Character>();
return (result->init(pos, facingRight) ? result : nullptr);
}
/**
* To switch animation nodes
*/
void switchAnimation(std::shared_ptr<cugl::AnimationNode> next_node);
/**
* Walking animation
*/
void animateWalking(bool on);
/**
* Falling animation
*/
bool beginFallingStart; // Can start the begin falling animation
bool beginFallingEnd; // Can end the begin falling animation
bool endFallingStart; // Can start the end falling animation
bool endFallingEnd; // Can end the end falling animation
bool fallAnimation; // True when the fall animation is running
void beginFalling(bool on);
void animateFalling(bool on);
void endFalling(bool on);
/**
* climbing animation
*/
void animateClimbing(bool on);
bool climbingStairs; // whether or not the character is currently climbing stairs
int notClimbingFrames; // to make sure character is actually off of the stairs
/**
* Pickup animation
*/
void animatePickup(bool on);
bool pickingUpObject; //whether or not the character is currently picking up object to ensure animation runs once
/**
*make character stop moving while layer switches
*/
void changeSpeed(float speed);
/**
Updates the character and its scene node position.
*/
void update(std::shared_ptr<cugl::ObstacleWorld> world, float dt);
};
#endif /* __PF_DUDE_MODEL_H__ */
| [
"[email protected]"
] | |
44f176b36d89caab7302051ff1d69f384b06eacb | 30d9882a0d86ccecdbc763adeef21ca23657c274 | /DXTutorial/GraphicsResources.cpp | aef2c8d4a7c0238ad0c11446475307c9df19f16b | [] | no_license | CheezBoiger/d3d12-testing | 5f219bd138c39b007c6237a2d78766e6c9b377cf | 7137b4aa123e21fcea5b58abf2de784d25f63fd0 | refs/heads/master | 2022-04-12T04:21:22.187429 | 2020-04-03T10:13:19 | 2020-04-03T10:13:19 | 210,415,386 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,200 | cpp | //
#include "GraphicsResources.h"
namespace jcl {
class GPUCache
{
public:
static RenderUUID cacheGPUResource(gfx::Resource* pResource);
static gfx::Resource* getGPUResource(RenderUUID uuid);
};
RenderUUID idd = 0;
std::unordered_map<RenderUUID, gfx::Resource*> m_pGraphicsResources;
std::unordered_map<RenderUUID, gfx::VertexBufferView*> m_pVertexBufferViews;
std::unordered_map<RenderUUID, gfx::IndexBufferView*> m_pIndexBufferViews;
RenderUUID cacheResource(gfx::Resource* pResource)
{
RenderUUID id = idd++;
m_pGraphicsResources[id] = pResource;
return id;
}
RenderUUID cacheVertexBufferView(gfx::VertexBufferView* pView)
{
RenderUUID id = idd++;
m_pVertexBufferViews[id] = pView;
return id;
}
RenderUUID cacheIndexBufferView(gfx::IndexBufferView* pView)
{
RenderUUID id = idd++;
m_pIndexBufferViews[id] = pView;
return id;
}
gfx::Resource* getResource(RenderUUID uuid)
{
return m_pGraphicsResources[uuid];
}
gfx::VertexBufferView* getVertexBufferView(RenderUUID uuid)
{
return m_pVertexBufferViews[uuid];
}
gfx::IndexBufferView* getIndexBufferView(RenderUUID uuid)
{
return m_pIndexBufferViews[uuid];
}
} // jcl | [
"[email protected]"
] | |
14403ace006737afb565c5599e59f44a0b1ac842 | 06b1c887274634ca9f4606641914e71443d9923c | /src/ascent-world/WorldSession.h | fd2e4f551d04609d04c91b909eef459b89806e7c | [] | no_license | zod331/Summit | 3d12db09fc02a1557de91cb61aacf6f801c16e38 | 95df88b83918a70d2d25d8618ca79b6cc1e8f38a | refs/heads/master | 2020-06-01T03:44:07.453120 | 2013-06-09T21:21:47 | 2013-06-09T21:21:47 | 10,589,168 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,041 | h | /*
* Ascent MMORPG Server
* Copyright (C) 2005-2008 Ascent Team <http://www.ascentemu.com/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
//
//
// WorldSession.h
//
#ifndef __WORLDSESSION_H
#define __WORLDSESSION_H
class Player;
class WorldPacket;
class WorldSocket;
class WorldSession;
class MapMgr;
class Creature;
class MovementInfo;
struct TrainerSpell;
//#define SESSION_CAP 5
// MovementFlags Contribution by Tenshi
enum MovementFlags
{
// Byte 1 (Resets on Movement Key Press)
MOVEFLAG_MOVE_STOP = 0x00, //verified
MOVEFLAG_MOVE_FORWARD = 0x01, //verified
MOVEFLAG_MOVE_BACKWARD = 0x02, //verified
MOVEFLAG_STRAFE_LEFT = 0x04, //verified
MOVEFLAG_STRAFE_RIGHT = 0x08, //verified
MOVEFLAG_TURN_LEFT = 0x10, //verified
MOVEFLAG_TURN_RIGHT = 0x20, //verified
MOVEFLAG_PITCH_DOWN = 0x40, //Unconfirmed
MOVEFLAG_PITCH_UP = 0x80, //Unconfirmed
// Byte 2 (Resets on Situation Change)
MOVEFLAG_WALK = 0x100, //verified
MOVEFLAG_TAXI = 0x200,
MOVEFLAG_NO_COLLISION = 0x400,
MOVEFLAG_FLYING = 0x800, //verified
MOVEFLAG_REDIRECTED = 0x1000, //Unconfirmed
MOVEFLAG_FALLING = 0x2000, //verified
MOVEFLAG_FALLING_FAR = 0x4000, //verified
MOVEFLAG_FREE_FALLING = 0x8000, //half verified
// Byte 3 (Set by server. TB = Third Byte. Completely unconfirmed.)
MOVEFLAG_TB_PENDING_STOP = 0x10000, // (MOVEFLAG_PENDING_STOP)
MOVEFLAG_TB_PENDING_UNSTRAFE = 0x20000, // (MOVEFLAG_PENDING_UNSTRAFE)
MOVEFLAG_TB_PENDING_FALL = 0x40000, // (MOVEFLAG_PENDING_FALL)
MOVEFLAG_TB_PENDING_FORWARD = 0x80000, // (MOVEFLAG_PENDING_FORWARD)
MOVEFLAG_TB_PENDING_BACKWARD = 0x100000, // (MOVEFLAG_PENDING_BACKWARD)
MOVEFLAG_SWIMMING = 0x200000, // verified
MOVEFLAG_FLYING_PITCH_UP = 0x400000, // (half confirmed)(MOVEFLAG_PENDING_STR_RGHT)
MOVEFLAG_TB_MOVED = 0x800000, // (half confirmed) gets called when landing (MOVEFLAG_MOVED)
// Byte 4 (Script Based Flags. Never reset, only turned on or off.)
MOVEFLAG_AIR_SUSPENSION = 0x1000000, // confirmed allow body air suspension(good name? lol).
MOVEFLAG_AIR_SWIMMING = 0x2000000, // confirmed while flying.
MOVEFLAG_SPLINE_MOVER = 0x4000000, // Unconfirmed
MOVEFLAG_IMMOBILIZED = 0x8000000,
MOVEFLAG_WATER_WALK = 0x10000000,
MOVEFLAG_FEATHER_FALL = 0x20000000, // Does not negate fall damage.
MOVEFLAG_LEVITATE = 0x40000000,
MOVEFLAG_LOCAL = 0x80000000, // This flag defaults to on. (Assumption)
// Masks
MOVEFLAG_MOVING_MASK = 0x03,
MOVEFLAG_STRAFING_MASK = 0x0C,
MOVEFLAG_TURNING_MASK = 0x30,
MOVEFLAG_FALLING_MASK = 0x6000,
MOVEFLAG_MOTION_MASK = 0xE00F, // Forwards, Backwards, Strafing, Falling
MOVEFLAG_PENDING_MASK = 0x7F0000,
MOVEFLAG_PENDING_STRAFE_MASK = 0x600000,
MOVEFLAG_PENDING_MOVE_MASK = 0x180000,
MOVEFLAG_FULL_FALLING_MASK = 0xE000,
};
struct OpcodeHandler
{
uint16 status;
void (WorldSession::*handler)(WorldPacket& recvPacket);
};
enum SessionStatus
{
STATUS_AUTHED = 0,
STATUS_LOGGEDIN
};
struct AccountDataEntry
{
char * data;
uint32 sz;
bool bIsDirty;
};
typedef struct Cords {
float x,y,z;
}Cords;
class MovementInfo
{
public:
uint32 time;
float unk6;//pitch
//on slip 8 is zero, on jump some other number
//9,10 changes if you are not on foot
uint32 unk8, unk9, unk10, unk11, unk12, unk13;
uint32 unklast;//something related to collision
uint8 unk_230;
float x, y, z, orientation;
uint32 flags;
uint32 FallTime;
uint64 transGuid;
float transX, transY, transZ, transO, transUnk;
void init(WorldPacket & data);
void write(WorldPacket & data);
};
#define CHECK_INWORLD_RETURN if(_player == NULL || !_player->IsInWorld()) { return; }
#define CHECK_GUID_EXISTS(guidx) if(_player->GetMapMgr()->GetUnit((guidx)) == NULL) { return; }
#define CHECK_PACKET_SIZE(pckp, ssize) if(ssize && pckp.size() < ssize) { Disconnect(); return; }
#define NOTIFICATION_MESSAGE_NO_PERMISSION "You do not have permission to perform that function."
//#define CHECK_PACKET_SIZE(x, y) if(y > 0 && x.size() < y) { _socket->Disconnect(); return; }
void EncodeHex(const char* source, char* dest, uint32 size);
void DecodeHex(const char* source, char* dest, uint32 size);
extern OpcodeHandler WorldPacketHandlers[NUM_MSG_TYPES];
void CapitalizeString(string& arg);
class SERVER_DECL WorldSession
{
friend class WorldSocket;
public:
WorldSession(uint32 id, string Name, WorldSocket *sock);
~WorldSession();
Player * m_loggingInPlayer;
ASCENT_INLINE void SendPacket(WorldPacket* packet)
{
if(_socket && _socket->IsConnected())
_socket->SendPacket(packet);
}
ASCENT_INLINE void SendPacket(StackPacket * packet)
{
if(_socket && _socket->IsConnected())
_socket->SendPacket(packet);
}
ASCENT_INLINE void OutPacket(uint16 opcode)
{
if(_socket && _socket->IsConnected())
_socket->OutPacket(opcode, 0, NULL);
}
void Delete();
void SendChatPacket(WorldPacket * data, uint32 langpos, int32 lang, WorldSession * originator);
uint32 m_currMsTime;
uint32 m_lastPing;
ASCENT_INLINE uint32 GetAccountId() const { return _accountId; }
ASCENT_INLINE Player* GetPlayer() { return _player; }
/* Acct flags */
void SetAccountFlags(uint32 flags) { _accountFlags = flags; }
bool HasFlag(uint32 flag) { return (_accountFlags & flag) != 0; }
/* GM Permission System */
void LoadSecurity(std::string securitystring);
void SetSecurity(std::string securitystring);
ASCENT_INLINE char* GetPermissions() { return permissions; }
ASCENT_INLINE int GetPermissionCount() { return permissioncount; }
ASCENT_INLINE bool HasPermissions() { return (permissioncount > 0) ? true : false; }
ASCENT_INLINE bool HasGMPermissions()
{
if(!permissioncount)
return false;
return (strchr(permissions,'a')!=NULL) ? true : false;
}
bool CanUseCommand(char cmdstr);
ASCENT_INLINE void SetSocket(WorldSocket *sock)
{
_socket = sock;
}
ASCENT_INLINE void SetPlayer(Player *plr) { _player = plr; }
ASCENT_INLINE void SetAccountData(uint32 index, char* data, bool initial,uint32 sz)
{
ASSERT(index < 8);
if(sAccountData[index].data)
delete [] sAccountData[index].data;
sAccountData[index].data = data;
sAccountData[index].sz = sz;
if(!initial && !sAccountData[index].bIsDirty) // Mark as "changed" or "dirty"
sAccountData[index].bIsDirty = true;
else if(initial)
sAccountData[index].bIsDirty = false;
}
ASCENT_INLINE AccountDataEntry* GetAccountData(uint32 index)
{
ASSERT(index < 8);
return &sAccountData[index];
}
void SetLogoutTimer(uint32 ms)
{
if(ms) _logoutTime = m_currMsTime+ms;
else _logoutTime = 0;
}
void LogoutPlayer(bool Save);
ASCENT_INLINE void QueuePacket(WorldPacket* packet)
{
m_lastPing = (uint32)UNIXTIME;
_recvQueue.Push(packet);
}
void OutPacket(uint16 opcode, uint16 len, const void* data)
{
if(_socket && _socket->IsConnected())
_socket->OutPacket(opcode, len, data);
}
ASCENT_INLINE WorldSocket* GetSocket() { return _socket; }
void Disconnect()
{
if(_socket && _socket->IsConnected())
_socket->Disconnect();
}
int __fastcall Update(uint32 InstanceID);
void SendItemPushResult(Item * pItem, bool Created, bool Received, bool SendToSet, bool NewItem, uint8 DestBagSlot, uint32 DestSlot, uint32 AddCount);
void SendBuyFailed(uint64 guid, uint32 itemid, uint8 error);
void SendSellItem(uint64 vendorguid, uint64 itemid, uint8 error);
void SendNotification(const char *message, ...);
ASCENT_INLINE void SetInstance(uint32 Instance) { instanceId = Instance; }
ASCENT_INLINE uint32 GetLatency() { return _latency; }
ASCENT_INLINE string GetAccountName() { return _accountName; }
ASCENT_INLINE const char * GetAccountNameS() { return _accountName.c_str(); }
ASCENT_INLINE uint32 GetClientBuild() { return client_build; }
ASCENT_INLINE void SetClientBuild(uint32 build) { client_build = build; }
bool bDeleted;
ASCENT_INLINE uint32 GetInstance() { return instanceId; }
Mutex deleteMutex;
void _HandleAreaTriggerOpcode(uint32 id);//real handle
int32 m_moveDelayTime;
int32 m_clientTimeDelay;
void CharacterEnumProc(QueryResult * result);
void LoadAccountDataProc(QueryResult * result);
ASCENT_INLINE bool IsLoggingOut() { return _loggingOut; }
protected:
/// Login screen opcodes (PlayerHandler.cpp):
void HandleCharEnumOpcode(WorldPacket& recvPacket);
void HandleCharDeleteOpcode(WorldPacket& recvPacket);
void HandleCharCreateOpcode(WorldPacket& recvPacket);
void HandlePlayerLoginOpcode(WorldPacket& recvPacket);
/// Authentification and misc opcodes (MiscHandler.cpp):
void HandlePingOpcode(WorldPacket& recvPacket);
void HandleAuthSessionOpcode(WorldPacket& recvPacket);
void HandleRepopRequestOpcode(WorldPacket& recvPacket);
void HandleAutostoreLootItemOpcode(WorldPacket& recvPacket);
void HandleLootMoneyOpcode(WorldPacket& recvPacket);
void HandleLootOpcode(WorldPacket& recvPacket);
void HandleLootReleaseOpcode(WorldPacket& recvPacket);
void HandleLootMasterGiveOpcode(WorldPacket& recv_data);
void HandleLootRollOpcode(WorldPacket& recv_data);
void HandleWhoOpcode(WorldPacket& recvPacket);
void HandleLogoutRequestOpcode(WorldPacket& recvPacket);
void HandlePlayerLogoutOpcode(WorldPacket& recvPacket);
void HandleLogoutCancelOpcode(WorldPacket& recvPacket);
void HandleZoneUpdateOpcode(WorldPacket& recvPacket);
void HandleSetTargetOpcode(WorldPacket& recvPacket);
void HandleSetSelectionOpcode(WorldPacket& recvPacket);
void HandleStandStateChangeOpcode(WorldPacket& recvPacket);
void HandleDismountOpcode(WorldPacket & recvPacket);
void HandleFriendListOpcode(WorldPacket& recvPacket);
void HandleAddFriendOpcode(WorldPacket& recvPacket);
void HandleDelFriendOpcode(WorldPacket& recvPacket);
void HandleAddIgnoreOpcode(WorldPacket& recvPacket);
void HandleDelIgnoreOpcode(WorldPacket& recvPacket);
void HandleBugOpcode(WorldPacket& recvPacket);
void HandleAreaTriggerOpcode(WorldPacket& recvPacket);
void HandleUpdateAccountData(WorldPacket& recvPacket);
void HandleRequestAccountData(WorldPacket& recvPacket);
void HandleSetActionButtonOpcode(WorldPacket& recvPacket);
void HandleSetAtWarOpcode(WorldPacket& recvPacket);
void HandleSetWatchedFactionIndexOpcode(WorldPacket& recvPacket);
void HandleTogglePVPOpcode(WorldPacket& recvPacket);
void HandleAmmoSetOpcode(WorldPacket& recvPacket);
void HandleGameObjectUse(WorldPacket& recvPacket);
//void HandleJoinChannelOpcode(WorldPacket& recvPacket);
//void HandleLeaveChannelOpcode(WorldPacket& recvPacket);
void HandlePlayedTimeOpcode(WorldPacket & recv_data);
void HandleSetSheathedOpcode(WorldPacket & recv_data);
void HandleCompleteCinematic(WorldPacket & recv_data);
void HandleInspectOpcode( WorldPacket & recv_data );
/// Gm Ticket System in GMTicket.cpp:
void HandleGMTicketCreateOpcode(WorldPacket& recvPacket);
void HandleGMTicketUpdateOpcode(WorldPacket& recvPacket);
void HandleGMTicketDeleteOpcode(WorldPacket& recvPacket);
void HandleGMTicketGetTicketOpcode(WorldPacket& recvPacket);
void HandleGMTicketSystemStatusOpcode(WorldPacket& recvPacket);
void HandleGMTicketToggleSystemStatusOpcode(WorldPacket& recvPacket);
/// Opcodes implemented in QueryHandler.cpp:
void HandleNameQueryOpcode(WorldPacket& recvPacket);
void HandleQueryTimeOpcode(WorldPacket& recvPacket);
void HandleCreatureQueryOpcode(WorldPacket& recvPacket);
void HandleGameObjectQueryOpcode(WorldPacket& recvPacket);
void HandleItemNameQueryOpcode( WorldPacket & recv_data );
void HandlePageTextQueryOpcode( WorldPacket & recv_data );
/// Opcodes implemented in MovementHandler.cpp
void HandleMoveWorldportAckOpcode( WorldPacket& recvPacket );
void HandleMovementOpcodes( WorldPacket& recvPacket );
void HandleMoveFallResetOpcode( WorldPacket & recvPacket);
void HandleMoveTimeSkippedOpcode( WorldPacket & recv_data );
void HandleMoveNotActiveMoverOpcode( WorldPacket & recv_data );
void HandleSetActiveMoverOpcode( WorldPacket & recv_data );
void HandleMoveTeleportAckOpcode( WorldPacket & recv_data );
/// Opcodes implemented in GroupHandler.cpp:
void HandleGroupInviteOpcode(WorldPacket& recvPacket);
void HandleGroupCancelOpcode(WorldPacket& recvPacket);
void HandleGroupAcceptOpcode(WorldPacket& recvPacket);
void HandleGroupDeclineOpcode(WorldPacket& recvPacket);
void HandleGroupUninviteOpcode(WorldPacket& recvPacket);
void HandleGroupUninviteGuildOpcode(WorldPacket& recvPacket);
void HandleGroupSetLeaderOpcode(WorldPacket& recvPacket);
void HandleGroupDisbandOpcode(WorldPacket& recvPacket);
void HandleLootMethodOpcode(WorldPacket& recvPacket);
void HandleMinimapPingOpcode(WorldPacket& recvPacket);
void HandleSetPlayerIconOpcode(WorldPacket& recv_data);
void SendPartyCommandResult(Player *pPlayer, uint32 p1, std::string name, uint32 err);
// Raid
void HandleConvertGroupToRaidOpcode(WorldPacket& recvPacket);
void HandleGroupChangeSubGroup(WorldPacket& recvPacket);
void HandleGroupAssistantLeader(WorldPacket& recvPacket);
void HandleRequestRaidInfoOpcode(WorldPacket& recvPacket);
void HandleReadyCheckOpcode(WorldPacket& recv_data);
void HandleGroupPromote(WorldPacket& recv_data);
// LFG opcodes
void HandleEnableAutoJoin(WorldPacket& recvPacket);
void HandleDisableAutoJoin(WorldPacket& recvPacket);
void HandleEnableAutoAddMembers(WorldPacket& recvPacket);
void HandleDisableAutoAddMembers(WorldPacket& recvPacket);
void HandleSetLookingForGroupComment(WorldPacket& recvPacket);
void HandleMsgLookingForGroup(WorldPacket& recvPacket);
void HandleSetLookingForGroup(WorldPacket& recvPacket);
void HandleSetLookingForMore(WorldPacket& recvPacket);
void HandleSetLookingForNone(WorldPacket& recvPacket);
void HandleLfgClear(WorldPacket & recvPacket);
void HandleLfgInviteAccept(WorldPacket & recvPacket);
void HandleLfgInviteDeny(WorldPacket & recvPacket);
/// Taxi opcodes (TaxiHandler.cpp)
void HandleTaxiNodeStatusQueryOpcode(WorldPacket& recvPacket);
void HandleTaxiQueryAvaibleNodesOpcode(WorldPacket& recvPacket);
void HandleActivateTaxiOpcode(WorldPacket& recvPacket);
void HandleMultipleActivateTaxiOpcode(WorldPacket & recvPacket);
/// NPC opcodes (NPCHandler.cpp)
void HandleTabardVendorActivateOpcode(WorldPacket& recvPacket);
void HandleBankerActivateOpcode(WorldPacket& recvPacket);
void HandleBuyBankSlotOpcode(WorldPacket& recvPacket);
void HandleTrainerListOpcode(WorldPacket& recvPacket);
void HandleTrainerBuySpellOpcode(WorldPacket& recvPacket);
void HandleCharterShowListOpcode(WorldPacket& recvPacket);
void HandleGossipHelloOpcode(WorldPacket& recvPacket);
void HandleGossipSelectOptionOpcode(WorldPacket& recvPacket);
void HandleSpiritHealerActivateOpcode(WorldPacket& recvPacket);
void HandleNpcTextQueryOpcode(WorldPacket& recvPacket);
void HandleBinderActivateOpcode(WorldPacket& recvPacket);
// Auction House opcodes
void HandleAuctionHelloOpcode(WorldPacket& recvPacket);
void HandleAuctionListItems( WorldPacket & recv_data );
void HandleAuctionListBidderItems( WorldPacket & recv_data );
void HandleAuctionSellItem( WorldPacket & recv_data );
void HandleAuctionListOwnerItems( WorldPacket & recv_data );
void HandleAuctionPlaceBid( WorldPacket & recv_data );
void HandleCancelAuction( WorldPacket & recv_data);
// Mail opcodes
void HandleGetMail( WorldPacket & recv_data );
void HandleSendMail( WorldPacket & recv_data );
void HandleTakeMoney( WorldPacket & recv_data );
void HandleTakeItem( WorldPacket & recv_data );
void HandleMarkAsRead( WorldPacket & recv_data );
void HandleReturnToSender( WorldPacket & recv_data );
void HandleMailDelete( WorldPacket & recv_data );
void HandleItemTextQuery( WorldPacket & recv_data);
void HandleMailTime(WorldPacket & recv_data);
void HandleMailCreateTextItem(WorldPacket & recv_data );
/// Item opcodes (ItemHandler.cpp)
void HandleSwapInvItemOpcode(WorldPacket& recvPacket);
void HandleSwapItemOpcode(WorldPacket& recvPacket);
void HandleDestroyItemOpcode(WorldPacket& recvPacket);
void HandleAutoEquipItemOpcode(WorldPacket& recvPacket);
void HandleItemQuerySingleOpcode(WorldPacket& recvPacket);
void HandleSellItemOpcode(WorldPacket& recvPacket);
void HandleBuyItemInSlotOpcode(WorldPacket& recvPacket);
void HandleBuyItemOpcode(WorldPacket& recvPacket);
void HandleListInventoryOpcode(WorldPacket& recvPacket);
void HandleAutoStoreBagItemOpcode(WorldPacket& recvPacket);
void HandleBuyBackOpcode(WorldPacket& recvPacket);
void HandleSplitOpcode(WorldPacket& recvPacket);
void HandleReadItemOpcode(WorldPacket& recvPacket);
void HandleRepairItemOpcode(WorldPacket &recvPacket);
void HandleAutoBankItemOpcode(WorldPacket &recvPacket);
void HandleAutoStoreBankItemOpcode(WorldPacket &recvPacket);
void HandleCancelTemporaryEnchantmentOpcode(WorldPacket &recvPacket);
void HandleInsertGemOpcode(WorldPacket &recvPacket);
/// Combat opcodes (CombatHandler.cpp)
void HandleAttackSwingOpcode(WorldPacket& recvPacket);
void HandleAttackStopOpcode(WorldPacket& recvPacket);
/// Spell opcodes (SpellHandler.cpp)
void HandleUseItemOpcode(WorldPacket& recvPacket);
void HandleCastSpellOpcode(WorldPacket& recvPacket);
void HandleCancelCastOpcode(WorldPacket& recvPacket);
void HandleCancelAuraOpcode(WorldPacket& recvPacket);
void HandleCancelChannellingOpcode(WorldPacket& recvPacket);
void HandleCancelAutoRepeatSpellOpcode(WorldPacket& recv_data);
void HandleAddDynamicTargetOpcode(WorldPacket & recvPacket);
/// Skill opcodes (SkillHandler.spp)
//void HandleSkillLevelUpOpcode(WorldPacket& recvPacket);
void HandleLearnTalentOpcode(WorldPacket& recvPacket);
void HandleUnlearnTalents( WorldPacket & recv_data );
/// Quest opcodes (QuestHandler.cpp)
void HandleQuestgiverStatusQueryOpcode(WorldPacket& recvPacket);
void HandleQuestgiverHelloOpcode(WorldPacket& recvPacket);
void HandleQuestgiverAcceptQuestOpcode(WorldPacket& recvPacket);
void HandleQuestgiverCancelOpcode(WorldPacket& recvPacket);
void HandleQuestgiverChooseRewardOpcode(WorldPacket& recvPacket);
void HandleQuestgiverRequestRewardOpcode(WorldPacket& recvPacket);
void HandleQuestGiverQueryQuestOpcode( WorldPacket& recvPacket );
void HandleQuestQueryOpcode(WorldPacket& recvPacket);
void HandleQuestgiverCompleteQuestOpcode( WorldPacket & recvPacket );
void HandleQuestlogRemoveQuestOpcode(WorldPacket& recvPacket);
void HandlePushQuestToPartyOpcode(WorldPacket &recvPacket);
void HandleQuestPushResult(WorldPacket &recvPacket);
/// Chat opcodes (Chat.cpp)
void HandleMessagechatOpcode(WorldPacket& recvPacket);
void HandleTextEmoteOpcode(WorldPacket& recvPacket);
void HandleReportSpamOpcode(WorldPacket& recvPacket);
/// Corpse opcodes (Corpse.cpp)
void HandleCorpseReclaimOpcode( WorldPacket& recvPacket );
void HandleCorpseQueryOpcode( WorldPacket& recvPacket );
void HandleResurrectResponseOpcode(WorldPacket& recvPacket);
/// Channel Opcodes (ChannelHandler.cpp)
void HandleChannelJoin(WorldPacket& recvPacket);
void HandleChannelLeave(WorldPacket& recvPacket);
void HandleChannelList(WorldPacket& recvPacket);
void HandleChannelPassword(WorldPacket& recvPacket);
void HandleChannelSetOwner(WorldPacket& recvPacket);
void HandleChannelOwner(WorldPacket& recvPacket);
void HandleChannelModerator(WorldPacket& recvPacket);
void HandleChannelUnmoderator(WorldPacket& recvPacket);
void HandleChannelMute(WorldPacket& recvPacket);
void HandleChannelUnmute(WorldPacket& recvPacket);
void HandleChannelInvite(WorldPacket& recvPacket);
void HandleChannelKick(WorldPacket& recvPacket);
void HandleChannelBan(WorldPacket& recvPacket);
void HandleChannelUnban(WorldPacket& recvPacket);
void HandleChannelAnnounce(WorldPacket& recvPacket);
void HandleChannelModerate(WorldPacket& recvPacket);
void HandleChannelNumMembersQuery(WorldPacket & recvPacket);
void HandleChannelRosterQuery(WorldPacket & recvPacket);
// Duel
void HandleDuelAccepted(WorldPacket & recv_data);
void HandleDuelCancelled(WorldPacket & recv_data);
// Trade
void HandleInitiateTrade(WorldPacket & recv_data);
void HandleBeginTrade(WorldPacket & recv_data);
void HandleBusyTrade(WorldPacket & recv_data);
void HandleIgnoreTrade(WorldPacket & recv_data);
void HandleAcceptTrade(WorldPacket & recv_data);
void HandleUnacceptTrade(WorldPacket & recv_data);
void HandleCancelTrade(WorldPacket & recv_data);
void HandleSetTradeItem(WorldPacket & recv_data);
void HandleClearTradeItem(WorldPacket & recv_data);
void HandleSetTradeGold(WorldPacket & recv_data);
// Guild
void HandleGuildQuery(WorldPacket & recv_data);
void HandleCreateGuild(WorldPacket & recv_data);
void HandleInviteToGuild(WorldPacket & recv_data);
void HandleGuildAccept(WorldPacket & recv_data);
void HandleGuildDecline(WorldPacket & recv_data);
void HandleGuildInfo(WorldPacket & recv_data);
void HandleGuildRoster(WorldPacket & recv_data);
void HandleGuildPromote(WorldPacket & recv_data);
void HandleGuildDemote(WorldPacket & recv_data);
void HandleGuildLeave(WorldPacket & recv_data);
void HandleGuildRemove(WorldPacket & recv_data);
void HandleGuildDisband(WorldPacket & recv_data);
void HandleGuildLeader(WorldPacket & recv_data);
void HandleGuildMotd(WorldPacket & recv_data);
void HandleGuildRank(WorldPacket & recv_data);
void HandleGuildAddRank(WorldPacket & recv_data);
void HandleGuildDelRank(WorldPacket & recv_data);
void HandleGuildSetPublicNote(WorldPacket & recv_data);
void HandleGuildSetOfficerNote(WorldPacket & recv_data);
void HandleSaveGuildEmblem(WorldPacket & recv_data);
void HandleCharterBuy(WorldPacket & recv_data);
void HandleCharterShowSignatures(WorldPacket & recv_data);
void HandleCharterTurnInCharter(WorldPacket & recv_data);
void HandleCharterQuery(WorldPacket & recv_data);
void HandleCharterOffer(WorldPacket & recv_data);
void HandleCharterSign(WorldPacket &recv_data);
void HandleCharterRename(WorldPacket & recv_data);
void HandleSetGuildInformation(WorldPacket & recv_data);
void HandleGuildLog(WorldPacket & recv_data);
void HandleGuildBankViewTab(WorldPacket & recv_data);
void HandleGuildBankViewLog(WorldPacket & recv_data);
void HandleGuildBankOpenVault(WorldPacket & recv_data);
void HandleGuildBankBuyTab(WorldPacket & recv_data);
void HandleGuildBankDepositMoney(WorldPacket & recv_data);
void HandleGuildBankWithdrawMoney(WorldPacket & recv_data);
void HandleGuildBankDepositItem(WorldPacket & recv_data);
void HandleGuildBankWithdrawItem(WorldPacket & recv_data);
void HandleGuildBankGetAvailableAmount(WorldPacket & recv_data);
void HandleGuildBankModifyTab(WorldPacket & recv_data);
void HandleGuildGetFullPermissions(WorldPacket & recv_data);
// Pet
void HandlePetAction(WorldPacket & recv_data);
void HandlePetInfo(WorldPacket & recv_data);
void HandlePetNameQuery(WorldPacket & recv_data);
void HandleBuyStableSlot(WorldPacket & recv_data);
void HandleStablePet(WorldPacket & recv_data);
void HandleUnstablePet(WorldPacket & recv_data);
void HandleStabledPetList(WorldPacket & recv_data);
void HandleStableSwapPet(WorldPacket & recv_data);
void HandlePetRename(WorldPacket & recv_data);
void HandlePetAbandon(WorldPacket & recv_data);
void HandlePetUnlearn(WorldPacket & recv_data);
// Battleground
void HandleBattlefieldPortOpcode(WorldPacket &recv_data);
void HandleBattlefieldStatusOpcode(WorldPacket &recv_data);
void HandleBattleMasterHelloOpcode(WorldPacket &recv_data);
void HandleLeaveBattlefieldOpcode(WorldPacket &recv_data);
void HandleAreaSpiritHealerQueryOpcode(WorldPacket &recv_data);
void HandleAreaSpiritHealerQueueOpcode(WorldPacket &recv_data);
void HandleBattlegroundPlayerPositionsOpcode(WorldPacket &recv_data);
void HandleArenaJoinOpcode(WorldPacket &recv_data);
void HandleBattleMasterJoinOpcode(WorldPacket &recv_data);
void HandleInspectHonorStatsOpcode(WorldPacket &recv_data);
void HandlePVPLogDataOpcode(WorldPacket &recv_data);
void HandleBattlefieldListOpcode(WorldPacket &recv_data);
void HandleSetActionBarTogglesOpcode(WorldPacket &recvPacket);
void HandleMoveSplineCompleteOpcode(WorldPacket &recvPacket);
/// Helper functions
void SetNpcFlagsForTalkToQuest(const uint64& guid, const uint64& targetGuid);
//Tutorials
void HandleTutorialFlag ( WorldPacket & recv_data );
void HandleTutorialClear( WorldPacket & recv_data );
void HandleTutorialReset( WorldPacket & recv_data );
//Acknowledgements
void HandleAcknowledgementOpcodes( WorldPacket & recv_data );
void HandleMountSpecialAnimOpcode(WorldPacket& recv_data);
void HandleSelfResurrectOpcode(WorldPacket& recv_data);
void HandleUnlearnSkillOpcode(WorldPacket &recv_data);
void HandleRandomRollOpcode(WorldPacket &recv_data);
void HandleOpenItemOpcode(WorldPacket &recv_data);
void HandleToggleHelmOpcode(WorldPacket &recv_data);
void HandleToggleCloakOpcode(WorldPacket &recv_data);
void HandleSetVisibleRankOpcode(WorldPacket& recv_data);
void HandlePetSetActionOpcode(WorldPacket& recv_data);
//instances
void HandleResetInstanceOpcode(WorldPacket& recv_data);
void HandleDungeonDifficultyOpcode(WorldPacket& recv_data);
uint8 TrainerGetSpellStatus(TrainerSpell* pSpell);
void SendMailError(uint32 error);
void HandleCharRenameOpcode(WorldPacket & recv_data);
void HandlePartyMemberStatsOpcode(WorldPacket & recv_data);
void HandleSummonResponseOpcode(WorldPacket & recv_data);
void HandleArenaTeamAddMemberOpcode(WorldPacket & recv_data);
void HandleArenaTeamRemoveMemberOpcode(WorldPacket & recv_data);
void HandleArenaTeamInviteAcceptOpcode(WorldPacket & recv_data);
void HandleArenaTeamInviteDenyOpcode(WorldPacket & recv_data);
void HandleArenaTeamLeaveOpcode(WorldPacket & recv_data);
void HandleArenaTeamDisbandOpcode(WorldPacket & recv_data);
void HandleArenaTeamPromoteOpcode(WorldPacket & recv_data);
void HandleArenaTeamQueryOpcode(WorldPacket & recv_data);
void HandleArenaTeamRosterOpcode(WorldPacket & recv_data);
void HandleInspectArenaStatsOpcode(WorldPacket & recv_data);
void HandleTeleportCheatOpcode(WorldPacket & recv_data);
void HandleTeleportToUnitOpcode(WorldPacket & recv_data);
void HandleWorldportOpcode(WorldPacket & recv_data);
void HandleWrapItemOpcode(WorldPacket& recv_data);
// VOICECHAT
void HandleEnableMicrophoneOpcode(WorldPacket & recv_data);
void HandleVoiceChatQueryOpcode(WorldPacket & recv_data);
void HandleChannelVoiceQueryOpcode(WorldPacket & recv_data);
void HandleSetAutoLootPassOpcode(WorldPacket & recv_data);
void HandleSetFriendNote(WorldPacket & recv_data);
void Handle38C(WorldPacket & recv_data);
void HandleInrangeQuestgiverQuery(WorldPacket & recv_data);
public:
void SendInventoryList(Creature* pCreature);
void SendTrainerList(Creature* pCreature);
void SendCharterRequest(Creature* pCreature);
void SendTaxiList(Creature* pCreature);
void SendInnkeeperBind(Creature* pCreature);
void SendBattlegroundList(Creature* pCreature, uint32 mapid);
void SendBankerList(Creature* pCreature);
void SendTabardHelp(Creature* pCreature);
void SendAuctionList(Creature* pCreature);
void SendSpiritHealerRequest(Creature* pCreature);
void FullLogin(Player * plr);
float m_wLevel; // Level of water the player is currently in
bool m_bIsWLevelSet; // Does the m_wLevel variable contain up-to-date information about water level?
MovementInfo* GetMovementInfo() { return &movement_info; }
private:
friend class Player;
Player *_player;
WorldSocket *_socket;
/* Preallocated buffers for movement handlers */
MovementInfo movement_info;
uint8 movement_packet[90];
uint32 _accountId;
uint32 _accountFlags;
string _accountName;
int8 _side;
WoWGuid m_MoverWoWGuid;
uint32 _logoutTime; // time we received a logout request -- wait 20 seconds, and quit
AccountDataEntry sAccountData[8];
FastQueue<WorldPacket*, Mutex> _recvQueue;
char *permissions;
int permissioncount;
bool _loggingOut;
uint32 _latency;
uint32 client_build;
uint32 instanceId;
uint8 _updatecount;
public:
static void InitPacketHandlerTable();
uint32 floodLines;
time_t floodTime;
void SystemMessage(const char * format, ...);
uint32 language;
WorldPacket* BuildQuestQueryResponse(Quest *qst);
uint32 m_muted;
uint32 m_lastEnumTime;
uint32 m_lastWhoTime;
protected:
uint32 m_repeatTime;
string m_repeatMessage;
uint32 m_repeatEmoteTime;
uint32 m_repeatEmoteId;
};
typedef std::set<WorldSession*> SessionSet;
#endif
| [
"[email protected]"
] | |
623b36e0e79a55965c95f5ff357a9f5fbd77d183 | d3affeadad9619cda35d5cd8674e503be203ac29 | /finalproject/src/hw_soln/fire_module/solution1/syn/systemc/FIFO_fire2_matrix_e3x3_stream_o_42_V.h | efda33f8fe24fa5e2d2fec4d71a8047efc795cd6 | [] | no_license | chl218/FPGA-for-Computer-Vision | 800c98ebf6df4d8ec1818698d401f88dd448fe79 | 9ccad894bf7ac59d9f4c33afcd385ea3f47bf938 | refs/heads/master | 2021-01-20T02:42:47.126346 | 2017-05-02T05:07:10 | 2017-05-02T05:07:10 | 89,445,626 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,829 | h | // ==============================================================
// File generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC
// Version: 2015.4
// Copyright (C) 2015 Xilinx Inc. All rights reserved.
//
// ==============================================================
#ifndef FIFO_fire2_matrix_e3x3_stream_o_42_V_HH_
#define FIFO_fire2_matrix_e3x3_stream_o_42_V_HH_
#include <systemc>
using namespace std;
SC_MODULE(FIFO_fire2_matrix_e3x3_stream_o_42_V) {
static const unsigned int DATA_WIDTH = 32;
static const unsigned int ADDR_WIDTH = 1;
static const unsigned int FIFO_fire2_matrix_e3x3_stream_o_42_V_depth = 2;
sc_core::sc_in_clk clk;
sc_core::sc_in< sc_dt::sc_logic > reset;
sc_core::sc_out< sc_dt::sc_logic > if_empty_n;
sc_core::sc_in< sc_dt::sc_logic > if_read_ce;
sc_core::sc_in< sc_dt::sc_logic > if_read;
sc_core::sc_out< sc_dt::sc_lv<DATA_WIDTH> > if_dout;
sc_core::sc_out< sc_dt::sc_logic > if_full_n;
sc_core::sc_in< sc_dt::sc_logic > if_write_ce;
sc_core::sc_in< sc_dt::sc_logic > if_write;
sc_core::sc_in< sc_dt::sc_lv<DATA_WIDTH> > if_din;
sc_core::sc_signal< sc_dt::sc_logic > internal_empty_n;
sc_core::sc_signal< sc_dt::sc_logic > internal_full_n;
sc_core::sc_signal< sc_dt::sc_lv<DATA_WIDTH> > mStorage[FIFO_fire2_matrix_e3x3_stream_o_42_V_depth];
sc_core::sc_signal< sc_dt::sc_uint<ADDR_WIDTH> > mInPtr;
sc_core::sc_signal< sc_dt::sc_uint<ADDR_WIDTH> > mOutPtr;
sc_core::sc_signal< sc_dt::sc_uint<1> > mFlag_nEF_hint;
sc_core::sc_trace_file* mTrace;
SC_CTOR(FIFO_fire2_matrix_e3x3_stream_o_42_V) : mTrace(0) {
const char* dump_vcd = std::getenv("AP_WRITE_VCD");
if (dump_vcd && string(dump_vcd) == "1") {
std::string tracefn = "sc_trace_" + std::string(name());
mTrace = sc_core::sc_create_vcd_trace_file( tracefn.c_str());
sc_trace(mTrace, clk, "(port)clk");
sc_trace(mTrace, reset, "(port)reset");
sc_trace(mTrace, if_full_n, "(port)if_full_n");
sc_trace(mTrace, if_write_ce, "(port)if_write_ce");
sc_trace(mTrace, if_write, "(port)if_write");
sc_trace(mTrace, if_din, "(port)if_din");
sc_trace(mTrace, if_empty_n, "(port)if_empty_n");
sc_trace(mTrace, if_read_ce, "(port)if_read_ce");
sc_trace(mTrace, if_read, "(port)if_read");
sc_trace(mTrace, if_dout, "(port)if_dout");
sc_trace(mTrace, mInPtr, "mInPtr");
sc_trace(mTrace, mOutPtr, "mOutPtr");
sc_trace(mTrace, mFlag_nEF_hint, "mFlag_nEF_hint");
}
mInPtr = 0;
mOutPtr = 0;
mFlag_nEF_hint = 0;
SC_METHOD(proc_read_write);
sensitive << clk.pos();
SC_METHOD(proc_dout);
sensitive << mOutPtr;
for (unsigned i = 0; i < FIFO_fire2_matrix_e3x3_stream_o_42_V_depth; i++) {
sensitive << mStorage[i];
}
SC_METHOD(proc_ptr);
sensitive << mInPtr << mOutPtr<< mFlag_nEF_hint;
SC_METHOD(proc_status);
sensitive << internal_empty_n << internal_full_n;
}
~FIFO_fire2_matrix_e3x3_stream_o_42_V() {
if (mTrace) sc_core::sc_close_vcd_trace_file(mTrace);
}
void proc_status() {
if_empty_n.write(internal_empty_n.read());
if_full_n.write(internal_full_n.read());
}
void proc_read_write() {
if (reset.read() == sc_dt::SC_LOGIC_1) {
mInPtr.write(0);
mOutPtr.write(0);
mFlag_nEF_hint.write(0);
}
else {
if (if_read_ce.read() == sc_dt::SC_LOGIC_1
&& if_read.read() == sc_dt::SC_LOGIC_1
&& internal_empty_n.read() == sc_dt::SC_LOGIC_1) {
sc_dt::sc_uint<ADDR_WIDTH> ptr;
if (mOutPtr.read().to_uint() == (FIFO_fire2_matrix_e3x3_stream_o_42_V_depth-1)) {
ptr = 0;
mFlag_nEF_hint.write(~mFlag_nEF_hint.read());
}
else {
ptr = mOutPtr.read();
ptr++;
}
assert(ptr.to_uint() < FIFO_fire2_matrix_e3x3_stream_o_42_V_depth);
mOutPtr.write(ptr);
}
if (if_write_ce.read() == sc_dt::SC_LOGIC_1
&& if_write.read() == sc_dt::SC_LOGIC_1
&& internal_full_n.read() == sc_dt::SC_LOGIC_1) {
sc_dt::sc_uint<ADDR_WIDTH> ptr;
ptr = mInPtr.read();
mStorage[ptr.to_uint()].write(if_din.read());
if (ptr.to_uint() == (FIFO_fire2_matrix_e3x3_stream_o_42_V_depth-1)) {
ptr = 0;
mFlag_nEF_hint.write(~mFlag_nEF_hint.read());
} else {
ptr++;
assert(ptr.to_uint() < FIFO_fire2_matrix_e3x3_stream_o_42_V_depth);
}
mInPtr.write(ptr);
}
}
}
void proc_dout() {
sc_dt::sc_uint<ADDR_WIDTH> ptr = mOutPtr.read();
if (ptr.to_uint() > FIFO_fire2_matrix_e3x3_stream_o_42_V_depth) {
if_dout.write(sc_dt::sc_lv<DATA_WIDTH>());
}
else {
if_dout.write(mStorage[ptr.to_uint()]);
}
}
void proc_ptr() {
if (mInPtr.read() == mOutPtr.read() && mFlag_nEF_hint.read().to_uint()==0) {
internal_empty_n.write(sc_dt::SC_LOGIC_0);
}
else {
internal_empty_n.write(sc_dt::SC_LOGIC_1);
}
if (mInPtr.read() == mOutPtr.read() && mFlag_nEF_hint.read().to_uint()==1) {
internal_full_n.write(sc_dt::SC_LOGIC_0);
}
else {
internal_full_n.write(sc_dt::SC_LOGIC_1);
}
}
};
#endif //FIFO_fire2_matrix_e3x3_stream_o_42_V_HH_
| [
"[email protected]"
] | |
0a563fe2314dda9e66f47b4bca7c0f6ae5827105 | 0a1e349daa9116b3c50b39f62413ee6ea21110f3 | /Lab2/print-interval.cpp | 3ae49159d8f8bf76e17a15920b38237ec64d01c2 | [] | no_license | TalhaR/CSCI-135 | d1b06046ffa841eeeb3f35f71bf6574952de93fd | 8cfc5e9af41609a3b0db0b8bd1634aaf0454bdf1 | refs/heads/master | 2022-01-13T07:39:31.980674 | 2019-05-06T22:11:04 | 2019-05-06T22:11:04 | 168,868,149 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 461 | cpp | #include <iostream>
using namespace std;
/*
Author: Talha Rahman
Course: CSCI-136
Instructor: Minh Nguyen
Assignment: Lab 2B
*/
// The program will ask the user for two integers
// and will print all the integers between that range (L <= i < U)
// seperated by spaces
int main() {
int L, U;
cout << "Please enter L: ";
cin >> L;
cout << "\nPlease enter U: ";
cin >> U;
for (int i = L; i < U; i++){
cout << i << " ";
}
} | [
"[email protected]"
] | |
1fd2a44f7bdd8efd56263a6968234dfa429bfbda | eab4884c3bb0f91cd897bb79857b400c9ddd4277 | /백준알고리즘/BOJ - 14501 퇴사.cpp | 3aab70f611f7639b73ab49cd540a2d6527786267 | [] | no_license | RobPang/Algorithm_study | bc4dc9f5387278c3430d32285a7781d42bdae16d | 8eba5e10eacf42d02522f34d6f9fe65778a5c2db | refs/heads/master | 2023-08-24T06:07:50.473812 | 2021-10-22T12:09:24 | 2021-10-22T12:09:24 | 388,168,710 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 457 | cpp | //퇴사 - dp
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int dp[21];
int t[17];
int p[17];
int n;
int bigger(int a, int b) { if (a > b) return a; return b; }
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> t[i];
cin >> p[i];
}
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= n; i++) {
dp[i + 1] = max(dp[i], dp[i + 1]);
dp[i+t[i]] = max(dp[i + t[i]], dp[i] + p[i]);
}
cout << dp[n+1];
}
| [
"[email protected]"
] | |
e8726a2596889562452ccc79f342e5d4c5d0c593 | c7075168b69d50d75f74569f32b876c79c2fda55 | /VulkanRender/HelloTriangleApplication/main.cpp | e76fca26d57bc264ce846135d04341d1e141ff08 | [] | no_license | EvgenBuiko/VulkanRender | 964b59fed1114ca136edb740cf6a5cff7b6a009d | 8939f07411e342821220ddf287f9d351e67fded7 | refs/heads/master | 2021-08-28T10:32:31.571441 | 2021-08-21T08:14:24 | 2021-08-21T08:14:24 | 237,952,444 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 364 | cpp | #pragma once
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#pragma once
#include "TriangleApp.h"
#include <iostream>
#include <stdexcept>
#include <functional>
#include <cstdlib>
int main()
{
TriangleApp app;
try { app.run(); }
catch (const std::exception & e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} | [
"[email protected]"
] | |
f1e6d1049112b9011c2938e677101b87fe6d3127 | 8bd30da01c1f22f9c360153311b429b7ce65980b | /PortSIPUC/include/ICUC4/unicode/measfmt.h | 4b748fea94aadfa7ed5b34c31625621088569d9e | [
"BSD-2-Clause"
] | permissive | jiaojian8063868/portsip-softphone-windows | 33adf93c21b97a684219d4cc3bf5cad3ea14b008 | df1b6391ff5d074cbc98cb559e52b181ef8e1b17 | refs/heads/master | 2022-11-19T20:22:40.519351 | 2020-07-24T04:06:23 | 2020-07-24T04:06:23 | 282,122,371 | 1 | 2 | BSD-2-Clause | 2020-07-24T04:26:24 | 2020-07-24T04:26:23 | null | UTF-8 | C++ | false | false | 12,108 | h | // © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (c) 2004-2016, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* Author: Alan Liu
* Created: April 20, 2004
* Since: ICU 3.0
**********************************************************************
*/
#ifndef MEASUREFORMAT_H
#define MEASUREFORMAT_H
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/format.h"
#include "unicode/udat.h"
/**
* \file
* \brief C++ API: Compatibility APIs for measure formatting.
*/
/**
* Constants for various widths.
* There are 4 widths: Wide, Short, Narrow, Numeric.
* For example, for English, when formatting "3 hours"
* Wide is "3 hours"; short is "3 hrs"; narrow is "3h";
* formatting "3 hours 17 minutes" as numeric give "3:17"
* @stable ICU 53
*/
enum UMeasureFormatWidth {
// Wide, short, and narrow must be first and in this order.
/**
* Spell out measure units.
* @stable ICU 53
*/
UMEASFMT_WIDTH_WIDE,
/**
* Abbreviate measure units.
* @stable ICU 53
*/
UMEASFMT_WIDTH_SHORT,
/**
* Use symbols for measure units when possible.
* @stable ICU 53
*/
UMEASFMT_WIDTH_NARROW,
/**
* Completely omit measure units when possible. For example, format
* '5 hours, 37 minutes' as '5:37'
* @stable ICU 53
*/
UMEASFMT_WIDTH_NUMERIC,
#ifndef U_HIDE_DEPRECATED_API
/**
* One more than the highest normal UMeasureFormatWidth value.
* @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
*/
UMEASFMT_WIDTH_COUNT = 4
#endif // U_HIDE_DEPRECATED_API
};
/** @stable ICU 53 */
typedef enum UMeasureFormatWidth UMeasureFormatWidth;
U_NAMESPACE_BEGIN
class Measure;
class MeasureUnit;
class NumberFormat;
class PluralRules;
class MeasureFormatCacheData;
class SharedNumberFormat;
class SharedPluralRules;
class QuantityFormatter;
class SimpleFormatter;
class ListFormatter;
class DateFormat;
/**
* <p><strong>IMPORTANT:</strong> New users are strongly encouraged to see if
* numberformatter.h fits their use case. Although not deprecated, this header
* is provided for backwards compatibility only.
*
* @see Format
* @author Alan Liu
* @stable ICU 3.0
*/
class U_I18N_API MeasureFormat : public Format {
public:
using Format::parseObject;
using Format::format;
/**
* Constructor.
* <p>
* <strong>NOTE:</strong> New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @stable ICU 53
*/
MeasureFormat(
const Locale &locale, UMeasureFormatWidth width, UErrorCode &status);
/**
* Constructor.
* <p>
* <strong>NOTE:</strong> New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @stable ICU 53
*/
MeasureFormat(
const Locale &locale,
UMeasureFormatWidth width,
NumberFormat *nfToAdopt,
UErrorCode &status);
/**
* Copy constructor.
* @stable ICU 3.0
*/
MeasureFormat(const MeasureFormat &other);
/**
* Assignment operator.
* @stable ICU 3.0
*/
MeasureFormat &operator=(const MeasureFormat &rhs);
/**
* Destructor.
* @stable ICU 3.0
*/
virtual ~MeasureFormat();
/**
* Return true if given Format objects are semantically equal.
* @stable ICU 53
*/
virtual UBool operator==(const Format &other) const;
/**
* Clones this object polymorphically.
* @stable ICU 53
*/
virtual Format *clone() const;
/**
* Formats object to produce a string.
* @stable ICU 53
*/
virtual UnicodeString &format(
const Formattable &obj,
UnicodeString &appendTo,
FieldPosition &pos,
UErrorCode &status) const;
/**
* Parse a string to produce an object. This implementation sets
* status to U_UNSUPPORTED_ERROR.
*
* @draft ICU 53
*/
virtual void parseObject(
const UnicodeString &source,
Formattable &reslt,
ParsePosition &pos) const;
/**
* Formats measure objects to produce a string. An example of such a
* formatted string is 3 meters, 3.5 centimeters. Measure objects appear
* in the formatted string in the same order they appear in the "measures"
* array. The NumberFormat of this object is used only to format the amount
* of the very last measure. The other amounts are formatted with zero
* decimal places while rounding toward zero.
* @param measures array of measure objects.
* @param measureCount the number of measure objects.
* @param appendTo formatted string appended here.
* @param pos the field position.
* @param status the error.
* @return appendTo reference
*
* @stable ICU 53
*/
UnicodeString &formatMeasures(
const Measure *measures,
int32_t measureCount,
UnicodeString &appendTo,
FieldPosition &pos,
UErrorCode &status) const;
/**
* Formats a single measure per unit. An example of such a
* formatted string is 3.5 meters per second.
* @param measure The measure object. In above example, 3.5 meters.
* @param perUnit The per unit. In above example, it is
* `*%MeasureUnit::createSecond(status)`.
* @param appendTo formatted string appended here.
* @param pos the field position.
* @param status the error.
* @return appendTo reference
*
* @stable ICU 55
*/
UnicodeString &formatMeasurePerUnit(
const Measure &measure,
const MeasureUnit &perUnit,
UnicodeString &appendTo,
FieldPosition &pos,
UErrorCode &status) const;
/**
* Gets the display name of the specified {@link MeasureUnit} corresponding to the current
* locale and format width.
* @param unit The unit for which to get a display name.
* @param status the error.
* @return The display name in the locale and width specified in
* the MeasureFormat constructor, or null if there is no display name available
* for the specified unit.
*
* @stable ICU 58
*/
UnicodeString getUnitDisplayName(const MeasureUnit& unit, UErrorCode &status) const;
/**
* Return a formatter for CurrencyAmount objects in the given
* locale.
* <p>
* <strong>NOTE:</strong> New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @param locale desired locale
* @param ec input-output error code
* @return a formatter object, or NULL upon error
* @stable ICU 3.0
*/
static MeasureFormat* U_EXPORT2 createCurrencyFormat(const Locale& locale,
UErrorCode& ec);
/**
* Return a formatter for CurrencyAmount objects in the default
* locale.
* <p>
* <strong>NOTE:</strong> New users are strongly encouraged to use
* {@link icu::number::NumberFormatter} instead of NumberFormat.
* @param ec input-output error code
* @return a formatter object, or NULL upon error
* @stable ICU 3.0
*/
static MeasureFormat* U_EXPORT2 createCurrencyFormat(UErrorCode& ec);
/**
* Return the class ID for this class. This is useful only for comparing to
* a return value from getDynamicClassID(). For example:
* <pre>
* . Base* polymorphic_pointer = createPolymorphicObject();
* . if (polymorphic_pointer->getDynamicClassID() ==
* . erived::getStaticClassID()) ...
* </pre>
* @return The class ID for all objects of this class.
* @stable ICU 53
*/
static UClassID U_EXPORT2 getStaticClassID(void);
/**
* Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
* method is to implement a simple version of RTTI, since not all C++
* compilers support genuine RTTI. Polymorphic operator==() and clone()
* methods call this method.
*
* @return The class ID for this object. All objects of a
* given class have the same class ID. Objects of
* other classes have different class IDs.
* @stable ICU 53
*/
virtual UClassID getDynamicClassID(void) const;
protected:
/**
* Default constructor.
* @stable ICU 3.0
*/
MeasureFormat();
#ifndef U_HIDE_INTERNAL_API
/**
* ICU use only.
* Initialize or change MeasureFormat class from subclass.
* @internal.
*/
void initMeasureFormat(
const Locale &locale,
UMeasureFormatWidth width,
NumberFormat *nfToAdopt,
UErrorCode &status);
/**
* ICU use only.
* Allows subclass to change locale. Note that this method also changes
* the NumberFormat object. Returns TRUE if locale changed; FALSE if no
* change was made.
* @internal.
*/
UBool setMeasureFormatLocale(const Locale &locale, UErrorCode &status);
/**
* ICU use only.
* Let subclass change NumberFormat.
* @internal.
*/
void adoptNumberFormat(NumberFormat *nfToAdopt, UErrorCode &status);
/**
* ICU use only.
* @internal.
*/
const NumberFormat &getNumberFormatInternal() const;
/**
* ICU use only.
* Always returns the short form currency formatter.
* @internal.
*/
const NumberFormat& getCurrencyFormatInternal() const;
/**
* ICU use only.
* @internal.
*/
const PluralRules &getPluralRules() const;
/**
* ICU use only.
* @internal.
*/
Locale getLocale(UErrorCode &status) const;
/**
* ICU use only.
* @internal.
*/
const char *getLocaleID(UErrorCode &status) const;
#endif /* U_HIDE_INTERNAL_API */
private:
const MeasureFormatCacheData *cache;
const SharedNumberFormat *numberFormat;
const SharedPluralRules *pluralRules;
UMeasureFormatWidth fWidth;
// Declared outside of MeasureFormatSharedData because ListFormatter
// objects are relatively cheap to copy; therefore, they don't need to be
// shared across instances.
ListFormatter *listFormatter;
UnicodeString &formatMeasure(
const Measure &measure,
const NumberFormat &nf,
UnicodeString &appendTo,
FieldPosition &pos,
UErrorCode &status) const;
UnicodeString &formatMeasuresSlowTrack(
const Measure *measures,
int32_t measureCount,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode& status) const;
UnicodeString &formatNumeric(
const Formattable *hms, // always length 3: [0] is hour; [1] is
// minute; [2] is second.
int32_t bitMap, // 1=hour set, 2=minute set, 4=second set
UnicodeString &appendTo,
UErrorCode &status) const;
UnicodeString &formatNumeric(
UDate date,
const DateFormat &dateFmt,
UDateFormatField smallestField,
const Formattable &smallestAmount,
UnicodeString &appendTo,
UErrorCode &status) const;
};
U_NAMESPACE_END
#endif // #if !UCONFIG_NO_FORMATTING
#endif // #ifndef MEASUREFORMAT_H
| [
"[email protected]"
] | |
d13a180313150858488a14b34baad7dc003c88e5 | d6cb90d92ccaf361348a3174ca914f62e00a897a | /libseq64/src/calculations_helpers.cpp | 5ecb7e06aae7ec2b972cf61d2168e6667501dff2 | [] | no_license | ahlstromcj/seq64-tests | d12fd99d52846d73716d9321fa3c6ee39c85bc76 | d217d41af7baa01ef784f41035397e7a0be9656e | refs/heads/master | 2016-08-12T07:35:43.538553 | 2015-12-05T14:04:46 | 2015-12-05T14:04:46 | 43,853,914 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,805 | cpp | /**
* \file calculations_helpers.cpp
* \library libseq64 (from the Sequencer64 project)
* \author Chris Ahlstrom
* \date 2015-12-01
* \updates 2015-12-02
* \version $Revision$
* \license $XPC_SUITE_GPL_LICENSE$
*
* This application provides helper functions for the calculations module of
* the libseq64 library.
*
* We could leverage these tests better by making the complementary test at
* the same time. Save a lot of code. Also need super-tests that
* comprehensively survey the BPM, PPQN, W (beat-width), B (beats/measure)
* parameter space.
*/
#include <iostream> /* std::cout, std::endl */
#include "calculations_helpers.hpp" /* declares these helper functions */
/*
* Helper function to run a test of seq64::extract_timing_numbers()
*/
bool
extract_timing_numbers_test
(
const xpc::cut_options & options,
const std::string & test
)
{
std::string s1, s2, s3, s4;
bool result = seq64::extract_timing_numbers(test, s1, s2, s3, s4);
if (options.is_verbose())
{
std::cout
<< "Source = '" << test << "' --> "
<< "'" << s1 << "'; "
<< "'" << s2 << "'; "
<< "'" << s3 << "'; "
<< "'" << s4 << "'"
<< std::endl
;
}
if (result)
{
std::string target = s1;
target += ":";
target += s2;
target += ":";
target += s3;
target += s4;
result = target == test;
}
return result;
}
/**
* Helper function to run a test of seq64::timestring_to_pulses().
*/
bool
timestring_to_pulses_test
(
const xpc::cut_options & options,
const std::string & test,
seq64::midipulse target,
int BPM,
int PPQN
)
{
bool result = false;
seq64::midipulse p = seq64::timestring_to_pulses(test, BPM, PPQN);
if (options.is_verbose())
{
std::cout
<< "Source = '" << test << "' --> " << p << " pulses"
<< std::endl
;
}
result = p == target;
return result;
}
/**
* Helper function to run a test of seq64::pulses_to_timestring().
*/
bool
pulses_to_timestring_test
(
const xpc::cut_options & options,
seq64::midipulse test,
const std::string & target,
int BPM,
int PPQN,
bool show_settings
)
{
bool result = false;
std::string t = seq64::pulses_to_timestring(test, BPM, PPQN);
if (options.is_verbose())
{
if (show_settings)
std::cout << "BPM = " << BPM << "; PPQN = " << PPQN << std::endl;
std::cout
<< "Source = " << test << " pulses --> '"
<< t << "' time string" << std::endl
;
}
result = t == target;
return result;
}
/**
* Helper function to run a test of seq64::pulses_to_midi_measures().
*/
bool
pulses_to_midi_measures_test
(
const xpc::cut_options & options,
seq64::midipulse test,
const seq64::midi_measures & target,
const seq64::midi_timing & mtt,
bool show_settings
)
{
seq64::midi_measures results;
bool result = seq64::pulses_to_midi_measures(test, mtt, results);
if (options.is_verbose())
{
if (show_settings)
{
std::cout
<< "PPQN = " << mtt.ppqn()
<< "; beats/minute = " << mtt.beats_per_minute()
<< "; beats/measure = " << mtt.beats_per_measure()
<< "; beat width = " << mtt.beat_width()
<< std::endl
;
}
std::cout
<< "Source = " << test << " pulses --> '"
<< results.measures() << ":"
<< results.beats() << ":"
<< results.divisions() << "' MIDI measures:beats:divisions"
<< std::endl
;
}
if (result)
result = results.measures() == target.measures();
if (result)
result = results.beats() == target.beats();
if (result)
result = results.divisions() == target.divisions();
return result;
}
/**
* Helper function to run a test of seq64::pulses_to_measurestring().
*/
bool
pulses_to_measurestring_test
(
const xpc::cut_options & options,
seq64::midipulse test,
const std::string & target,
const seq64::midi_timing & mtt,
bool show_setting
)
{
std::string ms = seq64::pulses_to_measurestring(test, mtt);
bool result = ! ms.empty();
if (options.is_verbose())
{
if (show_setting)
{
std::cout
<< "PPQN = " << mtt.ppqn()
<< "; beats/minute = " << mtt.beats_per_minute()
<< "; beats/measure = " << mtt.beats_per_measure()
<< "; beat width = " << mtt.beat_width()
<< std::endl
;
}
std::cout
<< "Source = " << test << " pulses --> '"
<< ms << "' MIDI measures:beats:divisions"
<< std::endl
;
}
if (result)
result = ms == target;
return result;
}
/**
* Helper function to run a test of seq64::midi_measures_to_pulses().
*/
bool
midi_measures_to_pulses_test
(
const xpc::cut_options & options,
const seq64::midi_measures & test,
seq64::midipulse target,
const seq64::midi_timing & mtt,
bool show_settings
)
{
seq64::midipulse p = seq64::midi_measures_to_pulses(test, mtt);
bool result = p == target;
if (options.is_verbose())
{
if (show_settings)
{
std::cout
<< "PPQN = " << mtt.ppqn()
<< "; beats/minute = " << mtt.beats_per_minute()
<< "; beats/measure = " << mtt.beats_per_measure()
<< "; beat width = " << mtt.beat_width()
<< std::endl
;
}
std::cout
<< "Source = "
<< test.measures() << ":"
<< test.beats() << ":"
<< test.divisions() << " MIDI measures:beats:divisions -->"
<< p << " pulses"
<< std::endl
;
}
return result;
}
/**
* Helper function to run a test of seq64::measurestring_to_pulses().
*/
bool
measurestring_to_pulses_test
(
const xpc::cut_options & options,
const std::string & test,
seq64::midipulse target,
const seq64::midi_timing & mtt,
bool show_settings
)
{
seq64::midipulse p = seq64::measurestring_to_pulses(test, mtt);
bool result = p == target;
if (options.is_verbose())
{
if (show_settings)
{
std::cout
<< "PPQN = " << mtt.ppqn()
<< "; beats/minute = " << mtt.beats_per_minute()
<< "; beats/measure = " << mtt.beats_per_measure()
<< "; beat width = " << mtt.beat_width()
<< std::endl
;
}
std::cout
<< "Source = '" << test << "' MIDI measures:beats:divisions -->"
<< p << " pulses"
<< std::endl
;
}
return result;
}
/*
* calculations_helpers.cpp
*
* vim: ts=3 sw=3 et ft=cpp
*/
| [
"[email protected]"
] | |
668a7292c1d76dc8ea1f40e175ef2d5faae2527c | 6caa1ce523a14b610f861ab0e55d4fc285367107 | /orig_Source.cpp | 7a588f73f140b78b639f2598db8dd79fe51fd52d | [] | no_license | ornelasf1/binary-calculator | ebb257436ccef53bcbe0390b8954ac564ab01876 | 106a8da3b277cd73a32eae0d4a308aefe81bb98c | refs/heads/master | 2021-01-25T07:50:23.549499 | 2017-06-07T20:43:16 | 2017-06-07T20:43:16 | 93,677,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,021 | cpp | #include <iostream>
#include <cmath>
#include <string>
#include <new>
using namespace std;
void conv_to_bin(int base_ten_num);
void conv_to_int(string base_two_num);
void text_to_bin(string text);
void conv_to_bin(int base_ten_num){
int original_ten = base_ten_num;
int * binary_num; //Creates pointer for dynamic array binary_num
binary_num = new int[base_ten_num];
int count = 0;
while (base_ten_num > 0){ //while loop creates binary number but in incorrect reverse order.
int remainder = base_ten_num % 2;
base_ten_num /= 2;
binary_num[count] = remainder;
count++;
}
string binary_text = "";
for (int i = count; i >= 1; i--){ //for loop starts from 'count' and decreases, compares to 1 instead of 0 because array index
binary_text += to_string(binary_num[i-1]);
}
int setOffour = binary_text.length()%4; //Uses modulus to determine number of 0's it's off from being divisible by 4.
while (setOffour != 0){
binary_text.insert(0, 1, '0'); //Use .insert(int index, int iterations, char '0') to insert 0 into the string
setOffour = binary_text.length() % 4;
}
for (int i = binary_text.length(); i > 0; i-=4){ //Splits the binary number string into groups of 4.
binary_text.insert(i, 1, ' ');
}
cout << "Binary Representation of " << original_ten << " is " << binary_text << endl << endl;;
delete[] binary_num;
binary_num = NULL;
}
void conv_to_int(string base_two_num){
string original_two = base_two_num;
int power = 0;
int binvalue = 0;
for (int i = base_two_num.length(); i >= 1; i--){
if (base_two_num[i-1] == '1'){
char integer = base_two_num[i-1];
//Assigning an int to a char will provide it's ASCI number.
int value = integer-'/'; //ASCI number of integer after it was converted to int from char(49). 1(49)-/(47) = 2
binvalue = binvalue + pow(value, power);
}
power++;
}
cout << "The value " << original_two << " represents " << binvalue << endl << endl;
}
void text_to_bin(string text_bin){
int sizeofstr = text_bin.length();
string bin_of_text;
for (int i = 0; i < sizeofstr; i++){
cout << (int)text_bin[i] << endl;
}
}
int main(){
reset:
int choice;
int base_ten;
string base_two;
string text;
cout << "----------Binary Calculator----------" << endl
<< "[1] Convert base 10 to base 2." << endl
<< "[2] Convert base 2 to base 10." << endl
<< "[3] Quit program." << endl;
cin >> choice;
switch (choice){
case 1:
cout << "What number do you want converted to binary?" << endl;
cin >> base_ten;
conv_to_bin(base_ten);
goto reset;
case 2:
cout << "What binary set do you want converted to integer? (Only input 0's and 1's)" << endl;
cin >> base_two;
for (int i = 0; i < base_two.length(); i++){
if ((base_two[i] == '0') || (base_two[i] == '1')){
continue;
}
else{
cout << "Only 1's and 0's are allowed as input!" << endl;
goto reset;
}
}
conv_to_int(base_two);
goto reset;
case 3:
break;
default:
cout << "Invalid choice" << endl;
goto reset;
}
system("pause");
}
| [
"[email protected]"
] | |
b4a38315f1a736b0ceecc2b2d9a031865dab8154 | 981565926d9b718af5e8e64f3bb8d8206ded484e | /Src/Nao/Modules/MotionControl/MotionCombinator/LegMotionCombinator.h | 7594614c8b38bae315708f560c467ccde7b7ac23 | [] | no_license | TJArk-Robotics/TJArkCodeRelease2019 | 249a939484d2e31b00731ce6935fcfb0036e4a13 | 950a1b2d6114c01bd810ae4eeebbc89ea2fd5356 | refs/heads/master | 2020-12-18T11:20:09.878914 | 2020-01-21T14:22:28 | 2020-01-21T14:22:28 | 235,360,704 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,165 | h | #pragma once
#include "Representations/Infrastructure/JointAngles.h"
#include "Representations/MotionControl/WalkingEngineOutput.h"
#include "Tools/Module/Blackboard.h"
class LegMotionCombinatorBase
{
public:
/* REQUIRES */
const JointAngles &theJointAngles = Blackboard::getInstance().jointAngles;
const WalkingEngineOutput &theWalkingEngineOutput = Blackboard::getInstance().walkingEngineOutput;
const StiffnessSettings &theStiffnessSettings = Blackboard::getInstance().stiffnessSettings;
const LegMotionSelection &theLegMotionSelection = Blackboard::getInstance().legMotionSelection;
const StandLegRequest &theStandLegRequest = Blackboard::getInstance().standLegRequest;
const SpecialActionsOutput &theSpecialActionsOutput = Blackboard::getInstance().specialActionsOutput;
/* PROVIDES */
// LegJointRequest &_theLegMotionRequest = Blackboard::getInstance().legJointRequest;
};
class LegMotionCombinator : public LegMotionCombinatorBase
{
public:
JointAngles lastJointAngles;/**< The measured joint angles the last time when not interpolating. */
void update();
void update(LegJointRequest &legJointRequest);
}; | [
"[email protected]"
] | |
b165ac0b182fcb063646d50dd661e09263447499 | b5156cfa261dd8838af40bd479e0174172eb0042 | /main.cpp | a7d6085d8f1945f359e12e7d526c2e912a543584 | [] | no_license | ThanasisMatskidis/Data-Stractures | a60362b3b374d39156e238f97e20070005a7875a | b3f9eb92b5af7564233e1600917e1226fed4db3c | refs/heads/main | 2023-08-25T15:11:08.965951 | 2021-09-16T17:06:26 | 2021-09-16T17:06:26 | 407,247,667 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,530 | cpp | #include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <chrono>
#include "cmake-build-debug/minheap.h"
#include "cmake-build-debug/maxheap.h"
#include "cmake-build-debug/AVLtree.h"
#include "cmake-build-debug/hashtable.h"
using namespace std;
using namespace std::chrono;
int main() {
ifstream file("commands.txt"); //Άνοιγμα του αρχείου που περιέχει τις εντολές για διάβασμα.//
ofstream screen; //Άνοιγμα του αρχείου output, για εγγραφή, στο οποίο θα εμφανίσουμε τα αποτελέσματα.//
screen.open("output.txt");
if(file.is_open()){
string line;
minheap mnheap;
maxheap mxheap;
AVLtree AVL;
hashtable hash;
while(getline(file,line)){ //Ανάγνωση του αρχείου με τις εντολές γραμή προς γραμμή, όπου σε κάθε γραμμή ελέγχουμε ποια εντολή έχουμε.//
string c1="BUILD";
string c2="GETSIZE";
string c3="FINDMIN";
string c4="FINDMAX";
string c5="SEARCH";
string c6="INSERT";
string c7="DELETEMIN";
string c8="DELETEMAX";
string c9="DELETE";
string s1="MINHEAP";
string s2="MAXHEAP";
string s3="AVLTREE";
string s4="HASHTABLE";
if(strstr(line.c_str(),c1.c_str())){
int sum=0;
if(strstr(line.c_str(),s1.c_str())){
size_t pos=line.size();
string filename=line.substr(line.find_last_of(' ',pos)); //Παίρνουμε την τελευταία λέξη της γραμμής που διαβάστηκε σε μία μεταβλητή τύπου string.//
filename.erase(remove(filename.begin(),filename.end(),' '),filename.end()); //Αφαιρούμε από αυτήν τυχόν κενά.//
ifstream data; //Ανοίγουμε το αρχέιου που περιέχει τα δεδομένα για διάβασμα.//
data.open(filename);
if(data.is_open()){
string lines;
while(getline(data,lines)){ //Μετράμε πόσα δεδομένα υπάρχουν μετρώντας τις σειρές του αρχείου αφού κάθε δεδομένο καταλαμβάνει και μία σειρά.//
sum+=1;
}
mnheap.setNrOfEl(sum); //"Περνάμε" στην κλάση τον αριθμό των σειρών και κατ' επέκταση των δεδομένων.//
mnheap.setfile(filename);//"Περνάμε" στην κλάση το όνομα του αρχείου που περιέχει τα δεδομένα.//
auto start=high_resolution_clock::now();
mnheap.build(); //Συνάρτηση για το χτίσιμο του σωρού ελαχίστων.//
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
ifstream tempfile("temp.txt"); //Αντιγραφή των περιεχωμένων του αρχείου temp στο αρχείο output.//
string temp;
screen<<"MINHEAP: "<<endl;
while(tempfile.good()){
getline(tempfile,temp);
screen<<temp<<endl;
}
screen<<"Minheap build time: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else{
cout<<"ERROR! Can not find the data file.("<<line<<")"<<endl;
}
}
else if(strstr(line.c_str(),s2.c_str())){
size_t pos=line.size();
string filename=line.substr(line.find_last_of(' ',pos)); //Παίρνουμε την τελευταία λέξη της γραμμής που διαβάστηκε σε μία μεταβλητή τύπου string.//
filename.erase(remove(filename.begin(),filename.end(),' '),filename.end()); //Αφαιρούμε από αυτήν τυχόν κενά.//
ifstream data; //Ανοίγουμε το αρχέιου που περιέχει τα δεδομένα για διάβασμα.//
data.open(filename);
if(data.is_open()){
string lines;
while(getline(data,lines)){ //Μετράμε πόσα δεδομένα υπάρχουν μετρώντας τις σειρές του αρχείου αφού κάθε δεδομένο καταλαμβάνει και μία σειρά.//
sum+=1;
}
mxheap.setNrOfEl(sum); //"Περνάμε" στην κλάση τον αριθμό των σειρών και κατ' επέκταση των δεδομένων.//
mxheap.setfile(filename); //"Περνάμε" στην κλάση το όνομα του αρχείου που περιέχει τα δεδομένα.//
auto start=high_resolution_clock::now();
mxheap.build(); //Συνάρτηση για το χτίσιμο του σωρού μεγίστων.//
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
ifstream tempfile("temp.txt"); //Αντιγραφή των περιεχωμένων του αρχείου temp στο αρχείο output.//
string temp;
screen<<"MAXHEAP: "<<endl;
while(tempfile.good()){
getline(tempfile,temp);
screen<<temp<<endl;
}
screen<<"Maxheap build time: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else{
cout<<"ERROR! Can not find the data file.("<<line<<")"<<endl;
}
}
else if(strstr(line.c_str(),s3.c_str())){
size_t pos=line.size();
string filename=line.substr(line.find_last_of(' ',pos)); //Παίρνουμε την τελευταία λέξη της γραμμής που διαβάστηκε σε μία μεταβλητή τύπου string.//
filename.erase(remove(filename.begin(),filename.end(),' '),filename.end()); //Αφαιρούμε από αυτήν τυχόν κενά.//
ifstream data; //Ανοίγουμε το αρχέιου που περιέχει τα δεδομένα για διάβασμα.//
data.open(filename);
if(data.is_open()){
string lines;
float x;
auto start=high_resolution_clock::now();
while(getline(data,lines)){
x=stof(lines); //Μετατροπή της μεταβλητής τύπου string(που περιέχει το δεδομένο) σε μεταβλητή τύπου float.//
AVL.insert(x); //Συνάρτηση για εισαγωγή του στοιχείου στο δέντρο AVL.//
}
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
AVL.write(); //Συνάρτηση για να γραφεί το αποτέλεσμα στο αρχείο temp.//
ifstream tempfile("temp.txt"); //Αντιγραφή των περιεχωμένων του αρχείου temp στο αρχείο output.//
string temp;
screen<<"AVL(preorder): "<<endl;
while(tempfile.good()){
getline(tempfile,temp);
screen<<temp<<endl;
}
screen<<"AVL tree build time: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else{
cout<<"ERROR! Can not find the data file.("<<line<<")"<<endl;
}
}
else if(strstr(line.c_str(),s4.c_str())){
size_t pos=line.size();
string filename=line.substr(line.find_last_of(' ',pos)); //Παίρνουμε την τελευταία λέξη της γραμμής που διαβάστηκε σε μία μεταβλητή τύπου string.//
filename.erase(remove(filename.begin(),filename.end(),' '),filename.end()); //Αφαιρούμε από αυτήν τυχόν κενά.//
ifstream data; //Ανοίγουμε το αρχέιου που περιέχει τα δεδομένα για διάβασμα.//
data.open(filename);
if(data.is_open()) {
string lines;
float x;
auto start=high_resolution_clock::now();
while (getline(data, lines)) {
x = stof(lines); //Μετατροπή της μεταβλητής τύπου string(που περιέχει το δεδομένο) σε μεταβλητή τύπου float.//
hash.insert(x); //Συνάρτηση για εισαγωγή του στοιχείου στον Hashtable.//
}
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
hash.write(); //Συνάρτηση για να γραφεί το αποτέλεσμα στο αρχείο temp.//
ifstream tempfile("temp.txt"); //Αντιγραφή των περιεχωμένων του αρχείου temp στο αρχείο output.//
string temp;
screen<<"HASHTABLE: "<<endl;
while(tempfile.good()){
getline(tempfile,temp);
screen<<temp<<endl;
}
screen<<"Hashtale build time: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else{
cout<<"ERROR! Can not find the data file.("<<line<<")"<<endl;
}
}
else{
cout<<"Invalid command.("<<line<<")"<<endl;
}
}
else if(strstr(line.c_str(),c2.c_str())){
if(strstr(line.c_str(),s1.c_str())){
auto start=high_resolution_clock::now();
screen<<"The size of the minheap is: "<<mnheap.getsize()<<endl<<endl; //Γράφουμε στο αρχείο output το αποτέλεσμα της συνάρτησης που επιστρέφει το πλήθος των στοιχείων του σωρού ελαχιστων.//
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
screen<<"Get the size of Minheap in: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else if(strstr(line.c_str(),s2.c_str())){
auto start=high_resolution_clock::now();
screen<<"The size of the maxheap is: "<<mxheap.getsize()<<endl<<endl; //Γράφουμε στο αρχείο output το αποτέλεσμα της συνάρτησης που επιστρέφει το πλήθος των στοιχείων του σωρού μεγίστων.//
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
screen<<"Get the size of Maxheap in: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else if(strstr(line.c_str(),s3.c_str())){
auto start=high_resolution_clock::now();
screen<<"The size of the AVL is: "<<AVL.getsize()<<endl<<endl; //Γράφουμε στο αρχείο output το αποτέλεσμα της συνάρτησης που επιστρέφει το πλήθος των στοιχείων του δέντρου AVL.//
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
screen<<"Get the size of AVL tree in: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else if(strstr(line.c_str(),s4.c_str())){
auto start=high_resolution_clock::now();
screen<<"Hashtable contains: "<<hash.getsize()<<" elements."<<endl<<endl; //Γράφουμε στο αρχείο output το αποτέλεσμα της συνάρτησης που επιστρέφει το πλήθος των στοιχείων του Hashtable.//
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
screen<<"Get the size of Hashtable in: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else{
cout<<"Invalid command.("<<line<<")"<<endl;
}
}
else if(strstr(line.c_str(),c3.c_str())){
if(strstr(line.c_str(),s1.c_str())) {
auto start=high_resolution_clock::now();
screen<<"Minimum of MINHEAP: "<<setprecision(2)<<fixed<<mnheap.findmin()<<endl<<endl; //Γράφουμε στο αρχείο output το αποτέλεσμα της συνάρτησης που επιστρέφει το μικρότερο στοιχείο του σωρού ελαχίστων.//
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
screen<<"Get the minimum element of Minheap in: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else if(strstr(line.c_str(),s3.c_str())){
auto start=high_resolution_clock::now();
screen<<"Minimum of AVL: "<<setprecision(2)<<fixed<<AVL.findmin()<<endl<<endl; //Γράφουμε στο αρχείο output το αποτέλεσμα της συνάρτησης που επιστρέφει το μικρότερο στοιχείο του δέντρου AVL.//
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
screen<<"Get the minimum element of AVL tree in: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else{
cout<<"Invalid command.("<<line<<")"<<endl;
}
}
else if(strstr(line.c_str(),c4.c_str())){
if(strstr(line.c_str(),s2.c_str())){
auto start=high_resolution_clock::now();
screen<<"Max of MAXHEAP: "<<setprecision(2)<<fixed<<mxheap.findmax()<<endl<<endl; //Γράφουμε στο αρχείο output το αποτέλεσμα της συνάρτησης που επιστρέφει το μέγιστο στοιχείο του σωρού μεγίστων.//
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
screen<<"Get the max element of Maxheap in: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else{
cout<<"Invalid command.("<<line<<")"<<endl;
}
}
else if(strstr(line.c_str(),c5.c_str())){
if(strstr(line.c_str(),s3.c_str())){
size_t pos=line.size();
string filename=line.substr(line.find_last_of(' ',pos)); //Παίρνουμε την τελευταία λέξη της γραμμής που διαβάστηκε σε μία μεταβλητή τύπου string.//
filename.erase(remove(filename.begin(),filename.end(),' '),filename.end()); //Αφαιρούμε από αυτήν τυχόν κενά.//
float x=stof(filename); //Μετατροπή της μεταβλητής τύπου string(που περιέχει το δεδομένο) σε μεταβλητή τύπου float.//
auto start=high_resolution_clock::now();
if(AVL.search(x)){ //Εμφάνιση στο αρχείο output του κατάλληλου αποτελέσματος ανάλογα με την τιμή της συνάρτησης αναζήτησης στο δέντρο AVL.//
screen<<"Search for element, with key "<<x<<", in AVL: SUCCESS"<<endl<<endl;
}
else{
screen<<"Search for element, with key "<<x<<", in AVL: FAILURE"<<endl<<endl;
}
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
screen<<"Search time of "<<x<<" in AVL tree: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else if(strstr(line.c_str(),s4.c_str())){
size_t pos=line.size();
string filename=line.substr(line.find_last_of(' ',pos)); //Παίρνουμε την τελευταία λέξη της γραμμής που διαβάστηκε σε μία μεταβλητή τύπου string.//
filename.erase(remove(filename.begin(),filename.end(),' '),filename.end()); //Αφαιρούμε από αυτήν τυχόν κενά.//
float x=stof(filename); //Μετατροπή της μεταβλητής τύπου string(που περιέχει το δεδομένο) σε μεταβλητή τύπου float.//
auto start=high_resolution_clock::now();
if(hash.search(x)){ //Εμφάνιση στο αρχείο output του κατάλληλου αποτελέσματος ανάλογα με την τιμή της συνάρτησης αναζήτησης στον Hashtable.//
screen<<"Search for element "<<x<<" in Hashtable: SUCCESS"<<endl<<endl;
}
else{
screen<<"Search for element "<<x<<" in Hashtable: FAILURE"<<endl<<endl;
}
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
screen<<"Search time of "<<x<<" in Hashtable: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else{
cout<<"Invalid command.("<<line<<")"<<endl;
}
}
else if(strstr(line.c_str(),c6.c_str())){
if(strstr(line.c_str(),s1.c_str())){
size_t pos=line.size();
string filename=line.substr(line.find_last_of(' ',pos)); //Παίρνουμε την τελευταία λέξη της γραμμής που διαβάστηκε σε μία μεταβλητή τύπου string.//
filename.erase(remove(filename.begin(),filename.end(),' '),filename.end()); //Αφαιρούμε από αυτήν τυχόν κενά.//
float x=stof(filename); //Μετατροπή της μεταβλητής τύπου string(που περιέχει το δεδομένο) σε μεταβλητή τύπου float.//
auto start=high_resolution_clock::now();
mnheap.insertion(x); //Συνάρτηση για την εισαγωγή του αριθμού στον σωρό ελαχίστων.//
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
ifstream tempfile("temp.txt"); //Αντιγραφή των περιεχωμένων του αρχείου temp στο αρχείο output.//
string temp;
screen<<"MINHEAP after the insertion of "<<x<<": "<<endl;
while(tempfile.good()){
getline(tempfile,temp);
screen<<temp<<endl;
}
screen<<"Insertion time of "<<x<<" in Minheap: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else if(strstr(line.c_str(),s2.c_str())){
size_t pos=line.size();
string filename=line.substr(line.find_last_of(' ',pos)); //Παίρνουμε την τελευταία λέξη της γραμμής που διαβάστηκε σε μία μεταβλητή τύπου string.//
filename.erase(remove(filename.begin(),filename.end(),' '),filename.end()); //Αφαιρούμε από αυτήν τυχόν κενά.//
float x=stof(filename); //Μετατροπή της μεταβλητής τύπου string(που περιέχει το δεδομένο) σε μεταβλητή τύπου float.//
auto start=high_resolution_clock::now();
mxheap.insertion(x); //Συνάρτηση για την εισαγωγή του αριθμού στον σωρό μεγίστων.//
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
ifstream tempfile("temp.txt"); //Αντιγραφή των περιεχωμένων του αρχείου temp στο αρχείο output.//
string temp;
screen<<"MAXHEAP after the insertion of "<<x<<": "<<endl;
while(tempfile.good()){
getline(tempfile,temp);
screen<<temp<<endl;
}
screen<<"Insertion time of "<<x<<" in Maxheap: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else if(strstr(line.c_str(),s3.c_str())){
size_t pos=line.size();
string filename=line.substr(line.find_last_of(' ',pos)); //Παίρνουμε την τελευταία λέξη της γραμμής που διαβάστηκε σε μία μεταβλητή τύπου string.//
filename.erase(remove(filename.begin(),filename.end(),' '),filename.end()); //Αφαιρούμε από αυτήν τυχόν κενά.//
float x=stof(filename); //Μετατροπή της μεταβλητής τύπου string(που περιέχει το δεδομένο) σε μεταβλητή τύπου float.//
auto start=high_resolution_clock::now();
AVL.insert(x); //Συνάρτηση για την εισαγωγή του αριθμού στο δέντρο AVL.//
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
AVL.write(); //Συνάρτηση για να γραφεί το αποτέλεσμα στο αρχείο temp.//
ifstream tempfile("temp.txt"); //Αντιγραφή των περιεχωμένων του αρχείου temp στο αρχείο output.//
string temp;
screen<<"AVL(preorder) after the insertion of "<<x<<": "<<endl;
while(tempfile.good()){
getline(tempfile,temp);
screen<<temp<<endl;
}
screen<<"Insertion time of "<<x<<" in AVL tree: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else if(strstr(line.c_str(),s4.c_str())){
size_t pos=line.size();
string filename=line.substr(line.find_last_of(' ',pos)); //Παίρνουμε την τελευταία λέξη της γραμμής που διαβάστηκε σε μία μεταβλητή τύπου string.//
filename.erase(remove(filename.begin(),filename.end(),' '),filename.end()); //Αφαιρούμε από αυτήν τυχόν κενά.//
float x=stof(filename); //Μετατροπή της μεταβλητής τύπου string(που περιέχει το δεδομένο) σε μεταβλητή τύπου float.//
auto start=high_resolution_clock::now();
hash.insert(x); //Συνάρτηση για την εισαγωγή του αριθμού στον Hashtable.//
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
hash.write(); //Συνάρτηση για να γραφεί το αποτέλεσμα στο αρχείο temp.//
ifstream tempfile("temp.txt"); //Αντιγραφή των περιεχωμένων του αρχείου temp στο αρχείο output.//
string temp;
screen<<"Hashtable after the insertion of "<<x<<": "<<endl;
while(tempfile.good()){
getline(tempfile,temp);
screen<<temp<<endl;
}
screen<<"Insertion time of "<<x<<" in Hashtable: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else{
cout<<"Invalid command.("<<line<<")"<<endl;
}
}
else if(strstr(line.c_str(),c7.c_str())){
if(strstr(line.c_str(),s1.c_str())){
auto start=high_resolution_clock::now();
mnheap.deletion(); //Συνάρτηση για τη διαγραφή του ελάχιστου στοιχείου από τον σωρό ελαχίστων.//
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
ifstream tempfile("temp.txt"); //Αντιγραφή των περιεχωμένων του αρχείου temp στο αρχείο output.//
string temp;
screen<<"MINHEAP after the deletion of minimum: "<<endl;
while(tempfile.good()){
getline(tempfile,temp);
screen<<temp<<endl;
}
screen<<"Deletion time of minimum element in Minheap: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else{
cout<<"Invalid command.("<<line<<")"<<endl;
}
}
else if(strstr(line.c_str(),c8.c_str())){
if(strstr(line.c_str(),s2.c_str())){
auto start=high_resolution_clock::now();
mxheap.deletion(); //Συνάρτηση για τη διαγραφή του μέγιστου στοιχείου από τον σωρό μεγίστων.//
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
ifstream tempfile("temp.txt"); //Αντιγραφή των περιεχωμένων του αρχείου temp στο αρχείο output.//
string temp;
screen<<"MAXHEAP after the deletion of max: "<<endl;
while(tempfile.good()){
getline(tempfile,temp);
screen<<temp<<endl;
}
screen<<"Deletion time of max element in Maxheap: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else{
cout<<"Invalid command.("<<line<<")"<<endl;
}
}
else if(strstr(line.c_str(),c9.c_str())){
if(strstr(line.c_str(),s3.c_str())){
size_t pos=line.size();
string filename=line.substr(line.find_last_of(' ',pos)); //Παίρνουμε την τελευταία λέξη της γραμμής που διαβάστηκε σε μία μεταβλητή τύπου string.//
filename.erase(remove(filename.begin(),filename.end(),' '),filename.end()); //Αφαιρούμε από αυτήν τυχόν κενά.//
float x=stof(filename); //Μετατροπή της μεταβλητής τύπου string(που περιέχει το δεδομένο) σε μεταβλητή τύπου float.//
auto start=high_resolution_clock::now();
AVL.deletenm(x); //Συνάρτηση για την διαγραφή του αριθμού από το δέντρο AVL.//
auto stop=high_resolution_clock::now();
auto duration=duration_cast<microseconds>(stop-start);
AVL.write(); //Συνάρτηση για να γραφεί το αποτέλεσμα στο αρχείο temp.//
ifstream tempfile("temp.txt"); //Αντιγραφή των περιεχωμένων του αρχείου temp στο αρχείο output.//
string temp;
screen<<"AVL(preorder) after the deletion of "<<x<<": "<<endl;
while(tempfile.good()){
getline(tempfile,temp);
screen<<temp<<endl;
}
screen<<"Deletion time of "<<x<<" in AVL tree: "<<duration.count()<<" microseconds."<<endl<<endl;
}
else{
cout<<"Invalid command.("<<line<<")"<<endl;
}
}
else{
cout<<"Invalid command.("<<line<<")"<<endl;
}
}
file.close();
screen.close();
}
else{
cout<<"ERROR! Can not find the commands file."<<endl;
file.close();
exit(1);
}
return 0;
} | [
"[email protected]"
] | |
80e8052056c12d332991a968c24775033645d62a | 329ca0fa3f13f468be1f7966c3ac715f955af3d7 | /Lista Dubla/ListaDubla_lac.cpp | 5b474fe251288645243e4689f00bc1236822ac4e | [] | no_license | diannab5/ex | f39cd00d20ab0a9dd893fc962b7f3a80cf64ec82 | baa2465f6e3824e34c9068094bde2ba256ba7b6c | refs/heads/master | 2022-12-24T20:25:31.168554 | 2020-09-20T07:29:16 | 2020-09-20T07:29:16 | 269,665,253 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,138 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
struct Lac {
int cod_lac;
char* denumire;
float suprafata;
int areInsule;
};
struct nodD {
Lac info;
nodD* next;
nodD* prev;
};
struct ListaDubla {
nodD* prim;
nodD* ultim;
};
Lac creareLac(int cod, const char* nume, float suprafata, int insule) {
Lac l;
l.cod_lac = cod;
l.denumire = (char*)malloc(sizeof(char)*(strlen(nume) + 1));
strcpy(l.denumire, nume);
l.suprafata = suprafata;
l.areInsule = insule;
return l;
}
void afisareLac(Lac l) {
printf("\nLacul %s (cod: %d) are o suprafata de %5.1f si %d insule", l.denumire, l.cod_lac, l.suprafata, l.areInsule);
}
void afisareListaIncSf(ListaDubla lista) {
nodD* aux = lista.prim;
while (aux) {
afisareLac(aux->info);
aux = aux->next;
}
}
void afisareListaSfInc(ListaDubla lista) {
nodD* aux = lista.ultim;
while (aux) {
afisareLac(aux->info);
aux = aux->prev;
}
}
nodD* creareNod(Lac l, nodD* next, nodD* prev) {
nodD* nou = (nodD*)malloc(sizeof(nodD));
nou->info = creareLac(l.cod_lac, l.denumire, l.suprafata, l.areInsule);
nou->next = next;
nou->prev = prev;
return nou;
}
ListaDubla inserareInceput(ListaDubla lista, Lac l) {
nodD* nou = creareNod(l, lista.prim, NULL);
if (lista.prim) {
lista.prim->prev = nou;
lista.prim = nou;
}
else {
lista.prim = lista.ultim = nou;
}
return lista;
}
ListaDubla stergereLista(ListaDubla lista) {
nodD* temp = lista.prim;
while (temp) {
free(temp->info.denumire);
nodD* aux = temp;
temp = temp->next;
free(aux);
}
lista.prim = lista.ultim = NULL;
return lista;
}
float suprafataTotalaLacuriFaraInsule(ListaDubla lista) {
nodD* temp = lista.prim;
float suma = 0;
while (temp) {
if (temp->info.areInsule == 0) {
suma += temp->info.suprafata;
}
temp = temp->next;
}
return suma;
}
Lac stergereDupaCod(ListaDubla* lista, int cod) {
nodD* temp = lista->prim;
while (temp) {
if (temp->info.cod_lac == cod) {
Lac rezultat = creareLac(temp->info.cod_lac, temp->info.denumire, temp->info.suprafata, temp->info.areInsule);
if (temp->prev) {
temp->prev->next = temp->next;
if (temp->next) { //suntem intre 2 noduri
temp->next->prev = temp->prev;
}
else { //suntem pe ultimul nod
lista->ultim = temp->prev;
if (lista->ultim == NULL) { //am sters singurul nod din lista
lista->prim = NULL;
}
}
}
else { //suntem pe primul nod
if (temp->next) {
temp->next = lista->prim;
temp->next->prev = NULL;
}
else {
lista->prim = lista->ultim = NULL;
}
}
free(temp->info.denumire);
free(temp);
return rezultat;
}
temp = temp->next;
}
if (temp->info.cod_lac != cod) {
return creareLac(0, "", 0, 0);
}
}
void dezalocareListaDubla(ListaDubla &lista) {
nodD* temp = lista.prim;
while (temp) {
free(temp->info.denumire);
nodD* aux = temp;
temp = temp->next;
free(aux);
}
lista.prim = NULL;
lista.ultim = NULL;
}
void main() {
ListaDubla lista;
lista.prim = lista.ultim = NULL;
lista = inserareInceput(lista, creareLac(258, "Balea", 200, 0));
lista = inserareInceput(lista, creareLac(842, "Sf. Ana", 840, 3));
lista = inserareInceput(lista, creareLac(185, "Frumos", 220, 5));
lista = inserareInceput(lista, creareLac(208, "Albastru", 690, 0));
lista = inserareInceput(lista, creareLac(957, "Verde", 750, 1));
printf("\nLista de la inceput la sfarsit este: ");
afisareListaIncSf(lista);
printf("\n*************************************");
printf("\nLista de la sfarsit la inceput este: ");
afisareListaSfInc(lista);
printf("\n*************************************");
float suprafata = suprafataTotalaLacuriFaraInsule(lista);
printf("\nSuprafata totala a lacurilor fara insule este de %5.2f", suprafata);
Lac cautat = stergereDupaCod(&lista, 185);
printf("\n*************************************");
printf("\nLacul cautat este: ");
afisareLac(cautat);
printf("\n*************************************");
printf("\nDupa extragere lista este: ");
afisareListaIncSf(lista);
lista = stergereLista(lista);
stergereLista(lista);
afisareListaIncSf(lista);
} | [
"[email protected]"
] | |
66bbed069b09219ee7c889f8eac97605f6fb292d | 6aab4199ab2cab0b15d9af390a251f37802366ab | /sdk/android/src/jni/scoped_java_ref_counted.cc | aa6d817225339a537cc118994cd7b8a5a9c3b5a4 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-google-patent-license-webm"
] | permissive | adwpc/webrtc | f288a600332e5883b2ca44492e02bea81e45b4fa | a30eb44013b8472ea6a042d7ed2909eb7346f9a8 | refs/heads/master | 2021-05-24T13:18:44.227242 | 2021-02-01T14:54:12 | 2021-02-01T14:54:12 | 174,692,051 | 0 | 0 | MIT | 2019-03-09T12:32:13 | 2019-03-09T12:32:13 | null | UTF-8 | C++ | false | false | 887 | cc | /*
* Copyright 2019 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "sdk/android/src/jni/scoped_java_ref_counted.h"
#include "sdk/android/generated_base_jni/RefCounted_jni.h"
namespace webrtc {
namespace jni {
ScopedJavaRefCounted::~ScopedJavaRefCounted() {
if (!j_object_.is_null()) {
JNIEnv* jni = AttachCurrentThreadIfNeeded();
Java_RefCounted_release(jni, j_object_);
CHECK_EXCEPTION(jni)
<< "Unexpected java exception from ScopedJavaRefCounted.release()";
}
}
} // namespace jni
} // namespace webrtc
| [
"[email protected]"
] | |
da9310662d6d37dc30cd0ef6cfe7d16de45d0a58 | b8499de1a793500b47f36e85828f997e3954e570 | /v2_3/build/Android/Debug/app/src/main/include/Uno/GraphicsContext.h | d2990fea6748d547add472298c520a28a425f734 | [] | no_license | shrivaibhav/boysinbits | 37ccb707340a14f31bd57ea92b7b7ddc4859e989 | 04bb707691587b253abaac064317715adb9a9fe5 | refs/heads/master | 2020-03-24T05:22:21.998732 | 2018-07-26T20:06:00 | 2018-07-26T20:06:00 | 142,485,250 | 0 | 0 | null | 2018-07-26T20:03:22 | 2018-07-26T19:30:12 | C++ | UTF-8 | C++ | false | false | 910 | h | // This file was generated based on C:/Users/Vaibhav/AppData/Local/Fusetools/Packages/UnoCore/1.9.0/Backends/CPlusPlus/Uno/GraphicsContext.h.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <XliPlatform/GLContext.h>
#include <XliPlatform/GL.h>
#include <Uno/Support.h>
extern ::Xli::GLContext *_XliGLContextPtr;
struct uGraphicsContext
{
static uGraphicsContext GetInstance()
{
return uGraphicsContext(_XliGLContextPtr);
}
uGraphicsContext()
{
this->context = NULL;
}
GLuint GetBackbufferGLHandle()
{
#if IOS
return 1;
#else
return 0;
#endif
}
::g::Uno::Int2 GetBackbufferSize()
{
return uInt2FromXliVector2i(context->GetDrawableSize());
}
private:
uGraphicsContext(Xli::GLContext *context)
{
this->context = context;
}
::Xli::GLContext *context;
};
| [
"[email protected]"
] | |
d32282c64c655b81d000bf51833a1333da241e7c | 928f458fc912c7d49f4a3c7e111529238ccd4251 | /Plugins/ProcGen/Source/ProcGen/Public/GridHelper.h | 2485701bdeeb198c5798ec56402d5c333cb4ad74 | [] | no_license | ntorkildson/GameplaySystems | 7195886a85fc424799768df768e37da1bd8d5e21 | 3872d36b87e277b2af961e19810f34d0c38b9918 | refs/heads/master | 2022-11-26T10:29:19.941223 | 2020-07-31T21:46:10 | 2020-07-31T21:46:10 | 283,616,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,868 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "GridHelper.generated.h"
/**
* Helper function for creating 1D up to 3D grids, templated so programmers dont have to contunually recreate the same for loops for different data types
*/
/*Returns a grid of type GridData*/
template <typename GH>
TArray<GH> MakeGrid( GH GridData, int GridWidth, int GridHeight, int GridDepth)
{
TArray<GH> NewGrid; //New Grid
for (int i = 0; GridWidth >= i; i++)
{
for (int j = 0; GridHeight >= j; j++)
{
for (int k = 0; GridDepth >= k; k++)
{
NewGrid.Add(GridData);
}
}
}
return NewGrid;
}
/*
returns a 1D array of size Height*Widgth*Depth with Locations being set by (Location * Cellsize + OffSetLocation)
NewGrid is the array type we are passing
DataType is relevant if we are NOT using it in 3d space
CellSize is relevant if we are using it in 3d space
offset location is relevant if the grid has a relative location in 3d space
*/
template<typename GH>
GH MakeGridWithLocation(TArray<GH> &NewGrid, int32 GridWidth, int32 GridHeight, int32 GridDepth, int32 CellSize, FVector OffsetLocation)
{
for (int i = 0; GridWidth > i; i++)
{
for (int j = 0; GridHeight > j; j++)
{
for (int k = 0; GridDepth > k; k++)
{
/*
* if(CellSize > 0
* location based, otherwise its probably just data
*/
GH Temp(i * CellSize + OffsetLocation.X, j * CellSize + OffsetLocation.Y, k * CellSize + OffsetLocation.Z);
NewGrid.AddUnique(Temp);
}
}
}
return OffsetLocation; //This is just worthless...
}
//returns the index from an array given an x,y,z location
template <typename GH>
GH GetGridIndexFromLocation(GH xLocation, GH yLocation, GH zLocation, GH GridWidth, GH GridHeight)
{
//Locations start at 0,0,0
//a 3x3x3 Grid center point would be 1,1,1 and the max extent would be 2,2,2
return xLocation + GridWidth * yLocation + GridWidth * GridHeight * zLocation;
}
//Returns an FVector coordinate from an index and a grid
template <typename GH>
GH GetLocationFromGridIndex(GH Index, GH Width, GH Height)
{
FVector Location;
Location.X = Index % Width;
Location.Y = (Index / Width) % Height;
Location.Z = Index / (Width * Height);
return Location;
}
//sets index of the grid with newData
template <typename GH>
GH SetDataAtIndex(int Index, GH &NewData, GH &Grid)
{
return Grid[Index] = NewData;
}
template <typename GH>
GH GetDataAtIndex(int Index, GH &Grid)
{
return Grid[Index];
}
UCLASS()
class PROCGEN_API UGridHelper : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category ="ProcGenLibrary | GridHelper")
void GenerateGrid();
// FVector GetLocationFromIndex(int32 Index, int32 GridWidth, int32 GridHeight);
};
| [
"[email protected]"
] | |
b83c0f9610c2e93b508c745b6b6f424a0fa64e28 | 13f78c34e80a52442d72e0aa609666163233e7e0 | /AtCoder/ABC 284/E.cpp | 2e05c6df62927f0bae236e70be89c4337d93789e | [] | no_license | Giantpizzahead/comp-programming | 0d16babe49064aee525d78a70641ca154927af20 | 232a19fdd06ecef7be845c92db38772240a33e41 | refs/heads/master | 2023-08-17T20:23:28.693280 | 2023-08-11T22:18:26 | 2023-08-11T22:18:26 | 252,904,746 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,239 | cpp | // ============================== BEGIN TEMPLATE ==============================
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define sz(x) ((int) x.size())
#define all(x) x.begin(), x.end()
#ifdef LOCAL
#include "pprint.hpp"
#else
#define debug(...) 42
#define dumpVars(...) 42
#endif
void solve();
int runTests(bool multiple_tests) {
ios::sync_with_stdio(0);
cin.tie(0);
if (multiple_tests) {
int T; cin >> T;
rep(i, 0, T) solve();
} else solve();
return 0;
}
// =============================== END TEMPLATE ===============================
int N, M, cnt;
vector<vector<int>> adj;
vector<bool> used;
void dfs(int n) {
cnt++;
used[n] = true;
for (int e : adj[n]) {
if (!used[e] && cnt < 1000000) dfs(e);
}
used[n] = false;
}
void solve() {
cin >> N >> M;
adj.resize(N);
used.resize(N);
rep(i, 0, M) {
int a, b; cin >> a >> b;
a--, b--;
adj[a].push_back(b);
adj[b].push_back(a);
}
cnt = 0;
dfs(0);
cout << min(cnt, 1000000) << "\n";
}
int main() {
bool multipleTests = false;
return runTests(multipleTests);
}
| [
"[email protected]"
] | |
c5e75aa5d14659bd91375065c28831878418f74f | e018d8a71360d3a05cba3742b0f21ada405de898 | /VS_UI/Client_PCH.cpp | 85856a21d4593642e9e8c1d58d7289d73dd0dfd3 | [] | no_license | opendarkeden/client | 33f2c7e74628a793087a08307e50161ade6f4a51 | 321b680fad81d52baf65ea7eb3beeb91176c15f4 | refs/heads/master | 2022-11-28T08:41:15.782324 | 2022-11-26T13:21:22 | 2022-11-26T13:21:22 | 42,562,963 | 24 | 18 | null | 2022-11-26T13:21:23 | 2015-09-16T03:43:01 | C++ | UTF-8 | C++ | false | false | 23 | cpp | #include "client_PCH.h" | [
"[email protected]"
] | |
682c8175ea9317cd4aea375456c0dcf08a10dc8c | a41f3c7343bc05c4fa4af6bec9b840bb7001b040 | /unicorn_state_machine/include/unicorn_state_machine/navigating_state.h | 00bd34f46f8b79d5dece3e8813991c3f3abeab5f | [] | no_license | willys0/UNICORN-2020 | 48585eeb1d453ac4021d45c273dd71f09c770a4f | dfa9a3d33b51801f3e71e138ea174b1a316a7a70 | refs/heads/master | 2023-02-19T23:33:34.120381 | 2021-01-15T11:45:51 | 2021-01-15T11:45:51 | 294,638,002 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 685 | h | #ifndef __NAVIGATING_STATE_H_
#define __NAVIGATING_STATE_H_
#include <unicorn_state_machine/state.h>
#include <actionlib/client/simple_action_client.h>
#include <geometry_msgs/Pose.h>
#include <move_base_msgs/MoveBaseAction.h>
class NavigatingState : public State {
public:
NavigatingState(const geometry_msgs::Pose& pose, int lift_cmd, ros::NodeHandle node);
virtual State* run() override;
virtual int stateIdentifier() const override { return 1; }
private:
geometry_msgs::Pose goal_;
int lift_cmd_;
actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> movebase_client_;
};
#endif // __NAVIGATING_STATE_H_
| [
"[email protected]"
] | |
db8900734fca1cbe6ce8e54108e9de3636e98ea3 | 3792887abc868a6d1def09bc359552fe0ece79fc | /RWMP5/RWMP5/RWMP5/include/BoxManager.h | b53d883c139537a3251c6e4e54026b1eecbda2a3 | [] | no_license | iprefersourceforge/RWMP5 | 0265d1d29ae54abcbb6d408b7f46eed3b3cdc2c9 | 3de6ba133003246381017053b01ce2c5dee3091d | refs/heads/master | 2020-09-12T20:27:30.631907 | 2012-02-28T11:22:49 | 2012-02-28T11:22:49 | 3,570,349 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,411 | h | #ifndef BOXMAN_H
#define BOXMAN_H
#include "BoxObject.h"
#include <vector>
class BoxManager
{
private:
static BoxManager * mInstance;
hkpWorld* mPhysicsWorld;
SceneManager * mSceneMgr;
std::vector<BoxObject*> mBoxes;
std::vector<BoxObject*>::iterator currIter;
std::vector<BoxObject*>::iterator endIter;
BoxManager(hkpWorld* physicsWorld, SceneManager * sceneMgr);
public:
~BoxManager();
static BoxManager * getInstance(hkpWorld* physicsWorld = NULL, SceneManager * sceneMgr = NULL);
void addBox(BoxObject::BOX_TYPE bType, float size, unsigned int id, hkVector4& position = hkVector4(0.0,0.0,0.0), bool isStatic = false, float mass = 20.f, float restitution = .1f, float friction = .1f);
void addBox(BoxObject::BOX_TYPE bType, float sizeX, float sizeY, float sizeZ, unsigned int id, hkVector4& position = hkVector4(0.0,0.0,0.0), bool isStatic = false, float mass = 20.f, float restitution = .1f, float friction = .1f);
BoxObject * newBox(BoxObject::BOX_TYPE bType, float size, unsigned int id, hkVector4& position = hkVector4(0.0,0.0,0.0), bool isStatic = false, float mass = 20.f, float restitution = .1f, float friction = .1f);
BoxObject * newBox(BoxObject::BOX_TYPE bType, float sizeX, float sizeY, float sizeZ, unsigned int id, hkVector4& position = hkVector4(0.0,0.0,0.0), bool isStatic = false, float mass = 20.f, float restitution = .1f, float friction = .1f);
void update();
};
#endif | [
"[email protected]"
] | |
d780d4908c5a844eb2da05436238ed2dc56871e0 | 7e167301a49a7b7ac6ff8b23dc696b10ec06bd4b | /prev_work/opensource/fMRI/FSL/fsl/extras/include/boost/boost/mpl/set/aux_/insert_impl.hpp | f486f5ce5624fd632a3ef30e74c4eb643b70ce4d | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Sejik/SignalAnalysis | 6c6245880b0017e9f73b5a343641065eb49e5989 | c04118369dbba807d99738accb8021d77ff77cb6 | refs/heads/master | 2020-06-09T12:47:30.314791 | 2019-09-06T01:31:16 | 2019-09-06T01:31:16 | 193,439,385 | 5 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,609 | hpp |
#ifndef BOOST_MPL_SET_AUX_INSERT_IMPL_HPP_INCLUDED
#define BOOST_MPL_SET_AUX_INSERT_IMPL_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2003-2004
// Copyright David Abrahams 2003-2004
//
// 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)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Source: /usr/local/share/sources/boost/boost/mpl/set/aux_/insert_impl.hpp,v $
// $Date: 2007/06/12 15:03:24 $
// $Revision: 1.1.1.1 $
#include <boost/mpl/insert_fwd.hpp>
#include <boost/mpl/set/aux_/has_key_impl.hpp>
#include <boost/mpl/set/aux_/item.hpp>
#include <boost/mpl/set/aux_/tag.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/base.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/aux_/na.hpp>
#include <boost/type_traits/is_same.hpp>
namespace boost { namespace mpl {
namespace aux {
template< typename Set, typename T > struct set_insert_impl
: eval_if<
has_key_impl<aux::set_tag>::apply<Set,T>
, identity<Set>
, eval_if<
is_same< T,typename Set::last_masked_ >
, base<Set>
, identity< s_item<T,Set> >
>
>
{
};
}
template<>
struct insert_impl< aux::set_tag >
{
template<
typename Set
, typename PosOrKey
, typename KeyOrNA
>
struct apply
: aux::set_insert_impl<
Set
, typename if_na<KeyOrNA,PosOrKey>::type
>
{
};
};
}}
#endif // BOOST_MPL_SET_AUX_INSERT_IMPL_HPP_INCLUDED
| [
"[email protected]"
] | |
0da6d4e71e4920d439fed79f9a2431cd39015d3b | edfdb97e31c75b7a21704db998023b3d7583f4fb | /iOS/Classes/Native/AssemblyU2DCSharp_Views_ReminderView683333339.h | 8e1a7da7842af678baf42572b3730487d5fad362 | [] | no_license | OmnificenceTeam/ICA_Iron_App | b643ab80393e17079031d64fec6fa95de0de0d81 | 7e4c8616ec2e2b358d68d446d4b40d732c085ca9 | refs/heads/master | 2021-07-16T06:53:58.273883 | 2017-10-23T10:52:21 | 2017-10-23T10:52:21 | 107,165,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,975 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_Object2689449295.h"
// UnityEngine.UI.Button
struct Button_t2872111280;
// UnityEngine.GameObject
struct GameObject_t1756533147;
// UniWebView
struct UniWebView_t3614141785;
// UnityEngine.Events.UnityAction
struct UnityAction_t4025899511;
// System.String
struct String_t;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Views.ReminderView
struct ReminderView_t683333339 : public Il2CppObject
{
public:
// UnityEngine.UI.Button Views.ReminderView::backButton
Button_t2872111280 * ___backButton_0;
// UnityEngine.GameObject Views.ReminderView::reminderView
GameObject_t1756533147 * ___reminderView_1;
// UnityEngine.GameObject Views.ReminderView::jade
GameObject_t1756533147 * ___jade_2;
// UniWebView Views.ReminderView::webView
UniWebView_t3614141785 * ___webView_3;
// UnityEngine.Events.UnityAction Views.ReminderView::OnClose
UnityAction_t4025899511 * ___OnClose_4;
// System.String Views.ReminderView::currentPage
String_t* ___currentPage_5;
public:
inline static int32_t get_offset_of_backButton_0() { return static_cast<int32_t>(offsetof(ReminderView_t683333339, ___backButton_0)); }
inline Button_t2872111280 * get_backButton_0() const { return ___backButton_0; }
inline Button_t2872111280 ** get_address_of_backButton_0() { return &___backButton_0; }
inline void set_backButton_0(Button_t2872111280 * value)
{
___backButton_0 = value;
Il2CppCodeGenWriteBarrier(&___backButton_0, value);
}
inline static int32_t get_offset_of_reminderView_1() { return static_cast<int32_t>(offsetof(ReminderView_t683333339, ___reminderView_1)); }
inline GameObject_t1756533147 * get_reminderView_1() const { return ___reminderView_1; }
inline GameObject_t1756533147 ** get_address_of_reminderView_1() { return &___reminderView_1; }
inline void set_reminderView_1(GameObject_t1756533147 * value)
{
___reminderView_1 = value;
Il2CppCodeGenWriteBarrier(&___reminderView_1, value);
}
inline static int32_t get_offset_of_jade_2() { return static_cast<int32_t>(offsetof(ReminderView_t683333339, ___jade_2)); }
inline GameObject_t1756533147 * get_jade_2() const { return ___jade_2; }
inline GameObject_t1756533147 ** get_address_of_jade_2() { return &___jade_2; }
inline void set_jade_2(GameObject_t1756533147 * value)
{
___jade_2 = value;
Il2CppCodeGenWriteBarrier(&___jade_2, value);
}
inline static int32_t get_offset_of_webView_3() { return static_cast<int32_t>(offsetof(ReminderView_t683333339, ___webView_3)); }
inline UniWebView_t3614141785 * get_webView_3() const { return ___webView_3; }
inline UniWebView_t3614141785 ** get_address_of_webView_3() { return &___webView_3; }
inline void set_webView_3(UniWebView_t3614141785 * value)
{
___webView_3 = value;
Il2CppCodeGenWriteBarrier(&___webView_3, value);
}
inline static int32_t get_offset_of_OnClose_4() { return static_cast<int32_t>(offsetof(ReminderView_t683333339, ___OnClose_4)); }
inline UnityAction_t4025899511 * get_OnClose_4() const { return ___OnClose_4; }
inline UnityAction_t4025899511 ** get_address_of_OnClose_4() { return &___OnClose_4; }
inline void set_OnClose_4(UnityAction_t4025899511 * value)
{
___OnClose_4 = value;
Il2CppCodeGenWriteBarrier(&___OnClose_4, value);
}
inline static int32_t get_offset_of_currentPage_5() { return static_cast<int32_t>(offsetof(ReminderView_t683333339, ___currentPage_5)); }
inline String_t* get_currentPage_5() const { return ___currentPage_5; }
inline String_t** get_address_of_currentPage_5() { return &___currentPage_5; }
inline void set_currentPage_5(String_t* value)
{
___currentPage_5 = value;
Il2CppCodeGenWriteBarrier(&___currentPage_5, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"[email protected]"
] | |
e609ea36fb3a502a9dea4b59312ce5b1b7ca2a58 | 38c10c01007624cd2056884f25e0d6ab85442194 | /components/favicon/content/content_favicon_driver_unittest.cc | 883b90fc4c00752d3c05c2f0e14e11aebb9a05df | [
"BSD-3-Clause"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 5,341 | cc | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/favicon/content/content_favicon_driver.h"
#include "base/memory/scoped_ptr.h"
#include "components/favicon/core/favicon_client.h"
#include "components/favicon/core/favicon_handler.h"
#include "components/favicon/core/favicon_service.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/favicon_url.h"
#include "content/public/test/test_renderer_host.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/favicon_size.h"
namespace favicon {
namespace {
class ContentFaviconDriverTest : public content::RenderViewHostTestHarness {
public:
ContentFaviconDriverTest() {}
~ContentFaviconDriverTest() override {}
// content::RenderViewHostTestHarness:
void SetUp() override {
RenderViewHostTestHarness::SetUp();
favicon_service_.reset(new FaviconService(nullptr, nullptr));
ContentFaviconDriver::CreateForWebContents(
web_contents(), favicon_service(), nullptr, nullptr);
}
FaviconService* favicon_service() {
return favicon_service_.get();
}
private:
scoped_ptr<FaviconService> favicon_service_;
DISALLOW_COPY_AND_ASSIGN(ContentFaviconDriverTest);
};
// Test that Favicon is not requested repeatedly during the same session if
// server returns HTTP 404 status.
TEST_F(ContentFaviconDriverTest, UnableToDownloadFavicon) {
const GURL missing_icon_url("http://www.google.com/favicon.ico");
const GURL another_icon_url("http://www.youtube.com/favicon.ico");
ContentFaviconDriver* content_favicon_driver =
ContentFaviconDriver::FromWebContents(web_contents());
std::vector<SkBitmap> empty_icons;
std::vector<gfx::Size> empty_icon_sizes;
int download_id = 0;
// Try to download missing icon.
download_id = content_favicon_driver->StartDownload(missing_icon_url, 0);
EXPECT_NE(0, download_id);
EXPECT_FALSE(favicon_service()->WasUnableToDownloadFavicon(missing_icon_url));
// Report download failure with HTTP 503 status.
content_favicon_driver->DidDownloadFavicon(download_id, 503, missing_icon_url,
empty_icons, empty_icon_sizes);
// Icon is not marked as UnableToDownload as HTTP status is not 404.
EXPECT_FALSE(favicon_service()->WasUnableToDownloadFavicon(missing_icon_url));
// Try to download again.
download_id = content_favicon_driver->StartDownload(missing_icon_url, 0);
EXPECT_NE(0, download_id);
EXPECT_FALSE(favicon_service()->WasUnableToDownloadFavicon(missing_icon_url));
// Report download failure with HTTP 404 status.
content_favicon_driver->DidDownloadFavicon(download_id, 404, missing_icon_url,
empty_icons, empty_icon_sizes);
// Icon is marked as UnableToDownload.
EXPECT_TRUE(favicon_service()->WasUnableToDownloadFavicon(missing_icon_url));
// Try to download again.
download_id = content_favicon_driver->StartDownload(missing_icon_url, 0);
// Download is not started and Icon is still marked as UnableToDownload.
EXPECT_EQ(0, download_id);
EXPECT_TRUE(favicon_service()->WasUnableToDownloadFavicon(missing_icon_url));
// Try to download another icon.
download_id = content_favicon_driver->StartDownload(another_icon_url, 0);
// Download is started as another icon URL is not same as missing_icon_url.
EXPECT_NE(0, download_id);
EXPECT_FALSE(favicon_service()->WasUnableToDownloadFavicon(another_icon_url));
// Clear the list of missing icons.
favicon_service()->ClearUnableToDownloadFavicons();
EXPECT_FALSE(favicon_service()->WasUnableToDownloadFavicon(missing_icon_url));
EXPECT_FALSE(favicon_service()->WasUnableToDownloadFavicon(another_icon_url));
// Try to download again.
download_id = content_favicon_driver->StartDownload(missing_icon_url, 0);
EXPECT_NE(0, download_id);
// Report download success with HTTP 200 status.
content_favicon_driver->DidDownloadFavicon(download_id, 200, missing_icon_url,
empty_icons, empty_icon_sizes);
// Icon is not marked as UnableToDownload as HTTP status is not 404.
EXPECT_FALSE(favicon_service()->WasUnableToDownloadFavicon(missing_icon_url));
favicon_service()->Shutdown();
}
// Test that ContentFaviconDriver ignores updated favicon URLs if there is no
// last committed entry. This occurs when script is injected in about:blank.
// See crbug.com/520759 for more details
TEST_F(ContentFaviconDriverTest, FaviconUpdateNoLastCommittedEntry) {
ASSERT_EQ(nullptr, web_contents()->GetController().GetLastCommittedEntry());
std::vector<content::FaviconURL> favicon_urls;
favicon_urls.push_back(content::FaviconURL(
GURL("http://www.google.ca/favicon.ico"), content::FaviconURL::FAVICON,
std::vector<gfx::Size>()));
favicon::ContentFaviconDriver* driver =
favicon::ContentFaviconDriver::FromWebContents(web_contents());
static_cast<content::WebContentsObserver*>(driver)
->DidUpdateFaviconURL(favicon_urls);
// Test that ContentFaviconDriver ignored the favicon url update.
EXPECT_TRUE(driver->favicon_urls().empty());
}
} // namespace
} // namespace favicon
| [
"[email protected]"
] | |
9588a32a5da0e04ec999568b07b15f3a83d1ba8c | 8f50c262f89d3dc4f15f2f67eb76e686b8f808f5 | /TileCalorimeter/TileMonitoring/src/TileMonitorAlgorithm.h | b666a75276740e13e6c6bdc07d6445084adb56ad | [
"Apache-2.0"
] | permissive | strigazi/athena | 2d099e6aab4a94ab8b636ae681736da4e13ac5c9 | 354f92551294f7be678aebcd7b9d67d2c4448176 | refs/heads/master | 2022-12-09T02:05:30.632208 | 2020-09-03T14:03:18 | 2020-09-03T14:03:18 | 292,587,480 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,645 | h | /*
Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
*/
#ifndef TILEMONITORING_TILEMONITORALGORITHM_H
#define TILEMONITORING_TILEMONITORALGORITHM_H
#include "AthenaMonitoring/AthMonitorAlgorithm.h"
class CaloCell;
class TileID;
/** @class TileMonitorAlgorithm
* @brief Base class for Tile monitoring per L1 trigger type
*/
class TileMonitorAlgorithm : public AthMonitorAlgorithm {
public:
TileMonitorAlgorithm(const std::string& name, ISvcLocator* svcLocator)
:AthMonitorAlgorithm(name, svcLocator), m_l1TriggerIndices(9, -1) {}
using AthMonitorAlgorithm::AthMonitorAlgorithm;
virtual ~TileMonitorAlgorithm() = default;
virtual StatusCode initialize() override;
virtual StatusCode fillHistograms(const EventContext& ctx) const override = 0;
/**
* @enum L1TriggerTypeBit
* @brief Describes L1 trigger type bits
*/
enum L1TriggerTypeBit {BIT0_RNDM, BIT1_ZEROBIAS, BIT2_L1CAL, BIT3_MUON,
BIT4_RPC, BIT5_FTK, BIT6_CTP, BIT7_CALIB, ANY_PHYSICS};
/**
* @enum AuxiliarySampling
* @brief Describes Tile auxiliary sampling
*/
enum AuxiliarySampling {SAMP_ALL = 4, MAX_SAMP = 5};
/**
* @enum Partition
* @brief Describes Tile partitions (ROS - 1)
*/
enum Partition {PART_LBA, PART_LBC, PART_EBA,
PART_EBC, PART_ALL, MAX_PART}; // ROS - 1
/**
* @brief Return indices of histograms to be filled according fired L1 trigger type
* @param lvl1TriggerType Level1 Trigger Type
* @return vector of indices of histograms to be filled
*/
std::vector<int> getL1TriggerIndices(uint32_t lvl1TriggerType) const;
/**
* @brief Return Level1 Trigger type bit according trigger index
* @param lvl1TriggerIdx Level1 Trigger index
* @return level1 trigger type bit according trigger index
*/
L1TriggerTypeBit getL1TriggerTypeBit(int lvl1TriggerIdx) const;
/**
* @brief Return number of L1 triggers for which histograms should be filled
*/
int getNumberOfL1Triggers(void) const {return m_fillHistogramsForL1Triggers.size();};
/**
* @brief Return true if it is physics event or false for calibration event
* @param lvl1TriggerType Level1 Trigger Type
* @return true if it is physics event according L1 trigger type
*/
bool isPhysicsEvent(uint32_t lvl1TriggerType) const;
/**
* @brief Return Partition for Tile cell or MAX_PART otherwise
* @param cell Calo cell
*/
Partition getPartition(const CaloCell* cell, const TileID* tileID) const;
/**
* @brief Return Partition for Tile cell identifier or MAX_PART otherwise
* @param id Calo cell identifier
*/
Partition getPartition(Identifier id, const TileID* tileID) const;
/**
* @brief Return Partition for Tile cell identifier hash or MAX_PART otherwise
* @param hash Calo cell identifier hash
*/
Partition getPartition(IdentifierHash hash, const TileID* tileID) const;
private:
L1TriggerTypeBit getL1TriggerTypeBitFromName(const std::string& triggerBitName) const;
Gaudi::Property<std::vector<std::string>> m_fillHistogramsForL1Triggers{this,
"fillHistogramsForL1Triggers", {}, "Fill histograms per given L1 trigger types"};
std::vector<L1TriggerTypeBit> m_l1Triggers;
std::vector<int> m_l1TriggerIndices;
std::vector<std::string> m_l1TriggerBitNames{"bit0_RNDM", "bit1_ZeroBias", "bit2_L1CAL", "bit3_MUON",
"bit4_RPC", "bit5_FTK", "bti6_CTP", "bit7_Calib", "AnyPhysTrig"};
};
#endif // TILEMONITORING_TILEMONITORALGORITHM_H
| [
"[email protected]"
] | |
c6b2596feb0abb049768547174544a21ae0f0fe8 | ff96ab2921b899fdc26baeb9d0995ad8d7fa551d | /Test/MetaFunctionsTest.cpp | 94962bd9ea50c5da98c65cc9221baeff7e480ca3 | [] | no_license | morimoto0606/ModernCpp | 9a3238644adfaa7cd4b2b018ca6f85828f7ad5f8 | 4cd123b1e75dee2ad4e86a97cb149e665af69e60 | refs/heads/master | 2020-04-17T14:51:48.855956 | 2019-01-20T16:49:05 | 2019-01-20T16:49:05 | 166,674,817 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,673 | cpp | //
// Created by MORIMOTO on 2017/12/23.
//
#include <gtest/gtest.h>
#include "../Source/meta_functions.h"
#include <tuple>
#include <vector>
#include <list>
#include <algorithm>
#include <iostream>
using testing::Test;
namespace test {
TEST(MetaFunctionsTest, is_pointer)
{
EXPECT_TRUE(meta_functions::is_pointer_v<int*>);
EXPECT_FALSE(meta_functions::is_pointer_v<int>);
}
TEST(MetaFunctionsTest, is_vector)
{
EXPECT_TRUE(meta_functions::is_vector<std::vector<int>>::value);
EXPECT_FALSE(meta_functions::is_vector_v<int>);
}
TEST(MetaFunctionsTest, is_int)
{
EXPECT_TRUE(meta_functions::is_int_v<int>);
EXPECT_FALSE(meta_functions::is_int_v<double>);
}
TEST(MetaFunctionsTest, f1)
{
int x;
double y;
meta_functions::f1(x);
meta_functions::f1(y);
}
TEST(MetaFunctionTest, has_iterator1)
{
EXPECT_TRUE(
meta_functions::has_iterator1<
std::vector<double>>::value);
EXPECT_FALSE(
meta_functions::has_iterator1_v<double>);
}
TEST(MetaFunctionsTest, has_iterator2)
{
EXPECT_TRUE(
meta_functions::has_iterator2_v<std::vector<int>>);
}
TEST(MetaFunctionsTest, has_iterator3)
{
EXPECT_TRUE(
meta_functions::has_iterator3_v<std::vector<int>>);
EXPECT_FALSE(
meta_functions::has_iterator3_v<int>);
}
TEST(MetaFunctionsTest, has_value) {
struct Hoge {
int value;
};
struct Fuga {
int val;
};
EXPECT_TRUE(
meta_functions::has_value_v<std::false_type>);
EXPECT_TRUE(
meta_functions::has_value_v<Hoge>);
EXPECT_FALSE(
meta_functions::has_value_v<Fuga>);
}
TEST(MetaFunctionsTest, has_f)
{
struct Hoge {
double f() const {
return 0.9;
}
};
EXPECT_FALSE(meta_functions::has_f_v<int>);
EXPECT_TRUE(meta_functions::has_f_v<Hoge>);
}
TEST(MetaFunctionsTest, has_member)
{
class Hoge {
public:
void hoge() const {}
};
class Fuga {
//publicならOK privateだとFalse
public:
int hoge = 0;
};
EXPECT_TRUE(meta_functions::has_member_v<Hoge>);
EXPECT_TRUE(meta_functions::has_member_v<Fuga>);
EXPECT_FALSE(meta_functions::has_member_v<float >);
}
TEST(MetaFunctionsTest, is_assignble)
{
int x;
int y = 3;
x = 3;
std::cout << x;
class Hoge {
public:
Hoge& operator =(const Hoge& other) = delete;
};
EXPECT_TRUE(meta_functions::is_assignable_v<double>);
EXPECT_FALSE(meta_functions::is_assignable_v<Hoge>);
}
TEST(MetaFunctionsTest, void_t)
{
class Hoge{
};
EXPECT_TRUE(meta_functions::is_equality_comparable<int>::value);
EXPECT_FALSE(meta_functions::is_equality_comparable<Hoge>::value);
}
TEST(MetaFunctionsTest, sort) {
std::vector<int> vec{3, 1, 4, 1, 5, 9, 2};
std::list<int> lis{3, 1, 4, 1, 5, 9, 2};
for (auto v : vec) {
std::cout << v << ',' << std::endl;
}
for (auto l : lis) {
std::cout << l << ',' << std::endl;
}
meta_functions::generalSort(std::move(vec));
meta_functions::generalSort(std::move(lis));
// std::sort(vec.begin(), vec.end());
// lis.sort();
for (auto v : vec) {
std::cout << v << ',' << std::endl;
}
for (auto l : lis) {
std::cout << l << ',' << std::endl;
}
}
TEST(MetaFunctionsTest, has_func) {
static_assert(meta_functions::is_assignable_v<meta_functions::X>, "assignable");
static_assert(meta_functions::has_func_v<meta_functions::X>, "double can be applied for func");
static_assert(!meta_functions::has_func_v<std::string>, "string can be applied for func");
std::cout << meta_functions::has_func_v<meta_functions::X> << std::endl;
std::cout << meta_functions::has_func_v<std::string> << std::endl;
int x;
double y;
std::string z;
meta_functions::X w;
EXPECT_EQ(1, meta_functions::get_func_value(x));
EXPECT_EQ(1, meta_functions::get_func_value(y));
EXPECT_EQ(2, meta_functions::get_func_value(w));
EXPECT_EQ(0, meta_functions::get_func_value(z));
}
}
| [
"[email protected]"
] | |
7a402be6850581fd986bf98e0491d41b3c3621c5 | bd228f68aa676a130cdb48557117310e03d9e857 | /vector4.cpp | 3dc08bcbbe45ba2fd1ac453464a938635e3bc704 | [] | no_license | iamketan56/CPP-STL-PROGRAMMING | bdae4b0cae34e15fc5aac562c28059120c5ce811 | bc33dd9d4d75a1a13250ea3175066fc3265b457c | refs/heads/main | 2023-05-07T18:28:46.716423 | 2021-06-10T15:52:02 | 2021-06-10T15:52:02 | 309,231,483 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 449 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
vector<int> v;
int ele;
cin >> ele;
int data;
while (ele--)
{
cin >> data;
v.push_back(data);
}
int removeele;
cin >> removeele;
v.erase(v.begin() + (removeele - 1));
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << " ";
}
return 0;
}
| [
"[email protected]"
] | |
ba1b100859e398cfac5b5449e43ddd85834793aa | 588ccfc71b569cb4709f1f11ffa17c4f79eba438 | /bodoasm/src/cmdline/cmdlineargs.cpp | 397c5b586efd898159db84baeb68620bd8b16b2d | [] | no_license | BenWenger/Bodobon | 057c8d02a5d8f4112916918e08b851fc9ed60718 | 719bd7704931cbf7026ef6d7707c72a4bcd1dba3 | refs/heads/master | 2020-04-01T11:27:25.584728 | 2019-02-11T17:40:37 | 2019-02-11T17:40:37 | 153,162,885 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,485 | cpp |
#include "cmdlineargs.h"
#include <set>
#include <deque>
#include <stdexcept>
namespace bodoasm
{
CommandLineArgs CommandLineArgs::parseCommandLine(int argc, const char* argv[])
{
std::string v;
std::set<char> givenArgs;
std::deque<char> queue;
CommandLineArgs out;
for(int i = 1; i < argc; ++i)
{
v = argv[i];
if(v.empty())
continue; // this shouldn't happen, but whatever
if(v[0] == '-') // option?
{
for(std::size_t x = 1; x < v.size(); ++x)
{
char opt = v[x];
auto didInsert = givenArgs.insert(opt);
if(!didInsert.second)
throw std::runtime_error(std::string("Option -") + opt + " cannot be given multiple times");
switch(opt)
{
case 'a': case 'o': case 'D':
queue.push_back(opt);
break;
case 'f':
out.fullOverwrite = true;
break;
case 'w':
out.warningAsErrors = true;
break;
default:
throw std::runtime_error(std::string("Unknown Option: -") + opt);
}
}
}
}
}
} | [
"[email protected]"
] | |
666d8b4fbbaea0eb3524d1489037fe71aaa31318 | f2af058f388625e859aafb1acb03ca0a1754e454 | /tapetool/CommandSamples.h | d497abf88ee30cfe9f67b256123c2df3a559f175 | [] | no_license | davidbroughsmyth/tapetool | 754f826e071842b60b7166c8879c35a2216581d2 | 4487cbf3d4c6087044eda7b39c8849078c2d16f3 | refs/heads/master | 2023-03-18T20:52:30.846125 | 2017-05-05T01:17:01 | 2017-05-05T01:17:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 580 | h | //////////////////////////////////////////////////////////////////////////
// CommandSamples.h - declaration of CCommandSamples
#ifndef __COMMANDSAMPLES_H
#define __COMMANDSAMPLES_H
#include "CommandWithRangedInputWaveFile.h"
class CCommandSamples : public CCommandWithRangedInputWaveFile
{
public:
CCommandSamples();
virtual int Process();
virtual int AddSwitch(const char* arg, const char* val);
virtual const char* GetCommandName() { return "samples"; };
void ShowUsage();
int _perline;
bool _showCycles;
bool _showPositionInfo;
};
#endif // __COMMANDSAMPLES_H
| [
"[email protected]"
] | |
022c8729d89d86ad34431bce74e829727bf0729b | cf67341c55ef5e061f71fb1c02b6490e7d384a1d | /Enemy_Rifle.h | 894d19ff46cea7eb2609e9d112d04dc5fb3b1d44 | [] | no_license | Hugo-Bo-Diaz/Gun-Smoke | 91b136dbe15037ba25b809288db980b55c2a54a8 | d092238888fbd21e0ae4c578854bfa7081cdf476 | refs/heads/master | 2020-04-06T06:22:50.691431 | 2017-06-05T00:07:30 | 2017-06-05T00:07:30 | 82,910,039 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 340 | h | #ifndef __ENEMY_RIFLE_H__
#define __ENEMY_RIFLE_H__
#include "Enemy.h"
#include "Path.h"
class Enemy_Rifle : public Enemy
{
private:
iPoint original_pos;
Animation fly;
Path path;
int path_part;
uint timer;
uint timer_2;
int shots_fired;
public:
Enemy_Rifle(int x, int y);
void Move();
void Shoot();
~Enemy_Rifle();
};
#endif
| [
"[email protected]"
] | |
6b2e3713942fceda3f8b9fa3e42f3de966fb8915 | 53c0b414ab73222631ebb32a6f26a99d4df3abb7 | /modules/planning/planner/em/em_planner_test.cc | 3cff668275091967dcd1b18b6074f594b4e47d6f | [
"Apache-2.0"
] | permissive | keenan-burnett/apollo | d8aa4c9b907fd248791d0f16abfd859be3d01efc | febf8182c5503a24753b3193c20e3705e106cc72 | refs/heads/master | 2020-03-28T02:36:29.446833 | 2018-09-05T20:38:27 | 2018-09-05T20:40:01 | 147,583,482 | 1 | 1 | Apache-2.0 | 2018-09-05T21:50:41 | 2018-09-05T21:50:40 | null | UTF-8 | C++ | false | false | 1,334 | cc | /******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/planner/em/em_planner.h"
#include "gtest/gtest.h"
#include "modules/common/proto/drive_state.pb.h"
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/map/hdmap/hdmap_common.h"
#include "modules/map/hdmap/hdmap_util.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
TEST(EMPlannerTest, Simple) {
EMPlanner em;
PlanningConfig config;
EXPECT_EQ(em.Name(), "EM");
EXPECT_EQ(em.Init(config), common::Status::OK());
}
} // namespace planning
} // namespace apollo
| [
"[email protected]"
] | |
00afe880e26fb42959decac4731635fffa69e011 | 786de89be635eb21295070a6a3452f3a7fe6712c | /pypdsdata/tags/V00-00-99/pyext/types/lusi/IpmFexV1.cpp | c8cc0da2ca3fd270578c97cd47590449c1eeedc3 | [] | no_license | connectthefuture/psdmrepo | 85267cfe8d54564f99e17035efe931077c8f7a37 | f32870a987a7493e7bf0f0a5c1712a5a030ef199 | refs/heads/master | 2021-01-13T03:26:35.494026 | 2015-09-03T22:22:11 | 2015-09-03T22:22:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,930 | cpp | //--------------------------------------------------------------------------
// File and Version Information:
// $Id: IpmFexV1.cpp 811 2010-03-26 17:40:08Z salnikov $
//
// Description:
// Class IpmFexV1...
//
// Author List:
// Andrei Salnikov
//
//------------------------------------------------------------------------
//-----------------------
// This Class's Header --
//-----------------------
#include "IpmFexV1.h"
//-----------------
// C/C++ Headers --
//-----------------
#include <sstream>
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
#include "DiodeFexConfigV1.h"
#include "../../Exception.h"
#include "../TypeLib.h"
//-----------------------------------------------------------------------
// Local Macros, Typedefs, Structures, Unions and Forward Declarations --
//-----------------------------------------------------------------------
namespace {
// methods
MEMBER_WRAPPER(pypdsdata::Lusi::IpmFexV1, sum)
MEMBER_WRAPPER(pypdsdata::Lusi::IpmFexV1, xpos)
MEMBER_WRAPPER(pypdsdata::Lusi::IpmFexV1, ypos)
PyObject* IpmFexV1_channel( PyObject* self, void* );
// disable warnings for non-const strings, this is a temporary measure
// newer Python versions should get constness correctly
#pragma GCC diagnostic ignored "-Wwrite-strings"
PyGetSetDef getset[] = {
{"sum", sum, 0, "Floating point number", 0},
{"xpos", xpos, 0, "Floating point number", 0},
{"ypos", ypos, 0, "Floating point number", 0},
{"channel", IpmFexV1_channel, 0, "List of 4 floating numbers", 0},
{0, 0, 0, 0, 0}
};
char typedoc[] = "Python class wrapping C++ Pds::Lusi::IpmFexV1 class.";
}
// ----------------------------------------
// -- Public Function Member Definitions --
// ----------------------------------------
void
pypdsdata::Lusi::IpmFexV1::initType( PyObject* module )
{
PyTypeObject* type = BaseType::typeObject() ;
type->tp_doc = ::typedoc;
type->tp_getset = ::getset;
BaseType::initType( "IpmFexV1", module );
}
void
pypdsdata::Lusi::IpmFexV1::print(std::ostream& str) const
{
str << "lusi.IpmFexV1(sum=" << m_obj->sum
<< ", xpos=" << m_obj->xpos
<< ", ypos=" << m_obj->ypos
<< ", channel=[" ;
const int size = sizeof m_obj->channel / sizeof m_obj->channel[0];
for ( int i = 0 ; i < size ; ++ i ) {
if ( i ) str << ", " ;
str << m_obj->channel[i];
}
str << "])" ;
}
namespace {
PyObject*
IpmFexV1_channel( PyObject* self, void* )
{
Pds::Lusi::IpmFexV1* obj = pypdsdata::Lusi::IpmFexV1::pdsObject(self);
if (not obj) return 0;
const int size = sizeof obj->channel / sizeof obj->channel[0];
PyObject* list = PyList_New( size );
for ( int i = 0 ; i < size ; ++ i ) {
PyList_SET_ITEM( list, i, pypdsdata::TypeLib::toPython(obj->channel[i]) );
}
return list;
}
}
| [
"[email protected]@b967ad99-d558-0410-b138-e0f6c56caec7"
] | [email protected]@b967ad99-d558-0410-b138-e0f6c56caec7 |
10bc7514e92b058a212e51376c501b64969f5423 | 05014e7206aa7c323c1bca84f0e8d554f9305fd3 | /model_qtlog4/log4qt/include/log4qt/binarylogger.h | 565f043506d5a9c256327770f5cb362b34811872 | [
"Apache-2.0"
] | permissive | snailone008/Gameinterface-Doudizhu | 59086c3799dd8fd3d50d9cf6ef3c863d14a8c52d | 8f7f9e3a4e73651ec9aa7eecb2f57a82ea6879ba | refs/heads/master | 2020-12-15T20:31:07.202936 | 2020-01-21T03:18:40 | 2020-01-21T03:18:40 | 235,245,974 | 0 | 0 | Apache-2.0 | 2020-01-21T03:12:26 | 2020-01-21T03:12:25 | null | UTF-8 | C++ | false | false | 2,494 | h | #ifndef LOG4QT_BINARYLOGGER_H
#define LOG4QT_BINARYLOGGER_H
#include "logger.h"
#include "binarylogstream.h"
#include "helpers/binaryclasslogger.h"
class QByteArray;
namespace Log4Qt
{
class Appender;
class BinaryLoggingEvent;
class LoggerRepository;
class Hierarchy;
#define LOG4QT_DECLARE_STATIC_BINARYLOGGER(FUNCTION, CLASS) \
static Log4Qt::BinaryLogger *FUNCTION() \
{ \
static Log4Qt::Logger * p_logger(Log4Qt::Logger::logger(#CLASS"@@binary@@" )); \
return qobject_cast<Log4Qt::BinaryLogger*>(p_logger); \
}
#define LOG4QT_DECLARE_QCLASS_BINARYLOGGER \
private: \
mutable Log4Qt::BinaryClassLogger mLog4QtClassLogger; \
public: \
inline Log4Qt::BinaryLogger *logger() const \
{ \
return mLog4QtClassLogger.logger(this); \
} \
private:
class LOG4QT_EXPORT BinaryLogger : public Logger
{
Q_OBJECT
public:
BinaryLogStream debug() const {return log(Level::DEBUG_INT);}
void debug(const QByteArray &message) const {log(Level::DEBUG_INT, message);}
BinaryLogStream error() const {return log(Level::ERROR_INT);}
void error(const QByteArray &message) const {log(Level::ERROR_INT, message);}
BinaryLogStream fatal() const {return log(Level::FATAL_INT);}
void fatal(const QByteArray &message) const {log(Level::FATAL_INT, message);}
BinaryLogStream info() const {return log(Level::INFO_INT);}
void info(const QByteArray &message) const {log(Level::INFO_INT, message);}
BinaryLogStream trace() const {return log(Level::TRACE_INT);}
void trace(const QByteArray &message) const {log(Level::TRACE_INT, message);}
BinaryLogStream warn() const {return log(Level::WARN_INT);}
void warn(const QByteArray &message) const {log(Level::WARN_INT, message);}
BinaryLogStream log(Level level) const;
void log(Level level, const QByteArray &message) const;
void log(Level level, const QByteArray &message, const QDateTime &timeStamp) const;
protected:
BinaryLogger(LoggerRepository *loggerRepository, Level level, const QString &name, Logger *parent = nullptr);
virtual ~BinaryLogger();
void forcedLog(Level level, const QByteArray &message) const;
private:
BinaryLogger(const BinaryLogger &other); // Not implemented
BinaryLogger &operator=(const BinaryLogger &other); // Not implemented
// Needs to be friend to create BinaryLogger objects
friend class Hierarchy;
};
} // namespace Log4Qt
#endif // LOG4QT_BINARYLOGGER_H
| [
"[email protected]"
] | |
a919fdfee86da7c2a55b8b13b96e1c7fc16362b8 | d468d856851990af88f1f80412d792e459af2b4f | /example.9.cpp | d191ccd8cf3d264f12c641caba22d78ac0bb70f4 | [] | no_license | jean-marc/objrdf | 27ed47a2ff6ee84d65476d3b1c2f5e39a4d24d34 | 3c83c11a10e2d9697e48bb81dff5a449d6ffb7a8 | refs/heads/master | 2020-05-17T07:59:00.765844 | 2017-10-04T18:35:01 | 2017-10-04T18:35:01 | 2,861,108 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 684 | cpp | #include "objrdf.h"
#include "rdf_xml_parser.h"
#include <iostream>
using namespace objrdf;
PROPERTY(p_0,int);
PROPERTY(p_1,std::string);
CLASS2(C,p_0,p_1);
PROPERTY(p_2,double);
//struct _D;typedef resource<_D,p_2,C> D;
char _D[]="D";
struct D:resource<rdfs_namespace,_D,p_2,D,C>{
void set(p_2){}
};
int main(){
rdf::RDF doc;
doc.insert(C::get_class());
doc.insert(D::get_class());
shared_ptr<C> a_C=new C(std::string("a_C"));
a_C->get<p_0>()=1;
a_C->get<p_1>().t="do";
doc.insert(a_C);
shared_ptr<D> a_D=new D;//(std::string("a_D"));
a_D->get<p_0>()=2;
a_D->get<p_1>().t="re";
a_D->get<p_2>()=3.14;
doc.insert(a_D);
doc.to_turtle(std::cout);
cout<<"here"<<endl;
}
| [
"user@dell830.(none)"
] | user@dell830.(none) |
4acde28ef1deb1120360eb4142300cb90d8cb8b3 | a5ede806cb7034ae5e73bd933acc5268a2f9be07 | /src/ertlibc/stdlib.cpp | 66b91fd56fb83f95d1e28aa28fa816541cdd1eed | [
"MIT"
] | permissive | Ruide/edgelessrt | 430e9785dfa6ad8b45753915ccb3d6abda8f7786 | 29f1a94a724176fff40c7df9a4cedf2bc95ad13a | refs/heads/master | 2023-03-19T03:25:33.295987 | 2021-03-05T11:07:52 | 2021-03-05T12:34:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 402 | cpp | // Copyright (c) Edgeless Systems GmbH.
// Licensed under the MIT License.
#include <cstdlib>
#include <stdexcept>
#include "ertlibc_t.h"
#include "syscalls.h"
using namespace std;
using namespace ert;
extern "C" char* secure_getenv(const char* name)
{
return getenv(name);
}
void sc::exit_group(int status)
{
if (ert_exit_ocall(status) != OE_OK)
throw logic_error("exit_group");
}
| [
"[email protected]"
] | |
cf9811187cfe787c4d042e4f65164fb589b64331 | fee34e5dc60112bb1c1e4847f2c3f3260ce639d3 | /Dungeon Plunderers/BlocksHandler.cpp | 1ed15fe34b5a6035b4938b0d7020358c339a98a8 | [] | no_license | Patryk-Trojak/Dungeon-Plunderers | 292c1547c18db7822854bc2aceb4f5bc0baeb2f9 | a4c70724bc273c2472c001bb0e44a1cc6d2b7759 | refs/heads/main | 2023-06-24T07:14:26.413671 | 2021-07-27T10:40:11 | 2021-07-27T10:40:11 | 372,948,170 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 977 | cpp | #include "pch.h"
#include "BlocksHandler.h"
BlocksHandler::BlocksHandler(std::vector<Block>& blocks,
std::vector<std::vector<Block>::const_iterator>& movingBlocks,
std::vector<Block>& decorationBlocks)
:blocks(blocks),
movingBlocks(movingBlocks),
decorationBlocks(decorationBlocks)
{
initIteratorsToMovingBlocks();
}
void BlocksHandler::moveAllBlocks(float deltaTime)
{
moveBlocks(blocks, deltaTime);
moveBlocks(decorationBlocks, deltaTime);
}
void BlocksHandler::initIteratorsToMovingBlocks()
{
initIteratorsToMovingBlocksFrom(blocks);
initIteratorsToMovingBlocksFrom(decorationBlocks);
}
void BlocksHandler::moveBlocks(std::vector<Block>& blocks, float deltaTime)
{
for (auto& i : blocks)
{
i.move(deltaTime);
}
}
void BlocksHandler::initIteratorsToMovingBlocksFrom(const std::vector<Block>& blocks)
{
for (auto i = blocks.begin(); i < blocks.end(); i++)
{
if (i->getVelocity() != sf::Vector2f(0.f, 0.f))
{
movingBlocks.emplace_back(i);
}
}
}
| [
"[email protected]"
] | |
7d6a99c2acbb8a1cbb761695b800c13e79418de4 | bc9dd00a3135ea1754977b48c24eb441fdb52ace | /src/cls_inheritance/acctabc.h | e75726c0bab164b4eec0dcf18bb5fb1fc805cc7f | [
"MIT"
] | permissive | XiangSugar/Learn_CPP | bba62b8a70a061f230f15a86661feb19849220bb | eb5b2a63f6a5b68c8acdd7cb4ed3c6b5f19f7abe | refs/heads/master | 2022-05-23T05:46:49.103302 | 2020-04-23T14:34:27 | 2020-04-23T14:34:27 | 258,229,637 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,752 | h | // acctabc.h -- bank account classes
#ifndef ACCTABC_H_
#define ACCTABC_H_
#include <iostream>
#include <string>
// Abstract Base Class
class AcctABC
{
private:
std::string fullName;
long acctNum;
double balance;
protected:
struct Formatting
{
std::ios_base::fmtflags flag;
std::streamsize pr;
};
const std::string &FullName() const { return fullName; }
long AcctNum() const { return acctNum; }
Formatting SetFormat() const;
void Restore(Formatting &f) const;
public:
AcctABC(const std::string &s = "Nullbody", long an = -1,
double bal = 0.0);
void Deposit(double amt);
double Balance() const { return balance; };
//纯虚函数,使得该类成为一个抽象基类
virtual void Withdraw(double amt) = 0; // pure virtual function
virtual void ViewAcct() const = 0; // pure virtual function
virtual ~AcctABC() {}
};
// Brass Account Class
class Brass : public AcctABC
{
public:
Brass(const std::string &s = "Nullbody", long an = -1,
double bal = 0.0) : AcctABC(s, an, bal) {}
virtual void Withdraw(double amt);
virtual void ViewAcct() const;
virtual ~Brass() {}
};
//Brass Plus Account Class
class BrassPlus : public AcctABC
{
private:
double maxLoan;
double rate;
double owesBank;
public:
BrassPlus(const std::string &s = "Nullbody", long an = -1,
double bal = 0.0, double ml = 500,
double r = 0.10);
BrassPlus(const Brass &ba, double ml = 500, double r = 0.1);
virtual void ViewAcct() const;
virtual void Withdraw(double amt);
void ResetMax(double m) { maxLoan = m; }
void ResetRate(double r) { rate = r; };
void ResetOwes() { owesBank = 0; }
};
#endif
| [
"[email protected]"
] | |
a25df50223eee7e0a24406e73a035c6157caccea | f83ef53177180ebfeb5a3e230aa29794f52ce1fc | /ACE/ACE_wrappers/TAO/orbsvcs/tests/EC_Custom_Marshal/ECM_Consumer.cpp | 685fcba8db5d2842e9b4565679df59c54a26b09a | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-sun-iiop"
] | permissive | msrLi/portingSources | fe7528b3fd08eed4a1b41383c88ee5c09c2294ef | 57d561730ab27804a3172b33807f2bffbc9e52ae | refs/heads/master | 2021-07-08T01:22:29.604203 | 2019-07-10T13:07:06 | 2019-07-10T13:07:06 | 196,183,165 | 2 | 1 | Apache-2.0 | 2020-10-13T14:30:53 | 2019-07-10T10:16:46 | null | UTF-8 | C++ | false | false | 11,245 | cpp | #include "ECM_Consumer.h"
#include "ECM_Data.h"
#include "orbsvcs/Event_Utilities.h"
#include "orbsvcs/Event_Service_Constants.h"
#include "orbsvcs/Time_Utilities.h"
#include "orbsvcs/CosNamingC.h"
#include "tao/Timeprobe.h"
#include "tao/ORB_Core.h"
#include "tao/CDR.h"
#include "ace/Get_Opt.h"
#include "ace/Auto_Ptr.h"
#include "ace/Sched_Params.h"
#include "ace/OS_NS_errno.h"
#include "ace/OS_NS_unistd.h"
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
Driver driver;
return driver.run (argc, argv);
}
// ****************************************************************
Driver::Driver (void)
: n_consumers_ (1),
event_count_ (100),
event_a_ (ACE_ES_EVENT_UNDEFINED),
event_b_ (ACE_ES_EVENT_UNDEFINED + 1),
pid_file_name_ (0),
recv_count_ (0)
{
}
// ****************************************************************
int
Driver::run (int argc, ACE_TCHAR* argv[])
{
try
{
CORBA::ORB_var orb =
CORBA::ORB_init (argc, argv);
CORBA::Object_var poa_object =
orb->resolve_initial_references("RootPOA");
if (CORBA::is_nil (poa_object.in ()))
ACE_ERROR_RETURN ((LM_ERROR,
" (%P|%t) Unable to initialize the POA.\n"),
1);
PortableServer::POA_var root_poa =
PortableServer::POA::_narrow (poa_object.in ());
PortableServer::POAManager_var poa_manager =
root_poa->the_POAManager ();
if (this->parse_args (argc, argv))
return 1;
ACE_DEBUG ((LM_DEBUG,
"Execution parameters:\n"
" consumers = <%d>\n"
" event count = <%d>\n"
" supplier Event A = <%d>\n"
" supplier Event B = <%d>\n"
" pid file name = <%s>\n",
this->n_consumers_,
this->event_count_,
this->event_a_,
this->event_b_,
this->pid_file_name_?this->pid_file_name_:ACE_TEXT("nil")) );
if (this->pid_file_name_ != 0)
{
FILE* pid = ACE_OS::fopen (this->pid_file_name_, "w");
if (pid != 0)
{
ACE_OS::fprintf (pid, "%ld\n",
static_cast<long> (ACE_OS::getpid ()));
ACE_OS::fclose (pid);
}
}
int min_priority =
ACE_Sched_Params::priority_min (ACE_SCHED_FIFO);
// Enable FIFO scheduling, e.g., RT scheduling class on Solaris.
if (ACE_OS::sched_params (ACE_Sched_Params (ACE_SCHED_FIFO,
min_priority,
ACE_SCOPE_PROCESS)) != 0)
{
if (ACE_OS::last_error () == EPERM)
ACE_DEBUG ((LM_DEBUG,
"%s: user is not superuser, "
"so remain in time-sharing class\n", argv[0]));
else
ACE_ERROR ((LM_ERROR,
"%s: ACE_OS::sched_params failed\n", argv[0]));
}
if (ACE_OS::thr_setprio (min_priority) == -1)
{
ACE_ERROR ((LM_ERROR, "(%P|%t) main thr_setprio failed,"
"no real-time features\n"));
}
CORBA::Object_var naming_obj =
orb->resolve_initial_references ("NameService");
if (CORBA::is_nil (naming_obj.in ()))
ACE_ERROR_RETURN ((LM_ERROR,
" (%P|%t) Unable to get the Naming Service.\n"),
1);
CosNaming::NamingContext_var naming_context =
CosNaming::NamingContext::_narrow (naming_obj.in ());
CosNaming::Name name (1);
name.length (1);
name[0].id = CORBA::string_dup ("EventService");
CORBA::Object_var ec_obj =
naming_context->resolve (name);
RtecEventChannelAdmin::EventChannel_var channel;
if (CORBA::is_nil (ec_obj.in ()))
channel = RtecEventChannelAdmin::EventChannel::_nil ();
else
channel = RtecEventChannelAdmin::EventChannel::_narrow (ec_obj.in ());
poa_manager->activate ();
this->connect_consumers (channel.in ());
ACE_DEBUG ((LM_DEBUG, "connected consumer(s)\n"));
ACE_DEBUG ((LM_DEBUG, "running the test\n"));
orb->run ();
ACE_DEBUG ((LM_DEBUG, "event loop finished\n"));
this->disconnect_consumers ();
channel->destroy ();
}
catch (const CORBA::SystemException& sys_ex)
{
sys_ex._tao_print_exception ("SYS_EX in Consumer");
}
catch (const CORBA::Exception& ex)
{
ex._tao_print_exception ("NON SYS EX in Consumer");
}
return 0;
}
void
Driver::push_consumer (void* /* consumer_cookie */,
ACE_hrtime_t /* arrival */,
const RtecEventComm::EventSet& events)
{
// int ID =
// (reinterpret_cast<Test_Consumer**> (consumer_cookie)
// - this->consumers_);
//
// ACE_DEBUG ((LM_DEBUG, "(%t) events received by consumer %d\n", ID));
if (events.length () == 0)
{
// ACE_DEBUG ((LM_DEBUG, "no events\n"));
return;
}
ACE_GUARD (TAO_SYNCH_MUTEX, ace_mon, this->recv_count_mutex_);
this->recv_count_ += events.length ();
int x = this->event_count_ / 10;
if (this->recv_count_ % x == 0)
{
ACE_DEBUG ((LM_DEBUG,
"ECM_Consumer (%P|%t): %d events received\n",
this->recv_count_));
}
if (this->recv_count_ >= this->event_count_)
{
TAO_ORB_Core_instance ()->orb ()->shutdown ();
}
// ACE_DEBUG ((LM_DEBUG, "%d event(s)\n", events.length ()));
#if (TAO_NO_COPY_OCTET_SEQUENCES == 1)
for (u_int i = 0; i < events.length (); ++i)
{
const RtecEventComm::Event& e = events[i];
if (e.data.payload.mb () == 0)
{
ACE_DEBUG ((LM_DEBUG, "No data in event[%d]\n", i));
continue;
}
// @@ TODO this is a little messy, infortunately we have to
// extract the first byte to determine the byte order, the CDR
// cannot do it for us because in certain cases the byte order
// is not in the encapsulation. Maybe we need another
// constructor for the InputCDR streams (but there are too many
// already!)?
// Note that there is no copying
int byte_order = e.data.payload[0];
ACE_Message_Block* mb =
ACE_Message_Block::duplicate (e.data.payload.mb ());
mb->rd_ptr (1); // skip the byte order
TAO_InputCDR cdr (mb, byte_order);
ECM_IDLData::Info info;
cdr >> info;
ECM_Data other;
cdr >> other;
if (!cdr.good_bit ())
ACE_ERROR ((LM_ERROR, "Problem demarshalling C++ data\n"));
ACE_Message_Block::release (mb);
CORBA::ULong n = info.trajectory.length ();
// ACE_DEBUG ((LM_DEBUG, "Payload contains <%d> elements\n", n));
// ACE_DEBUG ((LM_DEBUG, "Inventory <%s> contains <%d> elements\n",
// other.description.in (),
// other.inventory.current_size ()));
for (CORBA::ULong j = 0; j < n; ++j)
{
ECM_IDLData::Point& p = info.trajectory[j];
if (static_cast<CORBA::ULong>(p.x) != j ||
static_cast<CORBA::ULong>(p.y) != j*j)
{
ACE_DEBUG ((LM_DEBUG,
"invalid data in trajectory[%d] = (%f,%f)\n",
j, p.x, p.y));
}
}
}
#endif /* TAO_NO_COPY_OCTET_SEQUENCES == 1 */
}
void
Driver::connect_consumers (RtecEventChannelAdmin::EventChannel_ptr channel)
{
for (int i = 0; i < this->n_consumers_; ++i)
{
char buf[BUFSIZ];
ACE_OS::sprintf (buf, "consumer_%02d", i);
ACE_NEW (this->consumers_[i],
Test_Consumer (this, this->consumers_ + i));
this->consumers_[i]->connect (this->event_a_,
this->event_b_,
channel);
}
}
void
Driver::disconnect_consumers (void)
{
for (int i = 0; i < this->n_consumers_; ++i)
{
this->consumers_[i]->disconnect ();
}
}
int
Driver::parse_args (int argc, ACE_TCHAR *argv [])
{
ACE_Get_Opt get_opt (argc, argv, ACE_TEXT("dc:n:h:p:"));
int opt;
while ((opt = get_opt ()) != EOF)
{
switch (opt)
{
case 'c':
this->n_consumers_ = ACE_OS::atoi (get_opt.opt_arg ());
break;
case 'n':
this->event_count_ = ACE_OS::atoi (get_opt.opt_arg ());
break;
case 'h':
{
char* aux;
char* arg = ACE_OS::strtok_r (ACE_TEXT_ALWAYS_CHAR(get_opt.opt_arg ()), ",", &aux);
this->event_a_ = ACE_ES_EVENT_UNDEFINED + ACE_OS::atoi (arg);
arg = ACE_OS::strtok_r (0, ",", &aux);
this->event_b_ = ACE_ES_EVENT_UNDEFINED + ACE_OS::atoi (arg);
}
break;
case 'p':
this->pid_file_name_ = get_opt.opt_arg ();
break;
case '?':
default:
ACE_DEBUG ((LM_DEBUG,
"Usage: %s "
"[ORB options] "
"-s <global|local> "
"-a (send data in events) "
"-h <args> "
"-p <pid file name> "
"\n",
argv[0]));
return -1;
}
}
if (this->event_count_ <= 0)
{
ACE_DEBUG ((LM_DEBUG,
"%s: event count (%d) is out of range, "
"reset to default (%d)\n",
argv[0], this->event_count_,
100));
this->event_count_ = 100;
}
if (this->n_consumers_ <= 0)
{
ACE_ERROR_RETURN ((LM_ERROR,
"%s: number of consumers or "
"suppliers out of range\n", argv[0]), -1);
}
return 0;
}
// ****************************************************************
Test_Consumer::Test_Consumer (Driver *driver, void *cookie)
: driver_ (driver),
cookie_ (cookie)
{
}
void
Test_Consumer::connect (int event_a,
int event_b,
RtecEventChannelAdmin::EventChannel_ptr ec)
{
ACE_ConsumerQOS_Factory qos;
qos.start_disjunction_group ();
qos.insert_type (ACE_ES_EVENT_SHUTDOWN, 0);
qos.insert_type (event_a, 0);
qos.insert_type (event_b, 0);
// = Connect as a consumer.
RtecEventChannelAdmin::ConsumerAdmin_var consumer_admin =
ec->for_consumers ();
this->supplier_proxy_ =
consumer_admin->obtain_push_supplier ();
RtecEventComm::PushConsumer_var objref = this->_this ();
this->supplier_proxy_->connect_push_consumer (objref.in (),
qos.get_ConsumerQOS ());
}
void
Test_Consumer::disconnect (void)
{
if (CORBA::is_nil (this->supplier_proxy_.in ()))
return;
RtecEventChannelAdmin::ProxyPushSupplier_var proxy =
this->supplier_proxy_._retn ();
proxy->disconnect_push_supplier ();
}
void
Test_Consumer::push (const RtecEventComm::EventSet& events)
{
ACE_hrtime_t arrival = ACE_OS::gethrtime ();
this->driver_->push_consumer (this->cookie_, arrival, events);
}
void
Test_Consumer::disconnect_push_consumer (void)
{
}
| [
"[email protected]"
] | |
5d36631eaa5b00dcea69ee27c0f4dc9b91b9df21 | 850200edb0c4f5712bc0ad3dd92e7bf8e542d0e8 | /스택(연결리스트).cpp | 4ee46bbbd481ca5483fbb36a2660f875efe5bbfa | [] | no_license | hyejeong99/C_DataStructure | 10a3c9691359705d114d1563bf0fa2020c67318e | b2c03d9bf975d4f098cd0c1c02b2cbba8b0b00dd | refs/heads/main | 2023-03-30T19:30:15.747532 | 2021-04-05T05:48:59 | 2021-04-05T05:48:59 | null | 0 | 0 | null | null | null | null | ISO-8859-7 | C++ | false | false | 1,244 | cpp | #include <iostream>
using namespace std;
typedef int element;
class Node{
public:
element data;
Node *link;
Node(element value){
data=value;
link=NULL;
}
};
Node *StackPointer=NULL;
bool is_empty(){
if(StackPointer==NULL) return true;
else return false;
}
void push(element value){
Node *new_node=new Node(value);
new_node->link=StackPointer;
StackPointer=new_node;
}
element pop(){
if(StackPointer==NULL){
cout<<"STACK UNDERFLOW!!"<<endl;
exit(-1);
}
else{
element top_value=StackPointer->data;
StackPointer=StackPointer->link;
return top_value;
}
}
element peek(){
if(StackPointer==NULL){
cout<<"STACK UNDERFLOW!!"<<endl;
exit(-1);
}
else{
return StackPointer->data;
}
}
void printStack(){
cout<<"###STACK »σΕΒ###"<<endl;
for(Node *ptr=StackPointer; ptr!=NULL;ptr=ptr->link){
cout<<ptr->data<<endl;
}
if(StackPointer==NULL){
cout<<"STACK UNDERFLOW!!"<<endl;
exit(-1);
}
}
void main(){
push(100);printStack();
push(200);printStack();
push(300);printStack();
push(400);printStack();
pop();printStack();
push(500);printStack();
pop();printStack();
pop();printStack();
pop();printStack();
pop();printStack();
} | [
"[email protected]"
] | |
8a830219299eacdf2b558427832de0a527dcd8fb | 23f6ac9cb2e229ca88b814867e209aa2f1f8f1ab | /SmartPtr/SmartPtr.cpp | c89fac2bebaccb621a73287f0481e436dbe90e8f | [] | no_license | dacy413/SmartPtr | 6f7b5a1a314353d33b989c765238f6ee1db829b3 | 4027a576ea692cf55111757ecccf4d4e57cbe0e0 | refs/heads/master | 2016-09-05T16:25:28.116382 | 2015-02-13T06:23:53 | 2015-02-13T06:23:53 | 30,743,155 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,460 | cpp | #include <memory>
#include <iostream>
class Test
{
private:
int age;
std::string name;
public:
Test()
{
std::cout << "Call construct" << std::endl;
}
~Test()
{
std::cout << "Call deconstruct" << std::endl;
}
Test(const Test& t)
{
name = t.name;
age = t.age;
std::cout << "Call copy construct" << std::endl;
}
Test& operator =(const Test& t)
{
name = t.name;
age = t.age;
std::cout << "Call = operator" << std::endl;
return (*this);
}
void showYourself()
{
std::cout <<"My name is "<< name.c_str() << ",I'm " << age << " years." << std::endl;
}
bool setAge(int t_age)
{
age = t_age;
return 1;
}
bool setName(std::string t_name)
{
name = t_name;
return 1;
}
};
std::unique_ptr<Test> test(Test t)
{
std::unique_ptr<Test> p_t( new Test(t)) ;
t.showYourself();
p_t->setAge(25);
return p_t;
}
int main()
{
Test t;
t.setName("Daisy");
t.setAge(24);
std::unique_ptr<Test> tp1(std::move(test(t)));
{
Test t2;
t2 = *tp1.get();
t2.showYourself();
}
tp1.release();
t.~Test();
std::unique_ptr<Test> tp3(new Test());
//下面两种形式就是不可以
//std::unique_ptr<Test> tp4(tp3);
//std::unique_ptr<Test> tp5 = tp3;
std::cout << "END..." << std::endl;
return 1;
}
| [
"[email protected]"
] | |
dc1e56058835ba5472f21ab85b2125d9d8471fac | bd40065fc32921b6ac83df8b5b976a86b6b6a4ff | /src/builtins/loong64/builtins-loong64.cc | 220c9e36718cec1b296be04cd1d02c46181e1654 | [
"BSD-3-Clause",
"SunPro",
"Apache-2.0"
] | permissive | couchbasedeps/v8-mirror | 6e69f9053d15d37befdecec94804b2a50f91dab8 | bf5e3a8a0edfb78c975da04c0f79eb92215255e3 | refs/heads/main | 2022-08-29T05:53:22.946189 | 2022-08-23T13:57:03 | 2022-08-24T09:03:00 | 153,349,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 139,518 | cc | // Copyright 2021 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if V8_TARGET_ARCH_LOONG64
#include "src/api/api-arguments.h"
#include "src/codegen/code-factory.h"
#include "src/codegen/interface-descriptors-inl.h"
#include "src/debug/debug.h"
#include "src/deoptimizer/deoptimizer.h"
#include "src/execution/frame-constants.h"
#include "src/execution/frames.h"
#include "src/logging/counters.h"
// For interpreter_entry_return_pc_offset. TODO(jkummerow): Drop.
#include "src/codegen/loong64/constants-loong64.h"
#include "src/codegen/macro-assembler-inl.h"
#include "src/codegen/register-configuration.h"
#include "src/heap/heap-inl.h"
#include "src/objects/cell.h"
#include "src/objects/foreign.h"
#include "src/objects/heap-number.h"
#include "src/objects/js-generator.h"
#include "src/objects/objects-inl.h"
#include "src/objects/smi.h"
#include "src/runtime/runtime.h"
#if V8_ENABLE_WEBASSEMBLY
#include "src/wasm/wasm-linkage.h"
#include "src/wasm/wasm-objects.h"
#endif // V8_ENABLE_WEBASSEMBLY
namespace v8 {
namespace internal {
#define __ ACCESS_MASM(masm)
void Builtins::Generate_Adaptor(MacroAssembler* masm, Address address) {
__ li(kJavaScriptCallExtraArg1Register, ExternalReference::Create(address));
__ Jump(BUILTIN_CODE(masm->isolate(), AdaptorWithBuiltinExitFrame),
RelocInfo::CODE_TARGET);
}
namespace {
enum class ArgumentsElementType {
kRaw, // Push arguments as they are.
kHandle // Dereference arguments before pushing.
};
void Generate_PushArguments(MacroAssembler* masm, Register array, Register argc,
Register scratch, Register scratch2,
ArgumentsElementType element_type) {
DCHECK(!AreAliased(array, argc, scratch));
Label loop, entry;
__ Sub_d(scratch, argc, Operand(kJSArgcReceiverSlots));
__ Branch(&entry);
__ bind(&loop);
__ Alsl_d(scratch2, scratch, array, kPointerSizeLog2, t7);
__ Ld_d(scratch2, MemOperand(scratch2, 0));
if (element_type == ArgumentsElementType::kHandle) {
__ Ld_d(scratch2, MemOperand(scratch2, 0));
}
__ Push(scratch2);
__ bind(&entry);
__ Add_d(scratch, scratch, Operand(-1));
__ Branch(&loop, greater_equal, scratch, Operand(zero_reg));
}
void Generate_JSBuiltinsConstructStubHelper(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- a0 : number of arguments
// -- a1 : constructor function
// -- a3 : new target
// -- cp : context
// -- ra : return address
// -- sp[...]: constructor arguments
// -----------------------------------
// Enter a construct frame.
{
FrameScope scope(masm, StackFrame::CONSTRUCT);
// Preserve the incoming parameters on the stack.
__ SmiTag(a0);
__ Push(cp, a0);
__ SmiUntag(a0);
// Set up pointer to first argument (skip receiver).
__ Add_d(
t2, fp,
Operand(StandardFrameConstants::kCallerSPOffset + kSystemPointerSize));
// Copy arguments and receiver to the expression stack.
// t2: Pointer to start of arguments.
// a0: Number of arguments.
Generate_PushArguments(masm, t2, a0, t3, t0, ArgumentsElementType::kRaw);
// The receiver for the builtin/api call.
__ PushRoot(RootIndex::kTheHoleValue);
// Call the function.
// a0: number of arguments (untagged)
// a1: constructor function
// a3: new target
__ InvokeFunctionWithNewTarget(a1, a3, a0, InvokeType::kCall);
// Restore context from the frame.
__ Ld_d(cp, MemOperand(fp, ConstructFrameConstants::kContextOffset));
// Restore smi-tagged arguments count from the frame.
__ Ld_d(t3, MemOperand(fp, ConstructFrameConstants::kLengthOffset));
// Leave construct frame.
}
// Remove caller arguments from the stack and return.
__ DropArguments(t3, TurboAssembler::kCountIsSmi,
TurboAssembler::kCountIncludesReceiver, t3);
__ Ret();
}
} // namespace
// The construct stub for ES5 constructor functions and ES6 class constructors.
void Builtins::Generate_JSConstructStubGeneric(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- a0: number of arguments (untagged)
// -- a1: constructor function
// -- a3: new target
// -- cp: context
// -- ra: return address
// -- sp[...]: constructor arguments
// -----------------------------------
// Enter a construct frame.
FrameScope scope(masm, StackFrame::MANUAL);
Label post_instantiation_deopt_entry, not_create_implicit_receiver;
__ EnterFrame(StackFrame::CONSTRUCT);
// Preserve the incoming parameters on the stack.
__ SmiTag(a0);
__ Push(cp, a0, a1);
__ PushRoot(RootIndex::kUndefinedValue);
__ Push(a3);
// ----------- S t a t e -------------
// -- sp[0*kPointerSize]: new target
// -- sp[1*kPointerSize]: padding
// -- a1 and sp[2*kPointerSize]: constructor function
// -- sp[3*kPointerSize]: number of arguments (tagged)
// -- sp[4*kPointerSize]: context
// -----------------------------------
__ Ld_d(t2, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset));
__ Ld_wu(t2, FieldMemOperand(t2, SharedFunctionInfo::kFlagsOffset));
__ DecodeField<SharedFunctionInfo::FunctionKindBits>(t2);
__ JumpIfIsInRange(
t2, static_cast<uint32_t>(FunctionKind::kDefaultDerivedConstructor),
static_cast<uint32_t>(FunctionKind::kDerivedConstructor),
¬_create_implicit_receiver);
// If not derived class constructor: Allocate the new receiver object.
__ Call(BUILTIN_CODE(masm->isolate(), FastNewObject), RelocInfo::CODE_TARGET);
__ Branch(&post_instantiation_deopt_entry);
// Else: use TheHoleValue as receiver for constructor call
__ bind(¬_create_implicit_receiver);
__ LoadRoot(a0, RootIndex::kTheHoleValue);
// ----------- S t a t e -------------
// -- a0: receiver
// -- Slot 4 / sp[0*kPointerSize]: new target
// -- Slot 3 / sp[1*kPointerSize]: padding
// -- Slot 2 / sp[2*kPointerSize]: constructor function
// -- Slot 1 / sp[3*kPointerSize]: number of arguments (tagged)
// -- Slot 0 / sp[4*kPointerSize]: context
// -----------------------------------
// Deoptimizer enters here.
masm->isolate()->heap()->SetConstructStubCreateDeoptPCOffset(
masm->pc_offset());
__ bind(&post_instantiation_deopt_entry);
// Restore new target.
__ Pop(a3);
// Push the allocated receiver to the stack.
__ Push(a0);
// We need two copies because we may have to return the original one
// and the calling conventions dictate that the called function pops the
// receiver. The second copy is pushed after the arguments, we saved in a6
// since a0 will store the return value of callRuntime.
__ mov(a6, a0);
// Set up pointer to last argument.
__ Add_d(
t2, fp,
Operand(StandardFrameConstants::kCallerSPOffset + kSystemPointerSize));
// ----------- S t a t e -------------
// -- r3: new target
// -- sp[0*kPointerSize]: implicit receiver
// -- sp[1*kPointerSize]: implicit receiver
// -- sp[2*kPointerSize]: padding
// -- sp[3*kPointerSize]: constructor function
// -- sp[4*kPointerSize]: number of arguments (tagged)
// -- sp[5*kPointerSize]: context
// -----------------------------------
// Restore constructor function and argument count.
__ Ld_d(a1, MemOperand(fp, ConstructFrameConstants::kConstructorOffset));
__ Ld_d(a0, MemOperand(fp, ConstructFrameConstants::kLengthOffset));
__ SmiUntag(a0);
Label stack_overflow;
__ StackOverflowCheck(a0, t0, t1, &stack_overflow);
// TODO(victorgomes): When the arguments adaptor is completely removed, we
// should get the formal parameter count and copy the arguments in its
// correct position (including any undefined), instead of delaying this to
// InvokeFunction.
// Copy arguments and receiver to the expression stack.
// t2: Pointer to start of argument.
// a0: Number of arguments.
Generate_PushArguments(masm, t2, a0, t0, t1, ArgumentsElementType::kRaw);
// We need two copies because we may have to return the original one
// and the calling conventions dictate that the called function pops the
// receiver. The second copy is pushed after the arguments,
__ Push(a6);
// Call the function.
__ InvokeFunctionWithNewTarget(a1, a3, a0, InvokeType::kCall);
// ----------- S t a t e -------------
// -- s0: constructor result
// -- sp[0*kPointerSize]: implicit receiver
// -- sp[1*kPointerSize]: padding
// -- sp[2*kPointerSize]: constructor function
// -- sp[3*kPointerSize]: number of arguments
// -- sp[4*kPointerSize]: context
// -----------------------------------
// Store offset of return address for deoptimizer.
masm->isolate()->heap()->SetConstructStubInvokeDeoptPCOffset(
masm->pc_offset());
// If the result is an object (in the ECMA sense), we should get rid
// of the receiver and use the result; see ECMA-262 section 13.2.2-7
// on page 74.
Label use_receiver, do_throw, leave_and_return, check_receiver;
// If the result is undefined, we jump out to using the implicit receiver.
__ JumpIfNotRoot(a0, RootIndex::kUndefinedValue, &check_receiver);
// Otherwise we do a smi check and fall through to check if the return value
// is a valid receiver.
// Throw away the result of the constructor invocation and use the
// on-stack receiver as the result.
__ bind(&use_receiver);
__ Ld_d(a0, MemOperand(sp, 0 * kPointerSize));
__ JumpIfRoot(a0, RootIndex::kTheHoleValue, &do_throw);
__ bind(&leave_and_return);
// Restore smi-tagged arguments count from the frame.
__ Ld_d(a1, MemOperand(fp, ConstructFrameConstants::kLengthOffset));
// Leave construct frame.
__ LeaveFrame(StackFrame::CONSTRUCT);
// Remove caller arguments from the stack and return.
__ DropArguments(a1, TurboAssembler::kCountIsSmi,
TurboAssembler::kCountIncludesReceiver, a4);
__ Ret();
__ bind(&check_receiver);
__ JumpIfSmi(a0, &use_receiver);
// If the type of the result (stored in its map) is less than
// FIRST_JS_RECEIVER_TYPE, it is not an object in the ECMA sense.
__ GetObjectType(a0, t2, t2);
static_assert(LAST_JS_RECEIVER_TYPE == LAST_TYPE);
__ Branch(&leave_and_return, greater_equal, t2,
Operand(FIRST_JS_RECEIVER_TYPE));
__ Branch(&use_receiver);
__ bind(&do_throw);
// Restore the context from the frame.
__ Ld_d(cp, MemOperand(fp, ConstructFrameConstants::kContextOffset));
__ CallRuntime(Runtime::kThrowConstructorReturnedNonObject);
__ break_(0xCC);
__ bind(&stack_overflow);
// Restore the context from the frame.
__ Ld_d(cp, MemOperand(fp, ConstructFrameConstants::kContextOffset));
__ CallRuntime(Runtime::kThrowStackOverflow);
__ break_(0xCC);
}
void Builtins::Generate_JSBuiltinsConstructStub(MacroAssembler* masm) {
Generate_JSBuiltinsConstructStubHelper(masm);
}
static void AssertCodeIsBaseline(MacroAssembler* masm, Register code,
Register scratch) {
DCHECK(!AreAliased(code, scratch));
// Verify that the code kind is baseline code via the CodeKind.
__ Ld_d(scratch, FieldMemOperand(code, Code::kFlagsOffset));
__ DecodeField<Code::KindField>(scratch);
__ Assert(eq, AbortReason::kExpectedBaselineData, scratch,
Operand(static_cast<int>(CodeKind::BASELINE)));
}
// TODO(v8:11429): Add a path for "not_compiled" and unify the two uses under
// the more general dispatch.
static void GetSharedFunctionInfoBytecodeOrBaseline(MacroAssembler* masm,
Register sfi_data,
Register scratch1,
Label* is_baseline) {
Label done;
__ GetObjectType(sfi_data, scratch1, scratch1);
if (FLAG_debug_code) {
Label not_baseline;
__ Branch(¬_baseline, ne, scratch1, Operand(CODET_TYPE));
AssertCodeIsBaseline(masm, sfi_data, scratch1);
__ Branch(is_baseline);
__ bind(¬_baseline);
} else {
__ Branch(is_baseline, eq, scratch1, Operand(CODET_TYPE));
}
__ Branch(&done, ne, scratch1, Operand(INTERPRETER_DATA_TYPE));
__ Ld_d(sfi_data,
FieldMemOperand(sfi_data, InterpreterData::kBytecodeArrayOffset));
__ bind(&done);
}
// static
void Builtins::Generate_ResumeGeneratorTrampoline(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- a0 : the value to pass to the generator
// -- a1 : the JSGeneratorObject to resume
// -- ra : return address
// -----------------------------------
// Store input value into generator object.
__ St_d(a0, FieldMemOperand(a1, JSGeneratorObject::kInputOrDebugPosOffset));
__ RecordWriteField(a1, JSGeneratorObject::kInputOrDebugPosOffset, a0,
kRAHasNotBeenSaved, SaveFPRegsMode::kIgnore);
// Check that a1 is still valid, RecordWrite might have clobbered it.
__ AssertGeneratorObject(a1);
// Load suspended function and context.
__ Ld_d(a4, FieldMemOperand(a1, JSGeneratorObject::kFunctionOffset));
__ Ld_d(cp, FieldMemOperand(a4, JSFunction::kContextOffset));
// Flood function if we are stepping.
Label prepare_step_in_if_stepping, prepare_step_in_suspended_generator;
Label stepping_prepared;
ExternalReference debug_hook =
ExternalReference::debug_hook_on_function_call_address(masm->isolate());
__ li(a5, debug_hook);
__ Ld_b(a5, MemOperand(a5, 0));
__ Branch(&prepare_step_in_if_stepping, ne, a5, Operand(zero_reg));
// Flood function if we need to continue stepping in the suspended generator.
ExternalReference debug_suspended_generator =
ExternalReference::debug_suspended_generator_address(masm->isolate());
__ li(a5, debug_suspended_generator);
__ Ld_d(a5, MemOperand(a5, 0));
__ Branch(&prepare_step_in_suspended_generator, eq, a1, Operand(a5));
__ bind(&stepping_prepared);
// Check the stack for overflow. We are not trying to catch interruptions
// (i.e. debug break and preemption) here, so check the "real stack limit".
Label stack_overflow;
__ LoadStackLimit(kScratchReg,
MacroAssembler::StackLimitKind::kRealStackLimit);
__ Branch(&stack_overflow, lo, sp, Operand(kScratchReg));
// ----------- S t a t e -------------
// -- a1 : the JSGeneratorObject to resume
// -- a4 : generator function
// -- cp : generator context
// -- ra : return address
// -----------------------------------
// Push holes for arguments to generator function. Since the parser forced
// context allocation for any variables in generators, the actual argument
// values have already been copied into the context and these dummy values
// will never be used.
__ Ld_d(a3, FieldMemOperand(a4, JSFunction::kSharedFunctionInfoOffset));
__ Ld_hu(
a3, FieldMemOperand(a3, SharedFunctionInfo::kFormalParameterCountOffset));
__ Sub_d(a3, a3, Operand(kJSArgcReceiverSlots));
__ Ld_d(t1, FieldMemOperand(
a1, JSGeneratorObject::kParametersAndRegistersOffset));
{
Label done_loop, loop;
__ bind(&loop);
__ Sub_d(a3, a3, Operand(1));
__ Branch(&done_loop, lt, a3, Operand(zero_reg));
__ Alsl_d(kScratchReg, a3, t1, kPointerSizeLog2, t7);
__ Ld_d(kScratchReg, FieldMemOperand(kScratchReg, FixedArray::kHeaderSize));
__ Push(kScratchReg);
__ Branch(&loop);
__ bind(&done_loop);
// Push receiver.
__ Ld_d(kScratchReg,
FieldMemOperand(a1, JSGeneratorObject::kReceiverOffset));
__ Push(kScratchReg);
}
// Underlying function needs to have bytecode available.
if (FLAG_debug_code) {
Label is_baseline;
__ Ld_d(a3, FieldMemOperand(a4, JSFunction::kSharedFunctionInfoOffset));
__ Ld_d(a3, FieldMemOperand(a3, SharedFunctionInfo::kFunctionDataOffset));
GetSharedFunctionInfoBytecodeOrBaseline(masm, a3, t5, &is_baseline);
__ GetObjectType(a3, a3, a3);
__ Assert(eq, AbortReason::kMissingBytecodeArray, a3,
Operand(BYTECODE_ARRAY_TYPE));
__ bind(&is_baseline);
}
// Resume (Ignition/TurboFan) generator object.
{
__ Ld_d(a0, FieldMemOperand(a4, JSFunction::kSharedFunctionInfoOffset));
__ Ld_hu(a0, FieldMemOperand(
a0, SharedFunctionInfo::kFormalParameterCountOffset));
// We abuse new.target both to indicate that this is a resume call and to
// pass in the generator object. In ordinary calls, new.target is always
// undefined because generator functions are non-constructable.
__ Move(a3, a1);
__ Move(a1, a4);
static_assert(kJavaScriptCallCodeStartRegister == a2, "ABI mismatch");
__ Ld_d(a2, FieldMemOperand(a1, JSFunction::kCodeOffset));
__ JumpCodeObject(a2);
}
__ bind(&prepare_step_in_if_stepping);
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ Push(a1, a4);
// Push hole as receiver since we do not use it for stepping.
__ PushRoot(RootIndex::kTheHoleValue);
__ CallRuntime(Runtime::kDebugOnFunctionCall);
__ Pop(a1);
}
__ Ld_d(a4, FieldMemOperand(a1, JSGeneratorObject::kFunctionOffset));
__ Branch(&stepping_prepared);
__ bind(&prepare_step_in_suspended_generator);
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ Push(a1);
__ CallRuntime(Runtime::kDebugPrepareStepInSuspendedGenerator);
__ Pop(a1);
}
__ Ld_d(a4, FieldMemOperand(a1, JSGeneratorObject::kFunctionOffset));
__ Branch(&stepping_prepared);
__ bind(&stack_overflow);
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ CallRuntime(Runtime::kThrowStackOverflow);
__ break_(0xCC); // This should be unreachable.
}
}
void Builtins::Generate_ConstructedNonConstructable(MacroAssembler* masm) {
FrameScope scope(masm, StackFrame::INTERNAL);
__ Push(a1);
__ CallRuntime(Runtime::kThrowConstructedNonConstructable);
}
// Clobbers scratch1 and scratch2; preserves all other registers.
static void Generate_CheckStackOverflow(MacroAssembler* masm, Register argc,
Register scratch1, Register scratch2) {
// Check the stack for overflow. We are not trying to catch
// interruptions (e.g. debug break and preemption) here, so the "real stack
// limit" is checked.
Label okay;
__ LoadStackLimit(scratch1, MacroAssembler::StackLimitKind::kRealStackLimit);
// Make a2 the space we have left. The stack might already be overflowed
// here which will cause r2 to become negative.
__ sub_d(scratch1, sp, scratch1);
// Check if the arguments will overflow the stack.
__ slli_d(scratch2, argc, kPointerSizeLog2);
__ Branch(&okay, gt, scratch1, Operand(scratch2)); // Signed comparison.
// Out of stack space.
__ CallRuntime(Runtime::kThrowStackOverflow);
__ bind(&okay);
}
namespace {
// Called with the native C calling convention. The corresponding function
// signature is either:
//
// using JSEntryFunction = GeneratedCode<Address(
// Address root_register_value, Address new_target, Address target,
// Address receiver, intptr_t argc, Address** args)>;
// or
// using JSEntryFunction = GeneratedCode<Address(
// Address root_register_value, MicrotaskQueue* microtask_queue)>;
void Generate_JSEntryVariant(MacroAssembler* masm, StackFrame::Type type,
Builtin entry_trampoline) {
Label invoke, handler_entry, exit;
{
NoRootArrayScope no_root_array(masm);
// Registers:
// either
// a0: root register value
// a1: entry address
// a2: function
// a3: receiver
// a4: argc
// a5: argv
// or
// a0: root register value
// a1: microtask_queue
// Save callee saved registers on the stack.
__ MultiPush(kCalleeSaved | ra);
// Save callee-saved FPU registers.
__ MultiPushFPU(kCalleeSavedFPU);
// Set up the reserved register for 0.0.
__ Move(kDoubleRegZero, 0.0);
// Initialize the root register.
// C calling convention. The first argument is passed in a0.
__ mov(kRootRegister, a0);
}
// a1: entry address
// a2: function
// a3: receiver
// a4: argc
// a5: argv
// We build an EntryFrame.
__ li(s1, Operand(-1)); // Push a bad frame pointer to fail if it is used.
__ li(s2, Operand(StackFrame::TypeToMarker(type)));
__ li(s3, Operand(StackFrame::TypeToMarker(type)));
ExternalReference c_entry_fp = ExternalReference::Create(
IsolateAddressId::kCEntryFPAddress, masm->isolate());
__ li(s5, c_entry_fp);
__ Ld_d(s4, MemOperand(s5, 0));
__ Push(s1, s2, s3, s4);
// Clear c_entry_fp, now we've pushed its previous value to the stack.
// If the c_entry_fp is not already zero and we don't clear it, the
// SafeStackFrameIterator will assume we are executing C++ and miss the JS
// frames on top.
__ St_d(zero_reg, MemOperand(s5, 0));
// Set up frame pointer for the frame to be pushed.
__ addi_d(fp, sp, -EntryFrameConstants::kCallerFPOffset);
// Registers:
// either
// a1: entry address
// a2: function
// a3: receiver
// a4: argc
// a5: argv
// or
// a1: microtask_queue
//
// Stack:
// caller fp |
// function slot | entry frame
// context slot |
// bad fp (0xFF...F) |
// callee saved registers + ra
// [ O32: 4 args slots]
// args
// If this is the outermost JS call, set js_entry_sp value.
Label non_outermost_js;
ExternalReference js_entry_sp = ExternalReference::Create(
IsolateAddressId::kJSEntrySPAddress, masm->isolate());
__ li(s1, js_entry_sp);
__ Ld_d(s2, MemOperand(s1, 0));
__ Branch(&non_outermost_js, ne, s2, Operand(zero_reg));
__ St_d(fp, MemOperand(s1, 0));
__ li(s3, Operand(StackFrame::OUTERMOST_JSENTRY_FRAME));
Label cont;
__ b(&cont);
__ nop(); // Branch delay slot nop.
__ bind(&non_outermost_js);
__ li(s3, Operand(StackFrame::INNER_JSENTRY_FRAME));
__ bind(&cont);
__ Push(s3);
// Jump to a faked try block that does the invoke, with a faked catch
// block that sets the pending exception.
__ jmp(&invoke);
__ bind(&handler_entry);
// Store the current pc as the handler offset. It's used later to create the
// handler table.
masm->isolate()->builtins()->SetJSEntryHandlerOffset(handler_entry.pos());
// Caught exception: Store result (exception) in the pending exception
// field in the JSEnv and return a failure sentinel. Coming in here the
// fp will be invalid because the PushStackHandler below sets it to 0 to
// signal the existence of the JSEntry frame.
__ li(s1, ExternalReference::Create(
IsolateAddressId::kPendingExceptionAddress, masm->isolate()));
__ St_d(a0,
MemOperand(s1, 0)); // We come back from 'invoke'. result is in a0.
__ LoadRoot(a0, RootIndex::kException);
__ b(&exit); // b exposes branch delay slot.
__ nop(); // Branch delay slot nop.
// Invoke: Link this frame into the handler chain.
__ bind(&invoke);
__ PushStackHandler();
// If an exception not caught by another handler occurs, this handler
// returns control to the code after the bal(&invoke) above, which
// restores all kCalleeSaved registers (including cp and fp) to their
// saved values before returning a failure to C.
//
// Registers:
// either
// a0: root register value
// a1: entry address
// a2: function
// a3: receiver
// a4: argc
// a5: argv
// or
// a0: root register value
// a1: microtask_queue
//
// Stack:
// handler frame
// entry frame
// callee saved registers + ra
// [ O32: 4 args slots]
// args
//
// Invoke the function by calling through JS entry trampoline builtin and
// pop the faked function when we return.
Handle<Code> trampoline_code =
masm->isolate()->builtins()->code_handle(entry_trampoline);
__ Call(trampoline_code, RelocInfo::CODE_TARGET);
// Unlink this frame from the handler chain.
__ PopStackHandler();
__ bind(&exit); // a0 holds result
// Check if the current stack frame is marked as the outermost JS frame.
Label non_outermost_js_2;
__ Pop(a5);
__ Branch(&non_outermost_js_2, ne, a5,
Operand(StackFrame::OUTERMOST_JSENTRY_FRAME));
__ li(a5, js_entry_sp);
__ St_d(zero_reg, MemOperand(a5, 0));
__ bind(&non_outermost_js_2);
// Restore the top frame descriptors from the stack.
__ Pop(a5);
__ li(a4, ExternalReference::Create(IsolateAddressId::kCEntryFPAddress,
masm->isolate()));
__ St_d(a5, MemOperand(a4, 0));
// Reset the stack to the callee saved registers.
__ addi_d(sp, sp, -EntryFrameConstants::kCallerFPOffset);
// Restore callee-saved fpu registers.
__ MultiPopFPU(kCalleeSavedFPU);
// Restore callee saved registers from the stack.
__ MultiPop(kCalleeSaved | ra);
// Return.
__ Jump(ra);
}
} // namespace
void Builtins::Generate_JSEntry(MacroAssembler* masm) {
Generate_JSEntryVariant(masm, StackFrame::ENTRY, Builtin::kJSEntryTrampoline);
}
void Builtins::Generate_JSConstructEntry(MacroAssembler* masm) {
Generate_JSEntryVariant(masm, StackFrame::CONSTRUCT_ENTRY,
Builtin::kJSConstructEntryTrampoline);
}
void Builtins::Generate_JSRunMicrotasksEntry(MacroAssembler* masm) {
Generate_JSEntryVariant(masm, StackFrame::ENTRY,
Builtin::kRunMicrotasksTrampoline);
}
static void Generate_JSEntryTrampolineHelper(MacroAssembler* masm,
bool is_construct) {
// ----------- S t a t e -------------
// -- a1: new.target
// -- a2: function
// -- a3: receiver_pointer
// -- a4: argc
// -- a5: argv
// -----------------------------------
// Enter an internal frame.
{
FrameScope scope(masm, StackFrame::INTERNAL);
// Setup the context (we need to use the caller context from the isolate).
ExternalReference context_address = ExternalReference::Create(
IsolateAddressId::kContextAddress, masm->isolate());
__ li(cp, context_address);
__ Ld_d(cp, MemOperand(cp, 0));
// Push the function and the receiver onto the stack.
__ Push(a2);
// Check if we have enough stack space to push all arguments.
__ mov(a6, a4);
Generate_CheckStackOverflow(masm, a6, a0, s2);
// Copy arguments to the stack.
// a4: argc
// a5: argv, i.e. points to first arg
Generate_PushArguments(masm, a5, a4, s1, s2, ArgumentsElementType::kHandle);
// Push the receive.
__ Push(a3);
// a0: argc
// a1: function
// a3: new.target
__ mov(a3, a1);
__ mov(a1, a2);
__ mov(a0, a4);
// Initialize all JavaScript callee-saved registers, since they will be seen
// by the garbage collector as part of handlers.
__ LoadRoot(a4, RootIndex::kUndefinedValue);
__ mov(a5, a4);
__ mov(s1, a4);
__ mov(s2, a4);
__ mov(s3, a4);
__ mov(s4, a4);
__ mov(s5, a4);
// s6 holds the root address. Do not clobber.
// s7 is cp. Do not init.
// Invoke the code.
Handle<Code> builtin = is_construct
? BUILTIN_CODE(masm->isolate(), Construct)
: masm->isolate()->builtins()->Call();
__ Call(builtin, RelocInfo::CODE_TARGET);
// Leave internal frame.
}
__ Jump(ra);
}
void Builtins::Generate_JSEntryTrampoline(MacroAssembler* masm) {
Generate_JSEntryTrampolineHelper(masm, false);
}
void Builtins::Generate_JSConstructEntryTrampoline(MacroAssembler* masm) {
Generate_JSEntryTrampolineHelper(masm, true);
}
void Builtins::Generate_RunMicrotasksTrampoline(MacroAssembler* masm) {
// a1: microtask_queue
__ mov(RunMicrotasksDescriptor::MicrotaskQueueRegister(), a1);
__ Jump(BUILTIN_CODE(masm->isolate(), RunMicrotasks), RelocInfo::CODE_TARGET);
}
static void LeaveInterpreterFrame(MacroAssembler* masm, Register scratch1,
Register scratch2) {
Register params_size = scratch1;
// Get the size of the formal parameters + receiver (in bytes).
__ Ld_d(params_size,
MemOperand(fp, InterpreterFrameConstants::kBytecodeArrayFromFp));
__ Ld_w(params_size,
FieldMemOperand(params_size, BytecodeArray::kParameterSizeOffset));
Register actual_params_size = scratch2;
// Compute the size of the actual parameters + receiver (in bytes).
__ Ld_d(actual_params_size,
MemOperand(fp, StandardFrameConstants::kArgCOffset));
__ slli_d(actual_params_size, actual_params_size, kPointerSizeLog2);
// If actual is bigger than formal, then we should use it to free up the stack
// arguments.
__ slt(t2, params_size, actual_params_size);
__ Movn(params_size, actual_params_size, t2);
// Leave the frame (also dropping the register file).
__ LeaveFrame(StackFrame::INTERPRETED);
// Drop receiver + arguments.
__ DropArguments(params_size, TurboAssembler::kCountIsBytes,
TurboAssembler::kCountIncludesReceiver);
}
// Advance the current bytecode offset. This simulates what all bytecode
// handlers do upon completion of the underlying operation. Will bail out to a
// label if the bytecode (without prefix) is a return bytecode. Will not advance
// the bytecode offset if the current bytecode is a JumpLoop, instead just
// re-executing the JumpLoop to jump to the correct bytecode.
static void AdvanceBytecodeOffsetOrReturn(MacroAssembler* masm,
Register bytecode_array,
Register bytecode_offset,
Register bytecode, Register scratch1,
Register scratch2, Register scratch3,
Label* if_return) {
Register bytecode_size_table = scratch1;
// The bytecode offset value will be increased by one in wide and extra wide
// cases. In the case of having a wide or extra wide JumpLoop bytecode, we
// will restore the original bytecode. In order to simplify the code, we have
// a backup of it.
Register original_bytecode_offset = scratch3;
DCHECK(!AreAliased(bytecode_array, bytecode_offset, bytecode,
bytecode_size_table, original_bytecode_offset));
__ Move(original_bytecode_offset, bytecode_offset);
__ li(bytecode_size_table, ExternalReference::bytecode_size_table_address());
// Check if the bytecode is a Wide or ExtraWide prefix bytecode.
Label process_bytecode, extra_wide;
static_assert(0 == static_cast<int>(interpreter::Bytecode::kWide));
static_assert(1 == static_cast<int>(interpreter::Bytecode::kExtraWide));
static_assert(2 == static_cast<int>(interpreter::Bytecode::kDebugBreakWide));
static_assert(3 ==
static_cast<int>(interpreter::Bytecode::kDebugBreakExtraWide));
__ Branch(&process_bytecode, hi, bytecode, Operand(3));
__ And(scratch2, bytecode, Operand(1));
__ Branch(&extra_wide, ne, scratch2, Operand(zero_reg));
// Load the next bytecode and update table to the wide scaled table.
__ Add_d(bytecode_offset, bytecode_offset, Operand(1));
__ Add_d(scratch2, bytecode_array, bytecode_offset);
__ Ld_bu(bytecode, MemOperand(scratch2, 0));
__ Add_d(bytecode_size_table, bytecode_size_table,
Operand(kByteSize * interpreter::Bytecodes::kBytecodeCount));
__ jmp(&process_bytecode);
__ bind(&extra_wide);
// Load the next bytecode and update table to the extra wide scaled table.
__ Add_d(bytecode_offset, bytecode_offset, Operand(1));
__ Add_d(scratch2, bytecode_array, bytecode_offset);
__ Ld_bu(bytecode, MemOperand(scratch2, 0));
__ Add_d(bytecode_size_table, bytecode_size_table,
Operand(2 * kByteSize * interpreter::Bytecodes::kBytecodeCount));
__ bind(&process_bytecode);
// Bailout to the return label if this is a return bytecode.
#define JUMP_IF_EQUAL(NAME) \
__ Branch(if_return, eq, bytecode, \
Operand(static_cast<int>(interpreter::Bytecode::k##NAME)));
RETURN_BYTECODE_LIST(JUMP_IF_EQUAL)
#undef JUMP_IF_EQUAL
// If this is a JumpLoop, re-execute it to perform the jump to the beginning
// of the loop.
Label end, not_jump_loop;
__ Branch(¬_jump_loop, ne, bytecode,
Operand(static_cast<int>(interpreter::Bytecode::kJumpLoop)));
// We need to restore the original bytecode_offset since we might have
// increased it to skip the wide / extra-wide prefix bytecode.
__ Move(bytecode_offset, original_bytecode_offset);
__ jmp(&end);
__ bind(¬_jump_loop);
// Otherwise, load the size of the current bytecode and advance the offset.
__ Add_d(scratch2, bytecode_size_table, bytecode);
__ Ld_b(scratch2, MemOperand(scratch2, 0));
__ Add_d(bytecode_offset, bytecode_offset, scratch2);
__ bind(&end);
}
namespace {
void ResetBytecodeAge(MacroAssembler* masm, Register bytecode_array) {
__ St_h(zero_reg,
FieldMemOperand(bytecode_array, BytecodeArray::kBytecodeAgeOffset));
}
void ResetFeedbackVectorOsrUrgency(MacroAssembler* masm,
Register feedback_vector, Register scratch) {
DCHECK(!AreAliased(feedback_vector, scratch));
__ Ld_bu(scratch,
FieldMemOperand(feedback_vector, FeedbackVector::kOsrStateOffset));
__ And(scratch, scratch,
Operand(FeedbackVector::MaybeHasOptimizedOsrCodeBit::kMask));
__ St_b(scratch,
FieldMemOperand(feedback_vector, FeedbackVector::kOsrStateOffset));
}
} // namespace
// static
void Builtins::Generate_BaselineOutOfLinePrologue(MacroAssembler* masm) {
UseScratchRegisterScope temps(masm);
temps.Include({s1, s2});
temps.Exclude({t7});
auto descriptor =
Builtins::CallInterfaceDescriptorFor(Builtin::kBaselineOutOfLinePrologue);
Register closure = descriptor.GetRegisterParameter(
BaselineOutOfLinePrologueDescriptor::kClosure);
// Load the feedback vector from the closure.
Register feedback_vector = temps.Acquire();
__ Ld_d(feedback_vector,
FieldMemOperand(closure, JSFunction::kFeedbackCellOffset));
__ Ld_d(feedback_vector,
FieldMemOperand(feedback_vector, Cell::kValueOffset));
{
UseScratchRegisterScope temps(masm);
Register scratch = temps.Acquire();
__ AssertFeedbackVector(feedback_vector, scratch);
}
// Check for an tiering state.
Label has_optimized_code_or_state;
Register optimization_state = no_reg;
{
UseScratchRegisterScope temps(masm);
optimization_state = temps.Acquire();
// optimization_state will be used only in |has_optimized_code_or_state|
// and outside it can be reused.
__ LoadTieringStateAndJumpIfNeedsProcessing(
optimization_state, feedback_vector, &has_optimized_code_or_state);
}
{
UseScratchRegisterScope temps(masm);
ResetFeedbackVectorOsrUrgency(masm, feedback_vector, temps.Acquire());
}
// Increment invocation count for the function.
{
UseScratchRegisterScope temps(masm);
Register invocation_count = temps.Acquire();
__ Ld_w(invocation_count,
FieldMemOperand(feedback_vector,
FeedbackVector::kInvocationCountOffset));
__ Add_w(invocation_count, invocation_count, Operand(1));
__ St_w(invocation_count,
FieldMemOperand(feedback_vector,
FeedbackVector::kInvocationCountOffset));
}
FrameScope frame_scope(masm, StackFrame::MANUAL);
{
ASM_CODE_COMMENT_STRING(masm, "Frame Setup");
// Normally the first thing we'd do here is Push(ra, fp), but we already
// entered the frame in BaselineCompiler::Prologue, as we had to use the
// value ra before the call to this BaselineOutOfLinePrologue builtin.
Register callee_context = descriptor.GetRegisterParameter(
BaselineOutOfLinePrologueDescriptor::kCalleeContext);
Register callee_js_function = descriptor.GetRegisterParameter(
BaselineOutOfLinePrologueDescriptor::kClosure);
__ Push(callee_context, callee_js_function);
DCHECK_EQ(callee_js_function, kJavaScriptCallTargetRegister);
DCHECK_EQ(callee_js_function, kJSFunctionRegister);
Register argc = descriptor.GetRegisterParameter(
BaselineOutOfLinePrologueDescriptor::kJavaScriptCallArgCount);
// We'll use the bytecode for both code age/OSR resetting, and pushing onto
// the frame, so load it into a register.
Register bytecode_array = descriptor.GetRegisterParameter(
BaselineOutOfLinePrologueDescriptor::kInterpreterBytecodeArray);
ResetBytecodeAge(masm, bytecode_array);
__ Push(argc, bytecode_array);
// Baseline code frames store the feedback vector where interpreter would
// store the bytecode offset.
{
UseScratchRegisterScope temps(masm);
Register invocation_count = temps.Acquire();
__ AssertFeedbackVector(feedback_vector, invocation_count);
}
// Our stack is currently aligned. We have have to push something along with
// the feedback vector to keep it that way -- we may as well start
// initialising the register frame.
// TODO(v8:11429,leszeks): Consider guaranteeing that this call leaves
// `undefined` in the accumulator register, to skip the load in the baseline
// code.
__ Push(feedback_vector);
}
Label call_stack_guard;
Register frame_size = descriptor.GetRegisterParameter(
BaselineOutOfLinePrologueDescriptor::kStackFrameSize);
{
ASM_CODE_COMMENT_STRING(masm, "Stack/interrupt check");
// Stack check. This folds the checks for both the interrupt stack limit
// check and the real stack limit into one by just checking for the
// interrupt limit. The interrupt limit is either equal to the real stack
// limit or tighter. By ensuring we have space until that limit after
// building the frame we can quickly precheck both at once.
UseScratchRegisterScope temps(masm);
Register sp_minus_frame_size = temps.Acquire();
__ Sub_d(sp_minus_frame_size, sp, frame_size);
Register interrupt_limit = temps.Acquire();
__ LoadStackLimit(interrupt_limit,
MacroAssembler::StackLimitKind::kInterruptStackLimit);
__ Branch(&call_stack_guard, Uless, sp_minus_frame_size,
Operand(interrupt_limit));
}
// Do "fast" return to the caller pc in ra.
// TODO(v8:11429): Document this frame setup better.
__ Ret();
__ bind(&has_optimized_code_or_state);
{
ASM_CODE_COMMENT_STRING(masm, "Optimized marker check");
UseScratchRegisterScope temps(masm);
temps.Exclude(optimization_state);
// Ensure the optimization_state is not allocated again.
// Drop the frame created by the baseline call.
__ Pop(ra, fp);
__ MaybeOptimizeCodeOrTailCallOptimizedCodeSlot(optimization_state,
feedback_vector);
__ Trap();
}
__ bind(&call_stack_guard);
{
ASM_CODE_COMMENT_STRING(masm, "Stack/interrupt call");
FrameScope frame_scope(masm, StackFrame::INTERNAL);
// Save incoming new target or generator
__ Push(kJavaScriptCallNewTargetRegister);
__ SmiTag(frame_size);
__ Push(frame_size);
__ CallRuntime(Runtime::kStackGuardWithGap);
__ Pop(kJavaScriptCallNewTargetRegister);
}
__ Ret();
temps.Exclude({s1, s2});
}
// Generate code for entering a JS function with the interpreter.
// On entry to the function the receiver and arguments have been pushed on the
// stack left to right.
//
// The live registers are:
// o a0 : actual argument count
// o a1: the JS function object being called.
// o a3: the incoming new target or generator object
// o cp: our context
// o fp: the caller's frame pointer
// o sp: stack pointer
// o ra: return address
//
// The function builds an interpreter frame. See InterpreterFrameConstants in
// frame-constants.h for its layout.
void Builtins::Generate_InterpreterEntryTrampoline(
MacroAssembler* masm, InterpreterEntryTrampolineMode mode) {
Register closure = a1;
Register feedback_vector = a2;
// Get the bytecode array from the function object and load it into
// kInterpreterBytecodeArrayRegister.
__ Ld_d(kScratchReg,
FieldMemOperand(closure, JSFunction::kSharedFunctionInfoOffset));
__ Ld_d(
kInterpreterBytecodeArrayRegister,
FieldMemOperand(kScratchReg, SharedFunctionInfo::kFunctionDataOffset));
Label is_baseline;
GetSharedFunctionInfoBytecodeOrBaseline(
masm, kInterpreterBytecodeArrayRegister, kScratchReg, &is_baseline);
// The bytecode array could have been flushed from the shared function info,
// if so, call into CompileLazy.
Label compile_lazy;
__ GetObjectType(kInterpreterBytecodeArrayRegister, kScratchReg, kScratchReg);
__ Branch(&compile_lazy, ne, kScratchReg, Operand(BYTECODE_ARRAY_TYPE));
// Load the feedback vector from the closure.
__ Ld_d(feedback_vector,
FieldMemOperand(closure, JSFunction::kFeedbackCellOffset));
__ Ld_d(feedback_vector,
FieldMemOperand(feedback_vector, Cell::kValueOffset));
Label push_stack_frame;
// Check if feedback vector is valid. If valid, check for optimized code
// and update invocation count. Otherwise, setup the stack frame.
__ Ld_d(a4, FieldMemOperand(feedback_vector, HeapObject::kMapOffset));
__ Ld_hu(a4, FieldMemOperand(a4, Map::kInstanceTypeOffset));
__ Branch(&push_stack_frame, ne, a4, Operand(FEEDBACK_VECTOR_TYPE));
// Check the tiering state.
Label has_optimized_code_or_state;
Register optimization_state = a4;
__ LoadTieringStateAndJumpIfNeedsProcessing(
optimization_state, feedback_vector, &has_optimized_code_or_state);
{
UseScratchRegisterScope temps(masm);
ResetFeedbackVectorOsrUrgency(masm, feedback_vector, temps.Acquire());
}
Label not_optimized;
__ bind(¬_optimized);
// Increment invocation count for the function.
__ Ld_w(a4, FieldMemOperand(feedback_vector,
FeedbackVector::kInvocationCountOffset));
__ Add_w(a4, a4, Operand(1));
__ St_w(a4, FieldMemOperand(feedback_vector,
FeedbackVector::kInvocationCountOffset));
// Open a frame scope to indicate that there is a frame on the stack. The
// MANUAL indicates that the scope shouldn't actually generate code to set up
// the frame (that is done below).
__ bind(&push_stack_frame);
FrameScope frame_scope(masm, StackFrame::MANUAL);
__ PushStandardFrame(closure);
ResetBytecodeAge(masm, kInterpreterBytecodeArrayRegister);
// Load initial bytecode offset.
__ li(kInterpreterBytecodeOffsetRegister,
Operand(BytecodeArray::kHeaderSize - kHeapObjectTag));
// Push bytecode array and Smi tagged bytecode array offset.
__ SmiTag(a4, kInterpreterBytecodeOffsetRegister);
__ Push(kInterpreterBytecodeArrayRegister, a4);
// Allocate the local and temporary register file on the stack.
Label stack_overflow;
{
// Load frame size (word) from the BytecodeArray object.
__ Ld_w(a4, FieldMemOperand(kInterpreterBytecodeArrayRegister,
BytecodeArray::kFrameSizeOffset));
// Do a stack check to ensure we don't go over the limit.
__ Sub_d(a5, sp, Operand(a4));
__ LoadStackLimit(a2, MacroAssembler::StackLimitKind::kRealStackLimit);
__ Branch(&stack_overflow, lo, a5, Operand(a2));
// If ok, push undefined as the initial value for all register file entries.
Label loop_header;
Label loop_check;
__ LoadRoot(kInterpreterAccumulatorRegister, RootIndex::kUndefinedValue);
__ Branch(&loop_check);
__ bind(&loop_header);
// TODO(rmcilroy): Consider doing more than one push per loop iteration.
__ Push(kInterpreterAccumulatorRegister);
// Continue loop if not done.
__ bind(&loop_check);
__ Sub_d(a4, a4, Operand(kPointerSize));
__ Branch(&loop_header, ge, a4, Operand(zero_reg));
}
// If the bytecode array has a valid incoming new target or generator object
// register, initialize it with incoming value which was passed in r3.
Label no_incoming_new_target_or_generator_register;
__ Ld_w(a5, FieldMemOperand(
kInterpreterBytecodeArrayRegister,
BytecodeArray::kIncomingNewTargetOrGeneratorRegisterOffset));
__ Branch(&no_incoming_new_target_or_generator_register, eq, a5,
Operand(zero_reg));
__ Alsl_d(a5, a5, fp, kPointerSizeLog2, t7);
__ St_d(a3, MemOperand(a5, 0));
__ bind(&no_incoming_new_target_or_generator_register);
// Perform interrupt stack check.
// TODO(solanes): Merge with the real stack limit check above.
Label stack_check_interrupt, after_stack_check_interrupt;
__ LoadStackLimit(a5, MacroAssembler::StackLimitKind::kInterruptStackLimit);
__ Branch(&stack_check_interrupt, lo, sp, Operand(a5));
__ bind(&after_stack_check_interrupt);
// The accumulator is already loaded with undefined.
// Load the dispatch table into a register and dispatch to the bytecode
// handler at the current bytecode offset.
Label do_dispatch;
__ bind(&do_dispatch);
__ li(kInterpreterDispatchTableRegister,
ExternalReference::interpreter_dispatch_table_address(masm->isolate()));
__ Add_d(t5, kInterpreterBytecodeArrayRegister,
kInterpreterBytecodeOffsetRegister);
__ Ld_bu(a7, MemOperand(t5, 0));
__ Alsl_d(kScratchReg, a7, kInterpreterDispatchTableRegister,
kPointerSizeLog2, t7);
__ Ld_d(kJavaScriptCallCodeStartRegister, MemOperand(kScratchReg, 0));
__ Call(kJavaScriptCallCodeStartRegister);
__ RecordComment("--- InterpreterEntryReturnPC point ---");
if (mode == InterpreterEntryTrampolineMode::kDefault) {
masm->isolate()->heap()->SetInterpreterEntryReturnPCOffset(
masm->pc_offset());
} else {
DCHECK_EQ(mode, InterpreterEntryTrampolineMode::kForProfiling);
// Both versions must be the same up to this point otherwise the builtins
// will not be interchangable.
CHECK_EQ(
masm->isolate()->heap()->interpreter_entry_return_pc_offset().value(),
masm->pc_offset());
}
// Any returns to the entry trampoline are either due to the return bytecode
// or the interpreter tail calling a builtin and then a dispatch.
// Get bytecode array and bytecode offset from the stack frame.
__ Ld_d(kInterpreterBytecodeArrayRegister,
MemOperand(fp, InterpreterFrameConstants::kBytecodeArrayFromFp));
__ Ld_d(kInterpreterBytecodeOffsetRegister,
MemOperand(fp, InterpreterFrameConstants::kBytecodeOffsetFromFp));
__ SmiUntag(kInterpreterBytecodeOffsetRegister);
// Either return, or advance to the next bytecode and dispatch.
Label do_return;
__ Add_d(a1, kInterpreterBytecodeArrayRegister,
kInterpreterBytecodeOffsetRegister);
__ Ld_bu(a1, MemOperand(a1, 0));
AdvanceBytecodeOffsetOrReturn(masm, kInterpreterBytecodeArrayRegister,
kInterpreterBytecodeOffsetRegister, a1, a2, a3,
a4, &do_return);
__ jmp(&do_dispatch);
__ bind(&do_return);
// The return value is in a0.
LeaveInterpreterFrame(masm, t0, t1);
__ Jump(ra);
__ bind(&stack_check_interrupt);
// Modify the bytecode offset in the stack to be kFunctionEntryBytecodeOffset
// for the call to the StackGuard.
__ li(kInterpreterBytecodeOffsetRegister,
Operand(Smi::FromInt(BytecodeArray::kHeaderSize - kHeapObjectTag +
kFunctionEntryBytecodeOffset)));
__ St_d(kInterpreterBytecodeOffsetRegister,
MemOperand(fp, InterpreterFrameConstants::kBytecodeOffsetFromFp));
__ CallRuntime(Runtime::kStackGuard);
// After the call, restore the bytecode array, bytecode offset and accumulator
// registers again. Also, restore the bytecode offset in the stack to its
// previous value.
__ Ld_d(kInterpreterBytecodeArrayRegister,
MemOperand(fp, InterpreterFrameConstants::kBytecodeArrayFromFp));
__ li(kInterpreterBytecodeOffsetRegister,
Operand(BytecodeArray::kHeaderSize - kHeapObjectTag));
__ LoadRoot(kInterpreterAccumulatorRegister, RootIndex::kUndefinedValue);
__ SmiTag(a5, kInterpreterBytecodeOffsetRegister);
__ St_d(a5, MemOperand(fp, InterpreterFrameConstants::kBytecodeOffsetFromFp));
__ jmp(&after_stack_check_interrupt);
__ bind(&has_optimized_code_or_state);
__ MaybeOptimizeCodeOrTailCallOptimizedCodeSlot(optimization_state,
feedback_vector);
__ bind(&is_baseline);
{
// Load the feedback vector from the closure.
__ Ld_d(feedback_vector,
FieldMemOperand(closure, JSFunction::kFeedbackCellOffset));
__ Ld_d(feedback_vector,
FieldMemOperand(feedback_vector, Cell::kValueOffset));
Label install_baseline_code;
// Check if feedback vector is valid. If not, call prepare for baseline to
// allocate it.
__ Ld_d(t0, FieldMemOperand(feedback_vector, HeapObject::kMapOffset));
__ Ld_hu(t0, FieldMemOperand(t0, Map::kInstanceTypeOffset));
__ Branch(&install_baseline_code, ne, t0, Operand(FEEDBACK_VECTOR_TYPE));
// Check for an tiering state.
__ LoadTieringStateAndJumpIfNeedsProcessing(
optimization_state, feedback_vector, &has_optimized_code_or_state);
// Load the baseline code into the closure.
__ Move(a2, kInterpreterBytecodeArrayRegister);
static_assert(kJavaScriptCallCodeStartRegister == a2, "ABI mismatch");
__ ReplaceClosureCodeWithOptimizedCode(a2, closure);
__ JumpCodeObject(a2);
__ bind(&install_baseline_code);
__ GenerateTailCallToReturnedCode(Runtime::kInstallBaselineCode);
}
__ bind(&compile_lazy);
__ GenerateTailCallToReturnedCode(Runtime::kCompileLazy);
// Unreachable code.
__ break_(0xCC);
__ bind(&stack_overflow);
__ CallRuntime(Runtime::kThrowStackOverflow);
// Unreachable code.
__ break_(0xCC);
}
static void GenerateInterpreterPushArgs(MacroAssembler* masm, Register num_args,
Register start_address,
Register scratch, Register scratch2) {
// Find the address of the last argument.
__ Sub_d(scratch, num_args, Operand(1));
__ slli_d(scratch, scratch, kPointerSizeLog2);
__ Sub_d(start_address, start_address, scratch);
// Push the arguments.
__ PushArray(start_address, num_args, scratch, scratch2,
TurboAssembler::PushArrayOrder::kReverse);
}
// static
void Builtins::Generate_InterpreterPushArgsThenCallImpl(
MacroAssembler* masm, ConvertReceiverMode receiver_mode,
InterpreterPushArgsMode mode) {
DCHECK(mode != InterpreterPushArgsMode::kArrayFunction);
// ----------- S t a t e -------------
// -- a0 : the number of arguments
// -- a2 : the address of the first argument to be pushed. Subsequent
// arguments should be consecutive above this, in the same order as
// they are to be pushed onto the stack.
// -- a1 : the target to call (can be any Object).
// -----------------------------------
Label stack_overflow;
if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
// The spread argument should not be pushed.
__ Sub_d(a0, a0, Operand(1));
}
if (receiver_mode == ConvertReceiverMode::kNullOrUndefined) {
__ Sub_d(a3, a0, Operand(kJSArgcReceiverSlots));
} else {
__ mov(a3, a0);
}
__ StackOverflowCheck(a3, a4, t0, &stack_overflow);
// This function modifies a2, t0 and a4.
GenerateInterpreterPushArgs(masm, a3, a2, a4, t0);
if (receiver_mode == ConvertReceiverMode::kNullOrUndefined) {
__ PushRoot(RootIndex::kUndefinedValue);
}
if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
// Pass the spread in the register a2.
// a2 already points to the penultime argument, the spread
// is below that.
__ Ld_d(a2, MemOperand(a2, -kSystemPointerSize));
}
// Call the target.
if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
__ Jump(BUILTIN_CODE(masm->isolate(), CallWithSpread),
RelocInfo::CODE_TARGET);
} else {
__ Jump(masm->isolate()->builtins()->Call(ConvertReceiverMode::kAny),
RelocInfo::CODE_TARGET);
}
__ bind(&stack_overflow);
{
__ TailCallRuntime(Runtime::kThrowStackOverflow);
// Unreachable code.
__ break_(0xCC);
}
}
// static
void Builtins::Generate_InterpreterPushArgsThenConstructImpl(
MacroAssembler* masm, InterpreterPushArgsMode mode) {
// ----------- S t a t e -------------
// -- a0 : argument count
// -- a3 : new target
// -- a1 : constructor to call
// -- a2 : allocation site feedback if available, undefined otherwise.
// -- a4 : address of the first argument
// -----------------------------------
Label stack_overflow;
__ StackOverflowCheck(a0, a5, t0, &stack_overflow);
if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
// The spread argument should not be pushed.
__ Sub_d(a0, a0, Operand(1));
}
Register argc_without_receiver = a6;
__ Sub_d(argc_without_receiver, a0, Operand(kJSArgcReceiverSlots));
// Push the arguments, This function modifies t0, a4 and a5.
GenerateInterpreterPushArgs(masm, argc_without_receiver, a4, a5, t0);
// Push a slot for the receiver.
__ Push(zero_reg);
if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
// Pass the spread in the register a2.
// a4 already points to the penultimate argument, the spread
// lies in the next interpreter register.
__ Ld_d(a2, MemOperand(a4, -kSystemPointerSize));
} else {
__ AssertUndefinedOrAllocationSite(a2, t0);
}
if (mode == InterpreterPushArgsMode::kArrayFunction) {
__ AssertFunction(a1);
// Tail call to the function-specific construct stub (still in the caller
// context at this point).
__ Jump(BUILTIN_CODE(masm->isolate(), ArrayConstructorImpl),
RelocInfo::CODE_TARGET);
} else if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
// Call the constructor with a0, a1, and a3 unmodified.
__ Jump(BUILTIN_CODE(masm->isolate(), ConstructWithSpread),
RelocInfo::CODE_TARGET);
} else {
DCHECK_EQ(InterpreterPushArgsMode::kOther, mode);
// Call the constructor with a0, a1, and a3 unmodified.
__ Jump(BUILTIN_CODE(masm->isolate(), Construct), RelocInfo::CODE_TARGET);
}
__ bind(&stack_overflow);
{
__ TailCallRuntime(Runtime::kThrowStackOverflow);
// Unreachable code.
__ break_(0xCC);
}
}
static void Generate_InterpreterEnterBytecode(MacroAssembler* masm) {
// Set the return address to the correct point in the interpreter entry
// trampoline.
Label builtin_trampoline, trampoline_loaded;
Smi interpreter_entry_return_pc_offset(
masm->isolate()->heap()->interpreter_entry_return_pc_offset());
DCHECK_NE(interpreter_entry_return_pc_offset, Smi::zero());
// If the SFI function_data is an InterpreterData, the function will have a
// custom copy of the interpreter entry trampoline for profiling. If so,
// get the custom trampoline, otherwise grab the entry address of the global
// trampoline.
__ Ld_d(t0, MemOperand(fp, StandardFrameConstants::kFunctionOffset));
__ Ld_d(t0, FieldMemOperand(t0, JSFunction::kSharedFunctionInfoOffset));
__ Ld_d(t0, FieldMemOperand(t0, SharedFunctionInfo::kFunctionDataOffset));
__ GetObjectType(t0, kInterpreterDispatchTableRegister,
kInterpreterDispatchTableRegister);
__ Branch(&builtin_trampoline, ne, kInterpreterDispatchTableRegister,
Operand(INTERPRETER_DATA_TYPE));
__ Ld_d(t0,
FieldMemOperand(t0, InterpreterData::kInterpreterTrampolineOffset));
__ Add_d(t0, t0, Operand(Code::kHeaderSize - kHeapObjectTag));
__ Branch(&trampoline_loaded);
__ bind(&builtin_trampoline);
__ li(t0, ExternalReference::
address_of_interpreter_entry_trampoline_instruction_start(
masm->isolate()));
__ Ld_d(t0, MemOperand(t0, 0));
__ bind(&trampoline_loaded);
__ Add_d(ra, t0, Operand(interpreter_entry_return_pc_offset.value()));
// Initialize the dispatch table register.
__ li(kInterpreterDispatchTableRegister,
ExternalReference::interpreter_dispatch_table_address(masm->isolate()));
// Get the bytecode array pointer from the frame.
__ Ld_d(kInterpreterBytecodeArrayRegister,
MemOperand(fp, InterpreterFrameConstants::kBytecodeArrayFromFp));
if (FLAG_debug_code) {
// Check function data field is actually a BytecodeArray object.
__ SmiTst(kInterpreterBytecodeArrayRegister, kScratchReg);
__ Assert(ne,
AbortReason::kFunctionDataShouldBeBytecodeArrayOnInterpreterEntry,
kScratchReg, Operand(zero_reg));
__ GetObjectType(kInterpreterBytecodeArrayRegister, a1, a1);
__ Assert(eq,
AbortReason::kFunctionDataShouldBeBytecodeArrayOnInterpreterEntry,
a1, Operand(BYTECODE_ARRAY_TYPE));
}
// Get the target bytecode offset from the frame.
__ SmiUntag(kInterpreterBytecodeOffsetRegister,
MemOperand(fp, InterpreterFrameConstants::kBytecodeOffsetFromFp));
if (FLAG_debug_code) {
Label okay;
__ Branch(&okay, ge, kInterpreterBytecodeOffsetRegister,
Operand(BytecodeArray::kHeaderSize - kHeapObjectTag));
// Unreachable code.
__ break_(0xCC);
__ bind(&okay);
}
// Dispatch to the target bytecode.
__ Add_d(a1, kInterpreterBytecodeArrayRegister,
kInterpreterBytecodeOffsetRegister);
__ Ld_bu(a7, MemOperand(a1, 0));
__ Alsl_d(a1, a7, kInterpreterDispatchTableRegister, kPointerSizeLog2, t7);
__ Ld_d(kJavaScriptCallCodeStartRegister, MemOperand(a1, 0));
__ Jump(kJavaScriptCallCodeStartRegister);
}
void Builtins::Generate_InterpreterEnterAtNextBytecode(MacroAssembler* masm) {
// Advance the current bytecode offset stored within the given interpreter
// stack frame. This simulates what all bytecode handlers do upon completion
// of the underlying operation.
__ Ld_d(kInterpreterBytecodeArrayRegister,
MemOperand(fp, InterpreterFrameConstants::kBytecodeArrayFromFp));
__ Ld_d(kInterpreterBytecodeOffsetRegister,
MemOperand(fp, InterpreterFrameConstants::kBytecodeOffsetFromFp));
__ SmiUntag(kInterpreterBytecodeOffsetRegister);
Label enter_bytecode, function_entry_bytecode;
__ Branch(&function_entry_bytecode, eq, kInterpreterBytecodeOffsetRegister,
Operand(BytecodeArray::kHeaderSize - kHeapObjectTag +
kFunctionEntryBytecodeOffset));
// Load the current bytecode.
__ Add_d(a1, kInterpreterBytecodeArrayRegister,
kInterpreterBytecodeOffsetRegister);
__ Ld_bu(a1, MemOperand(a1, 0));
// Advance to the next bytecode.
Label if_return;
AdvanceBytecodeOffsetOrReturn(masm, kInterpreterBytecodeArrayRegister,
kInterpreterBytecodeOffsetRegister, a1, a2, a3,
a4, &if_return);
__ bind(&enter_bytecode);
// Convert new bytecode offset to a Smi and save in the stackframe.
__ SmiTag(a2, kInterpreterBytecodeOffsetRegister);
__ St_d(a2, MemOperand(fp, InterpreterFrameConstants::kBytecodeOffsetFromFp));
Generate_InterpreterEnterBytecode(masm);
__ bind(&function_entry_bytecode);
// If the code deoptimizes during the implicit function entry stack interrupt
// check, it will have a bailout ID of kFunctionEntryBytecodeOffset, which is
// not a valid bytecode offset. Detect this case and advance to the first
// actual bytecode.
__ li(kInterpreterBytecodeOffsetRegister,
Operand(BytecodeArray::kHeaderSize - kHeapObjectTag));
__ Branch(&enter_bytecode);
// We should never take the if_return path.
__ bind(&if_return);
__ Abort(AbortReason::kInvalidBytecodeAdvance);
}
void Builtins::Generate_InterpreterEnterAtBytecode(MacroAssembler* masm) {
Generate_InterpreterEnterBytecode(masm);
}
namespace {
void Generate_ContinueToBuiltinHelper(MacroAssembler* masm,
bool java_script_builtin,
bool with_result) {
const RegisterConfiguration* config(RegisterConfiguration::Default());
int allocatable_register_count = config->num_allocatable_general_registers();
UseScratchRegisterScope temps(masm);
Register scratch = temps.Acquire();
if (with_result) {
if (java_script_builtin) {
__ mov(scratch, a0);
} else {
// Overwrite the hole inserted by the deoptimizer with the return value
// from the LAZY deopt point.
__ St_d(
a0,
MemOperand(
sp, config->num_allocatable_general_registers() * kPointerSize +
BuiltinContinuationFrameConstants::kFixedFrameSize));
}
}
for (int i = allocatable_register_count - 1; i >= 0; --i) {
int code = config->GetAllocatableGeneralCode(i);
__ Pop(Register::from_code(code));
if (java_script_builtin && code == kJavaScriptCallArgCountRegister.code()) {
__ SmiUntag(Register::from_code(code));
}
}
if (with_result && java_script_builtin) {
// Overwrite the hole inserted by the deoptimizer with the return value from
// the LAZY deopt point. t0 contains the arguments count, the return value
// from LAZY is always the last argument.
constexpr int return_value_offset =
BuiltinContinuationFrameConstants::kFixedSlotCount -
kJSArgcReceiverSlots;
__ Add_d(a0, a0, Operand(return_value_offset));
__ Alsl_d(t0, a0, sp, kSystemPointerSizeLog2, t7);
__ St_d(scratch, MemOperand(t0, 0));
// Recover arguments count.
__ Sub_d(a0, a0, Operand(return_value_offset));
}
__ Ld_d(
fp,
MemOperand(sp, BuiltinContinuationFrameConstants::kFixedFrameSizeFromFp));
// Load builtin index (stored as a Smi) and use it to get the builtin start
// address from the builtins table.
__ Pop(t0);
__ Add_d(sp, sp,
Operand(BuiltinContinuationFrameConstants::kFixedFrameSizeFromFp));
__ Pop(ra);
__ LoadEntryFromBuiltinIndex(t0);
__ Jump(t0);
}
} // namespace
void Builtins::Generate_ContinueToCodeStubBuiltin(MacroAssembler* masm) {
Generate_ContinueToBuiltinHelper(masm, false, false);
}
void Builtins::Generate_ContinueToCodeStubBuiltinWithResult(
MacroAssembler* masm) {
Generate_ContinueToBuiltinHelper(masm, false, true);
}
void Builtins::Generate_ContinueToJavaScriptBuiltin(MacroAssembler* masm) {
Generate_ContinueToBuiltinHelper(masm, true, false);
}
void Builtins::Generate_ContinueToJavaScriptBuiltinWithResult(
MacroAssembler* masm) {
Generate_ContinueToBuiltinHelper(masm, true, true);
}
void Builtins::Generate_NotifyDeoptimized(MacroAssembler* masm) {
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ CallRuntime(Runtime::kNotifyDeoptimized);
}
DCHECK_EQ(kInterpreterAccumulatorRegister.code(), a0.code());
__ Ld_d(a0, MemOperand(sp, 0 * kPointerSize));
__ Add_d(sp, sp, Operand(1 * kPointerSize)); // Remove state.
__ Ret();
}
namespace {
void Generate_OSREntry(MacroAssembler* masm, Register entry_address,
Operand offset = Operand(zero_reg)) {
__ Add_d(ra, entry_address, offset);
// And "return" to the OSR entry point of the function.
__ Ret();
}
enum class OsrSourceTier {
kInterpreter,
kBaseline,
};
void OnStackReplacement(MacroAssembler* masm, OsrSourceTier source,
Register maybe_target_code) {
Label jump_to_optimized_code;
{
// If maybe_target_code is not null, no need to call into runtime. A
// precondition here is: if maybe_target_code is a Code object, it must NOT
// be marked_for_deoptimization (callers must ensure this).
__ Branch(&jump_to_optimized_code, ne, maybe_target_code,
Operand(Smi::zero()));
}
ASM_CODE_COMMENT(masm);
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ CallRuntime(Runtime::kCompileOptimizedOSR);
}
// If the code object is null, just return to the caller.
__ Ret(eq, maybe_target_code, Operand(Smi::zero()));
__ bind(&jump_to_optimized_code);
DCHECK_EQ(maybe_target_code, a0); // Already in the right spot.
// OSR entry tracing.
{
Label next;
__ li(a1, ExternalReference::address_of_FLAG_trace_osr());
__ Ld_bu(a1, MemOperand(a1, 0));
__ Branch(&next, eq, a1, Operand(zero_reg));
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ Push(a0); // Preserve the code object.
__ CallRuntime(Runtime::kTraceOptimizedOSREntry, 0);
__ Pop(a0);
}
__ bind(&next);
}
if (source == OsrSourceTier::kInterpreter) {
// Drop the handler frame that is be sitting on top of the actual
// JavaScript frame. This is the case then OSR is triggered from bytecode.
__ LeaveFrame(StackFrame::STUB);
}
// Load deoptimization data from the code object.
// <deopt_data> = <code>[#deoptimization_data_offset]
__ Ld_d(a1, MemOperand(maybe_target_code,
Code::kDeoptimizationDataOrInterpreterDataOffset -
kHeapObjectTag));
// Load the OSR entrypoint offset from the deoptimization data.
// <osr_offset> = <deopt_data>[#header_size + #osr_pc_offset]
__ SmiUntag(a1, MemOperand(a1, FixedArray::OffsetOfElementAt(
DeoptimizationData::kOsrPcOffsetIndex) -
kHeapObjectTag));
// Compute the target address = code_obj + header_size + osr_offset
// <entry_addr> = <code_obj> + #header_size + <osr_offset>
__ Add_d(maybe_target_code, maybe_target_code, a1);
Generate_OSREntry(masm, maybe_target_code,
Operand(Code::kHeaderSize - kHeapObjectTag));
}
} // namespace
void Builtins::Generate_InterpreterOnStackReplacement(MacroAssembler* masm) {
using D = InterpreterOnStackReplacementDescriptor;
static_assert(D::kParameterCount == 1);
OnStackReplacement(masm, OsrSourceTier::kInterpreter,
D::MaybeTargetCodeRegister());
}
void Builtins::Generate_BaselineOnStackReplacement(MacroAssembler* masm) {
using D = BaselineOnStackReplacementDescriptor;
static_assert(D::kParameterCount == 1);
__ Ld_d(kContextRegister,
MemOperand(fp, BaselineFrameConstants::kContextOffset));
OnStackReplacement(masm, OsrSourceTier::kBaseline,
D::MaybeTargetCodeRegister());
}
// static
void Builtins::Generate_FunctionPrototypeApply(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- a0 : argc
// -- sp[0] : receiver
// -- sp[4] : thisArg
// -- sp[8] : argArray
// -----------------------------------
Register argc = a0;
Register arg_array = a2;
Register receiver = a1;
Register this_arg = a5;
Register undefined_value = a3;
Register scratch = a4;
__ LoadRoot(undefined_value, RootIndex::kUndefinedValue);
// 1. Load receiver into a1, argArray into a2 (if present), remove all
// arguments from the stack (including the receiver), and push thisArg (if
// present) instead.
{
__ Sub_d(scratch, argc, JSParameterCount(0));
__ Ld_d(this_arg, MemOperand(sp, kPointerSize));
__ Ld_d(arg_array, MemOperand(sp, 2 * kPointerSize));
__ Movz(arg_array, undefined_value, scratch); // if argc == 0
__ Movz(this_arg, undefined_value, scratch); // if argc == 0
__ Sub_d(scratch, scratch, Operand(1));
__ Movz(arg_array, undefined_value, scratch); // if argc == 1
__ Ld_d(receiver, MemOperand(sp, 0));
__ DropArgumentsAndPushNewReceiver(argc, this_arg,
TurboAssembler::kCountIsInteger,
TurboAssembler::kCountIncludesReceiver);
}
// ----------- S t a t e -------------
// -- a2 : argArray
// -- a1 : receiver
// -- a3 : undefined root value
// -- sp[0] : thisArg
// -----------------------------------
// 2. We don't need to check explicitly for callable receiver here,
// since that's the first thing the Call/CallWithArrayLike builtins
// will do.
// 3. Tail call with no arguments if argArray is null or undefined.
Label no_arguments;
__ JumpIfRoot(arg_array, RootIndex::kNullValue, &no_arguments);
__ Branch(&no_arguments, eq, arg_array, Operand(undefined_value));
// 4a. Apply the receiver to the given argArray.
__ Jump(BUILTIN_CODE(masm->isolate(), CallWithArrayLike),
RelocInfo::CODE_TARGET);
// 4b. The argArray is either null or undefined, so we tail call without any
// arguments to the receiver.
__ bind(&no_arguments);
{
__ li(a0, JSParameterCount(0));
DCHECK(receiver == a1);
__ Jump(masm->isolate()->builtins()->Call(), RelocInfo::CODE_TARGET);
}
}
// static
void Builtins::Generate_FunctionPrototypeCall(MacroAssembler* masm) {
// 1. Get the callable to call (passed as receiver) from the stack.
{ __ Pop(a1); }
// 2. Make sure we have at least one argument.
// a0: actual number of arguments
{
Label done;
__ Branch(&done, ne, a0, Operand(JSParameterCount(0)));
__ PushRoot(RootIndex::kUndefinedValue);
__ Add_d(a0, a0, Operand(1));
__ bind(&done);
}
// 3. Adjust the actual number of arguments.
__ addi_d(a0, a0, -1);
// 4. Call the callable.
__ Jump(masm->isolate()->builtins()->Call(), RelocInfo::CODE_TARGET);
}
void Builtins::Generate_ReflectApply(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- a0 : argc
// -- sp[0] : receiver
// -- sp[8] : target (if argc >= 1)
// -- sp[16] : thisArgument (if argc >= 2)
// -- sp[24] : argumentsList (if argc == 3)
// -----------------------------------
Register argc = a0;
Register arguments_list = a2;
Register target = a1;
Register this_argument = a5;
Register undefined_value = a3;
Register scratch = a4;
__ LoadRoot(undefined_value, RootIndex::kUndefinedValue);
// 1. Load target into a1 (if present), argumentsList into a2 (if present),
// remove all arguments from the stack (including the receiver), and push
// thisArgument (if present) instead.
{
// Claim (3 - argc) dummy arguments form the stack, to put the stack in a
// consistent state for a simple pop operation.
__ Sub_d(scratch, argc, Operand(JSParameterCount(0)));
__ Ld_d(target, MemOperand(sp, kPointerSize));
__ Ld_d(this_argument, MemOperand(sp, 2 * kPointerSize));
__ Ld_d(arguments_list, MemOperand(sp, 3 * kPointerSize));
__ Movz(arguments_list, undefined_value, scratch); // if argc == 0
__ Movz(this_argument, undefined_value, scratch); // if argc == 0
__ Movz(target, undefined_value, scratch); // if argc == 0
__ Sub_d(scratch, scratch, Operand(1));
__ Movz(arguments_list, undefined_value, scratch); // if argc == 1
__ Movz(this_argument, undefined_value, scratch); // if argc == 1
__ Sub_d(scratch, scratch, Operand(1));
__ Movz(arguments_list, undefined_value, scratch); // if argc == 2
__ DropArgumentsAndPushNewReceiver(argc, this_argument,
TurboAssembler::kCountIsInteger,
TurboAssembler::kCountIncludesReceiver);
}
// ----------- S t a t e -------------
// -- a2 : argumentsList
// -- a1 : target
// -- a3 : undefined root value
// -- sp[0] : thisArgument
// -----------------------------------
// 2. We don't need to check explicitly for callable target here,
// since that's the first thing the Call/CallWithArrayLike builtins
// will do.
// 3. Apply the target to the given argumentsList.
__ Jump(BUILTIN_CODE(masm->isolate(), CallWithArrayLike),
RelocInfo::CODE_TARGET);
}
void Builtins::Generate_ReflectConstruct(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- a0 : argc
// -- sp[0] : receiver
// -- sp[8] : target
// -- sp[16] : argumentsList
// -- sp[24] : new.target (optional)
// -----------------------------------
Register argc = a0;
Register arguments_list = a2;
Register target = a1;
Register new_target = a3;
Register undefined_value = a4;
Register scratch = a5;
__ LoadRoot(undefined_value, RootIndex::kUndefinedValue);
// 1. Load target into a1 (if present), argumentsList into a2 (if present),
// new.target into a3 (if present, otherwise use target), remove all
// arguments from the stack (including the receiver), and push thisArgument
// (if present) instead.
{
// Claim (3 - argc) dummy arguments form the stack, to put the stack in a
// consistent state for a simple pop operation.
__ Sub_d(scratch, argc, Operand(JSParameterCount(0)));
__ Ld_d(target, MemOperand(sp, kPointerSize));
__ Ld_d(arguments_list, MemOperand(sp, 2 * kPointerSize));
__ Ld_d(new_target, MemOperand(sp, 3 * kPointerSize));
__ Movz(arguments_list, undefined_value, scratch); // if argc == 0
__ Movz(new_target, undefined_value, scratch); // if argc == 0
__ Movz(target, undefined_value, scratch); // if argc == 0
__ Sub_d(scratch, scratch, Operand(1));
__ Movz(arguments_list, undefined_value, scratch); // if argc == 1
__ Movz(new_target, target, scratch); // if argc == 1
__ Sub_d(scratch, scratch, Operand(1));
__ Movz(new_target, target, scratch); // if argc == 2
__ DropArgumentsAndPushNewReceiver(argc, undefined_value,
TurboAssembler::kCountIsInteger,
TurboAssembler::kCountIncludesReceiver);
}
// ----------- S t a t e -------------
// -- a2 : argumentsList
// -- a1 : target
// -- a3 : new.target
// -- sp[0] : receiver (undefined)
// -----------------------------------
// 2. We don't need to check explicitly for constructor target here,
// since that's the first thing the Construct/ConstructWithArrayLike
// builtins will do.
// 3. We don't need to check explicitly for constructor new.target here,
// since that's the second thing the Construct/ConstructWithArrayLike
// builtins will do.
// 4. Construct the target with the given new.target and argumentsList.
__ Jump(BUILTIN_CODE(masm->isolate(), ConstructWithArrayLike),
RelocInfo::CODE_TARGET);
}
namespace {
// Allocate new stack space for |count| arguments and shift all existing
// arguments already on the stack. |pointer_to_new_space_out| points to the
// first free slot on the stack to copy additional arguments to and
// |argc_in_out| is updated to include |count|.
void Generate_AllocateSpaceAndShiftExistingArguments(
MacroAssembler* masm, Register count, Register argc_in_out,
Register pointer_to_new_space_out, Register scratch1, Register scratch2,
Register scratch3) {
DCHECK(!AreAliased(count, argc_in_out, pointer_to_new_space_out, scratch1,
scratch2));
Register old_sp = scratch1;
Register new_space = scratch2;
__ mov(old_sp, sp);
__ slli_d(new_space, count, kPointerSizeLog2);
__ Sub_d(sp, sp, Operand(new_space));
Register end = scratch2;
Register value = scratch3;
Register dest = pointer_to_new_space_out;
__ mov(dest, sp);
__ Alsl_d(end, argc_in_out, old_sp, kSystemPointerSizeLog2);
Label loop, done;
__ Branch(&done, ge, old_sp, Operand(end));
__ bind(&loop);
__ Ld_d(value, MemOperand(old_sp, 0));
__ St_d(value, MemOperand(dest, 0));
__ Add_d(old_sp, old_sp, Operand(kSystemPointerSize));
__ Add_d(dest, dest, Operand(kSystemPointerSize));
__ Branch(&loop, lt, old_sp, Operand(end));
__ bind(&done);
// Update total number of arguments.
__ Add_d(argc_in_out, argc_in_out, count);
}
} // namespace
// static
void Builtins::Generate_CallOrConstructVarargs(MacroAssembler* masm,
Handle<Code> code) {
// ----------- S t a t e -------------
// -- a1 : target
// -- a0 : number of parameters on the stack
// -- a2 : arguments list (a FixedArray)
// -- a4 : len (number of elements to push from args)
// -- a3 : new.target (for [[Construct]])
// -----------------------------------
if (FLAG_debug_code) {
// Allow a2 to be a FixedArray, or a FixedDoubleArray if a4 == 0.
Label ok, fail;
__ AssertNotSmi(a2);
__ GetObjectType(a2, t8, t8);
__ Branch(&ok, eq, t8, Operand(FIXED_ARRAY_TYPE));
__ Branch(&fail, ne, t8, Operand(FIXED_DOUBLE_ARRAY_TYPE));
__ Branch(&ok, eq, a4, Operand(zero_reg));
// Fall through.
__ bind(&fail);
__ Abort(AbortReason::kOperandIsNotAFixedArray);
__ bind(&ok);
}
Register args = a2;
Register len = a4;
// Check for stack overflow.
Label stack_overflow;
__ StackOverflowCheck(len, kScratchReg, a5, &stack_overflow);
// Move the arguments already in the stack,
// including the receiver and the return address.
// a4: Number of arguments to make room for.
// a0: Number of arguments already on the stack.
// a7: Points to first free slot on the stack after arguments were shifted.
Generate_AllocateSpaceAndShiftExistingArguments(masm, a4, a0, a7, a6, t0, t1);
// Push arguments onto the stack (thisArgument is already on the stack).
{
Label done, push, loop;
Register src = a6;
Register scratch = len;
__ addi_d(src, args, FixedArray::kHeaderSize - kHeapObjectTag);
__ Branch(&done, eq, len, Operand(zero_reg));
__ slli_d(scratch, len, kPointerSizeLog2);
__ Sub_d(scratch, sp, Operand(scratch));
__ LoadRoot(t1, RootIndex::kTheHoleValue);
__ bind(&loop);
__ Ld_d(a5, MemOperand(src, 0));
__ addi_d(src, src, kPointerSize);
__ Branch(&push, ne, a5, Operand(t1));
__ LoadRoot(a5, RootIndex::kUndefinedValue);
__ bind(&push);
__ St_d(a5, MemOperand(a7, 0));
__ Add_d(a7, a7, Operand(kSystemPointerSize));
__ Add_d(scratch, scratch, Operand(kSystemPointerSize));
__ Branch(&loop, ne, scratch, Operand(sp));
__ bind(&done);
}
// Tail-call to the actual Call or Construct builtin.
__ Jump(code, RelocInfo::CODE_TARGET);
__ bind(&stack_overflow);
__ TailCallRuntime(Runtime::kThrowStackOverflow);
}
// static
void Builtins::Generate_CallOrConstructForwardVarargs(MacroAssembler* masm,
CallOrConstructMode mode,
Handle<Code> code) {
// ----------- S t a t e -------------
// -- a0 : the number of arguments
// -- a3 : the new.target (for [[Construct]] calls)
// -- a1 : the target to call (can be any Object)
// -- a2 : start index (to support rest parameters)
// -----------------------------------
// Check if new.target has a [[Construct]] internal method.
if (mode == CallOrConstructMode::kConstruct) {
Label new_target_constructor, new_target_not_constructor;
__ JumpIfSmi(a3, &new_target_not_constructor);
__ Ld_d(t1, FieldMemOperand(a3, HeapObject::kMapOffset));
__ Ld_bu(t1, FieldMemOperand(t1, Map::kBitFieldOffset));
__ And(t1, t1, Operand(Map::Bits1::IsConstructorBit::kMask));
__ Branch(&new_target_constructor, ne, t1, Operand(zero_reg));
__ bind(&new_target_not_constructor);
{
FrameScope scope(masm, StackFrame::MANUAL);
__ EnterFrame(StackFrame::INTERNAL);
__ Push(a3);
__ CallRuntime(Runtime::kThrowNotConstructor);
}
__ bind(&new_target_constructor);
}
Label stack_done, stack_overflow;
__ Ld_d(a7, MemOperand(fp, StandardFrameConstants::kArgCOffset));
__ Sub_d(a7, a7, Operand(kJSArgcReceiverSlots));
__ Sub_d(a7, a7, a2);
__ Branch(&stack_done, le, a7, Operand(zero_reg));
{
// Check for stack overflow.
__ StackOverflowCheck(a7, a4, a5, &stack_overflow);
// Forward the arguments from the caller frame.
// Point to the first argument to copy (skipping the receiver).
__ Add_d(a6, fp,
Operand(CommonFrameConstants::kFixedFrameSizeAboveFp +
kSystemPointerSize));
__ Alsl_d(a6, a2, a6, kSystemPointerSizeLog2, t7);
// Move the arguments already in the stack,
// including the receiver and the return address.
// a7: Number of arguments to make room for.
// a0: Number of arguments already on the stack.
// a2: Points to first free slot on the stack after arguments were shifted.
Generate_AllocateSpaceAndShiftExistingArguments(masm, a7, a0, a2, t0, t1,
t2);
// Copy arguments from the caller frame.
// TODO(victorgomes): Consider using forward order as potentially more cache
// friendly.
{
Label loop;
__ bind(&loop);
{
__ Sub_w(a7, a7, Operand(1));
__ Alsl_d(t0, a7, a6, kPointerSizeLog2, t7);
__ Ld_d(kScratchReg, MemOperand(t0, 0));
__ Alsl_d(t0, a7, a2, kPointerSizeLog2, t7);
__ St_d(kScratchReg, MemOperand(t0, 0));
__ Branch(&loop, ne, a7, Operand(zero_reg));
}
}
}
__ Branch(&stack_done);
__ bind(&stack_overflow);
__ TailCallRuntime(Runtime::kThrowStackOverflow);
__ bind(&stack_done);
// Tail-call to the {code} handler.
__ Jump(code, RelocInfo::CODE_TARGET);
}
// static
void Builtins::Generate_CallFunction(MacroAssembler* masm,
ConvertReceiverMode mode) {
// ----------- S t a t e -------------
// -- a0 : the number of arguments
// -- a1 : the function to call (checked to be a JSFunction)
// -----------------------------------
__ AssertCallableFunction(a1);
__ Ld_d(a2, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset));
// Enter the context of the function; ToObject has to run in the function
// context, and we also need to take the global proxy from the function
// context in case of conversion.
__ Ld_d(cp, FieldMemOperand(a1, JSFunction::kContextOffset));
// We need to convert the receiver for non-native sloppy mode functions.
Label done_convert;
__ Ld_wu(a3, FieldMemOperand(a2, SharedFunctionInfo::kFlagsOffset));
__ And(kScratchReg, a3,
Operand(SharedFunctionInfo::IsNativeBit::kMask |
SharedFunctionInfo::IsStrictBit::kMask));
__ Branch(&done_convert, ne, kScratchReg, Operand(zero_reg));
{
// ----------- S t a t e -------------
// -- a0 : the number of arguments
// -- a1 : the function to call (checked to be a JSFunction)
// -- a2 : the shared function info.
// -- cp : the function context.
// -----------------------------------
if (mode == ConvertReceiverMode::kNullOrUndefined) {
// Patch receiver to global proxy.
__ LoadGlobalProxy(a3);
} else {
Label convert_to_object, convert_receiver;
__ LoadReceiver(a3, a0);
__ JumpIfSmi(a3, &convert_to_object);
static_assert(LAST_JS_RECEIVER_TYPE == LAST_TYPE);
__ GetObjectType(a3, a4, a4);
__ Branch(&done_convert, hs, a4, Operand(FIRST_JS_RECEIVER_TYPE));
if (mode != ConvertReceiverMode::kNotNullOrUndefined) {
Label convert_global_proxy;
__ JumpIfRoot(a3, RootIndex::kUndefinedValue, &convert_global_proxy);
__ JumpIfNotRoot(a3, RootIndex::kNullValue, &convert_to_object);
__ bind(&convert_global_proxy);
{
// Patch receiver to global proxy.
__ LoadGlobalProxy(a3);
}
__ Branch(&convert_receiver);
}
__ bind(&convert_to_object);
{
// Convert receiver using ToObject.
// TODO(bmeurer): Inline the allocation here to avoid building the frame
// in the fast case? (fall back to AllocateInNewSpace?)
FrameScope scope(masm, StackFrame::INTERNAL);
__ SmiTag(a0);
__ Push(a0, a1);
__ mov(a0, a3);
__ Push(cp);
__ Call(BUILTIN_CODE(masm->isolate(), ToObject),
RelocInfo::CODE_TARGET);
__ Pop(cp);
__ mov(a3, a0);
__ Pop(a0, a1);
__ SmiUntag(a0);
}
__ Ld_d(a2, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset));
__ bind(&convert_receiver);
}
__ StoreReceiver(a3, a0, kScratchReg);
}
__ bind(&done_convert);
// ----------- S t a t e -------------
// -- a0 : the number of arguments
// -- a1 : the function to call (checked to be a JSFunction)
// -- a2 : the shared function info.
// -- cp : the function context.
// -----------------------------------
__ Ld_hu(
a2, FieldMemOperand(a2, SharedFunctionInfo::kFormalParameterCountOffset));
__ InvokeFunctionCode(a1, no_reg, a2, a0, InvokeType::kJump);
}
// static
void Builtins::Generate_CallBoundFunctionImpl(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- a0 : the number of arguments
// -- a1 : the function to call (checked to be a JSBoundFunction)
// -----------------------------------
__ AssertBoundFunction(a1);
// Patch the receiver to [[BoundThis]].
{
__ Ld_d(t0, FieldMemOperand(a1, JSBoundFunction::kBoundThisOffset));
__ StoreReceiver(t0, a0, kScratchReg);
}
// Load [[BoundArguments]] into a2 and length of that into a4.
__ Ld_d(a2, FieldMemOperand(a1, JSBoundFunction::kBoundArgumentsOffset));
__ SmiUntag(a4, FieldMemOperand(a2, FixedArray::kLengthOffset));
// ----------- S t a t e -------------
// -- a0 : the number of arguments
// -- a1 : the function to call (checked to be a JSBoundFunction)
// -- a2 : the [[BoundArguments]] (implemented as FixedArray)
// -- a4 : the number of [[BoundArguments]]
// -----------------------------------
// Reserve stack space for the [[BoundArguments]].
{
Label done;
__ slli_d(a5, a4, kPointerSizeLog2);
__ Sub_d(t0, sp, Operand(a5));
// Check the stack for overflow. We are not trying to catch interruptions
// (i.e. debug break and preemption) here, so check the "real stack limit".
__ LoadStackLimit(kScratchReg,
MacroAssembler::StackLimitKind::kRealStackLimit);
__ Branch(&done, hs, t0, Operand(kScratchReg));
{
FrameScope scope(masm, StackFrame::MANUAL);
__ EnterFrame(StackFrame::INTERNAL);
__ CallRuntime(Runtime::kThrowStackOverflow);
}
__ bind(&done);
}
// Pop receiver.
__ Pop(t0);
// Push [[BoundArguments]].
{
Label loop, done_loop;
__ SmiUntag(a4, FieldMemOperand(a2, FixedArray::kLengthOffset));
__ Add_d(a0, a0, Operand(a4));
__ Add_d(a2, a2, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
__ bind(&loop);
__ Sub_d(a4, a4, Operand(1));
__ Branch(&done_loop, lt, a4, Operand(zero_reg));
__ Alsl_d(a5, a4, a2, kPointerSizeLog2, t7);
__ Ld_d(kScratchReg, MemOperand(a5, 0));
__ Push(kScratchReg);
__ Branch(&loop);
__ bind(&done_loop);
}
// Push receiver.
__ Push(t0);
// Call the [[BoundTargetFunction]] via the Call builtin.
__ Ld_d(a1, FieldMemOperand(a1, JSBoundFunction::kBoundTargetFunctionOffset));
__ Jump(BUILTIN_CODE(masm->isolate(), Call_ReceiverIsAny),
RelocInfo::CODE_TARGET);
}
// static
void Builtins::Generate_Call(MacroAssembler* masm, ConvertReceiverMode mode) {
// ----------- S t a t e -------------
// -- a0 : the number of arguments
// -- a1 : the target to call (can be any Object).
// -----------------------------------
Register argc = a0;
Register target = a1;
Register map = t1;
Register instance_type = t2;
Register scratch = t8;
DCHECK(!AreAliased(argc, target, map, instance_type, scratch));
Label non_callable, class_constructor;
__ JumpIfSmi(target, &non_callable);
__ LoadMap(map, target);
__ GetInstanceTypeRange(map, instance_type, FIRST_CALLABLE_JS_FUNCTION_TYPE,
scratch);
__ Jump(masm->isolate()->builtins()->CallFunction(mode),
RelocInfo::CODE_TARGET, ls, scratch,
Operand(LAST_CALLABLE_JS_FUNCTION_TYPE -
FIRST_CALLABLE_JS_FUNCTION_TYPE));
__ Jump(BUILTIN_CODE(masm->isolate(), CallBoundFunction),
RelocInfo::CODE_TARGET, eq, instance_type,
Operand(JS_BOUND_FUNCTION_TYPE));
// Check if target has a [[Call]] internal method.
{
Register flags = t1;
__ Ld_bu(flags, FieldMemOperand(map, Map::kBitFieldOffset));
map = no_reg;
__ And(flags, flags, Operand(Map::Bits1::IsCallableBit::kMask));
__ Branch(&non_callable, eq, flags, Operand(zero_reg));
}
__ Jump(BUILTIN_CODE(masm->isolate(), CallProxy), RelocInfo::CODE_TARGET, eq,
instance_type, Operand(JS_PROXY_TYPE));
// Check if target is a wrapped function and call CallWrappedFunction external
// builtin
__ Jump(BUILTIN_CODE(masm->isolate(), CallWrappedFunction),
RelocInfo::CODE_TARGET, eq, instance_type,
Operand(JS_WRAPPED_FUNCTION_TYPE));
// ES6 section 9.2.1 [[Call]] ( thisArgument, argumentsList)
// Check that the function is not a "classConstructor".
__ Branch(&class_constructor, eq, instance_type,
Operand(JS_CLASS_CONSTRUCTOR_TYPE));
// 2. Call to something else, which might have a [[Call]] internal method (if
// not we raise an exception).
// Overwrite the original receiver with the (original) target.
__ StoreReceiver(target, argc, kScratchReg);
// Let the "call_as_function_delegate" take care of the rest.
__ LoadNativeContextSlot(target, Context::CALL_AS_FUNCTION_DELEGATE_INDEX);
__ Jump(masm->isolate()->builtins()->CallFunction(
ConvertReceiverMode::kNotNullOrUndefined),
RelocInfo::CODE_TARGET);
// 3. Call to something that is not callable.
__ bind(&non_callable);
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ Push(target);
__ CallRuntime(Runtime::kThrowCalledNonCallable);
}
// 4. The function is a "classConstructor", need to raise an exception.
__ bind(&class_constructor);
{
FrameScope frame(masm, StackFrame::INTERNAL);
__ Push(target);
__ CallRuntime(Runtime::kThrowConstructorNonCallableError);
}
}
void Builtins::Generate_ConstructFunction(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- a0 : the number of arguments
// -- a1 : the constructor to call (checked to be a JSFunction)
// -- a3 : the new target (checked to be a constructor)
// -----------------------------------
__ AssertConstructor(a1);
__ AssertFunction(a1);
// Calling convention for function specific ConstructStubs require
// a2 to contain either an AllocationSite or undefined.
__ LoadRoot(a2, RootIndex::kUndefinedValue);
Label call_generic_stub;
// Jump to JSBuiltinsConstructStub or JSConstructStubGeneric.
__ Ld_d(a4, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset));
__ Ld_wu(a4, FieldMemOperand(a4, SharedFunctionInfo::kFlagsOffset));
__ And(a4, a4, Operand(SharedFunctionInfo::ConstructAsBuiltinBit::kMask));
__ Branch(&call_generic_stub, eq, a4, Operand(zero_reg));
__ Jump(BUILTIN_CODE(masm->isolate(), JSBuiltinsConstructStub),
RelocInfo::CODE_TARGET);
__ bind(&call_generic_stub);
__ Jump(BUILTIN_CODE(masm->isolate(), JSConstructStubGeneric),
RelocInfo::CODE_TARGET);
}
// static
void Builtins::Generate_ConstructBoundFunction(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- a0 : the number of arguments
// -- a1 : the function to call (checked to be a JSBoundFunction)
// -- a3 : the new target (checked to be a constructor)
// -----------------------------------
__ AssertConstructor(a1);
__ AssertBoundFunction(a1);
// Load [[BoundArguments]] into a2 and length of that into a4.
__ Ld_d(a2, FieldMemOperand(a1, JSBoundFunction::kBoundArgumentsOffset));
__ SmiUntag(a4, FieldMemOperand(a2, FixedArray::kLengthOffset));
// ----------- S t a t e -------------
// -- a0 : the number of arguments
// -- a1 : the function to call (checked to be a JSBoundFunction)
// -- a2 : the [[BoundArguments]] (implemented as FixedArray)
// -- a3 : the new target (checked to be a constructor)
// -- a4 : the number of [[BoundArguments]]
// -----------------------------------
// Reserve stack space for the [[BoundArguments]].
{
Label done;
__ slli_d(a5, a4, kPointerSizeLog2);
__ Sub_d(t0, sp, Operand(a5));
// Check the stack for overflow. We are not trying to catch interruptions
// (i.e. debug break and preemption) here, so check the "real stack limit".
__ LoadStackLimit(kScratchReg,
MacroAssembler::StackLimitKind::kRealStackLimit);
__ Branch(&done, hs, t0, Operand(kScratchReg));
{
FrameScope scope(masm, StackFrame::MANUAL);
__ EnterFrame(StackFrame::INTERNAL);
__ CallRuntime(Runtime::kThrowStackOverflow);
}
__ bind(&done);
}
// Pop receiver.
__ Pop(t0);
// Push [[BoundArguments]].
{
Label loop, done_loop;
__ SmiUntag(a4, FieldMemOperand(a2, FixedArray::kLengthOffset));
__ Add_d(a0, a0, Operand(a4));
__ Add_d(a2, a2, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
__ bind(&loop);
__ Sub_d(a4, a4, Operand(1));
__ Branch(&done_loop, lt, a4, Operand(zero_reg));
__ Alsl_d(a5, a4, a2, kPointerSizeLog2, t7);
__ Ld_d(kScratchReg, MemOperand(a5, 0));
__ Push(kScratchReg);
__ Branch(&loop);
__ bind(&done_loop);
}
// Push receiver.
__ Push(t0);
// Patch new.target to [[BoundTargetFunction]] if new.target equals target.
{
Label skip_load;
__ Branch(&skip_load, ne, a1, Operand(a3));
__ Ld_d(a3,
FieldMemOperand(a1, JSBoundFunction::kBoundTargetFunctionOffset));
__ bind(&skip_load);
}
// Construct the [[BoundTargetFunction]] via the Construct builtin.
__ Ld_d(a1, FieldMemOperand(a1, JSBoundFunction::kBoundTargetFunctionOffset));
__ Jump(BUILTIN_CODE(masm->isolate(), Construct), RelocInfo::CODE_TARGET);
}
// static
void Builtins::Generate_Construct(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- a0 : the number of arguments
// -- a1 : the constructor to call (can be any Object)
// -- a3 : the new target (either the same as the constructor or
// the JSFunction on which new was invoked initially)
// -----------------------------------
Register argc = a0;
Register target = a1;
Register map = t1;
Register instance_type = t2;
Register scratch = t8;
DCHECK(!AreAliased(argc, target, map, instance_type, scratch));
// Check if target is a Smi.
Label non_constructor, non_proxy;
__ JumpIfSmi(target, &non_constructor);
// Check if target has a [[Construct]] internal method.
__ Ld_d(map, FieldMemOperand(target, HeapObject::kMapOffset));
{
Register flags = t3;
__ Ld_bu(flags, FieldMemOperand(map, Map::kBitFieldOffset));
__ And(flags, flags, Operand(Map::Bits1::IsConstructorBit::kMask));
__ Branch(&non_constructor, eq, flags, Operand(zero_reg));
}
// Dispatch based on instance type.
__ GetInstanceTypeRange(map, instance_type, FIRST_JS_FUNCTION_TYPE, scratch);
__ Jump(BUILTIN_CODE(masm->isolate(), ConstructFunction),
RelocInfo::CODE_TARGET, ls, scratch,
Operand(LAST_JS_FUNCTION_TYPE - FIRST_JS_FUNCTION_TYPE));
// Only dispatch to bound functions after checking whether they are
// constructors.
__ Jump(BUILTIN_CODE(masm->isolate(), ConstructBoundFunction),
RelocInfo::CODE_TARGET, eq, instance_type,
Operand(JS_BOUND_FUNCTION_TYPE));
// Only dispatch to proxies after checking whether they are constructors.
__ Branch(&non_proxy, ne, instance_type, Operand(JS_PROXY_TYPE));
__ Jump(BUILTIN_CODE(masm->isolate(), ConstructProxy),
RelocInfo::CODE_TARGET);
// Called Construct on an exotic Object with a [[Construct]] internal method.
__ bind(&non_proxy);
{
// Overwrite the original receiver with the (original) target.
__ StoreReceiver(target, argc, kScratchReg);
// Let the "call_as_constructor_delegate" take care of the rest.
__ LoadNativeContextSlot(target,
Context::CALL_AS_CONSTRUCTOR_DELEGATE_INDEX);
__ Jump(masm->isolate()->builtins()->CallFunction(),
RelocInfo::CODE_TARGET);
}
// Called Construct on an Object that doesn't have a [[Construct]] internal
// method.
__ bind(&non_constructor);
__ Jump(BUILTIN_CODE(masm->isolate(), ConstructedNonConstructable),
RelocInfo::CODE_TARGET);
}
#if V8_ENABLE_WEBASSEMBLY
void Builtins::Generate_WasmCompileLazy(MacroAssembler* masm) {
// The function index was put in t0 by the jump table trampoline.
// Convert to Smi for the runtime call
__ SmiTag(kWasmCompileLazyFuncIndexRegister);
// Compute register lists for parameters to be saved. We save all parameter
// registers (see wasm-linkage.h). They might be overwritten in the runtime
// call below. We don't have any callee-saved registers in wasm, so no need to
// store anything else.
constexpr RegList kSavedGpRegs = ([]() constexpr {
RegList saved_gp_regs;
for (Register gp_param_reg : wasm::kGpParamRegisters) {
saved_gp_regs.set(gp_param_reg);
}
// All set registers were unique.
CHECK_EQ(saved_gp_regs.Count(), arraysize(wasm::kGpParamRegisters));
// The Wasm instance must be part of the saved registers.
CHECK(saved_gp_regs.has(kWasmInstanceRegister));
// + instance
CHECK_EQ(WasmCompileLazyFrameConstants::kNumberOfSavedGpParamRegs + 1,
saved_gp_regs.Count());
return saved_gp_regs;
})();
constexpr DoubleRegList kSavedFpRegs = ([]() constexpr {
DoubleRegList saved_fp_regs;
for (DoubleRegister fp_param_reg : wasm::kFpParamRegisters) {
saved_fp_regs.set(fp_param_reg);
}
CHECK_EQ(saved_fp_regs.Count(), arraysize(wasm::kFpParamRegisters));
CHECK_EQ(WasmCompileLazyFrameConstants::kNumberOfSavedFpParamRegs,
saved_fp_regs.Count());
return saved_fp_regs;
})();
{
HardAbortScope hard_abort(masm); // Avoid calls to Abort.
FrameScope scope(masm, StackFrame::WASM_COMPILE_LAZY);
// Save registers that we need to keep alive across the runtime call.
__ MultiPush(kSavedGpRegs);
__ MultiPushFPU(kSavedFpRegs);
// kFixedFrameSizeFromFp is hard coded to include space for Simd
// registers, so we still need to allocate extra (unused) space on the stack
// as if they were saved.
__ Sub_d(sp, sp, kSavedFpRegs.Count() * kDoubleSize);
// Pass instance and function index as an explicit arguments to the runtime
// function.
// Allocate a stack slot, where the runtime function can spill a pointer to
// the the NativeModule.
__ Push(kWasmInstanceRegister, kWasmCompileLazyFuncIndexRegister, zero_reg);
// Initialize the JavaScript context with 0. CEntry will use it to
// set the current context on the isolate.
__ Move(kContextRegister, Smi::zero());
__ CallRuntime(Runtime::kWasmCompileLazy, 3);
// Untag the returned Smi into into t7, for later use.
static_assert(!kSavedGpRegs.has(t7));
__ SmiUntag(t7, a0);
__ Add_d(sp, sp, kSavedFpRegs.Count() * kDoubleSize);
// Restore registers.
__ MultiPopFPU(kSavedFpRegs);
__ MultiPop(kSavedGpRegs);
}
// The runtime function returned the jump table slot offset as a Smi (now in
// t7). Use that to compute the jump target.
static_assert(!kSavedGpRegs.has(t8));
__ Ld_d(t8, MemOperand(
kWasmInstanceRegister,
WasmInstanceObject::kJumpTableStartOffset - kHeapObjectTag));
__ Add_d(t7, t8, Operand(t7));
// Finally, jump to the jump table slot for the function.
__ Jump(t7);
}
void Builtins::Generate_WasmDebugBreak(MacroAssembler* masm) {
HardAbortScope hard_abort(masm); // Avoid calls to Abort.
{
FrameScope scope(masm, StackFrame::WASM_DEBUG_BREAK);
// Save all parameter registers. They might hold live values, we restore
// them after the runtime call.
__ MultiPush(WasmDebugBreakFrameConstants::kPushedGpRegs);
__ MultiPushFPU(WasmDebugBreakFrameConstants::kPushedFpRegs);
// Initialize the JavaScript context with 0. CEntry will use it to
// set the current context on the isolate.
__ Move(cp, Smi::zero());
__ CallRuntime(Runtime::kWasmDebugBreak, 0);
// Restore registers.
__ MultiPopFPU(WasmDebugBreakFrameConstants::kPushedFpRegs);
__ MultiPop(WasmDebugBreakFrameConstants::kPushedGpRegs);
}
__ Ret();
}
void Builtins::Generate_GenericJSToWasmWrapper(MacroAssembler* masm) {
__ Trap();
}
void Builtins::Generate_WasmReturnPromiseOnSuspend(MacroAssembler* masm) {
// TODO(v8:12191): Implement for this platform.
__ Trap();
}
void Builtins::Generate_WasmSuspend(MacroAssembler* masm) {
// TODO(v8:12191): Implement for this platform.
__ Trap();
}
void Builtins::Generate_WasmResume(MacroAssembler* masm) {
// TODO(v8:12191): Implement for this platform.
__ Trap();
}
void Builtins::Generate_WasmReject(MacroAssembler* masm) {
// TODO(v8:12191): Implement for this platform.
__ Trap();
}
void Builtins::Generate_WasmOnStackReplace(MacroAssembler* masm) {
// Only needed on x64.
__ Trap();
}
#endif // V8_ENABLE_WEBASSEMBLY
void Builtins::Generate_CEntry(MacroAssembler* masm, int result_size,
SaveFPRegsMode save_doubles, ArgvMode argv_mode,
bool builtin_exit_frame) {
// Called from JavaScript; parameters are on stack as if calling JS function
// a0: number of arguments including receiver
// a1: pointer to builtin function
// fp: frame pointer (restored after C call)
// sp: stack pointer (restored as callee's sp after C call)
// cp: current context (C callee-saved)
//
// If argv_mode == ArgvMode::kRegister:
// a2: pointer to the first argument
if (argv_mode == ArgvMode::kRegister) {
// Move argv into the correct register.
__ mov(s1, a2);
} else {
// Compute the argv pointer in a callee-saved register.
__ Alsl_d(s1, a0, sp, kPointerSizeLog2, t7);
__ Sub_d(s1, s1, kPointerSize);
}
// Enter the exit frame that transitions from JavaScript to C++.
FrameScope scope(masm, StackFrame::MANUAL);
__ EnterExitFrame(
save_doubles == SaveFPRegsMode::kSave, 0,
builtin_exit_frame ? StackFrame::BUILTIN_EXIT : StackFrame::EXIT);
// s0: number of arguments including receiver (C callee-saved)
// s1: pointer to first argument (C callee-saved)
// s2: pointer to builtin function (C callee-saved)
// Prepare arguments for C routine.
// a0 = argc
__ mov(s0, a0);
__ mov(s2, a1);
// We are calling compiled C/C++ code. a0 and a1 hold our two arguments. We
// also need to reserve the 4 argument slots on the stack.
__ AssertStackIsAligned();
// a0 = argc, a1 = argv, a2 = isolate
__ li(a2, ExternalReference::isolate_address(masm->isolate()));
__ mov(a1, s1);
__ StoreReturnAddressAndCall(s2);
// Result returned in a0 or a1:a0 - do not destroy these registers!
// Check result for exception sentinel.
Label exception_returned;
__ LoadRoot(a4, RootIndex::kException);
__ Branch(&exception_returned, eq, a4, Operand(a0));
// Check that there is no pending exception, otherwise we
// should have returned the exception sentinel.
if (FLAG_debug_code) {
Label okay;
ExternalReference pending_exception_address = ExternalReference::Create(
IsolateAddressId::kPendingExceptionAddress, masm->isolate());
__ li(a2, pending_exception_address);
__ Ld_d(a2, MemOperand(a2, 0));
__ LoadRoot(a4, RootIndex::kTheHoleValue);
// Cannot use check here as it attempts to generate call into runtime.
__ Branch(&okay, eq, a4, Operand(a2));
__ stop();
__ bind(&okay);
}
// Exit C frame and return.
// a0:a1: result
// sp: stack pointer
// fp: frame pointer
Register argc = argv_mode == ArgvMode::kRegister
// We don't want to pop arguments so set argc to no_reg.
? no_reg
// s0: still holds argc (callee-saved).
: s0;
__ LeaveExitFrame(save_doubles == SaveFPRegsMode::kSave, argc, EMIT_RETURN);
// Handling of exception.
__ bind(&exception_returned);
ExternalReference pending_handler_context_address = ExternalReference::Create(
IsolateAddressId::kPendingHandlerContextAddress, masm->isolate());
ExternalReference pending_handler_entrypoint_address =
ExternalReference::Create(
IsolateAddressId::kPendingHandlerEntrypointAddress, masm->isolate());
ExternalReference pending_handler_fp_address = ExternalReference::Create(
IsolateAddressId::kPendingHandlerFPAddress, masm->isolate());
ExternalReference pending_handler_sp_address = ExternalReference::Create(
IsolateAddressId::kPendingHandlerSPAddress, masm->isolate());
// Ask the runtime for help to determine the handler. This will set a0 to
// contain the current pending exception, don't clobber it.
ExternalReference find_handler =
ExternalReference::Create(Runtime::kUnwindAndFindExceptionHandler);
{
FrameScope scope(masm, StackFrame::MANUAL);
__ PrepareCallCFunction(3, 0, a0);
__ mov(a0, zero_reg);
__ mov(a1, zero_reg);
__ li(a2, ExternalReference::isolate_address(masm->isolate()));
__ CallCFunction(find_handler, 3);
}
// Retrieve the handler context, SP and FP.
__ li(cp, pending_handler_context_address);
__ Ld_d(cp, MemOperand(cp, 0));
__ li(sp, pending_handler_sp_address);
__ Ld_d(sp, MemOperand(sp, 0));
__ li(fp, pending_handler_fp_address);
__ Ld_d(fp, MemOperand(fp, 0));
// If the handler is a JS frame, restore the context to the frame. Note that
// the context will be set to (cp == 0) for non-JS frames.
Label zero;
__ Branch(&zero, eq, cp, Operand(zero_reg));
__ St_d(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
__ bind(&zero);
// Clear c_entry_fp, like we do in `LeaveExitFrame`.
{
UseScratchRegisterScope temps(masm);
Register scratch = temps.Acquire();
__ li(scratch, ExternalReference::Create(IsolateAddressId::kCEntryFPAddress,
masm->isolate()));
__ St_d(zero_reg, MemOperand(scratch, 0));
}
// Compute the handler entry address and jump to it.
__ li(t7, pending_handler_entrypoint_address);
__ Ld_d(t7, MemOperand(t7, 0));
__ Jump(t7);
}
void Builtins::Generate_DoubleToI(MacroAssembler* masm) {
Label done;
Register result_reg = t0;
Register scratch = GetRegisterThatIsNotOneOf(result_reg);
Register scratch2 = GetRegisterThatIsNotOneOf(result_reg, scratch);
Register scratch3 = GetRegisterThatIsNotOneOf(result_reg, scratch, scratch2);
DoubleRegister double_scratch = kScratchDoubleReg;
// Account for saved regs.
const int kArgumentOffset = 4 * kPointerSize;
__ Push(result_reg);
__ Push(scratch, scratch2, scratch3);
// Load double input.
__ Fld_d(double_scratch, MemOperand(sp, kArgumentOffset));
// Try a conversion to a signed integer.
__ ftintrz_w_d(double_scratch, double_scratch);
// Move the converted value into the result register.
__ movfr2gr_s(scratch3, double_scratch);
// Retrieve and restore the FCSR.
__ movfcsr2gr(scratch);
// Check for overflow and NaNs.
__ And(scratch, scratch,
kFCSRExceptionCauseMask ^ kFCSRDivideByZeroCauseMask);
// If we had no exceptions then set result_reg and we are done.
Label error;
__ Branch(&error, ne, scratch, Operand(zero_reg));
__ Move(result_reg, scratch3);
__ Branch(&done);
__ bind(&error);
// Load the double value and perform a manual truncation.
Register input_high = scratch2;
Register input_low = scratch3;
__ Ld_w(input_low,
MemOperand(sp, kArgumentOffset + Register::kMantissaOffset));
__ Ld_w(input_high,
MemOperand(sp, kArgumentOffset + Register::kExponentOffset));
Label normal_exponent;
// Extract the biased exponent in result.
__ bstrpick_w(result_reg, input_high,
HeapNumber::kExponentShift + HeapNumber::kExponentBits - 1,
HeapNumber::kExponentShift);
// Check for Infinity and NaNs, which should return 0.
__ Sub_w(scratch, result_reg, HeapNumber::kExponentMask);
__ Movz(result_reg, zero_reg, scratch);
__ Branch(&done, eq, scratch, Operand(zero_reg));
// Express exponent as delta to (number of mantissa bits + 31).
__ Sub_w(result_reg, result_reg,
Operand(HeapNumber::kExponentBias + HeapNumber::kMantissaBits + 31));
// If the delta is strictly positive, all bits would be shifted away,
// which means that we can return 0.
__ Branch(&normal_exponent, le, result_reg, Operand(zero_reg));
__ mov(result_reg, zero_reg);
__ Branch(&done);
__ bind(&normal_exponent);
const int kShiftBase = HeapNumber::kNonMantissaBitsInTopWord - 1;
// Calculate shift.
__ Add_w(scratch, result_reg,
Operand(kShiftBase + HeapNumber::kMantissaBits));
// Save the sign.
Register sign = result_reg;
result_reg = no_reg;
__ And(sign, input_high, Operand(HeapNumber::kSignMask));
// On ARM shifts > 31 bits are valid and will result in zero. On LOONG64 we
// need to check for this specific case.
Label high_shift_needed, high_shift_done;
__ Branch(&high_shift_needed, lt, scratch, Operand(32));
__ mov(input_high, zero_reg);
__ Branch(&high_shift_done);
__ bind(&high_shift_needed);
// Set the implicit 1 before the mantissa part in input_high.
__ Or(input_high, input_high,
Operand(1 << HeapNumber::kMantissaBitsInTopWord));
// Shift the mantissa bits to the correct position.
// We don't need to clear non-mantissa bits as they will be shifted away.
// If they weren't, it would mean that the answer is in the 32bit range.
__ sll_w(input_high, input_high, scratch);
__ bind(&high_shift_done);
// Replace the shifted bits with bits from the lower mantissa word.
Label pos_shift, shift_done;
__ li(kScratchReg, 32);
__ sub_w(scratch, kScratchReg, scratch);
__ Branch(&pos_shift, ge, scratch, Operand(zero_reg));
// Negate scratch.
__ Sub_w(scratch, zero_reg, scratch);
__ sll_w(input_low, input_low, scratch);
__ Branch(&shift_done);
__ bind(&pos_shift);
__ srl_w(input_low, input_low, scratch);
__ bind(&shift_done);
__ Or(input_high, input_high, Operand(input_low));
// Restore sign if necessary.
__ mov(scratch, sign);
result_reg = sign;
sign = no_reg;
__ Sub_w(result_reg, zero_reg, input_high);
__ Movz(result_reg, input_high, scratch);
__ bind(&done);
__ St_d(result_reg, MemOperand(sp, kArgumentOffset));
__ Pop(scratch, scratch2, scratch3);
__ Pop(result_reg);
__ Ret();
}
namespace {
int AddressOffset(ExternalReference ref0, ExternalReference ref1) {
int64_t offset = (ref0.address() - ref1.address());
DCHECK(static_cast<int>(offset) == offset);
return static_cast<int>(offset);
}
// Calls an API function. Allocates HandleScope, extracts returned value
// from handle and propagates exceptions. Restores context. stack_space
// - space to be unwound on exit (includes the call JS arguments space and
// the additional space allocated for the fast call).
void CallApiFunctionAndReturn(MacroAssembler* masm, Register function_address,
ExternalReference thunk_ref, int stack_space,
MemOperand* stack_space_operand,
MemOperand return_value_operand) {
Isolate* isolate = masm->isolate();
ExternalReference next_address =
ExternalReference::handle_scope_next_address(isolate);
const int kNextOffset = 0;
const int kLimitOffset = AddressOffset(
ExternalReference::handle_scope_limit_address(isolate), next_address);
const int kLevelOffset = AddressOffset(
ExternalReference::handle_scope_level_address(isolate), next_address);
DCHECK(function_address == a1 || function_address == a2);
Label profiler_enabled, end_profiler_check;
__ li(t7, ExternalReference::is_profiling_address(isolate));
__ Ld_b(t7, MemOperand(t7, 0));
__ Branch(&profiler_enabled, ne, t7, Operand(zero_reg));
__ li(t7, ExternalReference::address_of_runtime_stats_flag());
__ Ld_w(t7, MemOperand(t7, 0));
__ Branch(&profiler_enabled, ne, t7, Operand(zero_reg));
{
// Call the api function directly.
__ mov(t7, function_address);
__ Branch(&end_profiler_check);
}
__ bind(&profiler_enabled);
{
// Additional parameter is the address of the actual callback.
__ li(t7, thunk_ref);
}
__ bind(&end_profiler_check);
// Allocate HandleScope in callee-save registers.
__ li(s5, next_address);
__ Ld_d(s0, MemOperand(s5, kNextOffset));
__ Ld_d(s1, MemOperand(s5, kLimitOffset));
__ Ld_w(s2, MemOperand(s5, kLevelOffset));
__ Add_w(s2, s2, Operand(1));
__ St_w(s2, MemOperand(s5, kLevelOffset));
__ StoreReturnAddressAndCall(t7);
Label promote_scheduled_exception;
Label delete_allocated_handles;
Label leave_exit_frame;
Label return_value_loaded;
// Load value from ReturnValue.
__ Ld_d(a0, return_value_operand);
__ bind(&return_value_loaded);
// No more valid handles (the result handle was the last one). Restore
// previous handle scope.
__ St_d(s0, MemOperand(s5, kNextOffset));
if (FLAG_debug_code) {
__ Ld_w(a1, MemOperand(s5, kLevelOffset));
__ Check(eq, AbortReason::kUnexpectedLevelAfterReturnFromApiCall, a1,
Operand(s2));
}
__ Sub_w(s2, s2, Operand(1));
__ St_w(s2, MemOperand(s5, kLevelOffset));
__ Ld_d(kScratchReg, MemOperand(s5, kLimitOffset));
__ Branch(&delete_allocated_handles, ne, s1, Operand(kScratchReg));
// Leave the API exit frame.
__ bind(&leave_exit_frame);
if (stack_space_operand == nullptr) {
DCHECK_NE(stack_space, 0);
__ li(s0, Operand(stack_space));
} else {
DCHECK_EQ(stack_space, 0);
__ Ld_d(s0, *stack_space_operand);
}
static constexpr bool kDontSaveDoubles = false;
static constexpr bool kRegisterContainsSlotCount = false;
__ LeaveExitFrame(kDontSaveDoubles, s0, NO_EMIT_RETURN,
kRegisterContainsSlotCount);
// Check if the function scheduled an exception.
__ LoadRoot(a4, RootIndex::kTheHoleValue);
__ li(kScratchReg, ExternalReference::scheduled_exception_address(isolate));
__ Ld_d(a5, MemOperand(kScratchReg, 0));
__ Branch(&promote_scheduled_exception, ne, a4, Operand(a5));
__ Ret();
// Re-throw by promoting a scheduled exception.
__ bind(&promote_scheduled_exception);
__ TailCallRuntime(Runtime::kPromoteScheduledException);
// HandleScope limit has changed. Delete allocated extensions.
__ bind(&delete_allocated_handles);
__ St_d(s1, MemOperand(s5, kLimitOffset));
__ mov(s0, a0);
__ PrepareCallCFunction(1, s1);
__ li(a0, ExternalReference::isolate_address(isolate));
__ CallCFunction(ExternalReference::delete_handle_scope_extensions(), 1);
__ mov(a0, s0);
__ jmp(&leave_exit_frame);
}
} // namespace
void Builtins::Generate_CallApiCallback(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- cp : context
// -- a1 : api function address
// -- a2 : arguments count
// -- a3 : call data
// -- a0 : holder
// -- sp[0] : receiver
// -- sp[8] : first argument
// -- ...
// -- sp[(argc) * 8] : last argument
// -----------------------------------
Register api_function_address = a1;
Register argc = a2;
Register call_data = a3;
Register holder = a0;
Register scratch = t0;
Register base = t1; // For addressing MemOperands on the stack.
DCHECK(!AreAliased(api_function_address, argc, call_data, holder, scratch,
base));
using FCA = FunctionCallbackArguments;
static_assert(FCA::kArgsLength == 6);
static_assert(FCA::kNewTargetIndex == 5);
static_assert(FCA::kDataIndex == 4);
static_assert(FCA::kReturnValueOffset == 3);
static_assert(FCA::kReturnValueDefaultValueIndex == 2);
static_assert(FCA::kIsolateIndex == 1);
static_assert(FCA::kHolderIndex == 0);
// Set up FunctionCallbackInfo's implicit_args on the stack as follows:
//
// Target state:
// sp[0 * kPointerSize]: kHolder
// sp[1 * kPointerSize]: kIsolate
// sp[2 * kPointerSize]: undefined (kReturnValueDefaultValue)
// sp[3 * kPointerSize]: undefined (kReturnValue)
// sp[4 * kPointerSize]: kData
// sp[5 * kPointerSize]: undefined (kNewTarget)
// Set up the base register for addressing through MemOperands. It will point
// at the receiver (located at sp + argc * kPointerSize).
__ Alsl_d(base, argc, sp, kPointerSizeLog2, t7);
// Reserve space on the stack.
__ Sub_d(sp, sp, Operand(FCA::kArgsLength * kPointerSize));
// kHolder.
__ St_d(holder, MemOperand(sp, 0 * kPointerSize));
// kIsolate.
__ li(scratch, ExternalReference::isolate_address(masm->isolate()));
__ St_d(scratch, MemOperand(sp, 1 * kPointerSize));
// kReturnValueDefaultValue and kReturnValue.
__ LoadRoot(scratch, RootIndex::kUndefinedValue);
__ St_d(scratch, MemOperand(sp, 2 * kPointerSize));
__ St_d(scratch, MemOperand(sp, 3 * kPointerSize));
// kData.
__ St_d(call_data, MemOperand(sp, 4 * kPointerSize));
// kNewTarget.
__ St_d(scratch, MemOperand(sp, 5 * kPointerSize));
// Keep a pointer to kHolder (= implicit_args) in a scratch register.
// We use it below to set up the FunctionCallbackInfo object.
__ mov(scratch, sp);
// Allocate the v8::Arguments structure in the arguments' space since
// it's not controlled by GC.
static constexpr int kApiStackSpace = 4;
static constexpr bool kDontSaveDoubles = false;
FrameScope frame_scope(masm, StackFrame::MANUAL);
__ EnterExitFrame(kDontSaveDoubles, kApiStackSpace);
// EnterExitFrame may align the sp.
// FunctionCallbackInfo::implicit_args_ (points at kHolder as set up above).
// Arguments are after the return address (pushed by EnterExitFrame()).
__ St_d(scratch, MemOperand(sp, 1 * kPointerSize));
// FunctionCallbackInfo::values_ (points at the first varargs argument passed
// on the stack).
__ Add_d(scratch, scratch,
Operand((FCA::kArgsLength + 1) * kSystemPointerSize));
__ St_d(scratch, MemOperand(sp, 2 * kPointerSize));
// FunctionCallbackInfo::length_.
// Stored as int field, 32-bit integers within struct on stack always left
// justified by n64 ABI.
__ St_w(argc, MemOperand(sp, 3 * kPointerSize));
// We also store the number of bytes to drop from the stack after returning
// from the API function here.
// Note: Unlike on other architectures, this stores the number of slots to
// drop, not the number of bytes.
__ Add_d(scratch, argc, Operand(FCA::kArgsLength + 1 /* receiver */));
__ St_d(scratch, MemOperand(sp, 4 * kPointerSize));
// v8::InvocationCallback's argument.
DCHECK(!AreAliased(api_function_address, scratch, a0));
__ Add_d(a0, sp, Operand(1 * kPointerSize));
ExternalReference thunk_ref = ExternalReference::invoke_function_callback();
// There are two stack slots above the arguments we constructed on the stack.
// TODO(jgruber): Document what these arguments are.
static constexpr int kStackSlotsAboveFCA = 2;
MemOperand return_value_operand(
fp, (kStackSlotsAboveFCA + FCA::kReturnValueOffset) * kPointerSize);
static constexpr int kUseStackSpaceOperand = 0;
MemOperand stack_space_operand(sp, 4 * kPointerSize);
AllowExternalCallThatCantCauseGC scope(masm);
CallApiFunctionAndReturn(masm, api_function_address, thunk_ref,
kUseStackSpaceOperand, &stack_space_operand,
return_value_operand);
}
void Builtins::Generate_CallApiGetter(MacroAssembler* masm) {
// Build v8::PropertyCallbackInfo::args_ array on the stack and push property
// name below the exit frame to make GC aware of them.
static_assert(PropertyCallbackArguments::kShouldThrowOnErrorIndex == 0);
static_assert(PropertyCallbackArguments::kHolderIndex == 1);
static_assert(PropertyCallbackArguments::kIsolateIndex == 2);
static_assert(PropertyCallbackArguments::kReturnValueDefaultValueIndex == 3);
static_assert(PropertyCallbackArguments::kReturnValueOffset == 4);
static_assert(PropertyCallbackArguments::kDataIndex == 5);
static_assert(PropertyCallbackArguments::kThisIndex == 6);
static_assert(PropertyCallbackArguments::kArgsLength == 7);
Register receiver = ApiGetterDescriptor::ReceiverRegister();
Register holder = ApiGetterDescriptor::HolderRegister();
Register callback = ApiGetterDescriptor::CallbackRegister();
Register scratch = a4;
DCHECK(!AreAliased(receiver, holder, callback, scratch));
Register api_function_address = a2;
// Here and below +1 is for name() pushed after the args_ array.
using PCA = PropertyCallbackArguments;
__ Sub_d(sp, sp, (PCA::kArgsLength + 1) * kPointerSize);
__ St_d(receiver, MemOperand(sp, (PCA::kThisIndex + 1) * kPointerSize));
__ Ld_d(scratch, FieldMemOperand(callback, AccessorInfo::kDataOffset));
__ St_d(scratch, MemOperand(sp, (PCA::kDataIndex + 1) * kPointerSize));
__ LoadRoot(scratch, RootIndex::kUndefinedValue);
__ St_d(scratch,
MemOperand(sp, (PCA::kReturnValueOffset + 1) * kPointerSize));
__ St_d(scratch, MemOperand(sp, (PCA::kReturnValueDefaultValueIndex + 1) *
kPointerSize));
__ li(scratch, ExternalReference::isolate_address(masm->isolate()));
__ St_d(scratch, MemOperand(sp, (PCA::kIsolateIndex + 1) * kPointerSize));
__ St_d(holder, MemOperand(sp, (PCA::kHolderIndex + 1) * kPointerSize));
// should_throw_on_error -> false
DCHECK_EQ(0, Smi::zero().ptr());
__ St_d(zero_reg,
MemOperand(sp, (PCA::kShouldThrowOnErrorIndex + 1) * kPointerSize));
__ Ld_d(scratch, FieldMemOperand(callback, AccessorInfo::kNameOffset));
__ St_d(scratch, MemOperand(sp, 0 * kPointerSize));
// v8::PropertyCallbackInfo::args_ array and name handle.
const int kStackUnwindSpace = PropertyCallbackArguments::kArgsLength + 1;
// Load address of v8::PropertyAccessorInfo::args_ array and name handle.
__ mov(a0, sp); // a0 = Handle<Name>
__ Add_d(a1, a0, Operand(1 * kPointerSize)); // a1 = v8::PCI::args_
const int kApiStackSpace = 1;
FrameScope frame_scope(masm, StackFrame::MANUAL);
__ EnterExitFrame(false, kApiStackSpace);
// Create v8::PropertyCallbackInfo object on the stack and initialize
// it's args_ field.
__ St_d(a1, MemOperand(sp, 1 * kPointerSize));
__ Add_d(a1, sp, Operand(1 * kPointerSize));
// a1 = v8::PropertyCallbackInfo&
ExternalReference thunk_ref =
ExternalReference::invoke_accessor_getter_callback();
__ Ld_d(
api_function_address,
FieldMemOperand(callback, AccessorInfo::kMaybeRedirectedGetterOffset));
// +3 is to skip prolog, return address and name handle.
MemOperand return_value_operand(
fp, (PropertyCallbackArguments::kReturnValueOffset + 3) * kPointerSize);
MemOperand* const kUseStackSpaceConstant = nullptr;
CallApiFunctionAndReturn(masm, api_function_address, thunk_ref,
kStackUnwindSpace, kUseStackSpaceConstant,
return_value_operand);
}
void Builtins::Generate_DirectCEntry(MacroAssembler* masm) {
// The sole purpose of DirectCEntry is for movable callers (e.g. any general
// purpose Code object) to be able to call into C functions that may trigger
// GC and thus move the caller.
//
// DirectCEntry places the return address on the stack (updated by the GC),
// making the call GC safe. The irregexp backend relies on this.
__ St_d(ra, MemOperand(sp, 0)); // Store the return address.
__ Call(t7); // Call the C++ function.
__ Ld_d(ra, MemOperand(sp, 0)); // Return to calling code.
// TODO(LOONG_dev): LOONG64 Check this assert.
if (FLAG_debug_code && FLAG_enable_slow_asserts) {
// In case of an error the return address may point to a memory area
// filled with kZapValue by the GC. Dereference the address and check for
// this.
__ Ld_d(a4, MemOperand(ra, 0));
__ Assert(ne, AbortReason::kReceivedInvalidReturnAddress, a4,
Operand(reinterpret_cast<uint64_t>(kZapValue)));
}
__ Jump(ra);
}
namespace {
// This code tries to be close to ia32 code so that any changes can be
// easily ported.
void Generate_DeoptimizationEntry(MacroAssembler* masm,
DeoptimizeKind deopt_kind) {
Isolate* isolate = masm->isolate();
// Unlike on ARM we don't save all the registers, just the useful ones.
// For the rest, there are gaps on the stack, so the offsets remain the same.
const int kNumberOfRegisters = Register::kNumRegisters;
RegList restored_regs = kJSCallerSaved | kCalleeSaved;
RegList saved_regs = restored_regs | sp | ra;
const int kDoubleRegsSize = kDoubleSize * DoubleRegister::kNumRegisters;
// Save all double FPU registers before messing with them.
__ Sub_d(sp, sp, Operand(kDoubleRegsSize));
const RegisterConfiguration* config = RegisterConfiguration::Default();
for (int i = 0; i < config->num_allocatable_double_registers(); ++i) {
int code = config->GetAllocatableDoubleCode(i);
const DoubleRegister fpu_reg = DoubleRegister::from_code(code);
int offset = code * kDoubleSize;
__ Fst_d(fpu_reg, MemOperand(sp, offset));
}
// Push saved_regs (needed to populate FrameDescription::registers_).
// Leave gaps for other registers.
__ Sub_d(sp, sp, kNumberOfRegisters * kPointerSize);
for (int16_t i = kNumberOfRegisters - 1; i >= 0; i--) {
if ((saved_regs.bits() & (1 << i)) != 0) {
__ St_d(ToRegister(i), MemOperand(sp, kPointerSize * i));
}
}
__ li(a2,
ExternalReference::Create(IsolateAddressId::kCEntryFPAddress, isolate));
__ St_d(fp, MemOperand(a2, 0));
const int kSavedRegistersAreaSize =
(kNumberOfRegisters * kPointerSize) + kDoubleRegsSize;
// Get the address of the location in the code object (a2) (return
// address for lazy deoptimization) and compute the fp-to-sp delta in
// register a3.
__ mov(a2, ra);
__ Add_d(a3, sp, Operand(kSavedRegistersAreaSize));
__ sub_d(a3, fp, a3);
// Allocate a new deoptimizer object.
__ PrepareCallCFunction(5, a4);
// Pass six arguments, according to n64 ABI.
__ mov(a0, zero_reg);
Label context_check;
__ Ld_d(a1, MemOperand(fp, CommonFrameConstants::kContextOrFrameTypeOffset));
__ JumpIfSmi(a1, &context_check);
__ Ld_d(a0, MemOperand(fp, StandardFrameConstants::kFunctionOffset));
__ bind(&context_check);
__ li(a1, Operand(static_cast<int>(deopt_kind)));
// a2: code address or 0 already loaded.
// a3: already has fp-to-sp delta.
__ li(a4, ExternalReference::isolate_address(isolate));
// Call Deoptimizer::New().
{
AllowExternalCallThatCantCauseGC scope(masm);
__ CallCFunction(ExternalReference::new_deoptimizer_function(), 5);
}
// Preserve "deoptimizer" object in register a0 and get the input
// frame descriptor pointer to a1 (deoptimizer->input_);
// Move deopt-obj to a0 for call to Deoptimizer::ComputeOutputFrames() below.
__ Ld_d(a1, MemOperand(a0, Deoptimizer::input_offset()));
// Copy core registers into FrameDescription::registers_[kNumRegisters].
DCHECK_EQ(Register::kNumRegisters, kNumberOfRegisters);
for (int i = 0; i < kNumberOfRegisters; i++) {
int offset = (i * kPointerSize) + FrameDescription::registers_offset();
if ((saved_regs.bits() & (1 << i)) != 0) {
__ Ld_d(a2, MemOperand(sp, i * kPointerSize));
__ St_d(a2, MemOperand(a1, offset));
} else if (FLAG_debug_code) {
__ li(a2, Operand(kDebugZapValue));
__ St_d(a2, MemOperand(a1, offset));
}
}
int double_regs_offset = FrameDescription::double_registers_offset();
// Copy FPU registers to
// double_registers_[DoubleRegister::kNumAllocatableRegisters]
for (int i = 0; i < config->num_allocatable_double_registers(); ++i) {
int code = config->GetAllocatableDoubleCode(i);
int dst_offset = code * kDoubleSize + double_regs_offset;
int src_offset = code * kDoubleSize + kNumberOfRegisters * kPointerSize;
__ Fld_d(f0, MemOperand(sp, src_offset));
__ Fst_d(f0, MemOperand(a1, dst_offset));
}
// Remove the saved registers from the stack.
__ Add_d(sp, sp, Operand(kSavedRegistersAreaSize));
// Compute a pointer to the unwinding limit in register a2; that is
// the first stack slot not part of the input frame.
__ Ld_d(a2, MemOperand(a1, FrameDescription::frame_size_offset()));
__ add_d(a2, a2, sp);
// Unwind the stack down to - but not including - the unwinding
// limit and copy the contents of the activation frame to the input
// frame description.
__ Add_d(a3, a1, Operand(FrameDescription::frame_content_offset()));
Label pop_loop;
Label pop_loop_header;
__ Branch(&pop_loop_header);
__ bind(&pop_loop);
__ Pop(a4);
__ St_d(a4, MemOperand(a3, 0));
__ addi_d(a3, a3, sizeof(uint64_t));
__ bind(&pop_loop_header);
__ BranchShort(&pop_loop, ne, a2, Operand(sp));
// Compute the output frame in the deoptimizer.
__ Push(a0); // Preserve deoptimizer object across call.
// a0: deoptimizer object; a1: scratch.
__ PrepareCallCFunction(1, a1);
// Call Deoptimizer::ComputeOutputFrames().
{
AllowExternalCallThatCantCauseGC scope(masm);
__ CallCFunction(ExternalReference::compute_output_frames_function(), 1);
}
__ Pop(a0); // Restore deoptimizer object (class Deoptimizer).
__ Ld_d(sp, MemOperand(a0, Deoptimizer::caller_frame_top_offset()));
// Replace the current (input) frame with the output frames.
Label outer_push_loop, inner_push_loop, outer_loop_header, inner_loop_header;
// Outer loop state: a4 = current "FrameDescription** output_",
// a1 = one past the last FrameDescription**.
__ Ld_w(a1, MemOperand(a0, Deoptimizer::output_count_offset()));
__ Ld_d(a4, MemOperand(a0, Deoptimizer::output_offset())); // a4 is output_.
__ Alsl_d(a1, a1, a4, kPointerSizeLog2);
__ Branch(&outer_loop_header);
__ bind(&outer_push_loop);
// Inner loop state: a2 = current FrameDescription*, a3 = loop index.
__ Ld_d(a2, MemOperand(a4, 0)); // output_[ix]
__ Ld_d(a3, MemOperand(a2, FrameDescription::frame_size_offset()));
__ Branch(&inner_loop_header);
__ bind(&inner_push_loop);
__ Sub_d(a3, a3, Operand(sizeof(uint64_t)));
__ Add_d(a6, a2, Operand(a3));
__ Ld_d(a7, MemOperand(a6, FrameDescription::frame_content_offset()));
__ Push(a7);
__ bind(&inner_loop_header);
__ BranchShort(&inner_push_loop, ne, a3, Operand(zero_reg));
__ Add_d(a4, a4, Operand(kPointerSize));
__ bind(&outer_loop_header);
__ BranchShort(&outer_push_loop, lt, a4, Operand(a1));
__ Ld_d(a1, MemOperand(a0, Deoptimizer::input_offset()));
for (int i = 0; i < config->num_allocatable_double_registers(); ++i) {
int code = config->GetAllocatableDoubleCode(i);
const DoubleRegister fpu_reg = DoubleRegister::from_code(code);
int src_offset = code * kDoubleSize + double_regs_offset;
__ Fld_d(fpu_reg, MemOperand(a1, src_offset));
}
// Push pc and continuation from the last output frame.
__ Ld_d(a6, MemOperand(a2, FrameDescription::pc_offset()));
__ Push(a6);
__ Ld_d(a6, MemOperand(a2, FrameDescription::continuation_offset()));
__ Push(a6);
// Technically restoring 'at' should work unless zero_reg is also restored
// but it's safer to check for this.
DCHECK(!(restored_regs.has(t7)));
// Restore the registers from the last output frame.
__ mov(t7, a2);
for (int i = kNumberOfRegisters - 1; i >= 0; i--) {
int offset = (i * kPointerSize) + FrameDescription::registers_offset();
if ((restored_regs.bits() & (1 << i)) != 0) {
__ Ld_d(ToRegister(i), MemOperand(t7, offset));
}
}
__ Pop(t7); // Get continuation, leave pc on stack.
__ Pop(ra);
__ Jump(t7);
__ stop();
}
} // namespace
void Builtins::Generate_DeoptimizationEntry_Eager(MacroAssembler* masm) {
Generate_DeoptimizationEntry(masm, DeoptimizeKind::kEager);
}
void Builtins::Generate_DeoptimizationEntry_Lazy(MacroAssembler* masm) {
Generate_DeoptimizationEntry(masm, DeoptimizeKind::kLazy);
}
namespace {
// Restarts execution either at the current or next (in execution order)
// bytecode. If there is baseline code on the shared function info, converts an
// interpreter frame into a baseline frame and continues execution in baseline
// code. Otherwise execution continues with bytecode.
void Generate_BaselineOrInterpreterEntry(MacroAssembler* masm,
bool next_bytecode,
bool is_osr = false) {
Label start;
__ bind(&start);
// Get function from the frame.
Register closure = a1;
__ Ld_d(closure, MemOperand(fp, StandardFrameConstants::kFunctionOffset));
// Get the Code object from the shared function info.
Register code_obj = s1;
__ Ld_d(code_obj,
FieldMemOperand(closure, JSFunction::kSharedFunctionInfoOffset));
__ Ld_d(code_obj,
FieldMemOperand(code_obj, SharedFunctionInfo::kFunctionDataOffset));
// Check if we have baseline code. For OSR entry it is safe to assume we
// always have baseline code.
if (!is_osr) {
Label start_with_baseline;
__ GetObjectType(code_obj, t2, t2);
__ Branch(&start_with_baseline, eq, t2, Operand(CODET_TYPE));
// Start with bytecode as there is no baseline code.
Builtin builtin_id = next_bytecode
? Builtin::kInterpreterEnterAtNextBytecode
: Builtin::kInterpreterEnterAtBytecode;
__ Jump(masm->isolate()->builtins()->code_handle(builtin_id),
RelocInfo::CODE_TARGET);
// Start with baseline code.
__ bind(&start_with_baseline);
} else if (FLAG_debug_code) {
__ GetObjectType(code_obj, t2, t2);
__ Assert(eq, AbortReason::kExpectedBaselineData, t2, Operand(CODET_TYPE));
}
if (FLAG_debug_code) {
AssertCodeIsBaseline(masm, code_obj, t2);
}
// Replace BytecodeOffset with the feedback vector.
Register feedback_vector = a2;
__ Ld_d(feedback_vector,
FieldMemOperand(closure, JSFunction::kFeedbackCellOffset));
__ Ld_d(feedback_vector,
FieldMemOperand(feedback_vector, Cell::kValueOffset));
Label install_baseline_code;
// Check if feedback vector is valid. If not, call prepare for baseline to
// allocate it.
__ GetObjectType(feedback_vector, t2, t2);
__ Branch(&install_baseline_code, ne, t2, Operand(FEEDBACK_VECTOR_TYPE));
// Save BytecodeOffset from the stack frame.
__ SmiUntag(kInterpreterBytecodeOffsetRegister,
MemOperand(fp, InterpreterFrameConstants::kBytecodeOffsetFromFp));
// Replace BytecodeOffset with the feedback vector.
__ St_d(feedback_vector,
MemOperand(fp, InterpreterFrameConstants::kBytecodeOffsetFromFp));
feedback_vector = no_reg;
// Compute baseline pc for bytecode offset.
ExternalReference get_baseline_pc_extref;
if (next_bytecode || is_osr) {
get_baseline_pc_extref =
ExternalReference::baseline_pc_for_next_executed_bytecode();
} else {
get_baseline_pc_extref =
ExternalReference::baseline_pc_for_bytecode_offset();
}
Register get_baseline_pc = a3;
__ li(get_baseline_pc, get_baseline_pc_extref);
// If the code deoptimizes during the implicit function entry stack interrupt
// check, it will have a bailout ID of kFunctionEntryBytecodeOffset, which is
// not a valid bytecode offset.
// TODO(pthier): Investigate if it is feasible to handle this special case
// in TurboFan instead of here.
Label valid_bytecode_offset, function_entry_bytecode;
if (!is_osr) {
__ Branch(&function_entry_bytecode, eq, kInterpreterBytecodeOffsetRegister,
Operand(BytecodeArray::kHeaderSize - kHeapObjectTag +
kFunctionEntryBytecodeOffset));
}
__ Sub_d(kInterpreterBytecodeOffsetRegister,
kInterpreterBytecodeOffsetRegister,
(BytecodeArray::kHeaderSize - kHeapObjectTag));
__ bind(&valid_bytecode_offset);
// Get bytecode array from the stack frame.
__ Ld_d(kInterpreterBytecodeArrayRegister,
MemOperand(fp, InterpreterFrameConstants::kBytecodeArrayFromFp));
// Save the accumulator register, since it's clobbered by the below call.
__ Push(kInterpreterAccumulatorRegister);
{
Register arg_reg_1 = a0;
Register arg_reg_2 = a1;
Register arg_reg_3 = a2;
__ Move(arg_reg_1, code_obj);
__ Move(arg_reg_2, kInterpreterBytecodeOffsetRegister);
__ Move(arg_reg_3, kInterpreterBytecodeArrayRegister);
FrameScope scope(masm, StackFrame::INTERNAL);
__ PrepareCallCFunction(3, 0, a4);
__ CallCFunction(get_baseline_pc, 3, 0);
}
__ Add_d(code_obj, code_obj, kReturnRegister0);
__ Pop(kInterpreterAccumulatorRegister);
if (is_osr) {
// TODO(liuyu): Remove Ld as arm64 after register reallocation.
__ Ld_d(kInterpreterBytecodeArrayRegister,
MemOperand(fp, InterpreterFrameConstants::kBytecodeArrayFromFp));
ResetBytecodeAge(masm, kInterpreterBytecodeArrayRegister);
Generate_OSREntry(masm, code_obj,
Operand(Code::kHeaderSize - kHeapObjectTag));
} else {
__ Add_d(code_obj, code_obj, Code::kHeaderSize - kHeapObjectTag);
__ Jump(code_obj);
}
__ Trap(); // Unreachable.
if (!is_osr) {
__ bind(&function_entry_bytecode);
// If the bytecode offset is kFunctionEntryOffset, get the start address of
// the first bytecode.
__ mov(kInterpreterBytecodeOffsetRegister, zero_reg);
if (next_bytecode) {
__ li(get_baseline_pc,
ExternalReference::baseline_pc_for_bytecode_offset());
}
__ Branch(&valid_bytecode_offset);
}
__ bind(&install_baseline_code);
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ Push(kInterpreterAccumulatorRegister);
__ Push(closure);
__ CallRuntime(Runtime::kInstallBaselineCode, 1);
__ Pop(kInterpreterAccumulatorRegister);
}
// Retry from the start after installing baseline code.
__ Branch(&start);
}
} // namespace
void Builtins::Generate_BaselineOrInterpreterEnterAtBytecode(
MacroAssembler* masm) {
Generate_BaselineOrInterpreterEntry(masm, false);
}
void Builtins::Generate_BaselineOrInterpreterEnterAtNextBytecode(
MacroAssembler* masm) {
Generate_BaselineOrInterpreterEntry(masm, true);
}
void Builtins::Generate_InterpreterOnStackReplacement_ToBaseline(
MacroAssembler* masm) {
Generate_BaselineOrInterpreterEntry(masm, false, true);
}
void Builtins::Generate_RestartFrameTrampoline(MacroAssembler* masm) {
// Restart the current frame:
// - Look up current function on the frame.
// - Leave the frame.
// - Restart the frame by calling the function.
__ Ld_d(a1, MemOperand(fp, StandardFrameConstants::kFunctionOffset));
__ Ld_d(a0, MemOperand(fp, StandardFrameConstants::kArgCOffset));
__ LeaveFrame(StackFrame::INTERPRETED);
// The arguments are already in the stack (including any necessary padding),
// we should not try to massage the arguments again.
__ li(a2, Operand(kDontAdaptArgumentsSentinel));
__ InvokeFunction(a1, a2, a0, InvokeType::kJump);
}
#undef __
} // namespace internal
} // namespace v8
#endif // V8_TARGET_ARCH_LOONG64
| [
"[email protected]"
] | |
f05a777bda56cfbd2761e8775c1377d5d3239be8 | 426f26555e653f42cb17be0819d158ce8b8bfbf9 | /DirectX11SampleProj/DirectX11SampleProj/Source/Lib/WindowsSystem/WindowsSystem.cpp | de170d396a739f4ec06d3ac5fb669a8477cf7897 | [] | no_license | kou65/DirectX11Sample | dece4bfd2a0b5a6dc132f36e1f8876ec4b8aab5a | f9cc5c51b85804cd7759c75438e521b569bca426 | refs/heads/master | 2023-02-03T21:20:11.588400 | 2020-12-22T16:43:50 | 2020-12-22T16:43:50 | 299,990,258 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,274 | cpp | #include"WindowsSystem.h"
#include"../IOFunction/IOFunction.h"
namespace WindowsSystem {
bool ProcessMessage() {
// メッセージ受け取り用構造体
MSG msg;
while (PeekMessage(
&msg, // 取得メッセージ
NULL, // ウィンドウハンドル(ここはNULLにしないと終了しなかった)
0, // 取得メッセージの最大値
0, // 取得メッセージの最小値
PM_REMOVE // 取得メッセージの削除オプション
))
{
// 文字列入力系を受け取る
TranslateMessage(&msg);
// ウィンドウプロシージャを呼ぶ(重要)
DispatchMessage(&msg);
// 終了メッセージの時falseを返す(WM_QUITはスレッド用)
if (msg.message == WM_QUIT || msg.message == WM_NCDESTROY) {
return false;
}
break;
}
// メッセージ送信終了
return true;
}
void TextMessageBox(const std::string& string) {
MessageBoxA(NULL, string.c_str(), NULL, NULL);
}
void OutputDebugLog(const std::string& string) {
std::wstring wstr;
Utility::IOFunction::ToWString1(string,wstr);
OutputDebugString(wstr.c_str());
}
void OutputDebugLogLiteral(const std::string& string) {
OutputDebugStringA(string.c_str());
}
} | [
"[email protected]"
] | |
335b0bcd1ac0c327b0149b82a66aaa9e59ba34dd | 33eaafc0b1b10e1ae97a67981fe740234bc5d592 | /tests/RandomSAT/z3-master/src/ast/rewriter/ast_counter.h | 4509d25499c0ff14cf08009055b093cf1ed19908 | [
"MIT"
] | permissive | akinanop/mvl-solver | 6c21bec03422bb2366f146cb02e6bf916eea6dd0 | bfcc5b243e43bddcc34aba9c34e67d820fc708c8 | refs/heads/master | 2021-01-16T23:30:46.413902 | 2021-01-10T16:53:23 | 2021-01-10T16:53:23 | 48,694,935 | 6 | 2 | null | 2016-08-30T10:47:25 | 2015-12-28T13:55:32 | C++ | UTF-8 | C++ | false | false | 2,486 | h | /*++
Copyright (c) 2013 Microsoft Corporation
Module Name:
ast_counter.h
Abstract:
Routines for counting features of terms, such as free variables.
Author:
Nikolaj Bjorner (nbjorner) 2013-03-18.
Krystof Hoder (t-khoder) 2010-10-10.
Revision History:
Hoisted from dl_util.h 2013-03-18.
--*/
#ifndef AST_COUNTER_H_
#define AST_COUNTER_H_
#include "ast.h"
#include "map.h"
#include "uint_set.h"
#include "var_subst.h"
class counter {
protected:
typedef u_map<int> map_impl;
map_impl m_data;
public:
typedef map_impl::iterator iterator;
counter() {}
void reset() { m_data.reset(); }
iterator begin() const { return m_data.begin(); }
iterator end() const { return m_data.end(); }
void update(unsigned el, int delta);
int & get(unsigned el);
/**
\brief Increase values of elements in \c els by \c delta.
The function returns a reference to \c *this to allow for expressions like
counter().count(sz, arr).get_positive_count()
*/
counter & count(unsigned sz, const unsigned * els, int delta = 1);
counter & count(const unsigned_vector & els, int delta = 1) {
return count(els.size(), els.c_ptr(), delta);
}
void collect_positive(uint_set & acc) const;
unsigned get_positive_count() const;
bool get_max_positive(unsigned & res) const;
unsigned get_max_positive() const;
/**
Since the default counter value of a counter is zero, the result is never negative.
*/
int get_max_counter_value() const;
};
class var_counter : public counter {
protected:
expr_fast_mark1 m_visited;
expr_free_vars m_fv;
ptr_vector<expr> m_todo;
unsigned_vector m_scopes;
unsigned get_max_var(bool & has_var);
public:
var_counter() {}
void count_vars(const app * t, int coef = 1);
unsigned get_max_var(expr* e);
unsigned get_next_var(expr* e);
};
class ast_counter {
typedef obj_map<ast, int> map_impl;
map_impl m_data;
public:
typedef map_impl::iterator iterator;
ast_counter() {}
iterator begin() const { return m_data.begin(); }
iterator end() const { return m_data.end(); }
int & get(ast * el) {
return m_data.insert_if_not_there2(el, 0)->get_data().m_value;
}
void update(ast * el, int delta){
get(el) += delta;
}
void inc(ast * el) { update(el, 1); }
void dec(ast * el) { update(el, -1); }
};
#endif
| [
"[email protected]"
] | |
9756d496075cc95d4bd2f35f40c5167162dbd7f2 | 002902560639e77c5c9606af0fad90ff2334db1e | /1027A.cpp | fe6e81a649f83e5e15ed35497d42687a1e157f0a | [] | no_license | Hasanzakaria/CODEFORCES | 8662b464133d6058b74ea6bbbe0c6fd78366df9d | da08f70a3eae047e2da610b8a7aa3cc704b10202 | refs/heads/master | 2022-11-08T16:59:31.128716 | 2020-06-26T14:18:15 | 2020-06-26T14:18:15 | 275,172,665 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 634 | cpp | #include<bits/stdc++.h>
using namespace std;
int main ()
{
ios_base::sync_with_stdio(0);
long long int n,i,k,j,t,r,flag;
string a;
cin>>n;
for(i=1; i<=n; i++)
{
flag=0;
cin>>k;
cin>>a;
r=k-1;
for(j=0; j<=(k/2); j++)
{
t=a[j]-a[r];
r--;
if(t<0)
{
t=-t;
}
if(t!=0&&t!=2)
{
flag=1;
}
}
if(flag==0)
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
}
} | [
"[email protected]"
] | |
6d547916e096624767c173fe875cfd59626eb8bb | 21df29f0aca4ea68bf922fadaae52772bea993ad | /src/miner.cpp | aae58a120ecdb387bf893348f9a9fa78ac8d2ef8 | [
"MIT"
] | permissive | RegulusBit/utabit13 | 48767b2bdfb9e0872d66d1f530c64c09aaba679b | eb8b301e77fe116a43df87fabe1cb45da358213a | refs/heads/master | 2019-07-13T05:22:36.037577 | 2017-07-26T16:44:41 | 2017-07-26T16:44:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,834 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Utabit Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "miner.h"
#include "amount.h"
#include "chain.h"
#include "chainparams.h"
#include "coins.h"
#include "consensus/consensus.h"
#include "consensus/merkle.h"
#include "consensus/validation.h"
#include "hash.h"
#include "main.h"
#include "net.h"
#include "policy/policy.h"
#include "pow.h"
#include "primitives/transaction.h"
#include "script/standard.h"
#include "timedata.h"
#include "txmempool.h"
#include "util.h"
#include "utilmoneystr.h"
#include "validationinterface.h"
#include <algorithm>
#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>
#include <queue>
using namespace std;
//////////////////////////////////////////////////////////////////////////////
//
// UtabitMiner
//
//
// Unconfirmed transactions in the memory pool often depend on other
// transactions in the memory pool. When we select transactions from the
// pool, we select by highest priority or fee rate, so we might consider
// transactions that depend on transactions that aren't yet in the block.
uint64_t nLastBlockTx = 0;
uint64_t nLastBlockSize = 0;
uint64_t nLastBlockWeight = 0;
class ScoreCompare
{
public:
ScoreCompare() {}
bool operator()(const CTxMemPool::txiter a, const CTxMemPool::txiter b)
{
return CompareTxMemPoolEntryByScore()(*b,*a); // Convert to less than
}
};
int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
{
int64_t nOldTime = pblock->nTime;
int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
if (nOldTime < nNewTime)
pblock->nTime = nNewTime;
// Updating time can change work required on testnet:
if (consensusParams.fPowAllowMinDifficultyBlocks)
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
return nNewTime - nOldTime;
}
BlockAssembler::BlockAssembler(const CChainParams& _chainparams)
: chainparams(_chainparams)
{
// Block resource limits
// If neither -blockmaxsize or -blockmaxweight is given, limit to DEFAULT_BLOCK_MAX_*
// If only one is given, only restrict the specified resource.
// If both are given, restrict both.
nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE;
bool fWeightSet = false;
if (mapArgs.count("-blockmaxweight")) {
nBlockMaxWeight = GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
nBlockMaxSize = MAX_BLOCK_SERIALIZED_SIZE;
fWeightSet = true;
}
if (mapArgs.count("-blockmaxsize")) {
nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
if (!fWeightSet) {
nBlockMaxWeight = nBlockMaxSize * WITNESS_SCALE_FACTOR;
}
}
// Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity:
nBlockMaxWeight = std::max((unsigned int)4000, std::min((unsigned int)(MAX_BLOCK_WEIGHT-4000), nBlockMaxWeight));
// Limit size to between 1K and MAX_BLOCK_SERIALIZED_SIZE-1K for sanity:
nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SERIALIZED_SIZE-1000), nBlockMaxSize));
// Whether we need to account for byte usage (in addition to weight usage)
fNeedSizeAccounting = (nBlockMaxSize < MAX_BLOCK_SERIALIZED_SIZE-1000);
}
void BlockAssembler::resetBlock()
{
inBlock.clear();
// Reserve space for coinbase tx
nBlockSize = 1000;
nBlockWeight = 4000;
nBlockSigOpsCost = 400;
fIncludeWitness = false;
// These counters do not include coinbase tx
nBlockTx = 0;
nFees = 0;
lastFewTxs = 0;
blockFinished = false;
}
CBlockTemplate* BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn)
{
resetBlock();
pblocktemplate.reset(new CBlockTemplate());
if(!pblocktemplate.get())
return NULL;
pblock = &pblocktemplate->block; // pointer for convenience
// Add dummy coinbase tx as first transaction
pblock->vtx.push_back(CTransaction());
pblocktemplate->vTxFees.push_back(-1); // updated at end
pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
LOCK2(cs_main, mempool.cs);
CBlockIndex* pindexPrev = chainActive.Tip();
nHeight = pindexPrev->nHeight + 1;
pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
// -regtest only: allow overriding block.nVersion with
// -blockversion=N to test forking scenarios
if (chainparams.MineBlocksOnDemand())
pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
pblock->nTime = GetAdjustedTime();
const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
? nMedianTimePast
: pblock->GetBlockTime();
// Decide whether to include witness transactions
// This is only needed in case the witness softfork activation is reverted
// (which would require a very deep reorganization) or when
// -promiscuousmempoolflags is used.
// TODO: replace this with a call to main to assess validity of a mempool
// transaction (which in most cases can be a no-op).
fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus());
addPriorityTxs();
addPackageTxs();
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
nLastBlockWeight = nBlockWeight;
// Create coinbase transaction.
CMutableTransaction coinbaseTx;
coinbaseTx.vin.resize(1);
coinbaseTx.vin[0].prevout.SetNull();
coinbaseTx.vout.resize(1);
coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
pblock->vtx[0] = coinbaseTx;
pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus());
pblocktemplate->vTxFees[0] = -nFees;
uint64_t nSerializeSize = GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION);
LogPrintf("CreateNewBlock(): total size: %u block weight: %u txs: %u fees: %ld sigops %d\n", nSerializeSize, GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
pblock->nNonce = 0;
pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(pblock->vtx[0]);
CValidationState state;
if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
}
return pblocktemplate.release();
}
bool BlockAssembler::isStillDependent(CTxMemPool::txiter iter)
{
BOOST_FOREACH(CTxMemPool::txiter parent, mempool.GetMemPoolParents(iter))
{
if (!inBlock.count(parent)) {
return true;
}
}
return false;
}
void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
{
for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
// Only test txs not already in the block
if (inBlock.count(*iit)) {
testSet.erase(iit++);
}
else {
iit++;
}
}
}
bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost)
{
// TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight)
return false;
if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST)
return false;
return true;
}
// Perform transaction-level checks before adding to block:
// - transaction finality (locktime)
// - premature witness (in case segwit transactions are added to mempool before
// segwit activation)
// - serialized size (in case -blockmaxsize is in use)
bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package)
{
uint64_t nPotentialBlockSize = nBlockSize; // only used with fNeedSizeAccounting
BOOST_FOREACH (const CTxMemPool::txiter it, package) {
if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff))
return false;
if (!fIncludeWitness && !it->GetTx().wit.IsNull())
return false;
if (fNeedSizeAccounting) {
uint64_t nTxSize = ::GetSerializeSize(it->GetTx(), SER_NETWORK, PROTOCOL_VERSION);
if (nPotentialBlockSize + nTxSize >= nBlockMaxSize) {
return false;
}
nPotentialBlockSize += nTxSize;
}
}
return true;
}
bool BlockAssembler::TestForBlock(CTxMemPool::txiter iter)
{
if (nBlockWeight + iter->GetTxWeight() >= nBlockMaxWeight) {
// If the block is so close to full that no more txs will fit
// or if we've tried more than 50 times to fill remaining space
// then flag that the block is finished
if (nBlockWeight > nBlockMaxWeight - 400 || lastFewTxs > 50) {
blockFinished = true;
return false;
}
// Once we're within 4000 weight of a full block, only look at 50 more txs
// to try to fill the remaining space.
if (nBlockWeight > nBlockMaxWeight - 4000) {
lastFewTxs++;
}
return false;
}
if (fNeedSizeAccounting) {
if (nBlockSize + ::GetSerializeSize(iter->GetTx(), SER_NETWORK, PROTOCOL_VERSION) >= nBlockMaxSize) {
if (nBlockSize > nBlockMaxSize - 100 || lastFewTxs > 50) {
blockFinished = true;
return false;
}
if (nBlockSize > nBlockMaxSize - 1000) {
lastFewTxs++;
}
return false;
}
}
if (nBlockSigOpsCost + iter->GetSigOpCost() >= MAX_BLOCK_SIGOPS_COST) {
// If the block has room for no more sig ops then
// flag that the block is finished
if (nBlockSigOpsCost > MAX_BLOCK_SIGOPS_COST - 8) {
blockFinished = true;
return false;
}
// Otherwise attempt to find another tx with fewer sigops
// to put in the block.
return false;
}
// Must check that lock times are still valid
// This can be removed once MTP is always enforced
// as long as reorgs keep the mempool consistent.
if (!IsFinalTx(iter->GetTx(), nHeight, nLockTimeCutoff))
return false;
return true;
}
void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
{
pblock->vtx.push_back(iter->GetTx());
pblocktemplate->vTxFees.push_back(iter->GetFee());
pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
if (fNeedSizeAccounting) {
nBlockSize += ::GetSerializeSize(iter->GetTx(), SER_NETWORK, PROTOCOL_VERSION);
}
nBlockWeight += iter->GetTxWeight();
++nBlockTx;
nBlockSigOpsCost += iter->GetSigOpCost();
nFees += iter->GetFee();
inBlock.insert(iter);
bool fPrintPriority = GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
if (fPrintPriority) {
double dPriority = iter->GetPriority(nHeight);
CAmount dummy;
mempool.ApplyDeltas(iter->GetTx().GetHash(), dPriority, dummy);
LogPrintf("priority %.1f fee %s txid %s\n",
dPriority,
CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
iter->GetTx().GetHash().ToString());
}
}
void BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded,
indexed_modified_transaction_set &mapModifiedTx)
{
BOOST_FOREACH(const CTxMemPool::txiter it, alreadyAdded) {
CTxMemPool::setEntries descendants;
mempool.CalculateDescendants(it, descendants);
// Insert all descendants (not yet in block) into the modified set
BOOST_FOREACH(CTxMemPool::txiter desc, descendants) {
if (alreadyAdded.count(desc))
continue;
modtxiter mit = mapModifiedTx.find(desc);
if (mit == mapModifiedTx.end()) {
CTxMemPoolModifiedEntry modEntry(desc);
modEntry.nSizeWithAncestors -= it->GetTxSize();
modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost();
mapModifiedTx.insert(modEntry);
} else {
mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
}
}
}
}
// Skip entries in mapTx that are already in a block or are present
// in mapModifiedTx (which implies that the mapTx ancestor state is
// stale due to ancestor inclusion in the block)
// Also skip transactions that we've already failed to add. This can happen if
// we consider a transaction in mapModifiedTx and it fails: we can then
// potentially consider it again while walking mapTx. It's currently
// guaranteed to fail again, but as a belt-and-suspenders check we put it in
// failedTx and avoid re-evaluation, since the re-evaluation would be using
// cached size/sigops/fee values that are not actually correct.
bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx)
{
assert (it != mempool.mapTx.end());
if (mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it))
return true;
return false;
}
void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries)
{
// Sort package by ancestor count
// If a transaction A depends on transaction B, then A's ancestor count
// must be greater than B's. So this is sufficient to validly order the
// transactions for block inclusion.
sortedEntries.clear();
sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
}
// This transaction selection algorithm orders the mempool based
// on feerate of a transaction including all unconfirmed ancestors.
// Since we don't remove transactions from the mempool as we select them
// for block inclusion, we need an alternate method of updating the feerate
// of a transaction with its not-yet-selected ancestors as we go.
// This is accomplished by walking the in-mempool descendants of selected
// transactions and storing a temporary modified state in mapModifiedTxs.
// Each time through the loop, we compare the best transaction in
// mapModifiedTxs with the next transaction in the mempool to decide what
// transaction package to work on next.
void BlockAssembler::addPackageTxs()
{
// mapModifiedTx will store sorted packages after they are modified
// because some of their txs are already in the block
indexed_modified_transaction_set mapModifiedTx;
// Keep track of entries that failed inclusion, to avoid duplicate work
CTxMemPool::setEntries failedTx;
// Start by adding all descendants of previously added txs to mapModifiedTx
// and modifying them for their already included ancestors
UpdatePackagesForAdded(inBlock, mapModifiedTx);
CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
CTxMemPool::txiter iter;
while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty())
{
// First try to find a new transaction in mapTx to evaluate.
if (mi != mempool.mapTx.get<ancestor_score>().end() &&
SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
++mi;
continue;
}
// Now that mi is not stale, determine which transaction to evaluate:
// the next entry from mapTx, or the best from mapModifiedTx?
bool fUsingModified = false;
modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
if (mi == mempool.mapTx.get<ancestor_score>().end()) {
// We're out of entries in mapTx; use the entry from mapModifiedTx
iter = modit->iter;
fUsingModified = true;
} else {
// Try to compare the mapTx entry to the mapModifiedTx entry
iter = mempool.mapTx.project<0>(mi);
if (modit != mapModifiedTx.get<ancestor_score>().end() &&
CompareModifiedEntry()(*modit, CTxMemPoolModifiedEntry(iter))) {
// The best entry in mapModifiedTx has higher score
// than the one from mapTx.
// Switch which transaction (package) to consider
iter = modit->iter;
fUsingModified = true;
} else {
// Either no entry in mapModifiedTx, or it's worse than mapTx.
// Increment mi for the next loop iteration.
++mi;
}
}
// We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
// contain anything that is inBlock.
assert(!inBlock.count(iter));
uint64_t packageSize = iter->GetSizeWithAncestors();
CAmount packageFees = iter->GetModFeesWithAncestors();
int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
if (fUsingModified) {
packageSize = modit->nSizeWithAncestors;
packageFees = modit->nModFeesWithAncestors;
packageSigOpsCost = modit->nSigOpCostWithAncestors;
}
if (packageFees < ::minRelayTxFee.GetFee(packageSize)) {
// Everything else we might consider has a lower fee rate
return;
}
if (!TestPackage(packageSize, packageSigOpsCost)) {
if (fUsingModified) {
// Since we always look at the best entry in mapModifiedTx,
// we must erase failed entries so that we can consider the
// next best entry on the next loop iteration
mapModifiedTx.get<ancestor_score>().erase(modit);
failedTx.insert(iter);
}
continue;
}
CTxMemPool::setEntries ancestors;
uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
onlyUnconfirmed(ancestors);
ancestors.insert(iter);
// Test if all tx's are Final
if (!TestPackageTransactions(ancestors)) {
if (fUsingModified) {
mapModifiedTx.get<ancestor_score>().erase(modit);
failedTx.insert(iter);
}
continue;
}
// Package can be added. Sort the entries in a valid order.
vector<CTxMemPool::txiter> sortedEntries;
SortForBlock(ancestors, iter, sortedEntries);
for (size_t i=0; i<sortedEntries.size(); ++i) {
AddToBlock(sortedEntries[i]);
// Erase from the modified set, if present
mapModifiedTx.erase(sortedEntries[i]);
}
// Update transactions that depend on each of these
UpdatePackagesForAdded(ancestors, mapModifiedTx);
}
}
void BlockAssembler::addPriorityTxs()
{
// How much of the block should be dedicated to high-priority transactions,
// included regardless of the fees they pay
unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
if (nBlockPrioritySize == 0) {
return;
}
bool fSizeAccounting = fNeedSizeAccounting;
fNeedSizeAccounting = true;
// This vector will be sorted into a priority queue:
vector<TxCoinAgePriority> vecPriority;
TxCoinAgePriorityCompare pricomparer;
std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash> waitPriMap;
typedef std::map<CTxMemPool::txiter, double, CTxMemPool::CompareIteratorByHash>::iterator waitPriIter;
double actualPriority = -1;
vecPriority.reserve(mempool.mapTx.size());
for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
mi != mempool.mapTx.end(); ++mi)
{
double dPriority = mi->GetPriority(nHeight);
CAmount dummy;
mempool.ApplyDeltas(mi->GetTx().GetHash(), dPriority, dummy);
vecPriority.push_back(TxCoinAgePriority(dPriority, mi));
}
std::make_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
CTxMemPool::txiter iter;
while (!vecPriority.empty() && !blockFinished) { // add a tx from priority queue to fill the blockprioritysize
iter = vecPriority.front().second;
actualPriority = vecPriority.front().first;
std::pop_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
vecPriority.pop_back();
// If tx already in block, skip
if (inBlock.count(iter)) {
assert(false); // shouldn't happen for priority txs
continue;
}
// cannot accept witness transactions into a non-witness block
if (!fIncludeWitness && !iter->GetTx().wit.IsNull())
continue;
// If tx is dependent on other mempool txs which haven't yet been included
// then put it in the waitSet
if (isStillDependent(iter)) {
waitPriMap.insert(std::make_pair(iter, actualPriority));
continue;
}
// If this tx fits in the block add it, otherwise keep looping
if (TestForBlock(iter)) {
AddToBlock(iter);
// If now that this txs is added we've surpassed our desired priority size
// or have dropped below the AllowFreeThreshold, then we're done adding priority txs
if (nBlockSize >= nBlockPrioritySize || !AllowFree(actualPriority)) {
break;
}
// This tx was successfully added, so
// add transactions that depend on this one to the priority queue to try again
BOOST_FOREACH(CTxMemPool::txiter child, mempool.GetMemPoolChildren(iter))
{
waitPriIter wpiter = waitPriMap.find(child);
if (wpiter != waitPriMap.end()) {
vecPriority.push_back(TxCoinAgePriority(wpiter->second,child));
std::push_heap(vecPriority.begin(), vecPriority.end(), pricomparer);
waitPriMap.erase(wpiter);
}
}
}
}
fNeedSizeAccounting = fSizeAccounting;
}
void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
CMutableTransaction txCoinbase(pblock->vtx[0]);
txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
assert(txCoinbase.vin[0].scriptSig.size() <= 100);
pblock->vtx[0] = txCoinbase;
pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
}
| [
"[email protected]"
] | |
a79f9904847b304bdb95f1d16a33ff26a5ef9749 | a7dc9df7ecc9438c96b7a33038a3c70f0ff5bc86 | /jml/algebra/lapack.cc | 76250e0acb7cee12677ee51a7dff7b6a265deed1 | [
"Apache-2.0",
"LGPL-2.0-or-later",
"AGPL-3.0-only"
] | permissive | duyet/BGateRTB | ca19a2f23fad6a5063ec4463a3049984ed09ec67 | ea1782f7cd89a15e64cd87a175816ee68aee8934 | refs/heads/master | 2022-07-24T03:45:05.099793 | 2022-07-17T11:20:43 | 2022-07-17T11:20:43 | 37,047,062 | 0 | 0 | Apache-2.0 | 2022-07-17T11:21:09 | 2015-06-08T05:10:18 | C++ | UTF-8 | C++ | false | false | 20,015 | cc | /* lapack.cc
Jeremy Barnes, 5 November 2004
Copyright (c) 2004 Jeremy Barnes All rights reserved.
$Source$
LAPACK interface.
*/
#include "lapack.h"
#include <vector>
#include <boost/scoped_array.hpp>
#include <cmath>
#include "jml/arch/threads.h"
#include "jml/arch/exception.h"
#include <iostream>
using namespace std;
extern "C" {
/* Definitions of the FORTRAN routines that implement the functionality. */
/* Information on the linear algebra environment. */
int ilaenv_(const int * ispec, const char * routine, const char * opts,
const int * n1, const int * n2, const int * n3, const int * n4);
/* Information about the machine precision */
float slamch_(const char * param);
double dlamch_(const char * param);
/* Constrained least squares. */
void sgglse_(const int * m, const int * n, const int * p,
float * A, const int * lda,
float * B, const int * ldb,
float * c, float * d, float * result,
float * workspace, const int * workspace_size, int * info);
/* Constrained least squares. */
void dgglse_(const int * m, const int * n, const int * p,
double * A, const int * lda,
double * B, const int * ldb,
double * c, double * d, double * result,
double * workspace, const int * workspace_size, int * info);
/* Rank deficient least squares. */
void sgelsd_(const int * m, const int * n, const int * nrhs,
float * A, const int * lda, float * B, const int * ldb,
float * S, const float * rcond, int * rank,
float * workspace, const int * workspace_size,
int * iworkspace, int * info);
/* Rank deficient least squares. */
void dgelsd_(const int * m, const int * n, const int * nrhs,
double * A, const int * lda, double * B, const int * ldb,
double * S, const double * rcond, int * rank,
double * workspace, const int * workspace_size,
int * iworkspace, int * info);
/* Full rank least squares. */
void sgels_(char * trans, const int * m, const int * n, const int * nrhs,
float * A, const int * lda, float * B, const int * ldb,
float * workspace, int * workspace_size, int * info);
/* Full rank least squares. */
void dgels_(char * trans, const int * m, const int * n, const int * nrhs,
double * A, const int * lda, double * B, const int * ldb,
double * workspace, int * workspace_size, int * info);
/* Convert general matrix to bidiagonal form. */
void dgebrd_(const int * m, const int * n, double * A, const int * lda,
double * D, double * E, double * tauq, double * taup,
double * workspace, int * workspace_size, int * info);
/* Extract orthogonal matrix from output of xgebrd. */
void dorgbr_(const char * vect, const int * m, const int * n,
const int * k, double * A, const int * lda, const double * tau,
double * work, int * workspace_size, int * info);
/* SVD of bidiagonal form. */
void dbdsdc_(const char * uplo, const char * compq, const int * n,
double * D, double * E,
double * U, const int * ldu,
double * VT, const int * ldvt,
double * Q, int * iq, double * workspace, int * iworkspace,
int * info);
/* SVD of matrix. */
void dgesvd_(const char * jobu, const char * jobvt, const int * m,
const int * n,
double * A, const int * lda,
double * S,
double * U, const int * ldu,
double * VT, const int * ldvt,
double * workspace, int * workspace_size, int * info);
/* Better SVD of a matrix. */
void sgesdd_(const char * jobz, const int * m, const int * n,
float * A, const int * lda,
float * S,
float * U, const int * ldu,
float * vt, const int * ldvt,
float * workspace, int * workspace_size,
int * iwork, int * info);
void dgesdd_(const char * jobz, const int * m, const int * n,
double * A, const int * lda,
double * S,
double * U, const int * ldu,
double * vt, const int * ldvt,
double * workspace, int * workspace_size,
int * iword, int * info);
/* Solve a system of linear equations. */
void dgesv_(const int * n, const int * nrhs, double * A, const int * lda,
int * pivots, double * B, const int * ldb, int * info);
/* Cholesky factorization */
void spotrf_(const char * uplo, const int * n, float * A, const int * lda,
int * info);
/* Cholesky factorization */
void dpotrf_(const char * uplo, const int * n, double * A, const int * lda,
int * info);
/* QR factorization with partial pivoting */
void sgeqp3_(const int * m, const int * n, float * A, const int * lda,
int * jpvt, float * tau, float * work, const int * lwork,
int * info);
/* QR factorization with partial pivoting */
void dgeqp3_(const int * m, const int * n, double * A, const int * lda,
int * jpvt, double * tau, double * work, const int * lwork,
int * info);
/* Matrix multiply */
void sgemm_(const int * m, const int * n, const int * k, const float * alpha,
const float * A, const int * lda, const float * b,
const int * ldb, const float * beta, float * c, const int * ldc,
int * info);
/* Matrix multiply */
void dgemm_(const int * m, const int * n, const int * k, const double * alpha,
const double * A, const int * lda, const double * b,
const int * ldb, const double * beta, double * c, const int * ldc,
int * info);
/* Elementary reflector. Used to detect version 3.2 of the LAPACK. Most
important thing is that if n < 0, it will return zero in tau. */
void slarfp_(const int * n, float * alpha, float * X, const int * incx,
float * tau);
} // extern "C"
namespace ML {
namespace LAPack {
namespace {
// TODO: Determine if we need to lock the LAPack based upon its version
// For lapack 3.1.x, yes we do
// for lapack 3.2.x, no we don't
// To determine, we look for the routine slarfp which was added in version 3.2.
// If we find it (our weak reference is ignored), then we know that we are in
// version 3.2. Otherwise, we know that there is a previous version.
bool lapack_version_3_2_or_later()
{
// We assume that these days we are using 3.2 or later. The slarfp
// function appears to have been removed from 3.3 and so this code
// no longer has the desired effect.
return true;
float tau, alpha, x;
// 234 is the special value for the slarfp_dummy function above
int n = -234, incx;
slarfp_(&n, &alpha, &x, &incx, &tau);
// If the dummy slarfp function ran, it will return 1.0, which means that
// we are using a version of lapack 3.1 or lower. If the lapack
// 3.2 version ran, it will return 0.0.
if (tau == 1.0) return false; // dummy version ran
if (tau == 0.0) return true;
throw Exception("unable to interpret result of slarfp");
}
static bool need_lock = true;
struct Init {
Init()
{
need_lock = !lapack_version_3_2_or_later();
// ilaenv isn't thread safe (it can return different results if it's
// called for the first time twice from two different threads; see
// http://icl.cs.utk.edu/lapack-forum/archives/lapack/msg00342.html
int ispec = 10;
const char * routine = "BONUS";
const char * opts = "T";
int n1 = 0, n2 = 0, n3 = 0, n4 = 0;
// Call this one once so that it's thread safe thereafter
ilaenv_(&ispec, routine, opts, &n1, &n2, &n3, &n4);
dlamch_("e");
slamch_("e");
}
} init;
static Lock lock;
struct Lapack_Guard {
Lapack_Guard()
{
if (!need_lock) return;
lock.lock();
}
~Lapack_Guard()
{
if (!need_lock) return;
lock.unlock();
}
};
} // file scope
int ilaenv(int ispec, const char * routine, const char * opts,
int n1, int n2, int n3, int n4)
{
return ilaenv_(&ispec, routine, opts, &n1, &n2, &n3, &n4);
}
int gels(char trans, int m, int n, int nrhs, float * A, int lda, float * B,
int ldb)
{
Lapack_Guard guard;
int info = 0;
int workspace_size = -1;
float ws_return;
/* Find out how much to allocate. */
sgels_(&trans, &m, &n, &nrhs, A, &lda, B, &ldb, &ws_return,
&workspace_size, &info);
if (info != 0) return info;
workspace_size = (int)ws_return;
//cerr << "gels: asked for " << workspace_size << " workspace" << endl;
boost::scoped_array<float> workspace(new float[workspace_size]);
/* Perform the computation. */
sgels_(&trans, &m, &n, &nrhs, A, &lda, B, &ldb,
workspace.get(), &workspace_size, &info);
return info;
}
int gels(char trans, int m, int n, int nrhs, double * A, int lda, double * B,
int ldb)
{
Lapack_Guard guard;
int info = 0;
int workspace_size = -1;
double ws_return;
/* Find out how much to allocate. */
dgels_(&trans, &m, &n, &nrhs, A, &lda, B, &ldb, &ws_return,
&workspace_size, &info);
if (info != 0) return info;
workspace_size = (int)ws_return;
//cerr << "gels: asked for " << workspace_size << " workspace" << endl;
boost::scoped_array<double> workspace(new double[workspace_size]);
/* Perform the computation. */
dgels_(&trans, &m, &n, &nrhs, A, &lda, B, &ldb,
workspace.get(), &workspace_size, &info);
return info;
}
int gelsd(int m, int n, int nrhs, float * A, int lda, float * B, int ldb,
float * S, float rcond, int & rank)
{
Lapack_Guard guard;
int info = 0;
int workspace_size = -1;
float ws_return;
int smallsz = ilaenv(9, "SGELSD", "", m, n, nrhs, -1);
//cerr << "smallsz = " << smallsz << endl;
int minmn = std::min(m, n);
int nlvl = std::max(0, (int)(log2(minmn/(smallsz + 1))) + 1);
int intwss = 3 * minmn * nlvl + 11 * minmn;
boost::scoped_array<int> iwork(new int[intwss]);
/* Find out how much to allocate. */
sgelsd_(&m, &n, &nrhs, A, &lda, B, &ldb, S, &rcond, &rank, &ws_return,
&workspace_size, iwork.get(), &info);
if (info != 0) return info;
workspace_size = (int)ws_return;
//cerr << "gels: asked for " << workspace_size << " workspace" << endl;
boost::scoped_array<float> workspace(new float[workspace_size]);
/* Perform the computation. */
sgelsd_(&m, &n, &nrhs, A, &lda, B, &ldb, S, &rcond, &rank,
workspace.get(), &workspace_size, iwork.get(), &info);
return info;
}
int gelsd(int m, int n, int nrhs, double * A, int lda, double * B, int ldb,
double * S, double rcond, int & rank)
{
Lapack_Guard guard;
int info = 0;
int workspace_size = -1;
double ws_return;
int smallsz = ilaenv(9, "DGELSD", "", m, n, nrhs, -1);
//cerr << "smallsz = " << smallsz << endl;
int minmn = std::min(m, n);
int nlvl = std::max(0, (int)(log2(minmn/(smallsz + 1))) + 1);
int intwss = 3 * minmn * nlvl + 11 * minmn;
boost::scoped_array<int> iwork(new int[intwss]);
/* Find out how much to allocate. */
dgelsd_(&m, &n, &nrhs, A, &lda, B, &ldb, S, &rcond, &rank, &ws_return,
&workspace_size, iwork.get(), &info);
if (info != 0) return info;
workspace_size = (int)ws_return;
//cerr << "gels: asked for " << workspace_size << " workspace" << endl;
boost::scoped_array<double> workspace(new double[workspace_size]);
/* Perform the computation. */
dgelsd_(&m, &n, &nrhs, A, &lda, B, &ldb, S, &rcond, &rank,
workspace.get(), &workspace_size, iwork.get(), &info);
return info;
}
int gglse(int m, int n, int p, float * A, int lda, float * B, int ldb,
float * c, float * d, float * result)
{
Lapack_Guard guard;
int info = 0;
int workspace_size = -1;
float ws_return;
/* Find out how much to allocate. */
sgglse_(&m, &n, &p, A, &lda, B, &ldb, c, d, result, &ws_return,
&workspace_size, &info);
if (info != 0) return info;
workspace_size = (int)ws_return;
/* Get the workspace. */
boost::scoped_array<float> workspace(new float[workspace_size]);
/* Perform the computation. */
sgglse_(&m, &n, &p, A, &lda, B, &ldb, c, d, result,
&workspace[0], &workspace_size, &info);
return info;
}
int gglse(int m, int n, int p, double * A, int lda, double * B, int ldb,
double * c, double * d, double * result)
{
Lapack_Guard guard;
int info = 0;
int workspace_size = -1;
double ws_return;
/* Find out how much to allocate. */
dgglse_(&m, &n, &p, A, &lda, B, &ldb, c, d, result, &ws_return,
&workspace_size, &info);
if (info != 0) return info;
workspace_size = (int)ws_return;
//cerr << "gglse: asked for " << workspace_size << " workspace" << endl;
boost::scoped_array<double> workspace(new double[workspace_size]);
/* Perform the computation. */
dgglse_(&m, &n, &p, A, &lda, B, &ldb, c, d, result,
workspace.get(), &workspace_size, &info);
return info;
}
int gebrd(int m, int n, double * A, int lda,
double * D, double * E, double * tauq, double * taup)
{
Lapack_Guard guard;
int info = 0;
int workspace_size = -1;
double ws_return;
/* Find out how much to allocate. */
dgebrd_(&m, &n, A, &lda, D, E, tauq, taup, &ws_return,
&workspace_size, &info);
if (info != 0) return info;
workspace_size = (int)ws_return;
boost::scoped_array<double> workspace(new double[workspace_size]);
/* Perform the computation. */
dgebrd_(&m, &n, A, &lda, D, E, tauq, taup, workspace.get(),
&workspace_size, &info);
return info;
}
int orgbr(const char * vect, int m, int n, int k,
double * A, int lda, const double * tau)
{
Lapack_Guard guard;
int info = 0;
int workspace_size = -1;
double ws_return;
/* Find out how much to allocate. */
dorgbr_(vect, &m, &n, &k, A, &lda, tau, &ws_return, &workspace_size,
&info);
if (info != 0) return info;
workspace_size = (int)ws_return;
boost::scoped_array<double> workspace(new double[workspace_size]);
/* Perform the computation. */
dorgbr_(vect, &m, &n, &k, A, &lda, tau, workspace.get(), &workspace_size,
&info);
return info;
}
int bdsdc(const char * uplo, const char * compq, int n,
double * D, double * E,
double * U, int ldu,
double * VT, int ldvt,
double * Q, int * iq)
{
Lapack_Guard guard;
int workspace_size;
switch (*compq) {
case 'N': workspace_size = 2 * n; break;
case 'P': workspace_size = 6 * n; break;
case 'I': workspace_size = 3 * n * n + 2 * n; break;
default: return -2; // error with param 2 (compq)
}
boost::scoped_array<double> workspace(new double[workspace_size]);
int iworkspace_size = 7 * n;
boost::scoped_array<int> iworkspace(new int[iworkspace_size]);
int info;
/* Perform the computation. */
dbdsdc_(uplo, compq, &n, D, E, U, &ldu, VT, &ldvt, Q, iq, workspace.get(),
iworkspace.get(), &info);
return info;
}
int gesvd(const char * jobu, const char * jobvt, int m, int n,
double * A, int lda, double * S, double * U, int ldu,
double * VT, int ldvt)
{
Lapack_Guard guard;
int info = 0;
int workspace_size = -1;
double ws_return;
/* Find out how much to allocate. */
dgesvd_(jobu, jobvt, &m, &n, A, &lda, S, U, &ldu, VT, &ldvt, &ws_return,
&workspace_size, &info);
if (info != 0) return info;
workspace_size = (int)ws_return;
boost::scoped_array<double> workspace(new double[workspace_size]);
/* Perform the computation. */
dgesvd_(jobu, jobvt, &m, &n, A, &lda, S, U, &ldu, VT, &ldvt,
workspace.get(), &workspace_size, &info);
return info;
}
int gesdd(const char * jobz, int m, int n,
float * A, int lda, float * S, float * U, int ldu,
float * vt, int ldvt)
{
Lapack_Guard guard;
int info = 0;
int workspace_size = -1;
float ws_return;
int iwork[8 * std::min(m, n)];
/* Find out how much to allocate. */
sgesdd_(jobz, &m, &n, A, &lda, S, U, &ldu, vt, &ldvt, &ws_return,
&workspace_size, iwork, &info);
if (info != 0) return info;
workspace_size = (int)ws_return;
boost::scoped_array<float> workspace(new float[workspace_size]);
/* Perform the computation. */
sgesdd_(jobz, &m, &n, A, &lda, S, U, &ldu, vt, &ldvt, workspace.get(),
&workspace_size, iwork, &info);
return info;
}
int gesdd(const char * jobz, int m, int n,
double * A, int lda, double * S, double * U, int ldu,
double * vt, int ldvt)
{
Lapack_Guard guard;
int info = 0;
int workspace_size = -1;
double ws_return;
int iwork[8 * std::min(m, n)];
/* Find out how much to allocate. */
dgesdd_(jobz, &m, &n, A, &lda, S, U, &ldu, vt, &ldvt, &ws_return,
&workspace_size, iwork, &info);
if (info != 0) return info;
workspace_size = (int)ws_return;
boost::scoped_array<double> workspace(new double[workspace_size]);
/* Perform the computation. */
dgesdd_(jobz, &m, &n, A, &lda, S, U, &ldu, vt, &ldvt, workspace.get(),
&workspace_size, iwork, &info);
return info;
}
int gesv(int n, int nrhs, double * A, int lda, int * pivots, double * B,
int ldb)
{
Lapack_Guard guard;
int info = 0;
dgesv_(&n, &nrhs, A, &lda, pivots, B, &ldb, &info);
return info;
}
int spotrf(char uplo, int n, float * A, int lda)
{
Lapack_Guard guard;
int info = 0;
spotrf_(&uplo, &n, A, &lda, &info);
return info;
}
int dpotrf(char uplo, int n, double * A, int lda)
{
Lapack_Guard guard;
int info = 0;
dpotrf_(&uplo, &n, A, &lda, &info);
return info;
}
int geqp3(int m, int n, float * A, int lda, int * jpvt, float * tau)
{
Lapack_Guard guard;
int info = 0;
int workspace_size = -1;
float ws_return;
/* Find out how much to allocate. */
sgeqp3_(&m, &n, A, &lda, jpvt, tau, &ws_return, &workspace_size,
&info);
if (info != 0) return info;
workspace_size = (int)ws_return;
boost::scoped_array<float> workspace(new float[workspace_size]);
/* Perform the computation. */
sgeqp3_(&m, &n, A, &lda, jpvt, tau, workspace.get(), &workspace_size,
&info);
return info;
}
int geqp3(int m, int n, double * A, int lda, int * jpvt, double * tau)
{
Lapack_Guard guard;
int info = 0;
int workspace_size = -1;
double ws_return;
/* Find out how much to allocate. */
dgeqp3_(&m, &n, A, &lda, jpvt, tau, &ws_return, &workspace_size,
&info);
if (info != 0) return info;
workspace_size = (int)ws_return;
boost::scoped_array<double> workspace(new double[workspace_size]);
/* Perform the computation. */
dgeqp3_(&m, &n, A, &lda, jpvt, tau, workspace.get(), &workspace_size,
&info);
return info;
}
} // namespace LAPack
} // namespace ML
| [
"root@ubuntu-virtual-machine.(none)"
] | root@ubuntu-virtual-machine.(none) |
361866a912db0c5ea59bbc6761bc71b807249b10 | 0426ed8f979df8731c61acbf2d89113b228bf41a | /src/codec/src/autoencoder/Layer.cpp | 2a394bc96ca66f67949240d17c1fe7dfeb11fb73 | [] | no_license | HackerSuid/ace-core | 95fdc60a1da24969b925f05674045dc8629f2692 | 20ba1914ca860f5027634045e70037cc8750474d | refs/heads/master | 2021-09-07T09:46:38.450588 | 2018-02-21T05:36:42 | 2018-02-21T05:36:42 | 54,067,959 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 871 | cpp | #include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include "Layer.h"
#include "Node.h"
Layer::Layer(unsigned int numNodes, Layer *lower, bool addBias)
{
inputLayer = lower;
nodes = new std::vector<Node *>();
// create the nodes for this layer.
for (unsigned int i=0; i<numNodes; i++)
nodes->push_back(new Node(lower, false));
// add a bias node to the layer.
if (addBias)
nodes->push_back(new Node(lower, true));
}
Layer::~Layer()
{
}
void Layer::ForwardPropagationOverNodes()
{
unsigned int numNodes = nodes->size();
for (unsigned int i=0; i<numNodes; i++)
((*nodes)[i])->ComputeActivation();
}
void Layer::BackwardPropagationOverNodes()
{
unsigned int numNodes = nodes->size();
for (unsigned int i=0; i<numNodes; i++)
((*nodes)[i])->BackPropagateDelta();
}
| [
"[email protected]"
] | |
58d29e0d9c6885035e4356cfda0c89c41de89c8a | 64bf21e9b4ca104557d05dc90a70e9fc3c3544a4 | /tests/journal.lib/channel_inventory.cc | 65581291b4e318db6fe21ac9a33c98ff6d91a1b0 | [
"BSD-3-Clause"
] | permissive | pyre/pyre | e6341a96a532dac03f5710a046c3ebbb79c26395 | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | refs/heads/main | 2023-08-08T15:20:30.721308 | 2023-07-20T07:51:29 | 2023-07-20T07:51:29 | 59,451,598 | 27 | 13 | BSD-3-Clause | 2023-07-02T07:14:50 | 2016-05-23T04:17:24 | Python | UTF-8 | C++ | false | false | 954 | cc | // -*- c++ -*-
//
// michael a.g. aïvázis <[email protected]>
// (c) 1998-2023 all rights reserved
// get the journal
#include <pyre/journal.h>
// support
#include <cassert>
// type aliases
template <typename severityT>
using channel_t = pyre::journal::channel_t<severityT>;
// severity stub
class severity_t : public channel_t<severity_t> {
// metamethods
public:
// index initialization is required...
inline severity_t(const name_type & name) : channel_t<severity_t>(name) {}
};
// verify that the default channel state is what we expect
int
main()
{
// make a channel
severity_t channel("test.channel");
// verify it is on, by default
assert(channel.active() == true);
// not fatal
assert(channel.fatal() == false);
// and that its device is whatever is set globally
assert(channel.device() == pyre::journal::chronicler_t::device());
// all done
return 0;
}
// end of file
| [
"[email protected]"
] | |
ee7e6c069d7400ead6df677c5c2adb45c0ca199f | ed6e6320c3c046f2476ff05abedcbd760486952a | /graphs/bridge_tree.cpp | c0fa8b00d14b89c59cb08a61c56bb28f57f92ff0 | [] | no_license | JaroslavUrbann/ICPC-library | b17d1c61f41e85bb627d591d259d0457582a9efa | 15d819ebb9c89ad79c2383238e3cab847b792067 | refs/heads/main | 2023-07-30T12:29:55.498548 | 2021-09-26T07:29:03 | 2021-09-26T07:29:03 | 387,407,095 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,330 | cpp | // v has to be the other node :(
struct E{
int u,v,w;
};
// creates a dfs tree and those edges to children that don't have a backedge that goes above me are bridges
// ng contains a bridge tree that has bridges with old labels, so you have to use par[u] when using it
// should work with self-loops and multi edges
// high constant & memory usage, but O(n+m)
struct BT{
int n,c=0;
vector<vector<E>>g,ng,inside;
vector<int>par,low,dpt,vis;
vector<E>bridges;
BT(int n):n(n),g(n),par(n),low(n),dpt(n),vis(n){}
void ae(E e){E oe=e;swap(oe.u,oe.v);
g[e.u].push_back(e);
g[e.v].push_back(oe);
}
void dfs2(int u,int f){
ng.resize(c+1);inside.resize(c+1);
vis[u]=1;par[u]=c;
for(E e:g[u])if(e.v!=f){
if(vis[e.v]&&par[e.v]!=c){E oe=e;swap(oe.u,oe.v);
ng[c].push_back(e);
ng[par[e.v]].push_back(oe);
}else if(!vis[e.v])dfs2(e.v,f);
if(vis[e.v]==1)inside[c].push_back(e);
}
vis[u]=2;
}
int dfs(int u,int p,int d){
low[u]=dpt[u]=d;
for(E e:g[u])if(e.v!=p){
if(dpt[e.v])low[u]=min(low[u],dpt[e.v]);
else{
int lw=dfs(e.v,u,d+1);
low[u]=min(low[u],lw);
if(lw>d){
bridges.push_back(e);
dfs2(e.v,u);++c;
}
}
}
return low[u];
}
void calc(){//dfs(0,0,1);dfs2(0,-1);}
for(int i=0;i<n;++i)if(!vis[i]){ // not tested
dfs(i,i,1);
dfs2(i,-1),++c;
}
}
};
| [
"[email protected]"
] | |
94fbae3630161d31d399ae400af9bc69ec12ef4f | 03164185aac29d83154ff61682d036c84367415b | /engine/codecs/core/include/aeon/codecs/codec_manager.h | f0f27326ef135b012fbfc889f9df074e70d0bbd9 | [
"MIT"
] | permissive | anggawasita/aeon-engine | fb6d64b27ee1937a141102dc6cda9b0ff3f4d09b | 9efcf83985110c36ebf0964bd4f76b261f2f6717 | refs/heads/master | 2022-02-21T06:02:49.836345 | 2019-10-04T18:43:07 | 2019-10-04T18:43:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,093 | h | /*
* Copyright (c) 2012-2018 Robin Degen
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <aeon/codecs/codec.h>
#include <aeon/codecs/basic_codec.h>
#include <aeon/resources/resource_encoding.h>
#include <aeon/common/exception.h>
#include <aeon/logger/logger.h>
#include <aeon/common/logger.h>
#include <map>
#include <memory>
namespace aeon::codecs
{
DEFINE_EXCEPTION_OBJECT(codec_manager_exception, common::exception, "Generic Codec Manager exception.");
DEFINE_EXCEPTION_OBJECT(codec_unknown_exception, codec_manager_exception, "Unknown Codec exception.");
class codec_manager
{
public:
codec_manager();
~codec_manager();
codec_manager(const codec_manager &) noexcept = delete;
auto operator=(const codec_manager &) noexcept -> codec_manager & = delete;
codec_manager(codec_manager &&) = default;
auto operator=(codec_manager &&) -> codec_manager & = default;
void register_codec(std::unique_ptr<codec_factory> &&factory);
void register_codec(std::unique_ptr<codec_factory> &&factory, const resources::resource_encoding &encoding);
auto create(const resources::resource_encoding &encoding);
template <typename T>
auto create_basic(const resources::resource_encoding &encoding);
private:
logger::logger logger_;
std::map<resources::resource_encoding, std::unique_ptr<codec_factory>> codecs_;
};
inline auto codec_manager::create(const resources::resource_encoding &encoding)
{
const auto result = codecs_.find(encoding);
if (result == codecs_.end())
{
AEON_LOG_ERROR(logger_) << "Unknown codec: " << encoding << std::endl;
throw codec_unknown_exception();
}
return result->second->create();
}
template <typename T>
inline auto codec_manager::create_basic(const resources::resource_encoding &encoding)
{
auto codec = create(encoding);
auto *basic_codec_ptr = &dynamic_cast<basic_codec<T> &>(*codec.get());
codec.release();
return std::unique_ptr<basic_codec<T>>(basic_codec_ptr);
}
} // namespace aeon::codecs
| [
"[email protected]"
] | |
ae925c458c1ac0c3cea086a3adacc7f5f96aaf27 | 3801db9925a4e5abafa34574a51e4ad0dd781cd0 | /RANK_HACKER/2D_arrays_hourglass.cpp | 214d8d87f76e596ec258c313696ee9f3ebd2c342 | [] | no_license | Jitendra-Sahu/cpp | 3a328bf4bd141960d232910a460962bd84089a22 | 623b554ccb3c56794631c51b59018a2c6cce6ebc | refs/heads/master | 2021-01-11T20:57:41.190466 | 2018-10-03T09:21:37 | 2018-10-03T09:21:37 | 79,222,223 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,252 | cpp | //Calculate the hourglass sum for every hourglass in , then print the maximum hourglass sum.
/*
Context
Given a 2D Array, :
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
We define an hourglass in to be a subset of values with indices falling in this pattern in 's graphical representation:
a b c
d
e f g
There are hourglasses in , and an hourglass sum is the sum of an hourglass' values.
*/
#include<iostream>
#include<vector>
#include <climits>
#define SIZE 6
#define SIZE_GLASS 3
using namespace std;
int main(){
vector< vector<int> > arr(6,vector<int>(6));
for(int arr_i = 0;arr_i < 6;arr_i++){
for(int arr_j = 0;arr_j < 6;arr_j++){
cin >> arr[arr_i][arr_j];
}
}
int max = INT_MIN;
for(int arr_i = 0; arr_i<SIZE-SIZE_GLASS+1; arr_i++){
for(int arr_j=0; arr_j<SIZE-SIZE_GLASS+1; arr_j++){
int sum = 0;
for(int x=arr_j; x<arr_j+SIZE_GLASS; x++)
sum += arr[arr_i][x];
for(int x=arr_j; x<arr_j+SIZE_GLASS; x++)
sum += arr[arr_i+SIZE_GLASS-1][x];
sum += arr[arr_i+1][arr_j+1];
if(sum>max){
max = sum;
}
}
}
cout << max;
return 0;
}
| [
"[email protected]"
] | |
8ae0b56f8adfc639707525acbac6764af8758818 | 1fe75189271d62b434ebe95d679dbbb15a81b3b2 | /apps/procedural/source/blub/procedural/voxel/tile/accessor.hpp | 590cc9fc3859036afc40151ada8634707d54b180 | [] | no_license | thejasonfisher/voxelTerrain | d6edc1e5650d6583a821765e336a51307c40f4b0 | dc1481e5dd1749cfcb63a8f229cabb7f57f5ac19 | refs/heads/master | 2021-01-14T09:00:04.034271 | 2013-11-26T18:42:12 | 2013-11-26T18:42:12 | 17,955,018 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,775 | hpp | #ifndef PROCEDURAL_VOXEL_TILE_ACCESSOR_HPP
#define PROCEDURAL_VOXEL_TILE_ACCESSOR_HPP
#include "blub/core/array.hpp"
#include "blub/core/globals.hpp"
#include "blub/math/vector2int32.hpp"
#include "blub/math/vector3int32.hpp"
#include "blub/procedural/voxel/tile/container.hpp"
#include "blub/procedural/voxel/data.hpp"
#include "blub/serialization/access.hpp"
#include "blub/serialization/nameValuePair.hpp"
namespace blub
{
namespace procedural
{
namespace voxel
{
namespace tile
{
class accessor : public base<accessor>
{
public:
typedef base<accessor> t_base;
static constexpr int32 voxelLength = tile::container::voxelLength;
static constexpr int32 voxelLengthWithNormalCorrection = voxelLength+3;
static constexpr int32 voxelLengthLod = (voxelLength+1)*2;
static constexpr int32 voxelCount = voxelLengthWithNormalCorrection*voxelLengthWithNormalCorrection*voxelLengthWithNormalCorrection;
static constexpr int32 voxelCountLod = voxelLengthLod*voxelLengthLod;
static constexpr int32 voxelCountLodAll = 6*voxelCountLod;
static constexpr int32 voxelLengthSurface = tile::container::voxelLength+1;
static constexpr int32 voxelCountSurface = voxelLengthSurface*voxelLengthSurface*voxelLengthSurface;
typedef array<data, voxelCount> t_voxelArray;
typedef array<data, 6*voxelCountLod> t_voxelArrayLod;
static pointer create(const bool& calculateLod = false);
~accessor();
bool setVoxel(const vector3int32& pos, const data& toSet)
{
BASSERT(pos.x >= -1);
BASSERT(pos.y >= -1);
BASSERT(pos.z >= -1);
BASSERT(pos.x < voxelLengthWithNormalCorrection-1);
BASSERT(pos.y < voxelLengthWithNormalCorrection-1);
BASSERT(pos.z < voxelLengthWithNormalCorrection-1);
if (toSet.interpolation >= 0 && pos >= vector3int32(0) && pos < vector3int32(voxelLengthSurface))
{
++m_numVoxelLargerZero;
}
const int32 index((pos.x+1)*voxelLengthWithNormalCorrection*voxelLengthWithNormalCorrection + (pos.y+1)*voxelLengthWithNormalCorrection + pos.z+1);
const data oldValue(m_voxels[index]);
m_voxels[index] = toSet;
return oldValue != toSet;
}
bool setVoxelLod(const vector3int32& pos, const data& toSet, const int32& lod)
{
return setVoxelLod(calculateCoordsLod(pos, lod), toSet, lod);
}
void setEmpty(void)
{
setValueToAllVoxel(tile::container::voxelInterpolationMinimum);
}
void setFull(void)
{
setValueToAllVoxel(tile::container::voxelInterpolationMaximum);
}
const data& getVoxel(const vector3int32& pos) const
{
BASSERT(pos.x >= -1);
BASSERT(pos.y >= -1);
BASSERT(pos.z >= -1);
BASSERT(pos.x < voxelLengthWithNormalCorrection-1);
BASSERT(pos.y < voxelLengthWithNormalCorrection-1);
BASSERT(pos.z < voxelLengthWithNormalCorrection-1);
const int32 index((pos.x+1)*voxelLengthWithNormalCorrection*voxelLengthWithNormalCorrection + (pos.y+1)*voxelLengthWithNormalCorrection + pos.z+1);
return m_voxels[index];
}
const data& getVoxelLod(const vector3int32& pos, const int32& lod) const
{
return getVoxelLod(calculateCoordsLod(pos, lod), lod);
}
bool isEmpty(void) const
{
/*if (m_calculateLod)
{
return m_numVoxelLargerZero == 0 &&
m_numVoxelLargerZeroLod == 0;
}*/
return m_numVoxelLargerZero == 0;
}
bool isFull(void) const
{
/*if (m_calculateLod)
{
return m_numVoxelLargerZero == voxelCountSurface &&
m_numVoxelLargerZeroLod == voxelCountLodAll;
}*/
return m_numVoxelLargerZero == voxelCountSurface;
}
const bool& getCalculateLod(void) const
{
return m_calculateLod;
}
const int32& getNumVoxelLargerZero(void) const
{
return m_numVoxelLargerZero;
}
const int32& getNumVoxelLargerZeroLod(void) const
{
return m_numVoxelLargerZeroLod;
}
const t_voxelArray& getVoxelArray() const
{
return m_voxels;
}
t_voxelArray& getVoxelArray()
{
return m_voxels;
}
t_voxelArrayLod* getVoxelArrayLod() const
{
return m_voxelsLod;
}
t_voxelArrayLod* getVoxelArrayLod()
{
return m_voxelsLod;
}
void setCalculateLod(const bool& lod);
void setNumVoxelLargerZero(const int32& toSet)
{
m_numVoxelLargerZero = toSet;
}
void setNumVoxelLargerZeroLod(const int32& toSet)
{
m_numVoxelLargerZeroLod = toSet;
}
protected:
accessor(const bool& calculateLod = false)
: m_voxelsLod(nullptr)
, m_calculateLod(false)
, m_numVoxelLargerZero(0)
, m_numVoxelLargerZeroLod(0)
{
if (calculateLod)
{
setCalculateLod(calculateLod);
}
}
bool setVoxelLod(const vector2int32& index, const data& toSet, const int32& lod)
{
BASSERT(index >= 0);
BASSERT(index < voxelCountLod);
BASSERT(m_calculateLod);
BASSERT(m_voxelsLod != nullptr);
if (toSet.interpolation >= 0)
{
++m_numVoxelLargerZeroLod;
}
const uint32 index_(lod*voxelCountLod + index.x*voxelLengthLod + index.y);
const data oldValue((*m_voxelsLod)[index_]);
(*m_voxelsLod)[index_] = toSet;
return oldValue != toSet;
}
const data& getVoxelLod(const vector2int32& index, const int32& lod) const
{
BASSERT(index >= 0);
BASSERT(index < voxelCountLod);
BASSERT(m_calculateLod);
return (*m_voxelsLod)[lod*voxelCountLod + index.x*voxelLengthLod + index.y];
}
static vector2int32 calculateCoordsLod(const vector3int32& pos, const int32& lod)
{
BASSERT(lod >= 0);
BASSERT(lod < 6);
BASSERT(pos.x >= 0);
BASSERT(pos.y >= 0);
BASSERT(pos.z >= 0);
BASSERT(pos.x < voxelLengthLod);
BASSERT(pos.y < voxelLengthLod);
BASSERT(pos.z < voxelLengthLod);
BASSERT(pos.x == 0 || pos.y == 0 || pos.z == 0); // 2d!
switch (lod)
{
case 0: // x
case 1:
BASSERT(pos.x == 0);
return vector2int32(pos.y, pos.z);
case 2: // y
case 3:
BASSERT(pos.y == 0);
return vector2int32(pos.x, pos.z);
case 4: // z
case 5:
BASSERT(pos.z == 0);
return vector2int32(pos.x, pos.y);
default:
BASSERT(false);
}
return vector2int32();
}
void setValueToAllVoxel(const int8& value);
private:
BLUB_SERIALIZATION_ACCESS
template <class formatType>
void serialize(formatType & readWrite, const uint32& version)
{
using namespace serialization;
(void)version;
readWrite & nameValuePair::create("numVoxelLargerZero", m_numVoxelLargerZero);
readWrite & nameValuePair::create("numVoxelLargerZeroLod", m_numVoxelLargerZeroLod);
readWrite & nameValuePair::create("calculateLod", m_calculateLod);
readWrite & nameValuePair::create("voxels", m_voxels);
if (m_calculateLod)
{
if (m_voxelsLod == nullptr)
{
setCalculateLod(m_calculateLod);
}
BASSERT(m_voxelsLod != nullptr);
readWrite & nameValuePair::create("voxelsLod", *m_voxelsLod);
}
}
private:
t_voxelArray m_voxels;
t_voxelArrayLod *m_voxelsLod;
bool m_calculateLod;
int32 m_numVoxelLargerZero;
int32 m_numVoxelLargerZeroLod;
};
}
}
}
}
#endif // PROCEDURAL_VOXEL_TILE_ACCESSOR_HPP
| [
"[email protected]"
] | |
00f6d9aeca3f8719fb9b39006bdf9737fb0d7a1b | f03f4b660086c2c9bcfc9f6eec5d6739ec229950 | /sourceCode/Model/model.h | 412bf7306b0875578d9d5753e829e7da693cd623 | [] | no_license | mjy2002/TaskTrackingSystem | 9b05d45a5cbcdb05205780d54855c3250dd6b4ad | b8a2f37ab3771d96969a8ff582eab0c6684be845 | refs/heads/master | 2020-12-14T11:07:09.592414 | 2019-07-22T20:39:18 | 2019-07-22T20:39:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,165 | h | #ifndef MODEL_HPP
#define MODEL_HPP
#include <QList>
#include <QString>
class User;
class Task;
class Project;
class User{
private:
int _Id;
QString _name;
public:
User(QString name);
User(QString name, int id);
QString getName();
int getId();
void setId();
};
class Project{
private:
int _Id;
QString _name;
public:
Project(QString name);
Project(QString name, int Id);
int getId();
QString getName();
};
class Task{
private:
int _Id;
User _user;
QString _topic;
QString _type;
Project _project;
QString _desciption;
int _priority = 0;
public:
Task(User user, QString topic, QString type, QString description, int priority, Project project);
QString getTopic();
User getUser();
Project getProject();
void setUser(User user);
QString getType();
int getPriority();
QString getDescription();
int getId();
void setId(int Id);
};
#endif // MODEL_HPP
| [
"[email protected]"
] | |
5a1c76bd013ac35da32a9fd1c7f0cea8d299f7cf | 8d2558be6f8b6c251f518745e8bf8b2077191cb9 | /Day03/AoC2018_3.cpp | 4b0b665991285cb35e4310572c99b6bf492a4864 | [] | no_license | ivceh/Advent-of-Code-2018 | 4c0a180d3c96c400d7918d2eeecc49bad075b36e | 5c384a77ab1e53c7432f7f61ec878dca8169d842 | refs/heads/master | 2020-04-09T04:20:04.001885 | 2018-12-17T16:55:10 | 2018-12-17T16:55:10 | 160,018,683 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,680 | cpp | #include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdio>
#include <vector>
#include <array>
using namespace std;
struct rectangle
{
int x, y, width, height;
rectangle(int x, int y, int width, int height)
{
this->x = x;
this->y = y;
this->width = width;
this -> height = height;
}
};
// should be global because of the limited stack size
int A[1001][1001] = {{0}};
int main()
{
ifstream in;
string line, str;
int x, y, width, height, n=0;
vector <rectangle> V;
// reading input
in.open("input.txt");
while (getline(in, line))
{
if (!line.empty())
{
sscanf(line.c_str(), "#%*d @ %d,%d: %dx%d", &x, &y, &width, &height);
V.push_back(rectangle(x, y, width, height));
}
}
in.close();
// resolving Part One
for (rectangle r : V)
for (int i=r.x; i<r.x+r.width; ++i)
for (int j=r.y; j<r.y+r.height; ++j)
++A[i][j];
for (int i=1; i<=1000; ++i)
for (int j=1; j<=1000; ++j)
if (A[i][j] > 1)
++n;
cout << "Part One: " << n << endl;
// resolving Part Two
n=0;
cout << "Part Two: ";
for (int i=0; i<V.size(); ++i)
{
bool overlaps = false;
for (int j=0; j<V.size(); ++j)
if(i != j && (V[i].x < V[j].x + V[j].width && V[j].x < V[i].x + V[i].width) &&
(V[i].y < V[j].y + V[j].height && V[j].y < V[i].y + V[i].height))
{
overlaps = true;
break;
}
if (!overlaps)
cout << i+1 << " ";
}
return 0;
}
| [
"[email protected]"
] | |
d1afe1e54a3412cf8937f76e5aa84619d8c1b644 | a4aad39bf34861fdda2ac6be4a1a648fc10307ef | /Source/NewProject/ActionComponent/Action_PlayRootMotion.cpp | 464d6afd89ace959a9c2f9c1b21dc8b440529e69 | [
"Apache-2.0"
] | permissive | sdlwlxf1/UE4-ActionComponent | 9849cccc9588197471ceeca704c4803c3e769235 | e9830681c3ae5966557616ac0b81e9f889c55f6c | refs/heads/master | 2020-09-23T01:10:04.469567 | 2019-12-27T08:15:32 | 2019-12-27T08:15:32 | 225,362,654 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,178 | cpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "Action_PlayRootMotion.h"
#include "Animation/AnimMontage.h"
#include "Components/SkeletalMeshComponent.h"
#include "GameFramework/Character.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "Animation/AnimInstance.h"
#include "VisualLogger.h"
DEFINE_LOG_CATEGORY(LogAction_PlayRootMotion);
TSharedPtr<FAction_PlayRootMotion> FAction_PlayRootMotion::CreateAction(UAnimMontage* InAnimMontage, float InPlayRate /*= 1.0f*/, float InBlendInTime /*= -1.0f*/, float InBlendOutTime /*= -1.0f*/, bool InbLooping /*= false*/, FName InSlotNodeName /*= NAME_None*/, bool InbNonBlocking /*= false*/)
{
if (InAnimMontage == nullptr)
return nullptr;
if (InAnimMontage->HasRootMotion() == false)
return nullptr;
TSharedPtr<FAction_PlayRootMotion> Action = MakeShareable(new FAction_PlayRootMotion());
if (Action.IsValid())
{
Action->AnimMontage = InAnimMontage;
Action->bNonBlocking = InbNonBlocking;
Action->PlayRate = InPlayRate;
Action->SlotNodeName = InSlotNodeName;
Action->bLooping = InbLooping;
Action->BlendInTime = InBlendInTime;
Action->BlendOutTime = InBlendOutTime;
}
return Action;
}
EActionResult FAction_PlayRootMotion::ExecuteAction()
{
EActionResult Result = EActionResult::Fail;
ACharacter *Character = Cast<ACharacter>(GetOwner());
UCharacterMovementComponent *MovementComp = nullptr;
if (Character)
{
MovementComp = Character->GetCharacterMovement();
}
if (!MovementComp)
return Result;
bAutoHasFinished = false;
bHasUnbinded = false;
if (AnimMontage.IsValid())
{
if (Character)
{
CachedSkelMesh = Character->GetMesh();
}
else
{
CachedSkelMesh = GetOwner()->FindComponentByClass<USkeletalMeshComponent>();
}
if (CachedSkelMesh.IsValid())
{
UAnimInstance *AnimInst = CachedSkelMesh->GetAnimInstance();
if (AnimInst)
{
if (AnimMontage->SlotAnimTracks.Num() > 0)
{
if (SlotNodeName != NAME_None)
{
AnimMontage->SlotAnimTracks[0].SlotName = SlotNodeName;
}
if (AnimMontage->SlotAnimTracks[0].AnimTrack.AnimSegments.Num() > 0)
{
AnimMontage->SlotAnimTracks[0].AnimTrack.AnimSegments[0].LoopingCount = bLooping ? INT_MAX : 1;
}
}
if (BlendInTime != -1.0f)
AnimMontage->BlendIn.SetBlendTime(BlendInTime);
else
BlendInTime = AnimMontage->BlendIn.GetBlendTime();
if (BlendOutTime != -1.0f)
AnimMontage->BlendOut.SetBlendTime(BlendOutTime);
else
BlendOutTime = AnimMontage->BlendOut.GetBlendTime();
float PlayLength = AnimMontage->GetPlayLength();
if (Duration == -1.0f)
{
Duration = PlayLength - AnimMontage->BlendOut.GetBlendTime();
}
Duration = FMath::Max(Duration, KINDA_SMALL_NUMBER);
if (PlayRate == -1.0f && PlayLength != 0.0f)
{
PlayRate = (PlayLength - AnimMontage->BlendOut.GetBlendTime()) / Duration;
}
else
{
PlayRate = FMath::Max(PlayRate, KINDA_SMALL_NUMBER);
}
FinishDelay = Character->PlayAnimMontage(AnimMontage.Get(), PlayRate);
if (bNonBlocking == false && FinishDelay > 0)
{
if (bSetNewMovementMode)
{
StorgeMovementMode = MovementComp->MovementMode;
MovementComp->SetMovementMode(NewMovementMode);
}
StorgeRotation = Character->GetActorRotation();
FOnMontageBlendingOutStarted BlendingOutDelegate = FOnMontageBlendingOutStarted::CreateRaw(this, &FAction_PlayRootMotion::RootMotionFinished);
AnimInst->Montage_SetBlendingOutDelegate(BlendingOutDelegate, AnimMontage.Get());
MontageInstanceID = AnimInst->GetActiveInstanceForMontage(AnimMontage.Get())->GetInstanceID();
Result = EActionResult::Wait;
}
else
{
if (FinishDelay > 0)
{
TWeakObjectPtr<UAnimInstance> LocalAnimInstance = AnimInst;
TWeakObjectPtr<UAnimMontage> LocalAnimMontage = AnimMontage;
FRotator LocalStorgeRotation = Character->GetActorRotation();
bool SetNewMovementMode = bSetNewMovementMode;
EMovementMode LocalStorgeMoveMode = MovementComp->MovementMode;
if (bSetNewMovementMode)
{
MovementComp->SetMovementMode(NewMovementMode);
}
TWeakObjectPtr<UCharacterMovementComponent> MovementCompPtr = MovementComp;
FOnMontageEnded Delegate = FOnMontageEnded::CreateLambda([SetNewMovementMode, LocalStorgeMoveMode, LocalStorgeRotation, MovementCompPtr, LocalAnimInstance, LocalAnimMontage](UAnimMontage* Montage, bool bInterrupted) {
if (SetNewMovementMode)
{
if (MovementCompPtr.IsValid())
{
MovementCompPtr->SetMovementMode(LocalStorgeMoveMode);
MovementCompPtr->UpdatedComponent->SetWorldRotation(LocalStorgeRotation);
}
}
if (LocalAnimInstance.IsValid())
{
FAnimMontageInstance* MontageInstance = LocalAnimInstance->GetActiveInstanceForMontage(LocalAnimMontage.Get());
if (MontageInstance)
{
MontageInstance->OnMontageBlendingOutStarted.Unbind();
MontageInstance->OnMontageEnded.Unbind();
}
}
});
AnimInst->Montage_SetEndDelegate(Delegate, AnimMontage.Get());
}
UE_CVLOG(bNonBlocking == false, GetOwner(), LogAction_PlayRootMotion, Log, TEXT("Instant success due to having a valid AnimationToPlay and Character with SkelMesh, but 0-length animation"));
Result = EActionResult::Success;
}
}
}
}
else if (!AnimMontage.IsValid())
{
UE_CVLOG(!AnimMontage.IsValid(), GetOwner(), LogAction_PlayRootMotion, Warning, TEXT("Instant success but having a nullptr Animation to play"));
return EActionResult::Success;
}
return Result;
}
bool FAction_PlayRootMotion::FinishAction(EActionResult InResult, const FString& Reason /*= EActionFinishReason::UnKnown*/, EActionType StopType /*= EActionType::Default*/)
{
BlendingInDelegate.ExecuteIfBound(this, InResult);
BlendingInDelegate.Unbind();
ACharacter *Character = Cast<ACharacter>(GetOwner());
if (Character)
{
UAnimInstance *AnimInst = CachedSkelMesh->GetAnimInstance();
if (AnimInst)
{
FAnimMontageInstance* MontageInstance = AnimInst->GetMontageInstanceForID(MontageInstanceID);
if (MontageInstance)
{
if (StopType == EActionType::Move && InResult == EActionResult::Abort && bStopSeparateType)
{
MontageInstance->PushDisableRootMotion();
MoveHasAbort = true;
RecoverMoveStatue();
NotifyTypeChanged();
return false;
}
MontageInstance->OnMontageBlendingOutStarted.Unbind();
MontageInstance->OnMontageEnded.Unbind();
bHasUnbinded = true;
}
if (InResult == EActionResult::Abort && bAutoHasFinished == false)
{
AnimInst->DispatchQueuedAnimEvents();
Character->StopAnimMontage(AnimMontage.Get());
}
}
if (bNonBlocking == false && FinishDelay > 0 && MoveHasAbort == false)
{
RecoverMoveStatue();
}
}
return true;
}
EActionResult FAction_PlayRootMotion::TickAction(float DeltaTime)
{
CurrentTime += DeltaTime;
if (CurrentTime > BlendInTime)
{
BlendingInDelegate.ExecuteIfBound(this, EActionResult::Success);
BlendingInDelegate.Unbind();
}
if (bLooping == false && CurrentTime > Duration * RecoverMovementModeTime * 1.01f)
{
RecoverMoveStatue();
}
ACharacter *Character = Cast<ACharacter>(GetOwner());
if (Character)
{
UCharacterMovementComponent *Movement = Character->GetCharacterMovement();
if (Movement)
{
bool CanSend = false;
uint8 ClientMovementMode = Movement->MovementMode;
}
}
return EActionResult::Wait;
}
float FAction_PlayRootMotion::GetTimeRadio() const
{
ACharacter *Character = Cast<ACharacter>(GetOwner());
if (Character)
{
UAnimInstance *AnimInst = CachedSkelMesh->GetAnimInstance();
if (AnimInst)
{
FAnimMontageInstance* MontageInstance = AnimInst->GetMontageInstanceForID(MontageInstanceID);
if (MontageInstance)
{
return MontageInstance->GetPosition() / FinishDelay;
}
}
}
return 0.0f;
}
void FAction_PlayRootMotion::RootMotionFinished(UAnimMontage* Montage, bool bInterrupted)
{
if (bHasUnbinded == false)
{
if (bAutoHasFinished == false)
{
bAutoHasFinished = true;
NotifyActionFinish(bInterrupted ? EActionResult::Abort : EActionResult::Success, EActionFinishReason::UEInternalStop);
}
}
}
FName FAction_PlayRootMotion::GetName() const
{
return TEXT("Action_PlayRootMotion");
}
FString FAction_PlayRootMotion::GetDescription() const
{
return FString::Printf(TEXT("%s (RootMotion:%s)"), *GetName().ToString(), *(AnimMontage.IsValid() ? AnimMontage->GetPathName() : FString()));
}
void FAction_PlayRootMotion::UpdateType()
{
if (MoveHasAbort)
{
Type = EActionType::Animation;
}
else
{
Type = (EActionType::Animation | EActionType::Move | EActionType::Rotate);
}
}
void FAction_PlayRootMotion::RecoverMoveStatue()
{
if (bHasRecoverMovementMode == false)
{
bHasRecoverMovementMode = true;
ACharacter *Character = Cast<ACharacter>(GetOwner());
if (Character)
{
UCharacterMovementComponent *MovementComp = Character->GetCharacterMovement();
if (MovementComp)
{
if (bSetNewMovementMode)
{
MovementComp->SetMovementMode(StorgeMovementMode);
}
}
}
}
}
| [
"[email protected]"
] | |
273bf7efb92f21751a9e9a9cf82e514599a088cf | 92453143197bbcc24468ef11775f434bebd7e628 | /main.cpp | a40860fa488c3e7bb95b2613a2a3b4d832678df4 | [] | no_license | blytheej/IandSheInProfilePictureAndBrother | 846eb8bb965d360691a4a3fca8589ebdf6b9dfb0 | 93af2ce1e53afe700e5bf9d54cdceb0b3fd06edf | refs/heads/master | 2020-07-27T01:45:13.768770 | 2019-05-12T13:21:24 | 2019-05-12T13:21:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,291 | cpp | /*
* Team 프사속 그녀와 나와 형.
* [전체]
* - AI 기본 전략 수립
* - 기본적인 평가함수 전략 수립
* [김낙현(2014210036)]:
* - Connect 4 게임 기능 구현
* - 평가함수 계산 로직 구현 및 가중치 튜닝
* - 메모리 사용량 튜닝
* [조현규(2014210074)]
* - MinMax 서치 로직 구현
* - Alpha-Beta Pruning 구현
* - 처리 퍼포먼스 튜닝
* [김은주(2015410051)]
* - Rule based 로직 설계 및 구체화
* - Rule 기반 착수 로직 구현
* - Report 작성
*/
/*
* 사람 vs AI 기반의 connect 4 게임 기능 및 main 함수 관리
*
* Created by 김낙현(2014210036)
* Copyright © 2019 Team 프사 속 그녀와 나와 형. All rights reserved.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "main.hpp"
const char SYMBOL[2] = {'O', 'X'};
char board[7][8];
int col_h[8]; //Height of each column
int total_drops; //Total number of stone in a game
int ai_turn; //Whether AI's turn
State state;
//Clear Console
void clear(){system("@cls||clear");}
//Initialize board and game variables
void init(){
//Init Board
memset(board, ' ', sizeof(board));
board[0][0] = ' ';
for(int i = 1; i < 7; i++) board[i][0] = i + '0';
for(int i = 1; i < 8; i++) board[0][i] = i + '0';
//Init column height index
for(int i = 0; i < 8; i++) col_h[i] = 1;
total_drops = 0;
state.total_drops = state.bitmap_player = state.bitmap_total = 0;
//Set First Order
char t = -1;
do{
while(t != -1 && getchar() != '\n');
printf("Player First? (Y/N) : ");
scanf("%c", &t);
if(t > 'Z') t -= 'a' - 'A';
}while(t != 'Y' && t != 'N');
ai_turn = (t == 'Y' ? 0 : 1);
}
//Test if game ends
//Param : pos (int) - position of new stone
int check_end(int pos){
int c = pos,
r = col_h[pos] - 1;
//Row
for(int i = c-3; i <= c; i++)
if(i > 0 && i+3 <= WIDTH &&
board[r][i] == board[r][i+1] && board[r][i+1] == board[r][i+2] && board[r][i+2] == board[r][i+3])
return 1;
//Colomn
for(int i = r-3; i <= r; i++)
if(i > 0 && i+3 <= HEIGHT &&
board[i][c] == board[i+1][c] && board[i+1][c] == board[i+2][c] && board[i+2][c] == board[i+3][c])
return 1;
//Diagonal
//ri : row index, ci : column index (increase for /), cj : column index (decrease for \)
int ri = r - 3, ci = c - 3, cj = c + 3;
for(int i = 0; i <= 3; i++){
if(ri > 0 && ci > 0 && ri+3 <= HEIGHT && ci+3 <= WIDTH &&
board[ri][ci] == board[ri+1][ci+1] && board[ri+1][ci+1] == board[ri+2][ci+2] && board[ri+2][ci+2] == board[ri+3][ci+3])
return 1;
if(ri > 0 && cj-3 > 0 && ri+3 <= HEIGHT && cj <= WIDTH &&
board[ri][cj] == board[ri+1][cj-1] && board[ri+1][cj-1] == board[ri+2][cj-2] && board[ri+2][cj-2] == board[ri+3][cj-3])
return 1;
ri++; ci++; cj--;
}
return 0;
}
//Get Player's input
//Param : prev_pos (int) - Previous Position
int get_input(int prev_pos){
int pos;
do{
while(getchar() != '\n');
if(total_drops > 0) printf("%c : %d, %d\n", SYMBOL[ai_turn^1], prev_pos, col_h[prev_pos]-1);
printf("Select Position [1, 7] : ");
}while(scanf("%d", &pos) < 1 || pos < 1 || pos > WIDTH || col_h[pos] > HEIGHT || (total_drops == 0 && pos == 4));
return pos;
}
int get_ai_pos(){
int pos = rule_based_eval();
//if pos = 0, not dropping immeidately
if (!pos) {
//minmax
pos = run_ai(state);
}
return pos;
}
void drop(int pos){
board[col_h[pos]++][pos] = SYMBOL[ai_turn];
state = init_state(state, pos);
}
//ADD stone on board and DRAW Whole board
//Param : pos (int) - position of new stone
void draw_board(int pos){
//clear();
for(int i = HEIGHT; i >= 0; i--){
for(int j = 0; j <= WIDTH; j++) printf("%c ", board[i][j]);
printf("\n");
}
}
void connect4(){
int pos = 0; //position of new stone
while(total_drops < WIDTH * HEIGHT){
if(ai_turn) pos = get_ai_pos();
else pos = get_input(pos);
drop(pos);
draw_board(pos);
if(check_end(pos)) break;
ai_turn ^= 1;
total_drops++;
}
if(total_drops == WIDTH * HEIGHT) printf("DRAW!!\n");
else printf("%s win!!\n", ai_turn ? "AI" : "Player");
}
int main(){
init();
connect4();
return 0;
}
| [
"[email protected]"
] | |
071d8393f53c4fa8adcc6a854dad9bec2b6b4171 | e1d43568c86498f733ee3d40f1048630aaa34719 | /actuator-firmware/tests/softspi_test.cpp | 9772c6a03dce7f004266c905059126db449f69d2 | [
"MIT"
] | permissive | tokyoyoukanniocha-jp/robot-software | 878a785cc1bbca4dbd5d723917299f36dd9343b8 | de32fdd58735e1634fa682e91332a51b5b9204fd | refs/heads/master | 2023-08-23T21:00:47.473720 | 2021-10-25T11:37:11 | 2021-10-25T11:37:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,740 | cpp | #include <cstring>
#include <cstdint>
#include <CppUTest/TestHarness.h>
#include <CppUTestExt/MockSupport.h>
#include "../src/softspi.h"
extern "C" void softspi_sck_set(softspi_t* dev, int status)
{
mock("softspi").actualCall("set_sck").withBoolParameter("state", status);
}
extern "C" void softspi_mosi_set(softspi_t* dev, int data)
{
mock("softspi").actualCall("set_mosi").withBoolParameter("data", data);
}
extern "C" int softspi_miso_get(softspi_t* dev)
{
return mock("softspi").actualCall("get_miso").returnIntValueOrDefault(0);
}
TEST_GROUP (SoftSpiTestGroup) {
static constexpr int bufsize = 10;
softspi_t spi;
uint8_t txbuf[bufsize];
uint8_t rxbuf[bufsize];
void setup() override
{
memset(txbuf, 0, sizeof txbuf);
mock("softspi").strictOrder();
}
};
TEST(SoftSpiTestGroup, InitPutsClockLow)
{
mock("softspi").expectOneCall("set_sck").withBoolParameter("state", false);
softspi_init(&spi);
}
TEST(SoftSpiTestGroup, CanSendSpi)
{
// First 4 bits transmitted will be '1' (MSB first)
txbuf[0] = 0xf0;
for (auto i = 0; i < 4; i++) {
mock("softspi").expectOneCall("set_mosi").withBoolParameter("data", true);
mock("softspi").expectOneCall("set_sck").withBoolParameter("state", true);
mock("softspi").expectOneCall("set_sck").withBoolParameter("state", false);
}
// All the followup bits are '0'
for (auto i = 0; i < bufsize * 8 - 4; i++) {
mock("softspi").expectOneCall("set_mosi").withBoolParameter("data", false);
mock("softspi").expectOneCall("set_sck").withBoolParameter("state", true);
mock("softspi").expectOneCall("set_sck").withBoolParameter("state", false);
}
mock("softspi").ignoreOtherCalls();
softspi_send(&spi, txbuf, rxbuf, bufsize);
}
TEST(SoftSpiTestGroup, CanReceiveSpi)
{
// The first received byte will be 0xf0, and all the rest will be zero
for (auto i = 0; i < 4; i++) {
mock("softspi").expectOneCall("set_sck").withBoolParameter("state", true);
mock("softspi").expectOneCall("get_miso").andReturnValue(1);
mock("softspi").expectOneCall("set_sck").withBoolParameter("state", false);
}
for (auto i = 0; i < bufsize * 8 - 4; i++) {
mock("softspi").expectOneCall("set_sck").withBoolParameter("state", true);
mock("softspi").expectOneCall("get_miso").andReturnValue(0);
mock("softspi").expectOneCall("set_sck").withBoolParameter("state", false);
}
mock("softspi").ignoreOtherCalls();
softspi_send(&spi, txbuf, rxbuf, bufsize);
CHECK_EQUAL_TEXT(0xf0, rxbuf[0], "Invalid RX data");
for (auto i = 1; i < 8; i++) {
CHECK_EQUAL_TEXT(0x0, rxbuf[i], "Invalid RX data");
}
}
| [
"[email protected]"
] | |
8b378905b2260b63a967eb86b01e3dd2b3b9defa | 726a7bbb1716d2363c6de8ed0ac3c29d769d8688 | /L3G4200D/L3G4200D.ino | 44de3d96667ffb6d4a220a81a419506f1bf4afc0 | [] | no_license | vietlinhtspt/gyroscope_module | 53635e5b48ddbf5bf21880a8420ac5855fe92a8d | 092bb5c90a862405555ea900891ea1f950b1f9e9 | refs/heads/main | 2023-02-05T02:26:09.464345 | 2020-12-29T10:18:18 | 2020-12-29T10:18:18 | 315,232,837 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,807 | ino | /*
L3G4200D Triple Axis Gyroscope: Output for L3G4200D_processing_pry.pde
Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/3-osiowy-zyroskop-l3g4200d.html
GIT: https://github.com/jarzebski/Arduino-L3G4200D
Web: http://www.jarzebski.pl
(c) 2014 by Korneliusz Jarzebski
*/
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
SoftwareSerial s(5,6);
#include <Wire.h>
#include <L3G4200D.h>
L3G4200D gyroscope;
// Timers
unsigned long timer = 0;
float timeStep = 0.01;
float timeStep_send = 0.5;
float current_milis = millis();
// Pitch, Roll and Yaw values
float pitch = 0;
float roll = 0;
float yaw = 0;
int LED = 13;
boolean Blink = false;
void setup()
{
s.begin(115200);
Serial.begin(115200);
// Initialize L3G4200D
// Set scale 2000 dps and 400HZ Output data rate (cut-off 50)
while (!gyroscope.begin(L3G4200D_SCALE_250DPS, L3G4200D_DATARATE_400HZ_50))
{
// Waiting for initialization
if (Blink)
{
digitalWrite(LED, HIGH);
} else
{
digitalWrite(LED, LOW);
}
Blink = !Blink;
delay(500);
}
digitalWrite(LED, HIGH);
// Calibrate gyroscope. The calibration must be at rest.
// If you don't want calibrate, comment this line.
Serial.println("Starting ");
gyroscope.calibrate(100);
digitalWrite(LED, LOW);
}
void loop()
{
timer = millis();
// Read normalized values
Vector norm = gyroscope.readNormalize();
// Calculate Pitch, Roll and Yaw
pitch = pitch + norm.YAxis * timeStep;
roll = roll + norm.XAxis * timeStep;
yaw = yaw + norm.ZAxis * timeStep;
// Output raw
// Serial.print(norm.XAxis);
// Serial.print(":");
// Serial.print(norm.YAxis);
// Serial.print(":");
// Serial.print(norm.ZAxis);
// Serial.print(":");
Serial.print(pitch);
Serial.print(":");
Serial.print(roll);
Serial.print(":");
Serial.println(yaw);
// Output indicator
if (Blink)
{
digitalWrite(LED, HIGH);
} else
{
digitalWrite(LED, LOW);
}
Blink = !Blink;
if (isnan(yaw) || isnan(pitch) || isnan(roll)) {
Serial.println("Nan. Return.");
return;
}
char message[40];
sprintf(message, "\"y\":%d, \"p\":%d, \"r\":%d", (int)yaw, (int)pitch, (int)roll);
Serial.println(message);
Serial.print("s.available: ");
Serial.println(s.available());
if(s.available()>0)
{
if (millis() - current_milis > timeStep_send * 1000)
{
current_milis = millis();
Serial.println("Printed to s(5,6)");
s.write(message);
// Serial.print("Printed to s(5,6)");
// Serial.println(message);
}
}
// Wait to full timeStep period
if ((timeStep*1000) - (millis() - timer) > 0)
{
// Serial.println((timeStep*1000) - (millis() - timer));
delay((timeStep*1000) - (millis() - timer));
}
}
//}
| [
"[email protected]"
] | |
cbb6212de738e25a9b1e1f73b4a08eac3ae9089c | 40a2a72e0a09686fce0c5a1d14a7a1449038955f | /src/rm/rmtest_01.cc | ac1a2b361b2e65fb075682d020b5a1c0063a074d | [
"Apache-2.0"
] | permissive | moophis/CS222-Simple-Data-Management-System | 0f10e31fca117fd97ff58f60b184f20f6e5ead5b | 55b34eccc4d66c0c0ed201992fd0a2cd4e4711d5 | refs/heads/master | 2020-12-03T05:20:53.188138 | 2014-12-13T23:32:10 | 2014-12-13T23:32:10 | 24,794,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,512 | cc | #include "test_util.h"
void printScanResult(const string &tableName) {
cout << "Entries in Index EmpName" << endl;
scanIndex(tableName, "EmpName", TypeVarChar);
cout << "Entries in Index Age" << endl;
scanIndex(tableName, "Age", TypeInt);
cout << "Entries in Index Height" << endl;
scanIndex(tableName, "Height", TypeReal);
cout << "Entries in Index Salary" << endl;
scanIndex(tableName, "Salary", TypeInt);
}
void TEST_RM_1(const string &tableName, const int nameLength, const string &name, const int age, const float height, const int salary)
{
// Functions tested
// 1. Insert Tuple **
// 2. Read Tuple **
// NOTE: "**" signifies the new functions being tested in this test case.
// Additional: create indexes, scan index
cout << "****In Test Case 1****" << endl;
RC rc;
RID rid;
int tupleSize = 0;
void *tuple = malloc(100);
void *returnedData = malloc(100);
// Create indexes
rc = rm->createIndex(tableName, "EmpName");
assert(rc == success);
rc = rm->createIndex(tableName, "Age");
assert(rc == success);
rc = rm->createIndex(tableName, "Height");
assert(rc == success);
rc = rm->createIndex(tableName, "Salary");
assert(rc == success);
// Insert a tuple into a table
prepareTuple(nameLength, name, age, height, salary, tuple, &tupleSize);
cout << "Insert Data:" << endl;
printTuple(tuple, tupleSize);
rc = rm->insertTuple(tableName, tuple, rid);
assert(rc == success);
cout << "Data inserted at <" << rid.pageNum << ", " << rid.slotNum << ">" << endl;
// Given the rid, read the tuple from table
rc = rm->readTuple(tableName, rid, returnedData);
assert(rc == success);
cout << "Returned Data:" << endl;
printTuple(returnedData, tupleSize);
// Scan from each index
printScanResult(tableName);
// // Delete table
// rc = rm->deleteTable(tableName);
// assert(rc == success);
// cout << "Delete table done" << endl;
// Compare whether the two memory blocks are the same
if(memcmp(tuple, returnedData, tupleSize) == 0)
{
cout << "****Test case 1 passed****" << endl << endl;
}
else
{
cout << "****Test case 1 failed****" << endl << endl;
}
free(tuple);
free(returnedData);
return;
}
int main()
{
cout << endl << "Test Insert/Read Tuple .." << endl;
// Insert/Read Tuple
TEST_RM_1("tbl_employee", 6, "Peters", 24, 170.1, 5000);
return 0;
}
| [
"[email protected]"
] | |
7df66581f38a3d629b4cee0bbf49db2315759baf | cfbb377e99605241b3a87155070977e0465b7ff0 | /main.cpp | 39211e4460a2b1131213feca353e409ac6323421 | [] | no_license | Niels4P/bildverarbeitung | d8b2590189c74b272d76b0e4f51475c4733d6468 | 91dd176e62eb88156ee255834943435f53b5d8d1 | refs/heads/master | 2021-01-10T15:03:56.056650 | 2015-07-27T16:41:54 | 2015-07-27T16:41:54 | 36,502,078 | 0 | 0 | null | null | null | null | ISO-8859-3 | C++ | false | false | 20,791 | cpp | #include <iostream>
#include <iomanip>
#include <vector>
#include <list>
#include <string>
#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>
#include <vigra/impex.hxx>
#include <vigra/multi_array.hxx>
#include <vigra/convolution.hxx>
#include <vigra/multi_math.hxx>
#include <vigra/matrix.hxx>
#include <vigra/regression.hxx>
#include <vigra/quadprog.hxx>
#include <vigra/gaussians.hxx>
#include <vigra/resampling_convolution.hxx>
#include <vigra/basicgeometry.hxx>
#include <vigra/splineimageview.hxx>
inline double log2(double n)
{
return log(n)/log(2.);
}
/**
* Very basic dogFeature structure
*/
struct dogFeature
{
float x; //x-coord
float y; //y-coord
float s; //scale (sigma)
float m; //magnitude of DoG
double a; //angle
};
/**
* Inline function to determine if there is a local extremum or not
* present in the dog stack...
*/
inline bool localExtremum(const std::vector<vigra::MultiArray<2, float> > & dog, int i, int x, int y)
{
float my_val = dog[i-2](x,y);
return ( ( my_val < dog[i-2](x-1,y-1) && my_val < dog[i-2](x,y-1) && my_val < dog[i-2](x+1,y-1)
&& my_val < dog[i-2](x-1,y) && my_val < dog[i-2](x+1,y)
&& my_val < dog[i-2](x-1,y+1) && my_val < dog[i-2](x,y+1) && my_val < dog[i-2](x+1,y+1)
&& my_val < dog[i-3](x-1,y-1) && my_val < dog[i-3](x,y-1) && my_val < dog[i-3](x+1,y-1)
&& my_val < dog[i-3](x-1,y) && my_val < dog[i-3](x-1,y) && my_val < dog[i-3](x+1,y)
&& my_val < dog[i-3](x-1,y+1) && my_val < dog[i-3](x,y+1) && my_val < dog[i-3](x+1,y+1)
&& my_val < dog[i-1](x-1,y-1) && my_val < dog[i-1](x,y-1) && my_val < dog[i-1](x+1,y-1)
&& my_val < dog[i-1](x-1,y) && my_val < dog[i-1](x-1,y) && my_val < dog[i-1](x+1,y)
&& my_val < dog[i-1](x-1,y+1) && my_val < dog[i-1](x,y+1) && my_val < dog[i-1](x+1,y+1))
|| ( my_val > dog[i-2](x-1,y-1) && my_val > dog[i-2](x,y-1) && my_val > dog[i-2](x+1,y-1)
&& my_val > dog[i-2](x-1,y) && my_val > dog[i-2](x+1,y)
&& my_val > dog[i-2](x-1,y+1) && my_val > dog[i-2](x,y+1) && my_val > dog[i-2](x+1,y+1)
&& my_val > dog[i-3](x-1,y-1) && my_val > dog[i-3](x,y-1) && my_val > dog[i-3](x+1,y-1)
&& my_val > dog[i-3](x-1,y) && my_val > dog[i-3](x-1,y) && my_val > dog[i-3](x+1,y)
&& my_val > dog[i-3](x-1,y+1) && my_val > dog[i-3](x,y+1) && my_val > dog[i-3](x+1,y+1)
&& my_val > dog[i-1](x-1,y-1) && my_val > dog[i-1](x,y-1) && my_val > dog[i-1](x+1,y-1)
&& my_val > dog[i-1](x-1,y) && my_val > dog[i-1](x-1,y) && my_val > dog[i-1](x+1,y)
&& my_val > dog[i-1](x-1,y+1) && my_val > dog[i-1](x,y+1) && my_val > dog[i-1](x+1,y+1)));
}
/**
* Inline function to determine the exact angle of orientation
*
*/
inline void calcParabolaVertex(int x1, int y1, int x2, int y2, int x3, int y3, double& xv) //double& yv
{
double denom = (x1 - x2) * (x1 - x3) * (x2 - x3);
double A = (x3 * (y2 - y1) + x2 * (y1 - y3) + x1 * (y3 - y2)) / denom;
double B = (x3*x3 * (y1 - y2) + x2*x2 * (y3 - y1) + x1*x1 * (y2 - y3)) / denom;
double C = (x2 * x3 * (x2 - x3) * y1 + x3 * x1 * (x3 - x1) * y2 + x1 * x2 * (x1 - x2) * y3) / denom;
xv = -B / (2*A);
//yv = C - B*B / (4*A);
}
/**
* Function to locate extrema on subpixel-level
* using first derivative and hessian matrix
*/
bool subpixel(const std::vector<vigra::MultiArray<2, float> > & dog, int i, int x, int y, float threshold, float ratio, float height, float width, float& off_x, float& off_y, float& off_s)
{
using namespace vigra;
using namespace vigra::linalg;
int s = i-2;
// derivative of first order
float dx = (dog[s](x+1,y)-dog[s](x-1,y))/2;
float dy = (dog[s](x,y+1)-dog[s](x,y-1))/2;
float ds = (dog[s+1](x,y)-dog[s-1](x,y))/2;
// partial derivatives of second order
float d2 = 2*dog[s](x,y);
float dxx = dog[s](x+1,y)+dog[s](x-1,y)-d2;
float dyy = dog[s](x,y+1)+dog[s](x,y-1)-d2;
float dss = dog[s+1](x,y)+dog[s-1](x,y)-d2;
float dxy = (dog[s](x+1,y+1)-dog[s](x-1,y+1)-dog[s](x+1,y-1)+dog[s](x-1,y-1))/4;
float dxs = (dog[s+1](x+1,y)-dog[s+1](x-1,y)-dog[s-1](x+1,y)+dog[s-1](x-1,y))/4;
float dys = (dog[s+1](x,y+1)-dog[s+1](x,y-1)-dog[s-1](x,y+1)+dog[s-1](x,y-1))/4;
// hessian matrix
float H_data[] = {
dxx, dxy, dxs,
dxy, dyy, dys,
dxs, dys, dss
};
// vector with derivatives of first order
float D_data[] = {
dx,
dy,
ds
};
Matrix<float> H(Shape2(3,3), H_data);
Matrix<float> D(Shape2(3,1), D_data);
Matrix<float> offset(Shape2(3,1));
// trace of the hessian to the power of 2 divided by the determinant of the hessian
float soe = pow(trace(H),2)/determinant(H);
//elimination of keypoints with a ratio below the given value between the principal curvatures
if (soe>=(pow((ratio+1),2))/ratio){
return false;
}
// calculation of the offset in every dimension (x,y,sigma)
bool solution = linearSolve(H, D, offset);
if (solution){
// rejection of unstable extrema with low contrast below the threshold
if ((std::abs(dog[s](x,y)) + dot(D.transpose(),-offset)*0.5) < threshold*256){
return false;
}
off_x = offset(0,0);
off_y = offset(1,0);
off_s = offset(2,0);
// no change of offset, if keypoint is at the edge of any dimension
if ((x == 1 && off_x >= 0.5f) || (x == width && off_x <= -0.5f))
off_x = 0.0f;
if ((y == 1 && off_y >= 0.5f) || (y == height && off_y <= -0.5f))
off_y = 0.0f;
// keypoint will be added
return true;
}
return false;
}
/**
* Inline function to determine the exact angle of orientation
*
*/
bool orientation(const std::vector<vigra::MultiArray<2, float> > & octave, int i, int x, int y, double& angle, double& angle2){
using namespace std;
using namespace vigra;
using namespace vigra::multi_math;
// Gaussian weighted circular window (8 pixel radius)
Gaussian<double> gauss(8.0/3.0);
vector<double> bin(36);
//check, if keypoint is too close to the edge of any dimension
if (x < 8 || x > octave[i].width() - 8)
return false;
if (y < 8 || y > octave[i].height() - 8)
return false;
// orientation of neighbouring pixel is weighted by the gaussian and its magnitude and added to a histogram (bin-array)
for(int yo=-7; yo<=8; ++yo){
for(int xo=-7; xo<=8; ++xo){
double r = sqrt(xo*xo + yo*yo);
double weight = gauss(r);
double magnitude = sqrt(pow(octave[i](x+xo+1,y+yo)-octave[i](x+xo-1,y+yo),2)+pow(octave[i](x+xo,y+yo+1)-octave[i](x+xo,y+yo-1),2));
int theta = int(((atan2(octave[i](x+xo,y+yo+1)-octave[i](x+xo,y+yo-1), octave[i](x+xo+1,y+yo)-octave[i](x+xo-1,y+yo))+M_PI)/M_PI)*18);
bin[theta] += magnitude * weight;
}
}
double peak_value = 0.0, peak2_value = 0.0;
int peak_element = 0, peak2_element = 0;
bool found2 = false;
//searching for the peak value in the histogram
for(int b=0; b<36; ++b){
if (bin[b]>peak_value){
peak_value = bin[b];
peak_element = b;
}
}
//check for a second peak element with at least 80% value of the peak element
//-> will be added as an extra feature point with exact same coordinates but different angle
for(int b=0; b<36; ++b){
if (b==peak_element){
continue;
} else if (bin[b]>peak_value*0.8){
peak2_value = bin[b];
peak2_element = b;
found2 = true;
}
}
//neighbours of peak element will be needed for parabola computation of the exact angle
int n1, n2;
n1 = peak_element - 1;
n2 = peak_element + 1;
if (n1 < 0){
n1 = 35;
}
if (n2 > 35){
n2 = 0;
}
//calculation of exact angle with parabola computation
//5 degrees is added to every bin to use the mean of every bin
calcParabolaVertex(n1*10+5,bin[n1],peak_element*10+5,bin[peak_element],n2*10+5,bin[n2],angle);
//a second peak element was found and needs to be calculated like the first
if (found2){
n1 = peak2_element - 1;
n2 = peak2_element + 1;
if (n1 < 0){
n1 = 35;
}
if (n2 > 35){
n2 = 0;
}
calcParabolaVertex(n1*10+5,bin[n1],peak2_element*10+5,bin[peak2_element],n2*10+5,bin[n2],angle2);
}
return true;
}
bool keypoint(const std::vector<vigra::MultiArray<2, float> > & octave, int i, int x, int y, double angle, std::vector<std::vector<double>>& feature){
using namespace std;
using namespace vigra;
using namespace vigra::multi_math;
//check, if keypoint is too close to the edge of any dimension
if (x < 16 || x > octave[i].width() - 16)
return false;
if (y < 16 || y > octave[i].height() - 16)
return false;
SplineImageView<2, double> spi(srcImageRange(octave[i]));
// Gaussian weighted circular window (8 pixel radius)
Gaussian<double> gauss(8.0);
vector<vector<double>> bin(16, vector<double>(8));
// orientation of neighbouring pixel is weighted by the gaussian and its magnitude and added to a histogram (bin-array)
for(int yo=-7; yo<=8; ++yo){
for(int xo=-7; xo<=8; ++xo){
/*P' =(x_P', y_P') ist der Punkt P=(x_P, y_P)^T, der um den Mittelpunkt
R=(x_R, x_R)^T um alpha Grad gedreht worden ist, mit:
x_P' = x_R + (x_P - x_R)*cos(alpha) - (y_P - y_R)*sin(alpha)
y_P' = y_R + (x_P - x_R)*sin(alpha) + (y_P - y_R)*cos(alpha)
*/
double curr_x = x + ((x+xo) - x)*cos(angle) - ((y+yo) - y)*sin(angle);
double curr_y = y + ((x+xo) - x)*sin(angle) + ((y+yo) - y)*cos(angle);
double r = sqrt(xo*xo + yo*yo);
double weight = gauss(r);
double pi_angle = angle/360*2*M_PI;
double magnitude = sqrt(pow(spi.dx(curr_x,curr_y),2)+pow(spi.dy(curr_x,curr_y),2));
int theta = int(abs(((atan2(spi.dy(curr_x,curr_y), spi.dx(curr_x,curr_y))+M_PI-pi_angle)/M_PI)*4));
int region = 0;
if (yo>=-7 && yo<=-4){
region = 0;
} else if (yo>-4 && yo<=0){
region = 4;
} else if (yo>0 && yo<=4){
region = 8;
} else if (yo>4 && yo<=8){
region = 12;
}
if (xo>=-7 && xo<=-4){
region += 0;
} else if (xo>-4 && xo<=0){
region += 1;
} else if (xo>0 && xo<=4){
region += 2;
} else if (xo>4 && xo<=8){
region += 3;
}
bin[region][theta] += magnitude * weight;
}
}
feature = bin;
return true;
//TODO: Werte müssen auch in benachbarte Bins eingetragen werden!
//Gewichtet mit 1-Abstand zum Mittelpunkt des Bins! (normalisieren!)
}
/**
* The main method - will be called at program execution
*/
int main(int argc, char** argv)
{
using namespace std;
using namespace vigra;
using namespace vigra::multi_math;
using namespace vigra::linalg;
namespace po = boost::program_options;
//Parameter variables
string image_filename;
float sigma,
dog_threshold;
bool double_image_size,
iterative_interval_creation;
float threshold = 0.03f;
float ratio = 10.0f;
//Program (argument) options
po::options_description desc("Allowed options");
desc.add_options()
("image_filename", po::value<string>(&image_filename)->required(), "input image filename")
("sigma", po::value<float>(&sigma)->default_value(1.0), "sigma of scale step")
("dog_threshold", po::value<float>(&dog_threshold)->default_value(5.0), "keypoint threshold")
("double_image_size", po::value<bool>(&double_image_size)->default_value(true), "double image size for 0th scale")
("iterative_interval_creation", po::value<bool>(&iterative_interval_creation)->default_value(true), "use iterative gaussian convolution for each octave interval");
//Additional options for determining the options without name but by order of appearance
po::positional_options_description p;
p.add("image_filename",1);
p.add("sigma",1);
p.add("dog_threshold",1);
p.add("double_image_size",1);
//This map will hold the parser results: We don't need it, becaus we directly linked our variables
//to the program options abouv, (&VARIABLE)...
po::variables_map vm;
try
{
//Store the command line args in the program options
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
//and do the parsing
po::notify(vm);
//Load the given image
MultiArray<2, float> image;
importImage(image_filename, image);
int width = image.width();
int height = image.height();
//If we rescale the image (double in each direction), we need to adjust the
//octave offset - thus resulting DoG positions will be divided by two at the
//lowermost scale if needed
int o_offset=0;
if(double_image_size)
{
MultiArray<2, float> tmp(image.shape()*2);
resizeImageLinearInterpolation(image, tmp);
image.reshape(tmp.shape());
gaussianSmoothing(tmp, image, sigma);
o_offset=-1;
}
//Determine the number of Octaves
int octaves=log2(min(image.width(),image.height()))-3;
//Further parameters
int s = 2;
float k = pow(2.0,1.0/s);
const int intervals = s+3;
//Data containers:
vector<MultiArray<2, float> > octave(intervals);
vector<MultiArray<2, float> > dog(intervals-1);
list<dogFeature> dogFeatures;
//initialise first octave with current (maybe doubled) image
octave[0] = image;
//vector to store the sigma-value of every scale
vector<double> scales;
vector<vector<vector<double>>> keypoints;
//Run the loop
for(int o=0; o<octaves; ++o)
{
string file_basename = string("sift_octave") + boost::lexical_cast<string>(o);
//exportImage(octave[0], file_basename+ + "_level0.png");
//clear for every octave and add zero element
scales.clear();
scales.push_back(0.0);
for (int i=1; i<intervals; ++i)
{
//initialize curent interval image array
octave[i].reshape(octave[i-1].shape());
//Create each interval step image using the previous one
if(iterative_interval_creation)
{
// (total_sigma)^2 = sigma^2 + (last_sigma)^2
// --> sigma = sqrt((total_sigma)^2 - (last_sigma)^2)!
//determine the last sigma
double last_sigma = pow(k, i-1.0)*sigma,
total_sigma = last_sigma*k;
//scales[i] = sqrt(total_sigma*total_sigma - last_sigma*last_sigma);
scales.push_back(sqrt(total_sigma*total_sigma - last_sigma*last_sigma));
gaussianSmoothing(octave[i-1], octave[i], scales[i]);
}
//Create each interval step using the base image
else
{
//scales[i] = pow(k,(double)i)*sigma;
scales.push_back(pow(k,(double)i)*sigma);
gaussianSmoothing(octave[0], octave[i], scales[i]);
}
//Compute the dog
dog[i-1].reshape(octave[i].shape());
dog[i-1] = octave[i]-octave[i-1];
//if we have at least three DoGs, we can search for local extrema
if(i>2)
{
//Determine current sigma of this dog step at this octave:
double current_sigma = o*sigma + pow(k, i-2.0)*sigma;
for (int y=1; y<dog[i-2].height()-1; ++y)
{
for (int x=1; x<dog[i-2].width()-1; ++x)
{
float my_val = dog[i-2](x,y);
if ( abs(my_val) > dog_threshold && localExtremum(dog, i,x,y))
{
//calling subpixel function to determine subpixel-offset of extrema
float off_x, off_y, off_s;
if (subpixel(dog,i,x,y,threshold,ratio,dog[i-2].height()-1,dog[i-2].width()-1,off_x,off_y,off_s)){
int scale = 0;
double sigscale = 10.0;
//calculating the scale, where to look for orientation
//sigma of dog, where the extrema was found, has to be used to find the matching image with similar sigma in octave array
for(int s=0; s<scales.size(); ++s){
double check = abs(scales[s]-(current_sigma-off_s));
if (sigscale > check){
sigscale = check;
scale = s;
}
}
double angle, angle2;
bool save, save_kp;
//calculation of orientation of keypoint
//keypoint will be dismissed, if save is false
//may cause the need to add a second one (if angle2 is given back)
save = orientation(octave, scale, x, y, angle, angle2);
//adding keypoint(s) to list of feature keypoints
if (save) {
dogFeature new_feature = { (x-off_x)*pow(2,o+o_offset),
(y-off_y)*pow(2,o+o_offset),
(current_sigma-off_s),
abs(my_val),
angle};
dogFeatures.push_back(new_feature);
vector<vector<double>> kp(16, vector<double>(8));
save_kp = keypoint(octave, scale, x, y, angle, kp);
if (save_kp){
keypoints.push_back(kp);
}
if (angle2){
dogFeature new_feature = { (x-off_x)*pow(2,o+o_offset),
(y-off_y)*pow(2,o+o_offset),
(current_sigma-off_s),
abs(my_val),
angle2};
dogFeatures.push_back(new_feature);
save_kp = keypoint(octave, scale, x, y, angle2, kp);
if (save_kp){
keypoints.push_back(kp);
}
}
}
}
}
}
}
}
//exportImage(dog[i-1], file_basename + "_dog" + boost::lexical_cast<string>(i-1) + ".png");
//exportImage(octave[i], file_basename + "_level" + boost::lexical_cast<string>(i) + ".png");
}
//rescale for next pyramid step and resize old image (3rd from top)
octave[0].reshape(octave[0].shape()/2);
resizeImageNoInterpolation(octave[s], octave[0]);
}
/*
cout << " x; y; s; m\n";
for(const dogFeature& f : dogFeatures)
{
cout << setw(8) << fixed << setprecision(3) << f.x << "; "
<< setw(8) << fixed << setprecision(1) << f.y << ";"
<< setw(8) << fixed << setprecision(1) << f.s << ";"
<< setw(8) << fixed << setprecision(3) << f.m << "\n";
}
cout << "Found: " << dogFeatures.size() << " candidates.\n";
*/
//output will be in scalable vector graphics format
//with link to original image file in same directory
/*
cout << "<svg height=\"" << height << "\" width=\"" << width << "\">\n";
cout << "<g>\n" << "<image y=\"0.0\" x=\"0.0\" xlink:href=\"" << image_filename << "\" height=\"" << height << "\" width=\"" << width << "\" />\n" << "</g>\n";
cout << "<g>\n";
for(const dogFeature& f : dogFeatures)
{
cout << "<rect x=\"" << -(f.s/2) << "\" y=\"" << -(f.s/2) << "\" height=\"" << f.s << "\" width=\"" << f.s << "\" stroke=\"red\" fill=\"none\" transform=\"translate(" << f.x << "," << f.y << ") rotate(" << f.a << ")\" />\n";
}
cout << "</g>\n";
cout << "</svg>";
*/
//transform=\"rotate(" << f.a << "," << f.x-(f.s/2) << "," << f.y-(f.s/2) << ")\"
for(const vector<vector<double>>& kp : keypoints)
{
cout << "Keypoint\n";
for(int i=0; i<16; ++i){
cout << "Region " << i << ": [";
for(int j=0; j<8; ++j){
cout << j*8 << "° " << kp[i][j] << ", ";
}
cout << "]\n";
}
}
}
catch(po::required_option& e)
{
cerr << "Error: " << e.what()
<< std::endl
<< std::endl
<< desc << std::endl;
return 1;
}
catch(po::error& e)
{
cerr << "Error: " << e.what()
<< std::endl
<< std::endl
<< desc << std::endl;
return 1;
}
catch(exception & e)
{
cerr << "Error: " << e.what() << "\n";
}
return 0;
} | [
"[email protected]"
] | |
df29bb2862a0029fca1e38076cbfc68e2bc1351f | ca21d51502ca531a6190fba03df4a7e4ca4cc546 | /src/formats/chiptune/fm/tfc.cpp | 9509ab752134d548f429c0e6bc0e269d739dd1b0 | [] | no_license | wothke/spectrezx | 4b53e42dbf6d159a20b991a8082dc796ae15232c | 1878c17cdb2619a1c90d60b101c4951c790e226b | refs/heads/master | 2021-07-11T18:43:38.044905 | 2021-04-17T00:37:47 | 2021-04-17T00:37:47 | 36,067,729 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,900 | cpp | /**
*
* @file
*
* @brief TurboFM Compiled support implementation
*
* @author [email protected]
*
**/
//local includes
#include "tfc.h"
#include "formats/chiptune/container.h"
//common includes
#include <byteorder.h>
//library includes
#include <binary/format_factories.h>
#include <binary/input_stream.h>
#include <binary/typed_container.h>
//boost includes
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/make_shared.hpp>
//text includes
#include <formats/text/chiptune.h>
namespace Formats
{
namespace Chiptune
{
namespace TFC
{
typedef boost::array<uint8_t, 6> SignatureType; // keep boost::array to ease comparison
const SignatureType SIGNATURE = { {'T', 'F', 'M', 'c', 'o', 'm'} };
#ifdef USE_PRAGMA_PACK
#pragma pack(push,1)
#endif
PACK_PRE struct RawHeader
{
SignatureType Sign;
char Version[3];
uint8_t IntFreq;
ruint16_t Offsets[6];
uint8_t Reserved[12];
} PACK_POST;
PACK_PRE struct RawInt16
{
rint16_t Val;
} PACK_POST;
PACK_PRE struct RawUint16
{
ruint16_t Val;
} PACK_POST;
#ifdef USE_PRAGMA_PACK
#pragma pack(pop)
#endif
const std::size_t MIN_SIZE = sizeof(RawHeader) + 3 + 6;//header + 3 empty strings + 6 finish markers
const std::size_t MAX_STRING_SIZE = 64;
const std::size_t MAX_COMMENT_SIZE = 384;
class StubBuilder : public Builder
{
public:
virtual void SetVersion(const String& /*version*/) {}
virtual void SetIntFreq(uint_t /*freq*/) {}
virtual void SetTitle(const String& /*title*/) {}
virtual void SetAuthor(const String& /*author*/) {}
virtual void SetComment(const String& /*comment*/) {}
virtual void StartChannel(uint_t /*idx*/) {}
virtual void StartFrame() {}
virtual void SetSkip(uint_t /*count*/) {}
virtual void SetLoop() {}
virtual void SetSlide(uint_t /*slide*/) {}
virtual void SetKeyOff() {}
virtual void SetFreq(uint_t /*freq*/) {}
virtual void SetRegister(uint_t /*reg*/, uint_t /*val*/) {}
virtual void SetKeyOn() {}
};
bool checkOffsets(const RawHeader& hdr, const std::size_t size) {
for (int i= 0; i<6-1; i++) { // if some earlier element can be matched then return false
if (fromLE<uint16_t>(hdr.Offsets[i]) >= size)
// if (fromLE(hdr.Offsets[i]) >= size) XXX
return false;
}
return true;
}
bool FastCheck(const Binary::Container& rawData)
{
const std::size_t size = rawData.Size();
if (size < MIN_SIZE)
{
return false;
}
const RawHeader& hdr = *static_cast<const RawHeader*>(rawData.Start());
return (hdr.Sign == SIGNATURE) && checkOffsets(hdr, size);
}
const std::string FORMAT(
"'T'F'M'c'o'm"
"???"
"32|3c"
);
class Decoder : public Formats::Chiptune::Decoder
{
public:
Decoder()
: Format(Binary::CreateFormat(FORMAT, MIN_SIZE))
{
}
virtual String GetDescription() const
{
return Text::TFC_DECODER_DESCRIPTION;
}
virtual Binary::Format::Ptr GetFormat() const
{
return Format;
}
virtual bool Check(const Binary::Container& rawData) const
{
return FastCheck(rawData);
}
virtual Formats::Chiptune::Container::Ptr Decode(const Binary::Container& rawData) const
{
Builder& stub = GetStubBuilder();
return Parse(rawData, stub);
}
private:
const Binary::Format::Ptr Format;
};
struct Context
{
std::size_t RetAddr;
std::size_t RepeatFrames;
Context()
: RetAddr()
, RepeatFrames()
{
}
};
class Container
{
public:
explicit Container(const Binary::Container& data)
: Delegate(data)
, Min(Delegate.GetSize())
, Max(0)
{
}
std::size_t ParseFrameControl(std::size_t cursor, Builder& target, Context& context) const
{
if (context.RepeatFrames && !--context.RepeatFrames)
{
cursor = context.RetAddr;
context.RetAddr = 0;
}
for (;;)
{
const uint_t cmd = Get<uint8_t>(cursor++);
if (cmd == 0x7f)//%01111111
{
return 0;
}
else if (0x7e == cmd)//%01111110
{
target.SetLoop();
continue;
}
else if (0xd0 == cmd)//%11010000
{
Require(context.RepeatFrames == 0);
Require(context.RetAddr == 0);
context.RepeatFrames = Get<uint8_t>(cursor++);
const int_t offset = fromBE(Get<RawInt16>(cursor).Val);
context.RetAddr = cursor += 2;
return cursor + offset;
}
else
{
return cursor - 1;
}
}
}
std::size_t ParseFrameCommands(std::size_t cursor, Builder& target) const
{
const uint_t cmd = Get<uint8_t>(cursor++);
if (0xbf == cmd)//%10111111
{
const int_t offset = fromBE(Get<RawInt16>(cursor).Val);
cursor += 2;
ParseFrameData(cursor + offset, target);
}
else if (0xff == cmd)//%11111111
{
const int_t offset = -256 + Get<uint8_t>(cursor++);
ParseFrameData(cursor + offset, target);
}
else if (cmd >= 0xe0)//%111ttttt
{
target.SetSkip(256 - cmd);
}
else if (cmd >= 0xc0)//%110ddddd
{
target.SetSlide(cmd + 0x30);
}
else
{
cursor = ParseFrameData(cursor - 1, target);
}
return cursor;
}
std::size_t GetMin() const
{
return Min;
}
std::size_t GetMax() const
{
return Max;
}
private:
std::size_t ParseFrameData(std::size_t cursor, Builder& target) const
{
const uint_t data = Get<uint8_t>(cursor++);
if (0 != (data & 0xc0))
{
target.SetKeyOff();
}
if (0 != (data & 0x01))
{
const uint_t freq = fromBE(Get<RawUint16>(cursor).Val);
cursor += 2;
target.SetFreq(freq);
}
if (uint_t regs = (data & 0x3e) >> 1)
{
for (uint_t i = 0; i != regs; ++i)
{
const uint_t reg = Get<uint8_t>(cursor++);
const uint_t val = Get<uint8_t>(cursor++);
target.SetRegister(reg, val);
}
}
if (0 != (data & 0x80))
{
target.SetKeyOn();
}
return cursor;
}
private:
template<class T>
const T& Get(std::size_t offset) const
{
const T* const ptr = Delegate.GetField<T>(offset);
Require(ptr != 0);
Min = std::min(Min, offset);
Max = std::max(Max, offset + sizeof(T));
return *ptr;
}
private:
const Binary::TypedContainer Delegate;
mutable std::size_t Min;
mutable std::size_t Max;
};
Formats::Chiptune::Container::Ptr Parse(const Binary::Container& data, Builder& target)
{
if (!FastCheck(data))
{
return Formats::Chiptune::Container::Ptr();
}
try
{
Binary::InputStream stream(data);
const RawHeader& header = stream.ReadField<RawHeader>();
target.SetVersion(FromCharArray(header.Version));
target.SetIntFreq(header.IntFreq);
target.SetTitle(FromStdString(stream.ReadCString(MAX_STRING_SIZE)));
target.SetAuthor(FromStdString(stream.ReadCString(MAX_STRING_SIZE)));
target.SetComment(FromStdString(stream.ReadCString(MAX_COMMENT_SIZE)));
const Container container(data);
for (uint_t chan = 0; chan != 6; ++chan)
{
target.StartChannel(chan);
Context context;
for (std::size_t cursor = fromLE(header.Offsets[chan]); cursor != 0;)
{
if ((cursor = container.ParseFrameControl(cursor, target, context)))
{
target.StartFrame();
cursor = container.ParseFrameCommands(cursor, target);
}
}
}
const std::size_t usedSize = std::max(container.GetMax(), stream.GetPosition());
const std::size_t fixedOffset = container.GetMin();
const Binary::Container::Ptr subData = data.GetSubcontainer(0, usedSize);
return CreateCalculatingCrcContainer(subData, fixedOffset, usedSize - fixedOffset);
}
catch (const std::exception&)
{
return Formats::Chiptune::Container::Ptr();
}
}
Builder& GetStubBuilder()
{
static StubBuilder stub;
return stub;
}
}//namespace TFC
Decoder::Ptr CreateTFCDecoder()
{
return boost::make_shared<TFC::Decoder>();
}
}//namespace Chiptune
}//namespace Formats
| [
"[email protected]"
] | |
03f6f20c2eb292561fd060848360e03fbe33198f | 41e9eaa410050fe1b1abc315ed044f4b29971796 | /Dasha and Stairs.cpp | d09d31b25296586fc4ec9fada23cfde8dedb1d8f | [] | no_license | Raisul191491/Noob_C- | 32202ccf298de2915685b1a091fa5d7bf4cb80b3 | 3ce698ca763dab2a3d95f8dbfd1a755161e1857b | refs/heads/master | 2023-02-26T11:18:19.107628 | 2021-02-01T18:24:01 | 2021-02-01T18:24:01 | 240,031,404 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,021 | cpp | #include<bits/stdc++.h>
typedef long long ll;
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define last freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
#define fr first
#define sc second
#define lcm(a,b) (a*b)/__gcd(a,b)
#define com(i,n) for(int i=0;i<n;i++)
#define dom(i,n) for(int i=1;i<=n;i++)
#define mom(i,n) for(int i=n;i>=0;i--)
#define sortI(a,n) sort(a,a+n)
#define sortD(a,n) sort(a,a+n,greater<int>())
#define sortvi(a) sort(a.begin(),a.end())
#define sortvd(a) sort(a.begin(),a.end(),greater<int>())
#define sumall(a,x) accumulate(a.begin(),a.end(),x)
#define pi 3.14159265358979323846264338327950
#define endl '\n'
using namespace std;
int main()
{
int a,b;
cin>>a>>b;
if(a>0 || b>0)
{
if(abs(a-b)<=1)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
else
cout << "NO" << endl;
}
| [
"[email protected]"
] | |
ab5ca200632ca2a73acd6b1ed5314dfeab7cf297 | 8fff5cbd347b5f887e0670584905da5dfceb7118 | /atm_panel.cpp | c71bde2a74c14b3d5c3109a27c00e0cd9d28dff0 | [] | no_license | Centurix/attract | 7f4293d4d610e51c36fb5debaf23e4061ed12439 | e1a95a5e27d866265ee8207d621b49dd9ffb0816 | refs/heads/master | 2021-01-21T23:53:23.621609 | 2017-09-02T08:07:06 | 2017-09-02T08:07:06 | 102,182,308 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,356 | cpp | #include "atm_panel.h"
#include "panel_charset.h"
#include "panel_images.h"
#define BRIGHTNESS 64
Atm_panel & Atm_panel::begin() {
const static state_t state_table[] PROGMEM = {
/*|- STATES -----------|- ACTIONS ------------------------------------|- EVENTS ---------------------------------------------------------------------------------------------------------------------------------|
/* ON_ENTER, ON_LOOP, ON_EXIT, EVT_TIMER, EVT_ON, EVT_OFF, EVT_RAINBOW_ON, EVT_RAINBOW_TIMER, EVT_HISCORE_ON, EVT_HISCORE_TIMER, EVT_MAME, EVT_GAME, ELSE */
/* IDLE */ ENT_MAME_FLASH_OFF, -1, -1, -1, MAME_FLASH_ON, -1, RAINBOW, -1, HISCORE, -1, MAME_ON, GAME_ON, -1,
/* MAME_FLASH_ON */ ENT_MAME_FLASH_ON, -1, -1, MAME_FLASH_OFF, -1, -1, RAINBOW, -1, HISCORE, -1, MAME_ON, GAME_ON, -1,
/* MAME_FLASH_OFF */ ENT_MAME_FLASH_OFF, -1, -1, GAME_FLASH_ON, -1, -1, RAINBOW, -1, HISCORE, -1, MAME_ON, GAME_ON, -1,
/* GAME_FLASH_ON */ ENT_GAME_FLASH_ON, -1, -1, GAME_FLASH_OFF, -1, -1, RAINBOW, -1, HISCORE, -1, MAME_ON, GAME_ON, -1,
/* GAME_FLASH_OFF */ ENT_GAME_FLASH_OFF, -1, -1, MAME_FLASH_ON, -1, -1, RAINBOW, -1, HISCORE, -1, MAME_ON, GAME_ON, -1,
/* RAINBOW */ ENT_RAINBOW_ON, -1, -1, -1, -1, -1, RAINBOW, RAINBOW, HISCORE, -1, MAME_ON, GAME_ON, -1,
/* HISCORE */ ENT_HISCORE_ON, -1, -1, -1, -1, -1, RAINBOW, -1, HISCORE, HISCORE, MAME_ON, GAME_ON, -1,
/* MAME_ON */ ENT_MAME_FLASH_ON, -1, -1, -1, -1, -1, RAINBOW, -1, HISCORE, -1, MAME_ON, GAME_ON, -1,
/* GAME_ON */ ENT_GAME_FLASH_ON, -1, -1, -1, -1, -1, RAINBOW, -1, HISCORE, -1, MAME_ON, GAME_ON, -1
};
Machine::begin(state_table, ELSE);
width = 32;
height = 8;
safe_leds = new CRGB[width * height + 1];
timer.set(500);
rainbow_timer.set(45);
hiscore_timer.set(1000);
hiscore.reserve(20);
// Specific Panel information
FastLED.addLeds<WS2812B, PANEL_PIN, GRB>(safe_leds, width * height).setCorrection(TypicalSMD5050);
FastLED.setBrightness(64);
return *this;
}
int Atm_panel::event(int id) {
switch(id) {
case EVT_TIMER:
return timer.expired(this);
case EVT_RAINBOW_TIMER:
return rainbow_timer.expired(this);
case EVT_HISCORE_TIMER:
return hiscore_timer.expired(this);
}
return 0;
}
void Atm_panel::action(int id) {
uint32_t ms;
int32_t yHueDelta32, xHueDelta32;
switch(id) {
case ENT_MAME_FLASH_ON:
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
safe_leds[ XY(x, y) ] = img_mame[y][x];
}
}
FastLED.show();
return;
case ENT_MAME_FLASH_OFF:
empty();
FastLED.show();
return;
case ENT_GAME_FLASH_ON:
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
safe_leds[ XY(x, y) ] = img_game[y][x];
}
}
FastLED.show();
return;
case ENT_GAME_FLASH_OFF:
empty();
FastLED.show();
return;
case ENT_RAINBOW_ON:
ms = millis();
yHueDelta32 = ((int32_t)cos16( ms * (27/1) ) * (350 / width));
xHueDelta32 = ((int32_t)cos16( ms * (39/1) ) * (310 / height));
drawOneFrame( ms / 65536, yHueDelta32 / 32768, xHueDelta32 / 32768);
if( ms < 5000 ) {
FastLED.setBrightness( scale8( BRIGHTNESS, (ms * 256) / 5000));
} else {
FastLED.setBrightness(BRIGHTNESS);
}
FastLED.show();
return;
case ENT_HISCORE_ON:
// Show the score send through the serial port. Need a charset and a way to display it right here!
empty();
addText(hiscore, 0, 0, CRGB::Blue);
FastLED.show();
return;
}
}
uint16_t Atm_panel::XY( uint8_t x, uint8_t y) {
uint16_t offset = ((width - 1)- x) * height;
if (x & 0x01) {
return offset + height - 1 - y;
} else {
return offset + y;
}
return offset;
}
void Atm_panel::setGameImage(uint8_t image_data[768]) {
int row = 0;
int col = 0;
for (int index = 0; index < 768; index += 3) {
long red = image_data[index];
long green = image_data[index + 1];
long blue = image_data[index + 2];
long value = red << 16 | green << 8 | blue;
img_game[row][col++] = value;
if (col >= 32) {
col = 0;
row++;
if (row >= 8) {
row = 0;
}
}
}
}
void Atm_panel::drawOneFrame( byte startHue8, int8_t yHueDelta8, int8_t xHueDelta8) {
byte lineStartHue = startHue8;
for( byte y = 0; y < height; y++) {
lineStartHue += yHueDelta8;
byte pixelHue = lineStartHue;
for( byte x = 0; x < width; x++) {
pixelHue += xHueDelta8;
safe_leds[ XY(x, y)] = CHSV( pixelHue, 255, 255);
}
}
}
void Atm_panel::empty() {
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
safe_leds[ XY(x, y) ] = CRGB::Black;
}
}
}
void Atm_panel::addText(String text, int8_t x, int8_t y, CRGB text_color) {
int cursor = x;
for(int index = 0; index < text.length(); index++) {
int char_value = (int)text[index] - 32;
for(int line = 0; line < 8; line++) {
for(int pixel = 0; pixel < 8; pixel++) {
uint8_t byte_line = pgm_read_byte(charset + (char_value * 8) + line);
if ((byte_line & round(pow(2, (7 - pixel)))) > 0) {
safe_leds[ XY(cursor + pixel, line) ] = text_color;
}
}
}
// Move the cursor position
cursor += pgm_read_byte(char_widths + char_value);
}
}
| [
"[email protected]"
] | |
81ec819ba4b4ad7324fe44d5af59bf85377bb41a | fc7d5b988d885bd3a5ca89296a04aa900e23c497 | /Programming/mbed-os-example-sockets/mbed-os/connectivity/nfc/include/nfc/NFCEEPROMDriver.h | 1451dfc00181dc2cf7fabed158a4fed16ba18ff7 | [
"Apache-2.0"
] | permissive | AlbinMartinsson/master_thesis | 52746f035bc24e302530aabde3cbd88ea6c95b77 | 495d0e53dd00c11adbe8114845264b65f14b8163 | refs/heads/main | 2023-06-04T09:31:45.174612 | 2021-06-29T16:35:44 | 2021-06-29T16:35:44 | 334,069,714 | 3 | 1 | Apache-2.0 | 2021-03-16T16:32:16 | 2021-01-29T07:28:32 | C++ | UTF-8 | C++ | false | false | 6,106 | h | /* mbed Microcontroller Library
* Copyright (c) 2018 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 MBED_NFC_EEPROM_DRIVER_H
#define MBED_NFC_EEPROM_DRIVER_H
#include <stdint.h>
#include "events/EventQueue.h"
namespace mbed {
namespace nfc {
/**
* @addtogroup nfc
* @{
*/
/**
* The abstraction for a NFC EEPROM driver.
* Implementers need to derive from this class and implement its methods.
*/
class NFCEEPROMDriver {
public:
/**
* Construct a NFCEEPROM driver instance.
*/
NFCEEPROMDriver();
/**
* NFCEEPROM driver destructor.
*/
virtual ~NFCEEPROMDriver();
/**
* The NFCEEPROMDriver delegate.
* Methods in this class are called by the driver on completion of long-running operations.
*/
struct Delegate {
/**
* Completion of session start operation.
*
* @param[in] success whether this operation succeeded
*/
virtual void on_session_started(bool success) = 0;
/**
* Completion of session end operation.
*
* @param[in] success whether this operation succeeded
*/
virtual void on_session_ended(bool success) = 0;
/**
* Completion of read operation.
*
* @param[in] count number of bytes actually read
*/
virtual void on_bytes_read(size_t count) = 0;
/**
* Completion of write operation.
*
* @param[in] count number of bytes actually written
*/
virtual void on_bytes_written(size_t count) = 0;
/**
* Completion of size retrieval operation.
*
* @param[in] success whether this operation succeeded
* @param[out] size the current addressable memory size
*/
virtual void on_size_read(bool success, size_t size) = 0;
/**
* Completion of size setting operation.
*
* @param[in] success whether this operation succeeded
*/
virtual void on_size_written(bool success) = 0;
/**
* Completion of erasing operation.
*
* @param[in] count number of bytes actually erased
*/
virtual void on_bytes_erased(size_t count) = 0;
protected:
~Delegate() {}
};
/**
* Set the delegate that will receive events generated by this EEPROM.
*
* @param[in] delegate the delegate instance to use
*/
void set_delegate(Delegate *delegate);
/**
* Set the event queue that will be used to schedule event handling
*
* @param[in] queue the queue instance to use
*/
void set_event_queue(events::EventQueue *queue);
/**
* Reset and initialize the EEPROM.
* This method should complete synchronously.
*/
virtual void reset() = 0;
/**
* Get the maximum memory size addressable by the EEPROM.
*/
virtual size_t read_max_size() = 0;
/**
* Start a session of operations (reads, writes, erases, size gets/sets).
* This method is called prior to any memory access to allow the underlying implementation
* to disable the RF interface or abort the transaction if it's being used.
* This method should complete asynchronously by calling has_started_session().
*/
virtual void start_session(bool force = true) = 0; // This could lock the chip's RF interface
/**
* End a session.
* This method should complete asynchronously by calling has_ended_session().
*/
virtual void end_session() = 0;
/**
* Read bytes from memory.
* @param[in] address the virtual address (starting from 0) from which to start the read.
* @param[out] bytes a buffer in which the read bytes will be stored.
* This buffer should remain valid till the callback is called.
* @param[in] count the number of bytes to read.
* This method should complete asynchronously by calling has_read_bytes().
*/
virtual void read_bytes(uint32_t address, uint8_t *bytes, size_t count) = 0;
/**
* Write bytes to memory.
* @param[in] address the virtual address (starting from 0) from which to start the write.
* @param[in] bytes a buffer from to copy.
* This buffer should remain valid till the callback is called.
* @param[in] count the number of bytes to write.
* This method should complete asynchronously by calling has_written_bytes().
*/
virtual void write_bytes(uint32_t address, const uint8_t *bytes, size_t count) = 0;
/**
* Retrieve the size of the addressable memory.
* This method should complete asynchronously by calling has_gotten_size().
*/
virtual void read_size() = 0;
/**
* Set the size of the addressable memory.
* @param[in] count the number of addressable bytes.
* This method should complete asynchronously by calling has_set_size().
*/
virtual void write_size(size_t count) = 0;
/**
* Erase bytes from memory.
* @param[in] address the virtual address (starting from 0) from which to start erasing.
* @param[in] size the number of bytes to erase.
* This method should complete asynchronously by calling has_erased_bytes().
*/
virtual void erase_bytes(uint32_t address, size_t size) = 0;
protected:
Delegate *delegate();
events::EventQueue *event_queue();
private:
Delegate *_delegate;
events::EventQueue *_event_queue;
};
/**
* @}
*/
} // namespace nfc
} // namespace mbed
#endif
| [
"[email protected]"
] | |
da7ad2dd08dc946180a53002585fb1cd8af31270 | 3b542298d1046b163f243d360943599f0e426e2a | /deps/v8/src/x64/macro-assembler-x64.h | cc057ac54ca84efbae3a7c346531e8f004b0a235 | [
"LicenseRef-scancode-unknown-license-reference",
"ISC",
"LicenseRef-scancode-openssl",
"Apache-2.0",
"MIT",
"BSD-3-Clause",
"BSD-2-Clause",
"Artistic-2.0",
"NTP",
"Zlib",
"bzip2-1.0.6"
] | permissive | jashandeep-sohi/nodejs-qnx | 59ad84df742d779bfcbf9f25899d04c8dc57a610 | f8aa8a4c29ebc8157965400f98f79c3f39b4b608 | refs/heads/master | 2022-11-22T01:28:57.252590 | 2017-10-11T05:26:40 | 2017-10-11T05:26:40 | 106,509,655 | 2 | 3 | NOASSERTION | 2022-11-20T17:20:43 | 2017-10-11T05:29:43 | JavaScript | UTF-8 | C++ | false | false | 61,933 | h | // Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef V8_X64_MACRO_ASSEMBLER_X64_H_
#define V8_X64_MACRO_ASSEMBLER_X64_H_
#include "assembler.h"
#include "frames.h"
#include "v8globals.h"
namespace v8 {
namespace internal {
// Flags used for the AllocateInNewSpace functions.
enum AllocationFlags {
// No special flags.
NO_ALLOCATION_FLAGS = 0,
// Return the pointer to the allocated already tagged as a heap object.
TAG_OBJECT = 1 << 0,
// The content of the result register already contains the allocation top in
// new space.
RESULT_CONTAINS_TOP = 1 << 1
};
// Default scratch register used by MacroAssembler (and other code that needs
// a spare register). The register isn't callee save, and not used by the
// function calling convention.
const Register kScratchRegister = { 10 }; // r10.
const Register kSmiConstantRegister = { 12 }; // r12 (callee save).
const Register kRootRegister = { 13 }; // r13 (callee save).
// Value of smi in kSmiConstantRegister.
const int kSmiConstantRegisterValue = 1;
// Actual value of root register is offset from the root array's start
// to take advantage of negitive 8-bit displacement values.
const int kRootRegisterBias = 128;
// Convenience for platform-independent signatures.
typedef Operand MemOperand;
enum RememberedSetAction { EMIT_REMEMBERED_SET, OMIT_REMEMBERED_SET };
enum SmiCheck { INLINE_SMI_CHECK, OMIT_SMI_CHECK };
bool AreAliased(Register r1, Register r2, Register r3, Register r4);
// Forward declaration.
class JumpTarget;
struct SmiIndex {
SmiIndex(Register index_register, ScaleFactor scale)
: reg(index_register),
scale(scale) {}
Register reg;
ScaleFactor scale;
};
// MacroAssembler implements a collection of frequently used macros.
class MacroAssembler: public Assembler {
public:
// The isolate parameter can be NULL if the macro assembler should
// not use isolate-dependent functionality. In this case, it's the
// responsibility of the caller to never invoke such function on the
// macro assembler.
MacroAssembler(Isolate* isolate, void* buffer, int size);
// Prevent the use of the RootArray during the lifetime of this
// scope object.
class NoRootArrayScope BASE_EMBEDDED {
public:
explicit NoRootArrayScope(MacroAssembler* assembler)
: variable_(&assembler->root_array_available_),
old_value_(assembler->root_array_available_) {
assembler->root_array_available_ = false;
}
~NoRootArrayScope() {
*variable_ = old_value_;
}
private:
bool* variable_;
bool old_value_;
};
// Operand pointing to an external reference.
// May emit code to set up the scratch register. The operand is
// only guaranteed to be correct as long as the scratch register
// isn't changed.
// If the operand is used more than once, use a scratch register
// that is guaranteed not to be clobbered.
Operand ExternalOperand(ExternalReference reference,
Register scratch = kScratchRegister);
// Loads and stores the value of an external reference.
// Special case code for load and store to take advantage of
// load_rax/store_rax if possible/necessary.
// For other operations, just use:
// Operand operand = ExternalOperand(extref);
// operation(operand, ..);
void Load(Register destination, ExternalReference source);
void Store(ExternalReference destination, Register source);
// Loads the address of the external reference into the destination
// register.
void LoadAddress(Register destination, ExternalReference source);
// Returns the size of the code generated by LoadAddress.
// Used by CallSize(ExternalReference) to find the size of a call.
int LoadAddressSize(ExternalReference source);
// Pushes the address of the external reference onto the stack.
void PushAddress(ExternalReference source);
// Operations on roots in the root-array.
void LoadRoot(Register destination, Heap::RootListIndex index);
void StoreRoot(Register source, Heap::RootListIndex index);
// Load a root value where the index (or part of it) is variable.
// The variable_offset register is added to the fixed_offset value
// to get the index into the root-array.
void LoadRootIndexed(Register destination,
Register variable_offset,
int fixed_offset);
void CompareRoot(Register with, Heap::RootListIndex index);
void CompareRoot(const Operand& with, Heap::RootListIndex index);
void PushRoot(Heap::RootListIndex index);
// These functions do not arrange the registers in any particular order so
// they are not useful for calls that can cause a GC. The caller can
// exclude up to 3 registers that do not need to be saved and restored.
void PushCallerSaved(SaveFPRegsMode fp_mode,
Register exclusion1 = no_reg,
Register exclusion2 = no_reg,
Register exclusion3 = no_reg);
void PopCallerSaved(SaveFPRegsMode fp_mode,
Register exclusion1 = no_reg,
Register exclusion2 = no_reg,
Register exclusion3 = no_reg);
// ---------------------------------------------------------------------------
// GC Support
enum RememberedSetFinalAction {
kReturnAtEnd,
kFallThroughAtEnd
};
// Record in the remembered set the fact that we have a pointer to new space
// at the address pointed to by the addr register. Only works if addr is not
// in new space.
void RememberedSetHelper(Register object, // Used for debug code.
Register addr,
Register scratch,
SaveFPRegsMode save_fp,
RememberedSetFinalAction and_then);
void CheckPageFlag(Register object,
Register scratch,
int mask,
Condition cc,
Label* condition_met,
Label::Distance condition_met_distance = Label::kFar);
// Check if object is in new space. Jumps if the object is not in new space.
// The register scratch can be object itself, but scratch will be clobbered.
void JumpIfNotInNewSpace(Register object,
Register scratch,
Label* branch,
Label::Distance distance = Label::kFar) {
InNewSpace(object, scratch, not_equal, branch, distance);
}
// Check if object is in new space. Jumps if the object is in new space.
// The register scratch can be object itself, but it will be clobbered.
void JumpIfInNewSpace(Register object,
Register scratch,
Label* branch,
Label::Distance distance = Label::kFar) {
InNewSpace(object, scratch, equal, branch, distance);
}
// Check if an object has the black incremental marking color. Also uses rcx!
void JumpIfBlack(Register object,
Register scratch0,
Register scratch1,
Label* on_black,
Label::Distance on_black_distance = Label::kFar);
// Detects conservatively whether an object is data-only, i.e. it does need to
// be scanned by the garbage collector.
void JumpIfDataObject(Register value,
Register scratch,
Label* not_data_object,
Label::Distance not_data_object_distance);
// Checks the color of an object. If the object is already grey or black
// then we just fall through, since it is already live. If it is white and
// we can determine that it doesn't need to be scanned, then we just mark it
// black and fall through. For the rest we jump to the label so the
// incremental marker can fix its assumptions.
void EnsureNotWhite(Register object,
Register scratch1,
Register scratch2,
Label* object_is_white_and_not_data,
Label::Distance distance);
// Notify the garbage collector that we wrote a pointer into an object.
// |object| is the object being stored into, |value| is the object being
// stored. value and scratch registers are clobbered by the operation.
// The offset is the offset from the start of the object, not the offset from
// the tagged HeapObject pointer. For use with FieldOperand(reg, off).
void RecordWriteField(
Register object,
int offset,
Register value,
Register scratch,
SaveFPRegsMode save_fp,
RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
SmiCheck smi_check = INLINE_SMI_CHECK);
// As above, but the offset has the tag presubtracted. For use with
// Operand(reg, off).
void RecordWriteContextSlot(
Register context,
int offset,
Register value,
Register scratch,
SaveFPRegsMode save_fp,
RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
SmiCheck smi_check = INLINE_SMI_CHECK) {
RecordWriteField(context,
offset + kHeapObjectTag,
value,
scratch,
save_fp,
remembered_set_action,
smi_check);
}
// Notify the garbage collector that we wrote a pointer into a fixed array.
// |array| is the array being stored into, |value| is the
// object being stored. |index| is the array index represented as a non-smi.
// All registers are clobbered by the operation RecordWriteArray
// filters out smis so it does not update the write barrier if the
// value is a smi.
void RecordWriteArray(
Register array,
Register value,
Register index,
SaveFPRegsMode save_fp,
RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
SmiCheck smi_check = INLINE_SMI_CHECK);
// For page containing |object| mark region covering |address|
// dirty. |object| is the object being stored into, |value| is the
// object being stored. The address and value registers are clobbered by the
// operation. RecordWrite filters out smis so it does not update
// the write barrier if the value is a smi.
void RecordWrite(
Register object,
Register address,
Register value,
SaveFPRegsMode save_fp,
RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
SmiCheck smi_check = INLINE_SMI_CHECK);
#ifdef ENABLE_DEBUGGER_SUPPORT
// ---------------------------------------------------------------------------
// Debugger Support
void DebugBreak();
#endif
// Enter specific kind of exit frame; either in normal or
// debug mode. Expects the number of arguments in register rax and
// sets up the number of arguments in register rdi and the pointer
// to the first argument in register rsi.
//
// Allocates arg_stack_space * kPointerSize memory (not GCed) on the stack
// accessible via StackSpaceOperand.
void EnterExitFrame(int arg_stack_space = 0, bool save_doubles = false);
// Enter specific kind of exit frame. Allocates arg_stack_space * kPointerSize
// memory (not GCed) on the stack accessible via StackSpaceOperand.
void EnterApiExitFrame(int arg_stack_space);
// Leave the current exit frame. Expects/provides the return value in
// register rax:rdx (untouched) and the pointer to the first
// argument in register rsi.
void LeaveExitFrame(bool save_doubles = false);
// Leave the current exit frame. Expects/provides the return value in
// register rax (untouched).
void LeaveApiExitFrame();
// Push and pop the registers that can hold pointers.
void PushSafepointRegisters() { Pushad(); }
void PopSafepointRegisters() { Popad(); }
// Store the value in register src in the safepoint register stack
// slot for register dst.
void StoreToSafepointRegisterSlot(Register dst, const Immediate& imm);
void StoreToSafepointRegisterSlot(Register dst, Register src);
void LoadFromSafepointRegisterSlot(Register dst, Register src);
void InitializeRootRegister() {
ExternalReference roots_array_start =
ExternalReference::roots_array_start(isolate());
movq(kRootRegister, roots_array_start);
addq(kRootRegister, Immediate(kRootRegisterBias));
}
// ---------------------------------------------------------------------------
// JavaScript invokes
// Set up call kind marking in rcx. The method takes rcx as an
// explicit first parameter to make the code more readable at the
// call sites.
void SetCallKind(Register dst, CallKind kind);
// Invoke the JavaScript function code by either calling or jumping.
void InvokeCode(Register code,
const ParameterCount& expected,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper,
CallKind call_kind);
void InvokeCode(Handle<Code> code,
const ParameterCount& expected,
const ParameterCount& actual,
RelocInfo::Mode rmode,
InvokeFlag flag,
const CallWrapper& call_wrapper,
CallKind call_kind);
// Invoke the JavaScript function in the given register. Changes the
// current context to the context in the function before invoking.
void InvokeFunction(Register function,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper,
CallKind call_kind);
void InvokeFunction(Handle<JSFunction> function,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper,
CallKind call_kind);
// Invoke specified builtin JavaScript function. Adds an entry to
// the unresolved list if the name does not resolve.
void InvokeBuiltin(Builtins::JavaScript id,
InvokeFlag flag,
const CallWrapper& call_wrapper = NullCallWrapper());
// Store the function for the given builtin in the target register.
void GetBuiltinFunction(Register target, Builtins::JavaScript id);
// Store the code object for the given builtin in the target register.
void GetBuiltinEntry(Register target, Builtins::JavaScript id);
// ---------------------------------------------------------------------------
// Smi tagging, untagging and operations on tagged smis.
void InitializeSmiConstantRegister() {
movq(kSmiConstantRegister,
reinterpret_cast<uint64_t>(Smi::FromInt(kSmiConstantRegisterValue)),
RelocInfo::NONE);
}
// Conversions between tagged smi values and non-tagged integer values.
// Tag an integer value. The result must be known to be a valid smi value.
// Only uses the low 32 bits of the src register. Sets the N and Z flags
// based on the value of the resulting smi.
void Integer32ToSmi(Register dst, Register src);
// Stores an integer32 value into a memory field that already holds a smi.
void Integer32ToSmiField(const Operand& dst, Register src);
// Adds constant to src and tags the result as a smi.
// Result must be a valid smi.
void Integer64PlusConstantToSmi(Register dst, Register src, int constant);
// Convert smi to 32-bit integer. I.e., not sign extended into
// high 32 bits of destination.
void SmiToInteger32(Register dst, Register src);
void SmiToInteger32(Register dst, const Operand& src);
// Convert smi to 64-bit integer (sign extended if necessary).
void SmiToInteger64(Register dst, Register src);
void SmiToInteger64(Register dst, const Operand& src);
// Multiply a positive smi's integer value by a power of two.
// Provides result as 64-bit integer value.
void PositiveSmiTimesPowerOfTwoToInteger64(Register dst,
Register src,
int power);
// Divide a positive smi's integer value by a power of two.
// Provides result as 32-bit integer value.
void PositiveSmiDivPowerOfTwoToInteger32(Register dst,
Register src,
int power);
// Perform the logical or of two smi values and return a smi value.
// If either argument is not a smi, jump to on_not_smis and retain
// the original values of source registers. The destination register
// may be changed if it's not one of the source registers.
void SmiOrIfSmis(Register dst,
Register src1,
Register src2,
Label* on_not_smis,
Label::Distance near_jump = Label::kFar);
// Simple comparison of smis. Both sides must be known smis to use these,
// otherwise use Cmp.
void SmiCompare(Register smi1, Register smi2);
void SmiCompare(Register dst, Smi* src);
void SmiCompare(Register dst, const Operand& src);
void SmiCompare(const Operand& dst, Register src);
void SmiCompare(const Operand& dst, Smi* src);
// Compare the int32 in src register to the value of the smi stored at dst.
void SmiCompareInteger32(const Operand& dst, Register src);
// Sets sign and zero flags depending on value of smi in register.
void SmiTest(Register src);
// Functions performing a check on a known or potential smi. Returns
// a condition that is satisfied if the check is successful.
// Is the value a tagged smi.
Condition CheckSmi(Register src);
Condition CheckSmi(const Operand& src);
// Is the value a non-negative tagged smi.
Condition CheckNonNegativeSmi(Register src);
// Are both values tagged smis.
Condition CheckBothSmi(Register first, Register second);
// Are both values non-negative tagged smis.
Condition CheckBothNonNegativeSmi(Register first, Register second);
// Are either value a tagged smi.
Condition CheckEitherSmi(Register first,
Register second,
Register scratch = kScratchRegister);
// Is the value the minimum smi value (since we are using
// two's complement numbers, negating the value is known to yield
// a non-smi value).
Condition CheckIsMinSmi(Register src);
// Checks whether an 32-bit integer value is a valid for conversion
// to a smi.
Condition CheckInteger32ValidSmiValue(Register src);
// Checks whether an 32-bit unsigned integer value is a valid for
// conversion to a smi.
Condition CheckUInteger32ValidSmiValue(Register src);
// Check whether src is a Smi, and set dst to zero if it is a smi,
// and to one if it isn't.
void CheckSmiToIndicator(Register dst, Register src);
void CheckSmiToIndicator(Register dst, const Operand& src);
// Test-and-jump functions. Typically combines a check function
// above with a conditional jump.
// Jump if the value cannot be represented by a smi.
void JumpIfNotValidSmiValue(Register src, Label* on_invalid,
Label::Distance near_jump = Label::kFar);
// Jump if the unsigned integer value cannot be represented by a smi.
void JumpIfUIntNotValidSmiValue(Register src, Label* on_invalid,
Label::Distance near_jump = Label::kFar);
// Jump to label if the value is a tagged smi.
void JumpIfSmi(Register src,
Label* on_smi,
Label::Distance near_jump = Label::kFar);
// Jump to label if the value is not a tagged smi.
void JumpIfNotSmi(Register src,
Label* on_not_smi,
Label::Distance near_jump = Label::kFar);
// Jump to label if the value is not a non-negative tagged smi.
void JumpUnlessNonNegativeSmi(Register src,
Label* on_not_smi,
Label::Distance near_jump = Label::kFar);
// Jump to label if the value, which must be a tagged smi, has value equal
// to the constant.
void JumpIfSmiEqualsConstant(Register src,
Smi* constant,
Label* on_equals,
Label::Distance near_jump = Label::kFar);
// Jump if either or both register are not smi values.
void JumpIfNotBothSmi(Register src1,
Register src2,
Label* on_not_both_smi,
Label::Distance near_jump = Label::kFar);
// Jump if either or both register are not non-negative smi values.
void JumpUnlessBothNonNegativeSmi(Register src1, Register src2,
Label* on_not_both_smi,
Label::Distance near_jump = Label::kFar);
// Operations on tagged smi values.
// Smis represent a subset of integers. The subset is always equivalent to
// a two's complement interpretation of a fixed number of bits.
// Optimistically adds an integer constant to a supposed smi.
// If the src is not a smi, or the result is not a smi, jump to
// the label.
void SmiTryAddConstant(Register dst,
Register src,
Smi* constant,
Label* on_not_smi_result,
Label::Distance near_jump = Label::kFar);
// Add an integer constant to a tagged smi, giving a tagged smi as result.
// No overflow testing on the result is done.
void SmiAddConstant(Register dst, Register src, Smi* constant);
// Add an integer constant to a tagged smi, giving a tagged smi as result.
// No overflow testing on the result is done.
void SmiAddConstant(const Operand& dst, Smi* constant);
// Add an integer constant to a tagged smi, giving a tagged smi as result,
// or jumping to a label if the result cannot be represented by a smi.
void SmiAddConstant(Register dst,
Register src,
Smi* constant,
Label* on_not_smi_result,
Label::Distance near_jump = Label::kFar);
// Subtract an integer constant from a tagged smi, giving a tagged smi as
// result. No testing on the result is done. Sets the N and Z flags
// based on the value of the resulting integer.
void SmiSubConstant(Register dst, Register src, Smi* constant);
// Subtract an integer constant from a tagged smi, giving a tagged smi as
// result, or jumping to a label if the result cannot be represented by a smi.
void SmiSubConstant(Register dst,
Register src,
Smi* constant,
Label* on_not_smi_result,
Label::Distance near_jump = Label::kFar);
// Negating a smi can give a negative zero or too large positive value.
// NOTICE: This operation jumps on success, not failure!
void SmiNeg(Register dst,
Register src,
Label* on_smi_result,
Label::Distance near_jump = Label::kFar);
// Adds smi values and return the result as a smi.
// If dst is src1, then src1 will be destroyed, even if
// the operation is unsuccessful.
void SmiAdd(Register dst,
Register src1,
Register src2,
Label* on_not_smi_result,
Label::Distance near_jump = Label::kFar);
void SmiAdd(Register dst,
Register src1,
const Operand& src2,
Label* on_not_smi_result,
Label::Distance near_jump = Label::kFar);
void SmiAdd(Register dst,
Register src1,
Register src2);
// Subtracts smi values and return the result as a smi.
// If dst is src1, then src1 will be destroyed, even if
// the operation is unsuccessful.
void SmiSub(Register dst,
Register src1,
Register src2,
Label* on_not_smi_result,
Label::Distance near_jump = Label::kFar);
void SmiSub(Register dst,
Register src1,
Register src2);
void SmiSub(Register dst,
Register src1,
const Operand& src2,
Label* on_not_smi_result,
Label::Distance near_jump = Label::kFar);
void SmiSub(Register dst,
Register src1,
const Operand& src2);
// Multiplies smi values and return the result as a smi,
// if possible.
// If dst is src1, then src1 will be destroyed, even if
// the operation is unsuccessful.
void SmiMul(Register dst,
Register src1,
Register src2,
Label* on_not_smi_result,
Label::Distance near_jump = Label::kFar);
// Divides one smi by another and returns the quotient.
// Clobbers rax and rdx registers.
void SmiDiv(Register dst,
Register src1,
Register src2,
Label* on_not_smi_result,
Label::Distance near_jump = Label::kFar);
// Divides one smi by another and returns the remainder.
// Clobbers rax and rdx registers.
void SmiMod(Register dst,
Register src1,
Register src2,
Label* on_not_smi_result,
Label::Distance near_jump = Label::kFar);
// Bitwise operations.
void SmiNot(Register dst, Register src);
void SmiAnd(Register dst, Register src1, Register src2);
void SmiOr(Register dst, Register src1, Register src2);
void SmiXor(Register dst, Register src1, Register src2);
void SmiAndConstant(Register dst, Register src1, Smi* constant);
void SmiOrConstant(Register dst, Register src1, Smi* constant);
void SmiXorConstant(Register dst, Register src1, Smi* constant);
void SmiShiftLeftConstant(Register dst,
Register src,
int shift_value);
void SmiShiftLogicalRightConstant(Register dst,
Register src,
int shift_value,
Label* on_not_smi_result,
Label::Distance near_jump = Label::kFar);
void SmiShiftArithmeticRightConstant(Register dst,
Register src,
int shift_value);
// Shifts a smi value to the left, and returns the result if that is a smi.
// Uses and clobbers rcx, so dst may not be rcx.
void SmiShiftLeft(Register dst,
Register src1,
Register src2);
// Shifts a smi value to the right, shifting in zero bits at the top, and
// returns the unsigned intepretation of the result if that is a smi.
// Uses and clobbers rcx, so dst may not be rcx.
void SmiShiftLogicalRight(Register dst,
Register src1,
Register src2,
Label* on_not_smi_result,
Label::Distance near_jump = Label::kFar);
// Shifts a smi value to the right, sign extending the top, and
// returns the signed intepretation of the result. That will always
// be a valid smi value, since it's numerically smaller than the
// original.
// Uses and clobbers rcx, so dst may not be rcx.
void SmiShiftArithmeticRight(Register dst,
Register src1,
Register src2);
// Specialized operations
// Select the non-smi register of two registers where exactly one is a
// smi. If neither are smis, jump to the failure label.
void SelectNonSmi(Register dst,
Register src1,
Register src2,
Label* on_not_smis,
Label::Distance near_jump = Label::kFar);
// Converts, if necessary, a smi to a combination of number and
// multiplier to be used as a scaled index.
// The src register contains a *positive* smi value. The shift is the
// power of two to multiply the index value by (e.g.
// to index by smi-value * kPointerSize, pass the smi and kPointerSizeLog2).
// The returned index register may be either src or dst, depending
// on what is most efficient. If src and dst are different registers,
// src is always unchanged.
SmiIndex SmiToIndex(Register dst, Register src, int shift);
// Converts a positive smi to a negative index.
SmiIndex SmiToNegativeIndex(Register dst, Register src, int shift);
// Add the value of a smi in memory to an int32 register.
// Sets flags as a normal add.
void AddSmiField(Register dst, const Operand& src);
// Basic Smi operations.
void Move(Register dst, Smi* source) {
LoadSmiConstant(dst, source);
}
void Move(const Operand& dst, Smi* source) {
Register constant = GetSmiConstant(source);
movq(dst, constant);
}
void Push(Smi* smi);
void Test(const Operand& dst, Smi* source);
// ---------------------------------------------------------------------------
// String macros.
// If object is a string, its map is loaded into object_map.
void JumpIfNotString(Register object,
Register object_map,
Label* not_string,
Label::Distance near_jump = Label::kFar);
void JumpIfNotBothSequentialAsciiStrings(
Register first_object,
Register second_object,
Register scratch1,
Register scratch2,
Label* on_not_both_flat_ascii,
Label::Distance near_jump = Label::kFar);
// Check whether the instance type represents a flat ASCII string. Jump to the
// label if not. If the instance type can be scratched specify same register
// for both instance type and scratch.
void JumpIfInstanceTypeIsNotSequentialAscii(
Register instance_type,
Register scratch,
Label*on_not_flat_ascii_string,
Label::Distance near_jump = Label::kFar);
void JumpIfBothInstanceTypesAreNotSequentialAscii(
Register first_object_instance_type,
Register second_object_instance_type,
Register scratch1,
Register scratch2,
Label* on_fail,
Label::Distance near_jump = Label::kFar);
// ---------------------------------------------------------------------------
// Macro instructions.
// Load a register with a long value as efficiently as possible.
void Set(Register dst, int64_t x);
void Set(const Operand& dst, int64_t x);
// Move if the registers are not identical.
void Move(Register target, Register source);
// Support for constant splitting.
bool IsUnsafeInt(const int x);
void SafeMove(Register dst, Smi* src);
void SafePush(Smi* src);
// Bit-field support.
void TestBit(const Operand& dst, int bit_index);
// Handle support
void Move(Register dst, Handle<Object> source);
void Move(const Operand& dst, Handle<Object> source);
void Cmp(Register dst, Handle<Object> source);
void Cmp(const Operand& dst, Handle<Object> source);
void Cmp(Register dst, Smi* src);
void Cmp(const Operand& dst, Smi* src);
void Push(Handle<Object> source);
// Load a heap object and handle the case of new-space objects by
// indirecting via a global cell.
void LoadHeapObject(Register result, Handle<HeapObject> object);
void PushHeapObject(Handle<HeapObject> object);
void LoadObject(Register result, Handle<Object> object) {
if (object->IsHeapObject()) {
LoadHeapObject(result, Handle<HeapObject>::cast(object));
} else {
Move(result, object);
}
}
// Load a global cell into a register.
void LoadGlobalCell(Register dst, Handle<JSGlobalPropertyCell> cell);
// Emit code to discard a non-negative number of pointer-sized elements
// from the stack, clobbering only the rsp register.
void Drop(int stack_elements);
void Call(Label* target) { call(target); }
// Control Flow
void Jump(Address destination, RelocInfo::Mode rmode);
void Jump(ExternalReference ext);
void Jump(Handle<Code> code_object, RelocInfo::Mode rmode);
void Call(Address destination, RelocInfo::Mode rmode);
void Call(ExternalReference ext);
void Call(Handle<Code> code_object,
RelocInfo::Mode rmode,
TypeFeedbackId ast_id = TypeFeedbackId::None());
// The size of the code generated for different call instructions.
int CallSize(Address destination, RelocInfo::Mode rmode) {
return kCallInstructionLength;
}
int CallSize(ExternalReference ext);
int CallSize(Handle<Code> code_object) {
// Code calls use 32-bit relative addressing.
return kShortCallInstructionLength;
}
int CallSize(Register target) {
// Opcode: REX_opt FF /2 m64
return (target.high_bit() != 0) ? 3 : 2;
}
int CallSize(const Operand& target) {
// Opcode: REX_opt FF /2 m64
return (target.requires_rex() ? 2 : 1) + target.operand_size();
}
// Emit call to the code we are currently generating.
void CallSelf() {
Handle<Code> self(reinterpret_cast<Code**>(CodeObject().location()));
Call(self, RelocInfo::CODE_TARGET);
}
// Non-x64 instructions.
// Push/pop all general purpose registers.
// Does not push rsp/rbp nor any of the assembler's special purpose registers
// (kScratchRegister, kSmiConstantRegister, kRootRegister).
void Pushad();
void Popad();
// Sets the stack as after performing Popad, without actually loading the
// registers.
void Dropad();
// Compare object type for heap object.
// Always use unsigned comparisons: above and below, not less and greater.
// Incoming register is heap_object and outgoing register is map.
// They may be the same register, and may be kScratchRegister.
void CmpObjectType(Register heap_object, InstanceType type, Register map);
// Compare instance type for map.
// Always use unsigned comparisons: above and below, not less and greater.
void CmpInstanceType(Register map, InstanceType type);
// Check if a map for a JSObject indicates that the object has fast elements.
// Jump to the specified label if it does not.
void CheckFastElements(Register map,
Label* fail,
Label::Distance distance = Label::kFar);
// Check if a map for a JSObject indicates that the object can have both smi
// and HeapObject elements. Jump to the specified label if it does not.
void CheckFastObjectElements(Register map,
Label* fail,
Label::Distance distance = Label::kFar);
// Check if a map for a JSObject indicates that the object has fast smi only
// elements. Jump to the specified label if it does not.
void CheckFastSmiElements(Register map,
Label* fail,
Label::Distance distance = Label::kFar);
// Check to see if maybe_number can be stored as a double in
// FastDoubleElements. If it can, store it at the index specified by index in
// the FastDoubleElements array elements, otherwise jump to fail. Note that
// index must not be smi-tagged.
void StoreNumberToDoubleElements(Register maybe_number,
Register elements,
Register index,
XMMRegister xmm_scratch,
Label* fail);
// Compare an object's map with the specified map and its transitioned
// elements maps if mode is ALLOW_ELEMENT_TRANSITION_MAPS. FLAGS are set with
// result of map compare. If multiple map compares are required, the compare
// sequences branches to early_success.
void CompareMap(Register obj,
Handle<Map> map,
Label* early_success,
CompareMapMode mode = REQUIRE_EXACT_MAP);
// Check if the map of an object is equal to a specified map and branch to
// label if not. Skip the smi check if not required (object is known to be a
// heap object). If mode is ALLOW_ELEMENT_TRANSITION_MAPS, then also match
// against maps that are ElementsKind transition maps of the specified map.
void CheckMap(Register obj,
Handle<Map> map,
Label* fail,
SmiCheckType smi_check_type,
CompareMapMode mode = REQUIRE_EXACT_MAP);
// Check if the map of an object is equal to a specified map and branch to a
// specified target if equal. Skip the smi check if not required (object is
// known to be a heap object)
void DispatchMap(Register obj,
Handle<Map> map,
Handle<Code> success,
SmiCheckType smi_check_type);
// Check if the object in register heap_object is a string. Afterwards the
// register map contains the object map and the register instance_type
// contains the instance_type. The registers map and instance_type can be the
// same in which case it contains the instance type afterwards. Either of the
// registers map and instance_type can be the same as heap_object.
Condition IsObjectStringType(Register heap_object,
Register map,
Register instance_type);
// FCmp compares and pops the two values on top of the FPU stack.
// The flag results are similar to integer cmp, but requires unsigned
// jcc instructions (je, ja, jae, jb, jbe, je, and jz).
void FCmp();
void ClampUint8(Register reg);
void ClampDoubleToUint8(XMMRegister input_reg,
XMMRegister temp_xmm_reg,
Register result_reg);
void LoadUint32(XMMRegister dst, Register src, XMMRegister scratch);
void LoadInstanceDescriptors(Register map, Register descriptors);
void EnumLength(Register dst, Register map);
void NumberOfOwnDescriptors(Register dst, Register map);
template<typename Field>
void DecodeField(Register reg) {
static const int shift = Field::kShift + kSmiShift;
static const int mask = Field::kMask >> Field::kShift;
shr(reg, Immediate(shift));
and_(reg, Immediate(mask));
shl(reg, Immediate(kSmiShift));
}
// Abort execution if argument is not a number, enabled via --debug-code.
void AssertNumber(Register object);
// Abort execution if argument is a smi, enabled via --debug-code.
void AssertNotSmi(Register object);
// Abort execution if argument is not a smi, enabled via --debug-code.
void AssertSmi(Register object);
void AssertSmi(const Operand& object);
// Abort execution if a 64 bit register containing a 32 bit payload does not
// have zeros in the top 32 bits, enabled via --debug-code.
void AssertZeroExtended(Register reg);
// Abort execution if argument is not a string, enabled via --debug-code.
void AssertString(Register object);
// Abort execution if argument is not the root value with the given index,
// enabled via --debug-code.
void AssertRootValue(Register src,
Heap::RootListIndex root_value_index,
const char* message);
// ---------------------------------------------------------------------------
// Exception handling
// Push a new try handler and link it into try handler chain.
void PushTryHandler(StackHandler::Kind kind, int handler_index);
// Unlink the stack handler on top of the stack from the try handler chain.
void PopTryHandler();
// Activate the top handler in the try hander chain and pass the
// thrown value.
void Throw(Register value);
// Propagate an uncatchable exception out of the current JS stack.
void ThrowUncatchable(Register value);
// ---------------------------------------------------------------------------
// Inline caching support
// Generate code for checking access rights - used for security checks
// on access to global objects across environments. The holder register
// is left untouched, but the scratch register and kScratchRegister,
// which must be different, are clobbered.
void CheckAccessGlobalProxy(Register holder_reg,
Register scratch,
Label* miss);
void GetNumberHash(Register r0, Register scratch);
void LoadFromNumberDictionary(Label* miss,
Register elements,
Register key,
Register r0,
Register r1,
Register r2,
Register result);
// ---------------------------------------------------------------------------
// Allocation support
// Allocate an object in new space. If the new space is exhausted control
// continues at the gc_required label. The allocated object is returned in
// result and end of the new object is returned in result_end. The register
// scratch can be passed as no_reg in which case an additional object
// reference will be added to the reloc info. The returned pointers in result
// and result_end have not yet been tagged as heap objects. If
// result_contains_top_on_entry is true the content of result is known to be
// the allocation top on entry (could be result_end from a previous call to
// AllocateInNewSpace). If result_contains_top_on_entry is true scratch
// should be no_reg as it is never used.
void AllocateInNewSpace(int object_size,
Register result,
Register result_end,
Register scratch,
Label* gc_required,
AllocationFlags flags);
void AllocateInNewSpace(int header_size,
ScaleFactor element_size,
Register element_count,
Register result,
Register result_end,
Register scratch,
Label* gc_required,
AllocationFlags flags);
void AllocateInNewSpace(Register object_size,
Register result,
Register result_end,
Register scratch,
Label* gc_required,
AllocationFlags flags);
// Undo allocation in new space. The object passed and objects allocated after
// it will no longer be allocated. Make sure that no pointers are left to the
// object(s) no longer allocated as they would be invalid when allocation is
// un-done.
void UndoAllocationInNewSpace(Register object);
// Allocate a heap number in new space with undefined value. Returns
// tagged pointer in result register, or jumps to gc_required if new
// space is full.
void AllocateHeapNumber(Register result,
Register scratch,
Label* gc_required);
// Allocate a sequential string. All the header fields of the string object
// are initialized.
void AllocateTwoByteString(Register result,
Register length,
Register scratch1,
Register scratch2,
Register scratch3,
Label* gc_required);
void AllocateAsciiString(Register result,
Register length,
Register scratch1,
Register scratch2,
Register scratch3,
Label* gc_required);
// Allocate a raw cons string object. Only the map field of the result is
// initialized.
void AllocateTwoByteConsString(Register result,
Register scratch1,
Register scratch2,
Label* gc_required);
void AllocateAsciiConsString(Register result,
Register scratch1,
Register scratch2,
Label* gc_required);
// Allocate a raw sliced string object. Only the map field of the result is
// initialized.
void AllocateTwoByteSlicedString(Register result,
Register scratch1,
Register scratch2,
Label* gc_required);
void AllocateAsciiSlicedString(Register result,
Register scratch1,
Register scratch2,
Label* gc_required);
// ---------------------------------------------------------------------------
// Support functions.
// Check if result is zero and op is negative.
void NegativeZeroTest(Register result, Register op, Label* then_label);
// Check if result is zero and op is negative in code using jump targets.
void NegativeZeroTest(CodeGenerator* cgen,
Register result,
Register op,
JumpTarget* then_target);
// Check if result is zero and any of op1 and op2 are negative.
// Register scratch is destroyed, and it must be different from op2.
void NegativeZeroTest(Register result, Register op1, Register op2,
Register scratch, Label* then_label);
// Try to get function prototype of a function and puts the value in
// the result register. Checks that the function really is a
// function and jumps to the miss label if the fast checks fail. The
// function register will be untouched; the other register may be
// clobbered.
void TryGetFunctionPrototype(Register function,
Register result,
Label* miss,
bool miss_on_bound_function = false);
// Generates code for reporting that an illegal operation has
// occurred.
void IllegalOperation(int num_arguments);
// Picks out an array index from the hash field.
// Register use:
// hash - holds the index's hash. Clobbered.
// index - holds the overwritten index on exit.
void IndexFromHash(Register hash, Register index);
// Find the function context up the context chain.
void LoadContext(Register dst, int context_chain_length);
// Conditionally load the cached Array transitioned map of type
// transitioned_kind from the native context if the map in register
// map_in_out is the cached Array map in the native context of
// expected_kind.
void LoadTransitionedArrayMapConditional(
ElementsKind expected_kind,
ElementsKind transitioned_kind,
Register map_in_out,
Register scratch,
Label* no_map_match);
// Load the initial map for new Arrays from a JSFunction.
void LoadInitialArrayMap(Register function_in,
Register scratch,
Register map_out,
bool can_have_holes);
// Load the global function with the given index.
void LoadGlobalFunction(int index, Register function);
// Load the initial map from the global function. The registers
// function and map can be the same.
void LoadGlobalFunctionInitialMap(Register function, Register map);
// ---------------------------------------------------------------------------
// Runtime calls
// Call a code stub.
void CallStub(CodeStub* stub, TypeFeedbackId ast_id = TypeFeedbackId::None());
// Tail call a code stub (jump).
void TailCallStub(CodeStub* stub);
// Return from a code stub after popping its arguments.
void StubReturn(int argc);
// Call a runtime routine.
void CallRuntime(const Runtime::Function* f, int num_arguments);
// Call a runtime function and save the value of XMM registers.
void CallRuntimeSaveDoubles(Runtime::FunctionId id);
// Convenience function: Same as above, but takes the fid instead.
void CallRuntime(Runtime::FunctionId id, int num_arguments);
// Convenience function: call an external reference.
void CallExternalReference(const ExternalReference& ext,
int num_arguments);
// Tail call of a runtime routine (jump).
// Like JumpToExternalReference, but also takes care of passing the number
// of parameters.
void TailCallExternalReference(const ExternalReference& ext,
int num_arguments,
int result_size);
// Convenience function: tail call a runtime routine (jump).
void TailCallRuntime(Runtime::FunctionId fid,
int num_arguments,
int result_size);
// Jump to a runtime routine.
void JumpToExternalReference(const ExternalReference& ext, int result_size);
// Prepares stack to put arguments (aligns and so on). WIN64 calling
// convention requires to put the pointer to the return value slot into
// rcx (rcx must be preserverd until CallApiFunctionAndReturn). Saves
// context (rsi). Clobbers rax. Allocates arg_stack_space * kPointerSize
// inside the exit frame (not GCed) accessible via StackSpaceOperand.
void PrepareCallApiFunction(int arg_stack_space);
// Calls an API function. Allocates HandleScope, extracts returned value
// from handle and propagates exceptions. Clobbers r14, r15, rbx and
// caller-save registers. Restores context. On return removes
// stack_space * kPointerSize (GCed).
void CallApiFunctionAndReturn(Address function_address, int stack_space);
// Before calling a C-function from generated code, align arguments on stack.
// After aligning the frame, arguments must be stored in esp[0], esp[4],
// etc., not pushed. The argument count assumes all arguments are word sized.
// The number of slots reserved for arguments depends on platform. On Windows
// stack slots are reserved for the arguments passed in registers. On other
// platforms stack slots are only reserved for the arguments actually passed
// on the stack.
void PrepareCallCFunction(int num_arguments);
// Calls a C function and cleans up the space for arguments allocated
// by PrepareCallCFunction. The called function is not allowed to trigger a
// garbage collection, since that might move the code and invalidate the
// return address (unless this is somehow accounted for by the called
// function).
void CallCFunction(ExternalReference function, int num_arguments);
void CallCFunction(Register function, int num_arguments);
// Calculate the number of stack slots to reserve for arguments when calling a
// C function.
int ArgumentStackSlotsForCFunctionCall(int num_arguments);
// ---------------------------------------------------------------------------
// Utilities
void Ret();
// Return and drop arguments from stack, where the number of arguments
// may be bigger than 2^16 - 1. Requires a scratch register.
void Ret(int bytes_dropped, Register scratch);
Handle<Object> CodeObject() {
ASSERT(!code_object_.is_null());
return code_object_;
}
// Copy length bytes from source to destination.
// Uses scratch register internally (if you have a low-eight register
// free, do use it, otherwise kScratchRegister will be used).
// The min_length is a minimum limit on the value that length will have.
// The algorithm has some special cases that might be omitted if the string
// is known to always be long.
void CopyBytes(Register destination,
Register source,
Register length,
int min_length = 0,
Register scratch = kScratchRegister);
// Initialize fields with filler values. Fields starting at |start_offset|
// not including end_offset are overwritten with the value in |filler|. At
// the end the loop, |start_offset| takes the value of |end_offset|.
void InitializeFieldsWithFiller(Register start_offset,
Register end_offset,
Register filler);
// ---------------------------------------------------------------------------
// StatsCounter support
void SetCounter(StatsCounter* counter, int value);
void IncrementCounter(StatsCounter* counter, int value);
void DecrementCounter(StatsCounter* counter, int value);
// ---------------------------------------------------------------------------
// Debugging
// Calls Abort(msg) if the condition cc is not satisfied.
// Use --debug_code to enable.
void Assert(Condition cc, const char* msg);
void AssertFastElements(Register elements);
// Like Assert(), but always enabled.
void Check(Condition cc, const char* msg);
// Print a message to stdout and abort execution.
void Abort(const char* msg);
// Check that the stack is aligned.
void CheckStackAlignment();
// Verify restrictions about code generated in stubs.
void set_generating_stub(bool value) { generating_stub_ = value; }
bool generating_stub() { return generating_stub_; }
void set_allow_stub_calls(bool value) { allow_stub_calls_ = value; }
bool allow_stub_calls() { return allow_stub_calls_; }
void set_has_frame(bool value) { has_frame_ = value; }
bool has_frame() { return has_frame_; }
inline bool AllowThisStubCall(CodeStub* stub);
static int SafepointRegisterStackIndex(Register reg) {
return SafepointRegisterStackIndex(reg.code());
}
// Activation support.
void EnterFrame(StackFrame::Type type);
void LeaveFrame(StackFrame::Type type);
// Expects object in rax and returns map with validated enum cache
// in rax. Assumes that any other register can be used as a scratch.
void CheckEnumCache(Register null_value,
Label* call_runtime);
private:
// Order general registers are pushed by Pushad.
// rax, rcx, rdx, rbx, rsi, rdi, r8, r9, r11, r14, r15.
static const int kSafepointPushRegisterIndices[Register::kNumRegisters];
static const int kNumSafepointSavedRegisters = 11;
static const int kSmiShift = kSmiTagSize + kSmiShiftSize;
bool generating_stub_;
bool allow_stub_calls_;
bool has_frame_;
bool root_array_available_;
// Returns a register holding the smi value. The register MUST NOT be
// modified. It may be the "smi 1 constant" register.
Register GetSmiConstant(Smi* value);
intptr_t RootRegisterDelta(ExternalReference other);
// Moves the smi value to the destination register.
void LoadSmiConstant(Register dst, Smi* value);
// This handle will be patched with the code object on installation.
Handle<Object> code_object_;
// Helper functions for generating invokes.
void InvokePrologue(const ParameterCount& expected,
const ParameterCount& actual,
Handle<Code> code_constant,
Register code_register,
Label* done,
bool* definitely_mismatches,
InvokeFlag flag,
Label::Distance near_jump = Label::kFar,
const CallWrapper& call_wrapper = NullCallWrapper(),
CallKind call_kind = CALL_AS_METHOD);
void EnterExitFramePrologue(bool save_rax);
// Allocates arg_stack_space * kPointerSize memory (not GCed) on the stack
// accessible via StackSpaceOperand.
void EnterExitFrameEpilogue(int arg_stack_space, bool save_doubles);
void LeaveExitFrameEpilogue();
// Allocation support helpers.
// Loads the top of new-space into the result register.
// Otherwise the address of the new-space top is loaded into scratch (if
// scratch is valid), and the new-space top is loaded into result.
void LoadAllocationTopHelper(Register result,
Register scratch,
AllocationFlags flags);
// Update allocation top with value in result_end register.
// If scratch is valid, it contains the address of the allocation top.
void UpdateAllocationTopHelper(Register result_end, Register scratch);
// Helper for PopHandleScope. Allowed to perform a GC and returns
// NULL if gc_allowed. Does not perform a GC if !gc_allowed, and
// possibly returns a failure object indicating an allocation failure.
Object* PopHandleScopeHelper(Register saved,
Register scratch,
bool gc_allowed);
// Helper for implementing JumpIfNotInNewSpace and JumpIfInNewSpace.
void InNewSpace(Register object,
Register scratch,
Condition cc,
Label* branch,
Label::Distance distance = Label::kFar);
// Helper for finding the mark bits for an address. Afterwards, the
// bitmap register points at the word with the mark bits and the mask
// the position of the first bit. Uses rcx as scratch and leaves addr_reg
// unchanged.
inline void GetMarkBits(Register addr_reg,
Register bitmap_reg,
Register mask_reg);
// Helper for throwing exceptions. Compute a handler address and jump to
// it. See the implementation for register usage.
void JumpToHandlerEntry();
// Compute memory operands for safepoint stack slots.
Operand SafepointRegisterSlot(Register reg);
static int SafepointRegisterStackIndex(int reg_code) {
return kNumSafepointRegisters - kSafepointPushRegisterIndices[reg_code] - 1;
}
// Needs access to SafepointRegisterStackIndex for optimized frame
// traversal.
friend class OptimizedFrame;
};
// The code patcher is used to patch (typically) small parts of code e.g. for
// debugging and other types of instrumentation. When using the code patcher
// the exact number of bytes specified must be emitted. Is not legal to emit
// relocation information. If any of these constraints are violated it causes
// an assertion.
class CodePatcher {
public:
CodePatcher(byte* address, int size);
virtual ~CodePatcher();
// Macro assembler to emit code.
MacroAssembler* masm() { return &masm_; }
private:
byte* address_; // The address of the code being patched.
int size_; // Number of bytes of the expected patch size.
MacroAssembler masm_; // Macro assembler used to generate the code.
};
// -----------------------------------------------------------------------------
// Static helper functions.
// Generate an Operand for loading a field from an object.
inline Operand FieldOperand(Register object, int offset) {
return Operand(object, offset - kHeapObjectTag);
}
// Generate an Operand for loading an indexed field from an object.
inline Operand FieldOperand(Register object,
Register index,
ScaleFactor scale,
int offset) {
return Operand(object, index, scale, offset - kHeapObjectTag);
}
inline Operand ContextOperand(Register context, int index) {
return Operand(context, Context::SlotOffset(index));
}
inline Operand GlobalObjectOperand() {
return ContextOperand(rsi, Context::GLOBAL_OBJECT_INDEX);
}
// Provides access to exit frame stack space (not GCed).
inline Operand StackSpaceOperand(int index) {
#ifdef _WIN64
const int kShaddowSpace = 4;
return Operand(rsp, (index + kShaddowSpace) * kPointerSize);
#else
return Operand(rsp, index * kPointerSize);
#endif
}
#ifdef GENERATED_CODE_COVERAGE
extern void LogGeneratedCodeCoverage(const char* file_line);
#define CODE_COVERAGE_STRINGIFY(x) #x
#define CODE_COVERAGE_TOSTRING(x) CODE_COVERAGE_STRINGIFY(x)
#define __FILE_LINE__ __FILE__ ":" CODE_COVERAGE_TOSTRING(__LINE__)
#define ACCESS_MASM(masm) { \
byte* x64_coverage_function = \
reinterpret_cast<byte*>(FUNCTION_ADDR(LogGeneratedCodeCoverage)); \
masm->pushfd(); \
masm->pushad(); \
masm->push(Immediate(reinterpret_cast<int>(&__FILE_LINE__))); \
masm->call(x64_coverage_function, RelocInfo::RUNTIME_ENTRY); \
masm->pop(rax); \
masm->popad(); \
masm->popfd(); \
} \
masm->
#else
#define ACCESS_MASM(masm) masm->
#endif
} } // namespace v8::internal
#endif // V8_X64_MACRO_ASSEMBLER_X64_H_
| [
"[email protected]"
] | |
03408a50eb70deb320e86c5e459824928521c9f7 | 384ed1770ef4fb26ceddd1f696f9bce645ec7203 | /main.build/module.youtube_dl.extractor.businessinsider.cpp | a7f4660dd9f84135f1a9cde5b11ae6acdbed8801 | [
"Apache-2.0"
] | permissive | omarASC5/Download-Spotify-Playlists | 0bdc4d5c27704b869d346bb57127da401bb354bd | b768ddba33f52902c9276105099514f18f5c3f77 | refs/heads/master | 2022-11-06T09:32:38.264819 | 2020-06-21T14:31:01 | 2020-06-21T14:31:01 | 272,309,286 | 1 | 1 | null | 2020-06-16T21:02:37 | 2020-06-15T00:47:16 | HTML | UTF-8 | C++ | false | false | 75,105 | cpp | /* Generated code for Python module 'youtube_dl.extractor.businessinsider'
* created by Nuitka version 0.6.8.4
*
* This code is in part copyright 2020 Kay Hayen.
*
* 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 "nuitka/prelude.h"
#include "__helpers.h"
/* The "_module_youtube_dl$extractor$businessinsider" is a Python object pointer of module type.
*
* Note: For full compatibility with CPython, every module variable access
* needs to go through it except for cases where the module cannot possibly
* have changed in the mean time.
*/
PyObject *module_youtube_dl$extractor$businessinsider;
PyDictObject *moduledict_youtube_dl$extractor$businessinsider;
/* The declarations of module constants used, if any. */
extern PyObject *const_str_plain___orig_bases__;
static PyObject *const_str_digest_4831b1d45bf5873beaa0094d7502eaeb;
extern PyObject *const_str_plain_ie_key;
extern PyObject *const_str_plain_JWPlatformIE;
extern PyObject *const_str_plain___module__;
extern PyObject *const_str_plain_metaclass;
extern PyObject *const_str_plain___spec__;
extern PyObject *const_str_plain_unicode_literals;
extern PyObject *const_str_plain___name__;
extern PyObject *const_str_plain___getitem__;
static PyObject *const_str_digest_c8985c4d192d41c7e538ab50903788e5;
static PyObject *const_str_digest_34bc335cb176b992e6cbe2f5573daf95;
extern PyObject *const_str_plain___qualname__;
extern PyObject *const_tuple_str_plain___class___tuple;
extern PyObject *const_int_pos_1;
extern PyObject *const_str_angle_metaclass;
extern PyObject *const_str_digest_e1ab2c9ed9b4938f1f2f0ea9f3a809c8;
extern PyObject *const_str_plain___file__;
extern PyObject *const_str_plain__real_extract;
extern PyObject *const_str_plain__VALID_URL;
extern PyObject *const_tuple_str_plain_InfoExtractor_tuple;
static PyObject *const_list_5dd61d6814029a7489bf46a5c81c450e_list;
extern PyObject *const_str_plain__download_webpage;
extern PyObject *const_str_plain__match_id;
extern PyObject *const_str_plain_jwplatform_id;
extern PyObject *const_int_0;
extern PyObject *const_str_plain_jwplatform;
extern PyObject *const_str_plain___prepare__;
extern PyObject *const_str_plain_url;
extern PyObject *const_str_plain__search_regex;
extern PyObject *const_str_plain_self;
extern PyObject *const_str_plain_webpage;
extern PyObject *const_str_plain_origin;
extern PyObject *const_str_digest_85b759fbb8edc914edcda2370c952d73;
static PyObject *const_tuple_fb4409485e5d1f53f6a5493035c4cad0_tuple;
extern PyObject *const_str_plain_InfoExtractor;
extern PyObject *const_str_plain_video_id;
static PyObject *const_str_digest_cbb95ca5b8cd8fcee724d4a35bd0bc66;
static PyObject *const_str_digest_4c1ecff67e12ee2d68a9d8038a709995;
extern PyObject *const_str_digest_75fd71b1edada749c2ef7ac810062295;
extern PyObject *const_tuple_empty;
extern PyObject *const_str_plain_has_location;
static PyObject *const_tuple_bc3e7099eb9677a0966cd50443933ed9_tuple;
extern PyObject *const_tuple_str_plain_JWPlatformIE_tuple;
static PyObject *const_str_digest_83e86c30d8229a73bc53e4ab6e78b4b3;
static PyObject *const_str_digest_47f09c4c538b66e9b3cbaf64b653cc18;
extern PyObject *const_str_plain_BusinessInsiderIE;
extern PyObject *const_str_plain__TESTS;
static PyObject *const_str_digest_93d2d6e61df72dc9f463636ae041cda4;
extern PyObject *const_str_plain_type;
extern PyObject *const_str_plain_ie;
extern PyObject *const_str_plain_common;
extern PyObject *const_str_plain___doc__;
extern PyObject *const_str_plain___cached__;
extern PyObject *const_str_plain___class__;
extern PyObject *const_str_plain_url_result;
static PyObject *const_str_digest_92adad2d8256f0796fa29460fb39f0a7;
static PyObject *module_filename_obj;
/* Indicator if this modules private constants were created yet. */
static bool constants_created = false;
/* Function to create module private constants. */
static void createModuleConstants(void) {
const_str_digest_4831b1d45bf5873beaa0094d7502eaeb = UNSTREAM_STRING_ASCII(&constant_bin[ 985985 ], 35, 0);
const_str_digest_c8985c4d192d41c7e538ab50903788e5 = UNSTREAM_STRING_ASCII(&constant_bin[ 986020 ], 36, 0);
const_str_digest_34bc335cb176b992e6cbe2f5573daf95 = UNSTREAM_STRING_ASCII(&constant_bin[ 986056 ], 114, 0);
const_list_5dd61d6814029a7489bf46a5c81c450e_list = PyMarshal_ReadObjectFromString((char *)&constant_bin[ 986170 ], 804);
const_tuple_fb4409485e5d1f53f6a5493035c4cad0_tuple = PyTuple_New(4);
PyTuple_SET_ITEM(const_tuple_fb4409485e5d1f53f6a5493035c4cad0_tuple, 0, const_str_digest_4831b1d45bf5873beaa0094d7502eaeb); Py_INCREF(const_str_digest_4831b1d45bf5873beaa0094d7502eaeb);
const_str_digest_83e86c30d8229a73bc53e4ab6e78b4b3 = UNSTREAM_STRING_ASCII(&constant_bin[ 986974 ], 33, 0);
PyTuple_SET_ITEM(const_tuple_fb4409485e5d1f53f6a5493035c4cad0_tuple, 1, const_str_digest_83e86c30d8229a73bc53e4ab6e78b4b3); Py_INCREF(const_str_digest_83e86c30d8229a73bc53e4ab6e78b4b3);
const_str_digest_cbb95ca5b8cd8fcee724d4a35bd0bc66 = UNSTREAM_STRING_ASCII(&constant_bin[ 987007 ], 37, 0);
PyTuple_SET_ITEM(const_tuple_fb4409485e5d1f53f6a5493035c4cad0_tuple, 2, const_str_digest_cbb95ca5b8cd8fcee724d4a35bd0bc66); Py_INCREF(const_str_digest_cbb95ca5b8cd8fcee724d4a35bd0bc66);
const_str_digest_92adad2d8256f0796fa29460fb39f0a7 = UNSTREAM_STRING_ASCII(&constant_bin[ 987044 ], 54, 0);
PyTuple_SET_ITEM(const_tuple_fb4409485e5d1f53f6a5493035c4cad0_tuple, 3, const_str_digest_92adad2d8256f0796fa29460fb39f0a7); Py_INCREF(const_str_digest_92adad2d8256f0796fa29460fb39f0a7);
const_str_digest_4c1ecff67e12ee2d68a9d8038a709995 = UNSTREAM_STRING_ASCII(&constant_bin[ 987098 ], 76, 0);
const_tuple_bc3e7099eb9677a0966cd50443933ed9_tuple = PyTuple_New(5);
PyTuple_SET_ITEM(const_tuple_bc3e7099eb9677a0966cd50443933ed9_tuple, 0, const_str_plain_self); Py_INCREF(const_str_plain_self);
PyTuple_SET_ITEM(const_tuple_bc3e7099eb9677a0966cd50443933ed9_tuple, 1, const_str_plain_url); Py_INCREF(const_str_plain_url);
PyTuple_SET_ITEM(const_tuple_bc3e7099eb9677a0966cd50443933ed9_tuple, 2, const_str_plain_video_id); Py_INCREF(const_str_plain_video_id);
PyTuple_SET_ITEM(const_tuple_bc3e7099eb9677a0966cd50443933ed9_tuple, 3, const_str_plain_webpage); Py_INCREF(const_str_plain_webpage);
PyTuple_SET_ITEM(const_tuple_bc3e7099eb9677a0966cd50443933ed9_tuple, 4, const_str_plain_jwplatform_id); Py_INCREF(const_str_plain_jwplatform_id);
const_str_digest_47f09c4c538b66e9b3cbaf64b653cc18 = UNSTREAM_STRING_ASCII(&constant_bin[ 987174 ], 45, 0);
const_str_digest_93d2d6e61df72dc9f463636ae041cda4 = UNSTREAM_STRING_ASCII(&constant_bin[ 987219 ], 31, 0);
constants_created = true;
}
/* Function to verify module private constants for non-corruption. */
#ifndef __NUITKA_NO_ASSERT__
void checkModuleConstants_youtube_dl$extractor$businessinsider(void) {
// The module may not have been used at all, then ignore this.
if (constants_created == false) return;
}
#endif
// The module code objects.
static PyCodeObject *codeobj_b8de415787a83ff4155615bc147a647f;
static PyCodeObject *codeobj_2605a617e5f40c6ac7a622d04361480a;
static PyCodeObject *codeobj_7c72f444b9a68a776f59300745a8634e;
static void createModuleCodeObjects(void) {
module_filename_obj = const_str_digest_34bc335cb176b992e6cbe2f5573daf95;
codeobj_b8de415787a83ff4155615bc147a647f = MAKE_CODEOBJECT(module_filename_obj, 1, CO_NOFREE | CO_FUTURE_UNICODE_LITERALS, const_str_digest_47f09c4c538b66e9b3cbaf64b653cc18, const_tuple_empty, 0, 0, 0);
codeobj_2605a617e5f40c6ac7a622d04361480a = MAKE_CODEOBJECT(module_filename_obj, 8, CO_NOFREE | CO_FUTURE_UNICODE_LITERALS, const_str_plain_BusinessInsiderIE, const_tuple_str_plain___class___tuple, 0, 0, 0);
codeobj_7c72f444b9a68a776f59300745a8634e = MAKE_CODEOBJECT(module_filename_obj, 37, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS, const_str_plain__real_extract, const_tuple_bc3e7099eb9677a0966cd50443933ed9_tuple, 2, 0, 0);
}
// The module function declarations.
NUITKA_CROSS_MODULE PyObject *impl___internal__$$$function_4__mro_entries_conversion(PyObject **python_pars);
static PyObject *MAKE_FUNCTION_youtube_dl$extractor$businessinsider$$$function_1__real_extract();
// The module function definitions.
static PyObject *impl_youtube_dl$extractor$businessinsider$$$function_1__real_extract(struct Nuitka_FunctionObject const *self, PyObject **python_pars) {
// Preserve error status for checks
#ifndef __NUITKA_NO_ASSERT__
NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED();
#endif
// Local variable declarations.
PyObject *par_self = python_pars[0];
PyObject *par_url = python_pars[1];
PyObject *var_video_id = NULL;
PyObject *var_webpage = NULL;
PyObject *var_jwplatform_id = NULL;
struct Nuitka_FrameObject *frame_7c72f444b9a68a776f59300745a8634e;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *tmp_return_value = NULL;
int tmp_res;
static struct Nuitka_FrameObject *cache_frame_7c72f444b9a68a776f59300745a8634e = NULL;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
// Actual function body.
// Tried code:
if (isFrameUnusable(cache_frame_7c72f444b9a68a776f59300745a8634e)) {
Py_XDECREF(cache_frame_7c72f444b9a68a776f59300745a8634e);
#if _DEBUG_REFCOUNTS
if (cache_frame_7c72f444b9a68a776f59300745a8634e == NULL) {
count_active_frame_cache_instances += 1;
} else {
count_released_frame_cache_instances += 1;
}
count_allocated_frame_cache_instances += 1;
#endif
cache_frame_7c72f444b9a68a776f59300745a8634e = MAKE_FUNCTION_FRAME(codeobj_7c72f444b9a68a776f59300745a8634e, module_youtube_dl$extractor$businessinsider, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *));
#if _DEBUG_REFCOUNTS
} else {
count_hit_frame_cache_instances += 1;
#endif
}
assert(cache_frame_7c72f444b9a68a776f59300745a8634e->m_type_description == NULL);
frame_7c72f444b9a68a776f59300745a8634e = cache_frame_7c72f444b9a68a776f59300745a8634e;
// Push the new frame as the currently active one.
pushFrameStack(frame_7c72f444b9a68a776f59300745a8634e);
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert(Py_REFCNT(frame_7c72f444b9a68a776f59300745a8634e) == 2); // Frame stack
// Framed code:
{
PyObject *tmp_assign_source_1;
PyObject *tmp_called_instance_1;
PyObject *tmp_args_element_name_1;
CHECK_OBJECT(par_self);
tmp_called_instance_1 = par_self;
CHECK_OBJECT(par_url);
tmp_args_element_name_1 = par_url;
frame_7c72f444b9a68a776f59300745a8634e->m_frame.f_lineno = 38;
{
PyObject *call_args[] = {tmp_args_element_name_1};
tmp_assign_source_1 = CALL_METHOD_WITH_ARGS1(tmp_called_instance_1, const_str_plain__match_id, call_args);
}
if (tmp_assign_source_1 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 38;
type_description_1 = "ooooo";
goto frame_exception_exit_1;
}
assert(var_video_id == NULL);
var_video_id = tmp_assign_source_1;
}
{
PyObject *tmp_assign_source_2;
PyObject *tmp_called_instance_2;
PyObject *tmp_args_element_name_2;
PyObject *tmp_args_element_name_3;
CHECK_OBJECT(par_self);
tmp_called_instance_2 = par_self;
CHECK_OBJECT(par_url);
tmp_args_element_name_2 = par_url;
CHECK_OBJECT(var_video_id);
tmp_args_element_name_3 = var_video_id;
frame_7c72f444b9a68a776f59300745a8634e->m_frame.f_lineno = 39;
{
PyObject *call_args[] = {tmp_args_element_name_2, tmp_args_element_name_3};
tmp_assign_source_2 = CALL_METHOD_WITH_ARGS2(tmp_called_instance_2, const_str_plain__download_webpage, call_args);
}
if (tmp_assign_source_2 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 39;
type_description_1 = "ooooo";
goto frame_exception_exit_1;
}
assert(var_webpage == NULL);
var_webpage = tmp_assign_source_2;
}
{
PyObject *tmp_assign_source_3;
PyObject *tmp_called_instance_3;
PyObject *tmp_args_element_name_4;
PyObject *tmp_args_element_name_5;
PyObject *tmp_args_element_name_6;
CHECK_OBJECT(par_self);
tmp_called_instance_3 = par_self;
tmp_args_element_name_4 = const_tuple_fb4409485e5d1f53f6a5493035c4cad0_tuple;
CHECK_OBJECT(var_webpage);
tmp_args_element_name_5 = var_webpage;
tmp_args_element_name_6 = const_str_digest_85b759fbb8edc914edcda2370c952d73;
frame_7c72f444b9a68a776f59300745a8634e->m_frame.f_lineno = 40;
{
PyObject *call_args[] = {tmp_args_element_name_4, tmp_args_element_name_5, tmp_args_element_name_6};
tmp_assign_source_3 = CALL_METHOD_WITH_ARGS3(tmp_called_instance_3, const_str_plain__search_regex, call_args);
}
if (tmp_assign_source_3 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 40;
type_description_1 = "ooooo";
goto frame_exception_exit_1;
}
assert(var_jwplatform_id == NULL);
var_jwplatform_id = tmp_assign_source_3;
}
{
PyObject *tmp_called_name_1;
PyObject *tmp_expression_name_1;
PyObject *tmp_args_name_1;
PyObject *tmp_tuple_element_1;
PyObject *tmp_left_name_1;
PyObject *tmp_right_name_1;
PyObject *tmp_kw_name_1;
PyObject *tmp_dict_key_1;
PyObject *tmp_dict_value_1;
PyObject *tmp_called_instance_4;
PyObject *tmp_mvar_value_1;
PyObject *tmp_dict_key_2;
PyObject *tmp_dict_value_2;
CHECK_OBJECT(par_self);
tmp_expression_name_1 = par_self;
tmp_called_name_1 = LOOKUP_ATTRIBUTE(tmp_expression_name_1, const_str_plain_url_result);
if (tmp_called_name_1 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 46;
type_description_1 = "ooooo";
goto frame_exception_exit_1;
}
tmp_left_name_1 = const_str_digest_e1ab2c9ed9b4938f1f2f0ea9f3a809c8;
CHECK_OBJECT(var_jwplatform_id);
tmp_right_name_1 = var_jwplatform_id;
tmp_tuple_element_1 = BINARY_OPERATION_MOD_OBJECT_UNICODE_OBJECT(tmp_left_name_1, tmp_right_name_1);
if (tmp_tuple_element_1 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
Py_DECREF(tmp_called_name_1);
exception_lineno = 47;
type_description_1 = "ooooo";
goto frame_exception_exit_1;
}
tmp_args_name_1 = PyTuple_New(1);
PyTuple_SET_ITEM(tmp_args_name_1, 0, tmp_tuple_element_1);
tmp_dict_key_1 = const_str_plain_ie;
tmp_mvar_value_1 = GET_STRING_DICT_VALUE(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain_JWPlatformIE);
if (unlikely(tmp_mvar_value_1 == NULL)) {
tmp_mvar_value_1 = GET_STRING_DICT_VALUE(dict_builtin, (Nuitka_StringObject *)const_str_plain_JWPlatformIE);
}
if (tmp_mvar_value_1 == NULL) {
Py_DECREF(tmp_called_name_1);
Py_DECREF(tmp_args_name_1);
exception_type = PyExc_NameError;
Py_INCREF(exception_type);
exception_value = UNSTREAM_STRING(&constant_bin[ 36809 ], 34, 0);
exception_tb = NULL;
NORMALIZE_EXCEPTION(&exception_type, &exception_value, &exception_tb);
CHAIN_EXCEPTION(exception_value);
exception_lineno = 47;
type_description_1 = "ooooo";
goto frame_exception_exit_1;
}
tmp_called_instance_4 = tmp_mvar_value_1;
frame_7c72f444b9a68a776f59300745a8634e->m_frame.f_lineno = 47;
tmp_dict_value_1 = CALL_METHOD_NO_ARGS(tmp_called_instance_4, const_str_plain_ie_key);
if (tmp_dict_value_1 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
Py_DECREF(tmp_called_name_1);
Py_DECREF(tmp_args_name_1);
exception_lineno = 47;
type_description_1 = "ooooo";
goto frame_exception_exit_1;
}
tmp_kw_name_1 = _PyDict_NewPresized( 2 );
tmp_res = PyDict_SetItem(tmp_kw_name_1, tmp_dict_key_1, tmp_dict_value_1);
Py_DECREF(tmp_dict_value_1);
assert(!(tmp_res != 0));
tmp_dict_key_2 = const_str_plain_video_id;
CHECK_OBJECT(var_video_id);
tmp_dict_value_2 = var_video_id;
tmp_res = PyDict_SetItem(tmp_kw_name_1, tmp_dict_key_2, tmp_dict_value_2);
assert(!(tmp_res != 0));
frame_7c72f444b9a68a776f59300745a8634e->m_frame.f_lineno = 46;
tmp_return_value = CALL_FUNCTION(tmp_called_name_1, tmp_args_name_1, tmp_kw_name_1);
Py_DECREF(tmp_called_name_1);
Py_DECREF(tmp_args_name_1);
Py_DECREF(tmp_kw_name_1);
if (tmp_return_value == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 46;
type_description_1 = "ooooo";
goto frame_exception_exit_1;
}
goto frame_return_exit_1;
}
#if 0
RESTORE_FRAME_EXCEPTION(frame_7c72f444b9a68a776f59300745a8634e);
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_return_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION(frame_7c72f444b9a68a776f59300745a8634e);
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION(frame_7c72f444b9a68a776f59300745a8634e);
#endif
if (exception_tb == NULL) {
exception_tb = MAKE_TRACEBACK(frame_7c72f444b9a68a776f59300745a8634e, exception_lineno);
} else if (exception_tb->tb_frame != &frame_7c72f444b9a68a776f59300745a8634e->m_frame) {
exception_tb = ADD_TRACEBACK(exception_tb, frame_7c72f444b9a68a776f59300745a8634e, exception_lineno);
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
frame_7c72f444b9a68a776f59300745a8634e,
type_description_1,
par_self,
par_url,
var_video_id,
var_webpage,
var_jwplatform_id
);
// Release cached frame.
if (frame_7c72f444b9a68a776f59300745a8634e == cache_frame_7c72f444b9a68a776f59300745a8634e) {
#if _DEBUG_REFCOUNTS
count_active_frame_cache_instances -= 1;
count_released_frame_cache_instances += 1;
#endif
Py_DECREF(frame_7c72f444b9a68a776f59300745a8634e);
}
cache_frame_7c72f444b9a68a776f59300745a8634e = NULL;
assertFrameObject(frame_7c72f444b9a68a776f59300745a8634e);
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
NUITKA_CANNOT_GET_HERE("tried codes exits in all cases");
return NULL;
// Return handler code:
try_return_handler_1:;
CHECK_OBJECT(var_video_id);
Py_DECREF(var_video_id);
var_video_id = NULL;
CHECK_OBJECT(var_webpage);
Py_DECREF(var_webpage);
var_webpage = NULL;
CHECK_OBJECT(var_jwplatform_id);
Py_DECREF(var_jwplatform_id);
var_jwplatform_id = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF(var_video_id);
var_video_id = NULL;
Py_XDECREF(var_webpage);
var_webpage = NULL;
Py_XDECREF(var_jwplatform_id);
var_jwplatform_id = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto function_exception_exit;
// End of try:
NUITKA_CANNOT_GET_HERE("Return statement must have exited already.");
return NULL;
function_exception_exit:
CHECK_OBJECT(par_self);
Py_DECREF(par_self);
CHECK_OBJECT(par_url);
Py_DECREF(par_url); assert(exception_type);
RESTORE_ERROR_OCCURRED(exception_type, exception_value, exception_tb);
return NULL;
function_return_exit:
// Function cleanup code if any.
CHECK_OBJECT(par_self);
Py_DECREF(par_self);
CHECK_OBJECT(par_url);
Py_DECREF(par_url);
// Actual function exit with return value, making sure we did not make
// the error status worse despite non-NULL return.
CHECK_OBJECT(tmp_return_value);
assert(had_error || !ERROR_OCCURRED());
return tmp_return_value;
}
static PyObject *MAKE_FUNCTION_youtube_dl$extractor$businessinsider$$$function_1__real_extract() {
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_youtube_dl$extractor$businessinsider$$$function_1__real_extract,
const_str_plain__real_extract,
#if PYTHON_VERSION >= 300
const_str_digest_93d2d6e61df72dc9f463636ae041cda4,
#endif
codeobj_7c72f444b9a68a776f59300745a8634e,
NULL,
#if PYTHON_VERSION >= 300
NULL,
NULL,
#endif
module_youtube_dl$extractor$businessinsider,
NULL,
0
);
return (PyObject *)result;
}
extern PyObject *const_str_plain___compiled__;
extern PyObject *const_str_plain___package__;
extern PyObject *const_str_empty;
#if PYTHON_VERSION >= 300
extern PyObject *const_str_dot;
extern PyObject *const_str_plain___loader__;
#endif
#if PYTHON_VERSION >= 340
extern PyObject *const_str_plain___spec__;
extern PyObject *const_str_plain__initializing;
extern PyObject *const_str_plain_submodule_search_locations;
#endif
extern void _initCompiledCellType();
extern void _initCompiledGeneratorType();
extern void _initCompiledFunctionType();
extern void _initCompiledMethodType();
extern void _initCompiledFrameType();
extern PyTypeObject Nuitka_Loader_Type;
#ifdef _NUITKA_PLUGIN_DILL_ENABLED
// Provide a way to create find a function via its C code and create it back
// in another process, useful for multiprocessing extensions like dill
function_impl_code functable_youtube_dl$extractor$businessinsider[] = {
impl_youtube_dl$extractor$businessinsider$$$function_1__real_extract,
NULL
};
static char const *_reduce_compiled_function_argnames[] = {
"func",
NULL
};
static PyObject *_reduce_compiled_function(PyObject *self, PyObject *args, PyObject *kwds) {
PyObject *func;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:reduce_compiled_function", (char **)_reduce_compiled_function_argnames, &func, NULL)) {
return NULL;
}
if (Nuitka_Function_Check(func) == false) {
SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_TypeError, "not a compiled function");
return NULL;
}
struct Nuitka_FunctionObject *function = (struct Nuitka_FunctionObject *)func;
function_impl_code *current = functable_youtube_dl$extractor$businessinsider;
int offset = 0;
while (*current != NULL) {
if (*current == function->m_c_code) {
break;
}
current += 1;
offset += 1;
}
if (*current == NULL) {
SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_TypeError, "Cannot find compiled function in module.");
return NULL;
}
PyObject *code_object_desc = PyTuple_New(6);
PyTuple_SET_ITEM0(code_object_desc, 0, function->m_code_object->co_filename);
PyTuple_SET_ITEM0(code_object_desc, 1, function->m_code_object->co_name);
PyTuple_SET_ITEM(code_object_desc, 2, PyLong_FromLong(function->m_code_object->co_firstlineno));
PyTuple_SET_ITEM0(code_object_desc, 3, function->m_code_object->co_varnames);
PyTuple_SET_ITEM(code_object_desc, 4, PyLong_FromLong(function->m_code_object->co_argcount));
PyTuple_SET_ITEM(code_object_desc, 5, PyLong_FromLong(function->m_code_object->co_flags));
CHECK_OBJECT_DEEP(code_object_desc);
PyObject *result = PyTuple_New(4);
PyTuple_SET_ITEM(result, 0, PyLong_FromLong(offset));
PyTuple_SET_ITEM(result, 1, code_object_desc);
PyTuple_SET_ITEM0(result, 2, function->m_defaults);
PyTuple_SET_ITEM0(result, 3, function->m_doc != NULL ? function->m_doc : Py_None);
CHECK_OBJECT_DEEP(result);
return result;
}
static PyMethodDef _method_def_reduce_compiled_function = {"reduce_compiled_function", (PyCFunction)_reduce_compiled_function,
METH_VARARGS | METH_KEYWORDS, NULL};
static char const *_create_compiled_function_argnames[] = {
"func",
"code_object_desc",
"defaults",
"doc",
NULL
};
static PyObject *_create_compiled_function(PyObject *self, PyObject *args, PyObject *kwds) {
CHECK_OBJECT_DEEP(args);
PyObject *func;
PyObject *code_object_desc;
PyObject *defaults;
PyObject *doc;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOO:create_compiled_function", (char **)_create_compiled_function_argnames, &func, &code_object_desc, &defaults, &doc, NULL)) {
return NULL;
}
int offset = PyLong_AsLong(func);
if (offset == -1 && ERROR_OCCURRED()) {
return NULL;
}
if (offset > sizeof(functable_youtube_dl$extractor$businessinsider) || offset < 0) {
SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_TypeError, "Wrong offset for compiled function.");
return NULL;
}
PyObject *filename = PyTuple_GET_ITEM(code_object_desc, 0);
PyObject *function_name = PyTuple_GET_ITEM(code_object_desc, 1);
PyObject *line = PyTuple_GET_ITEM(code_object_desc, 2);
int line_int = PyLong_AsLong(line);
assert(!ERROR_OCCURRED());
PyObject *argnames = PyTuple_GET_ITEM(code_object_desc, 3);
PyObject *arg_count = PyTuple_GET_ITEM(code_object_desc, 4);
int arg_count_int = PyLong_AsLong(arg_count);
assert(!ERROR_OCCURRED());
PyObject *flags = PyTuple_GET_ITEM(code_object_desc, 5);
int flags_int = PyLong_AsLong(flags);
assert(!ERROR_OCCURRED());
PyCodeObject *code_object = MAKE_CODEOBJECT(
filename,
line_int,
flags_int,
function_name,
argnames,
arg_count_int,
0, // TODO: Missing kw_only_count
0 // TODO: Missing pos_only_count
);
// TODO: More stuff needed for Python3, best to re-order arguments of MAKE_CODEOBJECT.
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
functable_youtube_dl$extractor$businessinsider[offset],
code_object->co_name,
#if PYTHON_VERSION >= 300
NULL, // TODO: Not transferring qualname yet
#endif
code_object,
defaults,
#if PYTHON_VERSION >= 300
NULL, // kwdefaults are done on the outside currently
NULL, // TODO: Not transferring annotations
#endif
module_youtube_dl$extractor$businessinsider,
doc,
0
);
return (PyObject *)result;
}
static PyMethodDef _method_def_create_compiled_function = {
"create_compiled_function",
(PyCFunction)_create_compiled_function,
METH_VARARGS | METH_KEYWORDS, NULL
};
#endif
// Internal entry point for module code.
PyObject *modulecode_youtube_dl$extractor$businessinsider(PyObject *module) {
module_youtube_dl$extractor$businessinsider = module;
#if defined(_NUITKA_EXE) || PYTHON_VERSION >= 300
static bool _init_done = false;
// Modules might be imported repeatedly, which is to be ignored.
if (_init_done) {
return module_youtube_dl$extractor$businessinsider;
} else {
_init_done = true;
}
#endif
#ifdef _NUITKA_MODULE
// In case of a stand alone extension module, need to call initialization
// the init here because that's the first and only time we are going to get
// called here.
// May have to activate constants blob.
#if defined(_NUITKA_CONSTANTS_FROM_RESOURCE)
loadConstantsResource();
#endif
// Initialize the constant values used.
_initBuiltinModule();
createGlobalConstants();
/* Initialize the compiled types of Nuitka. */
_initCompiledCellType();
_initCompiledGeneratorType();
_initCompiledFunctionType();
_initCompiledMethodType();
_initCompiledFrameType();
#if PYTHON_VERSION < 300
_initSlotCompare();
#endif
#if PYTHON_VERSION >= 270
_initSlotIternext();
#endif
patchBuiltinModule();
patchTypeComparison();
// Enable meta path based loader if not already done.
#ifdef _NUITKA_TRACE
PRINT_STRING("youtube_dl.extractor.businessinsider: Calling setupMetaPathBasedLoader().\n");
#endif
setupMetaPathBasedLoader();
#if PYTHON_VERSION >= 300
patchInspectModule();
#endif
#endif
/* The constants only used by this module are created now. */
#ifdef _NUITKA_TRACE
PRINT_STRING("youtube_dl.extractor.businessinsider: Calling createModuleConstants().\n");
#endif
createModuleConstants();
/* The code objects used by this module are created now. */
#ifdef _NUITKA_TRACE
PRINT_STRING("youtube_dl.extractor.businessinsider: Calling createModuleCodeObjects().\n");
#endif
createModuleCodeObjects();
// PRINT_STRING("in inityoutube_dl$extractor$businessinsider\n");
// Create the module object first. There are no methods initially, all are
// added dynamically in actual code only. Also no "__doc__" is initially
// set at this time, as it could not contain NUL characters this way, they
// are instead set in early module code. No "self" for modules, we have no
// use for it.
moduledict_youtube_dl$extractor$businessinsider = MODULE_DICT(module_youtube_dl$extractor$businessinsider);
#ifdef _NUITKA_PLUGIN_DILL_ENABLED
{
PyObject *function_tables = PyObject_GetAttrString((PyObject *)builtin_module, "compiled_function_tables");
if (function_tables == NULL)
{
DROP_ERROR_OCCURRED();
function_tables = PyDict_New();
}
PyObject_SetAttrString((PyObject *)builtin_module, "compiled_function_tables", function_tables);
PyObject *funcs = PyTuple_New(2);
PyTuple_SET_ITEM(funcs, 0, PyCFunction_New(&_method_def_reduce_compiled_function, NULL));
PyTuple_SET_ITEM(funcs, 1, PyCFunction_New(&_method_def_create_compiled_function, NULL));
PyDict_SetItemString(function_tables, module_full_name, funcs);
}
#endif
// Set "__compiled__" to what version information we have.
UPDATE_STRING_DICT0(
moduledict_youtube_dl$extractor$businessinsider,
(Nuitka_StringObject *)const_str_plain___compiled__,
Nuitka_dunder_compiled_value
);
// Update "__package__" value to what it ought to be.
{
#if 0
UPDATE_STRING_DICT0(
moduledict_youtube_dl$extractor$businessinsider,
(Nuitka_StringObject *)const_str_plain___package__,
const_str_empty
);
#elif 0
PyObject *module_name = GET_STRING_DICT_VALUE(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain___name__);
UPDATE_STRING_DICT0(
moduledict_youtube_dl$extractor$businessinsider,
(Nuitka_StringObject *)const_str_plain___package__,
module_name
);
#else
#if PYTHON_VERSION < 300
PyObject *module_name = GET_STRING_DICT_VALUE(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain___name__);
char const *module_name_cstr = PyString_AS_STRING(module_name);
char const *last_dot = strrchr(module_name_cstr, '.');
if (last_dot != NULL)
{
UPDATE_STRING_DICT1(
moduledict_youtube_dl$extractor$businessinsider,
(Nuitka_StringObject *)const_str_plain___package__,
PyString_FromStringAndSize(module_name_cstr, last_dot - module_name_cstr)
);
}
#else
PyObject *module_name = GET_STRING_DICT_VALUE(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain___name__);
Py_ssize_t dot_index = PyUnicode_Find(module_name, const_str_dot, 0, PyUnicode_GetLength(module_name), -1);
if (dot_index != -1)
{
UPDATE_STRING_DICT1(
moduledict_youtube_dl$extractor$businessinsider,
(Nuitka_StringObject *)const_str_plain___package__,
PyUnicode_Substring(module_name, 0, dot_index)
);
}
#endif
#endif
}
CHECK_OBJECT(module_youtube_dl$extractor$businessinsider);
// For deep importing of a module we need to have "__builtins__", so we set
// it ourselves in the same way than CPython does. Note: This must be done
// before the frame object is allocated, or else it may fail.
if (GET_STRING_DICT_VALUE(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain___builtins__) == NULL)
{
PyObject *value = (PyObject *)builtin_module;
// Check if main module, not a dict then but the module itself.
#if !defined(_NUITKA_EXE) || !0
value = PyModule_GetDict(value);
#endif
UPDATE_STRING_DICT0(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain___builtins__, value);
}
#if PYTHON_VERSION >= 300
UPDATE_STRING_DICT0(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain___loader__, (PyObject *)&Nuitka_Loader_Type);
#endif
#if PYTHON_VERSION >= 340
// Set the "__spec__" value
#if 0
// Main modules just get "None" as spec.
UPDATE_STRING_DICT0(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain___spec__, Py_None);
#else
// Other modules get a "ModuleSpec" from the standard mechanism.
{
PyObject *bootstrap_module = PyImport_ImportModule("importlib._bootstrap");
CHECK_OBJECT(bootstrap_module);
PyObject *module_spec_class = PyObject_GetAttrString(bootstrap_module, "ModuleSpec");
Py_DECREF(bootstrap_module);
PyObject *args[] = {
GET_STRING_DICT_VALUE(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain___name__),
(PyObject *)&Nuitka_Loader_Type
};
PyObject *spec_value = CALL_FUNCTION_WITH_ARGS2(
module_spec_class,
args
);
Py_DECREF(module_spec_class);
// We can assume this to never fail, or else we are in trouble anyway.
CHECK_OBJECT(spec_value);
// For packages set the submodule search locations as well, even if to empty
// list, so investigating code will consider it a package.
#if 0
SET_ATTRIBUTE(spec_value, const_str_plain_submodule_search_locations, PyList_New(0));
#endif
// Mark the execution in the "__spec__" value.
SET_ATTRIBUTE(spec_value, const_str_plain__initializing, Py_True);
UPDATE_STRING_DICT1(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain___spec__, spec_value);
}
#endif
#endif
// Temp variables if any
PyObject *outline_0_var___class__ = NULL;
PyObject *tmp_class_creation_1__bases = NULL;
PyObject *tmp_class_creation_1__bases_orig = NULL;
PyObject *tmp_class_creation_1__class_decl_dict = NULL;
PyObject *tmp_class_creation_1__metaclass = NULL;
PyObject *tmp_class_creation_1__prepared = NULL;
struct Nuitka_FrameObject *frame_b8de415787a83ff4155615bc147a647f;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
bool tmp_result;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
int tmp_res;
PyObject *tmp_dictdel_dict;
PyObject *tmp_dictdel_key;
PyObject *locals_youtube_dl$extractor$businessinsider_8 = NULL;
PyObject *tmp_dictset_value;
struct Nuitka_FrameObject *frame_2605a617e5f40c6ac7a622d04361480a_2;
NUITKA_MAY_BE_UNUSED char const *type_description_2 = NULL;
static struct Nuitka_FrameObject *cache_frame_2605a617e5f40c6ac7a622d04361480a_2 = NULL;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *exception_keeper_type_2;
PyObject *exception_keeper_value_2;
PyTracebackObject *exception_keeper_tb_2;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2;
PyObject *exception_keeper_type_3;
PyObject *exception_keeper_value_3;
PyTracebackObject *exception_keeper_tb_3;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3;
// Module code.
{
PyObject *tmp_assign_source_1;
tmp_assign_source_1 = Py_None;
UPDATE_STRING_DICT0(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain___doc__, tmp_assign_source_1);
}
{
PyObject *tmp_assign_source_2;
tmp_assign_source_2 = const_str_digest_34bc335cb176b992e6cbe2f5573daf95;
UPDATE_STRING_DICT0(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain___file__, tmp_assign_source_2);
}
// Frame without reuse.
frame_b8de415787a83ff4155615bc147a647f = MAKE_MODULE_FRAME(codeobj_b8de415787a83ff4155615bc147a647f, module_youtube_dl$extractor$businessinsider);
// Push the new frame as the currently active one, and we should be exclusively
// owning it.
pushFrameStack(frame_b8de415787a83ff4155615bc147a647f);
assert(Py_REFCNT(frame_b8de415787a83ff4155615bc147a647f) == 2);
// Framed code:
{
PyObject *tmp_assattr_name_1;
PyObject *tmp_assattr_target_1;
PyObject *tmp_mvar_value_1;
tmp_assattr_name_1 = const_str_digest_34bc335cb176b992e6cbe2f5573daf95;
tmp_mvar_value_1 = GET_STRING_DICT_VALUE(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain___spec__);
if (unlikely(tmp_mvar_value_1 == NULL)) {
tmp_mvar_value_1 = GET_STRING_DICT_VALUE(dict_builtin, (Nuitka_StringObject *)const_str_plain___spec__);
}
CHECK_OBJECT(tmp_mvar_value_1);
tmp_assattr_target_1 = tmp_mvar_value_1;
tmp_result = SET_ATTRIBUTE(tmp_assattr_target_1, const_str_plain_origin, tmp_assattr_name_1);
if (tmp_result == false) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 1;
goto frame_exception_exit_1;
}
}
{
PyObject *tmp_assattr_name_2;
PyObject *tmp_assattr_target_2;
PyObject *tmp_mvar_value_2;
tmp_assattr_name_2 = Py_True;
tmp_mvar_value_2 = GET_STRING_DICT_VALUE(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain___spec__);
if (unlikely(tmp_mvar_value_2 == NULL)) {
tmp_mvar_value_2 = GET_STRING_DICT_VALUE(dict_builtin, (Nuitka_StringObject *)const_str_plain___spec__);
}
CHECK_OBJECT(tmp_mvar_value_2);
tmp_assattr_target_2 = tmp_mvar_value_2;
tmp_result = SET_ATTRIBUTE(tmp_assattr_target_2, const_str_plain_has_location, tmp_assattr_name_2);
if (tmp_result == false) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 1;
goto frame_exception_exit_1;
}
}
{
PyObject *tmp_assign_source_3;
tmp_assign_source_3 = Py_None;
UPDATE_STRING_DICT0(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain___cached__, tmp_assign_source_3);
}
{
PyObject *tmp_assign_source_4;
PyObject *tmp_import_name_from_1;
frame_b8de415787a83ff4155615bc147a647f->m_frame.f_lineno = 2;
tmp_import_name_from_1 = PyImport_ImportModule("__future__");
assert(!(tmp_import_name_from_1 == NULL));
if (PyModule_Check(tmp_import_name_from_1)) {
tmp_assign_source_4 = IMPORT_NAME_OR_MODULE(
tmp_import_name_from_1,
(PyObject *)moduledict_youtube_dl$extractor$businessinsider,
const_str_plain_unicode_literals,
const_int_0
);
} else {
tmp_assign_source_4 = IMPORT_NAME(tmp_import_name_from_1, const_str_plain_unicode_literals);
}
if (tmp_assign_source_4 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 2;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain_unicode_literals, tmp_assign_source_4);
}
{
PyObject *tmp_assign_source_5;
PyObject *tmp_import_name_from_2;
PyObject *tmp_name_name_1;
PyObject *tmp_globals_name_1;
PyObject *tmp_locals_name_1;
PyObject *tmp_fromlist_name_1;
PyObject *tmp_level_name_1;
tmp_name_name_1 = const_str_plain_common;
tmp_globals_name_1 = (PyObject *)moduledict_youtube_dl$extractor$businessinsider;
tmp_locals_name_1 = Py_None;
tmp_fromlist_name_1 = const_tuple_str_plain_InfoExtractor_tuple;
tmp_level_name_1 = const_int_pos_1;
frame_b8de415787a83ff4155615bc147a647f->m_frame.f_lineno = 4;
tmp_import_name_from_2 = IMPORT_MODULE5(tmp_name_name_1, tmp_globals_name_1, tmp_locals_name_1, tmp_fromlist_name_1, tmp_level_name_1);
if (tmp_import_name_from_2 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 4;
goto frame_exception_exit_1;
}
if (PyModule_Check(tmp_import_name_from_2)) {
tmp_assign_source_5 = IMPORT_NAME_OR_MODULE(
tmp_import_name_from_2,
(PyObject *)moduledict_youtube_dl$extractor$businessinsider,
const_str_plain_InfoExtractor,
const_int_pos_1
);
} else {
tmp_assign_source_5 = IMPORT_NAME(tmp_import_name_from_2, const_str_plain_InfoExtractor);
}
Py_DECREF(tmp_import_name_from_2);
if (tmp_assign_source_5 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 4;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain_InfoExtractor, tmp_assign_source_5);
}
{
PyObject *tmp_assign_source_6;
PyObject *tmp_import_name_from_3;
PyObject *tmp_name_name_2;
PyObject *tmp_globals_name_2;
PyObject *tmp_locals_name_2;
PyObject *tmp_fromlist_name_2;
PyObject *tmp_level_name_2;
tmp_name_name_2 = const_str_plain_jwplatform;
tmp_globals_name_2 = (PyObject *)moduledict_youtube_dl$extractor$businessinsider;
tmp_locals_name_2 = Py_None;
tmp_fromlist_name_2 = const_tuple_str_plain_JWPlatformIE_tuple;
tmp_level_name_2 = const_int_pos_1;
frame_b8de415787a83ff4155615bc147a647f->m_frame.f_lineno = 5;
tmp_import_name_from_3 = IMPORT_MODULE5(tmp_name_name_2, tmp_globals_name_2, tmp_locals_name_2, tmp_fromlist_name_2, tmp_level_name_2);
if (tmp_import_name_from_3 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 5;
goto frame_exception_exit_1;
}
if (PyModule_Check(tmp_import_name_from_3)) {
tmp_assign_source_6 = IMPORT_NAME_OR_MODULE(
tmp_import_name_from_3,
(PyObject *)moduledict_youtube_dl$extractor$businessinsider,
const_str_plain_JWPlatformIE,
const_int_pos_1
);
} else {
tmp_assign_source_6 = IMPORT_NAME(tmp_import_name_from_3, const_str_plain_JWPlatformIE);
}
Py_DECREF(tmp_import_name_from_3);
if (tmp_assign_source_6 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 5;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain_JWPlatformIE, tmp_assign_source_6);
}
// Tried code:
{
PyObject *tmp_assign_source_7;
PyObject *tmp_tuple_element_1;
PyObject *tmp_mvar_value_3;
tmp_mvar_value_3 = GET_STRING_DICT_VALUE(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain_InfoExtractor);
if (unlikely(tmp_mvar_value_3 == NULL)) {
tmp_mvar_value_3 = GET_STRING_DICT_VALUE(dict_builtin, (Nuitka_StringObject *)const_str_plain_InfoExtractor);
}
if (tmp_mvar_value_3 == NULL) {
exception_type = PyExc_NameError;
Py_INCREF(exception_type);
exception_value = UNSTREAM_STRING(&constant_bin[ 33651 ], 35, 0);
exception_tb = NULL;
NORMALIZE_EXCEPTION(&exception_type, &exception_value, &exception_tb);
CHAIN_EXCEPTION(exception_value);
exception_lineno = 8;
goto try_except_handler_1;
}
tmp_tuple_element_1 = tmp_mvar_value_3;
tmp_assign_source_7 = PyTuple_New(1);
Py_INCREF(tmp_tuple_element_1);
PyTuple_SET_ITEM(tmp_assign_source_7, 0, tmp_tuple_element_1);
assert(tmp_class_creation_1__bases_orig == NULL);
tmp_class_creation_1__bases_orig = tmp_assign_source_7;
}
{
PyObject *tmp_assign_source_8;
PyObject *tmp_dircall_arg1_1;
CHECK_OBJECT(tmp_class_creation_1__bases_orig);
tmp_dircall_arg1_1 = tmp_class_creation_1__bases_orig;
Py_INCREF(tmp_dircall_arg1_1);
{
PyObject *dir_call_args[] = {tmp_dircall_arg1_1};
tmp_assign_source_8 = impl___internal__$$$function_4__mro_entries_conversion(dir_call_args);
}
if (tmp_assign_source_8 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_1;
}
assert(tmp_class_creation_1__bases == NULL);
tmp_class_creation_1__bases = tmp_assign_source_8;
}
{
PyObject *tmp_assign_source_9;
tmp_assign_source_9 = PyDict_New();
assert(tmp_class_creation_1__class_decl_dict == NULL);
tmp_class_creation_1__class_decl_dict = tmp_assign_source_9;
}
{
PyObject *tmp_assign_source_10;
PyObject *tmp_metaclass_name_1;
nuitka_bool tmp_condition_result_1;
PyObject *tmp_key_name_1;
PyObject *tmp_dict_name_1;
PyObject *tmp_dict_name_2;
PyObject *tmp_key_name_2;
nuitka_bool tmp_condition_result_2;
int tmp_truth_name_1;
PyObject *tmp_type_arg_1;
PyObject *tmp_expression_name_1;
PyObject *tmp_subscript_name_1;
PyObject *tmp_bases_name_1;
tmp_key_name_1 = const_str_plain_metaclass;
CHECK_OBJECT(tmp_class_creation_1__class_decl_dict);
tmp_dict_name_1 = tmp_class_creation_1__class_decl_dict;
tmp_res = PyDict_Contains(tmp_dict_name_1, tmp_key_name_1);
if (tmp_res == -1) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_1;
}
tmp_condition_result_1 = (tmp_res != 0) ? NUITKA_BOOL_TRUE : NUITKA_BOOL_FALSE;
if (tmp_condition_result_1 == NUITKA_BOOL_TRUE) {
goto condexpr_true_1;
} else {
goto condexpr_false_1;
}
condexpr_true_1:;
CHECK_OBJECT(tmp_class_creation_1__class_decl_dict);
tmp_dict_name_2 = tmp_class_creation_1__class_decl_dict;
tmp_key_name_2 = const_str_plain_metaclass;
tmp_metaclass_name_1 = DICT_GET_ITEM(tmp_dict_name_2, tmp_key_name_2);
if (tmp_metaclass_name_1 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_1;
}
goto condexpr_end_1;
condexpr_false_1:;
CHECK_OBJECT(tmp_class_creation_1__bases);
tmp_truth_name_1 = CHECK_IF_TRUE(tmp_class_creation_1__bases);
if (tmp_truth_name_1 == -1) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_1;
}
tmp_condition_result_2 = tmp_truth_name_1 == 1 ? NUITKA_BOOL_TRUE : NUITKA_BOOL_FALSE;
if (tmp_condition_result_2 == NUITKA_BOOL_TRUE) {
goto condexpr_true_2;
} else {
goto condexpr_false_2;
}
condexpr_true_2:;
CHECK_OBJECT(tmp_class_creation_1__bases);
tmp_expression_name_1 = tmp_class_creation_1__bases;
tmp_subscript_name_1 = const_int_0;
tmp_type_arg_1 = LOOKUP_SUBSCRIPT_CONST(tmp_expression_name_1, tmp_subscript_name_1, 0);
if (tmp_type_arg_1 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_1;
}
tmp_metaclass_name_1 = BUILTIN_TYPE1(tmp_type_arg_1);
Py_DECREF(tmp_type_arg_1);
if (tmp_metaclass_name_1 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_1;
}
goto condexpr_end_2;
condexpr_false_2:;
tmp_metaclass_name_1 = (PyObject *)&PyType_Type;
Py_INCREF(tmp_metaclass_name_1);
condexpr_end_2:;
condexpr_end_1:;
CHECK_OBJECT(tmp_class_creation_1__bases);
tmp_bases_name_1 = tmp_class_creation_1__bases;
tmp_assign_source_10 = SELECT_METACLASS(tmp_metaclass_name_1, tmp_bases_name_1);
Py_DECREF(tmp_metaclass_name_1);
if (tmp_assign_source_10 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_1;
}
assert(tmp_class_creation_1__metaclass == NULL);
tmp_class_creation_1__metaclass = tmp_assign_source_10;
}
{
nuitka_bool tmp_condition_result_3;
PyObject *tmp_key_name_3;
PyObject *tmp_dict_name_3;
tmp_key_name_3 = const_str_plain_metaclass;
CHECK_OBJECT(tmp_class_creation_1__class_decl_dict);
tmp_dict_name_3 = tmp_class_creation_1__class_decl_dict;
tmp_res = PyDict_Contains(tmp_dict_name_3, tmp_key_name_3);
if (tmp_res == -1) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_1;
}
tmp_condition_result_3 = (tmp_res != 0) ? NUITKA_BOOL_TRUE : NUITKA_BOOL_FALSE;
if (tmp_condition_result_3 == NUITKA_BOOL_TRUE) {
goto branch_yes_1;
} else {
goto branch_no_1;
}
}
branch_yes_1:;
CHECK_OBJECT(tmp_class_creation_1__class_decl_dict);
tmp_dictdel_dict = tmp_class_creation_1__class_decl_dict;
tmp_dictdel_key = const_str_plain_metaclass;
tmp_result = DICT_REMOVE_ITEM(tmp_dictdel_dict, tmp_dictdel_key);
if (tmp_result == false) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_1;
}
branch_no_1:;
{
nuitka_bool tmp_condition_result_4;
PyObject *tmp_expression_name_2;
CHECK_OBJECT(tmp_class_creation_1__metaclass);
tmp_expression_name_2 = tmp_class_creation_1__metaclass;
tmp_res = PyObject_HasAttr(tmp_expression_name_2, const_str_plain___prepare__);
tmp_condition_result_4 = (tmp_res != 0) ? NUITKA_BOOL_TRUE : NUITKA_BOOL_FALSE;
if (tmp_condition_result_4 == NUITKA_BOOL_TRUE) {
goto branch_yes_2;
} else {
goto branch_no_2;
}
}
branch_yes_2:;
{
PyObject *tmp_assign_source_11;
PyObject *tmp_called_name_1;
PyObject *tmp_expression_name_3;
PyObject *tmp_args_name_1;
PyObject *tmp_tuple_element_2;
PyObject *tmp_kw_name_1;
CHECK_OBJECT(tmp_class_creation_1__metaclass);
tmp_expression_name_3 = tmp_class_creation_1__metaclass;
tmp_called_name_1 = LOOKUP_ATTRIBUTE(tmp_expression_name_3, const_str_plain___prepare__);
if (tmp_called_name_1 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_1;
}
tmp_tuple_element_2 = const_str_plain_BusinessInsiderIE;
tmp_args_name_1 = PyTuple_New(2);
Py_INCREF(tmp_tuple_element_2);
PyTuple_SET_ITEM(tmp_args_name_1, 0, tmp_tuple_element_2);
CHECK_OBJECT(tmp_class_creation_1__bases);
tmp_tuple_element_2 = tmp_class_creation_1__bases;
Py_INCREF(tmp_tuple_element_2);
PyTuple_SET_ITEM(tmp_args_name_1, 1, tmp_tuple_element_2);
CHECK_OBJECT(tmp_class_creation_1__class_decl_dict);
tmp_kw_name_1 = tmp_class_creation_1__class_decl_dict;
frame_b8de415787a83ff4155615bc147a647f->m_frame.f_lineno = 8;
tmp_assign_source_11 = CALL_FUNCTION(tmp_called_name_1, tmp_args_name_1, tmp_kw_name_1);
Py_DECREF(tmp_called_name_1);
Py_DECREF(tmp_args_name_1);
if (tmp_assign_source_11 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_1;
}
assert(tmp_class_creation_1__prepared == NULL);
tmp_class_creation_1__prepared = tmp_assign_source_11;
}
{
nuitka_bool tmp_condition_result_5;
PyObject *tmp_operand_name_1;
PyObject *tmp_expression_name_4;
CHECK_OBJECT(tmp_class_creation_1__prepared);
tmp_expression_name_4 = tmp_class_creation_1__prepared;
tmp_res = PyObject_HasAttr(tmp_expression_name_4, const_str_plain___getitem__);
tmp_operand_name_1 = (tmp_res != 0) ? Py_True : Py_False;
tmp_res = CHECK_IF_TRUE(tmp_operand_name_1);
if (tmp_res == -1) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_1;
}
tmp_condition_result_5 = (tmp_res == 0) ? NUITKA_BOOL_TRUE : NUITKA_BOOL_FALSE;
if (tmp_condition_result_5 == NUITKA_BOOL_TRUE) {
goto branch_yes_3;
} else {
goto branch_no_3;
}
}
branch_yes_3:;
{
PyObject *tmp_raise_type_1;
PyObject *tmp_raise_value_1;
PyObject *tmp_left_name_1;
PyObject *tmp_right_name_1;
PyObject *tmp_tuple_element_3;
PyObject *tmp_getattr_target_1;
PyObject *tmp_getattr_attr_1;
PyObject *tmp_getattr_default_1;
PyObject *tmp_expression_name_5;
PyObject *tmp_type_arg_2;
tmp_raise_type_1 = PyExc_TypeError;
tmp_left_name_1 = const_str_digest_75fd71b1edada749c2ef7ac810062295;
CHECK_OBJECT(tmp_class_creation_1__metaclass);
tmp_getattr_target_1 = tmp_class_creation_1__metaclass;
tmp_getattr_attr_1 = const_str_plain___name__;
tmp_getattr_default_1 = const_str_angle_metaclass;
tmp_tuple_element_3 = BUILTIN_GETATTR(tmp_getattr_target_1, tmp_getattr_attr_1, tmp_getattr_default_1);
if (tmp_tuple_element_3 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_1;
}
tmp_right_name_1 = PyTuple_New(2);
PyTuple_SET_ITEM(tmp_right_name_1, 0, tmp_tuple_element_3);
CHECK_OBJECT(tmp_class_creation_1__prepared);
tmp_type_arg_2 = tmp_class_creation_1__prepared;
tmp_expression_name_5 = BUILTIN_TYPE1(tmp_type_arg_2);
assert(!(tmp_expression_name_5 == NULL));
tmp_tuple_element_3 = LOOKUP_ATTRIBUTE(tmp_expression_name_5, const_str_plain___name__);
Py_DECREF(tmp_expression_name_5);
if (tmp_tuple_element_3 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
Py_DECREF(tmp_right_name_1);
exception_lineno = 8;
goto try_except_handler_1;
}
PyTuple_SET_ITEM(tmp_right_name_1, 1, tmp_tuple_element_3);
tmp_raise_value_1 = BINARY_OPERATION_MOD_OBJECT_UNICODE_TUPLE(tmp_left_name_1, tmp_right_name_1);
Py_DECREF(tmp_right_name_1);
if (tmp_raise_value_1 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_1;
}
exception_type = tmp_raise_type_1;
Py_INCREF(tmp_raise_type_1);
exception_value = tmp_raise_value_1;
exception_lineno = 8;
RAISE_EXCEPTION_IMPLICIT(&exception_type, &exception_value, &exception_tb);
goto try_except_handler_1;
}
branch_no_3:;
goto branch_end_2;
branch_no_2:;
{
PyObject *tmp_assign_source_12;
tmp_assign_source_12 = PyDict_New();
assert(tmp_class_creation_1__prepared == NULL);
tmp_class_creation_1__prepared = tmp_assign_source_12;
}
branch_end_2:;
{
PyObject *tmp_assign_source_13;
{
PyObject *tmp_set_locals_1;
CHECK_OBJECT(tmp_class_creation_1__prepared);
tmp_set_locals_1 = tmp_class_creation_1__prepared;
locals_youtube_dl$extractor$businessinsider_8 = tmp_set_locals_1;
Py_INCREF(tmp_set_locals_1);
}
// Tried code:
// Tried code:
tmp_dictset_value = const_str_digest_c8985c4d192d41c7e538ab50903788e5;
tmp_res = PyObject_SetItem(locals_youtube_dl$extractor$businessinsider_8, const_str_plain___module__, tmp_dictset_value);
if (tmp_res != 0) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_3;
}
tmp_dictset_value = const_str_plain_BusinessInsiderIE;
tmp_res = PyObject_SetItem(locals_youtube_dl$extractor$businessinsider_8, const_str_plain___qualname__, tmp_dictset_value);
if (tmp_res != 0) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_3;
}
if (isFrameUnusable(cache_frame_2605a617e5f40c6ac7a622d04361480a_2)) {
Py_XDECREF(cache_frame_2605a617e5f40c6ac7a622d04361480a_2);
#if _DEBUG_REFCOUNTS
if (cache_frame_2605a617e5f40c6ac7a622d04361480a_2 == NULL) {
count_active_frame_cache_instances += 1;
} else {
count_released_frame_cache_instances += 1;
}
count_allocated_frame_cache_instances += 1;
#endif
cache_frame_2605a617e5f40c6ac7a622d04361480a_2 = MAKE_FUNCTION_FRAME(codeobj_2605a617e5f40c6ac7a622d04361480a, module_youtube_dl$extractor$businessinsider, sizeof(void *));
#if _DEBUG_REFCOUNTS
} else {
count_hit_frame_cache_instances += 1;
#endif
}
assert(cache_frame_2605a617e5f40c6ac7a622d04361480a_2->m_type_description == NULL);
frame_2605a617e5f40c6ac7a622d04361480a_2 = cache_frame_2605a617e5f40c6ac7a622d04361480a_2;
// Push the new frame as the currently active one.
pushFrameStack(frame_2605a617e5f40c6ac7a622d04361480a_2);
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert(Py_REFCNT(frame_2605a617e5f40c6ac7a622d04361480a_2) == 2); // Frame stack
// Framed code:
tmp_dictset_value = const_str_digest_4c1ecff67e12ee2d68a9d8038a709995;
tmp_res = PyObject_SetItem(locals_youtube_dl$extractor$businessinsider_8, const_str_plain__VALID_URL, tmp_dictset_value);
if (tmp_res != 0) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 9;
type_description_2 = "o";
goto frame_exception_exit_2;
}
tmp_dictset_value = DEEP_COPY(const_list_5dd61d6814029a7489bf46a5c81c450e_list);
tmp_res = PyObject_SetItem(locals_youtube_dl$extractor$businessinsider_8, const_str_plain__TESTS, tmp_dictset_value);
Py_DECREF(tmp_dictset_value);
if (tmp_res != 0) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 10;
type_description_2 = "o";
goto frame_exception_exit_2;
}
tmp_dictset_value = MAKE_FUNCTION_youtube_dl$extractor$businessinsider$$$function_1__real_extract();
tmp_res = PyObject_SetItem(locals_youtube_dl$extractor$businessinsider_8, const_str_plain__real_extract, tmp_dictset_value);
Py_DECREF(tmp_dictset_value);
if (tmp_res != 0) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 37;
type_description_2 = "o";
goto frame_exception_exit_2;
}
#if 0
RESTORE_FRAME_EXCEPTION(frame_2605a617e5f40c6ac7a622d04361480a_2);
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_exception_exit_2:;
#if 0
RESTORE_FRAME_EXCEPTION(frame_2605a617e5f40c6ac7a622d04361480a_2);
#endif
if (exception_tb == NULL) {
exception_tb = MAKE_TRACEBACK(frame_2605a617e5f40c6ac7a622d04361480a_2, exception_lineno);
} else if (exception_tb->tb_frame != &frame_2605a617e5f40c6ac7a622d04361480a_2->m_frame) {
exception_tb = ADD_TRACEBACK(exception_tb, frame_2605a617e5f40c6ac7a622d04361480a_2, exception_lineno);
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
frame_2605a617e5f40c6ac7a622d04361480a_2,
type_description_2,
outline_0_var___class__
);
// Release cached frame.
if (frame_2605a617e5f40c6ac7a622d04361480a_2 == cache_frame_2605a617e5f40c6ac7a622d04361480a_2) {
#if _DEBUG_REFCOUNTS
count_active_frame_cache_instances -= 1;
count_released_frame_cache_instances += 1;
#endif
Py_DECREF(frame_2605a617e5f40c6ac7a622d04361480a_2);
}
cache_frame_2605a617e5f40c6ac7a622d04361480a_2 = NULL;
assertFrameObject(frame_2605a617e5f40c6ac7a622d04361480a_2);
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto nested_frame_exit_1;
frame_no_exception_1:;
goto skip_nested_handling_1;
nested_frame_exit_1:;
goto try_except_handler_3;
skip_nested_handling_1:;
{
nuitka_bool tmp_condition_result_6;
PyObject *tmp_compexpr_left_1;
PyObject *tmp_compexpr_right_1;
CHECK_OBJECT(tmp_class_creation_1__bases);
tmp_compexpr_left_1 = tmp_class_creation_1__bases;
CHECK_OBJECT(tmp_class_creation_1__bases_orig);
tmp_compexpr_right_1 = tmp_class_creation_1__bases_orig;
tmp_condition_result_6 = RICH_COMPARE_NE_NBOOL_OBJECT_TUPLE(tmp_compexpr_left_1, tmp_compexpr_right_1);
if (tmp_condition_result_6 == NUITKA_BOOL_EXCEPTION) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_3;
}
if (tmp_condition_result_6 == NUITKA_BOOL_TRUE) {
goto branch_yes_4;
} else {
goto branch_no_4;
}
}
branch_yes_4:;
CHECK_OBJECT(tmp_class_creation_1__bases_orig);
tmp_dictset_value = tmp_class_creation_1__bases_orig;
tmp_res = PyObject_SetItem(locals_youtube_dl$extractor$businessinsider_8, const_str_plain___orig_bases__, tmp_dictset_value);
if (tmp_res != 0) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_3;
}
branch_no_4:;
{
PyObject *tmp_assign_source_14;
PyObject *tmp_called_name_2;
PyObject *tmp_args_name_2;
PyObject *tmp_tuple_element_4;
PyObject *tmp_kw_name_2;
CHECK_OBJECT(tmp_class_creation_1__metaclass);
tmp_called_name_2 = tmp_class_creation_1__metaclass;
tmp_tuple_element_4 = const_str_plain_BusinessInsiderIE;
tmp_args_name_2 = PyTuple_New(3);
Py_INCREF(tmp_tuple_element_4);
PyTuple_SET_ITEM(tmp_args_name_2, 0, tmp_tuple_element_4);
CHECK_OBJECT(tmp_class_creation_1__bases);
tmp_tuple_element_4 = tmp_class_creation_1__bases;
Py_INCREF(tmp_tuple_element_4);
PyTuple_SET_ITEM(tmp_args_name_2, 1, tmp_tuple_element_4);
tmp_tuple_element_4 = locals_youtube_dl$extractor$businessinsider_8;
Py_INCREF(tmp_tuple_element_4);
PyTuple_SET_ITEM(tmp_args_name_2, 2, tmp_tuple_element_4);
CHECK_OBJECT(tmp_class_creation_1__class_decl_dict);
tmp_kw_name_2 = tmp_class_creation_1__class_decl_dict;
frame_b8de415787a83ff4155615bc147a647f->m_frame.f_lineno = 8;
tmp_assign_source_14 = CALL_FUNCTION(tmp_called_name_2, tmp_args_name_2, tmp_kw_name_2);
Py_DECREF(tmp_args_name_2);
if (tmp_assign_source_14 == NULL) {
assert(ERROR_OCCURRED());
FETCH_ERROR_OCCURRED(&exception_type, &exception_value, &exception_tb);
exception_lineno = 8;
goto try_except_handler_3;
}
assert(outline_0_var___class__ == NULL);
outline_0_var___class__ = tmp_assign_source_14;
}
CHECK_OBJECT(outline_0_var___class__);
tmp_assign_source_13 = outline_0_var___class__;
Py_INCREF(tmp_assign_source_13);
goto try_return_handler_3;
NUITKA_CANNOT_GET_HERE("tried codes exits in all cases");
return NULL;
// Return handler code:
try_return_handler_3:;
Py_DECREF(locals_youtube_dl$extractor$businessinsider_8);
locals_youtube_dl$extractor$businessinsider_8 = NULL;
goto try_return_handler_2;
// Exception handler code:
try_except_handler_3:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_DECREF(locals_youtube_dl$extractor$businessinsider_8);
locals_youtube_dl$extractor$businessinsider_8 = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto try_except_handler_2;
// End of try:
NUITKA_CANNOT_GET_HERE("tried codes exits in all cases");
return NULL;
// Return handler code:
try_return_handler_2:;
CHECK_OBJECT(outline_0_var___class__);
Py_DECREF(outline_0_var___class__);
outline_0_var___class__ = NULL;
goto outline_result_1;
// Exception handler code:
try_except_handler_2:;
exception_keeper_type_2 = exception_type;
exception_keeper_value_2 = exception_value;
exception_keeper_tb_2 = exception_tb;
exception_keeper_lineno_2 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
// Re-raise.
exception_type = exception_keeper_type_2;
exception_value = exception_keeper_value_2;
exception_tb = exception_keeper_tb_2;
exception_lineno = exception_keeper_lineno_2;
goto outline_exception_1;
// End of try:
NUITKA_CANNOT_GET_HERE("Return statement must have exited already.");
return NULL;
outline_exception_1:;
exception_lineno = 8;
goto try_except_handler_1;
outline_result_1:;
UPDATE_STRING_DICT1(moduledict_youtube_dl$extractor$businessinsider, (Nuitka_StringObject *)const_str_plain_BusinessInsiderIE, tmp_assign_source_13);
}
goto try_end_1;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_3 = exception_type;
exception_keeper_value_3 = exception_value;
exception_keeper_tb_3 = exception_tb;
exception_keeper_lineno_3 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF(tmp_class_creation_1__bases_orig);
tmp_class_creation_1__bases_orig = NULL;
Py_XDECREF(tmp_class_creation_1__bases);
tmp_class_creation_1__bases = NULL;
Py_XDECREF(tmp_class_creation_1__class_decl_dict);
tmp_class_creation_1__class_decl_dict = NULL;
Py_XDECREF(tmp_class_creation_1__metaclass);
tmp_class_creation_1__metaclass = NULL;
Py_XDECREF(tmp_class_creation_1__prepared);
tmp_class_creation_1__prepared = NULL;
// Re-raise.
exception_type = exception_keeper_type_3;
exception_value = exception_keeper_value_3;
exception_tb = exception_keeper_tb_3;
exception_lineno = exception_keeper_lineno_3;
goto frame_exception_exit_1;
// End of try:
try_end_1:;
// Restore frame exception if necessary.
#if 0
RESTORE_FRAME_EXCEPTION(frame_b8de415787a83ff4155615bc147a647f);
#endif
popFrameStack();
assertFrameObject(frame_b8de415787a83ff4155615bc147a647f);
goto frame_no_exception_2;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION(frame_b8de415787a83ff4155615bc147a647f);
#endif
if (exception_tb == NULL) {
exception_tb = MAKE_TRACEBACK(frame_b8de415787a83ff4155615bc147a647f, exception_lineno);
} else if (exception_tb->tb_frame != &frame_b8de415787a83ff4155615bc147a647f->m_frame) {
exception_tb = ADD_TRACEBACK(exception_tb, frame_b8de415787a83ff4155615bc147a647f, exception_lineno);
}
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto module_exception_exit;
frame_no_exception_2:;
CHECK_OBJECT(tmp_class_creation_1__bases_orig);
Py_DECREF(tmp_class_creation_1__bases_orig);
tmp_class_creation_1__bases_orig = NULL;
CHECK_OBJECT(tmp_class_creation_1__bases);
Py_DECREF(tmp_class_creation_1__bases);
tmp_class_creation_1__bases = NULL;
CHECK_OBJECT(tmp_class_creation_1__class_decl_dict);
Py_DECREF(tmp_class_creation_1__class_decl_dict);
tmp_class_creation_1__class_decl_dict = NULL;
CHECK_OBJECT(tmp_class_creation_1__metaclass);
Py_DECREF(tmp_class_creation_1__metaclass);
tmp_class_creation_1__metaclass = NULL;
CHECK_OBJECT(tmp_class_creation_1__prepared);
Py_DECREF(tmp_class_creation_1__prepared);
tmp_class_creation_1__prepared = NULL;
return module_youtube_dl$extractor$businessinsider;
module_exception_exit:
RESTORE_ERROR_OCCURRED(exception_type, exception_value, exception_tb);
return NULL;
}
| [
"[email protected]"
] | |
fc0081293384f206c6b3865d07d8e89a9aad35a0 | a7764174fb0351ea666faa9f3b5dfe304390a011 | /drv/MeshVS/MeshVS_DataMapOfIntegerTwoColors_0.cxx | e6986346f4ca79e3fbe2a81a4ee61e90127b4006 | [] | no_license | uel-dataexchange/Opencascade_uel | f7123943e9d8124f4fa67579e3cd3f85cfe52d91 | 06ec93d238d3e3ea2881ff44ba8c21cf870435cd | refs/heads/master | 2022-11-16T07:40:30.837854 | 2020-07-08T01:56:37 | 2020-07-08T01:56:37 | 276,290,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,801 | cxx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#include <MeshVS_DataMapOfIntegerTwoColors.hxx>
#ifndef _Standard_DomainError_HeaderFile
#include <Standard_DomainError.hxx>
#endif
#ifndef _Standard_NoSuchObject_HeaderFile
#include <Standard_NoSuchObject.hxx>
#endif
#ifndef _TColStd_MapIntegerHasher_HeaderFile
#include <TColStd_MapIntegerHasher.hxx>
#endif
#ifndef _MeshVS_DataMapNodeOfDataMapOfIntegerTwoColors_HeaderFile
#include <MeshVS_DataMapNodeOfDataMapOfIntegerTwoColors.hxx>
#endif
#ifndef _MeshVS_DataMapIteratorOfDataMapOfIntegerTwoColors_HeaderFile
#include <MeshVS_DataMapIteratorOfDataMapOfIntegerTwoColors.hxx>
#endif
#define TheKey Standard_Integer
#define TheKey_hxx <Standard_Integer.hxx>
#define TheItem MeshVS_TwoColors
#define TheItem_hxx <MeshVS_TwoColors.hxx>
#define Hasher TColStd_MapIntegerHasher
#define Hasher_hxx <TColStd_MapIntegerHasher.hxx>
#define TCollection_DataMapNode MeshVS_DataMapNodeOfDataMapOfIntegerTwoColors
#define TCollection_DataMapNode_hxx <MeshVS_DataMapNodeOfDataMapOfIntegerTwoColors.hxx>
#define TCollection_DataMapIterator MeshVS_DataMapIteratorOfDataMapOfIntegerTwoColors
#define TCollection_DataMapIterator_hxx <MeshVS_DataMapIteratorOfDataMapOfIntegerTwoColors.hxx>
#define Handle_TCollection_DataMapNode Handle_MeshVS_DataMapNodeOfDataMapOfIntegerTwoColors
#define TCollection_DataMapNode_Type_() MeshVS_DataMapNodeOfDataMapOfIntegerTwoColors_Type_()
#define TCollection_DataMap MeshVS_DataMapOfIntegerTwoColors
#define TCollection_DataMap_hxx <MeshVS_DataMapOfIntegerTwoColors.hxx>
#include <TCollection_DataMap.gxx>
| [
"[email protected]"
] | |
f4ab5e2e11ce160321fdeab49db773211f9002b2 | 62aef460f1b5eaa8d42eee3ddffd7426c3d36219 | /SharpEffect/Classes/shader_practice/LayerShaderPractice02.h | 0b0f48b46be8bc992573c838d2d64493e5f73866 | [
"MIT"
] | permissive | CanFengHome/Cocos2dXEffect | 2f942a674cdd0345373c17e226f633012edcc137 | 1a24ae9e638858946cc1c52bce60a5e956ccd9cf | refs/heads/master | 2020-12-24T07:36:21.865618 | 2016-08-09T03:49:27 | 2016-08-09T03:49:27 | 54,361,653 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 472 | h | //
// LayerShaderPractice02.h
// SharpEffect
//
// Created by ccf on 16/3/28.
//
//
#ifndef LayerShaderPractice02_h
#define LayerShaderPractice02_h
#include "cocos2d.h"
// 02 灯光光晕效果 Blend使用 参考资料:http://blog.csdn.net/yang3wei/article/details/7795764
class LayerShaderPractice02 : public cocos2d::LayerColor
{
public:
CREATE_FUNC(LayerShaderPractice02);
private:
virtual bool init() override;
};
#endif /* LayerShaderPractice02_h */
| [
"[email protected]"
] | |
5f80882dd199d1dd017f1ccfb9e2c8401fba3795 | ebf623d1c37d9180fdf502961a0b87244593ca16 | /telldusapi.h | 4ae233ad4f536546857f42ee126cccc639320604 | [] | no_license | geirwanvik/AutomationServerV2 | 75963588509b1184dc2e1b6a5a8563e93232e388 | 6086cb8fe3ce1b86dd589bcbb7f0a9806128179c | refs/heads/master | 2021-01-23T17:31:19.788222 | 2015-03-31T19:02:16 | 2015-03-31T19:02:16 | 33,203,111 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,647 | h | #ifndef TELLDUSAPI_H
#define TELLDUSAPI_H
#include <QObject>
#include <QtSql>
#include "telldus-core.h"
#include "singleton.h"
#include "common.h"
class TelldusApi : public QObject
{
Q_OBJECT
public:
explicit TelldusApi(QObject *parent = 0);
~TelldusApi();
void init();
int registerNewDevice(QString name, QString protocol, QString model, QString house, QString unit);
void getDeviceData(const int id, int &supportedCommands, int &lastCommand, int &lastValue);
signals:
void deviceEvent(int eventId, int eventCommand, int eventValue, QString deviceType);
void rawEvent(QString msg);
void logEvent(QString msg);
private slots:
public slots:
void deviceCommand(int id, int command, int value);
private:
void errorCode(int id, int code);
void removePreviousConfig();
void removeDevice(int id);
static void WINAPI rawDataEventCallback(const char *data, int controllerId, int, void *);
static void WINAPI controllerEventCallback(int controllerId, int changeEvent, int changeType, const char *newValue, int callbackId, void *);
static void WINAPI sensorEventCallback(const char *protocol, const char *model, int sensorId, int dataType, const char *value, int, int, void *);
static void WINAPI deviceEventCallback(int deviceId, int method, const char *data, int, void *);
static void WINAPI deviceChangeEventCallback(int deviceId, int changeEvent, int changeType, int, void *);
int rawDataEventId, sensorEventId, deviceEventId, deviceChangedEventId, controllerEventId;
};
//Global variable
typedef Singleton<TelldusApi> TelldusApiSingleton;
#endif // TELLDUSAPI_H
| [
"[email protected]"
] | |
387c39e92c08d373407860c7f22e11fee6416dc2 | 15c36c4bd77099b4359bc7cb81ee2f64550b43c6 | /sgu/460.plural-form-of-nouns/460.cpp | 80aad633ff8629cd5ed54af846a074a0e40bcd09 | [
"MIT"
] | permissive | KayvanMazaheri/acm | f969640ba0b7054bd6af6f0685715d7e37292f8e | aeb05074bc9b9c92f35b6a741183da09a08af85d | refs/heads/master | 2021-03-22T03:30:17.115202 | 2017-12-12T08:16:08 | 2017-12-12T08:16:08 | 48,699,733 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 652 | cpp | #include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
cin >> n ;
string word[10];
int i = 0;
for(; i < n; i ++)
{
cin >> word[i];
int s = word[i].size() - 1 ;
if ((word[i][s]=='o')||(word[i][s]=='s')||(word[i][s]=='x')||((word[i][s]=='h')&&(word[i][s-1]=='c')))
word[i]+="es";
else if (word[i][s]=='f')
word[i] = word[i].substr(0,s) + "ves" ;
else if ((word[i][s]=='e')&&(word[i][s-1]=='f'))
word[i] = word[i].substr(0,s-1) + "ves" ;
else if (word[i][s]=='y')
word[i] = word[i].substr(0,s) + "ies" ;
else
word[i] += 's';
}
for (int c=0; c<i; c++)
cout << word[c] << endl ;
return 0;
}
| [
"[email protected]"
] | |
d9f72abc327bd99e21c5049f06b72f336ae59163 | 69cf9c7f6596feadacdbf3d1e7964be79f4f2b1e | /Endian.cxx | 882f6ea2056ebb29c80ca1f0e4bd115995e01de8 | [] | no_license | liheyuan/keepasscxx | 4519efb9e69da92e1d8ed336b0eb9df38ead812e | fd9846cf71428d61bd63acdf3265b8dd78cf50fd | refs/heads/master | 2021-01-10T08:42:52.181269 | 2016-02-17T04:46:38 | 2016-02-17T04:46:38 | 50,974,514 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 429 | cxx | #include "Endian.h"
uint16_t Endian::convToLittle(uint16_t val) {
if(isBigEndianness()) {
val = changeEndianness(val);
}
return val;
}
uint32_t Endian::convToLittle(uint32_t val) {
if(isBigEndianness()) {
val = changeEndianness(val);
}
return val;
}
uint32_t Endian::convToLittle(uint64_t val) {
if(isBigEndianness()) {
val = changeEndianness(val);
}
return val;
}
| [
"[email protected]"
] | |
dbc07f539f4647bc7b5e0e96833602548d50d658 | 1d4dd176e05d883ebfe59c21806da9f53e043c1e | /dearchivedialog.h | ba7053b4fda517bc5d09294e6231c6200b4cee9f | [] | no_license | Subtselnyi/Archiver | afec48d4c606c2ead7e7ca0c3457c63ca0a3b2af | 9feaa614f9b48c7b484af0c786e523cdcc50da77 | refs/heads/master | 2021-01-13T03:36:53.067507 | 2016-12-27T03:15:57 | 2016-12-27T03:15:57 | 77,283,815 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 705 | h | #ifndef DEARCHIVEDIALOG_H
#define DEARCHIVEDIALOG_H
#pragma once
#include <QDialog>
#include <vector>
#include "SParch.h"
#include <string>
#include <sstream>
namespace Ui {
class DeArchiveDialog;
}
class DeArchiveDialog : public QDialog
{
Q_OBJECT
public:
explicit DeArchiveDialog(string,QWidget *parent = 0);
~DeArchiveDialog();
string file="";
double compress;
signals:
void FilePathDeArchive(const QString &atr);
private slots:
void on_DeArchiveSearchButton_clicked();
void on_DeArchiveOkButton_clicked();
void on_DeArchiveCancelButton_clicked();
private:
Ui::DeArchiveDialog *ui;
};
#endif // DEARCHIVEDIALOG_H
| [
"[email protected]"
] | |
aee3d53907a566f047ca192364631b3027ca3d25 | 55884f952212babe5e926a488cb0d2f1c4475a51 | /src/Websock.cpp | f154c52221409d8dd86bebaf11f07cbc5338eaa1 | [] | no_license | anhydrous99/qTrader | b51d0c827dc8d25d8c79f64e2cbcdaa05fdbb4f6 | 8e72121fd525cd5c76547bb1cd09e8120e16ee5e | refs/heads/master | 2021-03-27T17:04:01.176138 | 2021-02-25T01:12:47 | 2021-02-25T01:12:47 | 106,638,549 | 1 | 0 | null | 2021-02-19T14:24:33 | 2017-10-12T03:13:21 | C++ | UTF-8 | C++ | false | false | 5,702 | cpp | #include "Websock.h"
#include <mutex>
#include <algorithm>
#include <string>
#include <utility>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
using namespace rapidjson;
Websock::Websock(std::vector<std::string> channels, std::string product_id, std::string uri) {
Channels = std::move(channels);
Product_id = std::move(product_id);
Uri = std::move(uri);
Connect();
}
Websock::~Websock() {
std::string unsub = subscribe(false);
send_message(unsub);
client.close().wait();
}
void Websock::send_message(const std::string &to_send) {
web::websockets::client::websocket_outgoing_message out_msg;
out_msg.set_utf8_message(to_send);
client.send(out_msg).wait();
}
void Websock::message_handler(const web::websockets::client::websocket_incoming_message &msg) {
std::string input = msg.extract_string().get();
Document d;
d.Parse(input.c_str());
assert(d.HasMember("type"));
assert(d["type"].IsString());
std::string type = d["type"].GetString();
if (type == "snapshot") {
const Value &bids = d["bids"];
const Value &asks = d["asks"];
assert(bids.IsArray());
assert(asks.IsArray());
//std::scoped_lock<std::mutex, std::mutex> lock{buy_mut, sell_mut};
std::lock_guard<std::mutex> buy_lock(buy_mut);
std::lock_guard<std::mutex> sell_lock(sell_mut);
buy_prices.reserve(bids.Size());
sell_prices.reserve(asks.Size());
for (SizeType i = 0; i < bids.Size(); i++) {
assert(bids[i].IsArray());
assert(bids[i][0].IsString());
buy_prices.push_back(std::stod(bids[i][0].GetString()));
}
for (SizeType i = 0; i < asks.Size(); i++) {
assert(asks[i].IsArray());
assert(asks[i][0].IsString());
sell_prices.push_back(std::stod(asks[i][0].GetString()));
}
} else if (type == "l2update") {
const Value &changes = d["changes"];
assert(changes.IsArray());
//std::scoped_lock lock{buy_mut, sell_mut};
std::lock_guard<std::mutex> buy_lock(buy_mut);
std::lock_guard<std::mutex> sell_lock(sell_mut);
for (SizeType i = 0; i < changes.Size(); i++) {
assert(changes[i].IsArray());
assert(changes[i][0].IsString());
assert(changes[i][1].IsString());
double price = std::stod(changes[i][1].GetString());
std::string side = changes[i][0].GetString();
if (side == "buy") {
assert(changes[i][2].IsString());
if (0 == std::stod(changes[i][2].GetString()))
buy_prices.erase(std::remove(buy_prices.begin(), buy_prices.end(), price), buy_prices.end());
else
buy_prices.push_back(price);
} else {
assert(changes[i][2].IsString());
if (0 == std::stod(changes[i][2].GetString()))
sell_prices.erase(std::remove(sell_prices.begin(), sell_prices.end(), price), sell_prices.end());
else
sell_prices.push_back(price);
}
}
}
}
double Websock::Best_Buy_Price() {
std::lock_guard<std::mutex> lock(buy_mut);
auto biggest = std::max_element(std::begin(buy_prices), std::end(buy_prices));
return *biggest;
}
double Websock::Best_Sell_Price() {
std::lock_guard<std::mutex> lock(sell_mut);
auto smallest = std::min_element(std::begin(sell_prices), std::end(sell_prices));
return *smallest;
}
double Websock::MidMarket_Price() {
return (Best_Buy_Price() + Best_Sell_Price()) / 2;
}
inline std::string Websock::subscribe(bool sub) {
Document d;
d.SetObject();
rapidjson::Document::AllocatorType &allocator = d.GetAllocator();
if (sub)
d.AddMember("type", "subscribe", allocator);
else
d.AddMember("type", "unsubscribe", allocator);
Value product_ids(kArrayType);
product_ids.PushBack(Value().SetString(StringRef(Product_id.c_str())), allocator);
d.AddMember("product_ids", product_ids, allocator);
Value channels(kArrayType);
for (std::string &channel : Channels)
channels.PushBack(Value().SetString(StringRef(channel.c_str())), allocator);
d.AddMember("channels", channels, allocator);
/* create string with rapidjson */
StringBuffer strbuf;
Writer<StringBuffer> writer(strbuf);
d.Accept(writer);
return strbuf.GetString();
}
void Websock::Connect() {
client.set_message_handler(
[this](const web::websockets::client::websocket_incoming_message& msg) { message_handler(msg); });
#ifdef _WIN32
client.connect(web::uri(utility::conversions::to_string_t(Uri))).wait();
#else
client.connect(Uri).wait();
#endif
std::string sub = subscribe(true);
send_message(sub);
}
void Websock::Connect(std::vector<std::string> channels, std::string product_id, std::string uri) {
Channels = std::move(channels);
Product_id = std::move(product_id);
Uri = std::move(uri);
Connect();
}
void Websock::Disconnect() {
std::string unsub = subscribe(false);
send_message(unsub);
client.close().wait();
}
void Websock::Set_Channels(std::vector<std::string> channels) { Channels = std::move(channels); }
void Websock::Set_Product_id(std::string product_id) { Product_id = std::move(product_id); }
void Websock::Set_Uri(std::string uri) { Uri = std::move(uri); }
void Websock::Set_Data(std::vector<std::string> channels, std::string product_id, std::string uri) {
Channels = std::move(channels);
Product_id = std::move(product_id);
Uri = std::move(uri);
}
| [
"[email protected]"
] | |
75266bc3c07035d25487cd45a3daa10020ebe088 | ef507d37ea67ec09f1170ad0c764fd25c5cbe4ae | /894A.cpp | 08d25d8ee7a0cf485b6d11b2e0dc7c64817c0f04 | [] | no_license | saurabh3240/codeforces | 61292b8e8c77cf257c968169a711592aa1ca9a44 | 27cf189a22c3f4f91d1b3ab22b6d9767088f5c4f | refs/heads/master | 2021-08-17T05:48:44.278928 | 2020-05-25T17:42:13 | 2020-05-25T17:42:13 | 80,446,905 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,734 | cpp |
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> pii;
#define forup(i,a,b) for(int i=a; i<b; ++i)
#define fordn(i,a,b) for(int i=a; i>b; --i)
#define rep(i,a) for(int i=0; i<a; ++i)
#define dforup(i,a,b) for(i=a; i<b; ++i)
#define dfordn(i,a,b) for(i=a; i>b; --i)
#define drep(i,a) for(i=0; i<a; ++i)
#define slenn(s,n) for(n=0; s[n]!=13 and s[n]!=0; ++n);s[n]=0
#define gi(x) scanf("%d",&x)
#define gl(x) scanf("%lld",&x)
#define gd(x) scanf("%lf",&x)
#define gs(x) scanf("%s",x)
#define pis(x) printf("%d ",x)
#define pin(x) printf("%d\n",x)
#define pls(x) printf("%lld ",x)
#define pln(x) printf("%lld\n",x)
#define pds(x) printf("%.12f ",x)
#define pdn(x) printf("%.12f\n",x)
#define pnl() printf("\n")
#define fs first
#define sc second
#define ll long long
#define pb push_back
#define MOD 1000000007
#define limit 10000005
#define INF 1000000000
#define ull unsigned long long
using namespace std;
ull mod_pow(ull num, ull pow, ull mod)
{
ull test,n = num;
for(test = 1; pow; pow >>= 1)
{
if (pow & 1)
test = ((test % mod) * (n % mod)) % mod;
n = ((n % mod) * (n % mod)) % mod;
}
return test; /* note this is potentially lossy */
}
//while((getchar())!='\n'); //buffer clear
ll gcd(ll a,ll b)
{ ll r;
while(b)
{ r= a%b;a = b; b = r;
}
return a;
}
int dp[501];
int main()
{
string s;
cin>>s;
int n = s.size();
int ans=0;
rep(i,n)
{
int a = 0;
if(s[i]=='Q')
{
forup(j,i,n)
{
if(s[j]=='A')
a++;
if(s[j]=='Q')
ans+=a;
}
}
}
cout<<ans<<endl;
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.