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
9b438cc78d958dc6b58b37b39bd3e4bea448fb31
a5cf450078809a0b507e21d56660b7c4f033c6d5
/include/cim/tcim_Equipment.h
e8fe32aa59c18c7498bd4f876b3078b5c94dd43b
[]
no_license
fay1987/communication_manager
98a72677d4e2aa631e2c895741819a53c639c79a
7df29883f6a18400ceb26682cf2d800630b6df33
refs/heads/master
2021-07-13T14:30:04.214616
2018-01-25T08:08:05
2018-01-25T08:08:05
94,993,715
1
2
null
null
null
null
WINDOWS-1252
C++
false
false
824
h
/*********************************************************************** * Module: tcim_Equipment.h * Author: think * Modified: 2016Äê11ÔÂ28ÈÕ 12:07:48 * Purpose: Declaration of the class tcim_Equipment ***********************************************************************/ #if !defined(__CR8000_tcim_Equipment_h) #define __CR8000_tcim_Equipment_h #include <tcim_IdentifiedObject.h> class tcim_Equipment : public tcim_IdentifiedObject { public: short aggregat(void); short normallyinservice(void); std::string stationcode(void); std::string groupcode(void); std::string paratabname(void); int no(void); short f_aggregat; short f_normallyinservice; std::string f_stationcode; std::string f_groupcode; std::string f_paratabname; int f_no; protected: private: }; #endif
[ "lingquan324@163.com" ]
lingquan324@163.com
ac419d70abfe092cdcdc903dc2ba440fd32620b2
b137ebd2b936574cc52182fac651992bc84aa08c
/src/icp.cpp
a0d866bf362948a0f3425b33cb0444c81336c15f
[]
no_license
lct-cell/icp_localization
3bf1dabb37a3b25f68801fa306ee79198cf06b4e
214562400eb6cb3e94bd5254eddb93e5dd83fc84
refs/heads/main
2023-01-18T22:53:53.581224
2020-11-28T13:35:08
2020-11-28T13:35:08
316,712,552
0
0
null
null
null
null
UTF-8
C++
false
false
7,492
cpp
#include <iostream> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl/registration/icp.h> #include <pcl/conversions.h> #include <pcl/filters/voxel_grid.h> #include <pcl_conversions/pcl_conversions.h>// #include "ros/ros.h" #include "sensor_msgs/PointCloud2.h" #include <pcl_ros/transforms.h> #include "geometry_msgs/PoseStamped.h" #include <Eigen/Dense> #include <tf/transform_listener.h> #include <nav_msgs/Odometry.h> #include <fstream> /* geometry_msgs::PoseStamped gps; void gpsCallback(geometry_msgs::PoseStamped poseStamped) { std::cout << "in callback\n"; gps = poseStamped; std::cerr << "GPS from topic: " << gps << "\n"; }*/ /* std::ofstream myfile; myfile.open("submit_1.csv"); myfile << "id,x,y,z,yaw,pitch,roll\n"; */ pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_map (new pcl::PointCloud<pcl::PointXYZ>); pcl::PCLPointCloud2::Ptr lidar_points_PCL(new pcl::PCLPointCloud2()); pcl::PCLPointCloud2::Ptr lidar_cloud_filtered(new pcl::PCLPointCloud2()); pcl::PCLPointCloud2::Ptr lidar_Final_PCLpc2(new pcl::PCLPointCloud2()); pcl::VoxelGrid<pcl::PCLPointCloud2> sor_; tf::StampedTransform transform_base_velodyne; Eigen::Matrix4d initial_guess; int init = 1; ros::Publisher result_lidar_pub; ros::Publisher result_localization_pub; int id = 1; /* const int SIZE = 400; double x[SIZE]; double y[SIZE]; double z[SIZE]; double yaw[SIZE]; double pitch[SIZE]; double roll[SIZE]; */ void icpCallback(const sensor_msgs::PointCloud2::ConstPtr &lidar_points) { if(init) { initial_guess << -0.7689708, -0.6391353, 0.0137796, -284.8985597, 0.6382825, -0.7687940, -0.0393861, 226.1278839, 0.0357667, -0.0214914, 0.9991291, -12.5875616, 0, 0, 0, 1; //best init = 0; } pcl_conversions::toPCL(*lidar_points, *lidar_points_PCL); std::cerr << "Lidar pointCloud before filtering: " << lidar_points_PCL->width * lidar_points_PCL->height << " data points " << std::endl; //downsample sor_.setInputCloud(lidar_points_PCL); sor_.setLeafSize(0.5f, 0.5f, 0.5f);//0.5*0.5*0.5 sor_.filter(*lidar_cloud_filtered); std::cerr << "Lidar pointCloud after filtering: " << lidar_cloud_filtered->width * lidar_cloud_filtered->height << " data points " << std::endl; //transform from "velodyne" frame to "base_link" frame pcl::PointCloud<pcl::PointXYZ>::Ptr lidar_points_point_cloud(new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZ>::Ptr lidar_points_point_cloud_tf(new pcl::PointCloud<pcl::PointXYZ>); pcl::fromPCLPointCloud2(*lidar_cloud_filtered, *lidar_points_point_cloud); pcl_ros::transformPointCloud(*lidar_points_point_cloud, *lidar_points_point_cloud_tf, transform_base_velodyne); //icp pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp; icp.setInputSource(lidar_points_point_cloud_tf); icp.setInputTarget(cloud_map); icp.setMaxCorrespondenceDistance (1);//1 icp.setMaximumIterations (500); //500 icp.setTransformationEpsilon (1e-10);//1e-10 icp.setEuclideanFitnessEpsilon (1e-8);//1e-8 pcl::PointCloud<pcl::PointXYZ> Final; //ROS_WARN_STREAM_NAMED("test", "initial_guess is " << std::endl // << initial_guess); icp.align(Final, initial_guess.cast<float>()); ROS_INFO_STREAM_NAMED("RESULT", "has converged:" << icp.hasConverged() << " score: " << icp.getFitnessScore() << std::endl); ROS_INFO_STREAM_NAMED("RESULT", "\n" << icp.getFinalTransformation() << std::endl); initial_guess = icp.getFinalTransformation().cast<double>(); //pcl::pointcloud => pcl::pointcloud2 => sensor_msgs::pointcloud2 sensor_msgs::PointCloud2 lidar_scan_final_pc2; pcl::toPCLPointCloud2(Final, *lidar_Final_PCLpc2); pcl_conversions::fromPCL(*lidar_Final_PCLpc2, lidar_scan_final_pc2); lidar_scan_final_pc2.header.frame_id = "world"; result_lidar_pub.publish(lidar_scan_final_pc2); nav_msgs::Odometry odom; odom.header.frame_id = "world"; odom.child_frame_id = "base_link"; //transform matrix to translation and quaternion //initial_guess is our final transform matrix now Eigen::Quaterniond eigen_quat(initial_guess.block<3,3>(0,0).cast<double>()); Eigen::Vector3d eigen_trans(initial_guess.block<3,1>(0,3).cast<double>()); odom.pose.pose.position.x = eigen_trans(0); odom.pose.pose.position.y = eigen_trans(1); odom.pose.pose.position.z = eigen_trans(2); odom.pose.pose.orientation.x = eigen_quat.x(); odom.pose.pose.orientation.y = eigen_quat.y(); odom.pose.pose.orientation.z = eigen_quat.z(); odom.pose.pose.orientation.w = eigen_quat.w(); result_localization_pub.publish(odom); /* Eigen::Matrix3d m_rot = initial_guess.block<3,3>(0,0).cast<double>(); Eigen::Vector3d ea = m_rot.eulerAngles(2, 1, 0); x[id] = initial_guess(0,3); y[id] = initial_guess(1,3); z[id] = initial_guess(2,3); yaw[id] = ea(0); pitch[id] = ea(1); roll[id] = ea(2); */ //store data in csv /* if(id == 201) //201 { std::ofstream myfile; myfile.open("test_1.csv"); myfile << "id,x,y,z,yaw,pitch,roll\n"; for(int i=1; i<=id; i++) { myfile << i << "," << std::setprecision(15) << x[i] << "," << y[i] << "," << z[i] << "," << yaw[i] << "," << pitch[i] << "," << roll[i] << "\n"; } myfile.close(); std::cout << "stored data in csv\n"; } */ //std::cout << std::setprecision(15) << x[id] << " " << y[id] << std::endl; std::cout<< id << std::endl; id +=1; } int main (int argc, char** argv) { //set tranformation between base_link and velodyne transform_base_velodyne.setOrigin( tf::Vector3(0.46, 0.0, 3.46) ); transform_base_velodyne.setRotation( tf::Quaternion(-0.0051505, 0.018102, -0.019207, 0.99964) ); //pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_in (new pcl::PointCloud<pcl::PointXYZ>(5,1)); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_lidar (new pcl::PointCloud<pcl::PointXYZ>); pcl::PCLPointCloud2::Ptr cloud(new pcl::PCLPointCloud2()); pcl::PCLPointCloud2::Ptr cloud_filtered(new pcl::PCLPointCloud2()); // get map pointcloud from pcd file and filter the pointcloud pcl::PCDReader reader; // Replace the path below with the path where you saved your file reader.read("/home/lct/nctu_sdc/localization_ws/src/localization_309512009/map/itri_map.pcd", *cloud); std::cerr << "Map pointCloud before filtering: " << cloud->width * cloud->height << " data points " << std::endl; // Create the filtering object // change leaf size if need pcl::VoxelGrid<pcl::PCLPointCloud2> sor; sor.setInputCloud(cloud); sor.setLeafSize(0.5f, 0.5f, 0.5f);//0.5*0.5*0.5 sor.filter(*cloud_filtered); std::cerr << "Map pointCloud after filtering: " << cloud_filtered->width * cloud_filtered->height << " data points " << std::endl; pcl::fromPCLPointCloud2(*cloud_filtered, *cloud_map);//from PCLpointcloud2 to pointcloud std::cout << "Saved " << cloud_map->size () << " data points to cloud_map:" << std::endl; //--- //for (auto& point : *cloud_in) // std::cout << point << std::endl; //*cloud_out = *cloud_in; //init gps in world frame (change to subscriber later) //double gps_x, gps_y, gps_z; //gps_x = -263.89384941; //gps_y = -67.7809286182; //gps_z = -8.08355457512; /* std::ofstream myfile; myfile.open("submit_1.csv"); myfile << "id,x,y,z,yaw,pitch,roll\n"; myfile.close(); */ ros::init (argc, argv, "icp_node"); ros::NodeHandle nh; ros::Subscriber sub = nh.subscribe("lidar_points", 1000, icpCallback); result_lidar_pub = nh.advertise<sensor_msgs::PointCloud2>("result_lidar", 1000); result_localization_pub = nh.advertise<nav_msgs::Odometry>("result_localization", 1000); ros::spin(); return 0; }
[ "as1super123@gmail.com" ]
as1super123@gmail.com
7b6efb06867727d25841c01094be597a75279470
c057e033602e465adfa3d84d80331a3a21cef609
/C/testcases/CWE126_Buffer_Overread/s02/CWE126_Buffer_Overread__malloc_char_memcpy_82_bad.cpp
dba8a0d482ae9f08e42ca4abcb3d003a32772ec0
[]
no_license
Anzsley/My_Juliet_Test_Suite_v1.3_for_C_Cpp
12c2796ae7e580d89e4e7b8274dddf920361c41c
f278f1464588ffb763b7d06e2650fda01702148f
refs/heads/main
2023-04-11T08:29:22.597042
2021-04-09T11:53:16
2021-04-09T11:53:16
356,251,613
1
0
null
null
null
null
UTF-8
C++
false
false
1,159
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE126_Buffer_Overread__malloc_char_memcpy_82_bad.cpp Label Definition File: CWE126_Buffer_Overread__malloc.label.xml Template File: sources-sink-82_bad.tmpl.cpp */ /* * @description * CWE: 126 Buffer Over-read * BadSource: Use a small buffer * GoodSource: Use a large buffer * Sinks: memcpy * BadSink : Copy data to string using memcpy * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE126_Buffer_Overread__malloc_char_memcpy_82.h" namespace CWE126_Buffer_Overread__malloc_char_memcpy_82 { void CWE126_Buffer_Overread__malloc_char_memcpy_82_bad::action(char * data) { { char dest[100]; memset(dest, 'C', 100-1); dest[100-1] = '\0'; /* null terminate */ /* POTENTIAL FLAW: using memcpy with the length of the dest where data * could be smaller than dest causing buffer overread */ memcpy(dest, data, strlen(dest)*sizeof(char)); dest[100-1] = '\0'; printLine(dest); free(data); } } } #endif /* OMITBAD */
[ "65642214+Anzsley@users.noreply.github.com" ]
65642214+Anzsley@users.noreply.github.com
a30d5065a13db6416e665b1ce43f8eb70897e31f
986b7841f72eb24616be8d5fc7defcc3a308db94
/src/graphics/os-window-x11.cc
2de422e3bc553d9824ecff42b3d1d70a355826ec
[ "MIT" ]
permissive
zeroeffects/TempestRenderer
e783065fecdb1a5ffbe7945044453c6a8fb7e7b4
698e974dbeee89e3ca1258e2601b85e9cbfbfc8b
refs/heads/master
2021-01-23T22:15:31.970201
2016-12-05T19:14:48
2016-12-05T19:14:48
25,295,700
7
0
null
null
null
null
UTF-8
C++
false
false
1,572
cc
/* The MIT License * * Tempest Engine * Copyright (c) 2016 Zdravko Velinov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "tempest/graphics/os-window.hh" namespace Tempest { struct Texture; Texture* CaptureScreenshot(bool cursor) { TGE_ASSERT(false, "Stub"); return nullptr; } Texture* CaptureScreenshot(OSWindow wnd, bool cursor) { TGE_ASSERT(false, "Stub"); return nullptr; } void GenerateEvent(const WindowSystemEvent& evt) { } void GetMousePosition(int32_t* x, int32_t* y) { } }
[ "z.velinov@vkv5.com" ]
z.velinov@vkv5.com
61a86a77f5b9244ecff5c0bf151ad227ffda5fb0
3b9b4049a8e7d38b49e07bb752780b2f1d792851
/src/webos/webapp_window.h
edfdd6097a817267af603b71fcdd91a2f2cca15c
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
webosce/chromium53
f8e745e91363586aee9620c609aacf15b3261540
9171447efcf0bb393d41d1dc877c7c13c46d8e38
refs/heads/webosce
2020-03-26T23:08:14.416858
2018-08-23T08:35:17
2018-09-20T14:25:18
145,513,343
0
2
Apache-2.0
2019-08-21T22:44:55
2018-08-21T05:52:31
null
UTF-8
C++
false
false
5,411
h
// Copyright (c) 2016-2018 LG Electronics, Inc. // // 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. // // SPDX-License-Identifier: Apache-2.0 #ifndef WEBOS_WEBAPP_WINDOW_H_ #define WEBOS_WEBAPP_WINDOW_H_ #include <map> #include "base/timer/timer.h" #include "ui/events/event_handler.h" #include "ui/events/keycodes/dom/dom_code.h" #include "ui/display/display_observer.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/native_widget_types.h" #include "webos/common/webos_constants.h" #include "webos/common/webos_event.h" #include "webos/common/webos_native_event_delegate.h" namespace content { class WebContents; } namespace views { class DesktopWindowTreeHost; } namespace ui { class WindowGroupConfiguration; } namespace gfx { class Rect; } class WebAppWindowDelegate; class WebOSView; namespace webos { class WebOSBrowserContext; class WebAppWindow : public WebOSNativeEventDelegate, public display::DisplayObserver, public ui::EventHandler { public: WebAppWindow(const gfx::Rect& rect); virtual ~WebAppWindow(); void Show(); void Hide(); gfx::NativeWindow GetNativeWindow(); int DisplayWidth(); int DisplayHeight(); void AttachWebContents(content::WebContents* web_contents); void DetachWebContents(); void SetDelegate(WebAppWindowDelegate* webapp_window_delegate); bool Event(WebOSEvent* webos_event); void SetWebOSView(WebOSView* webos_view) { webos_view_ = webos_view; } void SetHost(views::DesktopWindowTreeHost* host); views::DesktopWindowTreeHost* host() { return host_; } NativeWindowState GetWindowHostState() const { return window_host_state_; } NativeWindowState GetWindowHostStateAboutToChange() const { return window_host_state_about_to_change_; } void SetWindowHostState(NativeWindowState state); void SetKeyMask(WebOSKeyMask key_mask, bool value); void SetWindowProperty(const std::string& name, const std::string& value); void SetOpacity(float opacity); void Resize(int width, int height); void SetUseVirtualKeyboard(bool enable); void SetAllowWindowResize(bool allow) { allow_window_resize_ = allow; } void CreateGroup(const ui::WindowGroupConfiguration& config); void AttachToGroup(const std::string& group, const std::string& layer); void FocusGroupOwner(); void FocusGroupLayer(); void DetachGroup(); // Overridden from WebOSNativeEventDelegate: void CompositorBuffersSwapped() override; void CursorVisibilityChange(bool visible) override; void InputPanelHidden() override; void InputPanelShown() override; void InputPanelRectChanged() override; bool IsEnableResize() override { return allow_window_resize_; } void KeyboardEnter() override; void KeyboardLeave() override; void WindowHostClose() override; void WindowHostExposed() override; void WindowHostStateChanged(ui::WidgetState new_state) override; void WindowHostStateAboutToChange(ui::WidgetState state) override; // Overridden from display::DisplayObserver: void OnDisplayAdded(const display::Display& new_display) override; void OnDisplayRemoved(const display::Display& old_display) override; void OnDisplayMetricsChanged(const display::Display& display, uint32_t metrics) override; // Overridden from ui::EventHandler: void OnMouseEvent(ui::MouseEvent* event) override; void OnKeyEvent(ui::KeyEvent* event) override; // For VKB viewport shift void UpdateViewportY(); void CheckKeyFilter(ui::KeyEvent* event); void CheckKeyFilterTable(unsigned keycode, unsigned& new_keycode, ui::DomCode& code, unsigned& modifier); private: void Restore(); void ComputeScaleFactor(); // Handle mouse events. bool OnMousePressed(float x, float y, int flags); bool OnMouseReleased(float x, float y, int flags); bool OnMouseMoved(float x, float y); bool OnMouseWheel(float x, float y, int x_offset, int y_offset); bool OnMouseEntered(float x, float y); bool OnMouseExited(float x, float y); // Handle key events bool OnKeyPressed(unsigned keycode); bool OnKeyReleased(unsigned keycode); WebAppWindowDelegate* webapp_window_delegate_; WebOSView* webos_view_; NativeWindowState window_host_state_; NativeWindowState window_host_state_about_to_change_; views::DesktopWindowTreeHost* host_; // For Restore. WebOSBrowserContext* browser_context_; content::WebContents* web_contents_; std::map<std::string, std::string> window_property_list_; std::map<WebOSKeyMask, bool> key_mask_list_; float opacity_; gfx::Rect rect_; bool keyboard_enter_; float scale_factor_; // For VKB viewport shift base::OneShotTimer viewport_timer_; int viewport_shift_height_; bool input_panel_visible_; bool cursor_visible_; bool allow_window_resize_; int current_rotation_; DISALLOW_COPY_AND_ASSIGN(WebAppWindow); }; } // namespace webos #endif // WEBOS_WEBAPP_WINDOW_H_
[ "changhyeok.bae@lge.com" ]
changhyeok.bae@lge.com
556a1c6acd83b6735d25e057d5a3313c5afef748
cc1d23080f81e514d382184f774934774f86c4b4
/src/drivers/pg/statement.cc
b06dbee7868ecb84be5ca0c901677eb8a1769e30
[ "CC-BY-4.0", "CC-BY-3.0" ]
permissive
kavikumarN/dbicpp
be4d37d7d76088a692d04057e931f161ab6bb36b
d105e978bc20acdb2f936c1413d0586913b50613
refs/heads/master
2020-04-25T04:08:46.961327
2012-09-27T07:01:01
2012-09-27T07:01:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,636
cc
#include "common.h" namespace dbi { void PgStatement::init() { _uuid = generateCompactUUID(); _result = 0; _last_insert_id = 0; } void PgStatement::prepare() { PGresult *result = 0; string normalized_sql = _sql; PQ_PREPROCESS_QUERY(normalized_sql); result = PQprepare(*_conn, _uuid.c_str(), normalized_sql.c_str(), 0, 0); if (!result) boom("Unable to allocate statement"); PQ_CHECK_RESULT(&result, *_conn, _sql); PQclear(result); } PgStatement::~PgStatement() { cleanup(); } PgStatement::PgStatement(string normalized_sql, PGconn **conn) { _sql = normalized_sql; _conn = conn; init(); prepare(); } void PgStatement::cleanup() { char command[1024]; if (_result) { PQclear(_result); _result = 0; } if (_uuid.length() == 32 && PQstatus(*_conn) != CONNECTION_BAD) { snprintf(command, 1024, "deallocate \"%s\"", _uuid.c_str()); PQclear(PQexec(*_conn, command)); } } void PgStatement::finish() { if (_result) { PQclear(_result); _result = 0; } _last_insert_id = 0; } string PgStatement::command() { return _sql; } PGresult* PgStatement::_pgexec() { PGresult *result; finish(); result = PQexecPrepared(*_conn, _uuid.c_str(), 0, 0, 0, 0, 0); PQ_CHECK_RESULT(&result, *_conn, _sql); return _result = result; } PGresult* PgStatement::_pgexec(param_list_t &bind) { int *param_l, *param_f; const char **param_v; PGresult *result; if (bind.size() == 0) return _pgexec(); finish(); PQ_PROCESS_BIND(&param_v, &param_l, &param_f, bind); try { result = PQexecPrepared(*_conn, _uuid.c_str(), bind.size(), (const char* const *)param_v, (const int*)param_l, (const int*)param_f, 0); PQ_CHECK_RESULT(&result, *_conn, _sql); } catch (ConnectionError &e) { delete []param_v; delete []param_l; delete []param_f; throw e; } catch (Error &e) { delete []param_v; delete []param_l; delete []param_f; throw e; } delete []param_v; delete []param_l; delete []param_f; return _result = result; } uint32_t PgStatement::execute() { uint32_t rows; PGresult *result = _pgexec(); rows = (uint32_t)PQntuples(result); _last_insert_id = rows > 0 ? PQgetisnull(result, 0, 0) ? 0 : atol(PQgetvalue(result, 0, 0)) : 0; return rows > 0 ? rows : (uint32_t)atoi(PQcmdTuples(result)); } uint32_t PgStatement::execute(param_list_t &bind) { uint32_t rows; PGresult *result = _pgexec(bind); rows = (uint32_t)PQntuples(result); _last_insert_id = rows > 0 ? PQgetisnull(result, 0, 0) ? 0 : atol(PQgetvalue(result, 0, 0)) : 0; return rows > 0 ? rows : (uint32_t)atoi(PQcmdTuples(result)); } PgResult* PgStatement::result() { PgResult *instance = new PgResult(_result, _sql, *_conn); _result = 0; return instance; } void PgStatement::boom(const char* m) { if (PQstatus(*_conn) == CONNECTION_BAD) throw ConnectionError(m); else throw RuntimeError(m); } uint64_t PgStatement::lastInsertID() { return _last_insert_id; } }
[ "deepfryed@gmail.com" ]
deepfryed@gmail.com
db8a68edaba1b2847ec8473f38a68bf6c8ec82a8
67007416a0a884cdc7edcad0d2f5cf77bca11998
/table.cpp
4ab97a979ecf29d0301f77caebe56f82e22a6475
[]
no_license
XifanTan/C-_homework
241e5e420d5e21f339aa150f076bb9c465e62362
ce45950bcec575f4c4f13c3b04da7cf6429cdb38
refs/heads/master
2020-05-02T11:05:53.538606
2019-06-19T03:17:26
2019-06-19T03:17:26
177,917,574
0
0
null
null
null
null
UTF-8
C++
false
false
753
cpp
#include<iostream> using namespace std; class Word{ private: char *word; public: Word(){ } Word(char *mesg){ } Word(int mesg){ } show(){ printf("%s",word); } }; class Table{ private: int row = 1,col = 1; Word *w[100][100]; public: Table(){ } Table(int a,int b){ } addRow(){ } addColumn(){ } set(int i,int j,int word){ } set(int i,int j,char word[]){ } delRow(int j){ } delColumn(int i){ } show(){ } }; int main() { Table tb; tb.show(); tb.addRow(); tb.show(); tb.addColumn(); tb.show(); Table tb1(5,5); tb1.show(); tb1.set(1,1,30); tb1.set(2,2,"hello"); tb1.show(); tb1.delRow(1); tb1.show(); tb1.delColumn(1); tb1.show(); return 0; }
[ "2603388295@qq.com" ]
2603388295@qq.com
02a20e99016a1eba3f75c7a36404fe7fdc7bbaac
f8d5a636bd2adafc3b63f8113ededc1fb03b80ea
/source/math/matrix3.hpp
1064b018aa90fe372b4fc9a51b81506bddef10c1
[]
no_license
MAPSWorks/earthInfo
f6468bed82dbee66e8841c500cf317a9d74591c0
5b8c8317ff2636053f5c78d63c3164048e0c5f76
refs/heads/master
2020-07-10T17:44:34.215908
2018-05-24T08:41:58
2018-05-24T08:41:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,733
hpp
#pragma once #include "../lib/glm/mat3.hpp" #include "../lib/glm/op/common.hpp" #include "../lib/glm/op/mat.hpp" #include "forward.hpp" #include "vector3.hpp" #include <iostream> namespace ss { namespace math { struct Matrix3 { glm::mat3 m; Matrix3() = default; // identity explicit Matrix3(float x) : m{x} {} explicit Matrix3(Vector3 a) : Matrix3{a[0], a[1], a[2]} {} explicit Matrix3(Vector3 x, Vector3 y, Vector3 z) : m{x.v, y.v, z.v} {} explicit Matrix3(float a, float b, float c) : m{ glm::vec3{a, 0.0f, 0.0f}, glm::vec3{0.0f, b, 0.0f}, glm::vec3{0.0f, 0.0f, c}, } {} explicit Matrix3(glm::mat3 x) : m{x} {} [[deprecated]] Matrix3(float (&xs)[9]) : m{glm::make_mat3(xs)} {} [[deprecated]] Matrix3(float xs[]) : m{glm::make_mat3(xs)} {} void swap(Matrix3 & a) { std::swap(m, a.m); } auto& operator [] (int i) const { return m[i]; } auto& operator [] (int i) { return m[i]; } auto ptr() const { return &m[0][0]; } auto ptr() { return &m[0][0]; } auto operator + () const { return Matrix3{+m}; } auto operator - () const { return Matrix3{-m}; } auto& operator += (Matrix3 const& a) { m += a.m; return *this; } auto& operator -= (Matrix3 const& a) { m -= a.m; return *this; } auto& operator *= (Matrix3 const& a) { m *= a.m; return *this; } auto& operator /= (Matrix3 const& a) { m /= a.m; return *this; } [[deprecated( "\n\n" "Clever use of multiplication order can get rid of the transpose." "\n\n" "Set `transpose = GL_TRUE` when calling glUniformMatrix* to transpose " "when uploading to VRAM." "\n\n" )]] auto transpose() const { return Matrix3{glm::transpose(m)}; } // undefined behavior if the matrix is not orthogonal auto inverse_as_if_orthogonal() const { return Matrix3{glm::transpose(m)}; } auto inverse() const { return Matrix3{glm::inverse(m)}; } auto determinant() const { return glm::determinant(m); } auto orthonormalize() const { return Matrix3{glm::orthonormalize(m)}; } }; inline bool operator == (Matrix3 const& a, Matrix3 const& b) { return a.m == b.m; } inline bool operator != (Matrix3 const& a, Matrix3 const& b) { return a.m != b.m; } inline Matrix3 operator + (Matrix3 const& a, Matrix3 const& b) { return Matrix3{a.m + b.m}; } inline Matrix3 operator - (Matrix3 const& a, Matrix3 const& b) { return Matrix3{a.m - b.m}; } inline Matrix3 operator * (Matrix3 const& a, Matrix3 const& b) { return Matrix3{a.m * b.m}; } inline Vector3 operator * (Matrix3 const& a, Vector3 const& b) { return Vector3{a.m * b.v}; } inline Vector3 operator * (Vector3 const& a, Matrix3 const& b) { return Vector3{a.v * b.m}; } inline Matrix3 abs(Matrix3 const& a) { return Matrix3{ Vector3{abs(a.m[0])}, Vector3{abs(a.m[1])}, Vector3{abs(a.m[2])}, }; } inline std::ostream & operator << (std::ostream & o, Matrix3 const& m) { return (o << "Matrix3{\n" << " " << Vector3{m[0]} << ",\n" << " " << Vector3{m[1]} << ",\n" << " " << Vector3{m[2]} << ",\n" << "}"); } } }
[ "624585443@qq.com" ]
624585443@qq.com
31cb0ead0238bb39c2403d1218edb7082c7e9e6a
5697b1c8be7355458900684abeb6ecf347a508c9
/most_occ.cpp
d0ac3711939c0eb82c618253c3f431ef97ddebb7
[]
no_license
Sneha-D/Programs
c1c4f5f2d7b31c1d3683275bd171664da3d20ec8
8da46875df50f409237077c1f84675cf46acd8ff
refs/heads/master
2021-01-10T01:03:02.243241
2014-03-01T18:29:19
2014-03-01T18:29:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
431
cpp
#include <iostream> using namespace std; int main(){ int n,h[99]; cin>>n; for(int i=0;i<=99;i++){ h[i]=0; } int max=0; for(int i=0;i<n;i++){ int x; cin>>x; h[x]++; if(max<h[x]) max=h[x]; } for(int i=0;i<=99;i++) if(h[i]==max) cout<<i<<" "; return 0; }
[ "dsneha26@hotmail.com" ]
dsneha26@hotmail.com
5941b84cdd780accb49c6ba7ec1ae21464c6ac97
ceaebe1be8d750649e9f78aded7a1db6f4959c14
/tree.cc
394a618f530006a9af04eee07d88776ac7837e1d
[]
no_license
3141592654/cs221hw5
62fa3017e0c0b77130932ef4bb135b6a95646b82
d72be37f8578ca0e8764646abba4317e5b0d1d97
refs/heads/master
2020-04-02T15:09:45.148802
2018-10-27T03:45:44
2018-10-27T03:45:44
154,504,779
0
0
null
null
null
null
UTF-8
C++
false
false
2,506
cc
/* * Implementation of tree.hh. */ #include <assert.h> #include "tree.hh" // implementation of create_tree tree_ptr_t create_tree(const key_t& key, const value_t& value, tree_ptr_t left, tree_ptr_t right) { tree_ptr_t retval = new Tree{key, value, left, right}; return retval; } // implementation of destroy_tree void destroy_tree(tree_ptr_t tree) { // could leave out the != nullptr if you wanted. if (tree->left_ != nullptr) { destroy_tree(tree->left_); } if (tree->right_ != nullptr) { destroy_tree(tree->right_); } delete tree; } // helper function. returns true if the key has been found // at this node or any of its children. constructs the path // to the relevant node in the following way. traverse through // the tree until you find the key. once you do, tell the parent // node about this. the parent node knows if this was to its left // or its right, so it prepends the relevant letter. then it // returns to its own parent node. bool value_found(const tree_ptr_t tree, std::string* result, const key_t key) { if (tree == nullptr) { return false; } if (tree->key_ == key) { return true; } // check if the key was found somewhere to the left of this parent node. // if so, make a note of it and return to the parent node. if (value_found(tree->left_, result, key)) { (*result).insert(0, 1, 'L'); return true; } // check if key was found to right of this parent node. if (value_found(tree->right_, result, key)) { (*result).insert(0, 1, 'R'); return true; } // if the code has gotten to this point, then this node // doesn't have the key, and neither do its children, so return false; } // implementation of path_to std::string path_to(tree_ptr_t tree, key_t key) { std::string result(""); assert(value_found(tree, &result, key)); return result; } // implementation of node_at tree_ptr_t node_at(tree_ptr_t tree, std::string path) { if (tree == nullptr) { return tree; } // pretty standard stuff, just go down the path // and store the result node in tree std::string::iterator it = path.begin(); for (; it != path.end(); ++it) { if (*it == 'L') { if (tree->left_ == nullptr) { return nullptr; } tree = tree->left_; } else { if (*it == 'R') { if (tree->right_ == nullptr) { return nullptr; } tree = tree->right_; } else { return nullptr; } } } return tree; }
[ "dummyemail@asd.com" ]
dummyemail@asd.com
fb5566c54fbfbd794d95fab4c8576a68565df178
6bfafac8429c051e20c963ff771040e870a3966a
/includes/Float.hpp
3cedf8f5ae62ac247c1a8df2ff2cdb317648000b
[]
no_license
marrodri/abstact_vm
0bdf30b92e18a04d8a1a9f49ce467df56567fb4f
0f15093964fabff71681d50df18a54a633b1acd0
refs/heads/master
2022-11-16T10:40:47.615955
2020-07-10T19:21:08
2020-07-10T19:21:08
263,718,065
0
0
null
null
null
null
UTF-8
C++
false
false
793
hpp
#ifndef FLOAT_HPP #define FLOAT_HPP #include "IOperand.hpp" #include "Op_exceptions.hpp" #include <float.h> class Float : public IOperand { private: float float_val; std::string instance; public: Float(); Float(double value); Float(Float const & src); ~Float(); char const getValue(); void setValue(char value); int getPrecision(void) const override; eOperandType getType(void) const override; IOperand const *operator+(IOperand const & rhs) const override; IOperand const *operator-(IOperand const & rhs) const override; IOperand const *operator*(IOperand const & rhs) const override; IOperand const *operator/(IOperand const & rhs) const override; IOperand const *operator%(IOperand const & rhs) const override; std::string const &toString(void) const override; }; #endif
[ "laza.mar64@gmail.com" ]
laza.mar64@gmail.com
e5d6218c6c2cf785dcb3f612addc2f7d2cfd0aed
519efab80e3475247c9539c541989814abf86e8d
/FastReport VCL 6.3.3/LibD26/TTFHelpers.hpp
de6b59bccd5bcddc25cc0a730c5db783835cc9dd
[]
no_license
noelsonneres/MeusComponentesDelphi
6c46d7b1ceca55209dc538258e3810589841d590
8f03a8a77794561762166c64d9a96aebf45b8824
refs/heads/master
2022-12-09T17:41:20.560526
2020-09-20T18:25:18
2020-09-20T18:25:18
252,246,981
3
5
null
2022-12-07T04:39:56
2020-04-01T17:48:43
Pascal
UTF-8
C++
false
false
1,797
hpp
// CodeGear C++Builder // Copyright (c) 1995, 2017 by Embarcadero Technologies, Inc. // All rights reserved // (DO NOT EDIT: machine generated header) 'TTFHelpers.pas' rev: 33.00 (Windows) #ifndef TtfhelpersHPP #define TtfhelpersHPP #pragma delphiheader begin #pragma option push #pragma option -w- // All warnings off #pragma option -Vx // Zero-length empty class member #pragma pack(push,8) #include <System.hpp> #include <SysInit.hpp> //-- user supplied ----------------------------------------------------------- namespace Ttfhelpers { //-- forward type declarations ----------------------------------------------- class DELPHICLASS TTF_Helpers; //-- type declarations ------------------------------------------------------- #pragma pack(push,4) class PASCALIMPLEMENTATION TTF_Helpers : public System::TObject { typedef System::TObject inherited; protected: __fastcall TTF_Helpers(); public: __classmethod void * __fastcall Increment(void * ptr, int cbSize); __classmethod short __fastcall SwapInt16(short v); __classmethod int __fastcall SwapInt32(int v); __classmethod System::Word __fastcall SwapUInt16(System::Word v); __classmethod unsigned __fastcall SwapUInt32(unsigned v); __classmethod unsigned __int64 __fastcall SwapUInt64(unsigned __int64 v); public: /* TObject.Destroy */ inline __fastcall virtual ~TTF_Helpers() { } }; #pragma pack(pop) //-- var, const, procedure --------------------------------------------------- } /* namespace Ttfhelpers */ #if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_TTFHELPERS) using namespace Ttfhelpers; #endif #pragma pack(pop) #pragma option pop #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // TtfhelpersHPP
[ "noelsonneres@gmail.com" ]
noelsonneres@gmail.com
32b82a3f2574f233f7ac9a96511ca1c067ea75bb
28e210d1e8a0127580c3f02ac0e8902b9c5b0512
/Neural Network/NeuralNetwork.h
a2ed75b1cb50c41c95e2cd3fd18ac73cc0656533
[ "MIT" ]
permissive
JTiefnig/NN_Visualizer
ae92081b5356b6525f078ac989ff2652a8df6304
9f17ef671caab05a971fa49f605586d1f4c2b32b
refs/heads/master
2023-03-16T19:55:56.409100
2019-06-06T18:07:05
2019-06-06T18:07:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,967
h
#pragma once #include "Layer.h" #include "DataSet.h" #include "LearningMethod.h" #include <vector> #include <string> class NeuralNetwork { public: // Initialization NeuralNetwork(); // Clear enough int getNumberOfLayers(); // Compares all layer sizes and returns maximum one int getMaxNumberOfNeurons(); // Adds layer to layers vector void addLayer(Layer*); // Calculates delta values for all neurons and updates all the weights and biases // based on that delta values void backPropogate(std::vector<double> const &, std::vector<double> const &, double); // Takes vector of values and assigns it to input layer neurons. // Then calculates activations throughout the network. std::vector<double> predict(std::vector<double> &); // TODO: Update the comment // Takes a DataSet and runs each sample through predict function. // Then takes the output layer result and pass it through backPropogation function // with expected values in the sample. void train(DataSet*, double, int); // To predict for set of inputs void test(DataSet*); // Returns a string which represent neurons in each layer with activation values std::string toString(); // Creates new Weight objects and bias values for each neuron void buildWeightsAndBiases(); // Last layer activations subtracted from expected value double costFunction(std::vector<double> const &); // Clear enough void setLearningMethod(LearningMethod*); // Clear enough LearningMethod* getLearningMethod(); std::string getCurrentStage(); const std::vector<Layer*> & getLayers(); // Redundant: Delete this line void printTheResult(int i, Sample* s); // Neural Network Builder class class Builder { public: Builder(); Builder* addLayer(Layer*); Builder* setLearningMethod(LearningMethod*); NeuralNetwork* build(); private: NeuralNetwork* neuralNetwork; }; private: std::vector<Layer*> layers; LearningMethod* learningMethod; std::string currentStage; };
[ "aslanbaxisli.ba@gmail.com" ]
aslanbaxisli.ba@gmail.com
eeabd6e3b57befa4d95264db85bd46f9f6ab2335
1269f59a03784427fa04ca9a9a4e2556edcdbd7a
/d04/ex00/Victim.hpp
28b0a54d6417a0a76e95c7959dcc90a685f1afaa
[]
no_license
spalmaro/Piscine-CPP
d0ccb8709fc513130140492250a78cdb23398f07
fe4d6abb464c559d38936c8001cc78bb2c87bb34
refs/heads/master
2020-03-18T19:36:22.839017
2018-06-05T18:24:50
2018-06-05T18:24:50
135,164,796
0
0
null
null
null
null
UTF-8
C++
false
false
549
hpp
#ifndef VICTIM_CLASS_H # define VICTIM_CLASS_H #include <string> class Victim { protected: Victim(void); std::string _name; public: Victim(std::string name); Victim(Victim const & src); virtual ~Victim(void); Victim & operator = (Victim const & rhs); void introduce() const; virtual void getPolymorphed() const; std::string getName() const ; }; std::ostream & operator<<( std::ostream &o, Victim const & rhs); #endif
[ "spalmaro@e2r11p15.42.fr" ]
spalmaro@e2r11p15.42.fr
5cd76e41df5183793052b67afe7387367d3dd5a7
1920fd9e106c2a7c2a32168e25cb0b940fd6e821
/Server/p7/include/ClTextConsole.h
5c5cbcd9ef57f1f6966f80f83d9505961975937a
[]
no_license
Mars36/Messenger
f6a624ee49aa7e24ea54df38bcdb90e70fb53c97
2d6b5814260374fdd5441b7f62d61c9107d1ef5c
refs/heads/main
2023-03-07T14:46:27.977802
2021-02-21T23:50:33
2021-02-21T23:50:33
340,997,598
0
0
null
null
null
null
UTF-8
C++
false
false
2,823
h
//////////////////////////////////////////////////////////////////////////////// // / // 2012-2020 (c) Baical / // / // This library is free software; you can redistribute it and/or / // modify it under the terms of the GNU Lesser General Public / // License as published by the Free Software Foundation; either / // version 3.0 of the License, or (at your option) any later version. / // / // This library is distributed in the hope that it will be useful, / // but WITHOUT ANY WARRANTY; without even the implied warranty of / // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU / // Lesser General Public License for more details. / // / // You should have received a copy of the GNU Lesser General Public / // License along with this library. / // / //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // This header file provide printing to console / //////////////////////////////////////////////////////////////////////////////// #ifndef CLTEXTCONSOLE_H #define CLTEXTCONSOLE_H //////////////////////////////////////////////////////////////////////////////// class CClTextConsole : public CClTextSink { public: CClTextConsole() { } virtual ~CClTextConsole() { } virtual eClient_Status Initialize(tXCHAR **i_pArgs, tINT32 i_iCount) { UNUSED_ARG(i_pArgs); UNUSED_ARG(i_iCount); return ECLIENT_STATUS_OK; } virtual eClient_Status Log(const CClTextSink::sLog &i_rRawLog, const tXCHAR *i_pFmtLog, size_t i_szFmtLog ) { UNUSED_ARG(i_rRawLog); UNUSED_ARG(i_szFmtLog); #ifdef UTF8_ENCODING printf("%s", i_pFmtLog); #else wprintf(L"%s", i_pFmtLog); #endif printf("\n"); return ECLIENT_STATUS_OK; } virtual eClient_Status DumpBuffers() { return ECLIENT_STATUS_OK; } }; #endif //CLTEXTCONSOLE_H
[ "igrok456@yandex.ru" ]
igrok456@yandex.ru
0573adab4e6d5f1a963abdab79bef1b6e883b876
e8e1a2385b5ab1b123d687f303df255562cb1902
/httpwindow.cpp
535073c36a4414cedfdd4a74db2aa96e1c688e3a
[]
no_license
lengocthuong15/buffalo-downloader
d68aa4665f4fda8f5e6f6e42f54a9e29bbd78a7f
385194d92b5b778c17a8f2c8b702e68b440b0dfd
refs/heads/main
2023-06-25T09:09:29.778457
2021-07-17T05:55:40
2021-07-17T05:55:40
385,887,364
1
0
null
null
null
null
UTF-8
C++
false
false
21,750
cpp
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of The Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtWidgets> #include <QtNetwork> #include <QUrl> #include <QHttp2Configuration> #include "httpwindow.h" #include "ui_authenticationdialog.h" #if QT_CONFIG(ssl) const char defaultUrl[] = "https://www.qt.io/"; #else const char defaultUrl[] = "http://www.qt.io/"; #endif const QString CONTENT_LENGTH = "Content-Length"; const char defaultFileName[] = "index.html"; ProgressDialog::ProgressDialog(const QUrl &url, QWidget *parent) : QProgressDialog(parent) { setWindowTitle(tr("Download Progress")); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setLabelText(tr("Downloading %1.").arg(url.toDisplayString())); setMinimum(0); setValue(0); setMinimumDuration(0); setMinimumSize(QSize(400, 75)); } void ProgressDialog::networkReplyProgress(qint64 bytesRead, qint64 totalBytes) { setMaximum(totalBytes); setValue(bytesRead); } DownloadWorker::DownloadWorker(const REQUEST_PARAM &rqParam, TEMP_FILE &tempFile) : QThread(), rqParam(rqParam), tempFile(tempFile) { QThread::moveToThread(this); qnam.moveToThread(this); if (!rqParam.proxyName.isEmpty() && rqParam.proxyPort) { QNetworkProxy proxy; proxy.setType(QNetworkProxy::HttpProxy); proxy.setHostName(rqParam.proxyName); proxy.setPort(rqParam.proxyPort); qnam.setProxy(proxy); } } void DownloadWorker::readyRead() { if (this->isCancle) { qDebug() << "Ready read but the requested is cancled"; return; } qint64 readByte = reply->bytesAvailable(); qDebug() << "ReadyRead - byteAvailable: " << readByte; if (tempFile.file) { tempFile.file->write(reply->readAll()); } emit reply_progress(readByte); } void DownloadWorker::doneRead() { if (this->tempFile.file) { this->tempFile.file->close(); } } void DownloadWorker::cancle_download_slot() { this->isCancle = true; this->reply->abort(); qDebug() << "DownloadWorker Cancle download: " << tempFile.file->fileName(); if (tempFile.file) { tempFile.file->close(); tempFile.file->remove(); delete tempFile.file; tempFile.file = nullptr; } emit cancle_download_signal(); } void DownloadWorker::run() { QNetworkRequest request(rqParam.url); request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, QVariant(true)); request.setAttribute(QNetworkRequest::HTTP2WasUsedAttribute, QVariant(true)); QString concatenated = QStringLiteral("%1:%2").arg(rqParam.user, rqParam.password); QByteArray data = concatenated.toLocal8Bit().toBase64(); QString headerData = "Basic " + data; request.setRawHeader("Authorization", headerData.toLocal8Bit()); QString rangeHeader = QStringLiteral("bytes=%1-%2").arg(rqParam.start).arg(rqParam.end); request.setRawHeader("Range", rangeHeader.toLocal8Bit()); QHttp2Configuration http2Config = request.http2Configuration(); http2Config.setMaxFrameSize(65536); request.setHttp2Configuration(http2Config); this->reply = qnam.get(request); QEventLoop waitingLoop; QObject::connect(reply, &QNetworkReply::finished, &waitingLoop, &QEventLoop::quit); //QObject::connect(this, &DownloadWorker::cancle_download_signal, &waitingLoop, &QEventLoop::quit); //QObject::connect(reply, &QNetworkReply::downloadProgress, this, &DownloadWorker::reply_progress); QObject::connect(reply, &QNetworkReply::readyRead, this, &DownloadWorker::readyRead); waitingLoop.exec(); if (!this->isCancle) { qDebug() << "Download done: " << tempFile.file->fileName(); emit download_done(tempFile.file->fileName()); } } HttpWindow::HttpWindow(QWidget *parent) : QDialog(parent) , statusLabel(new QLabel(tr("Please enter the URL of a file you want to download.\n\n"), this)) , urlLineEdit(new QLineEdit(defaultUrl)) , downloadButton(new QPushButton(tr("Download"))) , launchCheckBox(new QCheckBox("Launch file")) , defaultFileLineEdit(new QLineEdit(defaultFileName)) , downloadDirectoryLineEdit(new QLineEdit) , userNameEdit(new QLineEdit) , passEdit(new QLineEdit) , proxyServerEdit(new QLineEdit) , proxyPortEdit(new QLineEdit) , qnam(new QNetworkAccessManager) , reply(nullptr) , file(nullptr) , httpRequestAborted(false) { setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setWindowTitle(tr("Buffalo-Downloader")); connect(qnam, &QNetworkAccessManager::authenticationRequired, this, &HttpWindow::slotAuthenticationRequired); #ifndef QT_NO_SSL connect(qnam, &QNetworkAccessManager::sslErrors, this, &HttpWindow::sslErrors); #endif QFormLayout *formLayout = new QFormLayout; urlLineEdit->setClearButtonEnabled(true); connect(urlLineEdit, &QLineEdit::textChanged, this, &HttpWindow::enableDownloadButton); formLayout->addRow(tr("&URL:"), urlLineEdit); QString downloadDirectory = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation); if (downloadDirectory.isEmpty() || !QFileInfo(downloadDirectory).isDir()) downloadDirectory = QDir::currentPath(); downloadDirectoryLineEdit->setText(QDir::toNativeSeparators(downloadDirectory)); formLayout->addRow(tr("&Download directory:"), downloadDirectoryLineEdit); formLayout->addRow(tr("Default &file:"), defaultFileLineEdit); formLayout->addRow(tr("User"), userNameEdit); formLayout->addRow(tr("Password"), passEdit); passEdit->setEchoMode(QLineEdit::Password); formLayout->addRow(tr("Proxy"), proxyServerEdit); formLayout->addRow(tr("Proxy port"), proxyPortEdit); launchCheckBox->setChecked(false); formLayout->addRow(launchCheckBox); QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->addLayout(formLayout); mainLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding)); statusLabel->setWordWrap(true); mainLayout->addWidget(statusLabel); downloadButton->setDefault(true); connect(downloadButton, &QAbstractButton::clicked, this, &HttpWindow::downloadFile); QPushButton *quitButton = new QPushButton(tr("Quit")); quitButton->setAutoDefault(false); connect(quitButton, &QAbstractButton::clicked, this, &QWidget::close); QDialogButtonBox *buttonBox = new QDialogButtonBox; buttonBox->addButton(downloadButton, QDialogButtonBox::ActionRole); buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole); mainLayout->addWidget(buttonBox); urlLineEdit->setFocus(); QString proxyName = proxyServerEdit->text(); int port = proxyPortEdit->text().toInt(); if (!proxyName.isEmpty() && port) { QNetworkProxy proxy; proxy.setType(QNetworkProxy::HttpProxy); proxy.setHostName(proxyName); proxy.setPort(port); qnam->setProxy(proxy); } //for (int i = 0; i < 2; i++) { // downloadWorkerPools.push_back(new DownloadWorker()); //} // //for (auto worker : downloadWorkerPools) { // worker->start(); //} } quint64 HttpWindow::getContentLength(const QUrl &requestedUrl) { url = requestedUrl; httpRequestAborted = false; QNetworkRequest request(url); request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, QVariant(true)); QString user = userNameEdit->text(); QString password = passEdit->text(); QString concatenated = QStringLiteral("%1:%2").arg(user, password); QByteArray data = concatenated.toLocal8Bit().toBase64(); QString headerData = "Basic " + data; request.setRawHeader("Authorization", headerData.toLocal8Bit()); QHttp2Configuration http2Config = request.http2Configuration(); http2Config.setMaxFrameSize(65536); request.setHttp2Configuration(http2Config); reply = qnam->head(request); QEventLoop eventLoop; QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit())); eventLoop.exec(); QList<QByteArray> reply_headers = reply->rawHeaderList(); quint64 len = 0; foreach(QByteArray head, reply_headers) { QString headStr = QString::fromUtf8(head); if (headStr.contains(CONTENT_LENGTH, Qt::CaseInsensitive)) { len = reply->rawHeader(head).toULong(); } qDebug() << head << ":" << reply->rawHeader(head); } return len; } DownloadWorker* HttpWindow::pickWorker() { for (auto worker: downloadWorkerPools) { if (worker->isIdle()) { return worker; } } return nullptr; } void HttpWindow::startRequest(const QUrl &requestedUrl) { totalBytes = getContentLength(requestedUrl); currentBytes = 0; url = requestedUrl; httpRequestAborted = false; QString user = userNameEdit->text(); QString password = passEdit->text(); //QNetworkRequest request(url); //request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, QVariant(true)); //request.setAttribute(QNetworkRequest::HTTP2WasUsedAttribute, QVariant(true)); //QHttp2Configuration http2Config = request.http2Configuration(); //QString concatenated = QStringLiteral("%1:%2").arg(user, password); //QByteArray data = concatenated.toLocal8Bit().toBase64(); //QString headerData = "Basic " + data; //request.setRawHeader("Authorization", headerData.toLocal8Bit()); //reply = qnam->head(request); //connect(reply, &QNetworkReply::finished, this, &HttpWindow::httpFinished); //connect(reply, &QIODevice::readyRead, this, &HttpWindow::httpReadyRead); ProgressDialog *progressDialog = new ProgressDialog(url, this); progressDialog->setAttribute(Qt::WA_DeleteOnClose); connect(progressDialog, &QProgressDialog::canceled, this, &HttpWindow::cancelDownload); connect(this, &HttpWindow::download_progress_signal, progressDialog, &ProgressDialog::networkReplyProgress); connect(this, &HttpWindow::download_done_signal, progressDialog, &ProgressDialog::hide); connect(this, &HttpWindow::cancle_signal, progressDialog, &ProgressDialog::close); //connect(this, &HttpWindow::cancle_signal, progressDialog, &ProgressDialog::hide); progressDialog->show(); statusLabel->setText(tr("Downloading %1...").arg(url.toString())); //Testing REQUEST_PARAM rqParam; rqParam.url = requestedUrl; rqParam.user = user; rqParam.password = password; QString proxyName = proxyServerEdit->text(); int port = proxyPortEdit->text().toInt(); rqParam.proxyName = proxyName; rqParam.proxyPort = port; int size = filePools.size(); quint64 step = totalBytes / size; quint64 start = 0; quint64 end = step; for (auto item : filePools) { rqParam.start = start; rqParam.end = end; DownloadWorker *worker = new DownloadWorker(rqParam, item); connect(worker, &DownloadWorker::download_done, this, &HttpWindow::rebuildFile); connect(this, &HttpWindow::cancle_signal, worker, &DownloadWorker::cancle_download_slot); connect(worker, &DownloadWorker::reply_progress, this, &HttpWindow::download_progress); connect(worker, &QThread::finished, worker, &QThread::deleteLater, Qt::QueuedConnection); worker->start(); start = end + 1; end = start + step; } } void HttpWindow::downloadFile() { const QString urlSpec = urlLineEdit->text().trimmed(); if (urlSpec.isEmpty()) return; const QUrl newUrl = QUrl::fromUserInput(urlSpec); if (!newUrl.isValid()) { QMessageBox::information(this, tr("Error"), tr("Invalid URL: %1: %2").arg(urlSpec, newUrl.errorString())); return; } QString fileName = newUrl.fileName(); if (fileName.isEmpty()) fileName = defaultFileLineEdit->text().trimmed(); if (fileName.isEmpty()) fileName = defaultFileName; QString downloadDirectory = QDir::cleanPath(downloadDirectoryLineEdit->text().trimmed()); bool useDirectory = !downloadDirectory.isEmpty() && QFileInfo(downloadDirectory).isDir(); if (useDirectory) fileName.prepend(downloadDirectory + '/'); if (QFile::exists(fileName)) { if (QMessageBox::question(this, tr("Overwrite Existing File"), tr("There already exists a file called %1%2." " Overwrite?") .arg(fileName, useDirectory ? QString() : QStringLiteral(" in the current directory")), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No) { return; } QFile::remove(fileName); } file = openFileForWrite(fileName); filePools.clear(); for (int i = 0 ; i < 20; i++) { QString tempFileName = fileName; tempFileName.append(QStringLiteral("_%1").arg(i)); filePools.push_back(TEMP_FILE(openFileForWrite(tempFileName))); } if (!file) return; downloadButton->setEnabled(false); // schedule the request startRequest(newUrl); } QFile *HttpWindow::openFileForWrite(const QString &fileName) { QScopedPointer<QFile> file(new QFile(fileName)); if (!file->open(QIODevice::WriteOnly)) { QMessageBox::information(this, tr("Error"), tr("Unable to save the file %1: %2.") .arg(QDir::toNativeSeparators(fileName), file->errorString())); return nullptr; } return file.take(); } QFile *HttpWindow::openFileForRead(const QString &fileName) { QScopedPointer<QFile> file(new QFile(fileName)); if (!file->open(QIODevice::ReadOnly)) { QMessageBox::information(this, tr("Error"), tr("Unable to save the file %1: %2.") .arg(QDir::toNativeSeparators(fileName), file->errorString())); return nullptr; } return file.take(); } void HttpWindow::cancelDownload() { if (this->httpRequestAborted) { qDebug() << "The request is already cancled"; return; } qDebug() << "Cancle download: " << this->file->fileName(); statusLabel->setText(tr("Download canceled.")); httpRequestAborted = true; //reply->abort(); downloadButton->setEnabled(true); if (this->file) { file->close(); file->remove(); delete file; file = nullptr; } emit cancle_signal(); } void HttpWindow::rebuildFile(const QString &fileName) { qDebug() << "Rebuild file"; int count = 0; int size = filePools.size(); for (auto &item : filePools) { if (item.file->fileName() == fileName) { item.isFinished = true; } if (item.isFinished) { count++; } } if (count == size) { for (auto item : filePools) { item.file->flush(); item.file->close(); QString fileNameTemp = item.file->fileName(); auto tempFile = openFileForRead(fileNameTemp); this->file->write(tempFile->readAll()); tempFile->close(); delete tempFile; item.file->remove(); delete item.file; } filePools.clear(); file->close(); delete file; file = nullptr; emit download_done_signal(); } } void HttpWindow::httpFinished() { QFileInfo fi; fi.setFile(file->fileName()); //if (file) { // fi.setFile(file->fileName()); // file->close(); // delete file; // file = nullptr; //} if (httpRequestAborted) { reply->deleteLater(); reply = nullptr; return; } if (reply->error()) { QFile::remove(fi.absoluteFilePath()); statusLabel->setText(tr("Download failed:\n%1.").arg(reply->errorString())); downloadButton->setEnabled(true); reply->deleteLater(); reply = nullptr; return; } const QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); QList<QByteArray> reply_headers = reply->rawHeaderList(); foreach(QByteArray head, reply_headers) { qDebug() << head << ":" << reply->rawHeader(head); } reply->deleteLater(); reply = nullptr; if (!redirectionTarget.isNull()) { const QUrl redirectedUrl = url.resolved(redirectionTarget.toUrl()); if (QMessageBox::question(this, tr("Redirect"), tr("Redirect to %1 ?").arg(redirectedUrl.toString()), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) { QFile::remove(fi.absoluteFilePath()); downloadButton->setEnabled(true); statusLabel->setText(tr("Download failed:\nRedirect rejected.")); return; } file = openFileForWrite(fi.absoluteFilePath()); if (!file) { downloadButton->setEnabled(true); return; } startRequest(redirectedUrl); return; } statusLabel->setText(tr("Downloaded %1 bytes to %2\nin\n%3") .arg(fi.size()).arg(fi.fileName(), QDir::toNativeSeparators(fi.absolutePath()))); if (launchCheckBox->isChecked()) QDesktopServices::openUrl(QUrl::fromLocalFile(fi.absoluteFilePath())); downloadButton->setEnabled(true); } void HttpWindow::httpReadyRead() { // this slot gets called every time the QNetworkReply has new data. // We read all of its new data and write it into the file. // That way we use less RAM than when reading it at the finished() // signal of the QNetworkReply if (file) file->write(reply->readAll()); } void HttpWindow::enableDownloadButton() { downloadButton->setEnabled(!urlLineEdit->text().isEmpty()); } void HttpWindow::slotAuthenticationRequired(QNetworkReply *, QAuthenticator *authenticator) { QDialog authenticationDialog; Ui::Dialog ui; ui.setupUi(&authenticationDialog); authenticationDialog.adjustSize(); ui.siteDescription->setText(tr("%1 at %2").arg(authenticator->realm(), url.host())); // Did the URL have information? Fill the UI // This is only relevant if the URL-supplied credentials were wrong ui.userEdit->setText(url.userName()); ui.passwordEdit->setText(url.password()); if (authenticationDialog.exec() == QDialog::Accepted) { authenticator->setUser(ui.userEdit->text()); authenticator->setPassword(ui.passwordEdit->text()); } } void HttpWindow::download_progress(qint64 bytesRead) { qDebug() << "HttpWindow download_progress " << bytesRead; if (this->httpRequestAborted) { qDebug() << "HttpWindow download_progress: Request is cancled"; return; } currentBytes += bytesRead; emit download_progress_signal(currentBytes, this->totalBytes); } #ifndef QT_NO_SSL void HttpWindow::sslErrors(QNetworkReply *, const QList<QSslError> &errors) { QString errorString; foreach(const QSslError &error, errors) { if (!errorString.isEmpty()) errorString += '\n'; errorString += error.errorString(); } if (QMessageBox::warning(this, tr("SSL Errors"), tr("One or more SSL errors has occurred:\n%1").arg(errorString), QMessageBox::Ignore | QMessageBox::Abort) == QMessageBox::Ignore) { reply->ignoreSslErrors(); } } #endif
[ "lengocthuong15@gmail.com" ]
lengocthuong15@gmail.com
80d45da398728381f8c0eb2a6b8f3af56a5fa6a6
57de0787f7cee17ab1aaa48b919505f25ce11d80
/src/json/json_spirit_writer_template.h
f39a3b6d747d1e7bf1fad3e1f2447ec3178391a0
[ "MIT" ]
permissive
xcobary/xcoin
791b843581e847c39a8fb65ef02004983c8f66ea
946cae5c0354855b3ba4c3da79f80e5d5b8a8f77
refs/heads/master
2020-12-03T02:07:50.379876
2017-06-30T20:03:50
2017-06-30T20:03:50
95,906,887
0
0
null
null
null
null
UTF-8
C++
false
false
6,871
h
#ifndef JSON_SPIRIT_WRITER_TEMPLATE #define JSON_SPIRIT_WRITER_TEMPLATE // Copyright John W. Wilkinson 2007 - 2009. // Distributed under the MIT License, see accompanying file LICENSE.txt // json spirit version 4.03 #include "json_spirit_value.h" #include <cassert> #include <sstream> #include <iomanip> namespace json_spirit { inline char to_hex_char( unsigned int c ) { assert( c <= 0xF ); const char ch = static_cast< char >( c ); if( ch < 10 ) return '0' + ch; return 'A' - 10 + ch; } template< class String_type > String_type non_printable_to_string( unsigned int c ) { typedef typename String_type::value_type Char_type; String_type result( 6, '\\' ); result[1] = 'u'; result[ 5 ] = to_hex_char( c & 0x000F ); c >>= 4; result[ 4 ] = to_hex_char( c & 0x000F ); c >>= 4; result[ 3 ] = to_hex_char( c & 0x000F ); c >>= 4; result[ 2 ] = to_hex_char( c & 0x000F ); return result; } template< typename Char_type, class String_type > bool add_esc_char( Char_type c, String_type& s ) { switch( c ) { case '"': s += to_str< String_type >( "\\\"" ); return true; case '\\': s += to_str< String_type >( "\\\\" ); return true; case '\b': s += to_str< String_type >( "\\b" ); return true; case '\f': s += to_str< String_type >( "\\f" ); return true; case '\n': s += to_str< String_type >( "\\n" ); return true; case '\r': s += to_str< String_type >( "\\r" ); return true; case '\t': s += to_str< String_type >( "\\t" ); return true; } return false; } template< class String_type > String_type add_esc_chars( const String_type& s ) { typedef typename String_type::const_iterator Iter_type; typedef typename String_type::value_type Char_type; String_type result; const Iter_type end( s.end() ); for( Iter_type i = s.begin(); i != end; ++i ) { const Char_type c( *i ); if( add_esc_char( c, result ) ) continue; const wint_t unsigned_c( ( c >= 0 ) ? c : 256 + c ); if( iswprint( unsigned_c ) ) { result += c; } else { result += non_printable_to_string< String_type >( unsigned_c ); } } return result; } // this class generates the JSON text, // it keeps track of the indentation level etc. // template< class Value_type, class Ostream_type > class Generator { typedef typename Value_type::Config_type Config_type; typedef typename Config_type::String_type String_type; typedef typename Config_type::Object_type Object_type; typedef typename Config_type::Array_type Array_type; typedef typename String_type::value_type Char_type; typedef typename Object_type::value_type Obj_member_type; public: Generator( const Value_type& value, Ostream_type& os, bool pretty ) : os_( os ) , indentation_level_( 0 ) , pretty_( pretty ) { output( value ); } private: void output( const Value_type& value ) { switch( value.type() ) { case obj_type: output( value.get_obj() ); break; case array_type: output( value.get_array() ); break; case str_type: output( value.get_str() ); break; case bool_type: output( value.get_bool() ); break; case int_type: output_int( value ); break; /// Xcoin: Added std::fixed and changed precision from 16 to 8 case real_type: os_ << std::showpoint << std::fixed << std::setprecision(8) << value.get_real(); break; case null_type: os_ << "null"; break; default: assert( false ); } } void output( const Object_type& obj ) { output_array_or_obj( obj, '{', '}' ); } void output( const Array_type& arr ) { output_array_or_obj( arr, '[', ']' ); } void output( const Obj_member_type& member ) { output( Config_type::get_name( member ) ); space(); os_ << ':'; space(); output( Config_type::get_value( member ) ); } void output_int( const Value_type& value ) { if( value.is_uint64() ) { os_ << value.get_uint64(); } else { os_ << value.get_int64(); } } void output( const String_type& s ) { os_ << '"' << add_esc_chars( s ) << '"'; } void output( bool b ) { os_ << to_str< String_type >( b ? "true" : "false" ); } template< class T > void output_array_or_obj( const T& t, Char_type start_char, Char_type end_char ) { os_ << start_char; new_line(); ++indentation_level_; for( typename T::const_iterator i = t.begin(); i != t.end(); ++i ) { indent(); output( *i ); typename T::const_iterator next = i; if( ++next != t.end()) { os_ << ','; } new_line(); } --indentation_level_; indent(); os_ << end_char; } void indent() { if( !pretty_ ) return; for( int i = 0; i < indentation_level_; ++i ) { os_ << " "; } } void space() { if( pretty_ ) os_ << ' '; } void new_line() { if( pretty_ ) os_ << '\n'; } Generator& operator=( const Generator& ); // to prevent "assignment operator could not be generated" warning Ostream_type& os_; int indentation_level_; bool pretty_; }; template< class Value_type, class Ostream_type > void write_stream( const Value_type& value, Ostream_type& os, bool pretty ) { Generator< Value_type, Ostream_type >( value, os, pretty ); } template< class Value_type > typename Value_type::String_type write_string( const Value_type& value, bool pretty ) { typedef typename Value_type::String_type::value_type Char_type; std::basic_ostringstream< Char_type > os; write_stream( value, os, pretty ); return os.str(); } } #endif
[ "call08050208030@yahoo.com" ]
call08050208030@yahoo.com
603b551a4c14cea4233d2aaf502d38b331ae071a
404bcb0431139faa4e602a78a4a8d4fd076c4832
/ConsoleApplication1/ConsoleApplication1/ConsoleApplication1.cpp
c5858c6998001f995f1bd1454aa44fcc21c42716
[]
no_license
stalcer228/lab5
0afd0ef2d30037ff3424a2a5e27bcd7f2b8fce69
6ba7fca9e1aaa004eb74a14768ac2540e3781c13
refs/heads/master
2021-01-20T03:00:22.305894
2017-04-27T13:20:39
2017-04-27T13:20:39
89,478,129
0
0
null
null
null
null
UTF-8
C++
false
false
2,406
cpp
// ConsoleApplication1.cpp: определяет точку входа для консольного приложения. // #include "stdafx.h" #include <iostream> #include <list> #include <iterator> #include <ctime> #include <cstdlib> using namespace std; int main() { setlocale(LC_ALL, "Russian"); list<long> myList; // объявляем пустой список 1 srand(time(NULL)); for (int i = 0; i < 15; i++) { myList.push_back(rand() % 20); // добавляем в список новые элементы } cout << "List 1: "; copy(myList.begin(), myList.end(), ostream_iterator<long>(cout, " "));//вывод списка 1 cout << "\n"; int val; cout << "\nВведите номер удаляемого элемента: "; cin >> val; std::list<long>::iterator range = myList.begin(); std::advance(range, val - 1); myList.erase(range); cout << "\nList 1 с удаленным элементом: "; copy(myList.begin(), myList.end(), ostream_iterator<long>(cout, " ")); list<long> myList2; // объявляем пустой список 2 srand(time(NULL)); for (int i = 0; i < 15; i++) { myList2.push_back(rand() % 20); // добавляем в список 2 новые элементы } cout << "\nList 2: "; copy(myList2.begin(), myList2.end(), ostream_iterator<long>(cout, " ")); cout << "\n"; ////////////////////////////////////////////////////////////////////// int n; cout << "\nВведите номер элемента с которого будем удалять из List 1: \n"; cin >> n; cout << "\nВведите количество удаляемых элементов из List 1\n"; int count; cin >> count; for (int i = 0; i < count; i++) { std::list<long>::iterator range = myList.begin(); std::advance(range, n); myList.erase(range); } cout << "\nList 1 с удаленными элементами: "; copy(myList.begin(), myList.end(), ostream_iterator<long>(cout, " ")); ////////////////////////////////////////////////////////////////////// myList.sort(); myList2.sort(); myList.merge(myList2); cout << "\nОбъединили List 2 в list 1: "; copy(myList.begin(), myList.end(), ostream_iterator<long>(cout, " ")); cout << "\nЧто осталось в list 2: "; copy(myList2.begin(), myList2.end(), ostream_iterator<long>(cout, " ")); cout << "\n"; system("pause"); }
[ "brotherpahom@gmail.com" ]
brotherpahom@gmail.com
55b7929c72375161c1b52c05f2d19f4d1c6f86a2
c831d5b1de47a062e1e25f3eb3087404b7680588
/webkit/Source/WebKit2/WebProcess/WebCoreSupport/soup/WebFrameNetworkingContext.cpp
3d8d8d03729133de63095a149cc71554a6797e1e
[]
no_license
naver/sling
705b09c6bba6a5322e6478c8dc58bfdb0bfb560e
5671cd445a2caae0b4dd0332299e4cfede05062c
refs/heads/master
2023-08-24T15:50:41.690027
2016-12-20T17:19:13
2016-12-20T17:27:47
75,152,972
126
6
null
2022-10-31T00:25:34
2016-11-30T04:59:07
C++
UTF-8
C++
false
false
3,746
cpp
/* * Copyright (C) 2012 Igalia S.L. * Copyright (C) 2013 Company 100 Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h" #include "WebFrameNetworkingContext.h" #include "SessionTracker.h" #include "WebFrame.h" #include "WebPage.h" #include <WebCore/CookieJarSoup.h> #include <WebCore/NetworkStorageSession.h> #include <WebCore/SessionID.h> #include <WebCore/Settings.h> #include <WebCore/SoupNetworkSession.h> #include <wtf/NeverDestroyed.h> using namespace WebCore; namespace WebKit { void WebFrameNetworkingContext::ensurePrivateBrowsingSession(SessionID sessionID) { ASSERT(isMainThread()); if (SessionTracker::storageSession(sessionID)) return; SessionTracker::setSession(sessionID, NetworkStorageSession::createPrivateBrowsingSession(sessionID, String::number(sessionID.sessionID()))); } void WebFrameNetworkingContext::setCookieAcceptPolicyForAllContexts(HTTPCookieAcceptPolicy policy) { SoupCookieJarAcceptPolicy soupPolicy = SOUP_COOKIE_JAR_ACCEPT_ALWAYS; switch (policy) { case HTTPCookieAcceptPolicyAlways: soupPolicy = SOUP_COOKIE_JAR_ACCEPT_ALWAYS; break; case HTTPCookieAcceptPolicyNever: soupPolicy = SOUP_COOKIE_JAR_ACCEPT_NEVER; break; case HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain: soupPolicy = SOUP_COOKIE_JAR_ACCEPT_NO_THIRD_PARTY; break; } SoupCookieJar* cookieJar = WebCore::soupCookieJar(); soup_cookie_jar_set_accept_policy(cookieJar, soupPolicy); SoupNetworkSession& soupSession = NetworkStorageSession::defaultStorageSession().soupNetworkSession(); soup_cookie_jar_set_accept_policy(soupSession.cookieJar(), soupPolicy); SessionTracker::forEachNetworkStorageSession([&] (const NetworkStorageSession& session) { soup_cookie_jar_set_accept_policy(session.soupNetworkSession().cookieJar(), soupPolicy); }); } WebFrameNetworkingContext::WebFrameNetworkingContext(WebFrame* frame) : FrameNetworkingContext(frame->coreFrame()) { } NetworkStorageSession& WebFrameNetworkingContext::storageSession() const { if (frame() && frame()->page()->usesEphemeralSession()) return *SessionTracker::storageSession(SessionID::legacyPrivateSessionID()); return NetworkStorageSession::defaultStorageSession(); } WebFrameLoaderClient* WebFrameNetworkingContext::webFrameLoaderClient() const { if (!frame()) return nullptr; return toWebFrameLoaderClient(frame()->loader().client()); } }
[ "daewoong.jang@navercorp.com" ]
daewoong.jang@navercorp.com
e57d1479e726547db3b18872ed90308742c85e3c
1872ad087813269cd26d269fb6f0bfc5f9163c8a
/Code Forces/1185A - Ropewalkers.cpp
46299865e0d0922085c151e3caf4d4a53a84293d
[]
no_license
tashfi04/Programming_problem_solves
7d1506e06c5f95d01b7c7ee4bc13ec6f089fd864
e5c4603a0d17cf5f742818def675f74454922951
refs/heads/main
2023-06-08T08:45:40.341717
2021-06-26T03:17:22
2021-06-26T03:17:22
377,450,715
0
0
null
null
null
null
UTF-8
C++
false
false
295
cpp
#include<bits/stdc++.h> using namespace std; int main() { int a[3], d, time = 0; cin>>a[0]>>a[1]>>a[2]>>d; sort(a, a+3); if(a[1] - a[0] < d) time = d - (a[1] - a[0]); if(a[2] - a[1] < d) time += d - (a[2] - a[1]); cout<<time<<endl; return 0; }
[ "43473062+tashfi04@users.noreply.github.com" ]
43473062+tashfi04@users.noreply.github.com
76f2b8b5e67d9a55aef4412f443939cc2de2773f
1ab59ad983262a8989ff2c6414e43c192c2d963b
/Two Sum.cpp
2799a4bafc90ced44923969d20295f9b34576252
[]
no_license
Pradumnk23/Leetcode
868321d7efe4e6b01b41bb80a1d78da8769d19ce
1d707452fbb8e3266751b8372f8d0c90a8ca6422
refs/heads/main
2023-07-05T10:12:31.269104
2021-08-07T11:00:10
2021-08-07T11:00:10
333,369,804
1
0
null
null
null
null
UTF-8
C++
false
false
332
cpp
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> map; for (int i = 0;; ++i) { auto it = map.find(target - nums[i]); if (it != map.end()) return vector<int> {i, it->second}; map[nums[i]] = i; } } };
[ "noreply@github.com" ]
noreply@github.com
e633af258f1563ad65aa90e060d71dfd31fbf477
25820cc0eca78dcf4b95fdee2051d90d82222473
/55j/citemmulti.cpp
36daded88bccd6817211e6e2156596493224fedd
[ "Apache-2.0" ]
permissive
HappyFeng119/Source-Archive
eb619bba21159d920715e7ad0e54dd323eb57953
ab24ba44ffd34c329accedb980699e94c196fceb
refs/heads/main
2023-03-03T17:29:37.860236
2021-02-11T19:06:54
2021-02-11T19:06:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,559
cpp
// // CItemMulti.cpp // Copyright Menace Software (www.menasoft.com). // #include "graysvr.h" // predef header. ///////////////////////////////////////////////////////////////////////////// CItemMulti::CItemMulti( ITEMID_TYPE id, CItemBase * pItemDef ) : // CItemBaseMulti CItem( id, pItemDef ) { DEBUG_CHECK( dynamic_cast<const CItemBaseMulti*>(pItemDef)); m_pRegion = NULL; } CItemMulti::~CItemMulti() { MultiUnRealizeRegion(); // unrealize before removed from ground. DeletePrepare(); // Must remove early because virtuals will fail in child destructor. // NOTE: ??? This is dangerous to iterators. The "next" item may no longer be valid ! // Attempt to remove all the accessory junk. // NOTE: assume we have already been removed from Top Level if ( ! m_pRegion ) return; CWorldSearch Area( m_pRegion->m_pt, Multi_GetMaxDist() ); // largest area. while (true) { CItem * pItem = Area.GetItem(); if ( pItem == NULL ) break; if ( pItem == this ) // this gets deleted seperately. continue; if ( ! Multi_IsPartOf( pItem )) continue; pItem->Delete(); // delete the key id for the door/key/sign. } delete m_pRegion; } int CItemMulti::Multi_GetMaxDist() const { const CItemBaseMulti * pMultiDef = Multi_GetDef(); if ( pMultiDef == NULL ) return( 0 ); return( pMultiDef->GetMaxDist()); } const CItemBaseMulti * CItemMulti::Multi_GetDef( ITEMID_TYPE id ) // static { return( dynamic_cast <const CItemBaseMulti *> ( CItemBase::FindItemBase(id))); } bool CItemMulti::MultiRealizeRegion() { // Add/move a region for the multi so we know when we are in it. // RETURN: ignored. DEBUG_CHECK( IsType(IT_MULTI) || IsType(IT_SHIP) ); ASSERT( IsTopLevel()); const CItemBaseMulti * pMultiDef = Multi_GetDef(); if ( pMultiDef == NULL ) { DEBUG_ERR(( "Bad Multi type 0%x, uid=0%x\n", GetID(), GetUID())); return false; } if ( m_pRegion == NULL ) { RESOURCE_ID rid; rid.SetPrivateUID( GetUID()); m_pRegion = new CRegionWorld( rid ); } // Get Background region. CPointMap pt = GetTopPoint(); const CRegionWorld * pRegionBack = dynamic_cast <CRegionWorld*> (pt.GetRegion( REGION_TYPE_AREA )); ASSERT( pRegionBack ); ASSERT( pRegionBack != m_pRegion ); // Create the new region rectangle. CRectMap rect; reinterpret_cast<CGRect&>(rect) = pMultiDef->m_rect; rect.OffsetRect( pt.m_x, pt.m_y ); m_pRegion->SetRegionRect( rect ); m_pRegion->m_pt = pt; DWORD dwFlags; if ( IsType(IT_SHIP)) { dwFlags = REGION_FLAG_SHIP; } else { // Houses get some of the attribs of the land around it. dwFlags = pRegionBack->GetRegionFlags(); } dwFlags |= pMultiDef->m_dwRegionFlags; m_pRegion->SetRegionFlags( dwFlags ); CGString sName; sName.Format( "%s (%s)", (LPCTSTR) pRegionBack->GetName(), (LPCTSTR) GetName()); m_pRegion->SetName( sName ); return( m_pRegion->RealizeRegion()); } void CItemMulti::MultiUnRealizeRegion() { DEBUG_CHECK( IsType(IT_MULTI) || IsType(IT_SHIP) ); if ( m_pRegion == NULL ) return; m_pRegion->UnRealizeRegion(); // find all creatures in the region and remove this from them. CWorldSearch Area( m_pRegion->m_pt, Multi_GetMaxDist() ); while (true) { CChar * pChar = Area.GetChar(); if ( pChar == NULL ) break; if ( pChar->m_pArea != m_pRegion ) continue; pChar->MoveToRegionReTest( REGION_TYPE_AREA ); } } bool CItemMulti::Multi_CreateComponent( ITEMID_TYPE id, int dx, int dy, int dz, DWORD dwKeyCode ) { CItem * pItem = CreateTemplate( id ); ASSERT(pItem); CPointMap pt = GetTopPoint(); pt.m_x += dx; pt.m_y += dy; pt.m_z += dz; bool fNeedKey = false; switch ( pItem->GetType() ) { case IT_KEY: // it will get locked down with the house ? case IT_SIGN_GUMP: case IT_SHIP_TILLER: pItem->m_itKey.m_lockUID.SetPrivateUID( dwKeyCode ); // Set the key id for the key/sign. fNeedKey = true; break; case IT_DOOR: pItem->SetType(IT_DOOR_LOCKED); fNeedKey = true; break; case IT_CONTAINER: pItem->SetType(IT_CONTAINER_LOCKED); fNeedKey = true; break; case IT_SHIP_SIDE: pItem->SetType(IT_SHIP_SIDE_LOCKED); break; case IT_SHIP_HOLD: pItem->SetType(IT_SHIP_HOLD_LOCK); break; } pItem->SetAttr( ATTR_MOVE_NEVER | (m_Attr&(ATTR_MAGIC|ATTR_INVIS))); pItem->SetHue( GetHue()); pItem->m_uidLink = GetUID(); // lock it down with the structure. if ( pItem->IsTypeLockable() || pItem->IsTypeLocked()) { pItem->m_itContainer.m_lockUID.SetPrivateUID( dwKeyCode ); // Set the key id for the door/key/sign. pItem->m_itContainer.m_lock_complexity = 10000; // never pickable. } pItem->MoveTo( pt ); return( fNeedKey ); } void CItemMulti::Multi_Create( CChar * pChar, DWORD dwKeyCode ) { // Create house or Ship extra stuff. // ARGS: // dwKeyCode = set the key code for the doors/sides to this in case it's a drydocked ship. // NOTE: // This can only be done after the house is given location. const CItemBaseMulti * pMultiDef = Multi_GetDef(); // We are top level. if ( pMultiDef == NULL || ! IsTopLevel()) return; if ( dwKeyCode == UID_CLEAR ) dwKeyCode = GetUID(); // ??? SetTimeout( GetDecayTime()); house decay ? bool fNeedKey = false; int iQty = pMultiDef->m_Components.GetCount(); for ( int i=0; i<iQty; i++ ) { fNeedKey |= Multi_CreateComponent( (ITEMID_TYPE) pMultiDef->m_Components[i].m_id, pMultiDef->m_Components[i].m_dx, pMultiDef->m_Components[i].m_dy, pMultiDef->m_Components[i].m_dz, dwKeyCode ); } #if 0 const CGrayMulti * pMultiMul = g_World.GetMultiItemDefs( GetDispID()); if ( pMultiMul ) { iQty = pMultiMul->GetItemCount(); for ( int i=0; iQty--; i++ ) { const CUOMultiItemRec * pMultiItem = pMultiMul->GetItem(i); ASSERT(pMultiItem); if ( pMultiItem->m_visible ) // client side. continue; fNeedKey |= Multi_CreateComponent( pMultiItem->GetDispID(), pMultiItem->m_dx, pMultiItem->m_dy, pMultiItem->m_dz, dwKeyCode ); } } #endif CItem * pKey = NULL; if ( fNeedKey ) { // Create the key to the door. ITEMID_TYPE id = IsAttr(ATTR_MAGIC) ? ITEMID_KEY_MAGIC : ITEMID_KEY_COPPER ; pKey = CreateScript(id); ASSERT(pKey); pKey->SetType(IT_KEY); if ( g_Cfg.m_fAutoNewbieKeys ) pKey->SetAttr(ATTR_NEWBIE); pKey->SetAttr(m_Attr&ATTR_MAGIC); pKey->m_itKey.m_lockUID.SetPrivateUID( dwKeyCode ); pKey->m_uidLink = GetUID(); } Multi_GetSign(); // set the m_uidLink if ( pChar != NULL ) { m_itShip.m_UIDCreator = pChar->GetUID(); CItemMemory * pMemory = pChar->Memory_AddObjTypes( this, MEMORY_GUARD ); if ( pKey ) { // Put in your pack pChar->GetPackSafe()->ContentAdd( pKey ); // Put dupe key in the bank. pKey = CreateDupeItem( pKey ); pChar->GetBank()->ContentAdd( pKey ); pChar->SysMessage( "The duplicate key is in your bank account" ); } } else { // Just put the key on the front step ? DEBUG_CHECK( 0 ); } } bool CItemMulti::Multi_IsPartOf( const CItem * pItem ) const { // Assume it is in my area test already. // IT_MULTI // IT_SHIP ASSERT( pItem ); if ( pItem == this ) return( true ); return ( pItem->m_uidLink == GetUID()); } int CItemMulti::Multi_IsComponentOf( const CItem * pItem ) const { // NOTE: Doors can actually move so this won't work for them ! ASSERT(pItem); if ( ! Multi_IsPartOf( pItem )) return( -1 ); const CItemBaseMulti * pMultiDef = Multi_GetDef(); if ( pMultiDef == NULL ) return( -1 ); CPointMap pt = pItem->GetTopPoint(); int xdiff = pt.m_x - GetTopPoint().m_x ; int ydiff = pt.m_y - GetTopPoint().m_y; int iQty = pMultiDef->m_Components.GetCount(); for ( int i=0; i<iQty; i++ ) { if ( xdiff != pMultiDef->m_Components[i].m_dx || ydiff != pMultiDef->m_Components[i].m_dy ) continue; return( i ); } return( -1 ); } CItem * CItemMulti::Multi_FindItemComponent( int iComp ) const { const CItemBaseMulti * pMultiDef = Multi_GetDef(); if ( pMultiDef == NULL ) return( NULL ); return( NULL ); } CItem * CItemMulti::Multi_FindItemType( IT_TYPE type ) const { // Find a part of this multi nearby. if ( ! IsTopLevel()) return( NULL ); CWorldSearch Area( GetTopPoint(), Multi_GetMaxDist() ); while (true) { CItem * pItem = Area.GetItem(); if ( pItem == NULL ) return( NULL ); if ( ! Multi_IsPartOf( pItem )) continue; if ( pItem->IsType( type )) return( pItem ); } } bool CItemMulti::OnTick() { if ( IsType(IT_SHIP)) { // Ships move on their tick. if ( Ship_OnMoveTick()) return true; } return true; } void CItemMulti::OnMoveFrom() { // Being removed from the top level. // Might just be moving. ASSERT( m_pRegion ); m_pRegion->UnRealizeRegion(); } bool CItemMulti::MoveTo( CPointMap pt ) // Put item on the ground here. { // Move this item to it's point in the world. (ground/top level) if ( ! CItem::MoveTo(pt)) return false; // Multis need special region info to track when u are inside them. // Add new region info. MultiRealizeRegion(); return( true ); } CItem * CItemMulti::Multi_GetSign() { // Get my sign or tiller link. CItem * pTiller = m_uidLink.ItemFind(); if ( pTiller == NULL ) { pTiller = Multi_FindItemType( IsType(IT_SHIP) ? IT_SHIP_TILLER : IT_SIGN_GUMP ); if ( pTiller == NULL ) return( this ); m_uidLink = pTiller->GetUID(); } return( pTiller ); } bool CItemMulti::Multi_DeedConvert( CChar * pChar ) { // Turn a multi back into a deed. // If it has chests with stuff inside then refuse to do so ? // This item specifically will morph into a deed. (so keys will change!) CWorldSearch Area( GetTopPoint(), Multi_GetMaxDist() ); while (true) { CItem * pItem = Area.GetItem(); if ( pItem == NULL ) break; if ( ! Multi_IsPartOf( pItem )) continue; const CItemContainer* pCont = dynamic_cast <const CItemContainer*>(pItem); if ( pCont == NULL ) continue; if ( pCont->IsEmpty()) continue; // Can't re-deed this with the container full. if ( pChar ) { pChar->SysMessage( "Containers are not empty" ); } return( false ); } // Save the key code for the multi. return( false ); } #ifdef COMMENT void CItemMulti::Ship_Dock( CChar * pChar ) { // Attempt to dock this "ship". If it is a ship. // Must not have things on the deck or in the hold. ASSERT( pChar != NULL ); CItem * pItemShip; if ( ! IsType(IT_SHIP) ) { } if ( ! IsType(IT_SHIP) ) pChar->GetPackSafe()->ContentAdd( this ); } #endif bool CItem::Ship_Plank( bool fOpen ) { // IT_SHIP_PLANK to IT_SHIP_SIDE and IT_SHIP_SIDE_LOCKED // This item is the ships plank. CItemBase * pItemDef = Item_GetDef(); ITEMID_TYPE idState = (ITEMID_TYPE) RES_GET_INDEX( pItemDef->m_ttShipPlank.m_idState ); if ( ! idState ) { // Broken ? return( false ); } if ( IsType(IT_SHIP_PLANK)) { if ( fOpen ) return( true ); } else { DEBUG_CHECK( IsType(IT_SHIP_SIDE) || IsType(IT_SHIP_SIDE_LOCKED)); if ( ! fOpen ) return( true ); } SetID( idState ); Update(); return( true ); } void CItemMulti::Ship_Stop( void ) { // Make sure we have stopped. m_itShip.m_fSail = false; SetTimeout( -1 ); } bool CItemMulti::Ship_SetMoveDir( DIR_TYPE dir ) { // Set the direction we will move next time we get a tick. int iSpeed = 1; if ( m_itShip.m_DirMove == dir && m_itShip.m_fSail ) { if ( m_itShip.m_DirFace == m_itShip.m_DirMove && m_itShip.m_fSail == 1 ) { iSpeed = 2; } else return( false ); } if ( ! IsAttr(ATTR_MAGIC )) // make sound. { if ( ! Calc_GetRandVal(10)) { Sound( Calc_GetRandVal(2)?0x12:0x13 ); } } m_itShip.m_DirMove = dir; m_itShip.m_fSail = iSpeed; GetTopSector()->SetSectorWakeStatus(); // may get here b4 my client does. SetTimeout(( m_itShip.m_fSail == 1 ) ? 1*TICK_PER_SEC : (TICK_PER_SEC/5)); return( true ); } #define MAX_MULTI_LIST_OBJS 128 int CItemMulti::Ship_ListObjs( CObjBase ** ppObjList ) { // List all the objects in the structure. // Move the ship and everything on the deck // If too much stuff. then some will fall overboard. hehe. if ( ! IsTopLevel()) return 0; int iMaxDist = Multi_GetMaxDist(); // always list myself first. All other items must see my new region ! int iCount = 0; ppObjList[iCount++] = this; CWorldSearch AreaChar( GetTopPoint(), iMaxDist ); while ( iCount < MAX_MULTI_LIST_OBJS ) { CChar * pChar = AreaChar.GetChar(); if ( pChar == NULL ) break; if ( pChar->IsClient()) { pChar->GetClient()->addPause(); // get rid of flicker. for anyone even seeing this. } if ( ! m_pRegion->IsInside2d( pChar->GetTopPoint())) continue; int zdiff = pChar->GetTopZ() - GetTopZ(); if ( abs( zdiff ) > 3 ) continue; ppObjList[iCount++] = pChar; } CWorldSearch AreaItem( GetTopPoint(), iMaxDist ); while ( iCount < MAX_MULTI_LIST_OBJS ) { CItem * pItem = AreaItem.GetItem(); if ( pItem == NULL ) break; if ( pItem == this ) // already listed. continue; if ( ! Multi_IsPartOf( pItem )) { if ( ! m_pRegion->IsInside2d( pItem->GetTopPoint())) continue; if ( ! pItem->IsMovable()) continue; int zdiff = pItem->GetTopZ() - GetTopZ(); if ( abs( zdiff ) > 3 ) continue; } ppObjList[iCount++] = pItem; } return( iCount ); } bool CItemMulti::Ship_MoveDelta( CPointBase pdelta ) { // Move the ship one space in some direction. ASSERT( m_pRegion->m_iLinkedSectors ); int znew = GetTopZ() + pdelta.m_z; if ( pdelta.m_z > 0 ) { if ( znew >= (UO_SIZE_Z - PLAYER_HEIGHT )-1 ) return( false ); } else if ( pdelta.m_z < 0 ) { if ( znew <= (UO_SIZE_MIN_Z + 3 )) return( false ); } // Move the ship and everything on the deck CObjBase * ppObjs[MAX_MULTI_LIST_OBJS+1]; int iCount = Ship_ListObjs( ppObjs ); for ( int i=0; i <iCount; i++ ) { CObjBase * pObj = ppObjs[i]; ASSERT(pObj); CPointMap pt = pObj->GetTopPoint(); pt += pdelta; if ( ! pt.IsValidPoint()) // boat goes out of bounds ! { DEBUG_ERR(( "Ship uid=0%x out of bounds\n", GetUID())); continue; } pObj->MoveTo( pt ); if ( pObj->IsChar()) { ASSERT( m_pRegion->m_iLinkedSectors ); pObj->RemoveFromView(); // Get rid of the blink/walk pObj->Update(); } } return( true ); } bool CItemMulti::Ship_CanMoveTo( const CPointMap & pt ) const { // Can we move to the new location ? all water type ? if ( IsAttr(ATTR_MAGIC )) return( true ); // Run into other ships ? ignore my own region. const CRegionBase * pRegionOther = pt.GetRegion( REGION_TYPE_MULTI ); if ( pRegionOther == m_pRegion ) pRegionOther = NULL; WORD wBlockFlags = CAN_I_WATER; signed char z = g_World.GetHeightPoint( pt, wBlockFlags, pRegionOther ); if ( ! ( wBlockFlags & CAN_I_WATER )) { return( false ); } return( true ); } static const DIR_TYPE sm_Ship_FaceDir[] = { DIR_N, DIR_E, DIR_S, DIR_W, }; bool CItemMulti::Ship_Face( DIR_TYPE dir ) { // Change the direction of the ship. ASSERT( IsTopLevel()); DEBUG_CHECK( m_pRegion ); if ( m_pRegion == NULL ) { return false; } int i=0; for ( ; true; i++ ) { if ( i >= COUNTOF(sm_Ship_FaceDir)) return( false ); if ( dir == sm_Ship_FaceDir[i] ) break; } int iFaceOffset = Ship_GetFaceOffset(); ITEMID_TYPE idnew = (ITEMID_TYPE) ( GetID() - iFaceOffset + i ); const CItemBaseMulti * pMultiNew = Multi_GetDef( idnew ); if ( pMultiNew == NULL ) { return false; } const CItemBaseMulti * pMultiDef = Multi_GetDef(); ASSERT( pMultiDef); int iTurn = dir - sm_Ship_FaceDir[ iFaceOffset ]; // ?? Are there blocking items in the way of the turn ? // CRectMap // Reorient everything on the deck CObjBase * ppObjs[MAX_MULTI_LIST_OBJS+1]; int iCount = Ship_ListObjs( ppObjs ); for ( i=0; i<iCount; i++ ) { CObjBase * pObj = ppObjs[i]; CPointMap pt = pObj->GetTopPoint(); if ( pObj->IsItem()) { CItem * pItem = STATIC_CAST <CItem*> (pObj); ASSERT( pItem ); if ( pItem == this ) { m_pRegion->UnRealizeRegion(); pItem->SetID(idnew); // Adjust the region to be the new shape/area. MultiRealizeRegion(); pItem->Update(); continue; } // Is this a ship component ? transform it. int i = Multi_IsComponentOf( pItem ); if ( i>=0 ) { pItem->SetDispID( pMultiNew->m_Components[i].m_id ); pt = GetTopPoint(); pt.m_x += pMultiNew->m_Components[i].m_dx; pt.m_y += pMultiNew->m_Components[i].m_dy; pt.m_z += pMultiNew->m_Components[i].m_dz; pItem->MoveTo( pt ); continue; } } // -2,6 = left. // +2,-6 = right. // +-4 = flip around int iTmp; int xdiff = GetTopPoint().m_x - pt.m_x; int ydiff = GetTopPoint().m_y - pt.m_y; switch ( iTurn ) { case 2: // right case (2-DIR_QTY): iTmp = xdiff; xdiff = ydiff; ydiff = -iTmp; break; case -2: // left. case (DIR_QTY-2): iTmp = xdiff; xdiff = -ydiff; ydiff = iTmp; break; default: // u turn. xdiff = -xdiff; ydiff = -ydiff; break; } pt.m_x = GetTopPoint().m_x + xdiff; pt.m_y = GetTopPoint().m_y + ydiff; pObj->MoveTo( pt ); if ( pObj->IsChar()) { // Turn creatures as well. CChar * pChar = STATIC_CAST <CChar*> (pObj); ASSERT(pChar); pChar->m_dirFace = GetDirTurn( pChar->m_dirFace, iTurn ); pChar->RemoveFromView(); pChar->Update(); } } m_itShip.m_DirFace = dir; return( true ); } bool CItemMulti::Ship_Move( DIR_TYPE dir ) { if ( dir >= DIR_QTY ) return( false ); if ( m_pRegion == NULL ) { DEBUG_ERR(( "Ship bad region\n" )); return false; } CPointMap ptDelta; ptDelta.ZeroPoint(); ptDelta.Move( dir ); CPointMap ptForePrv = m_pRegion->GetRegionCorner(dir); CPointMap ptFore = ptForePrv; ptFore.Move( dir ); ptFore.m_z = GetTopZ(); if ( ! ptFore.IsValidPoint() || ( ptForePrv.m_x < UO_SIZE_X_REAL && ptFore.m_x >= UO_SIZE_X_REAL )) { // Circle the globe // Fall off edge of world ? CItem * pTiller = Multi_GetSign(); ASSERT(pTiller); pTiller->Speak( "Turbulent waters Cap'n", 0, TALKMODE_SAY, FONT_NORMAL ); // Compute the new safe place to go. (where we will not overlap) int iMaxDist = Multi_GetMaxDist(); if ( ptFore.m_x <= 0 ) { } else if ( ptFore.m_x >= UO_SIZE_X_REAL ) { } else if ( ptFore.m_y <= 0 ) { } else if ( ptFore.m_y >= UO_SIZE_Y ) { } return false; } // We should check all relevant corners. if ( ! Ship_CanMoveTo( ptFore )) { cantmove: CItem * pTiller = Multi_GetSign(); ASSERT(pTiller); pTiller->Speak( "We've stopped Cap'n", 0, TALKMODE_SAY, FONT_NORMAL ); return false; } // left side CPointMap ptTmp = m_pRegion->GetRegionCorner(GetDirTurn(dir,-1)); ptTmp.Move( dir ); ptTmp.m_z = GetTopZ(); if ( ! Ship_CanMoveTo( ptTmp )) goto cantmove; // right side. ptTmp = m_pRegion->GetRegionCorner(GetDirTurn(dir,+1)); ptTmp.Move( dir ); ptTmp.m_z = GetTopZ(); if ( ! Ship_CanMoveTo( ptTmp )) goto cantmove; Ship_MoveDelta( ptDelta ); // Move again GetTopSector()->SetSectorWakeStatus(); // may get here b4 my client does. return true; } bool CItemMulti::Ship_OnMoveTick( void ) { // We just got a move tick. // RETURN: false = delete the boat. if ( ! m_itShip.m_fSail ) // decay the ship instead ??? return( true ); // Calculate the leading point. DIR_TYPE dir = (DIR_TYPE) m_itShip.m_DirMove; if ( ! Ship_Move( dir )) { Ship_Stop(); return( true ); } SetTimeout(( m_itShip.m_fSail == 1 ) ? 1*TICK_PER_SEC : (TICK_PER_SEC/2)); return( true ); } void CItemMulti::OnHearRegion( LPCTSTR pszCmd, CChar * pSrc ) { // IT_SHIP or IT_MULTI const CItemBaseMulti * pMultiDef = Multi_GetDef(); if ( pMultiDef == NULL ) return; for ( int i=0; i<pMultiDef->m_Speech.GetCount(); i++ ) { CResourceLink * pLink = pMultiDef->m_Speech[i]; ASSERT(pLink); CResourceLock s; if ( ! pLink->ResourceLock( s )) continue; DEBUG_CHECK( pLink->HasTrigger(XTRIG_UNKNOWN)); TRIGRET_TYPE iRet = OnHearTrigger( s, pszCmd, pSrc ); if ( iRet == TRIGRET_ENDIF || iRet == TRIGRET_RET_FALSE ) continue; break; } } enum { SHV_SHIPANCHORDROP, SHV_SHIPANCHORRAISE, SHV_SHIPBACK, SHV_SHIPBACKLEFT, SHV_SHIPBACKRIGHT, SHV_SHIPDOWN, SHV_SHIPDRIFTLEFT, SHV_SHIPDRIFTRIGHT, SHV_SHIPFACE, SHV_SHIPFORE, SHV_SHIPFORELEFT, SHV_SHIPFORERIGHT, SHV_SHIPGATE, SHV_SHIPLAND, SHV_SHIPMOVE, SHV_SHIPSTOP, SHV_SHIPTURN, SHV_SHIPTURNLEFT, SHV_SHIPTURNRIGHT, SHV_SHIPUP, SHV_TAGLIST, SHV_QTY, }; LPCTSTR const CItemMulti::sm_szVerbKeys[SHV_QTY+1] = { "SHIPANCHORDROP", "SHIPANCHORRAISE", "SHIPBACK", "SHIPBACKLEFT", "SHIPBACKRIGHT", "SHIPDOWN", // down one space. "SHIPDRIFTLEFT", "SHIPDRIFTRIGHT", "SHIPFACE", // set the ships facing direction. "SHIPFORE", "SHIPFORELEFT", "SHIPFORERIGHT", "SHIPGATE", // Moves the whole ship to some new point location. "SHIPLAND", "SHIPMOVE", // move in a specified direction. "SHIPSTOP", "SHIPTURN", "SHIPTURNLEFT", "SHIPTURNRIGHT", "SHIPUP", // up one space. "TAGLIST", NULL, }; bool CItemMulti::r_GetRef( LPCTSTR & pszKey, CScriptObj * & pRef ) { // COMP(x). if ( ! strnicmp( pszKey, "COMP(", 4 )) { pszKey += 5; int i = Exp_GetVal(pszKey); SKIP_SEPERATORS(pszKey); pRef = Multi_FindItemComponent(i); return( true ); } if ( ! strnicmp( pszKey, "REGION", 6 )) { pszKey += 6; SKIP_SEPERATORS(pszKey); pRef = m_pRegion; return( true ); } return( CItem::r_GetRef( pszKey, pRef )); } void CItemMulti::r_DumpVerbKeys( CTextConsole * pSrc ) { r_DumpKeys(pSrc,sm_szVerbKeys); CItem::r_DumpVerbKeys(pSrc); } bool CItemMulti::r_Verb( CScript & s, CTextConsole * pSrc ) // Execute command from script { // Speaking in this ships region. // return: true = command for the ship. //"One (direction*)", " (Direction*), one" Moves ship one tile in desired direction and stops. //"Slow (direction*)" Moves ship slowly in desired direction (see below for possible directions). int iCmd = FindTableSorted( s.GetKey(), sm_szVerbKeys, COUNTOF( sm_szVerbKeys )-1 ); if ( iCmd < 0 ) { return( CItem::r_Verb( s, pSrc )); } if ( ! pSrc ) return( false ); if ( iCmd == SHV_TAGLIST ) { m_TagDefs.DumpKeys( pSrc, "TAG." ); return( true ); } if ( IsAttr(ATTR_MOVE_NEVER) || ! IsTopLevel()) return false; CChar * pChar = pSrc->GetChar(); // Only key holders can command the ship ??? // if ( pChar && pChar->ContentFindKeyFor( pItem )) // Find the tiller man object. CItem * pTiller = Multi_GetSign(); ASSERT( pTiller ); // Get current facing dir. DIR_TYPE DirFace = sm_Ship_FaceDir[ Ship_GetFaceOffset() ]; int DirMoveChange; LPCTSTR pszSpeak = NULL; switch ( iCmd ) { case SHV_SHIPSTOP: // "Furl sail" // "Stop" Stops current ship movement. if ( ! m_itShip.m_fSail ) return( false ); Ship_Stop(); break; case SHV_SHIPFACE: // Face this direction. do not change the direction of movement. if ( ! s.HasArgs()) return( false ); return Ship_Face( GetDirStr( s.GetArgStr())); case SHV_SHIPMOVE: // Move one space in this direction. // Does NOT protect against exploits ! if ( ! s.HasArgs()) return( false ); m_itShip.m_DirMove = GetDirStr( s.GetArgStr()); return Ship_Move( (DIR_TYPE) m_itShip.m_DirMove ); case SHV_SHIPGATE: // Move the whole ship and contents to another place. if ( ! s.HasArgs()) return( false ); { CPointMap ptdelta = g_Cfg.GetRegionPoint( s.GetArgStr()); if ( ! ptdelta.IsValidPoint()) return( false ); ptdelta -= GetTopPoint(); return Ship_MoveDelta( ptdelta ); } break; case SHV_SHIPTURNLEFT: // "Port", // "Turn Left", DirMoveChange = -2; doturn: if ( m_itShip.m_fAnchored ) { anchored: pszSpeak = "The anchor is down <SEX Sir/Mam>!"; break; } m_itShip.m_DirMove = GetDirTurn( DirFace, DirMoveChange ); Ship_Face( (DIR_TYPE) m_itShip.m_DirMove ); break; case SHV_SHIPTURNRIGHT: // "Turn Right", // "Starboard", // Turn Right DirMoveChange = 2; goto doturn; case SHV_SHIPDRIFTLEFT: // "Left", // "Drift Left", DirMoveChange = -2; dodirmovechange: if ( m_itShip.m_fAnchored ) goto anchored; if ( ! Ship_SetMoveDir( GetDirTurn( DirFace, DirMoveChange ))) return( false ); break; case SHV_SHIPDRIFTRIGHT: // "Right", // "Drift Right", DirMoveChange = 2; goto dodirmovechange; case SHV_SHIPBACK: // "Back", // Move ship backwards // "Backward", // Move ship backwards // "Backwards", // Move ship backwards DirMoveChange = 4; goto dodirmovechange; case SHV_SHIPFORE: // "Forward" // "Foreward", // Moves ship forward. // "Unfurl sail", // Moves ship forward. DirMoveChange = 0; goto dodirmovechange; case SHV_SHIPFORELEFT: // "Forward left", DirMoveChange = -1; goto dodirmovechange; case SHV_SHIPFORERIGHT: // "forward right", DirMoveChange = 1; goto dodirmovechange; case SHV_SHIPBACKLEFT: // "backward left", // "back left", DirMoveChange = -3; goto dodirmovechange; case SHV_SHIPBACKRIGHT: // "backward right", // "back right", DirMoveChange = 3; goto dodirmovechange; case SHV_SHIPANCHORRAISE: // "Raise Anchor", if ( ! m_itShip.m_fAnchored ) { pszSpeak = "The anchor is already up <SEX Sir/Mam>"; break; } m_itShip.m_fAnchored = false; break; case SHV_SHIPANCHORDROP: // "Drop Anchor", if ( m_itShip.m_fAnchored ) { pszSpeak = "The anchor is already down <SEX Sir/Mam>"; break; } m_itShip.m_fAnchored = true; Ship_Stop(); break; case SHV_SHIPTURN: // "Turn around", // Turns ship around and proceeds. // "Come about", // Turns ship around and proceeds. DirMoveChange = 4; goto doturn; case SHV_SHIPUP: // "Up" { if ( ! IsAttr(ATTR_MAGIC )) return( false ); CPointMap pt; pt.m_z = PLAYER_HEIGHT; if ( Ship_MoveDelta( pt )) { pszSpeak = "As you command <SEX Sir/Mam>"; } else { pszSpeak = "Can't do that <SEX Sir/Mam>"; } } break; case SHV_SHIPDOWN: // "Down" { if ( ! IsAttr(ATTR_MAGIC )) return( false ); CPointMap pt; pt.m_z = -PLAYER_HEIGHT; if ( Ship_MoveDelta( pt )) { pszSpeak = "As you command <SEX Sir/Mam>"; } else { pszSpeak = "Can't do that <SEX Sir/Mam>"; } } break; case SHV_SHIPLAND: // "Land" { if ( ! IsAttr(ATTR_MAGIC )) return( false ); signed char zold = GetTopZ(); CPointMap pt = GetTopPoint(); pt.m_z = zold; SetTopZ( -UO_SIZE_Z ); // bottom of the world where i won't get in the way. WORD wBlockFlags = CAN_I_WATER; signed char z = g_World.GetHeightPoint( pt, wBlockFlags ); SetTopZ( zold ); // restore z for now. pt.InitPoint(); pt.m_z = z - zold; if ( pt.m_z ) { Ship_MoveDelta( pt ); pszSpeak = "As you command <SEX Sir/Mam>"; } else { pszSpeak = "We have landed <SEX Sir/Mam>"; } } break; default: return( false ); } if ( pChar ) { if ( pszSpeak == NULL ) { static LPCTSTR const sm_pszAye[] = { "Aye", "Aye Cap'n", "Aye <SEX Sir/Mam>", }; pszSpeak = sm_pszAye[ Calc_GetRandVal( COUNTOF( sm_pszAye )) ]; } TCHAR szText[ MAX_TALK_BUFFER ]; strcpy( szText, pszSpeak ); pChar->ParseText( szText, &g_Serv ); pTiller->Speak( szText, 0, TALKMODE_SAY, FONT_NORMAL ); } return( true ); } void CItemMulti::r_DumpLoadKeys( CTextConsole * pSrc ) { CItem::r_DumpLoadKeys(pSrc); } void CItemMulti::r_Serialize( CGFile & a ) { CItem::r_Serialize(a); } void CItemMulti::r_Write( CScript & s ) { CItem::r_Write(s); m_TagDefs.r_WriteTags( s ); if ( m_pRegion ) { m_pRegion->r_WriteBody( s, "REGION." ); } } bool CItemMulti::r_WriteVal( LPCTSTR pszKey, CGString & sVal, CTextConsole * pSrc ) { if ( ! strnicmp( pszKey, "TAG.", 4 )) { pszKey += 4; sVal = m_TagDefs.GetKeyStr(pszKey); return( true ); } return( CItem::r_WriteVal(pszKey, sVal, pSrc)); } bool CItemMulti::r_LoadVal( CScript & s ) { if ( s.IsKeyHead( "REGION.", 7 )) { if ( ! IsTopLevel()) { MoveTo( GetTopPoint()); // Put item on the ground here. } ASSERT( m_pRegion ); return( m_pRegion->r_LoadVal( CScript( s.GetKey()+7, s.GetArgStr()))); } if ( s.IsKeyHead( "TAG.", 4 )) { m_TagDefs.SetStr( s.GetKey()+4, s.GetArgStr()); return( true ); } return( CItem::r_LoadVal(s)); } void CItemMulti::DupeCopy( const CItem * pItem ) { CItem::DupeCopy(pItem); const CItemMulti * pMultiItem = dynamic_cast <const CItemMulti *>(pItem); DEBUG_CHECK(pMultiItem); if ( pMultiItem == NULL ) return; m_TagDefs.Copy( &( pMultiItem->m_TagDefs )); // Region attributes ? }
[ "noreply@github.com" ]
noreply@github.com
5a3061c053e44ddd26c8204f5f87dc6a47e108f5
970e99849fb9c137888b256d28e8a2b34ddefc36
/Aula 17/include/Conta.hpp
e0f59b76695ea376a452eb6dbc50e465d8d5b3b2
[]
no_license
Gabsop/LP1
39f84df59beacf5e6b4757920c5390f05b703225
eed3f629372d224784aa6f75d31136cadddb8552
refs/heads/master
2022-11-20T16:32:39.387178
2020-07-20T18:58:25
2020-07-20T18:58:25
272,751,632
0
0
null
null
null
null
UTF-8
C++
false
false
363
hpp
#include "Cliente.hpp" #include "Agencia.hpp" using namespace std; class Conta { public: Agencia agencia; Cliente titular; int numeroConta; double saldo; static int numContas; Conta(Cliente titular); Conta(); ~Conta(); void saca(double valor); void deposita(double valor); void transfere(double valor, Conta &c); };
[ "gabsop@hotmail.com" ]
gabsop@hotmail.com
41421b8d2453e6af16d0feac8fd48d11e131a4de
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5670465267826688_0/C++/mngharbi/main.cpp
7d0c8c04bf8555ad5655397a0883bb554fe06c28
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
4,506
cpp
#include <bits/stdc++.h> #define all(c) c.begin(),c.end() #define ll long long #define ii pair <ll ,ll> #define iii pair <int, ii > #define vi vector <int> #define vii vector < ii > #define viii vector < iii > #define oo numeric_limits<ll>::max() #define mp make_pair #define pb push_back #define fi first #define se second #define MAXN 100000 using namespace std; int op (int a,int b) { if(a==-2 || b==-2) return -2; if(a==-1) { switch (b) { case -1: return 1; break; case 1: return -1; break; case 2: return 3; break; case 3: return 2; break; case 4: return 5; break; case 5: return 4; break; case 6: return 7; break; case 7: return 6; break; } } if(a==1) { return b; } if(a==2) { switch (b) { case -1: return 3; break; case 1: return 2; break; case 2: return -1; break; case 3: return 1; break; case 4: return 6; break; case 5: return 7; break; case 6: return 5; break; case 7: return 4; break; } } if(a==3) { switch (b) { case -1: return 2; break; case 1: return 3; break; case 2: return 1; break; case 3: return -1; break; case 4: return 7; break; case 5: return 6; break; case 6: return 4; break; case 7: return 5; break; } } if(a==4) { switch (b) { case -1: return 5; break; case 1: return 4; break; case 2: return 7; break; case 3: return 6; break; case 4: return -1; break; case 5: return 1; break; case 6: return 2; break; case 7: return 3; break; } } if(a==5) { switch (b) { case -1: return 4; break; case 1: return 5; break; case 2: return 6; break; case 3: return 7; break; case 4: return 1; break; case 5: return -1; break; case 6: return 3; break; case 7: return 2; break; } } if(a==6) { switch (b) { case -1: return 7; break; case 1: return 6; break; case 2: return 4; break; case 3: return 5; break; case 4: return 3; break; case 5: return 2; break; case 6: return -1; break; case 7: return 1; break; } } if(a==7) { switch (b) { case -1: return 6; break; case 1: return 7; break; case 2: return 5; break; case 3: return 4; break; case 4: return 2; break; case 5: return 3; break; case 6: return 1; break; case 7: return -1; break; } } } int V[10000]; int R[10000][10000]; int main() { freopen("input.in","r+",stdin); freopen("output.txt","w+",stdout); ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int T,L,X,k; char c; cin >> T; for(int t=1;t<=T;t++) { cin >> L >> X; for(int i=0;i<L;i++) { cin >> c; switch(c) { case 'i':k=2;break; case 'j':k=4;break; case 'k':k=6;break; } V[i] = k; } for(int i=1;i<X;i++) for(int j=0;j<L;j++) V[i*L+j] = V[j]; memset(R,-2,sizeof(R)); R[0][0] = V[0]; for(int i=1;i<L*X;i++) { R[i][i] = V[i]; for(int j=0;j<i;j++) { R[j][i] = op(R[j][i-1],V[i]); } } bool found = false; for(int a=0;a<L*X-2;a++) { int first = R[0][a]; for(int b=a+1;b<L*X-1;b++) { int second = R[a+1][b]; int third = R[b+1][L*X-1]; if(first == 2 && second == 4 && third == 6) { found = true; break; } } if(found) break; } cout << "Case #" << t << ": "; if(found) cout << "YES"; else cout << "NO"; cout << endl; } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
b28a91be08b5d7193d78a4ad134a49d509e82206
39da69ff48d35fffd70c92c20e6a71ca780c5ba0
/Support/FMTemplate/FMTemplate.cpp
29dd6aae5017bb56b845e3213632c5035f0b2a9e
[]
no_license
soliantconsulting/fm-lua
fcd430f5d099137860d03cd546c82ad2c3306823
a81c59a312406acc1d4789c46dadcee179fddbd3
refs/heads/master
2021-03-12T22:09:16.133664
2012-02-28T02:38:53
2012-02-28T02:38:53
3,159,220
3
1
null
null
null
null
WINDOWS-1252
C++
false
false
13,448
cpp
////////////////////////////////////////////////////////////////////////////////////// // // FMTemplate.cpp - Main entry point and underlying code for 24U Plug-In Template // // Version 3.0, Copyright ©2002-2010 by 24U Software. All rights reserved. // // Written by Tomas Zahradnicky, HOnza Koudelka, and Josef Andrysek // //////////////////////////////////////////////////////////////////////////////// // // The latest version of 24U Plug-In Template is available for download from: // // http://www.24uSoftware.com/PlugInTemplate // //////////////////////////////////////////////////////////////////////////////// // // 24U Sample Code - Terms of use // // Under the terms of the 24U Software License Agreement, 24U s.r.o. grants // you a non-exclusive royalty-free Developer License (3.2) to use 24U Plug-In // Template solely to compile plug-ins for use with FileMaker products. // // Redistribution of 24U Sample Code in the source form, as part of // an open-source plug-in project is permitted provided that the following // conditions are met: // // * Redistributions of source code must retain the copyright notice, the terms // of use, and the "24U Software License Agreement" document. // // * We require that you make it clear in the source wherever modified that the // code was descended from 24U Sample Code, but that you've made changes. // // See the "License.txt" and "24U Software License Agreement.pdf" files // for detailed terms of use and licensing conditions. // //////////////////////////////////////////////////////////////////////// // // This source file was derived from FileMaker template plug-in provided // by FileMaker, Inc. as a part of FileMaker Developer. // //////////////////////////////////////////////////////////////////////////////// // // Use this file as a part of all compiled parts of your plug-in. // Without this file your own code will never get called by FileMaker as it // contains the key routines which connect the FileMaker API to your code. // //////////////////////////////////////////////////////////////////////////////// // FMTConfig.h is required somewhere as it configures the FM Template #include "FMTConfig.h" #include "FMTemplate/FMTemplate.h" #if FMX_WIN_TARGET #include <Windows.h> #endif #define if_error( cond, label ) if(cond) goto label // ====== Forward Declaration ============================================================================== static FMX_Long Do_PluginInit(FMX_Short version); static void Do_PluginShutdown(void); #if WANT_IDLE static void Do_PluginIdle(FMX_IdleLevel idleLevel); #endif //WANT_IDLE #if WANT_PREFERENCES static void Do_PluginPrefs(); #endif //WANT_PREFERENCES static void Do_PluginGetString(); static void ProvideConfigString( FMX_UniChar* ioBuffer, FMX_ULong iBufferSize ); static void ProvideNameString( FMX_UniChar* ioBuffer, FMX_ULong iBufferSize ); static void ProvidePreferencesString( FMX_UniChar* ioBuffer, FMX_ULong iBufferSize ); FMX_Boolean RegisterExternalFunctions(); void UnRegisterExternalFunctions(); // ====== Global Variables ================================================================================= FMX_ExternCallPtr gFMX_ExternCallPtr=NULL; FMX_Boolean gPlugInInitialized=0; FMX_Boolean gPrefsOpen=0; void FMX_ENTRYPT FMExternCallProc(FMX_ExternCallPtr pb) { // Setup global defined in FMxExtern.h gFMX_ExternCallPtr = pb; // Message dispatcher switch (gFMX_ExternCallPtr->whichCall) { case kFMXT_Init: gFMX_ExternCallPtr->result = Do_PluginInit(gFMX_ExternCallPtr->extnVersion); break; case kFMXT_Shutdown: Do_PluginShutdown(); break; case kFMXT_GetString: Do_PluginGetString(); break; #if WANT_IDLE case kFMXT_Idle: Do_PluginIdle(gFMX_ExternCallPtr->parm1); break; #endif //WANT_IDLE #if WANT_PREFERENCES case kFMXT_DoAppPreferences: Do_PluginPrefs(); break; #endif //WANT_PREFERENCES };// switch whichCall } // FMExternCallProc // ====== Handlers ========================================================================================= static FMX_Long Do_PluginInit(FMX_Short version) { // Check the app API version if ((version < k70ExtnVersion) || (version > kMaxExtnVersion)) { // This version of FileMaker is not supported; let FileMaker disable this // plug-in and report the problem to the user. return (kBadExtnVersion); } if( Startup() ) { if( RegisterExternalFunctions() ) { gPlugInInitialized = 1; return kCurrentExtnVersion; } else Shutdown(); } return kDoNotEnable; } // Do_PluginInit static void Do_PluginShutdown(void) { gPlugInInitialized = 0; UnRegisterExternalFunctions(); Shutdown(); } // Do_PluginShutdown #if WANT_IDLE void Do_PluginIdle(FMX_IdleLevel idleLevel) { // eliminate the race condition we would be called when Startup is not yet done! if( gPlugInInitialized ) { if( idleLevel == kFMXT_UserIdle ) SafeIdle(); else if ( idleLevel == kFMXT_Unsafe) UnsafeIdle(); else SemiSafeIdle(idleLevel); } } // Do_PluginIdle #endif //WANT_IDLE #if WANT_PREFERENCES static void Do_PluginPrefs() { // Avoid opening multiple instances of the preferences dialog if (!gPrefsOpen) { gPrefsOpen = 1; Preferences(); gPrefsOpen = 0; } } #endif //WANT_PREFERENCES static void Do_PluginGetString() { FMX_Strings stringType = gFMX_ExternCallPtr->parm1; // FMX_ULong windowsLanguageID = gFMX_ExternCallPtr->parm2; FMX_ULong outStringBufferSize = gFMX_ExternCallPtr->parm3; FMX_Unichar* outStringBuffer = (FMX_Unichar*)(gFMX_ExternCallPtr->result); switch( stringType ) { case kFMXT_OptionsStr: ProvideConfigString(outStringBuffer,outStringBufferSize); break; case kFMXT_NameStr: ProvideNameString(outStringBuffer,outStringBufferSize); break; case kFMXT_AppConfigStr: ProvidePreferencesString(outStringBuffer,outStringBufferSize); break; } } #if FMX_WIN_TARGET HINSTANCE GetPluginInstance() { return (HINSTANCE)gFMX_ExternCallPtr->instanceID; } #endif #if FMX_MAC_TARGET CFBundleRef GetPluginBundle() { return (CFBundleRef)gFMX_ExternCallPtr->instanceID; } #endif void ProvideConfigString( FMX_UniChar* ioBuffer, FMX_ULong iBufferSize ) { #pragma unused(iBufferSize) // Provide plug-in config string here. ioBuffer[ 0] = ((unsigned char*)PLUGIN_ID_STRING)[0]; ioBuffer[ 1] = ((unsigned char*)PLUGIN_ID_STRING)[1]; ioBuffer[ 2] = ((unsigned char*)PLUGIN_ID_STRING)[2]; ioBuffer[ 3] = ((unsigned char*)PLUGIN_ID_STRING)[3]; ioBuffer[ 4] = '1'; #if WANT_PREFERENCES ioBuffer[ 5] = 'Y'; #else ioBuffer[ 5] = 'n'; #endif ioBuffer[ 6] = 'n'; ioBuffer[ 7] = 'Y'; #if WANT_IDLE ioBuffer[ 8] = 'Y'; #else ioBuffer[ 8] = 'n'; #endif ioBuffer[ 9] = 'n'; ioBuffer[10] = 'n'; ioBuffer[11] = 0; } void ProvideNameString( FMX_Unichar* ioBuffer, FMX_ULong iBufferSize ) { // Provide plug-in name string here. ReadString( ioBuffer, iBufferSize, PLUGIN_NAME_ID ); } void ProvidePreferencesString( FMX_Unichar* ioBuffer, FMX_ULong iBufferSize ) { // Provide plug-in name string here. ReadString( ioBuffer, iBufferSize, PLUGIN_PREFERENCES_ID ); } FMX_Boolean RegisterExternalFunctions() { // if enable = FALSE is returned, Shutdown will // be called and plug-in will not be activated. FMX_Boolean enable = FALSE; // Register plug-in functions fmx::errcode err; #ifdef FUNCTION_1_C_NAME fmx::ulong regFunction1Flags = 0 | FUNCTION_1_FLAGS; #endif #ifdef FUNCTION_2_C_NAME fmx::ulong regFunction2Flags = 0 | FUNCTION_2_FLAGS; #endif #ifdef FUNCTION_3_C_NAME fmx::ulong regFunction3Flags = 0 | FUNCTION_3_FLAGS; #endif #ifdef FUNCTION_4_C_NAME fmx::ulong regFunction4Flags = 0 | FUNCTION_4_FLAGS; #endif #ifdef FUNCTION_5_C_NAME fmx::ulong regFunction5Flags = 0 | FUNCTION_5_FLAGS; #endif #ifdef FUNCTION_6_C_NAME fmx::ulong regFunction6Flags = 0 | FUNCTION_6_FLAGS; #endif #ifdef FUNCTION_7_C_NAME fmx::ulong regFunction7Flags = 0 | FUNCTION_7_FLAGS; #endif #ifdef FUNCTION_8_C_NAME fmx::ulong regFunction8Flags = 0 | FUNCTION_8_FLAGS; #endif #ifdef FUNCTION_9_C_NAME fmx::ulong regFunction9Flags = 0 | FUNCTION_9_FLAGS; #endif #ifdef FUNCTION_10_C_NAME fmx::ulong regFunction10Flags = 0 | FUNCTION_10_FLAGS; #endif #ifdef FUNCTION_1_C_NAME err = RegisterExternalFunction( 1, FUNCTION_1_PARAMS, regFunction1Flags, FUNCTION_1_C_NAME ); if_error(err,bail); #endif #ifdef FUNCTION_2_C_NAME err = RegisterExternalFunction( 2, FUNCTION_2_PARAMS, regFunction2Flags, FUNCTION_2_C_NAME ); if_error(err,bail1); #endif #ifdef FUNCTION_3_C_NAME err = RegisterExternalFunction( 3, FUNCTION_3_PARAMS, regFunction3Flags, FUNCTION_3_C_NAME ); if_error(err,bail2); #endif #ifdef FUNCTION_4_C_NAME err = RegisterExternalFunction( 4, FUNCTION_4_PARAMS, regFunction4Flags, FUNCTION_4_C_NAME ); if_error(err,bail3); #endif #ifdef FUNCTION_5_C_NAME err = RegisterExternalFunction( 5, FUNCTION_5_PARAMS, regFunction5Flags, FUNCTION_5_C_NAME ); if_error(err,bail4); #endif #ifdef FUNCTION_6_C_NAME err = RegisterExternalFunction( 6, FUNCTION_6_PARAMS, regFunction6Flags, FUNCTION_6_C_NAME ); if_error(err,bail5); #endif #ifdef FUNCTION_7_C_NAME err = RegisterExternalFunction( 7, FUNCTION_7_PARAMS, regFunction7Flags, FUNCTION_7_C_NAME ); if_error(err,bail6); #endif #ifdef FUNCTION_8_C_NAME err = RegisterExternalFunction( 8, FUNCTION_8_PARAMS, regFunction8Flags, FUNCTION_8_C_NAME ); if_error(err,bail7); #endif #ifdef FUNCTION_9_C_NAME err = RegisterExternalFunction( 9, FUNCTION_9_PARAMS, regFunction9Flags, FUNCTION_9_C_NAME ); if_error(err,bail8); #endif #ifdef FUNCTION_10_C_NAME err = RegisterExternalFunction( 10, FUNCTION_10_PARAMS, regFunction10Flags, FUNCTION_10_C_NAME ); if_error(err,bail9); #endif //#ifdef FUNCTION_11_C_NAME //err = RegisterExternalFunction( 11, FUNCTION_11_PARAMS, regFunction11Flags, FUNCTION_11_C_NAME ); //if_error(err,bail10); //#endif //... enable = TRUE; goto bail; //... #ifdef FUNCTION_10_C_NAME //bail10: UnRegisterExternalFunction( 10 ); bail9: #endif #ifdef FUNCTION_9_C_NAME UnRegisterExternalFunction( 9 ); bail8: #endif #ifdef FUNCTION_8_C_NAME UnRegisterExternalFunction( 8 ); bail7: #endif #ifdef FUNCTION_7_C_NAME UnRegisterExternalFunction( 7 ); bail6: #endif #ifdef FUNCTION_6_C_NAME UnRegisterExternalFunction( 6 ); bail5: #endif #ifdef FUNCTION_5_C_NAME UnRegisterExternalFunction( 5 ); bail4: #endif #ifdef FUNCTION_4_C_NAME UnRegisterExternalFunction( 4 ); bail3: #endif #ifdef FUNCTION_3_C_NAME UnRegisterExternalFunction( 3 ); bail2: #endif #ifdef FUNCTION_2_C_NAME UnRegisterExternalFunction( 2 ); bail1: #endif #ifdef FUNCTION_1_C_NAME UnRegisterExternalFunction( 1 ); #endif bail: return enable; } void UnRegisterExternalFunctions() { // Unregister plug-in functions fmx::QuadCharAutoPtr pluginID(PLUGIN_ID_STRING[0], PLUGIN_ID_STRING[1], PLUGIN_ID_STRING[2], PLUGIN_ID_STRING[3]); #ifdef FUNCTION_10_C_NAME (void) fmx::ExprEnv::UnRegisterExternalFunction(*pluginID, 10 ); #endif #ifdef FUNCTION_9_C_NAME (void) fmx::ExprEnv::UnRegisterExternalFunction(*pluginID, 9 ); #endif #ifdef FUNCTION_8_C_NAME (void) fmx::ExprEnv::UnRegisterExternalFunction(*pluginID, 8 ); #endif #ifdef FUNCTION_7_C_NAME (void) fmx::ExprEnv::UnRegisterExternalFunction(*pluginID, 7 ); #endif #ifdef FUNCTION_6_C_NAME (void) fmx::ExprEnv::UnRegisterExternalFunction(*pluginID, 6 ); #endif #ifdef FUNCTION_5_C_NAME (void) fmx::ExprEnv::UnRegisterExternalFunction(*pluginID, 5 ); #endif #ifdef FUNCTION_4_C_NAME (void) fmx::ExprEnv::UnRegisterExternalFunction(*pluginID, 4 ); #endif #ifdef FUNCTION_3_C_NAME (void) fmx::ExprEnv::UnRegisterExternalFunction(*pluginID, 3 ); #endif #ifdef FUNCTION_2_C_NAME (void) fmx::ExprEnv::UnRegisterExternalFunction(*pluginID, 2 ); #endif #ifdef FUNCTION_1_C_NAME (void) fmx::ExprEnv::UnRegisterExternalFunction(*pluginID, 1 ); #endif }
[ "lart2150@gmail.com" ]
lart2150@gmail.com
093058d30beaaf1c9244fbe4a3e5c0171ca5272f
94bd295572de3f4934a3896ce1bb882fb4d35edc
/ios/chrome/browser/payments/payment_request.h
a0d32d00a2f6d6472a64a052a5ffa031cd012c0a
[ "BSD-3-Clause" ]
permissive
WebGameLinux/chromium
06109b62d6019b051474cd479f3d577e0eec4463
a35a1e2ce2ab74eccc467aa390eda1a8e29e3e09
refs/heads/master
2023-03-07T14:07:56.342758
2017-04-08T02:33:08
2017-04-08T03:38:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,092
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_PAYMENTS_PAYMENT_REQUEST_H_ #define IOS_CHROME_BROWSER_PAYMENTS_PAYMENT_REQUEST_H_ #include <set> #include <vector> #include "base/macros.h" #include "ios/web/public/payments/payment_request.h" namespace autofill { class AutofillProfile; class CreditCard; class PersonalDataManager; } // namespace autofill namespace payments { class CurrencyFormatter; } // namespace payments // Has a copy of web::PaymentRequest as provided by the page invoking the // PaymentRequest API. Also caches credit cards and addresses provided by the // |personal_data_manager| and manages shared resources and user selections for // the current PaymentRequest flow. It must be initialized with a non-null // instance of |personal_data_manager| that outlives this class. class PaymentRequest { public: // |personal_data_manager| should not be null and should outlive this object. PaymentRequest(const web::PaymentRequest& web_payment_request, autofill::PersonalDataManager* personal_data_manager); ~PaymentRequest(); autofill::PersonalDataManager* GetPersonalDataManager() const { return personal_data_manager_; } // Returns the payment details from |web_payment_request_|. const web::PaymentDetails& payment_details() const { return web_payment_request_.details; } // Returns the payment options from |web_payment_request_|. const web::PaymentOptions& payment_options() const { return web_payment_request_.options; } // Updates the payment details of the |web_payment_request_|. It also updates // the cached references to the shipping options in |web_payment_request_| as // well as the reference to the selected shipping option. void set_payment_details(const web::PaymentDetails& details); // Returns the payments::CurrencyFormatter instance for this PaymentRequest. // Note: Having multiple currencies per PaymentRequest flow is not supported; // hence the CurrencyFormatter is cached here. payments::CurrencyFormatter* GetOrCreateCurrencyFormatter(); // Returns the available autofill profiles for this user to be used as // shipping profiles. const std::vector<autofill::AutofillProfile*>& shipping_profiles() const { return shipping_profiles_; } // Returns the currently selected shipping profile for this PaymentRequest // flow if there is one. Returns nullptr if there is no selected profile. autofill::AutofillProfile* selected_shipping_profile() const { return selected_shipping_profile_; } // Sets the currently selected shipping profile for this PaymentRequest flow. void set_selected_shipping_profile(autofill::AutofillProfile* profile) { selected_shipping_profile_ = profile; } // Returns the available autofill profiles for this user to be used as // contact profiles. const std::vector<autofill::AutofillProfile*>& contact_profiles() const { return contact_profiles_; } // Returns the currently selected contact profile for this PaymentRequest // flow if there is one. Returns nullptr if there is no selected profile. autofill::AutofillProfile* selected_contact_profile() const { return selected_contact_profile_; } // Sets the currently selected contact profile for this PaymentRequest flow. void set_selected_contact_profile(autofill::AutofillProfile* profile) { selected_contact_profile_ = profile; } // Returns the available autofill profiles for this user to be used as // billing profiles. const std::vector<autofill::AutofillProfile*>& billing_profiles() const { return shipping_profiles_; } const std::vector<std::string>& supported_card_networks() const { return supported_card_networks_; } const std::set<std::string>& basic_card_specified_networks() const { return basic_card_specified_networks_; } // Adds |credit_card| to the list of cached credit cards and returns a pointer // to the cached copy. virtual autofill::CreditCard* AddCreditCard( const autofill::CreditCard& credit_card); // Returns the available autofill credit cards for this user that match a // supported type specified in |web_payment_request_|. const std::vector<autofill::CreditCard*>& credit_cards() const { return credit_cards_; } // Returns the currently selected credit card for this PaymentRequest flow if // there is one. Returns nullptr if there is no selected credit card. autofill::CreditCard* selected_credit_card() const { return selected_credit_card_; } // Sets the currently selected credit card for this PaymentRequest flow. void set_selected_credit_card(autofill::CreditCard* credit_card) { selected_credit_card_ = credit_card; } // Returns the available shipping options from |web_payment_request_|. const std::vector<web::PaymentShippingOption*>& shipping_options() const { return shipping_options_; } // Returns the selected shipping option from |web_payment_request_| if there // is one. Returns nullptr otherwise. web::PaymentShippingOption* selected_shipping_option() const { return selected_shipping_option_; } private: // Fetches the autofill profiles for this user from the PersonalDataManager, // and stores copies of them, owned by this PaymentRequest, in profile_cache_. void PopulateProfileCache(); // Fetches the autofill credit cards for this user from the // PersonalDataManager that match a supported type specified in // |web_payment_request_| and stores copies of them, owned by this // PaymentRequest, in credit_card_cache_. void PopulateCreditCardCache(); // Stores references to the shipping options in |web_payment_request_|. void PopulateShippingOptionCache(); // The web::PaymentRequest object as provided by the page invoking the Payment // Request API, owned by this object. web::PaymentRequest web_payment_request_; // Never null and outlives this object. autofill::PersonalDataManager* personal_data_manager_; // The currency formatter instance for this PaymentRequest flow. std::unique_ptr<payments::CurrencyFormatter> currency_formatter_; // Profiles returned by the Data Manager may change due to (e.g.) sync events, // meaning PaymentRequest may outlive them. Therefore, profiles are fetched // once and their copies are cached here. Whenever profiles are requested a // vector of pointers to these copies are returned. std::vector<autofill::AutofillProfile> profile_cache_; std::vector<autofill::AutofillProfile*> shipping_profiles_; autofill::AutofillProfile* selected_shipping_profile_; std::vector<autofill::AutofillProfile*> contact_profiles_; autofill::AutofillProfile* selected_contact_profile_; // Credit cards returnd by the Data Manager may change due to (e.g.) // sync events, meaning PaymentRequest may outlive them. Therefore, credit // cards are fetched once and their copies are cached here. Whenever credit // cards are requested a vector of pointers to these copies are returned. std::vector<autofill::CreditCard> credit_card_cache_; std::vector<autofill::CreditCard*> credit_cards_; autofill::CreditCard* selected_credit_card_; // A vector of supported basic card networks. This encompasses everything that // the merchant supports and should be used for support checks. std::vector<std::string> supported_card_networks_; // A subset of |supported_card_networks_| which is only the networks that have // been specified as part of the "basic-card" supported method. Callers should // use |supported_card_networks_| for merchant support checks. std::set<std::string> basic_card_specified_networks_; // A vector of pointers to the shipping options in |web_payment_request_|. std::vector<web::PaymentShippingOption*> shipping_options_; web::PaymentShippingOption* selected_shipping_option_; DISALLOW_COPY_AND_ASSIGN(PaymentRequest); }; #endif // IOS_CHROME_BROWSER_PAYMENTS_PAYMENT_REQUEST_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
397ddb32ee529dacfbb33bffe1cb29087dc47309
edb5695d72bba6cfb6c84853b3381d0fb3d1fda6
/include/learnopengl/elements.h
343e2f02f77d2e39c2ba464816b2acb8ffc78c07
[]
no_license
LeDaVR/project
96b39fc8400a124ab376d5da6dbb1756fc828e53
82d6b3101347f9ee47815f029128f47c010831f2
refs/heads/master
2020-05-28T04:22:52.254609
2019-06-25T00:22:45
2019-06-25T00:22:45
188,878,485
0
0
null
null
null
null
UTF-8
C++
false
false
1,053
h
#ifndef ELEMENTS_H #define ELEMENTS_H #include <learnopengl/dinamicarray.h> #include <learnopengl/model.h> #include <vector> #include <string> class Elements { protected: Elements(); Model model; int elementID; std::string info; public: virtual Model* getModel() { return NULL; } int getSizeData(); virtual std::string getInfo(); //~Elements(){} }; /*class Units : public Elements { }; class Edificios : public Elements{ void setID(); public: std::string getInfo(); }; */ class Resources : public Elements { protected: virtual Model* getModel() { return NULL; } virtual std::string getInfo(); }; class CampodeLino : public Resources { public: CampodeLino(); }; class Mina : public Resources { public: Mina(); }; class Arbol : public Resources { public: Arbol(); Model* getModel() { return &model; }; }; /* class Decorate_Elements : public Elements{ public: std::string getInfo(); };*/ struct ElementData { Arbol arbol; std::vector<Elements> data; public: ElementData(); Elements* Begin(); }; #endif
[ "danielvaldiviaramos@hotmail.com" ]
danielvaldiviaramos@hotmail.com
546ce076fceea9860fb266d333071a1032e1b3f3
74c5e311c72185e9e83f0dde18311700cf5b0e2f
/tests/test_main.cpp
d4e8fe683b4e7aeb2263705726bb0e52db26ef28
[ "Zlib" ]
permissive
wps1215/hzr
7c09cc44e503300988b1ebfc0ab8826c54178ed0
ef77444e2247204dfa046d64d25ba964a98ae378
refs/heads/master
2020-11-29T17:23:07.399812
2019-01-17T10:39:47
2019-01-17T10:39:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,290
cpp
//------------------------------------------------------------------------------ // hzr - A Huffman + RLE compression library. // // Copyright (C) 2016 Marcus Geelnard // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the // use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software in // a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. //------------------------------------------------------------------------------ // NOTE: This defines the main() function for any Catch based test executable, // along with the Catch test framework. #define CATCH_CONFIG_MAIN #include <catch.hpp>
[ "m@bitsnbites.eu" ]
m@bitsnbites.eu
536dba47ba3d05878357f91c07f3570a43a0787c
f72c28bc560346b36f30842c88a60e071d2bab9a
/GameCleint_Console/NetGameClient/NetGameClient/Client.cpp
c9cb5e5209c837cf60b7f504bc5dd91a9820e807
[]
no_license
TylerStein/NetGame
b1e71e7fd2fd776e891bb1311cc998cdc4b8ba17
aa36bfccba0a16a9922fd766346caae5ce3a0489
refs/heads/master
2020-05-05T08:05:54.182892
2019-04-06T15:26:29
2019-04-06T15:26:29
179,850,353
0
0
null
null
null
null
UTF-8
C++
false
false
5,553
cpp
#include "pch.h" #include "Client.h" #include <WinSock2.h> #include <WS2tcpip.h> #include <stdio.h> #pragma comment(lib, "Ws2_32.lib") Client::Client(const char* client_id, const char* server_ip, const char* port) { m_client_id = client_id; m_server_ip = server_ip; m_port = port; m_message_queue = new std::queue<std::string>(); m_async_message_handler.keep_open = false; m_async_message_handler.pending_queue = std::queue<std::string>(); m_async_message_handler.pending_queue_busy = false; WSADATA wsaData; int result; result = WSAStartup(MAKEWORD(2, 2), &wsaData); if (result != 0) { std::string reason = std::string("WSA Startup Failed: " + result); throw new ClientException(reason.c_str(), m_client_id, m_server_ip, m_port); } ZeroMemory(&m_hints, sizeof(m_hints)); m_hints.ai_family = AF_UNSPEC; m_hints.ai_socktype = SOCK_STREAM; m_hints.ai_protocol = IPPROTO_TCP; result = getaddrinfo(m_server_ip, m_port, &m_hints, &m_result); if (result != 0) { WSACleanup(); std::string reason = std::string("GetAddrInfo Failed: " + result); throw new ClientException(reason.c_str(), m_client_id, m_server_ip, m_port); } m_addr_ptr = m_result; m_connect_socket = socket(m_addr_ptr->ai_family, m_addr_ptr->ai_socktype, m_addr_ptr->ai_protocol); if (m_connect_socket == INVALID_SOCKET) { freeaddrinfo(m_result); WSACleanup(); std::string reason = std::string("Error at Socket(): " + WSAGetLastError()); throw new ClientException(reason.c_str(), m_client_id, m_server_ip, m_port); } result = connect(m_connect_socket, m_addr_ptr->ai_addr, (int)m_addr_ptr->ai_addrlen); if (result == SOCKET_ERROR) { closesocket(m_connect_socket); m_connect_socket = INVALID_SOCKET; } freeaddrinfo(m_result); if (m_connect_socket == INVALID_SOCKET) { WSACleanup(); throw new ClientException("Unable to connect to server!", m_client_id, m_server_ip, m_port); } m_async_message_handler.connect_socket = m_connect_socket; } Client::~Client() { m_client_id = nullptr; m_server_ip = nullptr; delete m_message_queue; WSACleanup(); m_port = nullptr; m_result = nullptr; m_addr_ptr = nullptr; } void Client::Send(const char* buffer) const { int result; result = send(m_connect_socket, buffer, (int)strlen(buffer), 0); if (result == SOCKET_ERROR) { closesocket(m_connect_socket); WSACleanup(); throw new ClientException(std::string("Send Failed: " + WSAGetLastError()).c_str(), m_client_id, m_server_ip, m_port); } } void Client::Receive() { if (m_async_message_handler.keep_open) { if (m_async_message_handler.pending_queue_busy == false) { m_async_message_handler.pending_queue_busy = true; while (m_async_message_handler.pending_queue.empty() == false) { std::string last = m_async_message_handler.pending_queue.front(); m_async_message_handler.pending_queue.pop(); m_message_queue->push(last); } m_async_message_handler.pending_queue_busy = false; } else { printf("Receive() Pendique Queue Busy"); } } } DWORD WINAPI receive_old(LPVOID lpParameter) { AsyncMessageHandler& handler = *((AsyncMessageHandler*)lpParameter); unsigned int counter = 0; do { if (handler.pending_queue_busy == false) { handler.pending_queue_busy = true; handler.pending_queue.push("HELLO NO." + std::to_string(counter)); handler.pending_queue_busy = false; if (counter < 0xFFFFFFFF) counter++; } else { printf("async receive(): Pending queue busy, retrying in 100ms"); } Sleep(100); } while (handler.keep_open); return 0; } DWORD WINAPI receive(LPVOID lpParameter) { AsyncMessageHandler& handler = *((AsyncMessageHandler*)lpParameter); int result; int recvbuflen = DEFAULT_BUFLEN; char recvbuf[DEFAULT_BUFLEN]; std::queue<std::string> backfill = std::queue<std::string>(); do { result = recv(handler.connect_socket, recvbuf, recvbuflen, 0); if (result > 0) { std::string readable = std::string(recvbuf).substr(0, result); if (handler.pending_queue_busy == false) { handler.pending_queue_busy = true; handler.pending_queue.push(readable); while (backfill.empty() == false) { handler.pending_queue.push(backfill.front()); backfill.pop(); } handler.pending_queue_busy = false; } else { backfill.push(readable); } } else if (result == 0) { printf("connection closed\n"); } else { printf("recv failed %d\n", WSAGetLastError()); } } while (result > 0 && handler.keep_open); handler.keep_open = false; return 0; } void Client::BeginReceive() { if (m_async_message_handler.keep_open == true) return; if (m_recv_handle != NULL) CloseHandle(m_recv_handle); m_async_message_handler.keep_open = true; m_recv_handle = CreateThread(0, 0, receive, &m_async_message_handler, 0, &m_recv_id); } void Client::EndReceive() { if (m_async_message_handler.keep_open == false) return; m_async_message_handler.keep_open = false; } void Client::Shutdown() const { int result = shutdown(m_connect_socket, SD_SEND); if (result == SOCKET_ERROR) { closesocket(m_connect_socket); WSACleanup(); throw new ClientException(std::string("Shutdown failed: " + WSAGetLastError()).c_str(), m_client_id, m_server_ip, m_port); } } bool Client::HasMessage() const { return (m_message_queue->empty() == false); } std::string Client::PopMessage() const { if (HasMessage() == false) { throw new ClientException("No more messages in the queue", m_client_id, m_server_ip, m_port); } std::string message = m_message_queue->front(); m_message_queue->pop(); return message; }
[ "tyler.stein1@yahoo.ca" ]
tyler.stein1@yahoo.ca
b4da81646c14714f160ebddaf6926c9f9a74456f
e3b7c398b565c396c8063157711ef9bca0bc112f
/9/autologin.cpp
826e683ecd229bd482d0cd9f23074a260cd39150
[]
no_license
blank-black/network-shenjian
62f38dcc42ce79d92d087b5810ce5996a8ebdb8a
9c390928c5b8c30f10ba78e3f6ae18523cd8b9ab
refs/heads/master
2021-08-30T19:43:03.788278
2017-12-19T07:10:57
2017-12-19T07:10:57
104,866,614
7
0
null
null
null
null
UTF-8
C++
false
false
6,554
cpp
#include <iostream> #include <fstream> #include <unistd.h> #include <sys/types.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <signal.h> #include <arpa/inet.h> #include <time.h> using namespace std; #define LEN 30000 #define port 80 #define IP "192.168.192.17" int retry = 0; //状态请求 char request_status[]="GET /srun_portal_pc_succeed.php HTTP/1.1\r\n\ Host: 192.168.192.18\r\n\ Connection: keep-alive\r\n\ Cache-Control: max-age=0\r\n\ User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36\r\n\ Upgrade-Insecure-Requests: 1\r\n\ Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n\ Accept-Encoding: gzip, deflate\r\n\ Accept-Language: zh-CN,zh;q=0.9,en;q=0.8\r\n\ \r\n"; //退出请求 char request_out[2048]; void set_request_out(const char username[]) { char buffer[1024] = { 0 }; sprintf(buffer, "action=auto_logout&info=&user_ip=10.22.241.253&username=1551265"); int len = strlen(buffer); sprintf(request_out, "POST http://192.168.192.18/srun_portal_pc_succeed.php HTTP/1.1\r\n\ Host: 192.168.192.18\r\n\ Connection: keep-alive\r\n\ Content-Length: %u\r\n\ Cache-Control: max-age=0\r\n\ Origin: http://192.168.192.18\r\n\ Upgrade-Insecure-Requests: 1\r\n\ Content-Type: application/x-www-form-urlencoded\r\n\ User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36\r\n\ Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image,/webp,image/apng,*/*;q=0.8\r\n\ Referer: http://192.168.192.18/srun_portal_pc_succeed.php\r\n\ Accept-Encoding: gzip, deflate\r\n\ Accept-Language: zh-CN,zh;q=0.9\r\n\ \r\n\ action=auto_logout&info=&user_ip=10.22.241.253&username=1551265", len); } //登录请求 char request_in[2048]; void set_request_in(const char username[], const char password[]) { char buffer[1024] = { 0 }; sprintf(buffer, "action=login&username=151265&password={B}MTU5MzU3&ac_id=7&user_ip=10.22.241.253&nas_ip=&user_mac=&save_me=1&ajax=1"); int len = strlen(buffer); sprintf(request_in, "POST http://192.168.192.18/include/auth_action.php HTTP/1.1\r\n\ Host: 192.168.192.18\r\n\ Connection: keep-alive\r\n\ Content-Length: %u\r\n\ Accept: */*\r\n\ Origin: http://192.168.192.18\r\n\ X-Requested-With: XMLHttpRequest\r\n\ User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36\r\n\ Content-Type: application/x-www-form-urlencoded\r\n\ Referer: http://192.168.192.18/srun_portal_pc.php?ac_id=7&userip=10.22.241.253&uservlan=600&userurl=http://www.msftconnecttest.com/redirect\r\n\ Accept-Encoding: gzip, deflate\r\n\ Accept-Language: zh-CN,zh;q=0.9\r\n\ \r\n\ action=login&username=1551265&password={B}MTU5MzU3&ac_id=7&user_ip=10.22.241.253&nas_ip=&user_mac=&save_me=1&ajax=1", len); } //获取当前时间 int connect() { int sockfd; struct sockaddr_in serv_addr; char time[20]; //建立socket if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { cout << "socket error" << endl; exit(1); } memset(&serv_addr, 0, sizeof(serv_addr)); //每个字节都用0填充 serv_addr.sin_family = AF_INET; //使用IPv4地址 serv_addr.sin_addr.s_addr = inet_addr(IP); serv_addr.sin_port = htons(port); get_time(time); cout << time << " connecting..." << endl; sleep(1); char choice; while (1) { if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) < 0) { get_time(time); cout << time << " connect error" << endl; sleep(retry); } else { get_time(time); cout << time << " connect success" << endl; break; } } return sockfd; } int if_login(int sockfd) { fd_set rfds, wfds, master; int maxfd = sockfd; FD_ZERO(&master); FD_SET(sockfd, &master); int len, flag = 0; char buf[LEN]; char time[20]; while (1) { rfds = master; if (flag) { FD_ZERO(&wfds); } else { wfds = master; flag = 1; } if (select(maxfd + 1, &rfds, &wfds, NULL, NULL) == -1) { cout << "select error" << endl; exit(1); } if (FD_ISSET(sockfd, &rfds)) { len = read(sockfd, buf, LEN); if (len < 0) { cout << "read error" << endl; close(sockfd); exit(1); } cout << "len=" <<len<< endl; int i; for(i=0;i<len;i++) if(!buf[i]) buf[i]=1; buf[len] = '\0'; // cout << buf << endl; char *logout = strstr(buf, "></span></td>"); if (logout) { get_time(time); cout << time << " out" << endl; return 1; } else { get_time(time); cout << time << " in" << endl; return 0; } sleep(1); } if (FD_ISSET(sockfd, &wfds)) { len = write(sockfd, request_status, strlen(request_status)); if (len <= 0) { cout << "send judge login request error" << endl; exit(1); } else { get_time(time); cout << time << " Send judge login request" << endl; } } } } void login(int sockfd) { char time[20]; get_time(time); int len = write(sockfd, request_in, strlen(request_in)); cout << time << " Send login request" << endl; //cout << buffer << endl; char buf[LEN]; len = read(sockfd, buf, LEN); get_time(time); int i; for(i=0;i<len;i++) if(!buf[i]) buf[i]=1; buf[len] = '\0'; char *p = strstr(buf, "login_ok"); // if (p) cout<<time << " login success" << endl; // else // cout << time << " login error" << endl; } void logout(int sockfd) { char time[20]; get_time(time); int len = write(sockfd, request_out, strlen(request_out)); cout << time << " Send logout request" << endl; char buf[65536]; len = read(sockfd, buf, 1024); get_time(time); char *p = strstr(buf, "logout"); if (p) { cout << time << " logout success" << endl; } else cout << time << " logout error" << endl; } int main(int argc,char** argv) { //读取配置文件 int sockfd = connect(); char username[20]; char password_temp[20]; char retrytime[10]; char checktime[10]; // read_cfg(username, password_temp, retrytime, checktime); retry = 15; int check = 900; char password[10] = "MTU5MzU3"; cout << "The password after base64 is:" << password << endl; //设置连接请求 set_request_in(username, password); set_request_out(username); char time[20]; if(argc==1) while(1) { if(if_login(sockfd)) login(sockfd); else cout<<"have login"<<endl; sleep(retry); } else if(argc==2&&!strcmp(argv[1],"logout")) logout(sockfd); else exit(1); return 0; }
[ "497256303zby@gmail.com" ]
497256303zby@gmail.com
c92f5e4236af9a5fb00e54deff9c5406ce8ca056
2555a1b9df460b88c1965b808024f79488f26b16
/GrimFandango/stdafx.cpp
cc036655fa5598937203fab77f2cc5a24387fc96
[]
no_license
Florin9doi/GrimFandangoFontEditor
8ce5b1a42ad5a8fee1ca16e5e2ea0e0bb291d56d
13ea73abb0dd1329ba63b20f895b100b4c97125a
refs/heads/master
2016-09-11T09:13:28.640517
2014-10-28T21:23:12
2014-10-28T21:23:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
205
cpp
// stdafx.cpp : source file that includes just the standard includes // GrimFandango.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "florin9doi@gmail.com" ]
florin9doi@gmail.com
294ff294b9eecdda2dfc0052cbefed6487d668f3
9bb6cefe6a102fa781f8db0b7d7e020934a81707
/sample/sample.cpp
7e86d48941045f2c075a0687c2966f44f56c6fba
[ "MIT" ]
permissive
kaityo256/mpistream
70a581ce1a300ef76d72fb1a244e2708a5b7789e
cd86eefb057970b847f9c61bf8e9b80c8cc4c542
refs/heads/master
2021-05-06T08:46:34.206837
2020-04-22T04:28:19
2020-04-22T04:28:19
161,983,892
1
1
null
null
null
null
UTF-8
C++
false
false
333
cpp
#include "mpistream.hpp" #include <mpi.h> int main(int argc, char **argv) { MPI_Init(&argc, &argv); int rank, procs; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &procs); mout.save_to_file = true; mout << "My rank is " << rank << " out of " << procs << " procs." << std::endl; MPI_Finalize(); }
[ "kaityo@users.sourceforge.jp" ]
kaityo@users.sourceforge.jp
2f4315665f2527c728b84da5e231af0ed3228d41
ea5d587dc7657b0e940b7359a97d94a0bbf1c9c6
/Happy_Notes_Projet_LO21_Capgen_Martin/notesediteur.h
cf9eaf2638dc0ce80afac23f38a2dc7d22528638
[]
no_license
kahn-aar/HappyNotes
ae521cead450082fe0242b6180dde4ea2038974b
16b23e7a365e41697647c8107503db18172d4c11
refs/heads/master
2016-09-06T10:00:19.519135
2014-02-23T09:31:32
2014-02-23T09:31:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,974
h
#ifndef NOTESEDITEUR_H #define NOTESEDITEUR_H #include <QMainWindow> #include <QWidget> #include <QMessageBox> #include <QAction> #include <QMenu> #include <QMenuBar> #include <QFileDialog> #include <QLabel> #include <QTabWidget> #include <QWidget> #include <QLineEdit> #include <QTextEdit> #include <QtWidgets/QApplication> #include <QtWidgets/QPushButton> #include <QtWidgets> #include <QVBoxLayout> #include <QString> #include <QObject> #include <QMessageBox> #include <QIcon> #include <QTreeView> #include <QStandardItemModel> #include <QGroupBox> #include <QVBoxLayout> #include <QRadioButton> #include "note.h" #include <iostream> using namespace std; /*! * \brief La classe NotesEditeur est la fenêtre principale de l'application * * La fenêtre est composée d'une barre d'outils, du widget central de l'éditeur et du widget de coté avec la liste des notes filtrées. */ class NotesEditeur : public QMainWindow { Q_OBJECT static NotesEditeur* instance;/**< Il s'agit d'un pointeur l'instance du NotesEditeur*/ QLineEdit* filter;/**< ligne du filtre*/ QTabWidget* tab;/**< Onglets*/ QRadioButton *contient;/**< bouton radio contient*/ QRadioButton *exact;/**< bouton radio exact*/ QStandardItemModel* modele;/**< modèle du coté*/ QListView* view;/**< Vue des notes*/ QPushButton* corbeille;/**< Bouton de la corbeille*/ Note* note_actuelle;/**< Pointeur sur la note ouverte*/ Note* cliked_note;/**< Pointeur sur la note cliquée*/ public: explicit NotesEditeur(QWidget *parent = 0); static NotesEditeur* getInstance(){ if(!instance) instance = new NotesEditeur; return instance;} QStandardItemModel* getModele() const {return modele;} void initDockWidgets(); void initCentralArea(); void generateModel(QStandardItem* item = 0); void refreshModel(); QString getFilter() const {return filter->text();} Note* getNote() const {return note_actuelle;} void load_article(Note* note); void load_document(Note* note); void load_image(Note* note); void load_video(Note* note); void load_audio(Note* note); void enableMenu(); void disableMenu(); signals: public slots: void newArticle(); void newImage(); void newVideo(); void newAudio(); void newDocument(); void save(); void add(); void addNewTag(); void addTag(); void remTag(); void onSupTag(); void onTitleChanged(const QString& title ); void onPathChanged(const QString& path ); void onDescChanged(); void onTextChanged(); void onClick(QModelIndex index); void onSimpleClick(QModelIndex index); void onFilterModify(QString); void onCorbeille(); void onDelete(); void onRefresh(); void onNewWorkspace(); void onCopyWorkspace(); void onChangeWorkspace(); void onExportHTML(); void onExportLATEX(); void onExportTXT(); }; /*! * \brief La classe SupprTag est une fenêtre permettant de supprimer un Tags. * * Cette classe créé une fenêtre avec des bouttons radios pour chaque Tags. Le boutton supprime le Tags. */ class SupprTag : public QWidget { Q_OBJECT QWidget fenetre;/**< Widget conteneur*/ QGroupBox *groupbox;/**< Contient les boutons radios*/ QVBoxLayout *vbox; /**< Layout de la fenêtre*/ public: SupprTag(); ~SupprTag(); public slots: void onSupprTag(); }; /*! * \brief La classe AddTag est une fenêtre permettant d'ajouter un Tags à une Note. * * Cette classe créé une fenêtre avec des bouttons radios pour chaque Tags. Le boutton applique le Tags choisi à la Note. */ class AddTag : public QWidget { Q_OBJECT QWidget fenetre;/**< Widget conteneur*/ QGroupBox *groupbox;/**< Contient les boutons radios*/ QVBoxLayout *vbox; /**< Layout de la fenêtre*/ public: AddTag(); public slots: void onAddTag(); }; /*! * \brief La classe RemTag est une fenêtre permettant de retirer un Tags à une Note. * * Cette classe créé une fenêtre avec des bouttons radios pour chaque Tags lié à la note courrante. Le boutton retire le Tags choisi de la Note. */ class RemTag : public QWidget { Q_OBJECT QWidget fenetre;/**< Widget conteneur*/ QGroupBox *groupbox;/**< Contient les boutons radios*/ QVBoxLayout *vbox; /**< Layout de la fenêtre*/ public: RemTag(); public slots: void onRemTag(); }; /*! * \brief La classe Corbeille permet de gérer la Corbeille. * * Cette classe ouvre une fenêtre où on aura 4 bouttons : supprimer, restaurer, Tout restaurer, Tout supprimer. * De plus, elle possède une vue permettant de montrer la liste des Note qui sont dans la Corbeille. */ class Corbeille : public QWidget { Q_OBJECT QWidget fenetre;/**< Widget conteneur*/ QVBoxLayout *vbox;/**< layout des boutons*/ QVBoxLayout *vbox2;/**< layout du modèle*/ QHBoxLayout *hbox;/**< layout de la fenêtre*/ QPushButton *restaure;/**< bouton de restauration*/ QPushButton *_delete;/**< bouton de suppression*/ QPushButton *restaureAll;/**< bouton pour tout restaurer*/ QPushButton *deleteAll;/**< bouton pour tout supprimer*/ QStandardItemModel* modele;/**< Modèle*/ QListView* view;/**< vue sur la corbeille*/ Note* note_actuelle; /**< Il s'agit d'un pointeur sur la Note sur laquelle on a cliqué*/ public: explicit Corbeille(); void generateModel(QStandardItem* item = 0); void refreshModel(); public slots: void onRestaure(); void onDelete(); void onRestaureAll(); void onDeleteAll(); void onClick(QModelIndex); }; /*! * \brief La classe AddDoc créé une fenêtre permettant de gérer les Document. * * Cette classe nous permet de gérer les Documents : Ajouter une Note ou supprimer une Note. */ class AddDoc : public QWidget { Q_OBJECT QWidget fenetre; /**< Widget de la fenêtre*/ QVBoxLayout *vbox;/**< layout de gauche*/ QVBoxLayout *vbox2;/**< layout de droite*/ QHBoxLayout *hbox;/**< layout de la fenêtre*/ QStandardItemModel* modele_gauche;/**< modèle de gauche*/ QListView* view_gauche;/**< Vue des notes qui ne sont pas dans le document*/ QStandardItemModel* modele_droite;/**< modèle de gauche*/ QListView* view_droite;/**< Vue des notes qui sont dans le document*/ Note* note_actuelle_gauche;/**< Pointeur sur la note cliquée de gauche*/ Note* note_actuelle_droite;/**< Pointeur sur la note cliquée de droite*/ QPushButton* ajouter;/**< Bouton d'ajout*/ QPushButton* supprimer;/**< Bouton de suppression*/ Document* doc;/**< Pointeur sur le document que l'on modifie */ public: AddDoc(Document*docu); void generateModel_gauche(QStandardItem* item = 0); void generateModel_droit(QStandardItem* item = 0); void refreshModel(); public slots: void onAddDoc(); void onClickGauche(QModelIndex index); void onClickDroit(QModelIndex index); void onRemDoc(); }; #endif // NOTESEDITEUR_H
[ "nicolas.martinr@gmail.com" ]
nicolas.martinr@gmail.com
27c97bd4aef0345e8cba7b99f890b6f832566eb0
2250b4bb995252778e5e5654a72f7e477064af7f
/PAT Advanced/1042.cpp
d43ac67bae960b5660ca54c32803ab7bb007969e
[]
no_license
cjf1699/PAT-solutions-and-notebook
60f9d8895898999143acdc7a5384e83cc3b617c9
ff57abf623afd4d5ba7320a3b22530d5e3419724
refs/heads/master
2020-04-20T00:01:18.796756
2019-02-03T06:01:16
2019-02-03T06:01:16
168,511,693
0
0
null
null
null
null
UTF-8
C++
false
false
3,476
cpp
/* 1042 Shuffling Machine (20 分) Shuffling is a procedure used to randomize a deck of playing cards. Because standard shuffling techniques are seen as weak, and in order to avoid "inside jobs" where employees collaborate with gamblers by performing inadequate shuffles, many casinos employ automatic shuffling machines. Your task is to simulate a shuffling machine. The machine shuffles a deck of 54 cards according to a given random order and repeats for a given number of times. It is assumed that the initial status of a card deck is in the following order: S1, S2, ..., S13, H1, H2, ..., H13, C1, C2, ..., C13, D1, D2, ..., D13, J1, J2 where "S" stands for "Spade", "H" for "Heart", "C" for "Club", "D" for "Diamond", and "J" for "Joker". A given order is a permutation of distinct integers in [1, 54]. If the number at the i-th position is j, it means to move the card from position i to position j. For example, suppose we only have 5 cards: S3, H5, C1, D13 and J2. Given a shuffling order {4, 2, 5, 3, 1}, the result will be: J2, H5, D13, S3, C1. If we are to repeat the shuffling again, the result will be: C1, H5, S3, J2, D13. Input Specification: Each input file contains one test case. For each case, the first line contains a positive integer K (≤20) which is the number of repeat times. Then the next line contains the given order. All the numbers in a line are separated by a space. Output Specification: For each test case, print the shuffling results in one line. All the cards are separated by a space, and there must be no extra space at the end of the line. Sample Input: 2 36 52 37 38 3 39 40 53 54 41 11 12 13 42 43 44 2 4 23 24 25 26 27 6 7 8 48 49 50 51 9 10 14 15 16 5 17 18 19 1 20 21 22 28 29 30 31 32 33 34 35 45 46 47 Sample Output: S7 C11 C10 C12 S1 H7 H8 H9 D8 D9 S11 S12 S13 D10 D11 D12 S3 S4 S6 S10 H1 H2 C13 D2 D3 D4 H6 H3 D13 J1 J2 C1 C2 C3 C4 D1 S5 H5 H11 H12 C6 C7 C8 C9 S2 S8 S9 H10 D5 D6 D7 H4 H13 C5 */ /******** 这道题关键是理清目的位置和当前位置的关系,并且每次迭代之后更新当前的存储情况。其实也可以直接计算出经过k轮操作后的最终位置,移动的过程就一步到位。 ********/ # include <stdio.h> # include <string.h> char *str[55] = {"start", "S1", "S2","S3","S4","S5","S6","S7","S8","S9","S10","S11","S12","S13", "H1", "H2","H3","H4","H5","H6","H7","H8","H9","H10","H11","H12","H13", "C1", "C2","C3","C4","C5","C6","C7","C8","C9","C10","C11","C12","C13", "D1", "D2","D3","D4","D5","D6","D7","D8","D9","D10","D11","D12","D13", "J1", "J2" }; int iter[55] = {0, 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, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54 }; int main() { int k; int index[55] = {0}, result[55] = {0}; scanf("%d", &k); for(int i=1; i<=54; i++){ scanf("%d", &index[i]); } for(int i=0; i<k; i++){ for(int j=1; j<=54; j++){ result[index[j]] = iter[j]; } memcpy(iter, result, sizeof(int)*55); } for(int i=1; i<=54; i++){ if(i != 54) printf("%s ", str[result[i]]); else printf("%s\n", str[result[i]]); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
4cb13385d60fda5ed5d731b3a97e6290791a5f8c
42b0339739df2d11f3b82488d8a1d9cf87fb24de
/476.number-complement.cpp
4c021e2496af5aab8e737b5847cfa582b3414d7d
[]
no_license
codeakki/DSA
b6013f3c23e3b0bf21b82831533abd15335e1022
a023840e6de9288a2ab29a801811e9439859ca2c
refs/heads/main
2023-06-26T20:24:06.273460
2021-07-12T16:05:11
2021-07-12T16:05:11
368,565,327
2
0
null
2021-07-10T16:38:10
2021-05-18T14:42:34
C++
UTF-8
C++
false
false
290
cpp
/* * @lc app=leetcode id=476 lang=cpp * * [476] Number Complement */ // @lc code=start class Solution { public: int findComplement(int num) { unsigned mask = ~0; while (num & mask) mask <<= 1; return ~mask & ~num; } }; // @lc code=end
[ "noreply@github.com" ]
noreply@github.com
aec1116b96a166e84704bfc9f17b92b260311903
85edd16a14ed5c2aeb658c1763b30a7dc08b3095
/Whisper/Source/UI/Source/Documents/XDocFocus.cpp
5356d6f9e3f81ac7516fd55f13425d61a1db694c
[ "MIT" ]
permissive
jesse99/whisper
14a17f94de8fccad2ddc6e9abf9cfa5f40922d50
c71c2da3d71463a59411b36730713f517934ffc4
refs/heads/master
2020-04-21T00:16:20.627290
2019-02-05T05:21:44
2019-02-05T05:21:44
169,191,357
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,649
cpp
/* * File: XDocFocus.cpp * Summary: The interface that handles focusing on documents. * Written by: Jesse Jones * * Copyright © 2000 Jesse Jones. * This code is distributed under the zlib/libpng license (see License.txt for details). * * Change History (most recent first): * * $Log: XDocFocus.cpp,v $ * Revision 1.4 2001/01/30 07:17:46 jesjones * Added HasFocus. * * Revision 1.3 2000/12/14 08:34:26 jesjones * More doxyfying. * * Revision 1.2 2000/11/09 12:32:30 jesjones * 1) Removed double CRs introduced during the initial checkin. 2) Changed the header comments to make it clearer that Whisper is using the zlib license agreement. 3) Added the Log keyword. */ #include <XWhisperHeader.h> #include <IFocus.h> #include <ICurrentFocus.h> namespace Whisper { // =================================================================================== // class XDocFocus //! The interface that handles focusing on documents. // =================================================================================== class XDocFocus : public IFocus { //----------------------------------- // Initialization/Destruction // public: virtual ~XDocFocus(); XDocFocus(XBoss* boss); //----------------------------------- // Inherited API // public: virtual bool WantsFocus() const; virtual void SetFocus(); virtual bool HasFocus() const; }; DEFINE_INTERFACE_FACTORY(XDocFocus) //--------------------------------------------------------------- // // XDocFocus::~XDocFocus // //--------------------------------------------------------------- XDocFocus::~XDocFocus() { } //--------------------------------------------------------------- // // XDocFocus::XDocFocus // //--------------------------------------------------------------- XDocFocus::XDocFocus(XBoss* boss) { IFocus::DoSetBoss(boss); } //--------------------------------------------------------------- // // XDocFocus::WantsFocus // //--------------------------------------------------------------- bool XDocFocus::WantsFocus() const { return false; } //--------------------------------------------------------------- // // XDocFocus::SetFocus // //--------------------------------------------------------------- void XDocFocus::SetFocus() { DEBUGSTR("Can't focus on documents!"); } //--------------------------------------------------------------- // // XDocFocus::HasFocus // //--------------------------------------------------------------- bool XDocFocus::HasFocus() const { ICurrentFocusPtr current(L"Application"); bool has = current->GetFocus() == this; return has; } } // namespace Whisper
[ "jesse9jones@gmail.com" ]
jesse9jones@gmail.com
4e43957b3c1d9038687ab6304c4cc7d48169bdea
ae65ca30adde7655080ea070ad046119014868ba
/ShiftingSort.cpp
81a0e9ad2a23e43c0431806eb5b7d0da72005b96
[]
no_license
sumitsojha88/CPP-Programs-
dd6d09eac774e777938c047aafd221e2fdf42007
ecaa89e00942db7564d31599c9270aa6b9e9cc6a
refs/heads/main
2023-08-13T18:19:57.654195
2021-10-06T10:10:37
2021-10-06T10:10:37
414,161,124
1
1
null
2021-10-06T10:10:08
2021-10-06T10:10:08
null
UTF-8
C++
false
false
963
cpp
//https://codeforces.com/contest/1579/problem/B #include<bits/stdc++.h> using namespace std; #define ll long long int #define mod 1e9 + 7 void solve(){ int n; cin>>n; vector<int> a(n); for(int i = 0; i<n; i++) cin>>a[i]; vector<pair<int,int>> actions; for(int i = 0; i<n; i++){ int minPos = i; for(int j = i; j<n; j++){ if(a[j] < a[minPos]) minPos = j; } if(minPos > i){ actions.push_back({i,minPos}); int bak = a[minPos]; for(int j = minPos; j>i; j--){ a[j] = a[j-1]; } a[i] = bak; } } cout<<actions.size()<<endl; for(auto x : actions){ cout<<x.first + 1<<" "<<x.second + 1<<" "<<x.second - x.first<<endl; } } int main(){ int t; cin>>t; while(t--){ solve(); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
09faec0191721be32c54e14a1c808dbaed63e687
c703a08d76783d68dc7f8b16ba445c26aee74cef
/CodeForces/860/c.cpp
5c64e21cea96ae150210a258952355c5f28d12dc
[]
no_license
romilpunetha/Online-Judges
7ab14efde8180a4cc0d22a263159b2c5486122d7
f1eb05795e4eecad5910c534226f61d920f53a4d
refs/heads/master
2023-08-18T01:16:15.299862
2023-08-09T13:48:25
2023-08-09T13:48:25
67,865,026
0
1
null
null
null
null
UTF-8
C++
false
false
2,613
cpp
#include <bits/stdc++.h> #define endl '\n' #define inf INT_MAX #define pb push_back #define der(c, x) ((c).find(x) != (c).end()) #define base 999983 #define baseinv 943912055 #define ff first #define ss second #define V vector #define L list #define P pair #define MP map #define ST set #define UM unordered_map #define MM multimap #define UMM unordered_multimap #define MST multiset #define UST unordered_set #define UMS unordered_multiset #define PQ priority_queue #define Pii P<int, int> #define Pll P<long long, long long> #define Graph V<L<int> > #define all(a) (a).begin(), (a).end() #define tr1(x) cerr << #x << ": " << x << endl; #define tr2(x, y) cerr << #x << ": " << x << " | " << #y << ": " << y << endl; #define tr3(x, y, z) cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl; #define tr4(a, b, c, d) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl; #define tr5(a, b, c, d, e) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << endl; #define tr6(a, b, c, d, e, f) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << " | " << #f << ": " << f << endl; using namespace std; template <typename A, typename B> inline ostream& operator<<(ostream& os, const pair<A, B>& v) { return os << v.first << ' ' << v.second; } template <typename A> inline ostream& operator<<(ostream& os, const vector<A>& v) { auto it = v.begin(); os << *it; for (++it; it != v.end(); os << ' ' << *it++) ; return os; } void tr() { cout << endl; } template <typename H, typename... T> inline void tr(H head, T... tail) { cerr << head << ' '; tr(tail...); } typedef long long ll; typedef unsigned long long ull; typedef double dbl; typedef long double ldbl; ll gcd(ll a, ll b) { if (a < b) swap(a, b); if (!b) return a; return gcd(b, a % b); } ll lcm(ll a, ll b) { return (a * b) / gcd(a, b); } void solve() { int n; cin >> n; ll ans = 1LL, gc = 0LL, lc = 1LL; for (int i = 0; i < n; i++) { ll p, q; cin >> p >> q; gc = gcd(gc, p * q); lc = lcm(lc, q); if (gc % lc != 0) { ans++; gc = p * q; lc = q; } } cout << ans << endl; } int main() { ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); int T; cin >> T; while (T--) { solve(); } return 0; }
[ "romil.punetha@dstreet.finance" ]
romil.punetha@dstreet.finance
74cde76f8f73b7aef3615fd723fb409fed563cb8
1673981f50c4594ec9c17285d9b4cf1e31585b8c
/codeforce-problem/main.cpp
955d1a04478ce5bafdcb366c1372f8c81d44bc02
[]
no_license
Aman2241/Coding-Solutions
d1b2dcb923941fa4167f8f1b8839a9c46c38bd2d
53fdb1be86c46d4eeac5953da852275826c56cf0
refs/heads/master
2022-12-14T10:57:32.992554
2020-09-12T17:52:23
2020-09-12T17:52:23
288,506,665
2
0
null
null
null
null
UTF-8
C++
false
false
653
cpp
/****************************************************************************** Codeforce Problem-231(A) *******************************************************************************/ #include <iostream> #define ll long long int using namespace std; int main() { int k; cin>>k; int count=0; while(k--) { ll n,m,a; cin>>n>>m>>a; if(n==1 && m==1) { count++; } else if(n==1 && a==1) { count++; } else if(m==1 && a==1) { count++; } else if(n==1 && a==1 && m==1) { count++; } } cout<<count<<endl; return 0; }
[ "amanrajsingh7870865175@gmail.com" ]
amanrajsingh7870865175@gmail.com
12e446e14798b4919bbc3a55ccf7ae12d58134c4
d1f5929e7d3334721b1b777ed557be35246ba4d5
/십자뒤집기.cpp
dea8b21bd347e0d906c3eaf7f4039c206a4ce184
[]
no_license
Readiz/acmicpc.net
67a59d9e785f31151a3801013f345dd2d0b304c9
9c80832f233eb6cc05e2d38808661c3793c8c7e0
refs/heads/master
2020-03-17T21:45:09.296701
2016-08-19T17:05:20
2016-08-19T17:05:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,642
cpp
#include <stdio.h> #define INF 987654321 char state[16][16]; int chgcount[16][16]; int dir[4][2] = { 0,1,1,0,-1,0,0,-1 }; int min; int N; int MIN(int a, int b) { return a < b ? a : b; } int check(int c) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (state[i][j] == '*')return 0; } } min = MIN(c, min); return 1; } int inpoint(int x, int y) { if (x >= 0 && x < N && y >= 0 && y < N) return 1; else return 0; } void stchange(int i, int j, int w) { state[i][j] = state[i][j] == '*' ? '.' : '*'; chgcount[i][j] = chgcount[i][j] + w; } int isOk(int i, int j) { if (state[i][j] == '*')return 1; if (chgcount[i][j] >= 2)return 0; for (int k = 0; k < 4; k++) { if (inpoint(i + dir[k][0], j + dir[k][1])) { if (state[i + dir[k][0]][j + dir[k][1]] == '*')return 1; else if (chgcount[i + dir[k][0]][j + dir[k][1]] >= 2) return 0; } } return 0; } void change(int i, int j, int w) { stchange(i, j, w); for (int k = 0; k < 4; k++) { if (inpoint(i + dir[k][0], j + dir[k][1])) { stchange(i + dir[k][0], j + dir[k][1], w); } } } void f(int index, int count) { if (index == N*N) { check(count); return; } f(index + 1, count); if (isOk(index / N, index % N)) { change(index / N, index % N, 1); f(index + 1, count + 1); change(index / N, index % N, -1); } } int main() { int testcase; int iCount; scanf("%d", &testcase); for (iCount = 0; iCount < testcase; iCount++) { scanf("%d", &N); for (int i = 0; i < N; i++) { scanf("%s", state[i]); } min = INF; if (N <= 10)f(0, 0); printf("#testcase%d\n", iCount + 1); printf("%d\n", min); } return 0; }
[ "kskung12@gmail.com" ]
kskung12@gmail.com
753f5fb5bc0891b7822b127afe396152c9c514a4
7f16497d6eb7ea596ec26bee5215ed92a28c11b8
/USACO/2018jan/plat/lifeguards.cpp
8dd377b9394b27f8477837ab26c207b84f2e32f1
[]
no_license
thecodingwizard/competitive-programming
6c088dc15116409583429486951a94a87f6c316b
76f8659dbb935604a31fad26967fdfa413141244
refs/heads/master
2022-05-27T02:25:34.593546
2022-05-19T06:00:00
2022-05-19T06:00:00
159,700,280
83
25
null
2021-10-01T15:26:22
2018-11-29T17:03:04
C++
UTF-8
C++
false
false
3,049
cpp
#include <iostream> #include <string> #include <utility> #include <sstream> #include <algorithm> #include <stack> #include <vector> #include <queue> #include <map> #include <set> #include <bitset> #include <cmath> #include <cstring> #include <iomanip> #include <fstream> #include <cassert> #include <unordered_set> using namespace std; template<class T> using min_heap = priority_queue<T, vector<T>, greater<T>>; #define FOR(i, a, b) for (int i=a; i<(b); i++) #define F0R(i, a) for (int i=0; i<(a); i++) #define F0R1(i, a) for (int i=1; i<=(a); i++) #define FORd(i, a, b) for (int i = (b)-1; i >= a; i--) #define F0Rd(i, a) for (int i = (a)-1; i >= 0; i--) #define F0Rd1(i, a) for (int i=a; i>0; i--) #define SORT(vec) sort(vec.begin(), vec.end()) #define MIN(a, b) a = min(a, b) #define MAX(a, b) a = max(a, b) #define INF 1000000010 #define LL_INF 4500000000000000000 #define LSOne(S) (S & (-S)) #define EPS 1e-9 #define pA first #define pB second #define mp make_pair #define pb push_back #define PI acos(-1.0) #define ll long long #define MOD (int)(2e+9+11) #define SET(vec, val, size) for (int i = 0; i < size; i++) vec[i] = val; #define SET2D(arr, val, dim1, dim2) F0R(i, dim1) F0R(j, dim2) arr[i][j] = val; #define SET3D(arr, val, dim1, dim2, dim3) F0R(i, dim1) F0R(j, dim2) F0R(k, dim3) arr[i][j][k] = val; #define SET4D(arr, val, dim1, dim2, dim3, dim4) F0R(i, dim1) F0R(j, dim2) F0R(k, dim3) F0R(l, dim4) arr[i][j][k][l] = val; #define READGRID(arr, dim) F0R(i, dim) F0R(j, dim) cin >> arr[i][j]; #define all(x) (x).begin(), (x).end() typedef pair<int, int> ii; typedef pair<int, ii> iii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<iii> viii; typedef vector<ll> vl; void setupIO(const string &PROB) { ios::sync_with_stdio(false); cin.tie(nullptr); ifstream infile(PROB + ".in"); if (infile.good()) { freopen((PROB + ".in").c_str(), "r", stdin); freopen((PROB + ".out").c_str(), "w", stdout); } } /* ============================ */ // Note: This solution is a little bit sketchier than the method described in the analysis. int n, k; ii A[100000]; int memo[100000][200]; vii toConsider[101000]; int dp(int cow, int kLeft) { if (kLeft < 0) kLeft = 0; if (n - cow <= kLeft) return -INF; if (memo[cow][kLeft] != INF) return memo[cow][kLeft]; int len = A[cow].pB - A[cow].pA; int best = len; for (ii x : toConsider[cow + kLeft + 1]) { if (A[cow].pB >= x.pB) { MAX(best, len + x.pA - (A[cow].pB - x.pB)); } else { MAX(best, len + x.pA); } } memo[cow][kLeft] = best; toConsider[cow + kLeft].pb(mp(memo[cow][kLeft], A[cow].pA)); return memo[cow][kLeft]; } int main() { setupIO("lifeguards"); cin >> n >> k; F0R(i, n) cin >> A[i].pA >> A[i].pB; sort(A, A+n); SET2D(memo, INF, 100000, 200); F0Rd(i, n) { F0R(j, k+1) dp(i, j); } int best = 0; F0R(i, k+1) MAX(best, dp(i, k - i)); cout << best << endl; return 0; }
[ "nathan.r.wang@gmail.com" ]
nathan.r.wang@gmail.com
59402c139c3a8a0c137660993997d03d661c9196
fbbed14dbbc818f8ae362e28995c0b5a0762baec
/Rescue-Plus-Game-Engine/Engine/PhysicsMaterial.cpp
952323a7691ed6e5eac63188369bee04372af262
[]
no_license
MAClavell/Rescue-Plus-Game-Engine
be261cd3ce11273d1d09c142f7e41d29b37ff6d9
38e581a4d67711b67079d79a44d0012610a397e7
refs/heads/master
2022-04-03T19:32:09.959745
2020-02-21T23:17:27
2020-02-21T23:17:27
168,427,899
3
0
null
null
null
null
UTF-8
C++
false
false
2,697
cpp
#include "PhysicsMaterial.h" #include "PhysicsManager.h" using namespace physx; // Create a physics material PhysicsMaterial::PhysicsMaterial(float dynamicFriction, float staticFriction, float restitution, PxCombineMode::Enum frictionCombineMode, PxCombineMode::Enum restitutionCombineMode) { this->dynamicFriction = dynamicFriction; this->staticFriction = staticFriction; this->restitution = restitution; this->frictionCombineMode = frictionCombineMode; this->restitutionCombineMode = restitutionCombineMode; materialDirty = true; GeneratePxMaterial(); } PhysicsMaterial::~PhysicsMaterial() { } // Get the PxMaterial representation of this mat physx::PxMaterial* PhysicsMaterial::GetPxMaterial() { if (materialDirty) GeneratePxMaterial(); return mat; } // Generate the PxMaterial from class members void PhysicsMaterial::GeneratePxMaterial() { PxPhysics* physics = PhysicsManager::GetInstance()->GetPhysics(); mat = physics->createMaterial(staticFriction, dynamicFriction, restitution); mat->setFrictionCombineMode(frictionCombineMode); mat->setRestitutionCombineMode(restitutionCombineMode); materialDirty = false; } // Get the dynamic friction of this material float PhysicsMaterial::GetDynamicFriction() { return dynamicFriction; } // Set the dynamic friction of this material void PhysicsMaterial::SetDynamicFriction(float dynamicFriction) { this->dynamicFriction = dynamicFriction; materialDirty = true; } // Get the static friction of this material float PhysicsMaterial::GetStaticFriction() { return staticFriction; } // Set the static friction of this material void PhysicsMaterial::SetStaticFriction(float staticFriction) { this->staticFriction = staticFriction; materialDirty = true; } // Get the restitution this material float PhysicsMaterial::GetRestitution() { return restitution; } // Set the restitution this material void PhysicsMaterial::SetRestitution(float restitution) { this->restitution = restitution; materialDirty = true; } // Get the friction combne mode of this material PxCombineMode::Enum PhysicsMaterial::GetFrictionCombineMode() { return frictionCombineMode; } // Set the friction combine mode of this material void PhysicsMaterial::SetFrictionCombineMode(PxCombineMode::Enum combineMode) { this->frictionCombineMode = combineMode; materialDirty = true; } // Get the restitution combine mode of this material PxCombineMode::Enum PhysicsMaterial::GetResitutionCombineMode() { return restitutionCombineMode; } // Set the restitution combine mode of this material void PhysicsMaterial::SetRestitutionCombineMode(PxCombineMode::Enum combineMode) { this->restitutionCombineMode = combineMode; materialDirty = true; }
[ "michaelclavell11@gmail.com" ]
michaelclavell11@gmail.com
8aa4db0093dc69cba5aaca80edbec449f3689211
50ae435ddf358ed949b1bfb0d5de59564412da15
/Atcoder/AGC030/B.cpp
9d5060e2c9f54ffdddbb93a7e77bb130dde73751
[ "MIT" ]
permissive
jinzhengyu1212/Clovers
3aba5afea2cf5774a25ebd84ced5f8c547d89d5d
0efbb0d87b5c035e548103409c67914a1f776752
refs/heads/master
2023-03-04T17:31:39.422230
2021-02-19T10:31:41
2021-02-19T10:31:41
325,534,245
0
0
null
null
null
null
UTF-8
C++
false
false
1,394
cpp
/* the vast starry sky, bright for those who chase the light. */ #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; #define mk make_pair const int inf=(int)1e9; const ll INF=(ll)5e18; const int MOD=998244353; int _abs(int x){return x<0 ? -x : x;} int add(int x,int y){x+=y; return x>=MOD ? x-MOD : x;} int sub(int x,int y){x-=y; return x<0 ? x+MOD : x;} #define mul(x,y) (ll)(x)*(y)%MOD void Add(int &x,int y){x+=y; if(x>=MOD) x-=MOD;} void Sub(int &x,int y){x-=y; if(x<0) x+=MOD;} void Mul(int &x,int y){x=mul(x,y);} int qpow(int x,int y){int ret=1; while(y){if(y&1) ret=mul(ret,x); x=mul(x,x); y>>=1;} return ret;} void checkmin(int &x,int y){if(x>y) x=y;} void checkmax(int &x,int y){if(x<y) x=y;} void checkmin(ll &x,ll y){if(x>y) x=y;} void checkmax(ll &x,ll y){if(x<y) x=y;} #define out(x) cerr<<#x<<'='<<x<<' ' #define outln(x) cerr<<#x<<'='<<x<<endl #define sz(x) (int)(x).size() inline int read(){ int x=0,f=1; char c=getchar(); while(c>'9'||c<'0'){if(c=='-') f=-1; c=getchar();} while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; } const int N=500005; const int M=1005; ll ans=0,sum1[N],sum2[N]; int n,a[N]; int dist(int i,int j,int flag){ if(flag) return a[j]-a[i];//shun else return L+a[i]-a[j]; } int main() { L=read(); n=read(); for(int i=1;i<=n;i++) a[i]=read(); return 0; }
[ "2280244201@qq.com" ]
2280244201@qq.com
3e4a4cfa406726c90ca572262feeb3b11c471cc5
3cdf8fc71ca6fa1e5c8f7111f72d4b0e13bbf2ae
/BRAINSCommonLib/BRAINSFitHelper.cxx
e331797bea46910a342a7285ebc0da066243cc11
[]
no_license
slimgec/BRAINSStandAlone
88523d3c47d4df53517a844eb420f7816cede690
0f8a8b87913bd1969997d0613840ba5e8ea19981
refs/heads/master
2021-01-23T23:34:15.653635
2012-09-12T18:51:52
2012-09-12T18:51:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,858
cxx
#include "BRAINSFitUtils.h" #include "BRAINSFitHelper.h" #include "BRAINSFitHelperTemplate.h" #include "genericRegistrationHelper.h" #include "itkNormalizedCorrelationImageToImageMetric.h" #include "itkMeanSquaresImageToImageMetric.h" #include "itkKullbackLeiblerCompareHistogramImageToImageMetric.h" #include "itkHistogramImageToImageMetric.h" #include "itkKappaStatisticImageToImageMetric.h" #include "itkMeanReciprocalSquareDifferenceImageToImageMetric.h" #include "itkMutualInformationHistogramImageToImageMetric.h" #include "itkGradientDifferenceImageToImageMetric.h" #include "itkCompareHistogramImageToImageMetric.h" #include "itkCorrelationCoefficientHistogramImageToImageMetric.h" #include "itkMatchCardinalityImageToImageMetric.h" #include "itkMeanSquaresHistogramImageToImageMetric.h" #include "itkBinaryThresholdImageFilter.h" #include "itkNormalizedMutualInformationHistogramImageToImageMetric.h" MaskImageType::ConstPointer ExtractConstPointerToImageMaskFromImageSpatialObject( SpatialObjectType::ConstPointer inputSpatialObject) { ImageMaskSpatialObjectType const * const temp = dynamic_cast<ImageMaskSpatialObjectType const *>( inputSpatialObject.GetPointer() ); if( temp == NULL ) { itkGenericExceptionMacro(<< "Invalid mask converstion attempted."); } ImageMaskSpatialObjectType::ConstPointer ImageMask( temp ); const MaskImageType::ConstPointer tempOutputVolumeROI = ImageMask->GetImage(); return tempOutputVolumeROI; } namespace itk { BRAINSFitHelper::BRAINSFitHelper() : m_FixedVolume(NULL), m_MovingVolume(NULL), m_PreprocessedMovingVolume(NULL), m_FixedBinaryVolume(NULL), m_MovingBinaryVolume(NULL), m_OutputFixedVolumeROI(""), m_OutputMovingVolumeROI(""), m_PermitParameterVariation(0), m_NumberOfSamples(500000), m_NumberOfHistogramBins(50), m_HistogramMatch(false), m_RemoveIntensityOutliers(0.00), m_NumberOfMatchPoints(10), m_NumberOfIterations(1, 1500), m_MaximumStepLength(0.2), m_MinimumStepLength(1, 0.005), m_RelaxationFactor(0.5), m_TranslationScale(1000.0), m_ReproportionScale(1.0), m_SkewScale(1.0), m_UseExplicitPDFDerivativesMode("AUTO"), m_UseCachingOfBSplineWeightsMode("ON"), m_BackgroundFillValue(0.0), m_TransformType(1, "Rigid"), m_InitializeTransformMode("Off"), m_MaskInferiorCutOffFromCenter(1000), m_SplineGridSize(3, 10), m_CostFunctionConvergenceFactor(1e+9), m_ProjectedGradientTolerance(1e-5), m_MaxBSplineDisplacement(0.0), m_ActualNumberOfIterations(0), m_PermittedNumberOfIterations(0), // m_AccumulatedNumberOfIterationsForAllLevels(0), m_DebugLevel(0), m_CurrentGenericTransform(NULL), m_GenericTransformList(0), m_DisplayDeformedImage(false), m_PromptUserAfterDisplay(false), m_FinalMetricValue(0.0), m_ObserveIterations(true), m_CostMetric("MMI"), // Default to Mattes Mutual Information Metric m_Helper(NULL), m_ForceMINumberOfThreads(-1) { m_SplineGridSize[0] = 14; m_SplineGridSize[1] = 10; m_SplineGridSize[2] = 12; } void BRAINSFitHelper::Update(void) { // // Do remove intensity outliers if requested // if( m_RemoveIntensityOutliers > vcl_numeric_limits<float>::epsilon() ) { this->m_FixedVolume = ClampNoisyTailsOfImage<FixedVolumeType, FixedBinaryVolumeType>( m_RemoveIntensityOutliers, this->m_FixedVolume.GetPointer(), this->m_FixedBinaryVolume.GetPointer() ); this->m_PreprocessedMovingVolume = ClampNoisyTailsOfImage<MovingVolumeType, MovingBinaryVolumeType>( m_RemoveIntensityOutliers, this->m_MovingVolume.GetPointer(), this->m_MovingBinaryVolume.GetPointer() ); { // if( this->m_DebugLevel > 9 ) { { typedef itk::ImageFileWriter<FixedVolumeType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->UseCompressionOn(); writer->SetFileName("DEBUGNormalizedFixedVolume.nii.gz"); writer->SetInput(this->m_FixedVolume); try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cout << "Exception Object caught: " << std::endl; std::cout << err << std::endl; throw; } } { typedef itk::ImageFileWriter<MovingVolumeType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->UseCompressionOn(); writer->SetFileName("DEBUGNormalizedMovingVolume.nii.gz"); writer->SetInput(this->m_PreprocessedMovingVolume); try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cout << "Exception Object caught: " << std::endl; std::cout << err << std::endl; throw; } } } } } else { this->m_PreprocessedMovingVolume = this->m_MovingVolume; } // Do Histogram equalization on moving image if requested. if( m_HistogramMatch ) { typedef itk::OtsuHistogramMatchingImageFilter<FixedVolumeType, MovingVolumeType> HistogramMatchingFilterType; HistogramMatchingFilterType::Pointer histogramfilter = HistogramMatchingFilterType::New(); // TODO: Regina: Write various histogram matching specializations and // compare them. // histogramfilter->SetForegroundMode("Otsu"); // A simple Otsu threshold // for each image .... BUT BE CAREFUL, need to do some quantile checking for // degenerate images // histogramfilter->SetForegroundMode("Simple"); // A simple average value // of the image should be used // histogramfilter->SetForegroundMode("Quantile"); // Only values between // the 25th and 66th quantile should be used. // histogramfilter->SetForegroundMode("Masks"); // Foreground is // specifically defined by masks. histogramfilter->SetReferenceImage(this->m_FixedVolume); if( this->m_FixedBinaryVolume.IsNull() ) { itkGenericExceptionMacro(<< "ERROR: Histogram matching requires a fixed mask."); } histogramfilter->SetReferenceMask( m_FixedBinaryVolume.GetPointer() ); histogramfilter->SetInput(this->m_PreprocessedMovingVolume); if( this->m_MovingBinaryVolume.IsNull() ) { itkGenericExceptionMacro(<< "ERROR: Histogram matching requires a moving mask."); } histogramfilter->SetSourceMask( m_MovingBinaryVolume.GetPointer() ); histogramfilter->SetNumberOfHistogramLevels(this->m_NumberOfHistogramBins); histogramfilter->SetNumberOfMatchPoints(this->m_NumberOfMatchPoints); histogramfilter->Update(); this->m_PreprocessedMovingVolume = histogramfilter->GetOutput(); if( this->m_DebugLevel > 5 ) { typedef itk::ImageFileWriter<MovingVolumeType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->UseCompressionOn(); writer->SetFileName("DEBUGHISTOGRAMMATCHEDMOVING.nii.gz"); writer->SetInput(this->m_PreprocessedMovingVolume); try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cout << "Exception Object caught: " << std::endl; std::cout << err << std::endl; throw; } } } else { this->m_PreprocessedMovingVolume = this->m_MovingVolume; } if( this->m_CostMetric == "MMI" ) { typedef COMMON_MMI_METRIC_TYPE<FixedVolumeType, MovingVolumeType> MetricType; this->SetupRegistration<MetricType>(); MetricType::Pointer localCostMetric = this->GetCostMetric<MetricType>(); localCostMetric->SetNumberOfHistogramBins(this->m_NumberOfHistogramBins); const bool UseCachingOfBSplineWeights = ( m_UseCachingOfBSplineWeightsMode == "ON" ) ? true : false; localCostMetric->SetUseCachingOfBSplineWeights(UseCachingOfBSplineWeights); this->RunRegistration<MetricType>(); } else if( this->m_CostMetric == "MSE" ) { typedef itk::MeanSquaresImageToImageMetric<FixedVolumeType, MovingVolumeType> MetricType; this->SetupRegistration<MetricType>(); this->RunRegistration<MetricType>(); } else if( this->m_CostMetric == "NC" ) { typedef itk::NormalizedCorrelationImageToImageMetric<FixedVolumeType, MovingVolumeType> MetricType; this->SetupRegistration<MetricType>(); this->RunRegistration<MetricType>(); } // This requires additional machinery (training transform, etc) and hence // isn't as easy to incorporate // into the BRAINSFit framework. /*else if(this->m_CostMetric == "KL") { typedef itk::KullbackLeiblerCompareHistogramImageToImageMetric<FixedVolumeType,MovingVolumeType> MetricType; this->SetupRegistration<MetricType>(); this->RunRegistration<MetricType>(); }*/ else if( this->m_CostMetric == "KS" ) { if( this->m_HistogramMatch ) { itkExceptionMacro(<< "The KS cost metric is not compatible with histogram matching."); } // This metric only works with binary images that it knows the value of. // It defaults to 255, so we threshold the inputs to 255. typedef itk::BinaryThresholdImageFilter<FixedVolumeType, FixedVolumeType> BinaryThresholdFixedVolumeType; BinaryThresholdFixedVolumeType::Pointer binaryThresholdFixedVolume = BinaryThresholdFixedVolumeType::New(); binaryThresholdFixedVolume->SetInput(this->m_FixedVolume); binaryThresholdFixedVolume->SetOutsideValue(0); binaryThresholdFixedVolume->SetInsideValue(255); binaryThresholdFixedVolume->SetLowerThreshold(1); binaryThresholdFixedVolume->Update(); this->m_FixedVolume = binaryThresholdFixedVolume->GetOutput(); typedef itk::BinaryThresholdImageFilter<MovingVolumeType, MovingVolumeType> BinaryThresholdMovingVolumeType; BinaryThresholdMovingVolumeType::Pointer binaryThresholdMovingVolume = BinaryThresholdMovingVolumeType::New(); binaryThresholdMovingVolume->SetInput(this->m_MovingVolume); binaryThresholdMovingVolume->SetOutsideValue(0); binaryThresholdMovingVolume->SetInsideValue(255); binaryThresholdMovingVolume->SetLowerThreshold(1); binaryThresholdMovingVolume->Update(); this->m_PreprocessedMovingVolume = binaryThresholdMovingVolume->GetOutput(); typedef itk::KappaStatisticImageToImageMetric<FixedVolumeType, MovingVolumeType> MetricType; this->SetupRegistration<MetricType>(); this->RunRegistration<MetricType>(); } else if( this->m_CostMetric == "MRSD" ) { typedef itk::MeanReciprocalSquareDifferenceImageToImageMetric<FixedVolumeType, MovingVolumeType> MetricType; this->SetupRegistration<MetricType>(); this->RunRegistration<MetricType>(); } else if( this->m_CostMetric == "MIH" ) { typedef itk::MutualInformationHistogramImageToImageMetric<FixedVolumeType, MovingVolumeType> MetricType; this->SetupRegistration<MetricType>(); this->RunRegistration<MetricType>(); } else if( this->m_CostMetric == "GD" ) { typedef itk::GradientDifferenceImageToImageMetric<FixedVolumeType, MovingVolumeType> MetricType; this->SetupRegistration<MetricType>(); this->RunRegistration<MetricType>(); } else if( this->m_CostMetric == "CCH" ) { typedef itk::CorrelationCoefficientHistogramImageToImageMetric<FixedVolumeType, MovingVolumeType> MetricType; this->SetupRegistration<MetricType>(); this->RunRegistration<MetricType>(); } else if( this->m_CostMetric == "MC" ) { typedef itk::MatchCardinalityImageToImageMetric<FixedVolumeType, MovingVolumeType> MetricType; this->SetupRegistration<MetricType>(); this->RunRegistration<MetricType>(); } else if( this->m_CostMetric == "MSEH" ) { typedef itk::MeanSquaresHistogramImageToImageMetric<FixedVolumeType, MovingVolumeType> MetricType; this->SetupRegistration<MetricType>(); this->RunRegistration<MetricType>(); } else if( this->m_CostMetric == "NMIH" ) { typedef itk::NormalizedMutualInformationHistogramImageToImageMetric<FixedVolumeType, MovingVolumeType> MetricType; this->SetupRegistration<MetricType>(); this->RunRegistration<MetricType>(); } else { std::cout << "Metric \"" << this->m_CostMetric << "\" not valid." << std::endl; } } void BRAINSFitHelper::PrintSelf(std::ostream & os, Indent indent) const { // Superclass::PrintSelf(os,indent); os << indent << "FixedVolume:\n" << this->m_FixedVolume << std::endl; os << indent << "MovingVolume:\n" << this->m_MovingVolume << std::endl; os << indent << "PreprocessedMovingVolume:\n" << this->m_PreprocessedMovingVolume << std::endl; if( this->m_FixedBinaryVolume.IsNotNull() ) { os << indent << "FixedBinaryVolume:\n" << this->m_FixedBinaryVolume << std::endl; } else { os << indent << "FixedBinaryVolume: IS NULL" << std::endl; } if( this->m_MovingBinaryVolume.IsNotNull() ) { os << indent << "MovingBinaryVolume:\n" << this->m_MovingBinaryVolume << std::endl; } else { os << indent << "MovingBinaryVolume: IS NULL" << std::endl; } os << indent << "NumberOfSamples: " << this->m_NumberOfSamples << std::endl; os << indent << "NumberOfIterations: ["; for( unsigned int q = 0; q < this->m_NumberOfIterations.size(); ++q ) { os << this->m_NumberOfIterations[q] << " "; } os << "]" << std::endl; os << indent << "NumberOfHistogramBins:" << this->m_NumberOfHistogramBins << std::endl; os << indent << "MaximumStepLength: " << this->m_MaximumStepLength << std::endl; os << indent << "MinimumStepLength: ["; for( unsigned int q = 0; q < this->m_MinimumStepLength.size(); ++q ) { os << this->m_MinimumStepLength[q] << " "; } os << "]" << std::endl; os << indent << "TransformType: ["; for( unsigned int q = 0; q < this->m_TransformType.size(); ++q ) { os << this->m_TransformType[q] << " "; } os << "]" << std::endl; os << indent << "RelaxationFactor: " << this->m_RelaxationFactor << std::endl; os << indent << "TranslationScale: " << this->m_TranslationScale << std::endl; os << indent << "ReproportionScale: " << this->m_ReproportionScale << std::endl; os << indent << "SkewScale: " << this->m_SkewScale << std::endl; os << indent << "UseExplicitPDFDerivativesMode: " << this->m_UseExplicitPDFDerivativesMode << std::endl; os << indent << "UseCachingOfBSplineWeightsMode: " << this->m_UseCachingOfBSplineWeightsMode << std::endl; os << indent << "BackgroundFillValue: " << this->m_BackgroundFillValue << std::endl; os << indent << "InitializeTransformMode: " << this->m_InitializeTransformMode << std::endl; os << indent << "MaskInferiorCutOffFromCenter: " << this->m_MaskInferiorCutOffFromCenter << std::endl; os << indent << "ActualNumberOfIterations: " << this->m_ActualNumberOfIterations << std::endl; os << indent << "PermittedNumberOfIterations: " << this->m_PermittedNumberOfIterations << std::endl; // os << indent << "AccumulatedNumberOfIterationsForAllLevels: " << // this->m_AccumulatedNumberOfIterationsForAllLevels << std::endl; os << indent << "SplineGridSize: ["; for( unsigned int q = 0; q < this->m_SplineGridSize.size(); ++q ) { os << this->m_SplineGridSize[q] << " "; } os << "]" << std::endl; os << indent << "PermitParameterVariation: ["; for( unsigned int q = 0; q < this->m_PermitParameterVariation.size(); ++q ) { os << this->m_PermitParameterVariation[q] << " "; } os << "]" << std::endl; if( m_CurrentGenericTransform.IsNotNull() ) { os << indent << "CurrentGenericTransform:\n" << this->m_CurrentGenericTransform << std::endl; } else { os << indent << "CurrentGenericTransform: IS NULL" << std::endl; } os << indent << "CostMetric: " << this->m_CostMetric << std::endl; } void BRAINSFitHelper::PrintCommandLine(const bool dumpTempVolumes, const std::string suffix) const { std::cout << "The equivalent command line to the current run would be:" << std::endl; const std::string fixedVolumeString("DEBUGFixedVolume_" + suffix + ".nii.gz"); const std::string movingVolumeString("DEBUGMovingVolume_" + suffix + ".nii.gz"); const std::string fixedBinaryVolumeString("DEBUGFixedBinaryVolume_" + suffix + ".nii.gz"); const std::string movingBinaryVolumeString("DEBUGMovingBinaryVolume_" + suffix + ".nii.gz"); std::ostringstream oss; oss << "BRAINSFit \\" << std::endl; if( dumpTempVolumes == true ) { { typedef itk::ImageFileWriter<FixedVolumeType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->UseCompressionOn(); writer->SetFileName(fixedVolumeString); writer->SetInput(this->m_FixedVolume); try { writer->Update(); } catch( itk::ExceptionObject & err ) { oss << "Exception Object caught: " << std::endl; oss << err << std::endl; throw; } } { typedef itk::ImageFileWriter<MovingVolumeType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->UseCompressionOn(); writer->SetFileName(movingVolumeString); writer->SetInput(this->m_MovingVolume); try { writer->Update(); } catch( itk::ExceptionObject & err ) { oss << "Exception Object caught: " << std::endl; oss << err << std::endl; throw; } } } oss << "--costMetric " << this->m_CostMetric << " \\" << std::endl; oss << "--fixedVolume " << fixedVolumeString << " \\" << std::endl; oss << "--movingVolume " << movingVolumeString << " \\" << std::endl; if( this->m_HistogramMatch ) { oss << "--histogramMatch " << " \\" << std::endl; } { if( this->m_FixedBinaryVolume.IsNotNull() ) { oss << "--fixedBinaryVolume " << fixedBinaryVolumeString << " \\" << std::endl; { { const MaskImageType::ConstPointer tempOutputFixedVolumeROI = ExtractConstPointerToImageMaskFromImageSpatialObject(m_FixedBinaryVolume.GetPointer() ); itkUtil::WriteConstImage<MaskImageType>(tempOutputFixedVolumeROI.GetPointer(), fixedBinaryVolumeString); } } } if( this->m_MovingBinaryVolume.IsNotNull() ) { oss << "--movingBinaryVolume " << movingBinaryVolumeString << " \\" << std::endl; { { const MaskImageType::ConstPointer tempOutputMovingVolumeROI = ExtractConstPointerToImageMaskFromImageSpatialObject(m_MovingBinaryVolume.GetPointer() ); itkUtil::WriteConstImage<MaskImageType>(tempOutputMovingVolumeROI.GetPointer(), movingBinaryVolumeString); } } } if( this->m_FixedBinaryVolume.IsNotNull() || this->m_MovingBinaryVolume.IsNotNull() ) { oss << "--maskProcessingMode ROI " << " \\" << std::endl; } } oss << "--numberOfSamples " << this->m_NumberOfSamples << " \\" << std::endl; oss << "--numberOfIterations "; for( unsigned int q = 0; q < this->m_NumberOfIterations.size(); ++q ) { oss << this->m_NumberOfIterations[q]; if( q < this->m_NumberOfIterations.size() - 1 ) { oss << ","; } } oss << " \\" << std::endl; oss << "--numberOfHistogramBins " << this->m_NumberOfHistogramBins << " \\" << std::endl; oss << "--maximumStepLength " << this->m_MaximumStepLength << " \\" << std::endl; oss << "--minimumStepLength "; for( unsigned int q = 0; q < this->m_MinimumStepLength.size(); ++q ) { oss << this->m_MinimumStepLength[q]; if( q < this->m_MinimumStepLength.size() - 1 ) { oss << ","; } } oss << " \\" << std::endl; oss << "--transformType "; for( unsigned int q = 0; q < this->m_TransformType.size(); ++q ) { oss << this->m_TransformType[q]; if( q < this->m_TransformType.size() - 1 ) { oss << ","; } } oss << " \\" << std::endl; oss << "--relaxationFactor " << this->m_RelaxationFactor << " \\" << std::endl; oss << "--translationScale " << this->m_TranslationScale << " \\" << std::endl; oss << "--reproportionScale " << this->m_ReproportionScale << " \\" << std::endl; oss << "--skewScale " << this->m_SkewScale << " \\" << std::endl; oss << "--useExplicitPDFDerivativesMode " << this->m_UseExplicitPDFDerivativesMode << " \\" << std::endl; oss << "--useCachingOfBSplineWeightsMode " << this->m_UseCachingOfBSplineWeightsMode << " \\" << std::endl; oss << "--maxBSplineDisplacement " << this->m_MaxBSplineDisplacement << " \\" << std::endl; oss << "--projectedGradientTolerance " << this->m_ProjectedGradientTolerance << " \\" << std::endl; oss << "--costFunctionConvergenceFactor " << this->m_CostFunctionConvergenceFactor << " \\" << std::endl; oss << "--backgroundFillValue " << this->m_BackgroundFillValue << " \\" << std::endl; oss << "--initializeTransformMode " << this->m_InitializeTransformMode << " \\" << std::endl; oss << "--maskInferiorCutOffFromCenter " << this->m_MaskInferiorCutOffFromCenter << " \\" << std::endl; oss << "--splineGridSize "; for( unsigned int q = 0; q < this->m_SplineGridSize.size(); ++q ) { oss << this->m_SplineGridSize[q]; if( q < this->m_SplineGridSize.size() - 1 ) { oss << ","; } } oss << " \\" << std::endl; if( this->m_PermitParameterVariation.size() > 0 ) { oss << "--permitParameterVariation "; for( unsigned int q = 0; q < this->m_PermitParameterVariation.size(); ++q ) { oss << this->m_PermitParameterVariation[q]; if( q < this->m_PermitParameterVariation.size() - 1 ) { oss << ","; } } oss << " \\" << std::endl; } if( m_CurrentGenericTransform.IsNotNull() ) { const std::string initialTransformString("DEBUGInitialTransform_" + suffix + ".mat"); WriteBothTransformsToDisk(this->m_CurrentGenericTransform.GetPointer(), initialTransformString, ""); oss << "--initialTransform " << initialTransformString << " \\" << std::endl; } { const std::string outputVolume("DEBUGOutputVolume_" + suffix + ".nii.gz"); oss << "--outputVolume " << outputVolume << " \\" << std::endl; std::cout << oss.str() << std::endl; } { const std::string outputTransform("DEBUGOutputTransform" + suffix + ".mat"); oss << "--outputTransform " << outputTransform << " \\" << std::endl; std::cout << oss.str() << std::endl; } const std::string TesterScript("DEBUGScript" + suffix + ".sh"); std::ofstream myScript; myScript.open( TesterScript.c_str() ); myScript << oss.str() << std::endl; myScript.close(); } void BRAINSFitHelper::GenerateData() { this->Update(); } } // end namespace itk
[ "hans-johnson@uiowa.edu" ]
hans-johnson@uiowa.edu
022354d3d118f9d48f2adbe02f72588d2186c90e
d61f2cac3bd9ed39f95184b89dd40952c6482786
/testCase/results/43/mu0
b476be374827183c771cc9d0754c4be6a6e610b8
[]
no_license
karimimp/PUFoam
4b3a5b427717aa0865889fa2342112cc3d24ce66
9d16e06d63e141607491219924018bea99cbb9e5
refs/heads/master
2022-06-24T08:51:18.370701
2022-04-28T18:33:03
2022-04-28T18:33:03
120,094,729
6
3
null
2022-04-27T09:46:38
2018-02-03T13:43:52
C++
UTF-8
C++
false
false
1,199
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 3.0.1 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "43"; object mu0; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [1 -1 -1 0 0 0 0]; internalField uniform 1e-05; boundaryField { Wall { type calculated; value uniform 1e-05; } frontAndBack { type empty; } atmosphere { type calculated; value uniform 1e-05; } } // ************************************************************************* //
[ "mohsenk@outlook.com" ]
mohsenk@outlook.com
63aa7715bfd07baf38d9bc39f21aad7789c6a8dc
62ba57430910bc599b540abb3e3b4c01cd29d9f9
/file_descriptor.cpp
21a8df7da4bb5917dd5e1c63f0956cc3620f358c
[]
no_license
valexby/NTFS-recovery
fe2056937a23f950eb18eb673c3df349125abcbd
75339003fcf03eed78e862b3855045c6500e6527
refs/heads/master
2020-12-31T04:56:00.162194
2016-06-09T22:20:30
2016-06-09T22:20:30
57,919,733
0
0
null
null
null
null
UTF-8
C++
false
false
4,495
cpp
#include "file_descriptor.h" #include "raw_disk_read.h" #include <string> #include "std_attr_header.h" #include "std_info.h" #include "non_resident_attr.h" file_descriptor::file_descriptor(HANDLE disk, LONGLONG sector) { try { BYTE* buffer = read_sector(disk, sector, 1); if (*(DWORD*)(buffer+24) > 512) { BYTE* temp = buffer; buffer = read_sector(disk, sector, *(DWORD*)(temp + 24) / 512 + (*(DWORD*)(temp + 24) / 512 != 0 ? 1 : 0)); delete[] temp; } dump_buffer(buffer, *(DWORD*)(buffer + 24), L"DUMP1"); init(buffer); try { clean_sect_bord(buffer); } catch (string err_msg) { throw; } int i, cur_offset = wFirstAttrOffset; attr_col = get_attr_col(buffer + wFirstAttrOffset); attributes = new std_attr_header*[attr_col]; for (i = 0; i < attr_col;i++) { attributes[i] = build_attr(buffer + cur_offset); cur_offset += attributes[i]->dwFullAttrLen; } delete[] buffer; } catch(std::string) { throw; } } file_descriptor::file_descriptor() {} file_descriptor::~file_descriptor() { for (int i = 0; i < attr_col;i++) { delete attributes[i]; } delete[] attributes; delete[] updateSeq; } void file_descriptor::clean_sect_bord(BYTE* raw) const { int i; for (i = 0; i < wUpdtSeqSize-1; i++) { if ((i + 1) * 512 - 2 > dwRealFileSize) break; if (!memcmp(raw + (i + 1) * 512 - 2, &wUpdateSeqNumb, 2)) memcpy(raw + (i + 1) * 512 - 2, &updateSeq[i], 2); else { string sterr = "Bad sector\n"; throw sterr; } } } file_descriptor::file_descriptor(const file_descriptor& source) { *this = source; } file_descriptor& file_descriptor::operator=(const file_descriptor& source) { if (this == &source) return *this; memcpy(signature, source.signature, 4); memcpy(&wUpdtSeqOffset, &source.wUpdtSeqOffset, 4); n64LogFileSeq = source.n64LogFileSeq; memcpy(&wUseCnt, &source.wUseCnt, 8); memcpy(&dwRealFileSize, &source.dwRealFileSize, 8); n64RefToBaseFile = source.n64RefToBaseFile; memcpy(&wNextAttrId, &source.wNextAttrId, 4); updateSeq = new WORD[wUpdtSeqSize - 1]; memcpy(updateSeq, source.updateSeq, wUpdtSeqSize - 1); attr_col = source.attr_col; attributes = new std_attr_header*[attr_col]; for (int i = 0; i < attr_col; i++) { if (source.attributes[i]->cResident == 1) attributes[i] = new non_resident_attr(*(non_resident_attr*)source.attributes[i]); else { switch(source.attributes[i]->dwAttrType) { case 0x10: attributes[i] = new std_info(*(std_info*)source.attributes[i]); break; default: attributes[i] = new std_attr_header(*source.attributes[i]); break; } } } return *this; } void file_descriptor::init(BYTE* buffer) { int i; for (i = 0; i < 4; i++) signature[i] = buffer[i]; memcpy(&wUpdtSeqOffset, buffer + 4, 4); memcpy(&n64LogFileSeq, buffer + 8, 8); memcpy(&wUseCnt, buffer + 16, 8); memcpy(&dwRealFileSize, buffer + 24, 8); memcpy(&n64RefToBaseFile, buffer + 32, 8); memcpy(&wNextAttrId, buffer + 40, 2); memcpy(&wUpdateSeqNumb, buffer + wUpdtSeqOffset, 2); updateSeq = new WORD[wUpdtSeqSize-1]; memcpy(updateSeq, buffer + wUpdtSeqOffset + 2, wUpdtSeqSize * 2 - 2); } int file_descriptor::get_attr_col(BYTE* start) { int out = 0, offset; while (*reinterpret_cast<DWORD*>(start)!=0xFFFFFFFF) { memcpy(&offset, start + 4, 4); start += offset; out++; } return out; } bool file_descriptor::is_resident(BYTE* raw) { return *(raw + 8) == 0; } std_attr_header* file_descriptor::build_attr(BYTE* raw) { DWORD type = *raw; std_attr_header* res_ptr; if (!is_resident(raw)) return new non_resident_attr(raw); switch(type) { case 0xFFFFFFFF: throw "Unexpected end of attribute list"; case 0x10: res_ptr = new std_info(raw); break; default: res_ptr = new std_attr_header(raw); break; } return res_ptr; } bool file_descriptor::isDirectory() const { for (int i = 0; i < attr_col;i++) { if (attributes[i]->dwAttrType == 0xA0) return true; } return false; } int file_descriptor::get_attr_pos(int signature) const { for (int i = 0; i < attr_col; i++) { if (attributes[i]->dwAttrType == signature) return i; } return -1; } wchar_t* file_descriptor::get_file_name() const { wchar_t* out; int pos = get_attr_pos(0x30); if (pos == -1) return nullptr; out = new wchar_t[attributes[pos]->attrContent[88] + 1]; out[attributes[pos]->attrContent[88]] = 0; for (int i = 0; i < attributes[pos]->attrContent[88] * 2; i+=2) memcpy(&out[i / 2], &attributes[pos]->attrContent[90 + i], 2); return out; }
[ "realnats@gmail.com" ]
realnats@gmail.com
e9959e1ff117df9e8e8b57f9b827ea3e5aab5e04
dea0f11b220a621ed9dca13f1ca1d0b2fa7017fe
/소스코드/display.cpp
d927a3b51359ff48f279fde59fa57feb0fb6d110
[]
no_license
danmin20/DataStructure
d26f0f2ca388ce4bd0ce093e1fd155957577729b
d177cf7f5964e3427c145de151eda133955d8bf4
refs/heads/master
2020-09-17T17:28:07.888500
2019-12-29T06:10:32
2019-12-29T06:10:32
224,105,197
0
0
null
null
null
null
UTF-8
C++
false
false
290
cpp
#include "display.h" #include "ui_display.h" Display::Display(QWidget *parent) : QDialog(parent), ui(new Ui::Display) { ui->setupUi(this); } Display::~Display() { delete ui; } void Display::DisplaySong(QString str){ ui->textBrowser->setText(str); }
[ "noreply@github.com" ]
noreply@github.com
a305d943a75c2fe93ab7cb51f37b8f10d8f85507
e379251bec97b701e863a68227906a0309bdfe43
/src/GurthHex/hexdown.cpp
a0bbab671e27e63ca27de6e7e5e0647e4fc6ad28
[ "MIT" ]
permissive
CasparZhou/GurthHex
0b75ab4207f650748a160fd687abeee0b1ee09b7
08354ed7bbb1990ff7dbb9bd881832254f09baf9
refs/heads/master
2023-01-13T14:29:11.009877
2020-09-20T03:13:27
2020-09-20T03:13:27
314,254,000
0
0
null
null
null
null
UTF-8
C++
false
false
969
cpp
#include "hexdown.h" #include "fileprocess.h" #include "mainwindow.h" #include <QtWidgets> #include <QString> #include <string.h> HexDown::HexDown() { } HexDown::~HexDown() { } bool HexDown::TransDown() { return true; } bool HexDown::TransDown(MainWindow & w) { QString buffer=w.editor->toPlainText(); size64 size_buff=buffer.size(); line=size_buff/49+1; size64 size_now= ((line-1)<<4)+(size_buff%49)/3; if(w.process.size<size_now) if(!w.process.RellocBuff(size_now)) return false; w.process.size=size_now; char* p=w.process.buff; QByteArray ba = buffer.toLatin1(); char* q=ba.data(); for(size64 i=0;i<line;i++) { for(size64 j=0;j<16;j++) { sscanf(q,"%x",p); p++; q+=3; } q++; } for(size64 i=0;i<(size_buff%49)/3;i++) { sscanf(q,"%x",p); p++; q+=3; } return true; }
[ "gurthpalarran@outlook.com" ]
gurthpalarran@outlook.com
e10109c199c31dde45a4b01f62a1ff043c3beb7f
c485cb363d29d81212427d3268df1ddcda64d952
/dependencies/boost/libs/geometry/test/geometries/segment.cpp
0baa04166257b96b67b77a5f9724711cab34b648
[ "BSL-1.0" ]
permissive
peplopez/El-Rayo-de-Zeus
66e4ed24d7d1d14a036a144d9414ca160f65fb9c
dc6f0a98f65381e8280d837062a28dc5c9b3662a
refs/heads/master
2021-01-22T04:40:57.358138
2013-10-04T01:19:18
2013-10-04T01:19:18
7,038,026
2
1
null
null
null
null
UTF-8
C++
false
false
2,943
cpp
// Boost.Geometry (aka GGL, Generic Geometry Library) // Unit Test // Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2008-2011 Bruno Lalande, Paris, France. // Copyright (c) 2009-2011 Mateusz Loskot, London, UK. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <iostream> #include <geometry_test_common.hpp> #include <boost/geometry/geometries/concepts/segment_concept.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/geometries/segment.hpp> #include <boost/geometry/geometries/adapted/c_array.hpp> #include <boost/geometry/geometries/adapted/boost_tuple.hpp> #include <boost/geometry/util/write_dsv.hpp> #include <test_common/test_point.hpp> #include <test_geometries/custom_segment.hpp> BOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian) BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian) template <typename P> void test_all() { typedef bg::model::referring_segment<P> S; P p1; P p2; S s(p1, p2); BOOST_CHECK_EQUAL(&s.first, &p1); BOOST_CHECK_EQUAL(&s.second, &p2); // Compilation tests, all things should compile. BOOST_CONCEPT_ASSERT( (bg::concept::ConstSegment<S>) ); BOOST_CONCEPT_ASSERT( (bg::concept::Segment<S>) ); typedef typename bg::coordinate_type<S>::type T; typedef typename bg::point_type<S>::type SP; //std::cout << sizeof(typename coordinate_type<S>::type) << std::endl; typedef bg::model::referring_segment<P const> CS; //BOOST_CONCEPT_ASSERT( (concept::ConstSegment<CS>) ); CS cs(p1, p2); typedef typename bg::coordinate_type<CS>::type CT; typedef typename bg::point_type<CS>::type CSP; } template <typename S> void test_custom() { S seg; bg::set<0,0>(seg, 1); bg::set<0,1>(seg, 2); bg::set<1,0>(seg, 3); bg::set<1,1>(seg, 4); std::ostringstream out; out << bg::dsv(seg); BOOST_CHECK_EQUAL(out.str(), "((1, 2), (3, 4))"); } int test_main(int, char* []) { test_all<int[3]>(); test_all<float[3]>(); test_all<double[3]>(); //test_all<test_point>(); test_all<bg::model::point<int, 3, bg::cs::cartesian> >(); test_all<bg::model::point<float, 3, bg::cs::cartesian> >(); test_all<bg::model::point<double, 3, bg::cs::cartesian> >(); test_custom<test::custom_segment>(); test_custom<test::custom_segment_of<bg::model::point<double, 2, bg::cs::cartesian> > >(); test_custom<test::custom_segment_of<test::custom_point_for_segment> >(); test_custom<test::custom_segment_4>(); return 0; }
[ "fibrizo.raziel@gmail.com" ]
fibrizo.raziel@gmail.com
1c06ef905d1aec99ebafc9132994ecd003e404c0
67ac02b13fe6112bb7c56983dd3729e1b8d8c00a
/direct/psegd.cxx
f55e8110a7f3e6c2ee6904930884a9239cfdd9c0
[]
no_license
exafmm/old_fmm_vortex
c3a3f9e957d03797ec69e9ad054ac4600c6bae95
ae260e724d786031048157acce04542d4aac1e15
refs/heads/master
2020-04-17T17:59:13.554966
2019-01-21T12:11:37
2019-01-21T12:11:37
166,806,979
0
0
null
null
null
null
UTF-8
C++
false
false
1,157
cxx
#include "../misc/parameters.h" #include "../misc/constants.h" extern float *xi,*yi,*zi,*gxi,*gyi,*gzi,*vi; extern float *xj,*yj,*zj,*gxj,*gyj,*gzj,*vj,*sj; extern float *gxd,*gyd,*gzd; extern void memoryuse(); extern void memoryfree(); void dird(int n0, int n1, int n2, int n3) { int i,j; double gxdd,gydd,gzdd,dxij,dyij,dzij,rij,sij,rsij,cutoff; gxd = new float [npmax]; gyd = new float [npmax]; gzd = new float [npmax]; mem = npmax*3*4; memoryuse(); for( i=n0; i<=n1; i++ ) { gxdd = 0; gydd = 0; gzdd = 0; for( j=n2; j<=n3; j++ ){ #include "rij.cxx" sij = 2*sj[j]*sj[j]; cutoff = 4.0*vis/sij/pow(pi*sij,1.5)*exp(-rij/sij); gxdd +=(gxj[j]*vi[i]-gxi[i]*vj[j])*cutoff; gydd +=(gyj[j]*vi[i]-gyi[i]*vj[j])*cutoff; gzdd +=(gzj[j]*vi[i]-gzi[i]*vj[j])*cutoff; } gxd[i] = gxdd; gyd[i] = gydd; gzd[i] = gzdd; } for( i=0; i<npmax; i++ ) { gxi[i] = 0; gyi[i] = 0; gzi[i] = 0; } for( i=n0; i<=n1; i++ ) { gxi[i] = gxd[i]; gyi[i] = gyd[i]; gzi[i] = gzd[i]; } delete[] gxd; delete[] gyd; delete[] gzd; mem = npmax*3*4; memoryfree(); }
[ "rioyokota@gmail.com" ]
rioyokota@gmail.com
48dfb6713175b9a3b52406655cca356aae81c5dc
9bd54ee5690b03b6617538e36099fa29f7585169
/Item.h
2236a2aace51f12fcf85c582529ac1c19f9b222a
[]
no_license
ikageso1/MAGUROBO
10c92e13cb61e97d619292c7f1cdf302f87a2da4
b97ee6e4ab7842de65863a0461ac1be176d84b67
refs/heads/master
2020-09-24T02:32:08.007529
2019-12-03T14:34:49
2019-12-03T14:34:49
225,640,437
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
395
h
#pragma once #include "DxLib.h" class Player; class Character; class Item{ protected: VECTOR position; bool isAvailable; int ModelHandle; float angleSpeed; float r; // あたり判定の半径 float Angle; // 角度 public: Item(float x,float y,float z); bool CollCheck(Character *chara); void Draw(); bool GetAvailavle(); void Rotate(); virtual void Effect(Player *chara)=0; };
[ "tenma.yusuke.tp2@gmail.com" ]
tenma.yusuke.tp2@gmail.com
6cf4e34c91013c65f5b66f13b4f5caeec89418ea
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/git/gumtree/git_patch_hunk_3589.cpp
df0626efe114b2bfff662f8a7816095592f44513
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
829
cpp
*/ struct fragment *forward; struct fragment *reverse; int status; int used, used_1; - forward = parse_binary_hunk(&buffer, &size, &status, &used); + forward = parse_binary_hunk(state, &buffer, &size, &status, &used); if (!forward && !status) /* there has to be one hunk (forward hunk) */ - return error(_("unrecognized binary patch at line %d"), linenr-1); + return error(_("unrecognized binary patch at line %d"), state->linenr-1); if (status) /* otherwise we already gave an error message */ return status; - reverse = parse_binary_hunk(&buffer, &size, &status, &used_1); + reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1); if (reverse) used += used_1; else if (status) { /* * Not having reverse hunk is not an error, but having * a corrupt reverse hunk is.
[ "993273596@qq.com" ]
993273596@qq.com
468eda09d2a5cf0af20c39b286394895691bd60c
2e83a34664cbf86467bf3a03d559bf5017531824
/deps/boost-1.50.0/boost/mpl/vector/aux_/push_front.hpp
4c24929573ecc06c8d01f01d220f1118f33bd268
[ "BSL-1.0" ]
permissive
argv0/riak-cxx
34c85e87de5fe3e026d650f85cac9139f9dadb1c
7ade8b30a5ba86511b5dc10ab6989804bde8f86d
refs/heads/master
2020-05-17T20:19:25.076003
2012-08-15T23:23:47
2012-08-15T23:23:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,053
hpp
#ifndef BOOST_MPL_VECTOR_AUX_PUSH_FRONT_HPP_INCLUDED #define BOOST_MPL_VECTOR_AUX_PUSH_FRONT_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id: push_front.hpp 49267 2008-10-11 06:19:02Z agurtovoy $ // $Date: 2008-10-11 02:19:02 -0400 (Sat, 11 Oct 2008) $ // $Revision: 49267 $ #include <boost/mpl/push_front_fwd.hpp> #include <boost/mpl/aux_/config/typeof.hpp> #if defined(BOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES) # include <boost/mpl/vector/aux_/item.hpp> # include <boost/mpl/vector/aux_/tag.hpp> namespace riakboost { namespace mpl { template<> struct push_front_impl< aux::vector_tag > { template< typename Vector, typename T > struct apply { typedef v_item<T,Vector,1> type; }; }; }} #endif // BOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES #endif // BOOST_MPL_VECTOR_AUX_PUSH_FRONT_HPP_INCLUDED
[ "andy@andygross.org" ]
andy@andygross.org
fc5d22f204b072891b1af455605479ae792ed621
149799de87d600796076c5b7b39ecbcf4aef1bda
/c/STL/Vectors/Modifiers.cpp
9511847483f273300751c60a5d3f1d34c6ae0b28
[]
no_license
prashik856/Code
50dfca7a4a74fcdcf7659bc728ae099a431cd5ab
2422ba103661e3d26b2b2a95aa492cff7c7bff2f
refs/heads/master
2021-05-07T17:25:26.238208
2017-10-29T12:54:41
2017-10-29T12:54:41
108,732,043
0
0
null
null
null
null
UTF-8
C++
false
false
522
cpp
#include<iostream> #include<vector> using namespace std; int main(){ vector <int> g1; vector <int> g2; vector <int> g3; g1.assign(5,10); vector <int> :: iterator it; it=g1.begin()+1; g2.assign(it,g1.end()-1); //Assigning using an array int gquiz[]={1,2,3}; g3.assign(gquiz,gquiz+2); for(int i=0; i<g1.size(); i++){ cout << g1[i] << " " << endl; } cout << endl; for(int i=0; i<g2.size(); i++){ cout << g2[i] << " " << endl; } cout << endl; for(int i=0; i<g3.size(); i++){ cout << g3[i] << " " << endl; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
19984ef894718a91d6583bed1c62c892dc607e2c
2e2271f0bf570f09267f1749981e66cec5ae6f84
/Queue.cpp
dc6e30d6c123ecb1d3de260dc64ecfc4b6eda755
[]
no_license
oguzhanaknc/Veri-Yapilari
29f56bf754b1cf01c2fd038743ac6b6139ebdd94
4a75f4c5e0c1400e7537fe61d3cdcc187d16b467
refs/heads/master
2022-12-31T15:56:03.288141
2020-10-10T18:21:00
2020-10-10T18:21:00
297,357,927
0
0
null
null
null
null
UTF-8
C++
false
false
3,023
cpp
/* * Author : Oğuzhan Akıncı * 29.09.2020 * Email: oguzhanaknc06@gmail.com */ #include <iostream> #include <stdlib.h> using namespace std; template<class T> class Queue{ private: // düğüm yapımızı oluşturduğumuz kısım. ( kutular ) struct n{ T x; n* next; }; typedef n node; node * root = (node *)malloc(sizeof(node)); //kök kutumuzu oluşturuyoruz. node * iter = (node *)malloc(sizeof(node)); // gezgin kutumuz. node * tail = (node *)malloc(sizeof(node)); // Sondan bir önceki kutu. public: // Construactor fonksyonumuzda kök elemanımızın değerlerini atıyor ve gezgin kutumuzu root'a eşitliyoruz. Queue(){ root->next = NULL; root->x = NULL; iter = root; tail = root; } //sona veri ekleme fonksyonu. parametre olarak eklenecek veriyi alıyor. void Push(T data){ if (root->x == NULL){ //eğer daha önce veri eklenmemişse onu root'a ver diyoruz. root->x = data; }else{ //eğer veri eklenmişse while (iter->next != NULL){ //son elemana kadar gezgin kutumuz gezsin. iter = iter->next; } iter->next = (node *)malloc(sizeof(node)); //ve en sona yeni bir düğüm (kutu) oluştursun. iter->next->x = data; //oluşan kutuya değerleri atayalım. tail = iter; // son kutuyu kaydırıyoruz. iter->next->next = NULL; } resetIter(); // gezgin kutumuzu tekrar root'a eşitleyeylim. } //ekrana yazdırma fonksyonu parametresi yok. void yaz(){ resetIter(); while (iter != NULL){ //son elemana kadar gezgin node (kutu) ilerliyor. cout << iter->x << endl; //her elemanın değerini yazdırıyor. iter = iter->next; } } // gezgin elemanı başa alma fonksyonu. void resetIter(){ iter = root; } // Pop() Son ilk sil ve döndür. T Pop() { resetIter(); //gezgin kutuyu sıfırla if (root->x == NULL){ //liste dolu mu boş mu bak. cout << "Boş Stack Silinemez..." << endl; return -1; } node * temp; //temp oluştur T tempdata; temp = root; //root'u bir kaydırıyoruz. tempdata = root->x; root = root->next; free(temp); //temp'i hafızadan sil resetIter(); // gezgini sıfırla return tempdata; // değeri döndür } // Top() ilk veriyi silmeden döndür. T Top(){ return root->x; } }; int main() { //tam sayılarla işlem yapmak Queue<int> liste; liste.Push(9); liste.Push(98); liste.Push(12); liste.Push(182); liste.Push(99); // bağlı listeye eleman eklemek. liste.yaz(); cout << "*/*/*/*/*/*/" << endl; cout << liste.Pop() << endl; // veri silme fonksyonu cout << "*/*/*/*/*/*/" << endl; liste.yaz(); cout << "*/*/*/*/*/*/" << endl; cout << liste.Top() << endl; return 0; }
[ "oguzzhanakinci@gmail.com" ]
oguzzhanakinci@gmail.com
9782f68cf85a8c78e0348cade95a30b6b673a0e2
c12eb4f81fc8394074ea9c54abda788c01c7c801
/CSE4095_HW1/buffile.cpp
7cc6e72301f3d04808c51c86f801d1973bc0b8ae
[]
no_license
shs1566/CSE4095_HW1
cf3f3189466511fbc6b5e776e95b11ec069decdd
3fe87c74c4d7a141f6882997b0dba4792b008577
refs/heads/master
2020-03-28T22:25:50.544675
2018-10-09T13:37:06
2018-10-09T13:37:06
149,232,351
4
0
null
null
null
null
UTF-8
C++
false
false
2,256
cpp
// buffile.cc #include "buffile.h" BufferFile::BufferFile (IOBuffer & from) // create with a buffer : Buffer (from) { } int BufferFile::Open (char * filename, int mode) // open an existing file and check the header // a correct header must be on the file // use ios::nocreate to ensure that a file exists { // these modes are not allowed when opening an existing file if (mode&ios::trunc) return FALSE; File . open (filename, mode|ios::in|ios::binary); if (! File.good()) return FALSE; File . seekg(0, ios::beg); File . seekp(0, ios::beg); HeaderSize = ReadHeader(); if (!HeaderSize) // no header and file opened for output return FALSE; File . seekp (HeaderSize, ios::beg); File . seekg (HeaderSize, ios::beg); return File . good(); } int BufferFile::Create (char * filename, int mode) // create a new file and write a header on it. // use ios::nocreate to ensure that no file exists { if (!(mode & ios::out)) return FALSE; // must include ios::out File . open (filename, mode|ios::in|ios::out|ios::binary); if (!File . good()) { File . close(); return FALSE; } HeaderSize = WriteHeader (); return HeaderSize != 0; } int BufferFile::Close () { File . close(); return TRUE; } int BufferFile::Rewind () { File . seekg (HeaderSize, ios::beg); File . seekp (HeaderSize, ios::beg); return 1; } // Input and Output operations int BufferFile::Read (int recaddr) // read a record into the buffer // return the record address // return <0 if read failed // if recaddr == -1, read the next record in the File // if recaddr != -1, read the record at that address { if (recaddr == -1) return Buffer . Read (File); else return Buffer . DRead (File, recaddr); } int BufferFile::Write (int recaddr) // write the current buffer contents { if (recaddr == -1) return Buffer . Write (File); else return Buffer . DWrite (File, recaddr); } int BufferFile::Append () // write the current buffer at the end of File { File . seekp (0, ios::end); return Buffer . Write (File); } // Access to IOBuffer IOBuffer & BufferFile::GetBuffer () { return Buffer;} // protected methods int BufferFile::ReadHeader () { return Buffer . ReadHeader (File); } int BufferFile::WriteHeader () { return Buffer . WriteHeader (File); }
[ "shs1566@naver.com" ]
shs1566@naver.com
ad24d6cbb094b7f5ec7e964eb9edad15ef82e664
73021632961fdecde46ac51b2424ecdb2b8fec16
/hash_table.cpp
971d0ab1f2bb886cd8c554ca6526cdbcda97fefb
[]
no_license
ReddyNick/Hash_table
2a6f6eec23f4cb10ca45ebeb855ab1069d8a4928
a8f0614046b68e6bb66255a9e9dc7bc280a35c72
refs/heads/master
2020-05-09T15:23:47.189638
2019-04-13T21:51:10
2019-04-13T21:51:10
181,231,934
0
0
null
null
null
null
UTF-8
C++
false
false
3,330
cpp
#include "hash_table.h" #include "stdio.h" #include "string.h" #include "assert.h" #include <string> int (*func[MAX_func])(char*); int (*gethash)(char*); int Htable::Insert(char *str) { int key = gethash(str); insert_k(str, key); return 0; } int Htable::insert_k(char *str, int key) { if (table[key] == nullptr) { Node* num = new Node; table[key] = num; } Node* ptr = table[key]; bool already_exist = false; while(ptr->next != nullptr && !already_exist) { ptr = ptr->next; if (strcmp(ptr->str, str) == 0) { ptr->data++; already_exist = true; } } if (!already_exist) { table[key]->data++; Node *node = new Node; strcpy(node->str, str); ptr->next = node; } return 0; } int Htable::Find(char *str) { int key = gethash(str); Node* ptr = table[key]; while(ptr != nullptr) { if (!strcmp(ptr->str, str)) return 1; ptr = ptr->next; } return 0; } int Htable::Del() { for(int i = 0; i < KEY_MAX; i++) { while(table[i] != nullptr) { Node* ptr = table[i]; table[i] = table[i]->next; delete ptr; } } } int Htable::Write_info(FILE* out) { for (int i = 0; i < KEY_MAX; i++) { if (table[i] == nullptr) fprintf(out,"0; "); else fprintf(out, "%d; ", table[i]->data); } fprintf(out, "\n"); return 0; } int Htable::read_write(FILE *in, FILE* out) { char str[MAX_STR]; func[0] = geth1; func[1] = geth2; func[2] = geth3; func[3] = geth4; func[4] = geth5; func[5] = MD5_to_int; func[6] = Sha_1; func[7] = Keccak_func; for(int i = 0; i < MAX_func; i++) { gethash = func[i]; rewind(in); while (fscanf(in, " %s ", str) != -1) Insert(str); Write_info(out); Del(); } return 0; } Htable::~Htable() { for(int i = 0; i < KEY_MAX; i++) { while(table[i] != nullptr) { Node* ptr = table[i]; table[i] = table[i]->next; delete ptr; } } } int geth1(char *str) { return 0; } int geth2(char *str) { assert(str != NULL); return (unsigned char)str[0] % KEY_MAX; } int geth3(char *str) { return strlen(str)% KEY_MAX; } int geth4(char *str) { int size = strlen(str); int res = 0; for (int i = 0; i < size - 1; i++) res += (unsigned char)str[i]; return res % KEY_MAX; } int geth5(char *str) { int size = strlen(str); unsigned int hash = str[0]; for (int i = 1; i < size; i++) { hash = ((hash << 31) | (hash >> 1)) ^ str[i]; } return hash % KEY_MAX; } int geth_string(std::string str) { int size = str.size(); unsigned int hash = str[0]; for (int i = 1; i < size; i++) { hash = ((hash << 31) | (hash >> 1)) ^ str[i]; } return hash % KEY_MAX; } int MD5_to_int(char *str) { hash2::MD5 make_hash; return geth_string(make_hash(str)); } int Sha_1(char *str) { SHA1 sh1; return geth_string(sh1(str)); } int Keccak_func(char *str) { Keccak kec; return geth_string(kec(str)); }
[ "mango.syrup@yandex.ru" ]
mango.syrup@yandex.ru
bfc1b451dbc645de828953b9fb646031165614f9
0a39f0e7efdb9e1bcddc038c10cbaa4d35fc9005
/Problem_024.cpp
661d6a0684cadfaf053b9709132be3c33f60f025
[]
no_license
pantDevesh/1ProblemEveryday
39374e58458c4816474f83c108fcf25079a2bd07
a3d7d041242d30553c1445fd0bf6bff215b5f7d7
refs/heads/main
2023-02-05T02:16:35.402121
2020-12-25T15:06:46
2020-12-25T15:06:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,062
cpp
// { Driver Code Starts #include <bits/stdc++.h> using namespace std; // Longest Consecutive Subsequence int findLongestConseqSubseq(int arr[], int n); // Driver program int main() { int t, n, i, a[100001]; cin >> t; while (t--) { cin >> n; for (i = 0; i < n; i++) cin >> a[i]; cout << findLongestConseqSubseq(a, n) << endl; } return 0; }// } Driver Code Ends // arr[] : the input array // N : size of the array arr[] // return the length of the longest subsequene of consecutive integers int findLongestConseqSubseq(int arr[], int N) { //Your code here int hash[100005] = {0}; int maxi = -1; for (int i = 0; i < N; i++) { hash[arr[i]]++; maxi = max(arr[i], maxi); } int ans = 0, MaxSoFar = 0; for (int i = 1; i <= maxi; i++) { if (hash[i] && hash[i - 1]) MaxSoFar++; else { ans = max(ans, MaxSoFar); MaxSoFar = 0; } } ans = max(ans, MaxSoFar); return ans + 1; }
[ "deveshpant43@gmail.com" ]
deveshpant43@gmail.com
ccd808df940225586292685c1a62739a580a5426
158ddb941e92de48e458cdc55a8868f26befb5b9
/0.3/p
09b4d1dc656a998a29c6b25bb312bff184c6771e
[]
no_license
numeric-bhusan/cavity-test
a73e4d453847403998714398a24a1556273efa1a
3856ea931ba687a1da321bdbf0aa66c8c7202543
refs/heads/master
2023-09-05T08:21:52.212790
2021-11-04T16:39:06
2021-11-04T16:39:06
424,660,149
0
0
null
null
null
null
UTF-8
C++
false
false
5,141
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v2012 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.3"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 400 ( 3.75947e-06 -0.00582251 -0.0129591 -0.0184103 -0.0204271 -0.0182331 -0.0117689 -0.00147943 0.0118405 0.0271509 0.0432448 0.0588221 0.0725767 0.0833058 0.09005 0.0922645 0.0900243 0.0842436 0.0768817 0.071069 0.00578141 -0.000216709 -0.00580162 -0.00953954 -0.0105955 -0.00842902 -0.00296636 0.00547727 0.0163053 0.0287133 0.0417505 0.0543859 0.0655858 0.0744089 0.0801192 0.0823151 0.0810772 0.0770557 0.071276 0.0653205 0.0133343 0.00503406 -0.00099401 -0.00442119 -0.00527058 -0.00326136 0.00160494 0.00902998 0.0185041 0.0293508 0.0407664 0.0518701 0.0617687 0.0696364 0.0748071 0.0768785 0.0758426 0.0720877 0.0658083 0.0575394 0.0201373 0.00869543 0.00122642 -0.0026673 -0.00372044 -0.00188337 0.00273334 0.00978661 0.0187822 0.0290966 0.0399932 0.0506549 0.0602337 0.0679167 0.0730041 0.0750027 0.0737676 0.0694586 0.0616066 0.0501076 0.0244991 0.00977206 0.000589898 -0.00398607 -0.00530089 -0.00350567 0.00117659 0.00833651 0.0174639 0.0279509 0.0390866 0.0500714 0.0600502 0.0681664 0.0736279 0.0757996 0.0743714 0.0692929 0.0595299 0.0445431 0.0251749 0.00714893 -0.00380195 -0.00905639 -0.0105108 -0.00849824 -0.00335481 0.00443159 0.0143156 0.0256813 0.037816 0.0499054 0.06105 0.070305 0.0767367 0.0795193 0.0781419 0.0723372 0.0605441 0.0418965 0.0210911 -0.000263033 -0.0129341 -0.0187082 -0.0200281 -0.0174118 -0.0113159 -0.002317 0.00899327 0.0219791 0.0359126 0.0499472 0.0631148 0.0743479 0.0825245 0.0865724 0.0857241 0.0794511 0.0656254 0.0430783 0.0111417 -0.013618 -0.0278739 -0.0338525 -0.0346012 -0.0308547 -0.0232097 -0.0123417 0.00110849 0.0164876 0.0330563 0.0499373 0.0660869 0.0802932 0.091204 0.0974334 0.097874 0.0916403 0.0759014 0.0491229 -0.00596646 -0.034265 -0.0498679 -0.055546 -0.0550871 -0.049511 -0.0395895 -0.026109 -0.00975254 0.00882768 0.0289057 0.0495981 0.0698019 0.0881587 0.103051 0.112705 0.115554 0.110196 0.0928391 0.0614172 -0.0318542 -0.0638731 -0.0804136 -0.0850036 -0.0824162 -0.074074 -0.0609761 -0.0440314 -0.023946 -0.00133127 0.0231512 0.0486665 0.0741008 0.0979771 0.1184 0.13313 0.139993 0.136822 0.118445 0.0819387 -0.0686621 -0.104599 -0.12134 -0.123585 -0.117511 -0.105121 -0.0877127 -0.0663196 -0.0416307 -0.0141492 0.015612 0.0469595 0.0788617 0.109799 0.137629 0.15959 0.172731 0.173782 0.155524 0.113575 -0.119395 -0.159351 -0.174909 -0.172752 -0.161142 -0.142923 -0.119753 -0.0927705 -0.0625706 -0.0294406 0.0063802 0.0444804 0.0840617 0.123709 0.161142 0.193091 0.215672 0.224081 0.208054 0.160635 -0.188619 -0.232234 -0.243932 -0.233942 -0.213688 -0.187148 -0.156366 -0.122494 -0.0858906 -0.0464647 -0.00400696 0.0415461 0.089849 0.139836 0.189325 0.234694 0.271079 0.291668 0.281745 0.229777 -0.283964 -0.329296 -0.331825 -0.308274 -0.274703 -0.236434 -0.195758 -0.153603 -0.109833 -0.0637374 -0.0144301 0.0388709 0.0965613 0.158283 0.22238 0.285293 0.341401 0.381578 0.384916 0.331835 -0.419308 -0.459663 -0.442343 -0.395786 -0.342123 -0.287734 -0.23461 -0.182923 -0.131602 -0.0789772 -0.0232061 0.0374829 0.10456 0.178844 0.259867 0.344975 0.42862 0.499703 0.529677 0.485392 -0.620522 -0.636736 -0.578671 -0.494188 -0.411235 -0.335653 -0.267775 -0.205971 -0.14753 -0.0893754 -0.0284182 0.038356 0.113814 0.200478 0.299981 0.41203 0.533033 0.651778 0.732773 0.722396 -0.935915 -0.878508 -0.741736 -0.597944 -0.474389 -0.372655 -0.288864 -0.217757 -0.153947 -0.0924568 -0.0287097 0.0417033 0.123271 0.220724 0.338931 0.482159 0.652 0.841345 1.01527 1.0975 -1.47642 -1.20663 -0.920499 -0.691385 -0.517302 -0.387541 -0.290058 -0.213333 -0.148118 -0.087209 -0.0245705 0.0454649 0.128945 0.233077 0.367109 0.542683 0.771297 1.05932 1.40329 1.73014 -2.53964 -1.63054 -1.04444 -0.710957 -0.49575 -0.352092 -0.254529 -0.18358 -0.126165 -0.0735893 -0.0192622 0.0427943 0.11922 0.21879 0.354819 0.547989 0.826397 1.23658 1.91168 2.92419 -4.36666 -2.04463 -0.973541 -0.563181 -0.357847 -0.240147 -0.170119 -0.123781 -0.0874778 -0.0535051 -0.0166477 0.0276685 0.084616 0.161738 0.272419 0.442106 0.718225 1.22571 2.41104 4.84853 ) ; boundaryField { movingWall { type zeroGradient; } fixedWalls { type zeroGradient; } frontAndBack { type empty; } } // ************************************************************************* //
[ "mailniladri5@gmail.com" ]
mailniladri5@gmail.com
d16c270c7313e5a4beb413451440aa1918fdbed2
56d3249264f4275141b67bfd3715353074c6c225
/src/logger/logger.cpp
7f300441d6ed4bece28e6144c0f4b5a9fbf9fc85
[ "MIT" ]
permissive
REXUS-PIOneERS/CPP_PIOneERS
56f807caa841c9b1f608c9163dc1fddbe8ed1894
858fa8805926c70e8b09ad868550644be67c9896
refs/heads/master
2021-10-02T20:19:56.102078
2018-11-30T13:11:48
2018-11-30T13:11:48
103,388,929
0
0
MIT
2018-11-30T13:11:49
2017-09-13T10:58:10
Objective-C
UTF-8
C++
false
false
1,420
cpp
/** * REXUS PIOneERS - Pi_1 * camera.cpp * Purpose: Implementation of functions in the PiCamera class * * @author David Amison * @version 2.0 10/10/2017 */ #include <string> #include <sstream> #include <stdint.h> #include <fstream> #include <iomanip> #include "logger.h" #include "timing/timer.h" std::string time(Timer tmr) { std::stringstream ss; uint64_t time = tmr.elapsed(); int hr = time / 3600000; time -= hr * 3600000; int min = time / 60000; time -= min * 60000; int sec = time / 1000; time -= sec * 1000; ss << std::setfill('0') << std::setw(2) << hr << ":" << min << ":" << sec << ":" << time; return ss.str(); } Logger::Logger(std::string filename) { _filename = filename; } void Logger::start_log() { _tmr.reset(); std::ostringstream ss; ss << _filename << ".txt"; _this_filename = ss.str(); _outf.open(_this_filename, std::ofstream::app); _outf << "\n[New run of log file at " << Timer::str_datetime() << "]\n" << std::endl; } void Logger::child_log() { std::stringstream ss; ss << _filename << "_child.txt"; _this_filename = ss.str(); _outf.close(); _outf.clear(); _outf.open(_this_filename, std::ofstream::app); _outf << "\n[New run of log file at " << Timer::str_datetime() << "]\n" << std::endl; } std::ostream& Logger::operator()(std::string str) { return _outf << std::endl << str << "(" << time(_tmr) << "): "; } void Logger::stop_log() { _outf.close(); }
[ "david.amison20@gmail.com" ]
david.amison20@gmail.com
6299db158b1bce6044846f7197a4ccba429d1bd2
a90d9373304c4ec4b3ea8ec46314bf02e9b2e864
/omg/include/omg/enums.h
9c4922abc5f8f62f173cf3095e465de59f10a338
[]
no_license
charlie-x/epsilon
084668654b1de8cce292ad9ede63fd02e10d5419
e4c3a98b24c2c407dac3b03332da4fb2c625b1e5
refs/heads/master
2023-06-08T19:59:28.898004
2023-01-30T10:11:19
2023-01-31T14:17:54
256,359,479
0
0
null
2020-04-17T00:16:41
2020-04-17T00:16:41
null
UTF-8
C++
false
false
170
h
#ifndef OMG_ENUMS_H #define OMG_ENUMS_H #include <stdint.h> namespace OMG { enum class Base : uint8_t { Binary = 2, Decimal = 10, Hexadecimal = 16 }; } #endif
[ "31415152+EmilieNumworks@users.noreply.github.com" ]
31415152+EmilieNumworks@users.noreply.github.com
9acbe1667f9d4f642679b4cec9b04c362d005140
afd697a5f9f34f09656d1bd2249565e56ceb970a
/src/main.cpp
193bc52df2e39bc850b953e3311b0d3eaeb2b2e8
[ "MIT" ]
permissive
ayaromenok/TimeLapseCamera_Stereo
1beea4cf45ee4b7834b64fc978cb78597e5bb084
f6224fb1eee9204aa0976d94241a1bbd27f282b0
refs/heads/master
2020-05-14T15:42:32.318153
2019-04-29T10:12:11
2019-04-29T10:12:11
181,858,750
0
1
null
null
null
null
UTF-8
C++
false
false
694
cpp
// Copyright(C) 2019 Andrey Yaromenok, ayaromenok@gmail.com // MIT License // https://raw.githubusercontent.com/ayaromenok/TimeLapseCamera_Stereo/master/LICENSE #include <QApplication> #include <QDebug> #include "yastereowidget.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); QApplication::setOrganizationName("Andrey Yaromenok"); QApplication::setOrganizationDomain("andreyayromenok.info"); QApplication::setApplicationName("TimeLapse Camera for Stereo"); QApplication::setApplicationVersion("0.1.a"); qInfo() << QApplication::applicationName() << QApplication::applicationVersion(); YaStereoWidget sw; sw.show(); return a.exec(); }
[ "ayaromenok@gmail.com" ]
ayaromenok@gmail.com
a5722ebacbb0f3c097861205aae48a270cc1d3b6
1a0e4d4d7989644cad2783bf5f123c7b7e56f8d1
/Chapter_2/2_3/main.cpp
21362de0774866bb2f63362b5c2138e9c95a049f
[]
no_license
84rn/kr_exercises
ad2f1ed32e344190c5e28112ca0453731986a6e4
8bef3ca5b4c4b6cf86375dd1028b09bf9709806a
refs/heads/master
2020-06-01T06:34:04.264134
2015-03-03T17:07:25
2015-03-03T17:07:25
31,023,894
0
0
null
null
null
null
UTF-8
C++
false
false
729
cpp
#include <cstdio> int htoi(char[]); int main(void) { printf("0xFFFF =\t%d\n", htoi("0xFFFF")); printf("FFFF =\t\t%d\n", htoi("FFFF")); printf("0xabCD =\t%d\n", htoi("0xabCD")); printf("AbCD =\t\t%d\n", htoi("AbCD")); printf("0XBEEF =\t%d\n", htoi("0XBEEF")); printf("000BEEF =\t%d\n", htoi("000BEEF")); return 0; } int htoi(char num[]) { int i = 0, n = 0; while (num[i] != '\0') { if (num[i] >= '0' && num[i] <= '9') { n = 16 * n + num[i] - '0'; } else if (num[i] >= 'A' && num[i] <= 'F') { n = 16 * n + num[i] - 'A' + 10; } else if (num[i] >= 'a' && num[i] <= 'f') { n = 16 * n + num[i] - 'a' + 10; } else if (num[i] == 'X' || num[i] == 'x') { n = 0; } ++i; } return n; }
[ "barbart1@gmail.com" ]
barbart1@gmail.com
0ed3cdb8cf42cd4848e4dbed74f883718f7bd200
5bb3a620c66749e0ce3dfbd0cd8692d40928dbf3
/arduino/hardware/espressif/esp32/libraries/WiFi/src/WiFiAP.cpp
19cb5fe5b586c05b4b7fb9f48b31a4353003bab6
[ "MIT" ]
permissive
wyolum/ClockIOT
6ce2a4605435f27e8d7eca4c2f219e97c5966cc5
52a1bf8e1acc3a5ad8314211ef3bc23186b3be89
refs/heads/master
2022-12-12T22:18:05.952206
2020-02-05T17:32:22
2020-02-05T17:32:22
126,251,414
5
2
MIT
2022-12-10T12:46:21
2018-03-21T23:10:27
C
UTF-8
C++
false
false
8,565
cpp
/* ESP8266WiFiSTA.cpp - WiFi library for esp8266 Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Reworked on 28 Dec 2015 by Markus Sattler */ #include "WiFi.h" #include "WiFiGeneric.h" #include "WiFiAP.h" extern "C" { #include <stdint.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <string.h> #include <esp_err.h> #include <esp_wifi.h> #include <esp_event_loop.h> #include <lwip/ip_addr.h> #include "apps/dhcpserver_options.h" } // ----------------------------------------------------------------------------------------------------------------------- // ---------------------------------------------------- Private functions ------------------------------------------------ // ----------------------------------------------------------------------------------------------------------------------- static bool softap_config_equal(const wifi_config_t& lhs, const wifi_config_t& rhs); /** * compare two AP configurations * @param lhs softap_config * @param rhs softap_config * @return equal */ static bool softap_config_equal(const wifi_config_t& lhs, const wifi_config_t& rhs) { if(strcmp(reinterpret_cast<const char*>(lhs.ap.ssid), reinterpret_cast<const char*>(rhs.ap.ssid)) != 0) { return false; } if(strcmp(reinterpret_cast<const char*>(lhs.ap.password), reinterpret_cast<const char*>(rhs.ap.password)) != 0) { return false; } if(lhs.ap.channel != rhs.ap.channel) { return false; } if(lhs.ap.ssid_hidden != rhs.ap.ssid_hidden) { return false; } if(lhs.ap.max_connection != rhs.ap.max_connection) { return false; } return true; } // ----------------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------- AP function ----------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------------- /** * Set up an access point * @param ssid Pointer to the SSID (max 63 char). * @param passphrase (for WPA2 min 8 char, for open use NULL) * @param channel WiFi channel number, 1 - 13. * @param ssid_hidden Network cloaking (0 = broadcast SSID, 1 = hide SSID) * @param max_connection Max simultaneous connected clients, 1 - 4. */ bool WiFiAPClass::softAP(const char* ssid, const char* passphrase, int channel, int ssid_hidden, int max_connection) { if(!WiFi.enableAP(true)) { // enable AP failed return false; } if(!ssid || *ssid == 0 || strlen(ssid) > 31) { // fail SSID too long or missing! return false; } if(passphrase && (strlen(passphrase) > 63 || strlen(passphrase) < 8)) { // fail passphrase to long or short! return false; } esp_wifi_start(); wifi_config_t conf; strcpy(reinterpret_cast<char*>(conf.ap.ssid), ssid); conf.ap.channel = channel; conf.ap.ssid_len = strlen(ssid); conf.ap.ssid_hidden = ssid_hidden; conf.ap.max_connection = max_connection; conf.ap.beacon_interval = 100; if(!passphrase || strlen(passphrase) == 0) { conf.ap.authmode = WIFI_AUTH_OPEN; *conf.ap.password = 0; } else { conf.ap.authmode = WIFI_AUTH_WPA2_PSK; strcpy(reinterpret_cast<char*>(conf.ap.password), passphrase); } wifi_config_t conf_current; esp_wifi_get_config(WIFI_IF_AP, &conf_current); if(!softap_config_equal(conf, conf_current) && esp_wifi_set_config(WIFI_IF_AP, &conf) != ESP_OK) { return false; } return true; } /** * Configure access point * @param local_ip access point IP * @param gateway gateway IP * @param subnet subnet mask */ bool WiFiAPClass::softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet) { if(!WiFi.enableAP(true)) { // enable AP failed return false; } esp_wifi_start(); tcpip_adapter_ip_info_t info; info.ip.addr = static_cast<uint32_t>(local_ip); info.gw.addr = static_cast<uint32_t>(gateway); info.netmask.addr = static_cast<uint32_t>(subnet); tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP); if(tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_AP, &info) == ESP_OK) { dhcps_lease_t lease; lease.enable = true; lease.start_ip.addr = static_cast<uint32_t>(local_ip) + (1 << 24); lease.end_ip.addr = static_cast<uint32_t>(local_ip) + (11 << 24); tcpip_adapter_dhcps_option( (tcpip_adapter_option_mode_t)TCPIP_ADAPTER_OP_SET, (tcpip_adapter_option_id_t)REQUESTED_IP_ADDRESS, (void*)&lease, sizeof(dhcps_lease_t) ); return tcpip_adapter_dhcps_start(TCPIP_ADAPTER_IF_AP) == ESP_OK; } return false; } /** * Disconnect from the network (close AP) * @param wifioff disable mode? * @return one value of wl_status_t enum */ bool WiFiAPClass::softAPdisconnect(bool wifioff) { bool ret; wifi_config_t conf; *conf.ap.ssid = 0; *conf.ap.password = 0; ret = esp_wifi_set_config(WIFI_IF_AP, &conf) == ESP_OK; if(wifioff) { ret = WiFi.enableAP(false) == ESP_OK; } return ret; } /** * Get the count of the Station / client that are connected to the softAP interface * @return Stations count */ uint8_t WiFiAPClass::softAPgetStationNum() { wifi_sta_list_t clients; if(esp_wifi_ap_get_sta_list(&clients) == ESP_OK) { return clients.num; } return 0; } /** * Get the softAP interface IP address. * @return IPAddress softAP IP */ IPAddress WiFiAPClass::softAPIP() { tcpip_adapter_ip_info_t ip; tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &ip); return IPAddress(ip.ip.addr); } /** * Get the softAP interface MAC address. * @param mac pointer to uint8_t array with length WL_MAC_ADDR_LENGTH * @return pointer to uint8_t* */ uint8_t* WiFiAPClass::softAPmacAddress(uint8_t* mac) { esp_wifi_get_mac(WIFI_IF_AP, mac); return mac; } /** * Get the softAP interface MAC address. * @return String mac */ String WiFiAPClass::softAPmacAddress(void) { uint8_t mac[6]; char macStr[18] = { 0 }; esp_wifi_get_mac(WIFI_IF_AP, mac); sprintf(macStr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); return String(macStr); } /** * Get the softAP interface Host name. * @return char array hostname */ const char * WiFiAPClass::softAPgetHostname() { const char * hostname; if(tcpip_adapter_get_hostname(TCPIP_ADAPTER_IF_AP, &hostname)) { return NULL; } return hostname; } /** * Set the softAP interface Host name. * @param hostname pointer to const string * @return true on success */ bool WiFiAPClass::softAPsetHostname(const char * hostname) { return tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_AP, hostname) == ESP_OK; } /** * Enable IPv6 on the softAP interface. * @return true on success */ bool WiFiAPClass::softAPenableIpV6() { return tcpip_adapter_create_ip6_linklocal(TCPIP_ADAPTER_IF_AP) == ESP_OK; } /** * Get the softAP interface IPv6 address. * @return IPv6Address softAP IPv6 */ IPv6Address WiFiAPClass::softAPIPv6() { static ip6_addr_t addr; if(tcpip_adapter_get_ip6_linklocal(TCPIP_ADAPTER_IF_AP, &addr)) { return IPv6Address(); } return IPv6Address(addr.addr); }
[ "wyojustin@gmail.com" ]
wyojustin@gmail.com
cc28152ebdd8690e1ed9b251d3b82b7937651433
c801f272839fb6fe2e3f2dfee9e433bfe872e8ac
/inc/Util/dorkestProfiler.h
5e1f11b22ac1f4f5d9f70be2b2a4a2fee0cb1606
[]
no_license
MrWisski/DorkestEngine
171a88d674ce2856ab466e39619b8bda25c7f927
97660822d8acdb0fb900d2edd26a653a736de65e
refs/heads/master
2023-07-18T11:11:50.022807
2021-09-06T15:10:36
2021-09-06T15:10:36
370,745,490
0
0
null
null
null
null
UTF-8
C++
false
false
8,589
h
/* Name : Dorkest Profiler System Created : 5/26/2021 Author : MrWisski License : (WISSKI-1) Copyright 2012 - 2021 Alex Wisnieski AKA MrWisski Permission is hereby granted, free of charge, to any person (hereafter "You") obtaining a copy or portion of this software, its resulting compilation products, or associated documentation files (hereafter "Software"), to deal in the Software with the following restrictions, using the following terminology : TERMINOLOGY : 1) COMMERCIAL : Any use of the Software in which You, or others recieve compensation for any reason, of any kind. RESTRICTIONS : 1) You MAY use, copy, publish, distribute, and/or merge, this Software, with any project or library or software, that is not COMMERCIAL in nature or intent. 2) You MAY NOT use, copy, publish, distribute, redistribute, sublicense, merge and/or sell copies of any software including partially, containing whole, or any portion of the Software, nor permit persons to whom the Software is furnished to do so for COMMERCIAL uses. 3) Derivations of the Software are permitted, provided the above copyright notice and this permission notice are NOT modified, with the exception of character encoding changes that do not substantially change the intent of the notice or the above copyright notice, or the readibility or useability of this permission notice or the above copyright notice, except for COMMERCIAL uses. 4) You MAY NOT imply endorsement of any product that includes or derives from the Software, by any any person or group of people involved in the creation of the Software without direct written permission from said persons or group of people. 5) You MAY NOT use the legal names, handles, aliases, or nicknames of any person involved in the creation of the Software, to promote any product derived from, or using the Software in any way, without written permission from said persons. The above copyright notice and this permission notice shall be included in all copies or portions of the Software. Any of the above restrictions which are unlawful or not permitted, whole or in part, in the jurisdiction You live in will not affect the rest of the portion of the restriction it exists in, the other restrictions listed in this permission notice. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. CERTAIN JURISDICTIONS DO NOT ALLOW LIMITATIONS ON IMPLIED WARRANTIES OR THE EXCLUSION OR LIMITATION OF CERTAIN DAMAGES. IF YOU RESIDE IN SUCH A JURISDICTION, SOME OR ALL OF THE ABOVE DISCLAIMERS, EXCLUSIONS, OR LIMITATIONS MAY NOT APPLY TO YOU, AND YOU MAY HAVE ADDITIONAL RIGHTS. THE LIMITATIONS OR EXCLUSIONS OF WARRANTIES, REMEDIES, OR LIABILITY CONTAINED IN THESE TERMS APPLY TO YOU TO THE FULLEST EXTENT SUCH LIMITATIONS OR EXCLUSIONS ARE PERMITTED UNDER THE LAWS OF THE JURISDICTION IN WHICH YOU ARE LOCATED. */ #pragma once #include "Log.h" #include <windows.h> #include <profileapi.h> #include <errhandlingapi.h> #include <algorithm> /// <summary> /// The main profiling class. /// This singleton contains all the machinery to recognize, ///catalog, and report on DataPoint tags you've created. The tags persist, so every ///time execution loops through your datapoint constructor and destructor, a new ///datapoint is collected! /// /// NOTE : I really won't make any assurances as to the ///speed of the profiler.Really, I don't nest datapoints, or I take them with a LARGE ///grain of sugar - profiler is NOT optimized, and only the area between construction of ///the datapoint, and the destruction of the datapoint, will be even marginally accurate. /// </summary> class dorkestProfiler { public: /// <summary> /// Singleton machinery. Call this to get a pointer to the global singleton. /// </summary> /// <returns>dorkestProfiler* to the global singleton instance</returns> static dorkestProfiler* getInstance() { if (dorkestProfiler::instance == nullptr) { dorkestProfiler::instance = new dorkestProfiler(); } return dorkestProfiler::instance; } /// <summary> /// Returns reports of all tags available. /// </summary> /// <returns>A string containing the report of ALL tags we have.</returns> std::string viewAllPoints() { std::stringstream ss; ss << std::endl; for (auto const& imap : tagMap) { ss << this->viewDataPoint(imap.first) << std::endl; } return ss.str(); } /// <summary> /// Collates the data of the datapoint with the name tagName. /// Will return a text readout of various statistical paramters. /// </summary> /// <param name="tagName">The name of the data points to process</param> /// <returns>a std::string containing a kinda-sorta formatted statistical data</returns> std::string viewDataPoint(std::string tagName) { if (tagMap.count(tagName) == 0) { error("No data points for tag name " + tagName); return "ERROR"; } else { LARGE_INTEGER medianT, minT, maxT, avgT, count; minT.QuadPart = MAXLONGLONG; maxT.QuadPart = 0; avgT.QuadPart = 0; count.QuadPart = 0; std::vector<long long> median; for (LARGE_INTEGER li : tagMap.at(tagName)) { if (minT.QuadPart > li.QuadPart) { minT = li; } if (maxT.QuadPart < li.QuadPart) maxT = li; median.push_back(li.QuadPart); avgT.QuadPart += li.QuadPart; count.QuadPart++; } std::sort(median.begin(), median.end()); medianT.QuadPart = median.at(int(median.size() / 2)); avgT.QuadPart /= count.QuadPart; std::stringstream ss; ss << "Details for tag : " << tagName << " : " << count.QuadPart << " Datapoints recorded." << std::endl; ss << "Smallest Datapoint : " << minT.QuadPart << " us" << std::endl; ss << "Mean Average Datapoint : " << avgT.QuadPart << " us" << std::endl; ss << "Median Datapoint : " << medianT.QuadPart << " us" << std::endl; ss << "Largest Datapoint : " << maxT.QuadPart << " us" << std::endl; return ss.str(); } } protected: //Called by the Datapoint's destructor. Records the data for the datapoint. FOR INTERNAL USE ONLY! void addDataPoint(LARGE_INTEGER startingTime, LARGE_INTEGER endingTime, std::string tagname) { LARGE_INTEGER ElapsedMicroseconds; ElapsedMicroseconds.QuadPart = endingTime.QuadPart - startingTime.QuadPart; ElapsedMicroseconds.QuadPart *= 1000000; ElapsedMicroseconds.QuadPart /= Frequency.QuadPart; if (tagMap.count(tagname) == 0) { tagMap.emplace(std::pair<std::string, std::vector<LARGE_INTEGER>>(tagname, std::vector<LARGE_INTEGER>())); } tagMap.at(tagname).push_back(ElapsedMicroseconds); } friend class dorkestDataPoint; private: std::map<std::string, std::vector<LARGE_INTEGER>> tagMap; static dorkestProfiler* instance; LARGE_INTEGER Frequency; dorkestProfiler() { QueryPerformanceFrequency(&Frequency); } }; /// <summary> /// dorkestDataPoint is basically a scope exploit. /n Just construct it before the area of code you want to profile, /// and let it fall out of scope when you're done. Then call the profiler's viewDataPoint member with the name /// of your datapoint set! These tags persist, so every time the constructor is called, it's a new point of data in the set. /// /// BEWARE : Not thread safe. Not optimized. THIS IS THE ONLY PART OF THIS CODE THAT IS REASONABLY ACCURATE. NOT VERY. /// USE AT OWN RISK. IN CASE OF UNANTICPATED SWELLING, LOSS OF VISION, SEIZURE, OR CESSATION OF LIFE, you have DEFINATELY used /// this class wrong. /// </summary> class dorkestDataPoint { public: /// <summary> /// Constructor for a datapoint. Simply call this in a scope you want to profile (surround my if(true) block if needed) /// and when it falls out of scope, it will report back to the profiler singleton! /// </summary> /// <param name="nameTag">The identifier of this set of datapoints</param> dorkestDataPoint(std::string nameTag) { tag = nameTag; bool ret = QueryPerformanceCounter(&timeStart); }; ~dorkestDataPoint() { bool ret = QueryPerformanceCounter(&timeEnd); dorkestProfiler::getInstance()->addDataPoint(timeStart, timeEnd, tag); } private: LARGE_INTEGER timeStart, timeEnd; std::string tag; };
[ "vektor_@hotmail.com" ]
vektor_@hotmail.com
0072b64540da83d0ef2ab553829489f68b3a2f09
193a74cc76bf1bc990ce7a3bf5fb0638236d9912
/src/core/lib/debug/event_log.cc
47f3450526b13b9e73d8e9fe58c0abba99337269
[ "Apache-2.0", "BSD-3-Clause", "MPL-2.0" ]
permissive
jtattermusch/grpc
899a0ab7fbc5987c37a4ffd13698b7540887343b
e5f7b1b8cd5666dfc4038daefb7d683ee1171856
refs/heads/master
2023-08-31T05:56:04.075028
2022-10-28T05:25:17
2022-10-28T05:25:17
31,382,470
4
2
Apache-2.0
2023-08-22T12:51:41
2015-02-26T18:39:52
C++
UTF-8
C++
false
false
2,807
cc
// Copyright 2022 gRPC authors. // // 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 <grpc/support/port_platform.h> #include "src/core/lib/debug/event_log.h" #include <algorithm> #include <atomic> #include <cstdint> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include <grpc/support/log.h> namespace grpc_core { std::atomic<EventLog*> EventLog::g_instance_{nullptr}; EventLog::~EventLog() { GPR_ASSERT(g_instance_.load(std::memory_order_acquire) != this); } void EventLog::BeginCollection() { for (auto& fragment : fragments_) { MutexLock lock(&fragment.mu); fragment.entries.clear(); } collection_begin_ = gpr_get_cycle_counter(); g_instance_.store(this, std::memory_order_release); Append("logging", 1); } std::vector<EventLog::Entry> EventLog::EndCollection( absl::Span<const absl::string_view> wanted_events) { Append("logging", -1); g_instance_.store(nullptr, std::memory_order_release); std::vector<Entry> result; for (auto& fragment : fragments_) { MutexLock lock(&fragment.mu); for (const auto& entry : fragment.entries) { if (std::find(wanted_events.begin(), wanted_events.end(), entry.event) != wanted_events.end()) { result.push_back(entry); } } fragment.entries.clear(); } std::stable_sort( result.begin(), result.end(), [](const Entry& a, const Entry& b) { return a.when < b.when; }); return result; } void EventLog::AppendInternal(absl::string_view event, int64_t delta) { auto& fragment = fragments_.this_cpu(); MutexLock lock(&fragment.mu); fragment.entries.push_back({gpr_get_cycle_counter(), event, delta}); } std::string EventLog::EndCollectionAndReportCsv( absl::Span<const absl::string_view> columns) { auto events = EndCollection(columns); std::vector<int64_t> values(columns.size(), 0); std::string result = absl::StrCat("timestamp,", absl::StrJoin(columns, ","), "\n"); for (const auto& entry : events) { auto idx = std::find(columns.begin(), columns.end(), entry.event) - columns.begin(); values[idx] += entry.delta; absl::StrAppend(&result, entry.when - collection_begin_, ",", absl::StrJoin(values, ","), "\n"); } return result; } } // namespace grpc_core
[ "noreply@github.com" ]
noreply@github.com
8272c47cf356f97bb98b706d7fde301db6739534
0db4b22b643c0f09c0bea7a3c4291f38c19a4d40
/components/autofill_assistant/browser/actions/highlight_element_action.cc
09a8df6a9c436b0906ed59f83bb89f59cc0bc774
[ "BSD-3-Clause" ]
permissive
wzhiliang/chromium
953f23bd4d7e86f8ad41f4fff1e87fb9230ea66a
d5f5d54c4081818329aa297abea212bff30a637d
refs/heads/master
2022-12-29T15:41:17.489661
2020-11-03T13:42:11
2020-11-03T13:42:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,564
cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/autofill_assistant/browser/actions/highlight_element_action.h" #include <utility> #include "base/bind.h" #include "base/callback.h" #include "components/autofill_assistant/browser/actions/action_delegate.h" #include "components/autofill_assistant/browser/actions/action_delegate_util.h" #include "components/autofill_assistant/browser/client_status.h" namespace autofill_assistant { HighlightElementAction::HighlightElementAction(ActionDelegate* delegate, const ActionProto& proto) : Action(delegate, proto) { DCHECK(proto_.has_highlight_element()); } HighlightElementAction::~HighlightElementAction() {} void HighlightElementAction::InternalProcessAction( ProcessActionCallback callback) { Selector selector = Selector(proto_.highlight_element().element()).MustBeVisible(); if (selector.empty()) { VLOG(1) << __func__ << ": empty selector"; UpdateProcessedAction(INVALID_SELECTOR); std::move(callback).Run(std::move(processed_action_proto_)); return; } delegate_->ShortWaitForElement( selector, base::BindOnce(&HighlightElementAction::OnWaitForElementTimed, weak_ptr_factory_.GetWeakPtr(), base::BindOnce(&HighlightElementAction::OnWaitForElement, weak_ptr_factory_.GetWeakPtr(), std::move(callback), selector))); } void HighlightElementAction::OnWaitForElement( ProcessActionCallback callback, const Selector& selector, const ClientStatus& element_status) { if (!element_status.ok()) { UpdateProcessedAction(element_status.proto_status()); std::move(callback).Run(std::move(processed_action_proto_)); return; } action_delegate_util::FindElementAndPerform( delegate_, selector, base::BindOnce(&ActionDelegate::HighlightElement, delegate_->GetWeakPtr()), base::BindOnce(&HighlightElementAction::OnHighlightElement, weak_ptr_factory_.GetWeakPtr(), std::move(callback))); } void HighlightElementAction::OnHighlightElement(ProcessActionCallback callback, const ClientStatus& status) { UpdateProcessedAction(status); std::move(callback).Run(std::move(processed_action_proto_)); } } // namespace autofill_assistant
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
c6905778f8735546f2b2c9ca70adc71b80666ced
297fd4aea57cb7ecf1aff04529328153ef09593d
/Source/Grapple/EventAnimNotify.cpp
cfdd033b1941c0ca5c87732038e058c7c2057679
[]
no_license
MGrime/Grapple
7e15a7f88c6a39ec5999631c33a8c7cb28045d75
99e90f735d937840ddc38f4fa8f6f734a052bbeb
refs/heads/main
2023-05-05T23:35:51.457833
2021-05-17T20:51:18
2021-05-17T20:51:18
358,914,927
0
0
null
null
null
null
UTF-8
C++
false
false
454
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "EventAnimNotify.h" #include "PlayerCharacterBase.h" void UEventAnimNotify::Notify(USkeletalMeshComponent* MeshComp, UAnimSequenceBase* Animation) { const auto Player = MeshComp->GetOwner(); if (Player) { const auto DowncastPlayer = Cast<APlayerCharacterBase>(Player); if (DowncastPlayer) { DowncastPlayer->NotifyAnimationEvent(EventData); } } }
[ "MGrime1@uclan.ac.uk" ]
MGrime1@uclan.ac.uk
bf4950933cc529e88bd6b49c6ea99745bb519026
1201a99bc1ef7b912072bb6fb1be7d51084443c7
/Arduino/program/analogget/analogget.ino
0fad4100853c65d9198e003595d731f38fb47aca
[]
no_license
TaikiWatanabe/FUNHACK2017
bf6e8b3f6e8bbe9d2fe987330083cec006473106
6e87830d79f619d8971212fd0f3997833cf78c8b
refs/heads/master
2021-01-11T22:02:43.999009
2017-01-15T05:07:26
2017-01-15T05:07:26
78,904,065
0
0
null
null
null
null
UTF-8
C++
false
false
236
ino
extern "C" { #include "user_interface.h" } void setup() { Serial.begin(115200); } void loop() { int a0 = system_adc_read(); //TOUTのアナログ値取得 float tmp = (a0 - 600) / 10; Serial.println(tmp); delay(300); }
[ "b1014258@gmail.com" ]
b1014258@gmail.com
690c485959621bc9dc85a0a9897348a447c59c06
dfbafbf64bcf153f53c053f8497c151429bf9313
/src/compiler-rt/lib/memprof/memprof_allocator.cpp
259c7c144ab7901ad89683076688854c91c5fe9a
[ "NCSA", "MIT", "LLVM-exception", "Apache-2.0" ]
permissive
solana-labs/rust-bpf-sysroot
46924a3d0a0b9ba22a8d3920fdbbc73a35336f53
5e455bd029812093c5566817fe6adea5ffe8192d
refs/heads/master
2021-06-14T00:43:05.867435
2021-03-26T10:38:47
2021-03-26T10:45:53
170,947,083
13
10
Apache-2.0
2021-03-26T10:45:54
2019-02-16T00:48:13
C
UTF-8
C++
false
false
30,345
cpp
//===-- memprof_allocator.cpp --------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file is a part of MemProfiler, a memory profiler. // // Implementation of MemProf's memory allocator, which uses the allocator // from sanitizer_common. // //===----------------------------------------------------------------------===// #include "memprof_allocator.h" #include "memprof_mapping.h" #include "memprof_stack.h" #include "memprof_thread.h" #include "sanitizer_common/sanitizer_allocator_checks.h" #include "sanitizer_common/sanitizer_allocator_interface.h" #include "sanitizer_common/sanitizer_allocator_report.h" #include "sanitizer_common/sanitizer_errno.h" #include "sanitizer_common/sanitizer_file.h" #include "sanitizer_common/sanitizer_flags.h" #include "sanitizer_common/sanitizer_internal_defs.h" #include "sanitizer_common/sanitizer_list.h" #include "sanitizer_common/sanitizer_stackdepot.h" #include <sched.h> #include <stdlib.h> #include <time.h> namespace __memprof { static int GetCpuId(void) { // _memprof_preinit is called via the preinit_array, which subsequently calls // malloc. Since this is before _dl_init calls VDSO_SETUP, sched_getcpu // will seg fault as the address of __vdso_getcpu will be null. if (!memprof_init_done) return -1; return sched_getcpu(); } // Compute the timestamp in ms. static int GetTimestamp(void) { // timespec_get will segfault if called from dl_init if (!memprof_timestamp_inited) { // By returning 0, this will be effectively treated as being // timestamped at memprof init time (when memprof_init_timestamp_s // is initialized). return 0; } timespec ts; clock_gettime(CLOCK_REALTIME, &ts); return (ts.tv_sec - memprof_init_timestamp_s) * 1000 + ts.tv_nsec / 1000000; } static MemprofAllocator &get_allocator(); // The memory chunk allocated from the underlying allocator looks like this: // H H U U U U U U // H -- ChunkHeader (32 bytes) // U -- user memory. // If there is left padding before the ChunkHeader (due to use of memalign), // we store a magic value in the first uptr word of the memory block and // store the address of ChunkHeader in the next uptr. // M B L L L L L L L L L H H U U U U U U // | ^ // ---------------------| // M -- magic value kAllocBegMagic // B -- address of ChunkHeader pointing to the first 'H' constexpr uptr kMaxAllowedMallocBits = 40; // Should be no more than 32-bytes struct ChunkHeader { // 1-st 4 bytes. u32 alloc_context_id; // 2-nd 4 bytes u32 cpu_id; // 3-rd 4 bytes u32 timestamp_ms; // 4-th 4 bytes // Note only 1 bit is needed for this flag if we need space in the future for // more fields. u32 from_memalign; // 5-th and 6-th 4 bytes // The max size of an allocation is 2^40 (kMaxAllowedMallocSize), so this // could be shrunk to kMaxAllowedMallocBits if we need space in the future for // more fields. atomic_uint64_t user_requested_size; // 23 bits available // 7-th and 8-th 4 bytes u64 data_type_id; // TODO: hash of type name }; static const uptr kChunkHeaderSize = sizeof(ChunkHeader); COMPILER_CHECK(kChunkHeaderSize == 32); struct MemprofChunk : ChunkHeader { uptr Beg() { return reinterpret_cast<uptr>(this) + kChunkHeaderSize; } uptr UsedSize() { return atomic_load(&user_requested_size, memory_order_relaxed); } void *AllocBeg() { if (from_memalign) return get_allocator().GetBlockBegin(reinterpret_cast<void *>(this)); return reinterpret_cast<void *>(this); } }; class LargeChunkHeader { static constexpr uptr kAllocBegMagic = FIRST_32_SECOND_64(0xCC6E96B9, 0xCC6E96B9CC6E96B9ULL); atomic_uintptr_t magic; MemprofChunk *chunk_header; public: MemprofChunk *Get() const { return atomic_load(&magic, memory_order_acquire) == kAllocBegMagic ? chunk_header : nullptr; } void Set(MemprofChunk *p) { if (p) { chunk_header = p; atomic_store(&magic, kAllocBegMagic, memory_order_release); return; } uptr old = kAllocBegMagic; if (!atomic_compare_exchange_strong(&magic, &old, 0, memory_order_release)) { CHECK_EQ(old, kAllocBegMagic); } } }; void FlushUnneededMemProfShadowMemory(uptr p, uptr size) { // Since memprof's mapping is compacting, the shadow chunk may be // not page-aligned, so we only flush the page-aligned portion. ReleaseMemoryPagesToOS(MemToShadow(p), MemToShadow(p + size)); } void MemprofMapUnmapCallback::OnMap(uptr p, uptr size) const { // Statistics. MemprofStats &thread_stats = GetCurrentThreadStats(); thread_stats.mmaps++; thread_stats.mmaped += size; } void MemprofMapUnmapCallback::OnUnmap(uptr p, uptr size) const { // We are about to unmap a chunk of user memory. // Mark the corresponding shadow memory as not needed. FlushUnneededMemProfShadowMemory(p, size); // Statistics. MemprofStats &thread_stats = GetCurrentThreadStats(); thread_stats.munmaps++; thread_stats.munmaped += size; } AllocatorCache *GetAllocatorCache(MemprofThreadLocalMallocStorage *ms) { CHECK(ms); return &ms->allocator_cache; } struct MemInfoBlock { u32 alloc_count; u64 total_access_count, min_access_count, max_access_count; u64 total_size; u32 min_size, max_size; u32 alloc_timestamp, dealloc_timestamp; u64 total_lifetime; u32 min_lifetime, max_lifetime; u32 alloc_cpu_id, dealloc_cpu_id; u32 num_migrated_cpu; // Only compared to prior deallocated object currently. u32 num_lifetime_overlaps; u32 num_same_alloc_cpu; u32 num_same_dealloc_cpu; u64 data_type_id; // TODO: hash of type name MemInfoBlock() : alloc_count(0) {} MemInfoBlock(u32 size, u64 access_count, u32 alloc_timestamp, u32 dealloc_timestamp, u32 alloc_cpu, u32 dealloc_cpu) : alloc_count(1), total_access_count(access_count), min_access_count(access_count), max_access_count(access_count), total_size(size), min_size(size), max_size(size), alloc_timestamp(alloc_timestamp), dealloc_timestamp(dealloc_timestamp), total_lifetime(dealloc_timestamp - alloc_timestamp), min_lifetime(total_lifetime), max_lifetime(total_lifetime), alloc_cpu_id(alloc_cpu), dealloc_cpu_id(dealloc_cpu), num_lifetime_overlaps(0), num_same_alloc_cpu(0), num_same_dealloc_cpu(0) { num_migrated_cpu = alloc_cpu_id != dealloc_cpu_id; } void Print(u64 id) { u64 p; if (flags()->print_terse) { p = total_size * 100 / alloc_count; Printf("MIB:%llu/%u/%d.%02d/%u/%u/", id, alloc_count, p / 100, p % 100, min_size, max_size); p = total_access_count * 100 / alloc_count; Printf("%d.%02d/%u/%u/", p / 100, p % 100, min_access_count, max_access_count); p = total_lifetime * 100 / alloc_count; Printf("%d.%02d/%u/%u/", p / 100, p % 100, min_lifetime, max_lifetime); Printf("%u/%u/%u/%u\n", num_migrated_cpu, num_lifetime_overlaps, num_same_alloc_cpu, num_same_dealloc_cpu); } else { p = total_size * 100 / alloc_count; Printf("Memory allocation stack id = %llu\n", id); Printf("\talloc_count %u, size (ave/min/max) %d.%02d / %u / %u\n", alloc_count, p / 100, p % 100, min_size, max_size); p = total_access_count * 100 / alloc_count; Printf("\taccess_count (ave/min/max): %d.%02d / %u / %u\n", p / 100, p % 100, min_access_count, max_access_count); p = total_lifetime * 100 / alloc_count; Printf("\tlifetime (ave/min/max): %d.%02d / %u / %u\n", p / 100, p % 100, min_lifetime, max_lifetime); Printf("\tnum migrated: %u, num lifetime overlaps: %u, num same alloc " "cpu: %u, num same dealloc_cpu: %u\n", num_migrated_cpu, num_lifetime_overlaps, num_same_alloc_cpu, num_same_dealloc_cpu); } } static void printHeader() { CHECK(flags()->print_terse); Printf("MIB:StackID/AllocCount/AveSize/MinSize/MaxSize/AveAccessCount/" "MinAccessCount/MaxAccessCount/AveLifetime/MinLifetime/MaxLifetime/" "NumMigratedCpu/NumLifetimeOverlaps/NumSameAllocCpu/" "NumSameDeallocCpu\n"); } void Merge(MemInfoBlock &newMIB) { alloc_count += newMIB.alloc_count; total_access_count += newMIB.total_access_count; min_access_count = Min(min_access_count, newMIB.min_access_count); max_access_count = Max(max_access_count, newMIB.max_access_count); total_size += newMIB.total_size; min_size = Min(min_size, newMIB.min_size); max_size = Max(max_size, newMIB.max_size); total_lifetime += newMIB.total_lifetime; min_lifetime = Min(min_lifetime, newMIB.min_lifetime); max_lifetime = Max(max_lifetime, newMIB.max_lifetime); // We know newMIB was deallocated later, so just need to check if it was // allocated before last one deallocated. num_lifetime_overlaps += newMIB.alloc_timestamp < dealloc_timestamp; alloc_timestamp = newMIB.alloc_timestamp; dealloc_timestamp = newMIB.dealloc_timestamp; num_same_alloc_cpu += alloc_cpu_id == newMIB.alloc_cpu_id; num_same_dealloc_cpu += dealloc_cpu_id == newMIB.dealloc_cpu_id; alloc_cpu_id = newMIB.alloc_cpu_id; dealloc_cpu_id = newMIB.dealloc_cpu_id; } }; static u32 AccessCount = 0; static u32 MissCount = 0; struct SetEntry { SetEntry() : id(0), MIB() {} bool Empty() { return id == 0; } void Print() { CHECK(!Empty()); MIB.Print(id); } // The stack id u64 id; MemInfoBlock MIB; }; struct CacheSet { enum { kSetSize = 4 }; void PrintAll() { for (int i = 0; i < kSetSize; i++) { if (Entries[i].Empty()) continue; Entries[i].Print(); } } void insertOrMerge(u64 new_id, MemInfoBlock &newMIB) { AccessCount++; SetAccessCount++; for (int i = 0; i < kSetSize; i++) { auto id = Entries[i].id; // Check if this is a hit or an empty entry. Since we always move any // filled locations to the front of the array (see below), we don't need // to look after finding the first empty entry. if (id == new_id || !id) { if (id == 0) { Entries[i].id = new_id; Entries[i].MIB = newMIB; } else { Entries[i].MIB.Merge(newMIB); } // Assuming some id locality, we try to swap the matching entry // into the first set position. if (i != 0) { auto tmp = Entries[0]; Entries[0] = Entries[i]; Entries[i] = tmp; } return; } } // Miss MissCount++; SetMissCount++; // We try to find the entries with the lowest alloc count to be evicted: int min_idx = 0; u64 min_count = Entries[0].MIB.alloc_count; for (int i = 1; i < kSetSize; i++) { CHECK(!Entries[i].Empty()); if (Entries[i].MIB.alloc_count < min_count) { min_idx = i; min_count = Entries[i].MIB.alloc_count; } } // Print the evicted entry profile information if (!flags()->print_terse) Printf("Evicted:\n"); Entries[min_idx].Print(); // Similar to the hit case, put new MIB in first set position. if (min_idx != 0) Entries[min_idx] = Entries[0]; Entries[0].id = new_id; Entries[0].MIB = newMIB; } void PrintMissRate(int i) { u64 p = SetAccessCount ? SetMissCount * 10000ULL / SetAccessCount : 0; Printf("Set %d miss rate: %d / %d = %5d.%02d%%\n", i, SetMissCount, SetAccessCount, p / 100, p % 100); } SetEntry Entries[kSetSize]; u32 SetAccessCount = 0; u32 SetMissCount = 0; }; struct MemInfoBlockCache { MemInfoBlockCache() { if (common_flags()->print_module_map) DumpProcessMap(); if (flags()->print_terse) MemInfoBlock::printHeader(); Sets = (CacheSet *)malloc(sizeof(CacheSet) * flags()->mem_info_cache_entries); Constructed = true; } ~MemInfoBlockCache() { free(Sets); } void insertOrMerge(u64 new_id, MemInfoBlock &newMIB) { u64 hv = new_id; // Use mod method where number of entries should be a prime close to power // of 2. hv %= flags()->mem_info_cache_entries; return Sets[hv].insertOrMerge(new_id, newMIB); } void PrintAll() { for (int i = 0; i < flags()->mem_info_cache_entries; i++) { Sets[i].PrintAll(); } } void PrintMissRate() { if (!flags()->print_mem_info_cache_miss_rate) return; u64 p = AccessCount ? MissCount * 10000ULL / AccessCount : 0; Printf("Overall miss rate: %d / %d = %5d.%02d%%\n", MissCount, AccessCount, p / 100, p % 100); if (flags()->print_mem_info_cache_miss_rate_details) for (int i = 0; i < flags()->mem_info_cache_entries; i++) Sets[i].PrintMissRate(i); } CacheSet *Sets; // Flag when the Sets have been allocated, in case a deallocation is called // very early before the static init of the Allocator and therefore this table // have completed. bool Constructed = false; }; // Accumulates the access count from the shadow for the given pointer and size. u64 GetShadowCount(uptr p, u32 size) { u64 *shadow = (u64 *)MEM_TO_SHADOW(p); u64 *shadow_end = (u64 *)MEM_TO_SHADOW(p + size); u64 count = 0; for (; shadow <= shadow_end; shadow++) count += *shadow; return count; } // Clears the shadow counters (when memory is allocated). void ClearShadow(uptr addr, uptr size) { CHECK(AddrIsAlignedByGranularity(addr)); CHECK(AddrIsInMem(addr)); CHECK(AddrIsAlignedByGranularity(addr + size)); CHECK(AddrIsInMem(addr + size - SHADOW_GRANULARITY)); CHECK(REAL(memset)); uptr shadow_beg = MEM_TO_SHADOW(addr); uptr shadow_end = MEM_TO_SHADOW(addr + size - SHADOW_GRANULARITY) + 1; if (shadow_end - shadow_beg < common_flags()->clear_shadow_mmap_threshold) { REAL(memset)((void *)shadow_beg, 0, shadow_end - shadow_beg); } else { uptr page_size = GetPageSizeCached(); uptr page_beg = RoundUpTo(shadow_beg, page_size); uptr page_end = RoundDownTo(shadow_end, page_size); if (page_beg >= page_end) { REAL(memset)((void *)shadow_beg, 0, shadow_end - shadow_beg); } else { if (page_beg != shadow_beg) { REAL(memset)((void *)shadow_beg, 0, page_beg - shadow_beg); } if (page_end != shadow_end) { REAL(memset)((void *)page_end, 0, shadow_end - page_end); } ReserveShadowMemoryRange(page_beg, page_end - 1, nullptr); } } } struct Allocator { static const uptr kMaxAllowedMallocSize = 1ULL << kMaxAllowedMallocBits; MemprofAllocator allocator; StaticSpinMutex fallback_mutex; AllocatorCache fallback_allocator_cache; uptr max_user_defined_malloc_size; atomic_uint8_t rss_limit_exceeded; MemInfoBlockCache MemInfoBlockTable; bool destructing; // ------------------- Initialization ------------------------ explicit Allocator(LinkerInitialized) : destructing(false) {} ~Allocator() { FinishAndPrint(); } void FinishAndPrint() { if (!flags()->print_terse) Printf("Live on exit:\n"); allocator.ForceLock(); allocator.ForEachChunk( [](uptr chunk, void *alloc) { u64 user_requested_size; MemprofChunk *m = ((Allocator *)alloc) ->GetMemprofChunk((void *)chunk, user_requested_size); if (!m) return; uptr user_beg = ((uptr)m) + kChunkHeaderSize; u64 c = GetShadowCount(user_beg, user_requested_size); long curtime = GetTimestamp(); MemInfoBlock newMIB(user_requested_size, c, m->timestamp_ms, curtime, m->cpu_id, GetCpuId()); ((Allocator *)alloc) ->MemInfoBlockTable.insertOrMerge(m->alloc_context_id, newMIB); }, this); allocator.ForceUnlock(); destructing = true; MemInfoBlockTable.PrintMissRate(); MemInfoBlockTable.PrintAll(); StackDepotPrintAll(); } void InitLinkerInitialized() { SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null); allocator.InitLinkerInitialized( common_flags()->allocator_release_to_os_interval_ms); max_user_defined_malloc_size = common_flags()->max_allocation_size_mb ? common_flags()->max_allocation_size_mb << 20 : kMaxAllowedMallocSize; } bool RssLimitExceeded() { return atomic_load(&rss_limit_exceeded, memory_order_relaxed); } void SetRssLimitExceeded(bool limit_exceeded) { atomic_store(&rss_limit_exceeded, limit_exceeded, memory_order_relaxed); } // -------------------- Allocation/Deallocation routines --------------- void *Allocate(uptr size, uptr alignment, BufferedStackTrace *stack, AllocType alloc_type) { if (UNLIKELY(!memprof_inited)) MemprofInitFromRtl(); if (RssLimitExceeded()) { if (AllocatorMayReturnNull()) return nullptr; ReportRssLimitExceeded(stack); } CHECK(stack); const uptr min_alignment = MEMPROF_ALIGNMENT; if (alignment < min_alignment) alignment = min_alignment; if (size == 0) { // We'd be happy to avoid allocating memory for zero-size requests, but // some programs/tests depend on this behavior and assume that malloc // would not return NULL even for zero-size allocations. Moreover, it // looks like operator new should never return NULL, and results of // consecutive "new" calls must be different even if the allocated size // is zero. size = 1; } CHECK(IsPowerOfTwo(alignment)); uptr rounded_size = RoundUpTo(size, alignment); uptr needed_size = rounded_size + kChunkHeaderSize; if (alignment > min_alignment) needed_size += alignment; CHECK(IsAligned(needed_size, min_alignment)); if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize || size > max_user_defined_malloc_size) { if (AllocatorMayReturnNull()) { Report("WARNING: MemProfiler failed to allocate 0x%zx bytes\n", (void *)size); return nullptr; } uptr malloc_limit = Min(kMaxAllowedMallocSize, max_user_defined_malloc_size); ReportAllocationSizeTooBig(size, malloc_limit, stack); } MemprofThread *t = GetCurrentThread(); void *allocated; if (t) { AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage()); allocated = allocator.Allocate(cache, needed_size, 8); } else { SpinMutexLock l(&fallback_mutex); AllocatorCache *cache = &fallback_allocator_cache; allocated = allocator.Allocate(cache, needed_size, 8); } if (UNLIKELY(!allocated)) { SetAllocatorOutOfMemory(); if (AllocatorMayReturnNull()) return nullptr; ReportOutOfMemory(size, stack); } uptr alloc_beg = reinterpret_cast<uptr>(allocated); uptr alloc_end = alloc_beg + needed_size; uptr beg_plus_header = alloc_beg + kChunkHeaderSize; uptr user_beg = beg_plus_header; if (!IsAligned(user_beg, alignment)) user_beg = RoundUpTo(user_beg, alignment); uptr user_end = user_beg + size; CHECK_LE(user_end, alloc_end); uptr chunk_beg = user_beg - kChunkHeaderSize; MemprofChunk *m = reinterpret_cast<MemprofChunk *>(chunk_beg); m->from_memalign = alloc_beg != chunk_beg; CHECK(size); m->cpu_id = GetCpuId(); m->timestamp_ms = GetTimestamp(); m->alloc_context_id = StackDepotPut(*stack); uptr size_rounded_down_to_granularity = RoundDownTo(size, SHADOW_GRANULARITY); if (size_rounded_down_to_granularity) ClearShadow(user_beg, size_rounded_down_to_granularity); MemprofStats &thread_stats = GetCurrentThreadStats(); thread_stats.mallocs++; thread_stats.malloced += size; thread_stats.malloced_overhead += needed_size - size; if (needed_size > SizeClassMap::kMaxSize) thread_stats.malloc_large++; else thread_stats.malloced_by_size[SizeClassMap::ClassID(needed_size)]++; void *res = reinterpret_cast<void *>(user_beg); atomic_store(&m->user_requested_size, size, memory_order_release); if (alloc_beg != chunk_beg) { CHECK_LE(alloc_beg + sizeof(LargeChunkHeader), chunk_beg); reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Set(m); } MEMPROF_MALLOC_HOOK(res, size); return res; } void Deallocate(void *ptr, uptr delete_size, uptr delete_alignment, BufferedStackTrace *stack, AllocType alloc_type) { uptr p = reinterpret_cast<uptr>(ptr); if (p == 0) return; MEMPROF_FREE_HOOK(ptr); uptr chunk_beg = p - kChunkHeaderSize; MemprofChunk *m = reinterpret_cast<MemprofChunk *>(chunk_beg); u64 user_requested_size = atomic_exchange(&m->user_requested_size, 0, memory_order_acquire); if (memprof_inited && memprof_init_done && !destructing && MemInfoBlockTable.Constructed) { u64 c = GetShadowCount(p, user_requested_size); long curtime = GetTimestamp(); MemInfoBlock newMIB(user_requested_size, c, m->timestamp_ms, curtime, m->cpu_id, GetCpuId()); { SpinMutexLock l(&fallback_mutex); MemInfoBlockTable.insertOrMerge(m->alloc_context_id, newMIB); } } MemprofStats &thread_stats = GetCurrentThreadStats(); thread_stats.frees++; thread_stats.freed += user_requested_size; void *alloc_beg = m->AllocBeg(); if (alloc_beg != m) { // Clear the magic value, as allocator internals may overwrite the // contents of deallocated chunk, confusing GetMemprofChunk lookup. reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Set(nullptr); } MemprofThread *t = GetCurrentThread(); if (t) { AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage()); allocator.Deallocate(cache, alloc_beg); } else { SpinMutexLock l(&fallback_mutex); AllocatorCache *cache = &fallback_allocator_cache; allocator.Deallocate(cache, alloc_beg); } } void *Reallocate(void *old_ptr, uptr new_size, BufferedStackTrace *stack) { CHECK(old_ptr && new_size); uptr p = reinterpret_cast<uptr>(old_ptr); uptr chunk_beg = p - kChunkHeaderSize; MemprofChunk *m = reinterpret_cast<MemprofChunk *>(chunk_beg); MemprofStats &thread_stats = GetCurrentThreadStats(); thread_stats.reallocs++; thread_stats.realloced += new_size; void *new_ptr = Allocate(new_size, 8, stack, FROM_MALLOC); if (new_ptr) { CHECK_NE(REAL(memcpy), nullptr); uptr memcpy_size = Min(new_size, m->UsedSize()); REAL(memcpy)(new_ptr, old_ptr, memcpy_size); Deallocate(old_ptr, 0, 0, stack, FROM_MALLOC); } return new_ptr; } void *Calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) { if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) { if (AllocatorMayReturnNull()) return nullptr; ReportCallocOverflow(nmemb, size, stack); } void *ptr = Allocate(nmemb * size, 8, stack, FROM_MALLOC); // If the memory comes from the secondary allocator no need to clear it // as it comes directly from mmap. if (ptr && allocator.FromPrimary(ptr)) REAL(memset)(ptr, 0, nmemb * size); return ptr; } void CommitBack(MemprofThreadLocalMallocStorage *ms, BufferedStackTrace *stack) { AllocatorCache *ac = GetAllocatorCache(ms); allocator.SwallowCache(ac); } // -------------------------- Chunk lookup ---------------------- // Assumes alloc_beg == allocator.GetBlockBegin(alloc_beg). MemprofChunk *GetMemprofChunk(void *alloc_beg, u64 &user_requested_size) { if (!alloc_beg) return nullptr; MemprofChunk *p = reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Get(); if (!p) { if (!allocator.FromPrimary(alloc_beg)) return nullptr; p = reinterpret_cast<MemprofChunk *>(alloc_beg); } // The size is reset to 0 on deallocation (and a min of 1 on // allocation). user_requested_size = atomic_load(&p->user_requested_size, memory_order_acquire); if (user_requested_size) return p; return nullptr; } MemprofChunk *GetMemprofChunkByAddr(uptr p, u64 &user_requested_size) { void *alloc_beg = allocator.GetBlockBegin(reinterpret_cast<void *>(p)); return GetMemprofChunk(alloc_beg, user_requested_size); } uptr AllocationSize(uptr p) { u64 user_requested_size; MemprofChunk *m = GetMemprofChunkByAddr(p, user_requested_size); if (!m) return 0; if (m->Beg() != p) return 0; return user_requested_size; } void Purge(BufferedStackTrace *stack) { allocator.ForceReleaseToOS(); } void PrintStats() { allocator.PrintStats(); } void ForceLock() { allocator.ForceLock(); fallback_mutex.Lock(); } void ForceUnlock() { fallback_mutex.Unlock(); allocator.ForceUnlock(); } }; static Allocator instance(LINKER_INITIALIZED); static MemprofAllocator &get_allocator() { return instance.allocator; } void InitializeAllocator() { instance.InitLinkerInitialized(); } void MemprofThreadLocalMallocStorage::CommitBack() { GET_STACK_TRACE_MALLOC; instance.CommitBack(this, &stack); } void PrintInternalAllocatorStats() { instance.PrintStats(); } void memprof_free(void *ptr, BufferedStackTrace *stack, AllocType alloc_type) { instance.Deallocate(ptr, 0, 0, stack, alloc_type); } void memprof_delete(void *ptr, uptr size, uptr alignment, BufferedStackTrace *stack, AllocType alloc_type) { instance.Deallocate(ptr, size, alignment, stack, alloc_type); } void *memprof_malloc(uptr size, BufferedStackTrace *stack) { return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC)); } void *memprof_calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) { return SetErrnoOnNull(instance.Calloc(nmemb, size, stack)); } void *memprof_reallocarray(void *p, uptr nmemb, uptr size, BufferedStackTrace *stack) { if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) { errno = errno_ENOMEM; if (AllocatorMayReturnNull()) return nullptr; ReportReallocArrayOverflow(nmemb, size, stack); } return memprof_realloc(p, nmemb * size, stack); } void *memprof_realloc(void *p, uptr size, BufferedStackTrace *stack) { if (!p) return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC)); if (size == 0) { if (flags()->allocator_frees_and_returns_null_on_realloc_zero) { instance.Deallocate(p, 0, 0, stack, FROM_MALLOC); return nullptr; } // Allocate a size of 1 if we shouldn't free() on Realloc to 0 size = 1; } return SetErrnoOnNull(instance.Reallocate(p, size, stack)); } void *memprof_valloc(uptr size, BufferedStackTrace *stack) { return SetErrnoOnNull( instance.Allocate(size, GetPageSizeCached(), stack, FROM_MALLOC)); } void *memprof_pvalloc(uptr size, BufferedStackTrace *stack) { uptr PageSize = GetPageSizeCached(); if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) { errno = errno_ENOMEM; if (AllocatorMayReturnNull()) return nullptr; ReportPvallocOverflow(size, stack); } // pvalloc(0) should allocate one page. size = size ? RoundUpTo(size, PageSize) : PageSize; return SetErrnoOnNull(instance.Allocate(size, PageSize, stack, FROM_MALLOC)); } void *memprof_memalign(uptr alignment, uptr size, BufferedStackTrace *stack, AllocType alloc_type) { if (UNLIKELY(!IsPowerOfTwo(alignment))) { errno = errno_EINVAL; if (AllocatorMayReturnNull()) return nullptr; ReportInvalidAllocationAlignment(alignment, stack); } return SetErrnoOnNull(instance.Allocate(size, alignment, stack, alloc_type)); } void *memprof_aligned_alloc(uptr alignment, uptr size, BufferedStackTrace *stack) { if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) { errno = errno_EINVAL; if (AllocatorMayReturnNull()) return nullptr; ReportInvalidAlignedAllocAlignment(size, alignment, stack); } return SetErrnoOnNull(instance.Allocate(size, alignment, stack, FROM_MALLOC)); } int memprof_posix_memalign(void **memptr, uptr alignment, uptr size, BufferedStackTrace *stack) { if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) { if (AllocatorMayReturnNull()) return errno_EINVAL; ReportInvalidPosixMemalignAlignment(alignment, stack); } void *ptr = instance.Allocate(size, alignment, stack, FROM_MALLOC); if (UNLIKELY(!ptr)) // OOM error is already taken care of by Allocate. return errno_ENOMEM; CHECK(IsAligned((uptr)ptr, alignment)); *memptr = ptr; return 0; } uptr memprof_malloc_usable_size(const void *ptr, uptr pc, uptr bp) { if (!ptr) return 0; uptr usable_size = instance.AllocationSize(reinterpret_cast<uptr>(ptr)); return usable_size; } void MemprofSoftRssLimitExceededCallback(bool limit_exceeded) { instance.SetRssLimitExceeded(limit_exceeded); } } // namespace __memprof // ---------------------- Interface ---------------- {{{1 using namespace __memprof; #if !SANITIZER_SUPPORTS_WEAK_HOOKS // Provide default (no-op) implementation of malloc hooks. SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_malloc_hook, void *ptr, uptr size) { (void)ptr; (void)size; } SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_free_hook, void *ptr) { (void)ptr; } #endif uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; } int __sanitizer_get_ownership(const void *p) { return memprof_malloc_usable_size(p, 0, 0) != 0; } uptr __sanitizer_get_allocated_size(const void *p) { return memprof_malloc_usable_size(p, 0, 0); } int __memprof_profile_dump() { instance.FinishAndPrint(); // In the future we may want to return non-zero if there are any errors // detected during the dumping process. return 0; }
[ "dmakarov@alumni.stanford.edu" ]
dmakarov@alumni.stanford.edu
0ef244fa385ac066928a5d8f9bca7eba86c35046
61b330e8806420655a8ecadf7b217db6a8830277
/chapter09/readfile2.cpp
e30974da098a5fc77ea9dd0f538962a054cbdd0e
[]
no_license
wolfwithcode/Cpp-Practice
316c2442716f29eac367f89d3aef4631ed83d122
f5aa67c7105bdde5944db63e8702402548b5815e
refs/heads/master
2020-07-30T03:28:07.903252
2016-04-15T09:39:58
2016-04-15T09:39:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
963
cpp
//read file from the prompt #include <iostream> #include <fstream> #include <cstring> using namespace std; #define COL_WIDTH 80 int main(int argc, char *argv[]){ int MAX_PATH = 100; int c; //input character int i; //loop counter char filename[MAX_PATH + 1]; char input_line[COL_WIDTH + 1]; if(argc > 1) strncpy(filename, argv[1], MAX_PATH); else{ cout << "Enter a file name and press ENTER: "; cin.getline(filename,MAX_PATH + 1); } ifstream file_in(filename); if (!file_in){ cout << filename << "could not be opened."; cout << endl; //system("PAUSE"); return -1; } while(true){ for (i = 1; i <= 24 && !file_in.eof(); i++){ file_in.getline(input_line, COL_WIDTH + 1); cout << input_line << endl; } if (file_in.eof()) break; cout << "More? (Press 'Q' and ENTER to quit)"; cin.getline(input_line, COL_WIDTH + 1); c = input_line[0]; if (c == 'Q' || c == 'q') break; } //system("PAUSE"); return 0; }
[ "weekend27@163.com" ]
weekend27@163.com
bf7c37b954772d47fa013cf83907e18811560a51
4cb4df1b8c4c1e591ac7c8fc9874b2b2edfb9884
/CPP/ADVANCE/IV_输入输出流/IV_文件的读写.cpp
538182af30a0a008881e6043cf3e70fa70de2328
[]
no_license
Gmrakari/Curious_realize
c377aae72dc62bf7bb25c4ffcd6aef20fa9a127d
38ef05f72dd2664fcac4915291417f9ef2120933
refs/heads/master
2021-12-19T01:39:35.806220
2021-12-09T03:09:53
2021-12-09T03:09:53
175,038,985
1
0
null
null
null
null
UTF-8
C++
false
false
1,380
cpp
#define _CRT_SECURE_NO_WARNINGS #include "iostream" using namespace std; #include "fstream" //date:2018-12-09 17 : 05 //Author : null //Project:文件的读写 // void main1() { char* fname = "c:/2.txt"; ofstream fout(fname,ios::app | ios::ate);//建一个 输出流对象 和文件 关联 if(!fout) { cout<<"文件打开失败"<<endl; return ; } fout<<"hello ... 111"<<endl; fout<<"hello ... 222"<<endl; fout<<"hello ... 333"<<endl; fout.close(); //读文件 ifstream fin(fname);//建立一个 输入流对象 和 文件关联 char ch; while(fin.get(ch)) { cout << ch; } fin.close(); cout<<"hellc"<<endl; system("pause"); return 0; } class Teacher { public: Teacher() { age = 33; strcpy(name,""); } Teacher(int age,char *_name) { age = _age; strcpy(name,_name); } void prinT() { cout<<"age :"<<age << "name: "<<name << endl; } private: int age; char name[32]; }; void main() { char *fname = "c:/11.dat"; ofstream fout(fname,ios::binary); if(!fout) { cout<<"打开文件失败"<<endl; return ; } Teacher t1(31,"t31"); Teacher t2(32,"t32"); fout.write((char *)&t1,sizeof(t1)); fout.write((char *)&t2,sizeof(t2)); fout.close(); // ifstream fin(fname);//建立一个输入流对象 和 文件关联 Teacher tmp; fin.read((char *)&tmp,sizeof(Teacher)); tmp.prinT(); fin.close(); system("pause"); }
[ "swift.chou@outlook.com" ]
swift.chou@outlook.com
de877af2da860f502cb9a8eb9e1aa2f8d7268d62
bc9dd00a3135ea1754977b48c24eb441fdb52ace
/src/function/ruler.cpp
bfa2b7690991a455602ac32c2345688195bec86c
[ "MIT" ]
permissive
XiangSugar/Learn_CPP
bba62b8a70a061f230f15a86661feb19849220bb
eb5b2a63f6a5b68c8acdd7cb4ed3c6b5f19f7abe
refs/heads/master
2022-05-23T05:46:49.103302
2020-04-23T14:34:27
2020-04-23T14:34:27
258,229,637
0
0
null
null
null
null
UTF-8
C++
false
false
1,974
cpp
/*---------------------------- 2019.10.14 利用递归模拟刻画直尺的刻度 ----------------------------*/ #include <iostream> int Ruler_Length = 66; int Divs = 10; void subdivide(char ar[], int low, int high, int lev); int main() { using namespace std; char ruler[Ruler_Length]; for (int i = 1; i < Ruler_Length-2; i++) { ruler[i] = ' '; } ruler[Ruler_Length-1] = '\0'; ruler[Ruler_Length - 2] = '|'; ruler[0] = '|'; cout << ruler << endl; for (int i = 1; i <= Divs; i++) { subdivide(ruler, 0, Ruler_Length - 2, i); cout << ruler << endl; for (int i = 1; i < Ruler_Length-2; i++) { ruler[i] = ' '; } } double temp; cin >> temp; return 0; } void subdivide(char ar[], int low, int high, int lev) { if (lev == 0) return; int mid = (low + high) / 2; ar[mid] = '|'; subdivide(ar, low, mid, lev - 1); subdivide(ar, mid, high, lev - 1); return; } /*该程序不完善,因为递归深度需要自己事先指定,而且必须要指定为比最大深度小的值,如果Divs不合理(过大),则后面做的是无用功 eg: 上述程序当 Divs = 10 时的运行结果 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| */
[ "xiangsuhust@gmail.com" ]
xiangsuhust@gmail.com
79c543cdba490bbfa0c282d506b95609d7f844e7
1f77da2ccd8392a8b8bd1cb6879dcd9f9b966afa
/arraysAndStrings/evaluateReversePolishExpression.cpp
14682c085d4d0a464bc1c5313560b600f59666a8
[]
no_license
srinivasan1995/programmingCreek
1d735c43f4f1f5f97ba40213d9ce98996bd0d569
fb9e296d8fe1444314eb08146124c475849f63a3
refs/heads/master
2020-06-04T15:05:17.695494
2019-06-17T03:49:27
2019-06-17T03:49:27
192,074,215
0
0
null
null
null
null
UTF-8
C++
false
false
894
cpp
/* *Evaluate the value of an arithmetic expression in Reverse Polish Notation. *Valid operators are +, -, *, /. *Each operand may be an integer or another expression. For example: 21+3* => 9 {((2 + 1) * 3) => 9} */ #include<iostream> #include<stack> using namespace std; stack<int> stac; int main(){ string s; cin>>s; for(int i=0;i<s.size();i++){ if(s[i] >= '0' && s[i] <='9'){ stac.push(s[i]-48); }else{ int temp[2]={0}; for(int i=0;i<2;i++){ if(!stac.empty()){ temp[i] = stac.top();stac.pop(); } } int result =0; switch(s[i]){ case '+': result = temp[0] + temp[1];break; case '-': result = temp[0] - temp[1];break; case '*': result= temp[0] * temp[1];break; case '/': result = temp[0] / temp[1];break; } stac.push(result); } } for(;!stac.empty();){ cout<<stac.top()<<" ";stac.pop(); } }
[ "noreply@github.com" ]
noreply@github.com
9b3ce01738b81ebeef85ac7e2d3df78690774b75
eacc64ff0c1ee69416b9fcb2d7a6085e1a016bef
/LOJ-1026 Critical Links.cpp
b8900bdfe53e37650acfbdb97e0b1db30f4066cd
[]
no_license
mahmoodreyal/LightOJ
f7179b4b7d9a8bf22a73a5a0d8dce6da85526a9c
7405fdffa102e7d4a019672f8a28b0e190498124
refs/heads/master
2023-03-25T05:26:18.816530
2021-03-15T02:02:21
2021-03-15T02:02:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,739
cpp
#include <bits/stdc++.h> using namespace std; #define Bismillah__Kun_Fayakun ios_base :: sync_with_stdio(false); #define ll long long #define MAXN 200007 int n, cnt = 0; vector <int> visited(MAXN, 0), disc(MAXN, 0), parent(MAXN, 0), low(MAXN, 0), graph[MAXN]; map <pair <int, int>, int> Map; void bridgeUtil(int u) { static int time = 0; visited[u] = true; disc[u] = low[u] = ++time; for (auto i = graph[u].begin(); i != graph[u].end(); ++i) { int v = *i; if (!visited[v]) { parent[v] = u; bridgeUtil(v); low[u] = min(low[u], low[v]); if (low[v] > disc[u]) {int p = u, q = v; if (p > q) swap(p, q); Map[{p, q}] = 1, ++cnt;} } else if (v != parent[u]) low[u] = min(low[u], disc[v]); } } void bridge() { for (int i = 0; i < n; i++) if (visited[i] == false) bridgeUtil(i); } void init() { for (int i = 0; i < n; ++i) { parent[i] = -1; low[i] = 0; visited[i] = 0; disc[i] = 0; graph[i].clear(); } Map.clear(); cnt = 0; } int main() { int test_case, case_no = 0; cin >> test_case; while(test_case--) { cin >> n; init(); for (int i = 0; i<n; ++i) { int node, adj; scanf("%d (%d)", &node, &adj); for (int j = 0; j<adj; ++j) { int a; scanf("%d", &a); graph[node].push_back(a); } } bridge(); printf("Case %d:\n", ++case_no); printf("%d critical links\n", cnt); for (auto it = Map.begin(); it != Map.end(); ++it) printf("%d - %d\n", it->first.first, it->first.second); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
9b873d4aa9bff0ab5e941b1bf685dc257087ed6a
2fd2ff04c91e8132b780bbd866e5d4524a8e66dd
/hlx/BD/dynamic_region_ddr4/ip/dynamic_region_ddr4_auto_cc_6/sim/dynamic_region_ddr4_auto_cc_6_sc.cpp
8ff7ebe5d6304c830b358f34557716525ccf3abd
[]
no_license
SanjayRai/U200_customThinShell_splitxDMA
401a4d178cabf618c8539e3ad575d16c27a6d086
04fa4e910de83117b5be8584b0732299e9dfad4d
refs/heads/master
2022-12-14T06:57:33.323260
2020-09-21T21:26:46
2020-09-21T21:26:46
297,464,543
2
0
null
null
null
null
UTF-8
C++
false
false
4,140
cpp
// (c) Copyright 1995-2020 Xilinx, Inc. All rights reserved. // // This file contains confidential and proprietary information // of Xilinx, Inc. and is protected under U.S. and // international copyright and other intellectual property // laws. // // DISCLAIMER // This disclaimer is not a license and does not grant any // rights to the materials distributed herewith. Except as // otherwise provided in a valid license issued to you by // Xilinx, and to the maximum extent permitted by applicable // law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND // WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES // AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING // BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- // INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and // (2) Xilinx shall not be liable (whether in contract or tort, // including negligence, or under any other theory of // liability) for any loss or damage of any kind or nature // related to, arising under or in connection with these // materials, including for any direct, or any indirect, // special, incidental, or consequential loss or damage // (including loss of data, profits, goodwill, or any type of // loss or damage suffered as a result of any action brought // by a third party) even if such damage or loss was // reasonably foreseeable or Xilinx had been advised of the // possibility of the same. // // CRITICAL APPLICATIONS // Xilinx products are not designed or intended to be fail- // safe, or for use in any application requiring fail-safe // performance, such as life-support or safety devices or // systems, Class III medical devices, nuclear facilities, // applications related to the deployment of airbags, or any // other applications that could lead to death, personal // injury, or severe property or environmental damage // (individually and collectively, "Critical // Applications"). Customer assumes the sole risk and // liability of any use of Xilinx products in Critical // Applications, subject only to applicable laws and // regulations governing limitations on product liability. // // THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS // PART OF THIS FILE AT ALL TIMES. // // DO NOT MODIFY THIS FILE. #include "dynamic_region_ddr4_auto_cc_6_sc.h" #include "axi_clock_converter.h" #include <map> #include <string> dynamic_region_ddr4_auto_cc_6_sc::dynamic_region_ddr4_auto_cc_6_sc(const sc_core::sc_module_name& nm) : sc_core::sc_module(nm), mp_impl(NULL) { // configure connectivity manager xsc::utils::xsc_sim_manager::addInstance("dynamic_region_ddr4_auto_cc_6", this); // initialize module xsc::common_cpp::properties model_param_props; model_param_props.addLong("C_AXI_ID_WIDTH", "1"); model_param_props.addLong("C_AXI_ADDR_WIDTH", "32"); model_param_props.addLong("C_AXI_DATA_WIDTH", "32"); model_param_props.addLong("C_S_AXI_ACLK_RATIO", "1"); model_param_props.addLong("C_M_AXI_ACLK_RATIO", "2"); model_param_props.addLong("C_AXI_IS_ACLK_ASYNC", "1"); model_param_props.addLong("C_AXI_PROTOCOL", "2"); model_param_props.addLong("C_AXI_SUPPORTS_USER_SIGNALS", "0"); model_param_props.addLong("C_AXI_AWUSER_WIDTH", "1"); model_param_props.addLong("C_AXI_ARUSER_WIDTH", "1"); model_param_props.addLong("C_AXI_WUSER_WIDTH", "1"); model_param_props.addLong("C_AXI_RUSER_WIDTH", "1"); model_param_props.addLong("C_AXI_BUSER_WIDTH", "1"); model_param_props.addLong("C_AXI_SUPPORTS_WRITE", "1"); model_param_props.addLong("C_AXI_SUPPORTS_READ", "1"); model_param_props.addLong("C_SYNCHRONIZER_STAGE", "3"); model_param_props.addString("C_FAMILY", "virtexuplus"); mp_impl = new axi_clock_converter("inst", model_param_props); // initialize sockets S_TARGET_rd_socket = mp_impl->S_TARGET_rd_socket; S_TARGET_wr_socket = mp_impl->S_TARGET_wr_socket; M_INITIATOR_rd_socket = mp_impl->M_INITIATOR_rd_socket; M_INITIATOR_wr_socket = mp_impl->M_INITIATOR_wr_socket; } dynamic_region_ddr4_auto_cc_6_sc::~dynamic_region_ddr4_auto_cc_6_sc() { xsc::utils::xsc_sim_manager::clean(); delete mp_impl; }
[ "sanjay.d.rai@gmail.com" ]
sanjay.d.rai@gmail.com
8a55ab004b16092dccb79ea3c898eef23d8a586e
ae1fccb9904ef8837b1a13987495fd537835397d
/TPDatos/src/ModuloDeTipos/Termino.h
9bbdf6c456963b0f8104db2b14d308511d091cd0
[]
no_license
tapiajimena/organizacion-de-datos-2011
232d2d698d771cbd3a10a8d736af5cec42863d2d
857695bef7328931e99ca1cd3a9876258c18ccdc
refs/heads/master
2021-01-01T05:30:18.583707
2011-06-26T07:49:58
2011-06-26T07:49:58
32,296,392
0
0
null
null
null
null
UTF-8
C++
false
false
1,633
h
#ifndef TERMINO_H_ #define TERMINO_H_ #include <list> #include <string> #include <stdint.h> #include <math.h> #include "PosicionesMasProximasTermino.h" #include "PosicionTerminoEnLibro.h" #include "DatoTriada.h" using namespace std; class Termino { private: string nombre; uint32_t id_termino; list<PosicionTerminoEnLibro*>* posicionesTerminoEnLibros; list<PosicionTerminoEnLibro*>::const_iterator ci_posicionTerminoEnLibro; public: Termino(); Termino(string nombre, list<DatoTriada*>* triadasDelTermino); uint32_t obtenerId(); string obtenerNombre(); list<uint32_t>* obtenerLibros(); int obtenerCantidadLibros(); int obtenerCantidadAparicionesEnLibro(uint32_t id_libro); float obtenerPesoGlobal(int totalDocumentos); list<long>* obtenerPosicionesEnLibro(uint32_t id_libro); bool estaEnLibro(uint32_t id_libro); /* * dado un libro y los terminos que anteceden y preceden al termino actual en la cosulta * restorna las posición del termino que antecede junto con la posición del término que * precede de modo tal que las distancia entre los tres sea mínima * * en caso de retornar -1, -1 es que los términos no estaban en orden en el libro */ PosicionesMasProximasTermino* obtenerMejoresPosiciones(uint32_t id_libro, Termino* terminoAnterior, Termino* terminoSiguiente); //devuelve -1 en caso de no haberla podido encontrar long obtenerPosicionAnteriorMasProxima(uint32_t id_libro, long posicion); //devuelve -1 en caso de no haberla podido encontrar long obtenerPosicionPosteriorMasProxima(uint32_t id_libro, long posicion); virtual ~Termino(); }; #endif /* TERMINO_H_ */
[ "paulofer85@gmail.com@4d5b8590-2f34-da2a-ecbf-15d6c6d80ed1" ]
paulofer85@gmail.com@4d5b8590-2f34-da2a-ecbf-15d6c6d80ed1
f6972f89f1f5fae50d9346e0e77a6ac383110ae5
8cc6d6f590285ef00e0f30e0151c4d407847b651
/build_test/windows-build/Sources/include/kha/graphics2/ImageScaleQuality.h
7c3a98057270fdc967d16fb46b21901555efee29
[]
no_license
piboistudios/ArmoryDeformIssues
e087d5097af74f958fd89dd8dd17ca57627bf6d1
84e8b14c5098a4a4db310c5177c5dcd46f40212d
refs/heads/master
2020-03-24T11:42:11.270376
2018-07-28T16:33:45
2018-07-28T16:33:45
142,692,926
0
0
null
null
null
null
UTF-8
C++
false
true
1,231
h
// Generated by Haxe 3.4.4 (git build master @ 99b08bb) #ifndef INCLUDED_kha_graphics2_ImageScaleQuality #define INCLUDED_kha_graphics2_ImageScaleQuality #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS2(kha,graphics2,ImageScaleQuality) namespace kha{ namespace graphics2{ class ImageScaleQuality_obj : public hx::EnumBase_obj { typedef hx::EnumBase_obj super; typedef ImageScaleQuality_obj OBJ_; public: ImageScaleQuality_obj() {}; HX_DO_ENUM_RTTI; static void __boot(); static void __register(); static bool __GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp); ::String GetEnumName( ) const { return HX_HCSTRING("kha.graphics2.ImageScaleQuality","\xbf","\x8e","\xc4","\x4a"); } ::String __ToString() const { return HX_HCSTRING("ImageScaleQuality.","\xfe","\xde","\x77","\xc8") + _hx_tag; } static ::kha::graphics2::ImageScaleQuality High; static inline ::kha::graphics2::ImageScaleQuality High_dyn() { return High; } static ::kha::graphics2::ImageScaleQuality Low; static inline ::kha::graphics2::ImageScaleQuality Low_dyn() { return Low; } }; } // end namespace kha } // end namespace graphics2 #endif /* INCLUDED_kha_graphics2_ImageScaleQuality */
[ "gabriel.speed.bullock@gmail.com" ]
gabriel.speed.bullock@gmail.com
e5b9082bd9ede948747224dee896809957356631
9952d6fd024282ee393109ee54bda216355c7a9e
/AELD_2016/AELD Assgn1 All files/AELD Assgn1/loadProgram/ALU.hpp
f88aeba9dcd06cff4ede1a65de844691e6c900a1
[]
no_license
ricktam1469/AELD_Codes
e1377a84372b157e1e3bfbc6f70e37e2aaf949b1
5e1e95b95b11d39c19911690894a119cb3de5d76
refs/heads/master
2021-01-10T05:07:47.976731
2020-04-02T07:02:30
2020-04-02T07:02:30
55,715,760
0
0
null
null
null
null
UTF-8
C++
false
false
1,086
hpp
#ifndef ALU_HPP #define ALU_HPP #include <iostream> #include <string> #include <vector> #include <fstream> #include <cstdlib> #include <cstring> using namespace std; typedef enum {ADD,SUB,MUL,DIV,CMP} Operation; typedef enum {LOAD,JMP,JNZ,JZ,JGT,JGE,HALT,NOP,COUT,COUTALL} OperationMain; class Registers { public : int storage_array[16]; //Array of Registers int z; //zero Flag int ge; //Greater Equal Flag int pc; //Program counter Registers(){ z=0; ge=0; pc=0; } }; class ALU { int op0; int op1; public : int *register_location; //Access to Registers class instances ALU(Registers reg); int execute(int,int,Operation operation) ; Registers registers; //object of Registers class }; class loadProgram{ ifstream file; public: loadProgram(char *file); ~loadProgram(){ file.close(); } struct commandM32 { char* command; char* operand1; char* operand2; }objcommandM32; vector<commandM32> storageVector; //Structured type vector void fileReading(); //Reading the file and store in a vector }; #endif
[ "ricktam1469@iiitd.ac.in" ]
ricktam1469@iiitd.ac.in
ffa782ffd8511c452285e3c2c9fd6cec6f4cb4db
4490e615a756d3f5f99ca7cad478040beeca9375
/Borland C++/Unidad III/A1103172.cpp
a436f9dde2cf87fcd776b909e3bfc7e6ddb8969d
[]
no_license
misaeladame/programacion-estructurada-con-almacenamiento-persistente-de-los-datos
04162ae22a48909aa743bdd3992067cef98ef205
7e7016dd50d958406e17174d90715e4fc6bfc0a2
refs/heads/main
2023-06-11T00:44:16.261384
2021-07-02T00:39:07
2021-07-02T00:39:07
382,189,717
0
0
null
null
null
null
ISO-8859-1
C++
false
false
712
cpp
// CENTRO DE BACHILLERATO TECNOLOGICO industrial y de servicios No 4 // MÓDULO 1 DE LA ESPECIALIDAD DE PRORGAMACIÓN // Archivo A1103172.CPP // PROGRAMA FUNCIONES CON RETORNO DE VALOR // Lenguaje C++ // Alumno: José Misael Adame Sandoval Gpo:11 NL:03 // Titular: Ing. Juan Antonio Yañez Palafox #include<iostream.h> #include<conio.h> double cuadrado (double); //Prototipo main() { int valor; clrscr(); cout<<"\n\nIntroduce un valor: "; cin>>valor; cout<<valor <<" elevado al cuadrado = " <<cuadrado(valor) <<endl; getch(); return 0; } double cuadrado(double valor) { int resultado; resultado=valor*valor; return resultado; }
[ "misael_adame@protonmail.com" ]
misael_adame@protonmail.com
4d5c61510cc197718fdf80b5bacb82fbde05ddeb
8b78f5eb294a0332c2ebdc4e836b777b465f5f8a
/Matrix/Print Matrix in snake Pattern.cpp
8a9f0bb060fce30a8256a5ebac6f23f9d13f46cd
[]
no_license
anjijava16/Practice-Geeks-For-Geeks
9a8f5e33992f79a7a4cec4321403290f737807a9
58ffb4750268abbc100f10dd36008eee92649494
refs/heads/master
2022-12-27T00:51:01.443164
2020-10-06T05:15:54
2020-10-06T05:15:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,057
cpp
//https://practice.geeksforgeeks.org/problems/print-matrix-in-snake-pattern/0 //Time complexity : O(n^2) using namespace std; int main() { //code int t; scanf("%d",&t); while(t--) { int n; scanf("%d",&n); int a[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { scanf("%d",&a[i][j]); } } int i,j=0; int f=0; for(i=0;i<n;i++) { switch(f) { case 0: while(j<n) { printf("%d ",a[i][j]); j++; } break; case 1: while(j>=0) { printf("%d ",a[i][j]); j--; } } if(f==1) { f=0; j=0; } else if(f==0) { f=1; j=n-1; } } printf("\n"); } return 0; }
[ "barathgopi1699@gmail.com" ]
barathgopi1699@gmail.com
d5e9ee0eea1cadf3c72a0ed11823aa4802337f10
66ab9c18cb12317ed624a20ebcaaed967968db36
/Naive.cpp
608c307b24045637b3e45de82197bb83fced4486
[]
no_license
HarshanaWalpita/String-Matching-Algorithms
79883e5b49bc1a96608eff47eba7e4e30c9f2b2b
04327e3a72d2ead086614b8440134c7725f01dbe
refs/heads/master
2023-01-06T12:13:36.681241
2020-10-30T19:03:42
2020-10-30T19:03:42
308,718,652
0
0
null
null
null
null
UTF-8
C++
false
false
2,324
cpp
#include<iostream> #include<fstream> #include<sstream> #include<string> #include <bits/stdc++.h> using namespace std; int main(){ void search(char* pat, char* str); char temporary[100];//create temporary array char *str = new char[100000000]; //dynamically create 100 million array string line; int i,space,Line,a; ifstream file("pi.txt");//open file while (getline(file,line)){ Line++;//count line from the beging of the file strcpy(temporary, line.c_str());//copy line to temporary array if(line.size()!=0 && Line>19){//skipping above lines in pi file if(Line==21){ space=0; for(a=0; a<line.size(); a++){ if(temporary[a]==' '){ space++; } if(space==2 && temporary[a]!=' '){ str[i]= temporary[a]; //copy temporary array to str array i++; } } } else{ space=0; a=0; while(space<=4){ if(temporary[a]!=' '){ str[i]=temporary[a]; //copy temporary array to str array i++; a++; } else{ space++; a++; } } } } } char pat[] = "970618"; //pattern has to search search(pat, str);// function call file.close();// close file } void search(char* pat, char* str){ int m = strlen(pat); //get pattern length int n = strlen(str); //get text length int times; string array1="Naive Pattern Searching Algorithm"; string array2="Birthday: 970618"; fstream myfile; myfile.open("results.txt",ios::out | ios::app); myfile<<endl; myfile<<array1<<endl;//write to results file myfile<<array2<<endl; for (int i = 0; i <= n - m; i++) { //search for pattern int j; for (j = 0; j < m; j++){ if (str[i + j] != pat[j]){ break; } } if (j == m){ myfile<<i<<endl;//write indexes to the results file times++;//count times } } cout<<pat<<" pattern found in "<<times<<" times"<<endl; cout<<"Indexes are successfully write to the file"<<endl; myfile.close();//close file }
[ "harshanawalpita@gmail.com" ]
harshanawalpita@gmail.com
14a2aa6902cd7010de39f0530ccc11b2c14caf98
af172028a211cd5ec72b254bbe506cacfe1d9e60
/FBDataPackLib/library.cpp
2c39928ccf0a219c00dae6e201f8691613fb8e2c
[]
no_license
fastbird/fastbirdEngine
c99ea03416217696ca048db96da7346c7001d24a
619e1c3af72a58ff939c3ecba8f5cc56b5ea3144
refs/heads/master
2021-01-17T00:26:01.866593
2017-06-17T10:21:05
2017-06-17T10:21:05
22,362,299
18
6
null
2015-12-04T06:32:44
2014-07-29T00:17:23
C++
UTF-8
C++
false
false
1,342
cpp
/* ----------------------------------------------------------------------------- This source file is part of fastbird engine For the latest info, see http://www.jungwan.net/ Copyright (c) 2013-2015 Jungwan Byun Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */
[ "jungwan82@gmail.com" ]
jungwan82@gmail.com
d6b102a0cb07c2aded6bb2f308e0ba70088decd9
e16deb573683cedf0acaeaca813ebbc0aa88c07a
/PotatoGame/Mesh.h
e6e9f942829a80cb2a40e27eaa8982fd30247990
[]
no_license
marcAndreTremblay/PotatoGame
46dfecb6712d08d6279569682709b424db0a361f
95eaa36d5dc5a39c4fe0d082842ef3bbd7511cea
refs/heads/master
2021-01-11T15:59:32.914979
2017-07-11T03:47:50
2017-07-11T03:47:50
79,973,342
0
0
null
null
null
null
UTF-8
C++
false
false
683
h
#if !defined(PG_MESH_H) #define PG_MESH_H #include "stdafx.h" #include "Core.h" #include "List.h" #include "String.h" #include "BuildableObject.h" #include "Shader.h" namespace PG { namespace Engine { class Mesh : public BuildableObject { protected: PGShader* Shader; GLuint VAO; GLuint VBO; private: public: Mesh(PGShader* shader) :BuildableObject() { this->Shader = shader; glGenVertexArrays(1, &this->VAO); glGenBuffers(1, &this->VBO); } ~Mesh() { delete(this->Shader); glDeleteVertexArrays(1, &this->VAO); glDeleteBuffers(1, &this->VBO); } void Mesh::Build() override = 0; void Mesh::Render(); }; } } #endif
[ "marct549@gmail.com" ]
marct549@gmail.com
b60cba1c5c2803973d8837d81f028f2ffd29b70e
dab2594d27cd99cdf7a303b2967598d507ff9fad
/Source/Rendering/Viewport.cpp
3dcb1a47be91535f3d0313d4f64f699845bc7fa9
[]
no_license
aradel/TGL
f228965af10687bdf8e0ba71c00f512bac2d2582
89e712989a7d7cb405c8c9933ed9de469af649d3
refs/heads/master
2021-04-25T09:33:24.396780
2018-01-06T13:09:39
2018-01-06T13:09:39
113,698,335
0
0
null
null
null
null
UTF-8
C++
false
false
307
cpp
#include "Viewport.hpp" TGL::ViewPort::ViewPort() { } TGL::ViewPort::ViewPort(uint16 xTopLeft, uint16 yTopLeft, uint16 xWidth, uint16 yHeight) { this->xTopLeft = xTopLeft; this->yTopLeft = yTopLeft; this->xWidth = xWidth; this->yHeight = yHeight; } TGL::ViewPort::~ViewPort() { }
[ "tobias_lundstrom@hotmail.com" ]
tobias_lundstrom@hotmail.com
9e96bd344b5ac8b2f1f2ca97d48650a7e27262be
63e1160aa422ea8e57d5398d1b150ab3f7eefeb9
/B/mark.h
294ea9f68fe76cb0d081b0dcfa402acba9f1f2ae
[]
no_license
orimoshe-rnd/Test
19b80f86458c0d47dbead0b2c6c8560544b8bab3
fd271caf9557d7d54b5146c32e913c58ea042ba4
refs/heads/master
2023-05-08T00:39:53.707881
2021-06-06T12:58:59
2021-06-06T12:58:59
374,359,677
0
0
null
null
null
null
UTF-8
C++
false
false
655
h
#pragma once #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QWidget> class Mark : public QWidget { Q_OBJECT public: QHBoxLayout *layout; QLineEdit *name; QLabel *label_x; QLineEdit *x; QLabel *label_y; QLineEdit *y; QLabel *label_z; QLineEdit *z; Mark(QWidget* parent, QString name, double X, double Y, double Z); void update(QString objectName, double X, double Y, double Z); };
[ "carmely@rafael.co.il" ]
carmely@rafael.co.il
fa57dcd04b70a32de2680d36e34f11cf41ffd39c
a92b18defb50c5d1118a11bc364f17b148312028
/src/prod/src/inc/clr/utilcode.h
f9275fa39024ceeb2839a62e468d59891f8936d9
[ "MIT" ]
permissive
KDSBest/service-fabric
34694e150fde662286e25f048fb763c97606382e
fe61c45b15a30fb089ad891c68c893b3a976e404
refs/heads/master
2023-01-28T23:19:25.040275
2020-11-30T11:11:58
2020-11-30T11:11:58
301,365,601
1
0
MIT
2020-11-30T11:11:59
2020-10-05T10:05:53
null
UTF-8
C++
false
false
189,842
h
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #ifndef __UtilCode_h__ #define __UtilCode_h__ #include "crtwrap.h" #include "winwrap.h" #include <wchar.h> #include <stdio.h> #include <malloc.h> #include <ole2.h> #include <oleauto.h> #include <limits.h> #include "clrtypes.h" #include "safewrap.h" #include "volatile.h" #include <daccess.h> #include "clrhost.h" #include "debugmacros.h" #include "corhlprpriv.h" #include "winnls.h" #include "check.h" #include "safemath.h" #include "clr_std/type_traits" #include "contract.h" #include "entrypoints.h" #include "clrnt.h" // Values for the names of Watson const WCHAR kWatsonName1[] = W("drwatson"); const WCHAR kWatsonName2[] = W("drwtsn32"); #include "random.h" // Windows CoreSystem has a different naming scheme for some dlls, which we must take account of when doing // LoadLibrary and the like. #if defined(FEATURE_CORESYSTEM) #define WINDOWS_KERNEL32_DLLNAME_A "kernelbase" #define WINDOWS_KERNEL32_DLLNAME_W W("kernelbase") #elif !defined(FEATURE_CORESYSTEM) || defined(CROSS_COMPILE) #define WINDOWS_KERNEL32_DLLNAME_A "kernel32" #define WINDOWS_KERNEL32_DLLNAME_W W("kernel32") #endif class StringArrayList; #if !defined(_DEBUG_IMPL) && defined(_DEBUG) && !defined(DACCESS_COMPILE) #define _DEBUG_IMPL 1 #endif #ifdef _TARGET_ARM_ // Under ARM we generate code only with Thumb encoding. In order to ensure we execute such code in the correct // mode we must ensure the low-order bit is set in any code address we'll call as a sub-routine. In C++ this // is handled automatically for us by the compiler. When generating and working with code generated // dynamically we have to be careful to set or mask-out this bit as appropriate. #ifndef THUMB_CODE #define THUMB_CODE 1 #endif // Given a WORD extract the bitfield [lowbit, highbit] (i.e. BitExtract(0xffff, 15, 0) == 0xffff). inline WORD BitExtract(WORD wValue, DWORD highbit, DWORD lowbit) { _ASSERTE((highbit < 16) && (lowbit < 16) && (highbit >= lowbit)); return (wValue >> lowbit) & ((1 << ((highbit - lowbit) + 1)) - 1); } // Determine whether an ARM Thumb mode instruction is 32-bit or 16-bit based on the first WORD of the // instruction. inline bool Is32BitInstruction(WORD opcode) { return BitExtract(opcode, 15, 11) >= 0x1d; } template <typename ResultType, typename SourceType> inline ResultType DataPointerToThumbCode(SourceType pCode) { return (ResultType)(((UINT_PTR)pCode) | THUMB_CODE); } template <typename ResultType, typename SourceType> inline ResultType ThumbCodeToDataPointer(SourceType pCode) { return (ResultType)(((UINT_PTR)pCode) & ~THUMB_CODE); } #endif // _TARGET_ARM_ // Convert from a PCODE to the corresponding PINSTR. On many architectures this will be the identity function; // on ARM, this will mask off the THUMB bit. inline TADDR PCODEToPINSTR(PCODE pc) { #ifdef _TARGET_ARM_ return ThumbCodeToDataPointer<TADDR,PCODE>(pc); #else return dac_cast<PCODE>(pc); #endif } typedef LPCSTR LPCUTF8; typedef LPSTR LPUTF8; #include "nsutilpriv.h" #include "stdmacros.h" /* // This is for WinCE #ifdef VERIFY #undef VERIFY #endif #ifdef _ASSERTE #undef _ASSERTE #endif */ //********** Macros. ********************************************************** #ifndef FORCEINLINE #if _MSC_VER < 1200 #define FORCEINLINE inline #else #define FORCEINLINE __forceinline #endif #endif #ifndef DEBUG_NOINLINE #if defined(_DEBUG) #define DEBUG_NOINLINE __declspec(noinline) #else #define DEBUG_NOINLINE #endif #endif #ifndef DBG_NOINLINE_X86__RET_INLINE #if defined(_DEBUG) && defined(_TARGET_X86_) // this exists to make scan work on x86. #define DBG_NOINLINE_X86__RET_INLINE __declspec(noinline) #else #define DBG_NOINLINE_X86__RET_INLINE FORCEINLINE #endif #endif #include <stddef.h> // for offsetof #ifndef NumItems // Number of elements in a fixed-size array #define NumItems(s) (sizeof(s) / sizeof(s[0])) #endif #ifndef StrLen // Number of characters in a string literal. Excludes terminating NULL. #define StrLen(str) (NumItems(str) - 1) #endif #define IS_DIGIT(ch) ((ch >= W('0')) && (ch <= W('9'))) #define DIGIT_TO_INT(ch) (ch - W('0')) #define INT_TO_DIGIT(i) ((WCHAR)(W('0') + i)) #define IS_HEXDIGIT(ch) (((ch >= W('a')) && (ch <= W('f'))) || \ ((ch >= W('A')) && (ch <= W('F')))) #define HEXDIGIT_TO_INT(ch) ((towlower(ch) - W('a')) + 10) #define INT_TO_HEXDIGIT(i) ((WCHAR)(W('a') + (i - 10))) // Helper will 4 byte align a value, rounding up. #define ALIGN4BYTE(val) (((val) + 3) & ~0x3) #ifdef _DEBUG #define DEBUGARG(x) , x #else #define DEBUGARG(x) #endif #ifndef sizeofmember // Returns the size of a class or struct member. #define sizeofmember(c,m) (sizeof(((c*)0)->m)) #endif //=--------------------------------------------------------------------------= // Prefast helpers. // #include "safemath.h" //=--------------------------------------------------------------------------= // string helpers. // // given and ANSI String, copy it into a wide buffer. // be careful about scoping when using this macro! // // how to use the below two macros: // // ... // LPSTR pszA; // pszA = MyGetAnsiStringRoutine(); // MAKE_WIDEPTR_FROMANSI(pwsz, pszA); // MyUseWideStringRoutine(pwsz); // ... // // similarily for MAKE_ANSIPTR_FROMWIDE. note that the first param does not // have to be declared, and no clean up must be done. // // We'll define an upper limit that allows multiplication by 4 (the max // bytes/char in UTF-8) but still remains positive, and allows some room for pad. // Under normal circumstances, we should never get anywhere near this limit. #define MAKE_MAX_LENGTH 0x1fffff00 #ifndef MAKE_TOOLONGACTION #define MAKE_TOOLONGACTION ThrowHR(COR_E_OVERFLOW) #endif #ifndef MAKE_TRANSLATIONFAILED #define MAKE_TRANSLATIONFAILED ThrowWin32(ERROR_NO_UNICODE_TRANSLATION) #endif // This version throws on conversion errors (ie, no best fit character // mapping to characters that look similar, and no use of the default char // ('?') when printing out unrepresentable characters. Use this method for // most development in the EE, especially anything like metadata or class // names. See the BESTFIT version if you're printing out info to the console. #define MAKE_MULTIBYTE_FROMWIDE(ptrname, widestr, codepage) \ int __l##ptrname = (int)wcslen(widestr); \ if (__l##ptrname > MAKE_MAX_LENGTH) \ MAKE_TOOLONGACTION; \ __l##ptrname = (int)((__l##ptrname + 1) * 2 * sizeof(char)); \ CQuickBytes __CQuickBytes##ptrname; \ __CQuickBytes##ptrname.AllocThrows(__l##ptrname); \ BOOL __b##ptrname; \ DWORD __cBytes##ptrname = WszWideCharToMultiByte(codepage, WC_NO_BEST_FIT_CHARS, widestr, -1, (LPSTR)__CQuickBytes##ptrname.Ptr(), __l##ptrname, NULL, &__b##ptrname); \ if (__b##ptrname || (__cBytes##ptrname == 0 && (widestr[0] != W('\0')))) { \ MAKE_TRANSLATIONFAILED; \ } \ LPSTR ptrname = (LPSTR)__CQuickBytes##ptrname.Ptr() // This version does best fit character mapping and also allows the use // of the default char ('?') for any Unicode character that isn't // representable. This is reasonable for writing to the console, but // shouldn't be used for most string conversions. #define MAKE_MULTIBYTE_FROMWIDE_BESTFIT(ptrname, widestr, codepage) \ int __l##ptrname = (int)wcslen(widestr); \ if (__l##ptrname > MAKE_MAX_LENGTH) \ MAKE_TOOLONGACTION; \ __l##ptrname = (int)((__l##ptrname + 1) * 2 * sizeof(char)); \ CQuickBytes __CQuickBytes##ptrname; \ __CQuickBytes##ptrname.AllocThrows(__l##ptrname); \ DWORD __cBytes##ptrname = WszWideCharToMultiByte(codepage, 0, widestr, -1, (LPSTR)__CQuickBytes##ptrname.Ptr(), __l##ptrname, NULL, NULL); \ if (__cBytes##ptrname == 0 && __l##ptrname != 0) { \ MAKE_TRANSLATIONFAILED; \ } \ LPSTR ptrname = (LPSTR)__CQuickBytes##ptrname.Ptr() // Use for anything critical other than output to console, where weird // character mappings are unacceptable. #define MAKE_ANSIPTR_FROMWIDE(ptrname, widestr) MAKE_MULTIBYTE_FROMWIDE(ptrname, widestr, CP_ACP) // Use for output to the console. #define MAKE_ANSIPTR_FROMWIDE_BESTFIT(ptrname, widestr) MAKE_MULTIBYTE_FROMWIDE_BESTFIT(ptrname, widestr, CP_ACP) #define MAKE_WIDEPTR_FROMANSI(ptrname, ansistr) \ CQuickBytes __qb##ptrname; \ int __l##ptrname; \ __l##ptrname = WszMultiByteToWideChar(CP_ACP, 0, ansistr, -1, 0, 0); \ if (__l##ptrname > MAKE_MAX_LENGTH) \ MAKE_TOOLONGACTION; \ LPWSTR ptrname = (LPWSTR) __qb##ptrname.AllocThrows((__l##ptrname+1)*sizeof(WCHAR)); \ if (WszMultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, ansistr, -1, ptrname, __l##ptrname) == 0) { \ MAKE_TRANSLATIONFAILED; \ } #define MAKE_WIDEPTR_FROMANSI_NOTHROW(ptrname, ansistr) \ CQuickBytes __qb##ptrname; \ LPWSTR ptrname = 0; \ int __l##ptrname; \ __l##ptrname = WszMultiByteToWideChar(CP_ACP, 0, ansistr, -1, 0, 0); \ if (__l##ptrname <= MAKE_MAX_LENGTH) { \ ptrname = (LPWSTR) __qb##ptrname.AllocNoThrow((__l##ptrname+1)*sizeof(WCHAR)); \ if (ptrname) { \ if (WszMultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, ansistr, -1, ptrname, __l##ptrname) != 0) { \ ptrname[__l##ptrname] = 0; \ } else { \ ptrname = 0; \ } \ } \ } #define MAKE_UTF8PTR_FROMWIDE(ptrname, widestr) CQuickBytes _##ptrname; _##ptrname.ConvertUnicode_Utf8(widestr); LPSTR ptrname = (LPSTR) _##ptrname.Ptr(); #define MAKE_UTF8PTR_FROMWIDE_NOTHROW(ptrname, widestr) \ CQuickBytes __qb##ptrname; \ int __l##ptrname = (int)wcslen(widestr); \ LPUTF8 ptrname = 0; \ if (__l##ptrname <= MAKE_MAX_LENGTH) { \ __l##ptrname = (int)((__l##ptrname + 1) * 2 * sizeof(char)); \ ptrname = (LPUTF8) __qb##ptrname.AllocNoThrow(__l##ptrname); \ } \ if (ptrname) { \ INT32 __lresult##ptrname=WszWideCharToMultiByte(CP_UTF8, 0, widestr, -1, ptrname, __l##ptrname-1, NULL, NULL); \ DWORD __dwCaptureLastError##ptrname = ::GetLastError(); \ if ((__lresult##ptrname==0) && (((LPCWSTR)widestr)[0] != W('\0'))) { \ if (__dwCaptureLastError##ptrname==ERROR_INSUFFICIENT_BUFFER) { \ INT32 __lsize##ptrname=WszWideCharToMultiByte(CP_UTF8, 0, widestr, -1, NULL, 0, NULL, NULL); \ ptrname = (LPSTR) __qb##ptrname .AllocNoThrow(__lsize##ptrname); \ if (ptrname) { \ if (WszWideCharToMultiByte(CP_UTF8, 0, widestr, -1, ptrname, __lsize##ptrname, NULL, NULL) != 0) { \ ptrname[__l##ptrname] = 0; \ } else { \ ptrname = 0; \ } \ } \ } \ else { \ ptrname = 0; \ } \ } \ } \ #define MAKE_WIDEPTR_FROMUTF8N(ptrname, utf8str, n8chrs) \ CQuickBytes __qb##ptrname; \ int __l##ptrname; \ __l##ptrname = WszMultiByteToWideChar(CP_UTF8, 0, utf8str, n8chrs, 0, 0); \ if (__l##ptrname > MAKE_MAX_LENGTH) \ MAKE_TOOLONGACTION; \ LPWSTR ptrname = (LPWSTR) __qb##ptrname .AllocThrows((__l##ptrname+1)*sizeof(WCHAR)); \ if (0==WszMultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8str, n8chrs, ptrname, __l##ptrname)) { \ MAKE_TRANSLATIONFAILED; \ } \ ptrname[__l##ptrname] = 0; #define MAKE_WIDEPTR_FROMUTF8(ptrname, utf8str) CQuickBytes _##ptrname; _##ptrname.ConvertUtf8_Unicode(utf8str); LPCWSTR ptrname = (LPCWSTR) _##ptrname.Ptr(); #define MAKE_WIDEPTR_FROMUTF8N_NOTHROW(ptrname, utf8str, n8chrs) \ CQuickBytes __qb##ptrname; \ int __l##ptrname; \ LPWSTR ptrname = 0; \ __l##ptrname = WszMultiByteToWideChar(CP_UTF8, 0, utf8str, n8chrs, 0, 0); \ if (__l##ptrname <= MAKE_MAX_LENGTH) { \ ptrname = (LPWSTR) __qb##ptrname.AllocNoThrow((__l##ptrname+1)*sizeof(WCHAR)); \ if (ptrname) { \ if (WszMultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8str, n8chrs, ptrname, __l##ptrname) != 0) { \ ptrname[__l##ptrname] = 0; \ } else { \ ptrname = 0; \ } \ } \ } #define MAKE_WIDEPTR_FROMUTF8_NOTHROW(ptrname, utf8str) MAKE_WIDEPTR_FROMUTF8N_NOTHROW(ptrname, utf8str, -1) // This method takes the number of characters #define MAKE_MULTIBYTE_FROMWIDEN(ptrname, widestr, _nCharacters, _pCnt, codepage) \ CQuickBytes __qb##ptrname; \ int __l##ptrname; \ __l##ptrname = WszWideCharToMultiByte(codepage, WC_NO_BEST_FIT_CHARS, widestr, _nCharacters, NULL, 0, NULL, NULL); \ if (__l##ptrname > MAKE_MAX_LENGTH) \ MAKE_TOOLONGACTION; \ ptrname = (LPUTF8) __qb##ptrname .AllocThrows(__l##ptrname+1); \ BOOL __b##ptrname; \ DWORD _pCnt = WszWideCharToMultiByte(codepage, WC_NO_BEST_FIT_CHARS, widestr, _nCharacters, ptrname, __l##ptrname, NULL, &__b##ptrname); \ if (__b##ptrname || (_pCnt == 0 && _nCharacters > 0)) { \ MAKE_TRANSLATIONFAILED; \ } \ ptrname[__l##ptrname] = 0; #define MAKE_MULTIBYTE_FROMWIDEN_BESTFIT(ptrname, widestr, _nCharacters, _pCnt, codepage) \ CQuickBytes __qb##ptrname; \ int __l##ptrname; \ __l##ptrname = WszWideCharToMultiByte(codepage, 0, widestr, _nCharacters, NULL, 0, NULL, NULL); \ if (__l##ptrname > MAKE_MAX_LENGTH) \ MAKE_TOOLONGACTION; \ ptrname = (LPUTF8) __qb##ptrname .AllocThrows(__l##ptrname+1); \ DWORD _pCnt = WszWideCharToMultiByte(codepage, 0, widestr, _nCharacters, ptrname, __l##ptrname, NULL, NULL); \ if (_pCnt == 0 && _nCharacters > 0) { \ MAKE_TRANSLATIONFAILED; \ } \ ptrname[__l##ptrname] = 0; #define MAKE_ANSIPTR_FROMWIDEN(ptrname, widestr, _nCharacters, _pCnt) \ MAKE_MULTIBYTE_FROMWIDEN(ptrname, widestr, _nCharacters, _pCnt, CP_ACP) inline LPWSTR DuplicateString( LPCWSTR wszString, size_t cchString) { STATIC_CONTRACT_NOTHROW; LPWSTR wszDup = NULL; if (wszString != NULL) { wszDup = new (nothrow) WCHAR[cchString + 1]; if (wszDup != NULL) { wcscpy_s(wszDup, cchString + 1, wszString); } } return wszDup; } inline LPWSTR DuplicateString( LPCWSTR wszString) { STATIC_CONTRACT_NOTHROW; if (wszString != NULL) { return DuplicateString(wszString, wcslen(wszString)); } else { return NULL; } } void DECLSPEC_NORETURN ThrowOutOfMemory(); inline LPWSTR DuplicateStringThrowing( LPCWSTR wszString, size_t cchString) { STATIC_CONTRACT_THROWS; if (wszString == NULL) return NULL; LPWSTR wszDup = DuplicateString(wszString, cchString); if (wszDup == NULL) ThrowOutOfMemory(); return wszDup; } inline LPWSTR DuplicateStringThrowing( LPCWSTR wszString) { STATIC_CONTRACT_THROWS; if (wszString == NULL) return NULL; LPWSTR wszDup = DuplicateString(wszString); if (wszDup == NULL) ThrowOutOfMemory(); return wszDup; } //***************************************************************************** // Placement new is used to new and object at an exact location. The pointer // is simply returned to the caller without actually using the heap. The // advantage here is that you cause the ctor() code for the object to be run. // This is ideal for heaps of C++ objects that need to get init'd multiple times. // Example: // void *pMem = GetMemFromSomePlace(); // Foo *p = new (pMem) Foo; // DoSomething(p); // p->~Foo(); //***************************************************************************** #ifndef __PLACEMENT_NEW_INLINE #define __PLACEMENT_NEW_INLINE inline void *__cdecl operator new(size_t, void *_P) { LIMITED_METHOD_DAC_CONTRACT; return (_P); } #endif // __PLACEMENT_NEW_INLINE /********************************************************************************/ /* portability helpers */ #ifdef _WIN64 #define IN_WIN64(x) x #define IN_WIN32(x) #else #define IN_WIN64(x) #define IN_WIN32(x) x #endif void * __cdecl operator new(size_t n); _Ret_bytecap_(_Size) void * __cdecl operator new[](size_t n); void __cdecl operator delete(void *p); void __cdecl operator delete[](void *p); #ifdef _DEBUG_IMPL HRESULT _OutOfMemory(LPCSTR szFile, int iLine); #define OutOfMemory() _OutOfMemory(__FILE__, __LINE__) #else inline HRESULT OutOfMemory() { LIMITED_METHOD_CONTRACT; return (E_OUTOFMEMORY); } #endif //***************************************************************************** // Handle accessing localizable resource strings //***************************************************************************** // NOTE: Should use locale names as much as possible. LCIDs don't support // custom cultures on Vista+. // TODO: This should always use the names #ifdef FEATURE_USE_LCID typedef LCID LocaleID; typedef LCID LocaleIDValue; #else typedef LPCWSTR LocaleID; typedef WCHAR LocaleIDValue[LOCALE_NAME_MAX_LENGTH]; #endif // Notes about the culture callbacks: // - The language we're operating in can change at *runtime*! // - A process may operate in *multiple* languages. // (ex: Each thread may have it's own language) // - If we don't care what language we're in (or have no way of knowing), // then return a 0-length name and UICULTUREID_DONTCARE for the culture ID. // - GetCultureName() and the GetCultureId() must be in sync (refer to the // same language). // - We have two functions separate functions for better performance. // - The name is used to resolve a directory for MsCorRC.dll. // - The id is used as a key to map to a dll hinstance. // Callback to obtain both the culture name and the culture's parent culture name typedef HRESULT (*FPGETTHREADUICULTURENAMES)(__inout StringArrayList* pCultureNames); #ifdef FEATURE_USE_LCID // Callback to return the culture ID. const LCID UICULTUREID_DONTCARE = (LCID)-1; #else const LPCWSTR UICULTUREID_DONTCARE = NULL; #endif typedef int (*FPGETTHREADUICULTUREID)(LocaleIDValue*); HMODULE CLRLoadLibrary(LPCWSTR lpLibFileName); HMODULE CLRLoadLibraryEx(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags); BOOL CLRFreeLibrary(HMODULE hModule); // Prevent people from using LoadStringRC & LoadStringRCEx from inside the product since it // causes issues with having the wrong version picked up inside the shim. #define LoadStringRC __error("From inside the CLR, use UtilLoadStringRC; LoadStringRC is only meant to be exported.") #define LoadStringRCEx __error("From inside the CLR, use UtilLoadStringRCEx; LoadStringRC is only meant to be exported.") // Load a string using the resources for the current module. STDAPI UtilLoadStringRC(UINT iResouceID, __out_ecount (iMax) LPWSTR szBuffer, int iMax, int bQuiet=FALSE); #if ENABLE_DOWNLEVEL_FOR_NLS STDAPI UtilLoadStringRCEx(LCID lcid, UINT iResourceID, __out_ecount (iMax) LPWSTR szBuffer, int iMax, int bQuiet, int *pcwchUsed); #endif // Specify callbacks so that UtilLoadStringRC can find out which language we're in. // If no callbacks specified (or both parameters are NULL), we default to the // resource dll in the root (which is probably english). void SetResourceCultureCallbacks( FPGETTHREADUICULTURENAMES fpGetThreadUICultureNames, FPGETTHREADUICULTUREID fpGetThreadUICultureId ); void GetResourceCultureCallbacks( FPGETTHREADUICULTURENAMES* fpGetThreadUICultureNames, FPGETTHREADUICULTUREID* fpGetThreadUICultureId ); #if !defined(DACCESS_COMPILE) // Get the MUI ID, on downlevel platforms where MUI is not supported it // returns the default system ID. extern int GetMUILanguageID(LocaleIDValue* pResult); extern HRESULT GetMUILanguageNames(__inout StringArrayList* pCultureNames); #endif // !defined(DACCESS_COMPILE) //***************************************************************************** // Use this class by privately deriving from noncopyable to disallow copying of // your class. //***************************************************************************** class noncopyable { protected: noncopyable() {} ~noncopyable() {} private: noncopyable(const noncopyable&); const noncopyable& operator=(const noncopyable&); }; //***************************************************************************** // Must associate each handle to an instance of a resource dll with the int // that it represents //***************************************************************************** typedef HINSTANCE HRESOURCEDLL; class CCulturedHInstance { LocaleIDValue m_LangId; HRESOURCEDLL m_hInst; BOOL m_fMissing; public: CCulturedHInstance() { LIMITED_METHOD_CONTRACT; m_hInst = NULL; m_fMissing = FALSE; } BOOL HasID(LocaleID id) { _ASSERTE(m_hInst != NULL || m_fMissing); if (id == UICULTUREID_DONTCARE) return FALSE; #ifdef FEATURE_USE_LCID return id == m_LangId; #else return wcscmp(id, m_LangId) == 0; #endif } HRESOURCEDLL GetLibraryHandle() { return m_hInst; } BOOL IsSet() { return m_hInst != NULL; } BOOL IsMissing() { return m_fMissing; } void SetMissing(LocaleID id) { _ASSERTE(m_hInst == NULL); SetId(id); m_fMissing = TRUE; } void Set(LocaleID id, HRESOURCEDLL hInst) { _ASSERTE(m_hInst == NULL); _ASSERTE(m_fMissing == FALSE); SetId(id); m_hInst = hInst; } private: void SetId(LocaleID id) { #ifdef FEATURE_USE_LCID m_LangId = id; #else if (id != UICULTUREID_DONTCARE) { wcsncpy_s(m_LangId, NumItems(m_LangId), id, NumItems(m_LangId)); m_LangId[NumItems(m_LangId)-1] = W('\0'); } else { m_LangId[0] = W('\0'); } #endif } }; #ifndef DACCESS_COMPILE void AddThreadPreferredUILanguages(StringArrayList* pArray); #endif //***************************************************************************** // CCompRC manages string Resource access for COM+. This includes loading // the MsCorRC.dll for resources as well allowing each thread to use a // a different localized version. //***************************************************************************** class CCompRC { public: enum ResourceCategory { // must be present Required, // present in Desktop CLR and Core CLR + debug pack, an error // If missing, get a generic error message instead Error, // present in Desktop CLR and Core CLR + debug pack, normal operation (e.g tracing) // if missing, get a generic "resource not found" message instead Debugging, // present in Desktop CLR, optional for CoreCLR DesktopCLR, // might not be present, non essential Optional }; CCompRC() { // This constructor will be fired up on startup. Make sure it doesn't // do anything besides zero-out out values. m_bUseFallback = FALSE; m_fpGetThreadUICultureId = NULL; m_fpGetThreadUICultureNames = NULL; m_pHash = NULL; m_nHashSize = 0; m_csMap = NULL; m_pResourceFile = NULL; }// CCompRC HRESULT Init(LPCWSTR pResourceFile, BOOL bUseFallback = FALSE); void Destroy(); BOOL ShouldUseFallback() { LIMITED_METHOD_CONTRACT; return m_bUseFallback; }; static void SetIsMscoree() {s_bIsMscoree = TRUE;} HRESULT LoadString(ResourceCategory eCategory, UINT iResourceID, __out_ecount (iMax) LPWSTR szBuffer, int iMax , int *pcwchUsed=NULL); HRESULT LoadString(ResourceCategory eCategory, LocaleID langId, UINT iResourceID, __out_ecount (iMax) LPWSTR szBuffer, int iMax, int *pcwchUsed); void SetResourceCultureCallbacks( FPGETTHREADUICULTURENAMES fpGetThreadUICultureNames, FPGETTHREADUICULTUREID fpGetThreadUICultureId ); void GetResourceCultureCallbacks( FPGETTHREADUICULTURENAMES* fpGetThreadUICultureNames, FPGETTHREADUICULTUREID* fpGetThreadUICultureId ); HRESULT LoadMUILibrary(HRESOURCEDLL * pHInst); // Get the default resource location (mscorrc.dll for desktop, mscorrc.debug.dll for CoreCLR) static CCompRC* GetDefaultResourceDll(); #ifdef FEATURE_CORECLR // Get the generic messages dll (Silverlight only, mscorrc.dll) static CCompRC* GetFallbackResourceDll(); #endif static void ShutdownDefaultResourceDll(); static void GetDefaultCallbacks( FPGETTHREADUICULTURENAMES* fpGetThreadUICultureNames, FPGETTHREADUICULTUREID* fpGetThreadUICultureId) { WRAPPER_NO_CONTRACT; m_DefaultResourceDll.GetResourceCultureCallbacks( fpGetThreadUICultureNames, fpGetThreadUICultureId); } static void SetDefaultCallbacks( FPGETTHREADUICULTURENAMES fpGetThreadUICultureNames, FPGETTHREADUICULTUREID fpGetThreadUICultureId) { WRAPPER_NO_CONTRACT; // Either both are NULL or neither are NULL _ASSERTE((fpGetThreadUICultureNames != NULL) == (fpGetThreadUICultureId != NULL)); m_DefaultResourceDll.SetResourceCultureCallbacks( fpGetThreadUICultureNames, fpGetThreadUICultureId); #ifdef FEATURE_CORECLR m_FallbackResourceDll.SetResourceCultureCallbacks( fpGetThreadUICultureNames, fpGetThreadUICultureId); #endif } #ifdef USE_FORMATMESSAGE_WRAPPER DWORD PALAPI static FormatMessage( IN DWORD dwFlags, IN LPCVOID lpSource, IN DWORD dwMessageId, IN DWORD dwLanguageId, OUT LPWSTR lpBuffer, IN DWORD nSize, IN va_list *Arguments); #endif // USE_FORMATMESSAGE_WRAPPER private: HRESULT GetLibrary(LocaleID langId, HRESOURCEDLL* phInst); #ifndef DACCESS_COMPILE HRESULT LoadLibraryHelper(HRESOURCEDLL *pHInst, __out_ecount(rcPathSize) WCHAR *rcPath, const DWORD rcPathSize); HRESULT LoadLibrary(HRESOURCEDLL * pHInst); HRESULT LoadResourceFile(HRESOURCEDLL * pHInst, LPCWSTR lpFileName); #endif // We do not have global constructors any more static LONG m_dwDefaultInitialized; static CCompRC m_DefaultResourceDll; static LPCWSTR m_pDefaultResource; #ifdef FEATURE_CORECLR // fallback resources if debug pack is not installed static LONG m_dwFallbackInitialized; static CCompRC m_FallbackResourceDll; static LPCWSTR m_pFallbackResource; #endif // We must map between a thread's int and a dll instance. // Since we only expect 1 language almost all of the time, we'll special case // that and then use a variable size map for everything else. CCulturedHInstance m_Primary; CCulturedHInstance * m_pHash; int m_nHashSize; CRITSEC_COOKIE m_csMap; LPCWSTR m_pResourceFile; // Main accessors for hash HRESOURCEDLL LookupNode(LocaleID langId, BOOL &fMissing); HRESULT AddMapNode(LocaleID langId, HRESOURCEDLL hInst, BOOL fMissing = FALSE); FPGETTHREADUICULTUREID m_fpGetThreadUICultureId; FPGETTHREADUICULTURENAMES m_fpGetThreadUICultureNames; BOOL m_bUseFallback; static BOOL s_bIsMscoree; }; HRESULT UtilLoadResourceString(CCompRC::ResourceCategory eCategory, UINT iResouceID, __out_ecount (iMax) LPWSTR szBuffer, int iMax); int UtilMessageBox( HWND hWnd, // Handle to Owner Window UINT uText, // Resource Identifier for Text message UINT uCaption, // Resource Identifier for Caption UINT uType, // Style of MessageBox BOOL displayForNonInteractive, // Display even if the process is running non interactive BOOL ShowFileNameInTitle, // Flag to show FileName in Caption ...); // Additional Arguments int UtilMessageBoxNonLocalized( HWND hWnd, // Handle to Owner Window LPCWSTR lpText, // Resource Identifier for Text message LPCWSTR lpTitle, // Resource Identifier for Caption UINT uType, // Style of MessageBox BOOL displayForNonInteractive, // Display even if the process is running non interactive BOOL ShowFileNameInTitle, // Flag to show FileName in Caption ...); // Additional Arguments int UtilMessageBoxVA( HWND hWnd, // Handle to Owner Window UINT uText, // Resource Identifier for Text message UINT uCaption, // Resource Identifier for Caption UINT uType, // Style of MessageBox BOOL displayForNonInteractive, // Display even if the process is running non interactive BOOL ShowFileNameInTitle, // Flag to show FileName in Caption va_list args); // Additional Arguments int UtilMessageBoxNonLocalizedVA( HWND hWnd, // Handle to Owner Window LPCWSTR lpText, // Text message LPCWSTR lpCaption, // Caption UINT uType, // Style of MessageBox BOOL displayForNonInteractive, // Display even if the process is running non interactive BOOL ShowFileNameInTitle, // Flag to show FileName in Caption BOOL * pInputFromUser, // To distinguish between user pressing abort vs. assuming abort. va_list args); // Additional Arguments int UtilMessageBoxNonLocalizedVA( HWND hWnd, // Handle to Owner Window LPCWSTR lpText, // Text message LPCWSTR lpCaption, // Caption LPCWSTR lpDetails, // Details that may be shown in a collapsed extended area of the dialog (Vista or higher). UINT uType, // Style of MessageBox BOOL displayForNonInteractive, // Display even if the process is running non interactive BOOL ShowFileNameInTitle, // Flag to show FileName in Caption BOOL * pInputFromUser, // To distinguish between user pressing abort vs. assuming abort. va_list args); // Additional Arguments int UtilMessageBoxCatastrophic( UINT uText, // Text for MessageBox UINT uTitle, // Title for MessageBox UINT uType, // Style of MessageBox BOOL ShowFileNameInTitle, // Flag to show FileName in Caption ...); int UtilMessageBoxCatastrophicNonLocalized( LPCWSTR lpText, // Text for MessageBox LPCWSTR lpTitle, // Title for MessageBox UINT uType, // Style of MessageBox BOOL ShowFileNameInTitle, // Flag to show FileName in Caption ...); int UtilMessageBoxCatastrophicVA( UINT uText, // Text for MessageBox UINT uTitle, // Title for MessageBox UINT uType, // Style of MessageBox BOOL ShowFileNameInTitle, // Flag to show FileName in Caption va_list args); // Additional Arguments int UtilMessageBoxCatastrophicNonLocalizedVA( LPCWSTR lpText, // Text for MessageBox LPCWSTR lpTitle, // Title for MessageBox UINT uType, // Style of MessageBox BOOL ShowFileNameInTitle, // Flag to show FileName in Caption va_list args); // Additional Arguments // The HRESULT_FROM_WIN32 macro evaluates its arguments three times. // <TODO>TODO: All HRESULT_FROM_WIN32(GetLastError()) should be replaced by calls to // this helper function avoid code bloat</TODO> inline HRESULT HRESULT_FROM_GetLastError() { WRAPPER_NO_CONTRACT; DWORD dw = GetLastError(); // Make sure we return a failure if (dw == ERROR_SUCCESS) { _ASSERTE(!"We were expecting to get an error code, but a success code is being returned. Check this code path for Everett!"); return E_FAIL; } else return HRESULT_FROM_WIN32(dw); } inline HRESULT HRESULT_FROM_GetLastErrorNA() { WRAPPER_NO_CONTRACT; DWORD dw = GetLastError(); // Make sure we return a failure if (dw == ERROR_SUCCESS) return E_FAIL; else return HRESULT_FROM_WIN32(dw); } inline HRESULT BadError(HRESULT hr) { LIMITED_METHOD_CONTRACT; _ASSERTE(!"Serious Error"); return (hr); } #define TESTANDRETURN(test, hrVal) \ { \ int ___test = (int)(test); \ if (! ___test) \ return hrVal; \ } #define TESTANDRETURNPOINTER(pointer) \ TESTANDRETURN(pointer!=NULL, E_POINTER) #define TESTANDRETURNMEMORY(pointer) \ TESTANDRETURN(pointer!=NULL, E_OUTOFMEMORY) #define TESTANDRETURNHR(hr) \ TESTANDRETURN(SUCCEEDED(hr), hr) #define TESTANDRETURNARG(argtest) \ TESTANDRETURN(argtest, E_INVALIDARG) // Quick validity check for HANDLEs that are returned by Win32 APIs that // use INVALID_HANDLE_VALUE instead of NULL to indicate an error inline BOOL IsValidHandle(HANDLE h) { LIMITED_METHOD_CONTRACT; return ((h != NULL) && (h != INVALID_HANDLE_VALUE)); } // Count the bits in a value in order iBits time. inline int CountBits(int iNum) { LIMITED_METHOD_CONTRACT; int iBits; for (iBits=0; iNum; iBits++) iNum = iNum & (iNum - 1); return (iBits); } //------------------------------------------------------------------------ // BitPosition: Return the position of the single bit that is set in 'value'. // // Return Value: // The position (0 is LSB) of bit that is set in 'value' // // Notes: // 'value' must have exactly one bit set. // The algorithm is as follows: // - PRIME is a prime bigger than sizeof(unsigned int), which is not of the // form 2^n-1. // - Taking the modulo of 'value' with this will produce a unique hash for all // powers of 2 (which is what "value" is). // - Entries in hashTable[] which are -1 should never be used. There // should be PRIME-8*sizeof(value) entries which are -1 . // inline unsigned BitPosition(unsigned value) { _ASSERTE((value != 0) && ((value & (value-1)) == 0)); #ifndef _TARGET_AMD64_ const unsigned PRIME = 37; static const char hashTable[PRIME] = { -1, 0, 1, 26, 2, 23, 27, -1, 3, 16, 24, 30, 28, 11, -1, 13, 4, 7, 17, -1, 25, 22, 31, 15, 29, 10, 12, 6, -1, 21, 14, 9, 5, 20, 8, 19, 18 }; _ASSERTE(PRIME >= 8*sizeof(value)); _ASSERTE(sizeof(hashTable) == PRIME); unsigned hash = value % PRIME; unsigned index = hashTable[hash]; _ASSERTE(index != (unsigned char)-1); #else // not enabled for x86 because BSF is extremely slow on Atom // (15 clock cycles vs 1-3 on any other Intel CPU post-P4) DWORD index; BitScanForward(&index, value); #endif return index; } // Used to remove trailing zeros from Decimal types. // NOTE: Assumes hi32 bits are empty (used for conversions from Cy->Dec) inline HRESULT DecimalCanonicalize(DECIMAL* dec) { WRAPPER_NO_CONTRACT; // Clear the VARENUM field (*(USHORT*)dec) = 0; // Remove trailing zeros: DECIMAL temp; DECIMAL templast; temp = templast = *dec; // Ensure the hi 32 bits are empty (should be if we came from a currency) if ((DECIMAL_HI32(temp) != 0) || (DECIMAL_SCALE(temp) > 4)) return DISP_E_OVERFLOW; // Return immediately if dec represents a zero. if (DECIMAL_LO32(temp) == 0 && DECIMAL_MID32(temp) == 0) return S_OK; // Compare to the original to see if we've // lost non-zero digits (and make sure we don't overflow the scale BYTE) #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:6219) // "Suppress PREFast warning about Implicit cast between semantically different integer types" #endif while ((DECIMAL_SCALE(temp) <= 4) && (VARCMP_EQ == VarDecCmp(dec, &temp))) { #ifdef _PREFAST_ #pragma warning(pop) #endif templast = temp; // Remove the last digit and normalize. Ignore temp.Hi32 // as Currency values will have a max of 64 bits of data. DECIMAL_SCALE(temp)--; UINT64 temp64 = (((UINT64) DECIMAL_MID32(temp)) << 32) + DECIMAL_LO32(temp); temp64 /= 10; DECIMAL_MID32(temp) = (ULONG)(temp64 >> 32); DECIMAL_LO32(temp) = (ULONG)temp64; } *dec = templast; return S_OK; } //***************************************************************************** // // Paths functions. Use these instead of the CRT. // //***************************************************************************** // secure version! Specify the size of the each buffer in count of elements void SplitPath(register const WCHAR *path, __inout_z __inout_ecount_opt(driveSizeInWords) WCHAR *drive, int driveSizeInWords, __inout_z __inout_ecount_opt(dirSizeInWords) WCHAR *dir, int dirSizeInWords, __inout_z __inout_ecount_opt(fnameSizeInWords) WCHAR *fname, size_t fnameSizeInWords, __inout_z __inout_ecount_opt(extSizeInWords) WCHAR *ext, size_t extSizeInWords); //******************************************************************************* // A much more sensible version that just points to each section of the string. //******************************************************************************* void SplitPathInterior( __in LPCWSTR wszPath, __out_opt LPCWSTR *pwszDrive, __out_opt size_t *pcchDrive, __out_opt LPCWSTR *pwszDir, __out_opt size_t *pcchDir, __out_opt LPCWSTR *pwszFileName, __out_opt size_t *pcchFileName, __out_opt LPCWSTR *pwszExt, __out_opt size_t *pcchExt); void MakePath(__out_ecount (MAX_PATH) register WCHAR *path, __in LPCWSTR drive, __in LPCWSTR dir, __in LPCWSTR fname, __in LPCWSTR ext); WCHAR * FullPath(__out_ecount (maxlen) WCHAR *UserBuf, const WCHAR *path, size_t maxlen); //***************************************************************************** // // SString version of the path functions. // //***************************************************************************** void SplitPath(__in SString const &path, __inout_opt SString *drive, __inout_opt SString *dir, __inout_opt SString *fname, __inout_opt SString *ext); //***************************************************************************** // // **** REGUTIL - Static helper functions for reading/writing to Windows registry. // //***************************************************************************** class REGUTIL { public: //***************************************************************************** enum CORConfigLevel { COR_CONFIG_ENV = 0x01, COR_CONFIG_USER = 0x02, COR_CONFIG_MACHINE = 0x04, COR_CONFIG_FUSION = 0x08, COR_CONFIG_REGISTRY = (COR_CONFIG_USER|COR_CONFIG_MACHINE|COR_CONFIG_FUSION), COR_CONFIG_ALL = (COR_CONFIG_ENV|COR_CONFIG_USER|COR_CONFIG_MACHINE), }; // // NOTE: The following function is deprecated; use the CLRConfig class instead. // To access a configuration value through CLRConfig, add an entry in file:../inc/CLRConfigValues.h. // static DWORD GetConfigDWORD_DontUse_( LPCWSTR name, DWORD defValue, CORConfigLevel level = COR_CONFIG_ALL, BOOL fPrependCOMPLUS = TRUE); // // NOTE: The following function is deprecated; use the CLRConfig class instead. // To access a configuration value through CLRConfig, add an entry in file:../inc/CLRConfigValues.h. // static HRESULT GetConfigDWORD_DontUse_( LPCWSTR name, DWORD defValue, __out DWORD * result, CORConfigLevel level = COR_CONFIG_ALL, BOOL fPrependCOMPLUS = TRUE); static ULONGLONG GetConfigULONGLONG_DontUse_( LPCWSTR name, ULONGLONG defValue, CORConfigLevel level = COR_CONFIG_ALL, BOOL fPrependCOMPLUS = TRUE); // // NOTE: The following function is deprecated; use the CLRConfig class instead. // To access a configuration value through CLRConfig, add an entry in file:../inc/CLRConfigValues.h. // static DWORD GetConfigFlag_DontUse_( LPCWSTR name, DWORD bitToSet, BOOL defValue = FALSE); // // NOTE: The following function is deprecated; use the CLRConfig class instead. // To access a configuration value through CLRConfig, add an entry in file:../inc/CLRConfigValues.h. // static LPWSTR GetConfigString_DontUse_( LPCWSTR name, BOOL fPrependCOMPLUS = TRUE, CORConfigLevel level = COR_CONFIG_ALL, BOOL fUsePerfCache = TRUE); static void FreeConfigString(__in __in_z LPWSTR name); #ifdef FEATURE_CORECLR private: #endif //FEATURE_CORECLR static LPWSTR EnvGetString(LPCWSTR name, BOOL fPrependCOMPLUS); #ifdef FEATURE_CORECLR public: #endif //FEATURE_CORECLR static BOOL UseRegistry(); private: //***************************************************************************** // Get either a DWORD or ULONGLONG. Always puts the result in a ULONGLONG that // you can safely cast to a DWORD if fGetDWORD is TRUE. //***************************************************************************** static HRESULT GetConfigInteger( LPCWSTR name, ULONGLONG defValue, __out ULONGLONG * result, BOOL fGetDWORD = TRUE, CORConfigLevel level = COR_CONFIG_ALL, BOOL fPrependCOMPLUS = TRUE); public: #ifndef FEATURE_CORECLR static void AllowRegistryUse(BOOL fAllowUse); //***************************************************************************** // Open's the given key and returns the value desired. If the key or value is // not found, then the default is returned. //***************************************************************************** static long GetLong( // Return value from registry or default. LPCTSTR szName, // Name of value to get. long iDefault, // Default value to return if not found. LPCTSTR szKey=NULL, // Name of key, NULL==default. HKEY hKey=HKEY_LOCAL_MACHINE);// What key to work on. //***************************************************************************** // Open's the given key and returns the value desired. If the key or value is // not found, then the default is returned. //***************************************************************************** static long SetLong( // Return value from registry or default. LPCTSTR szName, // Name of value to get. long iValue, // Value to set. LPCTSTR szKey=NULL, // Name of key, NULL==default. HKEY hKey=HKEY_LOCAL_MACHINE);// What key to work on. //***************************************************************************** // Open's the given key and returns the value desired. If the key or value is // not found, then it's created //***************************************************************************** static long SetOrCreateLong( // Return value from registry or default. LPCTSTR szName, // Name of value to get. long iValue, // Value to set. LPCTSTR szKey=NULL, // Name of key, NULL==default. HKEY hKey=HKEY_LOCAL_MACHINE);// What key to work on. //***************************************************************************** // Set an entry in the registry of the form: // HKEY_CLASSES_ROOT\szKey\szSubkey = szValue. If szSubkey or szValue are // NULL, omit them from the above expression. //***************************************************************************** static BOOL SetKeyAndValue( // TRUE or FALSE. LPCTSTR szKey, // Name of the reg key to set. LPCTSTR szSubkey, // Optional subkey of szKey. LPCTSTR szValue); // Optional value for szKey\szSubkey. //***************************************************************************** // Delete an entry in the registry of the form: // HKEY_CLASSES_ROOT\szKey\szSubkey. //***************************************************************************** static LONG DeleteKey( // TRUE or FALSE. LPCTSTR szKey, // Name of the reg key to set. LPCTSTR szSubkey); // Subkey of szKey. //***************************************************************************** // Open the key, create a new keyword and value pair under it. //***************************************************************************** static BOOL SetRegValue( // Return status. LPCTSTR szKeyName, // Name of full key. LPCTSTR szKeyword, // Name of keyword. LPCTSTR szValue); // Value of keyword. //***************************************************************************** // Does standard registration of a CoClass with a progid. //***************************************************************************** static HRESULT RegisterCOMClass( // Return code. REFCLSID rclsid, // Class ID. LPCTSTR szDesc, // Description of the class. LPCTSTR szProgIDPrefix, // Prefix for progid. int iVersion, // Version # for progid. LPCTSTR szClassProgID, // Class progid. LPCTSTR szThreadingModel, // What threading model to use. LPCTSTR szModule, // Path to class. HINSTANCE hInst, // Handle to module being registered LPCTSTR szAssemblyName, // Optional assembly name LPCTSTR szVersion, // Optional Runtime Version (directry containing runtime) BOOL fExternal, // flag - External to mscoree. BOOL fRelativePath); // flag - Relative path in szModule //***************************************************************************** // Unregister the basic information in the system registry for a given object // class. //***************************************************************************** static HRESULT UnregisterCOMClass( // Return code. REFCLSID rclsid, // Class ID we are registering. LPCTSTR szProgIDPrefix, // Prefix for progid. int iVersion, // Version # for progid. LPCTSTR szClassProgID, // Class progid. BOOL fExternal); // flag - External to mscoree. //***************************************************************************** // Does standard registration of a CoClass with a progid. // NOTE: This is the non-side-by-side execution version. //***************************************************************************** static HRESULT RegisterCOMClass( // Return code. REFCLSID rclsid, // Class ID. LPCTSTR szDesc, // Description of the class. LPCTSTR szProgIDPrefix, // Prefix for progid. int iVersion, // Version # for progid. LPCTSTR szClassProgID, // Class progid. LPCTSTR szThreadingModel, // What threading model to use. LPCTSTR szModule, // Path to class. BOOL bInprocServer = true); // Whether we register the server as inproc or local //***************************************************************************** // Unregister the basic information in the system registry for a given object // class. // NOTE: This is the non-side-by-side execution version. //***************************************************************************** static HRESULT UnregisterCOMClass( // Return code. REFCLSID rclsid, // Class ID we are registering. LPCTSTR szProgIDPrefix, // Prefix for progid. int iVersion, // Version # for progid. LPCTSTR szClassProgID); // Class progid. //***************************************************************************** // Register a type library. //***************************************************************************** static HRESULT RegisterTypeLib( // Return code. REFGUID rtlbid, // TypeLib ID we are registering. int iVersion, // Typelib version. LPCTSTR szDesc, // TypeLib description. LPCTSTR szModule); // Path to the typelib. //***************************************************************************** // Remove the registry keys for a type library. //***************************************************************************** static HRESULT UnregisterTypeLib( // Return code. REFGUID rtlbid, // TypeLib ID we are registering. int iVersion); // Typelib version. #endif //#ifndef FEATURE_CORECLR //***************************************************************************** // (Optional) Initialize the config registry cache // (see ConfigCacheValueNameSeenPerhaps, below.) //***************************************************************************** static void InitOptionalConfigCache(); private: #ifndef FEATURE_CORECLR //***************************************************************************** // Register the basics for a in proc server. //***************************************************************************** static HRESULT RegisterClassBase( // Return code. REFCLSID rclsid, // Class ID we are registering. LPCTSTR szDesc, // Class description. LPCTSTR szProgID, // Class prog ID. LPCTSTR szIndepProgID, // Class version independant prog ID. __out_ecount (cchOutCLSID) LPTSTR szOutCLSID, // CLSID formatted in character form. DWORD cchOutCLSID); // Out CLS ID buffer size in characters //***************************************************************************** // Delete the basic settings for an inproc server. //***************************************************************************** static HRESULT UnregisterClassBase( // Return code. REFCLSID rclsid, // Class ID we are registering. LPCTSTR szProgID, // Class prog ID. LPCTSTR szIndepProgID, // Class version independant prog ID. __out_ecount (cchOutCLSID) LPTSTR szOutCLSID, // Return formatted class ID here. DWORD cchOutCLSID); // Out CLS ID buffer size in characters #endif //#ifndef FEATURE_CORECLR //***************************************************************************** // Return TRUE if the registry value name might have been seen in the registry // at startup; // return FALSE if the value was definitely not seen at startup. // // Perf Optimization for VSWhidbey:113373. //***************************************************************************** static BOOL RegCacheValueNameSeenPerhaps( LPCWSTR name); //***************************************************************************** // Return TRUE if the environment variable name might have been seen at startup; // return FALSE if the value was definitely not seen at startup. //***************************************************************************** static BOOL EnvCacheValueNameSeenPerhaps( LPCWSTR name); static BOOL s_fUseRegCache; // Enable registry cache; if FALSE, CCVNSP // always returns TRUE. static BOOL s_fUseEnvCache; // Enable env cache. static BOOL s_fUseRegistry; // Allow lookups in the registry // Open the .NetFramework keys once and cache the handles static HKEY s_hMachineFrameworkKey; static HKEY s_hUserFrameworkKey; }; // need this here because CLRConfig depends on REGUTIL, and ConfigStringHolder depends on CLRConfig #include "clrconfig.h" //----------------------------------------------------------------------------- // Wrapper for configuration strings. // This serves as a holder to call FreeConfigString. class ConfigStringHolder { public: ConfigStringHolder() { m_wszString = NULL; } ~ConfigStringHolder() { Clear(); } // // NOTE: The following function is deprecated; use the CLRConfig class instead. // To access a configuration value through CLRConfig, add an entry in file:../inc/CLRConfigValues.h. // void Init_DontUse_(LPCWSTR wszName) { Clear(); m_wszString = REGUTIL::GetConfigString_DontUse_(wszName); } // Free resources. void Clear() { if (m_wszString != NULL) { REGUTIL::FreeConfigString(m_wszString); m_wszString = NULL; } } // Get the string value. NULL if not set. LPCWSTR Value() { return m_wszString; } private: LPWSTR m_wszString; }; #include "ostype.h" #define CLRGetTickCount64() GetTickCount64() // // Use this function to initialize the s_CodeAllocHint // during startup. base is runtime .dll base address, // size is runtime .dll virtual size. // void InitCodeAllocHint(SIZE_T base, SIZE_T size, int randomPageOffset); // // Use this function to reset the s_CodeAllocHint // after unloading an AppDomain // void ResetCodeAllocHint(); // // Returns TRUE if p is located in near clr.dll that allows us // to use rel32 IP-relative addressing modes. // BOOL IsPreferredExecutableRange(void * p); // // Allocate free memory that will be used for executable code // Handles the special requirements that we have on 64-bit platforms // where we want the executable memory to be located near mscorwks // BYTE * ClrVirtualAllocExecutable(SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); // // Allocate free memory within the range [pMinAddr..pMaxAddr] using // ClrVirtualQuery to find free memory and ClrVirtualAlloc to allocate it. // BYTE * ClrVirtualAllocWithinRange(const BYTE *pMinAddr, const BYTE *pMaxAddr, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); // // Allocate free memory with specific alignment // LPVOID ClrVirtualAllocAligned(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect, SIZE_T alignment); //****************************************************************************** // Returns the number of processors that a process has been configured to run on //****************************************************************************** class NumaNodeInfo { private: static BOOL m_enableGCNumaAware; static BOOL InitNumaNodeInfoAPI(); public: static BOOL CanEnableGCNumaAware(); static void InitNumaNodeInfo(); #if !defined(FEATURE_REDHAWK)&& !defined(FEATURE_PAL) private: // apis types #if !defined(FEATURE_CORESYSTEM) //GetNumaProcessorNode() typedef BOOL (WINAPI *PGNPN)(UCHAR, PUCHAR); #endif //GetNumaHighestNodeNumber() typedef BOOL (WINAPI *PGNHNN)(PULONG); //VirtualAllocExNuma() typedef LPVOID (WINAPI *PVAExN)(HANDLE,LPVOID,SIZE_T,DWORD,DWORD,DWORD); // api pfns and members #if !defined(FEATURE_CORESYSTEM) static PGNPN m_pGetNumaProcessorNode; #endif static PGNHNN m_pGetNumaHighestNodeNumber; static PVAExN m_pVirtualAllocExNuma; public: // functions #if !defined(FEATURE_CORESYSTEM) static BOOL GetNumaProcessorNode(UCHAR proc_no, PUCHAR node_no); #endif static LPVOID VirtualAllocExNuma(HANDLE hProc, LPVOID lpAddr, SIZE_T size, DWORD allocType, DWORD prot, DWORD node); #if !defined(FEATURE_CORECLR) || defined(FEATURE_CORESYSTEM) private: //GetNumaProcessorNodeEx() typedef BOOL (WINAPI *PGNPNEx)(PPROCESSOR_NUMBER, PUSHORT); static PGNPNEx m_pGetNumaProcessorNodeEx; public: static BOOL GetNumaProcessorNodeEx(PPROCESSOR_NUMBER proc_no, PUSHORT node_no); #endif #endif }; struct CPU_Group_Info { WORD nr_active; // at most 64 WORD reserved[1]; WORD begin; WORD end; DWORD_PTR active_mask; DWORD groupWeight; DWORD activeThreadWeight; }; class CPUGroupInfo { private: static LONG m_initialization; static WORD m_nGroups; static WORD m_nProcessors; static BOOL m_enableGCCPUGroups; static BOOL m_threadUseAllCpuGroups; static WORD m_initialGroup; static CPU_Group_Info *m_CPUGroupInfoArray; static BOOL InitCPUGroupInfoAPI(); static BOOL InitCPUGroupInfoArray(); static BOOL InitCPUGroupInfoRange(); static void InitCPUGroupInfo(); static BOOL IsInitialized(); public: static void EnsureInitialized(); static BOOL CanEnableGCCPUGroups(); static BOOL CanEnableThreadUseAllCpuGroups(); static WORD GetNumActiveProcessors(); static void GetGroupForProcessor(WORD processor_number, WORD *group_number, WORD *group_processor_number); static DWORD CalculateCurrentProcessorNumber(); //static void PopulateCPUUsageArray(void * infoBuffer, ULONG infoSize); #if !defined(FEATURE_REDHAWK) && !defined(FEATURE_PAL) private: //GetLogicalProcessorInforomationEx() typedef BOOL (WINAPI *PGLPIEx)(DWORD, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *, PDWORD); //SetThreadGroupAffinity() typedef BOOL (WINAPI *PSTGA)(HANDLE, GROUP_AFFINITY *, GROUP_AFFINITY *); //GetThreadGroupAffinity() typedef BOOL (WINAPI *PGTGA)(HANDLE, GROUP_AFFINITY *); #if !defined(FEATURE_CORESYSTEM) && !defined(FEATURE_CORECLR) //GetCurrentProcessorNumberEx() typedef void (WINAPI *PGCPNEx)(PROCESSOR_NUMBER *); //GetSystemTimes() typedef BOOL (WINAPI *PGST)(FILETIME *, FILETIME *, FILETIME *); //NtQuerySystemInformationEx() //typedef int //(WINAPI *PNTQSIEx)(SYSTEM_INFORMATION_CLASS, PULONG, ULONG, PVOID, ULONG, PULONG); #endif static PGLPIEx m_pGetLogicalProcessorInformationEx; static PSTGA m_pSetThreadGroupAffinity; static PGTGA m_pGetThreadGroupAffinity; #if !defined(FEATURE_CORESYSTEM) && !defined(FEATURE_CORECLR) static PGCPNEx m_pGetCurrentProcessorNumberEx; static PGST m_pGetSystemTimes; //static PNTQSIEx m_pNtQuerySystemInformationEx; #endif public: static BOOL GetLogicalProcessorInformationEx(DWORD relationship, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *slpiex, PDWORD count); static BOOL SetThreadGroupAffinity(HANDLE h, GROUP_AFFINITY *groupAffinity, GROUP_AFFINITY *previousGroupAffinity); static BOOL GetThreadGroupAffinity(HANDLE h, GROUP_AFFINITY *groupAffinity); #if !defined(FEATURE_CORESYSTEM) && !defined(FEATURE_CORECLR) static BOOL GetSystemTimes(FILETIME *idleTime, FILETIME *kernelTime, FILETIME *userTime); static void ChooseCPUGroupAffinity(GROUP_AFFINITY *gf); static void ClearCPUGroupAffinity(GROUP_AFFINITY *gf); #endif #endif }; int GetCurrentProcessCpuCount(); DWORD_PTR GetCurrentProcessCpuMask(); //***************************************************************************** // Return != 0 if the bit at the specified index in the array is on and 0 if // it is off. //***************************************************************************** inline int GetBit(PTR_BYTE pcBits,int iBit) { LIMITED_METHOD_CONTRACT; return (pcBits[iBit>>3] & (1 << (iBit & 0x7))); } #ifdef DACCESS_COMPILE inline int GetBit(BYTE const * pcBits,int iBit) { WRAPPER_NO_CONTRACT; return GetBit(dac_cast<PTR_BYTE>(pcBits), iBit); } #endif //***************************************************************************** // Set the state of the bit at the specified index based on the value of bOn. //***************************************************************************** inline void SetBit(PTR_BYTE pcBits,int iBit,int bOn) { LIMITED_METHOD_CONTRACT; if (bOn) pcBits[iBit>>3] |= (1 << (iBit & 0x7)); else pcBits[iBit>>3] &= ~(1 << (iBit & 0x7)); } #ifdef DACCESS_COMPILE inline void SetBit(BYTE * pcBits,int iBit,int bOn) { WRAPPER_NO_CONTRACT; SetBit(dac_cast<PTR_BYTE>(pcBits), iBit, bOn); } #endif template<typename T> class SimpleListNode { public: SimpleListNode<T>(const T& _t) { data = _t; next = 0; } T data; SimpleListNode<T>* next; }; template<typename T> class SimpleList { public: typedef SimpleListNode<T> NodeType; SimpleList<T>() { head = NULL; } void LinkHead(NodeType* pNode) { pNode->next = head; head = pNode; } NodeType* UnlinkHead() { NodeType* ret = head; if (head) { head = head->next; } return ret; } NodeType* Head() { return head; } protected: NodeType* head; }; template < typename T, typename U > struct Pair { public: typedef Pair< T, U > this_type; typedef T first_type; typedef U second_type; Pair() {} Pair( T const & t, U const & u ) : m_first( t ) , m_second( u ) { SUPPORTS_DAC; } Pair( this_type const & obj ) : m_first( obj.m_first ) , m_second( obj.m_second ) {} this_type & operator=( this_type const & obj ) { m_first = obj.m_first; m_second = obj.m_second; return *this; } T & First() { return m_first; } T const & First() const { return m_first; } U & Second() { return m_second; } U const & Second() const { return m_second; } bool operator==(const Pair& rhs) const { return ((this->First() == rhs.First()) && (this->Second() == rhs.Second())); } bool operator!=(const Pair& rhs) const { return !(*this == rhs); } private: first_type m_first; second_type m_second; }; template < typename T, typename U > Pair< T, U > MakePair( T const & t, U const & u ) { SUPPORTS_DAC; return Pair< T, U >( t, u ); } //***************************************************************************** // This class implements a dynamic array of structures for which the order of // the elements is unimportant. This means that any item placed in the list // may be swapped to any other location in the list at any time. If the order // of the items you place in the array is important, then use the CStructArray // class. //***************************************************************************** template <class T, int iGrowInc, class ALLOCATOR> class CUnorderedArrayWithAllocator { int m_iCount; // # of elements used in the list. int m_iSize; // # of elements allocated in the list. public: #ifndef DACCESS_COMPILE T *m_pTable; // Pointer to the list of elements. #else TADDR m_pTable; // Pointer to the list of elements. #endif public: #ifndef DACCESS_COMPILE CUnorderedArrayWithAllocator() : m_iCount(0), m_iSize(0), m_pTable(NULL) { LIMITED_METHOD_CONTRACT; } ~CUnorderedArrayWithAllocator() { LIMITED_METHOD_CONTRACT; // Free the chunk of memory. if (m_pTable != NULL) ALLOCATOR::Free(this, m_pTable); } void Clear() { WRAPPER_NO_CONTRACT; m_iCount = 0; if (m_iSize > iGrowInc) { T* tmp = ALLOCATOR::AllocNoThrow(this, iGrowInc); if (tmp) { ALLOCATOR::Free(this, m_pTable); m_pTable = tmp; m_iSize = iGrowInc; } } } void Clear(int iFirst, int iCount) { WRAPPER_NO_CONTRACT; int iSize; if (iFirst + iCount < m_iCount) memmove(&m_pTable[iFirst], &m_pTable[iFirst + iCount], sizeof(T) * (m_iCount - (iFirst + iCount))); m_iCount -= iCount; iSize = ((m_iCount / iGrowInc) * iGrowInc) + ((m_iCount % iGrowInc != 0) ? iGrowInc : 0); if (m_iSize > iGrowInc && iSize < m_iSize) { T *tmp = ALLOCATOR::AllocNoThrow(this, iSize); if (tmp) { memcpy (tmp, m_pTable, iSize * sizeof(T)); delete [] m_pTable; m_pTable = tmp; m_iSize = iSize; } } _ASSERTE(m_iCount <= m_iSize); } T *Table() { LIMITED_METHOD_CONTRACT; return (m_pTable); } T *Append() { CONTRACTL { NOTHROW; } CONTRACTL_END; // The array should grow, if we can't fit one more element into the array. if (m_iSize <= m_iCount && GrowNoThrow() == NULL) return (NULL); return (&m_pTable[m_iCount++]); } T *AppendThrowing() { CONTRACTL { THROWS; } CONTRACTL_END; // The array should grow, if we can't fit one more element into the array. if (m_iSize <= m_iCount) Grow(); return (&m_pTable[m_iCount++]); } void Delete(const T &Entry) { LIMITED_METHOD_CONTRACT; --m_iCount; for (int i=0; i <= m_iCount; ++i) if (m_pTable[i] == Entry) { m_pTable[i] = m_pTable[m_iCount]; return; } // Just in case we didn't find it. ++m_iCount; } void DeleteByIndex(int i) { LIMITED_METHOD_CONTRACT; --m_iCount; m_pTable[i] = m_pTable[m_iCount]; } void Swap(int i,int j) { LIMITED_METHOD_CONTRACT; T tmp; if (i == j) return; tmp = m_pTable[i]; m_pTable[i] = m_pTable[j]; m_pTable[j] = tmp; } #else TADDR Table() { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; return (m_pTable); } void EnumMemoryRegions(void) { SUPPORTS_DAC; DacEnumMemoryRegion(m_pTable, m_iCount * sizeof(T)); } #endif // #ifndef DACCESS_COMPILE USHORT Count() { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; _ASSERTE(FitsIn<USHORT>(m_iCount)); return static_cast<USHORT>(m_iCount); } private: T *Grow(); T *GrowNoThrow(); }; #ifndef DACCESS_COMPILE //***************************************************************************** // Increase the size of the array. //***************************************************************************** template <class T, int iGrowInc, class ALLOCATOR> T *CUnorderedArrayWithAllocator<T,iGrowInc,ALLOCATOR>::GrowNoThrow() // NULL if can't grow. { WRAPPER_NO_CONTRACT; T *pTemp; // try to allocate memory for reallocation. if ((pTemp = ALLOCATOR::AllocNoThrow(this, m_iSize+iGrowInc)) == NULL) return (NULL); memcpy (pTemp, m_pTable, m_iSize*sizeof(T)); ALLOCATOR::Free(this, m_pTable); m_pTable = pTemp; m_iSize += iGrowInc; _ASSERTE(m_iSize > 0); return (pTemp); } template <class T, int iGrowInc, class ALLOCATOR> T *CUnorderedArrayWithAllocator<T,iGrowInc,ALLOCATOR>::Grow() // exception if can't grow. { WRAPPER_NO_CONTRACT; T *pTemp; // try to allocate memory for reallocation. pTemp = ALLOCATOR::AllocThrowing(this, m_iSize+iGrowInc); memcpy (pTemp, m_pTable, m_iSize*sizeof(T)); ALLOCATOR::Free(this, m_pTable); m_pTable = pTemp; m_iSize += iGrowInc; _ASSERTE(m_iSize > 0); return (pTemp); } #endif // #ifndef DACCESS_COMPILE template <class T> class CUnorderedArray__Allocator { public: static T *AllocThrowing (void*, int nElements) { return new T[nElements]; } static T *AllocNoThrow (void*, int nElements) { return new (nothrow) T[nElements]; } static void Free (void*, T *pTable) { delete [] pTable; } }; template <class T,int iGrowInc> class CUnorderedArray : public CUnorderedArrayWithAllocator<T, iGrowInc, CUnorderedArray__Allocator<T> > { public: CUnorderedArray () { LIMITED_METHOD_CONTRACT; } }; //Used by the debugger. Included here in hopes somebody else might, too typedef CUnorderedArray<SIZE_T, 17> SIZE_T_UNORDERED_ARRAY; //***************************************************************************** // This class implements a dynamic array of structures for which the insert // order is important. Inserts will slide all elements after the location // down, deletes slide all values over the deleted item. If the order of the // items in the array is unimportant to you, then CUnorderedArray may provide // the same feature set at lower cost. //***************************************************************************** class CStructArray { BYTE *m_pList; // Pointer to the list of elements. int m_iCount; // # of elements used in the list. int m_iSize; // # of elements allocated in the list. int m_iGrowInc; // Growth increment. short m_iElemSize; // Size of an array element. bool m_bFree; // true if data is automatically maintained. public: CStructArray(short iElemSize, short iGrowInc = 1) : m_pList(NULL), m_iCount(0), m_iSize(0), m_iGrowInc(iGrowInc), m_iElemSize(iElemSize), m_bFree(true) { LIMITED_METHOD_CONTRACT; } ~CStructArray() { WRAPPER_NO_CONTRACT; Clear(); } void *Insert(int iIndex); void *InsertThrowing(int iIndex); void *Append(); void *AppendThrowing(); int AllocateBlock(int iCount); void AllocateBlockThrowing(int iCount); void Delete(int iIndex); void *Ptr() { LIMITED_METHOD_CONTRACT; return (m_pList); } void *Get(int iIndex) { WRAPPER_NO_CONTRACT; _ASSERTE(iIndex < m_iCount); return ((void *) ((size_t) Ptr() + (iIndex * m_iElemSize))); } int Size() { LIMITED_METHOD_CONTRACT; return (m_iCount * m_iElemSize); } int Count() { LIMITED_METHOD_CONTRACT; return (m_iCount); } void Clear(); void ClearCount() { LIMITED_METHOD_CONTRACT; m_iCount = 0; } void InitOnMem(short iElemSize, void *pList, int iCount, int iSize, int iGrowInc=1) { LIMITED_METHOD_CONTRACT; m_iElemSize = iElemSize; m_iGrowInc = (short) iGrowInc; m_pList = (BYTE*)pList; m_iCount = iCount; m_iSize = iSize; m_bFree = false; } private: void Grow(int iCount); }; //***************************************************************************** // This template simplifies access to a CStructArray by removing void * and // adding some operator overloads. //***************************************************************************** template <class T> class CDynArray : public CStructArray { public: CDynArray(short iGrowInc=16) : CStructArray(sizeof(T), iGrowInc) { LIMITED_METHOD_CONTRACT; } T *Insert(int iIndex) { WRAPPER_NO_CONTRACT; return ((T *)CStructArray::Insert((int)iIndex)); } T *InsertThrowing(int iIndex) { WRAPPER_NO_CONTRACT; return ((T *)CStructArray::InsertThrowing((int)iIndex)); } T *Append() { WRAPPER_NO_CONTRACT; return ((T *)CStructArray::Append()); } T *AppendThrowing() { WRAPPER_NO_CONTRACT; return ((T *)CStructArray::AppendThrowing()); } T *Ptr() { WRAPPER_NO_CONTRACT; return ((T *)CStructArray::Ptr()); } T *Get(int iIndex) { WRAPPER_NO_CONTRACT; return (Ptr() + iIndex); } T &operator[](int iIndex) { WRAPPER_NO_CONTRACT; return (*(Ptr() + iIndex)); } int ItemIndex(T *p) { WRAPPER_NO_CONTRACT; return (((int)(LONG_PTR)p - (int)(LONG_PTR)Ptr()) / sizeof(T)); } void Move(int iFrom, int iTo) { WRAPPER_NO_CONTRACT; T tmp; _ASSERTE(iFrom >= 0 && iFrom < Count() && iTo >= 0 && iTo < Count()); tmp = *(Ptr() + iFrom); if (iTo > iFrom) memmove(Ptr() + iFrom, Ptr() + iFrom + 1, (iTo - iFrom) * sizeof(T)); else memmove(Ptr() + iTo + 1, Ptr() + iTo, (iFrom - iTo) * sizeof(T)); *(Ptr() + iTo) = tmp; } }; // Some common arrays. typedef CDynArray<int> INTARRAY; typedef CDynArray<short> SHORTARRAY; typedef CDynArray<int> LONGARRAY; typedef CDynArray<USHORT> USHORTARRAY; typedef CDynArray<ULONG> ULONGARRAY; typedef CDynArray<BYTE> BYTEARRAY; typedef CDynArray<mdToken> TOKENARRAY; template <class T> class CStackArray : public CStructArray { public: CStackArray(short iGrowInc=4) : CStructArray(sizeof(T), iGrowInc), m_curPos(0) { LIMITED_METHOD_CONTRACT; } void Push(T p) { WRAPPER_NO_CONTRACT; // We should only inc m_curPos after we grow the array. T *pT = (T *)CStructArray::InsertThrowing(m_curPos); m_curPos ++; *pT = p; } T * Pop() { WRAPPER_NO_CONTRACT; T * retPtr; _ASSERTE(m_curPos > 0); retPtr = (T *)CStructArray::Get(m_curPos-1); CStructArray::Delete(m_curPos--); return (retPtr); } int Count() { LIMITED_METHOD_CONTRACT; return(m_curPos); } private: int m_curPos; }; //***************************************************************************** // This template manages a list of free entries by their 0 based offset. By // making it a template, you can use whatever size free chain will match your // maximum count of items. -1 is reserved. //***************************************************************************** template <class T> class TFreeList { public: void Init( T *rgList, int iCount) { LIMITED_METHOD_CONTRACT; // Save off values. m_rgList = rgList; m_iCount = iCount; m_iNext = 0; // Init free list. int i; for (i=0; i<iCount - 1; i++) m_rgList[i] = i + 1; m_rgList[i] = (T) -1; } T GetFreeEntry() // Index of free item, or -1. { LIMITED_METHOD_CONTRACT; T iNext; if (m_iNext == (T) -1) return (-1); iNext = m_iNext; m_iNext = m_rgList[m_iNext]; return (iNext); } void DelFreeEntry(T iEntry) { LIMITED_METHOD_CONTRACT; _ASSERTE(iEntry < m_iCount); m_rgList[iEntry] = m_iNext; m_iNext = iEntry; } // This function can only be used when it is guaranteed that the free // array is contigous, for example, right after creation to quickly // get a range of items from the heap. void ReserveRange(int iCount) { LIMITED_METHOD_CONTRACT; _ASSERTE(iCount < m_iCount); _ASSERTE(m_iNext == 0); m_iNext = iCount; } private: T *m_rgList; // List of free info. int m_iCount; // How many entries to manage. T m_iNext; // Next item to get. }; //***************************************************************************** //***************************************************************************** template <class T> class CQuickSort { protected: T *m_pBase; // Base of array to sort. private: SSIZE_T m_iCount; // How many items in array. SSIZE_T m_iElemSize; // Size of one element. public: CQuickSort( T *pBase, // Address of first element. SSIZE_T iCount) : // How many there are. m_pBase(pBase), m_iCount(iCount), m_iElemSize(sizeof(T)) { LIMITED_METHOD_DAC_CONTRACT; } //***************************************************************************** // Call to sort the array. //***************************************************************************** inline void Sort() { WRAPPER_NO_CONTRACT; SortRange(0, m_iCount - 1); } protected: //***************************************************************************** // Override this function to do the comparison. //***************************************************************************** virtual FORCEINLINE int Compare( // -1, 0, or 1 T *psFirst, // First item to compare. T *psSecond) // Second item to compare. { LIMITED_METHOD_DAC_CONTRACT; return (memcmp(psFirst, psSecond, sizeof(T))); // return (::Compare(*psFirst, *psSecond)); } virtual FORCEINLINE void Swap( SSIZE_T iFirst, SSIZE_T iSecond) { LIMITED_METHOD_DAC_CONTRACT; if (iFirst == iSecond) return; T sTemp( m_pBase[iFirst] ); m_pBase[iFirst] = m_pBase[iSecond]; m_pBase[iSecond] = sTemp; } private: inline void SortRange( SSIZE_T iLeft, SSIZE_T iRight) { WRAPPER_NO_CONTRACT; SSIZE_T iLast; SSIZE_T i; // loop variable. for (;;) { // if less than two elements you're done. if (iLeft >= iRight) return; // ASSERT that we now have valid indicies. This is statically provable // since this private function is only called with valid indicies, // and iLeft and iRight only converge towards eachother. However, // PreFast can't detect this because it doesn't know about our callers. COMPILER_ASSUME(iLeft >= 0 && iLeft < m_iCount); COMPILER_ASSUME(iRight >= 0 && iRight < m_iCount); // The mid-element is the pivot, move it to the left. Swap(iLeft, (iLeft + iRight) / 2); iLast = iLeft; // move everything that is smaller than the pivot to the left. for (i = iLeft + 1; i <= iRight; i++) { if (Compare(&m_pBase[i], &m_pBase[iLeft]) < 0) { Swap(i, ++iLast); } } // Put the pivot to the point where it is in between smaller and larger elements. Swap(iLeft, iLast); // Sort each partition. SSIZE_T iLeftLast = iLast - 1; SSIZE_T iRightFirst = iLast + 1; if (iLeftLast - iLeft < iRight - iRightFirst) { // Left partition is smaller, sort it recursively SortRange(iLeft, iLeftLast); // Tail call to sort the right (bigger) partition iLeft = iRightFirst; //iRight = iRight; continue; } else { // Right partition is smaller, sort it recursively SortRange(iRightFirst, iRight); // Tail call to sort the left (bigger) partition //iLeft = iLeft; iRight = iLeftLast; continue; } } } }; //***************************************************************************** // Faster and simpler version of the binary search below. //***************************************************************************** template <class T> const T * BinarySearch(const T * pBase, int iCount, const T & find) { WRAPPER_NO_CONTRACT; int iFirst = 0; int iLast = iCount - 1; // It is faster to use linear search once we get down to a small number of elements. while (iLast - iFirst > 10) { int iMid = (iLast + iFirst) / 2; if (find < pBase[iMid]) iLast = iMid - 1; else iFirst = iMid; } for (int i = iFirst; i <= iLast; i++) { if (find == pBase[i]) return &pBase[i]; if (find < pBase[i]) break; } return NULL; } //***************************************************************************** // This template encapsulates a binary search algorithm on the given type // of data. //***************************************************************************** template <class T> class CBinarySearch { private: const T *m_pBase; // Base of array to sort. int m_iCount; // How many items in array. public: CBinarySearch( const T *pBase, // Address of first element. int iCount) : // Value to find. m_pBase(pBase), m_iCount(iCount) { LIMITED_METHOD_CONTRACT; } //***************************************************************************** // Searches for the item passed to ctor. //***************************************************************************** const T *Find( // Pointer to found item in array. const T *psFind, // The key to find. int *piInsert = NULL) // Index to insert at. { WRAPPER_NO_CONTRACT; int iMid, iFirst, iLast; // Loop control. int iCmp; // Comparison. iFirst = 0; iLast = m_iCount - 1; while (iFirst <= iLast) { iMid = (iLast + iFirst) / 2; iCmp = Compare(psFind, &m_pBase[iMid]); if (iCmp == 0) { if (piInsert != NULL) *piInsert = iMid; return (&m_pBase[iMid]); } else if (iCmp < 0) iLast = iMid - 1; else iFirst = iMid + 1; } if (piInsert != NULL) *piInsert = iFirst; return (NULL); } //***************************************************************************** // Override this function to do the comparison if a comparison operator is // not valid for your data type (such as a struct). //***************************************************************************** virtual int Compare( // -1, 0, or 1 const T *psFirst, // Key you are looking for. const T *psSecond) // Item to compare to. { LIMITED_METHOD_CONTRACT; return (memcmp(psFirst, psSecond, sizeof(T))); // return (::Compare(*psFirst, *psSecond)); } }; //***************************************************************************** // The information that the hash table implementation stores at the beginning // of every record that can be but in the hash table. //***************************************************************************** typedef DPTR(struct HASHENTRY) PTR_HASHENTRY; struct HASHENTRY { ULONG iPrev; // Previous bucket in the chain. ULONG iNext; // Next bucket in the chain. }; typedef DPTR(struct FREEHASHENTRY) PTR_FREEHASHENTRY; struct FREEHASHENTRY : HASHENTRY { ULONG iFree; }; //***************************************************************************** // Used by the FindFirst/FindNextEntry functions. These api's allow you to // do a sequential scan of all entries. //***************************************************************************** struct HASHFIND { ULONG iBucket; // The next bucket to look in. ULONG iNext; }; //***************************************************************************** // IMPORTANT: This data structure is deprecated, please do not add any new uses. // The hashtable implementation that should be used instead is code:SHash. // If code:SHash does not work for you, talk to mailto:clrdeag. //***************************************************************************** // This is a class that implements a chain and bucket hash table. // // The data is actually supplied as an array of structures by the user of this class. // This allows the buckets to use small indices to point to the chain, instead of pointers. // // Each entry in the array contains a HASHENTRY structure immediately // followed by the key used to hash the structure. // // The HASHENTRY part of every structure is used to implement the chain of // entries in a single bucket. // // This implementation does not support rehashing the buckets if the table grows // to big. // @TODO: Fix this by adding an abstract function Hash() which must be implemented // by all clients. // //***************************************************************************** class CHashTable { friend class DebuggerRCThread; //RCthread actually needs access to //fields of derrived class DebuggerPatchTable protected: TADDR m_pcEntries; // Pointer to the array of structs. ULONG m_iEntrySize; // Size of the structs. ULONG m_iBuckets; // # of chains we are hashing into. PTR_ULONG m_piBuckets; // Ptr to the array of bucket chains. INDEBUG(unsigned m_maxSearch;) // For evaluating perf characteristics HASHENTRY *EntryPtr(ULONG iEntry) { LIMITED_METHOD_DAC_CONTRACT; return (PTR_HASHENTRY(m_pcEntries + (iEntry * m_iEntrySize))); } ULONG ItemIndex(HASHENTRY *p) { SUPPORTS_DAC; LIMITED_METHOD_CONTRACT; return (ULONG)((dac_cast<TADDR>(p) - m_pcEntries) / m_iEntrySize); } public: CHashTable( ULONG iBuckets) : // # of chains we are hashing into. m_pcEntries((TADDR)NULL), m_iBuckets(iBuckets) { LIMITED_METHOD_CONTRACT; m_piBuckets = NULL; INDEBUG(m_maxSearch = 0;) } CHashTable() : // # of chains we are hashing into. m_pcEntries((TADDR)NULL), m_iBuckets(5) { LIMITED_METHOD_CONTRACT; m_piBuckets = NULL; INDEBUG(m_maxSearch = 0;) } #ifndef DACCESS_COMPILE ~CHashTable() { LIMITED_METHOD_CONTRACT; if (m_piBuckets != NULL) { delete [] m_piBuckets; m_piBuckets = NULL; } } //***************************************************************************** // This is the second part of construction where we do all of the work that // can fail. We also take the array of structs here because the calling class // presumably needs to allocate it in its NewInit. //***************************************************************************** HRESULT NewInit( // Return status. BYTE *pcEntries, // Array of structs we are managing. ULONG iEntrySize); // Size of the entries. //***************************************************************************** // This can be called to change the pointer to the table that the hash table // is managing. You might call this if (for example) you realloc the size // of the table and its pointer is different. //***************************************************************************** void SetTable( BYTE *pcEntries) // Array of structs we are managing. { LIMITED_METHOD_CONTRACT; m_pcEntries = (TADDR)pcEntries; } //***************************************************************************** // Clear the hash table as if there were nothing in it. //***************************************************************************** void Clear() { LIMITED_METHOD_CONTRACT; _ASSERTE(m_piBuckets != NULL); memset(m_piBuckets, 0xff, m_iBuckets * sizeof(ULONG)); } //***************************************************************************** // Add the struct at the specified index in m_pcEntries to the hash chains. //***************************************************************************** BYTE *Add( // New entry. ULONG iHash, // Hash value of entry to add. ULONG iIndex); // Index of struct in m_pcEntries. //***************************************************************************** // Delete the struct at the specified index in m_pcEntries from the hash chains. //***************************************************************************** void Delete( ULONG iHash, // Hash value of entry to delete. ULONG iIndex); // Index of struct in m_pcEntries. void Delete( ULONG iHash, // Hash value of entry to delete. HASHENTRY *psEntry); // The struct to delete. //***************************************************************************** // The item at the specified index has been moved, update the previous and // next item. //***************************************************************************** void Move( ULONG iHash, // Hash value for the item. ULONG iNew); // New location. #endif // #ifndef DACCESS_COMPILE //***************************************************************************** // Return a boolean indicating whether or not this hash table has been inited. //***************************************************************************** int IsInited() { LIMITED_METHOD_CONTRACT; return (m_piBuckets != NULL); } //***************************************************************************** // Search the hash table for an entry with the specified key value. //***************************************************************************** BYTE *Find( // Index of struct in m_pcEntries. ULONG iHash, // Hash value of the item. SIZE_T key); // The key to match. //***************************************************************************** // Search the hash table for the next entry with the specified key value. //***************************************************************************** ULONG FindNext( // Index of struct in m_pcEntries. SIZE_T key, // The key to match. ULONG iIndex); // Index of previous match. //***************************************************************************** // Returns the first entry in the first hash bucket and inits the search // struct. Use the FindNextEntry function to continue walking the list. The // return order is not gauranteed. //***************************************************************************** BYTE *FindFirstEntry( // First entry found, or 0. HASHFIND *psSrch) // Search object. { WRAPPER_NO_CONTRACT; if (m_piBuckets == 0) return (0); psSrch->iBucket = 1; psSrch->iNext = m_piBuckets[0]; return (FindNextEntry(psSrch)); } //***************************************************************************** // Returns the next entry in the list. //***************************************************************************** BYTE *FindNextEntry( // The next entry, or0 for end of list. HASHFIND *psSrch); // Search object. #ifdef DACCESS_COMPILE void EnumMemoryRegions(CLRDataEnumMemoryFlags flags, ULONG numEntries); #endif protected: virtual BOOL Cmp(SIZE_T key1, const HASHENTRY * pc2) = 0; }; class CNewData { public: static BYTE *Alloc(int iSize, int iMaxSize) { WRAPPER_NO_CONTRACT; return (new BYTE[iSize]); } static void Free(BYTE *pPtr, int iSize) { LIMITED_METHOD_CONTRACT; delete [] pPtr; } static BYTE *Grow(BYTE *&pPtr, int iCurSize) { WRAPPER_NO_CONTRACT; BYTE *p; S_SIZE_T newSize = S_SIZE_T(iCurSize) + S_SIZE_T(GrowSize(iCurSize)); //check for overflow if(newSize.IsOverflow()) p = NULL; else p = new (nothrow) BYTE[newSize.Value()]; if (p == 0) return (0); memcpy (p, pPtr, iCurSize); delete [] pPtr; pPtr = p; return pPtr; } static void Clean(BYTE * pData, int iSize) { } static int RoundSize(int iSize) { LIMITED_METHOD_CONTRACT; return (iSize); } static int GrowSize(int iCurSize) { LIMITED_METHOD_CONTRACT; int newSize = (3 * iCurSize) / 2; return (newSize < 256) ? 256 : newSize; } }; class CNewDataNoThrow { public: static BYTE *Alloc(int iSize, int iMaxSize) { WRAPPER_NO_CONTRACT; return (new (nothrow) BYTE[iSize]); } static void Free(BYTE *pPtr, int iSize) { LIMITED_METHOD_CONTRACT; delete [] pPtr; } static BYTE *Grow(BYTE *&pPtr, int iCurSize) { WRAPPER_NO_CONTRACT; BYTE *p; S_SIZE_T newSize = S_SIZE_T(iCurSize) + S_SIZE_T(GrowSize(iCurSize)); //check for overflow if(newSize.IsOverflow()) p = NULL; else p = new (nothrow) BYTE[newSize.Value()]; if (p == 0) return (0); memcpy (p, pPtr, iCurSize); delete [] pPtr; pPtr = p; return pPtr; } static void Clean(BYTE * pData, int iSize) { } static int RoundSize(int iSize) { LIMITED_METHOD_CONTRACT; return (iSize); } static int GrowSize(int iCurSize) { LIMITED_METHOD_CONTRACT; int newSize = (3 * iCurSize) / 2; return (newSize < 256) ? 256 : newSize; } }; //***************************************************************************** // IMPORTANT: This data structure is deprecated, please do not add any new uses. // The hashtable implementation that should be used instead is code:SHash. // If code:SHash does not work for you, talk to mailto:clrdeag. //***************************************************************************** // CHashTable expects the data to be in a single array - this is provided by // CHashTableAndData. // The array is allocated using the MemMgr type. CNewData and // CNewDataNoThrow can be used for this. //***************************************************************************** template <class MemMgr> class CHashTableAndData : public CHashTable { public: ULONG m_iFree; // Index into m_pcEntries[] of next available slot ULONG m_iEntries; // size of m_pcEntries[] public: CHashTableAndData() : CHashTable() { LIMITED_METHOD_CONTRACT; } CHashTableAndData( ULONG iBuckets) : // # of chains we are hashing into. CHashTable(iBuckets) { LIMITED_METHOD_CONTRACT; } #ifndef DACCESS_COMPILE ~CHashTableAndData() { WRAPPER_NO_CONTRACT; if (m_pcEntries != NULL) MemMgr::Free((BYTE*)m_pcEntries, MemMgr::RoundSize(m_iEntries * m_iEntrySize)); } //***************************************************************************** // This is the second part of construction where we do all of the work that // can fail. We also take the array of structs here because the calling class // presumably needs to allocate it in its NewInit. //***************************************************************************** HRESULT NewInit( // Return status. ULONG iEntries, // # of entries. ULONG iEntrySize, // Size of the entries. int iMaxSize); // Max size of data. //***************************************************************************** // Clear the hash table as if there were nothing in it. //***************************************************************************** void Clear() { WRAPPER_NO_CONTRACT; m_iFree = 0; InitFreeChain(0, m_iEntries); CHashTable::Clear(); } //***************************************************************************** // Grabs a slot for the new entry to be added. // The caller should fill in the non-HASHENTRY part of the returned slot //***************************************************************************** BYTE *Add( ULONG iHash) // Hash value of entry to add. { WRAPPER_NO_CONTRACT; FREEHASHENTRY *psEntry; // Make the table bigger if necessary. if (m_iFree == UINT32_MAX && !Grow()) return (NULL); // Add the first entry from the free list to the hash chain. psEntry = (FREEHASHENTRY *) CHashTable::Add(iHash, m_iFree); m_iFree = psEntry->iFree; // If we're recycling memory, give our memory-allocator a chance to re-init it. // Each entry is prefixed with a header - we don't want to trash that. SIZE_T cbHeader = sizeof(FREEHASHENTRY); MemMgr::Clean((BYTE*) psEntry + cbHeader, (int) (m_iEntrySize - cbHeader)); return ((BYTE *) psEntry); } //***************************************************************************** // Delete the struct at the specified index in m_pcEntries from the hash chains. //***************************************************************************** void Delete( ULONG iHash, // Hash value of entry to delete. ULONG iIndex) // Index of struct in m_pcEntries. { WRAPPER_NO_CONTRACT; CHashTable::Delete(iHash, iIndex); ((FREEHASHENTRY *) EntryPtr(iIndex))->iFree = m_iFree; m_iFree = iIndex; } void Delete( ULONG iHash, // Hash value of entry to delete. HASHENTRY *psEntry) // The struct to delete. { WRAPPER_NO_CONTRACT; CHashTable::Delete(iHash, psEntry); ((FREEHASHENTRY *) psEntry)->iFree = m_iFree; m_iFree = ItemIndex(psEntry); } #endif // #ifndef DACCESS_COMPILE // This is a sad legacy workaround. The debugger's patch table (implemented as this // class) is shared across process. We publish the runtime offsets of // some key fields. Since those fields are private, we have to provide // accessors here. So if you're not using these functions, don't start. // We can hopefully remove them. // Note that we can't just make RCThread a friend of this class (we tried // originally) because the inheritence chain has a private modifier, // so DebuggerPatchTable::m_pcEntries is illegal. static SIZE_T helper_GetOffsetOfEntries() { LIMITED_METHOD_CONTRACT; return offsetof(CHashTableAndData, m_pcEntries); } static SIZE_T helper_GetOffsetOfCount() { LIMITED_METHOD_CONTRACT; return offsetof(CHashTableAndData, m_iEntries); } #ifdef DACCESS_COMPILE void EnumMemoryRegions(CLRDataEnumMemoryFlags flags) { SUPPORTS_DAC; CHashTable::EnumMemoryRegions(flags, m_iEntries); } #endif private: void InitFreeChain(ULONG iStart,ULONG iEnd); int Grow(); }; #ifndef DACCESS_COMPILE //***************************************************************************** // This is the second part of construction where we do all of the work that // can fail. We also take the array of structs here because the calling class // presumably needs to allocate it in its NewInit. //***************************************************************************** template<class MemMgr> HRESULT CHashTableAndData<MemMgr>::NewInit(// Return status. ULONG iEntries, // # of entries. ULONG iEntrySize, // Size of the entries. int iMaxSize) // Max size of data. { WRAPPER_NO_CONTRACT; BYTE *pcEntries; HRESULT hr; // note that this function can throw because it depends on the <M>::Alloc // Allocate the memory for the entries. if ((pcEntries = MemMgr::Alloc(MemMgr::RoundSize(iEntries * iEntrySize), MemMgr::RoundSize(iMaxSize))) == 0) return (E_OUTOFMEMORY); m_iEntries = iEntries; // Init the base table. if (FAILED(hr = CHashTable::NewInit(pcEntries, iEntrySize))) MemMgr::Free(pcEntries, MemMgr::RoundSize(iEntries * iEntrySize)); else { // Init the free chain. m_iFree = 0; InitFreeChain(0, iEntries); } return (hr); } //***************************************************************************** // Initialize a range of records such that they are linked together to be put // on the free chain. //***************************************************************************** template<class MemMgr> void CHashTableAndData<MemMgr>::InitFreeChain( ULONG iStart, // Index to start initializing. ULONG iEnd) // Index to stop initializing { LIMITED_METHOD_CONTRACT; BYTE* pcPtr; _ASSERTE(iEnd > iStart); pcPtr = (BYTE*)m_pcEntries + iStart * m_iEntrySize; for (++iStart; iStart < iEnd; ++iStart) { ((FREEHASHENTRY *) pcPtr)->iFree = iStart; pcPtr += m_iEntrySize; } ((FREEHASHENTRY *) pcPtr)->iFree = UINT32_MAX; } //***************************************************************************** // Attempt to increase the amount of space available for the record heap. //***************************************************************************** template<class MemMgr> int CHashTableAndData<MemMgr>::Grow() // 1 if successful, 0 if not. { WRAPPER_NO_CONTRACT; int iCurSize; // Current size in bytes. int iEntries; // New # of entries. _ASSERTE(m_pcEntries != NULL); _ASSERTE(m_iFree == UINT32_MAX); // Compute the current size and new # of entries. S_UINT32 iTotEntrySize = S_UINT32(m_iEntries) * S_UINT32(m_iEntrySize); if( iTotEntrySize.IsOverflow() ) { _ASSERTE( !"CHashTableAndData overflow!" ); return (0); } iCurSize = MemMgr::RoundSize( iTotEntrySize.Value() ); iEntries = (iCurSize + MemMgr::GrowSize(iCurSize)) / m_iEntrySize; if ( (iEntries < 0) || ((ULONG)iEntries <= m_iEntries) ) { _ASSERTE( !"CHashTableAndData overflow!" ); return (0); } // Try to expand the array. if (MemMgr::Grow(*(BYTE**)&m_pcEntries, iCurSize) == 0) return (0); // Init the newly allocated space. InitFreeChain(m_iEntries, iEntries); m_iFree = m_iEntries; m_iEntries = iEntries; return (1); } #endif // #ifndef DACCESS_COMPILE //***************************************************************************** //***************************************************************************** inline COUNT_T HashCOUNT_T(COUNT_T currentHash, COUNT_T data) { LIMITED_METHOD_DAC_CONTRACT; return ((currentHash << 5) + currentHash) ^ data; } inline COUNT_T HashPtr(COUNT_T currentHash, PTR_VOID ptr) { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; return HashCOUNT_T(currentHash, COUNT_T(SIZE_T(dac_cast<TADDR>(ptr)))); } inline DWORD HashThreeToOne(DWORD a, DWORD b, DWORD c) { LIMITED_METHOD_DAC_CONTRACT; // Current implementation taken from lookup3.c, by Bob Jenkins, May 2006 #define rot32(x,k) (((x)<<(k)) | ((x)>>(32-(k)))) c ^= b; c -= rot32(b,14); a ^= c; a -= rot32(c,11); b ^= a; b -= rot32(a,25); c ^= b; c -= rot32(b,16); a ^= c; a -= rot32(c,4); b ^= a; b -= rot32(a,14); c ^= b; c -= rot32(b,24); return c; } inline ULONG HashBytes(BYTE const *pbData, size_t iSize) { LIMITED_METHOD_CONTRACT; ULONG hash = 5381; BYTE const *pbDataEnd = pbData + iSize; for (/**/ ; pbData < pbDataEnd; pbData++) { hash = ((hash << 5) + hash) ^ *pbData; } return hash; } // Helper function for hashing a string char by char. inline ULONG HashStringA(LPCSTR szStr) { LIMITED_METHOD_CONTRACT; ULONG hash = 5381; int c; while ((c = *szStr) != 0) { hash = ((hash << 5) + hash) ^ c; ++szStr; } return hash; } inline ULONG HashString(LPCWSTR szStr) { LIMITED_METHOD_CONTRACT; ULONG hash = 5381; int c; while ((c = *szStr) != 0) { hash = ((hash << 5) + hash) ^ c; ++szStr; } return hash; } inline ULONG HashStringN(LPCWSTR szStr, SIZE_T cchStr) { LIMITED_METHOD_CONTRACT; ULONG hash = 5381; // hash the string two characters at a time ULONG *ptr = (ULONG *)szStr; // we assume that szStr is null-terminated _ASSERTE(cchStr <= wcslen(szStr)); SIZE_T cDwordCount = (cchStr + 1) / 2; for (SIZE_T i = 0; i < cDwordCount; i++) { hash = ((hash << 5) + hash) ^ ptr[i]; } return hash; } // Case-insensitive string hash function. inline ULONG HashiStringA(LPCSTR szStr) { LIMITED_METHOD_CONTRACT; ULONG hash = 5381; while (*szStr != 0) { hash = ((hash << 5) + hash) ^ toupper(*szStr); szStr++; } return hash; } // Case-insensitive string hash function. inline ULONG HashiString(LPCWSTR szStr) { LIMITED_METHOD_CONTRACT; ULONG hash = 5381; while (*szStr != 0) { hash = ((hash << 5) + hash) ^ towupper(*szStr); szStr++; } return hash; } // Case-insensitive string hash function. inline ULONG HashiStringN(LPCWSTR szStr, DWORD count) { LIMITED_METHOD_CONTRACT; ULONG hash = 5381; while (*szStr != 0 && count--) { hash = ((hash << 5) + hash) ^ towupper(*szStr); szStr++; } return hash; } // Case-insensitive string hash function when all of the // characters in the string are known to be below 0x80. // Knowing this is much more efficient than calling // towupper above. inline ULONG HashiStringKnownLower80(LPCWSTR szStr) { LIMITED_METHOD_CONTRACT; ULONG hash = 5381; int c; int mask = ~0x20; while ((c = *szStr)!=0) { //If we have a lowercase character, ANDing off 0x20 //(mask) will make it an uppercase character. if (c>='a' && c<='z') { c&=mask; } hash = ((hash << 5) + hash) ^ c; ++szStr; } return hash; } inline ULONG HashiStringNKnownLower80(LPCWSTR szStr, DWORD count) { LIMITED_METHOD_CONTRACT; ULONG hash = 5381; int c; int mask = ~0x20; while ((c = *szStr) !=0 && count--) { //If we have a lowercase character, ANDing off 0x20 //(mask) will make it an uppercase character. if (c>='a' && c<='z') { c&=mask; } hash = ((hash << 5) + hash) ^ c; ++szStr; } return hash; } // // // // // // See $\src\utilcode\Debug.cpp for "Binomial (K, M, N)", which // // // computes the binomial distribution, with which to compare your // // // hash-table statistics. // // // //***************************************************************************** // IMPORTANT: This data structure is deprecated, please do not add any new uses. // The hashtable implementation that should be used instead is code:SHash. // If code:SHash does not work for you, talk to mailto:clrdeag. //***************************************************************************** // This class implements a closed hashing table. Values are hashed to a bucket, // and if that bucket is full already, then the value is placed in the next // free bucket starting after the desired target (with wrap around). If the // table becomes 75% full, it is grown and rehashed to reduce lookups. This // class is best used in a reltively small lookup table where hashing is // not going to cause many collisions. By not having the collision chain // logic, a lot of memory is saved. // // The user of the template is required to supply several methods which decide // how each element can be marked as free, deleted, or used. It would have // been possible to write this with more internal logic, but that would require // either (a) more overhead to add status on top of elements, or (b) hard // coded types like one for strings, one for ints, etc... This gives you the // flexibility of adding logic to your type. //***************************************************************************** class CClosedHashBase { BYTE *EntryPtr(int iEntry) { LIMITED_METHOD_CONTRACT; return (m_rgData + (iEntry * m_iEntrySize)); } BYTE *EntryPtr(int iEntry, BYTE *rgData) { LIMITED_METHOD_CONTRACT; return (rgData + (iEntry * m_iEntrySize)); } public: enum ELEMENTSTATUS { FREE, // Item is not in use right now. DELETED, // Item is deleted. USED // Item is in use. }; CClosedHashBase( int iBuckets, // How many buckets should we start with. int iEntrySize, // Size of an entry. bool bPerfect) : // true if bucket size will hash with no collisions. m_bPerfect(bPerfect), m_iBuckets(iBuckets), m_iEntrySize(iEntrySize), m_iCount(0), m_iCollisions(0), m_rgData(0) { LIMITED_METHOD_CONTRACT; m_iSize = iBuckets + 7; } ~CClosedHashBase() { WRAPPER_NO_CONTRACT; Clear(); } virtual void Clear() { LIMITED_METHOD_CONTRACT; delete [] m_rgData; m_iCount = 0; m_iCollisions = 0; m_rgData = 0; } //***************************************************************************** // Accessors for getting at the underlying data. Be careful to use Count() // only when you want the number of buckets actually used. //***************************************************************************** int Count() { LIMITED_METHOD_CONTRACT; return (m_iCount); } int Collisions() { LIMITED_METHOD_CONTRACT; return (m_iCollisions); } int Buckets() { LIMITED_METHOD_CONTRACT; return (m_iBuckets); } void SetBuckets(int iBuckets, bool bPerfect=false) { LIMITED_METHOD_CONTRACT; _ASSERTE(m_rgData == 0); m_iBuckets = iBuckets; m_iSize = m_iBuckets + 7; m_bPerfect = bPerfect; } BYTE *Data() { LIMITED_METHOD_CONTRACT; return (m_rgData); } //***************************************************************************** // Add a new item to hash table given the key value. If this new entry // exceeds maximum size, then the table will grow and be re-hashed, which // may cause a memory error. //***************************************************************************** BYTE *Add( // New item to fill out on success. void *pData) // The value to hash on. { WRAPPER_NO_CONTRACT; // If we haven't allocated any memory, or it is too small, fix it. if (!m_rgData || ((m_iCount + 1) > (m_iSize * 3 / 4) && !m_bPerfect)) { if (!ReHash()) return (0); } return (DoAdd(pData, m_rgData, m_iBuckets, m_iSize, m_iCollisions, m_iCount)); } //***************************************************************************** // Delete the given value. This will simply mark the entry as deleted (in // order to keep the collision chain intact). There is an optimization that // consecutive deleted entries leading up to a free entry are themselves freed // to reduce collisions later on. //***************************************************************************** void Delete( void *pData); // Key value to delete. //***************************************************************************** // Callback function passed to DeleteLoop. //***************************************************************************** typedef BOOL (* DELETELOOPFUNC)( // Delete current item? BYTE *pEntry, // Bucket entry to evaluate void *pCustomizer); // User-defined value //***************************************************************************** // Iterates over all active values, passing each one to pDeleteLoopFunc. // If pDeleteLoopFunc returns TRUE, the entry is deleted. This is safer // and faster than using FindNext() and Delete(). //***************************************************************************** void DeleteLoop( DELETELOOPFUNC pDeleteLoopFunc, // Decides whether to delete item void *pCustomizer); // Extra value passed to deletefunc. //***************************************************************************** // Lookup a key value and return a pointer to the element if found. //***************************************************************************** BYTE *Find( // The item if found, 0 if not. void *pData); // The key to lookup. //***************************************************************************** // Look for an item in the table. If it isn't found, then create a new one and // return that. //***************************************************************************** BYTE *FindOrAdd( // The item if found, 0 if not. void *pData, // The key to lookup. bool &bNew); // true if created. //***************************************************************************** // The following functions are used to traverse each used entry. This code // will skip over deleted and free entries freeing the caller up from such // logic. //***************************************************************************** BYTE *GetFirst() // The first entry, 0 if none. { WRAPPER_NO_CONTRACT; int i; // Loop control. // If we've never allocated the table there can't be any to get. if (m_rgData == 0) return (0); // Find the first one. for (i=0; i<m_iSize; i++) { if (Status(EntryPtr(i)) != FREE && Status(EntryPtr(i)) != DELETED) return (EntryPtr(i)); } return (0); } BYTE *GetNext(BYTE *Prev) // The next entry, 0 if done. { WRAPPER_NO_CONTRACT; int i; // Loop control. for (i = (int)(((size_t) Prev - (size_t) &m_rgData[0]) / m_iEntrySize) + 1; i<m_iSize; i++) { if (Status(EntryPtr(i)) != FREE && Status(EntryPtr(i)) != DELETED) return (EntryPtr(i)); } return (0); } private: //***************************************************************************** // Hash is called with a pointer to an element in the table. You must override // this method and provide a hash algorithm for your element type. //***************************************************************************** virtual unsigned int Hash( // The key value. void const *pData)=0; // Raw data to hash. //***************************************************************************** // Compare is used in the typical memcmp way, 0 is eqaulity, -1/1 indicate // direction of miscompare. In this system everything is always equal or not. //***************************************************************************** virtual unsigned int Compare( // 0, -1, or 1. void const *pData, // Raw key data on lookup. BYTE *pElement)=0; // The element to compare data against. //***************************************************************************** // Return true if the element is free to be used. //***************************************************************************** virtual ELEMENTSTATUS Status( // The status of the entry. BYTE *pElement)=0; // The element to check. //***************************************************************************** // Sets the status of the given element. //***************************************************************************** virtual void SetStatus( BYTE *pElement, // The element to set status for. ELEMENTSTATUS eStatus)=0; // New status. //***************************************************************************** // Returns the internal key value for an element. //***************************************************************************** virtual void *GetKey( // The data to hash on. BYTE *pElement)=0; // The element to return data ptr for. //***************************************************************************** // This helper actually does the add for you. //***************************************************************************** BYTE *DoAdd(void *pData, BYTE *rgData, int &iBuckets, int iSize, int &iCollisions, int &iCount); //***************************************************************************** // This function is called either to init the table in the first place, or // to rehash the table if we ran out of room. //***************************************************************************** bool ReHash(); // true if successful. //***************************************************************************** // Walk each item in the table and mark it free. //***************************************************************************** void InitFree(BYTE *ptr, int iSize) { WRAPPER_NO_CONTRACT; int i; for (i=0; i<iSize; i++, ptr += m_iEntrySize) SetStatus(ptr, FREE); } private: bool m_bPerfect; // true if the table size guarantees // no collisions. int m_iBuckets; // How many buckets do we have. int m_iEntrySize; // Size of an entry. int m_iSize; // How many elements can we have. int m_iCount; // How many items cannot be used (NON free, i.e. USED+DELETED). int m_iCollisions; // How many have we had. BYTE *m_rgData; // Data element list. }; //***************************************************************************** // IMPORTANT: This data structure is deprecated, please do not add any new uses. // The hashtable implementation that should be used instead is code:SHash. // If code:SHash does not work for you, talk to mailto:clrdeag. //***************************************************************************** template <class T> class CClosedHash : public CClosedHashBase { public: CClosedHash( int iBuckets, // How many buckets should we start with. bool bPerfect=false) : // true if bucket size will hash with no collisions. CClosedHashBase(iBuckets, sizeof(T), bPerfect) { WRAPPER_NO_CONTRACT; } T &operator[](int iIndex) { WRAPPER_NO_CONTRACT; return ((T &) *(Data() + (iIndex * sizeof(T)))); } //***************************************************************************** // Add a new item to hash table given the key value. If this new entry // exceeds maximum size, then the table will grow and be re-hashed, which // may cause a memory error. //***************************************************************************** T *Add( // New item to fill out on success. void *pData) // The value to hash on. { WRAPPER_NO_CONTRACT; return ((T *) CClosedHashBase::Add(pData)); } //***************************************************************************** // Lookup a key value and return a pointer to the element if found. //***************************************************************************** T *Find( // The item if found, 0 if not. void *pData) // The key to lookup. { WRAPPER_NO_CONTRACT; return ((T *) CClosedHashBase::Find(pData)); } //***************************************************************************** // Look for an item in the table. If it isn't found, then create a new one and // return that. //***************************************************************************** T *FindOrAdd( // The item if found, 0 if not. void *pData, // The key to lookup. bool &bNew) // true if created. { WRAPPER_NO_CONTRACT; return ((T *) CClosedHashBase::FindOrAdd(pData, bNew)); } //***************************************************************************** // The following functions are used to traverse each used entry. This code // will skip over deleted and free entries freeing the caller up from such // logic. //***************************************************************************** T *GetFirst() // The first entry, 0 if none. { WRAPPER_NO_CONTRACT; return ((T *) CClosedHashBase::GetFirst()); } T *GetNext(T *Prev) // The next entry, 0 if done. { WRAPPER_NO_CONTRACT; return ((T *) CClosedHashBase::GetNext((BYTE *) Prev)); } }; //***************************************************************************** // IMPORTANT: This data structure is deprecated, please do not add any new uses. // The hashtable implementation that should be used instead is code:SHash. // If code:SHash does not work for you, talk to mailto:clrdeag. //***************************************************************************** // Closed hash with typed parameters. The derived class is the second // parameter to the template. The derived class must implement: // unsigned long Hash(const T *pData); // unsigned long Compare(const T *p1, T *p2); // ELEMENTSTATUS Status(T *pEntry); // void SetStatus(T *pEntry, ELEMENTSTATUS s); // void* GetKey(T *pEntry); //***************************************************************************** template<class T, class H>class CClosedHashEx : public CClosedHash<T> { public: CClosedHashEx( int iBuckets, // How many buckets should we start with. bool bPerfect=false) : // true if bucket size will hash with no collisions. CClosedHash<T> (iBuckets, bPerfect) { WRAPPER_NO_CONTRACT; } unsigned int Hash(const void *pData) { WRAPPER_NO_CONTRACT; return static_cast<H*>(this)->Hash((const T*)pData); } unsigned int Compare(const void *p1, BYTE *p2) { WRAPPER_NO_CONTRACT; return static_cast<H*>(this)->Compare((const T*)p1, (T*)p2); } typename CClosedHash<T>::ELEMENTSTATUS Status(BYTE *p) { WRAPPER_NO_CONTRACT; return static_cast<H*>(this)->Status((T*)p); } void SetStatus(BYTE *p, typename CClosedHash<T>::ELEMENTSTATUS s) { WRAPPER_NO_CONTRACT; static_cast<H*>(this)->SetStatus((T*)p, s); } void* GetKey(BYTE *p) { WRAPPER_NO_CONTRACT; return static_cast<H*>(this)->GetKey((T*)p); } }; //***************************************************************************** // IMPORTANT: This data structure is deprecated, please do not add any new uses. // The hashtable implementation that should be used instead is code:SHash. // If code:SHash does not work for you, talk to mailto:clrdeag. //***************************************************************************** // This template is another form of a closed hash table. It handles collisions // through a linked chain. To use it, derive your hashed item from HASHLINK // and implement the virtual functions required. 1.5 * ibuckets will be // allocated, with the extra .5 used for collisions. If you add to the point // where no free nodes are available, the entire table is grown to make room. // The advantage to this system is that collisions are always directly known, // there either is one or there isn't. //***************************************************************************** struct HASHLINK { ULONG iNext; // Offset for next entry. }; template <class T> class CChainedHash { friend class VerifyLayoutsMD; public: CChainedHash(int iBuckets=32) : m_rgData(0), m_iBuckets(iBuckets), m_iCount(0), m_iMaxChain(0), m_iFree(0) { LIMITED_METHOD_CONTRACT; m_iSize = iBuckets + (iBuckets / 2); } ~CChainedHash() { LIMITED_METHOD_CONTRACT; if (m_rgData) delete [] m_rgData; } void SetBuckets(int iBuckets) { LIMITED_METHOD_CONTRACT; _ASSERTE(m_rgData == 0); // if iBuckets==0, then we'll allocate a zero size array and AV on dereference. _ASSERTE(iBuckets > 0); m_iBuckets = iBuckets; m_iSize = iBuckets + (iBuckets / 2); } T *Add(void const *pData) { WRAPPER_NO_CONTRACT; ULONG iHash; int iBucket; T *pItem; // Build the list if required. if (m_rgData == 0 || m_iFree == 0xffffffff) { if (!ReHash()) return (0); } // Hash the item and pick a bucket. iHash = Hash(pData); iBucket = iHash % m_iBuckets; // Use the bucket if it is free. if (InUse(&m_rgData[iBucket]) == false) { pItem = &m_rgData[iBucket]; pItem->iNext = 0xffffffff; } // Else take one off of the free list for use. else { ULONG iEntry; // Pull an item from the free list. iEntry = m_iFree; pItem = &m_rgData[m_iFree]; m_iFree = pItem->iNext; // Link the new node in after the bucket. pItem->iNext = m_rgData[iBucket].iNext; m_rgData[iBucket].iNext = iEntry; } ++m_iCount; return (pItem); } T *Find(void const *pData, bool bAddIfNew=false) { WRAPPER_NO_CONTRACT; ULONG iHash; int iBucket; T *pItem; // Check states for lookup. if (m_rgData == 0) { // If we won't be adding, then we are through. if (bAddIfNew == false) return (0); // Otherwise, create the table. if (!ReHash()) return (0); } // Hash the item and pick a bucket. iHash = Hash(pData); iBucket = iHash % m_iBuckets; // If it isn't in use, then there it wasn't found. if (!InUse(&m_rgData[iBucket])) { if (bAddIfNew == false) pItem = 0; else { pItem = &m_rgData[iBucket]; pItem->iNext = 0xffffffff; ++m_iCount; } } // Scan the list for the one we want. else { ULONG iChain = 0; for (pItem=(T *) &m_rgData[iBucket]; pItem; pItem=GetNext(pItem)) { if (Cmp(pData, pItem) == 0) break; ++iChain; } if (!pItem && bAddIfNew) { ULONG iEntry; // Record maximum chain length. if (iChain > m_iMaxChain) m_iMaxChain = iChain; // Now need more room. if (m_iFree == 0xffffffff) { if (!ReHash()) return (0); } // Pull an item from the free list. iEntry = m_iFree; pItem = &m_rgData[m_iFree]; m_iFree = pItem->iNext; // Link the new node in after the bucket. pItem->iNext = m_rgData[iBucket].iNext; m_rgData[iBucket].iNext = iEntry; ++m_iCount; } } return (pItem); } int Count() { LIMITED_METHOD_CONTRACT; return (m_iCount); } int Buckets() { LIMITED_METHOD_CONTRACT; return (m_iBuckets); } ULONG MaxChainLength() { LIMITED_METHOD_CONTRACT; return (m_iMaxChain); } virtual void Clear() { LIMITED_METHOD_CONTRACT; // Free up the memory. if (m_rgData) { delete [] m_rgData; m_rgData = 0; } m_rgData = 0; m_iFree = 0; m_iCount = 0; m_iMaxChain = 0; } virtual bool InUse(T *pItem)=0; virtual void SetFree(T *pItem)=0; virtual ULONG Hash(void const *pData)=0; virtual int Cmp(void const *pData, void *pItem)=0; private: inline T *GetNext(T *pItem) { LIMITED_METHOD_CONTRACT; if (pItem->iNext != 0xffffffff) return ((T *) &m_rgData[pItem->iNext]); return (0); } bool ReHash() { WRAPPER_NO_CONTRACT; T *rgTemp; int iNewSize; // If this is a first time allocation, then just malloc it. if (!m_rgData) { if ((m_rgData = new (nothrow) T[m_iSize]) == 0) return (false); int i; for (i=0; i<m_iSize; i++) SetFree(&m_rgData[i]); m_iFree = m_iBuckets; for (i=m_iBuckets; i<m_iSize; i++) ((T *) &m_rgData[i])->iNext = i + 1; ((T *) &m_rgData[m_iSize - 1])->iNext = 0xffffffff; return (true); } // Otherwise we need more room on the free chain, so allocate some. iNewSize = m_iSize + (m_iSize / 2); // Allocate/realloc memory. if ((rgTemp = new (nothrow) T[iNewSize]) == 0) return (false); memcpy (rgTemp,m_rgData,m_iSize*sizeof(T)); delete [] m_rgData; // Init new entries, save the new free chain, and reset internals. m_iFree = m_iSize; for (int i=m_iFree; i<iNewSize; i++) { SetFree(&rgTemp[i]); ((T *) &rgTemp[i])->iNext = i + 1; } ((T *) &rgTemp[iNewSize - 1])->iNext = 0xffffffff; m_rgData = rgTemp; m_iSize = iNewSize; return (true); } private: T *m_rgData; // Data to store items in. int m_iBuckets; // How many buckets we want. int m_iSize; // How many are allocated. int m_iCount; // How many are we using. ULONG m_iMaxChain; // Max chain length. ULONG m_iFree; // Free chain. }; //***************************************************************************** // //********** String helper functions. // //***************************************************************************** //***************************************************************************** // Checks if string length exceeds the specified limit //***************************************************************************** inline BOOL IsStrLongerThan(__in __in_z char* pstr, unsigned N) { LIMITED_METHOD_CONTRACT; unsigned i = 0; if(pstr) { for(i=0; (i < N)&&(pstr[i]); i++); } return (i >= N); } //***************************************************************************** // Class to parse a list of simple assembly names and then find a match //***************************************************************************** class AssemblyNamesList { struct AssemblyName { LPUTF8 m_assemblyName; AssemblyName *m_next; // Next name }; AssemblyName *m_pNames; // List of names public: bool IsInList(LPCUTF8 assemblyName); bool IsEmpty() { LIMITED_METHOD_CONTRACT; return m_pNames == 0; } AssemblyNamesList(__in LPWSTR list); ~AssemblyNamesList(); }; //***************************************************************************** // Class to parse a list of method names and then find a match //***************************************************************************** class MethodNamesListBase { struct MethodName { LPUTF8 methodName; // NULL means wildcard LPUTF8 className; // NULL means wildcard int numArgs; // number of args for the method, -1 is wildcard MethodName *next; // Next name }; MethodName *pNames; // List of names public: void Init() { LIMITED_METHOD_CONTRACT; pNames = 0; } void Init(__in __in_z LPWSTR list) { WRAPPER_NO_CONTRACT; pNames = 0; Insert(list); } void Destroy(); void Insert(__in __in_z LPWSTR list); bool IsInList(LPCUTF8 methodName, LPCUTF8 className, PCCOR_SIGNATURE sig); bool IsEmpty() { LIMITED_METHOD_CONTRACT; return pNames == 0; } }; class MethodNamesList : public MethodNamesListBase { public: MethodNamesList() { WRAPPER_NO_CONTRACT; Init(); } MethodNamesList(__in LPWSTR list) { WRAPPER_NO_CONTRACT; Init(list); } ~MethodNamesList() { WRAPPER_NO_CONTRACT; Destroy(); } }; /**************************************************************************/ /* simple wrappers around the REGUTIL and MethodNameList routines that make the lookup lazy */ /* to be used as static variable - no constructor/destructor, assumes zero initialized memory */ class ConfigDWORD { public: // // NOTE: The following function is deprecated; use the CLRConfig class instead. // To access a configuration value through CLRConfig, add an entry in file:../inc/CLRConfigValues.h. // inline DWORD val_DontUse_(__in __in_z LPCWSTR keyName, DWORD defaultVal=0) { WRAPPER_NO_CONTRACT; // make sure that the memory was zero initialized _ASSERTE(m_inited == 0 || m_inited == 1); if (!m_inited) init_DontUse_(keyName, defaultVal); return m_value; } inline DWORD val(const CLRConfig::ConfigDWORDInfo & info) { WRAPPER_NO_CONTRACT; // make sure that the memory was zero initialized _ASSERTE(m_inited == 0 || m_inited == 1); if (!m_inited) init(info); return m_value; } private: void init_DontUse_(__in __in_z LPCWSTR keyName, DWORD defaultVal=0); void init(const CLRConfig::ConfigDWORDInfo & info); private: DWORD m_value; BYTE m_inited; }; /**************************************************************************/ class ConfigString { public: inline LPWSTR val(const CLRConfig::ConfigStringInfo & info) { WRAPPER_NO_CONTRACT; // make sure that the memory was zero initialized _ASSERTE(m_inited == 0 || m_inited == 1); if (!m_inited) init(info); return m_value; } bool isInitialized() { WRAPPER_NO_CONTRACT; // make sure that the memory was zero initialized _ASSERTE(m_inited == 0 || m_inited == 1); return m_inited == 1; } private: void init(const CLRConfig::ConfigStringInfo & info); private: LPWSTR m_value; BYTE m_inited; }; /**************************************************************************/ class ConfigMethodSet { public: bool isEmpty() { WRAPPER_NO_CONTRACT; _ASSERTE(m_inited == 1); return m_list.IsEmpty(); } bool contains(LPCUTF8 methodName, LPCUTF8 className, PCCOR_SIGNATURE sig); inline void ensureInit(const CLRConfig::ConfigStringInfo & info) { WRAPPER_NO_CONTRACT; // make sure that the memory was zero initialized _ASSERTE(m_inited == 0 || m_inited == 1); if (!m_inited) init(info); } private: void init(const CLRConfig::ConfigStringInfo & info); private: MethodNamesListBase m_list; BYTE m_inited; }; //***************************************************************************** // Convert a pointer to a string into a GUID. //***************************************************************************** HRESULT LPCSTRToGuid( // Return status. LPCSTR szGuid, // String to convert. GUID *psGuid); // Buffer for converted GUID. //***************************************************************************** // Convert a GUID into a pointer to a string //***************************************************************************** int GuidToLPWSTR( // Return status. GUID Guid, // [IN] The GUID to convert. __out_ecount (cchGuid) LPWSTR szGuid, // [OUT] String into which the GUID is stored DWORD cchGuid); // [IN] Size in wide chars of szGuid //***************************************************************************** // Parse a Wide char string into a GUID //***************************************************************************** BOOL LPWSTRToGuid( GUID * Guid, // [OUT] The GUID to fill in __in_ecount(cchGuid) LPCWSTR szGuid, // [IN] String to parse DWORD cchGuid); // [IN] Count in wchars in string typedef VPTR(class RangeList) PTR_RangeList; class RangeList { public: VPTR_BASE_CONCRETE_VTABLE_CLASS(RangeList) #ifndef DACCESS_COMPILE RangeList(); ~RangeList(); #else RangeList() { LIMITED_METHOD_CONTRACT; } #endif // Wrappers to make the virtual calls DAC-safe. BOOL AddRange(const BYTE *start, const BYTE *end, void *id) { return this->AddRangeWorker(start, end, id); } void RemoveRanges(void *id, const BYTE *start = NULL, const BYTE *end = NULL) { return this->RemoveRangesWorker(id, start, end); } BOOL IsInRange(TADDR address, TADDR *pID = NULL) { SUPPORTS_DAC; return this->IsInRangeWorker(address, pID); } #ifndef DACCESS_COMPILE // You can overload these two for synchronization (as LockedRangeList does) virtual BOOL AddRangeWorker(const BYTE *start, const BYTE *end, void *id); // If both "start" and "end" are NULL, then this method deletes all ranges with // the given id (i.e. the original behaviour). Otherwise, it ignores the given // id and deletes all ranges falling in the region [start, end). virtual void RemoveRangesWorker(void *id, const BYTE *start = NULL, const BYTE *end = NULL); #else virtual BOOL AddRangeWorker(const BYTE *start, const BYTE *end, void *id) { return TRUE; } virtual void RemoveRangesWorker(void *id, const BYTE *start = NULL, const BYTE *end = NULL) { } #endif // !DACCESS_COMPILE virtual BOOL IsInRangeWorker(TADDR address, TADDR *pID = NULL); #ifdef DACCESS_COMPILE void EnumMemoryRegions(enum CLRDataEnumMemoryFlags flags); #endif enum { RANGE_COUNT = 10 }; private: struct Range { TADDR start; TADDR end; TADDR id; }; struct RangeListBlock { Range ranges[RANGE_COUNT]; DPTR(RangeListBlock) next; #ifdef DACCESS_COMPILE void EnumMemoryRegions(enum CLRDataEnumMemoryFlags flags); #endif }; void InitBlock(RangeListBlock *block); RangeListBlock m_starterBlock; DPTR(RangeListBlock) m_firstEmptyBlock; TADDR m_firstEmptyRange; }; // // A private function to do the equavilent of a CoCreateInstance in // cases where we can't make the real call. Use this when, for // instance, you need to create a symbol reader in the Runtime but // we're not CoInitialized. Obviously, this is only good for COM // objects for which CoCreateInstance is just a glorified // find-and-load-me operation. // HRESULT FakeCoCreateInstanceEx(REFCLSID rclsid, LPCWSTR wszDllPath, REFIID riid, void ** ppv, HMODULE * phmodDll); // Provided for backward compatibility and for code that doesn't need the HMODULE of the // DLL that was loaded to create the COM object. See comment at implementation of // code:FakeCoCreateInstanceEx for more details. inline HRESULT FakeCoCreateInstance(REFCLSID rclsid, REFIID riid, void ** ppv) { CONTRACTL { NOTHROW; } CONTRACTL_END; return FakeCoCreateInstanceEx(rclsid, NULL, riid, ppv, NULL); }; HRESULT FakeCoCallDllGetClassObject(REFCLSID rclsid, LPCWSTR wszDllPath, REFIID riid, void ** ppv, HMODULE * phmodDll); //***************************************************************************** // Gets the directory based on the location of the module. This routine // is called at COR setup time. Set is called during EEStartup and by the // MetaData dispenser. //***************************************************************************** HRESULT GetInternalSystemDirectory(__out_ecount_part_opt(*pdwLength,*pdwLength) LPWSTR buffer, __inout DWORD* pdwLength); LPCWSTR GetInternalSystemDirectory(__out_opt DWORD * pdwLength = NULL); //***************************************************************************** // This function validates the given Method/Field/Standalone signature. (util.cpp) //***************************************************************************** struct IMDInternalImport; HRESULT validateTokenSig( mdToken tk, // [IN] Token whose signature needs to be validated. PCCOR_SIGNATURE pbSig, // [IN] Signature. ULONG cbSig, // [IN] Size in bytes of the signature. DWORD dwFlags, // [IN] Method flags. IMDInternalImport* pImport); // [IN] Internal MD Import interface ptr //***************************************************************************** // Determine the version number of the runtime that was used to build the // specified image. The pMetadata pointer passed in is the pointer to the // metadata contained in the image. //***************************************************************************** HRESULT GetImageRuntimeVersionString(PVOID pMetaData, LPCSTR* pString); void AdjustImageRuntimeVersion (SString* pVersion); //***************************************************************************** // The registry keys and values that contain the information regarding // the default registered unmanaged debugger. //***************************************************************************** SELECTANY const WCHAR kDebugApplicationsPoliciesKey[] = W("SOFTWARE\\Policies\\Microsoft\\Windows\\Windows Error Reporting\\DebugApplications"); SELECTANY const WCHAR kDebugApplicationsKey[] = W("SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\DebugApplications"); SELECTANY const WCHAR kUnmanagedDebuggerKey[] = W("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug"); SELECTANY const WCHAR kUnmanagedDebuggerValue[] = W("Debugger"); SELECTANY const WCHAR kUnmanagedDebuggerAutoValue[] = W("Auto"); SELECTANY const WCHAR kUnmanagedDebuggerAutoExclusionListKey[] = W("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList"); BOOL GetRegistryLongValue(HKEY hKeyParent, // Parent key. LPCWSTR szKey, // Key name to look at. LPCWSTR szName, // Name of value to get. long *pValue, // Put value here, if found. BOOL fReadNonVirtualizedKey); // Whether to read 64-bit hive on WOW64 HRESULT GetCurrentModuleFileName(__out_ecount(*pcchBuffer) LPWSTR pBuffer, __inout DWORD *pcchBuffer); //***************************************************************************** // Retrieve information regarding what registered default debugger //***************************************************************************** void GetDebuggerSettingInfo(SString &debuggerKeyValue, BOOL *pfAuto); HRESULT GetDebuggerSettingInfoWorker(__out_ecount_part_opt(*pcchDebuggerString, *pcchDebuggerString) LPWSTR wszDebuggerString, DWORD * pcchDebuggerString, BOOL * pfAuto); void TrimWhiteSpace(__deref_inout_ecount(*pcch) LPCWSTR *pwsz, __inout LPDWORD pcch); //***************************************************************************** // Convert a UTF8 string to Unicode, into a CQuickArray<WCHAR>. //***************************************************************************** HRESULT Utf2Quick( LPCUTF8 pStr, // The string to convert. CQuickArray<WCHAR> &rStr, // The QuickArray<WCHAR> to convert it into. int iCurLen); // Inital characters in the array to leave (default 0). //***************************************************************************** // Extract the movl 64-bit unsigned immediate from an IA64 bundle // (Format X2) //***************************************************************************** UINT64 GetIA64Imm64(UINT64 * pBundle); UINT64 GetIA64Imm64(UINT64 qword0, UINT64 qword1); //***************************************************************************** // Deposit the movl 64-bit unsigned immediate into an IA64 bundle // (Format X2) //***************************************************************************** void PutIA64Imm64(UINT64 * pBundle, UINT64 imm64); //***************************************************************************** // Extract the addl 22-bit signed immediate from an IA64 bundle // (Format A5) //***************************************************************************** INT32 GetIA64Imm22(UINT64 * pBundle, UINT32 slot); //***************************************************************************** // Deposit the addl 22-bit signed immediate into an IA64 bundle // (Format A5) //***************************************************************************** void PutIA64Imm22(UINT64 * pBundle, UINT32 slot, INT32 imm22); //***************************************************************************** // Extract the IP-Relative signed 25-bit immediate from an IA64 bundle // (Formats B1, B2 or B3) // Note that due to branch target alignment requirements // the lowest four bits in the result will always be zero. //***************************************************************************** INT32 GetIA64Rel25(UINT64 * pBundle, UINT32 slot); INT32 GetIA64Rel25(UINT64 qword0, UINT64 qword1, UINT32 slot); //***************************************************************************** // Deposit the IP-Relative signed 25-bit immediate into an IA64 bundle // (Formats B1, B2 or B3) // Note that due to branch target alignment requirements // the lowest four bits are required to be zero. //***************************************************************************** void PutIA64Rel25(UINT64 * pBundle, UINT32 slot, INT32 imm25); //***************************************************************************** // Extract the IP-Relative signed 64-bit immediate from an IA64 bundle // (Formats X3 or X4) //***************************************************************************** INT64 GetIA64Rel64(UINT64 * pBundle); INT64 GetIA64Rel64(UINT64 qword0, UINT64 qword1); //***************************************************************************** // Deposit the IP-Relative signed 64-bit immediate into a IA64 bundle // (Formats X3 or X4) //***************************************************************************** void PutIA64Rel64(UINT64 * pBundle, INT64 imm64); //***************************************************************************** // Extract the 32-bit immediate from movw/movt Thumb2 sequence //***************************************************************************** UINT32 GetThumb2Mov32(UINT16 * p); //***************************************************************************** // Deposit the 32-bit immediate into movw/movt Thumb2 sequence //***************************************************************************** void PutThumb2Mov32(UINT16 * p, UINT32 imm32); //***************************************************************************** // Extract the 24-bit rel offset from bl instruction //***************************************************************************** INT32 GetThumb2BlRel24(UINT16 * p); //***************************************************************************** // Extract the 24-bit rel offset from bl instruction //***************************************************************************** void PutThumb2BlRel24(UINT16 * p, INT32 imm24); //***************************************************************************** // Extract the PC-Relative offset from a b or bl instruction //***************************************************************************** INT32 GetArm64Rel28(UINT32 * pCode); //***************************************************************************** // Deposit the PC-Relative offset 'imm28' into a b or bl instruction //***************************************************************************** void PutArm64Rel28(UINT32 * pCode, INT32 imm28); //***************************************************************************** // Returns whether the offset fits into bl instruction //***************************************************************************** inline bool FitsInThumb2BlRel24(INT32 imm24) { return ((imm24 << 7) >> 7) == imm24; } //***************************************************************************** // Returns whether the offset fits into an Arm64 b or bl instruction //***************************************************************************** inline bool FitsInRel28(INT32 val32) { return (val32 >= -0x08000000) && (val32 < 0x08000000); } //***************************************************************************** // Returns whether the offset fits into an Arm64 b or bl instruction //***************************************************************************** inline bool FitsInRel28(INT64 val64) { return (val64 >= -0x08000000LL) && (val64 < 0x08000000LL); } //***************************************************************************** // Splits a command line into argc/argv lists, using the VC7 parsing rules. // This functions interface mimics the CommandLineToArgvW api. // If function fails, returns NULL. // If function suceeds, call delete [] on return pointer when done. //***************************************************************************** LPWSTR *SegmentCommandLine(LPCWSTR lpCmdLine, DWORD *pNumArgs); // // TEB access can be dangerous when using fibers because a fiber may // run on multiple threads. If the TEB pointer is retrieved and saved // and then a fiber is moved to a different thread, when it accesses // the saved TEB pointer, it will be looking at the TEB state for a // different fiber. // // These accessors serve the purpose of retrieving information from the // TEB in a manner that ensures that the current fiber will not switch // threads while the access is occuring. // class ClrTeb { public: #if defined(FEATURE_PAL) // returns pointer that uniquely identifies the fiber static void* GetFiberPtrId() { LIMITED_METHOD_CONTRACT; // not fiber for FEATURE_PAL - use the regular thread ID return (void *)(size_t)GetCurrentThreadId(); } static void* InvalidFiberPtrId() { return NULL; } static void* GetStackBase() { return PAL_GetStackBase(); } static void* GetStackLimit() { return PAL_GetStackLimit(); } #else // !FEATURE_PAL // returns pointer that uniquely identifies the fiber static void* GetFiberPtrId() { LIMITED_METHOD_CONTRACT; // stackbase is the unique fiber identifier return NtCurrentTeb()->NtTib.StackBase; } static void* GetStackBase() { LIMITED_METHOD_CONTRACT; return NtCurrentTeb()->NtTib.StackBase; } static void* GetStackLimit() { LIMITED_METHOD_CONTRACT; return NtCurrentTeb()->NtTib.StackLimit; } // Please don't start to use this method unless you absolutely have to. // The reason why this is added is for WIN64 to support LEGACY PE-style TLS // variables. On X86 it is supported by the JIT compilers themselves. On // WIN64 we build more logic into the JIT helper for accessing fields. static void* GetLegacyThreadLocalStoragePointer() { LIMITED_METHOD_CONTRACT; return NtCurrentTeb()->ThreadLocalStoragePointer; } static void* GetOleReservedPtr() { LIMITED_METHOD_CONTRACT; return NtCurrentTeb()->ReservedForOle; } static void* GetProcessEnvironmentBlock() { LIMITED_METHOD_CONTRACT; return NtCurrentTeb()->ProcessEnvironmentBlock; } #ifndef FEATURE_CORECLR static void* GetFiberDataPtr() { LIMITED_METHOD_CONTRACT; return ClrTeb::IsCurrentThreadAFiber()? GetCurrentFiber() : NULL; } static BOOL IsCurrentThreadAFiber() { return IsThreadAFiber(); } #endif static void* InvalidFiberPtrId() { return (void*) 1; } #endif // !FEATURE_PAL }; #if !defined(DACCESS_COMPILE) && !defined(CLR_STANDALONE_BINDER) // check if current thread is a GC thread (concurrent or server) inline BOOL IsGCSpecialThread () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; STATIC_CONTRACT_CANNOT_TAKE_LOCK; return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_GC); } // check if current thread is a Gate thread inline BOOL IsGateSpecialThread () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_Gate); } // check if current thread is a Timer thread inline BOOL IsTimerSpecialThread () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_Timer); } // check if current thread is a debugger helper thread inline BOOL IsDbgHelperSpecialThread () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_DbgHelper); } // check if current thread is a debugger helper thread inline BOOL IsETWRundownSpecialThread () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_ETWRundownThread); } // check if current thread is a generic instantiation lookup compare thread inline BOOL IsGenericInstantiationLookupCompareThread () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_GenericInstantiationCompare); } // check if current thread is a thread which is performing shutdown inline BOOL IsShutdownSpecialThread () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_Shutdown); } inline BOOL IsThreadPoolIOCompletionSpecialThread () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_Threadpool_IOCompletion); } inline BOOL IsThreadPoolWorkerSpecialThread () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_Threadpool_Worker); } inline BOOL IsWaitSpecialThread () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_Wait); } // check if current thread is a thread which is performing shutdown inline BOOL IsSuspendEEThread () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_DynamicSuspendEE); } inline BOOL IsFinalizerThread () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_Finalizer); } inline BOOL IsADUnloadHelperThread () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_ADUnloadHelper); } inline BOOL IsShutdownHelperThread () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_ShutdownHelper); } inline BOOL IsProfilerAttachThread () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_ProfAPI_Attach); } // set specical type for current thread inline void ClrFlsSetThreadType (TlsThreadTypeFlag flag) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; STATIC_CONTRACT_SO_TOLERANT; ClrFlsSetValue (TlsIdx_ThreadType, (LPVOID)(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) |flag)); } // clear specical type for current thread inline void ClrFlsClearThreadType (TlsThreadTypeFlag flag) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; ClrFlsSetValue (TlsIdx_ThreadType, (LPVOID)(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ~flag)); } #endif //!DACCESS_COMPILE #ifdef DACCESS_COMPILE #define SET_THREAD_TYPE_STACKWALKER(pThread) #define CLEAR_THREAD_TYPE_STACKWALKER() #else // DACCESS_COMPILE #define SET_THREAD_TYPE_STACKWALKER(pThread) ClrFlsSetValue(TlsIdx_StackWalkerWalkingThread, pThread) #define CLEAR_THREAD_TYPE_STACKWALKER() ClrFlsSetValue(TlsIdx_StackWalkerWalkingThread, NULL) #endif // DACCESS_COMPILE inline BOOL IsStackWalkerThread() { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; STATIC_CONTRACT_CANNOT_TAKE_LOCK; #if defined(DACCESS_COMPILE) || defined(CLR_STANDALONE_BINDER) return FALSE; #else return ClrFlsGetValue (TlsIdx_StackWalkerWalkingThread) != NULL; #endif } inline BOOL IsGCThread () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; STATIC_CONTRACT_SUPPORTS_DAC; STATIC_CONTRACT_SO_TOLERANT; #if !defined(DACCESS_COMPILE) && !defined(CLR_STANDALONE_BINDER) return IsGCSpecialThread () || IsSuspendEEThread (); #else return FALSE; #endif } #ifndef CLR_STANDALONE_BINDER class ClrFlsThreadTypeSwitch { public: ClrFlsThreadTypeSwitch (TlsThreadTypeFlag flag) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; #ifndef DACCESS_COMPILE m_flag = flag; m_fPreviouslySet = (((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & flag); // In debug builds, remember the full group of flags that were set at the time // the constructor was called. This will be used in ASSERTs in the destructor INDEBUG(m_nPreviousFlagGroup = (size_t)ClrFlsGetValue (TlsIdx_ThreadType)); if (!m_fPreviouslySet) { ClrFlsSetThreadType(flag); } #endif // DACCESS_COMPILE } ~ClrFlsThreadTypeSwitch () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; #ifndef DACCESS_COMPILE // This holder should only be used to set (and thus restore) ONE thread type flag // at a time. If more than that one flag was modified since this holder was // instantiated, then this holder still restores only the flag it knows about. To // prevent confusion, assert if some other flag was modified, so the user doesn't // expect the holder to restore the entire original set of flags. // // The expression below says that the only difference between the previous flag // group and the current flag group should be m_flag (or no difference at all, if // m_flag's state didn't actually change). _ASSERTE(((m_nPreviousFlagGroup ^ (size_t) ClrFlsGetValue(TlsIdx_ThreadType)) | (size_t) m_flag) == (size_t) m_flag); if (m_fPreviouslySet) { ClrFlsSetThreadType(m_flag); } else { ClrFlsClearThreadType(m_flag); } #endif // DACCESS_COMPILE } private: TlsThreadTypeFlag m_flag; BOOL m_fPreviouslySet; INDEBUG(size_t m_nPreviousFlagGroup); }; class ClrFlsValueSwitch { public: ClrFlsValueSwitch (PredefinedTlsSlots slot, PVOID value) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; #ifndef DACCESS_COMPILE m_slot = slot; m_PreviousValue = ClrFlsGetValue(slot); ClrFlsSetValue(slot, value); #endif // DACCESS_COMPILE } ~ClrFlsValueSwitch () { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; #ifndef DACCESS_COMPILE ClrFlsSetValue(m_slot, m_PreviousValue); #endif // DACCESS_COMPILE } private: PVOID m_PreviousValue; PredefinedTlsSlots m_slot; }; #endif // !CLR_STANDALONE_BINDER //********************************************************************************* // When we're hosted, operations called by the host (such as Thread::YieldTask) // may not cause calls back into the host, as the host needs not be reentrant. // Use the following holder for code in which calls into the host are forbidden. // (If a call into the host is attempted nevertheless, an assert will fire.) class ForbidCallsIntoHostOnThisThread { private: static Volatile<PVOID> s_pvOwningFiber; FORCEINLINE static BOOL Enter(BOOL) { WRAPPER_NO_CONTRACT; return InterlockedCompareExchangePointer( &s_pvOwningFiber, ClrTeb::GetFiberPtrId(), NULL) == NULL; } FORCEINLINE static void Leave(BOOL) { LIMITED_METHOD_CONTRACT; s_pvOwningFiber = NULL; } public: typedef ConditionalStateHolder<BOOL, ForbidCallsIntoHostOnThisThread::Enter, ForbidCallsIntoHostOnThisThread::Leave> Holder; FORCEINLINE static BOOL CanThisThreadCallIntoHost() { WRAPPER_NO_CONTRACT; return s_pvOwningFiber != ClrTeb::GetFiberPtrId(); } }; typedef ForbidCallsIntoHostOnThisThread::Holder ForbidCallsIntoHostOnThisThreadHolder; FORCEINLINE BOOL CanThisThreadCallIntoHost() { WRAPPER_NO_CONTRACT; return ForbidCallsIntoHostOnThisThread::CanThisThreadCallIntoHost(); } //********************************************************************************* #include "contract.inl" namespace util { // compare adapters // template < typename T > struct less { bool operator()( T const & first, T const & second ) const { return first < second; } }; template < typename T > struct greater { bool operator()( T const & first, T const & second ) const { return first > second; } }; // sort adapters // template< typename Iter, typename Pred > void sort( Iter begin, Iter end, Pred pred ); template< typename T, typename Pred > void sort( T * begin, T * end, Pred pred ) { struct sort_helper : CQuickSort< T > { sort_helper( T * begin, T * end, Pred pred ) : CQuickSort< T >( begin, end - begin ) , m_pred( pred ) {} virtual int Compare( T * first, T * second ) { return m_pred( *first, *second ) ? -1 : ( m_pred( *second, *first ) ? 1 : 0 ); } Pred m_pred; }; sort_helper sort_obj( begin, end, pred ); sort_obj.Sort(); } template < typename Iter > void sort( Iter begin, Iter end ); template < typename T > void sort( T * begin, T * end ) { util::sort( begin, end, util::less< T >() ); } // binary search adapters // template < typename Iter, typename T, typename Pred > Iter lower_bound( Iter begin, Iter end, T const & val, Pred pred ); template < typename T, typename Pred > T * lower_bound( T * begin, T * end, T const & val, Pred pred ) { for (; begin != end; ) { T * mid = begin + ( end - begin ) / 2; if ( pred( *mid, val ) ) begin = ++mid; else end = mid; } return begin; } template < typename Iter, typename T > Iter lower_bound( Iter begin, Iter end, T const & val ); template < typename T > T * lower_bound( T * begin, T * end, T const & val ) { return util::lower_bound( begin, end, val, util::less< T >() ); } } /* ------------------------------------------------------------------------ * * Overloaded operators for the executable heap * ------------------------------------------------------------------------ */ #ifndef FEATURE_PAL struct CExecutable { int x; }; extern const CExecutable executable; void * __cdecl operator new(size_t n, const CExecutable&); void * __cdecl operator new[](size_t n, const CExecutable&); void * __cdecl operator new(size_t n, const CExecutable&, const NoThrow&); void * __cdecl operator new[](size_t n, const CExecutable&, const NoThrow&); // // Executable heap delete to match the executable heap new above. // template<class T> void DeleteExecutable(T *p) { if (p != NULL) { p->T::~T(); ClrHeapFree(ClrGetProcessExecutableHeap(), 0, p); } } #endif // FEATURE_PAL INDEBUG(BOOL DbgIsExecutable(LPVOID lpMem, SIZE_T length);) class HighCharHelper { public: static inline BOOL IsHighChar(int c) { return (BOOL)HighCharTable[c]; } private: static const BYTE HighCharTable[]; }; BOOL ThreadWillCreateGuardPage(SIZE_T sizeReservedStack, SIZE_T sizeCommitedStack); FORCEINLINE void HolderSysFreeString(BSTR str) { CONTRACT_VIOLATION(ThrowsViolation); SysFreeString(str); } typedef Wrapper<BSTR, DoNothing, HolderSysFreeString> BSTRHolder; BOOL FileExists(LPCWSTR filename); #ifndef FEATURE_CORECLR class FileLockHolder { public: FileLockHolder(); ~FileLockHolder(); virtual void Acquire(LPCWSTR lockName, HANDLE hInterrupt = 0, BOOL* pInterrupted = NULL); HRESULT AcquireNoThrow(LPCWSTR lockName, HANDLE hInterrupt = 0, BOOL* pInterrupted = NULL); static BOOL IsTaken(LPCWSTR lockName); void Release(); private: HANDLE _hLock; }; #endif // FEATURE_CORECLR // a class for general x.x version info class MajorMinorVersionInfo { protected: WORD version[2]; BOOL bInitialized; public: //cctors MajorMinorVersionInfo() { LIMITED_METHOD_CONTRACT; bInitialized = FALSE; ZeroMemory(version,sizeof(version)); }; MajorMinorVersionInfo(WORD wMajor, WORD wMinor) { WRAPPER_NO_CONTRACT; Init(wMajor,wMinor); }; // getters BOOL IsInitialized() const { LIMITED_METHOD_CONTRACT; return bInitialized; }; WORD Major() const { LIMITED_METHOD_CONTRACT; return version[0]; }; WORD Minor() const { LIMITED_METHOD_CONTRACT; return version[1]; }; // setters void Init(WORD wMajor, WORD wMinor) { LIMITED_METHOD_CONTRACT; version[0]=wMajor; version[1]=wMinor; bInitialized=TRUE; }; }; // CLR runtime version info in Major/Minor form class RUNTIMEVERSIONINFO : public MajorMinorVersionInfo { static RUNTIMEVERSIONINFO notDefined; public: // cctors RUNTIMEVERSIONINFO() {}; RUNTIMEVERSIONINFO(WORD wMajor, WORD wMinor) : MajorMinorVersionInfo(wMajor,wMinor){}; // CLR version specific helpers BOOL IsPreWhidbey() const { WRAPPER_NO_CONTRACT; return (Major() == 1) && (Minor() <= 1); } static const RUNTIMEVERSIONINFO& NotApplicable() { LIMITED_METHOD_CONTRACT; return notDefined; } }; // HMODULE_TGT represents a handle to a module in the target process. In non-DAC builds this is identical // to HMODULE (HINSTANCE), which is the base address of the module. In DAC builds this must be a target address, // and so is represented by TADDR. #ifdef DACCESS_COMPILE typedef TADDR HMODULE_TGT; #else typedef HMODULE HMODULE_TGT; #endif BOOL IsIPInModule(HMODULE_TGT hModule, PCODE ip); //---------------------------------------------------------------------------------------- // The runtime invokes InitUtilcode() in its dllmain and passes along all of the critical // callback pointers. For the desktop CLR, all DLLs loaded by the runtime must also call // InitUtilcode with the same callbacks as the runtime used. To achieve this, the runtime // calls a special initialization routine exposed by the loaded module with the callbacks, // which in turn calls InitUtilcode. // // This structure collects all of the critical callback info passed in InitUtilcode(). // Note that one of them is GetCLRFunction() which is itself a gofer for many other // callbacks. If a callback fetch be safely deferred until we have TLS and stack probe // functionality running, it should be added to that function rather than this structure. // Things like IEE are here because that callback has to be set up before GetCLRFunction() // can be safely called. //---------------------------------------------------------------------------------------- struct CoreClrCallbacks { typedef IExecutionEngine* (__stdcall * pfnIEE_t)(); typedef HRESULT (__stdcall * pfnGetCORSystemDirectory_t)(LPWSTR pbuffer, DWORD cchBuffer, DWORD* pdwlength); typedef void* (__stdcall * pfnGetCLRFunction_t)(LPCSTR functionName); HINSTANCE m_hmodCoreCLR; pfnIEE_t m_pfnIEE; pfnGetCORSystemDirectory_t m_pfnGetCORSystemDirectory; pfnGetCLRFunction_t m_pfnGetCLRFunction; }; #if defined(FEATURE_CORECLR) || !defined(SELF_NO_HOST) || defined(DACCESS_COMPILE) // For DAC, we include this functionality only when EH SxS is enabled. //---------------------------------------------------------------------------------------- // CoreCLR must invoke this before CRT initialization to ensure utilcode has all the callback // pointers it needs. //---------------------------------------------------------------------------------------- VOID InitUtilcode(const CoreClrCallbacks &cccallbacks); CoreClrCallbacks const & GetClrCallbacks(); //---------------------------------------------------------------------------------------- // Stuff below is for utilcode.lib eyes only. //---------------------------------------------------------------------------------------- // Stores callback pointers provided by InitUtilcode(). extern CoreClrCallbacks g_CoreClrCallbacks; // Throws up a helpful dialog if InitUtilcode() wasn't called. #ifdef _DEBUG void OnUninitializedCoreClrCallbacks(); #define VALIDATECORECLRCALLBACKS() if (g_CoreClrCallbacks.m_hmodCoreCLR == NULL) OnUninitializedCoreClrCallbacks() #else //_DEBUG #define VALIDATECORECLRCALLBACKS() #endif //_DEBUG #endif // defined(FEATURE_CORECLR) || !defined(SELF_NO_HOST) || defined(DACCESS_COMPILE) #ifdef FEATURE_CORRUPTING_EXCEPTIONS // Corrupting Exception limited support for outside the VM folder BOOL IsProcessCorruptedStateException(DWORD dwExceptionCode, BOOL fCheckForSO = TRUE); #endif // FEATURE_CORRUPTING_EXCEPTIONS BOOL IsV2RuntimeLoaded(void); namespace UtilCode { // These are type-safe versions of Interlocked[Compare]Exchange // They avoid invoking struct cast operations via reinterpreting // the struct's address as a LONG* or LONGLONG* and dereferencing it. // // If we had a global ::operator & (unary), we would love to use that // to ensure we were not also accidentally getting a structs's provided // operator &. TODO: probe with a static_assert? template <typename T, int SIZE = sizeof(T)> struct InterlockedCompareExchangeHelper; template <typename T> struct InterlockedCompareExchangeHelper<T, sizeof(LONG)> { static inline T InterlockedExchange( T volatile * target, T value) { static_assert_no_msg(sizeof(T) == sizeof(LONG)); LONG res = ::InterlockedExchange( reinterpret_cast<LONG volatile *>(target), *reinterpret_cast<LONG *>(/*::operator*/&(value))); return *reinterpret_cast<T*>(&res); } static inline T InterlockedCompareExchange( T volatile * destination, T exchange, T comparand) { static_assert_no_msg(sizeof(T) == sizeof(LONG)); LONG res = ::InterlockedCompareExchange( reinterpret_cast<LONG volatile *>(destination), *reinterpret_cast<LONG*>(/*::operator*/&(exchange)), *reinterpret_cast<LONG*>(/*::operator*/&(comparand))); return *reinterpret_cast<T*>(&res); } }; template <typename T> struct InterlockedCompareExchangeHelper<T, sizeof(LONGLONG)> { static inline T InterlockedExchange( T volatile * target, T value) { static_assert_no_msg(sizeof(T) == sizeof(LONGLONG)); LONGLONG res = ::InterlockedExchange64( reinterpret_cast<LONGLONG volatile *>(target), *reinterpret_cast<LONGLONG *>(/*::operator*/&(value))); return *reinterpret_cast<T*>(&res); } static inline T InterlockedCompareExchange( T volatile * destination, T exchange, T comparand) { static_assert_no_msg(sizeof(T) == sizeof(LONGLONG)); LONGLONG res = ::InterlockedCompareExchange64( reinterpret_cast<LONGLONG volatile *>(destination), *reinterpret_cast<LONGLONG*>(/*::operator*/&(exchange)), *reinterpret_cast<LONGLONG*>(/*::operator*/&(comparand))); return *reinterpret_cast<T*>(&res); } }; } template <typename T> inline T InterlockedExchangeT( T volatile * target, T value) { return ::UtilCode::InterlockedCompareExchangeHelper<T>::InterlockedExchange( target, value); } template <typename T> inline T InterlockedCompareExchangeT( T volatile * destination, T exchange, T comparand) { return ::UtilCode::InterlockedCompareExchangeHelper<T>::InterlockedCompareExchange( destination, exchange, comparand); } // Pointer variants for Interlocked[Compare]ExchangePointer // If the underlying type is a const type, we have to remove its constness // since Interlocked[Compare]ExchangePointer doesn't take const void * arguments. template <typename T> inline T* InterlockedExchangeT( T* volatile * target, T* value) { //STATIC_ASSERT(value == 0); typedef typename std::remove_const<T>::type * non_const_ptr_t; return reinterpret_cast<T*>(InterlockedExchangePointer( reinterpret_cast<PVOID volatile *>(const_cast<non_const_ptr_t volatile *>(target)), reinterpret_cast<PVOID>(const_cast<non_const_ptr_t>(value)))); } template <typename T> inline T* InterlockedCompareExchangeT( T* volatile * destination, T* exchange, T* comparand) { //STATIC_ASSERT(exchange == 0); typedef typename std::remove_const<T>::type * non_const_ptr_t; return reinterpret_cast<T*>(InterlockedCompareExchangePointer( reinterpret_cast<PVOID volatile *>(const_cast<non_const_ptr_t volatile *>(destination)), reinterpret_cast<PVOID>(const_cast<non_const_ptr_t>(exchange)), reinterpret_cast<PVOID>(const_cast<non_const_ptr_t>(comparand)))); } // NULL pointer variants of the above to avoid having to cast NULL // to the appropriate pointer type. template <typename T> inline T* InterlockedExchangeT( T* volatile * target, int value) // When NULL is provided as argument. { //STATIC_ASSERT(value == 0); return InterlockedExchangeT(target, reinterpret_cast<T*>(value)); } template <typename T> inline T* InterlockedCompareExchangeT( T* volatile * destination, int exchange, // When NULL is provided as argument. T* comparand) { //STATIC_ASSERT(exchange == 0); return InterlockedCompareExchangeT(destination, reinterpret_cast<T*>(exchange), comparand); } template <typename T> inline T* InterlockedCompareExchangeT( T* volatile * destination, T* exchange, int comparand) // When NULL is provided as argument. { //STATIC_ASSERT(comparand == 0); return InterlockedCompareExchangeT(destination, exchange, reinterpret_cast<T*>(comparand)); } // NULL pointer variants of the above to avoid having to cast NULL // to the appropriate pointer type. template <typename T> inline T* InterlockedExchangeT( T* volatile * target, std::nullptr_t value) // When nullptr is provided as argument. { //STATIC_ASSERT(value == 0); return InterlockedExchangeT(target, reinterpret_cast<T*>(value)); } template <typename T> inline T* InterlockedCompareExchangeT( T* volatile * destination, std::nullptr_t exchange, // When nullptr is provided as argument. T* comparand) { //STATIC_ASSERT(exchange == 0); return InterlockedCompareExchangeT(destination, reinterpret_cast<T*>(exchange), comparand); } template <typename T> inline T* InterlockedCompareExchangeT( T* volatile * destination, T* exchange, std::nullptr_t comparand) // When nullptr is provided as argument. { //STATIC_ASSERT(comparand == 0); return InterlockedCompareExchangeT(destination, exchange, reinterpret_cast<T*>(comparand)); } #undef InterlockedExchangePointer #define InterlockedExchangePointer Use_InterlockedExchangeT #undef InterlockedCompareExchangePointer #define InterlockedCompareExchangePointer Use_InterlockedCompareExchangeT // Returns the directory for HMODULE. So, if HMODULE was for "C:\Dir1\Dir2\Filename.DLL", // then this would return "C:\Dir1\Dir2\" (note the trailing backslash). HRESULT GetHModuleDirectory(HMODULE hMod, __out_z __out_ecount(cchPath) LPWSTR wszPath, size_t cchPath); SString & GetHModuleDirectory(HMODULE hMod, SString &ssDir); HMODULE LoadLocalizedResourceDLLForSDK(_In_z_ LPCWSTR wzResourceDllName, _In_opt_z_ LPCWSTR modulePath=NULL, bool trySelf=true); // This is a slight variation that can be used for anything else typedef void* (__cdecl *LocalizedFileHandler)(LPCWSTR); void* FindLocalizedFile(_In_z_ LPCWSTR wzResourceDllName, LocalizedFileHandler lfh, _In_opt_z_ LPCWSTR modulePath=NULL); BOOL IsClrHostedLegacyComObject(REFCLSID rclsid); #if !defined(FEATURE_CORECLR) && !defined(CROSSGEN_COMPILE) // No utilcode code should use the global LoadLibraryShim anymore. UtilCode::LoadLibraryShim will do // the right thing based on whether the hosted or non-hosted utilcode is linked to. Using the global // LoadLibraryShim will result in a deprecated use warning. #ifdef SELF_NO_HOST #define LEGACY_ACTIVATION_SHIM_LOAD_LIBRARY WszLoadLibrary #include "legacyactivationshim.h" #include "mscoreepriv.h" namespace UtilCode { inline HRESULT LoadLibraryShim(LPCWSTR szDllName, LPCWSTR szVersion, LPVOID pvReserved, HMODULE *phModDll) { return LegacyActivationShim::LoadLibraryShim(szDllName, szVersion, pvReserved, phModDll); } }; #else // SELF_NO_HOST namespace UtilCode { // Hosted environment HRESULT LoadLibraryShim(LPCWSTR szDllName, LPCWSTR szVersion, LPVOID pvReserved, HMODULE *phModDll); }; #endif // SELF_NO_HOST #endif // !FEATURE_CORECLR && !CROSSGEN_COMPILE // Helper to support termination due to heap corruption // It's not supported on Win2K, so we have to manually delay load it void EnableTerminationOnHeapCorruption(); #if !defined(FEATURE_CORECLR) // On success, sets pwszProcessExePath (required) to full path to process EXE. HRESULT GetProcessExePath(LPCWSTR *pwszProcessExePath); #endif namespace Clr { namespace Util { // This api returns a pointer to a null-terminated string that contains the local appdata directory // or it returns NULL in the case that the directory could not be found. The return value from this function // is not actually checked for existence. HRESULT GetLocalAppDataDirectory(LPCWSTR *ppwzLocalAppDataDirectory); HRESULT SetLocalAppDataDirectory(LPCWSTR pwzLocalAppDataDirectory); namespace Reg { HRESULT ReadStringValue(HKEY hKey, LPCWSTR wszSubKey, LPCWSTR wszName, SString & ssValue); HRESULT ReadStringValue(HKEY hKey, LPCWSTR wszSubKey, LPCWSTR wszName, __deref_out __deref_out_z LPWSTR* pwszValue); } #ifdef FEATURE_COMINTEROP namespace Com { HRESULT FindServerUsingCLSID(REFCLSID rclsid, SString & ssServerName); HRESULT FindServerUsingCLSID(REFCLSID rclsid, __deref_out __deref_out_z LPWSTR* pwszServerName); HRESULT FindInprocServer32UsingCLSID(REFCLSID rclsid, SString & ssInprocServer32Name); HRESULT FindInprocServer32UsingCLSID(REFCLSID rclsid, __deref_out __deref_out_z LPWSTR* pwszInprocServer32Name); BOOL IsMscoreeInprocServer32(const SString & ssInprocServer32Name); BOOL CLSIDHasMscoreeAsInprocServer32(REFCLSID rclsid); } #endif // FEATURE_COMINTEROP namespace Win32 { static const WCHAR LONG_FILENAME_PREFIX_W[] = W("\\\\?\\"); static const CHAR LONG_FILENAME_PREFIX_A[] = "\\\\?\\"; void GetModuleFileName( HMODULE hModule, SString & ssFileName, bool fAllowLongFileNames = false); HRESULT GetModuleFileName( HMODULE hModule, __deref_out_z LPWSTR * pwszFileName, bool fAllowLongFileNames = false); void GetFullPathName( SString const & ssFileName, SString & ssPathName, DWORD * pdwFilePartIdx, bool fAllowLongFileNames = false); } }} #if defined(FEATURE_APPX) && !defined(DACCESS_COMPILE) // Forward declaration of AppX::IsAppXProcess namespace AppX { bool IsAppXProcess(); } // LOAD_WITH_ALTERED_SEARCH_PATH is unsupported in AppX processes. inline DWORD GetLoadWithAlteredSearchPathFlag() { WRAPPER_NO_CONTRACT; return AppX::IsAppXProcess() ? 0 : LOAD_WITH_ALTERED_SEARCH_PATH; } #else // FEATURE_APPX && !DACCESS_COMPILE // LOAD_WITH_ALTERED_SEARCH_PATH can be used unconditionally. inline DWORD GetLoadWithAlteredSearchPathFlag() { LIMITED_METHOD_CONTRACT; #ifdef LOAD_WITH_ALTERED_SEARCH_PATH return LOAD_WITH_ALTERED_SEARCH_PATH; #else return 0; #endif } #endif // FEATURE_APPX && !DACCESS_COMPILE // clr::SafeAddRef and clr::SafeRelease helpers. namespace clr { //================================================================================================================= template <typename ItfT> static inline typename std::enable_if< std::is_pointer<ItfT>::value, ItfT >::type SafeAddRef(ItfT pItf) { STATIC_CONTRACT_LIMITED_METHOD; if (pItf != nullptr) { pItf->AddRef(); } return pItf; } //================================================================================================================= template <typename ItfT> typename std::enable_if< std::is_pointer<ItfT>::value && std::is_reference<ItfT>::value, ULONG >::type SafeRelease(ItfT pItf) { STATIC_CONTRACT_LIMITED_METHOD; ULONG res = 0; if (pItf != nullptr) { res = pItf->Release(); pItf = nullptr; } return res; } //================================================================================================================= template <typename ItfT> typename std::enable_if< std::is_pointer<ItfT>::value && !std::is_reference<ItfT>::value, ULONG >::type SafeRelease(ItfT pItf) { STATIC_CONTRACT_LIMITED_METHOD; ULONG res = 0; if (pItf != nullptr) { res = pItf->Release(); } return res; } } // clr::SafeDelete namespace clr { //================================================================================================================= template <typename PtrT> static inline typename std::enable_if< std::is_pointer<PtrT>::value, PtrT >::type SafeDelete(PtrT & ptr) { STATIC_CONTRACT_LIMITED_METHOD; if (ptr != nullptr) { delete ptr; ptr = nullptr; } } } // ====================================================================================== // Spinning support (used by VM and by MetaData via file:..\Utilcode\UTSem.cpp) struct SpinConstants { DWORD dwInitialDuration; DWORD dwMaximumDuration; DWORD dwBackoffFactor; DWORD dwRepetitions; }; extern SpinConstants g_SpinConstants; // ====================================================================================== #endif // __UtilCode_h__
[ "31968192+bpm-ms@users.noreply.github.com" ]
31968192+bpm-ms@users.noreply.github.com
b40987720984e20e0aed88ff13e63ee689af4df3
a7f07e08264d9ad8b8090015516df342461dcae3
/string容器/string子串获取.cpp
c010e419ea84d1314de0b09d1b31a6b2165804a2
[]
no_license
luanyiping/cplusplus
4a973bb52d43777f8c0456c950bec20ec256953a
55d928dbb0d6a764d2040274580df2d30ddd09bb
refs/heads/main
2023-03-17T20:39:43.482391
2021-03-22T13:58:54
2021-03-22T13:58:54
323,602,831
0
0
null
null
null
null
UTF-8
C++
false
false
332
cpp
#include<iostream> #include<string> using namespace std; void test01() { string str = "abcdef"; string substr = str.substr(1, 3); cout << substr << endl; } void test02() { string email = "zhangsan@qq.com"; int pos = email.find("@"); string username = email.substr(0, pos); cout << username<< endl; } int main() { test01(); }
[ "3349244951@qq.com" ]
3349244951@qq.com
290ec2b140562f6e1bb734b675b7eecbe6676c8f
591e916e0f9823067a4ed632a771c5c4185513a5
/packages/node-fasttext/src/wrapper.h
d805e0a2f46295bca43f020a50b3f9b3a8528888
[ "MIT" ]
permissive
saurindashadia/nlu
39d02c51830e4ecd6a35abae29d7296f33a100fd
2bd043a4463b10d43e894a9fa770cf4150d3c23a
refs/heads/master
2023-07-29T15:05:07.306293
2021-09-13T20:49:02
2021-09-13T20:49:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,927
h
#ifndef WRAPPER_H #define WRAPPER_H // #include <time.h> #include <atomic> #include <memory> #include <set> #include <map> #include <mutex> #include "./fasttext_napi.h" #include "../fastText/src/fasttext.h" #include "../fastText/src/quantmatrix.h" using fasttext::Args; using fasttext::DenseMatrix; using fasttext::Dictionary; using fasttext::FastText; using fasttext::Model; using fasttext::QuantMatrix; using fasttext::real; using fasttext::Vector; struct PredictResult { std::string label; double value; }; class Wrapper { private: std::shared_ptr<Args> args_; std::shared_ptr<Dictionary> dict_; std::shared_ptr<Model> model_; DenseMatrix wordVectors_; FastTextNapi fastText_; // std::atomic<int64_t> tokenCount; // clock_t start; void signModel(std::ostream &); bool checkModel(std::istream &); std::vector<PredictResult> findNN(const Vector &, int32_t, const std::set<std::string> &); std::map<std::string, std::string> loadModel(std::istream &); bool quant_; std::string modelFilename_; std::mutex mtx_; std::mutex precomputeMtx_; bool isLoaded_; bool isPrecomputed_; bool isModelLoaded() { return isLoaded_; } bool fileExist(const std::string &filename); std::map<std::string, std::string> getModelInfo(); public: Wrapper(std::string modelFilename); void getVector(Vector &, const std::string &); std::vector<PredictResult> predict(std::string sentence, int32_t k); std::vector<PredictResult> nn(std::string query, int32_t k); std::vector<double> getWordVector(std::string query); std::map<std::string, std::string> train(const std::vector<std::string> args); std::map<std::string, std::string> quantize(const std::vector<std::string> args); void precomputeWordVectors(); std::map<std::string, std::string> loadModel(); std::map<std::string, std::string> loadModel(std::string filename); }; #endif
[ "francois_levasseur@hotmail.com" ]
francois_levasseur@hotmail.com
8c7cdd019b8167ea7b2c2a6133704ff69a87fea7
976004c9f4426106d7ca59db25755d4d574b8025
/algorithms/gaussian_processes/functions/draw_base.h
edf4a66e913a6c054f620463f68efc960893335d
[]
no_license
peterzxli/cvpp
18a90c23baaaa07a32b2aafdb25d6ae78a1768c0
3b73cfce99dc4b5908cd6cb7898ce5ef1e336dce
refs/heads/master
2022-12-05T07:23:20.488638
2020-08-11T20:08:10
2020-08-11T20:08:10
286,062,971
1
0
null
null
null
null
UTF-8
C++
false
false
1,840
h
#ifndef GP_DRAW_BASE_H #define GP_DRAW_BASE_H #include <cvpp/auxiliar/definitions.h> #include <cvpp/interfaces/cpplot.h> #include <cvpp/algorithms/gaussian_processes/models/base/gp_base_info.h> namespace cvpp { class DrawBase { protected: bool done; Matd Yz,Xy,lim_nlml,lim_errs; unsigned format,nr,nc; InfoGP* gp; CPPlot draw; Veci buffers; String title,nlml,rmse,nlpd; String mean[10],var[10]; public: DrawBase(); DrawBase( InfoGP* ); const bool input() { return draw.input(); } const void setFormat(); const void prepScreens( const bool& = false ); virtual const void prepBuffers(); virtual const void updateBuffers(); virtual const void improveBuffers(); virtual const void drawScreens(); virtual const void prepLML( const unsigned& ); virtual const void prepERR( const unsigned& ); virtual const void loopLocal( const SeqPts2d& , const SeqPts2d& ) {} virtual const void drawLMLbase( const unsigned& ); virtual const void drawERRbase( const unsigned& ); virtual const void drawTXT( const unsigned& ); virtual const void drawLML( const unsigned& ); virtual const void drawERR( const unsigned& ); virtual const void prepBuffersInput2D() {} virtual const void prepBuffersInput3D() {} virtual const void prepBuffersOutput(); virtual const void updateBuffersInput2D() {} virtual const void updateBuffersInput3D() {} virtual const void updateBuffersOutput(); virtual const void improveBuffersInput2D() {} virtual const void improveBuffersInput3D() {} virtual const void improveBuffersOutput(); virtual const void drawScreensInput2D() {} virtual const void drawScreensInput3D() {} virtual const void drawScreensOutput(); const void drawScreensExtras(); }; } #endif
[ "peterli@MacBook-Pro.local" ]
peterli@MacBook-Pro.local
13b638d291d03c4d15e0a1e8f1e0a2f3852351f7
5744e6f936ace66df924ac0e304baf0eef71f657
/src/moon/objects/Vehicle.h
164a9455cee1fbab44c09ffad9c888817aaf4e49
[]
no_license
minsulander/moon
c8cbff86c6f04f1d1fa2b19f76b871cdad08379b
2bc7531969f6268ae607c84bf2454e0c0d6705a5
refs/heads/master
2021-01-10T06:43:09.026487
2013-03-02T16:05:23
2013-03-02T16:05:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
474
h
#ifndef MOON_VEHICLE_H #define MOON_VEHICLE_H #include <moon/Export.h> #include <moonet/Player.h> namespace moon { /// \ingroup core objects /// @{ /// Interface class for vehicles class MOON_EXPORT Vehicle { public: Vehicle(); virtual void enter(); virtual void exit(); bool isOccupied() const; static Vehicle *current(); protected: virtual ~Vehicle(); static Vehicle* currentVehicle; moonet::Player *player; }; /// @} } #endif
[ "martin.insulander@coredination.net" ]
martin.insulander@coredination.net
14cb9f2eaab2b307c474e8c55dc37f764cfa0752
5ea96f4e6eb29b4d6e37c3b9a7187de356be40ef
/tensorflow/core/tfrt/saved_model/tests/saved_model_test.cc
59f5ef8351fc7e40e1e67b10b8c2c1a5c4de1442
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
yongtang/tensorflow
e79c4ef8da6b3f41bad2d4ec6543d9c162d12349
9c6b66cb3f474c8ea89e11efb6ce2842ed607abc
refs/heads/master
2023-03-09T20:09:05.923921
2023-03-09T18:11:39
2023-03-09T18:11:39
83,927,595
3
4
null
2017-08-05T15:38:25
2017-03-04T22:02:53
C++
UTF-8
C++
false
false
42,425
cc
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <algorithm> #include <cstdint> #include <iterator> #include <memory> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/resource_loader.h" #include "tensorflow/core/tfrt/fallback/cost_recorder.h" #include "tensorflow/core/tfrt/run_handler_thread_pool/run_handler_concurrent_work_queue.h" #include "tensorflow/core/tfrt/saved_model/saved_model_mira_impl.h" #include "tensorflow/core/tfrt/saved_model/saved_model_testutil.h" namespace tensorflow { namespace tfrt_stub { namespace { struct TestParams { bool enable_grappler = false; bool enable_lazy_loading = false; bool lazy_loading_use_graph_executor = false; }; class SavedModelTest : public ::testing::TestWithParam<TestParams> {}; TEST_P(SavedModelTest, BasicV1) { // SavedModel toy contains a graph of a single 'tf.AddV2' op. It is generated // using the following python code: // x = tf.placeholder(tf.int32, shape=(3)) // y = tf.compat.v1.get_variable(name='y', initializer=[1, 2, 3]) // r = tf.matmul(x, y) std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/toy_v1"); auto runtime = DefaultTfrtRuntime(/*num_threads=*/1); auto options = DefaultSavedModelOptions(runtime.get()); options.enable_lazy_loading = GetParam().enable_lazy_loading; options.lazy_loading_use_graph_executor = GetParam().lazy_loading_use_graph_executor; options.graph_execution_options.compile_options.enable_grappler = GetParam().enable_grappler; auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_CHECK_OK(saved_model.status()); // Set input 'x' to [[1, 1, 1]] std::vector<tensorflow::Tensor> inputs; inputs.push_back( CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1})); tfrt::SavedModel::RunOptions run_options; std::vector<tensorflow::Tensor> outputs; TF_ASSERT_OK((*saved_model)->Run(run_options, "toy", inputs, &outputs)); ASSERT_EQ(outputs.size(), 1); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), ::testing::ElementsAreArray({6})); } // Tests all the value combinations of `TestParams`. For readability, use // integers instead of booleans. INSTANTIATE_TEST_SUITE_P( SavedModelLiteTest, SavedModelTest, ::testing::Values( // The values below are for: // enable_grappler, enable_lazy_loading, lazy_loading_use_graph_executor TestParams{0, 0, 0}, TestParams{1, 0, 0}, TestParams{0, 1, 0}, TestParams{1, 1, 0}, TestParams{0, 1, 1}, TestParams{1, 1, 1})); TEST(SavedModelTest, BasicV2) { // SavedModel toy contains a graph of a single 'tf.AddV2' op. It is generated // using the following python code: // self.w = tf.Variable(tf.ones((3)), name='w') // r = tf.matmul(x, self.w) std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/toy_v2"); TFRTSavedModelTest test(saved_model_dir); // Set input 'x' to [[1, 1, 1]] std::vector<tensorflow::Tensor> inputs; inputs.emplace_back(tensorflow::DT_INT32, /*shape=*/tensorflow::TensorShape{1, 3}); auto flat = inputs.back().flat<int32_t>(); flat(0) = 1; flat(1) = 1; flat(2) = 1; std::vector<tensorflow::Tensor> outputs; TF_ASSERT_OK( test.GetSavedModel()->Run({}, "serving_default", inputs, &outputs)); ASSERT_EQ(outputs.size(), 1); auto& output = outputs[0]; ASSERT_EQ(output.NumElements(), 1); EXPECT_EQ(output.flat<int32_t>()(0), 6); } TEST(SavedModelTest, BasicInlineExecution) { // SavedModel toy contains a graph of a single 'tf.AddV2' op. It is generated // using the following python code: // self.w = tf.Variable(tf.ones((3)), name='w') // r = tf.matmul(x, self.w) std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/toy_v2"); auto runtime = DefaultTfrtRuntime(/*num_threads=*/1); runtime->SetCreateRequestQueueFn( [](int64_t) -> StatusOr<std::unique_ptr<WorkQueueInterface>> { return tensorflow::tfrt_stub::WrapDefaultWorkQueue( tfrt::CreateSingleThreadedWorkQueue()); }); auto options = DefaultSavedModelOptions(runtime.get()); TF_ASSERT_OK_AND_ASSIGN( auto saved_model, SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"})); // Set input 'x' to [[1, 1, 1]] std::vector<tensorflow::Tensor> inputs; inputs.emplace_back(tensorflow::DT_INT32, /*shape=*/tensorflow::TensorShape{1, 3}); auto flat = inputs.back().flat<int32_t>(); flat(0) = 1; flat(1) = 1; flat(2) = 1; std::vector<tensorflow::Tensor> outputs; TF_ASSERT_OK(saved_model->Run({}, "serving_default", inputs, &outputs)); ASSERT_EQ(outputs.size(), 1); auto& output = outputs[0]; ASSERT_EQ(output.NumElements(), 1); EXPECT_EQ(output.flat<int32_t>()(0), 6); } TEST(SavedModelTest, VariableOnTpu) { // A ReadVariableOp on 'TPU' would behave exactly the same as a ReadVariableOp // on 'CPU'. This is to be compatible with TF1 runtime. std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/variable_on_tpu"); auto runtime = DefaultTfrtRuntime(/*num_threads=*/1); auto options = DefaultSavedModelOptions(runtime.get()); auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_CHECK_OK(saved_model.status()); // Set input 'x' to [[1, 1, 1]] std::vector<tensorflow::Tensor> inputs; inputs.emplace_back(tensorflow::DT_INT32, /*shape=*/tensorflow::TensorShape{1, 3}); auto flat = inputs.back().flat<int32_t>(); flat(0) = 1; flat(1) = 1; flat(2) = 1; std::vector<tensorflow::Tensor> outputs; TF_ASSERT_OK((*saved_model)->Run({}, "serving_default", inputs, &outputs)); ASSERT_EQ(outputs.size(), 1); auto& output = outputs[0]; ASSERT_EQ(output.NumElements(), 1); EXPECT_EQ(output.flat<int32_t>()(0), 6); } std::vector<tensorflow::Tensor> CreateExpectedOutputs( const FunctionMetadata& function_metadata, const std::vector<std::pair<std::string, tensorflow::Tensor>>& named_outputs) { std::vector<tensorflow::Tensor> outputs; absl::flat_hash_map<std::string, tensorflow::Tensor> name_to_outputs; for (const auto& name_and_output : named_outputs) { name_to_outputs[name_and_output.first] = name_and_output.second; } for (const auto& name : function_metadata.GetOutputNames()) { outputs.push_back(name_to_outputs.at(name)); } return outputs; } TEST(SavedModelTest, RunMultipleSignatures) { // SavedModel toy contains a graph of a single 'tf.AddV2' op. It is generated // using the following python code: // x = tf.placeholder(tf.int32, shape=(3)) // y = tf.compat.v1.get_variable(name='y', initializer=[1, 2, 3]) // r = tf.matmul(x, y) std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/toy_v1"); auto runtime = DefaultTfrtRuntime(/*num_threads=*/1); auto options = DefaultSavedModelOptions(runtime.get()); auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_CHECK_OK(saved_model.status()); std::vector<tensorflow::Tensor> toy_inputs; toy_inputs.push_back(CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1})); std::vector<tensorflow::Tensor> another_toy_inputs; another_toy_inputs.push_back(CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{2, 2, 2})); std::vector<tensorflow::Tensor> yet_another_toy_inputs; yet_another_toy_inputs.push_back(CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{3, 3, 3})); // TODO(b/183220175): Construct `inputs` in place once `TenserHandle` is // copyable. std::vector<std::vector<tensorflow::Tensor>> inputs; inputs.push_back(std::move(toy_inputs)); inputs.push_back(std::move(another_toy_inputs)); inputs.push_back(std::move(yet_another_toy_inputs)); std::vector<std::vector<tensorflow::Tensor>> outputs; std::vector<std::string> names = {"toy", "another_toy", "yet_another_toy"}; TF_ASSERT_OK( (*saved_model) ->RunMultipleSignatures(/*run_options=*/{}, names, inputs, &outputs)); ASSERT_EQ(outputs.size(), 3); { auto toy_metadata = (*saved_model)->GetFunctionMetadata("toy"); ASSERT_TRUE(toy_metadata.has_value()); std::vector<std::pair<std::string, tensorflow::Tensor>> expected_toy_named_outputs; expected_toy_named_outputs.push_back( {"r1", CreateTfTensor<int32_t>(/*shape=*/{1}, /*data=*/{6})}); std::vector<tensorflow::Tensor> expected_toy_outputs = CreateExpectedOutputs(*toy_metadata, expected_toy_named_outputs); ASSERT_EQ(outputs[0].size(), 1); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0][0]), ::testing::ElementsAreArray( GetTfTensorData<int32_t>(expected_toy_outputs[0]))); } { auto another_toy_metadata = (*saved_model)->GetFunctionMetadata("another_toy"); ASSERT_TRUE(another_toy_metadata.has_value()); std::vector<std::pair<std::string, tensorflow::Tensor>> expected_another_toy_named_outputs; expected_another_toy_named_outputs.push_back( {"r21", CreateTfTensor<int32_t>(/*shape=*/{1}, /*data=*/{12})}); expected_another_toy_named_outputs.push_back( {"r22", CreateTfTensor<int32_t>(/*shape=*/{1}, /*data=*/{18})}); std::vector<tensorflow::Tensor> expected_another_toy_outputs = CreateExpectedOutputs(*another_toy_metadata, expected_another_toy_named_outputs); ASSERT_EQ(outputs[1].size(), 2); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[1][0]), ::testing::ElementsAreArray( GetTfTensorData<int32_t>(expected_another_toy_outputs[0]))); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[1][1]), ::testing::ElementsAreArray( GetTfTensorData<int32_t>(expected_another_toy_outputs[1]))); } { auto yet_another_toy_metadata = (*saved_model)->GetFunctionMetadata("yet_another_toy"); ASSERT_TRUE(yet_another_toy_metadata.has_value()); std::vector<std::pair<std::string, tensorflow::Tensor>> expected_yet_another_toy_named_outputs; expected_yet_another_toy_named_outputs.push_back( {"r31", CreateTfTensor<int32_t>(/*shape=*/{1}, /*data=*/{18})}); expected_yet_another_toy_named_outputs.push_back( {"r32", CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{21, 21, 21})}); expected_yet_another_toy_named_outputs.push_back( {"r33", CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{24, 24, 24})}); std::vector<tensorflow::Tensor> expected_yet_another_toy_outputs = CreateExpectedOutputs(*yet_another_toy_metadata, expected_yet_another_toy_named_outputs); ASSERT_EQ(outputs[2].size(), 3); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[2][0]), ::testing::ElementsAreArray(GetTfTensorData<int32_t>( expected_yet_another_toy_outputs[0]))); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[2][1]), ::testing::ElementsAreArray(GetTfTensorData<int32_t>( expected_yet_another_toy_outputs[1]))); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[2][2]), ::testing::ElementsAreArray(GetTfTensorData<int32_t>( expected_yet_another_toy_outputs[2]))); } } TEST(SavedModelTest, RunMultipleSignatures_OverlappingNodes) { // SavedModel toy contains a graph of a single 'tf.AddV2' op. It is generated // using the following python code: // x = tf.placeholder(tf.int32, shape=(3)) // y = tf.compat.v1.get_variable(name='y', initializer=[1, 2, 3]) // r = tf.matmul(x, y) std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/toy_v1"); auto runtime = DefaultTfrtRuntime(/*num_threads=*/1); auto options = DefaultSavedModelOptions(runtime.get()); auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_CHECK_OK(saved_model.status()); std::vector<std::vector<tensorflow::Tensor>> inputs = { {CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1})}, {CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1})}, {CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1})}}; std::vector<std::vector<tensorflow::Tensor>> outputs; std::vector<std::string> names = {"toy", "another_toy", "toy"}; TF_ASSERT_OK( (*saved_model) ->RunMultipleSignatures(/*run_options=*/{}, names, inputs, &outputs)); ASSERT_EQ(outputs.size(), 3); ASSERT_EQ(outputs[0].size(), 1); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0][0]), ::testing::ElementsAreArray({6})); { auto another_toy_metadata = (*saved_model)->GetFunctionMetadata("another_toy"); ASSERT_TRUE(another_toy_metadata.has_value()); std::vector<std::pair<std::string, tensorflow::Tensor>> expected_another_toy_named_outputs; expected_another_toy_named_outputs.push_back( {"r21", CreateTfTensor<int32_t>(/*shape=*/{1}, /*data=*/{6})}); expected_another_toy_named_outputs.push_back( {"r22", CreateTfTensor<int32_t>(/*shape=*/{1}, /*data=*/{12})}); std::vector<tensorflow::Tensor> expected_another_toy_outputs = CreateExpectedOutputs(*another_toy_metadata, expected_another_toy_named_outputs); ASSERT_EQ(outputs[1].size(), 2); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[1][0]), ::testing::ElementsAreArray( GetTfTensorData<int32_t>(expected_another_toy_outputs[0]))); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[1][1]), ::testing::ElementsAreArray( GetTfTensorData<int32_t>(expected_another_toy_outputs[1]))); } ASSERT_EQ(outputs[2].size(), 1); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[2][0]), ::testing::ElementsAreArray({6})); } class SavedModelRunByTensorNamesTest : public ::testing::Test { protected: void SetUp() override { // SavedModel toy contains a graph of a single 'tf.AddV2' op. It is // generated using the following python code: // x = tf.placeholder(tf.int32, shape=(3)) // y = tf.compat.v1.get_variable(name='y', initializer=[1, 2, 3]) // r = tf.matmul(x, y) auto saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/toy_v1"); runtime_ = DefaultTfrtRuntime(/*num_threads=*/1); auto options = DefaultSavedModelOptions(runtime_.get()); auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_CHECK_OK(saved_model.status()); saved_model_.reset(static_cast<SavedModelImpl*>(saved_model->release())); inputs_.push_back( std::make_pair("input1", CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1}))); inputs_.push_back( std::make_pair("input2", CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{2, 2, 2}))); inputs_.push_back( std::make_pair("input3", CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{3, 3, 3}))); } std::unique_ptr<tensorflow::tfrt_stub::Runtime> runtime_; std::unique_ptr<SavedModelImpl> saved_model_; std::vector<std::pair<std::string, tensorflow::Tensor>> inputs_; std::vector<std::string> output_tensor_names_{"result1", "result21", "result31"}; std::vector<std::string> target_node_names_{"result22", "result32"}; }; TEST_F(SavedModelRunByTensorNamesTest, Basic) { std::vector<tensorflow::Tensor> outputs; TF_ASSERT_OK(saved_model_->RunByTensorNames(/*run_options=*/{}, inputs_, output_tensor_names_, target_node_names_, &outputs)); ASSERT_EQ(outputs.size(), 3); // Check output "r1". EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), ::testing::ElementsAre(6)); // Check output "r21". EXPECT_THAT(GetTfTensorData<int32_t>(outputs[1]), ::testing::ElementsAre(12)); // Check output "r31". EXPECT_THAT(GetTfTensorData<int32_t>(outputs[2]), ::testing::ElementsAre(18)); } TEST_F(SavedModelRunByTensorNamesTest, NoTargetNodes) { std::vector<tensorflow::Tensor> outputs; TF_ASSERT_OK(saved_model_->RunByTensorNames( /*run_options=*/{}, inputs_, output_tensor_names_, /*target_node_names=*/{}, &outputs)); ASSERT_EQ(outputs.size(), 3); // Check output "r1". EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), ::testing::ElementsAre(6)); // Check output "r21". EXPECT_THAT(GetTfTensorData<int32_t>(outputs[1]), ::testing::ElementsAre(12)); // Check output "r31". EXPECT_THAT(GetTfTensorData<int32_t>(outputs[2]), ::testing::ElementsAre(18)); } TEST_F(SavedModelRunByTensorNamesTest, NoOutputNodes) { std::vector<tensorflow::Tensor> outputs; outputs.emplace_back(); // Test outputs is first cleared. TF_ASSERT_OK(saved_model_->RunByTensorNames( /*run_options=*/{}, inputs_, /*output_tensor_names=*/{}, target_node_names_, &outputs)); ASSERT_EQ(outputs.size(), 0); } TEST_F(SavedModelRunByTensorNamesTest, ShuffleInputsAndOutputs) { std::vector<std::pair<std::string, tensorflow::Tensor>> inputs = { {"input2", CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{4, 4, 4})}, {"input1", CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1})}, {"input3", CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{3, 3, 3})}, }; std::vector<std::string> output_tensor_names{"result22", "result1", "result31"}; std::vector<tensorflow::Tensor> outputs; TF_ASSERT_OK(saved_model_->RunByTensorNames( /*run_options=*/{}, inputs, output_tensor_names, {}, &outputs)); ASSERT_EQ(outputs.size(), 3); // Check output "r22". EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), ::testing::ElementsAre(30)); // Check output "r1". EXPECT_THAT(GetTfTensorData<int32_t>(outputs[1]), ::testing::ElementsAre(6)); // Check output "r31". EXPECT_THAT(GetTfTensorData<int32_t>(outputs[2]), ::testing::ElementsAre(18)); } TEST(SavedModelTest, CustomWorkQueue) { // SavedModel toy contains a graph of a single 'tf.AddV2' op. It is generated // using the following python code: // x = tf.placeholder(tf.int32, shape=(3)) // y = tf.compat.v1.get_variable(name='y', initializer=[1, 2, 3]) // r = tf.matmul(x, y) std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/toy_v1"); tfrt::tf::RunHandlerThreadWorkQueue::Options queue_options; queue_options.num_complementary_threads = 1; queue_options.num_main_threads = 1; queue_options.init_timeout_ms = 100; auto runtime = tensorflow::tfrt_stub::Runtime::Create( std::make_unique<tfrt::tf::RunHandlerThreadWorkQueue>(queue_options)); auto options = DefaultSavedModelOptions(runtime.get()); auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_CHECK_OK(saved_model.status()); // Set input 'x' to [[1, 1, 1]] std::vector<tensorflow::Tensor> inputs; inputs.push_back( CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1})); std::vector<tensorflow::Tensor> outputs; TF_ASSERT_OK((*saved_model)->Run({}, "toy", inputs, &outputs)); ASSERT_EQ(outputs.size(), 1); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), ::testing::ElementsAreArray({6})); // Run one more time to check per-request state is correct set up. outputs.clear(); TF_ASSERT_OK((*saved_model)->Run({}, "toy", inputs, &outputs)); ASSERT_EQ(outputs.size(), 1); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), ::testing::ElementsAreArray({6})); } // Verifies the savedmodel runs correctly with work queues specified in // RunOptions. TEST(SavedModelTest, RunOptionsWorkQueue) { // SavedModel toy contains a graph of a single 'tf.AddV2' op. It is generated // using the following python code: // x = tf.placeholder(tf.int32, shape=(3)) // y = tf.compat.v1.get_variable(name='y', initializer=[1, 2, 3]) // r = tf.matmul(x, y) std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/toy_v1"); auto runtime = tensorflow::tfrt_stub::Runtime::Create(/*num_inter_op_threads=*/4); auto options = DefaultSavedModelOptions(runtime.get()); auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_CHECK_OK(saved_model.status()); // Set input 'x' to [[1, 1, 1]] std::vector<tensorflow::Tensor> inputs; inputs.push_back( CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1})); std::vector<tensorflow::Tensor> outputs; tfrt::tf::RunHandlerThreadWorkQueue::Options queue_options; queue_options.num_complementary_threads = 1; queue_options.num_main_threads = 1; queue_options.init_timeout_ms = 100; tfrt::tf::RunHandlerThreadWorkQueue run_handler_queue(queue_options); tfrt::SavedModel::RunOptions run_options; run_options.work_queue = &run_handler_queue; TF_ASSERT_OK((*saved_model)->Run(run_options, "toy", inputs, &outputs)); ASSERT_EQ(outputs.size(), 1); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), ::testing::ElementsAreArray({6})); // Run one more time to check per-request state is correct set up. outputs.clear(); TF_ASSERT_OK((*saved_model)->Run(run_options, "toy", inputs, &outputs)); ASSERT_EQ(outputs.size(), 1); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), ::testing::ElementsAreArray({6})); } TEST(SavedModelTest, UseMira) { // SavedModel toy contains a graph of a single 'tf.AddV2' op. It is generated // using the following python code: // x = tf.placeholder(tf.int32, shape=(3)) // y = tf.compat.v1.get_variable(name='y', initializer=[1, 2, 3]) // r = tf.matmul(x, y) std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/toy_v1"); auto runtime = DefaultTfrtRuntime(/*num_threads=*/1); auto options = DefaultSavedModelOptions(runtime.get()); auto saved_model = SavedModelMiraImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_CHECK_OK(saved_model.status()); // Set input 'x' to [[1, 1, 1]] std::vector<tensorflow::Tensor> inputs; inputs.push_back( CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1})); tfrt::SavedModel::RunOptions run_options; std::vector<tensorflow::Tensor> outputs; TF_ASSERT_OK((*saved_model)->Run(run_options, "toy", inputs, &outputs)); ASSERT_EQ(outputs.size(), 1); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), ::testing::ElementsAreArray({6})); } TEST(SavedModelTest, FunctionMetadata) { // SavedModel toy contains a graph of a single 'tf.AddV2' op. It is generated // using the following python code: // x = tf.placeholder(tf.int32, shape=(3)) // y = tf.compat.v1.get_variable(name='y', initializer=[1, 2, 3]) // r = tf.matmul(x, y) std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/toy_v1"); TFRTSavedModelTest test(saved_model_dir); auto* saved_model = test.GetSavedModel(); auto function_metadata = saved_model->GetFunctionMetadata("toy"); ASSERT_TRUE(function_metadata.has_value()); EXPECT_THAT(function_metadata->GetInputNames(), ::testing::ElementsAreArray({"x1"})); EXPECT_THAT( function_metadata->GetInputSpecs(), ::testing::ElementsAreArray({TensorSpec(tensorflow::DT_INT32, {1, 3})})); EXPECT_THAT(function_metadata->GetOutputNames(), ::testing::ElementsAreArray({"r1"})); EXPECT_THAT(function_metadata->GetOutputSpecs(), // Shape inference disabled, thus we only match dtype. ::testing::ElementsAreArray({::testing::Field( &TensorSpec::dtype, tensorflow::DT_INT32)})); } TEST(SavedModelTest, WrongShape) { // SavedModel toy contains a graph of a single 'tf.AddV2' op. It is generated // using the following python code: // self.w = tf.Variable(tf.ones((3)), name='w') // r = tf.matmul(x, self.w) std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/toy_v2"); TFRTSavedModelTest test(saved_model_dir); // Set input 'x' to a wrong shape [[1, 1]] std::vector<tensorflow::Tensor> inputs; inputs.push_back(CreateTfTensor<int32_t>(/*shape=*/{1, 2}, /*data=*/{1, 1})); std::vector<tensorflow::Tensor> outputs; tfrt::SavedModel::RunOptions run_options; run_options.validate_input_specs = true; auto status = test.GetSavedModel()->Run(run_options, "serving_default", inputs, &outputs); ASSERT_FALSE(status.ok()); EXPECT_THAT(status.error_message(), ::testing::HasSubstr("input shape is wrong")); } TEST(SavedModelTest, RefTypeTensorInput) { // This test checks the loading does not fail for signatures with ref type // input/output. // // TODO(b/188580685): This is a short term workaround to skip signatures with // ref type input. We need to add correctness testing here for ref type inputs // once it is supported. std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/ref_type_tensor_input"); auto runtime = DefaultTfrtRuntime(/*num_threads=*/1); auto options = DefaultSavedModelOptions(runtime.get()); options.graph_execution_options.compile_options.enable_grappler = true; auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_ASSERT_OK(saved_model.status()); EXPECT_THAT( (*saved_model)->GetFunctionNames(), ::testing::UnorderedElementsAre( "non_ref", "__tf_saved_model_session_initializer_save/restore_all")); } TEST(SavedModelTest, HashTableAssetV1) { std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/" "hash_table_asset_v1"); auto runtime = DefaultTfrtRuntime(/*num_threads=*/1); auto options = DefaultSavedModelOptions(runtime.get()); options.graph_execution_options.compile_options.enable_grappler = true; options.graph_execution_options.compile_options.hoist_invariant_ops = true; auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_CHECK_OK(saved_model.status()); std::vector<tensorflow::Tensor> inputs; inputs.push_back(CreateTfStringTensor(/*shape=*/{}, /*data=*/{"cat"})); std::vector<tensorflow::Tensor> outputs; TF_ASSERT_OK((*saved_model)->Run({}, "serving_default", inputs, &outputs)); ASSERT_EQ(outputs.size(), 1); EXPECT_THAT(GetTfTensorData<int64_t>(outputs[0]), ::testing::ElementsAreArray({0})); } TEST(ControlFlowTest, CtrlFlow) { std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/if_v1"); TFRTSavedModelTest test(saved_model_dir); std::vector<int32_t> x_data = {-1}; std::vector<tensorflow::Tensor> inputs; inputs.push_back(CreateTfTensor<int32_t>( /*shape=*/{}, absl::MakeConstSpan(x_data))); std::vector<tensorflow::Tensor> outputs; TF_ASSERT_OK( test.GetSavedModel()->Run({}, "serving_default", inputs, &outputs)); ASSERT_EQ(outputs.size(), 1); auto function_metadata = test.GetSavedModel()->GetFunctionMetadata("serving_default"); ASSERT_TRUE(function_metadata.has_value()); tensorflow::Tensor x(tensorflow::DT_INT32, tensorflow::TensorShape({})); std::copy(std::begin(x_data), std::end(x_data), x.flat<int32_t>().data()); std::vector<tensorflow::Tensor> tf_inputs = {x}; std::vector<tensorflow::Tensor> tf_outputs; ComputeCurrentTFResult(saved_model_dir, /*signature_name=*/"serving_default", function_metadata->GetInputNames(), tf_inputs, function_metadata->GetOutputNames(), &tf_outputs); ASSERT_EQ(tf_outputs.size(), 1); EXPECT_THAT( GetTfTensorData<int32_t>(outputs[0]), ::testing::ElementsAreArray(std::vector<int32_t>( tf_outputs[0].flat<int32_t>().data(), tf_outputs[0].flat<int32_t>().data() + tf_outputs[0].NumElements()))); } TEST(SavedModelTest, ResourceGather) { std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/resource_gather_v1"); TFRTSavedModelTest test(saved_model_dir); std::vector<int32_t> x_data = {1}; std::vector<tensorflow::Tensor> inputs; inputs.push_back(CreateTfTensor<int32_t>( /*shape=*/{}, absl::MakeConstSpan(x_data))); std::vector<tensorflow::Tensor> outputs; TF_ASSERT_OK( test.GetSavedModel()->Run({}, "serving_default", inputs, &outputs)); ASSERT_EQ(outputs.size(), 1); auto function_metadata = test.GetSavedModel()->GetFunctionMetadata("serving_default"); ASSERT_TRUE(function_metadata.has_value()); tensorflow::Tensor x(tensorflow::DT_INT32, tensorflow::TensorShape({})); std::copy(std::begin(x_data), std::end(x_data), x.flat<int32_t>().data()); std::vector<tensorflow::Tensor> tf_inputs = {x}; std::vector<tensorflow::Tensor> tf_outputs; ComputeCurrentTFResult(saved_model_dir, /*signature_name=*/"serving_default", function_metadata->GetInputNames(), tf_inputs, function_metadata->GetOutputNames(), &tf_outputs); ASSERT_EQ(tf_outputs.size(), 1); EXPECT_THAT( GetTfTensorData<int32_t>(outputs[0]), ::testing::ElementsAreArray(std::vector<int32_t>( tf_outputs[0].flat<int32_t>().data(), tf_outputs[0].flat<int32_t>().data() + tf_outputs[0].NumElements()))); } TEST(SavedModelTest, DTypeCoverage) { std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/dtype_coverage_v1"); TFRTSavedModelTest test(saved_model_dir); std::vector<tensorflow::Tensor> inputs; std::vector<tensorflow::Tensor> outputs; TF_ASSERT_OK( test.GetSavedModel()->Run({}, "serving_default", inputs, &outputs)); ASSERT_EQ(outputs.size(), 16); auto function_metadata = test.GetSavedModel()->GetFunctionMetadata("serving_default"); ASSERT_TRUE(function_metadata.has_value()); std::vector<tensorflow::Tensor> tf_inputs; std::vector<tensorflow::Tensor> tf_outputs; ComputeCurrentTFResult(saved_model_dir, /*signature_name=*/"serving_default", function_metadata->GetInputNames(), tf_inputs, function_metadata->GetOutputNames(), &tf_outputs); ASSERT_EQ(tf_outputs.size(), 16); for (int i = 0; i < 16; ++i) { ExpectTensorEqual(outputs[i], tf_outputs[i]); } } TEST(SavedModelTest, Error) { std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/error_v1"); auto runtime = DefaultTfrtRuntime(/*num_threads=*/1); auto options = DefaultSavedModelOptions(runtime.get()); auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_ASSERT_OK(saved_model.status()); std::vector<tensorflow::Tensor> outputs; auto status = (*saved_model)->Run({}, "serving_default", {}, &outputs); ASSERT_FALSE(status.ok()); EXPECT_EQ(status.code(), absl::StatusCode::kInvalidArgument); EXPECT_TRUE(absl::StrContains( status.error_message(), "You must feed a value for placeholder tensor")); } struct PowTestParam { std::string path; bool run_placer_grappler_on_functions; }; class SavedModelPowTest : public ::testing::TestWithParam<PowTestParam> {}; TEST_P(SavedModelPowTest, Pow) { std::string saved_model_dir = tensorflow::GetDataDependencyFilepath(GetParam().path); auto runtime = DefaultTfrtRuntime(/*num_threads=*/1); auto options = DefaultSavedModelOptions(runtime.get()); options.graph_execution_options.compile_options.enable_grappler = true; options.graph_execution_options.enable_grappler_function_optimizer = true; options.graph_execution_options.run_placer_grappler_on_functions = GetParam().run_placer_grappler_on_functions; auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_CHECK_OK(saved_model.status()); std::vector<int32_t> data = {2}; std::vector<tensorflow::Tensor> inputs; inputs.push_back( CreateTfTensor<int32_t>(/*shape=*/{}, absl::MakeConstSpan(data))); std::vector<tensorflow::Tensor> outputs; TF_ASSERT_OK((*saved_model)->Run({}, "serving_default", inputs, &outputs)); ASSERT_EQ(outputs.size(), 1); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), ::testing::ElementsAre(8)); } INSTANTIATE_TEST_SUITE_P( SavedModelPowTest, SavedModelPowTest, ::testing::Values( PowTestParam{"tensorflow/core/tfrt/saved_model/tests/pow", false}, PowTestParam{"tensorflow/core/tfrt/saved_model/tests/pow_v2", false}, PowTestParam{"tensorflow/core/tfrt/saved_model/tests/pow_v2", true})); TEST(SavedModelPowTest, MapDataset) { std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/data"); auto runtime = DefaultTfrtRuntime(/*num_threads=*/1); auto options = DefaultSavedModelOptions(runtime.get()); options.graph_execution_options.compile_options.enable_grappler = true; auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_CHECK_OK(saved_model.status()); std::vector<int32_t> data = {2}; std::vector<tensorflow::Tensor> inputs; inputs.push_back( CreateTfTensor<int32_t>(/*shape=*/{}, absl::MakeConstSpan(data))); std::vector<tensorflow::Tensor> outputs; TF_ASSERT_OK((*saved_model)->Run({}, "serving_default", inputs, &outputs)); ASSERT_EQ(outputs.size(), 1); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), ::testing::ElementsAre(3)); } TEST(SavedModelTest, ControlFlowV1) { // This test checks that loading a savedmodel with V1 control flows works // properly. The current workflow requires functionalization on V1 control // flows and may insert extra functions. This test is to guard on errors due // to handling V1 control flows (eg. adding different functions with name // conflicts). std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/control_flow_v1"); auto runtime = DefaultTfrtRuntime(/*num_threads=*/1); auto options = DefaultSavedModelOptions(runtime.get()); options.graph_execution_options.compile_options.enable_grappler = true; auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_ASSERT_OK(saved_model.status()); } TEST(SavedModelTest, WhileLoopV1) { // This test checks that loading a savedmodel with V1 while works properly. // The current workflow applies functionalization which may change nodes in // the original graph. We insert additional nodes to prevent it from changing // fetch nodes. std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/while_v1"); auto runtime = DefaultTfrtRuntime(/*num_threads=*/1); auto options = DefaultSavedModelOptions(runtime.get()); options.graph_execution_options.compile_options.enable_grappler = true; // TODO(chky): Implement while op in MLRT. if (options.graph_execution_options.enable_mlrt) return; auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_ASSERT_OK(saved_model.status()); std::vector<int32_t> data = {0}; std::vector<tensorflow::Tensor> inputs; inputs.push_back( CreateTfTensor<int32_t>(/*shape=*/{}, absl::MakeConstSpan(data))); std::vector<tensorflow::Tensor> outputs; TF_ASSERT_OK((*saved_model)->Run({}, "serving_default", inputs, &outputs)); ASSERT_EQ(outputs.size(), 1); EXPECT_THAT(GetTfTensorData<int32_t>(outputs[0]), ::testing::ElementsAre(10)); } TEST(SavedModelTest, SparseTensorInput) { // This test checks the loading does not fail for signatures with sparse // input/output. // // TODO(b/184675681): This is a short term workaround to skip signatures with // sparse input. We need to add correctness testing here for sparse inputs // once it is supported. std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/sparse_tensor_input"); auto runtime = DefaultTfrtRuntime(/*num_threads=*/1); auto options = DefaultSavedModelOptions(runtime.get()); options.graph_execution_options.compile_options.enable_grappler = true; auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_ASSERT_OK(saved_model.status()); EXPECT_THAT((*saved_model)->GetFunctionNames(), ::testing::ElementsAre("dense")); } TEST(SavedModelTest, DeadlineExceeded) { // SavedModel toy contains a graph of a single 'tf.AddV2' op. It is generated // using the following python code: // x = tf.placeholder(tf.int32, shape=(3)) // y = tf.compat.v1.get_variable(name='y', initializer=[1, 2, 3]) // r = tf.matmul(x, y) std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/toy_v1"); auto runtime = DefaultTfrtRuntime(/*num_threads=*/1); auto options = DefaultSavedModelOptions(runtime.get()); // TODO(chky): Implement cancellation in MLRT. if (options.graph_execution_options.enable_mlrt) return; auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_CHECK_OK(saved_model.status()); // Set input 'x' to [[1, 1, 1]] std::vector<tensorflow::Tensor> inputs; inputs.push_back( CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1})); std::vector<tensorflow::Tensor> outputs; tfrt::SavedModel::RunOptions run_options; run_options.deadline = absl::ToChronoTime(absl::Now()); auto status = (*saved_model)->Run(run_options, "toy", inputs, &outputs); ASSERT_FALSE(status.ok()); EXPECT_THAT(status.error_message(), ::testing::HasSubstr("Deadline exceeded")); } TEST(SavedModelTest, DisableCompilation) { // SavedModel toy contains a graph of a single 'tf.AddV2' op. It is generated // using the following python code: // x = tf.placeholder(tf.int32, shape=(3)) // y = tf.compat.v1.get_variable(name='y', initializer=[1, 2, 3]) // r = tf.matmul(x, y) std::string saved_model_dir = tensorflow::GetDataDependencyFilepath( "tensorflow/core/tfrt/saved_model/tests/toy_v1"); auto runtime = DefaultTfrtRuntime(/*num_threads=*/1); auto options = DefaultSavedModelOptions(runtime.get()); options.enable_lazy_loading = true; auto saved_model = SavedModelImpl::LoadSavedModel(options, saved_model_dir, /*tags=*/{"serve"}); TF_CHECK_OK(saved_model.status()); // Set input 'x' to [[1, 1, 1]] std::vector<tensorflow::Tensor> inputs; inputs.push_back( CreateTfTensor<int32_t>(/*shape=*/{1, 3}, /*data=*/{1, 1, 1})); std::vector<tensorflow::Tensor> outputs; tfrt::SavedModel::RunOptions run_options; run_options.disable_compilation = true; auto status = (*saved_model)->Run(run_options, "toy", inputs, &outputs); ASSERT_FALSE(status.ok()); EXPECT_THAT( status.error_message(), ::testing::HasSubstr("GraphExecutor: compilation is disabled in " "execution but the compiled graph is not found")); run_options.disable_compilation = false; TF_ASSERT_OK((*saved_model)->Run(run_options, "toy", inputs, &outputs)); } } // namespace } // namespace tfrt_stub } // namespace tensorflow
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
0d4db91199dd6c8f166800b4872bc6d5c404e3c0
1245a46ba781efa23caf3220194944eaca5b30ac
/unique_fd.h
75822293844a208aad6ceeaed8091557407b141c
[ "MIT" ]
permissive
nliber/cool
bdf221bac85e0cfdb0b7cbb3893d7645ade8bf23
82e706f635e36dd3dbdde09fab425104d5b288d6
refs/heads/main
2023-08-17T10:41:45.740600
2023-07-25T22:03:23
2023-07-25T22:03:23
102,822,833
2
0
null
null
null
null
UTF-8
C++
false
false
1,201
h
#ifndef COOL_UNIQUE_FD_H_ #define COOL_UNIQUE_FD_H_ #include <unistd.h> namespace cool { class unique_fd; } int close(cool::unique_fd& that) noexcept; namespace cool { class unique_fd { public: constexpr explicit unique_fd(int fd = -1) noexcept : m_fd{fd} {} constexpr unique_fd(unique_fd&& that) noexcept : m_fd{that.m_fd} { that.m_fd = -1; } constexpr unique_fd& operator=(unique_fd&& that) noexcept { swap(*this, that); return *this; } ~unique_fd() noexcept { if (-1 != m_fd) close(m_fd); } constexpr int release() noexcept { int fd{m_fd}; m_fd = -1; return fd; } constexpr operator int() const noexcept { return m_fd; } constexpr int get() const noexcept { return m_fd; } friend int ::close(unique_fd& that) noexcept; constexpr friend void swap(unique_fd& l, unique_fd& r) noexcept { int fd{l.m_fd}; l.m_fd = r.m_fd; r.m_fd = fd; } private: int m_fd; }; } // cool namespace inline int close(cool::unique_fd& that) noexcept { int closed{close(that.m_fd)}; if (0 == closed) that.m_fd = -1; return closed; } #endif /* COOL_UNIQUE_FD_H_ */
[ "nevin@cplusplusguy.com" ]
nevin@cplusplusguy.com
922d65018a522782aa207635272839b503f249b6
301213d6cfc9749829aad30680901591ea1e1794
/ctphq/CtphqMdApi.cpp
e5766cdf2f102f7f8f6b4673db023047b6140bfe
[]
no_license
ssh352/ctphq_win32
eac2ad79c94cd0e4b21f14d24fe9b2bc83120a8c
9a20e9f436c89d516b34849b81d5ef723934e69c
refs/heads/master
2020-03-28T23:16:53.123289
2016-06-29T07:33:13
2016-06-29T07:33:13
null
0
0
null
null
null
null
GB18030
C++
false
false
3,817
cpp
#include <iostream> #include "CtphqMdApi.h" using namespace std; ///当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。 void CtphqMdApi::OnFrontConnected() { //user login CThostFtdcReqUserLoginField m_reqUserLogin; //Broker TThostFtdcBrokerIDType m_chBrokerID = "9999"; //userID TThostFtdcUserIDType m_UserID = "015809"; //password TThostFtdcPasswordKeyType m_Password = "12qwasZX"; strcpy_s(m_reqUserLogin.BrokerID, m_chBrokerID); strcpy_s(m_reqUserLogin.UserID, m_UserID); strcpy_s(m_reqUserLogin.Password, m_Password); m_pUserApi->ReqUserLogin(&m_reqUserLogin, 0); } ///当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。 ///@param nReason 错误原因 /// 0x1001 网络读失败 /// 0x1002 网络写失败 /// 0x2001 接收心跳超时 /// 0x2002 发送心跳失败 /// 0x2003 收到错误报文 void CtphqMdApi::OnFrontDisconnected(int nReason) { } ///心跳超时警告。当长时间未收到报文时,该方法被调用。 ///@param nTimeLapse 距离上次接收报文的时间 void CtphqMdApi::OnHeartBeatWarning(int nTimeLapse) { nTimeLapse = 5; } ///登录请求响应 void CtphqMdApi::OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { if (pRspInfo->ErrorID != 0) { cerr << "Failed to Login!" << endl; cerr << "Errorcode= " << pRspInfo->ErrorID << " Errormsg= " << pRspInfo->ErrorMsg << endl; cerr << "RequestID= " << nRequestID << " chain= " << bIsLast << endl; exit(-1); } else { cerr << "Login in OK:" <<" TradingDay= " << pRspUserLogin->TradingDay << endl; ///订阅行情。 ///@param ppInstrumentID 合约ID ///@param nCount 要订阅/退订行情的合约个数 ///@remark char *pInstrumentID[] = { "au1612","ag1612" }; int iCount = 2; m_pUserApi->SubscribeMarketData(pInstrumentID, iCount); ///退订行情。 ///@param ppInstrumentID 合约ID ///@param nCount 要订阅/退订行情的合约个数 ///@remark //m_pUserApi->UnSubscribeMarketData(pInstrumentID, iCount); } } ///登出请求响应 void CtphqMdApi::OnRspUserLogout(CThostFtdcUserLogoutField *pUserLogout, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { cerr << "GoodBye!" << pUserLogout->UserID << endl; } ///错误应答 void CtphqMdApi::OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { cout << "OnRspError! errorcode=" << pRspInfo->ErrorID << "errormsg=" << pRspInfo->ErrorMsg << "requestid=" << nRequestID << "chain=" << bIsLast << endl; cout << "出错啦!请检查" << endl; } ///订阅行情应答 void CtphqMdApi::OnRspSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { cerr << "OK " << pSpecificInstrument->InstrumentID << endl; } ///取消订阅行情应答 void CtphqMdApi::OnRspUnSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { cerr << "OVER " << pSpecificInstrument->InstrumentID << endl; } ///深度行情通知 void CtphqMdApi::OnRtnDepthMarketData(CThostFtdcDepthMarketDataField *pDepthMarketData) { cerr << pDepthMarketData->InstrumentID << " " << pDepthMarketData->LastPrice << " " << pDepthMarketData->Volume << " " << pDepthMarketData->OpenInterest << " " << pDepthMarketData->BidPrice1 << " " << pDepthMarketData->AskPrice1 << " " << pDepthMarketData->OpenPrice << " " << pDepthMarketData->HighestPrice << " " << pDepthMarketData->LowestPrice << " " << pDepthMarketData->TradingDay << " " << pDepthMarketData->UpdateTime << endl; }
[ "aiwengchen@126.com" ]
aiwengchen@126.com
e4dc16a6f169af653e2e878dc292eceeaae367f1
9d851f5315bce6e24c8adcf6d2d2b834f288d2b2
/chipyard/tools/chisel3/test_run_dir/FormattedAssertTester/202003062245529367103029593917087/VFormattedAssertTester__Trace.cpp
ab99a28dd50b42d98ce6648478a2e91d12c8a32c
[ "BSD-3-Clause" ]
permissive
ajis01/systolicMM
b9830b4b00cb7f68d49fb039a5a53c04dcaf3e60
d444d0b8cae525501911e8d3c8ad76dac7fb445c
refs/heads/master
2021-08-17T22:54:34.204694
2020-03-18T03:31:59
2020-03-18T03:31:59
247,648,431
0
1
null
2021-03-29T22:26:24
2020-03-16T08:27:34
C++
UTF-8
C++
false
false
1,361
cpp
// Verilated -*- C++ -*- // DESCRIPTION: Verilator output: Tracing implementation internals #include "verilated_vcd_c.h" #include "VFormattedAssertTester__Syms.h" //====================== void VFormattedAssertTester::traceChg(VerilatedVcd* vcdp, void* userthis, uint32_t code) { // Callback from vcd->dump() VFormattedAssertTester* t=(VFormattedAssertTester*)userthis; VFormattedAssertTester__Syms* __restrict vlSymsp = t->__VlSymsp; // Setup global symbol table if (vlSymsp->getClearActivity()) { t->traceChgThis (vlSymsp, vcdp, code); } } //====================== void VFormattedAssertTester::traceChgThis(VFormattedAssertTester__Syms* __restrict vlSymsp, VerilatedVcd* vcdp, uint32_t code) { VFormattedAssertTester* __restrict vlTOPp VL_ATTR_UNUSED = vlSymsp->TOPp; int c=code; if (0 && vcdp && c) {} // Prevent unused // Body { vlTOPp->traceChgThis__2(vlSymsp, vcdp, code); } // Final vlTOPp->__Vm_traceActivity = 0U; } void VFormattedAssertTester::traceChgThis__2(VFormattedAssertTester__Syms* __restrict vlSymsp, VerilatedVcd* vcdp, uint32_t code) { VFormattedAssertTester* __restrict vlTOPp VL_ATTR_UNUSED = vlSymsp->TOPp; int c=code; if (0 && vcdp && c) {} // Prevent unused // Body { vcdp->chgBit (c+1,(vlTOPp->clock)); vcdp->chgBit (c+2,(vlTOPp->reset)); } }
[ "ajithkumar.sreekumar94@gmail.com" ]
ajithkumar.sreekumar94@gmail.com
7ef77d982211236100cf28820b2c65e6d748ef37
332515cb827e57f3359cfe0562c5b91d711752df
/Application_UWP_WinRT/Generated Files/winrt/impl/Windows.UI.WebUI.0.h
1df021ed268817bbffea178c81e9eb974bb20841
[ "MIT" ]
permissive
GCourtney27/DX12-Simple-Xbox-Win32-Application
7c1f09abbfb768a1d5c2ab0d7ee9621f66ad85d5
4f0bc4a52aa67c90376f05146f2ebea92db1ec57
refs/heads/master
2023-02-19T06:54:18.923600
2021-01-24T08:18:19
2021-01-24T08:18:19
312,744,674
1
0
null
null
null
null
UTF-8
C++
false
false
68,933
h
// WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.201113.7 #ifndef WINRT_Windows_UI_WebUI_0_H #define WINRT_Windows_UI_WebUI_0_H WINRT_EXPORT namespace winrt::Windows::ApplicationModel { struct IEnteredBackgroundEventArgs; struct ILeavingBackgroundEventArgs; struct ISuspendingDeferral; struct ISuspendingEventArgs; struct ISuspendingOperation; } WINRT_EXPORT namespace winrt::Windows::ApplicationModel::Activation { struct IActivatedEventArgs; struct IAppointmentsProviderAddAppointmentActivatedEventArgs; struct IAppointmentsProviderRemoveAppointmentActivatedEventArgs; struct IAppointmentsProviderReplaceAppointmentActivatedEventArgs; struct IAppointmentsProviderShowAppointmentDetailsActivatedEventArgs; struct IAppointmentsProviderShowTimeFrameActivatedEventArgs; struct IBackgroundActivatedEventArgs; struct IBarcodeScannerPreviewActivatedEventArgs; struct ICachedFileUpdaterActivatedEventArgs; struct ICameraSettingsActivatedEventArgs; struct ICommandLineActivatedEventArgs; struct IContactCallActivatedEventArgs; struct IContactMapActivatedEventArgs; struct IContactMessageActivatedEventArgs; struct IContactPanelActivatedEventArgs; struct IContactPickerActivatedEventArgs; struct IContactPostActivatedEventArgs; struct IContactVideoCallActivatedEventArgs; struct IDeviceActivatedEventArgs; struct IDevicePairingActivatedEventArgs; struct IDialReceiverActivatedEventArgs; struct IFileActivatedEventArgs; struct IFileOpenPickerActivatedEventArgs; struct IFileOpenPickerContinuationEventArgs; struct IFileSavePickerActivatedEventArgs; struct IFileSavePickerContinuationEventArgs; struct IFolderPickerContinuationEventArgs; struct ILaunchActivatedEventArgs; struct ILockScreenActivatedEventArgs; struct ILockScreenCallActivatedEventArgs; struct IPrint3DWorkflowActivatedEventArgs; struct IPrintTaskSettingsActivatedEventArgs; struct IProtocolActivatedEventArgs; struct IProtocolForResultsActivatedEventArgs; struct IRestrictedLaunchActivatedEventArgs; struct ISearchActivatedEventArgs; struct IShareTargetActivatedEventArgs; struct IStartupTaskActivatedEventArgs; struct IToastNotificationActivatedEventArgs; struct IUserDataAccountProviderActivatedEventArgs; struct IVoiceCommandActivatedEventArgs; struct IWalletActionActivatedEventArgs; struct IWebAccountProviderActivatedEventArgs; struct IWebAuthenticationBrokerContinuationEventArgs; } WINRT_EXPORT namespace winrt::Windows::ApplicationModel::Core { enum class AppRestartFailureReason : int32_t; } WINRT_EXPORT namespace winrt::Windows::Foundation { struct Deferral; template <typename T> struct __declspec(empty_bases) EventHandler; struct EventRegistrationToken; template <typename TResult> struct __declspec(empty_bases) IAsyncOperation; template <typename TSender, typename TResult> struct __declspec(empty_bases) TypedEventHandler; struct Uri; } WINRT_EXPORT namespace winrt::Windows::System { struct User; } WINRT_EXPORT namespace winrt::Windows::UI::WebUI { enum class PrintContent : int32_t { AllPages = 0, CurrentPage = 1, CustomPageRange = 2, CurrentSelection = 3, }; struct IActivatedDeferral; struct IActivatedEventArgsDeferral; struct IActivatedOperation; struct IHtmlPrintDocumentSource; struct INewWebUIViewCreatedEventArgs; struct IWebUIActivationStatics; struct IWebUIActivationStatics2; struct IWebUIActivationStatics3; struct IWebUIActivationStatics4; struct IWebUIBackgroundTaskInstance; struct IWebUIBackgroundTaskInstanceStatics; struct IWebUINavigatedDeferral; struct IWebUINavigatedEventArgs; struct IWebUINavigatedOperation; struct IWebUIView; struct IWebUIViewStatics; struct ActivatedDeferral; struct ActivatedOperation; struct BackgroundActivatedEventArgs; struct EnteredBackgroundEventArgs; struct HtmlPrintDocumentSource; struct LeavingBackgroundEventArgs; struct NewWebUIViewCreatedEventArgs; struct SuspendingDeferral; struct SuspendingEventArgs; struct SuspendingOperation; struct WebUIApplication; struct WebUIAppointmentsProviderAddAppointmentActivatedEventArgs; struct WebUIAppointmentsProviderRemoveAppointmentActivatedEventArgs; struct WebUIAppointmentsProviderReplaceAppointmentActivatedEventArgs; struct WebUIAppointmentsProviderShowAppointmentDetailsActivatedEventArgs; struct WebUIAppointmentsProviderShowTimeFrameActivatedEventArgs; struct WebUIBackgroundTaskInstance; struct WebUIBackgroundTaskInstanceRuntimeClass; struct WebUIBarcodeScannerPreviewActivatedEventArgs; struct WebUICachedFileUpdaterActivatedEventArgs; struct WebUICameraSettingsActivatedEventArgs; struct WebUICommandLineActivatedEventArgs; struct WebUIContactCallActivatedEventArgs; struct WebUIContactMapActivatedEventArgs; struct WebUIContactMessageActivatedEventArgs; struct WebUIContactPanelActivatedEventArgs; struct WebUIContactPickerActivatedEventArgs; struct WebUIContactPostActivatedEventArgs; struct WebUIContactVideoCallActivatedEventArgs; struct WebUIDeviceActivatedEventArgs; struct WebUIDevicePairingActivatedEventArgs; struct WebUIDialReceiverActivatedEventArgs; struct WebUIFileActivatedEventArgs; struct WebUIFileOpenPickerActivatedEventArgs; struct WebUIFileOpenPickerContinuationEventArgs; struct WebUIFileSavePickerActivatedEventArgs; struct WebUIFileSavePickerContinuationEventArgs; struct WebUIFolderPickerContinuationEventArgs; struct WebUILaunchActivatedEventArgs; struct WebUILockScreenActivatedEventArgs; struct WebUILockScreenCallActivatedEventArgs; struct WebUILockScreenComponentActivatedEventArgs; struct WebUINavigatedDeferral; struct WebUINavigatedEventArgs; struct WebUINavigatedOperation; struct WebUIPrint3DWorkflowActivatedEventArgs; struct WebUIPrintTaskSettingsActivatedEventArgs; struct WebUIPrintWorkflowForegroundTaskActivatedEventArgs; struct WebUIProtocolActivatedEventArgs; struct WebUIProtocolForResultsActivatedEventArgs; struct WebUIRestrictedLaunchActivatedEventArgs; struct WebUISearchActivatedEventArgs; struct WebUIShareTargetActivatedEventArgs; struct WebUIStartupTaskActivatedEventArgs; struct WebUIToastNotificationActivatedEventArgs; struct WebUIUserDataAccountProviderActivatedEventArgs; struct WebUIView; struct WebUIVoiceCommandActivatedEventArgs; struct WebUIWalletActionActivatedEventArgs; struct WebUIWebAccountProviderActivatedEventArgs; struct WebUIWebAuthenticationBrokerContinuationEventArgs; struct ActivatedEventHandler; struct BackgroundActivatedEventHandler; struct EnteredBackgroundEventHandler; struct LeavingBackgroundEventHandler; struct NavigatedEventHandler; struct ResumingEventHandler; struct SuspendingEventHandler; } namespace winrt::impl { template <> struct category<Windows::UI::WebUI::IActivatedDeferral>{ using type = interface_category; }; template <> struct category<Windows::UI::WebUI::IActivatedEventArgsDeferral>{ using type = interface_category; }; template <> struct category<Windows::UI::WebUI::IActivatedOperation>{ using type = interface_category; }; template <> struct category<Windows::UI::WebUI::IHtmlPrintDocumentSource>{ using type = interface_category; }; template <> struct category<Windows::UI::WebUI::INewWebUIViewCreatedEventArgs>{ using type = interface_category; }; template <> struct category<Windows::UI::WebUI::IWebUIActivationStatics>{ using type = interface_category; }; template <> struct category<Windows::UI::WebUI::IWebUIActivationStatics2>{ using type = interface_category; }; template <> struct category<Windows::UI::WebUI::IWebUIActivationStatics3>{ using type = interface_category; }; template <> struct category<Windows::UI::WebUI::IWebUIActivationStatics4>{ using type = interface_category; }; template <> struct category<Windows::UI::WebUI::IWebUIBackgroundTaskInstance>{ using type = interface_category; }; template <> struct category<Windows::UI::WebUI::IWebUIBackgroundTaskInstanceStatics>{ using type = interface_category; }; template <> struct category<Windows::UI::WebUI::IWebUINavigatedDeferral>{ using type = interface_category; }; template <> struct category<Windows::UI::WebUI::IWebUINavigatedEventArgs>{ using type = interface_category; }; template <> struct category<Windows::UI::WebUI::IWebUINavigatedOperation>{ using type = interface_category; }; template <> struct category<Windows::UI::WebUI::IWebUIView>{ using type = interface_category; }; template <> struct category<Windows::UI::WebUI::IWebUIViewStatics>{ using type = interface_category; }; template <> struct category<Windows::UI::WebUI::ActivatedDeferral>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::ActivatedOperation>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::BackgroundActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::EnteredBackgroundEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::HtmlPrintDocumentSource>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::LeavingBackgroundEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::NewWebUIViewCreatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::SuspendingDeferral>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::SuspendingEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::SuspendingOperation>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIApplication>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIAppointmentsProviderAddAppointmentActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIAppointmentsProviderRemoveAppointmentActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIAppointmentsProviderReplaceAppointmentActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIAppointmentsProviderShowAppointmentDetailsActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIAppointmentsProviderShowTimeFrameActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIBackgroundTaskInstance>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIBackgroundTaskInstanceRuntimeClass>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIBarcodeScannerPreviewActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUICachedFileUpdaterActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUICameraSettingsActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUICommandLineActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIContactCallActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIContactMapActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIContactMessageActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIContactPanelActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIContactPickerActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIContactPostActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIContactVideoCallActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIDeviceActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIDevicePairingActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIDialReceiverActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIFileActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIFileOpenPickerActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIFileOpenPickerContinuationEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIFileSavePickerActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIFileSavePickerContinuationEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIFolderPickerContinuationEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUILaunchActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUILockScreenActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUILockScreenCallActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUILockScreenComponentActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUINavigatedDeferral>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUINavigatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUINavigatedOperation>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIPrint3DWorkflowActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIPrintTaskSettingsActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIPrintWorkflowForegroundTaskActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIProtocolActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIProtocolForResultsActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIRestrictedLaunchActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUISearchActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIShareTargetActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIStartupTaskActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIToastNotificationActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIUserDataAccountProviderActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIView>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIVoiceCommandActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIWalletActionActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIWebAccountProviderActivatedEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::WebUIWebAuthenticationBrokerContinuationEventArgs>{ using type = class_category; }; template <> struct category<Windows::UI::WebUI::PrintContent>{ using type = enum_category; }; template <> struct category<Windows::UI::WebUI::ActivatedEventHandler>{ using type = delegate_category; }; template <> struct category<Windows::UI::WebUI::BackgroundActivatedEventHandler>{ using type = delegate_category; }; template <> struct category<Windows::UI::WebUI::EnteredBackgroundEventHandler>{ using type = delegate_category; }; template <> struct category<Windows::UI::WebUI::LeavingBackgroundEventHandler>{ using type = delegate_category; }; template <> struct category<Windows::UI::WebUI::NavigatedEventHandler>{ using type = delegate_category; }; template <> struct category<Windows::UI::WebUI::ResumingEventHandler>{ using type = delegate_category; }; template <> struct category<Windows::UI::WebUI::SuspendingEventHandler>{ using type = delegate_category; }; template <> inline constexpr auto& name_v<Windows::UI::WebUI::ActivatedDeferral> = L"Windows.UI.WebUI.ActivatedDeferral"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::ActivatedOperation> = L"Windows.UI.WebUI.ActivatedOperation"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::BackgroundActivatedEventArgs> = L"Windows.UI.WebUI.BackgroundActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::EnteredBackgroundEventArgs> = L"Windows.UI.WebUI.EnteredBackgroundEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::HtmlPrintDocumentSource> = L"Windows.UI.WebUI.HtmlPrintDocumentSource"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::LeavingBackgroundEventArgs> = L"Windows.UI.WebUI.LeavingBackgroundEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::NewWebUIViewCreatedEventArgs> = L"Windows.UI.WebUI.NewWebUIViewCreatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::SuspendingDeferral> = L"Windows.UI.WebUI.SuspendingDeferral"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::SuspendingEventArgs> = L"Windows.UI.WebUI.SuspendingEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::SuspendingOperation> = L"Windows.UI.WebUI.SuspendingOperation"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIApplication> = L"Windows.UI.WebUI.WebUIApplication"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIAppointmentsProviderAddAppointmentActivatedEventArgs> = L"Windows.UI.WebUI.WebUIAppointmentsProviderAddAppointmentActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIAppointmentsProviderRemoveAppointmentActivatedEventArgs> = L"Windows.UI.WebUI.WebUIAppointmentsProviderRemoveAppointmentActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIAppointmentsProviderReplaceAppointmentActivatedEventArgs> = L"Windows.UI.WebUI.WebUIAppointmentsProviderReplaceAppointmentActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIAppointmentsProviderShowAppointmentDetailsActivatedEventArgs> = L"Windows.UI.WebUI.WebUIAppointmentsProviderShowAppointmentDetailsActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIAppointmentsProviderShowTimeFrameActivatedEventArgs> = L"Windows.UI.WebUI.WebUIAppointmentsProviderShowTimeFrameActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIBackgroundTaskInstance> = L"Windows.UI.WebUI.WebUIBackgroundTaskInstance"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIBackgroundTaskInstanceRuntimeClass> = L"Windows.UI.WebUI.WebUIBackgroundTaskInstanceRuntimeClass"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIBarcodeScannerPreviewActivatedEventArgs> = L"Windows.UI.WebUI.WebUIBarcodeScannerPreviewActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUICachedFileUpdaterActivatedEventArgs> = L"Windows.UI.WebUI.WebUICachedFileUpdaterActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUICameraSettingsActivatedEventArgs> = L"Windows.UI.WebUI.WebUICameraSettingsActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUICommandLineActivatedEventArgs> = L"Windows.UI.WebUI.WebUICommandLineActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIContactCallActivatedEventArgs> = L"Windows.UI.WebUI.WebUIContactCallActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIContactMapActivatedEventArgs> = L"Windows.UI.WebUI.WebUIContactMapActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIContactMessageActivatedEventArgs> = L"Windows.UI.WebUI.WebUIContactMessageActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIContactPanelActivatedEventArgs> = L"Windows.UI.WebUI.WebUIContactPanelActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIContactPickerActivatedEventArgs> = L"Windows.UI.WebUI.WebUIContactPickerActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIContactPostActivatedEventArgs> = L"Windows.UI.WebUI.WebUIContactPostActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIContactVideoCallActivatedEventArgs> = L"Windows.UI.WebUI.WebUIContactVideoCallActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIDeviceActivatedEventArgs> = L"Windows.UI.WebUI.WebUIDeviceActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIDevicePairingActivatedEventArgs> = L"Windows.UI.WebUI.WebUIDevicePairingActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIDialReceiverActivatedEventArgs> = L"Windows.UI.WebUI.WebUIDialReceiverActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIFileActivatedEventArgs> = L"Windows.UI.WebUI.WebUIFileActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIFileOpenPickerActivatedEventArgs> = L"Windows.UI.WebUI.WebUIFileOpenPickerActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIFileOpenPickerContinuationEventArgs> = L"Windows.UI.WebUI.WebUIFileOpenPickerContinuationEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIFileSavePickerActivatedEventArgs> = L"Windows.UI.WebUI.WebUIFileSavePickerActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIFileSavePickerContinuationEventArgs> = L"Windows.UI.WebUI.WebUIFileSavePickerContinuationEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIFolderPickerContinuationEventArgs> = L"Windows.UI.WebUI.WebUIFolderPickerContinuationEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUILaunchActivatedEventArgs> = L"Windows.UI.WebUI.WebUILaunchActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUILockScreenActivatedEventArgs> = L"Windows.UI.WebUI.WebUILockScreenActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUILockScreenCallActivatedEventArgs> = L"Windows.UI.WebUI.WebUILockScreenCallActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUILockScreenComponentActivatedEventArgs> = L"Windows.UI.WebUI.WebUILockScreenComponentActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUINavigatedDeferral> = L"Windows.UI.WebUI.WebUINavigatedDeferral"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUINavigatedEventArgs> = L"Windows.UI.WebUI.WebUINavigatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUINavigatedOperation> = L"Windows.UI.WebUI.WebUINavigatedOperation"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIPrint3DWorkflowActivatedEventArgs> = L"Windows.UI.WebUI.WebUIPrint3DWorkflowActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIPrintTaskSettingsActivatedEventArgs> = L"Windows.UI.WebUI.WebUIPrintTaskSettingsActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIPrintWorkflowForegroundTaskActivatedEventArgs> = L"Windows.UI.WebUI.WebUIPrintWorkflowForegroundTaskActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIProtocolActivatedEventArgs> = L"Windows.UI.WebUI.WebUIProtocolActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIProtocolForResultsActivatedEventArgs> = L"Windows.UI.WebUI.WebUIProtocolForResultsActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIRestrictedLaunchActivatedEventArgs> = L"Windows.UI.WebUI.WebUIRestrictedLaunchActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUISearchActivatedEventArgs> = L"Windows.UI.WebUI.WebUISearchActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIShareTargetActivatedEventArgs> = L"Windows.UI.WebUI.WebUIShareTargetActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIStartupTaskActivatedEventArgs> = L"Windows.UI.WebUI.WebUIStartupTaskActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIToastNotificationActivatedEventArgs> = L"Windows.UI.WebUI.WebUIToastNotificationActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIUserDataAccountProviderActivatedEventArgs> = L"Windows.UI.WebUI.WebUIUserDataAccountProviderActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIView> = L"Windows.UI.WebUI.WebUIView"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIVoiceCommandActivatedEventArgs> = L"Windows.UI.WebUI.WebUIVoiceCommandActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIWalletActionActivatedEventArgs> = L"Windows.UI.WebUI.WebUIWalletActionActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIWebAccountProviderActivatedEventArgs> = L"Windows.UI.WebUI.WebUIWebAccountProviderActivatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::WebUIWebAuthenticationBrokerContinuationEventArgs> = L"Windows.UI.WebUI.WebUIWebAuthenticationBrokerContinuationEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::PrintContent> = L"Windows.UI.WebUI.PrintContent"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::IActivatedDeferral> = L"Windows.UI.WebUI.IActivatedDeferral"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::IActivatedEventArgsDeferral> = L"Windows.UI.WebUI.IActivatedEventArgsDeferral"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::IActivatedOperation> = L"Windows.UI.WebUI.IActivatedOperation"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::IHtmlPrintDocumentSource> = L"Windows.UI.WebUI.IHtmlPrintDocumentSource"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::INewWebUIViewCreatedEventArgs> = L"Windows.UI.WebUI.INewWebUIViewCreatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::IWebUIActivationStatics> = L"Windows.UI.WebUI.IWebUIActivationStatics"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::IWebUIActivationStatics2> = L"Windows.UI.WebUI.IWebUIActivationStatics2"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::IWebUIActivationStatics3> = L"Windows.UI.WebUI.IWebUIActivationStatics3"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::IWebUIActivationStatics4> = L"Windows.UI.WebUI.IWebUIActivationStatics4"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::IWebUIBackgroundTaskInstance> = L"Windows.UI.WebUI.IWebUIBackgroundTaskInstance"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::IWebUIBackgroundTaskInstanceStatics> = L"Windows.UI.WebUI.IWebUIBackgroundTaskInstanceStatics"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::IWebUINavigatedDeferral> = L"Windows.UI.WebUI.IWebUINavigatedDeferral"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::IWebUINavigatedEventArgs> = L"Windows.UI.WebUI.IWebUINavigatedEventArgs"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::IWebUINavigatedOperation> = L"Windows.UI.WebUI.IWebUINavigatedOperation"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::IWebUIView> = L"Windows.UI.WebUI.IWebUIView"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::IWebUIViewStatics> = L"Windows.UI.WebUI.IWebUIViewStatics"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::ActivatedEventHandler> = L"Windows.UI.WebUI.ActivatedEventHandler"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::BackgroundActivatedEventHandler> = L"Windows.UI.WebUI.BackgroundActivatedEventHandler"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::EnteredBackgroundEventHandler> = L"Windows.UI.WebUI.EnteredBackgroundEventHandler"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::LeavingBackgroundEventHandler> = L"Windows.UI.WebUI.LeavingBackgroundEventHandler"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::NavigatedEventHandler> = L"Windows.UI.WebUI.NavigatedEventHandler"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::ResumingEventHandler> = L"Windows.UI.WebUI.ResumingEventHandler"; template <> inline constexpr auto& name_v<Windows::UI::WebUI::SuspendingEventHandler> = L"Windows.UI.WebUI.SuspendingEventHandler"; template <> inline constexpr guid guid_v<Windows::UI::WebUI::IActivatedDeferral>{ 0xC3BD1978,0xA431,0x49D8,{ 0xA7,0x6A,0x39,0x5A,0x4E,0x03,0xDC,0xF3 } }; // C3BD1978-A431-49D8-A76A-395A4E03DCF3 template <> inline constexpr guid guid_v<Windows::UI::WebUI::IActivatedEventArgsDeferral>{ 0xCA6D5F74,0x63C2,0x44A6,{ 0xB9,0x7B,0xD9,0xA0,0x3C,0x20,0xBC,0x9B } }; // CA6D5F74-63C2-44A6-B97B-D9A03C20BC9B template <> inline constexpr guid guid_v<Windows::UI::WebUI::IActivatedOperation>{ 0xB6A0B4BC,0xC6CA,0x42FD,{ 0x98,0x18,0x71,0x90,0x4E,0x45,0xFE,0xD7 } }; // B6A0B4BC-C6CA-42FD-9818-71904E45FED7 template <> inline constexpr guid guid_v<Windows::UI::WebUI::IHtmlPrintDocumentSource>{ 0xCEA6469A,0x0E05,0x467A,{ 0xAB,0xC9,0x36,0xEC,0x1D,0x4C,0xDC,0xB6 } }; // CEA6469A-0E05-467A-ABC9-36EC1D4CDCB6 template <> inline constexpr guid guid_v<Windows::UI::WebUI::INewWebUIViewCreatedEventArgs>{ 0xE8E1B216,0xBE2B,0x4C9E,{ 0x85,0xE7,0x08,0x31,0x43,0xEC,0x4B,0xE7 } }; // E8E1B216-BE2B-4C9E-85E7-083143EC4BE7 template <> inline constexpr guid guid_v<Windows::UI::WebUI::IWebUIActivationStatics>{ 0x351B86BD,0x43B3,0x482B,{ 0x85,0xDB,0x35,0xD8,0x7B,0x51,0x7A,0xD9 } }; // 351B86BD-43B3-482B-85DB-35D87B517AD9 template <> inline constexpr guid guid_v<Windows::UI::WebUI::IWebUIActivationStatics2>{ 0xC8E88696,0x4D78,0x4AA4,{ 0x8F,0x06,0x2A,0x9E,0xAD,0xC6,0xC4,0x0A } }; // C8E88696-4D78-4AA4-8F06-2A9EADC6C40A template <> inline constexpr guid guid_v<Windows::UI::WebUI::IWebUIActivationStatics3>{ 0x91ABB686,0x1AF5,0x4445,{ 0xB4,0x9F,0x94,0x59,0xF4,0x0F,0xC8,0xDE } }; // 91ABB686-1AF5-4445-B49F-9459F40FC8DE template <> inline constexpr guid guid_v<Windows::UI::WebUI::IWebUIActivationStatics4>{ 0x5E391429,0x183F,0x478D,{ 0x8A,0x25,0x67,0xF8,0x0D,0x03,0x93,0x5B } }; // 5E391429-183F-478D-8A25-67F80D03935B template <> inline constexpr guid guid_v<Windows::UI::WebUI::IWebUIBackgroundTaskInstance>{ 0x23F12C25,0xE2F7,0x4741,{ 0xBC,0x9C,0x39,0x45,0x95,0xDE,0x24,0xDC } }; // 23F12C25-E2F7-4741-BC9C-394595DE24DC template <> inline constexpr guid guid_v<Windows::UI::WebUI::IWebUIBackgroundTaskInstanceStatics>{ 0x9C7A5291,0x19AE,0x4CA3,{ 0xB9,0x4B,0xFE,0x4E,0xC7,0x44,0xA7,0x40 } }; // 9C7A5291-19AE-4CA3-B94B-FE4EC744A740 template <> inline constexpr guid guid_v<Windows::UI::WebUI::IWebUINavigatedDeferral>{ 0xD804204D,0x831F,0x46E2,{ 0xB4,0x32,0x3A,0xFC,0xE2,0x11,0xF9,0x62 } }; // D804204D-831F-46E2-B432-3AFCE211F962 template <> inline constexpr guid guid_v<Windows::UI::WebUI::IWebUINavigatedEventArgs>{ 0xA75841B8,0x2499,0x4030,{ 0xA6,0x9D,0x15,0xD2,0xD9,0xCF,0xE5,0x24 } }; // A75841B8-2499-4030-A69D-15D2D9CFE524 template <> inline constexpr guid guid_v<Windows::UI::WebUI::IWebUINavigatedOperation>{ 0x7A965F08,0x8182,0x4A89,{ 0xAB,0x67,0x84,0x92,0xE8,0x75,0x0D,0x4B } }; // 7A965F08-8182-4A89-AB67-8492E8750D4B template <> inline constexpr guid guid_v<Windows::UI::WebUI::IWebUIView>{ 0x6783F64F,0x52DA,0x4FD7,{ 0xBE,0x69,0x8E,0xF6,0x28,0x4B,0x42,0x3C } }; // 6783F64F-52DA-4FD7-BE69-8EF6284B423C template <> inline constexpr guid guid_v<Windows::UI::WebUI::IWebUIViewStatics>{ 0xB591E668,0x8E59,0x44F9,{ 0x88,0x03,0x1B,0x24,0xC9,0x14,0x9D,0x30 } }; // B591E668-8E59-44F9-8803-1B24C9149D30 template <> inline constexpr guid guid_v<Windows::UI::WebUI::ActivatedEventHandler>{ 0x50F1E730,0xC5D1,0x4B6B,{ 0x9A,0xDB,0x8A,0x11,0x75,0x6B,0xE2,0x9C } }; // 50F1E730-C5D1-4B6B-9ADB-8A11756BE29C template <> inline constexpr guid guid_v<Windows::UI::WebUI::BackgroundActivatedEventHandler>{ 0xEDB19FBB,0x0761,0x47CC,{ 0x9A,0x77,0x24,0xD7,0x07,0x29,0x65,0xCA } }; // EDB19FBB-0761-47CC-9A77-24D7072965CA template <> inline constexpr guid guid_v<Windows::UI::WebUI::EnteredBackgroundEventHandler>{ 0x2B09A173,0xB68E,0x4DEF,{ 0x88,0xC1,0x8D,0xE8,0x4E,0x5A,0xAB,0x2F } }; // 2B09A173-B68E-4DEF-88C1-8DE84E5AAB2F template <> inline constexpr guid guid_v<Windows::UI::WebUI::LeavingBackgroundEventHandler>{ 0x00B4CCD9,0x7A9C,0x4B6B,{ 0x9A,0xC4,0x13,0x47,0x4F,0x26,0x8B,0xC4 } }; // 00B4CCD9-7A9C-4B6B-9AC4-13474F268BC4 template <> inline constexpr guid guid_v<Windows::UI::WebUI::NavigatedEventHandler>{ 0x7AF46FE6,0x40CA,0x4E49,{ 0xA7,0xD6,0xDB,0xDB,0x33,0x0C,0xD1,0xA3 } }; // 7AF46FE6-40CA-4E49-A7D6-DBDB330CD1A3 template <> inline constexpr guid guid_v<Windows::UI::WebUI::ResumingEventHandler>{ 0x26599BA9,0xA22D,0x4806,{ 0xA7,0x28,0xAC,0xAD,0xC1,0xD0,0x75,0xFA } }; // 26599BA9-A22D-4806-A728-ACADC1D075FA template <> inline constexpr guid guid_v<Windows::UI::WebUI::SuspendingEventHandler>{ 0x509C429C,0x78E2,0x4883,{ 0xAB,0xC8,0x89,0x60,0xDC,0xDE,0x1B,0x5C } }; // 509C429C-78E2-4883-ABC8-8960DCDE1B5C template <> struct default_interface<Windows::UI::WebUI::ActivatedDeferral>{ using type = Windows::UI::WebUI::IActivatedDeferral; }; template <> struct default_interface<Windows::UI::WebUI::ActivatedOperation>{ using type = Windows::UI::WebUI::IActivatedOperation; }; template <> struct default_interface<Windows::UI::WebUI::BackgroundActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IBackgroundActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::EnteredBackgroundEventArgs>{ using type = Windows::ApplicationModel::IEnteredBackgroundEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::HtmlPrintDocumentSource>{ using type = Windows::UI::WebUI::IHtmlPrintDocumentSource; }; template <> struct default_interface<Windows::UI::WebUI::LeavingBackgroundEventArgs>{ using type = Windows::ApplicationModel::ILeavingBackgroundEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::NewWebUIViewCreatedEventArgs>{ using type = Windows::UI::WebUI::INewWebUIViewCreatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::SuspendingDeferral>{ using type = Windows::ApplicationModel::ISuspendingDeferral; }; template <> struct default_interface<Windows::UI::WebUI::SuspendingEventArgs>{ using type = Windows::ApplicationModel::ISuspendingEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::SuspendingOperation>{ using type = Windows::ApplicationModel::ISuspendingOperation; }; template <> struct default_interface<Windows::UI::WebUI::WebUIAppointmentsProviderAddAppointmentActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IAppointmentsProviderAddAppointmentActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIAppointmentsProviderRemoveAppointmentActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IAppointmentsProviderRemoveAppointmentActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIAppointmentsProviderReplaceAppointmentActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IAppointmentsProviderReplaceAppointmentActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIAppointmentsProviderShowAppointmentDetailsActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IAppointmentsProviderShowAppointmentDetailsActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIAppointmentsProviderShowTimeFrameActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IAppointmentsProviderShowTimeFrameActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIBackgroundTaskInstanceRuntimeClass>{ using type = Windows::UI::WebUI::IWebUIBackgroundTaskInstance; }; template <> struct default_interface<Windows::UI::WebUI::WebUIBarcodeScannerPreviewActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IBarcodeScannerPreviewActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUICachedFileUpdaterActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::ICachedFileUpdaterActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUICameraSettingsActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::ICameraSettingsActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUICommandLineActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::ICommandLineActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIContactCallActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IContactCallActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIContactMapActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IContactMapActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIContactMessageActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IContactMessageActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIContactPanelActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IContactPanelActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIContactPickerActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IContactPickerActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIContactPostActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IContactPostActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIContactVideoCallActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IContactVideoCallActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIDeviceActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IDeviceActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIDevicePairingActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IDevicePairingActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIDialReceiverActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IDialReceiverActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIFileActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IFileActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIFileOpenPickerActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IFileOpenPickerActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIFileOpenPickerContinuationEventArgs>{ using type = Windows::ApplicationModel::Activation::IFileOpenPickerContinuationEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIFileSavePickerActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IFileSavePickerActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIFileSavePickerContinuationEventArgs>{ using type = Windows::ApplicationModel::Activation::IFileSavePickerContinuationEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIFolderPickerContinuationEventArgs>{ using type = Windows::ApplicationModel::Activation::IFolderPickerContinuationEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUILaunchActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::ILaunchActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUILockScreenActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::ILockScreenActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUILockScreenCallActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::ILockScreenCallActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUILockScreenComponentActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUINavigatedDeferral>{ using type = Windows::UI::WebUI::IWebUINavigatedDeferral; }; template <> struct default_interface<Windows::UI::WebUI::WebUINavigatedEventArgs>{ using type = Windows::UI::WebUI::IWebUINavigatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUINavigatedOperation>{ using type = Windows::UI::WebUI::IWebUINavigatedOperation; }; template <> struct default_interface<Windows::UI::WebUI::WebUIPrint3DWorkflowActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IPrint3DWorkflowActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIPrintTaskSettingsActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IPrintTaskSettingsActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIPrintWorkflowForegroundTaskActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIProtocolActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IProtocolActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIProtocolForResultsActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IProtocolForResultsActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIRestrictedLaunchActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IRestrictedLaunchActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUISearchActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::ISearchActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIShareTargetActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IShareTargetActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIStartupTaskActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IStartupTaskActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIToastNotificationActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IToastNotificationActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIUserDataAccountProviderActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IUserDataAccountProviderActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIView>{ using type = Windows::UI::WebUI::IWebUIView; }; template <> struct default_interface<Windows::UI::WebUI::WebUIVoiceCommandActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IVoiceCommandActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIWalletActionActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IWalletActionActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIWebAccountProviderActivatedEventArgs>{ using type = Windows::ApplicationModel::Activation::IWebAccountProviderActivatedEventArgs; }; template <> struct default_interface<Windows::UI::WebUI::WebUIWebAuthenticationBrokerContinuationEventArgs>{ using type = Windows::ApplicationModel::Activation::IWebAuthenticationBrokerContinuationEventArgs; }; template <> struct abi<Windows::UI::WebUI::IActivatedDeferral> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall Complete() noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::IActivatedEventArgsDeferral> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_ActivatedOperation(void**) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::IActivatedOperation> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall GetDeferral(void**) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::IHtmlPrintDocumentSource> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_Content(int32_t*) noexcept = 0; virtual int32_t __stdcall put_Content(int32_t) noexcept = 0; virtual int32_t __stdcall get_LeftMargin(float*) noexcept = 0; virtual int32_t __stdcall put_LeftMargin(float) noexcept = 0; virtual int32_t __stdcall get_TopMargin(float*) noexcept = 0; virtual int32_t __stdcall put_TopMargin(float) noexcept = 0; virtual int32_t __stdcall get_RightMargin(float*) noexcept = 0; virtual int32_t __stdcall put_RightMargin(float) noexcept = 0; virtual int32_t __stdcall get_BottomMargin(float*) noexcept = 0; virtual int32_t __stdcall put_BottomMargin(float) noexcept = 0; virtual int32_t __stdcall get_EnableHeaderFooter(bool*) noexcept = 0; virtual int32_t __stdcall put_EnableHeaderFooter(bool) noexcept = 0; virtual int32_t __stdcall get_ShrinkToFit(bool*) noexcept = 0; virtual int32_t __stdcall put_ShrinkToFit(bool) noexcept = 0; virtual int32_t __stdcall get_PercentScale(float*) noexcept = 0; virtual int32_t __stdcall put_PercentScale(float) noexcept = 0; virtual int32_t __stdcall get_PageRange(void**) noexcept = 0; virtual int32_t __stdcall TrySetPageRange(void*, bool*) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::INewWebUIViewCreatedEventArgs> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_WebUIView(void**) noexcept = 0; virtual int32_t __stdcall get_ActivatedEventArgs(void**) noexcept = 0; virtual int32_t __stdcall get_HasPendingNavigate(bool*) noexcept = 0; virtual int32_t __stdcall GetDeferral(void**) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::IWebUIActivationStatics> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall add_Activated(void*, winrt::event_token*) noexcept = 0; virtual int32_t __stdcall remove_Activated(winrt::event_token) noexcept = 0; virtual int32_t __stdcall add_Suspending(void*, winrt::event_token*) noexcept = 0; virtual int32_t __stdcall remove_Suspending(winrt::event_token) noexcept = 0; virtual int32_t __stdcall add_Resuming(void*, winrt::event_token*) noexcept = 0; virtual int32_t __stdcall remove_Resuming(winrt::event_token) noexcept = 0; virtual int32_t __stdcall add_Navigated(void*, winrt::event_token*) noexcept = 0; virtual int32_t __stdcall remove_Navigated(winrt::event_token) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::IWebUIActivationStatics2> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall add_LeavingBackground(void*, winrt::event_token*) noexcept = 0; virtual int32_t __stdcall remove_LeavingBackground(winrt::event_token) noexcept = 0; virtual int32_t __stdcall add_EnteredBackground(void*, winrt::event_token*) noexcept = 0; virtual int32_t __stdcall remove_EnteredBackground(winrt::event_token) noexcept = 0; virtual int32_t __stdcall EnablePrelaunch(bool) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::IWebUIActivationStatics3> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall RequestRestartAsync(void*, void**) noexcept = 0; virtual int32_t __stdcall RequestRestartForUserAsync(void*, void*, void**) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::IWebUIActivationStatics4> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall add_NewWebUIViewCreated(void*, winrt::event_token*) noexcept = 0; virtual int32_t __stdcall remove_NewWebUIViewCreated(winrt::event_token) noexcept = 0; virtual int32_t __stdcall add_BackgroundActivated(void*, winrt::event_token*) noexcept = 0; virtual int32_t __stdcall remove_BackgroundActivated(winrt::event_token) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::IWebUIBackgroundTaskInstance> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_Succeeded(bool*) noexcept = 0; virtual int32_t __stdcall put_Succeeded(bool) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::IWebUIBackgroundTaskInstanceStatics> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_Current(void**) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::IWebUINavigatedDeferral> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall Complete() noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::IWebUINavigatedEventArgs> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_NavigatedOperation(void**) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::IWebUINavigatedOperation> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall GetDeferral(void**) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::IWebUIView> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_ApplicationViewId(int32_t*) noexcept = 0; virtual int32_t __stdcall add_Closed(void*, winrt::event_token*) noexcept = 0; virtual int32_t __stdcall remove_Closed(winrt::event_token) noexcept = 0; virtual int32_t __stdcall add_Activated(void*, winrt::event_token*) noexcept = 0; virtual int32_t __stdcall remove_Activated(winrt::event_token) noexcept = 0; virtual int32_t __stdcall get_IgnoreApplicationContentUriRulesNavigationRestrictions(bool*) noexcept = 0; virtual int32_t __stdcall put_IgnoreApplicationContentUriRulesNavigationRestrictions(bool) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::IWebUIViewStatics> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall CreateAsync(void**) noexcept = 0; virtual int32_t __stdcall CreateWithUriAsync(void*, void**) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::ActivatedEventHandler> { struct __declspec(novtable) type : unknown_abi { virtual int32_t __stdcall Invoke(void*, void*) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::BackgroundActivatedEventHandler> { struct __declspec(novtable) type : unknown_abi { virtual int32_t __stdcall Invoke(void*, void*) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::EnteredBackgroundEventHandler> { struct __declspec(novtable) type : unknown_abi { virtual int32_t __stdcall Invoke(void*, void*) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::LeavingBackgroundEventHandler> { struct __declspec(novtable) type : unknown_abi { virtual int32_t __stdcall Invoke(void*, void*) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::NavigatedEventHandler> { struct __declspec(novtable) type : unknown_abi { virtual int32_t __stdcall Invoke(void*, void*) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::ResumingEventHandler> { struct __declspec(novtable) type : unknown_abi { virtual int32_t __stdcall Invoke(void*) noexcept = 0; }; }; template <> struct abi<Windows::UI::WebUI::SuspendingEventHandler> { struct __declspec(novtable) type : unknown_abi { virtual int32_t __stdcall Invoke(void*, void*) noexcept = 0; }; }; template <typename D> struct consume_Windows_UI_WebUI_IActivatedDeferral { WINRT_IMPL_AUTO(void) Complete() const; }; template <> struct consume<Windows::UI::WebUI::IActivatedDeferral> { template <typename D> using type = consume_Windows_UI_WebUI_IActivatedDeferral<D>; }; template <typename D> struct consume_Windows_UI_WebUI_IActivatedEventArgsDeferral { [[nodiscard]] WINRT_IMPL_AUTO(Windows::UI::WebUI::ActivatedOperation) ActivatedOperation() const; }; template <> struct consume<Windows::UI::WebUI::IActivatedEventArgsDeferral> { template <typename D> using type = consume_Windows_UI_WebUI_IActivatedEventArgsDeferral<D>; }; template <typename D> struct consume_Windows_UI_WebUI_IActivatedOperation { WINRT_IMPL_AUTO(Windows::UI::WebUI::ActivatedDeferral) GetDeferral() const; }; template <> struct consume<Windows::UI::WebUI::IActivatedOperation> { template <typename D> using type = consume_Windows_UI_WebUI_IActivatedOperation<D>; }; template <typename D> struct consume_Windows_UI_WebUI_IHtmlPrintDocumentSource { [[nodiscard]] WINRT_IMPL_AUTO(Windows::UI::WebUI::PrintContent) Content() const; WINRT_IMPL_AUTO(void) Content(Windows::UI::WebUI::PrintContent const& value) const; [[nodiscard]] WINRT_IMPL_AUTO(float) LeftMargin() const; WINRT_IMPL_AUTO(void) LeftMargin(float value) const; [[nodiscard]] WINRT_IMPL_AUTO(float) TopMargin() const; WINRT_IMPL_AUTO(void) TopMargin(float value) const; [[nodiscard]] WINRT_IMPL_AUTO(float) RightMargin() const; WINRT_IMPL_AUTO(void) RightMargin(float value) const; [[nodiscard]] WINRT_IMPL_AUTO(float) BottomMargin() const; WINRT_IMPL_AUTO(void) BottomMargin(float value) const; [[nodiscard]] WINRT_IMPL_AUTO(bool) EnableHeaderFooter() const; WINRT_IMPL_AUTO(void) EnableHeaderFooter(bool value) const; [[nodiscard]] WINRT_IMPL_AUTO(bool) ShrinkToFit() const; WINRT_IMPL_AUTO(void) ShrinkToFit(bool value) const; [[nodiscard]] WINRT_IMPL_AUTO(float) PercentScale() const; WINRT_IMPL_AUTO(void) PercentScale(float scalePercent) const; [[nodiscard]] WINRT_IMPL_AUTO(hstring) PageRange() const; WINRT_IMPL_AUTO(bool) TrySetPageRange(param::hstring const& strPageRange) const; }; template <> struct consume<Windows::UI::WebUI::IHtmlPrintDocumentSource> { template <typename D> using type = consume_Windows_UI_WebUI_IHtmlPrintDocumentSource<D>; }; template <typename D> struct consume_Windows_UI_WebUI_INewWebUIViewCreatedEventArgs { [[nodiscard]] WINRT_IMPL_AUTO(Windows::UI::WebUI::WebUIView) WebUIView() const; [[nodiscard]] WINRT_IMPL_AUTO(Windows::ApplicationModel::Activation::IActivatedEventArgs) ActivatedEventArgs() const; [[nodiscard]] WINRT_IMPL_AUTO(bool) HasPendingNavigate() const; WINRT_IMPL_AUTO(Windows::Foundation::Deferral) GetDeferral() const; }; template <> struct consume<Windows::UI::WebUI::INewWebUIViewCreatedEventArgs> { template <typename D> using type = consume_Windows_UI_WebUI_INewWebUIViewCreatedEventArgs<D>; }; template <typename D> struct consume_Windows_UI_WebUI_IWebUIActivationStatics { WINRT_IMPL_AUTO(winrt::event_token) Activated(Windows::UI::WebUI::ActivatedEventHandler const& handler) const; using Activated_revoker = impl::event_revoker<Windows::UI::WebUI::IWebUIActivationStatics, &impl::abi_t<Windows::UI::WebUI::IWebUIActivationStatics>::remove_Activated>; [[nodiscard]] Activated_revoker Activated(auto_revoke_t, Windows::UI::WebUI::ActivatedEventHandler const& handler) const; WINRT_IMPL_AUTO(void) Activated(winrt::event_token const& token) const noexcept; WINRT_IMPL_AUTO(winrt::event_token) Suspending(Windows::UI::WebUI::SuspendingEventHandler const& handler) const; using Suspending_revoker = impl::event_revoker<Windows::UI::WebUI::IWebUIActivationStatics, &impl::abi_t<Windows::UI::WebUI::IWebUIActivationStatics>::remove_Suspending>; [[nodiscard]] Suspending_revoker Suspending(auto_revoke_t, Windows::UI::WebUI::SuspendingEventHandler const& handler) const; WINRT_IMPL_AUTO(void) Suspending(winrt::event_token const& token) const noexcept; WINRT_IMPL_AUTO(winrt::event_token) Resuming(Windows::UI::WebUI::ResumingEventHandler const& handler) const; using Resuming_revoker = impl::event_revoker<Windows::UI::WebUI::IWebUIActivationStatics, &impl::abi_t<Windows::UI::WebUI::IWebUIActivationStatics>::remove_Resuming>; [[nodiscard]] Resuming_revoker Resuming(auto_revoke_t, Windows::UI::WebUI::ResumingEventHandler const& handler) const; WINRT_IMPL_AUTO(void) Resuming(winrt::event_token const& token) const noexcept; WINRT_IMPL_AUTO(winrt::event_token) Navigated(Windows::UI::WebUI::NavigatedEventHandler const& handler) const; using Navigated_revoker = impl::event_revoker<Windows::UI::WebUI::IWebUIActivationStatics, &impl::abi_t<Windows::UI::WebUI::IWebUIActivationStatics>::remove_Navigated>; [[nodiscard]] Navigated_revoker Navigated(auto_revoke_t, Windows::UI::WebUI::NavigatedEventHandler const& handler) const; WINRT_IMPL_AUTO(void) Navigated(winrt::event_token const& token) const noexcept; }; template <> struct consume<Windows::UI::WebUI::IWebUIActivationStatics> { template <typename D> using type = consume_Windows_UI_WebUI_IWebUIActivationStatics<D>; }; template <typename D> struct consume_Windows_UI_WebUI_IWebUIActivationStatics2 { WINRT_IMPL_AUTO(winrt::event_token) LeavingBackground(Windows::UI::WebUI::LeavingBackgroundEventHandler const& handler) const; using LeavingBackground_revoker = impl::event_revoker<Windows::UI::WebUI::IWebUIActivationStatics2, &impl::abi_t<Windows::UI::WebUI::IWebUIActivationStatics2>::remove_LeavingBackground>; [[nodiscard]] LeavingBackground_revoker LeavingBackground(auto_revoke_t, Windows::UI::WebUI::LeavingBackgroundEventHandler const& handler) const; WINRT_IMPL_AUTO(void) LeavingBackground(winrt::event_token const& token) const noexcept; WINRT_IMPL_AUTO(winrt::event_token) EnteredBackground(Windows::UI::WebUI::EnteredBackgroundEventHandler const& handler) const; using EnteredBackground_revoker = impl::event_revoker<Windows::UI::WebUI::IWebUIActivationStatics2, &impl::abi_t<Windows::UI::WebUI::IWebUIActivationStatics2>::remove_EnteredBackground>; [[nodiscard]] EnteredBackground_revoker EnteredBackground(auto_revoke_t, Windows::UI::WebUI::EnteredBackgroundEventHandler const& handler) const; WINRT_IMPL_AUTO(void) EnteredBackground(winrt::event_token const& token) const noexcept; WINRT_IMPL_AUTO(void) EnablePrelaunch(bool value) const; }; template <> struct consume<Windows::UI::WebUI::IWebUIActivationStatics2> { template <typename D> using type = consume_Windows_UI_WebUI_IWebUIActivationStatics2<D>; }; template <typename D> struct consume_Windows_UI_WebUI_IWebUIActivationStatics3 { WINRT_IMPL_AUTO(Windows::Foundation::IAsyncOperation<Windows::ApplicationModel::Core::AppRestartFailureReason>) RequestRestartAsync(param::hstring const& launchArguments) const; WINRT_IMPL_AUTO(Windows::Foundation::IAsyncOperation<Windows::ApplicationModel::Core::AppRestartFailureReason>) RequestRestartForUserAsync(Windows::System::User const& user, param::hstring const& launchArguments) const; }; template <> struct consume<Windows::UI::WebUI::IWebUIActivationStatics3> { template <typename D> using type = consume_Windows_UI_WebUI_IWebUIActivationStatics3<D>; }; template <typename D> struct consume_Windows_UI_WebUI_IWebUIActivationStatics4 { WINRT_IMPL_AUTO(winrt::event_token) NewWebUIViewCreated(Windows::Foundation::EventHandler<Windows::UI::WebUI::NewWebUIViewCreatedEventArgs> const& handler) const; using NewWebUIViewCreated_revoker = impl::event_revoker<Windows::UI::WebUI::IWebUIActivationStatics4, &impl::abi_t<Windows::UI::WebUI::IWebUIActivationStatics4>::remove_NewWebUIViewCreated>; [[nodiscard]] NewWebUIViewCreated_revoker NewWebUIViewCreated(auto_revoke_t, Windows::Foundation::EventHandler<Windows::UI::WebUI::NewWebUIViewCreatedEventArgs> const& handler) const; WINRT_IMPL_AUTO(void) NewWebUIViewCreated(winrt::event_token const& token) const noexcept; WINRT_IMPL_AUTO(winrt::event_token) BackgroundActivated(Windows::UI::WebUI::BackgroundActivatedEventHandler const& handler) const; using BackgroundActivated_revoker = impl::event_revoker<Windows::UI::WebUI::IWebUIActivationStatics4, &impl::abi_t<Windows::UI::WebUI::IWebUIActivationStatics4>::remove_BackgroundActivated>; [[nodiscard]] BackgroundActivated_revoker BackgroundActivated(auto_revoke_t, Windows::UI::WebUI::BackgroundActivatedEventHandler const& handler) const; WINRT_IMPL_AUTO(void) BackgroundActivated(winrt::event_token const& token) const noexcept; }; template <> struct consume<Windows::UI::WebUI::IWebUIActivationStatics4> { template <typename D> using type = consume_Windows_UI_WebUI_IWebUIActivationStatics4<D>; }; template <typename D> struct consume_Windows_UI_WebUI_IWebUIBackgroundTaskInstance { [[nodiscard]] WINRT_IMPL_AUTO(bool) Succeeded() const; WINRT_IMPL_AUTO(void) Succeeded(bool succeeded) const; }; template <> struct consume<Windows::UI::WebUI::IWebUIBackgroundTaskInstance> { template <typename D> using type = consume_Windows_UI_WebUI_IWebUIBackgroundTaskInstance<D>; }; template <typename D> struct consume_Windows_UI_WebUI_IWebUIBackgroundTaskInstanceStatics { [[nodiscard]] WINRT_IMPL_AUTO(Windows::UI::WebUI::IWebUIBackgroundTaskInstance) Current() const; }; template <> struct consume<Windows::UI::WebUI::IWebUIBackgroundTaskInstanceStatics> { template <typename D> using type = consume_Windows_UI_WebUI_IWebUIBackgroundTaskInstanceStatics<D>; }; template <typename D> struct consume_Windows_UI_WebUI_IWebUINavigatedDeferral { WINRT_IMPL_AUTO(void) Complete() const; }; template <> struct consume<Windows::UI::WebUI::IWebUINavigatedDeferral> { template <typename D> using type = consume_Windows_UI_WebUI_IWebUINavigatedDeferral<D>; }; template <typename D> struct consume_Windows_UI_WebUI_IWebUINavigatedEventArgs { [[nodiscard]] WINRT_IMPL_AUTO(Windows::UI::WebUI::WebUINavigatedOperation) NavigatedOperation() const; }; template <> struct consume<Windows::UI::WebUI::IWebUINavigatedEventArgs> { template <typename D> using type = consume_Windows_UI_WebUI_IWebUINavigatedEventArgs<D>; }; template <typename D> struct consume_Windows_UI_WebUI_IWebUINavigatedOperation { WINRT_IMPL_AUTO(Windows::UI::WebUI::WebUINavigatedDeferral) GetDeferral() const; }; template <> struct consume<Windows::UI::WebUI::IWebUINavigatedOperation> { template <typename D> using type = consume_Windows_UI_WebUI_IWebUINavigatedOperation<D>; }; template <typename D> struct consume_Windows_UI_WebUI_IWebUIView { [[nodiscard]] WINRT_IMPL_AUTO(int32_t) ApplicationViewId() const; WINRT_IMPL_AUTO(winrt::event_token) Closed(Windows::Foundation::TypedEventHandler<Windows::UI::WebUI::WebUIView, Windows::Foundation::IInspectable> const& handler) const; using Closed_revoker = impl::event_revoker<Windows::UI::WebUI::IWebUIView, &impl::abi_t<Windows::UI::WebUI::IWebUIView>::remove_Closed>; [[nodiscard]] Closed_revoker Closed(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::UI::WebUI::WebUIView, Windows::Foundation::IInspectable> const& handler) const; WINRT_IMPL_AUTO(void) Closed(winrt::event_token const& token) const noexcept; WINRT_IMPL_AUTO(winrt::event_token) Activated(Windows::Foundation::TypedEventHandler<Windows::UI::WebUI::WebUIView, Windows::ApplicationModel::Activation::IActivatedEventArgs> const& handler) const; using Activated_revoker = impl::event_revoker<Windows::UI::WebUI::IWebUIView, &impl::abi_t<Windows::UI::WebUI::IWebUIView>::remove_Activated>; [[nodiscard]] Activated_revoker Activated(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::UI::WebUI::WebUIView, Windows::ApplicationModel::Activation::IActivatedEventArgs> const& handler) const; WINRT_IMPL_AUTO(void) Activated(winrt::event_token const& token) const noexcept; [[nodiscard]] WINRT_IMPL_AUTO(bool) IgnoreApplicationContentUriRulesNavigationRestrictions() const; WINRT_IMPL_AUTO(void) IgnoreApplicationContentUriRulesNavigationRestrictions(bool value) const; }; template <> struct consume<Windows::UI::WebUI::IWebUIView> { template <typename D> using type = consume_Windows_UI_WebUI_IWebUIView<D>; }; template <typename D> struct consume_Windows_UI_WebUI_IWebUIViewStatics { WINRT_IMPL_AUTO(Windows::Foundation::IAsyncOperation<Windows::UI::WebUI::WebUIView>) CreateAsync() const; WINRT_IMPL_AUTO(Windows::Foundation::IAsyncOperation<Windows::UI::WebUI::WebUIView>) CreateAsync(Windows::Foundation::Uri const& uri) const; }; template <> struct consume<Windows::UI::WebUI::IWebUIViewStatics> { template <typename D> using type = consume_Windows_UI_WebUI_IWebUIViewStatics<D>; }; } #endif
[ "garrett1168@outlook.com" ]
garrett1168@outlook.com
607a96dc6e2cddb3305a2588d1381001896a8246
d6efcfa0c1c1d644b01bf829eb40843297f38168
/include/utils/GraphicsUtils.h
28a7d3934a74a2b3c3b3b96334282f451015f9c8
[]
no_license
xiaopoooo/img-detective
9ccdfc610267ae475a642dae94f51033f53e940d
94a580f266f290e4c6f8a5223795315c3ded0a08
refs/heads/master
2021-01-16T19:04:17.225294
2013-06-01T18:13:42
2013-06-01T18:13:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
246
h
#pragma once #include "common/CommonInternal.h" namespace ImgDetective { namespace Utils { class Graphics { public: static Core::YCbCrColor RGBtoYCbCr(unsigned char r, unsigned char g, unsigned char b); }; } }
[ "tyutmanovmd@gmail.com" ]
tyutmanovmd@gmail.com
17720fc8b9dba3678dd2fb633ddac10eaba39096
cc13bdb0f445b8acf6bec24946fcfb5e854989b6
/Pods/abseil/absl/time/internal/cctz/include/cctz/civil_time_detail.h
4cde96f1aaf1043a0295211ad1e8bf475b81583e
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
devMEremenko/XcodeBenchmark
59eaf0f7d6cdaead6338511431489d9d2bf0bbb5
3aaaa6aa4400a20513dd4b6fdb372c48b8c9e772
refs/heads/master
2023-09-04T08:37:51.014081
2023-07-25T23:37:37
2023-07-25T23:37:37
288,524,849
2,335
346
MIT
2023-09-08T16:52:16
2020-08-18T17:47:47
Swift
UTF-8
C++
false
false
21,482
h
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef ABSL_TIME_INTERNAL_CCTZ_CIVIL_TIME_DETAIL_H_ #define ABSL_TIME_INTERNAL_CCTZ_CIVIL_TIME_DETAIL_H_ #include <cstdint> #include <limits> #include <ostream> #include <type_traits> #include "absl/base/config.h" // Disable constexpr support unless we are in C++14 mode. #if __cpp_constexpr >= 201304 || (defined(_MSC_VER) && _MSC_VER >= 1910) #define CONSTEXPR_D constexpr // data #define CONSTEXPR_F constexpr // function #define CONSTEXPR_M constexpr // member #else #define CONSTEXPR_D const #define CONSTEXPR_F inline #define CONSTEXPR_M #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace time_internal { namespace cctz { // Support years that at least span the range of 64-bit time_t values. using year_t = std::int_fast64_t; // Type alias that indicates an argument is not normalized (e.g., the // constructor parameters and operands/results of addition/subtraction). using diff_t = std::int_fast64_t; namespace detail { // Type aliases that indicate normalized argument values. using month_t = std::int_fast8_t; // [1:12] using day_t = std::int_fast8_t; // [1:31] using hour_t = std::int_fast8_t; // [0:23] using minute_t = std::int_fast8_t; // [0:59] using second_t = std::int_fast8_t; // [0:59] // Normalized civil-time fields: Y-M-D HH:MM:SS. struct fields { CONSTEXPR_M fields(year_t year, month_t month, day_t day, hour_t hour, minute_t minute, second_t second) : y(year), m(month), d(day), hh(hour), mm(minute), ss(second) {} std::int_least64_t y; std::int_least8_t m; std::int_least8_t d; std::int_least8_t hh; std::int_least8_t mm; std::int_least8_t ss; }; struct second_tag {}; struct minute_tag : second_tag {}; struct hour_tag : minute_tag {}; struct day_tag : hour_tag {}; struct month_tag : day_tag {}; struct year_tag : month_tag {}; //////////////////////////////////////////////////////////////////////// // Field normalization (without avoidable overflow). namespace impl { CONSTEXPR_F bool is_leap_year(year_t y) noexcept { return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0); } CONSTEXPR_F int year_index(year_t y, month_t m) noexcept { return (static_cast<int>((y + (m > 2)) % 400) + 400) % 400; } CONSTEXPR_F int days_per_century(year_t y, month_t m) noexcept { const int yi = year_index(y, m); return 36524 + (yi == 0 || yi > 300); } CONSTEXPR_F int days_per_4years(year_t y, month_t m) noexcept { const int yi = year_index(y, m); return 1460 + (yi == 0 || yi > 300 || (yi - 1) % 100 < 96); } CONSTEXPR_F int days_per_year(year_t y, month_t m) noexcept { return is_leap_year(y + (m > 2)) ? 366 : 365; } CONSTEXPR_F int days_per_month(year_t y, month_t m) noexcept { CONSTEXPR_D int k_days_per_month[1 + 12] = { -1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 // non leap year }; return k_days_per_month[m] + (m == 2 && is_leap_year(y)); } CONSTEXPR_F fields n_day(year_t y, month_t m, diff_t d, diff_t cd, hour_t hh, minute_t mm, second_t ss) noexcept { y += (cd / 146097) * 400; cd %= 146097; if (cd < 0) { y -= 400; cd += 146097; } y += (d / 146097) * 400; d = d % 146097 + cd; if (d > 0) { if (d > 146097) { y += 400; d -= 146097; } } else { if (d > -365) { // We often hit the previous year when stepping a civil time backwards, // so special case it to avoid counting up by 100/4/1-year chunks. y -= 1; d += days_per_year(y, m); } else { y -= 400; d += 146097; } } if (d > 365) { for (int n = days_per_century(y, m); d > n; n = days_per_century(y, m)) { d -= n; y += 100; } for (int n = days_per_4years(y, m); d > n; n = days_per_4years(y, m)) { d -= n; y += 4; } for (int n = days_per_year(y, m); d > n; n = days_per_year(y, m)) { d -= n; ++y; } } if (d > 28) { for (int n = days_per_month(y, m); d > n; n = days_per_month(y, m)) { d -= n; if (++m > 12) { ++y; m = 1; } } } return fields(y, m, static_cast<day_t>(d), hh, mm, ss); } CONSTEXPR_F fields n_mon(year_t y, diff_t m, diff_t d, diff_t cd, hour_t hh, minute_t mm, second_t ss) noexcept { if (m != 12) { y += m / 12; m %= 12; if (m <= 0) { y -= 1; m += 12; } } return n_day(y, static_cast<month_t>(m), d, cd, hh, mm, ss); } CONSTEXPR_F fields n_hour(year_t y, diff_t m, diff_t d, diff_t cd, diff_t hh, minute_t mm, second_t ss) noexcept { cd += hh / 24; hh %= 24; if (hh < 0) { cd -= 1; hh += 24; } return n_mon(y, m, d, cd, static_cast<hour_t>(hh), mm, ss); } CONSTEXPR_F fields n_min(year_t y, diff_t m, diff_t d, diff_t hh, diff_t ch, diff_t mm, second_t ss) noexcept { ch += mm / 60; mm %= 60; if (mm < 0) { ch -= 1; mm += 60; } return n_hour(y, m, d, hh / 24 + ch / 24, hh % 24 + ch % 24, static_cast<minute_t>(mm), ss); } CONSTEXPR_F fields n_sec(year_t y, diff_t m, diff_t d, diff_t hh, diff_t mm, diff_t ss) noexcept { // Optimization for when (non-constexpr) fields are already normalized. if (0 <= ss && ss < 60) { const second_t nss = static_cast<second_t>(ss); if (0 <= mm && mm < 60) { const minute_t nmm = static_cast<minute_t>(mm); if (0 <= hh && hh < 24) { const hour_t nhh = static_cast<hour_t>(hh); if (1 <= d && d <= 28 && 1 <= m && m <= 12) { const day_t nd = static_cast<day_t>(d); const month_t nm = static_cast<month_t>(m); return fields(y, nm, nd, nhh, nmm, nss); } return n_mon(y, m, d, 0, nhh, nmm, nss); } return n_hour(y, m, d, hh / 24, hh % 24, nmm, nss); } return n_min(y, m, d, hh, mm / 60, mm % 60, nss); } diff_t cm = ss / 60; ss %= 60; if (ss < 0) { cm -= 1; ss += 60; } return n_min(y, m, d, hh, mm / 60 + cm / 60, mm % 60 + cm % 60, static_cast<second_t>(ss)); } } // namespace impl //////////////////////////////////////////////////////////////////////// // Increments the indicated (normalized) field by "n". CONSTEXPR_F fields step(second_tag, fields f, diff_t n) noexcept { return impl::n_sec(f.y, f.m, f.d, f.hh, f.mm + n / 60, f.ss + n % 60); } CONSTEXPR_F fields step(minute_tag, fields f, diff_t n) noexcept { return impl::n_min(f.y, f.m, f.d, f.hh + n / 60, 0, f.mm + n % 60, f.ss); } CONSTEXPR_F fields step(hour_tag, fields f, diff_t n) noexcept { return impl::n_hour(f.y, f.m, f.d + n / 24, 0, f.hh + n % 24, f.mm, f.ss); } CONSTEXPR_F fields step(day_tag, fields f, diff_t n) noexcept { return impl::n_day(f.y, f.m, f.d, n, f.hh, f.mm, f.ss); } CONSTEXPR_F fields step(month_tag, fields f, diff_t n) noexcept { return impl::n_mon(f.y + n / 12, f.m + n % 12, f.d, 0, f.hh, f.mm, f.ss); } CONSTEXPR_F fields step(year_tag, fields f, diff_t n) noexcept { return fields(f.y + n, f.m, f.d, f.hh, f.mm, f.ss); } //////////////////////////////////////////////////////////////////////// namespace impl { // Returns (v * f + a) but avoiding intermediate overflow when possible. CONSTEXPR_F diff_t scale_add(diff_t v, diff_t f, diff_t a) noexcept { return (v < 0) ? ((v + 1) * f + a) - f : ((v - 1) * f + a) + f; } // Map a (normalized) Y/M/D to the number of days before/after 1970-01-01. // Probably overflows for years outside [-292277022656:292277026595]. CONSTEXPR_F diff_t ymd_ord(year_t y, month_t m, day_t d) noexcept { const diff_t eyear = (m <= 2) ? y - 1 : y; const diff_t era = (eyear >= 0 ? eyear : eyear - 399) / 400; const diff_t yoe = eyear - era * 400; const diff_t doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1; const diff_t doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; return era * 146097 + doe - 719468; } // Returns the difference in days between two normalized Y-M-D tuples. // ymd_ord() will encounter integer overflow given extreme year values, // yet the difference between two such extreme values may actually be // small, so we take a little care to avoid overflow when possible by // exploiting the 146097-day cycle. CONSTEXPR_F diff_t day_difference(year_t y1, month_t m1, day_t d1, year_t y2, month_t m2, day_t d2) noexcept { const diff_t a_c4_off = y1 % 400; const diff_t b_c4_off = y2 % 400; diff_t c4_diff = (y1 - a_c4_off) - (y2 - b_c4_off); diff_t delta = ymd_ord(a_c4_off, m1, d1) - ymd_ord(b_c4_off, m2, d2); if (c4_diff > 0 && delta < 0) { delta += 2 * 146097; c4_diff -= 2 * 400; } else if (c4_diff < 0 && delta > 0) { delta -= 2 * 146097; c4_diff += 2 * 400; } return (c4_diff / 400 * 146097) + delta; } } // namespace impl // Returns the difference between fields structs using the indicated unit. CONSTEXPR_F diff_t difference(year_tag, fields f1, fields f2) noexcept { return f1.y - f2.y; } CONSTEXPR_F diff_t difference(month_tag, fields f1, fields f2) noexcept { return impl::scale_add(difference(year_tag{}, f1, f2), 12, (f1.m - f2.m)); } CONSTEXPR_F diff_t difference(day_tag, fields f1, fields f2) noexcept { return impl::day_difference(f1.y, f1.m, f1.d, f2.y, f2.m, f2.d); } CONSTEXPR_F diff_t difference(hour_tag, fields f1, fields f2) noexcept { return impl::scale_add(difference(day_tag{}, f1, f2), 24, (f1.hh - f2.hh)); } CONSTEXPR_F diff_t difference(minute_tag, fields f1, fields f2) noexcept { return impl::scale_add(difference(hour_tag{}, f1, f2), 60, (f1.mm - f2.mm)); } CONSTEXPR_F diff_t difference(second_tag, fields f1, fields f2) noexcept { return impl::scale_add(difference(minute_tag{}, f1, f2), 60, f1.ss - f2.ss); } //////////////////////////////////////////////////////////////////////// // Aligns the (normalized) fields struct to the indicated field. CONSTEXPR_F fields align(second_tag, fields f) noexcept { return f; } CONSTEXPR_F fields align(minute_tag, fields f) noexcept { return fields{f.y, f.m, f.d, f.hh, f.mm, 0}; } CONSTEXPR_F fields align(hour_tag, fields f) noexcept { return fields{f.y, f.m, f.d, f.hh, 0, 0}; } CONSTEXPR_F fields align(day_tag, fields f) noexcept { return fields{f.y, f.m, f.d, 0, 0, 0}; } CONSTEXPR_F fields align(month_tag, fields f) noexcept { return fields{f.y, f.m, 1, 0, 0, 0}; } CONSTEXPR_F fields align(year_tag, fields f) noexcept { return fields{f.y, 1, 1, 0, 0, 0}; } //////////////////////////////////////////////////////////////////////// namespace impl { template <typename H> H AbslHashValueImpl(second_tag, H h, fields f) { return H::combine(std::move(h), f.y, f.m, f.d, f.hh, f.mm, f.ss); } template <typename H> H AbslHashValueImpl(minute_tag, H h, fields f) { return H::combine(std::move(h), f.y, f.m, f.d, f.hh, f.mm); } template <typename H> H AbslHashValueImpl(hour_tag, H h, fields f) { return H::combine(std::move(h), f.y, f.m, f.d, f.hh); } template <typename H> H AbslHashValueImpl(day_tag, H h, fields f) { return H::combine(std::move(h), f.y, f.m, f.d); } template <typename H> H AbslHashValueImpl(month_tag, H h, fields f) { return H::combine(std::move(h), f.y, f.m); } template <typename H> H AbslHashValueImpl(year_tag, H h, fields f) { return H::combine(std::move(h), f.y); } } // namespace impl //////////////////////////////////////////////////////////////////////// template <typename T> class civil_time { public: explicit CONSTEXPR_M civil_time(year_t y, diff_t m = 1, diff_t d = 1, diff_t hh = 0, diff_t mm = 0, diff_t ss = 0) noexcept : civil_time(impl::n_sec(y, m, d, hh, mm, ss)) {} CONSTEXPR_M civil_time() noexcept : f_{1970, 1, 1, 0, 0, 0} {} civil_time(const civil_time&) = default; civil_time& operator=(const civil_time&) = default; // Conversion between civil times of different alignment. Conversion to // a more precise alignment is allowed implicitly (e.g., day -> hour), // but conversion where information is discarded must be explicit // (e.g., second -> minute). template <typename U, typename S> using preserves_data = typename std::enable_if<std::is_base_of<U, S>::value>::type; template <typename U> CONSTEXPR_M civil_time(const civil_time<U>& ct, preserves_data<T, U>* = nullptr) noexcept : civil_time(ct.f_) {} template <typename U> explicit CONSTEXPR_M civil_time(const civil_time<U>& ct, preserves_data<U, T>* = nullptr) noexcept : civil_time(ct.f_) {} // Factories for the maximum/minimum representable civil_time. static CONSTEXPR_F civil_time(max)() { const auto max_year = (std::numeric_limits<std::int_least64_t>::max)(); return civil_time(max_year, 12, 31, 23, 59, 59); } static CONSTEXPR_F civil_time(min)() { const auto min_year = (std::numeric_limits<std::int_least64_t>::min)(); return civil_time(min_year, 1, 1, 0, 0, 0); } // Field accessors. Note: All but year() return an int. CONSTEXPR_M year_t year() const noexcept { return f_.y; } CONSTEXPR_M int month() const noexcept { return f_.m; } CONSTEXPR_M int day() const noexcept { return f_.d; } CONSTEXPR_M int hour() const noexcept { return f_.hh; } CONSTEXPR_M int minute() const noexcept { return f_.mm; } CONSTEXPR_M int second() const noexcept { return f_.ss; } // Assigning arithmetic. CONSTEXPR_M civil_time& operator+=(diff_t n) noexcept { f_ = step(T{}, f_, n); return *this; } CONSTEXPR_M civil_time& operator-=(diff_t n) noexcept { if (n != (std::numeric_limits<diff_t>::min)()) { f_ = step(T{}, f_, -n); } else { f_ = step(T{}, step(T{}, f_, -(n + 1)), 1); } return *this; } CONSTEXPR_M civil_time& operator++() noexcept { return *this += 1; } CONSTEXPR_M civil_time operator++(int) noexcept { const civil_time a = *this; ++*this; return a; } CONSTEXPR_M civil_time& operator--() noexcept { return *this -= 1; } CONSTEXPR_M civil_time operator--(int) noexcept { const civil_time a = *this; --*this; return a; } // Binary arithmetic operators. friend CONSTEXPR_F civil_time operator+(civil_time a, diff_t n) noexcept { return a += n; } friend CONSTEXPR_F civil_time operator+(diff_t n, civil_time a) noexcept { return a += n; } friend CONSTEXPR_F civil_time operator-(civil_time a, diff_t n) noexcept { return a -= n; } friend CONSTEXPR_F diff_t operator-(civil_time lhs, civil_time rhs) noexcept { return difference(T{}, lhs.f_, rhs.f_); } template <typename H> friend H AbslHashValue(H h, civil_time a) { return impl::AbslHashValueImpl(T{}, std::move(h), a.f_); } private: // All instantiations of this template are allowed to call the following // private constructor and access the private fields member. template <typename U> friend class civil_time; // The designated constructor that all others eventually call. explicit CONSTEXPR_M civil_time(fields f) noexcept : f_(align(T{}, f)) {} fields f_; }; // Disallows difference between differently aligned types. // auto n = civil_day(...) - civil_hour(...); // would be confusing. template <typename T, typename U> CONSTEXPR_F diff_t operator-(civil_time<T>, civil_time<U>) = delete; using civil_year = civil_time<year_tag>; using civil_month = civil_time<month_tag>; using civil_day = civil_time<day_tag>; using civil_hour = civil_time<hour_tag>; using civil_minute = civil_time<minute_tag>; using civil_second = civil_time<second_tag>; //////////////////////////////////////////////////////////////////////// // Relational operators that work with differently aligned objects. // Always compares all six fields. template <typename T1, typename T2> CONSTEXPR_F bool operator<(const civil_time<T1>& lhs, const civil_time<T2>& rhs) noexcept { return ( lhs.year() < rhs.year() || (lhs.year() == rhs.year() && (lhs.month() < rhs.month() || (lhs.month() == rhs.month() && (lhs.day() < rhs.day() || (lhs.day() == rhs.day() && (lhs.hour() < rhs.hour() || (lhs.hour() == rhs.hour() && (lhs.minute() < rhs.minute() || (lhs.minute() == rhs.minute() && (lhs.second() < rhs.second()))))))))))); } template <typename T1, typename T2> CONSTEXPR_F bool operator<=(const civil_time<T1>& lhs, const civil_time<T2>& rhs) noexcept { return !(rhs < lhs); } template <typename T1, typename T2> CONSTEXPR_F bool operator>=(const civil_time<T1>& lhs, const civil_time<T2>& rhs) noexcept { return !(lhs < rhs); } template <typename T1, typename T2> CONSTEXPR_F bool operator>(const civil_time<T1>& lhs, const civil_time<T2>& rhs) noexcept { return rhs < lhs; } template <typename T1, typename T2> CONSTEXPR_F bool operator==(const civil_time<T1>& lhs, const civil_time<T2>& rhs) noexcept { return lhs.year() == rhs.year() && lhs.month() == rhs.month() && lhs.day() == rhs.day() && lhs.hour() == rhs.hour() && lhs.minute() == rhs.minute() && lhs.second() == rhs.second(); } template <typename T1, typename T2> CONSTEXPR_F bool operator!=(const civil_time<T1>& lhs, const civil_time<T2>& rhs) noexcept { return !(lhs == rhs); } //////////////////////////////////////////////////////////////////////// enum class weekday { monday, tuesday, wednesday, thursday, friday, saturday, sunday, }; CONSTEXPR_F weekday get_weekday(const civil_second& cs) noexcept { CONSTEXPR_D weekday k_weekday_by_mon_off[13] = { weekday::monday, weekday::tuesday, weekday::wednesday, weekday::thursday, weekday::friday, weekday::saturday, weekday::sunday, weekday::monday, weekday::tuesday, weekday::wednesday, weekday::thursday, weekday::friday, weekday::saturday, }; CONSTEXPR_D int k_weekday_offsets[1 + 12] = { -1, 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4, }; year_t wd = 2400 + (cs.year() % 400) - (cs.month() < 3); wd += wd / 4 - wd / 100 + wd / 400; wd += k_weekday_offsets[cs.month()] + cs.day(); return k_weekday_by_mon_off[wd % 7 + 6]; } //////////////////////////////////////////////////////////////////////// CONSTEXPR_F civil_day next_weekday(civil_day cd, weekday wd) noexcept { CONSTEXPR_D weekday k_weekdays_forw[14] = { weekday::monday, weekday::tuesday, weekday::wednesday, weekday::thursday, weekday::friday, weekday::saturday, weekday::sunday, weekday::monday, weekday::tuesday, weekday::wednesday, weekday::thursday, weekday::friday, weekday::saturday, weekday::sunday, }; weekday base = get_weekday(cd); for (int i = 0;; ++i) { if (base == k_weekdays_forw[i]) { for (int j = i + 1;; ++j) { if (wd == k_weekdays_forw[j]) { return cd + (j - i); } } } } } CONSTEXPR_F civil_day prev_weekday(civil_day cd, weekday wd) noexcept { CONSTEXPR_D weekday k_weekdays_back[14] = { weekday::sunday, weekday::saturday, weekday::friday, weekday::thursday, weekday::wednesday, weekday::tuesday, weekday::monday, weekday::sunday, weekday::saturday, weekday::friday, weekday::thursday, weekday::wednesday, weekday::tuesday, weekday::monday, }; weekday base = get_weekday(cd); for (int i = 0;; ++i) { if (base == k_weekdays_back[i]) { for (int j = i + 1;; ++j) { if (wd == k_weekdays_back[j]) { return cd - (j - i); } } } } } CONSTEXPR_F int get_yearday(const civil_second& cs) noexcept { CONSTEXPR_D int k_month_offsets[1 + 12] = { -1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, }; const int feb29 = (cs.month() > 2 && impl::is_leap_year(cs.year())); return k_month_offsets[cs.month()] + feb29 + cs.day(); } //////////////////////////////////////////////////////////////////////// std::ostream& operator<<(std::ostream& os, const civil_year& y); std::ostream& operator<<(std::ostream& os, const civil_month& m); std::ostream& operator<<(std::ostream& os, const civil_day& d); std::ostream& operator<<(std::ostream& os, const civil_hour& h); std::ostream& operator<<(std::ostream& os, const civil_minute& m); std::ostream& operator<<(std::ostream& os, const civil_second& s); std::ostream& operator<<(std::ostream& os, weekday wd); } // namespace detail } // namespace cctz } // namespace time_internal ABSL_NAMESPACE_END } // namespace absl #undef CONSTEXPR_M #undef CONSTEXPR_F #undef CONSTEXPR_D #endif // ABSL_TIME_INTERNAL_CCTZ_CIVIL_TIME_DETAIL_H_
[ "devMEremenko@gmail.com" ]
devMEremenko@gmail.com
93df898adcd82c0c7d1056febd2a5dc8df72e1d8
6c5e29ec7df00f789cdb47d0abe2aa06a03c53de
/Codeforces/208/E/E.cpp
3e59404d5368a5d2f953be4ae3468c9cda49c08a
[]
no_license
alexkats/Code
5293ef19805379fceaac529556fc1f0b74f416bf
1468352c86985b8aa86d6782a42c187578c3d6db
refs/heads/master
2021-05-04T10:47:48.235424
2017-10-19T12:18:38
2017-10-19T12:18:38
45,812,032
0
0
null
null
null
null
UTF-8
C++
false
false
736
cpp
#include <iostream> #include <fstream> #include <string> #include <cstring> #include <cmath> #include <cstdio> #include <cstdlib> #include <vector> #include <algorithm> #include <set> #include <map> #include <cassert> #include <ctime> #include <stack> #include <queue> #include <deque> #include <utility> #include <iterator> #define NAME "" #define INF 1000000000 #define EPS 0.000000001 #define sqr(a) a*a #define mp make_pair #define pb push_back #define rep(i,n) (for (int i = 0; i < n; i++)) typedef unsigned long long ull; typedef long long ll; typedef long double ld; using namespace std; int main () { freopen (NAME".in", "r", stdin); freopen (NAME".out", "w", stdout); return 0; }
[ "alex2007508@gmail.com" ]
alex2007508@gmail.com
096cd69fa863b710db34036130a0eba7a5fd9155
248d53d54f3781c01880dfd40688f6fb73ac29a6
/caq/cppPrimer/ch09/9_20.cpp
b1db4260f441353b895037e4805c73ceff6c9ba0
[]
no_license
NH333/novel
7b69d5f873e761d799ebe974f2d491ab7b2b6d54
14d2c4b12d2e9ebe509662994bdf5bdd9fa3c809
refs/heads/master
2022-11-18T20:40:38.053248
2022-11-15T06:58:47
2022-11-15T06:58:47
220,582,529
0
0
null
null
null
null
UTF-8
C++
false
false
1,089
cpp
<<<<<<< HEAD #include <iostream> #include <list> #include <deque> using std::list; using std::deque; using std::cout; using std::endl; int main() { list<int> m_list = { 1,3,5,7,9,2,4,6,8,10 }; deque<int> m_deque1; deque<int> m_deque2; for (auto iter=m_list.begin(); iter!=m_list.end(); ++iter) { if (*iter % 2 == 0) { m_deque1.push_back(*iter); cout << "deque1 insert " << *iter << endl; } else { m_deque2.push_back(*iter); cout << "deque2 insert " << *iter << endl; } } system("pause"); ======= #include <iostream> #include <list> #include <deque> using std::list; using std::deque; using std::cout; using std::endl; int main() { list<int> m_list = { 1,3,5,7,9,2,4,6,8,10 }; deque<int> m_deque1; deque<int> m_deque2; for (auto iter=m_list.begin(); iter!=m_list.end(); ++iter) { if (*iter % 2 == 0) { m_deque1.push_back(*iter); cout << "deque1 insert " << *iter << endl; } else { m_deque2.push_back(*iter); cout << "deque2 insert " << *iter << endl; } } system("pause"); >>>>>>> 639ff8d95a9fe74af54e79615c03d2fa61b773a1 }
[ "842414969@qq.com" ]
842414969@qq.com