blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
92b721651b9646f1b5752273ed4cc8eeb316828f | ce315d03c7a79d828368f779269a67681e5782ff | /base/scoped_ptr_unittest.cc | db0d7fe740b02e03d1c694d167ef9b50952fddcb | [] | no_license | linzai1992/websearch | bc3a3f377326c990324a291d69df1dbeab8af50e | 6c5e6c1bbad5c1ac1324db71b2a4eaeef9376207 | refs/heads/master | 2020-07-05T14:49:22.911441 | 2014-06-23T01:48:52 | 2014-06-23T01:48:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,455 | cc | // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "base/scoped_ptr.h"
#include "thirdparty/gtest/gtest.h"
namespace {
class ConDecLogger {
public:
ConDecLogger() : ptr_(NULL) { }
explicit ConDecLogger(int* ptr) { set_ptr(ptr); }
~ConDecLogger() { --*ptr_; }
void set_ptr(int* ptr) { ptr_ = ptr; ++*ptr_; }
int SomeMeth(int x) { return x; }
private:
int* ptr_;
DISALLOW_COPY_AND_ASSIGN(ConDecLogger);
};
} // namespace
TEST(ScopedPtrTest, ScopedPtr) {
int constructed = 0;
{
scoped_ptr<ConDecLogger> scoper(new ConDecLogger(&constructed));
EXPECT_EQ(1, constructed);
EXPECT_TRUE(scoper.get());
EXPECT_EQ(10, scoper->SomeMeth(10));
EXPECT_EQ(10, scoper.get()->SomeMeth(10));
EXPECT_EQ(10, (*scoper).SomeMeth(10));
}
EXPECT_EQ(0, constructed);
// Test reset() and release()
{
scoped_ptr<ConDecLogger> scoper(new ConDecLogger(&constructed));
EXPECT_EQ(1, constructed);
EXPECT_TRUE(scoper.get());
scoper.reset(new ConDecLogger(&constructed));
EXPECT_EQ(1, constructed);
EXPECT_TRUE(scoper.get());
scoper.reset();
EXPECT_EQ(0, constructed);
EXPECT_FALSE(scoper.get());
scoper.reset(new ConDecLogger(&constructed));
EXPECT_EQ(1, constructed);
EXPECT_TRUE(scoper.get());
ConDecLogger* take = scoper.release();
EXPECT_EQ(1, constructed);
EXPECT_FALSE(scoper.get());
delete take;
EXPECT_EQ(0, constructed);
scoper.reset(new ConDecLogger(&constructed));
EXPECT_EQ(1, constructed);
EXPECT_TRUE(scoper.get());
}
EXPECT_EQ(0, constructed);
// Test swap(), == and !=
{
scoped_ptr<ConDecLogger> scoper1;
scoped_ptr<ConDecLogger> scoper2;
EXPECT_TRUE(scoper1 == scoper2.get());
EXPECT_FALSE(scoper1 != scoper2.get());
ConDecLogger* logger = new ConDecLogger(&constructed);
scoper1.reset(logger);
EXPECT_EQ(logger, scoper1.get());
EXPECT_FALSE(scoper2.get());
EXPECT_FALSE(scoper1 == scoper2.get());
EXPECT_TRUE(scoper1 != scoper2.get());
scoper2.swap(scoper1);
EXPECT_EQ(logger, scoper2.get());
EXPECT_FALSE(scoper1.get());
EXPECT_FALSE(scoper1 == scoper2.get());
EXPECT_TRUE(scoper1 != scoper2.get());
}
EXPECT_EQ(0, constructed);
}
TEST(ScopedPtrTest, ScopedArray) {
static const int kNumLoggers = 12;
int constructed = 0;
{
scoped_array<ConDecLogger> scoper(new ConDecLogger[kNumLoggers]);
EXPECT_TRUE(scoper.get());
EXPECT_EQ(&scoper[0], scoper.get());
for (int i = 0; i < kNumLoggers; ++i) {
scoper[i].set_ptr(&constructed);
}
EXPECT_EQ(12, constructed);
EXPECT_EQ(10, scoper.get()->SomeMeth(10));
EXPECT_EQ(10, scoper[2].SomeMeth(10));
}
EXPECT_EQ(0, constructed);
// Test reset() and release()
{
scoped_array<ConDecLogger> scoper;
EXPECT_FALSE(scoper.get());
EXPECT_FALSE(scoper.release());
EXPECT_FALSE(scoper.get());
scoper.reset();
EXPECT_FALSE(scoper.get());
scoper.reset(new ConDecLogger[kNumLoggers]);
for (int i = 0; i < kNumLoggers; ++i) {
scoper[i].set_ptr(&constructed);
}
EXPECT_EQ(12, constructed);
scoper.reset();
EXPECT_EQ(0, constructed);
scoper.reset(new ConDecLogger[kNumLoggers]);
for (int i = 0; i < kNumLoggers; ++i) {
scoper[i].set_ptr(&constructed);
}
EXPECT_EQ(12, constructed);
ConDecLogger* ptr = scoper.release();
EXPECT_EQ(12, constructed);
delete[] ptr;
EXPECT_EQ(0, constructed);
}
EXPECT_EQ(0, constructed);
// Test swap(), == and !=
{
scoped_array<ConDecLogger> scoper1;
scoped_array<ConDecLogger> scoper2;
EXPECT_TRUE(scoper1 == scoper2.get());
EXPECT_FALSE(scoper1 != scoper2.get());
ConDecLogger* loggers = new ConDecLogger[kNumLoggers];
for (int i = 0; i < kNumLoggers; ++i) {
loggers[i].set_ptr(&constructed);
}
scoper1.reset(loggers);
EXPECT_EQ(loggers, scoper1.get());
EXPECT_FALSE(scoper2.get());
EXPECT_FALSE(scoper1 == scoper2.get());
EXPECT_TRUE(scoper1 != scoper2.get());
scoper2.swap(scoper1);
EXPECT_EQ(loggers, scoper2.get());
EXPECT_FALSE(scoper1.get());
EXPECT_FALSE(scoper1 == scoper2.get());
EXPECT_TRUE(scoper1 != scoper2.get());
}
EXPECT_EQ(0, constructed);
}
// TODO scoped_ptr_malloc
| [
"shunping@shunping-desktop.(none)"
] | shunping@shunping-desktop.(none) |
ac6ed3d201f2b2a7a8b9b9c94aa1afc1f2c93da9 | f62072e737805aa9156040a699365aace14140f1 | /aws-cpp-sdk-ebs/source/model/ValidationExceptionReason.cpp | 7b908240d89327a9ca112c47a28092035e1435ea | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | neil-b/aws-sdk-cpp | 07e8e4e197cefff2ae60ab7d1b84bdb65be2c8f9 | 1602b75abbca880b770c12788f6d2bac0c87176a | refs/heads/master | 2022-11-20T16:50:19.236474 | 2020-07-08T19:05:34 | 2020-07-08T19:05:34 | 278,437,421 | 0 | 0 | Apache-2.0 | 2020-07-09T18:10:14 | 2020-07-09T18:10:14 | null | UTF-8 | C++ | false | false | 3,300 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ebs/model/ValidationExceptionReason.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace EBS
{
namespace Model
{
namespace ValidationExceptionReasonMapper
{
static const int INVALID_CUSTOMER_KEY_HASH = HashingUtils::HashString("INVALID_CUSTOMER_KEY");
static const int INVALID_PAGE_TOKEN_HASH = HashingUtils::HashString("INVALID_PAGE_TOKEN");
static const int INVALID_BLOCK_TOKEN_HASH = HashingUtils::HashString("INVALID_BLOCK_TOKEN");
static const int INVALID_SNAPSHOT_ID_HASH = HashingUtils::HashString("INVALID_SNAPSHOT_ID");
static const int UNRELATED_SNAPSHOTS_HASH = HashingUtils::HashString("UNRELATED_SNAPSHOTS");
ValidationExceptionReason GetValidationExceptionReasonForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == INVALID_CUSTOMER_KEY_HASH)
{
return ValidationExceptionReason::INVALID_CUSTOMER_KEY;
}
else if (hashCode == INVALID_PAGE_TOKEN_HASH)
{
return ValidationExceptionReason::INVALID_PAGE_TOKEN;
}
else if (hashCode == INVALID_BLOCK_TOKEN_HASH)
{
return ValidationExceptionReason::INVALID_BLOCK_TOKEN;
}
else if (hashCode == INVALID_SNAPSHOT_ID_HASH)
{
return ValidationExceptionReason::INVALID_SNAPSHOT_ID;
}
else if (hashCode == UNRELATED_SNAPSHOTS_HASH)
{
return ValidationExceptionReason::UNRELATED_SNAPSHOTS;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<ValidationExceptionReason>(hashCode);
}
return ValidationExceptionReason::NOT_SET;
}
Aws::String GetNameForValidationExceptionReason(ValidationExceptionReason enumValue)
{
switch(enumValue)
{
case ValidationExceptionReason::INVALID_CUSTOMER_KEY:
return "INVALID_CUSTOMER_KEY";
case ValidationExceptionReason::INVALID_PAGE_TOKEN:
return "INVALID_PAGE_TOKEN";
case ValidationExceptionReason::INVALID_BLOCK_TOKEN:
return "INVALID_BLOCK_TOKEN";
case ValidationExceptionReason::INVALID_SNAPSHOT_ID:
return "INVALID_SNAPSHOT_ID";
case ValidationExceptionReason::UNRELATED_SNAPSHOTS:
return "UNRELATED_SNAPSHOTS";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace ValidationExceptionReasonMapper
} // namespace Model
} // namespace EBS
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
d878907ad26eac72d9c92cbe73f506086fbd5c3b | eef68d8548a00af7e7bb99c645d1e5bc68bc9b70 | /utils/clist.h | 69c08f035ff6bb071857ac6dfc7dfea9e0549652 | [
"Apache-2.0"
] | permissive | NiklasWang/Sirius | 5b83bfe6d0f5be5989c90d4b6e4e98d58a2079d4 | 823f73363984a166124c2c9ffd08bbacfe7f7ee7 | refs/heads/master | 2021-06-25T10:32:43.372144 | 2019-05-07T16:28:45 | 2019-05-07T16:28:45 | 139,455,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 974 | h | #ifndef __Clist_H_
#define __Clist_H_
namespace sirius {
#define member_of(ptr, type, member) ({ \
const decltype(((type *)0)->member) *__mptr = (ptr); \
(type *)((char *)__mptr - offsetof(type,member));})
struct clist {
struct clist *next, *prev;
};
static inline void clist_init(struct clist *ptr)
{
ptr->next = ptr;
ptr->prev = ptr;
}
static inline void clist_add_tail_node(struct clist *item,
struct clist *head)
{
struct clist *prev = head->prev;
head->prev = item;
item->next = head;
item->prev = prev;
prev->next = item;
}
static inline void clist_insert_before_node(struct clist *item,
struct clist *node)
{
item->next = node;
item->prev = node->prev;
item->prev->next = item;
node->prev = item;
}
static inline void clist_del_node(struct clist *ptr)
{
struct clist *prev = ptr->prev;
struct clist *next = ptr->next;
next->prev = ptr->prev;
prev->next = ptr->next;
ptr->next = ptr;
ptr->prev = ptr;
}
};
#endif
| [
"niklas.wang@outlook.com"
] | niklas.wang@outlook.com |
7a2e24df4854076c9ef05a11a8db56606560d75b | e308652eacb626ccd368166dc1fa3c2bd97ed71c | /UnitTests.h | 9fa66b66b73617d5bf802c55fd3c404196ca2a3c | [] | no_license | sidfishus/BlockAllocator | 1cc6b179e038c7f02e9b9caf2d5422b4450ee570 | dc1f9da40202702f87a098dc70bcc6db7c264611 | refs/heads/master | 2022-06-12T13:20:57.617860 | 2020-05-05T10:16:44 | 2020-05-05T10:16:44 | 261,422,717 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,634 | h | #pragma once
#include "IUnitTest.h"
#define UNITTEST_ASSERT(val) _ASSERTE((val)); if(!(val)) return false;
class tUnitTestExecutor
{
void DescribeTest(
IUnitTest& test,
const unsigned short testnum,
const unsigned short descrcount,
WCHAR* const descr);
public:
int DoUnitTest(
IUnitTest& test,
const unsigned short failmsgcount,
WCHAR* failmsg); // Returns the first test which failed or -1
};
int tUnitTestExecutor::DoUnitTest(IUnitTest& test,const unsigned short failmsgcount,WCHAR* failmsg)
{
const char* testname=NULL;
const unsigned short firsttest=test.GetFirstTest();
const unsigned short testcount=test.GetTestCount();
unsigned short testnum=firsttest;
try
{
for(;testnum<(firsttest+testcount);++testnum)
{
if(!test.DoTest(testnum))
{
WCHAR descr[512];
DescribeTest(test,testnum,_countof(descr),descr);
wprintf_s(failmsg,failmsgcount,L"%ls. This test failed by returning false.",descr);
return testnum;
}
}
}
catch(...)
{
WCHAR descr[512];
DescribeTest(test,testnum,_countof(descr),descr);
wprintf_s(failmsg,failmsgcount,L"%ls. This test threw an exception!",descr);
return testnum;
}
return -1;
}
void tUnitTestExecutor::DescribeTest(IUnitTest& test,const unsigned short testnum,const unsigned short descrcount,
WCHAR* const descr)
{
WCHAR testname[64];
test.GetTestName(testnum,_countof(testname),testname);
WCHAR testdescr[256];
test.GetTestDescription(testnum,_countof(testdescr),testdescr);
wprintf_s(descr,descrcount,"Test (number %hd) %ls: %ls",testname,testdescr);
} | [
"noreply@github.com"
] | noreply@github.com |
8b0e2df95830d7729c46d936f78f030dadb1d542 | 903cc1b03935f5b551bd531142751e15698c4a37 | /lab5/ejer17.cpp | 887d100617ff84fbf88a1b489809dd26e893f520 | [] | no_license | ealvan/ProgSistemas | a25af731e4fa9c836f982e4eadbcaa678d3b2b3b | 035a95bce77bdcaa618244a00df5e0c6d4f0514f | refs/heads/main | 2023-07-10T10:25:40.540586 | 2021-08-20T04:18:43 | 2021-08-20T04:18:43 | 398,153,434 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | cpp | /*
hacer
raiz cuadrada
y potencia
con punteros y msotrar
que se puede retornar multiples valores
*/
#include <iostream>
#include <cmath>
using namespace std;
void fun(int n, int*cuadrado, double* raizcuadrada){
*cuadrado = n*n;
*raizcuadrada = sqrt(n);
}
int main(){
int n = 100;
int* sq = new int;
double* sq_root = new double;
fun(n, sq, sq_root);
cout << *sq << " " << *sq_root << endl;
return 0;
} | [
"ealvan@unsa.edu.pe"
] | ealvan@unsa.edu.pe |
f7a6a05d4cd2974c8500b34b3d73eb7646f58edc | 67dbcc8034a26325b3c2c735b0e4c9d700985f75 | /simple_db/net/tcp_server_test.cc | 94bb1b50a4bf8c23070d7dd5054aae49f534033e | [] | no_license | junjiejiangjjj/simple-db | b79feb08600edd89b1383a0d8023f584983ef426 | 117a5fe3d73dbee5c698e80831292705c87b5743 | refs/heads/master | 2022-11-19T09:36:53.782105 | 2020-06-28T16:25:28 | 2020-06-28T16:25:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 462 | cc | #include "tcp_server.h"
#include <gtest/gtest.h>
BEGIN_SIMPLE_DB_NS(net)
class TcpServerTest : public ::testing::Test {
protected:
TcpServerTest() {
}
~TcpServerTest() override {
}
void SetUp() override {
}
void TearDown() override {
}
};
TEST_F(TcpServerTest, h) {
ASSERT_EQ(0, 0);
}
END_SIMPLE_DB_NS(net)
int main(int argc, char **argv){
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| [
"1034457072@qq.com"
] | 1034457072@qq.com |
070a74d4f29ab368fe9dda77b3a0f9c417e84667 | c1cd9648b9c2720aee02d71ea8233cb475462c77 | /floam_noted/src/laserProcessingNode.cpp | 81e115220d1d2a2cafd670209d5eb7af225acce6 | [
"BSD-3-Clause"
] | permissive | idontlikelongname/opensource_slam_noted | 9fb953effdbc15793fbea75fe556e1625dfd9318 | 0b53d113a306b4d086c8695a170e6d5f14dd44b4 | refs/heads/master | 2023-06-22T08:34:37.525467 | 2021-07-15T05:42:01 | 2021-07-15T05:42:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,918 | cpp | // Author of FLOAM: Wang Han
// Email wh200720041@gmail.com
// Homepage https://wanghan.pro
//c++ lib
#include <cmath>
#include <vector>
#include <mutex>
#include <queue>
#include <thread>
#include <chrono>
//ros lib
#include <ros/ros.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/PointCloud2.h>
#include <nav_msgs/Odometry.h>
#include <tf/transform_datatypes.h>
#include <tf/transform_broadcaster.h>
//pcl lib
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
//local lib
#include "lidar.h"
#include "laserProcessingClass.h"
LaserProcessingClass laserProcessing;
std::mutex mutex_lock;
std::queue<sensor_msgs::PointCloud2ConstPtr> pointCloudBuf;
lidar::Lidar lidar_param;
ros::Publisher pubEdgePoints;
ros::Publisher pubSurfPoints;
ros::Publisher pubLaserCloudFiltered;
void velodyneHandler(const sensor_msgs::PointCloud2ConstPtr &laserCloudMsg) {
mutex_lock.lock();
pointCloudBuf.push(laserCloudMsg);
mutex_lock.unlock();
}
double total_time = 0;
int total_frame = 0;
void laser_processing() {
while (1) {
if (!pointCloudBuf.empty()) {
//read data
mutex_lock.lock();
pcl::PointCloud<pcl::PointXYZI>::Ptr pointcloud_in(new pcl::PointCloud<pcl::PointXYZI>());
pcl::fromROSMsg(*pointCloudBuf.front(), *pointcloud_in);
ros::Time pointcloud_time = (pointCloudBuf.front())->header.stamp;
pointCloudBuf.pop(); // pop掉
mutex_lock.unlock();
// 取queue里面的第一条数据
pcl::PointCloud<pcl::PointXYZI>::Ptr pointcloud_edge(new pcl::PointCloud<pcl::PointXYZI>());
pcl::PointCloud<pcl::PointXYZI>::Ptr pointcloud_surf(new pcl::PointCloud<pcl::PointXYZI>());
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
// 提取surface和corner特征
laserProcessing.featureExtraction(pointcloud_in, pointcloud_edge, pointcloud_surf);
end = std::chrono::system_clock::now();
std::chrono::duration<float> elapsed_seconds = end - start;
total_frame++;
float time_temp = elapsed_seconds.count() * 1000;
total_time += time_temp;
//ROS_INFO("average laser processing time %f ms \n \n", total_time/total_frame);
// 发布过滤点云,surface+corner
sensor_msgs::PointCloud2 laserCloudFilteredMsg;
pcl::PointCloud<pcl::PointXYZI>::Ptr pointcloud_filtered(new pcl::PointCloud<pcl::PointXYZI>());
*pointcloud_filtered += *pointcloud_edge;
*pointcloud_filtered += *pointcloud_surf;
pcl::toROSMsg(*pointcloud_filtered, laserCloudFilteredMsg);
laserCloudFilteredMsg.header.stamp = pointcloud_time;
laserCloudFilteredMsg.header.frame_id = "/base_link";
pubLaserCloudFiltered.publish(laserCloudFilteredMsg);
// 发布这两种特征点云
sensor_msgs::PointCloud2 edgePointsMsg;
pcl::toROSMsg(*pointcloud_edge, edgePointsMsg);
edgePointsMsg.header.stamp = pointcloud_time;
edgePointsMsg.header.frame_id = "/base_link";
pubEdgePoints.publish(edgePointsMsg);
sensor_msgs::PointCloud2 surfPointsMsg;
pcl::toROSMsg(*pointcloud_surf, surfPointsMsg);
surfPointsMsg.header.stamp = pointcloud_time;
surfPointsMsg.header.frame_id = "/base_link";
pubSurfPoints.publish(surfPointsMsg);
}
//sleep 2 ms every time
std::chrono::milliseconds dura(2);
std::this_thread::sleep_for(dura);
}
}
int main(int argc, char **argv) {
ros::init(argc, argv, "main");
ros::NodeHandle nh;
// 设置参数
int scan_line = 64; // 雷达线束
double vertical_angle = 2.0; // 垂直方向两线束的角度,用来计算每个点属于哪个激光线束发射出来的。
double scan_period = 0.1; // 扫描周期,0.1s转一圈
double max_dis = 60.0; // 点云的有效距离,60M以外噪声较大
double min_dis = 2.0;
nh.getParam("/scan_period", scan_period);
nh.getParam("/vertical_angle", vertical_angle);
nh.getParam("/max_dis", max_dis);
nh.getParam("/min_dis", min_dis);
nh.getParam("/scan_line", scan_line);
lidar_param.setScanPeriod(scan_period);
lidar_param.setVerticalAngle(vertical_angle);
lidar_param.setLines(scan_line);
lidar_param.setMaxDistance(max_dis);
lidar_param.setMinDistance(min_dis);
laserProcessing.init(lidar_param);
// callback里面不写逻辑,只装buffer数据
ros::Subscriber subLaserCloud = nh.subscribe<sensor_msgs::PointCloud2>("/velodyne_points", 100, velodyneHandler);
pubLaserCloudFiltered = nh.advertise<sensor_msgs::PointCloud2>("/velodyne_points_filtered", 100);
pubEdgePoints = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_edge", 100);
pubSurfPoints = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_surf", 100);
// 在process线程里面处理点云数据
std::thread laser_processing_process{laser_processing};
ros::spin();
return 0;
}
| [
"2022087641@qq.com"
] | 2022087641@qq.com |
e5d5bca01c5fdc39e60a842e19d32a33a41736cb | 55d560fe6678a3edc9232ef14de8fafd7b7ece12 | /libs/hana/test/ext/std/tuple/laws.searchable.cpp | ac674cd57aa25cf410ff1f59af6ecc18c0cf71d4 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | stardog-union/boost | ec3abeeef1b45389228df031bf25b470d3d123c5 | caa4a540db892caa92e5346e0094c63dea51cbfb | refs/heads/stardog/develop | 2021-06-25T02:15:10.697006 | 2020-11-17T19:50:35 | 2020-11-17T19:50:35 | 148,681,713 | 0 | 0 | BSL-1.0 | 2020-11-17T19:50:36 | 2018-09-13T18:38:54 | C++ | UTF-8 | C++ | false | false | 1,335 | cpp | // Copyright Louis Dionne 2013-2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
#include <boost/hana/bool.hpp>
#include <boost/hana/ext/std/tuple.hpp>
#include <boost/hana/tuple.hpp>
#include <laws/base.hpp>
#include <laws/searchable.hpp>
#include <tuple>
namespace hana = boost::hana;
using hana::test::ct_eq;
int main() {
auto tuples = hana::make_tuple(
std::make_tuple()
, std::make_tuple(ct_eq<0>{})
, std::make_tuple(ct_eq<0>{}, ct_eq<1>{})
, std::make_tuple(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{})
);
auto keys = hana::make_tuple(ct_eq<3>{}, ct_eq<5>{}, ct_eq<7>{});
auto bool_tuples = hana::make_tuple(
std::make_tuple(hana::true_c)
, std::make_tuple(hana::false_c)
, std::make_tuple(hana::true_c, hana::true_c)
, std::make_tuple(hana::true_c, hana::false_c)
, std::make_tuple(hana::false_c, hana::true_c)
, std::make_tuple(hana::false_c, hana::false_c)
);
auto bool_keys = hana::make_tuple(hana::true_c, hana::false_c);
hana::test::TestSearchable<hana::ext::std::tuple_tag>{tuples, keys};
hana::test::TestSearchable<hana::ext::std::tuple_tag>{bool_tuples, bool_keys};
}
| [
"james.pack@stardog.com"
] | james.pack@stardog.com |
2f37702d1cd614d08a30266f84fed5e9e8671ce0 | cf3ac35071a39b041f9b59dfbcd4d31b2c114ecf | /tamu/1semester/441/assingments/06/submition/display.h | d882d87b56770564fa5bfab9b2eda2ccd56886a6 | [] | no_license | gustavoem/bcc | 0aca907ceb18a798691d27d037e38c41de686657 | 53d57a91cb755b4dfc0b26ea58efbc4856dd44ec | refs/heads/master | 2023-06-08T04:15:54.730756 | 2023-06-06T14:26:00 | 2023-06-06T14:26:00 | 24,634,426 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,043 | h | /*
display.h
Display the skeleton, ground plane and other objects.
Revision 1 - Steve Lin, Jan. 14, 2002
Revision 2 - Alla and Kiran, Jan 18, 2002
*/
#ifndef _DSIPLAY_H
#define _DISPLAY_H
#include <GL/gl.h>
#include "skeleton.h"
#include "motion.h"
class Display
{
//member functions
public:
Display();
~Display();
//set actor for display
void loadActor(Skeleton *pActor);
//set motion for display
void loadMotion(Motion *pMotion);
//display the scene (actor, ground plane ....)
void show();
private:
//Draw a particular bone
void drawBone(Bone *ptr,int skelNum);
//Draw the skeleton hierarchy
void traverse(Bone *ptr,int skelNum);
//member variables
public:
int m_SpotJoint; //joint whose local coordinate system is drawn
int numActors;
int numMotions;
Skeleton *m_pActor[MAX_SKELS]; //pointer to current actor
Motion *m_pMotion[MAX_SKELS]; //pointer to current motion
private:
GLuint m_BoneList[MAX_SKELS]; //display list with bones
};
#endif
| [
"estrela.gustavo.matos@gmail.com"
] | estrela.gustavo.matos@gmail.com |
5404d0e95deef2da224d11f1f2a86977b0ea00a5 | 277d869859a3a375927a5d549c3d139313cff50f | /3.0/m_checkbans.cpp | af12e9fc9a5b0b6f4cf7abbce3b82c3fde4893ad | [] | no_license | Koragg-IRC-Backburner/inspircd-contrib | 7314d728131eeda8b01dac13cd6acccde8fb3da6 | 53ef82433c9ea1c1f303ba2c215e009ce4f82108 | refs/heads/master | 2022-02-19T20:50:21.854065 | 2019-09-12T22:07:18 | 2019-09-12T22:07:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,520 | cpp | /*
* InspIRCd -- Internet Relay Chat Daemon
*
* Copyright (C) 2017-2019 Matt Schatz <genius3000@g3k.solutions>
*
* This file is a module for InspIRCd. InspIRCd is free software: you can
* redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// $ModAuthor: genius3000
/// $ModAuthorMail: genius3000@g3k.solutions
/// $ModDepends: core 3
/// $ModDesc: Adds commands /checkbans, /testban, and /whyban
/* Helpop Lines for the CUSER section
* Find: '<helpop key="cuser" value="User Commands
* Place 'CHECKBANS', 'TESTBAN', and 'WHYBAN' in the
* command list accordingly. Re-space as needed.
* Find: '<helpop key="sslinfo" ...'
* Place just above that line:
<helpop key="testban" value="/TESTBAN <channel> <mask>
Test a channel ban mask against the users currently in the channel.">
<helpop key="whyban" value="/WHYBAN <channel> [user]
Get a list of bans and exceptions that match you (or the given user)
on the specified channel.">
<helpop key="checkbans" value="/CHECKBANS <channel>
Get a list of bans and exceptions that match current users on the channel.">
*/
#include "inspircd.h"
#include "listmode.h"
namespace
{
enum
{
RPL_BANMATCH = 540,
RPL_EXCEPTIONMATCH = 541,
RPL_ENDLIST = 542
};
bool CanCheck(Channel* chan, User* user, ChanModeReference& ban)
{
if (user->HasPrivPermission("channels/auspex"))
return true;
if (ban->GetLevelRequired(true) > chan->GetPrefixValue(user))
{
user->WriteNumeric(ERR_CHANOPRIVSNEEDED, chan->name, "You do not have access to modify the ban list.");
return false;
}
return true;
}
void CheckLists(User* source, Channel* chan, User* user, ChanModeReference& ban, ChanModeReference& exc)
{
ListModeBase::ModeList* list;
ListModeBase::ModeList::const_iterator iter;
ListModeBase* banlm = ban->IsListModeBase();
list = banlm ? banlm->GetList(chan) : NULL;
if (list)
{
for (iter = list->begin(); iter != list->end(); ++iter)
{
if (!chan->CheckBan(user, iter->mask))
continue;
source->WriteNumeric(RPL_BANMATCH, chan->name, InspIRCd::Format("Ban %s matches %s (set by %s on %s)",
iter->mask.c_str(), user->nick.c_str(), iter->setter.c_str(),
ServerInstance->TimeString(iter->time, "%Y-%m-%d %H:%M:%S UTC", true).c_str()));
}
}
ListModeBase* exclm = exc ? exc->IsListModeBase() : NULL;
list = exclm ? exclm->GetList(chan) : NULL;
if (list)
{
for (iter = list->begin(); iter != list->end(); ++iter)
{
if (!chan->CheckBan(user, iter->mask))
continue;
source->WriteNumeric(RPL_EXCEPTIONMATCH, chan->name, InspIRCd::Format("Exception %s matches %s (set by %s on %s)",
iter->mask.c_str(), user->nick.c_str(), iter->setter.c_str(),
ServerInstance->TimeString(iter->time, "%Y-%m-%d %H:%M:%S UTC", true).c_str()));
}
}
}
} // namespace
class CommandCheckBans : public Command
{
ChanModeReference& ban;
ChanModeReference& exc;
public:
CommandCheckBans(Module* Creator, ChanModeReference& _ban, ChanModeReference& _exc)
: Command(Creator, "CHECKBANS", 1, 1)
, ban(_ban)
, exc(_exc)
{
this->syntax = "<channel>";
this->Penalty = 6;
}
CmdResult Handle(User* user, const Params& parameters) CXX11_OVERRIDE
{
Channel* chan = ServerInstance->FindChan(parameters[0]);
if (!chan)
{
user->WriteNumeric(Numerics::NoSuchChannel(parameters[0]));
return CMD_FAILURE;
}
// Only allow checking for matching users if you have access to the ban list
if (!CanCheck(chan, user, ban))
return CMD_FAILURE;
// Loop through all users of the channel, checking for matches to bans and exceptions (if available)
const Channel::MemberMap& users = chan->GetUsers();
for (Channel::MemberMap::const_iterator u = users.begin(); u != users.end(); ++u)
CheckLists(user, chan, u->first, ban, exc);
user->WriteNumeric(RPL_ENDLIST, chan->name, "End of check bans list");
return CMD_SUCCESS;
}
};
class CommandTestBan : public Command
{
ChanModeReference& ban;
public:
CommandTestBan(Module* Creator, ChanModeReference& _ban)
: Command(Creator, "TESTBAN", 2, 2)
, ban(_ban)
{
this->syntax = "<channel> <mask>";
this->Penalty = 6;
}
CmdResult Handle(User* user, const Params& parameters) CXX11_OVERRIDE
{
Channel* chan = ServerInstance->FindChan(parameters[0]);
if (!chan)
{
user->WriteNumeric(Numerics::NoSuchChannel(parameters[0]));
return CMD_FAILURE;
}
// Only allow testing bans if the user has access to set a ban on the channel
if (!CanCheck(chan, user, ban))
return CMD_FAILURE;
unsigned int matched = 0;
const Channel::MemberMap& users = chan->GetUsers();
for (Channel::MemberMap::const_iterator u = users.begin(); u != users.end(); ++u)
{
if (chan->CheckBan(u->first, parameters[1]))
{
user->WriteNumeric(RPL_BANMATCH, chan->name, InspIRCd::Format("Mask %s matches %s",
parameters[1].c_str(), u->first->nick.c_str()));
matched++;
}
}
if (matched > 0)
{
float percent = ((float)matched / (float)users.size()) * 100;
user->WriteNumeric(RPL_BANMATCH, chan->name, InspIRCd::Format("Mask %s matched %d of %lu users (%.2f%%).",
parameters[1].c_str(), matched, users.size(), percent));
}
user->WriteNumeric(RPL_ENDLIST, chan->name, parameters[1], "End of test ban list");
return CMD_SUCCESS;
}
};
class CommandWhyBan : public Command
{
ChanModeReference& ban;
ChanModeReference& exc;
public:
CommandWhyBan(Module* Creator, ChanModeReference& _ban, ChanModeReference& _exc)
: Command(Creator, "WHYBAN", 1, 2)
, ban(_ban)
, exc(_exc)
{
this->syntax = "<channel> [user]";
}
CmdResult Handle(User* user, const Params& parameters) CXX11_OVERRIDE
{
Channel* chan = ServerInstance->FindChan(parameters[0]);
if (!chan)
{
user->WriteNumeric(Numerics::NoSuchChannel(parameters[0]));
return CMD_FAILURE;
}
/* Allow checking yourself against channel bans with no access, but only
* allow checking others if you have access to the channel ban list.
*/
User* u = parameters.size() == 1 ? user : NULL;
if (!u)
{
// Use a penalty of 10 when checking other users
LocalUser* lu = IS_LOCAL(user);
if (lu)
lu->CommandFloodPenalty += 10000;
if (!CanCheck(chan, user, ban))
return CMD_FAILURE;
u = ServerInstance->FindNick(parameters[1]);
if (!u)
{
user->WriteNumeric(Numerics::NoSuchNick(parameters[1]));
return CMD_FAILURE;
}
}
// Check for matching bans and exceptions (if available)
CheckLists(user, chan, u, ban, exc);
user->WriteNumeric(RPL_ENDLIST, chan->name, u->nick, "End of why ban list");
return CMD_SUCCESS;
}
};
class ModuleCheckBans : public Module
{
ChanModeReference ban;
ChanModeReference exc;
CommandCheckBans ccb;
CommandTestBan ctb;
CommandWhyBan cwb;
public:
ModuleCheckBans()
: ban(this, "ban")
, exc(this, "banexception")
, ccb(this, ban, exc)
, ctb(this, ban)
, cwb(this, ban, exc)
{
}
Version GetVersion() CXX11_OVERRIDE
{
return Version("Gives /checkbans, /testban, and /whyban - channel ban helper commands.");
}
};
MODULE_INIT(ModuleCheckBans)
| [
"petpow@saberuk.com"
] | petpow@saberuk.com |
cacc8a2a771fa5ea93a9bc61edf83ba34b1a3e69 | dd0cafca11c990626b55d3460b225ac5acf1619d | /Dynamic Programming/EvaluateExpressionToTrue.cpp | 6dd29a448190d00448feda3f364cfd15c5626469 | [] | no_license | VenkataAnilKumar/InterviewBit-CPlusPlus | 5439642fd316f06879f992c2f57de1ce5be8be4f | 65cba3a7c9844a84547c1a6faa327d5614a2d234 | refs/heads/master | 2022-01-29T15:17:41.994010 | 2019-07-20T18:34:18 | 2019-07-20T18:34:18 | 197,962,915 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,067 | cpp | struct Box{
int T,F;
Box():T(0),F(0){}
};
Box util(char c,Box b1, Box b2){
Box b;
if(c=='|'){
b.T=b1.T*b2.F+b1.F*b2.T+b1.T*b2.T;
b.F=b1.F*b2.F;
}
else if(c=='&'){
b.F=b1.T*b2.F+b1.F*b2.T+b1.F*b2.F;
b.T=b1.T*b2.T;
}
else {
b.F=b1.F*b2.F+b1.T*b2.T;
b.T=b1.F*b2.T+b1.T*b2.F;
}
b.T%=1003;
b.F%=1003;
return b;
}
Box method(Box **arr,int i,int l,string s1, string s2){
int m=0,n=s1.length();
Box b1;
for(m=i;m<l;m++){
Box b2;
b2=util(s2[m],arr[i][n-m-1],arr[m+1][n-l-1]);
b1.T+=b2.T;
b1.F+=b2.F;
b1.T%=1003;
b1.F%=1003;
}
return b1;
}
int Solution::cnttrue(string A) {
string s=A;
string s1="",s2="";
int i,j,k,l;
for(i=0;i<s.length();i++){
if(s[i]=='T' | s[i]=='F')
s1+=s[i];
else s2+=s[i];
}
int n=s1.length();
Box **arr=new Box *[n];
for(i=0;i<n;i++)
arr[i]=new Box[n-i];
for(i=0;i<n;i++){
Box b1;
if(s1[i]=='T')
b1.T=1;
else b1.F=1;
arr[i][n-i-1]=b1;
}
for(k=1;k<n;k++){
i=0;j=n-k-1;l=k;
while(i<n-k){
arr[i][j]=method(arr,i,l,s1,s2);
i++;j--;l++;
}
}
return arr[0][0].T;
} | [
"25908037+VenkataAnilKumar@users.noreply.github.com"
] | 25908037+VenkataAnilKumar@users.noreply.github.com |
e7aa40385418e38304900fa078ade42abda2f5f8 | 5122fd1df8157561ba5241abf3a93a6af609d86e | /FullGame/Brick.cpp | 3a57411b1d76fdb696003554a6b4546236c1c689 | [] | no_license | JHVy/Castlevania-JHVy | 2eecd31537edf9accb0797330cf977bfca625d61 | 41aa147f41f4e031b2bdfa12c2b0eb13690a8843 | refs/heads/master | 2022-11-26T02:43:55.068972 | 2020-08-08T06:47:10 | 2020-08-08T06:47:10 | 254,833,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 320 | cpp | #include "Brick.h"
Brick::Brick(float _x, float _y, int id , int type, float width, float height) : CGameObject(_x, _y)
{
this->_type = eType::BRICK_2;
this->width = width;
this->height = height;
}
void Brick::Render()
{
//RenderBoundingBox();
}
void Brick::Disappear()
{
this->width = 0;
this->height = 0;
}
| [
"16521470@gm.uit.edu.vn"
] | 16521470@gm.uit.edu.vn |
f1d37ebca894a3a26c92371f1243a46aa841d56a | b715e3a0f1dbaf5e51c0b5117681e44d6df1ea2f | /devel/include/object_segmentation/AddTwoIntsRequest.h | 65e88c252d35b1bef0aed502fd28872c6c25e503 | [] | no_license | yangshuo11/opencv_ros_ws | 92840fc54035485ab6b27c7d172c35069e9e3c49 | 889117261cd34282d2324d1c5e04218e4a95a8d7 | refs/heads/master | 2020-09-30T16:00:48.290397 | 2019-12-14T05:16:27 | 2019-12-14T05:16:27 | 227,320,627 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,599 | h | // Generated by gencpp from file object_segmentation/AddTwoIntsRequest.msg
// DO NOT EDIT!
#ifndef OBJECT_SEGMENTATION_MESSAGE_ADDTWOINTSREQUEST_H
#define OBJECT_SEGMENTATION_MESSAGE_ADDTWOINTSREQUEST_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace object_segmentation
{
template <class ContainerAllocator>
struct AddTwoIntsRequest_
{
typedef AddTwoIntsRequest_<ContainerAllocator> Type;
AddTwoIntsRequest_()
: a(0)
, b(0) {
}
AddTwoIntsRequest_(const ContainerAllocator& _alloc)
: a(0)
, b(0) {
(void)_alloc;
}
typedef int64_t _a_type;
_a_type a;
typedef int64_t _b_type;
_b_type b;
typedef boost::shared_ptr< ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator> const> ConstPtr;
}; // struct AddTwoIntsRequest_
typedef ::object_segmentation::AddTwoIntsRequest_<std::allocator<void> > AddTwoIntsRequest;
typedef boost::shared_ptr< ::object_segmentation::AddTwoIntsRequest > AddTwoIntsRequestPtr;
typedef boost::shared_ptr< ::object_segmentation::AddTwoIntsRequest const> AddTwoIntsRequestConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace object_segmentation
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'object_segmentation': ['/home/ys/MyGitRepository/opencv_ros_ws/src/object_segmentation/msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator> >
{
static const char* value()
{
return "36d09b846be0b371c5f190354dd3153e";
}
static const char* value(const ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x36d09b846be0b371ULL;
static const uint64_t static_value2 = 0xc5f190354dd3153eULL;
};
template<class ContainerAllocator>
struct DataType< ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator> >
{
static const char* value()
{
return "object_segmentation/AddTwoIntsRequest";
}
static const char* value(const ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator> >
{
static const char* value()
{
return "int64 a\n\
int64 b\n\
";
}
static const char* value(const ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.a);
stream.next(m.b);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct AddTwoIntsRequest_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::object_segmentation::AddTwoIntsRequest_<ContainerAllocator>& v)
{
s << indent << "a: ";
Printer<int64_t>::stream(s, indent + " ", v.a);
s << indent << "b: ";
Printer<int64_t>::stream(s, indent + " ", v.b);
}
};
} // namespace message_operations
} // namespace ros
#endif // OBJECT_SEGMENTATION_MESSAGE_ADDTWOINTSREQUEST_H
| [
"1024809808@qq.com"
] | 1024809808@qq.com |
fd6c0269381a51a9f5fb809885b40ce822c881e4 | 881c8115165ff14f91d8cc762e30dfabf4711758 | /Space Invaders/NYUCodebase/Loaders.h | 0f7b962ef979b99c9cc1d0ea8f8f17215b982850 | [] | no_license | nsw279/nsw279-cs3113 | a9c93a65bae6bff0893253adb3dfb3edd790bef4 | 5cf03b9a24cd24f7a2eca372dc0bc2728651e701 | refs/heads/master | 2020-04-20T20:40:37.104535 | 2019-05-14T23:11:07 | 2019-05-14T23:11:07 | 169,083,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 843 | h | ////
//// Loaders.h
//// NYUCodebase
////
//// Created by Noah Weitz on 4/2/19.
//// Copyright © 2019 Ivan Safrin. All rights reserved.
////
//
//#ifndef Loaders_h
//#define Loaders_h
//
//#ifdef _WINDOWS
//#include <GL/glew.h>
//#endif
//#include <SDL.h>
//#include <SDL_opengl.h>
//#include <SDL_image.h>
//#include "glm/mat4x4.hpp"
//#include "glm/gtc/matrix_transform.hpp"
//#include "ShaderProgram.h"
//#define STB_IMAGE_IMPLEMENTATION
//#include "stb_image.h"
//#include <vector>
//
//class Loaders {
//public:
// GLuint LoadTexture(const char *filePath);
// void DrawText(ShaderProgram& program, GLuint font, std::string text, float size, float space);
// void DrawSheet(ShaderProgram& program, glm::mat4 modelMatrix, int index, int sprX, int sprY, int textureID, float xPos, float yPos);
//};
//
//#endif /* Loaders_h */
| [
"nsw279@nyu.edu"
] | nsw279@nyu.edu |
77a1d50c8883a10864fee7c2799c3a6248a0a107 | cd5a78371196427bf258abe6386296cb2e57b72c | /out/include/octopus/HtmlParser.h | 83ea9c789a34f9df4c380f22c45b9ff39d96120d | [] | no_license | Grabli66/Octopus | 8ec86eb55d3ee27347d463147e2daed83e5abc64 | 22db97cdebfeee0b4e61e25ef2ad99f58aad7489 | refs/heads/master | 2020-04-14T02:58:10.950728 | 2019-01-07T16:53:29 | 2019-01-07T16:53:29 | 163,596,573 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 1,426 | h | // Generated by Haxe 4.0.0-preview.5+7eb789f
#ifndef INCLUDED_octopus_HtmlParser
#define INCLUDED_octopus_HtmlParser
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS1(octopus,HtmlParser)
HX_DECLARE_CLASS1(octopus,HtmlTree)
namespace octopus{
class HXCPP_CLASS_ATTRIBUTES HtmlParser_obj : public hx::Object
{
public:
typedef hx::Object super;
typedef HtmlParser_obj OBJ_;
HtmlParser_obj();
public:
enum { _hx_ClassId = 0x4831b4a9 };
void __construct();
inline void *operator new(size_t inSize, bool inContainer=false,const char *inName="octopus.HtmlParser")
{ return hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return hx::Object::operator new(inSize+extra,false,"octopus.HtmlParser"); }
static hx::ObjectPtr< HtmlParser_obj > __new();
static hx::ObjectPtr< HtmlParser_obj > __alloc(hx::Ctx *_hx_ctx);
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
//~HtmlParser_obj();
HX_DO_RTTI_ALL;
hx::Val __Field(const ::String &inString, hx::PropertyAccess inCallProp);
static void __register();
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_("HtmlParser",ca,0c,fb,b1); }
::octopus::HtmlTree parse(::String text);
::Dynamic parse_dyn();
};
} // end namespace octopus
#endif /* INCLUDED_octopus_HtmlParser */
| [
"grabli66@gmail.com"
] | grabli66@gmail.com |
eaba30fa243c99cd5f6f5b934c4943f281887376 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /media/audio/audio_input_controller.cc | c190056857cad2d0cc31553bf071f3e045955b97 | [
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 21,779 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/audio/audio_input_controller.h"
#include <algorithm>
#include <limits>
#include <utility>
#include "base/bind.h"
#include "base/metrics/histogram_macros.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "media/audio/audio_input_writer.h"
#include "media/base/user_input_monitor.h"
namespace {
const int kMaxInputChannels = 3;
#if defined(AUDIO_POWER_MONITORING)
// Time in seconds between two successive measurements of audio power levels.
const int kPowerMonitorLogIntervalSeconds = 15;
// A warning will be logged when the microphone audio volume is below this
// threshold.
const int kLowLevelMicrophoneLevelPercent = 10;
// Logs if the user has enabled the microphone mute or not. This is normally
// done by marking a checkbox in an audio-settings UI which is unique for each
// platform. Elements in this enum should not be added, deleted or rearranged.
enum MicrophoneMuteResult {
MICROPHONE_IS_MUTED = 0,
MICROPHONE_IS_NOT_MUTED = 1,
MICROPHONE_MUTE_MAX = MICROPHONE_IS_NOT_MUTED
};
void LogMicrophoneMuteResult(MicrophoneMuteResult result) {
UMA_HISTOGRAM_ENUMERATION("Media.MicrophoneMuted",
result,
MICROPHONE_MUTE_MAX + 1);
}
// Helper method which calculates the average power of an audio bus. Unit is in
// dBFS, where 0 dBFS corresponds to all channels and samples equal to 1.0.
float AveragePower(const media::AudioBus& buffer) {
const int frames = buffer.frames();
const int channels = buffer.channels();
if (frames <= 0 || channels <= 0)
return 0.0f;
// Scan all channels and accumulate the sum of squares for all samples.
float sum_power = 0.0f;
for (int ch = 0; ch < channels; ++ch) {
const float* channel_data = buffer.channel(ch);
for (int i = 0; i < frames; i++) {
const float sample = channel_data[i];
sum_power += sample * sample;
}
}
// Update accumulated average results, with clamping for sanity.
const float average_power =
std::max(0.0f, std::min(1.0f, sum_power / (frames * channels)));
// Convert average power level to dBFS units, and pin it down to zero if it
// is insignificantly small.
const float kInsignificantPower = 1.0e-10f; // -100 dBFS
const float power_dbfs = average_power < kInsignificantPower ?
-std::numeric_limits<float>::infinity() : 10.0f * log10f(average_power);
return power_dbfs;
}
#endif // AUDIO_POWER_MONITORING
} // namespace
namespace media {
// static
AudioInputController::Factory* AudioInputController::factory_ = nullptr;
AudioInputController::AudioInputController(EventHandler* handler,
SyncWriter* sync_writer,
UserInputMonitor* user_input_monitor,
const bool agc_is_enabled)
: creator_task_runner_(base::ThreadTaskRunnerHandle::Get()),
handler_(handler),
stream_(nullptr),
should_report_stats(0),
state_(CLOSED),
sync_writer_(sync_writer),
max_volume_(0.0),
user_input_monitor_(user_input_monitor),
agc_is_enabled_(agc_is_enabled),
#if defined(AUDIO_POWER_MONITORING)
power_measurement_is_enabled_(false),
log_silence_state_(false),
silence_state_(SILENCE_STATE_NO_MEASUREMENT),
#endif
prev_key_down_count_(0),
input_writer_(nullptr) {
DCHECK(creator_task_runner_.get());
}
AudioInputController::~AudioInputController() {
DCHECK_EQ(state_, CLOSED);
}
// static
scoped_refptr<AudioInputController> AudioInputController::Create(
AudioManager* audio_manager,
EventHandler* event_handler,
const AudioParameters& params,
const std::string& device_id,
UserInputMonitor* user_input_monitor) {
DCHECK(audio_manager);
if (!params.IsValid() || (params.channels() > kMaxInputChannels))
return nullptr;
if (factory_) {
return factory_->Create(
audio_manager, event_handler, params, user_input_monitor);
}
scoped_refptr<AudioInputController> controller(new AudioInputController(
event_handler, nullptr, user_input_monitor, false));
controller->task_runner_ = audio_manager->GetTaskRunner();
// Create and open a new audio input stream from the existing
// audio-device thread.
if (!controller->task_runner_->PostTask(
FROM_HERE,
base::Bind(&AudioInputController::DoCreate,
controller,
base::Unretained(audio_manager),
params,
device_id))) {
controller = nullptr;
}
return controller;
}
// static
scoped_refptr<AudioInputController> AudioInputController::CreateLowLatency(
AudioManager* audio_manager,
EventHandler* event_handler,
const AudioParameters& params,
const std::string& device_id,
SyncWriter* sync_writer,
UserInputMonitor* user_input_monitor,
const bool agc_is_enabled) {
DCHECK(audio_manager);
DCHECK(sync_writer);
if (!params.IsValid() || (params.channels() > kMaxInputChannels))
return nullptr;
// Create the AudioInputController object and ensure that it runs on
// the audio-manager thread.
scoped_refptr<AudioInputController> controller(new AudioInputController(
event_handler, sync_writer, user_input_monitor, agc_is_enabled));
controller->task_runner_ = audio_manager->GetTaskRunner();
// Create and open a new audio input stream from the existing
// audio-device thread. Use the provided audio-input device.
if (!controller->task_runner_->PostTask(
FROM_HERE,
base::Bind(&AudioInputController::DoCreateForLowLatency,
controller,
base::Unretained(audio_manager),
params,
device_id))) {
controller = nullptr;
}
return controller;
}
// static
scoped_refptr<AudioInputController> AudioInputController::CreateForStream(
const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
EventHandler* event_handler,
AudioInputStream* stream,
SyncWriter* sync_writer,
UserInputMonitor* user_input_monitor) {
DCHECK(sync_writer);
DCHECK(stream);
// Create the AudioInputController object and ensure that it runs on
// the audio-manager thread.
scoped_refptr<AudioInputController> controller(new AudioInputController(
event_handler, sync_writer, user_input_monitor, false));
controller->task_runner_ = task_runner;
if (!controller->task_runner_->PostTask(
FROM_HERE,
base::Bind(&AudioInputController::DoCreateForStream,
controller,
stream))) {
controller = nullptr;
}
return controller;
}
void AudioInputController::Record() {
task_runner_->PostTask(FROM_HERE, base::Bind(
&AudioInputController::DoRecord, this));
}
void AudioInputController::Close(const base::Closure& closed_task) {
DCHECK(!closed_task.is_null());
DCHECK(creator_task_runner_->BelongsToCurrentThread());
task_runner_->PostTaskAndReply(
FROM_HERE, base::Bind(&AudioInputController::DoClose, this), closed_task);
}
void AudioInputController::SetVolume(double volume) {
task_runner_->PostTask(FROM_HERE, base::Bind(
&AudioInputController::DoSetVolume, this, volume));
}
void AudioInputController::DoCreate(AudioManager* audio_manager,
const AudioParameters& params,
const std::string& device_id) {
DCHECK(task_runner_->BelongsToCurrentThread());
SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioInputController.CreateTime");
if (handler_)
handler_->OnLog(this, "AIC::DoCreate");
#if defined(AUDIO_POWER_MONITORING)
// Disable power monitoring for streams that run without AGC enabled to
// avoid adding logs and UMA for non-WebRTC clients.
power_measurement_is_enabled_ = agc_is_enabled_;
last_audio_level_log_time_ = base::TimeTicks::Now();
silence_state_ = SILENCE_STATE_NO_MEASUREMENT;
#endif
DoCreateForStream(audio_manager->MakeAudioInputStream(
params, device_id, base::Bind(&AudioInputController::LogMessage, this)));
}
void AudioInputController::DoCreateForLowLatency(AudioManager* audio_manager,
const AudioParameters& params,
const std::string& device_id) {
DCHECK(task_runner_->BelongsToCurrentThread());
#if defined(AUDIO_POWER_MONITORING)
// We only log silence state UMA stats for low latency mode and if we use a
// real device.
if (params.format() != AudioParameters::AUDIO_FAKE)
log_silence_state_ = true;
#endif
low_latency_create_time_ = base::TimeTicks::Now();
DoCreate(audio_manager, params, device_id);
}
void AudioInputController::DoCreateForStream(
AudioInputStream* stream_to_control) {
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK(!stream_);
stream_ = stream_to_control;
should_report_stats = 1;
if (!stream_) {
if (handler_)
handler_->OnError(this, STREAM_CREATE_ERROR);
LogCaptureStartupResult(CAPTURE_STARTUP_CREATE_STREAM_FAILED);
return;
}
if (stream_ && !stream_->Open()) {
stream_->Close();
stream_ = nullptr;
if (handler_)
handler_->OnError(this, STREAM_OPEN_ERROR);
LogCaptureStartupResult(CAPTURE_STARTUP_OPEN_STREAM_FAILED);
return;
}
// Set AGC state using mode in |agc_is_enabled_| which can only be enabled in
// CreateLowLatency().
#if defined(AUDIO_POWER_MONITORING)
bool agc_is_supported = false;
agc_is_supported = stream_->SetAutomaticGainControl(agc_is_enabled_);
// Disable power measurements on platforms that does not support AGC at a
// lower level. AGC can fail on platforms where we don't support the
// functionality to modify the input volume slider. One such example is
// Windows XP.
power_measurement_is_enabled_ &= agc_is_supported;
#else
stream_->SetAutomaticGainControl(agc_is_enabled_);
#endif
state_ = CREATED;
if (handler_)
handler_->OnCreated(this);
if (user_input_monitor_) {
user_input_monitor_->EnableKeyPressMonitoring();
prev_key_down_count_ = user_input_monitor_->GetKeyPressCount();
}
}
void AudioInputController::DoRecord() {
DCHECK(task_runner_->BelongsToCurrentThread());
SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioInputController.RecordTime");
if (state_ != CREATED)
return;
{
base::AutoLock auto_lock(lock_);
state_ = RECORDING;
}
if (handler_)
handler_->OnLog(this, "AIC::DoRecord");
stream_->Start(this);
if (handler_)
handler_->OnRecording(this);
}
void AudioInputController::DoClose() {
DCHECK(task_runner_->BelongsToCurrentThread());
SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioInputController.CloseTime");
// If we have already logged something, this does nothing.
// Otherwise, we haven't recieved data.
LogCaptureStartupResult(CAPTURE_STARTUP_NEVER_GOT_DATA);
if (state_ == CLOSED)
return;
// If this is a low-latency stream, log the total duration (since DoCreate)
// and add it to a UMA histogram.
if (!low_latency_create_time_.is_null()) {
base::TimeDelta duration =
base::TimeTicks::Now() - low_latency_create_time_;
UMA_HISTOGRAM_LONG_TIMES("Media.InputStreamDuration", duration);
if (handler_) {
std::string log_string =
base::StringPrintf("AIC::DoClose: stream duration=");
log_string += base::Int64ToString(duration.InSeconds());
log_string += " seconds";
handler_->OnLog(this, log_string);
}
}
DoStopCloseAndClearStream();
if (SharedMemoryAndSyncSocketMode())
sync_writer_->Close();
if (user_input_monitor_)
user_input_monitor_->DisableKeyPressMonitoring();
#if defined(AUDIO_POWER_MONITORING)
// Send UMA stats if enabled.
if (log_silence_state_)
LogSilenceState(silence_state_);
log_silence_state_ = false;
#endif
input_writer_ = nullptr;
state_ = CLOSED;
}
void AudioInputController::DoReportError() {
DCHECK(task_runner_->BelongsToCurrentThread());
if (handler_)
handler_->OnError(this, STREAM_ERROR);
}
void AudioInputController::DoSetVolume(double volume) {
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK_GE(volume, 0);
DCHECK_LE(volume, 1.0);
if (state_ != CREATED && state_ != RECORDING)
return;
// Only ask for the maximum volume at first call and use cached value
// for remaining function calls.
if (!max_volume_) {
max_volume_ = stream_->GetMaxVolume();
}
if (max_volume_ == 0.0) {
DLOG(WARNING) << "Failed to access input volume control";
return;
}
// Set the stream volume and scale to a range matched to the platform.
stream_->SetVolume(max_volume_ * volume);
}
void AudioInputController::OnData(AudioInputStream* stream,
const AudioBus* source,
uint32_t hardware_delay_bytes,
double volume) {
// |input_writer_| should only be accessed on the audio thread, but as a means
// to avoid copying data and posting on the audio thread, we just check for
// non-null here.
if (input_writer_) {
std::unique_ptr<AudioBus> source_copy =
AudioBus::Create(source->channels(), source->frames());
source->CopyTo(source_copy.get());
task_runner_->PostTask(
FROM_HERE,
base::Bind(
&AudioInputController::WriteInputDataForDebugging,
this,
base::Passed(&source_copy)));
}
// Now we have data, so we know for sure that startup was ok.
LogCaptureStartupResult(CAPTURE_STARTUP_OK);
{
base::AutoLock auto_lock(lock_);
if (state_ != RECORDING)
return;
}
bool key_pressed = false;
if (user_input_monitor_) {
size_t current_count = user_input_monitor_->GetKeyPressCount();
key_pressed = current_count != prev_key_down_count_;
prev_key_down_count_ = current_count;
DVLOG_IF(6, key_pressed) << "Detected keypress.";
}
// Use SharedMemory and SyncSocket if the client has created a SyncWriter.
// Used by all low-latency clients except WebSpeech.
if (SharedMemoryAndSyncSocketMode()) {
sync_writer_->Write(source, volume, key_pressed, hardware_delay_bytes);
#if defined(AUDIO_POWER_MONITORING)
// Only do power-level measurements if DoCreate() has been called. It will
// ensure that logging will mainly be done for WebRTC and WebSpeech
// clients.
if (!power_measurement_is_enabled_)
return;
// Perform periodic audio (power) level measurements.
if ((base::TimeTicks::Now() - last_audio_level_log_time_).InSeconds() >
kPowerMonitorLogIntervalSeconds) {
// Calculate the average power of the signal, or the energy per sample.
const float average_power_dbfs = AveragePower(*source);
// Add current microphone volume to log and UMA histogram.
const int mic_volume_percent = static_cast<int>(100.0 * volume);
// Use event handler on the audio thread to relay a message to the ARIH
// in content which does the actual logging on the IO thread.
task_runner_->PostTask(FROM_HERE,
base::Bind(&AudioInputController::DoLogAudioLevels,
this,
average_power_dbfs,
mic_volume_percent));
last_audio_level_log_time_ = base::TimeTicks::Now();
}
#endif
return;
}
// TODO(henrika): Investigate if we can avoid the extra copy here.
// (see http://crbug.com/249316 for details). AFAIK, this scope is only
// active for WebSpeech clients.
std::unique_ptr<AudioBus> audio_data =
AudioBus::Create(source->channels(), source->frames());
source->CopyTo(audio_data.get());
// Ownership of the audio buffer will be with the callback until it is run,
// when ownership is passed to the callback function.
task_runner_->PostTask(
FROM_HERE,
base::Bind(
&AudioInputController::DoOnData, this, base::Passed(&audio_data)));
}
void AudioInputController::DoOnData(std::unique_ptr<AudioBus> data) {
DCHECK(task_runner_->BelongsToCurrentThread());
if (handler_)
handler_->OnData(this, data.get());
}
void AudioInputController::DoLogAudioLevels(float level_dbfs,
int microphone_volume_percent) {
#if defined(AUDIO_POWER_MONITORING)
DCHECK(task_runner_->BelongsToCurrentThread());
if (!handler_)
return;
// Detect if the user has enabled hardware mute by pressing the mute
// button in audio settings for the selected microphone.
const bool microphone_is_muted = stream_->IsMuted();
if (microphone_is_muted) {
LogMicrophoneMuteResult(MICROPHONE_IS_MUTED);
handler_->OnLog(this, "AIC::OnData: microphone is muted!");
// Return early if microphone is muted. No need to adding logs and UMA stats
// of audio levels if we know that the micropone is muted.
return;
}
LogMicrophoneMuteResult(MICROPHONE_IS_NOT_MUTED);
std::string log_string = base::StringPrintf(
"AIC::OnData: average audio level=%.2f dBFS", level_dbfs);
static const float kSilenceThresholdDBFS = -72.24719896f;
if (level_dbfs < kSilenceThresholdDBFS)
log_string += " <=> low audio input level!";
handler_->OnLog(this, log_string);
UpdateSilenceState(level_dbfs < kSilenceThresholdDBFS);
UMA_HISTOGRAM_PERCENTAGE("Media.MicrophoneVolume", microphone_volume_percent);
log_string = base::StringPrintf(
"AIC::OnData: microphone volume=%d%%", microphone_volume_percent);
if (microphone_volume_percent < kLowLevelMicrophoneLevelPercent)
log_string += " <=> low microphone level!";
handler_->OnLog(this, log_string);
#endif
}
void AudioInputController::OnError(AudioInputStream* stream) {
// Handle error on the audio-manager thread.
task_runner_->PostTask(FROM_HERE, base::Bind(
&AudioInputController::DoReportError, this));
}
void AudioInputController::EnableDebugRecording(
AudioInputWriter* input_writer) {
task_runner_->PostTask(FROM_HERE, base::Bind(
&AudioInputController::DoEnableDebugRecording,
this,
input_writer));
}
void AudioInputController::DisableDebugRecording(
const base::Closure& callback) {
DCHECK(creator_task_runner_->BelongsToCurrentThread());
DCHECK(!callback.is_null());
task_runner_->PostTaskAndReply(
FROM_HERE,
base::Bind(&AudioInputController::DoDisableDebugRecording,
this),
callback);
}
void AudioInputController::DoStopCloseAndClearStream() {
DCHECK(task_runner_->BelongsToCurrentThread());
// Allow calling unconditionally and bail if we don't have a stream to close.
if (stream_ != nullptr) {
stream_->Stop();
stream_->Close();
stream_ = nullptr;
}
// The event handler should not be touched after the stream has been closed.
handler_ = nullptr;
}
#if defined(AUDIO_POWER_MONITORING)
void AudioInputController::UpdateSilenceState(bool silence) {
if (silence) {
if (silence_state_ == SILENCE_STATE_NO_MEASUREMENT) {
silence_state_ = SILENCE_STATE_ONLY_SILENCE;
} else if (silence_state_ == SILENCE_STATE_ONLY_AUDIO) {
silence_state_ = SILENCE_STATE_AUDIO_AND_SILENCE;
} else {
DCHECK(silence_state_ == SILENCE_STATE_ONLY_SILENCE ||
silence_state_ == SILENCE_STATE_AUDIO_AND_SILENCE);
}
} else {
if (silence_state_ == SILENCE_STATE_NO_MEASUREMENT) {
silence_state_ = SILENCE_STATE_ONLY_AUDIO;
} else if (silence_state_ == SILENCE_STATE_ONLY_SILENCE) {
silence_state_ = SILENCE_STATE_AUDIO_AND_SILENCE;
} else {
DCHECK(silence_state_ == SILENCE_STATE_ONLY_AUDIO ||
silence_state_ == SILENCE_STATE_AUDIO_AND_SILENCE);
}
}
}
void AudioInputController::LogSilenceState(SilenceState value) {
UMA_HISTOGRAM_ENUMERATION("Media.AudioInputControllerSessionSilenceReport",
value,
SILENCE_STATE_MAX + 1);
}
#endif
void AudioInputController::LogCaptureStartupResult(
CaptureStartupResult result) {
// Decrement shall_report_stats and check if it was 1 before decrement,
// which would imply that this is the first time this method is called
// after initialization. To avoid underflow, we
// also check if should_report_stats is one before decrementing.
if (base::AtomicRefCountIsOne(&should_report_stats) &&
!base::AtomicRefCountDec(&should_report_stats)) {
UMA_HISTOGRAM_ENUMERATION("Media.AudioInputControllerCaptureStartupSuccess",
result, CAPTURE_STARTUP_RESULT_MAX + 1);
}
}
void AudioInputController::DoEnableDebugRecording(
AudioInputWriter* input_writer) {
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK(!input_writer_);
input_writer_ = input_writer;
}
void AudioInputController::DoDisableDebugRecording() {
DCHECK(task_runner_->BelongsToCurrentThread());
input_writer_ = nullptr;
}
void AudioInputController::WriteInputDataForDebugging(
std::unique_ptr<AudioBus> data) {
DCHECK(task_runner_->BelongsToCurrentThread());
if (input_writer_)
input_writer_->Write(std::move(data));
}
void AudioInputController::LogMessage(const std::string& message) {
DCHECK(task_runner_->BelongsToCurrentThread());
handler_->OnLog(this, message);
}
} // namespace media
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
726674253b22b87aa94a1e36e7ae752b93c2539e | 719d411def1dff8a1872d9a1d0a62c650bd27006 | /include/cool/codegen/codegen_code_base.h | ae6f3e08db84fe0e29c1b616adb0f2d9cd09f12a | [
"MIT"
] | permissive | giulioborghesi/yacl-compiler | 6217e6fb923eb3984e306ce779945fd64e4a65dc | 8c6633202af39ebb3d56d38bd405d5558afb7783 | refs/heads/master | 2022-12-08T07:33:35.398168 | 2020-09-02T04:25:45 | 2020-09-02T04:25:45 | 251,518,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,426 | h | #ifndef COOL_CODEGEN_CODEGEN_CODE_BASE_H
#define COOL_CODEGEN_CODEGEN_CODE_BASE_H
#include <cool/codegen/codegen_base.h>
#include <cool/core/status.h>
#include <cool/ir/common.h>
#include <cool/ir/fwd.h>
#include <ostream>
namespace cool {
/// Forward declaration
class CodegenContext;
class CodegenCodePass : public CodegenBasePass {
public:
CodegenCodePass() = default;
virtual ~CodegenCodePass() override = default;
/// Program, class and attributes nodes
Status codegen(CodegenContext *context, MethodNode *node,
std::ostream *ios) final override;
/// Expressions nodes
Status codegen(CodegenContext *context, AssignmentExprNode *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, BinaryExprNode<ArithmeticOpID> *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, BinaryExprNode<ComparisonOpID> *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, BlockExprNode *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, BooleanExprNode *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, CaseBindingNode *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, CaseExprNode *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, DispatchExprNode *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, IdExprNode *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, IfExprNode *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, LetBindingNode *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, LetExprNode *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, LiteralExprNode<int32_t> *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, LiteralExprNode<std::string> *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, NewExprNode *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, StaticDispatchExprNode *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, UnaryExprNode *node,
std::ostream *ios) final override;
Status codegen(CodegenContext *context, WhileExprNode *node,
std::ostream *ios) final override;
private:
Status binaryEqualityCodegen(CodegenContext *context,
BinaryExprNode<ComparisonOpID> *node,
std::ostream *ios);
Status binaryInequalityCodegen(CodegenContext *context,
BinaryExprNode<ComparisonOpID> *node,
std::ostream *ios);
Status unaryEqualityCodegen(CodegenContext *context, UnaryExprNode *node,
std::ostream *ios);
Status unaryComplementCodegen(CodegenContext *context, UnaryExprNode *node,
std::ostream *ios);
};
} // namespace cool
#endif
| [
"giulio.borghesi.1981@gmail.com"
] | giulio.borghesi.1981@gmail.com |
9fa18be81a07117fc0f165428cdaa53b8b522880 | bddd16534ec08e99da7ea3bf2087e4c6d25acbb2 | /Data_Structures_and_Algorithms_Practice/sub_arrays.cpp | 869f34c6f3493b70ee9f921e9881a1235b968a39 | [] | no_license | VishwaP98/Competitive-Programming | f07264343731fdda7aaab2e11ca57263440652eb | 2430ab17f28a5888e09b89d060c4149d9fe8e34f | refs/heads/master | 2021-06-25T12:43:49.858603 | 2017-09-11T01:28:20 | 2017-09-11T01:28:20 | 103,061,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 581 | cpp | #include <stdio.h>
#include <deque>
int main(){
int a = 0;
scanf("%d", &a);
std::deque<int> queue;
int array[a];
for(int x = 0;x < a;x++){
int b = 0;
scanf("%d",&b);
array[x] = b;
}
int slide_factor = 0;
scanf("%d",&slide_factor);
for(int x = 0; x < a;x++){
while(!queue.empty() && queue.back() < array[x]){
queue.pop_back();
}
queue.push_back(array[x]);
if(x >= slide_factor - 1 && x < a - 1){
printf("%d ", queue.at(0));
if(queue.at(0) == array[x - slide_factor + 1]){
queue.pop_front();
}
}
}
printf("%d",queue.at(0));
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
dd81b368869f0eb8be9c9685f2a4f591b230fb52 | bdaea74bcbae474a1f54fd8699a0c4076b842910 | /span.h | f5e1fb9245780a31b695529a3ce63bbfc21d9d6e | [
"BSD-3-Clause"
] | permissive | questor/eastl | 5e1527d38e39db03300224f9f86657ecd99e8184 | fa8769c32cb058586b41e5db4da8b8fd777d2284 | refs/heads/master | 2022-08-13T04:58:33.344962 | 2022-07-20T19:41:51 | 2022-07-20T19:41:51 | 9,006,280 | 16 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 15,932 | h | /////////////////////////////////////////////////////////////////////////////
// Copyright (c) Electronic Arts Inc. All rights reserved.
/////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// This file implements the eastl::span which is part of the C++ standard
// STL library specification.
//
// eastl::span is a non-owning container that refers to a contiguous block of
// memory. It bundles up the classic pattern of a pointer and a size into a
// single type. A span can either have a static extent, in which case the
// number of elements in the sequence is known and encoded in the type, or a
// dynamic extent.
//
// http://en.cppreference.com/w/cpp/container/span
// http://eel.is/c++draft/views#span.syn
///////////////////////////////////////////////////////////////////////////////
#ifndef EASTL_SPAN_H
#define EASTL_SPAN_H
#if defined(EASTL_PRAGMA_ONCE_SUPPORTED)
#pragma once
#endif
#include <eastl/internal/config.h>
#include <eastl/type_traits.h>
#include <eastl/iterator.h>
#include <eastl/array.h>
namespace eastl
{
static EA_CONSTEXPR size_t dynamic_extent = size_t(-1);
namespace Internal
{
// HasSizeAndData
//
// custom type trait to determine if eastl::data(Container) and eastl::size(Container) are well-formed.
//
template <typename, typename = void>
struct HasSizeAndData : eastl::false_type {};
template <typename T>
struct HasSizeAndData<T, void_t<decltype(eastl::size(eastl::declval<T>())), decltype(eastl::data(eastl::declval<T>()))>> : eastl::true_type {};
// SubspanExtent
//
// Integral constant that calculates the resulting extent of a templated subspan operation.
//
// If Count is not dynamic_extent then SubspanExtent::value is Count,
// otherwise, if Extent is not dynamic_extent, SubspanExtent::value is (Extent - Offset),
// otherwise, SubspanExtent::value is dynamic_extent.
//
template<size_t Extent, size_t Offset, size_t Count>
struct SubspanExtent : eastl::integral_constant<size_t, (Count != dynamic_extent ? Count : (Extent != dynamic_extent ? (Extent - Offset) : dynamic_extent))> {};
}
template <typename T, size_t Extent = eastl::dynamic_extent>
class span
{
public:
typedef T element_type;
typedef remove_cv_t<T> value_type;
typedef eastl_size_t index_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T* iterator;
typedef const T* const_iterator;
typedef eastl::reverse_iterator<iterator> reverse_iterator;
typedef eastl::reverse_iterator<const_iterator> const_reverse_iterator;
static EA_CONSTEXPR size_t extent = Extent;
// constructors / destructor
EA_CONSTEXPR span() EASTL_NOEXCEPT = default;
EA_CONSTEXPR span(const span& other) EASTL_NOEXCEPT = default;
EA_CONSTEXPR span(pointer ptr, index_type count);
EA_CONSTEXPR span(pointer pBegin, pointer pEnd);
~span() EASTL_NOEXCEPT = default;
// copy-assignment operator
EA_CPP14_CONSTEXPR span& operator=(const span& other) EASTL_NOEXCEPT = default;
// conversion constructors for c-array and eastl::array
template <size_t N> EA_CONSTEXPR span(element_type (&arr)[N]) EASTL_NOEXCEPT;
template <size_t N> EA_CONSTEXPR span(eastl::array<value_type, N>& arr) EASTL_NOEXCEPT;
template <size_t N> EA_CONSTEXPR span(const eastl::array<value_type, N>& arr) EASTL_NOEXCEPT;
// SfinaeForGenericContainers
//
template <typename Container>
using SfinaeForGenericContainers =
enable_if_t<!is_same_v<Container, span> && !is_same_v<Container, array<value_type>> &&
!is_array_v<Container> &&
Internal::HasSizeAndData<Container>::value &&
is_convertible_v<remove_pointer_t<decltype(eastl::data(eastl::declval<Container&>()))> (*)[], element_type (*)[]>>;
// generic container conversion constructors
template <typename Container, typename = SfinaeForGenericContainers<Container>>
EA_CONSTEXPR span(Container& cont);
template <typename Container, typename = SfinaeForGenericContainers<const Container>>
EA_CONSTEXPR span(const Container& cont);
template <typename U, size_t N, typename = enable_if_t<(Extent == eastl::dynamic_extent || N == Extent) && (is_convertible_v<U(*)[], element_type(*)[]>)>>
EA_CONSTEXPR span(const span<U, N>& s) EASTL_NOEXCEPT;
// subviews
template<size_t Count>
EA_CPP14_CONSTEXPR span<element_type, Count> first() const;
EA_CPP14_CONSTEXPR span<element_type, dynamic_extent> first(size_t Count) const;
template<size_t Count>
EA_CPP14_CONSTEXPR span<element_type, Count> last() const;
EA_CPP14_CONSTEXPR span<element_type, dynamic_extent> last(size_t Count) const;
template <size_t Offset, size_t Count = dynamic_extent>
EA_CONSTEXPR span<element_type, Internal::SubspanExtent<Extent, Offset, Count>::value> subspan() const;
EA_CONSTEXPR span<element_type, dynamic_extent> subspan(size_t Offset, size_t Count = dynamic_extent) const;
// observers
EA_CONSTEXPR pointer data() const EASTL_NOEXCEPT;
EA_CONSTEXPR index_type size() const EASTL_NOEXCEPT;
EA_CONSTEXPR index_type size_bytes() const EASTL_NOEXCEPT;
EA_CONSTEXPR bool empty() const EASTL_NOEXCEPT;
// subscript operators, element access
EA_CONSTEXPR reference front() const;
EA_CONSTEXPR reference back() const;
EA_CONSTEXPR reference operator[](index_type idx) const;
EA_CONSTEXPR reference operator()(index_type idx) const;
// iterator support
EA_CONSTEXPR iterator begin() const EASTL_NOEXCEPT;
EA_CONSTEXPR iterator end() const EASTL_NOEXCEPT;
EA_CONSTEXPR const_iterator cbegin() const EASTL_NOEXCEPT;
EA_CONSTEXPR const_iterator cend() const EASTL_NOEXCEPT;
EA_CONSTEXPR reverse_iterator rbegin() const EASTL_NOEXCEPT;
EA_CONSTEXPR reverse_iterator rend() const EASTL_NOEXCEPT;
EA_CONSTEXPR const_reverse_iterator crbegin() const EASTL_NOEXCEPT;
EA_CONSTEXPR const_reverse_iterator crend() const EASTL_NOEXCEPT;
private:
pointer mpData = nullptr;
index_type mnSize = 0;
private:
EA_CONSTEXPR bool bounds_check(size_t) const; // utility used in asserts
};
///////////////////////////////////////////////////////////////////////////
// template deduction guides
///////////////////////////////////////////////////////////////////////////
#ifdef __cpp_deduction_guides
template<class T, size_t N> span(T (&)[N]) -> span <T, N>;
template<class T, size_t N> span(array<T, N>&) -> span <T, N>;
template<class T, size_t N> span(const array<T, N>&) -> span <const T, N>;
template<class Container> span(Container&) -> span <typename Container::value_type>;
template<class Container> span(const Container&) -> span <const typename Container::value_type>;
#endif
///////////////////////////////////////////////////////////////////////////
// comparison operators
///////////////////////////////////////////////////////////////////////////
template <class T, size_t X, class U, size_t Y>
EA_CONSTEXPR bool operator==(span<T, X> l, span<U, Y> r)
{
return (l.size() == r.size()) && eastl::equal(l.begin(), l.end(), r.begin());
}
template <class T, size_t X, class U, size_t Y>
EA_CONSTEXPR bool operator<(span<T, X> l, span<U, Y> r)
{
return eastl::lexicographicalCompare(l.begin(), l.end(), r.begin(), r.end());
}
template <class T, size_t X, class U, size_t Y>
EA_CONSTEXPR bool operator!=(span<T, X> l, span<U, Y> r) { return !(l == r); }
template <class T, size_t X, class U, size_t Y>
EA_CONSTEXPR bool operator<=(span<T, X> l, span<U, Y> r) { return !(r < l); }
template <class T, size_t X, class U, size_t Y>
EA_CONSTEXPR bool operator>(span<T, X> l, span<U, Y> r) { return r < l; }
template <class T, size_t X, class U, size_t Y>
EA_CONSTEXPR bool operator>=(span<T, X> l, span<U, Y> r) { return !(l < r); }
///////////////////////////////////////////////////////////////////////////
// ctor implementations
///////////////////////////////////////////////////////////////////////////
template <typename T, size_t Extent>
EA_CONSTEXPR span<T, Extent>::span(pointer ptr, index_type size)
: mpData(ptr), mnSize(size)
{
}
template <typename T, size_t Extent>
EA_CONSTEXPR span<T, Extent>::span(pointer pBegin, pointer pEnd)
: mpData(pBegin), mnSize(static_cast<index_type>(pEnd - pBegin))
{
}
template <typename T, size_t Extent>
template <size_t N>
EA_CONSTEXPR span<T, Extent>::span(element_type(&arr)[N]) EASTL_NOEXCEPT
: span(arr, static_cast<index_type>(N))
{
}
template <typename T, size_t Extent>
template <size_t N>
EA_CONSTEXPR span<T, Extent>::span(eastl::array<value_type, N> &arr) EASTL_NOEXCEPT
: span(arr.data(), arr.size())
{
}
template <typename T, size_t Extent>
template <size_t N>
EA_CONSTEXPR span<T, Extent>::span(const eastl::array<value_type, N>& arr) EASTL_NOEXCEPT
: span(arr.data(), arr.size())
{
}
template <typename T, size_t Extent>
template <typename Container, typename>
EA_CONSTEXPR span<T, Extent>::span(Container& cont)
: span(static_cast<pointer>(eastl::data(cont)), static_cast<index_type>(eastl::size(cont)))
{
}
template <typename T, size_t Extent>
template <typename Container, typename>
EA_CONSTEXPR span<T, Extent>::span(const Container& cont)
: span(static_cast<pointer>(eastl::data(cont)), static_cast<index_type>(eastl::size(cont)))
{
}
template <typename T, size_t Extent>
template <typename U, size_t N, typename>
EA_CONSTEXPR span<T, Extent>::span(const span<U, N>& s) EASTL_NOEXCEPT
: span(s.data(), s.size())
{
}
///////////////////////////////////////////////////////////////////////////
// member function implementations
///////////////////////////////////////////////////////////////////////////
template <typename T, size_t Extent>
EA_CONSTEXPR typename span<T, Extent>::pointer span<T, Extent>::data() const EASTL_NOEXCEPT
{
return mpData;
}
template <typename T, size_t Extent>
EA_CONSTEXPR typename span<T, Extent>::index_type span<T, Extent>::size() const EASTL_NOEXCEPT
{
return mnSize;
}
template <typename T, size_t Extent>
EA_CONSTEXPR typename span<T, Extent>::index_type span<T, Extent>::size_bytes() const EASTL_NOEXCEPT
{
return size() * sizeof(element_type);
}
template <typename T, size_t Extent>
EA_CONSTEXPR bool span<T, Extent>::empty() const EASTL_NOEXCEPT
{
return size() == 0;
}
template <typename T, size_t Extent>
EA_CONSTEXPR typename span<T, Extent>::reference span<T, Extent>::front() const
{
EASTL_ASSERT_MSG(!empty(), "undefined behavior accessing an empty span");
return mpData[0];
}
template <typename T, size_t Extent>
EA_CONSTEXPR typename span<T, Extent>::reference span<T, Extent>::back() const
{
EASTL_ASSERT_MSG(!empty(), "undefined behavior accessing an empty span");
return mpData[mnSize - 1];
}
template <typename T, size_t Extent>
EA_CONSTEXPR typename span<T, Extent>::reference span<T, Extent>::operator[](index_type idx) const
{
EASTL_ASSERT_MSG(!empty(), "undefined behavior accessing an empty span");
EASTL_ASSERT_MSG(bounds_check(idx), "undefined behavior accessing out of bounds");
return mpData[idx];
}
template <typename T, size_t Extent>
EA_CONSTEXPR typename span<T, Extent>::reference span<T, Extent>::operator()(index_type idx) const
{
EASTL_ASSERT_MSG(!empty(), "undefined behavior accessing an empty span");
EASTL_ASSERT_MSG(bounds_check(idx), "undefined behavior accessing out of bounds");
return mpData[idx];
}
template <typename T, size_t Extent>
EA_CONSTEXPR typename span<T, Extent>::iterator span<T, Extent>::begin() const EASTL_NOEXCEPT
{
return mpData;
}
template <typename T, size_t Extent>
EA_CONSTEXPR typename span<T, Extent>::iterator span<T, Extent>::end() const EASTL_NOEXCEPT
{
return mpData + mnSize;
}
template <typename T, size_t Extent>
EA_CONSTEXPR typename span<T, Extent>::const_iterator span<T, Extent>::cbegin() const EASTL_NOEXCEPT
{
return mpData;
}
template <typename T, size_t Extent>
EA_CONSTEXPR typename span<T, Extent>::const_iterator span<T, Extent>::cend() const EASTL_NOEXCEPT
{
return mpData + mnSize;
}
template <typename T, size_t Extent>
EA_CONSTEXPR typename span<T, Extent>::reverse_iterator span<T, Extent>::rbegin() const EASTL_NOEXCEPT
{
return reverse_iterator(mpData + mnSize);
}
template <typename T, size_t Extent>
EA_CONSTEXPR typename span<T, Extent>::reverse_iterator span<T, Extent>::rend() const EASTL_NOEXCEPT
{
return reverse_iterator(mpData);
}
template <typename T, size_t Extent>
EA_CONSTEXPR typename span<T, Extent>::const_reverse_iterator span<T, Extent>::crbegin() const EASTL_NOEXCEPT
{
return const_reverse_iterator(mpData + mnSize);
}
template <typename T, size_t Extent>
EA_CONSTEXPR typename span<T, Extent>::const_reverse_iterator span<T, Extent>::crend() const EASTL_NOEXCEPT
{
return const_reverse_iterator(mpData);
}
template <typename T, size_t Extent>
template <size_t Count>
EA_CPP14_CONSTEXPR span<typename span<T, Extent>::element_type, Count> span<T, Extent>::first() const
{
EASTL_ASSERT_MSG(bounds_check(Count), "undefined behavior accessing out of bounds");
return {data(), static_cast<index_type>(Count)};
}
template <typename T, size_t Extent>
EA_CPP14_CONSTEXPR span<typename span<T, Extent>::element_type, dynamic_extent>
span<T, Extent>::first(size_t sz) const
{
EASTL_ASSERT_MSG(bounds_check(sz), "undefined behavior accessing out of bounds");
return {data(), static_cast<index_type>(sz)};
}
template <typename T, size_t Extent>
template <size_t Count>
EA_CPP14_CONSTEXPR span<typename span<T, Extent>::element_type, Count> span<T, Extent>::last() const
{
EASTL_ASSERT_MSG(bounds_check(Count), "undefined behavior accessing out of bounds");
return {data() + size() - Count, static_cast<index_type>(Count)};
}
template <typename T, size_t Extent>
EA_CPP14_CONSTEXPR span<typename span<T, Extent>::element_type, dynamic_extent>
span<T, Extent>::last(size_t sz) const
{
EASTL_ASSERT_MSG(bounds_check(sz), "undefined behavior accessing out of bounds");
return {data() + size() - sz, static_cast<index_type>(sz)};
}
template <typename T, size_t Extent>
template <size_t Offset, size_t Count>
EA_CONSTEXPR span<typename span<T, Extent>::element_type, Internal::SubspanExtent<Extent, Offset, Count>::value>
span<T, Extent>::subspan() const
{
EASTL_ASSERT_MSG(bounds_check(Offset), "undefined behaviour accessing out of bounds");
EASTL_ASSERT_MSG(Count == dynamic_extent || Count <= (size() - Offset), "undefined behaviour exceeding size of span");
return {data() + Offset, eastl_size_t(Count == dynamic_extent ? size() - Offset : Count)};
}
template <typename T, size_t Extent>
EA_CONSTEXPR span<typename span<T, Extent>::element_type, dynamic_extent>
span<T, Extent>::subspan(size_t offset, size_t count) const
{
EASTL_ASSERT_MSG(bounds_check(offset), "undefined behaviour accessing out of bounds");
EASTL_ASSERT_MSG(count == dynamic_extent || count <= (size() - offset), "undefined behaviour exceeding size of span");
return {data() + offset, eastl_size_t(count == dynamic_extent ? size() - offset : count)};
}
template <typename T, size_t Extent>
EA_CONSTEXPR bool span<T, Extent>::bounds_check(size_t sz) const
{
return (sz >= 0 && sz < size());
}
}
#endif // EASTL_SPAN_H
| [
"questor@inter"
] | questor@inter |
8f903b3be1fdff26f88310437632ca29bab0180b | 39d53b9cb795bea241afb5ef38bd1a77ff01f25a | /Tokens/Add.cpp | 002d1adcb62ad45f5c5ee190f1ee778dbf704564 | [] | no_license | tobme/recipe-compiler | b5a38fd220fa4b36661f6f3974c9c9ca1b8a710c | 3532fd5dfaa5a9f78e2f3d8247573a1317ac3da6 | refs/heads/master | 2020-08-24T11:43:15.385747 | 2019-10-31T14:50:24 | 2019-10-31T14:50:24 | 216,819,381 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38 | cpp | #include "Add.h"
Add::~Add()
{
}
| [
"tobbemellberg@hotmail.se"
] | tobbemellberg@hotmail.se |
1f8d673000d14e45a8a00e15871fa002ac5df44d | c0f130f0e3619433753325af1ba56c8a4e99c22d | /include/mme-app/contextManager/mmeSvcReqProcedureCtxtManager.h | 9c589cf500e81471e7a44701939b127230da0368 | [
"Apache-2.0"
] | permissive | praj527/Nucleus | 555309fcb754c435f16d6007863103198b1e31fa | bc112f63c1e1ff42ea5276dd30a101b16dcb3a06 | refs/heads/master | 2022-11-12T21:33:35.861170 | 2020-06-30T12:18:14 | 2020-06-30T12:18:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,158 | h | /*
* Copyright 2019-present, Infosys Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __MmeSvcReqProcedureCtxtManager__
#define __MmeSvcReqProcedureCtxtManager__
/******************************************************
* mmeSvcReqProcedureCtxtManager.h
* This is an auto generated file.
* Please do not edit this file.
* All edits to be made through template source file
* <TOP-DIR/scripts/SMCodeGen/templates/ctxtManagerTmpls/blockPoolManager.h.tt>
***************************************/
#include "memPoolManager.h"
namespace mme
{
class MmeSvcReqProcedureCtxt;
class MmeSvcReqProcedureCtxtManager
{
public:
/****************************************
* MmeSvcReqProcedureCtxtManager
* constructor
****************************************/
MmeSvcReqProcedureCtxtManager(int numOfBlocks);
/****************************************
* MmeSvcReqProcedureCtxtManager
* Destructor
****************************************/
~MmeSvcReqProcedureCtxtManager();
/******************************************
* allocateMmeSvcReqProcedureCtxt
* allocate MmeSvcReqProcedureCtxt data block
******************************************/
MmeSvcReqProcedureCtxt* allocateMmeSvcReqProcedureCtxt();
/******************************************
* deallocateMmeSvcReqProcedureCtxt
* deallocate a MmeSvcReqProcedureCtxt data block
******************************************/
void deallocateMmeSvcReqProcedureCtxt(MmeSvcReqProcedureCtxt* MmeSvcReqProcedureCtxtp );
private:
cmn::memPool::MemPoolManager<MmeSvcReqProcedureCtxt> poolManager_m;
};
};
#endif
| [
"anjana_sreekumar@infosys.com"
] | anjana_sreekumar@infosys.com |
4cfd8f2b4a297b618eb25a5939a89c3d602a7cb4 | 278933e5750f3e90167fa14e9c62363e0ae9a7d0 | /libraries/MotorMasterSlave/SlaveVersion001/SlaveVersion001/SlaveVersion001.ino | 227d931253fdb01475a86c2a75e33e327f662704 | [] | no_license | ElliotHYLee/lee_5275 | e81f7c9fd943f83da9ee495bce8e6bd8c81dda4d | caaeb2b07ec8af10c9403fb97a519d7348646a1f | refs/heads/master | 2021-03-27T17:38:27.621124 | 2015-03-16T20:29:01 | 2015-03-16T20:29:01 | 23,250,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,185 | ino | /*
motor 1 = motor[0] = pin 2
motot 2 = motor[1] = pin 3
motor 3 = motor[2] = pin 4
motor 4 = motor[3] = pin 5
*/
int motor[] = {2,3,4,5};
int pulse=0;
int STOP = 0;
int analogPin = A0;
void setESC(int motor);
void speedESC(int motor, int pulse);
void setup()
{
motor[0] = 6;
Serial.begin(9600);
pinMode(motor[0], OUTPUT);
pinMode(motor[1], OUTPUT);
pinMode(motor[2], OUTPUT);
pinMode(motor[3], OUTPUT);
pinMode(analogPin, INPUT);
setESC(motor[0]);
}
void loop()
{
int incoming = analogRead(analogPin);
Serial.println(incoming);
// speedESC(motor[1],1180);
}
/**
* ESC setup for setup part. Only needs one-time call
*/
void setESC(int motor)
{
for (pulse = 0; pulse <=500; pulse +=1)
{
// HIGH and LOW: alternating signal: generating PWM!
digitalWrite(motor, HIGH);
delayMicroseconds(1100);
digitalWrite(motor, LOW);
delay(20); //required for setup
}
}
/**
* ESC setup for setup part. Only needs one-time call
* @param motor ESC motor number 1~4
* @param Pulse Pulse is a kind of speed.
*/
void speedESC(int motor, int pulse)
{
digitalWrite(motor, HIGH);
delayMicroseconds(pulse);
digitalWrite(motor, LOW);
}
| [
"hylee101001@gmail.com"
] | hylee101001@gmail.com |
a3c2d60f924b6ebc1480ac2e04eaaa49d4cf312b | c5595499a6b1b9f3623a7909fc06e669f564f81c | /2019/day19/part1.cpp | d829d211f4ea05159b615f352876f5075f1b3e53 | [] | no_license | rokcej/advent-of-code | 9ffc5ae8260c16cef859a0932a442afed755f4de | dee59d96fe4bd02fedef1bb87fa13b75fec05d7c | refs/heads/master | 2023-01-20T20:51:20.765413 | 2023-01-14T17:11:57 | 2023-01-14T17:11:57 | 160,039,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,199 | cpp | #include <iostream>
#include <vector>
#include <unordered_map>
typedef long long ll;
typedef std::unordered_map<ll, ll> Prog;
int digit(int val, int n) {
int div = 1;
for (int i = 0; i < n; ++i)
div *= 10;
return (val / div) % 10;
}
void get_params(std::vector<ll>& params, int num_params, int write_param, Prog& program, ll pc, ll rb) {
ll modes = program[pc] / 100;
for (int i = 0; i < num_params; ++i) {
ll param = program[pc+i+1];
ll mode = digit(modes, i);
ll val;
if (i == write_param) {
val = param;
if (mode == 2)
val += rb;
} else {
if (mode == 0) // Position mode
val = program[param];
else if (mode == 1) // Immediate mode
val = param;
else // Relative mode
val = program[param + rb];
}
params.push_back(val);
}
}
class Intcode {
private:
Prog program;
ll pc = 0; // Program counter
ll rb = 0; // Relative base
ll output = 0;
public:
bool running = true;
Intcode(Prog& program) {
this->program = program;
}
ll execute(std::vector<ll>& inputs) {
ll input_counter = 0; // Input counter
while (running) {
ll opcode = program[pc] % 100;
std::vector<ll> params;
switch (opcode) {
case 1: // Add
get_params(params, 3, 2, program, pc, rb);
program[params[2]] = params[0] + params[1];
pc += 4;
break;
case 2: // Multiply
get_params(params, 3, 2, program, pc, rb);
program[params[2]] = params[0] * params[1];
pc += 4;
break;
case 3: // Input
get_params(params, 1, 0, program, pc, rb);
program[params[0]] = inputs[input_counter++];
pc += 2;
break;
case 4: // Output
get_params(params, 1, -1, program, pc, rb);
output = params[0];
pc += 2;
return output;
break;
case 5: // Jump-if-true
get_params(params, 2, -1, program, pc, rb);
if (params[0] != 0)
pc = params[1];
else
pc += 3;
break;
case 6: // Jump-if-false
get_params(params, 2, -1, program, pc, rb);
if (params[0] == 0)
pc = params[1];
else
pc += 3;
break;
case 7: // Less than
get_params(params, 3, 2, program, pc, rb);
if (params[0] < params[1])
program[params[2]] = 1;
else
program[params[2]] = 0;
pc += 4;
break;
case 8: // Equals
get_params(params, 3, 2, program, pc, rb);
if (params[0] == params[1])
program[params[2]] = 1;
else
program[params[2]] = 0;
pc += 4;
break;
case 9: // Relative base
get_params(params, 1, -1, program, pc, rb);
rb += params[0];
pc += 2;
break;
case 99: // Terminate
running = false;
//pc += 1;
break;
}
}
return output;
}
};
int main() {
Prog program;
int idx = 0;
for (ll n; std::cin >> n;) {
program[idx++] = n;
std::cin.ignore(); // Ignore comma
}
int sum = 0;
for (int y = 0; y < 50; ++y) {
for (int x = 0; x < 50; ++x) {
Intcode comp(program);
std::vector<ll> inputs = { (ll)x, (ll)y };
int status = (int)comp.execute(inputs);
if (status == 1)
++sum;
}
}
std::cout << sum << std::endl;
return 0;
}
| [
"rokcej1997@gmail.com"
] | rokcej1997@gmail.com |
c6e9eb0e8f73065fe53797d48b7320bb7f6d7cee | 4f66f2b5c7dcf1a7a97e35fa25fc1e182d0e24a9 | /source/gloperate-text/include/gloperate-text/FontImporter.h | a6bdc12ff21d5de0be82fb189fc5f99fcc212c70 | [
"MIT"
] | permissive | p-otto/gloperate | 175c6743fb136aaa0b7a331c5f2247be05588dbd | e2de9e53b995e3f4a30c292ac59e76184fbddf35 | refs/heads/master | 2021-01-18T09:17:14.284841 | 2016-03-18T10:26:46 | 2016-03-18T10:26:46 | 40,965,291 | 0 | 0 | null | 2015-08-18T10:16:39 | 2015-08-18T10:16:39 | null | UTF-8 | C++ | false | false | 1,002 | h |
#pragma once
#include <string>
#include <iosfwd>
#include <gloperate-text/gloperate-text_api.h>
namespace gloperate
{
class ResourceManager;
} // namespace gloperate
namespace gloperate_text
{
class FontFace;
class GLOPERATE_TEXT_API FontImporter
{
public:
FontImporter(gloperate::ResourceManager & resourceManager);
FontFace * loadFont(const std::string & filename);
protected:
void handleInfo(std::stringstream & stream, FontFace * font);
void handleCommon(std::stringstream & stream, FontFace * font);
void handlePage(std::stringstream & stream, FontFace * font, const std::string & filename);
void handleChars(std::stringstream & stream, FontFace * font);
void handleChar(std::stringstream & stream, FontFace * font);
void handleKernings(std::stringstream & stream, FontFace * font);
void handleKerning(std::stringstream & stream, FontFace * font);
protected:
gloperate::ResourceManager & m_resourceManager;
};
} // namespace gloperate_text
| [
"willy.scheibel@hpi.de"
] | willy.scheibel@hpi.de |
ba0826755d2ad6dc1c7b813754b48612938ec8a5 | ea4f2445a0c97b427e5827138246129f28059a3d | /cpp/TriboolExample.cpp | a09c3e2b0b72947ceb7be1823db4255578b29a2b | [
"MIT"
] | permissive | so61pi/examples | 27cfe8a3e7712b25d2f344312f64fd4d4bdeeca3 | 38e2831cd6517864fc05f499f72fbb4ff6ae27c0 | refs/heads/master | 2023-01-22T04:13:27.785531 | 2020-04-30T14:07:36 | 2020-04-30T14:07:36 | 116,532,548 | 5 | 1 | MIT | 2023-01-05T00:47:46 | 2018-01-07T02:56:36 | C | UTF-8 | C++ | false | false | 1,428 | cpp | #include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include <boost/logic/tribool.hpp>
boost::tribool g_status{ boost::indeterminate };
std::mutex g_statusMutex{};
//
// working thread
//
void WorkThread() {
std::chrono::system_clock c{};
// working...
std::this_thread::sleep_for(std::chrono::seconds{ 5 });
// ... and set the return state (randomly)
std::lock_guard<std::mutex> lg{ g_statusMutex };
g_status = (c.to_time_t(c.now()) % 2 == 0);
}
int main() {
// start working thread
std::thread t(WorkThread);
while (true) {
// sleep
std::this_thread::sleep_for(std::chrono::milliseconds{ 500 });
//
// get job status
// can use indeterminate function instead
//
// if (boost::indeterminate(g_status)) {
// // indeterminate status
// std::cout << "Still working.\n";
// }
//
std::lock_guard<std::mutex> lg{ g_statusMutex };
if (g_status) {
// true state
std::cout << "Job done successfully.\n";
break;
}
else if (!g_status) {
// false state
std::cout << "Job done unsuccessfully.\n";
break;
}
else {
// indeterminate state
std::cout << "Still working.\n";
}
}
// wait for working thread
t.join();
}
| [
"so61pi.re@gmail.com"
] | so61pi.re@gmail.com |
71bd53da85c4225ea2dd18af9f5f44c31057ca18 | be4951f41d038c0e1d316d9fe0c26902a7c0548f | /Source code/CFileIO.cpp | b8b09a03e0b13add166157514a7052de5d255d77 | [] | no_license | geoseb94/Navigation-System | f61741fbc1124901fbf495061764a5d1545c9720 | b6f080b0254d0c18504f365798f53b1a65fb0638 | refs/heads/master | 2022-04-29T02:07:30.741550 | 2020-04-30T22:22:47 | 2020-04-30T22:22:47 | 260,322,786 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,311 | cpp | /***************************************************************************
*============= Copyright by Darmstadt University of Applied Sciences =======
****************************************************************************
* Filename : CFILEIO.CPP
* Author : George Sebastian
* Description : CFileIO provides some basic text file input and output operations
* for the ease of the end user
* Provides APIs for opening,closing,reading and writing a line to file
****************************************************************************/
#include <iostream>
#include <fstream>
using namespace std;
#include "CFileIO.h"
/**
* Constructor of CFileIO class
* Initializes attributes with some initial value
* @returnvalue no value
*/
CFileIO::CFileIO()
{
m_direction = UNDEF;
m_file.clear();
}
/**
* Constructor of CFileIO class with parameters
* @param const string& fileName : IN name of the file
* @param const t_direction& direction : IN direction of File operation
* @returnvalue no value
*/
CFileIO::CFileIO(const string& fileName, const t_direction& direction)
{
if (!openFile(fileName, direction))
// checking error condition
{
cout << "Error opening file" << endl;
}
}
/**
* Destructor of CFileIO class
* @returnvalue no value
*/
CFileIO::~CFileIO()
{
closeFile();
}
/**
* Function for opening the file and sets the direction of
* file operations as mentioned by user
* @param const string& fileName : IN name of the file to be opend
* @param const t_direction& direction : IN direction for file operations
* @returnvalue true if file is opened successfully
*/
bool CFileIO::openFile(const string& fileName, const t_direction& direction)
{
switch (direction)
{
case IN:
m_file.open(fileName.c_str(), fstream::in); // Open the file and sets file operation direction
m_file.seekg(0); // Go to the first position
break;
case OUT:
m_file.open(fileName.c_str(), fstream::out); // Open the file and sets file operation direction
m_file.seekp(0);
break;
default:
;
}
m_direction = direction;
return true;
}
/**
* Function reads a single line from a file
* @param string& line : OUT line read from the file
* @returnvalue true if line is read successfully
*/
bool CFileIO::readLineFromFile(string& line)
{
if ((m_file.is_open()) && (!m_file.eof()))
// file is open and not at end of the file
{
getline(m_file, line); // reading a single line from file
return true;
}
return false;
}
/**
* Function writes a single line to the file
* @param const string& line : IN line to be written to the file
* @returnvalue true if write operation is successful
*/
bool CFileIO::writeLineToFile(const string& line)
{
if (m_file.is_open())
// file is open
{
m_file << line << endl; // Write a single line, 'endl' is important here
return true;
}
else
// file is not open
{
return false;
}
}
/**
* Function for closing the file
* @returnvalue true if closing operation is done successfully
*/
bool CFileIO::closeFile()
{
if (m_file.is_open())
// file is open
m_file.close();
return true;
}
| [
"noreply@github.com"
] | noreply@github.com |
2c39d9f10128fd2372f5a66a381c44957e612e61 | 8dd866d72702d23012ddddfe6ab37452bca8cd50 | /src/vg_util.cpp | 8111a04b5f96f21b491fe826c1d6634efc5e26f8 | [
"BSD-2-Clause"
] | permissive | Happy-Ferret/vg-renderer | ba045badd68a6feb29de0bf666b6383731d21676 | 6a48691559b834923c0140a39ec9cacac78e9112 | refs/heads/master | 2020-03-27T16:25:41.593588 | 2018-08-11T10:27:16 | 2018-08-11T10:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,809 | cpp | #include "vg_util.h"
#include <vg/vg.h>
#include <bx/bx.h>
#if VG_CONFIG_ENABLE_SIMD && BX_CPU_X86
#include <xmmintrin.h>
#include <immintrin.h>
#endif
namespace vgutil
{
bool invertMatrix3(const float* __restrict t, float* __restrict inv)
{
// nvgTransformInverse
double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1];
if (det > -1e-6 && det < 1e-6) {
inv[0] = inv[2] = 1.0f;
inv[1] = inv[3] = inv[4] = inv[5] = 0.0f;
return false;
}
invdet = 1.0 / det;
inv[0] = (float)(t[3] * invdet);
inv[2] = (float)(-t[2] * invdet);
inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet);
inv[1] = (float)(-t[1] * invdet);
inv[3] = (float)(t[0] * invdet);
inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet);
return true;
}
#if VG_CONFIG_ENABLE_SIMD && BX_CPU_X86
void memset32(void* __restrict dst, uint32_t n, const void* __restrict src)
{
const __m128 s128 = _mm_load_ps1((const float*)src);
float* d = (float*)dst;
uint32_t iter = n >> 4;
while (iter-- > 0) {
_mm_storeu_ps(d + 0, s128);
_mm_storeu_ps(d + 4, s128);
_mm_storeu_ps(d + 8, s128);
_mm_storeu_ps(d + 12, s128);
d += 16;
}
uint32_t rem = n & 15;
if (rem >= 8) {
_mm_storeu_ps(d + 0, s128);
_mm_storeu_ps(d + 4, s128);
d += 8;
rem -= 8;
}
if (rem >= 4) {
_mm_storeu_ps(d, s128);
d += 4;
rem -= 4;
}
switch (rem) {
case 3: *d++ = *(const float*)src;
case 2: *d++ = *(const float*)src;
case 1: *d = *(const float*)src;
}
}
void memset64(void* __restrict dst, uint32_t n64, const void* __restrict src)
{
const float* s = (const float*)src;
const __m128 s0 = _mm_load_ss(&s[0]);
const __m128 s1 = _mm_load_ss(&s[1]);
const __m128 s0011 = _mm_shuffle_ps(s0, s1, _MM_SHUFFLE(0, 0, 0, 0));
const __m128 s128 = _mm_shuffle_ps(s0011, s0011, _MM_SHUFFLE(2, 0, 2, 0));
float* d = (float*)dst;
uint32_t iter = n64 >> 3; // 8 64-bit values per iteration (== 16 floats / iter)
while (iter-- > 0) {
_mm_storeu_ps(d + 0, s128);
_mm_storeu_ps(d + 4, s128);
_mm_storeu_ps(d + 8, s128);
_mm_storeu_ps(d + 12, s128);
d += 16;
}
uint32_t rem = n64 & 7;
if (rem >= 4) {
_mm_storeu_ps(d + 0, s128);
_mm_storeu_ps(d + 4, s128);
d += 8;
rem -= 4;
}
if (rem >= 2) {
_mm_storeu_ps(d, s128);
d += 4;
rem -= 2;
}
if (rem) {
d[0] = s[0];
d[1] = s[1];
}
}
void memset128(void* __restrict dst, uint32_t n128, const void* __restrict src)
{
const __m128 s128 = _mm_loadu_ps((const float*)src);
float* d = (float*)dst;
uint32_t iter = n128 >> 2; // 4 128-bit values per iteration (== 16 floats / iter)
while (iter-- > 0) {
_mm_storeu_ps(d + 0, s128);
_mm_storeu_ps(d + 4, s128);
_mm_storeu_ps(d + 8, s128);
_mm_storeu_ps(d + 12, s128);
d += 16;
}
uint32_t rem = n128 & 3;
if (rem >= 2) {
_mm_storeu_ps(d + 0, s128);
_mm_storeu_ps(d + 4, s128);
d += 8;
rem -= 2;
}
if (rem) {
_mm_storeu_ps(d, s128);
}
}
void batchTransformPositions(const float* __restrict src, uint32_t n, float* __restrict dst, const float* __restrict mtx)
{
const __m128 mtx0123 = _mm_loadu_ps(mtx);
const __m128 mtx45 = _mm_loadl_pi(_mm_setzero_ps(), (const __m64*)(mtx + 4));
const __m128 mtx0 = _mm_shuffle_ps(mtx0123, mtx0123, _MM_SHUFFLE(0, 0, 0, 0));
const __m128 mtx1 = _mm_shuffle_ps(mtx0123, mtx0123, _MM_SHUFFLE(1, 1, 1, 1));
const __m128 mtx2 = _mm_shuffle_ps(mtx0123, mtx0123, _MM_SHUFFLE(2, 2, 2, 2));
const __m128 mtx3 = _mm_shuffle_ps(mtx0123, mtx0123, _MM_SHUFFLE(3, 3, 3, 3));
const __m128 mtx4 = _mm_shuffle_ps(mtx45, mtx45, _MM_SHUFFLE(0, 0, 0, 0));
const __m128 mtx5 = _mm_shuffle_ps(mtx45, mtx45, _MM_SHUFFLE(1, 1, 1, 1));
const uint32_t iter = n >> 3;
for (uint32_t i = 0; i < iter; ++i) {
// x' = m[0] * x + m[2] * y + m[4];
// y' = m[1] * x + m[3] * y + m[5];
const __m128 xy01 = _mm_load_ps(src + 0); // { x0, y0, x1, y1 }
const __m128 xy23 = _mm_load_ps(src + 4); // { x2, y2, x3, y3 }
const __m128 xy45 = _mm_load_ps(src + 8); // { x4, y4, x5, y5 }
const __m128 xy67 = _mm_load_ps(src + 12); // { x6, y6, x7, y7 }
const __m128 x0123 = _mm_shuffle_ps(xy01, xy23, _MM_SHUFFLE(2, 0, 2, 0)); // { x0, x1, x2, x3 }
const __m128 y0123 = _mm_shuffle_ps(xy01, xy23, _MM_SHUFFLE(3, 1, 3, 1)); // { y0, y1, y2, y3 }
const __m128 x4567 = _mm_shuffle_ps(xy45, xy67, _MM_SHUFFLE(2, 0, 2, 0)); // { x0, x1, x2, x3 }
const __m128 y4567 = _mm_shuffle_ps(xy45, xy67, _MM_SHUFFLE(3, 1, 3, 1)); // { y0, y1, y2, y3 }
const __m128 resx0123 = _mm_add_ps(_mm_add_ps(_mm_mul_ps(x0123, mtx0), mtx4), _mm_mul_ps(y0123, mtx2)); // { xi * m[0] + yi * m[2] + m[4] }
const __m128 resy0123 = _mm_add_ps(_mm_add_ps(_mm_mul_ps(x0123, mtx1), mtx5), _mm_mul_ps(y0123, mtx3)); // { x1 * m[1] + yi * m[3] + m[5] }
const __m128 resx4567 = _mm_add_ps(_mm_add_ps(_mm_mul_ps(x4567, mtx0), mtx4), _mm_mul_ps(y4567, mtx2)); // { xi * m[0] + yi * m[2] + m[4] }
const __m128 resy4567 = _mm_add_ps(_mm_add_ps(_mm_mul_ps(x4567, mtx1), mtx5), _mm_mul_ps(y4567, mtx3)); // { x1 * m[1] + yi * m[3] + m[5] }
const __m128 resx01_resy01 = _mm_movelh_ps(resx0123, resy0123); // { rx0, rx1, ry0, ry1 }
const __m128 resx23_resy23 = _mm_movehl_ps(resy0123, resx0123); // { rx2, rx3, ry2, ry3 }
const __m128 resx45_resy45 = _mm_movelh_ps(resx4567, resy4567); // { rx4, rx5, ry4, ry5 }
const __m128 resx67_resy67 = _mm_movehl_ps(resy4567, resx4567); // { rx6, rx7, ry6, ry7 }
const __m128 resxy01 = _mm_shuffle_ps(resx01_resy01, resx01_resy01, _MM_SHUFFLE(3, 1, 2, 0)); // { rx0, ry0, rx1, ry1 }
const __m128 resxy23 = _mm_shuffle_ps(resx23_resy23, resx23_resy23, _MM_SHUFFLE(3, 1, 2, 0)); // { rx2, ry2, rx3, ry3 }
const __m128 resxy45 = _mm_shuffle_ps(resx45_resy45, resx45_resy45, _MM_SHUFFLE(3, 1, 2, 0)); // { rx4, ry4, rx5, ry5 }
const __m128 resxy67 = _mm_shuffle_ps(resx67_resy67, resx67_resy67, _MM_SHUFFLE(3, 1, 2, 0)); // { rx6, ry6, rx7, ry7 }
_mm_store_ps(dst + 0, resxy01);
_mm_store_ps(dst + 4, resxy23);
_mm_store_ps(dst + 8, resxy45);
_mm_store_ps(dst + 12, resxy67);
src += 16;
dst += 16;
}
uint32_t rem = n & 7;
if (rem >= 4) {
const __m128 xy01 = _mm_load_ps(src + 0);
const __m128 xy23 = _mm_load_ps(src + 4);
const __m128 x0123 = _mm_shuffle_ps(xy01, xy23, _MM_SHUFFLE(2, 0, 2, 0));
const __m128 y0123 = _mm_shuffle_ps(xy01, xy23, _MM_SHUFFLE(3, 1, 3, 1));
const __m128 resx0123 = _mm_add_ps(_mm_add_ps(_mm_mul_ps(x0123, mtx0), mtx4), _mm_mul_ps(y0123, mtx2));
const __m128 resy0123 = _mm_add_ps(_mm_add_ps(_mm_mul_ps(x0123, mtx1), mtx5), _mm_mul_ps(y0123, mtx3));
const __m128 resx01_resy01 = _mm_movelh_ps(resx0123, resy0123);
const __m128 resx23_resy23 = _mm_movehl_ps(resy0123, resx0123);
const __m128 resxy01 = _mm_shuffle_ps(resx01_resy01, resx01_resy01, _MM_SHUFFLE(3, 1, 2, 0));
const __m128 resxy23 = _mm_shuffle_ps(resx23_resy23, resx23_resy23, _MM_SHUFFLE(3, 1, 2, 0));
_mm_store_ps(dst + 0, resxy01);
_mm_store_ps(dst + 4, resxy23);
src += 8;
dst += 8;
rem -= 4;
}
switch (rem) {
case 3:
dst[0] = mtx[0] * src[0] + mtx[2] * src[1] + mtx[4];
dst[1] = mtx[1] * src[0] + mtx[3] * src[1] + mtx[5];
src += 2;
dst += 2;
case 2:
dst[0] = mtx[0] * src[0] + mtx[2] * src[1] + mtx[4];
dst[1] = mtx[1] * src[0] + mtx[3] * src[1] + mtx[5];
src += 2;
dst += 2;
case 1:
dst[0] = mtx[0] * src[0] + mtx[2] * src[1] + mtx[4];
dst[1] = mtx[1] * src[0] + mtx[3] * src[1] + mtx[5];
}
}
#else
void memset32(void* __restrict dst, uint32_t n, const void* __restrict src)
{
const uint32_t s = *(const uint32_t*)src;
uint32_t* d = (uint32_t*)dst;
while (n-- > 0) {
*d++ = s;
}
}
void memset64(void* __restrict dst, uint32_t n64, const void* __restrict src)
{
const uint32_t s0 = *((const uint32_t*)src + 0);
const uint32_t s1 = *((const uint32_t*)src + 1);
uint32_t* d = (uint32_t*)dst;
while (n64-- > 0) {
d[0] = s0;
d[1] = s1;
d += 2;
}
}
void memset128(void* __restrict dst, uint32_t n128, const void* __restrict src)
{
const uint32_t s0 = *((const uint32_t*)src + 0);
const uint32_t s1 = *((const uint32_t*)src + 1);
const uint32_t s2 = *((const uint32_t*)src + 2);
const uint32_t s3 = *((const uint32_t*)src + 3);
uint32_t* d = (uint32_t*)dst;
while (n128-- > 0) {
d[0] = s0;
d[1] = s1;
d[2] = s2;
d[3] = s3;
d += 4;
}
}
void batchTransformPositions(const float* __restrict v, uint32_t n, float* __restrict p, const float* __restrict mtx)
{
for (uint32_t i = 0; i < n; ++i) {
const uint32_t id = i << 1;
transformPos2D(v[id], v[id + 1], mtx, &p[id]);
}
}
#endif
void genQuadIndices_unaligned(uint16_t* dst, uint32_t n, uint16_t firstVertexID)
{
#if VG_CONFIG_ENABLE_SIMD && BX_CPU_X86
BX_ALIGN_DECL(16, static const uint16_t delta[]) = {
0, 1, 2, 0, 2, 3,
4, 5, 6, 4, 6, 7,
8, 9, 10, 8, 10, 11,
12, 13, 14, 12, 14, 15
};
const __m128i xmm_delta0 = _mm_load_si128((const __m128i*)&delta[0]);
const __m128i xmm_delta1 = _mm_load_si128((const __m128i*)&delta[8]);
const __m128i xmm_delta2 = _mm_load_si128((const __m128i*)&delta[16]);
const uint32_t numIter = n >> 2; // 4 quads per iteration
for (uint32_t i = 0; i < numIter; ++i) {
const __m128i id = _mm_set1_epi16(firstVertexID);
const __m128i id0 = _mm_add_epi16(id, xmm_delta0);
const __m128i id1 = _mm_add_epi16(id, xmm_delta1);
const __m128i id2 = _mm_add_epi16(id, xmm_delta2);
_mm_storeu_si128((__m128i*)(dst + 0), id0);
_mm_storeu_si128((__m128i*)(dst + 8), id1);
_mm_storeu_si128((__m128i*)(dst + 16), id2);
dst += 24;
firstVertexID += 16;
}
uint32_t rem = n & 3;
switch (rem) {
case 3:
dst[0] = firstVertexID; dst[1] = firstVertexID + 1; dst[2] = firstVertexID + 2;
dst[3] = firstVertexID; dst[4] = firstVertexID + 2; dst[5] = firstVertexID + 3;
dst += 6;
firstVertexID += 4;
case 2:
dst[0] = firstVertexID; dst[1] = firstVertexID + 1; dst[2] = firstVertexID + 2;
dst[3] = firstVertexID; dst[4] = firstVertexID + 2; dst[5] = firstVertexID + 3;
dst += 6;
firstVertexID += 4;
case 1:
dst[0] = firstVertexID; dst[1] = firstVertexID + 1; dst[2] = firstVertexID + 2;
dst[3] = firstVertexID; dst[4] = firstVertexID + 2; dst[5] = firstVertexID + 3;
dst += 6;
firstVertexID += 4;
}
#else
while (n-- > 0) {
dst[0] = firstVertexID; dst[1] = firstVertexID + 1; dst[2] = firstVertexID + 2;
dst[3] = firstVertexID; dst[4] = firstVertexID + 2; dst[5] = firstVertexID + 3;
dst += 6;
firstVertexID += 4;
}
#endif
}
void batchTransformTextQuads(const float* __restrict quads, uint32_t n, const float* __restrict mtx, float* __restrict transformedVertices)
{
#if VG_CONFIG_ENABLE_SIMD
const bx::simd128_t mtx0 = bx::simd_splat(mtx[0]);
const bx::simd128_t mtx1 = bx::simd_splat(mtx[1]);
const bx::simd128_t mtx2 = bx::simd_splat(mtx[2]);
const bx::simd128_t mtx3 = bx::simd_splat(mtx[3]);
const bx::simd128_t mtx4 = bx::simd_splat(mtx[4]);
const bx::simd128_t mtx5 = bx::simd_splat(mtx[5]);
const uint32_t iter = n >> 1; // 2 quads per iteration
for (uint32_t i = 0; i < iter; ++i) {
bx::simd128_t q0 = bx::simd_ld(quads); // (x0, y0, x1, y1)
bx::simd128_t q1 = bx::simd_ld(quads + 8); // (x2, y2, x3, y3)
bx::simd128_t x0123 = bx::simd_shuf_xyAB(bx::simd_swiz_xzxz(q0), bx::simd_swiz_xzxz(q1)); // (x0, x1, x2, x3)
bx::simd128_t y0123 = bx::simd_shuf_xyAB(bx::simd_swiz_ywyw(q0), bx::simd_swiz_ywyw(q1)); // (y0, y1, y2, y3)
bx::simd128_t x0123_m0 = bx::simd_mul(x0123, mtx0); // (x0, x1, x2, x3) * mtx[0]
bx::simd128_t x0123_m1 = bx::simd_mul(x0123, mtx1); // (x0, x1, x2, x3) * mtx[1]
bx::simd128_t y0123_m2 = bx::simd_mul(y0123, mtx2); // (y0, y1, y2, y3) * mtx[2]
bx::simd128_t y0123_m3 = bx::simd_mul(y0123, mtx3); // (y0, y1, y2, y3) * mtx[3]
// v0.x = x0_m0 + y0_m2 + m4
// v1.x = x1_m0 + y0_m2 + m4
// v2.x = x1_m0 + y1_m2 + m4
// v3.x = x0_m0 + y1_m2 + m4
// v0.y = x0_m1 + y0_m3 + m5
// v1.y = x1_m1 + y0_m3 + m5
// v2.y = x1_m1 + y1_m3 + m5
// v3.y = x0_m1 + y1_m3 + m5
bx::simd128_t x0110_m0 = bx::simd_swiz_xyyx(x0123_m0);
bx::simd128_t x0110_m1 = bx::simd_swiz_xyyx(x0123_m1);
bx::simd128_t y0011_m2 = bx::simd_swiz_xxyy(y0123_m2);
bx::simd128_t y0011_m3 = bx::simd_swiz_xxyy(y0123_m3);
bx::simd128_t v0123_x = bx::simd_add(x0110_m0, bx::simd_add(y0011_m2, mtx4));
bx::simd128_t v0123_y = bx::simd_add(x0110_m1, bx::simd_add(y0011_m3, mtx5));
bx::simd128_t v01 = bx::simd_swiz_xzyw(bx::simd_shuf_xyAB(v0123_x, v0123_y));
bx::simd128_t v23 = bx::simd_swiz_xzyw(bx::simd_shuf_zwCD(v0123_x, v0123_y));
bx::simd_st(transformedVertices, v01);
bx::simd_st(transformedVertices + 4, v23);
// v4.x = x2_m0 + y2_m2 + m4
// v5.x = x3_m0 + y2_m2 + m4
// v6.x = x3_m0 + y3_m2 + m4
// v7.x = x2_m0 + y3_m2 + m4
// v4.y = x2_m1 + y2_m3 + m5
// v5.y = x3_m1 + y2_m3 + m5
// v6.y = x3_m1 + y3_m3 + m5
// v7.y = x2_m1 + y3_m3 + m5
bx::simd128_t x2332_m0 = bx::simd_swiz_zwwz(x0123_m0);
bx::simd128_t x2332_m1 = bx::simd_swiz_zwwz(x0123_m1);
bx::simd128_t y2233_m2 = bx::simd_swiz_zzww(y0123_m2);
bx::simd128_t y2233_m3 = bx::simd_swiz_zzww(y0123_m3);
bx::simd128_t v4567_x = bx::simd_add(x2332_m0, bx::simd_add(y2233_m2, mtx4));
bx::simd128_t v4567_y = bx::simd_add(x2332_m1, bx::simd_add(y2233_m3, mtx5));
bx::simd128_t v45 = bx::simd_swiz_xzyw(bx::simd_shuf_xyAB(v4567_x, v4567_y));
bx::simd128_t v67 = bx::simd_swiz_xzyw(bx::simd_shuf_zwCD(v4567_x, v4567_y));
bx::simd_st(transformedVertices + 8, v45);
bx::simd_st(transformedVertices + 12, v67);
quads += 16;
transformedVertices += 16;
}
const uint32_t rem = n & 1;
if (rem) {
bx::simd128_t q0 = bx::simd_ld(quads);
bx::simd128_t x0101 = bx::simd_swiz_xzxz(q0); // (x0, x1, x0, x1)
bx::simd128_t y0101 = bx::simd_swiz_ywyw(q0); // (y0, y1, y0, y1)
bx::simd128_t x0101_m0 = bx::simd_mul(x0101, mtx0); // (x0, x1, x0, x1) * mtx[0]
bx::simd128_t x0101_m1 = bx::simd_mul(x0101, mtx1); // (x0, x1, x0, x1) * mtx[1]
bx::simd128_t y0101_m2 = bx::simd_mul(y0101, mtx2); // (y0, y1, y0, y1) * mtx[2]
bx::simd128_t y0101_m3 = bx::simd_mul(y0101, mtx3); // (y0, y1, y0, y1) * mtx[3]
// v0.x = x0_m0 + y0_m2 + m4
// v1.x = x1_m0 + y0_m2 + m4
// v2.x = x1_m0 + y1_m2 + m4
// v3.x = x0_m0 + y1_m2 + m4
// v0.y = x0_m1 + y0_m3 + m5
// v1.y = x1_m1 + y0_m3 + m5
// v2.y = x1_m1 + y1_m3 + m5
// v3.y = x0_m1 + y1_m3 + m5
bx::simd128_t x0110_m0 = bx::simd_swiz_xyyx(x0101_m0);
bx::simd128_t x0110_m1 = bx::simd_swiz_xyyx(x0101_m1);
bx::simd128_t y0011_m2 = bx::simd_swiz_xxyy(y0101_m2);
bx::simd128_t y0011_m3 = bx::simd_swiz_xxyy(y0101_m3);
bx::simd128_t v0123_x = bx::simd_add(x0110_m0, bx::simd_add(y0011_m2, mtx4));
bx::simd128_t v0123_y = bx::simd_add(x0110_m1, bx::simd_add(y0011_m3, mtx5));
bx::simd128_t v01 = bx::simd_swiz_xzyw(bx::simd_shuf_xyAB(v0123_x, v0123_y));
bx::simd128_t v23 = bx::simd_swiz_xzyw(bx::simd_shuf_zwCD(v0123_x, v0123_y));
bx::simd_st(transformedVertices, v01);
bx::simd_st(transformedVertices + 4, v23);
}
#else
for (uint32_t i = 0; i < n; ++i) {
const float* q = &quads[i * 8];
const uint32_t s = i << 3;
transformPos2D(q[0], q[1], mtx, &transformedVertices[s + 0]);
transformPos2D(q[2], q[1], mtx, &transformedVertices[s + 2]);
transformPos2D(q[2], q[3], mtx, &transformedVertices[s + 4]);
transformPos2D(q[0], q[3], mtx, &transformedVertices[s + 6]);
}
#endif
}
void batchTransformPositions_Unaligned(const float* __restrict v, uint32_t n, float* __restrict p, const float* __restrict mtx)
{
#if VG_CONFIG_ENABLE_SIMD && BX_CPU_X86
const float* src = v;
float* dst = p;
const bx::simd128_t mtx0 = bx::simd_splat(mtx[0]);
const bx::simd128_t mtx1 = bx::simd_splat(mtx[1]);
const bx::simd128_t mtx2 = bx::simd_splat(mtx[2]);
const bx::simd128_t mtx3 = bx::simd_splat(mtx[3]);
const bx::simd128_t mtx4 = bx::simd_splat(mtx[4]);
const bx::simd128_t mtx5 = bx::simd_splat(mtx[5]);
const uint32_t iter = n >> 2;
for (uint32_t i = 0; i < iter; ++i) {
bx::simd128_t src0123 = _mm_loadu_ps(src);
bx::simd128_t src4567 = _mm_loadu_ps(src + 4);
bx::simd128_t src0246 = bx::simd_shuf_xyAB(bx::simd_swiz_xzxz(src0123), bx::simd_swiz_xzxz(src4567));
bx::simd128_t src1357 = bx::simd_shuf_xyAB(bx::simd_swiz_ywyw(src0123), bx::simd_swiz_ywyw(src4567));
bx::simd128_t dst0246 = bx::simd_add(bx::simd_add(bx::simd_mul(src0246, mtx0), bx::simd_mul(src1357, mtx2)), mtx4);
bx::simd128_t dst1357 = bx::simd_add(bx::simd_add(bx::simd_mul(src0246, mtx1), bx::simd_mul(src1357, mtx3)), mtx5);
bx::simd128_t dst0123 = bx::simd_swiz_xzyw(bx::simd_shuf_xyAB(dst0246, dst1357));
bx::simd128_t dst4567 = bx::simd_swiz_xzyw(bx::simd_shuf_zwCD(dst0246, dst1357));
_mm_storeu_ps(dst, dst0123);
_mm_storeu_ps(dst + 4, dst4567);
src += 8;
dst += 8;
}
const uint32_t rem = n & 3;
switch (rem) {
case 3:
*dst++ = mtx[0] * src[0] + mtx[2] * src[1] + mtx[4];
*dst++ = mtx[1] * src[0] + mtx[3] * src[1] + mtx[5];
src += 2;
case 2:
*dst++ = mtx[0] * src[0] + mtx[2] * src[1] + mtx[4];
*dst++ = mtx[1] * src[0] + mtx[3] * src[1] + mtx[5];
src += 2;
case 1:
*dst++ = mtx[0] * src[0] + mtx[2] * src[1] + mtx[4];
*dst++ = mtx[1] * src[0] + mtx[3] * src[1] + mtx[5];
src += 2;
}
#else
for (uint32_t i = 0; i < n; ++i) {
const uint32_t id = i << 1;
transformPos2D(v[id], v[id + 1], mtx, &p[id]);
}
#endif
}
// NOTE: Assumes src is 16-byte aligned. Don't care about dst (unaligned stores)
void batchTransformDrawIndices(const uint16_t* __restrict src, uint32_t n, uint16_t* __restrict dst, uint16_t delta)
{
if (delta == 0) {
bx::memCopy(dst, src, sizeof(uint16_t) * n);
return;
}
#if VG_CONFIG_ENABLE_SIMD && BX_CPU_X86
const __m128i xmm_delta = _mm_set1_epi16(delta);
const uint32_t iter32 = n >> 5;
for (uint32_t i = 0; i < iter32; ++i) {
const __m128i s0 = _mm_load_si128((const __m128i*)src);
const __m128i s1 = _mm_load_si128((const __m128i*)(src + 8));
const __m128i s2 = _mm_load_si128((const __m128i*)(src + 16));
const __m128i s3 = _mm_load_si128((const __m128i*)(src + 24));
const __m128i d0 = _mm_add_epi16(s0, xmm_delta);
const __m128i d1 = _mm_add_epi16(s1, xmm_delta);
const __m128i d2 = _mm_add_epi16(s2, xmm_delta);
const __m128i d3 = _mm_add_epi16(s3, xmm_delta);
// NOTE: Proper alignment of dst buffer isn't guaranteed because it's part of the global IndexBuffer.
_mm_storeu_si128((__m128i*)dst, d0);
_mm_storeu_si128((__m128i*)(dst + 8), d1);
_mm_storeu_si128((__m128i*)(dst + 16), d2);
_mm_storeu_si128((__m128i*)(dst + 24), d3);
src += 32;
dst += 32;
}
uint32_t rem = n & 31;
if (rem >= 16) {
const __m128i s0 = _mm_load_si128((const __m128i*)src);
const __m128i s1 = _mm_load_si128((const __m128i*)(src + 8));
const __m128i d0 = _mm_add_epi16(s0, xmm_delta);
const __m128i d1 = _mm_add_epi16(s1, xmm_delta);
_mm_storeu_si128((__m128i*)dst, d0);
_mm_storeu_si128((__m128i*)(dst + 8), d1);
src += 16;
dst += 16;
rem -= 16;
}
if (rem >= 8) {
__m128i s0 = _mm_load_si128((const __m128i*)src);
__m128i d0 = _mm_add_epi16(s0, xmm_delta);
_mm_storeu_si128((__m128i*)dst, d0);
src += 8;
dst += 8;
rem -= 8;
}
switch (rem) {
case 7: *dst++ = *src++ + delta;
case 6: *dst++ = *src++ + delta;
case 5: *dst++ = *src++ + delta;
case 4: *dst++ = *src++ + delta;
case 3: *dst++ = *src++ + delta;
case 2: *dst++ = *src++ + delta;
case 1: *dst = *src + delta;
}
#else
for (uint32_t i = 0; i < n; ++i) {
*dst++ = *src + delta;
src++;
}
#endif
}
void convertA8_to_RGBA8(uint32_t* rgba, const uint8_t* a8, uint32_t w, uint32_t h, uint32_t rgbColor)
{
const uint32_t rgb0 = rgbColor & 0x00FFFFFF;
int numPixels = w * h;
for (int i = 0; i < numPixels; ++i) {
*rgba++ = rgb0 | (((uint32_t)* a8) << 24);
++a8;
}
}
}
| [
"makingartstudios@gmail.com"
] | makingartstudios@gmail.com |
976e7c68ff4e009cd5dbf1b64a173f05d987ca74 | 9870e11c26c15aec3cc13bc910e711367749a7ff | /EOJ/e_2606.cpp | 1262f62d64428f4f5d66a8f82e58a45a17ab1a92 | [] | no_license | liuq901/code | 56eddb81972d00f2b733121505555b7c7cbc2544 | fcbfba70338d3d10bad2a4c08f59d501761c205a | refs/heads/master | 2021-01-15T23:50:10.570996 | 2016-01-16T16:14:18 | 2016-01-16T16:14:18 | 12,918,517 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 199 | cpp | #include <cstdio>
int main()
{
int T;
scanf("%d",&T);
while (T--)
{
double a,b,h;
scanf("%lf%lf%lf",&a,&b,&h);
printf("%.2f\n",h/a*b);
}
return(0);
}
| [
"liuq901@163.com"
] | liuq901@163.com |
5f1bebe72815595b6181abdfc7e5c6e29ed7f43d | e668bcd9bee53f99b149d4871e788444b27cf5c3 | /card_deck.h | 8072b39c5b6539e1eaf35bcee03e08d1e89e467c | [] | no_license | brettc-git/Higher-and-Lower-Game | 209a1ed21f10fab3e37f004e9dc9fa11fbd9ecc8 | f1c42e16ce737bbc1e211dfe0a8bdaf8db6fa379 | refs/heads/main | 2023-03-01T08:24:13.128675 | 2021-01-27T07:08:58 | 2021-01-27T07:08:58 | 303,843,860 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 456 | h | #pragma once
#include <iostream>
#include <algorithm>
#include <chrono>
#include <random>
#include <vector>
#include "card.h"
using std::string;
using std::vector;
const int deck_size = 52;
class card_deck
{
private:
vector<Card> deck; // Dynamically allocate memory for 52 cards;
public:
card_deck(); // Constructor
~card_deck(); // Deconstructor
void shuffleDeck();
vector<Card> dealCards(vector<Card> set);
};
| [
"noreply@github.com"
] | noreply@github.com |
24abe63720e0716906f0a8255b8fd16f96c429f6 | 011006ca59cfe75fb3dd84a50b6c0ef6427a7dc3 | /SPOJ/CNEASY.cpp | dcd6e6e54cfab3f1fb0dda1af990b2fae227546a | [] | no_license | ay2306/Competitive-Programming | 34f35367de2e8623da0006135cf21ba6aec34049 | 8cc9d953b09212ab32b513acf874dba4fa1d2848 | refs/heads/master | 2021-06-26T16:46:28.179504 | 2021-01-24T15:32:57 | 2021-01-24T15:32:57 | 205,185,905 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,006 | cpp | #include <bits/stdc++.h>
//For ordered_set
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define MOD 1000000007
#define test int t; cin>>t; while(t--)
#define init(arr,val) memset(arr,val,sizeof(arr))
#define loop(i,a,b) for(int i=a;i<b;i++)
#define loopr(i,a,b) for(int i=a;i>=b;i--)
#define loops(i,a,b,step) for(int i=a;i<b;i+=step)
#define looprs(i,a,b,step) for(int i=a;i>=b;i-=step)
#define ull unsigned long long int
#define ll long long int
#define P pair
#define PLL pair<long long, long long>
#define PII pair<int, int>
#define PUU pair<unsigned long long int, unsigned long long int>
#define L list
#define V vector
#define D deque
#define ST set
#define MS multiset
#define M map
#define UM unordered_map
#define mp make_pair
#define pb push_back
#define pf push_front
#define MM multimap
#define F first
#define S second
#define IT iterator
#define RIT reverse_iterator
#define FAST ios_base::sync_with_stdio(false);cin.tie();cout.tie();
#define FILE_READ_IN freopen("input.txt","r",stdin);
#define FILE_READ_OUT freopen("output.txt","w",stdout);
#define all(a) a.begin(),a.end()
using namespace std;
// For ordered_set
using namespace __gnu_pbds;
template <typename T>
using ord_set = tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;
const ll maxn = 1e5;
const ll inf = 1e9;
const double pi = acos(-1);
void solve(){
int n;
cin >> n;
set<double> s;
loop(i,0,n){
string oop;
double a;
cin >> oop >> a;
s.insert(a);
}
n = s.size();
if(n == 1){
cout << "0\n";
return;
}
V<double> arr(n);
loop(i,0,n){
arr[i] = *s.begin();
s.erase(s.begin());
}
double ans = 360.0;
loop(i,1,n){
ans = min(ans,360.0-fabs(arr[i]-arr[i-1]));
}
ans = min(ans,360.0 - (arr[0] + 360.0 - arr[n-1]));
cout << int(ceil(ans*12)) << "\n";
}
int main(){
int t = 0;
cin >> t;
while(t--){
solve();
}
return 0;
} | [
"mahajan.ayush2306@gmail.com"
] | mahajan.ayush2306@gmail.com |
bb77b6546015aa912905679614580129e12aab8c | 83d42ce881ad34bb8a42da1d848e2289703371a7 | /src/db.h | 1c75b4ca079bfbc085f9ed9ee9bba1b9e956e640 | [
"MIT"
] | permissive | BitTokens/BitToken | c91da52aae898ecff60187077ab98dc602a19e58 | b5f3272537ab5b33b398092b8efa60347cf087ce | refs/heads/master | 2020-08-03T02:41:41.478818 | 2017-11-22T07:31:40 | 2017-11-22T07:31:50 | 73,554,561 | 3 | 4 | null | 2017-09-12T00:01:19 | 2016-11-12T13:35:06 | C++ | UTF-8 | C++ | false | false | 8,566 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The BitToken developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_DB_H
#define BITCOIN_DB_H
#include "sync.h"
#include "serialize.h"
#include <map>
#include <string>
#include <vector>
#include <boost/filesystem.hpp>
#include <db_cxx.h>
class CAddrMan;
class CBlockLocator;
class CDiskBlockIndex;
class CMasterKey;
class COutPoint;
class CWallet;
extern unsigned int nWalletDBUpdated;
void ThreadFlushWalletDB(const std::string& strWalletFile);
bool BackupWallet(const CWallet& wallet, const std::string& strDest);
class CDBEnv
{
private:
bool fDbEnvInit;
bool fMockDb;
boost::filesystem::path path;
void EnvShutdown();
public:
mutable CCriticalSection cs_db;
DbEnv dbenv;
std::map<std::string, int> mapFileUseCount;
std::map<std::string, Db*> mapDb;
CDBEnv();
~CDBEnv();
void MakeMock();
bool IsMock() { return fMockDb; }
/*
* Verify that database file strFile is OK. If it is not,
* call the callback to try to recover.
* This must be called BEFORE strFile is opened.
* Returns true if strFile is OK.
*/
enum VerifyResult { VERIFY_OK, RECOVER_OK, RECOVER_FAIL };
VerifyResult Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile));
/*
* Salvage data from a file that Verify says is bad.
* fAggressive sets the DB_AGGRESSIVE flag (see berkeley DB->verify() method documentation).
* Appends binary key/value pairs to vResult, returns true if successful.
* NOTE: reads the entire database into memory, so cannot be used
* for huge databases.
*/
typedef std::pair<std::vector<unsigned char>, std::vector<unsigned char> > KeyValPair;
bool Salvage(std::string strFile, bool fAggressive, std::vector<KeyValPair>& vResult);
bool Open(const boost::filesystem::path &path);
void Close();
void Flush(bool fShutdown);
void CheckpointLSN(std::string strFile);
void CloseDb(const std::string& strFile);
bool RemoveDb(const std::string& strFile);
DbTxn *TxnBegin(int flags=DB_TXN_WRITE_NOSYNC)
{
DbTxn* ptxn = NULL;
int ret = dbenv.txn_begin(NULL, &ptxn, flags);
if (!ptxn || ret != 0)
return NULL;
return ptxn;
}
};
extern CDBEnv bitdb;
/** RAII class that provides access to a Berkeley database */
class CDB
{
protected:
Db* pdb;
std::string strFile;
DbTxn *activeTxn;
bool fReadOnly;
explicit CDB(const char* pszFile, const char* pszMode="r+");
~CDB() { Close(); }
public:
void Flush();
void Close();
private:
CDB(const CDB&);
void operator=(const CDB&);
protected:
template<typename K, typename T>
bool Read(const K& key, T& value)
{
if (!pdb)
return false;
// Key
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(1000);
ssKey << key;
Dbt datKey(&ssKey[0], ssKey.size());
// Read
Dbt datValue;
datValue.set_flags(DB_DBT_MALLOC);
int ret = pdb->get(activeTxn, &datKey, &datValue, 0);
memset(datKey.get_data(), 0, datKey.get_size());
if (datValue.get_data() == NULL)
return false;
// Unserialize value
try {
CDataStream ssValue((char*)datValue.get_data(), (char*)datValue.get_data() + datValue.get_size(), SER_DISK, CLIENT_VERSION);
ssValue >> value;
}
catch (std::exception &e) {
return false;
}
// Clear and free memory
memset(datValue.get_data(), 0, datValue.get_size());
free(datValue.get_data());
return (ret == 0);
}
template<typename K, typename T>
bool Write(const K& key, const T& value, bool fOverwrite=true)
{
if (!pdb)
return false;
if (fReadOnly)
assert(!"Write called on database in read-only mode");
// Key
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(1000);
ssKey << key;
Dbt datKey(&ssKey[0], ssKey.size());
// Value
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.reserve(10000);
ssValue << value;
Dbt datValue(&ssValue[0], ssValue.size());
// Write
int ret = pdb->put(activeTxn, &datKey, &datValue, (fOverwrite ? 0 : DB_NOOVERWRITE));
// Clear memory in case it was a private key
memset(datKey.get_data(), 0, datKey.get_size());
memset(datValue.get_data(), 0, datValue.get_size());
return (ret == 0);
}
template<typename K>
bool Erase(const K& key)
{
if (!pdb)
return false;
if (fReadOnly)
assert(!"Erase called on database in read-only mode");
// Key
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(1000);
ssKey << key;
Dbt datKey(&ssKey[0], ssKey.size());
// Erase
int ret = pdb->del(activeTxn, &datKey, 0);
// Clear memory
memset(datKey.get_data(), 0, datKey.get_size());
return (ret == 0 || ret == DB_NOTFOUND);
}
template<typename K>
bool Exists(const K& key)
{
if (!pdb)
return false;
// Key
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.reserve(1000);
ssKey << key;
Dbt datKey(&ssKey[0], ssKey.size());
// Exists
int ret = pdb->exists(activeTxn, &datKey, 0);
// Clear memory
memset(datKey.get_data(), 0, datKey.get_size());
return (ret == 0);
}
Dbc* GetCursor()
{
if (!pdb)
return NULL;
Dbc* pcursor = NULL;
int ret = pdb->cursor(NULL, &pcursor, 0);
if (ret != 0)
return NULL;
return pcursor;
}
int ReadAtCursor(Dbc* pcursor, CDataStream& ssKey, CDataStream& ssValue, unsigned int fFlags=DB_NEXT)
{
// Read at cursor
Dbt datKey;
if (fFlags == DB_SET || fFlags == DB_SET_RANGE || fFlags == DB_GET_BOTH || fFlags == DB_GET_BOTH_RANGE)
{
datKey.set_data(&ssKey[0]);
datKey.set_size(ssKey.size());
}
Dbt datValue;
if (fFlags == DB_GET_BOTH || fFlags == DB_GET_BOTH_RANGE)
{
datValue.set_data(&ssValue[0]);
datValue.set_size(ssValue.size());
}
datKey.set_flags(DB_DBT_MALLOC);
datValue.set_flags(DB_DBT_MALLOC);
int ret = pcursor->get(&datKey, &datValue, fFlags);
if (ret != 0)
return ret;
else if (datKey.get_data() == NULL || datValue.get_data() == NULL)
return 99999;
// Convert to streams
ssKey.SetType(SER_DISK);
ssKey.clear();
ssKey.write((char*)datKey.get_data(), datKey.get_size());
ssValue.SetType(SER_DISK);
ssValue.clear();
ssValue.write((char*)datValue.get_data(), datValue.get_size());
// Clear and free memory
memset(datKey.get_data(), 0, datKey.get_size());
memset(datValue.get_data(), 0, datValue.get_size());
free(datKey.get_data());
free(datValue.get_data());
return 0;
}
public:
bool TxnBegin()
{
if (!pdb || activeTxn)
return false;
DbTxn* ptxn = bitdb.TxnBegin();
if (!ptxn)
return false;
activeTxn = ptxn;
return true;
}
bool TxnCommit()
{
if (!pdb || !activeTxn)
return false;
int ret = activeTxn->commit(0);
activeTxn = NULL;
return (ret == 0);
}
bool TxnAbort()
{
if (!pdb || !activeTxn)
return false;
int ret = activeTxn->abort();
activeTxn = NULL;
return (ret == 0);
}
bool ReadVersion(int& nVersion)
{
nVersion = 0;
return Read(std::string("version"), nVersion);
}
bool WriteVersion(int nVersion)
{
return Write(std::string("version"), nVersion);
}
bool static Rewrite(const std::string& strFile, const char* pszSkip = NULL);
};
/** Access to the (IP) address database (peers.dat) */
class CAddrDB
{
private:
boost::filesystem::path pathAddr;
public:
CAddrDB();
bool Write(const CAddrMan& addr);
bool Read(CAddrMan& addr);
};
#endif // BITCOIN_DB_H
| [
"bittokensteam@outlook.com"
] | bittokensteam@outlook.com |
9ddbc33acea6bae466d82984f48ddcce2a6c2b48 | 4a51cbfd9605b19464e003d3615b1d02680a5942 | /FelixEngine/FelixEngine/Systems/Graphics/Vulkan/VulkanGraphics.h | d7aadb0090ac8a9c8612e6d729f9fe011f3094d4 | [] | no_license | robmcrosby/FelixEngine | 9fa57f2ff2232c58a019ad168ad884f086370d64 | 3a6ab3128f2afad429adc4504e76f3596dd5e98a | refs/heads/master | 2023-01-11T20:50:30.529861 | 2022-12-29T02:15:19 | 2022-12-29T02:15:19 | 43,473,021 | 2 | 0 | null | 2018-09-28T04:30:33 | 2015-10-01T01:43:40 | C | UTF-8 | C++ | false | false | 1,411 | h | //
// VulkanGraphics.h
// FelixEngine
//
// Created by Robert Crosby on 5/3/18.
// Copyright © 2018 Robert Crosby. All rights reserved.
//
#ifndef VulkanGraphics_h
#define VulkanGraphics_h
#include "Graphics.h"
#include "Macros.h"
#include <vector>
OBJC_CLASS(UIView)
namespace fx {
class VulkanCommandPool;
typedef std::vector<GraphicTask> RenderPass;
typedef std::vector<VulkanCommandPool*> CommandPools;
/**
*
*/
class VulkanGraphics: public Graphics {
private:
std::vector<std::string> _layers;
std::vector<std::string> _extensions;
std::vector<RenderPass> _renderPasses;
CommandPools _commandPools;
public:
VulkanGraphics();
virtual ~VulkanGraphics();
bool initalize(UIView *view);
virtual FrameBufferPtr createFrameBuffer();
virtual ShaderProgramPtr createShaderProgram();
virtual VertexMeshPtr createVertexMesh();
virtual UniformBufferPtr createUniformBuffer();
virtual TextureBufferPtr createTextureBuffer();
virtual BufferPoolPtr createBufferPool();
virtual void nextFrame();
virtual void addTask(const GraphicTask &task);
virtual void presentFrame();
private:
bool createInstance();
bool createSwapChain(UIView *view);
bool createCommandPool();
void createCommandPools();
void clearCommandPools();
};
}
#endif /* VulkanGraphics_h */
| [
"robmcrosby@gmail.com"
] | robmcrosby@gmail.com |
3a384314bd24ac98c340006185c98f3774f09233 | 948c2f6909c6e9b37947df6e411b834ab93b261a | /athlete/athletetest.cpp | 51e7e41d7cb82f0754002d43038cac5d8f3e21af | [] | no_license | rocks6/schoolwork | 6d4705bd7656084208e4cee976f7aec0f3075bee | a466e6a8ded00768eee23009722eee1a803bb0e1 | refs/heads/master | 2021-01-18T19:27:23.724782 | 2016-10-26T22:45:07 | 2016-10-26T22:45:25 | 72,049,380 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,036 | cpp | #include <iostream>
#include <istream>
#include <fstream>
#include "BinarySearchTree.h"
#include "Athlete.h"
#include "Athlete.cpp"
using namespace std;
int main()
{
ifstream inFile ("WorldsHighestPaidAthletes.csv");
while (inFile.good())
{
string buffer;
getline(inFile, buffer);
string lastname_internal = buffer.substr(0, buffer.find(","));
string buffer2 = buffer.substr(buffer.find(",")+1,buffer.length());
string firstname_internal = buffer2.substr(0, buffer2.find(","));
string buffer3 = buffer2.substr(buffer2.find(",")+1,buffer2.length());
string rank_internal_str = buffer3.substr(0, buffer3.find(","));
int rank_internal_int = atoi(rank_internal_str.c_str());
string buffer4 = buffer3.substr(buffer3.find(",")+1,buffer3.length());
string earnings_internal_str = buffer4.substr(0, buffer4.find(","));
double earnings_internal_fl = atof(earnings_internal_str.c_str());
string buffer5 = buffer4.substr(buffer4.find(",")+1,buffer4.length());
string salary_internal_str = buffer5.substr(0, buffer5.find(","));
double salary_internal_fl = atof(salary_internal_str.c_str());
string buffer6 = buffer5.substr(buffer5.find(",")+1,buffer5.length());
string endorsements_internal_str = buffer6.substr(0, buffer6.find(","));
double endorsements_internal_fl = atof(endorsements_internal_str.c_str());
string buffer7 = buffer6.substr(buffer6.find(",")+1,buffer6.length());
string sport_internal = buffer7.substr(0, buffer7.find(","));
Athlete testAthlete(lastname_internal, firstname_internal, rank_internal_int, earnings_internal_fl, salary_internal_fl, endorsements_internal_fl, sport_internal);
athleteBST.add(testAthlete);
}
}
/*
Athlete(const string C_lastname, const string C_firstname, const int C_rank,
const double C_totalearnings, const double C_salary, const double C_endorsements, const string C_sport);
*/ | [
"stevebyerly62@gmail.com"
] | stevebyerly62@gmail.com |
c06ea6513039ebba7302ce258bf40fc1db91db88 | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /chrome/browser/ui/webui/settings/chromeos/bluetooth_section.cc | 2de04401ca6bc14771c1b204a4cf4b1630cbf1bf | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 12,980 | cc | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/settings/chromeos/bluetooth_section.h"
#include "base/bind.h"
#include "base/no_destructor.h"
#include "chrome/browser/ui/webui/chromeos/bluetooth_dialog_localized_strings_provider.h"
#include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom.h"
#include "chrome/browser/ui/webui/settings/chromeos/constants/setting.mojom.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search.mojom.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search_result_icon.mojom.h"
#include "chrome/browser/ui/webui/settings/chromeos/search/search_tag_registry.h"
#include "chrome/browser/ui/webui/webui_util.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "content/public/browser/web_ui_data_source.h"
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/bluetooth_device.h"
#include "device/bluetooth/chromeos/bluetooth_utils.h"
#include "device/bluetooth/dbus/bluez_dbus_manager.h"
#include "device/bluetooth/strings/grit/bluetooth_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/webui/web_ui_util.h"
namespace chromeos {
namespace settings {
namespace {
const std::vector<SearchConcept>& GetBluetoothSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_BLUETOOTH,
mojom::kBluetoothDevicesSubpagePath,
mojom::SearchResultIcon::kBluetooth,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSubpage,
{.subpage = mojom::Subpage::kBluetoothDevices}},
});
return *tags;
}
const std::vector<SearchConcept>& GetBluetoothOnSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_BLUETOOTH_TURN_OFF,
mojom::kBluetoothDevicesSubpagePath,
mojom::SearchResultIcon::kBluetooth,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kBluetoothOnOff},
{IDS_OS_SETTINGS_TAG_BLUETOOTH_TURN_OFF_ALT1,
SearchConcept::kAltTagEnd}},
});
return *tags;
}
const std::vector<SearchConcept>& GetBluetoothOffSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_BLUETOOTH_TURN_ON,
mojom::kBluetoothDevicesSubpagePath,
mojom::SearchResultIcon::kBluetooth,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kBluetoothOnOff},
{IDS_OS_SETTINGS_TAG_BLUETOOTH_TURN_ON_ALT1, SearchConcept::kAltTagEnd}},
});
return *tags;
}
const std::vector<SearchConcept>& GetBluetoothConnectableSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_BLUETOOTH_CONNECT,
mojom::kBluetoothDevicesSubpagePath,
mojom::SearchResultIcon::kBluetooth,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kBluetoothConnectToDevice}},
});
return *tags;
}
const std::vector<SearchConcept>& GetBluetoothConnectedSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_BLUETOOTH_DISCONNECT,
mojom::kBluetoothDevicesSubpagePath,
mojom::SearchResultIcon::kBluetooth,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kBluetoothDisconnectFromDevice}},
});
return *tags;
}
const std::vector<SearchConcept>& GetBluetoothPairableSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_BLUETOOTH_PAIR,
mojom::kBluetoothDevicesSubpagePath,
mojom::SearchResultIcon::kBluetooth,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kBluetoothPairDevice}},
});
return *tags;
}
const std::vector<SearchConcept>& GetBluetoothPairedSearchConcepts() {
static const base::NoDestructor<std::vector<SearchConcept>> tags({
{IDS_OS_SETTINGS_TAG_BLUETOOTH_UNPAIR,
mojom::kBluetoothDevicesSubpagePath,
mojom::SearchResultIcon::kBluetooth,
mojom::SearchResultDefaultRank::kMedium,
mojom::SearchResultType::kSetting,
{.setting = mojom::Setting::kBluetoothUnpairDevice},
{IDS_OS_SETTINGS_TAG_BLUETOOTH_UNPAIR_ALT1, SearchConcept::kAltTagEnd}},
});
return *tags;
}
} // namespace
BluetoothSection::BluetoothSection(Profile* profile,
SearchTagRegistry* search_tag_registry)
: OsSettingsSection(profile, search_tag_registry) {
// Note: May be uninitialized in tests.
if (bluez::BluezDBusManager::IsInitialized()) {
device::BluetoothAdapterFactory::Get()->GetAdapter(
base::Bind(&BluetoothSection::OnFetchBluetoothAdapter,
weak_ptr_factory_.GetWeakPtr()));
}
}
BluetoothSection::~BluetoothSection() {
if (bluetooth_adapter_)
bluetooth_adapter_->RemoveObserver(this);
}
void BluetoothSection::AddLoadTimeData(content::WebUIDataSource* html_source) {
static constexpr webui::LocalizedString kLocalizedStrings[] = {
{"bluetoothConnected", IDS_SETTINGS_BLUETOOTH_CONNECTED},
{"bluetoothConnectedWithBattery",
IDS_SETTINGS_BLUETOOTH_CONNECTED_WITH_BATTERY},
{"bluetoothConnecting", IDS_SETTINGS_BLUETOOTH_CONNECTING},
{"bluetoothDeviceListPaired", IDS_SETTINGS_BLUETOOTH_DEVICE_LIST_PAIRED},
{"bluetoothDeviceListUnpaired",
IDS_SETTINGS_BLUETOOTH_DEVICE_LIST_UNPAIRED},
{"bluetoothConnect", IDS_SETTINGS_BLUETOOTH_CONNECT},
{"bluetoothDisconnect", IDS_SETTINGS_BLUETOOTH_DISCONNECT},
{"bluetoothToggleA11yLabel",
IDS_SETTINGS_BLUETOOTH_TOGGLE_ACCESSIBILITY_LABEL},
{"bluetoothExpandA11yLabel",
IDS_SETTINGS_BLUETOOTH_EXPAND_ACCESSIBILITY_LABEL},
{"bluetoothNoDevices", IDS_SETTINGS_BLUETOOTH_NO_DEVICES},
{"bluetoothNoDevicesFound", IDS_SETTINGS_BLUETOOTH_NO_DEVICES_FOUND},
{"bluetoothNotConnected", IDS_SETTINGS_BLUETOOTH_NOT_CONNECTED},
{"bluetoothPageTitle", IDS_SETTINGS_BLUETOOTH},
{"bluetoothPairDevicePageTitle",
IDS_SETTINGS_BLUETOOTH_PAIR_DEVICE_TITLE},
{"bluetoothRemove", IDS_SETTINGS_BLUETOOTH_REMOVE},
{"bluetoothPrimaryUserControlled",
IDS_SETTINGS_BLUETOOTH_PRIMARY_USER_CONTROLLED},
{"bluetoothDeviceType_computer",
IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_COMPUTER},
{"bluetoothDeviceType_phone",
IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_PHONE},
{"bluetoothDeviceType_modem",
IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_MODEM},
{"bluetoothDeviceType_audio",
IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_AUDIO},
{"bluetoothDeviceType_carAudio",
IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_CAR_AUDIO},
{"bluetoothDeviceType_video",
IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_VIDEO},
{"bluetoothDeviceType_peripheral",
IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_PERIPHERAL},
{"bluetoothDeviceType_joystick",
IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_JOYSTICK},
{"bluetoothDeviceType_gamepad",
IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_GAMEPAD},
{"bluetoothDeviceType_keyboard",
IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_KEYBOARD},
{"bluetoothDeviceType_mouse",
IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_MOUSE},
{"bluetoothDeviceType_tablet",
IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_TABLET},
{"bluetoothDeviceType_keyboardMouseCombo",
IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_KEYBOARD_MOUSE_COMBO},
{"bluetoothDeviceType_unknown",
IDS_BLUETOOTH_ACCESSIBILITY_DEVICE_TYPE_UNKNOWN},
};
AddLocalizedStringsBulk(html_source, kLocalizedStrings);
chromeos::bluetooth_dialog::AddLocalizedStrings(html_source);
}
int BluetoothSection::GetSectionNameMessageId() const {
return IDS_SETTINGS_BLUETOOTH;
}
mojom::Section BluetoothSection::GetSection() const {
return mojom::Section::kBluetooth;
}
mojom::SearchResultIcon BluetoothSection::GetSectionIcon() const {
return mojom::SearchResultIcon::kBluetooth;
}
std::string BluetoothSection::GetSectionPath() const {
return mojom::kBluetoothSectionPath;
}
void BluetoothSection::RegisterHierarchy(HierarchyGenerator* generator) const {
generator->RegisterTopLevelSubpage(IDS_SETTINGS_BLUETOOTH,
mojom::Subpage::kBluetoothDevices,
mojom::SearchResultIcon::kBluetooth,
mojom::SearchResultDefaultRank::kMedium,
mojom::kBluetoothDevicesSubpagePath);
static constexpr mojom::Setting kBluetoothDevicesSettings[] = {
mojom::Setting::kBluetoothOnOff,
mojom::Setting::kBluetoothConnectToDevice,
mojom::Setting::kBluetoothDisconnectFromDevice,
mojom::Setting::kBluetoothPairDevice,
mojom::Setting::kBluetoothUnpairDevice,
};
RegisterNestedSettingBulk(mojom::Subpage::kBluetoothDevices,
kBluetoothDevicesSettings, generator);
generator->RegisterTopLevelAltSetting(mojom::Setting::kBluetoothOnOff);
}
void BluetoothSection::AdapterPresentChanged(device::BluetoothAdapter* adapter,
bool present) {
UpdateSearchTags();
}
void BluetoothSection::AdapterPoweredChanged(device::BluetoothAdapter* adapter,
bool powered) {
UpdateSearchTags();
}
void BluetoothSection::DeviceAdded(device::BluetoothAdapter* adapter,
device::BluetoothDevice* device) {
UpdateSearchTags();
}
void BluetoothSection::DeviceChanged(device::BluetoothAdapter* adapter,
device::BluetoothDevice* device) {
UpdateSearchTags();
}
void BluetoothSection::DeviceRemoved(device::BluetoothAdapter* adapter,
device::BluetoothDevice* device) {
UpdateSearchTags();
}
void BluetoothSection::OnFetchBluetoothAdapter(
scoped_refptr<device::BluetoothAdapter> bluetooth_adapter) {
bluetooth_adapter_ = bluetooth_adapter;
bluetooth_adapter_->AddObserver(this);
UpdateSearchTags();
}
void BluetoothSection::UpdateSearchTags() {
SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate();
// Start with no search tags, then add them below if appropriate.
updater.RemoveSearchTags(GetBluetoothSearchConcepts());
updater.RemoveSearchTags(GetBluetoothOnSearchConcepts());
updater.RemoveSearchTags(GetBluetoothOffSearchConcepts());
updater.RemoveSearchTags(GetBluetoothConnectableSearchConcepts());
updater.RemoveSearchTags(GetBluetoothConnectedSearchConcepts());
updater.RemoveSearchTags(GetBluetoothPairableSearchConcepts());
updater.RemoveSearchTags(GetBluetoothPairedSearchConcepts());
if (!bluetooth_adapter_->IsPresent())
return;
updater.AddSearchTags(GetBluetoothSearchConcepts());
if (!bluetooth_adapter_->IsPowered()) {
updater.AddSearchTags(GetBluetoothOffSearchConcepts());
return;
}
updater.AddSearchTags(GetBluetoothOnSearchConcepts());
// Filter devices so that only those shown in the UI are returned. Note that
// passing |max_devices| of 0 indicates that there is no maximum.
device::BluetoothAdapter::DeviceList devices =
device::FilterBluetoothDeviceList(bluetooth_adapter_->GetDevices(),
device::BluetoothFilterType::KNOWN,
/*max_devices=*/0);
bool connectable_device_exists = false;
bool connected_device_exists = false;
bool pairable_device_exists = false;
bool paired_device_exists = false;
for (const device::BluetoothDevice* device : devices) {
// Note: Device must be paired to be connectable.
if (device->IsPaired() && device->IsConnectable() && !device->IsConnected())
connectable_device_exists = true;
if (device->IsConnected())
connected_device_exists = true;
if (device->IsPairable() && !device->IsPaired())
pairable_device_exists = true;
if (device->IsPaired())
paired_device_exists = true;
}
if (connectable_device_exists)
updater.AddSearchTags(GetBluetoothConnectableSearchConcepts());
if (connected_device_exists)
updater.AddSearchTags(GetBluetoothConnectedSearchConcepts());
if (pairable_device_exists)
updater.AddSearchTags(GetBluetoothPairableSearchConcepts());
if (paired_device_exists)
updater.AddSearchTags(GetBluetoothPairedSearchConcepts());
}
} // namespace settings
} // namespace chromeos
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
c346c2f437068ba336bfc113a5a6f5d553f6ce77 | 617a0fedbf04c3bcb8cd545b20d6f0402e9b3874 | /12 IO/文件的输入输出4.cpp | c7e9721154595c8482f35c6b84a091d4eb79c822 | [] | no_license | ZhouXing-19/nailit_cpp | 006b9fa5b438bbca135b5ddb49aac9d941dc2faf | 54d1dc315654a93fa309297b22ecf6a5523e4244 | refs/heads/master | 2020-05-24T06:22:59.561917 | 2019-06-06T08:21:31 | 2019-06-06T08:21:31 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 427 | cpp | # include <iostream>
# include <fstream>
using namespace std;
int main(){
string name;
int score,sum = 0,cnt = 0;
ifstream myin("F:/Travail/大四下/cpp/nailit_cpp/files/2.txt",ios::in); //从文件中读取,ios::in可省略
if(myin){
while(myin>>name){ //不停读取?
myin>>score;
cout<<cnt<<endl;
sum = sum+score;
cnt ++;
}
cout<<"avg = "<<sum/(double)cnt<<endl;
cout<<"cnt = "<<cnt<<endl;
}
};
| [
"jane.c.xing@gmail.com"
] | jane.c.xing@gmail.com |
769411d9efaa3a084772e16295c077a5707c1a89 | 70c00133e353a5555514327f0a3a20e9bd3de737 | /Problem-1339.cpp | cefcf99cdf4c0969699952c455ddd1edc76c19ff | [] | no_license | VikasKumarRoy/Leetcode | 536d33a67d5448d75171682d82be7518648f39af | 953fe0380c0e64077fb2943d06b4ec0638a3c688 | refs/heads/master | 2021-06-25T16:18:47.367509 | 2021-03-21T16:58:45 | 2021-03-21T16:58:45 | 200,166,984 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 774 | cpp | // Problem - 1339
// https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/
// O(n) time complexity and O(height) space complexity solution
class Solution {
public:
int mod = 1e9 + 7;
int getSum(TreeNode* root) {
if(!root) {
return 0;
}
return root->val + getSum(root->left) + getSum(root->right);
}
long long dfs(TreeNode* root, long long& mx, int sum) {
if(!root) {
return 0;
}
long curr = root->val + dfs(root->left, mx, sum) + dfs(root->right, mx, sum);
mx = max(mx, ;
return curr;
}
int maxProduct(TreeNode* root) {
int sum = getSum(root);
int mx = 0;
dfs(root, mx, sum);
return mx;
}
}; | [
"vikas.vr8@gmail.com"
] | vikas.vr8@gmail.com |
868336833c62fe36b1da2d5be5bf9a033a6b82c9 | 7a6897a1a74d8fd239881a4388887003f4ab24a1 | /sortindex.hpp | 44981bfd4f58433758e307cb17237ddb8ed63ad2 | [
"MIT"
] | permissive | dongliangchu/Stellar_Dynearth3D | 9229f011caaf76e6061a667e1840b4b617fdc7fb | 0f440bf956ba9d58a9da25b02071b712d1760a25 | refs/heads/master | 2021-01-02T23:07:55.305447 | 2014-10-07T18:22:31 | 2014-10-07T18:22:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,196 | hpp | #ifndef DYNEARTHSOL3D_SORTINDEX_HPP
#define DYNEARTHSOL3D_SORTINDEX_HPP
#include <numeric>
template< typename T >
class idx_lt {
const std::vector<T>& _x;
public:
idx_lt( const std::vector<T>& x ) : _x(x) {}
bool operator()( std::size_t left, std::size_t right ) const { return _x[left] < _x[right]; }
};
template< typename T >
class idx_gt {
const std::vector<T>& _x;
public:
idx_gt( const std::vector<T>& x ) : _x(x) {}
bool operator()( std::size_t left, std::size_t right ) const { return _x[left] > _x[right]; }
};
/* sort x in ascending order, x is not modified, the sorted order is stored in idx */
template< typename T >
void sortindex(const std::vector<T>& x, std::vector<std::size_t>& idx)
{
// fill idx = [0, 1, 2, ...]
std::iota(idx.begin(), idx.end(), 0);
std::sort(idx.begin(), idx.end(), idx_lt<T>(x));
}
/* sort x in descending order, x is not modified, the sorted order is stored in idx */
template< typename T >
void sortindex_reversed(const std::vector<T>& x, std::vector<std::size_t>& idx)
{
// fill idx = [0, 1, 2, ...]
std::iota(idx.begin(), idx.end(), 0);
std::sort(idx.begin(), idx.end(), idx_gt<T>(x));
}
#endif
| [
"dchu@head.cluster"
] | dchu@head.cluster |
82a1a365ad03acb33c6746fd585c67dbba479167 | 4558f6494dcdc5f97757df21f643dda52fcb1fc5 | /src/Box.h | 0e902d1595c7cb1a8c81ad667e390d07b5df2cd0 | [] | no_license | rocketeer55/raytracer-rocketeer55 | 3e5d66eb9c4d379940adbc89058f4bbd0200a36a | 057f2e3efc0c161f46b149571b76ddc742ca174a | refs/heads/master | 2020-03-10T09:27:08.690541 | 2018-06-16T00:38:14 | 2018-06-16T00:38:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 412 | h | #ifndef BOX_H
#define BOX_H
#include "Object.h"
namespace Objects {
struct Box : public Object {
glm::vec3 min, max;
Box();
Box(glm::vec3 _min, glm::vec3 _max);
Box(const Box &other);
std::string type();
float getFirstCollision(Ray &ray);
glm::vec3 getNormal(glm::vec3 point);
void setPosition(glm::vec3 position);
glm::vec3 getPosition();
void calculateBoundingBox();
};
}
#endif | [
"spencer.schurk@gmail.com"
] | spencer.schurk@gmail.com |
bffeff89aef98f4c3b4e95a450a35d66bbedd581 | b71556aee4654b48e91ba8124a3a8ded26de273e | /contest/Summer/day8/C.cpp | 695c4a3ec363185283b4e305b9e82b931a8076e5 | [] | no_license | young-zy/algorithm | 0255a327390c6b149870b34fbd34816dc002e82e | 536eddd9a6bc03e81c566afa05c53f555eb14a86 | refs/heads/master | 2021-07-23T07:23:29.929221 | 2020-04-23T16:33:28 | 2020-04-23T16:33:28 | 149,439,464 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 828 | cpp | #include <bits/stdc++.h>
#define mod 998244353
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int countb[200005];
int main(int argc, char** argv) {
int n,m;
cin>>n>>m;
long long ans = 0;
string a,b;
cin>>a>>b;
for(int i = 0; i<m ; i++){
if(b[i] == '1'){
if(i == 0){
countb[0] = 1;
}else{
countb[i] = countb[i-1]+1;
}
}else{
if(i == 0){
countb[i] = 0;
}else{
countb[i] = countb[i-1];
}
}
}
long long base = 1;
for(int i = n-1;i>=0;i--){
int count = 0;
if(m-n+i < 0){
break;
}
if(a[i] == '1'){
count = m-n+i+1;
}else{
count = countb[m-n+i];
}
if(count < 0){
count = 0;
}
ans += (base*(count%mod))%mod;
ans %= mod;
base *= 2;
base %= mod;
}
cout<<ans;
return 0;
} | [
"youngzhaozhou@gmail.com"
] | youngzhaozhou@gmail.com |
17c7daa3f14590747fde8f8713339d94692e0f0a | 544dfbd73bff6cc0d8079cfac8531b90a56b5846 | /project2/hero.h | 83cf212b9290ba1d22da7111b22a9e76e8ccee50 | [] | no_license | whitneysit/AI | 4f3aa0f7b91b707b8ff649fd2ef6b632151d2345 | 9e7f053ec1da5524cb107abb73f2ec1496eeb64d | refs/heads/master | 2020-04-29T14:32:40.562364 | 2019-04-26T09:26:59 | 2019-04-26T09:26:59 | 176,199,510 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 716 | h | #ifndef HERO
#define HERO
class hero
{
private:
int heroID;
double power;
double teamMastery;
double opponentMastery;
int membershipIndicator; //you(1), opponent(2), available(0)
public:
hero(int heroID, double power, double teamMastery, double opponentMastery, int membershipIndicator);
~hero(){};
int getHeroID(){ return this->heroID; }
double getPower(){ return this->power; }
double getTeamMastery(){ return this->teamMastery; }
double getOpponentMastery(){ return this->opponentMastery; }
void setMembershipIndicator(int membershipIndicator){ this->membershipIndicator = membershipIndicator; }
int getMembershipIndicator(){ return this->membershipIndicator; }
void printStats();
};
#endif | [
"wsit@usc.edu"
] | wsit@usc.edu |
7a2e9990ba29416038bef1b76cd6ce29a1cb5470 | 36183993b144b873d4d53e7b0f0dfebedcb77730 | /GameDevelopment/Game Programming Gems 3/Source Code/03 Artificial Intelligence/06 Sterren/aseDoc.h | 5155dd78b6995ad01d30c0ec5c979ec87552320a | [] | no_license | alecnunn/bookresources | b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0 | 4562f6430af5afffde790c42d0f3a33176d8003b | refs/heads/master | 2020-04-12T22:28:54.275703 | 2018-12-22T09:00:31 | 2018-12-22T09:00:31 | 162,790,540 | 20 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 7,005 | h | /* Copyright (C) William van der Sterren, 2002.
* All rights reserved worldwide.
*
* This software is provided "as is" without express or implied
* warranties. You may freely copy and compile this source into
* applications you distribute provided that the copyright text
* below is included in the resulting source code, for example:
* "Portions Copyright (C) William van der Sterren, 2002"
*/
/* Copyright (C) James Matthews, 2001.
* All rights reserved worldwide.
*
* This software is provided "as is" without express or implied
* warranties. You may freely copy and compile this source into
* applications you distribute provided that the copyright text
* below is included in the resulting source code, for example:
* "Portions Copyright (C) James Matthews, 2001"
*/
#ifndef _AFX_ASEDOC_H_
#define _AFX_ASEDOC_H_
#if _MSC_VER > 1000
#pragma once
#endif
#define ASE_GRIDSIZE 8
#define ASE_BOARDX 320
#define ASE_BOARDY 240
#include "pathfinder.h"
#include "nodeview.h"
#include "aseview.h"
#include "ase_terrain.h"
#include "ase_threatboard.h"
#include "ase_search.h"
#include "ase_losapproxboard.h"
class CAseDoc : public CDocument
{
protected:
CAseDoc();
DECLARE_DYNCREATE(CAseDoc)
// movement type
public:
bool DoesUseDiagonalMovement() const
{ return ( m_bMovementDiagonal ); }
protected:
bool m_bMovementDiagonal;
// movement costs
public:
bool DoesUseCellBasedMovementCosts() const
{ return !m_bMovementCostsVectorBased; }
bool DoesUseVectorBasedMovementCosts() const
{ return m_bMovementCostsVectorBased; }
bool DoesUseRelativeMovementCosts() const
{ return m_bMovementCostsRelative; }
protected: // move to terrain?
bool m_bMovementCostsVectorBased;
bool m_bMovementCostsRelative;
void SelectMovementCostFunctions();
// threat costs
public:
bool DoesUseThreatCosts() const
{ return !m_bThreatCostsNone; }
bool DoesUseAimingThreatCosts() const
{ return m_bThreatLineOfFireWithAimingCosts; }
bool DoesUseThreatCountCosts() const
{ return m_bThreatCountCosts; }
bool DoesUseDistanceToThreatCosts() const
{ return m_bDistanceToThreatCosts; }
bool DoesUseThreatCostsFromApproxTable() const
{ return m_bThreatCostsFromApproximatedTable; }
protected: // move to threat board?
bool m_bThreatCostsNone;
bool m_bThreatCostsSimple;
bool m_bThreatLineOfFireWithAimingCosts;
bool m_bThreatCountCosts;
bool m_bDistanceToThreatCosts;
bool m_bThreatCostsFromApproximatedTable;
void SetThreatCostsMode();
void SelectThreatCostFunctions();
// views
public:
bool DoesDisplayThreatPositions() const
{ return m_bThreatPositions; }
bool DoesDisplayThreatLinesOfFire() const
{ return m_bThreatLinesOfFire; }
bool DoesDisplaySearchSpace() const
{ return m_bSearchSpace; }
bool DoesDisplayRoute() const
{ return m_bDrawRoute; }
bool DoesDisplayApproximatedLinesOfFire() const
{ return m_bDrawApproximatedLinesOfFire; }
protected:
bool m_bSearchSpace;
bool m_bThreatPositions;
bool m_bThreatLinesOfFire;
bool m_bDrawRoute;
bool m_bDrawApproximatedLinesOfFire;
// a-star algorithm
public:
bool Stepping() { return m_bStepped; }
void NodeAdded(_asNode *, int);
void NotifyClick();
void DrawNode(_asNode *);
void GetStartEnd(CPoint &x, CPoint &y) { x = m_cStart, y = m_cEnd; }
void SetStartEnd(CPoint x, CPoint y) { m_cStart = x, m_cEnd = y; }
void SetBreakpoint(CPoint bp) { m_cBreakpoint = bp; m_iBreakData = -1; }
CPoint GetBreakpoint() { return m_cBreakpoint; }
CAStar *GetPathFinder() { return &m_cAStar; }
//! check whether move is valid
static int AS_Valid(_asNode *, _asNode *, int, void *);
ASE_TerrainBoard* GetTerrainBoard()
{
return &m_TerrainBoard;
}
ASE_SearchBoard* GetSearchSpaceBoard()
{
return &m_SearchSpaceBoard;
}
ASE_ThreatBoard* GetThreatBoard()
{
return &m_ThreatBoard;
}
ASE_LOSApproximationBoard* GetLOSApproximationBoard()
{
return &m_LOSApproximationBoard;
}
//{{AFX_VIRTUAL(CAseDoc)
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
virtual BOOL OnOpenDocument(LPCTSTR lpszPathName);
//}}AFX_VIRTUAL
public:
void ListChanges(_asNode *, UINT);
virtual ~CAseDoc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// status bar
void SetStatusBarText(const char* aText);
protected:
bool m_bStepped;
bool m_bBreakpointHit;
bool m_bContinualUpdate;
//! boards used to describe/illustrate terrain, threat positions and search activity
ASE_TerrainBoard m_TerrainBoard;
ASE_ThreatBoard m_ThreatBoard;
ASE_SearchBoard m_SearchSpaceBoard;
ASE_LOSApproximationBoard m_LOSApproximationBoard;
int m_iBreakData;
CPoint m_cStart;
CPoint m_cEnd;
CPoint m_cBreakpoint;
UINT m_uBrushType;
_asNode *m_pcBreakNode;
CAStar m_cAStar;
bool SetupAStar(bool stepped = false);
inline void MessageBox(CString, CString, UINT);
CNodeView *GetNodeView();
CAseView *GetAseView();
//{{AFX_MSG(CAseDoc)
afx_msg void OnRunToBreakpoint();
afx_msg void OnUpdateRunToBreakpoint(CCmdUI* pCmdUI);
afx_msg void OnExecuteAStar();
afx_msg void OnStepAStar();
afx_msg void OnUpdatePathingAllowDiagonal(CCmdUI* pCmdUI);
afx_msg void OnViewARoute();
afx_msg void OnUpdateViewARoute(CCmdUI* pCmdUI);
afx_msg void OnPathingContinuousUpdate();
afx_msg void OnUpdatePathingContinuousUpdate(CCmdUI* pCmdUI);
afx_msg void OnViewSearchspace();
afx_msg void OnUpdateViewSearchspace(CCmdUI* pCmdUI);
//}}AFX_MSG
afx_msg void OnBrushType(UINT);
afx_msg void OnUpdateUIBrushType(CCmdUI* pCmdUI);
afx_msg void OnBreakpointType(UINT);
afx_msg void OnUpdateUIBreakpointType(CCmdUI* pCmdUI);
afx_msg void OnViewLineOfFire();
afx_msg void OnUpdateUIViewLineOfFire(CCmdUI* pCmdUI);
afx_msg void OnViewThreats();
afx_msg void OnUpdateUIViewThreats(CCmdUI* pCmdUI);
afx_msg void OnViewApproximatedLinesOfFire();
afx_msg void OnUpdateUIViewApproximatedLinesOfFire(CCmdUI* pCmdUI);
afx_msg void OnMovementType(UINT);
afx_msg void OnUpdateUIMovementType(CCmdUI* pCmdUI);
afx_msg void OnMovementCosts(UINT);
afx_msg void OnUpdateUIMovementCosts(CCmdUI* pCmdUI);
afx_msg void OnThreatCosts(UINT);
afx_msg void OnUpdateUIThreatCosts(CCmdUI* pCmdUI);
afx_msg void OnThreatMovement(UINT);
afx_msg void OnUpdateUIThreatMovement(CCmdUI* pCmdUI);
afx_msg void OnThreatDistanceBasedCosts();
afx_msg void OnUpdateUIThreatDistanceBasedCosts(CCmdUI* pCmdUI);
afx_msg void OnThreatCountBasedCosts();
afx_msg void OnUpdateUIThreatCountBasedCosts(CCmdUI* pCmdUI);
afx_msg void OnThreatFromApproxTableCosts();
afx_msg void OnUpdateUIThreatFromApproxTableCosts(CCmdUI* pCmdUI);
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
#endif
| [
"alec.nunn@gmail.com"
] | alec.nunn@gmail.com |
ba973515c1d831681d19b5cde83262ae11dfefff | e60112ee47d6887f00512e01d2c919495d578335 | /internal/iric_util.h | 714b70580727f98fff6be4e46f91da202e439dac | [
"MIT"
] | permissive | usgs-coupled/iriclib-test | 85ef24ef493d6caf8973405fffe1d2f387606a00 | f89e03024788d3ae8d8b751007fe38f341b9196f | refs/heads/develop_v4 | 2023-08-14T19:20:20.815199 | 2021-09-14T21:22:35 | 2021-09-14T21:22:35 | 406,461,481 | 0 | 1 | MIT | 2021-09-14T21:22:00 | 2021-09-14T17:25:28 | C++ | UTF-8 | C++ | false | false | 435 | h | #ifndef IRIC_UTIL_H
#define IRIC_UTIL_H
#include <string>
namespace iRICLib {
class H5CgnsZone;
int _iric_get_zone(int fid, int gid, H5CgnsZone** zone, const std::string& f_name);
int _iric_get_zone_for_solread(int fid, int gid, int solid, H5CgnsZone** zone, const std::string& f_name);
int _iric_get_zone_for_solwrite(int fid, int gid, H5CgnsZone** zone, const std::string& f_name);
} // namespace iRICLib
#endif // IRIC_UTIL_H
| [
"kskinoue@gmail.com"
] | kskinoue@gmail.com |
c5ae6e97cb224cb5ff4c30e99282ba23004a55d0 | ec390da9ff15cb2114e16742b6cad780732913b5 | /iter1/994.cpp | 011e245bbbf05a1dbd25d8bedc260ad72d34292d | [] | no_license | xiaomi388/LeetCode | 6107487537eeb1ac6128955cd30868985d1509ea | 877d0fbccc684e4fd7fee2aca63d2656f71a0241 | refs/heads/master | 2021-09-26T19:52:34.207507 | 2021-09-17T20:32:53 | 2021-09-17T20:32:53 | 241,884,416 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,382 | cpp | // BFS技巧:1. dir_x, dir_y,用于控制一个循环就获取所有下一阶的点
// 2. 层级BFS,在循环内再做一个循环,循环次数是当前queue的大小
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
queue<pair<int, int>> q;
int orgLeft = 0;
for (int i = 0; i < grid.size(); ++i) {
for (int j = 0; j < grid[0].size(); ++j) {
if (grid[i][j] == 2) q.push({i, j});
else if (grid[i][j] == 1) orgLeft++;
}
}
if (orgLeft == 0) return 0;
int ts = 0;
while (!q.empty()) {
ts++;
int t = q.size();
while (t--) {
auto cord = q.front(); q.pop();
static vector<int> dir_x{0, 0, 1, -1};
static vector<int> dir_y{1, -1, 0, 0};
for (int i = 0; i < 4; ++i) {
int tx = cord.first + dir_x[i], ty = cord.second + dir_y[i];
if (tx >= 0 && tx < grid.size() &&
ty >= 0 && ty < grid[0].size() &&
grid[tx][ty] == 1) {
orgLeft--;
grid[tx][ty] = 2;
q.push({tx, ty});
}
}
}
}
return orgLeft ? -1 : ts-1;
}
};
| [
"xiaomi388@gmail.com"
] | xiaomi388@gmail.com |
412337f30d2c9ebe20c1973831585d0bcb394def | 04c6d6a2534fa2e63aba918f2c038f45915ff828 | /动态规划/背包dp/2218. Maximum Value of K Coins From Piles.cpp | 8d5247fa0a35519c728a31a8dfe444f9551f6b24 | [] | no_license | ttzztztz/leetcodeAlgorithms | 7fdc15267ba9e1304f7c817ea9d3f1bd881b004b | d2ee1c8fecb8fc07e3c7d67dc20b964a606e065c | refs/heads/master | 2023-08-19T10:50:40.340415 | 2023-08-02T03:00:38 | 2023-08-02T03:00:38 | 206,009,736 | 17 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,018 | cpp | class Solution {
public:
int maxValueOfCoins(vector<vector<int>>& piles, int k) {
int f[2005][2005];
vector<vector<int>> psum;
memset(f, 0xff, sizeof f);
const int n = piles.size();
for (int i = 0; i < n; i++) {
vector<int> p(piles[i].size() + 1, 0);
for (int j = 1; j <= piles[i].size(); j++) {
p[j] = p[j - 1] + piles[i][j - 1];
}
psum.push_back(p);
}
for (int idx = psum.size(); idx >= 0; idx--) for (int remain = k; remain >= 0; remain--) {
int& val = f[idx][remain];
if (idx == psum.size()) {
val = 0;
continue;
}
int ans = 0;
for (int j = 0; j < psum[idx].size() && remain - j >= 0; j++) {
// j: [remain, len]
ans = max(ans, psum[idx][j] + f[idx + 1][remain - j]);
}
val = ans;
}
return f[0][k];
}
};
| [
"yangziyue80@outlook.com"
] | yangziyue80@outlook.com |
fca7c464067c484dce2c5a06e77ce356864ebe0c | d440f00e5e541bf5f8f45d84b65aae2bd30dafa5 | /atcoder/abc/abc165/questionB/main.cc | 675bc01379ab2b17d169108dcdf80047570951e7 | [] | no_license | negibokken/sandbox | dd8fc47d1e0f38eb3aad5284d1fb21380801f1e1 | 852ea91af5987906a00dd681658f01c457e966bd | refs/heads/main | 2023-02-08T23:51:28.119011 | 2022-11-14T06:05:35 | 2022-11-14T06:05:35 | 88,619,333 | 0 | 0 | null | 2023-01-27T04:28:16 | 2017-04-18T11:53:05 | C++ | UTF-8 | C++ | false | false | 2,587 | cc | #include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef pair<int, char> Pc;
typedef pair<int, string> Ps;
const int dx[4] = {-1, 0, 0, 1};
const int dy[4] = {0, -1, 1, 0};
const int dx8[8] = {0, 1, 1, 1, 0, -1, -1, -1};
const int dy8[8] = {-1, -1, 0, 1, 1, 1, 0, -1};
const string dir8[8] = {"U", "RU", "R", "RD", "D", "LD", "L", "LU"};
// Self settings
// clang-format off
#define MAX_N 100000
#define MAX 100000
#define INFTY (1<<30)
#define EPS (1e-10)
#define equals(a, b) (fabs((a) - (b)) < EPS)
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i, N) for (int i = 0; i < (int)(N); ++i)
#define SLN(i,N) (i == N-1 ? "\n" : " ")
ll fact(ll n) { ll res = 1; for(ll i=2;i<=n;++i) res = res * i; return res;}
ll nCr(ll n, ll r) {return (fact(n)/fact(n-r)*fact(r)) ;}
ll gcd(ll a,ll b){if(b==0)return a;return gcd(b,a%b);}
ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
const ll MOD = 1e9+7;
const ll INF = 1LL << 60;
const int inf = 1000100011;
class Point { public: double x, y; Point(double x = 0, double y = 0) : x(x), y(y) {} Point operator+(Point p) { return Point(x + p.x, y + p.y); } Point operator-(Point p) { return Point(x - p.x, y - p.y); } Point operator*(double a) { return Point(a * x, a * y); } Point operator/(double a) { return Point(x / a, y / a); } double abs() { return sqrt(norm()); } double norm() { return x * x + y * y; } bool operator<(const Point& p) const { return x != p.x ? x < p.x : y < p.y; } bool operator==(const Point& p) const { return fabs(x - p.y) < EPS && fabs(y - p.y) < EPS; } };
typedef Point Vector;
double norm(Vector a) { return a.x * a.x + a.y * a.y; }
double abs(Vector a) { return sqrt(norm(a));}
double dot(Vector a, Vector b) { return a.x * b.x + a.y * b.y; }
double cross(Vector a, Vector b) { return a.x * b.y - a.y * b.x; }
struct Segment { Point p1, p2; };
typedef Segment Line;
struct Node { int data; Node *left, *right; Node(int data) : data(data), left(NULL), right(NULL) {} };
// clang-format on
int main(void) {
cin.tie(0);
ios::sync_with_stdio(false);
std::cout << std::fixed << std::setprecision(15);
ll X;
cin >> X;
ll ans = 0;
long double y = 100;
for (int i = 0; i < 10000; i++) {
y = y + floor(y * 0.01);
if (y >= X) {
ans = i + 1;
break;
}
}
cout << ans << endl;
return 0;
}
| [
"negibokken@gmail.com"
] | negibokken@gmail.com |
7efc576a77a76c7589ea1e4ae575934f71541ddd | 17f37b79643b9c6acd181c55c43a3ab4c889433e | /cavity/62.2/U | 9344df6de15c0eed7e32c97c46fd3f9dcb27637e | [] | no_license | aashay201297/OpenFOAM-simulations | 5208b766ab1e715178e42c73d028cc43d17ec4c9 | 273f60ef66e6f5b0c99a53ac52de406be0e876a2 | refs/heads/master | 2021-01-23T06:34:17.044650 | 2017-06-04T19:02:27 | 2017-06-04T19:02:27 | 86,373,858 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,059 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: dev |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volVectorField;
location "62.2";
object U;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 1 -1 0 0 0 0];
internalField nonuniform List<vector>
400
(
(0.000253604 -0.000250268 0)
(0.000141506 0.00011154 0)
(-0.00117691 0.000564682 0)
(-0.00348127 0.000885055 0)
(-0.00637787 0.00104578 0)
(-0.0094701 0.00106181 0)
(-0.0124038 0.000957908 0)
(-0.014886 0.000760485 0)
(-0.0166907 0.000494675 0)
(-0.0176596 0.00018457 0)
(-0.0177034 -0.000145282 0)
(-0.0168063 -0.000468403 0)
(-0.0150311 -0.000755469 0)
(-0.012526 -0.000974332 0)
(-0.00952702 -0.00109126 0)
(-0.00635538 -0.00107408 0)
(-0.00340083 -0.000898175 0)
(-0.00108647 -0.000556419 0)
(0.000196455 -9.03651e-05 0)
(0.000267882 0.000262405 0)
(-7.73593e-05 -0.000169107 0)
(-0.00161147 0.00164514 0)
(-0.00569318 0.00361768 0)
(-0.0117197 0.00503527 0)
(-0.0188938 0.00574371 0)
(-0.0264029 0.00576068 0)
(-0.033472 0.0051721 0)
(-0.0394302 0.00409285 0)
(-0.0437478 0.00264785 0)
(-0.0460511 0.000966991 0)
(-0.0461334 -0.000813314 0)
(-0.0439651 -0.00254731 0)
(-0.0397045 -0.00407901 0)
(-0.0337055 -0.00524556 0)
(-0.0265155 -0.00588705 0)
(-0.018856 -0.00586532 0)
(-0.0115675 -0.00509514 0)
(-0.00551368 -0.00358967 0)
(-0.00149318 -0.00155923 0)
(-4.25762e-05 0.000227488 0)
(-0.000528605 0.00109184 0)
(-0.0037116 0.00573691 0)
(-0.0105897 0.0102254 0)
(-0.0199934 0.0134089 0)
(-0.0307675 0.0149476 0)
(-0.0418259 0.0148401 0)
(-0.0521245 0.0132569 0)
(-0.0607497 0.0104571 0)
(-0.0669755 0.00674254 0)
(-0.0702891 0.00243902 0)
(-0.070407 -0.0021068 0)
(-0.0672903 -0.00652611 0)
(-0.0611577 -0.0104302 0)
(-0.052493 -0.0134223 0)
(-0.0420406 -0.0151248 0)
(-0.0307764 -0.0152269 0)
(-0.0198307 -0.0135571 0)
(-0.0103644 -0.0101797 0)
(-0.00354878 -0.00555146 0)
(-0.000476878 -0.000948879 0)
(-0.000928285 0.0034802 0)
(-0.00569193 0.0122218 0)
(-0.015303 0.0199235 0)
(-0.0279192 0.0252 0)
(-0.041989 0.0275994 0)
(-0.0561839 0.0271398 0)
(-0.0692581 0.024111 0)
(-0.0801327 0.0189554 0)
(-0.0879559 0.0121965 0)
(-0.0921269 0.00440533 0)
(-0.0923114 -0.00380845 0)
(-0.0884577 -0.0117977 0)
(-0.0808117 -0.0188839 0)
(-0.0699287 -0.0243784 0)
(-0.0566738 -0.0276299 0)
(-0.0421981 -0.028104 0)
(-0.0278587 -0.0254996 0)
(-0.0150948 -0.0198931 0)
(-0.00550545 -0.0119285 0)
(-0.000861664 -0.00322507 0)
(-0.00127903 0.0068784 0)
(-0.00753661 0.0209554 0)
(-0.0198063 0.0325131 0)
(-0.0355377 0.0401065 0)
(-0.0527476 0.0432938 0)
(-0.0698641 0.0421962 0)
(-0.0854702 0.0372805 0)
(-0.0983685 0.0292153 0)
(-0.107628 0.0187786 0)
(-0.112597 0.00681406 0)
(-0.112906 -0.0057811 0)
(-0.108483 -0.0180564 0)
(-0.0995698 -0.0290139 0)
(-0.0867457 -0.0376358 0)
(-0.0709409 -0.0429484 0)
(-0.0534341 -0.0441321 0)
(-0.0357871 -0.0406816 0)
(-0.0197365 -0.0325947 0)
(-0.00737109 -0.0205919 0)
(-0.00120376 -0.00649856 0)
(-0.00160763 0.0112165 0)
(-0.00931862 0.0318769 0)
(-0.0242108 0.0479553 0)
(-0.0430054 0.0580761 0)
(-0.0632611 0.0619416 0)
(-0.0831583 0.0598854 0)
(-0.101131 0.052632 0)
(-0.1159 0.0411286 0)
(-0.126496 0.0264387 0)
(-0.132246 0.00969327 0)
(-0.132758 -0.00791724 0)
(-0.127931 -0.0251342 0)
(-0.117973 -0.0406281 0)
(-0.10344 -0.0530231 0)
(-0.0852736 -0.0609703 0)
(-0.064839 -0.0632841 0)
(-0.0438878 -0.0591456 0)
(-0.0244789 -0.0483472 0)
(-0.00925479 -0.0315593 0)
(-0.00153783 -0.0107291 0)
(-0.00194014 0.0164781 0)
(-0.0111217 0.044977 0)
(-0.0286516 0.0662373 0)
(-0.050482 0.0790641 0)
(-0.0736881 0.0834513 0)
(-0.0962079 0.0800789 0)
(-0.116357 0.0700285 0)
(-0.13282 0.0545879 0)
(-0.144637 0.0351335 0)
(-0.151148 0.0130851 0)
(-0.151955 -0.0100876 0)
(-0.146921 -0.032835 0)
(-0.136187 -0.0535031 0)
(-0.120228 -0.0703411 0)
(-0.0999363 -0.0815699 0)
(-0.0767041 -0.0855373 0)
(-0.052442 -0.0809678 0)
(-0.0295458 -0.0672803 0)
(-0.011284 -0.0449416 0)
(-0.00190014 -0.0159523 0)
(-0.00230009 0.0226961 0)
(-0.0130254 0.0603038 0)
(-0.0332516 0.0873678 0)
(-0.0580811 0.103001 0)
(-0.0840766 0.10767 0)
(-0.108956 0.102566 0)
(-0.130971 0.0892484 0)
(-0.148838 0.069414 0)
(-0.16167 0.0447735 0)
(-0.168872 0.0170202 0)
(-0.170067 -0.0121347 0)
(-0.165075 -0.0408958 0)
(-0.153933 -0.067318 0)
(-0.136973 -0.0892777 0)
(-0.114945 -0.104517 0)
(-0.0891776 -0.110801 0)
(-0.0616719 -0.106217 0)
(-0.035149 -0.0895829 0)
(-0.0135861 -0.0609518 0)
(-0.00232638 -0.0222784 0)
(-0.00271167 0.0299481 0)
(-0.0151081 0.0779594 0)
(-0.0381151 0.11136 0)
(-0.0658489 0.129754 0)
(-0.0943276 0.134322 0)
(-0.1211 0.126979 0)
(-0.144445 0.109906 0)
(-0.163215 0.0852849 0)
(-0.176689 0.0551689 0)
(-0.184408 0.0214873 0)
(-0.186059 -0.0138759 0)
(-0.181424 -0.0489591 0)
(-0.170396 -0.0815971 0)
(-0.153082 -0.109328 0)
(-0.129972 -0.129386 0)
(-0.102187 -0.138833 0)
(-0.0716901 -0.134891 0)
(-0.0414673 -0.115473 0)
(-0.0162882 -0.0798977 0)
(-0.00285472 -0.0298905 0)
(-0.00320765 0.0383606 0)
(-0.0174662 0.098092 0)
(-0.043341 0.138193 0)
(-0.0737566 0.15905 0)
(-0.10416 0.162906 0)
(-0.132032 0.152677 0)
(-0.155826 0.131345 0)
(-0.174679 0.101643 0)
(-0.188168 0.0659594 0)
(-0.196068 0.0263899 0)
(-0.198186 -0.0151137 0)
(-0.194284 -0.0565478 0)
(-0.184082 -0.0956455 0)
(-0.167367 -0.129693 0)
(-0.144216 -0.155428 0)
(-0.115339 -0.169102 0)
(-0.082446 -0.166807 0)
(-0.0486362 -0.145128 0)
(-0.0195288 -0.102162 0)
(-0.00353357 -0.0390481 0)
(-0.00384393 0.0481296 0)
(-0.0202461 0.120896 0)
(-0.0490463 0.167755 0)
(-0.081686 0.19037 0)
(-0.113053 0.192562 0)
(-0.140746 0.178619 0)
(-0.163621 0.152516 0)
(-0.181308 0.117596 0)
(-0.193846 0.0765368 0)
(-0.20136 0.0314948 0)
(-0.203856 -0.0156598 0)
(-0.201109 -0.0630527 0)
(-0.192648 -0.108494 0)
(-0.177857 -0.149175 0)
(-0.156223 -0.18142 0)
(-0.127779 -0.200611 0)
(-0.0936441 -0.201429 0)
(-0.056733 -0.178577 0)
(-0.0234798 -0.128175 0)
(-0.00443553 -0.0501052 0)
(-0.00472532 0.0595719 0)
(-0.0236945 0.146619 0)
(-0.0553825 0.199759 0)
(-0.0893756 0.222795 0)
(-0.120121 0.221896 0)
(-0.145674 0.203192 0)
(-0.165629 0.171844 0)
(-0.180369 0.131813 0)
(-0.190579 0.0859717 0)
(-0.196861 0.036377 0)
(-0.1995 -0.0153713 0)
(-0.198334 -0.067745 0)
(-0.192716 -0.11887 0)
(-0.181573 -0.166082 0)
(-0.163644 -0.205492 0)
(-0.137966 -0.231665 0)
(-0.104595 -0.237629 0)
(-0.0657333 -0.215528 0)
(-0.0283776 -0.15837 0)
(-0.00568207 -0.0635529 0)
(-0.00605152 0.0732289 0)
(-0.0282255 0.175565 0)
(-0.062508 0.233573 0)
(-0.0962557 0.25475 0)
(-0.123855 0.248735 0)
(-0.144396 0.22403 0)
(-0.158668 0.187111 0)
(-0.168104 0.142465 0)
(-0.174198 0.0929706 0)
(-0.178115 0.0403797 0)
(-0.180482 -0.0141991 0)
(-0.181263 -0.0698229 0)
(-0.179693 -0.125213 0)
(-0.174268 -0.178183 0)
(-0.162893 -0.224977 0)
(-0.143315 -0.259592 0)
(-0.113937 -0.273332 0)
(-0.0753927 -0.255069 0)
(-0.0345561 -0.193092 0)
(-0.00748626 -0.0801049 0)
(-0.00819199 0.0900467 0)
(-0.0344823 0.208022 0)
(-0.0704113 0.267886 0)
(-0.101022 0.283609 0)
(-0.121572 0.269814 0)
(-0.133105 0.237844 0)
(-0.138159 0.195407 0)
(-0.139458 0.147235 0)
(-0.139363 0.0959108 0)
(-0.13959 0.0426202 0)
(-0.141105 -0.0122334 0)
(-0.144051 -0.0685086 0)
(-0.147665 -0.125796 0)
(-0.150166 -0.182772 0)
(-0.148718 -0.236328 0)
(-0.139642 -0.28045 0)
(-0.119094 -0.305028 0)
(-0.0849353 -0.295161 0)
(-0.0424402 -0.232379 0)
(-0.010216 -0.100837 0)
(-0.0117674 0.111636 0)
(-0.0432593 0.243962 0)
(-0.0782962 0.300036 0)
(-0.100626 0.305095 0)
(-0.108348 0.280463 0)
(-0.105727 0.240385 0)
(-0.0975245 0.193284 0)
(-0.0877653 0.143551 0)
(-0.0794949 0.0930371 0)
(-0.074779 0.0420955 0)
(-0.0747967 -0.00972917 0)
(-0.0798849 -0.0632123 0)
(-0.0894576 -0.118992 0)
(-0.101784 -0.17696 0)
(-0.113683 -0.235287 0)
(-0.120302 -0.288885 0)
(-0.115261 -0.327198 0)
(-0.0922655 -0.331796 0)
(-0.0523153 -0.275405 0)
(-0.0144303 -0.127347 0)
(-0.0175492 0.140659 0)
(-0.0547641 0.282146 0)
(-0.0827851 0.32472 0)
(-0.0880784 0.312475 0)
(-0.0751054 0.274458 0)
(-0.0525869 0.226772 0)
(-0.0274534 0.17729 0)
(-0.00450872 0.129137 0)
(0.0131052 0.0829138 0)
(0.0234466 0.0379473 0)
(0.0254052 -0.00707379 0)
(0.0185138 -0.0537595 0)
(0.00298561 -0.103753 0)
(-0.0199919 -0.158322 0)
(-0.0476818 -0.217504 0)
(-0.0749817 -0.278363 0)
(-0.0935447 -0.331793 0)
(-0.0920626 -0.357684 0)
(-0.0632801 -0.319295 0)
(-0.0206335 -0.161974 0)
(-0.0254497 0.181711 0)
(-0.0657742 0.317772 0)
(-0.0733321 0.331363 0)
(-0.0480753 0.295402 0)
(-0.00557557 0.244213 0)
(0.0412222 0.192382 0)
(0.0846576 0.145048 0)
(0.120542 0.102973 0)
(0.146708 0.0651386 0)
(0.162053 0.0298917 0)
(0.165948 -0.00467179 0)
(0.157942 -0.0406291 0)
(0.137737 -0.0802476 0)
(0.105445 -0.125919 0)
(0.0622658 -0.179728 0)
(0.0118085 -0.242022 0)
(-0.0378281 -0.307879 0)
(-0.0716784 -0.360144 0)
(-0.0700552 -0.356609 0)
(-0.0279122 -0.208375 0)
(-0.029649 0.239176 0)
(-0.0608411 0.335768 0)
(-0.0219418 0.300503 0)
(0.050543 0.240128 0)
(0.127574 0.18295 0)
(0.19701 0.13539 0)
(0.25434 0.0973998 0)
(0.298255 0.0668517 0)
(0.328829 0.0413557 0)
(0.346472 0.0187787 0)
(0.351381 -0.0027943 0)
(0.343307 -0.0252655 0)
(0.321473 -0.0507883 0)
(0.284646 -0.0820488 0)
(0.231575 -0.122447 0)
(0.162183 -0.17567 0)
(0.0799019 -0.243432 0)
(-0.00318917 -0.319137 0)
(-0.0546693 -0.368613 0)
(-0.0284593 -0.267618 0)
(0.00808308 0.281861 0)
(0.0197831 0.294972 0)
(0.139066 0.210973 0)
(0.26446 0.143477 0)
(0.364368 0.0971863 0)
(0.440365 0.0657778 0)
(0.496745 0.0442378 0)
(0.536876 0.0288862 0)
(0.563449 0.017199 0)
(0.578308 0.00748482 0)
(0.582383 -0.00149419 0)
(0.575698 -0.0108454 0)
(0.557311 -0.0218473 0)
(0.525137 -0.0363352 0)
(0.475778 -0.0572598 0)
(0.404538 -0.0893843 0)
(0.305177 -0.139741 0)
(0.173417 -0.216386 0)
(0.0411721 -0.311655 0)
(0.0184302 -0.299995 0)
(0.299604 0.146091 0)
(0.396272 0.127503 0)
(0.55742 0.0760895 0)
(0.674487 0.0437233 0)
(0.743889 0.0255721 0)
(0.787154 0.0152423 0)
(0.815486 0.00921239 0)
(0.833956 0.00550945 0)
(0.845386 0.0030272 0)
(0.851372 0.00114935 0)
(0.852667 -0.000499403 0)
(0.849383 -0.0022151 0)
(0.841 -0.0043386 0)
(0.826141 -0.00742412 0)
(0.802079 -0.0125323 0)
(0.763621 -0.0217729 0)
(0.699108 -0.039283 0)
(0.583952 -0.0726601 0)
(0.415827 -0.127868 0)
(0.308819 -0.149468 0)
)
;
boundaryField
{
movingWall
{
type fixedValue;
value uniform (1 0 0);
}
fixedWalls
{
type noSlip;
}
frontAndBack
{
type empty;
}
}
// ************************************************************************* //
| [
"aashay225@gmail.com"
] | aashay225@gmail.com | |
739985fd73492e1e41d84bf812912e319be54531 | 39db050d5ad3cbcbbfa0f762a766e2602e46ffc9 | /1326/d1/d1.cpp | 072e8443b6dc71bfd6d47db1d6fddffe5254bf63 | [] | no_license | manncodes/codeforces | 0e5ac1701d3b10dc662d7c46774991aff1b5ebed | cd04c219b5b818f74daf0bf73f5d406097ee99ff | refs/heads/main | 2023-07-01T04:04:30.259778 | 2021-08-03T16:22:31 | 2021-08-03T16:22:31 | 390,113,487 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,751 | cpp |
#include <bits/stdc++.h>
using namespace std;
template <typename T>
vector<int> manacher(int n, const T &s) {
if (n == 0) {
return vector<int>();
}
vector<int> res(2 * n - 1, 0);
int l = -1, r = -1;
for (int z = 0; z < 2 * n - 1; z++) {
int i = (z + 1) >> 1;
int j = z >> 1;
int p = (i >= r ? 0 : min(r - i, res[2 * (l + r) - z]));
while (j + p + 1 < n && i - p - 1 >= 0) {
if (!(s[j + p + 1] == s[i - p - 1])) {
break;
}
p++;
}
if (j + p > r) {
l = i - p;
r = j + p;
}
res[z] = p;
}
return res;
}
template <typename T>
vector<int> manacher(const T &s) {
return manacher((int) s.size(), s);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int tt;
cin >> tt;
while (tt--) {
string s;
cin >> s;
int n = (int) s.size();
vector<int> res = manacher(s);
int match = 0;
while (2 * match + 2 <= n && s[match] == s[n - 1 - match]) {
match += 1;
}
int ans = 0;
int afrom = 0;
for (int z = 0; z <= 2 * n - 2; z++) {
int i = (z + 1) >> 1;
int j = z >> 1;
if (i > j && res[z] == 0) {
continue;
}
int from = i - res[z];
int to = j + res[z];
if (from < match) {
int shift = match - from;
from += shift;
to -= shift;
}
if (to >= n - match) {
int shift = to - (n - match) + 1;
from += shift;
to -= shift;
}
if (from != match && to != n - match - 1) {
continue;
}
if (to - from + 1 > ans) {
ans = to - from + 1;
afrom = from;
}
}
cout << (s.substr(0, match) + s.substr(afrom, ans) + s.substr(n - match, match)) << '\n';
}
return 0;
}
| [
"manncodes@gmail.com"
] | manncodes@gmail.com |
355a79146c536899e3ca5e0e81cbd616a8a0ab99 | 129cdb6bce9b9dbb8e3b6447cd55dbe332d6b5bd | /ClassDeclarationList.h | bd392949f13f65c7bdd6c06a748cd6511631656a | [] | no_license | tclin914/mj2MIPS | b072fde978996b2496abbaa8ccf64ee05929fcd4 | e436f8c7b85dc1696911a657b99e27e0a6b9261e | refs/heads/master | 2020-05-17T22:24:36.175466 | 2015-05-11T03:24:18 | 2015-05-11T03:24:18 | 28,191,309 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 351 | h | #pragma once
#include "BinaryNode.h"
#include <string>
using namespace std;
class ClassDeclarationList : public BinaryNode
{
public:
ClassDeclarationList(Node*, Node*); // (ClassDeclaration, ClassDeclarationList)
void SetSymbleTable(SymbolTable*, SymbolTable*);
void Accept(Visitor*);
bool SemanticCheck();
bool Initialize();
};
| [
"tclin914@gmail.com"
] | tclin914@gmail.com |
3ef89c0ed51b416303c53fe16ecac2612f5c7403 | 2468bde50fd4df491c800631ff9eaedc856041eb | /src/ui_confirm.h | 941848d6a3338584ad452b12f3b437f14c54b0d8 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | dreadlokeur/zec-qt-wallet | c129fa0855c6c8a9e0a46f8f3219c3fe776b2cff | a4e1de1b8b41872d53fb7bf23f2a2aebf4410253 | refs/heads/master | 2020-04-03T07:19:30.512292 | 2018-10-28T18:23:52 | 2018-10-28T18:23:52 | 155,099,477 | 0 | 0 | null | 2018-10-28T17:58:16 | 2018-10-28T17:58:16 | null | UTF-8 | C++ | false | false | 7,847 | h | /********************************************************************************
** Form generated from reading UI file 'confirm.ui'
**
** Created by: Qt User Interface Compiler version 5.11.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_CONFIRM_H
#define UI_CONFIRM_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QDialog>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QFrame>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QGroupBox>
#include <QtWidgets/QLabel>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QVBoxLayout>
QT_BEGIN_NAMESPACE
class Ui_confirm
{
public:
QVBoxLayout *verticalLayout;
QGroupBox *groupBox;
QVBoxLayout *verticalLayout_2;
QLabel *sendFrom;
QGroupBox *sendToAddrs;
QGridLayout *gridLayout;
QLabel *devFee;
QLabel *Amt1;
QLabel *labelDevFee;
QLabel *minerFee;
QLabel *Addr1;
QLabel *labelMinerFee;
QLabel *AmtUSD1;
QLabel *Memo1;
QLabel *minerFeeUSD;
QLabel *devFeeUSD;
QSpacerItem *verticalSpacer;
QFrame *line;
QDialogButtonBox *buttonBox;
void setupUi(QDialog *confirm)
{
if (confirm->objectName().isEmpty())
confirm->setObjectName(QStringLiteral("confirm"));
confirm->resize(429, 371);
verticalLayout = new QVBoxLayout(confirm);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
groupBox = new QGroupBox(confirm);
groupBox->setObjectName(QStringLiteral("groupBox"));
verticalLayout_2 = new QVBoxLayout(groupBox);
verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2"));
sendFrom = new QLabel(groupBox);
sendFrom->setObjectName(QStringLiteral("sendFrom"));
sendFrom->setWordWrap(true);
verticalLayout_2->addWidget(sendFrom);
verticalLayout->addWidget(groupBox);
sendToAddrs = new QGroupBox(confirm);
sendToAddrs->setObjectName(QStringLiteral("sendToAddrs"));
gridLayout = new QGridLayout(sendToAddrs);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
devFee = new QLabel(sendToAddrs);
devFee->setObjectName(QStringLiteral("devFee"));
QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(devFee->sizePolicy().hasHeightForWidth());
devFee->setSizePolicy(sizePolicy);
devFee->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
gridLayout->addWidget(devFee, 3, 1, 1, 1);
Amt1 = new QLabel(sendToAddrs);
Amt1->setObjectName(QStringLiteral("Amt1"));
sizePolicy.setHeightForWidth(Amt1->sizePolicy().hasHeightForWidth());
Amt1->setSizePolicy(sizePolicy);
Amt1->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
gridLayout->addWidget(Amt1, 0, 1, 1, 1);
labelDevFee = new QLabel(sendToAddrs);
labelDevFee->setObjectName(QStringLiteral("labelDevFee"));
gridLayout->addWidget(labelDevFee, 3, 0, 1, 1);
minerFee = new QLabel(sendToAddrs);
minerFee->setObjectName(QStringLiteral("minerFee"));
sizePolicy.setHeightForWidth(minerFee->sizePolicy().hasHeightForWidth());
minerFee->setSizePolicy(sizePolicy);
minerFee->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
gridLayout->addWidget(minerFee, 2, 1, 1, 1);
Addr1 = new QLabel(sendToAddrs);
Addr1->setObjectName(QStringLiteral("Addr1"));
Addr1->setWordWrap(true);
gridLayout->addWidget(Addr1, 0, 0, 1, 1);
labelMinerFee = new QLabel(sendToAddrs);
labelMinerFee->setObjectName(QStringLiteral("labelMinerFee"));
gridLayout->addWidget(labelMinerFee, 2, 0, 1, 1);
AmtUSD1 = new QLabel(sendToAddrs);
AmtUSD1->setObjectName(QStringLiteral("AmtUSD1"));
QSizePolicy sizePolicy1(QSizePolicy::Minimum, QSizePolicy::Preferred);
sizePolicy1.setHorizontalStretch(0);
sizePolicy1.setVerticalStretch(0);
sizePolicy1.setHeightForWidth(AmtUSD1->sizePolicy().hasHeightForWidth());
AmtUSD1->setSizePolicy(sizePolicy1);
AmtUSD1->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
gridLayout->addWidget(AmtUSD1, 0, 2, 1, 1);
Memo1 = new QLabel(sendToAddrs);
Memo1->setObjectName(QStringLiteral("Memo1"));
Memo1->setWordWrap(true);
gridLayout->addWidget(Memo1, 1, 0, 1, 3);
minerFeeUSD = new QLabel(sendToAddrs);
minerFeeUSD->setObjectName(QStringLiteral("minerFeeUSD"));
sizePolicy1.setHeightForWidth(minerFeeUSD->sizePolicy().hasHeightForWidth());
minerFeeUSD->setSizePolicy(sizePolicy1);
minerFeeUSD->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
gridLayout->addWidget(minerFeeUSD, 2, 2, 1, 1);
devFeeUSD = new QLabel(sendToAddrs);
devFeeUSD->setObjectName(QStringLiteral("devFeeUSD"));
sizePolicy1.setHeightForWidth(devFeeUSD->sizePolicy().hasHeightForWidth());
devFeeUSD->setSizePolicy(sizePolicy1);
devFeeUSD->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
gridLayout->addWidget(devFeeUSD, 3, 2, 1, 1);
verticalLayout->addWidget(sendToAddrs);
verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout->addItem(verticalSpacer);
line = new QFrame(confirm);
line->setObjectName(QStringLiteral("line"));
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
verticalLayout->addWidget(line);
buttonBox = new QDialogButtonBox(confirm);
buttonBox->setObjectName(QStringLiteral("buttonBox"));
buttonBox->setOrientation(Qt::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
verticalLayout->addWidget(buttonBox);
retranslateUi(confirm);
QObject::connect(buttonBox, SIGNAL(accepted()), confirm, SLOT(accept()));
QObject::connect(buttonBox, SIGNAL(rejected()), confirm, SLOT(reject()));
QMetaObject::connectSlotsByName(confirm);
} // setupUi
void retranslateUi(QDialog *confirm)
{
confirm->setWindowTitle(QApplication::translate("confirm", "Confirm Transaction", nullptr));
groupBox->setTitle(QApplication::translate("confirm", "From", nullptr));
sendFrom->setText(QString());
sendToAddrs->setTitle(QApplication::translate("confirm", "To", nullptr));
devFee->setText(QApplication::translate("confirm", "Dev Fee Amount", nullptr));
Amt1->setText(QApplication::translate("confirm", "TextLabel", nullptr));
labelDevFee->setText(QApplication::translate("confirm", "Dev Textlabel", nullptr));
minerFee->setText(QApplication::translate("confirm", "Miner Amount", nullptr));
Addr1->setText(QApplication::translate("confirm", "TextLabel", nullptr));
labelMinerFee->setText(QApplication::translate("confirm", "Miner Textlabel", nullptr));
AmtUSD1->setText(QApplication::translate("confirm", "TextLabel", nullptr));
Memo1->setText(QApplication::translate("confirm", "TextLabel", nullptr));
minerFeeUSD->setText(QApplication::translate("confirm", "TextLabel", nullptr));
devFeeUSD->setText(QApplication::translate("confirm", "TextLabel", nullptr));
} // retranslateUi
};
namespace Ui {
class confirm: public Ui_confirm {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_CONFIRM_H
| [
"adityapk@gmail.com"
] | adityapk@gmail.com |
756653e4bef6d2dfa7b20391fd13af4c1ed72d6f | 6bc8e22c2670a3e2d3dd2179ad6394b27277a6d4 | /charging.cpp | 3b9ecbef29c22e44697883f2c19ce33c11aa7ac8 | [] | no_license | ssjoshi10/NetworkOperatorTool | eb837e0c0a52bbce7068570df7a38547e687bd93 | 0114a15445336591e9a416a6f15c9d5cbeb2fe0a | refs/heads/master | 2022-09-18T06:48:50.587047 | 2020-06-03T09:21:21 | 2020-06-03T09:21:21 | 269,040,194 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,064 | cpp | /***********************************************************************************************
Name of the module : charging.cpp
Date of creation : 21/5/2020
Author of module : Shubhangi Joshi
Description of module:
This module contains all the function definitions of the class charging
Different functions supported in the module:
void rchg_cu(long long int msin, struct plan_info p, string str); Function to store the new subscriber info to database
void get_bal_cu(long long int msin); Function for printing balance for prepaid subscribers
void gen_bill_cu(long long int msin); Function to generate postpaid bill into file
static charging *get_cu_obj(void); Function to create singleton object of charging class
Revision/Modification History:
Added charging.cpp Shubhangi Joshi 21/5/2020
Added function header Shubhangi Joshi 26/5/2020
************************************************************************************************/
#include"Tstel.h"
charging *charging::cu_obj;
/*****************************************************************************************************
Function Name: void get_cu_obj(void)
Description: This function is used to create the object for the class charging.
This is a static function which makes sure that only one object for the class charging is created.
This function returns the created object.
*****************************************************************************************************/
charging * charging::get_cu_obj(void)///static function
{
if(cu_obj == NULL)
{
cu_obj = new charging;
}
return cu_obj;
}
/*****************************************************************************************************
Function Name: void rchg_cu(ull msin, struct plan_info plan_details, string str,database *db_obj)
Description: The prepaid and postpaid components calls this function when the user requests for new
prepaid or postpaid connection. This function has the arguments msin, struct plan (which includes imei
number, plan amount and validity), string which identifies whether the msin is prepaid or postpaid and
database class object. This all the information is copied in the struct validity_info along with todays
date and will make a call to rchg_db() function using database class object to store these details to
database.
*****************************************************************************************************/
void charging::rchg_cu(ull msin, struct plan_info plan_details, string str,database *db_obj)
{
struct validity_info val_info = {0,0,0,0,0,0};
time_t now = time(0);
tm *ptr = localtime(&now);
val_info.imei = plan_details.imei;
val_info.amt = plan_details.amt;
val_info.no_of_days = plan_details.no_of_days;
val_info.date = ptr->tm_mday;
val_info.month = 1U + ptr->tm_mon;
val_info.yr = CAL_BASE + ptr->tm_year;
db_obj->rchg_db(msin,val_info,str); //calling databse function
}
/*****************************************************************************************************
Function Name: int calculate_validity(date last_date, date curr_date)
Description: This function is used to calculate no. of days between two dates i.e between today's date
and plan activation date. Two structures dt1 & dt2 holding plan actiation date and today's date resp
are passed as arguments to this function. This function calculates the difference between two dates and
returns the integer difference value. From this function we get that for how many days the plan has
been active.
*****************************************************************************************************/
int charging::calculate_validity(date last_date, date curr_date)
{
long int n1 = (last_date.year)*YEAR + last_date.date;
for (int i = 0U; i < last_date.month - 1U; i++)
n1 += Mdays[i];
long int n2 = curr_date.year*YEAR + curr_date.date;
for (int i = 0U; i < curr_date.month - 1U; i++)
n2 += Mdays[i];
return (n2 - n1);
}
/*****************************************************************************************************
Function Name: void rchg_date(int *date, int *month, int *year, int days)
Description: This function is used to calculate next recharge date. Today's date in the form of date,
month and year values and no of days after which recharge is to be done. According to perticular date
month and year conditions next recharge date is calculated.
*****************************************************************************************************/
void charging::rchg_date(int *date, int *month, int *year, int days)
{
*date = *date + days;
while(*date > Mdays[*month - 1U])
{
*date = *date - Mdays[*month - 1U];
(*month)++;
if(*month > 12U)
{
*month = 1U;
(*year)++;
}
}
}
/*****************************************************************************************************
Function Name: void get_bal_cu(ull msin, database *db_obj, string type_of_sim)
Description: A call to this function has been made by the prepaid component when the existing prepaid
subscriber wants to check the balance and validity. Prepaid component will pass the msin and database
class object as arguments. Current date is stored in date type curr_date variable. A call to
get_validity_db function is made to get the plan activation date. Calculate_validity function is called
to get no of days between two dates. Next recharge date is calculated using rchg_date function.
Then all the details for the requested subscriber are printed on stdout.
*****************************************************************************************************/
void charging::get_bal_cu(ull msin, database *db_obj, string type_of_sim)
{
struct date lst_rchg_dt = {0,0,0}, curr_dt = {0,0,0}, nxt_rchg_dt = {0,0,0};
time_t now=time(0);
tm *ptr = localtime(&now);
curr_dt.date = ptr->tm_mday;
curr_dt.month = 1U + ptr->tm_mon;
curr_dt.year = CAL_BASE + ptr->tm_year;
//Getting data from database//
struct validity_info *sub_info = db_obj->get_validity_db(msin, type_of_sim);
if(sub_info == NULL)
{
cout<<"MSIN is Invalid \nCan't display balance"<<endl;
}
else
{
lst_rchg_dt.date = sub_info->date;
lst_rchg_dt.month = sub_info->month;
lst_rchg_dt.year = sub_info->yr;
//getting validity//
int diff = calculate_validity(lst_rchg_dt,curr_dt);
//getting next recharge date//
nxt_rchg_dt.date = curr_dt.date;
nxt_rchg_dt.month = curr_dt.month;
nxt_rchg_dt.year = curr_dt.year;
rchg_date(&nxt_rchg_dt.date, &nxt_rchg_dt.month, &nxt_rchg_dt.year, (sub_info->no_of_days)-diff);
//Printig the details on stdout//
cout<<"MSIN: "<<msin<<endl;
cout<<"IMEI: "<<sub_info->imei<<endl;
cout<<"TMSI: "<<sub_info->tmsi<<endl;
cout<<"Available balance is: "<<sub_info->amt;
cout<<"\nvalidity is: "<<sub_info->no_of_days-diff<<" days"<<endl;
cout<<"Next recharge date is: "<<nxt_rchg_dt.date<<"/"<<nxt_rchg_dt.month<<"/"<<nxt_rchg_dt.year<<endl;
}
}
/*****************************************************************************************************
Function Name: void generate_bill(ull msin,validity_info val_info, string type_of_sim)
Description: This function creates a file called bill.csv and generates a postpaid bill into it. This
bill will have the details as: msin, imei no, bill amount for perticular msin and plan activation date.
*****************************************************************************************************/
int charging :: generate_bill(ull msin, validity_info val_info, string type_of_sim)
{
struct date from_date = {0,0,0}, to_date = {0,0,0}, curr_dt = {0,0,0};
time_t now=time(0);
tm *ptr = localtime(&now);
curr_dt.date = ptr->tm_mday;
curr_dt.month = 1U + ptr->tm_mon;
curr_dt.year = CAL_BASE + ptr->tm_year;
if(val_info.month == curr_dt.month && val_info.yr == curr_dt.year)
{
return 0;
}
//Calculating from billing date
from_date.date = 1U;
if(val_info.month == 1U)
{
from_date.month = 12U;
from_date.year = curr_dt.year - 1U;
}
else
{
from_date.month = curr_dt.month - 1U;
from_date.year = curr_dt.year;
}
//Calculating to billing date
if(Mdays[from_date.month - 1U] == 31U)
{
to_date.date = 31U;
}
else if(Mdays[from_date.month - 1U] == 30U)
{
to_date.date = 30U;
}
else
{
to_date.date = 28U;
}
to_date.month = from_date.month;
to_date.year = from_date.year;
//Opening file
ofstream myfile;
stringstream sstr;
sstr<<msin;
string filename=sstr.str();
filename = filename + "_bill.csv";
myfile.open(filename); //creating file//
if(!myfile)
{
cout<<"\nError in Opening file";
return 0;
}
//Storing the data into file//
myfile << type_of_sim;
myfile << " Bill\n";
myfile << "MSIN,"<<msin << "\n";
myfile << "IMEI No.,"<<val_info.imei <<"\n";
myfile << "TMSI No,"<<val_info.tmsi <<"\n";
myfile << "Amount,"<<val_info.amt <<" Rs\n";
myfile << "Date,"<<from_date.date<<"/"<<from_date.month<<"/"<<from_date.year<<" to ";
myfile << to_date.date<<"/"<<to_date.month<<"/"<<to_date.year;
myfile.close();
return 1;
}
/*****************************************************************************************************
Function Name: void gen_bill_cu(ull msin, database *db_obj, string type_of_sim)
Description: A call to this function has been made by the postpaid component when the existing postpaid
subscriber wants to get the bill. Postpaid component will pass the msin and database class object as
arguments. A call to get_bill_db function is made to get the plan activation date. All the data from
databse is copied into struct validity_info. A call is made to the function generate bill to generate
the bill for requested postpaid subscriber. Also the bill amount for the requested subscriber is printed
on stdout.
*****************************************************************************************************/
void charging::gen_bill_cu(ull msin, database *db_obj, string type_of_sim)
{
//Getting data from database//
struct validity_info *sub_info = db_obj-> get_bill_db(msin, type_of_sim);
if(sub_info == NULL)
{
cout<<"MSIN is Invalid \nCan't generate bill"<<endl;
}
else
{
struct validity_info val_info = {0,0,0,0,0,0};
//Storing the data//
val_info.amt = sub_info->amt;
val_info.date = sub_info->date;
val_info.imei = sub_info->imei;
val_info.month = sub_info->month;
val_info.no_of_days = sub_info->no_of_days;
val_info.yr = sub_info->yr;
val_info.tmsi=sub_info->tmsi;
//Printing the data on stdout//
cout<<"MSIN: "<<msin<<endl;
cout<<"Total bill amount for last month is: "<<sub_info->amt<<endl;
//Generating bill//
if(generate_bill(msin,val_info,type_of_sim))
{
cout<<"\nBill generated\n";
}
else
{
cout<<"\nBill not generated\n";
}
}
}
| [
"shubhangijoshi42@gmail.com"
] | shubhangijoshi42@gmail.com |
5aaa4baab4a16c7c2d0eadb145452fb15330d7d6 | aad993fdac039d38bb9b060f55f08757204b35b4 | /geometry/proximity/test/surface_mesh_test.cc | 96c4d71ab6f2469ab8d5e36baf60e181a977a352 | [
"BSD-3-Clause"
] | permissive | sprax/drake | ede3fd93416f5bdcbce8a2bb89ce3a73b05ea47d | d15d147516001dabd6914fcd5ba1dbd27483a957 | refs/heads/master | 2020-06-13T17:04:09.463120 | 2019-07-01T16:54:22 | 2019-07-01T16:54:22 | 194,721,118 | 0 | 0 | NOASSERTION | 2019-07-01T18:08:24 | 2019-07-01T18:08:24 | null | UTF-8 | C++ | false | false | 4,111 | cc | #include "drake/geometry/proximity/surface_mesh.h"
#include <memory>
#include <utility>
#include <gtest/gtest.h>
#include "drake/common/autodiff.h"
#include "drake/common/eigen_types.h"
namespace drake {
namespace geometry {
namespace {
// Used for testing instantiation of SurfaceMesh and inspecting its components.
template <typename T>
std::unique_ptr<SurfaceMesh<T>> GenerateTwoTriangleMesh() {
// The surface mesh will consist of four vertices and two faces and will
// be constructed such that area and geometric centroid are straightforward
// to check.
// Create the vertices.
std::vector<SurfaceVertex<T>> vertices;
vertices.emplace_back(Vector3<T>(0.5, 0.5, -0.5));
vertices.emplace_back(Vector3<T>(-0.5, 0.5, -0.5));
vertices.emplace_back(Vector3<T>(-0.5, -0.5, -0.5));
vertices.emplace_back(Vector3<T>(1.0, -1.0, -0.5));
// Create the two triangles. Note that SurfaceMesh does not specify (or use) a
// particular winding.
std::vector<SurfaceFace> faces;
faces.emplace_back(
SurfaceVertexIndex(0), SurfaceVertexIndex(1), SurfaceVertexIndex(2));
faces.emplace_back(
SurfaceVertexIndex(2), SurfaceVertexIndex(3), SurfaceVertexIndex(0));
return std::make_unique<SurfaceMesh<T>>(
std::move(faces), std::move(vertices));
}
// Generates an empty mesh.
std::unique_ptr<SurfaceMesh<double>> GenerateEmptyMesh() {
std::vector<SurfaceVertex<double>> vertices;
std::vector<SurfaceFace> faces;
return std::make_unique<SurfaceMesh<double>>(
std::move(faces), std::move(vertices));
}
// Generates a zero-area mesh.
std::unique_ptr<SurfaceMesh<double>> GenerateZeroAreaMesh() {
// The surface mesh will consist of four vertices and two faces.
// Create the vertices.
std::vector<SurfaceVertex<double>> vertices;
for (int i = 0; i < 4; ++i)
vertices.emplace_back(Vector3<double>::Zero());
// Create the two triangles.
std::vector<SurfaceFace> faces;
faces.emplace_back(
SurfaceVertexIndex(0), SurfaceVertexIndex(1), SurfaceVertexIndex(2));
faces.emplace_back(
SurfaceVertexIndex(2), SurfaceVertexIndex(3), SurfaceVertexIndex(0));
return std::make_unique<SurfaceMesh<double>>(
std::move(faces), std::move(vertices));
}
// Test instantiation of SurfaceMesh using `double` as the underlying scalar
// type.
GTEST_TEST(SurfaceMeshTest, GenerateTwoTriangleMeshDouble) {
auto surface_mesh = GenerateTwoTriangleMesh<double>();
EXPECT_EQ(surface_mesh->num_faces(), 2);
}
// Smoke tests using `AutoDiffXd` as the underlying scalar type. The purpose
// of this test is simply to check that it compiles. There is no test of
// differentiation.
GTEST_TEST(SurfaceMeshTest, GenerateTwoTriangleMeshAutoDiffXd) {
auto surface_mesh = GenerateTwoTriangleMesh<AutoDiffXd>();
EXPECT_EQ(surface_mesh->num_faces(), 2);
}
// Checks the area calculations.
GTEST_TEST(SurfaceMeshTest, TestArea) {
const double tol = 10 * std::numeric_limits<double>::epsilon();
auto surface_mesh = GenerateTwoTriangleMesh<double>();
EXPECT_NEAR(surface_mesh->area(SurfaceFaceIndex(0)), 0.5, tol);
EXPECT_NEAR(surface_mesh->area(SurfaceFaceIndex(1)), 1.0, tol);
EXPECT_NEAR(surface_mesh->total_area(), 1.5, tol);
// Verify that the empty mesh and the zero area mesh both give zero area.
EXPECT_NEAR(GenerateEmptyMesh()->total_area(), 0.0, tol);
EXPECT_NEAR(GenerateZeroAreaMesh()->total_area(), 0.0, tol);
}
// Checks the centroid calculations.
GTEST_TEST(SurfaceMeshTest, TestCentroid) {
const double tol = 10 * std::numeric_limits<double>::epsilon();
auto surface_mesh = GenerateTwoTriangleMesh<double>();
const Vector3<double> centroid = surface_mesh->centroid();
EXPECT_NEAR(centroid[0], 1.0/6, tol);
EXPECT_NEAR(centroid[1], -1.0/6, tol);
EXPECT_NEAR(centroid[2], -0.5, tol);
// The documentation for the centroid method specifies particular behavior
// when the total area is zero. Test that.
EXPECT_NEAR(GenerateEmptyMesh()->centroid().norm(), 0.0, tol);
EXPECT_NEAR(GenerateZeroAreaMesh()->centroid().norm(), 0.0, tol);
}
} // namespace
} // namespace geometry
} // namespace drake
| [
"edrumwri@hotmail.com"
] | edrumwri@hotmail.com |
0e4555ffa58d9f2b29a51bf137f674458a681940 | 4c9d095014f46ff64cf3ce25a973c61726e15c9d | /devdc189.cpp | a47f105200a881aec03a24dec62783d9b89141da | [
"BSD-2-Clause"
] | permissive | vidit1999/coding_problems | 2955e9af5c27873184305f8af1fb06b3e657e5b6 | b6c9fa7fda37d9424cd11bcd54b385fd8cf1ee0a | refs/heads/master | 2021-07-06T00:48:43.015666 | 2021-05-20T20:43:37 | 2021-05-20T20:43:37 | 239,530,895 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,041 | cpp | #include <bits/stdc++.h>
using namespace std;
/*
Write a function that takes a random number as input and converts it
into an array with the digits of that number appearing in reverse order.
Example
convertNtA(348597) => [7,9,5,8,4,3]
Tests
convertNtA(6581554)
convertNtA(123456)
convertNtA(987123)
*/
vector<int> convertNtA(long number){
vector<int> numDigits;
if(number == 0) // if number is zero then return vector with only 0
return vector<int>({0});
while(number > 0){
numDigits.push_back(number%10);
number /= 10;
}
return numDigits;
}
// function for testing purpose
void testFunction(vector<int> numDigits){
for(int i : numDigits)
cout << i << " ";
cout << "\n";
}
// main function
int main(){
testFunction(convertNtA(348597));
testFunction(convertNtA(6581554));
testFunction(convertNtA(123456));
testFunction(convertNtA(987123));
testFunction(convertNtA(0));
testFunction(convertNtA(1));
testFunction(convertNtA(10));
return 0;
} | [
"sarkarvidit71@gmail.com"
] | sarkarvidit71@gmail.com |
1150a4bec5fe9760071c1d46e37c9b6984453329 | be3d301bf8c502bb94149c76cc09f053c532d87a | /src/GafferSceneBindings/MixinBinding.cpp | 6821b8bbb057dcb70c4722fdf874e6d0bae92156 | [
"BSD-3-Clause"
] | permissive | ljkart/gaffer | 28be401d04e05a3c973ef42d29a571aba6407665 | d2ce0eb7134a33ceee375d0a3676129a9bdcfbc6 | refs/heads/master | 2021-01-18T08:30:19.763744 | 2014-08-10T13:48:10 | 2014-08-10T13:48:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,468 | cpp | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software 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 "boost/python.hpp"
#include "GafferBindings/DependencyNodeBinding.h"
#include "GafferScene/SceneContextVariables.h"
#include "GafferScene/SceneSwitch.h"
#include "GafferScene/SceneTimeWarp.h"
#include "GafferSceneBindings/MixinBinding.h"
using namespace GafferScene;
void GafferSceneBindings::bindMixin()
{
GafferBindings::DependencyNodeClass<SceneMixinBase>();
GafferBindings::DependencyNodeClass<SceneContextProcessor>();
GafferBindings::DependencyNodeClass<SceneTimeWarp>();
GafferBindings::DependencyNodeClass<SceneContextVariables>();
GafferBindings::DependencyNodeClass<SceneSwitch>();
}
| [
"thehaddonyoof@gmail.com"
] | thehaddonyoof@gmail.com |
ac6a2a26f1d021a211e5c874d5202c971edd24ea | 9d2a3e1bdf6a74875e28c74cc80d2a18a57a1314 | /src/lib/support/exe/ExeLib.cpp | 0cf128c65a94a728616f29891460dadcaa8127bb | [
"BSD-3-Clause"
] | permissive | eirTony/EIRC2 | 1a979539d2b29cfbb9a2bb1010fe1d39af36aae7 | f0f917d101e3ca24d04c456c31a5b16252feeb62 | refs/heads/master | 2021-01-21T04:40:52.106253 | 2016-04-11T02:21:24 | 2016-04-11T02:21:24 | 55,930,007 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 894 | cpp | /*! @file ExeLib.cpp EclipseIR ExeLib definitions
*/
#include "ExeLib.h"
#include "Version.h"
#include <CommonVersion.h>
#include <QtDebug>
ExeLib * gpExe = &(Exe::instance());
/*! @fn ExeLib::ExeLib(void)
*
* @brief ExeLib::ExeLib initializes the ExeLib class.
*/
ExeLib::ExeLib(void)
: ModuleInfo(MODULE_NAME)
{
setVersion();
}
#if 0
/*! @fn void executeUnitTest(void)
*
* @brief The executeUnitTest() function is global to ExeLib
*
* This global extern "C" function can be Exeolved and executed
* after being loaded via QLibrary.
*/
extern "C" EXESHARED_EXPORT void executeUnitTest(void)
{
Exe::instance()->executeUnitTest();
}
/*! @fn void ExeLib::executeUnitTest(void)
*
* @internal
*/
void ExeLib::executeUnitTest(void)
{
QUT_FUNCTION();
QUT_EXPECTEQ(VER_MAJOR, Exe::instance()->version().getMajor());
//QUT_INSTANCE(AnyOtherClasses);
}
#endif
| [
"tony.dyndez@gmail.com"
] | tony.dyndez@gmail.com |
2f40fefa28d46c9a82a8519e1308eaaedeccb664 | ad0078a5cf257929243d253f60a14e62922b7c66 | /src/include/fst/replace-util.h | ed83f539849e9747b6125f4acb3541521c3f9eb2 | [
"Apache-2.0"
] | permissive | watergear/openfst | 4c7b46d93dc643cf0c788d6e317fe56390cbb16a | e895302f40d6ff9b5d37452f628b67ffca47cbfc | refs/heads/master | 2021-06-25T09:45:35.042119 | 2020-12-16T09:08:49 | 2020-12-16T09:08:49 | 174,268,680 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,795 | h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Utility classes for the recursive replacement of FSTs (RTNs).
#ifndef FST_REPLACE_UTIL_H_
#define FST_REPLACE_UTIL_H_
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <fst/types.h>
#include <fst/log.h>
#include <fst/connect.h>
#include <fst/mutable-fst.h>
#include <fst/topsort.h>
#include <fst/vector-fst.h>
namespace fst {
// This specifies what labels to output on the call or return arc. Note that
// REPLACE_LABEL_INPUT and REPLACE_LABEL_OUTPUT will produce transducers when
// applied to acceptors.
enum ReplaceLabelType {
// Epsilon labels on both input and output.
REPLACE_LABEL_NEITHER = 1,
// Non-epsilon labels on input and epsilon on output.
REPLACE_LABEL_INPUT = 2,
// Epsilon on input and non-epsilon on output.
REPLACE_LABEL_OUTPUT = 3,
// Non-epsilon labels on both input and output.
REPLACE_LABEL_BOTH = 4
};
// By default ReplaceUtil will copy the input label of the replace arc.
// The call_label_type and return_label_type options specify how to manage
// the labels of the call arc and the return arc of the replace FST
struct ReplaceUtilOptions {
int64 root; // Root rule for expansion.
ReplaceLabelType call_label_type; // How to label call arc.
ReplaceLabelType return_label_type; // How to label return arc.
int64 return_label; // Label to put on return arc.
explicit ReplaceUtilOptions(
int64 root = kNoLabel,
ReplaceLabelType call_label_type = REPLACE_LABEL_INPUT,
ReplaceLabelType return_label_type = REPLACE_LABEL_NEITHER,
int64 return_label = 0)
: root(root),
call_label_type(call_label_type),
return_label_type(return_label_type),
return_label(return_label) {}
// For backwards compatibility.
ReplaceUtilOptions(int64 root, bool epsilon_replace_arc)
: ReplaceUtilOptions(root, epsilon_replace_arc ? REPLACE_LABEL_NEITHER
: REPLACE_LABEL_INPUT) {}
};
// Every non-terminal on a path appears as the first label on that path in every
// FST associated with a given SCC of the replace dependency graph. This would
// be true if the SCC were formed from left-linear grammar rules.
constexpr uint8 kReplaceSCCLeftLinear = 0x01;
// Every non-terminal on a path appears as the final label on that path in every
// FST associated with a given SCC of the replace dependency graph. This would
// be true if the SCC were formed from right-linear grammar rules.
constexpr uint8 kReplaceSCCRightLinear = 0x02;
// The SCC in the replace dependency graph has more than one state or a
// self-loop.
constexpr uint8 kReplaceSCCNonTrivial = 0x04;
// Defined in replace.h.
template <class Arc>
void Replace(
const std::vector<std::pair<typename Arc::Label, const Fst<Arc> *>> &,
MutableFst<Arc> *, const ReplaceUtilOptions &);
// Utility class for the recursive replacement of FSTs (RTNs). The user provides
// a set of label/FST pairs at construction. These are used by methods for
// testing cyclic dependencies and connectedness and doing RTN connection and
// specific FST replacement by label or for various optimization properties. The
// modified results can be obtained with the GetFstPairs() or
// GetMutableFstPairs() methods.
template <class Arc>
class ReplaceUtil {
public:
using Label = typename Arc::Label;
using StateId = typename Arc::StateId;
using Weight = typename Arc::Weight;
using FstPair = std::pair<Label, const Fst<Arc> *>;
using MutableFstPair = std::pair<Label, MutableFst<Arc> *>;
using NonTerminalHash = std::unordered_map<Label, Label>;
// Constructs from mutable FSTs; FST ownership is given to ReplaceUtil.
ReplaceUtil(const std::vector<MutableFstPair> &fst_pairs,
const ReplaceUtilOptions &opts);
// Constructs from FSTs; FST ownership is retained by caller.
ReplaceUtil(const std::vector<FstPair> &fst_pairs,
const ReplaceUtilOptions &opts);
// Constructs from ReplaceFst internals; FST ownership is retained by caller.
ReplaceUtil(const std::vector<std::unique_ptr<const Fst<Arc>>> &fst_array,
const NonTerminalHash &nonterminal_hash,
const ReplaceUtilOptions &opts);
~ReplaceUtil() {
for (Label i = 0; i < fst_array_.size(); ++i) delete fst_array_[i];
}
// True if the non-terminal dependencies are cyclic. Cyclic dependencies will
// result in an unexpandable FST.
bool CyclicDependencies() const {
GetDependencies(false);
return depprops_ & kCyclic;
}
// Returns the strongly-connected component ID in the dependency graph of the
// replace FSTS.
StateId SCC(Label label) const {
GetDependencies(false);
const auto it = nonterminal_hash_.find(label);
if (it == nonterminal_hash_.end()) return kNoStateId;
return depscc_[it->second];
}
// Returns properties for the strongly-connected component in the dependency
// graph of the replace FSTs. If the SCC is kReplaceSCCLeftLinear or
// kReplaceSCCRightLinear, that SCC can be represented as finite-state despite
// any cyclic dependencies, but not by the usual replacement operation (see
// fst/extensions/pdt/replace.h).
uint8 SCCProperties(StateId scc_id) {
GetSCCProperties();
return depsccprops_[scc_id];
}
// Returns true if no useless FSTs, states or transitions are present in the
// RTN.
bool Connected() const {
GetDependencies(false);
uint64 props = kAccessible | kCoAccessible;
for (Label i = 0; i < fst_array_.size(); ++i) {
if (!fst_array_[i]) continue;
if (fst_array_[i]->Properties(props, true) != props || !depaccess_[i]) {
return false;
}
}
return true;
}
// Removes useless FSTs, states and transitions from the RTN.
void Connect();
// Replaces FSTs specified by labels, unless there are cyclic dependencies.
void ReplaceLabels(const std::vector<Label> &labels);
// Replaces FSTs that have at most nstates states, narcs arcs and nnonterm
// non-terminals (updating in reverse dependency order), unless there are
// cyclic dependencies.
void ReplaceBySize(size_t nstates, size_t narcs, size_t nnonterms);
// Replaces singleton FSTS, unless there are cyclic dependencies.
void ReplaceTrivial() { ReplaceBySize(2, 1, 1); }
// Replaces non-terminals that have at most ninstances instances (updating in
// dependency order), unless there are cyclic dependencies.
void ReplaceByInstances(size_t ninstances);
// Replaces non-terminals that have only one instance, unless there are cyclic
// dependencies.
void ReplaceUnique() { ReplaceByInstances(1); }
// Returns label/FST pairs, retaining FST ownership.
void GetFstPairs(std::vector<FstPair> *fst_pairs);
// Returns label/mutable FST pairs, giving FST ownership over to the caller.
void GetMutableFstPairs(std::vector<MutableFstPair> *mutable_fst_pairs);
private:
// FST statistics.
struct ReplaceStats {
StateId nstates; // Number of states.
StateId nfinal; // Number of final states.
size_t narcs; // Number of arcs.
Label nnonterms; // Number of non-terminals in FST.
size_t nref; // Number of non-terminal instances referring to this FST.
// Number of times that ith FST references this FST
std::map<Label, size_t> inref;
// Number of times that this FST references the ith FST
std::map<Label, size_t> outref;
ReplaceStats() : nstates(0), nfinal(0), narcs(0), nnonterms(0), nref(0) {}
};
// Checks that Mutable FSTs exists, creating them if necessary.
void CheckMutableFsts();
// Computes the dependency graph for the RTN, computing dependency statistics
// if stats is true.
void GetDependencies(bool stats) const;
void ClearDependencies() const {
depfst_.DeleteStates();
stats_.clear();
depprops_ = 0;
depsccprops_.clear();
have_stats_ = false;
}
// Gets topological order of dependencies, returning false with cyclic input.
bool GetTopOrder(const Fst<Arc> &fst, std::vector<Label> *toporder) const;
// Updates statistics to reflect the replacement of the jth FST.
void UpdateStats(Label j);
// Computes the properties for the strongly-connected component in the
// dependency graph of the replace FSTs.
void GetSCCProperties() const;
Label root_label_; // Root non-terminal.
Label root_fst_; // Root FST ID.
ReplaceLabelType call_label_type_; // See Replace().
ReplaceLabelType return_label_type_; // See Replace().
int64 return_label_; // See Replace().
std::vector<const Fst<Arc> *> fst_array_; // FST per ID.
std::vector<MutableFst<Arc> *> mutable_fst_array_; // Mutable FST per ID.
std::vector<Label> nonterminal_array_; // FST ID to non-terminal.
NonTerminalHash nonterminal_hash_; // Non-terminal to FST ID.
mutable VectorFst<Arc> depfst_; // FST ID dependencies.
mutable std::vector<StateId> depscc_; // FST SCC ID.
mutable std::vector<bool> depaccess_; // FST ID accessibility.
mutable uint64 depprops_; // Dependency FST props.
mutable bool have_stats_; // Have dependency statistics?
mutable std::vector<ReplaceStats> stats_; // Per-FST statistics.
mutable std::vector<uint8> depsccprops_; // SCC properties.
ReplaceUtil(const ReplaceUtil &) = delete;
ReplaceUtil &operator=(const ReplaceUtil &) = delete;
};
template <class Arc>
ReplaceUtil<Arc>::ReplaceUtil(const std::vector<MutableFstPair> &fst_pairs,
const ReplaceUtilOptions &opts)
: root_label_(opts.root),
call_label_type_(opts.call_label_type),
return_label_type_(opts.return_label_type),
return_label_(opts.return_label),
depprops_(0),
have_stats_(false) {
fst_array_.push_back(nullptr);
mutable_fst_array_.push_back(nullptr);
nonterminal_array_.push_back(kNoLabel);
for (const auto &fst_pair : fst_pairs) {
const auto label = fst_pair.first;
auto *fst = fst_pair.second;
nonterminal_hash_[label] = fst_array_.size();
nonterminal_array_.push_back(label);
fst_array_.push_back(fst);
mutable_fst_array_.push_back(fst);
}
root_fst_ = nonterminal_hash_[root_label_];
if (!root_fst_) {
FSTERROR() << "ReplaceUtil: No root FST for label: " << root_label_;
}
}
template <class Arc>
ReplaceUtil<Arc>::ReplaceUtil(const std::vector<FstPair> &fst_pairs,
const ReplaceUtilOptions &opts)
: root_label_(opts.root),
call_label_type_(opts.call_label_type),
return_label_type_(opts.return_label_type),
return_label_(opts.return_label),
depprops_(0),
have_stats_(false) {
fst_array_.push_back(nullptr);
nonterminal_array_.push_back(kNoLabel);
for (const auto &fst_pair : fst_pairs) {
const auto label = fst_pair.first;
const auto *fst = fst_pair.second;
nonterminal_hash_[label] = fst_array_.size();
nonterminal_array_.push_back(label);
fst_array_.push_back(fst->Copy());
}
root_fst_ = nonterminal_hash_[root_label_];
if (!root_fst_) {
FSTERROR() << "ReplaceUtil: No root FST for label: " << root_label_;
}
}
template <class Arc>
ReplaceUtil<Arc>::ReplaceUtil(
const std::vector<std::unique_ptr<const Fst<Arc>>> &fst_array,
const NonTerminalHash &nonterminal_hash, const ReplaceUtilOptions &opts)
: root_fst_(opts.root),
call_label_type_(opts.call_label_type),
return_label_type_(opts.return_label_type),
return_label_(opts.return_label),
nonterminal_array_(fst_array.size()),
nonterminal_hash_(nonterminal_hash),
depprops_(0),
have_stats_(false) {
fst_array_.push_back(nullptr);
for (size_t i = 1; i < fst_array.size(); ++i) {
fst_array_.push_back(fst_array[i]->Copy());
}
for (auto it = nonterminal_hash.begin(); it != nonterminal_hash.end(); ++it) {
nonterminal_array_[it->second] = it->first;
}
root_label_ = nonterminal_array_[root_fst_];
}
template <class Arc>
void ReplaceUtil<Arc>::GetDependencies(bool stats) const {
if (depfst_.NumStates() > 0) {
if (stats && !have_stats_) {
ClearDependencies();
} else {
return;
}
}
have_stats_ = stats;
if (have_stats_) stats_.reserve(fst_array_.size());
for (Label ilabel = 0; ilabel < fst_array_.size(); ++ilabel) {
depfst_.AddState();
depfst_.SetFinal(ilabel);
if (have_stats_) stats_.push_back(ReplaceStats());
}
depfst_.SetStart(root_fst_);
// An arc from each state (representing the FST) to the state representing the
// FST being replaced
for (Label ilabel = 0; ilabel < fst_array_.size(); ++ilabel) {
const auto *ifst = fst_array_[ilabel];
if (!ifst) continue;
for (StateIterator<Fst<Arc>> siter(*ifst); !siter.Done(); siter.Next()) {
const auto s = siter.Value();
if (have_stats_) {
++stats_[ilabel].nstates;
if (ifst->Final(s) != Weight::Zero()) ++stats_[ilabel].nfinal;
}
for (ArcIterator<Fst<Arc>> aiter(*ifst, s); !aiter.Done(); aiter.Next()) {
if (have_stats_) ++stats_[ilabel].narcs;
const auto &arc = aiter.Value();
auto it = nonterminal_hash_.find(arc.olabel);
if (it != nonterminal_hash_.end()) {
const auto nextstate = it->second;
depfst_.EmplaceArc(ilabel, arc.olabel, arc.olabel, nextstate);
if (have_stats_) {
++stats_[ilabel].nnonterms;
++stats_[nextstate].nref;
++stats_[nextstate].inref[ilabel];
++stats_[ilabel].outref[nextstate];
}
}
}
}
}
// Computes accessibility info.
SccVisitor<Arc> scc_visitor(&depscc_, &depaccess_, nullptr, &depprops_);
DfsVisit(depfst_, &scc_visitor);
}
template <class Arc>
void ReplaceUtil<Arc>::UpdateStats(Label j) {
if (!have_stats_) {
FSTERROR() << "ReplaceUtil::UpdateStats: Stats not available";
return;
}
if (j == root_fst_) return; // Can't replace root.
for (auto in = stats_[j].inref.begin(); in != stats_[j].inref.end(); ++in) {
const auto i = in->first;
const auto ni = in->second;
stats_[i].nstates += stats_[j].nstates * ni;
stats_[i].narcs += (stats_[j].narcs + 1) * ni;
stats_[i].nnonterms += (stats_[j].nnonterms - 1) * ni;
stats_[i].outref.erase(j);
for (auto out = stats_[j].outref.begin(); out != stats_[j].outref.end();
++out) {
const auto k = out->first;
const auto nk = out->second;
stats_[i].outref[k] += ni * nk;
}
}
for (auto out = stats_[j].outref.begin(); out != stats_[j].outref.end();
++out) {
const auto k = out->first;
const auto nk = out->second;
stats_[k].nref -= nk;
stats_[k].inref.erase(j);
for (auto in = stats_[j].inref.begin(); in != stats_[j].inref.end(); ++in) {
const auto i = in->first;
const auto ni = in->second;
stats_[k].inref[i] += ni * nk;
stats_[k].nref += ni * nk;
}
}
}
template <class Arc>
void ReplaceUtil<Arc>::CheckMutableFsts() {
if (mutable_fst_array_.empty()) {
for (Label i = 0; i < fst_array_.size(); ++i) {
if (!fst_array_[i]) {
mutable_fst_array_.push_back(nullptr);
} else {
mutable_fst_array_.push_back(new VectorFst<Arc>(*fst_array_[i]));
delete fst_array_[i];
fst_array_[i] = mutable_fst_array_[i];
}
}
}
}
template <class Arc>
void ReplaceUtil<Arc>::Connect() {
CheckMutableFsts();
static constexpr auto props = kAccessible | kCoAccessible;
for (auto *mutable_fst : mutable_fst_array_) {
if (!mutable_fst) continue;
if (mutable_fst->Properties(props, false) != props) {
fst::Connect(mutable_fst);
}
}
GetDependencies(false);
for (Label i = 0; i < mutable_fst_array_.size(); ++i) {
auto *fst = mutable_fst_array_[i];
if (fst && !depaccess_[i]) {
delete fst;
fst_array_[i] = nullptr;
mutable_fst_array_[i] = nullptr;
}
}
ClearDependencies();
}
template <class Arc>
bool ReplaceUtil<Arc>::GetTopOrder(const Fst<Arc> &fst,
std::vector<Label> *toporder) const {
// Finds topological order of dependencies.
std::vector<StateId> order;
bool acyclic = false;
TopOrderVisitor<Arc> top_order_visitor(&order, &acyclic);
DfsVisit(fst, &top_order_visitor);
if (!acyclic) {
LOG(WARNING) << "ReplaceUtil::GetTopOrder: Cyclical label dependencies";
return false;
}
toporder->resize(order.size());
for (Label i = 0; i < order.size(); ++i) (*toporder)[order[i]] = i;
return true;
}
template <class Arc>
void ReplaceUtil<Arc>::ReplaceLabels(const std::vector<Label> &labels) {
CheckMutableFsts();
std::unordered_set<Label> label_set;
for (const auto label : labels) {
// Can't replace root.
if (label != root_label_) label_set.insert(label);
}
// Finds FST dependencies restricted to the labels requested.
GetDependencies(false);
VectorFst<Arc> pfst(depfst_);
for (StateId i = 0; i < pfst.NumStates(); ++i) {
std::vector<Arc> arcs;
for (ArcIterator<VectorFst<Arc>> aiter(pfst, i); !aiter.Done();
aiter.Next()) {
const auto &arc = aiter.Value();
const auto label = nonterminal_array_[arc.nextstate];
if (label_set.count(label) > 0) arcs.push_back(arc);
}
pfst.DeleteArcs(i);
for (auto &arc : arcs) pfst.AddArc(i, std::move(arc));
}
std::vector<Label> toporder;
if (!GetTopOrder(pfst, &toporder)) {
ClearDependencies();
return;
}
// Visits FSTs in reverse topological order of dependencies and performs
// replacements.
for (Label o = toporder.size() - 1; o >= 0; --o) {
std::vector<FstPair> fst_pairs;
auto s = toporder[o];
for (ArcIterator<VectorFst<Arc>> aiter(pfst, s); !aiter.Done();
aiter.Next()) {
const auto &arc = aiter.Value();
const auto label = nonterminal_array_[arc.nextstate];
const auto *fst = fst_array_[arc.nextstate];
fst_pairs.emplace_back(label, fst);
}
if (fst_pairs.empty()) continue;
const auto label = nonterminal_array_[s];
const auto *fst = fst_array_[s];
fst_pairs.emplace_back(label, fst);
const ReplaceUtilOptions opts(label, call_label_type_, return_label_type_,
return_label_);
Replace(fst_pairs, mutable_fst_array_[s], opts);
}
ClearDependencies();
}
template <class Arc>
void ReplaceUtil<Arc>::ReplaceBySize(size_t nstates, size_t narcs,
size_t nnonterms) {
std::vector<Label> labels;
GetDependencies(true);
std::vector<Label> toporder;
if (!GetTopOrder(depfst_, &toporder)) {
ClearDependencies();
return;
}
for (Label o = toporder.size() - 1; o >= 0; --o) {
const auto j = toporder[o];
if (stats_[j].nstates <= nstates && stats_[j].narcs <= narcs &&
stats_[j].nnonterms <= nnonterms) {
labels.push_back(nonterminal_array_[j]);
UpdateStats(j);
}
}
ReplaceLabels(labels);
}
template <class Arc>
void ReplaceUtil<Arc>::ReplaceByInstances(size_t ninstances) {
std::vector<Label> labels;
GetDependencies(true);
std::vector<Label> toporder;
if (!GetTopOrder(depfst_, &toporder)) {
ClearDependencies();
return;
}
for (Label o = 0; o < toporder.size(); ++o) {
const auto j = toporder[o];
if (stats_[j].nref <= ninstances) {
labels.push_back(nonterminal_array_[j]);
UpdateStats(j);
}
}
ReplaceLabels(labels);
}
template <class Arc>
void ReplaceUtil<Arc>::GetFstPairs(std::vector<FstPair> *fst_pairs) {
CheckMutableFsts();
fst_pairs->clear();
for (Label i = 0; i < fst_array_.size(); ++i) {
const auto label = nonterminal_array_[i];
const auto *fst = fst_array_[i];
if (!fst) continue;
fst_pairs->emplace_back(label, fst);
}
}
template <class Arc>
void ReplaceUtil<Arc>::GetMutableFstPairs(
std::vector<MutableFstPair> *mutable_fst_pairs) {
CheckMutableFsts();
mutable_fst_pairs->clear();
for (Label i = 0; i < mutable_fst_array_.size(); ++i) {
const auto label = nonterminal_array_[i];
const auto *fst = mutable_fst_array_[i];
if (!fst) continue;
mutable_fst_pairs->emplace_back(label, fst->Copy());
}
}
template <class Arc>
void ReplaceUtil<Arc>::GetSCCProperties() const {
if (!depsccprops_.empty()) return;
GetDependencies(false);
if (depscc_.empty()) return;
for (StateId scc = 0; scc < depscc_.size(); ++scc) {
depsccprops_.push_back(kReplaceSCCLeftLinear | kReplaceSCCRightLinear);
}
if (!(depprops_ & kCyclic)) return; // No cyclic dependencies.
// Checks for self-loops in the dependency graph.
for (StateId scc = 0; scc < depscc_.size(); ++scc) {
for (ArcIterator<Fst<Arc>> aiter(depfst_, scc); !aiter.Done();
aiter.Next()) {
const auto &arc = aiter.Value();
if (arc.nextstate == scc) { // SCC has a self loop.
depsccprops_[scc] |= kReplaceSCCNonTrivial;
}
}
}
std::vector<bool> depscc_visited(depscc_.size(), false);
for (Label i = 0; i < fst_array_.size(); ++i) {
const auto *fst = fst_array_[i];
if (!fst) continue;
const auto depscc = depscc_[i];
if (depscc_visited[depscc]) { // SCC has more than one state.
depsccprops_[depscc] |= kReplaceSCCNonTrivial;
}
depscc_visited[depscc] = true;
std::vector<StateId> fstscc; // SCCs of the current FST.
uint64 fstprops;
SccVisitor<Arc> scc_visitor(&fstscc, nullptr, nullptr, &fstprops);
DfsVisit(*fst, &scc_visitor);
for (StateIterator<Fst<Arc>> siter(*fst); !siter.Done(); siter.Next()) {
const auto s = siter.Value();
for (ArcIterator<Fst<Arc>> aiter(*fst, s); !aiter.Done(); aiter.Next()) {
const auto &arc = aiter.Value();
auto it = nonterminal_hash_.find(arc.olabel);
if (it == nonterminal_hash_.end() || depscc_[it->second] != depscc) {
continue; // Skips if a terminal or a non-terminal not in SCC.
}
const bool arc_in_cycle = fstscc[s] == fstscc[arc.nextstate];
// Left linear iff all non-terminals are initial.
if (s != fst->Start() || arc_in_cycle) {
depsccprops_[depscc] &= ~kReplaceSCCLeftLinear;
}
// Right linear iff all non-terminals are final.
if (fst->Final(arc.nextstate) == Weight::Zero() || arc_in_cycle) {
depsccprops_[depscc] &= ~kReplaceSCCRightLinear;
}
}
}
}
}
} // namespace fst
#endif // FST_REPLACE_UTIL_H_
| [
"watergear@gmail.com"
] | watergear@gmail.com |
54c6667973e22d21446e7b41c983de920d8c112c | 2e2177dca7f5515095cfe595365e3380f1cb076d | /BSTException.h | 0711d78b60f82c456812e3517eab6eb808f974f6 | [] | no_license | jacob-anabi/cpsc350-assignment5 | 8cde4cbb89cfebf2c9c28782e7e193ab47c101cb | e158f716cfe4dd1fe79208e5d144747127b792cf | refs/heads/master | 2020-04-07T19:47:14.347871 | 2018-11-26T07:58:23 | 2018-11-26T07:58:23 | 158,662,616 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 737 | h | /**
* @author Jacob Anabi
* @date 2018-11-22
* @version 1.0
* 2294644
* CPSC 350
* Assignment 5 - Registrar Office Database
*/
#ifndef BSTEXCEPTION_H
#define BSTEXCEPTION_H
#include <string>
#include "RuntimeException.h"
class BSTException : public RuntimeException
{
public:
/**
* default constructor
*/
BSTException();
/**
* variable constructor
* @param err - the error message
*/
explicit BSTException(const std::string& err);
/**
* copy constructor
* @param exception - the exception to copy over
*/
BSTException(const BSTException& exception);
/**
* destructor
* NOTE: trivial
*/
~BSTException() override;
};
#endif // BSTEXCEPTION_H | [
"anabi@chapman.edu"
] | anabi@chapman.edu |
474ce2708c1109ec28e030d4605234dc1ef78ab4 | 648a58987793803813db372718188116a3bdff33 | /src/OBlock.cc | dc6a52848137f2bdcad3c75a965dae5b3a07fedd | [] | no_license | YuChenHeMTL/Quadris | dc96518dd1c1bc8c95f5875f37993a8fbcd58d04 | 517dd7847f7ac38d356b2b8deb3c801a0d63c924 | refs/heads/master | 2022-12-14T11:15:47.893969 | 2020-09-14T09:30:40 | 2020-09-14T09:30:40 | 295,343,311 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 674 | cc | #include "OBlock.h"
// Private Constructor
OBlock::OBlock(bool isHeavy, int levelGenerated) : Block(isHeavy, levelGenerated, 'O') {
std::vector<int> cell1 = {3, 0};
std::vector<int> cell2 = {3, 1};
std::vector<int> cell3 = {4, 0};
std::vector<int> cell4 = {4, 1};
occupiedCellPositions_ = {cell1, cell2, cell3, cell4};
}
// Create method used for BlockFactory since the constructor is private
std::shared_ptr<Block> OBlock::Factory::create(bool isHeavy, int levelGenerated) {
return std::shared_ptr<OBlock>(new OBlock(isHeavy, levelGenerated));
}
// Oblock rotate has no effect since it is a square
void OBlock::rotate(bool) {
moveDownIfHeavy();
return;
} | [
"yc4he@uwaterloo.ca"
] | yc4he@uwaterloo.ca |
a1e15722e5f603e6e8ccc0d0aac6e9c03076533c | 272274a37c6f4ea031dea803cf8fc8ee689ac471 | /services/tracing/public/cpp/perfetto/producer_client.h | aba96de2ec19c9f68c45305344dc9c274263ff19 | [
"BSD-3-Clause"
] | permissive | zjh19861014/chromium | 6db9890f3b2981df3e8a0a56883adc93f6761fd5 | 8d48b756239d336d8724f8f593a7b22959c506b4 | refs/heads/master | 2023-01-09T06:34:30.549622 | 2019-04-13T06:55:11 | 2019-04-13T06:55:11 | 181,134,794 | 1 | 0 | NOASSERTION | 2019-04-13T07:12:06 | 2019-04-13T07:12:06 | null | UTF-8 | C++ | false | false | 7,425 | h | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SERVICES_TRACING_PUBLIC_CPP_PERFETTO_PRODUCER_CLIENT_H_
#define SERVICES_TRACING_PUBLIC_CPP_PERFETTO_PRODUCER_CLIENT_H_
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/atomicops.h"
#include "base/component_export.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/sequence_checker.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "services/tracing/public/cpp/perfetto/task_runner.h"
#include "services/tracing/public/mojom/perfetto_service.mojom.h"
#include "third_party/perfetto/include/perfetto/tracing/core/tracing_service.h"
namespace perfetto {
class SharedMemoryArbiter;
class StartupTraceWriterRegistry;
} // namespace perfetto
namespace tracing {
class MojoSharedMemory;
class ScopedPerfettoPostTaskBlocker {
public:
explicit ScopedPerfettoPostTaskBlocker(bool enable);
~ScopedPerfettoPostTaskBlocker();
private:
const bool enabled_;
};
// This class is the per-process client side of the Perfetto
// producer, and is responsible for creating specific kinds
// of DataSources (like ChromeTracing) on demand, and provide
// them with TraceWriters and a configuration to start logging.
// Implementations of new DataSources should:
// * Implement ProducerClient::DataSourceBase.
// * Add a new data source name in perfetto_service.mojom.
// * Register the data source with Perfetto in ProducerHost::OnConnect.
// * Construct the new implementation when requested to
// in ProducerClient::StartDataSource.
class COMPONENT_EXPORT(TRACING_CPP) ProducerClient
: public mojom::ProducerClient,
public perfetto::TracingService::ProducerEndpoint {
public:
class DataSourceBase {
public:
explicit DataSourceBase(const std::string& name);
virtual ~DataSourceBase();
void StartTracingWithID(
uint64_t data_source_id,
ProducerClient* producer_client,
const perfetto::DataSourceConfig& data_source_config);
virtual void StartTracing(
ProducerClient* producer_client,
const perfetto::DataSourceConfig& data_source_config) = 0;
virtual void StopTracing(
base::OnceClosure stop_complete_callback = base::OnceClosure()) = 0;
// Flush the data source.
virtual void Flush(base::RepeatingClosure flush_complete_callback) = 0;
const std::string& name() const { return name_; }
uint64_t data_source_id() const { return data_source_id_; }
private:
uint64_t data_source_id_ = 0;
std::string name_;
};
// Returns the process-wide instance of the ProducerClient.
static ProducerClient* Get();
~ProducerClient() override;
static void DeleteSoonForTesting(std::unique_ptr<ProducerClient>);
// Returns the taskrunner used by Perfetto.
static PerfettoTaskRunner* GetTaskRunner();
void Connect(mojom::PerfettoServicePtr perfetto_service);
// Create the messagepipes that'll be used to connect
// to the service-side ProducerHost, on the correct
// sequence. The callback will be called on same sequence
// as CreateMojoMessagepipes() got called on.
using MessagepipesReadyCallback =
base::OnceCallback<void(mojom::ProducerClientPtr,
mojom::ProducerHostRequest)>;
void CreateMojoMessagepipes(MessagepipesReadyCallback);
// Binds the registry and its trace writers to the ProducerClient's SMB, to
// write into the given target buffer. The ownership of |registry| is
// transferred to ProducerClient (and its SharedMemoryArbiter).
void BindStartupTraceWriterRegistry(
std::unique_ptr<perfetto::StartupTraceWriterRegistry> registry,
perfetto::BufferID target_buffer);
// Add a new data source to the ProducerClient; the caller
// retains ownership and is responsible for making sure
// the data source outlives the ProducerClient.
void AddDataSource(DataSourceBase*);
// mojom::ProducerClient implementation.
// Called through Mojo by the ProducerHost on the service-side to control
// tracing and toggle specific DataSources.
void OnTracingStart(mojo::ScopedSharedBufferHandle shared_memory) override;
void StartDataSource(uint64_t id,
const perfetto::DataSourceConfig& data_source_config,
StartDataSourceCallback callback) override;
void StopDataSource(uint64_t id, StopDataSourceCallback callback) override;
void Flush(uint64_t flush_request_id,
const std::vector<uint64_t>& data_source_ids) override;
// perfetto::TracingService::ProducerEndpoint implementation.
// Used by the TraceWriters
// to signal Perfetto that shared memory chunks are ready
// for consumption.
void CommitData(const perfetto::CommitDataRequest& commit,
CommitDataCallback callback) override;
// Used by the DataSource implementations to create TraceWriters
// for writing their protobufs, and respond to flushes.
std::unique_ptr<perfetto::TraceWriter> CreateTraceWriter(
perfetto::BufferID target_buffer) override;
void NotifyFlushComplete(perfetto::FlushRequestID) override;
perfetto::SharedMemory* shared_memory() const override;
void RegisterTraceWriter(uint32_t writer_id, uint32_t target_buffer) override;
void UnregisterTraceWriter(uint32_t writer_id) override;
// These ProducerEndpoint functions are only used on the service
// side and should not be called on the clients.
void RegisterDataSource(const perfetto::DataSourceDescriptor&) override;
void UnregisterDataSource(const std::string& name) override;
void NotifyDataSourceStopped(perfetto::DataSourceInstanceID) override;
void NotifyDataSourceStarted(perfetto::DataSourceInstanceID) override;
void ActivateTriggers(const std::vector<std::string>&) override;
size_t shared_buffer_page_size_kb() const override;
static void ResetTaskRunnerForTesting();
protected:
// protected for testing.
ProducerClient();
private:
friend class base::NoDestructor<ProducerClient>;
void CommitDataOnSequence(const perfetto::CommitDataRequest& request);
void AddDataSourceOnSequence(DataSourceBase*);
void RegisterDataSourceWithHost(DataSourceBase* data_source);
// The callback will be run on the |origin_task_runner|, meaning
// the same sequence as CreateMojoMessagePipes() got called on.
void CreateMojoMessagepipesOnSequence(
scoped_refptr<base::SequencedTaskRunner> origin_task_runner,
MessagepipesReadyCallback,
mojom::ProducerClientRequest,
mojom::ProducerClientPtr);
std::unique_ptr<mojo::Binding<mojom::ProducerClient>> binding_;
std::unique_ptr<perfetto::SharedMemoryArbiter> shared_memory_arbiter_;
mojom::ProducerHostPtr producer_host_;
std::unique_ptr<MojoSharedMemory> shared_memory_;
std::set<DataSourceBase*> data_sources_;
// First value is the flush ID, the second is the number of
// replies we're still waiting for.
std::pair<uint64_t, size_t> pending_replies_for_latest_flush_;
SEQUENCE_CHECKER(sequence_checker_);
// NOTE: Weak pointers must be invalidated before all other member variables.
base::WeakPtrFactory<ProducerClient> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(ProducerClient);
};
} // namespace tracing
#endif // SERVICES_TRACING_PUBLIC_CPP_PERFETTO_PRODUCER_CLIENT_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
15901e1a1587bf2e8c1ff56121fea25e4e8c2373 | 4d77398fc24009f483f2b2abc028a135e09fc9eb | /Assignment4/Solid_convection/1.7001/T | 66c8a4cf512589cbfd8b9cc6a5524d127b9d704e | [] | permissive | Naveen-Surya/CFD-Lab-1 | 12c635b72c611d83080ed6dd316b1b0016f2f86f | c38b0bfe43c7135f4a10e744ea1ac6cf6e9d4a1a | refs/heads/master | 2020-04-05T16:43:39.651232 | 2018-08-23T12:10:06 | 2018-08-23T12:10:06 | 157,026,052 | 0 | 1 | MIT | 2018-11-10T22:11:51 | 2018-11-10T22:11:51 | null | UTF-8 | C++ | false | false | 54,237 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 5.x |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "1.7001";
object T;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 1 0 0 0];
internalField nonuniform List<scalar>
6300
(
322.853
322.559
322.264
321.967
321.668
321.366
321.06
320.75
320.436
320.116
319.792
319.461
319.125
318.783
318.436
322.853
322.56
322.266
321.969
321.671
321.369
321.064
320.755
320.441
320.122
319.797
319.467
319.131
318.789
318.441
322.854
322.562
322.269
321.974
321.677
321.376
321.072
320.764
320.451
320.133
319.809
319.479
319.143
318.801
318.453
322.855
322.565
322.274
321.981
321.686
321.387
321.085
320.778
320.466
320.149
319.826
319.496
319.16
318.818
318.47
322.857
322.569
322.281
321.991
321.698
321.402
321.102
320.797
320.487
320.171
319.849
319.52
319.184
318.842
318.492
322.858
322.575
322.29
322.003
321.713
321.42
321.123
320.821
320.514
320.2
319.879
319.551
319.216
318.872
318.522
322.86
322.581
322.3
322.018
321.732
321.443
321.15
320.851
320.547
320.235
319.916
319.59
319.254
318.91
318.558
322.863
322.589
322.313
322.035
321.755
321.471
321.182
320.887
320.586
320.278
319.962
319.636
319.301
318.957
318.602
322.866
322.597
322.328
322.056
321.781
321.502
321.219
320.93
320.634
320.329
320.016
319.693
319.358
319.012
318.655
322.869
322.607
322.344
322.079
321.811
321.539
321.262
320.979
320.689
320.39
320.081
319.76
319.427
319.08
318.719
322.873
322.619
322.363
322.105
321.845
321.581
321.311
321.036
320.752
320.46
320.157
319.84
319.509
319.161
318.795
322.877
322.631
322.384
322.135
321.883
321.627
321.367
321.1
320.825
320.541
320.246
319.935
319.608
319.26
318.89
322.882
322.645
322.407
322.167
321.924
321.679
321.428
321.172
320.908
320.635
320.349
320.047
319.726
319.382
319.01
322.886
322.659
322.431
322.201
321.969
321.735
321.496
321.251
321
320.74
320.468
320.179
319.869
319.531
319.163
322.892
322.675
322.457
322.238
322.017
321.794
321.568
321.338
321.102
320.858
320.603
320.333
320.039
319.711
319.349
318.112
317.814
317.513
317.208
316.9
316.59
316.276
315.96
315.642
315.321
314.998
314.674
314.348
314.021
313.692
313.363
313.033
312.702
312.371
312.039
311.708
311.376
311.044
310.712
310.379
310.047
309.714
309.381
309.049
308.716
308.383
308.051
307.718
307.386
307.054
306.722
306.391
306.06
305.729
305.398
305.067
304.736
304.405
304.074
303.743
303.413
303.082
302.752
302.422
302.093
301.763
301.434
301.106
300.777
300.448
300.12
299.792
299.464
299.135
298.807
298.48
298.152
297.825
297.498
297.171
296.845
296.52
296.194
295.869
295.544
295.22
294.895
294.571
294.247
293.923
293.6
293.277
292.954
292.632
292.31
291.988
291.666
291.344
291.022
290.699
290.376
290.051
289.726
289.4
289.073
318.118
317.819
317.518
317.213
316.905
316.593
316.28
315.963
315.645
315.324
315.001
314.676
314.35
314.022
313.694
313.364
313.034
312.703
312.371
312.04
311.708
311.376
311.044
310.712
310.379
310.047
309.714
309.382
309.049
308.716
308.383
308.05
307.718
307.386
307.054
306.722
306.391
306.059
305.728
305.397
305.066
304.736
304.405
304.074
303.743
303.412
303.082
302.752
302.422
302.092
301.763
301.434
301.105
300.777
300.448
300.12
299.792
299.463
299.135
298.807
298.479
298.152
297.824
297.497
297.171
296.845
296.519
296.194
295.869
295.544
295.219
294.895
294.571
294.247
293.923
293.599
293.276
292.954
292.631
292.309
291.988
291.666
291.344
291.022
290.7
290.377
290.053
289.728
289.402
289.074
318.128
317.83
317.527
317.222
316.913
316.601
316.287
315.97
315.651
315.329
315.006
314.681
314.354
314.026
313.696
313.366
313.035
312.704
312.372
312.04
311.708
311.376
311.044
310.712
310.38
310.047
309.715
309.382
309.049
308.716
308.383
308.05
307.717
307.385
307.053
306.721
306.39
306.059
305.728
305.397
305.066
304.735
304.405
304.074
303.743
303.412
303.081
302.751
302.421
302.091
301.762
301.433
301.105
300.776
300.448
300.12
299.791
299.463
299.135
298.806
298.478
298.151
297.823
297.496
297.17
296.844
296.518
296.193
295.868
295.543
295.219
294.894
294.57
294.246
293.922
293.598
293.275
292.953
292.63
292.309
291.987
291.666
291.345
291.023
290.702
290.379
290.055
289.731
289.405
289.077
318.144
317.845
317.542
317.235
316.926
316.613
316.298
315.98
315.66
315.338
315.014
314.688
314.36
314.031
313.7
313.369
313.037
312.705
312.373
312.041
311.709
311.377
311.045
310.713
310.38
310.048
309.715
309.382
309.049
308.715
308.382
308.049
307.716
307.383
307.051
306.72
306.389
306.058
305.728
305.397
305.066
304.735
304.404
304.073
303.742
303.411
303.08
302.749
302.419
302.09
301.761
301.432
301.104
300.776
300.448
300.119
299.791
299.463
299.134
298.806
298.477
298.149
297.821
297.494
297.168
296.842
296.516
296.191
295.867
295.542
295.218
294.893
294.569
294.245
293.921
293.597
293.274
292.951
292.629
292.307
291.987
291.666
291.346
291.025
290.705
290.383
290.06
289.736
289.41
289.082
318.166
317.866
317.561
317.253
316.942
316.629
316.312
315.994
315.673
315.349
315.024
314.697
314.368
314.037
313.705
313.373
313.04
312.707
312.374
312.041
311.709
311.377
311.045
310.713
310.381
310.049
309.716
309.383
309.049
308.715
308.381
308.047
307.714
307.381
307.049
306.718
306.387
306.057
305.727
305.397
305.066
304.736
304.404
304.073
303.741
303.41
303.078
302.747
302.417
302.088
301.759
301.431
301.103
300.775
300.447
300.119
299.791
299.462
299.133
298.804
298.475
298.147
297.819
297.491
297.165
296.839
296.514
296.189
295.865
295.541
295.217
294.892
294.568
294.243
293.919
293.595
293.271
292.948
292.626
292.305
291.985
291.666
291.347
291.028
290.709
290.388
290.066
289.743
289.417
289.089
318.194
317.892
317.585
317.276
316.963
316.648
316.33
316.01
315.688
315.364
315.037
314.709
314.378
314.045
313.712
313.377
313.043
312.708
312.374
312.041
311.709
311.377
311.046
310.715
310.383
310.051
309.718
309.384
309.049
308.715
308.38
308.045
307.711
307.378
307.046
306.715
306.385
306.056
305.727
305.397
305.067
304.736
304.405
304.073
303.74
303.408
303.076
302.744
302.414
302.084
301.756
301.428
301.101
300.774
300.447
300.12
299.792
299.463
299.133
298.803
298.473
298.144
297.815
297.487
297.161
296.835
296.511
296.187
295.863
295.54
295.216
294.892
294.567
294.242
293.916
293.591
293.267
292.944
292.622
292.302
291.983
291.665
291.348
291.031
290.714
290.396
290.075
289.753
289.427
289.099
318.228
317.923
317.615
317.302
316.988
316.67
316.351
316.03
315.707
315.382
315.054
314.723
314.39
314.056
313.719
313.382
313.045
312.709
312.374
312.04
311.708
311.377
311.046
310.716
310.385
310.054
309.72
309.386
309.051
308.714
308.378
308.042
307.707
307.373
307.042
306.711
306.382
306.054
305.726
305.398
305.069
304.738
304.406
304.073
303.739
303.405
303.072
302.74
302.409
302.079
301.752
301.425
301.1
300.774
300.448
300.121
299.793
299.464
299.133
298.802
298.47
298.14
297.81
297.482
297.155
296.83
296.507
296.184
295.862
295.539
295.216
294.892
294.566
294.24
293.914
293.587
293.262
292.938
292.616
292.296
291.979
291.663
291.349
291.035
290.721
290.406
290.088
289.767
289.442
289.113
318.269
317.961
317.649
317.333
317.015
316.696
316.375
316.053
315.729
315.403
315.074
314.741
314.406
314.068
313.728
313.387
313.047
312.708
312.371
312.037
311.705
311.375
311.047
310.718
310.389
310.058
309.725
309.39
309.053
308.714
308.375
308.037
307.7
307.366
307.035
306.706
306.378
306.052
305.727
305.4
305.072
304.742
304.409
304.075
303.739
303.402
303.067
302.733
302.401
302.072
301.746
301.421
301.098
300.774
300.45
300.124
299.796
299.466
299.134
298.801
298.467
298.134
297.802
297.473
297.147
296.823
296.501
296.181
295.861
295.54
295.217
294.893
294.567
294.239
293.91
293.582
293.254
292.929
292.607
292.288
291.972
291.66
291.349
291.04
290.73
290.419
290.105
289.786
289.462
289.133
318.318
318.005
317.687
317.367
317.045
316.723
316.401
316.079
315.755
315.428
315.098
314.764
314.425
314.082
313.737
313.391
313.046
312.703
312.365
312.03
311.7
311.372
311.047
310.722
310.395
310.066
309.733
309.397
309.057
308.715
308.372
308.03
307.691
307.355
307.024
306.697
306.373
306.05
305.728
305.405
305.078
304.748
304.415
304.078
303.739
303.398
303.059
302.723
302.39
302.062
301.737
301.415
301.095
300.775
300.454
300.13
299.803
299.471
299.137
298.8
298.462
298.125
297.792
297.461
297.135
296.813
296.494
296.177
295.86
295.542
295.221
294.897
294.57
294.239
293.907
293.574
293.243
292.916
292.592
292.274
291.961
291.653
291.348
291.045
290.741
290.436
290.128
289.813
289.491
289.16
318.375
318.055
317.73
317.403
317.076
316.751
316.428
316.106
315.784
315.459
315.129
314.793
314.45
314.101
313.748
313.394
313.041
312.693
312.352
312.017
311.69
311.367
311.047
310.727
310.405
310.079
309.747
309.408
309.064
308.716
308.366
308.019
307.675
307.338
307.008
306.684
306.365
306.048
305.731
305.413
305.09
304.761
304.425
304.084
303.739
303.393
303.048
302.708
302.373
302.046
301.724
301.407
301.093
300.779
300.462
300.141
299.814
299.481
299.143
298.8
298.456
298.113
297.775
297.443
297.118
296.799
296.484
296.173
295.861
295.548
295.23
294.907
294.577
294.242
293.904
293.565
293.228
292.896
292.571
292.254
291.944
291.641
291.344
291.049
290.755
290.46
290.159
289.85
289.531
289.199
318.444
318.113
317.776
317.437
317.103
316.775
316.453
316.135
315.818
315.496
315.168
314.831
314.483
314.126
313.761
313.394
313.03
312.674
312.329
311.996
311.672
311.357
311.046
310.735
310.421
310.1
309.769
309.428
309.077
308.719
308.359
308.001
307.651
307.312
306.983
306.664
306.352
306.045
305.738
305.427
305.109
304.782
304.444
304.097
303.742
303.385
303.03
302.684
302.347
302.021
301.704
301.395
301.09
300.785
300.476
300.161
299.835
299.5
299.155
298.802
298.447
298.095
297.75
297.416
297.092
296.777
296.471
296.168
295.866
295.56
295.247
294.924
294.592
294.251
293.902
293.552
293.204
292.865
292.538
292.222
291.917
291.622
291.335
291.053
290.772
290.49
290.202
289.903
289.589
289.255
318.528
318.182
317.823
317.467
317.121
316.79
316.472
316.163
315.856
315.544
315.221
314.884
314.531
314.161
313.777
313.388
313.007
312.639
312.29
311.959
311.644
311.34
311.044
310.749
310.447
310.134
309.806
309.462
309.101
308.726
308.346
307.972
307.612
307.269
306.943
306.633
306.334
306.042
305.75
305.452
305.143
304.818
304.477
304.12
303.749
303.372
303.002
302.645
302.305
301.982
301.674
301.377
301.087
300.797
300.501
300.193
299.871
299.532
299.177
298.808
298.434
298.065
297.71
297.373
297.051
296.745
296.451
296.163
295.875
295.581
295.276
294.957
294.621
294.269
293.904
293.533
293.169
292.819
292.487
292.173
291.876
291.592
291.32
291.054
290.791
290.528
290.26
289.979
289.674
289.338
318.638
318.267
317.867
317.481
317.118
316.787
316.478
316.188
315.903
315.606
315.296
314.961
314.603
314.214
313.802
313.373
312.963
312.578
312.226
311.899
311.597
311.313
311.042
310.772
310.489
310.19
309.867
309.52
309.143
308.742
308.324
307.924
307.548
307.203
306.882
306.586
306.306
306.039
305.772
305.493
305.197
304.878
304.535
304.161
303.765
303.35
302.954
302.581
302.239
301.921
301.627
301.349
301.084
300.819
300.541
300.248
299.93
299.589
299.217
298.823
298.411
298.017
297.646
297.306
296.989
296.697
296.421
296.158
295.894
295.619
295.327
295.012
294.674
294.305
293.914
293.505
293.115
292.748
292.412
292.1
291.814
291.547
291.296
291.052
290.808
290.573
290.338
290.089
289.805
289.468
318.794
318.397
317.889
317.462
317.07
316.75
316.457
316.207
315.964
315.69
315.404
315.071
314.719
314.3
313.853
313.328
312.884
312.471
312.126
311.802
311.527
311.266
311.039
310.813
310.554
310.281
309.962
309.623
309.218
308.785
308.275
307.842
307.439
307.102
306.784
306.515
306.259
306.035
305.812
305.556
305.287
304.971
304.636
304.235
303.807
303.301
302.873
302.473
302.139
301.824
301.557
301.303
301.081
300.858
300.605
300.337
300.023
299.689
299.291
298.864
298.361
297.935
297.537
297.205
296.892
296.625
296.373
296.152
295.931
295.679
295.413
295.101
294.769
294.373
293.949
293.45
293.026
292.631
292.301
291.99
291.727
291.477
291.261
291.048
290.814
290.617
290.438
290.248
290.013
289.687
319.039
318.685
317.797
317.391
316.919
316.675
316.371
316.218
316.071
315.79
315.581
315.207
314.932
314.426
314.017
313.167
312.761
312.264
311.995
311.634
311.435
311.172
311.036
310.9
310.638
310.441
310.084
309.82
309.333
308.938
308.113
307.719
307.234
306.972
306.619
306.423
306.165
306.031
305.897
305.639
305.444
305.093
304.831
304.35
303.959
303.142
302.751
302.271
302.011
301.661
301.467
301.21
301.077
300.944
300.687
300.493
300.144
299.884
299.404
299.015
298.202
297.813
297.335
297.076
296.727
296.534
296.279
296.146
296.014
295.758
295.565
295.217
294.959
294.481
294.094
293.285
292.897
292.421
292.162
291.813
291.619
291.358
291.222
291.077
290.765
290.635
290.553
290.471
290.351
290.106
288.712
288.317
287.921
287.524
287.127
286.73
286.333
285.938
285.543
285.149
284.757
284.365
283.974
283.584
283.195
288.713
288.318
287.921
287.524
287.127
286.729
286.333
285.937
285.542
285.148
284.756
284.364
283.974
283.584
283.195
288.716
288.32
287.923
287.525
287.126
286.728
286.331
285.935
285.54
285.146
284.754
284.362
283.972
283.583
283.194
288.72
288.323
287.925
287.525
287.126
286.727
286.328
285.931
285.536
285.142
284.75
284.36
283.97
283.582
283.194
288.726
288.328
287.928
287.526
287.125
286.724
286.324
285.927
285.531
285.137
284.745
284.355
283.967
283.58
283.193
288.735
288.335
287.932
287.528
287.123
286.72
286.319
285.92
285.523
285.13
284.739
284.35
283.963
283.577
283.192
288.748
288.344
287.937
287.529
287.121
286.714
286.311
285.91
285.513
285.12
284.73
284.342
283.957
283.574
283.191
288.764
288.356
287.944
287.53
287.116
286.706
286.299
285.897
285.5
285.107
284.718
284.332
283.95
283.569
283.19
288.788
288.373
287.952
287.53
287.109
286.693
286.283
285.879
285.482
285.09
284.703
284.32
283.94
283.563
283.188
288.821
288.394
287.961
287.527
287.098
286.675
286.261
285.856
285.458
285.068
284.683
284.304
283.929
283.556
283.185
288.867
288.423
287.971
287.521
287.079
286.649
286.23
285.824
285.427
285.039
284.659
284.284
283.914
283.547
283.182
288.933
288.461
287.98
287.507
287.05
286.61
286.188
285.781
285.387
285.004
284.629
284.26
283.897
283.537
283.179
289.031
288.506
287.98
287.477
287.002
286.554
286.131
285.726
285.337
284.96
284.592
284.231
283.876
283.524
283.174
289.175
288.552
287.958
287.418
286.927
286.475
286.054
285.656
285.274
284.906
284.548
284.197
283.851
283.509
283.17
289.385
288.568
287.883
287.309
286.812
286.366
285.954
285.568
285.199
284.843
284.496
284.157
283.823
283.493
283.164
322.897
322.689
322.482
322.273
322.064
321.852
321.639
321.422
321.202
320.976
320.742
320.495
320.224
319.909
319.499
322.901
322.703
322.505
322.306
322.107
321.907
321.705
321.502
321.297
321.089
320.877
320.658
320.425
320.154
319.744
322.906
322.717
322.529
322.34
322.151
321.962
321.772
321.583
321.393
321.204
321.016
320.831
320.652
320.495
320.442
322.91
322.731
322.552
322.373
322.195
322.017
321.839
321.664
321.49
321.319
321.155
321
320.864
320.764
320.729
322.915
322.745
322.576
322.407
322.238
322.071
321.906
321.743
321.584
321.43
321.286
321.155
321.05
320.989
321.013
322.92
322.759
322.599
322.439
322.281
322.125
321.971
321.82
321.674
321.535
321.407
321.294
321.206
321.154
321.146
322.924
322.773
322.621
322.471
322.323
322.176
322.033
321.893
321.759
321.633
321.517
321.416
321.336
321.288
321.288
322.928
322.786
322.643
322.502
322.363
322.226
322.092
321.963
321.839
321.723
321.616
321.522
321.445
321.388
321.352
322.933
322.798
322.665
322.532
322.402
322.274
322.149
322.029
321.914
321.806
321.707
321.618
321.54
321.473
321.405
322.937
322.81
322.685
322.561
322.438
322.319
322.203
322.091
321.984
321.884
321.79
321.705
321.628
321.558
321.497
322.941
322.822
322.704
322.588
322.473
322.362
322.253
322.149
322.05
321.956
321.869
321.787
321.711
321.638
321.557
322.944
322.833
322.722
322.613
322.506
322.402
322.301
322.204
322.111
322.024
321.942
321.865
321.793
321.722
321.657
322.948
322.843
322.74
322.638
322.537
322.44
322.346
322.255
322.17
322.089
322.012
321.941
321.872
321.803
321.722
322.951
322.853
322.756
322.66
322.567
322.476
322.388
322.304
322.224
322.149
322.079
322.014
321.952
321.892
321.834
322.954
322.862
322.771
322.682
322.594
322.509
322.428
322.35
322.276
322.207
322.143
322.085
322.032
321.98
321.915
322.957
322.871
322.786
322.702
322.62
322.541
322.465
322.392
322.324
322.261
322.203
322.152
322.109
322.078
322.076
322.96
322.879
322.799
322.721
322.644
322.57
322.499
322.432
322.369
322.311
322.259
322.214
322.179
322.156
322.148
322.962
322.887
322.812
322.738
322.667
322.597
322.531
322.468
322.41
322.357
322.309
322.27
322.239
322.223
322.228
322.964
322.894
322.823
322.754
322.687
322.622
322.561
322.502
322.448
322.398
322.355
322.318
322.291
322.274
322.268
322.967
322.9
322.834
322.769
322.706
322.646
322.588
322.533
322.482
322.436
322.395
322.361
322.335
322.319
322.317
322.969
322.906
322.844
322.783
322.724
322.667
322.612
322.561
322.513
322.469
322.43
322.398
322.372
322.353
322.342
322.97
322.912
322.853
322.796
322.74
322.686
322.635
322.586
322.541
322.499
322.462
322.43
322.403
322.383
322.372
322.972
322.917
322.862
322.808
322.755
322.704
322.656
322.609
322.566
322.526
322.49
322.458
322.43
322.406
322.386
322.974
322.921
322.869
322.818
322.769
322.721
322.674
322.631
322.589
322.551
322.516
322.483
322.454
322.427
322.399
322.975
322.926
322.876
322.828
322.781
322.736
322.692
322.65
322.61
322.573
322.539
322.507
322.477
322.448
322.421
322.976
322.93
322.883
322.837
322.793
322.749
322.708
322.668
322.63
322.594
322.56
322.528
322.498
322.468
322.436
322.978
322.933
322.889
322.846
322.803
322.762
322.722
322.684
322.648
322.613
322.581
322.549
322.519
322.49
322.461
322.979
322.936
322.895
322.853
322.813
322.774
322.736
322.699
322.664
322.631
322.6
322.57
322.54
322.511
322.478
322.98
322.94
322.9
322.86
322.822
322.784
322.748
322.713
322.68
322.648
322.618
322.589
322.561
322.534
322.506
322.981
322.942
322.904
322.867
322.83
322.794
322.76
322.726
322.694
322.664
322.635
322.608
322.582
322.557
322.528
322.982
322.945
322.909
322.873
322.838
322.803
322.77
322.738
322.708
322.679
322.651
322.626
322.603
322.582
322.57
322.982
322.947
322.912
322.878
322.844
322.812
322.78
322.749
322.72
322.692
322.666
322.642
322.621
322.603
322.588
322.983
322.949
322.916
322.883
322.851
322.819
322.789
322.759
322.731
322.705
322.68
322.657
322.637
322.62
322.61
322.984
322.951
322.919
322.888
322.857
322.826
322.797
322.768
322.741
322.716
322.692
322.67
322.651
322.634
322.62
322.984
322.953
322.922
322.892
322.862
322.833
322.804
322.777
322.751
322.726
322.703
322.681
322.662
322.646
322.633
322.985
322.955
322.925
322.895
322.867
322.838
322.811
322.784
322.759
322.735
322.712
322.691
322.672
322.655
322.64
322.985
322.956
322.927
322.899
322.871
322.843
322.817
322.791
322.766
322.742
322.72
322.699
322.68
322.662
322.648
322.986
322.958
322.93
322.902
322.875
322.848
322.822
322.797
322.773
322.749
322.727
322.706
322.687
322.668
322.651
322.986
322.959
322.932
322.905
322.878
322.852
322.827
322.802
322.778
322.756
322.734
322.713
322.693
322.674
322.654
322.987
322.96
322.933
322.907
322.881
322.856
322.831
322.807
322.784
322.761
322.739
322.719
322.698
322.679
322.66
322.987
322.961
322.935
322.909
322.884
322.859
322.835
322.811
322.788
322.766
322.745
322.724
322.704
322.684
322.664
322.987
322.962
322.936
322.911
322.886
322.862
322.838
322.815
322.792
322.77
322.749
322.729
322.708
322.689
322.67
322.987
322.962
322.938
322.913
322.889
322.865
322.841
322.818
322.796
322.774
322.753
322.733
322.713
322.693
322.673
322.988
322.963
322.939
322.914
322.89
322.867
322.844
322.821
322.799
322.778
322.757
322.737
322.718
322.698
322.68
322.988
322.964
322.939
322.916
322.892
322.869
322.846
322.824
322.802
322.781
322.761
322.741
322.722
322.703
322.684
322.988
322.964
322.94
322.917
322.893
322.87
322.848
322.826
322.805
322.784
322.764
322.744
322.726
322.708
322.692
322.988
322.964
322.941
322.917
322.894
322.872
322.849
322.828
322.807
322.786
322.766
322.747
322.729
322.712
322.696
322.988
322.965
322.941
322.918
322.895
322.873
322.851
322.829
322.808
322.788
322.768
322.749
322.731
322.714
322.699
322.988
322.965
322.942
322.918
322.896
322.873
322.851
322.83
322.809
322.789
322.77
322.751
322.733
322.716
322.7
322.988
322.965
322.942
322.919
322.896
322.874
322.852
322.83
322.81
322.79
322.77
322.752
322.734
322.717
322.702
322.988
322.965
322.942
322.919
322.896
322.874
322.852
322.831
322.81
322.79
322.771
322.752
322.735
322.718
322.702
322.988
322.965
322.942
322.919
322.896
322.873
322.852
322.83
322.81
322.79
322.771
322.752
322.735
322.718
322.702
322.988
322.965
322.941
322.918
322.895
322.873
322.851
322.83
322.809
322.789
322.77
322.751
322.734
322.718
322.702
322.988
322.964
322.941
322.917
322.894
322.872
322.85
322.828
322.808
322.788
322.768
322.75
322.733
322.716
322.701
322.988
322.964
322.94
322.917
322.893
322.871
322.848
322.827
322.806
322.786
322.766
322.748
322.731
322.715
322.7
322.988
322.964
322.939
322.915
322.892
322.869
322.846
322.824
322.803
322.783
322.764
322.745
322.728
322.712
322.698
322.988
322.963
322.938
322.914
322.89
322.867
322.844
322.822
322.8
322.78
322.76
322.742
322.725
322.709
322.694
322.987
322.962
322.937
322.912
322.888
322.864
322.841
322.819
322.797
322.776
322.756
322.737
322.72
322.704
322.691
322.987
322.961
322.936
322.911
322.886
322.861
322.838
322.815
322.793
322.771
322.751
322.732
322.714
322.698
322.684
322.987
322.96
322.934
322.908
322.883
322.858
322.834
322.81
322.788
322.766
322.746
322.726
322.708
322.691
322.677
322.986
322.959
322.932
322.906
322.88
322.854
322.83
322.806
322.782
322.76
322.739
322.719
322.7
322.681
322.661
322.986
322.958
322.93
322.903
322.876
322.85
322.825
322.8
322.776
322.754
322.732
322.711
322.691
322.672
322.653
322.986
322.957
322.928
322.9
322.872
322.845
322.819
322.794
322.77
322.746
322.724
322.703
322.683
322.662
322.641
322.985
322.955
322.926
322.896
322.868
322.84
322.813
322.787
322.762
322.738
322.716
322.694
322.674
322.654
322.634
322.984
322.953
322.923
322.893
322.863
322.834
322.806
322.779
322.754
322.73
322.707
322.685
322.664
322.644
322.623
322.984
322.952
322.92
322.888
322.857
322.828
322.799
322.771
322.745
322.72
322.697
322.675
322.654
322.635
322.617
322.983
322.949
322.916
322.883
322.851
322.82
322.79
322.762
322.735
322.709
322.685
322.664
322.644
322.625
322.606
322.982
322.947
322.912
322.878
322.845
322.812
322.781
322.751
322.723
322.697
322.673
322.651
322.632
322.615
322.601
322.981
322.945
322.908
322.872
322.837
322.803
322.771
322.74
322.711
322.684
322.659
322.637
322.619
322.604
322.594
322.981
322.942
322.903
322.866
322.829
322.793
322.759
322.727
322.696
322.668
322.643
322.621
322.603
322.589
322.579
322.98
322.939
322.898
322.859
322.82
322.782
322.746
322.712
322.681
322.651
322.625
322.603
322.585
322.572
322.567
322.978
322.935
322.893
322.851
322.81
322.77
322.732
322.697
322.663
322.632
322.605
322.581
322.562
322.549
322.542
322.977
322.932
322.887
322.842
322.799
322.757
322.717
322.679
322.643
322.611
322.581
322.556
322.536
322.523
322.521
322.976
322.928
322.88
322.833
322.787
322.743
322.7
322.66
322.622
322.587
322.555
322.527
322.504
322.488
322.48
322.974
322.923
322.873
322.823
322.774
322.727
322.682
322.639
322.599
322.561
322.526
322.495
322.468
322.448
322.443
322.973
322.918
322.865
322.812
322.76
322.71
322.662
322.617
322.573
322.533
322.495
322.46
322.428
322.397
322.359
322.971
322.913
322.856
322.8
322.745
322.692
322.641
322.592
322.546
322.502
322.462
322.423
322.387
322.351
322.316
322.969
322.908
322.847
322.787
322.729
322.673
322.618
322.566
322.517
322.47
322.427
322.385
322.345
322.304
322.257
322.967
322.902
322.837
322.774
322.712
322.651
322.594
322.538
322.486
322.436
322.39
322.346
322.303
322.262
322.223
322.965
322.896
322.827
322.759
322.693
322.629
322.567
322.508
322.453
322.401
322.352
322.305
322.261
322.218
322.17
322.963
322.889
322.815
322.743
322.673
322.604
322.539
322.476
322.418
322.362
322.311
322.264
322.219
322.177
322.138
322.96
322.881
322.803
322.726
322.651
322.578
322.508
322.442
322.38
322.322
322.268
322.22
322.175
322.134
322.089
322.958
322.873
322.79
322.708
322.627
322.55
322.475
322.405
322.339
322.278
322.222
322.173
322.13
322.092
322.062
322.955
322.865
322.776
322.688
322.602
322.519
322.44
322.364
322.294
322.23
322.172
322.122
322.08
322.046
322.028
322.952
322.856
322.761
322.667
322.575
322.486
322.401
322.32
322.245
322.177
322.117
322.066
322.024
321.989
321.947
322.949
322.846
322.745
322.645
322.546
322.451
322.359
322.272
322.192
322.118
322.055
322.003
321.964
321.936
321.912
322.945
322.836
322.728
322.621
322.516
322.413
322.314
322.22
322.133
322.053
321.985
321.931
321.896
321.881
321.887
322.942
322.825
322.71
322.595
322.483
322.373
322.266
322.164
322.068
321.981
321.905
321.847
321.813
321.812
321.855
322.938
322.814
322.691
322.569
322.448
322.33
322.214
322.103
321.997
321.9
321.814
321.746
321.707
321.714
321.799
322.934
322.803
322.672
322.542
322.412
322.285
322.16
322.038
321.921
321.81
321.71
321.626
321.568
321.561
321.669
289.605
288.463
287.711
287.139
286.66
286.233
285.841
285.471
285.118
284.776
284.443
284.116
283.794
283.475
283.158
289.203
288.097
287.431
286.921
286.484
286.09
285.722
285.372
285.036
284.709
284.39
284.076
283.766
283.458
283.153
287.613
287.425
287.042
286.651
286.28
285.927
285.59
285.264
284.947
284.637
284.333
284.032
283.735
283.44
283.147
286.989
286.889
286.657
286.369
286.063
285.755
285.45
285.149
284.853
284.561
284.273
283.987
283.704
283.422
283.14
286.399
286.445
286.312
286.098
285.847
285.58
285.306
285.031
284.756
284.483
284.211
283.94
283.671
283.402
283.134
286.132
286.124
286.023
285.853
285.642
285.409
285.164
284.913
284.659
284.404
284.148
283.892
283.637
283.382
283.127
285.856
285.868
285.782
285.637
285.454
285.247
285.026
284.797
284.562
284.325
284.085
283.845
283.604
283.362
283.121
285.732
285.679
285.582
285.446
285.281
285.095
284.895
284.684
284.468
284.247
284.023
283.797
283.57
283.342
283.114
285.633
285.522
285.409
285.276
285.123
284.953
284.769
284.576
284.376
284.171
283.962
283.751
283.537
283.323
283.108
285.463
285.365
285.25
285.121
284.977
284.82
284.651
284.473
284.288
284.098
283.903
283.705
283.505
283.304
283.101
285.352
285.22
285.1
284.975
284.84
284.695
284.539
284.375
284.204
284.027
283.846
283.661
283.474
283.285
283.095
285.17
285.067
284.954
284.836
284.71
284.576
284.433
284.282
284.124
283.96
283.791
283.619
283.444
283.267
283.089
285.052
284.921
284.811
284.702
284.587
284.464
284.333
284.194
284.048
283.896
283.739
283.579
283.415
283.25
283.083
284.85
284.761
284.668
284.572
284.469
284.358
284.238
284.111
283.976
283.835
283.69
283.541
283.388
283.234
283.078
284.704
284.604
284.527
284.447
284.357
284.257
284.149
284.032
283.908
283.778
283.643
283.504
283.362
283.218
283.073
284.418
284.43
284.389
284.327
284.251
284.163
284.065
283.958
283.845
283.725
283.599
283.47
283.338
283.204
283.068
284.29
284.292
284.266
284.218
284.153
284.076
283.987
283.89
283.785
283.674
283.558
283.438
283.315
283.19
283.063
284.148
284.174
284.159
284.121
284.065
283.996
283.916
283.827
283.73
283.628
283.52
283.409
283.294
283.177
283.059
284.077
284.082
284.069
284.035
283.986
283.923
283.85
283.768
283.679
283.584
283.485
283.381
283.274
283.165
283.055
283.992
284.004
283.992
283.961
283.915
283.858
283.791
283.715
283.633
283.545
283.452
283.355
283.256
283.154
283.052
283.948
283.944
283.927
283.896
283.853
283.8
283.737
283.667
283.59
283.508
283.422
283.332
283.239
283.144
283.048
283.897
283.893
283.873
283.841
283.798
283.747
283.689
283.623
283.551
283.475
283.394
283.31
283.223
283.135
283.045
283.872
283.853
283.826
283.792
283.75
283.701
283.645
283.583
283.516
283.444
283.369
283.29
283.209
283.126
283.042
283.851
283.818
283.785
283.748
283.706
283.659
283.605
283.547
283.484
283.416
283.345
283.272
283.196
283.118
283.039
283.814
283.782
283.747
283.709
283.667
283.62
283.569
283.514
283.454
283.391
283.324
283.255
283.183
283.111
283.037
283.788
283.748
283.711
283.672
283.631
283.586
283.537
283.484
283.427
283.367
283.305
283.24
283.172
283.104
283.035
283.747
283.712
283.675
283.637
283.597
283.553
283.506
283.456
283.403
283.346
283.287
283.226
283.162
283.098
283.033
283.719
283.678
283.641
283.604
283.565
283.523
283.479
283.431
283.38
283.327
283.271
283.213
283.153
283.092
283.031
283.672
283.64
283.606
283.572
283.535
283.496
283.453
283.408
283.36
283.309
283.256
283.201
283.145
283.087
283.029
283.638
283.603
283.573
283.541
283.507
283.47
283.43
283.387
283.341
283.293
283.243
283.191
283.137
283.083
283.028
283.572
283.562
283.54
283.512
283.481
283.446
283.408
283.367
283.324
283.278
283.23
283.181
283.13
283.078
283.026
283.542
283.53
283.511
283.486
283.457
283.424
283.389
283.35
283.308
283.265
283.219
283.172
283.124
283.075
283.025
283.51
283.503
283.486
283.464
283.436
283.405
283.371
283.334
283.294
283.253
283.209
283.164
283.118
283.071
283.024
283.494
283.482
283.466
283.444
283.418
283.388
283.355
283.32
283.282
283.242
283.2
283.157
283.113
283.068
283.023
283.475
283.465
283.448
283.427
283.402
283.373
283.341
283.307
283.271
283.232
283.192
283.151
283.109
283.066
283.022
283.466
283.452
283.434
283.413
283.388
283.36
283.329
283.296
283.261
283.224
283.185
283.146
283.105
283.063
283.021
283.456
283.441
283.423
283.401
283.376
283.349
283.319
283.287
283.253
283.217
283.179
283.141
283.101
283.061
283.02
283.451
283.433
283.414
283.392
283.367
283.34
283.31
283.279
283.245
283.21
283.174
283.137
283.098
283.059
283.02
283.447
283.427
283.406
283.384
283.359
283.332
283.303
283.272
283.239
283.205
283.17
283.133
283.096
283.058
283.019
283.441
283.422
283.4
283.377
283.352
283.326
283.297
283.266
283.234
283.201
283.166
283.13
283.094
283.056
283.019
283.438
283.417
283.395
283.372
283.347
283.32
283.292
283.262
283.23
283.197
283.163
283.128
283.092
283.055
283.018
283.433
283.413
283.392
283.368
283.343
283.317
283.288
283.258
283.227
283.194
283.161
283.126
283.091
283.055
283.018
283.431
283.411
283.389
283.366
283.341
283.314
283.286
283.256
283.225
283.192
283.159
283.125
283.09
283.054
283.018
283.428
283.409
283.387
283.364
283.339
283.312
283.284
283.254
283.223
283.191
283.158
283.124
283.089
283.054
283.018
283.428
283.409
283.387
283.363
283.338
283.312
283.283
283.254
283.223
283.191
283.158
283.123
283.089
283.053
283.018
283.43
283.41
283.388
283.364
283.339
283.312
283.284
283.254
283.223
283.191
283.158
283.124
283.089
283.053
283.018
283.432
283.412
283.39
283.366
283.341
283.314
283.285
283.255
283.224
283.192
283.159
283.124
283.089
283.054
283.018
283.437
283.415
283.393
283.369
283.343
283.316
283.288
283.258
283.226
283.194
283.16
283.125
283.09
283.054
283.018
283.44
283.419
283.397
283.373
283.347
283.32
283.291
283.261
283.229
283.196
283.162
283.127
283.091
283.055
283.018
283.447
283.425
283.402
283.378
283.352
283.325
283.296
283.265
283.233
283.199
283.165
283.129
283.093
283.056
283.019
283.451
283.43
283.408
283.384
283.358
283.331
283.301
283.27
283.237
283.203
283.168
283.132
283.095
283.057
283.019
283.458
283.437
283.415
283.391
283.365
283.338
283.308
283.276
283.243
283.208
283.172
283.135
283.097
283.058
283.02
283.463
283.444
283.423
283.4
283.374
283.346
283.316
283.284
283.249
283.214
283.177
283.139
283.1
283.06
283.02
283.468
283.453
283.433
283.41
283.385
283.356
283.325
283.292
283.257
283.22
283.182
283.143
283.103
283.062
283.021
283.48
283.464
283.445
283.423
283.397
283.368
283.336
283.302
283.266
283.228
283.189
283.148
283.106
283.064
283.021
283.49
283.478
283.46
283.438
283.411
283.381
283.349
283.313
283.276
283.237
283.196
283.154
283.11
283.067
283.022
283.51
283.497
283.479
283.455
283.428
283.397
283.363
283.326
283.287
283.246
283.204
283.16
283.115
283.069
283.023
283.527
283.518
283.5
283.476
283.447
283.415
283.379
283.341
283.3
283.257
283.213
283.167
283.12
283.072
283.024
283.561
283.547
283.526
283.5
283.469
283.434
283.397
283.357
283.314
283.269
283.223
283.175
283.126
283.076
283.025
283.592
283.58
283.556
283.526
283.493
283.456
283.417
283.375
283.33
283.283
283.234
283.184
283.132
283.08
283.027
283.661
283.622
283.59
283.556
283.519
283.48
283.439
283.394
283.347
283.297
283.246
283.193
283.139
283.084
283.028
283.696
283.66
283.624
283.587
283.548
283.506
283.462
283.415
283.365
283.314
283.259
283.204
283.146
283.088
283.029
283.744
283.699
283.659
283.619
283.578
283.534
283.488
283.438
283.386
283.331
283.274
283.215
283.155
283.093
283.031
283.772
283.734
283.694
283.653
283.61
283.564
283.515
283.463
283.408
283.35
283.29
283.227
283.164
283.099
283.033
283.814
283.77
283.73
283.688
283.644
283.596
283.545
283.49
283.432
283.371
283.307
283.241
283.173
283.104
283.035
283.84
283.804
283.766
283.725
283.68
283.631
283.577
283.519
283.458
283.393
283.326
283.256
283.184
283.111
283.037
283.877
283.84
283.804
283.764
283.719
283.668
283.612
283.551
283.486
283.418
283.346
283.272
283.195
283.118
283.039
283.899
283.876
283.845
283.807
283.762
283.709
283.65
283.586
283.517
283.444
283.368
283.289
283.208
283.125
283.042
283.924
283.916
283.891
283.855
283.809
283.755
283.693
283.624
283.551
283.473
283.392
283.307
283.221
283.133
283.045
283.975
283.967
283.946
283.911
283.863
283.805
283.739
283.666
283.588
283.504
283.417
283.328
283.235
283.142
283.047
284.02
284.028
284.01
283.974
283.924
283.862
283.791
283.712
283.628
283.538
283.445
283.349
283.251
283.151
283.05
284.106
284.107
284.087
284.048
283.992
283.925
283.847
283.762
283.671
283.575
283.475
283.372
283.267
283.161
283.054
284.179
284.199
284.178
284.132
284.07
283.994
283.909
283.816
283.718
283.614
283.507
283.397
283.285
283.172
283.057
284.324
284.32
284.286
284.229
284.156
284.071
283.976
283.875
283.768
283.656
283.541
283.423
283.304
283.183
283.061
284.456
284.46
284.41
284.337
284.25
284.153
284.048
283.937
283.821
283.7
283.577
283.451
283.323
283.194
283.065
284.753
284.639
284.549
284.455
284.352
284.242
284.125
284.003
283.876
283.746
283.614
283.479
283.343
283.206
283.069
284.906
284.802
284.691
284.578
284.459
284.334
284.205
284.071
283.934
283.795
283.653
283.509
283.364
283.219
283.073
285.121
284.969
284.836
284.704
284.57
284.431
284.288
284.143
283.994
283.844
283.693
283.54
283.386
283.232
283.077
285.25
285.122
284.98
284.833
284.683
284.53
284.374
284.216
284.056
283.895
283.733
283.571
283.408
283.245
283.082
285.456
285.286
285.127
284.964
284.799
284.63
284.46
284.29
284.118
283.946
283.774
283.602
283.43
283.258
283.086
285.586
285.443
285.276
285.098
284.916
284.732
284.548
284.364
284.18
283.998
283.815
283.634
283.452
283.271
283.09
285.803
285.618
285.431
285.235
285.035
284.835
284.635
284.438
284.242
284.049
283.856
283.665
283.474
283.284
283.095
285.939
285.793
285.593
285.375
285.154
284.936
284.721
284.511
284.303
284.099
283.896
283.695
283.496
283.297
283.099
286.156
286.007
285.766
285.516
285.271
285.035
284.805
284.581
284.362
284.147
283.935
283.725
283.517
283.31
283.103
286.756
286.285
285.947
285.653
285.383
285.128
284.884
284.648
284.419
284.194
283.972
283.754
283.537
283.322
283.107
286.953
286.472
286.096
285.775
285.485
285.215
284.958
284.711
284.472
284.238
284.008
283.781
283.556
283.333
283.111
287.029
286.585
286.206
285.874
285.572
285.292
285.025
284.769
284.521
284.279
284.041
283.806
283.574
283.344
283.115
287.062
286.652
286.285
285.952
285.646
285.358
285.085
284.822
284.566
284.317
284.072
283.83
283.591
283.354
283.118
287.074
286.691
286.339
286.012
285.706
285.416
285.137
284.869
284.607
284.351
284.1
283.852
283.607
283.364
283.121
287.066
286.708
286.375
286.058
285.756
285.465
285.183
284.91
284.644
284.383
284.126
283.873
283.622
283.372
283.124
322.93
322.79
322.65
322.51
322.372
322.234
322.097
321.963
321.832
321.704
321.584
321.473
321.377
321.305
321.268
322.925
322.775
322.626
322.476
322.326
322.177
322.027
321.878
321.73
321.582
321.436
321.291
321.144
320.991
320.808
322.92
322.761
322.601
322.441
322.281
322.119
321.957
321.793
321.627
321.459
321.288
321.109
320.919
320.706
320.448
322.916
322.747
322.577
322.407
322.236
322.063
321.887
321.709
321.527
321.34
321.146
320.94
320.717
320.466
320.174
322.911
322.733
322.554
322.374
322.193
322.008
321.821
321.63
321.433
321.229
321.015
320.787
320.541
320.269
319.962
322.907
322.72
322.532
322.343
322.152
321.957
321.759
321.555
321.345
321.127
320.897
320.654
320.392
320.107
319.793
322.903
322.708
322.512
322.314
322.114
321.91
321.702
321.488
321.266
321.036
320.794
320.538
320.266
319.973
319.657
322.899
322.697
322.494
322.288
322.08
321.868
321.651
321.427
321.196
320.956
320.705
320.44
320.16
319.862
319.545
322.896
322.687
322.477
322.265
322.05
321.83
321.606
321.375
321.136
320.888
320.629
320.358
320.072
319.771
319.453
322.893
322.679
322.463
322.245
322.023
321.798
321.567
321.329
321.084
320.83
320.565
320.289
320
319.696
319.378
322.891
322.671
322.451
322.228
322.001
321.771
321.535
321.292
321.042
320.783
320.514
320.234
319.941
319.636
319.318
322.889
322.666
322.441
322.214
321.984
321.749
321.509
321.263
321.008
320.746
320.473
320.19
319.896
319.59
319.271
322.887
322.661
322.434
322.204
321.971
321.733
321.49
321.24
320.983
320.718
320.443
320.159
319.863
319.556
319.237
322.886
322.658
322.429
322.197
321.962
321.722
321.477
321.226
320.967
320.7
320.424
320.138
319.841
319.533
319.214
322.886
322.657
322.426
322.194
321.957
321.717
321.471
321.218
320.959
320.691
320.414
320.127
319.83
319.522
319.203
321.252
320.836
319.448
318.857
318.225
317.912
317.54
317.358
317.187
316.866
316.63
316.21
315.903
315.341
314.89
313.949
313.501
312.952
312.656
312.259
312.04
311.75
311.601
311.451
311.164
310.947
310.556
310.266
309.73
309.295
308.386
307.952
307.416
307.126
306.736
306.519
306.233
306.085
305.937
305.651
305.435
305.045
304.756
304.221
303.787
302.879
302.444
301.908
301.617
301.226
301.01
300.723
300.574
300.425
300.138
299.92
299.528
299.236
298.697
298.258
297.339
296.899
296.356
296.062
295.664
295.444
295.151
294.998
294.845
294.549
294.323
293.914
293.607
293.035
292.565
291.573
291.094
290.489
290.155
289.686
289.416
289.027
288.808
288.522
287.806
287.553
287.438
287.366
287.3
287.209
320.55
320.118
319.445
318.881
318.378
317.98
317.626
317.333
317.053
316.741
316.42
316.047
315.656
315.192
314.698
314.118
313.628
313.172
312.792
312.436
312.133
311.847
311.598
311.349
311.064
310.765
310.414
310.041
309.596
309.119
308.557
308.08
307.635
307.263
306.912
306.614
306.331
306.083
305.836
305.553
305.255
304.904
304.532
304.088
303.611
303.049
302.572
302.127
301.754
301.403
301.104
300.82
300.571
300.322
300.038
299.738
299.385
299.01
298.561
298.08
297.512
297.03
296.579
296.201
295.845
295.541
295.251
294.998
294.743
294.449
294.138
293.771
293.378
292.903
292.391
291.781
291.26
290.766
290.347
289.942
289.59
289.241
288.925
288.587
288.188
287.898
287.69
287.524
287.373
287.21
320.132
319.75
319.282
318.818
318.381
317.986
317.624
317.29
316.965
316.631
316.284
315.911
315.514
315.084
314.63
314.156
313.705
313.282
312.894
312.535
312.203
311.891
311.594
311.297
310.986
310.658
310.303
309.922
309.507
309.066
308.605
308.164
307.749
307.368
307.014
306.686
306.377
306.081
305.786
305.476
305.149
304.795
304.414
303.999
303.558
303.097
302.656
302.241
301.859
301.504
301.176
300.865
300.569
300.272
299.961
299.631
299.274
298.891
298.472
298.027
297.562
297.116
296.696
296.31
295.95
295.617
295.301
294.998
294.695
294.375
294.035
293.665
293.265
292.826
292.357
291.862
291.387
290.935
290.517
290.124
289.758
289.407
289.073
288.741
288.413
288.125
287.88
287.664
287.461
287.258
319.849
319.504
319.116
318.716
318.322
317.944
317.582
317.234
316.89
316.542
316.183
315.81
315.42
315.012
314.591
314.163
313.743
313.34
312.956
312.592
312.246
311.914
311.589
311.265
310.934
310.59
310.23
309.851
309.454
309.042
308.623
308.211
307.814
307.436
307.076
306.733
306.403
306.079
305.756
305.426
305.083
304.723
304.345
303.947
303.535
303.116
302.704
302.306
301.927
301.566
301.222
300.891
300.566
300.242
299.91
299.564
299.202
298.821
298.421
298.005
297.582
297.166
296.764
296.381
296.016
295.667
295.331
295.001
294.67
294.33
293.976
293.603
293.209
292.792
292.359
291.916
291.479
291.056
290.652
290.268
289.902
289.552
289.215
288.891
288.579
288.291
288.028
287.784
287.552
287.323
319.641
319.317
318.968
318.606
318.24
317.878
317.522
317.171
316.82
316.466
316.105
315.734
315.352
314.96
314.56
314.157
313.758
313.368
312.99
312.625
312.27
311.925
311.584
311.243
310.898
310.546
310.183
309.808
309.422
309.028
308.631
308.237
307.852
307.477
307.114
306.762
306.418
306.078
305.738
305.393
305.041
304.678
304.303
303.917
303.523
303.125
302.731
302.344
301.969
301.605
301.251
300.906
300.564
300.223
299.877
299.523
299.157
298.78
298.391
297.994
297.593
297.195
296.805
296.426
296.058
295.701
295.351
295.005
294.659
294.306
293.945
293.571
293.184
292.784
292.375
291.961
291.55
291.149
290.759
290.384
290.023
289.676
289.342
289.02
288.713
288.422
288.147
287.886
287.636
287.391
319.477
319.167
318.84
318.5
318.153
317.804
317.455
317.106
316.755
316.401
316.041
315.674
315.299
314.919
314.533
314.146
313.76
313.38
313.007
312.641
312.282
311.928
311.578
311.228
310.875
310.517
310.152
309.781
309.402
309.02
308.635
308.252
307.873
307.502
307.137
306.779
306.426
306.076
305.726
305.373
305.014
304.65
304.277
303.899
303.515
303.129
302.746
302.366
301.994
301.628
301.269
300.915
300.563
300.211
299.856
299.496
299.129
298.755
298.374
297.988
297.599
297.213
296.831
296.455
296.086
295.724
295.366
295.011
294.655
294.296
293.93
293.558
293.177
292.789
292.396
292.002
291.609
291.223
290.846
290.48
290.125
289.782
289.45
289.13
288.823
288.528
288.246
287.975
287.712
287.456
319.344
319.044
318.729
318.403
318.07
317.731
317.389
317.044
316.696
316.343
315.986
315.624
315.256
314.884
314.508
314.131
313.755
313.382
313.012
312.647
312.286
311.928
311.572
311.216
310.858
310.497
310.132
309.763
309.389
309.013
308.636
308.259
307.886
307.516
307.151
306.789
306.431
306.074
305.718
305.359
304.998
304.632
304.261
303.887
303.51
303.132
302.754
302.379
302.008
301.642
301.279
300.92
300.562
300.203
299.843
299.48
299.112
298.74
298.364
297.984
297.604
297.224
296.847
296.474
296.105
295.74
295.378
295.017
294.656
294.293
293.927
293.556
293.181
292.802
292.421
292.039
291.66
291.285
290.918
290.559
290.21
289.87
289.541
289.222
288.914
288.616
288.329
288.051
287.78
287.516
319.235
318.941
318.634
318.318
317.993
317.662
317.326
316.986
316.642
316.293
315.94
315.582
315.22
314.854
314.486
314.116
313.746
313.378
313.011
312.647
312.285
311.925
311.566
311.207
310.846
310.484
310.119
309.751
309.381
309.008
308.636
308.263
307.892
307.524
307.158
306.795
306.433
306.073
305.712
305.351
304.987
304.62
304.251
303.88
303.506
303.132
302.759
302.387
302.017
301.65
301.285
300.923
300.561
300.199
299.835
299.47
299.102
298.731
298.358
297.983
297.607
297.231
296.858
296.486
296.118
295.751
295.387
295.024
294.66
294.296
293.93
293.561
293.191
292.818
292.445
292.073
291.703
291.337
290.978
290.625
290.281
289.944
289.617
289.299
288.99
288.69
288.399
288.116
287.839
287.569
319.146
318.855
318.554
318.244
317.926
317.601
317.27
316.934
316.594
316.249
315.9
315.546
315.189
314.828
314.465
314.101
313.736
313.371
313.007
312.644
312.282
311.921
311.56
311.199
310.838
310.474
310.109
309.743
309.374
309.005
308.635
308.265
307.896
307.528
307.162
306.798
306.434
306.071
305.709
305.345
304.98
304.613
304.245
303.875
303.504
303.133
302.761
302.391
302.022
301.655
301.289
300.924
300.56
300.195
299.83
299.464
299.096
298.726
298.354
297.982
297.609
297.237
296.865
296.495
296.127
295.76
295.395
295.03
294.666
294.302
293.936
293.57
293.203
292.835
292.468
292.103
291.74
291.381
291.027
290.68
290.339
290.006
289.68
289.363
289.053
288.752
288.458
288.171
287.89
287.615
319.072
318.785
318.487
318.182
317.868
317.548
317.222
316.89
316.553
316.211
315.866
315.516
315.162
314.806
314.447
314.087
313.725
313.363
313.001
312.639
312.278
311.916
311.555
311.193
310.831
310.467
310.102
309.737
309.369
309.002
308.633
308.265
307.897
307.53
307.164
306.799
306.435
306.07
305.706
305.341
304.975
304.608
304.241
303.872
303.502
303.132
302.763
302.393
302.025
301.657
301.291
300.925
300.559
300.193
299.827
299.46
299.092
298.723
298.353
297.982
297.611
297.241
296.871
296.502
296.134
295.767
295.402
295.037
294.672
294.308
293.944
293.58
293.215
292.852
292.489
292.129
291.771
291.417
291.068
290.724
290.387
290.056
289.732
289.415
289.105
288.802
288.506
288.217
287.933
287.655
319.013
318.728
318.433
318.131
317.821
317.504
317.181
316.852
316.518
316.18
315.837
315.49
315.14
314.787
314.431
314.074
313.715
313.355
312.995
312.634
312.273
311.912
311.55
311.188
310.825
310.462
310.097
309.732
309.366
308.999
308.632
308.265
307.898
307.531
307.165
306.8
306.434
306.069
305.704
305.338
304.972
304.605
304.238
303.87
303.501
303.132
302.763
302.395
302.027
301.659
301.292
300.925
300.559
300.192
299.825
299.458
299.09
298.721
298.352
297.982
297.613
297.243
296.875
296.506
296.139
295.773
295.407
295.043
294.678
294.315
293.952
293.589
293.227
292.866
292.507
292.151
291.797
291.447
291.101
290.76
290.425
290.096
289.773
289.456
289.146
288.843
288.545
288.254
287.968
287.688
318.967
318.683
318.39
318.09
317.783
317.468
317.148
316.822
316.491
316.155
315.815
315.47
315.123
314.772
314.419
314.063
313.706
313.348
312.989
312.629
312.269
311.908
311.546
311.184
310.821
310.458
310.094
309.729
309.363
308.997
308.631
308.264
307.898
307.532
307.166
306.8
306.434
306.068
305.703
305.337
304.97
304.603
304.236
303.868
303.5
303.132
302.763
302.395
302.027
301.66
301.292
300.925
300.558
300.191
299.824
299.456
299.089
298.72
298.352
297.983
297.614
297.246
296.877
296.51
296.143
295.777
295.412
295.047
294.684
294.321
293.959
293.597
293.237
292.879
292.522
292.168
291.817
291.47
291.127
290.788
290.455
290.127
289.805
289.489
289.178
288.874
288.576
288.283
287.996
287.713
318.934
318.65
318.359
318.06
317.754
317.442
317.124
316.799
316.47
316.136
315.797
315.455
315.109
314.76
314.409
314.055
313.699
313.342
312.984
312.625
312.265
311.904
311.543
311.181
310.818
310.455
310.091
309.727
309.361
308.996
308.63
308.264
307.898
307.532
307.166
306.8
306.434
306.068
305.702
305.335
304.969
304.602
304.235
303.867
303.499
303.131
302.763
302.396
302.028
301.66
301.293
300.925
300.558
300.191
299.823
299.456
299.088
298.72
298.352
297.983
297.615
297.247
296.88
296.512
296.146
295.78
295.415
295.051
294.688
294.326
293.964
293.604
293.246
292.889
292.534
292.182
291.833
291.487
291.146
290.809
290.476
290.15
289.828
289.512
289.202
288.898
288.599
288.305
288.016
287.733
318.912
318.629
318.338
318.04
317.736
317.425
317.107
316.784
316.456
316.123
315.786
315.445
315.1
314.752
314.402
314.049
313.695
313.338
312.981
312.622
312.263
311.902
311.541
311.179
310.817
310.453
310.089
309.725
309.36
308.995
308.629
308.263
307.897
307.531
307.165
306.799
306.433
306.067
305.701
305.335
304.968
304.601
304.234
303.867
303.499
303.131
302.763
302.396
302.028
301.66
301.293
300.925
300.558
300.191
299.823
299.455
299.088
298.72
298.352
297.984
297.616
297.248
296.881
296.514
296.148
295.783
295.418
295.054
294.691
294.329
293.968
293.609
293.251
292.895
292.542
292.191
291.843
291.498
291.158
290.822
290.491
290.164
289.843
289.528
289.218
288.913
288.613
288.319
288.03
287.746
318.901
318.618
318.328
318.031
317.726
317.416
317.099
316.777
316.449
316.117
315.78
315.44
315.096
314.749
314.399
314.046
313.692
313.336
312.979
312.621
312.261
311.901
311.54
311.178
310.816
310.452
310.089
309.724
309.36
308.994
308.629
308.263
307.897
307.531
307.165
306.799
306.433
306.067
305.701
305.334
304.968
304.601
304.234
303.866
303.499
303.131
302.763
302.396
302.028
301.66
301.293
300.925
300.558
300.19
299.823
299.455
299.087
298.72
298.352
297.984
297.616
297.249
296.882
296.515
296.149
295.784
295.419
295.055
294.693
294.331
293.97
293.611
293.254
292.898
292.545
292.195
291.848
291.504
291.164
290.829
290.498
290.172
289.851
289.535
289.225
288.92
288.621
288.326
288.037
287.752
287
286.707
286.402
286.098
285.801
285.511
285.228
284.951
284.681
284.415
284.152
283.893
283.636
283.381
283.127
286.993
286.719
286.43
286.136
285.843
285.554
285.27
284.991
284.716
284.445
284.178
283.913
283.651
283.39
283.13
287.023
286.748
286.462
286.172
285.881
285.592
285.307
285.025
284.747
284.472
284.201
283.931
283.664
283.398
283.132
287.07
286.787
286.499
286.208
285.917
285.628
285.34
285.056
284.775
284.497
284.221
283.947
283.675
283.405
283.135
287.124
286.832
286.539
286.245
285.952
285.66
285.371
285.084
284.8
284.518
284.239
283.962
283.686
283.411
283.137
287.178
286.878
286.579
286.281
285.985
285.691
285.399
285.109
284.822
284.538
284.255
283.974
283.695
283.416
283.139
287.23
286.922
286.617
286.316
286.016
285.719
285.425
285.132
284.843
284.555
284.269
283.986
283.703
283.421
283.14
287.277
286.963
286.654
286.348
286.045
285.745
285.448
285.153
284.861
284.57
284.282
283.995
283.71
283.426
283.142
287.318
287
286.686
286.377
286.071
285.768
285.468
285.171
284.876
284.584
284.293
284.004
283.716
283.429
283.143
287.354
287.032
286.715
286.402
286.094
285.788
285.486
285.187
284.89
284.595
284.303
284.012
283.722
283.433
283.144
287.384
287.059
286.739
286.424
286.113
285.805
285.501
285.2
284.902
284.605
284.311
284.018
283.726
283.435
283.145
287.408
287.08
286.758
286.441
286.128
285.819
285.514
285.211
284.911
284.613
284.317
284.023
283.73
283.437
283.146
287.426
287.097
286.773
286.455
286.14
285.83
285.523
285.219
284.918
284.619
284.322
284.026
283.732
283.439
283.146
287.438
287.108
286.783
286.463
286.148
285.837
285.529
285.224
284.922
284.623
284.325
284.029
283.734
283.44
283.147
287.444
287.113
286.788
286.468
286.152
285.84
285.532
285.227
284.925
284.625
284.327
284.03
283.735
283.441
283.147
)
;
boundaryField
{
hot
{
type fixedValue;
value uniform 323;
}
cold
{
type fixedValue;
value uniform 283;
}
interface_left
{
type fixedValue;
value nonuniform List<scalar>
90
(
319.214
319.214
320.712
320.712
321.135
321.135
321.343
321.343
321.343
321.488
321.488
321.649
321.649
321.826
321.826
322.138
322.138
322.259
322.259
322.334
322.334
322.378
322.378
322.378
322.413
322.413
322.453
322.453
322.498
322.498
322.58
322.58
322.612
322.612
322.631
322.631
322.643
322.643
322.643
322.652
322.652
322.661
322.661
322.672
322.672
322.688
322.688
322.693
322.693
322.694
322.694
322.694
322.694
322.694
322.692
322.692
322.687
322.687
322.677
322.677
322.646
322.646
322.628
322.628
322.61
322.61
322.594
322.594
322.594
322.573
322.573
322.535
322.535
322.473
322.473
322.31
322.31
322.216
322.216
322.13
322.13
322.052
322.052
322.052
321.894
321.894
321.894
321.894
321.894
321.894
)
;
}
interface_right
{
type fixedValue;
value nonuniform List<scalar>
90
(
290.61
290.61
287.013
287.013
286.144
286.144
285.74
285.74
285.74
285.47
285.47
285.176
285.176
284.855
284.855
284.299
284.299
284.085
284.085
283.956
283.956
283.879
283.879
283.879
283.821
283.821
283.754
283.754
283.679
283.679
283.55
283.55
283.502
283.502
283.474
283.474
283.459
283.459
283.459
283.449
283.449
283.441
283.441
283.437
283.437
283.441
283.441
283.449
283.449
283.46
283.46
283.471
283.471
283.471
283.488
283.488
283.519
283.519
283.57
283.57
283.704
283.704
283.781
283.781
283.848
283.848
283.908
283.908
283.908
283.985
283.985
284.116
284.116
284.336
284.336
284.914
284.914
285.259
285.259
285.595
285.595
285.954
285.954
285.954
287.282
287.282
287.282
287.282
287.282
287.282
)
;
}
interface_top
{
type fixedValue;
value nonuniform List<scalar>
90
(
321.894
321.894
318.875
318.875
317.919
317.919
317.361
317.361
317.361
316.867
316.867
316.21
316.21
315.337
315.337
313.511
313.511
312.661
312.661
312.043
312.043
311.602
311.602
311.602
311.163
311.163
310.555
310.555
309.725
309.725
307.96
307.96
307.13
307.13
306.522
306.522
306.086
306.086
306.086
305.65
305.65
305.044
305.044
304.216
304.216
302.452
302.452
301.622
301.622
301.013
301.013
300.575
300.575
300.575
300.137
300.137
299.527
299.527
298.692
298.692
296.908
296.908
296.066
296.066
295.447
295.447
295
295
295
294.548
294.548
293.911
293.911
293.028
293.028
291.101
291.101
290.156
290.156
289.415
289.415
288.798
288.798
288.798
287.282
287.282
287.282
287.282
287.282
287.282
)
;
}
interface_bottom
{
type fixedValue;
value nonuniform List<scalar>
90
(
319.214
319.214
317.403
317.403
316.68
316.68
316.22
316.22
316.22
315.789
315.789
315.204
315.204
314.418
314.418
312.766
312.766
311.996
311.996
311.435
311.435
311.034
311.034
311.034
310.634
310.634
310.08
310.08
309.324
309.324
307.722
307.722
306.972
306.972
306.423
306.423
306.029
306.029
306.029
305.635
305.635
305.088
305.088
304.341
304.341
302.755
302.755
302.011
302.011
301.467
301.467
301.075
301.075
301.075
300.684
300.684
300.139
300.139
299.395
299.395
297.816
297.816
297.075
297.075
296.533
296.533
296.143
296.143
296.143
295.753
295.753
295.211
295.211
294.47
294.47
292.898
292.898
292.158
292.158
291.612
291.612
291.21
291.21
291.21
290.61
290.61
290.61
290.61
290.61
290.61
)
;
}
defaultFaces
{
type empty;
}
}
// ************************************************************************* //
| [
"sarthakgarg1993@gmail.com"
] | sarthakgarg1993@gmail.com | |
a138a7e070d15e64e80c0b8c698b24d8eb544d56 | c58b550ef1cfc2ae395c31565be56c71580fc346 | /meta/client/k2_client.h | 41d28f848c9ad5b41dfba7e5cfa21907be9690fd | [] | no_license | BorgesLu/skv-nebula | e9b037a940ff09298c62f17f5bfcdc63c1b0f7ac | 09b4534933b96ac9450080fc2aaab7e34d606ed4 | refs/heads/main | 2023-08-27T01:35:54.975019 | 2021-11-12T08:26:05 | 2021-11-12T08:26:05 | 427,279,125 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 971 | h | #pragma once
#include "k2_includes.h"
namespace k2pg {
namespace gate {
class PGK2Client {
public:
PGK2Client();
~PGK2Client();
// required for seastar::distributed interface
seastar::future<> gracefulStop();
seastar::future<> start();
private:
bool _stop = false;
k2::K23SIClient *_client;
seastar::future<> _poller = seastar::make_ready_future();
std::unordered_map<k2::dto::K23SI_MTR, k2::K2TxnHandle>* _txns;
seastar::future<> _pollForWork();
seastar::future<> _pollBeginQ();
seastar::future<> _pollEndQ();
seastar::future<> _pollSchemaGetQ();
seastar::future<> _pollSchemaCreateQ();
seastar::future<> _pollReadQ();
// seastar::future<> _pollCreateScanReadQ();
// seastar::future<> _pollScanReadQ();
//seastar::future<> _pollWriteQ();
// seastar::future<> _pollUpdateQ();
seastar::future<> _pollCreateCollectionQ();
// seastar::future<> _pollDropCollectionQ();
};
}//gate
}//k2pg | [
"noreply@github.com"
] | noreply@github.com |
6f777d1bc068e72e1e69c7699a47e29f00c8e4ed | ba96d7f21540bd7504e61954f01a6d77f88dea6f | /build/Android/Preview/app/src/main/jni/_root.fa_certificate.cpp | 531552de3ad09fa060776dda93950a268a9bf1d5 | [] | no_license | GetSomefi/haslaamispaivakirja | 096ff35fe55e3155293e0030c91b4bbeafd512c7 | 9ba6766987da4af3b662e33835231b5b88a452b3 | refs/heads/master | 2020-03-21T19:54:24.148074 | 2018-11-09T06:44:18 | 2018-11-09T06:44:18 | 138,976,977 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,429 | cpp | // This file was generated based on '/Users/petervirtanen/OneDrive/Fuse projektit/Häsläämispäiväkirja/build/Android/Preview/cache/ux15/fa_certificate.g.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#include <_root.fa_certificate.h>
#include <_root.MainView.h>
#include <Fuse.Controls.TextControl.h>
#include <Fuse.Font.h>
#include <Uno.Int.h>
static uString* STRINGS[2];
namespace g{
// public partial sealed class fa_certificate :2
// {
// static fa_certificate() :4
static void fa_certificate__cctor_4_fn(uType* __type)
{
}
static void fa_certificate_build(uType* type)
{
::STRINGS[0] = uString::Const("\357\202\243");
::STRINGS[1] = uString::Const("Components/fa_icons.ux");
type->SetDependencies(
::g::MainView_typeof());
type->SetInterfaces(
::g::Uno::Collections::IList_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL), offsetof(::g::Fuse::Controls::TextControl_type, interface0),
::g::Fuse::Scripting::IScriptObject_typeof(), offsetof(::g::Fuse::Controls::TextControl_type, interface1),
::g::Fuse::IProperties_typeof(), offsetof(::g::Fuse::Controls::TextControl_type, interface2),
::g::Fuse::INotifyUnrooted_typeof(), offsetof(::g::Fuse::Controls::TextControl_type, interface3),
::g::Fuse::ISourceLocation_typeof(), offsetof(::g::Fuse::Controls::TextControl_type, interface4),
::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL), offsetof(::g::Fuse::Controls::TextControl_type, interface5),
::g::Uno::Collections::IEnumerable_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL), offsetof(::g::Fuse::Controls::TextControl_type, interface6),
::g::Uno::Collections::IList_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL), offsetof(::g::Fuse::Controls::TextControl_type, interface7),
::g::Uno::UX::IPropertyListener_typeof(), offsetof(::g::Fuse::Controls::TextControl_type, interface8),
::g::Fuse::ITemplateSource_typeof(), offsetof(::g::Fuse::Controls::TextControl_type, interface9),
::g::Uno::Collections::IEnumerable_typeof()->MakeType(::g::Fuse::Visual_typeof(), NULL), offsetof(::g::Fuse::Controls::TextControl_type, interface10),
::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL), offsetof(::g::Fuse::Controls::TextControl_type, interface11),
::g::Uno::Collections::IEnumerable_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL), offsetof(::g::Fuse::Controls::TextControl_type, interface12),
::g::Fuse::Triggers::Actions::IShow_typeof(), offsetof(::g::Fuse::Controls::TextControl_type, interface13),
::g::Fuse::Triggers::Actions::IHide_typeof(), offsetof(::g::Fuse::Controls::TextControl_type, interface14),
::g::Fuse::Triggers::Actions::ICollapse_typeof(), offsetof(::g::Fuse::Controls::TextControl_type, interface15),
::g::Fuse::IActualPlacement_typeof(), offsetof(::g::Fuse::Controls::TextControl_type, interface16),
::g::Fuse::Animations::IResize_typeof(), offsetof(::g::Fuse::Controls::TextControl_type, interface17),
::g::Fuse::Triggers::IValue_typeof()->MakeType(::g::Uno::String_typeof(), NULL), offsetof(::g::Fuse::Controls::TextControl_type, interface18));
type->SetFields(121);
type->Reflection.SetFunctions(1,
new uFunction(".ctor", NULL, (void*)fa_certificate__New4_fn, 0, true, type, 0));
}
::g::Fuse::Controls::TextControl_type* fa_certificate_typeof()
{
static uSStrong< ::g::Fuse::Controls::TextControl_type*> type;
if (type != NULL) return type;
uTypeOptions options;
options.BaseDefinition = ::g::Fuse::Controls::Text_typeof();
options.FieldCount = 121;
options.InterfaceCount = 19;
options.DependencyCount = 1;
options.ObjectSize = sizeof(fa_certificate);
options.TypeSize = sizeof(::g::Fuse::Controls::TextControl_type);
type = (::g::Fuse::Controls::TextControl_type*)uClassType::New("fa_certificate", options);
type->fp_build_ = fa_certificate_build;
type->fp_ctor_ = (void*)fa_certificate__New4_fn;
type->fp_cctor_ = fa_certificate__cctor_4_fn;
type->interface18.fp_get_Value = (void(*)(uObject*, uTRef))::g::Fuse::Controls::TextControl__get_Value_fn;
type->interface18.fp_set_Value = (void(*)(uObject*, void*))::g::Fuse::Controls::TextControl__set_Value_fn;
type->interface18.fp_add_ValueChanged = (void(*)(uObject*, uDelegate*))::g::Fuse::Controls::TextControl__add_ValueChanged_fn;
type->interface18.fp_remove_ValueChanged = (void(*)(uObject*, uDelegate*))::g::Fuse::Controls::TextControl__remove_ValueChanged_fn;
type->interface13.fp_Show = (void(*)(uObject*))::g::Fuse::Elements::Element__FuseTriggersActionsIShowShow_fn;
type->interface15.fp_Collapse = (void(*)(uObject*))::g::Fuse::Elements::Element__FuseTriggersActionsICollapseCollapse_fn;
type->interface14.fp_Hide = (void(*)(uObject*))::g::Fuse::Elements::Element__FuseTriggersActionsIHideHide_fn;
type->interface17.fp_SetSize = (void(*)(uObject*, ::g::Uno::Float2*))::g::Fuse::Elements::Element__FuseAnimationsIResizeSetSize_fn;
type->interface16.fp_get_ActualSize = (void(*)(uObject*, ::g::Uno::Float3*))::g::Fuse::Elements::Element__FuseIActualPlacementget_ActualSize_fn;
type->interface16.fp_get_ActualPosition = (void(*)(uObject*, ::g::Uno::Float3*))::g::Fuse::Elements::Element__FuseIActualPlacementget_ActualPosition_fn;
type->interface16.fp_add_Placed = (void(*)(uObject*, uDelegate*))::g::Fuse::Elements::Element__add_Placed_fn;
type->interface16.fp_remove_Placed = (void(*)(uObject*, uDelegate*))::g::Fuse::Elements::Element__remove_Placed_fn;
type->interface10.fp_GetEnumerator = (void(*)(uObject*, uObject**))::g::Fuse::Visual__UnoCollectionsIEnumerableFuseVisualGetEnumerator_fn;
type->interface11.fp_Clear = (void(*)(uObject*))::g::Fuse::Visual__UnoCollectionsICollectionFuseNodeClear_fn;
type->interface11.fp_Contains = (void(*)(uObject*, void*, bool*))::g::Fuse::Visual__UnoCollectionsICollectionFuseNodeContains_fn;
type->interface7.fp_RemoveAt = (void(*)(uObject*, int32_t*))::g::Fuse::Visual__UnoCollectionsIListFuseNodeRemoveAt_fn;
type->interface12.fp_GetEnumerator = (void(*)(uObject*, uObject**))::g::Fuse::Visual__UnoCollectionsIEnumerableFuseNodeGetEnumerator_fn;
type->interface11.fp_get_Count = (void(*)(uObject*, int32_t*))::g::Fuse::Visual__UnoCollectionsICollectionFuseNodeget_Count_fn;
type->interface7.fp_get_Item = (void(*)(uObject*, int32_t*, uTRef))::g::Fuse::Visual__UnoCollectionsIListFuseNodeget_Item_fn;
type->interface7.fp_Insert = (void(*)(uObject*, int32_t*, void*))::g::Fuse::Visual__Insert1_fn;
type->interface8.fp_OnPropertyChanged = (void(*)(uObject*, ::g::Uno::UX::PropertyObject*, ::g::Uno::UX::Selector*))::g::Fuse::Controls::Control__OnPropertyChanged2_fn;
type->interface9.fp_FindTemplate = (void(*)(uObject*, uString*, ::g::Uno::UX::Template**))::g::Fuse::Visual__FindTemplate_fn;
type->interface11.fp_Add = (void(*)(uObject*, void*))::g::Fuse::Visual__Add1_fn;
type->interface11.fp_Remove = (void(*)(uObject*, void*, bool*))::g::Fuse::Visual__Remove1_fn;
type->interface5.fp_Clear = (void(*)(uObject*))::g::Fuse::Node__UnoCollectionsICollectionFuseBindingClear_fn;
type->interface5.fp_Contains = (void(*)(uObject*, void*, bool*))::g::Fuse::Node__UnoCollectionsICollectionFuseBindingContains_fn;
type->interface0.fp_RemoveAt = (void(*)(uObject*, int32_t*))::g::Fuse::Node__UnoCollectionsIListFuseBindingRemoveAt_fn;
type->interface6.fp_GetEnumerator = (void(*)(uObject*, uObject**))::g::Fuse::Node__UnoCollectionsIEnumerableFuseBindingGetEnumerator_fn;
type->interface1.fp_SetScriptObject = (void(*)(uObject*, uObject*, ::g::Fuse::Scripting::Context*))::g::Fuse::Node__FuseScriptingIScriptObjectSetScriptObject_fn;
type->interface5.fp_get_Count = (void(*)(uObject*, int32_t*))::g::Fuse::Node__UnoCollectionsICollectionFuseBindingget_Count_fn;
type->interface0.fp_get_Item = (void(*)(uObject*, int32_t*, uTRef))::g::Fuse::Node__UnoCollectionsIListFuseBindingget_Item_fn;
type->interface1.fp_get_ScriptObject = (void(*)(uObject*, uObject**))::g::Fuse::Node__FuseScriptingIScriptObjectget_ScriptObject_fn;
type->interface1.fp_get_ScriptContext = (void(*)(uObject*, ::g::Fuse::Scripting::Context**))::g::Fuse::Node__FuseScriptingIScriptObjectget_ScriptContext_fn;
type->interface4.fp_get_SourceNearest = (void(*)(uObject*, uObject**))::g::Fuse::Node__FuseISourceLocationget_SourceNearest_fn;
type->interface3.fp_add_Unrooted = (void(*)(uObject*, uDelegate*))::g::Fuse::Node__FuseINotifyUnrootedadd_Unrooted_fn;
type->interface3.fp_remove_Unrooted = (void(*)(uObject*, uDelegate*))::g::Fuse::Node__FuseINotifyUnrootedremove_Unrooted_fn;
type->interface0.fp_Insert = (void(*)(uObject*, int32_t*, void*))::g::Fuse::Node__Insert_fn;
type->interface2.fp_get_Properties = (void(*)(uObject*, ::g::Fuse::Properties**))::g::Fuse::Node__get_Properties_fn;
type->interface4.fp_get_SourceLineNumber = (void(*)(uObject*, int32_t*))::g::Fuse::Node__get_SourceLineNumber_fn;
type->interface4.fp_get_SourceFileName = (void(*)(uObject*, uString**))::g::Fuse::Node__get_SourceFileName_fn;
type->interface5.fp_Add = (void(*)(uObject*, void*))::g::Fuse::Node__Add_fn;
type->interface5.fp_Remove = (void(*)(uObject*, void*, bool*))::g::Fuse::Node__Remove_fn;
return type;
}
// public fa_certificate() :8
void fa_certificate__ctor_8_fn(fa_certificate* __this)
{
__this->ctor_8();
}
// private void InitializeUX() :12
void fa_certificate__InitializeUX1_fn(fa_certificate* __this)
{
__this->InitializeUX1();
}
// public fa_certificate New() :8
void fa_certificate__New4_fn(fa_certificate** __retval)
{
*__retval = fa_certificate::New4();
}
// public fa_certificate() [instance] :8
void fa_certificate::ctor_8()
{
ctor_7();
InitializeUX1();
}
// private void InitializeUX() [instance] :12
void fa_certificate::InitializeUX1()
{
uStackFrame __("fa_certificate", "InitializeUX()");
Value(::STRINGS[0/*"\uF0A3"*/]);
SourceLineNumber(124);
SourceFileName(::STRINGS[1/*"Components/...*/]);
Font(::g::MainView::fa());
}
// public fa_certificate New() [static] :8
fa_certificate* fa_certificate::New4()
{
fa_certificate* obj1 = (fa_certificate*)uNew(fa_certificate_typeof());
obj1->ctor_8();
return obj1;
}
// }
} // ::g
| [
"peyte.com@gmail.com"
] | peyte.com@gmail.com |
f0ba07b1c15e53a08153fe70887666157793ba9c | 220b67122f354591f7d9dc5ad89a9bd4450547c7 | /raygame/BooleanDecision.cpp | 46336eb9e9ae2437ab9c6d73056e107630ed9cb6 | [
"MIT"
] | permissive | KyraWooders/AIAgents | d8fa989d591d73b7615a625cd82ca945c258f7da | cb17aadda9ea7b9bca69a39cfa761a5402bc4a39 | refs/heads/master | 2021-04-18T01:05:55.054602 | 2020-04-03T13:28:21 | 2020-04-03T13:28:21 | 249,492,117 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 212 | cpp | #include "BooleanDecision.h"
void BooleanDecision::makeDecision(Agent * agent, float deltaTime)
{
if (testCondition(agent))
m_a->makeDecision(agent, deltaTime);
else
m_b->makeDecision(agent, deltaTime);
}
| [
"wooderskyra@gmail.com"
] | wooderskyra@gmail.com |
bf95371d7b0d01b6936f17f8f817f6d8f9738c7a | 06cb3c6ecfeca7cc8f9c1b5be1e8d3ee86829dc9 | /3rd-party/leveldb/leveldb-rocksdb-3.7/table/plain_table_index.h | 0b26ecd0d0e6fa45e659c3f353c074f488d65cfd | [
"BSD-3-Clause",
"MIT"
] | permissive | melancthon/node-kv | aeaa2823e8b84c1cdae9e7e81793f3b20d27c45a | b654347a8abc5f805517332ad17e415499b37c74 | refs/heads/rocksdb | 2021-01-11T04:40:18.266684 | 2019-07-24T15:07:42 | 2019-07-24T15:07:42 | 71,142,488 | 2 | 0 | null | 2016-10-17T13:38:55 | 2016-10-17T13:38:54 | null | UTF-8 | C++ | false | false | 7,181 | h | // Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#pragma once
#include <string>
#include <vector>
#include "db/dbformat.h"
#include "rocksdb/options.h"
#include "util/murmurhash.h"
#include "util/hash.h"
#include "util/arena.h"
#include "util/histogram.h"
namespace rocksdb {
// PlainTableIndex contains buckets size of index_size_, each is a
// 32-bit integer. The lower 31 bits contain an offset value (explained below)
// and the first bit of the integer indicates type of the offset.
//
// +--------------+------------------------------------------------------+
// | Flag (1 bit) | Offset to binary search buffer or file (31 bits) +
// +--------------+------------------------------------------------------+
//
// Explanation for the "flag bit":
//
// 0 indicates that the bucket contains only one prefix (no conflict when
// hashing this prefix), whose first row starts from this offset of the
// file.
// 1 indicates that the bucket contains more than one prefixes, or there
// are too many rows for one prefix so we need a binary search for it. In
// this case, the offset indicates the offset of sub_index_ holding the
// binary search indexes of keys for those rows. Those binary search indexes
// are organized in this way:
//
// The first 4 bytes, indicate how many indexes (N) are stored after it. After
// it, there are N 32-bit integers, each points of an offset of the file,
// which
// points to starting of a row. Those offsets need to be guaranteed to be in
// ascending order so the keys they are pointing to are also in ascending
// order
// to make sure we can use them to do binary searches. Below is visual
// presentation of a bucket.
//
// <begin>
// number_of_records: varint32
// record 1 file offset: fixedint32
// record 2 file offset: fixedint32
// ....
// record N file offset: fixedint32
// <end>
class PlainTableIndex {
public:
enum IndexSearchResult {
kNoPrefixForBucket = 0,
kDirectToFile = 1,
kSubindex = 2
};
explicit PlainTableIndex(Slice data) { InitFromRawData(data); }
PlainTableIndex()
: index_size_(0),
sub_index_size_(0),
num_prefixes_(0),
index_(nullptr),
sub_index_(nullptr) {}
IndexSearchResult GetOffset(uint32_t prefix_hash,
uint32_t* bucket_value) const;
Status InitFromRawData(Slice data);
const char* GetSubIndexBasePtrAndUpperBound(uint32_t offset,
uint32_t* upper_bound) const {
const char* index_ptr = &sub_index_[offset];
return GetVarint32Ptr(index_ptr, index_ptr + 4, upper_bound);
}
uint32_t GetIndexSize() const { return index_size_; }
uint32_t GetSubIndexSize() const { return sub_index_size_; }
uint32_t GetNumPrefixes() const { return num_prefixes_; }
static const uint64_t kMaxFileSize = (1u << 31) - 1;
static const uint32_t kSubIndexMask = 0x80000000;
static const size_t kOffsetLen = sizeof(uint32_t);
private:
uint32_t index_size_;
size_t sub_index_size_;
uint32_t num_prefixes_;
uint32_t* index_;
char* sub_index_;
};
// PlainTableIndexBuilder is used to create plain table index.
// After calling Finish(), it returns Slice, which is usually
// used either to initialize PlainTableIndex or
// to save index to sst file.
// For more details about the index, please refer to:
// https://github.com/facebook/rocksdb/wiki/PlainTable-Format
// #wiki-in-memory-index-format
class PlainTableIndexBuilder {
public:
PlainTableIndexBuilder(Arena* arena, const ImmutableCFOptions& ioptions,
uint32_t index_sparseness, double hash_table_ratio,
double huge_page_tlb_size)
: arena_(arena),
ioptions_(ioptions),
record_list_(kRecordsPerGroup),
is_first_record_(true),
due_index_(false),
num_prefixes_(0),
num_keys_per_prefix_(0),
prev_key_prefix_hash_(0),
index_sparseness_(index_sparseness),
prefix_extractor_(ioptions.prefix_extractor),
hash_table_ratio_(hash_table_ratio),
huge_page_tlb_size_(huge_page_tlb_size) {}
void AddKeyPrefix(Slice key_prefix_slice, uint64_t key_offset);
Slice Finish();
uint32_t GetTotalSize() const {
return VarintLength(index_size_) + VarintLength(num_prefixes_) +
PlainTableIndex::kOffsetLen * index_size_ + sub_index_size_;
}
static const std::string kPlainTableIndexBlock;
private:
struct IndexRecord {
uint32_t hash; // hash of the prefix
uint32_t offset; // offset of a row
IndexRecord* next;
};
// Helper class to track all the index records
class IndexRecordList {
public:
explicit IndexRecordList(size_t num_records_per_group)
: kNumRecordsPerGroup(num_records_per_group),
current_group_(nullptr),
num_records_in_current_group_(num_records_per_group) {}
~IndexRecordList() {
for (size_t i = 0; i < groups_.size(); i++) {
delete[] groups_[i];
}
}
void AddRecord(murmur_t hash, uint32_t offset);
size_t GetNumRecords() const {
return (groups_.size() - 1) * kNumRecordsPerGroup +
num_records_in_current_group_;
}
IndexRecord* At(size_t index) {
return &(groups_[index / kNumRecordsPerGroup]
[index % kNumRecordsPerGroup]);
}
private:
IndexRecord* AllocateNewGroup() {
IndexRecord* result = new IndexRecord[kNumRecordsPerGroup];
groups_.push_back(result);
return result;
}
// Each group in `groups_` contains fix-sized records (determined by
// kNumRecordsPerGroup). Which can help us minimize the cost if resizing
// occurs.
const size_t kNumRecordsPerGroup;
IndexRecord* current_group_;
// List of arrays allocated
std::vector<IndexRecord*> groups_;
size_t num_records_in_current_group_;
};
void AllocateIndex();
// Internal helper function to bucket index record list to hash buckets.
void BucketizeIndexes(std::vector<IndexRecord*>* hash_to_offsets,
std::vector<uint32_t>* entries_per_bucket);
// Internal helper class to fill the indexes and bloom filters to internal
// data structures.
Slice FillIndexes(const std::vector<IndexRecord*>& hash_to_offsets,
const std::vector<uint32_t>& entries_per_bucket);
Arena* arena_;
const ImmutableCFOptions ioptions_;
HistogramImpl keys_per_prefix_hist_;
IndexRecordList record_list_;
bool is_first_record_;
bool due_index_;
uint32_t num_prefixes_;
uint32_t num_keys_per_prefix_;
uint32_t prev_key_prefix_hash_;
uint32_t index_sparseness_;
uint32_t index_size_;
size_t sub_index_size_;
const SliceTransform* prefix_extractor_;
double hash_table_ratio_;
double huge_page_tlb_size_;
std::string prev_key_prefix_;
static const size_t kRecordsPerGroup = 256;
};
}; // namespace rocksdb
| [
"anlv.tan@tendcloud.com"
] | anlv.tan@tendcloud.com |
13c8aa632742f040408d5d1274dfaae46cbf92c1 | 5574ed33f1fa5cdc3a104e8856d1c90a83354146 | /practice/test.cpp | 74b7f7e17bc04b073f8cd43771716a5bf31cdad5 | [] | no_license | shliu/Random | 11d6fdfa1c9dd785baf8aff1624965587e1508f1 | 47cb5e5e4f33d017922df950b1f31c58abdceff9 | refs/heads/master | 2021-01-25T12:14:01.678736 | 2014-09-23T02:29:08 | 2014-09-23T02:29:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 749 | cpp | // multimap::equal_elements
#include <iostream>
#include <map>
using namespace std;
int main ()
{
multimap<char,int> mymm;
multimap<char,int>::iterator it;
pair<multimap<char,int>::iterator,multimap<char,int>::iterator> ret;
mymm.insert(pair<char,int>('a',10));
mymm.insert(pair<char,int>('b',20));
mymm.insert(pair<char,int>('b',30));
mymm.insert(pair<char,int>('b',40));
mymm.insert(pair<char,int>('c',50));
mymm.insert(pair<char,int>('c',60));
mymm.insert(pair<char,int>('d',60));
cout << "mymm contains:\n";
for (char ch='a'; ch<='d'; ch++)
{
cout << ch << " =>";
ret = mymm.equal_range(ch);
for (it=ret.first; it!=ret.second; ++it)
cout << " " << (*it).second;
cout << endl;
}
return 0;
} | [
"shliu2@uky.edu"
] | shliu2@uky.edu |
382e72b5f35309f3dd1ce2f527f1d85c4b6544a9 | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /external/chromium_org/chrome/browser/apps/web_view_interactive_browsertest.cc | 15a1bba4652133f4a483354e60b65ec7c86a0fc8 | [
"MIT",
"BSD-3-Clause"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 29,272 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "apps/shell_window.h"
#include "apps/shell_window_registry.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/apps/app_browsertest_util.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test_utils.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "ui/base/test/ui_controls.h"
#include "ui/events/keycodes/keyboard_codes.h"
using apps::ShellWindow;
class WebViewInteractiveTest
: public extensions::PlatformAppBrowserTest {
public:
WebViewInteractiveTest()
: corner_(gfx::Point()),
mouse_click_result_(false),
first_click_(true) {}
virtual void SetUp() OVERRIDE {
// We need real contexts, otherwise the embedder doesn't composite, but the
// guest does, and that isn't an expected configuration.
UseRealGLContexts();
extensions::PlatformAppBrowserTest::SetUp();
}
void MoveMouseInsideWindowWithListener(gfx::Point point,
const std::string& message) {
ExtensionTestMessageListener move_listener(message, false);
ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(
gfx::Point(corner_.x() + point.x(), corner_.y() + point.y())));
ASSERT_TRUE(move_listener.WaitUntilSatisfied());
}
void SendMouseClickWithListener(ui_controls::MouseButton button,
const std::string& message) {
ExtensionTestMessageListener listener(message, false);
SendMouseClick(button);
ASSERT_TRUE(listener.WaitUntilSatisfied());
}
void SendMouseClick(ui_controls::MouseButton button) {
SendMouseEvent(button, ui_controls::DOWN);
SendMouseEvent(button, ui_controls::UP);
}
void MoveMouseInsideWindow(const gfx::Point& point) {
ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(
gfx::Point(corner_.x() + point.x(), corner_.y() + point.y())));
}
gfx::NativeWindow GetPlatformAppWindow() {
const apps::ShellWindowRegistry::ShellWindowList& shell_windows =
apps::ShellWindowRegistry::Get(
browser()->profile())->shell_windows();
return (*shell_windows.begin())->GetNativeWindow();
}
void SendKeyPressToPlatformApp(ui::KeyboardCode key) {
ASSERT_EQ(1U, GetShellWindowCount());
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), key, false, false, false, false));
}
void SendCopyKeyPressToPlatformApp() {
ASSERT_EQ(1U, GetShellWindowCount());
#if defined(OS_MACOSX)
// Send Cmd+C on MacOSX.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_C, false, false, false, true));
#else
// Send Ctrl+C on Windows and Linux/ChromeOS.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_C, true, false, false, false));
#endif
}
void SendStartOfLineKeyPressToPlatformApp() {
#if defined(OS_MACOSX)
// Send Cmd+Left on MacOSX.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_LEFT, false, false, false, true));
#else
// Send Ctrl+Left on Windows and Linux/ChromeOS.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_LEFT, true, false, false, false));
#endif
}
void SendBackShortcutToPlatformApp() {
#if defined(OS_MACOSX)
// Send Cmd+[ on MacOSX.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_OEM_4, false, false, false, true));
#else
// Send browser back key on Linux/Windows.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_BROWSER_BACK,
false, false, false, false));
#endif
}
void SendForwardShortcutToPlatformApp() {
#if defined(OS_MACOSX)
// Send Cmd+] on MacOSX.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_OEM_6, false, false, false, true));
#else
// Send browser back key on Linux/Windows.
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_BROWSER_FORWARD,
false, false, false, false));
#endif
}
void SendMouseEvent(ui_controls::MouseButton button,
ui_controls::MouseButtonState state) {
if (first_click_) {
mouse_click_result_ = ui_test_utils::SendMouseEventsSync(button,
state);
first_click_ = false;
} else {
ASSERT_EQ(mouse_click_result_, ui_test_utils::SendMouseEventsSync(
button, state));
}
}
enum TestServer {
NEEDS_TEST_SERVER,
NO_TEST_SERVER
};
scoped_ptr<ExtensionTestMessageListener> RunAppHelper(
const std::string& test_name,
const std::string& app_location,
TestServer test_server,
content::WebContents** embedder_web_contents) {
// For serving guest pages.
if ((test_server == NEEDS_TEST_SERVER) && !StartEmbeddedTestServer()) {
LOG(ERROR) << "FAILED TO START TEST SERVER.";
return scoped_ptr<ExtensionTestMessageListener>();
}
ExtensionTestMessageListener launched_listener("Launched", false);
LoadAndLaunchPlatformApp(app_location.c_str());
if (!launched_listener.WaitUntilSatisfied()) {
LOG(ERROR) << "TEST DID NOT LAUNCH.";
return scoped_ptr<ExtensionTestMessageListener>();
}
if (!ui_test_utils::ShowAndFocusNativeWindow(GetPlatformAppWindow())) {
LOG(ERROR) << "UNABLE TO FOCUS TEST WINDOW.";
return scoped_ptr<ExtensionTestMessageListener>();
}
// Flush any pending events to make sure we start with a clean slate.
content::RunAllPendingInMessageLoop();
*embedder_web_contents = GetFirstShellWindowWebContents();
scoped_ptr<ExtensionTestMessageListener> done_listener(
new ExtensionTestMessageListener("TEST_PASSED", false));
done_listener->AlsoListenForFailureMessage("TEST_FAILED");
if (!content::ExecuteScript(
*embedder_web_contents,
base::StringPrintf("runTest('%s')", test_name.c_str()))) {
LOG(ERROR) << "UNABLE TO START TEST";
return scoped_ptr<ExtensionTestMessageListener>();
}
return done_listener.Pass();
}
void TestHelper(const std::string& test_name,
const std::string& app_location,
TestServer test_server) {
content::WebContents* embedder_web_contents = NULL;
scoped_ptr<ExtensionTestMessageListener> done_listener(
RunAppHelper(
test_name, app_location, test_server, &embedder_web_contents));
ASSERT_TRUE(done_listener);
ASSERT_TRUE(done_listener->WaitUntilSatisfied());
}
void RunTest(const std::string& app_name) {
}
void SetupTest(const std::string& app_name,
const std::string& guest_url_spec) {
ASSERT_TRUE(StartEmbeddedTestServer());
GURL::Replacements replace_host;
std::string host_str("localhost"); // Must stay in scope with replace_host.
replace_host.SetHostStr(host_str);
GURL guest_url = embedded_test_server()->GetURL(guest_url_spec);
guest_url = guest_url.ReplaceComponents(replace_host);
ui_test_utils::UrlLoadObserver guest_observer(
guest_url, content::NotificationService::AllSources());
ExtensionTestMessageListener guest_connected_listener("connected", false);
LoadAndLaunchPlatformApp(app_name.c_str());
guest_observer.Wait();
// Wait until the guest process reports that it has established a message
// channel with the app.
ASSERT_TRUE(guest_connected_listener.WaitUntilSatisfied());
content::Source<content::NavigationController> source =
guest_observer.source();
EXPECT_TRUE(source->GetWebContents()->GetRenderProcessHost()->IsGuest());
guest_web_contents_ = source->GetWebContents();
embedder_web_contents_ = guest_web_contents_->GetEmbedderWebContents();
gfx::Rect offset;
embedder_web_contents_->GetView()->GetContainerBounds(&offset);
corner_ = gfx::Point(offset.x(), offset.y());
const testing::TestInfo* const test_info =
testing::UnitTest::GetInstance()->current_test_info();
const char* prefix = "DragDropWithinWebView";
if (!strncmp(test_info->name(), prefix, strlen(prefix))) {
// In the drag drop test we add 20px padding to the page body because on
// windows if we get too close to the edge of the window the resize cursor
// appears and we start dragging the window edge.
corner_.Offset(20, 20);
}
}
content::WebContents* guest_web_contents() {
return guest_web_contents_;
}
content::WebContents* embedder_web_contents() {
return embedder_web_contents_;
}
gfx::Point corner() {
return corner_;
}
void SimulateRWHMouseClick(content::RenderWidgetHost* rwh, int x, int y) {
blink::WebMouseEvent mouse_event;
mouse_event.button = blink::WebMouseEvent::ButtonLeft;
mouse_event.x = mouse_event.windowX = x;
mouse_event.y = mouse_event.windowY = y;
mouse_event.modifiers = 0;
mouse_event.type = blink::WebInputEvent::MouseDown;
rwh->ForwardMouseEvent(mouse_event);
mouse_event.type = blink::WebInputEvent::MouseUp;
rwh->ForwardMouseEvent(mouse_event);
}
// TODO(lazyboy): implement
class PopupCreatedObserver {
public:
PopupCreatedObserver() : created_(false), last_render_widget_host_(NULL) {
}
virtual ~PopupCreatedObserver() {
}
void Reset() {
created_ = false;
}
void Start() {
if (created_)
return;
message_loop_ = new content::MessageLoopRunner;
message_loop_->Run();
}
content::RenderWidgetHost* last_render_widget_host() {
return last_render_widget_host_;
}
private:
scoped_refptr<content::MessageLoopRunner> message_loop_;
bool created_;
content::RenderWidgetHost* last_render_widget_host_;
};
void WaitForTitle(const char* title) {
base::string16 expected_title(ASCIIToUTF16(title));
base::string16 error_title(ASCIIToUTF16("FAILED"));
content::TitleWatcher title_watcher(guest_web_contents(), expected_title);
title_watcher.AlsoWaitForTitle(error_title);
ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
void PopupTestHelper(const gfx::Point& padding) {
PopupCreatedObserver popup_created_observer;
popup_created_observer.Reset();
content::SimulateKeyPress(
guest_web_contents(),
ui::VKEY_C, // C to autocomplete.
false, false, false, false);
WaitForTitle("PASSED1");
popup_created_observer.Start();
content::RenderWidgetHost* popup_rwh = NULL;
popup_rwh = popup_created_observer.last_render_widget_host();
// Popup must be present.
ASSERT_TRUE(popup_rwh);
ASSERT_TRUE(!popup_rwh->IsRenderView());
ASSERT_TRUE(popup_rwh->GetView());
base::string16 expected_title = ASCIIToUTF16("PASSED2");
base::string16 error_title = ASCIIToUTF16("FAILED");
content::TitleWatcher title_watcher(guest_web_contents(), expected_title);
title_watcher.AlsoWaitForTitle(error_title);
EXPECT_TRUE(content::ExecuteScript(guest_web_contents(),
"changeTitle();"));
ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle());
gfx::Rect popup_bounds = popup_rwh->GetView()->GetViewBounds();
// (2, 2) is expected to lie on the first datalist element.
SimulateRWHMouseClick(popup_rwh, 2, 2);
content::RenderViewHost* embedder_rvh =
GetFirstShellWindowWebContents()->GetRenderViewHost();
gfx::Rect embedder_bounds = embedder_rvh->GetView()->GetViewBounds();
gfx::Vector2d diff = popup_bounds.origin() - embedder_bounds.origin();
LOG(INFO) << "DIFF: x = " << diff.x() << ", y = " << diff.y();
const int left_spacing = 40 + padding.x(); // div.style.paddingLeft = 40px.
// div.style.paddingTop = 50px + (input box height = 26px).
const int top_spacing = 50 + 26 + padding.y();
// If the popup is placed within |threshold_px| of the expected position,
// then we consider the test as a pass.
const int threshold_px = 10;
EXPECT_LE(std::abs(diff.x() - left_spacing), threshold_px);
EXPECT_LE(std::abs(diff.y() - top_spacing), threshold_px);
WaitForTitle("PASSED3");
}
void DragTestStep1() {
// Move mouse to start of text.
MoveMouseInsideWindow(gfx::Point(45, 8));
MoveMouseInsideWindow(gfx::Point(45, 9));
SendMouseEvent(ui_controls::LEFT, ui_controls::DOWN);
MoveMouseInsideWindow(gfx::Point(74, 12));
MoveMouseInsideWindow(gfx::Point(78, 12));
// Now wait a bit before moving mouse to initiate drag/drop.
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&WebViewInteractiveTest::DragTestStep2,
base::Unretained(this)),
base::TimeDelta::FromMilliseconds(200));
}
void DragTestStep2() {
// Drag source over target.
MoveMouseInsideWindow(gfx::Point(76, 76));
// Create a second mouse over the source to trigger the drag over event.
MoveMouseInsideWindow(gfx::Point(76, 77));
// Release mouse to drop.
SendMouseEvent(ui_controls::LEFT, ui_controls::UP);
SendMouseClick(ui_controls::LEFT);
quit_closure_.Run();
// Note that following ExtensionTestMessageListener and ExecuteScript*
// call must be after we quit |quit_closure_|. Otherwise the class
// here won't be able to receive messages sent by chrome.test.sendMessage.
// This is because of the nature of drag and drop code (esp. the
// MessageLoop) in it.
// Now check if we got a drop and read the drop data.
embedder_web_contents_ = GetFirstShellWindowWebContents();
ExtensionTestMessageListener drop_listener("guest-got-drop", false);
EXPECT_TRUE(content::ExecuteScript(embedder_web_contents_,
"window.checkIfGuestGotDrop()"));
EXPECT_TRUE(drop_listener.WaitUntilSatisfied());
std::string last_drop_data;
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
embedder_web_contents_,
"window.domAutomationController.send(getLastDropData())",
&last_drop_data));
last_drop_data_ = last_drop_data;
}
protected:
content::WebContents* guest_web_contents_;
content::WebContents* embedder_web_contents_;
gfx::Point corner_;
bool mouse_click_result_;
bool first_click_;
// Only used in drag/drop test.
base::Closure quit_closure_;
std::string last_drop_data_;
};
// ui_test_utils::SendMouseMoveSync doesn't seem to work on OS_MACOSX, and
// likely won't work on many other platforms as well, so for now this test
// is for Windows and Linux only. As of Sept 17th, 2013 this test is disabled
// on Windows due to flakines, see http://crbug.com/293445.
#if defined(OS_LINUX)
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, PointerLock) {
SetupTest("web_view/pointer_lock",
"/extensions/platform_apps/web_view/pointer_lock/guest.html");
// Move the mouse over the Lock Pointer button.
ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(
gfx::Point(corner().x() + 75, corner().y() + 25)));
// Click the Lock Pointer button. The first two times the button is clicked
// the permission API will deny the request (intentional).
ExtensionTestMessageListener exception_listener("request exception", false);
SendMouseClickWithListener(ui_controls::LEFT, "lock error");
ASSERT_TRUE(exception_listener.WaitUntilSatisfied());
SendMouseClickWithListener(ui_controls::LEFT, "lock error");
// Click the Lock Pointer button, locking the mouse to lockTarget1.
SendMouseClickWithListener(ui_controls::LEFT, "locked");
// Attempt to move the mouse off of the lock target, and onto lockTarget2,
// (which would trigger a test failure).
ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(
gfx::Point(corner().x() + 74, corner().y() + 74)));
MoveMouseInsideWindowWithListener(gfx::Point(75, 75), "mouse-move");
#if (defined(OS_WIN) && defined(USE_AURA))
// When the mouse is unlocked on win aura, sending a test mouse click clicks
// where the mouse moved to while locked. I was unable to figure out why, and
// since the issue only occurs with the test mouse events, just fix it with
// a simple workaround - moving the mouse back to where it should be.
// TODO(mthiesse): Fix Win Aura simulated mouse events while mouse locked.
MoveMouseInsideWindowWithListener(gfx::Point(75, 25), "mouse-move");
#endif
ExtensionTestMessageListener unlocked_listener("unlocked", false);
// Send a key press to unlock the mouse.
SendKeyPressToPlatformApp(ui::VKEY_ESCAPE);
// Wait for page to receive (successful) mouse unlock response.
ASSERT_TRUE(unlocked_listener.WaitUntilSatisfied());
// After the second lock, guest.js sends a message to main.js to remove the
// webview object. main.js then removes the div containing the webview, which
// should unlock, and leave the mouse over the mousemove-capture-container
// div. We then move the mouse over that div to ensure the mouse was properly
// unlocked and that the div receieves the message.
ExtensionTestMessageListener move_captured_listener("move-captured", false);
move_captured_listener.AlsoListenForFailureMessage("timeout");
// Mouse should already be over lock button (since we just unlocked), so send
// click to re-lock the mouse.
SendMouseClickWithListener(ui_controls::LEFT, "deleted");
// A mousemove event is triggered on the mousemove-capture-container element
// when we delete the webview container (since the mouse moves onto the
// element), but just in case, send an explicit mouse movement to be safe.
ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(
gfx::Point(corner().x() + 50, corner().y() + 10)));
// Wait for page to receive second (successful) mouselock response.
bool success = move_captured_listener.WaitUntilSatisfied();
if (!success) {
fprintf(stderr, "TIMEOUT - retrying\n");
// About 1 in 40 tests fail to detect mouse moves at this point (why?).
// Sending a right click seems to fix this (why?).
ExtensionTestMessageListener move_listener2("move-captured", false);
SendMouseClick(ui_controls::RIGHT);
ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(
gfx::Point(corner().x() + 51, corner().y() + 11)));
ASSERT_TRUE(move_listener2.WaitUntilSatisfied());
}
}
#endif // (defined(OS_WIN) || defined(OS_LINUX))
// Tests that setting focus on the <webview> sets focus on the guest.
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, Focus_FocusEvent) {
TestHelper("testFocusEvent", "web_view/focus", NO_TEST_SERVER);
}
// Tests that setting focus on the <webview> sets focus on the guest.
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, Focus_BlurEvent) {
TestHelper("testBlurEvent", "web_view/focus", NO_TEST_SERVER);
}
// Tests that guests receive edit commands and respond appropriately.
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, EditCommands) {
ExtensionTestMessageListener guest_connected_listener("connected", false);
LoadAndLaunchPlatformApp("web_view/edit_commands");
// Wait until the guest process reports that it has established a message
// channel with the app.
ASSERT_TRUE(guest_connected_listener.WaitUntilSatisfied());
ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow(
GetPlatformAppWindow()));
// Flush any pending events to make sure we start with a clean slate.
content::RunAllPendingInMessageLoop();
ExtensionTestMessageListener copy_listener("copy", false);
SendCopyKeyPressToPlatformApp();
// Wait for the guest to receive a 'copy' edit command.
ASSERT_TRUE(copy_listener.WaitUntilSatisfied());
}
// Tests that guests receive edit commands and respond appropriately.
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, EditCommandsNoMenu) {
SetupTest("web_view/edit_commands_no_menu",
"/extensions/platform_apps/web_view/edit_commands_no_menu/"
"guest.html");
ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow(
GetPlatformAppWindow()));
// Flush any pending events to make sure we start with a clean slate.
content::RunAllPendingInMessageLoop();
ExtensionTestMessageListener start_of_line_listener("StartOfLine", false);
SendStartOfLineKeyPressToPlatformApp();
// Wait for the guest to receive a 'copy' edit command.
ASSERT_TRUE(start_of_line_listener.WaitUntilSatisfied());
}
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest,
NewWindow_NewWindowNameTakesPrecedence) {
TestHelper("testNewWindowNameTakesPrecedence",
"web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest,
NewWindow_WebViewNameTakesPrecedence) {
TestHelper("testWebViewNameTakesPrecedence",
"web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, NewWindow_NoName) {
TestHelper("testNoName",
"web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, NewWindow_Redirect) {
TestHelper("testNewWindowRedirect",
"web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, NewWindow_Close) {
TestHelper("testNewWindowClose",
"web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, NewWindow_ExecuteScript) {
TestHelper("testNewWindowExecuteScript",
"web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest,
NewWindow_DeclarativeWebRequest) {
TestHelper("testNewWindowDeclarativeWebRequest",
"web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, NewWindow_WebRequest) {
TestHelper("testNewWindowWebRequest",
"web_view/newwindow",
NEEDS_TEST_SERVER);
}
// A custom elements bug needs to be addressed to enable this test:
// See http://crbug.com/282477 for more information.
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest,
DISABLED_NewWindow_WebRequestCloseWindow) {
TestHelper("testNewWindowWebRequestCloseWindow",
"web_view/newwindow",
NEEDS_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest,
NewWindow_WebRequestRemoveElement) {
TestHelper("testNewWindowWebRequestRemoveElement",
"web_view/newwindow",
NEEDS_TEST_SERVER);
}
// Tests that Ctrl+Click/Cmd+Click on a link fires up the newwindow API.
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, NewWindow_OpenInNewTab) {
content::WebContents* embedder_web_contents = NULL;
ExtensionTestMessageListener loaded_listener("Loaded", false);
scoped_ptr<ExtensionTestMessageListener> done_listener(
RunAppHelper("testNewWindowOpenInNewTab",
"web_view/newwindow",
NEEDS_TEST_SERVER,
&embedder_web_contents));
loaded_listener.WaitUntilSatisfied();
#if defined(OS_MACOSX)
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_RETURN,
false, false, false, true /* cmd */));
#else
ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
GetPlatformAppWindow(), ui::VKEY_RETURN,
true /* ctrl */, false, false, false));
#endif
// Wait for the embedder to receive a 'newwindow' event.
ASSERT_TRUE(done_listener->WaitUntilSatisfied());
}
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, ExecuteCode) {
ASSERT_TRUE(RunPlatformAppTestWithArg(
"platform_apps/web_view/common", "execute_code")) << message_;
}
// This test used the old Autofill UI, which has been removed.
// See crbug.com/259438
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, DISABLED_PopupPositioning) {
SetupTest(
"web_view/popup_positioning",
"/extensions/platform_apps/web_view/popup_positioning/guest.html");
ASSERT_TRUE(guest_web_contents());
PopupTestHelper(gfx::Point());
// moveTo a random location and run the steps again.
EXPECT_TRUE(content::ExecuteScript(embedder_web_contents(),
"window.moveTo(16, 20);"));
PopupTestHelper(gfx::Point());
}
// Tests that moving browser plugin (without resize/UpdateRects) correctly
// repositions popup.
// Started flakily failing after a Blink roll: http://crbug.com/245332
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, DISABLED_PopupPositioningMoved) {
SetupTest(
"web_view/popup_positioning_moved",
"/extensions/platform_apps/web_view/popup_positioning_moved"
"/guest.html");
ASSERT_TRUE(guest_web_contents());
PopupTestHelper(gfx::Point(20, 0));
}
// Drag and drop inside a webview is currently only enabled for linux and mac,
// but the tests don't work on anything except chromeos for now. This is because
// of simulating mouse drag code's dependency on platforms.
#if defined(OS_CHROMEOS)
// This test is flaky. See crbug.com/309032
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, DISABLED_DragDropWithinWebView) {
ExtensionTestMessageListener guest_connected_listener("connected", false);
LoadAndLaunchPlatformApp("web_view/dnd_within_webview");
ASSERT_TRUE(guest_connected_listener.WaitUntilSatisfied());
ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow(GetPlatformAppWindow()));
gfx::Rect offset;
embedder_web_contents_ = GetFirstShellWindowWebContents();
embedder_web_contents_->GetView()->GetContainerBounds(&offset);
corner_ = gfx::Point(offset.x(), offset.y());
// In the drag drop test we add 20px padding to the page body because on
// windows if we get too close to the edge of the window the resize cursor
// appears and we start dragging the window edge.
corner_.Offset(20, 20);
// Flush any pending events to make sure we start with a clean slate.
content::RunAllPendingInMessageLoop();
for (;;) {
base::RunLoop run_loop;
quit_closure_ = run_loop.QuitClosure();
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&WebViewInteractiveTest::DragTestStep1,
base::Unretained(this)));
run_loop.Run();
if (last_drop_data_ == "Drop me")
break;
LOG(INFO) << "Drag was cancelled in interactive_test, restarting drag";
// Reset state for next try.
ExtensionTestMessageListener reset_listener("resetStateReply", false);
EXPECT_TRUE(content::ExecuteScript(embedder_web_contents_,
"window.resetState()"));
ASSERT_TRUE(reset_listener.WaitUntilSatisfied());
}
ASSERT_EQ("Drop me", last_drop_data_);
}
#endif // (defined(OS_CHROMEOS))
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, Navigation) {
TestHelper("testNavigation", "web_view/navigation", NO_TEST_SERVER);
}
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest, Navigation_BackForwardKeys) {
ExtensionTestMessageListener launched_listener("Launched", false);
LoadAndLaunchPlatformApp("web_view/navigation");
ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow(
GetPlatformAppWindow()));
// Flush any pending events to make sure we start with a clean slate.
content::RunAllPendingInMessageLoop();
content::WebContents* embedder_web_contents =
GetFirstShellWindowWebContents();
ASSERT_TRUE(embedder_web_contents);
ExtensionTestMessageListener done_listener(
"TEST_PASSED", false);
done_listener.AlsoListenForFailureMessage("TEST_FAILED");
ExtensionTestMessageListener ready_back_key_listener(
"ReadyForBackKey", false);
ExtensionTestMessageListener ready_forward_key_listener(
"ReadyForForwardKey", false);
EXPECT_TRUE(content::ExecuteScript(
embedder_web_contents,
"runTest('testBackForwardKeys')"));
ASSERT_TRUE(ready_back_key_listener.WaitUntilSatisfied());
SendBackShortcutToPlatformApp();
ASSERT_TRUE(ready_forward_key_listener.WaitUntilSatisfied());
SendForwardShortcutToPlatformApp();
ASSERT_TRUE(done_listener.WaitUntilSatisfied());
}
IN_PROC_BROWSER_TEST_F(WebViewInteractiveTest,
PointerLock_PointerLockLostWithFocus) {
TestHelper("testPointerLockLostWithFocus",
"web_view/pointerlock",
NO_TEST_SERVER);
}
| [
"karun.matharu@gmail.com"
] | karun.matharu@gmail.com |
16bae832a3dbae7000e59e6cfaa0229c75e01de8 | 786d74f7a59c2ded394bc653f559238e35414ef5 | /src/sfu/src/Codecs/VP9.cpp | 148987dae89f62aa162239891ddb81ef4cc47223 | [] | no_license | akumrao/mediaserver | 77f71c46e69cbcef9969bcf70867d140fdd0a806 | 046aad2106a859562cf9b6d56a1e56c589843fc2 | refs/heads/master | 2023-04-16T13:51:12.166666 | 2022-06-27T07:01:48 | 2022-06-27T07:01:48 | 214,117,984 | 15 | 12 | null | null | null | null | UTF-8 | C++ | false | false | 10,617 | cpp | #define MS_CLASS "RTC::Codecs::VP9"
// #define MS_LOG_DEV_LEVEL 3
#include "RTC/Codecs/VP9.h"
#include "LoggerTag.h"
namespace RTC
{
namespace Codecs
{
/* Class methods. */
VP9::PayloadDescriptor* VP9::Parse(
const uint8_t* data,
size_t len,
RTC::RtpPacket::FrameMarking* /*frameMarking*/,
uint8_t /*frameMarkingLen*/)
{
MS_TRACE();
if (len < 1)
return nullptr;
std::unique_ptr<PayloadDescriptor> payloadDescriptor(new PayloadDescriptor());
size_t offset{ 0 };
uint8_t byte = data[offset];
payloadDescriptor->i = (byte >> 7) & 0x01;
payloadDescriptor->p = (byte >> 6) & 0x01;
payloadDescriptor->l = (byte >> 5) & 0x01;
payloadDescriptor->f = (byte >> 4) & 0x01;
payloadDescriptor->b = (byte >> 3) & 0x01;
payloadDescriptor->e = (byte >> 2) & 0x01;
payloadDescriptor->v = (byte >> 1) & 0x01;
if (payloadDescriptor->i)
{
if (len < ++offset + 1)
return nullptr;
byte = data[offset];
if (byte >> 7 & 0x01)
{
if (len < ++offset + 1)
return nullptr;
payloadDescriptor->pictureId = (byte & 0x7F) << 8;
payloadDescriptor->pictureId += data[offset];
payloadDescriptor->hasTwoBytesPictureId = true;
}
else
{
payloadDescriptor->pictureId = byte & 0x7F;
payloadDescriptor->hasOneBytePictureId = true;
}
payloadDescriptor->hasPictureId = true;
}
if (payloadDescriptor->l)
{
if (len < ++offset + 1)
return nullptr;
byte = data[offset];
payloadDescriptor->interLayerDependency = byte & 0x01;
payloadDescriptor->switchingUpPoint = byte >> 4 & 0x01;
payloadDescriptor->slIndex = byte >> 1 & 0x07;
payloadDescriptor->tlIndex = byte >> 5 & 0x07;
payloadDescriptor->hasSlIndex = true;
payloadDescriptor->hasTlIndex = true;
if (len < ++offset + 1)
return nullptr;
// Read TL0PICIDX if flexible mode is unset.
if (!payloadDescriptor->f)
{
payloadDescriptor->tl0PictureIndex = data[offset];
payloadDescriptor->hasTl0PictureIndex = true;
}
}
if (
!payloadDescriptor->p &&
payloadDescriptor->b &&
payloadDescriptor->slIndex == 0
)
{
payloadDescriptor->isKeyFrame = true;
}
return payloadDescriptor.release();
}
void VP9::ProcessRtpPacket(RTC::RtpPacket* packet)
{
MS_TRACE();
auto* data = packet->GetPayload();
auto len = packet->GetPayloadLength();
RtpPacket::FrameMarking* frameMarking{ nullptr };
uint8_t frameMarkingLen{ 0 };
// Read frame-marking.
packet->ReadFrameMarking(&frameMarking, frameMarkingLen);
PayloadDescriptor* payloadDescriptor = VP9::Parse(data, len, frameMarking, frameMarkingLen);
if (!payloadDescriptor)
return;
if (payloadDescriptor->isKeyFrame)
{
MS_DEBUG_DEV(
"key frame [spatialLayer:%" PRIu8 ", temporalLayer:%" PRIu8 "]",
packet->GetSpatialLayer(),
packet->GetTemporalLayer());
}
auto* payloadDescriptorHandler = new PayloadDescriptorHandler(payloadDescriptor);
packet->SetPayloadDescriptorHandler(payloadDescriptorHandler);
}
/* Instance methods. */
void VP9::PayloadDescriptor::Dump() const
{
MS_TRACE();
MS_DUMP("<PayloadDescriptor>");
MS_DUMP(
" i:%" PRIu8 "|p:%" PRIu8 "|l:%" PRIu8 "|f:%" PRIu8 "|b:%" PRIu8 "|e:%" PRIu8 "|v:%" PRIu8,
this->i,
this->p,
this->l,
this->f,
this->b,
this->e,
this->v);
MS_DUMP(" pictureId : %" PRIu16, this->pictureId);
MS_DUMP(" slIndex : %" PRIu8, this->slIndex);
MS_DUMP(" tlIndex : %" PRIu8, this->tlIndex);
MS_DUMP(" tl0PictureIndex : %" PRIu8, this->tl0PictureIndex);
MS_DUMP(" interLayerDependency : %" PRIu8, this->interLayerDependency);
MS_DUMP(" switchingUpPoint : %" PRIu8, this->switchingUpPoint);
MS_DUMP(" isKeyFrame : %s", this->isKeyFrame ? "true" : "false");
MS_DUMP(" hasPictureId : %s", this->hasPictureId ? "true" : "false");
MS_DUMP(" hasOneBytePictureId : %s", this->hasOneBytePictureId ? "true" : "false");
MS_DUMP(" hasTwoBytesPictureId : %s", this->hasTwoBytesPictureId ? "true" : "false");
MS_DUMP(" hasTl0PictureIndex : %s", this->hasTl0PictureIndex ? "true" : "false");
MS_DUMP(" hasSlIndex : %s", this->hasSlIndex ? "true" : "false");
MS_DUMP(" hasTlIndex : %s", this->hasTlIndex ? "true" : "false");
MS_DUMP("</PayloadDescriptor>");
}
VP9::PayloadDescriptorHandler::PayloadDescriptorHandler(VP9::PayloadDescriptor* payloadDescriptor)
{
MS_TRACE();
this->payloadDescriptor.reset(payloadDescriptor);
}
bool VP9::PayloadDescriptorHandler::Process(
RTC::Codecs::EncodingContext* encodingContext, uint8_t* /*data*/, bool& marker)
{
MS_TRACE();
auto* context = static_cast<RTC::Codecs::VP9::EncodingContext*>(encodingContext);
assertm(context->GetTargetSpatialLayer() >= 0, "target spatial layer cannot be -1");
assertm(context->GetTargetTemporalLayer() >= 0, "target temporal layer cannot be -1");
auto packetSpatialLayer = GetSpatialLayer();
auto packetTemporalLayer = GetTemporalLayer();
auto tmpSpatialLayer = context->GetCurrentSpatialLayer();
auto tmpTemporalLayer = context->GetCurrentTemporalLayer();
// If packet spatial or temporal layer is higher than maximum announced
// one, drop the packet.
if (
packetSpatialLayer >= context->GetSpatialLayers() ||
packetTemporalLayer >= context->GetTemporalLayers()
)
{
MS_WARN_TAG(
rtp, "too high packet layers %" PRIu8 ":%" PRIu8, packetSpatialLayer, packetTemporalLayer);
return false;
}
// Check whether pictureId sync is required.
if (
context->syncRequired &&
this->payloadDescriptor->hasPictureId
)
{
context->pictureIdManager.Sync(this->payloadDescriptor->pictureId - 1);
context->syncRequired = false;
}
bool isOldPacket = (
this->payloadDescriptor->hasPictureId &&
RTC::SeqManager<uint16_t>::IsSeqLowerThan(
this->payloadDescriptor->pictureId,
context->pictureIdManager.GetMaxInput())
);
// Upgrade current spatial layer if needed.
if (context->GetTargetSpatialLayer() > context->GetCurrentSpatialLayer())
{
if (this->payloadDescriptor->isKeyFrame)
{
MS_DEBUG_DEV(
"upgrading tmpSpatialLayer from %" PRIu16 " to %" PRIu16 " (packet:%" PRIu8 ":%" PRIu8
")",
context->GetCurrentSpatialLayer(),
context->GetTargetSpatialLayer(),
packetSpatialLayer,
packetTemporalLayer);
tmpSpatialLayer = context->GetTargetSpatialLayer();
tmpTemporalLayer = 0; // Just in case.
}
}
// Downgrade current spatial layer if needed.
else if (context->GetTargetSpatialLayer() < context->GetCurrentSpatialLayer())
{
// In K-SVC we must wait for a keyframe.
if (context->IsKSvc())
{
if (this->payloadDescriptor->isKeyFrame)
{
MS_DEBUG_DEV(
"downgrading tmpSpatialLayer from %" PRIu16 " to %" PRIu16 " (packet:%" PRIu8
":%" PRIu8 ") after keyframe (K-SVC)",
context->GetCurrentSpatialLayer(),
context->GetTargetSpatialLayer(),
packetSpatialLayer,
packetTemporalLayer);
tmpSpatialLayer = context->GetTargetSpatialLayer();
tmpTemporalLayer = 0; // Just in case.
}
}
// In full SVC we do not need a keyframe.
else
{
if (
packetSpatialLayer == context->GetTargetSpatialLayer() &&
this->payloadDescriptor->e
)
{
MS_DEBUG_DEV(
"downgrading tmpSpatialLayer from %" PRIu16 " to %" PRIu16 " (packet:%" PRIu8
":%" PRIu8 ") without keyframe (full SVC)",
context->GetCurrentSpatialLayer(),
context->GetTargetSpatialLayer(),
packetSpatialLayer,
packetTemporalLayer);
tmpSpatialLayer = context->GetTargetSpatialLayer();
tmpTemporalLayer = 0; // Just in case.
}
}
}
// Filter spatial layers higher than current one (unless old packet).
if (packetSpatialLayer > tmpSpatialLayer && !isOldPacket)
return false;
// Check and handle temporal layer (unless old packet).
if (!isOldPacket)
{
// Upgrade current temporal layer if needed.
if (context->GetTargetTemporalLayer() > context->GetCurrentTemporalLayer())
{
if (
packetTemporalLayer >= context->GetCurrentTemporalLayer() + 1 &&
(
context->GetCurrentTemporalLayer() == -1 ||
this->payloadDescriptor->switchingUpPoint
) &&
this->payloadDescriptor->b
)
{
MS_DEBUG_DEV(
"upgrading tmpTemporalLayer from %" PRIu16 " to %" PRIu8 " (packet:%" PRIu8 ":%" PRIu8
")",
context->GetCurrentTemporalLayer(),
packetTemporalLayer,
packetSpatialLayer,
packetTemporalLayer);
tmpTemporalLayer = packetTemporalLayer;
}
}
// Downgrade current temporal layer if needed.
else if (context->GetTargetTemporalLayer() < context->GetCurrentTemporalLayer())
{
if (
packetTemporalLayer == context->GetTargetTemporalLayer() &&
this->payloadDescriptor->e
)
{
MS_DEBUG_DEV(
"downgrading tmpTemporalLayer from %" PRIu16 " to %" PRIu16 " (packet:%" PRIu8
":%" PRIu8 ")",
context->GetCurrentTemporalLayer(),
context->GetTargetTemporalLayer(),
packetSpatialLayer,
packetTemporalLayer);
tmpTemporalLayer = context->GetTargetTemporalLayer();
}
}
// Filter temporal layers higher than current one.
if (packetTemporalLayer > tmpTemporalLayer)
return false;
}
// Set marker bit if needed.
if (packetSpatialLayer == tmpSpatialLayer && this->payloadDescriptor->e)
marker = true;
// Update the pictureId manager.
if (this->payloadDescriptor->hasPictureId)
{
uint16_t pictureId;
context->pictureIdManager.Input(this->payloadDescriptor->pictureId, pictureId);
}
// Update current spatial layer if needed.
if (tmpSpatialLayer != context->GetCurrentSpatialLayer())
context->SetCurrentSpatialLayer(tmpSpatialLayer);
// Update current temporal layer if needed.
if (tmpTemporalLayer != context->GetCurrentTemporalLayer())
context->SetCurrentTemporalLayer(tmpTemporalLayer);
return true;
}
void VP9::PayloadDescriptorHandler::Restore(uint8_t* /*data*/)
{
MS_TRACE();
}
} // namespace Codecs
} // namespace RTC
| [
"arvind.umrao@sococo.com"
] | arvind.umrao@sococo.com |
bf1905e36516141043035358930ad5bd2eb8d535 | c9c41adca80ad363396334f1be9d4e43c35a2edb | /src/kernel/connectx/connectx.cpp | 7c728e5ac75dd676e81ed747dae9aaf4de340981 | [] | no_license | MattKackles/xbox360-emu | bcbace649045410c7875486ffb71a1c12b823503 | c021c9fb29ac07baf6888208e6b294d4281a0080 | refs/heads/master | 2021-01-09T20:17:25.530741 | 2014-05-13T00:03:14 | 2014-05-13T00:03:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 92 | cpp | #include "kernel/connectx/connectx.h"
connectx::connectx() :
Module("connectx.xex")
{
}
| [
"james.benton2@gmail.com"
] | james.benton2@gmail.com |
1bcf729100c387a138dbf82cdb94e1232fa3e0dd | f0a08b44802a5e4f785fea3d5266f560c7a212de | /IceCream/IceCream.cpp | 8497238302c40066b6b01e2968b440edbc4d5340 | [] | no_license | krasimira99/Object-Oriented_Programing-18-19 | fc49c2df497169a92703a7c6ce1304e36f3ef0af | 221209acd89d64735bf6e1fb2a451a1564c911d7 | refs/heads/master | 2020-05-20T00:04:11.444190 | 2019-05-12T17:00:07 | 2019-05-12T17:00:07 | 185,279,687 | 1 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 3,100 | cpp | #include "pch.h"
#include "IceCream.h"
#include <iostream>
#include<cstring>
using namespace std;
IceCreamFlavour::IceCreamFlavour(char name[32], int priceOfBall)
{
strcpy_s(this->name, strlen(name) + 1, name);
this->priceOfBall = priceOfBall;
}
IceCreamFlavour::IceCreamFlavour()
{
name[0] = '\0';
priceOfBall = 0;
}
//"set" функции
void IceCream::setNameI(const char* name)
{
delete[] this->name;
int len = strlen(name) + 1;
this->name = new char[len];
strcpy_s(this->name, len, name);
}
void IceCream::setNumberOfBalls(const int numberOfBalls)
{
this->numberOfBalls = numberOfBalls;
}
void IceCream::setIceCreamFlavour(const IceCreamFlavour& flavour)
{
this->flavour = flavour;
}
//"get" функции
char* IceCream::getNameI() const
{
return this->name;
}
int IceCream::getNumberOfBalls() const
{
return this->numberOfBalls;
}
IceCreamFlavour IceCream::getIceCreamFlavour() const
{
return this->flavour;
}
//Конструктор по подразбиране
IceCream::IceCream() :name(nullptr)
{
name = new char[1];
name[0] = '\0';
numberOfBalls = 0;
flavour.name[0] = '\0';
flavour.priceOfBall = 0;
}
//Конструктор за общо ползване
IceCream::IceCream(const char* name, int numberOfBalls, IceCreamFlavour flavour) :name(nullptr)
{
this->name = new char[strlen(name) + 1];
strcpy_s(this->name, strlen(name) + 1, name);
this->numberOfBalls = numberOfBalls;
this->flavour = flavour;
}
//Copy конструктор
IceCream::IceCream(const IceCream &other) :name(nullptr)
{
this->name = new char[strlen(other.name) + 1];
strcpy_s(this->name, strlen(other.name) + 1, other.name);
this->numberOfBalls = other.numberOfBalls;
this->flavour = other.flavour;
}
//operator=
IceCream& IceCream::operator=(const IceCream& other)
{
if (this != &other)
{
setNameI(other.getNameI());
setNumberOfBalls(other.getNumberOfBalls());
setIceCreamFlavour(other.getIceCreamFlavour());
}
return *this;
}
//Деструктор
IceCream::~IceCream()
{
delete[] this->name;
}
//Цена на Ice Cream
double IceCream::getPrice() const
{
return numberOfBalls * flavour.priceOfBall;
}
//Print функция
void IceCream::print() const
{
cout << flavour.name << endl;
cout << flavour.priceOfBall << endl;
cout << name << endl;
cout << numberOfBalls << endl;
}
IceCream bestIceCream(IceCream* arr, int size, double money)
{
int idx = -1, coutBallsMax = -1;
double price = -5;
for (int i = 0; i < size; i++)
{
if ((arr[i].getPrice() < money && arr[i].getNumberOfBalls() > coutBallsMax) || (arr[i].getPrice() > price && arr[i].getNumberOfBalls() == coutBallsMax))
{
idx = i;
coutBallsMax = arr[i].getNumberOfBalls();
price = arr[i].getPrice();
}
}
return arr[idx];
}
void printIceCreamWithFlavour(IceCream* arr, int size, IceCreamFlavour searchedFlavour)
{
for (int i = 0; i < size; i++)
{
if (strcmp(arr[i].getIceCreamFlavour().name, searchedFlavour.name) == 0)
{
arr[i].print();
}
}
} | [
"noreply@github.com"
] | noreply@github.com |
67d4a5c02661e6f20e731fe2e7f094acff92270c | fcc5422a2473d38cc1456a363182f60f93b78d1d | /source/GSG/Base/Objects/Object.h | 54600064f88bf0e2f6af360b8965076694275a1c | [
"MIT"
] | permissive | perryiv/generic_scene_graph | 97d4f9b4d921af72a7602ee465a194435e155301 | 352a0093abc0fd9eaa047a6b34a51c7ef294ff9c | refs/heads/master | 2023-07-07T10:35:33.591519 | 2021-08-09T04:07:12 | 2021-08-09T04:07:12 | 271,178,791 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,742 | h |
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2021, Perry L Miller IV
// All rights reserved.
// MIT License: https://opensource.org/licenses/mit-license.html
//
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
// Base class for all reference-counted objects.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef _GSG_BASE_OBJECTS_OBJECT_CLASS_H_
#define _GSG_BASE_OBJECTS_OBJECT_CLASS_H_
#include "GSG/Config.h"
#include "GSG/Base/Export.h"
#include "Usul/Base/Referenced.h"
#include "Usul/Pointers/Pointers.h"
#include "Usul/Tools/NoCopying.h"
#include <string>
#define GSG_DECLARE_OBJECT_CLASS_BASE(class_name) \
USUL_REFERENCED_CLASS ( class_name ); \
typedef ValidAccessRefPtr Ptr; \
static std::string className(); \
virtual std::string getClassName()
#define GSG_DECLARE_OBJECT_CLASS(class_name) \
GSG_DECLARE_OBJECT_CLASS_BASE ( class_name ) override \
#define GSG_IMPLEMENT_OBJECT_CLASS(class_name) \
std::string class_name::className() { return std::string ( #class_name ); } \
std::string class_name::getClassName() { return class_name::className(); }
namespace GSG {
namespace Base {
namespace Objects {
class GSG_BASE_EXPORT Object : public Usul::Base::Referenced,
public Usul::Tools::NoCopying
{
public:
GSG_DECLARE_OBJECT_CLASS_BASE ( Object );
typedef Usul::Base::Referenced BaseClass;
protected:
Object();
virtual ~Object();
private:
void _destroyObject();
};
} // namespace Objects
} // namespace Base
} // namespace GSG
#endif // _GSG_BASE_OBJECTS_OBJECT_CLASS_H_
| [
"perry@modelspace.com"
] | perry@modelspace.com |
421c92ccd75205b201333c95e06266b3079793e6 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/multimedia/danim/src/appel/privinc/textimg.h | f094139d18d0e567225a188c7504853713704c62 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,918 | h |
/*******************************************************************************
Copyright (c) 1995_96 Microsoft Corporation
Abstract:
{Insert General Comment Here}
*******************************************************************************/
#ifndef _TEXTIMG_H
#define _TEXTIMG_H
#include "privinc/storeobj.h"
#include "appelles/text.h"
#include "appelles/image.h"
#include "privinc/probe.h"
#include "privinc/texti.h"
#include "privinc/textctx.h"
#include "privinc/bbox2i.h"
class TextImage : public Image {
public:
TextImage(Text *t) : _text(t), _bbox(NullBbox2) {}
void Render(GenericDevice& dev);
const Bbox2 BoundingBox() {
return DeriveBbox();
}
#if BOUNDINGBOX_TIGHTER
const Bbox2 BoundingBoxTighter(Bbox2Ctx &bbctx) {
Transform2 *xf = bbctx.GetTransform();
return TransformBbox2(xf, DeriveBbox());
}
#endif // BOUNDINGBOX_TIGHTER
const Bbox2 OperateOn(const Bbox2 &box) { return box; }
Bool DetectHit(PointIntersectCtx& ctx) {
Point2Value *lcPt = ctx.GetLcPoint();
if (!lcPt) return FALSE; // singular transform
return BoundingBox().Contains(Demote(*lcPt));
}
#if _USE_PRINT
ostream& Print(ostream& os) {
return os << "RenderTextToImage(...)";
}
#endif
Bool GetColor(Color **color) {
TextCtx ctx;
ctx.BeginRendering(TextCtx::renderForColor);
_text->RenderToTextCtx(ctx);
ctx.EndRendering();
*color = ctx.GetStashedColor();
return TRUE;
}
Text *GetText() { return _text; }
// Turn off text caching because of clear quality issues by making
// Savings return 0. Re-enable by making it return 2.
int Savings(CacheParam& p) { return 0; }
virtual void DoKids(GCFuncObj proc);
protected:
const Bbox2 DeriveBbox();
Text *_text;
Bbox2 _bbox;
};
#endif /* _TEXTIMG_H */
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
e90fa6a5ce7dd40cb9ec6b02a1dcba07233d189c | 81d8d99c64a901bbec13676cd5342c6605f17eab | /src/cocos/CCTextureCache.cpp | 31454adedd5e7ae9bd54f837b462020deb7f6519 | [
"Apache-2.0"
] | permissive | vyouyou/kof | a6cfb17355efbffd41d9816ee21d07948329ca11 | fb7340b7eb61779cc299d135189b65550685b625 | refs/heads/master | 2022-12-28T21:05:40.376525 | 2020-09-23T04:05:32 | 2020-09-23T04:05:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,150 | cpp | /*******************************************************************************
author : ljc
version : <1.0>
--------------------------------------------------------------------------------
info :
--------------------------------------------------------------------------------
*******************************************************************************/
#include "CCTextureCache.h"
#include "CCTexture2D.h"
#include <list>
#include <SDL_image.h>
static CCTextureCache *g_sharedTextureCache = NULL;
CCTextureCache * CCTextureCache::sharedTextureCache()
{
if (!g_sharedTextureCache)
{
g_sharedTextureCache = new CCTextureCache();
}
return g_sharedTextureCache;
}
CCTextureCache::CCTextureCache()
{
CAssert(g_sharedTextureCache == NULL, "Attempted to allocate a second instance of a singleton.");
glEnable(GL_BLEND);
m_pTextures = new CDictionary();
m_pUITextures = new CDictionary();
}
CCTextureCache::~CCTextureCache()
{
CC_SAFE_RELEASE(m_pTextures);
CC_SAFE_RELEASE(m_pUITextures);
}
void CCTextureCache::purgeSharedTextureCache()
{
CC_SAFE_RELEASE_NULL(g_sharedTextureCache);
}
void CCTextureCache::ClearTexture()
{
CDictElement* ele;
CCDICT_FOREACH(m_pTextures, ele)
{
CObject* obj = ele->getObject();
if (obj->isSingleReference())
{
m_pTextures->removeObjectForElememt(ele);
}
}
}
void CCTextureCache::ClearUITexture()
{
CDictElement* ele;
CCDICT_FOREACH(m_pUITextures, ele)
{
CObject* obj = ele->getObject();
if (obj->isSingleReference())
{
m_pUITextures->removeObjectForElememt(ele);
}
}
}
CCTexture2D* CCTextureCache::GetPngImage(const char* name)
{
PrintMessage("GetPngImage %s", name);
std::string key(name);
CCTexture2D *texture = (CCTexture2D*)m_pTextures->objectForKey(key);
if (texture)
{
return texture;
}
SDL_ClearError();
SDL_Surface* surface = IMG_LoadTyped_RW(SDL_RWFromFile(name,"rb"), 1, "png");
if (surface == NULL)
{
PrintMessage("IMG_LoadTyped_RW error: %s", SDL_GetError());
return NULL;
}
texture = new CCTexture2D;
texture->initWithSurface(surface, true);
m_pTextures->setObject(texture, key);
texture->autorelease();
return texture;
}
CCTexture2D* CCTextureCache::addSffImage(SFFSPRITE *lpSprite,PaletteFormat* sharePallet)
{
//TODO:use other key, number is not right
char keyStr[MAX_PATH];
SDL_snprintf(keyStr, MAX_PATH, "%d_%d", lpSprite, sharePallet);
std::string key(keyStr);
CCTexture2D *texture = (CCTexture2D*)m_pTextures->objectForKey(key);
if (texture)
{
return texture;
}
Uint32 width = lpSprite->PcxHeader.widht;
Uint32 height = lpSprite->PcxHeader.height;
Uint32 NPlane = lpSprite->PcxHeader.NPlanes;
Uint8* pcxData = DecodePcx(lpSprite->byPcxFile, lpSprite->PcxHeader);
Uint8* rgbaData = ConvertIndexToRGBA(pcxData, width*NPlane*height, sharePallet);
texture = new CCTexture2D;
CSize contentSize = CSize(width, height);
texture->initWithData(rgbaData, width, height, contentSize);
SDL_Color back = sharePallet->color[0];
texture->SetBackColor(back);
m_pTextures->setObject(texture, key);
free(pcxData);
free(rgbaData);
texture->autorelease();
return texture;
}
Uint8* CCTextureCache::ConvertIndexToRGBA(Uint8* data, int length, PaletteFormat* sharePallet)
{
Uint8* retData = (Uint8*)malloc(sizeof(Uint8)*(length+1)*4);
sharePallet->color[0].a = BACK_COLOR_ALPHA;
for (int i=0;i<length;i++)
{
int posOfPal = data[i];
retData[i*4] = sharePallet->color[posOfPal].r;
retData[i*4+1] = sharePallet->color[posOfPal].g;
retData[i*4+2] = sharePallet->color[posOfPal].b;
retData[i*4+3] = sharePallet->color[posOfPal].a;
}
return retData;
}
//decodes one PCX file
Uint8* CCTextureCache::DecodePcx(Uint8* PcxByte,PCXHEADER header)
{
Uint8* byImageBuffer=0;
Uint8 BPP,byData;
u16 size;
s16 x,y,widht;
u32 Pos=0;
u32 nCountByte,nTotalyByte,
nHowManyBytes,nHowManyBlank;
nTotalyByte=header.bytesPerLine*header.NPlanes;
nHowManyBytes=0;
nHowManyBlank=0;
nCountByte=0;
BPP=header.NPlanes*8;
//allocate memory
byImageBuffer=(Uint8*)malloc(sizeof(Uint8)*(header.widht*header.NPlanes*header.height+1));
widht=header.widht;
if(widht<header.bytesPerLine * header.NPlanes)
widht=header.bytesPerLine*header.NPlanes;
//we do not support 24bit pcx images
if(BPP>8)
{
PrintMessage("24Bit pcx file is not supproted");
return byImageBuffer;
}
size=0;
y=0;
x=0;
for(y=0;y<header.height;y++)
{
x=0;
while(x < widht)
{
byData=PcxByte[Pos++];
if( (byData & 0xC0) == 0xC0 )
{
size = byData & 0x3F;
byData=PcxByte[Pos++];
}
else
{
size=1;
}
while(size-- > 0)
{
if(x <= header.widht)
{
byImageBuffer[x + (y * header.widht)]=byData;
}
//this it to Skip blank data on PCX image wich are on the right side
//TODO:OK? Skip two bytes
if(x == widht && widht != header.widht)
{
nHowManyBlank=widht-header.widht;
for(u32 i=0;i<nHowManyBlank;i++)
Pos+=2;
}
x++;
}
}
}
return byImageBuffer;
}
| [
"lijinchao2007@gmail.com"
] | lijinchao2007@gmail.com |
34970f827cc629c069f39c7949e341a9d6a17e1d | a33aac97878b2cb15677be26e308cbc46e2862d2 | /program_data/PKU_raw/91/1065.c | 79df599388e0846a1a38fe417e13fd012ddfb2b1 | [] | no_license | GabeOchieng/ggnn.tensorflow | f5d7d0bca52258336fc12c9de6ae38223f28f786 | 7c62c0e8427bea6c8bec2cebf157b6f1ea70a213 | refs/heads/master | 2022-05-30T11:17:42.278048 | 2020-05-02T11:33:31 | 2020-05-02T11:33:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 257 | c | int main ()
{
int i,n;
char s1[101],s2[101];
char * p,* q;
gets(s1);
p=s1;
q=s2;
n=strlen(s1);
for (i=0;*(p+i+1)!='\0';i++){
*q=(*(p+i))+(*(p+i+1));
q++;
}
*(q++)=*(p+n-1)+*p;
*(q++)='\0';
puts(s2);
return 0;
} | [
"bdqnghi@gmail.com"
] | bdqnghi@gmail.com |
2278b323703a44f401645541e94107ce113bd8e2 | 3c51e26a569c1c53c9e14e52178314f9010c364b | /cut4/objfile.h | 9e955cde0b145ce335545e63483d77d4acfee2dc | [] | no_license | solarix95/mpops | 982c33e52c8b7c62df590b198425fbb3963f0faa | db349a8eede0e2cfb050a69ad8518ce6f4f0dea4 | refs/heads/master | 2021-01-10T03:33:51.873859 | 2015-12-26T09:57:46 | 2015-12-26T09:57:46 | 47,355,667 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 270 | h | #ifndef OBJFILE_H
#define OBJFILE_H
#include <QString>
class ObjFile
{
public:
ObjFile();
bool load(const QString &filename);
int verticeCount() const;
float *vertice(int index) const;
private:
QList<float*> mVertices;
};
#endif // OBJFILE_H
| [
"roman@ubu00.(none)"
] | roman@ubu00.(none) |
564107ae77a31c0855a7c6aa3b6e3225bcd74cf4 | 9c4dfafc2820c857d8d11097a2f7564a0e9d5334 | /src/WSTestAndroid/Source/easywsclient.hpp | 5a7148b12f337fa07e793d0fdb59797c37c5665a | [] | no_license | taetaytae/remote-colaboratory | b40acae33702f029e272713cf1b8de8a886db3b9 | 63949006b711210ea510f5552e44535fb7128727 | refs/heads/main | 2023-03-05T05:52:19.590635 | 2021-02-16T03:21:02 | 2021-02-16T03:21:02 | 339,234,984 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,756 | hpp | #ifndef EASYWSCLIENT_HPP_20120819_MIOFVASDTNUASZDQPLFD
#define EASYWSCLIENT_HPP_20120819_MIOFVASDTNUASZDQPLFD
// This code comes from:
// https://github.com/dhbaird/easywsclient
//
// To get the latest version:
// wget https://raw.github.com/dhbaird/easywsclient/master/easywsclient.hpp
// wget https://raw.github.com/dhbaird/easywsclient/master/easywsclient.cpp
#include <string>
#include <vector>
namespace easywsclient {
struct Callback_Imp { virtual void operator()(const std::string& message) = 0; };
struct BytesCallback_Imp { virtual void operator()(const std::vector<uint8_t>& message) = 0; };
class WebSocket {
public:
typedef WebSocket * pointer;
typedef enum readyStateValues { CLOSING, CLOSED, CONNECTING, OPEN } readyStateValues;
// Factories:
static pointer create_dummy();
static pointer from_url(const std::string& url, const std::string& origin = std::string());
static pointer from_url_no_mask(const std::string& url, const std::string& origin = std::string());
// Interfaces:
virtual ~WebSocket() { }
virtual void poll(int timeout = 0) = 0; // timeout in milliseconds
virtual void send(const std::string& message) = 0;
virtual void sendBinary(const std::string& message) = 0;
virtual void sendBinary(const std::vector<uint8_t>& message) = 0;
virtual void sendPing() = 0;
virtual void close() = 0;
virtual readyStateValues getReadyState() const = 0;
template<class Callable>
void dispatch(Callable callable)
// For callbacks that accept a string argument.
{ // N.B. this is compatible with both C++11 lambdas, functors and C function pointers
struct _Callback : public Callback_Imp {
Callable& callable;
_Callback(Callable& callable) : callable(callable) { }
void operator()(const std::string& message) { callable(message); }
};
_Callback callback(callable);
_dispatch(callback);
}
template<class Callable>
void dispatchBinary(Callable callable)
// For callbacks that accept a std::vector<uint8_t> argument.
{ // N.B. this is compatible with both C++11 lambdas, functors and C function pointers
struct _Callback : public BytesCallback_Imp {
Callable& callable;
_Callback(Callable& callable) : callable(callable) { }
void operator()(const std::vector<uint8_t>& message) { callable(message); }
};
_Callback callback(callable);
_dispatchBinary(callback);
}
protected:
virtual void _dispatch(Callback_Imp& callable) = 0;
virtual void _dispatchBinary(BytesCallback_Imp& callable) = 0;
};
} // namespace easywsclient
#endif /* EASYWSCLIENT_HPP_20120819_MIOFVASDTNUASZDQPLFD */ | [
"mario.a.sanchez199902@gmail.com"
] | mario.a.sanchez199902@gmail.com |
e5a09568a7c04a27eb2aea2f7f77af9ce72b0646 | cb77dcbbce6c480f68c3dcb8610743f027bee95c | /android/art/runtime/jni_internal.cc | cd66a60376ecc89d2652440238724f1fa2a2ff9d | [
"MIT",
"Apache-2.0",
"NCSA"
] | permissive | fengjixuchui/deoptfuscator | c888b93361d837ef619b9eb95ffd4b01a4bef51a | dec8fbf2b59f8dddf2dbd10868726b255364e1c5 | refs/heads/master | 2023-03-17T11:49:00.988260 | 2023-03-09T02:01:47 | 2023-03-09T02:01:47 | 333,074,914 | 0 | 0 | MIT | 2023-03-09T02:01:48 | 2021-01-26T12:16:31 | null | UTF-8 | C++ | false | false | 117,714 | cc | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "jni_internal.h"
#include <dlfcn.h>
#include <cstdarg>
#include <memory>
#include <utility>
#include <vector>
#include "art_field-inl.h"
#include "art_method-inl.h"
#include "base/allocator.h"
#include "base/atomic.h"
#include "base/enums.h"
#include "base/logging.h" // For VLOG.
#include "base/mutex.h"
#include "base/safe_map.h"
#include "base/stl_util.h"
#include "class_linker-inl.h"
#include "dex/dex_file-inl.h"
#include "dex/utf.h"
#include "fault_handler.h"
#include "hidden_api.h"
#include "gc/accounting/card_table-inl.h"
#include "gc_root.h"
#include "indirect_reference_table-inl.h"
#include "interpreter/interpreter.h"
#include "java_vm_ext.h"
#include "jni_env_ext.h"
#include "jvalue-inl.h"
#include "mirror/class-inl.h"
#include "mirror/class_loader.h"
#include "mirror/field-inl.h"
#include "mirror/method.h"
#include "mirror/object-inl.h"
#include "mirror/object_array-inl.h"
#include "mirror/string-inl.h"
#include "mirror/throwable.h"
#include "nativehelper/scoped_local_ref.h"
#include "parsed_options.h"
#include "reflection.h"
#include "runtime.h"
#include "scoped_thread_state_change-inl.h"
#include "thread.h"
#include "well_known_classes.h"
namespace {
// Frees the given va_list upon destruction.
// This also guards the returns from inside of the CHECK_NON_NULL_ARGUMENTs.
struct ScopedVAArgs {
explicit ScopedVAArgs(va_list* args): args(args) {}
ScopedVAArgs(const ScopedVAArgs&) = delete;
ScopedVAArgs(ScopedVAArgs&&) = delete;
~ScopedVAArgs() { va_end(*args); }
private:
va_list* args;
};
} // namespace
namespace art {
// Consider turning this on when there is errors which could be related to JNI array copies such as
// things not rendering correctly. E.g. b/16858794
static constexpr bool kWarnJniAbort = false;
static bool IsCallerTrusted(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_) {
return hiddenapi::IsCallerTrusted(GetCallingClass(self, /* num_frames */ 1));
}
template<typename T>
ALWAYS_INLINE static bool ShouldBlockAccessToMember(T* member, Thread* self)
REQUIRES_SHARED(Locks::mutator_lock_) {
hiddenapi::Action action = hiddenapi::GetMemberAction(
member, self, IsCallerTrusted, hiddenapi::kJNI);
if (action != hiddenapi::kAllow) {
hiddenapi::NotifyHiddenApiListener(member);
}
return action == hiddenapi::kDeny;
}
// Helpers to call instrumentation functions for fields. These take jobjects so we don't need to set
// up handles for the rare case where these actually do something. Once these functions return it is
// possible there will be a pending exception if the instrumentation happens to throw one.
static void NotifySetObjectField(ArtField* field, jobject obj, jobject jval)
REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK_EQ(field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
if (UNLIKELY(instrumentation->HasFieldWriteListeners())) {
Thread* self = Thread::Current();
ArtMethod* cur_method = self->GetCurrentMethod(/*dex_pc*/ nullptr,
/*check_suspended*/ true,
/*abort_on_error*/ false);
if (cur_method == nullptr) {
// Set/Get Fields can be issued without a method during runtime startup/teardown. Ignore all
// of these changes.
return;
}
DCHECK(cur_method->IsNative());
JValue val;
val.SetL(self->DecodeJObject(jval));
instrumentation->FieldWriteEvent(self,
self->DecodeJObject(obj).Ptr(),
cur_method,
0, // dex_pc is always 0 since this is a native method.
field,
val);
}
}
static void NotifySetPrimitiveField(ArtField* field, jobject obj, JValue val)
REQUIRES_SHARED(Locks::mutator_lock_) {
DCHECK_NE(field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
if (UNLIKELY(instrumentation->HasFieldWriteListeners())) {
Thread* self = Thread::Current();
ArtMethod* cur_method = self->GetCurrentMethod(/*dex_pc*/ nullptr,
/*check_suspended*/ true,
/*abort_on_error*/ false);
if (cur_method == nullptr) {
// Set/Get Fields can be issued without a method during runtime startup/teardown. Ignore all
// of these changes.
return;
}
DCHECK(cur_method->IsNative());
instrumentation->FieldWriteEvent(self,
self->DecodeJObject(obj).Ptr(),
cur_method,
0, // dex_pc is always 0 since this is a native method.
field,
val);
}
}
static void NotifyGetField(ArtField* field, jobject obj)
REQUIRES_SHARED(Locks::mutator_lock_) {
instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
if (UNLIKELY(instrumentation->HasFieldReadListeners())) {
Thread* self = Thread::Current();
ArtMethod* cur_method = self->GetCurrentMethod(/*dex_pc*/ nullptr,
/*check_suspended*/ true,
/*abort_on_error*/ false);
if (cur_method == nullptr) {
// Set/Get Fields can be issued without a method during runtime startup/teardown. Ignore all
// of these changes.
return;
}
DCHECK(cur_method->IsNative());
instrumentation->FieldReadEvent(self,
self->DecodeJObject(obj).Ptr(),
cur_method,
0, // dex_pc is always 0 since this is a native method.
field);
}
}
// Section 12.3.2 of the JNI spec describes JNI class descriptors. They're
// separated with slashes but aren't wrapped with "L;" like regular descriptors
// (i.e. "a/b/C" rather than "La/b/C;"). Arrays of reference types are an
// exception; there the "L;" must be present ("[La/b/C;"). Historically we've
// supported names with dots too (such as "a.b.C").
static std::string NormalizeJniClassDescriptor(const char* name) {
std::string result;
// Add the missing "L;" if necessary.
if (name[0] == '[') {
result = name;
} else {
result += 'L';
result += name;
result += ';';
}
// Rewrite '.' as '/' for backwards compatibility.
if (result.find('.') != std::string::npos) {
LOG(WARNING) << "Call to JNI FindClass with dots in name: "
<< "\"" << name << "\"";
std::replace(result.begin(), result.end(), '.', '/');
}
return result;
}
static void ThrowNoSuchMethodError(ScopedObjectAccess& soa,
ObjPtr<mirror::Class> c,
const char* name,
const char* sig,
const char* kind)
REQUIRES_SHARED(Locks::mutator_lock_) {
std::string temp;
soa.Self()->ThrowNewExceptionF("Ljava/lang/NoSuchMethodError;",
"no %s method \"%s.%s%s\"",
kind,
c->GetDescriptor(&temp),
name,
sig);
}
static void ReportInvalidJNINativeMethod(const ScopedObjectAccess& soa,
ObjPtr<mirror::Class> c,
const char* kind,
jint idx)
REQUIRES_SHARED(Locks::mutator_lock_) {
LOG(ERROR)
<< "Failed to register native method in " << c->PrettyDescriptor()
<< " in " << c->GetDexCache()->GetLocation()->ToModifiedUtf8()
<< ": " << kind << " is null at index " << idx;
soa.Self()->ThrowNewExceptionF("Ljava/lang/NoSuchMethodError;",
"%s is null at index %d",
kind,
idx);
}
static ObjPtr<mirror::Class> EnsureInitialized(Thread* self, ObjPtr<mirror::Class> klass)
REQUIRES_SHARED(Locks::mutator_lock_) {
if (LIKELY(klass->IsInitialized())) {
return klass;
}
StackHandleScope<1> hs(self);
Handle<mirror::Class> h_klass(hs.NewHandle(klass));
if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, h_klass, true, true)) {
return nullptr;
}
return h_klass.Get();
}
static jmethodID FindMethodID(ScopedObjectAccess& soa, jclass jni_class,
const char* name, const char* sig, bool is_static)
REQUIRES_SHARED(Locks::mutator_lock_) {
ObjPtr<mirror::Class> c = EnsureInitialized(soa.Self(), soa.Decode<mirror::Class>(jni_class));
if (c == nullptr) {
return nullptr;
}
ArtMethod* method = nullptr;
auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
if (c->IsInterface()) {
method = c->FindInterfaceMethod(name, sig, pointer_size);
} else {
method = c->FindClassMethod(name, sig, pointer_size);
}
if (method != nullptr && ShouldBlockAccessToMember(method, soa.Self())) {
method = nullptr;
}
if (method == nullptr || method->IsStatic() != is_static) {
ThrowNoSuchMethodError(soa, c, name, sig, is_static ? "static" : "non-static");
return nullptr;
}
return jni::EncodeArtMethod(method);
}
static ObjPtr<mirror::ClassLoader> GetClassLoader(const ScopedObjectAccess& soa)
REQUIRES_SHARED(Locks::mutator_lock_) {
ArtMethod* method = soa.Self()->GetCurrentMethod(nullptr);
// If we are running Runtime.nativeLoad, use the overriding ClassLoader it set.
if (method == jni::DecodeArtMethod(WellKnownClasses::java_lang_Runtime_nativeLoad)) {
return soa.Decode<mirror::ClassLoader>(soa.Self()->GetClassLoaderOverride());
}
// If we have a method, use its ClassLoader for context.
if (method != nullptr) {
return method->GetDeclaringClass()->GetClassLoader();
}
// We don't have a method, so try to use the system ClassLoader.
ObjPtr<mirror::ClassLoader> class_loader =
soa.Decode<mirror::ClassLoader>(Runtime::Current()->GetSystemClassLoader());
if (class_loader != nullptr) {
return class_loader;
}
// See if the override ClassLoader is set for gtests.
class_loader = soa.Decode<mirror::ClassLoader>(soa.Self()->GetClassLoaderOverride());
if (class_loader != nullptr) {
// If so, CommonCompilerTest should have marked the runtime as a compiler not compiling an
// image.
CHECK(Runtime::Current()->IsAotCompiler());
CHECK(!Runtime::Current()->IsCompilingBootImage());
return class_loader;
}
// Use the BOOTCLASSPATH.
return nullptr;
}
static jfieldID FindFieldID(const ScopedObjectAccess& soa, jclass jni_class, const char* name,
const char* sig, bool is_static)
REQUIRES_SHARED(Locks::mutator_lock_) {
StackHandleScope<2> hs(soa.Self());
Handle<mirror::Class> c(
hs.NewHandle(EnsureInitialized(soa.Self(), soa.Decode<mirror::Class>(jni_class))));
if (c == nullptr) {
return nullptr;
}
ArtField* field = nullptr;
mirror::Class* field_type;
ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
if (sig[1] != '\0') {
Handle<mirror::ClassLoader> class_loader(hs.NewHandle(c->GetClassLoader()));
field_type = class_linker->FindClass(soa.Self(), sig, class_loader);
} else {
field_type = class_linker->FindPrimitiveClass(*sig);
}
if (field_type == nullptr) {
// Failed to find type from the signature of the field.
DCHECK(soa.Self()->IsExceptionPending());
StackHandleScope<1> hs2(soa.Self());
Handle<mirror::Throwable> cause(hs2.NewHandle(soa.Self()->GetException()));
soa.Self()->ClearException();
std::string temp;
soa.Self()->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
"no type \"%s\" found and so no field \"%s\" "
"could be found in class \"%s\" or its superclasses", sig, name,
c->GetDescriptor(&temp));
soa.Self()->GetException()->SetCause(cause.Get());
return nullptr;
}
std::string temp;
if (is_static) {
field = mirror::Class::FindStaticField(
soa.Self(), c.Get(), name, field_type->GetDescriptor(&temp));
} else {
field = c->FindInstanceField(name, field_type->GetDescriptor(&temp));
}
if (field != nullptr && ShouldBlockAccessToMember(field, soa.Self())) {
field = nullptr;
}
if (field == nullptr) {
soa.Self()->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
"no \"%s\" field \"%s\" in class \"%s\" or its superclasses",
sig, name, c->GetDescriptor(&temp));
return nullptr;
}
return jni::EncodeArtField(field);
}
static void ThrowAIOOBE(ScopedObjectAccess& soa, mirror::Array* array, jsize start,
jsize length, const char* identifier)
REQUIRES_SHARED(Locks::mutator_lock_) {
std::string type(array->PrettyTypeOf());
soa.Self()->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
"%s offset=%d length=%d %s.length=%d",
type.c_str(), start, length, identifier, array->GetLength());
}
static void ThrowSIOOBE(ScopedObjectAccess& soa, jsize start, jsize length,
jsize array_length)
REQUIRES_SHARED(Locks::mutator_lock_) {
soa.Self()->ThrowNewExceptionF("Ljava/lang/StringIndexOutOfBoundsException;",
"offset=%d length=%d string.length()=%d", start, length,
array_length);
}
int ThrowNewException(JNIEnv* env, jclass exception_class, const char* msg, jobject cause)
REQUIRES(!Locks::mutator_lock_) {
// Turn the const char* into a java.lang.String.
ScopedLocalRef<jstring> s(env, env->NewStringUTF(msg));
if (msg != nullptr && s.get() == nullptr) {
return JNI_ERR;
}
// Choose an appropriate constructor and set up the arguments.
jvalue args[2];
const char* signature;
if (msg == nullptr && cause == nullptr) {
signature = "()V";
} else if (msg != nullptr && cause == nullptr) {
signature = "(Ljava/lang/String;)V";
args[0].l = s.get();
} else if (msg == nullptr && cause != nullptr) {
signature = "(Ljava/lang/Throwable;)V";
args[0].l = cause;
} else {
signature = "(Ljava/lang/String;Ljava/lang/Throwable;)V";
args[0].l = s.get();
args[1].l = cause;
}
jmethodID mid = env->GetMethodID(exception_class, "<init>", signature);
if (mid == nullptr) {
ScopedObjectAccess soa(env);
LOG(ERROR) << "No <init>" << signature << " in "
<< mirror::Class::PrettyClass(soa.Decode<mirror::Class>(exception_class));
return JNI_ERR;
}
ScopedLocalRef<jthrowable> exception(
env, reinterpret_cast<jthrowable>(env->NewObjectA(exception_class, mid, args)));
if (exception.get() == nullptr) {
return JNI_ERR;
}
ScopedObjectAccess soa(env);
soa.Self()->SetException(soa.Decode<mirror::Throwable>(exception.get()));
return JNI_OK;
}
static JavaVMExt* JavaVmExtFromEnv(JNIEnv* env) {
return reinterpret_cast<JNIEnvExt*>(env)->GetVm();
}
#define CHECK_NON_NULL_ARGUMENT(value) \
CHECK_NON_NULL_ARGUMENT_FN_NAME(__FUNCTION__, value, nullptr)
#define CHECK_NON_NULL_ARGUMENT_RETURN_VOID(value) \
CHECK_NON_NULL_ARGUMENT_FN_NAME(__FUNCTION__, value, )
#define CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(value) \
CHECK_NON_NULL_ARGUMENT_FN_NAME(__FUNCTION__, value, 0)
#define CHECK_NON_NULL_ARGUMENT_RETURN(value, return_val) \
CHECK_NON_NULL_ARGUMENT_FN_NAME(__FUNCTION__, value, return_val)
#define CHECK_NON_NULL_ARGUMENT_FN_NAME(name, value, return_val) \
if (UNLIKELY((value) == nullptr)) { \
JavaVmExtFromEnv(env)->JniAbort(name, #value " == null"); \
return return_val; \
}
#define CHECK_NON_NULL_MEMCPY_ARGUMENT(length, value) \
if (UNLIKELY((length) != 0 && (value) == nullptr)) { \
JavaVmExtFromEnv(env)->JniAbort(__FUNCTION__, #value " == null"); \
return; \
}
template <bool kNative>
static ArtMethod* FindMethod(mirror::Class* c, const StringPiece& name, const StringPiece& sig)
REQUIRES_SHARED(Locks::mutator_lock_) {
auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
for (auto& method : c->GetMethods(pointer_size)) {
if (kNative == method.IsNative() && name == method.GetName() && method.GetSignature() == sig) {
return &method;
}
}
return nullptr;
}
class JNI {
public:
static jint GetVersion(JNIEnv*) {
return JNI_VERSION_1_6;
}
static jclass DefineClass(JNIEnv*, const char*, jobject, const jbyte*, jsize) {
LOG(WARNING) << "JNI DefineClass is not supported";
return nullptr;
}
static jclass FindClass(JNIEnv* env, const char* name) {
CHECK_NON_NULL_ARGUMENT(name);
Runtime* runtime = Runtime::Current();
ClassLinker* class_linker = runtime->GetClassLinker();
std::string descriptor(NormalizeJniClassDescriptor(name));
ScopedObjectAccess soa(env);
mirror::Class* c = nullptr;
if (runtime->IsStarted()) {
StackHandleScope<1> hs(soa.Self());
Handle<mirror::ClassLoader> class_loader(hs.NewHandle(GetClassLoader(soa)));
c = class_linker->FindClass(soa.Self(), descriptor.c_str(), class_loader);
} else {
c = class_linker->FindSystemClass(soa.Self(), descriptor.c_str());
}
return soa.AddLocalReference<jclass>(c);
}
static jmethodID FromReflectedMethod(JNIEnv* env, jobject jlr_method) {
CHECK_NON_NULL_ARGUMENT(jlr_method);
ScopedObjectAccess soa(env);
return jni::EncodeArtMethod(ArtMethod::FromReflectedMethod(soa, jlr_method));
}
static jfieldID FromReflectedField(JNIEnv* env, jobject jlr_field) {
CHECK_NON_NULL_ARGUMENT(jlr_field);
ScopedObjectAccess soa(env);
ObjPtr<mirror::Object> obj_field = soa.Decode<mirror::Object>(jlr_field);
if (obj_field->GetClass() != mirror::Field::StaticClass()) {
// Not even a java.lang.reflect.Field, return null. TODO, is this check necessary?
return nullptr;
}
ObjPtr<mirror::Field> field = ObjPtr<mirror::Field>::DownCast(obj_field);
return jni::EncodeArtField(field->GetArtField());
}
static jobject ToReflectedMethod(JNIEnv* env, jclass, jmethodID mid, jboolean) {
CHECK_NON_NULL_ARGUMENT(mid);
ScopedObjectAccess soa(env);
ArtMethod* m = jni::DecodeArtMethod(mid);
mirror::Executable* method;
DCHECK_EQ(Runtime::Current()->GetClassLinker()->GetImagePointerSize(), kRuntimePointerSize);
DCHECK(!Runtime::Current()->IsActiveTransaction());
if (m->IsConstructor()) {
method = mirror::Constructor::CreateFromArtMethod<kRuntimePointerSize, false>(soa.Self(), m);
} else {
method = mirror::Method::CreateFromArtMethod<kRuntimePointerSize, false>(soa.Self(), m);
}
return soa.AddLocalReference<jobject>(method);
}
static jobject ToReflectedField(JNIEnv* env, jclass, jfieldID fid, jboolean) {
CHECK_NON_NULL_ARGUMENT(fid);
ScopedObjectAccess soa(env);
ArtField* f = jni::DecodeArtField(fid);
return soa.AddLocalReference<jobject>(
mirror::Field::CreateFromArtField<kRuntimePointerSize>(soa.Self(), f, true));
}
static jclass GetObjectClass(JNIEnv* env, jobject java_object) {
CHECK_NON_NULL_ARGUMENT(java_object);
ScopedObjectAccess soa(env);
ObjPtr<mirror::Object> o = soa.Decode<mirror::Object>(java_object);
return soa.AddLocalReference<jclass>(o->GetClass());
}
static jclass GetSuperclass(JNIEnv* env, jclass java_class) {
CHECK_NON_NULL_ARGUMENT(java_class);
ScopedObjectAccess soa(env);
ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(java_class);
return soa.AddLocalReference<jclass>(c->IsInterface() ? nullptr : c->GetSuperClass());
}
// Note: java_class1 should be safely castable to java_class2, and
// not the other way around.
static jboolean IsAssignableFrom(JNIEnv* env, jclass java_class1, jclass java_class2) {
CHECK_NON_NULL_ARGUMENT_RETURN(java_class1, JNI_FALSE);
CHECK_NON_NULL_ARGUMENT_RETURN(java_class2, JNI_FALSE);
ScopedObjectAccess soa(env);
ObjPtr<mirror::Class> c1 = soa.Decode<mirror::Class>(java_class1);
ObjPtr<mirror::Class> c2 = soa.Decode<mirror::Class>(java_class2);
return c2->IsAssignableFrom(c1) ? JNI_TRUE : JNI_FALSE;
}
static jboolean IsInstanceOf(JNIEnv* env, jobject jobj, jclass java_class) {
CHECK_NON_NULL_ARGUMENT_RETURN(java_class, JNI_FALSE);
if (jobj == nullptr) {
// Note: JNI is different from regular Java instanceof in this respect
return JNI_TRUE;
} else {
ScopedObjectAccess soa(env);
ObjPtr<mirror::Object> obj = soa.Decode<mirror::Object>(jobj);
ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(java_class);
return obj->InstanceOf(c) ? JNI_TRUE : JNI_FALSE;
}
}
static jint Throw(JNIEnv* env, jthrowable java_exception) {
ScopedObjectAccess soa(env);
ObjPtr<mirror::Throwable> exception = soa.Decode<mirror::Throwable>(java_exception);
if (exception == nullptr) {
return JNI_ERR;
}
soa.Self()->SetException(exception);
return JNI_OK;
}
static jint ThrowNew(JNIEnv* env, jclass c, const char* msg) {
CHECK_NON_NULL_ARGUMENT_RETURN(c, JNI_ERR);
return ThrowNewException(env, c, msg, nullptr);
}
static jboolean ExceptionCheck(JNIEnv* env) {
return static_cast<JNIEnvExt*>(env)->self_->IsExceptionPending() ? JNI_TRUE : JNI_FALSE;
}
static void ExceptionClear(JNIEnv* env) {
ScopedObjectAccess soa(env);
soa.Self()->ClearException();
}
static void ExceptionDescribe(JNIEnv* env) {
ScopedObjectAccess soa(env);
// If we have no exception to describe, pass through.
if (!soa.Self()->GetException()) {
return;
}
StackHandleScope<1> hs(soa.Self());
Handle<mirror::Throwable> old_exception(
hs.NewHandle<mirror::Throwable>(soa.Self()->GetException()));
soa.Self()->ClearException();
ScopedLocalRef<jthrowable> exception(env,
soa.AddLocalReference<jthrowable>(old_exception.Get()));
ScopedLocalRef<jclass> exception_class(env, env->GetObjectClass(exception.get()));
jmethodID mid = env->GetMethodID(exception_class.get(), "printStackTrace", "()V");
if (mid == nullptr) {
LOG(WARNING) << "JNI WARNING: no printStackTrace()V in "
<< mirror::Object::PrettyTypeOf(old_exception.Get());
} else {
env->CallVoidMethod(exception.get(), mid);
if (soa.Self()->IsExceptionPending()) {
LOG(WARNING) << "JNI WARNING: " << mirror::Object::PrettyTypeOf(soa.Self()->GetException())
<< " thrown while calling printStackTrace";
soa.Self()->ClearException();
}
}
soa.Self()->SetException(old_exception.Get());
}
static jthrowable ExceptionOccurred(JNIEnv* env) {
ScopedObjectAccess soa(env);
mirror::Object* exception = soa.Self()->GetException();
return soa.AddLocalReference<jthrowable>(exception);
}
static void FatalError(JNIEnv*, const char* msg) {
LOG(FATAL) << "JNI FatalError called: " << msg;
}
static jint PushLocalFrame(JNIEnv* env, jint capacity) {
// TODO: SOA may not be necessary but I do it to please lock annotations.
ScopedObjectAccess soa(env);
if (EnsureLocalCapacityInternal(soa, capacity, "PushLocalFrame") != JNI_OK) {
return JNI_ERR;
}
down_cast<JNIEnvExt*>(env)->PushFrame(capacity);
return JNI_OK;
}
static jobject PopLocalFrame(JNIEnv* env, jobject java_survivor) {
ScopedObjectAccess soa(env);
ObjPtr<mirror::Object> survivor = soa.Decode<mirror::Object>(java_survivor);
soa.Env()->PopFrame();
return soa.AddLocalReference<jobject>(survivor);
}
static jint EnsureLocalCapacity(JNIEnv* env, jint desired_capacity) {
// TODO: SOA may not be necessary but I do it to please lock annotations.
ScopedObjectAccess soa(env);
return EnsureLocalCapacityInternal(soa, desired_capacity, "EnsureLocalCapacity");
}
static jobject NewGlobalRef(JNIEnv* env, jobject obj) {
ScopedObjectAccess soa(env);
ObjPtr<mirror::Object> decoded_obj = soa.Decode<mirror::Object>(obj);
return soa.Vm()->AddGlobalRef(soa.Self(), decoded_obj);
}
static void DeleteGlobalRef(JNIEnv* env, jobject obj) {
JavaVMExt* vm = down_cast<JNIEnvExt*>(env)->GetVm();
Thread* self = down_cast<JNIEnvExt*>(env)->self_;
vm->DeleteGlobalRef(self, obj);
}
static jweak NewWeakGlobalRef(JNIEnv* env, jobject obj) {
ScopedObjectAccess soa(env);
ObjPtr<mirror::Object> decoded_obj = soa.Decode<mirror::Object>(obj);
return soa.Vm()->AddWeakGlobalRef(soa.Self(), decoded_obj);
}
static void DeleteWeakGlobalRef(JNIEnv* env, jweak obj) {
JavaVMExt* vm = down_cast<JNIEnvExt*>(env)->GetVm();
Thread* self = down_cast<JNIEnvExt*>(env)->self_;
vm->DeleteWeakGlobalRef(self, obj);
}
static jobject NewLocalRef(JNIEnv* env, jobject obj) {
ScopedObjectAccess soa(env);
ObjPtr<mirror::Object> decoded_obj = soa.Decode<mirror::Object>(obj);
// Check for null after decoding the object to handle cleared weak globals.
if (decoded_obj == nullptr) {
return nullptr;
}
return soa.AddLocalReference<jobject>(decoded_obj);
}
static void DeleteLocalRef(JNIEnv* env, jobject obj) {
if (obj == nullptr) {
return;
}
// SOA is only necessary to have exclusion between GC root marking and removing.
// We don't want to have the GC attempt to mark a null root if we just removed
// it. b/22119403
ScopedObjectAccess soa(env);
auto* ext_env = down_cast<JNIEnvExt*>(env);
if (!ext_env->locals_.Remove(ext_env->local_ref_cookie_, obj)) {
// Attempting to delete a local reference that is not in the
// topmost local reference frame is a no-op. DeleteLocalRef returns
// void and doesn't throw any exceptions, but we should probably
// complain about it so the user will notice that things aren't
// going quite the way they expect.
LOG(WARNING) << "JNI WARNING: DeleteLocalRef(" << obj << ") "
<< "failed to find entry";
}
}
static jboolean IsSameObject(JNIEnv* env, jobject obj1, jobject obj2) {
if (obj1 == obj2) {
return JNI_TRUE;
} else {
ScopedObjectAccess soa(env);
return (soa.Decode<mirror::Object>(obj1) == soa.Decode<mirror::Object>(obj2))
? JNI_TRUE : JNI_FALSE;
}
}
static jobject AllocObject(JNIEnv* env, jclass java_class) {
CHECK_NON_NULL_ARGUMENT(java_class);
ScopedObjectAccess soa(env);
ObjPtr<mirror::Class> c = EnsureInitialized(soa.Self(), soa.Decode<mirror::Class>(java_class));
if (c == nullptr) {
return nullptr;
}
if (c->IsStringClass()) {
gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
return soa.AddLocalReference<jobject>(mirror::String::AllocEmptyString<true>(soa.Self(),
allocator_type));
}
return soa.AddLocalReference<jobject>(c->AllocObject(soa.Self()));
}
static jobject NewObject(JNIEnv* env, jclass java_class, jmethodID mid, ...) {
va_list args;
va_start(args, mid);
ScopedVAArgs free_args_later(&args);
CHECK_NON_NULL_ARGUMENT(java_class);
CHECK_NON_NULL_ARGUMENT(mid);
jobject result = NewObjectV(env, java_class, mid, args);
return result;
}
static jobject NewObjectV(JNIEnv* env, jclass java_class, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT(java_class);
CHECK_NON_NULL_ARGUMENT(mid);
ScopedObjectAccess soa(env);
ObjPtr<mirror::Class> c = EnsureInitialized(soa.Self(),
soa.Decode<mirror::Class>(java_class));
if (c == nullptr) {
return nullptr;
}
if (c->IsStringClass()) {
// Replace calls to String.<init> with equivalent StringFactory call.
jmethodID sf_mid = jni::EncodeArtMethod(
WellKnownClasses::StringInitToStringFactory(jni::DecodeArtMethod(mid)));
return CallStaticObjectMethodV(env, WellKnownClasses::java_lang_StringFactory, sf_mid, args);
}
ObjPtr<mirror::Object> result = c->AllocObject(soa.Self());
if (result == nullptr) {
return nullptr;
}
jobject local_result = soa.AddLocalReference<jobject>(result);
CallNonvirtualVoidMethodV(env, local_result, java_class, mid, args);
if (soa.Self()->IsExceptionPending()) {
return nullptr;
}
return local_result;
}
static jobject NewObjectA(JNIEnv* env, jclass java_class, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT(java_class);
CHECK_NON_NULL_ARGUMENT(mid);
ScopedObjectAccess soa(env);
ObjPtr<mirror::Class> c = EnsureInitialized(soa.Self(),
soa.Decode<mirror::Class>(java_class));
if (c == nullptr) {
return nullptr;
}
if (c->IsStringClass()) {
// Replace calls to String.<init> with equivalent StringFactory call.
jmethodID sf_mid = jni::EncodeArtMethod(
WellKnownClasses::StringInitToStringFactory(jni::DecodeArtMethod(mid)));
return CallStaticObjectMethodA(env, WellKnownClasses::java_lang_StringFactory, sf_mid, args);
}
ObjPtr<mirror::Object> result = c->AllocObject(soa.Self());
if (result == nullptr) {
return nullptr;
}
jobject local_result = soa.AddLocalReference<jobjectArray>(result);
CallNonvirtualVoidMethodA(env, local_result, java_class, mid, args);
if (soa.Self()->IsExceptionPending()) {
return nullptr;
}
return local_result;
}
static jmethodID GetMethodID(JNIEnv* env, jclass java_class, const char* name, const char* sig) {
CHECK_NON_NULL_ARGUMENT(java_class);
CHECK_NON_NULL_ARGUMENT(name);
CHECK_NON_NULL_ARGUMENT(sig);
ScopedObjectAccess soa(env);
return FindMethodID(soa, java_class, name, sig, false);
}
static jmethodID GetStaticMethodID(JNIEnv* env, jclass java_class, const char* name,
const char* sig) {
CHECK_NON_NULL_ARGUMENT(java_class);
CHECK_NON_NULL_ARGUMENT(name);
CHECK_NON_NULL_ARGUMENT(sig);
ScopedObjectAccess soa(env);
return FindMethodID(soa, java_class, name, sig, true);
}
static jobject CallObjectMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT(obj);
CHECK_NON_NULL_ARGUMENT(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, ap));
return soa.AddLocalReference<jobject>(result.GetL());
}
static jobject CallObjectMethodV(JNIEnv* env, jobject obj, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT(obj);
CHECK_NON_NULL_ARGUMENT(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, args));
return soa.AddLocalReference<jobject>(result.GetL());
}
static jobject CallObjectMethodA(JNIEnv* env, jobject obj, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT(obj);
CHECK_NON_NULL_ARGUMENT(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args));
return soa.AddLocalReference<jobject>(result.GetL());
}
static jboolean CallBooleanMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, ap));
return result.GetZ();
}
static jboolean CallBooleanMethodV(JNIEnv* env, jobject obj, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, args).GetZ();
}
static jboolean CallBooleanMethodA(JNIEnv* env, jobject obj, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args).GetZ();
}
static jbyte CallByteMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, ap));
return result.GetB();
}
static jbyte CallByteMethodV(JNIEnv* env, jobject obj, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, args).GetB();
}
static jbyte CallByteMethodA(JNIEnv* env, jobject obj, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args).GetB();
}
static jchar CallCharMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, ap));
return result.GetC();
}
static jchar CallCharMethodV(JNIEnv* env, jobject obj, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, args).GetC();
}
static jchar CallCharMethodA(JNIEnv* env, jobject obj, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args).GetC();
}
static jdouble CallDoubleMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, ap));
return result.GetD();
}
static jdouble CallDoubleMethodV(JNIEnv* env, jobject obj, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, args).GetD();
}
static jdouble CallDoubleMethodA(JNIEnv* env, jobject obj, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args).GetD();
}
static jfloat CallFloatMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, ap));
return result.GetF();
}
static jfloat CallFloatMethodV(JNIEnv* env, jobject obj, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, args).GetF();
}
static jfloat CallFloatMethodA(JNIEnv* env, jobject obj, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args).GetF();
}
static jint CallIntMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, ap));
return result.GetI();
}
static jint CallIntMethodV(JNIEnv* env, jobject obj, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, args).GetI();
}
static jint CallIntMethodA(JNIEnv* env, jobject obj, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args).GetI();
}
static jlong CallLongMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, ap));
return result.GetJ();
}
static jlong CallLongMethodV(JNIEnv* env, jobject obj, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, args).GetJ();
}
static jlong CallLongMethodA(JNIEnv* env, jobject obj, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args).GetJ();
}
static jshort CallShortMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, ap));
return result.GetS();
}
static jshort CallShortMethodV(JNIEnv* env, jobject obj, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, args).GetS();
}
static jshort CallShortMethodA(JNIEnv* env, jobject obj, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args).GetS();
}
static void CallVoidMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(mid);
ScopedObjectAccess soa(env);
InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, ap);
}
static void CallVoidMethodV(JNIEnv* env, jobject obj, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(mid);
ScopedObjectAccess soa(env);
InvokeVirtualOrInterfaceWithVarArgs(soa, obj, mid, args);
}
static void CallVoidMethodA(JNIEnv* env, jobject obj, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(mid);
ScopedObjectAccess soa(env);
InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args);
}
static jobject CallNonvirtualObjectMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT(obj);
CHECK_NON_NULL_ARGUMENT(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, obj, mid, ap));
jobject local_result = soa.AddLocalReference<jobject>(result.GetL());
return local_result;
}
static jobject CallNonvirtualObjectMethodV(JNIEnv* env, jobject obj, jclass, jmethodID mid,
va_list args) {
CHECK_NON_NULL_ARGUMENT(obj);
CHECK_NON_NULL_ARGUMENT(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, obj, mid, args));
return soa.AddLocalReference<jobject>(result.GetL());
}
static jobject CallNonvirtualObjectMethodA(JNIEnv* env, jobject obj, jclass, jmethodID mid,
jvalue* args) {
CHECK_NON_NULL_ARGUMENT(obj);
CHECK_NON_NULL_ARGUMENT(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithJValues(soa, obj, mid, args));
return soa.AddLocalReference<jobject>(result.GetL());
}
static jboolean CallNonvirtualBooleanMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid,
...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, obj, mid, ap));
return result.GetZ();
}
static jboolean CallNonvirtualBooleanMethodV(JNIEnv* env, jobject obj, jclass, jmethodID mid,
va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithVarArgs(soa, obj, mid, args).GetZ();
}
static jboolean CallNonvirtualBooleanMethodA(JNIEnv* env, jobject obj, jclass, jmethodID mid,
jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithJValues(soa, obj, mid, args).GetZ();
}
static jbyte CallNonvirtualByteMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, obj, mid, ap));
return result.GetB();
}
static jbyte CallNonvirtualByteMethodV(JNIEnv* env, jobject obj, jclass, jmethodID mid,
va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithVarArgs(soa, obj, mid, args).GetB();
}
static jbyte CallNonvirtualByteMethodA(JNIEnv* env, jobject obj, jclass, jmethodID mid,
jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithJValues(soa, obj, mid, args).GetB();
}
static jchar CallNonvirtualCharMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, obj, mid, ap));
return result.GetC();
}
static jchar CallNonvirtualCharMethodV(JNIEnv* env, jobject obj, jclass, jmethodID mid,
va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithVarArgs(soa, obj, mid, args).GetC();
}
static jchar CallNonvirtualCharMethodA(JNIEnv* env, jobject obj, jclass, jmethodID mid,
jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithJValues(soa, obj, mid, args).GetC();
}
static jshort CallNonvirtualShortMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, obj, mid, ap));
return result.GetS();
}
static jshort CallNonvirtualShortMethodV(JNIEnv* env, jobject obj, jclass, jmethodID mid,
va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithVarArgs(soa, obj, mid, args).GetS();
}
static jshort CallNonvirtualShortMethodA(JNIEnv* env, jobject obj, jclass, jmethodID mid,
jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithJValues(soa, obj, mid, args).GetS();
}
static jint CallNonvirtualIntMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, obj, mid, ap));
return result.GetI();
}
static jint CallNonvirtualIntMethodV(JNIEnv* env, jobject obj, jclass, jmethodID mid,
va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithVarArgs(soa, obj, mid, args).GetI();
}
static jint CallNonvirtualIntMethodA(JNIEnv* env, jobject obj, jclass, jmethodID mid,
jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithJValues(soa, obj, mid, args).GetI();
}
static jlong CallNonvirtualLongMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, obj, mid, ap));
return result.GetJ();
}
static jlong CallNonvirtualLongMethodV(JNIEnv* env, jobject obj, jclass, jmethodID mid,
va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithVarArgs(soa, obj, mid, args).GetJ();
}
static jlong CallNonvirtualLongMethodA(JNIEnv* env, jobject obj, jclass, jmethodID mid,
jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithJValues(soa, obj, mid, args).GetJ();
}
static jfloat CallNonvirtualFloatMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, obj, mid, ap));
return result.GetF();
}
static jfloat CallNonvirtualFloatMethodV(JNIEnv* env, jobject obj, jclass, jmethodID mid,
va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithVarArgs(soa, obj, mid, args).GetF();
}
static jfloat CallNonvirtualFloatMethodA(JNIEnv* env, jobject obj, jclass, jmethodID mid,
jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithJValues(soa, obj, mid, args).GetF();
}
static jdouble CallNonvirtualDoubleMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, obj, mid, ap));
return result.GetD();
}
static jdouble CallNonvirtualDoubleMethodV(JNIEnv* env, jobject obj, jclass, jmethodID mid,
va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithVarArgs(soa, obj, mid, args).GetD();
}
static jdouble CallNonvirtualDoubleMethodA(JNIEnv* env, jobject obj, jclass, jmethodID mid,
jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithJValues(soa, obj, mid, args).GetD();
}
static void CallNonvirtualVoidMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(mid);
ScopedObjectAccess soa(env);
InvokeWithVarArgs(soa, obj, mid, ap);
}
static void CallNonvirtualVoidMethodV(JNIEnv* env, jobject obj, jclass, jmethodID mid,
va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(mid);
ScopedObjectAccess soa(env);
InvokeWithVarArgs(soa, obj, mid, args);
}
static void CallNonvirtualVoidMethodA(JNIEnv* env, jobject obj, jclass, jmethodID mid,
jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(obj);
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(mid);
ScopedObjectAccess soa(env);
InvokeWithJValues(soa, obj, mid, args);
}
static jfieldID GetFieldID(JNIEnv* env, jclass java_class, const char* name, const char* sig) {
CHECK_NON_NULL_ARGUMENT(java_class);
CHECK_NON_NULL_ARGUMENT(name);
CHECK_NON_NULL_ARGUMENT(sig);
ScopedObjectAccess soa(env);
return FindFieldID(soa, java_class, name, sig, false);
}
static jfieldID GetStaticFieldID(JNIEnv* env, jclass java_class, const char* name,
const char* sig) {
CHECK_NON_NULL_ARGUMENT(java_class);
CHECK_NON_NULL_ARGUMENT(name);
CHECK_NON_NULL_ARGUMENT(sig);
ScopedObjectAccess soa(env);
return FindFieldID(soa, java_class, name, sig, true);
}
static jobject GetObjectField(JNIEnv* env, jobject obj, jfieldID fid) {
CHECK_NON_NULL_ARGUMENT(obj);
CHECK_NON_NULL_ARGUMENT(fid);
ScopedObjectAccess soa(env);
ArtField* f = jni::DecodeArtField(fid);
NotifyGetField(f, obj);
ObjPtr<mirror::Object> o = soa.Decode<mirror::Object>(obj);
return soa.AddLocalReference<jobject>(f->GetObject(o));
}
static jobject GetStaticObjectField(JNIEnv* env, jclass, jfieldID fid) {
CHECK_NON_NULL_ARGUMENT(fid);
ScopedObjectAccess soa(env);
ArtField* f = jni::DecodeArtField(fid);
NotifyGetField(f, nullptr);
return soa.AddLocalReference<jobject>(f->GetObject(f->GetDeclaringClass()));
}
static void SetObjectField(JNIEnv* env, jobject java_object, jfieldID fid, jobject java_value) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(java_object);
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(fid);
ScopedObjectAccess soa(env);
ArtField* f = jni::DecodeArtField(fid);
NotifySetObjectField(f, java_object, java_value);
ObjPtr<mirror::Object> o = soa.Decode<mirror::Object>(java_object);
ObjPtr<mirror::Object> v = soa.Decode<mirror::Object>(java_value);
f->SetObject<false>(o, v);
}
static void SetStaticObjectField(JNIEnv* env, jclass, jfieldID fid, jobject java_value) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(fid);
ScopedObjectAccess soa(env);
ArtField* f = jni::DecodeArtField(fid);
NotifySetObjectField(f, nullptr, java_value);
ObjPtr<mirror::Object> v = soa.Decode<mirror::Object>(java_value);
f->SetObject<false>(f->GetDeclaringClass(), v);
}
#define GET_PRIMITIVE_FIELD(fn, instance) \
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(instance); \
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(fid); \
ScopedObjectAccess soa(env); \
ArtField* f = jni::DecodeArtField(fid); \
NotifyGetField(f, instance); \
ObjPtr<mirror::Object> o = soa.Decode<mirror::Object>(instance); \
return f->Get ##fn (o)
#define GET_STATIC_PRIMITIVE_FIELD(fn) \
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(fid); \
ScopedObjectAccess soa(env); \
ArtField* f = jni::DecodeArtField(fid); \
NotifyGetField(f, nullptr); \
return f->Get ##fn (f->GetDeclaringClass())
#define SET_PRIMITIVE_FIELD(fn, instance, value) \
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(instance); \
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(fid); \
ScopedObjectAccess soa(env); \
ArtField* f = jni::DecodeArtField(fid); \
NotifySetPrimitiveField(f, instance, JValue::FromPrimitive<decltype(value)>(value)); \
ObjPtr<mirror::Object> o = soa.Decode<mirror::Object>(instance); \
f->Set ##fn <false>(o, value)
#define SET_STATIC_PRIMITIVE_FIELD(fn, value) \
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(fid); \
ScopedObjectAccess soa(env); \
ArtField* f = jni::DecodeArtField(fid); \
NotifySetPrimitiveField(f, nullptr, JValue::FromPrimitive<decltype(value)>(value)); \
f->Set ##fn <false>(f->GetDeclaringClass(), value)
static jboolean GetBooleanField(JNIEnv* env, jobject obj, jfieldID fid) {
GET_PRIMITIVE_FIELD(Boolean, obj);
}
static jbyte GetByteField(JNIEnv* env, jobject obj, jfieldID fid) {
GET_PRIMITIVE_FIELD(Byte, obj);
}
static jchar GetCharField(JNIEnv* env, jobject obj, jfieldID fid) {
GET_PRIMITIVE_FIELD(Char, obj);
}
static jshort GetShortField(JNIEnv* env, jobject obj, jfieldID fid) {
GET_PRIMITIVE_FIELD(Short, obj);
}
static jint GetIntField(JNIEnv* env, jobject obj, jfieldID fid) {
GET_PRIMITIVE_FIELD(Int, obj);
}
static jlong GetLongField(JNIEnv* env, jobject obj, jfieldID fid) {
GET_PRIMITIVE_FIELD(Long, obj);
}
static jfloat GetFloatField(JNIEnv* env, jobject obj, jfieldID fid) {
GET_PRIMITIVE_FIELD(Float, obj);
}
static jdouble GetDoubleField(JNIEnv* env, jobject obj, jfieldID fid) {
GET_PRIMITIVE_FIELD(Double, obj);
}
static jboolean GetStaticBooleanField(JNIEnv* env, jclass, jfieldID fid) {
GET_STATIC_PRIMITIVE_FIELD(Boolean);
}
static jbyte GetStaticByteField(JNIEnv* env, jclass, jfieldID fid) {
GET_STATIC_PRIMITIVE_FIELD(Byte);
}
static jchar GetStaticCharField(JNIEnv* env, jclass, jfieldID fid) {
GET_STATIC_PRIMITIVE_FIELD(Char);
}
static jshort GetStaticShortField(JNIEnv* env, jclass, jfieldID fid) {
GET_STATIC_PRIMITIVE_FIELD(Short);
}
static jint GetStaticIntField(JNIEnv* env, jclass, jfieldID fid) {
GET_STATIC_PRIMITIVE_FIELD(Int);
}
static jlong GetStaticLongField(JNIEnv* env, jclass, jfieldID fid) {
GET_STATIC_PRIMITIVE_FIELD(Long);
}
static jfloat GetStaticFloatField(JNIEnv* env, jclass, jfieldID fid) {
GET_STATIC_PRIMITIVE_FIELD(Float);
}
static jdouble GetStaticDoubleField(JNIEnv* env, jclass, jfieldID fid) {
GET_STATIC_PRIMITIVE_FIELD(Double);
}
static void SetBooleanField(JNIEnv* env, jobject obj, jfieldID fid, jboolean v) {
SET_PRIMITIVE_FIELD(Boolean, obj, v);
}
static void SetByteField(JNIEnv* env, jobject obj, jfieldID fid, jbyte v) {
SET_PRIMITIVE_FIELD(Byte, obj, v);
}
static void SetCharField(JNIEnv* env, jobject obj, jfieldID fid, jchar v) {
SET_PRIMITIVE_FIELD(Char, obj, v);
}
static void SetFloatField(JNIEnv* env, jobject obj, jfieldID fid, jfloat v) {
SET_PRIMITIVE_FIELD(Float, obj, v);
}
static void SetDoubleField(JNIEnv* env, jobject obj, jfieldID fid, jdouble v) {
SET_PRIMITIVE_FIELD(Double, obj, v);
}
static void SetIntField(JNIEnv* env, jobject obj, jfieldID fid, jint v) {
SET_PRIMITIVE_FIELD(Int, obj, v);
}
static void SetLongField(JNIEnv* env, jobject obj, jfieldID fid, jlong v) {
SET_PRIMITIVE_FIELD(Long, obj, v);
}
static void SetShortField(JNIEnv* env, jobject obj, jfieldID fid, jshort v) {
SET_PRIMITIVE_FIELD(Short, obj, v);
}
static void SetStaticBooleanField(JNIEnv* env, jclass, jfieldID fid, jboolean v) {
SET_STATIC_PRIMITIVE_FIELD(Boolean, v);
}
static void SetStaticByteField(JNIEnv* env, jclass, jfieldID fid, jbyte v) {
SET_STATIC_PRIMITIVE_FIELD(Byte, v);
}
static void SetStaticCharField(JNIEnv* env, jclass, jfieldID fid, jchar v) {
SET_STATIC_PRIMITIVE_FIELD(Char, v);
}
static void SetStaticFloatField(JNIEnv* env, jclass, jfieldID fid, jfloat v) {
SET_STATIC_PRIMITIVE_FIELD(Float, v);
}
static void SetStaticDoubleField(JNIEnv* env, jclass, jfieldID fid, jdouble v) {
SET_STATIC_PRIMITIVE_FIELD(Double, v);
}
static void SetStaticIntField(JNIEnv* env, jclass, jfieldID fid, jint v) {
SET_STATIC_PRIMITIVE_FIELD(Int, v);
}
static void SetStaticLongField(JNIEnv* env, jclass, jfieldID fid, jlong v) {
SET_STATIC_PRIMITIVE_FIELD(Long, v);
}
static void SetStaticShortField(JNIEnv* env, jclass, jfieldID fid, jshort v) {
SET_STATIC_PRIMITIVE_FIELD(Short, v);
}
static jobject CallStaticObjectMethod(JNIEnv* env, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, nullptr, mid, ap));
jobject local_result = soa.AddLocalReference<jobject>(result.GetL());
return local_result;
}
static jobject CallStaticObjectMethodV(JNIEnv* env, jclass, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, nullptr, mid, args));
return soa.AddLocalReference<jobject>(result.GetL());
}
static jobject CallStaticObjectMethodA(JNIEnv* env, jclass, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithJValues(soa, nullptr, mid, args));
return soa.AddLocalReference<jobject>(result.GetL());
}
static jboolean CallStaticBooleanMethod(JNIEnv* env, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, nullptr, mid, ap));
return result.GetZ();
}
static jboolean CallStaticBooleanMethodV(JNIEnv* env, jclass, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithVarArgs(soa, nullptr, mid, args).GetZ();
}
static jboolean CallStaticBooleanMethodA(JNIEnv* env, jclass, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithJValues(soa, nullptr, mid, args).GetZ();
}
static jbyte CallStaticByteMethod(JNIEnv* env, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, nullptr, mid, ap));
return result.GetB();
}
static jbyte CallStaticByteMethodV(JNIEnv* env, jclass, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithVarArgs(soa, nullptr, mid, args).GetB();
}
static jbyte CallStaticByteMethodA(JNIEnv* env, jclass, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithJValues(soa, nullptr, mid, args).GetB();
}
static jchar CallStaticCharMethod(JNIEnv* env, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, nullptr, mid, ap));
return result.GetC();
}
static jchar CallStaticCharMethodV(JNIEnv* env, jclass, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithVarArgs(soa, nullptr, mid, args).GetC();
}
static jchar CallStaticCharMethodA(JNIEnv* env, jclass, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithJValues(soa, nullptr, mid, args).GetC();
}
static jshort CallStaticShortMethod(JNIEnv* env, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, nullptr, mid, ap));
return result.GetS();
}
static jshort CallStaticShortMethodV(JNIEnv* env, jclass, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithVarArgs(soa, nullptr, mid, args).GetS();
}
static jshort CallStaticShortMethodA(JNIEnv* env, jclass, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithJValues(soa, nullptr, mid, args).GetS();
}
static jint CallStaticIntMethod(JNIEnv* env, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, nullptr, mid, ap));
return result.GetI();
}
static jint CallStaticIntMethodV(JNIEnv* env, jclass, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithVarArgs(soa, nullptr, mid, args).GetI();
}
static jint CallStaticIntMethodA(JNIEnv* env, jclass, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithJValues(soa, nullptr, mid, args).GetI();
}
static jlong CallStaticLongMethod(JNIEnv* env, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, nullptr, mid, ap));
return result.GetJ();
}
static jlong CallStaticLongMethodV(JNIEnv* env, jclass, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithVarArgs(soa, nullptr, mid, args).GetJ();
}
static jlong CallStaticLongMethodA(JNIEnv* env, jclass, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithJValues(soa, nullptr, mid, args).GetJ();
}
static jfloat CallStaticFloatMethod(JNIEnv* env, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, nullptr, mid, ap));
return result.GetF();
}
static jfloat CallStaticFloatMethodV(JNIEnv* env, jclass, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithVarArgs(soa, nullptr, mid, args).GetF();
}
static jfloat CallStaticFloatMethodA(JNIEnv* env, jclass, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithJValues(soa, nullptr, mid, args).GetF();
}
static jdouble CallStaticDoubleMethod(JNIEnv* env, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
JValue result(InvokeWithVarArgs(soa, nullptr, mid, ap));
return result.GetD();
}
static jdouble CallStaticDoubleMethodV(JNIEnv* env, jclass, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithVarArgs(soa, nullptr, mid, args).GetD();
}
static jdouble CallStaticDoubleMethodA(JNIEnv* env, jclass, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid);
ScopedObjectAccess soa(env);
return InvokeWithJValues(soa, nullptr, mid, args).GetD();
}
static void CallStaticVoidMethod(JNIEnv* env, jclass, jmethodID mid, ...) {
va_list ap;
va_start(ap, mid);
ScopedVAArgs free_args_later(&ap);
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(mid);
ScopedObjectAccess soa(env);
InvokeWithVarArgs(soa, nullptr, mid, ap);
}
static void CallStaticVoidMethodV(JNIEnv* env, jclass, jmethodID mid, va_list args) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(mid);
ScopedObjectAccess soa(env);
InvokeWithVarArgs(soa, nullptr, mid, args);
}
static void CallStaticVoidMethodA(JNIEnv* env, jclass, jmethodID mid, jvalue* args) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(mid);
ScopedObjectAccess soa(env);
InvokeWithJValues(soa, nullptr, mid, args);
}
static jstring NewString(JNIEnv* env, const jchar* chars, jsize char_count) {
if (UNLIKELY(char_count < 0)) {
JavaVmExtFromEnv(env)->JniAbortF("NewString", "char_count < 0: %d", char_count);
return nullptr;
}
if (UNLIKELY(chars == nullptr && char_count > 0)) {
JavaVmExtFromEnv(env)->JniAbortF("NewString", "chars == null && char_count > 0");
return nullptr;
}
ScopedObjectAccess soa(env);
mirror::String* result = mirror::String::AllocFromUtf16(soa.Self(), char_count, chars);
return soa.AddLocalReference<jstring>(result);
}
static jstring NewStringUTF(JNIEnv* env, const char* utf) {
if (utf == nullptr) {
return nullptr;
}
ScopedObjectAccess soa(env);
mirror::String* result = mirror::String::AllocFromModifiedUtf8(soa.Self(), utf);
return soa.AddLocalReference<jstring>(result);
}
static jsize GetStringLength(JNIEnv* env, jstring java_string) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(java_string);
ScopedObjectAccess soa(env);
return soa.Decode<mirror::String>(java_string)->GetLength();
}
static jsize GetStringUTFLength(JNIEnv* env, jstring java_string) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(java_string);
ScopedObjectAccess soa(env);
return soa.Decode<mirror::String>(java_string)->GetUtfLength();
}
static void GetStringRegion(JNIEnv* env, jstring java_string, jsize start, jsize length,
jchar* buf) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(java_string);
ScopedObjectAccess soa(env);
ObjPtr<mirror::String> s = soa.Decode<mirror::String>(java_string);
if (start < 0 || length < 0 || length > s->GetLength() - start) {
ThrowSIOOBE(soa, start, length, s->GetLength());
} else {
CHECK_NON_NULL_MEMCPY_ARGUMENT(length, buf);
if (s->IsCompressed()) {
for (int i = 0; i < length; ++i) {
buf[i] = static_cast<jchar>(s->CharAt(start+i));
}
} else {
const jchar* chars = static_cast<jchar*>(s->GetValue());
memcpy(buf, chars + start, length * sizeof(jchar));
}
}
}
static void GetStringUTFRegion(JNIEnv* env, jstring java_string, jsize start, jsize length,
char* buf) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(java_string);
ScopedObjectAccess soa(env);
ObjPtr<mirror::String> s = soa.Decode<mirror::String>(java_string);
if (start < 0 || length < 0 || length > s->GetLength() - start) {
ThrowSIOOBE(soa, start, length, s->GetLength());
} else {
CHECK_NON_NULL_MEMCPY_ARGUMENT(length, buf);
if (s->IsCompressed()) {
for (int i = 0; i < length; ++i) {
buf[i] = s->CharAt(start+i);
}
} else {
const jchar* chars = s->GetValue();
size_t bytes = CountUtf8Bytes(chars + start, length);
ConvertUtf16ToModifiedUtf8(buf, bytes, chars + start, length);
}
}
}
static const jchar* GetStringChars(JNIEnv* env, jstring java_string, jboolean* is_copy) {
CHECK_NON_NULL_ARGUMENT(java_string);
ScopedObjectAccess soa(env);
ObjPtr<mirror::String> s = soa.Decode<mirror::String>(java_string);
gc::Heap* heap = Runtime::Current()->GetHeap();
if (heap->IsMovableObject(s) || s->IsCompressed()) {
jchar* chars = new jchar[s->GetLength()];
if (s->IsCompressed()) {
int32_t length = s->GetLength();
for (int i = 0; i < length; ++i) {
chars[i] = s->CharAt(i);
}
} else {
memcpy(chars, s->GetValue(), sizeof(jchar) * s->GetLength());
}
if (is_copy != nullptr) {
*is_copy = JNI_TRUE;
}
return chars;
}
if (is_copy != nullptr) {
*is_copy = JNI_FALSE;
}
return static_cast<jchar*>(s->GetValue());
}
static void ReleaseStringChars(JNIEnv* env, jstring java_string, const jchar* chars) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(java_string);
ScopedObjectAccess soa(env);
ObjPtr<mirror::String> s = soa.Decode<mirror::String>(java_string);
if (s->IsCompressed() || (s->IsCompressed() == false && chars != s->GetValue())) {
delete[] chars;
}
}
static const jchar* GetStringCritical(JNIEnv* env, jstring java_string, jboolean* is_copy) {
CHECK_NON_NULL_ARGUMENT(java_string);
ScopedObjectAccess soa(env);
ObjPtr<mirror::String> s = soa.Decode<mirror::String>(java_string);
gc::Heap* heap = Runtime::Current()->GetHeap();
if (heap->IsMovableObject(s)) {
StackHandleScope<1> hs(soa.Self());
HandleWrapperObjPtr<mirror::String> h(hs.NewHandleWrapper(&s));
if (!kUseReadBarrier) {
heap->IncrementDisableMovingGC(soa.Self());
} else {
// For the CC collector, we only need to wait for the thread flip rather than the whole GC
// to occur thanks to the to-space invariant.
heap->IncrementDisableThreadFlip(soa.Self());
}
}
if (s->IsCompressed()) {
if (is_copy != nullptr) {
*is_copy = JNI_TRUE;
}
int32_t length = s->GetLength();
jchar* chars = new jchar[length];
for (int i = 0; i < length; ++i) {
chars[i] = s->CharAt(i);
}
return chars;
} else {
if (is_copy != nullptr) {
*is_copy = JNI_FALSE;
}
return static_cast<jchar*>(s->GetValue());
}
}
static void ReleaseStringCritical(JNIEnv* env,
jstring java_string,
const jchar* chars) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(java_string);
ScopedObjectAccess soa(env);
gc::Heap* heap = Runtime::Current()->GetHeap();
ObjPtr<mirror::String> s = soa.Decode<mirror::String>(java_string);
if (heap->IsMovableObject(s)) {
if (!kUseReadBarrier) {
heap->DecrementDisableMovingGC(soa.Self());
} else {
heap->DecrementDisableThreadFlip(soa.Self());
}
}
if (s->IsCompressed() || (s->IsCompressed() == false && s->GetValue() != chars)) {
delete[] chars;
}
}
static const char* GetStringUTFChars(JNIEnv* env, jstring java_string, jboolean* is_copy) {
if (java_string == nullptr) {
return nullptr;
}
if (is_copy != nullptr) {
*is_copy = JNI_TRUE;
}
ScopedObjectAccess soa(env);
ObjPtr<mirror::String> s = soa.Decode<mirror::String>(java_string);
size_t byte_count = s->GetUtfLength();
char* bytes = new char[byte_count + 1];
CHECK(bytes != nullptr); // bionic aborts anyway.
if (s->IsCompressed()) {
for (size_t i = 0; i < byte_count; ++i) {
bytes[i] = s->CharAt(i);
}
} else {
const uint16_t* chars = s->GetValue();
ConvertUtf16ToModifiedUtf8(bytes, byte_count, chars, s->GetLength());
}
bytes[byte_count] = '\0';
return bytes;
}
static void ReleaseStringUTFChars(JNIEnv*, jstring, const char* chars) {
delete[] chars;
}
static jsize GetArrayLength(JNIEnv* env, jarray java_array) {
CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(java_array);
ScopedObjectAccess soa(env);
ObjPtr<mirror::Object> obj = soa.Decode<mirror::Object>(java_array);
if (UNLIKELY(!obj->IsArrayInstance())) {
soa.Vm()->JniAbortF("GetArrayLength", "not an array: %s", obj->PrettyTypeOf().c_str());
return 0;
}
mirror::Array* array = obj->AsArray();
return array->GetLength();
}
static jobject GetObjectArrayElement(JNIEnv* env, jobjectArray java_array, jsize index) {
CHECK_NON_NULL_ARGUMENT(java_array);
ScopedObjectAccess soa(env);
ObjPtr<mirror::ObjectArray<mirror::Object>> array =
soa.Decode<mirror::ObjectArray<mirror::Object>>(java_array);
return soa.AddLocalReference<jobject>(array->Get(index));
}
static void SetObjectArrayElement(JNIEnv* env, jobjectArray java_array, jsize index,
jobject java_value) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(java_array);
ScopedObjectAccess soa(env);
ObjPtr<mirror::ObjectArray<mirror::Object>> array =
soa.Decode<mirror::ObjectArray<mirror::Object>>(java_array);
ObjPtr<mirror::Object> value = soa.Decode<mirror::Object>(java_value);
array->Set<false>(index, value.Ptr());
}
static jbooleanArray NewBooleanArray(JNIEnv* env, jsize length) {
return NewPrimitiveArray<jbooleanArray, mirror::BooleanArray>(env, length);
}
static jbyteArray NewByteArray(JNIEnv* env, jsize length) {
return NewPrimitiveArray<jbyteArray, mirror::ByteArray>(env, length);
}
static jcharArray NewCharArray(JNIEnv* env, jsize length) {
return NewPrimitiveArray<jcharArray, mirror::CharArray>(env, length);
}
static jdoubleArray NewDoubleArray(JNIEnv* env, jsize length) {
return NewPrimitiveArray<jdoubleArray, mirror::DoubleArray>(env, length);
}
static jfloatArray NewFloatArray(JNIEnv* env, jsize length) {
return NewPrimitiveArray<jfloatArray, mirror::FloatArray>(env, length);
}
static jintArray NewIntArray(JNIEnv* env, jsize length) {
return NewPrimitiveArray<jintArray, mirror::IntArray>(env, length);
}
static jlongArray NewLongArray(JNIEnv* env, jsize length) {
return NewPrimitiveArray<jlongArray, mirror::LongArray>(env, length);
}
static jobjectArray NewObjectArray(JNIEnv* env, jsize length, jclass element_jclass,
jobject initial_element) {
if (UNLIKELY(length < 0)) {
JavaVmExtFromEnv(env)->JniAbortF("NewObjectArray", "negative array length: %d", length);
return nullptr;
}
CHECK_NON_NULL_ARGUMENT(element_jclass);
// Compute the array class corresponding to the given element class.
ScopedObjectAccess soa(env);
ObjPtr<mirror::Class> array_class;
{
ObjPtr<mirror::Class> element_class = soa.Decode<mirror::Class>(element_jclass).Ptr();
if (UNLIKELY(element_class->IsPrimitive())) {
soa.Vm()->JniAbortF("NewObjectArray",
"not an object type: %s",
element_class->PrettyDescriptor().c_str());
return nullptr;
}
ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
array_class = class_linker->FindArrayClass(soa.Self(), &element_class);
if (UNLIKELY(array_class == nullptr)) {
return nullptr;
}
}
// Allocate and initialize if necessary.
mirror::ObjectArray<mirror::Object>* result =
mirror::ObjectArray<mirror::Object>::Alloc(soa.Self(), array_class, length);
if (result != nullptr && initial_element != nullptr) {
ObjPtr<mirror::Object> initial_object = soa.Decode<mirror::Object>(initial_element);
if (initial_object != nullptr) {
mirror::Class* element_class = result->GetClass()->GetComponentType();
if (UNLIKELY(!element_class->IsAssignableFrom(initial_object->GetClass()))) {
soa.Vm()->JniAbortF("NewObjectArray", "cannot assign object of type '%s' to array with "
"element type of '%s'",
mirror::Class::PrettyDescriptor(initial_object->GetClass()).c_str(),
element_class->PrettyDescriptor().c_str());
return nullptr;
} else {
for (jsize i = 0; i < length; ++i) {
result->SetWithoutChecks<false>(i, initial_object.Ptr());
}
}
}
}
return soa.AddLocalReference<jobjectArray>(result);
}
static jshortArray NewShortArray(JNIEnv* env, jsize length) {
return NewPrimitiveArray<jshortArray, mirror::ShortArray>(env, length);
}
static void* GetPrimitiveArrayCritical(JNIEnv* env, jarray java_array, jboolean* is_copy) {
CHECK_NON_NULL_ARGUMENT(java_array);
ScopedObjectAccess soa(env);
ObjPtr<mirror::Array> array = soa.Decode<mirror::Array>(java_array);
if (UNLIKELY(!array->GetClass()->IsPrimitiveArray())) {
soa.Vm()->JniAbortF("GetPrimitiveArrayCritical", "expected primitive array, given %s",
array->GetClass()->PrettyDescriptor().c_str());
return nullptr;
}
gc::Heap* heap = Runtime::Current()->GetHeap();
if (heap->IsMovableObject(array)) {
if (!kUseReadBarrier) {
heap->IncrementDisableMovingGC(soa.Self());
} else {
// For the CC collector, we only need to wait for the thread flip rather than the whole GC
// to occur thanks to the to-space invariant.
heap->IncrementDisableThreadFlip(soa.Self());
}
// Re-decode in case the object moved since IncrementDisableGC waits for GC to complete.
array = soa.Decode<mirror::Array>(java_array);
}
if (is_copy != nullptr) {
*is_copy = JNI_FALSE;
}
return array->GetRawData(array->GetClass()->GetComponentSize(), 0);
}
static void ReleasePrimitiveArrayCritical(JNIEnv* env, jarray java_array, void* elements,
jint mode) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(java_array);
ScopedObjectAccess soa(env);
ObjPtr<mirror::Array> array = soa.Decode<mirror::Array>(java_array);
if (UNLIKELY(!array->GetClass()->IsPrimitiveArray())) {
soa.Vm()->JniAbortF("ReleasePrimitiveArrayCritical", "expected primitive array, given %s",
array->GetClass()->PrettyDescriptor().c_str());
return;
}
const size_t component_size = array->GetClass()->GetComponentSize();
ReleasePrimitiveArray(soa, array.Ptr(), component_size, elements, mode);
}
static jboolean* GetBooleanArrayElements(JNIEnv* env, jbooleanArray array, jboolean* is_copy) {
return GetPrimitiveArray<jbooleanArray, jboolean, mirror::BooleanArray>(env, array, is_copy);
}
static jbyte* GetByteArrayElements(JNIEnv* env, jbyteArray array, jboolean* is_copy) {
return GetPrimitiveArray<jbyteArray, jbyte, mirror::ByteArray>(env, array, is_copy);
}
static jchar* GetCharArrayElements(JNIEnv* env, jcharArray array, jboolean* is_copy) {
return GetPrimitiveArray<jcharArray, jchar, mirror::CharArray>(env, array, is_copy);
}
static jdouble* GetDoubleArrayElements(JNIEnv* env, jdoubleArray array, jboolean* is_copy) {
return GetPrimitiveArray<jdoubleArray, jdouble, mirror::DoubleArray>(env, array, is_copy);
}
static jfloat* GetFloatArrayElements(JNIEnv* env, jfloatArray array, jboolean* is_copy) {
return GetPrimitiveArray<jfloatArray, jfloat, mirror::FloatArray>(env, array, is_copy);
}
static jint* GetIntArrayElements(JNIEnv* env, jintArray array, jboolean* is_copy) {
return GetPrimitiveArray<jintArray, jint, mirror::IntArray>(env, array, is_copy);
}
static jlong* GetLongArrayElements(JNIEnv* env, jlongArray array, jboolean* is_copy) {
return GetPrimitiveArray<jlongArray, jlong, mirror::LongArray>(env, array, is_copy);
}
static jshort* GetShortArrayElements(JNIEnv* env, jshortArray array, jboolean* is_copy) {
return GetPrimitiveArray<jshortArray, jshort, mirror::ShortArray>(env, array, is_copy);
}
static void ReleaseBooleanArrayElements(JNIEnv* env, jbooleanArray array, jboolean* elements,
jint mode) {
ReleasePrimitiveArray<jbooleanArray, jboolean, mirror::BooleanArray>(env, array, elements,
mode);
}
static void ReleaseByteArrayElements(JNIEnv* env, jbyteArray array, jbyte* elements, jint mode) {
ReleasePrimitiveArray<jbyteArray, jbyte, mirror::ByteArray>(env, array, elements, mode);
}
static void ReleaseCharArrayElements(JNIEnv* env, jcharArray array, jchar* elements, jint mode) {
ReleasePrimitiveArray<jcharArray, jchar, mirror::CharArray>(env, array, elements, mode);
}
static void ReleaseDoubleArrayElements(JNIEnv* env, jdoubleArray array, jdouble* elements,
jint mode) {
ReleasePrimitiveArray<jdoubleArray, jdouble, mirror::DoubleArray>(env, array, elements, mode);
}
static void ReleaseFloatArrayElements(JNIEnv* env, jfloatArray array, jfloat* elements,
jint mode) {
ReleasePrimitiveArray<jfloatArray, jfloat, mirror::FloatArray>(env, array, elements, mode);
}
static void ReleaseIntArrayElements(JNIEnv* env, jintArray array, jint* elements, jint mode) {
ReleasePrimitiveArray<jintArray, jint, mirror::IntArray>(env, array, elements, mode);
}
static void ReleaseLongArrayElements(JNIEnv* env, jlongArray array, jlong* elements, jint mode) {
ReleasePrimitiveArray<jlongArray, jlong, mirror::LongArray>(env, array, elements, mode);
}
static void ReleaseShortArrayElements(JNIEnv* env, jshortArray array, jshort* elements,
jint mode) {
ReleasePrimitiveArray<jshortArray, jshort, mirror::ShortArray>(env, array, elements, mode);
}
static void GetBooleanArrayRegion(JNIEnv* env, jbooleanArray array, jsize start, jsize length,
jboolean* buf) {
GetPrimitiveArrayRegion<jbooleanArray, jboolean, mirror::BooleanArray>(env, array, start,
length, buf);
}
static void GetByteArrayRegion(JNIEnv* env, jbyteArray array, jsize start, jsize length,
jbyte* buf) {
GetPrimitiveArrayRegion<jbyteArray, jbyte, mirror::ByteArray>(env, array, start, length, buf);
}
static void GetCharArrayRegion(JNIEnv* env, jcharArray array, jsize start, jsize length,
jchar* buf) {
GetPrimitiveArrayRegion<jcharArray, jchar, mirror::CharArray>(env, array, start, length, buf);
}
static void GetDoubleArrayRegion(JNIEnv* env, jdoubleArray array, jsize start, jsize length,
jdouble* buf) {
GetPrimitiveArrayRegion<jdoubleArray, jdouble, mirror::DoubleArray>(env, array, start, length,
buf);
}
static void GetFloatArrayRegion(JNIEnv* env, jfloatArray array, jsize start, jsize length,
jfloat* buf) {
GetPrimitiveArrayRegion<jfloatArray, jfloat, mirror::FloatArray>(env, array, start, length,
buf);
}
static void GetIntArrayRegion(JNIEnv* env, jintArray array, jsize start, jsize length,
jint* buf) {
GetPrimitiveArrayRegion<jintArray, jint, mirror::IntArray>(env, array, start, length, buf);
}
static void GetLongArrayRegion(JNIEnv* env, jlongArray array, jsize start, jsize length,
jlong* buf) {
GetPrimitiveArrayRegion<jlongArray, jlong, mirror::LongArray>(env, array, start, length, buf);
}
static void GetShortArrayRegion(JNIEnv* env, jshortArray array, jsize start, jsize length,
jshort* buf) {
GetPrimitiveArrayRegion<jshortArray, jshort, mirror::ShortArray>(env, array, start, length,
buf);
}
static void SetBooleanArrayRegion(JNIEnv* env, jbooleanArray array, jsize start, jsize length,
const jboolean* buf) {
SetPrimitiveArrayRegion<jbooleanArray, jboolean, mirror::BooleanArray>(env, array, start,
length, buf);
}
static void SetByteArrayRegion(JNIEnv* env, jbyteArray array, jsize start, jsize length,
const jbyte* buf) {
SetPrimitiveArrayRegion<jbyteArray, jbyte, mirror::ByteArray>(env, array, start, length, buf);
}
static void SetCharArrayRegion(JNIEnv* env, jcharArray array, jsize start, jsize length,
const jchar* buf) {
SetPrimitiveArrayRegion<jcharArray, jchar, mirror::CharArray>(env, array, start, length, buf);
}
static void SetDoubleArrayRegion(JNIEnv* env, jdoubleArray array, jsize start, jsize length,
const jdouble* buf) {
SetPrimitiveArrayRegion<jdoubleArray, jdouble, mirror::DoubleArray>(env, array, start, length,
buf);
}
static void SetFloatArrayRegion(JNIEnv* env, jfloatArray array, jsize start, jsize length,
const jfloat* buf) {
SetPrimitiveArrayRegion<jfloatArray, jfloat, mirror::FloatArray>(env, array, start, length,
buf);
}
static void SetIntArrayRegion(JNIEnv* env, jintArray array, jsize start, jsize length,
const jint* buf) {
SetPrimitiveArrayRegion<jintArray, jint, mirror::IntArray>(env, array, start, length, buf);
}
static void SetLongArrayRegion(JNIEnv* env, jlongArray array, jsize start, jsize length,
const jlong* buf) {
SetPrimitiveArrayRegion<jlongArray, jlong, mirror::LongArray>(env, array, start, length, buf);
}
static void SetShortArrayRegion(JNIEnv* env, jshortArray array, jsize start, jsize length,
const jshort* buf) {
SetPrimitiveArrayRegion<jshortArray, jshort, mirror::ShortArray>(env, array, start, length,
buf);
}
static jint RegisterNatives(JNIEnv* env,
jclass java_class,
const JNINativeMethod* methods,
jint method_count) {
if (UNLIKELY(method_count < 0)) {
JavaVmExtFromEnv(env)->JniAbortF("RegisterNatives", "negative method count: %d",
method_count);
return JNI_ERR; // Not reached except in unit tests.
}
CHECK_NON_NULL_ARGUMENT_FN_NAME("RegisterNatives", java_class, JNI_ERR);
ScopedObjectAccess soa(env);
StackHandleScope<1> hs(soa.Self());
Handle<mirror::Class> c = hs.NewHandle(soa.Decode<mirror::Class>(java_class));
if (UNLIKELY(method_count == 0)) {
LOG(WARNING) << "JNI RegisterNativeMethods: attempt to register 0 native methods for "
<< c->PrettyDescriptor();
return JNI_OK;
}
CHECK_NON_NULL_ARGUMENT_FN_NAME("RegisterNatives", methods, JNI_ERR);
for (jint i = 0; i < method_count; ++i) {
const char* name = methods[i].name;
const char* sig = methods[i].signature;
const void* fnPtr = methods[i].fnPtr;
if (UNLIKELY(name == nullptr)) {
ReportInvalidJNINativeMethod(soa, c.Get(), "method name", i);
return JNI_ERR;
} else if (UNLIKELY(sig == nullptr)) {
ReportInvalidJNINativeMethod(soa, c.Get(), "method signature", i);
return JNI_ERR;
} else if (UNLIKELY(fnPtr == nullptr)) {
ReportInvalidJNINativeMethod(soa, c.Get(), "native function", i);
return JNI_ERR;
}
bool is_fast = false;
// Notes about fast JNI calls:
//
// On a normal JNI call, the calling thread usually transitions
// from the kRunnable state to the kNative state. But if the
// called native function needs to access any Java object, it
// will have to transition back to the kRunnable state.
//
// There is a cost to this double transition. For a JNI call
// that should be quick, this cost may dominate the call cost.
//
// On a fast JNI call, the calling thread avoids this double
// transition by not transitioning from kRunnable to kNative and
// stays in the kRunnable state.
//
// There are risks to using a fast JNI call because it can delay
// a response to a thread suspension request which is typically
// used for a GC root scanning, etc. If a fast JNI call takes a
// long time, it could cause longer thread suspension latency
// and GC pauses.
//
// Thus, fast JNI should be used with care. It should be used
// for a JNI call that takes a short amount of time (eg. no
// long-running loop) and does not block (eg. no locks, I/O,
// etc.)
//
// A '!' prefix in the signature in the JNINativeMethod
// indicates that it's a fast JNI call and the runtime omits the
// thread state transition from kRunnable to kNative at the
// entry.
if (*sig == '!') {
is_fast = true;
++sig;
}
// Note: the right order is to try to find the method locally
// first, either as a direct or a virtual method. Then move to
// the parent.
ArtMethod* m = nullptr;
bool warn_on_going_to_parent = down_cast<JNIEnvExt*>(env)->GetVm()->IsCheckJniEnabled();
for (ObjPtr<mirror::Class> current_class = c.Get();
current_class != nullptr;
current_class = current_class->GetSuperClass()) {
// Search first only comparing methods which are native.
m = FindMethod<true>(current_class.Ptr(), name, sig);
if (m != nullptr) {
break;
}
// Search again comparing to all methods, to find non-native methods that match.
m = FindMethod<false>(current_class.Ptr(), name, sig);
if (m != nullptr) {
break;
}
if (warn_on_going_to_parent) {
LOG(WARNING) << "CheckJNI: method to register \"" << name << "\" not in the given class. "
<< "This is slow, consider changing your RegisterNatives calls.";
warn_on_going_to_parent = false;
}
}
if (m == nullptr) {
c->DumpClass(LOG_STREAM(ERROR), mirror::Class::kDumpClassFullDetail);
LOG(ERROR)
<< "Failed to register native method "
<< c->PrettyDescriptor() << "." << name << sig << " in "
<< c->GetDexCache()->GetLocation()->ToModifiedUtf8();
ThrowNoSuchMethodError(soa, c.Get(), name, sig, "static or non-static");
return JNI_ERR;
} else if (!m->IsNative()) {
LOG(ERROR)
<< "Failed to register non-native method "
<< c->PrettyDescriptor() << "." << name << sig
<< " as native";
ThrowNoSuchMethodError(soa, c.Get(), name, sig, "native");
return JNI_ERR;
}
VLOG(jni) << "[Registering JNI native method " << m->PrettyMethod() << "]";
if (UNLIKELY(is_fast)) {
// There are a few reasons to switch:
// 1) We don't support !bang JNI anymore, it will turn to a hard error later.
// 2) @FastNative is actually faster. At least 1.5x faster than !bang JNI.
// and switching is super easy, remove ! in C code, add annotation in .java code.
// 3) Good chance of hitting DCHECK failures in ScopedFastNativeObjectAccess
// since that checks for presence of @FastNative and not for ! in the descriptor.
LOG(WARNING) << "!bang JNI is deprecated. Switch to @FastNative for " << m->PrettyMethod();
is_fast = false;
// TODO: make this a hard register error in the future.
}
const void* final_function_ptr = m->RegisterNative(fnPtr);
UNUSED(final_function_ptr);
}
return JNI_OK;
}
static jint UnregisterNatives(JNIEnv* env, jclass java_class) {
CHECK_NON_NULL_ARGUMENT_RETURN(java_class, JNI_ERR);
ScopedObjectAccess soa(env);
ObjPtr<mirror::Class> c = soa.Decode<mirror::Class>(java_class);
VLOG(jni) << "[Unregistering JNI native methods for " << mirror::Class::PrettyClass(c) << "]";
size_t unregistered_count = 0;
auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
for (auto& m : c->GetMethods(pointer_size)) {
if (m.IsNative()) {
m.UnregisterNative();
unregistered_count++;
}
}
if (unregistered_count == 0) {
LOG(WARNING) << "JNI UnregisterNatives: attempt to unregister native methods of class '"
<< mirror::Class::PrettyDescriptor(c) << "' that contains no native methods";
}
return JNI_OK;
}
static jint MonitorEnter(JNIEnv* env, jobject java_object) NO_THREAD_SAFETY_ANALYSIS {
CHECK_NON_NULL_ARGUMENT_RETURN(java_object, JNI_ERR);
ScopedObjectAccess soa(env);
ObjPtr<mirror::Object> o = soa.Decode<mirror::Object>(java_object);
o = o->MonitorEnter(soa.Self());
if (soa.Self()->HoldsLock(o)) {
soa.Env()->monitors_.Add(o);
}
if (soa.Self()->IsExceptionPending()) {
return JNI_ERR;
}
return JNI_OK;
}
static jint MonitorExit(JNIEnv* env, jobject java_object) NO_THREAD_SAFETY_ANALYSIS {
CHECK_NON_NULL_ARGUMENT_RETURN(java_object, JNI_ERR);
ScopedObjectAccess soa(env);
ObjPtr<mirror::Object> o = soa.Decode<mirror::Object>(java_object);
bool remove_mon = soa.Self()->HoldsLock(o);
o->MonitorExit(soa.Self());
if (remove_mon) {
soa.Env()->monitors_.Remove(o);
}
if (soa.Self()->IsExceptionPending()) {
return JNI_ERR;
}
return JNI_OK;
}
static jint GetJavaVM(JNIEnv* env, JavaVM** vm) {
CHECK_NON_NULL_ARGUMENT_RETURN(vm, JNI_ERR);
Runtime* runtime = Runtime::Current();
if (runtime != nullptr) {
*vm = runtime->GetJavaVM();
} else {
*vm = nullptr;
}
return (*vm != nullptr) ? JNI_OK : JNI_ERR;
}
static jobject NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity) {
if (capacity < 0) {
JavaVmExtFromEnv(env)->JniAbortF("NewDirectByteBuffer", "negative buffer capacity: %" PRId64,
capacity);
return nullptr;
}
if (address == nullptr && capacity != 0) {
JavaVmExtFromEnv(env)->JniAbortF("NewDirectByteBuffer",
"non-zero capacity for nullptr pointer: %" PRId64, capacity);
return nullptr;
}
// At the moment, the capacity of DirectByteBuffer is limited to a signed int.
if (capacity > INT_MAX) {
JavaVmExtFromEnv(env)->JniAbortF("NewDirectByteBuffer",
"buffer capacity greater than maximum jint: %" PRId64,
capacity);
return nullptr;
}
jlong address_arg = reinterpret_cast<jlong>(address);
jint capacity_arg = static_cast<jint>(capacity);
jobject result = env->NewObject(WellKnownClasses::java_nio_DirectByteBuffer,
WellKnownClasses::java_nio_DirectByteBuffer_init,
address_arg, capacity_arg);
return static_cast<JNIEnvExt*>(env)->self_->IsExceptionPending() ? nullptr : result;
}
static void* GetDirectBufferAddress(JNIEnv* env, jobject java_buffer) {
return reinterpret_cast<void*>(env->GetLongField(
java_buffer, WellKnownClasses::java_nio_DirectByteBuffer_effectiveDirectAddress));
}
static jlong GetDirectBufferCapacity(JNIEnv* env, jobject java_buffer) {
return static_cast<jlong>(env->GetIntField(
java_buffer, WellKnownClasses::java_nio_DirectByteBuffer_capacity));
}
static jobjectRefType GetObjectRefType(JNIEnv* env ATTRIBUTE_UNUSED, jobject java_object) {
if (java_object == nullptr) {
return JNIInvalidRefType;
}
// Do we definitely know what kind of reference this is?
IndirectRef ref = reinterpret_cast<IndirectRef>(java_object);
IndirectRefKind kind = IndirectReferenceTable::GetIndirectRefKind(ref);
switch (kind) {
case kLocal:
return JNILocalRefType;
case kGlobal:
return JNIGlobalRefType;
case kWeakGlobal:
return JNIWeakGlobalRefType;
case kHandleScopeOrInvalid:
// Assume value is in a handle scope.
return JNILocalRefType;
}
LOG(FATAL) << "IndirectRefKind[" << kind << "]";
UNREACHABLE();
}
private:
static jint EnsureLocalCapacityInternal(ScopedObjectAccess& soa, jint desired_capacity,
const char* caller)
REQUIRES_SHARED(Locks::mutator_lock_) {
if (desired_capacity < 0) {
LOG(ERROR) << "Invalid capacity given to " << caller << ": " << desired_capacity;
return JNI_ERR;
}
std::string error_msg;
if (!soa.Env()->locals_.EnsureFreeCapacity(static_cast<size_t>(desired_capacity), &error_msg)) {
std::string caller_error = android::base::StringPrintf("%s: %s", caller, error_msg.c_str());
soa.Self()->ThrowOutOfMemoryError(caller_error.c_str());
return JNI_ERR;
}
return JNI_OK;
}
template<typename JniT, typename ArtT>
static JniT NewPrimitiveArray(JNIEnv* env, jsize length) {
ScopedObjectAccess soa(env);
if (UNLIKELY(length < 0)) {
soa.Vm()->JniAbortF("NewPrimitiveArray", "negative array length: %d", length);
return nullptr;
}
ArtT* result = ArtT::Alloc(soa.Self(), length);
return soa.AddLocalReference<JniT>(result);
}
template <typename JArrayT, typename ElementT, typename ArtArrayT>
static ArtArrayT* DecodeAndCheckArrayType(ScopedObjectAccess& soa, JArrayT java_array,
const char* fn_name, const char* operation)
REQUIRES_SHARED(Locks::mutator_lock_) {
ObjPtr<ArtArrayT> array = soa.Decode<ArtArrayT>(java_array);
if (UNLIKELY(ArtArrayT::GetArrayClass() != array->GetClass())) {
soa.Vm()->JniAbortF(fn_name,
"attempt to %s %s primitive array elements with an object of type %s",
operation,
mirror::Class::PrettyDescriptor(
ArtArrayT::GetArrayClass()->GetComponentType()).c_str(),
mirror::Class::PrettyDescriptor(array->GetClass()).c_str());
return nullptr;
}
DCHECK_EQ(sizeof(ElementT), array->GetClass()->GetComponentSize());
return array.Ptr();
}
template <typename ArrayT, typename ElementT, typename ArtArrayT>
static ElementT* GetPrimitiveArray(JNIEnv* env, ArrayT java_array, jboolean* is_copy) {
CHECK_NON_NULL_ARGUMENT(java_array);
ScopedObjectAccess soa(env);
ArtArrayT* array = DecodeAndCheckArrayType<ArrayT, ElementT, ArtArrayT>(soa, java_array,
"GetArrayElements",
"get");
if (UNLIKELY(array == nullptr)) {
return nullptr;
}
// Only make a copy if necessary.
if (Runtime::Current()->GetHeap()->IsMovableObject(array)) {
if (is_copy != nullptr) {
*is_copy = JNI_TRUE;
}
const size_t component_size = sizeof(ElementT);
size_t size = array->GetLength() * component_size;
void* data = new uint64_t[RoundUp(size, 8) / 8];
memcpy(data, array->GetData(), size);
return reinterpret_cast<ElementT*>(data);
} else {
if (is_copy != nullptr) {
*is_copy = JNI_FALSE;
}
return reinterpret_cast<ElementT*>(array->GetData());
}
}
template <typename ArrayT, typename ElementT, typename ArtArrayT>
static void ReleasePrimitiveArray(JNIEnv* env, ArrayT java_array, ElementT* elements, jint mode) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(java_array);
ScopedObjectAccess soa(env);
ArtArrayT* array = DecodeAndCheckArrayType<ArrayT, ElementT, ArtArrayT>(soa, java_array,
"ReleaseArrayElements",
"release");
if (array == nullptr) {
return;
}
ReleasePrimitiveArray(soa, array, sizeof(ElementT), elements, mode);
}
static void ReleasePrimitiveArray(ScopedObjectAccess& soa, mirror::Array* array,
size_t component_size, void* elements, jint mode)
REQUIRES_SHARED(Locks::mutator_lock_) {
void* array_data = array->GetRawData(component_size, 0);
gc::Heap* heap = Runtime::Current()->GetHeap();
bool is_copy = array_data != elements;
size_t bytes = array->GetLength() * component_size;
if (is_copy) {
// Sanity check: If elements is not the same as the java array's data, it better not be a
// heap address. TODO: This might be slow to check, may be worth keeping track of which
// copies we make?
if (heap->IsNonDiscontinuousSpaceHeapAddress(elements)) {
soa.Vm()->JniAbortF("ReleaseArrayElements",
"invalid element pointer %p, array elements are %p",
reinterpret_cast<void*>(elements), array_data);
return;
}
if (mode != JNI_ABORT) {
memcpy(array_data, elements, bytes);
} else if (kWarnJniAbort && memcmp(array_data, elements, bytes) != 0) {
// Warn if we have JNI_ABORT and the arrays don't match since this is usually an error.
LOG(WARNING) << "Possible incorrect JNI_ABORT in Release*ArrayElements";
soa.Self()->DumpJavaStack(LOG_STREAM(WARNING));
}
}
if (mode != JNI_COMMIT) {
if (is_copy) {
delete[] reinterpret_cast<uint64_t*>(elements);
} else if (heap->IsMovableObject(array)) {
// Non copy to a movable object must means that we had disabled the moving GC.
if (!kUseReadBarrier) {
heap->DecrementDisableMovingGC(soa.Self());
} else {
heap->DecrementDisableThreadFlip(soa.Self());
}
}
}
}
template <typename JArrayT, typename ElementT, typename ArtArrayT>
static void GetPrimitiveArrayRegion(JNIEnv* env, JArrayT java_array,
jsize start, jsize length, ElementT* buf) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(java_array);
ScopedObjectAccess soa(env);
ArtArrayT* array =
DecodeAndCheckArrayType<JArrayT, ElementT, ArtArrayT>(soa, java_array,
"GetPrimitiveArrayRegion",
"get region of");
if (array != nullptr) {
if (start < 0 || length < 0 || length > array->GetLength() - start) {
ThrowAIOOBE(soa, array, start, length, "src");
} else {
CHECK_NON_NULL_MEMCPY_ARGUMENT(length, buf);
ElementT* data = array->GetData();
memcpy(buf, data + start, length * sizeof(ElementT));
}
}
}
template <typename JArrayT, typename ElementT, typename ArtArrayT>
static void SetPrimitiveArrayRegion(JNIEnv* env, JArrayT java_array,
jsize start, jsize length, const ElementT* buf) {
CHECK_NON_NULL_ARGUMENT_RETURN_VOID(java_array);
ScopedObjectAccess soa(env);
ArtArrayT* array =
DecodeAndCheckArrayType<JArrayT, ElementT, ArtArrayT>(soa, java_array,
"SetPrimitiveArrayRegion",
"set region of");
if (array != nullptr) {
if (start < 0 || length < 0 || length > array->GetLength() - start) {
ThrowAIOOBE(soa, array, start, length, "dst");
} else {
CHECK_NON_NULL_MEMCPY_ARGUMENT(length, buf);
ElementT* data = array->GetData();
memcpy(data + start, buf, length * sizeof(ElementT));
}
}
}
};
const JNINativeInterface gJniNativeInterface = {
nullptr, // reserved0.
nullptr, // reserved1.
nullptr, // reserved2.
nullptr, // reserved3.
JNI::GetVersion,
JNI::DefineClass,
JNI::FindClass,
JNI::FromReflectedMethod,
JNI::FromReflectedField,
JNI::ToReflectedMethod,
JNI::GetSuperclass,
JNI::IsAssignableFrom,
JNI::ToReflectedField,
JNI::Throw,
JNI::ThrowNew,
JNI::ExceptionOccurred,
JNI::ExceptionDescribe,
JNI::ExceptionClear,
JNI::FatalError,
JNI::PushLocalFrame,
JNI::PopLocalFrame,
JNI::NewGlobalRef,
JNI::DeleteGlobalRef,
JNI::DeleteLocalRef,
JNI::IsSameObject,
JNI::NewLocalRef,
JNI::EnsureLocalCapacity,
JNI::AllocObject,
JNI::NewObject,
JNI::NewObjectV,
JNI::NewObjectA,
JNI::GetObjectClass,
JNI::IsInstanceOf,
JNI::GetMethodID,
JNI::CallObjectMethod,
JNI::CallObjectMethodV,
JNI::CallObjectMethodA,
JNI::CallBooleanMethod,
JNI::CallBooleanMethodV,
JNI::CallBooleanMethodA,
JNI::CallByteMethod,
JNI::CallByteMethodV,
JNI::CallByteMethodA,
JNI::CallCharMethod,
JNI::CallCharMethodV,
JNI::CallCharMethodA,
JNI::CallShortMethod,
JNI::CallShortMethodV,
JNI::CallShortMethodA,
JNI::CallIntMethod,
JNI::CallIntMethodV,
JNI::CallIntMethodA,
JNI::CallLongMethod,
JNI::CallLongMethodV,
JNI::CallLongMethodA,
JNI::CallFloatMethod,
JNI::CallFloatMethodV,
JNI::CallFloatMethodA,
JNI::CallDoubleMethod,
JNI::CallDoubleMethodV,
JNI::CallDoubleMethodA,
JNI::CallVoidMethod,
JNI::CallVoidMethodV,
JNI::CallVoidMethodA,
JNI::CallNonvirtualObjectMethod,
JNI::CallNonvirtualObjectMethodV,
JNI::CallNonvirtualObjectMethodA,
JNI::CallNonvirtualBooleanMethod,
JNI::CallNonvirtualBooleanMethodV,
JNI::CallNonvirtualBooleanMethodA,
JNI::CallNonvirtualByteMethod,
JNI::CallNonvirtualByteMethodV,
JNI::CallNonvirtualByteMethodA,
JNI::CallNonvirtualCharMethod,
JNI::CallNonvirtualCharMethodV,
JNI::CallNonvirtualCharMethodA,
JNI::CallNonvirtualShortMethod,
JNI::CallNonvirtualShortMethodV,
JNI::CallNonvirtualShortMethodA,
JNI::CallNonvirtualIntMethod,
JNI::CallNonvirtualIntMethodV,
JNI::CallNonvirtualIntMethodA,
JNI::CallNonvirtualLongMethod,
JNI::CallNonvirtualLongMethodV,
JNI::CallNonvirtualLongMethodA,
JNI::CallNonvirtualFloatMethod,
JNI::CallNonvirtualFloatMethodV,
JNI::CallNonvirtualFloatMethodA,
JNI::CallNonvirtualDoubleMethod,
JNI::CallNonvirtualDoubleMethodV,
JNI::CallNonvirtualDoubleMethodA,
JNI::CallNonvirtualVoidMethod,
JNI::CallNonvirtualVoidMethodV,
JNI::CallNonvirtualVoidMethodA,
JNI::GetFieldID,
JNI::GetObjectField,
JNI::GetBooleanField,
JNI::GetByteField,
JNI::GetCharField,
JNI::GetShortField,
JNI::GetIntField,
JNI::GetLongField,
JNI::GetFloatField,
JNI::GetDoubleField,
JNI::SetObjectField,
JNI::SetBooleanField,
JNI::SetByteField,
JNI::SetCharField,
JNI::SetShortField,
JNI::SetIntField,
JNI::SetLongField,
JNI::SetFloatField,
JNI::SetDoubleField,
JNI::GetStaticMethodID,
JNI::CallStaticObjectMethod,
JNI::CallStaticObjectMethodV,
JNI::CallStaticObjectMethodA,
JNI::CallStaticBooleanMethod,
JNI::CallStaticBooleanMethodV,
JNI::CallStaticBooleanMethodA,
JNI::CallStaticByteMethod,
JNI::CallStaticByteMethodV,
JNI::CallStaticByteMethodA,
JNI::CallStaticCharMethod,
JNI::CallStaticCharMethodV,
JNI::CallStaticCharMethodA,
JNI::CallStaticShortMethod,
JNI::CallStaticShortMethodV,
JNI::CallStaticShortMethodA,
JNI::CallStaticIntMethod,
JNI::CallStaticIntMethodV,
JNI::CallStaticIntMethodA,
JNI::CallStaticLongMethod,
JNI::CallStaticLongMethodV,
JNI::CallStaticLongMethodA,
JNI::CallStaticFloatMethod,
JNI::CallStaticFloatMethodV,
JNI::CallStaticFloatMethodA,
JNI::CallStaticDoubleMethod,
JNI::CallStaticDoubleMethodV,
JNI::CallStaticDoubleMethodA,
JNI::CallStaticVoidMethod,
JNI::CallStaticVoidMethodV,
JNI::CallStaticVoidMethodA,
JNI::GetStaticFieldID,
JNI::GetStaticObjectField,
JNI::GetStaticBooleanField,
JNI::GetStaticByteField,
JNI::GetStaticCharField,
JNI::GetStaticShortField,
JNI::GetStaticIntField,
JNI::GetStaticLongField,
JNI::GetStaticFloatField,
JNI::GetStaticDoubleField,
JNI::SetStaticObjectField,
JNI::SetStaticBooleanField,
JNI::SetStaticByteField,
JNI::SetStaticCharField,
JNI::SetStaticShortField,
JNI::SetStaticIntField,
JNI::SetStaticLongField,
JNI::SetStaticFloatField,
JNI::SetStaticDoubleField,
JNI::NewString,
JNI::GetStringLength,
JNI::GetStringChars,
JNI::ReleaseStringChars,
JNI::NewStringUTF,
JNI::GetStringUTFLength,
JNI::GetStringUTFChars,
JNI::ReleaseStringUTFChars,
JNI::GetArrayLength,
JNI::NewObjectArray,
JNI::GetObjectArrayElement,
JNI::SetObjectArrayElement,
JNI::NewBooleanArray,
JNI::NewByteArray,
JNI::NewCharArray,
JNI::NewShortArray,
JNI::NewIntArray,
JNI::NewLongArray,
JNI::NewFloatArray,
JNI::NewDoubleArray,
JNI::GetBooleanArrayElements,
JNI::GetByteArrayElements,
JNI::GetCharArrayElements,
JNI::GetShortArrayElements,
JNI::GetIntArrayElements,
JNI::GetLongArrayElements,
JNI::GetFloatArrayElements,
JNI::GetDoubleArrayElements,
JNI::ReleaseBooleanArrayElements,
JNI::ReleaseByteArrayElements,
JNI::ReleaseCharArrayElements,
JNI::ReleaseShortArrayElements,
JNI::ReleaseIntArrayElements,
JNI::ReleaseLongArrayElements,
JNI::ReleaseFloatArrayElements,
JNI::ReleaseDoubleArrayElements,
JNI::GetBooleanArrayRegion,
JNI::GetByteArrayRegion,
JNI::GetCharArrayRegion,
JNI::GetShortArrayRegion,
JNI::GetIntArrayRegion,
JNI::GetLongArrayRegion,
JNI::GetFloatArrayRegion,
JNI::GetDoubleArrayRegion,
JNI::SetBooleanArrayRegion,
JNI::SetByteArrayRegion,
JNI::SetCharArrayRegion,
JNI::SetShortArrayRegion,
JNI::SetIntArrayRegion,
JNI::SetLongArrayRegion,
JNI::SetFloatArrayRegion,
JNI::SetDoubleArrayRegion,
JNI::RegisterNatives,
JNI::UnregisterNatives,
JNI::MonitorEnter,
JNI::MonitorExit,
JNI::GetJavaVM,
JNI::GetStringRegion,
JNI::GetStringUTFRegion,
JNI::GetPrimitiveArrayCritical,
JNI::ReleasePrimitiveArrayCritical,
JNI::GetStringCritical,
JNI::ReleaseStringCritical,
JNI::NewWeakGlobalRef,
JNI::DeleteWeakGlobalRef,
JNI::ExceptionCheck,
JNI::NewDirectByteBuffer,
JNI::GetDirectBufferAddress,
JNI::GetDirectBufferCapacity,
JNI::GetObjectRefType,
};
const JNINativeInterface* GetJniNativeInterface() {
return &gJniNativeInterface;
}
void (*gJniSleepForeverStub[])() = {
nullptr, // reserved0.
nullptr, // reserved1.
nullptr, // reserved2.
nullptr, // reserved3.
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
SleepForever,
};
const JNINativeInterface* GetRuntimeShutdownNativeInterface() {
return reinterpret_cast<JNINativeInterface*>(&gJniSleepForeverStub);
}
} // namespace art
std::ostream& operator<<(std::ostream& os, const jobjectRefType& rhs) {
switch (rhs) {
case JNIInvalidRefType:
os << "JNIInvalidRefType";
return os;
case JNILocalRefType:
os << "JNILocalRefType";
return os;
case JNIGlobalRefType:
os << "JNIGlobalRefType";
return os;
case JNIWeakGlobalRefType:
os << "JNIWeakGlobalRefType";
return os;
default:
LOG(FATAL) << "jobjectRefType[" << static_cast<int>(rhs) << "]";
UNREACHABLE();
}
}
| [
"gyoonus@gmail.com"
] | gyoonus@gmail.com |
a6ce66f476f07e2a2d07335e76edeaba6a66c29a | 1e5939e1a3dd85aeb8d386ab697ed7eb4da57ec4 | /src/slg/scene/parseshapes.cpp | a6de270eeaf38abdb02f16b0f5c8e4b0841af95b | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | yazici/LuxCore | 3f58b3e34b5b726be64c9d9c94688025d6e559a9 | 67592ce9bcf3f7b7f40c0c1a3736a9927f12840a | refs/heads/master | 2020-04-28T07:26:22.089029 | 2019-03-11T12:53:39 | 2019-03-11T12:53:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,020 | cpp | /***************************************************************************
* Copyright 1998-2018 by authors (see AUTHORS.txt) *
* *
* This file is part of LuxCoreRender. *
* *
* 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 <boost/detail/container_fwd.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/format.hpp>
#include <boost/unordered_map.hpp>
#include <boost/unordered_set.hpp>
#include "slg/scene/scene.h"
#include "slg/utils/filenameresolver.h"
#include "slg/shapes/meshshape.h"
#include "slg/shapes/pointiness.h"
#include "slg/shapes/strands.h"
using namespace std;
using namespace luxrays;
using namespace slg;
void Scene::ParseShapes(const Properties &props) {
vector<string> shapeKeys = props.GetAllUniqueSubNames("scene.shapes");
if (shapeKeys.size() == 0) {
// There are not shape definitions
return;
}
double lastPrint = WallClockTime();
u_int shapeCount = 0;
BOOST_FOREACH(const string &key, shapeKeys) {
// Extract the shape name
const string shapeName = Property::ExtractField(key, 2);
if (shapeName == "")
throw runtime_error("Syntax error in shape definition: " + shapeName);
ExtTriangleMesh *mesh = CreateShape(shapeName, props);
DefineMesh(mesh);
++shapeCount;
const double now = WallClockTime();
if (now - lastPrint > 2.0) {
SDL_LOG("Shape count: " << shapeCount);
lastPrint = now;
}
}
SDL_LOG("Shape count: " << shapeCount);
editActions.AddActions(GEOMETRY_EDIT);
}
ExtTriangleMesh *Scene::CreateInlinedMesh(const string &shapeName, const string &propName, const Properties &props) {
// The mesh definition is in-lined
u_int pointsSize;
Point *points;
if (props.IsDefined(propName + ".vertices")) {
Property prop = props.Get(propName + ".vertices");
if ((prop.GetSize() == 0) || (prop.GetSize() % 3 != 0))
throw runtime_error("Wrong shape vertex list length: " + shapeName);
pointsSize = prop.GetSize() / 3;
points = TriangleMesh::AllocVerticesBuffer(pointsSize);
for (u_int i = 0; i < pointsSize; ++i) {
const u_int index = i * 3;
points[i] = Point(prop.Get<float>(index), prop.Get<float>(index + 1), prop.Get<float>(index + 2));
}
} else
throw runtime_error("Missing shape vertex list: " + shapeName);
u_int trisSize;
Triangle *tris;
if (props.IsDefined(propName + ".faces")) {
Property prop = props.Get(propName + ".faces");
if ((prop.GetSize() == 0) || (prop.GetSize() % 3 != 0))
throw runtime_error("Wrong shape face list length: " + shapeName);
trisSize = prop.GetSize() / 3;
tris = TriangleMesh::AllocTrianglesBuffer(trisSize);
for (u_int i = 0; i < trisSize; ++i) {
const u_int index = i * 3;
tris[i] = Triangle(prop.Get<u_int>(index), prop.Get<u_int>(index + 1), prop.Get<u_int>(index + 2));
}
} else {
delete[] points;
throw runtime_error("Missing shape face list: " + shapeName);
}
Normal *normals = NULL;
if (props.IsDefined(propName + ".normals")) {
Property prop = props.Get(propName + ".normals");
if ((prop.GetSize() == 0) || (prop.GetSize() / 3 != pointsSize))
throw runtime_error("Wrong shape normal list length: " + shapeName);
normals = new Normal[pointsSize];
for (u_int i = 0; i < pointsSize; ++i) {
const u_int index = i * 3;
normals[i] = Normal(prop.Get<float>(index), prop.Get<float>(index + 1), prop.Get<float>(index + 2));
}
}
UV *uvs = NULL;
if (props.IsDefined(propName + ".uvs")) {
Property prop = props.Get(propName + ".uvs");
if ((prop.GetSize() == 0) || (prop.GetSize() / 2 != pointsSize))
throw runtime_error("Wrong shape uv list length: " + shapeName);
uvs = new UV[pointsSize];
for (u_int i = 0; i < pointsSize; ++i) {
const u_int index = i * 2;
uvs[i] = UV(prop.Get<float>(index), prop.Get<float>(index + 1));
}
}
return new ExtTriangleMesh(pointsSize, trisSize, points, tris, normals, uvs);
}
ExtTriangleMesh *Scene::CreateShape(const string &shapeName, const Properties &props) {
const string propName = "scene.shapes." + shapeName;
// Get the shape type
const string shapeType = props.Get(Property(propName + ".type")("mesh")).Get<string>();
// Define the shape
Shape *shape;
if (shapeType == "mesh") {
const string meshFileName = SLG_FileNameResolver.ResolveFile(props.Get(Property(propName + ".ply")("")).Get<string>());
MeshShape *meshShape = new MeshShape(meshFileName);
if (props.IsDefined(propName + ".transformation")) {
// Apply the transformation
const Matrix4x4 mat = props.Get(Property(propName +
".transformation")(Matrix4x4::MAT_IDENTITY)).Get<Matrix4x4>();
meshShape->ApplyTransform(Transform(mat));
} else {
const Matrix4x4 mat = props.Get(Property(propName +
".appliedtransformation")(Matrix4x4::MAT_IDENTITY)).Get<Matrix4x4>();
meshShape->SetLocal2World(Transform(mat));
}
shape = meshShape;
} else if (shapeType == "inlinedmesh") {
MeshShape *meshShape = new MeshShape(CreateInlinedMesh(shapeName, propName, props));
if (props.IsDefined(propName + ".transformation")) {
// Apply the transformation
const Matrix4x4 mat = props.Get(Property(propName +
".transformation")(Matrix4x4::MAT_IDENTITY)).Get<Matrix4x4>();
meshShape->ApplyTransform(Transform(mat));
} else {
const Matrix4x4 mat = props.Get(Property(propName +
".appliedtransformation")(Matrix4x4::MAT_IDENTITY)).Get<Matrix4x4>();
meshShape->SetLocal2World(Transform(mat));
}
shape = meshShape;
} else if (shapeType == "pointiness") {
const string sourceMeshName = props.Get(Property(propName + ".source")("")).Get<string>();
if (!extMeshCache.IsExtMeshDefined(sourceMeshName))
throw runtime_error("Unknown shape name in a pointiness shape: " + shapeName);
shape = new PointinessShape((ExtTriangleMesh *)extMeshCache.GetExtMesh(sourceMeshName));
} else if (shapeType == "strands") {
const string fileName = SLG_FileNameResolver.ResolveFile(props.Get(Property(propName + ".file")("strands.hair")).Get<string>());
// For compatibility with the past
string tessellationTypeStr = props.Get(Property(propName + ".tesselation.type")("ribbon")).Get<string>();
tessellationTypeStr = props.Get(Property(propName + ".tessellation.type")(tessellationTypeStr)).Get<string>();
StrendsShape::TessellationType tessellationType;
if (tessellationTypeStr == "ribbon")
tessellationType = StrendsShape::TESSEL_RIBBON;
else if (tessellationTypeStr == "ribbonadaptive")
tessellationType = StrendsShape::TESSEL_RIBBON_ADAPTIVE;
else if (tessellationTypeStr == "solid")
tessellationType = StrendsShape::TESSEL_SOLID;
else if (tessellationTypeStr == "solidadaptive")
tessellationType = StrendsShape::TESSEL_SOLID_ADAPTIVE;
else
throw runtime_error("Tessellation type unknown: " + tessellationTypeStr);
// For compatibility with the past
u_int adaptiveMaxDepth = Max(0, props.Get(Property(propName + ".tesselation.adaptive.maxdepth")(8)).Get<int>());
adaptiveMaxDepth = Max(0, props.Get(Property(propName + ".tessellation.adaptive.maxdepth")(adaptiveMaxDepth)).Get<int>());
// For compatibility with the past
float adaptiveError = props.Get(Property(propName + ".tesselation.adaptive.error")(.1f)).Get<float>();
adaptiveError = props.Get(Property(propName + ".tessellation.adaptive.error")(adaptiveError)).Get<float>();
// For compatibility with the past
u_int solidSideCount = Max(0, props.Get(Property(propName + ".tesselation.solid.sidecount")(3)).Get<int>());
solidSideCount = Max(0, props.Get(Property(propName + ".tessellation.solid.sidecount")(solidSideCount)).Get<int>());
// For compatibility with the past
bool solidCapBottom = props.Get(Property(propName + ".tesselation.solid.capbottom")(false)).Get<bool>();
solidCapBottom = props.Get(Property(propName + ".tessellation.solid.capbottom")(solidCapBottom)).Get<bool>();
// For compatibility with the past
bool solidCapTop = props.Get(Property(propName + ".tesselation.solid.captop")(false)).Get<bool>();
solidCapTop = props.Get(Property(propName + ".tessellation.solid.captop")(solidCapTop)).Get<bool>();
// For compatibility with the past
bool useCameraPosition = props.Get(Property(propName + ".tesselation.usecameraposition")(false)).Get<bool>();
useCameraPosition = props.Get(Property(propName + ".tessellation.usecameraposition")(useCameraPosition)).Get<bool>();
cyHairFile strandsFile;
const int strandsCount = strandsFile.LoadFromFile(fileName.c_str());
if (strandsCount <= 0)
throw runtime_error("Unable to read strands file: " + fileName);
shape = new StrendsShape(this,
&strandsFile, tessellationType,
adaptiveMaxDepth, adaptiveError,
solidSideCount, solidCapBottom, solidCapTop,
useCameraPosition);
} else
throw runtime_error("Unknown shape type: " + shapeType);
ExtTriangleMesh *mesh = shape->Refine(this);
delete shape;
mesh->SetName(shapeName);
return mesh;
}
| [
"dade916@gmail.com"
] | dade916@gmail.com |
d8dca16c667b2a078d6635d8c264984792a7ff89 | d01188de09d02244121f86ec277c74d74cde53bd | /Kechkin - Project/Capstone/Capstone/Vigenere.h | de34759a092646f256717d3f839be6bf9c8848a5 | [] | no_license | yaroslavkechkin/capstone | 3a54fdaa871171783b9be9ac86d58c478861c547 | 090cfa10ed869d6c3f7a910c6e619b61a47a6721 | refs/heads/master | 2021-05-16T00:40:32.319252 | 2017-10-14T20:24:46 | 2017-10-14T20:24:46 | 106,960,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,566 | h | //Copyright 2012 Yaroslav Kechkin
//Distributed under the terms of the GNU General Public License
//This file is part of Capstone.
//
// Capstone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Capstone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Capstone. If not, see <http://www.gnu.org/licenses/>.
#include <string>
using namespace std;
class Vigenere
{
private:
string inputText; // input text
string outputText; // output text
string key; // key to encrypt/decrypt between plaintext and ciphertext
public:
Vigenere(); // construct Vigenere instance
// ACCESSOR GET
string getInputText(); //returns inputText value
string getOutputText(); // returns outputText value
string getKey(); // return key value
// ACCESSOR SET
void setInputText(string); // changes inputText value
void setOutputText(string); // changes outputText value
void setKey(string); // changes key value
// METHOD
void menu(); // displays command menu
void inputKey(); // inputs key for encryption / decryption
void inputAutoKey();
string getRepeatKey(); // returns repeated key with length equals plaintext's length
void encryptKey(); // encrypts plaintext using key
void encryptAutoKey(); // encrypts plaintext using key with Auto-Key mode
void decryptKey(); // decrypts ciphertext using key
void decryptAutoKey(); // decrypts ciphertext using key with Auto-Key mode
void inputDisplay(); // display input
void outputDisplay(); // display output
void inputFile(); // reads input from a file
void outputFileEncrypt(); // writes ciphertext output into a file (outputEncrypt.txt)
void outputFileEncryptAutoKey(); // writes ciphertext (with auto-key) output into a file (outputEncryptAutoKey.txt)
void outputFileDecrypt(); // writes plaintext output into a file (outputDecrypt.txt)
void outputFileDecryptAutoKey(); // writes plaintext (with auto-key) output into a file (outputDecryptAutoKey.txt)
}; | [
"yaroslavkechkin@gmail.com"
] | yaroslavkechkin@gmail.com |
80d49d113e6e96eedbaf09a6d807af87e0bdf665 | 836bace568ce8ff9e1a493e44a28e137a8466f0f | /GamePhysicsApp/GamePhysicsApp/GamePhysicsApp.cpp | ccafbe144f25e3cdc9c833b68f9b97289adb09ca | [] | no_license | simonazy/Simulation-Design | b9a5230a6e2b2ec6c880240c0ee1aa53bbcba24e | 4776d67d4de4be7d3eef86a4d185936f86be5739 | refs/heads/main | 2023-07-29T05:00:22.300240 | 2023-07-18T03:57:15 | 2023-07-18T03:57:15 | 348,007,900 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,929 | cpp | // GamePhysicsApp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
/*
* The main entry point for all demos.
*
* Part of the Cyclone physics system.
*
* Copyright (c) Icosagon 2003. All Rights Reserved.
*
* This software is distributed under licence. Use of this software
* implies agreement with all terms and conditions of the accompanying
* software licence.
*/
// Include appropriate OpenGL headers.
#include "ogl_header.h"
// Include the general application structure.
#include "app.h"
// Include the timing functions
#include "timing.h"
// Forward declaration of the function that will return the
// application object for this particular demo. This should be
// implemented in the demo's .cpp file.
extern Application* getApplication();
// Store the global application object.
Application* app;
/**
* Creates a window in which to display the scene.
*/
void createWindow(const char* title)
{
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(640,320);
glutInitWindowPosition(0,0);
glutCreateWindow(title);
}
/**
* Called each frame to update the 3D scene. Delegates to
* the application.
*/
void update()
{
// Update the timing.
TimingData::get().update();
// Delegate to the application.
app->update();
}
/**
* Called each frame to display the 3D scene. Delegates to
* the application.
*/
void display()
{
app->display();
// Update the displayed content.
glFlush();
glutSwapBuffers();
}
/**
* Called when a mouse button is pressed. Delegates to the
* application.
*/
void mouse(int button, int state, int x, int y)
{
app->mouse(button, state, x, y);
}
/**
* Called when the display window changes size.
*/
void reshape(int width, int height)
{
app->resize(width, height);
}
/**
* Called when a key is pressed.
*/
void keyboard(unsigned char key, int x, int y)
{
// Note we omit passing on the x and y: they are rarely needed.
app->key(key);
}
/**
* Called when the mouse is dragged.
*/
void motion(int x, int y)
{
app->mouseDrag(x, y);
}
/**
* The main entry point. We pass arguments onto GLUT.
*/
int main(int argc, char** argv)
{
// Set up GLUT and the timers
glutInit(&argc, argv);
TimingData::init();
// Create the application and its window
app = getApplication();
createWindow(app->getTitle());
// Set up the appropriate handler functions
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutDisplayFunc(display);
glutIdleFunc(update);
glutMouseFunc(mouse);
glutMotionFunc(motion);
// Run the application
app->initGraphics();
glutMainLoop();
// Clean up the application
app->deinit();
delete app;
TimingData::deinit();
} | [
"noreply@github.com"
] | noreply@github.com |
b8d234fd0327ce550ccb5860e5d34ef2f08e4d78 | e8b0e4004449f5149dafe9a8bfc5996e4b33637e | /Surface/Implicit/Variational/SurfletCompactRBF.h | 7249c8113a1ccdfa030e08fe914d0f4bae59fdb1 | [] | no_license | benardp/Wickbert | 3259ee4c0129769cf1e2a4aed587d2465beb4e77 | 73f72b160945f9c4f5cc91e55941bf85836276d2 | refs/heads/master | 2020-03-13T13:32:19.900393 | 2018-05-04T11:18:18 | 2018-05-04T11:18:18 | 131,140,762 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,337 | h | /** @file SurfletCompactRBF.h
* Expansion of CompactRBF to handle the surflet-style normal constraints of Ohtake, et al...
* A small "piece of surface" (linear or quadratic) is fit to the region of support,
* and blended between CSRBF centers (similar to Partition of Unity and MLS, but not quite the same)
* @author: Scott Kircher
* @date: November 7, 2004
*/
#ifndef SURFLETCOMPACTRBF_H
#define SURFLETCOMPACTRBF_H
#include "Surface/Implicit/Variational/CompactRBF.h"
#include <fstream>
//utility
//compute the axis-aligned bounding box (AABB) of a pointset
template<class VectorT>
void boundingBox(const std::vector<VectorT> &points,VectorT &bb_min,VectorT &bb_max)
{
if(points.size()<1) return;
bb_min=bb_max=points[0];
for(unsigned int c=1;c<points.size();c++)
{
for(int d=0;d<3;d++)
{
if(bb_min[d]>points[c][d]) bb_min[d]=points[c][d];
if(bb_max[d]<points[c][d]) bb_max[d]=points[c][d];
}
}
}
/** Surflet abstract base class
*/
class Surflet
{
public:
//fit to local surface
virtual void fit(gmVector3 point,gmVector3 normal,const RBFModelerConstraints &points,const std::vector<int> &nz_indices,const std::vector<double> &nz_weights)=0;
//evaluate
virtual float eval(const gmVector3 &point) const = 0;
//analytical gradient
virtual gmVector3 gradient(const gmVector3 &point) const = 0;
//analytical hessian
virtual gmMatrix3 hessian(const gmVector3 &point) const = 0;
virtual void writeOut(std::ofstream &out) const = 0;
virtual void readIn(std::ifstream &in) = 0;
};
/** Linear surflet
* linear local approximation of a surface...
* Not even the LS plane, just the plane defined by the normal and position given
*/
class LinearSurflet
{
public:
LinearSurflet() {d=0;}
//fit to local surface
virtual void fit(gmVector3 point,gmVector3 normal,const RBFModelerConstraints &points,const std::vector<int> &nz_indices,const std::vector<double> &nz_weights);
//evaluate
virtual float eval(const gmVector3 &point) const;
//analytical gradient
virtual gmVector3 gradient(const gmVector3 &point) const;
//analytical hessian
//since the gradient is constant, this is just zero
virtual gmMatrix3 hessian(const gmVector3 &point) const
{
return gmMatrix3();
}
virtual void writeOut(std::ofstream &out) const
{
out<<" ls";
out<<" "<<n[0]<<" "<<n[1]<<" "<<n[2]<<" "<<d;
}
virtual void readIn(std::ifstream &in)
{
in>>n[0]>>n[1]>>n[2]>>d;
}
private:
//plane equation
gmVector3 n;
float d;
};
/** Quadratic surflet
* quadratic local approximation of surface...
* defined as height field over plane used by LinearSurflet
*/
class QuadraticSurflet
{
public:
QuadraticSurflet() {a=0;b=0;c=0;d=0;e=0;f=0;}
//fit to local surface
virtual void fit(gmVector3 point,gmVector3 normal,const RBFModelerConstraints &points,const std::vector<int> &nz_indices,const std::vector<double> &nz_weights);
//evaluate
virtual float eval(const gmVector3 &point) const;
//analytical gradient
virtual gmVector3 gradient(const gmVector3 &point) const;
//analytical hessian
virtual gmMatrix3 hessian(const gmVector3 &point) const;
virtual void writeOut(std::ofstream &out) const
{
out<<" qs";
out<<" "<<origin[0]<<" "<<origin[1]<<" "<<origin[2]<<" ";
out<<" "<<uhat[0]<<" "<<uhat[1]<<" "<<uhat[2]<<" ";
out<<" "<<vhat[0]<<" "<<vhat[1]<<" "<<vhat[2]<<" ";
out<<" "<<what[0]<<" "<<what[1]<<" "<<what[2]<<" ";
out<<" "<<a<<" "<<b<<" "<<c<<" "<<d<<" "<<e<<" "<<f;
}
virtual void readIn(std::ifstream &in)
{
in>>origin[0]>>origin[1]>>origin[2];
in>>uhat[0]>>uhat[1]>>uhat[2];
in>>vhat[0]>>vhat[1]>>vhat[2];
in>>what[0]>>what[1]>>what[2];
in>>a>>b>>c>>d>>e>>f;
}
private:
gmVector3 uhat,vhat,what; //basis vectors
gmVector3 origin; //origin point
float a,b,c,d,e,f;
//global->local conversion
inline gmVector3 toLocal(const gmVector3 &x) const {return gmVector3(dot(x-origin,uhat),dot(x-origin,vhat),dot(x-origin,what));}
inline gmVector3 toGlobal(const gmVector3 &x) const {return x[0]*uhat+x[1]*vhat+x[2]*what+origin;}
};
/** SurfletCompactRBF class
*/
class SurfletCompactRBF : public CompactRBF
{
public:
MAKE_NAME()
//default constructor
SurfletCompactRBF();
//interpolate constructor
SurfletCompactRBF(int cont,double support,int surflet_deg,float bloffset,const std::vector<gmVector3> &positions,
const std::vector<double> &interp_vals,
const std::vector<gmVector3> &normals);
//destructor
virtual ~SurfletCompactRBF() {clearSurflets();}
/// Solve the constraint system to get the new interpolation surface.
virtual void updateRBF(void);
int unsigned qlen();
void getq(double *q);
void _setq(double *q);
void getqname(const char **qn);
#ifndef INTERVAL_EVAL_ONLY
virtual double proc(const gmVector3 & x);
virtual gmVector3 grad(const gmVector3 & x);
virtual gmMatrix3 hess(const gmVector3 & x);
#endif
/// Function to generate a new interpolating surface from a set of constraints.
virtual void interpolate(std::vector<gmVector3> positions,
std::vector<double> interp_vals,
std::vector<gmVector3> normals,
std::valarray<bool>& flexible,
bool pos_changed);
//for use by MultiscaleCSRBF (root of hierarchy should have a blevel of 1, all others are 0)
//this hsould not be a GUI settable parameter (and it isn't)
void setBaseLevelOffset(double blevel) {base_level_offset=blevel;}
double getBaseLevelOffset() {return base_level_offset;}
protected:
//surflet degree
//valid values:
// 1 - Local linear approximations
// 2 - Local quadratic approximations
int surflet_degree;
//surflet array (together with centers, defines all the constraints for the surface)
std::vector<Surflet *> surflets;
void clearSurflets(); //deletes as well as clears vector
//value of implicit "outside" of surface
double base_level_offset;
/** Function to convert the modeler constraints to true Surflet RBF constraints
* unlike RBF and CompactRBF, SurfletCompactRBFs do not add extra centers for
* normal constraints, instead they fit a surflet to the surface at that point.
*/
void convert_constraints(); //this includes building the KDtree
//create a surflet of the current degree
Surflet *newSurflet()
{
if(surflet_degree==1) return (Surflet*)new LinearSurflet;
else return (Surflet*)new QuadraticSurflet;
}
};
#endif
| [
"pierre.g.benard@inria.fr"
] | pierre.g.benard@inria.fr |
6463104d0c2dd4df8901af85ef3f96b76faafa0d | b0989c3b3e2ae03511c4866795e5a43ac751a3a6 | /src/AppLayer/Audio/Music.cpp | 9da30e3e392bd4f2b4a9a23fb79ba2c92a4a6cff | [] | no_license | rickyah/columnas-sdl | 2a6350bc6cb85e73cf1544e82dc17c5cc738a338 | ada7e9244adfe6f03665156e8ef5fba928d19c31 | refs/heads/master | 2021-01-16T21:14:00.585427 | 2016-07-11T13:32:35 | 2016-07-11T13:32:35 | 61,109,694 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | //
// Music.cpp
// king-test
//
// Created by Ricardo Amores Hernández on 23/6/16.
//
//
#include "Music.hpp"
| [
"rickyah@gmail.com"
] | rickyah@gmail.com |
a7dc552911eed2c67f10ccc5beca2a762e743868 | c67f49a21f60d673b5d0909c9b7a52b8a220261c | /longests_sub_sequence.cpp | 79cd57203a5050c7c16e57d92658d538acbf92db | [] | no_license | LetsDoAlgo/Solution-of-Dynamic-Programmnig-challenges-by-Tushar-Roy | 3cd18682b3e7f463eeeb5a13b2570f1e89cb7f9b | 9e20539a9fe627473f97a143512e482f0a3be50b | refs/heads/master | 2020-08-02T20:20:52.222490 | 2019-01-17T08:01:47 | 2019-01-17T08:01:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,401 | cpp | #include<iostream>
#include<cstring>
using namespace std;
int main()
{
int i,j,n1,n2;
string s1,s2;
cin>>s1>>s2;
n2=s1.length();
n1=s2.length();
int a[n1+1][n2+1];
for(i=0;i<n2+1;i++)
{
a[0][i]=0;
}
for(i=0;i<n1+1;i++)
{
a[i][0]=0;
}
for(i=1;i<n1+1;i++)
{
for(j=1;j<n2+1;j++)
{
int p;
if(a[i-1][j]>a[i][j-1])
p=a[i-1][j];
else
p=a[i][j-1];
if(s2[i-1]!=s1[j-1])
{
a[i][j]=p;
}
else if(s2[i-1]==s1[j-1])
{
a[i][j]=p+1;
}
}
}
int n3=a[n1][n2];
char s3[n3];
int k=0;
for(i=n1;i>=0;i--)
{
for(j=n2;j>=0;j--)
{
int p1;
if(a[i-1][j]>a[i][j-1])
p1=a[i-1][j];
else
p1=a[i][j-1];
if(a[i][j]>p1)
{
s3[k++]=s2[j-1];
cout<<i<<j<<s2[i-1]<<"\n";
i--;
}
}
}
/* for(i=0;i<=n3;i++)
{
cout<<s3[i];
}*/
cout<<"\n";
for(i=0;i<n1+1;i++)
{
for(j=0;j<n2+1;j++)
{
cout<<a[i][j]<<"\t";
}
cout<<"\n";
}
// cout<<a[n1][n2];
return 0;
}
| [
"viditgarg1999@gmail.com"
] | viditgarg1999@gmail.com |
ab0d4dba9db7c086935bb08db4e95781b048fb23 | 470fae08316b55246ab01675ac5013febfb13eee | /src/server/scripts/Zandalar/TheMotherlode/the_motherlode.cpp | 7e0feb484235bb80fb5a93d3bb4e6a81368a3a70 | [] | no_license | adde13372/shadowcore | 8db6fb6ccc99821e6bd40237a0c284ce7cf543c2 | aa87944193ce02f6e99f7b35eceac5023abfca1b | refs/heads/main | 2023-04-01T07:38:39.359558 | 2021-04-03T07:54:17 | 2021-04-03T07:54:17 | 354,320,611 | 4 | 8 | null | 2021-04-03T15:02:49 | 2021-04-03T15:02:49 | null | UTF-8 | C++ | false | false | 1,163 | cpp | /*
* Copyright 2021 ShadowCore
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "AreaTrigger.h"
#include "AreaTriggerAI.h"
#include "ObjectMgr.h"
#include "ScriptMgr.h"
#include "the_motherlode.h"
//136776
struct npc_mine_cart_136776 : public ScriptedAI
{
npc_mine_cart_136776(Creature* creature) : ScriptedAI(creature) { }
void Reset() override
{
ScriptedAI::Reset();
me->SetFaction(35);
me->SetReactState(REACT_PASSIVE);
}
};
void AddSC_the_motherlode()
{
RegisterCreatureAI(npc_mine_cart_136776);
}
| [
"81566364+NemoPRM@users.noreply.github.com"
] | 81566364+NemoPRM@users.noreply.github.com |
d227c5c7292fa6714fdbc8fb9a3ebcfd8b31d1cc | 9a873b18c98964465c08462c792cfe3a69bf727e | /src/fmt/posix.cc | 4477b77648bcbd15ced687222832005cf992ed6f | [
"MIT"
] | permissive | shiinamiyuki/kcc | 83cdc742c88c6893a0f4521b700fc9c6fec8ea54 | d1b63a2378f0dd189534f89455601538ac5c9bd9 | refs/heads/master | 2020-03-28T12:48:00.067693 | 2019-09-25T02:02:24 | 2019-09-25T02:02:24 | 148,335,036 | 9 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,854 | cc | // A C++ interface to POSIX functions.
//
// Copyright (c) 2012 - 2016, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
// Disable bogus MSVC warnings.
#if !defined(_CRT_SECURE_NO_WARNINGS) && defined(_MSC_VER)
# define _CRT_SECURE_NO_WARNINGS
#endif
#include "posix.h"
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifndef _WIN32
# include <unistd.h>
#else
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# include <io.h>
# define O_CREAT _O_CREAT
# define O_TRUNC _O_TRUNC
# ifndef S_IRUSR
# define S_IRUSR _S_IREAD
# endif
# ifndef S_IWUSR
# define S_IWUSR _S_IWRITE
# endif
# ifdef __MINGW32__
# define _SH_DENYNO 0x40
# endif
#endif // _WIN32
#ifdef fileno
# undef fileno
#endif
namespace {
#ifdef _WIN32
// Return type of read and write functions.
typedef int RWResult;
// On Windows the count argument to read and write is unsigned, so convert
// it from size_t preventing integer overflow.
inline unsigned convert_rwcount(std::size_t count) {
return count <= UINT_MAX ? static_cast<unsigned>(count) : UINT_MAX;
}
#else
// Return type of read and write functions.
typedef ssize_t RWResult;
inline std::size_t convert_rwcount(std::size_t count) { return count; }
#endif
}
FMT_BEGIN_NAMESPACE
buffered_file::~buffered_file() FMT_NOEXCEPT {
if (file_ && FMT_SYSTEM(fclose(file_)) != 0)
report_system_error(errno, "cannot close file");
}
buffered_file::buffered_file(cstring_view filename, cstring_view mode) {
FMT_RETRY_VAL(file_,
FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())), FMT_NULL);
if (!file_)
FMT_THROW(system_error(errno, "cannot open file {}", filename.c_str()));
}
void buffered_file::close() {
if (!file_)
return;
int result = FMT_SYSTEM(fclose(file_));
file_ = FMT_NULL;
if (result != 0)
FMT_THROW(system_error(errno, "cannot close file"));
}
// A macro used to prevent expansion of fileno on broken versions of MinGW.
#define FMT_ARGS
int buffered_file::fileno() const {
int fd = FMT_POSIX_CALL(fileno FMT_ARGS(file_));
if (fd == -1)
FMT_THROW(system_error(errno, "cannot get file descriptor"));
return fd;
}
file::file(cstring_view path, int oflag) {
int mode = S_IRUSR | S_IWUSR;
#if defined(_WIN32) && !defined(__MINGW32__)
fd_ = -1;
FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode));
#else
FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode)));
#endif
if (fd_ == -1)
FMT_THROW(system_error(errno, "cannot open file {}", path.c_str()));
}
file::~file() FMT_NOEXCEPT {
// Don't retry close in case of EINTR!
// See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0)
report_system_error(errno, "cannot close file");
}
void file::close() {
if (fd_ == -1)
return;
// Don't retry close in case of EINTR!
// See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
int result = FMT_POSIX_CALL(close(fd_));
fd_ = -1;
if (result != 0)
FMT_THROW(system_error(errno, "cannot close file"));
}
long long file::size() const {
#ifdef _WIN32
// Use GetFileSize instead of GetFileSizeEx for the case when _WIN32_WINNT
// is less than 0x0500 as is the case with some default MinGW builds.
// Both functions support large file sizes.
DWORD size_upper = 0;
HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd_));
DWORD size_lower = FMT_SYSTEM(GetFileSize(handle, &size_upper));
if (size_lower == INVALID_FILE_SIZE) {
DWORD error = GetLastError();
if (error != NO_ERROR)
FMT_THROW(windows_error(GetLastError(), "cannot get file size"));
}
unsigned long long long_size = size_upper;
return (long_size << sizeof(DWORD) * CHAR_BIT) | size_lower;
#else
typedef struct stat Stat;
Stat file_stat = Stat();
if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1)
FMT_THROW(system_error(errno, "cannot get file attributes"));
static_assert(sizeof(long long) >= sizeof(file_stat.st_size),
"return type of file::size is not large enough");
return file_stat.st_size;
#endif
}
std::size_t file::read(void *buffer, std::size_t count) {
RWResult result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count))));
if (result < 0)
FMT_THROW(system_error(errno, "cannot read from file"));
return internal::to_unsigned(result);
}
std::size_t file::write(const void *buffer, std::size_t count) {
RWResult result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count))));
if (result < 0)
FMT_THROW(system_error(errno, "cannot write to file"));
return internal::to_unsigned(result);
}
file file::dup(int fd) {
// Don't retry as dup doesn't return EINTR.
// http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html
int new_fd = FMT_POSIX_CALL(dup(fd));
if (new_fd == -1)
FMT_THROW(system_error(errno, "cannot duplicate file descriptor {}", fd));
return file(new_fd);
}
void file::dup2(int fd) {
int result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
if (result == -1) {
FMT_THROW(system_error(errno,
"cannot duplicate file descriptor {} to {}", fd_, fd));
}
}
void file::dup2(int fd, error_code &ec) FMT_NOEXCEPT {
int result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
if (result == -1)
ec = error_code(errno);
}
void file::pipe(file &read_end, file &write_end) {
// Close the descriptors first to make sure that assignments don't throw
// and there are no leaks.
read_end.close();
write_end.close();
int fds[2] = {};
#ifdef _WIN32
// Make the default pipe capacity same as on Linux 2.6.11+.
enum { DEFAULT_CAPACITY = 65536 };
int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY));
#else
// Don't retry as the pipe function doesn't return EINTR.
// http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html
int result = FMT_POSIX_CALL(pipe(fds));
#endif
if (result != 0)
FMT_THROW(system_error(errno, "cannot create pipe"));
// The following assignments don't throw because read_fd and write_fd
// are closed.
read_end = file(fds[0]);
write_end = file(fds[1]);
}
buffered_file file::fdopen(const char *mode) {
// Don't retry as fdopen doesn't return EINTR.
FILE *f = FMT_POSIX_CALL(fdopen(fd_, mode));
if (!f)
FMT_THROW(system_error(errno,
"cannot associate stream with file descriptor"));
buffered_file bf(f);
fd_ = -1;
return bf;
}
long getpagesize() {
#ifdef _WIN32
SYSTEM_INFO si;
GetSystemInfo(&si);
return si.dwPageSize;
#else
long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE));
if (size < 0)
FMT_THROW(system_error(errno, "cannot get memory page size"));
return size;
#endif
}
FMT_END_NAMESPACE
| [
"38184032+xt271828@users.noreply.github.com"
] | 38184032+xt271828@users.noreply.github.com |
917e38ac3d2e141664b24bc7db7db7ea3c7de4e5 | 26fd4d615946f73ee3964cd48fa06120611bf449 | /342_Power_of_Four.cpp | 74a1308bd8efad8a3d5da96a5e0eefe6ae60eea3 | [] | no_license | xujie-nm/Leetcode | 1aab8a73a33f954bfb3382a286626a56d2f14617 | eb8a7282083e2d2a6c94475759ba01bd4220f354 | refs/heads/master | 2020-04-12T07:25:51.621189 | 2016-12-03T09:29:36 | 2016-12-03T09:29:36 | 28,400,113 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 655 | cpp | #include <iostream>
#include <string>
#include <vector>
using namespace std;
// 1 2 3 4 | 5 6 7 8 | 9 10 11 12 | 13 14 15 16 | 17 18 19 20 | 21 22 23 24 | 25 26 27 28 | 29 30 31 32|
// 0x 5 5 5 5 5 5 5 5
// = 0 1 0 1 | 0 1 0 1 | 0 1 0 1 | 0 1 0 1 | 0 1 0 1 | 0 1 0 1 | 0 1 0 1 | 0 1 0 1|
// 以上
bool isPowerOfFour(int num){
if((num & (num-1)) == 0){
return num & 0x55555555;
}
return false;
}
int main(int argc, const char *argv[])
{
cout << isPowerOfFour(16) << endl;
cout << isPowerOfFour(5) << endl;
return 0;
}
| [
"xujie_nm@163.com"
] | xujie_nm@163.com |
afc28310de88c0a79ea60e8a02d10478bf1afa8d | dfa8d28d831ea609d32882fd8a6d112a27d97db7 | /QGIS-Test/Lex-Example/lex/main.cpp | d7c2804066d5ba09ebc61643fde3a85573269150 | [] | no_license | serdarkocerr/QT | 04a20c7a3f21d95c46e2dec774a38a75433591a5 | 6d9f1b1cce398d4f78e010ebdd13a25a3cb8526f | refs/heads/master | 2022-07-29T15:35:21.564840 | 2022-07-26T22:21:29 | 2022-07-26T22:21:29 | 217,359,418 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,186 | cpp | #define _USE_MATH_DEFINES
#include <cmath>
#include "mainwindow.h"
#include "qgsapplication.h"
#include <QApplication>
#include <qgsmapcanvas.h>
#include <QVBoxLayout>
#include <QApplication>
#include <qgsapplication.h>
#include <mainwindow.h>
#include <QDebug>
#include <qgsapplication.h>
#include <qgsproviderregistry.h>
#include <qgssinglesymbolrenderer.h>
#include <qgsmaplayer.h>
#include <qgsvectorlayer.h>
#include <qgsmapcanvas.h>
#include <qgsproject.h>
#include <qgssymbol.h>
void myMessageHandler(QtMsgType type, const QMessageLogContext &, const QString & msg)
{
QString txt;
switch (type) {
case QtDebugMsg:
txt = QString("Debug: %1").arg(msg);
break;
case QtWarningMsg:
txt = QString("Warning: %1").arg(msg);
break;
case QtCriticalMsg:
txt = QString("Critical: %1").arg(msg);
break;
case QtFatalMsg:
txt = QString("Fatal: %1").arg(msg);
abort();
}
QFile outFile("D:/Qt5.12.12/workspace/OUTPUTS/log.txt");
outFile.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream ts(&outFile);
ts << txt << endl;
}
int main(int argc, char *argv[])
{
QgsApplication app(argc, argv, true);
qInstallMessageHandler(myMessageHandler);
QgsApplication::setPrefixPath("D:/OSGeo4W/apps/qgis-ltr-dev",true);
QgsApplication::initQgis();
//QApplication a(argc, argv);
MainWindow w;
w.show();
// w.loadMap();
w.raise();
w.loadMap();
w.setPanMode();
int result = app.exec();
QgsApplication::exitQgis();
return result;
// return a.exec();
// QgsApplication app(argc, argv, true);
// QgsApplication::setPrefixPath("D:/OSGeo4W/apps/qgis-ltr-dev",true);
// app.init();
// QVBoxLayout *vlayout = new QVBoxLayout;
// vlayout->setContentsMargins(0,0,0,0);
// QgsMapCanvas * mypMapCanvas = new QgsMapCanvas();
// mypMapCanvas->setCanvasColor(Qt::white);
// mypMapCanvas->show();
// vlayout->addWidget(mypMapCanvas);
// int rsult = app.exec();
// // app.exitQgis();
// return rsult;
}
| [
"noreply@github.com"
] | noreply@github.com |
3ed37023e50f4831fe50b938c75ae933c649ce30 | 4d4f014f79501d657a8e578c9a2a356df3dcd32b | /sketch_apr08c/sketch_apr08c.ino | 054646d909c4d085cf27522f46a01b460bf0d5b8 | [] | no_license | zoyazee/Electronics | 8049f14b1f9fd88847ca71a57beebea568c30b6e | 975d18dd8b5ceacd36f54e107f0760b28c7c7e33 | refs/heads/master | 2020-05-09T22:13:09.356133 | 2019-07-01T20:12:33 | 2019-07-01T20:12:33 | 181,464,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 595 | ino | int pinpot=A0;
int LEDRED=10;
int Brightness;
int Readvalue;
String message="pinpot value=";
String message2="Brightness=";
void setup() {
Serial.begin(9600);
pinMode(pinpot,INPUT);
pinMode(LEDRED,OUTPUT);
// put your setup code here, to run once:
}
void loop() {
Readvalue=analogRead(pinpot);
Serial.print(message);
Serial.print(Readvalue);
Serial.print(message2);
Serial.println(Brightness);
Brightness=(255./1023.)*Readvalue;
analogWrite(LEDRED,Brightness);
delay(1000);
analogWrite(LEDRED,0);
delay(1000);
// put your main code here, to run repeatedly:
}
| [
"joygathigira@gmail.com"
] | joygathigira@gmail.com |
c2dc204e3b237172c704a4a8f962490823efffb3 | d9db2195cf3f3f5090d3d9ee938e023ddd43b55d | /GraphBar/gen_prop_dlgs.h | e4c33906e0ef2a7050205f7639132455644e0e23 | [] | no_license | radtek/AiPI | e3a31fbf34a695764a36855cb0fae1e9e48db9d8 | 732a21ba0707be1c01002dcbefba433c69d46e1b | refs/heads/master | 2020-06-08T21:40:36.564225 | 2012-06-09T22:32:01 | 2012-06-09T22:32:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,930 | h | /*
This file was created by Paul Barvinko (pbarvinko@yahoo.com).
This file is distributed "as is", e.g. there are no warranties
and obligations and you could use it in your applications on your
own risk.
Your comments and questions are welcome.
If using in your applications, please mention author in credits for your app.
*/
#if !defined(AFX_GEN_PROP_DLGS_H__ED91D495_DF96_11D3_B4B5_00C04F89477F__INCLUDED_)
#define AFX_GEN_PROP_DLGS_H__ED91D495_DF96_11D3_B4B5_00C04F89477F__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// gen_prop_dlgs.h : header file
//
#include "..\resource.h"
#include "graphcombobox.h"
#include "graph_props.h"
#include <afxtempl.h>
/////////////////////////////////////////////////////////////////////////////
// CAxisPropertyPage dialog
class CAxisPropertyPage : public CPropertyPage
{
DECLARE_DYNCREATE(CAxisPropertyPage)
// Construction
public:
CAxisPropertyPage();
~CAxisPropertyPage();
// Dialog Data
//{{AFX_DATA(CAxisPropertyPage)
enum { IDD = IDD_GRAPH_AXISPROPPAGE_DLG };
long m_x_precision;
CString m_x_title;
CString m_x_uom;
long m_y_precision;
CString m_y_title;
CString m_y_uom;
//}}AFX_DATA
// Overrides
// ClassWizard generate virtual function overrides
//{{AFX_VIRTUAL(CAxisPropertyPage)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CAxisPropertyPage)
virtual BOOL OnInitDialog();
// NOTE: the ClassWizard will add member functions here
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
// CGraphicsPropertyPage dialog
class CGraphPropsComboBox : public CGraphComboBox
{
public:
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
};
class CGraphicsPropertyPage : public CPropertyPage, public CGraphBaseClass
{
DECLARE_DYNCREATE(CGraphicsPropertyPage)
// Construction
public:
CGraphicsPropertyPage();
CGraphicsPropertyPage(CGraphWnd* main_wnd);
~CGraphicsPropertyPage();
// Dialog Data
CArray<CGraphProps*, CGraphProps*> grprops;
void SetActiveSel(int selnum);
void SetHideShowAttr(int selnum);
//{{AFX_DATA(CGraphicsPropertyPage)
enum { IDD = IDD_GRAPH_GRAPHICS_PROPS };
CGraphPropsComboBox m_graph_combo;
CString m_graph_title;
//}}AFX_DATA
// Overrides
// ClassWizard generate virtual function overrides
//{{AFX_VIRTUAL(CGraphicsPropertyPage)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CGraphicsPropertyPage)
afx_msg void OnGraphChColor();
afx_msg void OnGraphChTitle();
afx_msg void OnGraphHideshow();
afx_msg void OnGraphsShowall();
afx_msg void OnSelchangeGraphChoice();
virtual BOOL OnInitDialog();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
// CGraphTitlePrompt dialog
class CGraphTitlePrompt : public CDialog
{
// Construction
public:
CGraphTitlePrompt(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CGraphTitlePrompt)
enum { IDD = IDD_GRAPH_CHANGETITLE_DLG };
CString m_title;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CGraphTitlePrompt)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CGraphTitlePrompt)
virtual BOOL OnInitDialog();
// NOTE: the ClassWizard will add member functions here
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_GEN_PROP_DLGS_H__ED91D495_DF96_11D3_B4B5_00C04F89477F__INCLUDED_)
| [
"malpharo1969"
] | malpharo1969 |
f720a93d02569053a117e62bd9955a88f2361d47 | 4ef68112b8f4348d1cbf71cd86d0378b93222794 | /CLR-Plugins/CLIWrapper/USBinterface.h | 5158edc74c19554dcac3e39e7ffed04cb06dba20 | [] | no_license | TheLastRar/PCSX2-CLR-Plugins | ac6c6c28e6e7651d5aca9401d6d4d57040a4d240 | 128f3534b0933c6fc634081146fcfc1c6920efbf | refs/heads/master | 2016-09-06T17:19:23.345864 | 2015-09-19T16:39:56 | 2015-09-19T16:39:56 | 30,390,638 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,030 | h | /* USBnull
* Copyright (C) 2002-2010 PCSX2 Dev Team
*
* PCSX2 is free software: you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* PCSX2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with PCSX2.
* If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __USB_H__
#define __USB_H__
#include "PSEInterface.h"
#include "USBWrapper.h"
class NativeUSBWrapper
{
public:
msclr::auto_gcroot<USBWrapper^> USBwrap;
};
extern NativeUSBWrapper* nat_usb;
// Previous USB plugins have needed this in ohci.
//static const s64 PSXCLK = 36864000; /* 36.864 Mhz */
extern u8 *ram;
#endif
| [
"alastairbarnes123@hotmail.com"
] | alastairbarnes123@hotmail.com |
eb824222b56b01bae72ea72f621bb03af514a2ef | af6477da701ede3758888f9429040ea6685e2cf3 | /TriSpark_Slot/_src/CMenuManager.cpp | 5517e5836c017a00ba0dccba03771d35341b2fe6 | [] | no_license | M1spark20/TriSpark_Slot_VC2019 | 393014a84b737948e5ce06136c805efb186e5fb7 | 0bd3c4405a7f00035de1a4a035360dc14852a730 | refs/heads/master | 2023-06-15T07:37:39.824821 | 2021-07-09T15:04:43 | 2021-07-09T15:04:43 | 282,438,584 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,029 | cpp | #include "_header/CMenuManager.hpp"
#include "_header/keyexport.h"
#include "_header/CGameDataManage.h"
#include "DxLib.h"
#include <cmath>
CMenuManager::CMenuManager() {
mMenuElement = nullptr;
mMenuStartTime = -1;
mMenuFinishTime = -1;
mBaseImgID = -1;
mTitleFontHandle = -1;
mDataFontHandle = -1;
mDataFontHandleMid = -1;
mLicenseTXT = -1;
mResumeMenu = EMenuList::eHowTo;
}
bool CMenuManager::Init(CGameDataManage& pDataManageIns, const int pLicenseFileID, const int pDataFontHandle, const int pDataFontHandleMid, const int pBaseImgID, const int pTitleFontHandle) {
mBaseImgID = pDataManageIns.GetDataHandle(pBaseImgID);
mTitleFontHandle = pDataManageIns.GetDataHandle(pTitleFontHandle);
mDataFontHandle = pDataManageIns.GetDataHandle(pDataFontHandle);
mDataFontHandleMid = pDataManageIns.GetDataHandle(pDataFontHandleMid);
mLicenseTXT = pDataManageIns.GetDataHandle(pLicenseFileID);
return true;
}
bool CMenuManager::Process(CGameDataManage& pDataManageIns, SSlotGameDataWrapper& pSlotData) {
CKeyExport_S& key = CKeyExport_S::GetInstance();
if (key.GetExportStatus() == EKeyExportStatus::eGameMain) {
if (key.ExportKeyState(KEY_INPUT_M)) {
// initialize
ResetMenuContents(mResumeMenu, pDataManageIns, pSlotData);
key.SetExportStatus(EKeyExportStatus::eMenu);
mMenuStartTime = DxLib::GetNowCount();
}
}
else if (key.GetExportStatus() == EKeyExportStatus::eMenu)
if (mMenuElement != nullptr) {
for (int a = 0; a < 256; ++a) {
if (key.ExportKeyState(a)) {
const auto nextMode = mMenuElement->PushButton(a);
ResetMenuContents(nextMode, pDataManageIns, pSlotData);
}
}
if (mMenuFinishTime < 0)
if (key.ExportKeyState(KEY_INPUT_M) || key.ExportKeyState(KEY_INPUT_ESCAPE)){
mMenuFinishTime = DxLib::GetNowCount();
}
const int nowCount = DxLib::GetNowCount();
if (mMenuStartTime > 0 && nowCount - mMenuStartTime >= 250) mMenuStartTime = -1;
if (mMenuFinishTime > 0 && nowCount - mMenuFinishTime >= 250) {
delete mMenuElement;
mMenuElement = nullptr;
mMenuFinishTime = -1;
key.SetExportStatus(EKeyExportStatus::eGameMain);
}
}
return true;
}
bool CMenuManager::Draw(int pBasicScr) {
if (mMenuElement == nullptr) return true;
int opacity = 255;
const int nowCount = DxLib::GetNowCount();
if (mMenuStartTime >= 0) opacity = floorf(255.f * ((nowCount - mMenuStartTime) / 250.f));
if (mMenuFinishTime >= 0) opacity = 255 - floorf(255.f * ((nowCount - mMenuFinishTime) / 250.f));
mMenuElement->Draw(opacity, pBasicScr);
return true;
}
CMenuManager::~CMenuManager() {
delete mMenuElement;
}
bool CMenuManager::ResetMenuContents(EMenuList pNext, CGameDataManage& pDataManageIns, SSlotGameDataWrapper& pSlotData) {
switch (pNext) {
case EMenuList::eLicense:
delete mMenuElement;
mMenuElement = nullptr;
mMenuElement = new CMenuLicenses(mLicenseTXT, mDataFontHandle, mBaseImgID, mTitleFontHandle);
mMenuElement->Init();
mResumeMenu = pNext;
break;
case EMenuList::eReelHistory:
delete mMenuElement;
mMenuElement = nullptr;
mMenuElement = new CMenuReelHistory(pDataManageIns, mDataFontHandle, mDataFontHandleMid, mBaseImgID, pSlotData.reelManager, mTitleFontHandle);
mMenuElement->Init();
mResumeMenu = pNext;
break;
case EMenuList::eBonusHistory:
delete mMenuElement;
mMenuElement = nullptr;
mMenuElement = new CMenuBonusHistory(pDataManageIns, mDataFontHandle, mDataFontHandleMid, mBaseImgID, pSlotData.dataCounter, mTitleFontHandle);
mMenuElement->Init();
mResumeMenu = pNext;
break;
case EMenuList::eHowTo:
delete mMenuElement;
mMenuElement = nullptr;
mMenuElement = new CMenuHowTo(pDataManageIns, mBaseImgID, mTitleFontHandle);
mMenuElement->Init();
mResumeMenu = pNext;
break;
case EMenuList::eReachPatternCollection:
delete mMenuElement;
mMenuElement = nullptr;
mMenuElement = new CMenuReachCollection(pDataManageIns, mDataFontHandle, mBaseImgID, pSlotData.reachCollection, mTitleFontHandle);
mMenuElement->Init();
mResumeMenu = pNext;
break;
}
return true;
}
| [
"spaaaark.sin120@gmail.com"
] | spaaaark.sin120@gmail.com |
33fe54498cc0a65c92e177922c23e5632e5a141e | d2e378763c65b9da32157eee1d7e6f0fa4b0c4ea | /src/jsonrpccpp/server/abstractthreadedserver.h | 4fa3f3c7a7d76d5dee11c010ea1acad9196e973f | [
"MIT"
] | permissive | who-biz/blur-api-cpp | f6575573edc19cfc2f11e7889dad46ef098d1521 | cef4f0a2ed241fbe124af572090c82fe0c7bc4cc | refs/heads/master | 2023-04-14T06:21:37.667778 | 2021-04-19T20:05:40 | 2021-04-19T20:05:40 | 276,978,388 | 4 | 2 | MIT | 2020-07-16T18:06:26 | 2020-07-03T20:02:20 | C++ | UTF-8 | C++ | false | false | 1,183 | h | #ifndef ABSTRACTTHREADEDSERVER_H
#define ABSTRACTTHREADEDSERVER_H
#include "abstractserverconnector.h"
#include "threadpool.h"
#include <memory>
#include <thread>
namespace jsonrpc {
class AbstractThreadedServer : public AbstractServerConnector {
public:
AbstractThreadedServer(size_t threads);
virtual ~AbstractThreadedServer();
virtual bool StartListening();
virtual bool StopListening();
protected:
/**
* @brief InitializeListener should initialize sockets, file descriptors etc.
* @return
*/
virtual bool InitializeListener() = 0;
/**
* @brief CheckForConnection should poll for a new connection. This must be
* a non-blocking call.
* @return a handle which is passed on to HandleConnection()
*/
virtual int CheckForConnection() = 0;
/**
* @brief HandleConnection must handle connection information for a given
* handle that has been returned by CheckForConnection()
* @param connection
*/
virtual void HandleConnection(int connection) = 0;
private:
bool running;
std::unique_ptr<std::thread> listenerThread;
ThreadPool threadPool;
size_t threads;
void ListenLoop();
};
}
#endif // ABSTRACTTHREADEDSERVER_H
| [
"37732338+who-biz@users.noreply.github.com"
] | 37732338+who-biz@users.noreply.github.com |
a53340474a7998f3e8b116c7db8d26c323f89576 | 1a283ec7b87dc77b86637baf9d99382127f42059 | /HDU_1064.cpp | 78aa3c9c9d333e887cc515553c9f149c5f407cee | [] | no_license | he1l0world/Acm-trainning | c185ebae4498ce07529be044ec994d2c2826094b | acd6273eade71d50455e0c579744655cfa0a0851 | refs/heads/master | 2021-09-20T21:52:40.713255 | 2018-08-15T23:10:10 | 2018-08-15T23:10:10 | 111,166,844 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 245 | cpp | #include<iostream>
#include<iomanip>
int main ()
{
using namespace std;
double sum = 0;
double a;
for(int i = 0 ; i < 12 ; ++i)
{
cin >> a;
sum += a;
}
cout << fixed << setprecision(2) << "$" <<sum/12 <<endl;
return 0;
}
| [
"hellochen19970916@gmail.com"
] | hellochen19970916@gmail.com |
eb260235376f7af7dc9d6cbdd63ffc457868a1b7 | 9ee3fc7acc5ed8ae8316040c3a6758dfdbdee1dd | /src/VectorizedStressMajorization/ShortestPath.h | 72f3827ffc2cdb0dfffad675d3b5b0c3d526b118 | [
"MIT"
] | permissive | Ideas-Laboratory/vectorized_stress_majorization | f54248c58d4d5d0b0d09d8cb8f9b056f7dbdf769 | 00eff1a0f94fb1742f12756912ff7e072684b114 | refs/heads/master | 2022-04-22T22:12:36.725810 | 2020-04-17T15:28:34 | 2020-04-17T15:28:34 | 241,616,407 | 8 | 1 | null | null | null | null | GB18030 | C++ | false | false | 512 | h | #ifndef ShortestPath_H
#define ShortestPath_H
#include "BasicHeader.h"
#include <string>
using namespace std;
const int maxnum = 100000;
//const int maxint = 99;
class ShortestPath
{
public:
ShortestPath(int max);
~ShortestPath();
void Dijkstra(int n, int v, int *dist, int *prev, MatrixXf c);
MatrixXf edgelistToShortestPath(int n, Edges& edgelist);
void initToMaxint(int maxint, int n, int*& dist);
int maxint;
//int n, line; // 图的结点数和路径数
};
#endif | [
"root@DESKTOP-OLUT1QP.localdomain"
] | root@DESKTOP-OLUT1QP.localdomain |
a2648c2e47c5ef8ccd271c291bd7d2766a55694e | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function13796/function13796_schedule_17/function13796_schedule_17_wrapper.cpp | 5ce497a4acea81c826dfd2abdc1ac3c937a35c5f | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 935 | cpp | #include "Halide.h"
#include "function13796_schedule_17_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(128, 2048, 256);
Halide::Buffer<int32_t> buf0(128, 2048, 256);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function13796_schedule_17(buf00.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function13796/function13796_schedule_17/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
b1ec296c27eb97fc8ee1dd03e5d5e8e2396d79c3 | 4ea1ba3326a0e2317fc1541a3055f1a370962114 | /Cpp/Listing14-1/main.cpp | a552f95e942bc116e74ace22a753f5d82ca1c6d0 | [] | no_license | lxmiccio/QtCppExercises | 8a7b4e894755b17ed6bacce58e52378251a5964e | aada77e949c4391aaf7dc46255c4c0339f689f21 | refs/heads/master | 2020-09-25T21:19:23.568178 | 2016-11-01T13:26:22 | 2016-11-01T13:26:22 | 67,614,705 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 266 | cpp | #include <cstdio>
#include <fstream>
#include <iostream>
int main()
{
std::ifstream in {"list1401.txt"};
if(not in) {
std::perror("list1401.txt");
} else {
int x {};
while(in >> x) {
std::cout << x << std::endl;
}
in.close();
}
}
| [
"alex.miccio@artgroup.local"
] | alex.miccio@artgroup.local |
6fae0b00a60e413b43d07b0176ba405a8649bbbd | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/Editor/UnrealEd/Private/Fbx/FBxLibs.cpp | 62a73bb7d4fd6df715e7a1d07c224ef07403d0f1 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 1,562 | cpp | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "FbxLibs.h"
#include "FbxExporter.h"
//-------------------------------------------------------------------------
// Memory management callback functions used by the FBX SDK
//-------------------------------------------------------------------------
void* MyMalloc(size_t pSize)
{
return FMemory::Malloc(pSize);
}
void* MyCalloc(size_t pCount,size_t pSize)
{
void* Alloc = FMemory::Malloc(pCount*pSize);
return FMemory::Memzero(Alloc, pCount*pSize);
}
void* MyRealloc(void* pData, size_t pSize)
{
return FMemory::Realloc(pData, pSize);
}
void MyFree(void* pData)
{
FMemory::Free(pData);
}
void LoadFBxLibraries()
{
// Specify global memory handler callbacks to be used by the FBX SDK
FbxSetMallocHandler( &MyMalloc);
FbxSetCallocHandler( &MyCalloc);
FbxSetReallocHandler( &MyRealloc);
FbxSetFreeHandler( &MyFree);
}
void UnloadFBxLibraries()
{
UnFbx::FFbxImporter::DeleteInstance();
UnFbx::FFbxExporter::DeleteInstance();
// Hack: After we have freed our fbx sdk instance we need to set back to the default fbx memory handlers.
// This is required because there are some allocations made in the FBX dllmain before it is possible to set up our custom allocators
// If this is not done, memory created by one allocator will be freed by another
FbxSetMallocHandler( FbxGetDefaultMallocHandler() );
FbxSetCallocHandler( FbxGetDefaultCallocHandler() );
FbxSetReallocHandler( FbxGetDefaultReallocHandler() );
FbxSetFreeHandler( FbxGetDefaultFreeHandler() );
}
| [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
c1a06a828d780c14b183a1043bbd29e00eebc578 | 9a0a8b698e0b3753db02b23fca0c95cc404290a1 | /include/balor/gui/DragDrop.hpp | 619aad7af11e119238349f744d4f04a6b25fecbc | [] | no_license | pdpdds/balor-chb | 77099e4139a8f98f75df907f8cb535e99afad848 | 76e97bd598566ecf23fab462e8895e3581c1118e | refs/heads/master | 2021-01-18T11:59:53.378036 | 2014-07-24T02:39:02 | 2014-07-24T02:39:02 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 12,835 | hpp | #pragma once
#include <balor/gui/Control.hpp>
#include <balor/system/ComPtr.hpp>
#include <balor/Enum.hpp>
#include <balor/OutOfMemoryException.hpp>
#include <balor/StringRangeArray.hpp>
struct _IMAGELIST;
struct IDataObject;
namespace balor {
namespace graphics {
class Bitmap;
}
namespace io {
class MemoryStream;
class Stream;
}
}
namespace balor {
namespace gui {
/**
* ドラッグ&ドロップ機能を提供する。
*
* ドラッグを開始するコントロールを指定して DragDrop::Source を作成し、Control::onDrag イベントまたは任意のイベントから DragDrop::Source::doDragDrop 関数でドラッグドロップを開始する。
* ドロップするコントロールを指定して DragDrop::Target を作成し、DragDrop::Target::onDrop イベントでドロップされたデータを処理する。
*
* <h3>・サンプルコード</h3>
* <pre><code>
Frame frame(L"DragDrop Sample");
Label label(frame, 20, 10, 0, 0, L"ここに文字列をドラッグ、またはここから文字列をドラッグできる");
label.edge(Label::Edge::client);
label.resize();
DragDrop::Target target(label);
target.onDrop() = [&] (DragDrop::Drop& e) {
if (e.data().containsText()) {
label.text(e.data().getText());
}
};
target.onMove() = [&] (DragDrop::Move& e) {
if (!e.data().containsText()) {
// 文字列のドラッグでなければ受け付けないアイコン表示にする。
e.effect(DragDrop::Effect::none);
}
};
DragDrop::Source source(label);
label.onDrag() = [&] (Control::Drag& e) {
if (e.lButton()) {
Bitmap bitmap(label.size());
label.drawTo(bitmap);
ImageList list(label.size());
list.add(bitmap);
source.doDragDrop(label.text(), DragDrop::Effect::move, list, 0, e.position().x, e.position().y);
}
};
frame.runMessageLoop();
* </code></pre>
*/
class DragDrop {
public:
typedef ::_IMAGELIST* HIMAGELIST;
typedef Control::HBITMAP HBITMAP;
typedef Control::HCURSOR HCURSOR;
typedef ::balor::graphics::Bitmap Bitmap;
typedef ::balor::io::MemoryStream MemoryStream;
typedef ::balor::io::Stream Stream;
class Data;
class Source;
private:
class DropSource;
class DropTarget;
public:
/// メモリが足りなかった。
struct OutOfMemoryException : public ::balor::OutOfMemoryException {};
/// ドラッグ&ドロップ操作。組み合わせで指定する。
struct Effect {
enum _enum {
none = 0 , /// 何も行われなかった。
copy = 1 , /// コピー操作を行う。
move = 2 , /// 移動操作を行う。
link = 4 , /// ショートカットの作成操作を行う。
scroll = 0x80000000, ///
};
BALOR_NAMED_LOGICAL_ENUM_MEMBERS(Effect);
};
/// ドラッグ中のデータをドロップしたイベント。
struct Drop : public Control::Event {
Drop(Control& sender, const Data& data, Effect allowedEffects, int keyState, const Point& position);
/// ドラッグ元が許可する操作の組み合わせ。
DragDrop::Effect allowedEffects() const;
/// ALT キーが押されているかどうか。
bool alt() const;
/// CTRL キーが押されているかどうか。
bool ctrl() const;
/// ドラッグしているデータ。
const DragDrop::Data& data() const;
/// ドラッグ&ドロップの操作。組み合わせではない値になる。初期値はエクスプローラと同じ挙動。
DragDrop::Effect effect() const;
void effect(DragDrop::Effect value);
/// マウスの左ボタンが押されているかどうか。
bool lButton() const;
/// マウスの中央ボタンが押されているかどうか。
bool mButton() const;
/// マウスカーソルの位置。
const Point& position() const;
/// マウスの右ボタンが押されているかどうか。
bool rButton() const;
/// Shift キーが押されているかどうか。
bool shift() const;
private:
const Data& _data;
Effect _allowedEffects;
int _keyState;
Point _position;
Effect _effect;
};
/// ドラッグ中のマウスカーソルがコントロール上に入ったイベント。
typedef Drop Enter;
/// ドラッグ&ドロップの操作 に対して適切なカーソルを設定するイベント。設定しなかった場合はシステムのデフォルトの挙動になる。
/// DragDrop::Target クラスの onDragEnter や onDragMove イベント等の後に発生する。
struct Feedback : public Control::Event {
Feedback(Control& sender, Effect effect);
/// カーソルを設定する。設定しなかった場合はシステムのデフォルトのカーソルになる。
void cursor(HCURSOR value);
/// 現状のドラッグ&ドロップの操作。
DragDrop::Effect effect() const;
private:
friend DropSource;
Effect _effect;
bool _useDefaultCursor;
};
/// ドラッグ中のマウスカーソルがコントロール上から出たイベント。
typedef Control::Event Leave;
/// ドラッグ中にマウスカーソルがコントロール上を移動したイベント。
typedef Drop Move;
/// キー入力状態等からドラッグ&ドロップを続行するかキャンセルするか決めるイベント。
/// DragDrop::Target クラスの onDragEnter や onDragMove イベント等の前に発生する。
struct QueryContinue : public Control::Event {
QueryContinue(Control& sender, bool esc, int keyState);
/// ALT キーが押されているかどうか。
bool alt() const;
/// ドラッグ&ドロップをキャンセルするかどうか。
bool cancelDrag() const;
void cancelDrag(bool value);
/// CTRL キーが押されているかどうか。
bool ctrl() const;
/// ドロップしてドラッグ&ドロップを終了するかどうか。
bool drop() const;
void drop(bool value);
/// ESC キーが押されたかどうか。
bool esc() const;
/// マウスの左ボタンが押されているかどうか。
bool lButton() const;
/// マウスの中央ボタンが押されているかどうか。
bool mButton() const;
/// マウスの右ボタンが押されているかどうか。
bool rButton() const;
/// Shift キーが押されているかどうか。
bool shift() const;
private:
bool _esc;
int _keyState;
bool _cancelDrag;
bool _drop;
};
public:
/// ドラッグ&ドロップするデータを表す。
/// ユーザ定義のデータを使用する場合は registerMemoryFormat 関数で一意な名前でメモリフォーマットを登録する。
class Data : private NonCopyable {
friend Source;
public:
/// 空のデータを作成。
Data();
Data(Data&& value);
/// ビットマップを持つデータを作成。
Data(HBITMAP bitmap);
Data(const Bitmap& bitmap);
/// ユーザ定義のメモリデータを持つデータを作成。
Data(int memoryFormat, MemoryStream& stream);
/// 文字列を持つデータを作成。
Data(const String& text);
Data(const wchar_t* text);
Data(const std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >& text);
Data(::IDataObject* dataObject);
~Data();
Data& operator=(Data&& value);
public:
/// データに ビットマップが含まれるかどうか。
bool containsBitmap() const;
/// データに DIB ビットマップが含まれるかどうか。
bool containsDIB() const;
/// データにファイルドロップリストが含まれるかどうか。
bool containsFileDropList() const;
/// データにユーザ定義のメモリデータが含まれるかどうか。
bool containsMemory(int memoryFormat) const;
/// データに文字列が含まれるかどうか。
bool containsText() const;
/// DDB ビットマップを取得する。無い場合はヌルのビットマップを返す。
Bitmap getBitmap() const;
/// DIB ビットマップを取得する。無い場合はヌルのビットマップを返す。
Bitmap getDIB() const;
/// ファイルドロップリストを取得する。無い場合は空の配列を返す。
std::vector<String, std::allocator<String> > getFileDropList() const;
/// ユーザ定義のメモリデータを取得する。無い場合は空のメモリストリームを返す。
MemoryStream getMemory(int memoryFormat) const;
/// 文字列を取得する。無い場合は空文字列を返す。
String getText() const;
/// ユーザ定義のメモリフォーマット名を登録し、メモリフォーマットを返す。メモリフォーマット名が他のプロセスで既に登録されていたら同じメモリフォーマットを返す。
static int registerMemoryFormat(StringRange memoryFormatName);
/// DDB ビットマップを設定する。
void setBitmap(HBITMAP value);
/// DIB ビットマップを設定する。
void setDIB(HBITMAP value);
/// ファイルドロップリストを設定する。
void setFileDropList(StringRangeArray value);
/// ユーザ定義のメモリデータを設定する。
void setMemory(int memoryFormat, Stream& stream);
/// 文字列を設定する。
void setText(StringRange value);
private:
::balor::system::ComPtr<::IDataObject> _dataObject;
};
/// ドラッグ&ドロップを開始するコントロールを表す。
class Source : private NonCopyable {
public:
/// 未初期化状態。
Source();
Source(Source&& value);
/// ドラッグ&ドロップの開始点となるコントロールを指定して作成。
Source(Control& control);
~Source();
Source& operator=(Source&& value);
public:
/// ドラッグ&ドロップを開始する。最終的に行われた操作を返す。allowedEffect には許可するドラッグ&ドロップ操作の組み合わせを設定する。
/// また画像リストとその画像インデックス、画像の左上からみたマウスカーソルの位置を指定してマウスカーソルに重ねて画像を表示することができる。
DragDrop::Effect doDragDrop(const DragDrop::Data& data, DragDrop::Effect allowedEffects = Effect::copy | Effect::move | Effect::link | Effect::scroll
, HIMAGELIST imageList = nullptr, int imageIndex = 0, int xHotSpot = 0, int yHotSpot = 0);
/// ドラッグ&ドロップの操作に対して適切なカーソルを設定するイベント。設定しなかった場合はシステムのデフォルトの挙動になる。
Listener<DragDrop::Feedback&>& onFeedback();
/// キー入力状態等からドラッグ&ドロップを続行するかキャンセルするか決めるイベント。
Listener<DragDrop::QueryContinue&>& onQueryContinue();
private:
::balor::system::ComPtr<DropSource> _dropSource;
};
/// ドラッグ&ロップを受け取るコントロールを表す。
/// 要注意!このクラスはコンストラクタ引数に渡した Control よりも先に破壊しないとメモリリークする。
class Target : private NonCopyable {
public:
/// 未初期化状態。
Target();
Target(Target&& value);
/// ドラッグ&ドロップを受け取るコントロールを指定して作成。
Target(Control& control);
~Target();
Target& operator=(Target&& value);
public:
/// ドロップしたイベント。
Listener<DragDrop::Drop&>& onDrop();
/// ドラッグ中のマウスカーソルがコントロール上に入ったイベント。ここで DragDrop::Enter::data() 関数がどのデータを持っているか調べて
/// 処理できるデータが無ければ DragDrop::Enter::effect() に DragDrop::Effect::none を指定したりする。
Listener<DragDrop::Enter&>& onEnter();
/// ドラッグ中のマウスカーソルがコントロール上から出たイベント。
Listener<DragDrop::Leave&>& onLeave();
/// ドラッグ中にマウスカーソルがコントロール上を移動したイベント。ここで DragDrop::Move::data() 関数がどのデータを持っているか調べて
/// 処理できるデータが無ければ DragDrop::Move::effect() に DragDrop::Effect::none を指定したりする。
Listener<DragDrop::Move&>& onMove();
private:
::balor::system::ComPtr<DropTarget> _dropTarget;
};
public:
/// マウスボタンを押しながら移動した時にドラッグ&ドロップを開始する移動範囲のシステム標準。
static Size defaultDragSize();
};
}
} | [
"jacking75@gmail.com"
] | jacking75@gmail.com |
e6d1c3c2121f0478cdcc1ac8ea2a4761a208c68e | 4f4ddc396fa1dfc874780895ca9b8ee4f7714222 | /src/activex/G2Com/NBConReq.cpp | dfb3e487f2ba88e9cd5921f04f91b39f9b57b41d | [] | no_license | UtsavChokshiCNU/GenSym-Test2 | 3214145186d032a6b5a7486003cef40787786ba0 | a48c806df56297019cfcb22862dd64609fdd8711 | refs/heads/master | 2021-01-23T23:14:03.559378 | 2017-09-09T14:20:09 | 2017-09-09T14:20:09 | 102,960,203 | 3 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 3,690 | cpp | // NBConReq.cpp: implementation of the NBConReq class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "G2Com.h"
#include "Gateway.h"
#include "NBConReq.h"
#include "GsiContext.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
NBConReq::NBConReq(GsiContext *Context, TCHAR *InterfaceName, TCHAR *ClassName,
TCHAR *Host, unsigned short Port, TCHAR *RemoteInitString)
: ConnectingRequest(Context, InterfaceName, ClassName,
Host, Port, RemoteInitString, NBConnect)
{}
NBConReq::~NBConReq()
{}
//
// Here is the logic to actually connect to the remote system
// Returns 0 or -1
//
int NBConReq::invoke()
{
Gatekeeper gk(&mLocker) ;
GsiContext *pContext = GsiContext::FindContext(mContextObjId);
if (!pContext)
{
SetComError(OLESTR("Internal Error"));
return -9;
}
if (pContext->mIsConnected)
return 0; // If we are already connected, ok, done
TCHAR buf[100];
_itot(mPort, buf, 10); // Convert to string for GSI
TCHAR buf2[1024]; // make the interface name upper case
_tcscpy(buf2, mClassName);
for (TCHAR *ptr = buf2; *ptr; ptr++)
{
*ptr = _totupper(*ptr);
}
pContext->mConnReqId = Id();
gk.unLock() ;
int ret = gsi_initiate_connection_with_user_data((gsi_char *)(TCHAR *)mInterfaceName, (gsi_char *)buf2,
((VARIANT_FALSE == pContext->getDiscOnReset()) ? TRUE : FALSE),
(gsi_char *)_T("TCP/IP"), (gsi_char *)(TCHAR *)mHost,(gsi_char *) buf, (gsi_char *)(TCHAR *)mRemoteInitString, (void *) pContext->mObjId);
if (ret)
{
SetComError(OLESTR("Unable to create connection with G2"));
return -1;
}
getContext()->mCtxKilled = FALSE ;
return 0; // ok
}
void NBConReq::error()
{
Gatekeeper gk(&mLocker) ;
GsiContext *pContext = GsiContext::FindContext(mContextObjId);
if (!pContext)
return;
pContext->mConnReqId = 0; // no longer connecting
CallData *cd = new CallData;
// Notify container of error
cd->CallId = -1;
cd->EventCode = GSI_EVENT_ERROR;
cd->ErrorCode = mErrorCode;
USES_CONVERSION;
// cd->ErrorMessage = SysAllocString(A2W((char *) mErrorMessage));
cd->ErrorMessage = mErrorMessage;
pContext->FireEventInThread(cd);
stateToError() ;
}
void NBConReq::timeout()
{
Gatekeeper gk(&mLocker) ;
GsiContext *pContext = GsiContext::FindContext(mContextObjId);
if (!pContext)
return;
pContext->mConnReqId = 0;
CallData *cd = new CallData;
cd->CallId = -1;
cd->EventCode = GSI_EVENT_ERROR;
cd->ErrorCode = 0;
// cd->ErrorMessage = SysAllocString(L"Timeout on non blocking connection attempt");
cd->ErrorMessage = L"Timeout on non blocking connection attempt";
pContext->FireEventInThread(cd);
stateToError() ;
}
//
// Ok, the request happened.
//
// This is called on the GSI run loop thread
//
void NBConReq::complete()
{
Gatekeeper gk(&mLocker) ;
// int ThreadId = GetCurrentThreadId();
GsiContext *pContext = getContext() ;
if (!pContext)
return;
ATLTRACE2(atrAxlMsgs,1,"Connection Complete\n");
pContext->mIsConnected = true; // now connecting
pContext->mContext = gsi_current_context(); // save context number
pContext->mConnReqId = 0; // no longer pending connection
CallData *cd = new CallData;
cd->EventCode = GSI_EVENT_CONNECT;
pContext->FireEventInThread(cd);
stateToProcessed() ;
}
| [
"utsavchokshi@Utsavs-MacBook-Pro.local"
] | utsavchokshi@Utsavs-MacBook-Pro.local |
89ab6636d894cabc8c47f6dfd5c60f14fdbbf95e | 52dc9080af88c00222cc9b37aa08c35ff3cafe86 | /1300/30/1333a.cpp | 8231e8e76b7fb94f17833a30e3dd6606d63b9e1b | [
"Unlicense"
] | permissive | shivral/cf | 1c1acde25fc6af775acaeeb6b5fe5aa9bbcfd4d2 | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | refs/heads/master | 2023-03-20T01:29:25.559828 | 2021-03-05T08:30:30 | 2021-03-05T08:30:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 649 | cpp | #include <iostream>
char color(unsigned n, unsigned m, unsigned i, unsigned j)
{
if (n % 2 == 0 && i == n-1 && j == 0)
return 'B';
if (n % 2 == 1 && m % 2 == 0 && i == 0 && j == m-1)
return 'B';
return (i + j) % 2 == 0 ? 'B' : 'W';
}
void solve(unsigned n, unsigned m)
{
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < m; ++j)
std::cout << color(n, m, i, j);
std::cout << '\n';
}
}
void test_case()
{
unsigned n, m;
std::cin >> n >> m;
solve(n, m);
}
int main()
{
size_t t;
std::cin >> t;
while (t-- > 0)
test_case();
return 0;
}
| [
"5691735+actium@users.noreply.github.com"
] | 5691735+actium@users.noreply.github.com |
3373009c8d502f123acd2f9a919f464fcd4f38bb | 1b10d0f11660d0a2dd88fc785a88ed41592e4a31 | /aten/src/ATen/native/cuda/BatchLinearAlgebra.cpp | 9dbf27789e8b0a34e8924626c598e28f53689ad4 | [
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla",
"BSL-1.0",
"Apache-2.0"
] | permissive | qqa6/pytorch | be28537054c7e5df94e7531013f775ca91f3ae61 | a17a4e93ce7abf2f24f61e025eb374bdc2810a50 | refs/heads/master | 2023-08-25T17:08:39.562144 | 2021-10-19T01:02:58 | 2021-10-19T01:04:22 | 418,726,305 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 127,184 | cpp | #include <ATen/Context.h>
#include <ATen/cuda/CUDAContext.h>
#include <ATen/Dispatch.h>
#include <ATen/NativeFunctions.h>
#include <ATen/cuda/PinnedMemoryAllocator.h>
#include <ATen/cuda/detail/IndexUtils.cuh>
#include <ATen/native/LinearAlgebraUtils.h>
#include <ATen/native/cuda/MiscUtils.h>
#include <ATen/native/Resize.h>
#include <ATen/native/LinearAlgebra.h>
#include <ATen/native/BatchLinearAlgebra.h>
#include <ATen/native/cuda/BatchLinearAlgebraLib.h>
#include <ATen/native/cpu/zmath.h>
#if AT_MAGMA_ENABLED()
#include <magma_types.h>
#include <magma_v2.h>
#include <ATen/cuda/detail/CUDAHooks.h>
const bool use_magma_ = true;
namespace {
struct MagmaInitializer {
MagmaInitializer() {
::at::cuda::detail::set_magma_init_fn([]{ magma_init(); });
};
} initializer;
} // namespace (anonymous)
#else
const bool use_magma_ = false;
#endif
namespace at {
namespace native {
#if AT_MAGMA_ENABLED()
template<class scalar_t>
void magmaSolve(
magma_int_t n, magma_int_t nrhs, scalar_t* dA, magma_int_t ldda,
magma_int_t* ipiv, scalar_t* dB, magma_int_t lddb, magma_int_t* info);
template<class scalar_t>
void magmaSolveBatched(
magma_int_t n, magma_int_t nrhs, scalar_t** dA_array, magma_int_t ldda,
magma_int_t** dipiv_array, scalar_t** dB_array, magma_int_t lddb,
magma_int_t* dinfo_array, magma_int_t batch_count, const MAGMAQueue& magma_queue);
template<class scalar_t>
void magmaLu(
magma_int_t m, magma_int_t n, scalar_t* dA, magma_int_t ldda,
magma_int_t* ipiv, magma_int_t* info);
template<class scalar_t>
void magmaLuBatched(
magma_int_t m, magma_int_t n, scalar_t** dA_array, magma_int_t ldda,
magma_int_t** ipiv_array, magma_int_t* info_array, magma_int_t batchsize,
const MAGMAQueue& magma_queue);
template<class scalar_t>
void magmaLuNoPiv(
magma_int_t m, magma_int_t n, scalar_t* dA, magma_int_t ldda,
magma_int_t* info);
template<class scalar_t>
void magmaLuNoPivBatched(
magma_int_t m, magma_int_t n, scalar_t** dA_array, magma_int_t ldda,
magma_int_t* info_array, magma_int_t batchsize, const MAGMAQueue& magma_queue);
template<class scalar_t>
inline magma_int_t magmaGetriOptimalBlocksize(magma_int_t n);
template<class scalar_t>
void magmaGetri(
magma_int_t n, scalar_t* dA, magma_int_t ldda, magma_int_t* ipiv, scalar_t* dwork,
magma_int_t lwork, magma_int_t* info);
template<class scalar_t>
void magmaGetriBatched(
magma_int_t n, scalar_t** dA_array, magma_int_t ldda,
magma_int_t** ipiv_array, scalar_t** dinvA_array, magma_int_t lddia,
magma_int_t* info_array, magma_int_t batchsize, const MAGMAQueue& magma_queue);
template<class scalar_t>
void magmaCholeskySolve(
magma_uplo_t uplo, magma_int_t n, magma_int_t nrhs, scalar_t* dA, magma_int_t ldda,
scalar_t* dB, magma_int_t lddb, magma_int_t* info);
template<class scalar_t>
void magmaCholeskySolveBatched(
magma_uplo_t uplo, magma_int_t n, magma_int_t nrhs, scalar_t** dA_array, magma_int_t ldda,
scalar_t** dB_array, magma_int_t lddb, magma_int_t& info, magma_int_t batchsize, const MAGMAQueue& magma_queue);
template<class scalar_t>
void magmaCholesky(
magma_uplo_t uplo, magma_int_t n, scalar_t* dA,
magma_int_t ldda, magma_int_t* info);
template<class scalar_t>
void magmaCholeskyBatched(
magma_uplo_t uplo, magma_int_t n, scalar_t** dA_array, magma_int_t ldda,
magma_int_t* info_array, magma_int_t batchsize, const MAGMAQueue& magma_queue);
template<class scalar_t>
void magmaTriangularSolveBatched(
magma_side_t side, magma_uplo_t uplo, magma_trans_t trans, magma_diag_t diag, magma_int_t m, magma_int_t n,
scalar_t** dA_array, magma_int_t ldda, scalar_t** dB_array, magma_int_t lddb, magma_int_t batchsize,
const MAGMAQueue& magma_queue);
template<class scalar_t>
inline magma_int_t magmaGeqrfOptimalBlocksize(magma_int_t m, magma_int_t n);
template<class scalar_t>
void magmaGeqrf(
magma_int_t m, magma_int_t n, scalar_t* dA, magma_int_t ldda,
scalar_t* tau, scalar_t* dT, magma_int_t* info, bool is_v2);
template<class scalar_t>
void magmaOrgqr(
magma_int_t m, magma_int_t n, magma_int_t k, scalar_t* dA,
magma_int_t ldda, scalar_t* tau, scalar_t* dT, magma_int_t nb, magma_int_t* info);
template<class scalar_t, class value_t=scalar_t>
void magmaSyevd(
magma_vec_t jobz, magma_uplo_t uplo, magma_int_t n, scalar_t* dA, magma_int_t ldda,
value_t* w, scalar_t* wA, magma_int_t ldwa, scalar_t* work, magma_int_t lwork, value_t* rwork,
magma_int_t lrwork, magma_int_t* iwork, magma_int_t liwork, magma_int_t* info);
template<class scalar_t, class value_t=scalar_t>
void magmaEig(
magma_vec_t jobvl, magma_vec_t jobvr, magma_int_t n, scalar_t *A, magma_int_t lda,
scalar_t *w, scalar_t *VL, magma_int_t ldvl,
scalar_t *VR, magma_int_t ldvr, scalar_t *work, magma_int_t lwork,
value_t *rwork,
magma_int_t *info);
template<class scalar_t, class value_t=scalar_t>
void magmaSvd(
magma_vec_t jobz, magma_int_t m, magma_int_t n, scalar_t* A,
magma_int_t lda, value_t* s, scalar_t* U, magma_int_t ldu,
scalar_t* VT, magma_int_t ldvt, scalar_t* work, magma_int_t lwork,
value_t* rwork,
magma_int_t* iwork, magma_int_t* info);
template<class scalar_t>
void magmaLuSolve(
magma_int_t n, magma_int_t nrhs, scalar_t* dA, magma_int_t ldda, magma_int_t* ipiv,
scalar_t* dB, magma_int_t lddb, magma_int_t* info, magma_trans_t trans);
template<class scalar_t>
void magmaLuSolveBatched(
magma_int_t n, magma_int_t nrhs, scalar_t** dA_array, magma_int_t ldda, magma_int_t** dipiv_array,
scalar_t** dB_array, magma_int_t lddb, magma_int_t& info,
magma_int_t batchsize, const MAGMAQueue& magma_queue, magma_trans_t trans);
template<class scalar_t>
void magmaGels(
magma_trans_t trans, magma_int_t m, magma_int_t n, magma_int_t nrhs,
scalar_t* dA, magma_int_t ldda, scalar_t* dB, magma_int_t lddb,
scalar_t* hwork, magma_int_t lwork, magma_int_t* info);
template<>
void magmaSolve<double>(
magma_int_t n, magma_int_t nrhs, double* dA, magma_int_t ldda,
magma_int_t* ipiv, double* dB, magma_int_t lddb, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_dgesv_gpu(n, nrhs, dA, ldda, ipiv, dB, lddb, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaSolve<float>(
magma_int_t n, magma_int_t nrhs, float* dA, magma_int_t ldda,
magma_int_t* ipiv, float* dB, magma_int_t lddb, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_sgesv_gpu(n, nrhs, dA, ldda, ipiv, dB, lddb, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaSolve<c10::complex<double>>(
magma_int_t n, magma_int_t nrhs, c10::complex<double>* dA, magma_int_t ldda,
magma_int_t* ipiv, c10::complex<double>* dB, magma_int_t lddb, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_zgesv_gpu(n, nrhs,
reinterpret_cast<magmaDoubleComplex*>(dA), ldda, ipiv,
reinterpret_cast<magmaDoubleComplex*>(dB), lddb, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaSolve<c10::complex<float>>(
magma_int_t n, magma_int_t nrhs, c10::complex<float>* dA, magma_int_t ldda,
magma_int_t* ipiv, c10::complex<float>* dB, magma_int_t lddb, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_cgesv_gpu(n, nrhs,
reinterpret_cast<magmaFloatComplex*>(dA), ldda, ipiv,
reinterpret_cast<magmaFloatComplex*>(dB), lddb, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaSolveBatched<double>(
magma_int_t n, magma_int_t nrhs, double** dA_array, magma_int_t ldda,
magma_int_t** dipiv_array, double** dB_array, magma_int_t lddb,
magma_int_t* dinfo_array, magma_int_t batch_count, const MAGMAQueue& magma_queue) {
magma_dgesv_batched(n, nrhs, dA_array, ldda, dipiv_array, dB_array, lddb, dinfo_array, batch_count, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaSolveBatched<float>(
magma_int_t n, magma_int_t nrhs, float** dA_array, magma_int_t ldda,
magma_int_t** dipiv_array, float** dB_array, magma_int_t lddb,
magma_int_t* dinfo_array, magma_int_t batch_count, const MAGMAQueue& magma_queue) {
magma_sgesv_batched(n, nrhs, dA_array, ldda, dipiv_array, dB_array, lddb, dinfo_array, batch_count, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaSolveBatched<c10::complex<double>>(
magma_int_t n, magma_int_t nrhs, c10::complex<double>** dA_array, magma_int_t ldda,
magma_int_t** dipiv_array, c10::complex<double>** dB_array, magma_int_t lddb,
magma_int_t* dinfo_array, magma_int_t batch_count, const MAGMAQueue& magma_queue) {
magma_zgesv_batched(n, nrhs,
reinterpret_cast<magmaDoubleComplex**>(dA_array), ldda, dipiv_array,
reinterpret_cast<magmaDoubleComplex**>(dB_array), lddb, dinfo_array, batch_count, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaSolveBatched<c10::complex<float>>(
magma_int_t n, magma_int_t nrhs, c10::complex<float>** dA_array, magma_int_t ldda,
magma_int_t** dipiv_array, c10::complex<float>** dB_array, magma_int_t lddb,
magma_int_t* dinfo_array, magma_int_t batch_count, const MAGMAQueue& magma_queue) {
magma_cgesv_batched(n, nrhs,
reinterpret_cast<magmaFloatComplex**>(dA_array), ldda, dipiv_array,
reinterpret_cast<magmaFloatComplex**>(dB_array), lddb, dinfo_array, batch_count, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLu<double>(
magma_int_t m, magma_int_t n, double* dA, magma_int_t ldda,
magma_int_t* ipiv, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_dgetrf_gpu(m, n, dA, ldda, ipiv, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLu<float>(
magma_int_t m, magma_int_t n, float* dA, magma_int_t ldda,
magma_int_t* ipiv, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_sgetrf_gpu(m, n, dA, ldda, ipiv, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLu<c10::complex<double>>(
magma_int_t m, magma_int_t n, c10::complex<double>* dA, magma_int_t ldda,
magma_int_t* ipiv, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_zgetrf_gpu(m, n, reinterpret_cast<magmaDoubleComplex*>(dA), ldda, ipiv, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLu<c10::complex<float>>(
magma_int_t m, magma_int_t n, c10::complex<float>* dA, magma_int_t ldda,
magma_int_t* ipiv, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_cgetrf_gpu(m, n, reinterpret_cast<magmaFloatComplex*>(dA), ldda, ipiv, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuBatched<double>(
magma_int_t m, magma_int_t n, double** dA_array, magma_int_t ldda,
magma_int_t** ipiv_array, magma_int_t* info_array, magma_int_t batchsize,
const MAGMAQueue& magma_queue) {
magma_dgetrf_batched(m, n, dA_array, ldda, ipiv_array, info_array, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuBatched<float>(
magma_int_t m, magma_int_t n, float** dA_array, magma_int_t ldda,
magma_int_t** ipiv_array, magma_int_t* info_array, magma_int_t batchsize,
const MAGMAQueue& magma_queue) {
magma_sgetrf_batched(m, n, dA_array, ldda, ipiv_array, info_array, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuBatched<c10::complex<double>>(
magma_int_t m, magma_int_t n, c10::complex<double>** dA_array, magma_int_t ldda,
magma_int_t** ipiv_array, magma_int_t* info_array, magma_int_t batchsize,
const MAGMAQueue& magma_queue) {
magma_zgetrf_batched(m, n, reinterpret_cast<magmaDoubleComplex**>(dA_array), ldda, ipiv_array, info_array, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuBatched<c10::complex<float>>(
magma_int_t m, magma_int_t n, c10::complex<float>** dA_array, magma_int_t ldda,
magma_int_t** ipiv_array, magma_int_t* info_array, magma_int_t batchsize,
const MAGMAQueue& magma_queue) {
magma_cgetrf_batched(m, n, reinterpret_cast<magmaFloatComplex**>(dA_array), ldda, ipiv_array, info_array, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuNoPiv<double>(
magma_int_t m, magma_int_t n, double* dA, magma_int_t ldda,
magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_dgetrf_nopiv_gpu(m, n, dA, ldda, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuNoPiv<float>(
magma_int_t m, magma_int_t n, float* dA, magma_int_t ldda,
magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_sgetrf_nopiv_gpu(m, n, dA, ldda, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuNoPiv<c10::complex<double>>(
magma_int_t m, magma_int_t n, c10::complex<double>* dA, magma_int_t ldda,
magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_zgetrf_nopiv_gpu(m, n, reinterpret_cast<magmaDoubleComplex*>(dA), ldda, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuNoPiv<c10::complex<float>>(
magma_int_t m, magma_int_t n, c10::complex<float>* dA, magma_int_t ldda,
magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_cgetrf_nopiv_gpu(m, n, reinterpret_cast<magmaFloatComplex*>(dA), ldda, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuNoPivBatched<double>(
magma_int_t m, magma_int_t n, double** dA_array, magma_int_t ldda,
magma_int_t* info_array, magma_int_t batchsize, const MAGMAQueue& magma_queue) {
magma_dgetrf_nopiv_batched(m, n, dA_array, ldda, info_array, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuNoPivBatched<float>(
magma_int_t m, magma_int_t n, float** dA_array, magma_int_t ldda,
magma_int_t* info_array, magma_int_t batchsize, const MAGMAQueue& magma_queue) {
magma_sgetrf_nopiv_batched(m, n, dA_array, ldda, info_array, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuNoPivBatched<c10::complex<double>>(
magma_int_t m, magma_int_t n, c10::complex<double>** dA_array, magma_int_t ldda,
magma_int_t* info_array, magma_int_t batchsize, const MAGMAQueue& magma_queue) {
magma_zgetrf_nopiv_batched(m, n, reinterpret_cast<magmaDoubleComplex**>(dA_array), ldda, info_array, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuNoPivBatched<c10::complex<float>>(
magma_int_t m, magma_int_t n, c10::complex<float>** dA_array, magma_int_t ldda,
magma_int_t* info_array, magma_int_t batchsize, const MAGMAQueue& magma_queue) {
magma_cgetrf_nopiv_batched(m, n, reinterpret_cast<magmaFloatComplex**>(dA_array), ldda, info_array, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
inline magma_int_t magmaGetriOptimalBlocksize<double>(magma_int_t n) {
return magma_get_dgetri_nb(n);
}
template<>
inline magma_int_t magmaGetriOptimalBlocksize<float>(magma_int_t n) {
return magma_get_sgetri_nb(n);
}
template <>
inline magma_int_t magmaGetriOptimalBlocksize<c10::complex<double>>(
magma_int_t n) {
return magma_get_zgetri_nb(n);
}
template <>
inline magma_int_t magmaGetriOptimalBlocksize<c10::complex<float>>(
magma_int_t n) {
return magma_get_cgetri_nb(n);
}
template<>
void magmaGetri<double>(
magma_int_t n, double* dA, magma_int_t ldda, magma_int_t* ipiv, double* dwork,
magma_int_t lwork, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_dgetri_gpu(n, dA, ldda, ipiv, dwork, lwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaGetri<float>(
magma_int_t n, float* dA, magma_int_t ldda, magma_int_t* ipiv, float* dwork,
magma_int_t lwork, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_sgetri_gpu(n, dA, ldda, ipiv, dwork, lwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template <>
void magmaGetri<c10::complex<double>>(
magma_int_t n,
c10::complex<double>* dA,
magma_int_t ldda,
magma_int_t* ipiv,
c10::complex<double>* dwork,
magma_int_t lwork,
magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_zgetri_gpu(
n,
reinterpret_cast<magmaDoubleComplex*>(dA),
ldda,
ipiv,
reinterpret_cast<magmaDoubleComplex*>(dwork),
lwork,
info);
AT_CUDA_CHECK(cudaGetLastError());
}
template <>
void magmaGetri<c10::complex<float>>(
magma_int_t n,
c10::complex<float>* dA,
magma_int_t ldda,
magma_int_t* ipiv,
c10::complex<float>* dwork,
magma_int_t lwork,
magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_cgetri_gpu(
n,
reinterpret_cast<magmaFloatComplex*>(dA),
ldda,
ipiv,
reinterpret_cast<magmaFloatComplex*>(dwork),
lwork,
info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaGetriBatched<double>(
magma_int_t n, double** dA_array, magma_int_t ldda,
magma_int_t** ipiv_array, double** dinvA_array, magma_int_t lddia,
magma_int_t* info_array, magma_int_t batchsize, const MAGMAQueue& magma_queue) {
magma_dgetri_outofplace_batched(n, dA_array, ldda, ipiv_array, dinvA_array, lddia, info_array, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaGetriBatched<float>(
magma_int_t n, float** dA_array, magma_int_t ldda,
magma_int_t** ipiv_array, float** dinvA_array, magma_int_t lddia,
magma_int_t* info_array, magma_int_t batchsize, const MAGMAQueue& magma_queue) {
magma_sgetri_outofplace_batched(n, dA_array, ldda, ipiv_array, dinvA_array, lddia, info_array, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template <>
void magmaGetriBatched<c10::complex<double>>(
magma_int_t n,
c10::complex<double>** dA_array,
magma_int_t ldda,
magma_int_t** ipiv_array,
c10::complex<double>** dinvA_array,
magma_int_t lddia,
magma_int_t* info_array,
magma_int_t batchsize,
const MAGMAQueue& magma_queue) {
magma_zgetri_outofplace_batched(
n,
reinterpret_cast<magmaDoubleComplex**>(dA_array),
ldda,
ipiv_array,
reinterpret_cast<magmaDoubleComplex**>(dinvA_array),
lddia,
info_array,
batchsize,
magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template <>
void magmaGetriBatched<c10::complex<float>>(
magma_int_t n,
c10::complex<float>** dA_array,
magma_int_t ldda,
magma_int_t** ipiv_array,
c10::complex<float>** dinvA_array,
magma_int_t lddia,
magma_int_t* info_array,
magma_int_t batchsize,
const MAGMAQueue& magma_queue) {
magma_cgetri_outofplace_batched(
n,
reinterpret_cast<magmaFloatComplex**>(dA_array),
ldda,
ipiv_array,
reinterpret_cast<magmaFloatComplex**>(dinvA_array),
lddia,
info_array,
batchsize,
magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaCholeskySolve<double>(
magma_uplo_t uplo, magma_int_t n, magma_int_t nrhs, double* dA, magma_int_t ldda,
double* dB, magma_int_t lddb, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_dpotrs_gpu(uplo, n, nrhs, dA, ldda, dB, lddb, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaCholeskySolve<float>(
magma_uplo_t uplo, magma_int_t n, magma_int_t nrhs, float* dA, magma_int_t ldda,
float* dB, magma_int_t lddb, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_spotrs_gpu(uplo, n, nrhs, dA, ldda, dB, lddb, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaCholeskySolve<c10::complex<double>>(
magma_uplo_t uplo, magma_int_t n, magma_int_t nrhs, c10::complex<double>* dA, magma_int_t ldda,
c10::complex<double>* dB, magma_int_t lddb, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_zpotrs_gpu(uplo, n, nrhs,
reinterpret_cast<magmaDoubleComplex*>(dA), ldda,
reinterpret_cast<magmaDoubleComplex*>(dB), lddb, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaCholeskySolve<c10::complex<float>>(
magma_uplo_t uplo, magma_int_t n, magma_int_t nrhs, c10::complex<float>* dA, magma_int_t ldda,
c10::complex<float>* dB, magma_int_t lddb, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_cpotrs_gpu(uplo, n, nrhs,
reinterpret_cast<magmaFloatComplex*>(dA), ldda,
reinterpret_cast<magmaFloatComplex*>(dB), lddb, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaCholeskySolveBatched<double>(
magma_uplo_t uplo, magma_int_t n, magma_int_t nrhs, double** dA_array, magma_int_t ldda,
double** dB_array, magma_int_t lddb, magma_int_t& info, magma_int_t batchsize, const MAGMAQueue& magma_queue) {
info = magma_dpotrs_batched(uplo, n, nrhs, dA_array, ldda, dB_array, lddb, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaCholeskySolveBatched<float>(
magma_uplo_t uplo, magma_int_t n, magma_int_t nrhs, float** dA_array, magma_int_t ldda,
float** dB_array, magma_int_t lddb, magma_int_t& info, magma_int_t batchsize, const MAGMAQueue& magma_queue) {
info = magma_spotrs_batched(uplo, n, nrhs, dA_array, ldda, dB_array, lddb, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaCholeskySolveBatched<c10::complex<double>>(
magma_uplo_t uplo, magma_int_t n, magma_int_t nrhs, c10::complex<double>** dA_array, magma_int_t ldda,
c10::complex<double>** dB_array, magma_int_t lddb, magma_int_t& info, magma_int_t batchsize, const MAGMAQueue& magma_queue) {
info = magma_zpotrs_batched(uplo, n, nrhs,
reinterpret_cast<magmaDoubleComplex**>(dA_array), ldda,
reinterpret_cast<magmaDoubleComplex**>(dB_array), lddb, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaCholeskySolveBatched<c10::complex<float>>(
magma_uplo_t uplo, magma_int_t n, magma_int_t nrhs, c10::complex<float>** dA_array, magma_int_t ldda,
c10::complex<float>** dB_array, magma_int_t lddb, magma_int_t& info, magma_int_t batchsize, const MAGMAQueue& magma_queue) {
info = magma_cpotrs_batched(uplo, n, nrhs,
reinterpret_cast<magmaFloatComplex**>(dA_array), ldda,
reinterpret_cast<magmaFloatComplex**>(dB_array), lddb, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaCholesky<double>(
magma_uplo_t uplo, magma_int_t n, double* dA,
magma_int_t ldda, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_dpotrf_gpu(uplo, n, dA, ldda, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaCholesky<float>(
magma_uplo_t uplo, magma_int_t n, float* dA,
magma_int_t ldda, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_spotrf_gpu(uplo, n, dA, ldda, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaCholesky<c10::complex<double>>(
magma_uplo_t uplo, magma_int_t n, c10::complex<double>* dA,
magma_int_t ldda, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_zpotrf_gpu(uplo, n, reinterpret_cast<magmaDoubleComplex*>(dA), ldda, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaCholesky<c10::complex<float>>(
magma_uplo_t uplo, magma_int_t n, c10::complex<float>* dA,
magma_int_t ldda, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_cpotrf_gpu(uplo, n, reinterpret_cast<magmaFloatComplex*>(dA), ldda, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaCholeskyBatched<double>(
magma_uplo_t uplo, magma_int_t n, double** dA_array, magma_int_t ldda,
magma_int_t* info_array, magma_int_t batchsize, const MAGMAQueue& magma_queue) {
magma_dpotrf_batched(uplo, n, dA_array, ldda, info_array, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaCholeskyBatched<float>(
magma_uplo_t uplo, magma_int_t n, float** dA_array, magma_int_t ldda,
magma_int_t* info_array, magma_int_t batchsize, const MAGMAQueue& magma_queue) {
magma_spotrf_batched(uplo, n, dA_array, ldda, info_array, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaCholeskyBatched<c10::complex<double>>(
magma_uplo_t uplo, magma_int_t n, c10::complex<double>** dA_array, magma_int_t ldda,
magma_int_t* info_array, magma_int_t batchsize, const MAGMAQueue& magma_queue) {
magma_zpotrf_batched(uplo, n, reinterpret_cast<magmaDoubleComplex**>(dA_array), ldda, info_array, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaCholeskyBatched<c10::complex<float>>(
magma_uplo_t uplo, magma_int_t n, c10::complex<float>** dA_array, magma_int_t ldda,
magma_int_t* info_array, magma_int_t batchsize, const MAGMAQueue& magma_queue) {
magma_cpotrf_batched(uplo, n, reinterpret_cast<magmaFloatComplex**>(dA_array), ldda, info_array, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaTriangularSolveBatched<double>(
magma_side_t side, magma_uplo_t uplo, magma_trans_t trans, magma_diag_t diag, magma_int_t m, magma_int_t n,
double** dA_array, magma_int_t ldda, double** dB_array, magma_int_t lddb, magma_int_t batchsize,
const MAGMAQueue& magma_queue) {
magmablas_dtrsm_batched(side, uplo, trans, diag, m, n, 1, dA_array, ldda, dB_array, lddb, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaTriangularSolveBatched<float>(
magma_side_t side, magma_uplo_t uplo, magma_trans_t trans, magma_diag_t diag, magma_int_t m, magma_int_t n,
float** dA_array, magma_int_t ldda, float** dB_array, magma_int_t lddb, magma_int_t batchsize,
const MAGMAQueue& magma_queue) {
magmablas_strsm_batched(side, uplo, trans, diag, m, n, 1, dA_array, ldda, dB_array, lddb, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaTriangularSolveBatched<c10::complex<double>>(
magma_side_t side, magma_uplo_t uplo, magma_trans_t trans, magma_diag_t diag, magma_int_t m, magma_int_t n,
c10::complex<double>** dA_array, magma_int_t ldda, c10::complex<double>** dB_array, magma_int_t lddb, magma_int_t batchsize,
const MAGMAQueue& magma_queue) {
magmaDoubleComplex alpha({1, 0});
magmablas_ztrsm_batched(side, uplo, trans, diag, m, n, alpha,
reinterpret_cast<magmaDoubleComplex**>(dA_array), ldda,
reinterpret_cast<magmaDoubleComplex**>(dB_array), lddb, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaTriangularSolveBatched<c10::complex<float>>(
magma_side_t side, magma_uplo_t uplo, magma_trans_t trans, magma_diag_t diag, magma_int_t m, magma_int_t n,
c10::complex<float>** dA_array, magma_int_t ldda, c10::complex<float>** dB_array, magma_int_t lddb, magma_int_t batchsize,
const MAGMAQueue& magma_queue) {
magmaFloatComplex alpha({1, 0});
magmablas_ctrsm_batched(side, uplo, trans, diag, m, n, alpha,
reinterpret_cast<magmaFloatComplex**>(dA_array), ldda,
reinterpret_cast<magmaFloatComplex**>(dB_array), lddb, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
inline magma_int_t magmaGeqrfOptimalBlocksize<double>(magma_int_t m, magma_int_t n) {
return magma_get_dgeqrf_nb(m, n);
}
template<>
inline magma_int_t magmaGeqrfOptimalBlocksize<float>(magma_int_t m, magma_int_t n) {
return magma_get_sgeqrf_nb(m, n);
}
template <>
inline magma_int_t magmaGeqrfOptimalBlocksize<c10::complex<double>>(
magma_int_t m,
magma_int_t n) {
return magma_get_zgeqrf_nb(m, n);
}
template <>
inline magma_int_t magmaGeqrfOptimalBlocksize<c10::complex<float>>(
magma_int_t m,
magma_int_t n) {
return magma_get_cgeqrf_nb(m, n);
}
template<>
void magmaGeqrf<double>(
magma_int_t m, magma_int_t n, double* dA, magma_int_t ldda,
double* tau, double* dT, magma_int_t* info, bool is_v2) {
MagmaStreamSyncGuard guard;
if (!is_v2) {
magma_dgeqrf_gpu(m, n, dA, ldda, tau, dT, info);
} else {
magma_dgeqrf2_gpu(m, n, dA, ldda, tau, info);
}
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaGeqrf<float>(
magma_int_t m, magma_int_t n, float* dA, magma_int_t ldda,
float* tau, float* dT, magma_int_t* info, bool is_v2) {
MagmaStreamSyncGuard guard;
if (!is_v2) {
magma_sgeqrf_gpu(m, n, dA, ldda, tau, dT, info);
} else {
magma_sgeqrf2_gpu(m, n, dA, ldda, tau, info);
}
AT_CUDA_CHECK(cudaGetLastError());
}
template <>
void magmaGeqrf<c10::complex<double>>(
magma_int_t m,
magma_int_t n,
c10::complex<double>* dA,
magma_int_t ldda,
c10::complex<double>* tau,
c10::complex<double>* dT,
magma_int_t* info,
bool is_v2) {
MagmaStreamSyncGuard guard;
if (!is_v2) {
magma_zgeqrf_gpu(
m,
n,
reinterpret_cast<magmaDoubleComplex*>(dA),
ldda,
reinterpret_cast<magmaDoubleComplex*>(tau),
reinterpret_cast<magmaDoubleComplex*>(dT),
info);
} else {
magma_zgeqrf2_gpu(
m,
n,
reinterpret_cast<magmaDoubleComplex*>(dA),
ldda,
reinterpret_cast<magmaDoubleComplex*>(tau),
info);
}
AT_CUDA_CHECK(cudaGetLastError());
}
template <>
void magmaGeqrf<c10::complex<float>>(
magma_int_t m,
magma_int_t n,
c10::complex<float>* dA,
magma_int_t ldda,
c10::complex<float>* tau,
c10::complex<float>* dT,
magma_int_t* info,
bool is_v2) {
MagmaStreamSyncGuard guard;
if (!is_v2) {
magma_cgeqrf_gpu(
m,
n,
reinterpret_cast<magmaFloatComplex*>(dA),
ldda,
reinterpret_cast<magmaFloatComplex*>(tau),
reinterpret_cast<magmaFloatComplex*>(dT),
info);
} else {
magma_cgeqrf2_gpu(
m,
n,
reinterpret_cast<magmaFloatComplex*>(dA),
ldda,
reinterpret_cast<magmaFloatComplex*>(tau),
info);
}
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaOrgqr<double>(
magma_int_t m, magma_int_t n, magma_int_t k, double* dA, magma_int_t ldda,
double* tau, double* dT, magma_int_t nb, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_dorgqr_gpu(m, n, k, dA, ldda, tau, dT, nb, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaOrgqr<float>(
magma_int_t m, magma_int_t n, magma_int_t k, float* dA, magma_int_t ldda,
float* tau, float* dT, magma_int_t nb, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_sorgqr_gpu(m, n, k, dA, ldda, tau, dT, nb, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template <>
void magmaOrgqr<c10::complex<double>>(
magma_int_t m,
magma_int_t n,
magma_int_t k,
c10::complex<double>* dA,
magma_int_t ldda,
c10::complex<double>* tau,
c10::complex<double>* dT,
magma_int_t nb,
magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_zungqr_gpu(
m,
n,
k,
reinterpret_cast<magmaDoubleComplex*>(dA),
ldda,
reinterpret_cast<magmaDoubleComplex*>(tau),
reinterpret_cast<magmaDoubleComplex*>(dT),
nb,
info);
AT_CUDA_CHECK(cudaGetLastError());
}
template <>
void magmaOrgqr<c10::complex<float>>(
magma_int_t m,
magma_int_t n,
magma_int_t k,
c10::complex<float>* dA,
magma_int_t ldda,
c10::complex<float>* tau,
c10::complex<float>* dT,
magma_int_t nb,
magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_cungqr_gpu(
m,
n,
k,
reinterpret_cast<magmaFloatComplex*>(dA),
ldda,
reinterpret_cast<magmaFloatComplex*>(tau),
reinterpret_cast<magmaFloatComplex*>(dT),
nb,
info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaSyevd<double>(
magma_vec_t jobz, magma_uplo_t uplo, magma_int_t n, double* dA, magma_int_t ldda,
double* w, double* wA, magma_int_t ldwa, double* work, magma_int_t lwork, double* rwork,
magma_int_t lrwork, magma_int_t* iwork, magma_int_t liwork, magma_int_t* info) {
(void)rwork; // unused
(void)lrwork; // unused
MagmaStreamSyncGuard guard;
magma_dsyevd_gpu(jobz, uplo, n, dA, ldda, w, wA, ldwa, work, lwork, iwork, liwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaSyevd<float>(
magma_vec_t jobz, magma_uplo_t uplo, magma_int_t n, float* dA, magma_int_t ldda,
float* w, float* wA, magma_int_t ldwa, float* work, magma_int_t lwork, float* rwork,
magma_int_t lrwork, magma_int_t* iwork, magma_int_t liwork, magma_int_t* info) {
(void)rwork; // unused
(void)lrwork; // unused
MagmaStreamSyncGuard guard;
magma_ssyevd_gpu(jobz, uplo, n, dA, ldda, w, wA, ldwa, work, lwork, iwork, liwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaSyevd<c10::complex<double>, double>(
magma_vec_t jobz, magma_uplo_t uplo, magma_int_t n, c10::complex<double>* dA, magma_int_t ldda,
double* w, c10::complex<double>* wA, magma_int_t ldwa, c10::complex<double>* work, magma_int_t lwork, double* rwork,
magma_int_t lrwork, magma_int_t* iwork, magma_int_t liwork, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_zheevd_gpu(
jobz, uplo, n, reinterpret_cast<magmaDoubleComplex*>(dA), ldda, w, reinterpret_cast<magmaDoubleComplex*>(wA),
ldwa, reinterpret_cast<magmaDoubleComplex*>(work), lwork, rwork, lrwork, iwork, liwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaSyevd<c10::complex<float>, float>(
magma_vec_t jobz, magma_uplo_t uplo, magma_int_t n, c10::complex<float>* dA, magma_int_t ldda,
float* w, c10::complex<float>* wA, magma_int_t ldwa, c10::complex<float>* work, magma_int_t lwork, float* rwork,
magma_int_t lrwork, magma_int_t* iwork, magma_int_t liwork, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_cheevd_gpu(
jobz, uplo, n, reinterpret_cast<magmaFloatComplex*>(dA), ldda, w, reinterpret_cast<magmaFloatComplex*>(wA),
ldwa, reinterpret_cast<magmaFloatComplex*>(work), lwork, rwork, lrwork, iwork, liwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaEig<double>(
magma_vec_t jobvl, magma_vec_t jobvr, magma_int_t n,
double *A, magma_int_t lda,
double *w,
double *VL, magma_int_t ldvl,
double *VR, magma_int_t ldvr,
double *work, magma_int_t lwork,
double *rwork,
magma_int_t *info) {
MagmaStreamSyncGuard guard;
// magma [sd]geev wants to separate output arrays: wr and wi for the real
// and imaginary parts
double *wr = w;
double *wi = w + n;
(void)rwork; // unused
magma_dgeev(jobvl, jobvr, n, A, lda, wr, wi, VL, ldvl, VR, ldvr, work, lwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaEig<float>(
magma_vec_t jobvl, magma_vec_t jobvr, magma_int_t n,
float *A, magma_int_t lda,
float *w,
float *VL, magma_int_t ldvl,
float *VR, magma_int_t ldvr,
float *work, magma_int_t lwork,
float *rwork,
magma_int_t *info) {
MagmaStreamSyncGuard guard;
float *wr = w;
float *wi = w + n;
(void)rwork; // unused
magma_sgeev(jobvl, jobvr, n, A, lda, wr, wi, VL, ldvl, VR, ldvr, work, lwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaEig<c10::complex<double>, double>(
magma_vec_t jobvl, magma_vec_t jobvr, magma_int_t n,
c10::complex<double> *A, magma_int_t lda,
c10::complex<double> *w,
c10::complex<double> *VL, magma_int_t ldvl,
c10::complex<double> *VR, magma_int_t ldvr,
c10::complex<double> *work, magma_int_t lwork,
double *rwork,
magma_int_t *info) {
MagmaStreamSyncGuard guard;
magma_zgeev(jobvl, jobvr, n,
reinterpret_cast<magmaDoubleComplex*>(A), lda,
reinterpret_cast<magmaDoubleComplex*>(w),
reinterpret_cast<magmaDoubleComplex*>(VL), ldvl,
reinterpret_cast<magmaDoubleComplex*>(VR), ldvr,
reinterpret_cast<magmaDoubleComplex*>(work), lwork,
rwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaEig<c10::complex<float>, float>(
magma_vec_t jobvl, magma_vec_t jobvr, magma_int_t n,
c10::complex<float> *A, magma_int_t lda,
c10::complex<float> *w,
c10::complex<float> *VL, magma_int_t ldvl,
c10::complex<float> *VR, magma_int_t ldvr,
c10::complex<float> *work, magma_int_t lwork,
float *rwork,
magma_int_t *info) {
MagmaStreamSyncGuard guard;
magma_cgeev(jobvl, jobvr, n,
reinterpret_cast<magmaFloatComplex*>(A), lda,
reinterpret_cast<magmaFloatComplex*>(w),
reinterpret_cast<magmaFloatComplex*>(VL), ldvl,
reinterpret_cast<magmaFloatComplex*>(VR), ldvr,
reinterpret_cast<magmaFloatComplex*>(work), lwork,
rwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaSvd<double>(
magma_vec_t jobz, magma_int_t m, magma_int_t n, double* A,
magma_int_t lda, double* s, double* U, magma_int_t ldu,
double* VT, magma_int_t ldvt, double* work, magma_int_t lwork,
double *rwork, magma_int_t* iwork, magma_int_t* info) {
(void)rwork; // unused
MagmaStreamSyncGuard guard;
magma_dgesdd(jobz, m, n, A, lda, s, U, ldu, VT, ldvt, work, lwork, iwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaSvd<float>(
magma_vec_t jobz, magma_int_t m, magma_int_t n, float* A,
magma_int_t lda, float* s, float* U, magma_int_t ldu,
float* VT, magma_int_t ldvt, float* work, magma_int_t lwork,
float* rwork, magma_int_t* iwork, magma_int_t* info) {
(void)rwork; // unused
MagmaStreamSyncGuard guard;
magma_sgesdd(jobz, m, n, A, lda, s, U, ldu, VT, ldvt, work, lwork, iwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaSvd<c10::complex<float>, float>(
magma_vec_t jobz, magma_int_t m, magma_int_t n, c10::complex<float>* A,
magma_int_t lda, float* s, c10::complex<float>* U, magma_int_t ldu,
c10::complex<float>* VT, magma_int_t ldvt, c10::complex<float>* work, magma_int_t lwork,
float *rwork, magma_int_t* iwork, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_cgesdd(jobz, m, n, reinterpret_cast<magmaFloatComplex*>(A), lda, s,
reinterpret_cast<magmaFloatComplex*>(U), ldu,
reinterpret_cast<magmaFloatComplex*>(VT), ldvt,
reinterpret_cast<magmaFloatComplex*>(work), lwork,
rwork, iwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaSvd<c10::complex<double>, double>(
magma_vec_t jobz, magma_int_t m, magma_int_t n, c10::complex<double>* A,
magma_int_t lda, double* s, c10::complex<double>* U, magma_int_t ldu,
c10::complex<double>* VT, magma_int_t ldvt, c10::complex<double>* work, magma_int_t lwork,
double *rwork, magma_int_t* iwork, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_zgesdd(jobz, m, n, reinterpret_cast<magmaDoubleComplex*>(A), lda, s,
reinterpret_cast<magmaDoubleComplex*>(U), ldu,
reinterpret_cast<magmaDoubleComplex*>(VT), ldvt,
reinterpret_cast<magmaDoubleComplex*>(work), lwork,
rwork, iwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuSolve<double>(
magma_int_t n, magma_int_t nrhs, double* dA, magma_int_t ldda, magma_int_t* ipiv,
double* dB, magma_int_t lddb, magma_int_t* info, magma_trans_t trans) {
MagmaStreamSyncGuard guard;
magma_dgetrs_gpu(trans, n, nrhs, dA, ldda, ipiv, dB, lddb, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuSolve<float>(
magma_int_t n, magma_int_t nrhs, float* dA, magma_int_t ldda, magma_int_t* ipiv,
float* dB, magma_int_t lddb, magma_int_t* info, magma_trans_t trans) {
MagmaStreamSyncGuard guard;
magma_sgetrs_gpu(trans, n, nrhs, dA, ldda, ipiv, dB, lddb, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuSolve<c10::complex<double>>(
magma_int_t n, magma_int_t nrhs, c10::complex<double>* dA, magma_int_t ldda, magma_int_t* ipiv,
c10::complex<double>* dB, magma_int_t lddb, magma_int_t* info, magma_trans_t trans) {
MagmaStreamSyncGuard guard;
magma_zgetrs_gpu(trans, n, nrhs, reinterpret_cast<magmaDoubleComplex*>(dA), ldda, ipiv, reinterpret_cast<magmaDoubleComplex*>(dB), lddb, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuSolve<c10::complex<float>>(
magma_int_t n, magma_int_t nrhs, c10::complex<float>* dA, magma_int_t ldda, magma_int_t* ipiv,
c10::complex<float>* dB, magma_int_t lddb, magma_int_t* info, magma_trans_t trans) {
MagmaStreamSyncGuard guard;
magma_cgetrs_gpu(trans, n, nrhs, reinterpret_cast<magmaFloatComplex*>(dA), ldda, ipiv, reinterpret_cast<magmaFloatComplex*>(dB), lddb, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuSolveBatched<double>(
magma_int_t n, magma_int_t nrhs, double** dA_array, magma_int_t ldda, magma_int_t** dipiv_array,
double** dB_array, magma_int_t lddb, magma_int_t& info,
magma_int_t batchsize, const MAGMAQueue& magma_queue, magma_trans_t trans) {
info = magma_dgetrs_batched(trans, n, nrhs, dA_array, ldda, dipiv_array, dB_array, lddb, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuSolveBatched<float>(
magma_int_t n, magma_int_t nrhs, float** dA_array, magma_int_t ldda, magma_int_t** dipiv_array,
float** dB_array, magma_int_t lddb, magma_int_t& info,
magma_int_t batchsize, const MAGMAQueue& magma_queue, magma_trans_t trans) {
info = magma_sgetrs_batched(trans, n, nrhs, dA_array, ldda, dipiv_array, dB_array, lddb, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuSolveBatched<c10::complex<double>>(
magma_int_t n, magma_int_t nrhs, c10::complex<double>** dA_array, magma_int_t ldda, magma_int_t** dipiv_array,
c10::complex<double>** dB_array, magma_int_t lddb, magma_int_t& info,
magma_int_t batchsize, const MAGMAQueue& magma_queue, magma_trans_t trans) {
info = magma_zgetrs_batched(trans, n, nrhs, reinterpret_cast<magmaDoubleComplex**>(dA_array), ldda, dipiv_array, reinterpret_cast<magmaDoubleComplex**>(dB_array), lddb, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaLuSolveBatched<c10::complex<float>>(
magma_int_t n, magma_int_t nrhs, c10::complex<float>** dA_array, magma_int_t ldda, magma_int_t** dipiv_array,
c10::complex<float>** dB_array, magma_int_t lddb, magma_int_t& info,
magma_int_t batchsize, const MAGMAQueue& magma_queue, magma_trans_t trans) {
info = magma_cgetrs_batched(trans, n, nrhs, reinterpret_cast<magmaFloatComplex**>(dA_array), ldda, dipiv_array, reinterpret_cast<magmaFloatComplex**>(dB_array), lddb, batchsize, magma_queue.get_queue());
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaGels<float>(
magma_trans_t trans, magma_int_t m, magma_int_t n, magma_int_t nrhs,
float* dA, magma_int_t ldda, float* dB, magma_int_t lddb,
float* hwork, magma_int_t lwork, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_sgels_gpu(trans, m, n, nrhs,
dA, ldda, dB, lddb,
hwork, lwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaGels<double>(
magma_trans_t trans, magma_int_t m, magma_int_t n, magma_int_t nrhs,
double* dA, magma_int_t ldda, double* dB, magma_int_t lddb,
double* hwork, magma_int_t lwork, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_dgels_gpu(trans, m, n, nrhs,
dA, ldda, dB, lddb,
hwork, lwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaGels<c10::complex<float>>(
magma_trans_t trans, magma_int_t m, magma_int_t n, magma_int_t nrhs,
c10::complex<float>* dA, magma_int_t ldda, c10::complex<float>* dB, magma_int_t lddb,
c10::complex<float>* hwork, magma_int_t lwork, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_cgels_gpu(trans, m, n, nrhs,
reinterpret_cast<magmaFloatComplex*>(dA), ldda,
reinterpret_cast<magmaFloatComplex*>(dB), lddb,
reinterpret_cast<magmaFloatComplex*>(hwork), lwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
template<>
void magmaGels<c10::complex<double>>(
magma_trans_t trans, magma_int_t m, magma_int_t n, magma_int_t nrhs,
c10::complex<double>* dA, magma_int_t ldda, c10::complex<double>* dB, magma_int_t lddb,
c10::complex<double>* hwork, magma_int_t lwork, magma_int_t* info) {
MagmaStreamSyncGuard guard;
magma_zgels_gpu(trans, m, n, nrhs,
reinterpret_cast<magmaDoubleComplex*>(dA), ldda,
reinterpret_cast<magmaDoubleComplex*>(dB), lddb,
reinterpret_cast<magmaDoubleComplex*>(hwork), lwork, info);
AT_CUDA_CHECK(cudaGetLastError());
}
namespace {
/*
MAGMA can return errors both as a return value and in the info argument.
The return value and info should always be identical.
In general, the meaning is as given in this table.
Predefined error codes are large negative numbers. Using the symbolic
constants below is preferred, but the numeric values can be found in
include/magma_types.h.
Info | Description
----------- | -----------
info = 0 (MAGMA_SUCCESS) | Successful exit
info < 0, but small | For info = -i, the i-th argument had an illegal value
info > 0 | Function-specific error such as singular matrix
MAGMA_ERR_DEVICE_ALLOC | Could not allocate GPU device memory
MAGMA_ERR_HOST_ALLOC | Could not allocate CPU host memory
MAGMA_ERR_ILLEGAL_VALUE | An argument had an illegal value (deprecated; instead it should return -i to say the i-th argument was bad)
MAGMA_ERR_INVALID_PTR | Can't free pointer
MAGMA_ERR_NOT_IMPLEMENTED | Function or option not implemented
MAGMA_ERR_NOT_SUPPORTED | Function or option not supported on the current architecture
*/
void checkMagmaInternalError(magma_int_t info, const std::string& magma_function_name) {
// if info > 0 the error is function-specific, do nothing in this case
TORCH_CHECK(info >= 0,
"MAGMA error: ",
magma_strerror(info),
", info = ", info,
", when calling ", magma_function_name);
}
magma_trans_t to_magma(TransposeType trans) {
switch (trans) {
case TransposeType::NoTranspose: return MagmaNoTrans;
case TransposeType::Transpose: return MagmaTrans;
case TransposeType::ConjTranspose: return MagmaConjTrans;
}
TORCH_INTERNAL_ASSERT(false, "Invalid transpose type");
}
} // anonymous namespace
#endif // AT_MAGMA_ENABLED()
#define ALLOCATE_ARRAY(name, type, size) \
auto storage_##name = pin_memory<type>(size); \
name = static_cast<type*>(storage_##name.data());
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ solve ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <typename scalar_t>
static void apply_solve(Tensor& b, Tensor& A, Tensor& infos_out) {
#if !AT_MAGMA_ENABLED()
AT_ERROR("solve: MAGMA library not found in "
"compilation. Please rebuild with MAGMA.");
#else
auto A_data = A.data_ptr<scalar_t>();
auto b_data = b.data_ptr<scalar_t>();
magma_int_t n = magma_int_cast(A.size(-2), "A.size(-2)");
magma_int_t nrhs = magma_int_cast(b.size(-1), "b.size(-1)");
magma_int_t lda = std::max(magma_int_t{1}, n);
if (b.dim() == 2) {
auto ipiv = at::empty({n}, at::kInt);
// magmaSolve requires infos tensor to live on CPU
Tensor infos = at::empty(infos_out.sizes(), infos_out.options().device(kCPU));
magmaSolve<scalar_t>(n, nrhs, A_data, lda, ipiv.data_ptr<magma_int_t>(),
b_data, lda, infos.data_ptr<magma_int_t>());
infos_out.copy_(infos);
} else {
auto infos_data = infos_out.data_ptr<magma_int_t>();
auto A_mat_stride = matrixStride(A);
auto b_mat_stride = matrixStride(b);
magma_int_t batch_size = magma_int_cast(batchCount(A), "batchCount");
magma_int_t* ipiv_data;
magma_int_t** ipiv_array;
scalar_t** A_array;
scalar_t** b_array;
ALLOCATE_ARRAY(ipiv_data, magma_int_t, batch_size * n);
ALLOCATE_ARRAY(ipiv_array, magma_int_t*, batch_size);
ALLOCATE_ARRAY(A_array, scalar_t*, batch_size);
ALLOCATE_ARRAY(b_array, scalar_t*, batch_size);
// Set up the created arrays
for (int64_t i = 0; i < batch_size; i++) {
A_array[i] = &A_data[i * A_mat_stride];
b_array[i] = &b_data[i * b_mat_stride];
ipiv_array[i] = &ipiv_data[i * n];
}
MAGMAQueue magma_queue(b.get_device());
constexpr int64_t batch_limit = 65535;
// Compute as many batches of 65535 possible
// The number of "mini"-batches are floor(batch_size / batch_limit)
// and these cover floor(batch_size / batch_limit) * batch_limit matrix solves
int64_t mini_batches = batch_size / batch_limit, mini_idx;
for (mini_idx = 0; mini_idx < mini_batches * batch_limit; mini_idx += batch_limit) {
scalar_t** A_array_cur = &A_array[mini_idx];
scalar_t** b_array_cur = &b_array[mini_idx];
magma_int_t** ipiv_array_cur = &ipiv_array[mini_idx];
magma_int_t* info_array_cur = &infos_data[mini_idx];
magmaSolveBatched<scalar_t>(
n, nrhs, A_array_cur, lda, ipiv_array_cur, b_array_cur, lda,
info_array_cur, batch_limit, magma_queue);
}
// Compute whatever is left = batch_size - floor(batch_size / batch_limit) * batch_limit
// which concisely is equal to batch_size % batch_limit
if (batch_size % batch_limit != 0) {
magmaSolveBatched<scalar_t>(
n, nrhs, &A_array[mini_idx], lda, &ipiv_array[mini_idx], &b_array[mini_idx], lda,
&infos_data[mini_idx], batch_size % batch_limit, magma_queue);
}
}
#endif
}
std::tuple<Tensor, Tensor> _solve_helper_cuda(const Tensor& self, const Tensor& A) {
auto self_working_copy = cloneBatchedColumnMajor(self);
auto A_working_copy = cloneBatchedColumnMajor(A);
// infos might not get filled for empty inputs therefore at::zeros is used instead of at::empty
auto infos = at::zeros({std::max<int64_t>(1, batchCount(self))}, self.options().dtype(kInt));
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(self.scalar_type(), "solve_cuda", [&]{
apply_solve<scalar_t>(self_working_copy, A_working_copy, infos);
});
if (self.dim() > 2) {
batchCheckErrors(infos, "solve_cuda");
} else {
singleCheckErrors(infos.item().toInt(), "solve_cuda");
}
return std::tuple<Tensor, Tensor>(self_working_copy, A_working_copy);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ inverse ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
Computes the inverse of n-by-n matrix 'self', it is saved to 'self_inv'.
'infos' is an int Tensor containing error codes for each matrix in the batched input.
'infos_lu' is for holding magmaLU errors, and 'infos_getri' is for holding magmaGetri errors
For more information see MAGMA's documentation for GETRI and GETRF routines.
*/
template <typename scalar_t>
static void apply_batched_inverse(Tensor& self, Tensor& self_inv, Tensor& infos_lu, Tensor& infos_getri) {
#if !AT_MAGMA_ENABLED()
AT_ERROR("inverse: MAGMA library not found in "
"compilation. Please rebuild with MAGMA.");
#else
auto self_data = self.data_ptr<scalar_t>();
auto self_mat_stride = matrixStride(self);
auto self_inv_data = self_inv.data_ptr<scalar_t>();
auto self_inv_mat_stride = matrixStride(self_inv);
auto infos_lu_data = infos_lu.data_ptr<magma_int_t>();
auto infos_getri_data = infos_getri.data_ptr<magma_int_t>();
magma_int_t batch_size = magma_int_cast(batchCount(self), "batchCount");
// MAGMA does not work with batch_size == 0, let's return early in this case
if (batch_size == 0) {
return;
}
magma_int_t n = magma_int_cast(self.size(-2), "self.size(-2)");
magma_int_t lda = std::max<magma_int_t>(1, n);
magma_int_t* ipiv_data;
magma_int_t** ipiv_array;
scalar_t** self_array;
scalar_t** self_inv_array;
ALLOCATE_ARRAY(ipiv_data, magma_int_t, batch_size * lda);
ALLOCATE_ARRAY(ipiv_array, magma_int_t*, batch_size);
ALLOCATE_ARRAY(self_array, scalar_t*, batch_size);
ALLOCATE_ARRAY(self_inv_array, scalar_t*, batch_size);
// Set up the created arrays
for (int64_t i = 0; i < batch_size; i++) {
self_array[i] = &self_data[i * self_mat_stride];
self_inv_array[i] = &self_inv_data[i * self_inv_mat_stride];
ipiv_array[i] = &ipiv_data[i * n];
}
// magmaLuBatched leaves ipiv_data values unwritten for singular matrices.
// Initialize to avoid memory access violations inside magma kernels (gh-51930).
std::fill_n(ipiv_data, batch_size * n, 1);
MAGMAQueue magma_queue(self.get_device());
magmaLuBatched<scalar_t>(
n, n, self_array, lda, ipiv_array, infos_lu_data,
batch_size, magma_queue);
constexpr int64_t batch_limit = 65535;
// Compute as many batches of 65535 possible
// The number of "mini"-batches are floor(batch_size / batch_limit)
// and these cover floor(batch_size / batch_limit) * batch_limit matrix solves
int64_t mini_batches = batch_size / batch_limit, mini_idx;
for (mini_idx = 0; mini_idx < mini_batches * batch_limit; mini_idx += batch_limit) {
scalar_t** self_array_cur = &self_array[mini_idx];
scalar_t** self_inv_array_cur = &self_inv_array[mini_idx];
magma_int_t** ipiv_array_cur = &ipiv_array[mini_idx];
magma_int_t* info_array_cur_getri = &infos_getri_data[mini_idx];
magmaGetriBatched<scalar_t>(
n, self_array_cur, lda, ipiv_array_cur, self_inv_array_cur,
lda, info_array_cur_getri, batch_limit, magma_queue);
}
// Compute whatever is left = batch_size - floor(batch_size / batch_limit) * batch_limit
// which concisely is equal to batch_size % batch_limit
if (batch_size % batch_limit != 0) {
magmaGetriBatched<scalar_t>(
n, &self_array[mini_idx], lda, &ipiv_array[mini_idx], &self_inv_array[mini_idx],
lda, &infos_getri_data[mini_idx], batch_size % batch_limit, magma_queue);
}
#endif
}
template <typename scalar_t>
static void apply_single_inverse(Tensor& self, Tensor& info_lu, Tensor& info_getri) {
#if !AT_MAGMA_ENABLED()
AT_ERROR("inverse: MAGMA library not found in "
"compilation. Please rebuild with MAGMA.");
#else
auto self_data = self.data_ptr<scalar_t>();
magma_int_t n = magma_int_cast(self.size(-2), "self.size(-2)");
magma_int_t lda = std::max<magma_int_t>(1, n);
magma_int_t lwork = n * magmaGetriOptimalBlocksize<scalar_t>(n);
// magmaLu and magmaGetri requires info argument to live on CPU
// but info_lu and info_getri tensors are on the same device as self
magma_int_t info_lu_cpu = 0;
magma_int_t info_getri_cpu = 0;
Tensor ipiv = at::empty({lda}, at::kInt);
Tensor dwork = at::empty({lwork}, self.options());
magmaLu<scalar_t>(n, n, self_data, lda, ipiv.data_ptr<magma_int_t>(), &info_lu_cpu);
magmaGetri<scalar_t>(
n, self_data, lda, ipiv.data_ptr<magma_int_t>(), dwork.data_ptr<scalar_t>(), lwork, &info_getri_cpu);
info_lu.fill_(info_lu_cpu);
info_getri.fill_(info_getri_cpu);
#endif
}
Tensor _inverse_helper_cuda_legacy(const Tensor& self) {
auto self_inv_working_copy = cloneBatchedColumnMajor(self);
if (self.dim() > 2) {
auto infos_lu = at::zeros({std::max<int64_t>(1, batchCount(self))}, self.options().dtype(kInt));
auto infos_getri = at::zeros({std::max<int64_t>(1, batchCount(self))}, self.options().dtype(kInt));
auto self_working_copy = cloneBatchedColumnMajor(self);
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(self.scalar_type(), "inverse_cuda", [&]{
apply_batched_inverse<scalar_t>(
self_working_copy, self_inv_working_copy, infos_lu, infos_getri);
});
batchCheckErrors(infos_lu, "inverse_cuda");
batchCheckErrors(infos_getri, "inverse_cuda");
} else {
// magmaLu and magmaGetri requires infos tensor to live on CPU
auto infos_lu = at::zeros({1}, self.options().dtype(kInt).device(kCPU));
auto infos_getri = at::zeros({1}, self.options().dtype(kInt).device(kCPU));
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(self.scalar_type(), "inverse_cuda", [&]{
apply_single_inverse<scalar_t>(self_inv_working_copy, infos_lu, infos_getri);
});
singleCheckErrors(infos_lu.item().toInt(), "inverse_cuda");
singleCheckErrors(infos_getri.item().toInt(), "inverse_cuda");
}
return self_inv_working_copy;
}
Tensor _inverse_helper_cuda(const Tensor& self) {
#ifdef USE_CUSOLVER
if ((self.dim() == 2) || (/* self.dim() > 2 && */ batchCount(self) <= 2) || !use_magma_) {
return _inverse_helper_cuda_lib(self); // cusolver or cublas
} else {
return _inverse_helper_cuda_legacy(self); // magma-cuda
}
#else
return _inverse_helper_cuda_legacy(self); // magma-cuda
#endif
}
// This is a type dispatching helper function for 'apply_batched_inverse' and 'singleCheckErrors'
Tensor& _linalg_inv_out_helper_cuda_legacy(Tensor& result, Tensor& infos_lu, Tensor& infos_getri) {
// assuming result is in column major order and contains the matrices to invert
if (result.dim() > 2) {
auto input_working_copy = cloneBatchedColumnMajor(result);
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(result.scalar_type(), "linalg_inv_out_cuda", [&]{
apply_batched_inverse<scalar_t>(
input_working_copy, result, infos_lu, infos_getri);
});
} else {
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(result.scalar_type(), "linalg_inv_out_cuda", [&]{
apply_single_inverse<scalar_t>(result, infos_lu, infos_getri);
});
}
return result;
}
// This is a MAGMA/cuSOLVER dispatching helper function
Tensor& _linalg_inv_out_helper_cuda(Tensor &result, Tensor& infos_lu, Tensor& infos_getri) {
// This function calculates the inverse matrix in-place
// result should be in column major order and contain matrices to invert
#ifdef USE_CUSOLVER
if ((result.dim() == 2) || (/* result.dim() > 2 && */ batchCount(result) <= 2) || !use_magma_) {
return _linalg_inv_out_helper_cuda_lib(result, infos_lu, infos_getri); // cusolver or cublas
} else {
return _linalg_inv_out_helper_cuda_legacy(result, infos_lu, infos_getri); // magma-cuda
}
#else
return _linalg_inv_out_helper_cuda_legacy(result, infos_lu, infos_getri); // magma-cuda
#endif
return result;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ cholesky_solve ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <typename scalar_t>
static void apply_cholesky_solve(Tensor& b, Tensor& A, bool upper, int64_t& info) {
#if !AT_MAGMA_ENABLED()
AT_ERROR("cholesky_solve: MAGMA library not found in "
"compilation. Please rebuild with MAGMA.");
#else
magma_uplo_t uplo = upper ? MagmaUpper : MagmaLower;
auto A_data = A.data_ptr<scalar_t>();
auto b_data = b.data_ptr<scalar_t>();
magma_int_t n = magma_int_cast(A.size(-2), "A.size(-2)");
magma_int_t lda = std::max<magma_int_t>(1, n);
magma_int_t nrhs = magma_int_cast(b.size(-1), "b.size(-1)");
int info_tmp = 0;
if (b.dim() == 2) {
magmaCholeskySolve<scalar_t>(uplo, n, nrhs, A_data, lda,
b_data, lda, &info_tmp);
info = info_tmp;
} else {
auto A_mat_stride = matrixStride(A);
auto b_mat_stride = matrixStride(b);
magma_int_t batch_size = magma_int_cast(batchCount(A), "batchCount");
scalar_t** A_array;
scalar_t** b_array;
ALLOCATE_ARRAY(A_array, scalar_t*, batch_size);
ALLOCATE_ARRAY(b_array, scalar_t*, batch_size);
// Set up the created arrays
for (int64_t i = 0; i < batch_size; i++) {
A_array[i] = &A_data[i * A_mat_stride];
b_array[i] = &b_data[i * b_mat_stride];
}
MAGMAQueue magma_queue(b.get_device());
constexpr int64_t batch_limit = 65535;
// Compute as many batches of 65535 possible
// The number of "mini"-batches are floor(batch_size / batch_limit)
// and these cover floor(batch_size / batch_limit) * batch_limit matrix solves
int64_t mini_batches = batch_size / batch_limit, mini_idx;
for (mini_idx = 0; mini_idx < mini_batches * batch_limit; mini_idx += batch_limit) {
scalar_t** A_array_cur = &A_array[mini_idx];
scalar_t** b_array_cur = &b_array[mini_idx];
magmaCholeskySolveBatched<scalar_t>(
uplo, n, nrhs, A_array_cur, lda, b_array_cur, lda,
info_tmp, batch_limit, magma_queue);
if (info_tmp != 0) {
break;
}
}
// Compute whatever is left = batch_size - floor(batch_size / batch_limit) * batch_limit
// which concisely is equal to batch_size % batch_limit
if (batch_size % batch_limit != 0 && info_tmp == 0) {
magmaCholeskySolveBatched<scalar_t>(
uplo, n, nrhs, &A_array[mini_idx], lda, &b_array[mini_idx], lda,
info_tmp, batch_size % batch_limit, magma_queue);
}
info = info_tmp;
}
#endif
}
Tensor _cholesky_solve_helper_cuda_magma(const Tensor& self, const Tensor& A, bool upper) {
int64_t info = 0;
auto self_working_copy = cloneBatchedColumnMajor(self);
auto A_working_copy = cloneBatchedColumnMajor(A);
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(self.scalar_type(), "cholesky_solve_cuda", [&]{
apply_cholesky_solve<scalar_t>(self_working_copy, A_working_copy, upper, info);
});
TORCH_CHECK(info == 0, "MAGMA cholesky_solve : invalid argument: ", -info);
return self_working_copy;
}
// Todo: cusolverDn<T>potrsBatched only supports nrhs == 1 and does not have good performance.
// Batched cholesky_solve is dispatched to magma.
Tensor _cholesky_solve_helper_cuda(const Tensor& self, const Tensor& A, bool upper) {
#ifdef USE_CUSOLVER
if (batchCount(self) == 1 || !use_magma_) {
return _cholesky_solve_helper_cuda_cusolver(self, A, upper);
} else {
return _cholesky_solve_helper_cuda_magma(self, A, upper);
}
#else
return _cholesky_solve_helper_cuda_magma(self, A, upper);
#endif
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ cholesky ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <typename scalar_t>
static void apply_cholesky(const Tensor& self, bool upper, const Tensor& info) {
#if !AT_MAGMA_ENABLED()
TORCH_CHECK(
false,
"Calling torch.linalg.cholesky on a CUDA tensor requires compiling ",
"PyTorch with MAGMA. Please use PyTorch built with MAGMA support.");
#else
magma_uplo_t uplo = upper ? MagmaUpper : MagmaLower;
auto self_data = self.data_ptr<scalar_t>();
magma_int_t n = magma_int_cast(self.size(-2), "self.size(-2)");
auto lda = std::max<magma_int_t>(1, n);
if (self.dim() == 2) {
// magmaCholesky requires info to be on CPU
magma_int_t info_cpu = 0;
magmaCholesky<scalar_t>(uplo, n, self_data, lda, &info_cpu);
info.fill_(info_cpu);
} else {
TORCH_INTERNAL_ASSERT(info.is_cuda());
auto info_data = info.data_ptr<magma_int_t>();
// magmaCholeskyBatched supports only upper=false
uplo = MagmaLower;
auto self_mat_stride = matrixStride(self);
magma_int_t batch_size = magma_int_cast(batchCount(self), "batchCount");
scalar_t** self_array;
ALLOCATE_ARRAY(self_array, scalar_t*, batch_size);
// Set up the created arrays
for (int64_t i = 0; i < batch_size; i++) {
self_array[i] = &self_data[i * self_mat_stride];
}
MAGMAQueue magma_queue(self.get_device());
// Compute as many batches of 262140 possible
// 262140 is the size of the largest batch of matrices that can be run with
// violating maximum kernel configuration
// For complex input the batch limit is 65535 (determined experimentally, see https://github.com/pytorch/pytorch/pull/47047#discussion_r516086923 for more information)
int64_t batch_limit = self.is_complex() ? 65535 : 262140;
for (int64_t mini_idx = 0; mini_idx < batch_size; mini_idx += batch_limit) {
int64_t nbatches = std::min(batch_limit, batch_size - mini_idx);
scalar_t** self_array_cur = &self_array[mini_idx];
magma_int_t* info_array_cur = &info_data[mini_idx];
magmaCholeskyBatched<scalar_t>(
uplo, n, self_array_cur, lda, info_array_cur, nbatches, magma_queue);
}
}
#endif
}
void cholesky_helper_magma(const Tensor& input, bool upper, const Tensor& info) {
Tensor result = input;
if (input.dim() > 2) {
// MAGMA's batched cholesky operator has an off-by-one error causing IMA
// (see https://github.com/pytorch/pytorch/issues/42666). This code is based
// on the #cloneBatchedColumnMajor function however it pads the input with
// one extra element utilizing the fact that the resize_as_ method preserves
// the storage even if it's larger than the new sizes. This way if MAGMA
// reads off bounds it will still be valid user memory.
result = at::empty(input.numel() + 1, input.options());
result.resize_as_(input).transpose_(-2, -1);
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(result.mT().is_contiguous());
// batched MAGMA doesn't support upper=true
// we transpose and conjugate the input as a workaround
result.copy_(upper ? input.mH() : input);
}
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(
input.scalar_type(), "cholesky_cuda", [&] {
apply_cholesky<scalar_t>(result, upper, info);
});
if (input.dim() > 2) {
// if upper=true we need to tranpose and conjugate the result tensor
// because the cholesky decomposition is stored in the lower triangular part
if (upper) {
input.copy_(result.mH());
} else {
input.copy_(result);
}
}
}
static void cholesky_kernel(const Tensor& input, const Tensor& info, bool upper) {
#ifdef USE_CUSOLVER
if (batchCount(input) == 1 || !use_magma_ || use_cusolver_potrf_batched_) {
cholesky_helper_cusolver(input, upper, info);
} else {
cholesky_helper_magma(input, upper, info);
}
#else
cholesky_helper_magma(input, upper, info);
#endif // USE_CUSOLVER
}
REGISTER_CUDA_DISPATCH(cholesky_stub, &cholesky_kernel)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ cholesky_inverse ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
Computes the inverse of a symmetric (Hermitian) positive-definite matrix n-by-n matrix 'input' using the Cholesky solver
This is an in-place routine, content of 'input' is overwritten.
'infos' is an int Tensor containing error codes for each matrix in the batched input.
MAGMA requires 'infos' to reside in CPU memory.
For more information see MAGMA's documentation for POTRS routine.
*/
template <typename scalar_t>
static void apply_cholesky_inverse(Tensor& input, Tensor& infos, bool upper) {
#if !AT_MAGMA_ENABLED()
TORCH_CHECK(false, "cholesky_inverse: MAGMA library not found in compilation. Please rebuild with MAGMA.");
#else
// magmaCholeskyInverse (magma_dpotri_gpu) is slow because internally
// it transfers data several times between GPU and CPU and calls lapack routine on CPU
// using magmaCholeskySolveBatched is a lot faster
// note that magmaCholeskySolve is also slow
// 'input' is modified in-place we need to clone it and replace with a diagonal matrix
// for apply_cholesky_solve
auto input_working_copy = cloneBatchedColumnMajor(input);
// 'input' tensor has to be a batch of diagonal matrix
input.fill_(0);
input.diagonal(/*offset=*/0, /*dim1=*/-2, /*dim2=*/-1).fill_(1);
Tensor result_u, input_u;
if (input.dim() == 2) {
// unsqueezing here so that the batched version is used
result_u = input.unsqueeze(0);
input_u = input_working_copy.unsqueeze(0);
} else {
result_u = input;
input_u = input_working_copy;
}
// magma's potrs_batched doesn't take matrix-wise array of ints as an 'info' argument
// it returns a single 'magma_int_t'
// if info = 0 the operation is successful, if info = -i, the i-th parameter had an illegal value.
int64_t info_tmp = 0;
apply_cholesky_solve<scalar_t>(result_u, input_u, upper, info_tmp);
infos.fill_(info_tmp);
#endif
}
// This is a type dispatching helper function for 'apply_cholesky_inverse'
Tensor& cholesky_inverse_kernel_impl_magma(Tensor &result, Tensor& infos, bool upper) {
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(result.scalar_type(), "cholesky_inverse_out_cuda", [&]{
apply_cholesky_inverse<scalar_t>(result, infos, upper);
});
return result;
}
Tensor& cholesky_inverse_kernel_impl(Tensor &result, Tensor& infos, bool upper) {
// This function calculates the inverse matrix in-place
// result should be in column major order and contain matrices to invert
// the content of result is overwritten by 'apply_cholesky_inverse'
#ifdef USE_CUSOLVER
if (batchCount(result) == 1 || !use_magma_) {
return cholesky_inverse_kernel_impl_cusolver(result, infos, upper);
} else {
return cholesky_inverse_kernel_impl_magma(result, infos, upper);
}
#else
return cholesky_inverse_kernel_impl_magma(result, infos, upper);
#endif
}
REGISTER_CUDA_DISPATCH(cholesky_inverse_stub, &cholesky_inverse_kernel_impl);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ lu ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
Computes the LU decomposition of a m×n matrix or batch of matrices in 'input' tensor.
This is an in-place routine, content of 'input', 'pivots', and 'infos' is overwritten.
This is a "looped" variant for calling single input MAGMA function on batched input.
Args:
* `input` - [in] the input matrix for LU decomposition
[out] the LU decomposition
* `pivots` - [out] the pivot indices
* `infos` - [out] error codes, positive values indicate singular matrices
* `compute_pivots` - controls whether LU is computed with or without pivoting
For further details, please see the MAGMA documentation for magma_dgetrf_gpu.
*/
template <typename scalar_t>
static void apply_lu_looped_magma(const Tensor& input, const Tensor& pivots, const Tensor& infos, bool compute_pivots) {
#if !AT_MAGMA_ENABLED()
TORCH_CHECK(
false,
"Calling torch.lu on a CUDA tensor requires compiling ",
"PyTorch with MAGMA. lease rebuild with MAGMA.");
#else
// magmaLu and magmaLuNoPiv require infos and pivots tensor to be on CPU
// the data is later copied back to the appropriate output tensor
Tensor infos_cpu = at::empty_like(infos, infos.options().device(kCPU).pinned_memory(true));
auto input_data = input.data_ptr<scalar_t>();
auto infos_data = infos_cpu.data_ptr<magma_int_t>();
auto input_matrix_stride = matrixStride(input);
auto pivots_stride = pivots.size(-1);
auto batch_size = batchCount(input);
magma_int_t m = magma_int_cast(input.size(-2), "m");
magma_int_t n = magma_int_cast(input.size(-1), "n");
auto leading_dimension = std::max<magma_int_t>(1, m);
if (compute_pivots) {
Tensor pivots_cpu = at::empty_like(pivots, pivots.options().device(kCPU).pinned_memory(true));
auto pivots_data = pivots_cpu.data_ptr<magma_int_t>();
for (decltype(batch_size) i = 0; i < batch_size; i++) {
scalar_t* input_working_ptr = &input_data[i * input_matrix_stride];
int* pivots_working_ptr = &pivots_data[i * pivots_stride];
int* infos_working_ptr = &infos_data[i];
magmaLu<scalar_t>(m, n, input_working_ptr, leading_dimension, pivots_working_ptr, infos_working_ptr);
}
pivots.copy_(pivots_cpu, /*non_blocking=*/true);
} else {
for (decltype(batch_size) i = 0; i < batch_size; i++) {
scalar_t* input_working_ptr = &input_data[i * input_matrix_stride];
int* infos_working_ptr = &infos_data[i];
magmaLuNoPiv<scalar_t>(m, n, input_working_ptr, leading_dimension, infos_working_ptr);
}
// fill the pivots tensor with indices using 1-based (Fortran) indexing
auto k = std::min(m, n);
Tensor pivots_tmp = at::arange(1, k + 1, input.options().dtype(at::kInt)).expand_as(pivots);
pivots.copy_(pivots_tmp);
}
infos.copy_(infos_cpu, /*non_blocking=*/true);
#endif
}
/*
Computes the LU decomposition of a m×n matrix or batch of matrices in 'input' tensor.
This is an in-place routine, content of 'input', 'pivots', and 'infos' is overwritten.
This is a specialized batched variant, it is expected to be faster than the "looped" version only for small inputs.
Args:
* `input` - [in] the input matrix for LU decomposition
[out] the LU decomposition
* `pivots` - [out] the pivot indices
* `infos` - [out] error codes, positive values indicate singular matrices
* `compute_pivots` - controls whether LU is computed with or without pivoting
For further details, please see the MAGMA documentation for magma_dgetrf_batched.
*/
template <typename scalar_t>
static void apply_lu_batched_magma(const Tensor& input, const Tensor& pivots, const Tensor& infos, bool compute_pivots) {
#if !AT_MAGMA_ENABLED()
TORCH_CHECK(
false,
"Calling torch.lu on a CUDA tensor requires compiling ",
"PyTorch with MAGMA. lease rebuild with MAGMA.");
#else
auto input_data = input.data_ptr<scalar_t>();
auto infos_data = infos.data_ptr<magma_int_t>();
auto input_matrix_stride = matrixStride(input);
magma_int_t batch_size = magma_int_cast(batchCount(input), "batchCount");
// magmaLuBatched doesn't work with zero batch dimensions
// it gives CUDA error: invalid configuration argument
if (batch_size == 0) {
infos.fill_(0);
return;
}
magma_int_t m = magma_int_cast(input.size(-2), "m");
magma_int_t n = magma_int_cast(input.size(-1), "n");
auto leading_dimension = std::max<magma_int_t>(1, m);
scalar_t** input_array;
ALLOCATE_ARRAY(input_array, scalar_t*, batch_size);
// Set up array of pointers to matrices
for (int64_t i = 0; i < batch_size; i++) {
input_array[i] = &input_data[i * input_matrix_stride];
}
MAGMAQueue magma_queue(input.get_device());
if (compute_pivots) {
auto pivots_data = pivots.data_ptr<magma_int_t>();
auto pivots_stride = pivots.size(-1);
// fill pivots with ones to avoid memory access violations inside magma kernels
// magmaLuBatched might not set the values for it
// see https://github.com/pytorch/pytorch/pull/53064
pivots.fill_(1);
magma_int_t** pivots_array;
ALLOCATE_ARRAY(pivots_array, magma_int_t*, batch_size);
for (int64_t i = 0; i < batch_size; i++) {
pivots_array[i] = &pivots_data[i * pivots_stride];
}
magmaLuBatched<scalar_t>(m, n, input_array, leading_dimension, pivots_array, infos_data, batch_size, magma_queue);
} else {
magmaLuNoPivBatched<scalar_t>(m, n, input_array, leading_dimension, infos_data, batch_size, magma_queue);
// fill the pivots tensor with indices using 1-based (Fortran) indexing
auto k = std::min(m, n);
Tensor pivots_tmp = at::arange(1, k + 1, input.options().dtype(at::kInt)).expand_as(pivots);
pivots.copy_(pivots_tmp);
}
// block CPU until all operations on the queue are finished
// this explicit sync prevents garbage results from the subsequent magmaLuSolveBatched call from a different queue
magma_queue_sync(magma_queue.get_queue());
#endif
}
static void lu_looped_magma(const Tensor& input, const Tensor& pivots, const Tensor& infos, bool compute_pivots) {
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(input.scalar_type(), "lu_magma_looped", [&]{
apply_lu_looped_magma<scalar_t>(input, pivots, infos, compute_pivots);
});
}
static void lu_batched_magma(const Tensor& input, const Tensor& pivots, const Tensor& infos, bool compute_pivots) {
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(input.scalar_type(), "lu_magma_batched", [&]{
apply_lu_batched_magma<scalar_t>(input, pivots, infos, compute_pivots);
});
}
static void apply_lu(const Tensor& input, const Tensor& pivots, const Tensor& infos, bool compute_pivots) {
int64_t batch_size = batchCount(input);
#ifdef USE_CUSOLVER
// Use a heuristic to determine that cusolver is faster than MAGMA for the following sizes.
auto m = input.size(-2);
// exclude complex128 since nan_to_num_ does not work with it.
if ((batch_size == 1 || (batch_size <= 8 && m <= 16) || !use_magma_ ) && !input.is_complex()) {
lu_looped_cusolver(input, pivots, infos, compute_pivots);
}
#else
if (batch_size == 1) {
lu_looped_magma(input, pivots, infos, compute_pivots);
}
#endif // USE_CUSOLVER
else {
lu_batched_magma(input, pivots, infos, compute_pivots);
}
}
REGISTER_CUDA_DISPATCH(lu_stub, &apply_lu);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ triangular_solve ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <typename scalar_t>
static void apply_triangular_solve_batched_magma(Tensor& A, Tensor& b, bool left, bool upper, TransposeType transpose, bool unitriangular) {
#if !AT_MAGMA_ENABLED()
AT_ERROR("triangular_solve: MAGMA library not found in "
"compilation. Please rebuild with MAGMA.");
#else
magma_uplo_t uplo = upper ? MagmaUpper : MagmaLower;
magma_trans_t trans = to_magma(transpose);
magma_diag_t diag = unitriangular ? MagmaUnit : MagmaNonUnit;
magma_side_t side = left ? MagmaLeft : MagmaRight;
auto A_data = A.data_ptr<scalar_t>();
auto b_data = b.data_ptr<scalar_t>();
// This allows to pass rectangular A and b when left = True
magma_int_t m = magma_int_cast(left ? A.size(-1) : b.size(-2), "m");
magma_int_t n = magma_int_cast(b.size(-1), "n");
// magma returns early if m <= 0 || n <= 0 for magmaTriangularSolveBatched
// magmaTriangularSolve is calling cuBLAS and it prints
// ** On entry to DTRSM parameter number 9 had an illegal value
// so let's use proper lda parameter here
magma_int_t lda = std::max<magma_int_t>(1, A.size(-2));
magma_int_t ldb = std::max<magma_int_t>(1, b.size(-2));
magma_int_t batch_size = magma_int_cast(batchCount(A), "batch_size");
auto A_mat_stride = matrixStride(A);
auto b_mat_stride = matrixStride(b);
scalar_t** A_array;
scalar_t** b_array;
ALLOCATE_ARRAY(A_array, scalar_t*, batch_size);
ALLOCATE_ARRAY(b_array, scalar_t*, batch_size);
// Set up the created arrays
for (int64_t i = 0; i < batch_size; i++) {
A_array[i] = &A_data[i * A_mat_stride];
b_array[i] = &b_data[i * b_mat_stride];
}
MAGMAQueue magma_queue(b.get_device());
constexpr int64_t batch_limit = 65535;
// Compute as many batches of 65535 as possible
// The number of "mini"-batches are floor(batch_size / batch_limit)
// and these cover floor(batch_size / batch_limit) * batch_limit matrix solves
int64_t mini_batches = batch_size / batch_limit;
int64_t mini_idx; // this is outside the loop because it is used for the case batch_size % batch_limit != 0
for (mini_idx = 0; mini_idx < mini_batches * batch_limit; mini_idx += batch_limit) {
scalar_t** A_array_cur = &A_array[mini_idx];
scalar_t** b_array_cur = &b_array[mini_idx];
magmaTriangularSolveBatched<scalar_t>(
side, uplo, trans, diag, m, n, A_array_cur,
lda, b_array_cur, ldb, batch_limit, magma_queue);
}
// Compute whatever is left = batch_size - floor(batch_size / batch_limit) * batch_limit
// which concisely is equal to batch_size % batch_limit
if (batch_size % batch_limit != 0) {
magmaTriangularSolveBatched<scalar_t>(
side, uplo, trans, diag, m, n, &A_array[mini_idx],
lda, &b_array[mini_idx], ldb, batch_size % batch_limit, magma_queue);
}
#endif
}
void triangular_solve_batched_magma(Tensor& A, Tensor& B, bool left, bool upper, TransposeType transpose, bool unitriangular) {
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(A.scalar_type(), "triangular_solve_cuda", [&]{
apply_triangular_solve_batched_magma<scalar_t>(A, B, left, upper, transpose, unitriangular);
});
}
void triangular_solve_kernel(Tensor& A, Tensor& B, bool left, bool upper, TransposeType transpose, bool unitriangular) {
// For batches smaller than 8 and matrix sizes larger than 64x64 cuBLAS forloop is faster than batched version
if (batchCount(A) <= 8 && A.size(-1) >= 64) {
triangular_solve_cublas(A, B, left, upper, transpose, unitriangular);
} else {
#if !AT_MAGMA_ENABLED()
triangular_solve_batched_cublas(A, B, left, upper, transpose, unitriangular);
#else
// cuBLAS batched is faster than MAGMA batched up until 512x512, after that MAGMA is faster
if (A.size(-1) <= 512) {
triangular_solve_batched_cublas(A, B, left, upper, transpose, unitriangular);
} else {
triangular_solve_batched_magma(A, B, left, upper, transpose, unitriangular);
}
#endif // AT_MAGMA_ENABLED()
}
}
REGISTER_CUDA_DISPATCH(triangular_solve_stub, &triangular_solve_kernel);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ orgqr ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tensor& orgqr_kernel_impl(Tensor& result, const Tensor& tau) {
// TODO: It is possible to implement efficient batched orgqr for small tau (tau.size(-1) <= 32)
// using MAGMA, however it fails on Windows because of some illegal memory reads inside MAGMA.
// See discussions in https://github.com/pytorch/pytorch/pull/51348 for comparison of cuSOLVER-MAGMA
// and Windows failure.
// For reference here is the MAGMA-based implementation: https://gist.github.com/IvanYashchuk/2db50002c9d3c1462ff769e6410ad983
#if defined(USE_CUSOLVER)
return orgqr_helper_cusolver(result, tau); // cusolver
#else
TORCH_CHECK(false, "Calling torch.orgqr on a CUDA tensor requires compiling ",
"PyTorch with cuSOLVER. Please use PyTorch built with cuSOLVER support.");
#endif
}
REGISTER_CUDA_DISPATCH(orgqr_stub, &orgqr_kernel_impl);
void ormqr_kernel(const Tensor& input, const Tensor& tau, const Tensor& other, bool left, bool transpose) {
#if defined(USE_CUSOLVER)
ormqr_cusolver(input, tau, other, left, transpose);
#else
TORCH_CHECK(false,
"Calling torch.ormqr on a CUDA tensor requires compiling ",
"PyTorch with cuSOLVER. Please use PyTorch built with cuSOLVER support.");
#endif
}
REGISTER_CUDA_DISPATCH(ormqr_stub, &ormqr_kernel);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ qr ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <typename scalar_t>
static void apply_geqrf(const Tensor& input, const Tensor& tau) {
#if !AT_MAGMA_ENABLED()
TORCH_CHECK(
false,
"Calling torch.geqrf on a CUDA tensor requires compiling ",
"PyTorch with MAGMA. Please use PyTorch built with MAGMA support.");
#else
magma_int_t m = magma_int_cast(input.size(-2), "m");
magma_int_t n = magma_int_cast(input.size(-1), "n");
auto input_data = input.data_ptr<scalar_t>();
auto input_matrix_stride = matrixStride(input);
auto tau_stride = tau.size(-1);
auto batch_size = batchCount(input);
auto lda = std::max<int>(1, m);
// magmaGeqrf uses a hybrid CPU-GPU algorithm to compute the elementary reflectors.
// The driver routine geqrf2_gpu accepts a tensor on the CPU for elementary reflectors.
Tensor tau_cpu = at::empty(tau.sizes(), tau.options().device(at::kCPU).pinned_memory(true));
scalar_t* tau_data = tau_cpu.data_ptr<scalar_t>();
scalar_t* work_data = nullptr; // workspace is not needed for geqrf2_gpu
magma_int_t info = 0;
for (int64_t i = 0; i < batch_size; i++) {
scalar_t* input_working_ptr = &input_data[i * input_matrix_stride];
scalar_t* tau_working_ptr = &tau_data[i * tau_stride];
// now compute the actual QR and tau
// MAGMA's geqrf2_gpu function is used, this version has LAPACK-complaint arguments.
magmaGeqrf<scalar_t>(m, n, input_working_ptr, lda, tau_working_ptr, work_data, &info, /*is_v2=*/true);
checkMagmaInternalError(info, "geqrf");
}
tau.copy_(tau_cpu, /*non_blocking=*/true);
#endif
}
// This is a type dispatching helper function for 'apply_geqrf'
void geqrf_magma(const Tensor& input, const Tensor& tau) {
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(input.scalar_type(), "geqrf_magma", [&]{
apply_geqrf<scalar_t>(input, tau);
});
}
// This is a backend library dispatching helper function for calling looped batch implementation
void geqrf_looped(const Tensor& input, const Tensor& tau) {
#if defined(USE_CUSOLVER)
return geqrf_cusolver(input, tau);
#else
return geqrf_magma(input, tau);
#endif
}
// This is a backend library dispatching helper function for calling specialized batched implementation
void geqrf_batched(const Tensor& input, const Tensor& tau) {
#ifdef CUDART_VERSION
// if cuBLAS is available
return geqrf_batched_cublas(input, tau);
#else
// TODO: implement MAGMA-based path using magma_zgeqrf_expert_batched
return geqrf_looped(input, tau);
#endif
}
void geqrf_kernel(const Tensor& input, const Tensor& tau) {
// if number of rows is smaller than 32 batched is always faster for batch size > 1
// for larger number of rows number of batches condition
if (input.size(-2) <= 256 && batchCount(input) >= std::max<int64_t>(2, input.size(-2) / 16)) {
return geqrf_batched(input, tau);
} else {
return geqrf_looped(input, tau);
}
}
REGISTER_CUDA_DISPATCH(geqrf_stub, &geqrf_kernel);
template <typename scalar_t>
static void apply_qr(Tensor& Q, Tensor& R, int64_t q_size_minus_2, int64_t r_size_minus_1, int64_t n_columns,
bool compute_q) {
#if !AT_MAGMA_ENABLED()
AT_ERROR("qr: MAGMA library not found in "
"compilation. Please rebuild with MAGMA.");
#else
magma_int_t m = magma_int_cast(q_size_minus_2, "Q.size(-2)");
magma_int_t n = magma_int_cast(r_size_minus_1, "R.size(-1)");
auto r_data = R.data_ptr<scalar_t>();
auto r_matrix_stride = matrixStride(R);
magma_int_t k = m < n ? m : n;
magma_int_t nb = magmaGeqrfOptimalBlocksize<scalar_t>(m, n);
int64_t batch_size = batchCount(R);
// magmaGeqrf uses a hybrid CPU-GPU algorithm to compute the elementary reflectors.
// The driver routine magma_(d/s)geqrf2_gpu accepts a tensor on the CPU for elementary reflectors.
Tensor tau = at::empty({k}, Q.options().device(at::kCPU));
Tensor work = at::empty({(2 * k + magma_roundup(n, 32)) * nb}, R.options());
scalar_t* tau_data = tau.data_ptr<scalar_t>();
scalar_t* work_data = work.data_ptr<scalar_t>();
// This phase computes R (the raw version)
// This uses MAGMA's ?geqrf2_gpu function
magma_int_t info = 0;
for (int64_t i = 0; i < batch_size; i++) {
scalar_t* r_working_ptr = &r_data[i * r_matrix_stride];
magmaGeqrf<scalar_t>(m, n, r_working_ptr, m, tau_data, work_data, &info, /*is_v2=*/true);
checkMagmaInternalError(info, "geqrf");
}
if (!compute_q) {
// this is for mode='r'
return;
}
// This phase computes Q (the raw version)
// We require to perform ?geqrf_gpu again due to this bug in MAGMA:
// - ?geqrf_gpu allows fast computation of Q via ?orgqr_gpu, but doesn't give R properly.
// - ?geqrf2_gpu gives correct R, but doesn't allow computation of Q via ?orgqr_gpu
// Refer to the below link for more details:
// http://icl.cs.utk.edu/magma/forum/viewtopic.php?f=2&t=1015&p=2800&hilit=geqrf_gpu#p2800
auto q_data = Q.data_ptr<scalar_t>();
auto q_matrix_stride = matrixStride(Q);
for (int64_t i = 0; i < batch_size; i++) {
scalar_t* q_working_ptr = &q_data[i * q_matrix_stride];
magmaGeqrf<scalar_t>(m, n, q_working_ptr, m, tau_data, work_data, &info, /*is_v2=*/false);
checkMagmaInternalError(info, "geqrf");
magmaOrgqr<scalar_t>(m, n_columns, k, q_working_ptr, m, tau_data, work_data, nb, &info);
checkMagmaInternalError(info, "orgqr");
}
#endif
}
std::tuple<Tensor, Tensor> linalg_qr_helper_magma(const Tensor& self, c10::string_view mode) {
bool compute_q, reduced;
std::tie(compute_q, reduced) = _parse_qr_mode(mode);
// Setup input geometry and inputs for apply_qr
std::vector<int64_t> q_sizes, q_strides;
int64_t n_columns_q;
std::tie(q_sizes, q_strides, n_columns_q) = _compute_geometry_for_Q(self, reduced);
Tensor q_working_copy, r_working_copy;
// If there are no elements, then we simply return a pair of tensors of required dimensions
if (self.numel() == 0) {
int64_t n = self.size(-1);
auto r_shape = self.sizes().vec();
r_shape.end()[-2] = n_columns_q;
r_shape.end()[-1] = n;
r_working_copy = at::empty(r_shape, self.options());
if (compute_q) {
auto q_shape = q_sizes;
q_shape.end()[-1] = n_columns_q;
q_working_copy = at::zeros(q_shape, self.options());
q_working_copy.diagonal(/*offset=*/0, /*dim1=*/-2, /*dim2=*/-1).fill_(1);
} else {
q_working_copy = at::empty({0}, self.options());
}
return std::make_tuple(q_working_copy, r_working_copy);
}
if (compute_q) {
q_working_copy = at::empty_strided(q_sizes, q_strides, self.options());
q_working_copy.narrow(-1, 0, self.size(-1)).copy_(self);
} else {
q_working_copy = at::empty({0}, self.options());
}
r_working_copy = cloneBatchedColumnMajor(self);
int64_t m = q_sizes[self.dim() - 2];
int64_t n = r_working_copy.size(-1);
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(self.scalar_type(), "qr_cuda", [&]{
apply_qr<scalar_t>(q_working_copy, r_working_copy, m, n, n_columns_q, compute_q);
});
if (compute_q) {
q_working_copy = q_working_copy.narrow(-1, 0, n_columns_q);
}
r_working_copy = r_working_copy.narrow(-2, 0, n_columns_q).triu();
return std::make_tuple(q_working_copy, r_working_copy);
}
std::tuple<Tensor, Tensor> _linalg_qr_helper_cuda(const Tensor& input, c10::string_view mode) {
#if defined(USE_CUSOLVER)
// _linalg_qr_helper_default is a generic function that is implemented using
// geqrf_stub and orgqr_stub. It dispatches to cuSOLVER for CUDA inputs if USE_CUSOLVER is defined
return _linalg_qr_helper_default(input, mode);
#else
return linalg_qr_helper_magma(input, mode);
#endif
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ symeig ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <typename scalar_t>
static void apply_magma_eigh(const Tensor& values, const Tensor& vectors, const Tensor& infos, bool upper, bool compute_eigenvectors) {
#if !AT_MAGMA_ENABLED()
TORCH_CHECK(
false,
"Calling torch.linalg.eigh/eigvalsh on a CUDA tensor requires compiling ",
"PyTorch with MAGMA. Please use PyTorch built with MAGMA support.");
#else
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(values.device() == kCPU);
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(infos.device() == kCPU);
using value_t = typename c10::scalar_value_type<scalar_t>::type;
magma_uplo_t uplo = upper ? MagmaUpper : MagmaLower;
magma_vec_t jobz = compute_eigenvectors ? MagmaVec : MagmaNoVec;
magma_int_t n = magma_int_cast(vectors.size(-1), "n");
auto lda = std::max<magma_int_t>(1, n);
auto batch_size = batchCount(vectors);
auto vectors_stride = matrixStride(vectors);
auto values_stride = values.size(-1);
auto vectors_data = vectors.data_ptr<scalar_t>();
auto values_data = values.data_ptr<value_t>();
auto infos_data = infos.data_ptr<magma_int_t>();
scalar_t* wA;
ALLOCATE_ARRAY(wA, scalar_t, lda * lda);
// Run once, first to get the optimum work sizes.
// Since we deal with batches of matrices with the same dimensions, doing this outside
// the loop saves (batch_size - 1) workspace queries which would provide the same result
// and (batch_size - 1) calls to allocate and deallocate workspace using at::empty()
magma_int_t lwork = -1;
scalar_t wkopt;
magma_int_t liwork = -1;
magma_int_t iwkopt;
magma_int_t lrwork = -1;
value_t rwkopt;
magmaSyevd<scalar_t, value_t>(jobz, uplo, n, vectors_data, lda, values_data,
wA, lda, &wkopt, lwork, &rwkopt, lrwork, &iwkopt, liwork, infos_data);
scalar_t* work;
magma_int_t* iwork;
lwork = magma_int_cast(std::max<int64_t>(1, real_impl<scalar_t, value_t>(wkopt)), "work_size");
liwork = magma_int_cast(std::max<int64_t>(1, iwkopt), "iwork_size");
ALLOCATE_ARRAY(work, scalar_t, lwork);
ALLOCATE_ARRAY(iwork, magma_int_t, liwork);
value_t* rwork = nullptr;
c10::Storage storage_rwork;
if (vectors.is_complex()) {
lrwork = magma_int_cast(std::max<int64_t>(1, rwkopt), "rwork_size");
storage_rwork = pin_memory<value_t>(lrwork);
rwork = static_cast<value_t*>(storage_rwork.data());
}
for (decltype(batch_size) i = 0; i < batch_size; i++) {
scalar_t* vectors_working_ptr = &vectors_data[i * vectors_stride];
value_t* values_working_ptr = &values_data[i * values_stride];
magma_int_t* info_working_ptr = &infos_data[i];
magmaSyevd<scalar_t, value_t>(jobz, uplo, n, vectors_working_ptr, lda, values_working_ptr,
wA, lda, work, lwork, rwork, lrwork, iwork, liwork, info_working_ptr);
// The current behaviour for Linear Algebra functions to raise an error if something goes wrong
// or input doesn't satisfy some requirement
// therefore return early since further computations will be wasted anyway
if (*info_working_ptr != 0) {
return;
}
}
#endif
}
std::tuple<Tensor, Tensor> _symeig_helper_cuda(const Tensor& self, bool eigenvectors, bool upper) {
Tensor infos = at::zeros({std::max<int64_t>(1, batchCount(self))}, self.options().dtype(kInt).device(at::kCPU));
auto eigvals_shape = IntArrayRef(self.sizes().data(), self.dim()-1); // self.shape[:-1]
ScalarType real_dtype = toValueType(self.scalar_type());
// magmaSyevd uses a hybrid CPU-GPU algorithm to compute the eigenvalues and eigenvectors.
// The driver routine magma_(d/s)syev_gpu accepts a tensor on the CPU for eigvalenvalues.
// The data is later moved to the appropriate device.
// In the case where self.numel() == 0, we just return an empty tensor of
// dimensions on the CUDA (to avoid the unnecessary "to(at::kCUDA)")
auto eigvals_working_copy = self.numel() == 0
? at::empty(eigvals_shape, self.options().dtype(real_dtype))
: at::empty(eigvals_shape, self.options().dtype(real_dtype).device(at::kCPU));
if (self.numel() == 0) {
return std::tuple<Tensor, Tensor>(eigvals_working_copy, at::empty_like(self, LEGACY_CONTIGUOUS_MEMORY_FORMAT));
}
auto self_working_copy = cloneBatchedColumnMajor(self);
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(self.scalar_type(), "symeig_cuda", [&]{
apply_magma_eigh<scalar_t>(eigvals_working_copy, self_working_copy, infos, upper, eigenvectors);
});
if (self.dim() > 2) {
batchCheckErrors(infos, "symeig_cuda");
} else {
singleCheckErrors(infos.item().toInt(), "symeig_cuda");
}
if (eigenvectors) {
return std::tuple<Tensor, Tensor>(eigvals_working_copy.to(self.device()), self_working_copy);
} else {
return std::tuple<Tensor, Tensor>(eigvals_working_copy.to(self.device()), at::empty({0}, self.options()));
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ linalg_eigh ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// This is a type dispatch function for 'apply_magma_eigh'
// For small inputs result is computed on CPU
void linalg_eigh_magma(const Tensor& eigenvalues, const Tensor& eigenvectors, const Tensor& infos, bool upper, bool compute_eigenvectors) {
// MAGMA just calls LAPACK for eigenvectors.size(-1) <= 128
// See https://bitbucket.org/icl/magma/src/e6fdca447bd402693e8b0b950a898b6879bbcc41/src/zheevd_gpu.cpp?at=master#lines-258
// in addition lda is ignored breaking 0x0 inputs
if (eigenvectors.size(-1) > 128) {
// MAGMA requires eigenvalues and infos tensors to reside on CPU
Tensor eigenvalues_cpu = eigenvalues.to(kCPU);
Tensor infos_cpu = infos.to(kCPU);
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(
eigenvectors.scalar_type(), "linalg_eigh_magma", [&] {
apply_magma_eigh<scalar_t>(
eigenvalues_cpu, eigenvectors, infos_cpu, upper, compute_eigenvectors);
});
// Transfer computed by MAGMA results from CPU to GPU
eigenvalues.copy_(eigenvalues_cpu);
infos.copy_(infos_cpu);
} else { // eigenvectors.size(-1) <= 128
// transfer to CPU, compute the result and copy back to GPU
// this is faster than going through MAGMA that does the same
Tensor eigenvalues_cpu = at::empty_like(eigenvalues, eigenvalues.options().device(kCPU));
if (compute_eigenvectors) {
Tensor eigenvectors_cpu = at::empty_like(eigenvectors, eigenvectors.options().device(kCPU));
at::linalg_eigh_out(eigenvalues_cpu, eigenvectors_cpu, eigenvectors.to(kCPU), upper ? "U" : "L");
eigenvectors.copy_(eigenvectors_cpu);
} else {
at::linalg_eigvalsh_out(eigenvalues_cpu, eigenvectors.to(kCPU), upper ? "U" : "L");
}
eigenvalues.copy_(eigenvalues_cpu);
}
}
void linalg_eigh_kernel(const Tensor& eigenvalues, const Tensor& eigenvectors, const Tensor& infos, bool upper, bool compute_eigenvectors) {
#if defined(USE_CUSOLVER)
linalg_eigh_cusolver(eigenvalues, eigenvectors, infos, upper, compute_eigenvectors);
#else
linalg_eigh_magma(eigenvalues, eigenvectors, infos, upper, compute_eigenvectors);
#endif
}
REGISTER_CUDA_DISPATCH(linalg_eigh_stub, &linalg_eigh_kernel);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ eig ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// magmaEig uses a hybrid CPU-GPU algorithm, which takes and return CPU
// memory. So, we accept a GPU tensor, copy it to CPU memory, and later copy
// the returned values from CPU to GPU. See also magmaSymeig, which uses a
// similar approach.
template <typename scalar_t>
static void apply_eig(const Tensor& self, bool eigenvectors, Tensor& out_eigvals, Tensor& out_eigvecs,
int64_t *info_ptr) {
#if !AT_MAGMA_ENABLED()
TORCH_CHECK(false, "Calling torch.eig on a CUDA tensor requires compiling PyTorch with MAGMA. "
"Either transfer the tensor to the CPU before calling torch.eig or recompile with MAGMA.");
#else
TORCH_INTERNAL_ASSERT(self.device() == at::kCPU, "Internal error: apply_eig needs a CPU tensor");
using value_t = typename c10::scalar_value_type<scalar_t>::type;
magma_vec_t jobvr = eigenvectors ? MagmaVec : MagmaNoVec;
magma_int_t n = magma_int_cast(self.size(-1), "n");
auto self_data = self.data_ptr<scalar_t>();
auto out_eigvals_data = out_eigvals.data_ptr<scalar_t>();
scalar_t *wr = out_eigvals_data;
scalar_t *vr_data = NULL;
magma_int_t ldvr = 1;
if (jobvr == MagmaVec)
{
vr_data = out_eigvecs.data_ptr<scalar_t>();
ldvr = n;
}
value_t *rwork_data = nullptr;
if (isComplexType(at::typeMetaToScalarType(self.dtype()))) {
ALLOCATE_ARRAY(rwork_data, value_t, n*2);
}
if (n > 0) {
// call magmaEig once to get the optimal size of work_data
scalar_t wkopt;
magma_int_t info;
magmaEig<scalar_t, value_t>(MagmaNoVec, jobvr, n, self_data, n, wr, NULL, 1, vr_data, ldvr, &wkopt, -1, rwork_data, &info);
magma_int_t lwork = static_cast<magma_int_t>(real_impl<scalar_t, value_t>(wkopt));
// call it a 2nd time to to the actual work
scalar_t *work_data = nullptr;
ALLOCATE_ARRAY(work_data, scalar_t, lwork);
magmaEig<scalar_t, value_t>(MagmaNoVec, jobvr, n, self_data, n, wr, NULL, 1, vr_data, ldvr, work_data, lwork, rwork_data, &info);
*info_ptr = info;
}
#endif
}
/*
* Internal helper; like eig_cuda but:
* 1. assume that self is a square matrix of side "n"
* 2. return CPU tensors (because this is what magmaEig returns), which will be copied to GPU memory
* by the caller
*/
std::tuple<Tensor, Tensor> eig_kernel_impl(const Tensor& self, bool& eigenvectors) {
int64_t n = self.size(-1);
// copy self to pinned CPU memory
auto self_working_copy = at::empty_strided(
{n, n}, // square matrix
{1, n}, // column-ordered, as magmaEig expects
at::TensorOptions(at::kCPU).dtype(self.dtype()).pinned_memory(true));
self_working_copy.copy_(self);
// tensors holding the results. We use empty_strided to make them column-ordered
auto options = self.options().device(at::kCPU).memory_format(LEGACY_CONTIGUOUS_MEMORY_FORMAT);
Tensor out_eigvals;
if (isComplexType(at::typeMetaToScalarType(self.dtype()))) {
out_eigvals = at::empty({n}, options);
} else {
out_eigvals = at::empty_strided({n, 2}, {1, n}, options);
}
auto out_eigvecs = eigenvectors
? at::empty_strided({n, n}, {1, n}, options)
: Tensor();
int64_t info;
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(self.scalar_type(), "eig_cuda", [&]{
apply_eig<scalar_t>(self_working_copy, eigenvectors, out_eigvals, out_eigvecs, &info);
});
singleCheckErrors(info, "eig_cuda");
return std::tuple<Tensor, Tensor>(out_eigvals, out_eigvecs);
}
REGISTER_CUDA_DISPATCH(eig_stub, &eig_kernel_impl);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ linalg_eig ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
Computes the eigenvalues and eigenvectors of n-by-n matrix 'input'.
This is an in-place routine, content of 'input', 'values', 'vectors' is overwritten.
'infos' is an int Tensor containing error codes for each matrix in the batched input.
For more information see MAGMA's documentation for GEEV routine.
*/
template <typename scalar_t>
void apply_linalg_eig(Tensor& values, Tensor& vectors, Tensor& input, Tensor& infos, bool compute_eigenvectors) {
#if !AT_MAGMA_ENABLED()
TORCH_CHECK(false, "Calling torch.linalg.eig on a CUDA tensor requires compiling PyTorch with MAGMA. "
"Either transfer the tensor to the CPU before calling torch.linalg.eig or recompile with MAGMA.");
#else
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.device() == at::kCPU);
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(values.device() == at::kCPU);
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(infos.device() == at::kCPU);
if (compute_eigenvectors) {
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(vectors.device() == at::kCPU);
}
using value_t = typename c10::scalar_value_type<scalar_t>::type;
magma_vec_t jobvr = compute_eigenvectors ? MagmaVec : MagmaNoVec;
magma_vec_t jobvl = MagmaNoVec; // only right eigenvectors are computed
magma_int_t n = magma_int_cast(input.size(-1), "n");
auto lda = std::max<magma_int_t>(1, n);
auto batch_size = batchCount(input);
auto input_matrix_stride = matrixStride(input);
auto values_stride = values.size(-1);
auto input_data = input.data_ptr<scalar_t>();
auto values_data = values.data_ptr<scalar_t>();
auto infos_data = infos.data_ptr<magma_int_t>();
auto rvectors_data = compute_eigenvectors ? vectors.data_ptr<scalar_t>() : nullptr;
scalar_t* lvectors_data = nullptr; // only right eigenvectors are computed
int64_t ldvr = compute_eigenvectors ? lda : 1;
int64_t ldvl = 1;
Tensor rwork;
value_t* rwork_data = nullptr;
if (input.is_complex()) {
ScalarType real_dtype = toValueType(input.scalar_type());
rwork = at::empty({lda * 2}, input.options().dtype(real_dtype));
rwork_data = rwork.data_ptr<value_t>();
}
// call magmaEig once to get the optimal size of work_data
scalar_t work_query;
magmaEig<scalar_t, value_t>(jobvl, jobvr, n, input_data, lda, values_data,
lvectors_data, ldvl, rvectors_data, ldvr, &work_query, -1, rwork_data, &infos_data[0]);
magma_int_t lwork = std::max<magma_int_t>(1, static_cast<magma_int_t>(real_impl<scalar_t, value_t>(work_query)));
Tensor work = at::empty({lwork}, input.dtype());
auto work_data = work.data_ptr<scalar_t>();
for (auto i = decltype(batch_size){0}; i < batch_size; i++) {
scalar_t* input_working_ptr = &input_data[i * input_matrix_stride];
scalar_t* values_working_ptr = &values_data[i * values_stride];
scalar_t* rvectors_working_ptr = compute_eigenvectors ? &rvectors_data[i * input_matrix_stride] : nullptr;
int* info_working_ptr = &infos_data[i];
magmaEig<scalar_t, value_t>(jobvl, jobvr, n, input_working_ptr, lda, values_working_ptr,
lvectors_data, ldvl, rvectors_working_ptr, ldvr, work_data, lwork, rwork_data, info_working_ptr);
}
#endif
}
// This is a type dispatching helper function for 'apply_linalg_eig'
void linalg_eig_kernel(Tensor& eigenvalues, Tensor& eigenvectors, Tensor& infos, const Tensor& input, bool compute_eigenvectors) {
// This function calculates the non-symmetric eigendecomposition in-place
// tensors should be in batched column major memory format
// the content of eigenvalues, eigenvectors and infos is overwritten by 'apply_linalg_eig'
// apply_linalg_eig modifies the provided input matrix in-place, therefore we need a copy
// MAGMA doesn't have GPU interface for the eigendecomposition and it forces us to transfer 'input' to CPU
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.is_cuda());
Tensor input_working_copy = at::empty(input.sizes(), input.options().device(kCPU));
input_working_copy.transpose_(-2, -1); // make input_working_copy to have Fortran contiguous memory layout
input_working_copy.copy_(input);
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(input.scalar_type(), "linalg_eig_out_cuda", [&]{
apply_linalg_eig<scalar_t>(eigenvalues, eigenvectors, input_working_copy, infos, compute_eigenvectors);
});
}
REGISTER_CUDA_DISPATCH(linalg_eig_stub, &linalg_eig_kernel);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ svd ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template<typename scalar_t>
static void apply_svd(Tensor& self, Tensor& U, Tensor& S, Tensor& VT,
char jobchar, std::vector<int64_t>& infos) {
#if !AT_MAGMA_ENABLED()
AT_ERROR("svd: MAGMA library not found in "
"compilation. Please rebuild with MAGMA.");
#else
using value_t = typename c10::scalar_value_type<scalar_t>::type;
auto self_data = self.data_ptr<scalar_t>();
auto U_data = U.data_ptr<scalar_t>();
auto S_data = S.data_ptr<value_t>();
auto VT_data = VT.data_ptr<scalar_t>();
auto self_stride = matrixStride(self);
auto U_stride = jobchar == 'N' ? 1 : matrixStride(U);
auto S_stride = S.size(-1);
auto VT_stride = jobchar == 'N' ? 1 :matrixStride(VT);
auto batchsize = batchCount(self);
magma_vec_t jobz = jobchar == 'A' ? MagmaAllVec : (jobchar == 'S' ? MagmaSomeVec : MagmaNoVec);
magma_int_t m = magma_int_cast(self.size(-2), "m");
magma_int_t n = magma_int_cast(self.size(-1), "n");
auto lda = std::max<magma_int_t>(1, m);
auto ldvt = std::max<magma_int_t>(1, jobchar == 'N' ? 1 : VT.size(-2));
auto mn = std::min(m, n);
c10::Storage storage_rwork;
value_t* rwork = nullptr;
magma_int_t* iwork;
ALLOCATE_ARRAY(iwork, magma_int_t, 8 * mn);
if (isComplexType(at::typeMetaToScalarType(self.dtype()))) {
auto lrwork = computeLRWorkDim(jobchar, m, n);
storage_rwork = pin_memory<value_t>(lrwork);
rwork = static_cast<value_t*>(storage_rwork.data());
}
magma_int_t info = 0;
// Run once, first to get the optimum work size.
// Since we deal with batches of matrices with the same dimensions, doing this outside
// the loop saves (batch_size - 1) workspace queries which would provide the same result
// and (batch_size - 1) calls to allocate and deallocate workspace using at::empty()
magma_int_t lwork = -1;
scalar_t wkopt = 1; // MAGMA might not set the value for the optimal workspace therefore use 1 as the default value
magmaSvd<scalar_t, value_t>(jobz, m, n, self_data, lda, S_data, U_data, lda, VT_data, ldvt, &wkopt, lwork, rwork, iwork, &info);
lwork = magma_int_cast(real_impl<scalar_t, value_t>(wkopt), "work_size");
scalar_t* work;
ALLOCATE_ARRAY(work, scalar_t, lwork);
for (int64_t i = 0; i < batchsize; i++) {
scalar_t* self_working_ptr = &self_data[i * self_stride];
value_t* S_working_ptr = &S_data[i * S_stride];
scalar_t* U_working_ptr = &U_data[i * U_stride];
scalar_t* VT_working_ptr = &VT_data[i * VT_stride];
// Compute S, U (optionally), VT (optionally)
magmaSvd<scalar_t, value_t>(jobz, m, n, self_working_ptr, lda,
S_working_ptr, U_working_ptr, lda, VT_working_ptr, ldvt, work, lwork, rwork, iwork, &info);
infos[i] = info;
if (info != 0) {
return;
}
}
#endif
}
std::tuple<Tensor, Tensor, Tensor> _svd_helper_cuda_legacy(const Tensor& self, bool some, bool compute_uv) {
std::vector<int64_t> infos(batchCount(self), 0);
int64_t m = self.size(-2);
char jobchar = compute_uv ? (some ? 'S' : 'A') : 'N';
Tensor U_working_copy, S_working_copy, VT_working_copy;
std::tie(U_working_copy, S_working_copy, VT_working_copy) = _create_U_S_VT(self, some, compute_uv);
// The input matrix, U, S and VT have to reside in pinned memory.
// Additionally, the input and U have to be in column major format.
// _create_U_S_VT takes care of a part of these requirements (for U, S and VT)
// For the input matrix, this requirements are being taken care of below.
// Specify strides
auto self_col_major_strides = at::detail::defaultStrides(self.sizes());
self_col_major_strides[self.dim() - 2] = 1;
self_col_major_strides[self.dim() - 1] = m;
// Create strided tensor in pinned memory
auto self_working_copy = at::empty_strided(self.sizes(), self_col_major_strides,
at::TensorOptions(at::kCPU).dtype(self.dtype()).pinned_memory(true));
self_working_copy.copy_(self);
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(self.scalar_type(), "svd_cuda", [&] {
apply_svd<scalar_t>(self_working_copy, U_working_copy, S_working_copy, VT_working_copy, jobchar, infos);
});
if (self.dim() > 2) {
batchCheckErrors(infos, "svd_cuda");
} else {
singleCheckErrors(infos[0], "svd_cuda");
}
U_working_copy = same_stride_to(U_working_copy, self.options());
S_working_copy = same_stride_to(S_working_copy, S_working_copy.options().device(self.device()));
VT_working_copy = same_stride_to(VT_working_copy, self.options());
// so far we have computed VT, but torch.svd returns V instead. Adjust accordingly.
// Note that the 'apply_svd' routine returns VT = V^T (for real inputs) or VT = V^H (for complex inputs), not V.
if (compute_uv) {
VT_working_copy = VT_working_copy.conj();
VT_working_copy.transpose_(-2, -1);
}
return std::make_tuple(U_working_copy, S_working_copy, VT_working_copy);
}
std::tuple<Tensor, Tensor, Tensor> _svd_helper_cuda(const Tensor& self, bool some, bool compute_uv) {
#ifdef USE_CUSOLVER
return _svd_helper_cuda_lib(self, some, compute_uv);
#else
return _svd_helper_cuda_legacy(self, some, compute_uv);
#endif
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ lu_solve ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
Solves the matrix equation A X = B
X and B are n-by-nrhs matrices, A is represented using the LU factorization.
This is an in-place routine, content of `b` is overwritten.
This is a "looped" variant for calling single input MAGMA function on batched input.
Args:
* `b` - [in] the right hand side matrix B
[out] the solution matrix X
* `lu` - [in] the LU factorization of matrix A (see at::_lu_with_info)
* `pivots` - [in] the pivot indices (see at::_lu_with_info)
For further details, please see the MAGMA documentation for magma_dgetrs_gpu.
*/
template <typename scalar_t>
static void apply_lu_solve_looped_magma(const Tensor& b, const Tensor& lu, const Tensor& pivots, TransposeType transpose) {
#if !AT_MAGMA_ENABLED()
TORCH_CHECK(
false,
"Calling torch.lu_solve on a CUDA tensor requires compiling ",
"PyTorch with MAGMA. lease rebuild with MAGMA.");
#else
auto trans = to_magma(transpose);
auto b_data = b.data_ptr<scalar_t>();
auto lu_data = lu.data_ptr<scalar_t>();
// MAGMA requires pivots to be a CPU tensor
Tensor pivots_cpu = pivots.cpu();
auto pivots_data = pivots_cpu.data_ptr<magma_int_t>();
auto b_stride = matrixStride(b);
auto lu_stride = matrixStride(lu);
auto pivots_stride = pivots_cpu.size(-1);
auto batch_size = batchCount(b);
magma_int_t n = magma_int_cast(lu.size(-2), "n");
magma_int_t nrhs = magma_int_cast(b.size(-1), "nrhs");
auto leading_dimension = std::max<magma_int_t>(1, n);
int info = 0;
for (decltype(batch_size) i = 0; i < batch_size; i++) {
scalar_t* b_working_ptr = &b_data[i * b_stride];
scalar_t* lu_working_ptr = &lu_data[i * lu_stride];
int* pivots_working_ptr = &pivots_data[i * pivots_stride];
magmaLuSolve<scalar_t>(n, nrhs, lu_working_ptr, leading_dimension, pivots_working_ptr, b_working_ptr, leading_dimension, &info, trans);
// info from magmaLuSolve only reports if the i-th parameter is wrong
// so we don't need to check it all the time
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(info == 0);
}
#endif
}
/*
Solves the matrix equation A X = B
X and B are n-by-nrhs matrices, A is represented using the LU factorization.
This is an in-place routine, content of `b` is overwritten.
This is a specialized batched variant, it is expected to be faster than the "looped" version only for small inputs.
Args:
* `b` - [in] the right hand side matrix B
[out] the solution matrix X
* `lu` - [in] the LU factorization of matrix A (see at::_lu_with_info)
* `pivots` - [in] the pivot indices (see at::_lu_with_info)
For further details, please see the MAGMA documentation for magma_dgetrs_batched.
*/
template <typename scalar_t>
static void apply_lu_solve_batched_magma(const Tensor& b, const Tensor& lu, const Tensor& pivots, TransposeType transpose) {
#if !AT_MAGMA_ENABLED()
TORCH_CHECK(
false,
"Calling torch.lu_solve on a CUDA tensor requires compiling ",
"PyTorch with MAGMA. lease rebuild with MAGMA.");
#else
auto trans = to_magma(transpose);
auto b_data = b.data_ptr<scalar_t>();
auto lu_data = lu.data_ptr<scalar_t>();
magma_int_t n = magma_int_cast(lu.size(-2), "n");
magma_int_t nrhs = magma_int_cast(b.size(-1), "nrhs");
auto leading_dimension = std::max<magma_int_t>(1, n);
auto pivots_data = pivots.data_ptr<magma_int_t>();
auto b_stride = matrixStride(b);
auto lu_stride = matrixStride(lu);
auto pivots_stride = pivots.size(-1);
magma_int_t batch_size = magma_int_cast(batchCount(b), "batchCount");
magma_int_t** pivots_array;
scalar_t** lu_array;
scalar_t** b_array;
ALLOCATE_ARRAY(pivots_array, magma_int_t*, batch_size);
ALLOCATE_ARRAY(lu_array, scalar_t*, batch_size);
ALLOCATE_ARRAY(b_array, scalar_t*, batch_size);
for (int64_t i = 0; i < batch_size; i++) {
pivots_array[i] = &pivots_data[i * pivots_stride];
b_array[i] = &b_data[i * b_stride];
lu_array[i] = &lu_data[i * lu_stride];
}
MAGMAQueue magma_queue(b.get_device());
// Compute the result in batches of 65535
// that is the maximum allowed number for batch_size in MAGMA
constexpr int64_t batch_limit = 65535;
for (int64_t mini_idx = 0; mini_idx < batch_size; mini_idx += batch_limit) {
int64_t nbatches = std::min(batch_limit, batch_size - mini_idx);
scalar_t** lu_array_cur = &lu_array[mini_idx];
scalar_t** b_array_cur = &b_array[mini_idx];
magma_int_t** pivots_array_cur = &pivots_array[mini_idx];
int info;
magmaLuSolveBatched<scalar_t>(
n, nrhs, lu_array_cur, leading_dimension,
pivots_array_cur, b_array_cur, leading_dimension,
info, nbatches, magma_queue, trans);
// info from magmaLuSolveBatched only reports if the i-th parameter is wrong
// so we don't need to check it all the time
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(info == 0);
}
#endif
}
static void lu_solve_batched_magma(const Tensor& b, const Tensor& lu, const Tensor& pivots, TransposeType trans) {
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(b.scalar_type(), "lu_solve_batched_magma", [&]{
apply_lu_solve_batched_magma<scalar_t>(b, lu, pivots, trans);
});
}
static void lu_solve_looped_magma(const Tensor& b, const Tensor& lu, const Tensor& pivots, TransposeType trans) {
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(b.scalar_type(), "lu_solve_looped_magma", [&]{
apply_lu_solve_looped_magma<scalar_t>(b, lu, pivots, trans);
});
}
static void lu_solve_trans_dispatch(const Tensor& b, const Tensor& lu, const Tensor& pivots, TransposeType trans) {
auto batch_size = batchCount(lu);
auto m = lu.size(-2);
auto b2 = b.size(-1);
bool over_magma_dim_limit = b2 > 1024; // magma implementation of LU solve cannot handle a b tensor with last dim > 1024 (https://bitbucket.org/icl/magma/issues/19/dgesv_batched-dgetrs_batched-fails-for)
// heuristics determined from tests dicussed in https://github.com/pytorch/pytorch/pull/59148
#ifdef USE_CUSOLVER
if ((batch_size == 1 && m > 512) || (batch_size <= 8 && over_magma_dim_limit)) {
lu_solve_looped_cusolver(b, lu, pivots, trans);
}
#else
if (batch_size == 1) {
lu_solve_looped_magma(b, lu, pivots, trans);
}
#endif // ifdef USE_CUSOLVER
#ifdef CUDART_VERSION
else if ((batch_size > 2 && m <= 128) || (batch_size > 8 && over_magma_dim_limit)) {
lu_solve_batched_cublas(b, lu, pivots, trans);
}
#endif // ifdef CUDART_VERSION
else {
lu_solve_batched_magma(b, lu, pivots, trans);
}
}
REGISTER_CUDA_DISPATCH(lu_solve_trans_stub, &lu_solve_trans_dispatch);
static void lu_solve_dispatch(const Tensor& b, const Tensor& lu, const Tensor& pivots) {
lu_solve_trans_dispatch(b, lu, pivots, TransposeType::NoTranspose);
}
REGISTER_CUDA_DISPATCH(lu_solve_stub, &lu_solve_dispatch);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ lstsq ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <typename scalar_t>
static void apply_gels(const Tensor& a, Tensor& b, Tensor& infos) {
#if !AT_MAGMA_ENABLED()
TORCH_CHECK(false, "torch.linalg.lstsq: MAGMA library not found in "
"compilation. Please rebuild with MAGMA.");
#else
auto trans = MagmaNoTrans;
auto m = magma_int_cast(a.size(-2), "m");
auto n = magma_int_cast(a.size(-1), "n");
TORCH_CHECK(
m >= n,
"torch.linalg.lstsq: only overdetermined systems (input.size(-2) >= input.size(-1)) are allowed on CUDA");
auto nrhs = magma_int_cast(b.size(-1), "nrhs");
auto ldda = std::max<magma_int_t>(1, m);
auto lddb = std::max<magma_int_t>(1, std::max(m, n));
auto nb = magmaGeqrfOptimalBlocksize<scalar_t>(m, n);
auto lwork = (m - n + nb) * (nrhs + nb) + nrhs * nb;
Tensor hwork = at::empty({static_cast<int64_t>(lwork)}, a.scalar_type());
auto* hwork_ptr = hwork.data_ptr<scalar_t>();
// MAGMA requires infos tensor to live on CPU
infos = infos.to(at::kCPU);
auto infos_data = infos.data_ptr<magma_int_t>();
batch_iterator_with_broadcasting<scalar_t>(a, b,
[&](scalar_t* a_working_ptr, scalar_t* b_working_ptr,
int64_t a_linear_batch_idx) {
magma_int_t* infos_working_ptr = &infos_data[a_linear_batch_idx];
magmaGels<scalar_t>(trans, m, n, nrhs,
a_working_ptr, ldda, b_working_ptr, lddb,
hwork_ptr, lwork, infos_working_ptr);
}
);
#endif
}
void gels_magma(const Tensor& a, Tensor& b, Tensor& infos) {
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(a.scalar_type(), "gels_magma", [&] {
apply_gels<scalar_t>(a, b, infos);
});
}
void linalg_lstsq_gels(const Tensor& A, const Tensor& B, const Tensor& /*infos*/) {
// The steps for using the QR decomposition for solving least squares problems
// are outlined here https://en.wikipedia.org/wiki/QR_decomposition#Using_for_solution_to_linear_inverse_problems
auto m = A.size(-2);
auto n = A.size(-1);
auto mn = std::min(m, n);
// explicitly broadcast the batch dimensions of A
// TODO: revisit this later to use batch_iterator_with_broadcasting in triangular_solve
IntArrayRef A_batch_sizes(A.sizes().data(), A.dim() - 2);
IntArrayRef B_batch_sizes(B.sizes().data(), B.dim() - 2);
std::vector<int64_t> expand_batch_portion = at::infer_size(A_batch_sizes, B_batch_sizes);
auto tau_shape = A.sizes().vec();
tau_shape.pop_back();
tau_shape.back() = mn;
Tensor tau = at::empty(tau_shape, A.options());
if (m >= n) {
// Step 1: compute QR factorization using geqrf
geqrf_kernel(A, tau);
// explicitly broadcast the batch dimensions of A
// we do it after geqrf so that we don't do redundant computations for the same input
auto A_expand_batch = expand_batch_portion;
A_expand_batch.insert(A_expand_batch.end(), {A.size(-2), A.size(-1)});
Tensor A_expanded = A.expand({A_expand_batch});
bool is_fortran_contiguous = A_expanded.mT().is_contiguous();
Tensor A_broadcasted = is_fortran_contiguous ? A_expanded : cloneBatchedColumnMajor(A_expanded);
auto tau_expand_batch = expand_batch_portion;
tau_expand_batch.push_back(tau.size(-1));
Tensor tau_broadcasted = tau.expand({tau_expand_batch}).contiguous();
// Step 2: B <- Q^H B
ormqr_kernel(A_broadcasted, tau_broadcasted, B, /*left=*/true, /*transpose=*/true);
// Step 3: solve R X = B
triangular_solve_kernel(
const_cast<Tensor&>(A_broadcasted),
const_cast<Tensor&>(B),
/*left=*/true,
/*upper=*/true,
/*transpose=*/TransposeType::NoTranspose,
/*unitriangular=*/false);
} else { // underdetermined case
Tensor Ah = cloneBatchedColumnMajor(A.mH());
// Step 1: compute QR factorization of conjugate transpose of A using geqrf
geqrf_kernel(Ah, tau);
// explicitly broadcast the batch dimensions of A
// we do it after geqrf so that we don't do redundant computations for the same input
auto A_expand_batch = expand_batch_portion;
A_expand_batch.insert(A_expand_batch.end(), {Ah.size(-2), Ah.size(-1)});
Tensor Ah_expanded = Ah.expand({A_expand_batch});
bool is_fortran_contiguous = Ah_expanded.mT().is_contiguous();
Tensor Ah_broadcasted = is_fortran_contiguous ? Ah_expanded : cloneBatchedColumnMajor(Ah_expanded);
// Step 2: R^H Z = B
const auto trans = Ah_broadcasted.is_complex() ? TransposeType::ConjTranspose
: TransposeType::Transpose;
triangular_solve_kernel(
const_cast<Tensor&>(Ah_broadcasted),
const_cast<Tensor&>(B),
/*left=*/true,
/*upper=*/true,
/*transpose=*/trans,
/*unitriangular=*/false);
// B matrix has the size max(m, n) x nrhs
// triangular_solve_kernel writes its output into the first m rows of B leaving the rest untouched
// we need to set the rest of the rows to zero so that the multiplication from step 3 is correct
B.narrow(-2, m, n - m).zero_();
auto tau_expand_batch = expand_batch_portion;
tau_expand_batch.push_back(tau.size(-1));
Tensor tau_broadcasted = tau.expand({tau_expand_batch}).contiguous();
// Step 3: X <- Q Z
ormqr_kernel(Ah_broadcasted, tau_broadcasted, B, /*left=*/true, /*transpose=*/false);
}
}
void gels_looped(const Tensor& a, Tensor& b, Tensor& infos) {
#if defined(USE_CUSOLVER)
// linalg_lstsq_gels is a generic function that is implemented using
// geqrf_stub, ormqr_stub, and triangular_solve_stub
// It dispatches to cuSOLVER for CUDA inputs if USE_CUSOLVER is defined
return linalg_lstsq_gels(a, b, infos);
#else
return gels_magma(a, b, infos);
#endif
}
void lstsq_kernel(const Tensor& a, Tensor& b, Tensor& /*rank*/, Tensor& /*singular_values*/, Tensor& infos, double /*rcond*/, std::string /*driver_name*/) {
auto m = a.size(-2);
auto n = a.size(-1);
// first handle the underdetermined case (m < n)
// this case is not supported by MAGMA or cuBLAS
if (m < n) {
#if defined(USE_CUSOLVER)
linalg_lstsq_gels(a, b, infos);
#else
TORCH_CHECK(
false,
"torch.linalg.lstsq: only overdetermined systems (input.size(-2) >= input.size(-1)) are allowed on CUDA. ",
"Please rebuild with cuSOLVER.");
#endif
} else { // m >= n
#if !AT_MAGMA_ENABLED()
// MAGMA is not available we can either use cuBLAS or cuSOLVER here
// the batched vs looped dispatch is implemented based on the following performance results
// https://github.com/pytorch/pytorch/pull/54725#issuecomment-832234456
if (m <= 256 && batchCount(b) >= std::max<int64_t>(2, m / 16)) {
// if CUDART_VERSION is defined then cuBLAS is available
#ifdef CUDART_VERSION
gels_batched_cublas(a, b, infos);
#else
// this would either call cuSOLVER or MAGMA,
// if MAGMA is called a runtime error is thrown about not finding MAGMA in compilation
gels_looped(a, b, infos);
#endif // CUDART_VERSION
} else {
gels_looped(a, b, infos);
}
#else
// if both MAGMA and cuSOLVER are available this would call cuSOLVER
// MAGMA is called if cuSOLVER is not available
gels_looped(a, b, infos);
#endif // AT_MAGMA_ENABLED()
}
}
REGISTER_CUDA_DISPATCH(lstsq_stub, &lstsq_kernel);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ legacy_lstsq ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
std::tuple<Tensor, Tensor> legacy_lstsq_cuda(const Tensor &B, const Tensor &A) {
TORCH_WARN_ONCE(
"torch.lstsq is deprecated in favor of torch.linalg.lstsq and will be removed in a future PyTorch release.\n",
"torch.linalg.lstsq has reversed arguments and does not return the QR decomposition in "
"the returned tuple (although it returns other information about the problem).\n",
"To get the qr decomposition consider using torch.linalg.qr.\n",
"The returned solution in torch.lstsq stored the residuals of the solution in the ",
"last m - n columns of the returned value whenever m > n. In torch.linalg.lstsq, the ",
"residuals in the field 'residuals' of the returned named tuple.\n",
"The unpacking of the solution, as in\n",
"X, _ = torch.lstsq(B, A).solution[:A.size(1)]\n",
"should be replaced with\n",
"X = torch.linalg.lstsq(A, B).solution"
);
#if !AT_MAGMA_ENABLED()
TORCH_CHECK(false, "solve: MAGMA library not found in "
"compilation. Please rebuild with MAGMA.");
#else
const auto dtype = A.scalar_type();
TORCH_CHECK(B.scalar_type() == dtype, "exepected A and B dtypes to match but found ",
dtype, " and ", B.scalar_type());
TORCH_CHECK(A.numel() > 0 && A.dim() == 2, "A should be (non-empty) 2 dimensional");
TORCH_CHECK(B.numel() > 0 && B.dim() == 2, "B should be (non-empty) 2 dimensional");
auto a_sizes = A.sizes();
auto b_sizes = B.sizes();
TORCH_CHECK(a_sizes[0] == b_sizes[0], "Expected A and b to have same size "
"at dim 0, but A has ", a_sizes[0], " rows and B has ", b_sizes[0], " rows");
TORCH_CHECK(a_sizes[0] >= a_sizes[1], "Expected A with shape (m x n) to have "
"m >= n. The case for m < n is not implemented yet.");
Tensor A_working = cloneBatchedColumnMajor(A);
Tensor B_working = cloneBatchedColumnMajor(B);
int64_t m = a_sizes[0];
int64_t n = a_sizes[1];
int64_t nrhs = b_sizes[1];
int info;
AT_DISPATCH_FLOATING_TYPES(A.scalar_type(), "legacy_lstsq_cuda", [&] {
scalar_t *a_data = A_working.data_ptr<scalar_t>();
scalar_t *b_data = B_working.data_ptr<scalar_t>();
scalar_t wkopt;
magmaGels(MagmaNoTrans, m, n, nrhs, a_data, m, b_data, m, &wkopt, -1, &info);
const auto hwork_size = static_cast<magma_int_t>(wkopt);
scalar_t *hwork = nullptr;
ALLOCATE_ARRAY(hwork, scalar_t, hwork_size);
magmaGels(MagmaNoTrans, m, n, nrhs, a_data, m, b_data, m, hwork, hwork_size, &info);
});
TORCH_CHECK(info == 0, "MAGMA gels : Argument %d : illegal value", -info);
return std::tuple<Tensor, Tensor>(B_working, A_working);
#endif // AT_MAGMA_ENABLED()
}
std::tuple<Tensor&, Tensor&> legacy_lstsq_out_cuda(
const Tensor& B, const Tensor& A, Tensor& B_out, Tensor& A_out) {
const auto dtype = A.scalar_type();
TORCH_CHECK(B.scalar_type() == dtype, "exepected A and B dtypes to match but found ",
A.scalar_type(), " and ", B.scalar_type());
TORCH_CHECK(A_out.scalar_type() == dtype, "A_out to have scalar type ", dtype,
" but found", A_out.scalar_type());
TORCH_CHECK(B_out.scalar_type() == dtype, "A_out to have scalar type ", dtype,
" but found", B_out.scalar_type());
Tensor A_tmp, B_tmp;
std::tie(B_tmp, A_tmp) = native::legacy_lstsq_cuda(B, A);
resize_output(A_out, A_tmp.sizes());
A_out.copy_(A_tmp);
resize_output(B_out, B_tmp.sizes());
B_out.copy_(B_tmp);
return std::tuple<Tensor&, Tensor&>(B_out, A_out);
}
}} // namespace at::native
#undef ALLOCATE_ARRAY
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
25405e1b8e78b80e52c1f48e70c83990df9944bb | 4c25432a6d82aaebd82fd48e927317b15a6bf6ab | /data/dataset_2017/dataset_2017_8_formatted_macrosremoved/chocimir/3264486_5633382285312000_chocimir.cpp | 783d035e199847ea4cf6da8a1170817269e5f5c8 | [] | no_license | wzj1988tv/code-imitator | dca9fb7c2e7559007e5dbadbbc0d0f2deeb52933 | 07a461d43e5c440931b6519c8a3f62e771da2fc2 | refs/heads/master | 2020-12-09T05:33:21.473300 | 2020-01-09T15:29:24 | 2020-01-09T15:29:24 | 231,937,335 | 1 | 0 | null | 2020-01-05T15:28:38 | 2020-01-05T15:28:37 | null | UTF-8 | C++ | false | false | 1,204 | cpp | #include <algorithm>
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
typedef long long LL;
typedef long double LD;
int cond = 1;
LL solve() {
LL n, tmp;
cin >> tmp;
vector<int> d;
n = tmp;
if (n < 10) {
return n;
}
while (n > 0) {
d.push_back(n % 10);
n /= 10;
}
int l = d.size();
int prev = 0;
int i = l - 1;
for (; i >= 0; --i) {
if (d[i] >= prev) {
prev = d[i];
} else {
break;
}
}
if (i < 0) {
return tmp;
}
for (int j = i + 1; j < l; ++j) {
if (d[j] > 0) {
d[j]--;
}
if (j < l - 1 && d[j + 1] <= d[j]) {
break;
}
if (j < l - 1) {
i++;
}
}
for (int j = 0; j <= i; ++j) {
d[j] = 9;
}
long long r = 0;
for (int i = l - 1; i >= 0; --i) {
r *= 10;
r += d[i];
}
return r;
}
int main() {
int t;
cin >> t;
for (int x = 1; x <= t; ++x) {
cout << "Case #" << x << ": " << solve() << endl; // result
}
return 0;
}
| [
"e.quiring@tu-bs.de"
] | e.quiring@tu-bs.de |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.