blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
95254a8b15093515c15e287853ed55824e7bd078 | 096f86d816a86bf0fe774dcd350d191820bf2290 | /src/airdrone_gazebo/drone/plugins/src/gazebo_quadrotor_propulsion.cpp | 47cad183e5aafe7e1c3608f78bbe9731e9104cc1 | [
"MIT"
] | permissive | ncos/mipt-airdrone | f1e1d75b8d1a6cc6a28eb80f922620fd1f78adba | 75450c6fda05303b04c190682aa5c8fc029327f6 | refs/heads/master | 2016-09-06T18:53:41.039844 | 2015-03-13T23:18:59 | 2015-03-13T23:18:59 | 17,603,073 | 2 | 2 | null | 2014-10-10T17:00:37 | 2014-03-10T18:13:03 | C | UTF-8 | C++ | false | false | 10,766 | cpp | gazebo_quadrotor_propulsion.cpp | //=================================================================================================
// Copyright (c) 2012, Johannes Meyer, TU Darmstadt
// 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 Flight Systems and Automatic Control group,
// TU Darmstadt, 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 HOLDER 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 "../include/gazebo_quadrotor_propulsion.h"
#include "../include/helpers.h"
#include <gazebo/common/Events.hh>
#include <gazebo/physics/physics.hh>
#include <rosgraph_msgs/Clock.h>
namespace gazebo {
using namespace common;
using namespace math;
using namespace hector_quadrotor_model;
GazeboQuadrotorPropulsion::GazeboQuadrotorPropulsion()
: node_handle_(0)
{
}
GazeboQuadrotorPropulsion::~GazeboQuadrotorPropulsion()
{
event::Events::DisconnectWorldUpdateBegin(updateConnection);
if (node_handle_) {
node_handle_->shutdown();
if (callback_queue_thread_.joinable())
callback_queue_thread_.join();
delete node_handle_;
}
}
////////////////////////////////////////////////////////////////////////////////
// Load the controller
void GazeboQuadrotorPropulsion::Load(physics::ModelPtr _model, sdf::ElementPtr _sdf)
{
world = _model->GetWorld();
link = _model->GetLink();
// default parameters
namespace_.clear();
param_namespace_ = "quadrotor_propulsion";
trigger_topic_ = "quadro/trigger";
command_topic_ = "command/motor";
pwm_topic_ = "motor_pwm";
wrench_topic_ = "wrench_out";
supply_topic_ = "supply";
status_topic_ = "motor_status";
control_tolerance_ = ros::Duration();
control_delay_ = ros::Duration();
// load parameters
if (_sdf->HasElement("robotNamespace")) namespace_ = _sdf->GetElement("robotNamespace")->Get<std::string>();
if (_sdf->HasElement("paramNamespace")) param_namespace_ = _sdf->GetElement("paramNamespace")->Get<std::string>();
if (_sdf->HasElement("triggerTopic")) trigger_topic_ = _sdf->GetElement("triggerTopic")->Get<std::string>();
if (_sdf->HasElement("topicName")) command_topic_ = _sdf->GetElement("topicName")->Get<std::string>();
if (_sdf->HasElement("pwmTopicName")) pwm_topic_ = _sdf->GetElement("pwmTopicName")->Get<std::string>();
if (_sdf->HasElement("wrenchTopic")) wrench_topic_ = _sdf->GetElement("wrenchTopic")->Get<std::string>();
if (_sdf->HasElement("supplyTopic")) supply_topic_ = _sdf->GetElement("supplyTopic")->Get<std::string>();
if (_sdf->HasElement("statusTopic")) status_topic_ = _sdf->GetElement("statusTopic")->Get<std::string>();
if (_sdf->HasElement("voltageTopicName")) {
gzwarn << "[quadrotor_propulsion] Plugin parameter 'voltageTopicName' is deprecated! Plese change your config to use "
<< "'topicName' for MotorCommand messages or 'pwmTopicName' for MotorPWM messages." << std::endl;
pwm_topic_ = _sdf->GetElement("voltageTopicName")->Get<std::string>();
}
// set control timing parameters
controlTimer.Load(world, _sdf, "control");
motorStatusTimer.Load(world, _sdf, "motorStatus");
if (_sdf->HasElement("controlTolerance")) control_tolerance_.fromSec(_sdf->GetElement("controlTolerance")->Get<double>());
if (_sdf->HasElement("controlDelay")) control_delay_.fromSec(_sdf->GetElement("controlDelay")->Get<double>());
// set initial supply voltage
if (_sdf->HasElement("supplyVoltage")) model_.setInitialSupplyVoltage(_sdf->GetElement("supplyVoltage")->Get<double>());
// Make sure the ROS node for Gazebo has already been initialized
if (!ros::isInitialized())
{
ROS_FATAL_STREAM("A ROS node for Gazebo has not been initialized, unable to load plugin. "
<< "Load the Gazebo system plugin 'libgazebo_ros_api_plugin.so' in the gazebo_ros package)");
return;
}
node_handle_ = new ros::NodeHandle(namespace_);
// get model parameters
if (!model_.configure(ros::NodeHandle(*node_handle_, param_namespace_))) {
gzwarn << "[quadrotor_propulsion] Could not properly configure the propulsion plugin. Make sure you loaded the parameter file." << std::endl;
return;
}
// publish trigger
if (!trigger_topic_.empty())
{
ros::AdvertiseOptions ops;
ops.callback_queue = &callback_queue_;
ops.init<rosgraph_msgs::Clock>(trigger_topic_, 10);
trigger_publisher_ = node_handle_->advertise(ops);
}
// subscribe voltage command
if (!command_topic_.empty())
{
ros::SubscribeOptions ops;
ops.callback_queue = &callback_queue_;
ops.init<airdrone_gazebo::MotorCommand>(command_topic_, 1, boost::bind(&QuadrotorPropulsion::addCommandToQueue, &model_, _1));
command_subscriber_ = node_handle_->subscribe(ops);
}
// subscribe pwm command
if (!pwm_topic_.empty())
{
ros::SubscribeOptions ops;
ops.callback_queue = &callback_queue_;
ops.init<airdrone_gazebo::MotorPWM>(pwm_topic_, 1, boost::bind(&QuadrotorPropulsion::addPWMToQueue, &model_, _1));
pwm_subscriber_ = node_handle_->subscribe(ops);
}
// publish wrench
if (!wrench_topic_.empty())
{
ros::AdvertiseOptions ops;
ops.callback_queue = &callback_queue_;
ops.init<geometry_msgs::Wrench>(wrench_topic_, 10);
wrench_publisher_ = node_handle_->advertise(ops);
}
// publish and latch supply
if (!supply_topic_.empty())
{
ros::AdvertiseOptions ops;
ops.callback_queue = &callback_queue_;
ops.latch = true;
ops.init<airdrone_gazebo::Supply>(supply_topic_, 10);
supply_publisher_ = node_handle_->advertise(ops);
supply_publisher_.publish(model_.getSupply());
}
// publish motor_status
if (!status_topic_.empty())
{
ros::AdvertiseOptions ops;
ops.callback_queue = &callback_queue_;
ops.init<airdrone_gazebo::MotorStatus>(status_topic_, 10);
motor_status_publisher_ = node_handle_->advertise(ops);
}
// callback_queue_thread_ = boost::thread( boost::bind( &GazeboQuadrotorPropulsion::QueueThread,this ) );
Reset();
// New Mechanism for Updating every World Cycle
// Listen to the update event. This event is broadcast every
// simulation iteration.
updateConnection = event::Events::ConnectWorldUpdateBegin(
boost::bind(&GazeboQuadrotorPropulsion::Update, this));
}
////////////////////////////////////////////////////////////////////////////////
// Update the controller
void GazeboQuadrotorPropulsion::Update()
{
// Get simulator time
Time current_time = world->GetSimTime();
Time dt = current_time - last_time_;
last_time_ = current_time;
if (dt <= 0.0) return;
// Send trigger
bool trigger = controlTimer.getUpdatePeriod() > 0.0 ? controlTimer.update() : false;
if (trigger && trigger_publisher_) {
rosgraph_msgs::Clock clock;
clock.clock = ros::Time(current_time.sec, current_time.nsec);
trigger_publisher_.publish(clock);
ROS_DEBUG_STREAM_NAMED("quadrotor_propulsion", "Sent a trigger message at t = " << current_time.Double() << " (dt = " << (current_time - last_trigger_time_).Double() << ")");
last_trigger_time_ = current_time;
}
// Get new commands/state
callback_queue_.callAvailable();
// Process input queue
model_.processQueue(ros::Time(current_time.sec, current_time.nsec), control_tolerance_, control_delay_, (model_.getMotorStatus().on && trigger) ? ros::WallDuration(1.0) : ros::WallDuration(), &callback_queue_);
// fill input vector u for propulsion model
geometry_msgs::Twist twist;
fromVector(link->GetRelativeLinearVel(), twist.linear);
fromVector(link->GetRelativeAngularVel(), twist.angular);
model_.setTwist(twist);
// update the model
model_.update(dt.Double());
// get wrench from model
Vector3 force, torque;
toVector(model_.getWrench().force, force);
toVector(model_.getWrench().torque, torque);
// publish wrench
if (wrench_publisher_) {
wrench_publisher_.publish(model_.getWrench());
}
// publish motor status
if (motor_status_publisher_ && motorStatusTimer.update() /* && current_time >= last_motor_status_time_ + control_period_ */) {
airdrone_gazebo::MotorStatus motor_status = model_.getMotorStatus();
motor_status.header.stamp = ros::Time(current_time.sec, current_time.nsec);
motor_status_publisher_.publish(motor_status);
last_motor_status_time_ = current_time;
}
// publish supply
if (supply_publisher_ && current_time >= last_supply_time_ + 1.0) {
supply_publisher_.publish(model_.getSupply());
last_supply_time_ = current_time;
}
// set force and torque in gazebo
link->AddRelativeForce(force);
link->AddRelativeTorque(torque - link->GetInertial()->GetCoG().Cross(force));
}
////////////////////////////////////////////////////////////////////////////////
// Reset the controller
void GazeboQuadrotorPropulsion::Reset()
{
model_.reset();
last_time_ = Time();
last_trigger_time_ = Time();
last_motor_status_time_ = Time();
last_supply_time_ = Time();
}
////////////////////////////////////////////////////////////////////////////////
// custom callback queue thread
void GazeboQuadrotorPropulsion::QueueThread()
{
static const double timeout = 0.01;
while (node_handle_->ok())
{
callback_queue_.callAvailable(ros::WallDuration(timeout));
}
}
// Register this plugin with the simulator
GZ_REGISTER_MODEL_PLUGIN(GazeboQuadrotorPropulsion)
} // namespace gazebo
|
db75e7350a7ed472fe5391985a9a0e06f957d9af | baf7927dcb69ea476a4e601621fea802c0616f13 | /src/engine/Terrain.cpp | c0462dc8a583ce167e450fdfb4c697a6e1d67ede | [
"MIT"
] | permissive | Zycon42/Heightmap | d5227f91f90c06802d380fc6d080c406c7978c33 | 63d46abfc77f0427f604d68edfb8a4fe0117e7d1 | refs/heads/master | 2016-08-04T17:22:34.345772 | 2013-12-20T00:14:47 | 2013-12-20T00:14:47 | 15,296,378 | 1 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 2,985 | cpp | Terrain.cpp | /**
* @file Terrain.cpp
*
* @author Jan Dušek <xdusek17@stud.fit.vutbr.cz>
* @date 2013
*/
#include "Terrain.h"
#include "ArrayRef.h"
#include <cassert>
struct Vertex {
glm::vec3 pos, normal;
};
Terrain::Terrain(const HeightMap& heightMap) {
// check that sizes match to avoid buffer overflow
assert((heightMap.height * heightMap.width) == heightMap.heights.size());
auto vertices = computeVertices(heightMap);
std::vector<VertexElement> layout = { VertexElement(3), VertexElement(3) };
m_mesh.loadVertices(vertices, vertices.size() / sizeof(Vertex), layout);
m_mesh.loadIndices(computeIndices(heightMap));
m_mesh.setPrimitiveType(PrimitiveType::TriangleStrip);
}
std::vector<uint32_t> Terrain::computeIndices(const HeightMap& map) {
size_t numIndices = (map.width * 2) * (map.height - 1) + (map.height - 2);
std::vector<uint32_t> result;
result.resize(numIndices);
size_t index = 0;
for (size_t y = 0; y < map.height - 1; ++y) {
// Even rows move left to right, odd rows move right to left.
if (y % 2 == 0) {
size_t x;
for (x = 0; x < map.width; ++x) {
result[index++] = x + (y * map.width);
result[index++] = x + (y * map.width) + map.width;
}
// Insert degenerate vertex if this isn't the last row
if (y != map.height - 2) {
result[index++] = --x + (y * map.width);
}
} else {
int x;
for (x = map.width - 1; x >= 0; --x) {
result[index++] = x + (y * map.width);
result[index++] = x + (y * map.width) + map.width;
}
// Insert degenerate vertex if this isn't the last row
if (y != map.height - 2) {
result[index++] = ++x + (y * map.width);
}
}
}
return result;
}
template <typename T>
class ArrayMapper
{
public:
ArrayMapper(void* arr, size_t pitch) : m_arr(arr), m_pitch(pitch) { }
T& operator()(size_t x, size_t y) {
char* arr = reinterpret_cast<char*>(m_arr);
return *reinterpret_cast<T*>(arr + ((y * m_pitch + x) * sizeof(T)));
}
private:
void* m_arr;
size_t m_pitch;
};
std::vector<char> Terrain::computeVertices(const HeightMap& map) {
std::vector<char> storage;
// allocate vertices storage
storage.resize(sizeof(Vertex) * map.heights.size());
ArrayMapper<Vertex> vertices{ storage.data(), map.width };
// generate positions
for (size_t y = 0; y < map.height; ++y) {
for (size_t x = 0; x < map.width; ++x) {
vertices(x, y).pos = glm::vec3(x, y, map.heights[y * map.width + x]);
}
}
// generate normals - we need to do it in separate loop because this algorithm looks ahead
for (size_t y = 0; y < map.height; ++y) {
for (size_t x = 0; x < map.width; ++x) {
float z0 = vertices(x, y).pos.z;
float az = (x + 1 < map.width) ? (vertices(x + 1, y).pos.z) : z0;
float bz = (y + 1 < map.height) ? (vertices(x, y + 1).pos.z) : z0;
float cz = (x > 0) ? (vertices(x - 1, y).pos.z) : z0;
float dz = (y > 0) ? (vertices(x, y - 1).pos.z) : z0;
vertices(x, y).normal = glm::normalize(glm::vec3(cz - az, dz - bz, 2.0f));
}
}
return storage;
}
|
02e93be987d945f72b1fab3db4dcdf0cd24f4662 | f699576e623d90d2e07d6c43659a805d12b92733 | /WTLOnline-SDK/SDK/WTLOnline_UI_HUD_SteamInventoryDropArea_classes.hpp | 62189b8403a51ad3ee993e061a2b94d4ce96fc61 | [] | no_license | ue4sdk/WTLOnline-SDK | 2309620c809efeb45ba9ebd2fc528fa2461b9ca0 | ff244cd4118c54ab2048ba0632b59ced111c405c | refs/heads/master | 2022-07-12T13:02:09.999748 | 2019-04-22T08:22:35 | 2019-04-22T08:22:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 805 | hpp | WTLOnline_UI_HUD_SteamInventoryDropArea_classes.hpp | #pragma once
// Will To Live Online (0.57) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "WTLOnline_UI_HUD_SteamInventoryDropArea_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// WidgetBlueprintGeneratedClass UI_HUD_SteamInventoryDropArea.UI_HUD_SteamInventoryDropArea_C
// 0x0000 (0x02E8 - 0x02E8)
class UUI_HUD_SteamInventoryDropArea_C : public UWTLHUDBaseActionDropArea
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>(_xor_("WidgetBlueprintGeneratedClass UI_HUD_SteamInventoryDropArea.UI_HUD_SteamInventoryDropArea_C"));
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
ae4a96187b192941d7f38a123cf1c48092667e5d | 4100749ca52cee89bc288fb6c5b1511d56ee305a | /Project1/kruscal_TPATH.cpp | 72956a0db34eed6d6af0e341a658e3b51e65a5be | [] | no_license | jisukJ/algorithm-source-code | 20b981d020413db314a59f915090c7c0a58177b0 | 27656a6ffd90c7a98153167d13354e7efc24258e | refs/heads/master | 2023-04-18T12:04:38.845848 | 2021-05-04T11:50:18 | 2021-05-04T11:50:18 | 339,270,029 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,410 | cpp | kruscal_TPATH.cpp | #include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <math.h>
#include <iomanip>
using namespace std;
const int MAX_V = 2000;
vector<pair<int, int>>adj[MAX_V];
int V, E,C;
int ans;
const int INF = 1000000000;
vector<pair<int,pair<int,int>>> weight;
vector<int>edges;
struct disjointSet {
vector<int>rank, parent;
disjointSet(int val) : rank(val), parent(val) {
for (int i = 0; i < val; ++i)
parent[i] = i;
}
int find(int u)
{
if (parent[u] == u)
return u;
else parent[u] = find(parent[u]);
}
void merge(int u, int v)
{
u = find(u), v = find(v);
if (u == v)
return;
if (rank[u] < rank[v])
swap(u, v);
parent[v] = u;
if (rank[u] == rank[v])
rank[u]++;
}
};
int kruscal(vector<pair<int,int>>& selected , int lo,int hi)
{
selected.clear();
int ret = weight[hi].first - weight[lo].first;
disjointSet set(V);
for (int i = lo; i <= hi; ++i)
{
int u=weight[i].second.first;
int v = weight[i].second.second;
if (set.find(u) ==set.find(v))
continue;
selected.push_back(make_pair(u, v));
set.merge(u, v);
}
return ret;
}
bool hasPath(int hi, int lo)
{
queue<int> q;
vector<int> visit(MAX_V, 0);
q.push(0);
visit[0] = 1;
while (!q.empty()) {
int here = q.front();
q.pop();
if (here == V - 1) break;
for (int i = 0; i < adj[here].size(); ++i) {
int there = adj[here][i].first;
int velocity = adj[here][i].second;
if (velocity<lo || velocity>hi || visit[there]) continue;
visit[there] = 1;
q.push(there);
}
}
if (visit[V - 1]) return true;
return false;
}
int minUpperBound(int low)
{
int lo = low - 1, hi = edges.size();
while (lo + 1 < hi)
{
int mid = (lo + hi) / 2;
if (hasPath(edges[low], edges[mid]))
hi = mid;
else
lo = mid;
}
if (hi == edges.size())
return INF;
return edges[hi];
}
int main()
{
cin >> C;
for (int test = 0; test < C; ++test)
{
cin >> V >> E;
for (int i = 0; i < V; ++i)
adj[i].clear();
weight.clear();
edges.clear();
for (int i = 0; i < E; ++i)
{
int a, b, c;
cin >> a >> b >> c;
if(c!=0)
{
adj[a].push_back(make_pair(b, c));
adj[b].push_back(make_pair(a, c));
weight.push_back(make_pair(c,make_pair(a,b)));
weight.push_back(make_pair(c, make_pair(b, a)));
edges.push_back(c);
}
}
sort(edges.begin(), edges.end());
sort(weight.begin(), weight.end());
ans = 1000;
cout << ans<<endl;
}
} |
86df985627c548f7079a98a6070fcb2ee489d068 | 5d6237b731b9d3bf3e43a3de6bd67df3ccfa9b45 | /linux/css.cc | 17fba0bef480028767f9cb31f05b92852abd601a | [] | no_license | jamshidh/translato | ed8d7f7f32e3d0077cb87966c7210b37200211b4 | 68043b9ecc8d2600e6b597f205b6e10edb15a4a0 | refs/heads/master | 2021-01-22T20:54:17.221599 | 2015-11-06T23:31:49 | 2015-11-06T23:31:49 | 34,648,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,081 | cc | css.cc | #include <gtk/gtk.h>
#include <gtk/gtkmain.h>
void applyCSSToWindow(const char *styleString) {
GtkCssProvider *provider;
GdkDisplay *display;
GdkScreen *screen;
provider = gtk_css_provider_new();
display = gdk_display_get_default ();
screen = gdk_display_get_default_screen (display);
gtk_style_context_add_provider_for_screen (screen,
GTK_STYLE_PROVIDER (provider),
GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
gtk_css_provider_load_from_data (GTK_CSS_PROVIDER(provider), styleString,
/*" GtkWindow {\n"
" -GtkWidget-focus-line-width: 0;\n"
" background-color: blue;\n"
"}\n"
" GtkGrid {\n"
" padding: 4px;\n"
" border: 4px solid orange;\n"
"}\n"
" GtkLabel {\n"
//" background-color: green;\n"
//" border: red 10px solid;\n"
//" border-top: orange 10px solid;\n"
//" border-radius: 10px;\n"
" padding: 10px;\n"
"}\n", */
-1, NULL);
g_object_unref (provider);
}
void applyCSSToWidget(GtkWidget *widget) {
GtkCssProvider *provider;
provider = gtk_css_provider_new();
gtk_style_context_add_provider(gtk_widget_get_style_context(widget), GTK_STYLE_PROVIDER(provider), G_MAXUINT);
gtk_css_provider_load_from_data (GTK_CSS_PROVIDER(provider),
" GtkLabel {\n"
" background-color: yellow;\n"
" border-top: green solid 10px;\n"
" margin: 20px;\n"
"}\n", -1, NULL);
}
|
2c76785611a1faf41b1ffca107dd3a2ad80ba36c | 492a621d240e8e249f82a3e5ca387180190fd0c0 | /Proyecto3/3/p3.cpp | 6c81befd2858e59d0739555a8ab3633da9f61f12 | [] | no_license | joseluisjb1990/ci5651 | e194ac5170a8b09536b0706426374b86e7910d21 | 3be876adfff06cb3a07e91fc368c66d63d61bad0 | refs/heads/master | 2021-01-20T10:36:30.039247 | 2015-03-15T23:38:59 | 2015-03-15T23:38:59 | 29,275,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,698 | cpp | p3.cpp | #include <iostream>
#include <vector>
#include <sstream>
using namespace std;
int n;
int *numeros;
int ***memoMatrix;
void initMatrix(int ***memoMatrix)
{
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
for(int k = 0; k < n; k++)
memoMatrix[i][j][k] = 0;
}
void printMatrix(int ***memoMatrix)
{
for(int i = 0; i < n; i++){
cout << "Matriz " << i << endl;
for(int j = 0; j < n; j++){
for(int k = 0; k < n; k++){
cout << memoMatrix[i][j][k] << " ";
}
cout << endl;
}
}
}
void dp(int asc, int des, int idx)
{
if(idx < n)
{
if(asc == -1) dp(idx, des, idx+1);
else if(numeros[idx] > numeros[asc]) dp(idx, des, idx+1);
if(des == -1) dp(asc, idx, idx+1);
else if(numeros[idx] < numeros[des]) dp(asc, idx, idx+1);
if(des != -1 && asc != -1) memoMatrix[asc][des][idx] = 1 + memoMatrix[asc][des][idx-1]; dp(asc, des, idx+1);
//cout << numeros[idx] << " " << numeros[asc] << " " << asc << " " << des << " " << idx << " " << n << endl;
}
}
int main()
{
int buff;
string entrada;
cin >> n;
while(n != -1)
{
numeros = new int[n];
for(int i = 0; i < n; i++)
{
cin >> numeros[i];
}
memoMatrix = new int**[n];
for(int i = 0; i < n; i++)
{
memoMatrix[i] = new int*[n];
for(int j = 0; j < n; j++)
memoMatrix[i][j] = new int[n];
}
initMatrix(memoMatrix);
dp(-1, -1, 0);
//printMatrix(memoMatrix);
int min = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
if(memoMatrix[i][j][n-1] < min)
min = memoMatrix[i][j][n-1];
cout << min << endl;
cin >> n;
}
}
|
8e669577a1d164b1244a094905b5c83f44bfc8f6 | 7b729c4839ddb57a9cad7f84bdaaa35aa871c59b | /Playlist/Playlist.h | 901b2e5fc19c36a9612c9638e6ea203fc0c22cf0 | [] | no_license | tuanxn/Playlist | 1683f4fabe5779c67c6a93dfeb9053cce37f7a12 | 859da104af4ad0eb9da661e2a73c13f50696ebf4 | refs/heads/master | 2022-11-08T20:38:57.251684 | 2020-06-23T14:35:04 | 2020-06-23T14:35:04 | 273,967,666 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,661 | h | Playlist.h | // Important implementation note: With the exception of to_string() and find...()
// all Playlist methods below should operate in a constant amount of time
// regardless of the size of the Playlist instance.
//
// The semantics of prev_to_current is such that it always points to the
// node *BEFORE* the cursor (current). This makes the manipulations easy because
// we can only look forward (and not back) in singly linked lists.
#ifndef Playlist_h
#define Playlist_h
#include <string>
#include <sstream>
using namespace std;
class Playlist {
public:
// Inner public class ---------------------------------------------------
// The client can refer to it by using the qualified name Playlist::Song_Entry
class Song_Entry {
private:
int _id;
string _name;
public:
Song_Entry(int id = 0, string name = "Unnamed")
: _id(id), _name(name) {}
int get_id() const { return _id; }
string get_name() const { return _name; }
bool set_id(int id);
bool set_name(string name);
bool operator==(const Song_Entry& that) {
return this->_id == that._id && this->_name == that._name;
}
bool operator!=(const Song_Entry& that) {
return !(*this == that);
}
friend std::ostream& operator<<(ostream& os, const Song_Entry& s) {
return os << "{ id: " << s.get_id() << ", name: " << s.get_name() << " }";
}
friend class Tests; // Don't remove this line
};
private:
// This is going to be our inner private class. The client doesn't need to
// know.
class Node {
private:
Song_Entry _song;
Node* _next;
public:
Node(const Song_Entry& song = Song_Entry(), Node* next = nullptr) : _song(song), _next(next) {}
~Node(); // Do not do recursive free
Song_Entry& get_song() { return _song; }
Node* get_next() { return _next; }
Node* insert_next(Node* p);
Node* remove_next();
friend class Tests; // Don't remove this line
};
private:
Node* _head, * _tail, * _prev_to_current;
size_t _size;
public:
Playlist();
~Playlist();
size_t get_size() const { return _size; }
Song_Entry& get_current_song() const;
// The following return "this" on success, null on failure. See the spec
// for why.
Playlist* clear();
Playlist* rewind();
Playlist* push_back(const Song_Entry& s);
Playlist* push_front(const Song_Entry& s);
Playlist* insert_at_cursor(const Song_Entry& s);
Playlist* remove_at_cursor();
Playlist* advance_cursor();
Playlist* circular_advance_cursor();
// The following return the target payload (or sentinel) reference on success
Song_Entry& find_by_id(int id) const;
Song_Entry& find_by_name(string songName) const;
string to_string() const;
friend class Tests; // Don't remove this line
};
#endif |
307881a52f2973438718ad5d0ac1638ee6e60da5 | 7cddd418f09223d71dd5758559f133921ad878ac | /2018/test0313-2/test02.cpp | 1a33d1a3e2e17da15fab4151c4857cd2da4143f4 | [] | no_license | lijuni/allCPPTest | 599b946eae46da919f1e4a5aba2b5ea1c1425688 | 9c3b23e61d12bc911cb1f9c3eb0a5cccabec6967 | refs/heads/master | 2020-03-19T09:19:42.551206 | 2018-06-06T05:42:01 | 2018-06-06T05:42:01 | 136,278,615 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 158 | cpp | test02.cpp | #include<iostream>
using namespace std;
int main()
{
constexpr size_t array_size=10;
int a[array_size];
for(size_t i=0; i<array_size; ++i)
a[i]=i;
}
|
74d333bbd18187c4472f0d39ba51c15ebfc69001 | ed9404757f5ee1a2270da3520b6dd797f91c1f5b | /track_oracle/file_formats/track_kw18/track_kw18_instances.cxx | c4fd373008ce16b1de34c826a96ff052ab1c0094 | [
"BSD-3-Clause"
] | permissive | tao558/kwiver | 5d88b7868441ad6222fa2f08ab46a6544271830f | 51d671228ada60dd41e465cf9c282cba8614b057 | refs/heads/master | 2021-07-04T09:57:36.587434 | 2020-10-14T13:26:40 | 2020-10-14T13:26:40 | 304,072,315 | 1 | 0 | NOASSERTION | 2020-10-14T16:24:51 | 2020-10-14T16:24:51 | null | UTF-8 | C++ | false | false | 824 | cxx | track_kw18_instances.cxx | /*ckwg +5
* Copyright 2017 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include <vgl/vgl_point_2d.h>
#include <vgl/vgl_box_2d.h>
#include <vital/vital_config.h>
#include <track_oracle/file_formats/track_kw18/track_kw18_export.h>
#define TRACK_FIELD_IO_PROXY_EXPORT TRACK_KW18_EXPORT
#include <track_oracle/core/track_field_io_proxy_instantiation.h>
TRACK_FIELD_IO_PROXY_INSTANCES( int );
TRACK_FIELD_IO_PROXY_INSTANCES( vgl_point_2d<double> );
TRACK_FIELD_IO_PROXY_INSTANCES( vgl_box_2d<double> );
TRACK_FIELD_IO_PROXY_INSTANCES( double );
TRACK_FIELD_IO_PROXY_INSTANCES( unsigned );
TRACK_FIELD_IO_PROXY_INSTANCES( uint64_t );
#undef TRACK_FIELD_IO_PROXY_EXPORT
|
aa5a4f1790863777689ed02f7291a1dfa7a86508 | 29e866d407dd8a12b3e87a802efe3809913891f4 | /test/bls_c256_test.cpp | f433b78109fd0fc95fb37f072d7b73a9f4844cf4 | [
"BSD-3-Clause"
] | permissive | prysmaticlabs/mcl | 9eaedf666e04c844543af573f8c867e71307e1a0 | 79b3a33e21072712f00985ed2adf34b3bcf0d74e | refs/heads/master | 2020-04-02T07:36:34.316310 | 2019-01-08T16:54:17 | 2019-01-08T16:54:17 | 154,205,223 | 2 | 1 | NOASSERTION | 2019-06-19T20:43:10 | 2018-10-22T19:39:09 | Assembly | UTF-8 | C++ | false | false | 54 | cpp | bls_c256_test.cpp | #define MCLBN_FP_UNIT_SIZE 4
#include "bls_c_test.hpp" |
6563f7e0d140169b63bb27b251309a0a4a225698 | 11b24a4e9313fddf721b552d736ea1ae9c98f05e | /mycat.cpp | 41ff9ef6f405d112c3a203d1f5a8fc4647749598 | [] | no_license | chefZau/Unix-FileSystem-Simulator | 3463b9e39d694da04a619c34abd97831e219530f | a9232ba2fe45d7d155558771dd42e5aeaf8b8bfc | refs/heads/master | 2023-02-26T03:45:17.243363 | 2021-01-31T15:18:38 | 2021-01-31T15:18:38 | 212,415,160 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 981 | cpp | mycat.cpp | /**
* @author MingCong Zhou
* @desc pass argument by command promomt, mymv linux command
* @date 2019/10/2
* @student_number 250945414
* @student_account MZHOU272
*/
#include "file.h"
/**
* Will dump the contents of all files given as parameters to the terminal.
* mycat: mycat filename1 filename2 ...
* display the contents of all of the files given as parameters to the command to the terminal.
* support more than one file as the original command does.
*
* @param argc the number of argument to be passed
* in this file you can pass as many argument as you want
* @param argv the char array of the element in this case
* is file1.txt file2.txt ...
* @return 0 when finish
*/
int main(int argc, char *argv[]) {
for (int i = 1 ; i < argc; ++i){
file source_file = file(argv[i]);
std::cout << std::ifstream(source_file.get_name()).rdbuf(); // print the entire file in one line
cout << '\n';
}
return 0;
}
|
73add14f4edd4f964899dd6777d8c646d60eadd3 | 682116aec2ecfddccbad6f6f2320b7bf5f2115fa | /maxcode/neuron/iv/src/lib/IV-2_6/compeditor.cpp | ccd604197a105a63bd8977de817e724d8698b6e4 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive"
] | permissive | Rauell/neuron | 251423831bb93577e74ae98cee2cb38b0f05e3f4 | f7f0a80122aec2b748aa2bef10b442fbeef8a12c | refs/heads/master | 2016-09-06T06:22:19.357913 | 2015-07-17T13:26:44 | 2015-07-17T13:26:44 | 30,427,231 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,403 | cpp | compeditor.cpp | #ifdef HAVE_CONFIG_H
#include <../../config.h>
#endif
/*
* Copyright (c) 1987, 1988, 1989, 1990, 1991 Stanford University
* Copyright (c) 1991 Silicon Graphics, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Stanford and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Stanford and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL STANFORD OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
/*
* CompletionEditor - StringEditor with completion
*/
#include <IV-2_6/InterViews/compeditor.h>
#include <IV-2_6/InterViews/textbuffer.h>
#include <IV-2_6/InterViews/world.h>
#include <OS/math.h>
#include <string.h>
CompletionEditor::CompletionEditor (
ButtonState* s, const char* sample1, const char* done1
) : StringEditor(s, sample1, done1) {
Init();
}
CompletionEditor::CompletionEditor (
const char* name, ButtonState* s, const char* sample1, const char* done1
) : StringEditor(name, s, sample1, done1) {
Init();
}
CompletionEditor::~CompletionEditor() { }
void CompletionEditor::Init () {
complete_ = CEComplete;
completions_ = nil;
count_ = 0;
}
void CompletionEditor::Completions (const char* list[], int c, char comp) {
complete_ = comp;
completions_ = list;
count_ = c;
}
boolean CompletionEditor::HandleChar (char c) {
if (c == complete_) {
InsertText("", 0);
const char* best = nil;
int match = 0;
int length = text->LineOffset(text->EndOfLine(0));
for (int i = 0; i < count_; ++i) {
for (int j = 0; ; ++j) {
char c = completions_[i][j];
if (j < length) {
if (text->Char(j) != c) {
match = Math::max(match, j);
break;
}
} else {
if (best == nil) {
best = completions_[i];
match = strlen(best);
break;
} else {
if (c == '\0' || best[j] != c) {
match = Math::min(match, j);
break;
}
}
}
}
}
Select(match, length);
if (match > length) {
InsertText(best+length, match-length);
} else if (best != nil && best[match] != '\0') {
GetWorld()->RingBell(1);
}
return false;
} else {
return StringEditor::HandleChar(c);
}
}
|
5e08b32debbab6b6d1f801afa9c7befe419db0d8 | f5fb39010aec616f37ac24427f6af61dcdfd3756 | /Pokemon_Mystery_Dungeon/Atile.cpp | ce5067e62eacb75c7dcbeb4ddd29b7e86fd60c3e | [] | no_license | JinKyong/Pokemon_Dungeon | 08df9ce02362a239525730aaa06aaa46c4bfbc0e | c595cdcb92f822b54e99e1a366f797712ad69475 | refs/heads/main | 2023-07-31T05:01:27.372424 | 2021-10-03T13:00:52 | 2021-10-03T13:00:52 | 384,614,340 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 564 | cpp | Atile.cpp | #include "stdafx.h"
#include "Atile.h"
Atile::Atile()
: _totalCost(0), _costFromStart(0),
_costToGoal(0), _parentNode(NULL),
_idX(0), _idY(0), _isOpen(true)
{
}
Atile::~Atile()
{
}
HRESULT Atile::init(int x, int y)
{
_idX = x;
_idY = y;
_center = PointMake(_idX * TILEWIDTH + (TILEWIDTH / 2),
_idY * TILEHEIGHT + (TILEHEIGHT / 2));
_totalCost = 0;
_costFromStart = 0;
_costToGoal = 0;
_isOpen = true;//갈수있는 타일인지 유무
_parentNode = nullptr; //제일 상위 타일 (계속 갱신되는 타일)
_attribute = "";
return S_OK;
} |
1de3edafa5dc98ee8fe8fc3eb4b6d1fca84e22a0 | ab4654ec4e18fecbd9e5c38690a5c773ad5fc9fe | /spoj/AMR10G.cpp | c655cad6ec696563bdce246b40af9af12d430548 | [] | no_license | khushhallchandra/algoPractice | ebfb91626cee3c55456310d763d10078ae3a3b47 | 598bad668b1139e47d892394fbebb287e746d9c6 | refs/heads/master | 2020-04-04T05:52:06.898170 | 2017-01-01T18:26:45 | 2017-01-01T18:26:45 | 45,354,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 342 | cpp | AMR10G.cpp | #include <iostream>
#include <algorithm>
using namespace std;
int main(){
int T, n, k, minDiff, a[20000];
cin>>T;
while(T--){
cin>>n>>k;
for(int i = 0; i < n; i++)
cin>>a[i];
sort(a,a+n);
minDiff = a[k-1]-a[0];
for(int i = 0; i + k <= n; i++)
minDiff = min(a[i+k-1]-a[i], minDiff);
cout<<minDiff<<endl;
}
return 0;
}
|
d7fc20cc73c88b70356fd3220a9f4d3705b03fde | d252cd575e6241f2fe3cb8b545acf8a50f6a346c | /www/snapper/engine/protocol.h | 58b3aa1b6fa413586bb4bcd6ba9a44934409cb34 | [
"BSD-3-Clause"
] | permissive | lenovo/Snapper | 2363fc42901f03d46c4cfb03c17e083170574249 | 4300739bbdf0b101c7ddd8be09c89f582bf47202 | refs/heads/master | 2020-07-08T20:57:33.116182 | 2020-02-02T15:22:20 | 2020-02-02T23:57:09 | 203,777,163 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,103 | h | protocol.h | //---------------------------------------------------------------------
// <copyright file="protocol.h" company="Lenovo">
// Copyright (c) 2018-present, Lenovo. All rights reserved. Licensed under BSD, see COPYING.BSD file for details.
// </copyright>
//---------------------------------------------------------------------
#pragma once
#include "sessions.h"
#include <string.h>
namespace snapper { namespace service
{
#define R_CHGPWD_EXPIRED 1
#define R_CHGPWD_FORCE 2
class PROTOCOL
{
public:
static int AUTH_BASIC;
static int AUTH_SESSION;
static int IDENT_SESSION;
static CURRENT_SESSION cur_session;
public:
static std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len);
static std::string base64_decode(std::string const& encoded_string);
static int do_authenticate( char *service, char *user, char *pwd, char *remoteip, void **pam_handle, char **displayname, int *pam_err );
static int do_login(char *service, char *user, char *pwd, char *family, char *remoteip, bool sessionless);
static int do_logout(bool sessionless);
#ifdef __SIM_X86__
static int do_login_x86(char *service, char *user, char *pwd, char *family, char *remoteip, bool sessionless);
static int do_logout_x86(bool sessionless);
#endif
static void set_cur_session(int handle, int aimid, char *loginname, char *displayname, char *remoteip, int privil, int uid, int pwdreason, char *orig);
static CURRENT_SESSION & get_cur_session();
static void clear_cur_session();
static int avail_sessions_num();
static std::vector<unsigned int> session_instances();
static int add_new_session(CURRENT_SESSION &sess_in, string &token_out);
static int open_session(char *session_token);
static int delete_session(string sid);
static int session_info(unsigned int slot, char *username, int *priv, char *sid, char *remoteip);
private:
static const std::string base64_chars;
static inline bool is_base64(unsigned char c)
{
return (isalnum(c) || (c == '+') || (c == '/'));
}
};
}}
|
79ce0e168fed2a03f7f92edb1a71d9f5c220d8b6 | d6da8f710dfd79b56d542617961e4a7126d2234e | /sourcefiles/JSONReader.h | 6c20e5ef279e0cc93222d16ad71311daa9e9d758 | [] | no_license | cgsingh/Basic-JSON-Parser | 0fcf90928a501398d6eb9859bd6f9ee2a558dbf1 | 962889a70419791591be063e8321441736f2a138 | refs/heads/master | 2020-12-18T15:08:33.865520 | 2020-01-21T20:10:33 | 2020-01-21T20:10:33 | 235,431,430 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 412 | h | JSONReader.h | /*
Name: Christopher Singh
Course: OOP345A
Date: October 10, 2014
*/
#include <iostream>
#include <string>
#ifndef JSONREADER_H
#define JSONREADER_H
namespace json
{
struct Collection
{
std::string objectName;
std::string name[50];
std::string value[50];
};
int read(const std::string&, std::string*);
int extract(const std::string* buffer, int, int&, Collection&);
int print(const Collection&);
}
#endif |
afc684064faf06c8b789ef35f9e4bcea9ebbebf1 | aa811a8479b36946e8c2e882f1e5ca5662f20d0d | /2D/CollisionQuadTree/src/main.cpp | 820a2df8c6a3d2141041ea88a9a3ece6493dbec0 | [] | no_license | MichaelSt98/NNS | 107747e8875d2ac513bdedb66a5ddf58a5163e2b | 597739cd00d05442bb6ace8bca24df5f141b290b | refs/heads/main | 2023-08-16T11:09:11.577019 | 2021-08-18T08:52:50 | 2021-08-18T08:52:50 | 331,554,105 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,452 | cpp | main.cpp | #include "../include/Rectangle.h"
#include "../include/Particle.h"
#include "../include/QuadTree.h"
#include <time.h>
#include <iostream>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/Font.hpp>
#include <SFML/Window/Event.hpp>
/** Settings **/
Rectangle WINDOW_BOUNDS = { 0, 0, 1280, 720 };
Rectangle MAP_BOUNDS = {0, 0, WINDOW_BOUNDS.width - 560, WINDOW_BOUNDS.height};
float RADIUS = 10;
unsigned CAPACITY = 8;
unsigned MAX_LEVEL = 5;
class Object {
public:
// velocity
double dx;
double dy;
//sf::RectangleShape shape;
sf::CircleShape shape;
Particle item;
Object(double _x, double _y, double _width, double _height) {
item = Particle({ _x, _y, _width, _height }, this);
shape.setPosition((float)item.bound.x, (float)item.bound.y);
shape.setRadius(RADIUS);
dx = (rand() % 201 - 100) * 0.05f; //0.05f;
dy = (rand() % 201 - 100) * 0.05f; //0.05f
}
void move() {
if (item.bound.x + dx < 0 || item.bound.x + item.bound.width + dx > MAP_BOUNDS.width)
dx = -dx;
if (item.bound.y + dy < 0 || item.bound.y + item.bound.height + dy > MAP_BOUNDS.height)
dy = -dy;
item.bound.x += dx;
item.bound.y += dy;
shape.setPosition((float)item.bound.x, (float)item.bound.y);
}
};
int main() {
// initialize random number generator
srand((unsigned)time(NULL));
// initialize window for graphical representation
sf::RenderWindow window(sf::VideoMode((unsigned)WINDOW_BOUNDS.width, (unsigned)WINDOW_BOUNDS.height), "QuadTree");
// set frame rate (limit)
window.setFramerateLimit(60);
// set mouse cursor invisible
window.setMouseCursorVisible(false);
// create QuadTree instance
QuadTree map = QuadTree(MAP_BOUNDS, CAPACITY, MAX_LEVEL);
std::vector<Object*> objects;
// font for graphical representation
sf::Font font;
font.loadFromFile("UbuntuMono-R.ttf");
map.setFont(font);
// info text (box)
sf::Text info("Info", font);
info.setCharacterSize(15);
info.setStyle(sf::Text::Bold);
info.setFillColor(sf::Color::White);
info.setPosition(720, 0);
// event handling
sf::Event event;
// mouse handling
sf::CircleShape mouseHandler;
mouseHandler.setOutlineThickness(3.0f);
mouseHandler.setFillColor(sf::Color(127, 0, 255, 0));
mouseHandler.setOutlineColor(sf::Color::Magenta);
Rectangle mouseBoundary = { 0, 0, 20, 20 };
// moving objects or frozen objects
bool freezeObjects = false;
/** GUI mainloop **/
while (window.isOpen()) {
// Update controls
while (window.pollEvent(event)) {
// Key events
if (event.type == sf::Event::KeyPressed) {
switch (event.key.code) {
// Esc = exit
case sf::Keyboard::Escape:
window.close();
break;
// F = freeze all objects
case sf::Keyboard::F:
freezeObjects = !freezeObjects;
break;
// C = clear quadtree and remove all objects
case sf::Keyboard::C:
map.clear();
for (auto &&obj : objects)
delete obj;
objects.clear();
break;
// Up = increase size of mouse box
case sf::Keyboard::Up:
mouseBoundary.width += 2;
mouseBoundary.height += 2;
break;
// Down = decrease size of mouse box
case sf::Keyboard::Down:
mouseBoundary.width -= 2;
mouseBoundary.height -= 2;
break;
default:
std::cout << "Not implemented" << std::endl;
}
}
// Window closed?
else if (event.type == sf::Event::Closed) {
window.close();
}
// ...
else {
// if event.type is not a KeyPressed nor Closed event
}
}
//clear the window
window.clear();
// draw the map (QuadTree)
map.draw(window);
/** Collisions **/
std::vector<Object*> mouseCollisions;
unsigned long long collisions = 0;
unsigned long long qtCollisionChecks = 0;
unsigned long long bfCollisionChecks = 0;
for (auto&& obj : objects) {
obj->shape.setFillColor(sf::Color::Blue);
if (mouseBoundary.intersects(obj->item.bound)) {
obj->shape.setFillColor(sf::Color::Red);
mouseCollisions.push_back(obj);
++collisions;
}
for (auto&& otherObj : objects)
++bfCollisionChecks;
for (auto&& found : map.getObjectsInBound_unchecked(obj->item.bound)) {
++qtCollisionChecks;
if (&obj->item != found && found->bound.intersects(obj->item.bound)) {
++collisions;
obj->shape.setFillColor(sf::Color::Red);
}
}
if (!freezeObjects) {
obj->move();
map.update(&obj->item);
}
window.draw(obj->shape);
}
// Update mouse box
mouseBoundary.x = sf::Mouse::getPosition(window).x;
mouseBoundary.y = sf::Mouse::getPosition(window).y;
mouseHandler.setRadius(RADIUS);
mouseHandler.setPosition((float)mouseBoundary.x, (float)mouseBoundary.y);
// Add objects on left click
if (sf::Mouse::isButtonPressed(sf::Mouse::Left) && MAP_BOUNDS.contains(mouseBoundary)) {
objects.push_back(new Object(mouseBoundary.getRight(), mouseBoundary.getTop(), rand() % 20 + 4, rand() % 20 + 4));
map.insert(&objects.back()->item);
}
// Remove objects on right click
if (sf::Mouse::isButtonPressed(sf::Mouse::Right)) {
for (auto&& obj : mouseCollisions) {
objects.erase(std::find(objects.begin(), objects.end(), obj));
map.remove(&obj->item);
delete obj;
}
}
// Display quadtree debug info
std::stringstream ss;
ss << "Total number of Children: " << map.totalNumberOfChildren()
<< "\nTotal number of Objects: " << map.totalNumberOfObjects()
<< "\nTotal number of Collisions: " << collisions
<< "\nQuadTree collision checks: " << qtCollisionChecks
<< "\nBrute force collision checks: " << bfCollisionChecks
<< "\nCollisions with mouse: " << mouseCollisions.size()
<< "\nObjects in this quad: " << map.getLeaf(mouseBoundary)->totalNumberOfObjects();
info.setString(ss.str());
window.draw(info);
if (MAP_BOUNDS.contains(mouseBoundary)) {
window.draw(mouseHandler);
}
window.display();
}
/** GUI was terminated
* cleanup (memory)
* **/
// delete map/QuadTree
map.clear();
// delete objects
for (auto&& obj : objects)
delete obj;
objects.clear();
}
|
0779badba60d609be0847b36c88b17849153a1d1 | f87be3873076c1e21ddd1378eb14b5f574887642 | /src/client/data/Friend.cpp | 04da6cb021f79cb228715d54135adc50d687fcd0 | [] | no_license | edd83/Skype-like | d50e29362e9f9f0e2e482fd8ef7f4684d70de848 | b30f16d2f9f528a70d7779d8864919196062e154 | refs/heads/master | 2021-05-02T17:52:59.399992 | 2018-02-09T11:01:33 | 2018-02-09T11:01:33 | 63,306,098 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 397 | cpp | Friend.cpp | #include "Friend.h"
Friend::Friend(QString const &name, eFriendStatus status)
{
this->_name = name;
this->_status = status;
}
Friend::~Friend()
{
}
QString const &Friend::getName() const
{
return (this->_name);
}
eFriendStatus Friend::getStatus() const
{
return (this->_status);
}
void Friend::setStatus(eFriendStatus status)
{
this->_status = status;
}
|
d58d993bebff6afae7bf358d5a5d66e5014cf263 | 5d3aa2c7603fcb287e764e30fc1ef5983d28ce5b | /Client/Header/Define.h | 3e79ebd8a7ba10243a0d8b9b7351dae1f181ae34 | [] | no_license | AlisaCodeDragon/AliceMadnessReturns | f46d3178df90c6ccf6da5c76a83c1f9ac809c28f | 80b322253846c50fc130cd540051a64440fe62e7 | refs/heads/main | 2023-03-18T14:26:37.758657 | 2021-02-08T13:43:35 | 2021-02-08T13:43:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | h | Define.h | #ifndef Define_h__
#define Define_h__
#include "Typedef.h"
#include "Function.h"
#include "sjhD3DXFunction.h"
#include "Macro.h"
using namespace Client;
#include "Enum.h"
#include "Const.h"
#include "Struct.h"
extern HWND g_hWnd;
extern HINSTANCE g_hInst;
#endif // Define_h__
|
31ad18dbf5f195acc5cb6052ab1342bb8835e998 | 12113d8c87d3181138117d5adfeeeb0eeab18202 | /DXFrameWork/DefaultWindow/Client/HPBar.cpp | 0f7c1720240107ae948c13deacb047dd13f36a79 | [] | no_license | Jangk/DX2D | 101156924da8dc36c3f16c06eae03f0b4a23fc41 | 4fa7021721e1c50efe75936b3cd9eddf4a6cc3d2 | refs/heads/master | 2020-12-22T18:13:23.135881 | 2020-03-11T01:25:19 | 2020-03-11T01:25:19 | 236,884,541 | 1 | 1 | null | null | null | null | UHC | C++ | false | false | 3,025 | cpp | HPBar.cpp | #include "stdafx.h"
#include "HPBar.h"
#include "Player.h"
#include "Character.h"
CHPBar::CHPBar()
{
}
CHPBar::~CHPBar()
{
Release();
}
int CHPBar::Update()
{
return 0;
}
void CHPBar::LateUpdate()
{
}
void CHPBar::Render()
{
D3DXMATRIX matScale, matTrans,matWorld;
const TEX_INFO* pTexInfo;
// 최대체력바
pTexInfo = m_pTextureMgr->GetTexInfo(L"UI", L"MaxHP", 1);
NULL_CHECK(pTexInfo);
m_pDeviceMgr->GetSprite()->SetTransform(&m_tInfo.matWorld);
m_pDeviceMgr->GetSprite()->Draw(pTexInfo->pTexture, nullptr, &D3DXVECTOR3(0, m_tInfo.fCenterY, 0.f),
nullptr, D3DCOLOR_ARGB(255, 255, 255, 255));
// 현재 체력바
pTexInfo = m_pTextureMgr->GetTexInfo(L"UI", L"CurHP", 1);
NULL_CHECK(pTexInfo);
matWorld = m_tInfo.matWorld;
D3DXMatrixScaling(
&matScale,
m_fRatio * (float)m_Target->GetCharacterInfo().iCurHP,
1.5,
1);
matWorld = matScale * m_tInfo.matTrans;
m_pDeviceMgr->GetSprite()->SetTransform(&matWorld);
m_pDeviceMgr->GetSprite()->Draw(pTexInfo->pTexture, nullptr, &D3DXVECTOR3(0, m_tInfo.fCenterY, 0.f),
nullptr, D3DCOLOR_ARGB(255, 255, 255, 255));
// 쉴드 체력바
pTexInfo = m_pTextureMgr->GetTexInfo(L"UI", L"SheildHP", 1);
NULL_CHECK(pTexInfo);
matWorld = m_tInfo.matWorld;
D3DXMatrixScaling(
&matScale,
m_fRatio * (float)m_Target->GetCharacterInfo().iSheild,
1.5,
1);
matWorld = matScale * m_tInfo.matTrans;
m_pDeviceMgr->GetSprite()->SetTransform(&matWorld);
m_pDeviceMgr->GetSprite()->Draw(pTexInfo->pTexture, nullptr, &D3DXVECTOR3(0, m_tInfo.fCenterY, 0.f),
nullptr, D3DCOLOR_ARGB(255, 255, 255, 255));
// 체력 폰트
swprintf_s(m_szHPText, L"%d/%d", m_Target->GetCharacterInfo().iCurHP, m_Target->GetCharacterInfo().iMaxHP);
D3DXMatrixScaling(&matScale, 0.8f, 0.8f, 1.f);
D3DXMatrixTranslation(&matTrans, m_tInfo.vPos.x + 100, m_tInfo.vPos.y- 10, 0.8f);
matWorld = matScale * matTrans;
m_pDeviceMgr->GetSprite()->SetTransform(&matWorld);
m_pDeviceMgr->GetFont()->DrawText(
m_pDeviceMgr->GetSprite(),
m_szHPText,
lstrlen(m_szHPText),
nullptr,
0,
D3DCOLOR_ARGB(255, 0, 0, 0));
}
HRESULT CHPBar::Initialize()
{
const TEX_INFO* pTexInfo = m_pTextureMgr->GetTexInfo(L"UI", L"MaxHP", 1);
m_tInfo.fCenterX = pTexInfo->tImgInfo.Width * 0.5f;
m_tInfo.fCenterY = pTexInfo->tImgInfo.Height * 0.5f;
m_tInfo.vPos = { m_Target->GetInfo().vPos.x -130, m_Target->GetInfo().vPos.y + 150, 1};
m_vecDefaultScale = { 2, 1.5, 1 };
D3DXMatrixScaling(&m_tInfo.matScale, m_vecDefaultScale.x, m_vecDefaultScale.y, m_vecDefaultScale.z);
D3DXMatrixTranslation(&m_tInfo.matTrans, m_tInfo.vPos.x, m_tInfo.vPos.y, 0.9f);
m_tInfo.matWorld = m_tInfo.matScale * m_tInfo.matTrans;
m_fRatio = m_tInfo.matScale.m[0][0] / (float)m_Target->GetCharacterInfo().iMaxHP;
return S_OK;
}
void CHPBar::Release()
{
}
CHPBar* CHPBar::Create(CCharacter* target)
{
CHPBar* pInstance = new CHPBar;
pInstance->m_Target = target;
if (FAILED(pInstance->Initialize()))
{
SafeDelete(pInstance);
return nullptr;
}
return pInstance;
} |
92bc0f5aa4733891b112354aa2cd8f2f53f504f3 | 386e9266dbd463d261d99a77a7cbe22a80ed61b0 | /HW.2.SE.18-19/Task3/Main.cpp | 138d42b510a1a7e99dc32bdcd50d1a3de6a48ee4 | [] | no_license | andy489/Object_Oriented_Programming_with_CPP | f629c756d3aa784a5a5c6fe9fccc6a85717d1633 | 492266ecd99b0de36b3f941b3397d2b69b195206 | refs/heads/master | 2023-04-17T05:38:52.159375 | 2021-05-04T18:16:23 | 2021-05-04T18:16:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 997 | cpp | Main.cpp | #include "Admin.h"
int main()
{
Guest guest1("11.111.11.111"); guest1.print();
User user1("22.222.22.222", "andy489", "1234", "Andrey Stoev"); user1.print();
user1.changePass("0000", "newPassword");
//checking function changePass and the encrypting & decrypting also
user1.changePass("1234", "new"); user1.print();
PowerUser powUser1("33.333.33.333", "powUser_12", "abc", "Clint Eastwood"); powUser1.print();
powUser1.incrementReputation(user1); /* checking giving reputation */ powUser1.print();
powUser1.incrementReputation(powUser1);
VIP vip1("444.44.444.44", "Mr_nullPtr", "123", "Svetlin Popivanov"); vip1.print();
vip1.setTitle("Svetlin Popivanov"); vip1.setTitle("Patarenkov"); vip1.print();
Admin admin1("55.555.55.55", "Kalata_123", "trivial", "Kaloyan Nikolov"); admin1.print();
admin1.setUsername("Kalata_123"); admin1.setUsername("Kalata_new_username"); admin1.print();
admin1.setUsernameOfUser(powUser1, "Clint_Eastwood_12");
powUser1.print();
return 0;
}
|
d1f29b3d665c44d1e66af3030ea405bd04c6455e | 88486227b16de4b785affafd087cbbceaf34e167 | /models/event.h | be521fb50a7fa356ea2ae7b3fafd857d1d540712 | [] | no_license | MigotMateusz/Time_organizer | 92cd3bc49aa145aa8e952e49663a5e32884727ed | a103de969e636925ad815830267c92070c5a3da1 | refs/heads/master | 2022-06-23T09:27:15.281734 | 2020-05-10T10:59:46 | 2020-05-10T10:59:46 | 246,005,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | h | event.h | #ifndef EVENT_H
#define EVENT_H
#include <string>
#include <QDate>
#include <memory>
#include <QDateTime>
#include "mycalendar.h"
class Event
{
private:
std::string name_of_the_event;
std::string description;
std::string place; //optional
QDateTime date;
std::shared_ptr<MyCalendar> calendar;
public:
Event();
Event(std::string,std::string, QDateTime, std::shared_ptr<MyCalendar> , std::string);
Event(const Event&);
~Event();
std::string get_name() const;
std::string get_description() const;
std::string get_place() const;
QDateTime get_date() const;
std::shared_ptr<MyCalendar> getcalendar() const;
bool operator==(Event &event);
};
#endif // EVENT_H
|
b91db27ad0e6ce78ce54249d949eca14c8c90851 | 28a7775b5d34b50a5b7dd07d07aaaf9204aa355e | /AdventOfCode/Day1.cpp | ff742cdda0a2e6fd71c4f5ef59d74f3d97065277 | [] | no_license | wkhughes/AdventOfCode2016 | bdbb1c625cb5d860a54136b2761be71a5d627ee0 | 6241f595018cc60ff5054ffbc1980dc6fc6e9381 | refs/heads/master | 2020-06-13T01:58:08.308688 | 2017-12-01T10:17:16 | 2017-12-01T10:17:16 | 75,465,316 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,333 | cpp | Day1.cpp | #include <sstream>
#include <string>
#include <algorithm>
using namespace std;
enum class Direction
{
North,
East,
South,
West
};
Direction goRight(Direction direction);
Direction goLeft(Direction direction);
string instructions = "R4, R1, L2, R1, L1, L1, R1, L5, R1, R5, L2, R3, L3, L4, R4, R4, R3, L5, L1, R5, R3, L4, R1, R5, L1, R3, L2, R3, R1, L4, L1, R1, L1, L5, R1, L2, R2, L3, L5, R1, R5, L1, R188, L3, R2, R52, R5, L3, R79, L1, R5, R186, R2, R1, L3, L5, L2, R2, R4, R5, R5, L5, L4, R5, R3, L4, R4, L4, L4, R5, L4, L3, L1, L4, R1, R2, L5, R3, L4, R3, L3, L5, R1, R1, L3, R2, R1, R2, R2, L4, R5, R1, R3, R2, L2, L2, L1, R2, L1, L3, R5, R1, R4, R5, R2, R2, R4, R4, R1, L3, R4, L2, R2, R1, R3, L5, R5, R2, R5, L1, R2, R4, L1, R5, L3, L3, R1, L4, R2, L2, R1, L1, R4, R3, L2, L3, R3, L2, R1, L4, R5, L1, R5, L2, L1, L5, L2, L5, L2, L4, L2, R3";
string day1Solution()
{
auto direction = Direction::North;
int verticalSteps = 0;
int horizontalSteps = 0;
instructions.erase(remove(instructions.begin(), instructions.end(), ' '), instructions.end());
istringstream iss(instructions);
string instruction;
while (getline(iss, instruction, ','))
{
direction = instruction[0] == 'L' ? goLeft(direction) : goRight(direction);
int steps = stoi(instruction.substr(1, instruction.length() - 1));
if (direction == Direction::North)
{
verticalSteps += steps;
}
else if (direction == Direction::South)
{
verticalSteps -= steps;
}
else if (direction == Direction::East)
{
horizontalSteps += steps;
}
else
{
horizontalSteps -= steps;
}
}
return to_string(abs(verticalSteps) + abs(horizontalSteps));
}
Direction goRight(Direction direction)
{
if (direction == Direction::North) return Direction::East;
if (direction == Direction::East) return Direction::South;
if (direction == Direction::South) return Direction::West;
return Direction::North;
}
Direction goLeft(Direction direction)
{
if (direction == Direction::North) return Direction::West;
if (direction == Direction::West) return Direction::South;
if (direction == Direction::South) return Direction::East;
return Direction::North;
} |
0a4fb051351a8e2a6a87d5b5977b26ff1bcb4b67 | cf8088a2a79a2070883e864dfeffc24c5ddd331d | /BurnServer_Core/src/Burn/tslib/Source/TSFile.h | d21dd21e7be9ddb845f7f1b0087b957583b31ea6 | [] | no_license | qingswu/CD-Burn | 5ae644d465ec145805d23a37577f911729ef679d | 5f71f858b38c8e570784356c8a1d7014f0ab94f3 | refs/heads/master | 2021-05-09T06:08:24.198985 | 2017-04-20T16:03:12 | 2017-04-20T16:03:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,137 | h | TSFile.h | ///////////////////////////////////////////////////////////////////////////////
/******************************************************************************
Project ZMediaServer
TSFile Header File
Create 20120302 ZHAOTT read support
******************************************************************************/
///////////////////////////////////////////////////////////////////////////////
#ifndef _ZTSFILE_H_
#define _ZTSFILE_H_
///////////////////////////////////////////////////////////////////////////////
#include "ZOSFile.h"
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//Virtual File IO Interface
///////////////////////////////////////////////////////////////////////////////
/* */
/* FILEOPEN */
/* FILEREAD/FILEWRITE */
/* FILECLOSE */
/* */
///////////////////////////////////////////////////////////////////////////////
#define ZFILE UINT
///////////////////////////////////////////////////////////////////////////////
typedef ZFILE* (* FILEOPEN)(const char*,const char*); //fopen
typedef ZFILE (* FILEREAD)(void*,ZFILE,ZFILE,ZFILE*); //fread
typedef ZFILE (* FILEWRITE)(const void*,ZFILE,ZFILE,ZFILE*); //fwrite
typedef int (* FILECLOSE)(ZFILE*); //fclose
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
class TSFile
{
///////////////////////////////////////////////////////////////////////////////
public:
TSFile();
virtual ~TSFile();
///////////////////////////////////////////////////////////////////////////////
public:
virtual BOOL Open(CONST CHAR* sURL);
virtual BOOL Create(CONST CHAR* sURL);
virtual BOOL Close();
///////////////////////////////////////////////////////////////////////////////
public:
UINT64 GetTime();
UINT64 SetTime(UINT64 nTime);
UINT64 GetDuration();
UINT32 GetTimeScale();
///////////////////////////////////////////////////////////////////////////////
public:
virtual UINT64 Read(VOID* sData,UINT64 nData);
virtual UINT64 Write(VOID* sData,UINT64 nData);
virtual UINT64 Seek(UINT64 nSeek);
///////////////////////////////////////////////////////////////////////////////
public:
virtual UINT64 GetPosition();
virtual UINT64 GetSize();
///////////////////////////////////////////////////////////////////////////////
public:
BOOL IsCreate();
BOOL Is64Bits();
///////////////////////////////////////////////////////////////////////////////
protected:
virtual UINT8 ReadUINT8();
virtual UINT16 ReadUINT16();
virtual UINT32 ReadUINT24();
virtual UINT32 ReadUINT32();
virtual UINT64 ReadUINT64();
virtual UINT64 ReadBytes(BYTE* pData,UINT64 nData);
///////////////////////////////////////////////////////////////////////////////
protected:
virtual UINT8 WriteUINT8(UINT8 nData);
virtual UINT16 WriteUINT16(UINT16 nData);
virtual UINT32 WriteUINT24(UINT32 nData);
virtual UINT32 WriteUINT32(UINT32 nData);
virtual UINT64 WriteUINT64(UINT64 nData);
virtual UINT64 WriteBytes(BYTE* pData,UINT64 nData);
///////////////////////////////////////////////////////////////////////////////
protected:
virtual UINT64 SkipBytes(UINT64 nData);
///////////////////////////////////////////////////////////////////////////////
protected:
typedef struct _FILE_SYSTEM_
{
BOOL m_bInit;
ZFILE* m_hFile;
FILEOPEN m_fOpen;
FILEREAD m_fRead;
FILEWRITE m_fWrite;
FILECLOSE m_fClose;
}FILE_SYSTEM;
///////////////////////////////////////////////////////////////////////////////
protected:
FILE_SYSTEM m_MediaFileSystem;
///////////////////////////////////////////////////////////////////////////////
public:
STATIC FILE_SYSTEM g_FileSystem;
///////////////////////////////////////////////////////////////////////////////
public:
STATIC VOID SetMediaFileSystem(FILEOPEN fopen,FILEREAD fread,FILEWRITE fwrite,FILECLOSE fclose);
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
protected:
BOOL m_bIsCreate;
BOOL m_bIs64Bits;
///////////////////////////////////////////////////////////////////////////////
protected:
ZOSFile m_MediaFile;
///////////////////////////////////////////////////////////////////////////////
protected:
UINT64 m_nTime;
UINT64 m_nDuration;
UINT32 m_nTimeScale;
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
};
///////////////////////////////////////////////////////////////////////////////
#endif //_ZTSFILE_H_
///////////////////////////////////////////////////////////////////////////////
|
15518a95fa7909f9536828fbf1de3186703427c8 | b3cebb6540be701d0df9a330fab5a4c9bfb24c6d | /cppProjects/smart_home/inc/atomic_value.hpp | 970118174ed3b5b4b45ed40c852e1aaacc5ce8d3 | [] | no_license | SivanTelTzur/projects | cd97662164127033a462c607cf2d295eee9341a1 | 8f49857c61fe64abecdf82bb84d82b4c0c83b3b9 | refs/heads/main | 2023-03-31T01:06:57.716591 | 2021-04-04T10:12:51 | 2021-04-04T10:12:51 | 344,538,097 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,359 | hpp | atomic_value.hpp | #ifndef E0AFE807_C888_479C_87A7_F50D64534D4C_H__
#define E0AFE807_C888_479C_87A7_F50D64534D4C_H__
namespace advcpp
{
template<typename T>
//{requires : T in an integer value (char, short, int, long)}
class AtomicValue {
public:
explicit AtomicValue(T a_initialVal = T(0));
//~AtomicValue();//default
AtomicValue(const AtomicValue& a_copyFrom);//default
T operator++();//++g
T operator++(int); //g++
void operator+=(T a_val);
T operator--(); //--g;
T operator--(int); // g--
void operator-=(T a_val);
bool operator==(T a_val);
bool operator!=(T a_val);
void Set(T a_val);
void Reset();
operator T() const;
T Get() const;
private:
AtomicValue& operator=(const AtomicValue& a_AtomicValue);
private:
mutable T m_value;
};
//template<>
//inline bool AtomicValue<bool>::Get() const
//{
// return __sync_bool_compare_and_swap(&m_value, true , true);
//}
template<>
class AtomicValue<bool>
{
public:
explicit AtomicValue(bool a_val);
void Set(bool a_ex);
bool Get() const;
bool operator==(bool a_val) const;
private:
mutable bool m_val;
};
template<> class AtomicValue<double>;
template<> class AtomicValue<float> ;
//template<> class AtomicValue<long long> ;
}//advcpp
#include "inl/atomic_value.hxx"
#endif // E0AFE807_C888_479C_87A7_F50D64534D4C_H__
|
15c52df8f5f8f615269c28064d582d4b93ecc72e | 49808d5e67f372395608e4f6e39591239e525e06 | /game.h | b45869f89ef604908186b8b54641d6a27290f4fc | [] | no_license | sarojshakya01/RPG-Game | a81eedef4b95dac3da636248e03e44b6c9be9b42 | d233c54b10ed2e7cc0f7df29dafc7b565a7b8188 | refs/heads/master | 2023-04-15T22:10:56.442262 | 2021-04-25T09:01:40 | 2021-04-25T09:01:40 | 254,435,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 373 | h | game.h | #ifndef GAME_H
#define GAME_H
#include "character.h"
using namespace std;
class Game {
private:
Character *players[2];
int current_turn;
int num_of_characters;
public:
//constructors
Game();
//getters
int getTurn();
int getCharacters();
//other functions
void RemoveCharacter(int);
void AddCharacter(Character *);
void NextTurn();
void Print();
};
#endif |
cc5c8428e615bf8d82d7b123bc69db4a56144a59 | b395fca4065fd496715a0c306d5ff643cecd31cc | /source/Core/Castor3D/Render/Technique/Opaque/Lighting/MeshLightPass.cpp | 910f59d760d624266a7eb37ab3c8739eb85882b3 | [
"MIT"
] | permissive | vn-os/Castor3D | e357372268f94a76d61e5b0059bf40f5c1f4f66a | fdaf4067e1a657979690ef6c6746079602e29d8e | refs/heads/master | 2023-06-05T19:45:24.819879 | 2021-02-19T01:39:54 | 2021-02-19T01:39:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,679 | cpp | MeshLightPass.cpp | #include "Castor3D/Render/Technique/Opaque/Lighting/MeshLightPass.hpp"
#include "Castor3D/Engine.hpp"
#include "Castor3D/Buffer/GpuBuffer.hpp"
#include "Castor3D/Buffer/UniformBufferPools.hpp"
#include "Castor3D/Material/Texture/TextureLayout.hpp"
#include "Castor3D/Material/Texture/TextureUnit.hpp"
#include "Castor3D/Render/RenderPipeline.hpp"
#include "Castor3D/Render/RenderSystem.hpp"
#include "Castor3D/Render/Technique/Opaque/Lighting/LightPassResult.hpp"
#include "Castor3D/Scene/Scene.hpp"
#include "Castor3D/Scene/Camera.hpp"
#include "Castor3D/Scene/Light/PointLight.hpp"
#include "Castor3D/Shader/Shaders/GlslLight.hpp"
#include "Castor3D/Shader/Ubos/GpInfoUbo.hpp"
#include <ashespp/Buffer/UniformBuffer.hpp>
#include <ashespp/Buffer/VertexBuffer.hpp>
#include <ashespp/Image/ImageView.hpp>
#include <ashespp/RenderPass/RenderPass.hpp>
#include <ashespp/RenderPass/RenderPassCreateInfo.hpp>
#include <ShaderWriter/Source.hpp>
using namespace castor;
namespace castor3d
{
//*********************************************************************************************
namespace
{
ashes::RenderPassPtr doCreateRenderPass( RenderDevice const & device
, castor::String const & name
, LightPassResult const & lpResult
, bool generatesIndirect
, bool first )
{
VkImageLayout layout = first
? VK_IMAGE_LAYOUT_UNDEFINED
: VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
VkAttachmentLoadOp loadOp = first
? VK_ATTACHMENT_LOAD_OP_CLEAR
: VK_ATTACHMENT_LOAD_OP_LOAD;
ashes::VkAttachmentDescriptionArray attaches
{
{
0u,
lpResult[LpTexture::eDepth].getTexture()->getPixelFormat(),
VK_SAMPLE_COUNT_1_BIT,
VK_ATTACHMENT_LOAD_OP_LOAD,
VK_ATTACHMENT_STORE_OP_STORE,
VK_ATTACHMENT_LOAD_OP_LOAD,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
},
{
0u,
lpResult[LpTexture::eDiffuse].getTexture()->getPixelFormat(),
VK_SAMPLE_COUNT_1_BIT,
loadOp,
VK_ATTACHMENT_STORE_OP_STORE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
layout,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
},
{
0u,
lpResult[LpTexture::eSpecular].getTexture()->getPixelFormat(),
VK_SAMPLE_COUNT_1_BIT,
loadOp,
VK_ATTACHMENT_STORE_OP_STORE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
layout,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
},
};
ashes::VkAttachmentReferenceArray references
{
{ 1u, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL },
{ 2u, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL },
};
if ( generatesIndirect )
{
attaches.push_back( {
0u,
lpResult[LpTexture::eIndirectDiffuse].getTexture()->getPixelFormat(),
VK_SAMPLE_COUNT_1_BIT,
VK_ATTACHMENT_LOAD_OP_CLEAR,
VK_ATTACHMENT_STORE_OP_STORE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
} );
attaches.push_back( {
0u,
lpResult[LpTexture::eIndirectSpecular].getTexture()->getPixelFormat(),
VK_SAMPLE_COUNT_1_BIT,
VK_ATTACHMENT_LOAD_OP_CLEAR,
VK_ATTACHMENT_STORE_OP_STORE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
} );
references.push_back( { 3u, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL } );
references.push_back( { 4u, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL } );
}
ashes::SubpassDescriptionArray subpasses;
subpasses.emplace_back( ashes::SubpassDescription
{
0u,
VK_PIPELINE_BIND_POINT_GRAPHICS,
{},
references,
{},
VkAttachmentReference{ 0u, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL },
{},
} );
ashes::VkSubpassDependencyArray dependencies
{
{
VK_SUBPASS_EXTERNAL,
0u,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
VK_ACCESS_SHADER_READ_BIT,
VK_DEPENDENCY_BY_REGION_BIT,
},
{
0u,
VK_SUBPASS_EXTERNAL,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
VK_ACCESS_SHADER_READ_BIT,
VK_DEPENDENCY_BY_REGION_BIT,
}
};
ashes::RenderPassCreateInfo createInfo
{
0u,
std::move( attaches ),
std::move( subpasses ),
std::move( dependencies ),
};
auto result = device->createRenderPass( name + ( first ? "First" : "Blend" )
, std::move( createInfo ) );
return result;
}
}
//*********************************************************************************************
MeshLightPass::Program::Program( Engine & engine
, RenderDevice const & device
, String const & name
, ShaderModule const & vtx
, ShaderModule const & pxl
, bool hasShadows
, bool hasVoxels
, bool generatesIndirect )
: LightPass::Program{ engine
, device
, name
, vtx
, pxl
, hasShadows
, hasVoxels
, generatesIndirect }
{
}
MeshLightPass::Program::~Program()
{
}
ashes::GraphicsPipelinePtr MeshLightPass::Program::doCreatePipeline( ashes::PipelineVertexInputStateCreateInfo const & vertexLayout
, ashes::RenderPass const & renderPass
, bool blend )
{
ashes::PipelineDepthStencilStateCreateInfo dsstate
{
0u,
VK_FALSE,
VK_FALSE,
VK_COMPARE_OP_LESS,
VK_FALSE,
VK_FALSE,
{
VK_STENCIL_OP_KEEP,
VK_STENCIL_OP_KEEP,
VK_STENCIL_OP_KEEP,
VK_COMPARE_OP_NOT_EQUAL,
0xFFFFFFFFu,
0xFFFFFFFFu,
0x0u,
},
};
ashes::VkPipelineColorBlendAttachmentStateArray blattaches;
if ( blend )
{
blattaches.push_back( VkPipelineColorBlendAttachmentState
{
true,
VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ONE,
VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ONE,
VK_BLEND_OP_ADD,
defaultColorWriteMask,
} );
}
else
{
blattaches.push_back( VkPipelineColorBlendAttachmentState
{
true,
VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ZERO,
VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ZERO,
VK_BLEND_OP_ADD,
defaultColorWriteMask,
} );
}
blattaches.push_back( blattaches.back() );
if ( m_generatesIndirect )
{
blattaches.push_back( blattaches.back() );
blattaches.push_back( blattaches.back() );
}
auto result = m_device->createPipeline( m_name + ( blend ? std::string{ "Blend" } : std::string{ "First" } )
, ashes::GraphicsPipelineCreateInfo
{
0u,
m_program,
vertexLayout,
ashes::PipelineInputAssemblyStateCreateInfo{ 0u, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST },
ashes::nullopt,
ashes::PipelineViewportStateCreateInfo{},
ashes::PipelineRasterizationStateCreateInfo{ 0u, VK_FALSE, VK_FALSE, VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT },
ashes::PipelineMultisampleStateCreateInfo{},
std::move( dsstate ),
ashes::PipelineColorBlendStateCreateInfo{ 0u, VK_FALSE, VK_LOGIC_OP_COPY, std::move( blattaches ) },
ashes::PipelineDynamicStateCreateInfo{ 0u, { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR } },
*m_pipelineLayout,
renderPass,
} );
return result;
}
//*********************************************************************************************
MeshLightPass::MeshLightPass( RenderDevice const & device
, castor::String const & suffix
, LightPassConfig const & lpConfig
, VoxelizerUbo const * vctConfig
, LightType type )
: LightPass{ device
, suffix
, doCreateRenderPass( device
, suffix
, lpConfig.lpResult
, lpConfig.generatesIndirect
, true )
, doCreateRenderPass( device
, suffix
, lpConfig.lpResult
, lpConfig.generatesIndirect
, false )
, lpConfig
, vctConfig }
, m_modelMatrixUbo{ m_device.renderSystem
, 1u
, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT
, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT
, getName() + "ModelMatrix" }
, m_modelMatrixData{ reinterpret_cast< ModelMatrixUboConfiguration * >( m_modelMatrixUbo.getBuffer().getBuffer().lock( 0u
, m_modelMatrixUbo.getAlignedSize()
, 0u ) ) }
, m_stencilPass{ m_engine
, getName()
, lpConfig.lpResult[LpTexture::eDepth].getTexture()->getDefaultView().getTargetView()
, m_matrixUbo
, m_modelMatrixUbo }
, m_type{ type }
{
}
MeshLightPass::~MeshLightPass()
{
m_vertexBuffer.reset();
}
void MeshLightPass::initialise( Scene const & scene
, OpaquePassResult const & gp
, SceneUbo & sceneUbo
, RenderPassTimer & timer )
{
auto & renderSystem = *m_engine.getRenderSystem();
ashes::PipelineVertexInputStateCreateInfo declaration
{
0u,
ashes::VkVertexInputBindingDescriptionArray
{
{ 0u, sizeof( castor::Point3f ), VK_VERTEX_INPUT_RATE_VERTEX },
},
ashes::VkVertexInputAttributeDescriptionArray
{
{ 0u, 0u, VK_FORMAT_R32G32B32_SFLOAT, 0u },
}
};
auto data = doGenerateVertices();
m_count = uint32_t( data.size() );
m_vertexBuffer = makeVertexBuffer< float >( m_device
, uint32_t( data.size() * 3u )
, 0u
, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT
, "MeshLightPassVbo" );
if ( auto * buffer = m_vertexBuffer->lock( 0u, m_vertexBuffer->getCount(), 0u ) )
{
std::memcpy( buffer, data.data()->constPtr(), m_vertexBuffer->getSize() );
m_vertexBuffer->flush( 0u, m_vertexBuffer->getCount() );
m_vertexBuffer->unlock();
}
m_stencilPass.initialise( m_device, declaration, *m_vertexBuffer );
doInitialise( scene
, gp
, m_type
, *m_vertexBuffer
, declaration
, sceneUbo
, &m_modelMatrixUbo
, timer );
}
void MeshLightPass::cleanup()
{
doCleanup();
m_stencilPass.cleanup();
m_matrixUbo.cleanup( m_device );
m_vertexBuffer.reset();
}
ashes::Semaphore const & MeshLightPass::render( uint32_t index
, ashes::Semaphore const & toWait )
{
auto * result = &toWait;
result = &m_stencilPass.render( m_device , *result );
result = &LightPass::render( index, *result );
return *result;
}
uint32_t MeshLightPass::getCount()const
{
return m_count;
}
void MeshLightPass::doUpdate( bool first
, Size const & size
, Light const & light
, Camera const & camera )
{
m_matrixUbo.cpuUpdate( camera.getView(), camera.getProjection() );
auto model = doComputeModelMatrix( light, camera );
auto normal = castor::Matrix3x3f{ model };
normal.invert();
normal.transpose();
auto & data = *m_modelMatrixData;
data.prvModel = data.curModel;
data.prvNormal = data.curNormal;
data.curModel = model;
data.curNormal = Matrix4x4f{ normal };
m_pipeline->program->bind( light );
}
ShaderPtr MeshLightPass::doGetVertexShaderSource( SceneFlags const & sceneFlags )const
{
using namespace sdw;
VertexWriter writer;
// Shader inputs
UBO_MATRIX( writer, MatrixUbo::BindingPoint, 0u );
UBO_MODEL_MATRIX( writer, ModelMatrixUbo::BindingPoint, 0u );
UBO_GPINFO( writer, GpInfoUbo::BindingPoint, 0u );
auto vertex = writer.declInput< Vec3 >( "position", 0u );
// Shader outputs
auto out = writer.getOut();
writer.implementFunction< sdw::Void >( "main"
, [&]()
{
out.vtx.position = c3d_projection * c3d_curView * c3d_curMtxModel * vec4( vertex, 1.0_f );
} );
return std::make_unique< ast::Shader >( std::move( writer.getShader() ) );
}
//*********************************************************************************************
}
|
8cf41e1bcc8f6b5582b624db1fb29a843035c4e3 | 6014e8b21ff501c1f7f00ae54b95a908c7f94feb | /PSC_Ychanger/stdafx.h | becf7d44482cfd87d4f563c7e0fa815db1cde918 | [] | no_license | YukiiiPL/POS | c29c57d80983a8a6417ee75170f8dd4750403704 | 9aae39e3fe425e918f992ad8692bb8a53f13f8e7 | refs/heads/master | 2021-01-17T16:42:54.827049 | 2016-06-28T05:49:27 | 2016-06-28T05:49:27 | 61,650,924 | 0 | 2 | null | 2016-06-28T05:49:28 | 2016-06-21T16:50:05 | C++ | UTF-8 | C++ | false | false | 1,029 | h | stdafx.h | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <atlstr.h>
#include <sys/stat.h>
#include <sys/stat.h>
#include <iostream>
#include <Windows.h>
#include <vector>
#include "string.h"
#include "conio.h"
#include "strsafe.h"
#include <process.h>
#include "INIReader.h"
#include "ini.h"
#include "opencv2/opencv.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
using namespace std;
/// \brief Funkcja sluzaca do wyrownwania jasnosci obrazu
/// \details Funkcja dokonuje operacji wyrownania jasnosci na wszystkich obrazach znajdujacych sie wewnatrz wektora <i>data</i>
/// \param <i>data</i> wektor zawierajacy sciezki do obrazow
void EqualizeImages(void *data);
// TODO: reference additional headers your program requires here
|
8754c7c4c7e076f42ec6754f21b01dd5946d43e0 | 7444df64f8faf5c0b5cb45d00e76fbd10b07d654 | /src/Renderer/Components/MeshRenderer.cpp | c5445d8977f56d54c8593b289af47b2d10d72c25 | [] | no_license | adriankrupa/AKEngine | 21945dacaf0885ff67acc54636317d1fbfeb4ca4 | ef8d5f4e037ca7fa7ab6a21f90e031d93003cb80 | refs/heads/master | 2021-01-20T13:37:31.528358 | 2017-03-03T09:19:24 | 2017-03-03T09:19:24 | 82,704,183 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 98 | cpp | MeshRenderer.cpp | //
// Created by akrupa on 2017-02-24.
//
#include "akengine/Renderer/Components/MeshRenderer.h"
|
b934da0a78e26a4c275b9ea9efffe06f8d4e59d3 | fc732bfc6f69a578b919c0fca2b35ebf6eded22e | /Arena/source/Managers/soundSingleton.cpp | 20062fd65c0fde2e4012cc22918462a4d91d9f84 | [] | no_license | polymonster/demos-archive | 62ae3af439d6b1da115976365e055a1b2e5a797c | 86347051fe35b926ed9f9826af4474cde0635059 | refs/heads/master | 2020-05-01T18:00:28.238367 | 2019-08-13T14:37:21 | 2019-08-13T14:37:21 | 177,614,524 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,447 | cpp | soundSingleton.cpp | #include "soundSingleton.h"
CSound* CSound::m_instance = NULL;
void CSound::create(){
if(m_instance == NULL)
{
m_instance = new CSound;
}
}
void CSound::destroy(){
if(m_instance)
{
delete m_instance;
m_instance = NULL;
}
}
void CSound::kill(){
for(int i = 0; i < 3; i++)
{
FSOUND_Stream_Stop( gun[i] );
FSOUND_Stream_Close( gun[i] );
}
for(i = 0; i < 3; i++)
{
FSOUND_Stream_Stop( run[i] );
FSOUND_Stream_Close( run[i] );
}
FSOUND_Stream_Stop( reload );
FSOUND_Stream_Close( reload );
FSOUND_Stream_Stop( noAmmo );
FSOUND_Stream_Close( noAmmo );
FSOUND_Stream_Stop( atmosphere );
FSOUND_Stream_Close( atmosphere );
FSOUND_Stream_Stop( clicks );
FSOUND_Stream_Close( clicks );
FSOUND_Stream_Stop( walk );
FSOUND_Stream_Close( walk );
FSOUND_Stream_Stop( walk2 );
FSOUND_Stream_Close( walk2 );
FSOUND_Stream_Stop( jump );
FSOUND_Stream_Close( jump );
for(i = 0; i < 3; i++)
{
FSOUND_Stream_Stop( pain[i] );
FSOUND_Stream_Close( pain[i] );
FSOUND_Stream_Stop( death[i] );
FSOUND_Stream_Close( death[i] );
}
};
CSound::CSound()
{
// initialise fmod, 44000 Hz, 64 channels
if( FSOUND_Init(44000,64,0) == FALSE ) {
cout << "[ERROR] Could not initialise fmod\n";
}
atmosphere = FSOUND_Stream_Open( "data/sound/threat.mp3" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
//FSOUND_Stream_Play(3,atmosphere);
//FSOUND_SetVolume (3, 70);
// attempt to open the mp3 file as a stream - use the following option:
// FSOUND_2D - Tells software (not hardware) based sample not to be included in 3d processing.
// FSOUND_LOOP_NORMAL - To enable repeat playing
gun[0] = FSOUND_Stream_Open( "data/sound/machinegun.wav" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
gun[1] = FSOUND_Stream_Open( "data/sound/shotgun.wav" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
gun[2] = FSOUND_Stream_Open( "data/sound/plasma.wav" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
reload = FSOUND_Stream_Open( "data/sound/reload.wav" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
noAmmo = FSOUND_Stream_Open( "data/sound/noammo.wav" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
clicks = FSOUND_Stream_Open( "data/sound/click.mp3" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
walk = FSOUND_Stream_Open( "data/sound/boot1.wav" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
walk2 = FSOUND_Stream_Open( "data/sound/boot2.wav" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
jump = FSOUND_Stream_Open( "data/sound/jump.wav" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
pain[0] = FSOUND_Stream_Open( "data/sound/pain25_1.wav" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
pain[1] = FSOUND_Stream_Open( "data/sound/pain50_1.wav" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
pain[2] = FSOUND_Stream_Open( "data/sound/pain75_1.wav" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
death[0] = FSOUND_Stream_Open( "data/sound/death1.wav" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
death[1] = FSOUND_Stream_Open( "data/sound/death2.wav" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
death[2] = FSOUND_Stream_Open( "data/sound/death3.wav" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
run[0] = FSOUND_Stream_Open( "data/sound/speedfinal1.mp3" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
run[1] = FSOUND_Stream_Open( "data/sound/speedfinal2.mp3" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
run[2] = FSOUND_Stream_Open( "data/sound/speedfinal3.mp3" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
FSOUND_Stream_SetLoopCount(gun[0],0);
FSOUND_Stream_SetLoopCount(gun[1],0);
FSOUND_Stream_SetLoopCount(gun[2],0);
FSOUND_Stream_SetLoopCount(run[0],0);
FSOUND_Stream_SetLoopCount(run[1],0);
FSOUND_Stream_SetLoopCount(run[2],0);
FSOUND_Stream_SetLoopCount(clicks,0);
FSOUND_Stream_SetLoopCount(walk,0);
FSOUND_Stream_SetLoopCount(walk2,0);
FSOUND_Stream_SetLoopCount(jump,0);
FSOUND_Stream_SetLoopCount(reload,0);
FSOUND_Stream_SetLoopCount(noAmmo,0);
for(int i = 0; i < 3; i++)
{
FSOUND_Stream_SetLoopCount(death[i],0);
FSOUND_Stream_SetLoopCount(pain[i],0);
}
}
void CSound::play(int id){
if(id == 0) FSOUND_Stream_Play(1,noAmmo);
if(id == 1) FSOUND_Stream_Play(1,reload);
if(id == 2)
{
FSOUND_SetVolume (2, 30);
FSOUND_Stream_Play(4,walk);
}
if(id == 3) FSOUND_Stream_Play(5,jump);
if(id == 6) FSOUND_Stream_Play(12,run[0]);
if(id == 7) FSOUND_Stream_Play(13,run[1]);
if(id == 8) FSOUND_Stream_Play(14,run[2]);
if(id == 9)
{
FSOUND_SetVolume (9, 20);
FSOUND_Stream_Play(6,walk2);
}
if(id == 10) FSOUND_Stream_Play(10,pain[0]);
if(id == 11) FSOUND_Stream_Play(11,pain[1]);
if(id == 12) FSOUND_Stream_Play(12,pain[2]);
if(id == 20) FSOUND_Stream_Play(11,death[0]);
if(id == 21) FSOUND_Stream_Play(11,death[1]);
if(id == 22) FSOUND_Stream_Play(11,death[2]);
}
void CSound::click(){
//FSOUND_Stream_Stop(clicks);
FSOUND_Stream_Play(0,clicks);
}
void CSound::gunshot(int id){
FSOUND_Stream_Stop( gun[id] );
FSOUND_Stream_Play(0,gun[id]);
}
void CSound::startAtmosphere(){
FSOUND_Stream_Stop( atmosphere );
atmosphere = FSOUND_Stream_Open( "data/sound/grind.mp3" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
FSOUND_Stream_Play(3,atmosphere);
FSOUND_SetVolume (3, 150);
}
void CSound::startMenuMusic(){
FSOUND_Stream_Stop( atmosphere );
atmosphere = FSOUND_Stream_Open( "data/sound/threat.mp3" , FSOUND_2D|FSOUND_LOOP_NORMAL, 0 , 0 );
FSOUND_Stream_Play(3,atmosphere);
FSOUND_SetVolume (3, 150);
}
void CSound::endAtmosphere(){
FSOUND_Stream_Stop( atmosphere );
//FSOUND_Stream_Close( atmosphere );
} |
b017e1400d712c6506f0b678fb55b8e85430bd8b | e01cca8d52c08bbfd4bd039acd508d2c55a5ea52 | /lib/sound.cpp | d047bff3038eec61262117e7d24940aef93314cb | [] | no_license | Yahao277/RobotMaze | f97c3acc637814f5bef3ff8a0096055daffb23a3 | 26098394eb76eb9a95c188079c40e79679a9fc32 | refs/heads/master | 2021-08-14T12:12:18.553160 | 2017-11-15T17:21:46 | 2017-11-15T17:21:46 | 105,135,027 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,450 | cpp | sound.cpp | #include <SDL.h>
#include <stdlib.h>
#include <math.h>
#include <cassert>
#include "libreria.h"
#include "sound.h"
#include "stb_vorbis.h"
#define NUM_CANALES_STEREO 2
#define NO_SOUND_CHANNEL_AVAILABLE -1
#pragma warning(disable : 4996)
//#define DEBUG_TEST_TONE
#ifdef DEBUG_TEST_TONE
float g_angulo_generador ;
#endif
signed short *g_music_buffer ;
//signed short *g_sound_buffer ;
signed short *g_sound_buffer_queue[MAX_SIMULTANEOUS_SOUND_CHANNELS_FOR_SOUND_EFFECTS] ;
struct T_SOUND *g_current_music = NULL ;
//struct T_SOUND *g_current_sound = NULL ;
int g_samples ;
struct T_SOUND *g_Sound_Queue[MAX_SIMULTANEOUS_SOUND_CHANNELS_FOR_SOUND_EFFECTS] ;
int g_CanalesLibres[MAX_SIMULTANEOUS_SOUND_CHANNELS_FOR_SOUND_EFFECTS] ;
int g_Posicion_Pila_Sonidos_Libres ;
void Sound_Lock()
{
SDL_LockAudio() ;
}
void Sound_Unlock()
{
SDL_UnlockAudio() ;
}
void PushCanalLibre(int cual)
{
assert(g_Posicion_Pila_Sonidos_Libres < (MAX_SIMULTANEOUS_SOUND_CHANNELS-1)) ;
g_CanalesLibres[g_Posicion_Pila_Sonidos_Libres] = cual ;
g_Sound_Queue[cual] = NULL ;
g_Posicion_Pila_Sonidos_Libres++ ;
}
int PopCanalLibre()
{
int canal_libre = NO_SOUND_CHANNEL_AVAILABLE ;
if(g_Posicion_Pila_Sonidos_Libres > 0) {
g_Posicion_Pila_Sonidos_Libres-- ;
canal_libre = g_CanalesLibres[g_Posicion_Pila_Sonidos_Libres] ;
}
return canal_libre ;
}
// ------------------------------------------------------------------------------------------------
// Devuelve el tama? en bytes del fichero
//
int TamanyoFicheroAbierto(FILE *fichero)
{
int posicion_actual, tamanyo ;
posicion_actual = ftell(fichero) ;
// Vamos al final del fichero
fseek(fichero, 0, SEEK_END) ;
tamanyo = ftell(fichero) ;
// Volvemos a donde estuvi?emos
fseek(fichero, posicion_actual, SEEK_SET) ;
return tamanyo ;
}
// ------------------------------------------------------------------------------------------------
// Devuelve el tama? en bytes del fichero
int TamanyoFichero(char *ruta)
{
FILE *fichero ;
int tamanyo ;
fichero = fopen(ruta, "rb") ;
if(fichero == NULL) return 0 ;
tamanyo = TamanyoFicheroAbierto(fichero) ;
return tamanyo ;
}
int Sound_GetSoundQueueSlot(struct T_SOUND *sonido)
{
sonido->posicion_cola = PopCanalLibre() ;
// Si no tenemos un slot de reproducci? libre nos marchamos sin hacer nada
if(sonido->posicion_cola == NO_SOUND_CHANNEL_AVAILABLE) {
return NO_SOUND_CHANNEL_AVAILABLE ;
}
// Si tenemos un slot asignado nos metemos en la cola
g_Sound_Queue[sonido->posicion_cola] = sonido ;
return sonido->posicion_cola ;
}
void Sound_Callback(void *unused, Uint8 *stream, int len)
{
int var1 ;
int num_samples ;
signed short *puntero ;
int var_sonido ;
int valor_final ;
(void)unused ;
assert(stream) ;
Sound_Lock() ;
num_samples = (len / NUM_CANALES_STEREO) ;
//ASSERT((num_samples / NUM_CANALES_STEREO) <= g_samples) ;
puntero = (signed short *)stream ;
memset(g_music_buffer, 0, g_samples * NUM_CANALES_STEREO * sizeof(signed short)) ;
if(g_current_music != NULL) {
if(g_current_music->ogg != NULL) {
/*if(g_current_music->buffer_fichero == NULL) g_current_music->posicion_stream = stb_vorbis_get_file_offset(g_current_music->ogg) ;
else */g_current_music->posicion_stream = stb_vorbis_get_sample_offset(g_current_music->ogg) ;
if(g_current_music->posicion_stream == g_current_music->num_samples) {
if(g_current_music->bLoop) Sound_Restart(g_current_music) ;
else Sound_Stop(g_current_music) ;
}
stb_vorbis_get_samples_short_interleaved(g_current_music->ogg, 2, g_music_buffer, num_samples) ;
}
}
// Paso previo de render de .ogg
for(var_sonido = 0; var_sonido < MAX_SIMULTANEOUS_SOUND_CHANNELS_FOR_SOUND_EFFECTS; var_sonido++) {
struct T_SOUND *sonido = g_Sound_Queue[var_sonido] ;
// Borramos el contenido del buffer
memset(g_sound_buffer_queue[var_sonido], 0, g_samples * NUM_CANALES_STEREO * sizeof(signed short)) ;
// ?Hay sonido?
if(sonido != NULL) {
// ?Tiene un stream ogg?
if(sonido->ogg != NULL) {
if(sonido->buffer_fichero == NULL) sonido->posicion_stream = stb_vorbis_get_file_offset(sonido->ogg) ;
else sonido->posicion_stream = stb_vorbis_get_sample_offset(sonido->ogg) ;
if(sonido->posicion_stream == sonido->num_samples) {
if(sonido->bLoop) Sound_Restart(sonido) ;
else Sound_Stop(sonido) ;
}
if(sonido->estado == SOUND_STATE_PLAYING) {
// Llenamos el contenido del buffer hasta donde podamos
stb_vorbis_get_samples_short_interleaved(sonido->ogg, 2, g_sound_buffer_queue[var_sonido], num_samples) ;
}
}
}
}
for(var1 = 0; var1 < num_samples; var1++) {
#ifdef DEBUG_TEST_TONE
*puntero = 1000 * sin(g_angulo_generador) ;
g_angulo_generador += 0.1f ;
#else
valor_final = 0 ;
for(var_sonido = 0; var_sonido < MAX_SIMULTANEOUS_SOUND_CHANNELS_FOR_SOUND_EFFECTS; var_sonido++) {
if(g_Sound_Queue[var_sonido] != NULL) {
valor_final += g_sound_buffer_queue[var_sonido][var1] ;
}
}
valor_final += g_music_buffer[var1] ;
*puntero = (short)(valor_final / MAX_SIMULTANEOUS_SOUND_CHANNELS) ;
//*puntero = g_music_buffer[var1] ;
#endif
puntero++ ;
}
Sound_Unlock() ;
}
void Sound_Init()
{
SDL_AudioSpec desired, obtained ;
int resultado ;
int var_sonido ;
desired.format = AUDIO_S16 ;
desired.freq = 44100 ;
desired.samples = (Uint16) 512 ;
desired.channels = 2 ;
desired.callback = Sound_Callback ;
desired.userdata = NULL ;
resultado = SDL_OpenAudio(&desired, &obtained) ;
g_samples = obtained.samples ;
if ( resultado != 0 ) {
if (resultado < 0) {
int a = 5 ;
(void)a ;
}
}
g_current_music = NULL ;
g_music_buffer = (signed short *)malloc(g_samples * NUM_CANALES_STEREO * sizeof(signed short)) ;
memset(g_music_buffer, 0, g_samples * NUM_CANALES_STEREO * sizeof(signed short)) ;
// g_current_sound = NULL ;
//g_sound_buffer = (signed short *)malloc(g_samples * NUM_CANALES_STEREO * sizeof(signed short)) ;
// memset(g_sound_buffer, 0, g_samples * NUM_CANALES_STEREO * sizeof(signed short)) ;
// Inicializamos la cola de reproducci? de sonidos
g_Posicion_Pila_Sonidos_Libres = 0 ;
for(var_sonido = 0; var_sonido < MAX_SIMULTANEOUS_SOUND_CHANNELS_FOR_SOUND_EFFECTS; var_sonido++) {
g_sound_buffer_queue[var_sonido] = (signed short *)malloc(g_samples * NUM_CANALES_STEREO * sizeof(signed short)) ;
memset(g_sound_buffer_queue[var_sonido], 0, g_samples * NUM_CANALES_STEREO * sizeof(signed short)) ;
PushCanalLibre(var_sonido) ;
}
SDL_PauseAudio(0) ;
}
struct T_SOUND *Sound_LoadFileStream(char *path, int bLoop)
{
struct T_SOUND *new_sound ;
int error ;
new_sound = (struct T_SOUND *) malloc(sizeof(struct T_SOUND)) ;
new_sound->bLoop = bLoop ;
new_sound->posicion_stream = 0 ;
new_sound->estado = SOUND_STATE_STOPPED ;
new_sound->posicion_cola = -1 ;
new_sound->buffer_fichero = NULL ;
new_sound->ogg = stb_vorbis_open_filename(path, &error, NULL) ;
if(new_sound->ogg == NULL) {
printf("\nERROR: No se encuentra el archivo %s", path) ;
new_sound->num_samples = 0 ;
}
else {
// stb_vorbis_info info = stb_vorbis_get_info(new_sound->ogg) ;
new_sound->num_samples = stb_vorbis_stream_length_in_samples(new_sound->ogg) ;
}
return new_sound ;
}
struct T_SOUND *Sound_LoadMemoryStream(char *path, int bLoop)
{
struct T_SOUND *new_sound ;
int tam_buffer ;
int error ;
FILE *fichero ;
new_sound = (struct T_SOUND *) malloc(sizeof(struct T_SOUND)) ;
new_sound->bLoop = bLoop ;
new_sound->posicion_stream = 0 ;
new_sound->estado = SOUND_STATE_STOPPED ;
new_sound->posicion_cola = -1 ;
fichero = fopen(path, "rb") ;
if(fichero == NULL) {
printf("\nERROR: No se encuentra el archivo %s", path) ;
new_sound->buffer_fichero = NULL ;
new_sound->ogg = NULL ;
new_sound->num_samples = 0 ;
}
else {
tam_buffer = TamanyoFicheroAbierto(fichero) ;
new_sound->buffer_fichero = (unsigned char *) malloc(tam_buffer) ;
fread(new_sound->buffer_fichero, tam_buffer, 1, fichero) ;
fclose(fichero) ;
new_sound->ogg = stb_vorbis_open_memory(new_sound->buffer_fichero, tam_buffer, &error, NULL) ;
new_sound->num_samples = stb_vorbis_stream_length_in_samples(new_sound->ogg) ;
}
return new_sound ;
}
struct T_SOUND *Sound_LoadMusic(char *path, int bStream)
{
if(bStream) g_current_music = Sound_LoadFileStream(path, PLAY_THEN_LOOP_AT_END) ;
else g_current_music = Sound_LoadMemoryStream(path, PLAY_THEN_LOOP_AT_END) ;
return g_current_music ;
}
struct T_SOUND *Sound_LoadSound(char *path)
{
struct T_SOUND *sound ;
// g_current_sound = Sound_LoadMemoryStream(path, PLAY_THEN_STOP_AT_END) ;
// return g_current_sound ;
sound = Sound_LoadMemoryStream(path, PLAY_THEN_STOP_AT_END) ;
return sound ;
}
int Sound_Play(struct T_SOUND *sonido, int mode)
{
// g_current_sound = sonido ;
if(sonido->estado != SOUND_STATE_PLAYING) {
// Si el sonido estaba parado pedimos una nueva posici? en la cola
if(Sound_GetSoundQueueSlot(sonido) == NO_SOUND_CHANNEL_AVAILABLE) {
return NO_SOUND_CHANNEL_AVAILABLE ;
}
// ?Comenzaremos desde el principio?
if(sonido->estado != SOUND_STATE_PAUSED ||
mode == SOUND_FORCE_RESTART) {
// Reiniciar el sonido
Sound_Restart(sonido) ;
}
// Cambiamos el estado a "playing"
sonido->estado = SOUND_STATE_PLAYING ;
}
else {
// Si el sonido no estaba playe?dose y no est?en pause hay que reiniciarlo
if(mode != SOUND_DO_NOT_RESTART_IF_ALREADY_PLAYING) Sound_Restart(sonido) ;
}
// Devolvemos la posici? en la cola de reproducci?
return sonido->posicion_cola ;
}
void Sound_FreeSoundQueueSlot(struct T_SOUND *sonido)
{
// Si el sonido no est?reproduci?dose no hacemos nada
if(sonido->posicion_cola == -1) return ;
// Liberamos la posici? de la cola que est?ocupando el sonido
PushCanalLibre(sonido->posicion_cola) ;
sonido->posicion_cola = -1 ;
}
void Sound_Delete(struct T_SOUND *sonido)
{
// Liberamos la posici? de la cola que est?ocupando el sonido
Sound_FreeSoundQueueSlot(sonido) ;
// Falta...
}
void Sound_Pause(struct T_SOUND *sonido)
{
// Liberamos la posici? de la cola que est?ocupando el sonido
Sound_FreeSoundQueueSlot(sonido) ;
sonido->estado = SOUND_STATE_PAUSED ;
}
void Sound_Stop(struct T_SOUND *sonido)
{
// Liberamos la posici? de la cola que est?ocupando el sonido
Sound_FreeSoundQueueSlot(sonido) ;
sonido->estado = SOUND_STATE_STOPPED ;
}
void Sound_Restart(struct T_SOUND *sonido)
{
Sound_Lock() ;
stb_vorbis_seek_start(sonido->ogg) ;
sonido->posicion_stream = 0 ;
Sound_Unlock() ;
}
|
b88f1eeb60a2a5e76199d2f653bff79b6f02f96b | 4eabb12af4c20ca251dc076cd79ea1d4e321acc6 | /project01/SongTest.h | 7b0e816d41755931baf4372d5d64b805473bcb32 | [] | no_license | Elilewis327/cs112 | fd609b3ea6a035e25faf2c2faf629725624242fd | 80839a1eb933de30b8b3a1d3e16896a28ed1fa5d | refs/heads/main | 2023-08-11T19:10:41.744047 | 2021-10-03T21:26:11 | 2021-10-03T21:26:11 | 410,397,115 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 326 | h | SongTest.h | /*
* Author: Eli Lewis: etl3
* Date: 9/5/21
* Begun by: Joel Adams, for CS 112 at Calvin University.
*/
#ifndef SONGTEST_H_
#define SONGTEST_H_
class SongTest {
public:
SongTest();
void runTests();
void testConstructors();
void testReadFrom();
void testWriteTo();
void testEqualsTo();
};
#endif /* SONGTEST_H_ */
|
8999e7e77498f6cfc91813a772ebb5149539c108 | e261e0f4b94d49d0ecb62022250d27349e6ce02d | /bench.cc | 0e04d3dbbc71708ea8bda660cfc5f39eb23b2cd1 | [
"MIT"
] | permissive | dashahe/b-tree | 0d5685c5684dbde96cf0ffb8154eb694667a817a | 46cd4cea6878d5de6e5bf64935b9998401c3ae94 | refs/heads/master | 2022-06-05T03:21:29.762567 | 2019-03-04T15:44:02 | 2019-03-04T15:44:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,247 | cc | bench.cc | //
// Created by xiebei on 2019-03-02.
//
#include "b_tree.h"
#include <iostream>
#include <map>
#include <ctime>
using namespace std;
using RBTree = map<int, string>;
void benchInsert() {
BTree<int, string> btree;
RBTree rbtree;
printf("insert 1000*1000 pairs\n");
clock_t begin = clock();
for (int i = 0; i < 1000 * 1000; i++) {
auto str = std::to_string(i);
rbtree.insert(std::pair(i, str));
}
clock_t end = clock();
printf("\tRBtree, time used: %.4fsecond\n", (end - begin) / 1000.0 / 1000.0);
begin = clock();
for (int i = 0; i < 1000 * 1000; i++) {
auto str = std::to_string(i);
btree.insert(i, str);
}
end = clock();
printf("\tBTree, time used: %.4fsecond\n\n", (end - begin) / 1000.0 / 1000.0);
}
void benchSearch() {
BTree<int, string> btree;
RBTree rbtree;
for (int i = 0; i < 1000 * 1000; i++) {
auto str = std::to_string(i);
rbtree.insert(std::pair(i, str));
btree.insert(i, str);
}
printf("search 1000*1000 pairs\n");
clock_t begin = clock();
for (int i = 0; i < 1000 * 1000; i++) {
rbtree.find(i);
}
clock_t end = clock();
printf("\tRBtree, time used: %.4fsecond\n", (end - begin) / 1000.0 / 1000.0);
begin = clock();
for (int i = 0; i < 1000 * 1000; i++) {
btree.search(i);
}
end = clock();
printf("\tBTree, time used: %.4fsecond\n\n", (end - begin) / 1000.0 / 1000.0);
}
void benchLargeData() {
BTree<int, string> btree;
RBTree rbtree;
//1KB
auto largeStr = string(1024 * 4 , 'a');
printf("large data insert and search 1000*1000 pairs\n");
clock_t begin = clock();
for (int i = 0; i < 1000 * 1000; i++) {
rbtree.insert(std::pair(i, largeStr));
// rbtree.find(i);
}
clock_t end = clock();
printf("\tRBtree, time used: %.4fsecond\n", (end - begin) / 1000.0 / 1000.0);
begin = clock();
for (int i = 0; i < 1000 * 1000; i++) {
btree.insert(i, largeStr);
// btree.search(i);
}
end = clock();
printf("\tBTree, time used: %.4fsecond\n\n", (end - begin) / 1000.0 / 1000.0);
}
int main() {
benchInsert();
benchSearch();
benchLargeData();
} |
0207161db97fcd3eb7e80a6b50391c315d299d5e | c7ad884698f0af1deddafd30dab598af08033aa3 | /CHAIN2.cpp | f38b62a8209d26c0199b9a8ffa3edffb2f00e2db | [] | no_license | snowynguyen/Code-CPP | 2504a05377e8c1910f3c5efb1fce37e805bde7a8 | 95d3334c8fbd11c4ab9b375d008f843c09020c04 | refs/heads/master | 2022-07-17T04:31:49.987478 | 2020-05-21T13:57:45 | 2020-05-21T13:57:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 936 | cpp | CHAIN2.cpp | #include <iostream>
#include <cstring>
using namespace std;
struct node {
int u;
node *c [26];
};
const int N = 250000;
node root;
char s [N];
node* make (node *p){
p = new node;
p -> u = 0;
for (int i = 0; i < 26; ++i){
p -> c[i] = NULL;
}
return p;
}
void add (int n){
node *p = &root;
for (int i = 0; i < n; ++i){
int c = (int) s[i] - 'a';
if (p -> c[c] == NULL) p-> c[c] = make(p -> c[c]);
p = p -> c[c];
}
p -> u += 1;
}
void start(){
int m;
cin >> m;
cin.getline(s, N);
for (int i = 1; i <= m; ++i){
cin.getline(s, N);
add (strlen (s));
}
}
int dfs (node*p){
int f = 0;
for (int i = 0; i < 26; ++i){
if (p->c[i] == NULL) continue;
f = max (f, dfs (p -> c[i]));
}
f += p-> u;
return f;
}
int main()
{
make (&root);
start();
cout << dfs (&root);
return 0;
}
|
b49b4cedd724437ab65ca64cf89c296cbb70da46 | 6818ce61817ae8feb814122745a7df527867a489 | /vfp/Model/settings.cpp | 204124174cb75139f6a432593001fa513de91354 | [] | no_license | MKSherbini/Qt-Projects | afc5cfe82b5495f370ad8d0cf9f20acf15c1ea49 | c86ed2d8eb4bba9d6fcd9d2aba206f5b4eded421 | refs/heads/master | 2022-12-02T18:33:04.040286 | 2020-08-17T07:36:55 | 2020-08-17T07:36:55 | 286,914,226 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,688 | cpp | settings.cpp | #include "settings.h"
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QMessageBox>
#include <QStandardPaths>
#include <QString>
#include <QStringListModel>
#include <utility>
namespace Skull {
static const int PW_CMD_INDEX = 5;
static auto RESOURCE_PREFIX = QStringLiteral(":/json");
Settings::Settings(QObject *parent, QString filename)
: QObject(parent), m_filename(filename),
m_modelCommands(*new QStringListModel(this)) {}
void Settings::ParseJsonData() {
QString raw_json = ReadJsonFile();
if (raw_json.size() == 0)
return;
auto json_res = GetJsonObject(raw_json);
auto json_err = json_res.second;
if (json_err.error != QJsonParseError::NoError) {
ShowJsonParseError(json_err);
}
auto json_obj = json_res.first;
m_applicationName = json_obj["applicationTitle"].toString();
m_appShortName = json_obj["appShortName"].toString();
m_hostName = json_obj["hostName"].toString();
m_portNumber = json_obj["port"].toInt();
m_longWaitMs = json_obj["tcpWaitMs"].toInt();
m_shortWaitMs = json_obj["readWaitMs"].toInt();
SetupCommands(json_obj);
}
QString Settings::ReadJsonFile() {
auto default_settings =
ReadJsonFromInternalResource(); // TODO do only if you need to ie. when
// custom config fails
QDir config_dir = OpenConfigurationDirectory();
auto path = config_dir.filePath(m_filename);
QFile std_file(path);
if (std_file.exists()) {
if (!std_file.open(QFile::ReadOnly | QFile::Text)) {
SendErrorMessage("Could not open " + path);
return default_settings;
}
QString settings = std_file.readAll();
std_file.close();
return settings;
} else {
WriteDefaultstoStdConfigFile(std_file, default_settings);
return default_settings;
}
}
void Settings::WriteDefaultstoStdConfigFile(QFile &stdConfigFile,
const QString &settings) {
int len = settings.size();
if (!stdConfigFile.open(QFile::WriteOnly | QFile::Text)) {
SendErrorMessage("Could not open file to write to " +
stdConfigFile.fileName());
}
auto bytes_written = stdConfigFile.write(qPrintable(settings), len);
if (bytes_written != len) {
SendErrorMessage("Could not write the settings to " +
stdConfigFile.fileName());
if (!stdConfigFile.remove()) {
SendErrorMessage("Could not remove config file. Please delete manually " +
stdConfigFile.fileName());
}
}
stdConfigFile.close();
}
QDir Settings::OpenConfigurationDirectory() {
QDir config_dir(
QStandardPaths::writableLocation(QStandardPaths::ConfigLocation));
if (!config_dir.exists()) {
QDir dir;
dir.mkpath(config_dir.path());
}
return config_dir;
}
void Settings::SetupCommands(const QJsonObject &jo) {
QJsonArray cmd_array = jo["commands"].toArray();
QStringList cmd_list;
for (auto item : cmd_array) {
cmd_list.append(item.toString());
}
m_modelCommands.setStringList(cmd_list);
auto index = m_modelCommands.index(PW_CMD_INDEX);
auto test_cmd = m_modelCommands.data(index, Qt::DisplayRole);
qDebug() << "test_cmd " << test_cmd.toString();
if (PW_CMD_INDEX < cmd_list.size()) {
m_pwCommand = cmd_list[PW_CMD_INDEX];
} else {
emit NotifyStatusMessage(tr("Unable to get pulse width command"));
}
}
JsonObjErrPair Settings::GetJsonObject(const QString &rawJson) {
QJsonParseError json_parse_error;
QJsonDocument json_doc =
QJsonDocument::fromJson(rawJson.toUtf8(), &json_parse_error);
auto json_obj = json_doc.object();
return std::make_pair(json_obj, json_parse_error);
}
QString Settings::ReadJsonFromInternalResource() {
QDir res_dir(RESOURCE_PREFIX);
if (!res_dir.exists()) {
SendErrorMessage("Internal resource path misssing " +
res_dir.canonicalPath());
return "";
}
auto path = res_dir.filePath(m_filename);
QFile res_file(path);
if (!res_file.open(QFile::ReadOnly | QFile::Text)) {
SendErrorMessage("Couldn't open internal resource" + path);
return "";
}
QString settings = res_file.readAll();
return settings;
}
void Settings::SendErrorMessage(const QString &msg) {
emit NotifyStatusMessage(msg);
}
void Settings::ShowJsonParseError(QJsonParseError err) {
QString msg = tr("Error parsing json settings file.\n");
msg.append(err.errorString());
// msg.append(tr("\nThe default value will be used."));
QMessageBox::critical(0, tr("VFP"), msg);
}
JsonObjErrPair Settings::GetJsonPair(const QString &rawJson) {}
} // namespace Skull
|
3b9402a8d95a1f2a3cb189b3edced7c5a80e283e | b5d45a79f971e138e17e54b57fecaaeab14b2b26 | /spoj/brckts.cpp | b067f097dd7d5c5e3a6a29fe1613ccf586877e41 | [] | no_license | vedsarkushwaha/code | 8a0ccab1a16a0e4b9c2151613322ea83a3d57288 | d2e9d6a3f27ea7875a86c7c4869bc3cff75ccca1 | refs/heads/master | 2021-07-05T02:47:43.012012 | 2020-08-27T21:36:48 | 2020-08-27T21:36:48 | 36,807,007 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,615 | cpp | brckts.cpp | #include<bits/stdc++.h>
#define fr(i,m,n) for(i=m;i<n;i++)
#define ifr(i,m,n) for(i=m;i>n;i--)
#define ll long long
#define sc scanf
#define pf printf
#define var(x) x i=0,j=0,k=0,tmp1=0,tmp2=0,tmp3=0,tmp=0,tmp4=0,tmp5=0,flag=0,T=0,N=0
#define pb push_back
#define vi vector<int>
#define vii vector<pair<int,int> >
#define vl vector<ll>
#define vll vector<pair<ll,ll> >
using namespace std;
struct node {
int l,r;
};
vector<node> segtree;
vi vec;
void init_seg(int N) {
node tmp;
tmp.l=0,tmp.r=0;
segtree.resize(4*N,tmp);
}
void build_seg(int nd, int l, int r) {
var(int);
if(l==r)
return;
else {
tmp1=2*nd,tmp2=2*nd+1;
build_seg(tmp1,l,(l+r)/2);
build_seg(tmp2,(l+r)/2+1,r);
segtree[nd].l=segtree[tmp1].l+segtree[tmp2].l;
segtree[nd].r=segtree[tmp1].r+segtree[tmp2].r;
}
}
node update(int nd, int l,int r,int i,int j) {
node p1,p2;
if(i>r || j<l) {
p1.bs=p1.pr=p1.su=p1.sm=INT_MIN;
return p1;
}
if (l>=i && r<=j)
return segtree[nd];
p1=query(2*nd,l,(l+r)/2,i,j);
p2=query(2*nd+1,(l+r)/2+1,r,i,j);
if(p1.bs==INT_MIN)
return p2;
if(p2.bs==INT_MIN)
return p1;
p1.bs=max(p1.su+p2.pr,max(p1.bs,p2.bs)),p1.su=max(p2.su,p2.sm+p1.su),p1.pr=max(p1.pr,p1.sm+p2.pr),p1.sm=p1.sm+p2.sm;
return p1;
}
int main() {
var(int);
T=10;
vec.pb(0);
fr(i,1,T+1) {
sc("%d",&tmp);
init_seg(tmp);
fr(j,1,tmp+1) {
sc("%c",&ch);
if(ch=='(') {
segtree[j].l=1;
segtree[j].r=0;
}
else {
segtree[j].l=0;
segtree[j].r=1;
}
}
}
build_seg(1,1,tmp);
sc("%d",&N);
while(N--) {
sc("%d",&tmp1);
if(tmp1==0)
//check
else
//update segtree
}
return 0;
} |
df81886172e9ece4019998e4a43dd26e40b7bd2a | 19b1c001545ae3083257a08516081ba053ba1c7a | /Cam3dCppClrWrapper/CamCommon/includes/CamCommon/BitWord.hpp | b03fbc4f0fd579337df2c37e017607c86d26e6c1 | [] | no_license | KFlaga/Cam3D | a6b324b2991b739067e584c4ced7ccc0726e1835 | fed29f8d2cc71146e7ddbb3af96000545373d339 | refs/heads/master | 2021-01-10T16:42:55.562158 | 2018-02-11T20:36:30 | 2018-02-11T20:36:30 | 46,155,063 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,463 | hpp | BitWord.hpp | #pragma once
#include "PreReqs.hpp"
#include <algorithm>
#include <cstring>
namespace cam3d
{
template<typename uint_t>
struct WordBitsLut
{
private:
static constexpr size_t wordBitsSize = ((size_t)std::numeric_limits<uint16_t>::max()) + 1;
public:
static uint_t* createWordBitsLut()
{
static uint_t wordBits[wordBitsSize];
uint_t count;
for (size_t i = 0, x; i < wordBitsSize; ++i)
{
x = i;
for (count = 0u; x > 0; ++count) { x &= x - 1; }
wordBits[i] = count;
}
return wordBits;
}
};
struct HammingLookup32
{
static inline uint32_t getOnesCount(uint32_t i)
{
static uint32_t* wordBits = WordBitsLut<uint32_t>::createWordBitsLut();
return (wordBits[i & 0x0000FFFF] + wordBits[i >> 16]);
}
};
struct HammingLookup64
{
static inline uint64_t getOnesCount(uint64_t i)
{
static uint64_t* wordBits = WordBitsLut<uint64_t>::createWordBitsLut();
return (wordBits[i & 0xFFFF] + wordBits[(i >> 16) & 0xFFFF] + wordBits[(i >> 32) & 0xFFFF] + wordBits[(i >> 48) & 0xFFFF]);
}
};
template<typename BWT>
struct BitWord_helper
{
};
template<size_t length, size_t bits, typename uint_type, typename HammingLookupT>
struct BitWord
{
static constexpr size_t lengthInWords = length;
static constexpr size_t bitSizeOfWord = bits;
using HammingLookup = HammingLookupT;
using uint_t = uint_type;
uint_t bytes[length];
BitWord()
{
std::memset(bytes, 0, sizeof(bytes));
}
BitWord(uint_t* bytes_)
{
std::memcpy(bytes, bytes_, sizeof(bytes));
}
public:
inline uint_t getHammingDistance(const BitWord& bw) const
{
return BitWord_helper<BitWord>::getOnesCount(bytes, bw.bytes);
}
};
template<size_t length>
using BitWord32 = BitWord<length, 32, uint32_t, HammingLookup32>;
template<size_t length>
using BitWord64 = BitWord<length, 64, uint64_t, HammingLookup64>;
// CLI non-working template recursion workaround
template<>
struct BitWord_helper<BitWord32<1>>
{
using BW = BitWord32<1>;
static BW::uint_t getOnesCount(const BW::uint_t* b1, const BW::uint_t* b2)
{
return BW::HammingLookup::getOnesCount(b1[0] ^ b2[0]);
}
};
template<>
struct BitWord_helper<BitWord32<2>>
{
using BW = BitWord32<2>;
static BW::uint_t getOnesCount(const BW::uint_t* b1, const BW::uint_t* b2)
{
return BW::HammingLookup::getOnesCount(b1[0] ^ b2[0]) +
BW::HammingLookup::getOnesCount(b1[1] ^ b2[1]);
}
};
template<>
struct BitWord_helper<BitWord32<3>>
{
using BW = BitWord32<3>;
static BW::uint_t getOnesCount(const BW::uint_t* b1, const BW::uint_t* b2)
{
return BW::HammingLookup::getOnesCount(b1[0] ^ b2[0]) +
BW::HammingLookup::getOnesCount(b1[1] ^ b2[1]) +
BW::HammingLookup::getOnesCount(b1[2] ^ b2[2]);
}
};
template<>
struct BitWord_helper<BitWord32<4>>
{
using BW = BitWord32<4>;
static BW::uint_t getOnesCount(const BW::uint_t* b1, const BW::uint_t* b2)
{
return BW::HammingLookup::getOnesCount(b1[0] ^ b2[0]) +
BW::HammingLookup::getOnesCount(b1[1] ^ b2[1]) +
BW::HammingLookup::getOnesCount(b1[2] ^ b2[2]) +
BW::HammingLookup::getOnesCount(b1[3] ^ b2[3]);
}
};
template<>
struct BitWord_helper<BitWord32<5>>
{
using BW = BitWord32<5>;
static BW::uint_t getOnesCount(const BW::uint_t* b1, const BW::uint_t* b2)
{
return BW::HammingLookup::getOnesCount(b1[0] ^ b2[0]) +
BW::HammingLookup::getOnesCount(b1[1] ^ b2[1]) +
BW::HammingLookup::getOnesCount(b1[2] ^ b2[2]) +
BW::HammingLookup::getOnesCount(b1[3] ^ b2[3]) +
BW::HammingLookup::getOnesCount(b1[4] ^ b2[4]);
}
};
template<>
struct BitWord_helper<BitWord32<6>>
{
using BW = BitWord32<6>;
static BW::uint_t getOnesCount(const BW::uint_t* b1, const BW::uint_t* b2)
{
return BW::HammingLookup::getOnesCount(b1[0] ^ b2[0]) +
BW::HammingLookup::getOnesCount(b1[1] ^ b2[1]) +
BW::HammingLookup::getOnesCount(b1[2] ^ b2[2]) +
BW::HammingLookup::getOnesCount(b1[3] ^ b2[3]) +
BW::HammingLookup::getOnesCount(b1[4] ^ b2[4]) +
BW::HammingLookup::getOnesCount(b1[5] ^ b2[5]);
}
};
template<>
struct BitWord_helper<BitWord32<7>>
{
using BW = BitWord32<7>;
static BW::uint_t getOnesCount(const BW::uint_t* b1, const BW::uint_t* b2)
{
return BW::HammingLookup::getOnesCount(b1[0] ^ b2[0]) +
BW::HammingLookup::getOnesCount(b1[1] ^ b2[1]) +
BW::HammingLookup::getOnesCount(b1[2] ^ b2[2]) +
BW::HammingLookup::getOnesCount(b1[3] ^ b2[3]) +
BW::HammingLookup::getOnesCount(b1[4] ^ b2[4]) +
BW::HammingLookup::getOnesCount(b1[5] ^ b2[5]) +
BW::HammingLookup::getOnesCount(b1[6] ^ b2[6]);
}
};
template<>
struct BitWord_helper<BitWord32<8>>
{
using BW = BitWord32<8>;
static BW::uint_t getOnesCount(const BW::uint_t* b1, const BW::uint_t* b2)
{
return BW::HammingLookup::getOnesCount(b1[0] ^ b2[0]) +
BW::HammingLookup::getOnesCount(b1[1] ^ b2[1]) +
BW::HammingLookup::getOnesCount(b1[2] ^ b2[2]) +
BW::HammingLookup::getOnesCount(b1[3] ^ b2[3]) +
BW::HammingLookup::getOnesCount(b1[4] ^ b2[4]) +
BW::HammingLookup::getOnesCount(b1[5] ^ b2[5]) +
BW::HammingLookup::getOnesCount(b1[4] ^ b2[4]) +
BW::HammingLookup::getOnesCount(b1[5] ^ b2[5]);
}
};
template<>
struct BitWord_helper<BitWord64<1>>
{
using BW = BitWord64<1>;
static BW::uint_t getOnesCount(const BW::uint_t* b1, const BW::uint_t* b2)
{
return BW::HammingLookup::getOnesCount(b1[0] ^ b2[0]);
}
};
template<>
struct BitWord_helper<BitWord64<2>>
{
using BW = BitWord64<2>;
static BW::uint_t getOnesCount(const BW::uint_t* b1, const BW::uint_t* b2)
{
return BW::HammingLookup::getOnesCount(b1[0] ^ b2[0]) +
BW::HammingLookup::getOnesCount(b1[1] ^ b2[1]);
}
};
template<>
struct BitWord_helper<BitWord64<3>>
{
using BW = BitWord64<3>;
static BW::uint_t getOnesCount(const BW::uint_t* b1, const BW::uint_t* b2)
{
return BW::HammingLookup::getOnesCount(b1[0] ^ b2[0]) +
BW::HammingLookup::getOnesCount(b1[1] ^ b2[1]) +
BW::HammingLookup::getOnesCount(b1[2] ^ b2[2]);
}
};
template<>
struct BitWord_helper<BitWord64<4>>
{
using BW = BitWord64<4>;
static BW::uint_t getOnesCount(const BW::uint_t* b1, const BW::uint_t* b2)
{
return BW::HammingLookup::getOnesCount(b1[0] ^ b2[0]) +
BW::HammingLookup::getOnesCount(b1[1] ^ b2[1]) +
BW::HammingLookup::getOnesCount(b1[2] ^ b2[2]) +
BW::HammingLookup::getOnesCount(b1[3] ^ b2[3]);
}
};
}
|
b645343861d0a128d9d7f18a84db5e254a9fa906 | 2f70a69e1c95db1d67963e315f1e449d11b87961 | /xen_scheduler/SysInfo.cpp | f0d840683a96e621f8a17dcfcf9debcbe472d66d | [] | no_license | kingrui/xen_scheduler | 946672e81f6c56493e1e951d4dedbcee212aa839 | ada561cc102496d673e7ef811d0549dc79ef1035 | refs/heads/master | 2021-01-20T07:02:06.649018 | 2015-09-14T06:29:46 | 2015-09-14T06:29:46 | 42,430,994 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,801 | cpp | SysInfo.cpp | /*
jinrui
*/
#include "SysInfo.h"
#include <iostream>
using namespace std;
/*
*The constructor of SysInfo
*Jin Rui
*jinrui@jinrui.name
*/
SysInfo::SysInfo(mutex &m)
{
mu = &m;
//set an initial connection use libvirt
if ((conn = virConnectOpen("xen:///"))== NULL){
perror("failed to execute virConnectOpen function");
return;
}
//system("xl cpupool-numa-split"); //split the domains to cpupool
system("python cpupool-numa-split.py");
memset(domainPtrList, 0, sizeof(domainPtrList)); //initialize the domain pointer list
domainCount = 0; //set domain count to 0
nodeCount = get_numa_node_nr(); //get the node number of system
get_node_distance_matrix(); //get the cpu distance matrix
getNodeCpuCount(); //get the node cpu count
memset(dom_mem_alloc, 0, sizeof dom_mem_alloc);
}
int SysInfo::getNodeCpuCount(void){
FILE *file_p;
if((file_p = fopen("node_info.cfg", "r")) == NULL){
perror("failed to open file 'result2'");
return ERROR;
}
int node_id;
int cpu_count;
for(int i=0;i<nodeCount;i++){
fscanf(file_p,"%d",&node_id);
fscanf(file_p,"%d",&cpu_count);
nodeCpuCount[node_id] = cpu_count;
cout<<"node"<<node_id<<": "<<cpu_count<<endl;
}
fclose(file_p);
return SUCCESS;
}
SysInfo::~SysInfo(void)
{
virConnectClose(conn); //close the connection of libvirt
}
double const SysInfo::WEIGHT_OF_CPU_COST = 1.0;
/*
*return an instance of SysInfo
*Jin Rui
*jinrui@jinrui.name
*2013-08-08
*/
SysInfo* SysInfo::getInstance(std::mutex &m){
static SysInfo sys(m);
return &sys;
}
void SysInfo::run(){
while(true){
mu->lock();
getActiveDomian(); //get the domains list that need schedule
getDomainsInfo(); //get the information of domians
mu->unlock();
this_thread::sleep_for(chrono::seconds(10)); //sleep for ten seconds
}
}
/*
*get the domains list that need schedule
*Jin Rui
*jinrui@jinrui.name
*2013-08-08
*/
int SysInfo::getActiveDomian(){
int totalDomainCount = 0;
virDomainPtr domsPtr_total_list[MAX_DOMS_NUM];
/*
* get the active domain, store the domian_ptr in doms_active_Ptr_lst[i];
*/
totalDomainCount = virConnectNumOfDomains(conn);//the number of domain found or -1 in case of error
this->allRunningDomainsNum = totalDomainCount; //save the all running domains number to allRunningDomainsNum
if(totalDomainCount < 0){
perror("failed to execute virConnectNumOfDomains");
return ERROR;
}
totalDomainCount = virConnectListDomains(conn, dom_active_id_list, totalDomainCount);//dom_active_id_lst array to collect the list of IDs of active domains
if(totalDomainCount < 0){
perror("failed to execute virConnectListDomains");
return ERROR;
}
//get all the domain pointer by domain id
for(int i = 0; i < totalDomainCount; i++){
domsPtr_total_list[i] = virDomainLookupByID(conn, dom_active_id_list[i]);//get domain pointer by id
if(domsPtr_total_list[i] == NULL){
perror("failed to execute virDomainLookupByID");
return ERROR;
}
}
/*
* query every domains's used memory
* set domsPtr_active_lst[i] = NULL,
* if the domain's mem is less than the MEM_THREASHOLD.
*/
virDomainInfo domain_info;
for(int i = 0; i < totalDomainCount; i++){
if(virDomainGetInfo(domsPtr_total_list[i], &domain_info) < 0){
perror("failed to virDomainGetInfo");
return ERROR;
}
//DEBUG print every domain memory.
cout<<"dom_mem_max : "<<domain_info.maxMem<<endl;
cout<<"dom_mem_used : "<<domain_info.memory<<endl;
//if the memory usage of a domain is less than threshold, free the domain pointer
if(domain_info.memory < MEM_THRESHOLD){
free(domsPtr_total_list[i]);
domsPtr_total_list[i] = NULL;
}
}
/*
* query every domain CPU total utilization.
* populate domsPtr_sche_lst
*/
domainCount= 0;
double dom_cpu_uti = 0.0;
/*
for (int i = 0; i < totalDomainCount; i++){
cout << "-dom_active_id_list[" << i << "]:" << dom_active_id_list[i] << endl;
}
*/
for(int i = 0; i < totalDomainCount; i++){
if(domsPtr_total_list[i] != NULL){
if(dom_active_id_list[i]==0)//ignore domain0
{
continue;
}
dom_cpu_uti = domain_get_cpu_util(domsPtr_total_list[i]);
cout<<"dom_cpu_utilization : "<<dom_cpu_uti<<endl;
if(dom_cpu_uti > CPU_THRESHOLD){
domainPtrList[domainCount] = domsPtr_total_list[i];
dom_active_id_list[domainCount++] = dom_active_id_list[i];
}
else
continue;
}
}
for (int i = 0; i < domainCount; i++){
cout << "dom_active_id_list[" << i << "]:" << dom_active_id_list[i] << endl;
//getchar();
}
return SUCCESS;
}
double SysInfo::domain_get_cpu_util(virDomainPtr domain_p){
virDomainInfo info;
double cpu_time_fir; //cnt in ns
double cpu_time_sec; //cnt in ns
struct timeval sys_time_fir; //cnt in us
struct timeval sys_time_sec; //cnt in us
double cpu_time_elap; //cnt in us
double sys_time_elap; //cnt in us
//first snapshot of CPU time and current_system_time;
if ((virDomainGetInfo(domain_p, &info)) < 0)
perror("failed virDomainGetInfo to get the CPU time");
cpu_time_fir = (double)info.cpuTime;
if (gettimeofday(&sys_time_fir, NULL) == -1)
perror("failed to gettimeofday.");
if(sleep(SLEEP_INTERVAL) != 0)
perror("failed to sleep for a while");
//second snapshot of CPU time and current_system_time;
if ((virDomainGetInfo(domain_p, &info)) < 0)
perror("failed virDomainGetInfo to get the CPU time");
cpu_time_sec = (double)info.cpuTime;
if (gettimeofday(&sys_time_sec, NULL) == -1)
perror("failed to gettimeofday.");
//calculate the CPU utilization.
cpu_time_elap = (cpu_time_sec - cpu_time_fir) / 1000;
sys_time_elap = 1000000 * (sys_time_sec.tv_sec - sys_time_fir.tv_sec) +
(sys_time_sec.tv_usec - sys_time_fir.tv_usec);
return cpu_time_elap / (double)sys_time_elap;
}
/*
*Get the number of node
*Jin Rui
*jinrui@jinrui.name
*2013-07-08
*/
int SysInfo::get_numa_node_nr(){
return getNumaInfo((char *)("xl info -n | grep nr_nodes > ./numa_info"));
}
/*
*Get the number of cpus
*Jin Rui
*jinrui@jinrui.name
*2013-07-08
*/
int SysInfo::get_pcpus_nr(){
return getNumaInfo((char *)("xl info -n | grep nr_cpus > ./numa_info"));
}
/*
*Help to get the number of nodes and cpus by a system call
*Jin Rui
*jinrui@jinrui.name
*2013-07-08
*/
int SysInfo::getNumaInfo(char* searchText){
int nodeNum = 0;
char a[50];//save syscall result
int i=0;
//serchText is sth. like "xl -f info -n | grep nr_cpus > ./numa_info"
if(system(searchText) < 0){
perror("failed to execute system() to get xm info");
}
FILE *numa_info_file_p;
if((numa_info_file_p = fopen("./numa_info", "r")) < 0){
perror("failed to fopen the file numa_info.");
return -1;
}
else{
//get the number from the result like "nr_nodes : 2"
fgets(a,50,numa_info_file_p);
while(i<50&&a[i] != '\0'){
if(a[i]>='0'&&a[i]<='9'){
nodeNum = nodeNum*10 + (a[i]-'0');
}
i++;
}
}
fclose(numa_info_file_p);
return nodeNum;
}
int SysInfo::get_node_distance_matrix()
{
cout<<"starting to get_node_distance_matrix..."<<endl;
//set default distance
for(int i=0;i<nodeCount;i++)
for(int j=0;j<nodeCount;j++){
if(i==j)
node_dist_matrix[i][j] = 10;
else
node_dist_matrix[i][j] = 20;
}
/*
char cmd[MAX_CHARS_ONE_LINE];
char file_name[MAX_LEN_FILE_NAME];
char buff[MAX_FILE_BUFF_SIZE];
sprintf(cmd, "xl info -n > numa_info");
if(system(cmd) < 0){
perror("failed to execute the xl info command");
return ERROR;
}
FILE *file_p;
if((file_p = fopen("numa_info", "r")) == NULL){
perror("failed to open file 'numa_info'");
return ERROR;
}
fgets(buff, MAX_FILE_BUFF_SIZE, file_p);
while(!strstr(buff,"numa_info")){
if(fgets(buff, MAX_FILE_BUFF_SIZE, file_p)==NULL)
return ERROR;
}
fgets(buff, MAX_FILE_BUFF_SIZE, file_p);
for(int i=0;i<nodeCount;i++){
fgets(buff, MAX_FILE_BUFF_SIZE, file_p);
cout<<buff;
int p;
int memsize=0;
int memfree=0;
for(p=0;p<MAX_FILE_BUFF_SIZE&&buff[p]!=':';p++);//skip domainid:
for(;p<MAX_FILE_BUFF_SIZE&&(buff[p]<'0'||buff[p]>'9');p++);//skip ' '
for(;p<MAX_FILE_BUFF_SIZE&&(buff[p]>='0'&&buff[p]<='9');p++)//get memsize
{
memsize = memsize*10+buff[p]-'0';
}
cout<<"memsize:"<<memsize<<endl;
for(;p<MAX_FILE_BUFF_SIZE&&(buff[p]<'0'||buff[p]>'9');p++);//skip ' '
for(;p<MAX_FILE_BUFF_SIZE&&(buff[p]>='0'&&buff[p]<='9');p++)//get memfree
{
memfree = memfree*10+buff[p]-'0';
}
cout<<"memfree:"<<memfree<<endl;
for(;p<MAX_FILE_BUFF_SIZE&&(buff[p]<'0'||buff[p]>'9');p++);//skip ' '
for(int j=0;j<nodeCount;j++)//get node distance
{
int dis =0;
for(;p<MAX_FILE_BUFF_SIZE&&(buff[p]>='0'&&buff[p]<='9');p++){
dis = dis*10 + buff[p]-'0';
}
p++;
node_dist_matrix[i][j] = dis;
cout<<"dist["<<i<<"]["<<j<<"]="<<dis<<endl;
}
}
fclose(file_p);
*/
cout<<"finish to get_node_distance_matrix..."<<endl;
return SUCCESS;
}
/*
* Get domain Cpu usage per node(domain i)
* jinrui
* jinrui@jinrui.name
* 2013-07-11
*/
int SysInfo::getCpuMatrix(int i){
cout<<"running getCPUMatrix..."<<endl;
virVcpuInfo vcpuinfo_lst[MAX_VCPU_IN_DOMAINS];
virVcpuInfo vcpuinfo_lst2[MAX_VCPU_IN_DOMAINS];
double CpuTime[MAX_VCPU_IN_DOMAINS];
int kk=0;
int cpu_node_map[MAX_CPUS_NUM];
int nr_vcpus = MAX_VCPU_IN_DOMAINS;
unsigned char *cpumaps;
int j;
int cpumap_len = get_pcpus_nr()/BITS_IN_ONE_BYTES;
for(kk=0;kk<nodeCount;kk++){
cpu_node_map[kk] = -1;
}
system("xl debug-keys u");
system("xl dmesg | grep \"(XEN) CPU[0-9]* -> NODE[0-9]*\" >mesgout");
system("sed 's/(XEN) CPU//g' mesgout -i");
system("sed 's/ -> NODE/ /g' mesgout -i");
FILE *file_p;
if((file_p = fopen("mesgout", "r")) == NULL){
perror("failed to open file 'mesgout'");
return ERROR;
}
int pcpuNum;
int nodeNum;
while(fscanf(file_p, "%d%d",&pcpuNum,&nodeNum)==2){
//printf("debug-%d,%d\n",pcpuNum,nodeNum);
cpu_node_map[pcpuNum] = nodeNum;
}
fclose(file_p);
cpumaps = (unsigned char*)calloc(nr_vcpus, cpumap_len);
nr_vcpus = virDomainGetVcpus(domainPtrList[i], vcpuinfo_lst, nr_vcpus, cpumaps, cpumap_len);
if (nr_vcpus < 0){
perror("failed to virDomainGetVcpus");
exit(ERROR);
}
struct timeval sys_time_fir; //cnt in us
struct timeval sys_time_sec; //cnt in us
if (gettimeofday(&sys_time_fir, NULL) == -1)
perror("failed to gettimeofday.");
if(sleep(SLEEP_INTERVAL) != 0)
perror("failed to sleep for a while");
nr_vcpus = virDomainGetVcpus(domainPtrList[i], vcpuinfo_lst2, nr_vcpus, cpumaps, cpumap_len);
if (nr_vcpus < 0){
perror("failed to virDomainGetVcpus");
exit(ERROR);
}
if (gettimeofday(&sys_time_sec, NULL) == -1)
perror("failed to gettimeofday.");
double sys_time_elap = 1000000 * (sys_time_sec.tv_sec - sys_time_fir.tv_sec) +
(sys_time_sec.tv_usec - sys_time_fir.tv_usec);
cout<<"nr_vcpus:"<<nr_vcpus<<endl;
float cpuTimeSum = 0;
for(kk=0;kk<nr_vcpus;kk++){
CpuTime[kk] = vcpuinfo_lst2[kk].cpuTime - vcpuinfo_lst[kk].cpuTime;
cpuTimeSum += CpuTime[kk];
cout<<"number:"<<vcpuinfo_lst2[kk].number<<",cpu:"<<vcpuinfo_lst2[kk].cpu<<endl;
}
for(kk=0;kk<nodeCount;kk++){
C[i][kk]=0;
CPU[i][kk]=0;
}
for(kk=0;kk<nr_vcpus;kk++){
int nodeNum = cpu_node_map[vcpuinfo_lst2[kk].cpu];
if(nodeNum>=0){
C[i][nodeNum]+= (CpuTime[kk]/cpuTimeSum);
CPU[i][nodeNum]+= CpuTime[kk];
}
//cout<<"Vcpu:"<<kk<<",cpu:"<<C[i][nodeNum]<<endl;
}
//
for(kk=0;kk<nodeCount;kk++){
cout<<"node"<<kk<<":normalized:"<<C[i][kk]<<endl;
cout<<"node"<<kk<<":"<<CPU[i][kk]<<endl;
}
free(cpumaps);
cout<<"finish getCPUMatrix..."<<endl;
return SUCCESS;
}
/*
* Get domain's memory distribution(domian i,domain id is dom_id)
* jinrui
* jinrui@jinrui.name
* 2013-07-11
*/
void SysInfo::getMemoryMatrix(int i,int dom_id){
cout<<"running getMemoryMatrix..."<<endl;
char dmesg_cmd[MAX_CHARS_ONE_LINE];
system("xl debug-keys u");
sprintf(dmesg_cmd, "xl dmesg | tail -n %d > mem_distri", (nodeCount + 1) * domainCount);
system(dmesg_cmd);
if(parse_domain_mem_alloc(dom_id) < -1){
perror("failed to parser the dom_mem_alloc");
return ;
}
//get memory usage pesentage per node
int memory_sum = 0;
int kk=0;
for(kk = 0; kk < nodeCount; kk++){
memory_sum+=dom_mem_alloc[kk];
}
for(kk = 0; kk < nodeCount; kk++){
M[i][kk]=dom_mem_alloc[kk]*1.0/memory_sum;
MEM[i][kk]=dom_mem_alloc[kk];
}
for(kk = 0; kk < nodeCount; kk++){
cout<<"memory-node"<<kk<<":"<<M[i][kk]<<endl;
}
cout<<"finish getMemoryMatrix..."<<endl;
return ;
}
/*
*Modified by
*Jin Rui
*jinrui@jinrui.name
*2013-07-09
*/
int SysInfo::parse_domain_mem_alloc(int dom_id)
{
FILE *file_p;
char cmd[MAX_CHARS_ONE_LINE];
char file_name[MAX_LEN_FILE_NAME];
char buff[MAX_FILE_BUFF_SIZE];
/*
* 'sed' to grep the domain memory information
* store the into mem_info_DomX
*/
sprintf(cmd, "cat mem_distri | sed -n '/Domain %d /,+%dp' | tail -n %d > mem_info_Dom%d", dom_id, nodeCount, nodeCount, dom_id);
if(system(cmd) < 0){
perror("failed to system the 'sed' to grep domainX");
return ERROR;
}
sprintf(file_name, "mem_info_Dom%d", dom_id);
if((file_p = fopen(file_name, "r")) == NULL){
perror("failed to open file 'mem_info_Dom'");
return ERROR;
}
for(int i = 0; i < nodeCount; i++){
fgets(buff, MAX_FILE_BUFF_SIZE, file_p);
dom_mem_alloc[i]=0;
//buff="XEN Node 0: 748374",get the finger from buff
strtok(buff, ":");
char *num_p = strtok(NULL, ":");//num_p=' 748374'
int k=0;
while(*(num_p+k)&&num_p[k] != '\0'){
if(num_p[k]>='0'&&num_p[k]<='9'){
dom_mem_alloc[i] = dom_mem_alloc[i]*10 + (num_p[k]-'0');
}
k++;
}
cout<<"dome_id:"<<dom_id<<",node:"<<i<<",mem_alloc:"<<dom_mem_alloc[i]<<endl;
}
fclose(file_p);
sprintf(cmd, "rm mem_info_Dom%d", dom_id);
if(system(cmd) < 0){
perror("failed to system the 'rm' to remove temperate file");
return ERROR;
}
return SUCCESS;
}
//the 2 dimensional array's second dimensional number must be assign. temporally assign it to 2
int SysInfo::calc_cost(int domain_i,int which_node_to_cal)
{
int sum_cost = 0;
for(int i = 0; i < nodeCount; i++){
sum_cost += M[domain_i][i] * node_dist_matrix[which_node_to_cal][i];
}
sum_cost+= CPU[domain_i][which_node_to_cal]*WEIGHT_OF_CPU_COST;
return sum_cost;
}
/*
*get the domain information
*Jin Rui
*jinrui@jinrui.name
*2013-07-09
*/
int SysInfo::getDomainsInfo(){
cout<<"starting to getDomainsInfo"<<endl;
memset(node_dist_matrix, 0, sizeof node_dist_matrix);
int currentDomainCount = virConnectNumOfDomains(conn);//the number of domain found or -1 in case of error
if(currentDomainCount!=this->allRunningDomainsNum){
cout<<"Domains have been changed"<<endl;
return ERROR;
}
for(int i = 0; i < domainCount; i++){
int dom_id = dom_active_id_list[i];
//Get domain's CPU distribution:
getCpuMatrix(i);
//Get domain's memory distribution:
getMemoryMatrix(i,dom_id);
//get the cost for each domain node
for(int j=0;j<nodeCount;j++){
cost[i][j] = calc_cost(i,j);
}
}
/*
for(int i=0;i< domainCount;i++){
for(int j=0;j<nodeCount;j++){
cout<<"domain"<<i<<":node"<<j<<"-C:"<<C[i][j]<<endl;
cout<<"domain"<<i<<":node"<<j<<"-CPU:"<<CPU[i][j]<<endl;
}
}
*/
//getMissRate();
cout<<"finish to getDomainsInfo"<<endl;
return SUCCESS;
}
/*
* get MissRate of each domain
* Jinrui
* jinrui@jinrui.name
* 2013-08-24
*/
int SysInfo::getMissRate(){
//--passive-domains=1,2,3 --passive-images=/boot/vmlinux-3.0.13-0.27-xen,/boot/vmlinux-3.0.13-0.27-xen,/boot/vmlinux-3.0.13-0.27-xen
char command[1000] = "opcontrol --start-daemon --event=LLC_MISSES:6000:0x41:1:1 --event=LLC_REFS:6000:0x4f:1:1 --xen=/boot/xen-syms-4.1.2_14-0.5.5 --vmlinux=/boot/vmlinux-3.0.13-0.27-xen --active-domains=0 --session-dir=/root/op_samples/ ";
if(domainCount>0){
strcat(command,"--passive-domains=");
}
for(int i=0;i<domainCount;i++){
if(i!=domainCount-1){
sprintf(command, "%s%d,", command, dom_active_id_list[i]);
}
else{
sprintf(command, "%s%d", command, dom_active_id_list[i]);
}
}
if(domainCount>0){
strcat(command,"--passive-images=");
}
for(int i=0;i<domainCount;i++){
if(i!=domainCount-1){
strcat(command,"/boot/vmlinux-3.0.13-0.27-xen,");
}
else{
strcat(command,"/boot/vmlinux-3.0.13-0.27-xen");
}
}
if(system(command) < 0){
perror("failed to set opcontrol");
return ERROR;
}
char command2[MAX_CHARS_ONE_LINE] = "opcontrol --start";
if(system(command2) < 0){
perror("failed to start opcontrol");
return ERROR;
}
this_thread::sleep_for(chrono::seconds(20));
char command3[MAX_CHARS_ONE_LINE] = "opcontrol --stop;opreport --session-dir=/root/op_samples > result";
if(system(command3) < 0){
perror("failed to stop opcontrol");
return ERROR;
}
char cmd[MAX_CHARS_ONE_LINE] = "cat result | grep -E 'domain[0-9]+-[a-z]+' > result2";
if(system(cmd) < 0){
perror("failed to grep domains' miss rate");
return ERROR;
}
//Domains' infomation are in file result2, example as follows:
/*
538 12.7973 11947 10.1256 domain2-apps
403 9.5861 8732 7.4008 domain2-modules
351 8.3492 12733 10.7918 domain13-modules
260 6.1846 16169 13.7039 domain13-apps
229 5.4472 9808 8.3127 domain1-apps
211 5.0190 7394 6.2667 domain1-modules
25 0.5947 3862 3.2732 domain3-xen
13 0.3092 2697 2.2858 domain2-xen
9 0.2141 2630 2.2290 domain1-xen
2 0.0476 65 0.0551 domain3-xen-unknown
0 0 47 0.0398 domain1-xen-unknown
0 0 60 0.0509 domain2-xen-unknown
*/
//get domain num from result file
char cmd2[MAX_CHARS_ONE_LINE] = "grep -E 'domain[0-9]+' result2 -o | grep -E '[0-9]+' -o > result3";
if(system(cmd2) < 0){
perror("failed to grep domains' number");
return ERROR;
}
//open file result2
FILE *file_p;
if((file_p = fopen("result2", "r")) == NULL){
perror("failed to open file 'result2'");
return ERROR;
}
//open file result3
FILE *file_n;
if((file_n = fopen("result3","r")) == NULL){
perror("failed to open file 'result3'");
return ERROR;
}
double sample1;
double sample2;
double uselessData;
//char domainName[80];
int domainNum;
double domainMissSum[MAX_DOMS_NUM];
double domainSampleSum[MAX_DOMS_NUM];
for(int i=0;i<domainCount;i++){
domainMissSum[i] = 0;
domainSampleSum[i] = 0;
}
while(fscanf(file_p,"%lf",&sample1)>0){
fscanf(file_p,"%lf",&uselessData);
fscanf(file_p,"%lf",&sample2);
fscanf(file_p,"%lf",&uselessData);
//fscanf(file_p,"%s",domainName);
//printf("%f:%f\n",sample1,sample2);
fscanf(file_n,"%d",&domainNum);
domainMissSum[domainNum] += sample1;
domainSampleSum[domainNum] += sample2;
}
for(int i=0;i<MAX_DOMS_NUM;i++){
MissRate[i] = 0;
if(domainSampleSum[i]!=0){
MissRate[i] = domainMissSum[i] / domainSampleSum[i];
//cout << "MissRate of domain" << i << ":" << MissRate[i] << endl;
}
else{
MissRate[i] = 0;
}
}
fclose(file_p);
fclose(file_n);
return SUCCESS;
}
|
a64bfa6eac64b4b7fc4457e75f62e43f35fa009b | 6a117dfa4ec8b89301fc98beaa6efa227094bf1d | /proxy/logging/LogFile.h | 2e345a5d171113e27d225532631b5fd046774109 | [
"LicenseRef-scancode-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-3-Clause",
"TCL",
"MIT",
"HPND",
"ISC",
"BSD-2-Clause"
] | permissive | pixiv/trafficserver | ab1e0736afdfee512d81ffc73b7d5b6eeef3f6bf | 79b01ca4e98d1ffde94324ca25ec6c7c3fce5a03 | refs/heads/release | 2023-04-10T12:01:37.946504 | 2016-03-02T00:59:27 | 2016-03-02T00:59:27 | 52,246,093 | 1 | 1 | Apache-2.0 | 2023-03-27T03:04:55 | 2016-02-22T04:05:04 | C++ | UTF-8 | C++ | false | false | 5,781 | h | LogFile.h | /** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef LOG_FILE_H
#define LOG_FILE_H
#include <stdarg.h>
#include <stdio.h>
#include "libts.h"
#include "LogBufferSink.h"
class LogSock;
class LogBuffer;
struct LogBufferHeader;
class LogObject;
#define LOGFILE_ROLLED_EXTENSION ".old"
#define LOGFILE_SEPARATOR_STRING "_"
/*-------------------------------------------------------------------------
MetaInfo
Meta information for LogFile
-------------------------------------------------------------------------*/
class MetaInfo
{
public:
enum {
DATA_FROM_METAFILE = 1, // metadata was read (or attempted to)
// from metafile
VALID_CREATION_TIME = 2, // creation time is valid
VALID_SIGNATURE = 4, // signature is valid
// (i.e., creation time only)
FILE_OPEN_SUCCESSFUL = 8 // metafile was opened successfully
};
enum {
BUF_SIZE = 640 // size of read/write buffer
};
private:
char *_filename; // the name of the meta file
time_t _creation_time; // file creation time
uint64_t _log_object_signature; // log object signature
int _flags; // metainfo status flags
char _buffer[BUF_SIZE]; // read/write buffer
void _read_from_file();
void _write_to_file();
void _build_name(const char *filename);
public:
MetaInfo(const char *filename) : _flags(0)
{
_build_name(filename);
_read_from_file();
}
MetaInfo(char *filename, time_t creation, uint64_t signature)
: _creation_time(creation), _log_object_signature(signature), _flags(VALID_CREATION_TIME | VALID_SIGNATURE)
{
_build_name(filename);
_write_to_file();
}
~MetaInfo() { ats_free(_filename); }
bool
get_creation_time(time_t *time)
{
if (_flags & VALID_CREATION_TIME) {
*time = _creation_time;
return true;
} else {
return false;
}
}
bool
get_log_object_signature(uint64_t *signature)
{
if (_flags & VALID_SIGNATURE) {
*signature = _log_object_signature;
return true;
} else {
return false;
}
}
bool
data_from_metafile() const
{
return (_flags & DATA_FROM_METAFILE ? true : false);
}
bool
file_open_successful()
{
return (_flags & FILE_OPEN_SUCCESSFUL ? true : false);
}
};
/*-------------------------------------------------------------------------
LogFile
-------------------------------------------------------------------------*/
class LogFile : public LogBufferSink, public RefCountObj
{
public:
LogFile(const char *name, const char *header, LogFileFormat format, uint64_t signature, size_t ascii_buffer_size = 4 * 9216,
size_t max_line_size = 9216);
LogFile(const LogFile &);
~LogFile();
enum {
LOG_FILE_NO_ERROR = 0,
LOG_FILE_NO_PIPE_READERS,
LOG_FILE_COULD_NOT_CREATE_PIPE,
LOG_FILE_PIPE_MODE_NOT_SUPPORTED,
LOG_FILE_COULD_NOT_OPEN_FILE,
LOG_FILE_FILESYSTEM_CHECKS_FAILED
};
int preproc_and_try_delete(LogBuffer *lb);
int roll(long interval_start, long interval_end);
const char *
get_name() const
{
return m_name;
}
void change_header(const char *header);
void change_name(const char *new_name);
LogFileFormat
get_format() const
{
return m_file_format;
}
const char *
get_format_name() const
{
return (m_file_format == LOG_FILE_BINARY ? "binary" : (m_file_format == LOG_FILE_PIPE ? "ascii_pipe" : "ascii"));
}
static int write_ascii_logbuffer(LogBufferHeader *buffer_header, int fd, const char *path, const char *alt_format = NULL);
int write_ascii_logbuffer3(LogBufferHeader *buffer_header, const char *alt_format = NULL);
static bool rolled_logfile(char *file);
static bool exists(const char *pathname);
void display(FILE *fd = stdout);
int open_file();
off_t
get_size_bytes() const
{
return m_file_format != LOG_FILE_PIPE ? m_bytes_written : 0;
};
int
do_filesystem_checks()
{
return 0;
}; // TODO: this need to be tidy up when to redo the file checking
public:
bool
is_open()
{
return (m_fd >= 0);
}
void close_file();
void check_fd();
static int writeln(char *data, int len, int fd, const char *path);
void read_metadata();
public:
LogFileFormat m_file_format;
private:
char *m_name;
public:
char *m_header;
uint64_t m_signature; // signature of log object stored
MetaInfo *m_meta_info;
size_t m_ascii_buffer_size; // size of ascii buffer
size_t m_max_line_size; // size of longest log line (record)
int m_fd;
long m_start_time;
long m_end_time;
volatile uint64_t m_bytes_written;
off_t m_size_bytes; // current size of file in bytes
public:
Link<LogFile> link;
private:
// -- member functions not allowed --
LogFile();
LogFile &operator=(const LogFile &);
};
/***************************************************************************
LogFileList IS NOT USED
****************************************************************************/
#endif
|
10d72aaa8727066e660348f827a24b0434d37ee0 | 554a3b859473dc4dfebc6a31b16dfd14c84ffd09 | /ui/sxgo_frame.hpp | 0a4986e0335613f18e75d3239a7be134638e1644 | [
"BSL-1.0"
] | permissive | DannyHavenith/sxsim | c0fbaf016fc7dcae7535e152ae9e33f3386d3792 | e3d5ad1f6f75157397d03c191b4b4b0af00ebb60 | refs/heads/master | 2021-01-19T11:22:20.615306 | 2011-05-30T22:11:18 | 2011-05-30T22:11:18 | 1,822,817 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,621 | hpp | sxgo_frame.hpp |
// Copyright Danny Havenith 2006 - 2009.
// 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)
/// wxWindows class for the main frame of this application.
#include "wx/aui/aui.h"
#include "wx/docmdi.h"
#include "sxgo_event_definitions.hpp"
class wxMenu;
class sxgo_ram_window;
class sxgo_variables_window;
class sxgo_document;
class sxgo_label_window;
class MyFrame : public wxDocMDIParentFrame , public sxgo_event_definitions
{
public:
static MyFrame *GetMainFrame(){return main_frame;}
MyFrame(wxDocManager *manager, wxFrame *frame, const wxString& title, const wxPoint& pos, const wxSize& size,
long type);
~MyFrame();
wxAuiDockArt* GetDockArt();
void DoUpdate();
wxAuiManager &GetUIManager() { return m_mgr;}
void UpdateAll( const sxgo_document &);
static wxMenuBar *CreateFrameMenuBar();
private:
void OnEraseBackground(wxEraseEvent& evt);
void OnSize(wxSizeEvent& evt);
void OnExit(wxCommandEvent& evt);
void OnAbout(wxCommandEvent& evt);
void OnTabAlignment(wxCommandEvent &evt);
void OnUpdateUI(wxUpdateUIEvent& evt);
void OnRestorePerspective(wxCommandEvent& evt);
void OnCreatePerspective(wxCommandEvent& evt);
void OnCopyPerspectiveCode(wxCommandEvent& evt);
private:
static MyFrame *main_frame;
wxAuiManager m_mgr;
wxArrayString m_perspectives;
sxgo_ram_window *m_ram_window;
sxgo_variables_window *m_variables_window;
sxgo_label_window *m_label_window;
DECLARE_EVENT_TABLE()
};
|
7eaadc4c2061dd841ed7b97f622a07bc4f1fffda | e649acb68fc5134a3843ef2330e5c2d4070363a8 | /L.lonely_day.cpp | 56d27ac1d6e5633c6f3a2305a7e4077423cc6cd3 | [] | no_license | jesuswr/cp-codes-and-problems | 6483949ce896e59c471f0e0640f5c8b47f482ec3 | 770f3bf004f90015f078d5699d26cde5c33d9a28 | refs/heads/master | 2023-08-08T03:37:36.626572 | 2023-07-24T16:54:02 | 2023-07-24T16:54:02 | 196,292,128 | 1 | 1 | null | 2019-10-09T23:23:43 | 2019-07-11T00:26:10 | C++ | UTF-8 | C++ | false | false | 3,507 | cpp | L.lonely_day.cpp | #include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
#include <math.h>
#include <string>
#include <cstring>
#include <set>
#include <map>
#include <unordered_map>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<int, pair<int, int>> piii;
typedef vector<int> vi;
typedef vector<pii> vii;
#define ri(a) scanf("%d", &a)
#define rii(a,b) scanf("%d %d", &a, &b)
#define riii(a,b,c) scanf("%d %d %d", &a, &b, &c)
#define rl(a) scanf("%lld", &a)
#define rll(a,b) scanf("%lld %lld", &a, &b)
#define FOR(i,n,m) for(int i=n; i<m; i++)
#define ROF(i,n,m) for(int i=n; i>m; i--)
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define F first
#define S second
const int INF = 0x3f3f3f3f;
const ll LLINF = 1e18;
const int MAXN = 2010; // CAMBIAR ESTE
// GJNM
int n, m;
char MAT[MAXN][MAXN];
int mv[MAXN][MAXN][4]; // up down left right
bool vis[MAXN][MAXN];
int cst[MAXN][MAXN];
char to[MAXN][MAXN];
int f(int r, int c) {
queue<pii> bfs;
bfs.push({r, c});
vis[r][c] = true;
while (!bfs.empty()) {
int nr = bfs.front().F, nc = bfs.front().S; bfs.pop();
if (MAT[nr][nc] == 'E')
return cst[nr][nc];
if (mv[nr][nc][1] != -1 && (!vis[ mv[nr][nc][1] ][nc])) {
cst[ mv[nr][nc][1] ][nc] = cst[nr][nc] + 1;
to[ mv[nr][nc][1] ][nc] = 'D';
bfs.push( {mv[nr][nc][1], nc} );
vis[ mv[nr][nc][1] ][nc] = true;
}
if (mv[nr][nc][2] != -1 && (!vis[nr][ mv[nr][nc][2] ])) {
cst[nr][ mv[nr][nc][2] ] = cst[nr][nc] + 1;
to[nr][ mv[nr][nc][2] ] = 'L';
bfs.push( {nr, mv[nr][nc][2]} );
vis[nr][mv[nr][nc][2]] = true;
}
if (mv[nr][nc][3] != -1 && (!vis[nr][ mv[nr][nc][3] ])) {
cst[nr][ mv[nr][nc][3] ] = cst[nr][nc] + 1;
to[nr][ mv[nr][nc][3] ] = 'R';
bfs.push( {nr, mv[nr][nc][3]} );
vis[nr][mv[nr][nc][3]] = true;
}
if (mv[nr][nc][0] != -1 && (!vis[ mv[nr][nc][0] ][nc])) {
cst[ mv[nr][nc][0] ][nc] = cst[nr][nc] + 1;
to[ mv[nr][nc][0] ][nc] = 'U';
bfs.push( {mv[nr][nc][0], nc} );
vis[mv[nr][nc][0]][nc] = true;
}
}
return -1;
}
int main() {
rii(n, m);
FOR(i, 0, n) {
scanf("%s", MAT[i]);
}
FOR(i, 0, n) {
FOR(j, 0, m) {
mv[i][j][0] = mv[i][j][1] = mv[i][j][2] = mv[i][j][3] = -1;
}
}
FOR(c, 0, m) {
// up
int lst = -1;
FOR(r, 0, n) {
if (MAT[r][c] == 'X') continue;
mv[r][c][0] = lst;
lst = r;
}
// down
lst = -1;
ROF(r, n - 1, -1) {
if (MAT[r][c] == 'X') continue;
mv[r][c][1] = lst;
lst = r;
}
}
FOR(r, 0, n) {
// left
int lst = -1;
FOR(c, 0, m) {
if (MAT[r][c] == 'X') continue;
mv[r][c][2] = lst;
lst = c;
}
// right
lst = -1;
ROF(c, m - 1, -1) {
if (MAT[r][c] == 'X') continue;
mv[r][c][3] = lst;
lst = c;
}
}
int start_r, start_c;
int end_r, end_c;
FOR(r, 0, n) {
FOR(c, 0, m) {
if ( MAT[r][c] == 'S' ) {
start_r = r;
start_c = c;
}
if ( MAT[r][c] == 'E' ) {
end_r = r;
end_c = c;
}
}
}
int ans = f(start_r, start_c);
printf("%d\n", ans);
if (ans != -1) {
string s;
while (end_r != start_r || end_c != start_c) {
s.pb(to[end_r][end_c]);
if (to[end_r][end_c] == 'U') {
end_r = mv[end_r][end_c][1];
}
else if (to[end_r][end_c] == 'D') {
end_r = mv[end_r][end_c][0];
}
else if (to[end_r][end_c] == 'L') {
end_c = mv[end_r][end_c][3];
}
else if (to[end_r][end_c] == 'R') {
end_c = mv[end_r][end_c][2];
}
}
reverse(s.begin(), s.end());
cout << s << "\n";
}
return 0;
} |
1c621e27ee2bcf6cf83c29dc07591b92dbb005df | 8a8744104d9d2b50d350239dbc8a9f09a8ecc03a | /Code/CPlusPlus/Engine/Subsystems/Renderer/Font/Font.h | b934a74b7e5374704927282abd9656b8347217a8 | [] | no_license | JonnyRivers/rorn | fadd039b13fd95de5033d25e4552c456ab2eaa13 | ea3dab1d42838917c29d81f7ff92c11fc312a62e | refs/heads/master | 2016-08-12T19:55:18.729619 | 2014-09-11T21:20:30 | 2014-09-11T21:20:30 | 52,677,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 429 | h | Font.h | #pragma once
#include <map>
#include "Glyph.h"
namespace Rorn
{
namespace Engine
{
class Font
{
public:
Font(const std::map<unsigned int, Glyph>& glyphMap, unsigned int textureId);
~Font();
const Glyph& GetGlyph(unsigned int characterCode) const;
private:
Font(Font&);
Font& operator=(Font&);
std::map<unsigned int, Glyph> glyphMap_;
unsigned int textureId_;
};
}
} |
04886d3335975bf869a4beb7f5f0643349247fa8 | b3abc64d675731cd8b0b04d655b1713f585599fa | /Ejercicios/EjerciciosRelacion2/Ejercicio51.cpp | 9bd0fef1bcad5439d621ca3dbf0bb4022780add7 | [
"Apache-2.0"
] | permissive | JArandaIzquierdo/FundamentosDeProgramacion | a3808836ab29629662a272b46b16ec2117d8cbd1 | c7c8e79c880de511c3667796356ffa265b021eb2 | refs/heads/master | 2021-05-04T10:03:42.807157 | 2017-11-30T23:47:15 | 2017-11-30T23:47:15 | 43,295,671 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 368 | cpp | Ejercicio51.cpp | #include <iostream>
#include <cmath>
using namespace std;
int main(){
int funcion, x=-50, y=40;
for(int i=x; i<=50; i++){
for(int j=y; j >= -40; j--){
funcion = sqrt(i) / (pow(j,2)-1);
cout<<"El valor de la funcion para los varos de x="<<i<<" e y="<< j << " es: "<< funcion << endl;
}
}
}
|
cc075e48817d80bad820300a74ad1fd64b3d6337 | efce435f8c86079c596ef2d2f6a842bd4659451e | /libJMPX/libJMPX.cpp | c73fb4d0f6ba7ff28edc534548dc350bc06ca26b | [
"MIT"
] | permissive | KD9QZO/JMPX | 6ab5e39736246a1be05aecfcfc03ab1720976271 | ee67dad079812e074a79741a2e5831b28bc7ebb3 | refs/heads/master | 2023-05-28T16:00:52.828290 | 2020-01-04T21:38:55 | 2020-01-04T21:38:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,298 | cpp | libJMPX.cpp | #include "libJMPX.h"
#include <QDebug>
#include <QtEndian>
#include <unistd.h>
#include <random>
#include <QTimer>
static __inline__ unsigned long long rdtsc(void)
{
unsigned hi, lo;
__asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32 );
}
//these run the dispatchers
void Usual_Runnable::run()
{
inst->SoundcardInOut_dispatcher();
}
void SCA_Runnable::run()
{
inst->SCA_dispatcher();
}
JMPXEncoder::JMPXEncoder(QObject *parent):
JMPXInterface(parent),
pTDspGen( new TDspGen(&ASetGen)),
pWaveTable( new WaveTable(pTDspGen.get(),19000)),
pFMModulator( new FMModulator(pTDspGen.get()))
{
_GotError=false;
stereo=true;
RDS_enabled=true;
SCA_enabled=true;
dsca_enable_send_rds=true;
decl=0;
scabigval=0.0;
lbigval=0.0;
rbigval=0.0;
outbigval=0.0;
sigstats.scavol=0.0;
sigstats.lvol=0.0;
sigstats.rvol=0.0;
sigstats.outvol=0.0;
sigstats.opusbufferuseagepercent=0.0;
//reserve 2 threads for the SCA and the other one for the usual one
tp=new QThreadPool(this);
tp->setMaxThreadCount(2);
pOQPSKModulator = new OQPSKModulator(pTDspGen.get(),this);
pJCSound = new TJCSound(this);
pJCSound->iParameters.nChannels=2;
pJCSound->oParameters.nChannels=2;
pJCSound->sampleRate=192000;//default setting
pJCSound->bufferFrames=8096;
pJCSound->options.streamName="JMPX";
rds = new RDS(this);
//SCA setup
pJCSound_SCA = new TJCSound(this);
pJCSound_SCA->iParameters.nChannels=2;//stero input
pJCSound_SCA->oParameters.nChannels=0;//no output channels
pJCSound_SCA->bufferFrames=8096;
pJCSound_SCA->options.streamName="JMPX_SCA";
pJCSound_SCA->sampleRate=48000;//default setting
SCA_MaxDeviation=3000;//3khz
SCA_Level=0.1;//10%
SCA_CarrierFrequency=67500;//67.5khz
SCA_MaxInputFrequency=5000;//5khz
//
compositeclipper=true;
monolevel=0.9;
level38k=1.0;
pilotlevel=0.07;
rdslevel=0.06;
scaPeak.setSettings(40,0.01,0.8,0.0001,100,false);
lPeak.setSettings(40,0.01,0.8,0.0001,100,false);
rPeak.setSettings(40,0.01,0.8,0.0001,100,false);
outPeak.setSettings(160,0.01/4.0,0.95,0.0001/4.0,100,false);
opusBufferUsagePeak.setSettings(160,0.001,0.99,0.0001/10.0,40000,true);
rdsbpf = new JFastFIRFilter;
rdsbpf->setKernel(JFilterDesign::BandPassHanning(57000-2400,57000+2400,pJCSound->sampleRate,512-1));
//oqpsk modulator for opus
connect(pOQPSKModulator,SIGNAL(CallForMoreData(int)),this,SLOT(onCallForMoreData(int)));
//data formatter for modulator
oqpskdataformatter.setMode(DataFormatter::mode1);
//opus setup
int err;
encoder = opus_encoder_create(SAMPLE_RATE, CHANNELS, OPUS_APPLICATION_VOIP,&err);//APPLICATION, &err);
if (err<0)qDebug()<<"failed to create opus encoder: "<<opus_strerror(err);
int application;
opus_encoder_ctl(encoder, OPUS_GET_APPLICATION(&application));
//qDebug()<<"start application= "<<application;
err = opus_encoder_ctl(encoder, OPUS_SET_BITRATE(BITRATE));
if (err<0)qDebug()<<"failed to set bitrate: "<<opus_strerror(err);
SCA_opus=true;
//periodic rds info sending
QTimer *timer=new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(DSCAsendRds()));
timer->start(4000);
}
JMPXEncoder::~JMPXEncoder()
{
//stop the sound card
pJCSound->GotError=false;
pJCSound->Active(false);
pJCSound->GotError=false;
pJCSound_SCA->GotError=false;
pJCSound->Active(false);
pJCSound_SCA->GotError=false;
//stop SoundcardInOut threads, SCA thread and reset channel
StopTheThreadPool();
delete rdsbpf;
opus_encoder_destroy(encoder);
}
void JMPXEncoder::onCallForMoreData(int maxbitswanted)
{
Q_UNUSED(maxbitswanted);
callback_mutex.lock();
pOQPSKModulator->LoadBits(oqpskdataformatter.getFrame());
callback_mutex.unlock();
}
void JMPXEncoder::DSCAsendRds()
{
if(!dsca_enable_send_rds)return;
if(!pOQPSKModulator->isSpooling())return;
QByteArray ba;
ba.push_back(rds->get_ps().size());
ba+=rds->get_ps().toLatin1();
ba.push_back(rds->get_rt().size());
ba+=rds->get_rt().toLatin1();
oqpskdataformatter.pushPacket(DataFormatter::PacketType_RDS,ba);
}
void JMPXEncoder::Active(bool Enabled)
{
_GotError=false;
if(Enabled==pJCSound->IsActive())return;
//disconnect signals/slots
disconnect(pJCSound,SIGNAL(SoundEvent(double*,double*,int)),this,SLOT(SoundcardInOut_Callback(double*,double*,int)));
disconnect(pJCSound_SCA,SIGNAL(SoundEvent(qint16*,qint16*,int)),this,SLOT(SCA_Callback(qint16*,qint16*,int)));
//stop the sound cards
pJCSound->GotError=false;
pJCSound->Active(false);
pJCSound->GotError=false;
pJCSound_SCA->GotError=false;
pJCSound->Active(false);
pJCSound_SCA->GotError=false;
//stop SoundcardInOut threads, SCA thread and reset channel
StopTheThreadPool();
if(Enabled)
{
//here we dont need lock as other threads should be stoped
//we should already have 2 threads set aside for us in the tp thread pool
qDebug()<<"threads in pool == "<<tp->maxThreadCount();
StartTheThreadPool();
ASetGen.SampleRate=pJCSound->sampleRate;
pTDspGen->ResetSettings();
pWaveTable->RefreshSettings(19000.0);
pOQPSKModulator->RefreshSettings();//incase samplerate has changed
pFMModulator->RefreshSettings();//incase samplerate has changed
rds->reset();
rt_dynamic.clear();
rds->set_rt(rt_default);
//4.8khz rds bpf
rdsbpf->setKernel(JFilterDesign::BandPassHanning(57000-2400,57000+2400,pJCSound->sampleRate,512-1));
//clear OQPSK buffer
oqpskdataformatter.clearBuffer();
//SCA uses 16 bit int
pJCSound_SCA->audioformat=RTAUDIO_SINT16;
connect(pJCSound_SCA,SIGNAL(SoundEvent(qint16*,qint16*,int)),this,SLOT(SCA_Callback(qint16*,qint16*,int)),Qt::DirectConnection);//DirectConnection!!!
//Usual sound card uses double
connect(pJCSound,SIGNAL(SoundEvent(double*,double*,int)),this,SLOT(SoundcardInOut_Callback(double*,double*,int)),Qt::DirectConnection);//DirectConnection!!!
//stop SCA working untill we know how big this buffer should be
SCA_buffer.clear();
//this is what we would like but there is no garentee this is what we will get once the soundcard has started
SCA_ratechange=0;
SCA_rate=((double)pJCSound->sampleRate)/48000.0;//SCA rate must be 48k as thats the fastest that opus can handle //
pJCSound_SCA->bufferFrames=1.0*((double)pJCSound->bufferFrames)/((((double)pJCSound->sampleRate)/((double)pJCSound_SCA->sampleRate)));// 1.0 --> same 0.5 --> twice as often, etc
}
try
{
pJCSound->Active(Enabled);
if(pJCSound->GotError)throw 1;
pJCSound_SCA->Active(SCA_enabled&&Enabled);
if(pJCSound_SCA->GotError)throw 2;
}
catch(int e)
{
_GotError=true;
switch(e)
{
case 1:
LastErrorMessage=pJCSound->LastErrorMessage;
break;
case 2:
LastErrorMessage="SCA input : "+pJCSound_SCA->LastErrorMessage;
break;
default:
LastErrorMessage="unknowen";
}
pJCSound->GotError=false;
pJCSound->Active(false);
pJCSound->GotError=false;
pJCSound_SCA->GotError=false;
pJCSound->Active(false);
pJCSound_SCA->GotError=false;
}
scaPeak.zero();
lPeak.zero();
rPeak.zero();
outPeak.zero();
opusBufferUsagePeak.zero();
if(SCA_opus&&pJCSound_SCA->IsActive())pOQPSKModulator->StartSpooling();
else pOQPSKModulator->StopSpooling();
}
void JMPXEncoder::SetEnableStereo(bool enable)
{
stereo=enable;
}
bool JMPXEncoder::GetEnableStereo()
{
return stereo;
}
void JMPXEncoder::SetEnableRDS(bool enable)
{
RDS_enabled=enable;
}
bool JMPXEncoder::GetEnableRDS()
{
return RDS_enabled;
}
TSigStats* JMPXEncoder::GetSignalStats()
{
return &sigstats;
}
TimeConstant JMPXEncoder::GetPreEmphasis()
{
return (TimeConstant)lpreemp.GetTc();
}
void JMPXEncoder::SetPreEmphasis(TimeConstant timeconst)
{
lpreemp.SetTc(timeconst);
rpreemp.SetTc(timeconst);
pFMModulator->SetTc(timeconst);
}
//starts the 2 threads
void JMPXEncoder::StartTheThreadPool()
{
//start SoundcardInOut_dispatcher thread and wait till it has started
do_SoundcardInOut_dispatcher_cancel=true;
Usual_Runnable *usual_runnable = new Usual_Runnable();
usual_runnable->setAutoDelete(true);
usual_runnable->inst=this;
tp->start(usual_runnable,QThread::TimeCriticalPriority);
while(do_SoundcardInOut_dispatcher_cancel)usleep(10000);
//start SCA_dispatcher thread and wait till it has started
do_SCA_dispatcher_cancel=true;
SCA_Runnable *sca_runnable = new SCA_Runnable();
sca_runnable->setAutoDelete(true);
sca_runnable->inst=this;
tp->start(sca_runnable,QThread::TimeCriticalPriority);
while(do_SCA_dispatcher_cancel)usleep(10000);
}
//stops the 2 threads
void JMPXEncoder::StopTheThreadPool()
{
buffers_mut.lock();
do_SoundcardInOut_dispatcher_cancel=true;
buffers_process.wakeAll();
buffers_mut.unlock();
buffers_mut_sca.lock();
do_SCA_dispatcher_cancel=true;
buffers_process_sca.wakeAll();
buffers_mut_sca.unlock();
tp->waitForDone();
buffers_head_ptr_in=0;
buffers_tail_ptr_in=0;
buffers_used_in=0;
buffers_head_ptr_out=0;
buffers_tail_ptr_out=0;
buffers_used_out=0;
spooling=false;
for(int i=0;i<N_BUFFERS;i++)
{
buffers_in[i].assign(buffers_in[i].size(),0.0);
buffers_out[i].assign(buffers_in[i].size(),0.0);
}
buffers_head_ptr_in_sca=0;
buffers_tail_ptr_in_sca=0;
buffers_used_in_sca=0;
buffers_used_out_sca=0;
spooling_sca=false;
for(int i=0;i<N_BUFFERS;i++)
{
buffers_in_sca[i].assign(buffers_in_sca[i].size(),0);
}
}
//thread 1 (192k sound in/out processing thread)
void JMPXEncoder::SoundcardInOut_dispatcher()
{
do_SoundcardInOut_dispatcher_cancel=false;
qDebug()<<"SoundcardInOut_dispatcher started";
while(true)
{
//if we have no data to process then wait
buffers_mut.lock();
if(buffers_used_in<1)
{
buffers_process.wait(&buffers_mut);
}
buffers_mut.unlock();
//check if reason for waking is to cancel
if(do_SoundcardInOut_dispatcher_cancel)break;
//cycle buffers
buffers_tail_ptr_in%=N_BUFFERS;
buffers_head_ptr_out%=N_BUFFERS;
//get size
int units=buffers_in[buffers_tail_ptr_in].size();
int nFrames=units/2;
//make sure buffers are of the right size
buffers_in[buffers_tail_ptr_in].resize(units,0);
buffers_out[buffers_head_ptr_out].resize(units,0);
//create buffer ptr
double *DataIn=buffers_in[buffers_tail_ptr_in].data();
double *DataOut=buffers_out[buffers_head_ptr_out].data();
Update(DataIn,DataOut,nFrames);
//goto next buffer
++buffers_tail_ptr_in;
++buffers_head_ptr_out;
buffers_mut.lock();
--buffers_used_in;
++buffers_used_out;
buffers_mut.unlock();
}
qDebug()<<"SoundcardInOut_dispatcher finished";
}
//thread 2 (192k sound in/out transfer thread)
void JMPXEncoder::SoundcardInOut_Callback(double *DataIn,double *DataOut, int nFrames)
{
//return if in a cancelling state
if(do_SoundcardInOut_dispatcher_cancel)return;
//if there is no room to store the incoming data then ????
buffers_mut.lock();
if(buffers_used_in>=N_BUFFERS)
{
//??? maybe just panic and return and hope at a later time we will have some room
buffers_mut.unlock();
qDebug()<<"SoundcardOut_Callback overrun";
return;
}
buffers_mut.unlock();
//size of this buffer and every other buffer. this needs to be the same
int units=2*nFrames;
//if there is no data for us to return then ????
buffers_mut.lock();
if(buffers_used_out<1)
{
//??? either we are spooling up or we have an underrun
//??? set the spooling flag to tell this fuction to return garbarge
qDebug()<<"SoundcardOut_Callback underrun";
spooling=true;
}
if(spooling&&(buffers_used_out+buffers_used_in)>=N_BUFFERS)spooling=false;
buffers_mut.unlock();
// if(spooling)qDebug()<<"spooling usual";
//cycle buffers
buffers_head_ptr_in%=N_BUFFERS;
buffers_tail_ptr_out%=N_BUFFERS;
//make sure buffers are of the right size
buffers_in[buffers_head_ptr_in].resize(units,0);
buffers_out[buffers_tail_ptr_out].resize(units,0);
double *buffptr_in=buffers_in[buffers_head_ptr_in].data();
double *buffptr_out=buffers_out[buffers_tail_ptr_out].data();
//compy memory
memcpy(buffptr_in,DataIn, sizeof(double)*units);
memcpy(DataOut,buffptr_out, sizeof(double)*units);
//goto next buffer
++buffers_head_ptr_in;
if(!spooling)++buffers_tail_ptr_out;
//tell dispatcher thread to process this and any other callback blocks
buffers_mut.lock();
++buffers_used_in;
if(!spooling)--buffers_used_out;
// if((!spooling)&&(buffers_used_out<(N_BUFFERS-1)))qDebug()<<"dual sound card thread caught a buffer. buffers_used_in=="<<buffers_used_in<<"buffers_used_out=="<<buffers_used_out<<" N_BUFFERS="<<N_BUFFERS;
buffers_process.wakeAll();
buffers_mut.unlock();
}
//thread 3 (SCA audio in processing thread)
void JMPXEncoder::SCA_dispatcher()
{
do_SCA_dispatcher_cancel=false;
qDebug()<<"SCA_dispatcher started";
while(true)
{
//if we have no data to process then wait
buffers_mut_sca.lock();
if(buffers_used_in_sca<1)
{
buffers_process_sca.wait(&buffers_mut_sca);
}
buffers_mut_sca.unlock();
//check if reason for waking is to cancel
if(do_SCA_dispatcher_cancel)break;
//cycle buffers
buffers_tail_ptr_in_sca%=N_BUFFERS;
//get size
int units=buffers_in_sca[buffers_tail_ptr_in_sca].size();
int nFrames=units/2;
//make sure buffers are of the right size
buffers_in_sca[buffers_tail_ptr_in_sca].resize(units,0);
//create buffer ptr
qint16 *DataIn=buffers_in_sca[buffers_tail_ptr_in_sca].data();
qint16 *DataOut=NULL;//nothing comes back
if(SCA_opus)Update_opusSCA(DataIn,DataOut,nFrames);
else Update_SCA(DataIn,DataOut,nFrames);
//goto next buffer
++buffers_tail_ptr_in_sca;
buffers_mut_sca.lock();
--buffers_used_in_sca;
++buffers_used_out_sca;
buffers_mut_sca.unlock();
}
qDebug()<<"SCA_dispatcher finished";
}
//thread 4 (SCA audio in transfer thread)
void JMPXEncoder::SCA_Callback(qint16 *DataIn,qint16 *DataOut, int nFrames)
{
Q_UNUSED(DataOut);
//return if in a cancelling state
if(do_SCA_dispatcher_cancel)return;
//if there is no room to store the incoming data then ????
buffers_mut_sca.lock();
if(buffers_used_in_sca>=N_BUFFERS)
{
//??? maybe just panic and return and hope at a later time we will have some room
buffers_mut_sca.unlock();
qDebug()<<"SCA_Callback overrun";
return;
}
buffers_mut_sca.unlock();
//size of this buffer and every other buffer. this needs to be the same
int units=2*nFrames;
//if there is no data for us to return then ????
buffers_mut_sca.lock();
if(buffers_used_out_sca<1)
{
//??? either we are spooling up or we have an underrun
//??? set the spooling flag to tell this fuction to return garbarge
qDebug()<<"SCA_Callback underrun";
spooling_sca=true;
}
if(spooling_sca&&(buffers_used_out_sca+buffers_used_in_sca)>=N_BUFFERS)spooling_sca=false;
buffers_mut_sca.unlock();
// if(spooling_sca)qDebug()<<"spooling_sca";
//cycle buffers
buffers_head_ptr_in_sca%=N_BUFFERS;
//make sure buffers are of the right size
buffers_in_sca[buffers_head_ptr_in_sca].resize(units,0);
qint16 *buffptr_in=buffers_in_sca[buffers_head_ptr_in_sca].data();
//compy memory
memcpy(buffptr_in,DataIn, sizeof(qint16)*units);
//goto next buffer
++buffers_head_ptr_in_sca;
//tell dispatcher thread to process this and any other callback blocks
buffers_mut_sca.lock();
++buffers_used_in_sca;
if(!spooling_sca)--buffers_used_out_sca;
// if((!spooling_sca)&&(buffers_used_out_sca<(N_BUFFERS-1)))qDebug()<<"dual SCA sound card thread caught a buffer. buffers_used_in=="<<buffers_used_in_sca<<"buffers_used_out=="<<buffers_used_out_sca<<" N_BUFFERS="<<N_BUFFERS;
buffers_process_sca.wakeAll();
buffers_mut_sca.unlock();
}
//part of thread 1 (called by dispatcher)
void JMPXEncoder::Update(double *DataIn,double *DataOut, int nFrames)
{
callback_mutex.lock();
//calculate SCA buffer usage
if(!SCA_buffer.isEmpty())
{
SCA_buffer_use_percentage=((double)(SCA_buf_ptr_head-SCA_buf_ptr_tail))/((double)SCA_buffer.size());
if(SCA_buffer_use_percentage<0)SCA_buffer_use_percentage=1.0+SCA_buffer_use_percentage;
}
else SCA_buffer_use_percentage=0;
double rval;
double lval;
double sca_val=0;
double rival;
double lival;
double oval;
//rds generation
rds->FIRFilterImpulses(nFrames);// number of frames
//low pass filter. about 16.5Khz is standard
//fast fir
stereofir.Update(DataIn,nFrames);
if(!stereo)
{
for(int i=0;i<nFrames*2;i+=2)
{
pWaveTable->WTnextFrame();
lval=DataIn[i];
rval=DataIn[i+1];
lval=lpreemp.Update(lval*0.5);
rval=rpreemp.Update(rval*0.5);
lival=lval*2.0;
rival=rval*2.0;
lval=clipper.Update(lval);
rval=clipper.Update(rval);
DataOut[i]=monolevel*0.608*(lval+rval);//sum at 0Hz
if(RDS_enabled)DataOut[i]+=rdslevel*rdsbpf->Update_Single(pWaveTable->WTSin3Value()*rds->outputsignal[i/2]);//RDS at 57kHz
//SCA start
if((SCA_enabled)&&(!SCA_buffer.isEmpty()))
{
if(!SCA_opus)
{
//SCA input
//upsample from 48000 or 96000 to 192000
sca_val=0;
SCA_ratechange+=1.0;
if(SCA_ratechange>=SCA_rate)
{
SCA_ratechange-=SCA_rate;
SCA_ratechange+=0.1*(SCA_buffer_use_percentage-0.5);//adjust phase of sampleing so as to keep asynchronous sound cards synchronised
//check for under run
if(SCA_buf_ptr_head==SCA_buf_ptr_tail)
{
qDebug()<<"SCA input UnderRun";
//this should only happen when the buffer is spooling up
//set tail to be as far away as posible from the head
SCA_buffer.fill(0);
SCA_buf_ptr_tail=SCA_buf_ptr_head+SCA_buffer.size()/2;
SCA_buf_ptr_tail%=SCA_buffer.size();
}
//take sample (left and right have been summed in slow callback)
sca_val=SCA_buffer[SCA_buf_ptr_tail];
SCA_buf_ptr_tail++;SCA_buf_ptr_tail%=SCA_buffer.size();
}
//Modulate SCA signal
DataOut[i]+=SCA_Level*pFMModulator->update(sca_val);
} else DataOut[i]+=SCA_Level*pOQPSKModulator->update();
}
//SCA end
#ifdef DEV_TAB
// add white noise hack
if(noiselevel>0)
{
const double mean = 0.0;
const double stddev = noiselevel;
std::normal_distribution<double> dist(mean, stddev);
DataOut[i]+=dist(generator);
}
#endif
oval=DataOut[i];
if(compositeclipper)DataOut[i]=clipper.Update(DataOut[i]);
if(fabs(sca_val)>scabigval)scabigval=fabs(sca_val);
if(fabs(DataIn[i])>lbigval)lbigval=fabs(lival);
if(fabs(DataIn[i+1])>rbigval)rbigval=fabs(rival);
if(fabs(DataOut[i])>outbigval)outbigval=fabs(oval);
decl++;
if(!(decl%=1250))//about 154 times a second
{
if(!SCA_opus)opusBufferUsagePeak.zero();
sigstats.outvol=outPeak.update(outbigval);
sigstats.scavol=scaPeak.update(scabigval);
sigstats.lvol=lPeak.update(lbigval);
sigstats.rvol=rPeak.update(rbigval);
sigstats.opusbufferuseagepercent=opusBufferUsagePeak.update(oqpskdataformatter.getBufferUsagePercentage());
decl=0;
scabigval=0.0;
lbigval=0.0;
rbigval=0.0;
outbigval=0.0;
}
DataOut[i+1]=DataOut[i];
}
callback_mutex.unlock();
return;
}
for(int i=0;i<nFrames*2;i+=2)
{
pWaveTable->WTnextFrame();
lval=DataIn[i];
rval=DataIn[i+1];
lval=lpreemp.Update(lval*0.5);
rval=rpreemp.Update(rval*0.5);
lival=lval*2.0;
rival=rval*2.0;
lval=clipper.Update(lval);
rval=clipper.Update(rval);
DataOut[i]=monolevel*0.608*(lval+rval);//sum at 0Hz
DataOut[i]+=level38k*0.608*(pWaveTable->WTSin2Value())*(lval-rval);//diff at 38kHz
DataOut[i]+=pilotlevel*pWaveTable->WTSinValue();//19kHz pilot
if(RDS_enabled)DataOut[i]+=rdslevel*rdsbpf->Update_Single(pWaveTable->WTSin3Value()*rds->outputsignal[i/2]);//RDS at 57kHz
//SCA start
if((SCA_enabled)&&(!SCA_buffer.isEmpty()))
{
if(!SCA_opus)
{
//SCA input
//upsample from 48000 to 192000
sca_val=0;
SCA_ratechange+=1.0;
if(SCA_ratechange>=SCA_rate)
{
SCA_ratechange-=SCA_rate;
SCA_ratechange+=0.1*(SCA_buffer_use_percentage-0.5);//adjust phase of sampleing so as to keep asynchronous sound cards synchronised
//check for under run
if(SCA_buf_ptr_head==SCA_buf_ptr_tail)
{
qDebug()<<"SCA input UnderRun";
//this should only happen when the buffer is spooling up
//set tail to be as far away as posible from the head
SCA_buffer.fill(0);
SCA_buf_ptr_tail=SCA_buf_ptr_head+SCA_buffer.size()/2;
SCA_buf_ptr_tail%=SCA_buffer.size();
}
//take sample (left and right have been summed in slow callback)
sca_val=SCA_buffer[SCA_buf_ptr_tail];
SCA_buf_ptr_tail++;SCA_buf_ptr_tail%=SCA_buffer.size();
}
//Modulate SCA signal
DataOut[i]+=SCA_Level*pFMModulator->update(sca_val);
} else DataOut[i]+=SCA_Level*pOQPSKModulator->update();
}
//SCA end
#ifdef DEV_TAB
// add white noise hack
if(noiselevel>0)
{
const double mean = 0.0;
const double stddev = noiselevel;
std::normal_distribution<double> dist(mean, stddev);
DataOut[i]+=dist(generator);
}
#endif
double oval=DataOut[i];
if(compositeclipper)DataOut[i]=clipper.Update(DataOut[i]);
if(fabs(sca_val)>scabigval)scabigval=fabs(sca_val);
if(fabs(DataIn[i])>lbigval)lbigval=fabs(lival);
if(fabs(DataIn[i+1])>rbigval)rbigval=fabs(rival);
if(fabs(DataOut[i])>outbigval)outbigval=fabs(oval);
decl++;
if(!(decl%=1250))//about 154 times a second
{
if(!SCA_opus)opusBufferUsagePeak.zero();
sigstats.outvol=outPeak.update(outbigval);
sigstats.scavol=scaPeak.update(scabigval);
sigstats.lvol=lPeak.update(lbigval);
sigstats.rvol=rPeak.update(rbigval);
sigstats.opusbufferuseagepercent=opusBufferUsagePeak.update(oqpskdataformatter.getBufferUsagePercentage());
decl=0;
scabigval=0.0;
lbigval=0.0;
rbigval=0.0;
outbigval=0.0;
}
DataOut[i+1]=DataOut[i];
}
callback_mutex.unlock();
}
//part of thread 3 (called by dispatcher)
void JMPXEncoder::Update_opusSCA(qint16 *DataIn, qint16 *DataOut, int nFrames)
{
Q_UNUSED(DataOut);
callback_mutex.lock();
//this is not used by us directly but in case the user switches back to SCA. also SCA_buffer.size() can't be zero for us to work
if(SCA_buffer.isEmpty())
{
//setup shared cycle buffer for enough space for 4 calls from the fast callback
//SCA_buffer is a mono signal buffer
SCA_buffer.fill(0,4*qMax((int)pJCSound_SCA->bufferFrames,1024));
SCA_buf_ptr_head=0;
SCA_buf_ptr_tail=SCA_buffer.size()/2;
SCA_buffer_use_percentage=0.5;
SCA_ratechange=0;
SCA_rate=((double)pJCSound->sampleRate)/48000.0;//SCA rate must be 48k as thats the fastest that opus can handle //
//
}
double sca_val=0;
//CHANNELS must be 2
//down sampling to 48000 if needed. we should have a LPF if this is done but who is likly to be sending frequencies above 24kHz
//todo add fir LPF
int stepper=1;
if(pJCSound_SCA->sampleRate==96000){stepper=2;if(nFrames%2)qDebug()<<"cant devide SCA buffer size by 2!!";}
if(pJCSound_SCA->sampleRate==192000){stepper=4;if(nFrames%4)qDebug()<<"cant devide SCA buffer size by 4!!";}
static int in_ptr=0;
for(int i=0;i<nFrames*CHANNELS;i+=(2*stepper))
{
sca_val=((double)DataIn[i])/32767.0;
if(fabs(sca_val)>scabigval)scabigval=fabs(sca_val);
sca_val=((double)DataIn[i+1])/32767.0;
if(fabs(sca_val)>scabigval)scabigval=fabs(sca_val);
if(in_ptr%2!=i%2)//just incase something goes wrong with L/R sync
{
qDebug()<<"LR stuffup"<<in_ptr<<i;
in_ptr++;
in_ptr%=FRAME_SIZE*CHANNELS;
}
in[in_ptr]=DataIn[i];
in[in_ptr+1]=DataIn[i+1];
in_ptr+=2;in_ptr%=FRAME_SIZE*CHANNELS;
if(!in_ptr)
{
nbBytes = opus_encode(encoder, in, FRAME_SIZE, cbits, MAX_PACKET_SIZE);
if(!oqpskdataformatter.pushPacket(DataFormatter::PacketType_OPUS,cbits,nbBytes))
{
qDebug()<<"packet buffer overflow";
}
}
}
callback_mutex.unlock();
}
//part of thread 3 (called by dispatcher)
void JMPXEncoder::Update_SCA(qint16 *DataIn, qint16 *DataOut, int nFrames)
{
Q_UNUSED(DataOut);
callback_mutex.lock();
if(SCA_buffer.isEmpty())
{
//setup shared cycle buffer for enough space for 4 calls from the fast callback
//SCA_buffer is a mono signal buffer
SCA_buffer.fill(0,4*qMax((int)pJCSound_SCA->bufferFrames,1024));
SCA_buf_ptr_head=0;
SCA_buf_ptr_tail=SCA_buffer.size()/2;
SCA_buffer_use_percentage=0.5;
SCA_ratechange=0;
SCA_rate=((double)pJCSound->sampleRate)/48000.0;//SCA rate must be 48k as thats the fastest that opus can handle //
//
}
//down sampling to 48000 if needed. we should have a LPF if this is done but who is likly to be sending frequencies above 24kHz
//todo add fir LPF
int stepper=1;
if(pJCSound_SCA->sampleRate==96000){stepper=2;if(nFrames%2)qDebug()<<"cant devide SCA buffer size by 2!!";}
if(pJCSound_SCA->sampleRate==192000){stepper=4;if(nFrames%4)qDebug()<<"cant devide SCA buffer size by 4!!";}
for(int i=0;i<nFrames*2;i+=(2*stepper))
{
SCA_buffer[SCA_buf_ptr_head]=(((double)DataIn[i])/32767.0+((double)DataIn[i+1])/32767.0)*SCA_rate;//sum left and right channels
SCA_buf_ptr_head++;if(SCA_buf_ptr_head>=SCA_buffer.size())SCA_buf_ptr_head=0;
if(SCA_buf_ptr_head==SCA_buf_ptr_tail)
{
qDebug()<<"SCA input Overflow";
//this should only happen when the buffer is spooling up
//set tail to be as far away as posible from the head
SCA_buffer.fill(0);
SCA_buf_ptr_tail=SCA_buf_ptr_head+SCA_buffer.size()/2;
SCA_buf_ptr_tail%=SCA_buffer.size();
}
}
callback_mutex.unlock();
}
//class factory
JMPXInterface* createObject(QObject *parent)
{
return new JMPXEncoder(parent);
}
|
2637d42f1b7763a7c8446d79a6898934bdbae346 | cc474c0fa39ca8b77b6b5cbce50445cac5506265 | /FlipFluid/Sorter.cpp | 7fb95bd19ce874f8bb4e291af5576baeec5386b4 | [] | no_license | duoshengyu/FLIP_FLUID | d6f329d085f6ed23c6810d244eb3f94af036aeca | 791e64736b731d99ed164a295a3a25fc6e194947 | refs/heads/master | 2021-01-10T12:23:09.471298 | 2016-04-05T03:21:01 | 2016-04-05T03:21:01 | 50,499,381 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,188 | cpp | Sorter.cpp | //------------------------------------------------------------------------------
//reference to https://code.google.com/archive/p/flip3d/ ando`s filp code.
//I just use this for surface reconstruction.
//------------------------------------------------------------------------------
#include "Sorter.h"
sorter::sorter(int _gnx, int _gny, int _gnz) {
gnx = _gnx;
gny = _gny;
gnz = _gnz;
cells = memAlloc3D<vector<Particle *> >(gnx, gny, gnz);
}
sorter::~sorter() {
}
void sorter::sort(std::vector<Particle> &_Particles) {
// Clear All Cells
FOR_EACH_CELL(gnx, gny, gnz)
{
cells[i][j][k].clear();
}
// Store Into The Cells
for (int n = 0; n<_Particles.size(); n++)
{
Particle *p = &(_Particles[n]);
double pos[3];
pos[0] = p->_p.X;
pos[1] = p->_p.Y;
pos[2] = p->_p.Z;
int i = fmax(0, fmin(gnx - 1, gnx*pos[0]));
int j = fmax(0, fmin(gny - 1, gny*pos[1]));
int k = fmax(0, fmin(gnz - 1, gnz*pos[2]));
cells[i][j][k].push_back(p);
}
#if 0
FOR_EACH_CELL(gnx, gny, gnz)
{
for (int l = 0; l < cells[i][j][k].size(); l++)
{
debug << i << " " << j << " " << k << " " << cells[i][j][k][l] << endl;
}
}
debug << endl;
#endif
}
std::vector<Particle *> sorter::getNeigboringParticles_wall(int i, int j, int k, int w, int h, int d) {
std::vector<Particle *> res;
for (int si = i - w; si <= i + w - 1; si++) for (int sj = j - h; sj <= j + h - 1; sj++) for (int sk = k - d; sk <= k + d - 1; sk++) {
if (si < 0 || si > gnx - 1 || sj < 0 || sj > gny - 1 || sk < 0 || sk > gnz - 1) continue;
for (int a = 0; a<cells[si][sj][sk].size(); a++) {
Particle *p = cells[si][sj][sk][a];
res.push_back(p);
}
}
return res;
}
std::vector<Particle *> sorter::getNeigboringParticles_cell(int i, int j, int k, int w, int h, int d) {
std::vector<Particle *> res;
for (int si = i - w; si <= i + w; si++) for (int sj = j - h; sj <= j + h; sj++) for (int sk = k - d; sk <= k + d; sk++) {
if (si < 0 || si > gnx - 1 || sj < 0 || sj > gny - 1 || sk < 0 || sk > gnz - 1) continue;
for (int a = 0; a<cells[si][sj][sk].size(); a++) {
Particle *p = cells[si][sj][sk][a];
res.push_back(p);
}
}
#if 0
debug << i << " " << j << " " << k << " " << res.size() << endl;
#endif
return res;
}
int sorter::getNumParticleAt(int i, int j, int k) {
return cells[i][j][k].size();
}
double sorter::levelset(int i, int j, int k, double ***halfwall, double density) {
double accm = 0.0;
for (int a = 0; a<cells[i][j][k].size(); a++)
{
//if (cells[i][j][k][a]->type == FLUID) {
accm += cells[i][j][k][a]->density;
//else {
//return 1.0;
//}
}
double n0 = 1.0 / (density*density*density);
return 0.2*n0 - accm;
}
void sorter::markWater(char ***A, double ***halfwall, double density) {
FOR_EACH_CELL(gnx, gny, gnz)
{
A[i][j][k] = AIR;
//for (int a = 0; a<cells[i][j][k].size(); a++) {
// if (cells[i][j][k][a]->type == WALL) {
// A[i][j][k] = WALL;
// }
//}
if (A[i][j][k] != SOLID) A[i][j][k] = levelset(i, j, k, halfwall, density) < 0.0 ? WATER : AIR;
}
}
void sorter::deleteAllParticles() {
FOR_EACH_CELL(gnx, gny, gnz)
{
for (int a = 0; a<cells[i][j][k].size(); a++) {
delete cells[i][j][k][a];
}
}
} |
f988ee88e94cef7e048f0ae828618d0977aa886f | 072c2b7406bece70b9550f42032da8617eb570f0 | /Vulkan/Main.cpp | 0da3e87d34b7cac4e982ff478749a7955146b027 | [] | no_license | AlexMerritt/Vulkan | 330aefb79fc49a7263b4a2f41f9ba2741243a703 | 30d073e8820e6aa346830d1c034380b6c42425fd | refs/heads/master | 2021-01-20T18:39:44.163375 | 2016-08-15T18:04:11 | 2016-08-15T18:04:11 | 65,753,411 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 433 | cpp | Main.cpp | #define GLFW_INCLUDE_VULKAN
#include <GLFW\glfw3.h>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/vec4.hpp>
#include <glm/mat4x4.hpp>
#include<iostream>
#include <string>
#include "System.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdshow)
{
System* sys = new System();
if (sys->Initialize())
{
sys->Run();
}
sys->Release();
return 0;
}
|
1332a4eef7bb44482552157af56024d0cdfa8998 | 10549922d157ce67b6a32759b09a8dee78aebe9c | /clock2/clockengines/clocktimezoneresolver/inc/clocktimezoneresolverimpl.h | 0c7ff7bc1c5f690be78806e1a107c08b1878df33 | [] | no_license | SymbianSource/oss.FCL.sf.app.organizer | c8be5fbc1c5d8fc7d54a63bb1793f8db823fa3d7 | e15734d1943a012120b188fe3ffd5dd7594d145f | refs/heads/master | 2021-01-10T22:41:15.449986 | 2010-11-03T11:42:22 | 2010-11-03T11:42:22 | 70,369,523 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,452 | h | clocktimezoneresolverimpl.h | /*
* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: This is the header file of the CClockTimeZoneResolverImpl class.
*
*/
#ifndef __CLOCK_TIMEZONE_RESOLVER_IMPL_H__
#define __CLOCK_TIMEZONE_RESOLVER_IMPL_H__
// System includes
#include <e32base.h>
#include <etelmm.h>
#include <tz.h>
#include <tzconverter.h>
#include <tzlocalizationdatatypes.h>
#include <vtzrules.h>
// User includes
#include "clocktimesourceinterface.hrh"
// Forward declarations
class CClockMCCTzIdMapper;
// Class declaration
/**
* @class CClockTimeZoneResolverImpl
* @brief An instance of class CClockTimeZoneResolverImpl which is the actual implementation of timezone mapper.
* @dll clocktimezoneresolver.dll
*/
class CClockTimeZoneResolverImpl : public CBase
{
public: // Constructor and destructor
/**
* @brief Creates a CClockTimeZoneResolverImpl object
* @return CClockTimeZoneResolverImpl*
*/
static CClockTimeZoneResolverImpl* NewL();
/**
* @brief Destroy the object and release all memory objects
*/
~CClockTimeZoneResolverImpl();
public: // New functions
/**
* @brief Gets the timezone based on the MCC and NITZ info.
* @param aTimeInfo Time information got from the plugin.
* @param aMcc Mobile country code.
* @param aTzId The matching timezone ID.
* @return KErrNone if a matching timezone ID is found, KErrNotFound otherwise.
*/
TInt GetTimeZoneL( const STimeAttributes& aTimeInfo,
const RMobilePhone::TMobilePhoneNetworkCountryCode& aMcc,
TInt& aTzId );
/**
* @brief Find all TzIds for a given MCC with optional matching StdTimeOffset
* @param aMCC Mobile Country Code to search for
* @param aTzIdArray Array of CTzID objects to add matching zones to.
* @param aStdTimeOffset Limit returned zones to zones with a matching offset
*/
void TzIdFromMccL( const RMobilePhone::TMobilePhoneNetworkCountryCode& aMCC,
RArray< CTzId >& aTzIdArray,
const TTimeIntervalMinutes& aStdTimeOffset = -1 );
/**
* @brief Find the MCC for a given TzId
* @param aTzId CTzId to search for
* @return the MCC of the DST zone, or KErrNotFound if not found.
*/
TInt MCCFromTzIdL( const CTzId& aTzId );
private: // Constructor
/**
* @brief C++ default constructor
*/
CClockTimeZoneResolverImpl();
/**
* @brief Symbian OS 2nd phase constructor is private.
*/
void ConstructL();
private: // New functions
/**
* @brief Uses the received Nitz UTC offset in conjunction with the
* Mobile Country Code to calculate which DST zone we are in.
* @param aTimeInfo Time information got from any of the plugins.
* @param aMcc Mobile Country code got from MCC Listener.
* @param aTzId Contains the valid timezone ID, -1 otherwise.
* @return TInt KErrNone if successful, KErrNotFound otherwise.
*/
TInt FindDstZoneIdFromMccAndUtcOffsetL( const STimeAttributes& aTimeInfo,
const RMobilePhone::TMobilePhoneNetworkCountryCode& aMcc,
TInt& aTzId );
/**
* @brief Gets all the localized timezones for the corresponding mcc and timezone offset.
* @param aMcc Mobile Country code got from MCC Listener.
* @param aTimezoneOffset The standard offset got from the plugin.
* @param aTzLocalisedArray Contains all the matching localized timezones.
*/
void GetLocalizedZonesL( const RMobilePhone::TMobilePhoneNetworkCountryCode& aMcc,
const TTimeIntervalMinutes& aTimezoneOffset,
CTzLocalizedTimeZoneArray& aTzLocalisedArray );
/**
* @brief Gets the list of timezone ID's given an array of localized timezones.
* @param aLocTimeZones List of localized timezones.
* @param aZoneIdArray Array containing all matching timezone ID's.
* @param aNwLocalTime Local time.
* @param aNwUtcTime UTC time.
*/
void FindMatchingLocalisedZoneL( CTzLocalizedTimeZoneArray& aLocTimeZones,
RPointerArray<CTzId>& aZoneIdArray,
TTime& aNwLocalTime,
TTime& aNwUtcTime );
/**
* @brief Gets all the timezones for the corresponding mcc and timezone offset.
* @param aMcc Mobile Country code got from MCC Listener.
* @param aTimezoneOffset The standard offset got from the plugin.
* @param aTzUnLocalizedArray Contains all the matching timezones.
*/
void GetAllUnLocalizedZonesL( const RMobilePhone::TMobilePhoneNetworkCountryCode& aMcc,
const TTimeIntervalMinutes& aTimezoneOffset,
RArray< CTzId >& aTzUnLocalizedArray);
/**
* @brief Gets the list of timezone ID's given an array of unlocalized timezones.
* @param aUnLocalizedTzArray List of unlocalized timezones.
* @param aZoneIdArray Array containing all matching timezone ID's.
* @param aNwLocalTime Local time.
* @param aNwUtcTime UTC time.
*/
void FindMatchingUnLocalizedZoneL( RArray< CTzId >& aUnLocalizedTzArray,
RPointerArray<CTzId>& aZoneIdArray,
TTime& aNwLocalTime,
TTime& aNwUtcTime );
/**
* @brief Find DstOffset and standard Offset for the time zone aTzId using CTzRules
* @param aDstOffset referance to DstOffset
* @param aStdOffset referance to Standard Offset
* @param aTzId time zone Id for which DstOffset and StdOffset is to be found
*/
void GetStdOffSetAndDstOffSetL( TInt32& aDstOffset,
TInt32& aStdOffset,
const CTzId& aTzId );
/**
* @brief Finds the matching timezone ID with the specified offset.
* @param aTzOffset The offset for which we are trying to find the timezone ID.
* @param aTzId Contains the timezone ID matching the offset.
* @return KErrNotFound if no matches were found, KErrNone otherwise.
*/
TInt GetTimeZoneIdWithOffsetL( const TTimeIntervalMinutes& aTzOffset,
TInt& aTzId );
/**
* @brief Finds the matching timezone ID with the specified MCC.
* @param aMcc The MCC for which we are trying to find the timezone ID.
* @param aTzOffset The offset for which we are trying to find the timezone ID.
* @param aTzId Contains the timezone ID matching the MCC.
* @return KErrNotFound if no matches were found, KErrNone otherwise.
*/
TInt GetTimeZoneIdWithMccL( const RMobilePhone::TMobilePhoneNetworkCountryCode& aMcc,
const TTimeIntervalMinutes& aTzOffset,
TInt& aTzId );
/**
* @brief Tries to narrow down to a single timezone ID from the timezone array
* @param aLocTimeZones The array which contains all matching timezones.
* @param aTzId Contains the timezone ID, if found.
* @return KErrNotFound if no matches were found, KErrNone otherwise.
*/
TInt ProcessMatchingZones( CTzLocalizedTimeZoneArray& aLocTimeZones, TInt& aTzId );
/**
* @brief Tries to get timezone ID based on the dstoffset.
* @param aLocTimeZones The array which contains all matching timezones.
* @param aTzOffset The offset for which we are trying to find the timezone ID.
* @param aDstOffset The DST offset for which we are trying to find the timezone ID.
* @return KErrNotFound if no matches were found, KErrNone otherwise.
*/
TInt GetCorrectZone( CTzLocalizedTimeZoneArray& aLocTimeZones,
const TTimeIntervalMinutes& aTzOffset,
const TTimeIntervalMinutes& aDstOffset, TInt& aTzId );
/**
* @brief Gets the localized timezones for each zone that matches.
* @param aLocTimeZones The array which contains all matching timezones.
* @param aTzId Contains the timezone ID, if found.
* @return KErrNone if we have only one matching zone.
*/
TInt GetMatchingZonesL( CTzLocalizedTimeZoneArray* aLocTimeZones, TInt& aTzId );
private: // Data
/**
* @var iMccTzIdMapper
* @brief Interface to the MCC->TzIDMapper of type CMCCTzIdMapper*
*/
CClockMCCTzIdMapper* iMccTzIdMapper;
/**
* @var iTempZoneIds
* @brief Array of timezone id's.
*/
RPointerArray< CTzId > iTempZoneIds;
/**
* @var iRtz
* @brief Object of type RTz.
*/
RTz iRtz;
};
#endif // __CLOCK_TIMEZONE_RESOLVER_IMPL_H__
// End of file
|
8845428a5937e3d6d09d51dd38b1c8267bf75bbc | b90886f155c24b6f0c6bac5a6d813a1f09ead44d | /ExamplePlugin/Plugin.cpp | 21291009b87a48a4986d229122b2086374adc2c6 | [
"MIT"
] | permissive | PourrezJ/Infinity | 2531d19a44750177f17d7277435c2082b6754d1f | a5eb1e5078400cd9a566c9444a74c1802f6009d6 | refs/heads/master | 2023-02-24T21:57:17.442289 | 2021-01-25T04:35:18 | 2021-01-25T04:35:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,913 | cpp | Plugin.cpp | #include "pch.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "../BIDebugEngine/Plugins.h"
struct testclass {
char* name;
};
//this is wrong
void* CreateTestClass(char* name)
{
Infinity::Logging::Print("Creating New Test Class! w/ Name: %s", name);
testclass* result = (testclass*)malloc(sizeof(testclass));
if(result)
result->name = name;
return result;
}
//this doesn't work because the above is wrong (can't test it until above is correct)
char* GetTestClassName(void* arg1)
{
Infinity::Logging::Print("Getting Test Class Name!");
if (!arg1)
return NULL;
return ((testclass*)arg1)->name;
}
//this works :)
int GetInternalValue(char* string_input)
{
Infinity::Logging::Print("Getting String Length of '%s'", string_input);
return strlen(string_input);
}
void TestPluginFunction()
{
Infinity::Logging::Print("Test!");
}
//we need to export this function
void __declspec(dllexport) OnPluginLoad()
{
Infinity::Logging::Print("Plugin Load!"); //plugins can write to console/logfile by using Print & Error methods
Infinity::Enfusion::Enscript::RegisterFunction("TestPluginFunc", &TestPluginFunction); //this function will be imported from BIDebugEngine.dll
Infinity::Enfusion::PrintToConsole("Plugin Console Print Test!");
void* pCustomType = Infinity::Enfusion::Enscript::RegisterObject("ExampleTestClass");
if (pCustomType)
{
Infinity::Enfusion::Enscript::RegisterFunctionForObject(pCustomType, "Create", &CreateTestClass, false);
Infinity::Enfusion::Enscript::RegisterFunctionForObject(pCustomType, "GetName", &GetTestClassName, false);
Infinity::Enfusion::Enscript::RegisterFunctionForObject(pCustomType, "GetInternalValue", &GetInternalValue, false);
}
else
{
Infinity::Logging::Print("Failed to register 'ExampleTestClass'. Are you sure the enscript class is defined properly?");
}
Infinity::Logging::Print("All Functions Registered!");
} |
8a9de4cffdcd60548bd0759b93289831d418b5a7 | 27d20d5d5ba446128b602e338b583ee5f76666b9 | /2014/1013/cards4b.cpp | 8a6489aaa43821ab1c2f0a8a50ed6e552fec10b0 | [] | no_license | Neverous/ii-mia | 2b6b10181e7b6207d22a1ffd6c08c499ccc8c613 | 9a87fa85e325b1c39041c99a74005f88341a1aa7 | refs/heads/master | 2021-01-10T15:52:27.778247 | 2016-03-22T14:49:34 | 2016-03-22T14:49:34 | 54,483,598 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,695 | cpp | cards4b.cpp | /* 2014
* Maciej Szeptuch
* II UWr
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
char cards[131072];
int total_ones, ones, eaten_ones,
total_zeros, zeros, eaten_zeros,
total_marks, marks,
n;
bool p00,
p01,
p10,
p11;
int main(void)
{
scanf("%s", cards);
n = strlen(cards);
for(int c = 0; cards[c]; ++ c)
switch(cards[c])
{
case '1':
++ total_ones;
break;
case '0':
++ total_zeros;
break;
case '?':
++ total_marks;
break;
}
eaten_zeros = (n - 2) / 2;
eaten_ones = (n - 1) / 2;
p00 = total_zeros + total_marks >= 2 + eaten_zeros;
p11 = total_ones + total_marks >= 2 + eaten_ones;
for(int c = 0; cards[c]; ++ c)
{
if( (cards[c] == '1' || cards[c] == '?')
&& zeros + marks >= 1 + eaten_zeros
&& total_ones + total_marks - std::max(0, eaten_zeros + 1 - zeros) >= 1 + eaten_ones)
p01 = true;
if( (cards[c] == '0' || cards[c] == '?')
&& ones + marks >= 1 + eaten_ones
&& total_zeros + total_marks - std::max(0, eaten_ones + 1 - ones) >= 1 + eaten_zeros)
p10 = true;
switch(cards[c])
{
case '1':
++ ones;
break;
case '0':
++ zeros;
break;
case '?':
++ marks;
break;
}
}
if(p00)
puts("00");
if(p01)
puts("01");
if(p10)
puts("10");
if(p11)
puts("11");
return 0;
}
|
0c8471cb53feef50064246b84aba5e1e5d2c2313 | 7d113f8d417248248cfc290268e3023f02da2d65 | /include/config.hpp | e43a58a45016341acb5afef8168382f3da6d9b85 | [
"MIT"
] | permissive | northy/digital-certificates | 8b971812af9b40da24782dd5c566a911cd008b9e | 890e232b877ac2f6400b7605d71682dd3e2cd193 | refs/heads/master | 2023-03-29T11:40:55.346945 | 2021-04-10T19:25:51 | 2021-04-10T19:25:51 | 355,726,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25 | hpp | config.hpp | #define RSA_KEYSIZE 2048
|
e200ed85865b976c46a4a40fbec0d254c5422544 | 39daf438ab3b8425c3be8f7c5fc61f23619922ae | /test/test.ino | 957c2ac5560b2a69e579fa774e56a180f969a12b | [] | no_license | muenznej/DocHat_Lukas | c6ac4c13d6420bc2022073ddbf87b831f4ab6546 | f506388d3f6e1893888168dcbd8f0cc0f4b38fd8 | refs/heads/master | 2021-08-11T16:31:40.569324 | 2017-11-13T22:50:03 | 2017-11-13T22:50:03 | 109,705,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,546 | ino | test.ino |
// Credit:
// Midi to Arduino Converter
// - Andy Tran (extramaster), 2015
// https://www.extramaster.net/tools/midiToArduino/
//
// Process:
// Midi -> Midi tracks -> Note mappings -> Frequency
//
// CC0
// Set this to be the pin that your buzzer resides in. (Note that you can only have one buzzer actively using the PWM signal at a time).
int tonePin = 11;
void setup() {
}
void midi() {
tone(tonePin, 220, 2.74122829861);
delay(2.74122829861);
tone(tonePin, 110, 27.4122829861);
delay(27.4122829861);
delay(145.285099826);
tone(tonePin, 130, 8.22368489583);
delay(8.22368489583);
tone(tonePin, 261, 38.3771961806);
delay(38.3771961806);
tone(tonePin, 146, 109.649131944);
delay(109.649131944);
delay(19.1885980903);
tone(tonePin, 293, 32.8947395833);
delay(32.8947395833);
tone(tonePin, 174, 109.649131944);
delay(109.649131944);
delay(32.8947395833);
tone(tonePin, 349, 32.8947395833);
delay(32.8947395833);
tone(tonePin, 293, 320.723710937);
delay(320.723710937);
tone(tonePin, 146, 41.1184244792);
delay(41.1184244792);
delay(131.578958333);
tone(tonePin, 220, 131.578958333);
delay(131.578958333);
delay(43.8596527778);
tone(tonePin, 146, 16.4473697917);
delay(16.4473697917);
tone(tonePin, 349, 16.4473697917);
delay(16.4473697917);
tone(tonePin, 329, 98.68421875);
delay(98.68421875);
tone(tonePin, 130, 10.9649131944);
delay(10.9649131944);
tone(tonePin, 195, 13.7061414931);
delay(13.7061414931);
delay(194.627209201);
tone(tonePin, 116, 441.337756076);
delay(441.337756076);
delay(84.9780772569);
tone(tonePin, 174, 65.7894791667);
delay(65.7894791667);
tone(tonePin, 293, 2.74122829861);
delay(2.74122829861);
delay(106.907903646);
tone(tonePin, 116, 208.333350694);
delay(208.333350694);
delay(142.543871528);
tone(tonePin, 174, 46.6008810764);
delay(46.6008810764);
tone(tonePin, 293, 27.4122829861);
delay(27.4122829861);
tone(tonePin, 116, 68.5307074653);
delay(68.5307074653);
delay(32.8947395833);
tone(tonePin, 329, 191.885980903);
delay(191.885980903);
tone(tonePin, 195, 5.48245659722);
delay(5.48245659722);
tone(tonePin, 130, 16.4473697917);
delay(16.4473697917);
delay(312.500026042);
tone(tonePin, 277, 82.2368489583);
delay(82.2368489583);
tone(tonePin, 195, 139.802643229);
delay(139.802643229);
tone(tonePin, 329, 87.7193055556);
delay(87.7193055556);
tone(tonePin, 130, 21.9298263889);
delay(21.9298263889);
delay(19.1885980903);
tone(tonePin, 146, 331.688624132);
delay(331.688624132);
delay(19.1885980903);
tone(tonePin, 110, 175.438611111);
delay(175.438611111);
delay(175.438611111);
tone(tonePin, 130, 21.9298263889);
delay(21.9298263889);
tone(tonePin, 146, 139.802643229);
delay(139.802643229);
delay(13.7061414931);
tone(tonePin, 174, 134.320186632);
delay(134.320186632);
tone(tonePin, 220, 13.7061414931);
delay(13.7061414931);
delay(27.4122829861);
tone(tonePin, 146, 402.960559896);
delay(402.960559896);
delay(123.355273437);
tone(tonePin, 220, 120.614045139);
delay(120.614045139);
delay(54.8245659722);
tone(tonePin, 146, 16.4473697917);
delay(16.4473697917);
tone(tonePin, 349, 65.7894791667);
delay(65.7894791667);
tone(tonePin, 329, 60.3070225694);
delay(60.3070225694);
tone(tonePin, 130, 10.9649131944);
delay(10.9649131944);
tone(tonePin, 195, 21.9298263889);
delay(21.9298263889);
delay(175.438611111);
tone(tonePin, 116, 460.526354167);
delay(460.526354167);
delay(65.7894791667);
tone(tonePin, 174, 65.7894791667);
delay(65.7894791667);
tone(tonePin, 293, 10.9649131944);
delay(10.9649131944);
delay(98.68421875);
tone(tonePin, 116, 243.969318576);
delay(243.969318576);
delay(106.907903646);
tone(tonePin, 174, 60.3070225694);
delay(60.3070225694);
tone(tonePin, 293, 52.0833376736);
delay(52.0833376736);
tone(tonePin, 116, 41.1184244792);
delay(41.1184244792);
delay(21.9298263889);
tone(tonePin, 329, 191.885980903);
delay(191.885980903);
tone(tonePin, 195, 13.7061414931);
delay(13.7061414931);
tone(tonePin, 130, 13.7061414931);
delay(13.7061414931);
delay(307.017569444);
delay(87.7193055556);
tone(tonePin, 277, 38.3771961806);
delay(38.3771961806);
tone(tonePin, 195, 117.87281684);
delay(117.87281684);
tone(tonePin, 329, 74.0131640625);
delay(74.0131640625);
tone(tonePin, 130, 10.9649131944);
delay(10.9649131944);
delay(21.9298263889);
tone(tonePin, 146, 331.688624132);
delay(331.688624132);
delay(19.1885980903);
tone(tonePin, 110, 175.438611111);
delay(175.438611111);
tone(tonePin, 130, 148.026328125);
delay(148.026328125);
delay(27.4122829861);
tone(tonePin, 146, 156.250013021);
delay(156.250013021);
delay(19.1885980903);
tone(tonePin, 174, 112.390360243);
delay(112.390360243);
delay(63.0482508681);
tone(tonePin, 349, 383.771961806);
delay(383.771961806);
tone(tonePin, 220, 27.4122829861);
delay(27.4122829861);
tone(tonePin, 146, 5.48245659722);
delay(5.48245659722);
delay(109.649131944);
tone(tonePin, 220, 112.390360243);
delay(112.390360243);
tone(tonePin, 146, 63.0482508681);
delay(63.0482508681);
tone(tonePin, 349, 68.5307074653);
delay(68.5307074653);
tone(tonePin, 329, 74.0131640625);
delay(74.0131640625);
tone(tonePin, 195, 57.5657942708);
delay(57.5657942708);
delay(150.767556424);
tone(tonePin, 116, 433.114071181);
delay(433.114071181);
delay(93.2017621528);
tone(tonePin, 174, 74.0131640625);
delay(74.0131640625);
tone(tonePin, 293, 13.7061414931);
delay(13.7061414931);
delay(87.7193055556);
tone(tonePin, 116, 241.228090278);
delay(241.228090278);
delay(109.649131944);
tone(tonePin, 174, 54.8245659722);
delay(54.8245659722);
tone(tonePin, 293, 43.8596527778);
delay(43.8596527778);
tone(tonePin, 116, 49.342109375);
delay(49.342109375);
delay(27.4122829861);
tone(tonePin, 130, 208.333350694);
delay(208.333350694);
tone(tonePin, 329, 10.9649131944);
delay(10.9649131944);
delay(307.017569444);
delay(87.7193055556);
tone(tonePin, 277, 30.1535112847);
delay(30.1535112847);
tone(tonePin, 195, 104.166675347);
delay(104.166675347);
tone(tonePin, 329, 74.0131640625);
delay(74.0131640625);
tone(tonePin, 130, 35.6359678819);
delay(35.6359678819);
delay(19.1885980903);
delay(350.877222222);
tone(tonePin, 146, 2.74122829861);
delay(2.74122829861);
delay(172.697382812);
tone(tonePin, 110, 8.22368489583);
delay(8.22368489583);
delay(167.214926215);
tone(tonePin, 130, 24.6710546875);
delay(24.6710546875);
delay(150.767556424);
tone(tonePin, 146, 2.74122829861);
delay(2.74122829861);
tone(tonePin, 174, 128.837730035);
delay(128.837730035);
delay(43.8596527778);
tone(tonePin, 349, 372.807048611);
delay(372.807048611);
tone(tonePin, 220, 24.6710546875);
delay(24.6710546875);
tone(tonePin, 146, 5.48245659722);
delay(5.48245659722);
delay(123.355273437);
tone(tonePin, 220, 131.578958333);
delay(131.578958333);
tone(tonePin, 146, 43.8596527778);
delay(43.8596527778);
tone(tonePin, 349, 87.7193055556);
delay(87.7193055556);
tone(tonePin, 329, 65.7894791667);
delay(65.7894791667);
tone(tonePin, 130, 21.9298263889);
delay(21.9298263889);
tone(tonePin, 195, 2.74122829861);
delay(2.74122829861);
delay(172.697382812);
tone(tonePin, 116, 433.114071181);
delay(433.114071181);
delay(93.2017621528);
tone(tonePin, 174, 65.7894791667);
delay(65.7894791667);
tone(tonePin, 293, 2.74122829861);
delay(2.74122829861);
delay(106.907903646);
tone(tonePin, 116, 175.438611111);
delay(175.438611111);
delay(175.438611111);
tone(tonePin, 174, 46.6008810764);
delay(46.6008810764);
tone(tonePin, 293, 27.4122829861);
delay(27.4122829861);
tone(tonePin, 116, 60.3070225694);
delay(60.3070225694);
delay(41.1184244792);
tone(tonePin, 130, 265.899144965);
delay(265.899144965);
tone(tonePin, 329, 41.1184244792);
delay(41.1184244792);
tone(tonePin, 195, 2.74122829861);
delay(2.74122829861);
delay(216.55703559);
tone(tonePin, 130, 243.969318576);
delay(243.969318576);
tone(tonePin, 329, 8.22368489583);
delay(8.22368489583);
tone(tonePin, 195, 49.342109375);
delay(49.342109375);
delay(224.780720486);
tone(tonePin, 110, 208.333350694);
delay(208.333350694);
tone(tonePin, 164, 27.4122829861);
delay(27.4122829861);
tone(tonePin, 220, 5.48245659722);
delay(5.48245659722);
delay(285.087743056);
tone(tonePin, 130, 241.228090278);
delay(241.228090278);
tone(tonePin, 261, 10.9649131944);
delay(10.9649131944);
tone(tonePin, 195, 5.48245659722);
delay(5.48245659722);
delay(268.640373264);
delay(350.877222222);
tone(tonePin, 69, 427.631614583);
delay(427.631614583);
delay(98.68421875);
tone(tonePin, 329, 24.6710546875);
delay(24.6710546875);
tone(tonePin, 207, 30.1535112847);
delay(30.1535112847);
delay(120.614045139);
tone(tonePin, 69, 309.758797743);
delay(309.758797743);
tone(tonePin, 329, 41.1184244792);
delay(41.1184244792);
tone(tonePin, 277, 24.6710546875);
delay(24.6710546875);
tone(tonePin, 207, 8.22368489583);
delay(8.22368489583);
delay(142.543871528);
tone(tonePin, 69, 249.451775174);
delay(249.451775174);
delay(101.425447049);
tone(tonePin, 207, 131.578958333);
delay(131.578958333);
tone(tonePin, 329, 30.1535112847);
delay(30.1535112847);
delay(13.7061414931);
tone(tonePin, 277, 2.74122829861);
delay(2.74122829861);
tone(tonePin, 174, 8.22368489583);
delay(8.22368489583);
delay(339.912309028);
delay(175.438611111);
tone(tonePin, 184, 230.263177083);
delay(230.263177083);
tone(tonePin, 77, 13.7061414931);
delay(13.7061414931);
tone(tonePin, 311, 5.48245659722);
delay(5.48245659722);
tone(tonePin, 261, 13.7061414931);
delay(13.7061414931);
delay(87.7193055556);
tone(tonePin, 77, 142.543871528);
delay(142.543871528);
delay(32.8947395833);
delay(350.877222222);
tone(tonePin, 184, 24.6710546875);
delay(24.6710546875);
tone(tonePin, 311, 21.9298263889);
delay(21.9298263889);
delay(128.837730035);
tone(tonePin, 51, 175.438611111);
delay(175.438611111);
delay(175.438611111);
tone(tonePin, 103, 2.74122829861);
delay(2.74122829861);
tone(tonePin, 261, 93.2017621528);
delay(93.2017621528);
tone(tonePin, 311, 16.4473697917);
delay(16.4473697917);
tone(tonePin, 51, 8.22368489583);
delay(8.22368489583);
tone(tonePin, 184, 19.1885980903);
delay(19.1885980903);
delay(35.6359678819);
delay(350.877222222);
delay(175.438611111);
tone(tonePin, 82, 134.320186632);
delay(134.320186632);
delay(216.55703559);
tone(tonePin, 329, 30.1535112847);
delay(30.1535112847);
tone(tonePin, 207, 8.22368489583);
delay(8.22368489583);
tone(tonePin, 246, 30.1535112847);
delay(30.1535112847);
tone(tonePin, 82, 63.0482508681);
delay(63.0482508681);
delay(43.8596527778);
tone(tonePin, 329, 241.228090278);
delay(241.228090278);
tone(tonePin, 261, 10.9649131944);
delay(10.9649131944);
tone(tonePin, 195, 27.4122829861);
delay(27.4122829861);
tone(tonePin, 65, 8.22368489583);
delay(8.22368489583);
delay(238.486861979);
tone(tonePin, 73, 265.899144965);
delay(265.899144965);
tone(tonePin, 184, 41.1184244792);
delay(41.1184244792);
tone(tonePin, 293, 10.9649131944);
delay(10.9649131944);
delay(208.333350694);
tone(tonePin, 82, 197.3684375);
delay(197.3684375);
tone(tonePin, 207, 60.3070225694);
delay(60.3070225694);
tone(tonePin, 246, 8.22368489583);
delay(8.22368489583);
tone(tonePin, 329, 13.7061414931);
delay(13.7061414931);
delay(71.2719357639);
delay(175.438611111);
tone(tonePin, 440, 235.745633681);
delay(235.745633681);
tone(tonePin, 277, 13.7061414931);
delay(13.7061414931);
tone(tonePin, 329, 16.4473697917);
delay(16.4473697917);
delay(84.9780772569);
tone(tonePin, 41, 416.666701389);
delay(416.666701389);
tone(tonePin, 493, 98.68421875);
delay(98.68421875);
tone(tonePin, 293, 10.9649131944);
delay(10.9649131944);
tone(tonePin, 415, 10.9649131944);
delay(10.9649131944);
delay(164.473697917);
tone(tonePin, 82, 296.05265625);
delay(296.05265625);
tone(tonePin, 41, 32.8947395833);
delay(32.8947395833);
delay(21.9298263889);
tone(tonePin, 493, 156.250013021);
delay(156.250013021);
tone(tonePin, 293, 8.22368489583);
delay(8.22368489583);
tone(tonePin, 415, 5.48245659722);
delay(5.48245659722);
delay(5.48245659722);
tone(tonePin, 82, 24.6710546875);
delay(24.6710546875);
delay(326.206167535);
delay(175.438611111);
tone(tonePin, 92, 191.885980903);
delay(191.885980903);
tone(tonePin, 220, 27.4122829861);
delay(27.4122829861);
delay(131.578958333);
tone(tonePin, 329, 76.7543923611);
delay(76.7543923611);
tone(tonePin, 184, 10.9649131944);
delay(10.9649131944);
tone(tonePin, 277, 52.0833376736);
delay(52.0833376736);
delay(35.6359678819);
tone(tonePin, 92, 38.3771961806);
delay(38.3771961806);
tone(tonePin, 123, 246.710546875);
delay(246.710546875);
delay(65.7894791667);
tone(tonePin, 184, 98.68421875);
delay(98.68421875);
tone(tonePin, 311, 5.48245659722);
delay(5.48245659722);
tone(tonePin, 246, 5.48245659722);
delay(5.48245659722);
delay(65.7894791667);
tone(tonePin, 123, 178.17983941);
delay(178.17983941);
tone(tonePin, 184, 145.285099826);
delay(145.285099826);
tone(tonePin, 246, 5.48245659722);
delay(5.48245659722);
tone(tonePin, 311, 21.9298263889);
delay(21.9298263889);
tone(tonePin, 123, 109.649131944);
delay(109.649131944);
delay(65.7894791667);
tone(tonePin, 440, 265.899144965);
delay(265.899144965);
delay(84.9780772569);
tone(tonePin, 277, 38.3771961806);
delay(38.3771961806);
delay(137.061414931);
tone(tonePin, 415, 104.166675347);
delay(104.166675347);
tone(tonePin, 82, 95.9429904514);
delay(95.9429904514);
tone(tonePin, 246, 30.1535112847);
delay(30.1535112847);
tone(tonePin, 329, 57.5657942708);
delay(57.5657942708);
delay(63.0482508681);
tone(tonePin, 82, 112.390360243);
delay(112.390360243);
delay(63.0482508681);
tone(tonePin, 277, 345.394765625);
delay(345.394765625);
delay(5.48245659722);
tone(tonePin, 329, 76.7543923611);
delay(76.7543923611);
tone(tonePin, 110, 35.6359678819);
delay(35.6359678819);
tone(tonePin, 220, 30.1535112847);
delay(30.1535112847);
delay(32.8947395833);
delay(350.877222222);
tone(tonePin, 51, 21.9298263889);
delay(21.9298263889);
tone(tonePin, 329, 16.4473697917);
delay(16.4473697917);
tone(tonePin, 207, 16.4473697917);
delay(16.4473697917);
tone(tonePin, 246, 21.9298263889);
delay(21.9298263889);
tone(tonePin, 103, 19.1885980903);
delay(19.1885980903);
delay(79.4956206597);
delay(350.877222222);
tone(tonePin, 46, 156.250013021);
delay(156.250013021);
delay(19.1885980903);
tone(tonePin, 92, 120.614045139);
delay(120.614045139);
tone(tonePin, 220, 98.68421875);
delay(98.68421875);
tone(tonePin, 277, 46.6008810764);
delay(46.6008810764);
delay(84.9780772569);
tone(tonePin, 329, 60.3070225694);
delay(60.3070225694);
tone(tonePin, 184, 27.4122829861);
delay(27.4122829861);
tone(tonePin, 92, 54.8245659722);
delay(54.8245659722);
delay(32.8947395833);
delay(350.877222222);
tone(tonePin, 184, 16.4473697917);
delay(16.4473697917);
tone(tonePin, 246, 13.7061414931);
delay(13.7061414931);
tone(tonePin, 311, 16.4473697917);
delay(16.4473697917);
delay(128.837730035);
tone(tonePin, 61, 208.333350694);
delay(208.333350694);
tone(tonePin, 123, 79.4956206597);
delay(79.4956206597);
delay(63.0482508681);
tone(tonePin, 184, 21.9298263889);
delay(21.9298263889);
tone(tonePin, 246, 65.7894791667);
delay(65.7894791667);
tone(tonePin, 329, 2.74122829861);
delay(2.74122829861);
tone(tonePin, 61, 52.0833376736);
delay(52.0833376736);
delay(32.8947395833);
delay(350.877222222);
tone(tonePin, 41, 446.820212674);
delay(446.820212674);
tone(tonePin, 246, 13.7061414931);
delay(13.7061414931);
tone(tonePin, 82, 65.7894791667);
delay(65.7894791667);
tone(tonePin, 329, 32.8947395833);
delay(32.8947395833);
tone(tonePin, 41, 123.355273437);
delay(123.355273437);
delay(19.1885980903);
}
void loop() {
// Play midi
midi();
}
|
ca230d1e06be2805b7a69459959bc8c718a9dfe5 | 8856b4097de90a8bef468a8c6a242770df4d03bc | /Zork/creature.cpp | fb94a3068c25a34754ecb22654840c857e228987 | [
"MIT"
] | permissive | lowysole/zork | b391f9deee728a956971bec8bd93365bfdc7fe22 | 07e85a6f2297eec95c57a60ee6a2e30bbaced4a4 | refs/heads/master | 2022-11-22T08:41:48.133332 | 2020-07-26T20:02:04 | 2020-07-26T20:02:04 | 281,786,862 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,394 | cpp | creature.cpp | #include "creature.h"
#include "npc.h"
#include "item.h"
//Constructor
Creature::Creature(const char* name, const char* description, Room* location) :
Entity(name, description, (Entity*)location) {
entity_type = CREATURE;
creature_type = NPC;
this->location = location;
hp = 10;
attack = 0;
armour = NULL;
weapon = NULL;
}
//Destructor
Creature::~Creature() {
}
void Creature::Look()
{
if (creature_type == NPC) {
Npc* npc = (Npc*)this;
if (npc->isAlive())
{
cout << name << endl;
cout << description << endl;
}
else
{
cout << name << "'s body, he is dead" << endl;
}
}
}
Room* Creature::GetCurrentRoom() {
return (Room*)parent;
}
void Creature::Stats() {
cout << "Stats from " << name << ":" << endl;
cout << "-----------------------" << endl;
cout << "HP: " << hp << endl;
cout << "Armour: " <<
((armour) ? armour->name : "no armour equiped") << endl;
cout << "Attack: " << attack << endl;
cout << "Weapon: " <<
((weapon) ? weapon->name : "no weapon equiped") << endl;
}
void Creature::KillNPC(Npc* npc) {
npc->hp = 0;
// Drop enemy items to the current Room
Room* room = this->GetCurrentRoom();
list<Entity*> items = npc->FindAll(ITEM);
for (list<Entity*>::iterator it = items.begin(); it != items.end(); ++it) {
(*it)->SetNewParent((Entity*)room);
cout << "Enemy item '" << (*it)->name << "' dropped into the room." << endl;
}
} |
fa93d985f73eb4064aa95b40fff4015d6cf5612d | bf176e00de9b2bc9c144e83b62e197c9d7d828fb | /lab3.cpp | 6ce55943869d3aa846f350fb04383bda161f7673 | [] | no_license | KarenBarrientos/laab3 | 288e4caaee418ee45671ddffbdbb4355404d12bb | 5032990c420b6332c327e4217cce56ede7c3e32b | refs/heads/master | 2021-05-03T08:50:50.475698 | 2016-10-28T23:35:57 | 2016-10-28T23:35:57 | 72,235,244 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,590 | cpp | lab3.cpp | #include <iostream>
using std::cin;
using std::cout;
using std::endl;
void imprimir(int**,int,int);
int main(int argc, char const *argv[]){
int opcion;
char continuar;
do{
cout<<endl;
cout <<"***** MENU ***** "<< endl
<< "1. Ejercicio1" << endl
<< "2. Ejercicio2" << endl
<< "3. Ejercicio3" << endl;
cin >> opcion;
if (opcion == 1){
int anio=1901;
int final = 2000;
int domingos = 0;
int cantidadDias=1;
int meses[] = {31,28,31,30,31,30,31,31,30,31,30,31};
cout<<"-------------- EJERCICIO 1 --------------"<<endl;
for(int i=anio; i<=final; i++){
for(int j=0;j<12;j++){
if(i>1901){
if(cantidadDias%7==0){
domingos++;
}
}
int dias=0;
if(j!=1 || i%4!=0 || (i%100==0 && i%400!=0)){ // comparando meses y el año divisible entre 4 y 400
dias= meses[j];
}
else{ // febrero
dias = 29;
}
cantidadDias += dias;
}
} //fin for
cout<<"Hay "<<domingos+1 <<" domingos"<<endl;
} // fin if
if (opcion==2){
int gradoAlto,contador=0,polinomio;
int a;
cout<<"-------------- EJERCICIO 2 --------------"<<endl;
cout<<"Ingrese el grado mas alto del polinomio: "<<endl;
cin>>gradoAlto;
int** matriz = new int*[3];
for(int i=0;i<gradoAlto;i++){
matriz[i]=new int[gradoAlto];
}
for(int i=gradoAlto; i>=0; i--){
cout<<"Polinomio de grado x^"<<i<<":";
cout<<"Ingrese el polinomio x^"<<i<<": ";
cin>> matriz[0][contador];
contador++;
}
cout<<"Ingrese a:";
cin>>a;
for(int i=0;i<2;i++){
if(i==0){
matriz[1][0]=matriz[0][0];
matriz[2][0]=matriz[0][0];
imprimir(matriz,a,gradoAlto);
}else{
for(int j=1;j<=gradoAlto;j++){
matriz[i][j]=matriz[i+1][j-1];
matriz[i+1][j]=matriz[i-1][j]+matriz[i][j];
imprimir(matriz,a,gradoAlto);
}
}
}
cout<<"El Residuo es :"<<matriz[2][gradoAlto]<<"\n";
imprimir(matriz,a,gradoAlto);
for(int i = 0;i<gradoAlto;i++){
delete[] matriz[i];
}
delete[] matriz;
}// fin if2
if (opcion==3){
int numero;
cout<<"Ingrese numero: "<<endl;
cin>>numero;
cout<<"NO ME DIO TIEMPO :( "<<endl;
}
cout<<"Desea Continuar[s/n]: ";
cin>>continuar;
}while(continuar == 's'||continuar == 'S');
return 0;
}
void imprimir(int** matrix,int a,int grado){
for(int i=0;i<3;i++){
for(int j=0;j<grado+1;j++){
cout<<" "<<matrix[i][j];
}
if(i<2){
cout<<"| "<<a;
}
cout<<"\n";
if(i==2){
cout<<"------------------------ \n";
}
}
cout<<"\n";
} |
1f03d078a2a9086a87d7c8515a6894112557f734 | 072026be4b3c02d69ec0ac6b3eed37da6721a9fb | /UVA 00336 - A Node Too Far.cpp | d058c0ded9a03f8872d058549b59c7e5a102414c | [] | no_license | vmmc2/Competitive-Programming | 1c4f61528301a9d83eeabee352d4e55ed2e64e1f | 0c71f99a7d7144ae762b04ec2af8e18c5181d330 | refs/heads/master | 2022-06-26T23:49:50.088941 | 2022-05-27T21:38:20 | 2022-05-27T21:38:20 | 152,163,693 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,049 | cpp | UVA 00336 - A Node Too Far.cpp | #include <bits/stdc++.h>
#include <sstream>
#include <cmath>
#define pb push_back
#define INF 99999999
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
vector<int> adjlist[100000];
int visitados[100000];
int dist[100000];
void reset_graph(){
for(int i = 0; i < 100000; i++){
adjlist[i].clear();
visitados[i] = 0;
dist[i] = INF;
}
return;
}
void reset_visdist(){
for(int i = 0; i < 100000; i++){
visitados[i] = 0;
dist[i] = INF;
}
return;
}
void bfs(int source){
queue<int> fila;
visitados[source] = 1;
dist[source] = 0;
fila.push(source);
while(!fila.empty()){
int u = fila.front();
fila.pop();
for(int i = 0; i < (int)adjlist[u].size(); i++){
int x = adjlist[u][i];
if(visitados[x] == 0){
visitados[x] = 1;
dist[x] = min(dist[x], dist[u] + 1);
fila.push(x);
}
}
}
return;
}
int main(){
int numedges;
int counter = 1;
while(cin >>numedges){
reset_graph();
set<int> vertices_existentes;
if(numedges == 0) break; //fim do programa.
int x, y;
for(int a = 1; a <= numedges; a++){
cin >> x >> y;
vertices_existentes.insert(x);
vertices_existentes.insert(y);
adjlist[x].pb(y);
adjlist[y].pb(x);
}
int initnode, ttl;
while(true){
cin >> initnode >> ttl;
reset_visdist();
if(initnode == 0 && ttl == 0) break;
bfs(initnode);
int not_reached = 0;
for(set<int>::iterator it = vertices_existentes.begin(); it != vertices_existentes.end(); it++){
if(dist[*it] > ttl) not_reached++;
}
cout << "Case " << counter << ": " << not_reached << " nodes not reachable from node " << initnode << " with TTL = " << ttl << ".\n";
counter++;
}
}
return 0;
}
|
9140f28d7a2dd83743562f73f18afd6a14c56a1c | ffb4b96794d3a7b3a1275f3f3f360ce45479bbb9 | /client/letter.h | bed1599f9e7dc7710203f77afcd52ecaac2e5eca | [] | no_license | SimoneDutto/CollaborativeEditor | c556dd9fd2611f2aa72caa1453eda2e7d208a379 | b42ca41da6ff641e6605d661313356bb2f2abdb8 | refs/heads/master | 2022-10-20T17:14:20.155851 | 2020-06-16T14:56:14 | 2020-06-16T14:56:14 | 207,262,147 | 2 | 1 | null | 2020-06-13T14:35:17 | 2019-09-09T08:33:03 | C++ | UTF-8 | C++ | false | false | 1,508 | h | letter.h | #ifndef LECTER_H
#define LECTER_H
#include <QString>
#include <QStringList>
#include <QVector>
#include <QChar>
#include <QTextCursor>
class Letter
{
// campi per gestire la lettera, la posizione, lo stile, etc
private:
QChar letter;
QVector<int> fractionalIndexes;
QString letterID;
QTextCharFormat format;
Qt::AlignmentFlag alignment;
public:
Letter(QChar letter, QVector<int> fractionals, QString letterID, QTextCharFormat format, Qt::AlignmentFlag alignment);
Letter(const Letter& l);
Letter& operator=(const Letter && source);
Letter& operator=(const Letter& source);
QChar getValue();
QVector<int> getFractionalIndexes();
QString getLetterID();
int getSiteID();
int getIndex();
int getUserId();
int getNumberOfFractionals();
QTextCharFormat getFormat();
Qt::AlignmentFlag getAlignment();
void setIndex(int index);
void setStyle(QString style);
void editIndex(int index, int value);
void addFractionalDigit(int value);
bool hasSameFractionals(Letter other);
bool comesFirstRight(Letter other, int pos_id);
bool comesFirstLeft(Letter other, int pos_id);
void setNewPosition(QVector<int> position);
void setFormat(QTextCharFormat format);
void setStyleFromString(QString format, QString font);
void setAlignment(Qt::AlignmentFlag alignment);
void setColor(QColor c);
void setBack(QColor c);
QBrush getColor();
QBrush getBack();
~Letter(){}
};
#endif // LECTER_H
|
81a71ab968d5552e81836108798623a8bd125638 | 2c86487ff9f8a4597e9c72cca746e073d1b01ff0 | /TD3/Bibliotheque/main.cpp | b1fe54915e687c4ec47d8ba70b153e5d939a5fae | [] | no_license | Ennaouri/cours-cpp | 3dfbdce3a548c182f5848779e48ff7c42474ad29 | 6a83115cff619be44593cf3d79238ef707af8b29 | refs/heads/master | 2020-08-05T21:19:32.748535 | 2017-05-09T20:11:25 | 2017-05-09T20:11:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 861 | cpp | main.cpp | // Created by bothmena on 17/02/17.
# include <iostream>
#include "Ouvrage.h"
#include "Bibliotheque.h"
int main() {
Ouvrage *ouvrageUn = new Ouvrage(123, "ouvrage Un", 10, 29);
Ouvrage *ouvrageDeux = new Ouvrage(234, "ouvrage Deux", 20, 25);
Ouvrage *ouvrageTrois = new Ouvrage(345, "ouvrage Trois", 30, 15);
Bibliotheque *bibliotheque = new Bibliotheque();
bibliotheque->ajouter( ouvrageUn );
bibliotheque->ajouter( ouvrageDeux );
bibliotheque->afficher();
cout << "prix total: " << bibliotheque->prixTotal() << "Dt" << endl;
bibliotheque->augmenterNbExp( 123, 8 );
bibliotheque->augmenterNbExp( 123, 18 );
bibliotheque->diminuerNbExp( 234, 11 );
bibliotheque->ajouter( ouvrageTrois );
bibliotheque->afficher();
cout << "prix total: " << bibliotheque->prixTotal() << "Dt" << endl;
return 1;
}
|
9d74ef7a3bc607ca748d56fed1f1760831e3376d | 005f6e37941b66536f6719a7bb94ab4d3d7cf418 | /src/prx_planning/prx/planning/applications/motoman_planning_application.cpp | cd0fc0411b6ad47420e0104ababcf5cc1c71bd28 | [] | no_license | warehouse-picking-automation-challenges/ru_pracsys | c56b9a873218fefb91658e08b74c4a1bc7e16628 | 786ce2e3e0d70d01c951028a90c117a0f23d0804 | refs/heads/master | 2021-05-31T05:52:33.396310 | 2016-02-07T22:34:39 | 2016-02-07T22:34:39 | 39,845,771 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 125,304 | cpp | motoman_planning_application.cpp | /**
* @file base_apc_planning_application.cpp
*
* @copyright Software License Agreement (BSD License)
* Copyright (c) 2013, Rutgers the State University of New Jersey, New Brunswick
* All Rights Reserved.
* For a full description see the file named LICENSE.
*
* Authors: Andrew Dobson, Andrew Kimmel, Athanasios Krontiris, Zakary Littlefield, Kostas Bekris
*
* Email: pracsys@googlegroups.com
*/
#include "prx/planning/communication/planning_comm.hpp"
#include "prx/planning/communication/simulation_comm.hpp"
#include "prx/planning/communication/visualization_comm.hpp"
#include "prx/planning/problem_specifications/motion_planning_specification.hpp"
#include "prx/planning/queries/motion_planning_query.hpp"
#include "prx/utilities/goals/goal.hpp"
#include "prx/utilities/goals/multiple_goal_states.hpp"
#include "prx/planning/world_model.hpp"
#include "prx/planning/modules/stopping_criteria/stopping_criteria.hpp"
#include "prx/planning/task_planners/task_planner.hpp"
#include "prx/planning/motion_planners/motion_planner.hpp"
#include "prx/planning/applications/motoman_planning_application.hpp"
#include "prx/planning/modules/path_smoothers/path_smoother.hpp"
#include "prx/utilities/definitions/sys_clock.hpp"
#include "prx/simulation/systems/obstacle.hpp"
#include "prx/simulation/sensing/sensors/point_cloud_sensor.hpp"
#include "prx/planning/task_planners/base_apc_task_planner/base_apc_task_planner.hpp"
#include "prx/utilities/statistics/statistics.hpp"
#include "prx/utilities/definitions/random.hpp"
#include "simulation/manipulator_simulator.hpp"
#include "prx/utilities/parameters/parameter_reader.hpp"
#include "prx/utilities/communication/tf_broadcaster.hpp"
#include "prx/utilities/definitions/string_manip.hpp"
#include <boost/range/adaptor/map.hpp>
#include <pluginlib/class_list_macros.h>
#include <yaml-cpp/yaml.h>
#include <boost/assign/list_of.hpp>
#include <algorithm>
#define ROBOT_SEND_COMMAND_TIMEOUT 0
#define ROBOT_AC_SERVER_TIMEOUT 5
#define LIFT_HEIGHT 0.02
#define GENERAL_IK 0
#define GRASPING_IK 1
#define LIFTING_IK 2
#define RETRACTION_IK 3
#define GRASPING_TIMEOUT 90
PLUGINLIB_EXPORT_CLASS(prx::plan::motoman_planning_application_t, prx::plan::planning_application_t)
namespace prx
{
using namespace util;
using namespace sim;
using namespace prx::packages::manipulation;
namespace plan
{
using namespace comm;
const std::string motoman_planning_application_t::dof_names[16] = {"torso_joint_b1", "arm_left_joint_1_s", "arm_left_joint_2_l", "arm_left_joint_3_e", "arm_left_joint_4_u", "arm_left_joint_5_r", "arm_left_joint_6_b", "arm_left_joint_7_t", "arm_right_joint_1_s", "arm_right_joint_2_l", "arm_right_joint_3_e", "arm_right_joint_4_u", "arm_right_joint_5_r", "arm_right_joint_6_b", "arm_right_joint_7_t", "torso_joint_b2"};
motoman_planning_application_t::motoman_planning_application_t()
{
sem_init(&semaphore, 0, 1);
_hand = "right";
_grasping = false;
_left_manipulator = NULL;
_right_manipulator = NULL;
left_IK_data_base = NULL;
left_cam_IK_data_base = NULL;
right_IK_data_base = NULL;
right_cam_IK_data_base = NULL;
enabled_robot = false;
current_state = NULL;
object_start_state = NULL;
the_shelf_pos.resize(7);
grasp_configurations.resize(1000);
}
motoman_planning_application_t::~motoman_planning_application_t()
{
model->get_state_space()->free_point(multi_goal_assist);
model->get_state_space()->free_point(current_state);
for( unsigned i=0; i<candidate_IKs.size(); ++i )
model->get_state_space()->free_point( candidate_IKs[i] );
for( unsigned i=0; i<lifting_IKs.size(); ++i )
model->get_state_space()->free_point( lifting_IKs[i] );
for( unsigned i=0; i<retraction_IKs.size(); ++i )
model->get_state_space()->free_point( retraction_IKs[i] );
if( left_IK_data_base != NULL )
delete left_IK_data_base;
if( right_IK_data_base != NULL )
delete right_IK_data_base;
if( left_cam_IK_data_base != NULL )
delete left_cam_IK_data_base;
if( right_cam_IK_data_base != NULL )
delete right_cam_IK_data_base;
sem_destroy(&semaphore);
}
void motoman_planning_application_t::init(const parameter_reader_t* reader)
{
load_roadmaps = reader->get_attribute_as<bool>("load_roadmaps", true);
has_roadmaps = false;
if( load_roadmaps )
{
PRX_PRINT("This application will load roadmaps precomputed offline", PRX_TEXT_BLUE);
}
else
{
PRX_PRINT("This application will need to generate roadmaps online", PRX_TEXT_BLUE);
}
enabled_robot = false;
std::string left = "left_";
std::string right = "right_";
std::string plugin_type_name = reader->get_attribute("plan_to_vis_comm", "visualization_comm");
vis_comm = plan_base_communication_t::get_loader().createUnmanagedInstance("prx_planning/" + plugin_type_name);
vis_comm->link_application(this);
left_grasped_planner = "left_prm_grasp";
left_ungrasped_planner = "left_prm";
right_grasped_planner = "right_prm_grasp";
right_ungrasped_planner = "right_prm";
simulation::update_all_configs = false;
//debug and communication flags
debug = false;
visualize = false;
simulate = false;
// initialize world model
model = new world_model_t();
reader->initialize(model, "world_model");
model->use_context("full_space");
std::vector< plant_t* > all_plants;
model->get_system_graph().get_plants(all_plants);
context_flags true_flags(true, true);
context_flags active_flags(true, false);
context_flags inactive_flags(false, false);
util::hash_t<std::string, context_flags> mappings;
foreach(plant_t* plant, all_plants)
{
if( _left_manipulator == NULL && dynamic_cast<manipulator_plant_t*>(plant) != NULL && plant->get_pathname().find(left) != std::string::npos )
_left_manipulator = static_cast<manipulator_plant_t*>(plant);
if( _right_manipulator == NULL && dynamic_cast<manipulator_plant_t*>(plant) != NULL && plant->get_pathname().find(right) != std::string::npos )
_right_manipulator = static_cast<manipulator_plant_t*>(plant);
}
left_manip_space = _left_manipulator->get_state_space();
right_manip_space = _right_manipulator->get_state_space();
geom_map_t geom_map;
model->get_simulator()->update_phys_geoms(geom_map);
model->get_simulator()->update_obstacle_geoms(geom_map);
tf_broadcasting();
foreach(std::string name, geom_map | boost::adaptors::map_keys)
{
vis_comm->add_marker_to_array(geom_map[name], name);
}
vis_comm->publish_markers();
tf_broadcasting();
//left arm contexts
mappings[_left_manipulator->get_pathname()] = true_flags;
foreach(plant_t* plant, all_plants)
{
if( dynamic_cast<movable_body_plant_t*>(plant) != NULL )
{
mappings[plant->get_pathname()] = active_flags;
std::string context_name = left + split_path(plant->get_pathname()).second;
// PRX_INFO_S("Setting up context for " << context_name);
object_contexts.push_back(context_name);
model->create_new_planning_context(context_name, mappings, inactive_flags);
mappings[plant->get_pathname()] = inactive_flags;
}
}
//right arm contexts
mappings.clear();
mappings[_right_manipulator->get_pathname()] = true_flags;
foreach(plant_t* plant, all_plants)
{
if( dynamic_cast<movable_body_plant_t*>(plant) != NULL )
{
mappings[plant->get_pathname()] = active_flags;
std::string context_name = right + split_path(plant->get_pathname()).second;
std::string obj_name = split_path(plant->get_pathname()).second;
// PRX_PRINT("Set up the object mapping for: " << obj_name, PRX_TEXT_GREEN);
object_list[ obj_name ] = system_ptr_t( plant );
// PRX_INFO_S("Setting up context for " << context_name);
object_contexts.push_back(context_name);
model->create_new_planning_context(context_name, mappings, inactive_flags);
mappings[plant->get_pathname()] = inactive_flags;
}
}
obstacle_list = model->get_obstacles();
// ((comm::visualization_comm_t*)comm::vis_comm)->to_config = boost::bind(&world_model_t::get_configs, model, _1, _2);
root_task = (task_planner_t*)reader->create_from_loader<planner_t > ("task_planner", "prx_planning");
root_task->set_pathname("task_planner");
parameters::initialize(root_task, reader, "task_planner", NULL, "");
// reader->initialize(*root_task,"task_planner");
root_task->link_world_model(model);
if( reader->has_attribute("problems") )
{
parameter_reader_t::reader_map_t problem_reader = reader->get_map("problems");
const parameter_reader_t* specification_template_reader = NULL;
std::string specification_template_name;
const parameter_reader_t* query_template_reader = NULL;
std::string query_template_name;
foreach(const parameter_reader_t::reader_map_t::value_type problem_item, problem_reader)
{
if( problem_item.second->has_attribute("specification/template") )
{
specification_template_name = problem_item.second->get_attribute("specification/template");
specification_template_reader = new parameter_reader_t(ros::this_node::getName() + "/" + specification_template_name);
}
specification_t* specification = parameters::initialize_from_loader<specification_t>("prx_planning", problem_item.second, "specification", specification_template_reader, "");
if( specification_template_reader != NULL )
{
delete specification_template_reader;
specification_template_reader = NULL;
}
root_specifications.push_back(specification);
if( problem_item.second->has_attribute("query") )
{
PRX_DEBUG_COLOR("Found query with specification", PRX_TEXT_BLUE);
if( problem_item.second->has_attribute("query/template") )
{
query_template_name = problem_item.second->get_attribute("query/template");
query_template_reader = new parameter_reader_t(ros::this_node::getName() + "/" + query_template_name);
}
query_t* query = parameters::initialize_from_loader<query_t>("prx_planning", problem_item.second, "query", query_template_reader, "");
root_queries.push_back(query);
task_query = dynamic_cast<base_apc_task_query_t*>(query);
query_t* query_2 = parameters::initialize_from_loader<query_t>("prx_planning", problem_item.second, "query", query_template_reader, "");
lifting_task_query = dynamic_cast<base_apc_task_query_t*>(query_2);
query_t* query_3 = parameters::initialize_from_loader<query_t>("prx_planning", problem_item.second, "query", query_template_reader, "");
retracting_task_query = dynamic_cast<base_apc_task_query_t*>(query_3);
if( query_template_reader != NULL )
{
delete query_template_reader;
query_template_reader = NULL;
}
}
else
{
PRX_FATAL_S("No intial query found in input. Please add a query");
}
}
}
else
{
PRX_FATAL_S("No problem definition read from input!");
}
stop_updating_state();
sub_joint = n.subscribe("/joint_states", 1, &motoman_planning_application_t::get_state_callback, this);
vis_array_pub = n.advertise<visualization_msgs::Marker>("visualization_marker", 0);
cancel_publisher = n.advertise<actionlib_msgs::GoalID>("/joint_trajectory_action/cancel", 1);
current_state = model->get_state_space()->alloc_point();
multi_goal_assist = model->get_state_space()->alloc_point();
unsigned num_ik_seeds = reader->get_attribute_as<double>("num_ik_seeds", 70);
for( unsigned i=0; i<num_ik_seeds; ++i )
{
candidate_IKs.push_back( model->get_state_space()->alloc_point() );
lifting_IKs.push_back( model->get_state_space()->alloc_point() );
retraction_IKs.push_back( model->get_state_space()->alloc_point() );
}
IK_seeds.resize( num_ik_seeds );
for( int i=0; i<IK_seeds.size(); i++ )
IK_seeds[i] = NULL;
load_grasp_data( reader );
store_IK_data_base = reader->get_attribute_as<bool>("store_IK_data_base", false);
load_IK_data_base = reader->get_attribute_as<bool>("load_IK_data_base", false);
store_trajectory_data = reader->get_attribute_as<bool>("store_trajectory_data_base", false);
load_trajectory_data = reader->get_attribute_as<bool>("load_trajectory_data_base", false);
visualize_grasps = reader->get_attribute_as<bool>("visualize_grasps", false);
if( store_trajectory_data )
{
PRX_PRINT("Application will STORE trajectory information.", PRX_TEXT_CYAN);
}
if( load_trajectory_data )
{
PRX_PRINT("Application will LOAD trajectory information.", PRX_TEXT_GREEN);
}
left_IK_data_base = NULL;
right_IK_data_base = NULL;
if(store_IK_data_base || load_IK_data_base)
{
if(reader->has_attribute("left_IK_data_base"))
{
left_IK_data_base = new IK_data_base_t();
left_IK_data_base->init(reader->get_child("left_IK_data_base").get());
}
else
PRX_FATAL_S("You requested to store/load the IK data bases but you have not initialize the left data base!");
left_IK_file = reader->get_attribute("left_IK_file", "left_IK_data_base.txt");
if(reader->has_attribute("left_cam_IK_data_base"))
{
left_cam_IK_data_base = new IK_data_base_t();
left_cam_IK_data_base->init(reader->get_child("left_cam_IK_data_base").get());
}
else
PRX_FATAL_S("You requested to store/load the IK data bases but you have not initialize the left camera data base!");
if(reader->has_attribute("right_IK_data_base"))
{
right_IK_data_base = new IK_data_base_t();
right_IK_data_base->init(reader->get_child("right_IK_data_base").get());
}
else
PRX_FATAL_S("You requested to store/load the IK data bases but you have not initialize the right data base!");
right_IK_file = reader->get_attribute("right_IK_file", "right_IK_data_base.txt");
if(reader->has_attribute("right_cam_IK_data_base"))
{
right_cam_IK_data_base = new IK_data_base_t();
right_cam_IK_data_base->init(reader->get_child("right_cam_IK_data_base").get());
}
else
PRX_FATAL_S("You requested to store/load the IK data bases but you have not initialize the right camera data base!");
}
task_query->get_goal()->link_space( model->get_state_space() );
lifting_task_query->get_goal()->link_space( model->get_state_space() );
retracting_task_query->get_goal()->link_space( model->get_state_space() );
if( load_trajectory_data )
{
PRX_PRINT("\n\n LOADING TRAJECTORY DATA \n\n", PRX_TEXT_CYAN);
load_trajectories();
}
if( load_roadmaps && !has_roadmaps )
{
PRX_PRINT("\n\n\n COMPUTE ROADMAPS \n\n\n", PRX_TEXT_LIGHTGRAY);
compute_roadmaps();
}
}
void motoman_planning_application_t::execute()
{
start_updating_state();
for( int i = 0; i < 15; i++ )
index_map[ dof_names[i] ] = i;
// get the execution things
for( int i = 1; i < 15; i++ )
motoman_command.trajectory.joint_names.push_back(dof_names[i]);
motoman_command.trajectory.joint_names.push_back(dof_names[0]);
motoman_command.trajectory.joint_names.push_back(dof_names[15]);
unigripper_command.trajectory.joint_names.push_back("head_hinge");
model->use_context(_hand + "_manipulator");
// setting up callbacks
clear_objects_service = n.advertiseService("clear_objects", &motoman_planning_application_t::clear_objects_callback, this);
clear_object_service = n.advertiseService("clear_object", &motoman_planning_application_t::clear_object_callback, this);
place_object_service = n.advertiseService("place_object", &motoman_planning_application_t::place_object_callback, this);
grasp_service = n.advertiseService("grasp", &motoman_planning_application_t::grasp_callback, this);
release_service = n.advertiseService("release", &motoman_planning_application_t::release_callback, this);
validate_end_effector_service = n.advertiseService("validate_end_effector", &motoman_planning_application_t::validate_end_effector_callback, this);
compute_grasp_service = n.advertiseService("compute_grasp", &motoman_planning_application_t::compute_grasp_callback, this);
// boost::bind(&distance_function_t::distance, this, _1, _2);
compute_plan_server = new CServer(n, "compute_plan", boost::bind(&motoman_planning_application_t::compute_plan_server_callback, this, _1), false);
execute_plan_server = new EServer(n, "execute_plan", boost::bind(&motoman_planning_application_t::execute_plan_server_callback, this, _1), false);
compute_plan_server->start();
execute_plan_server->start();
ac = new actionlib::SimpleActionClient<control_msgs::FollowJointTrajectoryAction>("joint_trajectory_action", false);
ac_uni = new actionlib::SimpleActionClient<control_msgs::FollowJointTrajectoryAction>("unigripper/unigripper_joint_trajectory_action", false);
PRX_PRINT("\n\n prx_planning is ready to receive queries. \n\n ", PRX_TEXT_GREEN);
}
void motoman_planning_application_t::get_state_callback(const sensor_msgs::JointState& stateMsg)
{
int value;
sem_getvalue(&semaphore, &value);
if( value==0 || !has_roadmaps )
return;
stop_updating_state();
sensor_msgs::JointState start_state = stateMsg;
for( unsigned i = 0; i < start_state.name.size(); i++ )
{
if( index_map.find(start_state.name[i]) != index_map.end() )
current_state->at(index_map[start_state.name[i]]) = start_state.position[i];
else if( start_state.name[i] == "head_hinge" )
current_state->at(15) = start_state.position[i];
}
left_manip_space->copy_from_point(current_state);
right_manip_space->copy_from_point(current_state);
if( _grasping )
{
current_state->at(16) = 1;
((manipulation_simulator_t*)model->get_simulator())->update_ground_truth();
}
else
current_state->at(16) = 0;
start_updating_state();
tf_broadcasting();
}
void motoman_planning_application_t::compute_plan_server_callback(const prx_planning::compute_planGoalConstPtr& req)
{
// PRX_INFO_S( "===== COMPUTE PLAN @ state ======================" );
//if( _grasping )
//PRX_PRINT( "object state at compute plan: " << model->get_active_space()->print_memory( 7 ), PRX_TEXT_GREEN );
if( !has_roadmaps && !load_roadmaps )
{
stop_updating_state();
compute_roadmaps();
start_updating_state();
}
if( req->dest_type == "origin" )
{
place_albertos_box( true );
((base_apc_task_planner_t*)(this->root_task))->restart_planners();
}
sleep(1);
// check to see if the planning context needs to be changed depending on the arm
check_for_context_switch(req->arm);
// setting up the goal of the query
sensor_msgs::JointState end_state = req->end_state;
((base_apc_task_query_t*)task_query)->clear_goal();
((multiple_goal_states_t*)task_query->get_goal())->add_goal_state( current_state );
for( unsigned i = 0; i < end_state.name.size(); i++ )
{
if( index_map.find(end_state.name[i]) != index_map.end() )
task_query->get_goal()->get_goal_points()[0]->at(index_map[end_state.name[i]]) = end_state.position[i];
else if( end_state.name[i] == "head_hinge" )
task_query->get_goal()->get_goal_points()[0]->at(15) = end_state.position[i];
}
// PRX_PRINT( " Initial state :: " << model->get_state_space()->print_point( current_state, 3 ) , PRX_TEXT_LIGHTGRAY );
// PRX_PRINT( " Goal state :: " << model->get_state_space()->print_point( task_query->get_goal()->get_goal_points()[0], 3 ), PRX_TEXT_LIGHTGRAY );
// computing the actual path
stop_updating_state();
bool success = find_path_internal( current_state, task_query->get_goal()->get_goal_points()[0], GENERAL_IK );
start_updating_state();
// PRX_INFO_S( "Do we have a path? " << success );
if( success )
{
// PRX_INFO_S( "Success in computing plan" );
compute_plan_server->setSucceeded();
}
else
{
// PRX_INFO_S( "Failure in computing plan" );
compute_plan_server->setAborted();
}
//if( _grasping )
// PRX_PRINT( "object state at compute plan's end: " << model->get_active_space()->print_memory( 3 ), PRX_TEXT_GREEN );
}
void motoman_planning_application_t::execute_plan_server_callback(const prx_planning::execute_planGoalConstPtr& req)
{
// PRX_INFO_S( "================== EXECUTE PLAN ======================");
// PRX_PRINT( "initial state is: " << model->get_state_space()->print_point( current_state, 3 ), PRX_TEXT_GREEN );
//if( _grasping )
//PRX_PRINT( "object state at execute plan's end: " << model->get_active_space()->print_memory( 3 ), PRX_TEXT_GREEN );
//PRX_PRINT( "context name is: " << model->get_current_context(), PRX_TEXT_GREEN );
// read the speed with which the arm should move
double speed = req->speed;
if( speed < .1 || speed > 1 )
{
PRX_WARN_S("Speed multiplier for motoman execution is out of range [.1,1]. Ts ts ts ts. Setting to .2");
speed = .2;
}
// make sure the robot is enabled
if( !enabled_robot )
{
state_t* state = task_query->get_start_state();
trajectory_t traj;
traj.link_space(model->get_state_space());
traj.copy_onto_back(state);
traj.copy_onto_back(state);
communicate_trajectory(traj, speed);
}
manipulator_plant_t* manipulator = NULL;
if( _hand == "left" )
manipulator = _left_manipulator;
else
manipulator = _right_manipulator;
plan_t prop_plan;
trajectory_t compare_traj;
space_point_t* start = NULL;
space_point_t* goal = NULL;
config_t ee_config;
if(req->traj_type=="query")
{
prop_plan = task_query->plan;
compare_traj = task_query->path;
}
else if(req->traj_type=="IK")
{
prop_plan = IK_plan;
compare_traj = IK_traj;
if( compare_traj.size() > 0 )
{
//PRX_PRINT("Setting start/goal pair for IK type.", PRX_TEXT_MAGENTA);
start = compare_traj.at( 0 );
goal = compare_traj.back();
model->push_state( goal );
manipulator->get_end_effector_configuration( ee_config );
//PRX_PRINT("The end effector is: " << ee_config, PRX_TEXT_MAGENTA);
}
}
else if(req->traj_type=="grasping")
{
prop_plan = grasping_plan;
compare_traj = grasping_traj;
}
else if(req->traj_type=="lifting")
{
prop_plan = lifting_plan;
compare_traj = lifting_traj;
}
else if(req->traj_type=="retracting")
{
prop_plan = retracting_plan;
compare_traj = retracting_traj;
}
/*
trajectory_t prop_traj(model->get_state_space());
// propagate the plan to rediscover the trajectory to be followed
stop_updating_state();
//PRX_INFO_S("Before propagating plan... grasping is " << _grasping );
//PRX_PRINT( "The object before: " << model->get_active_space()->print_memory( ), PRX_TEXT_BROWN );
model->propagate_plan( current_state, prop_plan, prop_traj, true );
//PRX_PRINT( "The object after: " << model->get_active_space()->print_memory( ), PRX_TEXT_BROWN );
if(prop_traj.in_collision() || (prop_traj.size() > 1 && prop_traj.size() != compare_traj.size() ) )
{
if( prop_traj.size() != compare_traj.size() )
{
PRX_ERROR_S( "The two trajectories are of different size" );
}
if( prop_traj.in_collision() )
{
PRX_ERROR_S("The computed trajectory is in collision. Bad juju.");
}
PRX_INFO_S("Stored: \n"<<compare_traj.print());
PRX_INFO_S("Computed: \n"<<prop_traj.print());
if(!_grasping)
{
for( int i=0; i<prop_traj.size(); i++ )
{
model->push_state( prop_traj[i] );
collision_list_t* list = model->get_colliding_bodies();
if( list->size() > 0 )
{
PRX_WARN_S("failed index is: " << i );
foreach(collision_pair_t pair, list->get_body_pairs())
{
PRX_WARN_S(pair.first << " " << pair.second);
}
PRX_WARN_S("");
config_t ee_pose;
manipulator->get_end_effector_configuration( ee_pose );
PRX_WARN_S("EE config: " << ee_config );
}
}
}
execute_plan_server->setAborted();
start_updating_state();
if( prop_traj.size() != compare_traj.size() )
{
PRX_FATAL_S( "The two trajectories are of different size" );
}
if( prop_traj.in_collision() )
{
PRX_FATAL_S("The computed trajectory is in collision. Bad juju.");
}
return;
}
//PRX_PRINT( "The object after: " << model->get_active_space()->print_memory( 3 ), PRX_TEXT_BROWN );
//PRX_INFO_S("After propagating plan... of length " << task_query->plan.length() );
start_updating_state();
// if there is a plan to execute
if( prop_plan.length() > 0 )
*/
if( compare_traj.size() > 1 )
{
// take the plan in task_query and publish to JointCommand
bool suc = communicate_trajectory(compare_traj, speed);
// PRX_PRINT("Finished communicating trajectory with success: "<<suc,PRX_TEXT_GREEN);
if( suc )
{
// if we are grasping an object, make sure we set the object to be at the end of the executed plan
sleep(1);
execute_plan_server->setSucceeded();
// Since we successfully transmitted this trajectory, store it in the database
if( store_trajectory_data && start != NULL )
{
// PRX_PRINT("Adding a trajectory to the database!", PRX_TEXT_MAGENTA);
add_trajectory_to_database( start, ee_config, compare_traj );
}
}
else
{
//DEBUG: Breaking when we fail to communicate the trajectory.
// PRX_WARN_S("Somehow got a failure back from the Robot. Previously, this would stop everything!");
execute_plan_server->setAborted();
}
}
else
execute_plan_server->setSucceeded();
//if( _grasping )
// PRX_PRINT( "object state at execute plan's end: " << model->get_active_space()->print_memory( 7 ), PRX_TEXT_GREEN );
// PRX_PRINT( "resulting state is: " << model->get_state_space()->print_point( current_state, 3 ), PRX_TEXT_GREEN );
}
bool motoman_planning_application_t::place_object_callback(prx_planning::place_object::Request& req, prx_planning::place_object::Response& res)
{
std::string context_name = _hand + "_" + req.object_name;
std::string obstacle_name = "simulator/obstacles/" + req.object_name;
geometry_msgs::PoseStamped pose = req.object_pose;
// If the input object is in the obstacle list, then move it to the input pose
if( obstacle_list.find(obstacle_name) != obstacle_list.end() )
{
// PRX_INFO_S("Moving " << req.object_name << " obstacle in planning node.");
config_t obs_config;
obs_config.set_position(pose.pose.position.x, pose.pose.position.y, pose.pose.position.z);
obs_config.set_orientation(pose.pose.orientation.x, pose.pose.orientation.y, pose.pose.orientation.z, pose.pose.orientation.w);
static_cast<obstacle_t*>(obstacle_list[obstacle_name].get())->update_root_configuration(obs_config);
model->get_simulator()->update_obstacles_in_collision_checker();
std::string bin_name, remaining;
boost::tie( bin_name, remaining ) = split_path_delimiter( req.object_name, '_');
if( req.object_name == "shelf" || bin_name == "bin" || bin_name =="albertos" )
{
the_shelf_pos[0] = pose.pose.position.x;
the_shelf_pos[1] = pose.pose.position.y;
the_shelf_pos[2] = pose.pose.position.z;
the_shelf_pos[3] = pose.pose.orientation.x;
the_shelf_pos[4] = pose.pose.orientation.y;
the_shelf_pos[5] = pose.pose.orientation.z;
the_shelf_pos[6] = pose.pose.orientation.w;
this->root_task->set_param("", "shelf_position", the_shelf_pos);
}
// PRX_INFO_S("Done moving " << req.object_name << " obstacle in planning node.");
}
// Otherwise, we need to activate the object and move it to the input pose
else
{
// PRX_INFO_S("Adding " << req.object_name << " to the planning node: " << pose.pose.position.x << " " << pose.pose.position.y << " " << pose.pose.position.z);
model->use_context(context_name);
if( object_start_state == NULL )
object_start_state = model->get_active_space()->alloc_point();
object_start_state->at(0) = pose.pose.position.x;
object_start_state->at(1) = pose.pose.position.y;
object_start_state->at(2) = pose.pose.position.z;
object_start_state->at(3) = pose.pose.orientation.x;
object_start_state->at(4) = pose.pose.orientation.y;
object_start_state->at(5) = pose.pose.orientation.z;
object_start_state->at(6) = pose.pose.orientation.w;
model->get_active_space()->copy_from_point(object_start_state);
sim::update_point_cloud = true;
model->update_sensing();
sim::update_point_cloud = false;
// PRX_INFO_S("Done adding " << context_name << " to the planning node: ");
}
res.success = true;
}
void motoman_planning_application_t::place_albertos_box( bool activate )
{
std::string obstacle_name = "simulator/obstacles/albertos_box";
config_t obs_config;
if( activate)
{
//PRX_PRINT( "\n\n\nThe shelf pose is: " << the_shelf_pos[0] << " " << the_shelf_pos[1] << " " <<the_shelf_pos[2] << " " <<the_shelf_pos[3] << " " <<the_shelf_pos[4] << " " <<the_shelf_pos[5] << " " <<the_shelf_pos[6] << "\n\n\n", PRX_TEXT_BROWN );
obs_config.set_position( the_shelf_pos[0], the_shelf_pos[1], the_shelf_pos[2]);
obs_config.set_orientation( the_shelf_pos[3], the_shelf_pos[4], the_shelf_pos[5], the_shelf_pos[6] );
}
else
{
obs_config.set_position( -1999, -1999, -1999 );
obs_config.set_orientation( 0, 0, 0, 1 );
}
static_cast<obstacle_t*>(obstacle_list[obstacle_name].get())->update_root_configuration(obs_config);
model->get_simulator()->update_obstacles_in_collision_checker();
}
bool motoman_planning_application_t::clear_objects_callback(prx_planning::clear_objects::Request& req, prx_planning::clear_objects::Response& res)
{
//Define a configuration far far away
config_t obs_config;
obs_config.set_position(-999, -999, -999);
obs_config.set_orientation(0, 0, 0, 1);
foreach(std::string name, obstacle_list | boost::adaptors::map_keys)
static_cast<obstacle_t*>(obstacle_list[name].get())->update_root_configuration(obs_config);
model->get_simulator()->update_obstacles_in_collision_checker();
if( _hand == "left" )
model->use_context("left_manipulator");
else
model->use_context("right_manipulator");
// tf_broadcasting();
res.success = true;
return true;
}
bool motoman_planning_application_t::clear_object_callback(prx_planning::clear_object::Request& req, prx_planning::clear_object::Response& res)
{
std::string context_name = _hand + "_" + req.object_name;
std::string obstacle_name = "simulator/obstacles/" + req.object_name;
// If the input object is in the obstacle list, then move it far far away
if( obstacle_list.find(obstacle_name) != obstacle_list.end() )
{
// PRX_INFO_S("Removing " << req.object_name << " obstacle in planning node.");
config_t obs_config;
obs_config.set_position(-999, -999, -999);
obs_config.set_orientation(0, 0, 0, 1);
static_cast<obstacle_t*>(obstacle_list[obstacle_name].get())->update_root_configuration(obs_config);
model->get_simulator()->update_obstacles_in_collision_checker();
//PRX_INFO_S("Done Removing " << req.object_name << " obstacle in planning node.");
}
// Otherwise, change the planning context so that it is not active anymore
else
{
// PRX_INFO_S("Removing " << req.object_name << " in planning node.");
std::string old_context = model->get_current_context();
if( old_context == context_name )
{
if( _hand == "left" )
model->use_context("left_manipulator");
else
model->use_context("right_manipulator");
}
std::vector<double> clear_state = boost::assign::list_of(-999)(-999)(-999)(0)(0)(0)(1);
foreach(system_ptr_t ptr, object_list | boost::adaptors::map_values)
{
ptr->get_state_space()->set_from_vector(clear_state);
}
//PRX_INFO_S("Done removing " << context_name << " in planning node.");
}
// tf_broadcasting();
res.success = true;
return true;
}
bool motoman_planning_application_t::grasp_callback(prx_planning::grasp::Request& req, prx_planning::grasp::Response& res)
{
// PRX_INFO_S( "================== GRASP CALLBACK ===== for object " << req.object_name);
model->use_context(_hand + "_" + req.object_name);
_grasping = true;
res.success = true;
stop_updating_state();
if( _grasping )
current_state->at(16) = 1;
model->push_state( current_state );
((manipulation_simulator_t*)model->get_simulator())->compute_relative_config();
start_updating_state();
//PRX_PRINT( "current object state at grasping: " << model->get_active_space()->print_memory( 3 ), PRX_TEXT_GREEN );
return true;
}
bool motoman_planning_application_t::release_callback(prx_planning::release::Request& req, prx_planning::release::Response& res)
{
// PRX_INFO_S( "================== RELEASE CALLBACK ===== " );
stop_updating_state();
model->push_state( current_state );
//PRX_PRINT( "current object state at releasing: " << model->get_active_space()->print_memory( 3 ), PRX_TEXT_GREEN );
model->use_context(_hand + "_" + "manipulator");
_grasping = false;
res.success = true;
if( _grasping )
current_state->at(16) = 0;
model->push_state( current_state );
((manipulation_simulator_t*)model->get_simulator())->compute_relative_config();
start_updating_state();
return true;
}
bool motoman_planning_application_t::validate_end_effector_callback(prx_planning::validate_end_effector::Request& req, prx_planning::validate_end_effector::Response& res)
{
// PRX_INFO_S( "================== VALIDATE END EFFECTOR ======================");
//if( _grasping )
// PRX_PRINT( "current object state at start of validation: " << model->get_active_space()->print_memory( 7 ), PRX_TEXT_GREEN );
// check to see if we need to switch contexts
check_for_context_switch(req.arm);
manipulator_plant_t* manipulator = NULL;
if( _hand == "left" )
manipulator = _left_manipulator;
else
manipulator = _right_manipulator;
manipulator->get_state_space()->copy_from_point(current_state);
// Getting the input pose into a configuration
config_t config;
geometry_msgs::PoseStamped pose = req.pose;
config.set_position(pose.pose.position.x, pose.pose.position.y, pose.pose.position.z-.01);
config.set_orientation(pose.pose.orientation.x, pose.pose.orientation.y, pose.pose.orientation.z, pose.pose.orientation.w);
// Arguments are: camera or end effector, current state, target config, returned state, reachable plan, type of IK solution
sys_clock_t zak_clock;
zak_clock.reset();
timeout_clock.reset();
stop_updating_state();
bool success = check_for_stored_trajectory( current_state, config );
if( success == false )
success = reachable_IK( req.camera, current_state, config, GENERAL_IK );
start_updating_state();
// PRX_PRINT("overall_time " << zak_clock.measure(), PRX_TEXT_BROWN );
// if successful, drop an egg
if( success )
{
std::vector<double> params;
params.push_back(.02);
geometry_t geom(PRX_SPHERE,¶ms);
vis_array_pub.publish(vis_comm->send_marker(geom, "EE_config", config));
}
// PRX_INFO_S("Valid IK: " << success);
res.success = success;
if (res.success)
{
int robot_state_size = IK_traj.back()->memory.size();
res.arm_config.position.resize(robot_state_size);
res.arm_config.name.resize(robot_state_size);
for( unsigned i = 0; i < 16; i++ )
{
res.arm_config.name[i] = dof_names[i];
res.arm_config.position[i] = IK_traj.back()->at(index_map[dof_names[i]]);
}
res.arm_config.position[16] = IK_traj.back()->at(15);
res.arm_config.name[16] = "head_hinge";
// int robot_state_size = IK_traj.back()->memory.size();
// res.arm_config.position.resize(robot_state_size);
// res.arm_config.name.resize(robot_state_size);
// for (int i = 1; i < 15; i++)
// {
// res.arm_config.position[i - 1] = IK_traj.back()->at(i);
// res.arm_config.name[i - 1] = dof_names[i];
// }
// res.arm_config.position[14] = IK_traj.back()->at(0);
// res.arm_config.position[15] = IK_traj.back()->at(0);
// res.arm_config.position[16] = IK_traj.back()->at(15);
// res.arm_config.name[14] = dof_names[0];
// res.arm_config.name[15] = dof_names[15];
// res.arm_config.name[16] = "head_hinge";
}
//if( _grasping )
// PRX_PRINT( "current object state at end of validation: " << model->get_active_space()->print_memory( 7 ), PRX_TEXT_GREEN );
place_albertos_box( false );
return true;
}
void motoman_planning_application_t::tf_broadcasting()
{
bool flag = false;
if( !dont_update_state )
{
flag = true;
stop_updating_state();
}
PRX_ASSERT(tf_broadcaster != NULL);
config_list_t config_map;
unsigned index = 0;
// Include in the config_map the configurations of all active plants and objects
model->get_simulator()->update_phys_configs(config_map, index);
// Make sure you include both manipulators (redundancy here for the active manipulator)
_left_manipulator->update_phys_configs(config_map, index);
_right_manipulator->update_phys_configs(config_map, index);
// Include all the obstacles
model->get_simulator()->update_obstacles_configs(config_map, index);
// transmit configurations
for( config_list_t::iterator iter = config_map.begin(); iter != config_map.end(); iter++ )
tf_broadcaster->queue_config(iter->second, iter->first);
tf_broadcaster->broadcast_configs();
if( flag )
start_updating_state();
}
bool motoman_planning_application_t::communicate_trajectory(trajectory_t& traj, double speed)
{
motoman_command.trajectory.points.clear();
unigripper_command.trajectory.points.clear();
//PRX_PRINT("Communicating trajectory of size: " << traj.size() << " Speed: " << speed, PRX_TEXT_BLUE);
double duration = 0;
if( traj.size() == 0 )
return true;
double sim_step = simulation::simulation_step;
if(traj.size()==2)
sim_step = .5;
foreach(state_t* state, traj)
{
//setup the JointTrajectoryPoint
trajectory_msgs::JointTrajectoryPoint point;
point.time_from_start = ros::Duration(duration);
trajectory_msgs::JointTrajectoryPoint point_uni;
point_uni.time_from_start = ros::Duration(duration);
for( unsigned i = 1; i < 15; i++ )
{
point.positions.push_back(state->memory[i]);
point.velocities.push_back(0);
point.accelerations.push_back(0);
}
point.positions.push_back(state->memory[0]);
point.velocities.push_back(0);
point.accelerations.push_back(0);
point.positions.push_back(state->memory[0]);
point.velocities.push_back(0);
point.accelerations.push_back(0);
point_uni.positions.push_back(state->memory[15]);
point_uni.velocities.push_back(0);
point_uni.accelerations.push_back(0);
duration += ((int)(1.0 / speed)) * sim_step;
motoman_command.trajectory.points.push_back(point);
unigripper_command.trajectory.points.push_back(point_uni);
}
double duration_of_timeout = (traj.size()*((int)(1.0 / speed)) * sim_step)*1.5+1.5;
motoman_command.trajectory.header.stamp = ros::Time::now();
unigripper_command.trajectory.header.stamp = ros::Time::now();
//PRX_PRINT("Motoman Command Size: " << motoman_command.trajectory.points.size() << " and Time Stamp: " << motoman_command.trajectory.header.stamp, PRX_TEXT_BLUE);
//PRX_PRINT("Wait for Server", PRX_TEXT_BLUE);
bool found_ac_server = false;
while( !found_ac_server )
found_ac_server = ac->waitForServer(ros::Duration(ROBOT_AC_SERVER_TIMEOUT)) && ac_uni->waitForServer(ros::Duration(ROBOT_AC_SERVER_TIMEOUT));
// sleep(2);
//PRX_PRINT("Ready to Send Goal", PRX_TEXT_BLUE);
ac->sendGoal(motoman_command);
ac_uni->sendGoal(unigripper_command);
bool finished_before_timeout;
finished_before_timeout = ac->waitForResult(ros::Duration(duration_of_timeout));
//PRX_PRINT("Done waiting...", PRX_TEXT_BLUE);
enabled_robot = true;
actionlib::SimpleClientGoalState state = ac->getState();
// PRX_INFO_S("AC state: " << state.toString());
// sys_clock_t clock;
// clock.reset();
// while(clock.measure()<3 && state.toString() != "SUCCEEDED")
// {
// state = ac->getState();
// PRX_INFO_S("AC state: " << state.toString());
// }
if( !finished_before_timeout )
{
actionlib_msgs::GoalID empty_msg;
cancel_publisher.publish(empty_msg);
bool ret_value = false;
// PRX_INFO_S("Time of " << duration_of_timeout << "s met. Abort.");
sleep(1);
stop_updating_state();
if(model->get_state_space()->distance(current_state,traj.back()) < .01 )
ret_value = true;
start_updating_state();
//PRX_INFO_S("AC state: " << state.toString());
return ret_value;
}
else if( state.toString() == "SUCCEEDED" )
return true;
else
return false;
}
void motoman_planning_application_t::compute_roadmaps()
{
PRX_PRINT("compute roadmaps\n",PRX_TEXT_BROWN);
if(load_IK_data_base)
{
char* w = std::getenv("PRACSYS_PATH");
std::string dir(w);
dir += ("/prx_output/IK_data_bases/");
// LEFT
std::string file = dir + left_IK_file;
PRX_PRINT("Load left IK data base from the file: " << file, PRX_TEXT_CYAN);
std::ifstream fin_left;
fin_left.open(file.c_str());
if(!fin_left.is_open())
PRX_FATAL_S("Could not open the file : " << file);
left_IK_data_base->deserialize(fin_left, _left_manipulator->get_state_space());
fin_left.close();
fin_left.clear();
file = dir + "left_camera.database";
fin_left.open(file.c_str());
if(!fin_left.is_open())
PRX_FATAL_S("Could not open the file : " << file);
left_cam_IK_data_base->deserialize(fin_left, _left_manipulator->get_state_space());
// RIGHT
file = dir + right_IK_file;
PRX_PRINT("Load right IK data base from the file: " << file, PRX_TEXT_CYAN);
std::ifstream fin_right;
fin_right.open(file.c_str());
if(!fin_right.is_open())
PRX_FATAL_S("Could not open the file : " << file);
right_IK_data_base->deserialize(fin_right, _right_manipulator->get_state_space());
fin_right.close();
fin_right.clear();
file = dir + "right_camera.database";
fin_right.open(file.c_str());
if(!fin_right.is_open())
PRX_FATAL_S("Could not open the file : " << file);
right_cam_IK_data_base->deserialize(fin_right, _right_manipulator->get_state_space());
}
std::string old_context = model->get_current_context();
this->root_task->link_specification(root_specifications[0]);
dynamic_cast<base_apc_task_planner_t*>(this->root_task)->link_manipulators(_left_manipulator, _right_manipulator);
dynamic_cast<base_apc_task_planner_t*>(this->root_task)->link_IK_data_base(left_IK_data_base, right_IK_data_base, left_cam_IK_data_base, right_IK_data_base);
this->root_task->setup();
if( load_roadmaps )
{
model->use_context("left_manipulator");
((base_apc_task_planner_t*)root_task)->deserialize("left_prm");
((base_apc_task_planner_t*)root_task)->special_deserialize("left_prm_grasp");
model->use_context("right_manipulator");
((base_apc_task_planner_t*)root_task)->deserialize("right_prm");
((base_apc_task_planner_t*)root_task)->special_deserialize("right_prm_grasp");
}
else
{
this->root_task->execute();
place_albertos_box( true );
((base_apc_task_planner_t*)(this->root_task))->special_serialize();
place_albertos_box( false );
}
if( store_IK_data_base )
{
//Clear out any previous information we have
left_IK_data_base->clear();
right_IK_data_base->clear();
left_cam_IK_data_base->clear();
right_cam_IK_data_base->clear();
PRX_PRINT("Going to store IK data bases", PRX_TEXT_CYAN);
dynamic_cast<base_apc_task_planner_t*>(this->root_task)->generate_IK_data_base(*left_IK_data_base, *right_IK_data_base, *left_cam_IK_data_base, *right_cam_IK_data_base);
char* w = std::getenv("PRACSYS_PATH");
std::string dir(w);
dir += ("/prx_output/");
boost::filesystem::path output_dir(dir);
if( !boost::filesystem::exists(output_dir) )
{
boost::filesystem::create_directory(output_dir);
}
dir += ("IK_data_bases/");
boost::filesystem::path output_dir2(dir);
if( !boost::filesystem::exists(output_dir2) )
{
boost::filesystem::create_directory(output_dir2);
}
// LEFT
std::string file = dir + left_IK_file;
PRX_PRINT("Store left IK data base at the file: " << file, PRX_TEXT_CYAN);
std::ofstream fout_left;
fout_left.open(file.c_str());
if(!fout_left.is_open())
PRX_FATAL_S("Could not open the file : " << file);
left_IK_data_base->serialize(fout_left, _left_manipulator->get_state_space(), 4);
fout_left.close();
fout_left.clear();
file = dir + "left_camera.database";
fout_left.open(file.c_str());
if(!fout_left.is_open())
PRX_FATAL_S("Could not open the file : " << file);
left_cam_IK_data_base->serialize(fout_left, _left_manipulator->get_state_space(), 4);
// RIGHT
file = dir + right_IK_file;
PRX_PRINT("Store right IK data base at the file: " << file, PRX_TEXT_CYAN);
std::ofstream fout_right;
fout_right.open(file.c_str());
if(!fout_right.is_open())
PRX_FATAL_S("Could not open the file : " << file);
right_IK_data_base->serialize(fout_right, _right_manipulator->get_state_space(), 4);
fout_right.close();
fout_right.clear();
file = dir + "right_camera.database";
fout_right.open(file.c_str());
if(!fout_right.is_open())
PRX_FATAL_S("Could not open the file : " << file);
right_cam_IK_data_base->serialize(fout_right, _right_manipulator->get_state_space(), 4);
}
if( !load_roadmaps )
PRX_FATAL_S("I can now exit safely");
this->root_task->link_query(retracting_task_query);
this->root_task->link_query(lifting_task_query);
this->root_task->link_query(task_query);
// PRX_PRINT("Root Task statistics: " << this->root_task->get_statistics()->get_statistics(), PRX_TEXT_LIGHTGRAY);
has_roadmaps = true;
model->use_context(old_context);
}
bool motoman_planning_application_t::check_for_stored_trajectory( state_t* source_state, config_t ee_config )
{
//Let's try using the trajectory databases here
if( _hand == "left" && left_trajectories.size() > 0 )
{
// PRX_PRINT("\nLooking at left-hand trajectory database.\n", PRX_TEXT_CYAN);
bool found_traj = false;
// PRX_PRINT("Searching for the following::: ", PRX_TEXT_CYAN);
// PRX_PRINT("State : " << model->get_state_space()->print_point( source_state, 6 ), PRX_TEXT_LIGHTGRAY );
// PRX_PRINT("Config: " << ee_config, PRX_TEXT_LIGHTGRAY );
//Search for the goal we are trying to reach
for( unsigned i=0; i<left_trajectories.size() && !found_traj; ++i )
{
// PRX_PRINT("Entry: " << i, PRX_TEXT_BROWN);
// PRX_PRINT("State : " << model->get_state_space()->print_point( left_trajectories[i].start, 6 ), PRX_TEXT_LIGHTGRAY );
// PRX_PRINT("Config: " << left_trajectories[i].end_configuration, PRX_TEXT_LIGHTGRAY );
//If the goal is the same and we're starting from the correct state
if( left_trajectories[i].end_configuration.is_approximate_equal( ee_config ) &&
model->get_state_space()->equal_points( left_trajectories[i].start, source_state, .001) )
{
found_traj = true;
IK_traj = left_trajectories[i].trajectory;
IK_plan.clear();
}
// else
// {
// PRX_PRINT( "Trajectory end configuration: " << left_trajectories[i].end_configuration, PRX_TEXT_GREEN );
// PRX_PRINT( "End-Effector Config: " << ee_config, PRX_TEXT_CYAN );
// PRX_PRINT( "------: "<<model->get_state_space()->distance( left_trajectories[i].start, source_state), PRX_TEXT_LIGHTGRAY );
// }
}
//If we did find a trajectory in the database, report success
if( found_traj )
{
// PRX_PRINT("\n\n\n ======= Using a trajectory from the left arm database! ===== \n\n", PRX_TEXT_GREEN);
return true;
}
else
{
// PRX_FATAL_S("Unable to find trajectory in left arm database!");
// PRX_PRINT("Unable to find trajectory in left arm database!", PRX_TEXT_RED);
return false;
}
}
else if( _hand == "right" && right_trajectories.size() > 0 )
{
// PRX_PRINT("\nLooking at right-hand trajectory database.\n", PRX_TEXT_CYAN);
bool found_traj = false;
//Search for the goal we are trying to reach
for( unsigned i=0; i<right_trajectories.size() && !found_traj; ++i )
{
//If the goal is the same and we're starting from the correct state
if( right_trajectories[i].end_configuration.is_approximate_equal( ee_config ) &&
model->get_state_space()->equal_points( right_trajectories[i].start, source_state,.001 ) )
{
found_traj = true;
IK_traj = right_trajectories[i].trajectory;
IK_plan.clear();
}
// else
// {
// PRX_INFO_S( right_trajectories[i].end_configuration );
// PRX_INFO_S( ee_config );
// PRX_INFO_S( "------: "<<model->get_state_space()->distance( right_trajectories[i].start, source_state));
// }
}
//If we did find a trajectory in the database, report success
if( found_traj )
{
// PRX_PRINT("\n\n\n ======= Using a trajectory from the right arm database! ===== \n\n", PRX_TEXT_GREEN);
return true;
}
else
{
// PRX_FATAL_S("Unable to find trajectory in right arm database!");
// PRX_PRINT("Unable to find trajectory in right arm database!", PRX_TEXT_RED);
return false;
}
}
return false;
}
void motoman_planning_application_t::load_trajectories()
{
// LEFT TRAJECTORIES
char* w = std::getenv("PRACSYS_PATH");
std::string dir(w);
dir += ("/prx_output/");
//We need to explicily load both, so try both explicitly
std::string file = dir + "trajectories_left.database";
std::ifstream traj_in;
traj_in.open( file.c_str() );
if( !traj_in.is_open() )
{
PRX_FATAL_S( "Left trajectory file failed to open!" );
}
//We need something more principled here....
for( unsigned i=0; i<48; ++i )
{
//Create a new thingermajigger in the trajectory database
left_trajectories.push_back( trajectory_db_entry() );
//First, deserialize the start point
left_trajectories.back().start = model->get_state_space()->deserialize_point( traj_in );
// PRX_PRINT("STATE: " << model->get_state_space()->print_point( left_trajectories.back().start, 4 ), PRX_TEXT_BLUE );
//Then, we get the end configuration
double x, y, z, w;
char junk;
traj_in >> x >> y >> z;
left_trajectories.back().end_configuration.set_position( x, y, z );
traj_in >> x >> y >> z >> w;
left_trajectories.back().end_configuration.set_xyzw_orientation( x, y, z, w );
// PRX_PRINT("Configuration: " << left_trajectories.back().end_configuration, PRX_TEXT_LIGHTGRAY);
//Finally, get the trajectory
left_trajectories.back().trajectory.link_space(_left_manipulator->get_state_space());
unsigned num_traj_points;
traj_in >> num_traj_points;
space_point_t* state;
// PRX_PRINT("Trajectory: " << num_traj_points, PRX_TEXT_BLUE);
for( unsigned k=0; k<num_traj_points; ++k )
{
state = model->get_state_space()->deserialize_point( traj_in );
// PRX_PRINT(":: " << model->get_state_space()->print_point( state, 6 ), PRX_TEXT_LIGHTGRAY );
left_trajectories.back().trajectory.copy_onto_back( state );
model->get_state_space()->free_point( state );
}
}
traj_in.close();
// PRX_PRINT("Read in " << left_trajectories.size() << " trajectories for the left arm", PRX_TEXT_CYAN);
// RIGHT TRAJECTORIES
//We need to explicily load both, so try both explicitly
file = dir + "trajectories_right.database";
traj_in.open( file.c_str() );
if( !traj_in.is_open() )
{
PRX_FATAL_S( "Right trajectory file failed to open!" );
}
// RIGHT ARMs
//We need something more principled here....
for( unsigned i=0; i<48; ++i )
{
//Create a new thingermajigger in the trajectory database
right_trajectories.push_back( trajectory_db_entry() );
//First, deserialize the start point
right_trajectories.back().start = model->get_state_space()->deserialize_point( traj_in );
// PRX_PRINT("STATE: " << model->get_state_space()->print_point( right_trajectories.back().start, 4 ), PRX_TEXT_BLUE );
//Then, we get the end configuration
double x, y, z, w;
char junk;
traj_in >> x >> y >> z;
right_trajectories.back().end_configuration.set_position( x, y, z );
traj_in >> x >> y >> z >> w;
right_trajectories.back().end_configuration.set_xyzw_orientation( x, y, z, w );
// PRX_PRINT("Configuration: " << right_trajectories.back().end_configuration, PRX_TEXT_LIGHTGRAY);
//Finally, get the trajectory
right_trajectories.back().trajectory.link_space(_right_manipulator->get_state_space());
unsigned num_traj_points;
traj_in >> num_traj_points;
space_point_t* state;
// PRX_PRINT("Trajectory: " << num_traj_points, PRX_TEXT_BLUE);
for( unsigned k=0; k<num_traj_points; ++k )
{
state = model->get_state_space()->deserialize_point( traj_in );
// PRX_PRINT(":: " << model->get_state_space()->print_point( state, 6 ), PRX_TEXT_LIGHTGRAY );
right_trajectories.back().trajectory.copy_onto_back( state );
model->get_state_space()->free_point( state );
}
}
traj_in.close();
// PRX_PRINT("Read in " << right_trajectories.size() << " trajectories for the right arm", PRX_TEXT_CYAN);
}
void motoman_planning_application_t::init_object_geometry(std::string object_name)
{
geom_map_t geom_map;
config_list_t configs;
unsigned int count = 0;
model->get_simulator()->update_phys_geoms(geom_map);
model->get_simulator()->update_phys_configs(configs, count);
unsigned found_index = 0;
std::string system_name = "simulator/" + object_name + "/body";
for( unsigned i = 0; i < count; i++ )
{
if( configs[i].first == system_name )
{
found_index = i;
break;
}
}
vis_array_pub.publish(vis_comm->send_marker(geom_map[system_name], system_name, configs[found_index].second));
}
void motoman_planning_application_t::check_for_context_switch(std::string the_arm)
{
if( _hand != the_arm )
{
std::string context = model->get_current_context();
std::string::size_type i = context.find(_hand);
if( i != std::string::npos )
context.erase(i, _hand.length());
_hand = the_arm;
model->use_context(_hand + context);
}
//PRX_PRINT( "I am now operating for arm : " << the_arm, PRX_TEXT_BROWN );
}
void operator >> (const YAML::Node& node, std::vector<double>& config)
{
config.resize(7);
config[0] = node[0].as<double>();
config[1] = node[1].as<double>();
config[2] = node[2].as<double>();
config[3] = node[3].as<double>();
config[4] = node[4].as<double>();
config[5] = node[5].as<double>();
config[6] = node[6].as<double>();
}
void operator >> (const YAML::Node& node, config_t& config)
{
std::vector<double> vec;
node["grasp"] >> vec;
config.set_position(vec[0],vec[1],vec[2]);
config.set_xyzw_orientation(vec[3],vec[4],vec[5],vec[6]);
}
void motoman_planning_application_t::load_grasp_data(const parameter_reader_t* reader)
{
PRX_PRINT("Loading Grasp Data in the Motoman Application", PRX_TEXT_MAGENTA);
//Need to read in the UniGripper grasp data
if( reader->has_attribute("unigripper_grasps") )
{
parameter_reader_t::reader_map_t uni_grasp_reader = reader->get_map("unigripper_grasps");
foreach(const parameter_reader_t::reader_map_t::value_type item, uni_grasp_reader)
{
std::string object_name = item.first;
char* w = std::getenv("PRACSYS_PATH");
std::string dir(w);
dir += ("/../grasp_data/Unigripper/")+object_name+".yaml";
std::ifstream fin(dir.c_str());
YAML::Node doc;
doc = YAML::Load(dir);
for(unsigned i=0;i<doc.size();i++)
{
config_t config;
doc[i] >> config;
left_grasps[ object_name ].push_back( std::pair<config_t,int>(config,1) );
}
fin.close();
PRX_PRINT("Read [" << left_grasps[object_name].size() << "] UniGripper Grasps for object: " << object_name, PRX_TEXT_CYAN);
}
}
else
{
PRX_WARN_S("No grasp data provided for the UniGripper: cannot grasp with the left hand!");
}
//Then, read in the robotiq grasp data
if( reader->has_attribute("robotiq_grasps") )
{
using_robotiq_hand = true;
parameter_reader_t::reader_map_t robo_grasp_reader = reader->get_map("robotiq_grasps");
foreach(const parameter_reader_t::reader_map_t::value_type item, robo_grasp_reader)
{
std::string object_name = item.first;
char* w = std::getenv("PRACSYS_PATH");
std::string dir(w);
dir += ("/../grasp_data/Robotiq/")+object_name+".yaml";
std::ifstream fin(dir.c_str());
YAML::Node doc;
doc = YAML::Load(dir);
for(unsigned i=0;i<doc.size();i++)
{
config_t config;
doc[i] >> config;
right_grasps[ object_name ].push_back( std::pair<config_t,int>(config,1) );
}
fin.close();
PRX_PRINT("Read [" << right_grasps[object_name].size() << "] Robotiq Grasps for object: " << object_name, PRX_TEXT_LIGHTGRAY);
}
}
std::vector< std::string > grasp_types;
grasp_types.push_back("full");
grasp_types.push_back("pinch");
grasp_types.push_back("tips");
//Then, read in the ReFlex grasp data
if( reader->has_attribute("reflex_grasps") )
{
using_robotiq_hand = false;
parameter_reader_t::reader_map_t ref_grasp_reader = reader->get_map("reflex_grasps");
foreach(const parameter_reader_t::reader_map_t::value_type item, ref_grasp_reader)
{
std::string object_name = item.first;
//Alright, now we have to read in all of these different files
for( unsigned k=0; k<grasp_types.size(); ++k )
{
char* w = std::getenv("PRACSYS_PATH");
std::string dir(w);
dir += ("/../grasp_data/Reflex/")+object_name+("_")+grasp_types[k]+".yaml";
std::ifstream fin(dir.c_str());
if( fin.good() )
{
PRX_PRINT("Reading in information from file: " << dir, PRX_TEXT_LIGHTGRAY)
YAML::Node doc;
doc = YAML::Load(dir);
for(unsigned i=0; i<doc.size(); i++)
{
config_t config;
doc[i] >> config;
right_grasps[ object_name ].push_back( std::pair<config_t,int>(config, k+1) );
}
}
fin.close();
}
PRX_PRINT("Read [" << right_grasps[object_name].size() << "] Reflex Grasps for object: " << object_name, PRX_TEXT_CYAN);
}
}
}
bool motoman_planning_application_t::find_grasp_for_object( )
{
// PRX_PRINT( "================== FIND GRASP ===== for object: " << object_name << " and arm " << _hand, PRX_TEXT_BROWN );
bool object_in_collision = model->get_simulator()->in_collision();
if(object_in_collision)
return false;
// Find the pose of the object pose
config_t object_pose;
sim::system_ptr_t object = object_list[object_name];
movable_body_plant_t* cast_object = dynamic_cast< movable_body_plant_t* >( object.get() );
if( cast_object == NULL )
return false;
cast_object->get_configuration( object_pose );
//Get the relative orientations first
std::vector< std::pair<config_t, int > >* config_pointer = NULL;
if( _hand == "left" )
config_pointer = &( left_grasps[ object_name ] );
else
config_pointer = &(right_grasps[ object_name ]);
PRX_ASSERT( config_pointer != NULL );
const std::vector< std::pair<config_t, int > >& relative_configurations = *config_pointer;
//PRX_PRINT("Object has: [" << relative_configurations.size() << "] possible grasps.", PRX_TEXT_CYAN);
config_t right_hand_config;
config_t right_hand_pinch_config;
if( using_robotiq_hand )
{
//Robotiq Configuration
right_hand_config.set_position( 0, 0.14, 0 );
right_hand_config.set_orientation( 0.5, -0.5, -0.5, -0.5 );
}
else
{
//ReFlex Configuration
right_hand_config.set_position( 0.01, 0, 0.1295 );
right_hand_config.set_orientation( 0, 0, 0, 1 );
}
//ReFlex Configuration
right_hand_pinch_config.set_position( 0.01, 0, 0.14 );
right_hand_pinch_config.set_orientation( 0, 0, 0, 1 );
config_t left_hand_config;
left_hand_config.set_position( 0.01, 0.0, 0.004 );
left_hand_config.set_orientation( 0, 0, 0, 1 );
std::vector<unsigned> indices;
for (int i = 0; i < relative_configurations.size(); ++i)
{
indices.push_back(i);
}
for (int i = 0; i < 9001; ++i)
{
unsigned i1,i2;
i1 = uniform_int_random(0,relative_configurations.size()-1);
i2 = uniform_int_random(0,relative_configurations.size()-1);
std::swap(indices[i1],indices[i2]);
}
//Then, for each of those, put it into the global coordinate frame
for( unsigned i=0; i<indices.size(); ++i )
{
if( _hand == "left" )
{
grasp_configurations[i] = left_hand_config;
grasp_configurations[i].relative_to_global( relative_configurations[indices[i]].first );
}
else
{
if( relative_configurations[indices[i]].second == 1 || relative_configurations[indices[i]].second == 3 )
grasp_configurations[i] = right_hand_config;
else if( relative_configurations[indices[i]].second == 2 )
grasp_configurations[i] = right_hand_pinch_config;
else
PRX_FATAL_S("Improper grasp mode specified!!! " << relative_configurations[indices[i]].second );
grasp_configurations[i].relative_to_global( relative_configurations[indices[i]].first );
}
grasp_configurations[i].relative_to_global( object_pose );
}
//Ask for an IK solution to that configuration
manipulator_plant_t* manipulator;
if( _hand == "left" )
manipulator = _left_manipulator;
else
manipulator = _right_manipulator;
model->get_active_space()->copy_to_point( object_start_state );
steering_time = seeding_time = validation_time = planning_time = 0;
steering_counter = validation_counter = planning_counter = 0;
bool success = false;
timeout_clock.reset();
sys_clock_t zak_clock;
zak_clock.reset();
stop_updating_state();
unsigned i;
for( i=0; i<relative_configurations.size() && success == false; ++i )
{
// PRX_INFO_S("ZL: "<<model->get_active_space()->print_memory(3));
// PRX_PRINT( "\n --- Trying grasp id: " << i << " ---\n", PRX_TEXT_BROWN );
if( timeout_clock.measure() > GRASPING_TIMEOUT )
{
PRX_PRINT( "\n\n\n Grasping Timeout \n\n\n", PRX_TEXT_BROWN );
break;
}
success = reachable_IK( false, current_state, grasp_configurations[i], GRASPING_IK );
if( success )
PRX_PRINT("Found grasp, id: " << indices[i] << " type: " << relative_configurations[indices[i]].second, PRX_TEXT_CYAN);
}
start_updating_state();
num_grasps_tried = i;
grasp_id = relative_configurations[indices[i-1]].second;
// PRX_PRINT("overall_time " << zak_clock.measure(), PRX_TEXT_BROWN );
//PRX_PRINT(" steering_time " << steering_time, PRX_TEXT_BROWN );
//PRX_PRINT(" seeding_time " << seeding_time, PRX_TEXT_BROWN );
//PRX_PRINT(" validation_time " << validation_time, PRX_TEXT_BROWN );
//PRX_PRINT(" planning_time " << planning_time, PRX_TEXT_BROWN );
//PRX_PRINT(" avarage steering_time " << (steering_time/steering_counter), PRX_TEXT_BROWN );
//PRX_PRINT(" avarage seeding_time " << (seeding_time/validation_counter), PRX_TEXT_BROWN );
//PRX_PRINT(" avarage validation_time " << (validation_time/validation_counter), PRX_TEXT_BROWN );
//PRX_PRINT(" avarage planning_time " << (planning_time/planning_counter), PRX_TEXT_BROWN );
return success;
}
bool motoman_planning_application_t::compute_grasp_callback(prx_planning::compute_grasp::Request& req, prx_planning::compute_grasp::Response& res )
{
object_name = req.object_name;
if( find_grasp_for_object( ) )
{
res.success = true;
res.arm = _hand;
res.grasp_id = grasp_id;
res.num_grasps_tried = num_grasps_tried;
return true;
}
else
{
PRX_PRINT( "Grasping failed - REPORTING FAILURE", PRX_TEXT_BROWN );
res.success = false;
res.arm = _hand;
res.num_grasps_tried = num_grasps_tried;
return true;
}
}
void motoman_planning_application_t::impose_hand_state( space_point_t* target_state )
{
if( _hand == "left" )
{
for( int i=8; i<15; i++ )
target_state->at(i) = current_state->at(i);
}
else
{
for( int i=1; i<8; i++ )
target_state->at(i) = current_state->at(i);
target_state->at(15) = current_state->at(15);
}
target_state->at(16) = _grasping;
}
// camera_link is the
// source_state is the current state of the robot
// ee_config is the desired end effector configuration
// target_state is the state corresponding to the end effector
// resulting_plan is the trajectory from source_state to the target_state
// IK_stage: one of
bool motoman_planning_application_t::reachable_IK( bool camera_link, space_point_t* source_state, const config_t& ee_config, int IK_stage )
{
// PRX_PRINT( "reachable IK function at IK stage:: " << IK_stage, PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "source state = " << model->get_state_space()->print_point( source_state, 3 ), PRX_TEXT_BROWN + IK_stage );
if( timeout_clock.measure() > GRASPING_TIMEOUT )
{
PRX_PRINT( "\n\n\n Grasping Timeout \n\n\n", PRX_TEXT_BROWN );
return false;
}
if( camera_link == true && IK_stage != GENERAL_IK )
{
PRX_PRINT( "\nA grasping/lifting/retraction IK call for a camera - ERROR\n", PRX_TEXT_RED);
exit(-1);
}
if( IK_stage != GENERAL_IK && IK_stage != GRASPING_IK && IK_stage != LIFTING_IK && IK_stage != RETRACTION_IK )
{
PRX_PRINT( "\nInvalid IK stage parameter: " << IK_stage << " - ERROR\n", PRX_TEXT_RED);
exit(-1);
}
if (IK_stage == GRASPING_IK)
{
if(_hand == "left")
{
_left_manipulator->get_state_space()->copy_from_point(source_state);
_left_manipulator->get_end_effector_configuration(retracting_config);
}
else
{
_right_manipulator->get_state_space()->copy_from_point(source_state);
_right_manipulator->get_end_effector_configuration(retracting_config);
}
}
//IK_clock.reset();
// PRX_INFO_S("ZL: "<<model->get_active_space()->print_memory(3));
// First, I will try IK steering
bool success = check_IK_steering( camera_link, source_state, ee_config, IK_stage );
// PRX_INFO_S("ZL: "<<model->get_active_space()->print_memory(3));
//steering_counter++;
//double local_steering_time = IK_clock.measure_reset();
//PRX_PRINT( "steering time = " << local_steering_time, PRX_TEXT_BROWN + IK_stage );
//steering_time += local_steering_time;
if( !success && IK_stage != LIFTING_IK )
{
generate_IK_seeds( camera_link );
//validation_counter++;
//double local_seeding_time = IK_clock.measure_reset();
//PRX_PRINT( "seeding time = " << local_seeding_time, PRX_TEXT_BROWN + IK_stage );
//seeding_time += local_seeding_time;
int number_of_valid_states = generate_valid_IK_states( camera_link, ee_config, IK_stage );
//double local_validation_time = IK_clock.measure_reset();
//PRX_PRINT( "validation time = " << local_validation_time, PRX_TEXT_BROWN + IK_stage );
//validation_time += local_validation_time;
if( number_of_valid_states > 0 )
{
// PRX_INFO_S("ZL: "<<model->get_active_space()->print_memory(3));
//planning_counter++;
success = compute_reachable_IK( source_state, ee_config, IK_stage, number_of_valid_states );
// PRX_INFO_S("ZL: "<<model->get_active_space()->print_memory(3));
}
else
success = false;
//double local_planning_time = IK_clock.measure_reset();
//PRX_PRINT( "planning time = " << local_planning_time, PRX_TEXT_BROWN + IK_stage );
//planning_time += local_planning_time;
}
return success;
}
void motoman_planning_application_t::generate_IK_seeds( bool for_camera )
{
//Check that the memory is allocated
for( int i=0; i<IK_seeds.size(); i++ )
if( IK_seeds[i] == NULL )
IK_seeds[i] = model->get_state_space()->alloc_point();
IK_data_base_t* IK_DB;
if( for_camera && _hand == "left" )
IK_DB = left_cam_IK_data_base;
else if( !for_camera && _hand == "left" )
IK_DB = left_IK_data_base;
else if( for_camera && _hand == "right" )
IK_DB = right_cam_IK_data_base;
else if( !for_camera && _hand == "right" )
IK_DB = right_IK_data_base;
// RANDOM Seeds Version
if( IK_DB == NULL )
{
PRX_FATAL_S("Random IK Seeds" );
model->get_state_space()->copy_point( IK_seeds[0], current_state );
impose_hand_state( IK_seeds[0] );
for( int i=1; i<IK_seeds.size(); i++ )
{
model->get_state_space()->uniform_sample( IK_seeds[i] );
impose_hand_state( IK_seeds[i] );
}
}
//Database Seeds Version
else
{
config_t ee_config;
manipulator_plant_t* manipulator = (_hand == "left") ? _left_manipulator : _right_manipulator;
manipulator->get_end_effector_configuration( ee_config );
std::vector< state_t* > local_seeds;
IK_DB->get_near_neighbors( local_seeds, ee_config, IK_seeds.size()-1 );
model->get_state_space()->copy_point( IK_seeds[0], current_state );
for( unsigned i=0; i<local_seeds.size(); ++i )
model->get_state_space()->copy_point( IK_seeds[i+1], local_seeds[i] );
}
}
int motoman_planning_application_t::generate_valid_IK_states( bool camera_link, const config_t& config, int IK_stage )
{
manipulator_plant_t* manipulator = ( _hand == "left" ? _left_manipulator : _right_manipulator );
if( timeout_clock.measure() > GRASPING_TIMEOUT )
{
PRX_PRINT( "\n\n\n Grasping Timeout \n\n\n", PRX_TEXT_BROWN );
return 0;
}
std::vector< state_t* >* local_IK_ptr;
if( IK_stage == GENERAL_IK || IK_stage == GRASPING_IK )
local_IK_ptr = &candidate_IKs;
else if( IK_stage == LIFTING_IK )
local_IK_ptr = &lifting_IKs;
else if ( IK_stage == RETRACTION_IK )
local_IK_ptr = &retraction_IKs;
std::vector< state_t* > &local_candidate_IKs = *local_IK_ptr;
unsigned number_of_valid_states = 0;
int in_collision = 0;
int failed_ik = 0;
for( unsigned i=0; i<IK_seeds.size(); ++i )
{
if( timeout_clock.measure() > GRASPING_TIMEOUT )
{
PRX_PRINT( "\n\n\n Grasping Timeout \n\n\n", PRX_TEXT_BROWN );
break;
}
bool success = false;
//PRX_PRINT( "Calling for link " << camera_link, PRX_TEXT_BROWN + IK_stage );
if( camera_link )
success = manipulator->get_utility_IK( config, local_candidate_IKs[number_of_valid_states], _grasping, IK_seeds[i], true );
else
success = manipulator->IK_solver( config, local_candidate_IKs[number_of_valid_states], _grasping, IK_seeds[i], true );
if( visualize_grasps && success && IK_stage == GRASPING_IK )
{
std::vector<double> params;
params.push_back(.02);
geometry_t geom(PRX_SPHERE,¶ms);
vis_array_pub.publish(vis_comm->send_marker(geom, "THING_config", config));
}
//PRX_PRINT( "IK success is " << success << "for state: " << model->get_state_space()->print_point( local_candidate_IKs[number_of_valid_states], 4 ), PRX_TEXT_BROWN + IK_stage );
if( success )
{
if( model->valid_state( local_candidate_IKs[number_of_valid_states] ) )
++number_of_valid_states;
else
{
in_collision++;
// PRX_PRINT( "The resulting state is in collision", PRX_TEXT_BROWN + IK_stage );
// collision_list_t* list = model->get_colliding_bodies();
// foreach(collision_pair_t pair, list->get_body_pairs())
// {
// PRX_WARN_S(pair.first << " " << pair.second);
// }
// PRX_WARN_S("");
}
}
else
failed_ik++;
if ( IK_stage == RETRACTION_IK && number_of_valid_states >= 25 )
break;
}
//If there are no valid free states, abort out, no need to do more work
// if( number_of_valid_states == 0 )
// {
// PRX_PRINT( "SEEDS FAILED: out of (" << IK_seeds.size() << "): IK failures: " << failed_ik << " Collisions: " << in_collision , PRX_TEXT_BROWN + IK_stage );
// }
// else
// {
// PRX_PRINT( "NUMBER OF VALID STATES IS " << number_of_valid_states, PRX_TEXT_BROWN + IK_stage );
// }
return number_of_valid_states;
}
bool motoman_planning_application_t::compute_reachable_IK( space_point_t* source_state, const config_t& ee_config, int IK_stage, int number_of_valid_states )
{
if( timeout_clock.measure() > GRASPING_TIMEOUT )
{
PRX_PRINT( "\n\n\n Grasping Timeout \n\n\n", PRX_TEXT_BROWN );
return false;
}
/*
std::vector< trajectory_t > successful_trajectories;
std::vector< plan_t > successful_plans;
std::vector< space_point_t* > successful_states;
*/
std::vector< state_t* > local_candidate_IKs;
for( int i=0; i<number_of_valid_states; i++ )
{
if( IK_stage == GENERAL_IK || IK_stage == GRASPING_IK )
local_candidate_IKs.push_back( candidate_IKs[i] );
else if( IK_stage == LIFTING_IK )
local_candidate_IKs.push_back( lifting_IKs[i] );
else if ( IK_stage == RETRACTION_IK )
local_candidate_IKs.push_back( retraction_IKs[i] );
}
//PRX_PRINT( "the size of the vector is " << local_candidate_IKs.size(), PRX_TEXT_BROWN + IK_stage );
// PRX_INFO_S("ZL: "<<model->get_active_space()->print_memory(3));
if( find_shortest_path_internal( source_state, local_candidate_IKs, IK_stage ) )
{
if( IK_stage == GENERAL_IK )
{
IK_plan = task_query->plan;
IK_traj = task_query->path;
// PRX_PRINT( "Computed plan for :: ", PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Initial state :: " << model->get_state_space()->print_point( source_state, 3 ) , PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Goal state :: " << model->get_state_space()->print_point( task_query->path.back(), 3 ), PRX_TEXT_BROWN + IK_stage );
return true;
}
else if( IK_stage == GRASPING_IK )
{
int counter = local_candidate_IKs.size();
while( counter > 0 )
{
if( timeout_clock.measure() > GRASPING_TIMEOUT )
{
PRX_PRINT( "\n\n\n Grasping Timeout \n\n\n", PRX_TEXT_BROWN );
return false;
}
// PRX_INFO_S("ZL: "<<model->get_active_space()->print_memory(3));
if( IK_recursion( task_query->path.back(), ee_config, GRASPING_IK ) )
{
grasping_traj = task_query->path;
grasping_plan = task_query->plan;
// PRX_PRINT( "Computed plan for :: ", PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Initial state :: " << model->get_state_space()->print_point( source_state, 3 ) , PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Goal state :: " << model->get_state_space()->print_point( task_query->path.back(), 3 ), PRX_TEXT_BROWN + IK_stage );
return true;
}
else
{
int goal_index = -1;
for( int i=0; i<local_candidate_IKs.size() && goal_index == -1; i++ )
if( model->get_state_space()->equal_points( local_candidate_IKs[i], task_query->path.back(), .001) )
goal_index = i;
if( goal_index == -1 )
PRX_FATAL_S( "The last state on the trajectory was not in the local candidate IK vector" );
local_candidate_IKs.erase( local_candidate_IKs.begin() + goal_index );
counter--;
if( find_shortest_path_internal( source_state, local_candidate_IKs, GRASPING_IK ) == false )
return false;
}
}
// PRX_INFO_S("ZL: "<<model->get_active_space()->print_memory(3));
return false;
}
else if( IK_stage == LIFTING_IK )
{
int counter = local_candidate_IKs.size();
while( counter > 0 )
{
if( timeout_clock.measure() > GRASPING_TIMEOUT )
{
PRX_PRINT( "\n\n\n Grasping Timeout \n\n\n", PRX_TEXT_BROWN );
return false;
}
if( IK_recursion( lifting_task_query->path.back(), ee_config, LIFTING_IK ) )
{
lifting_traj = lifting_task_query->path;
lifting_plan = lifting_task_query->plan;
// PRX_PRINT( "Computed plan for :: ", PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Initial state :: " << model->get_state_space()->print_point( source_state, 3 ) , PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Goal state :: " << model->get_state_space()->print_point( lifting_task_query->path.back(), 3 ), PRX_TEXT_BROWN + IK_stage );
return true;
}
else
{
int goal_index = -1;
for( int i=0; i<local_candidate_IKs.size() && goal_index == -1; i++ )
if( model->get_state_space()->equal_points( local_candidate_IKs[i], lifting_task_query->path.back(), .001) )
goal_index = i;
if( goal_index == -1 )
PRX_FATAL_S( "The last state on the trajectory was not in the local candidate IK vector" );
local_candidate_IKs.erase( local_candidate_IKs.begin() + goal_index );
counter--;
if( find_shortest_path_internal( source_state, local_candidate_IKs, LIFTING_IK ) == false )
return false;
}
}
return false;
}
else if( IK_stage == RETRACTION_IK )
{
retracting_plan = retracting_task_query->plan;
retracting_traj = retracting_task_query->path;
// PRX_PRINT( "Computed plan for :: " << retracting_traj.size(), PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Initial state :: " << model->get_state_space()->print_point( source_state, 3 ) , PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Goal state :: " << model->get_state_space()->print_point( retracting_task_query->path.back(), 3 ), PRX_TEXT_BROWN + IK_stage );
return true;
}
}
else
return false;
/*
std::vector< state_t* >* local_IK_ptr;
if( IK_stage == GENERAL_IK || IK_stage == GRASPING_IK )
local_IK_ptr = &candidate_IKs;
else if( IK_stage == LIFTING_IK )
local_IK_ptr = &lifting_IKs;
else if ( IK_stage == RETRACTION_IK )
local_IK_ptr = &retraction_IKs;
std::vector< state_t* > &local_candidate_IKs = *local_IK_ptr;
bool success = false;
for( unsigned i=0; i<number_of_valid_states && success == false; i++ )
{
if( timeout_clock.measure() > GRASPING_TIMEOUT )
{
PRX_PRINT( "\n\n\n Grasping Timeout \n\n\n", PRX_TEXT_BROWN );
return false;
}
// PRX_PRINT(" -- Checking valid state " << i << " in mode " << IK_stage, PRX_TEXT_BROWN + IK_stage );
// For Multi-goal use:: find_shortest_path_internal( source_state, candidate_IKs );
if( IK_stage == GENERAL_IK && find_path_internal( source_state, local_candidate_IKs[i], GENERAL_IK ) )
{
successful_trajectories.push_back( task_query->path );
successful_plans.push_back( task_query->plan );
successful_states.push_back( local_candidate_IKs[i] );
}
else if( IK_stage == GRASPING_IK && find_path_internal( source_state, local_candidate_IKs[i], GRASPING_IK ) )
{
if( IK_recursion( local_candidate_IKs[i], ee_config, GRASPING_IK ) )
{
successful_trajectories.push_back( task_query->path );
successful_plans.push_back( task_query->plan );
successful_states.push_back( local_candidate_IKs[i] );
success = true;
}
}
else if( IK_stage == LIFTING_IK && find_path_internal( source_state, local_candidate_IKs[i], LIFTING_IK ) )
{
if( IK_recursion( local_candidate_IKs[i], ee_config, LIFTING_IK) )
{
successful_trajectories.push_back( lifting_task_query->path );
successful_plans.push_back( lifting_task_query->plan );
successful_states.push_back( local_candidate_IKs[i] );
success = true;
}
}
else if( IK_stage == RETRACTION_IK && find_path_internal( source_state, local_candidate_IKs[i], RETRACTION_IK ))
{
successful_trajectories.push_back( retracting_task_query->path );
successful_plans.push_back( retracting_task_query->plan );
successful_states.push_back( local_candidate_IKs[i] );
success = true;
// PRX_PRINT( "WE HAVE LIFT OFF!!!!!", PRX_TEXT_GREEN );
}
}
PRX_PRINT( "Number of successful states is " << successful_trajectories.size(), PRX_TEXT_BROWN + IK_stage );
double smallest_cost = PRX_INFINITY;
unsigned shortest_index;
if( successful_trajectories.size() > 0 )
{
//For each one, evaluate it based on its length, remembering the best one
for( unsigned i=0; i<successful_trajectories.size(); ++i )
{
if( successful_trajectories[i].length() < smallest_cost )
{
shortest_index = i;
smallest_cost = successful_trajectories[i].length();
}
}
//PRX_PRINT( "Successful state :: " << model->get_state_space()->print_point( successful_states[shortest_index], 3 ), PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "With index :: " << shortest_index, PRX_TEXT_BROWN + IK_stage );
//PRX_INFO_S("Selected trajectory: \n" << successful_trajectories[shortest_index].print());
// these variables can be used when we plan
if( IK_stage == GENERAL_IK )
{
IK_plan = successful_plans[ shortest_index ];
IK_traj = successful_trajectories[shortest_index];
}
else if(IK_stage == GRASPING_IK)
{
grasping_plan = successful_plans[ shortest_index ];
grasping_traj = successful_trajectories[shortest_index];
}
else if(IK_stage == LIFTING_IK)
{
lifting_plan = successful_plans[ shortest_index ];
lifting_traj = successful_trajectories[shortest_index];
}
else if(IK_stage == RETRACTION_IK)
{
retracting_plan = successful_plans[ shortest_index ];
retracting_traj = successful_trajectories[shortest_index];
}
return true;
}
return false;
*/
}
bool motoman_planning_application_t::IK_recursion( space_point_t* destination, const config_t& destination_config, int IK_stage )
{
if( timeout_clock.measure() > GRASPING_TIMEOUT )
{
PRX_PRINT( "\n\n\n Grasping Timeout \n\n\n", PRX_TEXT_BROWN );
return false;
}
if( IK_stage == GRASPING_IK )
{
// PRX_PRINT("In Grasping mode - making a recursive call", PRX_TEXT_BROWN + IK_stage );
config_t lifting_config;
lifting_config = destination_config;
double x,y,z;
lifting_config.get_position( &x, &y, &z );
lifting_config.set_position_at( 2, z+LIFT_HEIGHT );
//PRX_PRINT("Lifting configuration is: " << lifting_config, PRX_TEXT_BROWN + IK_stage );
model->use_context(_hand + "_" + object_name);
_grasping = true;
destination->at(16) = 1;
model->push_state( destination );
model->get_active_space()->copy_from_point( object_start_state );
//PRX_PRINT(" THE OBJECT IS AT 1 :::: " << model->get_active_space()->print_memory( 7 ), PRX_TEXT_BROWN + IK_stage);
((manipulation_simulator_t*)model->get_simulator())->compute_relative_config();
//PRX_PRINT( "RELATIVE CONFIG 1", PRX_TEXT_BROWN + IK_stage );
//((manipulation_simulator_t*)model->get_simulator())->print_relative_config();
//PRX_PRINT( "START state is" << model->get_state_space()->print_point( destination, 3 ), PRX_TEXT_BROWN + IK_stage );
bool success = reachable_IK( false, destination, lifting_config, LIFTING_IK );
//PRX_PRINT( "DESTINATION 2 is" << model->get_state_space()->print_point( destination ), PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "RELATIVE CONFIG 2", PRX_TEXT_BROWN + IK_stage );
//((manipulation_simulator_t*)model->get_simulator())->print_relative_config();
model->push_state( destination );
//PRX_PRINT(" THE OBJECT IS AT 2:::: " << model->get_active_space()->print_memory( 7 ), PRX_TEXT_BROWN + IK_stage );
destination->at(16) = 0;
model->use_context(_hand + "_" + "manipulator");
_grasping = false;
model->push_state( destination );
((manipulation_simulator_t*)model->get_simulator())->compute_relative_config();
if( success && _hand == "left" )
{
// PRX_PRINT("\n\n TRYING TO PUSH\n\n", PRX_TEXT_BROWN);
config_t initial_config;
_left_manipulator->get_end_effector_configuration( initial_config );
config_t pushing_config;
pushing_config.set_position( 0.0, 0.0, 0.02 );
pushing_config.set_orientation( 0.0, 0.0, 0.0, 1.0 );
pushing_config.relative_to_global( initial_config );
// PRX_PRINT( "initial configuration: " << initial_config, PRX_TEXT_GREEN );
// PRX_PRINT( "goal configuration: " << pushing_config, PRX_TEXT_GREEN );
plan_t first_plan, second_plan;
trajectory_t first_traj, second_traj;
first_plan.link_control_space( _left_manipulator->get_control_space() );
first_plan.clear();
first_traj.link_space( _left_manipulator->get_state_space() );
first_traj.clear();
second_plan.link_control_space( _left_manipulator->get_control_space() );
second_plan.clear();
second_traj.link_space( _left_manipulator->get_state_space() );
second_traj.clear();
if( _left_manipulator->IK_steering_general( initial_config, pushing_config, first_plan, false, false ) )
{
// PRX_PRINT("\n\n Steering General worked the first time\n\n", PRX_TEXT_BROWN);
for(int i=0;i<first_plan.size();i++)
{
first_plan[i].duration *= 2;
}
model->propagate_plan( destination, first_plan, first_traj, false );
if( _left_manipulator->IK_steering_general( pushing_config, initial_config, second_plan, false, false ) )
{
model->propagate_plan( first_traj.back(), second_plan, second_traj, false );
// PRX_PRINT("\n\n Steering General worked the second time\n\n", PRX_TEXT_BROWN);
first_plan += second_plan;
first_plan += lifting_plan;
lifting_plan = first_plan;
first_traj += second_traj;
first_traj += lifting_traj;
lifting_traj = first_traj;
}
}
}
model->use_context(_hand + "_" + object_name);
return success;
}
else if( IK_stage == LIFTING_IK )
{
//PRX_PRINT("In Lifting mode - making a recursive call", PRX_TEXT_BROWN + IK_stage );
config_t local_retraction_config;
if( uniform_random( 0.0, 1.0 ) < 0.5 )
{
// PRX_PRINT( "CASE gripper position and orientation", PRX_TEXT_BROWN + IK_stage );
double x,y,z;
retracting_config.get_position(x,y,z);
local_retraction_config.set_position( x,y,z );
double w;
quaternion_t quat = retracting_config.get_orientation();
quat.get( x, y, z, w );
local_retraction_config.set_orientation( x,y,z,w );
}
else
{
// PRX_PRINT( "CASE lifting orientation with gripper x", PRX_TEXT_BROWN + IK_stage );
local_retraction_config = destination_config;
double x,y,z, x_new, y_new, z_new;
destination_config.get_position(x,y,z);
retracting_config.get_position(x_new,y_new,z_new);
local_retraction_config.set_position( x_new, y, z );
}
//PRX_PRINT("Retraction configuration is: " << local_retraction_config, PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "START state is" << model->get_state_space()->print_point( destination, 3 ), PRX_TEXT_BROWN + IK_stage );
return reachable_IK( false, destination, local_retraction_config, RETRACTION_IK );
}
}
bool motoman_planning_application_t::check_IK_steering( bool camera_link, space_point_t* source_state, const config_t& ee_config, int IK_stage )
{
if( timeout_clock.measure() > GRASPING_TIMEOUT )
{
PRX_PRINT( "\n\n\n Grasping Timeout \n\n\n", PRX_TEXT_BROWN );
return false;
}
//PRX_PRINT( "checking IK steering", PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Source state in CIKS: " << model->get_state_space()->print_point( source_state, 3 ), PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Destination config in CIKS: " << ee_config, PRX_TEXT_BROWN + IK_stage );
// setup the right query, its start state and the corresponding planner
base_apc_task_query_t* current_query = setup_planning( source_state, IK_stage );
manipulator_plant_t* manipulator = NULL;
if( _hand == "left" )
manipulator = _left_manipulator;
else
manipulator = _right_manipulator;
manipulator->get_state_space()->copy_from_point( source_state );
config_t start_config;
manipulator->get_end_effector_configuration( start_config );
if( ee_config.is_approximate_equal( start_config ) )
{
current_query->plan.clear();
current_query->path.clear();
//PRX_PRINT( "Start and goal configurations are the same - success!!", PRX_TEXT_BROWN + IK_stage );
return true;
}
// linking the query
root_task->link_query( current_query );
//PRX_PRINT( "Linked query and ready to perform IK resolution...", PRX_TEXT_BROWN + IK_stage );
// calling the IK steering function for the desired end effector configuration
((base_apc_task_planner_t*)root_task)->IK_resolve_query( ee_config, _grasping, camera_link );
// Fail to compute a path
if( (current_query->plan.length() <= 0 ) )
{
// PRX_PRINT("IK steering: There was NO path", PRX_TEXT_BROWN + IK_stage );
return false;
}
else
{
// PRX_PRINT( "IK steering: Success", PRX_TEXT_BROWN + IK_stage );
if( IK_stage == GENERAL_IK )
{
IK_plan = task_query->plan;
IK_traj = task_query->path;
// PRX_PRINT( "Computed IK steering plan for mode ", PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Initial state :: " << model->get_state_space()->print_point( source_state, 3 ) , PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Goal state :: " << model->get_state_space()->print_point( task_query->path.back(), 3 ), PRX_TEXT_BROWN + IK_stage );
return true;
}
else if(IK_stage == GRASPING_IK)
{
if( IK_recursion( current_query->get_goal()->get_goal_points()[0], ee_config, IK_stage ) )
{
grasping_plan = task_query->plan;
grasping_traj = task_query->path;
// PRX_PRINT( "Computed IK steering plan for :: ", PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Initial state :: " << model->get_state_space()->print_point( source_state, 3 ) , PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Goal state :: " << model->get_state_space()->print_point( task_query->path.back(), 3 ), PRX_TEXT_BROWN + IK_stage );
return true;
}
else
return false;
}
else if(IK_stage == LIFTING_IK)
{
if( IK_recursion( current_query->get_goal()->get_goal_points()[0], ee_config, IK_stage ) )
{
lifting_plan = lifting_task_query->plan;
lifting_traj = lifting_task_query->path;
// PRX_PRINT( "Computed IK steering plan for :: ", PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Initial state :: " << model->get_state_space()->print_point( source_state, 3 ) , PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Goal state :: " << model->get_state_space()->print_point( lifting_task_query->path.back(), 3 ), PRX_TEXT_BROWN + IK_stage );
return true;
}
else
return false;
}
else if(IK_stage == RETRACTION_IK)
{
retracting_plan = retracting_task_query->plan;
retracting_traj = retracting_task_query->path;
// PRX_PRINT( "Computed IK steering plan for :: ", PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Initial state :: " << model->get_state_space()->print_point( source_state, 3 ) , PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Goal state :: " << model->get_state_space()->print_point( retracting_task_query->path.back(), 3 ), PRX_TEXT_BROWN + IK_stage );
return true;
}
}
}
base_apc_task_query_t* motoman_planning_application_t::setup_planning( space_point_t* source, int IK_stage )
{
// setting object to its pose relative to the manipulator
if( _grasping )
model->push_state( source );
base_apc_task_query_t* current_query;
//setup new query from request
if( IK_stage == GENERAL_IK || IK_stage == GRASPING_IK )
current_query = task_query;
else if( IK_stage == LIFTING_IK )
current_query = lifting_task_query;
else if( IK_stage == RETRACTION_IK )
current_query = retracting_task_query;
current_query->clear();
((base_apc_task_query_t*)current_query)->clear_goal();
// Setting the start and the goal state of the query
model->get_state_space()->copy_point( current_query->get_start_state(), source);
current_query->get_start_state()->at(16) = (double)_grasping;
// Setting the planner to the appropriate one per hand use and grasping mode
if( _hand == "left" && _grasping )
( (base_apc_task_planner_t*)root_task )->change_queried_planner(left_grasped_planner);
if( _hand == "left" && !_grasping )
( (base_apc_task_planner_t*)root_task )->change_queried_planner(left_ungrasped_planner);
if( _hand == "right" && _grasping )
( (base_apc_task_planner_t*)root_task )->change_queried_planner(right_grasped_planner);
if( _hand == "right" && !_grasping )
( (base_apc_task_planner_t*)root_task )->change_queried_planner(right_ungrasped_planner);
return current_query;
}
bool motoman_planning_application_t::find_path_internal( space_point_t* source, space_point_t* destination, int IK_stage )
{
//PRX_PRINT( "find path internal", PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Source state in FPI: " << model->get_state_space()->print_point( source, 3 ), PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Destination state in FPI: " << model->get_state_space()->print_point( destination, 3), PRX_TEXT_BROWN + IK_stage );
base_apc_task_query_t* current_query = setup_planning( source, IK_stage );
( (multiple_goal_states_t*) (current_query->get_goal() ) )->init_with_goal_state( destination );
state_t* prx_goal_state = current_query->get_goal()->get_goal_points()[0];
prx_goal_state->at(16) = (double)_grasping;
if( model->get_state_space()->equal_points( current_query->get_start_state(), prx_goal_state, .001) )
{
//PRX_PRINT( "Already at goal. No path to be found.", PRX_TEXT_BROWN + IK_stage );
current_query->plan.clear();
current_query->path.clear();
return true;
}
// linking the query - to update the goal
root_task->link_query(current_query);
//PRX_PRINT("Resolving query in context " << model->get_current_context() << " ...", PRX_TEXT_BROWN + IK_stage );
//if( _grasping )
// PRX_PRINT( "Before resolve query, the object is at: " << model->get_active_space()->print_memory( 7 ), PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "RELATIVE CONFIG", PRX_TEXT_BROWN + IK_stage );
//((manipulation_simulator_t*)model->get_simulator())->print_relative_config();
((base_apc_task_planner_t*)root_task)->resolve_query( _grasping );
//PRX_PRINT( "Path computed::\n " << current_query->path.print(), PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "RELATIVE CONFIG", PRX_TEXT_GREEN );
//((manipulation_simulator_t*)model->get_simulator())->print_relative_config();
//if( _grasping )
// PRX_PRINT( "After resolve query, the object is at: " << model->get_active_space()->print_memory( 7 ), PRX_TEXT_BROWN + IK_stage );
if( current_query->plan.length() <= 0 )
{
// PRX_PRINT("Resolve Query: There was NO path", PRX_TEXT_BROWN + IK_stage );
return false;
}
else
{
// PRX_PRINT("Resolve Query: Path returned", PRX_TEXT_BROWN + IK_stage );
return true;
}
}
bool motoman_planning_application_t::find_shortest_path_internal( space_point_t* source, std::vector<space_point_t*> destinations, int IK_stage )
{
//PRX_PRINT( "find shortest path internal", PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Source state in FPI: " << model->get_state_space()->print_point( source, 3 ), PRX_TEXT_BROWN + IK_stage );
//PRX_PRINT( "Destination state in FPI: " << model->get_state_space()->print_point( destination, 3), PRX_TEXT_BROWN + IK_stage );
// PRX_INFO_S("ZL: "<<model->get_active_space()->print_memory(3));
base_apc_task_query_t* current_query = setup_planning( source, IK_stage );
// PRX_INFO_S("ZL: "<<model->get_active_space()->print_memory(3));
//PRX_PRINT( "Ready to add destinations", PRX_TEXT_BROWN + IK_stage );
foreach(state_t* d, destinations)
{
model->get_state_space()->copy_point( multi_goal_assist, d);
multi_goal_assist->at(16) = (double)_grasping;
static_cast<multiple_goal_states_t*>(current_query->get_goal())->add_goal_state(multi_goal_assist);
//PRX_PRINT( "Goal state in FPI " << model->get_state_space()->print_point( multi_goal_assist, 3 ), PRX_TEXT_BROWN + IK_stage );
if( model->get_state_space()->equal_points( current_query->get_start_state(), multi_goal_assist, .001) )
{
// PRX_INFO_S("ZL: "<<model->get_active_space()->print_memory(3));
current_query->plan.clear();
current_query->path.clear();
return true;
}
}
// linking the query
root_task->link_query(current_query);
//PRX_PRINT("Resolving query in context " << model->get_current_context() << " ...", PRX_TEXT_LIGHTGRAY );
// PRX_INFO_S("ZL: "<<model->get_active_space()->print_memory(3));
((base_apc_task_planner_t*)root_task)->resolve_query( _grasping );
// PRX_INFO_S("ZL: "<<model->get_active_space()->print_memory(3));
if( current_query->plan.length() <= 0 )
{
//PRX_PRINT("Resolve Query: There was NO path", PRX_TEXT_BROWN + IK_stage );
return false;
}
else
{
//PRX_PRINT("Resolve Query: Path returned", PRX_TEXT_BROWN + IK_stage );
return true;
}
}
void motoman_planning_application_t::add_trajectory_to_database( space_point_t* start, config_t ee_config, trajectory_t& traj )
{
// PRX_PRINT( "Going to add trajectory!", PRX_TEXT_GREEN );
char* w = std::getenv("PRACSYS_PATH");
std::string dir(w);
dir += ("/prx_output/");
std::string file = dir + "trajectories_" + _hand + ".database";
PRX_PRINT(":: " << file, PRX_TEXT_LIGHTGRAY);
std::ofstream traj_out;
traj_out.open( file.c_str(), std::ofstream::app );
// Output the start/goal pair
traj_out << model->get_state_space()->serialize_point( start, 8 ) << "\n";
traj_out << ee_config << "\n";
//Then, output the trajectory itself
traj.save_to_stream( traj_out );
//Cleanup
traj_out.close();
}
}
}
|
bdb5c3e6c6fec18d54d443e991450437f9dc0f50 | 11523e7798335a3ea9b73520edad9701e7cbabfd | /src/triangular.cpp | 47db499aa1dde3ca92a25349ba2d4fc176480b83 | [] | no_license | nparrado/Memoria2013 | d277fa144e0944d9f459ffccd82d87a19d61cd92 | 6014f92247781aa28ce1c0b33e818e63eae9a418 | refs/heads/master | 2021-01-01T15:19:03.836094 | 2013-02-22T13:09:14 | 2013-02-22T13:09:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 344 | cpp | triangular.cpp | #include "triangular.h"
#include "mallacuadrilateros.h"
Triangular::Triangular(Malla *m) : Comando(m) {
assert(m->getTipoMalla() == "quadrilateral");
}
void Triangular::execute() {
nueva_malla = ((MallaCuadrilateros *)malla)->triangular();
}
MallaTriangulos *Triangular::getMalla() {
return nueva_malla;
}
Triangular::~Triangular(){
}
|
023bf5098d284c1c3cdb5052ec7163ddfdf3a112 | 1936d0f9d8ba33b9ea8b0888e6d5c4b03bf0cef6 | /Lengine/Src/Components/TransformComponent.cpp | 9981c46628138969e4be666573cf4ce4ba403991 | [] | no_license | LioQing/Lengine | d50b6d5476cbb03ad248285150f1da231686fa95 | af5e844c924cbda8479c9fa4ea906eb1a41bfb9d | refs/heads/master | 2022-11-27T17:47:23.911470 | 2020-08-04T14:28:35 | 2020-08-04T14:28:35 | 259,930,158 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 973 | cpp | TransformComponent.cpp | #include "TransformComponent.h"
TransformComponent::TransformComponent(Vector2Df position, uint32_t width, uint32_t height)
: position(position), width(width), height(height), scale(Vector2Df(1.0f, 1.0f)), speed(1.0f), velocity(Vector2Df(0.0f, 0.0f))
{
}
TransformComponent::TransformComponent(Vector2Df position, uint32_t width, uint32_t height, Vector2Df scale)
: position(position), width(width), height(height), scale(scale), speed(1.0f), velocity(Vector2Df(0.0f, 0.0f))
{
}
TransformComponent::TransformComponent(Vector2Df position, uint32_t width, uint32_t height, Vector2Df scale, float speed)
: position(position), width(width), height(height), scale(scale), speed(speed), velocity(Vector2Df(0.0f, 0.0f))
{
}
TransformComponent::TransformComponent(Vector2Df position, uint32_t width, uint32_t height, Vector2Df scale, float speed, Vector2Df velocity)
: position(position), width(width), height(height), scale(scale), speed(speed), velocity(velocity)
{
}
|
f2fcd39366761addb4e84325af5d8ead01d85e2a | e1cba3821814e106be21d957eaac422c01ed309a | /Caesar_Decipher/crack.cpp | 2322c781355522c70f564b2a11035c43d99a63e3 | [] | no_license | jake-sheppard/EE355 | a78516a1207967cd094e798ce98f31ee53ae0bfa | 33c5632d461629daf192e952225127b83245de9e | refs/heads/master | 2020-04-12T11:37:04.044932 | 2016-05-05T07:33:20 | 2016-05-05T07:33:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,625 | cpp | crack.cpp | /*
crack.cpp
Author: Jake Sheppard
Short description of this file: Method of cracking a message.
*/
#include "caesarlib.h"
#include <fstream>
#include <iostream>
using namespace std;
// frequencies of letters in a large sample of English
const double enfreq[26] = {0.0793, 0.0191, 0.0392, 0.0351, 0.1093,
0.0131, 0.0279, 0.0238, 0.0824, 0.0024, 0.0103, 0.0506, 0.0277,
0.0703, 0.0602, 0.0274, 0.0019, 0.0705, 0.1109, 0.0652, 0.0321,
0.0098, 0.0093, 0.0026, 0.0156, 0.0040};
// return score when ch is shifted (if ch not letter, return 0)
double char_score(char ch, int shift) {
if (is_letter(ch)){
char val = image(ch,shift);
int index;
if (val>=65 && val<=90){
index = (static_cast<int>(val)-65) % 26;
}
else{
index = (static_cast<int>(val)-97) % 26;
}
return enfreq[index];
}
else{
return 0;
}
}
// return score when contents of entire file are shifted
double file_score(const char filename[], int shift) {
ifstream ifile(filename);
double total = 0;
char c;
while (ifile.get(c)){
total += char_score(c,shift);
}
return total;
}
int main(int argc, char* argv[]) {
if (argc != 2) {
cout << "Wrong number of arguments." << endl;
cout << "Usage: crack ciphertext.txt" << endl;
return 1;
}
// FILL this in
double bestScore = 0;
int tracker;
for (int i = 0; i < 26; i++){
double score = file_score(argv[1],i);
if (score > bestScore){
bestScore = score;
tracker = i;
}
}
print_file_image(argv[1],tracker);
return 0;
}
|
f137440598fdfc88bc6f48f97060e3a698d10546 | f156ca526b4a86b6ffa1e7d4fe663a1e71e08a8e | /tutorial/demo-1/StackSet.cpp | c31322dba2153e0ff4ce24b1d892b8523f7eae90 | [
"MIT"
] | permissive | hjwalt/program-analysis | 9a96f94d1ddaca412354b3c1b943c11db2d45d18 | 13eb8f8a043879ac48fd8000e1c3f3edb7c809c9 | refs/heads/master | 2020-04-19T23:18:11.385732 | 2019-04-21T03:17:09 | 2019-04-21T03:17:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,217 | cpp | StackSet.cpp | #include <cstdio>
#include <iostream>
#include <set>
#include <map>
#include <stack>
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
std::string getSimpleNodeLabel(const BasicBlock *Node);
int main(int argc, char **argv)
{
// Read the IR file.
static LLVMContext Context;
SMDiagnostic Err;
// Extract Module M from IR (assuming only one Module exists)
std::unique_ptr<Module> M = parseIRFile(argv[1], Err, Context);
if (M == nullptr)
{
fprintf(stderr, "error: failed to load LLVM IR file \"%s\"", argv[1]);
return EXIT_FAILURE;
}
// 1.Extract Function main from Module M
Function *F = M->getFunction("main");
// 2. Traversing the CFG in Depth First Order
// In order to do so, we use a stack: traversalStack.
// First, we add the entry basic block and a integer 0 representing depth to
// the stack. The depth represents the distance of the BB from entryBB.
std::stack<std::pair<BasicBlock *, int>> traversalStack;
BasicBlock *entryBB = &F->getEntryBlock();
std::pair<BasicBlock *, int> succAnalysisNode = std::make_pair(entryBB, 0);
traversalStack.push(succAnalysisNode);
// 3. while the stack is not empty we pop the top Basic Block, print it and
// add it's successor nodes to the stack plus an updated integer
while (!traversalStack.empty())
{
// Pop the top Basic Block and the depth from stack
std::pair<BasicBlock *, int> succAnalysisNode = traversalStack.top();
BasicBlock *BB = succAnalysisNode.first;
int depth = succAnalysisNode.second;
traversalStack.pop();
// Print the Basic Block, depth is used for pretty printing
if (BB != entryBB)
{
for (int i = 0; i < 2 * depth; i++)
llvm::outs() << " ";
llvm::outs() << "| \n";
}
for (int i = 0; i < 2 * depth; i++)
llvm::outs() << " ";
llvm::outs() << "Label:" << getSimpleNodeLabel(BB) << "\n";
// Extract the last instruction in the stack (Terminator Instruction)
const TerminatorInst *TInst = BB->getTerminator();
// Extract the number of successors the terminator instructor has
int NSucc = TInst->getNumSuccessors();
for (int i = 0; i < NSucc; ++i)
{
// For all successor basic blocks, add them to the stack
// Increase the value of depth by 1
BasicBlock *Succ = TInst->getSuccessor(i);
std::pair<BasicBlock *, int> succAnalysisNode = std::make_pair(Succ, depth + 1);
traversalStack.push(succAnalysisNode);
}
}
return 0;
}
// Printing Basic Block Label
std::string getSimpleNodeLabel(const BasicBlock *Node)
{
if (!Node->getName().empty())
return Node->getName().str();
std::string Str;
raw_string_ostream OS(Str);
Node->printAsOperand(OS, false);
return OS.str();
}
|
cce9161dacfe75e7ff2d804519ab38262cbd7a42 | 82bdd38af1f7b8fd5550717b4f32c76536b06ae6 | /test/server/Service_Mock.h | d230dcb8d8b077d73d2fe57675c228dba285fa98 | [] | no_license | UmbrellaSampler/gpuATTRACT_2.0 | ee424b1112da7e3f9bc9fb3832376ca7e89e8da5 | 6b6271b56d58657d869acf8c0ba3e915888ee30b | refs/heads/master | 2020-05-22T05:40:40.806852 | 2018-10-17T15:33:34 | 2018-10-17T15:33:34 | 61,951,527 | 2 | 2 | null | 2018-10-17T15:33:35 | 2016-06-25T16:21:23 | C++ | UTF-8 | C++ | false | false | 579 | h | Service_Mock.h | /*
* Int_Service.h
*
* Created on: Dec 23, 2015
* Author: uwe
*/
#ifndef TEST_TEST_SERVICE_H_
#define TEST_TEST_SERVICE_H_
#include <gmock/gmock.h>
#include "CPUEnergyService.h"
#include "GenericTypes.h"
namespace test {
class Service_Mock : public as::CPUEnergyService<GenericTypes<int, int, int>> {
public:
Service_Mock() :
as::CPUEnergyService<genericTypes_t>(nullptr) {}
MOCK_METHOD0(createItemProcessor, std::function<bool(workItem_t*)> () );
itemProcessor_t createItemProcessorImpl();
};
} // namespace test
#endif /* TEST_TEST_SERVICE_H_ */
|
bb330d2e85460af3a1ea23f8db7b6c9e4c888004 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/inetsrv/msmq/src/lib/utl/lib/utf8.cpp | 3f37afd5bba1063a7888f1276d33edcb27fce721 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 13,224 | cpp | utf8.cpp | /*++
Copyright (c) 1995-97 Microsoft Corporation
Module Name:
utf8.cpp
Abstract:
Implementation of conversion functions from\to utf8 caracters set
Author:
Gil Shafriri (gilsh) 15-10-2000
--*/
#include <libpch.h>
#include <utf8.h>
#include <strutl.h>
#include "utf8.tmh"
static size_t UtlUtf8LenOfWc(wchar_t wc)throw()
/*++
Routine Description:
return the number of utf8 caracters representing the given unicode caracter.
Arguments:
wc - unicode carcter.
Returned value:
number of utf8 caracters representing the given unicode caracter.
--*/
{
if (wc < 0x80)
return 1;
if (wc < 0x800)
return 2;
return 3;
}
size_t UtlUtf8LenOfWcs(const wchar_t* pwc, size_t cbWcs)throw()
/*++
Routine Description:
Return the number of utf8 caracters representing the given unicode buffer.
Arguments:
pwc - unicode buffer.
cbWcs - unicode buffer length in unicode caracters.
Returned value:
The number of utf8 caracters representing the given unicode buffer.
--*/
{
size_t len = 0;
for(size_t i=0; i<cbWcs; ++i)
{
len += UtlUtf8LenOfWc(pwc[i]);
}
return len;
}
size_t UtlUtf8LenOfWcs(const wchar_t* pwc)throw()
/*++
Routine Description:
Return the number of utf8 caracters representing the given unicode null terminating string.
Arguments:
pwc - unicode string.
Returned value:
The number of utf8 caracters representing the given unicode null terminating string.
Note:
The null termination unicode caracter (L'\0') is not processed.
--*/
{
size_t len = 0;
while(*pwc != L'\0')
{
len += UtlUtf8LenOfWc(*pwc);
pwc++;
}
return len;
}
size_t
UtlWcToUtf8(
wchar_t wc ,
utf8_char *pUtf8,
size_t cbUtf8
)
/*++
Routine Description:
Convert single unicode caracter into one or more (up to 3) utf8 caracters.
Arguments:
wc - Unicode caracter to convert.
pUtf8 - Output buffer that receive the utf8 carcters that are the conversion result.
cbUtf8 - the size in bytes of the space pUtf8 point to.
Returned value:
The number of utf8 caracters that copied to the output buffer. If the function
fails because of invalid input - bad_utf8 exception is thrown.
Note:
The null termination unicode caracter (L'\0') is not processed.
--*/
{
size_t count = UtlUtf8LenOfWc(wc);
ASSERT(count <= 3 && count > 0);
if (cbUtf8 < count)
throw std::range_error("");
switch (count) /* note: code falls through cases! */
{
case 3: pUtf8[2] = (utf8_char)(0x80 | (wc & 0x3f)); wc = wc >> 6; wc |= 0x800;
// Fall through
case 2: pUtf8[1] = (utf8_char)(0x80 | (wc & 0x3f)); wc = wc >> 6; wc |= 0xc0;
// Fall through
case 1: pUtf8[0] = (utf8_char)(wc);
}
return count;
}
static
size_t
UtlUtf8ToWc(
const utf8_char *pUtf8,
size_t cbUtf8,
wchar_t *pwc
)
/*++
Routine Description:
Convert utf8 caracters into single unicode caracter.
Arguments:
pUtf8 - Pointer to utf8 caracters that should be converted into single unicode caracter.
cbUtf8 - The length in bytes of the buffer pUtf8 points to.
pwc - Output buffer for the unicode caracter created.
Returned value:
The number of utf8 caracters that converted. If the function failed because of invalid
input - bad_utf8 exception is thrown.
--*/
{
ASSERT(pwc != 0);
ASSERT(pUtf8 != 0);
ASSERT(cbUtf8 != 0);
utf8_char c = pUtf8[0];
if (c < 0x80)
{
*pwc = c;
return 1;
}
if (c < 0xc2)
{
throw bad_utf8();
}
if (c < 0xe0)
{
if (cbUtf8 < 2)
throw std::range_error("");
if (!((pUtf8[1] ^ 0x80) < 0x40))
throw bad_utf8();
*pwc = ((wchar_t) (c & 0x1f) << 6) | (wchar_t) (pUtf8[1] ^ 0x80);
return 2;
}
if (c < 0xf0)
{
if (cbUtf8 < 3)
throw std::range_error("");
if (!((pUtf8[1] ^ 0x80) < 0x40 && (pUtf8[2] ^ 0x80) < 0x40
&& (c >= 0xe1 || pUtf8[1] >= 0xa0)))
throw bad_utf8();
*pwc = ((wchar_t) (c & 0x0f) << 12)
| ((wchar_t) (pUtf8[1] ^ 0x80) << 6)
| (wchar_t) (pUtf8[2] ^ 0x80);
return 3;
}
throw bad_utf8();
}
void
UtlUtf8ToWcs(
const utf8_char* pUtf8,
size_t cbUtf8,
wchar_t* pWcs,
size_t cbWcs,
size_t* pActualLen
)
/*++
Routine Description:
Convert utf8 array (not null terminating) into unicode string.
Arguments:
pUtf8 - utf8 string to convert.
size_t cbUtf8 size in bytes of array pUtf8 points to.
pWcs - Output buffer for the converted unicode caracters
cbWcs - The size in unicode caracters of the space that pWcs points to.
pActualLen - Receives the number of unicode caracters created.
Returned value:
None
Note:
It is the responsibility of the caller to allocate buffer large enough
to hold the converted data + null termination. To be on the safe side - allocate buffer
that the number of unicode caracters in it >= strlen(pUtf8) +1
--*/
{
size_t index = 0;
const utf8_char* Utf8End = pUtf8 + cbUtf8;
for(; pUtf8 != Utf8End; ++index)
{
size_t size = UtlUtf8ToWc(
pUtf8,
cbWcs - index,
&pWcs[index]
);
pUtf8 += size;
ASSERT(pUtf8 <= Utf8End);
ASSERT(index < cbWcs - 1);
}
ASSERT(index < cbWcs);
pWcs[index] = L'\0';
if(pActualLen != NULL)
{
*pActualLen = index;
}
}
void
UtlUtf8ToWcs(
const utf8_char *pUtf8,
wchar_t* pWcs,
size_t cbWcs,
size_t* pActualLen
)
/*++
Routine Description:
Convert utf8 string into unicode string.
Arguments:
pUtf8 - utf8 string to convert.
pWcs - Output buffer for the converted unicode caracters
cbWcs - The size in unicode caracters of the space that pWcs points to.
pActualLen - Receives the number of unicode caracters created.
Returned value:
None
Note:
It is the responsibility of the caller to allocate buffer large enough
to hold the converted data + null termination. To be on the safe side - allocate buffer
that the number of unicode caracters in it >= strlen(pUtf8) +1
--*/
{
size_t index = 0;
for(; *pUtf8 != '\0' ; ++index)
{
size_t size = UtlUtf8ToWc(
pUtf8,
cbWcs - index,
&pWcs[index]
);
pUtf8 += size;
ASSERT(index < cbWcs - 1);
}
ASSERT(index < cbWcs);
pWcs[index] = L'\0';
if(pActualLen != NULL)
{
*pActualLen = index;
}
}
utf8_char* UtlWcsToUtf8(const wchar_t* pwcs, size_t* pActualLen)
/*++
Routine Description:
Convert unicode string into utf8 string.
Arguments:
pwcs - Unicode string to convert.
pActualLen - Receives the number of bytes created in utf8 format.
Returned value:
Utf8 reperesentation of the given unicode string.
If the function failes because of invalid input - bad_utf8 exception
is thrown.
Note:
It is the responsibility of the caller to call delete[] on returned pointer.
--*/
{
ASSERT(pwcs != NULL);
size_t len = UtlUtf8LenOfWcs(pwcs) +1;
AP<utf8_char> pUtf8 = new utf8_char[len];
UtlWcsToUtf8(pwcs, pUtf8.get(), len, pActualLen);
return pUtf8.detach();
}
wchar_t* UtlUtf8ToWcs(const utf8_char* pUtf8, size_t cbUtf8, size_t* pActualLen)
/*++
Routine Description:
Convert utf8 array of bytes into unicode string.
Arguments:
pUtf8 - utf8 array of bytes to convert.
cbUtf8 - The length in bytes of the buffer pUtf8 points to.
pActualLen - Receives the number of unicode caracters created.
Returned value:
Unicode reperesentation of the given utf8 string.
If the function failes because of invalid input - bad_utf8 exception
is thrown
Note:
It is the responsibility of the caller to call delete[] on returned pointer.
--*/
{
ASSERT(pUtf8 != NULL);
size_t Wcslen = cbUtf8 + 1;
AP<wchar_t> pWcs = new wchar_t[Wcslen];
UtlUtf8ToWcs(pUtf8, cbUtf8, pWcs.get(), Wcslen, pActualLen);
return pWcs.detach();
}
wchar_t* UtlUtf8ToWcs(const utf8_char* pUtf8, size_t* pActualLen)
/*++
Routine Description:
Convert utf8 string into unicode string.
Arguments:
pUtf8 - utf8 string to convert.
pActualLen - Receives the number of unicode caracters created.
Returned value:
Unicode reperesentation of the given utf8 string.
If the function failes because of invalid input - bad_utf8 exception
is thrown
Note:
It is the responsibility of the caller to call delete[] on returned pointer.
--*/
{
ASSERT(pUtf8 != NULL);
size_t len = UtlCharLen<utf8_char>::len(pUtf8) + 1;
AP<wchar_t> pWcs = new wchar_t[len];
UtlUtf8ToWcs(pUtf8, pWcs.get(), len, pActualLen);
return pWcs.detach();
}
void
UtlWcsToUtf8(
const wchar_t* pwcs,
size_t cbwcs,
utf8_char* pUtf8,
size_t cbUtf8,
size_t* pActualLen
)
/*++
Routine Description:
Convert unicode array (non null terminating) into utf8 string.
Arguments:
pwcs - Unicode string to convert.
cbwcs - Size in unicode characters of the array pwcs points to.
pUtf8 - Pointer to buffer that receives the utf8 converted caracters.
cbUtf8 - The size in bytes of the space that pUtf8 points to.
pActualLen - Receives the number of bytes created in utf8 format.
Returned value:
None
Note:
It is the responsibility of the caller to allocate buffer large enough
to hold the converted data + null termination. To be on the safe side - allocate buffer
that the number of bytes in it >= UtlWcsUtf8Len(pwcs) +1
--*/
{
const wchar_t* pwcsEnd = pwcs + cbwcs;
size_t index = 0;
for( ; pwcs != pwcsEnd; ++pwcs)
{
ASSERT(index < cbUtf8 - 1);
index += UtlWcToUtf8(*pwcs, &pUtf8[index], cbUtf8 - index );
}
ASSERT(index < cbUtf8);
pUtf8[index] = '\0';
if(pActualLen != NULL)
{
*pActualLen = index;
}
}
void
UtlWcsToUtf8(
const wchar_t* pwcs,
utf8_char* pUtf8,
size_t cbUtf8,
size_t* pActualLen
)
/*++
Routine Description:
Convert unicode string into utf8 string.
Arguments:
pwcs - Unicode string to convert.
pUtf8 - Pointer to buffer that receives the utf8 converted caracters.
cbUtf8 - The size in bytes of the space that pUtf8 points to.
pActualLen - Receives the number of bytes created in utf8 format.
Returned value:
None
Note:
It is the responsibility of the caller to allocate buffer large enough
to hold the converted data + null termination. To be on the safe side - allocate buffer
that the number of bytes in it >= UtlWcsUtf8Len(pwcs) +1
--*/
{
size_t index = 0;
for( ; *pwcs != L'\0'; ++pwcs)
{
ASSERT(index < cbUtf8 -1);
index += UtlWcToUtf8(*pwcs, &pUtf8[index], cbUtf8 - index );
}
ASSERT(index < cbUtf8);
pUtf8[index] = '\0';
if(pActualLen != NULL)
{
*pActualLen = index;
}
}
utf8_str
UtlWcsToUtf8(
const std::wstring& wcs
)
/*++
Routine Description:
Convert unicode stl string into utf8 stl string.
Arguments:
wcs - Unicode stl string to convert.
Returned value:
Stl utf8 string reperesentation of the given unicode string.
If the function failes because of invalid input - bad_utf8 exception
is thrown.
--*/
{
size_t len = UtlUtf8LenOfWcs(wcs.c_str()) +1 ;
utf8_str utf8(len ,' ');
size_t ActualLen;
UtlWcsToUtf8(wcs.c_str(), utf8.begin(), len, &ActualLen);
ASSERT(ActualLen == len -1);
utf8.resize(ActualLen);
return utf8;
}
utf8_str
UtlWcsToUtf8(
const wchar_t* pwcs,
size_t cbWcs
)
/*++
Routine Description:
Convert unicode buffer into utf8 stl string.
Arguments:
pwcs - pointer to buffer to convert
cbWcs - buffer length in unicode bytes
Returned value:
Stl utf8 string reperesentation of the given unicode string.
If the function failes because of invalid input - bad_utf8 exception
is thrown.
--*/
{
size_t len = UtlUtf8LenOfWcs(pwcs, cbWcs) +1;
utf8_str utf8(len ,' ');
size_t ActualLen;
UtlWcsToUtf8(pwcs, cbWcs, utf8.begin(), len, &ActualLen);
ASSERT(ActualLen == len -1);
utf8.resize(ActualLen);
return utf8;
}
std::wstring
UtlUtf8ToWcs(
const utf8_str& utf8
)
/*++
Routine Description:
Convert utf8 stl string into unicode stl string.
Arguments:
pUtf8 - utf8 string to convert.
Returned value:
Stl Unicode string reperesentation of the given utf8 string.
If the function failes because of invalid input - bad_utf8 exception
is thrown
--*/
{
return UtlUtf8ToWcs (utf8.c_str(), utf8.size());
}
std::wstring
UtlUtf8ToWcs(
const utf8_char* pUtf8,
size_t cbUtf8
)
/*++
Routine Description:
Convert utf8 array of bytes (non null terminating) into unicode stl string.
Arguments:
pUtf8 - utf8 string to convert.
cbUtf8 - The size in bytes of the array pUtf8 points to.
Returned value:
Stl Unicode string reperesentation of the given utf8 string.
If the function failes because of invalid input - bad_utf8 exception
is thrown
--*/
{
size_t len = cbUtf8 +1;
std::wstring wcs(len ,L' ');
ASSERT(wcs.size() == len);
size_t ActualLen;
UtlUtf8ToWcs(pUtf8, cbUtf8, wcs.begin(), len , &ActualLen);
ASSERT(ActualLen <= cbUtf8);
wcs.resize(ActualLen);
return wcs;
}
|
812d0b7844a7be971d3228e17be39dcd6a0cf962 | 32deed40f82700e2ab824ceea74ffe4ca9468132 | /SvGame/Source/SvGame/Private/Res/HitCheckSphereRes.cpp | d9950c8e946f7c5ea8a95ab1237ca5514b7d8043 | [] | no_license | renjihe/unreal_demo | 6304017d395bb3edf897163492a81bc6bc9e720d | ae14068f4e821bf4c9c1df1418c9b16e332a43a8 | refs/heads/master | 2020-07-12T04:25:52.659179 | 2019-08-27T15:02:39 | 2019-08-27T15:02:39 | 204,717,545 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,084 | cpp | HitCheckSphereRes.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "SvGame.h"
#include "HitCheckSphereRes.h"
#include <Runtime/XmlParser/Public/XmlFile.h>
HitCheckSphereRes& HitCheckSphereRes::Get()
{
static HitCheckSphereRes ins;
return ins;
}
HitCheckSphereRes::HitCheckSphereRes()
{
HitCheckSphereDataTable = LoadObject<UDataTable>(NULL, TEXT("/Game/Config/HitCheckSphere"));
HitCheckSphereDataTable->AddToRoot();
FHitCheckSphereRow *Row = HitCheckSphereDataTable->FindRow<FHitCheckSphereRow>(FName("0"), FString(""));
if (Row) {
DefaultRow = *Row;
}
else
{
TArray<FHitCheckSphereRow*> AllRow;
HitCheckSphereDataTable->GetAllRows(FString(""), AllRow);
if (AllRow.Num()) {
DefaultRow = *AllRow[0];
}
}
}
FHitCheckSphereRow& HitCheckSphereRes::GetHitCheckSphere(int HitCheckSphereID)
{
FHitCheckSphereRow *HitCheckSphere = HitCheckSphereDataTable->FindRow<FHitCheckSphereRow>(FName(*FString::FromInt(HitCheckSphereID)), FString(""));
if (nullptr == HitCheckSphere) {
HitCheckSphere = &DefaultRow;
}
return *HitCheckSphere;
} |
605a21c30b9f25bfbfb01d32e81a1753f2a56359 | bfcee910251df9c4b72207dc7fd8f04afa0da6b1 | /CSCI3132/Assignments/GroupProject/BLACKJACK/BLACKJACK/Dealer.cpp | 49e562e52cfab7363586300220a2a28d8c9fc652 | [] | no_license | Toyide/CSCI3132-C-Object-Orientation-and-Generic-Programming | 9d78d6ab2f3db5e5647653d36140e4260bf7d170 | 4a1eb5041a65641a89ecb145ef5219218c9f8494 | refs/heads/master | 2020-12-07T06:48:48.603107 | 2020-01-08T21:22:20 | 2020-01-08T21:22:20 | 232,662,162 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 743 | cpp | Dealer.cpp | /*
* Dealer.cpp
*/
#include "Dealer.h"
Dealer::Dealer() {
SYSTEM("Dealer was created by default");
}
Dealer::~Dealer() {
hand.clear();
}
// override virtual function from parent class
void Dealer::clearHand() {
hand.clear(); // clear hand cards for each turn
}
// override virtual function from parent class
void Dealer::Hit() {
Game game;
this->hand.push_back(game.getCard());
}
// override virtual function from parent class
int Dealer::CheckHand() {
int sum = 0;
int cardNum = 1;
SYSTEM("Dealer Hand:");
for (auto i : this->hand) {
if (i == 1 && sum + 11 <= 21)
i = 11;
SYSTEM("Card" << cardNum << ": " << i);
sum += i;
cardNum++;
}
SYSTEM("Total: " << sum);
return sum;
} |
0fdcf566e19b315013007fd98da112906eede4ea | 6783144064023cfa972bd0af50ac3fc1eb885fb5 | /AguacateMon.h | 380faa76b3724a02384ed22416aac8284b27f456 | [] | no_license | Noel-coder/P3Lab7_NoelMartinez | bac1e5820692d6d8af90b08a1e5e24c31285686a | 6d86c2b437c2d9380f2fa6296e988d1cfacf4bcb | refs/heads/master | 2023-03-17T16:32:50.915397 | 2021-03-06T00:28:51 | 2021-03-06T00:28:51 | 344,906,341 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 240 | h | AguacateMon.h | #ifndef AGUACATEMON_H
#define AGUACATEMON_H
#include "NokemonHierba.h"
#include <vector>
#include <string>
using namespace std;
class AguacateMon : public NokemonHierba
{
private:
public:
AguacateMon();
~AguacateMon();
};
#endif |
29e61a73f436ad8498d623b0b4ff09cd544f02b2 | facd5bdf6f1abf942957453f918a1ab78f2cf85a | /GeometrischeObjekte/GeometrischeObjekte/Rectangle.h | 6c3f638911bab7f4c013b7125b7730be6f9cb9bc | [] | no_license | M3IY0U/PAD2 | e1602efee246b11392758c439f689a51217c9710 | 6c42ee970ec04cd612f477ce09c5db3d06e526e6 | refs/heads/master | 2021-09-18T01:42:46.277733 | 2018-07-08T20:40:03 | 2018-07-08T20:40:03 | 130,972,745 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 314 | h | Rectangle.h | #pragma once
#include "Shape.h"
class Rectangle : public Shape
{
public:
Rectangle(double l, double w);
virtual ~Rectangle();
virtual double getArea() override;
virtual double getCircumference() override;
virtual double operator-(Shape& a) override;
private:
double length;
double width;
};
|
5f2b54c65d07f660aad81c2ff707a2dcd4693401 | a44d37d7cb7e79a44d3e4803791552a617fc9eec | /Bomberman/BrickableBlockComponent.h | a9c7f1ffafc622f920db2cbd68c437802fd5c245 | [] | no_license | florianPat/SFMLBomberman | 2a309bb2cdc55c53b89b3cecf46b4c4f057c0a79 | 939233ea9d35aa30fd241ea16976865ec5049ce6 | refs/heads/master | 2021-01-01T04:38:03.672478 | 2017-07-14T10:31:50 | 2017-07-14T10:31:50 | 97,214,772 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,279 | h | BrickableBlockComponent.h | #pragma once
#include "Component.h"
#include "Actor.h"
#include "Physics.h"
#include <vector>
#include <memory>
#include "SFML\Graphics.hpp"
#include "Assets.h"
#include "Animation.h"
class BrickableBlockComponent : public Component
{
sf::RenderTarget& renderTarget;
Physics& physics;
std::vector<sf::FloatRect> boundingBoxes;
std::vector<std::shared_ptr<Physics::Body>> bodies;
std::shared_ptr<sf::Texture> texture;
sf::Sprite sprite;
std::vector<std::pair<sf::FloatRect, Animation>> destroyBoundingBoxesAnimations;
private:
void eventEntitiyHitByBombHandler(EventData* eventData);
private:
std::function<void(EventData*)> eventEntitiyHitByBombFunction = std::bind(&BrickableBlockComponent::eventEntitiyHitByBombHandler, this, std::placeholders::_1);
static constexpr int delegateEntitiyHitByBombId = 0xd20a76ad;
DelegateFunction delegateCollectedAllDiamonds = std::make_pair(delegateEntitiyHitByBombId, eventEntitiyHitByBombFunction);
public:
static constexpr int COMPONENT_BRICKABLEBLOCK_ID = 0x3590dd31;
public:
BrickableBlockComponent(std::string& textureFileName, std::vector<sf::FloatRect>& boundingBoxes, Physics& physics, sf::RenderWindow& renderTarget, EventManager* eventManager, Actor* owner);
void update(float dt) override;
void draw() override;
}; |
1361fe0a4a057711a1141da1d5fcf0c46dcff192 | 04341d0b012ff2725d32e69a5a28590c91a61485 | /1task/base64.cpp | 476270aadea36231d7800116d85830582d6c9c40 | [] | no_license | iskislamov/kas | 63254e5e7886e93018b7b49d85040dd151677cba | 6db64fc02663364ad175d30fb22c50d69bd78bfd | refs/heads/master | 2020-04-09T04:42:16.586432 | 2018-12-04T09:24:28 | 2018-12-04T09:24:28 | 160,032,913 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,608 | cpp | base64.cpp | #include "base64.h"
#include "utf8.h"
#include <sstream>
static const int ASCII = 256;
static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
inline void decode_utf8(const std::string& bytes, std::wstring& wstr) {
utf8::utf8to32(bytes.begin(), bytes.end(), std::back_inserter(wstr));
}
inline void encode_utf8(const std::wstring& wstr, std::string& bytes) {
utf8::utf32to8(wstr.begin(), wstr.end(), std::back_inserter(bytes));
}
Exception::Exception(const std::string& message) {
message_ = message;
}
std::string Exception::what() const {
return message_;
}
Encoder::Encoder() {}
Encoder& Encoder::instance() {
static Encoder e;
return e;
}
std::string Encoder::encode(const std::string& str) {
if (str.size() == 0) {
return "";
}
std::vector<byte> data(str.size());
for (int i = 0; i < str.size(); ++i) {
data[i] = str[i];
}
return encode(&data[0], str.size());
}
std::string Encoder::encode(const std::wstring& wstr) {
std::string str;
encode_utf8(wstr, str);
return encode(str);
}
std::string Encoder::encode(const std::vector<byte>& data) {
return encode(&data[0], data.size());
}
std::string Encoder::encode(const byte* data, size_t size) {
std::stringstream stream;
size_t stream_size = 0;
int value = 0;
int shift = -6;
for (size_t i = 0; i < size; ++i) {
byte curr = *(data + i);
value = (value << 8) + curr;
shift += 8;
while (shift >= 0) {
stream << base64_chars[(value >> shift) & 0x3F];
++stream_size;
shift -= 6;
}
}
if (shift > -6) {
stream << base64_chars[((value << 8) >> (shift + 8)) & 0x3F];
++stream_size;
}
while (stream_size % 4) {
stream << '=';
++stream_size;
}
return stream.str();
}
Decoder::Decoder() {}
Decoder& Decoder::instance() {
static Decoder d;
return d;
}
std::string Decoder::decodeToASCII(const std::string& encoded_string) {
std::stringstream stream;
std::vector<int> alphabet(ASCII, -1);
int value = 0;
int shift = -8;
for (size_t i = 0; i < base64_chars.size(); ++i) {
alphabet[base64_chars[i]] = i;
}
for (size_t i = 0; i < encoded_string.size() && encoded_string[i] != '='; ++i) {
byte c = encoded_string[i];
if (alphabet[c] == -1) {
throw new Exception("Not a BASE64 string");
}
value = (value << 6) + alphabet[c];
shift += 6;
if (shift >= 0) {
stream << (char((value >> shift) & 0xFF));
shift -= 8;
}
}
return stream.str();
}
std::wstring Decoder::decodeToUTF(const std::string& encoded_string) {
std::wstring wstr;
decode_utf8(decodeToASCII(encoded_string), wstr);
return wstr;
} |
4e5c48904c3eca8c5c653c6953f57c1c6f6fd4b9 | 5525144908e55c5425377949fb7df8765c1d21c0 | /Forms/ODToolbarDef.h | 1b0097a4eff6c28799f6d3f39a07f0f07b75412c | [] | no_license | jongough/ocpn_draw_pi | 7800b80b371c9515805201e642c2d392b4fd4f6d | 4e12a45226f8935830a2a2f0a121edd0238fb308 | refs/heads/master | 2023-08-08T01:12:14.329011 | 2023-07-30T03:30:37 | 2023-07-30T03:30:37 | 29,998,842 | 5 | 27 | null | 2023-07-30T03:30:38 | 2015-01-29T02:03:31 | C++ | UTF-8 | C++ | false | false | 1,951 | h | ODToolbarDef.h | ///////////////////////////////////////////////////////////////////////////
// C++ code generated with wxFormBuilder (version 3.10.1-0-g8feb16b)
// http://www.wxformbuilder.org/
//
// PLEASE DO *NOT* EDIT THIS FILE!
///////////////////////////////////////////////////////////////////////////
#pragma once
#include <wx/artprov.h>
#include <wx/xrc/xmlres.h>
#include <wx/intl.h>
#include <wx/gdicmn.h>
#include <wx/toolbar.h>
#include <wx/font.h>
#include <wx/colour.h>
#include <wx/settings.h>
#include <wx/string.h>
#include <wx/sizer.h>
#include <wx/dialog.h>
#include "extra_formbuilder_headers.h"
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/// Class ODToolbarDialog
///////////////////////////////////////////////////////////////////////////////
class ODToolbarDialog : public wxDialog
{
private:
protected:
wxBoxSizer* m_bSizerToolbar;
// Virtual event handlers, override them in your derived class
virtual void OnActivate( wxActivateEvent& event ) { event.Skip(); }
virtual void OnClose( wxCloseEvent& event ) { event.Skip(); }
virtual void OnKeyDown( wxKeyEvent& event ) { event.Skip(); }
virtual void OnLeftDown( wxMouseEvent& event ) { event.Skip(); }
virtual void OnSize( wxSizeEvent& event ) { event.Skip(); }
public:
wxToolBar* m_toolBarODToolbar;
ODToolbarDialog();
ODToolbarDialog( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Draw Toolbar"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxCAPTION|wxCLOSE_BOX|wxRESIZE_BORDER|wxSTAY_ON_TOP );
bool Create( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Draw Toolbar"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( -1,-1 ), long style = wxCAPTION|wxCLOSE_BOX|wxRESIZE_BORDER|wxSTAY_ON_TOP );
~ODToolbarDialog();
};
|
e0b702b8f28156b18e64bf6509de6551d42d9885 | bb7ef3ddea766ce63126b849073ce0939e1b7f5a | /课程/数据结构/其他/示例代码/线性表的顺序表示.cpp | c04fe4fcde8543856dfe8099cf7c19795184ff85 | [] | no_license | OmniJax/SZU-resources | d11aa9d6e821ac953e277046f64ddc329c2bb318 | 6aa9eb75a0320bcb41bf25757d94856d9ed34803 | refs/heads/master | 2023-03-18T21:23:23.647456 | 2021-03-08T03:42:21 | 2021-03-08T03:42:21 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,964 | cpp | 线性表的顺序表示.cpp | #include <iostream>
using namespace std;
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
template <class T>
class Sqlist {
private:
T* elem;
int length;
int listsize;
public:
Sqlist() {
elem = new T[LIST_INIT_SIZE];
if (!elem) exit(-1);
length = 0;
listsize = LIST_INIT_SIZE;
}
~Sqlist() {
if (elem) delete elem;
}
int getLength() {
return length;
}
T getItem(int i) {
if (i>length || i<1) exit(-1);
else return elem[i - 1];
}
bool Insert(int i, T e) {
if (i<1 || i>length + 1) return false;
if (length >= listsize) {
T* newbase = new T[listsize + LISTINCREMENT];
if (!newbase) exit(OVERFLOW);
for (int j = 0; j<length; j++) newbase[j] = elem[j];
delete [] elem;
elem = newbase;
listsize += LISTINCREMENT;
} // 以上皆为准备阶段
T* q = &(elem[i - 1]); // 找到插入位置
for (T* p = &(elem[length - 1]); p >= q; --p)
*(p + 1) = *p; // 右移
*q = e;
++length;
return true;
} // ListInsert_Sq
bool Delete(int i) {
if (i<1 || i>length) return false;
T* p = &(elem[i - 1]); // 找到要删除的元素位置
T* q = elem + length - 1; // 找到最后一个元素位置
for (++p; p <= q; ++p)
*(p - 1) = *p; // 左移
--length; // 表长减1
return true;
} // ListDelete_Sq
bool isEmpty() {
if (length == 0) return true;
else return false;
}
int locateItem(T x) {
for (int i = 0; i<length; i++)
if (elem[i] == x) return i + 1;
return -1;
}
void Traverse() {
cout << "共有" << length << "个元素。" << endl;
for (int i = 0; i<length; i++)
cout << "第" << i + 1 << "个元素是:" << elem[i] << endl;
}
T* getElem() { return elem; }
void setLength(int i) { length = i; }
};
template<class T>
void MergeList(Sqlist<T>& la, Sqlist<T>& lb, Sqlist<T>& lc) {
T *pa = la.getElem(), *pb = lb.getElem(), *pc = lc.getElem();
lc.setLength(la.getLength() + lb.getLength());
while (pa <= la.getElem() + la.getLength() - 1 && pb <= lb.getElem() + lb.getLength() - 1) {
if (*pa <= *pb) { *pc++ = *pa++; }
else { *pc++ = *pb++; }
}
while (pa <= la.getElem() + la.getLength() - 1) *pc++ = *pa++;
while (pb <= lb.getElem() + lb.getLength() - 1) *pc++ = *pb++;
}
/*template<class T>
void MergeList(Sqlist<T>& la,Sqlist<T>& lb,Sqlist<T>& lc){
int i=0,j=0,k=1;
while(i<la.getLength()&&j<lb.getLength()){
if(la.getItem(i+1)<=lb.getItem(j+1)) {lc.Insert(k++,la.getItem(i+1));i++;}
else {lc.Insert(k++,lb.getItem(j+1));j++;}
}
while(i<la.getLength()) lc.Insert(k++,la.getItem(++i));
while(j<lb.getLength()) lc.Insert(k++,lb.getItem(++j));
}*/
void main() {
Sqlist<int> list1, list2, list3;
for (int i = 1; i <= 5; i++)
list1.Insert(i, i * 10);
for (int j = 1; j <= 5; j++)
list2.Insert(j, j * 3);
list1.Traverse();
list2.Traverse();
MergeList(list1, list2, list3);
list3.Traverse();
}
|
8b95feed6e6188ddab910c6c5bb9385c7581a3ac | 7e8d135d41ba27078bd51c4980252b6ce63d9be9 | /01_Math/02_Combinatorics/01.03.01_mod-pow.hpp | 533c4a39c137695bc27bc69211cfab0fc9e19c9c | [] | no_license | legosuke/lib | db4cf760cb9824a64c63bcf2f730796f25deff3d | 04f4f230845158d816877adf8d1e76d0f7b1ce30 | refs/heads/master | 2023-07-07T12:28:42.672454 | 2021-08-13T07:17:58 | 2021-08-13T07:17:58 | 321,906,930 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 349 | hpp | 01.03.01_mod-pow.hpp | #pragma once
#include <cstdint>
/**
* @brief 累乗 : $a^n\bmod{m}$
* @note O(log(m))
*/
std::uint32_t mod_pow(std::int64_t a, std::uint64_t n, std::uint32_t m) {
a = (a % m + m) % m;
std::uint64_t res = 1;
while (n) {
if (n & 1) (res *= a) %= m;
(a *= a) %= m;
n >>= 1;
}
return (std::uint32_t)res;
} |
dfac405bc592f9615007199820e2b79de5251518 | b8906afecca06f48f2cd289a9997f670b26c4721 | /lib/commonAPI/printing_zebra/ext/platform/wm/src/p2p/common/ResultConverter.h | 0ba46d666186983274c94892028a3192f4dafeb1 | [
"MIT"
] | permissive | rhomobile/rhodes | 51bd88921c51bd618948f9a557de17fc297e7cc2 | fc8409c9c281684a49d7ff6805ddc565de09a6d5 | refs/heads/master | 2023-09-01T17:45:36.149868 | 2023-08-31T20:56:06 | 2023-08-31T20:56:06 | 54,084 | 504 | 155 | MIT | 2023-09-12T00:14:29 | 2008-09-18T21:55:16 | C | UTF-8 | C++ | false | false | 1,205 | h | ResultConverter.h | // P2PClient.cpp : Defines the entry point for the console application.
//
#include <common/RhoStd.h>
#include "api_generator/MethodResult.h"
#include <algorithm>
namespace rho
{
namespace printing
{
template<typename T>
class ResultConverter
{
public:
static void convert(rho::apiGenerator::CMethodResult& result, const rho::String& value)
{
result.set(value);
}
};
template<>
class ResultConverter<bool>
{
public:
static void convert(rho::apiGenerator::CMethodResult& result, const rho::String& value)
{
rho::String resultFromServer;
std::transform(value.begin(), value.end(), std::back_inserter(resultFromServer), &tolower);
if (resultFromServer == "false")
{
result.set(false);
}
else if (resultFromServer == "true")
{
result.set(true);
}
else
{
result.set(resultFromServer);
}
}
};
template<>
class ResultConverter<int>
{
public:
static void convert(rho::apiGenerator::CMethodResult& result, const rho::String& value)
{
int intResult = atoi(value.c_str());
result.set(intResult);
}
};
} // printing
} // rho |
214f470c39cd54ebf9449680ccc651e047e451d4 | f29e561f2215f782fcb13122613fcaa66bbd5b7f | /cpp/collecting_coins.cpp | 337b998cd8964ba219356e0d76f08a0b2ca93492 | [] | no_license | kakabisht/practice_compi_coding | 46fbd3bcfc8c7a08026764e95a94bd8887b4a15c | 54746797658eae3a8b6be6d8673676d43bf4666b | refs/heads/main | 2023-08-31T04:33:56.955099 | 2021-10-13T05:38:10 | 2021-10-13T05:38:10 | 393,240,107 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 581 | cpp | collecting_coins.cpp |
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
long long int a, b, c, n;
cin >> a >> b >> c >> n;
long long int sum = a + b + c;
long long int ma = max(max(a, b), c);
long long int diffsum = 3 * ma - sum;
long long int m2 = n - diffsum;
if (m2 < 0)
cout << "NO" << '\n';
else
{
if (m2 % 3 == 0)
cout << "YES" << '\n';
else
cout << "NO" << '\n';
}
}
}
|
a566d03c713d47abd6c7b0328fe8cd091c43b14f | b0138f04fa27479bcec6e41e4c04c15513f04ac6 | /EndOfLevel/EndOfLevel/Game.cpp | c5a3df1312831de193c950b877e861e5c3f6f4f8 | [] | no_license | C00192781/EndOfLevel | bb55f1fa0de71331ffa098007784db083f8d983e | ad7e742ed7943517e21d3cdaabca0c01bb5fcf96 | refs/heads/master | 2021-09-05T11:40:01.928027 | 2018-01-26T21:34:47 | 2018-01-26T21:34:47 | 116,491,250 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,800 | cpp | Game.cpp | #include "Game.h"
#include <iostream>
using namespace std;
void Game::Initialize()
{
isRunning = true; // used for while loop in main
// Initialize SDL
SDL_Init(SDL_INIT_EVERYTHING);
// Create the window
window = SDL_CreateWindow("End of Level", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, window_width, window_height, SDL_WINDOW_SHOWN);
// retrieve window surface for surface
screen = SDL_GetWindowSurface(window);
/// <summary>
/// Renderer doesn't seem to be used for blitting
/// </summary>
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
rect.x = 0;
rect.y = 0;
rect.h = 1800;
rect.w = 2700;
kernelRadius = 1;
bloomMultiplier = 3;
}
void Game::Load()
{
myTexture.loadFromFile("ASSETS/texture.png", renderer);
SDL_Surface* optimizedSurface = NULL;
SDL_Surface* loadedSurface = IMG_Load("ASSETS/texture.png");
optimizedSurface = SDL_ConvertSurface(loadedSurface, screen->format, NULL);
// No longer need loadedSurface so we git rid of it
SDL_FreeSurface(loadedSurface);
stretchedSurface = optimizedSurface;
}
void Game::Update()
{
SDL_Event e;
while (SDL_PollEvent(&e) != 0)
{
if (e.type == SDL_KEYDOWN)
{
switch (e.key.keysym.sym)
{
case SDLK_r:
r += 8;
break;
case SDLK_t:
r -= 8;
break;
case SDLK_g:
g += 8;
break;
case SDLK_h:
g -= 8;
break;
case SDLK_b:
g += 8;
break;
case SDLK_n:
b -= 8;
break;
case SDLK_q:
bloomMultiplier++;
break;
case SDLK_o:
kernelRadius++;
cout << kernelRadius << endl;
break;
// Testing
case SDLK_l:
Uint32 *pixelArray = nullptr;
int totalPixels = myTexture.getTotalPixels();
pixelArray = new Uint32[totalPixels];
pixelArray = bloom.BrightPass(&myTexture, stretchedSurface, 1);
pixelArray = bloom.Blur(&myTexture, kernelRadius, totalPixels, stretchedSurface);
pixelArray = bloom.ApplyBloom(&myTexture, stretchedSurface, totalPixels, bloomMultiplier);
SDL_UpdateTexture(myTexture.getTexture(), &myTexture.getRect(), pixelArray, myTexture.getPitch());
break;
}
}
}
}
void Game::Render()
{
static float xPos = 310;
static float yPos = 310;
static float startWidth = 50;
static float startHeight = 50;
static float endWidth = 300;
static float endHeight = 300;
grow.Animation(&myTexture, screen, stretchedSurface, &stretchedRect, &xPos, &yPos, &startWidth, &startHeight, &endWidth, &endHeight, 3, 3);
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(renderer);
myTexture.setColour(r, g, b);
//SDL_RenderCopy(renderer, myTexture.getTexture(), NULL, &myTexture.getRect());
SDL_RenderCopyEx(renderer, myTexture.getTexture(), &rect, &stretchedRect, 0, NULL, SDL_FLIP_NONE);
SDL_RenderPresent(renderer);
} |
42c3997bb35ee1c3ba7153cd59f55b5b2604c79e | 34051601060d0c647482e5da20d8ab61906c7bd7 | /app/src/main/jni/CustomJNI.cpp | 39f1557a1fe971f52e6fbb98df57df4561b86dba | [] | no_license | AleksaJanjatovic/PNRS1_Projekat | 04325ca5e52bfc44959fff24af3c933695b6cf9e | b88fdda61f5d88e3ab22726908eebf664cb60e21 | refs/heads/master | 2020-05-04T17:57:43.892119 | 2019-05-31T08:34:47 | 2019-05-31T08:34:47 | 179,333,801 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 452 | cpp | CustomJNI.cpp | //
// Created by Aleksa on 31-May-19.
//
#include "CustomJNI.h"
extern "C" JNIEXPORT jdouble JNICALL Java_project_weatherforecast_CustomJNI_convert_1temperature
(JNIEnv *, jclass type, jdouble x, jint unit) {
{
//0 JE KONVERZIJA IZ FARENHAJT U CELZIJUS
if(unit == 0){
return (x - 32) * 5.0 / 9;
}
//1 JE KONVERZIJA IZ CELZIJUSA U FARENHAJT
return (x * 9) / 5.0 + 32;
}
} |
27f138517060653629f438f077f32f873ebb89a5 | 0134789707ac0c93ca85a871d17e997017b843c4 | /EventDisplay/EvdLayoutOptions_service.cc | db5399e03dcde40ceb36d815791139558b448ed2 | [] | no_license | vivekj99/garsoft | 6b455a34b928d9811f4646a35f53474ba0fd83db | 691760e03a8ee36451995815ed92e78b7701d126 | refs/heads/master | 2023-05-14T19:03:11.232400 | 2017-05-17T15:50:22 | 2017-05-17T15:50:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,194 | cc | EvdLayoutOptions_service.cc | ////////////////////////////////////////////////////////////////////////
/// \file EvdLayoutOptions_service.cc
///
/// \version $Id: EvdLayoutOptions_plugin.cc,v 1.1 2010/11/11 18:11:22 p-novaart Exp $
/// \author andrzejs@fnal.gov
// Framework includes
/// GArSoft includes
#include "EventDisplay/EvdLayoutOptions.h"
#include <iostream>
namespace gar {
namespace evd {
//......................................................................
EvdLayoutOptions::EvdLayoutOptions(fhicl::ParameterSet const& pset,
art::ActivityRegistry& /* reg */)
{
this->reconfigure(pset);
}
//......................................................................
EvdLayoutOptions::~EvdLayoutOptions()
{
}
//......................................................................
void EvdLayoutOptions::reconfigure(fhicl::ParameterSet const& pset)
{
fEnableMCTruthCheckBox = pset.get< int >("EnableMCTruthCheckBox");
}
}
namespace evd {
DEFINE_ART_SERVICE(EvdLayoutOptions)
} // namespace evd
}
////////////////////////////////////////////////////////////////////////
|
0913b47dc345ba35cd4c7179f09e34554a9fab38 | 049badc229edb18fb3eb64aaa4e838b0a0a4e6ad | /Source/TrafficSimulator/Network/RuneSocketSet.cpp | e4f714235e3a204fbaba769ccf12b5be52286f42 | [] | no_license | riemervdzee/TrafficSimulator | 0fc21f42ca8d546b794b170ffce7ad58bcd6c27f | 18e6a90113fffdd7de6b864e31094aa2a56b1b2b | refs/heads/master | 2020-05-18T05:04:25.897381 | 2013-01-16T15:00:36 | 2013-01-16T15:00:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,073 | cpp | RuneSocketSet.cpp | /*
* File: RuneSocketSet.cpp
* Author: Mark van der Wal
*
* Handles sets of sockets for activity
*
* Created on November 26, 2012, 1:21 PM
*/
#include <algorithm>
#include "RuneSocketSet.h"
namespace RuneSocket
{
RuneSocketSet::RuneSocketSet()
{
FD_ZERO( &m_set );
FD_ZERO( &m_readset );
FD_ZERO( &m_writeset );
FD_ZERO( &m_excepset );
}
void RuneSocketSet::AddSocket( const BaseSocket& p_sock )
{
// add the socket desc to the set
FD_SET( p_sock.GetSock(), &m_set );
// if linux, then record the descriptor into the vector,
// and check if it's the largest descriptor.
#ifndef WIN32
m_socketdescs.insert( p_sock.GetSock() );
#endif
}
void RuneSocketSet::RemoveSocket( const BaseSocket& p_sock )
{
FD_CLR( p_sock.GetSock(), &m_set );
#ifndef WIN32
// remove the descriptor from the vector
m_socketdescs.erase( p_sock.GetSock() );
#endif
}
} // end namespace RuneSocket |
3f3137d570c3a525f7d1f7ee1778477c0c53d032 | 2a366c33c240ad8a8c1fa35f14604b485fd32d98 | /main/cpp/End_Effector.cpp | 1bed7bded6655a634dee99b4b635df222487b191 | [] | no_license | team4243/code_2019 | c99126d07ab5a15469d24d7e252e6816efa09837 | fa0e2fc8b96fe189fdfdfcc03b2621578705a91e | refs/heads/master | 2020-04-20T13:19:40.293026 | 2019-03-02T01:04:10 | 2019-03-02T01:04:10 | 168,866,048 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,852 | cpp | End_Effector.cpp | /*************************************************************************************************/
/**** Includes ****/
#include "Excelsior_Classes.h"
#include "frc/WPILib.h"
#include "ctre/Phoenix.h"
#include <frc/Talon.h>
#include "frc/PWM.h"
#include <iostream>
/**** !!!!!!! TUNING VARIABLES !!!!!!! ****/
/*************************************************************************************************/
/**** !!!!!!! TUNING VARIABLES !!!!!!! ****/
// Enable Cargo Limit Switch
#define ENABLE_LIMIT_SWITCH_CARGO (false)
// Cargo Roller speed as Rotations Per Second (RPS) of output shaft, the setpoint of the PID controller
#define CARGO_ROLLER_SPEED (0.75)
// Speed to move Camera
#define CAMERA_TILT_STEP_AMOUNT (0.01)
// TalonSRX Configuration -- ENABLE
#define ROLLERS_WRITE_CONFIGURATION (false) // enabling bit to set configuration so we don't do it every time
// TalonSRX Configuration -- SET Values
#define ROLLERS_PEAK_OUTPUT_FWD (0.75) // In or out?
#define ROLLERS_PEAK_OUTPUT_REV (-0.35)
#define ROLLERS_PROPORTIONAL_CTRL (0.1)
#define ROLLERS_DERIVATIVE_CTRL (0.01)
#define ROLLERS_FEED_FWD_CTRL (0)
#define ROLLERS_RAMP_TIME (0) // Seconds to get from neutral to full speed (peak output)
#define ROLLERS_SLOT_IDX (0) // Which motor control profile to save the configuration to, 0 and 1 available
// Hatch Flower MAX/MIN values, 0->1
#define HATCH_FLOWER_MAX (1.0)
#define HATCH_FLOWER_MIN (0.2)
// Camera Tilt MAX/MIN values, 0->1
#define CAMERA_TILT_MAX (0.7)
#define CAMERA_TILT_MIN (0.2)
/*************************************************************************************************/
/**** Definitions ****/
// Rollers CAN device numbers
#define CARGO_ROLLER_DEVICENUMBER_LEADER (24)
#define CARGO_ROLLER_DEVICENUMBER_FOLLOWER (25)
// Hatch Flower Servo -- PWM Channel
#define HATCH_FLOWER_PWM_CHANNEL (1)
// Camera Tilt Servo -- PWM Channel
#define CAMERA_TILT_PWM_CHANNEL (2)
// End Effector Limit Switch -- DigitalIO Channel
#define LIMIT_SWITCH_CHANNEL (2)
// Converting to RPS for ToughBox output..
// .. and the bag motors will be different, but we can just leave this alone and tune the SPEED_RPS variable
#define CONVERT_TO_RPS_EE (1024)
/*************************************************************************************************/
/**** Object Declarations and Global Variables ****/
// Cargo Motor Drivers
WPI_TalonSRX Cargo_Roller_Leader{CARGO_ROLLER_DEVICENUMBER_LEADER};
WPI_TalonSRX Cargo_Roller_Follower{CARGO_ROLLER_DEVICENUMBER_FOLLOWER};
// End Effector -- Hatch Catch Servo
frc::PWM Hatch_Flower_Servo(HATCH_FLOWER_PWM_CHANNEL);
// End Effector -- Camera Tilt Servo
frc::PWM Camera_Tilt_Servo(CAMERA_TILT_PWM_CHANNEL);
//We are adding a limit switch to check to see if the cargo is firmly secured within the end effector
frc::DigitalInput End_Effector_Limit_Switch(LIMIT_SWITCH_CHANNEL);
double Camera_Tilt_Position = 0.0;
/*************************************************************************************************/
/**** Configuration ****/
void Excelsior_End_Effector::Configure_End_Effector()
{
// Set rotation direction, clockwise == false
Cargo_Roller_Leader.SetInverted(true);
if (ROLLERS_WRITE_CONFIGURATION)
{
Cargo_Roller_Leader.ConfigPeakOutputForward(ROLLERS_PEAK_OUTPUT_FWD);
Cargo_Roller_Leader.ConfigPeakOutputReverse(ROLLERS_PEAK_OUTPUT_REV);
Cargo_Roller_Leader.ConfigClosedloopRamp(ROLLERS_RAMP_TIME);
Cargo_Roller_Leader.Config_kP(ROLLERS_SLOT_IDX, ROLLERS_PROPORTIONAL_CTRL);
Cargo_Roller_Leader.Config_kD(ROLLERS_SLOT_IDX, ROLLERS_DERIVATIVE_CTRL);
Cargo_Roller_Leader.Config_kF(ROLLERS_SLOT_IDX, ROLLERS_FEED_FWD_CTRL);
}
Cargo_Roller_Follower.SetInverted(false);
Cargo_Roller_Follower.Follow(Cargo_Roller_Leader);
Hatch_Flower_Servo.SetPeriodMultiplier(frc::PWM::kPeriodMultiplier_2X);
Camera_Tilt_Servo.SetPeriodMultiplier(frc::PWM::kPeriodMultiplier_4X); // _4X == 50Hz, _2X == 100Hz, _1X == 200Hz
}
/*************************************************************************************************/
/**** Actions ****/
void Excelsior_End_Effector::Cargo_Roller_Action(bool dispense, double speed)
{
if (dispense)
Cargo_Roller_Leader.Set(ControlMode::PercentOutput, speed * CARGO_ROLLER_SPEED);
else if (!ENABLE_LIMIT_SWITCH_CARGO || !End_Effector_Limit_Switch.Get())
Cargo_Roller_Leader.Set(ControlMode::PercentOutput, -speed * CARGO_ROLLER_SPEED);
}
void Excelsior_End_Effector::Cargo_Roller_Manual(double speed)
{
Cargo_Roller_Leader.Set(ControlMode::PercentOutput, speed * CARGO_ROLLER_SPEED);
}
void Excelsior_End_Effector::Hatch_Flower_Action(bool extend)
{
if (extend)
Hatch_Flower_Servo.SetPosition(HATCH_FLOWER_MAX);
else
Hatch_Flower_Servo.SetPosition(HATCH_FLOWER_MIN);
}
void Excelsior_End_Effector::Camera_Tilt_Action(bool tiltUp)
{
if (tiltUp)
{
if ((Camera_Tilt_Position + CAMERA_TILT_STEP_AMOUNT) <= 1)
{
Camera_Tilt_Position += CAMERA_TILT_STEP_AMOUNT;
Camera_Tilt_Servo.SetPosition(Camera_Tilt_Position);
}
}
else
{
if ((Camera_Tilt_Position - CAMERA_TILT_STEP_AMOUNT) >= 0)
{
Camera_Tilt_Position -= CAMERA_TILT_STEP_AMOUNT;
Camera_Tilt_Servo.SetPosition(Camera_Tilt_Position);
}
}
}
/*************************************************************************************************/
/**** Helper Functions ****/
void Excelsior_End_Effector::Print_Roller_Encoders()
{
std::cout << "Roller: " << Cargo_Roller_Leader.GetSensorCollection().GetQuadraturePosition()
<< std::endl;
}
|
988024a3f6328091751624877bdc30129278257b | c62cb1790a9a7768cfe65c7996ef1962d4cc8760 | /include/cilantro/3rd_party/libqhullcpp/Qhull.h | 5348d55ece26489afe8debf6522053b19d9d29a2 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | kzampog/cilantro | 76f61a25e7bc00f5698495f2e7db4f9801e6b5c0 | 57ad1a397b73b6f4bbf9604fd75f8fe4363206a7 | refs/heads/master | 2023-09-06T00:02:19.389281 | 2023-08-15T21:31:46 | 2023-08-15T21:31:46 | 90,198,569 | 960 | 187 | MIT | 2019-12-26T22:39:25 | 2017-05-03T22:26:48 | C++ | UTF-8 | C++ | false | false | 6,746 | h | Qhull.h | /****************************************************************************
**
** Copyright (c) 2008-2020 C.B. Barber. All rights reserved.
** $Id: //main/2019/qhull/src/libqhullcpp/Qhull.h#5 $$Change: 2956 $
** $DateTime: 2020/05/23 21:08:29 $$Author: bbarber $
**
****************************************************************************/
#ifndef QHULLCPP_H
#define QHULLCPP_H
#include <cilantro/3rd_party/libqhullcpp/QhullPoint.h>
#include <cilantro/3rd_party/libqhullcpp/QhullVertex.h>
#include <cilantro/3rd_party/libqhullcpp/QhullFacet.h>
namespace orgQhull {
/***
Compile qhullcpp and libqhull with the same compiler. setjmp() and longjmp() must be the same.
#define QHULL_NO_STL
Do not supply conversions to STL
Coordinates.h requires <vector>. It could be rewritten for another vector class such as QList
#define QHULL_USES_QT
Supply conversions to QT
qhulltest requires QT. It is defined in RoadTest.h
#define QHULL_ASSERT
Defined by QhullError.h
It invokes assert()
*/
#//!\name Used here
class QhullFacetList;
class QhullPoints;
class QhullQh;
class RboxPoints;
#//!\name Defined here
class Qhull;
//! Interface to Qhull from C++
class Qhull {
private:
#//!\name Members and friends
QhullQh * qh_qh; //! qhT for this instance
Coordinates origin_point; //! origin for qh_qh->hull_dim. Set by runQhull()
bool run_called; //! True at start of runQhull. Errors if call again.
Coordinates feasible_point; //! feasible point for half-space intersection (alternative to qh.feasible_string for qh.feasible_point)
public:
#//!\name Constructors
Qhull(); //!< call runQhull() next
Qhull(const RboxPoints &rboxPoints, const char *qhullCommand2);
Qhull(const char *inputComment2, int pointDimension, int pointCount, const realT *pointCoordinates, const char *qhullCommand2);
~Qhull() throw();
private: //! Disable copy constructor and assignment. Qhull owns QhullQh.
Qhull(const Qhull &);
Qhull & operator=(const Qhull &);
private:
void allocateQhullQh();
public:
#//!\name GetSet
void checkIfQhullInitialized();
int dimension() const { return qh_qh->input_dim; } //!< Dimension of input and result
void disableOutputStream() { qh_qh->disableOutputStream(); }
void enableOutputStream() { qh_qh->enableOutputStream(); }
countT facetCount() const { return qh_qh->num_facets; }
Coordinates feasiblePoint() const;
int hullDimension() const { return qh_qh->hull_dim; } //!< Dimension of the computed hull
bool hasOutputStream() const { return qh_qh->hasOutputStream(); }
bool initialized() const { return (qh_qh->hull_dim>0); }
const char * inputComment() const { return qh_qh->rbox_command; }
QhullPoint inputOrigin();
bool isDelaunay() const { return qh_qh->DELAUNAY; }
//! non-const due to QhullPoint
QhullPoint origin() { QHULL_ASSERT(initialized()); return QhullPoint(qh_qh, origin_point.data()); }
QhullQh * qh() const { return qh_qh; }
const char * qhullCommand() const { return qh_qh->qhull_command; }
const char * rboxCommand() const { return qh_qh->rbox_command; }
int rotateRandom() const { return qh_qh->ROTATErandom; } //!< Return QRn for repeating QR0 runs
void setFeasiblePoint(const Coordinates &c) { feasible_point= c; } //!< Sets qh.feasible_point via initializeFeasiblePoint
countT vertexCount() const { return qh_qh->num_vertices; }
#//!\name Delegated to QhullQh
double angleEpsilon() const { return qh_qh->angleEpsilon(); } //!< Epsilon for hyperplane angle equality
void appendQhullMessage(const std::string &s) { qh_qh->appendQhullMessage(s); }
void clearQhullMessage() { qh_qh->clearQhullMessage(); }
double distanceEpsilon() const { return qh_qh->distanceEpsilon(); } //!< Epsilon for distance to hyperplane
double factorEpsilon() const { return qh_qh->factorEpsilon(); } //!< Factor for angleEpsilon and distanceEpsilon
std::string qhullMessage() const { return qh_qh->qhullMessage(); }
bool hasQhullMessage() const { return qh_qh->hasQhullMessage(); }
int qhullStatus() const { return qh_qh->qhullStatus(); }
void setErrorStream(std::ostream *os) { qh_qh->setErrorStream(os); }
void setFactorEpsilon(double a) { qh_qh->setFactorEpsilon(a); }
void setOutputStream(std::ostream *os) { qh_qh->setOutputStream(os); }
#//!\name ForEach
QhullFacet beginFacet() const { return QhullFacet(qh_qh, qh_qh->facet_list); }
QhullVertex beginVertex() const { return QhullVertex(qh_qh, qh_qh->vertex_list); }
void defineVertexNeighborFacets(); //!< Automatically called if merging facets or Voronoi diagram
QhullFacet endFacet() const { return QhullFacet(qh_qh, qh_qh->facet_tail); }
QhullVertex endVertex() const { return QhullVertex(qh_qh, qh_qh->vertex_tail); }
QhullFacetList facetList() const;
QhullFacet firstFacet() const { return beginFacet(); }
QhullVertex firstVertex() const { return beginVertex(); }
QhullPoints points() const;
QhullPointSet otherPoints() const;
//! Same as points().coordinates()
coordT * pointCoordinateBegin() const { return qh_qh->first_point; }
coordT * pointCoordinateEnd() const { return qh_qh->first_point + qh_qh->num_points*qh_qh->hull_dim; }
QhullVertexList vertexList() const;
#//!\name Methods
double area();
void outputQhull();
void outputQhull(const char * outputflags);
void prepareVoronoi(bool *isLower, int *voronoiVertexCount);
void runQhull(const RboxPoints &rboxPoints, const char *qhullCommand2);
void runQhull(const char *inputComment2, int pointDimension, int pointCount, const realT *pointCoordinates, const char *qhullCommand2);
double volume();
#//!\name Helpers
private:
void initializeFeasiblePoint(int hulldim);
};//Qhull
}//namespace orgQhull
#endif // QHULLCPP_H
|
f3529e5fd5bdb86cae31a0afa2a7a8687421b34e | 476f6405b08a5e3d4cfd8be29101143625af9d38 | /10844.cpp | 8ff6dfcfb90dd432bbf9b7f5a4864cffdc4ee72a | [] | no_license | DongJinNam/boj | 7e77b80b6c422d974eca722f78629d77bd7f60d4 | 1b4fbffc047f13e304ccb39b398d02b4867bf5cf | refs/heads/master | 2021-06-22T19:58:00.620117 | 2018-05-26T16:35:11 | 2018-05-26T16:35:11 | 96,141,902 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 707 | cpp | 10844.cpp | #include <stdio.h>
#define MAX 1000000000
unsigned long long dp[101][10]; // 행 : 자리수가 N일 때, 열 : 마지막 자리수. dp[N][M] N자리수를 가지고 마지막자리수가 M인 계단수의 개수
int main() {
int size;
int i, j;
unsigned long long result = 0;
scanf("%d", &size);
dp[1][0] = 0;
for (i = 1; i < 10; i++)
dp[1][i] = 1; // 한자리수 일 때는 모두 1로 초기화 (0 제외)
for (i = 2; i <= size; i++) {
for (j = 0; j < 10; j++) {
if (j > 0)
dp[i][j] += (dp[i - 1][j - 1] % MAX);
if (j < 9)
dp[i][j] += (dp[i - 1][j + 1] % MAX);
}
}
for (i = 0; i < 10; i++)
result += dp[size][i];
result %= MAX;
printf("%llu\n", result);
return 0;
} |
081bfa3906d1492ce04d9f5180dfd393d782c3c1 | 4969d1b65585c2778005852b6d7a7718d6e1d702 | /10025.cpp | 9fbb1db8de626b5cc4229831fc39dbd30e899e0d | [] | no_license | cartove/My-UVA-solutions | 64461d6ab5acde0f90dfb31a4c8e209628e3f0c3 | 471edb70b08112936810711c888452d0dcf0e72c | refs/heads/master | 2021-01-16T19:32:33.138516 | 2013-05-12T11:24:25 | 2013-05-12T11:24:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 970 | cpp | 10025.cpp | #include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <cctype>
#define max(x,y) ((x) > (y) ? (x) : (y))
#define min(x,y) ((x) < (y) ? (x) : (y))
#define CLEAR(s) memset(&(s), 0, sizeof(s))
int main() {
int cases;
scanf("%d",&cases);
while(cases--) {
long long k;
scanf("%lld",&k);
if(k==0){
puts("3");
if(cases!=0)printf("\n");
continue;
}
k=abs(k);
long i=((-1 + sqrtl(1+8*k)) / 2),j=i*(i+1)/2;
if (j== k) {
printf("%ld\n",i);
if(cases!=0)printf("\n");
} else {
for(;; ++i) {
j=i*(i+1)/2;
if (j < k) continue;
if((j-k)%2==0) {
printf("%ld\n",i);
if(cases!=0)printf("\n");
break;
}
}
}
}
return 0;
}
|
95c3f7ee6b4cf534167377a6876d611f81a6f887 | 1f87571032231ae38b40e4fece60fb7c79879378 | /sketch_jul26b.ino | f42390e62a860cef03b82ef0fdb2dc33d4864f84 | [] | no_license | khamidn/manual-transpoter-robot-arduino | bf471a64c47110dc12068c1ff079af9618089bc6 | 69a44405d9f9b2ce37ed4b5c6d23bd5c018b0390 | refs/heads/master | 2023-03-28T13:30:50.211431 | 2021-03-27T10:42:22 | 2021-03-27T10:42:22 | 352,045,597 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,292 | ino | sketch_jul26b.ino |
#include <PS2X_lib.h>
#include <Servo.h>
//MOTOR BELAKANG//
#define dirka_bel 28
#define pwmka_bel 12
#define pwmki_bel 11
#define dirki_bel 26
//MOTOR DEPAN
#define dirka_dep 30
#define pwmka_dep 9
#define pwmki_dep 10
#define dirki_dep 32
//////////////////////////////PIN SERVO//////////////////////////////
Servo angkatKanan;
Servo jepitKanan;
Servo angkatKiri;
Servo jepitKiri;
Servo angkatBelakang;
Servo jepitBelakang;
PS2X ps2x;
int countJepitKanan=0,countJepitKiri=0,countAngkatKanan=0,countAngkatKiri=0;
int countR1=0, countR2=0,countL1=0;;
int error = 0;
byte type = 0;
byte vibrate = 0;
int set_pwm = 100,set_MaxPwm=255, pwm_belok=130,pwm_mundur=-180;
int RX,RY,LX,LY;
int L1,L2,R1,R2;
int tombol_atas,tombol_bawah,tombol_kanan,tombol_kiri;
int kotak,X,segitiga,bulet;
void motBel(int kiri, int kanan){
if(kiri>=0){digitalWrite(dirki_bel,LOW);}
else{digitalWrite(dirki_bel,HIGH);kiri=255+kiri;}
analogWrite(pwmki_bel,abs(kiri));
if(kanan>=0){digitalWrite(dirka_bel,LOW);}
else{digitalWrite(dirka_bel,HIGH);kanan=255+kanan;}
analogWrite(pwmka_bel,abs(kanan));
}
void motDep(int kiri, int kanan){
if(kiri>=0){digitalWrite(dirki_dep,LOW);}
else{digitalWrite(dirki_dep,HIGH);kiri=255+kiri;}
analogWrite(pwmki_dep,abs(kiri));
if(kanan>=0){digitalWrite(dirka_dep,LOW);}
else{digitalWrite(dirka_dep,HIGH);kanan=255+kanan;}
analogWrite(pwmka_dep,abs(kanan));
}
void setup(){
Serial.begin(57600);
pinMode(dirka_bel,OUTPUT);
pinMode(pwmka_bel,OUTPUT);
pinMode(pwmki_bel,OUTPUT);
pinMode(dirki_bel,OUTPUT);
pinMode(dirka_dep,OUTPUT);
pinMode(pwmka_dep,OUTPUT);
pinMode(pwmki_dep,OUTPUT);
pinMode(dirki_dep,OUTPUT);
jepitKanan.attach(2);
angkatKanan.attach(3);
angkatKiri.attach(6);
jepitKiri.attach(7);
angkatBelakang.attach(5);
jepitBelakang.attach(4);
angkatKiri.write(125);
angkatKanan.write(35);
jepitKanan.write(45);
jepitKiri.write(95);
angkatBelakang.write(35);
jepitBelakang.write(40);
//CHANGES for v1.6 HERE!!! **************PAY ATTENTION*************
delay(350);
error = ps2x.config_gamepad(52,51,53,50, true, true); //setup pins and settings: GamePad(clock, command, attention, data, Pressures?, Rumble?) check for error
if(error == 0){
Serial.println("Found Controller, configured successful");
}
else if(error == 1)
Serial.println("No controller found, check wiring, see readme.txt to enable debug. visit www.billporter.info for troubleshooting tips");
else if(error == 2)
Serial.println("Controller found but not accepting commands. see readme.txt to enable debug. Visit www.billporter.info for troubleshooting tips");
else if(error == 3)
Serial.println("Controller refusing to enter Pressures mode, may not support it. ");
//Serial.print(ps2x.Analog(1), HEX);
type = ps2x.readType();
switch(type) {
case 0:
Serial.println("Unknown Controller type");
break;
case 1:
Serial.println("DualShock Controller Found");
break;
}
}
void loop()
{
error = 0;type = 1;
ps2x.read_gamepad(false, vibrate);
RX=ps2x.Analog(PSS_RX); RY=ps2x.Analog(PSS_RY);
LX=ps2x.Analog(PSS_LX); LY=ps2x.Analog(PSS_LY);
L1=ps2x.Button(PSB_L1); L2=ps2x.Button(PSB_L2);
R1=ps2x.Button(PSB_R1); R2=ps2x.Button(PSB_R2);
tombol_atas=ps2x.Button(PSB_PAD_UP); tombol_bawah=ps2x.Button(PSB_PAD_DOWN);
tombol_kanan=ps2x.Button(PSB_PAD_RIGHT); tombol_kiri=ps2x.Button(PSB_PAD_LEFT);
kotak=ps2x.Button(PSB_PINK); bulet=ps2x.Button(PSB_RED);
X=ps2x.Button(PSB_BLUE); segitiga=ps2x.Button(PSB_GREEN);
if(((LX>=120) && (LX<=130)) && ((LY>=0) && (LY<=50))){ //ROBOT MAJU
Serial.println("Maju");
motDep(103,100);motBel(105,94);
}
else if(((LY> 240) && (LY<=255)) && ((LX>= 64) && (LX<= 192))){ //ROBOT MUNDUR
Serial.println("mundur");
motDep(-set_pwm,-set_pwm);motBel(-set_pwm,-set_pwm);
}
else if(((LX>=0) && (LX<=50)) && ((LY>=0) && (LY<=50))){
Serial.println("Serong maju ke kiri");
motDep(0,set_pwm+20);motBel(set_pwm+20,0);
}
else if(((LX>=150) && (LX<=255)) && ((LY>=0) && (LY<=50))){
Serial.println("Serong maju ke kanan");
motDep(set_pwm+20,0);motBel(0,set_pwm+10);
}
else if(((LY>=150) && (LY<=255)) && ((LX>=0) && (LX<=50))){
Serial.println("Serong mudur ke kiri");
motDep(-set_pwm-20,0);motBel(0,-set_pwm-10);
}
else if(((LY>=150) && (LY<=255)) && ((LX>=150) && (LX<=255))){
Serial.println("Serong mundur ke kanan");
motDep(0,-set_pwm-20);motBel(-set_pwm-20,0);
}
else if((LX > 192) && ((LY >= 64) && (LY <= 192))){
Serial.println("Geser ke kanan");
motDep(130,-128);motBel(-123,124);
}
else if((LX < 64) && ((LY >= 64) && (LY <= 192))){
Serial.println("Geser ke kiri");
motDep(-130,130);motBel(131,-130);
}
else if(((LY>=100 && LY<=140) && (LX>=100 && LX<=140))){
Serial.println("Diam");
motDep(0,0);motBel(0,0);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
if((RX > 192) && ((RY >= 64) && (RY <= 192))){
Serial.println("Putar ke kanan");
motDep(set_pwm,-set_pwm);motBel(set_pwm,-set_pwm);
}
else if((RX < 64) && ((RY >= 64) && (RY <= 192))){
Serial.println("Putar ke kiri");
motDep(-set_pwm,set_pwm);motBel(-set_pwm,set_pwm);
}
///////////////////////////////////////////////KENDALI GRIPPER////////////////////////////////////////////////////
if (ps2x.NewButtonState()) //will be TRUE if any button changes state (on to off, or off to on)
{
if(R2){
countR2++;
Serial.print(countR2);
delay(150);
if(countR2>=4){
countR2=0;
}
if(countR2==0){
angkatBelakang.write(35);
Serial.println(":Belakang Naik");
}
if(countR2==1){
angkatBelakang.write(135);
Serial.println(":Belakang Turun");
}
if(countR2==2){
jepitBelakang.write(145);
Serial.println(": Jepit Belakang Buka");
}
if(countR2==3){
jepitBelakang.write(40);
Serial.println(": Jepit Belakang Tutup");
}
}
if(R1){
countR1++;
Serial.print(countR2);
delay(150);
if(countR1>=4){
countR1=0;
}
if(countR1==0){
angkatKanan.write(35);
Serial.println(":Kanan Naik");
}
if(countR1==1){
angkatKanan.write(155);
Serial.println(":Kanan Turun");
}
if(countR1==2){
jepitKanan.write(145);
Serial.println(": Jepit Kanan Buka");
}
if(countR1==3){
jepitKanan.write(45);
Serial.println(": Jepit Kanan Tutup");
}
}
if(L1){
countL1++;
Serial.print(countL1);
delay(150);
if(countL1>=4){
countL1=0;
}
if(countL1==0){
angkatKiri.write(125);
Serial.println(": Kiri Naik");
}
if(countL1==1){
angkatKiri.write(20);
Serial.println(": Kiri Turun");
}
if(countL1==2){
jepitKiri.write(10);
Serial.println(": Jepit Kiri Buka");
}
if(countL1==3){
jepitKiri.write(98);
Serial.println(": Jepit Kiri Tutup");
}
}
}
delay(50);
}
|
136258cf5183c50668ecbaffc930c7cdce7e9ff6 | c1220a49523a33a18ca2a2c726cdbf4111d36b83 | /src/program/test/observer2.cpp | 00e0b89966c80fddbd5d6c93797f29d606ad7bc7 | [] | no_license | nigels-com/glt | 6c13c59e996e87107ab4c05cd758a919036ea0c0 | 3e5db250836308b08aa308891cf03c3758eb863f | refs/heads/master | 2021-05-15T01:24:11.703854 | 2016-11-13T07:45:54 | 2016-11-13T07:45:54 | 32,901,980 | 2 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,655 | cpp | observer2.cpp | #include <misc/observer.h>
#include <vector>
#include <cstdlib>
#include <iostream>
using namespace std;
/*
Subject-Observer Pattern Example
This example related to a spread-sheet consisting of
Cell objects that can be inter-dependent. Each cell is
both a potential subject and observer. Potentially,
a cyclic dependency can exist between a sequence of
cells.
In this example, each Cell stores a value (_val) and
CellSum cells also stores a list of other cells which
are summed to determine the value. CellSum is notified
whenever one of these cells is updated.
The implementation of subject-observer here does not
handle cyclic dependencies. Perhaps a new combined
Subject-Observer class can be designed to handle this
case.
*/
class Cell : public GltSubject
{
public:
Cell()
: _val(0.0)
{
}
void set(double val)
{
_val = val;
notify(this);
}
double _val;
};
class CellSum : public Cell, public GltObserver<Cell>
{
public:
void add(Cell *ptr)
{
observe(*ptr);
_cells.push_back(ptr);
}
void calc()
{
_val = 0.0;
for (uint32 i=0; i<_cells.size(); i++)
_val += _cells[i]->_val;
}
void OnNotify(const Cell *ptr)
{
calc();
cout << "Sum has been updated to " << _val << endl;
notify(this);
}
private:
vector<const Cell *> _cells;
};
int main(int argc,char *argv[])
{
Cell a,b,c;
CellSum sum;
sum.add(&a);
sum.add(&b);
sum.add(&c);
a.set(1.0);
b.set(1.0);
c.set(1.0);
return EXIT_SUCCESS;
}
|
96237277ffbbb6b7e61e3f7aa090f7c4056c1e50 | 8447d06d0d5da3db2b3aae926ec66409b38fb140 | /3rdPartLib/g2o/g2o/types/slam3d/edge_se3_pointxyz_depth.cpp | 2f9477e6e92879104481e150f3bb23b5f0c26dae | [
"GPL-3.0-or-later",
"LGPL-3.0-or-later",
"BSD-3-Clause",
"GPL-1.0-or-later",
"BSD-2-Clause"
] | permissive | HKPolyU-UAV/FLVIS | 60d0fecac6e10eb19a131d589a5c0ddf89198157 | 4ad31bbe5191ae2763c70a641c31337b1e06c9e2 | refs/heads/master | 2023-07-21T11:11:05.885918 | 2023-07-12T14:26:32 | 2023-07-12T14:26:32 | 197,144,164 | 145 | 37 | BSD-2-Clause | 2021-06-07T08:45:04 | 2019-07-16T07:33:55 | C++ | UTF-8 | C++ | false | false | 5,917 | cpp | edge_se3_pointxyz_depth.cpp | // g2o - General Graph Optimization
// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "edge_se3_pointxyz_depth.h"
namespace g2o {
using namespace g2o;
// point to camera projection, monocular
EdgeSE3PointXYZDepth::EdgeSE3PointXYZDepth() : BaseBinaryEdge<3, Vector3, VertexSE3, VertexPointXYZ>() {
resizeParameters(1);
installParameter(params, 0);
information().setIdentity();
information()(2,2)=100;
J.fill(0);
J.block<3,3>(0,0) = -Matrix3::Identity();
}
bool EdgeSE3PointXYZDepth::resolveCaches(){
ParameterVector pv(1);
pv[0]=params;
resolveCache(cache, (OptimizableGraph::Vertex*)_vertices[0],"CACHE_CAMERA",pv);
return cache != 0;
}
bool EdgeSE3PointXYZDepth::read(std::istream& is) {
int pid;
is >> pid;
setParameterId(0,pid);
// measured keypoint
Vector3 meas;
for (int i=0; i<3; i++) is >> meas[i];
setMeasurement(meas);
// don't need this if we don't use it in error calculation (???)
// information matrix is the identity for features, could be changed to allow arbitrary covariances
if (is.bad()) {
return false;
}
for ( int i=0; i<information().rows() && is.good(); i++)
for (int j=i; j<information().cols() && is.good(); j++){
is >> information()(i,j);
if (i!=j)
information()(j,i)=information()(i,j);
}
if (is.bad()) {
// we overwrite the information matrix
information().setIdentity();
information()(2,2)=10/_measurement(2); // scale the info by the inverse of the measured depth
}
return true;
}
bool EdgeSE3PointXYZDepth::write(std::ostream& os) const {
os << params->id() << " ";
for (int i=0; i<3; i++) os << measurement()[i] << " ";
for (int i=0; i<information().rows(); i++)
for (int j=i; j<information().cols(); j++) {
os << information()(i,j) << " ";
}
return os.good();
}
void EdgeSE3PointXYZDepth::computeError() {
// from cam to point (track)
//VertexSE3 *cam = static_cast<VertexSE3*>(_vertices[0]);
VertexPointXYZ *point = static_cast<VertexPointXYZ*>(_vertices[1]);
Vector3 p = cache->w2i() * point->estimate();
Vector3 perr;
perr.head<2>() = p.head<2>()/p(2);
perr(2) = p(2);
// error, which is backwards from the normal observed - calculated
// _measurement is the measured projection
_error = perr - _measurement;
// std::cout << _error << std::endl << std::endl;
}
void EdgeSE3PointXYZDepth::linearizeOplus() {
//VertexSE3 *cam = static_cast<VertexSE3 *>(_vertices[0]);
VertexPointXYZ *vp = static_cast<VertexPointXYZ *>(_vertices[1]);
const Vector3& pt = vp->estimate();
Vector3 Zcam = cache->w2l() * pt;
// J(0,3) = -0.0;
J(0,4) = -2*Zcam(2);
J(0,5) = 2*Zcam(1);
J(1,3) = 2*Zcam(2);
// J(1,4) = -0.0;
J(1,5) = -2*Zcam(0);
J(2,3) = -2*Zcam(1);
J(2,4) = 2*Zcam(0);
// J(2,5) = -0.0;
J.block<3,3>(0,6) = cache->w2l().rotation();
Eigen::Matrix<number_t,3,9,Eigen::ColMajor> Jprime = params->Kcam_inverseOffsetR() * J;
Vector3 Zprime = cache->w2i() * pt;
Eigen::Matrix<number_t,3,9,Eigen::ColMajor> Jhom;
Jhom.block<2,9>(0,0) = 1/(Zprime(2)*Zprime(2)) * (Jprime.block<2,9>(0,0)*Zprime(2) - Zprime.head<2>() * Jprime.block<1,9>(2,0));
Jhom.block<1,9>(2,0) = Jprime.block<1,9>(2,0);
_jacobianOplusXi = Jhom.block<3,6>(0,0);
_jacobianOplusXj = Jhom.block<3,3>(0,6);
}
bool EdgeSE3PointXYZDepth::setMeasurementFromState(){
//VertexSE3 *cam = static_cast<VertexSE3*>(_vertices[0]);
VertexPointXYZ *point = static_cast<VertexPointXYZ*>(_vertices[1]);
// calculate the projection
const Vector3& pt = point->estimate();
Vector3 p = cache->w2i() * pt;
Vector3 perr;
perr.head<2>() = p.head<2>()/p(2);
perr(2) = p(2);
_measurement = perr;
return true;
}
void EdgeSE3PointXYZDepth::initialEstimate(const OptimizableGraph::VertexSet& from, OptimizableGraph::Vertex* /*to_*/)
{
(void) from;
assert(from.size() == 1 && from.count(_vertices[0]) == 1 && "Can not initialize VertexDepthCam position by VertexTrackXYZ");
VertexSE3 *cam = dynamic_cast<VertexSE3*>(_vertices[0]);
VertexPointXYZ *point = dynamic_cast<VertexPointXYZ*>(_vertices[1]);
const Eigen::Matrix<number_t, 3, 3, Eigen::ColMajor>& invKcam = params->invKcam();
Vector3 p;
p(2) = _measurement(2);
p.head<2>() = _measurement.head<2>()*p(2);
p=invKcam*p;
point->setEstimate(cam->estimate() * (params->offset() * p));
}
}
|
cd56646fcaa68e0204f4c20238b473771748dc67 | 96187cb1b203d621ff20abe0f13a5ece35c7de15 | /Codechef/SeptemberLong/FIBEASY.cpp | 59719a8f6795be4c3c41350283c019aab707c6e3 | [] | no_license | shadabshaikh0/Competitive-Programming | 7faa248513338f0af8b0ce651536dbe0b18aafe7 | 56d0723e69c750ac287feb76e1cf60e646910a83 | refs/heads/master | 2020-07-04T04:27:28.498903 | 2020-01-05T02:28:18 | 2020-01-05T02:28:18 | 202,155,410 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 647 | cpp | FIBEASY.cpp | #include<bits/stdc++.h>
#define ll unsigned long long int
#define RD(v,n) for(ll i =0;i<n;i++ ) cin>>v[i]
#define bolt ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
using namespace std;
#define MAX 60
int main()
{
bolt;
vector<ll> v;
v.push_back(0);
v.push_back(1);
for( ll i=2;i<MAX;i++ ){
v.push_back( ( v[i-1] + v[i-2] ) % 10 );
}
ll t;
cin>>t;
while(t--){
ll n;
cin>>n;
ll res = 1;
while( res < n ){
res = res * 2;
}
if( res != n ){
res = res /2;
}
cout<<v[(res-1)%60]<<"\n";
}
return 0;
} |
bc45903330c30ca7e61b8051778331bdf5162d7b | 19ccfd6806c5054679dab3f275822302206b222f | /src/game/client/swarm/vgui/asw_hudelement.h | de1f1cb88c2fbc6a1b92eb4f17917069bc4412bb | [
"Apache-2.0"
] | permissive | BenLubar/SwarmDirector2 | 425441d5ac3fd120c998379ddc96072b2c375109 | 78685d03eaa0d35e87c638ffa78f46f3aa8379a6 | refs/heads/master | 2021-01-17T22:14:37.146323 | 2015-07-09T19:18:03 | 2015-07-09T19:18:03 | 20,357,966 | 4 | 1 | Apache-2.0 | 2018-08-30T13:37:22 | 2014-05-31T15:00:51 | C++ | UTF-8 | C++ | false | false | 652 | h | asw_hudelement.h | #ifndef _INCLUDED_ASW_HUDELEMENT_H
#define _INCLUDED_ASW_HUDELEMENT_H
#ifdef _WIN32
#pragma once
#endif
#include "hudelement.h"
class CASW_HudElement : public CHudElement
{
public:
// DECLARE_CLASS_SIMPLE( CASW_HudElement, CHudElement );
CASW_HudElement( const char *pElementName );
// Return true if this hud element should be visible in the current hud state
virtual bool ShouldDraw( void );
protected:
/// simple convenience for printing unformatted text with a drop shadow
static void DrawColoredTextWithDropShadow( const vgui::HFont &font, int x, int y, int r, int g, int b, int a, char *fmt );
};
#endif //_INCLUDED_ASW_HUDELEMENT_H |
7c85b43789d600c103f269afc32a4af977e4a892 | 3527ff6346f98a5b7c51ce3c58428227f4bc8617 | /leetcode/cpp/5561.cpp | f2b77504404a28952175af89ada18522a8a92cc4 | [] | no_license | ShawnDong98/Algorithm-Book | 48e2c1158d6e54d4652b0791749ba05a4b85f96d | f350b3d6e59fd5771e11ec0b466f9ba5eeb8e927 | refs/heads/master | 2022-07-17T04:09:39.559310 | 2022-07-13T15:46:37 | 2022-07-13T15:46:37 | 242,317,482 | 0 | 0 | null | 2020-10-11T14:50:48 | 2020-02-22T09:53:41 | C++ | UTF-8 | C++ | false | false | 1,005 | cpp | 5561.cpp | #include <iostream>
#include <vector>
#include <algorithm>
typedef long long ll;
using namespace std;
class Solution {
public:
int getMaximumGenerated(int n) {
vector<int> num;
if(n==0){
return 0;
}
if(n==1){
return 1;
}
if(n>=2){
num.push_back(0);
num.push_back(1);
for(int i=2; i<(n+1); ++i){
if(i%2==0){
num.push_back(num[i/2]);
}
else{
num.push_back(num[(i-1)/2] + num[(i-1)/2 + 1]);
}
}
// for(int i=0; i<num.size(); ++i){
// cout << num[i] << endl;
// }
sort(num.begin(), num.end());
// cout << num[num.size()-1] << endl;
return num[num.size()-1];
}
return -1;
}
};
int main(){
Solution S;
cout << S.getMaximumGenerated(0) << endl;
return 0;
} |
ad905439dda574552fa40124d35add359201b2e7 | f5c303eaf682b13ab9bc8cea548774b50caafa01 | /configurator/cfgeditor.cpp | 0c582155e1d1b9b2a2f987f2938f86cb47aabb49 | [] | no_license | minerva-tech/vtrpk-arm-enc-app | 60ad8e877e08767f9b0bd7563e184436573bde4d | bf142b6584896f7d0a3998957df7638f5bd637bc | refs/heads/master | 2021-01-19T10:29:43.613214 | 2016-11-20T12:50:14 | 2016-11-20T12:50:14 | 16,434,788 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,025 | cpp | cfgeditor.cpp | #include "ext_headers.h"
#include "pchbarrier.h"
#include <QDebug>
#include <QFileDialog>
#include <QTextStream>
#include <QMessageBox>
#include "cfgeditor.h"
#include "ui_cfgeditor.h"
#include "progress_dialog.h"
#include "portconfig.h"
#include "comm.h"
#include "proto.h"
CfgEditor::CfgEditor(QWidget *parent) :
QWidget(parent),
ui(new Ui::CfgEditor)
{
ui->setupUi(this);
}
CfgEditor::~CfgEditor()
{
delete ui;
}
void CfgEditor::on_downloadCfg_clicked()
{
ProgressDialog progress(tr("Downloading encoder config"), QString(), 0, Client::get_enc_cfg_timeout.count(), this);
QString cfg_str = QString::fromStdString(Client::GetEncCfg(&progress));
this->ui->plainTextEdit->setPlainText(cfg_str);
progress.close();
}
void CfgEditor::on_uploadCfg_clicked()
{
Server::SendEncCfg(this->ui->plainTextEdit->toPlainText().toStdString());
}
void CfgEditor::on_loadCfg_clicked()
{
QFileDialog d;
d.setNameFilter("*.cfg");
d.setWindowTitle("Load encoder config file");
if (d.exec() == QDialog::Accepted && d.selectedFiles().size() == 1) {
QFile cfgfile(d.selectedFiles().at(0));
if (cfgfile.exists()) {
cfgfile.open(QIODevice::ReadOnly);
QTextStream stream(&cfgfile);
QString str = stream.readAll();
cfgfile.close();
this->ui->plainTextEdit->setPlainText(str);
}
}
}
void CfgEditor::on_saveCfg_clicked()
{
QFileDialog d;
d.setNameFilter("*.cfg");
d.setWindowTitle("Store encoder config file");
d.setConfirmOverwrite(true);
d.setLabelText(QFileDialog::Accept, "Save");
if (d.exec() == QDialog::Accepted && d.selectedFiles().size() == 1) {
QFile cfgfile(d.selectedFiles().at(0));
cfgfile.open(QIODevice::WriteOnly | QIODevice::Truncate);
QTextStream stream(&cfgfile);
stream << this->ui->plainTextEdit->toPlainText();
cfgfile.close();
}
}
|
2ce34cf4f4ad90f5940c6978356f5658b67b5fd1 | 08dc6bb8b91a717b3594512d93554ad8fb1e9cd6 | /1_ARDUINO/Arduino/AnalogPot/Sketch/Pot/Pot.ino | d41b740468e3ce9db5b97ddcab8a6ae891114cda | [] | no_license | mirkomancin/ArduinoLessons | 188e099f35000e44f6c493b300e01aea0fa13a82 | b5e7cf7ec10bf91fdff4ad2c6b6da7badd18590b | refs/heads/master | 2021-05-27T07:17:59.671403 | 2013-11-15T07:42:42 | 2013-11-15T07:42:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 254 | ino | Pot.ino | int pot = 3;
void setup() {
//NON ho bisogno di dichiarare la modalità del pin analogico
Serial.begin(9600);
}
void loop() {
//leggo il valore e lo scrivo sulla seriale
int sensorValue = analogRead(pot);
Serial.println(sensorValue, DEC);
}
|
5df786fade2649fbd9ae418b508de82360ef6934 | e3e76c7b01a369608c93bbd5286bc85f0e4cf62a | /Pointers/10.1/TestScores1.cpp | 81d750a809ef67b9fdb553fcea32347677bbfad6 | [] | no_license | aw-leigh/Cpp_Practice | 12c171aa14b07fa40656306c5fa1307ff97af729 | 8e5af8d957579c194a10109953317d5e45f8906f | refs/heads/master | 2020-04-08T14:20:31.355853 | 2019-02-12T04:09:08 | 2019-02-12T04:09:08 | 159,432,751 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,531 | cpp | TestScores1.cpp | /*
Write a program that dynamically allocates an array large enough to hold a user-defined number of test scores.
Once all the scores are entered, the array should be passed to a function that sorts them in ascending order.
Another function should be called that calculates the average score.
The program should display the sorted list of scores and averages with appropriate headings.
Use pointer notation rather than array notation whenever possible
*/
#include <iostream>
#include <algorithm>
using std::cin;
using std::cout;
using std::endl;
double calcAverage(double* array, int arrayLength);
void sortAscending(double* array, int arrayLength);
int validatePositiveInt(int &choice);
double validatePositiveDouble(double &choice);
int main()
{
int numberOfScores;
double score = 0;
cout << "How many scores would you like to enter? ";
cin >> numberOfScores;
validatePositiveInt(numberOfScores); //user must input a nonnegative integer
if (numberOfScores == 0)
return 0;
double* scoreArray = new double[numberOfScores]; //dynamically allocate array
for (int i = 0; i < numberOfScores; i++)
{
cout << "Enter score: ";
cin >> score;
validatePositiveDouble(score);
*(scoreArray + i) = score; //the assignment says to use pointer notation so I'm doing it, but scoreArray[i] is easier to understand
}
sortAscending(scoreArray, numberOfScores);
cout << "Scores in ascending order: " << endl;
for (int i = 0; i < numberOfScores; i++)
cout << *(scoreArray + i) << " ";
cout << endl << "Average score: " << endl << calcAverage(scoreArray, numberOfScores);
delete []scoreArray;
return 0;
}
double calcAverage(double* array, int arrayLength)
{
double temp = 0.0;
for (int i = 0; i < arrayLength; i++)
temp += *(array + i);
return temp/arrayLength;
}
void sortAscending(double* array, int arrayLength)
{
std::sort(array, array+arrayLength); //is it cheating to use std::sort? also this doesn't even need to be a function
}
int validatePositiveInt(int &choice)
{
while (!cin || choice < 0)
{
cout << "Please enter a nonnegative integer: ";
cin.clear();
cin.ignore(10000,'\n');
cin >> choice;
}
}
double validatePositiveDouble(double &choice)
{
while (!cin || choice < 0)
{
cout << "Please enter a nonnegative decimal or integer: ";
cin.clear();
cin.ignore(10000,'\n');
cin >> choice;
}
} |
c1bd98ac5ce593ab85a1ddfea13e5f0635414383 | f6f5735be942a0ed672baec1df6077480f60ac8d | /Uebung-2-Solveig-Andres-Eva-Maria-Paul/ub/Node.cpp | b3dc2bbef796711442d5394d7b2d1d7d50f88bf6 | [] | no_license | s9ep/Uebung4 | f81d3061aae17db1367258a0c375f7144452a960 | 4b5d6ba85470862c94923c544514f31e16b736d8 | refs/heads/master | 2021-01-13T01:23:41.620126 | 2014-11-24T22:46:26 | 2014-11-24T22:46:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,973 | cpp | Node.cpp | #include "Node.h"
#include "Sequence.h"
#include "Edge.h"
#include <string.h>
#include <iostream>
#include <string>
#include <stdio.h>
#include <cstring>
NucleicAcid n_s("");
/*
* Default - Konstruktor
*/
Node::Node():sequence_(n_s){
}
/*
* Copy - Konstruktor
*/
Node::Node(const Node& node):sequence_(node.sequence_),inedges(node.getInEdges()),outedges(node.getOutEdges()){
}
/*
* Detailed Konstruktor
*/
Node::Node(Sequence& sequence):sequence_(sequence){
}
/*
* Destruktor
*/
Node::~Node(){}
/*
* Zuweisungsoperatorator "="
*/
Node& Node::operator=(const Node& node){
sequence_= node.sequence_;
inedges=node.getInEdges();
outedges=node.getOutEdges();
return *this;
}
/*
* Operator "=="
*/
bool Node::operator==(const Node &node) const {
return ((sequence_==node.sequence_)&&(inedges==node.inedges)&&(outedges==node.outedges));
}
/*
* Operator "!="
*/
bool Node::operator!=(const Node &node) const {
return !((sequence_==node.sequence_)&&(inedges==node.inedges)&&(outedges==node.outedges));
}
/*
* Gibt die Liste aller ausgehenden Kanten zurueck
*/
std::vector<Edge> Node::getOutEdges() const {
return outedges;
}
/*
* Gibt die Liste aller eingehenden Kanten zurueck
*/
std::vector<Edge> Node::getInEdges() const {
return Node::inedges;
}
/*
* erstellt eine Kante von diesem zum uebergebenen Knoten mit korrekten Kantengewicht
*/
Edge Node::buildEdgeTo(Node& node){
Edge edge = *new Edge(*this,node); // neue Kante
outedges.push_back(edge);
//fuege neue Ausgehende Kante hinzu --> Kantengewicht wird in "Edge" autmatisch geupdatet
return edge;
}
/*
* falls eine ausgehende Kante zu node besteht, wird diese entfernt
*/
void Node::removeEdgeTo(Node& node){
outedges.erase(std::remove(outedges.begin(), outedges.end(), node), outedges.end());
}
Sequence& Node::getSequence(){
return sequence_;
}
std::ostream& operator<<(std::ostream& ostr, const Node&){
return ostr;
}
|
8c26a9bdbb647f389061f33b953c507a72f9dcf6 | 93becb0e207e95d75dbb05c92c08c07402bcc492 | /codeforces/cgr6/d.cpp | 894c0e7804400ec30bfb7290d310e2f2cfc26200 | [] | no_license | veqcc/atcoder | 2c5f12e12704ca8eace9e2e1ec46a354f1ec71ed | cc3b30a818ba2f90c4d29c74b4d2231e8bca1903 | refs/heads/master | 2023-04-14T21:39:29.705256 | 2023-04-10T02:31:49 | 2023-04-10T02:31:49 | 136,691,016 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,825 | cpp | d.cpp | #include <functional>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <string>
#include <vector>
#include <random>
#include <bitset>
#include <queue>
#include <cmath>
#include <stack>
#include <set>
#include <map>
typedef long long ll;
using namespace std;
const ll MOD = 1000000007LL;
typedef pair <int, ll> P;
int main() {
cin.sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
vector <ll> sm(n);
for (int i = 0; i < m; i++) {
int u, v;
ll d;
cin >> u >> v >> d;
u--; v--;
sm[u] += d;
sm[v] -= d;
}
vector <P> plus, minus;
for (int i = 0; i < n; i++) {
if (sm[i] > 0) {
plus.push_back(P(i, sm[i]));
} else if (sm[i] < 0) {
minus.push_back(P(i, -sm[i]));
}
}
int count = 0, p_idx = 0, m_idx = 0;
vector <vector<P>> ans(n);
while (true) {
if (p_idx == plus.size()) {
break;
}
count++;
int p_node = plus[p_idx].first;
int m_node = minus[m_idx].first;
ll p_val = plus[p_idx].second;
ll m_val = minus[m_idx].second;
if (p_val < m_val) {
ans[m_node].push_back(P(p_node, p_val));
minus[m_idx].second -= p_val;
p_idx++;
} else if (p_val > m_val) {
ans[m_node].push_back(P(p_node, m_val));
plus[p_idx].second -= m_val;
m_idx++;
} else {
ans[m_node].push_back(P(p_node, p_val));
p_idx++;
m_idx++;
}
}
cout << count << "\n";
for (int i = 0; i < n; i++) {
for (P p : ans[i]) {
cout << p.first + 1 << ' ' << i + 1 << ' ' << p.second << '\n';
}
}
return 0;
} |
895fcac16c6bfb33d77c6ed8cd53ac5fd39801df | 2ed2eab1052083cded0815c382fd3747477ad287 | /lastHomework/Subscribers.hpp | 2ebad2338317ef47021b9f51bf8e72ba0be270b3 | [] | no_license | lilyanagb/OOP | 7be635d7b303d0faf9438c5b8362886b219cc005 | 9db18e6d20efda91df254f216c317b2602007561 | refs/heads/main | 2023-08-14T12:54:37.742223 | 2021-09-22T14:24:46 | 2021-09-22T14:24:46 | 409,225,804 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 416 | hpp | Subscribers.hpp | #pragma once
#include "Message.hpp"
#include <string>
#include <vector>
using namespace std;
class Subscribers
{
public:
Subscribers(const string& id = "");
virtual ~Subscribers()=default;
string getID() const;
virtual void signal(const Message&)=0;
virtual int read() const=0;
virtual Subscribers* copy() const = 0;
protected:
vector<Message> messages;
private:
string id;
};
|
0cb3a82e0198a8eb781807426f54b2d508dfe772 | 6d549f4512c4e39c2a857d8e5b820f75c083df6d | /Source/Lady/HighScoreSave.cpp | a559202f66609daa1ccae60be21c865993c8d43f | [] | no_license | afletcher222/LadyGoldM | a5175eef1c5a1f456de0fb9957f1c74133bccd1d | c57fb1f780820a876e41c9176418b23d574c3285 | refs/heads/master | 2022-11-17T13:40:49.028818 | 2020-07-14T22:18:07 | 2020-07-14T22:18:07 | 276,931,354 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 194 | cpp | HighScoreSave.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "HighScoreSave.h"
UHighScoreSave::UHighScoreSave()
{
PlayerName = TEXT("HighScore");
UserIndex = 1;
} |
6d0586bc99b5f816e7664040469150b459ca61a8 | ae60fdf2d0c25faa679de7f37fb20522ce239835 | /c++book/chap2/4_1.cpp | 2de0d7b08df65f472a60b9426c33742cf4b93f67 | [] | no_license | hyomss/C-Study | 82b24ef36fb09ff6b7c77605f4ca369ec6a380e3 | 5be61243d9251a72ec6fd30ca50e6cfbf91ca8fc | refs/heads/master | 2020-05-30T05:02:23.573638 | 2019-05-31T07:55:19 | 2019-05-31T07:55:19 | 189,552,572 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 341 | cpp | 4_1.cpp | // c++ standard function 1
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char *a = "home";
cout << strlen(a) << endl;
char dest[10];
strcat_s(dest, sizeof(dest), a);
cout << dest << endl;
strcpy_s(dest, sizeof(dest), a);
cout << dest << endl;
cout << strcmp(dest, a) << endl;
return 0;
}
|
311373d4e0a917f765d2de5358700d354560ad0b | e32f725e33007f0db3af34318fc2ef7b7a754f99 | /c++/book_mayers/item_23_Rvalue_References_Move_Semantics_and_Perfect_Forwarding/Widget.hpp | 108b876939fea98a997113dd1be7666a07a19d5b | [] | no_license | gitkusiu/exercises | bc0517dab1f8de2d9c790cacb036928503d2bae9 | ccf3e51c2d90fde72a4a58f3dbbea8f384a84977 | refs/heads/master | 2023-04-24T07:52:19.731883 | 2021-05-12T07:14:56 | 2021-05-12T07:14:56 | 72,887,341 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 161 | hpp | Widget.hpp | #pragma once
#include <string>
class Widget {
public:
Widget();
Widget(Widget&& rhs);
private:
// static std::size_t moveCtorCalls;
std::string s;
}; |
575fa8178abb2c2c84c95161d4c6b5e5fdb309b1 | cb157512e2194e72adf07fc2291526d177371269 | /PQ/heap/test_PQ.cpp | 7d431775e786d2493613c9150e262a0648b7ecb0 | [] | no_license | hexu1985/general_algo | de30213462f8e091b53a782d31386af700469550 | 4797936bf81dcb489350812c95421a02aaaee223 | refs/heads/master | 2020-03-29T18:40:36.297849 | 2018-11-01T03:29:05 | 2018-11-01T03:29:05 | 150,226,005 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | cpp | test_PQ.cpp | #include <iostream>
#include "PQ.hpp"
using namespace std;
using namespace general_algo::heap;
int main(int argc, char *argv[])
{
const int maxN = 100;
PQ<int> pq(maxN);
int n;
int count = 0;
while (cin >> n) {
count++;
if (count > maxN)
break;
pq.insert(n);
}
cout << "pop all item from PQ:\n";
while (!pq.empty()) {
cout << pq.getmax() << "\n";
}
cout << endl;
return 0;
}
|
4c01f799c3bbf9ac2dd1964ea75173d3127b05c2 | e45e53f65f1417d0f0ffad8153025668c31231a7 | /blocking queue.h | 59bdbb74cc4c5ee76d9fe434e4110d67abf1288e | [] | no_license | nikanor97/concurrency | 0314ddbbf67d8dc1cbf2bc4261f129023719469e | 9108899e2cfe9bfb0e1eaee5b53dc5d748fbbb7d | refs/heads/master | 2021-08-26T06:40:10.605059 | 2017-11-21T22:52:23 | 2017-11-21T22:52:23 | 111,608,587 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,349 | h | blocking queue.h | //
// Created by nikita on 26.03.17.
//
#ifndef INC_3_W_BLOCKING_QUEUE_H
#define INC_3_W_BLOCKING_QUEUE_H
#endif //INC_3_W_BLOCKING_QUEUE_H
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <atomic>
#include <deque>
#include <stdexcept>
template <class T, class Container = std::deque<T>>
class BlockingQueue {
public:
explicit BlockingQueue(const size_t& cap){
capacity_ = cap;
}
void Put(T&& element){
std::unique_lock<std::mutex> lk(m_);
if (!power_){
throw std::runtime_error("Queue is turned off");
}
while (q_.size() == capacity_){
cvput_.wait(lk);
}
q_.push_back(std::move(element));
cvget_.notify_all();
}
bool Get(T& result){
std::unique_lock<std::mutex> lk(m_);
if (!power_ && q_.size() == 0) return false;
while (q_.size() == 0)
cvget_.wait(lk);
cvput_.notify_all();
result = std::move(q_.front());
q_.pop_front();
return true;
}
void Shutdown(){
std::unique_lock<std::mutex> lk(m_);
power_ = false;
cvput_.notify_all();
cvget_.notify_all();
}
private:
Container q_;
std::size_t capacity_;
std::condition_variable cvput_, cvget_;
std::mutex m_;
bool power_ = true;
};
|
ea1db8a8118c665c18ff01bb94730e5b13c6b2df | af75d3f56135742f48cd2607861a32033fd53980 | /电影节.cpp | 0d37ebd255dcda4051782739279c36efbcb3abe2 | [] | no_license | royalneverwin/Programming_Practice | 0f5f6ec570cba6ce16a4b7bb47206f50c1ecdbeb | c617efa2cf2b82ecbeda8f4b7e74470015c38bb0 | refs/heads/main | 2023-06-08T21:31:32.333734 | 2021-07-04T02:27:18 | 2021-07-04T02:27:18 | 350,348,227 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,052 | cpp | 电影节.cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//贪心算法,每次观看能观看的电影中结束时间最早的一场电影,这样就能观看到最多部电影
struct movie{
int start;
int end;
bool operator < (const struct movie &m) const{
return end < m.end;
}
};
vector<movie> Movie;
int main(){
int n;
int totalMovie;
int movieEnd;
cin >> n;
while(n != 0) {
totalMovie = 0;
movieEnd = 0;
Movie.clear();
for (int i = 0; i < n; i++) {//输入数据
struct movie tmp;
cin >> tmp.start >> tmp.end;
Movie.push_back(tmp);
}
sort(Movie.begin(), Movie.end());//按照电影结束时间排序
for(auto &i: Movie){
if(i.start >= movieEnd){//如果开始时间>=结束时间,就可以看电影
totalMovie += 1;
movieEnd = i.end;
}
}
cout << totalMovie << endl;
cin >> n;
}
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.