hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
d2dcd4c2633801db322269d367ba024fb961ad47
384
cpp
C++
string_array/string_array/main.cpp
silentShadow/C-plus-plus
fb0108beb83f69d0c207f75dc29fae8c1657121c
[ "MIT" ]
null
null
null
string_array/string_array/main.cpp
silentShadow/C-plus-plus
fb0108beb83f69d0c207f75dc29fae8c1657121c
[ "MIT" ]
null
null
null
string_array/string_array/main.cpp
silentShadow/C-plus-plus
fb0108beb83f69d0c207f75dc29fae8c1657121c
[ "MIT" ]
null
null
null
// // main.cpp // string_array // // Created by Jonathan Reiter on 6/3/16. // Copyright © 2016 Jonathan Reiter. All rights reserved. // #include <iostream> #include <string> using namespace std; int main() { string members[] = {"Jonny", "Paul", "Ben", "Ringo"}; for (int i = 0; i < 4; i++) { cout << members[i] << " " << endl; } return 0; }
15.36
58
0.541667
silentShadow
d2df115b253d364d5896a77c6d1692ca58081a1d
8,957
cpp
C++
track_odometry/test/src/test_track_odometry.cpp
fangzheng81/neonavigation
1251ac6dfcb7fa102a21925863ff930a3fc03111
[ "BSD-3-Clause" ]
1
2019-09-26T01:13:02.000Z
2019-09-26T01:13:02.000Z
track_odometry/test/src/test_track_odometry.cpp
DiaS-77/neonavigation
486e0b34d0c5601e3a8517c71ba329535e641b6b
[ "BSD-3-Clause" ]
null
null
null
track_odometry/test/src/test_track_odometry.cpp
DiaS-77/neonavigation
486e0b34d0c5601e3a8517c71ba329535e641b6b
[ "BSD-3-Clause" ]
2
2019-10-05T12:27:54.000Z
2020-07-23T10:42:47.000Z
/* * Copyright (c) 2018-2019, the neonavigation authors * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <string> #include <vector> #include <ros/ros.h> #include <nav_msgs/Odometry.h> #include <sensor_msgs/Imu.h> #include <tf2/utils.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <gtest/gtest.h> class TrackOdometryTest : public ::testing::TestWithParam<const char*> { protected: std::vector<nav_msgs::Odometry> odom_msg_buffer_; public: void initializeNode(const std::string& ns) { ros::NodeHandle nh(ns); pub_odom_ = nh.advertise<nav_msgs::Odometry>("odom_raw", 10); pub_imu_ = nh.advertise<sensor_msgs::Imu>("imu/data", 10); sub_odom_ = nh.subscribe("odom", 10, &TrackOdometryTest::cbOdom, this); } bool initializeTrackOdometry( nav_msgs::Odometry& odom_raw, sensor_msgs::Imu& imu) { ros::Duration(0.1).sleep(); ros::Rate rate(100); odom_ = nullptr; for (int i = 0; i < 100 && ros::ok(); ++i) { odom_raw.header.stamp = ros::Time::now(); imu.header.stamp = odom_raw.header.stamp + ros::Duration(0.0001); pub_odom_.publish(odom_raw); pub_imu_.publish(imu); rate.sleep(); ros::spinOnce(); if (odom_ && i > 50) break; } return static_cast<bool>(odom_); } bool run( nav_msgs::Odometry& odom_raw, sensor_msgs::Imu& imu, const float dt, const int steps) { ros::Rate rate(1.0 / dt); int cnt(0); while (ros::ok()) { tf2::Quaternion quat_odom; tf2::fromMsg(odom_raw.pose.pose.orientation, quat_odom); odom_raw.pose.pose.orientation = tf2::toMsg( quat_odom * tf2::Quaternion(tf2::Vector3(0.0, 0.0, 1.0), dt * odom_raw.twist.twist.angular.z)); tf2::Quaternion quat_imu; tf2::fromMsg(imu.orientation, quat_imu); imu.orientation = tf2::toMsg( quat_imu * tf2::Quaternion(tf2::Vector3(0.0, 0.0, 1.0), dt * imu.angular_velocity.z)); const double yaw = tf2::getYaw(odom_raw.pose.pose.orientation); odom_raw.pose.pose.position.x += cos(yaw) * dt * odom_raw.twist.twist.linear.x; odom_raw.pose.pose.position.y += sin(yaw) * dt * odom_raw.twist.twist.linear.x; stepAndPublish(odom_raw, imu, dt); rate.sleep(); ros::spinOnce(); if (++cnt >= steps) break; } flushOdomMsgs(); return ros::ok(); } void stepAndPublish( nav_msgs::Odometry& odom_raw, sensor_msgs::Imu& imu, const float dt) { odom_raw.header.stamp += ros::Duration(dt); imu.header.stamp += ros::Duration(dt); pub_imu_.publish(imu); // Buffer odom message to add delay and jitter. // Send odometry in half rate of IMU. ++odom_cnt_; if (odom_cnt_ % 2 == 0) odom_msg_buffer_.push_back(odom_raw); if (odom_msg_buffer_.size() > 10) { flushOdomMsgs(); } } void flushOdomMsgs() { for (nav_msgs::Odometry& o : odom_msg_buffer_) { pub_odom_.publish(o); } odom_msg_buffer_.clear(); } void waitAndSpinOnce() { ros::Duration(0.1).sleep(); ros::spinOnce(); } protected: ros::Publisher pub_odom_; ros::Publisher pub_imu_; ros::Subscriber sub_odom_; nav_msgs::Odometry::ConstPtr odom_; size_t odom_cnt_; void cbOdom(const nav_msgs::Odometry::ConstPtr& msg) { odom_ = msg; }; }; TEST_F(TrackOdometryTest, OdomImuFusion) { initializeNode(""); const float dt = 0.01; const int steps = 200; nav_msgs::Odometry odom_raw; odom_raw.header.frame_id = "odom"; odom_raw.pose.pose.orientation.w = 1; sensor_msgs::Imu imu; imu.header.frame_id = "base_link"; imu.orientation.w = 1; imu.linear_acceleration.z = 9.8; ASSERT_TRUE(initializeTrackOdometry(odom_raw, imu)); // Go forward for 1m odom_raw.twist.twist.linear.x = 0.5; ASSERT_TRUE(run(odom_raw, imu, dt, steps)); odom_raw.twist.twist.linear.x = 0.0; stepAndPublish(odom_raw, imu, dt); flushOdomMsgs(); waitAndSpinOnce(); ASSERT_NEAR(odom_->pose.pose.position.x, 1.0, 1e-3); ASSERT_NEAR(odom_->pose.pose.position.y, 0.0, 1e-3); ASSERT_NEAR(odom_->pose.pose.position.z, 0.0, 1e-3); ASSERT_NEAR(tf2::getYaw(odom_->pose.pose.orientation), 0.0, 1e-3); // Turn 90 degrees with 10% of odometry errors imu.angular_velocity.z = M_PI * 0.25; odom_raw.twist.twist.angular.z = imu.angular_velocity.z * 1.1; // Odometry with error ASSERT_TRUE(run(odom_raw, imu, dt, steps)); imu.angular_velocity.z = 0; odom_raw.twist.twist.angular.z = 0; imu.orientation = tf2::toMsg(tf2::Quaternion(tf2::Vector3(0.0, 0.0, 1.0), M_PI / 2)); stepAndPublish(odom_raw, imu, dt); flushOdomMsgs(); waitAndSpinOnce(); ASSERT_NEAR(odom_->pose.pose.position.x, 1.0, 1e-2); ASSERT_NEAR(odom_->pose.pose.position.y, 0.0, 1e-2); ASSERT_NEAR(odom_->pose.pose.position.z, 0.0, 1e-2); ASSERT_NEAR(tf2::getYaw(odom_->pose.pose.orientation), M_PI / 2, 1e-2); // Go forward for 1m odom_raw.twist.twist.linear.x = 0.5; ASSERT_TRUE(run(odom_raw, imu, dt, steps)); odom_raw.twist.twist.linear.x = 0.0; stepAndPublish(odom_raw, imu, dt); flushOdomMsgs(); waitAndSpinOnce(); ASSERT_NEAR(odom_->pose.pose.position.x, 1.0, 5e-2); ASSERT_NEAR(odom_->pose.pose.position.y, 1.0, 5e-2); ASSERT_NEAR(odom_->pose.pose.position.z, 0.0, 5e-2); ASSERT_NEAR(tf2::getYaw(odom_->pose.pose.orientation), M_PI / 2, 1e-2); } TEST_P(TrackOdometryTest, ZFilterOff) { const std::string ns_postfix(GetParam()); initializeNode("no_z_filter" + ns_postfix); const float dt = 0.01; const int steps = 200; nav_msgs::Odometry odom_raw; odom_raw.header.frame_id = "odom"; odom_raw.pose.pose.orientation.w = 1; sensor_msgs::Imu imu; imu.header.frame_id = "base_link"; imu.orientation.y = sin(-M_PI / 4); imu.orientation.w = cos(-M_PI / 4); imu.linear_acceleration.x = -9.8; ASSERT_TRUE(initializeTrackOdometry(odom_raw, imu)); // Go forward for 1m odom_raw.twist.twist.linear.x = 0.5; ASSERT_TRUE(run(odom_raw, imu, dt, steps)); odom_raw.twist.twist.linear.x = 0.0; stepAndPublish(odom_raw, imu, dt); flushOdomMsgs(); waitAndSpinOnce(); ASSERT_NEAR(odom_->pose.pose.position.x, 0.0, 1e-3); ASSERT_NEAR(odom_->pose.pose.position.y, 0.0, 1e-3); ASSERT_NEAR(odom_->pose.pose.position.z, 1.0, 1e-3); } TEST_P(TrackOdometryTest, ZFilterOn) { const std::string ns_postfix(GetParam()); initializeNode("z_filter" + ns_postfix); const float dt = 0.01; const int steps = 200; nav_msgs::Odometry odom_raw; odom_raw.header.frame_id = "odom"; odom_raw.pose.pose.orientation.w = 1; sensor_msgs::Imu imu; imu.header.frame_id = "base_link"; imu.orientation.y = sin(-M_PI / 4); imu.orientation.w = cos(-M_PI / 4); imu.linear_acceleration.x = -9.8; ASSERT_TRUE(initializeTrackOdometry(odom_raw, imu)); // Go forward for 1m odom_raw.twist.twist.linear.x = 0.5; ASSERT_TRUE(run(odom_raw, imu, dt, steps)); odom_raw.twist.twist.linear.x = 0.0; stepAndPublish(odom_raw, imu, dt); flushOdomMsgs(); waitAndSpinOnce(); ASSERT_NEAR(odom_->pose.pose.position.z, 1.0 - 1.0 / M_E, 5e-2); } INSTANTIATE_TEST_CASE_P( TrackOdometryTestInstance, TrackOdometryTest, ::testing::Values("", "_old_param")); int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "test_track_odometry"); return RUN_ALL_TESTS(); }
30.057047
97
0.67824
fangzheng81
d2e1fa813fc7092527657cca4336ad0055119896
1,195
cpp
C++
examples/simpleClientClass/simpleStreamer.cpp
Max-Mobility/socket.io-client-cpp
575223b4f8e6664493a0c6ff88b66297a92d38d6
[ "MIT" ]
null
null
null
examples/simpleClientClass/simpleStreamer.cpp
Max-Mobility/socket.io-client-cpp
575223b4f8e6664493a0c6ff88b66297a92d38d6
[ "MIT" ]
null
null
null
examples/simpleClientClass/simpleStreamer.cpp
Max-Mobility/socket.io-client-cpp
575223b4f8e6664493a0c6ff88b66297a92d38d6
[ "MIT" ]
null
null
null
#include "simpleClient.h" void SimpleStreamer::on_connected() { _lock.lock(); _cond.notify_all(); _connect_finish = true; _connected = true; _lock.unlock(); } void SimpleStreamer::on_close() { _connected = false; } void SimpleStreamer::on_fail() { _lock.lock(); _cond.notify_all(); _connect_finish = true; _connected = false; _lock.unlock() } public: connection_listener(): { } bool SimpleStreamer::connect(std::string url) { h.set_open_listener(&on_connected); h.set_close_litener(&on_close); h.set_fail_listener(&on_fail); h.connect(url); _lock.lock(); if(!_connect_finish) { _cond.wait(_lock); } _lock.unlock(); return _connected; } void SimpleStreamer::close() { h.sync_close(); h.clear_con_listeners(); } bool SimpleStreamer::sendBuffer(std::string name, char* buff) { if(_connected) { h.socket()->emit(name, std::make_shared<std::string>(buff,sizeof(buff))); } return _connected; } bool SimpleStreamer::sendMessage(std::string name, std::string message) { if(_connected) { h.socket()->emit(name, message); } return _connected; } bool isConnected() { return _connected; } };
15.126582
75
0.666109
Max-Mobility
d2e20c703eb0cbf9df4758d98a5a93fa06058a27
57
hpp
C++
Example/Pods/Headers/Public/WCDB/WCDB/statement_release.hpp
hatjs880328s/IIPureOCWCDB
14e1dbe450a6b8e0119ff5ef1ce4f4edb5e1e211
[ "MIT" ]
5
2020-09-06T08:22:27.000Z
2021-09-22T05:32:53.000Z
iOSProjects/Pods/Headers/Public/WCDB/WCDB/statement_release.hpp
YYDreams/iOSProjects
7b142ecfb82349c5301816d3bc46cc2a76f16683
[ "Apache-2.0" ]
null
null
null
iOSProjects/Pods/Headers/Public/WCDB/WCDB/statement_release.hpp
YYDreams/iOSProjects
7b142ecfb82349c5301816d3bc46cc2a76f16683
[ "Apache-2.0" ]
5
2020-04-29T11:20:00.000Z
2021-11-09T08:49:20.000Z
../../../../WCDB/objc/WCDB/abstract/statement_release.hpp
57
57
0.701754
hatjs880328s
d2e326ff3d07283e34d6306577e70363005bcd0e
122
cpp
C++
code/engine.vc2008/xrManagedEngineLib/CallbackTypes.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
7
2018-03-27T12:36:07.000Z
2020-06-26T11:31:52.000Z
code/engine.vc2008/xrManagedEngineLib/CallbackTypes.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
2
2018-05-26T23:17:14.000Z
2019-04-14T18:33:27.000Z
code/engine.vc2008/xrManagedEngineLib/CallbackTypes.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
3
2020-10-12T18:04:42.000Z
2020-10-12T18:04:59.000Z
#include "stdafx.h" #include "FunctionInvoker.h" FunctionInvoker<unsigned int> Shedule_Update_Invoker("shedule_update");
24.4
71
0.811475
Rikoshet-234
5e44f233b6c7218a0f767c76deb368be7ac82a10
1,071
cpp
C++
src/graphics/renderable/Layer.cpp
vitaminac/minige
15adb8084e66b5e6800b706559d1ce63220ea116
[ "MIT" ]
1
2021-03-25T13:40:11.000Z
2021-03-25T13:40:11.000Z
src/graphics/renderable/Layer.cpp
vitaminac/minige
15adb8084e66b5e6800b706559d1ce63220ea116
[ "MIT" ]
null
null
null
src/graphics/renderable/Layer.cpp
vitaminac/minige
15adb8084e66b5e6800b706559d1ce63220ea116
[ "MIT" ]
null
null
null
#include "Layer.h" namespace gengine { namespace graphics { Layer::Layer(Renderer2D* renderer, Shader* shader, geometry::mat4 projection_matrix) :renderer(renderer), shader(shader), projection_matrix(projection_matrix) { this->shader->enable(); this->shader->setUniformMat4("projection_matrix", this->projection_matrix); this->shader->disable(); } Layer::~Layer() { delete shader; delete renderer; for (int i = 0; i < this->renderables.size(); i++) delete this->renderables[i]; } void Layer::add(Renderable2D* renderable) { this->renderables.push_back(renderable); } void Layer::render() { this->shader->enable(); this->renderer->begin(); for (const Renderable2D* renderable : this->renderables) renderable->render(this->renderer); this->renderer->end(); this->renderer->flush(); } } }
28.945946
166
0.54155
vitaminac
5e45de3a22442603be005b2bea678374f8288439
2,046
cc
C++
auth/tests/desktop/rpcs/reset_password_test.cc
IvanArtogon/firebase-cpp-sdk
dbe14b68c6cd7aeb585f560bf093fc76fab6fbc5
[ "Apache-2.0" ]
1
2021-02-14T19:09:51.000Z
2021-02-14T19:09:51.000Z
auth/tests/desktop/rpcs/reset_password_test.cc
IvanArtogon/firebase-cpp-sdk
dbe14b68c6cd7aeb585f560bf093fc76fab6fbc5
[ "Apache-2.0" ]
null
null
null
auth/tests/desktop/rpcs/reset_password_test.cc
IvanArtogon/firebase-cpp-sdk
dbe14b68c6cd7aeb585f560bf093fc76fab6fbc5
[ "Apache-2.0" ]
1
2020-08-16T11:53:44.000Z
2020-08-16T11:53:44.000Z
// Copyright 2017 Google LLC // // 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 <memory> #include "app/rest/transport_builder.h" #include "app/src/include/firebase/app.h" #include "app/tests/include/firebase/app_for_testing.h" #include "gtest/gtest.h" #include "gmock/gmock.h" #include "auth/src/desktop/rpcs/reset_password_request.h" #include "auth/src/desktop/rpcs/reset_password_response.h" namespace firebase { namespace auth { // Test ResetPasswordRequest TEST(ResetPasswordTest, TestResetPasswordRequest) { std::unique_ptr<App> app(testing::CreateApp()); ResetPasswordRequest request("APIKEY", "oob", "password"); EXPECT_EQ( "https://www.googleapis.com/identitytoolkit/v3/relyingparty/" "resetPassword?key=APIKEY", request.options().url); EXPECT_EQ( "{\n" " oobCode: \"oob\",\n" " newPassword: \"password\"\n" "}\n", request.options().post_fields); } // Test ResetPasswordResponse TEST(ResetPasswordTest, TestResetPasswordResponse) { std::unique_ptr<App> app(testing::CreateApp()); ResetPasswordResponse response; // An example HTTP response JSON in the exact format we get from real server // with token string replaced by dummy string. const char body[] = "{\n" " \"kind\": \"identitytoolkit#ResetPasswordResponse\",\n" " \"email\": \"abc@email\",\n" " \"requestType\": \"PASSWORD_RESET\"\n" "}"; response.ProcessBody(body, sizeof(body)); response.MarkCompleted(); } } // namespace auth } // namespace firebase
33
78
0.707234
IvanArtogon
5e464265d799784250e40ef0246d8ae0d37aba56
2,483
cpp
C++
aws-cpp-sdk-kinesisanalyticsv2/source/model/UpdateApplicationRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-kinesisanalyticsv2/source/model/UpdateApplicationRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-kinesisanalyticsv2/source/model/UpdateApplicationRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2020-11-04T03:18:11.000Z
2020-11-04T03:18:11.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/kinesisanalyticsv2/model/UpdateApplicationRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::KinesisAnalyticsV2::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateApplicationRequest::UpdateApplicationRequest() : m_applicationNameHasBeenSet(false), m_currentApplicationVersionId(0), m_currentApplicationVersionIdHasBeenSet(false), m_applicationConfigurationUpdateHasBeenSet(false), m_serviceExecutionRoleUpdateHasBeenSet(false), m_runConfigurationUpdateHasBeenSet(false), m_cloudWatchLoggingOptionUpdatesHasBeenSet(false) { } Aws::String UpdateApplicationRequest::SerializePayload() const { JsonValue payload; if(m_applicationNameHasBeenSet) { payload.WithString("ApplicationName", m_applicationName); } if(m_currentApplicationVersionIdHasBeenSet) { payload.WithInt64("CurrentApplicationVersionId", m_currentApplicationVersionId); } if(m_applicationConfigurationUpdateHasBeenSet) { payload.WithObject("ApplicationConfigurationUpdate", m_applicationConfigurationUpdate.Jsonize()); } if(m_serviceExecutionRoleUpdateHasBeenSet) { payload.WithString("ServiceExecutionRoleUpdate", m_serviceExecutionRoleUpdate); } if(m_runConfigurationUpdateHasBeenSet) { payload.WithObject("RunConfigurationUpdate", m_runConfigurationUpdate.Jsonize()); } if(m_cloudWatchLoggingOptionUpdatesHasBeenSet) { Array<JsonValue> cloudWatchLoggingOptionUpdatesJsonList(m_cloudWatchLoggingOptionUpdates.size()); for(unsigned cloudWatchLoggingOptionUpdatesIndex = 0; cloudWatchLoggingOptionUpdatesIndex < cloudWatchLoggingOptionUpdatesJsonList.GetLength(); ++cloudWatchLoggingOptionUpdatesIndex) { cloudWatchLoggingOptionUpdatesJsonList[cloudWatchLoggingOptionUpdatesIndex].AsObject(m_cloudWatchLoggingOptionUpdates[cloudWatchLoggingOptionUpdatesIndex].Jsonize()); } payload.WithArray("CloudWatchLoggingOptionUpdates", std::move(cloudWatchLoggingOptionUpdatesJsonList)); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection UpdateApplicationRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "KinesisAnalytics_20180523.UpdateApplication")); return headers; }
29.211765
185
0.808296
Neusoft-Technology-Solutions
5e4865e4ce97666c6f0b4d7ad91dd0e387932c87
3,077
cpp
C++
src/cosmoscout/main.cpp
bernstein/cosmoscout-vr
4243384a0f96853dc12fc8e9d5862c9c37f7cadf
[ "MIT" ]
null
null
null
src/cosmoscout/main.cpp
bernstein/cosmoscout-vr
4243384a0f96853dc12fc8e9d5862c9c37f7cadf
[ "MIT" ]
null
null
null
src/cosmoscout/main.cpp
bernstein/cosmoscout-vr
4243384a0f96853dc12fc8e9d5862c9c37f7cadf
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of CosmoScout VR // // and may be used under the terms of the MIT license. See the LICENSE file for details. // // Copyright: (c) 2019 German Aerospace Center (DLR) // //////////////////////////////////////////////////////////////////////////////////////////////////// #include "../cs-core/SolarSystem.hpp" #include "../cs-gui/gui.hpp" #include "../cs-utils/CommandLine.hpp" #include "Application.hpp" #include <VistaOGLExt/VistaShaderRegistry.h> //////////////////////////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { // launch gui child processes cs::gui::executeChildProcess(argc, argv); // parse program options std::string settingsFile = "../share/config/simple_desktop.json"; bool printHelp = false; bool printVistaHelp = false; // First configure all possible command line options. cs::utils::CommandLine args("Welcome to CosmoScout VR! Here are the available options:"); args.addArgument({"-s", "--settings"}, &settingsFile, "JSON file containing settings (default: " + settingsFile + ")"); args.addArgument({"-h", "--help"}, &printHelp, "Print this help."); args.addArgument({"-v", "--vistahelp"}, &printVistaHelp, "Print help for vista options."); // The do the actual parsing. try { args.parse(argc, argv); } catch (std::runtime_error const& e) { std::cout << e.what() << std::endl; return -1; } // When printHelp was set to true, we print a help message and exit. if (printHelp) { args.printHelp(); return 0; } // When printVistaHelp was set to true, we print a help message and exit. if (printVistaHelp) { VistaSystem::ArgHelpMsg(argv[0], &std::cout); return 0; } // read settings cs::core::Settings settings; try { settings = cs::core::Settings::read(settingsFile); } catch (std::exception& e) { std::cerr << "Failed to read settings: " << e.what() << std::endl; return 1; } // start application try { std::list<std::string> liSearchPath; liSearchPath.emplace_back("../share/config/vista"); VistaShaderRegistry::GetInstance().AddSearchDirectory("../share/resources/shaders"); auto pVistaSystem = new VistaSystem(); pVistaSystem->SetIniSearchPaths(liSearchPath); cs::core::SolarSystem::init(settings.mSpiceKernel); Application app(settings); pVistaSystem->SetFrameLoop(&app, true); if (pVistaSystem->Init(argc, argv)) { pVistaSystem->Run(); } cs::core::SolarSystem::cleanup(); } catch (VistaExceptionBase& e) { e.PrintException(); return 1; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; return 1; } return 0; } ////////////////////////////////////////////////////////////////////////////////////////////////////
33.086022
100
0.542411
bernstein
5e48b3deeca191dff86aa7d36cc8c5f2ab15b218
1,967
hpp
C++
src/viewer/tile_provider.hpp
malasiot/maplite
1edeec673110cdd5fa904ff2ff88289b6c3ec324
[ "MIT" ]
12
2017-05-11T21:44:57.000Z
2021-12-30T08:35:56.000Z
src/viewer/tile_provider.hpp
malasiot/mftools
1edeec673110cdd5fa904ff2ff88289b6c3ec324
[ "MIT" ]
8
2016-10-27T10:10:05.000Z
2019-12-07T21:27:02.000Z
src/viewer/tile_provider.hpp
malasiot/mftools
1edeec673110cdd5fa904ff2ff88289b6c3ec324
[ "MIT" ]
5
2017-10-17T08:18:58.000Z
2021-11-12T11:44:23.000Z
#ifndef __TILE_PROVIDER_H__ #define __TILE_PROVIDER_H__ #include <QPixmap> #include <QPixmapCache> #include "geometry.hpp" class TileProvider: public QObject { Q_OBJECT public: TileProvider(const QByteArray &id, unsigned int tileSize): tile_size_(tileSize), id_(id), async_(false), start_zoom_(-1), has_start_position_(false) {} virtual QImage getTile(int x, int y, int z) = 0 ; QByteArray id() const { return id_ ; } void setName(const QString &name) { name_ = name ; } QString name() const { return name_ ; } QString attribution() const { return attribution_ ; } QString description() const { return description_ ; } unsigned int tileSize() const { return tile_size_ ; } bool isAsync() const { return async_ ; } void coordsFromTileKey(const QByteArray &key, int &x, int &y, int &z) ; void setDescription(const QString &desc) { description_ = desc ; } void setAttribution(const QString &attr) { attribution_ = attr ; } void setZoomRange(int minZ, int maxZ) { min_zoom_ = minZ ; max_zoom_ = maxZ ; } int getStartZoom() const { return start_zoom_ ; } QPointF getStartPosition() const { return start_position_ ; } bool hasStartPosition() const { return has_start_position_ ; } void setStartZoom(int z) { start_zoom_ = z ; } void setStartPosition(const LatLon &center) { start_position_ = QPointF(center.lat_, center.lon_) ; has_start_position_ = true ; } virtual QByteArray key() const { return id_ ; } virtual QByteArray tileKey(int x, int y, int z) const ; virtual time_t creationTime() const { return 0 ; } protected: unsigned int tile_size_, min_zoom_, max_zoom_ ; QString name_ ; QByteArray id_ ; QString attribution_, description_ ; bool async_ ; QPointF start_position_ ; int start_zoom_ ; bool has_start_position_ ; Q_SIGNALS: void tileReady(QByteArray, QImage) ; } ; #endif
28.926471
100
0.68124
malasiot
5e4c64946150222e401dbf38c34a8ebdbd70d2c0
962
cc
C++
chrome/browser/chromeos/policy/stub_enterprise_install_attributes.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-08-04T15:17:59.000Z
2016-10-23T08:11:14.000Z
chrome/browser/chromeos/policy/stub_enterprise_install_attributes.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chromeos/policy/stub_enterprise_install_attributes.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2017-07-31T19:09:52.000Z
2019-01-04T18:48:50.000Z
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/policy/stub_enterprise_install_attributes.h" #include <string> #include "chrome/browser/policy/cloud/cloud_policy_constants.h" namespace policy { StubEnterpriseInstallAttributes::StubEnterpriseInstallAttributes() : EnterpriseInstallAttributes(NULL, NULL) { device_locked_ = true; } void StubEnterpriseInstallAttributes::SetDomain(const std::string& domain) { registration_domain_ = domain; } void StubEnterpriseInstallAttributes::SetRegistrationUser( const std::string& user) { registration_user_ = user; } void StubEnterpriseInstallAttributes::SetDeviceId(const std::string& id) { registration_device_id_ = id; } void StubEnterpriseInstallAttributes::SetMode(DeviceMode mode) { registration_mode_ = mode; } } // namespace policy
26.722222
78
0.785863
pozdnyakov
5e4de08ccf4c1ed4e615d55ce4b84e736ec89ffa
10,624
cpp
C++
remodet_repository_wdh_part/hp_demo_bak.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_wdh_part/hp_demo_bak.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_wdh_part/hp_demo_bak.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
// if not use OPENCV, note it. #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> // if not use, note it. #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> #include <map> // Google log & flags #include "gflags/gflags.h" #include "glog/logging.h" // caffe #include "caffe/proto/caffe.pb.h" #include "caffe/caffe.hpp" // remo, note the useless classes. #include "caffe/remo/remo_front_visualizer.hpp" #include "caffe/remo/net_wrap.hpp" #include "caffe/remo/frame_reader.hpp" #include "caffe/remo/data_frame.hpp" #include "caffe/remo/basic.hpp" #include "caffe/remo/res_frame.hpp" #include "caffe/remo/visualizer.hpp" #include "caffe/mask/bbox_func.hpp" #include "caffe/tracker/basic.hpp" #include <boost/foreach.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include "caffe/det/detwrap.hpp" #include "caffe/hp/hp_net.hpp" using namespace std; using namespace caffe; using std::string; using std::vector; namespace bfs = boost::filesystem; // 获取FaceBoxes: 3 void getFaceBoxes(const vector<LabeledBBox<float> >& rois, vector<BoundingBox<float> >* face_boxes) { face_boxes->clear(); for (int i = 0; i < rois.size(); ++i) { if (rois[i].cid != 3) continue; face_boxes->push_back(rois[i].bbox); } } // 获取HeadBoxes: 2 void getHeadBoxes(const vector<LabeledBBox<float> >& rois, vector<BoundingBox<float> >* head_boxes) { head_boxes->clear(); for (int i = 0; i < rois.size(); ++i) { if (rois[i].cid != 2) continue; head_boxes->push_back(rois[i].bbox); } } // 获取HandBoxes: 1 void getHandBoxes(const vector<LabeledBBox<float> >& rois, vector<BoundingBox<float> >* hand_boxes) { hand_boxes->clear(); for (int i = 0; i < rois.size(); ++i) { if (rois[i].cid != 1) continue; hand_boxes->push_back(rois[i].bbox); } } // 滤出HandBoxes: // 将与Head/Face交叠的HandBoxes全部删除 void filterHandBoxes(vector<BoundingBox<float> >& hand_boxes, const vector<BoundingBox<float> >& head_boxes, const vector<BoundingBox<float> >& face_boxes) { for (vector<BoundingBox<float> >::iterator it = hand_boxes.begin(); it!= hand_boxes.end();) { bool cov = false; // HEAD for (int i = 0; i < head_boxes.size(); ++i) { if (it->compute_coverage(head_boxes[i]) > 0.2) { cov = true; break; } } // FACE if (! cov) { for (int i = 0; i < face_boxes.size(); ++i) { if (it->compute_coverage(face_boxes[i]) > 0.1) { cov = true; break; } } } // 结论 if (cov) { // 删除之 it = hand_boxes.erase(it); } else { ++it; } } } vector<bool> filterHandBoxesbyDistance(const vector<BoundingBox<float> >& head_boxes, const vector<BoundingBox<float> >& hand_boxes) { vector<bool> matrix(hand_boxes.size() * head_boxes.size(), false); vector<bool> chosen(hand_boxes.size(), false); // 未匹配过 // 距离判断 for (int i = 0; i < hand_boxes.size(); ++i) { for (int j = 0; j < head_boxes.size(); ++j) { float dx = hand_boxes[i].get_center_x() - head_boxes[j].get_center_x(); float dy = hand_boxes[i].get_center_y() - head_boxes[j].get_center_y(); float dis = dx * dx + dy * dy; float size = head_boxes[j].compute_area(); matrix[i * head_boxes.size() + j] = (dis < size * 5) ? true : false; } } // 择一判断 for (int j = 0; j < head_boxes.size(); ++j) { // 选择最大的一个 int max_id = -1; float max_area = 0; for (int i = 0; i < hand_boxes.size(); ++i) { // 遍历所有hands if (chosen[i]) continue; // 已经匹配过,pass if (matrix[i * head_boxes.size() + j]) { // 匹配 const float area = hand_boxes[i].compute_area(); if (area > max_area) { max_area = area; max_id = i; } } } // 匹配的hand面积必须要大于head面积的一半以上 const float coeff = max_area / head_boxes[j].compute_area(); if (max_id >= 0 && coeff > 0.2) { chosen[max_id] = true; // 匹配成功! } } // 匹配成功的有效 return chosen; } int main(int nargc, char** args) { // ################################ NETWORK ################################ // network input int resized_width = 512; int resized_height = 288; const std::string network_proto = "/home/ethan/ForZhangM/Release20180314/Release20180314_Merged_profo2.5/Base_BD_PD_HD.prototxt"; const std::string network_model = "/home/ethan/ForZhangM/Release20180314/Release20180314_Merged_profo2.5/ResPoseDetTrackRelease_merge.caffemodel"; // GPU int gpu_id = 0; bool mode = true; // use GPU // features const std::string proposals = "det_out"; // display Size int max_dis_size = 1280; // active labels vector<int> active_label; // active_label.push_back(0); active_label.push_back(1); active_label.push_back(2); // active_label.push_back(3); // ################################ DATA #################################### // CAMERA const bool use_camera = true; // 0 const int cam_width = 1280; const int cam_height = 720; // ################################ MAIN LOOP ################################ // det_warpper caffe::DetWrapper<float> det_wrapper(network_proto,network_model,mode,gpu_id,proposals,max_dis_size); // HP const string hp_network = "/home/ethan/Models/Results/HPNet/CNN_Base_V0-I96-FL/Proto/test_copy.prototxt"; // const string hp_network = "/home/ethan/Models/Results/HPNet/test.prototxt"; const string hp_model = "/home/ethan/Models/Results/HPNet/CNN_Base_V0-I96-FL/Models/CNN_Base_V0-I96-FL-ROT-20K_iter_100000.caffemodel"; // const string hp_model = "/home/ethan/Models/Results/HPNet/CNN_Base_I96-FLRTScaleAug1.5-2.0R8_V1Split1_1A_iter_100000.caffemodel"; caffe::HPNetWrapper hp_wrapper(hp_network, hp_model); // CAMERA if (use_camera) { cv::VideoCapture cap; if (!cap.open(0)) { LOG(FATAL) << "Failed to open webcam: " << 0; } cap.set(CV_CAP_PROP_FRAME_WIDTH, cam_width); cap.set(CV_CAP_PROP_FRAME_HEIGHT, cam_height); int ex = static_cast<int>(cap.get(CV_CAP_PROP_FOURCC)); cv::VideoWriter outputVideo; outputVideo.open("outvideo_hp_CNN_Base_I96-FLRTScaleAug1.5-2.0R8_V1Split1_1A.avi", ex, cap.get(CV_CAP_PROP_FPS), cv::Size(cam_width,cam_height), true); cv::Mat cv_img; cap >> cv_img; int count = 0; CHECK(cv_img.data) << "Could not load image."; while (1) { ++count; cv::Mat image; cap >> image; caffe::DataFrame<float> data_frame(count, image, resized_width, resized_height); // 获取hand_detector的结果 vector<LabeledBBox<float> > rois; det_wrapper.get_rois(data_frame, &rois); vector<BoundingBox<float> > head_boxes; vector<BoundingBox<float> > face_boxes; vector<BoundingBox<float> > hand_boxes; getHeadBoxes(rois, &head_boxes); getFaceBoxes(rois, &face_boxes); getHandBoxes(rois, &hand_boxes); filterHandBoxes(hand_boxes, head_boxes, face_boxes); /** * 进一步滤除,每个Head最多允许一个HandBox * (1) 滤除距离:头的max(w,h)的两倍距离,超过这个距离的全部忽略 * (2) 如果保留多个,则只选择其中面积最大的一个进行分析 */ vector<bool> active_hands = filterHandBoxesbyDistance(head_boxes, hand_boxes); // 绘制Head for (int i = 0; i < head_boxes.size(); ++i) { BoundingBox<float>& roi = head_boxes[i]; float x1 = roi.get_center_x() - 1 * roi.get_width() / 2; float y1 = roi.get_center_y() - 1 * roi.get_height() / 2; float x2 = roi.get_center_x() + 1 * roi.get_width() / 2; float y2 = roi.get_center_y() + 1 * roi.get_height() / 2; x1 = (x1 < 0) ? 0 : (x1 > 1 ? 1 : x1); y1 = (y1 < 0) ? 0 : (y1 > 1 ? 1 : y1); x2 = (x2 < 0) ? 0 : (x2 > 1 ? 1 : x2); y2 = (y2 < 0) ? 0 : (y2 > 1 ? 1 : y2); x1 *= image.cols; x2 *= image.cols; y1 *= image.rows; y2 *= image.rows; const cv::Point point1(x1, y1); const cv::Point point2(x2, y2); cv::rectangle(image, point1, point2, cv::Scalar(255,0,0), 3); } // 绘制Face // for (int i = 0; i < face_boxes.size(); ++i) { // BoundingBox<float>& roi = face_boxes[i]; // float x1 = roi.get_center_x() - 1 * roi.get_width() / 2; // float y1 = roi.get_center_y() - 1 * roi.get_height() / 2; // float x2 = roi.get_center_x() + 1 * roi.get_width() / 2; // float y2 = roi.get_center_y() + 1 * roi.get_height() / 2; // x1 = (x1 < 0) ? 0 : (x1 > 1 ? 1 : x1); // y1 = (y1 < 0) ? 0 : (y1 > 1 ? 1 : y1); // x2 = (x2 < 0) ? 0 : (x2 > 1 ? 1 : x2); // y2 = (y2 < 0) ? 0 : (y2 > 1 ? 1 : y2); // x1 *= image.cols; // x2 *= image.cols; // y1 *= image.rows; // y2 *= image.rows; // const cv::Point point1(x1, y1); // const cv::Point point2(x2, y2); // cv::rectangle(image, point1, point2, cv::Scalar(0,255,0), 3); // } // 绘制minihand网络的结果 for (int i = 0; i < hand_boxes.size(); ++i) { BoundingBox<float>& roi = hand_boxes[i]; float x1 = roi.get_center_x() - 1 * roi.get_width() / 2; float y1 = roi.get_center_y() - 1 * roi.get_height() / 2; float x2 = roi.get_center_x() + 1 * roi.get_width() / 2; float y2 = roi.get_center_y() + 1 * roi.get_height() / 2; x1 = (x1 < 0) ? 0 : (x1 > 1 ? 1 : x1); y1 = (y1 < 0) ? 0 : (y1 > 1 ? 1 : y1); x2 = (x2 < 0) ? 0 : (x2 > 1 ? 1 : x2); y2 = (y2 < 0) ? 0 : (y2 > 1 ? 1 : y2); x1 *= image.cols; x2 *= image.cols; y1 *= image.rows; y2 *= image.rows; const cv::Point point1(x1, y1); const cv::Point point2(x2, y2); const int r = active_hands[i] ? 0 : 255; const int g = active_hands[i] ? 255 : 0; /** * 获取手势 */ if (active_hands[i]) { float score; int label = hp_wrapper.hpmode(image, hand_boxes[i], &score); char tmp_str[256]; snprintf(tmp_str, 256, "%d", label); cv::putText(image, tmp_str, cv::Point(x1, y1), cv::FONT_HERSHEY_SIMPLEX, 3, cv::Scalar(0,0,255), 5); } cv::rectangle(image, point1, point2, cv::Scalar(0,g,r), 3); } outputVideo << image; cv::namedWindow("RemoDet", cv::WINDOW_AUTOSIZE); cv::imshow( "RemoDet", image); cv::waitKey(1); } } LOG(INFO) << "Finished."; return 0; }
36.634483
156
0.577654
UrwLee
5e4eeb30aab610c15d659219b4b2639ae6bf94b8
2,162
hh
C++
psdaq/psdaq/eb/Batch.hh
ZhenghengLi/lcls2
94e75c6536954a58c8937595dcac295163aa1cdf
[ "BSD-3-Clause-LBNL" ]
16
2017-11-09T17:10:56.000Z
2022-03-09T23:03:10.000Z
psdaq/psdaq/eb/Batch.hh
ZhenghengLi/lcls2
94e75c6536954a58c8937595dcac295163aa1cdf
[ "BSD-3-Clause-LBNL" ]
6
2017-12-12T19:30:05.000Z
2020-07-09T00:28:33.000Z
psdaq/psdaq/eb/Batch.hh
ZhenghengLi/lcls2
94e75c6536954a58c8937595dcac295163aa1cdf
[ "BSD-3-Clause-LBNL" ]
25
2017-09-18T20:02:43.000Z
2022-03-27T22:27:42.000Z
#ifndef Pds_Eb_Batch_hh #define Pds_Eb_Batch_hh #include "eb.hh" #include "psdaq/service/EbDgram.hh" #include <cstdint> // For uint64_t #include <cstddef> // for size_t namespace Pds { namespace Eb { class Batch { public: Batch(); public: static uint64_t index(uint64_t pid); public: int initialize(size_t bufSize); Pds::EbDgram* allocate(); // Allocate buffer in batch Batch* initialize(void* region, uint64_t pid); size_t extent() const; // Current extent uint64_t id() const; // Batch start pulse ID unsigned index() const; // Batch's index const void* buffer() const; // Pointer to batch in RDMA space void dump() const; private: void* _buffer; // Pointer to RDMA space for this Batch size_t _bufSize; // Size of entries uint64_t _id; // Id of Batch, in case it remains empty unsigned _extent; // Current extent (unsigned is large enough) }; }; }; inline uint64_t Pds::Eb::Batch::index(uint64_t pid) { return pid & (MAX_LATENCY - 1); } inline unsigned Pds::Eb::Batch::index() const { return index(_id); } inline uint64_t Pds::Eb::Batch::id() const { return _id; // Full PID, not BatchNum } inline const void* Pds::Eb::Batch::buffer() const { return _buffer; } inline size_t Pds::Eb::Batch::extent() const { return _extent; } inline Pds::Eb::Batch* Pds::Eb::Batch::initialize(void* region, uint64_t pid) { _id = pid; // Full PID, not BatchNum _buffer = static_cast<char*>(region) + index(pid) * _bufSize; _extent = 0; //_buffer = region; // Revisit: For dense batch allocation idea return this; } inline Pds::EbDgram* Pds::Eb::Batch::allocate() { char* buf = static_cast<char*>(_buffer) + _extent; _extent += _bufSize; //if (_extent > (MAX_LATENCY - BATCH_DURATION) * _bufSize) _extent = 0; // Revisit return reinterpret_cast<Pds::EbDgram*>(buf); } #endif
23.758242
85
0.584181
ZhenghengLi
5e5016ca697c7845540ba25711dcfef827df438b
1,221
cpp
C++
src/EnemyWandering.cpp
anqin-gh/minimaze
cfa3df279c75d5fe95a2e69af4569a3981a6f274
[ "MIT" ]
null
null
null
src/EnemyWandering.cpp
anqin-gh/minimaze
cfa3df279c75d5fe95a2e69af4569a3981a6f274
[ "MIT" ]
null
null
null
src/EnemyWandering.cpp
anqin-gh/minimaze
cfa3df279c75d5fe95a2e69af4569a3981a6f274
[ "MIT" ]
null
null
null
#include <algorithm> #include <random> #include <EnemyWandering.h> #include <Renderer.h> #include <RendManager.h> namespace minimaze { EnemyWandering::EnemyWandering() : m_rend_manager{&RendManager::get_instance()} { init(); } void EnemyWandering::init() { std::default_random_engine generator; std::uniform_int_distribution<int8_t> distribution(1, 10); m_dirs[0] = { 0, 1, distribution(generator)}; m_dirs[1] = { 0, -1, distribution(generator)}; m_dirs[2] = { 1, 0, distribution(generator)}; m_dirs[3] = {-1, 0, distribution(generator)}; std::random_shuffle(m_dirs.begin(), m_dirs.end()); m_di = 0; m_step = 0; } int8_t EnemyWandering::steps_left_in_current_direction() const { return m_dirs[m_di].steps - m_step; } void EnemyWandering::move_one_step_in_current_direction() { const MoveDir& move = m_dirs[m_di]; set_next_movement(move.dx, move.dy); ++m_step; } void EnemyWandering::change_direction() { ++m_di; if (m_di < 3) init(); } void EnemyWandering::update() { if (!steps_left_in_current_direction()) { change_direction(); } move_one_step_in_current_direction(); } void EnemyWandering::draw() const { m_rend_manager->renderer().draw_enemy_wandering(m_x, m_y); } } // minimaze
21.421053
64
0.719902
anqin-gh
5e560a970d4604b6a6b5b3ed5440ef5e5b52e92f
2,693
cpp
C++
internal/query/src/querier.cpp
mingkaic/tenncor
f2fa9652e55e9ca206de5e9741fe41bde43791c1
[ "BSL-1.0", "MIT" ]
1
2020-12-29T20:38:08.000Z
2020-12-29T20:38:08.000Z
internal/query/src/querier.cpp
mingkaic/tenncor
f2fa9652e55e9ca206de5e9741fe41bde43791c1
[ "BSL-1.0", "MIT" ]
16
2018-01-28T04:20:19.000Z
2021-01-23T09:38:52.000Z
internal/query/src/querier.cpp
mingkaic/tenncor
f2fa9652e55e9ca206de5e9741fe41bde43791c1
[ "BSL-1.0", "MIT" ]
null
null
null
#include "internal/query/querier.hpp" #ifdef QUERY_QUERIER_HPP namespace query { inline bool doub_eq (const double& a, const double& b) { return std::fabs(a - b) < std::numeric_limits<float>::epsilon(); } bool equals ( QResultsT& candidates, const marsh::iObject* attr, const Attribute& pba, const Query& matcher) { bool match = false; switch (pba.attr_case()) { case Attribute::kInum: if (auto num = dynamic_cast<const marsh::iNumber*>(attr)) { match = pba.inum() == num->to_int64(); } break; case Attribute::kDnum: if (auto num = dynamic_cast<const marsh::iNumber*>(attr)) { match = doub_eq(pba.dnum(), num->to_float64()); } break; case Attribute::kIarr: if (auto narr = dynamic_cast<const marsh::iArray*>(attr)) { const auto& arr = pba.iarr().values(); if ((size_t) arr.size() == narr->size() && narr->is_integral()) { match = true; narr->foreach( [&](size_t i, const marsh::iObject* obj) { auto num = dynamic_cast<const marsh::iNumber*>(obj); match = match && nullptr != num && arr[i] == num->to_int64(); }); } } break; case Attribute::kDarr: if (auto narr = dynamic_cast<const marsh::iArray*>(attr)) { const auto& arr = pba.darr().values(); if ((size_t) arr.size() == narr->size() && false == narr->is_integral()) { match = true; narr->foreach( [&](size_t i, const marsh::iObject* obj) { auto num = dynamic_cast<const marsh::iNumber*>(obj); match = match && nullptr != num && doub_eq(arr[i], num->to_float64()); }); } } break; case Attribute::kStr: if (nullptr != attr) { match = pba.str() == attr->to_string(); } break; case Attribute::kNode: if (auto tens = dynamic_cast<const teq::TensorObj*>(attr)) { candidates = matcher.match(pba.node()); estd::remove_if(candidates, [&tens](const QueryResult& result) { return result.root_ != tens->get_tensor().get(); }); match = candidates.size() > 0; } break; case Attribute::kLayer: if (auto lay = dynamic_cast<const teq::LayerObj*>(attr)) { const Layer& layer = pba.layer(); match = query::Layer::kName != layer.nullable_name_case() || layer.name() == lay->get_opname(); if (match && layer.has_input()) { candidates = matcher.match(layer.input()); estd::remove_if(candidates, [&lay](const QueryResult& result) { return result.root_ != lay->get_tensor().get(); }); match = candidates.size() > 0; } } break; default: match = true; // return true if attribute is unknown } return match; } } #endif
24.044643
76
0.59042
mingkaic
5e5710941b5bfedbc3bd03b2c065a90f96c0d2cd
16,820
cpp
C++
Modules/ExampleModule/src/smartrefinement.cpp
pv6/smart-refinement-tool
1221a0a22ec0fc868cf922267fd0af73697025ea
[ "BSD-3-Clause" ]
null
null
null
Modules/ExampleModule/src/smartrefinement.cpp
pv6/smart-refinement-tool
1221a0a22ec0fc868cf922267fd0af73697025ea
[ "BSD-3-Clause" ]
null
null
null
Modules/ExampleModule/src/smartrefinement.cpp
pv6/smart-refinement-tool
1221a0a22ec0fc868cf922267fd0af73697025ea
[ "BSD-3-Clause" ]
null
null
null
#include <smartrefinement.hpp> #include <queue> #include <iostream> #include <vvt/algorithms/generallsm.hpp> #include <vvt/algorithms/chanveselsm.hpp> namespace vvt { namespace accessory { SmartRefinement::SmartRefinement(viewer::base *viewer) : PropagationAccessory(viewer), smartBrush_(new SmartBrushLevelSetImpl()), lsm_(1, 1) { smartBrush_->connect([this](VoxelPosition p) { markVoxel(p); smartBrushMarkedVoxels_.push_back(p); }, [this](VoxelPosition p) { return getVoxelIntensity(p); }, [this]() { return getSliceMinX(); }, [this]() { return getSliceMaxX(); }, [this]() { return getSliceMinY(); }, [this]() { return getSliceMaxY(); } ); smartBrush_->changeRadius(smartBrush_->getRadius() / 2); smartBrush_->startSelection(); result_ = std::make_unique<Matrix2D<bool>>(1, 1); } void SmartRefinement::exposeUseCaseCommands(vvt::engine *engine) { engine->registerCommand(getUseCaseName() + "_setSensitivity", this, &SmartRefinement::changeSensitivity, args_in("sensitivity")); engine->registerCommand(getUseCaseName() + "_setBorderPenalty", this, &SmartRefinement::changeBorderPenalty, args_in("sensitivity")); engine->registerCommand(getUseCaseName() + "_setSmoothness", this, &SmartRefinement::changeSmoothness, args_in("sensitivity")); engine->registerCommand(getUseCaseName() + "_setBrushRadius", this, &SmartRefinement::changeBrushRadius, args_in("radius")); engine->registerCommand(getUseCaseName() + "_startNewAnnotation", this, &SmartRefinement::startNewAnnotation); engine->registerCommand(getUseCaseName() + "_saveDist", this, &SmartRefinement::saveDist, args_in("fileName")); engine->registerCommand(getUseCaseName() + "_saveMask", this, &SmartRefinement::saveMask, args_in("fileName")); engine->registerCommand(getUseCaseName() + "_savePhi", this, &SmartRefinement::savePhi, args_in("fileName")); engine->registerCommand(getUseCaseName() + "_clearMask", this, &SmartRefinement::onClearMask); } void SmartRefinement::clearState() { clicks_.clear(); smartBrushMarkedVoxels_.clear(); } void SmartRefinement::onClearMask() { clearState(); } void SmartRefinement::startNewAnnotation() { convertTemporaryPatchToPrimary(); // save the latest patch clearState(); } std::string SmartRefinement::getUseCaseName() { return "SmartRefinement"; } void SmartRefinement::changeSensitivity(double sens) { sensitivity_ = sens; lsm_.setSensitivity(sens); } void SmartRefinement::changeSmoothness(double sens) { lsm_.setR2Mu(1 - sens); } void SmartRefinement::changeBrushRadius(int radius) { smartBrush_->changeRadius(radius); } void SmartRefinement::changeBorderPenalty(double sens) { lsm_.setDF2SS(1 - sens); } // End of 'SmartRefinement::changeSSCoef' function void SmartRefinement::updateClicksBBox(BBox3D &bbox, const int padding) { int minX = getSliceMaxX(), maxX = getSliceMinX(), minY = getSliceMaxY(), maxY = getSliceMinY(); int z = clicks_[0][2]; for (auto &p : clicks_) { int x = p[0]; int y = p[1]; minX = std::min(minX, x); minY = std::min(minY, y); maxX = std::max(maxX, x); maxY = std::max(maxY, y); } //if (minY > maxY) { // minY = getSliceMinY(); // maxY = getSliceMaxY(); //} bbox = { VoxelPosition({ std::max(minX - padding, getSliceMinX()), std::max(minY - padding, getSliceMinY()), z }), VoxelPosition({ std::min(maxX + padding, getSliceMaxX()), std::min(maxY + padding, getSliceMaxY()), z }) }; } // end of 'SmartRefinement::updateClicksBBox' function void SmartRefinement::wholeShabang() { if (clicks_.size() >= 3) { BBox3D bbox; std::cout << "I am here now\n"; const int padding = smartBrush_->getRadius(); // 3; /* if (!updateSliceBBox(bbox, voxelPos[2], padding)) { std::cout << "Can't find at least one marked voxel" << std::endl; return; } */ // find bbox using clicks_ updateClicksBBox(bbox, padding); bbox_ = bbox; bbox_[0][0] -= 1; bbox_[0][1] += 1; bbox_[1][0] -= 1; bbox_[1][1] += 1; /*seedPoints_.clear(); for (auto &seed : clicks_) { seedPoints_.push_back(seed); }*/ seedPoints_ = clicks_; refine(bbox); time_t tmp; timer_ = time(&tmp) - timer_; } } // end of 'SmartRefinement::wholeShabang' function void SmartRefinement::OnNewLabel2D(std::array<int, 3> &voxelPos) { // seedPoints_.push_back(voxelPos); time(&timer_); std::cout << "I am here, clicks size = " << clicks_.size() << std::endl; clicks_.push_back(voxelPos); drawSmartBrush(voxelPos); wholeShabang(); } void SmartRefinement::drawSmartBrush(std::array<int, 3> &voxelPos) { // startNewLabeling(); // PATCH_TYPE_TEMP); startNewLabeling(PATCH_TYPE_TEMP); setPrimaryLabel(); for (auto &p : clicks_) { smartBrush_->draw(p, smartBrush_->getRadius()); } // smartBrush_->draw(voxelPos, smartBrush_->getRadius()); endNewLabeling(); } void SmartRefinement::complementMask(Matrix2D<bool> &mask) { struct Vec { Vec() : x(0), y(0) {} Vec(const Vec &vec) : x(vec.x), y(vec.y) {} Vec(const int _x, const int _y) : x(_x), y(_y) {} Vec operator-(const Vec& rhs) { return Vec(x - rhs.x, y - rhs.y); } Vec cross() { return Vec(-y, x); } int operator*(const Vec& rhs) { return x * rhs.x + y * rhs.y; } int x; int y; }; std::vector<Vec> rectPoints; // Add border points /* for (int y = 0; y < mask.sizeY; y++) { for (int x = 0; x < mask.sizeX; x++) { if (mask.get(x, y) && !mask.get(x - 1, y) && !mask.get(x - 1, y - 1) && !mask.get(x, y - 1)) { rectPoints.push_back(Vec(x, y)); } } } */ for (auto &p : seedPoints_) { rectPoints.push_back(Vec(p[0], p[1])); } if (rectPoints.size() <= 1) { return; } // Sort points by x coordinate std::sort(rectPoints.begin(), rectPoints.end(), [](auto a, auto b) { if (a.x == b.x) return a.y < b.y; return a.x < b.x; }); Vec normal = (rectPoints.back() - rectPoints.front()).cross(); Vec left = rectPoints.front(); std::vector<Vec> poly; // Copy points placed below the first->last line auto beg = std::copy_if(rectPoints.begin(), rectPoints.end(), std::back_inserter(poly), [&normal, &left](auto p) { return normal * (left - p) >= 0; }); // Copy points placed above first->last line std::copy_if(rectPoints.rbegin(), rectPoints.rend(), beg, [&normal, &left](auto p) { return normal * (left - p) < 0; }); // Even-odd rule for polygon rasterization std::function<bool(Vec&)> isPointInPath = [&poly](Vec& p) -> bool { size_t num = poly.size(); size_t end = num - 1; bool res = false; for (size_t i = 0; i < num; i++) { // p.y is between i and end points bool c1 = (poly[i].y > p.y) != (poly[end].y > p.y); Vec diff = poly[end] - poly[i]; if (c1 && ((poly[i].x * diff.y + diff.x * (p - poly[i]).y > p.x * diff.y) == (diff.y > 0))) { res = !res; } end = i; } return res; }; // Rasterize polygon for (int y = 0; y < mask.sizeY; y++) { for (int x = 0; x < mask.sizeX; x++) { mask.set(x, y, mask.get(x, y) || isPointInPath(Vec(x, y))); } } } void SmartRefinement::refine(BBox3D &bbox) { startNewLabeling(PATCH_TYPE_TEMP); setPrimaryLabel(); // transform seed points for (VoxelPosition &seedPoint : seedPoints_) seedPoint = { seedPoint[0] - bbox[0][0], seedPoint[1] - bbox[0][1] }; const int height = bbox[1][1] - bbox[0][1], width = bbox[1][0] - bbox[0][0]; const int z = bbox[0][2]; Matrix2D<bool> mask(width, height); Matrix2D<bool> trustedMask(width, height); // load mask for (int y = 0; y <= height; y++) for (int x = 0; x <= width; x++) { mask.set( x, y, isLabeled(x + bbox[0][0], y + bbox[0][1], z) ); trustedMask.set( x, y, isLabeled(x + bbox[0][0], y + bbox[0][1], z) ); } for (const auto& p : smartBrushMarkedVoxels_) { const int x = p[0] - bbox[0][0]; const int y = p[1] - bbox[0][1]; if (x < 0 || y < 0 || x > width || y > height) continue; mask.set(x, y, true); trustedMask.set(x, y, true); } complementMask(mask); Matrix2D<bool> result(width, height); Matrix2D<double> sliceImage(width, height); NormalizationParameters initialSliceNorm; NormalizeImage(bbox, sliceImage, initialSliceNorm); initLSM(sliceImage, mask); refineSlice(sliceImage, mask, trustedMask, result); mask.fill(false); removeLeaks(mask, result); result_ = std::make_unique<Matrix2D<bool>>(mask); markMask(bbox[0], mask); // markMask(bbox[0], result); endNewLabeling(); //flushMarkedVoxels(); } void SmartRefinement::initLSM(const Matrix2D<double> &sliceImage, const Matrix2D<bool> &mask) { } // End of 'SmartRefinement::initLSM' function void SmartRefinement::refineSlice(const Matrix2D<double> &sliceImage, const Matrix2D<bool> &mask, const Matrix2D<bool> &trustedMask, Matrix2D<bool> &result) { /*Matrix2D<double> densityField(sliceImage.sizeX, sliceImage.sizeY); const double threshold = calcThreshold(sliceImage, mask); const double eps = calcEps(sliceImage, threshold, mask); initDensityField(sliceImage, eps, threshold, densityField); GeneralLevelSet lsm_ = GeneralLevelSet(sliceImage.sizeX, sliceImage.sizeY); lsm_.setAlpha(0.75); lsm_.setIterationsDivider(1); std::cout << "threshold: " << threshold << std::endl; std::cout << "eps: " << eps << std::endl; lsm_.run(densityField, mask, result);*/ lsm_.resize(sliceImage.sizeX, sliceImage.sizeY); // lsm_.setTheta(50); // lsm_.setEuclIncrease(10); std::cout << "I am being refined over here" << std::endl; //lsm_.setLambda(std::exp(sensitivity_ * 10.0)); //lsm_.setEuclIncrease(std::exp(sensitivity_ * 2.0)); lsm_.setInputSlice(sliceImage); lsm_.setMaxIterations(100); // If mask is passed instead of trustedMask, then area between clicks will be filled lsm_.run(sliceImage, trustedMask, result, [&trustedMask, &mask, this]() -> double { return lsm_.calculateC(trustedMask); //return c; //double c1 = lsm_.calculateC(trustedMask); //double c2 = lsm_.calculateC(mask); //const double alpha = sensitivity_; //return c1 * alpha + c2 * (1 - alpha); }); } double SmartRefinement::calcEps(const Matrix2D<double> &sliceImage, const double threshold, const Matrix2D<bool> &mask) { NormalizedIntensityHistogram<255> hist; double max = std::numeric_limits<double>::min(); for (int y = 0; y < sliceImage.sizeY; y++) { for (int x = 0; x < sliceImage.sizeX; x++) { if (mask.get(x, y)) { const double dist = fabs(sliceImage.get(x, y) - threshold); hist.add(dist); max = std::max(max, dist); } } } hist.normalize(); std::cout << "quantile: " << hist.quantile(0.85) << std::endl; std::cout << "max: " << max << std::endl; return hist.quantile(0.85); } double SmartRefinement::calcThreshold(const Matrix2D<double> &sliceImage, const Matrix2D<bool> &mask) { std::vector<double> intensities; for (int y = 0; y < sliceImage.sizeY; y++) { for (int x = 0; x < sliceImage.sizeX; x++) { if (mask.get(x, y)) { intensities.push_back(sliceImage.get(x, y)); } } } const auto median_it = intensities.begin() + intensities.size() / 2; std::nth_element(intensities.begin(), median_it, intensities.end()); if (&(*median_it) == nullptr) return -1; double median = *median_it; return median; } // End of '' function void SmartRefinement::initDensityField(const Matrix2D<double> &sliceImage, const double eps, const double thresh, Matrix2D<double> &dField) { for (int y = 0; y < dField.sizeY; y++) { for (int x = 0; x < dField.sizeX; x++) { double value = sliceImage.get(x, y); const double density = eps - fabs(value - thresh); dField.set(x, y, density); } } } // End of 'SmartRefinement::initDensityField' function void SmartRefinement::saveDist(const std::string &fileName) { printf("save distance\n"); saveImage(fileName, *lsm_.dist_); } // End of 'SmartRefinement::saveDist' function void SmartRefinement::saveMask(const std::string &fileName) { printf("save mask\n"); saveImage(fileName, *result_); startNewAnnotation(); } // End of 'SmartRefinement::saveMask' function void SmartRefinement::savePhi(const std::string &fileName) { printf("save phi\n"); saveImage(fileName, *lsm_.phi_); } // End of 'SmartRefinement::savePhi' function } // end of 'accessory' namespace } // end of 'vvt' namespace
37.968397
147
0.481391
pv6
5e59824552fc0d88437aa54cf513d0704cf47ee2
3,100
hpp
C++
src/stan/math/rev/core.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
src/stan/math/rev/core.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
src/stan/math/rev/core.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_REV_CORE_HPP #define STAN_MATH_REV_CORE_HPP #include <stan/math/rev/core/autodiffstackstorage.hpp> #include <stan/math/rev/core/build_vari_array.hpp> #include <stan/math/rev/core/chainable_alloc.hpp> #include <stan/math/rev/core/chainablestack.hpp> #include <stan/math/rev/core/init_chainablestack.hpp> #include <stan/math/rev/core/ddv_vari.hpp> #include <stan/math/rev/core/dv_vari.hpp> #include <stan/math/rev/core/dvd_vari.hpp> #include <stan/math/rev/core/dvv_vari.hpp> #include <stan/math/rev/core/empty_nested.hpp> #include <stan/math/rev/core/gevv_vvv_vari.hpp> #include <stan/math/rev/core/grad.hpp> #include <stan/math/rev/core/matrix_vari.hpp> #include <stan/math/rev/core/nested_size.hpp> #include <stan/math/rev/core/operator_addition.hpp> #include <stan/math/rev/core/operator_divide_equal.hpp> #include <stan/math/rev/core/operator_division.hpp> #include <stan/math/rev/core/operator_equal.hpp> #include <stan/math/rev/core/operator_greater_than.hpp> #include <stan/math/rev/core/operator_greater_than_or_equal.hpp> #include <stan/math/rev/core/operator_less_than.hpp> #include <stan/math/rev/core/operator_less_than_or_equal.hpp> #include <stan/math/rev/core/operator_logical_and.hpp> #include <stan/math/rev/core/operator_logical_or.hpp> #include <stan/math/rev/core/operator_minus_equal.hpp> #include <stan/math/rev/core/operator_multiplication.hpp> #include <stan/math/rev/core/operator_multiply_equal.hpp> #include <stan/math/rev/core/operator_not_equal.hpp> #include <stan/math/rev/core/operator_plus_equal.hpp> #include <stan/math/rev/core/operator_subtraction.hpp> #include <stan/math/rev/core/operator_unary_decrement.hpp> #include <stan/math/rev/core/operator_unary_increment.hpp> #include <stan/math/rev/core/operator_unary_negative.hpp> #include <stan/math/rev/core/operator_unary_not.hpp> #include <stan/math/rev/core/operator_unary_plus.hpp> #include <stan/math/rev/core/precomp_v_vari.hpp> #include <stan/math/rev/core/precomp_vv_vari.hpp> #include <stan/math/rev/core/precomp_vvv_vari.hpp> #include <stan/math/rev/core/precomputed_gradients.hpp> #include <stan/math/rev/core/print_stack.hpp> #include <stan/math/rev/core/recover_memory.hpp> #include <stan/math/rev/core/recover_memory_nested.hpp> #include <stan/math/rev/core/set_zero_all_adjoints.hpp> #include <stan/math/rev/core/set_zero_all_adjoints_nested.hpp> #include <stan/math/rev/core/start_nested.hpp> #include <stan/math/rev/core/std_isinf.hpp> #include <stan/math/rev/core/std_isnan.hpp> #include <stan/math/rev/core/std_numeric_limits.hpp> #include <stan/math/rev/core/stored_gradient_vari.hpp> #include <stan/math/rev/core/v_vari.hpp> #include <stan/math/rev/core/var.hpp> #include <stan/math/rev/core/vari.hpp> #include <stan/math/rev/core/vd_vari.hpp> #include <stan/math/rev/core/vdd_vari.hpp> #include <stan/math/rev/core/vdv_vari.hpp> #include <stan/math/rev/core/vector_vari.hpp> #include <stan/math/rev/core/vv_vari.hpp> #include <stan/math/rev/core/vvd_vari.hpp> #include <stan/math/rev/core/vvv_vari.hpp> #endif
47.692308
65
0.785806
alashworth
5e5bc38c68e2b2a36041f55727630c8942e686e4
1,337
cc
C++
solutions/cses/dp/1097.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
4
2020-11-07T14:38:02.000Z
2022-01-03T19:02:36.000Z
solutions/cses/dp/1097.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
1
2019-04-17T06:55:14.000Z
2019-04-17T06:55:14.000Z
solutions/cses/dp/1097.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
null
null
null
#include <stdio.h> #include <algorithm> #include <array> #include <bitset> #include <cassert> #include <climits> #include <cmath> #include <deque> #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <numeric> #include <queue> #include <set> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; typedef long long ll; typedef long double ld; int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int n; cin >> n; vector<int> x(n); for (int& i : x) { cin >> i; } vector<vector<ll>> dp(n, vector<ll>(n)); for (int i = n - 1; i >= 0; --i) { for (int j = i; j < n; ++j) { if (i == j) { dp[i][j] = x[i]; } else { dp[i][j] = max(x[i] - dp[i + 1][j], x[j] - dp[i][j - 1]); } } } cout << (accumulate(x.begin(), x.end(), 0ll) + dp[0][n - 1]) / 2; // Alternative DP solution // for (int i = n - 1; i >= 0; --i) { // for (int j = i; j < n; ++j) { // if (i == j) { // dp[i][j] = a[i]; // } else { // dp[i][j] = max( // a[i] + min(i + 2 < n ? dp[i + 2][j] : INT_MAX, dp[i + 1][j - 1]), // a[j] + min(dp[i + 1][j - 1], j - 2 >= 0 ? dp[i][j - 2] : // INT_MAX)); // } // } // } // cout << dp[0][n - 1]; }
20.890625
80
0.471952
zwliew
5e683509ed69e27ce1bc582e62270e503fe47f28
592
hpp
C++
include/rive/nested_animation.hpp
rive-app/rive-cpp
2cc9cc92868d468ca75f8b5fcc40ad1ec33d27b1
[ "MIT" ]
139
2020-08-17T20:10:24.000Z
2022-03-28T12:22:44.000Z
include/rive/nested_animation.hpp
rive-app/rive-cpp
2cc9cc92868d468ca75f8b5fcc40ad1ec33d27b1
[ "MIT" ]
89
2020-08-28T16:41:01.000Z
2022-03-28T19:10:49.000Z
include/rive/nested_animation.hpp
rive-app/rive-cpp
2cc9cc92868d468ca75f8b5fcc40ad1ec33d27b1
[ "MIT" ]
19
2020-10-19T00:54:40.000Z
2022-02-28T05:34:17.000Z
#ifndef _RIVE_NESTED_ANIMATION_HPP_ #define _RIVE_NESTED_ANIMATION_HPP_ #include "rive/generated/nested_animation_base.hpp" #include <stdio.h> namespace rive { class NestedAnimation : public NestedAnimationBase { public: StatusCode onAddedDirty(CoreContext* context) override; // Advance animations and apply them to the artboard. virtual void advance(float elapsedSeconds, Artboard* artboard) = 0; // Initialize the animation (make instances as necessary) from the // source artboard. virtual void initializeAnimation(Artboard* artboard) = 0; }; } // namespace rive #endif
28.190476
69
0.782095
rive-app
5e686496b797fb9ec22025e3d40802b44a013a21
10,688
cpp
C++
oneflow/core/framework/placement_sbp_util.cpp
Warmchay/oneflow
5a333ff065bb89990318de2f1bd650e314d49301
[ "Apache-2.0" ]
null
null
null
oneflow/core/framework/placement_sbp_util.cpp
Warmchay/oneflow
5a333ff065bb89990318de2f1bd650e314d49301
[ "Apache-2.0" ]
null
null
null
oneflow/core/framework/placement_sbp_util.cpp
Warmchay/oneflow
5a333ff065bb89990318de2f1bd650e314d49301
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 The OneFlow 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 "oneflow/core/framework/placement_sbp_util.h" #include "oneflow/core/common/shape.h" #include "oneflow/core/job/parallel_desc.h" #include "oneflow/core/job/sbp_parallel.cfg.h" #include "oneflow/core/common/decorator.h" #include "oneflow/core/common/optional.h" #include "oneflow/core/common/util.h" #include "oneflow/core/common/container_util.h" #include "oneflow/core/rpc/include/global_process_ctx.h" namespace oneflow { namespace { using IndexVector = DimVector; using StrideVector = DimVector; void GetStrideVector(const Shape& shape, StrideVector* strides) { strides->resize(shape.NumAxes()); for (int i = 0; i < shape.NumAxes(); ++i) { strides->at(i) = shape.Count(i + 1); } } Maybe<void> GetIndexesFromOffset(const StrideVector& strides, int64_t offset, IndexVector* indexes) { indexes->resize(strides.size()); for (int i = 0; i < strides.size(); ++i) { indexes->at(i) = offset / strides.at(i); offset = offset % strides.at(i); } CHECK_EQ_OR_RETURN(offset, 0); return Maybe<void>::Ok(); } Maybe<void> GetOffsetFromIndexes(const StrideVector& strides, const IndexVector& indexes, int64_t* offset) { CHECK_EQ_OR_RETURN(strides.size(), indexes.size()); *offset = 0; for (int i = 0; i < strides.size(); ++i) { *offset += indexes.at(i) * strides.at(i); } return Maybe<void>::Ok(); } Maybe<void> GetBroadcastIndex2OriginIndex( const IndexVector& indexes, const std::vector<bool>& dim2is_broadcast, std::function<void(const DimVector&, DimVector*)>* BroadcastIndex2OriginIndex) { CHECK_EQ_OR_RETURN(dim2is_broadcast.size(), indexes.size()); *BroadcastIndex2OriginIndex = [=](const DimVector& broadcast, DimVector* origin) { origin->resize(indexes.size()); for (int i = 0; i < indexes.size(); ++i) { origin->at(i) = dim2is_broadcast.at(i) ? broadcast.at(i) : indexes.at(i); } }; return Maybe<void>::Ok(); } Maybe<const Shape> GetBroadcastShape(const Shape& hierarchy_shape, const std::vector<bool>& dim2is_broadcast) { CHECK_EQ_OR_RETURN(hierarchy_shape.NumAxes(), dim2is_broadcast.size()); DimVector dim_vec = hierarchy_shape.dim_vec(); for (int i = 0; i < dim2is_broadcast.size(); ++i) { if (!dim2is_broadcast.at(i)) { dim_vec.at(i) = 1; } } return std::make_shared<const Shape>(dim_vec); } Maybe<Symbol<ParallelDesc>> GetBroadcastSubParallelDesc(const ParallelDesc& parallel_desc, const cfg::NdSbp& nd_sbp, int64_t parallel_id) { const auto& hierarchy_shape = *parallel_desc.hierarchy(); std::vector<bool> dim2is_broadcast(nd_sbp.sbp_parallel_size()); for (int i = 0; i < dim2is_broadcast.size(); ++i) { dim2is_broadcast.at(i) = nd_sbp.sbp_parallel(i).has_broadcast_parallel(); } const auto& broadcast_parallel_ids = JUST(GetBroadcastParallelIds(hierarchy_shape, dim2is_broadcast, parallel_id)); ParallelConf parallel_conf; parallel_conf.set_device_tag(parallel_desc.device_tag()); bool found_parallel_id = false; for (int64_t i : *broadcast_parallel_ids) { found_parallel_id = found_parallel_id || (i == parallel_id); int64_t machine_id = JUST(parallel_desc.MachineId4ParallelId(i)); int64_t device_id = JUST(parallel_desc.DeviceId4ParallelId(i)); parallel_conf.add_device_name(std::string("@") + std::to_string(machine_id) + ":" + std::to_string(device_id)); } CHECK_OR_RETURN(found_parallel_id); return SymbolOf(ParallelDesc(parallel_conf)); } } // namespace Maybe<Symbol<ParallelDesc>> GetBroadcastSubParallelDesc(Symbol<ParallelDesc> parallel_desc, Symbol<cfg::NdSbp> nd_sbp) { using PlacementSbp = std::pair<Symbol<ParallelDesc>, Symbol<cfg::NdSbp>>; static thread_local HashMap<PlacementSbp, Symbol<ParallelDesc>> map; const auto& key = std::make_pair(parallel_desc, nd_sbp); auto iter = map.find(key); if (iter == map.end()) { Optional<int64_t> opt_parallel_id; JUST(GetTensorDevice4CurrentProcessCtx(parallel_desc, &opt_parallel_id)); int64_t parallel_id = JUST(opt_parallel_id.value()); const auto& sub_parallel_desc = JUST(GetBroadcastSubParallelDesc(*parallel_desc, *nd_sbp, parallel_id)); iter = map.emplace(key, sub_parallel_desc).first; } return iter->second; } Maybe<std::vector<int64_t>> GetBroadcastParallelIds(const Shape& hierarchy_shape, const std::vector<bool>& dim2is_broadcast, int64_t parallel_id) { CHECK_EQ_OR_RETURN(hierarchy_shape.NumAxes(), dim2is_broadcast.size()); StrideVector hierarchy_strides{}; GetStrideVector(hierarchy_shape, &hierarchy_strides); IndexVector indexes{}; JUST(GetIndexesFromOffset(hierarchy_strides, parallel_id, &indexes)); std::function<void(const DimVector&, DimVector*)> BroadcastIndex2OriginIndex; JUST(GetBroadcastIndex2OriginIndex(indexes, dim2is_broadcast, &BroadcastIndex2OriginIndex)); const auto& broadcast_shape = JUST(GetBroadcastShape(hierarchy_shape, dim2is_broadcast)); StrideVector broadcast_strides{}; GetStrideVector(*broadcast_shape, &broadcast_strides); const auto& origin_offsets = std::make_shared<std::vector<int64_t>>(broadcast_shape->elem_cnt()); for (int64_t i = 0; i < broadcast_shape->elem_cnt(); ++i) { IndexVector broadcast_indexes{}; JUST(GetIndexesFromOffset(broadcast_strides, i, &broadcast_indexes)); IndexVector origin_indexes{}; BroadcastIndex2OriginIndex(broadcast_indexes, &origin_indexes); int64_t origin_offset = -1; JUST(GetOffsetFromIndexes(hierarchy_strides, origin_indexes, &origin_offset)); origin_offsets->at(i) = origin_offset; } return origin_offsets; } namespace { Maybe<std::unordered_map<int64_t, Symbol<ParallelDesc>>> CalcBroadcastGroup( Symbol<ParallelDesc> src_parallel_desc, Symbol<ParallelDesc> dst_parallel_desc, bool allow_across_node) { CHECK_EQ_OR_RETURN(src_parallel_desc->parallel_num(), src_parallel_desc->sorted_machine_ids().size()); CHECK_EQ_OR_RETURN(dst_parallel_desc->parallel_num(), dst_parallel_desc->sorted_machine_ids().size()); CHECK_EQ_OR_RETURN(src_parallel_desc->device_type(), dst_parallel_desc->device_type()); CHECK_LE_OR_RETURN(src_parallel_desc->parallel_num(), dst_parallel_desc->parallel_num()); const auto& src_process_ids = src_parallel_desc->sorted_machine_ids(); HashMap<int64_t, std::vector<int64_t>> process_id2group{}; HashMap<int64_t, std::vector<int64_t>> node_id2src_process_id{}; for (int64_t process_id : src_process_ids) { std::vector<int64_t> vec{process_id}; CHECK_OR_RETURN(process_id2group.emplace(process_id, vec).second); CHECK_OR_RETURN(dst_parallel_desc->ContainingMachineId(process_id)); node_id2src_process_id[GlobalProcessCtx::NodeId(process_id)].push_back(process_id); } std::vector<int64_t> remainder_process_ids{}; remainder_process_ids.reserve(dst_parallel_desc->sorted_machine_ids().size()); HashMap<int64_t, int64_t> node_id2counter{}; for (int64_t process_id : dst_parallel_desc->sorted_machine_ids()) { if (!src_parallel_desc->ContainingMachineId(process_id)) { const auto& node_iter = node_id2src_process_id.find(GlobalProcessCtx::NodeId(process_id)); if (node_iter == node_id2src_process_id.end()) { CHECK_OR_RETURN(allow_across_node) << Error::UnimplementedError() << "\n----[src_placement]----\n" << src_parallel_desc->parallel_conf().DebugString() << "\n----[dst_placement]----\n" << dst_parallel_desc->parallel_conf().DebugString(); // handle `process_id` later. remainder_process_ids.push_back(process_id); } else { // balancedly put `process_id` into the groups within the same node.. int64_t node_id = node_iter->first; const auto& src_process_ids = node_iter->second; int64_t src_process_index = (node_id2counter[node_id]++) % src_process_ids.size(); int64_t src_process_id = src_process_ids.at(src_process_index); JUST(MutMapAt(&process_id2group, src_process_id))->push_back(process_id); } } } // put remainder process ids into src groups. for (int i = 0; i < remainder_process_ids.size(); ++i) { int64_t src_process_id = src_process_ids.at(i % src_process_ids.size()); JUST(MutMapAt(&process_id2group, src_process_id))->push_back(remainder_process_ids.at(i)); } const auto& map = std::make_shared<std::unordered_map<int64_t, Symbol<ParallelDesc>>>(); for (const auto& pair : process_id2group) { const auto& group = pair.second; ParallelConf parallel_conf; parallel_conf.set_device_tag(dst_parallel_desc->parallel_conf().device_tag()); for (int64_t process_id : group) { const auto& device_ids = dst_parallel_desc->sorted_dev_phy_ids(process_id); CHECK_EQ_OR_RETURN(device_ids.size(), 1); parallel_conf.add_device_name(std::string("@") + std::to_string(process_id) + ":" + std::to_string(device_ids.at(0))); } const auto& parallel_desc = SymbolOf(ParallelDesc(parallel_conf)); for (int64_t process_id : group) { CHECK_OR_RETURN(map->emplace(process_id, parallel_desc).second); } } return map; } auto* CachedBroadcastGroup = DECORATE(&CalcBroadcastGroup, ThreadLocal); } // namespace Maybe<std::unordered_map<int64_t, Symbol<ParallelDesc>>> GetBroadcastGroup( Symbol<ParallelDesc> src_parallel_desc, Symbol<ParallelDesc> dst_parallel_desc) { return CachedBroadcastGroup(src_parallel_desc, dst_parallel_desc, true); } Maybe<std::unordered_map<int64_t, Symbol<ParallelDesc>>> GetBroadcastGroupWithoutAcrossNode( Symbol<ParallelDesc> src_parallel_desc, Symbol<ParallelDesc> dst_parallel_desc) { return CachedBroadcastGroup(src_parallel_desc, dst_parallel_desc, false); } } // namespace oneflow
46.469565
99
0.711546
Warmchay
5e6d1eaa5f7d9cfa04f05a64b5fa55436d372cbf
5,620
cpp
C++
dist/two/type.cpp
raptoravis/two
4366fcf8b3072d0233eb8e1e91ac1105194f60f5
[ "Zlib" ]
578
2019-05-04T09:09:42.000Z
2022-03-27T23:02:21.000Z
dist/two/type.cpp
raptoravis/two
4366fcf8b3072d0233eb8e1e91ac1105194f60f5
[ "Zlib" ]
14
2019-05-11T14:34:56.000Z
2021-02-02T07:06:46.000Z
dist/two/type.cpp
raptoravis/two
4366fcf8b3072d0233eb8e1e91ac1105194f60f5
[ "Zlib" ]
42
2019-05-11T16:04:19.000Z
2022-01-24T02:21:43.000Z
#include <two/infra.h> #include <two/type.h> #ifdef TWO_MODULES module two.obj; #else #endif namespace two { AnyHandler AnyHandler::none; } #ifdef TWO_MODULES module two.type; #else #endif namespace two { vector<Prototype*> g_prototypes = vector<Prototype*>(c_max_types); Prototype::Prototype(Type& type, span<Type*> parts) : m_type(type) , m_hash_parts(c_max_types) { g_prototypes[type.m_id] = this; for(Type* part : parts) this->add_part(*part); this->add_part(m_type); } void Prototype::add_part(Type& type) { Type* base = &type; while(base) { m_hash_parts[base->m_id] = m_parts.size(); base = base->m_base; } m_parts.push_back(&type); } } #ifndef TWO_CPP_20 #include <cstring> #include <cstdio> #endif #ifdef TWO_MODULES module two.obj; #else #include <stl/vector.h> #include <stl/string.h> //#include <ecs/Proto.h> #endif namespace two { bool Address::operator==(const Address& other) const { return strncmp(value, other.value, 16) == 0; } Index Index::me; static uint32_t s_type_index = 2; Type::Type(int) : m_id(1) , m_name("Type") {} Type::Type() : m_id(0) , m_name("") {} Type::Type(const char* name, size_t size) : m_id(s_type_index++) , m_name(name) , m_size(size) { //printf("[debug] Type %s %i\n", name, int(m_id)); if(strcmp(name, "INVALID") == 0) printf("[warning] Invalid type created, this means an lref was created for a type which isn't exported\n"); } Type::Type(const char* name, Type& base, size_t size) : Type(name, size) { m_base = &base; } Type::~Type() {} bool Type::is(const Type& type) const { if(&type == this) return true; else if(m_base) return m_base->is(type); else return false; } } #ifndef USE_STL #ifdef TWO_MODULES module two.math; #else #include <stl/vector.hpp> #include <stl/unordered_set.hpp> #include <stl/unordered_map.hpp> #endif namespace stl { using namespace two; template class TWO_TYPE_EXPORT vector<string>; template class TWO_TYPE_EXPORT vector<Type*>; template class TWO_TYPE_EXPORT vector<Prototype*>; template class TWO_TYPE_EXPORT buf<Var>; template class TWO_TYPE_EXPORT buffer<Var>; template class TWO_TYPE_EXPORT vector<Var>; template class TWO_TYPE_EXPORT vector<Ref>; template class TWO_TYPE_EXPORT vector<void(*)(Ref, Ref)>; template class TWO_TYPE_EXPORT vector<vector<void(*)(Ref, Ref)>>; template class TWO_TYPE_EXPORT vector<unique<Indexer>>; //template class TWO_TYPE_EXPORT unordered_set<string>; template class TWO_TYPE_EXPORT unordered_map<string, string>; } #endif #ifdef TWO_MODULES module two.type; #else #endif namespace two { // Exported types template <> TWO_TYPE_EXPORT Type& type<void*>() { static Type ty("void*", sizeof(void*)); return ty; } template <> TWO_TYPE_EXPORT Type& type<bool>() { static Type ty("bool", sizeof(bool)); return ty; } template <> TWO_TYPE_EXPORT Type& type<char>() { static Type ty("char", sizeof(char)); return ty; } template <> TWO_TYPE_EXPORT Type& type<schar>() { static Type ty("schar", sizeof(schar)); return ty; } template <> TWO_TYPE_EXPORT Type& type<short>() { static Type ty("short", sizeof(short)); return ty; } template <> TWO_TYPE_EXPORT Type& type<int>() { static Type ty("int", sizeof(int)); return ty; } template <> TWO_TYPE_EXPORT Type& type<long>() { static Type ty("long", sizeof(long)); return ty; } template <> TWO_TYPE_EXPORT Type& type<uchar>() { static Type ty("uchar", sizeof(uchar)); return ty; } template <> TWO_TYPE_EXPORT Type& type<ushort>() { static Type ty("ushort", sizeof(ushort)); return ty; } template <> TWO_TYPE_EXPORT Type& type<uint>() { static Type ty("uint", sizeof(uint)); return ty; } template <> TWO_TYPE_EXPORT Type& type<ulong>() { static Type ty("ulong", sizeof(ulong)); return ty; } template <> TWO_TYPE_EXPORT Type& type<ullong>() { static Type ty("ullong", sizeof(ullong)); return ty; } template <> TWO_TYPE_EXPORT Type& type<llong>() { static Type ty("llong", sizeof(llong)); return ty; } template <> TWO_TYPE_EXPORT Type& type<ldouble>() { static Type ty("ldouble", sizeof(ldouble)); return ty; } template <> TWO_TYPE_EXPORT Type& type<float>() { static Type ty("float", sizeof(float)); return ty; } template <> TWO_TYPE_EXPORT Type& type<double>() { static Type ty("double", sizeof(double)); return ty; } template <> TWO_TYPE_EXPORT Type& type<const char*>() { static Type ty("const char*", sizeof(const char*)); return ty; } template <> TWO_TYPE_EXPORT Type& type<stl::string>() { static Type ty("stl::string", sizeof(stl::string)); return ty; } template <> TWO_TYPE_EXPORT Type& type<void>() { static Type ty("void"); return ty; } template <> TWO_TYPE_EXPORT Type& type<stl::vector<stl::string>>() { static Type ty("vector<stl::string>", sizeof(stl::vector<stl::string>)); return ty; } template <> TWO_TYPE_EXPORT Type& type<stl::vector<two::Ref>>() { static Type ty("vector<two::Ref>", sizeof(stl::vector<two::Ref>)); return ty; } template <> TWO_TYPE_EXPORT Type& type<two::Ref>() { static Type ty("Ref", sizeof(two::Ref)); return ty; } template <> TWO_TYPE_EXPORT Type& type<two::Indexer>() { static Type ty("Indexer", sizeof(two::Indexer)); return ty; } template <> TWO_TYPE_EXPORT Type& type<two::Index>() { static Type ty("Index", sizeof(two::Index)); return ty; } template <> TWO_TYPE_EXPORT Type& type<two::Var>() { static Type ty("Var", sizeof(two::Var)); return ty; } template <> TWO_TYPE_EXPORT Type& type<two::Prototype>() { static Type ty("Prototype", sizeof(two::Prototype)); return ty; } }
31.931818
158
0.682028
raptoravis
5e6e42425dcad7b83032aa5639e9bd1c2b6eb83e
2,268
cpp
C++
world/seasons/source/SeasonFactory.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
world/seasons/source/SeasonFactory.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
world/seasons/source/SeasonFactory.cpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include "SeasonFactory.hpp" #include "Spring.hpp" #include "Summer.hpp" #include "Autumn.hpp" #include "Winter.hpp" using namespace std; SeasonSerializationMap SeasonFactory::season_map; SeasonFactory::SeasonFactory() { } SeasonFactory::~SeasonFactory() { } ISeasonPtr SeasonFactory::create_season(const Season season) { ISeasonPtr new_season; switch(season) { case Season::SEASON_SPRING: new_season = std::make_unique<Spring>(); break; case Season::SEASON_SUMMER: new_season = std::make_unique<Summer>(); break; case Season::SEASON_AUTUMN: new_season = std::make_unique<Autumn>(); break; case Season::SEASON_WINTER: default: new_season = std::make_unique<Winter>(); break; } return new_season; } ISeasonPtr SeasonFactory::create_season(const ClassIdentifier ci) { ISeasonPtr season; if (season_map.empty()) { initialize_season_map(); } SeasonSerializationMap::iterator s_it = season_map.find(ci); if (s_it != season_map.end()) { season = ISeasonPtr(s_it->second->clone()); } return season; } ISeasonPtr SeasonFactory::create_season(const uint month_of_year) { ISeasonPtr season; set<Season> seasons = {Season::SEASON_SPRING, Season::SEASON_SUMMER, Season::SEASON_AUTUMN, Season::SEASON_WINTER}; for (Season cur_season_enum : seasons) { ISeasonPtr cur_season = create_season(cur_season_enum); set<Months> months = cur_season->get_months_in_season(); if (months.find(static_cast<Months>(month_of_year)) != months.end()) { season = ISeasonPtr(cur_season->clone()); break; } } return season; } void SeasonFactory::initialize_season_map() { season_map.clear(); ISeasonPtr spring = std::make_unique<Spring>(); ISeasonPtr summer = std::make_unique<Summer>(); ISeasonPtr autumn = std::make_unique<Autumn>(); ISeasonPtr winter = std::make_unique<Winter>(); season_map.insert(make_pair(ClassIdentifier::CLASS_ID_SPRING, std::move(spring))); season_map.insert(make_pair(ClassIdentifier::CLASS_ID_SUMMER, std::move(summer))); season_map.insert(make_pair(ClassIdentifier::CLASS_ID_AUTUMN, std::move(autumn))); season_map.insert(make_pair(ClassIdentifier::CLASS_ID_WINTER, std::move(winter))); }
23.873684
117
0.715608
prolog
5e703cdd9ca2cb7d95d7f6c206ba3cfc36a709ea
5,736
hpp
C++
game/quest/PC.hpp
miguelmig/LibM2
dad7591a885a421842851905dc2bc8bbd648ca20
[ "BSD-3-Clause" ]
null
null
null
game/quest/PC.hpp
miguelmig/LibM2
dad7591a885a421842851905dc2bc8bbd648ca20
[ "BSD-3-Clause" ]
null
null
null
game/quest/PC.hpp
miguelmig/LibM2
dad7591a885a421842851905dc2bc8bbd648ca20
[ "BSD-3-Clause" ]
1
2021-11-14T10:51:30.000Z
2021-11-14T10:51:30.000Z
/* This file belongs to the LibM2 library (http://github.com/imermcmaps/LibM2) * Copyright (c) 2013, iMer (www.imer.cc) * All rights reserved. * Licensed under the BSD 3-clause license (http://opensource.org/licenses/BSD-3-Clause) */ #ifndef __LIBM2_GAME_QUEST_HPP #define __LIBM2_GAME_QUEST_HPP #include "../stdInclude.hpp" #include "../CHARACTER.hpp" #include "RewardData.hpp" #include "QuestState.hpp" namespace libm2 { namespace quest { class PC { public: class TQuestStateChangeInfo { DWORD quest_idx; int prev_state; int next_state; public: TQuestStateChangeInfo(DWORD, int, int); }; private: std::vector<quest::PC::TQuestStateChangeInfo, std::allocator<quest::PC::TQuestStateChangeInfo> > m_QuestStateChange; std::vector<quest::RewardData, std::allocator<quest::RewardData> > m_vRewardData; bool m_bIsGivenReward; bool m_bShouldSendDone; DWORD m_dwID; std::map<unsigned int, quest::QuestState, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, quest::QuestState> > > m_QuestInfo; quest::QuestState *m_RunningQuestState; std::string m_stCurQuest; std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> > const, int> > > m_FlagMap; std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> > const, int> > > m_FlagSaveMap; std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, boost::intrusive_ptr<event>, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> > const, boost::intrusive_ptr<event> > > > m_TimerMap; int m_iSendToClient; bool m_bLoaded; int m_iLastState; DWORD m_dwWaitConfirmFromPID; bool m_bConfirmWait; public: PC(void); ~PC(); void Destroy(void); void SetID(DWORD); DWORD GetID(void); bool HasQuest(const std::string &); quest::QuestState & GetQuest(const std::string &); std::_Rb_tree_iterator<std::pair<unsigned int const, quest::QuestState> > quest_begin(void); std::_Rb_tree_iterator<std::pair<unsigned int const, quest::QuestState> > quest_end(void); std::_Rb_tree_iterator<std::pair<unsigned int const, quest::QuestState> > quest_find(DWORD); bool IsRunning(void); void EndRunning(void); void CancelRunning(void); quest::QuestState * GetRunningQuestState(void); void SetQuest(const std::string &, quest::QuestState &); void SetCurrentQuestStateName(const std::string &); void SetQuestState(const std::string &, const std::string &); void SetQuestState(const std::string &, int); void SetQuestState(const char *, const char *); void ClearQuest(const std::string &); private: void AddQuestStateChange(const std::string &, int, int); void DoQuestStateChange(void); public: void SetFlag(const std::string &, int, bool); int GetFlag(const std::string &); bool DeleteFlag(const std::string &); const std::string & GetCurrentQuestName(void) const; int GetCurrentQuestIndex(void); void RemoveTimer(const std::string &); void RemoveTimerNotCancel(const std::string &); void AddTimer(const std::string &, LPEVENT); void ClearTimer(void); void SetCurrentQuestStartFlag(void); void SetCurrentQuestDoneFlag(void); void SetQuestTitle(const std::string &, const std::string &); void SetCurrentQuestTitle(const std::string &); void SetCurrentQuestClockName(const std::string &); void SetCurrentQuestClockValue(int); void SetCurrentQuestCounterName(const std::string &); void SetCurrentQuestCounterValue(int); void SetCurrentQuestIconFile(const std::string &); bool IsLoaded(void) const; void SetLoaded(void); void Build(void); void Save(void); bool HasReward(void); void Reward(LPCHARACTER); void GiveItem(const std::string &, DWORD, int); void GiveExp(const std::string &, DWORD); void SetSendDoneFlag(void); bool GetAndResetDoneFlag(void); void SendFlagList(LPCHARACTER); void SetConfirmWait(DWORD); void ClearConfirmWait(void); bool IsConfirmWait(void) const; bool IsConfirmWait(DWORD) const; private: void SetSendFlag(int); void ClearSendFlag(void); void SaveFlag(const std::string &, int); void ClearCurrentQuestBeginFlag(void); void SetCurrentQuestBeginFlag(void); int GetCurrentQuestBeginFlag(void); void SendQuestInfoPakcet(void); }; } } #endif // __LIBM2_GAME_QUEST_HPP
49.025641
354
0.614017
miguelmig
5e704717d60453d3b88d72c0f87bfadb9c7113f7
1,280
hh
C++
util/bufferreader.hh
drewnoakes/bold-humanoid
6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335
[ "Apache-2.0" ]
null
null
null
util/bufferreader.hh
drewnoakes/bold-humanoid
6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335
[ "Apache-2.0" ]
null
null
null
util/bufferreader.hh
drewnoakes/bold-humanoid
6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335
[ "Apache-2.0" ]
null
null
null
#pragma once #include <cstdint> // TODO endianness as a type param? eg: BufferReader<LittleEndian> // TODO read N bytes // TODO read string of N bytes (encoding?) // TODO test length and remaining namespace bold { class BufferReader { public: BufferReader(const char* ptr) : d_start(ptr), d_ptr(ptr) {} int8_t readInt8() { return static_cast<int8_t>(*d_ptr++); } uint8_t readInt8u() { return static_cast<uint8_t>(*d_ptr++); } int16_t readInt16() { auto val = *reinterpret_cast<const int16_t*>(d_ptr); d_ptr += sizeof(int16_t); return val; } uint16_t readInt16u() { auto val = *reinterpret_cast<const uint16_t*>(d_ptr); d_ptr += sizeof(uint16_t); return val; } int32_t readInt32() { auto val = *reinterpret_cast<const int32_t*>(d_ptr); d_ptr += sizeof(int32_t); return val; } uint32_t readInt32u() { auto val = *reinterpret_cast<const uint32_t*>(d_ptr); d_ptr += sizeof(uint32_t); return val; } void skip(size_t num) { d_ptr += num; } size_t pos() { return d_ptr - d_start; } private: const char* const d_start; const char* d_ptr; }; }
17.297297
66
0.582031
drewnoakes
5e72592f1eabbbc9a0c9a14c97531d4fc154e159
4,891
cc
C++
verilog/analysis/checkers/numeric_format_string_style_rule.cc
imphil/verible
cc9ec78b29e2e0190f6244a7d8981a2a90d77d79
[ "Apache-2.0" ]
487
2019-11-07T02:16:12.000Z
2021-07-08T14:44:12.000Z
verilog/analysis/checkers/numeric_format_string_style_rule.cc
hzeller/verible
c926ededf7953febb5f577b081474987d0f0209d
[ "Apache-2.0" ]
704
2019-11-12T18:00:12.000Z
2021-07-08T08:21:31.000Z
verilog/analysis/checkers/numeric_format_string_style_rule.cc
hzeller/verible
c926ededf7953febb5f577b081474987d0f0209d
[ "Apache-2.0" ]
96
2019-11-12T06:21:03.000Z
2021-07-06T23:20:39.000Z
// Copyright 2017-2020 The Verible 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 "verilog/analysis/checkers/numeric_format_string_style_rule.h" #include <set> #include <string> #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "common/analysis/lint_rule_status.h" #include "common/analysis/token_stream_lint_rule.h" #include "common/strings/naming_utils.h" #include "common/text/token_info.h" #include "verilog/analysis/descriptions.h" #include "verilog/analysis/lint_rule_registry.h" #include "verilog/parser/verilog_lexer.h" #include "verilog/parser/verilog_token_classifications.h" #include "verilog/parser/verilog_token_enum.h" namespace verilog { namespace analysis { using verible::LintRuleStatus; using verible::LintViolation; using verible::TokenInfo; using verible::TokenStreamLintRule; // Register the lint rule VERILOG_REGISTER_LINT_RULE(NumericFormatStringStyleRule); static const char kMessage[] = "Formatting string must contain proper style-compilant numeric specifiers."; const LintRuleDescriptor& NumericFormatStringStyleRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "numeric-format-string-style", .topic = "number-formatting", .desc = "Checks that string literals with numeric format specifiers " "have proper prefixes for hex and bin values and no prefixes for " "decimal values.", }; return d; } template <typename T> class TD; void NumericFormatStringStyleRule::CheckAndReportViolation( const TokenInfo& token, size_t pos, size_t len, std::initializer_list<unsigned char> prefixes) { const absl::string_view text(token.text()); // Check for prefix if (pos >= 2 && (text[pos - 2] == '0' || text[pos - 2] == '\'')) { const auto ch = text[pos - 1]; if (std::none_of(prefixes.begin(), prefixes.end(), [&ch](const char& _ch) { return _ch == ch; })) { // Report whole prefix with a "0" or "'" violations_.insert(LintViolation( TokenInfo(token.token_enum(), text.substr(pos - 2, len + 2)), kMessage)); } } else { // Report just radix violations_.insert(LintViolation( TokenInfo(token.token_enum(), text.substr(pos, len)), kMessage)); } } void NumericFormatStringStyleRule::HandleToken(const TokenInfo& token) { const auto token_enum = static_cast<verilog_tokentype>(token.token_enum()); const absl::string_view text(token.text()); if (IsUnlexed(verilog_tokentype(token.token_enum()))) { // recursively lex to examine inside macro definition bodies, etc. RecursiveLexText( text, [this](const TokenInfo& subtoken) { HandleToken(subtoken); }); return; } if (token_enum != TK_StringLiteral) return; for (size_t pos = 0; pos < text.size();) { const auto& ch = text[pos]; // Skip ordinary characters if (ch != '%') { ++pos; continue; } // Examine formatting directive for (size_t itr = pos + 1; itr < text.size(); ++itr) { // Skip field with display data size if (absl::ascii_isdigit(text[itr])) continue; const auto radix = text[itr]; const auto len = itr - pos + 1; // Format radix switch (radix) { // binary value case 'b': case 'B': { CheckAndReportViolation(token, pos, len, {'b'}); break; } // hexdecimal value case 'h': case 'H': case 'x': case 'X': { CheckAndReportViolation(token, pos, len, {'h', 'x'}); break; } // decimal value case 'd': case 'D': { // Detect prefixes starting with "0" and "'" if (pos >= 2 && (text[pos - 2] == '0' || text[pos - 2] == '\'')) { // Report whole string with a "0" or "'" violations_.insert(LintViolation( TokenInfo(token.token_enum(), text.substr(pos - 2, len + 2)), kMessage)); } break; } default: break; } // continue with the following character pos = itr + 1; break; } } } LintRuleStatus NumericFormatStringStyleRule::Report() const { return LintRuleStatus(violations_, GetDescriptor()); } } // namespace analysis } // namespace verilog
30.191358
80
0.645062
imphil
5e73977de01edda429bf31620ef17ccf67aad6d5
3,568
cpp
C++
day18a.cpp
Fossegrimen/advent-of-code
d9323346c167435fe461214e9eae990a1940c78e
[ "MIT" ]
null
null
null
day18a.cpp
Fossegrimen/advent-of-code
d9323346c167435fe461214e9eae990a1940c78e
[ "MIT" ]
null
null
null
day18a.cpp
Fossegrimen/advent-of-code
d9323346c167435fe461214e9eae990a1940c78e
[ "MIT" ]
null
null
null
#include <iostream> #include <queue> #include <sstream> #include <stack> #include <string> #include <vector> typedef std::queue<char> OutputQueue; typedef std::stack<char> OperatorStack; typedef std::vector<char> TokenList; void shuntingYardAlgorithm(const TokenList& tokens, OutputQueue& outputQueue); uint64_t evalReversePolishNotation(OutputQueue& outputQueue); int main() { uint64_t sum = 0; std::string line; while (std::getline(std::cin, line)) { TokenList tokens; std::stringstream _line(line); char token; while (_line >> token) { tokens.push_back(token); } OutputQueue outputQueue; shuntingYardAlgorithm(tokens, outputQueue); sum += evalReversePolishNotation(outputQueue); } std::cout << sum << std::endl; return 0; } void shuntingYardAlgorithm(const TokenList& tokens, OutputQueue& outputQueue) { OperatorStack operatorStack; for (char token : tokens) { switch (token) { case '+': { while (!operatorStack.empty() && (operatorStack.top() == '+' || operatorStack.top() == '*') && operatorStack.top() != '(') { outputQueue.push(operatorStack.top()); operatorStack.pop(); } operatorStack.push('+'); break; } case '*': { while (!operatorStack.empty() && (operatorStack.top() == '+' || operatorStack.top() == '*') && operatorStack.top() != '(') { outputQueue.push(operatorStack.top()); operatorStack.pop(); } operatorStack.push('*'); break; } case ')': { while (operatorStack.top() != '(') { outputQueue.push(operatorStack.top()); operatorStack.pop(); } if (operatorStack.empty()) { exit(1); } operatorStack.pop(); break; } case '(': { operatorStack.push('('); break; } default: { outputQueue.push(token); break; } } } while (!operatorStack.empty()) { outputQueue.push(operatorStack.top()); operatorStack.pop(); } } uint64_t evalReversePolishNotation(OutputQueue& outputQueue) { std::stack<uint64_t> outputStack; while (!outputQueue.empty()) { const char token = outputQueue.front(); outputQueue.pop(); if (token != '+' && token != '*') { outputStack.push(token - '0'); } else { const uint64_t a = outputStack.top(); outputStack.pop(); const uint64_t b = outputStack.top(); outputStack.pop(); switch (token) { case '+': { outputStack.push(a + b); break; } case '*': { outputStack.push(a * b); break; } } } } return outputStack.top(); }
23.629139
84
0.43778
Fossegrimen
5e76666312e198d4bca69ff7c21fe85b79cf3922
2,169
cpp
C++
problems/codeforces/1520/f-guess-the-kth-zero/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
7
2020-10-15T22:37:10.000Z
2022-02-26T17:23:49.000Z
problems/codeforces/1520/f-guess-the-kth-zero/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
problems/codeforces/1520/f-guess-the-kth-zero/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define long int64_t #define DV(a) (" [" #a "=" + to_string(a) + "]") // ***** struct fenwick { int N; vector<int> tree; explicit fenwick(int N = 0) : N(N), tree(N + 1, 0) {} int sum(int i) { int sum = 0; while (i > 0) { sum += tree[i]; i -= i & -i; } return sum; } void add(int i, int n) { assert(i > 0); while (i <= N) { tree[i] += n; i += i & -i; } } int lower_bound(int n) { int i = 0; int bits = CHAR_BIT * sizeof(int) - __builtin_clz(N << 1); for (int j = 1 << bits; j; j >>= 1) { if (i + j <= N && tree[i + j] < n) { n -= tree[i + j]; i += j; } } return i + 1; } }; #define MAXN 200'010 #define MAX_QUERIES 60'000 int N, Q, queries_count = 0; int know[MAXN]; // how many ones initially in [1..n]. fenwick added; // how many ones in positions [1..r] int QUERY(int r) { queries_count++; assert(queries_count <= MAX_QUERIES); string s = "? 1 " + to_string(r); cout << s << endl; int ones; cin >> ones; return ones; } // how many ones in positions [1..r] int maybe_query(int r) { if (know[r] < 0) { int ones = QUERY(r); know[r] = ones - added.sum(r); } return know[r] + added.sum(r); } auto solve() { cin >> N >> Q; added = fenwick(N + 1); memset(know, 0xff, sizeof(know)); // -1 know[0] = 0; while (Q--) { int k; cin >> k; int L = 0, R = N + 1; while (L + 1 < R) { int M = (L + R) / 2; int ones = maybe_query(M); int zeros = M - ones; if (zeros >= k) { R = M; } else { L = M; } } assert(R <= N); string s = "! " + to_string(R); cout << s << endl; added.add(R, 1); } } // ***** int main() { ios::sync_with_stdio(false); solve(); cerr << "Queries: " << queries_count << endl; return 0; }
19.718182
66
0.420009
brunodccarvalho
5e7a9d6a3c0e5e060c1c63b7d3da15fb8ea4f4ff
483
hpp
C++
include/fcppt/container/tree/optional_ref_decl.hpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
include/fcppt/container/tree/optional_ref_decl.hpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
include/fcppt/container/tree/optional_ref_decl.hpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2016. // 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) #ifndef FCPPT_CONTAINER_TREE_OPTIONAL_REF_DECL_HPP_INCLUDED #define FCPPT_CONTAINER_TREE_OPTIONAL_REF_DECL_HPP_INCLUDED #include <fcppt/reference_decl.hpp> #include <fcppt/container/tree/optional_ref_fwd.hpp> #include <fcppt/optional/object_decl.hpp> #endif
30.1875
61
0.776398
vinzenz
5e7c817c6621a61112d7d514238a587961b91ffc
1,662
cpp
C++
LeetCode/C++/93. Restore IP Addresses.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
LeetCode/C++/93. Restore IP Addresses.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
LeetCode/C++/93. Restore IP Addresses.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
//backtracking //Runtime: 4 ms, faster than 80.26% of C++ online submissions for Restore IP Addresses. //Memory Usage: 7.1 MB, less than 26.58% of C++ online submissions for Restore IP Addresses. class Solution { public: vector<string> ans; string join(const string& s, vector<int>& split){ string ret = s; for(int i = split.size()-1; i >= 0; --i){ // cout << split[i] << " " << ret << endl; ret.insert(ret.begin()+split[i], '.'); } // cout << ret << endl; return ret; } bool isValid(string s){ //length == 0 or length > 3 if(s.empty() || s.size() > 3) return false; //length == 3 and >= 256 if(s.size() == 3 && stoi(s) >= 256) return false; //length > 1 and start with 0 if(s.size() > 1 && s[0] == '0') return false; return true; } void backtrack(string& s, int start, vector<int>& split){ if(split.size() == 3){ if(isValid(s.substr(split.back()))){ ans.push_back(join(s, split)); } }else{ for(int len = 1; len <= 3 && start + len < s.size(); ++len){ if(!isValid(s.substr(start, len))) continue; //now s[start:start+len-1] is valid //'.' will be the (start+len)th char split.push_back(start+len); backtrack(s, start+len, split); split.pop_back(); } } } vector<string> restoreIpAddresses(string s) { vector<int> split; backtrack(s, 0, split); return ans; } };
31.358491
92
0.484356
shreejitverma
5e7f18c28fca97ab25b2e639734e788486d458d9
1,530
inl
C++
Core/DianYing/Include/Dy/Meta/Information/Inline/DMetaMetarialInstanceTmp.inl
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
4
2019-03-17T19:46:54.000Z
2019-12-09T20:11:01.000Z
Core/DianYing/Include/Dy/Meta/Information/Inline/DMetaMetarialInstanceTmp.inl
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
null
null
null
Core/DianYing/Include/Dy/Meta/Information/Inline/DMetaMetarialInstanceTmp.inl
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
null
null
null
#ifndef GUARD_DY_META_INFORMATION_INLINE_DMETAMETARIALINSTANCETMP_INL #define GUARD_DY_META_INFORMATION_INLINE_DMETAMETARIALINSTANCETMP_INL /// /// MIT License /// Copyright (c) 2018-2019 Jongmin Yun /// /// 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 <Dy/Core/Resource/Type/Uniform/TUniformValue.h> #include <Dy/Helper/System/Assertion.h> namespace dy { template <EUniformVariableType TType> void PDyMaterialInstanceMetaInfo::InsertValue( PDyMaterialInstanceMetaInfo& ioMaterialInfo, const std::string& iSpecifier, const typename MDY_PRIVATE(UniformBinder)<TType>::ValueType& iValue) { const auto it = ioMaterialInfo.mUniformValues.find(iSpecifier); MDY_ASSERT_MSG_FORCE( it == ioMaterialInfo.mUniformValues.end(), "Initial uniform value's string must not be duplicated with others." ); // In case of success. auto [_, __] = ioMaterialInfo.mUniformValues.try_emplace ( iSpecifier, std::make_unique<TUniformValue<TType>>(-1, iValue) ); } } /// ::dy namespace #endif /// GUARD_DY_META_INFORMATION_INLINE_DMETAMETARIALINSTANCETMP_INL
34.772727
81
0.769281
liliilli
5e8033d6a5e8dbc6b5461d779d6109848849d550
15,005
cpp
C++
libs/yap/example/autodiff_library/BinaryOPNode.cpp
Talustus/boost_src
ffe074de008f6e8c46ae1f431399cf932164287f
[ "BSL-1.0" ]
32
2019-02-27T06:57:07.000Z
2021-08-29T10:56:19.000Z
third_party/boost/libs/yap/example/autodiff_library/BinaryOPNode.cpp
avplayer/cxxrpc
7049b4079fac78b3828e68f787d04d699ce52f6d
[ "BSL-1.0" ]
1
2019-03-04T11:21:00.000Z
2019-05-24T01:36:31.000Z
third_party/boost/libs/yap/example/autodiff_library/BinaryOPNode.cpp
avplayer/cxxrpc
7049b4079fac78b3828e68f787d04d699ce52f6d
[ "BSL-1.0" ]
5
2019-08-20T13:45:04.000Z
2022-03-01T18:23:49.000Z
/* * BinaryOPNode.cpp * * Created on: 6 Nov 2013 * Author: s0965328 */ #include "auto_diff_types.h" #include "BinaryOPNode.h" #include "PNode.h" #include "Stack.h" #include "Tape.h" #include "EdgeSet.h" #include "Node.h" #include "VNode.h" #include "OPNode.h" #include "ActNode.h" #include "EdgeSet.h" namespace AutoDiff { BinaryOPNode::BinaryOPNode(OPCODE op_, Node* left_, Node* right_):OPNode(op_,left_),right(right_) { } OPNode* BinaryOPNode::createBinaryOpNode(OPCODE op, Node* left, Node* right) { assert(left!=NULL && right!=NULL); OPNode* node = NULL; node = new BinaryOPNode(op,left,right); return node; } BinaryOPNode::~BinaryOPNode() { if(right->getType()!=VNode_Type) { delete right; right = NULL; } } void BinaryOPNode::inorder_visit(int level,ostream& oss){ if(left!=NULL){ left->inorder_visit(level+1,oss); } oss<<this->toString(level)<<endl; if(right!=NULL){ right->inorder_visit(level+1,oss); } } void BinaryOPNode::collect_vnodes(boost::unordered_set<Node*>& nodes,unsigned int& total){ total++; if (left != NULL) { left->collect_vnodes(nodes,total); } if (right != NULL) { right->collect_vnodes(nodes,total); } } void BinaryOPNode::eval_function() { assert(left!=NULL && right!=NULL); left->eval_function(); right->eval_function(); this->calc_eval_function(); } void BinaryOPNode::calc_eval_function() { double x = NaN_Double; double rx = SV->pop_back(); double lx = SV->pop_back(); switch (op) { case OP_PLUS: x = lx + rx; break; case OP_MINUS: x = lx - rx; break; case OP_TIMES: x = lx * rx; break; case OP_DIVID: x = lx / rx; break; case OP_POW: x = pow(lx,rx); break; default: cerr<<"op["<<op<<"] not yet implemented!!"<<endl; assert(false); break; } SV->push_back(x); } //1. visiting left if not NULL //2. then, visiting right if not NULL //3. calculating the immediate derivative hu and hv void BinaryOPNode::grad_reverse_0() { assert(left!=NULL && right != NULL); this->adj = 0; left->grad_reverse_0(); right->grad_reverse_0(); this->calc_grad_reverse_0(); } //right left - right most traversal void BinaryOPNode::grad_reverse_1() { assert(right!=NULL && left!=NULL); double r_adj = SD->pop_back()*this->adj; right->update_adj(r_adj); double l_adj = SD->pop_back()*this->adj; left->update_adj(l_adj); right->grad_reverse_1(); left->grad_reverse_1(); } void BinaryOPNode::calc_grad_reverse_0() { assert(left!=NULL && right != NULL); double l_dh = NaN_Double; double r_dh = NaN_Double; double rx = SV->pop_back(); double lx = SV->pop_back(); double x = NaN_Double; switch (op) { case OP_PLUS: x = lx + rx; l_dh = 1; r_dh = 1; break; case OP_MINUS: x = lx - rx; l_dh = 1; r_dh = -1; break; case OP_TIMES: x = lx * rx; l_dh = rx; r_dh = lx; break; case OP_DIVID: x = lx / rx; l_dh = 1 / rx; r_dh = -(lx) / pow(rx, 2); break; case OP_POW: if(right->getType()==PNode_Type){ x = pow(lx,rx); l_dh = rx*pow(lx,(rx-1)); r_dh = 0; } else{ assert(lx>0.0); //otherwise log(lx) is not defined in read number x = pow(lx,rx); l_dh = rx*pow(lx,(rx-1)); r_dh = pow(lx,rx)*log(lx); //this is for x1^x2 when x1=0 cause r_dh become +inf, however d(0^x2)/d(x2) = 0 } break; default: cerr<<"error op not impl"<<endl; break; } SV->push_back(x); SD->push_back(l_dh); SD->push_back(r_dh); } void BinaryOPNode::hess_reverse_0_init_n_in_arcs() { this->left->hess_reverse_0_init_n_in_arcs(); this->right->hess_reverse_0_init_n_in_arcs(); this->Node::hess_reverse_0_init_n_in_arcs(); } void BinaryOPNode::hess_reverse_1_clear_index() { this->left->hess_reverse_1_clear_index(); this->right->hess_reverse_1_clear_index(); this->Node::hess_reverse_1_clear_index(); } unsigned int BinaryOPNode::hess_reverse_0() { assert(this->left!=NULL && right!=NULL); if(index==0) { unsigned int lindex=0, rindex=0; lindex = left->hess_reverse_0(); rindex = right->hess_reverse_0(); assert(lindex!=0 && rindex !=0); II->set(lindex); II->set(rindex); double rx,rx_bar,rw,rw_bar; double lx,lx_bar,lw,lw_bar; double x,x_bar,w,w_bar; double r_dh, l_dh; right->hess_reverse_0_get_values(rindex,rx,rx_bar,rw,rw_bar); left->hess_reverse_0_get_values(lindex,lx,lx_bar,lw,lw_bar); switch(op) { case OP_PLUS: // cout<<"lindex="<<lindex<<"\trindex="<<rindex<<"\tI="<<I<<endl; x = lx + rx; // cout<<lx<<"\t+"<<rx<<"\t="<<x<<"\t\t"<<toString(0)<<endl; x_bar = 0; l_dh = 1; r_dh = 1; w = lw * l_dh + rw * r_dh; // cout<<lw<<"\t+"<<rw<<"\t="<<w<<"\t\t"<<toString(0)<<endl; w_bar = 0; break; case OP_MINUS: x = lx - rx; x_bar = 0; l_dh = 1; r_dh = -1; w = lw * l_dh + rw * r_dh; w_bar = 0; break; case OP_TIMES: x = lx * rx; x_bar = 0; l_dh = rx; r_dh = lx; w = lw * l_dh + rw * r_dh; w_bar = 0; break; case OP_DIVID: x = lx / rx; x_bar = 0; l_dh = 1/rx; r_dh = -lx/pow(rx,2); w = lw * l_dh + rw * r_dh; w_bar = 0; break; case OP_POW: if(right->getType()==PNode_Type) { x = pow(lx,rx); x_bar = 0; l_dh = rx*pow(lx,(rx-1)); r_dh = 0; w = lw * l_dh + rw * r_dh; w_bar = 0; } else { assert(lx>0.0); //otherwise log(lx) undefined in real number x = pow(lx,rx); x_bar = 0; l_dh = rx*pow(lx,(rx-1)); r_dh = pow(lx,rx)*log(lx); //log(lx) cause -inf when lx=0; w = lw * l_dh + rw * r_dh; w_bar = 0; } break; default: cerr<<"op["<<op<<"] not yet implemented!"<<endl; assert(false); break; } TT->set(x); TT->set(x_bar); TT->set(w); TT->set(w_bar); TT->set(l_dh); TT->set(r_dh); assert(TT->index == TT->index); index = TT->index; } return index; } void BinaryOPNode::hess_reverse_0_get_values(unsigned int i,double& x, double& x_bar, double& w, double& w_bar) { --i; // skip the r_dh (ie, dh/du) --i; // skip the l_dh (ie. dh/dv) w_bar = TT->get(--i); w = TT->get(--i); x_bar = TT->get(--i); x = TT->get(--i); } void BinaryOPNode::hess_reverse_1(unsigned int i) { n_in_arcs--; if(n_in_arcs==0) { assert(right!=NULL && left!=NULL); unsigned int rindex = II->get(--(II->index)); unsigned int lindex = II->get(--(II->index)); // cout<<"ri["<<rindex<<"]\tli["<<lindex<<"]\t"<<this->toString(0)<<endl; double r_dh = TT->get(--i); double l_dh = TT->get(--i); double w_bar = TT->get(--i); --i; //skip w double x_bar = TT->get(--i); --i; //skip x double lw_bar=0,rw_bar=0; double lw=0,lx=0; left->hess_reverse_1_get_xw(lindex,lw,lx); double rw=0,rx=0; right->hess_reverse_1_get_xw(rindex,rw,rx); switch(op) { case OP_PLUS: assert(l_dh==1); assert(r_dh==1); lw_bar += w_bar*l_dh; rw_bar += w_bar*r_dh; break; case OP_MINUS: assert(l_dh==1); assert(r_dh==-1); lw_bar += w_bar*l_dh; rw_bar += w_bar*r_dh; break; case OP_TIMES: assert(rx == l_dh); assert(lx == r_dh); lw_bar += w_bar*rx; lw_bar += x_bar*lw*0 + x_bar*rw*1; rw_bar += w_bar*lx; rw_bar += x_bar*lw*1 + x_bar*rw*0; break; case OP_DIVID: lw_bar += w_bar*l_dh; lw_bar += x_bar*lw*0 + x_bar*rw*-1/(pow(rx,2)); rw_bar += w_bar*r_dh; rw_bar += x_bar*lw*-1/pow(rx,2) + x_bar*rw*2*lx/pow(rx,3); break; case OP_POW: if(right->getType()==PNode_Type){ lw_bar += w_bar*l_dh; lw_bar += x_bar*lw*pow(lx,rx-2)*rx*(rx-1) + 0; rw_bar += w_bar*r_dh; assert(r_dh==0.0); rw_bar += 0; } else{ assert(lx>0.0); //otherwise log(lx) is not define in Real lw_bar += w_bar*l_dh; lw_bar += x_bar*lw*pow(lx,rx-2)*rx*(rx-1) + x_bar*rw*pow(lx,rx-1)*(rx*log(lx)+1); //cause log(lx)=-inf when rw_bar += w_bar*r_dh; rw_bar += x_bar*lw*pow(lx,rx-1)*(rx*log(lx)+1) + x_bar*rw*pow(lx,rx)*pow(log(lx),2); } break; default: cerr<<"op["<<op<<"] not yet implemented !"<<endl; assert(false); break; } double rx_bar = x_bar*r_dh; double lx_bar = x_bar*l_dh; right->update_x_bar(rindex,rx_bar); left->update_x_bar(lindex,lx_bar); right->update_w_bar(rindex,rw_bar); left->update_w_bar(lindex,lw_bar); this->right->hess_reverse_1(rindex); this->left->hess_reverse_1(lindex); } } void BinaryOPNode::hess_reverse_1_init_x_bar(unsigned int i) { TT->at(i-5) = 1; } void BinaryOPNode::update_x_bar(unsigned int i ,double v) { TT->at(i-5) += v; } void BinaryOPNode::update_w_bar(unsigned int i ,double v) { TT->at(i-3) += v; } void BinaryOPNode::hess_reverse_1_get_xw(unsigned int i,double& w,double& x) { w = TT->get(i-4); x = TT->get(i-6); } void BinaryOPNode::hess_reverse_get_x(unsigned int i,double& x) { x = TT->get(i-6); } void BinaryOPNode::nonlinearEdges(EdgeSet& edges) { for(list<Edge>::iterator it=edges.edges.begin();it!=edges.edges.end();) { Edge e = *it; if(e.a==this || e.b == this){ if(e.a == this && e.b == this) { Edge e1(left,left); Edge e2(right,right); Edge e3(left,right); edges.insertEdge(e1); edges.insertEdge(e2); edges.insertEdge(e3); } else { Node* o = e.a==this? e.b: e.a; Edge e1(left,o); Edge e2(right,o); edges.insertEdge(e1); edges.insertEdge(e2); } it = edges.edges.erase(it); } else { it++; } } Edge e1(left,right); Edge e2(left,left); Edge e3(right,right); switch(op) { case OP_PLUS: case OP_MINUS: //do nothing for linear operator break; case OP_TIMES: edges.insertEdge(e1); break; case OP_DIVID: edges.insertEdge(e1); edges.insertEdge(e3); break; case OP_POW: edges.insertEdge(e1); edges.insertEdge(e2); edges.insertEdge(e3); break; default: cerr<<"op["<<op<<"] not yet implmented !"<<endl; assert(false); break; } left->nonlinearEdges(edges); right->nonlinearEdges(edges); } #if FORWARD_ENABLED void BinaryOPNode::hess_forward(unsigned int len, double** ret_vec) { double* lvec = NULL; double* rvec = NULL; if(left!=NULL){ left->hess_forward(len,&lvec); } if(right!=NULL){ right->hess_forward(len,&rvec); } *ret_vec = new double[len]; hess_forward_calc0(len,lvec,rvec,*ret_vec); //delete lvec, rvec delete[] lvec; delete[] rvec; } void BinaryOPNode::hess_forward_calc0(unsigned int& len, double* lvec, double* rvec, double* ret_vec) { double hu = NaN_Double, hv= NaN_Double; double lval = NaN_Double, rval = NaN_Double; double val = NaN_Double; unsigned int index = 0; switch (op) { case OP_PLUS: rval = SV->pop_back(); lval = SV->pop_back(); val = lval + rval; SV->push_back(val); //calculate the first order derivatives for(unsigned int i=0;i<AutoDiff::num_var;++i) { ret_vec[i] = lvec[i]+rvec[i]; } //calculate the second order index = AutoDiff::num_var; for(unsigned int i=0;i<AutoDiff::num_var;++i) { for(unsigned int j=i;j<AutoDiff::num_var;++j){ ret_vec[index] = lvec[index] + 0 + rvec[index] + 0; ++index; } } assert(index==len); break; case OP_MINUS: rval = SV->pop_back(); lval = SV->pop_back(); val = lval + rval; SV->push_back(val); //calculate the first order derivatives for(unsigned int i=0;i<AutoDiff::num_var;++i) { ret_vec[i] = lvec[i] - rvec[i]; } //calculate the second order index = AutoDiff::num_var; for(unsigned int i=0;i<AutoDiff::num_var;++i) { for(unsigned int j=i;j<AutoDiff::num_var;++j){ ret_vec[index] = lvec[index] + 0 - rvec[index] + 0; ++index; } } assert(index==len); break; case OP_TIMES: rval = SV->pop_back(); lval = SV->pop_back(); val = lval * rval; SV->push_back(val); hu = rval; hv = lval; //calculate the first order derivatives for(unsigned int i =0;i<AutoDiff::num_var;++i) { ret_vec[i] = hu*lvec[i] + hv*rvec[i]; } //calculate the second order index = AutoDiff::num_var; for(unsigned int i=0;i<AutoDiff::num_var;++i) { for(unsigned int j=i;j<AutoDiff::num_var;++j) { ret_vec[index] = hu * lvec[index] + lvec[i] * rvec[j]+hv * rvec[index] + rvec[i] * lvec[j]; ++index; } } assert(index==len); break; case OP_POW: rval = SV->pop_back(); lval = SV->pop_back(); val = pow(lval,rval); SV->push_back(val); if(left->getType()==PNode_Type && right->getType()==PNode_Type) { std::fill_n(ret_vec,len,0); } else { hu = rval*pow(lval,(rval-1)); hv = pow(lval,rval)*log(lval); if(left->getType()==PNode_Type) { double coeff = pow(log(lval),2)*pow(lval,rval); //calculate the first order derivatives for(unsigned int i =0;i<AutoDiff::num_var;++i) { ret_vec[i] = hu*lvec[i] + hv*rvec[i]; } //calculate the second order index = AutoDiff::num_var; for(unsigned int i=0;i<AutoDiff::num_var;++i) { for(unsigned int j=i;j<AutoDiff::num_var;++j) { ret_vec[index] = 0 + 0 + hv * rvec[index] + rvec[i] * coeff * rvec[j]; ++index; } } } else if(right->getType()==PNode_Type) { double coeff = rval*(rval-1)*pow(lval,rval-2); //calculate the first order derivatives for(unsigned int i =0;i<AutoDiff::num_var;++i) { ret_vec[i] = hu*lvec[i] + hv*rvec[i]; } //calculate the second order index = AutoDiff::num_var; for(unsigned int i=0;i<AutoDiff::num_var;++i) { for(unsigned int j=i;j<AutoDiff::num_var;++j) { ret_vec[index] = hu*lvec[index] + lvec[i] * coeff * lvec[j] + 0 + 0; ++index; } } } else { assert(false); } } assert(index==len); break; case OP_SIN: //TODO should move to UnaryOPNode.cpp? assert(left!=NULL&&right==NULL); lval = SV->pop_back(); val = sin(lval); SV->push_back(val); hu = cos(lval); double coeff; coeff = -val; //=sin(left->val); -- and avoid cross initialisation //calculate the first order derivatives for(unsigned int i =0;i<AutoDiff::num_var;++i) { ret_vec[i] = hu*lvec[i] + 0; } //calculate the second order index = AutoDiff::num_var; for(unsigned int i=0;i<AutoDiff::num_var;++i) { for(unsigned int j=i;j<AutoDiff::num_var;++j) { ret_vec[index] = hu*lvec[index] + lvec[i] * coeff * lvec[j] + 0 + 0; ++index; } } assert(index==len); break; default: cerr<<"op["<<op<<"] not yet implemented!"; break; } } #endif string BinaryOPNode::toString(int level){ ostringstream oss; string s(level,'\t'); oss<<s<<"[BinaryOPNode]("<<op<<")"; return oss.str(); } } /* namespace AutoDiff */
23.013804
113
0.588937
Talustus
5e82025e8dadf298a606cd33e4afd6e015564838
962
cpp
C++
ITP1/ITP1_7D.cpp
taki-d/AizuOnlineJudgeAnswer
9ab2a6db91d9ea703081703b66ee5aaeb8ec0c31
[ "MIT" ]
2
2017-05-02T06:46:31.000Z
2017-06-18T21:59:05.000Z
ITP1/ITP1_7D.cpp
taki-d/AizuOnlineJudgeAnswer
9ab2a6db91d9ea703081703b66ee5aaeb8ec0c31
[ "MIT" ]
null
null
null
ITP1/ITP1_7D.cpp
taki-d/AizuOnlineJudgeAnswer
9ab2a6db91d9ea703081703b66ee5aaeb8ec0c31
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main() { int a,b,c; cin >> a >> b >> c; vector<vector<int>> A(a,vector<int>(b,0)); vector<vector<int>> B(b,vector<int>(c,0)); for (int d = 0; d < a; ++d) { for (int e = 0; e < b; ++e) { cin >> A.at(d).at(e); } } for (int f = 0; f < b; ++f) { for (int g = 0; g < c; ++g) { cin >> B.at(f).at(g); } } vector<vector<int>> Result(a,vector<int>(c,0)); for (int i = 0; i < a; ++i) { for (int k = 0; k < b; ++k) { for (int j = 0; j < c; ++j) { Result.at(i).at(j) += A.at(i).at(k) * B.at(k).at(j); } } } for (int l = 0; l < a; ++l) { for (int m = 0; m < c; ++m) { cout << Result.at(l).at(m); if(m != c -1){ cout << " "; } } cout << endl; } return 0; }
18.862745
68
0.351351
taki-d
5e83c1758508b791cb57a8fffdd64d222b9b10c4
16,013
cpp
C++
copasi/sedml/SEDMLUtils.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
null
null
null
copasi/sedml/SEDMLUtils.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
null
null
null
copasi/sedml/SEDMLUtils.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
null
null
null
// Copyright (C) 2019 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2013 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. /* * SEDMLUtils.cpp * * Created on: 15 Jul 2013 * Author: dada */ //#include <zip.h> #include <sstream> #include <iostream> #include <vector> #include "SEDMLUtils.h" #include <sedml/SedTypes.h> #include <sbml/SBMLTypes.h> #include "copasi/model/CModel.h" #include "copasi/CopasiDataModel/CDataModel.h" #include "copasi/core/CDataObject.h" std::string SEDMLUtils::findIdByNameAndType( const std::map<const CDataObject*, SBase*>& map, int typeCode, const std::string& name) { std::map<const CDataObject*, SBase*>::const_iterator it = map.begin(); std::string::size_type compartmentStart = name.find("{"); std::string compId; if (compartmentStart != std::string::npos) { std::string compName = name.substr(compartmentStart + 1, name.size() - compartmentStart - 2); SEDMLUtils::removeCharactersFromString(compName, "\""); compId = findIdByNameAndType(map, SBML_COMPARTMENT, compName); } while (it != map.end()) { SBase* current = it->second; const CDataObject* object = it->first; std::string displayName = object->getObjectDisplayName(); if (((current->getTypeCode() & typeCode) != typeCode)) { ++it; continue; } if (current->getName() == name) return current->getId(); if (typeCode == SBML_SPECIES && compartmentStart != std::string::npos) { if (displayName == name) { Species* species = static_cast<Species*>(current); if (species->getCompartment() == compId) return species->getId(); } } ++it; } return ""; } std::string SEDMLUtils::getXPathAndName(std::string& sbmlId, const std::string &type, const CModel *pModel, const CDataModel& dataModel) { std::vector<std::string> stringsContainer; std::string targetXPathString; const std::map<const CDataObject*, SBase*>& copasi2sbmlmap = const_cast<CDataModel&>(dataModel).getCopasi2SBMLMap(); std::string displayName = sbmlId; if (copasi2sbmlmap.empty()) { // this should not be happening, as this is used to verify the element. return ""; } std::map<CDataObject*, SBase*>::const_iterator pos; if (type == "Concentration" || type == "InitialConcentration") { targetXPathString = "/sbml:sbml/sbml:model/sbml:listOfSpecies/sbml:species[@id=\'"; //remove unwanted characters from the plot item object name removeCharactersFromString(displayName, "[]"); if (type == "InitialConcentration") { displayName = displayName.substr(0, displayName.length() - 2); } sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_SPECIES, displayName); if (!sbmlId.empty()) { return targetXPathString + sbmlId + "\']"; } return ""; } if (type == "Flux") { targetXPathString = "/sbml:sbml/sbml:model/sbml:listOfReactions/sbml:reaction[@id=\'"; std::string::size_type pos = displayName.rfind(".Flux"); displayName = displayName.substr(1, pos - 2); sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_REACTION, displayName); if (!sbmlId.empty()) { return targetXPathString + sbmlId + "\']"; } return ""; } if (type == "Value" || type == "InitialValue") { if (type == "InitialValue") { displayName = displayName.substr(0, displayName.find(".InitialValue")); } targetXPathString = "/sbml:sbml/sbml:model/sbml:listOfParameters/sbml:parameter[@id=\'"; splitStrings(displayName, '[', stringsContainer); if (stringsContainer.size() == 1) { // not found ... might be a local parameter size_t parameterPos = displayName.rfind("."); if (parameterPos != std::string::npos) { std::string parameterId = displayName.substr(parameterPos + 1); std::string reactionName = displayName.substr(1, parameterPos - 2); sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_REACTION, reactionName); std::stringstream xpath; xpath << "/sbml:sbml/sbml:model/sbml:listOfReactions/sbml:reaction[@id=\'"; xpath << sbmlId; xpath << "\']/sbml:kineticLaw/sbml:listOfParameters/sbml:parameter[@id=\'"; xpath << parameterId; xpath << "\']"; sbmlId += "_" + parameterId; return xpath.str(); } removeCharactersFromString(displayName, "()"); splitStrings(displayName, '.', stringsContainer); if (stringsContainer.size() == 2) { sbmlId = stringsContainer[0] + "_" + stringsContainer[1]; std::stringstream xpath; xpath << "/sbml:sbml/sbml:model/sbml:listOfReactions/sbml:reaction[@id=\'"; xpath << stringsContainer[0]; xpath << "\']/sbml:kineticLaw/sbml:listOfParameters/sbml:parameter[@id=\'"; xpath << stringsContainer[1]; xpath << "\']"; return xpath.str(); } } displayName = stringsContainer[1]; removeCharactersFromString(displayName, "]"); sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_PARAMETER , displayName); if (sbmlId.empty()) sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_LOCAL_PARAMETER , displayName); if (!sbmlId.empty()) { return targetXPathString + sbmlId + "\']"; } return ""; } if (type == "Volume" || type == "InitialVolume") { targetXPathString = "/sbml:sbml/sbml:model/sbml:listOfCompartments/sbml:compartment[@id=\'"; splitStrings(displayName, '[', stringsContainer); displayName = stringsContainer[1]; if (type == "InitialVolume") { displayName = displayName.substr(0, displayName.find(".InitialVolume")); } if (type == "Volume") { displayName = displayName.substr(0, displayName.find(".Volume")); } removeCharactersFromString(displayName, "]"); sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_COMPARTMENT, displayName); if (!sbmlId.empty()) { return targetXPathString + sbmlId + "\']"; } return ""; } if (type == "Time" || type == "Initial Time") return SEDML_TIME_URN; sbmlId = ""; return targetXPathString; } const CDataObject* SEDMLUtils::resolveDatagenerator(const CModel *model, const SedDataGenerator* dataReference) { // for now one variable only if (dataReference == NULL || dataReference->getNumVariables() < 1) return NULL; const SedVariable* var = dataReference->getVariable(0); if (var->isSetSymbol() && var->getSymbol() == SEDML_TIME_URN) { return static_cast<const CDataObject *>(model->getObject(CCommonName("Reference=Time"))); } return resolveXPath(model, var->getTarget()); } std::string SEDMLUtils::translateTargetXpathInSBMLId(const std::string &xpath, std::string& SBMLType) { std::vector<std::string> xpathStrings; std::string id, nextString; splitStrings(xpath, ':', xpathStrings); nextString = xpathStrings[xpathStrings.size() - 1]; splitStrings(nextString, '[', xpathStrings); SBMLType = xpathStrings[0]; nextString = xpathStrings[xpathStrings.size() - 1]; splitStrings(nextString, '=', xpathStrings); nextString = xpathStrings[xpathStrings.size() - 1]; splitStrings(nextString, ']', xpathStrings); id = xpathStrings[0]; //remove the remaining unwanted characters removeCharactersFromString(id, "\"']"); return id; } const CDataObject* SEDMLUtils::resolveXPath(const CModel *model, const std::string& xpath, bool initial /* = false*/) { std::string SBMLType; std::string id = translateTargetXpathInSBMLId(xpath, SBMLType); const CDataObject* result = getObjectForSbmlId(model, id, SBMLType, initial); if (result == NULL) { // old method fails here, possibly a local parameter size_t pos = xpath.find("/sbml:kineticLaw/sbml:listOfParameters/"); if (pos != std::string::npos) { std::string reactionType; std::string reactionId = translateTargetXpathInSBMLId(xpath.substr(0, pos), reactionType); const CDataObject* flux = getObjectForSbmlId(model, reactionId, reactionType); if (flux != NULL) { const CDataObject* reactionObj = flux->getObjectParent(); std::string cn = "ParameterGroup=Parameters,Parameter=" + id + ",Reference=Value"; return dynamic_cast<const CDataObject*>(reactionObj->getObject(cn)); } } } return result; } std::string& SEDMLUtils::removeCharactersFromString(std::string& str, const std::string& characters) { for (unsigned int ii = 0; ii < characters.length(); ++ii) { str.erase(std::remove(str.begin(), str.end(), characters[ii]), str.end()); } return str; } std::string SEDMLUtils::getXPathForObject(const CDataObject& object) { std::string sbmlId = getSbmlId(object); std::string targetXPathString; if (!sbmlId.empty()) { targetXPathString = getXPathForSbmlIdAndType(object.getObjectName(), sbmlId); if (!targetXPathString.empty()) return targetXPathString; } const std::string& type = object.getObjectName(); const CDataModel* dm = object.getObjectDataModel(); std::string yAxis = object.getObjectDisplayName(); targetXPathString = getXPathAndName(yAxis, type, dm->getModel(), *dm); return targetXPathString; } std::string SEDMLUtils::getXPathForSbmlIdAndType(const std::string& type, const std::string& sbmlId) { if (type == "Concentration" || type == "InitialConcentration") return "/sbml:sbml/sbml:model/sbml:listOfSpecies/sbml:species[@id=\'" + sbmlId + "\']"; if (type == "Flux") return "/sbml:sbml/sbml:model/sbml:listOfReactions/sbml:reaction[@id=\'" + sbmlId + "\']"; if (type == "Volume" || type == "InitialVolume") return "/sbml:sbml/sbml:model/sbml:listOfCompartments/sbml:compartment[@id=\'" + sbmlId + "\']"; if (type == "Value" || type == "InitialValue") return "/sbml:sbml/sbml:model/sbml:listOfParameters/sbml:parameter[@id=\'" + sbmlId + "\']"; return std::string(); } std::string SEDMLUtils::getNextId(const std::string& base, int count) { std::stringstream str; str << base << count; return str.str(); } std::string SEDMLUtils::getSbmlId(const CDataObject& object) { const CModelEntity* entity = dynamic_cast<const CModelEntity*>(&object); if (entity != NULL) return entity->getSBMLId(); entity = dynamic_cast<const CModelEntity*>(object.getObjectParent()); if (entity != NULL) return entity->getSBMLId(); return std::string(); } int SEDMLUtils::processArchive(const std::string & archiveFile, std::string &fileName, std::string &fileContent) { int err = 0; /* const char * cArchive = archiveFile.c_str(); //Open the ZIP archive zip *zip = zip_open(cArchive, 0, &err); //Search for file using its given name const char *nameOfFile = fileName.c_str(); struct zip_stat st; zip_stat_init(&st); zip_stat(zip, nameOfFile, 0, &st); //Alloc memory for its uncompressed contents char *fileCont = new char[st.size]; //Read the compressed file zip_file *file = zip_fopen(zip, nameOfFile, 0); zip_fread(file, fileCont, st.size); std::ostringstream fileContentStream; size_t i, iMax = st.size; for(i = 0; i<iMax; ++i){ fileContentStream << fileCont[i]; } fileContent = fileContentStream.str(); //close the file and archive zip_fclose(file); zip_close(zip); */ return err; } //split: receives a char delimiter and string and a vector of strings that will contain the splited strings //this is presently a hack to parse the XPath based target attribute in SEDML. A better solution may be //necessary in the future. void SEDMLUtils::splitStrings(const std::string &xpath, char delim, std::vector<std::string> &xpathStrings) { std::string myPath = xpath; xpathStrings.clear(); std::string next; // For each character in the string for (std::string::const_iterator it = xpath.begin(); it != xpath.end(); it++) { // check delimiter character if (*it == delim) { if (!next.empty()) { // Add them to the xpathStrings vector xpathStrings.push_back(next); next.clear(); } } else { next += *it; } } if (!next.empty()) xpathStrings.push_back(next); } const CDataObject * SEDMLUtils::getObjectForSbmlId(const CModel* pModel, const std::string& id, const std::string& SBMLType, bool initial/* = false*/) { if (SBMLType == "Time") return static_cast<const CDataObject *>(pModel->getObject(CCommonName("Reference=Time"))); if (SBMLType == "species") { size_t iMet, imax = pModel->getMetabolites().size(); for (iMet = 0; iMet < imax; ++iMet) { // the importer should not need to change the initial concentration // pModel->getMetabolites()[iMet].setInitialConcentration(0.896901); if (pModel->getMetabolites()[iMet].getSBMLId() == id) { if (initial) return pModel->getMetabolites()[iMet].getInitialConcentrationReference(); return pModel->getMetabolites()[iMet].getConcentrationReference(); } } } else if (SBMLType == "reaction") { size_t iMet, imax = pModel->getReactions().size(); for (iMet = 0; iMet < imax; ++iMet) { if (pModel->getReactions()[iMet].getSBMLId() == id) { if (initial) return NULL; return pModel->getReactions()[iMet].getFluxReference(); } } } else if (SBMLType == "parameter") { size_t iMet, imax = pModel->getModelValues().size(); for (iMet = 0; iMet < imax; ++iMet) { if (pModel->getModelValues()[iMet].getSBMLId() == id) { if (initial) return pModel->getModelValues()[iMet].getInitialValueReference(); return pModel->getModelValues()[iMet].getValueReference(); } } } else if (SBMLType == "compartment") { size_t iComp, imax = pModel->getCompartments().size(); for (iComp = 0; iComp < imax; ++iComp) { if (pModel->getCompartments()[iComp].getSBMLId() == id) { if (initial) return pModel->getCompartments()[iComp].getInitialValueReference(); return pModel->getCompartments()[iComp].getValueReference(); } } } return NULL; } /*void SEDMLUtils::resmoveUnwantedChars(std::string & str, char chars[]) { for (unsigned int i = 0; i < strlen(chars); ++i) { str.erase(std::remove(str.begin(), str.end(), chars[i]), str.end()); } } */ SEDMLUtils::SEDMLUtils() { // TODO Auto-generated constructor stub } SEDMLUtils::~SEDMLUtils() { // TODO Auto-generated destructor stub }
29.061706
130
0.614563
SzVarga
5e88986ddffff23f840c96fd4ed5316b03269989
581
cpp
C++
src/common/sun.cpp
alexkafer/planets
ad118c7ba9d479afc29ba9d5b65222c8c7f2cde2
[ "Unlicense", "MIT" ]
null
null
null
src/common/sun.cpp
alexkafer/planets
ad118c7ba9d479afc29ba9d5b65222c8c7f2cde2
[ "Unlicense", "MIT" ]
null
null
null
src/common/sun.cpp
alexkafer/planets
ad118c7ba9d479afc29ba9d5b65222c8c7f2cde2
[ "Unlicense", "MIT" ]
1
2021-03-02T16:54:40.000Z
2021-03-02T16:54:40.000Z
#include "sun.hpp" #include "graphics/vert_buffer.hpp" Sun::Sun(float radius): OrbitalMass({0.f, 0, 0, 0, 0}, 5), shape(radius) { std::cout << "Sun created\n"; } void Sun::upload() { VertAttributes sunAttrs; sunAttrs.add_(VertAttributes::POSITION) .add_(VertAttributes::NORMAL) .add_(VertAttributes::TEX_COORDS) .add_(VertAttributes::TANGENT); sunMesh = shape.generate("sun", 100, 70, sunAttrs); VertBuffer::uploadSingleMesh(sunMesh); } void Sun::render(RenderType type) { if (type == RenderType::Terrain) sunMesh->render(); }
25.26087
74
0.660929
alexkafer
5e88c33719a8b3c623d5ae9d2b5b3a96e8ed9d82
90
hpp
C++
2SST/2LW/files.hpp
AVAtarMod/University
3c784a1e109b7a6f6ea495278ec3dc126258625a
[ "BSD-3-Clause" ]
1
2021-07-31T06:55:08.000Z
2021-07-31T06:55:08.000Z
2SST/2LW/files.hpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
1
2020-11-25T12:00:11.000Z
2021-01-13T08:51:52.000Z
2SST/2LW/files.hpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
null
null
null
#ifndef FILES #define FILES #include <fstream> bool isFileExist(const char *file); #endif
15
35
0.766667
AVAtarMod
5e88c9cd294c0c9ca7fd2c0eb85bfc85a43eea8d
4,251
cpp
C++
sjf_p.cpp
tanujsinghal24/Lab_codes-COC3930-
3f36835b16897304c6b5d00ead1219d76f6b58df
[ "MIT" ]
1
2021-08-02T08:35:32.000Z
2021-08-02T08:35:32.000Z
sjf_p.cpp
tanujsinghal24/Lab_codes-COC3930-
3f36835b16897304c6b5d00ead1219d76f6b58df
[ "MIT" ]
null
null
null
sjf_p.cpp
tanujsinghal24/Lab_codes-COC3930-
3f36835b16897304c6b5d00ead1219d76f6b58df
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class System_p { public: int process_num ,burst_time,arrival_t; }; int n; int wait_time[1000], turn_around_t[1000], total_wt = 0,total_tat = 0; void print_process(System_p pt[],int i,int curr_t){ cout << "Process num Burst time Arrival time Current time\n"; cout << " " << pt[i].process_num << "\t\t"<< pt[i].burst_time << "\t\t"<< pt[i].arrival_t << "\t\t"<< curr_t << endl<<endl; } void fcfs(System_p p[]){ System_p ptemp[n]; int current_time=0;float avg_wt=0,avg_tat=0,st[n],ft[n]; for(int i=0;i<n;i++) ptemp[i]=p[i]; for(int i=0;i<n;i++){ for(int j=0;j<n-i-1;j++){ if(ptemp[j+1].arrival_t<ptemp[j].arrival_t){ System_p temp = ptemp[j]; ptemp[j]=ptemp[j+1]; ptemp[j+1]=temp; } } } current_time=ptemp[0].arrival_t; st[0]=current_time; for(int i=0;i<n;i++){ int curr_p=i; if(i<n-1) st[i]=current_time; print_process(ptemp,curr_p,current_time); wait_time[i]= current_time - ptemp[curr_p].arrival_t; if (wait_time[curr_p] < 0) wait_time[curr_p] = 0; avg_wt+=wait_time[i]; turn_around_t[i]=ptemp[curr_p].burst_time + wait_time[i]; avg_tat+=turn_around_t[i]; current_time+=ptemp[curr_p].burst_time; ft[i]=current_time; } cout<<"\n\nGantt Chart: "<<ptemp[0].arrival_t<<" "; for (int i = 0; i < n; i++){ if(0) cout << " P" << ptemp[i].process_num << "\t"<< ptemp[i].arrival_t+turn_around_t[i]; else cout << " P" << ptemp[i].process_num << "\t"<< ft[i]; } cout<<"\n\n\n"; cout<<"FCFS Final Process Table:"<<endl; cout << "Process num Burst time Arrival time Waiting time Turn around time\n"; for (int i = 0; i < n; i++) cout << " " << ptemp[i].process_num << "\t\t"<< ptemp[i].burst_time << "\t\t"<< ptemp[i].arrival_t << "\t\t " << wait_time[i] << "\t\t " << turn_around_t[i] << endl; avg_wt/=n; avg_tat/=n; cout << "\nAverage waiting time = "<< avg_wt<<"\nAverage turn around time = "<< avg_tat<<endl; cout<<"\n\n\n\n"; } void sjf_preemtive(System_p p[]) { int temp[n]; float avg_wt,avg_tat; for (int i = 0; i < n; i++) temp[i] = p[i].burst_time; int num_p = 0, current_time = 0, curr_min = 1000000,curr_p = 0, finish_time,f=0; while (num_p != n) { for (int j = 0; j < n; j++) { if ((p[j].arrival_t <= current_time) ) if((temp[j] < curr_min) && (temp[j] > 0)) { curr_min = temp[j]; curr_p = j; f = 1; } } if (f == 0) { current_time++; continue; } print_process(p,curr_p,current_time); current_time++; temp[curr_p]--; curr_min = temp[curr_p]; if (temp[curr_p] == 0) { num_p++; f = 0; wait_time[curr_p] = current_time - p[curr_p].arrival_t - p[curr_p].burst_time; if (wait_time[curr_p] < 0) wait_time[curr_p] = 0; } if (curr_min == 0) curr_min = 1000000; } for (int i = 0; i < n; i++) turn_around_t[i] = p[i].burst_time + wait_time[i]; cout<<"\n\nSJF PREEMTIVE Final Process Table:"<<endl; cout << "Process num Burst time Arrival time Waiting time Turn around time\n"; for (int i = 0; i < n; i++) { avg_wt += wait_time[i]; avg_tat += turn_around_t[i]; } for (int i = 0; i < n; i++) cout << " " << p[i].process_num << "\t\t"<< p[i].burst_time << "\t\t"<< p[i].arrival_t << "\t\t " << wait_time[i] << "\t\t " << turn_around_t[i] << endl; avg_wt/=n; avg_tat/=n; cout << "\nAverage waiting time = "<< avg_wt<<"\nAverage turn around time = "<< avg_tat<<endl; cout<<"\n\n\n\n"; } int main() { cout<<"Enter number of processes:"; cin>>n; System_p p[n]; for(int i=0;i<n;i++){ cout<<"Enter arrival and burst time of process "<<i+1<<" :"; p[i].process_num=i+1; cin>>p[i].arrival_t>>p[i].burst_time; } fcfs(p); // int t=1; // cout<<"Enter Scheduling algorithm to be used(1.SJF PREEMTIVE 2.FCFS):"; // cin>>t; // if(t==1) // sjf_preemtive(p); // else if(t==2) // fcfs(p); return 0; }
32.204545
168
0.537521
tanujsinghal24
5e890d1e38aab834240113dda32730c054454f38
1,261
cpp
C++
aws-cpp-sdk-kinesis/source/model/SubscribeToShardRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-kinesis/source/model/SubscribeToShardRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-kinesis/source/model/SubscribeToShardRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/kinesis/model/SubscribeToShardRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Kinesis::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; SubscribeToShardRequest::SubscribeToShardRequest() : m_consumerARNHasBeenSet(false), m_shardIdHasBeenSet(false), m_startingPositionHasBeenSet(false), m_decoder(Aws::Utils::Event::EventStreamDecoder(&m_handler)) { } Aws::String SubscribeToShardRequest::SerializePayload() const { JsonValue payload; if(m_consumerARNHasBeenSet) { payload.WithString("ConsumerARN", m_consumerARN); } if(m_shardIdHasBeenSet) { payload.WithString("ShardId", m_shardId); } if(m_startingPositionHasBeenSet) { payload.WithObject("StartingPosition", m_startingPosition.Jsonize()); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection SubscribeToShardRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "Kinesis_20131202.SubscribeToShard")); return headers; }
21.372881
98
0.75337
Neusoft-Technology-Solutions
5e8adc56b28047c250962ca4213d1599c115c497
189
cpp
C++
Random.cpp
JAPLJ/Legerdemain
78a7634f8dc1f4398c407d41acea0478484f111d
[ "MIT" ]
1
2017-04-06T08:24:06.000Z
2017-04-06T08:24:06.000Z
Random.cpp
JAPLJ/Legerdemain
78a7634f8dc1f4398c407d41acea0478484f111d
[ "MIT" ]
null
null
null
Random.cpp
JAPLJ/Legerdemain
78a7634f8dc1f4398c407d41acea0478484f111d
[ "MIT" ]
null
null
null
#include "Random.h" #include <random> Random Random::instance; int Random::randint(int lo, int hi) { std::uniform_int_distribution<int> dist(lo, hi); return dist(instance.mt); }
17.181818
52
0.693122
JAPLJ
5e8b22afdc251b65480a82d20249eeabcd099f99
4,103
cpp
C++
src/mpc-base.cpp
PepMS/eagle-mpc
522b4af6f31dcdec72c9c461ace28bb774aa4057
[ "BSD-3-Clause" ]
10
2021-07-14T10:50:20.000Z
2022-03-14T06:27:13.000Z
src/mpc-base.cpp
PepMS/multicopter-mpc
522b4af6f31dcdec72c9c461ace28bb774aa4057
[ "BSD-3-Clause" ]
29
2020-06-04T08:38:52.000Z
2020-09-25T10:26:25.000Z
src/mpc-base.cpp
PepMS/eagle-mpc
522b4af6f31dcdec72c9c461ace28bb774aa4057
[ "BSD-3-Clause" ]
2
2021-11-02T02:14:45.000Z
2022-01-10T11:32:59.000Z
#include "eagle_mpc/mpc-base.hpp" namespace eagle_mpc { MpcAbstract::MpcAbstract(const std::string& yaml_path) { eagle_mpc::ParserYaml parser(yaml_path); params_server_ = boost::make_shared<ParamsServer>(parser.get_params()); initializeRobotObjects(); loadParams(); int_models_.reserve(params_.knots); dif_models_.reserve(params_.knots); cost_factory_ = boost::make_shared<CostModelFactory>(); } void MpcAbstract::initializeRobotObjects() { std::string prefix_robot = "robot/"; robot_model_path_ = getUrdfPath(params_server_->getParam<std::string>(prefix_robot + "urdf")); pinocchio::Model model; pinocchio::urdf::buildModel(robot_model_path_, pinocchio::JointModelFreeFlyer(), model); robot_model_ = boost::make_shared<pinocchio::Model>(model); platform_params_ = boost::make_shared<MultiCopterBaseParams>(); platform_params_->autoSetup(prefix_robot + "platform/", params_server_, robot_model_); robot_state_ = boost::make_shared<crocoddyl::StateMultibody>(robot_model_); actuation_ = boost::make_shared<crocoddyl::ActuationModelMultiCopterBase>(robot_state_, platform_params_->tau_f_); squash_ = boost::make_shared<crocoddyl::SquashingModelSmoothSat>(platform_params_->u_lb, platform_params_->u_ub, actuation_->get_nu()); actuation_squash_ = boost::make_shared<crocoddyl::ActuationSquashingModel>(actuation_, squash_, actuation_->get_nu()); } void MpcAbstract::loadParams() { std::string prefix_controller = "mpc_controller/"; std::string integration_method = params_server_->getParam<std::string>(prefix_controller + "integration_method"); params_.integrator_type = IntegratedActionModelTypes_map.at(integration_method); params_.knots = params_server_->getParam<int>(prefix_controller + "knots"); params_.iters = params_server_->getParam<int>(prefix_controller + "iters"); params_.dt = params_server_->getParam<int>(prefix_controller + "dt"); std::string solver = params_server_->getParam<std::string>(prefix_controller + "solver"); params_.solver_type = SolverTypes_map.at(solver); try { params_.callback = params_server_->getParam<bool>(prefix_controller + "callback"); } catch (const std::exception& e) { EMPC_DEBUG(e.what(), " Set to false."); params_.callback = false; } } const boost::shared_ptr<pinocchio::Model>& MpcAbstract::get_robot_model() const { return robot_model_; } const std::string& MpcAbstract::get_robot_model_path() const { return robot_model_path_; } const boost::shared_ptr<MultiCopterBaseParams>& MpcAbstract::get_platform_params() const { return platform_params_; } const boost::shared_ptr<crocoddyl::StateMultibody>& MpcAbstract::get_robot_state() const { return robot_state_; } const boost::shared_ptr<crocoddyl::ActuationModelMultiCopterBase>& MpcAbstract::get_actuation() const { return actuation_; } const boost::shared_ptr<crocoddyl::SquashingModelSmoothSat>& MpcAbstract::get_squash() const { return squash_; } const boost::shared_ptr<crocoddyl::ActuationSquashingModel>& MpcAbstract::get_actuation_squash() const { return actuation_squash_; } const std::vector<boost::shared_ptr<crocoddyl::DifferentialActionModelAbstract>>& MpcAbstract::get_dif_models() const { return dif_models_; } const std::vector<boost::shared_ptr<crocoddyl::ActionModelAbstract>>& MpcAbstract::get_int_models() const { return int_models_; } const boost::shared_ptr<crocoddyl::ShootingProblem>& MpcAbstract::get_problem() const { return problem_; } const boost::shared_ptr<crocoddyl::SolverDDP>& MpcAbstract::get_solver() const { return solver_; } const std::size_t& MpcAbstract::get_dt() const { return params_.dt; } const std::size_t& MpcAbstract::get_knots() const { return params_.knots; } const std::size_t& MpcAbstract::get_iters() const { return params_.iters; } const SolverTypes& MpcAbstract::get_solver_type() const { return params_.solver_type; } } // namespace eagle_mpc
46.101124
119
0.737022
PepMS
5e8ccbbf856ee66c4c6afbe3f21b273f792e6fbc
1,749
cpp
C++
Editor/Source/Controls/ToolbarView.cpp
Claudio-Marchini/Lumen
41183d71f0fe6dfe9964617b127b40b26339c822
[ "MIT" ]
null
null
null
Editor/Source/Controls/ToolbarView.cpp
Claudio-Marchini/Lumen
41183d71f0fe6dfe9964617b127b40b26339c822
[ "MIT" ]
null
null
null
Editor/Source/Controls/ToolbarView.cpp
Claudio-Marchini/Lumen
41183d71f0fe6dfe9964617b127b40b26339c822
[ "MIT" ]
null
null
null
#include "ToolbarView.h" #include "../EditorApplication.h" #include <imgui/imgui.h> void ToolbarView::Render() { if (ImGui::BeginMainMenuBar()) { if (ImGui::BeginMenu("Project")) { if (ImGui::MenuItem("Create")) { mFileOpen = true; } ImGui::MenuItem("Open"); if (ImGui::MenuItem("Save")) { EditorApp::Get()->Save(); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Actions")) { const b8 scenePlaying{ EditorApp::Get()->GetIsPlaying() }; if (ImGui::MenuItem(scenePlaying ? "Stop" : "Play")) { static const char* tempFile{ "$Temp$.lumen" }; EditorApp::Get()->SetPlaying(!scenePlaying); auto& project{ EditorApp::Get()->GetProject() }; Lumen::Utils::Serializer serializer{ &project }; scenePlaying ? serializer.Load(project.Path / tempFile) : serializer.Save(project.Path / tempFile); if (scenePlaying) { EditorApp::Get()->GetSceneView().mSelectedEntity = nullptr; std::filesystem::remove(project.Path / tempFile); } else { EditorApp::Get()->GetScriptManager().Start(EditorApp::Get()->GetScene()); } } ImGui::EndMenu(); } if (ImGui::BeginMenu("Settings")) { ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } CreateDialog(); } void ToolbarView::CreateDialog() { if (mFileOpen) { ImGui::OpenPopup("Select a location"); mFileOpen = false; if (!std::filesystem::exists(mFileExplorer.GetCurrentPath())) { mFileExplorer.SetCurrentPath("C:\\"); } } if (ImGui::BeginPopupModal("Select a location")) { mFileExplorer.Draw(); if (ImGui::Button("Create")) ImGui::CloseCurrentPopup(); ImGui::SameLine(); if (ImGui::Button("Cancel")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } }
20.576471
103
0.626072
Claudio-Marchini
5e906bde120ef8c06b7312812947a1ed610dcf97
609
cpp
C++
Leetcode/May-Challenge/remove-kdigits.cpp
shashankkmciv18/dsa
6feba269292d95d36e84f1adb910fe2ed5467f71
[ "MIT" ]
54
2020-07-31T14:50:23.000Z
2022-03-14T11:03:02.000Z
Leetcode/May-Challenge/remove-kdigits.cpp
SahilMund/dsa
a94151b953b399ea56ff50cf30dfe96100e8b9a7
[ "MIT" ]
null
null
null
Leetcode/May-Challenge/remove-kdigits.cpp
SahilMund/dsa
a94151b953b399ea56ff50cf30dfe96100e8b9a7
[ "MIT" ]
30
2020-08-15T17:39:02.000Z
2022-03-10T06:50:18.000Z
class Solution { public: string removeKdigits(string num, int k) { int n = num.size(); if( n<= k ) { return "0"; } while(k) { int i = 0; // for finding the peaks. while(i+1<n && num[i+1]>=num[i]) i++; num.erase(i,1); k--; } // for deleting cases for 0 0 2 0 0 or 0 0 0 0 0 int j = 0; while( j < n && num[j] == '0' ) j++; num = num.substr(j); return num=="" ? "0" : num; } };
20.3
58
0.338259
shashankkmciv18
5e91443948cd6fcb252f4d3afbb40e79771127f5
4,403
cpp
C++
src/sf/Thread.cpp
bqqbarbhg/spear
727f41fa5197f9681337d1ff37ea63c44708f0d4
[ "BSD-3-Clause" ]
29
2020-07-27T09:56:02.000Z
2022-03-28T01:38:07.000Z
src/sf/Thread.cpp
bqqbarbhg/spear
727f41fa5197f9681337d1ff37ea63c44708f0d4
[ "BSD-3-Clause" ]
3
2020-05-29T11:43:20.000Z
2020-09-04T09:56:56.000Z
src/sf/Thread.cpp
bqqbarbhg/spear
727f41fa5197f9681337d1ff37ea63c44708f0d4
[ "BSD-3-Clause" ]
2
2020-05-29T11:34:46.000Z
2021-03-08T08:39:07.000Z
#include "Thread.h" #include "Internal.h" #if defined(TRACY_ENABLE) #include "ext/tracy/Tracy.hpp" #endif #if SF_OS_WINDOWS #define WIN32_LEAN_AND_MEAN #include <Windows.h> #elif SF_USE_PTHREADS #include <pthread.h> #if SF_OS_EMSCRIPTEN #include <emscripten.h> #include <emscripten/threading.h> #else #include <time.h> #endif #endif #if SF_OS_WINDOWS // Cursed code from MSDN: // https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-set-a-thread-name-in-native-code // Usage: SetThreadName ((DWORD)-1, "MainThread"); const DWORD MS_VC_EXCEPTION = 0x406D1388; #pragma pack(push,8) typedef struct tagTHREADNAME_INFO { DWORD dwType; // Must be 0x1000. LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1=caller thread). DWORD dwFlags; // Reserved for future use, must be zero. } THREADNAME_INFO; #pragma pack(pop) void SetThreadName(DWORD dwThreadID, const char* threadName) { THREADNAME_INFO info; info.dwType = 0x1000; info.szName = threadName; info.dwThreadID = dwThreadID; info.dwFlags = 0; #pragma warning(push) #pragma warning(disable: 6320 6322) __try{ RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info); } __except (EXCEPTION_EXECUTE_HANDLER){ } #pragma warning(pop) } #endif namespace sf { #if SF_OS_WINDOWS void setDebugThreadName(sf::String name) { sf::StringBuf nameBuf(name); typedef HRESULT (WINAPI *pfn_SetThreadDescription)(HANDLE, PCWSTR); static pfn_SetThreadDescription setThreadDescription = (pfn_SetThreadDescription)GetProcAddress(LoadLibraryA("Kernel32.dll"), "SetThreadDescription"); SetThreadName(GetCurrentThreadId(), nameBuf.data); if (setThreadDescription) { Array<wchar_t> wideName; win32Utf8To16(wideName, name); setThreadDescription(GetCurrentThread(), wideName.data); } } struct ThreadImp : Thread { ThreadEntry entry; void *user; sf::StringBuf debugName; HANDLE handle; DWORD id; }; DWORD WINAPI threadEntry(LPVOID arg) { ThreadImp *imp = (ThreadImp*)arg; if (imp->debugName.size > 0) { setDebugThreadName(imp->debugName); #if defined(TRACY_ENABLE) tracy::SetThreadName(imp->debugName.data); #endif } imp->entry(imp->user); return 0; } Thread *Thread::start(const ThreadDesc &desc) { ThreadImp *imp = new ThreadImp(); if (!imp) return nullptr; imp->debugName = desc.name; imp->entry = desc.entry; imp->user = desc.user; imp->handle = CreateThread(NULL, 0, &threadEntry, imp, 0, &imp->id); return imp; } void Thread::join(Thread *thread) { if (!thread) return; ThreadImp *imp = (ThreadImp*)thread; WaitForSingleObject(imp->handle, INFINITE); CloseHandle(imp->handle); delete imp; } void Thread::sleepMs(uint32_t ms) { Sleep(ms); } #elif SF_USE_PTHREADS void setDebugThreadName(sf::String name) { sf::StringBuf nameBuf(name); #if SF_OS_EMSCRIPTEN emscripten_set_thread_name(pthread_self(), nameBuf.data); #endif } struct ThreadImp : Thread { ThreadEntry entry; void *user; sf::StringBuf debugName; pthread_t thread; }; void *threadEntry(void *arg) { ThreadImp *imp = (ThreadImp*)arg; if (imp->debugName.size > 0) { setDebugThreadName(imp->debugName); #if defined(TRACY_ENABLE) tracy::SetThreadName(imp->debugName.data); #endif } imp->entry(imp->user); return 0; } Thread *Thread::start(const ThreadDesc &desc) { ThreadImp *imp = new ThreadImp(); if (!imp) return nullptr; imp->debugName = desc.name; imp->entry = desc.entry; imp->user = desc.user; pthread_create(&imp->thread, NULL, &threadEntry, imp); return imp; } void Thread::join(Thread *thread) { if (!thread) return; ThreadImp *imp = (ThreadImp*)thread; pthread_join(imp->thread, nullptr); delete imp; } void Thread::sleepMs(uint32_t ms) { #if SF_OS_EMSCRIPTEN emscripten_sleep(ms); #else struct timespec ts; ts.tv_sec = ms / 1000; ts.tv_nsec = (ms % 1000) * 1000000; while (nanosleep(&ts, &ts)) { } #endif } #else void setDebugThreadName(sf::String name) { } Thread *Thread::start(const ThreadDesc &desc) { return nullptr; } void Thread::join(Thread *thread) { } void Thread::sleepMs(uint32_t ms) { } #endif }
20.671362
154
0.678174
bqqbarbhg
5e920058302229030b495ccc64ce0a3139ccc199
4,226
cpp
C++
psx/_dump_/47/_dump_c_src_/diabpsx/source/quests.cpp
maoa3/scalpel
2e7381b516cded28996d290438acc618d00b2aa7
[ "Unlicense" ]
15
2018-06-28T01:11:25.000Z
2021-09-27T15:57:18.000Z
psx/_dump_/47/_dump_c_src_/diabpsx/source/quests.cpp
maoa3/scalpel
2e7381b516cded28996d290438acc618d00b2aa7
[ "Unlicense" ]
7
2018-06-29T04:08:23.000Z
2019-10-17T13:57:22.000Z
psx/_dump_/47/_dump_c_src_/diabpsx/source/quests.cpp
maoa3/scalpel
2e7381b516cded28996d290438acc618d00b2aa7
[ "Unlicense" ]
7
2018-06-28T01:11:34.000Z
2020-05-23T09:21:48.000Z
// C:\diabpsx\SOURCE\QUESTS.CPP #include "types.h" // address: 0x80060B58 // line start: 160 // line end: 220 void TSK_Lava2Water__FP4TASK(struct TASK *T) { // address: 0xFFFFFFB0 // size: 0x20 auto unsigned short LAVAPAL[16]; // address: 0xFFFFFFD0 // size: 0x20 auto unsigned short WATERPAL[16]; // address: 0xFFFFFFF0 // size: 0x8 auto struct RECT ClutR; // register: 16 register int clut; // register: 16 // size: 0x6C register struct TextDat *ThisDat; // register: 3 // size: 0x8 register struct PAL *Pal; // register: 2 register unsigned short cx; // register: 3 register unsigned short cy; // register: 16 register bool ch; { { { // register: 4 register int i; { { // register: 10 register int i; { // register: 11 register unsigned short col1; // register: 3 register unsigned short col2; // register: 14 register unsigned char sb; // register: 13 register unsigned char sg; // register: 8 register unsigned char dr; // register: 7 register unsigned char dg; // register: 5 register unsigned char db; } } } } } } } // address: 0x80060DA8 // line start: 226 // line end: 291 void CheckQuests__Fv() { // register: 18 register int i; // register: 4 register int rportx; // register: 5 register int rporty; } // address: 0x80061264 // line start: 295 // line end: 322 unsigned char ForceQuests__Fv() { { // register: 6 register int i; { // register: 16 register int ql; // register: 18 register int qx; // register: 17 register int qy; { // register: 4 register int j; } } } } // address: 0x80061408 // line start: 327 // line end: 333 unsigned char QuestStatus__Fi(int i) { } // address: 0x8006149C // line start: 339 // line end: 437 void CheckQuestKill__FiUc(int m, unsigned char sendmsg) { { { { { { { { { { { // register: 4 register int i; // register: 7 register int j; } } } } } } } } } } } // address: 0x80061A7C // line start: 471 // line end: 496 void SetReturnLvlPos__Fv() { } // address: 0x80061B8C // line start: 504 // line end: 509 void GetReturnLvlPos__Fv() { } // address: 0x80061BE0 // line start: 516 // line end: 538 void ResyncMPQuests__Fv() { } // address: 0x80061D1C // line start: 548 // line end: 637 void ResyncQuests__Fv() { // register: 16 register int i; // register: 16 register int tren; } // address: 0x8006227C // line start: 653 // line end: 694 void PrintQLString__FiiUcPcc(int x, int y, unsigned char cjustflag, char *str, int col) { // register: 10 register unsigned char r; // register: 9 register unsigned char g; // register: 8 register unsigned char b; { { // register: 17 register int len; } } } // address: 0x800624A8 // line start: 703 // line end: 733 void DrawQuestLog__Fv() { // register: 18 register int i; // register: 17 register int l; // register: 2 register int q; } // address: 0x80062670 // line start: 743 // line end: 764 void DrawQuestLogTSK__FP4TASK(struct TASK *T) { } // address: 0x80062708 // line start: 772 // line end: 793 void StartQuestlog__Fv() { // register: 5 register int i; } // address: 0x80062820 // line start: 800 // line end: 818 void QuestlogUp__Fv() { } // address: 0x80062870 // line start: 826 // line end: 846 void QuestlogDown__Fv() { } // address: 0x800628D8 // line start: 855 // line end: 867 void RemoveQLog__Fv() { } // address: 0x80062950 // line start: 872 // line end: 893 void QuestlogEnter__Fv() { // register: 3 register int q; } // address: 0x80062A14 // line start: 901 // line end: 903 void QuestlogESC__Fv() { } // address: 0x80062A3C // line start: 910 // line end: 930 void SetMultiQuest__FiiUci(int q, int s, unsigned char l, int v1) { } // address: 0x80062ABC // line start: 977 // line end: 977 void _GLOBAL__D_questlog() { } // address: 0x80062AE4 // line start: 977 // line end: 977 void _GLOBAL__I_questlog() { }
15.256318
89
0.604117
maoa3
5e993460efef73c852f0c0da59d4ff81ccfb98e3
182
cpp
C++
regression/esbmc-cpp/qt/QVector/vector_capacity_bug/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
143
2015-06-22T12:30:01.000Z
2022-03-21T08:41:17.000Z
regression/esbmc-cpp/qt/QVector/vector_capacity_bug/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
542
2017-06-02T13:46:26.000Z
2022-03-31T16:35:17.000Z
regression/esbmc-cpp/qt/QVector/vector_capacity_bug/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
81
2015-10-21T22:21:59.000Z
2022-03-24T14:07:55.000Z
#include <QVector> #include <cassert> int main () { QVector<int> myQVector; myQVector << 1 << 4 << 6 << 8 << 10 << 12; assert( !(myQVector.capacity() > 0) ); return 0; }
13
44
0.56044
shmarovfedor
5e99fc1ad3513b3b4399c14fccbfcc41d5f07bc7
749
hpp
C++
cmdstan/stan/lib/stan_math/test/unit/math/torsten/expect_near_matrix_eq.hpp
csetraynor/Torsten
55b59b8068e2a539346f566ec698c755a9e3536c
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/test/unit/math/torsten/expect_near_matrix_eq.hpp
csetraynor/Torsten
55b59b8068e2a539346f566ec698c755a9e3536c
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/test/unit/math/torsten/expect_near_matrix_eq.hpp
csetraynor/Torsten
55b59b8068e2a539346f566ec698c755a9e3536c
[ "BSD-3-Clause" ]
null
null
null
#ifndef TEST_MATH_MATRIX_EXPECT_NEAR_MATRIX_EQ_HPP #define TEST_MATH_MATRIX_EXPECT_NEAR_MATRIX_EQ_HPP #include <gtest/gtest.h> void expect_near_matrix_eq(const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& a, const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& b, const double& rel_err, const double& abs_err = 1e-15) { EXPECT_EQ(a.rows(), b.rows()); EXPECT_EQ(a.cols(), b.cols()); double err; for (int i = 0; i < a.rows(); ++i) for (int j = 0; j < a.cols(); ++j) { err = std::max(std::abs(rel_err * a(i, j)), abs_err); EXPECT_NEAR(a(i, j), b(i, j), err); } } #endif
32.565217
84
0.543391
csetraynor
5e9b2b33dccecfcee45176a9b9692fff4562fc2b
4,059
cpp
C++
game_server/src/ecs/system/hatred_system.cpp
mzxdream/cherry
cf247ecda039a7255b7fc0e1b2c2a591bb4af8e0
[ "Apache-2.0" ]
null
null
null
game_server/src/ecs/system/hatred_system.cpp
mzxdream/cherry
cf247ecda039a7255b7fc0e1b2c2a591bb4af8e0
[ "Apache-2.0" ]
null
null
null
game_server/src/ecs/system/hatred_system.cpp
mzxdream/cherry
cf247ecda039a7255b7fc0e1b2c2a591bb4af8e0
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <ecs/component/hatred.h> #include <ecs/component/location.h> #include <ecs/component/serialize/component_serialize.h> #include <ecs/component/view.h> #include <ecs/event/component_event.h> #include <ecs/system/hatred_system.h> #include <scene/scene.h> #include <world.h> namespace cherry { HatredSystem::HatredSystem(Scene *scene) : scene_(scene) { scene_->GetEventManager().AddListener<ComponentRemoveEvent>( std::bind(&HatredSystem::OnRemoveComponent, this, std::placeholders::_1), this); } HatredSystem::~HatredSystem() { scene_->GetEventManager().RemoveListener<ComponentRemoveEvent>(this); } static void OnRemoveHatredPublish(Scene *scene, mzx::Entity *entity, mzx::ComponentBase *component_base) { auto *hatred_publish = static_cast<mzx::Component<HatredPublish> *>(component_base)->Get(); for (auto &subscribe : hatred_publish->subscribe_list) { auto *other_hatred_subscribe = subscribe->GetComponent<HatredSubscribe>(); auto iter_index = other_hatred_subscribe->entity_index.find(entity); if (iter_index != other_hatred_subscribe->entity_index.end()) { other_hatred_subscribe->publish_list.erase(iter_index->second); other_hatred_subscribe->entity_index.erase(iter_index); } } } static void OnRemoveHatredSubscribe(Scene *scene, mzx::Entity *entity, mzx::ComponentBase *component_base) { auto *hatred_subscribe = static_cast<mzx::Component<HatredSubscribe> *>(component_base)->Get(); for (auto &iter_publish : hatred_subscribe->entity_index) { iter_publish.first->GetComponent<HatredPublish>()->subscribe_list.erase( entity); } } void HatredSystem::OnRemoveComponent(const mzx::SimpleEventBase *base) { auto *event = static_cast<const ComponentRemoveEvent *>(base); auto class_index = event->component_base->ClassIndex(); if (class_index == mzx::Component<HatredPublish>::CLASS_INDEX) { OnRemoveHatredPublish(scene_, event->entity, event->component_base); } else if (class_index == mzx::Component<HatredSubscribe>::CLASS_INDEX) { OnRemoveHatredSubscribe(scene_, event->entity, event->component_base); } } void HatredSystem::_Update(Scene *scene) { scene->GetEntityManager() .ForeachEntity<HatredSubscribe, HatredDistanceCheck, ViewSubscribe, Location>([](mzx::Entity *entity) { auto *hatred_subscribe = entity->GetComponent<HatredSubscribe>(); auto *hatred_distance_check = entity->GetComponent<HatredDistanceCheck>(); auto *view_subscribe = entity->GetComponent<ViewSubscribe>(); auto *location = entity->GetComponent<Location>(); for (auto &other : view_subscribe->publish_list) { auto *other_location = other->GetComponent<Location>(); auto *other_hatred_publish = other->GetComponent<HatredPublish>(); if (!other_location || !other_hatred_publish) { continue; } if (mzx::Vector3<double>::Distance(location->position, other_location->position) <= hatred_distance_check->distance) { if (hatred_subscribe->entity_index.find(other) == hatred_subscribe->entity_index.end()) { auto result = hatred_subscribe->publish_list.insert( HatredSubscribe::SortType::value_type(1, other)); hatred_subscribe->entity_index[other] = result; other_hatred_publish->subscribe_list.insert(entity); } } } return true; }); } } // namespace cherry
36.241071
80
0.612712
mzxdream
5e9e28e61087468619cdf5fbde79cf0393bf04da
1,609
cpp
C++
wpilibc/src/test/native/cpp/simulation/AnalogTriggerSimTest.cpp
shueja-personal/allwpilib
4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b
[ "BSD-3-Clause" ]
707
2016-05-11T16:54:13.000Z
2022-03-30T13:03:15.000Z
wpilibc/src/test/native/cpp/simulation/AnalogTriggerSimTest.cpp
shueja-personal/allwpilib
4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b
[ "BSD-3-Clause" ]
2,308
2016-05-12T00:17:17.000Z
2022-03-30T20:08:10.000Z
wpilibc/src/test/native/cpp/simulation/AnalogTriggerSimTest.cpp
shueja-personal/allwpilib
4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b
[ "BSD-3-Clause" ]
539
2016-05-11T20:33:26.000Z
2022-03-28T20:20:25.000Z
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "frc/simulation/AnalogTriggerSim.h" // NOLINT(build/include_order) #include <hal/HAL.h> #include "callback_helpers/TestCallbackHelpers.h" #include "frc/AnalogTrigger.h" #include "gtest/gtest.h" namespace frc::sim { TEST(AnalogTriggerSimTest, Initialization) { HAL_Initialize(500, 0); AnalogTriggerSim sim = AnalogTriggerSim::CreateForIndex(0); EXPECT_FALSE(sim.GetInitialized()); BooleanCallback callback; auto cb = sim.RegisterInitializedCallback(callback.GetCallback(), false); AnalogTrigger trigger{0}; EXPECT_TRUE(sim.GetInitialized()); EXPECT_TRUE(callback.WasTriggered()); EXPECT_TRUE(callback.GetLastValue()); } TEST(AnalogTriggerSimTest, TriggerLowerBound) { HAL_Initialize(500, 0); AnalogTrigger trigger{0}; AnalogTriggerSim sim(trigger); DoubleCallback lowerCallback; DoubleCallback upperCallback; auto lowerCb = sim.RegisterTriggerLowerBoundCallback(lowerCallback.GetCallback(), false); auto upperCb = sim.RegisterTriggerUpperBoundCallback(upperCallback.GetCallback(), false); trigger.SetLimitsVoltage(0.299, 1.91); EXPECT_EQ(0.299, sim.GetTriggerLowerBound()); EXPECT_EQ(1.91, sim.GetTriggerUpperBound()); EXPECT_TRUE(lowerCallback.WasTriggered()); EXPECT_EQ(0.299, lowerCallback.GetLastValue()); EXPECT_TRUE(upperCallback.WasTriggered()); EXPECT_EQ(1.91, upperCallback.GetLastValue()); } } // namespace frc::sim
28.732143
80
0.765071
shueja-personal
5ea16254bd340594b68996760722d1463f05ff33
647
cpp
C++
src/bits_of_matcha/tensor/iterations/flatiteration.cpp
patztablook22/matcha-core
c6c595e82a6f2ff42342f28ed856be37a2b2ab5c
[ "MIT" ]
null
null
null
src/bits_of_matcha/tensor/iterations/flatiteration.cpp
patztablook22/matcha-core
c6c595e82a6f2ff42342f28ed856be37a2b2ab5c
[ "MIT" ]
null
null
null
src/bits_of_matcha/tensor/iterations/flatiteration.cpp
patztablook22/matcha-core
c6c595e82a6f2ff42342f28ed856be37a2b2ab5c
[ "MIT" ]
1
2022-01-09T12:07:04.000Z
2022-01-09T12:07:04.000Z
#include "bits_of_matcha/tensor/iterations/flatiteration.h" #include "bits_of_matcha/tensor/iterators/flatiterator.h" #include "bits_of_matcha/tensor/tensor.h" namespace matcha { template <class T, class Access> FlatIteration<T, Access>::FlatIteration(Access& tensor) : tensor_(tensor) {} template <class T, class Access> FlatIterator<T> FlatIteration<T, Access>::begin() { return FlatIterator<T>( reinterpret_cast<T*>(&tensor_.buffer_[0]) ); } template <class T, class Access> FlatIterator<T> FlatIteration<T, Access>::end() { return FlatIterator( reinterpret_cast<T*>(&tensor_.buffer_[0] + tensor_.buffer_.bytes()) ); } }
23.962963
71
0.735703
patztablook22
5ea3878acb0a6799a1327973d36d59e0acf096d6
5,787
cpp
C++
src/Script/gameObjs/majorGos/bushs/Bush.cpp
turesnake/tprPixelGames
6b5471a072a1a8b423834ab04ff03e64df215d5e
[ "BSD-3-Clause" ]
591
2020-03-12T05:10:33.000Z
2022-03-30T13:41:59.000Z
src/Script/gameObjs/majorGos/bushs/Bush.cpp
turesnake/tprPixelGames
6b5471a072a1a8b423834ab04ff03e64df215d5e
[ "BSD-3-Clause" ]
4
2020-04-06T01:55:06.000Z
2020-05-02T04:28:04.000Z
src/Script/gameObjs/majorGos/bushs/Bush.cpp
turesnake/tprPixelGames
6b5471a072a1a8b423834ab04ff03e64df215d5e
[ "BSD-3-Clause" ]
112
2020-04-05T23:55:36.000Z
2022-03-17T11:58:02.000Z
/* * ======================= Bush.cpp ========================== * -- tpr -- * CREATE -- 2019.10.09 * MODIFY -- * ---------------------------------------------------------- */ #include "pch.h" #include "Script/gameObjs/majorGos/bushs/Bush.h" //-------------------- Engine --------------------// #include "animSubspeciesId.h" #include "dyParams.h" #include "esrc_gameSeed.h" //-------------------- Script --------------------// #include "Script/components/windAnim/WindAnim.h" using namespace std::placeholders; namespace gameObjs {//------------- namespace gameObjs ---------------- namespace bush_inn {//----------- namespace: bush_inn ----------------// std::vector<AnimActionEName> windAnimActionEName_pool {}; //----- flags -----// bool isFstCalled {true}; //===== funcs =====// void init()noexcept; }//-------------- namespace: bush_inn end ----------------// class Bush_PvtBinary{ public: Bush_PvtBinary(): windAnimUPtr( std::make_unique<component::WindAnim>() ) {} // Exist but forbidden to call Bush_PvtBinary( const Bush_PvtBinary & ){ tprAssert(0); } Bush_PvtBinary &operator=( const Bush_PvtBinary & ); //------- vals -------// int tmp {0}; std::unique_ptr<component::WindAnim> windAnimUPtr {}; }; Bush_PvtBinary &Bush_PvtBinary::operator=( const Bush_PvtBinary & ){ tprAssert(0); return *this; // never reach } void Bush::init(GameObj &goRef_, const DyParam &dyParams_ ){ //-- simple way ... if( bush_inn::isFstCalled ){ bush_inn::isFstCalled = false; bush_inn::init(); } //================ go.pvtBinary =================// auto *pvtBp = goRef_.init_pvtBinary<Bush_PvtBinary>(); //================ dyParams =================// size_t typeHash = dyParams_.get_typeHash(); tprAssert( typeHash == typeid(DyParams_GoDataForCreate).hash_code() ); const DyParams_GoDataForCreate *bpParamPtr = dyParams_.get_binaryPtr<DyParams_GoDataForCreate>(); const GoDataForCreate *goDataPtr = bpParamPtr->goDataPtr; //----- must before creat_new_goMesh() !!! -----// goRef_.actionDirection.reset( goDataPtr->get_direction() ); goRef_.brokenLvl.reset( goDataPtr->get_brokenLvl() ); goRef_.set_colliDataFromJsonPtr( goDataPtr->get_colliDataFromJsonPtr() ); //================ animFrameSet/animFrameIdxHandle/ goMesh =================// // 有些 bush 只有一个 gomesh,有些则是 复数个 // 一律按 复数个来处理 for( const auto &sptrRef : goDataPtr->get_goMeshs_autoInit() ){ const GoDataForCreate::GoMeshBase &gmRef = *sptrRef; auto &goMeshRef = goRef_.goMeshSet.creat_new_goMesh( gmRef.get_goMeshName(), gmRef.get_subspeciesId(), gmRef.get_animActionEName(), gmRef.get_renderLayerType(), gmRef.get_shaderType(), // pic shader gmRef.get_dposOff(), //- pposoff gmRef.get_zOff(), //- zOff 1151, // uweight tmp gmRef.get_isVisible() //- isVisible ); // 先收集 所有参与 风吹动画的 gomesh 数据 pvtBp->windAnimUPtr->insert_goMesh( &goMeshRef, gmRef.get_windDelayIdx() ); } //----- component: windAnim -----// // 正式 init pvtBp->windAnimUPtr->init( &bush_inn::windAnimActionEName_pool ); //================ bind callback funcs =================// //-- 故意将 首参数this 绑定到 保留类实例 dog_a 身上 goRef_.RenderUpdate = std::bind( &Bush::OnRenderUpdate, _1 ); goRef_.LogicUpdate = std::bind( &Bush::OnLogicUpdate, _1 ); //-------- actionSwitch ---------// goRef_.actionSwitch.bind_func( std::bind( &Bush::OnActionSwitch, _1, _2 ) ); goRef_.actionSwitch.signUp( ActionSwitchType::Idle ); //================ go self vals =================// } void Bush::OnRenderUpdate( GameObj &goRef_ ){ //=====================================// // ptr rebind //-------------------------------------// auto *pvtBp = goRef_.get_pvtBinaryPtr<Bush_PvtBinary>(); //=====================================// // windClock //-------------------------------------// // goMeshRef.bind_animAction() 已经在 update 内被自动调用了 // 这不是一个好实现 // 在未来,可能要被转移到 其他地方 // ... pvtBp->windAnimUPtr->update(); //=====================================// // 将 确认要渲染的 goMeshs,添加到 renderPool //-------------------------------------// goRef_.goMeshSet.render_all_goMeshs_without_callback(); } void Bush::bind( GameObj &goRef_ ){ /* do nothing... */ } void Bush::rebind( GameObj &goRef_ ){ /* do nothing... */ } void Bush::OnLogicUpdate( GameObj &goRef_ ){ /* do nothing... */ } void Bush::OnActionSwitch( GameObj &goRef_, ActionSwitchType type_ ){ /* do nothing... */ } namespace bush_inn {//----------- namespace: bush_inn ----------------// void init()noexcept{ std::default_random_engine randEngine; randEngine.seed( get_new_seed() ); //=== windAnimActionName pool ===// windAnimActionEName_pool.reserve(20); windAnimActionEName_pool.insert( windAnimActionEName_pool.end(), 15, AnimActionEName::Wind ); windAnimActionEName_pool.insert( windAnimActionEName_pool.end(), 1, AnimActionEName::Idle ); std::shuffle( windAnimActionEName_pool.begin(), windAnimActionEName_pool.end(), randEngine ); } }//-------------- namespace: bush_inn end ----------------// }//------------- namespace gameObjs: end ----------------
31.796703
101
0.51633
turesnake
5ea8820da0106fd47dbe8c8727502233e2c7aca2
379
hpp
C++
include/ce2/modules/ae/detail/ae_defines.hpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
include/ce2/modules/ae/detail/ae_defines.hpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
include/ce2/modules/ae/detail/ae_defines.hpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
#pragma once #include "chokoengine.hpp" #define CE_MOD_AE_NS ModuleAE #define CE_BEGIN_MOD_AE_NAMESPACE\ CE_BEGIN_NAMESPACE\ namespace CE_MOD_AE_NS { #define CE_END_MOD_AE_NAMESPACE }\ CE_END_NAMESPACE #if PLATFORM_WIN #ifdef BUILD_MODULE_AE #define CE_AE_EXPORT __declspec(dllexport) #else #define CE_AE_EXPORT __declspec(dllimport) #endif #else #define CE_EXPORT #endif
17.227273
42
0.825858
chokomancarr
5ea906dc45617093f59b7a7d0595d94ba4b23efd
11,885
cc
C++
media/base/android/media_player_bridge.cc
codenote/chromium-test
0637af0080f7e80bf7d20b29ce94c5edc817f390
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/base/android/media_player_bridge.cc
codenote/chromium-test
0637af0080f7e80bf7d20b29ce94c5edc817f390
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/base/android/media_player_bridge.cc
codenote/chromium-test
0637af0080f7e80bf7d20b29ce94c5edc817f390
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:25:45.000Z
2020-11-04T07:25:45.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/base/android/media_player_bridge.h" #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/basictypes.h" #include "base/logging.h" #include "base/message_loop_proxy.h" #include "jni/MediaPlayerBridge_jni.h" #include "jni/MediaPlayer_jni.h" #include "media/base/android/media_player_bridge_manager.h" #include "media/base/android/media_resource_getter.h" using base::android::ConvertUTF8ToJavaString; using base::android::ScopedJavaLocalRef; // Time update happens every 250ms. static const int kTimeUpdateInterval = 250; // Android MediaMetadataRetriever may fail to extract the metadata from the // media under some circumstances. This makes the user unable to perform // seek. To solve this problem, we use a temporary duration of 100 seconds when // the duration is unknown. And we scale the seek position later when duration // is available. static const int kTemporaryDuration = 100; namespace media { MediaPlayerBridge::MediaPlayerBridge( int player_id, const GURL& url, const GURL& first_party_for_cookies, MediaResourceGetter* resource_getter, bool hide_url_log, MediaPlayerBridgeManager* manager, const MediaErrorCB& media_error_cb, const VideoSizeChangedCB& video_size_changed_cb, const BufferingUpdateCB& buffering_update_cb, const MediaMetadataChangedCB& media_metadata_changed_cb, const PlaybackCompleteCB& playback_complete_cb, const SeekCompleteCB& seek_complete_cb, const TimeUpdateCB& time_update_cb, const MediaInterruptedCB& media_interrupted_cb) : media_error_cb_(media_error_cb), video_size_changed_cb_(video_size_changed_cb), buffering_update_cb_(buffering_update_cb), media_metadata_changed_cb_(media_metadata_changed_cb), playback_complete_cb_(playback_complete_cb), seek_complete_cb_(seek_complete_cb), media_interrupted_cb_(media_interrupted_cb), time_update_cb_(time_update_cb), player_id_(player_id), prepared_(false), pending_play_(false), url_(url), first_party_for_cookies_(first_party_for_cookies), hide_url_log_(hide_url_log), duration_(base::TimeDelta::FromSeconds(kTemporaryDuration)), width_(0), height_(0), can_pause_(true), can_seek_forward_(true), can_seek_backward_(true), manager_(manager), resource_getter_(resource_getter), ALLOW_THIS_IN_INITIALIZER_LIST(weak_this_(this)), listener_(base::MessageLoopProxy::current(), weak_this_.GetWeakPtr()) { Initialize(); } MediaPlayerBridge::~MediaPlayerBridge() { Release(); } void MediaPlayerBridge::Initialize() { if (url_.SchemeIsFile()) { cookies_.clear(); ExtractMediaMetadata(url_.spec()); return; } if (url_.SchemeIsFileSystem()) { cookies_.clear(); resource_getter_->GetPlatformPathFromFileSystemURL(url_, base::Bind( &MediaPlayerBridge::ExtractMediaMetadata, weak_this_.GetWeakPtr())); return; } resource_getter_->GetCookies(url_, first_party_for_cookies_, base::Bind( &MediaPlayerBridge::OnCookiesRetrieved, weak_this_.GetWeakPtr())); } void MediaPlayerBridge::CreateMediaPlayer() { JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); j_media_player_.Reset(JNI_MediaPlayer::Java_MediaPlayer_Constructor(env)); jobject j_context = base::android::GetApplicationContext(); DCHECK(j_context); listener_.CreateMediaPlayerListener(j_context, j_media_player_.obj()); } void MediaPlayerBridge::SetVideoSurface(jobject surface) { if (j_media_player_.is_null()) { if (surface == NULL) return; Prepare(); } JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); JNI_MediaPlayer::Java_MediaPlayer_setSurface( env, j_media_player_.obj(), surface); } void MediaPlayerBridge::Prepare() { if (j_media_player_.is_null()) CreateMediaPlayer(); if (url_.SchemeIsFileSystem()) { resource_getter_->GetPlatformPathFromFileSystemURL(url_, base::Bind( &MediaPlayerBridge::SetDataSource, weak_this_.GetWeakPtr())); } else { SetDataSource(url_.spec()); } } void MediaPlayerBridge::SetDataSource(const std::string& url) { if (j_media_player_.is_null()) return; JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); // Create a Java String for the URL. ScopedJavaLocalRef<jstring> j_url_string = ConvertUTF8ToJavaString(env, url); ScopedJavaLocalRef<jstring> j_cookies = ConvertUTF8ToJavaString( env, cookies_); jobject j_context = base::android::GetApplicationContext(); DCHECK(j_context); if (Java_MediaPlayerBridge_setDataSource( env, j_media_player_.obj(), j_context, j_url_string.obj(), j_cookies.obj(), hide_url_log_)) { if (manager_) manager_->RequestMediaResources(this); JNI_MediaPlayer::Java_MediaPlayer_prepareAsync( env, j_media_player_.obj()); } else { media_error_cb_.Run(player_id_, MEDIA_ERROR_FORMAT); } } void MediaPlayerBridge::OnCookiesRetrieved(const std::string& cookies) { cookies_ = cookies; ExtractMediaMetadata(url_.spec()); } void MediaPlayerBridge::ExtractMediaMetadata(const std::string& url) { resource_getter_->ExtractMediaMetadata( url, cookies_, base::Bind(&MediaPlayerBridge::OnMediaMetadataExtracted, weak_this_.GetWeakPtr())); } void MediaPlayerBridge::OnMediaMetadataExtracted( base::TimeDelta duration, int width, int height, bool success) { if (success) { duration_ = duration; width_ = width; height_ = height; } media_metadata_changed_cb_.Run(player_id_, duration_, width_, height_, success); } void MediaPlayerBridge::Start() { if (j_media_player_.is_null()) { pending_play_ = true; Prepare(); } else { if (prepared_) StartInternal(); else pending_play_ = true; } } void MediaPlayerBridge::Pause() { if (j_media_player_.is_null()) { pending_play_ = false; } else { if (prepared_ && IsPlaying()) PauseInternal(); else pending_play_ = false; } } bool MediaPlayerBridge::IsPlaying() { if (!prepared_) return pending_play_; JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); jboolean result = JNI_MediaPlayer::Java_MediaPlayer_isPlaying( env, j_media_player_.obj()); return result; } int MediaPlayerBridge::GetVideoWidth() { if (!prepared_) return width_; JNIEnv* env = base::android::AttachCurrentThread(); return JNI_MediaPlayer::Java_MediaPlayer_getVideoWidth( env, j_media_player_.obj()); } int MediaPlayerBridge::GetVideoHeight() { if (!prepared_) return height_; JNIEnv* env = base::android::AttachCurrentThread(); return JNI_MediaPlayer::Java_MediaPlayer_getVideoHeight( env, j_media_player_.obj()); } void MediaPlayerBridge::SeekTo(base::TimeDelta time) { // Record the time to seek when OnMediaPrepared() is called. pending_seek_ = time; if (j_media_player_.is_null()) Prepare(); else if (prepared_) SeekInternal(time); } base::TimeDelta MediaPlayerBridge::GetCurrentTime() { if (!prepared_) return pending_seek_; JNIEnv* env = base::android::AttachCurrentThread(); return base::TimeDelta::FromMilliseconds( JNI_MediaPlayer::Java_MediaPlayer_getCurrentPosition( env, j_media_player_.obj())); } base::TimeDelta MediaPlayerBridge::GetDuration() { if (!prepared_) return duration_; JNIEnv* env = base::android::AttachCurrentThread(); return base::TimeDelta::FromMilliseconds( JNI_MediaPlayer::Java_MediaPlayer_getDuration( env, j_media_player_.obj())); } void MediaPlayerBridge::Release() { if (j_media_player_.is_null()) return; time_update_timer_.Stop(); if (prepared_) pending_seek_ = GetCurrentTime(); if (manager_) manager_->ReleaseMediaResources(this); prepared_ = false; pending_play_ = false; SetVideoSurface(NULL); JNIEnv* env = base::android::AttachCurrentThread(); JNI_MediaPlayer::Java_MediaPlayer_release(env, j_media_player_.obj()); j_media_player_.Reset(); listener_.ReleaseMediaPlayerListenerResources(); } void MediaPlayerBridge::SetVolume(float left_volume, float right_volume) { if (j_media_player_.is_null()) return; JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); JNI_MediaPlayer::Java_MediaPlayer_setVolume( env, j_media_player_.obj(), left_volume, right_volume); } void MediaPlayerBridge::DoTimeUpdate() { base::TimeDelta current = GetCurrentTime(); time_update_cb_.Run(player_id_, current); } void MediaPlayerBridge::OnMediaError(int error_type) { media_error_cb_.Run(player_id_, error_type); } void MediaPlayerBridge::OnVideoSizeChanged(int width, int height) { width_ = width; height_ = height; video_size_changed_cb_.Run(player_id_, width, height); } void MediaPlayerBridge::OnBufferingUpdate(int percent) { buffering_update_cb_.Run(player_id_, percent); } void MediaPlayerBridge::OnPlaybackComplete() { time_update_timer_.Stop(); playback_complete_cb_.Run(player_id_); } void MediaPlayerBridge::OnMediaInterrupted() { time_update_timer_.Stop(); media_interrupted_cb_.Run(player_id_); } void MediaPlayerBridge::OnSeekComplete() { seek_complete_cb_.Run(player_id_, GetCurrentTime()); } void MediaPlayerBridge::OnMediaPrepared() { if (j_media_player_.is_null()) return; prepared_ = true; base::TimeDelta dur = duration_; duration_ = GetDuration(); if (duration_ != dur && 0 != dur.InMilliseconds()) { // Scale the |pending_seek_| according to the new duration. pending_seek_ = base::TimeDelta::FromSeconds( pending_seek_.InSecondsF() * duration_.InSecondsF() / dur.InSecondsF()); } // If media player was recovered from a saved state, consume all the pending // events. SeekInternal(pending_seek_); if (pending_play_) { StartInternal(); pending_play_ = false; } GetAllowedOperations(); media_metadata_changed_cb_.Run(player_id_, duration_, width_, height_, true); } void MediaPlayerBridge::GetAllowedOperations() { JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); ScopedJavaLocalRef<jobject> allowedOperations = Java_MediaPlayerBridge_getAllowedOperations(env, j_media_player_.obj()); can_pause_ = Java_AllowedOperations_canPause(env, allowedOperations.obj()); can_seek_forward_ = Java_AllowedOperations_canSeekForward( env, allowedOperations.obj()); can_seek_backward_ = Java_AllowedOperations_canSeekBackward( env, allowedOperations.obj()); } void MediaPlayerBridge::StartInternal() { JNIEnv* env = base::android::AttachCurrentThread(); JNI_MediaPlayer::Java_MediaPlayer_start(env, j_media_player_.obj()); if (!time_update_timer_.IsRunning()) { time_update_timer_.Start( FROM_HERE, base::TimeDelta::FromMilliseconds(kTimeUpdateInterval), this, &MediaPlayerBridge::DoTimeUpdate); } } void MediaPlayerBridge::PauseInternal() { JNIEnv* env = base::android::AttachCurrentThread(); JNI_MediaPlayer::Java_MediaPlayer_pause(env, j_media_player_.obj()); time_update_timer_.Stop(); } void MediaPlayerBridge::SeekInternal(base::TimeDelta time) { JNIEnv* env = base::android::AttachCurrentThread(); CHECK(env); int time_msec = static_cast<int>(time.InMilliseconds()); JNI_MediaPlayer::Java_MediaPlayer_seekTo( env, j_media_player_.obj(), time_msec); } bool MediaPlayerBridge::RegisterMediaPlayerBridge(JNIEnv* env) { bool ret = RegisterNativesImpl(env); DCHECK(g_MediaPlayerBridge_clazz); if (ret) ret = JNI_MediaPlayer::RegisterNativesImpl(env); return ret; } } // namespace media
29.638404
80
0.734623
codenote
5eaaa89704591e20926447a76de9cf021a1864ac
1,579
cpp
C++
base/crts/crtw32/rtc/stack.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/crts/crtw32/rtc/stack.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/crts/crtw32/rtc/stack.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*** *stack.cpp - RTC support * * Copyright (c) 1998-2001, Microsoft Corporation. All rights reserved. * * *Revision History: * 07-28-98 JWM Module incorporated into CRTs (from KFrei) * 05-11-99 KBF Error if RTC support define not enabled * 07-15-01 PML Remove all ALPHA, MIPS, and PPC code * ****/ #ifndef _RTC #error RunTime Check support not enabled! #endif #include "rtcpriv.h" /* Stack Checking Calls */ void __declspec(naked) _RTC_CheckEsp() { __asm { jne esperror ; ret esperror: ; function prolog push ebp mov ebp, esp sub esp, __LOCAL_SIZE push eax ; save the old return value push edx push ebx push esi push edi } _RTC_Failure(_ReturnAddress(), _RTC_CHKSTK); __asm { ; function epilog pop edi pop esi pop ebx pop edx ; restore the old return value pop eax mov esp, ebp pop ebp ret } } void __fastcall _RTC_CheckStackVars(void *frame, _RTC_framedesc *v) { int i; for (i = 0; i < v->varCount; i++) { int *head = (int *)(((char *)frame) + v->variables[i].addr + v->variables[i].size); int *tail = (int *)(((char *)frame) + v->variables[i].addr - sizeof(int)); if (*tail != 0xcccccccc || *head != 0xcccccccc) _RTC_StackFailure(_ReturnAddress(), v->variables[i].name); } }
20.506494
92
0.525016
npocmaka
5eac58620adb30b5a225f27e47cf7ed807f85462
4,869
cc
C++
src/PingService.cc
taschik/ramcloud
6ef2e1cd61111995881d54bda6f9296b4777b928
[ "0BSD" ]
1
2016-01-18T12:41:28.000Z
2016-01-18T12:41:28.000Z
src/PingService.cc
taschik/ramcloud
6ef2e1cd61111995881d54bda6f9296b4777b928
[ "0BSD" ]
null
null
null
src/PingService.cc
taschik/ramcloud
6ef2e1cd61111995881d54bda6f9296b4777b928
[ "0BSD" ]
null
null
null
/* Copyright (c) 2011-2012 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "Common.h" #include "CycleCounter.h" #include "Cycles.h" #include "RawMetrics.h" #include "ShortMacros.h" #include "PingClient.h" #include "PingService.h" #include "ServerList.h" namespace RAMCloud { /** * Construct a PingService. * * \param context * Overall information about the RAMCloud server. The caller is assumed * to have associated a serverList with this context; if not, this service * will not return a valid ServerList version in response to pings. */ PingService::PingService(Context* context) : context(context) , ignoreKill(false) { } /** * Top-level service method to handle the GET_METRICS request. * * \copydetails Service::ping */ void PingService::getMetrics(const WireFormat::GetMetrics::Request* reqHdr, WireFormat::GetMetrics::Response* respHdr, Rpc* rpc) { string serialized; metrics->serialize(serialized); respHdr->messageLength = downCast<uint32_t>(serialized.length()); memcpy(new(rpc->replyPayload, APPEND) uint8_t[respHdr->messageLength], serialized.c_str(), respHdr->messageLength); } /** * Top-level service method to handle the PING request. * * \copydetails Service::ping */ void PingService::ping(const WireFormat::Ping::Request* reqHdr, WireFormat::Ping::Response* respHdr, Rpc* rpc) { uint64_t ticks = 0; CycleCounter<> counter(&ticks); string callerId = ServerId(reqHdr->callerId).toString(); ServerId serverId(reqHdr->callerId); if (serverId.isValid()) { // Careful, turning this into a real log message causes spurious // ping timeouts. TEST_LOG("Received ping request from server %s", serverId.toString().c_str()); if (!context->serverList->isUp(serverId)) { respHdr->common.status = STATUS_CALLER_NOT_IN_CLUSTER; } } counter.stop(); double ms = Cycles::toSeconds(ticks) * 1000; if (ms > 10) { LOG(WARNING, "Slow responding to ping request from server %s; " "took %.2f ms", callerId.c_str(), ms); } } /** * Top-level service method to handle the PROXY_PING request. * * \copydetails Service::ping */ void PingService::proxyPing(const WireFormat::ProxyPing::Request* reqHdr, WireFormat::ProxyPing::Response* respHdr, Rpc* rpc) { uint64_t start = Cycles::rdtsc(); PingRpc pingRpc(context, ServerId(reqHdr->serverId)); respHdr->replyNanoseconds = ~0UL; if (pingRpc.wait(reqHdr->timeoutNanoseconds)) { respHdr->replyNanoseconds = Cycles::toNanoseconds( Cycles::rdtsc() - start); } } /** * For debugging and testing this function tells the server to kill itself. * There will be no response to the RPC for this message, and the process * will exit with status code 0. * * TODO(Rumble): Should be only for debugging and performance testing. */ void PingService::kill(const WireFormat::Kill::Request* reqHdr, WireFormat::Kill::Response* respHdr, Rpc* rpc) { LOG(ERROR, "Server remotely told to kill itself."); if (!ignoreKill) exit(0); } /** * Dispatch an RPC to the right handler based on its opcode. */ void PingService::dispatch(WireFormat::Opcode opcode, Rpc* rpc) { switch (opcode) { case WireFormat::GetMetrics::opcode: callHandler<WireFormat::GetMetrics, PingService, &PingService::getMetrics>(rpc); break; case WireFormat::Ping::opcode: callHandler<WireFormat::Ping, PingService, &PingService::ping>(rpc); break; case WireFormat::ProxyPing::opcode: callHandler<WireFormat::ProxyPing, PingService, &PingService::proxyPing>(rpc); break; case WireFormat::Kill::opcode: callHandler<WireFormat::Kill, PingService, &PingService::kill>(rpc); break; default: throw UnimplementedRequestError(HERE); } } } // namespace RAMCloud
31.211538
80
0.659889
taschik
5ead6da0ea4124805da8dfa169fee9826a3c4b94
2,528
cc
C++
thread/test/WeakCallback_test.cc
ririripley/recipes
04267c68a7424326b4aa8dd14b1a879b59ab887c
[ "BSD-3-Clause" ]
1,418
2015-01-07T09:40:09.000Z
2022-03-29T08:37:02.000Z
thread/test/WeakCallback_test.cc
ririripley/recipes
04267c68a7424326b4aa8dd14b1a879b59ab887c
[ "BSD-3-Clause" ]
22
2015-02-17T17:31:18.000Z
2022-02-08T07:00:29.000Z
thread/test/WeakCallback_test.cc
ririripley/recipes
04267c68a7424326b4aa8dd14b1a879b59ab887c
[ "BSD-3-Clause" ]
854
2015-01-03T11:56:10.000Z
2022-03-31T08:50:28.000Z
#include "../WeakCallback.h" #define BOOST_TEST_MAIN #ifdef BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #else #include <boost/test/included/unit_test.hpp> #endif #include <stdio.h> #include <boost/noncopyable.hpp> class String { public: String(const char* str) { printf("String ctor this %p\n", this); } String(const String& rhs) { printf("String copy ctor this %p, rhs %p\n", this, &rhs); } String(String&& rhs) { printf("String move ctor this %p, rhs %p\n", this, &rhs); } }; class Foo : boost::noncopyable { public: void zero(); void zeroc() const; void one(int); void oner(int&); void onec(int) const; void oneString(const String& str); void oneStringRR(String&& str); }; void Foo::zero() { printf("Foo::zero()\n"); } void Foo::zeroc() const { printf("Foo::zeroc()\n"); } void Foo::one(int x) { printf("Foo::one() x=%d\n", x); } void Foo::oner(int& x) { printf("Foo::oner() x=%d\n", x); x = 1000; } void Foo::onec(int x) const { printf("Foo::onec() x=%d\n", x); } void Foo::oneString(const String& str) { printf("Foo::oneString\n"); } void Foo::oneStringRR(String&& str) { printf("Foo::oneStringRR\n"); } String getString() { return String("zz"); } BOOST_AUTO_TEST_CASE(testMove) { String s("xx"); Foo f; f.oneString(s); f.oneString(String("yy")); // f.oneStringRR(s); f.oneStringRR(String("yy")); f.oneString(getString()); f.oneStringRR(getString()); } BOOST_AUTO_TEST_CASE(testWeakCallback) { printf("======== testWeakCallback \n"); std::shared_ptr<Foo> foo(new Foo); muduo::WeakCallback<Foo> cb0 = muduo::makeWeakCallback(foo, &Foo::zero); muduo::WeakCallback<Foo> cb0c = muduo::makeWeakCallback(foo, &Foo::zeroc); cb0(); cb0c(); muduo::WeakCallback<Foo, int> cb1 = muduo::makeWeakCallback(foo, &Foo::one); auto cb1c = muduo::makeWeakCallback(foo, &Foo::onec); auto cb1r = muduo::makeWeakCallback(foo, &Foo::oner); cb1(123); cb1c(234); int i = 345; cb1r(i); BOOST_CHECK_EQUAL(i, 1000); auto cb2 = muduo::makeWeakCallback(foo, &Foo::oneString); auto cb2r = muduo::makeWeakCallback(foo, &Foo::oneStringRR); printf("_Z%s\n", typeid(cb2).name()); printf("_Z%s\n", typeid(cb2r).name()); cb2(String("xx")); cb2r(String("yy")); muduo::WeakCallback<Foo> cb3(foo, std::bind(&Foo::oneString, std::placeholders::_1, "zz")); cb3(); printf("======== reset \n"); foo.reset(); cb0(); cb0c(); cb1(123); cb1c(234); cb2(String("xx")); cb2r(String("yy")); cb3(); }
18.588235
93
0.629351
ririripley
5eadd409f127c8b4fcf46a006fd9a0e3ac303e55
1,694
cpp
C++
clang/test/Driver/sycl-offload.cpp
steffenlarsen/llvm
9d60c3d97773c63b8ee597c35c3f897dbc1a7f9f
[ "Apache-2.0" ]
null
null
null
clang/test/Driver/sycl-offload.cpp
steffenlarsen/llvm
9d60c3d97773c63b8ee597c35c3f897dbc1a7f9f
[ "Apache-2.0" ]
null
null
null
clang/test/Driver/sycl-offload.cpp
steffenlarsen/llvm
9d60c3d97773c63b8ee597c35c3f897dbc1a7f9f
[ "Apache-2.0" ]
null
null
null
/// Check "-aux-target-cpu" and "target-cpu" are passed when compiling for SYCL offload device and host codes: // RUN: %clang -### -fsycl -c %s 2>&1 | FileCheck -check-prefix=CHECK-OFFLOAD %s // CHECK-OFFLOAD: clang{{.*}} "-cc1" {{.*}} "-fsycl-is-device" // CHECK-OFFLOAD-SAME: "-aux-target-cpu" "[[HOST_CPU_NAME:[^ ]+]]" // CHECK-OFFLOAD-NEXT: clang{{.*}} "-cc1" {{.*}} // CHECK-OFFLOAD-NEXT-SAME: "-fsycl-is-host" // CHECK-OFFLOAD-NEXT-SAME: "-target-cpu" "[[HOST_CPU_NAME]]" /// Check "-aux-target-cpu" with "-aux-target-feature" and "-target-cpu" with "-target-feature" are passed /// when compiling for SYCL offload device and host codes: // RUN: %clang -fsycl -mavx -c %s -### -o %t.o 2>&1 | FileCheck -check-prefix=OFFLOAD-AVX %s // OFFLOAD-AVX: clang{{.*}} "-cc1" {{.*}} "-fsycl-is-device" // OFFLOAD-AVX-SAME: "-aux-target-cpu" "[[HOST_CPU_NAME:[^ ]+]]" "-aux-target-feature" "+avx" // OFFLOAD-AVX-NEXT: clang{{.*}} "-cc1" {{.*}} // OFFLOAD-AVX-NEXT-SAME: "-fsycl-is-host" // OFFLOAD-AVX-NEXT-SAME: "-target-cpu" "[[HOST_CPU_NAME]]" "-target-feature" "+avx" /// Check that the needed -fsycl -fsycl-is-device and -fsycl-is-host options /// are passed to all of the needed compilation steps regardless of final /// phase. // RUN: %clang -### -fsycl -c %s 2>&1 | FileCheck -check-prefix=CHECK-OPTS %s // RUN: %clang -### -fsycl -E %s 2>&1 | FileCheck -check-prefix=CHECK-OPTS %s // RUN: %clang -### -fsycl -S %s 2>&1 | FileCheck -check-prefix=CHECK-OPTS %s // RUN: %clang -### -fsycl %s 2>&1 | FileCheck -check-prefix=CHECK-OPTS %s // CHECK-OPTS: clang{{.*}} "-cc1" {{.*}} "-fsycl" "-fsycl-is-device" // CHECK-OPTS: clang{{.*}} "-cc1" {{.*}} "-fsycl" "-fsycl-is-host"
62.740741
110
0.619835
steffenlarsen
5eaf05902abdb938a52200beeb204c685b041d2b
20,651
cpp
C++
src/jnc_ct/jnc_ct_OperatorMgr/jnc_ct_CastOp_DataPtr.cpp
project-kotinos/vovkos___jancy
7050c9edba3185f8293b3e06766f31970ff1ed1a
[ "MIT" ]
null
null
null
src/jnc_ct/jnc_ct_OperatorMgr/jnc_ct_CastOp_DataPtr.cpp
project-kotinos/vovkos___jancy
7050c9edba3185f8293b3e06766f31970ff1ed1a
[ "MIT" ]
null
null
null
src/jnc_ct/jnc_ct_OperatorMgr/jnc_ct_CastOp_DataPtr.cpp
project-kotinos/vovkos___jancy
7050c9edba3185f8293b3e06766f31970ff1ed1a
[ "MIT" ]
null
null
null
//.............................................................................. // // This file is part of the Jancy toolkit. // // Jancy is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/jancy/license.txt // //.............................................................................. #include "pch.h" #include "jnc_ct_CastOp_DataPtr.h" #include "jnc_ct_Module.h" #include "jnc_ct_ArrayType.h" #include "jnc_ct_LeanDataPtrValidator.h" namespace jnc { namespace ct { //.............................................................................. CastKind Cast_DataPtr_FromArray::getCastKind( const Value& opValue, Type* type ) { if (isArrayRefType(opValue.getType())) { Value ptrValue = m_module->m_operatorMgr.prepareOperandType(opValue, OpFlag_ArrayRefToPtr); return m_module->m_operatorMgr.getCastKind(ptrValue, type); } ASSERT(opValue.getType()->getTypeKind() == TypeKind_Array); ASSERT(type->getTypeKind() == TypeKind_DataPtr); ArrayType* srcType = (ArrayType*)opValue.getType(); DataPtrType* dstType = (DataPtrType*)type; Type* arrayElementType = srcType->getElementType(); Type* ptrDataType = dstType->getTargetType(); return arrayElementType->cmp(ptrDataType) == 0 ? CastKind_Implicit : (arrayElementType->getFlags() & TypeFlag_Pod) ? ptrDataType->getTypeKind() == TypeKind_Void ? CastKind_Implicit : (ptrDataType->getFlags() & TypeFlag_Pod) ? CastKind_Explicit : CastKind_None : CastKind_None; } bool Cast_DataPtr_FromArray::constCast( const Value& opValue, Type* type, void* dst ) { if (isArrayRefType(opValue.getType())) { Value ptrValue; bool result = m_module->m_operatorMgr.prepareOperand(opValue, &ptrValue, OpFlag_ArrayRefToPtr) && m_module->m_operatorMgr.castOperator(&ptrValue, type); if (!result) return false; const void* p = ptrValue.getConstData(); if (((DataPtrType*)type)->getPtrTypeKind() == DataPtrTypeKind_Normal) *(DataPtr*)dst = *(DataPtr*)p; else // thin or lean *(void**) dst = *(void**) p; return true; } ASSERT(opValue.getType()->getTypeKind() == TypeKind_Array); ASSERT(type->getTypeKind() == TypeKind_DataPtr); ArrayType* srcType = (ArrayType*)opValue.getType(); DataPtrType* dstType = (DataPtrType*)type; const Value& savedOpValue = m_module->m_constMgr.saveValue(opValue); const void* p = savedOpValue.getConstData(); AXL_TODO("create a global constant holding the array") if (dstType->getPtrTypeKind() == DataPtrTypeKind_Normal) { DataPtr* ptr = (DataPtr*)dst; ptr->m_p = (void*)p; ptr->m_validator = m_module->m_constMgr.createConstDataPtrValidator(p, srcType); } else // thin or lean { *(const void**) dst = p; } return true; } bool Cast_DataPtr_FromArray::llvmCast( const Value& opValue, Type* type, Value* resultValue ) { if (isArrayRefType(opValue.getType())) { Value ptrValue; return m_module->m_operatorMgr.prepareOperand(opValue, &ptrValue, OpFlag_ArrayRefToPtr) && m_module->m_operatorMgr.castOperator(ptrValue, type, resultValue); } err::setFormatStringError("casting from array to pointer is currently only implemented for constants"); return false; } //.............................................................................. CastKind Cast_DataPtr_FromClassPtr::getCastKind( const Value& opValue, Type* type ) { ASSERT(opValue.getType()->getTypeKindFlags() & TypeKindFlag_ClassPtr); ASSERT(type->getTypeKind() == TypeKind_DataPtr); DataPtrType* dstType = (DataPtrType*)type; ClassPtrType* srcType = (ClassPtrType*)opValue.getType(); bool isSrcConst = (srcType->getFlags() & PtrTypeFlag_Const) != 0; bool isDstConst = (dstType->getFlags() & PtrTypeFlag_Const) != 0; return isSrcConst && !isDstConst ? CastKind_None : dstType->getPtrTypeKind() != DataPtrTypeKind_Thin ? CastKind_None : dstType->getTargetType()->getTypeKind() == TypeKind_Void ? CastKind_ImplicitCrossFamily : CastKind_Explicit; } bool Cast_DataPtr_FromClassPtr::llvmCast( const Value& opValue, Type* type, Value* resultValue ) { ASSERT(opValue.getType()->getTypeKindFlags() & TypeKindFlag_ClassPtr); ASSERT(type->getTypeKind() == TypeKind_DataPtr); DataPtrType* dstType = (DataPtrType*)type; ClassPtrType* srcType = (ClassPtrType*)opValue.getType(); bool isSrcConst = (srcType->getFlags() & PtrTypeFlag_Const) != 0; bool isDstConst = (dstType->getFlags() & PtrTypeFlag_Const) != 0; if (isSrcConst && !isDstConst) { setCastError(opValue, type); return false; } if (dstType->getPtrTypeKind() == DataPtrTypeKind_Thin) { err::setFormatStringError("casting from class pointer to fat data pointer is not yet implemented (thin only for now)"); return false; } if (!m_module->m_operatorMgr.isUnsafeRgn()) { setUnsafeCastError(srcType, dstType); return false; } m_module->m_llvmIrBuilder.createBitCast(opValue, type, resultValue); return true; } //.............................................................................. CastKind Cast_DataPtr_FromFunctionPtr::getCastKind( const Value& opValue, Type* type ) { ASSERT(opValue.getType()->getTypeKindFlags() & TypeKindFlag_FunctionPtr); ASSERT(type->getTypeKind() == TypeKind_DataPtr); DataPtrType* dstType = (DataPtrType*)type; FunctionPtrType* srcType = (FunctionPtrType*)opValue.getType(); return srcType->getPtrTypeKind() != FunctionPtrTypeKind_Thin ? CastKind_None : dstType->getPtrTypeKind() != DataPtrTypeKind_Thin ? CastKind_None : dstType->getTargetType()->getTypeKind() == TypeKind_Void ? CastKind_ImplicitCrossFamily : CastKind_Explicit; } bool Cast_DataPtr_FromFunctionPtr::llvmCast( const Value& opValue, Type* type, Value* resultValue ) { ASSERT(opValue.getType()->getTypeKindFlags() & TypeKindFlag_FunctionPtr); ASSERT(type->getTypeKind() == TypeKind_DataPtr); DataPtrType* dstType = (DataPtrType*)type; FunctionPtrType* srcType = (FunctionPtrType*)opValue.getType(); if (srcType->getPtrTypeKind() != FunctionPtrTypeKind_Thin || dstType->getPtrTypeKind() != DataPtrTypeKind_Thin) { setCastError(opValue, type); return false; } if (!m_module->m_operatorMgr.isUnsafeRgn()) { setUnsafeCastError(srcType, dstType); return false; } m_module->m_llvmIrBuilder.createBitCast(opValue, type, resultValue); return true; } //.............................................................................. CastKind Cast_DataPtr_FromPropertyPtr::getCastKind( const Value& opValue, Type* type ) { ASSERT(opValue.getType()->getTypeKindFlags() & TypeKindFlag_PropertyPtr); ASSERT(type->getTypeKind() == TypeKind_DataPtr); DataPtrType* dstType = (DataPtrType*)type; PropertyPtrType* srcType = (PropertyPtrType*)opValue.getType(); return srcType->getPtrTypeKind() != PropertyPtrTypeKind_Thin ? CastKind_None : dstType->getPtrTypeKind() != DataPtrTypeKind_Thin ? CastKind_None : dstType->getTargetType()->getTypeKind() == TypeKind_Void ? CastKind_ImplicitCrossFamily : CastKind_Explicit; } bool Cast_DataPtr_FromPropertyPtr::llvmCast( const Value& opValue, Type* type, Value* resultValue ) { ASSERT(opValue.getType()->getTypeKindFlags() & TypeKindFlag_PropertyPtr); ASSERT(type->getTypeKind() == TypeKind_DataPtr); DataPtrType* dstType = (DataPtrType*)type; PropertyPtrType* srcType = (PropertyPtrType*)opValue.getType(); if (srcType->getPtrTypeKind() != PropertyPtrTypeKind_Thin || dstType->getPtrTypeKind() != DataPtrTypeKind_Thin) { setCastError(opValue, type); return false; } if (!m_module->m_operatorMgr.isUnsafeRgn()) { setUnsafeCastError(srcType, dstType); return false; } m_module->m_llvmIrBuilder.createBitCast(opValue, type, resultValue); return true; } //.............................................................................. CastKind Cast_DataPtr_Base::getCastKind( const Value& opValue, Type* type ) { ASSERT(opValue.getType()->getTypeKindFlags() & TypeKindFlag_DataPtr); ASSERT(type->getTypeKind() == TypeKind_DataPtr); DataPtrType* srcType = (DataPtrType*)opValue.getType(); DataPtrType* dstType = (DataPtrType*)type; bool isSrcConst = (srcType->getFlags() & PtrTypeFlag_Const) != 0; bool isDstConst = (dstType->getFlags() & PtrTypeFlag_Const) != 0; if (isSrcConst && !isDstConst) return CastKind_None; // const vs non-const mismatch CastKind implicitCastKind = isDstConst != isSrcConst ? CastKind_ImplicitCrossConst : CastKind_Implicit; Type* srcDataType = srcType->getTargetType(); Type* dstDataType = dstType->getTargetType(); if (srcDataType->cmp(dstDataType) == 0) return implicitCastKind; bool isSrcPod = (srcDataType->getFlags() & TypeFlag_Pod) != 0; bool isDstPod = (dstDataType->getFlags() & TypeFlag_Pod) != 0; bool isDstDerivable = (dstDataType->getTypeKindFlags() & TypeKindFlag_Derivable) != 0; bool canCastToPod = isSrcPod || isDstConst || dstType->getPtrTypeKind() == DataPtrTypeKind_Thin; if (dstDataType->getStdType() == StdType_AbstractData || dstDataType->getTypeKind() == TypeKind_Void && canCastToPod) return implicitCastKind; if (srcDataType->getTypeKind() == TypeKind_Void && (dstDataType->getTypeKind() == TypeKind_Int8 || dstDataType->getTypeKind() == TypeKind_Int8_u)) return implicitCastKind; if ((srcDataType->getTypeKindFlags() & TypeKindFlag_Integer) && (dstDataType->getTypeKindFlags() & TypeKindFlag_Integer) && srcDataType->getSize() == dstDataType->getSize()) return implicitCastKind; bool isDstBase = srcDataType->getTypeKind() == TypeKind_Struct && ((StructType*)srcDataType)->findBaseTypeTraverse(dstDataType); return isDstBase ? implicitCastKind : isDstPod && canCastToPod ? CastKind_Explicit : isDstDerivable ? CastKind_Dynamic : CastKind_None; } size_t Cast_DataPtr_Base::getOffset( DataPtrType* srcType, DataPtrType* dstType, BaseTypeCoord* coord ) { bool isSrcConst = (srcType->getFlags() & PtrTypeFlag_Const) != 0; bool isDstConst = (dstType->getFlags() & PtrTypeFlag_Const) != 0; if (isSrcConst && !isDstConst) { setCastError(srcType, dstType); return -1; } Type* srcDataType = srcType->getTargetType(); Type* dstDataType = dstType->getTargetType(); if (srcDataType->cmp(dstDataType) == 0) return 0; bool isSrcPod = (srcDataType->getFlags() & TypeFlag_Pod) != 0; bool isDstPod = (dstDataType->getFlags() & TypeFlag_Pod) != 0; bool isDstDerivable = (dstDataType->getTypeKindFlags() & TypeKindFlag_Derivable) != 0; bool canCastToPod = isSrcPod || isDstConst || dstType->getPtrTypeKind() == DataPtrTypeKind_Thin; if (dstDataType->getStdType() == StdType_AbstractData || dstDataType->getTypeKind() == TypeKind_Void && canCastToPod) return 0; bool isDstBase = srcDataType->getTypeKind() == TypeKind_Struct && ((StructType*)srcDataType)->findBaseTypeTraverse(dstDataType, coord); if (isDstBase) return coord->m_offset; if (isDstPod && canCastToPod) return 0; CastKind castKind = isDstDerivable? CastKind_Dynamic : CastKind_None; setCastError(srcType, dstType, castKind); return -1; } bool Cast_DataPtr_Base::getOffsetUnsafePtrValue( const Value& ptrValue, DataPtrType* srcType, DataPtrType* dstType, bool isFat, Value* resultValue ) { BaseTypeCoord coord; size_t offset = getOffset(srcType, dstType, &coord); if (offset == -1) return false; if (isFat) dstType = (DataPtrType*)m_module->m_typeMgr.getStdType(StdType_BytePtr); else if (dstType->getPtrTypeKind() != DataPtrTypeKind_Thin) dstType = dstType->getTargetType()->getDataPtrType_c(); if (!coord.m_llvmIndexArray.isEmpty()) { coord.m_llvmIndexArray.insert(0, 0); srcType = srcType->getTargetType()->getDataPtrType_c(); Value tmpValue; m_module->m_llvmIrBuilder.createBitCast(ptrValue, srcType, &tmpValue); m_module->m_llvmIrBuilder.createGep( tmpValue, coord.m_llvmIndexArray, coord.m_llvmIndexArray.getCount(), dstType, &tmpValue ); if (isFat) m_module->m_llvmIrBuilder.createBitCast(tmpValue, dstType, resultValue); return true; } ASSERT(offset == 0); m_module->m_llvmIrBuilder.createBitCast(ptrValue, dstType, resultValue); return true; } //.............................................................................. bool Cast_DataPtr_Normal2Normal::constCast( const Value& opValue, Type* type, void* dst ) { ASSERT(opValue.getType()->getTypeKindFlags() & TypeKindFlag_DataPtr); ASSERT(type->getTypeKind() == TypeKind_DataPtr); size_t offset = getOffset((DataPtrType*)opValue.getType(), (DataPtrType*)type, NULL); if (offset == -1) return false; DataPtr* dstPtr = (DataPtr*)dst; DataPtr* srcPtr = (DataPtr*)opValue.getConstData(); dstPtr->m_p = (char*)srcPtr->m_p + offset; dstPtr->m_validator = srcPtr->m_validator; return true; } bool Cast_DataPtr_Normal2Normal::llvmCast( const Value& opValue, Type* type, Value* resultValue ) { ASSERT(opValue.getType()->getTypeKindFlags() & TypeKindFlag_DataPtr); ASSERT(type->getTypeKind() == TypeKind_DataPtr); bool result; if (type->getFlags() & PtrTypeFlag_Safe) { result = m_module->m_operatorMgr.checkDataPtrRange(opValue); if (!result) return false; } BaseTypeCoord coord; size_t offset = getOffset((DataPtrType*)opValue.getType(), (DataPtrType*)type, &coord); if (offset == -1) return false; if (!offset) { resultValue->overrideType(opValue, type); return true; } Value ptrValue; m_module->m_llvmIrBuilder.createExtractValue(opValue, 0, NULL, &ptrValue); result = getOffsetUnsafePtrValue(ptrValue, (DataPtrType*)opValue.getType(), (DataPtrType*)type, true, &ptrValue); if (!result) return false; m_module->m_llvmIrBuilder.createInsertValue(opValue, ptrValue, 0, type, resultValue); return true; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bool Cast_DataPtr_Lean2Normal::constCast( const Value& opValue, Type* type, void* dst ) { ASSERT(opValue.getType()->getTypeKindFlags() & TypeKindFlag_DataPtr); ASSERT(type->getTypeKind() == TypeKind_DataPtr); DataPtrType* srcPtrType = (DataPtrType*)opValue.getType(); ASSERT(srcPtrType->getPtrTypeKind() == DataPtrTypeKind_Lean); size_t offset = getOffset(srcPtrType, (DataPtrType*)type, NULL); if (offset == -1) return false; DataPtr* dstPtr = (DataPtr*)dst; const void* src = opValue.getConstData(); const void* p = (char*)src + offset; dstPtr->m_p = (void*)p; dstPtr->m_validator = m_module->m_constMgr.createConstDataPtrValidator(p, srcPtrType->getTargetType()); return true; } bool Cast_DataPtr_Lean2Normal::llvmCast( const Value& opValue, Type* type, Value* resultValue ) { ASSERT(opValue.getType()->getTypeKindFlags() & TypeKindFlag_DataPtr); ASSERT(type->getTypeKind() == TypeKind_DataPtr); bool result; DataPtrType* srcPtrType = (DataPtrType*)opValue.getType(); ASSERT(srcPtrType->getPtrTypeKind() == DataPtrTypeKind_Lean); Value ptrValue; result = getOffsetUnsafePtrValue(opValue, (DataPtrType*)opValue.getType(), (DataPtrType*)type, true, &ptrValue); if (!result) return false; if (type->getFlags() & PtrTypeFlag_Safe) { result = m_module->m_operatorMgr.checkDataPtrRange(opValue); if (!result) return false; } LeanDataPtrValidator* validator = opValue.getLeanDataPtrValidator(); Value validatorValue = validator->getValidatorValue(); Value tmpValue = type->getUndefValue(); m_module->m_llvmIrBuilder.createInsertValue(tmpValue, ptrValue, 0, NULL, &tmpValue); m_module->m_llvmIrBuilder.createInsertValue(tmpValue, validatorValue, 1, type, resultValue); return true; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bool Cast_DataPtr_Normal2Thin::constCast( const Value& opValue, Type* type, void* dst ) { ASSERT(opValue.getType()->getTypeKindFlags() & TypeKindFlag_DataPtr); ASSERT(type->getTypeKind() == TypeKind_DataPtr); size_t offset = getOffset((DataPtrType*)opValue.getType(), (DataPtrType*)type, NULL); if (offset == -1) return false; *(char**) dst = *(char**) opValue.getConstData() + offset; return true; } bool Cast_DataPtr_Normal2Thin::llvmCast( const Value& opValue, Type* type, Value* resultValue ) { ASSERT(opValue.getType()->getTypeKindFlags() & TypeKindFlag_DataPtr); ASSERT(type->getTypeKind() == TypeKind_DataPtr); Value ptrValue; m_module->m_llvmIrBuilder.createExtractValue(opValue, 0, NULL, &ptrValue); return getOffsetUnsafePtrValue(ptrValue, (DataPtrType*)opValue.getType(), (DataPtrType*)type, false, resultValue); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bool Cast_DataPtr_Lean2Thin::llvmCast( const Value& opValue, Type* type, Value* resultValue ) { ASSERT(opValue.getType()->getTypeKindFlags() & TypeKindFlag_DataPtr); ASSERT(type->getTypeKind() == TypeKind_DataPtr); return getOffsetUnsafePtrValue(opValue, (DataPtrType*)opValue.getType(), (DataPtrType*)type, false, resultValue); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bool Cast_DataPtr_Thin2Thin::constCast( const Value& opValue, Type* type, void* dst ) { ASSERT(opValue.getType()->getTypeKindFlags() & TypeKindFlag_DataPtr); ASSERT(type->getTypeKind() == TypeKind_DataPtr); size_t offset = getOffset((DataPtrType*)opValue.getType(), (DataPtrType*)type, NULL); if (offset == -1) return false; *(char**) dst = *(char**) opValue.getConstData() + offset; return true; } //.............................................................................. Cast_DataPtr::Cast_DataPtr() { memset(m_operatorTable, 0, sizeof(m_operatorTable)); m_operatorTable[DataPtrTypeKind_Normal][DataPtrTypeKind_Normal] = &m_normal2Normal; m_operatorTable[DataPtrTypeKind_Normal][DataPtrTypeKind_Thin] = &m_normal2Thin; m_operatorTable[DataPtrTypeKind_Lean][DataPtrTypeKind_Normal] = &m_lean2Normal; m_operatorTable[DataPtrTypeKind_Lean][DataPtrTypeKind_Thin] = &m_lean2Thin; m_operatorTable[DataPtrTypeKind_Thin][DataPtrTypeKind_Thin] = &m_thin2Thin; m_opFlags = OpFlag_KeepDerivableRef; } CastOperator* Cast_DataPtr::getCastOperator( const Value& opValue, Type* type ) { ASSERT(type->getTypeKind() == TypeKind_DataPtr); DataPtrType* dstPtrType = (DataPtrType*)type; DataPtrTypeKind dstPtrTypeKind = dstPtrType->getPtrTypeKind(); Type* srcType = opValue.getType(); if (isArrayRefType(srcType)) return &m_fromArray; TypeKind typeKind = srcType->getTypeKind(); switch (typeKind) { case TypeKind_DataPtr: case TypeKind_DataRef: break; case TypeKind_Array: return &m_fromArray; case TypeKind_ClassPtr: case TypeKind_ClassRef: return &m_fromClassPtr; case TypeKind_FunctionPtr: case TypeKind_FunctionRef: return &m_fromFunctionPtr; case TypeKind_PropertyPtr: case TypeKind_PropertyRef: return &m_fromPropertyPtr; default: return NULL; } DataPtrType* srcPtrType = (DataPtrType*)srcType; DataPtrTypeKind srcPtrTypeKind = srcPtrType->getPtrTypeKind(); if (dstPtrTypeKind == DataPtrTypeKind_Normal && (srcPtrType->getFlags() & PtrTypeFlag_Const) && !(dstPtrType->getFlags() & PtrTypeFlag_Const)) return NULL; ASSERT((size_t)srcPtrTypeKind < DataPtrTypeKind__Count); ASSERT((size_t)dstPtrTypeKind < DataPtrTypeKind__Count); return m_operatorTable[srcPtrTypeKind][dstPtrTypeKind]; } //.............................................................................. CastKind Cast_DataRef::getCastKind( const Value& opValue, Type* type ) { ASSERT(type->getTypeKind() == TypeKind_DataRef); Type* intermediateSrcType = m_module->m_operatorMgr.getUnaryOperatorResultType(UnOpKind_Addr, opValue); if (!intermediateSrcType) return CastKind_None; DataPtrType* ptrType = (DataPtrType*)type; DataPtrType* intermediateDstType = ptrType->getTargetType()->getDataPtrType( TypeKind_DataPtr, ptrType->getPtrTypeKind(), ptrType->getFlags() ); return m_module->m_operatorMgr.getCastKind(intermediateSrcType, intermediateDstType); } bool Cast_DataRef::llvmCast( const Value& opValue, Type* type, Value* resultValue ) { ASSERT(type->getTypeKind() == TypeKind_DataRef); DataPtrType* ptrType = (DataPtrType*)type; DataPtrType* intermediateType = ptrType->getTargetType()->getDataPtrType( TypeKind_DataPtr, ptrType->getPtrTypeKind(), ptrType->getFlags() ); Value intermediateValue; return m_module->m_operatorMgr.unaryOperator(UnOpKind_Addr, opValue, &intermediateValue) && m_module->m_operatorMgr.castOperator(&intermediateValue, intermediateType) && m_module->m_operatorMgr.unaryOperator(UnOpKind_Indir, intermediateValue, resultValue); } //.............................................................................. } // namespace ct } // namespace jnc
27.244063
121
0.702048
project-kotinos
5eb38f1610c536d5bae4e478119b780d351fa8f9
6,296
cpp
C++
third_party/android_crazy_linker/src/src/crazy_linker_util_unittest.cpp
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
third_party/android_crazy_linker/src/src/crazy_linker_util_unittest.cpp
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
third_party/android_crazy_linker/src/src/crazy_linker_util_unittest.cpp
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "crazy_linker_util.h" #include <gtest/gtest.h> #include <utility> namespace crazy { TEST(GetBaseNamePtr, Test) { const char kString[] = "/tmp/foo"; EXPECT_EQ(kString + 5, GetBaseNamePtr(kString)); } TEST(String, Empty) { String s; EXPECT_TRUE(s.IsEmpty()); EXPECT_EQ(0u, s.size()); EXPECT_EQ('\0', s.c_str()[0]); } TEST(String, CStringConstructor) { String s("Simple"); EXPECT_STREQ("Simple", s.c_str()); EXPECT_EQ(6U, s.size()); } TEST(String, CStringConstructorWithLength) { String s2("Simple", 3); EXPECT_STREQ("Sim", s2.c_str()); EXPECT_EQ(3U, s2.size()); } TEST(String, CopyConstructor) { String s1("Simple"); String s2(s1); EXPECT_EQ(6U, s2.size()); EXPECT_STREQ(s2.c_str(), s1.c_str()); } TEST(String, MoveConstructor) { String s1("Source"); String s2(std::move(s1)); EXPECT_TRUE(s1.IsEmpty()); EXPECT_EQ(6U, s2.size()); EXPECT_STREQ(s2.c_str(), "Source"); } TEST(String, CharConstructor) { String s('H'); EXPECT_EQ(1U, s.size()); EXPECT_STREQ("H", s.c_str()); } TEST(String, CopyAssign) { String s1("Source"); String s2("Destination"); s1 = s2; EXPECT_STREQ(s1.c_str(), s2.c_str()); } TEST(String, MoveAssign) { String s1("Source"); String s2("Destination"); s2 = std::move(s1); EXPECT_TRUE(s1.IsEmpty()); EXPECT_STREQ("Source", s2.c_str()); } TEST(String, AppendCString) { String s("Foo"); s += "Bar"; EXPECT_STREQ("FooBar", s.c_str()); s += "Zoo"; EXPECT_STREQ("FooBarZoo", s.c_str()); } TEST(String, AppendOther) { String s("Foo"); String s2("Bar"); s += s2; EXPECT_STREQ("FooBar", s.c_str()); } TEST(String, ArrayAccess) { String s("FooBar"); EXPECT_EQ('F', s[0]); EXPECT_EQ('o', s[1]); EXPECT_EQ('o', s[2]); EXPECT_EQ('B', s[3]); EXPECT_EQ('a', s[4]); EXPECT_EQ('r', s[5]); EXPECT_EQ('\0', s[6]); } TEST(String, EqualityOperators) { String a("Foo"); String b("Bar"); EXPECT_TRUE(a == String("Foo")); EXPECT_TRUE(a == "Foo"); EXPECT_TRUE(b != String("Foo")); EXPECT_TRUE(b != "Foo"); EXPECT_TRUE(a != b); EXPECT_TRUE(b == String("Bar")); EXPECT_TRUE(b == "Bar"); EXPECT_FALSE(a == "Foo "); EXPECT_FALSE(b == " Bar"); EXPECT_FALSE(a == "foo"); EXPECT_TRUE(a != "Foo "); EXPECT_TRUE(b != " Bar"); EXPECT_TRUE(a != "foo"); } TEST(String, Resize) { String s("A very long string to have fun"); s.Resize(10); EXPECT_EQ(10U, s.size()); EXPECT_STREQ("A very lon", s.c_str()); } TEST(String, ResizeToZero) { String s("Long string to force a dynamic allocation"); s.Resize(0); EXPECT_EQ(0U, s.size()); EXPECT_STREQ("", s.c_str()); } TEST(Vector, IsEmpty) { Vector<void*> v; EXPECT_TRUE(v.IsEmpty()); } TEST(Vector, PushBack) { Vector<int> v; v.PushBack(12345); EXPECT_FALSE(v.IsEmpty()); EXPECT_EQ(1U, v.GetCount()); EXPECT_EQ(12345, v[0]); } TEST(Vector, PushBack2) { const int kMaxCount = 500; Vector<int> v; for (int n = 0; n < kMaxCount; ++n) v.PushBack(n * 100); EXPECT_FALSE(v.IsEmpty()); EXPECT_EQ(static_cast<size_t>(kMaxCount), v.GetCount()); } TEST(Vector, MoveConstructor) { const int kMaxCount = 500; Vector<int> v1; for (int n = 0; n < kMaxCount; ++n) v1.PushBack(n * 100); Vector<int> v2(std::move(v1)); EXPECT_TRUE(v1.IsEmpty()); EXPECT_FALSE(v2.IsEmpty()); EXPECT_EQ(static_cast<size_t>(kMaxCount), v2.GetCount()); for (int n = 0; n < kMaxCount; ++n) { EXPECT_EQ(n * 100, v2[n]) << "Checking v[" << n << "]"; } } TEST(Vector, MoveAssign) { const int kMaxCount = 500; Vector<int> v1; for (int n = 0; n < kMaxCount; ++n) v1.PushBack(n * 100); Vector<int> v2; v2 = std::move(v1); EXPECT_TRUE(v1.IsEmpty()); EXPECT_FALSE(v2.IsEmpty()); EXPECT_EQ(static_cast<size_t>(kMaxCount), v2.GetCount()); for (int n = 0; n < kMaxCount; ++n) { EXPECT_EQ(n * 100, v2[n]) << "Checking v[" << n << "]"; } } TEST(Vector, At) { const int kMaxCount = 500; Vector<int> v; for (int n = 0; n < kMaxCount; ++n) v.PushBack(n * 100); for (int n = 0; n < kMaxCount; ++n) { EXPECT_EQ(n * 100, v[n]) << "Checking v[" << n << "]"; } } TEST(Vector, Find) { const int kMaxCount = 500; Vector<int> v; for (int n = 0; n < kMaxCount; ++n) v.PushBack(n * 100); for (int n = 0; n < kMaxCount; ++n) { SearchResult r = v.Find(n * 100); EXPECT_TRUE(r.found) << "Looking for " << n * 100; EXPECT_EQ(n, r.pos) << "Looking for " << n * 100; } } TEST(Vector, ForRangeLoop) { const int kMaxCount = 500; Vector<int> v; for (int n = 0; n < kMaxCount; ++n) v.PushBack(n * 100); int n = 0; for (const int& value : v) { EXPECT_EQ(n * 100, value) << "Checking v[" << n << "]"; n++; } } TEST(Vector, InsertAt) { const int kMaxCount = 500; for (size_t k = 0; k < kMaxCount; ++k) { Vector<int> v; for (int n = 0; n < kMaxCount; ++n) v.PushBack(n * 100); v.InsertAt(k, -1000); EXPECT_EQ(kMaxCount + 1, v.GetCount()); for (int n = 0; n < v.GetCount(); ++n) { int expected; if (n < k) expected = n * 100; else if (n == k) expected = -1000; else expected = (n - 1) * 100; EXPECT_EQ(expected, v[n]) << "Checking v[" << n << "]"; } } } TEST(Vector, RemoveAt) { const int kMaxCount = 500; for (size_t k = 0; k < kMaxCount; ++k) { Vector<int> v; for (int n = 0; n < kMaxCount; ++n) v.PushBack(n * 100); v.RemoveAt(k); EXPECT_EQ(kMaxCount - 1, v.GetCount()); for (int n = 0; n < kMaxCount - 1; ++n) { int expected = (n < k) ? (n * 100) : ((n + 1) * 100); EXPECT_EQ(expected, v[n]) << "Checking v[" << n << "]"; } } } TEST(Vector, PopFirst) { const int kMaxCount = 500; Vector<int> v; for (int n = 0; n < kMaxCount; ++n) v.PushBack(n * 100); for (int n = 0; n < kMaxCount; ++n) { int first = v.PopFirst(); EXPECT_EQ(n * 100, first) << "Checking " << n << "-th PopFirst()"; EXPECT_EQ(kMaxCount - 1 - n, v.GetCount()) << "Checking " << n << "-th PopFirst()"; } EXPECT_EQ(0u, v.GetCount()); EXPECT_TRUE(v.IsEmpty()); } } // namespace crazy
21.198653
73
0.580845
zealoussnow
5eb6a20b0b73279855218d0c2d00eb1ca6c594d3
14,127
hpp
C++
src/hotspot/share/gc/parallel/psPromotionManager.inline.hpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2020-12-26T04:52:15.000Z
2020-12-26T04:52:15.000Z
src/hotspot/share/gc/parallel/psPromotionManager.inline.hpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2020-12-26T04:57:19.000Z
2020-12-26T04:57:19.000Z
src/hotspot/share/gc/parallel/psPromotionManager.inline.hpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2021-12-06T01:13:18.000Z
2021-12-06T01:13:18.000Z
/* * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_GC_PARALLEL_PSPROMOTIONMANAGER_INLINE_HPP #define SHARE_GC_PARALLEL_PSPROMOTIONMANAGER_INLINE_HPP #include "gc/parallel/psPromotionManager.hpp" #include "gc/parallel/parallelScavengeHeap.hpp" #include "gc/parallel/parMarkBitMap.inline.hpp" #include "gc/parallel/psOldGen.hpp" #include "gc/parallel/psPromotionLAB.inline.hpp" #include "gc/parallel/psScavenge.inline.hpp" #include "gc/shared/taskqueue.inline.hpp" #include "gc/shared/tlab_globals.hpp" #include "logging/log.hpp" #include "memory/iterator.inline.hpp" #include "oops/access.inline.hpp" #include "oops/oop.inline.hpp" #include "runtime/orderAccess.hpp" #include "runtime/prefetch.inline.hpp" inline PSPromotionManager* PSPromotionManager::manager_array(uint index) { assert(_manager_array != NULL, "access of NULL manager_array"); assert(index <= ParallelGCThreads, "out of range manager_array access"); return &_manager_array[index]; } inline void PSPromotionManager::push_depth(ScannerTask task) { claimed_stack_depth()->push(task); } template <class T> inline void PSPromotionManager::claim_or_forward_depth(T* p) { assert(should_scavenge(p, true), "revisiting object?"); assert(ParallelScavengeHeap::heap()->is_in(p), "pointer outside heap"); oop obj = RawAccess<IS_NOT_NULL>::oop_load(p); Prefetch::write(obj->mark_addr(), 0); push_depth(ScannerTask(p)); } inline void PSPromotionManager::promotion_trace_event(oop new_obj, oop old_obj, size_t obj_size, uint age, bool tenured, const PSPromotionLAB* lab) { // Skip if memory allocation failed if (new_obj != NULL) { const ParallelScavengeTracer* gc_tracer = PSScavenge::gc_tracer(); if (lab != NULL) { // Promotion of object through newly allocated PLAB if (gc_tracer->should_report_promotion_in_new_plab_event()) { size_t obj_bytes = obj_size * HeapWordSize; size_t lab_size = lab->capacity(); gc_tracer->report_promotion_in_new_plab_event(old_obj->klass(), obj_bytes, age, tenured, lab_size); } } else { // Promotion of object directly to heap if (gc_tracer->should_report_promotion_outside_plab_event()) { size_t obj_bytes = obj_size * HeapWordSize; gc_tracer->report_promotion_outside_plab_event(old_obj->klass(), obj_bytes, age, tenured); } } } } class PSPushContentsClosure: public BasicOopIterateClosure { PSPromotionManager* _pm; public: PSPushContentsClosure(PSPromotionManager* pm) : BasicOopIterateClosure(PSScavenge::reference_processor()), _pm(pm) {} template <typename T> void do_oop_nv(T* p) { if (PSScavenge::should_scavenge(p)) { _pm->claim_or_forward_depth(p); } } virtual void do_oop(oop* p) { do_oop_nv(p); } virtual void do_oop(narrowOop* p) { do_oop_nv(p); } }; // // This closure specialization will override the one that is defined in // instanceRefKlass.inline.cpp. It swaps the order of oop_oop_iterate and // oop_oop_iterate_ref_processing. Unfortunately G1 and Parallel behaves // significantly better (especially in the Derby benchmark) using opposite // order of these function calls. // template <> inline void InstanceRefKlass::oop_oop_iterate_reverse<oop, PSPushContentsClosure>(oop obj, PSPushContentsClosure* closure) { oop_oop_iterate_ref_processing<oop>(obj, closure); InstanceKlass::oop_oop_iterate_reverse<oop>(obj, closure); } template <> inline void InstanceRefKlass::oop_oop_iterate_reverse<narrowOop, PSPushContentsClosure>(oop obj, PSPushContentsClosure* closure) { oop_oop_iterate_ref_processing<narrowOop>(obj, closure); InstanceKlass::oop_oop_iterate_reverse<narrowOop>(obj, closure); } inline void PSPromotionManager::push_contents(oop obj) { if (!obj->klass()->is_typeArray_klass()) { PSPushContentsClosure pcc(this); obj->oop_iterate_backwards(&pcc); } } template<bool promote_immediately> inline oop PSPromotionManager::copy_to_survivor_space(oop o) { assert(should_scavenge(&o), "Sanity"); // NOTE! We must be very careful with any methods that access the mark // in o. There may be multiple threads racing on it, and it may be forwarded // at any time. markWord m = o->mark(); if (!m.is_marked()) { return copy_unmarked_to_survivor_space<promote_immediately>(o, m); } else { // Ensure any loads from the forwardee follow all changes that precede // the release-cmpxchg that performed the forwarding, possibly in some // other thread. OrderAccess::acquire(); // Return the already installed forwardee. return cast_to_oop(m.decode_pointer()); } } // // This method is pretty bulky. It would be nice to split it up // into smaller submethods, but we need to be careful not to hurt // performance. // template<bool promote_immediately> inline oop PSPromotionManager::copy_unmarked_to_survivor_space(oop o, markWord test_mark) { assert(should_scavenge(&o), "Sanity"); oop new_obj = NULL; bool new_obj_is_tenured = false; size_t new_obj_size = o->size(); // Find the objects age, MT safe. uint age = (test_mark.has_displaced_mark_helper() /* o->has_displaced_mark() */) ? test_mark.displaced_mark_helper().age() : test_mark.age(); if (!promote_immediately) { // Try allocating obj in to-space (unless too old) if (age < PSScavenge::tenuring_threshold()) { new_obj = cast_to_oop(_young_lab.allocate(new_obj_size)); if (new_obj == NULL && !_young_gen_is_full) { // Do we allocate directly, or flush and refill? if (new_obj_size > (YoungPLABSize / 2)) { // Allocate this object directly new_obj = cast_to_oop(young_space()->cas_allocate(new_obj_size)); promotion_trace_event(new_obj, o, new_obj_size, age, false, NULL); } else { // Flush and fill _young_lab.flush(); HeapWord* lab_base = young_space()->cas_allocate(YoungPLABSize); if (lab_base != NULL) { _young_lab.initialize(MemRegion(lab_base, YoungPLABSize)); // Try the young lab allocation again. new_obj = cast_to_oop(_young_lab.allocate(new_obj_size)); promotion_trace_event(new_obj, o, new_obj_size, age, false, &_young_lab); } else { _young_gen_is_full = true; } } } } } // Otherwise try allocating obj tenured if (new_obj == NULL) { #ifndef PRODUCT if (ParallelScavengeHeap::heap()->promotion_should_fail()) { return oop_promotion_failed(o, test_mark); } #endif // #ifndef PRODUCT new_obj = cast_to_oop(_old_lab.allocate(new_obj_size)); new_obj_is_tenured = true; if (new_obj == NULL) { if (!_old_gen_is_full) { // Do we allocate directly, or flush and refill? if (new_obj_size > (OldPLABSize / 2)) { // Allocate this object directly new_obj = cast_to_oop(old_gen()->allocate(new_obj_size)); promotion_trace_event(new_obj, o, new_obj_size, age, true, NULL); } else { // Flush and fill _old_lab.flush(); HeapWord* lab_base = old_gen()->allocate(OldPLABSize); if(lab_base != NULL) { #ifdef ASSERT // Delay the initialization of the promotion lab (plab). // This exposes uninitialized plabs to card table processing. if (GCWorkerDelayMillis > 0) { os::naked_sleep(GCWorkerDelayMillis); } #endif _old_lab.initialize(MemRegion(lab_base, OldPLABSize)); // Try the old lab allocation again. new_obj = cast_to_oop(_old_lab.allocate(new_obj_size)); promotion_trace_event(new_obj, o, new_obj_size, age, true, &_old_lab); } } } // This is the promotion failed test, and code handling. // The code belongs here for two reasons. It is slightly // different than the code below, and cannot share the // CAS testing code. Keeping the code here also minimizes // the impact on the common case fast path code. if (new_obj == NULL) { _old_gen_is_full = true; return oop_promotion_failed(o, test_mark); } } } assert(new_obj != NULL, "allocation should have succeeded"); // Copy obj Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(o), cast_from_oop<HeapWord*>(new_obj), new_obj_size); // Now we have to CAS in the header. // Make copy visible to threads reading the forwardee. oop forwardee = o->forward_to_atomic(new_obj, test_mark, memory_order_release); if (forwardee == NULL) { // forwardee is NULL when forwarding is successful // We won any races, we "own" this object. assert(new_obj == o->forwardee(), "Sanity"); // Increment age if obj still in new generation. Now that // we're dealing with a markWord that cannot change, it is // okay to use the non mt safe oop methods. if (!new_obj_is_tenured) { new_obj->incr_age(); assert(young_space()->contains(new_obj), "Attempt to push non-promoted obj"); } log_develop_trace(gc, scavenge)("{%s %s " PTR_FORMAT " -> " PTR_FORMAT " (%d)}", new_obj_is_tenured ? "copying" : "tenuring", new_obj->klass()->internal_name(), p2i((void *)o), p2i((void *)new_obj), new_obj->size()); // Do the size comparison first with new_obj_size, which we // already have. Hopefully, only a few objects are larger than // _min_array_size_for_chunking, and most of them will be arrays. // So, the is->objArray() test would be very infrequent. if (new_obj_size > _min_array_size_for_chunking && new_obj->is_objArray() && PSChunkLargeArrays) { // we'll chunk it push_depth(ScannerTask(PartialArrayScanTask(o))); TASKQUEUE_STATS_ONLY(++_arrays_chunked; ++_array_chunk_pushes); } else { // we'll just push its contents push_contents(new_obj); } return new_obj; } else { // We lost, someone else "owns" this object. // Ensure loads from the forwardee follow all changes that preceeded the // release-cmpxchg that performed the forwarding in another thread. OrderAccess::acquire(); assert(o->is_forwarded(), "Object must be forwarded if the cas failed."); assert(o->forwardee() == forwardee, "invariant"); // Try to deallocate the space. If it was directly allocated we cannot // deallocate it, so we have to test. If the deallocation fails, // overwrite with a filler object. if (new_obj_is_tenured) { if (!_old_lab.unallocate_object(cast_from_oop<HeapWord*>(new_obj), new_obj_size)) { CollectedHeap::fill_with_object(cast_from_oop<HeapWord*>(new_obj), new_obj_size); } } else if (!_young_lab.unallocate_object(cast_from_oop<HeapWord*>(new_obj), new_obj_size)) { CollectedHeap::fill_with_object(cast_from_oop<HeapWord*>(new_obj), new_obj_size); } return forwardee; } } // Attempt to "claim" oop at p via CAS, push the new obj if successful // This version tests the oop* to make sure it is within the heap before // attempting marking. template <bool promote_immediately, class T> inline void PSPromotionManager::copy_and_push_safe_barrier(T* p) { assert(should_scavenge(p, true), "revisiting object?"); oop o = RawAccess<IS_NOT_NULL>::oop_load(p); oop new_obj = copy_to_survivor_space<promote_immediately>(o); RawAccess<IS_NOT_NULL>::oop_store(p, new_obj); // We cannot mark without test, as some code passes us pointers // that are outside the heap. These pointers are either from roots // or from metadata. if ((!PSScavenge::is_obj_in_young((HeapWord*)p)) && ParallelScavengeHeap::heap()->is_in_reserved(p)) { if (PSScavenge::is_obj_in_young(new_obj)) { PSScavenge::card_table()->inline_write_ref_field_gc(p, new_obj); } } } inline void PSPromotionManager::process_popped_location_depth(ScannerTask task) { if (task.is_partial_array_task()) { assert(PSChunkLargeArrays, "invariant"); process_array_chunk(task.to_partial_array_task()); } else { if (task.is_narrow_oop_ptr()) { assert(UseCompressedOops, "Error"); copy_and_push_safe_barrier</*promote_immediately=*/false>(task.to_narrow_oop_ptr()); } else { copy_and_push_safe_barrier</*promote_immediately=*/false>(task.to_oop_ptr()); } } } inline bool PSPromotionManager::steal_depth(int queue_num, ScannerTask& t) { return stack_array_depth()->steal(queue_num, t); } #if TASKQUEUE_STATS void PSPromotionManager::record_steal(ScannerTask task) { if (task.is_partial_array_task()) { ++_array_chunk_steals; } } #endif // TASKQUEUE_STATS #endif // SHARE_GC_PARALLEL_PSPROMOTIONMANAGER_INLINE_HPP
39.132964
130
0.683231
1690296356
5eb6cc9ecbe82e80d5d57e365e50d79f65fe8661
2,054
cpp
C++
src/game/snake_game.cpp
Hippo/Snake
9390c34e86685bf905bad85d09819f0df8b2d7e0
[ "MIT" ]
null
null
null
src/game/snake_game.cpp
Hippo/Snake
9390c34e86685bf905bad85d09819f0df8b2d7e0
[ "MIT" ]
null
null
null
src/game/snake_game.cpp
Hippo/Snake
9390c34e86685bf905bad85d09819f0df8b2d7e0
[ "MIT" ]
null
null
null
#include "game/snake_game.hpp" #include <chrono> #include <queue> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> static std::queue<int> s_KeyQueue; #define MILLIS() std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count() Game::Game() : m_Window(800, 600, "Snake"), m_Shader("assets/shader/shader.vert", "assets/shader/shader.frag") { } void Game::run() { float width = static_cast<float>(m_Window.width()) / 10.0f; float height = static_cast<float>(m_Window.height()) / 10.0f; glm::vec4 border = glm::vec4(width / -2.0f, height / -2.0f, width / 2.0f, height / 2.0f); m_Snake.setBorder(border); m_Snake.spawnApple(); m_Shader.bind(); glm::mat4 projection = glm::ortho(width / -2.0f, width / 2.0f, height / -2.0f, height / 2.0f); GLuint projectionMatrix = m_Shader.getUniformLocation("projectionMatrix"); glUniformMatrix4fv(projectionMatrix, 1, GL_FALSE, glm::value_ptr(projection)); m_Window.setKeyPressCallback(onKeyPress); constexpr int delay = 1000 / 15; long last = MILLIS(); while (!m_Window.shouldClose()) { long now = MILLIS(); if (now - last >= delay) { update(); last = now; } render(); m_Window.swapBuffers(); Window::pollEvents(); } } void Game::update() { if (!s_KeyQueue.empty()) { int key = s_KeyQueue.front(); s_KeyQueue.pop(); m_Snake.handleKeyPress(key); } m_Snake.update(); } void Game::render() const { glClear(GL_COLOR_BUFFER_BIT); m_Snake.render(m_Shader); } void Game::onKeyPress(GLFWwindow*, int key, int, int action, int) { if (action == GLFW_PRESS) { switch (key) { //NOLINT case GLFW_KEY_UP: case GLFW_KEY_DOWN: case GLFW_KEY_LEFT: case GLFW_KEY_RIGHT: s_KeyQueue.push(key); break; } } }
26
140
0.614898
Hippo
5eb8a6fac8cb84f19d7dad312cdefdba71d4291a
1,825
cpp
C++
fboss/agent/SflowShimUtils.cpp
dgrnbrg-meta/fboss
cde5aa021fbb28e08cc912a7c227e93ed3faefee
[ "BSD-3-Clause" ]
1
2022-02-10T10:48:41.000Z
2022-02-10T10:48:41.000Z
fboss/agent/SflowShimUtils.cpp
dgrnbrg-meta/fboss
cde5aa021fbb28e08cc912a7c227e93ed3faefee
[ "BSD-3-Clause" ]
null
null
null
fboss/agent/SflowShimUtils.cpp
dgrnbrg-meta/fboss
cde5aa021fbb28e08cc912a7c227e93ed3faefee
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2004-present Facebook. All Rights Reserved. #include "fboss/agent/SflowShimUtils.h" namespace facebook::fboss::utility { SflowShimHeaderInfo parseSflowShim(folly::io::Cursor& cursor) { SflowShimHeaderInfo shim{}; shim.asic = SflowShimAsic::SFLOW_SHIM_ASIC_UNKNOWN; uint8_t srcPort = cursor.readBE<uint8_t>(); uint8_t srcModId = cursor.readBE<uint8_t>(); uint8_t dstPort = cursor.readBE<uint8_t>(); uint8_t dstModId = cursor.readBE<uint8_t>(); /* * In BRCM TH4 ASIC we have a 32 bit version field at the start and * rest of the fields is same as that of TH3. * * And we also confirmed from BRCM that unless the sampled packet is * ingressing and egressing from the CPU port, * All four fields (srcPort, srcModId, dstPort, dstModid) won't be 0. * * And we also verified that version field in TH4 sample packet will be 0. * * So, if the below calculated potentialVersionField is 0, we can safely * assume that the packet is from TH4 ASIC */ uint32_t potentialVersionField = srcPort << 24 | srcModId << 16 | dstPort << 8 | dstModId; if (potentialVersionField == 0) { // This is a coming from TH4 ASIC. shim.asic = SflowShimAsic::SFLOW_SHIM_ASIC_TH4; srcPort = cursor.readBE<uint8_t>(); // Src Module ID not needed cursor.readBE<uint8_t>(); dstPort = cursor.readBE<uint8_t>(); // Src Module ID not needed cursor.readBE<uint8_t>(); } else { shim.asic = SflowShimAsic::SFLOW_SHIM_ASIC_TH3; } // don't need sflow flags + reserved bits cursor.readBE<uint32_t>(); // For shim header, we store source/dest ports in the interface fields. // The ports will later be translated into interface names. shim.srcPort = srcPort; shim.dstPort = dstPort; return shim; } } // namespace facebook::fboss::utility
32.589286
76
0.70137
dgrnbrg-meta
5eba72f10a96b5069dbb5d037b90b77ab08ad604
4,015
cpp
C++
cui_raw/cui_rawImpl/Text/Text.cpp
alecmus/cui
bbfc1cbeeac43b717b05094d69adf8a57469d125
[ "MIT" ]
7
2020-03-17T10:47:39.000Z
2021-03-19T04:49:03.000Z
cui_raw/cui_rawImpl/Text/Text.cpp
alecmus/cui
bbfc1cbeeac43b717b05094d69adf8a57469d125
[ "MIT" ]
1
2021-05-21T15:17:31.000Z
2021-05-24T09:34:37.000Z
cui_raw/cui_rawImpl/Text/Text.cpp
alecmus/cui
bbfc1cbeeac43b717b05094d69adf8a57469d125
[ "MIT" ]
1
2020-03-20T13:22:38.000Z
2020-03-20T13:22:38.000Z
// // Text.cpp - text control implementation // // cui framework, part of the liblec library // Copyright (c) 2016 Alec Musasa (alecmus at live dot com) // // Released under the MIT license. For full details see the // file LICENSE.txt // #include "../cui_rawImpl.h" static bool design = false; LRESULT CALLBACK cui_rawImpl::TextControlProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { LONG_PTR ptr = GetWindowLongPtr(hWnd, GWLP_USERDATA); cui_rawImpl::TextControl* pThis = reinterpret_cast<cui_rawImpl::TextControl*>(ptr); switch (msg) { case WM_PAINT: { PAINTSTRUCT ps; HDC dc = BeginPaint(hWnd, &ps); RECT rc; GetClientRect(hWnd, &rc); int cx = rc.right - rc.left; int cy = rc.bottom - rc.top; // use double buffering to avoid flicker HDC hdc = CreateCompatibleDC(dc); if (!pThis->hbm_buffer) pThis->hbm_buffer = CreateCompatibleBitmap(dc, cx, cy); HBITMAP hbmOld = SelectBitmap(hdc, pThis->hbm_buffer); COLORREF clr_text = pThis->clrText; INT style = Gdiplus::FontStyle::FontStyleRegular; if (pThis->bHot && !pThis->bStatic) { clr_text = pThis->clrTextHot; style = Gdiplus::FontStyle::FontStyleUnderline; } // create graphics object Gdiplus::Graphics graphics(hdc); // fill background Gdiplus::Color color; color.SetFromCOLORREF(pThis->clrBackground); graphics.Clear(color); Gdiplus::RectF layoutRect = convert_rect(rc); Gdiplus::FontFamily ffm(pThis->sFontName.c_str()); Gdiplus::Font* p_font = new Gdiplus::Font(&ffm, static_cast<Gdiplus::REAL>(pThis->iFontSize), style); if (p_font->GetLastStatus() != Gdiplus::Status::Ok) { delete p_font; p_font = nullptr; p_font = new Gdiplus::Font(pThis->sFontName.c_str(), static_cast<Gdiplus::REAL>(pThis->iFontSize), style, Gdiplus::UnitPoint, &pThis->d->m_font_collection); } color.SetFromCOLORREF(clr_text); Gdiplus::SolidBrush text_brush(color); Gdiplus::StringFormat format; format.SetAlignment(Gdiplus::StringAlignment::StringAlignmentNear); format.SetTrimming(Gdiplus::StringTrimming::StringTrimmingEllipsisCharacter); if (!pThis->bMultiLine) format.SetFormatFlags(Gdiplus::StringFormatFlags::StringFormatFlagsNoWrap); // measure text rectangle Gdiplus::RectF text_rect; graphics.MeasureString(pThis->sText.c_str(), -1, p_font, layoutRect, &text_rect); if (!pThis->bMultiLine) { if (text_rect.Width < layoutRect.Width) text_rect.Width = min(text_rect.Width * 1.01f, layoutRect.Width); } // align the text rectangle to the layout rectangle align_text(text_rect, layoutRect, pThis->align); if (design) { color.SetFromCOLORREF(RGB(240, 240, 240)); Gdiplus::SolidBrush brush(color); graphics.FillRectangle(&brush, layoutRect); color.SetFromCOLORREF(RGB(230, 230, 230)); brush.SetColor(color); graphics.FillRectangle(&brush, text_rect); } // draw text graphics.DrawString(pThis->sText.c_str(), -1, p_font, text_rect, &format, &text_brush); delete p_font; p_font = nullptr; // capture the text rectangle pThis->rcText = convert_rect(text_rect); BitBlt(dc, 0, 0, cx, cy, hdc, 0, 0, SRCCOPY); EndPaint(hWnd, &ps); SelectBitmap(hdc, hbmOld); DeleteDC(hdc); } break; case WM_ENABLE: { bool bEnabled = wParam == TRUE; if (bEnabled) { // control has been enabled InvalidateRect(hWnd, NULL, TRUE); } else { // control has been disabled InvalidateRect(hWnd, NULL, TRUE); } } break; case WM_DESTROY: { // delete buffer, we're done if (pThis->hbm_buffer) { DeleteBitmap(pThis->hbm_buffer); pThis->hbm_buffer = NULL; } } break; case WM_SIZE: { // delete buffer, we need it recreated if (pThis->hbm_buffer) { DeleteBitmap(pThis->hbm_buffer); pThis->hbm_buffer = NULL; } InvalidateRect(hWnd, NULL, TRUE); } break; } // Any messages we don't process must be passed onto the original window function return CallWindowProc((WNDPROC)pThis->PrevProc, hWnd, msg, wParam, lParam); } // TextControlProc
23.757396
107
0.700872
alecmus
5ebb412f4a888654ce1059403fcbf0e730ed7023
1,052
cpp
C++
src/game/server/infclass/entities/laser-teleport.cpp
srdante/teeworlds-infclassR
8b05eae1f23297617da47403cf04bceafdc198ac
[ "Zlib" ]
6
2021-02-24T22:15:23.000Z
2022-03-23T18:41:58.000Z
src/game/server/infclass/entities/laser-teleport.cpp
srdante/teeworlds-infclassR
8b05eae1f23297617da47403cf04bceafdc198ac
[ "Zlib" ]
75
2021-02-02T17:48:50.000Z
2022-03-23T18:54:25.000Z
src/game/server/infclass/entities/laser-teleport.cpp
srdante/teeworlds-infclassR
8b05eae1f23297617da47403cf04bceafdc198ac
[ "Zlib" ]
8
2021-03-13T15:06:27.000Z
2022-03-23T12:09:07.000Z
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <game/server/gamecontext.h> #include "laser-teleport.h" CLaserTeleport::CLaserTeleport(CGameContext *pGameContext, vec2 StartPos, vec2 EndPos) : CInfCEntity(pGameContext, CGameWorld::ENTTYPE_LASER_TELEPORT) { m_StartPos = StartPos; m_EndPos = EndPos; m_LaserFired = false; GameWorld()->InsertEntity(this); } void CLaserTeleport::Tick() { if (m_LaserFired) GameServer()->m_World.DestroyEntity(this); } void CLaserTeleport::Snap(int SnappingClient) { m_LaserFired = true; if (Server()->GetClientAntiPing(SnappingClient)) return; CNetObj_Laser *pObj = static_cast<CNetObj_Laser *>(Server()->SnapNewItem(NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); if(!pObj) return; pObj->m_X = (int)m_EndPos.x; pObj->m_Y = (int)m_EndPos.y; pObj->m_FromX = (int)m_StartPos.x; pObj->m_FromY = (int)m_StartPos.y; pObj->m_StartTick = Server()->Tick(); }
27.684211
122
0.737643
srdante
5ebf84420dd74f26c0ae3a9a2ebc6a9d46fe8777
595
cpp
C++
codeforce6/1029B. Creating the Contest.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce6/1029B. Creating the Contest.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce6/1029B. Creating the Contest.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
/* Idea: - Using cumulative sum we can determine the maximum number of consequtive elements that form the answer. */ #include <bits/stdc++.h> using namespace std; int const N = 2e5 + 1; int n, a[N]; bool ck[N]; int main() { scanf("%d", &n); for(int i = 0; i < n; ++i) scanf("%d", a + i); for(int i = 1; i < n; ++i) ck[i] = a[i] <= 2 * a[i - 1]; int res = 0; for(int i = 0; i < n; ++i) { int j = i; while(ck[j] == 1) ++j; if(j != i) { res = max(res, j - i); i = j; --i; } } printf("%d\n", res + 1); return 0; }
14.875
58
0.457143
khaled-farouk
5ec2f30b9e28db0a7b27c22722c4511d6d99eb34
2,842
cxx
C++
smtk/session/polygon/vtk/vtkPolygonArcProvider.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
40
2015-02-21T19:55:54.000Z
2022-01-06T13:13:05.000Z
smtk/session/polygon/vtk/vtkPolygonArcProvider.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
127
2015-01-15T20:55:45.000Z
2021-08-19T17:34:15.000Z
smtk/session/polygon/vtk/vtkPolygonArcProvider.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
27
2015-03-04T14:17:51.000Z
2021-12-23T01:05:42.000Z
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "smtk/session/polygon/vtk/vtkPolygonArcProvider.h" #include "vtkCellArray.h" #include "vtkCompositeDataIterator.h" #include "vtkDataObjectTreeIterator.h" #include "vtkIdList.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMultiBlockDataSet.h" #include "vtkNew.h" #include "vtkObjectFactory.h" #include "vtkPoints.h" #include "vtkPolyData.h" vtkStandardNewMacro(vtkPolygonArcProvider); //vtkCxxSetObjectMacro(vtkPolygonArcProvider,CachedOutput,vtkPolyData); vtkPolygonArcProvider::vtkPolygonArcProvider() { this->SetNumberOfInputPorts(1); this->SetNumberOfOutputPorts(1); } vtkPolygonArcProvider::~vtkPolygonArcProvider() = default; int vtkPolygonArcProvider::FillInputPortInformation(int /*port*/, vtkInformation* info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkMultiBlockDataSet"); return 1; } int vtkPolygonArcProvider::RequestData( vtkInformation* /*request*/, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkMultiBlockDataSet* input = vtkMultiBlockDataSet::GetData(inputVector[0], 0); vtkPolyData* output = vtkPolyData::GetData(outputVector, 0); if (!input) { vtkErrorMacro("Input not specified!"); return 0; } if (this->BlockIndex == -1) { vtkErrorMacro("Must specify block index to extract!"); return 0; } vtkCompositeDataIterator* iter = input->NewIterator(); iter->SetSkipEmptyNodes(false); vtkDataObjectTreeIterator* treeIter = vtkDataObjectTreeIterator::SafeDownCast(iter); if (treeIter) { treeIter->VisitOnlyLeavesOff(); } // Copy selected block over to the output. vtkNew<vtkPolyData> linePoly; linePoly->Initialize(); int index = 0; for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem(), index++) { if (index == this->BlockIndex) { vtkPolyData* block = vtkPolyData::SafeDownCast(iter->GetCurrentDataObject()); if (block) { linePoly->ShallowCopy(block); } break; } } iter->Delete(); output->Initialize(); //see if both end nodes are the same // by default we always use the whole arc output->ShallowCopy(linePoly.GetPointer()); return 1; } void vtkPolygonArcProvider::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "BlockIndex: " << this->BlockIndex << endl; }
28.42
90
0.689655
jcfr
5ec73d33048f446fe2e21da885d82b95f5720d80
10,076
cpp
C++
BinarySearchTrees-Improved/SearchTree.cpp
jogdandsnehal14/BinarySearchTrees-Improved
0a1df1bfefdc55241cbc2e22d7e9674ba0d651fc
[ "MIT" ]
null
null
null
BinarySearchTrees-Improved/SearchTree.cpp
jogdandsnehal14/BinarySearchTrees-Improved
0a1df1bfefdc55241cbc2e22d7e9674ba0d651fc
[ "MIT" ]
null
null
null
BinarySearchTrees-Improved/SearchTree.cpp
jogdandsnehal14/BinarySearchTrees-Improved
0a1df1bfefdc55241cbc2e22d7e9674ba0d651fc
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- // File: SearchTree.cpp // Author: Snehal Jogdand // Date: 01/14/2020 // Program 1: Improved binary search trees // // DESCRIPTION: // SearchTree: // The class file for SearchTree class // Provides the set of variables and functions to process // a Binary Search Tree //--------------------------------------------------------------------------- #include "SearchTree.h" using namespace std; /** The binary search tree default constructor */ SearchTree::SearchTree() : root(nullptr) { } /** The copy constructor for binary search tree @pre None. @param other The binary search tree to copy from */ SearchTree::SearchTree(const SearchTree& other) { root = copy(other.root); } /** The copy helper for binary search tree @pre None. @param other The binary search tree to copy from */ Node* SearchTree::copy(const Node* other) { if (other == nullptr) return nullptr; Node* node = createNode(other->item); node->left = copy(other->left); node->right = copy(other->right); node->count = other->count; return node; } /** Checks if the two binary search tree are equal @pre None. @param node1 The root of binary search tree 1 @param node2 The root of binary search tree 2 @returns true if the two binary search tree are equal, false otherwise */ bool SearchTree::isEqual(const Node* node1, const Node* node2) { if (node1 == nullptr && node2 == nullptr) return true; else if (node1 != nullptr && node2 == nullptr) return false; else if (node1 == nullptr && node2 != nullptr) return false; else if (*node1->item == *node2->item && node1->count == node2->count) return isEqual(node1->left, node2->left) && isEqual(node1->right, node2->right); return false; } /** Creates a new node with the given comparable item @pre None. @param item The comparable item @returns The newly created Node object */ Node* SearchTree::createNode(Comparable* item) { Node* node = new Node; node->item = item; node->count = 1; node->left = nullptr; node->right = nullptr; return node; } /** Iteratively inserts a Comparable into the tree or increments the count if it is already in the tree. This method returns false if the Comparable is found (and, thus, not inserted). @pre None. @param item The comparable item @returns True if the new item is inserted */ bool SearchTree::insert(Comparable* item) { // empty tree - set the root node if (root == nullptr) { root = createNode(item); return true; } Node* current = root; Node* parent = nullptr; // find the position where the node can be inserted while (current != nullptr) { parent = current; if (*(current->item) > * item) current = current->left; else if (*(current->item) < *item) current = current->right; else { // duplicate node found, just increment the count and return current->count++; return false; } } Node* node = createNode(item); if (*(parent->item) > * item) parent->left = node; else if (*(parent->item) < *item) parent->right = node; return true; } /** Removes one occurrence of a Comparable from the tree. If it is the last occurrence, remove the node. Return false if the Comparable is not found. @pre None. @param item The comparable item @returns True if item is removed, false otherwise */ bool SearchTree::remove(const Comparable& item) { return deleteNode(root, item); } /** Removes and deallocates all of the data from the tree. @pre None. */ void SearchTree::makeEmpty() { clear(root); delete root; root = nullptr; } /** Finds a Comparable in the tree using a key stored in the parameter. @pre None. @param item The comparable item @returns The comparable item found, nullptr if not found */ const Comparable* SearchTree::retrieve(const Comparable& item) const { // get the node in the tree Node* node = search(root, item); // node found, return the corresponding item if (node != nullptr) return node->item; // no node found, return null return nullptr; } /** Returns the height of the node storing the Comparable in the tree. A leaf has height 0. Return -1 if the Comparable is not found. @pre None. @param item The comparable item @returns The height of the tree */ int SearchTree::height(const Comparable& item) const { Node* node = search(root, item); // item not found, return -1 if (node == nullptr) return -1; return height(node); } /** Returns the height of the node storing the Comparable in the tree. A leaf has height 0. Return -1 if the Comparable is not found. @pre None. @param node The root node @returns The height of the tree */ int SearchTree::height(const Node* node) const { if (node == nullptr) return 0; int leftHeight = height(node->left); int rightHeight = height(node->right); return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight); } /** Searches a Comparable in the tree using the comparable item stored in the parameter. @pre None. @param node The root node @param item The comparable item @returns The node with comparable item found, nullptr if not found */ Node* SearchTree::search(Node* node, const Comparable& item) const { if (node == nullptr) return nullptr; else if (*node->item == item) return node; else if (*(node->item) > item) return search(node->left, item); else return search(node->right, item); } /** Deletes a Node in the tree which has the the comparable item in the parameter. @pre None. @param node The root node @param item The comparable item @returns True if deletion succeeds, false otherwise */ bool SearchTree::deleteNode(Node*& root, const Comparable& item) { if (root == nullptr) return false; else if (*root->item == item) { if (root->count > 1) root->count--; else deleteRoot(root); return true; } else if (*root->item > item) return deleteNode(root->left, item); else return deleteNode(root->right, item); return false; } /** Deletes the root node in the tree @pre None. @param node The root node */ void SearchTree::deleteRoot(Node*& root) { delete root->item; // leaf node if (root->left == nullptr && root->right == nullptr) { delete root; root = nullptr; } // node with one child else if (root->left == nullptr || root->right == nullptr) { Node* tmp = root; root = root->left == nullptr ? root->right : root->left; delete tmp; } // node with both children else { // get max from left subtree Node* parent = root->right; Node* maxLeft = root->right; while (maxLeft->left != nullptr) { parent = maxLeft; maxLeft = maxLeft->left; } parent->left = maxLeft->right; // copy max values to the root node root->item = maxLeft->item; root->count = maxLeft->count; delete maxLeft; } } /** Overload assignment operator. @pre None. @param other The SearchTree object to copy values from @returns The SearchTree object */ SearchTree SearchTree::operator=(SearchTree const& other) { if (&other != this) { SearchTree temp(other); swap(temp.root, root); } return *this; } /** Overload equality check operator. @pre None. @param right The SearchTree object to compare against @returns True if the two tree are equal */ bool SearchTree::operator==(const SearchTree& right) { return isEqual(root, right.root); } /** Overload not equality check operator. @pre None. @param right The SearchTree object to compare against @returns True if the two tree are not equal */ bool SearchTree::operator!=(const SearchTree& right) { return !isEqual(root, right.root); } /** Overload << operator. @pre None. @param output The output stream to print the output @param searchTree The SearchTree object to output */ ostream& operator<<(ostream& output, SearchTree& searchTree) { searchTree.inorder(output, searchTree.root); return output; } /** Prints the inorder traversal of the search tree @pre None. @param output The output stream to print the output @param node The root node */ void SearchTree::inorder(ostream& output, Node* node) { if (node == nullptr) return; inorder(output, node->left); output << *node->item << "\t" << node->count << endl; inorder(output, node->right); } /** * Destroys all the nodes in the given BS Tree in a recursive manner */ void SearchTree::clear(Node* node) { Node* nodeToDeletePtr = node; if (node == nullptr) return; if (node->left == nullptr && node->right == nullptr) { // Return node to the system /* if (nodeToDeletePtr->item != nullptr) { delete nodeToDeletePtr->item; nodeToDeletePtr->item = nullptr; } */ delete nodeToDeletePtr; nodeToDeletePtr = nullptr; return; } clear(node->left); clear(node->right); nodeToDeletePtr->left = nullptr; nodeToDeletePtr->right = nullptr; } /** The Search Tree destructor */ SearchTree::~SearchTree() { clear(root); delete root; root = nullptr; }
26.585752
89
0.597261
jogdandsnehal14
5eca1173bcd8decc94a75037514d66d74e9ecacd
37,582
cpp
C++
src/algos/fmath.cpp
rdmenezes/fibernavigator2
bbb8bc8ff16790580d5b03fce7e1fad45fae1b91
[ "MIT" ]
null
null
null
src/algos/fmath.cpp
rdmenezes/fibernavigator2
bbb8bc8ff16790580d5b03fce7e1fad45fae1b91
[ "MIT" ]
null
null
null
src/algos/fmath.cpp
rdmenezes/fibernavigator2
bbb8bc8ff16790580d5b03fce7e1fad45fae1b91
[ "MIT" ]
null
null
null
/* * fmath.cpp * * Created on: Jul 17, 2012 * @author Ralph Schurade */ #include "fmath.h" #include "math.h" #include "../thirdparty/newmat10/newmatap.h" #include "../thirdparty/newmat10/newmatio.h" #include "../thirdparty/newmat10/newmatrm.h" #include "../thirdparty/newmat10/precisio.h" #include <QDebug> #include <qmath.h> #include <boost/math/special_functions/spherical_harmonic.hpp> #include <float.h> FMath::FMath() {} FMath::~FMath() {} ColumnVector FMath::vlog( ColumnVector v ) { // allocate memory of output object: ColumnVector tmp( v.Nrows() ); // for each element of the vector: for ( int i( 1 ); i <= v.Nrows(); ++i ) { if ( v( i ) <= 0.0 ) tmp( i ) = -1.0e+17; else tmp( i ) = log( v( i ) ); } return tmp; } double FMath::legendre_p( int k ) { double z = 1.0; double n = 1.0; for ( int i = 1; i <= k + 1; i += 2 ) z *= i; for ( int i = 2; i <= k - 2; i += 2 ) n *= i; if (( k / 2 ) % 2 == 0) { return -1.0 / ( 8 * M_PI ) * ( z / n ); } else { return 1.0 / ( 8 * M_PI ) * ( z / n ); } } double FMath::boostLegendre_p( int order, int arg1, double arg2 ) { return boost::math::legendre_p<double>( order, arg1, arg2 ); } Matrix FMath::sh_base( Matrix g, int maxOrder ) { //qDebug() << "start calculating sh base"; // allcoate result matrix unsigned long sh_dirs( ( maxOrder + 2 ) * ( maxOrder + 1 ) / 2 ); Matrix out( g.Nrows(), sh_dirs ); out = 0.0; // for each direction for ( int i = 0; i < g.Nrows(); ++i ) { // transform current direction to polar coordinates double theta( acos( g( i + 1, 3 ) ) ); double phi( atan2( g( i + 1, 2 ), g( i + 1, 1 ) ) ); // calculate spherical harmonic base for ( int order = 0, j = 0; order <= maxOrder; order += 2 ) { for ( int degree( -order ); degree <= order; ++degree, ++j ) { out( i + 1, j + 1 ) = sh_base_function( order, degree, theta, phi ); } } } //qDebug() << "finished calculating sh base"; return out; } double FMath::sh_base_function( int order, int degree, double theta, double phi ) { using namespace boost::math; #if 0 double P = legendre_p<double>( order, abs(degree), cos(theta) ); if ( degree > 0 ) { return P * cos( degree * phi ); } else if ( degree < 0 ) { return P * sin( -degree * phi ); } else { return P; } #else if ( degree > 0 ) { return spherical_harmonic_r( order, abs( degree ), theta, phi ); } else if ( degree < 0 ) { return spherical_harmonic_i( order, abs( degree ), theta, phi ); } else { return spherical_harmonic_r( order, 0, theta, phi ); } #endif } SymmetricMatrix FMath::moment_of_inertia( const ColumnVector& values, const QVector<ColumnVector>& points ) { SymmetricMatrix result( 3 ); result = 0.0; double sum( 0.0 ); for ( int i = 0; i < points.size(); ++i ) { double x( points[i]( 1 ) ); double y( points[i]( 2 ) ); double z( points[i]( 3 ) ); double val = fabs( values( i + 1 ) ); result( 1, 1 ) += x * x * val; result( 1, 2 ) += x * y * val; result( 1, 3 ) += x * z * val; result( 2, 2 ) += y * y * val; result( 2, 3 ) += y * z * val; result( 3, 3 ) += z * z * val; sum += val * val; } result = result / sum; return result; } double FMath::iprod( const ColumnVector& v1, const ColumnVector& v2 ) { double result( 0.0 ); if ( v1.Nrows() != v2.Nrows() ) { throw std::range_error( "Vectors in scalar product need same size!" ); } for ( int i = 1; i < v1.Nrows() + 1; ++i ) { result += v1( i ) * v2( i ); } return result; } ColumnVector FMath::cprod( const ColumnVector& v1, const ColumnVector& v2 ) { ColumnVector result( 3 ); if ( v1.Nrows() != 3 || v2.Nrows() != 3 ) throw std::range_error( "Vectors in cross product both need size 3!" ); result( 1 ) = v1( 2 ) * v2( 3 ) - v1( 3 ) * v2( 2 ); result( 2 ) = v1( 3 ) * v2( 1 ) - v1( 1 ) * v2( 3 ); result( 3 ) = v1( 1 ) * v2( 2 ) - v1( 2 ) * v2( 1 ); result = result / sqrt( FMath::iprod( result, result ) ); return result; } void FMath::evd3x3( ColumnVector tensor, QVector<ColumnVector>& vecs, ColumnVector& vals ) { double i1, i2, i3, v, s, phi, l1, l2, l3; double ev1_x, ev1_y, ev1_z, ev2_x, ev2_y, ev2_z, ev3_x, ev3_y, ev3_z, vec_norm; double xx = tensor( 1 ); double xy = tensor( 2 ); double xz = tensor( 3 ); double yy = tensor( 4 ); double yz = tensor( 5 ); double zz = tensor( 6 ); // three invariants of D (dt) // i1=l1+l2+l3 (trace) // i2=l1*l2+l1*l3+l2*l3 // i3=l1*l2*l3 (determinante) i1 = xx + yy + zz; i2 = xx * yy + xx * zz + yy * zz - ( pow2( xy ) + pow2( xz ) + pow2( yz ) ); i3 = xx * yy * zz + 2. * xy * xz * yz - ( zz * pow2( xy ) + yy * pow2( xz ) + xx * pow2( yz ) ); v = pow2( i1 / 3 ) - i2 / 3; s = pow3( i1 / 3 ) - i1 * i2 / 6 + i3 / 2; if ( ( v > 0 ) && ( pow2( s ) < pow3( v ) ) ) phi = acos( s / v * sqrt( 1. / v ) ) / 3; else phi = 0; // eigenvalues if ( phi != 0 ) { l1 = i1 / 3 + 2 * sqrt( v ) * cos( phi ); l2 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. + phi ); l3 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. - phi ); } else l1 = l2 = l3 = 0.0; // eigenvectors ev1_x = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * yz - ( zz - l1 ) * xy ); ev1_y = ( xz * yz - ( zz - l1 ) * xy ) * ( xz * xy - ( xx - l1 ) * yz ); ev1_z = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * xy - ( xx - l1 ) * yz ); ev2_x = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * yz - ( zz - l2 ) * xy ); ev2_y = ( xz * yz - ( zz - l2 ) * xy ) * ( xz * xy - ( xx - l2 ) * yz ); ev2_z = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * xy - ( xx - l2 ) * yz ); ev3_x = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * yz - ( zz - l3 ) * xy ); ev3_y = ( xz * yz - ( zz - l3 ) * xy ) * ( xz * xy - ( xx - l3 ) * yz ); ev3_z = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * xy - ( xx - l3 ) * yz ); vec_norm = sqrt( pow2( ev1_x ) + pow2( ev1_y ) + pow2( ev1_z ) ); if ( vec_norm > 0 ) { ev1_x = ev1_x / vec_norm; ev1_y = ev1_y / vec_norm; ev1_z = ev1_z / vec_norm; } else ev1_x = ev1_y = ev1_z = 0.0; vec_norm = sqrt( pow2( ev2_x ) + pow2( ev2_y ) + pow2( ev2_z ) ); if ( vec_norm > 0 ) { ev2_x = ev2_x / vec_norm; ev2_y = ev2_y / vec_norm; ev2_z = ev2_z / vec_norm; } else ev2_x = ev2_y = ev2_z = 0.0; vec_norm = sqrt( pow2( ev3_x ) + pow2( ev3_y ) + pow2( ev3_z ) ); if ( vec_norm > 0 ) { ev3_x = ev3_x / vec_norm; ev3_y = ev3_y / vec_norm; ev3_z = ev3_z / vec_norm; } else ev3_x = ev3_y = ev3_z = 0.0; ColumnVector ev1( 3 ); ColumnVector ev2( 3 ); ColumnVector ev3( 3 ); vals(1) = l1; vals(2) = l2; vals(3) = l3; ev1( 1 ) = ev1_x; ev1( 2 ) = ev1_y; ev1( 3 ) = ev1_z; ev2( 1 ) = ev2_x; ev2( 2 ) = ev2_y; ev2( 3 ) = ev2_z; ev3( 1 ) = ev3_x; ev3( 2 ) = ev3_y; ev3( 3 ) = ev1_z; vecs.clear(); vecs.push_back( ev3 ); vecs.push_back( ev2 ); vecs.push_back( ev1 ); } ///* *************************************************************************** ///* @file math.cpp ///* @fn Vector cart2sphere( ///* ///* const Vector& input ) ///* ///* @brief Transforms a cartesian-coordinate vector to spherical coordinates. ///* ///* For further information view: <br> ///* Wikipedia article on cartesian and spherical coordinates. ///* ///* @param Vector: a in cartesian-coordinates ///* ///* @return Vector: representation of a in spherical coordinates, ///* order: r, theta, phi. ///* *************************************************************************** ColumnVector FMath::cart2sphere( const ColumnVector& input ) { if ( input.Nrows() != 3 ) throw std::range_error("Can only transform 3D-vectors."); ColumnVector result( 3 ); result( 1 ) = sqrt( input( 1 ) * input( 1 ) + input( 2 ) * input( 2 ) + input( 3 ) * input( 3 ) ); result( 2 ) = acos( input( 3 ) / result( 1 ) ); result( 3 ) = atan2( input( 2 ), input( 1 ) ); return result; } ///* *************************************************************************** ///* @file math.cpp ///* @fn Vector sphere2cart( ///* ///* const Vector& input ) ///* ///* @brief Transforms a spherical-coordinate vector to cartesian-coordinates. ///* ///* For further information view: <br> ///* Wikipedia article on cartesian and spherical coordinates. <br> ///* ///* @param Vector: a in spherical-coordinates ///* ///* @return Vector: represantation of a in cartesian-coordinates, order: x,y,z. ///* *************************************************************************** ColumnVector FMath::sphere2cart( const ColumnVector& input ) { if ( input.Nrows() != 3 ) throw std::range_error( "Can only transform 3D-vectors." ); ColumnVector result( 3 ); result( 1 ) = input( 1 ) * sin( input( 2 ) ) * cos( input( 3 ) ); result( 2 ) = input( 1 ) * sin( input( 2 ) ) * sin( input( 3 ) ); result( 3 ) = input( 1 ) * cos( input( 2 ) ); return result; } ColumnVector FMath::SH_opt_max( const ColumnVector& startX, const ColumnVector& coeff ) { ColumnVector newX( startX ); ColumnVector oldX( 3 ); // set values for computation const double precision( 10.e-6 ); const double eps( 10.e-4 ); double delta( 1.0 ); int steps( 0 ); while ( delta > precision && steps < 100 ) { // Update old value ++steps; oldX = newX; double SH_old( sh_eval( oldX, coeff ) ); // define the delta steps ColumnVector dt( oldX ); ColumnVector dp( oldX ); dt( 2 ) += eps; dp( 3 ) += eps; // calculate Jacobian double Jt( ( FMath::sh_eval( dt, coeff ) - SH_old ) ); double Jp( ( FMath::sh_eval( dp, coeff ) - SH_old ) ); // do iteration newX( 2 ) = oldX( 2 ) + Jt; newX( 3 ) = oldX( 3 ) + Jp; delta = fabs( Jt ) + fabs( Jp ); //std::cout<<delta<<" "; } return newX; } ///* *************************************************************************** ///* @file math.cpp ///* @fn double sh_eval( ///* ///* const Vector& position, ///* const Vector& coeff, ///* const unsigned long max_order ) ///* ///* @brief Evaluates a spherical harmonic function defined by its coefficients ///* in direction of the position vector. ///* ///* important: this function works in place. <br> ///* ///* For further information view: <br> ///* Cormen, Leiversn, Rivest, and Stein: Introduction to Algorithms <br> ///* Wikipedia article on bubble sort. ///* ///* @param Vector: values the vector which determies the sorting ///* @param Vector: indices to be sorted going along ///* ///* @return TODO ///* *************************************************************************** double FMath::sh_eval( const ColumnVector& position, const ColumnVector& coeff ) { const int max_order( ( -3 + static_cast<int>( sqrt( 8 * coeff.Nrows() ) + 1 ) ) / 2 ); const double radius( position( 1 ) ); if ( radius == 0.0 ) { return 0.0; } // for easier readability const double theta( position( 2 ) ); const double phi( position( 3 ) ); double result( 0 ); for ( int order( 0 ), j( 1 ); order <= max_order; order += 2 ) { for ( int degree( -order ); degree <= order; degree++, ++j ) { result += coeff( j ) * FMath::sh_base_function( order, degree, theta, phi ); } } return result; } // calculate rotation matrix: http://en.wikipedia.org/wiki/Rotation_matrix Matrix FMath::RotationMatrix( const double angle, const ColumnVector& axis ) { double s( sin( angle ) ); double c( cos( angle ) ); double d( 1. - c ); Matrix R( 3, 3 ); R( 1, 1 ) = c + axis( 1 ) * axis( 1 ) * d; R( 1, 2 ) = axis( 1 ) * axis( 2 ) * d - axis( 3 ) * s; R( 1, 3 ) = axis( 1 ) * axis( 3 ) * d + axis( 2 ) * s; R( 2, 1 ) = axis( 1 ) * axis( 2 ) * d + axis( 3 ) * s; R( 2, 2 ) = c + axis( 1 ) * axis( 1 ) * d; R( 2, 3 ) = axis( 2 ) * axis( 3 ) * d - axis( 1 ) * s; R( 3, 1 ) = axis( 1 ) * axis( 3 ) * d - axis( 2 ) * s; R( 3, 2 ) = axis( 2 ) * axis( 3 ) * d + axis( 1 ) * s; R( 3, 3 ) = c + axis( 3 ) * axis( 3 ) * d; return R; } void FMath::debugColumnVector3( const ColumnVector& v, QString name ) { if ( v.Nrows() != 3 ) { qDebug() << name << "error not 3 elements in vector"; } qDebug() << name << v( 1 ) << v( 2 ) << v( 3 ); } Matrix FMath::pseudoInverse( const Matrix& A ) { /* Matrix U( A.Nrows(), A.Ncols() ); DiagonalMatrix D( A.Ncols() ); Matrix V( A.Ncols(), A.Ncols() ); SVD( A, D, U, V ); return ( V * ( D.t() * D ) * D.t() * U.t() ); */ return ( ( A.t() * A ).i() * A.t() ); } void FMath::fitTensors( QVector<ColumnVector>& data, QVector<float>& b0Images, QVector<QVector3D>& bvecs, QVector<float>& bvals, QVector<Matrix>& out ) { int N = bvecs.size(); Matrix B( N, 6 ); Matrix U( N, 6 ); Matrix V( 6, 6 ); Matrix BI( 6, N ); DiagonalMatrix D( 6 ); double mult_c; for ( int i = 0; i < N; ++i ) { mult_c = bvals[i] / (float) ( bvecs[i].x() * bvecs[i].x() + bvecs[i].y() * bvecs[i].y() + bvecs[i].z() * bvecs[i].z() ); B( i + 1, 1 ) = mult_c * bvecs[i].x() * bvecs[i].x(); B( i + 1, 2 ) = 2 * mult_c * bvecs[i].x() * bvecs[i].y(); B( i + 1, 3 ) = 2 * mult_c * bvecs[i].x() * bvecs[i].z(); B( i + 1, 4 ) = mult_c * bvecs[i].y() * bvecs[i].y(); B( i + 1, 5 ) = 2 * mult_c * bvecs[i].y() * bvecs[i].z(); B( i + 1, 6 ) = mult_c * bvecs[i].z() * bvecs[i].z(); } SVD( B, D, U, V ); for ( int j = 1; j <= 6; ++j ) { D( j ) = 1. / D( j ); } BI = V * D * U.t(); double s0 = 0.0; double si = 0.0; vector<double> log_s0_si_pixel( N ); out.clear(); out.reserve( data.size() ); Matrix blank( 3, 3 ); blank = 0.0; for ( int i = 0; i < data.size(); ++i ) { s0 = b0Images.at( i ); if ( s0 > 0 ) { // compute log(s0)-log(si) s0 = log( s0 ); for ( int j = 0; j < N; ++j ) { si = data.at( i )( j + 1 ); //dti[j*blockSize+i]; if ( si > 0 ) { si = log( si ); } else { si = 0.0; } log_s0_si_pixel[j] = s0 - si; } double value; // compute tensor ColumnVector t( 6 ); for ( int l = 0; l < 6; l++ ) { value = 0; for ( int m = 1; m <= N; ++m ) { value += BI( l + 1, m ) * log_s0_si_pixel[m - 1]; } t( l + 1 ) = (float) ( value ); // save the tensor components in a adjacent memory } Matrix m( 3, 3 ); m( 1, 1 ) = t( 1 ); m( 1, 2 ) = t( 2 ); m( 1, 3 ) = t( 3 ); m( 2, 1 ) = t( 2 ); m( 2, 2 ) = t( 4 ); m( 2, 3 ) = t( 5 ); m( 3, 1 ) = t( 3 ); m( 3, 2 ) = t( 5 ); m( 3, 3 ) = t( 6 ); out.push_back( m ); } // end if s0 > 0 else { out.push_back( blank ); } } } void FMath::fa( QVector<Matrix>& tensors, QVector<float>& faOut ) { int blockSize = tensors.size(); faOut.resize( blockSize ); QVector<float> trace( blockSize ); float value = 0; for ( int i = 0; i < blockSize; ++i ) { value = tensors.at( i )( 1, 1 ); value += tensors.at( i )( 2, 2 ); value += tensors.at( i )( 3, 3 ); trace[i] = value / 3.0; } QVector<float> fa( blockSize ); double xx, xy, xz, yy, yz, zz, tr, AA, DD; for ( int i = 0; i < blockSize; ++i ) { xx = tensors.at( i )( 1, 1 ); xy = tensors.at( i )( 1, 2 ); xz = tensors.at( i )( 1, 3 ); yy = tensors.at( i )( 2, 2 ); yz = tensors.at( i )( 2, 3 ); zz = tensors.at( i )( 3, 3 ); tr = trace[i]; AA = pow2( xx - tr ) + pow2( yy - tr ) + pow2( zz - tr ) + 2 * pow2( xy ) + 2 * pow2( xz ) + 2 * pow2( yz ); DD = pow2( xx ) + pow2( yy ) + pow2( zz ) + 2 * pow2( xy ) + 2 * pow2( xz ) + 2 * pow2( yz ); if ( DD > 0 ) { faOut[i] = qMin( 1.0f, (float) ( sqrt( AA ) / sqrt( DD ) * sqrt( 1.5 ) ) ); } else { faOut[i] = 0.0; } } } float FMath::fa( Matrix tensor ) { float trace; float value = 0; value = tensor( 1, 1 ); value += tensor( 2, 2 ); value += tensor( 3, 3 ); trace = value / 3.0; float fa; double xx, xy, xz, yy, yz, zz, tr, AA, DD; xx = tensor( 1, 1 ); xy = tensor( 1, 2 ); xz = tensor( 1, 3 ); yy = tensor( 2, 2 ); yz = tensor( 2, 3 ); zz = tensor( 3, 3 ); tr = trace; AA = pow2( xx - tr ) + pow2( yy - tr ) + pow2( zz - tr ) + 2 * pow2( xy ) + 2 * pow2( xz ) + 2 * pow2( yz ); DD = pow2( xx ) + pow2( yy ) + pow2( zz ) + 2 * pow2( xy ) + 2 * pow2( xz ) + 2 * pow2( yz ); if ( DD > 0 ) { fa = qMin( 1.0f, (float) ( sqrt( AA ) / sqrt( DD ) * sqrt( 1.5 ) ) ); } else { fa = 0.0; } return fa; } void FMath::evec1( QVector<Matrix>& tensors, QVector<QVector3D>& evec1 ) { int blockSize = tensors.size(); evec1.resize( blockSize ); double xx, xy, xz, yy, yz, zz; double i1, i2, i3, v, s, phi, l1, l2, l3; double vec_norm, ev1_x, ev1_y, ev1_z; for ( int i = 0; i < blockSize; ++i ) { xx = tensors.at( i )( 1, 1 ); xy = tensors.at( i )( 1, 2 ); xz = tensors.at( i )( 1, 3 ); yy = tensors.at( i )( 2, 2 ); yz = tensors.at( i )( 2, 3 ); zz = tensors.at( i )( 3, 3 ); // three invariants of D (dt) // i1=l1+l2+l3 (trace) // i2=l1*l2+l1*l3+l2*l3 // i3=l1*l2*l3 (determinante) i1 = xx + yy + zz; i2 = xx * yy + xx * zz + yy * zz - ( pow2( xy ) + pow2( xz ) + pow2( yz ) ); i3 = xx * yy * zz + 2. * xy * xz * yz - ( zz * pow2( xy ) + yy * pow2( xz ) + xx * pow2( yz ) ); v = pow2( i1 / 3 ) - i2 / 3; s = pow3( i1 / 3 ) - i1 * i2 / 6 + i3 / 2; if ( ( v > 0 ) && ( pow2( s ) < pow3( v ) ) ) phi = acos( s / v * sqrt( 1. / v ) ) / 3; else phi = 0; // eigenvalues if ( phi != 0 ) { l1 = i1 / 3 + 2 * sqrt( v ) * cos( phi ); l2 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. + phi ); l3 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. - phi ); } else l1 = l2 = l3 = 0.0; // eigenvectors ev1_x = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * yz - ( zz - l1 ) * xy ); ev1_y = ( xz * yz - ( zz - l1 ) * xy ) * ( xz * xy - ( xx - l1 ) * yz ); ev1_z = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * xy - ( xx - l1 ) * yz ); vec_norm = sqrt( pow2( ev1_x ) + pow2( ev1_y ) + pow2( ev1_z ) ); if ( vec_norm > 0 ) { ev1_x = ev1_x / vec_norm; ev1_y = ev1_y / vec_norm; ev1_z = ev1_z / vec_norm; } else ev1_x = ev1_y = ev1_z = 0.0; evec1[i].setX( ev1_x ); evec1[i].setY( ev1_y ); evec1[i].setZ( ev1_z ); } } void FMath::evecs( QVector<Matrix>& tensors, QVector<QVector3D>& evec1, QVector<float>& eval1, QVector<QVector3D>& evec2, QVector<float>& eval2, QVector<QVector3D>& evec3, QVector<float>& eval3 ) { int blockSize = tensors.size(); evec1.resize( blockSize ); evec2.resize( blockSize ); evec3.resize( blockSize ); eval1.resize( blockSize ); eval2.resize( blockSize ); eval3.resize( blockSize ); double xx, xy, xz, yy, yz, zz; double i1, i2, i3, v, s, phi, l1, l2, l3; double vec_norm, ev1_x, ev1_y, ev1_z, ev2_x, ev2_y, ev2_z, ev3_x, ev3_y, ev3_z; for ( int i = 0; i < blockSize; ++i ) { xx = tensors.at( i )( 1, 1 ); xy = tensors.at( i )( 1, 2 ); xz = tensors.at( i )( 1, 3 ); yy = tensors.at( i )( 2, 2 ); yz = tensors.at( i )( 2, 3 ); zz = tensors.at( i )( 3, 3 ); // three invariants of D (dt) // i1=l1+l2+l3 (trace) // i2=l1*l2+l1*l3+l2*l3 // i3=l1*l2*l3 (determinante) i1 = xx + yy + zz; i2 = xx * yy + xx * zz + yy * zz - ( pow2( xy ) + pow2( xz ) + pow2( yz ) ); i3 = xx * yy * zz + 2. * xy * xz * yz - ( zz * pow2( xy ) + yy * pow2( xz ) + xx * pow2( yz ) ); v = pow2( i1 / 3 ) - i2 / 3; s = pow3( i1 / 3 ) - i1 * i2 / 6 + i3 / 2; if ( ( v > 0 ) && ( pow2( s ) < pow3( v ) ) ) phi = acos( s / v * sqrt( 1. / v ) ) / 3; else phi = 0; // eigenvalues if ( phi != 0 ) { l1 = i1 / 3 + 2 * sqrt( v ) * cos( phi ); l2 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. + phi ); l3 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. - phi ); } else l1 = l2 = l3 = 0.0; eval1[i] = l1; eval2[i] = l2; eval3[i] = l3; // eigenvectors ev1_x = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * yz - ( zz - l1 ) * xy ); ev1_y = ( xz * yz - ( zz - l1 ) * xy ) * ( xz * xy - ( xx - l1 ) * yz ); ev1_z = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * xy - ( xx - l1 ) * yz ); ev2_x = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * yz - ( zz - l2 ) * xy ); ev2_y = ( xz * yz - ( zz - l2 ) * xy ) * ( xz * xy - ( xx - l2 ) * yz ); ev2_z = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * xy - ( xx - l2 ) * yz ); ev3_x = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * yz - ( zz - l3 ) * xy ); ev3_y = ( xz * yz - ( zz - l3 ) * xy ) * ( xz * xy - ( xx - l3 ) * yz ); ev3_z = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * xy - ( xx - l3 ) * yz ); vec_norm = sqrt( pow2( ev1_x ) + pow2( ev1_y ) + pow2( ev1_z ) ); if ( vec_norm > 0 ) { ev1_x = ev1_x / vec_norm; ev1_y = ev1_y / vec_norm; ev1_z = ev1_z / vec_norm; } else ev1_x = ev1_y = ev1_z = 0.0; vec_norm = sqrt( pow2( ev2_x ) + pow2( ev2_y ) + pow2( ev2_z ) ); if ( vec_norm > 0 ) { ev2_x = ev2_x / vec_norm; ev2_y = ev2_y / vec_norm; ev2_z = ev2_z / vec_norm; } else ev2_x = ev2_y = ev2_z = 0.0; vec_norm = sqrt( pow2( ev3_x ) + pow2( ev3_y ) + pow2( ev3_z ) ); if ( vec_norm > 0 ) { ev3_x = ev3_x / vec_norm; ev3_y = ev3_y / vec_norm; ev3_z = ev3_z / vec_norm; } else ev3_x = ev3_y = ev3_z = 0.0; evec1[i].setX( ev1_x ); evec1[i].setY( ev1_y ); evec1[i].setZ( ev1_z ); evec2[i].setX( ev2_x ); evec2[i].setY( ev2_y ); evec2[i].setZ( ev2_z ); evec3[i].setX( ev3_x ); evec3[i].setY( ev3_y ); evec3[i].setZ( ev3_z ); } } Matrix FMath::expT( Matrix& t ) { double xx, xy, xz, yy, yz, zz; double i1, i2, i3, v, s, phi, l1, l2, l3; double ev1_x, ev1_y, ev1_z, ev2_x, ev2_y, ev2_z, ev3_x, ev3_y, ev3_z, vec_norm; xx = t( 1, 1 ); xy = t( 1, 2 ); xz = t( 1, 3 ); yy = t( 2, 2 ); yz = t( 2, 3 ); zz = t( 3, 3 ); // three invariants of D (dt) // i1=l1+l2+l3 (trace) // i2=l1*l2+l1*l3+l2*l3 // i3=l1*l2*l3 (determinante) i1 = xx + yy + zz; i2 = xx * yy + xx * zz + yy * zz - ( FMath::pow2( xy ) + FMath::pow2( xz ) + FMath::pow2( yz ) ); i3 = xx * yy * zz + 2. * xy * xz * yz - ( zz * FMath::pow2( xy ) + yy * FMath::pow2( xz ) + xx * FMath::pow2( yz ) ); v = FMath::pow2( i1 / 3 ) - i2 / 3; s = FMath::pow3( i1 / 3 ) - i1 * i2 / 6 + i3 / 2; if ( ( v > 0 ) && ( FMath::pow2( s ) < FMath::pow3( v ) ) ) phi = acos( s / v * sqrt( 1. / v ) ) / 3; else phi = 0; // eigenvalues if ( phi != 0 ) { l1 = i1 / 3 + 2 * sqrt( v ) * cos( phi ); l2 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. + phi ); l3 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. - phi ); } else l1 = l2 = l3 = 0.0; /* eval1[i] = l1; eval2[i] = l2; eval3[i] = l3; */ // eigenvectors ev1_x = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * yz - ( zz - l1 ) * xy ); ev1_y = ( xz * yz - ( zz - l1 ) * xy ) * ( xz * xy - ( xx - l1 ) * yz ); ev1_z = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * xy - ( xx - l1 ) * yz ); ev2_x = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * yz - ( zz - l2 ) * xy ); ev2_y = ( xz * yz - ( zz - l2 ) * xy ) * ( xz * xy - ( xx - l2 ) * yz ); ev2_z = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * xy - ( xx - l2 ) * yz ); ev3_x = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * yz - ( zz - l3 ) * xy ); ev3_y = ( xz * yz - ( zz - l3 ) * xy ) * ( xz * xy - ( xx - l3 ) * yz ); ev3_z = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * xy - ( xx - l3 ) * yz ); vec_norm = sqrt( FMath::pow2( ev1_x ) + FMath::pow2( ev1_y ) + FMath::pow2( ev1_z ) ); if ( vec_norm > 0 ) { ev1_x = ev1_x / vec_norm; ev1_y = ev1_y / vec_norm; ev1_z = ev1_z / vec_norm; } else ev1_x = ev1_y = ev1_z = 0.0; vec_norm = sqrt( FMath::pow2( ev2_x ) + FMath::pow2( ev2_y ) + FMath::pow2( ev2_z ) ); if ( vec_norm > 0 ) { ev2_x = ev2_x / vec_norm; ev2_y = ev2_y / vec_norm; ev2_z = ev2_z / vec_norm; } else ev2_x = ev2_y = ev2_z = 0.0; vec_norm = sqrt( FMath::pow2( ev3_x ) + FMath::pow2( ev3_y ) + FMath::pow2( ev3_z ) ); if ( vec_norm > 0 ) { ev3_x = ev3_x / vec_norm; ev3_y = ev3_y / vec_norm; ev3_z = ev3_z / vec_norm; } else ev3_x = ev3_y = ev3_z = 0.0; Matrix U( 3, 3 ); DiagonalMatrix D( 3 ); U( 1, 1 ) = ev1_x; U( 2, 1 ) = ev1_y; U( 3, 1 ) = ev1_z; U( 1, 2 ) = ev2_x; U( 2, 2 ) = ev2_y; U( 3, 2 ) = ev2_z; U( 1, 3 ) = ev3_x; U( 2, 3 ) = ev3_y; U( 3, 3 ) = ev3_z; D( 1 ) = exp( l1 ); D( 2 ) = exp( l2 ); D( 3 ) = exp( l3 ); Matrix expM(3,3); expM = U * D * U.t(); return expM; } //void evd3x3_2( ColumnVector tensor, QVector<ColumnVector>& vecs, ColumnVector& vals ); void FMath::evd3x3_2( ColumnVector &d, QVector<ColumnVector>& vec, ColumnVector& val ) { if ( d.Nrows() != 6 ) throw std::invalid_argument( "Tensor (6-component vector) expected!" ); // calculate the eigenvalues: val = ColumnVector( 3 ); vec.reserve( 3 ); std::vector<int> index( 3 ); ColumnVector e( 3 ); // Create work variables: Matrix A( 3, 3 ), Q( 3, 3 ); A( 1, 1 ) = d( 1 ); A( 2, 1 ) = A( 1, 2 ) = d( 2 ); A( 3, 1 ) = A( 1, 3 ) = d( 3 ); A( 2, 2 ) = d( 4 ); A( 3, 2 ) = A( 2, 3 ) = d( 5 ); A( 3, 3 ) = d( 6 ); double m, c1, c0; // Determine coefficients of characteristic poynomial. We write // | a d f | // A = | d* b e | // | f* e* c | double de = A( 1, 2 ) * A( 2, 3 ); // d * e double dd = A( 1, 2 ) * A( 1, 2 ); // d^2 double ee = A( 2, 3 ) * A( 2, 3 ); // e^2 double ff = A( 1, 3 ) * A( 1, 3 ); // f^2 m = A( 1, 1 ) + A( 2, 2 ) + A( 3, 3 ); c1 = ( A( 1, 1 ) * A( 2, 2 ) + A( 1, 1 ) * A( 3, 3 ) + A( 2, 2 ) * A( 3, 3 ) ) // a*b + a*c + b*c - d^2 - e^2 - f^2 - ( dd + ee + ff ); c0 = A( 3, 3 ) * dd + A( 1, 1 ) * ee + A( 2, 2 ) * ff - A( 1, 1 ) * A( 2, 2 ) * A( 3, 3 ) - 2.0 * A( 1, 3 ) * de; // c*d^2 + a*e^2 + b*f^2 - a*b*c - 2*f*d*e) double p, sqrt_p, q, c, s, phi; p = m * m - 3.0 * c1; q = m * ( p - ( 3.0 / 2.0 ) * c1 ) - ( 27.0 / 2.0 ) * c0; sqrt_p = sqrt( fabs( p ) ); phi = 27.0 * ( 0.25 * c1 * c1 * ( p - c1 ) + c0 * ( q + 27.0 / 4.0 * c0 ) ); phi = ( 1.0 / 3.0 ) * atan2( sqrt( fabs( phi ) ), q ); c = sqrt_p * cos( phi ); s = ( 1.0 / sqrt( 3.0 ) ) * sqrt_p * sin( phi ); e( 2 ) = ( 1.0 / 3.0 ) * ( m - c ); e( 3 ) = e( 2 ) + s; e( 1 ) = e( 2 ) + c; e( 2 ) -= s; if ( e( 1 ) > e( 2 ) ) { if ( e( 1 ) > e( 3 ) ) { if ( e( 2 ) > e( 3 ) ) { index = { 0,1,2}; } else { index = {0,2,1}; } } else { index = { 2,0,1}; } } else { if( e(2) > e(3) ) { if( e(1) > e(3) ) { index = { 1,0,2}; } else { index = { 1,2,0}; } } else { index = {2,1,0}; } } for ( unsigned long i( 1 ); i < 4; ++i ) val( i ) = e( index[i-1]+1 ); double wmax = ( fabs( val( 1 ) ) > fabs( val( 3 ) ) ) ? val( 1 ) : val( 3 ); double thresh = ( 8.0 * DBL_EPSILON * wmax ) * ( 8.0 * DBL_EPSILON * wmax ); // Prepare calculation of eigenvectors: double n0tmp = A( 1, 2 ) * A( 1, 2 ) + A( 1, 3 ) * A( 1, 3 ); double n1tmp = A( 1, 2 ) * A( 1, 2 ) + A( 2, 3 ) * A( 2, 3 ); Q( 1, 2 ) = A( 1, 2 ) * A( 2, 3 ) - A( 1, 3 ) * A( 2, 2 ); Q( 2, 2 ) = A( 1, 3 ) * A( 2, 1 ) - A( 2, 3 ) * A( 1, 1 ); Q( 3, 2 ) = A( 1, 2 ) * A( 1, 2 ); // Calculate first eigenvector by the formula // v(0) = (A - w(0)).e1 x (A - w(0)).e2 A( 1, 1 ) -= val( 1 ); A( 2, 2 ) -= val( 1 ); Q( 1, 1 ) = Q( 1, 2 ) + A( 1, 3 ) * val( 1 ); Q( 2, 1 ) = Q( 2, 2 ) + A( 2, 3 ) * val( 1 ); Q( 3, 1 ) = A( 1, 1 ) * A( 2, 2 ) - Q( 3, 2 ); double norm = Q( 1, 1 ) * Q( 1, 1 ) + Q( 2, 1 ) * Q( 2, 1 ) + Q( 3, 1 ) * Q( 3, 1 ); double n0 = n0tmp + A( 1, 1 ) * A( 1, 1 ); double n1 = n1tmp + A( 2, 2 ) * A( 2, 2 ); double error = n0 * n1; double t( 0 ), f( 0 ); unsigned long i( 0 ), j( 0 ); if ( n0 <= thresh ) // If the first column is zero, then (1,0,0) is an eigenvector { Q( 1, 1 ) = 1.0; Q( 2, 1 ) = 0.0; Q( 3, 1 ) = 0.0; } else if ( n1 <= thresh ) // If the second column is zero, then (0,1,0) is an eigenvector { Q( 1, 1 ) = 0.0; Q( 2, 1 ) = 1.0; Q( 3, 1 ) = 0.0; } else if ( norm < 64.0 * 64.0 * DBL_EPSILON * DBL_EPSILON * error ) { // If angle between A(0) and A(1) is too small, don't use t = A( 1, 2 ) * A( 1, 2 ); // cross product, but calculate v ~ (1, -A0/A1, 0) f = -A( 1, 1 ) / A( 1, 2 ); if ( A( 2, 2 ) * A( 2, 2 ) > t ) { t = A( 2, 2 ) * A( 2, 2 ); f = -A( 1, 2 ) / A( 2, 2 ); } if ( A( 2, 3 ) * A( 2, 3 ) > t ) f = -A( 1, 3 ) / A( 2, 3 ); norm = 1.0 / sqrt( 1 + f * f ); Q( 1, 1 ) = norm; Q( 2, 1 ) = f * norm; Q( 3, 1 ) = 0.0; } else // This is the standard branch { norm = sqrt( 1.0 / norm ); for ( j = 1; j < 4; ++j ) Q( j, 1 ) = Q( j, 1 ) * norm; } // Prepare calculation of second eigenvector t = val( 1 ) - val( 2 ); if ( fabs( t ) > 8.0 * DBL_EPSILON * wmax ) { // For non-degenerate eigenvalue, calculate second eigenvector by the formula // v(1) = (A - w(1)).e1 x (A - w(1)).e2 A( 1, 1 ) += t; A( 2, 2 ) += t; Q( 1, 2 ) = Q( 1, 2 ) + A( 1, 3 ) * val( 1 ); Q( 2, 2 ) = Q( 2, 2 ) + A( 2, 3 ) * val( 1 ); Q( 3, 2 ) = A( 1, 1 ) * A( 2, 2 ) - Q( 3, 2 ); norm = Q( 1, 2 ) * Q( 1, 2 ) + Q( 2, 2 ) * Q( 2, 2 ) + Q( 3, 2 ) * Q( 3, 2 ); n0 = n0tmp + A( 1, 1 ) * A( 1, 1 ); n1 = n1tmp + A( 2, 2 ) * A( 2, 2 ); error = n0 * n1; if ( n0 <= thresh ) // If the first column is zero, then (1,0,0) is an eigenvector { Q( 1, 2 ) = 1.0; Q( 2, 2 ) = 0.0; Q( 3, 2 ) = 0.0; } else if ( n1 <= thresh ) // If the second column is zero, then (0,1,0) is an eigenvector { Q( 1, 2 ) = 0.0; Q( 2, 2 ) = 1.0; Q( 3, 2 ) = 0.0; } else if ( norm < 64.0 * DBL_EPSILON * 64.0 * DBL_EPSILON * error ) { // If angle between A(0) and A(1) is too small, don't use t = A( 1, 2 ) * A( 1, 2 ); // cross product, but calculate v ~ (1, -A0/A1, 0) f = -A( 1, 1 ) / A( 1, 2 ); if ( A( 2, 2 ) * A( 2, 2 ) > t ) { t = A( 2, 2 ) * A( 2, 2 ); f = -A( 1, 2 ) / A( 2, 2 ); } if ( A( 2, 3 ) * A( 2, 3 ) > t ) f = -A( 1, 3 ) / A( 2, 3 ); norm = 1.0 / sqrt( 1 + f * f ); Q( 1, 2 ) = norm; Q( 2, 2 ) = f * norm; Q( 3, 2 ) = 0.0; } else { norm = sqrt( 1.0 / norm ); for ( j = 1; j < 4; ++j ) Q( j, 2 ) = Q( j, 2 ) * norm; } } else { // For degenerate eigenvalue, calculate second eigenvector according to // v(1) = v(0) x (A - w(1)).e(i) // // This would really get to complicated if we could not assume all of A to // contain meaningful values. A( 2, 1 ) = A( 1, 2 ); A( 3, 1 ) = A( 1, 3 ); A( 3, 2 ) = A( 2, 3 ); A( 1, 1 ) += val( 1 ); A( 2, 2 ) += val( 1 ); for ( i = 1; i < 4; ++i ) { A( i, i ) -= val( 2 ); n0 = A( 1, i ) * A( 1, i ) + A( 2, i ) * A( 2, i ) + A( 3, i ) * A( 3, i ); if ( n0 > thresh ) { Q( 1, 2 ) = Q( 2, 1 ) * A( 3, i ) - Q( 3, 1 ) * A( 2, i ); Q( 2, 2 ) = Q( 3, 1 ) * A( 1, i ) - Q( 1, 1 ) * A( 3, i ); Q( 3, 2 ) = Q( 1, 1 ) * A( 2, i ) - Q( 2, 1 ) * A( 1, i ); norm = Q( 1, 2 ) * Q( 1, 2 ) + Q( 2, 2 ) * Q( 2, 2 ) + Q( 3, 2 ) * Q( 3, 2 ); if ( norm > 256.0 * DBL_EPSILON * 256.0 * DBL_EPSILON * n0 ) // Accept cross product only if the angle between { // the two vectors was not too small norm = sqrt( 1.0 / norm ); for ( j = 1; j < 4; ++j ) Q( j, 2 ) = Q( j, 2 ) * norm; break; } } } if ( i == 4 ) // This means that any vector orthogonal to v(0) is an EV. { for ( j = 1; j < 4; ++j ) if ( Q( j, 1 ) != 0.0 ) // Find nonzero element of v(0) ... { // ... and swap it with the next one norm = 1.0 / sqrt( Q( j, 1 ) * Q( j, 1 ) + Q( ( j + 2 ) % 3 + 1, 1 ) * Q( ( j + 1 ) % 3 + 1, 1 ) ); Q( j, 2 ) = Q( ( j + 1 ) % 3 + 1, 1 ) * norm; Q( ( j + 1 ) % 3 + 1, 2 ) = -Q( j, 1 ) * norm; Q( ( j + 2 ) % 3 + 1, 2 ) = 0.0; break; } } } // Calculate third eigenvector according to // v(2) = v(0) x v(1) Q( 1, 3 ) = Q( 2, 1 ) * Q( 3, 2 ) - Q( 3, 1 ) * Q( 2, 2 ); Q( 2, 3 ) = Q( 3, 1 ) * Q( 1, 2 ) - Q( 1, 1 ) * Q( 3, 2 ); Q( 3, 3 ) = Q( 1, 1 ) * Q( 2, 2 ) - Q( 2, 1 ) * Q( 1, 2 ); vec.clear(); for ( int ii( 1 ); ii < 4; ++ii ) { ColumnVector tmp( 3 ); tmp( 1 ) = Q( 1, ii ); tmp( 2 ) = Q( 2, ii ); tmp( 3 ) = Q( 3, ii ); vec.push_back( tmp ); } } bool FMath::linePlaneIntersection( QVector3D& contact, QVector3D ray, QVector3D rayOrigin, QVector3D normal, QVector3D coord ) { // calculate plane float d = QVector3D::dotProduct( normal, coord ); if ( QVector3D::dotProduct( normal, ray ) == 0 ) { return false; // avoid divide by zero } // Compute the t value for the directed line ray intersecting the plane float t = ( d - QVector3D::dotProduct( normal, rayOrigin ) ) / QVector3D::dotProduct( normal, ray ); // scale the ray by t QVector3D newRay = ray * t; // calc contact point contact = rayOrigin + newRay; if ( t >= 0.0f && t <= 1.0f ) { return true; // line intersects plane } return false; // line does not }
30.357027
161
0.414879
rdmenezes
5ecb86d81887a82e2049be442d56db498b130b8a
2,194
cpp
C++
codes/UVA/10001-19999/uva10641.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/UVA/10001-19999/uva10641.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/UVA/10001-19999/uva10641.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; const int N = 105; const int M = 1005; const int INF = 0x3f3f3f3f; const double eps = 1e-6; const double pi = atan(1.0)*4; struct state { int l, r, val; }s[M]; struct point { double x, y; point (double x = 0, double y = 0) { this->x = x; this->y = y;} point operator - (const point &o) const {return point(x - o.x, y - o.y);} double det(const point &o) const {return x * o.y - y * o.x;} }p[N], o; int n, m, dp[N]; inline double dis(double x, double y) { return sqrt(x*x+y*y); } inline int sign(double x) {return x < -eps ? -1 : x > eps;} inline double getP(double y, double x) { if (fabs(x) < eps) { return y > 0 ? -pi : pi; } return atan2(y, x); } bool judge (point l, point a, point b) { return sign((l - a).det(b - a) * (o - a).det(b - a)) < 0; } void cat (state& u, double xi, double yi) { bool flag[N]; memset(flag, false, sizeof(flag)); for (int i = 0; i < n; i++) { if (judge(point(xi, yi), p[i], p[i+1])) flag[i] = true; } if (flag[0] && flag[n-1]) { int l = n-1, r = n; while (flag[l]) u.l = l, l--; while (flag[r-n]) u.r = r, r++; } else { int l = 0, r = n-1; while (!flag[l]) l++; u.l = l; while (!flag[r]) r--; u.r = r; } u.r++; if (u.r < u.l) u.r += n; } void init () { o.x = o.y = 0; for (int i = 0; i < n; i++) { scanf("%lf%lf", &p[i].x, &p[i].y); o.x += p[i].x; o.y += p[i].y; } o.x /= n; o.y /= n; p[n] = p[0]; double x, y; int value; scanf("%d", &m); for (int i = 0; i < m; i++) { scanf("%lf%lf%d", &x, &y, &value); cat(s[i], x, y); s[i].val = value; } } bool solve () { int ans = INF; for (int i = 0; i < n; i++) { memset(dp, INF, sizeof(dp)); dp[i] = 0; for (int j = 0; j < n; j++) { int t = i + j; for (int x = 0; x < m; x++) { if (s[x].l > t) continue; int ad = min(s[x].r, i+n); dp[ad] = min(dp[ad], dp[t]+s[x].val); } } ans = min(ans, dp[i+n]); } if (ans == INF) return false; printf("%d\n", ans); return true; } int main () { while (scanf("%d", &n) == 1 && n) { init (); if (!solve()) printf("Impossible.\n"); } return 0; }
17.275591
74
0.494075
JeraKrs
5ece56c363f9bef2a5e89e10ef8ee7690b553ca4
3,817
cpp
C++
src/MQTT/Network.cpp
dinhhuy258/mqtt-client
b07e027e7e3d2d84008a22513bedebf6d95c4bb1
[ "MIT" ]
8
2016-06-01T09:44:10.000Z
2022-01-19T01:03:50.000Z
src/MQTT/Network.cpp
dinhhuy258/mqtt-client
b07e027e7e3d2d84008a22513bedebf6d95c4bb1
[ "MIT" ]
null
null
null
src/MQTT/Network.cpp
dinhhuy258/mqtt-client
b07e027e7e3d2d84008a22513bedebf6d95c4bb1
[ "MIT" ]
4
2017-01-06T02:51:24.000Z
2022-01-19T01:03:52.000Z
#include "Network.h" #include <iostream> #include "Utils.h" Network::Network() : connectedCallback(nullptr), disconnectedCallback(nullptr), receivedCallback(nullptr), sentCallback(nullptr), socket(nullptr) { } void Network::Connect(std::string host, uint32_t port, bool security) { if (security) { socket = make_unique<SSLSocket>(); } else { socket = make_unique<TCPSocket>(); } if (socket->Initialize()) { socket->Connect(host, port, std::bind(&Network::ConnectHandler, this, std::placeholders::_1)); } } void Network::Disconnect() { socket->Close(); if (disconnectedCallback) { disconnectedCallback(); } } void Network::WriteData(uint8_t *data, std::size_t dataLength) { socket->WriteData(data, dataLength, std::bind(&Network::WriteHandler, this, std::placeholders::_1, std::placeholders::_2)); } void Network::RegisterConnectedCallback(std::function<void()> connectedCallback) { this->connectedCallback = connectedCallback; } void Network::RegisterDisconnectedCallback(std::function<void()> disconnectedCallback) { this->disconnectedCallback = disconnectedCallback; } void Network::RegisterReceivedCallback(std::function<void(uint8_t*, std::size_t)> receivedCallback) { this->receivedCallback = receivedCallback; } void Network::RegisterSentCallback(std::function<void(std::size_t)> sentCallback) { this->sentCallback = sentCallback; } void Network::ConnectHandler(bool error) { if (!error) { if (connectedCallback) { connectedCallback(); } bufferIndex = 0; readDone = false; socket->ReadData(readBuffer, 1, std::bind(&Network::ReadHandler, this, std::placeholders::_1, std::placeholders::_2)); } else { LOGI("Connect error"); Disconnect(); } } void Network::WriteHandler(bool error, std::size_t bytesTransferred) { if (!error) { if (sentCallback) { sentCallback(bytesTransferred); } } else { LOGI("Write data error"); Disconnect(); } } void Network::ReadHandler(bool error, std::size_t bytesTransferred) { if (!error) { if (readDone) { // Read variable header and payload done. Send it to receivedCallback for (std::size_t i = 0; i < bytesTransferred; ++i) { buffer[bufferIndex++] = readBuffer[i]; } if (receivedCallback) { receivedCallback(buffer, bufferIndex); } bufferIndex = 0; readDone = false; socket->ReadData(readBuffer, 1, std::bind(&Network::ReadHandler, this, std::placeholders::_1, std::placeholders::_2)); } else if (!bufferIndex) { buffer[bufferIndex++] = readBuffer[0]; socket->ReadData(readBuffer, 1, std::bind(&Network::ReadHandler, this, std::placeholders::_1, std::placeholders::_2)); } else { buffer[bufferIndex++] = readBuffer[0]; if (readBuffer[0] == 0) { //Some MQTT message has no variable header and payload if (receivedCallback) { receivedCallback(buffer, bufferIndex); } bufferIndex = 0; socket->ReadData(readBuffer, 1, std::bind(&Network::ReadHandler, this, std::placeholders::_1, std::placeholders::_2)); } else if ((readBuffer[0] & 0x80) != 0x80) { //Reading reamaining length bytes done readDone = true; uint32_t multiplier = 1; uint32_t remainingLength = 0; for (uint8_t i = 1; i < bufferIndex; ++i) { remainingLength += (buffer[i] & 127) * multiplier; multiplier *= 128; } //Try to read variable header and payload socket->ReadData(readBuffer, remainingLength, std::bind(&Network::ReadHandler, this, std::placeholders::_1, std::placeholders::_2)); } else { //Continue read remaining length bytes socket->ReadData(readBuffer, 1, std::bind(&Network::ReadHandler, this, std::placeholders::_1, std::placeholders::_2)); } } } else { LOGI("Read data error %d", static_cast<int>(bytesTransferred)); Disconnect(); } }
24.158228
145
0.685617
dinhhuy258
5ed00c45c1058e41ab71fbfbc351c8add170a0b8
1,491
hpp
C++
libkcommon/hclust_compactor.hpp
disa-mhembere/knor
5c4174b80726eb5fc8da7042d517e8c3929ec747
[ "Apache-2.0" ]
13
2017-06-30T12:48:54.000Z
2021-05-26T06:54:10.000Z
libkcommon/hclust_compactor.hpp
disa-mhembere/knor
5c4174b80726eb5fc8da7042d517e8c3929ec747
[ "Apache-2.0" ]
30
2016-11-21T23:21:48.000Z
2017-03-05T06:26:52.000Z
libkcommon/hclust_compactor.hpp
disa-mhembere/k-par-means
5c4174b80726eb5fc8da7042d517e8c3929ec747
[ "Apache-2.0" ]
5
2017-04-11T00:44:04.000Z
2018-11-01T10:41:06.000Z
/* * Copyright 2016 neurodata (http://neurodata.io/) * Written by Disa Mhembere (disa@jhu.edu) * * This file is part of knor * * 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 CURRENT_KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __KNOR_HCLUST_COMPACTOR_HPP__ #define __KNOR_HCLUST_COMPACTOR_HPP__ #include <vector> #include <unordered_map> namespace knor { namespace util { class compactor { public: template <typename T> static void remap(std::vector<T>& counts, std::vector<size_t>& remapd_counts, std::unordered_map<unsigned, unsigned>& id_map) { for (size_t i = 0; i < counts.size(); i++) { assert(counts[i] >= 0); if (counts[i] > 0) { id_map[i] = remapd_counts.size(); remapd_counts.push_back(counts[i]); } } } }; } } // End namespace knor::util #endif
30.428571
83
0.603622
disa-mhembere
5ed615d1056095dcf175c37f14284e9416e27c03
45,085
cpp
C++
src/devices/cpu/dspp/dsppdrc.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/devices/cpu/dspp/dsppdrc.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/devices/cpu/dspp/dsppdrc.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Philip Bennett /****************************************************************************** DSPP UML recompiler core ******************************************************************************/ #include "emu.h" #include "debugger.h" #include "dspp.h" #include "dsppfe.h" #include "cpu/drcfe.h" #include "cpu/drcuml.h" #include "cpu/drcumlsh.h" using namespace uml; #define USE_SWAPDQ 0 // map variables #define MAPVAR_PC M0 #define MAPVAR_CYCLES M1 // exit codes #define EXECUTE_OUT_OF_CYCLES 0 #define EXECUTE_MISSING_CODE 1 #define EXECUTE_UNMAPPED_CODE 2 #define EXECUTE_RESET_CACHE 3 inline void dspp_device::alloc_handle(drcuml_state *drcuml, code_handle **handleptr, const char *name) { if (*handleptr == nullptr) *handleptr = drcuml->handle_alloc(name); } static inline uint32_t epc(const opcode_desc *desc) { return desc->pc; } #if 0 static void cfunc_unimplemented(void *param) { dspp_device *dspp = (dspp_device *)param; dspp->cfunc_unimplemented(); } #endif void dspp_device::cfunc_unimplemented() { // uint64_t op = m_core->m_arg0; // fatalerror("PC=%08X: Unimplemented op %04X%08X\n", m_core->m_pc, (uint32_t)(op >> 32), (uint32_t)(op)); } static void cfunc_update_fifo_dma(void *param) { dspp_device *dspp = (dspp_device *)param; dspp->update_fifo_dma(); } /*static void cfunc_print_sums(void *param) { dspp_device *dspp = (dspp_device *)param; dspp->print_sums(); } static void cfunc_print_value(void *param) { dspp_device *dspp = (dspp_device *)param; dspp->print_value(); } static void cfunc_print_addr(void *param) { dspp_device *dspp = (dspp_device *)param; dspp->print_addr(); } static void cfunc_print_branches(void *param) { dspp_device *dspp = (dspp_device *)param; dspp->print_branches(); }*/ /*------------------------------------------------- load_fast_iregs - load any fast integer registers -------------------------------------------------*/ inline void dspp_device::load_fast_iregs(drcuml_block &block) { #if 0 // TODO for (uint32_t regnum = 0; regnum < std::size(m_regmap); regnum++) { if (m_regmap[regnum].is_int_register()) { UML_MOV(block, ireg(m_regmap[regnum].ireg() - REG_I0), mem(&m_core->r[regnum])); } } #endif } /*------------------------------------------------- save_fast_iregs - save any fast integer registers -------------------------------------------------*/ void dspp_device::save_fast_iregs(drcuml_block &block) { #if 0 // TODO int regnum; for (regnum = 0; regnum < std::size(m_regmap); regnum++) { if (m_regmap[regnum].is_int_register()) { UML_MOV(block, mem(&m_core->r[regnum]), ireg(m_regmap[regnum].ireg() - REG_I0)); } } #endif } void dspp_device::static_generate_memory_accessor(bool iswrite, const char *name, uml::code_handle *&handleptr) { // I0 = read/write data // I1 = address drcuml_block &block = m_drcuml->begin_block(10); // add a global entry for this alloc_handle(m_drcuml.get(), &handleptr, name); UML_HANDLE(block, *handleptr); // handle *handleptr if (iswrite) { UML_WRITE(block, I1, I0, SIZE_WORD, SPACE_DATA); } else { UML_READ(block, I0, I1, SIZE_WORD, SPACE_DATA); } UML_RET(block); block.end(); } void dspp_device::execute_run_drc() { drcuml_state *drcuml = m_drcuml.get(); int execute_result; if (m_cache_dirty) flush_cache(); m_cache_dirty = false; do { execute_result = drcuml->execute(*m_entry); /* if we need to recompile, do it */ if (execute_result == EXECUTE_MISSING_CODE) { compile_block(m_core->m_pc); } else if (execute_result == EXECUTE_UNMAPPED_CODE) { fatalerror("Attempted to execute unmapped code at PC=%08X\n", m_core->m_pc); } else if (execute_result == EXECUTE_RESET_CACHE) { flush_cache(); } } while (execute_result != EXECUTE_OUT_OF_CYCLES); } void dspp_device::compile_block(offs_t pc) { drcuml_state *drcuml = m_drcuml.get(); compiler_state compiler = { 0 }; const opcode_desc *seqhead, *seqlast; int override = false; g_profiler.start(PROFILER_DRC_COMPILE); /* get a description of this sequence */ const opcode_desc *desclist = m_drcfe->describe_code(pc); bool succeeded = false; while (!succeeded) { try { /* start the block */ drcuml_block &block = drcuml->begin_block(32768); /* loop until we get through all instruction sequences */ for (seqhead = desclist; seqhead != nullptr; seqhead = seqlast->next()) { const opcode_desc *curdesc; uint32_t nextpc; /* add a code log entry */ if (drcuml->logging()) block.append_comment("-------------------------"); /* determine the last instruction in this sequence */ for (seqlast = seqhead; seqlast != nullptr; seqlast = seqlast->next()) if (seqlast->flags & OPFLAG_END_SEQUENCE) break; assert(seqlast != nullptr); /* if we don't have a hash for this mode/pc, or if we are overriding all, add one */ if (override || !drcuml->hash_exists(0, seqhead->pc)) UML_HASH(block, 0, seqhead->pc); // hash mode,pc /* if we already have a hash, and this is the first sequence, assume that we */ /* are recompiling due to being out of sync and allow future overrides */ else if (seqhead == desclist) { override = true; UML_HASH(block, 0, seqhead->pc); // hash mode,pc } /* otherwise, redispatch to that fixed PC and skip the rest of the processing */ else { UML_LABEL(block, seqhead->pc | 0x80000000); // label seqhead->pc UML_HASHJMP(block, 0, seqhead->pc, *m_nocode); // hashjmp <0>,seqhead->pc,nocode continue; } generate_checksum_block(block, &compiler, seqhead, seqlast); /* label this instruction, if it may be jumped to locally */ if (seqhead->flags & OPFLAG_IS_BRANCH_TARGET) UML_LABEL(block, seqhead->pc | 0x80000000); // label seqhead->pc compiler.abortlabel = compiler.labelnum++; /* iterate over instructions in the sequence and compile them */ for (curdesc = seqhead; curdesc != seqlast->next(); curdesc = curdesc->next()) generate_sequence_instruction(block, &compiler, curdesc); UML_LABEL(block, compiler.abortlabel); /* if we need to return to the start, do it */ if (seqlast->flags & OPFLAG_RETURN_TO_START) nextpc = pc; /* otherwise we just go to the next instruction */ else nextpc = seqlast->pc + seqlast->length; /* count off cycles and go there */ generate_update_cycles(block, &compiler, nextpc); // <subtract cycles> /* if the last instruction can change modes, use a variable mode; otherwise, assume the same mode */ if (seqlast->next() == nullptr || seqlast->next()->pc != nextpc) UML_HASHJMP(block, 0, nextpc, *m_nocode); // hashjmp <mode>,nextpc,nocode } /* end the sequence */ block.end(); g_profiler.stop(); succeeded = true; } catch (drcuml_block::abort_compilation &) { flush_cache(); } } } void dspp_device::generate_checksum_block(drcuml_block &block, compiler_state *compiler, const opcode_desc *seqhead, const opcode_desc *seqlast) { const opcode_desc *curdesc; if (m_drcuml->logging()) block.append_comment("[Validation for %08X]", seqhead->pc); // comment /* loose verify or single instruction: just compare and fail */ if (false/*!(m_drcoptions & DSPPDRC_STRICT_VERIFY)*/ || seqhead->next() == nullptr) { if (!(seqhead->flags & OPFLAG_VIRTUAL_NOOP)) { uint32_t sum = seqhead->opptr.w[0]; uint32_t addr = seqhead->physpc; const void *base = m_code_cache.read_ptr(addr); UML_MOV(block, I0, 0); UML_LOAD(block, I0, base, 0, SIZE_WORD, SCALE_x2); // load i0,base,0,word UML_CMP(block, I0, sum); // cmp i0,opptr[0] UML_EXHc(block, COND_NE, *m_nocode, seqhead->pc); // exne nocode,seqhead->pc } } /* full verification; sum up everything */ else { uint32_t sum = 0; uint32_t addr = seqhead->physpc; const void *base = m_code_cache.read_ptr(addr); UML_LOAD(block, I0, base, 0, SIZE_WORD, SCALE_x2); // load i0,base,0,dword sum += seqhead->opptr.w[0]; for (curdesc = seqhead->next(); curdesc != seqlast->next(); curdesc = curdesc->next()) if (!(curdesc->flags & OPFLAG_VIRTUAL_NOOP)) { addr = curdesc->physpc; base = m_code_cache.read_ptr(addr); assert(base != nullptr); UML_LOAD(block, I1, base, 0, SIZE_WORD, SCALE_x2); // load i1,base,dword UML_ADD(block, I0, I0, I1); // add i0,i0,i1 sum += curdesc->opptr.w[0]; } UML_CMP(block, I0, sum); // cmp i0,sum UML_EXHc(block, COND_NE, *m_nocode, epc(seqhead)); // exne nocode,seqhead->pc } } void dspp_device::flush_cache() { /* empty the transient cache contents */ m_drcuml->reset(); try { // generate the entry point and out-of-cycles handlers static_generate_entry_point(); static_generate_nocode_handler(); static_generate_out_of_cycles(); // generate memory accessors static_generate_memory_accessor(false, "dm_read16", m_dm_read16); static_generate_memory_accessor(true, "dm_write16", m_dm_write16); } catch (drcuml_block::abort_compilation &) { fatalerror("Error generating dspp static handlers\n"); } } void dspp_device::static_generate_entry_point() { /* begin generating */ drcuml_block &block = m_drcuml->begin_block(20); /* forward references */ alloc_handle(m_drcuml.get(), &m_nocode, "nocode"); alloc_handle(m_drcuml.get(), &m_entry, "entry"); UML_HANDLE(block, *m_entry); // handle entry //load_fast_iregs(block); // <load fastregs> /* generate a hash jump via the current mode and PC */ UML_HASHJMP(block, 0, mem(&m_core->m_pc), *m_nocode); block.end(); } void dspp_device::static_generate_nocode_handler() { /* begin generating */ drcuml_block &block = m_drcuml->begin_block(10); /* generate a hash jump via the current mode and PC */ alloc_handle(m_drcuml.get(), &m_nocode, "nocode"); UML_HANDLE(block, *m_nocode); // handle nocode UML_GETEXP(block, I0); // getexp i0 UML_MOV(block, mem(&m_core->m_pc), I0); // mov [pc],i0 //save_fast_iregs(block); // <save fastregs> UML_EXIT(block, EXECUTE_MISSING_CODE); // exit EXECUTE_MISSING_CODE block.end(); } void dspp_device::static_generate_out_of_cycles() { /* begin generating */ drcuml_block &block = m_drcuml->begin_block(10); /* generate a hash jump via the current mode and PC */ alloc_handle(m_drcuml.get(), &m_out_of_cycles, "out_of_cycles"); UML_HANDLE(block, *m_out_of_cycles); // handle out_of_cycles UML_GETEXP(block, I0); // getexp i0 UML_MOV(block, mem(&m_core->m_pc), I0); // mov <pc>,i0 //save_fast_iregs(block); // <save fastregs> UML_EXIT(block, EXECUTE_OUT_OF_CYCLES); // exit EXECUTE_OUT_OF_CYCLES block.end(); } void dspp_device::generate_sequence_instruction(drcuml_block &block, compiler_state *compiler, const opcode_desc *desc) { /* set the PC map variable */ UML_MAPVAR(block, MAPVAR_PC, desc->pc); // mapvar PC,desc->pc /* accumulate total cycles */ compiler->cycles += desc->cycles; /* update the icount map variable */ UML_MAPVAR(block, MAPVAR_CYCLES, compiler->cycles); // mapvar CYCLES,compiler->cycles /* if we are debugging, call the debugger */ if ((machine().debug_flags & DEBUG_FLAG_ENABLED) != 0) { UML_MOV(block, mem(&m_core->m_pc), desc->pc); // mov [pc],desc->pc //save_fast_iregs(block); // <save fastregs> UML_DEBUG(block, desc->pc); // debug desc->pc } /* if we hit an unmapped address, fatal error */ if (desc->flags & OPFLAG_COMPILER_UNMAPPED) { UML_MOV(block, mem(&m_core->m_pc), desc->pc); // mov [pc],desc->pc save_fast_iregs(block); // <save fastregs> UML_EXIT(block, EXECUTE_UNMAPPED_CODE); // exit EXECUTE_UNMAPPED_CODE } /* unless this is a virtual no-op, it's a regular instruction */ if (!(desc->flags & OPFLAG_VIRTUAL_NOOP)) { generate_opcode(block, compiler, desc); } } void dspp_device::generate_update_cycles(drcuml_block &block, compiler_state *compiler, uml::parameter param) { /* account for cycles */ if (compiler->cycles > 0) { UML_SUB(block, mem(&m_core->m_icount), mem(&m_core->m_icount), MAPVAR_CYCLES); // sub icount,icount,cycles UML_MAPVAR(block, MAPVAR_CYCLES, 0); // mapvar cycles,0 UML_EXHc(block, COND_S, *m_out_of_cycles, param); // exh out_of_cycles,nextpc } compiler->cycles = 0; } void dspp_device::generate_opcode(drcuml_block &block, compiler_state *compiler, const opcode_desc *desc) { uint16_t op = desc->opptr.w[0]; UML_SUB(block, mem(&m_core->m_tclock), mem(&m_core->m_tclock), 1); UML_CALLC(block, cfunc_update_fifo_dma, this); if (m_drcuml.get()->logging()) block.append_comment("generate_opcode: %04x", op); code_label skip = compiler->labelnum++; UML_TEST(block, mem(&m_core->m_dspx_control), DSPX_CONTROL_GWILLING); UML_JMPc(block, COND_Z, compiler->abortlabel); //UML_TEST(block, mem(&m_core->m_flag_sleep), 1); //UML_JMPc(block, COND_NZ, compiler->abortlabel); //UML_MOV(block, mem(&m_core->m_arg0), desc->physpc); //UML_MOV(block, mem(&m_core->m_arg1), op); //UML_CALLC(block, cfunc_print_sums, this); if (op & 0x8000) { switch ((op >> 13) & 3) { case 0: generate_special_opcode(block, compiler, desc); break; case 1: case 2: generate_branch_opcode(block, compiler, desc); break; case 3: generate_complex_branch_opcode(block, compiler, desc); break; } } else { generate_arithmetic_opcode(block, compiler, desc); } UML_LABEL(block, skip); } void dspp_device::generate_set_rbase(drcuml_block &block, compiler_state *compiler, uint32_t base, uint32_t addr) { if (m_drcuml.get()->logging()) block.append_comment("set_rbase"); switch (base) { case 4: UML_MOV(block, mem(&m_core->m_rbase[1]), addr + 4 - base); break; case 0: UML_MOV(block, mem(&m_core->m_rbase[0]), addr); UML_MOV(block, mem(&m_core->m_rbase[1]), addr + 4 - base); [[fallthrough]]; case 8: UML_MOV(block, mem(&m_core->m_rbase[2]), addr + 8 - base); [[fallthrough]]; case 12: UML_MOV(block, mem(&m_core->m_rbase[3]), addr + 12 - base); break; } } void dspp_device::generate_super_special(drcuml_block &block, compiler_state *compiler, const opcode_desc *desc) { uint16_t op = desc->opptr.w[0]; uint32_t sel = (op >> 7) & 7; switch (sel) { case 1: // BAC { if (m_drcuml.get()->logging()) block.append_comment("BAC"); UML_SHR(block, mem(&m_core->m_jmpdest), mem(&m_core->m_acc), 4); // m_core->m_pc = m_core->m_acc >> 4; generate_branch(block, compiler, desc); break; } case 4: // RTS { if (m_drcuml.get()->logging()) block.append_comment("RTS"); // m_core->m_pc = m_core->m_stack[--m_core->m_stack_ptr]; UML_SUB(block, mem(&m_core->m_stack_ptr), mem(&m_core->m_stack_ptr), 1); UML_LOAD(block, mem(&m_core->m_jmpdest), (void *)m_core->m_stack, mem(&m_core->m_stack_ptr), SIZE_DWORD, SCALE_x4); generate_branch(block, compiler, desc); break; } case 5: // OP_MASK { // TODO if (m_drcuml.get()->logging()) block.append_comment("OP_MASK"); break; } case 7: // SLEEP { // TODO: How does sleep work? if (m_drcuml.get()->logging()) block.append_comment("SLEEP"); UML_SUB(block, mem(&m_core->m_pc), mem(&m_core->m_pc), 1); // --m_core->m_pc; UML_MOV(block, mem(&m_core->m_flag_sleep), 1); // m_core->m_flag_sleep = 1; break; } case 0: // NOP case 2: // Unused case 3: case 6: break; } } void dspp_device::generate_special_opcode(drcuml_block &block, compiler_state *compiler, const opcode_desc *desc) { uint16_t op = desc->opptr.w[0]; switch ((op >> 10) & 7) { case 0: { generate_super_special(block, compiler, desc); break; } case 1: // JUMP { if (m_drcuml.get()->logging()) block.append_comment("JUMP"); UML_MOV(block, mem(&m_core->m_jmpdest), op & 0x3ff); generate_branch(block, compiler, desc); break; } case 2: // JSR { if (m_drcuml.get()->logging()) block.append_comment("JSR"); UML_STORE(block, (void *)m_core->m_stack, mem(&m_core->m_stack_ptr), mem(&m_core->m_pc), SIZE_DWORD, SCALE_x4); UML_ADD(block, mem(&m_core->m_stack_ptr), mem(&m_core->m_stack_ptr), 1); UML_MOV(block, mem(&m_core->m_jmpdest), op & 0x3ff); generate_branch(block, compiler, desc); break; } case 3: // BFM { // TODO if (m_drcuml.get()->logging()) block.append_comment("BFM"); break; } case 4: // MOVEREG { if (m_drcuml.get()->logging()) block.append_comment("MOVEREG"); const uint32_t regdi = op & 0x3f; generate_translate_reg(block, regdi & 0xf); // Indirect if (regdi & 0x0010) { UML_CALLH(block, *m_dm_read16); // addr = read_data(addr); UML_MOV(block, I2, I0); } else { UML_MOV(block, I2, I1); } generate_parse_operands(block, compiler, desc, 1); generate_read_next_operand(block, compiler, desc); UML_MOV(block, I0, I1); UML_MOV(block, I1, I2); UML_CALLH(block, *m_dm_write16); // write_data(addr, read_next_operand()); break; } case 5: // RBASE { if (m_drcuml.get()->logging()) block.append_comment("RBASE"); generate_set_rbase(block, compiler, (op & 3) << 2, op & 0x3fc); break; } case 6: // MOVED { if (m_drcuml.get()->logging()) block.append_comment("MOVED"); generate_parse_operands(block, compiler, desc, 1); generate_read_next_operand(block, compiler, desc); UML_MOV(block, I0, I1); UML_MOV(block, I1, op & 0x3ff); UML_CALLH(block, *m_dm_write16); // write_data(op & 0x3ff, read_next_operand()); break; } case 7: // MOVEI { if (m_drcuml.get()->logging()) block.append_comment("MOVEI"); generate_parse_operands(block, compiler, desc, 1); UML_MOV(block, I1, op & 0x3ff); UML_CALLH(block, *m_dm_read16); // uint32_t addr = read_data(op & 0x3ff); UML_MOV(block, I2, I1); generate_read_next_operand(block, compiler, desc); UML_MOV(block, I0, I1); UML_MOV(block, I1, I2); UML_CALLH(block, *m_dm_write16); // write_data(addr, read_next_operand()); break; } default: break; } } void dspp_device::generate_branch(drcuml_block &block, compiler_state *compiler, const opcode_desc *desc) { compiler_state compiler_temp(*compiler); /* update the cycles and jump through the hash table to the target */ if (desc->targetpc != BRANCH_TARGET_DYNAMIC) { generate_update_cycles(block, &compiler_temp, desc->targetpc); // <subtract cycles> if (desc->flags & OPFLAG_INTRABLOCK_BRANCH) UML_JMP(block, desc->targetpc | 0x80000000); // jmp desc->targetpc | 0x80000000 else UML_HASHJMP(block, 0, desc->targetpc, *m_nocode); // hashjmp <mode>,desc->targetpc,nocode } else { generate_update_cycles(block, &compiler_temp, uml::mem(&m_core->m_jmpdest)); // <subtract cycles> UML_HASHJMP(block, 0, mem(&m_core->m_jmpdest), *m_nocode); // hashjmp <mode>,<rsreg>,nocode } /* update the label */ compiler->labelnum = compiler_temp.labelnum; /* reset the mapvar to the current cycles */ UML_MAPVAR(block, MAPVAR_CYCLES, compiler->cycles); // mapvar CYCLES,compiler.cycles } void dspp_device::generate_branch_opcode(drcuml_block &block, compiler_state *compiler, const opcode_desc *desc) { uint16_t op = desc->opptr.w[0]; if (m_drcuml.get()->logging()) block.append_comment("branch_opcode"); uint32_t mode = (op >> 13) & 3; uint32_t select = (op >> 12) & 1; uint32_t mask = (op >> 10) & 3; if (select == 0) { UML_MOV(block, I0, mem(&m_core->m_flag_neg)); UML_MOV(block, I1, mem(&m_core->m_flag_over)); } else { UML_MOV(block, I0, mem(&m_core->m_flag_carry)); UML_MOV(block, I1, mem(&m_core->m_flag_zero)); } //UML_MOV(block, mem(&m_core->m_arg1), I0); //UML_MOV(block, mem(&m_core->m_arg3), I1); const uint32_t mask0 = (mask & 2) ? 0 : 1; const uint32_t mask1 = (mask & 1) ? 0 : 1; UML_OR(block, I0, I0, mask0); UML_OR(block, I1, I1, mask1); UML_AND(block, I0, I0, I1); // bool branch = (flag0 || mask0) && (flag1 || mask1); if (mode == 2) // if (mode == 2) UML_SUB(block, I0, 1, I0); // branch = !branch; //UML_MOV(block, mem(&m_core->m_arg0), I0); //UML_MOV(block, mem(&m_core->m_arg2), 1-mask0); //UML_MOV(block, mem(&m_core->m_arg4), 1-mask1); //UML_CALLC(block, cfunc_print_branches, this); code_label skip = compiler->labelnum++; UML_TEST(block, I0, 1); // if (branch) UML_JMPc(block, COND_Z, skip); UML_MOV(block, mem(&m_core->m_jmpdest), op & 0x3ff); // m_core->m_pc = op & 0x3ff; generate_branch(block, compiler, desc); UML_LABEL(block, skip); } void dspp_device::generate_complex_branch_opcode(drcuml_block &block, compiler_state *compiler, const opcode_desc *desc) { uint16_t op = desc->opptr.w[0]; switch ((op >> 10) & 7) { case 0: // BLT if (m_drcuml.get()->logging()) block.append_comment("BLT"); UML_XOR(block, I0, mem(&m_core->m_flag_neg), mem(&m_core->m_flag_over)); // branch = (n && !v) || (!n && v); break; case 1: // BLE if (m_drcuml.get()->logging()) block.append_comment("BLE"); UML_XOR(block, I0, mem(&m_core->m_flag_neg), mem(&m_core->m_flag_over)); UML_OR(block, I0, I0, mem(&m_core->m_flag_zero)); // branch = ((n && !v) || (!n && v)) || z; break; case 2: // BGE if (m_drcuml.get()->logging()) block.append_comment("BGE"); UML_XOR(block, I0, mem(&m_core->m_flag_neg), mem(&m_core->m_flag_over)); UML_SUB(block, I0, 1, I0); // branch = ((n && v) || (!n && !v)); break; case 3: // BGT if (m_drcuml.get()->logging()) block.append_comment("BGT"); UML_AND(block, I0, mem(&m_core->m_flag_neg), mem(&m_core->m_flag_over)); UML_SUB(block, I0, 1, I0); UML_SUB(block, I1, 1, mem(&m_core->m_flag_zero)); UML_AND(block, I0, I0, I1); // branch = ((n && v) || (!n && !v)) && !z; break; case 4: // BHI if (m_drcuml.get()->logging()) block.append_comment("BHI"); UML_SUB(block, I0, 1, mem(&m_core->m_flag_zero)); UML_AND(block, I0, I0, mem(&m_core->m_flag_carry)); // branch = c && !z; break; case 5: // BLS if (m_drcuml.get()->logging()) block.append_comment("BLS"); UML_SUB(block, I0, 1, mem(&m_core->m_flag_carry)); UML_OR(block, I0, I0, mem(&m_core->m_flag_zero)); // branch = !c || z; break; case 6: // BXS if (m_drcuml.get()->logging()) block.append_comment("BXS"); UML_MOV(block, I0, mem(&m_core->m_flag_exact)); // branch = x; break; case 7: // BXC if (m_drcuml.get()->logging()) block.append_comment("BXC"); UML_SUB(block, I0, 1, mem(&m_core->m_flag_exact)); // branch = !x; break; } code_label skip = compiler->labelnum++; UML_TEST(block, I0, 1); // if (branch) UML_JMPc(block, COND_Z, skip); UML_MOV(block, mem(&m_core->m_jmpdest), op & 0x3ff); // m_core->m_pc = op & 0x3ff; generate_branch(block, compiler, desc); UML_LABEL(block, skip); } void dspp_device::generate_translate_reg(drcuml_block &block, uint16_t reg) { const uint32_t base = (reg >> 2) & 3; if (m_drcuml.get()->logging()) block.append_comment("translate_reg"); UML_MOV(block, I1, mem(&m_core->m_rbase[base])); UML_ADD(block, I1, I1, reg - (reg & ~3)); } void dspp_device::generate_parse_operands(drcuml_block &block, compiler_state *compiler, const opcode_desc *desc, uint32_t numops) { uint32_t addr, val = 0xBAD; uint32_t opidx = 0; uint32_t operand = 0; uint32_t numregs = 0; if (m_drcuml.get()->logging()) block.append_comment("parse_operands"); for (uint32_t i = 0; i < MAX_OPERANDS; ++i) { // Reset operands UML_DMOV(block, mem(&m_core->m_operands[i]), 0xffffffffffffffffULL); } // Reset global op index UML_MOV(block, mem(&m_core->m_opidx), 0); uint32_t opoffset = 1; while (opidx < numops) { operand = m_code_cache.read_word(desc->pc + opoffset); opoffset++; if (operand & 0x8000) { // Immediate value if ((operand & 0xc000) == 0xc000) { val = operand & 0x1fff; if (operand & 0x2000) { // Left justify val = val << 3; } else { // Sign extend if right justified if (val & 0x1000) val |= 0xe000; } UML_MOV(block, mem(&m_core->m_operands[opidx].value), val); opidx++; } else if((operand & 0xe000) == 0x8000) { // Address operand addr = operand & 0x03ff; if (operand & 0x0400) { // Indirect UML_MOV(block, I1, addr); UML_CALLH(block, *m_dm_read16); UML_MOV(block, mem(&m_core->m_operands[opidx].addr), I0); if (operand & 0x0800) { // Writeback UML_MOV(block, mem(&m_core->m_writeback), I0); } } else { UML_MOV(block, mem(&m_core->m_operands[opidx].addr), addr); if (operand & 0x0800) { // Writeback UML_MOV(block, mem(&m_core->m_writeback), addr); } } ++opidx; } else if ((operand & 0xe000) == 0xa000) { // 1 or 2 register operand numregs = (operand & 0x0400) ? 2 : 1; } } else { numregs = 3; } if (numregs > 0) { // Shift successive register operands from a single operand word for (uint32_t i = 0; i < numregs; ++i) { uint32_t shifter = ((numregs - i) - 1) * 5; uint32_t regdi = (operand >> shifter) & 0x1f; generate_translate_reg(block, regdi & 0xf); if (regdi & 0x0010) { // Indirect? UML_CALLH(block, *m_dm_read16); } if (numregs == 2) { if ((i == 0) && (operand & 0x1000)) UML_MOV(block, mem(&m_core->m_writeback), I0); else if ((i == 1) && (operand & 0x0800)) UML_MOV(block, mem(&m_core->m_writeback), I0); } else if (numregs == 1) { if (operand & 0x800) UML_MOV(block, mem(&m_core->m_writeback), I0); } UML_MOV(block, mem(&m_core->m_operands[opidx].addr), I0); opidx++; } numregs = 0; } } UML_ADD(block, mem(&m_core->m_pc), mem(&m_core->m_pc), opoffset-1); UML_SUB(block, mem(&m_core->m_tclock), mem(&m_core->m_tclock), opoffset-1); } void dspp_device::generate_read_next_operand(drcuml_block &block, compiler_state *compiler, const opcode_desc *desc) { //uint16_t op = (uint16_t)desc->opptr.w[0]; code_label no_load; if (m_drcuml.get()->logging()) block.append_comment("read_next_operand"); UML_LOAD(block, I0, (void *)&m_core->m_operands[0].value, mem(&m_core->m_opidx), SIZE_DWORD, SCALE_x8); //if (op == 0x46a0) //{ // UML_MOV(block, mem(&m_core->m_arg0), I0); // UML_CALLC(block, cfunc_print_value, this); //} UML_TEST(block, I0, 0x80000000U); UML_JMPc(block, COND_Z, no_load = compiler->labelnum++); UML_LOAD(block, I1, (void *)&m_core->m_operands[0].addr, mem(&m_core->m_opidx), SIZE_DWORD, SCALE_x8); //if (op == 0x46a0) //{ // UML_MOV(block, mem(&m_core->m_arg1), I1); //} UML_CALLH(block, *m_dm_read16); //if (op == 0x46a0) //{ // UML_MOV(block, mem(&m_core->m_arg0), I0); // UML_CALLC(block, cfunc_print_addr, this); //} UML_LABEL(block, no_load); // Next operand UML_ADD(block, mem(&m_core->m_opidx), mem(&m_core->m_opidx), 1); } void dspp_device::generate_write_next_operand(drcuml_block &block, compiler_state *compiler) { if (m_drcuml.get()->logging()) block.append_comment("write_next_operand"); // int32_t addr = m_core->m_operands[m_core->m_opidx].addr; UML_LOAD(block, I1, (void *)&m_core->m_operands[0].addr, mem(&m_core->m_opidx), SIZE_DWORD, SCALE_x8); // write_data(addr, m_core->m_acc >> 4); UML_SHR(block, I0, mem(&m_core->m_acc), 4); // Advance to the next operand UML_ADD(block, mem(&m_core->m_opidx), mem(&m_core->m_opidx), 1); } void dspp_device::generate_arithmetic_opcode(drcuml_block &block, compiler_state *compiler, const opcode_desc *desc) { uint16_t op = (uint16_t)desc->opptr.w[0]; uint32_t numops = (op >> 13) & 3; uint32_t muxa = (op >> 10) & 3; uint32_t muxb = (op >> 8) & 3; uint32_t alu_op = (op >> 4) & 0xf; uint32_t barrel_code = op & 0xf; if (m_drcuml.get()->logging()) block.append_comment("arithmetic_opcode"); // Check for operand overflow if (numops == 0 && ((muxa == 1) || (muxa == 2) || (muxb == 1) || (muxb == 2))) numops = 4; // Implicit barrel shift if (barrel_code == 8) ++numops; // Parse ops... generate_parse_operands(block, compiler, desc, numops); if (muxa == 3 || muxb == 3) { uint32_t mul_sel = (op >> 12) & 1; generate_read_next_operand(block, compiler, desc); UML_SEXT(block, I2, I2, SIZE_WORD); if (mul_sel) { generate_read_next_operand(block, compiler, desc); } else { UML_SHR(block, I0, mem(&m_core->m_acc), 4); } UML_SEXT(block, I0, I0, SIZE_WORD); UML_MULS(block, I3, I0, I0, I2); // mul_res = (op1 * op2); UML_SHR(block, I3, I3, 11); // mul_res >>= 11; } switch (muxa) { case 0: UML_MOV(block, I2, mem(&m_core->m_acc)); // alu_a = m_core->m_acc; break; case 1: case 2: generate_read_next_operand(block, compiler, desc); UML_SHL(block, I2, I0, 4); // alu_a = read_next_operand() << 4; break; case 3: { UML_MOV(block, I2, I3); // alu_a = mul_res; break; } } switch (muxb) { case 0: { UML_MOV(block, I3, mem(&m_core->m_acc)); // alu_b = m_core->m_acc; break; } case 1: case 2: { generate_read_next_operand(block, compiler, desc); UML_SHL(block, I3, I0, 4); // alu_b = read_next_operand() << 4; break; } case 3: { // alu_b = mul_res; break; } } // For carry detection apparently UML_AND(block, I2, I2, 0x000fffff); UML_AND(block, I3, I3, 0x000fffff); code_label skip_over = compiler->labelnum++; // ALU_A = I2 // ALU_B = I3 // ALU_RES = I0 switch (alu_op) { case 0: // _TRA if (m_drcuml.get()->logging()) block.append_comment("_TRA"); UML_MOV(block, I0, I2); // alu_res = alu_a; UML_MOV(block, mem(&m_core->m_flag_over), 0); // m_core->m_flag_over = 0; UML_MOV(block, mem(&m_core->m_flag_carry), 0); // m_core->m_flag_carry = 0; break; case 1: // _NEG if (m_drcuml.get()->logging()) block.append_comment("_NEG"); UML_SUB(block, I0, 0, I3); // alu_res = -alu_b; UML_MOV(block, mem(&m_core->m_flag_over), 0); // m_core->m_flag_over = 0; UML_MOV(block, mem(&m_core->m_flag_carry), 0); // m_core->m_flag_carry = 0; break; case 2: // _+ if (m_drcuml.get()->logging()) block.append_comment("_+"); UML_ADD(block, I0, I2, I3); // alu_res = alu_a + alu_b; UML_MOV(block, mem(&m_core->m_flag_over), 0); UML_XOR(block, I3, I2, I3); UML_TEST(block, I3, 0x80000); UML_JMPc(block, COND_NZ, skip_over); // if ((alu_a & 0x80000) == (alu_b & 0x80000) && UML_XOR(block, I3, I2, I0); UML_TEST(block, I3, 0x80000); // (alu_a & 0x80000) != (alu_res & 0x80000)) UML_MOVc(block, COND_NZ, mem(&m_core->m_flag_over), 1); // m_core->m_flag_over = 1; UML_LABEL(block, skip_over); UML_TEST(block, I0, 0x00100000); // if (alu_res & 0x00100000) UML_MOVc(block, COND_NZ, mem(&m_core->m_flag_carry), 1); // m_core->m_flag_carry = 1; // else UML_MOVc(block, COND_Z, mem(&m_core->m_flag_carry), 0); // m_core->m_flag_carry = 0; break; case 3: // _+C if (m_drcuml.get()->logging()) block.append_comment("_+C"); UML_SHL(block, I3, mem(&m_core->m_flag_carry), 4); UML_ADD(block, I0, I2, I3); // alu_res = alu_a + (m_core->m_flag_carry << 4); UML_MOV(block, mem(&m_core->m_flag_over), 0); // m_core->m_flag_over = 0; UML_TEST(block, I0, 0x00100000); // if (alu_res & 0x00100000) UML_MOVc(block, COND_NZ, mem(&m_core->m_flag_carry), 1); // m_core->m_flag_carry = 1; // else UML_MOVc(block, COND_Z, mem(&m_core->m_flag_carry), 0); // m_core->m_flag_carry = 0; break; case 4: // _- if (m_drcuml.get()->logging()) block.append_comment("_-"); UML_SUB(block, I0, I2, I3); // alu_res = alu_a - alu_b; UML_MOV(block, mem(&m_core->m_flag_over), 0); UML_XOR(block, I3, I3, 0xffffffffU); UML_XOR(block, I3, I2, I3); UML_TEST(block, I3, 0x80000); UML_JMPc(block, COND_NZ, skip_over); // if ((alu_a & 0x80000) == (~alu_b & 0x80000) && UML_XOR(block, I3, I2, I0); UML_TEST(block, I3, 0x80000); // (alu_a & 0x80000) != (alu_res & 0x80000)) UML_MOVc(block, COND_NZ, mem(&m_core->m_flag_over), 1); // m_core->m_flag_over = 1; UML_LABEL(block, skip_over); UML_TEST(block, I0, 0x00100000); // if (alu_res & 0x00100000) UML_MOVc(block, COND_NZ, mem(&m_core->m_flag_carry), 1); // m_core->m_flag_carry = 1; // else UML_MOVc(block, COND_Z, mem(&m_core->m_flag_carry), 0); // m_core->m_flag_carry = 0; break; case 5: // _-B if (m_drcuml.get()->logging()) block.append_comment("_-B"); UML_SHL(block, I3, mem(&m_core->m_flag_carry), 4); UML_SUB(block, I0, I2, I3); // alu_res = alu_a - (m_core->m_flag_carry << 4); UML_MOV(block, mem(&m_core->m_flag_over), 0); // m_core->m_flag_over = 0; UML_TEST(block, I0, 0x00100000); // if (alu_res & 0x00100000) UML_MOVc(block, COND_NZ, mem(&m_core->m_flag_carry), 1); // m_core->m_flag_carry = 1; // else UML_MOVc(block, COND_Z, mem(&m_core->m_flag_carry), 0); // m_core->m_flag_carry = 0; break; case 6: // _++ if (m_drcuml.get()->logging()) block.append_comment("_++"); UML_ADD(block, I0, I2, 1); // alu_res = alu_a + 1; UML_XOR(block, I3, I2, 0x80000); UML_AND(block, I3, I3, I0); UML_TEST(block, I3, 0x80000); UML_MOVc(block, COND_NZ, mem(&m_core->m_flag_over), 1); UML_MOVc(block, COND_Z, mem(&m_core->m_flag_over), 0); // m_core->m_flag_over = !(alu_a & 0x80000) && (alu_res & 0x80000); UML_MOV(block, mem(&m_core->m_flag_carry), 0); // m_core->m_flag_carry = 0; break; case 7: // _-- if (m_drcuml.get()->logging()) block.append_comment("_--"); UML_SUB(block, I0, I2, 1); // alu_res = alu_a - 1; UML_XOR(block, I3, I0, 0x80000); UML_AND(block, I3, I3, I2); UML_TEST(block, I3, 0x80000); UML_MOVc(block, COND_NZ, mem(&m_core->m_flag_over), 1); UML_MOVc(block, COND_Z, mem(&m_core->m_flag_over), 0); // m_core->m_flag_over = (alu_a & 0x80000) && !(alu_res & 0x80000); UML_MOV(block, mem(&m_core->m_flag_carry), 0); // m_core->m_flag_carry = 0; break; case 8: // _TRL if (m_drcuml.get()->logging()) block.append_comment("_TRL"); UML_MOV(block, I0, I2); // alu_res = alu_a; UML_MOV(block, mem(&m_core->m_flag_over), 0); // m_core->m_flag_over = 0; UML_MOV(block, mem(&m_core->m_flag_carry), 0); // m_core->m_flag_carry = 0; break; case 9: // _NOT if (m_drcuml.get()->logging()) block.append_comment("_NOT"); UML_XOR(block, I0, I2, 0xffffffff); // alu_res = ~alu_a; UML_MOV(block, mem(&m_core->m_flag_over), 0); // m_core->m_flag_over = 0; UML_MOV(block, mem(&m_core->m_flag_carry), 0); // m_core->m_flag_carry = 0; break; case 10: // _AND if (m_drcuml.get()->logging()) block.append_comment("_AND"); UML_AND(block, I0, I2, I3); // alu_res = alu_a & alu_b; UML_MOV(block, mem(&m_core->m_flag_over), 0); // m_core->m_flag_over = 0; UML_MOV(block, mem(&m_core->m_flag_carry), 0); // m_core->m_flag_carry = 0; break; case 11: // _NAND if (m_drcuml.get()->logging()) block.append_comment("_NAND"); UML_AND(block, I0, I2, I3); UML_XOR(block, I0, I0, 0xffffffff); // alu_res = ~(alu_a & alu_b); UML_MOV(block, mem(&m_core->m_flag_over), 0); // m_core->m_flag_over = 0; UML_MOV(block, mem(&m_core->m_flag_carry), 0); // m_core->m_flag_carry = 0; break; case 12: // _OR if (m_drcuml.get()->logging()) block.append_comment("_OR"); UML_OR(block, I0, I2, I3); // alu_res = alu_a | alu_b; UML_MOV(block, mem(&m_core->m_flag_over), 0); // m_core->m_flag_over = 0; UML_MOV(block, mem(&m_core->m_flag_carry), 0); // m_core->m_flag_carry = 0; break; case 13: // _NOR if (m_drcuml.get()->logging()) block.append_comment("_NOR"); UML_OR(block, I0, I2, I3); UML_XOR(block, I0, I0, 0xffffffff); // alu_res = ~(alu_a | alu_b); UML_MOV(block, mem(&m_core->m_flag_over), 0); // m_core->m_flag_over = 0; UML_MOV(block, mem(&m_core->m_flag_carry), 0); // m_core->m_flag_carry = 0; break; case 14: // _XOR if (m_drcuml.get()->logging()) block.append_comment("_XOR"); UML_XOR(block, I0, I2, I3); // alu_res = alu_a ^ alu_b; UML_MOV(block, mem(&m_core->m_flag_over), 0); // m_core->m_flag_over = 0; UML_MOV(block, mem(&m_core->m_flag_carry), 0); // m_core->m_flag_carry = 0; break; case 15: // _XNOR if (m_drcuml.get()->logging()) block.append_comment("_XNOR"); UML_XOR(block, I0, I2, I3); UML_XOR(block, I0, I0, 0xffffffff); // alu_res = ~(alu_a ^ alu_b); UML_MOV(block, mem(&m_core->m_flag_over), 0); // m_core->m_flag_over = 0; UML_MOV(block, mem(&m_core->m_flag_carry), 0); // m_core->m_flag_carry = 0; break; } UML_TEST(block, I0, 0x00080000); UML_MOVc(block, COND_NZ, mem(&m_core->m_flag_neg), 1); UML_MOVc(block, COND_Z, mem(&m_core->m_flag_neg), 0); // m_core->m_flag_neg = (alu_res & 0x00080000) != 0; UML_TEST(block, I0, 0x000ffff0); UML_MOVc(block, COND_Z, mem(&m_core->m_flag_zero), 1); UML_MOVc(block, COND_NZ, mem(&m_core->m_flag_zero), 0); // m_core->m_flag_zero = (alu_res & 0x000ffff0) == 0; UML_TEST(block, I0, 0x0000000f); UML_MOVc(block, COND_Z, mem(&m_core->m_flag_exact), 1); UML_MOVc(block, COND_NZ, mem(&m_core->m_flag_exact), 0); // m_core->m_flag_exact = (alu_res & 0x0000000f) == 0; // ALU_RES = I3 UML_MOV(block, I3, I0); // Barrel shift static const int32_t shifts[8] = { 0, 1, 2, 3, 4, 5, 8, 16 }; if (barrel_code == 8) generate_read_next_operand(block, compiler, desc); // I0 = barrel_code; else UML_MOV(block, I0, barrel_code); // I0 = barrel_code; code_label left_shift = compiler->labelnum++; code_label done_shift = compiler->labelnum++; code_label no_shift = compiler->labelnum++; code_label no_clip = compiler->labelnum++; code_label no_writeback = compiler->labelnum++; code_label done = compiler->labelnum++; UML_TEST(block, I0, 8); // if (barrel_code & 8) UML_JMPc(block, COND_Z, left_shift); // { UML_XOR(block, I0, I0, 0xffffffffU); UML_ADD(block, I0, I0, 1); UML_AND(block, I0, I0, 7); UML_LOAD(block, I0, (void *)shifts, I0, SIZE_DWORD, SCALE_x8); // uint32_t shift = shifts[(~barrel_code + 1) & 7]; if (alu_op < 8) // if (alu_op < 8) { // { UML_SHL(block, I3, I3, 12); UML_SAR(block, I3, I3, 12); // // Arithmetic UML_SAR(block, mem(&m_core->m_acc), I3, I0); // m_core->m_acc = sign_extend20(alu_res) >> shift; } // } else // else { // { UML_AND(block, I3, I3, 0x000fffff); // // Logical UML_SHR(block, mem(&m_core->m_acc), I3, I0); // m_core->m_acc = (alu_res & 0xfffff) >> shift; } // } UML_JMP(block, done_shift); // } UML_LABEL(block, left_shift); // else // { UML_LOAD(block, I0, (void *)shifts, I0, SIZE_DWORD, SCALE_x8); // uint32_t shift = shifts[barrel_code]; UML_CMP(block, I0, 16); // if (shift != 16) UML_JMPc(block, COND_E, no_shift); // { UML_SHL(block, I3, I3, 12); UML_SAR(block, I3, I3, 12); UML_SHL(block, mem(&m_core->m_acc), I3, I0); // m_core->m_acc = sign_extend20(alu_res) << shift; UML_JMP(block, done_shift); // } // else UML_LABEL(block, no_shift); // { UML_TEST(block, mem(&m_core->m_flag_over), 1); // // Clip and saturate UML_JMPc(block, COND_Z, no_clip); // if (m_core->m_flag_over) UML_TEST(block, mem(&m_core->m_flag_neg), 1); UML_MOVc(block, COND_NZ, mem(&m_core->m_acc), 0x7ffff); // m_core->m_acc = m_core->m_flag_neg ? 0x7ffff : 0xfff80000; UML_MOVc(block, COND_Z, mem(&m_core->m_acc), 0xfff80000); UML_JMP(block, done_shift); // else UML_LABEL(block, no_clip); UML_SHL(block, I3, I3, 12); // sign_extend20(alu_res); UML_SAR(block, mem(&m_core->m_acc), I3, 12); // } UML_LABEL(block, done_shift); // } UML_CMP(block, mem(&m_core->m_writeback), 0); // if (m_core->m_writeback >= 0) UML_JMPc(block, COND_L, no_writeback); // { UML_SHR(block, I0, mem(&m_core->m_acc), 4); UML_MOV(block, I1, mem(&m_core->m_writeback)); UML_CALLH(block, *m_dm_write16); // write_data(m_core->m_writeback, m_core->m_acc >> 4); UML_MOV(block, mem(&m_core->m_writeback), 0xffffffffU); // m_core->m_writeback = -1; UML_JMP(block, done); // } UML_LABEL(block, no_writeback); UML_CMP(block, mem(&m_core->m_opidx), numops); // else if (m_core->m_opidx < numops) UML_JMPc(block, COND_GE, done); // { generate_write_next_operand(block, compiler); // write_next_operand(m_core->m_acc >> 4); UML_LABEL(block, done); // } }
33.746257
144
0.577554
Robbbert
5ed76785dc9b3ed5ed6a9d089bcbc28b0e017326
4,797
cpp
C++
catboost/private/libs/text_features/feature_calcer.cpp
PallHaraldsson/catboost
f4b86aae0acb853f0216081518d490e52722ad88
[ "Apache-2.0" ]
null
null
null
catboost/private/libs/text_features/feature_calcer.cpp
PallHaraldsson/catboost
f4b86aae0acb853f0216081518d490e52722ad88
[ "Apache-2.0" ]
null
null
null
catboost/private/libs/text_features/feature_calcer.cpp
PallHaraldsson/catboost
f4b86aae0acb853f0216081518d490e52722ad88
[ "Apache-2.0" ]
null
null
null
#include "feature_calcer.h" #include <catboost/libs/helpers/serialization.h> #include <util/system/guard.h> namespace NCB { void TTextCalcerSerializer::Save(IOutputStream* stream, const TTextFeatureCalcer& calcer) { WriteMagic(CalcerMagic.data(), MagicSize, Alignment, stream); ::Save(stream, static_cast<ui32>(calcer.Type())); ::Save(stream, calcer); } TTextFeatureCalcerPtr TTextCalcerSerializer::Load(IInputStream* stream) { ReadMagic(CalcerMagic.data(), MagicSize, Alignment, stream); static_assert(sizeof(EFeatureCalcerType) == sizeof(ui32)); EFeatureCalcerType calcerType; ::Load(stream, calcerType); TTextFeatureCalcer* calcer = TTextFeatureCalcerFactory::Construct(calcerType); ::Load(stream, *calcer); return calcer; } void TTextFeatureCalcer::Save(IOutputStream* stream) const { flatbuffers::FlatBufferBuilder builder; TFeatureCalcerFbs anyCalcerFbs = SaveParametersToFB(builder); auto fbsGuid = CreateFbsGuid(Guid); auto calcerFbs = NCatBoostFbs::CreateTFeatureCalcer( builder, &fbsGuid, ActiveFeatureIndicesToFB(builder), anyCalcerFbs.GetCalcerType(), anyCalcerFbs.GetCalcerFlatBuffer() ); builder.Finish(calcerFbs); { ui64 bufferSize = static_cast<ui64>(builder.GetSize()); ::Save(stream, bufferSize); stream->Write(builder.GetBufferPointer(), bufferSize); } SaveLargeParameters(stream); } void TTextFeatureCalcer::Load(IInputStream* stream) { ui64 bufferSize; ::Load(stream, bufferSize); TArrayHolder<ui8> buffer = new ui8[bufferSize]; const ui64 loadedBytes = stream->Load(buffer.Get(), bufferSize); CB_ENSURE(loadedBytes == bufferSize, "Failed to deserialize: Couldn't read calcer flatbuffer"); auto calcer = flatbuffers::GetRoot<NCatBoostFbs::TFeatureCalcer>(buffer.Get()); ActiveFeatureIndices = TVector<ui32>( calcer->ActiveFeatureIndices()->begin(), calcer->ActiveFeatureIndices()->end() ); const TGuid guid = GuidFromFbs(calcer->Id()); SetId(guid); LoadParametersFromFB(calcer); LoadLargeParameters(stream); } TTextFeatureCalcer::TFeatureCalcerFbs TTextFeatureCalcer::SaveParametersToFB(flatbuffers::FlatBufferBuilder&) const { Y_FAIL("Serialization to flatbuffer is not implemented"); } void TTextFeatureCalcer::SaveLargeParameters(IOutputStream*) const { Y_FAIL("Serialization is not implemented"); } void TTextFeatureCalcer::LoadParametersFromFB(const NCatBoostFbs::TFeatureCalcer*) { Y_FAIL("Deserialization from flatbuffer is not implemented"); } void TTextFeatureCalcer::LoadLargeParameters(IInputStream*) { Y_FAIL("Deserialization is not implemented"); } flatbuffers::Offset<flatbuffers::Vector<uint32_t>> TTextFeatureCalcer::ActiveFeatureIndicesToFB(flatbuffers::FlatBufferBuilder& builder) const { return builder.CreateVector( reinterpret_cast<const uint32_t*>(ActiveFeatureIndices.data()), ActiveFeatureIndices.size() ); } void TTextFeatureCalcer::TrimFeatures(TConstArrayRef<ui32> featureIndices) { const ui32 featureCount = FeatureCount(); CB_ENSURE( featureIndices.size() <= featureCount && featureIndices.back() < featureCount, "Specified trim feature indices is greater than number of features that calcer produce" ); ActiveFeatureIndices = TVector<ui32>(featureIndices.begin(), featureIndices.end()); } ui32 TTextFeatureCalcer::FeatureCount() const { return GetActiveFeatureIndices().size(); } TConstArrayRef<ui32> TTextFeatureCalcer::GetActiveFeatureIndices() const { return MakeConstArrayRef(ActiveFeatureIndices); } TOutputFloatIterator::TOutputFloatIterator(float* data, ui64 size) : DataPtr(data) , EndPtr(data + size) , Step(1) {} TOutputFloatIterator::TOutputFloatIterator(float* data, ui64 step, ui64 size) : DataPtr(data) , EndPtr(data + size) , Step(step) {} const TOutputFloatIterator TOutputFloatIterator::operator++(int) { TOutputFloatIterator tmp(*this); operator++(); return tmp; } bool TOutputFloatIterator::IsValid() { return DataPtr < EndPtr; } TOutputFloatIterator& TOutputFloatIterator::operator++() { Y_ASSERT(IsValid()); DataPtr += Step; return *this; } float& TOutputFloatIterator::operator*() { Y_ASSERT(IsValid()); return *DataPtr; } }
33.545455
148
0.66354
PallHaraldsson
5eddaa1e4c73618c8bbf3056d1b2a275d5ad9ced
1,585
cxx
C++
kernel/mutex.cxx
SuperLeaf1995/uDOS
9c2236b14ccdc2a4c25ec5e725b8df4525bf8b96
[ "Unlicense" ]
2
2022-01-23T00:11:16.000Z
2022-01-26T22:18:01.000Z
kernel/mutex.cxx
SuperLeaf1995/uDOS
9c2236b14ccdc2a4c25ec5e725b8df4525bf8b96
[ "Unlicense" ]
null
null
null
kernel/mutex.cxx
SuperLeaf1995/uDOS
9c2236b14ccdc2a4c25ec5e725b8df4525bf8b96
[ "Unlicense" ]
2
2022-02-03T22:04:59.000Z
2022-03-26T10:51:25.000Z
export module mutex; export namespace base { typedef volatile int short atomic_int; struct mutex { enum { UNLOCKED = 0, LOCKED = 1, }; mutex(mutex& lhs) = delete; mutex(const mutex& lhs) = delete; mutex(mutex&& lhs) = delete; mutex(const mutex&& lhs) = delete; inline mutex() { // ... } inline ~mutex() { // ... } inline bool try_lock() { if(this->_lock == base::mutex::LOCKED) { return false; } this->_lock = base::mutex::LOCKED; return true; } inline void lock() { while(!this->try_lock()) { // Loop until mutex is aquired } } inline void unlock() { this->_lock = base::mutex::UNLOCKED; } atomic_int _lock = base::mutex::UNLOCKED; }; struct scoped_mutex { scoped_mutex() = delete; scoped_mutex(scoped_mutex& lhs) = delete; scoped_mutex(const scoped_mutex& lhs) = delete; scoped_mutex(scoped_mutex&& lhs) = delete; scoped_mutex(const scoped_mutex&& lhs) = delete; scoped_mutex(base::mutex& _lock) : lock{ _lock } { this->lock.lock(); } ~scoped_mutex() { this->lock.unlock(); } base::mutex& lock; }; };
22.323944
57
0.4347
SuperLeaf1995
5edf4bcab9b34cf83025786e36f24f600e164ddc
1,601
cpp
C++
menu/MenuComponent.cpp
fpeterek/arduino_menu
a854b303bfcc2b197401de3592f9a7165564b11c
[ "MIT" ]
null
null
null
menu/MenuComponent.cpp
fpeterek/arduino_menu
a854b303bfcc2b197401de3592f9a7165564b11c
[ "MIT" ]
null
null
null
menu/MenuComponent.cpp
fpeterek/arduino_menu
a854b303bfcc2b197401de3592f9a7165564b11c
[ "MIT" ]
null
null
null
// // MenuComponent.cpp // menu // // Created by Filip Peterek on 26/01/2017. // Copyright © 2017 Filip Peterek. All rights reserved. // #include "MenuComponent.hpp" void noFunction() { return; } MenuComponent::MenuComponent() { string = (char *) malloc(2 * sizeof(char)); strcpy(string, ""); setFunction(); } MenuComponent::MenuComponent(const char * newString, void (*newFunction)(void)) { string = (char *) malloc(strlen(newString) * sizeof(char)); strcpy(string, newString); setFunction(newFunction); } MenuComponent::MenuComponent(MenuComponent & mc) { const char * newStr = mc.getString(); string = (char *) malloc( strlen(newStr) * sizeof(char)); strcpy(string, newStr); setFunction(mc.getFunction()); } void MenuComponent::operator= (const MenuComponent & mc) { setString(mc.getString()); setFunction(mc.getFunction()); } void MenuComponent::operator=(const MenuComponent && mc) { operator=(mc); } MenuComponent::~MenuComponent() { free(string); string = nullptr; } void MenuComponent::setString(const char * newString) { string = (char *) realloc(string, strlen(newString)); strcpy(string, newString); } void MenuComponent::setFunction(void (*newFunction)(void)) { function = newFunction; } const char * MenuComponent::getString() const { return string; } funPtr MenuComponent::getFunction() const { return function; } void MenuComponent::call() { function(); }
17.215054
81
0.620862
fpeterek
5ee7a117d61504477aa81ee3698c1333c6fa8bef
563
cpp
C++
2.cpp
wuyongfa-genius/Algorithms_in_C-
0973fc1e2c01a818056a0f0b3bfac7a62449bc73
[ "MIT" ]
1
2021-08-17T05:22:09.000Z
2021-08-17T05:22:09.000Z
2.cpp
wuyongfa-genius/Algorithms_in_C-
0973fc1e2c01a818056a0f0b3bfac7a62449bc73
[ "MIT" ]
null
null
null
2.cpp
wuyongfa-genius/Algorithms_in_C-
0973fc1e2c01a818056a0f0b3bfac7a62449bc73
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> using namespace std; int main(){ vector<vector<double>>in={{0.0400, 0.0800, 0.1200, 0.1600, 0.2000}, {0.2400, 0.2800, 0.3200, 0.3600, 0.4000}, {0.4400, 0.4800, 0.5200, 0.5600, 0.6000}, {0.6400, 0.6800, 0.7200, 0.7600, 0.8000}, {0.8400, 0.8800, 0.9200, 0.9600, 1.0000}}; vector<vector<vector<double>>>conv_weight= {{{0.1000, 0.1000, 0.1000}, {0.1000, 0.1000, 0.1000}, {0.1000, 0.1000, 0.1000}}, {{0.2000, 0.2000, 0.2000}, {0.2000, 0.2000, 0.2000}, {0.2000, 0.2000, 0.2000}}}; }
28.15
71
0.571936
wuyongfa-genius
d67398c6c220e203a4e37e2cd80a33fd61a6d338
1,167
hpp
C++
game/code/common/game/bowlergame/gamescript/levelscript6.hpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
null
null
null
game/code/common/game/bowlergame/gamescript/levelscript6.hpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
null
null
null
game/code/common/game/bowlergame/gamescript/levelscript6.hpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
2
2019-03-08T03:02:45.000Z
2019-05-14T08:41:26.000Z
#ifndef LEVEL_SCRIPT_6_HPP #define LEVEL_SCRIPT_6_HPP ////////////////////////////////////////////////////// // INCLUDES ////////////////////////////////////////////////////// #include "common/game/bowlergame/gamescript/levelscript.hpp" ////////////////////////////////////////////////////// // FORWARD DECLARATIONS ////////////////////////////////////////////////////// ////////////////////////////////////////////////////// // CONSTANTS ////////////////////////////////////////////////////// ////////////////////////////////////////////////////// // CLASSES ////////////////////////////////////////////////////// class LevelScript6 : public LevelScript { public: LevelScript6(); ~LevelScript6(); void Initialize( const std::vector<BowlerObject*> &objects, const std::vector<BowlerObject*> &triggerObjects ); void Update( float elapsedTime, const std::vector<BowlerObject*> &objects, const std::vector<BowlerObject*> &triggerObjects ); void Reset(); private: std::vector<BowlerObject*> mToggleObjects; std::vector<BowlerObject*> mTriggerToggleObjects; char mMovingPlatformName1[32]; bool mAllTriggered; }; #endif
22.018868
60
0.456727
justinctlam
d6753cd765b808e4f5d8d9b8282128610b29230f
15,744
cc
C++
src/sepia/cluster/medoids.cc
mahmoudimus/flamingo
61b46a9f57c9aa4050b0dd8b95a44e1abef0d006
[ "Unlicense" ]
4
2018-08-23T08:05:33.000Z
2019-06-13T09:23:27.000Z
src/sepia/cluster/medoids.cc
mahmoudimus/flamingo
61b46a9f57c9aa4050b0dd8b95a44e1abef0d006
[ "Unlicense" ]
null
null
null
src/sepia/cluster/medoids.cc
mahmoudimus/flamingo
61b46a9f57c9aa4050b0dd8b95a44e1abef0d006
[ "Unlicense" ]
null
null
null
/* $Id: medoids.cc 4143 2008-12-08 23:23:55Z abehm $ Copyright (C) 2007 by The Regents of the University of California Redistribution of this file is permitted under the terms of the BSD license Date: 01/14/2006 Author: Rares Vernica <rares (at) ics.uci.edu> */ #include "medoids.h" #include <cstdlib> Medoids::Medoids(const vector<string>* d, unsigned clusterNo, SampleType sampleType, unsigned samplePer, unsigned queueSize, unsigned uniqueNo, unsigned ver, unsigned sampleSizeMul, unsigned sampleSets, unsigned sampleSteps): Clusters(d, clusterNo, sampleType, samplePer, queueSize, uniqueNo), ver(ver), sampleSizeMul(sampleSizeMul), sampleSets(sampleSets), sampleSteps(sampleSteps) { for (unsigned i = 0; i < clusterNo; i++) clusters->push_back(Cluster()); sampleSize = sampleSizeMul * clusterNo; if (sampleSize > d->size()) sampleSize = d->size(); time_t ltime; time(&ltime); srand(static_cast<unsigned int>(ltime)); } void Medoids::buildClusters() { cerr << "cluster"; cerr.flush(); switch (ver) { case 1: buildClustersVer1(); break; case 2: buildClustersVer2(); break; case 3: buildClustersVer3(); break; case 5: buildClustersVer5(); break; case 6: buildClustersVer6(); case 7: buildClustersVer7(); break; } cerr << "OK" << endl; } void Medoids::buildClustersVer1() { const unsigned dataSize = static_cast<unsigned>(data->size()); unsigned *pivot = new unsigned[clusterNo]; unsigned *pivotFinal = new unsigned[clusterNo]; unsigned *sample = new unsigned[sampleSize]; set<unsigned> *idSet = new set<unsigned>, *dataSet = new set<unsigned>; SimType minSumDist = 0; for (unsigned l = 0; l < sampleSets; l++) { cerr << '.'; cerr.flush(); // ---=== SAMPLE ===--- // select sample records for (unsigned i = 0; i < dataSize; i++) dataSet->insert(i); for (unsigned i = 0; i < sampleSize; i++) { set<unsigned>::iterator it = dataSet-> lower_bound(rand() % static_cast<unsigned>(dataSet->size())); unsigned id = *it; sample[i] = id; dataSet->erase(it); } for (unsigned k = 0; k < sampleSteps; k++){// ---=== BUILD ===--- // select random pivots idSet->clear(); for (unsigned i = 0; idSet->size() < clusterNo;) { // BUILD (select pivots) unsigned j = sample[rand()%sampleSize]; if (idSet->insert(j).second) pivot[i++] = j; } // assign each sample element to a pivot (to a cluster) and // compute the sum of dissimilarities (sum of objective functions) SimType sumDist = 0; for (unsigned i = 0; i < sampleSize; i++) { // find the best pivot SimType minDist = 0; for (unsigned j = 0; j < clusterNo; j++) { SimType dist = SimDist((*data)[sample[i]], (*data)[pivot[j]]); if (j == 0 || dist < minDist) minDist = dist; } sumDist+=minDist; } if ((l == 0 && k == 0) || sumDist < minSumDist) { minSumDist = sumDist; unsigned *pivotExtra; pivotExtra = pivotFinal; pivotFinal = pivot; pivot = pivotExtra; } } } delete dataSet; delete idSet; delete [] sample; // set final pivots as pivots for (unsigned i = 0; i < clusterNo; i++) (*clusters)[i].setPivot(pivotFinal[i]); delete [] pivotFinal; delete [] pivot; assignClusters(); } void Medoids::buildClustersVer2() { const unsigned dataSize = static_cast<unsigned>(data->size()); unsigned *pivot = new unsigned[clusterNo]; unsigned *pivotFinal = new unsigned[clusterNo]; set<unsigned> *idSet = new set<unsigned>; SimType minSumDist = 0; for (unsigned k = 0; k < sampleSteps; k++){ cerr << '.'; cerr.flush(); // ---=== BUILD ===--- // select random pivots idSet->clear(); for (unsigned i = 0; idSet->size() < clusterNo;) { // BUILD (select pivots) unsigned j = rand()%dataSize; if (idSet->insert(j).second) pivot[i++] = j; } // assign each sample element to a pivot (to a cluster) and // compute the sum of dissimilarities (sum of objective functions) SimType sumDist = 0; for (unsigned i = 0; i < dataSize; i++) { // find the best pivot SimType minDist = 0; for (unsigned j = 0; j < clusterNo; j++) { SimType dist = SimDist((*data)[i], (*data)[pivot[j]]); if (j == 0 || dist < minDist) minDist = dist; } sumDist+=minDist; } if (k == 0 || sumDist < minSumDist) { minSumDist = sumDist; unsigned *pivotExtra; pivotExtra = pivotFinal; pivotFinal = pivot; pivot = pivotExtra; } } delete idSet; // set final pivots as pivots for (unsigned i = 0; i < clusterNo; i++) (*clusters)[i].setPivot(pivotFinal[i]); delete [] pivotFinal; delete [] pivot; assignClusters(); } void Medoids::buildClustersVer3() { const unsigned dataSize = static_cast<unsigned>(data->size()); unsigned *pivot = new unsigned[clusterNo]; unsigned *pivotFinal = new unsigned[clusterNo]; unsigned *sample = new unsigned[sampleSize]; set<unsigned> *idSet = new set<unsigned>; SimType minSumDist = 0; for (unsigned k = 0; k < sampleSteps; k++){ cerr << '.'; cerr.flush(); // ---=== SAMPLE ===--- // select sample records idSet->clear(); if (k != 0) { // we already have a set of pivotFinal // add the set of pivotFinal to the sample for (unsigned i = 0; i < clusterNo; i++) { idSet->insert(pivotFinal[i]); sample[i] = pivotFinal[i]; } } for (unsigned i = idSet->size(); idSet->size() < sampleSize;) { // 1st SAMPLE unsigned j = rand()%dataSize; if (idSet->insert(j).second) sample[i++] = j; } // ---=== BUILD ===--- // idSet->clear(); // for (unsigned i = 0; i < sampleSize; i++) idSet->insert(sample[i]); // first pivot unsigned pivotId = 0; SimType minSumDistPivot = 0; for (set<unsigned>::iterator i = idSet->begin(); i != idSet->end(); i++) { SimType sumDist = 0; for (set<unsigned>::iterator j = idSet->begin(); j != idSet->end(); j++) sumDist+=SimDist((*data)[*i], (*data)[*j]); if (i == idSet->begin() || sumDist < minSumDistPivot) { pivotId = *i; minSumDistPivot = sumDist; } } pivot[0] = pivotId; // we have the first idSet->erase(pivotId); // rest of the pivots for (unsigned m = 1; m < clusterNo; m++) { SimType maxSumCji = 0; unsigned pivotId = 0; // the best unselected object - the new pivot for (set<unsigned>::iterator i = idSet->begin(); i != idSet->end(); i++) { SimType sumCji = 0; for (set<unsigned>::iterator j = idSet->begin(); j != idSet->end(); j++) { // compute Dj SimType Dj = 0; for (unsigned l = 0; l < m; l++) { SimType dist = SimDist((*data)[*j], (*data)[pivot[l]]); if (l == 0 || dist < Dj) { Dj = dist; } } // compute Cji SimType dist = SimDist((*data)[*j], (*data)[*i]); SimType Cji = Dj>dist?Dj-dist:0; // add to total sumCji+=Cji; } if (i == idSet->begin() || sumCji>maxSumCji) { maxSumCji = sumCji; pivotId = *i; } } pivot[m] = pivotId; idSet->erase(pivotId); } // assign each sample element to a pivot (to a cluster) and // compute the sum of dissimilarities (sum of objective functions) SimType sumDist = 0; for (unsigned i = 0; i < sampleSize; i++) { // find the best pivot SimType minDist = 0; for (unsigned j = 0; j < clusterNo; j++) { SimType dist = SimDist((*data)[sample[i]], (*data)[pivot[j]]); if (j == 0 || dist < minDist) minDist = dist; } sumDist+=minDist; } if (k == 0 || sumDist < minSumDist) { minSumDist = sumDist; unsigned *pivotExtra; pivotExtra = pivotFinal; pivotFinal = pivot; pivot = pivotExtra; } } delete idSet; delete [] sample; // set final pivots as pivots for (unsigned i = 0; i < clusterNo; i++) (*clusters)[i].setPivot(pivotFinal[i]); delete [] pivotFinal; delete [] pivot; assignClusters(); } void Medoids::buildClustersVer5() { const unsigned dataSize = data->size(); vector<unsigned> *pivots = new vector<unsigned>(clusterNo); SimType sumMin = 0; for (unsigned i = 0; i < dataSize; i++) { SimType sumCrt = 0; for (unsigned j = 0; j < dataSize; j++) { if (i == j) continue; sumCrt += SimDist((*data)[i], (*data)[j]); } if (i == 0 || sumCrt < sumMin) { sumMin = sumCrt; (*pivots)[0] = i; } } cerr << '.'; cerr.flush(); vector<unsigned> *assigned = new vector<unsigned>(); assigned->reserve(dataSize); vector<SimType> *distances = new vector<SimType>(); distances->reserve(dataSize); for (unsigned i = 0; i < dataSize; i++) { (*assigned)[i] = 0; (*distances)[i] = SimDist((*data)[(*pivots)[0]], (*data)[i]); } cerr << '.'; cerr.flush(); for (unsigned i = 1; i < clusterNo; i++) { SimType maxGain = 0; for (unsigned j = 0; j < dataSize; j++) { unsigned k; for (k = 0; k < i && (*pivots)[k] != j; k++); if (k != i) continue; SimType crtGain = 0; for (k = 0; k < dataSize; k++) { SimType crtDist = SimDist((*data)[j], (*data)[k]); if (crtDist < (*distances)[k]) crtGain += (*distances)[k] - crtDist; } if (crtGain > maxGain) { maxGain = crtGain; (*pivots)[i] = j; } } for (unsigned j = 0; j < dataSize; j++) { SimType newDist = SimDist((*data)[(*pivots)[i]], (*data)[j]); if (newDist < (*distances)[j]) { (*assigned)[j] = i; (*distances)[j] = newDist; } } } cerr << '.'; cerr.flush(); for (unsigned i = 0; i < clusterNo; i++) (*clusters)[i].setPivot((*pivots)[i]); for (unsigned i = 0; i < dataSize; i++) { unsigned clusterId = (*assigned)[i]; (*clusters)[clusterId].insert(i); (*clusters)[clusterId].setRadius(max((*clusters)[clusterId].getRadius(), (*distances)[i])); } delete distances; delete assigned; delete pivots; } void Medoids::buildClustersVer6() { const unsigned dataSize = data->size(); set<unsigned> *pivots = new set<unsigned>(); time_t ltime; time(&ltime); srand(static_cast<unsigned>(ltime)); while (pivots->size() < clusterNo) pivots->insert(rand() % dataSize); unsigned i = 0; for (set<unsigned>::iterator it = pivots->begin(); it != pivots->end(); ++it) (*clusters)[i++].setPivot(*it); delete pivots; assignClusters(); for (unsigned i = 0; i < sampleSteps; i++) { cerr << '.'; cerr.flush(); bool changed = false; for (VectClusterIt it = clusters->begin(); it != clusters->end(); ++it) if (it->improve(*data)) changed = true; if (changed) { for (VectClusterIt it = clusters->begin(); it != clusters->end(); ++it) it->clear(); assignClusters(); } else break; } } void Medoids::buildClustersVer7() { const unsigned dataSize = data->size(); time_t ltime; time(&ltime); srand(static_cast<unsigned>(ltime)); Sample samples = Sample(sampleSize, dataSize), pivots = Sample(clusterNo, sampleSize); unsigned i = 0; for (vector<unsigned>::const_iterator it = pivots.begin(); it != pivots.end(); ++it) (*clusters)[i++].setPivot(samples[*it]); assignClusters(samples.begin(), samples.end()); for (unsigned i = 0; i < sampleSteps; i++) { cerr << '.'; cerr.flush(); bool changed = false; for (VectClusterIt it = clusters->begin(); it != clusters->end(); ++it) if (it->improve(*data)) changed = true; if (changed) { for (VectClusterIt it = clusters->begin(); it != clusters->end(); ++it) it->clear(); assignClusters(samples.begin(), samples.end()); } else break; } assignClustersMinus(samples.begin(), samples.end()); } void Medoids::assignClusters() { const unsigned dataSize = data->size(); cerr << '.'; cerr.flush(); // assign each data element to a pivot (to a cluster) for (unsigned i = 0; i < dataSize; i++) { SimType minDist = 0; unsigned clusterI = 0; // find the best pivot for (unsigned j = 0; j < clusterNo; j++) { if (i == (*clusters)[j].getPivot()) { minDist = 0; clusterI = j; break; } SimType dist = SimDist((*data)[i], (*data)[(*clusters)[j].getPivot()]); if (j == 0 || dist < minDist) { minDist = dist; clusterI = j; } } (*clusters)[clusterI].insert(i); (*clusters)[clusterI].setRadius(max((*clusters)[clusterI].getRadius(), minDist)); } } void Medoids::assignClusters(vector<unsigned>::const_iterator begin, vector<unsigned>::const_iterator end) { cerr << '.'; cerr.flush(); // assign each data element to a pivot (to a cluster) for (vector<unsigned>::const_iterator i = begin; i != end; ++i) { SimType minDist = 0; unsigned clusterI = 0; // find the best pivot for (unsigned j = 0; j < clusterNo; j++) { if (*i == (*clusters)[j].getPivot()) { minDist = 0; clusterI = j; break; } SimType dist = SimDist((*data)[*i], (*data)[(*clusters)[j].getPivot()]); if (j == 0 || dist < minDist) { minDist = dist; clusterI = j; } } (*clusters)[clusterI].insert(*i); (*clusters)[clusterI].setRadius(max((*clusters)[clusterI].getRadius(), minDist)); } } void Medoids::assignClustersMinus(vector<unsigned>::const_iterator begin, vector<unsigned>::const_iterator end) { cerr << '.'; cerr.flush(); set<unsigned> samples = set<unsigned>(begin, end); const unsigned dataSize = data->size(); // assign each data element to a pivot (to a cluster) for (unsigned i = 0; i < dataSize; i++) { if (samples.find(i) != samples.end()) continue; SimType minDist = 0; unsigned clusterI = 0; // find the best pivot for (unsigned j = 0; j < clusterNo; j++) { if (i == (*clusters)[j].getPivot()) { minDist = 0; clusterI = j; break; } SimType dist = SimDist((*data)[i], (*data)[(*clusters)[j].getPivot()]); if (j == 0 || dist < minDist) { minDist = dist; clusterI = j; } } (*clusters)[clusterI].insert(i); (*clusters)[clusterI].setRadius(max((*clusters)[clusterI].getRadius(), minDist)); } } ostream& Medoids::info(ostream &out) { Clusters::info(out); out << "Cluster method\tMedoids " << ver << endl; out << "sample size\t" << sampleSizeMul << endl; out << "sample sets\t" << sampleSets << endl; out << "sample steps\t" << sampleSteps << endl; return out << endl; } ostream& output(ostream &out, const unsigned* p, const unsigned k, const vector<string> &d) { for (unsigned i = 0; i < k; i++) out << '[' << i << "]\t" << p[i] << "\t(" << d[p[i]] << ')' << endl; return out; } ostream& output(ostream &out, const Closest* c, const unsigned nK, const unsigned* p, const unsigned* np) { for (unsigned i = 0; i < nK; i++) out << np[i] << ":\t(" << p[c[i].d] << ',' << p[c[i].e] << ')' << endl; return out; }
27.38087
82
0.55545
mahmoudimus
d67927f1561a131ccbc566922fca8e4679197cb9
717
hpp
C++
ares/fc/fc.hpp
moon-chilled/Ares
909fb098c292f8336d0502dc677050312d8b5c81
[ "0BSD" ]
7
2020-07-25T11:44:39.000Z
2021-01-29T13:21:31.000Z
ares/fc/fc.hpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
null
null
null
ares/fc/fc.hpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
1
2021-03-22T16:15:30.000Z
2021-03-22T16:15:30.000Z
#pragma once //started: 2011-09-05 #include <ares/ares.hpp> #include <component/processor/mos6502/mos6502.hpp> #include <component/audio/ym2149/ym2149.hpp> #include <component/audio/ym2413/ym2413.hpp> #include <component/eeprom/x24c01/x24c01.hpp> namespace ares::Famicom { #include <ares/inline.hpp> struct Region { static inline auto NTSCJ() -> bool; static inline auto NTSCU() -> bool; static inline auto PAL() -> bool; }; #include <fc/controller/controller.hpp> #include <fc/system/system.hpp> #include <fc/cartridge/cartridge.hpp> #include <fc/cpu/cpu.hpp> #include <fc/apu/apu.hpp> #include <fc/ppu/ppu.hpp> #include <fc/fds/fds.hpp> } #include <fc/interface/interface.hpp>
23.9
50
0.707113
moon-chilled
d67a4821068d7a35b268da8e5e7661b7c65cd068
3,411
cpp
C++
src/hssh/local_topological/training/boosting_feature_selection.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
3
2020-03-05T23:56:14.000Z
2021-02-17T19:06:50.000Z
src/hssh/local_topological/training/boosting_feature_selection.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-07T01:23:47.000Z
2021-03-07T01:23:47.000Z
src/hssh/local_topological/training/boosting_feature_selection.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-03T07:54:16.000Z
2021-03-03T07:54:16.000Z
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ #include "hssh/local_topological/area_detection/labeling/hypothesis_features.h" #include "utils/boosting.h" #include <algorithm> #include <boost/filesystem.hpp> #include <iostream> #include <map> #include <set> void output_features_for_type(const std::string& type, const std::string& directory); int main(int argc, char** argv) { if (argc < 2) { std::cout << "Expected command-line: boosting_feature_selection <classifier dir>\n"; return -1; } output_features_for_type("path", argv[1]); output_features_for_type("decision", argv[1]); output_features_for_type("dest", argv[1]); return 0; } void output_features_for_type(const std::string& type, const std::string& directory) { using namespace boost::filesystem; using namespace vulcan; using namespace vulcan::hssh; // Iterate through the directory provided by the first command-line argument and load all classifiers // containing 'likelihood' and 'ada' // Create a set of all features used print them out, along with features not used std::map<int, double> weights; std::set<int> unusedFeatures; HypothesisFeatures allFeatures; for (int n = 0, end = allFeatures.numFeatures(); n < end; ++n) { unusedFeatures.insert(n); } utils::AdaBoostClassifier classifier; for (auto dirIt = directory_iterator(path(directory)), endIt = directory_iterator(); dirIt != endIt; ++dirIt) { auto entry = dirIt->path().generic_string(); if ((entry.find("likelihood") != std::string::npos) && (entry.find(type) != std::string::npos) && (entry.find("ada") != std::string::npos)) { if (!classifier.load(entry)) { std::cerr << "ERROR: Failed to load classifier: " << entry << '\n'; continue; } // std::cout << "Loading classifier: " << entry << '\n'; for (auto& stump : classifier) { if (weights.find(stump.featureIndex()) == weights.end()) { weights[stump.featureIndex()] = stump.weight(); } else { weights[stump.featureIndex()] += stump.weight(); } unusedFeatures.erase(stump.featureIndex()); } } } std::vector<std::pair<int, double>> usedFeatures; for (auto feature : weights) { usedFeatures.emplace_back(feature.first, feature.second); } std::sort(usedFeatures.begin(), usedFeatures.end(), [](auto lhs, auto rhs) { return lhs.second > rhs.second; }); std::cout << type << " features used by AdaBoost:\nIdx:\tName:\n"; for (auto feature : usedFeatures) { std::cout << feature.first << '\t' << feature.second << '\t' << HypothesisFeatures::featureName(feature.first) << '\n'; } std::cout << "\n\n" << type << " unused features:\nIdx:\tName:\n"; for (int idx : unusedFeatures) { std::cout << idx << '\t' << HypothesisFeatures::featureName(idx) << '\n'; } }
34.454545
118
0.61888
anuranbaka
d67acbf8f7a05b2d9fc364162a06e452d6b8c175
6,163
cpp
C++
src/gluon/app/app.cpp
cmourglia/gluon-old
9c9a55e86cd8878c0e90917882965c87c84969eb
[ "MIT" ]
null
null
null
src/gluon/app/app.cpp
cmourglia/gluon-old
9c9a55e86cd8878c0e90917882965c87c84969eb
[ "MIT" ]
null
null
null
src/gluon/app/app.cpp
cmourglia/gluon-old
9c9a55e86cd8878c0e90917882965c87c84969eb
[ "MIT" ]
2
2022-02-21T19:09:02.000Z
2022-02-21T19:09:51.000Z
#include "gluon/app/app.h" // #include "gluon/core/Utils.h" #include <SDL.h> #include <SDL_image.h> #include <beard/io/io.h> #include <nanosvg.h> #include <vector> #include "gluon/widgets/widget.h" GluonApp* GluonApp::s_instance = nullptr; GluonApp* GluonApp::instance() { return s_instance; } GluonApp::GluonApp(int argc, char** argv) : m_background_color{0.8f, 0.8f, 0.8f, 1.0f} { // TODO: Do stuff with argc, argv; UNUSED(argc); UNUSED(argv); ASSERT(s_instance == nullptr, "Multiple initializations"); if (s_instance == nullptr) { s_instance = this; // TODO: Extract window infos if set // TODO: Error handling SDL_Init(SDL_INIT_VIDEO); IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_WEBP); u32 window_flags = SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE; m_window = SDL_CreateWindow("Hey !", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1024, 768, window_flags); m_surface = SDL_GetWindowSurface(m_window); } } GluonApp::~GluonApp() { SDL_DestroyWindow(m_window); m_surface = nullptr; m_window = nullptr; IMG_Quit(); SDL_Quit(); } int GluonApp::Run() { i64 last_write_time = 0; // auto ConvertColor = [](const glm::vec4& InColor) -> Color //{ // return Color{static_cast<u8>(InColor.r * 255), // static_cast<u8>(InColor.g * 255), // static_cast<u8>(InColor.b * 255), // static_cast<u8>(InColor.a * 255)}; // }; Widget* root_widget = nullptr; bool should_quit = false; while (!should_quit) { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: should_quit = true; break; } } if (should_quit) { continue; } // Check if gluon file update is needed i64 write_time = -1; bool draw_needs_update = false; if (auto file_content = beard::io::read_while_file_if_newer( "test.gluon", last_write_time, &write_time); file_content.has_value()) { delete root_widget; root_widget = ParseGluonBuffer(file_content.value().c_str()); draw_needs_update = true; last_write_time = write_time; } if (root_widget != nullptr) { // if (IsWindowResized()) //{ // i32 w = GetScreenWidth(); // i32 h = GetScreenHeight(); // bDrawNeedsUpdate |= root_widget->WindowResized(w, h); // } // Vector2 MouseDelta = GetMouseDelta(); // if (Vector2LengthSqr(MouseDelta) > 0.0f) //{ // Vector2 MousePos = GetMousePosition(); // // bDrawNeedsUpdate |= RootWidget->MouseMoved({MousePos.x, // // MousePos.y}); //} if (draw_needs_update) { m_rectangles.clear(); Widget::Evaluate(); root_widget->BuildRenderInfos(&m_rectangles); } } // ClearBackground(ConvertColor(m_background_color)); // BeginDrawing(); //{ // for (const auto& Rect : m_rectangles) // { // Rectangle R = {Rect.Position.x, Rect.Position.y, Rect.Size.x, // Rect.Size.y}; // f32 SmallSide = beard::min(R.width, R.height); // f32 Roundness = beard::min(Rect.Radius, SmallSide) / SmallSide; // if (Rect.bIsImage) // { // if (Rect.ImageInfo->bIsVectorial) // { // NSVGshape* Shape = Rect.ImageInfo->SvgImage->shapes; // while (Shape != nullptr) // { // if ((Shape->flags & NSVG_FLAGS_VISIBLE) == 0) // { // continue; // } // Color ShapeColor = *(Color*)&Shape->stroke.color; // ShapeColor.a = u8(Shape->opacity * 255); // NSVGpath* Path = Shape->paths; // while (Path != nullptr) // { // for (int i = 0; i < Path->npts - 1; i += 3) // { // float* P = &Path->pts[i * 2]; // DrawLineBezierCubic(Vector2{P[0] + R.x, P[1] + // R.y}, // Vector2{P[6] + R.x, P[7] + // R.y}, Vector2{P[2] + R.x, // P[3] + R.y}, Vector2{P[4] // + R.x, P[5] + R.y}, // Shape->strokeWidth, // ShapeColor); // } // Path = Path->next; // } // Shape = Shape->next; // } // } // else // { // Texture2D* Texture = Rect.ImageInfo->RasterImage->Texture; // DrawTexture(*Texture, // (int)(R.x + // Rect.ImageInfo->RasterImage->OffsetX), // (int)(R.y + // Rect.ImageInfo->RasterImage->OffsetY), // ConvertColor(Rect.FillColor)); // DrawRectangleRoundedLines(R, 0, 1, 5, BLACK); // } // } // else // { // DrawRectangleRounded(R, Roundness, 32, // ConvertColor(Rect.FillColor)); // if (Rect.BorderWidth > 0.0f) // { // DrawRectangleRoundedLines(R, Roundness, 32, // Rect.BorderWidth, ConvertColor(Rect.BorderColor)); // } // } // } //} } return 0; } void GluonApp::SetTitle(const char* title) { SDL_SetWindowTitle(m_window, title); } void GluonApp::SetWindowSize(i32 w, i32 h) { SDL_SetWindowSize(m_window, w, h); m_width = w; m_height = h; }
29.917476
80
0.469252
cmourglia
d67c1099519ae718f4c37319460961db62833847
993
cc
C++
chrome/browser/ui/sync/browser_synced_tab_delegate.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
chrome/browser/ui/sync/browser_synced_tab_delegate.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
chrome/browser/ui/sync/browser_synced_tab_delegate.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// 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 "chrome/browser/ui/sync/browser_synced_tab_delegate.h" #include "chrome/browser/sync/sessions/sync_sessions_router_tab_helper.h" #include "components/sessions/content/session_tab_helper.h" BrowserSyncedTabDelegate::BrowserSyncedTabDelegate( content::WebContents* web_contents) { SetWebContents(web_contents); } BrowserSyncedTabDelegate::~BrowserSyncedTabDelegate() {} SessionID BrowserSyncedTabDelegate::GetWindowId() const { return sessions::SessionTabHelper::FromWebContents(web_contents()) ->window_id(); } SessionID BrowserSyncedTabDelegate::GetSessionId() const { return sessions::SessionTabHelper::FromWebContents(web_contents()) ->session_id(); } bool BrowserSyncedTabDelegate::IsPlaceholderTab() const { return false; } WEB_CONTENTS_USER_DATA_KEY_IMPL(BrowserSyncedTabDelegate);
31.03125
73
0.79859
zealoussnow
d67ce055c71847927406dd2e774cbd3657ab1ae1
14,896
hpp
C++
src/hadt_forward_list.hpp
gahcep/HeterogeneousList
e39a6b3ceff2423e9ed3711bbf9bff5c1e5d145f
[ "MIT" ]
null
null
null
src/hadt_forward_list.hpp
gahcep/HeterogeneousList
e39a6b3ceff2423e9ed3711bbf9bff5c1e5d145f
[ "MIT" ]
null
null
null
src/hadt_forward_list.hpp
gahcep/HeterogeneousList
e39a6b3ceff2423e9ed3711bbf9bff5c1e5d145f
[ "MIT" ]
null
null
null
#pragma once // std::bidirectional_iterator_tag, std::forward_iterator_tag, std::iterator #include <iterator> // std::out_of_range, std::length_error #include <stdexcept> // std::cout, std::endl, std::ostream #include <iostream> // std::move, std::swap, std::ptrdiff_t #include <utility> // std::is_same, std::enable_if #include <type_traits> // std::initializer_list #include <initializer_list> #include "hadt_common.hpp" namespace hadt { template <class T> class forward_list { protected: template <bool IsConst = false> class list_iterator : public std::iterator <std::forward_iterator_tag, T> { public: typedef T value_type; // T& / const T& typedef typename hadt::node_iterator_base<T, IsConst>::iterator_reference reference; // T* / const T* typedef typename hadt::node_iterator_base<T, IsConst>::iterator_pointer pointer; typedef std::ptrdiff_t difference_type; typedef std::forward_iterator_tag iterator_category; list_iterator() : ptr_{ nullptr } {}; explicit list_iterator(HNode<T> *ptr) : ptr_(ptr) {}; list_iterator(const list_iterator<IsConst>& it) : ptr_(it.ptr_) {}; list_iterator(const list_iterator<IsConst>&& it) : ptr_(std::move(it.ptr_)) {}; list_iterator<IsConst>& operator=(const list_iterator<IsConst>& it) = delete; list_iterator<IsConst>& operator=(const list_iterator<IsConst>&& it) = delete; bool operator==(const list_iterator<IsConst>& other) { return ptr_ == other.ptr_; } bool operator!=(const list_iterator<IsConst>& other) { return ptr_ != other.ptr_; } reference operator*() const { return ptr_->data; } pointer operator->() const { return &(ptr_->data); } // { return &(**this) } auto get() const -> reference { return &(ptr_->data); } auto get_node() const -> HNode<T>* { return ptr_; } auto operator++() -> list_iterator<IsConst>& { ptr_ = ptr_->next; return *this; } auto operator++(int) -> list_iterator<IsConst> { list_iterator<IsConst> it(*this); this->operator++(); return it; } private: // HNode<T> * / const HNode<T> * typename hadt::node_iterator_base<T, IsConst>::iterator_value_type_ptr ptr_; }; HNode<T> *head, *tail; HNode<T> *tail_junk; size_t size_; public: typedef std::forward_iterator_tag iterator_category; typedef list_iterator<false> iterator; typedef list_iterator<true> const_iterator; forward_list() : head{ nullptr }, tail{ nullptr }, tail_junk{ nullptr } {}; virtual ~forward_list() throw() { clear(); } // copy ctor; move ctor; copy assign; move assign forward_list(const forward_list& node) = delete; forward_list& operator=(const forward_list& node) = delete; forward_list(forward_list&& node) = delete; forward_list& operator=(forward_list&& node) = delete; iterator begin() const { return iterator(head); } iterator end() const { return iterator(tail_junk); } const_iterator cbegin() const { return const_iterator(head); } const_iterator cend() const { return const_iterator(tail_junk); } // Insert at front auto push_front(const T& data) throw() -> void; auto move_front(T&& data) throw() -> void; // Insert at back auto push_back(const T& data) throw() -> void; auto move_back(T&& data) throw() -> void; // Pop(remove) from the list auto pop_front() throw(std::length_error, std::out_of_range)->T; auto pop_back() throw(std::length_error, std::out_of_range)->T; auto pop_at(size_t idx) throw(std::length_error, std::out_of_range)->T; // Populate the list auto fill_with(std::initializer_list<T> init_list) -> void; template <class Iter, class Enable = std::enable_if< (std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::forward_iterator_tag>::value || std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::bidirectional_iterator_tag>::value || std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::random_access_iterator_tag>::value) && std::is_same<typename std::iterator_traits<Iter>::value_type, T>::value >::type> //TODO: CANNOT DEDUCE TEMPLATE ARGUMENT FOR "ENABLE" /*template <class Iter, class Enable = std::enable_if< std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::input_iterator_tag>::value && std::is_same<typename std::iterator_traits<Iter>::value_type, T>::value >::type>*/ auto fill_with(const Iter& _begin, const Iter& _end) -> void; // Append / Prepend the list auto append_with(std::initializer_list<T> append_list) -> void; auto prepend_with(std::initializer_list<T> prepend_list) -> void; template <class Iter, class Enable = std::enable_if< (std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::forward_iterator_tag>::value || std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::bidirectional_iterator_tag>::value || std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::random_access_iterator_tag>::value) && std::is_same<typename std::iterator_traits<Iter>::value_type, T>::value >::type> auto append_with(const Iter& _begin, const Iter& _end) -> void; template <class Iter, class Enable = std::enable_if< (std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::forward_iterator_tag>::value || std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::bidirectional_iterator_tag>::value || std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::random_access_iterator_tag>::value) && std::is_same<typename std::iterator_traits<Iter>::value_type, T>::value >::type> auto prepend_with(const Iter& _begin, const Iter& _end) -> void; // Find by value/by index // O(n) auto find_first(T value) const -> iterator; // O(size() - idx) auto find_nth_to_last(size_t idx) const throw(std::out_of_range) -> iterator; // Look at item in idx position auto at(size_t idx) throw(std::out_of_range) -> T; auto at_front() throw(std::out_of_range) -> T; auto at_back() throw(std::out_of_range) -> T; // Reverse the list virtual auto reverse_inplace() -> void; auto reverse(forward_list<T>& ref) -> void; // Service functions inline auto size() const -> size_t { return size_; }; inline auto empty() -> bool { return begin() == end(); }; // Print list auto print(std::ostream& ostream = std::cout) const -> std::ostream&; virtual auto print_reverse(std::ostream& ostream = std::cout) -> std::ostream&; // Clear container virtual auto clear() throw() -> void; private: // Insert HNode at front or back virtual auto _push_front(T&& data) throw() -> void; virtual auto _push_back(T&& data) throw() -> void; // Remove HNode at given position virtual auto _remove_at(size_t idx) throw(std::out_of_range) -> T; // Return HNode at given position auto _node_at(size_t idx) throw(std::out_of_range) -> HNode<T>*; }; template <class T> auto forward_list<T>::_push_front(T&& data) throw() -> void { HNode<T> *node = new HNode<T>(std::move(data)); if (nullptr == tail_junk) tail_junk = new HNode<T>(T{ 55 }, nullptr, nullptr); // Head if (nullptr != head) node->next = head; head = node; // Tail if (nullptr == tail) { tail = node; tail->next = tail_junk; } } template <class T> auto forward_list<T>::push_front(const T& data) throw() -> void { _push_front(std::move(T{ data })); size_++; } template <class T> auto forward_list<T>::move_front(T&& data) throw() -> void { _push_front(std::move(data)); size_++; } template <class T> auto forward_list<T>::_push_back(T&& data) throw() -> void { HNode<T> *node = new HNode<T>(std::move(data)); if (tail_junk == nullptr) tail_junk = new HNode<T>(T{}, nullptr, nullptr); // Tail if (nullptr != tail) tail->next = node; node->next = tail_junk; tail = node; // Head if (nullptr == head) head = node; } template <class T> auto forward_list<T>::push_back(const T& data) throw() -> void { _push_back(std::move(T{ data })); size_++; } template <class T> auto forward_list<T>::move_back(T&& data) throw() -> void { _push_back(std::move(data)); size_++; } template <class T> auto forward_list<T>::fill_with(std::initializer_list<T> init_list) -> void { clear(); append_with(init_list); } template <class T> auto forward_list<T>::append_with(std::initializer_list<T> append_list) -> void { for (auto &x : append_list) push_back(x); } template <class T> auto forward_list<T>::prepend_with(std::initializer_list<T> prepend_list) -> void { for (auto &x : prepend_list) push_front(x); } template <class T> template <class Iter, class Enable = std::enable_if< (std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::forward_iterator_tag>::value || std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::bidirectional_iterator_tag>::value || std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::random_access_iterator_tag>::value) && std::is_same<typename std::iterator_traits<Iter>::value_type, T>::value >::type> auto forward_list<T>::fill_with(const Iter& _begin, const Iter& _end) -> void { clear(); append_with(_begin, _end); } template <class T> template <class Iter, class Enable = std::enable_if< (std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::forward_iterator_tag>::value || std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::bidirectional_iterator_tag>::value || std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::random_access_iterator_tag>::value) && std::is_same<typename std::iterator_traits<Iter>::value_type, T>::value >::type> auto forward_list<T>::append_with(const Iter& _begin, const Iter& _end) -> void { auto it = _begin; while (it != _end) push_back(*it++); } template <class T> template <class Iter, class Enable = std::enable_if< (std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::forward_iterator_tag>::value || std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::bidirectional_iterator_tag>::value || std::is_same<typename std::iterator_traits<Iter>::iterator_category, std::random_access_iterator_tag>::value) && std::is_same<typename std::iterator_traits<Iter>::value_type, T>::value >::type> auto forward_list<T>::prepend_with(const Iter& _begin, const Iter& _end) -> void { auto it = _begin; while (it != _end) push_front(*it++); } template <class T> auto forward_list<T>::_node_at(size_t idx) throw(std::out_of_range) -> HNode<T>* { if (idx >= size()) throw std::out_of_range("_node_at()"); size_t cnt{}; auto it = begin(); while (idx != 0 && it++ != end() && ++cnt != idx); return it.get_node(); } template <class T> auto forward_list<T>::clear() throw() -> void { HNode<T> *tmp = head; HNode<T> *it = head; try { while (tmp != tail_junk) { tmp = it->next; delete it; it = tmp; } if (nullptr != tail_junk) delete tail_junk; head = tail = tail_junk = nullptr; size_ = 0; } catch (...) { terminate(); } } template <class T> auto forward_list<T>::_remove_at(size_t idx) throw(std::out_of_range) -> T { T val{}; if (idx >= size()) throw std::out_of_range("_remove_at()"); // At the front if (idx == 0) { val = head->data; if (size() == 1) { clear(); } else { HNode<T> * tmp = head; head = head->next; delete tmp; size_--; } } // At the back else if (idx == (size() - 1)) { val = tail->data; if (size() == 1) { clear(); } else { HNode<T> * tmp = tail; // O(n) HNode<T> * prev = _node_at(size() - 2); prev->next = tail_junk; tail = prev; delete tmp; size_--; } } // In the middle else { HNode<T> * prev = _node_at(idx - 1); HNode<T> * curr = prev->next; HNode<T> * next = curr->next; val = curr->data; prev->next = next; delete curr; size_--; } return val; } template <class T> auto forward_list<T>::pop_front() throw(std::length_error, std::out_of_range) -> T { if (empty()) throw std::length_error("list is empty"); return _remove_at(0); } template <class T> auto forward_list<T>::pop_back() throw(std::length_error, std::out_of_range) -> T { if (empty()) throw std::length_error("list is empty"); return _remove_at(size() - 1); } template <class T> auto forward_list<T>::pop_at(size_t idx) throw(std::length_error, std::out_of_range) -> T { if (empty()) throw std::length_error("list is empty"); return _remove_at(idx); } template <class T> auto forward_list<T>::at(size_t idx) throw(std::out_of_range) -> T { if (idx >= size()) throw std::out_of_range("at()"); size_t cnt{}; auto it = begin(); while (idx != 0 && it++ != end() && ++cnt != idx); return *it; } template <class T> auto forward_list<T>::at_front() throw(std::out_of_range) -> T { return at(0); } template <class T> auto forward_list<T>::at_back() throw(std::out_of_range) -> T { return at(size() - 1); } template <class T> auto forward_list<T>::find_first(T value) const -> iterator { auto it = begin(); while (*it != value && ++it != end()); return it; } template <class T> auto forward_list<T>::find_nth_to_last(size_t idx) const throw(std::out_of_range) -> iterator { if (idx >= size()) throw std::out_of_range("at()"); auto it_range_end = ++begin(); auto it_range_begin = begin(); while (it_range_end != end()) { it_range_end++; if (idx == 0) it_range_begin++; else idx--; } return it_range_begin; } template <class T> auto forward_list<T>::print(std::ostream& ostream = std::cout) const -> std::ostream& { if (size() == 0) return ostream; auto it = begin(); ostream << *it++; while (it != end()) ostream << "," << *it++; return ostream; } template <class T> auto forward_list<T>::print_reverse(std::ostream& ostream = std::cout) -> std::ostream& { if (size() == 0) return ostream; // Reverse the list forward_list temp{}; reverse(temp); temp.print(ostream); return ostream; } template <class T> auto forward_list<T>::reverse_inplace() -> void { if (empty()) return; HNode<T> * tmp{}; HNode<T> * curr = head; HNode<T> * succ = curr->next; curr->next = tail_junk; tail = curr; while (succ != tail_junk) { tmp = succ->next; succ->next = curr; curr = succ; succ = tmp; } head = curr; } template <class T> auto forward_list<T>::reverse(forward_list<T>& ref) -> void { ref.clear(); if (empty()) return; auto it = begin(); while (it != end()) { ref.push_front(*it); it++; } } }
24.951424
115
0.66058
gahcep
d67f2bb45571bc373a35179532f8fd9e2994bff9
20,207
cpp
C++
da/min/OPTI/Solvers/Source/cbcmex_old.cpp
Heliot7/open-set-da
cd3c8c9a2491dd7165259e8fde769046f735a5b8
[ "BSD-3-Clause" ]
83
2017-11-21T00:50:05.000Z
2022-03-18T00:54:25.000Z
da/min/OPTI/Solvers/Source/cbcmex_old.cpp
Heliot7/open-set-da
cd3c8c9a2491dd7165259e8fde769046f735a5b8
[ "BSD-3-Clause" ]
6
2017-11-21T00:50:44.000Z
2021-09-07T13:43:14.000Z
da/min/OPTI/Solvers/Source/cbcmex_old.cpp
Heliot7/open-set-da
cd3c8c9a2491dd7165259e8fde769046f735a5b8
[ "BSD-3-Clause" ]
15
2018-03-06T00:01:29.000Z
2021-07-28T05:18:16.000Z
/* CBCMEX - A MATLAB MEX Interface to CBC * Released Under the BSD 3-Clause License: * http://www.i2c2.aut.ac.nz/Wiki/OPTI/index.php/DL/License * * Copyright (C) Jonathan Currie 2012-2013 * www.i2c2.aut.ac.nz */ #include "mex.h" #include "Coin_C_defines.h" #include "config_clp_default.h" #include "config_cbc_default.h" #include "config_cgl_default.h" #include "config_osi_default.h" #include "config_coinutils_default.h" #include "OsiClpSolverInterface.hpp" #include "CbcModel.hpp" #include "CoinModel.hpp" #include "CoinMessageHandler.hpp" #include "CbcEventHandler.hpp" #include "CglProbing.hpp" #include "CglFlowCover.hpp" #include "CglMixedIntegerRounding2.hpp" #include "CbcHeuristic.hpp" #include "CbcHeuristicLocal.hpp" #include "CbcSOS.hpp" #include <exception> using namespace std; //Function Prototypes void printSolverInfo(); void checkInputs(const mxArray *prhs[], int nrhs); double getStatus(int stat); //Ctrl-C Detection (Undocumented - Found in gurobi_mex.c!) #ifdef __cplusplus extern "C" bool utIsInterruptPending(); extern "C" void utSetInterruptPending(bool); #else extern bool utIsInterruptPending(); extern void utSetInterruptPending(bool); #endif //Message Handler class DerivedHandler : public CoinMessageHandler { public: virtual int print() ; }; int DerivedHandler::print() { mexPrintf(messageBuffer()); mexPrintf("\n"); mexEvalString("drawnow;"); //flush draw buffer return 0; } //Ctrl-C Event Handler class DerivedEvent : public CbcEventHandler { public: virtual CbcAction event(CbcEvent whichEvent); virtual CbcEventHandler * clone() const ; }; CbcEventHandler::CbcAction DerivedEvent::event(CbcEvent whichEvent) { if (utIsInterruptPending()) { utSetInterruptPending(false); /* clear Ctrl-C status */ mexPrintf("\nCtrl-C Detected. Exiting CBC...\n\n"); return stop; //terminate asap } else return noAction; //return ok } CbcEventHandler * DerivedEvent::clone() const { return new DerivedEvent(*this); } void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]) { //Input Args double *f, *A, *rl, *ru, *lb, *ub, *H = NULL; int *ixtype; char *xtype = NULL; //Return Args double *x, *fval, *exitflag, *iter, *contobj; //Options int maxnodes = 10000, printLevel = 0, debug = 0; double maxtime = 1000, intTol = 1e-5; double objc = 0.0; //Internal Vars size_t ncon, ndec; size_t i, j, k; const double *sol; double *llb, *lub, *lrl = NULL, *lru = NULL; int ii, *rowInd, no = 0; mwIndex startRow, stopRow; char msgbuf[1024]; //Sparse Indicing mwIndex *A_ir, *A_jc; mwIndex *H_ir, *H_jc; int *rows = NULL; CoinBigIndex *cols = NULL; //SOS CbcObject ** objects; int no_sets; char *sostype; double *sosind, *soswt; int no_entries, type, *isosind; if(nrhs < 1) { if(nlhs < 1) printSolverInfo(); else plhs[0] = mxCreateString(CBC_VERSION); return; } //Check Inputs checkInputs(prhs,nrhs); //Get pointers to Input variables f = mxGetPr(prhs[0]); A = mxGetPr(prhs[1]); A_ir = mxGetIr(prhs[1]); A_jc = mxGetJc(prhs[1]); rl = mxGetPr(prhs[2]); ru = mxGetPr(prhs[3]); lb = mxGetPr(prhs[4]); ub = mxGetPr(prhs[5]); if(mxIsInt32(prhs[6])) //backwards compatibility ixtype = (int*)mxGetData(prhs[6]); else xtype = mxArrayToString(prhs[6]); if(nrhs > 9) //optional quadratic part H = mxGetPr(prhs[9]); //Get sizes ndec = mxGetM(prhs[0]); ncon = mxGetM(prhs[1]); //Get Options if Specified if(nrhs > 8) { if(mxGetField(prhs[8],0,"intTol")) intTol = *mxGetPr(mxGetField(prhs[8],0,"intTol")); if(mxGetField(prhs[8],0,"maxnodes")) maxnodes = (int)*mxGetPr(mxGetField(prhs[8],0,"maxnodes")); if(mxGetField(prhs[8],0,"maxtime")) maxtime = (int)*mxGetPr(mxGetField(prhs[8],0,"maxtime")); if(mxGetField(prhs[8],0,"display")) printLevel = (int)*mxGetPr(mxGetField(prhs[8],0,"display")); if(mxGetField(prhs[8],0,"debug")) debug = (int)*mxGetPr(mxGetField(prhs[8],0,"debug")); if(mxGetField(prhs[8],0,"objbias")) objc = *mxGetPr(mxGetField(prhs[8],0,"objbias")); } //Create Outputs plhs[0] = mxCreateDoubleMatrix(ndec,1, mxREAL); plhs[1] = mxCreateDoubleMatrix(1,1, mxREAL); plhs[2] = mxCreateDoubleMatrix(1,1, mxREAL); plhs[3] = mxCreateDoubleMatrix(1,1, mxREAL); plhs[4] = mxCreateDoubleMatrix(1,1, mxREAL); x = mxGetPr(plhs[0]); fval = mxGetPr(plhs[1]); exitflag = mxGetPr(plhs[2]); iter = mxGetPr(plhs[3]); contobj = mxGetPr(plhs[4]); try { //Objects CbcModel cbcmodel; CoinModel model; OsiClpSolverInterface OSImodel; DerivedHandler *mexprinter; DerivedEvent *ctrlCEvent; //Allocate Index Vector rowInd = (int*)mxCalloc(ncon,sizeof(int)); //set as max no of rows //Process Bounds (must copy in as we will change them) llb = (double*)mxCalloc(ndec,sizeof(double)); lub = (double*)mxCalloc(ndec,sizeof(double)); //Create bounds if empty if(mxIsEmpty(prhs[4])) { for(i=0;i<ndec;i++) llb[i] = -COIN_DBL_MAX; } else memcpy(llb,lb,ndec*sizeof(double)); if(mxIsEmpty(prhs[5])) { for(i=0;i<ndec;i++) lub[i] = COIN_DBL_MAX; } else memcpy(lub,ub,ndec*sizeof(double)); //Ensure 'finite' bounds for(i = 0; i < ndec; i++) { if(mxIsInf(llb[i])) llb[i] = -COIN_DBL_MAX; if(mxIsInf(lub[i])) lub[i] = COIN_DBL_MAX; } //Modify bounds based on binary constraints if(mxIsChar(prhs[6])) { for(ii = 0; ii < ndec; ii++) { switch(xtype[ii]) { case 'B': //Enforce binary bounds if not specified if(llb[ii] == -COIN_DBL_MAX) llb[ii] = 0; if(lub[ii] == COIN_DBL_MAX) lub[ii] = 1; break; } } } //Add Linear Constraints (Sparse) if(ncon) { for(i = 0; i < ndec; i++) { startRow = A_jc[i]; stopRow = A_jc[i+1]; no = (int)(stopRow - startRow); if(no > 0) { for(j = 0, k = startRow; k < stopRow; j++, k++) //build int32 row indicies rowInd[j] = (int)A_ir[k]; } model.addColumn(no,rowInd,&A[startRow],llb[i],lub[i],f[i]); } //Copy and process row bounds lrl = (double*)mxCalloc(ncon,sizeof(double)); lru = (double*)mxCalloc(ncon,sizeof(double)); for(i = 0; i < ncon; i++) { if(mxIsInf(rl[i])) lrl[i] = -COIN_DBL_MAX; else lrl[i] = rl[i]; if(mxIsInf(ru[i])) lru[i] = COIN_DBL_MAX; else lru[i] = ru[i]; } } else {//just bounds for(ii=0;ii<ndec;ii++) { model.setObjective(ii,f[ii]); model.setColumnBounds(ii,llb[ii],lub[ii]); } } //Add Row Bounds for (ii = 0; ii < ncon; ii++) model.setRowBounds(ii, lrl[ii], lru[ii]); //Add Objective Offset model.setObjectiveOffset(-objc); //Add Integer and Binary Constraints for(ii = 0; ii < ndec; ii++) { if(mxIsInt32(prhs[6])) { if(ixtype[ii]) model.setInteger(ii); } else { switch(xtype[ii]) { case 'C': break; case 'I': case 'B': model.setInteger(ii); break; default: throw exception("Unknown xtype, only 'C', 'I' and 'B' are accepted"); } } } //Add Quadratic Objective (can't work this out - suggestions anyone??) if(H && !mxIsEmpty(prhs[9])) { // H_ir = mxGetIr(prhs[7]); // H_jc = mxGetJc(prhs[7]); // //Convert Indicies // mwIndex nzH = H_jc[ndec]; // rows = (int*)mxCalloc(nzH,sizeof(int)); // cols = (CoinBigIndex*)mxCalloc(ndec+1,sizeof(CoinBigIndex)); // //Assign Convert Data Type Vectors // for(i = 0; i <= ndec; i++) // cols[i] = (CoinBigIndex)H_jc[i]; // for(i = 0; i < nzH; i++) // rows[i] = (int)H_ir[i]; // Load QuadObj (don't know what to do here...) // clpQuad = new ClpQuadraticObjective(f, ndec, cols, rows, H); } //Load Problem into OSI Interface OSImodel.loadFromCoinModel(model); OSImodel.setHintParam(OsiDoReducePrint,true,OsiHintTry); //prevent clp output //Load into CBC cbcmodel = CbcModel(OSImodel); //Load Cutting Generators + Heuristics (Following examples .. not really sure here!) CglProbing generator1; generator1.setUsingObjective(true); generator1.setMaxPass(1); generator1.setMaxPassRoot(5); // Number of unsatisfied variables to look at generator1.setMaxProbe(10); generator1.setMaxProbeRoot(1000); // How far to follow the consequences generator1.setMaxLook(50); generator1.setMaxLookRoot(500); // Only look at rows with fewer than this number of elements generator1.setMaxElements(200); generator1.setRowCuts(3); //Other Generators CglMixedIntegerRounding2 mixedGen; CglFlowCover flowGen; // Add in generators cbcmodel.addCutGenerator(&generator1,-1,"Probing"); cbcmodel.addCutGenerator(&flowGen,-1,"FlowCover"); cbcmodel.addCutGenerator(&mixedGen,-1,"MixedIntegerRounding"); //Heuristics CbcRounding heuristic1(cbcmodel); cbcmodel.addHeuristic(&heuristic1); CbcHeuristicLocal heuristic2(cbcmodel); cbcmodel.addHeuristic(&heuristic2); //Setup SOS if(nrhs > 7 && !mxIsEmpty(prhs[7])) { no_sets = (int)mxGetNumberOfElements(mxGetField(prhs[7],0,"type")); if(no_sets > 0) { //Collect Types sostype = mxArrayToString(mxGetField(prhs[7],0,"type")); //Allocate Set Memory objects = new CbcObject * [no_sets]; //Copy in SOS data, creating CbcSOS objects as we go for(i=0;i<no_sets;i++) { type = (int)sostype[i] - '0'; //convert to numerical representation if(type < 1 || type > 2) throw exception("Only SOS of type '1' and '2' are supported"); no_entries = (int)mxGetNumberOfElements(mxGetCell(mxGetField(prhs[7],0,"index"),i)); //Create sosind memory and copy in isosind = new int[no_entries]; sosind = mxGetPr(mxGetCell(mxGetField(prhs[7],0,"index"),i)); for(j=0;j<no_entries;j++) isosind[j] = (int)sosind[j]-1; //Get soswt soswt = mxGetPr(mxGetCell(mxGetField(prhs[7],0,"weight"),i)); //Create Set object objects[i] = new CbcSOS(&cbcmodel,no_entries,isosind,soswt,(int)i,type); delete isosind; //free memory as we go round, CoinSet copies internally } //Add objects to model cbcmodel.addObjects(no_sets,objects); //Priorities?? //Delete objects for(i=0;i<no_sets;i++) delete objects[i]; delete [] objects; //Delete type string mxFree(sostype); } } //Set Options cbcmodel.setMaximumNodes(maxnodes); cbcmodel.setMaximumSeconds(maxtime); cbcmodel.setIntegerTolerance(intTol); if(printLevel) { mexprinter = new DerivedHandler(); mexprinter->setLogLevel(0,printLevel); cbcmodel.passInMessageHandler(mexprinter); } //Add Event Handler for Ctrl+C ctrlCEvent = new DerivedEvent(); cbcmodel.passInEventHandler(ctrlCEvent); //Solve using CBC + CLP cbcmodel.initialSolve(); //relaxed LP cbcmodel.branchAndBound(); //full solve //Assign Return Arguments sol = cbcmodel.getColSolution(); if(sol != NULL) { memcpy(x,sol,ndec*sizeof(double)); *fval = cbcmodel.getObjValue(); *exitflag = getStatus(cbcmodel.secondaryStatus()); *iter = cbcmodel.getNodeCount(); *contobj = cbcmodel.getContinuousObjective(); } //Clean up memory mxFree(rowInd); mxFree(llb); mxFree(lub); if(xtype != NULL) mxFree(xtype); xtype = NULL; if(lrl != NULL) mxFree(lrl); lrl = NULL; if(lru != NULL) mxFree(lru); lru = NULL; if(printLevel) delete mexprinter; if(rows) mxFree(rows); if(cols) mxFree(cols); } //Error Handling (still crashes Matlab though...) catch(CoinError e) { sprintf(msgbuf,"Caught Coin Error: %s",e.message()); mexErrMsgTxt(msgbuf); } catch(exception& e) { sprintf(msgbuf,"Caught CBC Error: %s",e.what()); mexErrMsgTxt(msgbuf); } } //Check all inputs for size and type errors void checkInputs(const mxArray *prhs[], int nrhs) { size_t ndec, ncon; //Correct number of inputs if(nrhs < 7) mexErrMsgTxt("You must supply at least 7 arguments to cbc (f, A, rl, ru, lb, ub, xtype)"); //Check we have an objective if(mxIsEmpty(prhs[0])) mexErrMsgTxt("You must supply an objective function!"); //Check we have some constraints if(mxIsEmpty(prhs[1]) && mxIsEmpty(prhs[4]) && mxIsEmpty(prhs[5])) mexErrMsgTxt("You have not supplied any constraints!"); //Check SOS structure if(nrhs > 7 && !mxIsEmpty(prhs[7])) { if(!mxIsStruct(prhs[7])) mexErrMsgTxt("The SOS argument must be a structure!"); if(mxGetFieldNumber(prhs[7],"type") < 0) mexErrMsgTxt("The sos structure should contain the field 'type'"); if(mxGetFieldNumber(prhs[7],"index") < 0) mexErrMsgTxt("The sos structure should contain the field 'index'"); if(mxGetFieldNumber(prhs[7],"weight") < 0) mexErrMsgTxt("The sos structure should contain the field 'weight'"); //Ensure type is char array if(!mxIsChar(mxGetField(prhs[7],0,"type"))) mexErrMsgTxt("sos.type should be a char array"); //Check multiple sets length int no_sets = (int)mxGetNumberOfElements(mxGetField(prhs[7],0,"type")); if(no_sets > 1) { if(!mxIsCell(mxGetField(prhs[7],0,"index")) || mxIsEmpty(mxGetField(prhs[7],0,"index"))) mexErrMsgTxt("sos.index must be a cell array, and not empty!"); if(!mxIsCell(mxGetField(prhs[7],0,"weight")) || mxIsEmpty(mxGetField(prhs[7],0,"weight"))) mexErrMsgTxt("sos.weight must be a cell array, and not empty!"); if(mxGetNumberOfElements(mxGetField(prhs[7],0,"index")) != no_sets) mexErrMsgTxt("sos.index cell array is not the same length as sos.type!"); if(mxGetNumberOfElements(mxGetField(prhs[7],0,"weight")) != no_sets) mexErrMsgTxt("sos.weight cell array is not the same length as sos.type!"); } } //Check options is a structure with correct fields if(nrhs > 8 && !mxIsStruct(prhs[8])) mexErrMsgTxt("The options argument must be a structure!"); //Get Sizes ndec = mxGetM(prhs[0]); ncon = mxGetM(prhs[1]); //Check xtype if(mxIsEmpty(prhs[6]) || mxGetNumberOfElements(prhs[6]) < ndec || (!mxIsChar(prhs[6]) && !mxIsInt32(prhs[6]))) mexErrMsgTxt("xtype should be a char array with ndec elements"); //Check Constraint Pairs if(ncon && mxIsEmpty(prhs[2])) mexErrMsgTxt("rl is empty!"); if(ncon && mxIsEmpty(prhs[3])) mexErrMsgTxt("ru is empty!"); //Check Sparsity (only supported in A and H) if(mxIsSparse(prhs[0])) mexErrMsgTxt("Only A is a sparse matrix"); if(!mxIsSparse(prhs[1])) mexErrMsgTxt("A must be a sparse matrix"); if(nrhs > 9 && !mxIsSparse(prhs[9])) mexErrMsgTxt("H must be a sparse matrix"); //Check Orientation if(mxGetM(prhs[0]) < mxGetN(prhs[0])) mexErrMsgTxt("f must be a column vector"); if(mxGetM(prhs[2]) < mxGetN(prhs[2])) mexErrMsgTxt("rl must be a column vector"); if(mxGetM(prhs[3]) < mxGetN(prhs[3])) mexErrMsgTxt("ru must be a column vector"); if(mxGetM(prhs[4]) < mxGetN(prhs[4])) mexErrMsgTxt("lb must be a column vector"); if(mxGetM(prhs[5]) < mxGetN(prhs[5])) mexErrMsgTxt("ub must be a column vector"); //Check Sizes if(ncon) { if(mxGetN(prhs[1]) != ndec) mexErrMsgTxt("A has incompatible dimensions"); if(mxGetM(prhs[2]) != ncon) mexErrMsgTxt("rl has incompatible dimensions"); if(mxGetM(prhs[3]) != ncon) mexErrMsgTxt("ru has incompatible dimensions"); } if(!mxIsEmpty(prhs[4]) && (mxGetM(prhs[4]) != ndec)) mexErrMsgTxt("lb has incompatible dimensions"); if(!mxIsEmpty(prhs[5]) && (mxGetM(prhs[5]) != ndec)) mexErrMsgTxt("ub has incompatible dimensions"); if(nrhs > 9 && !mxIsEmpty(prhs[9]) && ((mxGetM(prhs[9]) != ndec) || (mxGetN(prhs[9]) != ndec))) mexErrMsgTxt("H has incompatible dimensions"); } //Convert exiflag to OPTI status double getStatus(int stat) { double ret = -1; switch(stat) { case 0: //looks optimal ret = 1; break; case 1: //lp relax infeasible ret = -1; break; case 2: //gap reached case 3: //max nodes case 4: //max time ret = 0; break; case 5: //user exit ret = -5; break; default: //inaccuracy / unbounded ret = -2; break; } return ret; } //Print Solver Information void printSolverInfo() { mexPrintf("\n-----------------------------------------------------------\n"); mexPrintf(" CBC: COIN-OR Branch and Cut [v%s]\n",CBC_VERSION); mexPrintf(" - Released under the Eclipse Public License: http://opensource.org/licenses/eclipse-1.0\n"); mexPrintf(" - Source available from: https://projects.coin-or.org/Cbc\n\n"); mexPrintf(" This binary is statically linked to the following software:\n"); mexPrintf(" - CGL [v%s] (Eclipse Public License)\n",CGL_VERSION); mexPrintf(" - CLP [v%s] (Eclipse Public License)\n",CLP_VERSION); mexPrintf(" - CoinUtils [v%s] (Eclipse Public License)\n",COINUTILS_VERSION); mexPrintf(" - OSI [v%s] (Eclipse Public License)\n",OSI_VERSION); mexPrintf("\n MEX Interface J.Currie 2013 (www.i2c2.aut.ac.nz)\n"); mexPrintf("-----------------------------------------------------------\n"); }
34.839655
114
0.545801
Heliot7
d680da63aa1e35fd53bd14dada1f39efa659114b
679
hpp
C++
RFGR Extended Camera/pch.hpp
Moneyl/RFGR-Extended-Camera
a68fa3a531f0be71eea0416bdd390bd1b1fa560e
[ "MIT" ]
4
2020-05-25T01:42:56.000Z
2021-01-16T19:46:50.000Z
RFGR Extended Camera/pch.hpp
Moneyl/RFGR-Extended-Camera
a68fa3a531f0be71eea0416bdd390bd1b1fa560e
[ "MIT" ]
null
null
null
RFGR Extended Camera/pch.hpp
Moneyl/RFGR-Extended-Camera
a68fa3a531f0be71eea0416bdd390bd1b1fa560e
[ "MIT" ]
null
null
null
#pragma once //Keep in mind that precompiled header use is actually disabled for the moment, since I was having issues getting them working properly. #pragma warning(push, 0) //Disable warnings on included files since I can't / won't modify them to remove warnings. #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <fstream> #include <string> #include <ctime> #include <iostream> #include <iomanip> #include <vector> #include <map> #include <ctype.h> #include <tlhelp32.h> #include <math.h> #include <Shlwapi.h> #pragma comment(lib, "Shlwapi.lib") #include <filesystem> #include <experimental/filesystem> #include <nlohmann/json.hpp> #pragma warning(pop)
26.115385
136
0.748159
Moneyl
d68582f71f2fc072e07c8f7be7c157197ab3f61b
4,887
cpp
C++
plugins/channel-safely/channel-manager.cpp
cppcooper/dfhack-cxxrandom
550ee4441473ced455ab552ccdbff77cf0978e31
[ "CC-BY-3.0" ]
null
null
null
plugins/channel-safely/channel-manager.cpp
cppcooper/dfhack-cxxrandom
550ee4441473ced455ab552ccdbff77cf0978e31
[ "CC-BY-3.0" ]
null
null
null
plugins/channel-safely/channel-manager.cpp
cppcooper/dfhack-cxxrandom
550ee4441473ced455ab552ccdbff77cf0978e31
[ "CC-BY-3.0" ]
null
null
null
#include "channel-manager.h" #include "inlines.h" #include <df/block_square_event_designation_priorityst.h> #include <LuaTools.h> #include <LuaWrapper.h> extern color_ostream* debug_out; extern bool cheat_mode; // executes dig designations for the specified tile coordinates static bool dig_now_tile(color_ostream &out, const df::coord &map_pos) { auto L = Lua::Core::State; Lua::StackUnwinder top(L); if (!lua_checkstack(L, 2) || !Lua::PushModulePublic(out, L, "plugins.dig-now", "dig_now_tile")) return false; Lua::Push(L, map_pos); if (!Lua::SafeCall(out, L, 1, 1)) return false; return lua_toboolean(L, -1); } // sets mark flags as necessary, for all designations void ChannelManager::manage_all(color_ostream &out) { if (debug_out) debug_out->print("manage_all()\n"); // make sure we've got a fort map to analyze if (World::isFortressMode() && Maps::IsValid()) { // read map / analyze designations build_groups(); // iterate the groups we built/updated for (const auto &group : groups) { if (debug_out) debug_out->print("foreach group\n"); // iterate the members of each group (designated tiles) for (auto &designation : group) { if (debug_out) debug_out->print("foreach tile\n"); // each tile has a position and a block* const df::coord &tile_pos = designation.first; df::map_block* block = designation.second; // check the safety manage_one(out, group, tile_pos, block); } } if (debug_out) debug_out->print("done managing designations\n"); } } // sets mark flags as necessary, for a single designation void ChannelManager::manage_one(color_ostream &out, const df::coord &map_pos, df::map_block* block, bool manage_neighbours) { if (!groups.count(map_pos)) { build_groups(); } auto iter = groups.find(map_pos); if (iter != groups.end()) { manage_one(out, *iter, map_pos, block); // only if asked, and if map_pos was found mapped to a group do we want to manage neighbours if (manage_neighbours) { // todo: how necessary is this? this->manage_neighbours(out, map_pos); } } } void ChannelManager::manage_one(color_ostream &out, const Group &group, const df::coord &map_pos, df::map_block* block) { // we calculate the position inside the block* df::coord local(map_pos); local.x = local.x % 16; local.y = local.y % 16; df::tile_occupancy &tile_occupancy = block->occupancy[local.x][local.y]; // ensure that we aren't on the top-most layer if(map_pos.z < mapz - 1) { // next search for the designation priority for (df::block_square_event* event : block->block_events) { if (auto evT = virtual_cast<df::block_square_event_designation_priorityst>(event)) { // todo: should we revise this check and disregard priority 1/2 or some such? // we want to let the user keep some designations free of being managed if (evT->priority[local.x][local.y] < 6000) { if (debug_out) debug_out->print("if(has_groups_above())\n"); // check that the group has no incomplete groups directly above it if (!has_groups_above(groups, group)) { tile_occupancy.bits.dig_marked = false; block->flags.bits.designated = true; } else { tile_occupancy.bits.dig_marked = true; jobs.erase_and_cancel(map_pos); //cancels job if designation is an open/active job // is it permanently unsafe? and is it safe to instantly dig the group of tiles if (cheat_mode && !is_safe_to_dig_down(map_pos) && !is_group_occupied(groups, group)) { tile_occupancy.bits.dig_marked = false; dig_now_tile(out, map_pos); } } } } } } else { // if we are though, it should be totally safe to dig tile_occupancy.bits.dig_marked = false; } } // sets mark flags as necessary, for a neighbourhood void ChannelManager::manage_neighbours(color_ostream &out, const df::coord &map_pos) { // todo: when do we actually need to manage neighbours df::coord neighbours[8]; get_neighbours(map_pos, neighbours); // for all the neighbours to our tile for (auto &position : neighbours) { // we need to ensure the position is still within the bounds of the map if (Maps::isValidTilePos(position)) { manage_one(out, position, Maps::getTileBlock(position)); } } }
41.415254
125
0.606916
cppcooper
d688e280038f673816c624e808145f579b1b157a
2,533
cpp
C++
fboss/agent/hw/test/dataplane_tests/HwInDiscardCounterTests.cpp
phshaikh/fboss
05e6ed1e9d62bf7db45a770886b1761e046c1722
[ "BSD-3-Clause" ]
1
2020-03-20T22:47:21.000Z
2020-03-20T22:47:21.000Z
fboss/agent/hw/test/dataplane_tests/HwInDiscardCounterTests.cpp
phshaikh/fboss
05e6ed1e9d62bf7db45a770886b1761e046c1722
[ "BSD-3-Clause" ]
null
null
null
fboss/agent/hw/test/dataplane_tests/HwInDiscardCounterTests.cpp
phshaikh/fboss
05e6ed1e9d62bf7db45a770886b1761e046c1722
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/hw/test/HwLinkStateDependentTest.h" #include "fboss/agent/Platform.h" #include "fboss/agent/hw/test/ConfigFactory.h" #include "fboss/agent/hw/test/HwTestPacketUtils.h" #include "fboss/agent/test/EcmpSetupHelper.h" #include "fboss/agent/state/Interface.h" #include "fboss/agent/state/SwitchState.h" using folly::IPAddress; using folly::IPAddressV6; using std::string; namespace facebook::fboss { class HwInDiscardsCounterTest : public HwLinkStateDependentTest { private: cfg::SwitchConfig initialConfig() const override { auto cfg = utility::onePortPerVlanConfig( getHwSwitch(), masterLogicalPortIds(), cfg::PortLoopbackMode::MAC); cfg.staticRoutesToNull.resize(2); cfg.staticRoutesToNull[0].routerID = cfg.staticRoutesToNull[1].routerID = 0; cfg.staticRoutesToNull[0].prefix = "0.0.0.0/0"; cfg.staticRoutesToNull[1].prefix = "::/0"; return cfg; } void pumpTraffic(bool isV6) { auto vlanId = VlanID(initialConfig().vlanPorts[0].vlanID); auto intfMac = utility::getInterfaceMac(getProgrammedState(), vlanId); auto srcIp = IPAddress(isV6 ? "1001::1" : "10.0.0.1"); auto dstIp = IPAddress(isV6 ? "100:100:100::1" : "100.100.100.1"); auto pkt = utility::makeUDPTxPacket( getHwSwitch(), VlanID(1), intfMac, intfMac, srcIp, dstIp, 10000, 10001); getHwSwitch()->sendPacketOutOfPortSync( std::move(pkt), PortID(masterLogicalPortIds()[0])); } protected: void runTest(bool isV6) { auto setup = [=]() {}; auto verify = [=]() { auto portStatsBefore = getLatestPortStats(masterLogicalPortIds()[0]); pumpTraffic(isV6); auto portStatsAfter = getLatestPortStats(masterLogicalPortIds()[0]); EXPECT_EQ( 1, portStatsAfter.inDiscardsRaw_ - portStatsBefore.inDiscardsRaw_); EXPECT_EQ( 1, portStatsAfter.inDstNullDiscards_ - portStatsBefore.inDstNullDiscards_); EXPECT_EQ(0, portStatsAfter.inDiscards_ - portStatsBefore.inDiscards_); }; verifyAcrossWarmBoots(setup, verify); } }; TEST_F(HwInDiscardsCounterTest, v6) { runTest(true); } TEST_F(HwInDiscardsCounterTest, v4) { runTest(false); } } // namespace facebook::fboss
32.896104
80
0.702724
phshaikh
d6895fc87a464aec04165fc254a2ea15e733e06f
2,198
cpp
C++
utility/fsutils.cpp
anatolse/beam
43c4ce0011598641d9cdeffbfdee66fde0a49730
[ "Apache-2.0" ]
2
2020-03-11T09:10:10.000Z
2020-04-17T13:45:08.000Z
utility/fsutils.cpp
anatolse/beam
43c4ce0011598641d9cdeffbfdee66fde0a49730
[ "Apache-2.0" ]
null
null
null
utility/fsutils.cpp
anatolse/beam
43c4ce0011598641d9cdeffbfdee66fde0a49730
[ "Apache-2.0" ]
null
null
null
// Copyright 2018 The Beam Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <boost/filesystem.hpp> #include "common.h" #include "logger.h" #include "fsutils.h" namespace beam::fsutils { bool remove(const boost::filesystem::path& path) { boost::system::error_code error; boost::filesystem::remove(path, error); if (error) LOG_ERROR() << "fsutils::remove " << path << " error: " << error.message(); return !static_cast<bool>(error); } bool remove(const std::string& spath) { #ifdef WIN32 boost::filesystem::path path(Utf8toUtf16(spath)); return fsutils::remove(path); #else boost::filesystem::path path(spath); return fsutils::remove(path); #endif } bool isExist(const std::string& path) { #ifdef WIN32 return boost::filesystem::exists(Utf8toUtf16(path.c_str())); #else return boost::filesystem::exists(path); #endif } bool rename(const boost::filesystem::path& oldPath, const boost::filesystem::path& newPath) { boost::system::error_code error; boost::filesystem::rename(oldPath, newPath, error); if (error) LOG_ERROR() << "fsutils::rename " << oldPath << " error: " << error.message(); return !static_cast<bool>(error); } bool rename(const std::string& oldPath, const std::string& newPath) { #ifdef WIN32 boost::filesystem::path fromPath(Utf8toUtf16(oldPath)); boost::filesystem::path toPath(Utf8toUtf16(newPath)); #else boost::filesystem::path fromPath(oldPath); boost::filesystem::path toPath(newPath); #endif return fsutils::rename(fromPath, toPath); } }
31.4
97
0.66424
anatolse
d68d60e836ae31e5531df8ad7cbb210367525877
1,052
cc
C++
device/usb/usb_descriptors.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-02-03T05:32:07.000Z
2019-02-03T05:32:07.000Z
device/usb/usb_descriptors.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
device/usb/usb_descriptors.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-27T11:15:39.000Z
2016-08-17T14:19:56.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "device/usb/usb_descriptors.h" namespace device { UsbEndpointDescriptor::UsbEndpointDescriptor() : address(0), direction(USB_DIRECTION_INBOUND), maximum_packet_size(0), synchronization_type(USB_SYNCHRONIZATION_NONE), transfer_type(USB_TRANSFER_CONTROL), usage_type(USB_USAGE_DATA), polling_interval(0) { } UsbEndpointDescriptor::~UsbEndpointDescriptor() { } UsbInterfaceDescriptor::UsbInterfaceDescriptor() : interface_number(0), alternate_setting(0), interface_class(0), interface_subclass(0), interface_protocol(0) { } UsbInterfaceDescriptor::~UsbInterfaceDescriptor() { } UsbConfigDescriptor::UsbConfigDescriptor() : configuration_value(0), self_powered(false), remote_wakeup(false), maximum_power(0) { } UsbConfigDescriptor::~UsbConfigDescriptor() { } } // namespace device
23.909091
73
0.730989
kjthegod
d6917a653edaec9f829f04d7520029e30008ea9c
5,018
cpp
C++
experimental/Pomdog.Experimental/Rendering/Renderer.cpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
experimental/Pomdog.Experimental/Rendering/Renderer.cpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
experimental/Pomdog.Experimental/Rendering/Renderer.cpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license. #include "Renderer.hpp" #include "RenderCommand.hpp" #include "Pomdog.Experimental/Rendering/RenderCommandProcessor.hpp" #include "Pomdog/Graphics/GraphicsCommandList.hpp" #include "Pomdog/Utility/Assert.hpp" #include <algorithm> #include <functional> #include <typeindex> #include <unordered_map> #include <utility> #include <vector> namespace Pomdog { namespace { bool CompareRenderCommands(const RenderCommand& a, const RenderCommand& b) { if (a.GetDrawOrder() == b.GetDrawOrder()) { return a.GetType() < b.GetType(); } return a.GetDrawOrder() < b.GetDrawOrder(); } } // unnamed namespace // MARK: - Renderer::Impl class Renderer::Impl { public: explicit Impl(const std::shared_ptr<GraphicsDevice>& graphicsDevice); void AddProcessor( const std::type_index& index, std::unique_ptr<RenderCommandProcessor> && processor); void Reset(); std::shared_ptr<GraphicsCommandList> Render(); void SortCommands(); public: std::unordered_map< std::type_index, std::unique_ptr<RenderCommandProcessor>> processors; std::vector<std::reference_wrapper<RenderCommand>> commands; std::shared_ptr<GraphicsCommandList> commandList; Matrix4x4 viewMatrix; Matrix4x4 projectionMatrix; int drawCallCount; bool needToSortCommandList; }; Renderer::Impl::Impl(const std::shared_ptr<GraphicsDevice>& graphicsDevice) : viewMatrix(Matrix4x4::Identity) , projectionMatrix(Matrix4x4::Identity) , drawCallCount(0) { POMDOG_ASSERT(graphicsDevice); commandList = std::make_shared<GraphicsCommandList>(graphicsDevice); } void Renderer::Impl::Reset() { commands.clear(); } void Renderer::Impl::AddProcessor( const std::type_index& index, std::unique_ptr<RenderCommandProcessor> && processor) { POMDOG_ASSERT(processor); processors.emplace(index, std::move(processor)); } void Renderer::Impl::SortCommands() { if (!needToSortCommandList) { return; } std::sort(std::begin(commands), std::end(commands), CompareRenderCommands); needToSortCommandList = false; } std::shared_ptr<GraphicsCommandList> Renderer::Impl::Render() { POMDOG_ASSERT(commandList); commandList->Reset(); drawCallCount = 0; const auto viewProjection = viewMatrix * projectionMatrix; for (auto & iter : processors) { auto & processor = iter.second; POMDOG_ASSERT(processor); processor->Begin(commandList, viewProjection); } auto prevIter = std::end(processors); SortCommands(); for (auto & command : commands) { auto iter = processors.find(command.get().GetType()); if (prevIter != iter) { if (prevIter != std::end(processors)) { auto & processor = prevIter->second; POMDOG_ASSERT(processor); processor->FlushBatch(); POMDOG_ASSERT(processor->GetDrawCallCount() >= 0); drawCallCount += processor->GetDrawCallCount(); } prevIter = iter; } POMDOG_ASSERT(prevIter == iter); if (iter == std::end(processors)) { // NOTE: If the command processor is not found, skipping rendering. continue; } POMDOG_ASSERT(iter != std::end(processors)); POMDOG_ASSERT(iter->second); auto & processor = iter->second; processor->Draw(commandList, command); } if (std::end(processors) != prevIter) { POMDOG_ASSERT(prevIter->second); auto & processor = prevIter->second; processor->End(); POMDOG_ASSERT(processor->GetDrawCallCount() >= 0); drawCallCount += processor->GetDrawCallCount(); } return commandList; } // MARK: - Renderer Renderer::Renderer(const std::shared_ptr<GraphicsDevice>& graphicsDevice) : impl(std::make_unique<Impl>(graphicsDevice)) {} Renderer::~Renderer() = default; std::shared_ptr<GraphicsCommandList> Renderer::Render() { POMDOG_ASSERT(impl); return impl->Render(); } void Renderer::PushCommand(std::reference_wrapper<RenderCommand> && command) { POMDOG_ASSERT(impl); impl->commands.push_back(std::move(command)); impl->needToSortCommandList = true; } void Renderer::SetViewMatrix(const Matrix4x4& viewMatrixIn) { POMDOG_ASSERT(impl); impl->viewMatrix = viewMatrixIn; } void Renderer::SetProjectionMatrix(const Matrix4x4& projectionMatrixIn) { POMDOG_ASSERT(impl); impl->projectionMatrix = projectionMatrixIn; } int Renderer::GetDrawCallCount() const noexcept { POMDOG_ASSERT(impl); return impl->drawCallCount; } void Renderer::Reset() { POMDOG_ASSERT(impl); impl->Reset(); } void Renderer::AddProcessor(std::unique_ptr<RenderCommandProcessor> && processor) { POMDOG_ASSERT(impl); auto typeIndex = processor->GetCommandType(); impl->AddProcessor(std::move(typeIndex), std::move(processor)); } } // namespace Pomdog
25.343434
81
0.676365
ValtoForks
d69236b2dbbfa8f1a674d34f30360b9f9f0bebb3
10,022
cpp
C++
code_reading/oceanbase-master/src/sql/engine/expr/ob_expr_to_temporal_base.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/sql/engine/expr/ob_expr_to_temporal_base.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/sql/engine/expr/ob_expr_to_temporal_base.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
1
2020-10-18T12:59:31.000Z
2020-10-18T12:59:31.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX SQL_ENG #include "sql/engine/expr/ob_expr_to_temporal_base.h" #include "sql/engine/ob_physical_plan_ctx.h" #include "sql/engine/ob_exec_context.h" #include "lib/timezone/ob_time_convert.h" namespace oceanbase { using namespace common; using namespace share; namespace sql { template <ObObjType type> int set_datum_from_ob_time(ObEvalCtx& ctx, ObTime& ob_time, ObDatum& result) { UNUSED(ctx); UNUSED(ob_time); UNUSED(result); return OB_NOT_SUPPORTED; } template <> int set_datum_from_ob_time<ObDateTimeType>(ObEvalCtx& ctx, ObTime& ob_time, ObDatum& result) { int ret = OB_SUCCESS; ObTimeConvertCtx time_cvrt_ctx(TZ_INFO(ctx.exec_ctx_.get_my_session()), false); ObDateTime result_value; OZ(ObTimeConverter::ob_time_to_datetime(ob_time, time_cvrt_ctx, result_value)); OX(result.set_datetime(result_value)); return ret; } template <> int set_datum_from_ob_time<ObTimestampNanoType>(ObEvalCtx& ctx, ObTime& ob_time, ObDatum& result) { int ret = OB_SUCCESS; UNUSED(ctx); ObOTimestampData result_value; OZ(ObTimeConverter::ob_time_to_otimestamp(ob_time, result_value)); OX(result.set_otimestamp_tiny(result_value)); return ret; } template <> int set_datum_from_ob_time<ObTimestampTZType>(ObEvalCtx& ctx, ObTime& ob_time, ObDatum& result) { int ret = OB_SUCCESS; ObTimeConvertCtx time_cvrt_ctx(TZ_INFO(ctx.exec_ctx_.get_my_session()), false); ObOTimestampData result_value; OZ(ObTimeConverter::ob_time_to_utc(ObTimestampTZType, time_cvrt_ctx, ob_time)); OZ(ObTimeConverter::ob_time_to_otimestamp(ob_time, result_value)); OX(result.set_otimestamp_tz(result_value)); return ret; } int calc_to_temporal_expr(const ObExpr& expr, ObEvalCtx& ctx, ObDatum& res_datum) { int ret = OB_SUCCESS; ObSQLSessionInfo* session = nullptr; ObDatum* input_char = nullptr; ObDatum* fmt = nullptr; ObDatum* nls_param = nullptr; ObObjType target_type = expr.datum_meta_.type_; CK(OB_NOT_NULL(session = ctx.exec_ctx_.get_my_session())); OZ(expr.args_[0]->eval(ctx, input_char)); if (expr.arg_cnt_ > 1) { OZ(expr.args_[1]->eval(ctx, fmt)); } if (expr.arg_cnt_ > 2) { OZ(expr.args_[2]->eval(ctx, nls_param)); } if (OB_SUCC(ret)) { if (input_char->is_null() || (OB_NOT_NULL(fmt) && fmt->is_null()) || (OB_NOT_NULL(nls_param) && nls_param->is_null())) { res_datum.set_null(); } else { ObString format_str; if (OB_NOT_NULL(fmt)) { format_str = fmt->get_string(); } else { OZ(session->get_local_nls_format(target_type, format_str)); } if (OB_SUCC(ret) && OB_NOT_NULL(nls_param)) { if (!ObArithExprOperator::is_valid_nls_param(nls_param->get_string())) { ret = OB_ERR_INVALID_NLS_PARAMETER_STRING; LOG_WARN("nls param is invalid", K(ret), "nls_param", nls_param->get_string()); } } ObTime ob_time; ObTimeConvertCtx time_cvrt_ctx(TZ_INFO(session), format_str, false); ObScale scale = 0; // not used OZ(ObTimeConverter::str_to_ob_time_oracle_dfm( input_char->get_string(), time_cvrt_ctx, target_type, ob_time, scale)); if (OB_SUCC(ret)) { switch (target_type) { case ObDateTimeType: OZ(set_datum_from_ob_time<ObDateTimeType>(ctx, ob_time, res_datum)); break; case ObTimestampNanoType: OZ(set_datum_from_ob_time<ObTimestampNanoType>(ctx, ob_time, res_datum)); break; case ObTimestampTZType: OZ(set_datum_from_ob_time<ObTimestampTZType>(ctx, ob_time, res_datum)); break; default: ret = OB_NOT_SUPPORTED; break; } } } } return ret; } ObExprToTemporalBase::ObExprToTemporalBase(ObIAllocator& alloc, ObExprOperatorType type, const char* name) : ObFuncExprOperator(alloc, type, name, MORE_THAN_ZERO, NOT_ROW_DIMENSION) {} int ObExprToTemporalBase::calc_result_typeN( ObExprResType& type, ObExprResType* types_array, int64_t param_num, ObExprTypeCtx& type_ctx) const { // https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions193.htm UNUSED(type_ctx); int ret = OB_SUCCESS; if (OB_UNLIKELY(param_num < 1) || OB_UNLIKELY(param_num > 3)) { ret = OB_INVALID_ARGUMENT_NUM; LOG_WARN("not enough params for function to_date", K(ret), K(param_num)); } else if (OB_ISNULL(types_array)) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), KP(types_array)); } else { ObExprResType& input_char = types_array[0]; if (OB_SUCC(ret)) { bool accept_input_type = ob_is_datetime(get_my_target_obj_type()) || input_char.is_null() || input_char.is_string_type() || input_char.is_datetime() || input_char.is_otimestamp_type(); if (OB_UNLIKELY(!accept_input_type)) { ret = OB_ERR_INVALID_TYPE_FOR_OP; LOG_WARN("inconsistent type", K(ret), K(input_char)); } else { input_char.set_calc_type_default_varchar(); } } ObExprResType& fmt = types_array[1]; if (OB_SUCC(ret) && param_num > 1) { bool accept_fmt_type = fmt.is_null() || fmt.is_string_type(); if (OB_UNLIKELY(!accept_fmt_type)) { ret = OB_ERR_INVALID_TYPE_FOR_OP; LOG_WARN("inconsistent type", K(ret), K(fmt)); } else { fmt.set_calc_type_default_varchar(); } } ObExprResType& nlsparam = types_array[2]; if (OB_SUCC(ret) && param_num > 2) { bool accept_nlsparam_type = nlsparam.is_null() || nlsparam.is_string_type(); if (OB_UNLIKELY(!accept_nlsparam_type)) { ret = OB_ERR_INVALID_TYPE_FOR_OP; LOG_WARN("inconsistent type", K(ret), K(nlsparam)); } else { nlsparam.set_calc_type_default_varchar(); } } // result type if (OB_SUCC(ret)) { if (input_char.is_null() || (param_num > 1 && fmt.is_null())) { type.set_null(); } else { type.set_type(get_my_target_obj_type()); } } // result scale if (OB_SUCC(ret)) { ObScale max_scale = ObAccuracy::MAX_ACCURACY2[ORACLE_MODE][get_my_target_obj_type()].get_scale(); ObScale result_scale = 0; if (input_char.is_null()) { // do nothing } else if (input_char.is_string_type()) { result_scale = max_scale; } else if (input_char.is_datetime() || input_char.is_otimestamp_type()) { result_scale = std::min(input_char.get_scale(), max_scale); } else if (ob_is_datetime(get_my_target_obj_type())) { result_scale = max_scale; } else { ret = OB_ERR_UNEXPECTED; LOG_WARN("unexpected type", K(ret), K(input_char)); } type.set_scale(result_scale); } } return ret; } int ObExprToTemporalBase::calc_resultN( ObObj& result, const ObObj* objs_array, int64_t param_num, ObExprCtx& expr_ctx) const { int ret = OB_SUCCESS; ObString input_str; ObString format_str; ObString nls_param_str; if (OB_UNLIKELY(param_num < 1) || OB_UNLIKELY(param_num > 3)) { ret = OB_INVALID_ARGUMENT_NUM; LOG_WARN("not enough params for function to_date", K(ret), K(param_num)); } else if (OB_ISNULL(objs_array) || OB_ISNULL(expr_ctx.my_session_)) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret), KP(objs_array), KP(expr_ctx.my_session_)); } // check params if (OB_SUCC(ret)) { if (OB_FAIL(objs_array[0].get_string(input_str))) { LOG_WARN("failed to get input string", K(ret), K(objs_array[0])); } else if (OB_FAIL((param_num > 1) ? objs_array[1].get_string(format_str) : expr_ctx.my_session_->get_local_nls_format(get_my_target_obj_type(), format_str))) { LOG_WARN("failed to get format string", K(ret), K(objs_array[1])); } else if (param_num > 2) { if (OB_FAIL(objs_array[2].get_string(nls_param_str))) { LOG_WARN("failed to get nls param string", K(ret), K(objs_array[2])); } else if (!is_valid_nls_param(nls_param_str)) { ret = OB_ERR_INVALID_NLS_PARAMETER_STRING; LOG_WARN("date format is invalid", K(ret), K(nls_param_str)); } } } // do convert if (OB_SUCC(ret)) { const ObTimeZoneInfo* tz_info = get_timezone_info(expr_ctx.my_session_); ObTime ob_time; ObTimeConvertCtx time_cvrt_ctx(tz_info, format_str, false); ObScale scale = 0; // not used if (OB_UNLIKELY(input_str.length() < 1) || OB_UNLIKELY(format_str.length() < 1)) { result.set_null(); } else if (OB_FAIL(ObTimeConverter::str_to_ob_time_oracle_dfm( input_str, time_cvrt_ctx, get_my_target_obj_type(), ob_time, scale))) { LOG_WARN("failed to convert to ob_time", K(input_str), K(format_str)); } else if (OB_FAIL(set_my_result_from_ob_time(expr_ctx, ob_time, result))) { LOG_WARN("failed to calc result from ob_time", K(ret), K(ob_time), K(input_str), K(format_str)); } else { LOG_DEBUG("to temporal succ", K(input_str), K(ob_time), K(result), K(lbt())); } } return ret; } int ObExprToTemporalBase::cg_expr(ObExprCGCtx& expr_cg_ctx, const ObRawExpr& raw_expr, ObExpr& rt_expr) const { int ret = OB_SUCCESS; UNUSED(expr_cg_ctx); UNUSED(raw_expr); int64_t param_cnt = raw_expr.get_param_count(); CK(param_cnt >= 1 && param_cnt <= 3); rt_expr.eval_func_ = calc_to_temporal_expr; return ret; } } // namespace sql } // namespace oceanbase
34.439863
113
0.675314
wangcy6
d694116e42ea4f7293c4db1780197698d435c225
6,510
cpp
C++
third_party/WebKit/Source/platform/audio/StereoPanner.cpp
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
third_party/WebKit/Source/platform/audio/StereoPanner.cpp
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
third_party/WebKit/Source/platform/audio/StereoPanner.cpp
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "platform/audio/StereoPanner.h" #include "platform/audio/AudioBus.h" #include "platform/audio/AudioUtilities.h" #include "wtf/MathExtras.h" #include <algorithm> // Use a 50ms smoothing / de-zippering time-constant. const float SmoothingTimeConstant = 0.050f; namespace blink { // Implement equal-power panning algorithm for mono or stereo input. // See: http://webaudio.github.io/web-audio-api/#panning-algorithm std::unique_ptr<StereoPanner> StereoPanner::create(float sampleRate) { return WTF::wrapUnique(new StereoPanner(sampleRate)); } StereoPanner::StereoPanner(float sampleRate) : m_isFirstRender(true), m_pan(0.0) { // Convert smoothing time (50ms) to a per-sample time value. m_smoothingConstant = AudioUtilities::discreteTimeConstantForSampleRate( SmoothingTimeConstant, sampleRate); } void StereoPanner::panWithSampleAccurateValues(const AudioBus* inputBus, AudioBus* outputBus, const float* panValues, size_t framesToProcess) { bool isInputSafe = inputBus && (inputBus->numberOfChannels() == 1 || inputBus->numberOfChannels() == 2) && framesToProcess <= inputBus->length(); ASSERT(isInputSafe); if (!isInputSafe) return; unsigned numberOfInputChannels = inputBus->numberOfChannels(); bool isOutputSafe = outputBus && outputBus->numberOfChannels() == 2 && framesToProcess <= outputBus->length(); ASSERT(isOutputSafe); if (!isOutputSafe) return; const float* sourceL = inputBus->channel(0)->data(); const float* sourceR = numberOfInputChannels > 1 ? inputBus->channel(1)->data() : sourceL; float* destinationL = outputBus->channelByType(AudioBus::ChannelLeft)->mutableData(); float* destinationR = outputBus->channelByType(AudioBus::ChannelRight)->mutableData(); if (!sourceL || !sourceR || !destinationL || !destinationR) return; double gainL, gainR, panRadian; int n = framesToProcess; if (numberOfInputChannels == 1) { // For mono source case. while (n--) { float inputL = *sourceL++; m_pan = clampTo(*panValues++, -1.0, 1.0); // Pan from left to right [-1; 1] will be normalized as [0; 1]. panRadian = (m_pan * 0.5 + 0.5) * piOverTwoDouble; gainL = std::cos(panRadian); gainR = std::sin(panRadian); *destinationL++ = static_cast<float>(inputL * gainL); *destinationR++ = static_cast<float>(inputL * gainR); } } else { // For stereo source case. while (n--) { float inputL = *sourceL++; float inputR = *sourceR++; m_pan = clampTo(*panValues++, -1.0, 1.0); // Normalize [-1; 0] to [0; 1]. Do nothing when [0; 1]. panRadian = (m_pan <= 0 ? m_pan + 1 : m_pan) * piOverTwoDouble; gainL = std::cos(panRadian); gainR = std::sin(panRadian); if (m_pan <= 0) { *destinationL++ = static_cast<float>(inputL + inputR * gainL); *destinationR++ = static_cast<float>(inputR * gainR); } else { *destinationL++ = static_cast<float>(inputL * gainL); *destinationR++ = static_cast<float>(inputR + inputL * gainR); } } } } void StereoPanner::panToTargetValue(const AudioBus* inputBus, AudioBus* outputBus, float panValue, size_t framesToProcess) { bool isInputSafe = inputBus && (inputBus->numberOfChannels() == 1 || inputBus->numberOfChannels() == 2) && framesToProcess <= inputBus->length(); ASSERT(isInputSafe); if (!isInputSafe) return; unsigned numberOfInputChannels = inputBus->numberOfChannels(); bool isOutputSafe = outputBus && outputBus->numberOfChannels() == 2 && framesToProcess <= outputBus->length(); ASSERT(isOutputSafe); if (!isOutputSafe) return; const float* sourceL = inputBus->channel(0)->data(); const float* sourceR = numberOfInputChannels > 1 ? inputBus->channel(1)->data() : sourceL; float* destinationL = outputBus->channelByType(AudioBus::ChannelLeft)->mutableData(); float* destinationR = outputBus->channelByType(AudioBus::ChannelRight)->mutableData(); if (!sourceL || !sourceR || !destinationL || !destinationR) return; float targetPan = clampTo(panValue, -1.0, 1.0); // Don't de-zipper on first render call. if (m_isFirstRender) { m_isFirstRender = false; m_pan = targetPan; } double gainL, gainR, panRadian; const double smoothingConstant = m_smoothingConstant; int n = framesToProcess; if (numberOfInputChannels == 1) { // For mono source case. while (n--) { float inputL = *sourceL++; m_pan += (targetPan - m_pan) * smoothingConstant; // Pan from left to right [-1; 1] will be normalized as [0; 1]. panRadian = (m_pan * 0.5 + 0.5) * piOverTwoDouble; gainL = std::cos(panRadian); gainR = std::sin(panRadian); *destinationL++ = static_cast<float>(inputL * gainL); *destinationR++ = static_cast<float>(inputL * gainR); } } else { // For stereo source case. while (n--) { float inputL = *sourceL++; float inputR = *sourceR++; m_pan += (targetPan - m_pan) * smoothingConstant; // Normalize [-1; 0] to [0; 1] for the left pan position (<= 0), and // do nothing when [0; 1]. panRadian = (m_pan <= 0 ? m_pan + 1 : m_pan) * piOverTwoDouble; gainL = std::cos(panRadian); gainR = std::sin(panRadian); // The pan value should be checked every sample when de-zippering. // See crbug.com/470559. if (m_pan <= 0) { // When [-1; 0], keep left channel intact and equal-power pan the // right channel only. *destinationL++ = static_cast<float>(inputL + inputR * gainL); *destinationR++ = static_cast<float>(inputR * gainR); } else { // When [0; 1], keep right channel intact and equal-power pan the // left channel only. *destinationL++ = static_cast<float>(inputL * gainL); *destinationR++ = static_cast<float>(inputR + inputL * gainR); } } } } } // namespace blink
35.769231
74
0.615975
google-ar
d69526bacc874b51045fc26db91ebeb35ae36f94
12,135
cpp
C++
Engine/Source/Runtime/AnimGraphRuntime/Private/BoneControllers/AnimNode_Fabrik.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/AnimGraphRuntime/Private/BoneControllers/AnimNode_Fabrik.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/AnimGraphRuntime/Private/BoneControllers/AnimNode_Fabrik.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "BoneControllers/AnimNode_Fabrik.h" #include "AnimationRuntime.h" #include "Components/SkeletalMeshComponent.h" #include "DrawDebugHelpers.h" #include "Animation/AnimInstanceProxy.h" ///////////////////////////////////////////////////// // AnimNode_Fabrik // Implementation of the FABRIK IK Algorithm // Please see http://www.academia.edu/9165835/FABRIK_A_fast_iterative_solver_for_the_Inverse_Kinematics_problem for more details FAnimNode_Fabrik::FAnimNode_Fabrik() : EffectorTransform(FTransform::Identity) , EffectorTransformSpace(BCS_ComponentSpace) , EffectorRotationSource(BRS_KeepLocalSpaceRotation) , Precision(1.f) , MaxIterations(10) , bEnableDebugDraw(false) { } FVector FAnimNode_Fabrik::GetCurrentLocation(FCSPose<FCompactPose>& MeshBases, const FCompactPoseBoneIndex& BoneIndex) { return MeshBases.GetComponentSpaceTransform(BoneIndex).GetLocation(); } FTransform FAnimNode_Fabrik::GetTargetTransform(const FTransform& InComponentTransform, FCSPose<FCompactPose>& MeshBases, FBoneSocketTarget& InTarget, EBoneControlSpace Space, const FTransform& InOffset) { FTransform OutTransform; if (Space == BCS_BoneSpace) { OutTransform = InTarget.GetTargetTransform(InOffset, MeshBases, InComponentTransform); } else { // parent bone space still goes through this way // if your target is socket, it will try find parents of joint that socket belongs to OutTransform = InOffset; FAnimationRuntime::ConvertBoneSpaceTransformToCS(InComponentTransform, MeshBases, OutTransform, InTarget.GetCompactPoseBoneIndex(), Space); } return OutTransform; } void FAnimNode_Fabrik::EvaluateSkeletalControl_AnyThread(FComponentSpacePoseContext& Output, TArray<FBoneTransform>& OutBoneTransforms) { const FBoneContainer& BoneContainer = Output.Pose.GetPose().GetBoneContainer(); // Update EffectorLocation if it is based off a bone position FTransform CSEffectorTransform = EffectorTransform; CSEffectorTransform = GetTargetTransform(Output.AnimInstanceProxy->GetComponentTransform(), Output.Pose, EffectorTarget, EffectorTransformSpace, EffectorTransform); FVector const CSEffectorLocation = CSEffectorTransform.GetLocation(); #if WITH_EDITOR CachedEffectorCSTransform = CSEffectorTransform; #endif // Gather all bone indices between root and tip. TArray<FCompactPoseBoneIndex> BoneIndices; { const FCompactPoseBoneIndex RootIndex = RootBone.GetCompactPoseIndex(BoneContainer); FCompactPoseBoneIndex BoneIndex = TipBone.GetCompactPoseIndex(BoneContainer); do { BoneIndices.Insert(BoneIndex, 0); BoneIndex = Output.Pose.GetPose().GetParentBoneIndex(BoneIndex); } while (BoneIndex != RootIndex); BoneIndices.Insert(BoneIndex, 0); } // Maximum length of skeleton segment at full extension float MaximumReach = 0; // Gather transforms int32 const NumTransforms = BoneIndices.Num(); OutBoneTransforms.AddUninitialized(NumTransforms); // Gather chain links. These are non zero length bones. TArray<FABRIKChainLink> Chain; Chain.Reserve(NumTransforms); // Start with Root Bone { const FCompactPoseBoneIndex& RootBoneIndex = BoneIndices[0]; const FTransform& BoneCSTransform = Output.Pose.GetComponentSpaceTransform(RootBoneIndex); OutBoneTransforms[0] = FBoneTransform(RootBoneIndex, BoneCSTransform); Chain.Add(FABRIKChainLink(BoneCSTransform.GetLocation(), 0.f, RootBoneIndex, 0)); } // Go through remaining transforms for (int32 TransformIndex = 1; TransformIndex < NumTransforms; TransformIndex++) { const FCompactPoseBoneIndex& BoneIndex = BoneIndices[TransformIndex]; const FTransform& BoneCSTransform = Output.Pose.GetComponentSpaceTransform(BoneIndex); FVector const BoneCSPosition = BoneCSTransform.GetLocation(); OutBoneTransforms[TransformIndex] = FBoneTransform(BoneIndex, BoneCSTransform); // Calculate the combined length of this segment of skeleton float const BoneLength = FVector::Dist(BoneCSPosition, OutBoneTransforms[TransformIndex-1].Transform.GetLocation()); if (!FMath::IsNearlyZero(BoneLength)) { Chain.Add(FABRIKChainLink(BoneCSPosition, BoneLength, BoneIndex, TransformIndex)); MaximumReach += BoneLength; } else { // Mark this transform as a zero length child of the last link. // It will inherit position and delta rotation from parent link. FABRIKChainLink & ParentLink = Chain[Chain.Num()-1]; ParentLink.ChildZeroLengthTransformIndices.Add(TransformIndex); } } bool bBoneLocationUpdated = false; float const RootToTargetDistSq = FVector::DistSquared(Chain[0].Position, CSEffectorLocation); int32 const NumChainLinks = Chain.Num(); // FABRIK algorithm - bone translation calculation // If the effector is further away than the distance from root to tip, simply move all bones in a line from root to effector location if (RootToTargetDistSq > FMath::Square(MaximumReach)) { for (int32 LinkIndex = 1; LinkIndex < NumChainLinks; LinkIndex++) { FABRIKChainLink const & ParentLink = Chain[LinkIndex - 1]; FABRIKChainLink & CurrentLink = Chain[LinkIndex]; CurrentLink.Position = ParentLink.Position + (CSEffectorLocation - ParentLink.Position).GetUnsafeNormal() * CurrentLink.Length; } bBoneLocationUpdated = true; } else // Effector is within reach, calculate bone translations to position tip at effector location { int32 const TipBoneLinkIndex = NumChainLinks - 1; // Check distance between tip location and effector location float Slop = FVector::Dist(Chain[TipBoneLinkIndex].Position, CSEffectorLocation); if (Slop > Precision) { // Set tip bone at end effector location. Chain[TipBoneLinkIndex].Position = CSEffectorLocation; int32 IterationCount = 0; while ((Slop > Precision) && (IterationCount++ < MaxIterations)) { // "Forward Reaching" stage - adjust bones from end effector. for (int32 LinkIndex = TipBoneLinkIndex - 1; LinkIndex > 0; LinkIndex--) { FABRIKChainLink & CurrentLink = Chain[LinkIndex]; FABRIKChainLink const & ChildLink = Chain[LinkIndex + 1]; CurrentLink.Position = ChildLink.Position + (CurrentLink.Position - ChildLink.Position).GetUnsafeNormal() * ChildLink.Length; } // "Backward Reaching" stage - adjust bones from root. for (int32 LinkIndex = 1; LinkIndex < TipBoneLinkIndex; LinkIndex++) { FABRIKChainLink const & ParentLink = Chain[LinkIndex - 1]; FABRIKChainLink & CurrentLink = Chain[LinkIndex]; CurrentLink.Position = ParentLink.Position + (CurrentLink.Position - ParentLink.Position).GetUnsafeNormal() * CurrentLink.Length; } // Re-check distance between tip location and effector location // Since we're keeping tip on top of effector location, check with its parent bone. Slop = FMath::Abs(Chain[TipBoneLinkIndex].Length - FVector::Dist(Chain[TipBoneLinkIndex - 1].Position, CSEffectorLocation)); } // Place tip bone based on how close we got to target. { FABRIKChainLink const & ParentLink = Chain[TipBoneLinkIndex - 1]; FABRIKChainLink & CurrentLink = Chain[TipBoneLinkIndex]; CurrentLink.Position = ParentLink.Position + (CurrentLink.Position - ParentLink.Position).GetUnsafeNormal() * CurrentLink.Length; } bBoneLocationUpdated = true; } } // If we moved some bones, update bone transforms. if (bBoneLocationUpdated) { // First step: update bone transform positions from chain links. for (int32 LinkIndex = 0; LinkIndex < NumChainLinks; LinkIndex++) { FABRIKChainLink const & ChainLink = Chain[LinkIndex]; OutBoneTransforms[ChainLink.TransformIndex].Transform.SetTranslation(ChainLink.Position); // If there are any zero length children, update position of those int32 const NumChildren = ChainLink.ChildZeroLengthTransformIndices.Num(); for (int32 ChildIndex = 0; ChildIndex < NumChildren; ChildIndex++) { OutBoneTransforms[ChainLink.ChildZeroLengthTransformIndices[ChildIndex]].Transform.SetTranslation(ChainLink.Position); } } // FABRIK algorithm - re-orientation of bone local axes after translation calculation for (int32 LinkIndex = 0; LinkIndex < NumChainLinks - 1; LinkIndex++) { FABRIKChainLink const & CurrentLink = Chain[LinkIndex]; FABRIKChainLink const & ChildLink = Chain[LinkIndex + 1]; // Calculate pre-translation vector between this bone and child FVector const OldDir = (GetCurrentLocation(Output.Pose, ChildLink.BoneIndex) - GetCurrentLocation(Output.Pose, CurrentLink.BoneIndex)).GetUnsafeNormal(); // Get vector from the post-translation bone to it's child FVector const NewDir = (ChildLink.Position - CurrentLink.Position).GetUnsafeNormal(); // Calculate axis of rotation from pre-translation vector to post-translation vector FVector const RotationAxis = FVector::CrossProduct(OldDir, NewDir).GetSafeNormal(); float const RotationAngle = FMath::Acos(FVector::DotProduct(OldDir, NewDir)); FQuat const DeltaRotation = FQuat(RotationAxis, RotationAngle); // We're going to multiply it, in order to not have to re-normalize the final quaternion, it has to be a unit quaternion. checkSlow(DeltaRotation.IsNormalized()); // Calculate absolute rotation and set it FTransform& CurrentBoneTransform = OutBoneTransforms[CurrentLink.TransformIndex].Transform; CurrentBoneTransform.SetRotation(DeltaRotation * CurrentBoneTransform.GetRotation()); CurrentBoneTransform.NormalizeRotation(); // Update zero length children if any int32 const NumChildren = CurrentLink.ChildZeroLengthTransformIndices.Num(); for (int32 ChildIndex = 0; ChildIndex < NumChildren; ChildIndex++) { FTransform& ChildBoneTransform = OutBoneTransforms[CurrentLink.ChildZeroLengthTransformIndices[ChildIndex]].Transform; ChildBoneTransform.SetRotation(DeltaRotation * ChildBoneTransform.GetRotation()); ChildBoneTransform.NormalizeRotation(); } } } // Special handling for tip bone's rotation. int32 const TipBoneTransformIndex = OutBoneTransforms.Num() - 1; switch (EffectorRotationSource) { case BRS_KeepLocalSpaceRotation: OutBoneTransforms[TipBoneTransformIndex].Transform = Output.Pose.GetLocalSpaceTransform(BoneIndices[TipBoneTransformIndex]) * OutBoneTransforms[TipBoneTransformIndex - 1].Transform; break; case BRS_CopyFromTarget: OutBoneTransforms[TipBoneTransformIndex].Transform.SetRotation(CSEffectorTransform.GetRotation()); break; case BRS_KeepComponentSpaceRotation: // Don't change the orientation at all break; default: break; } } bool FAnimNode_Fabrik::IsValidToEvaluate(const USkeleton* Skeleton, const FBoneContainer& RequiredBones) { // Allow evaluation if all parameters are initialized and TipBone is child of RootBone return ( TipBone.IsValidToEvaluate(RequiredBones) && RootBone.IsValidToEvaluate(RequiredBones) && Precision > 0 && RequiredBones.BoneIsChildOf(TipBone.BoneIndex, RootBone.BoneIndex) ); } void FAnimNode_Fabrik::ConditionalDebugDraw(FPrimitiveDrawInterface* PDI, USkeletalMeshComponent* PreviewSkelMeshComp) const { #if WITH_EDITOR if(bEnableDebugDraw && PreviewSkelMeshComp && PreviewSkelMeshComp->GetWorld()) { FVector const CSEffectorLocation = CachedEffectorCSTransform.GetLocation(); // Show end effector position. DrawDebugBox(PreviewSkelMeshComp->GetWorld(), CSEffectorLocation, FVector(Precision), FColor::Green, true, 0.1f); DrawDebugCoordinateSystem(PreviewSkelMeshComp->GetWorld(), CSEffectorLocation, CachedEffectorCSTransform.GetRotation().Rotator(), 5.f, true, 0.1f); } #endif } void FAnimNode_Fabrik::InitializeBoneReferences(const FBoneContainer& RequiredBones) { TipBone.Initialize(RequiredBones); RootBone.Initialize(RequiredBones); EffectorTarget.InitializeBoneReferences(RequiredBones); } void FAnimNode_Fabrik::GatherDebugData(FNodeDebugData& DebugData) { FString DebugLine = DebugData.GetNodeName(this); DebugData.AddDebugItem(DebugLine); ComponentPose.GatherDebugData(DebugData); } void FAnimNode_Fabrik::Initialize_AnyThread(const FAnimationInitializeContext& Context) { Super::Initialize_AnyThread(Context); EffectorTarget.Initialize(Context.AnimInstanceProxy); }
39.917763
204
0.776185
windystrife
d6984666bc2ca846b10e0e34b9da321c7ff06d8b
5,269
cpp
C++
ImageProcessing/HarrisCornerDetector.cpp
IntelSoftware/MulticoreImageProcessing
1dbb65b6ac893d608016f6595523f5b0b9ba342e
[ "Intel" ]
14
2018-07-18T08:08:51.000Z
2021-12-24T15:32:23.000Z
ImageProcessing/HarrisCornerDetector.cpp
IntelSoftware/MulticoreImageProcessing
1dbb65b6ac893d608016f6595523f5b0b9ba342e
[ "Intel" ]
null
null
null
ImageProcessing/HarrisCornerDetector.cpp
IntelSoftware/MulticoreImageProcessing
1dbb65b6ac893d608016f6595523f5b0b9ba342e
[ "Intel" ]
7
2018-10-10T09:02:05.000Z
2021-03-20T05:34:28.000Z
#include "stdafx.h" #include < math.h> #include <fstream> #include "omp.h" using namespace std; extern "C" __declspec(dllexport) int __stdcall HarrisCornerDetector(BYTE* inBGR, BYTE* outBGR, int stride, int width, int height, KVP* arr, int nArr) { // Pack the following structure on one-byte boundaries: smallest possible alignment // This allows to use the minimal memory space for this type: exact fit - no padding #pragma pack(push, 1) struct BGRA { BYTE B, G, R, A; }; #pragma pack(pop) // Back to the default packing mode // Reading the input parameters bool openMP = parameter("openMP", 1, arr, nArr) == 1 ? true : false; // If openMP should be used for multithreading const int radius_kernel = parameter("radius", 3, arr, nArr); // Radius of the convolution kernel int radius_x = width / 2; int radius_y = height / 2; // Creating Sobel Kernels double M[2][3][3] = { { { -1,0,1 },{ -2,0,2 },{ -1,0,1 } },{ { -1,-2,-1 },{ 0,0,0 },{ 1,2,1 } } }; // Creating Gauss Kernel const int size_kernel = 2 * radius_kernel + 1; double ** MGauss = new double*[size_kernel]; InitGaussian(MGauss, size_kernel); // Creating a temporary memory to keep the Grayscale picture BYTE* tmpBGR = new BYTE[stride*height * 4]; if (tmpBGR) { // Allocating the needed memory to hold the 3 matrices to store the Sobel results // Each thread will contain one matrix of each, Ix,Iy,Ixy. // We are creating as many set of 3 matrices as the number of threads // the machine can create. int max_threads = omp_get_max_threads(); double *** Ix = new double**[max_threads]; double *** Iy = new double**[max_threads]; double *** Ixy = new double**[max_threads]; for (int i = 0; i < max_threads; i++) { Ix[i] = new double*[size_kernel]; Iy[i] = new double*[size_kernel]; Ixy[i] = new double*[size_kernel]; for (int j = 0;j < size_kernel;j++) { Ix[i][j] = new double[size_kernel]; Iy[i][j] = new double[size_kernel]; Ixy[i][j] = new double[size_kernel]; } } // Converting the picture into a grayscale picture Grayscale(inBGR, tmpBGR, stride, width, height, openMP); // If the boolean openMP is true, this directive is interpreted so that the following for loop // will be run on multiple cores. #pragma omp parallel for if(openMP) for (int v = 0; v < height; ++v) { int omp_threads = omp_get_num_threads(); auto offset = v * stride; BGRA* p = reinterpret_cast<BGRA*>(tmpBGR + offset); BGRA* q = reinterpret_cast<BGRA*>(outBGR + offset); for (int u = 0; u < width; ++u) { int x = u - radius_x; bool skip = abs(x) > (radius_x - radius_kernel - 1) || abs(radius_y - v) > (radius_y - radius_kernel - 1); if (skip) { q[u] = BGRA{ 0,0,0,255 }; // if convolution not possible (near the edges) } else { int id_thread = omp_get_thread_num(); // For each pixel of the kernel, apply the Sobel operator for (int y = 0, dy = -radius_kernel; y < size_kernel; y++, dy++) { for (int x = 0, dx = -radius_kernel; x < size_kernel; x++, dx++) { int indexKernel = u + dx + dy * width; // Application of the Sobel operator double T[2]; T[0] = 0; T[1] = 0; for (int yS = 0, dy_S = -1; yS < 3; yS++, dy_S++) { for (int xS = 0, dx_S = 0; xS < 3; xS++, dx_S++) { int indexSobel = indexKernel + dx_S + dy_S * width; T[0] += p[indexSobel].G * M[0][yS][xS]; T[1] += p[indexSobel].G * M[1][yS][xS]; } } // Save the results Ix2 and Iy2 and IxIy into the 3 matrices // Considering the thread ID double Tx(T[0]), Ty(T[1]); Ix[id_thread][y][x] = Tx * Tx; Iy[id_thread][y][x] = Ty * Ty; Ixy[id_thread][y][x] = Tx * Ty; } } // After the Sobel operator is applied to neighbors // For each matrix, apply the Gaussian kernel double Tx(0), Ty(0), Txy(0); for (int j = 0; j < size_kernel; j++) { for (int i = 0; i < size_kernel; i++) { Tx += MGauss[i][j] * Ix[id_thread][i][j]; Ty += MGauss[i][j] * Iy[id_thread][i][j]; Txy += MGauss[i][j] * Ixy[id_thread][i][j]; // Reset values for the next time the thread will run Ix[id_thread][i][j] = 0; Iy[id_thread][i][j] = 0; Ixy[id_thread][i][j] = 0; } } // These 3 results are parts of a matrix A such as // A = | Tx Txy| // | Txy Ty | // Calculation of a Score k = det(A) - lambda.trace(A)2 double det = Tx * Ty - (Txy*Txy); double trace = (Tx + Ty); double k = det - 0.04*trace*trace; if (k > 100000000) // Condition for corner detection q[u] = BGRA{ 255,255,255,255 }; else q[u] = BGRA{ 0,0,0,255 }; } } } // Delete the allocated memory for the convolution kernel and the temporary grayscale image for (int i = 0;i < size_kernel;i++) { delete MGauss[i]; } delete[] MGauss; delete tmpBGR; // And also the allocated matrices for the Sobel operators for (int i = 0; i < size_kernel; i++) { for (int j = 0; j < size_kernel; j++) { delete Ix[i][j]; delete Iy[i][j]; delete Ixy[i][j]; } delete Ix[i]; delete Iy[i]; delete Ixy[i]; } delete[] Ix; delete[] Iy; delete[] Ixy; } return 0; }
34.89404
149
0.59423
IntelSoftware
d6998d6612575288ebed1b2c85d3f7c60738ad8a
440
cc
C++
cc/template.cc
asciphx/CarryLib
6f8c54f182525eee47feae412a109e15ead319cc
[ "MIT" ]
1
2021-12-02T11:24:08.000Z
2021-12-02T11:24:08.000Z
cc/template.cc
asciphx/CarryLib
6f8c54f182525eee47feae412a109e15ead319cc
[ "MIT" ]
null
null
null
cc/template.cc
asciphx/CarryLib
6f8c54f182525eee47feae412a109e15ead319cc
[ "MIT" ]
null
null
null
#include <string> #include <iostream> using namespace std; template <typename T,int N> class Array{private:T arr[N]; public:int Size()const{return N;}}; template <typename T> void print(T& x) { std::cout << x << std::endl; } template <typename T, typename... Args> void print(T s, Args... a) { std::cout << s; print<Args...>(a...); } int main(){ Array<int,5>arr; print(arr.Size()); cin.get(); print(1, " dsag ", 1.5f, " ", 3.14); }
27.5
71
0.618182
asciphx
d6a2b7460e047a9fbe289a488e5b9ebf1d56154c
5,326
hpp
C++
src/color/lab/convert/LabCH.hpp
ehtec/color
aa6d8c796303d1f3cfd7361978bfa58eac808b6e
[ "Apache-2.0" ]
120
2015-12-31T22:30:14.000Z
2022-03-29T15:08:01.000Z
src/color/lab/convert/LabCH.hpp
ehtec/color
aa6d8c796303d1f3cfd7361978bfa58eac808b6e
[ "Apache-2.0" ]
6
2016-08-22T02:14:56.000Z
2021-11-06T22:39:52.000Z
src/color/lab/convert/LabCH.hpp
ehtec/color
aa6d8c796303d1f3cfd7361978bfa58eac808b6e
[ "Apache-2.0" ]
23
2016-02-03T01:56:26.000Z
2021-09-28T16:36:27.000Z
#ifndef color_lab_convert_LabCH #define color_lab_convert_LabCH #include "../../_internal/convert.hpp" #include "../category.hpp" #include "../../LabCH/LabCH.hpp" namespace color { namespace _internal { template < typename lab_tag_name ,typename LabCH_tag_name > struct convert < ::color::category::lab< lab_tag_name, ::color::constant::lab::CIE_entity > ,::color::category::LabCH< LabCH_tag_name > > { public: typedef ::color::category::lab< lab_tag_name, ::color::constant::lab::CIE_entity > lab_category_type, category_left_type; typedef ::color::category::LabCH< LabCH_tag_name > LabCH_category_type, category_right_type; typedef typename ::color::trait::scalar< lab_category_type >::instance_type scalar_type; typedef ::color::trait::container<category_left_type> container_left_trait_type; typedef ::color::trait::container<category_right_type> container_right_trait_type; typedef typename container_left_trait_type::input_type container_left_input_type; typedef typename container_right_trait_type::model_type container_right_const_input_type; typedef typename ::color::lab< scalar_type >::category_type LABscalar_category_type; typedef typename ::color::LabCH< scalar_type >::category_type LabCHscalar_category_type; typedef ::color::_internal::reformat< category_left_type, LABscalar_category_type > reformatAB_type; typedef ::color::_internal::reformat< LabCHscalar_category_type, category_right_type > reformatCH_type; typedef ::color::constant::generic< LABscalar_category_type > generic_costant_type; enum { lightness_left_p = ::color::place::_internal::lightness<category_left_type>::position_enum }; enum { lightness_right_p = ::color::place::_internal::lightness<category_right_type>::position_enum ,chroma_right_p = ::color::place::_internal::chroma<category_right_type>::position_enum ,hue_right_p = ::color::place::_internal::hue<category_right_type>::position_enum }; static void process ( container_left_input_type left ,container_right_const_input_type right ) { scalar_type l = reformatCH_type::template process< 0, lightness_right_p >( container_right_trait_type::template get<lightness_right_p >( right ) ); scalar_type c = reformatCH_type::template process< 1, chroma_right_p >( container_right_trait_type::template get<chroma_right_p >( right ) ); scalar_type h = reformatCH_type::template process< 2, hue_right_p >( container_right_trait_type::template get<hue_right_p >( right ) ); scalar_type a = c * cos( h * generic_costant_type::deg2rad() ); scalar_type b = c * sin( h * generic_costant_type::deg2rad() ); container_left_trait_type::template set<lightness_left_p>( left, reformatAB_type::template process< lightness_left_p, 0 >( l ) ); container_left_trait_type::template set<1>( left, reformatAB_type::template process< 1, 1 >( a ) ); container_left_trait_type::template set<2>( left, reformatAB_type::template process< 2, 2 >( b ) ); } }; template < typename lab_tag_name ,typename LabCH_tag_name > struct convert < ::color::category::lab< lab_tag_name, ::color::constant::lab::Hunter_entity > ,::color::category::LabCH< LabCH_tag_name > > { public: typedef ::color::category::lab< lab_tag_name, ::color::constant::lab::Hunter_entity > lab_category_type, category_left_type; typedef ::color::category::LabCH< LabCH_tag_name > LabCH_category_type, category_right_type; typedef typename ::color::trait::scalar<category_left_type>::instance_type scalar_type; typedef ::color::model< lab_category_type > lab_model_type; typedef ::color::model< LabCH_category_type > LabCH_model_type; typedef ::color::xyz< scalar_type > xyz_model_type; typedef ::color::trait::container<category_left_type> container_left_trait_type; typedef ::color::trait::container<category_right_type> container_right_trait_type; typedef typename container_left_trait_type::input_type container_left_input_type; typedef typename container_right_trait_type::model_type container_right_const_input_type; static void process ( container_left_input_type left ,container_right_const_input_type right ) { //::color::_internal::convert< xyz_model_type::category_type, LabCH_category_type >::process( t0, right ); //::color::_internal::convert< lab_category_type, xyz_model_type::category_type >::process( left, t0 ); left = lab_model_type( xyz_model_type( LabCH_model_type( right ) ) ).container(); } }; } } #endif
40.656489
160
0.647953
ehtec
d6a76973891f68e41b3c62084dae8a29d8a61ab6
8,726
cpp
C++
sound-cloud/audio/Audio.cpp
MikaylaFischler/light-art-sound-cloud
31fa393d85e42fb0523579b46da5a1680fa63650
[ "MIT" ]
null
null
null
sound-cloud/audio/Audio.cpp
MikaylaFischler/light-art-sound-cloud
31fa393d85e42fb0523579b46da5a1680fa63650
[ "MIT" ]
null
null
null
sound-cloud/audio/Audio.cpp
MikaylaFischler/light-art-sound-cloud
31fa393d85e42fb0523579b46da5a1680fa63650
[ "MIT" ]
null
null
null
#include "Audio.hpp" AudioControlSGTL5000* Audio::board = NULL; AudioInputI2S* Audio::input = NULL; AudioAnalyzeFFT1024* Audio::fft_l = NULL; AudioAnalyzeFFT1024* Audio::fft_r = NULL; AudioConnection* Audio::fft_l_conn = NULL; AudioConnection* Audio::fft_r_conn = NULL; float** Audio::last_fft = NULL; float*** Audio::fft_history = NULL; uint8_t Audio::ready = 0; uint8_t Audio::hysteresis = 0; uint8_t Audio::h_idx = 0; /** * @brief Initialize the audio system * */ void Audio::init(void) { if (!ready) { // allocate audio memory AudioMemory(20); // create objects for audio processing board = new AudioControlSGTL5000(); input = new AudioInputI2S(); fft_l = new AudioAnalyzeFFT1024(); fft_r = new AudioAnalyzeFFT1024(); fft_l_conn = new AudioConnection(*input, 0, *fft_l, 0); fft_r_conn = new AudioConnection(*input, 0, *fft_r, 0); // last FFT data set last_fft = (float**) malloc(sizeof(float*) * 2); last_fft[AUDIO_FFT_LEFT] = (float*) malloc(sizeof(float) * 512); last_fft[AUDIO_FFT_RIGHT] = (float*) malloc(sizeof(float) * 512); // historical FFT data set fft_history = (float***) malloc(sizeof(float**) * 2); fft_history[AUDIO_FFT_LEFT] = (float**) malloc(sizeof(float*) * 512); fft_history[AUDIO_FFT_RIGHT] = (float**) malloc(sizeof(float*) * 512); for (uint16_t i = 0; i < 512; i++) { fft_history[AUDIO_FFT_LEFT][i] = (float*) calloc(sizeof(float), 3); fft_history[AUDIO_FFT_RIGHT][i] = (float*) calloc(sizeof(float), 3); } disableHysteresis(); // setup board board->enable(); board->inputSelect(AUDIO_INPUT_LINEIN); board->volume(0.5); board->lineInLevel(15); ready = 1; } } /** * @brief Enable hysteresis (readings will be average of last 3 values) * */ void Audio::enableHysteresis(void) { hysteresis = 1; } /** * @brief Disable hysteresis (readings will no longer be average of last 3 values) * */ void Audio::disableHysteresis(void) { hysteresis = 0; } /** * @brief Read the FFT into Audio's buffer, averaging if requested * */ void Audio::__read_fft(void) { // read data for (uint16_t i = 0; i < 512; i++) { fft_history[AUDIO_FFT_LEFT][i][h_idx] = fft_l->read(i); fft_history[AUDIO_FFT_RIGHT][i][h_idx] = fft_r->read(i); } if (hysteresis) { for (uint16_t i = 0; i < 512; i++) { for (uint8_t s = 0; s < 3; s++) { last_fft[AUDIO_FFT_LEFT][i] += fft_history[AUDIO_FFT_LEFT][i][s]; last_fft[AUDIO_FFT_RIGHT][i] += fft_history[AUDIO_FFT_RIGHT][i][s]; } last_fft[AUDIO_FFT_LEFT][i] /= 3.0; last_fft[AUDIO_FFT_RIGHT][i] /= 3.0; } } else { for (uint16_t i = 0; i < 512; i++) { last_fft[AUDIO_FFT_LEFT][i] = fft_history[AUDIO_FFT_LEFT][i][h_idx]; last_fft[AUDIO_FFT_RIGHT][i] = fft_history[AUDIO_FFT_RIGHT][i][h_idx]; } } if (++h_idx > 2) { h_idx = 0; } } /** * @brief Get the FFT data if available * * @return Pointer to FFT array of last collected data */ float** Audio::getFFT(void) { // check availability if (!(fft_l->available() && fft_r->available())) { return last_fft; } // read data __read_fft(); // return the pointer for ease of use return last_fft; } /** * @brief Get the FFT data if available, if not, returns NULL * * @return Pointer to FFT array of the collected data or NULL if not ready */ float** Audio::getFFTWhenReady(void) { // return if unavailable if (!(fft_l->available() && fft_r->available())) { return NULL; } // read data __read_fft(); // return the pointer for ease of use return last_fft; } /** * @brief Get the FFT data if available, if not, this becomes blocking until data is available * * @return Pointer to FFT array of the collected data */ float** Audio::getFFTWhenReadyBlocking(void) { // wait for availability while (!(fft_l->available() && fft_r->available())) { __asm__ __volatile__ ("nop\n\t"); } // read data __read_fft(); // return the pointer for ease of use return last_fft; } /** * @brief Average together a range of FFT data points * * @param side Either AUDIO_FFT_LEFT, AUDIO_FFT_RIGHT, or AUDIO_FFT_COMBINED to combine them (for sepearte data, use one of the averageDualFFTRange functions) * @param bin_start The start index (inclusive, min 0, max 511) * @param bin_end The end index (inclusive, min 0, max 511) * @return float The average of the FFT range */ float Audio::averageFFTRange(uint8_t side, uint16_t bin_start, uint16_t bin_end) { if (bin_start > 511) { bin_start = 511; } if (bin_end > 511) { bin_end = 511; } float avg = 0.0; if (side == AUDIO_FFT_LEFT || side == AUDIO_FFT_RIGHT) { for (uint8_t i = bin_start; i <= bin_end; i++) { avg += Audio::last_fft[side][i]; } avg /= bin_end - bin_start + 1; } else if (side == AUDIO_FFT_COMBINED) { for (uint8_t i = bin_start; i <= bin_end; i++) { avg += Audio::last_fft[AUDIO_FFT_LEFT][i]; avg += Audio::last_fft[AUDIO_FFT_RIGHT][i]; } avg /= (bin_end - bin_start + 1) * 2.0; } return avg; } /** * @brief 'Average' together a range of FFT data points. This sums the data, but divides not by the count, but by the provided division_factor * * @param side Either AUDIO_FFT_LEFT, AUDIO_FFT_RIGHT, or AUDIO_FFT_COMBINED to combine them (for sepearte data, use one of the averageDualFFTRange functions) * @param bin_start The start index (inclusive, min 0, max 511) * @param bin_end The end index (inclusive, min 0, max 511) * @param division_factor The factor to divide the sum by (instead of dividing by the number of points summed) * @return float The scaled 'pseudo-average' of the FFT range */ float Audio::averageFFTRangeUnbalanced(uint8_t side, uint16_t bin_start, uint16_t bin_end, float division_factor) { if (bin_start > 511) { bin_start = 511; } if (bin_end > 511) { bin_end = 511; } float avg = 0.0; if (side == AUDIO_FFT_LEFT || side == AUDIO_FFT_RIGHT) { for (uint8_t i = bin_start; i <= bin_end; i++) { avg += Audio::last_fft[side][i]; } avg /= division_factor; } else if (side == AUDIO_FFT_COMBINED) { for (uint8_t i = bin_start; i <= bin_end; i++) { avg += Audio::last_fft[AUDIO_FFT_LEFT][i]; avg += Audio::last_fft[AUDIO_FFT_RIGHT][i]; } avg /= (division_factor) * 2.0; } return avg; } /** * @brief 'Average' together a range of FFT data points. This sums the data, but divides not by the count, but by the provided division_factor. * Returns a 2 element array, containing the left then the right data. * * @param bin_start The start index (inclusive, min 0, max 511) * @param bin_end The end index (inclusive, min 0, max 511) * @param division_factor The factor to divide the sum by (instead of dividing by the number of points summed) * @return float The scaled 'pseudo-average' of the FFT range [left, right] */ float* Audio::averageDualFFTRange(uint16_t bin_start, uint16_t bin_end) { if (bin_start > 511) { bin_start = 511; } if (bin_end > 511) { bin_end = 511; } static float avgs[2] = { 0.0, 0.0 }; for (uint8_t i = bin_start; i <= bin_end; i++) { avgs[0] += Audio::last_fft[AUDIO_FFT_LEFT][i]; avgs[1] += Audio::last_fft[AUDIO_FFT_RIGHT][i]; } avgs[0] /= bin_end - bin_start + 1; avgs[1] /= bin_end - bin_start + 1; return avgs; } /** * @brief 'Average' together a range of FFT data points. This sums the data, but divides not by the count, but by the provided division_factor. * Returns a 2 element array, containing the left then the right data. * * @param bin_start The start index (inclusive, min 0, max 511) * @param bin_end The end index (inclusive, min 0, max 511) * @param division_factor The factor to divide the sum by (instead of dividing by the number of points summed) * @return float* The scaled 'pseudo-averages' of the FFT range [left, right] */ float* Audio::averageDualFFTRangeUnbalanced(uint16_t bin_start, uint16_t bin_end, float division_factor) { if (bin_start > 511) { bin_start = 511; } if (bin_end > 511) { bin_end = 511; } static float avgs[2] = { 0.0, 0.0 }; for (uint8_t i = bin_start; i <= bin_end; i++) { avgs[0] += Audio::last_fft[AUDIO_FFT_LEFT][i]; avgs[1] += Audio::last_fft[AUDIO_FFT_RIGHT][i]; } avgs[0] /= division_factor; avgs[1] /= division_factor; return avgs; } /** * @brief Convert an FFT float bin to a integer * * @param bin The float value * @param scale_factor Scale the input float by this before conversion * @param brightness_transform This allows transformation of the output before returning * @return uint8_t 0 to 255 for LED control */ uint8_t Audio::fftToInt(float bin, float scale_factor, uint8_t (*brightness_transform)(uint8_t) = NULL) { uint8_t converted = (uint8_t) round(bin * scale_factor * 255.0); if (brightness_transform) { converted = brightness_transform(converted); } return converted; }
30.833922
159
0.683475
MikaylaFischler
d6ad47df68a2fcb10c7d062499ad5b3f4b09c858
260
cpp
C++
src/skills/Skill.cpp
char-lotl/traveller-cc
802d36d7eaa8b027655912c4c71f7ebff2f2059f
[ "MIT" ]
null
null
null
src/skills/Skill.cpp
char-lotl/traveller-cc
802d36d7eaa8b027655912c4c71f7ebff2f2059f
[ "MIT" ]
null
null
null
src/skills/Skill.cpp
char-lotl/traveller-cc
802d36d7eaa8b027655912c4c71f7ebff2f2059f
[ "MIT" ]
null
null
null
#include <optional> #include <string> #include "Skill.h" Skill::Skill(skill_type ws) : which_skill(ws) { // nothing required here } Skill::Skill(skill_type ws, std::string subsk) : which_skill(ws), specialty(subsk) { // still nothing required here }
20
48
0.7
char-lotl
d6ae0786b9df375767708406bdc7c02258a5dfb4
925
cpp
C++
src/shader.cpp
cbries/tetrisgl
a40f22140d05c2cf6116946459a99a0477c1569a
[ "MIT" ]
1
2015-02-23T19:06:04.000Z
2015-02-23T19:06:04.000Z
src/shader.cpp
cbries/tetrisgl
a40f22140d05c2cf6116946459a99a0477c1569a
[ "MIT" ]
null
null
null
src/shader.cpp
cbries/tetrisgl
a40f22140d05c2cf6116946459a99a0477c1569a
[ "MIT" ]
null
null
null
/* * Copyright (c) 2008 Christian Benjamin Ries * License: MIT * Website: https://github.com/cbries/tetrisgl */ #include <stdio.h> #include <stdlib.h> #include <string> #include <iostream> #include "shader.h" #include "textfile.h" GLuint setShaders( std::string filename ) { GLuint v, f; char *vs = NULL,*fs = NULL,*fs2 = NULL; v = glCreateShader(GL_VERTEX_SHADER); f = glCreateShader(GL_FRAGMENT_SHADER); std::string vertexStr = filename + ".vert"; std::string fragmentStr = filename + ".frag"; vs = textFileRead( (char*)vertexStr.c_str() ); fs = textFileRead( (char*)fragmentStr.c_str() ); const char * ff = fs; const char * ff2 = fs2; const char * vv = vs; glShaderSource(v, 1, &vv,NULL); glShaderSource(f, 1, &ff,NULL); free(vs); free(fs); glCompileShader(v); glCompileShader(f); GLuint p = glCreateProgram(); glAttachShader(p,f); glAttachShader(p,v); glLinkProgram(p); return p; }
18.877551
49
0.675676
cbries
d6af020326eb0058e688e2e0c92a0d4c933038d4
8,161
cpp
C++
clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
null
null
null
clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
null
null
null
clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
null
null
null
//===--- VirtualClassDestructorCheck.cpp - clang-tidy -----------------===// // // 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 // //===----------------------------------------------------------------------===// #include "VirtualClassDestructorCheck.h" #include "../utils/LexerUtils.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Lex/Lexer.h" #include <string> using namespace clang::ast_matchers; namespace clang { namespace tidy { namespace cppcoreguidelines { AST_MATCHER(CXXRecordDecl, hasPublicVirtualOrProtectedNonVirtualDestructor) { // We need to call Node.getDestructor() instead of matching a // CXXDestructorDecl. Otherwise, tests will fail for class templates, since // the primary template (not the specialization) always gets a non-virtual // CXXDestructorDecl in the AST. https://bugs.llvm.org/show_bug.cgi?id=51912 const CXXDestructorDecl *Destructor = Node.getDestructor(); if (!Destructor) return false; return (((Destructor->getAccess() == AccessSpecifier::AS_public) && Destructor->isVirtual()) || ((Destructor->getAccess() == AccessSpecifier::AS_protected) && !Destructor->isVirtual())); } void VirtualClassDestructorCheck::registerMatchers(MatchFinder *Finder) { ast_matchers::internal::Matcher<CXXRecordDecl> InheritsVirtualMethod = hasAnyBase(hasType(cxxRecordDecl(has(cxxMethodDecl(isVirtual()))))); Finder->addMatcher( cxxRecordDecl( anyOf(has(cxxMethodDecl(isVirtual())), InheritsVirtualMethod), unless(hasPublicVirtualOrProtectedNonVirtualDestructor())) .bind("ProblematicClassOrStruct"), this); } static Optional<CharSourceRange> getVirtualKeywordRange(const CXXDestructorDecl &Destructor, const SourceManager &SM, const LangOptions &LangOpts) { if (Destructor.getLocation().isMacroID()) return None; SourceLocation VirtualBeginLoc = Destructor.getBeginLoc(); SourceLocation VirtualEndLoc = VirtualBeginLoc.getLocWithOffset( Lexer::MeasureTokenLength(VirtualBeginLoc, SM, LangOpts)); /// Range ends with \c StartOfNextToken so that any whitespace after \c /// virtual is included. SourceLocation StartOfNextToken = Lexer::findNextToken(VirtualEndLoc, SM, LangOpts) .getValue() .getLocation(); return CharSourceRange::getCharRange(VirtualBeginLoc, StartOfNextToken); } static const AccessSpecDecl * getPublicASDecl(const CXXRecordDecl &StructOrClass) { for (DeclContext::specific_decl_iterator<AccessSpecDecl> AS{StructOrClass.decls_begin()}, ASEnd{StructOrClass.decls_end()}; AS != ASEnd; ++AS) { AccessSpecDecl *ASDecl = *AS; if (ASDecl->getAccess() == AccessSpecifier::AS_public) return ASDecl; } return nullptr; } static FixItHint generateUserDeclaredDestructor(const CXXRecordDecl &StructOrClass, const SourceManager &SourceManager) { std::string DestructorString; SourceLocation Loc; bool AppendLineBreak = false; const AccessSpecDecl *AccessSpecDecl = getPublicASDecl(StructOrClass); if (!AccessSpecDecl) { if (StructOrClass.isClass()) { Loc = StructOrClass.getEndLoc(); DestructorString = "public:"; AppendLineBreak = true; } else { Loc = StructOrClass.getBraceRange().getBegin().getLocWithOffset(1); } } else { Loc = AccessSpecDecl->getEndLoc().getLocWithOffset(1); } DestructorString = (llvm::Twine(DestructorString) + "\nvirtual ~" + StructOrClass.getName().str() + "() = default;" + (AppendLineBreak ? "\n" : "")) .str(); return FixItHint::CreateInsertion(Loc, DestructorString); } static std::string getSourceText(const CXXDestructorDecl &Destructor) { std::string SourceText; llvm::raw_string_ostream DestructorStream(SourceText); Destructor.print(DestructorStream); return SourceText; } static std::string eraseKeyword(std::string &DestructorString, const std::string &Keyword) { size_t KeywordIndex = DestructorString.find(Keyword); if (KeywordIndex != std::string::npos) DestructorString.erase(KeywordIndex, Keyword.length()); return DestructorString; } static FixItHint changePrivateDestructorVisibilityTo( const std::string &Visibility, const CXXDestructorDecl &Destructor, const SourceManager &SM, const LangOptions &LangOpts) { std::string DestructorString = (llvm::Twine() + Visibility + ":\n" + (Visibility == "public" && !Destructor.isVirtual() ? "virtual " : "")) .str(); std::string OriginalDestructor = getSourceText(Destructor); if (Visibility == "protected" && Destructor.isVirtualAsWritten()) OriginalDestructor = eraseKeyword(OriginalDestructor, "virtual "); DestructorString = (llvm::Twine(DestructorString) + OriginalDestructor + (Destructor.isExplicitlyDefaulted() ? ";\n" : "") + "private:") .str(); /// Semicolons ending an explicitly defaulted destructor have to be deleted. /// Otherwise, the left-over semicolon trails the \c private: access /// specifier. SourceLocation EndLocation; if (Destructor.isExplicitlyDefaulted()) EndLocation = utils::lexer::findNextTerminator(Destructor.getEndLoc(), SM, LangOpts) .getLocWithOffset(1); else EndLocation = Destructor.getEndLoc().getLocWithOffset(1); auto OriginalDestructorRange = CharSourceRange::getCharRange(Destructor.getBeginLoc(), EndLocation); return FixItHint::CreateReplacement(OriginalDestructorRange, DestructorString); } void VirtualClassDestructorCheck::check( const MatchFinder::MatchResult &Result) { const auto *MatchedClassOrStruct = Result.Nodes.getNodeAs<CXXRecordDecl>("ProblematicClassOrStruct"); const CXXDestructorDecl *Destructor = MatchedClassOrStruct->getDestructor(); if (!Destructor) return; if (Destructor->getAccess() == AccessSpecifier::AS_private) { diag(MatchedClassOrStruct->getLocation(), "destructor of %0 is private and prevents using the type") << MatchedClassOrStruct; diag(MatchedClassOrStruct->getLocation(), /*Description=*/"make it public and virtual", DiagnosticIDs::Note) << changePrivateDestructorVisibilityTo( "public", *Destructor, *Result.SourceManager, getLangOpts()); diag(MatchedClassOrStruct->getLocation(), /*Description=*/"make it protected", DiagnosticIDs::Note) << changePrivateDestructorVisibilityTo( "protected", *Destructor, *Result.SourceManager, getLangOpts()); return; } // Implicit destructors are public and non-virtual for classes and structs. bool ProtectedAndVirtual = false; FixItHint Fix; if (MatchedClassOrStruct->hasUserDeclaredDestructor()) { if (Destructor->getAccess() == AccessSpecifier::AS_public) { Fix = FixItHint::CreateInsertion(Destructor->getLocation(), "virtual "); } else if (Destructor->getAccess() == AccessSpecifier::AS_protected) { ProtectedAndVirtual = true; if (const auto MaybeRange = getVirtualKeywordRange(*Destructor, *Result.SourceManager, Result.Context->getLangOpts())) Fix = FixItHint::CreateRemoval(*MaybeRange); } } else { Fix = generateUserDeclaredDestructor(*MatchedClassOrStruct, *Result.SourceManager); } diag(MatchedClassOrStruct->getLocation(), "destructor of %0 is %select{public and non-virtual|protected and " "virtual}1") << MatchedClassOrStruct << ProtectedAndVirtual; diag(MatchedClassOrStruct->getLocation(), "make it %select{public and virtual|protected and non-virtual}0", DiagnosticIDs::Note) << ProtectedAndVirtual << Fix; } } // namespace cppcoreguidelines } // namespace tidy } // namespace clang
37.26484
80
0.687171
LaudateCorpus1
d6b35ae2331cfd74b20a6fe63fc1a21789b750d9
673
cc
C++
algo/lc.114.cc
cdluminate/MyNotes
cf28f2a3fa72723153147e21fed5e7b598baf44f
[ "CC0-1.0" ]
null
null
null
algo/lc.114.cc
cdluminate/MyNotes
cf28f2a3fa72723153147e21fed5e7b598baf44f
[ "CC0-1.0" ]
null
null
null
algo/lc.114.cc
cdluminate/MyNotes
cf28f2a3fa72723153147e21fed5e7b598baf44f
[ "CC0-1.0" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void flatten(TreeNode* root) { if (nullptr == root) return; flatten(root->left); flatten(root->right); if (nullptr == root->left) { return; } else { TreeNode* cur = root->left; while (nullptr != cur->right) cur = cur->right; cur->right = root->right; root->right = root->left; root->left = nullptr; } } };
23.206897
59
0.481426
cdluminate
d6b42c58ecda30c17d6cfe97615a6f11bcaafbf5
25,018
cpp
C++
src/modules/processes/ColorCalibration/BackgroundNeutralizationInterface.cpp
fmeschia/pixinsight-class-library
11b956e27d6eee3e119a7b1c337d090d7a03f436
[ "JasPer-2.0", "libtiff" ]
null
null
null
src/modules/processes/ColorCalibration/BackgroundNeutralizationInterface.cpp
fmeschia/pixinsight-class-library
11b956e27d6eee3e119a7b1c337d090d7a03f436
[ "JasPer-2.0", "libtiff" ]
null
null
null
src/modules/processes/ColorCalibration/BackgroundNeutralizationInterface.cpp
fmeschia/pixinsight-class-library
11b956e27d6eee3e119a7b1c337d090d7a03f436
[ "JasPer-2.0", "libtiff" ]
null
null
null
// ____ ______ __ // / __ \ / ____// / // / /_/ // / / / // / ____// /___ / /___ PixInsight Class Library // /_/ \____//_____/ PCL 2.4.9 // ---------------------------------------------------------------------------- // Standard ColorCalibration Process Module Version 1.5.1 // ---------------------------------------------------------------------------- // BackgroundNeutralizationInterface.cpp - Released 2021-04-09T19:41:48Z // ---------------------------------------------------------------------------- // This file is part of the standard ColorCalibration PixInsight module. // // Copyright (c) 2003-2021 Pleiades Astrophoto S.L. All Rights Reserved. // // Redistribution and use in both source and binary forms, with or without // modification, is permitted provided that the following conditions are met: // // 1. All redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. All redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names // of their contributors, may be used to endorse or promote products derived // from this software without specific prior written permission. For written // permission, please contact info@pixinsight.com. // // 4. All products derived from this software, in any form whatsoever, must // reproduce the following acknowledgment in the end-user documentation // and/or other materials provided with the product: // // "This product is based on software from the PixInsight project, developed // by Pleiades Astrophoto and its contributors (https://pixinsight.com/)." // // Alternatively, if that is where third-party acknowledgments normally // appear, this acknowledgment must be reproduced in the product itself. // // THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO 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 PLEIADES ASTROPHOTO OR ITS // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS // INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE, // DATA OR PROFITS) 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 "BackgroundNeutralizationInterface.h" #include "BackgroundNeutralizationProcess.h" #include "BackgroundNeutralizationParameters.h" #include <pcl/ErrorHandler.h> #include <pcl/PreviewSelectionDialog.h> #include <pcl/ViewSelectionDialog.h> namespace pcl { // ---------------------------------------------------------------------------- BackgroundNeutralizationInterface* TheBackgroundNeutralizationInterface = nullptr; // ---------------------------------------------------------------------------- BackgroundNeutralizationInterface::BackgroundNeutralizationInterface() : instance( TheBackgroundNeutralizationProcess ) { TheBackgroundNeutralizationInterface = this; } // ---------------------------------------------------------------------------- BackgroundNeutralizationInterface::~BackgroundNeutralizationInterface() { if ( GUI != nullptr ) delete GUI, GUI = nullptr; } // ---------------------------------------------------------------------------- IsoString BackgroundNeutralizationInterface::Id() const { return "BackgroundNeutralization"; } // ---------------------------------------------------------------------------- MetaProcess* BackgroundNeutralizationInterface::Process() const { return TheBackgroundNeutralizationProcess; } // ---------------------------------------------------------------------------- String BackgroundNeutralizationInterface::IconImageSVGFile() const { return "@module_icons_dir/BackgroundNeutralization.svg"; } // ---------------------------------------------------------------------------- InterfaceFeatures BackgroundNeutralizationInterface::Features() const { return InterfaceFeature::Default; } // ---------------------------------------------------------------------------- void BackgroundNeutralizationInterface::ApplyInstance() const { instance.LaunchOnCurrentView(); } // ---------------------------------------------------------------------------- void BackgroundNeutralizationInterface::ResetInstance() { BackgroundNeutralizationInstance defaultInstance( TheBackgroundNeutralizationProcess ); ImportProcess( defaultInstance ); } // ---------------------------------------------------------------------------- bool BackgroundNeutralizationInterface::Launch( const MetaProcess& P, const ProcessImplementation*, bool& dynamic, unsigned& /*flags*/ ) { if ( GUI == nullptr ) { GUI = new GUIData( *this ); SetWindowTitle( "BackgroundNeutralization" ); UpdateControls(); } dynamic = false; return &P == TheBackgroundNeutralizationProcess; } // ---------------------------------------------------------------------------- ProcessImplementation* BackgroundNeutralizationInterface::NewProcess() const { return new BackgroundNeutralizationInstance( instance ); } // ---------------------------------------------------------------------------- bool BackgroundNeutralizationInterface::ValidateProcess( const ProcessImplementation& p, String& whyNot ) const { if ( dynamic_cast<const BackgroundNeutralizationInstance*>( &p ) != nullptr ) return true; whyNot = "Not a BackgroundNeutralization instance."; return false; } // ---------------------------------------------------------------------------- bool BackgroundNeutralizationInterface::RequiresInstanceValidation() const { return true; } // ---------------------------------------------------------------------------- bool BackgroundNeutralizationInterface::ImportProcess( const ProcessImplementation& p ) { instance.Assign( p ); UpdateControls(); return true; } // ---------------------------------------------------------------------------- #define TARGET_IMAGE String( "<target image>" ) #define REFERENCE_ID( x ) (x.IsEmpty() ? TARGET_IMAGE : x) #define BACKGROUND_REFERENCE_ID REFERENCE_ID( instance.backgroundReferenceViewId ) void BackgroundNeutralizationInterface::UpdateControls() { GUI->BackgroundReferenceView_Edit.SetText( BACKGROUND_REFERENCE_ID ); GUI->BackgroundLow_NumericControl.SetValue( instance.backgroundLow ); GUI->BackgroundHigh_NumericControl.SetValue( instance.backgroundHigh ); GUI->Mode_ComboBox.SetCurrentItem( instance.mode ); GUI->TargetBackground_NumericControl.Enable( instance.mode == BNMode::TargetBackground ); GUI->TargetBackground_NumericControl.SetValue( instance.targetBackground ); GUI->ROI_GroupBox.SetChecked( instance.useROI ); GUI->ROIX0_SpinBox.SetValue( instance.roi.x0 ); GUI->ROIY0_SpinBox.SetValue( instance.roi.y0 ); GUI->ROIWidth_SpinBox.SetValue( instance.roi.Width() ); GUI->ROIHeight_SpinBox.SetValue( instance.roi.Height() ); } // ---------------------------------------------------------------------------- void BackgroundNeutralizationInterface::__GetFocus( Control& sender ) { Edit* e = dynamic_cast<Edit*>( &sender ); if ( e != nullptr ) if ( e->Text() == TARGET_IMAGE ) e->Clear(); } // ---------------------------------------------------------------------------- void BackgroundNeutralizationInterface::__EditCompleted( Edit& sender ) { if ( sender == GUI->BackgroundReferenceView_Edit ) { try { String id = sender.Text().Trimmed(); if ( id == TARGET_IMAGE ) id.Clear(); if ( !id.IsEmpty() ) if ( !View::IsValidViewId( id ) ) throw Error( "Invalid view identifier: " + id ); instance.backgroundReferenceViewId = id; sender.SetText( BACKGROUND_REFERENCE_ID ); } catch ( ... ) { sender.SetText( BACKGROUND_REFERENCE_ID ); try { throw; } ERROR_HANDLER sender.SelectAll(); sender.Focus(); } } } // ---------------------------------------------------------------------------- void BackgroundNeutralizationInterface::__EditValueUpdated( NumericEdit& sender, double value ) { if ( sender == GUI->BackgroundLow_NumericControl ) instance.backgroundLow = value; else if ( sender == GUI->BackgroundHigh_NumericControl ) instance.backgroundHigh = value; else if ( sender == GUI->TargetBackground_NumericControl ) instance.targetBackground = value; } // ---------------------------------------------------------------------------- void BackgroundNeutralizationInterface::__Click( Button& sender, bool checked ) { if ( sender == GUI->BackgroundReferenceView_ToolButton ) { ViewSelectionDialog d( instance.backgroundReferenceViewId ); if ( d.Execute() == StdDialogCode::Ok ) { instance.backgroundReferenceViewId = d.Id(); GUI->BackgroundReferenceView_Edit.SetText( BACKGROUND_REFERENCE_ID ); } } } // ---------------------------------------------------------------------------- void BackgroundNeutralizationInterface::__ItemSelected( ComboBox& sender, int itemIndex ) { if ( sender == GUI->Mode_ComboBox ) { instance.mode = itemIndex; UpdateControls(); } } // ---------------------------------------------------------------------------- void BackgroundNeutralizationInterface::__ROI_Check( GroupBox& sender, bool checked ) { if ( sender == GUI->ROI_GroupBox ) instance.useROI = checked; } // ---------------------------------------------------------------------------- void BackgroundNeutralizationInterface::__ROI_SpinValueUpdated( SpinBox& sender, int value ) { if ( sender == GUI->ROIX0_SpinBox ) instance.roi.x0 = value; else if ( sender == GUI->ROIY0_SpinBox ) instance.roi.y0 = value; else if ( sender == GUI->ROIWidth_SpinBox ) instance.roi.x1 = instance.roi.x0 + value; else if ( sender == GUI->ROIHeight_SpinBox ) instance.roi.y1 = instance.roi.y0 + value; } // ---------------------------------------------------------------------------- void BackgroundNeutralizationInterface::__ROI_Click( Button& sender, bool checked ) { if ( sender == GUI->ROISelectPreview_Button ) { PreviewSelectionDialog d; if ( d.Execute() ) if ( !d.Id().IsEmpty() ) { View view = View::ViewById( d.Id() ); if ( !view.IsNull() ) { instance.roi = view.Window().PreviewRect( view.Id() ); UpdateControls(); } } } } // ---------------------------------------------------------------------------- void BackgroundNeutralizationInterface::__ViewDrag( Control& sender, const Point& pos, const View& view, unsigned modifiers, bool& wantsView ) { if ( sender == GUI->BackgroundReferenceView_Edit ) wantsView = true; else if ( sender == GUI->ROI_GroupBox || sender == GUI->ROISelectPreview_Button ) wantsView = view.IsPreview(); } // ---------------------------------------------------------------------------- void BackgroundNeutralizationInterface::__ViewDrop( Control& sender, const Point& pos, const View& view, unsigned modifiers ) { if ( sender == GUI->BackgroundReferenceView_Edit ) { instance.backgroundReferenceViewId = view.FullId(); GUI->BackgroundReferenceView_Edit.SetText( BACKGROUND_REFERENCE_ID ); } else if ( sender == GUI->ROI_GroupBox || sender == GUI->ROISelectPreview_Button ) { if ( view.IsPreview() ) { instance.useROI = true; instance.roi = view.Window().PreviewRect( view.Id() ); UpdateControls(); } } } // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- BackgroundNeutralizationInterface::GUIData::GUIData( BackgroundNeutralizationInterface& w ) { #define DELTA_FRAME 1 pcl::Font fnt = w.Font(); int labelWidth1 = fnt.Width( String( "Target background:" ) + 'T' ); int labelWidth2 = fnt.Width( String( "Height:" ) + 'T' ); int editWidth1 = fnt.Width( String( '0', 12 ) ); // BackgroundReferenceView_Label.SetText( "Reference image:" ); BackgroundReferenceView_Label.SetFixedWidth( labelWidth1 ); BackgroundReferenceView_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); BackgroundReferenceView_Edit.SetToolTip( "<p>BackgroundNeutralization will use pixels read from this " "image to compute an initial mean background level for each color channel. If you leave this field blank " "(or with its default &lt;target image&gt; value), the target image will be also the background " "reference image during the neutralization process.</p>" "<p>You should specify a view that represents the <i>true background</i> of the image. In most cases this " "means that you must select a view whose pixels are strongly dominated by the sky background, as it is " "being represented on the target image. A typical example involves defining a small preview over a free " "sky area of the target image, and selecting it here as the background reference image.</p>" ); BackgroundReferenceView_Edit.OnGetFocus( (Control::event_handler)&BackgroundNeutralizationInterface::__GetFocus, w ); BackgroundReferenceView_Edit.OnEditCompleted( (Edit::edit_event_handler)&BackgroundNeutralizationInterface::__EditCompleted, w ); BackgroundReferenceView_Edit.OnViewDrag( (Control::view_drag_event_handler)&BackgroundNeutralizationInterface::__ViewDrag, w ); BackgroundReferenceView_Edit.OnViewDrop( (Control::view_drop_event_handler)&BackgroundNeutralizationInterface::__ViewDrop, w ); BackgroundReferenceView_ToolButton.SetIcon( Bitmap( w.ScaledResource( ":/icons/select-view.png" ) ) ); BackgroundReferenceView_ToolButton.SetScaledFixedSize( 20, 20 ); BackgroundReferenceView_ToolButton.SetToolTip( "<p>Select the background reference image.</p>" ); BackgroundReferenceView_ToolButton.OnClick( (Button::click_event_handler)&BackgroundNeutralizationInterface::__Click, w ); BackgroundReferenceView_Sizer.SetSpacing( 4 ); BackgroundReferenceView_Sizer.Add( BackgroundReferenceView_Label ); BackgroundReferenceView_Sizer.Add( BackgroundReferenceView_Edit ); BackgroundReferenceView_Sizer.Add( BackgroundReferenceView_ToolButton ); BackgroundLow_NumericControl.label.SetText( "Lower limit:" ); BackgroundLow_NumericControl.label.SetFixedWidth( labelWidth1 ); BackgroundLow_NumericControl.slider.SetRange( 0, 100 ); BackgroundLow_NumericControl.slider.SetScaledMinWidth( 200 ); BackgroundLow_NumericControl.SetReal(); BackgroundLow_NumericControl.SetRange( TheBNBackgroundLowParameter->MinimumValue(), TheBNBackgroundLowParameter->MaximumValue() ); BackgroundLow_NumericControl.SetPrecision( TheBNBackgroundLowParameter->Precision() ); BackgroundLow_NumericControl.edit.SetFixedWidth( editWidth1 ); BackgroundLow_NumericControl.SetToolTip( "<p>Lower bound of the set of background pixels. Background reference " "pixels with values less than or equal to this value will be rejected for calculation of mean background " "levels. Note that since the minimum allowed value for this parameter is zero, black pixels are never taken " "into account.</p>" ); BackgroundLow_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&BackgroundNeutralizationInterface::__EditValueUpdated, w ); BackgroundHigh_NumericControl.label.SetText( "Upper limit:" ); BackgroundHigh_NumericControl.label.SetFixedWidth( labelWidth1 ); BackgroundHigh_NumericControl.slider.SetRange( 0, 100 ); BackgroundHigh_NumericControl.slider.SetScaledMinWidth( 200 ); BackgroundHigh_NumericControl.SetReal(); BackgroundHigh_NumericControl.SetRange( TheBNBackgroundHighParameter->MinimumValue(), TheBNBackgroundHighParameter->MaximumValue() ); BackgroundHigh_NumericControl.SetPrecision( TheBNBackgroundHighParameter->Precision() ); BackgroundHigh_NumericControl.edit.SetFixedWidth( editWidth1 ); BackgroundHigh_NumericControl.SetToolTip( "<p>Upper bound of the set of background pixels. Background reference " "pixels above this value will be rejected for calculation of mean background levels.</p>" ); BackgroundHigh_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&BackgroundNeutralizationInterface::__EditValueUpdated, w ); const char* modeToolTip = "<p>Select a background neutralization mode.</p>" "<p>In <i>target background</i> mode, BackgroundNeutralization will force the target image to have " "the specified mean background value (see the target background parameter below) for the three RGB " "channels. In this mode, any resulting out-of-range values after neutralization will be truncated. " "There can be some (usually negligible) data clipping, but only additive transformations are applied " "to the data.</p>" "<p>In <i>rescale</i> mode, the target image will always be rescaled after neutralization. In this " "mode there are no data clippings, and the neutralized image maximizes dynamic range usage. However, " "in this mode you have no control over the resulting mean background value, and the rescaling operation " "is a multiplicative transformation that redistributes all pixel values throughout the available dynamic " "range.</p>" "<p>The <i>rescale as needed</i> mode is similar to <i>rescale</i>, but the target image is only rescaled " "if there are out-of-range-values after neutralization. This is the default mode.</p>" "<p>In <i>truncate</i> mode all resulting out-of-range pixels after neutralization will be truncated, " "which usually results in severely clipped data. This mode is useful to perform a background subtraction " "to a working image used for an intermediate analysis or processing step.</p>"; Mode_Label.SetText( "Working mode:" ); Mode_Label.SetFixedWidth( labelWidth1 ); Mode_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); Mode_Label.SetToolTip( modeToolTip ); Mode_ComboBox.AddItem( "Target Background" ); Mode_ComboBox.AddItem( "Rescale" ); Mode_ComboBox.AddItem( "Rescale as needed" ); Mode_ComboBox.AddItem( "Truncate" ); Mode_ComboBox.SetToolTip( modeToolTip ); Mode_ComboBox.OnItemSelected( (ComboBox::item_event_handler)&BackgroundNeutralizationInterface::__ItemSelected, w ); Mode_Sizer.SetSpacing( 4 ); Mode_Sizer.Add( Mode_Label ); Mode_Sizer.Add( Mode_ComboBox ); Mode_Sizer.AddStretch(); TargetBackground_NumericControl.label.SetText( "Target background:" ); TargetBackground_NumericControl.label.SetFixedWidth( labelWidth1 ); TargetBackground_NumericControl.slider.SetRange( 0, 100 ); TargetBackground_NumericControl.slider.SetScaledMinWidth( 200 ); TargetBackground_NumericControl.SetReal(); TargetBackground_NumericControl.SetRange( TheBNTargetBackgroundParameter->MinimumValue(), TheBNTargetBackgroundParameter->MaximumValue() ); TargetBackground_NumericControl.SetPrecision( TheBNTargetBackgroundParameter->Precision() ); TargetBackground_NumericControl.edit.SetFixedWidth( editWidth1 ); TargetBackground_NumericControl.SetToolTip( "<p>In the <i>target background</i> working mode, this is the " "final mean background level that will be imposed to the three RGB channels of the target image.</p>" "<p>In the rest of modes (<i>rescale</i>, <i>rescale as needed</i> and <i>truncate</i>) this parameter " "is not used.</p>" ); TargetBackground_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&BackgroundNeutralizationInterface::__EditValueUpdated, w ); // ROI_GroupBox.SetTitle( "Region of Interest" ); ROI_GroupBox.EnableTitleCheckBox(); ROI_GroupBox.OnCheck( (GroupBox::check_event_handler)&BackgroundNeutralizationInterface::__ROI_Check, w ); ROI_GroupBox.OnViewDrag( (Control::view_drag_event_handler)&BackgroundNeutralizationInterface::__ViewDrag, w ); ROI_GroupBox.OnViewDrop( (Control::view_drop_event_handler)&BackgroundNeutralizationInterface::__ViewDrop, w ); const char* roiX0ToolTip = "<p>X pixel coordinate of the upper-left corner of the ROI.</p>"; ROIX0_Label.SetText( "Left:" ); ROIX0_Label.SetFixedWidth( labelWidth1 - w.LogicalPixelsToPhysical( 6 + DELTA_FRAME ) ); ROIX0_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); ROIX0_Label.SetToolTip( roiX0ToolTip ); ROIX0_SpinBox.SetRange( 0, int_max ); ROIX0_SpinBox.SetToolTip( roiX0ToolTip ); ROIX0_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&BackgroundNeutralizationInterface::__ROI_SpinValueUpdated, w ); const char* roiY0ToolTip = "<p>Y pixel coordinate of the upper-left corner of the ROI.</p>"; ROIY0_Label.SetText( "Top:" ); ROIY0_Label.SetFixedWidth( labelWidth2 ); ROIY0_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); ROIY0_Label.SetToolTip( roiY0ToolTip ); ROIY0_SpinBox.SetRange( 0, int_max ); ROIY0_SpinBox.SetToolTip( roiY0ToolTip ); ROIY0_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&BackgroundNeutralizationInterface::__ROI_SpinValueUpdated, w ); ROIRow1_Sizer.SetSpacing( 4 ); ROIRow1_Sizer.Add( ROIX0_Label ); ROIRow1_Sizer.Add( ROIX0_SpinBox ); ROIRow1_Sizer.Add( ROIY0_Label ); ROIRow1_Sizer.Add( ROIY0_SpinBox ); ROIRow1_Sizer.AddStretch(); const char* roiWidthToolTip = "<p>Width of the ROI in pixels.</p>"; ROIWidth_Label.SetText( "Width:" ); ROIWidth_Label.SetFixedWidth( labelWidth1 - w.LogicalPixelsToPhysical( 6 + DELTA_FRAME ) ); ROIWidth_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); ROIWidth_Label.SetToolTip( roiWidthToolTip ); ROIWidth_SpinBox.SetRange( 0, int_max ); ROIWidth_SpinBox.SetToolTip( roiWidthToolTip ); ROIWidth_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&BackgroundNeutralizationInterface::__ROI_SpinValueUpdated, w ); const char* roiHeightToolTip = "<p>Height of the ROI in pixels.</p>"; ROIHeight_Label.SetText( "Height:" ); ROIHeight_Label.SetFixedWidth( labelWidth2 ); ROIHeight_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); ROIHeight_Label.SetToolTip( roiHeightToolTip ); ROIHeight_SpinBox.SetRange( 0, int_max ); ROIHeight_SpinBox.SetToolTip( roiHeightToolTip ); ROIHeight_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&BackgroundNeutralizationInterface::__ROI_SpinValueUpdated, w ); ROISelectPreview_Button.SetText( "From Preview" ); ROISelectPreview_Button.SetToolTip( "<p>Import ROI coordinates from an existing preview.</p>" ); ROISelectPreview_Button.OnClick( (Button::click_event_handler)&BackgroundNeutralizationInterface::__ROI_Click, w ); ROISelectPreview_Button.OnViewDrag( (Control::view_drag_event_handler)&BackgroundNeutralizationInterface::__ViewDrag, w ); ROISelectPreview_Button.OnViewDrop( (Control::view_drop_event_handler)&BackgroundNeutralizationInterface::__ViewDrop, w ); ROIRow2_Sizer.SetSpacing( 4 ); ROIRow2_Sizer.Add( ROIWidth_Label ); ROIRow2_Sizer.Add( ROIWidth_SpinBox ); ROIRow2_Sizer.Add( ROIHeight_Label ); ROIRow2_Sizer.Add( ROIHeight_SpinBox ); ROIRow2_Sizer.AddSpacing( 12 ); ROIRow2_Sizer.Add( ROISelectPreview_Button ); ROIRow2_Sizer.AddStretch(); ROI_Sizer.SetMargin( 6 ); ROI_Sizer.SetSpacing( 4 ); ROI_Sizer.Add( ROIRow1_Sizer ); ROI_Sizer.Add( ROIRow2_Sizer ); ROI_GroupBox.SetSizer( ROI_Sizer ); // Global_Sizer.SetMargin( 8 ); Global_Sizer.SetSpacing( 4 ); Global_Sizer.Add( BackgroundReferenceView_Sizer ); Global_Sizer.Add( BackgroundLow_NumericControl ); Global_Sizer.Add( BackgroundHigh_NumericControl ); Global_Sizer.Add( Mode_Sizer ); Global_Sizer.Add( TargetBackground_NumericControl ); Global_Sizer.Add( ROI_GroupBox ); // w.SetSizer( Global_Sizer ); w.EnsureLayoutUpdated(); w.AdjustToContents(); w.SetFixedSize(); } // ---------------------------------------------------------------------------- } // pcl // ---------------------------------------------------------------------------- // EOF BackgroundNeutralizationInterface.cpp - Released 2021-04-09T19:41:48Z
43.509565
145
0.6664
fmeschia