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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
729a7eb20d56e1c271635ebe845881bdb822a578 | 606a8c3a5d704814480586dfbf159cd828711c92 | /tools/stereo_split.cpp | 498006ad16045ff0161efe0ce04e60b5072e92b3 | [
"MIT"
] | permissive | CharlesAO/dsvo | a6f624292a54f9abb297a18d2f3097ac16c2c069 | a6d6f3a5377b472550fd3f48308adc701ed5c679 | refs/heads/master | 2020-04-14T10:44:38.584541 | 2018-12-22T17:56:45 | 2018-12-22T17:56:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,707 | cpp | stereo_split.cpp | #include "opencv2/opencv.hpp"
#include "ros/ros.h"
#include <image_transport/image_transport.h>
#include <opencv2/highgui/highgui.hpp>
#include <cv_bridge/cv_bridge.h>
#include <stdlib.h>
using namespace cv;
int main(int argc, char** argv)
{
VideoCapture cap(atoi(argv[1]));
if(!cap.isOpened())
return -1;
cap.set(cv::CAP_PROP_FRAME_WIDTH, 1344);
cap.set(cv::CAP_PROP_FRAME_HEIGHT, 376);
cap.set(cv::CAP_PROP_FPS, 100);
ros::init(argc, argv, "stereo_split");
ros::NodeHandle nh;
image_transport::ImageTransport it(nh);
image_transport::Publisher left_pub = it.advertise("/stereo/left/image_raw_color", 1);
image_transport::Publisher right_pub = it.advertise("/stereo/right/image_raw_color", 1);
// namedWindow("frame",1);
int counter=0;
ros::Rate loop_rate(20);
while (nh.ok())
{
Mat frame;
cap >> frame;
// imshow("frame", frame);
// std::cout<<frame.size()<<std::endl;
Mat left_frame = frame(Rect(0, 0, frame.cols/2, frame.rows));
Mat right_frame = frame(Rect(frame.cols/2, 0, frame.cols/2, frame.rows));
cvtColor(left_frame, left_frame, CV_RGB2GRAY);
cvtColor(right_frame, right_frame, CV_RGB2GRAY);
std_msgs::Header header;
header.seq = counter++;
header.stamp = ros::Time::now();
sensor_msgs::ImagePtr left_msg = cv_bridge::CvImage(header, "mono8", left_frame).toImageMsg();
sensor_msgs::ImagePtr right_msg = cv_bridge::CvImage(header, "mono8", right_frame).toImageMsg();
left_pub.publish(left_msg);
right_pub.publish(right_msg);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
|
9eaa6770543cede008bcd3fa79c2011c6ff9ea29 | 376b40b62f996ecc6665de0e0bc9735bf6a18268 | /src/tests/tangent.cpp | 0085fb2fd83372e3a60fbedc93e556bf2cddf4dc | [
"MIT"
] | permissive | PearCoding/PearRay | f687863b3bc722240997fb0b3d22e5032d91b7b8 | 95f065adb20fc6202dfa40140d0308fc605dc440 | refs/heads/master | 2022-05-02T01:01:28.462545 | 2022-04-13T09:52:16 | 2022-04-13T09:52:16 | 45,111,096 | 20 | 0 | MIT | 2020-06-22T11:32:21 | 2015-10-28T12:33:36 | C++ | UTF-8 | C++ | false | false | 3,979 | cpp | tangent.cpp | #include "math/Tangent.h"
#include "Test.h"
using namespace PR;
PR_BEGIN_TESTCASE(Tangent)
PR_TEST("Frame 1")
{
auto N = Vector3f(0, 0, 1);
Vector3f Nx, Ny;
Tangent::unnormalized_frame(N, Nx, Ny);
PR_CHECK_NEARLY_EQ(Nx, Vector3f(1, 0, 0));
PR_CHECK_NEARLY_EQ(Ny, Vector3f(0, 1, 0));
}
PR_TEST("Frame 2")
{
auto N = Vector3f(0, 1, 0);
Vector3f Nx, Ny;
Tangent::unnormalized_frame(N, Nx, Ny);
PR_CHECK_NEARLY_EQ(Nx, Vector3f(1, 0, 0));
PR_CHECK_NEARLY_EQ(Ny, Vector3f(0, 0, -1));
}
PR_TEST("Frame Perpendicular")
{
auto N = Vector3f(0, 1, 0);
Vector3f Nx, Ny;
Tangent::unnormalized_frame(N, Nx, Ny);
PR_CHECK_NEARLY_EQ(Nx.dot(N), 0);
PR_CHECK_NEARLY_EQ(Ny.dot(N), 0);
PR_CHECK_NEARLY_EQ(Nx.dot(Ny), 0);
}
PR_TEST("Align 1")
{
auto N = Vector3f(0, 0, 1);
auto V = Vector3f(0, 1, 0);
auto R = Tangent::align(N, V);
PR_CHECK_NEARLY_EQ(R, V);
}
PR_TEST("Align 2")
{
auto N = Vector3f(0, 1, 0);
auto V = Vector3f(0, 1, 0);
auto R = Tangent::align(N, V);
PR_CHECK_NEARLY_EQ(R, Vector3f(0, 0, -1));
}
PR_TEST("Align 3")
{
auto N = Vector3f(0, 0.5f, 0.5f).normalized();
auto V = Vector3f(0, 1, 0);
auto R = Tangent::align(N, V);
PR_CHECK_NEARLY_EQ(R, Vector3f(0, 0.5f, -0.5f).normalized());
}
PR_TEST("Align 4")
{
auto N = Vector3f(1, 0, 0);
auto V = Vector3f(0, 1, 0);
auto R = Tangent::align(N, V);
PR_CHECK_NEARLY_EQ(R, Vector3f(0, 1, 0));
}
PR_TEST("Align 5")
{
auto N = Vector3f(0, 1, 0);
auto V = Vector3f(0, 0, 1);
auto R = Tangent::align(N, V);
PR_CHECK_NEARLY_EQ(R, N);
}
/*PR_TEST("Align 6")
{
auto N = Vector3f(0, 0, -1);
auto V = Vector3f(0, 1, 0);
auto R = Tangent::align(N, V);
PR_CHECK_NEARLY_EQ(R, Vector3f(0, -1, 0));
}
PR_TEST("Align 7")
{
auto N = Vector3f(0, 0, -1);
auto V = Vector3f(1, 0, 0);
auto R = Tangent::align(N, V);
PR_CHECK_NEARLY_EQ(R, Vector3f(1, 0, 0));
}*/
PR_TEST("Align 8")
{
auto N = Vector3f(0, -1, 0);
auto V = Vector3f(0, 1, 0);
auto R = Tangent::align(N, V);
PR_CHECK_NEARLY_EQ(R, Vector3f(0, 0, 1));
}
PR_TEST("Space 1")
{
auto N = Vector3f(0, 0, 1);
auto Nx = Vector3f(1, 0, 0);
auto Ny = Vector3f(0, 1, 0);
auto V = Vector3f(0, 0, 1);
auto R = Tangent::toTangentSpace(N, Nx, Ny, V);
PR_CHECK_NEARLY_EQ(R, Vector3f(0, 0, 1));
}
PR_TEST("Space 2")
{
auto N = Vector3f(0, 0, 1);
auto Nx = Vector3f(1, 0, 0);
auto Ny = Vector3f(0, 1, 0);
auto V = Vector3f(1, 0, 0);
auto R = Tangent::toTangentSpace(N, Nx, Ny, V);
PR_CHECK_NEARLY_EQ(R, Vector3f(1, 0, 0));
}
PR_TEST("Space 3")
{
auto N = Vector3f(0, 0, 1);
auto Nx = Vector3f(1, 0, 0);
auto Ny = Vector3f(0, 1, 0);
auto V = Vector3f(0, 1, 0);
auto R = Tangent::toTangentSpace(N, Nx, Ny, V);
PR_CHECK_NEARLY_EQ(R, Vector3f(0, 1, 0));
}
PR_TEST("Space Reversibility 1")
{
auto N = Vector3f(0, 0, 1);
auto Nx = Vector3f(1, 0, 0);
auto Ny = Vector3f(0, 1, 0);
auto V = Vector3f(0, 1, 0);
auto T = Tangent::toTangentSpace(N, Nx, Ny, V);
auto R = Tangent::fromTangentSpace(N, Nx, Ny, T);
PR_CHECK_NEARLY_EQ(R, V);
}
PR_TEST("Space Reversibility 2")
{
auto N = Vector3f(1, 1, 0).normalized();
Vector3f Nx, Ny;
Tangent::unnormalized_frame(N, Nx, Ny);
auto V = Vector3f(0, 1, 0);
auto T = Tangent::toTangentSpace(N, Nx, Ny, V);
auto R = Tangent::fromTangentSpace(N, Nx, Ny, T);
PR_CHECK_NEARLY_EQ(R, V);
}
PR_TEST("Space Reversibility 3")
{
auto N = Vector3f(0, 0, 1);
auto Nx = Vector3f(1, 0, 0);
auto Ny = Vector3f(0, 1, 0);
auto V = Vector3f(0, 1, 0);
auto T = Tangent::fromTangentSpace(N, Nx, Ny, V);
auto R = Tangent::toTangentSpace(N, Nx, Ny, T);
PR_CHECK_NEARLY_EQ(R, V);
}
PR_TEST("Space Reversibility 4")
{
auto N = Vector3f(1, 1, 0).normalized();
Vector3f Nx, Ny;
Tangent::unnormalized_frame(N, Nx, Ny);
auto V = Vector3f(0, 1, 0);
auto T = Tangent::fromTangentSpace(N, Nx, Ny, V);
auto R = Tangent::toTangentSpace(N, Nx, Ny, T);
PR_CHECK_NEARLY_EQ(R, V);
}
PR_END_TESTCASE()
// MAIN
PRT_BEGIN_MAIN
PRT_TESTCASE(Tangent);
PRT_END_MAIN |
f81c07a952f95d0d208fe22e6b20435e45bdf44f | 9affd19b94eca661e537921b9873901942b2fda3 | /C++/Data Structures/Stack/Stack/StackUsingTemplate.cpp | 23bbb7100f2f4154e2622f2dd45b28c348293198 | [] | no_license | LeMinhTinh/Broblocks | 78183b997dcc872723c3a6997104beaeeca60d7b | 709ef03709b1f4bfdcd214dac98732bdc68b9bc3 | refs/heads/master | 2022-05-12T19:37:24.671990 | 2022-05-09T03:17:29 | 2022-05-09T03:17:29 | 120,144,616 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 488 | cpp | StackUsingTemplate.cpp | #include "stdafx.h"
#include "StackUsingTemplate.h"
template<class T>
StackUsingTemplate<T>::StackUsingTemplate()
{
top = -1;
arr = new[MAX];
}
template<class T>
void StackUsingTemplate<T>::Push(T t)
{
if (top >= MAX - 1)
{
cout << "Stack is full";
}
else
{
arr[++top] = t;
cout << "Element Push" << t;;
}
}
template<class T>
T StackUsingTemplate<T>::Pop()
{
if (top < 0)
{
cout << "Stack empty";
}
cout << "Element pop:" << arr[top--]<<endl;
return arr[top--];
} |
3283e2939d7d48850833092a686b435612850d06 | c26b2d68eab6ce8a7bcabaa61a0edcf067362aea | /vz03/src/macan.h | 97c2ce1f70a02c37f40ead6cc2ece75f653d628f | [] | no_license | reiva5/oop | b810f4c75f209eef631c2cf2cd26dfad284cd236 | 465c6075f2d2f16221c482bae9dbb4117c4a6398 | refs/heads/master | 2020-12-10T04:28:46.077254 | 2017-03-15T06:36:02 | 2017-03-15T06:36:02 | 83,626,249 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 876 | h | macan.h | #ifndef MACAN_H
#define MACAN_H
#include "include.h"
/** @class Macan
* Kelas Macan turunan dari Carnivore dan Karnivora
*/
class Macan: public Carnivore, public Karnivora {
public:
/** @brief Constructor.
* Menciptakan Macan dengan inisial 'M' dan ID i
* @param i Nilai Id Animal yang diciptakan
* @param x Posisi x Animal yang diciptakan
* @param y Posisi y Animal yang diciptakan
* @param massa berat Animal yang diciptakan
* @param jinak nilai jinak Animal yang diciptakan
*/
Macan(int i, int x, int y, int massa, bool jinak);
/** @brief Menampilkan aksi binatang ke layar
*/
void Interact();
/** @brief Melihat jumlah makanan dari binatang.
* Memanggil fungsi GetAmount parent Karnivora
* @return Jumlah makanan dari binatang.
*/
int GetJmlMakanan();
private:
string aksi;
const int rasio=12;
};
#endif |
7784592e4eaaa55a3dc0f8531d84209f86b9f631 | 6079670a82f3b92a3e6c6ed180aa498b78baca9a | /zmy/cpp/39.combination-sum.cpp | b24bf9a826e11901b8de9a1ff15c07f48b24c87e | [] | no_license | sing-dance-rap-basketball/leetcode | 97d59d923dfe6a48dd5adba3fa3137a684c0b3ca | d663d8093d4547ab1c6a24203255dba004b1e067 | refs/heads/master | 2022-08-07T15:17:47.059875 | 2022-07-23T15:59:36 | 2022-07-23T15:59:36 | 194,498,806 | 0 | 1 | null | 2019-07-12T08:28:39 | 2019-06-30T09:35:12 | C++ | UTF-8 | C++ | false | false | 671 | cpp | 39.combination-sum.cpp | /*
* @lc app=leetcode id=39 lang=cpp
*
* [39] Combination Sum
*/
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<vector<int>>> dp(target+1, vector<vector<int>>());
dp[0].push_back(vector<int>());
for(int i : candidates) {
for(int j = i; j<=target; j++) {
if(dp[j-i].size()>0){
auto tmp = dp[j-i];
for(auto &k : tmp)
k.push_back(i);
dp[j].insert(dp[j].end(), tmp.begin(), tmp.end());
}
}
}
return dp[target];
}
};
|
7d68263b25a1b9cf24aa360f54ee6a8679f95968 | 2f6c2872118a7b6df295174c2338fcd2afa6a1bc | /src/map/generators/test_maps.cpp | 2af5cf77352576eecb4e633e3209517120974757 | [
"MIT"
] | permissive | matteobarbieri/titan | 2ff020367eb6a000c09de6087b0e8233d42050a4 | e440f921ce165a7b1004a971b55d3ae63b145514 | refs/heads/master | 2021-07-11T19:23:12.792053 | 2020-08-27T15:34:32 | 2020-08-27T15:34:32 | 192,607,869 | 1 | 0 | MIT | 2020-08-20T09:02:52 | 2019-06-18T20:25:40 | C | UTF-8 | C++ | false | false | 2,225 | cpp | test_maps.cpp | #include <iostream>
// TODO check if file stays in place
#include "../GameMap.hpp"
#include "../../RenderOrder.hpp"
#include "../../libtcod.hpp"
#include "../../Entity.hpp"
// Components
#include "../../components/Stairs.hpp"
// Prefabs
#include "../../prefabs/enemies.hpp"
#include "../../prefabs/weapons/melee.hpp"
#include "../../prefabs/weapons/ranged.hpp"
namespace test_room {
/**
* Add a single immobile orc in the room
*/
void add_monsters(GameMap * level);
/**
* Add a dagger in the room
*/
void add_items(GameMap * level);
//GameMap generate_dungeon_level(width, height, min_room_length, max_room_length)
GameMap * generate_room(int width, int height)
{
GameMap * level = new GameMap(width, height);
level->dungeon_level = 1;
int xc = width/2;
int yc = height/2;
// Collect coordinates in a variable
//Rect xy(xc-10, yc-6, xc+10, yc+6);
Rect xy(xc-14, yc-10, xc+14, yc+10);
// Add room to level
Room * entry_room = new Room(xy, Direction::FourD());
level->add_part(entry_room);
// Add an external layer of walls to rooms
//std::cout << "Adding walls" << std::endl;
//level->add_walls();
// Populate Dungeon with entities
// Create and add entry stairs '<'
Stairs * up_stairs_component = new Stairs(level->dungeon_level - 1);
// Create entity object
Entity * up_stairs = new Entity(
xc, yc, '<',
TCODColor::white, "Stairs up", STAIRS);
// Add stairs component to entity
up_stairs->stairs = up_stairs_component;
level->add_entity(up_stairs);
// Monsters
//add_monsters(level);
// Add some items in the room
//add_items(level);
return level;
}
////////////////////////////////
/////// IMPLEMENTATIONS ////////
////////////////////////////////
void add_monsters(GameMap * level)
{
Entity * orc = make_orc(level->rooms[0]);
level->add_entity(orc);
}
// TODO implement
void add_items(GameMap * level)
{
//std::cout << "Implement add_items!" << std::endl;
//float a = 1/0;
int x = level->width/2 - 2;
int y = level->height/2 - 2;
Entity * dagger = make_dagger();
dagger->x = x;
dagger->y = y;
level->add_entity(dagger);
}
}
|
82ed2952cf81eda7f7b71a274430003218a827e7 | e4e5983a118cc1a89e688a18bf5a3a58c7eb7e79 | /AlgorithmicProblem/Solved/Books/Strategies/Strategies1/4/LinearTimeAlgorithm_Calc_MovingAverage_4_2.cpp | c4226f301e3e6eeed056624e45cf7d979d9e74de | [] | no_license | JaykayChoi/AlgorithmicProblem | 5c2375b48b49e13f9a82897510d2e1ee838b4a46 | a1a21bf95a4d7e8744887217c9e62378eb2f7a0e | refs/heads/master | 2021-09-06T02:13:02.549990 | 2018-02-01T15:50:05 | 2018-02-01T15:50:05 | 103,219,073 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,146 | cpp | LinearTimeAlgorithm_Calc_MovingAverage_4_2.cpp | #include <string>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class LinearTimeAlgorithm_Calc_MovingAverage_4_2
{
public:
void Solve()
{
vector<double> v;
v.push_back(10);
v.push_back(11);
v.push_back(12);
v.push_back(13);
v.push_back(14);
v.push_back(15);
vector<double> answer;
answer = movingAverage2(v, 3);
for_each(answer.begin(), answer.end(), [](double d)
{
cout << d << endl;
});
}
private:
#pragma region answer
vector<double> movingAverage1(const vector<double>& A, int M)
{
vector<double> ret;
int N = A.size();
for (int i = M - 1; i < N; ++i)
{
double partialSum = 0;
for (int j = 0; j < M; ++j)
{
partialSum += A[i - j];
}
ret.push_back(partialSum / M);
}
return ret;
}
vector<double> movingAverage2(const vector<double>& A, int M)
{
vector<double> ret;
int N = A.size();
double partialSum = 0;
for (int i = 0; i < M - 1; ++i)
partialSum += A[i];
for (int i = M - 1; i < N; ++i)
{
partialSum += A[i];
ret.push_back(partialSum / M);
partialSum -= A[i - M + 1];
}
return ret;
}
#pragma endregion
}; |
df897de6d90e419918c42e6bbc933a0f6f2f26ef | 3a399a7d866aad65a3d03b0710e4a517a88150d0 | /Laborator 4/RepositorySTL.h | 422c576349675237941db9d4182de58e8bc353c6 | [] | no_license | LauraDiosan-CS/lab04-MesesanAndrei | 66e26613b4f04b1a287ac50598ce2f18fafc73d7 | 0e8c67ffc5de6875b2fff4d37f39d8f5fe530796 | refs/heads/master | 2021-04-24T07:35:04.075681 | 2020-03-26T11:14:27 | 2020-03-26T11:14:27 | 250,101,494 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 376 | h | RepositorySTL.h | #pragma once
#include "Tranzactie.h"
#include <vector>
using namespace std;
class RepositorySTL {
private:
vector<Tranzactie> elem;
public:
RepositorySTL();
void addElem(Tranzactie);
bool findElem(Tranzactie);
void delElem(Tranzactie);
Tranzactie updateElem(Tranzactie);
Tranzactie getItemFromPos(int);
vector<Tranzactie> getAll();
int dim();
~RepositorySTL();
}; |
e6c7d91aa946a2932a08185e6fb131ece42331ab | 13739586a566a82b47b88f06a9ba7da61d9f167e | /LeetCode/637. Average of Levels in Binary Tree.cpp | d886727bc94784ea459a0291908dfe4b62e8e44a | [] | no_license | sajalagrawal/BugFreeCodes | d712e5a46fa62319b66b00977a157e4c1758273f | c1930a68bdc50619daefea7f7088b506dd921e4c | refs/heads/master | 2023-01-20T19:13:08.736719 | 2023-01-15T14:38:27 | 2023-01-15T14:38:27 | 56,171,988 | 5 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,802 | cpp | 637. Average of Levels in Binary Tree.cpp | //https://leetcode.com/problems/average-of-levels-in-binary-tree/
//DFS
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<pair<long,int>> levelData(10005, make_pair(0,0));
computeLevelSum(root, 0, levelData);
vector<double> averages;
for(int i=0; i<levelData.size();i++){
// cout<<levelData[i].first<<" "<<levelData[i].second<<endl;
if(levelData[i].second == 0)break;
averages.push_back((double)levelData[i].first/levelData[i].second);
}
return averages;
}
void computeLevelSum(TreeNode* node, int level, vector<pair<long,int>>& levelData){
if(node == NULL){
return;
}
levelData[level].first += node->val;
levelData[level].second++;
computeLevelSum(node->left, level+1, levelData);
computeLevelSum(node->right, level+1, levelData);
}
};
//BFS
vector<double> averageOfLevels(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
vector<double> averages;
while(!q.empty()){
double levelSum = 0;
int count = q.size();
for(int i=0;i<count;i++){
TreeNode* front = q.front();
q.pop();
levelSum += front->val;
if(front->left != NULL)q.push(front->left);
if(front->right != NULL)q.push(front->right);
}
averages.push_back(levelSum/count);
}
return averages;
} |
001349459403ee9036398ede69bcfa47ff737b20 | 6e732acde750b904e9eee94b33be978eba4d20c4 | /左移字符串.cpp | 746eccee9c6dabc4c1dfd608ef45033e1c0f0ee1 | [] | no_license | DoubleKing0625/SwordToOffer | 6b65229d47fec4a5b36b5f560fe910150dd61fce | cb335f45a2d95a82b9aea11dde304d9c4f575897 | refs/heads/master | 2020-03-07T04:00:48.617012 | 2018-11-06T14:16:16 | 2018-11-06T14:16:16 | 127,253,685 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,022 | cpp | 左移字符串.cpp | /*
* Created by Peng Qixiang on 2018/8/14.
*/
/*
* 左旋转字符串
* 对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。
* 例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。
*
*/
# include <iostream>
# include <string>
# include <queue>
using namespace std;
class Solution {
public:
string LeftRotateString(string str, int n) {
if(str.empty()) return str;
queue<char> tmp;
for(int i = 0; i < str.size(); i++){
tmp.push(str[i]);
}
for(int i = 0; i < n; i++){
char cur = tmp.front();
tmp.pop();
tmp.push(cur);
}
for(int i = 0; i < str.size(); i++){
str[i] = tmp.front();
tmp.pop();
}
return str;
}
//还可以三次翻转
};
int main(){
Solution s = Solution();
string test = "abcdef";
cout << s.LeftRotateString(test, 2) << endl;
return 0;
}
|
8d41eb1654bb69f57e8fa78cfa4cd0370ab06833 | 2a94d32043b7ca038528a98920b06f8006fea778 | /Task3/Visualization_of_one-dimensional_data_Reciver/widget.h | 439731a62b897f92effaa39277ba1feaf8a8311d | [] | no_license | turboSergik/Qt-data-exchanger | cc9d62e809ac1cd1f93c5bb73fe227505ca147f1 | ba3f092734c250a42cab3d5a5ec8748be286993e | refs/heads/master | 2022-11-26T06:57:52.705586 | 2020-07-31T11:52:19 | 2020-07-31T11:52:19 | 283,966,949 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,273 | h | widget.h | #ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QGraphicsView>
#include <QtWidgets>
#include <QtGui>
#include <QtCore>
#include <QTimer>
#include <QTime>
#include <QPair>
#include "udpsocket.h"
#include "receivingdatathread.h"
#include "datacontainer.h"
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
public slots:
void updateUI();
private:
Ui::Widget *ui;
QTimer* renderTimer;
protected:
void closeEvent(QCloseEvent *event) override;
void mousePressEvent(QMouseEvent *eventPress) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void wheelEvent(QWheelEvent *event) override;
void paintEvent(QPaintEvent *event) override;
void paintTimeLine();
QPair<float, float> getTruePointPosition(milliseconds x, float y, milliseconds timeNow);
UdpSocket* socket;
ReceivingDataThread* thread;
DataContainer* container;
QPointF mouseClickPosition;
bool isMove = false;
float move_x = 0;
float move_y = 0;
float scaleUIFactor = 0.01;
milliseconds lastYPoint;
};
#endif // WIDGET_H
|
1d66a344acee1f51d353e2ed7cb08525112e5ca2 | 5bd1134ac453aa7b035267d5c760511571bbcae8 | /include/gamelib/utils/CallbackHandler.hpp | 90f17ec0a8210c921eec858b8b24b5abce32f265 | [
"MIT"
] | permissive | mphe/GameLib | 32fb659dd711423ccd3a737d1964a53a9fa590cd | df4116b53c39be7b178dd87f7eb0fe32a94d00d3 | refs/heads/master | 2020-12-25T19:58:46.202111 | 2020-05-07T12:18:40 | 2020-05-07T12:18:40 | 43,610,821 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,730 | hpp | CallbackHandler.hpp | #ifndef CALLBACK_HANDLER_HPP
#define CALLBACK_HANDLER_HPP
#include <vector>
#include <algorithm>
#include <utility>
namespace gamelib
{
template <class Ret, class... Args>
class CallbackHandler
{
public:
typedef Ret (*CallbackFunction)(void*, Args...);
private:
struct CallbackInfo
{
void* me;
CallbackFunction callback;
inline CallbackInfo(void* me_, CallbackFunction callback_) :
me(me_),
callback(callback_)
{}
inline bool operator==(const CallbackInfo& ci) const
{
return me == ci.me && callback == ci.callback;
}
inline explicit operator bool() const
{
return callback;
}
};
public:
void regCallback(CallbackFunction callback, void* me);
// The entry won't be erased immediatelly, because it could damage the iterators in call().
// Instead it will be erased when calling clean() or when iterating over it inside call().
void unregCallback(CallbackFunction callback, void* me);
template <class... Args2>
void call(Args2&&... args);
void clear();
// Iterates through the list and removes every entry marked for removal
// DON'T CALL THIS INSIDE CALL() OR A KITTEN WILL DIE AND SEGFAULTS MAY RAIN UPON YOU!
void clean();
size_t size() const;
private:
std::vector<CallbackInfo> _callbacks;
};
}
#include "CallbackHandler.inl"
#endif
|
bbff2d34849d985ca6568d24814159dbd33dc7b1 | c8133d77d57b7c4fa61584b7a8a15f5923129a5e | /Test6.h | 58543dcec5213a5e1f7e0b8e2c549fcff17583de | [] | no_license | Fungungun/PCT | e6575a3268db33e9da4e12cbc6b093c8ae811a48 | f40f367472076bda9f25acb7d97b5b49c6223af4 | refs/heads/master | 2021-09-06T06:12:02.453896 | 2018-02-03T02:37:56 | 2018-02-03T02:37:56 | 81,433,955 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 433 | h | Test6.h | #ifndef __TEST_6_H__
#define __TEST_6_H__
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <omp.h>
#include <math.h>
#include <time.h>
#include <sstream>
#include <string>
#include <fstream>
#include "covImage.h"
#include "debug.h"
#include "utils.h"
#include "Cparticle.h"
#include "SParater.h"
using namespace std;
using namespace cv;
#endif
|
3b6187afc329619ad8ddce7135e6713022756220 | 0fbdba5f4372ddb01bb4ba69ba18ff26a9fb5d5d | /system/qplaylistitem.cpp | 0162df411adc4224ef48a5a4e5c68541b0f612fd | [] | no_license | dissonancedev/phonograph | fc47f1e0988949d4dbee8dc9fece161ce6708e74 | 1433407690b790d1896cfee769cfb51aa72f4319 | refs/heads/master | 2022-09-06T11:20:16.149679 | 2015-04-15T14:06:10 | 2015-04-15T14:06:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27 | cpp | qplaylistitem.cpp | #include "qplaylistitem.h"
|
d2120a993b8e1aa408a855e46cb7291848b5b16e | 40e15adb8a88a008abeaf314ad5d8cd722b092d4 | /CO2Sensor/CO2Sensor.ino | 9074825b5f4e1f6b22b3bfce89a7dc1f76263720 | [] | no_license | jalfarohi/ESP32_CO2 | 291c3f832cf19228e92d084f3b94b71489d3dd92 | 9fbc7f918dce8f610176592a46b577dedd19cb87 | refs/heads/main | 2023-03-16T00:05:13.737163 | 2021-03-02T18:10:27 | 2021-03-02T18:10:27 | 343,848,388 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,046 | ino | CO2Sensor.ino | // JORGE ALFARO
// Weather Station
// Obj: Sensar Temp, Hum, PresAt, Humedad Suelo, Caida agua y CO2
// Board info : NodeMCU -32S
// Load required libraries
#include <SoftwareSerial.h>
#include <WiFi.h>
#include <NTPClient.h> //Time sync used to add timestamp to message
#include <PubSubClient.h>
#include <MHZ.h>
#include "iot.h"
#include "conf.h"
#include <HardwareSerial.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#define BAUDRATE 9600 // Device to MH-Z19 Serial baudrate (should not be changed)
#define SEALEVELPRESSURE_HPA (1013.25)
Adafruit_BME280 bme; // I2C
// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 60000;
// WEB
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
// Create an Event Source on /events
AsyncEventSource events("/events");
String payload;
// variables to Store values
// String s_Temp, s_Hum, s_Pres, s_Luz, s_Piso, s_Agua;
float f_temp, f_pressu, f_altid, f_hum, f_luz, f_piso, f_agua;
int cont, i_co2_uart, i_co2_pwm;
unsigned long getDataTimer = 0;
// Replace with your network credentials
const char* ssid = "mired";
const char* password = "Eero1367!";
const int LuzPin = 32; // Luz
const int SoilPin = 35; // Hum tierra
const int AguaPin = 34; // Plub
#define CO2_IN 14
#define MH_Z19_RX 16 // D7
#define MH_Z19_TX 17 // D6
MHZ co2(MH_Z19_RX, MH_Z19_TX, CO2_IN, MHZ19B);
WiFiClientSecure secureClient = WiFiClientSecure();
PubSubClient mqttClient(secureClient);
IOT iotclient(secureClient, mqttClient);
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
void ReadBME()
{
f_temp = bme.readTemperature();
f_pressu = bme.readPressure() / 100.0F;
f_altid = bme.readAltitude(SEALEVELPRESSURE_HPA);
f_hum = bme.readHumidity();
}
// Leer CO2
void leerco2()
{
i_co2_uart = co2.readCO2UART();
Serial.print("PPMuart: ");
if (i_co2_uart > 0) {
Serial.print(i_co2_uart);
} else {
Serial.print("n/a");
}
i_co2_pwm = co2.readCO2PWM();
Serial.print(", PPMpwm: ");
Serial.print(i_co2_pwm);
}
// Leer humedad suelo
void leerSoil()
{
// leemos SOIL
f_piso = analogRead(SoilPin);
}
// Leer intensidad solar
void leerluz()
{
// leemos LUZ
f_luz = analogRead(LuzPin);
}
String processor(const String& var){
// f_temp, f_pressu, f_altid, f_hum, f_luz, f_piso, f_agua; i_co2_uart
if(var == "temp"){
return String(f_temp);
}
else if(var == "presion"){
return String(f_pressu);
}
else if(var == "altitud"){
return String(f_altid);
}
else if(var == "hum"){
return String(f_hum);
}
else if(var == "luz"){
return String(f_luz);
}
else if(var == "soil"){
return String(f_piso);
}
else if(var == "co2"){
return String(i_co2_pwm);
}
return String();
}
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<title>Weather Station</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<link rel="icon" href="data:,">
<style>
html {font-family: Arial; display: inline-block; text-align: center;}
p { font-size: 1.2rem;}
body { margin: 0;}
.topnav { overflow: hidden; background-color: #50B8B4; color: white; font-size: 1rem; }
.content { padding: 20px; }
.card { background-color: white; box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5); }
.cards { max-width: 800px; margin: 0 auto; display: grid; grid-gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }
.reading { font-size: 1.4rem; }
</style>
</head>
<body>
<div class="topnav">
<h1>Estacion de Clima </h1>
</div>
<div class="content">
<div class="cards">
<div class="card">
<p><i class="fas fa-thermometer" style="color:#00add6;"></i> Temperatura</p><p><span class="reading"><span id="temp">%temp%</span> °C</span></p>
</div>
<div class="card">
<p><i class="fas fa-weight-hanging" style="color:#e1e437;"></i> Presion</p><p><span class="reading"><span id="presion">%presion%</span> hPa</span></p>
</div>
<div class="card">
<p><i class="fas fa-mountain" style="color:#e1e437;"></i> Altura</p><p><span class="reading"><span id="altitud">%f_pressu%</span> mts</span></p>
</div>
<div class="card">
<p><i class="fas fa-tint" style="color:#e1e437;"></i> Humedad</p><p><span class="reading"><span id="hum">%hum%</span> </span></p>
</div>
<div class="card">
<p><i class="fas fa-sun" style="color:#e1e437;"></i> Int. Luminosa</p><p><span class="reading"><span id="luz">%luz%</span> </span></p>
</div>
<div class="card">
<p><i class="fas fa-cloud-rain" style="color:#e1e437;"></i> Humedad Suelo</p><p><span class="reading"><span id="soil">%soil%</span> </span></p>
</div>
<div class="card">
<p><i class="fas fa-fill-drip" style="color:#e1e437;"></i> CO2</p><p><span class="reading"><span id="co2">%co2%</span> ppm</span></p>
</div>
</div>
</div>
<script>
if (!!window.EventSource) {
var source = new EventSource('/events');
source.addEventListener('open', function(e) {
console.log("Events Connected");
}, false);
source.addEventListener('error', function(e) {
if (e.target.readyState != EventSource.OPEN) {
console.log("Events Disconnected");
}
}, false);
source.addEventListener('message', function(e) {
console.log("message", e.data);
}, false);
source.addEventListener('temp', function(e) {
console.log("temp", e.data);
document.getElementById("temp").innerHTML = e.data;
}, false);
source.addEventListener('presion', function(e) {
console.log("presion", e.data);
document.getElementById("presion").innerHTML = e.data;
}, false);
source.addEventListener('altitud', function(e) {
console.log("altitud", e.data);
document.getElementById("altitud").innerHTML = e.data;
}, false);
source.addEventListener('hum', function(e) {
console.log("hum", e.data);
document.getElementById("hum").innerHTML = e.data;
}, false);
source.addEventListener('luz', function(e) {
console.log("luz", e.data);
document.getElementById("luz").innerHTML = e.data;
}, false);
source.addEventListener('soil', function(e) {
console.log("soil", e.data);
document.getElementById("soil").innerHTML = e.data;
}, false);
source.addEventListener('co2', function(e) {
console.log("co2", e.data);
document.getElementById("co2").innerHTML = e.data;
}, false);
}
</script>
</body>
</html>)rawliteral";
void setup(){
// initialize serial port
Serial.begin(9600);
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
// Preheating CO2
if (co2.isPreHeating()) {
Serial.print("Preheating");
while (co2.isPreHeating()) {
Serial.print(".");
delay(5000);
}
Serial.println();
}
iotclient.setup();
iotclient.print_on_publish(true);
timeClient.begin();
// Inicia BME
if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
// Handle Web Server
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);
});
// Handle Web Server Events
events.onConnect([](AsyncEventSourceClient *client){
if(client->lastId()){
Serial.printf("Client reconnected! Last message ID that it got is: %u\n", client->lastId());
}
// send event with message "hello!", id current millis
// and set reconnect delay to 1 second
client->send("hello!", NULL, millis(), 10000);
});
server.addHandler(&events);
server.begin();
}
void loop()
{
if ((millis() - lastTime) > timerDelay) {
ReadBME();
leerSoil();
leerluz();
leerco2();
// f_temp, f_pressu, f_altid, f_hum, f_luz, f_piso, f_agua;
// "{ \"C02\":%s,\"TI\":%s,\"TE\":%s,\"Al\":%s}"
payload = "{\"time\":";
payload += timeClient.getEpochTime();
payload += ",\"Temp\":";
payload += String(f_temp).c_str();
payload += ",\"Hum\":";
payload += String(f_hum).c_str();
payload += ",\"Press\":";
payload += String(f_pressu).c_str();
payload += ",\"Luz\":";
payload += String(f_luz).c_str();
payload += ",\"soil\":";
payload += String(f_piso).c_str();
payload += ",\"CO2\":";
payload += String(i_co2_pwm).c_str();
payload += "}";
// sprintf(payload,dataBL,CO2,temp_int,temp_ext,Alco_Volt);
// const char dataBL[] = "C02:%c|TI:%c|TE:%c|Al:%c";
Serial.print("Topic:");
Serial.println(payload);
if (cont == 5) // Publicamos a AWS cada 5 Min.
{
if (iotclient.publish(TOPIC_NAME, (char*) payload.c_str() ))
{
Serial.println("Successfully posted");
}
else
{
Serial.println(String("Failed to post to MQTT"));
}
cont = 0;
}
cont = cont + 1;
// delay(10000); // Cada 10 Seg.
// Send Events to the Web Server with the Sensor Readings
events.send("ping",NULL,millis());
events.send(String(f_temp).c_str(),"temp",millis());
events.send(String(f_pressu).c_str(),"presion",millis());
events.send(String(f_altid).c_str(),"altitud",millis());
events.send(String(f_hum).c_str(),"hum",millis());
events.send(String(f_luz).c_str(),"luz",millis());
events.send(String(f_piso).c_str(),"soil",millis());
events.send(String(i_co2_pwm).c_str(),"co2",millis());
lastTime = millis();
}
}
|
3a8f04195c15c09ac329af4c9a2f6d4cb30c73fe | 1c1c1fed0952aeacb4ccd3ce9374f67f0e92cae6 | /EX1.cpp | af27a577305d0445a225cf847d019e947a759959 | [] | no_license | guipolicarpo/C | 1e0898de96b9fb9106dc5dc42c06f98d3d78f7a2 | acb61820d01993af7a574e0797c51be40be2aa4d | refs/heads/main | 2023-02-08T03:07:13.997048 | 2021-01-04T18:32:57 | 2021-01-04T18:32:57 | 326,767,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 467 | cpp | EX1.cpp | #include<stdio.h>
#include <stdlib.h>
#include <locale.h>
main(){
setlocale(LC_ALL, "Portuguese");
float dolar, imposto, reais;
printf("Digite o valor do produto em Dolar: ");
scanf("%f",&dolar);
reais=dolar*5.25;
imposto=reais*0.32;
printf("Valor em reais: %.2f\n",reais);
printf("Valor do Imposto: %.2f\n",imposto);
printf("Valor Final: %.2f\n",reais+imposto);
system("PAUSE");
}
|
1b559268e04e62e1859a404f4ff1a0c7eaabc9c2 | 1b187a33c25767a3eb0d0be6748c0b9b82251663 | /src/game/entities/particle_effect_component.h | 284c69d6fd62c1e7818f8b5bec6f1437134c5c8b | [
"MIT",
"Apache-2.0"
] | permissive | codeka/ravaged-planets | db7436ec8b4fdd3aa3e16754fa0c7fa05e4ddb13 | 018828e0bd84f77e055636ee711a95d1a3e1489b | refs/heads/master | 2023-05-15T06:43:37.014246 | 2023-05-01T17:05:47 | 2023-05-01T17:05:47 | 34,597,215 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,146 | h | particle_effect_component.h | #pragma once
#include <atomic>
#include <framework/math.h>
#include <game/entities/entity.h>
namespace fw {
class ParticleEffect;
}
namespace ent {
class PositionComponent;
// This component holds a bunch of ParticleEmitters, and allows an Entity to act as a particle emitter as well
// (basically, the ParticleEmitter follows the Entity around).
class ParticleEffectComponent: public EntityComponent {
private:
struct EffectInfo {
std::string name;
std::shared_ptr<fw::ParticleEffect> effect;
fw::Vector offset;
bool destroy_entity_on_complete;
bool started;
EffectInfo() : destroy_entity_on_complete(false), started(false) {
}
};
std::map<std::string, EffectInfo> effects_;
PositionComponent *our_position_;
public:
static const int identifier = 700;
ParticleEffectComponent();
virtual ~ParticleEffectComponent();
void apply_template(fw::lua::Value tmpl) override;
void initialize() override;
void update(float dt) override;
void start_effect(std::string const &name);
void stop_effect(std::string const &name);
virtual int get_identifier() {
return identifier;
}
};
}
|
d0bdadec4522bf148876012e2953fb570bee60fb | b5d8aff49b179101e6012991f4dba9b368092116 | /MRSlib/MRS/MRS_Algorithms_cpp/Source/MRS_Layer.cpp | b1bfaf70b4f9dd4c26b2327450dd460b8535c352 | [] | no_license | Redestroy/MRS | 2b5505114a58e76b5dbdc1b1107cf2cb44af14ea | a5d908c8d4a341670d4d3f6f0524026d758d1afa | refs/heads/master | 2023-08-19T10:04:57.067551 | 2021-07-23T00:24:17 | 2021-07-23T00:24:17 | 287,121,607 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,943 | cpp | MRS_Layer.cpp | #include "../Include/MRS_Layer.hpp"
namespace MRS {
namespace Algorithms {
void Layer::SetLayerState(LayerState state)
{
this->state = state;
if (debug) {
PrintState(state);
}
}
Layer::Layer() : Layer(false) {
}
Layer::Layer(bool debug)
{
this->debug = debug;
SetLayerState(LayerState::CREATEING);
Create();
SetLayerState(LayerState::CREATED);
}
Layer::~Layer()
{
Destroy();
}
void Layer::Create()
{
OnCreate();
}
void Layer::Init()
{
SetLayerState(LayerState::INITIALIZING);
OnInit();
SetLayerState(LayerState::INITIALIZED);
}
void Layer::Start()
{
SetLayerState(LayerState::STARTING);
OnStart();
SetLayerState(LayerState::STARTED);
Run();
}
void Layer::Run()
{
is_working = true;
while (is_working) {
SetLayerState(LayerState::PROCESSING);
Process();
SetLayerState(LayerState::PROCESSED);
PreUpdate();
SetLayerState(LayerState::UPDATING);
Update();
SetLayerState(LayerState::UPDATED);
PostUpdate();
}
}
void Layer::Stop()
{
is_working = false;
OnStop();
SetLayerState(LayerState::STOPPED);
}
void Layer::Pause()
{
is_working = false;
OnPause();
SetLayerState(LayerState::PAUSED);
}
void Layer::PreUpdate()
{
OnPreUpdate();
}
void Layer::Update()
{
OnUpdate();
}
void Layer::PostUpdate()
{
OnPostUpdate();
}
void Layer::Exit()
{
SetLayerState(LayerState::EXITING);
OnExit();
SetLayerState(LayerState::EXITED);
}
void Layer::Destroy()
{
OnDestroy();
}
LayerState Layer::GetLayerState()
{
return state;
}
bool Layer::GetDebug()
{
return debug;
}
void Layer::PrintState(LayerState state)
{
std::cout << "State: ";
switch (state) {
case LayerState::NEW:
std::cout << "NEW";
break;
case LayerState::CREATEING:
std::cout << "CREATEING";
break;
case LayerState::CREATED:
std::cout << "CREATED";
break;
case LayerState::INITIALIZING:
std::cout << "INITIALIZING";
break;
case LayerState::INITIALIZED:
std::cout << "INITIALIZED";
break;
case LayerState::STARTING:
std::cout << "STARTING";
break;
case LayerState::STARTED:
std::cout << "STARTED";
break;
case LayerState::PROCESSING:
std::cout << "PROCESSING";
break;
case LayerState::PROCESSED:
std::cout << "PROCESSED";
break;
case LayerState::UPDATING:
std::cout << "UPDATING";
break;
case LayerState::UPDATED:
std::cout << "UPDATED";
break;
case LayerState::PAUSED:
std::cout << "PAUSED";
break;
case LayerState::STOPPED:
std::cout << "STOPPED";
break;
case LayerState::EXITING:
std::cout << "EXITING";
break;
case LayerState::EXITED:
std::cout << "EXITED";
break;
default:
std::cout << "Error: No such state exists";
}
std::cout << "\n";
}
}
} |
16449c1cb1bf83a22657f8e36a927a3c552366e0 | 2291759d7908079a4cb37a99af3a0ca88518ab25 | /cpp/bst.h | 9836a6fce98f79de38d9a64bd829603f161650fe | [] | no_license | davides/ds-a-day | 8bfca2006574f171c7dbb805b51135b8496a17c9 | d60b2a8e2aa0f66d4a3b26b5ed990e447d4ae869 | refs/heads/master | 2021-01-10T11:53:24.206211 | 2016-02-04T06:12:11 | 2016-02-04T06:12:11 | 50,643,537 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 987 | h | bst.h | #include <cstdio>
using namespace std;
template <typename T>
class Bst {
public:
Bst(T value) : value_(value) { left_ = right_ = 0; }
~Bst() {
delete left_;
delete right_;
}
void insert(T value) {
if (value < value_) {
left_ = createOrInsert(left_, value);
} else if (value > value_) {
right_ = createOrInsert(right_, value);
}
}
bool contains(T value) {
if (value == value_) {
return true;
} else if (value < value_ && left_ != NULL) {
return left_->contains(value);
} else if (value > value_ && right_ != NULL) {
return right_->contains(value);
}
return false;
}
T value() { return value_; }
Bst<T>* left() { return left_; }
Bst<T>* right() { return right_; }
private:
Bst<T>* createOrInsert(Bst<T>* node, T value) {
if (!node) {
node = new Bst<T>(value);
} else {
node->insert(value);
}
return node;
}
T value_;
Bst<T>* left_;
Bst<T>* right_;
};
|
0cfea57c2281727f00b96ff384cb1a140ca69ef5 | 1006fb24c2c105b888c19766ffea0de70fe70fa0 | /homework-2/infix-to-postfix.cpp | c5984ebfd2d46ea48090c7cd5cf114102d8365cf | [] | no_license | marcos-bah/maratona-programacao | 1beba584ce91fbde9451ae3e479124bc879b3434 | cf98f9bc4a4e0ed9bd3870979e8236d29d2e1170 | refs/heads/main | 2023-08-22T00:06:39.921973 | 2021-10-27T20:27:33 | 2021-10-27T20:27:33 | 411,766,790 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,348 | cpp | infix-to-postfix.cpp | #include <bits/stdc++.h>
using namespace std;
map<char, int> op;
void sieve()
{
op['+'] = 1;
op['-'] = 1;
op['/'] = 2;
op['*'] = 2;
op['^'] = 3;
}
void infixToPostfix(string str)
{
stack<char> q;
for (int i = 0; i < str.length(); i++)
{
if (isalnum(str[i]))
cout << str[i];
else if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/' ||
str[i] == '^')
{
if (!q.empty())
{
while (op[str[i]] <= op[q.top()])
{
cout << q.top();
q.pop();
if (q.empty())
break;
}
}
q.push(str[i]);
}
else if (str[i] == '(')
{
q.push('(');
//cout<<"first";
}
else if (str[i] == ')')
{
while (q.top() != '(')
{
cout << q.top();
q.pop();
}
q.pop();
}
}
while (!q.empty())
{
cout << q.top();
q.pop();
}
cout << endl;
}
int main()
{
sieve();
int t;
cin >> t;
cin.ignore();
string str;
while (t--)
{
cin >> str;
infixToPostfix(str);
}
return 0;
} |
72bf35eaed70719024a44873e1f222ca60a2c6e2 | ff86d33523e9887f04a2b70d08d9e07c254bdc6e | /include/ensmallen_bits/problems/goldstein_price_function.hpp | 9c0db792e4e799fb2c6a1aae921fd37c206b1c8d | [
"BSD-3-Clause",
"BSL-1.0"
] | permissive | mlpack/ensmallen | 3a880d4276a9038d43702bb6a6ff35a0cf25a1a3 | b97c8b08e25b96be53a0efcadbe9bed0c29aa276 | refs/heads/master | 2023-09-04T07:35:08.481001 | 2023-09-01T20:51:06 | 2023-09-01T20:51:06 | 151,348,135 | 654 | 152 | NOASSERTION | 2023-09-01T20:51:07 | 2018-10-03T01:53:06 | C++ | UTF-8 | C++ | false | false | 4,096 | hpp | goldstein_price_function.hpp | /**
* @file goldstein_price_function.hpp
* @author Suryoday Basak
*
* Definition of the Goldstein-Price function.
*
* ensmallen is free software; you may redistribute it and/or modify it under
* the terms of the 3-clause BSD license. You should have received a copy of
* the 3-clause BSD license along with ensmallen. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef ENSMALLEN_PROBLEMS_GOLDSTEIN_PRICE_FUNCTION_HPP
#define ENSMALLEN_PROBLEMS_GOLDSTEIN_PRICE_FUNCTION_HPP
namespace ens {
namespace test {
/**
* The Goldstein-Price function, defined by
* \f[
* f(x_1, x_2) = (1 + (x_1 + x_2 + 1)^2 * (19 - 14 * x_1 + 3 * x_1^2 - 14 *
* x_2 + 6 * x_1 * x_2 + 3 * x_2^2)) *
* (30 + (2 * x_1 - 3 * x_2)^2 * (18 - 32 * x_1 + 12 * x^2 +
* 48 * x_2 - 36 * x_1 * x_2 + 27 * x_2^2))
* \f]
*
* This should optimize to f(x) = 3, at x = [0, -1].
*
* For more information, please refer to:
*
* @code
* @article{Picheny:2013:BKI:2579829.2579986,
* author = {Picheny, Victor and Wagner, Tobias and Ginsbourger, David},
* title = {A Benchmark of Kriging-based Infill Criteria for Noisy
* Optimization},
* journal = {Struct. Multidiscip. Optim.},
* issue_date = {September 2013},
* volume = {48},
* number = {3},
* month = sep,
* year = {2013},
* issn = {1615-147X},
* pages = {607--626},
* numpages = {20},
* doi = {10.1007/s00158-013-0919-4},
* }
* @endcode
*/
class GoldsteinPriceFunction
{
public:
//! Initialize the GoldsteinPriceFunction.
GoldsteinPriceFunction();
/**
* Shuffle the order of function visitation. This may be called by the
* optimizer.
*/
void Shuffle();
//! Return 1 (the number of functions).
size_t NumFunctions() const { return 1; }
/**
* Evaluate a function for a particular batch-size.
*
* @param coordinates The function coordinates.
* @param begin The first function.
* @param batchSize Number of points to process.
*/
template<typename MatType>
typename MatType::elem_type Evaluate(const MatType& coordinates,
const size_t begin,
const size_t batchSize) const;
/**
* Evaluate a function with the given coordinates.
*
* @param coordinates The function coordinates.
*/
template<typename MatType>
typename MatType::elem_type Evaluate(const MatType& coordinates) const;
/**
* Evaluate the gradient of a function for a particular batch-size.
*
* @param coordinates The function coordinates.
* @param begin The first function.
* @param gradient The function gradient.
* @param batchSize Number of points to process.
*/
template<typename MatType, typename GradType>
void Gradient(const MatType& coordinates,
const size_t begin,
GradType& gradient,
const size_t batchSize) const;
/**
* Evaluate the gradient of a function with the given coordinates.
*
* @param coordinates The function coordinates.
* @param gradient The function gradient.
*/
template<typename MatType, typename GradType>
void Gradient(const MatType& coordinates, GradType& gradient);
// Note: GetInitialPoint(), GetFinalPoint(), and GetFinalObjective() are not
// required for using ensmallen to optimize this function! They are
// specifically used as a convenience just for ensmallen's testing
// infrastructure.
//! Get the starting point.
template<typename MatType = arma::mat>
MatType GetInitialPoint() const { return MatType("0.2; -0.5"); }
//! Get the final point.
template<typename MatType = arma::mat>
MatType GetFinalPoint() const { return MatType("0.0; -1.0"); }
//! Get the final objective.
double GetFinalObjective() const { return 3.0; }
};
} // namespace test
} // namespace ens
// Include implementation.
#include "goldstein_price_function_impl.hpp"
#endif // ENSMALLEN_PROBLEMS_GOLDSTEIN_PRICE_FUNCTION_HPP
|
0ffbc0275fe8182163f2b52430d912b3c02c7baa | eebcae99279b69b9f94767024de80127c7bd73ae | /src/LogQueueVoid.h | 0883b93090d0a3fffd18fd45338b33e2bbdb3d29 | [
"MIT"
] | permissive | nowtechnologies/cpp-logger | 452f3bf37132b05d48e882ec084fab7910bef26e | b211b9d9e7b881c2cf83edd74fccecae008c152b | refs/heads/master | 2022-01-01T07:50:59.004927 | 2020-12-18T15:09:53 | 2020-12-18T15:09:53 | 254,288,541 | 3 | 2 | MIT | 2020-12-22T17:40:04 | 2020-04-09T06:22:43 | C++ | UTF-8 | C++ | false | false | 683 | h | LogQueueVoid.h | #ifndef LOG_QUEUE_VOID
#define LOG_QUEUE_VOID
#include <cstddef>
namespace nowtech::log {
template<typename tMessage, typename tAppInterface, size_t tQueueSize>
class QueueVoid final {
public:
using tMessage_ = tMessage;
using tAppInterface_ = tAppInterface;
using LogTime = typename tAppInterface::LogTime;
private:
QueueVoid() = delete;
public:
static void init() { // nothing to do
}
static void done() { // nothing to do
}
static bool empty() noexcept {
return true;
}
static void push(tMessage const) noexcept { // nothing to do
}
static bool pop(tMessage &, LogTime const) noexcept { // nothing to do
return false;
}
};
}
#endif
|
642cd1e9a0c933e5ef0ea6a7018c5978010384ef | 809064fa0a7d7604879f4a36321004c1aebc1429 | /src/ui/ScrollState.cpp | 3564d53369df3e40920776fcec75555ed192a474 | [
"MIT"
] | permissive | Rookfighter/GameOfLife | f30087577b29a85bf41035796b18ca9082f3275f | c57371c82080900086b915ac3603470fac3c8c25 | refs/heads/master | 2021-01-18T13:58:22.993610 | 2015-01-20T18:14:49 | 2015-01-20T18:14:49 | 29,013,959 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,173 | cpp | ScrollState.cpp | #include "ui/ScrollState.hpp"
#include "ui/WaitingState.hpp"
namespace gol
{
ScrollState::ScrollState(WindowProperties &properties, const sf::Vector2i &mousePos)
: WindowState(properties), lastPos_(mousePos)
{
}
ScrollState::~ScrollState()
{
}
WindowState* ScrollState::handleInput(const sf::Event& event)
{
WindowState *result = nullptr;
if(event.type == sf::Event::MouseButtonReleased) {
if(event.mouseButton.button == sf::Mouse::Left)
result = new WaitingState(properties_);
} else if(event.type == sf::Event::MouseMoved) {
sf::Vector2f last = properties_.getWindow().mapPixelToCoords(lastPos_,
properties_.getGameView());
sf::Vector2f curr = properties_.getWindow().mapPixelToCoords(
sf::Vector2i(event.mouseMove.x, event.mouseMove.y),
properties_.getGameView());
sf::Vector2f diff = last - curr;
properties_.getGameView().move(diff);
lastPos_.x = event.mouseMove.x;
lastPos_.y = event.mouseMove.y;
}
return result;
}
}
|
e2d552b9fc5f4d1ae67c39fea6a962614366e150 | f7f83bee98149dd87cc75c14a7eed1160dfd704b | /RC_Car.ino | 9c312cd3dd647cfe27a293d026918bc5d6857eaa | [] | no_license | aspirant1999/RC_bot | 329db07c6b51b48d25344405b04de880dad24123 | e709a775723ef26c9be231ce791e73638b706e03 | refs/heads/master | 2021-05-23T18:32:15.606698 | 2020-04-06T06:49:00 | 2020-04-06T06:49:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,431 | ino | RC_Car.ino | int motorA1 = 9; // Pin 2 of L293
int motorA2 = 10; // Pin 7 of L293
int motorB1 = 5; // Pin 10 of L293
int motorB2 = 6 ; // Pin 14 of L293
int vel = 200; // Speed Of Motors (0-255)
int state = '0'; // Initialise Motors
void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 bits per second
// Set pins as outputs
pinMode(motorA1, OUTPUT);
pinMode(motorA2, OUTPUT);
pinMode(motorB1, OUTPUT);
pinMode(motorB2, OUTPUT);
}
void loop() {
if(Serial.available()>0){ // Reads from bluetooth and stores its value
state = Serial.read();
}
if(state=='F'){ // Forward
Serial.println(state);
analogWrite(motorA1, vel);
analogWrite(motorA2, 0);
analogWrite(motorB1, vel);
analogWrite(motorB2, 0);
}
if(state=='B'){ // Reverse
Serial.println(state);
analogWrite(motorA1, 0);
analogWrite(motorA2, vel);
analogWrite(motorB1, 0);
analogWrite(motorB2, vel);
}
if(state=='R'){ // Right
Serial.println(state);
analogWrite(motorA1, vel);
analogWrite(motorA2, 0);
analogWrite(motorB1, 0);
analogWrite(motorB2, vel);
}
if(state=='L'){ // Left
Serial.println(state);
analogWrite(motorA1, 0);
analogWrite(motorA2, vel);
analogWrite(motorB1, vel);
analogWrite(motorB2, 0);
}
if(state=='S'){ // Stop
Serial.println(state);
analogWrite(motorA1, 0);
analogWrite(motorA2, 0);
analogWrite(motorB1, 0);
analogWrite(motorB2, 0);
}
}
|
65b27242f572ce2117d013b69cb28147d45d7619 | 6f08fa4f3b572c04b8af4c7f541c517876972bff | /milkman.cpp | f6550f15d579b197ed0142e0a79e9d4de789dba5 | [] | no_license | sal-glitch/Algos | 33d0daff205fa1cd0cf5ea46dabdda38022cb271 | 81311a2c3b14105e93f5eb0c90cc851cc9ad15ad | refs/heads/main | 2023-03-03T04:53:24.270218 | 2021-02-07T11:38:27 | 2021-02-07T11:38:27 | 332,800,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 480 | cpp | milkman.cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
cin.tie(0); cout.tie(0); freopen("mixmilk.in", "r", stdin); freopen("mixmilk.out", "w", stdout);
int c[3], a[3];
for(int i=0;i<3;++i)
cin>>c[i]>>a[i];
int first=-1; int second=1;
int amt;
for(int i=0;i<100;++i)
{
first=(first+1)%3;
second=(first+1)%3;
amt=min(a[first],c[second]-a[second]);
a[first]-=amt;
a[second]+=amt;
}
cout<<a[0]<<"\n"<<a[1]<<"\n"<<a[2];
return 0;
}
|
9f8a2711396cda5c5a8ed9cb132eeed810dd0d2c | 291a28a21425b413d043e611ccdc5466048dc78b | /src/src/udp_controller/udp_controller.cpp | 59cda3326465fb6097fcee2fcbcfecbbc64a4b14 | [] | no_license | Dysonsun/learninggithub | b9ac8c4fc534c812f8bc5033e375e5e7fe73c112 | 51fd5a15fbfcb2a2ad09cb101a936be91a9f3983 | refs/heads/master | 2020-06-07T05:15:36.167117 | 2019-06-20T14:21:06 | 2019-06-20T14:21:06 | 192,933,397 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,241 | cpp | udp_controller.cpp | #include "udp_controller.hpp"
namespace carnet{
udp_controller::udp_controller(const ros::NodeHandle &nh, const ros::NodeHandle &nh_private,
std::string node_name)
:nh_(nh),
nh_private_(nh_private),
node_name_(node_name){
initialize();
}
bool udp_controller::initSocket() {
this->addr_remote_len = sizeof(this->addr_local);
//// create a socket
this->CarNetSocket = socket(AF_INET, SOCK_DGRAM, 0);
if(this->CarNetSocket < 0)
{
perror("create CarNetSocket failed!\n");
return false;
}
else
{
std::cout<<"create CarNetSocket succeed!"<<std::endl;
}
//// set the local address
memset((char*)&addr_local, 0, sizeof(addr_local));
this->addr_local.sin_addr.s_addr = htonl(INADDR_ANY);
this->addr_local.sin_family = AF_INET;
this->addr_local.sin_port = htons(local_port);
//// bind the socket with local address
if(bind(CarNetSocket, (sockaddr*)&addr_local, sizeof(sockaddr)) < 0)
{
perror("bind the CarNetSocket failed!");
return false;
}
else
{
std::cout<<"bind the CarNetSocket succeed!"<<std::endl;
std::cout<<"Local Port : "<< this->local_port<<std::endl;
}
//// set the remote address
//memset(&addr_remote,0,sizeof(addr_remote));
this->addr_remote.sin_addr.s_addr = inet_addr(remote_ip.c_str());
this->addr_remote.sin_family = AF_INET;
this->addr_remote.sin_port = htons(remote_port);
std::cout<<"Remote IP : "<< this->remote_ip.c_str()<<std::endl;
std::cout<<"Remote Port: "<< this->remote_port<<std::endl;
return true;
}
void udp_controller::UpdateMsg(){
//// Receive Other Car State
unsigned char recvBuf[4096]; //// receive buffer
int recvlen; //// bytes received
recvlen = recvfrom(CarNetSocket, recvBuf, 4096, MSG_DONTWAIT, (struct sockaddr *)&addr_remote, &addr_remote_len);
if(recvlen > 0 && this->addr_remote.sin_port == htons(this->remote_port))
{
std::cout<<" RECV DATA NOW!!! "<<std::endl;
cmddataupdate = true;
for (int i = 0; i < recvlen; i++)
{
recvmsgs(recvBuf[i]);
}
}
}
void udp_controller::recvmsgs(char ch){
static char static_cHeadFlag = 0;
static char static_cTailFlag = 0;
static char static_cOverFlag = 0;
static int static_cRXDataNum = 0;
static int static_cRXAfterStarDataNum = 0;
static char static_cRXDataChecksum = 0; //校验位
static char static_cRXDataCsc[1];
char cTemp = ch;
if('$' == cTemp)
{
static_cHeadFlag = 1;//找到了包头‘$’
static_cTailFlag = 0;
static_cOverFlag = 0;
static_cRXDataChecksum = cTemp;
static_cRXDataNum = 0;
memset(RecvData,0,150);
}
if(1 == static_cHeadFlag)
{
if('*' == cTemp)
static_cTailFlag = 1;
else //没找到包尾,存数 求校验
{
this->RecvData[static_cRXDataNum++] = cTemp;
static_cRXAfterStarDataNum = 0;
}
if(static_cTailFlag == 1)
{
static_cRXDataCsc[static_cRXAfterStarDataNum++] = cTemp;
if(1 == static_cRXAfterStarDataNum)
{
if(/*(static_cRXDataCsc[1] == cTempRXDataCsc1) && (static_cRXDataCsc[2] == cTempRXDataCsc2)*/1)
{
char RecvDataHead[10];
char *pStr = NULL;
//char *next_token = NULL;
char seps[] = ",\t\n";
double dTemp = 0.0;
int i = 0;
int j = 0;
int DataCommaNum = 0;
char tempData[15];
memset(RecvDataHead,0,10);
memset(tempData,0,15);
memcpy(this->temp_RecvData,this->RecvData,150);
pStr = strtok(this->RecvData,seps);
if(pStr)
{
strcpy(RecvDataHead,pStr);
if(0 == strcmp(RecvDataHead,"$"))
{
while( i++ <= static_cRXDataNum)
{
if(i > 150)
i = 0;
if(',' == this->temp_RecvData[i])
{
j = 0;
DataCommaNum++;
switch(DataCommaNum)
{
case 1:
dTemp = atof(tempData);
memset(tempData,0,15);
break;
case 2:
dTemp = atof(tempData);
carstate.expvel = dTemp;
memset(tempData,0,15);
break;
case 3:
dTemp = atof(tempData);
carstate.expsteering = dTemp;
memset(tempData,0,15);
break;
default:
break;
}
}
else
{
tempData[j++] = this->temp_RecvData[i];
}
}
}
else
{
static_cOverFlag = 1;
}
}
else // 数据解析完毕
{
static_cOverFlag = 1;
}
}
}
else if(static_cRXAfterStarDataNum > 1)
{
static_cOverFlag = 1;
}
}
if(static_cRXDataNum >= 150)
{
static_cOverFlag = 1;
}
}
if(1 == static_cOverFlag)
{
static_cHeadFlag = 1;
static_cOverFlag = 0;
static_cTailFlag = 0;
static_cRXDataChecksum = 0;
static_cRXDataNum = 0;
static_cRXAfterStarDataNum = 0;
memset(this->RecvData,0,150);
}
}
void udp_controller::initialize(){
local_port = 8001;
remote_ip = "127.0.0.1"; //"127.0.0.1";自机通讯地址//
remote_port = 8000;
//test
carstate.expvel = 0.0;
carstate.expsteering = 0.0;
initSocket();
auto &pnh = nh_;
expsteerdata_pub_ = pnh.advertise<std_msgs::Float32>("cmd_str",10);
expdirdata_pub_ = pnh.advertise<std_msgs::Float32>("cmd_dir",10);
expveldata_pub_ = pnh.advertise<std_msgs::Float32>("cmd_vel",10);
this->cmd_vel_.data = 0;
this->cmd_str_.data = 0;
this->cmd_dir_.data = 0;
loop_timer_ = pnh.createTimer(ros::Duration(0.05), boost::bind(&udp_controller::timerCb, this));
}
void udp_controller::timerCb() {
ROS_INFO_ONCE("udp car start");
UpdateMsg();
std::cout<<"carstate.expvel: "<<carstate.expvel<<std::endl;
std::cout<<"carstate.expsteering: "<<carstate.expsteering<<std::endl;
cmd_str_.data = double(fabs(carstate.expsteering));//角度
if(carstate.expsteering>0)//方向
{
cmd_dir_.data = 1;
}
else if(carstate.expsteering<0)
{
cmd_dir_.data = -1;
}
else cmd_dir_.data = 0;
cmd_vel_.data =0.9*double(carstate.expvel);//速度
expsteerdata_pub_.publish(cmd_str_);
expdirdata_pub_.publish(cmd_dir_);
expveldata_pub_.publish(cmd_vel_);
}
}//namespace carnet
int main(int argc, char** argv) {
std::string node_name = "udp_controller";
ros::init(argc, argv, node_name);
ros::NodeHandle nh("");
ros::NodeHandle nh_private("~");
carnet::udp_controller sender(nh, nh_private, node_name);
ROS_INFO("Initialized sender node.");
ros::spin();
}
|
a56e71601a0df6f9109f4a4adb3e6d0e5bd463db | 1894685e4beaf304d0351b7cbb29f8421b597050 | /src/designerfilesortproxy.cpp | 67283ab5e3e1bc2b52c80a938934edd7e9c6e8b3 | [] | no_license | maxavadallat/maxdesigner | f9d9f9568d633fc0b1ede609894630a2e0ac0eba | cf13dd5927be0a9aa8c45826f3cac213fb0578be | refs/heads/master | 2021-01-22T07:48:40.904807 | 2017-11-22T13:15:24 | 2017-11-22T13:15:24 | 81,853,498 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,199 | cpp | designerfilesortproxy.cpp | #include <QDebug>
#include <QFileInfo>
#include "designerfilesortproxy.h"
#include "projecttreemodel.h"
//==============================================================================
// Constructor
//==============================================================================
DesignerFileSortProxy::DesignerFileSortProxy(QObject* aParent)
: QSortFilterProxyModel(aParent)
{
qDebug() << "DesignerFileSortProxy created.";
// ...
// // Set Filter Role
// setFilterRole(QFileSystemModel::FileNameRole);
// Set Sort Role
setSortRole(QFileSystemModel::FileNameRole);
// Set Dynamic Sort Filter
setDynamicSortFilter(true);
}
//==============================================================================
// Less Than
//==============================================================================
bool DesignerFileSortProxy::lessThan(const QModelIndex& aLeft, const QModelIndex& aRight) const
{
// Check Sort Column
if (sortColumn() == 0) {
qDebug() << "#### DesignerFileSortProxy::lessThan";
// Get File System Model
QFileSystemModel* fsm = qobject_cast<QFileSystemModel*>(sourceModel());
// Get Ascending Order
bool asc = (sortOrder() == Qt::AscendingOrder);
QFileInfo leftFileInfo = fsm->fileInfo(aLeft);
QFileInfo rightFileInfo = fsm->fileInfo(aRight);
// If DotAndDot move in the beginning
if (sourceModel()->data(aLeft).toString() == "..") {
return asc;
}
if (sourceModel()->data(aRight).toString() == "..") {
return !asc;
}
// Move dirs upper
if (!leftFileInfo.isDir() && rightFileInfo.isDir()) {
return !asc;
}
if (leftFileInfo.isDir() && !rightFileInfo.isDir()) {
return asc;
}
}
// // Get Source Model
// QFileSystemModel* sm = static_cast<QFileSystemModel*>(sourceModel());
// // Get Left File Info
// QFileInfo leftFileInfo(sm->data(aLeft, QFileSystemModel::FilePathRole).toString());
// // Get Right File Info
// QFileInfo rightFileInfo(sm->data(aRight, QFileSystemModel::FilePathRole).toString());
// qDebug() << "DesignerFileSortProxy::lessThan - aLeft: " << leftFileInfo.fileName() << " - aRight: " << rightFileInfo.fileName();
// // Check If Is Dir
// if (leftFileInfo.isDir() && !rightFileInfo.isDir()) {
// return mSortOrder == Qt::DescendingOrder;
// }
// // Check If Is Dir
// if (!leftFileInfo.isDir() && rightFileInfo.isDir()) {
// return mSortOrder == Qt::AscendingOrder;
// }
// if (mSortOrder == Qt::AscendingOrder) {
// return leftFileInfo.fileName() > rightFileInfo.fileName();
// }
// return leftFileInfo.fileName() < rightFileInfo.fileName();
return QSortFilterProxyModel::lessThan(aLeft, aRight);
}
//==============================================================================
// Sort
//==============================================================================
void DesignerFileSortProxy::sort(int column, Qt::SortOrder order)
{
qDebug() << "#### DesignerFileSortProxy::sort";
QSortFilterProxyModel::sort(column, order);
}
|
30e6800b11e2badbb22810d4260a3074de2aa20e | 6aeccfb60568a360d2d143e0271f0def40747d73 | /sandbox/generic/test/libs/generic/test/std_concept/concepts/has_logical_or.cpp | f48e9f7c63fc67aabefbd1babc5b4cb6177917af | [] | no_license | ttyang/sandbox | 1066b324a13813cb1113beca75cdaf518e952276 | e1d6fde18ced644bb63e231829b2fe0664e51fac | refs/heads/trunk | 2021-01-19T17:17:47.452557 | 2013-06-07T14:19:55 | 2013-06-07T14:19:55 | 13,488,698 | 1 | 3 | null | 2023-03-20T11:52:19 | 2013-10-11T03:08:51 | C++ | UTF-8 | C++ | false | false | 1,342 | cpp | has_logical_or.cpp | /*==============================================================================
Copyright (c) 2011 Matt Calabrese
Use, modification and distribution is subject to the Boost Software
License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#include <boost/generic/std_concept/concepts/has_logical_or.hpp>
#include <boost/generic/assert.hpp>
using boost::generic::std_concept::HasLogicalOr;
BOOST_GENERIC_ASSERT( HasLogicalOr< int, int > );
BOOST_GENERIC_ASSERT( HasLogicalOr< float, float > );
struct a {};
struct logical_or_object_left {};
struct logical_or_object_right {};
bool operator ||( logical_or_object_left, logical_or_object_right );
a operator ||( logical_or_object_right, logical_or_object_left );
BOOST_GENERIC_ASSERT
( HasLogicalOr< logical_or_object_left, logical_or_object_right > );
BOOST_GENERIC_ASSERT_NOT
( HasLogicalOr< logical_or_object_left, logical_or_object_left > );
BOOST_GENERIC_ASSERT_NOT
( HasLogicalOr< logical_or_object_right, logical_or_object_right > );
BOOST_GENERIC_ASSERT_NOT
( HasLogicalOr< logical_or_object_right, logical_or_object_left > );
BOOST_GENERIC_ASSERT_NOT
( HasLogicalOr< logical_or_object_right, logical_or_object_left > );
|
01880f5c0fd65266806cc2e845a48c4b977cbf88 | 09bd5ce544726087f2422ed3c593e077933b2d92 | /CryptoMachine_policies.h | 26d85fb0f3d856b003429d552ee7fe2fcb71eae3 | [] | no_license | tom-dusty/moreassignment | 2342f5e483fb6445ecaae2dd1aac884fd9b47ace | 44d8f64cfa93657bf4a689b3695cc84c06966ef8 | refs/heads/master | 2020-05-16T23:05:03.989835 | 2014-05-14T00:23:19 | 2014-05-14T00:23:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,313 | h | CryptoMachine_policies.h | // CryptoMachine_policies policies class
// Thomas Dusterwald
// 13 May 2014
#ifndef _CRYPTOMACHINE_POLICIES_H
#define _CRYPTOMACHINE_POLICIES_H
#include <iostream>
#include <algorithm>
#include <bitset>
#include <cstdint>
#include "types.h"
//Functor used for vignere encoding. Makes use of ascii values for the chars instead of using a lookup table
class vig {
int count;
std::vector<char> key;
public:
vig(std::vector<char> keyIn) :count(0), key(keyIn){}
char operator()(char in)
{
char ret = 32;
if(in == 32)
in = 91;
//in-=13;
if(((key[count]-11)%27+(in-11)%27)<26)
{
ret = (key[count]+in)%26+65;
}
else if(((key[count]-11)%27+(in-11)%27)!=26)
{
ret = (key[count]+in-1)%26+65;
}
count = (count +1)%(key.size());
return ret;
}
};
//Decoding functor for vignere encoding.
class vigdec {
int count;
std::vector<char> key;
public:
vigdec(std::vector<char> keyIn) :count(0), key(keyIn){}
char operator()(char in)
{
char ret = 32;
if(in == 32)
in = 91;
//in-=13;
if(in>=key[count])
{
ret = (in-key[count])%27+65;
if(ret == 91)
ret = 32;
}
else
{
ret = ((in-11)%27+27-(key[count]-11)%27)+65;
if(ret == 91)
ret = 32;
}
count = (count +1)%(key.size());
return ret;
}
};
//grouping functor
class gro {
public:
int count;
std::string grouped;
gro() : count(0), grouped(""){};
void operator()(char in)
{
grouped += in;
if(count%5 == 4)
grouped += ' ';
count++;
}
};
//xor ecb encoder/decoder functor
class xorenc{
public:
int count;
std::vector<char> key;
std::vector<char> IV;
std::string mode;
xorenc(std::vector<char> keyIn,std::vector<char> IVin, std::string modeIn) : key(keyIn), IV(IVin), mode(modeIn), count(0){};
char operator()(char in)
{
char tbr = in xor key[count];
if(mode == "CBC")
tbr = tbr xor IV[count];
if(tbr == EOF)
tbr = in;
IV[count] = tbr;
count = (count+1)%4;
return tbr;
}
};
//xor cbc decoder functor
class xordec {
public:
int count;
std::vector<char> key;
std::vector<char> IV;
std::string mode;
xordec(std::vector<char> keyIn,std::vector<char> IVin, std::string modeIn) : key(keyIn), IV(IVin), mode(modeIn), count(0){};
char operator()(char in)
{
char tbr = in xor key[count];
if(mode == "CBC")
tbr = tbr xor IV[count];
if(tbr == EOF)
tbr = in;
IV[count] = in;
count = (count+1)%4;
return tbr;
}
};
// Templated with four types that modify functionality
template <typename Cipher, typename Mode, typename Group, typename Pack>
class CryptoMachine_policies
{
public:
void encode(std::string in, std::ostream & out, std::vector<char> key);
void decode(std::string in, std::ostream & out, std::vector<char> key);
};
//CryptoMachine_policies templated with vignere and ECB options
template <typename Group, typename Pack>
class CryptoMachine_policies <vignere, ecb, Group, Pack>
{
public:
void encode(std::string in, std::ostream & out, std::vector<char> key)
{
vig translater(key);
std::transform(in.begin(), in.end(), in.begin(), translater);
out << in;
}
void decode(std::string in, std::ostream & out, std::vector<char> key)
{
vigdec translater(key);
std::transform(in.begin(), in.end(),in.begin(), [](char z) -> char{if(z==32){return 91;}return toupper(z);});
std::transform(in.begin(), in.end(), in.begin(), translater);
out << in;
}
};
//vignere ecb pack
template <typename Group>
class CryptoMachine_policies <vignere, ecb, Group, pack>
{
public:
void encode(std::string in, std::ostream & out, std::vector<char> key)
{
vig translater(key);
//encode using vignere
std::transform(in.begin(), in.end(), in.begin(), translater);
//pack
std::transform(in.begin(), in.end(),in.begin(),[](char z)->char{if(z==32){return 27;};return z-64;});
std::bitset<1000> bits;
std::for_each(in.begin(), in.end(),[&bits](char z){bits = bits<<5;bits|=(std::bitset<1000>(z));});
//chop off bits that we want into char again
std::vector<bool> squishy((in.size()*5)/8+1);
int count = 0;
std::string temp3;
std::transform(squishy.begin(), squishy.end(),std::back_inserter(temp3),[&count, &bits](bool n)->char{count = 0;char ret;std::vector<bool> squishy2(8);std::bitset<8> bitty;std::for_each(squishy2.begin(),squishy2.end(),[&count, &bits, &bitty](bool meh){bitty[count]=bits[count];count++;});bits = bits>>8;return bitty.to_ulong();});
std::reverse(temp3.begin(), temp3.end());
out << temp3;
}
void decode(std::string in, std::ostream & out, std::vector<char> key)
{
vigdec translater(key);
//unpack
std::bitset<1000> bits;
std::vector<bool> squishy((in.size()*8)/5);
int count = 0;
std::string temp3;
std::string temp4;
bool odd = false;
std::for_each(in.begin(), in.end(),[&bits](char z){bits = bits<<8;bits|=(std::bitset<1000>(std::bitset<8>(z).to_string()));});
std::transform(squishy.begin(), squishy.end(),std::back_inserter(temp3),[&count, &bits,&odd](bool n)->char{count = 0;char ret;std::vector<bool> squishy2(5);std::bitset<8> bitty;std::for_each(squishy2.begin(),squishy2.end(),[&count, &bits, &bitty](bool meh){bitty[count]=bits[count];count++;});bits = bits>>5;if(bitty.to_ulong()==0)odd=true;return bitty.to_ulong();}); //chop off bits that we want into char again
std::reverse(temp3.begin(), temp3.end());
if(odd)
{
std::copy_if(temp3.begin(),temp3.end(),std::back_inserter(temp4),[&](char in)->bool{return !(in==0);});
temp3 = temp4;
}
std::transform(temp3.begin(), temp3.end(),temp3.begin(),[](char z)->char{if(z==27){return 32;};return z+64;});
std::transform(temp3.begin(), temp3.end(),temp3.begin(), [](char z) -> char{if(z==32){return 91;}return toupper(z);});
std::transform(temp3.begin(), temp3.end(), temp3.begin(), translater);
out << temp3;
}
};
//Vignere with Grouping option
template <typename Pack>
class CryptoMachine_policies <vignere, ecb, group, Pack>
{
public:
void encode(std::string in, std::ostream & out, std::vector<char> key)
{
vig translater(key);
std::string temp3;
//Grouping part:
// removes spaces
std::copy_if(in.begin(), in.end(), back_inserter(temp3), [](char z)->bool{if(z==91)return false;return true;});
// insert spaces every 5
gro y = std::for_each(temp3.begin(),temp3.end(),gro());
temp3 = y.grouped;
std::transform(temp3.begin(), temp3.end(), temp3.begin(), translater);
out << temp3;
}
void decode(std::string in, std::ostream & out, std::vector<char> key)
{
vigdec translater(key);
std::transform(in.begin(), in.end(),in.begin(), [](char z) -> char{if(z==32){return 91;}return toupper(z);});
std::transform(in.begin(), in.end(), in.begin(), translater);
out << in;
}
};
//vignere ecb pack and group
template <>
class CryptoMachine_policies <vignere, ecb, group, pack>
{
public:
void encode(std::string in, std::ostream & out, std::vector<char> key)
{
vig translater(key);
std::string temp3;
//Group
std::transform(in.begin(), in.end(),in.begin(), [](char z) -> char{return toupper(z);});
std::copy_if(in.begin(), in.end(), back_inserter(temp3), [](char z)->bool{if(z==32)return false;return true;});
// insert spaces every 5
gro y = std::for_each(temp3.begin(),temp3.end(),gro());
in = y.grouped;
std::transform(in.begin(), in.end(),in.begin(), [](char z) -> char{if(z==32){return 91;}return toupper(z);});
std::transform(in.begin(), in.end(), in.begin(), translater);
//pack
std::transform(in.begin(), in.end(),in.begin(),[](char z)->char{if(z==32){return 27;};return z-64;});
std::bitset<1000> bits;
std::for_each(in.begin(), in.end(),[&bits](char z){bits = bits<<5;bits|=(std::bitset<1000>(z));});
//chop off bits that we want into char again
std::vector<bool> squishy((in.size()*5)/8+1);
int count = 0;
temp3 = "";
std::transform(squishy.begin(), squishy.end(),std::back_inserter(temp3),[&count, &bits](bool n)->char{count = 0;char ret;std::vector<bool> squishy2(8);std::bitset<8> bitty;std::for_each(squishy2.begin(),squishy2.end(),[&count, &bits, &bitty](bool meh){bitty[count]=bits[count];count++;});bits = bits>>8;return bitty.to_ulong();});
std::reverse(temp3.begin(), temp3.end());
out << temp3;
}
void decode(std::string in, std::ostream & out, std::vector<char> key)
{
vigdec translater(key);
//unpack
std::bitset<1000> bits;
std::vector<bool> squishy((in.size()*8)/5);
int count = 0;
std::string temp3;
std::string temp4;
bool odd = false;
std::for_each(in.begin(), in.end(),[&bits](char z){bits = bits<<8;bits|=(std::bitset<1000>(std::bitset<8>(z).to_string()));});
std::transform(squishy.begin(), squishy.end(),std::back_inserter(temp3),[&count, &bits,&odd](bool n)->char{count = 0;char ret;std::vector<bool> squishy2(5);std::bitset<8> bitty;std::for_each(squishy2.begin(),squishy2.end(),[&count, &bits, &bitty](bool meh){bitty[count]=bits[count];count++;});bits = bits>>5;if(bitty.to_ulong()==0)odd=true;return bitty.to_ulong();}); //chop off bits that we want into char again
std::reverse(temp3.begin(), temp3.end());
if(odd)
{
std::copy_if(temp3.begin(),temp3.end(),std::back_inserter(temp4),[&](char in)->bool{return !(in==0);});
temp3 = temp4;
}
std::transform(temp3.begin(), temp3.end(),temp3.begin(),[](char z)->char{if(z==27){return 32;};return z+64;});
std::transform(temp3.begin(), temp3.end(),temp3.begin(), [](char z) -> char{if(z==32){return 91;}return toupper(z);});
std::transform(temp3.begin(), temp3.end(), temp3.begin(), translater);
out << temp3;
}
};
//xor ecb/cbc
template <typename Mode, typename Group, typename Pack>
class CryptoMachine_policies <xorencrypt, Mode, Group, Pack>
{
public:
void encode(std::string in, std::ostream & out, std::vector<char> key,std::vector<char> IV, std::string mode)
{
std::transform(in.begin(), in.end(),in.begin(), [](char z) -> char{return toupper(z);});
std::transform(in.begin(), in.end(), in.begin(), xorenc(key,IV,mode));
out << in;
}
void decode(std::string in, std::ostream & out, std::vector<char> key,std::vector<char> IV, std::string mode)
{
std::transform(in.begin(), in.end(), in.begin(), xordec(key,IV,mode));
out << in;
}
};
//xor ecb/cbc grouping
template <typename Mode, typename Pack>
class CryptoMachine_policies <xorencrypt, Mode, group, Pack>
{
public:
void encode(std::string in, std::ostream & out, std::vector<char> key,std::vector<char> IV, std::string mode)
{
std::string temp3;
std::transform(in.begin(), in.end(),in.begin(), [](char z) -> char{return toupper(z);});
//Grouping part:
// removes spaces
std::transform(in.begin(), in.end(),in.begin(), [](char z) -> char{return toupper(z);});
std::copy_if(in.begin(), in.end(), back_inserter(temp3), [](char z)->bool{if(z==32)return false;return true;});
// insert spaces every 5
gro y = std::for_each(temp3.begin(),temp3.end(),gro());
temp3 = y.grouped;
std::transform(temp3.begin(), temp3.end(), temp3.begin(), xorenc(key,IV,mode));
out << temp3;
}
void decode(std::string in, std::ostream & out, std::vector<char> key,std::vector<char> IV, std::string mode)
{
std::transform(in.begin(), in.end(), in.begin(), xordec(key,IV,mode));
out << in;
}
};
//xor ecb packing
template <typename Mode, typename Group>
class CryptoMachine_policies <xorencrypt, Mode, Group, pack>
{
public:
void encode(std::string in, std::ostream & out, std::vector<char> key,std::vector<char> IV, std::string mode)
{
std::transform(in.begin(), in.end(),in.begin(), [](char z) -> char{return toupper(z);});
//pack
std::transform(in.begin(), in.end(),in.begin(),[](char z)->char{if(z==32){return 27;};return z-64;});
std::bitset<1000> bits;
std::for_each(in.begin(), in.end(),[&bits](char z){bits = bits<<5;bits|=(std::bitset<1000>(z));});
//chop off bits that we want into char again
std::vector<bool> squishy((in.size()*5)/8+1);
int count = 0;
std::string temp3;
std::transform(squishy.begin(), squishy.end(),std::back_inserter(temp3),[&count, &bits](bool n)->char{count = 0;char ret;std::vector<bool> squishy2(8);std::bitset<8> bitty;std::for_each(squishy2.begin(),squishy2.end(),[&count, &bits, &bitty](bool meh){bitty[count]=bits[count];count++;});bits = bits>>8;return bitty.to_ulong();});
std::reverse(temp3.begin(), temp3.end());
std::transform(temp3.begin(), temp3.end(), temp3.begin(), xorenc(key,IV,mode));
out << temp3;
}
void decode(std::string in, std::ostream & out, std::vector<char> key,std::vector<char> IV, std::string mode)
{
std::transform(in.begin(), in.end(), in.begin(), xordec(key,IV,mode));
//unpack
std::bitset<1000> bits;
std::vector<bool> squishy((in.size()*8)/5);
int count = 0;
std::string temp3;
std::string temp4;
bool odd = false;
std::for_each(in.begin(), in.end(),[&bits](char z){bits = bits<<8;bits|=(std::bitset<1000>(std::bitset<8>(z).to_string()));});
std::transform(squishy.begin(), squishy.end(),std::back_inserter(temp3),[&count, &bits,&odd](bool n)->char{count = 0;char ret;std::vector<bool> squishy2(5);std::bitset<8> bitty;std::for_each(squishy2.begin(),squishy2.end(),[&count, &bits, &bitty](bool meh){bitty[count]=bits[count];count++;});bits = bits>>5;if(bitty.to_ulong()==0)odd=true;return bitty.to_ulong();}); //chop off bits that we want into char again
std::reverse(temp3.begin(), temp3.end());
if(odd)
{
std::copy_if(temp3.begin(),temp3.end(),std::back_inserter(temp4),[&](char in)->bool{return !(in==0);});
temp3 = temp4;
}
std::transform(temp3.begin(), temp3.end(),temp3.begin(),[](char z)->char{if(z==27){return 32;};return z+64;});
out << temp3;
}
};
//xor ecb/ecb packing and grouping
template <typename Mode>
class CryptoMachine_policies <xorencrypt, Mode, group, pack>
{
public:
void encode(std::string in, std::ostream & out, std::vector<char> key,std::vector<char> IV, std::string mode)
{
std::string temp3;
std::transform(in.begin(), in.end(),in.begin(), [](char z) -> char{return toupper(z);});
//Grouping part:
// removes spaces
std::transform(in.begin(), in.end(),in.begin(), [](char z) -> char{return toupper(z);});
std::copy_if(in.begin(), in.end(), back_inserter(temp3), [](char z)->bool{if(z==32)return false;return true;});
// insert spaces every 5
gro y = std::for_each(temp3.begin(),temp3.end(),gro());
in = y.grouped;
temp3 = "";
//pack
std::transform(in.begin(), in.end(),in.begin(),[](char z)->char{if(z==32){return 27;};return z-64;});
std::bitset<1000> bits;
std::for_each(in.begin(), in.end(),[&bits](char z){bits = bits<<5;bits|=(std::bitset<1000>(z));});
//chop off bits that we want into char again
std::vector<bool> squishy((in.size()*5)/8+1);
int count = 0;
std::transform(squishy.begin(), squishy.end(),std::back_inserter(temp3),[&count, &bits](bool n)->char{count = 0;char ret;std::vector<bool> squishy2(8);std::bitset<8> bitty;std::for_each(squishy2.begin(),squishy2.end(),[&count, &bits, &bitty](bool meh){bitty[count]=bits[count];count++;});bits = bits>>8;return bitty.to_ulong();});
std::reverse(temp3.begin(), temp3.end());
std::transform(temp3.begin(), temp3.end(), temp3.begin(), xorenc(key,IV,mode));
out << temp3;
};
void decode(std::string in, std::ostream & out, std::vector<char> key,std::vector<char> IV, std::string mode)
{
std::transform(in.begin(), in.end(), in.begin(), xordec(key,IV,mode));
//unpack
std::bitset<1000> bits;
std::vector<bool> squishy((in.size()*8)/5);
int count = 0;
std::string temp3;
std::string temp4;
bool odd = false;
std::for_each(in.begin(), in.end(),[&bits](char z){bits = bits<<8;bits|=(std::bitset<1000>(std::bitset<8>(z).to_string()));});
std::transform(squishy.begin(), squishy.end(),std::back_inserter(temp3),[&count, &bits,&odd](bool n)->char{count = 0;char ret;std::vector<bool> squishy2(5);std::bitset<8> bitty;std::for_each(squishy2.begin(),squishy2.end(),[&count, &bits, &bitty](bool meh){bitty[count]=bits[count];count++;});bits = bits>>5;if(bitty.to_ulong()==0)odd=true;return bitty.to_ulong();}); //chop off bits that we want into char again
std::reverse(temp3.begin(), temp3.end());
if(odd)
{
std::copy_if(temp3.begin(),temp3.end(),std::back_inserter(temp4),[&](char in)->bool{return !(in==0);});
temp3 = temp4;
}
std::transform(temp3.begin(), temp3.end(),temp3.begin(),[](char z)->char{if(z==27){return 32;};return z+64;});
out << temp3;
}
};
#endif
|
22e29ad880f1fb651807c757bab19c81e6831039 | db5e5d680007fa48658023dd96ba5d2a0412ec71 | /src/Shader.h | 6e5aeb66817861eb4846efb6bff818ed0e9dbb4c | [] | no_license | LiquidPeach/Pool-OpenGL | d49466a334a88468c3b2a36699c8a9e0efdfcc41 | 49f0bd4bdc2280f8a7834d00d289221dede302b3 | refs/heads/master | 2023-08-29T02:00:13.582119 | 2021-10-29T04:52:00 | 2021-10-29T04:52:00 | 412,317,481 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 779 | h | Shader.h | #pragma once
#include <unordered_map>
class Shader {
public:
Shader() = default;
~Shader();
void CompileShader(const unsigned int shaderType, const char* source);
void CreateProgram(const std::string& vertexShader, const std::string& fragmentShader);
std::string ReadFile(const std::string& fileName);
void SetUniform1i(const std::string& name, int value);
void SetUniform4f(const std::string& name, float v0, float v1, float v2, float v3);
void SetUniformMatrix4fv(const std::string& name, int count, unsigned int transpose, float* value);
int GetUniformLocation(const std::string& name);
void Bind() const;
void Unbind() const;
void DeleteShader() const;
private:
unsigned int m_ProgramID = 0;
std::unordered_map<std::string, int> m_UniformLocationCache;
}; |
0e2b6e4860bcdbf2b688ec88dda3806ad63168b0 | a9e54f17407f143d4d9ac9448da317f66dbc712c | /include/BeastDecoder.h | 446cb45faf20d6da05987cbb93b46324c2cee1ed | [
"MIT"
] | permissive | VerlorenMind/TrellisDecoders | 7e8449b81c5c8aab6252f62c9ebcfdc9699ea2c5 | fb6603efe2fb1afb81dcc3febfa49d7ebcc644cb | refs/heads/master | 2022-12-08T19:39:02.422722 | 2020-08-26T09:59:06 | 2020-08-26T09:59:06 | 142,466,881 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 948 | h | BeastDecoder.h | #ifndef BEAST_BEASTDECODER_H
#define BEAST_BEASTDECODER_H
#include <fstream>
#include <cstdint>
#include <set>
#include <queue>
#include "TrellisDecoder.h"
enum InsertionStatus {
INSERTED,
REPLACED,
DISCARDED,
ENDED,
};
class BeastDecoder : public TrellisDecoder {
protected:
double min_metric = -1;
double delta = 1;
uint64_t min_candidate = 0;
Node *fwd_tree{}, *fwd_tree_buffer{}, *bkw_tree{}, *bkw_tree_buffer{};
unsigned fwd_tree_size{}, fwd_tree_buffer_size{}, bkw_tree_size{}, bkw_tree_buffer_size{};
Node **trellis{};
InsertionStatus insert_node(const Node &node);
void init(double delta);
public:
BeastDecoder(unsigned int n, unsigned int k, std::ifstream &filename, double delta);
BeastDecoder(unsigned int n, unsigned int k, int **h, double delta);
double decode(const double *x, int *u) override;
void set_delta(double d);
double get_delta();
~BeastDecoder();
};
#endif //BEAST_BEASTDECODER_H
|
5383e98ce3ca7456ebb874368e616ad9dcb6ede8 | a77cae61867e4fb947f88acb4e11603d9cd0f6d1 | /SJTUOJ/SJTU1209_十进制转二进制.cpp | 18fe67d516d7a7c27e4f3502804176dc05b43e6f | [] | no_license | CHOcho-quan/OJ-Journey | cbad32f7ab52e59218ce4741097d6fa0ac9b462f | a9618891b5e14790ba65914783e26f8a7aa03497 | refs/heads/master | 2023-06-09T15:35:27.418405 | 2023-06-01T00:57:11 | 2023-06-01T00:57:11 | 166,665,271 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 594 | cpp | SJTU1209_十进制转二进制.cpp | //
// SJTU1209_十进制转二进制.cpp
//
//
// Created by 铨 on 2019/3/5.
//
//
#include <iostream>
#include <set>
#include <vector>
#include <string>
#include <stack>
#include <iomanip>
using namespace std;
int main() {
int n,tmp,sum=0;
cin >> n;
for (int i = 0;i < n;i++)
{
cin >> tmp;
while (tmp >= 1)
{
if (tmp == 1) {
sum+=1;
break;
}
int t = tmp % 2;
tmp = tmp / 2;
if (t == 1) sum+=1;
}
}
cout << sum;
}
|
48aed0aa2571ce5f88797f11d39fdf987751fd0a | 4f8a11be6de8f06ec230d2169eee1e42915c24c4 | /src/depixelize/spline_optimizer.cpp | 05e131da578c6f9417d9a6f4dbffba3c910c57bf | [] | no_license | bsl/depixelize | 641585ed79e2d7d33e9c9578dfa78e0b95382b6c | 844ba2b5dd5fb7b050910a024441cfe5648b1d60 | refs/heads/master | 2021-01-16T21:48:52.937547 | 2015-01-13T08:27:25 | 2015-01-13T08:27:25 | 28,911,851 | 0 | 0 | null | 2015-01-07T11:33:47 | 2015-01-07T11:33:47 | null | UTF-8 | C++ | false | false | 15,392 | cpp | spline_optimizer.cpp | #include "spline_optimizer.hpp"
#include "color_util.hpp"
#include "math_util.hpp"
#include "voronoi_visual_utils.hpp"
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
namespace Depixelize {
void SplineOptimizer::initialize()
{
std::unordered_multimap<uint32_t, EdgeRef> adjacent_edges;
std::unordered_set<Edge> seen_edges;
std::vector<EdgeRef> *component_edges = new std::vector<EdgeRef>[this->num_components]();
for (vd_type::const_edge_iterator it = this->vd.edges().begin(); it != this->vd.edges().end(); ++it) {
// Cannot be visible if it isn't primary
if (!it->is_primary()) {
continue;
}
// Also assume that all primary edges are finite...
if (!it->is_finite()) {
std::cout << "WARNING: Primary, infinite edge..." << std::endl;
}
uint64_t cell_idx1 = it->cell()->source_index();
uint64_t cell_idx2 = it->twin()->cell()->source_index();
// The two sides of the edge have different components, its visible
if (this->components[cell_idx1] != this->components[cell_idx2]) {
Edge cur_edge = Edge(*it);
// This may not work if we have a curved and a straight edge with
// the same endpoints, but I don't think that will happen...
if (seen_edges.count(cur_edge) > 0) {
continue;
}
seen_edges.insert(cur_edge);
bool is_shading_edge = shading_edge(this->colors[cell_idx1].val, this->colors[cell_idx2].val);
using point_type = boost::polygon::point_data<vd_type::coordinate_type>;
std::vector<point_type> samples;
point_type vertex0(it->vertex0()->x(), it->vertex0()->y());
point_type vertex1(it->vertex1()->x(), it->vertex1()->y());
samples.push_back(vertex0);
samples.push_back(vertex1);
if (it->is_curved()) {
this->sample_curved_edge(*it, &samples);
}
std::vector<uint32_t> path_points;
std::vector<EdgeRef> path_edges;
for (uint32_t i = 0; i < samples.size(); i++) {
uint32_t pt_idx;
Point cur_pt = Point(samples[i].x(), samples[i].y());
auto pt_idx_it = this->point_map.find(cur_pt);
if (pt_idx_it == this->point_map.end()) {
pt_idx = this->all_points.size();
this->all_points.push_back(cur_pt);
this->point_map.insert({ cur_pt, pt_idx });
} else {
pt_idx = pt_idx_it->second;
}
path_points.push_back(pt_idx);
if (i != 0) path_edges.push_back({ path_points[i - 1], path_points[i], is_shading_edge });
}
for (uint32_t i = 0; i < samples.size(); i++) {
if (i != 0) adjacent_edges.insert({ path_points[i], path_edges[i - 1] });
if (i != samples.size() - 1) {
adjacent_edges.insert({ path_points[i], path_edges[i] });
component_edges[this->components[cell_idx1]].push_back(path_edges[i]);
component_edges[this->components[cell_idx2]].push_back(path_edges[i]);
}
}
}
}
// int hist[] = { 0, 0, 0, 0, 0, 0 };
// for (uint32_t i = 0; i < this->all_points.size(); i++) {
// hist[adjacent_edges.count(i) - 1]++;
// }
// std::cout << "Number of edges with given valences" << std::endl;
// for (int i = 0; i < 6; i++) {
// std::cout << i + 1 << ": " << hist[i] << std::endl;
// }
// cv::Mat im1 = cv::Mat::zeros(39 * 20, 49 * 20, CV_8UC3);
// for (uint32_t i = 0; i < this->all_points.size(); i++) {
// auto range = adjacent_edges.equal_range(i);
// for_each(
// range.first,
// range.second,
// [&](std::unordered_multimap<uint32_t, EdgeRef>::value_type &p){
// Point pt1 = this->all_points[p.second.idx1];
// Point pt2 = this->all_points[p.second.idx2];
// cv::line(im1, cv::Point(10 * pt1.x, 10 * pt1.y), cv::Point(10 * pt2.x, 10 * pt2.y), cv::Scalar(0, 0, 255), 1, 8);
// }
// );
// }
// cv::imshow("Image", im1);
// cv::waitKey(0);
this->component_paths = new Path[this->num_components]();
this->component_splines = new BSpline[this->num_components];
for (uint32_t i = 0; i < this->num_components; i++) {
join_edges(&this->component_paths[i], component_edges[i], adjacent_edges);
std::vector<Point*> ptr_path;
for (auto &p : this->component_paths[i]) {
ptr_path.push_back(&this->all_points[p.idx]);
}
this->component_splines[i] = BSpline(ptr_path);
}
// cv::Mat im2 = cv::Mat::zeros(39 * 20, 49 * 20, CV_8UC3);
// for (uint32_t i = 0; i < this->num_components; i++) {
// Path &cur_path = this->component_paths[i];
// for (uint32_t j = 0; j < cur_path.size(); j++) {
// PointRef prev_ptref = j == 0 ? cur_path.back() : cur_path[j - 1];
// PointRef cur_ptref = cur_path[j];
// Point pt1 = this->all_points[prev_ptref.idx];
// Point pt2 = this->all_points[cur_ptref.idx];
// cv::line(im2, cv::Point(10 * pt1.x, 10 * pt1.y), cv::Point(10 * pt2.x, 10 * pt2.y), cv::Scalar(255.0 * i / this->num_components, 255, 192), 1, 8);
// }
// }
// cv::cvtColor(im2, im2, CV_HSV2BGR);
// cv::imshow("Image", im2);
// cv::waitKey(0);
delete[] component_edges;
}
static inline double positional_energy(Point guess, Point initial)
{
using std::pow;
return pow(pow(guess.x - initial.x, 2) + pow(guess.y - initial.y, 2), 2);
}
void SplineOptimizer::optimize_splines()
{
const uint32_t NUM_ITERATIONS = 8;
const uint32_t GUESSES_PER_ITERATION = 16;
const double RADIUS = 0.125;
std::vector<Point> original_points(all_points.begin(), all_points.end());
for (uint32_t n1 = 0; n1 < NUM_ITERATIONS; n1++) {
for (uint32_t i = 0; i < this->num_components; i++) {
Path &cur_path = this->component_paths[i];
BSpline &cur_spline = this->component_splines[i];
int path_len = cur_path.size();
std::vector<int> indices;
for (int j = 0; j < path_len; j++) {
indices.push_back(j);
}
std::random_shuffle(indices.begin(), indices.end());
for (int &idx : indices) {
if (!cur_path[idx].can_optimize) {
continue;
}
for (uint32_t n2 = 0; n2 < GUESSES_PER_ITERATION; n2++) {
Point saved_old_pt = this->all_points[cur_path[idx].idx];
Point &old_pt = this->all_points[cur_path[idx].idx];
double orig_p_energy = positional_energy(old_pt, original_points[cur_path[idx].idx]);
double orig_s_energy = cur_spline.curvature_energy(idx);
double orig_energy = orig_p_energy + orig_s_energy;
Point r = random_point(RADIUS);
old_pt.x += r.x;
old_pt.y += r.y;
double p_energy = positional_energy(old_pt, original_points[cur_path[idx].idx]);
double s_energy = cur_spline.curvature_energy(idx);
double energy = p_energy + s_energy;
if (energy >= orig_energy) {
old_pt.x = saved_old_pt.x;
old_pt.y = saved_old_pt.y;
}
}
}
}
}
}
std::vector<Shape> SplineOptimizer::make_shapes()
{
std::vector<ColorPoint> *component_colors = new std::vector<ColorPoint>[this->num_components]();
for (vd_type::const_cell_iterator it = this->vd.cells().begin(); it != this->vd.cells().end(); ++it) {
Point centroid(0, 0);
uint32_t num_points = 0;
auto *edge = it->incident_edge();
if (edge == NULL) {
continue;
}
// Actually calculates the barycenter. Also leaves out infinite
// edges when those should be clipped to the edge of the image
do {
if (edge->vertex0()) {
centroid.x += edge->vertex0()->x();
centroid.y += edge->vertex0()->y();
num_points += 1;
}
if (edge->vertex1()) {
centroid.x += edge->vertex1()->x();
centroid.y += edge->vertex1()->y();
num_points += 1;
}
edge = edge->next();
} while (edge != it->incident_edge());
centroid.x /= num_points;
centroid.y /= num_points;
uint64_t idx = it->source_index();
component_colors[this->components[idx]].push_back({ centroid, this->colors[idx] });
}
std::vector<Shape> ret;
for (uint32_t i = 0; i < this->num_components; i++) {
// All credits to http://alienryderflex.com/polygon_area/
double area = 0;
Path edge = this->component_paths[i];
uint32_t k = edge.size() - 1;
for (uint32_t j = 0; j < edge.size(); j++) {
Point prev_pt = this->all_points[edge[k].idx];
Point next_pt = this->all_points[edge[j].idx];
area += (prev_pt.x + next_pt.x) * (prev_pt.y - next_pt.y);
k = j;
}
area = fabs(area * 0.5);
ret.push_back(Shape(this->component_splines[i], component_colors[i], area));
}
delete[] component_colors;
std::sort(ret.begin(), ret.end());
std::reverse(ret.begin(), ret.end());
return ret;
}
void SplineOptimizer::join_edges(Path *path, const std::vector<EdgeRef> &edges,
const std::unordered_multimap<uint32_t, EdgeRef> &adjacent_edges)
{
std::unordered_multimap<uint32_t, EdgeRef> adj_list;
for (auto &it : edges) {
adj_list.insert({ it.idx1, it });
adj_list.insert({ it.idx2, { it.idx2, it.idx1, it.is_shading_edge } });
}
path->push_back({ edges[0].idx1, true });
std::unordered_set<uint32_t> used_pts;
used_pts.insert(edges[0].idx1);
EdgeRef cur_edge = edges[0];
uint32_t next_pt = edges[0].idx2;
bool next_should_optimize = true;
do {
path->push_back({ next_pt, next_should_optimize });
used_pts.insert(next_pt);
// There can be one, in that case this might break...
auto range = adj_list.equal_range(next_pt);
next_pt = all_points.size();
for (auto it = range.first; it != range.second; ++it) {
if (used_pts.count(it->second.idx2) == 0) {
next_should_optimize = should_optimize(cur_edge, it->second, adjacent_edges);
cur_edge = it->second;
next_pt = cur_edge.idx2;
break;
}
}
} while (next_pt != all_points.size());
// Have to do the last one separately after we know what the last point
// in the path is
auto last_range = adj_list.equal_range(path->back().idx);
EdgeRef last_edge;
bool found = false;
for (auto it = last_range.first; it != last_range.second; ++it) {
if (it->second.idx2 == path->front().idx) {
last_edge = it->second;
found = true;
break;
}
}
// This should always be true...hopefully
if (found) {
path->front().can_optimize = should_optimize(last_edge, edges[0], adjacent_edges);
}
}
// Invariant: e1.idx2 == e2.idx1
bool SplineOptimizer::should_optimize(EdgeRef e1, EdgeRef e2,
const std::unordered_multimap<uint32_t, EdgeRef> &adjacent_edges)
{
assert(e1.idx2 == e2.idx1);
uint32_t common_pt = e1.idx2;
uint32_t num_edges_around = adjacent_edges.count(common_pt);
if (num_edges_around <= 2) {
return true;
} else if (num_edges_around >= 4) {
// If there are at least 4 edges, then this point is fixed.
return false;
}
// `last_edge` is guaranteed to be assigned in this loop; initialization
// is just to silence a compiler warning
EdgeRef last_edge = { 0, 0, false };
auto range = adjacent_edges.equal_range(common_pt);
for (auto it = range.first; it != range.second; ++it) {
if (it->second != e1 && it->second != e2) {
last_edge = it->second;
break;
}
}
uint32_t last_pt = last_edge.idx1 == common_pt ? last_edge.idx2 : last_edge.idx1;
// If we have 2 contour edges and 1 shading edge, then we can resolve the
// ambiguity easily: true iff both e1 and e2 are contour edges
int num_shading_edges = last_edge.is_shading_edge + e1.is_shading_edge + e2.is_shading_edge;
if (num_shading_edges == 1) {
return last_edge.is_shading_edge;
}
// Everything else failed, we have to measure the angles
Point e1_vec(this->all_points[e1.idx1].x - this->all_points[common_pt].x,
this->all_points[e1.idx1].y - this->all_points[common_pt].y);
Point e2_vec(this->all_points[e2.idx2].x - this->all_points[common_pt].x,
this->all_points[e2.idx2].y - this->all_points[common_pt].y);
Point last_vec(this->all_points[last_pt].x - this->all_points[common_pt].x,
this->all_points[last_pt].y - this->all_points[common_pt].y);
// Technically, we want the pair closest to 180 degrees. However,
// vector_angle will always return the principle angle (<180), so the
// largest angle will also be the one closest to 180
double e1_e2_angle = vector_angle(e1_vec, e2_vec);
return e1_e2_angle > vector_angle(e2_vec, last_vec) && e1_e2_angle > vector_angle(e1_vec, last_vec);
}
void SplineOptimizer::sample_curved_edge(const vd_type::edge_type& edge,
std::vector< boost::polygon::point_data<vd_type::coordinate_type> >* sampled_edge)
{
boost::polygon::point_data<int> point = edge.cell()->contains_point() ?
retrieve_point(*edge.cell()) :
retrieve_point(*edge.twin()->cell());
boost::polygon::segment_data<int> segment = edge.cell()->contains_point() ?
retrieve_segment(*edge.twin()->cell()) :
retrieve_segment(*edge.cell());
boost::polygon::voronoi_visual_utils<vd_type::coordinate_type>::discretize(
point, segment, 0.05, sampled_edge);
}
boost::polygon::point_data<int> SplineOptimizer::retrieve_point(const vd_type::cell_type& cell)
{
vd_type::cell_type::source_index_type index = cell.source_index();
vd_type::cell_type::source_category_type category = cell.source_category();
if (category == boost::polygon::SOURCE_CATEGORY_SINGLE_POINT) {
return this->point_data[index];
}
index -= this->point_data.size();
if (category == boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT) {
return low(this->segment_data[index]);
} else {
return high(this->segment_data[index]);
}
}
boost::polygon::segment_data<int> SplineOptimizer::retrieve_segment(const vd_type::cell_type& cell)
{
vd_type::cell_type::source_index_type index = cell.source_index() - this->point_data.size();
return this->segment_data[index];
}
} /* Depixelize */
|
accb9a8309cda5f37eaa4b5a818c39d093c81351 | 5f93e8a4a0694ca2d7593b4494ac8b7dc75536e2 | /PP2-TextAdventure/World.cpp | 2d605aa3d4357dad037d658249dfbbde99fa6d7d | [] | no_license | Phaktumn/PP2-TextAdventure | 965d110b7acda6274e626ec763236d758900eb71 | dd74b5e8d556b7920a33782bd58a418ced7d29d4 | refs/heads/development | 2020-12-11T05:39:26.125874 | 2016-04-11T15:32:03 | 2016-04-11T15:32:03 | 54,288,239 | 0 | 0 | null | 2016-03-19T21:36:51 | 2016-03-19T21:36:51 | null | UTF-8 | C++ | false | false | 4,266 | cpp | World.cpp | #include "World.h"
#include "Globals.h"
void World::draw(sf::RenderWindow* window, sf::Font& font)
{
currentLocation->draw(window, font);
}
void World::moveTo(const std::string& name)
{
Location* loc = getLocation(name);
if (loc == nullptr) return;
if (!currentLocation->hasPath(loc)) {
std::cout << "Current location is not connected to " << name << "." << std::endl;
return;
}
currentLocation = loc;
std::cout << "Moved to " << loc->getName() << "." << std::endl;
connections.clear();
for (size_t i = 0; i < currentLocation->connections.size(); i++) {
connections.push_back(currentLocation->connections[i].location->getName());
}
}
void World::addLocation(const std::string& name, const std::string& description, int locationLevel)
{
locations.push_back(std::shared_ptr<Location>(new Location(name, description, locationLevel)));
if (locations.size() == 1) {
currentLocation = locations[0].get();
}
}
void World::addLocation(const std::string& name, const std::string& description, sfe::RichText displayName, sfe::RichText displayDescription, int locationLevel)
{
displayName.setPosition(LOCATION_NAME_POSITION_X, LOCATION_NAME_POSITION_Y);
displayDescription.setPosition(LOCATION_DESCRIPTION_POSITION_X, LOCATION_DESCRIPTION_POSITION_Y);
Location* loc = new Location(name, description, displayName, displayDescription, locationLevel);
locations.push_back(std::shared_ptr<Location>(loc));
if (locations.size() == 1){
currentLocation = locations[0].get();
}
}
void World::connect(const std::string& start, const std::string& dest, int distance, bool twoWay)
{
Location* startLoc = getLocation(start);
Location* destLoc = getLocation(dest);
if (startLoc == nullptr) {
printf("Specified start location does not exit.");
return;
}
if (destLoc == nullptr) {
printf("Specified destination location does not exit.");
return;
}
Path path = Path{ distance, destLoc };
startLoc->addConnection(path);
if (!twoWay) return;
path = Path{ distance, startLoc };
destLoc->addConnection(path);
}
World::Location* World::getLocation(const std::string& name)
{
for (size_t i = 0; i < locations.size(); i++) {
if (locations[i].get()->getName() == name) {
return locations[i].get();
}
}
return nullptr;
}
void World::debugPrintConnections(const std::string& name)
{
Location* loc = getLocation(name);
if (loc == nullptr) return;
loc->debugPrintConnections();
}
void World::Location::draw(sf::RenderWindow* window, sf::Font& font)
{
if (!hasDisplay) return;
drawText(LOCATION_NAME_POSITION_X + 300, LOCATION_NAME_POSITION_Y, sfe::RichText(font) << "Location NPC LvL: " << sf::Color::Red << std::to_string(zoneLevel), CHARACTER_SIZE, window);
window->draw(_displayName);
window->draw(_displayDescription);
}
std::map<int, World::Location*> World::getConnections()
{
Location* loc = currentLocation;
path__locations.clear();
int i = 0, std_map__counter = 0;
while (true)
{
if (GameManager::getLocationName(i) == "") break;
if (loc->hasPath(getLocation(GameManager::getLocationName(i))))
{
path__locations.emplace(std_map__counter, getLocation(GameManager::getLocationName(i)));
std_map__counter++;
}
i++;
}
return path__locations;
}
bool World::circuitExists(Location* location)
{
bool circuitExists = false;
for (size_t i = 0; i < location->connections.size(); i++) {
circuitExists = pathExists(location->connections[i].location, location);
if (circuitExists) { return circuitExists; }
}
return circuitExists;
}
bool World::pathExists(Location* start, Location* end)
{
bool exists = false;
for (size_t i = 0; i < start->connections.size(); i++) {
if (start->connections[i].location == end) {
return true;
}
exists = true * pathExists(start->connections[i].location, end);
}
return exists;
}
void World::Location::drawText(float x, float y, const std::string& text, sf::Font& font, int size, sf::RenderWindow* window){
sf::Text _text;
_text.setPosition(x, y);
_text.setString(text);
_text.setFont(font);
_text.setCharacterSize(size);
window->draw(_text);
}
void World::Location::drawText(float x, float y, sfe::RichText text, int size, sf::RenderWindow* window){
text.setPosition(x, y);
text.setCharacterSize(size);
window->draw(text);
} |
a7f5df1815d001bc2c1e0b12e62df1c032c969a3 | 6d3bb23428c196a3cf63efcf8d9654a0cc32adb6 | /Codeforces: Div1 553A. A. Kyoya and Colored Balls.cpp | ce5f8983ba64c5f21119ec423e8f5a1144fd31f9 | [] | no_license | antimatter007/DP-Problem-Solution | 2d1cd9773e4c646f318401df78bcd7ddf09b4dde | 98e120c73137c5b62ee19ed8d9a91ebbed4a0efb | refs/heads/master | 2023-04-09T12:02:24.360436 | 2021-03-10T20:49:44 | 2021-03-10T20:49:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,183 | cpp | Codeforces: Div1 553A. A. Kyoya and Colored Balls.cpp |
/// Codeforces: Div1 553A. A. Kyoya and Colored Balls
/// Category : dp+combinatorics. an easy one .
#include<bits/stdc++.h>
using namespace std;
/// Every time we can fix a ball of the i colour at the end and fill the former places with other balls
/// Thus we can get the answer for when only k=2.
/// Now when k=3,new color balls are available then put one ball at last place and other ball of this color will be placed other places
/// For every possible answer of color (k=2) ,we can get different ways so count f(i-1)*f(i) and so on.
typedef long long ll;
const int mx=1010;
ll nCr[mx][mx];
const ll mod = 1000000007;
void pre_compute()
{
nCr[0][0]=1ll;
for(int i=1;i<mx;i++)
{
nCr[i][0]=1;
for(int j=1;j<=i;j++)
{
nCr[i][j]=(nCr[i-1][j]+nCr[i-1][j-1])%mod;
}
}
}
int main()
{
pre_compute();
int k;
cin>>k;
int color[k];
for(int i=0;i<k;i++) cin>>color[i];
ll result=1ll;
ll tota_balls=0ll;
for(int i=0;i<k;i++)
{
tota_balls+=(ll)color[i];
result*=(nCr[tota_balls-1][color[i]-1]);
result%=mod;
}
cout<<(result%mod)<<endl;
return 0;
}
|
776c0030187d8edd0d474a624194c314239d029a | ca27fe38d4f61981b0186dac5c974d5ea0f0a0a6 | /cppDir/GroupBy.cc | 3ffc00eb1cf789a28625151183dd09e40184fde8 | [] | no_license | google-code/490db | 5e73196ed328b65584375402d64bc7f29a92f9c2 | aba162f343d9319386be7d03c455b369669202eb | refs/heads/master | 2016-09-05T19:20:09.858240 | 2015-03-13T15:45:35 | 2015-03-13T15:45:35 | 32,164,746 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,329 | cc | GroupBy.cc | #include <stdlib.h>
#include <strings.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>
#include "EfficientMap.cc"
#include "TwoWayList.cc"
#include "Types.cc"
class AggRecord;
class InRecord
{
private:
#include "Atts.cc"
friend class AggRecord;
public:
InRecord() {}
~InRecord() {}
bool ReadIn(FILE *fromMe)
{
bool res;
#include "ReadIn.cc"
fgetc_unlocked (fromMe);
return res;
}
long GetHash()
{
long hash = 0;
#include "Hashing.cc"
return hash;
}
void Aggregate(AggRecord & aggMe);
};
class AggRecord
{
private:
#include "AggAtts.cc"
friend class InRecord;
public:
bool Matches(InRecord & aggMe)
{
#include "CheckSameGroup.cc"
}
void Swap(AggRecord & withMe)
{
char temp[sizeof (AggRecord)];
memmove (temp, this, sizeof (AggRecord));
memmove (this, &withMe, sizeof (AggRecord));
memmove (&withMe, temp, sizeof (AggRecord));
}
void WriteOut(FILE *toMe)
{
#include "WriteOut.cc"
fputc_unlocked('\n', toMe);
}
AggRecord () {};
~AggRecord () {};
};
void InRecord :: Aggregate (AggRecord & aggMe)
{
#include "DoAgg.cc"
}
class Hash
{
private:
long value;
public:
Hash (long inVal)
{
value = inVal;
}
~Hash () {}
Hash () {}
void Swap(Hash & withMe)
{
long temp = value;
value = withMe.value;
withMe.value = temp;
}
int IsEqual(Hash & withMe)
{
return withMe.value == value;
}
int LessThan(Hash & withMe)
{
return withMe.value < value;
}
};
int
main(int numArgs, char **args)
{
if (numArgs != 3)
{
fprintf(stderr, "Usage: GroupBy inputFile outputFile\n");
exit(-1);
}
// this is the main lookup table for the join
EfficientMap <Hash, TwoWayList <AggRecord> > lookupTable;
// first, we read in the small input table
FILE *inFile = fopen (args[1], "r");
// now go through the small table and hash everything
InRecord myRec;
while (myRec.ReadIn (inFile))
{
Hash myHash (myRec.GetHash ());
// if that hash value is already there, then see if there is a match
bool gotOne = false;
if (lookupTable.IsThere (myHash))
{
TwoWayList <AggRecord> &values = lookupTable.Find (myHash);
// look thru every potential match
for (values.MoveToStart (); values.RightLength (); values.Advance ())
{
if (values.Current ().Matches (myRec))
{
myRec.Aggregate (values.Current ());
gotOne = true;
}
}
// if we got no match, then add to the table
if (!gotOne)
{
AggRecord temp;
myRec.Aggregate (temp);
values.Insert (temp);
values.MoveToStart ();
}
continue;
}
// if we got no match, then add to the table
AggRecord temp;
myRec.Aggregate (temp);
TwoWayList <AggRecord> newList;
newList.Insert (temp);
lookupTable.Insert (myHash, newList);
}
// now, at this point, we've aggregated everything, so we can write it out
fclose (inFile);
FILE *outFile = fopen (args[2], "w");
for (lookupTable.MoveToStart (); !lookupTable.AtEnd (); lookupTable.Advance ())
{
TwoWayList <AggRecord> ¤t = lookupTable.CurrentData ();
for (current.MoveToStart (); current.RightLength (); current.Advance ())
{
current.Current ().WriteOut (outFile);
}
}
fclose (outFile);
return 0;
}
|
7e193e12b2cef3ee1adb91bd4378df062c91cbd6 | 8d57489e484b2def01f27a8a00e41ee6932a4905 | /Pintia-ds/PopSequence.cpp | 6fef79b3326056932c49b9daf8dd0747ff3adea9 | [] | no_license | athelare/SourceCode-ACM | f8c3a5d4f308de3ffaabd371c85f22a4a0225613 | b0385ef8409f3f3b3dbf77e9ad326d13fed9171c | refs/heads/master | 2020-03-24T07:54:17.769303 | 2018-11-25T01:26:55 | 2018-11-25T01:26:55 | 142,578,771 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 648 | cpp | PopSequence.cpp | #include<iostream>
#define MXN 1005
#define INIT \
sp = 0; \
k = 1;
#define POP --sp
#define TOP Stack[sp - 1]
#define PUSH Stack[sp++] = k++;
using namespace std;
int main()
{
int Stack[MXN], Sequ[MXN], M, N, K,i,j,k,sp;
cin >> M >> N >> K;
while(K--){
for (i = 0; i < N;++i)
cin >> Sequ[i];
INIT;
for (i = 0; i < N;++i){
while(sp == 0 || TOP < Sequ[i])
PUSH;
if(TOP != Sequ[i] || sp>M){
cout << "NO" << endl;
break;
}
POP;
}
if(i==N)cout << "YES" << endl;
}
return 0;
} |
525a03defbb21cd4a2630b42c361b6bdcc79649d | f0bd42c8ae869dee511f6d41b1bc255cb32887d5 | /Codeforces/58A - Chat room.cpp | 9e29a8557c01a3168996049b27e1604adc228c09 | [] | no_license | osamahatem/CompetitiveProgramming | 3c68218a181d4637c09f31a7097c62f20977ffcd | a5b54ae8cab47b2720a64c68832a9c07668c5ffb | refs/heads/master | 2021-06-10T10:21:13.879053 | 2020-07-07T14:59:44 | 2020-07-07T14:59:44 | 113,673,720 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 374 | cpp | 58A - Chat room.cpp | #include<stdio.h>
main()
{
int i=0,j=0;
char in[101],hello[6]={'h','e','l','l','o'};
gets(in);
while(in[i]!='\0')
{
if(in[i]==hello[j])
{
j++;
}
if(j==5)
{
break;
}
i++;
}
if(j==5)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
|
b7de4e000f29692abd04d9cab160cf596ae2e6b4 | 783c65250483abd3e1f79a40a5acc2eb5f83da14 | /GameMemory.h | a4d58b4baffb87d9485462387217b084293ddef7 | [] | no_license | FredericDesgreniers/comp472 | 90f8e16e4f5907c701fcd2f9dee5bc1037dfbe72 | afb30c6c980bf262f9ebf0f1b298601806cbe26d | refs/heads/master | 2021-08-22T09:31:08.902826 | 2017-11-29T21:39:40 | 2017-11-29T21:39:40 | 106,746,666 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,841 | h | GameMemory.h | #pragma once
#include <vector>
#include "vec2.h"
#define BOARD_WIDTH 9
#define BOARD_HEIGHT 5
enum TileType
{
INVALID, EMPTY, GREEN, RED
};
static bool isBlackReferenceBoard[5][9] =
{
1, 0, 1, 0, 1,
0, 1, 0, 1, 0,
1, 0, 1, 0, 1,
0, 1, 0, 1, 0,
1, 0, 1, 0, 1,
0, 1, 0, 1, 0,
1, 0, 1, 0, 1,
0, 1, 0, 1, 0,
1, 0, 1, 0, 1,
};
class MoveResult
{
bool valid;
public:
MoveResult(bool valid): valid(valid)
{
}
bool isValid() const
{
return valid;
}
};
class GameMemory
{
TileType tiles[BOARD_HEIGHT][BOARD_WIDTH];
TileType currentTurn = GREEN;
std::vector<vec2> greenPositions;
std::vector<vec2> redPositions;
unsigned int turnsWithoutAttack = 0;
public:
GameMemory();
static TileType playerType;
bool isPositionOnBoard(vec2 position);
TileType getTileAt(const vec2 &position);
void setTileAt(vec2 position, TileType type);
TileType* getTileArray()
{
return (TileType *)tiles;
}
void start();
void doAiMove();
void generateTile(vec2 vec2);
MoveResult doMove(vec2 origin, vec2 destination);
MoveResult doMoveUnsafe(const vec2 &origin, const vec2 &destination);
bool isValidMove(vec2 origin, vec2 destination);
void getKillsInDirection(const vec2 origin, const vec2 direction, std::vector<vec2> &killList);
std::vector<vec2> getKillsInDirection(const vec2 origin, const vec2 direction);
void nextTurn();
TileType getCurrentTurn()
{
return currentTurn;
}
const std::vector<vec2> &getGreenPositions()
{
return greenPositions;
}
const std::vector<vec2> &getRedPositions()
{
return redPositions;
}
TileType getPlayerType()
{
return playerType;
}
void setPlayerType(TileType pType)
{
playerType = pType;
}
unsigned int getTurnsWithoutAttack()
{
return turnsWithoutAttack;
}
std::vector<vec2>& getCurrentTurnTokenList();
};
|
798dfcc349830b47ce2a1d4597dca8e3acd1b442 | f1415cbffc54d9e9e66ad32f5a5bfa98f70f4632 | /cpp/cpp_day11/Date.h | f28f94cd78bec7984a46174d01527e7a28fed781 | [] | no_license | wallmamami/Daily-life | 6052d73d3c7ad7d07bd512391ffe429a43df7c19 | cf6eec5fc5bffed88794c9f588076fa86cd107bd | refs/heads/master | 2020-03-18T06:29:04.449067 | 2019-07-30T04:05:38 | 2019-07-30T04:05:38 | 134,398,585 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,765 | h | Date.h | #pragma once
#include <iostream>
using namespace std;
class Date
{
public:
friend ostream& operator<< (ostream& os, const Date& d);//定义<<运算符重载为类的友元函数
//类的默认成员函数
Date(int year = 1900, int month = 1, int day = 1)//构造函数
: _year(year)
, _month(month)
, _day(day)
{
if (_year < 1990 || _month < 1 || _day < 1 || GetMonth(_year, _month))
{//非法日期
cout << "Invalid Date " << endl;
}
}
bool Isleap(int year)
{
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
{
return true;
}
return false;
}
int GetMonth(int year, int month)//获取该月的天数
{
if (month < 1 || month > 12)
{
cout << "Invalid month" << endl;
return 0;
}
int monthday[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (Isleap(year))//瑞年二月29天
{
monthday[2] = 29;
}
return monthday[month];
}
Date(const Date& d)//拷贝构造
: _year(d._year)
, _month(d._month)
, _day(d._day)
{
}
Date& operator=(const Date& d)//赋值运算符重载
{
_year = d._year;
_month = d._month;
_day = d._day;
return *this;
}
/*日期类的基本操作函数*/
//日期编辑哦
bool operator==(const Date& d);
bool operator!=(const Date& d);
bool operator>(const Date& d);
bool operator<(const Date& d);
bool operator>=(const Date& d);
bool operator<=(const Date& d);
//日期计算
Date operator+ (int day);
Date& operator+= (int day);
Date operator- (int day);
Date& operator-= (int day);
Date operator++ (int); //后置++
Date& operator++ (); //前置++
Date operator-- (int);
Date& operator-- ();
int operator- (const Date& d);//计算两个日期相差的天数
private:
int _year;
int _month;
int _day;
}; |
66f58148970f79aa8f71d19d7ee98db8c1c999f6 | e4e2a9dc58fcc0bc41e268b354d943846202928b | /c++/matriz3D.cpp | af40cb2ada0a65f53a78b8b7debba6c50aa57765 | [] | no_license | Carlos-Rodolfo-Rodriguez/Carlos-Rodolfo-Rodriguez.github.io | 713316922d3901fd304bb7e97f67d6fa0dc6875f | 6b14da1df87eb7a6350625f5773b9413acf7ae6b | refs/heads/master | 2022-04-22T18:14:51.313165 | 2020-04-16T20:01:27 | 2020-04-16T20:01:27 | 256,269,877 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,216 | cpp | matriz3D.cpp | #include <program1.h> // Archivo de traducción de seudocódigo a C++
/**
* Enunciado:
*/
constante entera T1 = 2, T2 =3, T3 = 4;
#define matriz(tipo,tam) array<tipo,tam>
principal // Unidad de programa principal
arreglo3D(real,T1,T2,T3) mat3D;
limpiar; // Limpia la pantalla.
entero cuenta {0};
paraCada(fila,mat3D)
mostrar << "Fila:" << salto;
paraCada(colu,fila)
mostrar << "Columna:" << salto;
paraCada(ele,colu)
ele = cuenta++;
mostrar << ele << ", ";
finParaCada
mostrar << salto;
finParaCada
mostrar << salto;
finParaCada
entero fila,colu,prof;
variar(fila,0,T1-1,1)
mostrar << "Fila:"<<fila << salto;
variar(colu,0,T2-1,1)
mostrar << "Columna:"<< colu << salto;
variar(prof,0,T3-1,1)
mostrar << mat3D[fila][colu][prof] << ", ";
finVariar
mostrar << salto;
finVariar
mostrar << salto;
finVariar
pausa; // Pausa antes de finalizar.
finPrincipal
|
1c6b91c14c7d9ac4b3264429a66ede553dfe1bf9 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /ash/system/network/cellular_setup_notifier_unittest.cc | 512c3ff7e61706af1ff8e20b12f52923a488b053 | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 9,331 | cc | cellular_setup_notifier_unittest.cc | // Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/network/cellular_setup_notifier.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/session/session_controller_impl.h"
#include "ash/shell.h"
#include "ash/system/system_notification_controller.h"
#include "ash/test/ash_test_base.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/timer/mock_timer.h"
#include "chromeos/ash/components/dbus/hermes/hermes_clients.h"
#include "chromeos/ash/components/dbus/shill/shill_clients.h"
#include "chromeos/ash/components/network/network_cert_loader.h"
#include "chromeos/ash/components/network/network_handler.h"
#include "chromeos/ash/components/network/system_token_cert_db_storage.h"
#include "chromeos/ash/services/network_config/public/cpp/cros_network_config_test_helper.h"
#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h"
#include "components/prefs/pref_service.h"
#include "third_party/cros_system_api/dbus/shill/dbus-constants.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/public/cpp/notification.h"
namespace ash {
namespace {
const char kShillManagerClientStubCellularDevice[] =
"/device/stub_cellular_device";
const char kShillManagerClientStubCellularDeviceName[] = "stub_cellular_device";
} // namespace
class CellularSetupNotifierTest : public NoSessionAshTestBase {
protected:
CellularSetupNotifierTest() = default;
CellularSetupNotifierTest(const CellularSetupNotifierTest&) = delete;
CellularSetupNotifierTest& operator=(const CellularSetupNotifierTest&) =
delete;
~CellularSetupNotifierTest() override = default;
void SetUp() override {
SystemTokenCertDbStorage::Initialize();
NetworkCertLoader::Initialize();
shill_clients::InitializeFakes();
hermes_clients::InitializeFakes();
NetworkHandler::Initialize();
network_config_helper_ =
std::make_unique<network_config::CrosNetworkConfigTestHelper>();
AshTestBase::SetUp();
auto mock_notification_timer = std::make_unique<base::MockOneShotTimer>();
mock_notification_timer_ = mock_notification_timer.get();
Shell::Get()
->system_notification_controller()
->cellular_setup_notifier_->SetTimerForTesting(
std::move(mock_notification_timer));
base::RunLoop().RunUntilIdle();
}
void TearDown() override {
AshTestBase::TearDown();
network_config_helper_.reset();
NetworkHandler::Shutdown();
hermes_clients::Shutdown();
shill_clients::Shutdown();
NetworkCertLoader::Shutdown();
SystemTokenCertDbStorage::Shutdown();
}
// Returns the cellular setup notification if it is shown, and null if it is
// not shown.
message_center::Notification* GetCellularSetupNotification() {
return message_center::MessageCenter::Get()->FindVisibleNotificationById(
CellularSetupNotifier::kCellularSetupNotificationId);
}
void LogIn() { SimulateUserLogin("user1@test.com"); }
void LogOut() { ClearLogin(); }
void LogInAndFireTimer() {
LogIn();
EXPECT_TRUE(GetCanCellularSetupNotificationBeShown());
ASSERT_TRUE(mock_notification_timer_->IsRunning());
mock_notification_timer_->Fire();
// Wait for the async network calls to complete.
base::RunLoop().RunUntilIdle();
}
bool GetCanCellularSetupNotificationBeShown() {
PrefService* prefs =
Shell::Get()->session_controller()->GetLastActiveUserPrefService();
return prefs->GetBoolean(prefs::kCanCellularSetupNotificationBeShown);
}
void SetCanCellularSetupNotificationBeShown(bool value) {
PrefService* prefs =
Shell::Get()->session_controller()->GetLastActiveUserPrefService();
prefs->SetBoolean(prefs::kCanCellularSetupNotificationBeShown, value);
}
// Ownership passed to Shell owned CellularSetupNotifier instance.
raw_ptr<base::MockOneShotTimer, DanglingUntriaged | ExperimentalAsh>
mock_notification_timer_;
std::unique_ptr<network_config::CrosNetworkConfigTestHelper>
network_config_helper_;
};
TEST_F(CellularSetupNotifierTest, DontShowNotificationUnfinishedOOBE) {
ASSERT_FALSE(mock_notification_timer_->IsRunning());
message_center::Notification* notification = GetCellularSetupNotification();
EXPECT_FALSE(notification);
}
TEST_F(CellularSetupNotifierTest, ShowNotificationUnactivatedNetwork) {
network_config_helper_->network_state_helper().AddDevice(
kShillManagerClientStubCellularDevice, shill::kTypeCellular,
kShillManagerClientStubCellularDeviceName);
LogInAndFireTimer();
message_center::Notification* notification = GetCellularSetupNotification();
EXPECT_TRUE(notification);
EXPECT_FALSE(GetCanCellularSetupNotificationBeShown());
}
TEST_F(CellularSetupNotifierTest, DontShowNotificationActivatedNetwork) {
network_config_helper_->network_state_helper().AddDevice(
kShillManagerClientStubCellularDevice, shill::kTypeCellular,
kShillManagerClientStubCellularDeviceName);
const std::string& cellular_path_ =
network_config_helper_->network_state_helper().ConfigureService(
R"({"GUID": "cellular_guid", "Type": "cellular", "Technology": "LTE",
"State": "idle"})");
network_config_helper_->network_state_helper().SetServiceProperty(
cellular_path_, shill::kActivationStateProperty,
base::Value(shill::kActivationStateActivated));
LogInAndFireTimer();
message_center::Notification* notification = GetCellularSetupNotification();
EXPECT_FALSE(notification);
EXPECT_FALSE(GetCanCellularSetupNotificationBeShown());
}
TEST_F(CellularSetupNotifierTest, ShowNotificationMultipleUnactivatedNetworks) {
network_config_helper_->network_state_helper().AddDevice(
kShillManagerClientStubCellularDevice, shill::kTypeCellular,
kShillManagerClientStubCellularDeviceName);
network_config_helper_->network_state_helper().ConfigureService(
R"({"GUID": "cellular_guid", "Type": "cellular", "Technology": "LTE",
"State": "idle"})");
network_config_helper_->network_state_helper().ConfigureService(
R"({"GUID": "cellular_guid1", "Type": "cellular", "Technology": "LTE",
"State": "idle"})");
LogInAndFireTimer();
message_center::Notification* notification = GetCellularSetupNotification();
EXPECT_TRUE(notification);
EXPECT_FALSE(GetCanCellularSetupNotificationBeShown());
}
TEST_F(CellularSetupNotifierTest, LogOutBeforeNotificationShowsLogInAgain) {
network_config_helper_->network_state_helper().AddDevice(
kShillManagerClientStubCellularDevice, shill::kTypeCellular,
kShillManagerClientStubCellularDeviceName);
LogIn();
ASSERT_TRUE(mock_notification_timer_->IsRunning());
LogOut();
ASSERT_FALSE(mock_notification_timer_->IsRunning());
LogInAndFireTimer();
message_center::Notification* notification = GetCellularSetupNotification();
EXPECT_TRUE(notification);
EXPECT_FALSE(GetCanCellularSetupNotificationBeShown());
}
TEST_F(CellularSetupNotifierTest, LogInAgainAfterShowingNotification) {
network_config_helper_->network_state_helper().AddDevice(
kShillManagerClientStubCellularDevice, shill::kTypeCellular,
kShillManagerClientStubCellularDeviceName);
LogInAndFireTimer();
message_center::Notification* notification = GetCellularSetupNotification();
EXPECT_TRUE(notification);
EXPECT_FALSE(GetCanCellularSetupNotificationBeShown());
message_center::MessageCenter::Get()->RemoveNotification(
CellularSetupNotifier::kCellularSetupNotificationId, false);
LogOut();
LogIn();
ASSERT_FALSE(mock_notification_timer_->IsRunning());
}
TEST_F(CellularSetupNotifierTest, LogInAgainAfterCheckingNonCellularDevice) {
LogInAndFireTimer();
message_center::Notification* notification = GetCellularSetupNotification();
EXPECT_FALSE(notification);
EXPECT_FALSE(GetCanCellularSetupNotificationBeShown());
LogOut();
LogIn();
ASSERT_FALSE(mock_notification_timer_->IsRunning());
}
TEST_F(CellularSetupNotifierTest, RemoveNotificationAfterAddingNetwork) {
network_config_helper_->network_state_helper().AddDevice(
kShillManagerClientStubCellularDevice, shill::kTypeCellular,
kShillManagerClientStubCellularDeviceName);
LogInAndFireTimer();
message_center::Notification* notification = GetCellularSetupNotification();
EXPECT_TRUE(notification);
EXPECT_FALSE(GetCanCellularSetupNotificationBeShown());
const std::string& cellular_path_ =
network_config_helper_->network_state_helper().ConfigureService(
R"({"GUID": "cellular_guid", "Type": "cellular", "Technology": "LTE",
"State": "idle"})");
base::RunLoop().RunUntilIdle();
// Notification is not removed after adding unactivated network.
notification = GetCellularSetupNotification();
EXPECT_TRUE(notification);
network_config_helper_->network_state_helper().SetServiceProperty(
cellular_path_, shill::kActivationStateProperty,
base::Value(shill::kActivationStateActivated));
base::RunLoop().RunUntilIdle();
notification = GetCellularSetupNotification();
EXPECT_FALSE(notification);
ASSERT_FALSE(mock_notification_timer_->IsRunning());
}
} // namespace ash
|
7a3120b81ffb3e020075a1950aae5ab1153c8a88 | 21c599c04672445e0c021eeb4a759908c2bd4436 | /iOS/SDK/Bearers/vncbearer-D/Buffer.h | 50084c36a633d6a49ffb9d6ab929302c1adec1b8 | [] | no_license | 892526/tlink | ae507c3b3cd6e9821f035b2103fbcf256ad80fee | 28d86935c27a14a816c75107b711b92c0c8582e4 | refs/heads/master | 2022-03-04T05:21:51.163507 | 2019-06-20T09:46:08 | 2019-06-20T09:46:08 | 167,317,060 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,132 | h | Buffer.h | /* Copyright (C) 2002-2018 VNC Automotive Ltd. All Rights Reserved.
*/
#ifndef __BUFFER_H__
#define __BUFFER_H__
#include <vector>
class Buffer
{
public:
inline Buffer();
inline unsigned char *getData();
inline const unsigned char *getData() const;
inline size_t getCapacity() const;
inline size_t getUsed() const;
inline size_t getFree() const;
void reserve(size_t n);
void append(const unsigned char *p, size_t n);
inline void use(size_t n);
void free(size_t n);
inline void clear();
private:
typedef std::vector<unsigned char> Data;
Data data;
size_t used;
};
inline Buffer::Buffer()
: data(0),
used(0)
{
}
inline const unsigned char *Buffer::getData() const
{
return &data[0];
}
inline unsigned char *Buffer::getData()
{
return &data[0];
}
inline size_t Buffer::getCapacity() const
{
return data.size();
}
inline size_t Buffer::getUsed() const
{
return used;
}
inline size_t Buffer::getFree() const
{
return data.size() - used;
}
inline void Buffer::use(size_t n)
{
used += n;
}
inline void Buffer::clear()
{
data.resize(0);
}
#endif /* !defined(__BUFFER_H__) */
|
c84e8e973bc3ad3f90d59617b1d04cbcd9a6608a | 939506ab5e6730545cdadc44d504e795255206cf | /CS162 Intro to Computer Science 2/test/pokemon.h | 65e9300e2f7bb1d5af07b7fc8cc32079e234755f | [] | no_license | nguyepe2/class_courses | a603672d1e9a2563768652565e41165dea995dae | f149a22949ee5dc8b8a0f99f13edfd3b61c455aa | refs/heads/master | 2022-12-10T03:15:32.384895 | 2022-04-03T05:26:18 | 2022-04-03T05:26:18 | 245,482,086 | 0 | 5 | null | 2022-12-09T02:03:09 | 2020-03-06T17:41:08 | C | UTF-8 | C++ | false | false | 207 | h | pokemon.h | #ifndef POKEMON_H
#define POKEMON_H
#include "event.h"
class pokemon : public event {
private:
int rng;
public:
pokemon();
void get_event();
virtual void get_capture_rate();
};
#endif
|
9678fadd9a1d5383c11671e067aa3bd72acf1058 | 586e12e4bd6ba9eb4cd35d4376b0082195d94397 | /Pandemic/Pandemic/togglePlayerStats.h | 8ab66a56268a8a4e51ea96c2fe8a020fed707ca9 | [] | no_license | RyanL94/Pandemic | 257eba23236eec1daa1a8d42c33c899b3014d25e | 4955553c81989f063e3fbce54db628da0fc148a1 | refs/heads/master | 2020-09-19T20:05:48.023201 | 2017-04-19T03:55:37 | 2017-04-19T03:55:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,471 | h | togglePlayerStats.h | #pragma once
#include <string>
#include <vector>
#include <iostream>
#include "player.h"
#include "map.h"
#include "Observer.h"
using namespace std;
class togglePlayerStats
{
public:
togglePlayerStats();
virtual string getGameLog(Player* p) = 0;
static void getStats(Player* p);
};
class basicStats : public togglePlayerStats {
public:
string getGameLog(Player* p) {
string back = "Player" + p -> getPlayerID();
return back + " has: /n";
}
};
class togglePlayerDecorator : public togglePlayerStats {
protected:
togglePlayerStats *toggledView;
public:
togglePlayerDecorator(togglePlayerStats *toggledView) {
this->toggledView = toggledView;
}
string getGameLog(Player* p) {
return toggledView->getGameLog(p);
}
};
class playerAction :public togglePlayerDecorator {
public:
playerAction(togglePlayerStats *toggledView) : togglePlayerDecorator(toggledView) {}
string getGameLog(Player* p) {
return togglePlayerDecorator::getGameLog(p);
}
};
class drawPlayerCard :public togglePlayerDecorator {
public:
drawPlayerCard(togglePlayerStats *toggledView) : togglePlayerDecorator(toggledView) {}
string getGameLog(Player* p) {
return togglePlayerDecorator::getGameLog(p);// +p->displayCardsInHand();
}
};
class drawInfection :public togglePlayerDecorator {
public:
drawInfection(togglePlayerStats *toggledView) : togglePlayerDecorator(toggledView) {}
string getGameLog(Player* p) {
return togglePlayerDecorator::getGameLog(p);
}
};
|
5d75ccebdfd44e6784f74df3d6f8fb8b0fecccd5 | 769a77f0d86cb17ce1391917cf54bebda1245245 | /include/BiasValues.hpp | 5b984a4cd2edf19bdeb2bf0bba9325155276d2ad | [] | no_license | mdh266/PECS | 13a3e4d7b7d88722608729af49c98590efd94777 | 7af9f6c064d96dc257afd10546fcb4276a2639e5 | refs/heads/master | 2021-04-09T10:28:15.770367 | 2017-03-23T17:20:07 | 2017-03-23T17:20:07 | 61,489,926 | 3 | 1 | null | 2019-05-03T07:49:43 | 2016-06-19T16:42:21 | C++ | UTF-8 | C++ | false | false | 2,305 | hpp | BiasValues.hpp | #ifndef _BOUNDARY_VALUES_H___
#define _BOUNDARY_VALUES_H___
#include <deal.II/base/function.h>
#include <deal.II/lac/vector.h>
using namespace dealii;
///////////////////////////////////////////////////////////////////////////////
// Poisson Boundary Functions
///////////////////////////////////////////////////////////////////////////////
/** \brief The built in bias of the semiconductor \$f\Phi_{\text{bi}}\f$.*/
template <int dim>
class Built_In_Bias : public dealii::Function<dim>
{
public:
/** \brief Default constructor.*/
Built_In_Bias() : dealii::Function<dim>()
{}
void set_value(const double & bias_value);
/** \brief Returns value of \$f\Phi_{\text{bi}}\f$ at point p.*/
virtual double value(const dealii::Point<dim> &p,
const unsigned int component = 0 ) const;
private:
double built_in_bias;
};
/** \brief The schottky bias \$f\Phi_{\text{sch}}\f$.*/
template <int dim>
class Schottky_Bias : public dealii::Function<dim>
{
public:
/** \brief Default constructor.*/
Schottky_Bias() : dealii::Function<dim>()
{}
void set_location(const double & bias_location);
void set_value(const double & bias_value);
/** \brief Returns value of \$f\Phi_{\text{sch.}}\f$ at point p.*/
virtual double value(const dealii::Point<dim> &p,
const unsigned int component = 0 ) const;
private:
double Schottky_bias;
double Schottky_location;
};
/** \brief The applied bias \$f\Phi_{\text{app}}\f$.*/
template <int dim>
class Applied_Bias : public dealii::Function<dim>
{
public:
/** \brief Default constructor.*/
Applied_Bias() : dealii::Function<dim>()
{}
void set_value(const double & bias_value);
/** \brief Returns value of \$f\Phi_{\text{app.}}\f$ at point p.*/
virtual double value(const dealii::Point<dim> &p,
const unsigned int component = 0 ) const;
private:
double applied_bias;
};
/** \brief The bulk bias of the electrolyte \$f\Phi^{\infty}\f$.*/
template <int dim>
class Bulk_Bias : public dealii::Function<dim>
{
public:
/** \brief Default constructor.*/
Bulk_Bias() : dealii::Function<dim>()
{}
/** \brief Returns value of \$f\Phi^{\infty}}\f$ at point p.*/
virtual double value(const dealii::Point<dim> &p,
const unsigned int component = 0 ) const;
};
#endif
|
9c06808bc6b75ad6d1aed87c7d8490ff3f304b08 | 2bfbf9e4ce069c2f0258b65361aa7db9833ce14c | /p2pserver/udpserver.cpp | a028215a7f3adb9ee0eee3bba8df13694d13633c | [] | no_license | se19880529/eagle_craft | cb15802ab323e3fa5d17534d46d2f2d0edc15cea | 0f954846df2d01248204f92bbd1d0c79ef3989fc | refs/heads/master | 2016-09-06T01:24:27.706308 | 2014-10-12T15:19:55 | 2014-10-12T15:19:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,543 | cpp | udpserver.cpp | #include "udpheader.h"
#include <stack>
template<typename T>
class DictionaryTree
{
public:
bool Get(char* key, T& val)
{
Node* n = &root;
while(*key && n)
{
n = n->childs[*(key++) - 32];
}
if(!*key && n && n->settled)
{
val = n->val;
return true;
}
else
return false;
}
void Set(char* key, T val)
{
Node* n = &root;
while(*key)
{
if(!n->childs[*key-32])
{
n->childs[*key-32] = new Node();
}
n = n->childs[*key-32];
key++;
}
n->settled = true;
n->val = val;
}
void Dump()
{
std::stack<Node*> q;
char key[256];
int keyid = 0;
q.push(&root);
cout<<"Dump DictionaryTree:"<<endl;
while(!q.empty())
{
Node* n = q.top();
q.pop();
if(n == NULL)
{
keyid--;
key[keyid] = 0;
}
else if((unsigned long)n < 256)
{
key[keyid] = *(char*)&n;
keyid++;
key[keyid] = 0;
}
else
{
if(n->settled)
{
cout<<key<<":"<<n->val<<endl;
}
for(int i = 0; i < 256; i++)
{
if(n->childs[i] != NULL)
{
q.push(NULL);
q.push(n->childs[i]);
q.push((Node*)(i+32));
}
}
}
}
}
private:
class Node
{
public:
Node()
{
for(int i = 0; i < 256; i++)
childs[i] = NULL;
settled = false;
}
Node* childs[256];
T val;
bool settled;
};
Node root;
};
class P2PServer
{
public:
P2PServer()
{
sock = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in addr;
addr.sin_port = htons(8887);
addr.sin_addr.s_addr = inet_addr("10.211.55.2");
bind(sock, (sockaddr*)&addr, sizeof(sockaddr_in));
}
void Send(char* ip, unsigned short port, P2PProtocol& p)
{
sockaddr_in addr;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ip);
char buffer[4096];
char* end = p.Write(buffer, buffer+4095);
cout<<"send data to "<<ip<<":"<<port<<endl;
BufferDump(buffer, end-buffer);
sendto(sock, buffer, end-buffer,0, (const sockaddr*)&addr, sizeof(sockaddr_in));
}
void HandleProtocol()
{
char buffer[4096];
sockaddr_in addr;
socklen_t len = sizeof(addr);
int bufferlen = recvfrom(sock, buffer, 4096, 0, (sockaddr*)&addr, &len);
cout<<"received data size:"<<bufferlen<<endl;
BufferDump(buffer, bufferlen);
if(bufferlen > 4)
cout<<"protocol type:"<<P2PProtocol::PeekType(buffer, bufferlen)<<endl;
P2PProtocol* p = NULL;
switch(P2PProtocol::PeekType(buffer, bufferlen))
{
case AddPeerProtocol::TYPE:
p = new AddPeerProtocol();
break;
case QueryPeerProtocol::TYPE:
p = new QueryPeerProtocol();
break;
case MakeHoleAgree::TYPE:
p = new MakeHoleAgree();
break;
}
if(p)
{
cout<<"find protocol:"<<p->type<<endl;
p->Read(buffer, bufferlen);
OnProtocol(*p, sock, inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
delete p;
}
}
void OnProtocol(P2PProtocol& p, int socket, char* ip, unsigned short port)
{
switch(p.type)
{
case AddPeerProtocol::TYPE:
{
AddPeerProtocol& peer = *(AddPeerProtocol*)&p;
if(peer.id < 0)
{
peer.id = _sessionSeed++;
}
if(peer.name[0])
{
_dict.Set(peer.name, peer.id);
_nameMap[peer.id] = peer.name;
cout<<"dump _dict"<<endl;
_dict.Dump();
}
_cache.AddPeer(peer.id, ip, port);
cout<<"add peer request from"<<ip<<":"<<port<<" with name "<<peer.name<<endl;
AddPeerResultProtocol p;
p.retcode = 0;
p.id = peer.id;
Send(ip, port, p);
}
break;
case QueryPeerProtocol::TYPE:
{
QueryPeerProtocol& query = *(QueryPeerProtocol*)&p;
long id;
cout<<"query peer request from "<<_nameMap[query.id]<<" in "<<ip<<":"<<port<<" for "<<query.user_query<<endl;
if(_dict.Get(query.user_query, id))
{
PeerInfo* info = _cache.GetPeerInfo(id);
if(info != NULL)
{
MakeHoleRequest req;
strcpy(req.ip, ip);
strcpy(req.name, _nameMap[query.id].c_str());
req.port = port;
req.type = MakeHoleRequest::TYPE;
Send(info->ip, info->port, req);
cout<<"query peer request success, find peer "<<info->ip<<":"<<info->port<<endl;
}
}
}
break;
case MakeHoleAgree::TYPE:
{
MakeHoleAgree& re = *(MakeHoleAgree*)&p;
QueryPeerReProtocol p;
strcpy(p.ip, ip);
strcpy(p.name, re.name);
p.port = port;
Send(re.ip, re.port, p);
cout<<"peer hole made for "<<re.ip<<":"<<re.port<<" at "<<ip<<":"<<port<<endl;
}
break;
}
}
private:
int sock;
P2PCache _cache;
long _sessionSeed;
map<long, string> _nameMap;
DictionaryTree<long> _dict;
};
int main()
{
P2PServer server;
while(true)
{
server.HandleProtocol();
}
return 0;
}
|
0caec00939e2f139d513bcc3709b6a2512eec9ef | d1a60cb1d08d820f1fb56d15dd149faf276e3f88 | /include/rtvideosdk/shinevv++/vv_device.hpp | 1ed15be75dfce5991efef8deea7bdf68ab5862c2 | [
"MIT"
] | permissive | hanson1977/rtvideo | 9c9b5024ceb64bff5f329f5485d3a3468362e6af | ce2dc900f09b6590a451ef6ebe34b6885c203365 | refs/heads/main | 2023-06-26T02:11:16.828493 | 2021-07-28T05:55:53 | 2021-07-28T05:55:53 | 390,224,728 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,124 | hpp | vv_device.hpp | #ifndef __VV__DEVICE_HPP__
#include "shinevv.h"
#define __VV__DEVICE_HPP__
class VVDevice {
public:
VVDevice() {};
//重置摄像头
virtual void ResetCapture(int idx, int width, int height, int fps) = 0;
//开启摄像头
virtual void StartCapture() = 0;
//停止摄像头
virtual void StopCapture() = 0;
//增加摄像头预览窗口
virtual void AddCapturePreview(void* window) = 0;
//移除摄像头预览
virtual void RemoveCapturePreview(void* window) = 0;
//devices manager
virtual int GetVideoDevices(vv_device_info deviceInfo[]) = 0;
//切换摄像头,桌面共享,RTSP摄像头等其他源
virtual void SetVideoSource(const char* sourceUrl) = 0;
//音频设备
virtual int GetAudioDevices(vv_device_info deviceInfo[]) = 0;
public:
void SetCameraCapture(int idx, int width, int height, int fps) {
_config._index = idx;
_config._width = width;
_config._height = height;
_config._fps = fps;
}
public:
struct Config {
public:
Config() {};
int _index = 0;
int _width = 1920;
int _height = 1080;
int _fps = 25;
}_config;
};
#endif
|
f58878aed4f4d0899ec819cdbe4f39f50d74e7fd | 773a806e909dfb79fd8c1389d1e10847f6d32aaa | /STRIPS/Source and Header Files/libs.h | df04c070982e0b10a04e832c567f3d392dff6268 | [] | no_license | Mopson/STRIPS-Planner | 9e0caee324f151bbd3d2fe8e3c3d974f3eddd9de | 023f7ca5885ac9a0d03d6adab52df16c277d416c | refs/heads/master | 2021-01-22T06:19:52.195551 | 2017-06-05T23:46:43 | 2017-06-05T23:46:43 | 92,545,640 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 207 | h | libs.h | #pragma once
#ifndef LIBS_H_
#define LIBS_H_
#include <iostream>
#include <vector>
#include <list>
#include <sstream>
#include <string>
#include <fstream>
using namespace std;
#endif // LIBS_H_ |
823c2f1f36672b15e477a35b160fda024e0f35bb | eddcd87c24939a0b9d35bfd52401a2ecd62c04de | /developing/yggdrasil/yggr/proxy/proxy_mode/proxy_mode_creator.hpp | f3dc50f3e7d0dec8f071879ac2969f2fea3fe02e | [] | no_license | chinagdlex/yggdrasil | 121539b5f4d171598be2bb79d36f5d673ad11cb4 | 16f6192fd0011dc3f7c1a44f8d4d2a8ba9bc8520 | refs/heads/master | 2021-03-12T19:08:19.120204 | 2016-09-26T09:36:19 | 2016-09-26T09:36:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,500 | hpp | proxy_mode_creator.hpp | //proxy_mode_creator.hpp
#ifndef __YGGR_PROXY_PROXY_MODE_PROXY_MODE_CREATOR_HPP__
#define __YGGR_PROXY_PROXY_MODE_PROXY_MODE_CREATOR_HPP__
#include <algorithm>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/push_back.hpp>
#include <yggr/ppex/friend.hpp>
#include <yggr/base/interface_ptr.hpp>
#include <yggr/proxy/proxy_mode/basic_proxy_mode.hpp>
#include <yggr/safe_container/safe_unordered_map.hpp>
namespace yggr
{
namespace proxy
{
namespace proxy_mode
{
template<typename ModeVector,
typename OwnerInfoContainer>
class proxy_mode_creator
{
public:
typedef ModeVector mode_vt_type;
typedef OwnerInfoContainer owner_info_container_type;
//typedef OwnerIDContainer owner_id_container_type;
typedef basic_proxy_mode<
owner_info_container_type
> base_proxy_mode_type;
typedef typename base_proxy_mode_type::owner_id_container_type owner_id_container_type;
typedef yggr::interface_ptr<base_proxy_mode_type> interface_proxy_mode_type;
private:
typedef proxy_mode_creator this_type;
typedef interface_proxy_mode_type (this_type::*creator_type)(void) const;
typedef u32 key_type;
typedef safe_container::safe_unordered_map<key_type, creator_type> creator_map_type;
enum
{
E_mode_length = boost::mpl::size<mode_vt_type>::value,
E_compile_u32 = 0xffffffff
};
struct end_creator
{
bool operator()(creator_map_type& map)
{
return true;
}
};
template<u32 idx, u32 idx_size>
struct init_creator
{
private:
typedef proxy_mode_creator parent_type;
YGGR_PP_FRIEND_TYPENAME(parent_type);
typedef typename boost::mpl::at_c<mode_vt_type, idx>::type mode_type;
enum
{
E_mode = mode_type::E_mode
};
BOOST_MPL_ASSERT((boost::is_same<typename mode_type::owner_info_container_type, owner_info_container_type>));
BOOST_MPL_ASSERT((boost::is_same<typename mode_type::owner_id_container_type, owner_id_container_type>));
typedef init_creator this_type;
public:
bool operator()(creator_map_type& map)
{
if(!map.insert(this_type::E_mode, &parent_type::prv_create_mode<mode_type>))
{
return false;
}
typename boost::mpl::if_c
<
(idx + 1 < idx_size),
init_creator<idx + 1, idx_size>,
end_creator
>::type init;
return init(map);
}
};
public:
proxy_mode_creator(void)
{
init_creator<0, E_mode_length> init;
init(_creator_map);
assert((_creator_map.size() == this_type::E_mode_length));
}
~proxy_mode_creator(void)
{
_creator_map.clear();
}
interface_proxy_mode_type operator()(const key_type& key) const
{
return _creator_map.use_handler(boost::bind(&this_type::handler_creator, this, _1, boost::cref(key)));
}
private:
template<typename T>
interface_proxy_mode_type prv_create_mode(void) const
{
return interface_proxy_mode_type(new T());
}
interface_proxy_mode_type
handler_creator(const typename creator_map_type::base_type& base, const key_type& key) const
{
typedef typename creator_map_type::const_iterator citer_type;
citer_type iter = base.find(key);
if(iter == base.end())
{
return interface_proxy_mode_type();
}
assert(iter->second);
return (this->*(iter->second))();
}
private:
creator_map_type _creator_map;
};
} // namespace proxy_mode
} // namespace proxy
} // namespace yggr
#endif //__YGGR_PROXY_PROXY_MODE_PROXY_MODE_CREATOR_HPP__
|
e5b6fc5d39f3821711c70d7b3481ed10a39cc3e2 | 7ca92ca80333e35d0d3488184cc2479863e738bd | /2.2-ExpressionTree/TEST_ExprTree.cpp | 4346d80485d5326f5899f4b4768c79902286a7d2 | [] | no_license | MMMMMMoSky/cpp-course | dabaa97b9d8d90c3683ec0da0fefa71ca378ebf0 | 5c02f35a7990eb3d8d08de864bc145576989dc46 | refs/heads/master | 2020-04-28T14:04:30.015188 | 2019-04-19T07:09:44 | 2019-04-19T07:09:44 | 175,326,955 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,837 | cpp | TEST_ExprTree.cpp | /**
* Copyright (c) 2019 MMMMMMoSky All rights reserved.
*
* 单元测试
* g++ ExprTree.cpp TEST_ExprTree.cpp -o tmp -g
*/
#include "ExprTree.h"
#include <iostream>
using namespace std;
int main()
{
/* 测试二叉树的构造和display
ExprTree expr("(1+2)*(4-3)");
expr.display();
expr = "((1+2)*(4-3))";
expr.display();
expr = "1+2-3/(4*5-6)";
expr.display();
// 已通过 */
/* 测试转换回中缀
string expr = "(1+2)*(4-3)";
ExprTree exprTree(expr);
cout << "原表达式: " << expr << endl;
cout << "建树转回: " << exprTree.toInfixExpression() << endl;
expr = "((1+2)*(4-3))";
exprTree = expr;
cout << "原表达式: " << expr << endl;
cout << "建树转回: " << exprTree.toInfixExpression() << endl;
expr = "1+2-3/(4*5-6)";
exprTree = expr;
cout << "原表达式: " << expr << endl;
cout << "建树转回: " << exprTree.toInfixExpression() << endl;
// 通过 */
/* 测试转换回中缀/后缀
string expr = "(1+2)*(4-3)";
ExprTree exprTree(expr);
cout << "原表达式: " << expr << endl;
cout << "转回中缀: " << exprTree.toInfixExpression() << endl;
cout << "转回后缀: " << exprTree.toPostfixExpression() << endl;
expr = "((1+2)*(4-3))";
exprTree = expr;
cout << "原表达式: " << expr << endl;
cout << "转回中缀: " << exprTree.toInfixExpression() << endl;
cout << "转回后缀: " << exprTree.toPostfixExpression() << endl;
expr = "1+2-3/(4*5-6)";
exprTree = expr;
cout << "原表达式: " << expr << endl;
cout << "转回中缀: " << exprTree.toInfixExpression() << endl;
cout << "转回后缀: " << exprTree.toPostfixExpression() << endl;
// 通过 */
return 0;
} |
5e06c7a6ac01b05ed2a0b9892281c590b38b8945 | ef35552267ac45345c60135845470260afbd6687 | /libalcc/libalcc.cpp | 85f18c1b65dc2e1b838cc6065e7dc6339dffe869 | [
"MIT"
] | permissive | xianliangjiang/ALCC | 2bbe7e48aaf7ab273cfea4622855be12e261730f | fc9c627de8c381987fc775ce0872339fceb43ddf | refs/heads/main | 2023-05-16T21:11:06.738812 | 2021-06-10T11:43:23 | 2021-06-10T11:43:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,771 | cpp | libalcc.cpp | #include <stdio.h>
#include <iostream>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include "libalcc.h"
#include <time.h>
#include <cstdio>
#include <memory>
#include <mutex>
#include <linux/netlink.h>
#include <math.h>
#define MYPROTO NETLINK_USERSOCK
# define NETLINK_TEST 17
std::map < int, ALCCSocket * > alccSocketList;
Circular_Queue::Circular_Queue(int queue_length) {
this->MAX = queue_length;
this->cqueue_arr = new char[MAX];
this->front = 0;
this->rear = 0;
pthread_mutex_init( & lockBuffer, NULL);
}
int Circular_Queue::insert(char * item, int len, ofstream & log) {
if (front == rear)
len = fmin(len, MAX);
else if (front < rear)
len = fmin(len, MAX - rear + front - 1);
else
len = fmin(len, front - rear - 1);
if (len == 0) {
return len;
}
pthread_mutex_lock( & lockBuffer);
if ((front <= rear && MAX - rear - 1 >= len) || rear < front) {
memcpy(cqueue_arr + rear, item, len);
rear = (rear + len) % MAX;
} else {
memcpy(cqueue_arr + rear, item, MAX - rear);
memcpy(cqueue_arr, item + MAX - rear, len - (MAX - rear));
rear = len - (MAX - rear);
}
pthread_mutex_unlock( & lockBuffer);
return len;
}
int Circular_Queue::remove(char * chunk, int len) {
pthread_mutex_lock( & lockBuffer);
if (front == rear) {
pthread_mutex_unlock( & lockBuffer);
return 0;
} else if (front < rear)
len = fmin(len, rear - front);
else
len = fmin(len, MAX - front + rear);
if (front < rear || (rear < front && MAX - front >= len)) {
memcpy(chunk, cqueue_arr + front, len);
front = (front + len) % MAX;
} else {
memcpy(chunk, cqueue_arr + front, MAX - front);
memcpy(chunk + MAX - front, cqueue_arr, len - (MAX - front));
front = len - (MAX - front);
}
pthread_mutex_unlock( & lockBuffer);
return len;
}
int Circular_Queue::length(ofstream & log) {
int len;
pthread_mutex_lock( & lockBuffer);
if (front <= rear)
len = rear - front;
else
len = MAX - front + rear;
pthread_mutex_unlock( & lockBuffer);
return len;
}
ALCCSocket::ALCCSocket(long queue_length, int new_sockfd, int port) {
this->rcvSeq = 0;
this->rcvSeqLast = 0;
this->tcpSeq = 0;
this->terminateThreads = false;
this->sentSeq = 0;
this->tempS = 1;
this->pktsInFlight = 0;
this->sending_queue = new Circular_Queue(queue_length);
this->port = port;
struct stat info;
time_t now;
time( & now);
struct tm * now_tm;
now_tm = localtime( & now);
char timeString[80];
strftime(timeString, 80, "%Y-%m-%d_%H:%M:%S", now_tm);
if (stat(timeString, & info) != 0) {
sprintf(command, "exec mkdir /tmp/%s", timeString);
system(command);
}
sprintf(command, "/tmp/%s/info.out", timeString);
infoLog.open(command, ios::out);
sprintf(command, "/tmp/%s/Receiver.out", timeString);
receiverLog.open(command, ios::out);
gettimeofday( & startTime, NULL);
ack_receiver_thread = thread( & ALCCSocket::ack_receiver, this, new_sockfd);
pkt_sender_thread = thread( & ALCCSocket::pkt_sender, this, new_sockfd);
}
int ALCCSocket::pkt_sender(int sockfd) {
int ret, z, size;
int sPkts;
char * data;
struct timeval pktTime;
data = (char * ) malloc(MTU);
usleep(100000);
// write2Log(infoLog, "ALCC sending thread started", "", "", "", "");
while (!terminateThreads) {
while (tempS > 0 && !terminateThreads) {
sPkts = tempS;
// recording the sending times for each packet sent
gettimeofday( & pktTime, NULL);
for (int i = 0; i < sPkts; i++) {
size = sending_queue->remove(data, MTU);
if (size == 0) // queue is empty and tempS is still big
break;
sentSeq++;
z = 0;
while (z < size) {
ret = ::send(sockfd, data + z, size - z, 0);
z += ret;
}
tempS -= 1;
pktsInFlight += 1;
write2Log(infoLog, "Sent pkt", std::to_string(sentSeq), std::to_string(size), std::to_string(pktsInFlight), std::to_string(cwnd));
seqNumbersList[sentSeq] = pktTime;
}
}
}
return 0;
}
int ALCCSocket::ack_receiver(int sockfd) {
struct timeval receivedtime;
struct timeval sendTime;
double delay;
int sock;
int numAcks;
int group = NETLINK_TEST;
unsigned src_port;
unsigned dst_port;
unsigned long rcv_seq;
unsigned long ack_seq;
char buffer[257];
int ret;
struct sockaddr_nl addr;
struct msghdr msg;
struct iovec iov;
iov.iov_base = (void * ) buffer;
iov.iov_len = sizeof(buffer);
msg.msg_name = (void * ) & (addr);
msg.msg_namelen = sizeof(addr);
msg.msg_iov = & iov;
msg.msg_iovlen = 1;
sock = socket(AF_NETLINK, SOCK_RAW, MYPROTO);
if (sock < 0) {
printf("sock < 0.\n");
return sock;
}
memset((void * ) & addr, 0, sizeof(addr));
addr.nl_family = AF_NETLINK;
addr.nl_pid = getpid();
if (bind(sock, (struct sockaddr * ) & addr, sizeof(addr)) < 0) {
printf("bind < 0.\n");
return -1;
}
if (setsockopt(sock, 270, NETLINK_ADD_MEMBERSHIP, & group, sizeof(group)) < 0) {
printf("setsockopt < 0\n");
return -1;
}
if (sock < 0)
return sock;
while (!terminateThreads) {
ret = recvmsg(sock, & msg, 0);
if (ret < 0) {
printf("ret < 0.\n");
write2Log(infoLog, "error ret < 0", "", "", "", "");
} else {
sscanf((char * ) NLMSG_DATA((struct nlmsghdr * ) & buffer), "%u %u %lu %lu", & src_port, & dst_port, & rcv_seq, & ack_seq);
// getting the starting sequence number
if (tcpSeq == 0 && src_port == 60001) {
tcpSeq = rcv_seq;
write2Log(infoLog, "Starting Seq", std::to_string(tcpSeq), "", "", "");
cc_loigc_thread = thread( & ALCCSocket::CC_logic, this);
continue;
} else if (src_port == 60001)
continue;
// write2Log(receiverLog, "KERN", std::to_string(rcv_seq), std::to_string(ack_seq), std::to_string(rcvSeq), std::to_string((ack_seq - tcpSeq) / MTU));
int64_t diff = tcpSeq - ack_seq;
gettimeofday( & receivedtime, NULL);
if (tcpSeq > 0 && (ack_seq >= tcpSeq || diff > pow(2, 31))) {
int num = (ack_seq - tcpSeq) / MTU;
// checking for seq numbers wrap-around
if (num < 0) {
rcvSeq += (pow(2, 32) - tcpSeq + ack_seq) / MTU;
} else {
rcvSeq += num;
}
tcpSeq = ack_seq;
if (seqNumbersList.begin()->first <= rcvSeq && seqNumbersList.size() > 0) {
if (seqNumbersList.find(rcvSeq) != seqNumbersList.end()) {
sendTime = seqNumbersList.find(rcvSeq)->second;
delay = (receivedtime.tv_sec - sendTime.tv_sec) * 1000.0 + (receivedtime.tv_usec - sendTime.tv_usec) / 1000.0;
write2Log(receiverLog, std::to_string(rcvSeq), std::to_string(delay), "", "", "");
numAcks = rcvSeq - rcvSeqLast;
pktsInFlight -= numAcks;
if (rcvSeq >= rcvSeqLast + 1) {
rcvSeqLast = rcvSeq;
}
if (seqNumbersList.find(rcvSeq) != seqNumbersList.end()) {
seqNumbersList.erase(rcvSeq);
}
}
}
}
}
}
return 0;
}
int ALCCSocket::CC_logic() {
// fixed cwnd
cwnd = 20;
while (!terminateThreads) {
tempS += fmax(0, cwnd - pktsInFlight - tempS);
// write2Log(infoLog, "pkts in flight", std::to_string(pktsInFlight), "cwnd", std::to_string(cwnd), "");
usleep(EPOCH);
}
infoLog.close();
receiverLog.close();
return 0;
}
void ALCCSocket::write2Log(std::ofstream & logFile, std::string arg1, std::string arg2, std::string arg3, std::string arg4, std::string arg5) {
double relativeTime;
struct timeval currentTime;
gettimeofday( & currentTime, NULL);
relativeTime = (currentTime.tv_sec - startTime.tv_sec) + (currentTime.tv_usec - startTime.tv_usec) / 1000000.0;
logFile << relativeTime << "," << arg1;
if (arg2 != "")
logFile << "," << arg2;
if (arg3 != "")
logFile << "," << arg3;
if (arg4 != "")
logFile << "," << arg4;
if (arg5 != "")
logFile << "," << arg5;
logFile << "\n";
logFile.flush();
return;
}
int alcc_accept(int sockfd, struct sockaddr * addr, socklen_t * addrlen) {
int new_sockfd = ::accept(sockfd, addr, addrlen);
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
getpeername(new_sockfd, (struct sockaddr * ) & sin, & len);
ALCCSocket * alcc = new ALCCSocket(10000000, new_sockfd, ntohs(sin.sin_port));
alccSocketList[new_sockfd] = alcc;
int sndbuf = 10000000;
if (::setsockopt(new_sockfd, SOL_SOCKET, SO_SNDBUF, & sndbuf, sizeof(sndbuf)) < 0) {
alcc->infoLog << "Couldnt set the TCP send buffer size" << endl;
perror("socket error() set buf");
}
int rcvbuf = 10000000;
if (::setsockopt(new_sockfd, SOL_SOCKET, SO_RCVBUF, & rcvbuf, sizeof(rcvbuf)) < 0) {
alcc->infoLog << "Couldnt set the TCP send buffer size" << endl;
perror("socket error() set buf");
}
int flag = 1;
int result = ::setsockopt(new_sockfd, IPPROTO_TCP, TCP_NODELAY, (char * ) & flag, sizeof(int));
if (result < 0)
perror("socket error() set TCP_NODELAY");
return new_sockfd;
}
int alcc_send(int sockfd,
const char * buffer, int buflen, int flags) {
ALCCSocket * alcc;
if (alccSocketList.find(sockfd) != alccSocketList.end()) {
alcc = alccSocketList.find(sockfd)->second;
}
return alcc->sending_queue->insert((char * ) buffer, buflen, alcc->infoLog);
}
int alcc_close(int sockfd) {
ALCCSocket * alcc;
if (alccSocketList.find(sockfd) != alccSocketList.end()) {
alcc = alccSocketList.find(sockfd)->second;
}
while (alcc->sending_queue->length(alcc->infoLog) > 0)
usleep(1);
alcc->terminateThreads = true;
alcc->write2Log(alcc->infoLog, "closing connection", "", "", "", "");
delete alcc;
close(sockfd);
return 1;
} |
b56d8090afcc297fdb3c52f00a23ebf17d64bc59 | 1dff02275f30fe1b0c5b4f15ddd8954cae917c1b | /ugene/src/corelibs/U2Core/src/dbi/U2SQLiteTripleStore.cpp | 1bc3215c93356a451b1a9a268b2c2bc5d176f841 | [
"MIT"
] | permissive | iganna/lspec | eaba0a5de9cf467370934c6235314bb2165a0cdb | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | refs/heads/master | 2021-05-05T09:03:18.420097 | 2018-06-13T22:59:08 | 2018-06-13T22:59:08 | 118,641,727 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,416 | cpp | U2SQLiteTripleStore.cpp | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2012 UniPro <ugene@unipro.ru>
* http://ugene.unipro.ru
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <sqlite3.h>
#include <U2Core/Log.h>
#include <U2Core/U2SafePoints.h>
#include <U2Core/U2SqlHelpers.h>
#include "U2SQLiteTripleStore.h"
namespace U2 {
/************************************************************************/
/* Triplet */
/************************************************************************/
Triplet::Triplet(const QString &_key, const QString &_role, const QString &_value)
: id(-1), key(_key), role(_role), value(_value)
{
}
Triplet::Triplet(const Triplet& other)
: id(other.id), key(other.key), role(other.role), value(other.value)
{
}
QString Triplet::getKey() const {
return key;
}
QString Triplet::getRole() const {
return role;
}
QString Triplet::getValue() const {
return value;
}
/************************************************************************/
/* Owner */
/************************************************************************/
Owner::Owner(const QString &_name)
: id(-1), name(_name)
{
}
Owner::Owner(const Owner &owner) {
id = owner.id;
name = owner.name;
}
QString Owner::getName() const {
return name;
}
/************************************************************************/
/* U2SQLiteTripleStore */
/************************************************************************/
U2SQLiteTripleStore::U2SQLiteTripleStore() {
state = U2DbiState_Void;
db = new DbRef();
}
U2SQLiteTripleStore::~U2SQLiteTripleStore() {
delete db;
}
void U2SQLiteTripleStore::init(const QString &url, U2OpStatus &os) {
if (db->handle != NULL) {
os.setError(TripleStoreL10N::tr("Database is already opened!"));
return;
}
if (state != U2DbiState_Void) {
os.setError(TripleStoreL10N::tr("Illegal database state: %1").arg(state));
return;
}
state = U2DbiState_Starting;
if (url.isEmpty()) {
os.setError(TripleStoreL10N::tr("URL is not specified"));
state = U2DbiState_Void;
return;
}
do {
int flags = SQLITE_OPEN_READWRITE;
flags |= SQLITE_OPEN_CREATE;
QByteArray file = url.toUtf8();
int rc = sqlite3_open_v2(file.constData(), &db->handle, flags, NULL);
if (rc != SQLITE_OK) {
QString err = db->handle == NULL ? QString(" error-code: %1").arg(rc) : QString(sqlite3_errmsg(db->handle));
os.setError(TripleStoreL10N::tr("Error opening SQLite database: %1!").arg(err));
break;
}
SQLiteQuery("PRAGMA synchronous = OFF", db, os).execute();
SQLiteQuery("PRAGMA main.locking_mode = NORMAL", db, os).execute();
SQLiteQuery("PRAGMA temp_store = MEMORY", db, os).execute();
SQLiteQuery("PRAGMA journal_mode = MEMORY", db, os).execute();
SQLiteQuery("PRAGMA cache_size = 10000", db, os).execute();
// check if the opened database is valid sqlite dbi
if (isEmpty(os)) {
createTables(os);
if (os.hasError()) {
break;
}
}
// OK, initialization complete
if (!os.hasError()) {
ioLog.trace(QString("SQLite: initialized: %1\n").arg(url));
}
} while (0);
if (os.hasError()) {
sqlite3_close(db->handle);
db->handle = NULL;
state = U2DbiState_Void;
return;
}
state = U2DbiState_Ready;
}
static int isEmptyCallback(void *o, int argc, char ** /*argv*/, char ** /*column*/) {
int* res = (int*)o;
*res = argc;
return 0;
}
bool U2SQLiteTripleStore::isEmpty(U2OpStatus &os) const {
QMutexLocker lock(&db->lock);
QByteArray showTablesQuery = "SELECT * FROM sqlite_master WHERE type='table';";
int nTables = 0;
char* err;
int rc = sqlite3_exec(db->handle, showTablesQuery.constData(), isEmptyCallback, &nTables, &err);
if (rc != SQLITE_OK) {
os.setError(TripleStoreL10N::tr("Error checking SQLite database: %1!").arg(err));
sqlite3_free(err);
return false;
}
return nTables == 0;
}
void U2SQLiteTripleStore::createTables(U2OpStatus &os) {
QMutexLocker lock(&db->lock);
SQLiteQuery("CREATE TABLE Triplets (id INTEGER PRIMARY KEY AUTOINCREMENT, "
"key TEXT NOT NULL, role TEXT NOT NULL, value TEXT NOT NULL)", db, os).execute();
}
void U2SQLiteTripleStore::shutdown(U2OpStatus &os) {
if (db == NULL) {
os.setError(TripleStoreL10N::tr("Database is already closed!"));
return;
}
if (state != U2DbiState_Ready) {
os.setError(TripleStoreL10N::tr("Illegal database state %1!").arg(state));
return;
}
state = U2DbiState_Stopping;
{
int rc = sqlite3_close(db->handle);
if (rc != SQLITE_OK) {
QString err = db->handle == NULL ? QString(" error-code: %1").arg(rc) : QString(sqlite3_errmsg(db->handle));
ioLog.error(TripleStoreL10N::tr("Failed to close triple store database: %1").arg(err));
}
db->handle = NULL;
}
state = U2DbiState_Void;
return;
}
void U2SQLiteTripleStore::addValue(const Triplet &value, U2OpStatus &os) {
QMutexLocker lock(&db->lock);
bool found = false;
// find triplet
qint64 dataId = this->getTripletId(value, found, os);
CHECK_OP(os, );
if (!found) { // insert triplet
dataId = this->insertTriplet(value, os);
CHECK_OP(os, );
}
}
bool U2SQLiteTripleStore::contains(const QString &key, const QString &role, U2OpStatus &os) const {
QMutexLocker lock(&db->lock);
QString value = this->getValue(key, role, os);
return !value.isEmpty();
}
bool U2SQLiteTripleStore::contains(const Triplet &value, U2OpStatus &os) const {
QMutexLocker lock(&db->lock);
static const QString queryString("SELECT t.id FROM Triplets t WHERE t.key = ?1 AND t.role = ?2 AND t.value = ?3");
SQLiteQuery q(queryString, db, os);
q.bindString(1, value.getKey());
q.bindString(2, value.getRole());
q.bindString(3, value.getValue());
if (q.step()) {
QString result = q.getString(0);
q.ensureDone();
return true;
}
return false;
}
QString U2SQLiteTripleStore::getValue(const QString &key, const QString &role, U2OpStatus &os) const {
QMutexLocker lock(&db->lock);
static const QString queryString("SELECT t.value FROM Triplets t WHERE t.key = ?1 AND t.role = ?2 ORDER BY t.id");
SQLiteQuery q(queryString, db, os);
q.bindString(1, key);
q.bindString(2, role);
QStringList results;
while (q.step()) {
results << q.getString(0);
}
return results.isEmpty() ? "" : results.last();
}
qint64 U2SQLiteTripleStore::getTripletId(const Triplet &triplet, bool &found, U2OpStatus &os) const {
QMutexLocker lock(&db->lock);
static const QString queryString("SELECT t.id FROM Triplets t WHERE t.key = ?1 AND t.role = ?2 AND t.value = ?3");
SQLiteQuery q(queryString, db, os);
q.bindString(1, triplet.getKey());
q.bindString(2, triplet.getRole());
q.bindString(3, triplet.getValue());
found = false;
if (q.step()) {
qint64 dataId = q.getInt64(0);
q.ensureDone();
found = true;
return dataId;
}
return 0;
}
qint64 U2SQLiteTripleStore::insertTriplet(const Triplet &triplet, U2OpStatus &os) {
QMutexLocker lock(&db->lock);
static const QString queryString("INSERT INTO Triplets(key, role, value) VALUES(?1, ?2, ?3)");
SQLiteQuery q(queryString, db, os);
q.bindString(1, triplet.getKey());
q.bindString(2, triplet.getRole());
q.bindString(3, triplet.getValue());
return q.insert();
}
void U2SQLiteTripleStore::removeTriplet(qint64 tripletId, U2OpStatus &os) {
QMutexLocker lock(&db->lock);
static const QString queryString("DELETE FROM Triplets WHERE id = ?1");
SQLiteQuery q(queryString, db, os);
q.bindInt64(1, tripletId);
q.execute();
}
QList<Triplet> U2SQLiteTripleStore::getTriplets(U2OpStatus &os) const {
QMutexLocker lock(&db->lock);
static const QString queryString("SELECT t.id, t.key, t.role, t.value FROM Triplets t");
SQLiteQuery q(queryString, db, os);
QList<Triplet> result;
while (q.step()) {
Triplet t(q.getString(1), q.getString(2), q.getString(3));
t.id = q.getInt64(0);
result << t;
}
return result;
}
void U2SQLiteTripleStore::removeValue(const Triplet &value, U2OpStatus &os) {
QMutexLocker lock(&db->lock);
static const QString queryString("DELETE FROM Triplets WHERE id = ?1");
SQLiteQuery q(queryString, db, os);
q.bindInt64(1, value.id);
q.execute();
}
} // U2
|
36b511d18dc8a025f6dc666f3c371df065917b2b | 9cc120939594c984e7bb3ded6db559768213e5ab | /source/loader/server/server.cpp | 1a12e296354b18551daa825d0b4d08fbf7cff579 | [] | no_license | Classic1338/sourceengine_cheat_loader | d3ff645a63cfcc0d1f9cca02fd0c410877ad87a5 | 5a6d05e1a8c2e879e775669f13b2b3f531882642 | refs/heads/main | 2023-05-23T22:02:28.133184 | 2021-06-16T00:05:28 | 2021-06-16T00:05:28 | 377,322,752 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,040 | cpp | server.cpp | #include <SFML/Network.hpp>
#include <shared/constants.h>
#include <shared/console.h>
#include <shared/string_utils.h>
#include <Windows.h>
#include "session_manager/session_manager.h"
int main() {
DWORD previous_mode;
GetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ), &previous_mode );
SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ), ENABLE_EXTENDED_FLAGS | ( previous_mode & ~ENABLE_QUICK_EDIT_MODE ) );
sf::TcpListener listener;
if ( listener.listen( NETWORK_PORT ) != sf::Socket::Done ) {
console::log( FMT("failed to listen on port %i \n", NETWORK_PORT) );
}
console::log( "server started successfully \n" );
for ( ;; ) {
std::shared_ptr<session> cur_session = g_session_manager->create_session( );
if ( listener.accept( cur_session->m_socket ) != sf::Socket::Done) {
console::log( "failed to create new client \n" );
}
cur_session->m_ip = cur_session->m_socket.getRemoteAddress( ).getPublicAddress( ).toString( );
if ( !cur_session->start( ) ) {
console::log( "failed to start session \n" );
}
}
} |
c69a89a1c4ce598b20e6120d8558b875fe87b761 | 472ce7bde53239b1ec9300695e73eaed5130c498 | /src/reverseengineering/responses/watchpage.cpp | 35d16cf6ae071fd77d8a43194eac75c82ffa9196 | [] | no_license | PhilInTheGaps/qytlib | e0430adb370ebc9bd4ece0a2d54530950fc06502 | 74a80edaa57306ceb12211df71609b6d7d92fe07 | refs/heads/master | 2021-07-13T15:12:58.929412 | 2020-10-21T14:33:38 | 2020-10-21T14:33:38 | 216,276,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,879 | cpp | watchpage.cpp | #include "qytlib/reverseengineering/responses/watchpage.h"
#include "qytlib/reverseengineering/responses/videoinforesponse.h"
#include "qytlib/utils/regexutils.h"
#include <QNetworkReply>
#include <qgumbodocument.h>
#include <qgumbonode.h>
Q_LOGGING_CATEGORY(ytWatchPage, "yt.responses.watchpage")
using namespace YouTube::Responses;
WatchPage::WatchPage(const QByteArray &raw, QObject *parent)
: QObject(parent)
{
parse(raw);
}
WatchPage *WatchPage::get(QNetworkAccessManager *networkManager, const YouTube::Videos::VideoId &videoId, QObject *parent)
{
qCDebug(ytWatchPage()) << "get(" << videoId << ")";
auto *watchPage = new WatchPage(parent);
auto url = QString("https://youtube.com/watch?v=%1&bpctr=9999999999&hl=en").arg(videoId);
auto *reply = networkManager->get(QNetworkRequest(url));
connect(reply, &QNetworkReply::finished, watchPage, [ = ]() {
if (reply->error() != QNetworkReply::NoError)
{
qCWarning(ytWatchPage()) << reply->error() << reply->errorString();
reply->deleteLater();
return;
}
watchPage->parse(reply->readAll());
reply->deleteLater();
if (!watchPage->isOk())
{
qCWarning(ytWatchPage()) << "Error: Could not parse WatchPage, something went wrong.";
}
});
return watchPage;
}
void WatchPage::parse(const QByteArray &raw)
{
qCDebug(ytWatchPage()) << "parse()";
auto doc = QGumboDocument::parse(raw);
auto root = doc.rootNode();
// Is Ok?
auto player = root.getElementById("player");
m_isOk = player.size() == 1;
if (!m_isOk) qCWarning(ytWatchPage()) << raw;
// Is video available?
auto meta = root.getElementsByTagName(HtmlTag::META);
for (const auto element : meta)
{
if (element.getAttribute("property") == "og:url")
{
m_isVideoAvailable = true;
break;
}
}
// Likes
auto likeLabel = Utils::RegExUtils::match(raw, R"("label"\s*:\s*"([\d,\.]+) likes)", 1);
likeLabel.replace(',', "").replace(QRegularExpression("\\D"), ""); // Strip non digits
m_videoLikeCount = likeLabel.toLong();
// Dislikes
auto dislikeLabel = Utils::RegExUtils::match(raw, R"("label"\s*:\s*"([\d,\.]+) dislikes)", 1);
dislikeLabel.replace(',', "").replace(QRegularExpression("\\D"), ""); // Strip non digits
m_videoDislikeCount = dislikeLabel.toLong();
// PlayerConfig
auto jsonRaw = Utils::RegExUtils::match(raw, R"(ytplayer\.config\s*=\s*(\{.*\}\});)", 1, false);
QJsonParseError error;
auto json = QJsonDocument::fromJson(jsonRaw.toUtf8(), &error);
if (json.isNull())
{
qCWarning(ytWatchPage()) << "Error during parsing of PlayerConfig:" << error.errorString();
}
m_playerConfig = new PlayerConfig(json.object(), this);
emit ready();
}
|
ec74a2e345b6d4ee0f49277585732a07f0574c4b | bc01d89e3b77b9b60afd6f5f8fcad5675b813f8e | /natfw/natfwunsaf_protocols/unsaf_transport/src/cnatfwunsafmsgassembler.cpp | fec4fb34fe985cd38a05e504dff9d50bb16872ec | [] | no_license | SymbianSource/oss.FCL.sf.mw.ipappsrv | fce862742655303fcfa05b9e77788734aa66724e | 65c20a5a6e85f048aa40eb91066941f2f508a4d2 | refs/heads/master | 2021-01-12T15:40:59.380107 | 2010-09-17T05:32:38 | 2010-09-17T05:32:38 | 71,849,396 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,735 | cpp | cnatfwunsafmsgassembler.cpp | /*
* Copyright (c) 2006-2007 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: implementation
*
*/
// INCLUDE FILES
#include "cnatfwunsafmsgassembler.h"
#include "mnatfwunsafmsgassemblerobserver.h"
#include "tnatfwunsafmsgstateinit.h"
#include "tnatfwunsafmsgstateheaderstart.h"
#include "tnatfwunsafmsgstateheaderend.h"
#include "tnatfwunsafmsgstatecomplete.h"
#include "natfwunsafmessagefactory.h"
#include "natfwunsafmessage.h"
const TInt KBufExpandSize = 100;
// -----------------------------------------------------------------------------
// CNATFWUNSAFMsgAssembler::NewL
// -----------------------------------------------------------------------------
//
CNATFWUNSAFMsgAssembler* CNATFWUNSAFMsgAssembler::NewL(
MNATFWUNSAFMsgAssemblerObserver& aObserver )
{
CNATFWUNSAFMsgAssembler* self =
CNATFWUNSAFMsgAssembler::NewLC( aObserver );
CleanupStack::Pop( self );
return self;
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFMsgAssembler::NewLC
// -----------------------------------------------------------------------------
//
CNATFWUNSAFMsgAssembler* CNATFWUNSAFMsgAssembler::NewLC(
MNATFWUNSAFMsgAssemblerObserver& aObserver )
{
CNATFWUNSAFMsgAssembler* self =
new ( ELeave ) CNATFWUNSAFMsgAssembler( aObserver );
CleanupStack::PushL( self );
self->ConstructL();
return self;
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFMsgAssembler::CNATFWUNSAFMsgAssembler
// -----------------------------------------------------------------------------
//
CNATFWUNSAFMsgAssembler::CNATFWUNSAFMsgAssembler(
MNATFWUNSAFMsgAssemblerObserver& aObserver )
: iObserver( aObserver ),
iStates( TNATFWUNSAFMsgStateBase::EMsgMaxStates ),
iStateValue( TNATFWUNSAFMsgStateBase::EMsgInit )
{
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFMsgAssembler::ConstructL
// -----------------------------------------------------------------------------
//
void CNATFWUNSAFMsgAssembler::ConstructL()
{
iMsgFactory = CNATFWUNSAFMessageFactory::NewL();
iMsgBuf = CBufFlat::NewL( KBufExpandSize );
iStates.AppendL( TNATFWUNSAFMsgStateInit( *this ),
sizeof( TNATFWUNSAFMsgStateInit ) );
iStates.AppendL( TNATFWUNSAFMsgStateHeaderStart( *this ),
sizeof( TNATFWUNSAFMsgStateHeaderStart ) );
iStates.AppendL( TNATFWUNSAFMsgStateHeaderEnd( *this ),
sizeof( TNATFWUNSAFMsgStateHeaderEnd ) );
iStates.AppendL( TNATFWUNSAFMsgStateComplete( *this ),
sizeof( TNATFWUNSAFMsgStateComplete ) );
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFMsgAssembler::~CNATFWUNSAFMsgAssembler
// -----------------------------------------------------------------------------
//
CNATFWUNSAFMsgAssembler::~CNATFWUNSAFMsgAssembler()
{
delete iMsgFactory;
delete iMsgBuf;
delete iMessage;
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFMsgAssembler::MsgObserver
// From MNATFWUNSAFMsgAssemblerCtx
// -----------------------------------------------------------------------------
//
MNATFWUNSAFMsgAssemblerObserver& CNATFWUNSAFMsgAssembler::MsgObserver()
{
return iObserver;
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFMsgAssembler::MsgFactory
// From MNATFWUNSAFMsgAssemblerCtx
// -----------------------------------------------------------------------------
//
CNATFWUNSAFMessageFactory& CNATFWUNSAFMsgAssembler::MsgFactory()
{
return *iMsgFactory;
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFMsgAssembler::MsgBuffer
// From MNATFWUNSAFMsgAssemblerCtx
// -----------------------------------------------------------------------------
//
CBufFlat& CNATFWUNSAFMsgAssembler::MsgBuffer()
{
return *iMsgBuf;
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFMsgAssembler::Message
// From MNATFWUNSAFMsgAssemblerCtx
// -----------------------------------------------------------------------------
//
CNATFWUNSAFMessage* CNATFWUNSAFMsgAssembler::Message()
{
return iMessage;
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFMsgAssembler::SetMessage
// From MNATFWUNSAFMsgAssemblerCtx
// -----------------------------------------------------------------------------
//
void CNATFWUNSAFMsgAssembler::SetMessage( CNATFWUNSAFMessage* aMessage )
{
delete iMessage;
iMessage = aMessage;
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFMsgAssembler::DetachMessage
// From MNATFWUNSAFMsgAssemblerCtx
// -----------------------------------------------------------------------------
//
void CNATFWUNSAFMsgAssembler::DetachMessage()
{
iMessage = 0;
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFMsgAssembler::SetMessageLength
// From MNATFWUNSAFMsgAssemblerCtx
// -----------------------------------------------------------------------------
//
void CNATFWUNSAFMsgAssembler::SetMessageLength( TInt aMessageLength )
{
iMessageLength = aMessageLength;
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFMsgAssembler::MessageLength
// From MNATFWUNSAFMsgAssemblerCtx
// -----------------------------------------------------------------------------
//
TInt CNATFWUNSAFMsgAssembler::MessageLength()
{
return iMessageLength;
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFMsgAssembler::ChangeState
// From MNATFWUNSAFMsgAssemblerCtx
// -----------------------------------------------------------------------------
//
void CNATFWUNSAFMsgAssembler::ChangeState(
TNATFWUNSAFMsgStateBase::TNATFWUNSAFMsgStateValue aState )
{
iStateValue = aState;
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFMsgAssembler::CurrentState
// From MNATFWUNSAFMsgAssemblerCtx
// -----------------------------------------------------------------------------
//
TNATFWUNSAFMsgStateBase& CNATFWUNSAFMsgAssembler::CurrentState()
{
_LIT(KPanicCategory, "CNATFWUNSAFMsgAssembler::CurrentState");
__ASSERT_ALWAYS( iStateValue < iStates.Count(),
User::Panic( KPanicCategory, KErrTotalLossOfPrecision ) );
return iStates.At( iStateValue );
}
// -----------------------------------------------------------------------------
// CNATFWUNSAFMsgAssembler::InputL
// -----------------------------------------------------------------------------
//
TBool CNATFWUNSAFMsgAssembler::InputL( HBufC8* aData, TUint& aNextLength )
{
__ASSERT_ALWAYS( aData, User::Leave( KErrArgument ) );
__ASSERT_ALWAYS( aData->Length() != 0, User::Leave( KErrArgument ) );
aNextLength = CNATFWUNSAFMsgAssembler::EDefaultBufferSize;
TPtr8 dataPtr = aData->Des();
TBool retVal = CurrentState().DataReceivedL( dataPtr, aNextLength );
delete aData;
return retVal;
}
// End of File
|
49578e7351fac8c32cf46665d681e9fe50f3d0fa | 6b73c67d58a1f2a18b6bf0d9912b805d1e4032cc | /CAU-Baekjoon-Cpp-/11047(동전 0).cpp | 5a789f7f13ad29bb9ce9b6ffb411b89a46b4815d | [] | no_license | javaBarista/CAU-Baekjoon-Cpp- | 6f7c3fe95effc21c549951c8de7c73416747a48a | 5622e4bc4b2ca3ddaae9241170f1099083ab23c6 | refs/heads/master | 2020-12-15T07:07:18.081040 | 2020-05-05T14:22:43 | 2020-05-05T14:22:43 | 235,026,597 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 413 | cpp | 11047(동전 0).cpp | #include <iostream>
#include <vector>
#pragma warning (disable : 4996)
using namespace std;
int n, k;
bool isclear = false;
static int coin[10];
void init() {
scanf(" %d %d", &n, &k);
for (int i = 0; i < n; i++) scanf(" %d", &coin[i]);
}
int main() {
init();
int count = 0;
for (int i = n - 1; i >= 0; i--) {
if (k >= coin[i]) {
count += (k / coin[i]);
k %= coin[i];
}
}
printf("%d", count);
} |
479384bea5eaf2bb72f18894de61748ba65f3961 | a2466a560bfebbb0540d6f9da99980a612723b81 | /millis_timestamp_events.ino | c76788624ec020f86e6a8ffd1cf6edf8eb098317 | [
"LicenseRef-scancode-public-domain",
"Unlicense"
] | permissive | Koepel/Fun_with_millis | 36ec11d39a781acd9ad7593cb86a6ccb655559be | cde746f7daa91a100b23f78ea9f5eae94c7394fb | refs/heads/master | 2022-04-30T01:09:59.817009 | 2022-03-18T20:49:01 | 2022-03-18T20:49:01 | 167,151,918 | 11 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,049 | ino | millis_timestamp_events.ino | // ---------------------------------------------
// millis_timestamp_events.ino
// ---------------------------------------------
// License: The Unlicense, Public Domain.
// Author: Koepel
// 2019 april 13, Version 1
// 2021 may 23, Version 2
// Added a small delay of 2ms at the end of the loop(),
// because button-bounching could fill the queue
// with a single press on the button.
// ---------------------------------------------
//
// Record events (button presses and button releases)
// and give each event a timestamp with millis.
// Put the data in a queue and use that to delay
// the events before they are send to the output (a led).
//
// A button is connected to pin 2 and GND.
//
// The LED_BUILTIN is the led on the Arduino board,
// any other digital pin can be used.
//
#define NUM_SAMPLES 100
struct EventQueueStruct
{
unsigned long timeStamp; // the timestamp (from millis)
int event; // the event (HIGH or LOW for led)
};
EventQueueStruct myEvents[NUM_SAMPLES];
int indexIn = 0; // index where to put new data
int indexOut = 0; // index where to read data
const unsigned long interval = 2000UL; // delay
const int pinButton = 2; // button to this pin and GND
const int pinLed = LED_BUILTIN; // The digital pin to which a led is connected.
int last_button_state;
void setup()
{
pinMode( pinButton, INPUT_PULLUP);
pinMode( pinLed, OUTPUT);
last_button_state = digitalRead( pinButton);
}
void loop()
{
unsigned long currentMillis = millis();
// --------------------------------------
// Write any button event to the queue.
// --------------------------------------
int buttonState = digitalRead( pinButton);
if( buttonState != last_button_state) // button changed ?
{
// Calculate the new index.
// The queue could be full.
// The data is only stored and the index is only advanced,
// when everything is okay.
int newIndex = indexIn + 1;
if( newIndex >= NUM_SAMPLES)
{
newIndex = 0;
}
if( newIndex != indexOut) // The queue is not full ?
{
// A LOW from the button is a HIGH for the led.
int ledstate = (buttonState == LOW) ? HIGH : LOW;
myEvents[indexIn].timeStamp = currentMillis;
myEvents[indexIn].event = ledstate;
indexIn = newIndex; // set index for next data
}
last_button_state = buttonState; // remember button state to detect a change
}
// --------------------------------------
// Read the queue and process the events.
// --------------------------------------
// The queue is empty when the indexIn is the same
// as the indexOut.
if( indexOut != indexIn) // something in the queue ?
{
if( currentMillis - myEvents[indexOut].timeStamp >= interval)
{
digitalWrite( pinLed, myEvents[indexOut].event);
indexOut++;
if( indexOut >= NUM_SAMPLES)
{
indexOut = 0;
}
}
}
delay( 2); // slow down the sketch to reduce button bounching
}
|
a66f8d5243bb8bcd5dc12c3a5481b38bac3ebbcf | 26e0f1ce7789dd6b5eb9c0971c3438c666f42880 | /87.scramble-string.cpp | ae65e275dc96f7b372738a0e9f1d9ebe016dd275 | [] | no_license | yanmulin/leetcode | 81ee38bb8fbe8ca208bc68683d0ffb96b20f2b68 | 7cc1f650e1ba4d68fb3104aecf3dfbb093ad9c1d | refs/heads/master | 2020-12-05T01:39:32.290473 | 2020-08-19T03:47:23 | 2020-08-19T03:47:23 | 231,969,717 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 882 | cpp | 87.scramble-string.cpp | class Solution {
private:
bool recurse(string s1, string s2) {
if (s1.size() != s2.size()) return false;
if (s1.size() == 0 || s2.size() == 0) return false;
if (s1 == s2) return true;
string ss1 = s1, ss2 = s2;
sort(ss1.begin(), ss1.end());
sort(ss2.begin(), ss2.end());
if (ss1 != ss2) return false;
for (int i=1;i<s1.size();i++) {
if (recurse(s1.substr(0, i), s2.substr(s2.size()-i, i)) &&
recurse(s1.substr(i, s1.size()-i), s2.substr(0, s2.size()-i)))
return true;
if (recurse(s1.substr(0, i), s2.substr(0, i)) &&
recurse(s1.substr(i, s1.size()-i), s2.substr(i, s2.size()-i)))
return true;
}
return false;
}
public:
bool isScramble(string s1, string s2) {
return recurse(s1, s2);
}
};
|
b10a1fa57c84bfcaa5512b8088f45aa98918abed | 0a9465576341cd55480de06914d023569f041b6a | /src/xcroscpp/src/libros/intraprocess_subscriber_link.cpp | d93b67fa651d6a4b18b871b9f2aa947d47c3b840 | [
"Unlicense"
] | permissive | dogchenya/xc-ros | 95751827e13627afdc186d02d3113b8b0d1e0560 | 43c8b773a552ea610bd03750c9c32d7732f8ea69 | refs/heads/main | 2023-06-11T04:05:44.994499 | 2021-06-30T12:22:44 | 2021-06-30T12:22:44 | 331,613,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,912 | cpp | intraprocess_subscriber_link.cpp |
/*
* Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc.
*
* 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 names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/intraprocess_subscriber_link.h"
#include "ros/intraprocess_publisher_link.h"
#include "ros/publication.h"
#include "ros/header.h"
#include "ros/connection.h"
#include "ros/transport/transport.h"
#include "ros/this_node.h"
#include "ros/connection_manager.h"
#include "ros/topic_manager.h"
#include "ros/file_log.h"
#include "ros/assert.h"
#include <boost/bind.hpp>
namespace xcros
{
IntraProcessSubscriberLink::IntraProcessSubscriberLink(const PublicationPtr& parent)
: dropped_(false)
{
ROS_ASSERT(parent);
parent_ = parent;
topic_ = parent->getName();
}
IntraProcessSubscriberLink::~IntraProcessSubscriberLink()
{
}
void IntraProcessSubscriberLink::setSubscriber(const IntraProcessPublisherLinkPtr& subscriber)
{
subscriber_ = subscriber;
connection_id_ = ConnectionManager::Instance()->getNewConnectionID();
destination_caller_id_ = this_node::getName();
}
bool IntraProcessSubscriberLink::isLatching()
{
if (PublicationPtr parent = parent_.lock())
{
return parent->isLatching();
}
return false;
}
void IntraProcessSubscriberLink::enqueueMessage(const SerializedMessage& m, bool ser, bool nocopy)
{
boost::recursive_mutex::scoped_lock lock(drop_mutex_);
if (dropped_)
{
return;
}
ROS_ASSERT(subscriber_);
subscriber_->handleMessage(m, ser, nocopy);
}
std::string IntraProcessSubscriberLink::getTransportType()
{
return std::string("INTRAPROCESS");
}
std::string IntraProcessSubscriberLink::getTransportInfo()
{
// TODO: Check if we can dump more useful information here
return getTransportType();
}
void IntraProcessSubscriberLink::drop()
{
{
boost::recursive_mutex::scoped_lock lock(drop_mutex_);
if (dropped_)
{
return;
}
dropped_ = true;
}
if (subscriber_)
{
subscriber_->drop();
subscriber_.reset();
}
if (PublicationPtr parent = parent_.lock())
{
ROSCPP_LOG_DEBUG("Connection to local subscriber on topic [%s] dropped", topic_.c_str());
parent->removeSubscriberLink(shared_from_this());
}
}
void IntraProcessSubscriberLink::getPublishTypes(bool& ser, bool& nocopy, const std::type_info& ti)
{
boost::recursive_mutex::scoped_lock lock(drop_mutex_);
if (dropped_)
{
return;
}
subscriber_->getPublishTypes(ser, nocopy, ti);
}
} // namespace xcros
|
499bb51446571de0f6bc3edf4fb8acdd0bf65d37 | 9dc2c4a8549a4ab2920eafed17caa1b03d846fa9 | /ProjectWarshipbattle/source/ArtificialIntelligence.h | 9a5537f35c7c1a85028cde460cf7095500e1fd2c | [] | no_license | DingJunyu/WarshipBattleRe | 1d4dcd6ebed0d7e3e12a88d6e3447a5d09246ca6 | 6fd3b17d48f8e45dca18e04c4d802d0d2bba78ed | refs/heads/master | 2020-05-07T22:04:20.520706 | 2019-06-21T01:22:59 | 2019-06-21T01:22:59 | 178,110,286 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,644 | h | ArtificialIntelligence.h | #pragma once
#include"DefinedData.h"
#include"ShipMain.h"
#include"OtherFunctions.h"
#include"AI_Action.h"
#include"Ammo.h"
#include<vector>
#include<list>
/*このクラスにはAIの行動を実現する*/
class ArtificialIntelligence
{
public:
ArtificialIntelligence();
~ArtificialIntelligence();
void SetStatus(ShipMain ship);
void Move(ShipMain me,ShipMain target);//フラグシープ以外はフラグシープを目標にして移動する
void InBattle(ShipMain *me,std::vector<ShipMain> shipList,
int targetNum);
void SetFlagShip() { flagShip = true; }//フラグシープフラグを設置
bool ReferFlagShip() { return flagShip; }
//船状態問い合わせ関数
double ReferRadianNeededNow() { return radianNeededNow; }
double ReferOutPutRateNeededNow() { return outPutRate; }
private:
const double disToFront = 10;
double range;//
double targetDis;//目標との距離
double wayPointDis;//ウェイポイントとの距離
Coordinate2D<double> wayPoint;//ウェイポイント
Coordinate2D<double> myPos;//自分の位置
bool flagShip;//フラグシープフラグ
double nowRadian;//今の角度
double targetRadian;//目標角度
double radianNeededNow;//転回角度
double outPutRate;//速度
void SetTargetPos(Coordinate2D<double> target,double radian);//ウェイポイント設置関数
void SetMyPos(Coordinate2D<double> pos) { myPos = pos; }//自分の位置設置関数
void SetNowRadian(double rad) { nowRadian = rad; }
void CalTargetRadian();
void SetRadianNeeded();
void CalDistance(Coordinate2D<double> coord);
void CalWaypointDis();
void SetSpeed(double outputRate);
};
|
2e3f06861b2351640e245cfe305c96fd5e25417a | f895c7375fa5768f8522edd5da2389c74987fc54 | /NaoCar/Oculus Rift/Sources/MainWindowDelegate.hpp | 9bb637b4b092f9b21455b866088d92878deabc79 | [] | no_license | EdWata/nao-car | 5e0f994645a71e6473d10d42315c667d712f414e | a7b54635bc5b2f37930ee2370719002178d1cce6 | refs/heads/master | 2021-04-14T23:27:13.022569 | 2016-04-23T21:08:21 | 2016-04-23T21:08:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 910 | hpp | MainWindowDelegate.hpp | //
// MainWindowDelegate.hpp
// NaoCar Remote
//
#ifndef _MAIN_WINDOW_DELEGATE_HPP_
# define _MAIN_WINDOW_DELEGATE_HPP_
# include "MainWindow.hpp"
class MainWindowDelegate {
public:
virtual ~MainWindowDelegate(void) {}
virtual void connect(void) = 0;
virtual void hostEntered(std::string host) = 0;
virtual void disconnect(void) = 0;
virtual void viewChanged(int index) = 0;
virtual void carambarAction(void) = 0;
virtual void talk(std::string message) = 0;
virtual void autoDriving(void) = 0;
virtual void safeMode(void) = 0;
virtual void steeringWheelAction(void) = 0;
virtual void funAction(void) = 0;
virtual void frontward(void) = 0;
virtual void backward(void) = 0;
virtual void stop(void) = 0;
virtual void left(void) = 0;
virtual void right(void) = 0;
virtual void front(void) = 0;
virtual void rift(void) = 0;
};
#endif
|
85e899004f4c4cbda6fc0af3b0a42d46022f5180 | 8f50c262f89d3dc4f15f2f67eb76e686b8f808f5 | /InnerDetector/InDetRecTools/TRT_DetElementsRoadTool_xk/TRT_DetElementsRoadTool_xk/TRT_DetElementsRoadData_xk.h | dc461654816bec9777ad1b0925e9b198f0d595fd | [
"Apache-2.0"
] | permissive | strigazi/athena | 2d099e6aab4a94ab8b636ae681736da4e13ac5c9 | 354f92551294f7be678aebcd7b9d67d2c4448176 | refs/heads/master | 2022-12-09T02:05:30.632208 | 2020-09-03T14:03:18 | 2020-09-03T14:03:18 | 292,587,480 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,438 | h | TRT_DetElementsRoadData_xk.h | /*
Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
*/
#include "TrkSurfaces/CylinderBounds.h"
#include "TRT_DetElementsRoadTool_xk/TRT_DetElementsLayerVectors_xk.h"
#ifndef TRT_DetElementsRoadData_xk_H
#define TRT_DetElementsRoadData_xk_H
namespace InDet{
class TRT_DetElementsRoadData_xk{
public:
TRT_DetElementsRoadData_xk()=default;
~TRT_DetElementsRoadData_xk()=default;
inline void setTRTLayerVectors(TRT_DetElementsLayerVectors_xk layers){m_TRTLayerVectors=std::move(layers);}
inline void setBounds(Trk::CylinderBounds cbounds, double rmintrt){m_bounds=cbounds;m_rminTRT=rmintrt;}
inline const TRT_DetElementsLayerVectors_xk* getLayers() const {return &m_TRTLayerVectors;}
inline const Trk::CylinderBounds getBounds() const {return m_bounds;}
inline double getTRTMinR() const {return m_rminTRT;}
private:
TRT_DetElementsLayerVectors_xk m_TRTLayerVectors;
double m_rminTRT{};
Trk::CylinderBounds m_bounds;
};
}
#include "AthenaKernel/CLASS_DEF.h"
CLASS_DEF( InDet::TRT_DetElementsRoadData_xk , 151597572 , 1 )
#include "AthenaKernel/CondCont.h"
CONDCONT_DEF( InDet::TRT_DetElementsRoadData_xk , 991597572 );
#endif
|
3e42ffc6b6678adb18dd77c7ec2a0c5424902557 | c20c4812ac0164c8ec2434e1126c1fdb1a2cc09e | /Source/Source/Tools/SceneEditor/ResourceManager.h | b376525a0ea26f79a5a0a5736896eb6e5478af82 | [
"MIT"
] | permissive | uvbs/FullSource | f8673b02e10c8c749b9b88bf18018a69158e8cb9 | 07601c5f18d243fb478735b7bdcb8955598b9a90 | refs/heads/master | 2020-03-24T03:11:13.148940 | 2018-07-25T18:30:25 | 2018-07-25T18:30:25 | 142,408,505 | 2 | 2 | null | 2018-07-26T07:58:12 | 2018-07-26T07:58:12 | null | GB18030 | C++ | false | false | 10,991 | h | ResourceManager.h | // KResourceManager.h: interface for the KResourceManager class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_KResourceManager_H__9C3F564E_0218_4D56_AF1D_1E90C01E8AD6__INCLUDED_)
#define AFX_KResourceManager_H__9C3F564E_0218_4D56_AF1D_1E90C01E8AD6__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define MAX_PATH_LENGTH 256
#include <string.h>
#include <hash_map>
using namespace std;
using namespace stdext;
struct eqstr
{
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) == 0;
}
};
typedef class KResourceHandle
{
public:
string m_szFileName;
WORD m_nRefCount; // 引用计数
DWORD m_dwLastTimeUsed; // 最近使用时间
KResourceHandle()
{
m_nRefCount = 0;
m_dwLastTimeUsed = 0;
}
virtual ~KResourceHandle()
{
};
void IncRefCount(){ m_nRefCount++; }
void DecRefCount(){ m_nRefCount--; }
void SetRefCount(WORD nRefCount){ m_nRefCount = nRefCount; }
virtual HRESULT LoadFromFile(const char *szFilename,DWORD Option = 0,DWORD Operator=0)//从文件中载入
{
return S_OK;
}
virtual HRESULT Release()//释放
{
return S_OK;
}
virtual HRESULT Cleanup()//清除
{
return S_OK;
}
virtual HRESULT OnLostDevice(void)
{
return S_OK;
}
virtual HRESULT OnResetDevice(void)
{
return S_OK;
}
}* HRESOURCE;
template <class HResourceType>
class KResourceManager
{
public:
typedef hash_map<string, HResourceType >_ResourceHashMap;//定义存储资源的哈西表类型
_ResourceHashMap m_ResourceHashmap;//实际存储资源的哈西表
protected:
virtual HRESULT LoadResource(HResourceType* HResource, const char *szFilename,DWORD Option = 0,DWORD Operator=0)
{
if (!HResource)
{
HResource = new HResourceType;
}
if(SUCCEEDED(HResource->LoadFromFile(szFilename,Option,Operator)))
{
return S_OK;
}
else
{
return E_FAIL;
}
}
public:
virtual HRESULT FindResourceByName(HResourceType** ppHandle,const char *szFilename)
{
_ResourceHashMap :: const_iterator i;
i = m_ResourceHashmap.find(szFilename);
if( i == m_ResourceHashmap.end() )
return E_FAIL;
else
{
(*ppHandle) = (HResourceType*) (&((*i).second));
// 增加引用计数
(*ppHandle)->IncRefCount();
return S_OK;
}
}
HRESULT GetResource(HResourceType** pHResource, const char *szFilename,DWORD Option = 0,DWORD Operator=0)
{
if(FAILED(FindResourceByName(pHResource,szFilename)))
{
HResourceType* HResource = new HResourceType;
if(SUCCEEDED(LoadResource(HResource,szFilename,Option,Operator)))
{
m_ResourceHashmap[szFilename] = *HResource;
_ResourceHashMap :: const_iterator i = m_ResourceHashmap.find(szFilename);
HResourceType* pHandle = (HResourceType*)(&(i->second));
int s = 0;
(*pHResource) = HResource;
}
else
{
SAFE_DELETE(HResource);
(*pHResource) = NULL;
}
}
return S_OK;
}
HRESULT OnLostDevice(void)
{
_ResourceHashMap :: const_iterator i = m_ResourceHashmap.begin();
while (i!=m_ResourceHashmap.end())
{
HResourceType HResource = (*i).second;
HResource.OnLostDevice();
i++;
}
return S_OK;
}
HRESULT OnResetDevice(void)
{
_ResourceHashMap :: const_iterator i = m_ResourceHashmap.begin();
while (i!=m_ResourceHashmap.end())
{
HResourceType HResource = (*i).second;
HResource.OnResetDevice();
i++;
}
return S_OK;
}
KResourceManager()
{
;
}
virtual ~KResourceManager()
{
;
}
};
class KCacheBase
{
public:
DWORD m_dwLastUseTime;
int m_nReference;
KCacheBase()
{
m_dwLastUseTime = 0;
m_nReference = 0;
}
virtual HRESULT Clear()
{
return S_OK;
}
virtual ~KCacheBase()
{
;
}
HRESULT AddRef()
{
m_nReference++;
return S_OK;
}
virtual HRESULT Release()
{
m_nReference--;
if(m_nReference<0)
return E_FAIL;
else
return S_OK;
}
};
template <class TCache>
class KCacheManager
{
public:
DWORD m_dwMaxCacheSize;
vector<TCache*>m_vecCache;
public:
TCache* GetLastUnUsed()
{
if(m_vecCache.size()<m_dwMaxCacheSize)
{
TCache* pNewCatch = new TCache;
m_vecCache.push_back(pNewCatch);
pNewCatch->m_dwLastUseTime = timeGetTime();
return pNewCatch;
}
else
{
DWORD LastTime = 0;
DWORD MaxIndex = 0;
for(DWORD i=0;i<m_vecCache.size();i++)
{
TCache* pCache = m_vecCache[i];
if(i==0)
{
LastTime = pCache->m_dwLastUseTime;
MaxIndex = i;
}
if(LastTime > pCache->m_dwLastUseTime)
{
LastTime = pCache->m_dwLastUseTime;
MaxIndex = i;
}
}
TCache* pCache = m_vecCache[MaxIndex];
pCache->m_dwLastUseTime = timeGetTime();
return pCache;
}
}
TCache* GetUnUsed()
{
for(DWORD i=0;i<m_vecCache.size();i++)
{
TCache* pCache = m_vecCache[i];
if(pCache->m_nReference==0)
{
pCache->m_dwLastUseTime = timeGetTime();
pCache->AddRef();
return pCache;
}
}
if(m_vecCache.size()<m_dwMaxCacheSize)
{
TCache* pNewCatch = new TCache;
m_vecCache.push_back(pNewCatch);
pNewCatch->m_dwLastUseTime = timeGetTime();
pNewCatch->AddRef();
return pNewCatch;
}
else
{
return NULL;
}
}
void SetMaxSize(DWORD Size)
{
m_dwMaxCacheSize = Size;
}
KCacheManager()
{
m_dwMaxCacheSize = 0;
}
virtual ~KCacheManager()
{
for(DWORD i=0;i<m_vecCache.size();i++)
{
TCache* pCache = m_vecCache[i];
SAFE_DELETE(pCache);
}
m_vecCache.clear();
}
virtual HRESULT Clear()
{
for(DWORD i=0;i<m_vecCache.size();i++)
{
TCache* pCache = m_vecCache[i];
pCache->Clear();
}
return S_OK;
}
};
template <class TResource>
class KTResourceManagerBase
{
friend TResource;
protected:
hash_map<string,TResource*>m_hashmapResource;
DWORD m_dwNextID;//下一个分配的ID
DWORD m_dwReleaseQueueSzie;
list<TResource*>m_listReleaseQueue;//需要释放的资源队列
map<DWORD,TResource*>m_mapResource;
public:
virtual HRESULT Get1NewResourcePointer(TResource** ppT,DWORD Type,DWORD Option)
{
(*ppT) = new TResource();
if(!*ppT)
return E_FAIL;
return S_OK;
}
virtual HRESULT Get1NewResource(TResource** ppT,DWORD Type,DWORD Option = 0)
{
if(FAILED(Get1NewResourcePointer(ppT,Type,Option)))
{
return E_FAIL;
}
TResource* pT = (*ppT);
pT->Init(m_dwNextID++);
pT->AddRef();
m_mapResource.insert(map<DWORD,TResource*>::value_type(pT->m_dwID,pT));
m_hashmapResource.insert(hash_map<string,TResource*>::value_type(pT->m_scName,pT));
return S_OK;
}
virtual HRESULT GetTypeByFileName(DWORD* pType,BOOL* pAwaysNew,LPSTR pFileName)
{
(pType) = 0;
(*pAwaysNew) = FALSE;
return S_OK;
}
virtual HRESULT LoadFromFile(TResource** ppT,LPSTR pFileName,DWORD Option = 0)
{
DWORD dwType = 0;
BOOL bAwaysNew = FALSE;
if(FAILED(GetTypeByFileName(&dwType,&bAwaysNew,pFileName)))
return E_FAIL;
if(bAwaysNew)//是否总是创建新资源
{
if(FAILED(Get1NewResourcePointer(ppT,dwType,Option)))
{
return E_FAIL;
}
TResource* pT = (*ppT);
pT->Init(m_dwNextID++);
pT->AddRef();
pT->m_scName = pFileName;
m_mapResource.insert(map<DWORD,TResource*>::value_type(pT->m_dwID,pT));
m_hashmapResource.insert(hash_map<string,TResource*>::value_type(pT->m_scName,pT));
}
else//先搜索以前的资源,相同文件名的
{
hash_map<string,TResource*>::iterator h = m_hashmapResource.find(pFileName);
if(h!=m_hashmapResource.end())//找到了,直接使用
{
(*ppT) = h->second;
(*ppT)->AddRef();
}
else
{
if(FAILED(Get1NewResourcePointer(ppT,dwType,Option)))
{
return E_FAIL;
}
TResource* pT = (*ppT);
pT->Init(m_dwNextID++);
pT->AddRef();
pT->m_scName = pFileName;
m_mapResource.insert(map<DWORD,TResource*>::value_type(pT->m_dwID,pT));
m_hashmapResource.insert(hash_map<string,TResource*>::value_type(pT->m_scName,pT));
}
}
TResource* pT = (*ppT);
return pT->LoadFromFile(pFileName,Option);
}
virtual HRESULT FindResource(TResource** ppT,LPSTR pFileName)
{
hash_map<string,TResource*>::iterator h = m_hashmapResource.find(pFileName);
if(h!=m_hashmapResource.end())//找到了,直接使用
{
(*ppT) = h->second;
(*ppT)->AddRef();
return S_OK;
}
else
{
return E_FAIL;
}
}
virtual HRESULT GetResource(TResource** ppT,DWORD dwID)
{
map<DWORD,TResource*>::iterator i = m_mapResource.find(dwID);
if(i!=m_mapResource.end())
{
(*ppT) = i->second;
return S_OK;
}
return E_FAIL;
}
virtual HRESULT ReleaseResource(DWORD dwID)
{
TResource* lpResource = NULL;
if(SUCCEEDED(GetResource(&lpResource,dwID)))
{
return lpResource->Release();
}
return E_FAIL;
}
virtual HRESULT CleanUp()
{
map<DWORD,TResource*>::iterator m = m_mapResource.begin();
while(m!=m_mapResource.end())
{
TResource* pResource = m->second;
pResource->CleanUp();
SAFE_DELETE(pResource);
m++;
}
m_mapResource.clear();
m_hashmapResource.clear();
m_listReleaseQueue.clear();
return S_OK;
}
KTResourceManagerBase()
{
m_dwReleaseQueueSzie = 20;
m_dwNextID = 1;
}
virtual ~KTResourceManagerBase()
{
;
}
protected:
virtual HRESULT ReleaseResource(TResource* pT,DWORD dwOption = RELEASE_INQUEUE)
{
if(dwOption==RELEASE_INQUEUE)
{
m_listReleaseQueue.push_back(pT);
if(m_listReleaseQueue.size()>m_dwReleaseQueueSzie)
{
list<TResource*>::iterator i = m_listReleaseQueue.begin();
TResource* pResource = *i;
m_listReleaseQueue.pop_front();
map<DWORD,TResource*>::iterator m = m_mapResource.find(pT->m_dwID);
if(m!=m_mapResource.end())
{
m_mapResource.erase(m);
}
hash_map<string,TResource*>::iterator h = m_hashmapResource.find(pT->m_scName);
if(h!=m_hashmapResource.end())
{
m_hashmapResource.erase(h);
}
pResource->CleanUp();
SAFE_DELETE(pResource);
}
}
else
{
pT->CleanUp();
map<DWORD,TResource*>::iterator i = m_mapResource.find(pT->m_dwID);
if(i!=m_mapResource.end())
{
m_mapResource.erase(i);
}
SAFE_DELETE(pT);
}
return S_OK;
}
};
class KResourceBase
{
protected:
int m_nRefrence;//物品使用计数
public:
DWORD m_dwID;//物品ID
string m_scName;
public:
virtual HRESULT LoadFromFile(LPSTR pFileName,DWORD dwOption = 0)
{
return S_OK;
}
virtual HRESULT CleanUp()//释放资源
{
return S_OK;
}
virtual HRESULT AddRef()
{
m_nRefrence++;
return S_OK;
}
virtual HRESULT Release()
{
m_nRefrence--;
if(m_nRefrence<=0)
{
return OnRefrenceZero();
}
return S_OK;
}
virtual HRESULT OnRefrenceZero()//当引用个数降低到0时,默认把自己放到MGR的删除队列里
{
return S_OK;
}
void Init(DWORD dwID)//初始化
{
m_dwID = dwID;
TCHAR Name[256];
wsprintfA(Name,"Resource%d",m_dwID);
m_scName = Name;
}
KResourceBase()
{
m_nRefrence = 0;
}
virtual ~KResourceBase()
{
m_nRefrence = 0;
}
};
#endif // !defined(AFX_KResourceManager_H__9C3F564E_0218_4D56_AF1D_1E90C01E8AD6__INCLUDED_)
|
a8598e4f9cf473f480a8fc881704a76eaef5823f | 69d0deb5921edc82eea0ae184db99b87a0ca6900 | /catkin_ws/src/srrg2_slam_interfaces/srrg2_slam_interfaces/src/srrg2_slam_interfaces/system/map_listener.h | 6d82c08792c97b53feb8516ea72238553c4b75f8 | [
"MIT",
"BSD-3-Clause"
] | permissive | laaners/progetto-labiagi_pick_e_delivery | 8d4006e206cd15b90b7e2291876c2b201e314621 | 3453bfbc1dd7562c78ba06c0f79b069b0a952c0e | refs/heads/main | 2023-08-19T00:17:51.491475 | 2021-09-16T16:35:45 | 2021-09-16T16:35:45 | 409,192,385 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,951 | h | map_listener.h | #pragma once
#include "srrg_messages/message_handlers/message_sink_base.h"
namespace srrg2_solver {
class FactorGraph;
using FactorGraphPtr = std::shared_ptr<FactorGraph>;
} // namespace srrg2_solver
namespace srrg2_slam_interfaces {
template <typename TransformType_>
using Trajectory_ = std::map<double,
TransformType_,
std::less<double>,
Eigen::aligned_allocator<std::pair<double, TransformType_>>>;
using Trajectory2D = Trajectory_<srrg2_core::Isometry2f>;
using Trajectory3D = Trajectory_<srrg2_core::Isometry3f>;
using PropertyTrajectory2D = srrg2_core::Property_<Trajectory2D>;
using PropertyTrajectory3D = srrg2_core::Property_<Trajectory3D>;
class MapListener : public srrg2_core::MessageSinkBase {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
MapListener();
void reset() override;
bool putMessage(srrg2_core::BaseSensorMessagePtr msg_) override;
inline srrg2_solver::FactorGraphPtr graph() {
return _graph;
}
void computeTrajectory(Trajectory2D& trajectory);
void computeTrajectory(Trajectory3D& trajectory);
bool cmdSaveTrajectory(std::string& response,
const std::string& filename);
bool cmdSaveGraph(std::string& response,
const std::string& filename);
protected:
bool handleLocalMapMessage2D(srrg2_core::BaseSensorMessagePtr msg_);
bool handleFactorMessage2D(srrg2_core::BaseSensorMessagePtr msg_);
bool handleNodeUpdateMessage2D(srrg2_core::BaseSensorMessagePtr msg_);
bool handleLocalMapMessage3D(srrg2_core::BaseSensorMessagePtr msg_);
bool handleFactorMessage3D(srrg2_core::BaseSensorMessagePtr msg_);
bool handleNodeUpdateMessage3D(srrg2_core::BaseSensorMessagePtr msg_);
srrg2_solver::FactorGraphPtr _graph = nullptr;
};
} // namespace srrg2_slam_interfaces
|
44d614ddc81c4cd3f9ac1441f16b9caf2880cbda | 88935ce124c354acdb013df9a499067444829ca0 | /solutions/1947.cpp | 9641b279c5a5741199a16e7bc58be60c3813849c | [] | no_license | pascal-the-elf/TIOJ-ASE | 6883e4d0d0a23f02d3f2efe58bf5bd9537952384 | 181ba41b732d52f9c8c728be247961dda3bd4398 | refs/heads/main | 2023-06-04T11:40:20.715491 | 2021-06-27T16:35:40 | 2021-06-27T16:35:40 | 377,033,735 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 982 | cpp | 1947.cpp | #include <cstdio>
#include <vector>
#define pb emplace_back
const int N = 1000025;
inline char readchar() {
constexpr int B = 1<<20;
static char buf[B], *p, *q;
if(p == q && (q=(p=buf)+fread(buf,1,B,stdin)) == buf) return EOF;
return *p++;
}
inline int nextint() {
int x = 0, c = readchar();
while(c < '0') c = readchar();
while(c >= '0') x=x*10+(c^'0'), c=readchar();
return x;
}
int n,sz[N],mx[N],res;
std::vector<int> g[N];
void dfs(int u, int p) {
for(int v: g[u]) {
if(v == p) continue;
dfs(v, u);
sz[u] += sz[v];
if(sz[v] > mx[u]) mx[u] = sz[v];
}
if(n-sz[u] > mx[u]) mx[u] = n-sz[u];
// printf("%d\n", mx[u]);
if(res > mx[u]) res = mx[u];
}
signed main() {
n = res = nextint();
for(int i = 1; i < n; i++) {
int a = nextint(), b = nextint();
g[a].pb(b), g[b].pb(a);
}
for(int i = 0; i < n; i++) sz[i] = 1, mx[i] = 0;
dfs(0,-1);
printf("%d\n", res);
}
|
d57a7b05db399ce1adca4e514515423b25c2a26e | 6dff85b5e9dd68763ae65c5f2bd39ae8a807598f | /KeyCursor/KeyCursor.cpp | 17c5d00a2fcde4b527fba2824ce1d8b77cc05c4c | [] | no_license | winjii/KeyCursor | 292ded667efd987d6a15fdb6055e5d5fbdd30ab2 | d4d12f3aaa9a6b634740c93c4cba7ca00e47657a | refs/heads/master | 2021-05-13T23:10:36.678520 | 2018-01-06T19:55:16 | 2018-01-06T19:55:16 | 116,507,747 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,665 | cpp | KeyCursor.cpp | #include "KeyCursor.h"
namespace KeyCursor {
KeyCursor::KeyCursor(const DevicePos &pos) : _pos(pos), _lastV(0, 0), _leftStickDir(0, 0), _rightStickDir(0, 0) {}
void KeyCursor::update() {
Point l(0, 0), r(0, 0);
if (KeyE.pressed()) l.y--;
if (KeyS.pressed()) l.x--;
if (KeyD.pressed()) l.y++;
if (KeyF.pressed()) l.x++;
if (KeyI.pressed()) r.y--;
if (KeyJ.pressed()) r.x--;
if (KeyK.pressed()) r.y++;
if (KeyL.pressed()) r.x++;
bool validInput = true;
if ((l + r).isZero()) validInput = false;
Vec2 vl(l), vr(r);
double multiplier = 2.0;
if (!l.isZero() && !r.isZero()) multiplier *= 1.5;
if (!vl.isZero()) vl.normalize();
if (!vr.isZero()) vr.normalize();
_leftStickDir = vl;
_rightStickDir = vr;
Vec2 v;
if (validInput) {
Vec2 end = (vl + vr)*multiplier;
Vec2 diff(end - _lastV);
if (diff.length() < 1e-3) v = end;
else v = _lastV + diff.normalized()*std::min(114514.0, diff.length());
_pos += v*multiplier;
_lastV = v;
}
else {
v = _lastV = Vec2(0, 0);
}
Circle(_pos, 5).draw(Palette::Black);
//Line(_pos, _pos + vl*15*multiplier).drawArrow(2, Vec2(5, 5), Palette::Lightblue);
//Line(_pos, _pos + vr*15*multiplier).drawArrow(2, Vec2(5, 5), Palette::Orange);
_locus.drawCatmullRom(1, Palette::Gray);
if (validInput) {
//Line(_pos, _pos + v*15).drawArrow(4, Vec2(10, 10), Palette::Darkgray);
Circle(_pos + v*20, 20).draw(Color(Palette::Red, 15));
}
_locus.push_front(_pos);
while (_locus.size() > 20) _locus.pop_back();
}
Vec2 KeyCursor::leftStickDir() const {
return _leftStickDir;
}
Vec2 KeyCursor::rightStickDir() const {
return _rightStickDir;
}
DevicePos KeyCursor::getPos() const {
return _pos;
}
} |
a0b9e964a43e79cf5c346c41d11ecc0270cc25fe | 2bec5a52ce1fb3266e72f8fbeb5226b025584a16 | /simstudy/inst/testfiles/clipVec/clipVec_DeepState_TestHarness.cpp | 75047abe2dfc62f1decb8b43321dfcd3f50fb425 | [] | no_license | akhikolla/InformationHouse | 4e45b11df18dee47519e917fcf0a869a77661fce | c0daab1e3f2827fd08aa5c31127fadae3f001948 | refs/heads/master | 2023-02-12T19:00:20.752555 | 2020-12-31T20:59:23 | 2020-12-31T20:59:23 | 325,589,503 | 9 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,414 | cpp | clipVec_DeepState_TestHarness.cpp | // AUTOMATICALLY GENERATED BY RCPPDEEPSTATE PLEASE DO NOT EDIT BY HAND, INSTEAD EDIT
// clipVec_DeepState_TestHarness_generation.cpp and clipVec_DeepState_TestHarness_checks.cpp
#include <fstream>
#include <RInside.h>
#include <iostream>
#include <RcppDeepState.h>
#include <qs.h>
#include <DeepState.hpp>
Rcpp::IntegerVector clipVec(IntegerVector id, IntegerVector seq, IntegerVector event);
TEST(simstudy_deepstate_test,clipVec_test){
RInside R;
std::cout << "input starts" << std::endl;
IntegerVector id = RcppDeepState_IntegerVector();
qs::c_qsave(id,"/home/akhila/fuzzer_packages/fuzzedpackages/simstudy/inst/testfiles/clipVec/inputs/id.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "id values: "<< id << std::endl;
IntegerVector seq = RcppDeepState_IntegerVector();
qs::c_qsave(seq,"/home/akhila/fuzzer_packages/fuzzedpackages/simstudy/inst/testfiles/clipVec/inputs/seq.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "seq values: "<< seq << std::endl;
IntegerVector event = RcppDeepState_IntegerVector();
qs::c_qsave(event,"/home/akhila/fuzzer_packages/fuzzedpackages/simstudy/inst/testfiles/clipVec/inputs/event.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "event values: "<< event << std::endl;
std::cout << "input ends" << std::endl;
try{
clipVec(id,seq,event);
}
catch(Rcpp::exception& e){
std::cout<<"Exception Handled"<<std::endl;
}
}
|
1c50dcad346d892c1dec5251d8d7817a040c3232 | 612252bef1d47b5d5bfe2d94e8de0a318db4fc8e | /3.8.1/Voxel_Explorer/Classes/Levels/SewerBossLevel.hpp | 33aa494e319606eef2529d9cbd87124cd3cea872 | [
"MIT"
] | permissive | dingjunyong/MyCocos2dxGame | 78cf0727b85f8d57c7c575e05766c84b9fa726c1 | c8ca9a65cd6f54857fc8f6c445bd6226f2f5409d | refs/heads/master | 2020-06-05T08:32:45.776325 | 2016-10-08T16:09:38 | 2016-10-08T16:09:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,019 | hpp | SewerBossLevel.hpp | //
// SewerBossLevel.hpp
// Voxel_Explorer
//
// Created by wang haibo on 15/12/1.
//
//
#ifndef SewerBossLevel_hpp
#define SewerBossLevel_hpp
#include "StandardLevel.h"
class SewerBossLevel : public StandardLevel
{
public:
SewerBossLevel();
virtual bool build();
virtual bool createTerrain();
virtual void generateAreaStyle();
virtual bool createMonsters();
virtual bool createSummoningMonsters(const cocos2d::Vec2& mapPos);
virtual bool createEliteMonster(int tileIndex);
virtual void createSiegeMonsters(const cocos2d::Vec2& pos);
virtual bool createBoss(const cocos2d::Vec2& pos);
virtual bool createSummoningMonstersBySlimeKing(const cocos2d::Vec2& mapPos, int skillStage);
virtual void clearBossRoom();
virtual bool createPickableItems();
virtual void handleUseStandardPortal(const cocos2d::Vec2& pos);
private:
cocos2d::Vec2 m_BossPosition;
Area* m_pBossExitRoom;
};
#endif /* SewerBossLevel_hpp */
|
fb1baa42d959d3ddbd931efac20bc58b9deb8028 | 7494e2cad705acfeab333690817d024d09e77913 | /imutest.cpp | 320b126fed1774fcee2ebef01b81d831aa3e0543 | [] | no_license | nasa-watchdog/watchdog_integration | b02870bd5e3462e2848df9dc5fdd8d7c543c00df | bedf6e93f5f34f0e4a1db587c9c2eeb28e9acb88 | refs/heads/master | 2020-05-17T05:22:30.515363 | 2019-05-05T02:22:42 | 2019-05-05T02:22:42 | 183,533,268 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 211 | cpp | imutest.cpp | #include "imu.h"
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
imu_acc imu_acc_out;
run_imu(imu_acc_out);
cout<<imu_acc_out.x<<' '<<imu_acc_out.y<<' '<<imu_acc_out.z<<endl;
}
|
3438d85b39697471eefdd1c13a91896f61332067 | 60bd10c54e8499691bbcf25a5acb58541046b67d | /game_server_logic/export/include/reversi/remoting/multiplayer_match.hpp | 463649e3f1b3a60b61f287eef6fae8d3425f4c99 | [] | no_license | andyprowl/reversi | 86af2dfd78779f489fd11cf2ac24620c788e2ec6 | 19e8b8193e3fc2c6adf3c954bf4f21483f52482b | refs/heads/master | 2021-01-02T22:59:00.115805 | 2015-04-20T00:21:39 | 2015-04-20T00:21:39 | 34,134,666 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,290 | hpp | multiplayer_match.hpp | #pragma once
#include "util/signal_traits.hpp"
#include <boost/signals2.hpp>
#include <functional>
#include <memory>
#include <string>
#include <vector>
namespace reversi
{
class game;
class game_logger;
}
namespace reversi { namespace remoting
{
class match_full_exception : public virtual std::exception
{
};
class match_not_started_exception : public virtual std::exception
{
};
class multiplayer_match
{
public:
using match_full_handler = std::function<void(game&)>;
public:
multiplayer_match(std::string name, int board_size, std::unique_ptr<game_logger>&& logger);
~multiplayer_match();
std::string get_name() const;
int get_board_size() const;
void join(std::string player_name);
bool is_full() const;
game& get_game() const;
boost::signals2::connection register_match_full_handler(match_full_handler h);
private:
void add_player(std::string player_name);
void create_game_and_fire_event();
private:
using match_full_event = util::signal_type_t<match_full_handler>;
private:
std::string name;
int board_size;
std::vector<std::string> player_names;
std::unique_ptr<game> played_game;
match_full_event on_match_full;
std::unique_ptr<game_logger> logger;
};
} } |
d57d68230ea7b8f4113ef3f92a4686c045729fbf | a5938b70a2db3763365e57f5adae334c4dd5953c | /TEST_DIR/test_win32Console/test/test.cpp | fe68ab70ac5bb902784345e51acab6c6d61545dc | [] | no_license | jerryhanhuan/test-code-backup | 7dea8a8eb4209dc241dae1864df6b1eb1a48c7bd | 2ebf0b1cb6715f66ea4c0b3153d426652ce9235f | refs/heads/master | 2021-01-22T22:57:25.097424 | 2014-09-17T02:31:47 | 2014-09-17T02:31:47 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,084 | cpp | test.cpp | // test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
//int _tmain(int argc, _TCHAR* argv[])
//{
// return 0;
//}
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;
typedef unsigned char UCHAR;
typedef unsigned short USHORT;
typedef unsigned long ULONG;
#include <WinCon.h>
////c++ 在win32程序中打开控制台 并重定向输出
//
//#ifdef _DEBUG // Release版禁用
////AllocConsole为调用进程分配一个新的控制台。 如果函数成功,则返回值为非零值。如果该函数失败,则返回值为零。会设置GetLastError
//AllocConsole(); //打开控制台窗口以显示调试信息
////SetConsoleTitle设置控制台窗口的标题 GetConsoleTitle函数用于获取当前控制台窗口的标题
//SetConsoleTitleA("Debug Win Output"); //设置标题
//
////GetStdHandle用于从一个特定的标准设备(标准输入、标准输出或标准错误)中取得一个句柄。
//HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE); //获取控制台输出句柄
//
//INT hCrt = _open_osfhandle((INT)hCon, _O_TEXT); //转化为C文件描述符
//FILE * hf = _fdopen( hCrt, "w" ); //转化为C文件流
//setvbuf( hf, NULL, _IONBF, 0); //无缓冲
//*stdout = *hf; //重定向标准输出
//#endif
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
ULONG ulCurrPercent = 0;
printf("\n");
printf("\r当前程序执行进度:%2d%% 这里是空格 \r\n ", ulCurrPercent);
for (ulCurrPercent = 0; ulCurrPercent <= 100; ulCurrPercent++)
{
Sleep(50);
printf("\r进度:%2d%", ulCurrPercent); //\n是另起一行,\r的话回到本行的开头,如果继续输入的话会把先前的覆盖掉
}
printf("\n");
printf("\r当前程序执行进度:%2d%% 这里是空格 \r\n ", ulCurrPercent);
return nRetCode;
}
|
e0172146ca509822bacfa00dfd3ddaf66976b589 | e768f432416693d0c66a776711a27fa078021973 | /Player.h | 071ec9b14e15c51fb052d906af1004a899dc61af | [] | no_license | Shad0wC0der/Bombermaaan-for-Firefox-OS-WSServer | 196f8bafb381559a945322080f8931777d7a75c4 | 19f8dddb89d7c7f40926878d50cbb1e855871aaa | refs/heads/master | 2021-01-01T15:18:16.182485 | 2013-04-08T22:08:26 | 2013-04-08T22:08:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 636 | h | Player.h | /*
* Player.h
*
* Created on: 9 déc. 2012
* Author: robin
*/
#ifndef PLAYER_H_
#define PLAYER_H_
#include <string>
#include <websocketpp/websocketpp.hpp>
class Player {
private:
std::string name;
websocketpp::server::connection_ptr con;
std::string id;
public:
Player(const websocketpp::server::connection_ptr&,const std::string&,const std::string&);
virtual ~Player(){}
std::string getName() const{return this->name;}
void setName(std::string name){this->name=name;}
websocketpp::server::connection_ptr getCon()const{return this->con;}
std::string getID()const{return id;}
};
#endif /* PLAYER_H_ */
|
f1449171a1719effbbde96ec37e693176d15be47 | 9d4f58b64eab23ab1098a987ee5deaa62840cb9d | /Lab3_C.h | 1c0a692f2a94035bccafca139bf200e7ca06cc0c | [] | no_license | Efimenk0/Lab3_C | bfc62703e24e79338ebf10f65eb6acd2ab87b2a0 | c912ecf7572b9be7430d4aa3aa203480479d8ee7 | refs/heads/main | 2023-03-04T14:54:54.489628 | 2021-02-09T20:38:55 | 2021-02-09T20:38:55 | 315,260,747 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,585 | h | Lab3_C.h | #ifndef LAB3_C_H
#define LAB3_C_H
#include <vector>
#include <string>
#include "TernaryVectorClass.h"
namespace Lab3_C {
// Выбор номера альтернативы
int dialog(const std::vector<std::string> msgs);
// Первая инициализация вектора
TernaryVectorClass::TernaryVector Input();
// Переопределить вектор (с помощью перегруженного ">>")
void SetVector(TernaryVectorClass::TernaryVector&, TernaryVectorClass::TernaryVector&);
// Вывод текущего вектора
void GetVector(TernaryVectorClass::TernaryVector&, TernaryVectorClass::TernaryVector&);
// Дизъюнкция данного вектора со вторым вектором
void Disjunction(TernaryVectorClass::TernaryVector&, TernaryVectorClass::TernaryVector&);
// Конъюнкция первого вектора со вторым ветором
void Conjunction(TernaryVectorClass::TernaryVector&, TernaryVectorClass::TernaryVector&);
// Сравнить два вектора между собой
void Comparation(TernaryVectorClass::TernaryVector&, TernaryVectorClass::TernaryVector&);
//Инвертирование вектора (1 меняется на 0, 0 на 1)
void Invertion(TernaryVectorClass::TernaryVector&, TernaryVectorClass::TernaryVector&);
// Анализ определенности вектора
void Analysis(TernaryVectorClass::TernaryVector&, TernaryVectorClass::TernaryVector&);
}
#endif // !LAB3_C_H
|
a99cbfe43b657fd5df3a69f7f258f1aa0901c615 | ccaa04196e2ee3b394198f3981dac9fa51f6c00a | /sources/Rental.cpp | babfec3bbc96ce4a41f5f16192044a47ce126364 | [] | no_license | EricB2A/GEN_LABO5 | 0ac7738253f56898b09196c57d91de5361678c40 | 24c5b790caecd036bc011e13e0388b0e81347e29 | refs/heads/master | 2022-11-05T15:26:38.997004 | 2020-06-21T12:09:29 | 2020-06-21T12:09:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 659 | cpp | Rental.cpp | #include <sstream>
#include "Rental.h"
using std::ostringstream;
Rental::Rental( const Movie& movie, int daysRented )
: _movie( movie )
, _daysRented( daysRented ) {}
int Rental::getDaysRented() const { return _daysRented; }
const Movie& Rental::getMovie() const { return _movie; }
double Rental::calculateAmount(){
return _movie.calculateAmount(_daysRented);
}
int Rental::addFrequentRenterPoints(){
return _movie.addFrequentRenterPoints(_daysRented);
}
std::string Rental::statement() {
std::ostringstream result;
result << "\t" << getMovie().getTitle() << "\t" << calculateAmount() << "\n";
return result.str();
} |
4625e25631564a3d7fda5a0dc216cc7691030b8e | 2dd4e6a5b0398ddf56defd928af6669fb567368b | /FileIO.h | 54148b2bbb56fb2d8284aabbbf00c34dc566f4ba | [
"MIT"
] | permissive | jtpils/non-rigid-recon | 7a71fd8394f2acfeca6368cd0125ebf7d89f2898 | 15b7e22454f2d6f1813f89e09c31c00abe2c5873 | refs/heads/master | 2020-05-14T20:22:53.773379 | 2018-11-13T16:17:33 | 2018-11-13T16:17:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 409 | h | FileIO.h | #pragma once
#include <string>
#include <Eigen/Dense>
#include <vector>
class FileIO
{
public:
FileIO();
~FileIO();
void saveMeshPly(const std::string &outPath);
void saveMatrix(const Eigen::MatrixXd &mat, const std::string &file);
const void SavePintsWithNormals(const std::vector<Eigen::Vector3f>&pt_clouds,
const std::vector<Eigen::Vector3f>&pt_normals, const std::string &path);
};
|
e09cac3287fa337a075a1bfed52d9ffda88a849f | 36d75a92ebacdbfebe87cba633548ef78ad08b5b | /youBot/main.cpp | e8133c8ee9e33cf885b16a48a462a242968779fd | [
"MIT"
] | permissive | XITASO/CAROL | 33bc576139cf33e2b82e436929a84357d73ce0e9 | 0fe36c1835928db15fb36f752ca83f8d2c2e33d4 | refs/heads/main | 2023-07-18T22:09:18.686875 | 2021-09-17T08:20:10 | 2021-09-17T08:20:10 | 346,043,561 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 631 | cpp | main.cpp | #include "main.h"
int main(int argc, char** argv)
{
/*init ros*/
ros::init(argc, argv, "youbot_driver");
ros::NodeHandle nodeHandle;
ros::AsyncSpinner spinner(1);
ros::start();
spinner.start();
MoveItSubscriber moveItSubscriber(nodeHandle);
Manipulator youbot(argv);
youbot.readAllLimits();
//youbot.testGrippers();
while(moveItSubscriber.ready()==false)
{
sleep(5);
}
own_msg::youBotJoints nextMotion;
while(moveItSubscriber.getNextYouBotMotion(nextMotion) == true)
{
youbot.executeMotion(nextMotion);
SLEEP_SEC(2);
}
return 0;
}
|
3c4d1616625df9b806c813ce2160943dfd34a43b | ad106c4b501111cb05236721fa5f4d0bb9a5adc7 | /cmake_project/lib/lifev/lifev/core/array/MatrixElemental.cpp | f1a69b0c401e07a68f309ef9ca9880b700b816d8 | [] | no_license | LucaZampieri/FSI_HiMod | 30dc0f433f61aaed25fa6bcf58e2b67c3c733ec7 | 10a00c01b52a2ddd8a364a25897316ac08b1ae2f | refs/heads/master | 2020-03-24T00:03:56.987253 | 2018-08-02T13:30:09 | 2018-08-02T13:30:09 | 142,271,122 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,906 | cpp | MatrixElemental.cpp | //@HEADER
/*
*******************************************************************************
Copyright (C) 2004, 2005, 2007 EPFL, Politecnico di Milano, INRIA
Copyright (C) 2010 EPFL, Politecnico di Milano, Emory University
This file is part of LifeV.
LifeV is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
LifeV is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with LifeV. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************
*/
//@HEADER
/*!
@file
@brief Matrix for elementary assembly
@contributor Matteo Astorino <matteo.astorino@epfl.ch>
@mantainer Matteo Astorino <matteo.astorino@epfl.ch>
*/
#include <lifev/core/array/MatrixElemental.hpp>
namespace LifeV
{
MatrixElemental::~MatrixElemental()
{
}
MatrixElemental::MatrixElemental ( UInt nNode1, UInt nbr1, UInt nbc1 ) :
_mat ( nNode1* nbr1, nNode1* nbc1 )
{
//
_nBlockRow = nbr1;
_nBlockCol = nbc1;
//
_nRow.resize ( _nBlockRow );
_firstRow.resize ( _nBlockRow );
_nCol.resize ( _nBlockCol );
_firstCol.resize ( _nBlockCol );
//
UInt first = 0;
for ( UInt n = 0; n < nbr1; n++ )
{
_nRow[ n ] = nNode1;
_firstRow[ n ] = first;
first += nNode1;
}
//
first = 0;
for ( UInt n = 0; n < nbc1; n++ )
{
_nCol[ n ] = nNode1;
_firstCol[ n ] = first;
first += nNode1;
}
}
MatrixElemental::MatrixElemental ( UInt nNode1, UInt nbr1, UInt nbc1,
UInt nNode2, UInt nbr2, UInt nbc2 ) :
_mat ( nNode1 * nbr1 + nNode2* nbr2, nNode1 * nbc1 + nNode2* nbc2 )
{
//
_nBlockRow = nbr1 + nbr2;
_nBlockCol = nbc1 + nbc2;
//
_nRow.resize ( _nBlockRow );
_firstRow.resize ( _nBlockRow );
_nCol.resize ( _nBlockCol );
_firstCol.resize ( _nBlockCol );
//
UInt first = 0, n;
for ( n = 0; n < nbr1; n++ )
{
_nRow[ n ] = nNode1;
_firstRow[ n ] = first;
first += nNode1;
}
for ( n = nbr1; n < nbr1 + nbr2; n++ )
{
_nRow[ n ] = nNode2;
_firstRow[ n ] = first;
first += nNode2;
}
//
first = 0;
for ( n = 0; n < nbc1; n++ )
{
_nCol[ n ] = nNode1;
_firstCol[ n ] = first;
first += nNode1;
}
for ( n = nbc1; n < nbc1 + nbc2; n++ )
{
_nCol[ n ] = nNode2;
_firstCol[ n ] = first;
first += nNode2;
}
}
MatrixElemental::MatrixElemental ( UInt nNode1, UInt nbr1, UInt nbc1,
UInt nNode2, UInt nbr2, UInt nbc2,
UInt nNode3, UInt nbr3, UInt nbc3 ) :
_mat ( nNode1 * nbr1 + nNode2 * nbr2 + nNode3* nbr3,
nNode1 * nbc1 + nNode2 * nbc2 + nNode3* nbc3 )
{
//
_nBlockRow = nbr1 + nbr2 + nbr3;
_nBlockCol = nbc1 + nbc2 + nbc3;
//
_nRow.resize ( _nBlockRow );
_firstRow.resize ( _nBlockRow );
_nCol.resize ( _nBlockCol );
_firstCol.resize ( _nBlockCol );
//
UInt first = 0, n;
for ( n = 0; n < nbr1; n++ )
{
_nRow[ n ] = nNode1;
_firstRow[ n ] = first;
first += nNode1;
}
for ( n = nbr1; n < nbr1 + nbr2; n++ )
{
_nRow[ n ] = nNode2;
_firstRow[ n ] = first;
first += nNode2;
}
for ( n = nbr1 + nbr2; n < nbr1 + nbr2 + nbr3; n++ )
{
_nRow[ n ] = nNode3;
_firstRow[ n ] = first;
first += nNode3;
}
//
first = 0;
for ( n = 0; n < nbc1; n++ )
{
_nCol[ n ] = nNode1;
_firstCol[ n ] = first;
first += nNode1;
}
for ( n = nbc1; n < nbc1 + nbc2; n++ )
{
_nCol[ n ] = nNode2;
_firstCol[ n ] = first;
first += nNode2;
}
for ( n = nbc1 + nbc2; n < nbc1 + nbc2 + nbc3; n++ )
{
_nCol[ n ] = nNode3;
_firstCol[ n ] = first;
first += nNode3;
}
}
void MatrixElemental::showMe ( std::ostream& c )
{
UInt i, j;
for ( i = 0; i < _nBlockRow; i++ )
{
for ( j = 0; j < _nBlockCol; j++ )
{
c << "Block (" << i << "," << j << "), ";
c << block ( i, j ) << std::endl;
}
}
}
}
|
ee831794b2b41542768a0e235169aefe2974f068 | 3163a95f941ff160218ea4a481855dad352ead38 | /HomeTask/Ch4/task17.cpp | 6c326fe6b9d097f8f0d82eaad63b2912b339289a | [] | no_license | obserrrver/StephenPrataCplusplus | c998d176e2115e9512348eb7d93a651dad26ae8f | 59b93c4e69578ba1ac1232e87827c6a430e894eb | refs/heads/master | 2022-11-25T10:23:23.795616 | 2020-07-12T10:58:43 | 2020-07-12T10:58:43 | 279,044,839 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 211 | cpp | task17.cpp | #include <vector>
#include <array>
const int numOfStrings = 10;
int main()
{
std::vector<std::string>vectorStringsMassive(numOfStrings);
std::array<std::string, numOfStrings>arrayStringsMassive;
} |
5bce0cdf5a72c49b030a0041189df0b72df31013 | 5b8c79e53cbe90fc1a0f6dbef76059a2694794e6 | /hackerank/RoadsandLibraries.cpp | ac839269a916477def15d8e32c543fc3f61272c7 | [] | no_license | shubham-shinde/competative-and-DS | 7b4cb6e68d45ef2b86a8bf15beca2f497dd6fc9c | fdabed8b58be4a2701a74c76c5ed6b864c57e08b | refs/heads/master | 2023-05-26T09:26:37.768907 | 2023-05-11T05:56:47 | 2023-05-11T05:56:47 | 150,870,524 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,005 | cpp | RoadsandLibraries.cpp | #include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
void showlist(list <int> g)
{
list <int> :: iterator it;
for(it = g.begin(); it != g.end(); ++it)
cout << '\t' << *it;
cout << '\n';
}
void printAdjecencyList(list<int> adj[], int n) {
for(int i=0; i<n; i++) {
cout<<i<<" ";
showlist(adj[i]);
cout<<endl;
}
}
int DFS(list<int> Adj[],int V[],int vertex, int n) {
int sum=1;
V[vertex]=1;
for(auto i=Adj[vertex].begin(); i!=Adj[vertex].end(); i++) {
if(V[*i] != 1) {
sum+=DFS(Adj, V, *i, n);
}
}
return sum;
}
long roadsAndLibraries(int n, int c_lib, int c_road, vector<vector<int>> cities) {
int n_roads = cities.size();
if(c_lib < c_road) {
return (long)c_lib*n;
}
else {
list<int> Adj[n];
// for(int i=0; i<cities.size(); i++) {
// for(int j=0; j<cities[i].size(); j++) {
// cout<<cities[i][j]<<" ";
// }
// cout<<endl;
// }
for(unsigned int i=0; i<cities.size(); i++) {
int edge1 = cities[i][0]-1;
int edge2 = cities[i][1]-1;
Adj[edge1].push_back(edge2);
Adj[edge2].push_back(edge1);
}
// printAdjecencyList(Adj, n);
int V[n] {0};
long cost=0;
for(int i=0; i<n; i++) {
if(V[i] != 1) {
int dfs = DFS(Adj, V, i, n)-1;
cost+=c_road*dfs+c_lib;
// cout<<dfs;
}
}
// cout<<"cost"<<cost;
return cost;
}
}
int main()
{
// ofstream fout(getenv("OUTPUT_PATH"));
int q;
cin >> q;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int q_itr = 0; q_itr < q; q_itr++) {
string nmC_libC_road_temp;
getline(cin, nmC_libC_road_temp);
vector<string> nmC_libC_road = split_string(nmC_libC_road_temp);
int n = stoi(nmC_libC_road[0]);
int m = stoi(nmC_libC_road[1]);
int c_lib = stoi(nmC_libC_road[2]);
int c_road = stoi(nmC_libC_road[3]);
vector<vector<int>> cities(m);
for (int i = 0; i < m; i++) {
cities[i].resize(2);
for (int j = 0; j < 2; j++) {
cin >> cities[i][j];
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
long result = roadsAndLibraries(n, c_lib, c_road, cities);
cout<<result<<endl;
// fout << result << "\n";
}
// fout.close();
return 0;
}
vector<string> split_string(string input_string) {
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}
/*
wldsfubcsxrryqpqyqqxrlffumtuwymbybnpemdiwyqz
990
31 38
29 33
13 34
4 17
15 26
2 10
10 33
15 25
18 42
23 39
17 21
28 41
29 30
1 9
30 34
17 35
2 30
11 18
27 28
8 32
18 31
26 34
5 23
13 19
39 39
13 27
26 43
23 25
32 40
14 15
27 38
7 15
18 19
5 25
10 25
8 26
4 31
28 42
26 39
15 41
2 16
1 29
4 22
20 40
5 36
22 28
18 35
12 23
24 43
9 31
12 20
3 41
6 42
42 42
4 13
4 14
15 40
31 40
9 22
10 10
1 22
11 15
30 37
21 40
16 25
29 32
12 32
11 22
16 27
25 29
37 43
23 38
20 22
41 42
21 37
13 28
13 36
6 26
8 28
24 26
25 30
2 26
13 26
10 23
11 41
1 8
15 23
23 35
5 16
1 14
26 40
28 34
27 40
9 40
22 37
14 22
27 44
25 40
32 35
23 41
40 41
6 39
12 44
15 36
14 33
10 44
7 26
36 36
34 37
14 34
3 15
30 31
11 24
7 25
26 38
4 6
11 43
35 43
19 19
2 35
18 18
11 28
6 44
1 20
43 44
10 14
21 29
32 33
33 37
29 40
4 5
3 19
21 30
34 38
3 17
2 19
10 30
8 21
16 43
23 27
18 41
10 42
13 20
11 23
10 18
1 44
3 38
7 35
3 11
20 37
14 37
4 34
7 27
9 11
7 19
5 5
8 14
8 10
6 29
2 40
19 21
4 38
16 28
12 37
31 42
25 34
20 35
4 20
33 39
11 16
10 29
30 43
15 42
1 7
7 21
27 34
38 40
12 28
5 14
38 38
9 44
4 21
27 27
22 27
38 43
8 11
14 21
39 40
4 44
31 36
1 6
11 42
4 16
13 42
5 18
9 38
27 42
17 28
14 40
17 34
14 32
17 43
1 10
27 31
23 29
14 25
17 24
9 17
26 37
2 12
29 41
7 23
23 42
1 43
2 31
18 34
38 39
23 31
5 11
7 9
1 27
6 10
3 18
1 19
33 34
5 17
17 32
3 30
9 20
8 13
37 38
19 34
6 27
20 33
3 33
7 29
3 13
17 41
6 9
5 35
19 42
3 21
35 37
20 20
26 36
2 13
17 30
8 15
38 41
10 35
15 22
7 31
12 21
30 35
4 26
39 42
17 22
18 38
32 44
18 23
28 28
17 39
33 35
9 12
26 42
35 39
25 39
1 2
19 26
27 36
8 35
15 19
17 27
25 33
3 3
26 44
5 30
13 21
31 39
4 18
1 24
2 14
24 36
18 37
6 13
19 41
30 42
10 38
34 40
22 41
21 28
37 39
35 38
19 27
2 37
2 27
2 38
10 20
1 4
8 36
7 7
42 44
6 6
6 31
24 27
10 31
17 33
13 24
28 40
17 38
5 29
20 23
3 26
30 33
20 36
28 37
18 21
12 38
22 25
4 11
17 31
32 36
24 40
41 41
10 19
1 39
22 35
6 37
10 34
12 18
1 26
14 39
6 12
7 12
5 19
21 31
5 33
3 9
22 22
9 14
6 7
40 42
1 12
10 15
26 29
6 22
2 29
24 29
6 28
29 35
5 10
32 43
4 35
19 23
21 27
3 31
14 27
5 38
6 15
17 40
21 39
16 22
16 39
31 37
1 28
22 24
13 44
11 36
1 35
40 44
24 30
25 31
2 34
11 27
14 20
28 35
20 43
30 41
16 23
2 43
7 38
11 12
10 13
9 16
7 20
15 29
30 39
36 41
12 12
37 42
5 41
2 24
32 37
14 44
4 24
20 21
36 37
6 35
40 43
43 43
8 8
28 32
1 15
30 30
8 12
16 16
8 24
22 40
13 14
20 38
14 14
3 44
5 9
23 28
24 41
12 14
23 44
19 39
8 29
11 20
15 21
19 32
8 38
13 38
16 19
29 39
10 28
6 19
15 30
32 32
8 19
9 9
11 25
24 35
13 15
31 31
4 27
17 44
25 26
36 44
21 21
13 22
29 34
24 25
13 25
9 35
9 41
3 40
1 40
40 40
14 30
35 44
9 33
14 23
3 20
6 25
10 12
11 21
31 44
14 35
9 15
14 26
25 36
26 27
35 40
23 33
11 31
2 8
14 43
1 41
5 20
10 27
8 18
3 12
17 37
22 32
27 35
26 32
17 26
35 42
14 41
19 28
24 44
34 42
11 14
7 41
44 44
12 19
9 32
4 25
3 29
6 43
15 15
9 30
4 42
18 43
6 17
41 43
22 34
30 32
10 24
8 43
7 10
7 30
25 25
7 11
11 13
20 32
5 37
4 8
20 34
18 44
38 44
22 30
3 8
21 23
2 20
6 38
9 34
3 37
8 27
6 24
11 29
9 43
15 37
9 13
12 43
15 20
24 42
1 21
4 43
12 35
9 28
17 19
1 30
9 42
33 36
27 32
8 17
12 33
2 33
11 37
18 33
5 12
9 26
7 37
24 32
2 18
30 40
12 41
22 23
39 41
21 34
9 37
1 1
9 39
8 33
24 38
23 23
14 29
22 33
13 33
31 32
3 22
8 22
2 17
19 31
1 13
2 3
5 13
28 31
16 24
2 21
15 33
7 36
6 21
15 38
19 29
4 15
6 16
3 32
37 41
7 16
5 22
11 34
20 27
33 33
2 36
18 29
5 34
12 26
36 40
20 26
13 30
14 36
13 35
18 25
8 31
17 25
5 28
2 7
3 4
9 24
15 32
3 34
8 9
18 36
26 33
7 22
21 26
6 14
5 42
3 24
21 32
10 32
5 21
21 43
11 39
27 37
19 35
2 44
29 43
16 34
11 26
37 37
26 31
20 28
11 40
4 29
37 40
9 29
28 30
13 31
2 42
6 30
29 36
19 24
1 37
2 6
38 42
39 44
22 38
23 24
35 35
25 41
29 44
19 40
12 22
6 20
25 37
1 34
16 18
2 9
7 42
23 37
2 4
10 41
15 28
31 34
11 17
6 41
19 44
33 41
4 33
19 30
9 23
7 18
21 24
24 37
18 24
7 33
20 44
10 21
10 36
12 25
12 36
14 24
31 43
34 41
15 44
4 30
6 36
17 17
2 39
17 36
33 44
20 29
16 20
20 31
25 32
7 28
16 35
1 33
2 23
42 43
13 18
34 44
15 16
16 44
18 32
10 39
28 44
25 27
9 25
1 3
3 25
32 42
22 39
16 37
7 34
31 33
31 35
16 26
16 32
3 6
25 38
21 25
6 34
24 28
27 29
17 42
5 39
20 25
28 38
6 23
11 11
34 35
2 22
10 22
2 28
20 30
2 11
16 31
4 36
24 39
12 34
14 16
13 39
4 7
20 39
8 30
13 29
17 18
25 43
8 37
12 27
3 35
23 34
21 42
4 32
12 39
16 33
9 18
14 17
14 28
13 32
32 38
6 8
11 38
18 22
3 28
19 20
9 19
4 37
16 29
41 44
5 31
8 44
2 15
13 23
7 24
10 43
9 36
27 33
8 41
28 29
13 17
9 21
4 4
5 44
21 33
25 44
12 16
5 40
8 39
1 23
4 40
6 33
1 38
3 23
6 11
36 42
11 30
15 43
12 17
2 25
12 42
7 8
17 23
16 38
13 43
16 40
23 43
16 42
5 8
10 11
21 36
1 18
12 30
8 23
3 27
19 38
4 23
25 42
11 44
13 37
6 18
15 35
5 6
4 41
13 13
34 36
3 42
16 41
16 17
20 42
12 29
20 41
11 19
13 16
27 30
1 11
24 33
26 28
8 42
24 34
9 27
7 17
5 7
18 30
30 38
8 16
15 24
37 44
33 42
4 39
3 43
15 39
26 41
33 38
14 19
2 2
33 43
17 20
19 43
5 24
1 32
28 43
26 35
7 39
39 43
29 31
4 9
24 31
12 13
7 13
29 29
22 29
21 44
36 43
15 17
1 36
12 40
2 41
14 31
18 20
22 31
18 39
12 15
14 38
29 42
31 41
8 34
26 30
10 26
14 18
14 42
18 40
13 40
3 5
8 20
21 22
28 39
18 28
3 36
6 40
3 14
19 36
12 31
10 37
7 32
32 39
34 39
16 30
17 29
3 10
18 26
15 31
27 39
15 27
33 40
3 16
25 35
23 32
23 26
10 40
36 39
24 24
22 44
10 16
13 41
1 31
22 26
22 42
9 10
8 25
4 12
26 26
32 41
29 37
1 25
21 38
1 5
11 32
27 43
10 17
34 43
11 35
15 34
7 44
7 40
7 14
23 30
1 42
3 39
4 19
4 28
28 33
29 38
4 10
8 40
27 41
20 24
2 5
5 26
1 16
36 38
19 33
35 36
22 36
15 18
35 41
19 25
5 15
32 34
21 41
34 34
2 32
5 27
5 43
28 36
18 27
23 36
5 32
1 17
16 21
6 32
25 28
12 24
19 22
19 37
11 33
23 40
22 43
30 44
7 43
16 36
3 7
30 36
21 35
*/ |
0b94310a2684958480031eff0827cd56419e66a4 | b574f6719749d1b55d5af70a591bcef325bbdd8d | /src/Pilha.hpp | e76a7312cee92f63c16681226bf9cb4a3092cf4b | [] | no_license | williamthewill/trabalhoPilha | b0574267dca70a37d561f1525f607e6d637830d9 | b98bf511e36dddb3c6822cea353cf08316943196 | refs/heads/master | 2021-01-10T02:19:11.999625 | 2016-04-04T15:08:19 | 2016-04-04T15:08:19 | 55,407,202 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,921 | hpp | Pilha.hpp | // Copyright [2016] <William Müller>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template<typename T> class Pilha {
private:
/*
* declaração e atribuição da capaciadade maxima da pilha
* */
int capacidade = 0;
/*
* declaração do ponteiro
* */
int ponteiro = -1;
T * pilha;
public:
// Construtor vazio
Pilha() {
}
// construtor setando capacidade do vetor
Pilha<T>(int capacidade) {
this-> capacidade = capacidade;
pilha = new T[capacidade];
}
/*
* retorna capacidade da pilha
* */
int getCapaciadade() {
return capacidade;
}
/*
* função extra que exibe textualmente o tamanho da pilha
* */
void tamanhoPilha() {
cout << "O tamanho da pilha é de " << getCapaciadade() << endl;
}
/*
* Verifica se pilha atingiu sua capaciadade maxima
* */
bool PilhaCheia() {
bool returner = false;
if (ponteiro == (capacidade - 1))
returner = true;
return returner;
}
/*
* Verifica se a pilha está vazia
* */
bool PilhaVazia() {
bool returner = false;
if (ponteiro == -1)
returner = true;
return returner;
}
/*
* Adiciona elemento ao topo da pilha
* */
void empilha(T dado) {
if (PilhaCheia()) {
throw "pilha cheia !!";
}
pilha[++ponteiro] = dado;
}
/*
* Remove elemento do topo da pilha
* */
T desempilha() {
if (PilhaVazia()) {
throw "A pilha está vazia";
}
--ponteiro;
return pilha[ponteiro+1];
}
/*
* retorna o elemento contido no topo da pilha
* */
T topo() {
if (PilhaVazia()) {
throw "A pilha está vazia";
}
return pilha[ponteiro];
}
/*
* retorna a posição do ultimo elemento da pilha
* */
int getPosTopo() {
if (PilhaVazia()) {
throw "A pilha está vazia";
}
return ponteiro;
}
/*
* Desloca o topo da pilha para -1
* */
void limparPilha() {
if (PilhaVazia()) {
throw "A pilha está vazia";
}
ponteiro = -1;
}
};
|
2652ce777d924296638a770b9fbd6228ac6e27a0 | 2c6221df607e3e41571e552ce6966acd5e8accab | /Epoll.cpp | 3195b3e872464da6a99f8152abb2f4248a9d2309 | [] | no_license | Charlyhash/GakkiNet | 1a66adaa5ea82116c001943c9f5faa433fbf17ed | 2d1c8ac4cb4c65875223a88627da8075129f92f7 | refs/heads/master | 2021-07-02T21:48:20.950842 | 2017-09-25T01:04:00 | 2017-09-25T01:04:00 | 104,687,870 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,449 | cpp | Epoll.cpp | #include "Epoll.h"
#include "GakkiLog.h"
#include <string.h>
#include <unistd.h>
#include <sys/epoll.h>
using namespace GakkiNet;
Epoll::Epoll() : epollFd(epoll_create1(EPOLL_CLOEXEC))
{
if (epollFd < 0)
LOG(ERROR) << "epll_create1 error";
}
Epoll::~Epoll()
{
::close(epollFd);
}
bool Epoll::addEvent(Event* event)
{
if (epollCtrl(EPOLL_CTL_ADD, event->getFd(), event->getEvents()) < 0)
{
LOG(ERROR) << "add epoll";
return false;
}
return true;
}
bool Epoll::removeEvent(Event* event)
{
if (epollCtrl(EPOLL_CTL_DEL, event->getFd(), event->getEvents()) < 0)
{
LOG(ERROR) << "delete epoll";
return false;
}
return true;
}
bool Epoll::modifyEvent(Event* event)
{
if (epollCtrl(EPOLL_CTL_MOD, event->getFd(), event->getEvents()) < 0)
{
LOG(ERROR) << "modify epoll";
return false;
}
return true;
}
bool Epoll::removeEvent(int fd)
{
if (epollCtrl(EPOLL_CTL_DEL, fd, 0) < 0)
{
LOG(ERROR) << "delete epoll";
return false;
}
return true;
}
int Epoll::waitEvent(struct epoll_event* eventList, int eventSize, int timeMs)
{
int rst = epoll_wait(epollFd, eventList, eventSize, timeMs);
return rst;
}
int Epoll::epollCtrl(int op, int fd, int events)
{
struct epoll_event event;
bzero(&event, sizeof(event));
event.events = events;
event.data.fd = fd;
//修改会反映在events上
int rst = epoll_ctl(epollFd, op, fd, &event);
return rst;
} |
c2c874df63f784a30e30799001aea44628efe0ed | ae956ea7df63b4fcca6af2d65c3902f986b7b08a | /BallSpawner.cpp | 0c0964e6806233c4b28eb87305cd076d076bb8f4 | [] | no_license | Chillex/phs-engine | 92a6fcddec158bfc43c10dc95c60164fd1903cbc | 9ba6c97a596a9b4e4d3143eafaef7194916e2595 | refs/heads/master | 2020-06-20T03:16:59.672721 | 2017-06-26T20:13:24 | 2017-06-26T20:13:24 | 94,192,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,894 | cpp | BallSpawner.cpp | #include "BallSpawner.h"
#include <SFML/Graphics.hpp>
#include "Simulation.h"
#include "Particle.h"
#include "ParticleForceRegistry.h"
#include "ParticleGravity.h"
#include "FanForce.h"
BallSpawner::BallSpawner(ParticleForceRegistry* forceRegistry)
: BallSpawner(glm::vec2(0.0f), 1.0f, forceRegistry)
{
}
BallSpawner::BallSpawner(glm::vec2 center, float width, ParticleForceRegistry* forceRegistry)
: m_center(center)
, m_width(width)
, m_forceRegistry(forceRegistry)
{
}
BallSpawner::~BallSpawner()
{
for (size_t i = 0; i < m_particles.size(); ++i)
{
delete m_particles[i];
}
}
void BallSpawner::Update(float duration)
{
// update all particles
for (Particles::iterator it = m_particles.begin(); it != m_particles.end(); ++it)
{
(*it)->Integrate(duration);
}
}
void BallSpawner::Render(sf::RenderWindow& window)
{
sf::CircleShape particle;
particle.setFillColor(sf::Color::Green);
particle.setOutlineThickness(0.0f);
sf::CircleShape circleShape;
circleShape.setFillColor(sf::Color::Transparent);
circleShape.setOutlineColor(sf::Color::Red);
circleShape.setOutlineThickness(-4.0f);
// render all particles
for (Particles::iterator it = m_particles.begin(); it != m_particles.end(); ++it)
{
glm::vec2 pos = (*it)->position;
particle.setPosition(pos.x, pos.y);
particle.setRadius((*it)->radius);
particle.setOrigin((*it)->radius, (*it)->radius);
window.draw(particle);
bool debugDraw = false;
if(debugDraw)
{
// CircleBound
circleShape.setPosition((*it)->circleBound.center.x, (*it)->circleBound.center.y);
circleShape.setRadius((*it)->circleBound.radius);
circleShape.setOrigin((*it)->circleBound.radius, (*it)->circleBound.radius);
window.draw(circleShape);
}
}
}
void BallSpawner::Reset()
{
for (size_t i = 0; i < m_particles.size(); ++i)
{
m_forceRegistry->Remove(m_particles[i], Simulation::ParticleGravityGenerator);
m_forceRegistry->Remove(m_particles[i], Simulation::FanForceGenerator);
delete m_particles[i];
}
m_particles.clear();
}
std::vector<Particle*> BallSpawner::GetParticles() const
{
return m_particles;
}
void BallSpawner::CreateParticles(int amount)
{
for (int i = 0; i < amount; ++i)
{
CreateParticle();
}
}
void BallSpawner::CreateParticle()
{
int min = -m_width;
int max = m_width;
int randWidth = rand() % (max - min + 1) + min;
min = 0;
max = 200.0f;
int randHeight = rand() % (max - min + 1) + min;
glm::vec2 velocity(0.0f);
glm::vec2 acceleration(0.0f);
float dampening = 0.9f;
float mass = 1.0f;
float lifetime = Particle::INFINITE_LIFETIME;
float size = 20.0f;
float bounciness = 0.75f;
Particle* particle = new Particle(glm::vec2(m_center.x + randWidth, m_center.y - randHeight), velocity, acceleration, dampening, mass, lifetime, size, bounciness);
m_particles.push_back(particle);
m_forceRegistry->Add(particle, Simulation::ParticleGravityGenerator);
}
|
c6177a7496a98fa613dabef13d036dd1d186a800 | 6cc0bc68c17538666e0258caae959d44c936970d | /spatial-hash.cpp | ff0d2597693621feb98dbc76de0ece4fbd05fb71 | [] | no_license | JDonner/gabbleduck | a02ebb0ebb11e86fd0cf2608d2e1e17bd9126f9a | a818a198bdaaa761067470dca25e47094a871a5b | refs/heads/master | 2018-12-28T11:57:16.650439 | 2010-07-07T15:58:09 | 2010-07-07T15:58:09 | 38,141 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,002 | cpp | spatial-hash.cpp | #include "spatial-hash.h"
#include "instrument.h"
#include <math.h>
#include <assert.h>
SpatialHash::SpatialHash()
{
for (unsigned i = 0; i < Dimension; ++i) {
total_grid_phys_extent_[i] = 0;
cell_phys_extent_[i] = 0;
n_cells_[i] = 0;
}
stride_0_ = 0;
stride_1_ = 0;
}
void SpatialHash::init(ImageType::PointType origin,
double grid_phys_separation,
unsigned (&n_pixels)[Dimension],
double (&phys_separation)[Dimension])
{
image_origin_ = origin;
for (unsigned i = 0; i < Dimension; ++i) {
this->cell_phys_extent_[i] = grid_phys_separation;
this->n_cells_[i] = ::ceil((n_pixels[i] * phys_separation[i]) / this->cell_phys_extent_[i]);
this->total_grid_phys_extent_[i] = this->n_cells_[i] * this->cell_phys_extent_[i];
}
this->stride_1_ = this->n_cells_[2];
this->stride_0_ = this->stride_1_ * this->n_cells_[1];
assert(this->cells_.empty());
unsigned final_size = this->n_cells_[0] * this->n_cells_[1] * this->n_cells_[2];
assert(this->cells_.capacity() < final_size);
this->cells_.resize(final_size, 0);
}
void SpatialHash::addPt(PointType const& physPt)
{
Pts* pts = this->pts_at(physPt);
pts->push_back(physPt);
++n_total_hashed_pts;
}
// The strategy here is, though this is n^2, it's a very small n, just
// finely-spaced adjacent cells.
bool SpatialHash::isWithinDistanceOfAnything(PointType const& physPt,
double distance) const
{
// (save taking a lot of square roots)
double d2 = distance * distance;
Index idx = index_of(physPt);
Cells nbrs;
get_neighbors(idx, nbrs);
// 27 <= we include the center cell itself, too.
assert(nbrs.size() <= 27);
for (Cells::const_iterator itCells = nbrs.begin(), endCells = nbrs.end();
itCells != endCells; ++itCells) {
Pts const* pts = *itCells;
if (pts) {
for (Pts::const_iterator itPts = pts->begin(), endPts = pts->end();
itPts != endPts; ++itPts) {
if (itPts->SquaredEuclideanDistanceTo<double>(physPt) < d2) {
return true;
}
}
}
}
return false;
}
SpatialHash::Index SpatialHash::index_of(PointType const& physPt) const
{
Index idx;
PointType zeroed = zero_offset_based(physPt);
for (unsigned i = 0; i < Dimension; ++i) {
idx[i] = unsigned(zeroed[i] / this->cell_phys_extent_[i]);
}
#if WANT_GRID_BOUNDS_CHECKING
assert(0 <= idx[0] and idx[0] < (int)this->n_cells_[0]);
assert(0 <= idx[1] and idx[1] < (int)this->n_cells_[1]);
assert(0 <= idx[2] and idx[2] < (int)this->n_cells_[2]);
#endif
return idx;
}
unsigned SpatialHash::offset_of(Index const& idx) const
{
#if WANT_GRID_BOUNDS_CHECKING
assert(0 <= idx[0] and idx[0] < (int)this->n_cells_[0]);
assert(0 <= idx[1] and idx[1] < (int)this->n_cells_[1]);
assert(0 <= idx[2] and idx[2] < (int)this->n_cells_[2]);
#endif
unsigned offset =
idx[0] * this->stride_0_ +
idx[1] * this->stride_1_ +
idx[2];
return offset;
}
SpatialHash::Pts* SpatialHash::pts_at(PointType const& physPt)
{
return pts_at(index_of(physPt));
}
SpatialHash::Pts* SpatialHash::pts_at(int offset)
{
#if WANT_GRID_BOUNDS_CHECKING
assert(0 <= offset and offset < (int)this->cells_.size());
#endif
Pts* cell = this->cells_[offset];
if (not cell) {
cell = new Pts;
this->cells_[offset] = cell;
}
return cell;
}
SpatialHash::Pts* SpatialHash::pts_at(Index idx)
{
return pts_at(offset_of(idx));
}
void SpatialHash::get_neighbors(Index ctr, Cells& neighbors) const
{
Index idx;
for (int k = -1; k <= 1; ++k) {
idx[0] = ctr[0] + k;
for (int j = -1; j <= 1; ++j) {
idx[1] = ctr[1] + j;
for (int i = -1; i <= 1; ++i) {
idx[2] = ctr[2] + i;
Pts* cell = this->cells_[offset_of(idx)];
neighbors.push_back(cell);
}
}
}
}
|
ccabcb9b212ddade4173a881d2f9843e587860ae | 157fd7fe5e541c8ef7559b212078eb7a6dbf51c6 | /TRiAS/Framework/TRiAS Framework/_CLIPBRD.CXX | 0a80419f171047aed31de1ab351a7902b26625e9 | [] | no_license | 15831944/TRiAS | d2bab6fd129a86fc2f06f2103d8bcd08237c49af | 840946b85dcefb34efc219446240e21f51d2c60d | refs/heads/master | 2020-09-05T05:56:39.624150 | 2012-11-11T02:24:49 | 2012-11-11T02:24:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 889 | cxx | _CLIPBRD.CXX |
#include "tfrmpre.hxx"
#include "clipdef.h"
#include "clip_im.hxx"
#include "Clipbrd.hxx"
#if !defined(WIN32)
#define _DLLENTRY __export
#endif
_DLLENTRY CClipboard :: CClipboard (void)
{
cb_imp = new CClipBoard_Imp();
}
_DLLENTRY CClipboard :: ~CClipboard (void)
{
delete cb_imp;
}
void _DLLENTRY CClipboard :: Clear (void)
{
cb_imp->Clear();
}
long _DLLENTRY CClipboard :: GetItemSize (Format fmt)
{
return cb_imp-> GetItemSize(fmt);
}
void _DLLENTRY CClipboard :: Insert (const char *txt)
{
cb_imp->Insert(txt);
}
void _DLLENTRY CClipboard :: Insert (const pBitmap bitmap)
{
cb_imp->Insert(bitmap);
}
BOOL _DLLENTRY CClipboard ::Retrieve (char * txt, int len)
{
return cb_imp->Retrieve (txt, len);
}
BOOL _DLLENTRY CClipboard :: Retrieve (pBitmap bitmap)
{
return cb_imp->Retrieve (bitmap);
}
|
31e6f9cbe8847ca6e0e2505546ae4c906bb82e5a | 0f0b8690fdaebaca92d06de4565a36a0b6e4c57b | /src/ColEm/Coleco.cpp | a7af02e1dab9b37d4ca9e290bc3cdd430470c4e5 | [] | no_license | tredpath/ColEm-pb | 1c4b15906dfe7863f9b63cc621a678719d4a45b6 | ce525f53f31cb07262306ea99a4aaf41af80f538 | refs/heads/master | 2016-09-05T11:13:21.164171 | 2012-08-01T19:58:53 | 2012-08-01T19:58:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,071 | cpp | Coleco.cpp | /** ColEm: portable Coleco emulator **************************/
/** **/
/** Coleco.c **/
/** **/
/** This file contains implementation for the Coleco **/
/** specific hardware. Initialization code is also here. **/
/** **/
/** Copyright (C) Marat Fayzullin 1994-2010 **/
/** You are not allowed to distribute this software **/
/** commercially. Please, notify me, if you make any **/
/** changes to this file. **/
/*************************************************************/
#include "Coleco.h"
#include "../EMULib/Sound.h"
#include "../EMULib/EMULib.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#ifdef __WATCOMC__
#include <direct.h>
#endif
#ifdef ZLIB
#include <zlib.h>
#endif
byte Verbose = 1; /* Debug msgs ON/OFF */
byte UPeriod = 75; /* Percentage of frames to draw */
int Mode = 0; /* Conjunction of CV_* bits */
int ScrWidth = WIDTH; /* Screen buffer width */
int ScrHeight = HEIGHT; /* Screen buffer height */
byte *ScrBuffer = 0; /* If screen buffer allocated, */
/* put address here */
Z80 CPU; /* Z80 CPU state */
SN76489 PSG; /* SN76489 PSG state */
TMS9918 VDP; /* TMS9918 VDP state */
byte *RAM; /* CPU address space */
byte *ROMPage[8]; /* 8x8kB read-only (ROM) pages */
byte *RAMPage[8]; /* 8x8kB read-write (RAM) pages */
byte Port20; /* Adam port 0x20-0x3F (AdamNet) */
byte Port60; /* Adam port 0x60-0x7F (memory) */
byte ExitNow; /* 1: Exit the emulator */
byte AdamROMs; /* 1: All Adam ROMs are loaded */
byte JoyMode; /* Joystick controller mode */
unsigned int JoyState; /* Joystick states */
unsigned int SpinCount; /* Spinner counters */
unsigned int SpinStep; /* Spinner steps */
unsigned int SpinState; /* Spinner bit states */
char *SndName = (char*)"LOG.MID"; /* Soundtrack log file */
char *StaName = 0; /* Emulation state save file */
char *HomeDir = 0; /* Full path to home directory */
char *PrnName = 0; /* Printer redirection file */
FILE *PrnStream;
#ifdef ZLIB
#define fopen gzopen
#define fclose gzclose
#define fread(B,N,L,F) gzread(F,B,(L)*(N))
#define fwrite(B,N,L,F) gzwrite(F,B,(L)*(N))
#endif
/** StartColeco() ********************************************/
/** Allocate memory, load ROM image, initialize hardware, **/
/** CPU and start the emulation. This function returns 0 in **/
/** the case of failure. **/
/*************************************************************/
int StartColeco(const char *Cartridge)
{
char CurDir[256];
FILE *F;
int *T,J;
char *P;
/*** STARTUP CODE starts here: ***/
T=(int *)"\01\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
#ifdef LSB_FIRST
if(*T!=1)
{
printf("********** This machine is high-endian. **********\n");
printf("Take #define LSB_FIRST out and compile ColEm again.\n");
return(0);
}
#else
if(*T==1)
{
printf("********* This machine is low-endian. **********\n");
printf("Insert #define LSB_FIRST and compile ColEm again.\n");
return(0);
}
#endif
/* Zero everything */
RAM = 0;
ExitNow = 0;
AdamROMs = 0;
StaName = 0;
/* Set up CPU modes */
CPU.TrapBadOps = Verbose&0x04;
CPU.IAutoReset = 1;
/* Allocate memory for RAM and ROM */
if(Verbose) printf("Allocating 256kB for CPU address space...");
if(!(RAM=(byte *)malloc(0x40000))) { if(Verbose) puts("FAILED");return(0); }
memset(RAM,NORAM,0x40000);
/* Create TMS9918 VDP */
if(Verbose) printf("OK\nCreating VDP...");
ScrBuffer=New9918(&VDP,ScrBuffer,ScrWidth,ScrHeight);
if(!ScrBuffer) { if(Verbose) puts("FAILED");return(0); }
VDP.DrawFrames=UPeriod;
/* Loading the ROMs... */
if(Verbose) printf("OK\nLoading ROMs:\n");
P=0;
/* Go to home directory if specified */
if(!HomeDir) CurDir[0]='\0';
else
{
if(!getcwd(CurDir,sizeof(CurDir))) CurDir[0]='\0';
chdir(HomeDir);
}
/* COLECO.ROM: OS7 (ColecoVision BIOS) */
if(Verbose) printf(" Opening COLECO.ROM...");
if(!(F=fopen("COLECO.ROM","rb"))) P=(char*)"NOT FOUND";
else
{
if(fread(ROM_BIOS,1,0x2000,F)!=0x2000) P=(char*)"SHORT FILE";
fclose(F);
}
/* WRITER.ROM: SmartWriter (Adam bootup) */
if(!P)
{
if(Verbose) printf("OK\n Opening WRITER.ROM...");
if(F=fopen("WRITER.ROM","rb"))
{
if(fread(ROM_WRITER,1,0x8000,F)==0x8000) ++AdamROMs;
fclose(F);
}
if(Verbose) printf(AdamROMs>=1? "OK\n":"FAILED\n");
}
/* EOS.ROM: EOS (Adam BIOS) */
if(!P&&AdamROMs)
{
if(Verbose) printf(" Opening EOS.ROM...");
if(F=fopen("EOS.ROM","rb"))
{
if(fread(ROM_EOS,1,0x2000,F)==0x2000) ++AdamROMs;
fclose(F);
}
if(Verbose) printf(AdamROMs>=2? "OK\n":"FAILED\n");
}
/* If not all Adam ROMs loaded, disable Adam */
AdamROMs=AdamROMs>=2;
if(!AdamROMs) Mode&=~CV_ADAM;
/* Done loading ROMs */
if(CurDir[0]) chdir(CurDir);
if(P) { if(Verbose) printf("%s\n",P);return(0); }
/* Open stream for a printer */
if(!PrnName) PrnStream=stdout;
else
{
if(Verbose) printf("Redirecting printer output to %s...",PrnName);
if(!(PrnStream=fopen(PrnName,"wb"))) PrnStream=stdout;
if(Verbose) printf(PrnStream==stdout? "FAILED\n":"OK\n");
}
/* Initialize MIDI sound logging */
InitMIDI(SndName);
/* Reset system hardware */
ResetColeco(Mode);
/* Load cartridge */
if(Cartridge)
{
if(Verbose) printf(" Opening %s...",Cartridge);
J=LoadROM(Cartridge);
if(Verbose)
{
if(J) printf("%d bytes loaded...OK\n",J);
else printf("FAILED\n");
}
}
if(Verbose) printf("RUNNING ROM CODE...\n");
J=RunZ80(&CPU);
if(Verbose) printf("EXITED at PC = %04Xh.\n",J);
return(1);
}
/** LoadROM() ************************************************/
/** Load given cartridge ROM file. Returns number of bytes **/
/** on success, 0 on failure. **/
/*************************************************************/
int LoadROM(const char *Cartridge)
{
byte Buf[2],*P;
FILE *F;
int J;
char* cart = (char*) malloc(sizeof(char) * (strlen(Cartridge) + 22));
strcpy(cart, "shared/misc/ColEm/ROM/");
strcat(cart, Cartridge);
/* Open file */
F=fopen(cart,"rb");
if(!F) return(0);
/* Read magic number */
if(fread(Buf,1,2,F)!=2) { fclose(F);free(cart);return(0); }
/* If it is a ColecoVision game cartridge... */
/* If it is a Coleco Adam expansion ROM... */
P = (Buf[0]==0x55)&&(Buf[1]==0xAA)? ROM_CARTRIDGE
: (Buf[0]==0xAA)&&(Buf[1]==0x55)? ROM_CARTRIDGE
: (Buf[0]==0x66)&&(Buf[1]==0x99)? ROM_EXPANSION
: 0;
/* If ROM not recognized, drop out */
if(!P) { fclose(F);return(0); }
/* Clear ROM buffer and store the first two bytes */
memset(P,NORAM,0x8000);
P[0]=Buf[0];
P[1]=Buf[1];
/* Read the rest of the ROM */
J=2+fread(P+2,1,0x7FFE,F);
/* Done with the file */
fclose(F);
/* Reset hardware */
ResetColeco(Mode);
/* Free previous state name */
if(StaName) free(StaName);
/* If allocated enough space for the state name... */
if(StaName=(char*)malloc(strlen(Cartridge)+4))
{
/* Compose state file name */
strcpy(StaName,Cartridge);
P=(byte*)strrchr(StaName,'.');
if(P) strcpy((char*)P,".sta"); else strcat(StaName,".sta");
/* Try loading state file */
//LoadSTA(StaName);
}
free(cart);
/* Done */
return(J);
}
/** SaveSTA() ************************************************/
/** Save emulation state to a given file. Returns 1 on **/
/** success, 0 on failure. **/
/*************************************************************/
int SaveSTA(const char *StateFile)
{
static byte Header[16] = { 'S', 'T', 'F', '\032', '\002', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
unsigned int State[256],J;
FILE *F;
char path[256];
strcpy(path, "shared/misc/ColEm/save/");
strcat(path, StateFile);
/* Open saved state file */
if(!(F=fopen(path,"wb"))) return(0);
/* Fill header */
J=CartCRC();
Header[5] = Mode&CV_ADAM;
Header[6] = J&0xFF;
Header[7] = (J>>8)&0xFF;
Header[8] = (J>>16)&0xFF;
Header[9] = (J>>24)&0xFF;
/* Write out the header */
if(fwrite(Header,1,16,F)!=16) { fclose(F);return(0); }
/* Generate hardware state */
J=0;
memset(State,0,sizeof(State));
State[J++] = Mode;
State[J++] = UPeriod;
State[J++] = ROMPage[0]-RAM;
State[J++] = ROMPage[1]-RAM;
State[J++] = ROMPage[2]-RAM;
State[J++] = ROMPage[3]-RAM;
State[J++] = ROMPage[4]-RAM;
State[J++] = ROMPage[5]-RAM;
State[J++] = ROMPage[6]-RAM;
State[J++] = ROMPage[7]-RAM;
State[J++] = RAMPage[0]-RAM;
State[J++] = RAMPage[1]-RAM;
State[J++] = RAMPage[2]-RAM;
State[J++] = RAMPage[3]-RAM;
State[J++] = RAMPage[4]-RAM;
State[J++] = RAMPage[5]-RAM;
State[J++] = RAMPage[6]-RAM;
State[J++] = RAMPage[7]-RAM;
State[J++] = JoyMode;
State[J++] = Port20;
State[J++] = Port60;
/* Write out CPU state */
if(fwrite(&CPU,1,sizeof(CPU),F)!=sizeof(CPU))
{ fclose(F);return(0); }
/* Write out VDP state */
if(fwrite(&VDP,1,sizeof(VDP),F)!=sizeof(VDP))
{ fclose(F);return(0); }
/* Write out PSG state */
if(fwrite(&PSG,1,sizeof(PSG),F)!=sizeof(PSG))
{ fclose(F);return(0); }
/* Write out hardware state */
if(fwrite(State,1,sizeof(State),F)!=sizeof(State))
{ fclose(F);return(0); }
/* Write out memory contents */
if(fwrite(RAM_BASE,1,0xA000,F)!=0xA000)
{ fclose(F);return(0); }
if(fwrite(VDP.VRAM,1,0x4000,F)!=0x4000)
{ fclose(F);return(0); }
/* Done */
fclose(F);
return(1);
}
/** LoadSTA() ************************************************/
/** Load emulation state from a given file. Returns 1 on **/
/** success, 0 on failure. **/
/*************************************************************/
int LoadSTA(const char *StateFile)
{
unsigned int State[256],J;
byte Header[16],*VRAM;
int XPal[16];
byte *XBuf;
FILE *F;
char path[256];
strcpy(path, "shared/misc/ColEm/save/");
strcat(path, StateFile);
/* Open saved state file */
if(!(F=fopen(path,"rb"))) return(0);
/* Read and check the header */
if(fread(Header,1,16,F)!=16)
{ fclose(F);return(0); }
if(memcmp(Header,"STF\032\002",5))
{ fclose(F);return(0); }
J=CartCRC();
if(
(Header[5]!=(Mode&CV_ADAM)) ||
(Header[6]!=(J&0xFF)) ||
(Header[7]!=((J>>8)&0xFF)) ||
(Header[8]!=((J>>16)&0xFF)) ||
(Header[9]!=((J>>24)&0xFF))
) { fclose(F);return(0); }
/* Read CPU state */
if(fread(&CPU,1,sizeof(CPU),F)!=sizeof(CPU))
{ fclose(F);ResetColeco(Mode);return(0); }
/* Read VDP state, preserving VRAM address */
VRAM = VDP.VRAM;
XBuf = VDP.XBuf;
memcpy(XPal,VDP.XPal,sizeof(XPal));
if(fread(&VDP,1,sizeof(VDP),F)!=sizeof(VDP))
{ fclose(F);VDP.VRAM=VRAM;VDP.XBuf=XBuf;ResetColeco(Mode);return(0); }
VDP.ChrTab += VRAM-VDP.VRAM;
VDP.ChrGen += VRAM-VDP.VRAM;
VDP.SprTab += VRAM-VDP.VRAM;
VDP.SprGen += VRAM-VDP.VRAM;
VDP.ColTab += VRAM-VDP.VRAM;
VDP.VRAM = VRAM;
VDP.XBuf = XBuf;
memcpy(VDP.XPal,XPal,sizeof(VDP.XPal));
/* Read PSG state */
if(fread(&PSG,1,sizeof(PSG),F)!=sizeof(PSG))
{ fclose(F);ResetColeco(Mode);return(0); }
/* Read hardware state */
if(fread(State,1,sizeof(State),F)!=sizeof(State))
{ fclose(F);ResetColeco(Mode);return(0); }
/* Read memory contents */
if(fread(RAM_BASE,1,0xA000,F)!=0xA000)
{ fclose(F);ResetColeco(Mode);return(0); }
if(fread(VDP.VRAM,1,0x4000,F)!=0x4000)
{ fclose(F);ResetColeco(Mode);return(0); }
/* Done with the file */
fclose(F);
/* Parse hardware state */
J=0;
Mode = State[J++];
UPeriod = State[J++];
ROMPage[0] = State[J++]+RAM;
ROMPage[1] = State[J++]+RAM;
ROMPage[2] = State[J++]+RAM;
ROMPage[3] = State[J++]+RAM;
ROMPage[4] = State[J++]+RAM;
ROMPage[5] = State[J++]+RAM;
ROMPage[6] = State[J++]+RAM;
ROMPage[7] = State[J++]+RAM;
RAMPage[0] = State[J++]+RAM;
RAMPage[1] = State[J++]+RAM;
RAMPage[2] = State[J++]+RAM;
RAMPage[3] = State[J++]+RAM;
RAMPage[4] = State[J++]+RAM;
RAMPage[5] = State[J++]+RAM;
RAMPage[6] = State[J++]+RAM;
RAMPage[7] = State[J++]+RAM;
JoyMode = State[J++];
Port20 = State[J++];
Port60 = State[J++];
/* All PSG channels have been changed */
PSG.Changed = 0xFF;
/* Done */
return(1);
}
#ifdef ZLIB
#undef fopen
#undef fclose
#undef fread
#undef fwrite
#endif
/** TrashColeco() ********************************************/
/** Free memory allocated by StartColeco(). **/
/*************************************************************/
void TrashColeco(void)
{
/* Free all memory and resources */
if(RAM) free(RAM);
if(StaName) free(StaName);
/* Close MIDI sound log */
TrashMIDI();
/* Done with VDP */
Trash9918(&VDP);
}
/** SetMemory() **********************************************/
/** Set memory pages according to passed values. **/
/*************************************************************/
void SetMemory(byte NewPort60,byte NewPort20)
{
/* Store new values */
Port60 = NewPort60;
Port20 = NewPort20;
/* Lower 32kB ROM */
if(!(NewPort60&0x03)&&(NewPort20&0x02))
{
ROMPage[0] = RAM_DUMMY;
ROMPage[1] = RAM_DUMMY;
ROMPage[2] = ROM_EOS;
ROMPage[3] = ROM_EOS;
}
else
{
ROMPage[0] = RAM+((int)(NewPort60&0x03)<<15);
if(!(Mode&CV_ADAM))
{
ROMPage[1] = RAM_DUMMY;
ROMPage[2] = RAM_DUMMY;
ROMPage[3] = RAM_BASE;
}
else
{
ROMPage[1] = ((NewPort60&0x03)==3? RAM_MAIN_LO:ROMPage[0])+0x2000;
ROMPage[2] = ROMPage[1]+0x2000;
ROMPage[3] = ROMPage[1]+0x4000;
}
}
/* Upper 32kB ROM */
ROMPage[4] = RAM+((int)(NewPort60&0x0C)<<13)+0x20000;
ROMPage[5] = ROMPage[4]+0x2000;
ROMPage[6] = ROMPage[4]+0x4000;
ROMPage[7] = ROMPage[4]+0x6000;
/* Lower 32kB RAM */
if(!(Port60&0x03))
RAMPage[0]=RAMPage[1]=RAMPage[2]=RAMPage[3]=RAM_DUMMY;
else
{
RAMPage[0] = (Port60&0x03)==3? RAM_DUMMY:ROMPage[0];
RAMPage[1] = ROMPage[1];
RAMPage[2] = ROMPage[2];
RAMPage[3] = ROMPage[3];
}
/* Upper 32kB RAM */
if(Port60&0x04)
RAMPage[4]=RAMPage[5]=RAMPage[6]=RAMPage[7]=RAM_DUMMY;
else
{
RAMPage[4] = ROMPage[4];
RAMPage[5] = ROMPage[5];
RAMPage[6] = ROMPage[6];
RAMPage[7] = ROMPage[7];
}
}
/** CartCRC() ************************************************/
/** Compute cartridge CRC. **/
/*************************************************************/
unsigned int CartCRC(void)
{
unsigned int I,J;
for(J=I=0;J<0x8000;++J) I+=ROM_CARTRIDGE[J];
return(I);
}
/** ResetColeco() ********************************************/
/** Reset CPU and hardware to new operating modes. Returns **/
/** new value of the Mode variable (possibly != NewMode). **/
/*************************************************************/
int ResetColeco(int NewMode)
{
int I,J;
/* Disable Adam if not all ROMs are loaded */
if(!AdamROMs) NewMode&=~CV_ADAM;
/* Set new modes into effect */
Mode = NewMode;
/* Initialize hardware */
JoyMode = 0;
JoyState = 0;
SpinState = 0;
SpinCount = 0;
SpinStep = 0;
/* Clear memory (important for NetPlay, to */
/* keep states at both sides consistent) */
/* Clearing to zeros (Heist) */
memset(RAM_MAIN_LO,0x00,0x8000);
memset(RAM_MAIN_HI,0x00,0x8000);
memset(RAM_EXP_LO,0x00,0x8000);
memset(RAM_EXP_HI,0x00,0x8000);
memset(RAM_OS7,0x00,0x2000);
/* Set up memory pages */
SetMemory(Mode&CV_ADAM? 0x00:0x0F,0x00);
/* Set scanline parameters according to video type */
/* (this has to be done before CPU and VDP are reset) */
VDP.MaxSprites = Mode&CV_ALLSPRITE? 255:TMS9918_MAXSPRITES;
VDP.Scanlines = Mode&CV_PAL? TMS9929_LINES:TMS9918_LINES;
CPU.IPeriod = Mode&CV_PAL? TMS9929_LINE:TMS9918_LINE;
/* Reset TMS9918 VDP */
Reset9918(&VDP,ScrBuffer,ScrWidth,ScrHeight);
/* Reset SN76489 PSG */
Reset76489(&PSG,0);
Sync76489(&PSG,SN76489_SYNC);
/* Reset Z80 CPU */
ResetZ80(&CPU);
/* Set up the palette */
I = Mode&CV_PALETTE;
I = I==CV_PALETTE0? 0:I==CV_PALETTE1? 16:I==CV_PALETTE2? 32:0;
for(J=0;J<16;++J,++I)
VDP.XPal[J]=SetColor(J,Palette9918[I].R,Palette9918[I].G,Palette9918[I].B);
/* Return new modes */
return(Mode);
}
/** WrZ80() **************************************************/
/** Z80 emulation calls this function to write byte V to **/
/** address A of Z80 address space. **/
/*************************************************************/
void WrZ80(register word A,register byte V)
{
if(Mode&CV_ADAM) RAMPage[A>>13][A&0x1FFF]=V;
else if((A>=0x6000)&&(A<0x8000))
{
A&=0x03FF;
RAM_BASE[A] =RAM_BASE[0x0400+A]=
RAM_BASE[0x0800+A]=RAM_BASE[0x0C00+A]=
RAM_BASE[0x1000+A]=RAM_BASE[0x1400+A]=
RAM_BASE[0x1800+A]=RAM_BASE[0x1C00+A]=V;
}
}
/** RdZ80() **************************************************/
/** Z80 emulation calls this function to read a byte from **/
/** address A of Z80 address space. Copied to Z80.c and **/
/** made inlined to speed things up. **/
/*************************************************************/
byte RdZ80(register word A) { return(ROMPage[A>>13][A&0x1FFF]); }
/** PatchZ80() ***********************************************/
/** Z80 emulation calls this function when it encounters a **/
/** special patch command (ED FE) provided for user needs. **/
/*************************************************************/
void PatchZ80(Z80 *R) {}
/** InZ80() **************************************************/
/** Z80 emulation calls this function to read a byte from **/
/** a given I/O port. **/
/*************************************************************/
byte InZ80(register word Port)
{
/* Coleco uses 8bit port addressing */
Port&=0x00FF;
switch(Port&0xE0)
{
case 0x40: /* Printer Status */
if((Mode&CV_ADAM)&&(Port==0x40)) return(0xFF);
break;
case 0x20: /* AdamNet Control */
if(Mode&CV_ADAM) return(Port20);
break;
case 0x60: /* Memory Control */
if(Mode&CV_ADAM) return(Port60);
break;
case 0xE0: /* Joysticks Data */
Port = Port&0x02? (JoyState>>16):JoyState;
Port = JoyMode? (Port>>8):Port;
return(~Port&0x7F);
case 0xA0: /* VDP Status/Data */
return(Port&0x01? RdCtrl9918(&VDP):RdData9918(&VDP));
}
/* No such port */
return(NORAM);
}
/** OutZ80() *************************************************/
/** Z80 emulation calls this function to write a byte to a **/
/** given I/O port. **/
/*************************************************************/
void OutZ80(register word Port,register byte Value)
{
/* Coleco uses 8bit port addressing */
Port&=0x00FF;
switch(Port&0xE0)
{
case 0x80: JoyMode=0;break;
case 0xC0: JoyMode=1;break;
case 0xE0: Write76489(&PSG,Value);break;
case 0xA0:
if(!(Port&0x01)) WrData9918(&VDP,Value);
else if(WrCtrl9918(&VDP,Value)) CPU.IRequest=INT_NMI;
break;
case 0x40:
if((Mode&CV_ADAM)&&(Port==0x40)) fputc(Value,PrnStream);
break;
case 0x20:
if(Mode&CV_ADAM) SetMemory(Port60,Value);
break;
case 0x60:
if(Mode&CV_ADAM) SetMemory(Value,Port20);
break;
}
}
/** LoopZ80() ************************************************/
/** Z80 emulation calls this function periodically to check **/
/** if the system hardware requires any interrupts. **/
/*************************************************************/
word LoopZ80(Z80 *R)
{
static byte ACount=0;
/* If emulating spinners... */
if(Mode&CV_SPINNERS)
{
/* Reset spinner bits */
JoyState&=~0x30003000;
/* Count ticks for both spinners */
SpinCount+=SpinStep;
/* Process first spinner */
if(SpinCount&0x00008000)
{
SpinCount&=~0x00008000;
if(Mode&CV_SPINNER1)
{
JoyState |= SpinState&0x00003000;
R->IRequest = INT_RST38;
}
}
/* Process second spinner */
if(SpinCount&0x80000000)
{
SpinCount&=~0x80000000;
if(Mode&CV_SPINNER2)
{
JoyState |= SpinState&0x30000000;
R->IRequest = INT_RST38;
}
}
}
/* Refresh VDP */
if(Loop9918(&VDP)) R->IRequest=INT_NMI;
/* Drop out unless end of screen is reached */
if(VDP.Line!=TMS9918_END_LINE) return(R->IRequest);
/* End of screen reached... */
/* Check joysticks, clear unused bits */
JoyState=Joystick()&~0x30003000;
/* Lock out opposite direction keys (Grog's Revenge) */
if(JoyState&JST_RIGHT) JoyState&=~JST_LEFT;
if(JoyState&JST_DOWN) JoyState&=~JST_UP;
if(JoyState&(JST_RIGHT<<16)) JoyState&=~(JST_LEFT<<16);
if(JoyState&(JST_DOWN<<16)) JoyState&=~(JST_UP<<16);
/* If emulating spinners... */
if(Mode&CV_SPINNERS)
{
int I,K;
/* Get mouse position relative to the window center, */
/* normalized to -512..+512 range */
I = Mouse();
/* First spinner */
K = (Mode&CV_SPINNER1Y? (I<<2):Mode&CV_SPINNER1X? (I<<16):0)>>16;
K = K<-512? -512:K>512? 512:K;
SpinStep = K>=0? (K>32? K:0):(K<-32? -K:0);
SpinState = K>0? 0x00003000:K<0? 0x00001000:0;
/* Second spinner */
K = (Mode&CV_SPINNER2Y? (I<<2):Mode&CV_SPINNER2X? (I<<16):0)>>16;
K = K<-512? -512:K>512? 512:K;
SpinStep |= (K>=0? (K>32? K:0):(K<-32? -K:0))<<16;
SpinState|= K>0? 0x10000000:K<0? 0x30000000:0;
/* Fire buttons */
if(I&0x80000000)
JoyState |= (Mode&CV_SPINNER2? (JST_FIRER<<16):0)
| (Mode&CV_SPINNER1? JST_FIRER:0);
if(I&0x40000000)
JoyState |= (Mode&CV_SPINNER2? (JST_FIREL<<16):0)
| (Mode&CV_SPINNER1? JST_FIREL:0);
}
/* Autofire emulation */
ACount=(ACount+1)&0x07;
if(ACount>3)
{
if(Mode&CV_AUTOFIRER) JoyState&=~(JST_FIRER|(JST_FIRER<<16));
if(Mode&CV_AUTOFIREL) JoyState&=~(JST_FIREL|(JST_FIREL<<16));
}
/* Count ticks for MIDI ouput */
MIDITicks(1000/(Mode&CV_PAL? TMS9929_FRAMES:TMS9918_FRAMES));
/* Flush any accumulated sound changes */
Sync76489(&PSG,SN76489_FLUSH|(Mode&CV_DRUMS? SN76489_DRUMS:0));
/* If exit requested, return INT_QUIT */
if(ExitNow) return(INT_QUIT);
/* Generate interrupt if needed */
return(R->IRequest);
}
|
ec3d00fc20ae7c69d86d94ae982a1cefcb62e779 | c57c691e0b431a283bf2bf909e5e8735b68c06ce | /ppp.cpp | 799548639c7a86d281754bf4f0500e66df63b009 | [] | no_license | prabal-k/prabal-k | 55fdd0aae95dcac8c4325b312f7d35363b260294 | 01fabccdcef8da27a1a895f0c59b4390dc560ac6 | refs/heads/main | 2023-08-27T19:49:24.143657 | 2021-09-24T05:34:46 | 2021-09-24T05:34:46 | 409,473,966 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 284 | cpp | ppp.cpp | #include<stdio.h>
#include<conio.h>
int main()
{
int i=0,x,count=0;
printf("enter the number:");
scanf("%d",&x);
for(i=1;i<=x;i++)
{
if(i%2==0)
{
count++;
}
}
if(count==2)
{
printf("%d is prime number",x);
}
else
printf("%d is not prime",x);
return(0);
}
|
14963a1176f02a4945b237edba7391c093f2ef15 | 7619baf942a24e5f1c3c776126d5b3e9286f1341 | /KeywordsColoring2/source/Hook.cpp | f0a9a52327988ebcebd29384c6799e5e20573e19 | [] | no_license | sillsdev/CarlaLegacy | 2fe9c6f35f065e7167bfd4135dd5e48be3ad23be | 553ae08a7ca6c24cffcdeaf85846df63125a57fd | refs/heads/master | 2022-11-15T04:57:18.629339 | 2022-09-27T14:18:15 | 2022-09-27T14:18:15 | 6,128,324 | 10 | 8 | null | 2022-11-09T21:43:38 | 2012-10-08T17:33:08 | XSLT | UTF-8 | C++ | false | false | 12,671 | cpp | Hook.cpp | // Hook.cpp : Implementation of CHook
#include "stdafx.h"
#include "CARLAStudioApp.h"
#include <atlconv.h>
#ifndef mr270
#import "..\..\CarlaStudio\CStudio\csautomation\csautomation.tlb" no_namespace
#else // mr270
#import "..\..\csautomation\csautomation.tlb" no_namespace
#endif // mr270
#include "Hook.h"
#include "LangModelsDoc.h"
#include "CarlaLanguage.h"
#include "InputDoc.h"
//#include "..\..\csremote\CSRemoteRegistry.h"
#include "processingprefs.h"
#include "PathDescriptor.h"
#include "analysisprocesses.h"
#include "processSequence.h"
#include "projectDoc.h"
//#include "carlalanguage.h"
#ifndef mr270
#include "..\..\CarlaStudio\CStudio\CS Utility DLL\cleaner.h" // Added by ClassView
#else // mr270
#include "..\..\cs utility dll\cleaner.h"
#endif // mr270
#include <strstrea.h>
#include "ParseStream.h"
#include <io.h>
/////////////////////////////////////////////////////////////////////////////
// CHook
static CString sThrow; // static so it doesn't go out of scope during the throw
// and loose its contents
#define throwIt throw (LPCTSTR)sThrow;
static BOOL backupFile(LPCTSTR lpszInPath, int nMaxBaks);
STDMETHODIMP CHook::PerformTask(VARIANT varICSTask)
{
USES_CONVERSION;
if(!varICSTask.punkVal)
return E_POINTER;
if(varICSTask.vt != VT_DISPATCH && varICSTask.vt != VT_UNKNOWN)
return E_INVALIDARG;
ITaskPtr qTask(varICSTask.punkVal);
char* lpszInPath = OLE2A(qTask->GetInputPath());
CDocument* pDoc = NULL;
try
{
// clear this in case we don't get to the end
CComBSTR bstrNULL("");
qTask->PutActualOutputPath(bstrNULL.m_str);
CPathDescriptor sPath = lpszInPath;
if(!sPath.fileExists())
{
sThrow.Format("Could not find the input file, %s", sPath.getFullPath());
throwIt;
}
CRemoteCommand cmd;
// fill in our CRemoteCommand from the COM Task object
cmd.iGoal = qTask->GetGoal();
cmd.eOutputLocation = (CRemoteCommand::CSOUTPUTLOCATION)qTask->GetOutputLocation();
if(cmd.eOutputLocation == (CRemoteCommand::CSOUTPUTLOCATION)csSpecifiedPath)
{
cmd.sDesiredOutputPath = OLE2A(qTask->GetDesiredOutputPath());
if(cmd.sDesiredOutputPath.GetLength() == 0)
throw "You must specify the desired output path";
}
else if(cmd.eOutputLocation == csReplaceInput)
{
const int kNumBackups = 3;
if(!backupFile(sPath, kNumBackups))
{
cmd.sDesiredOutputPath = sPath.getDirectory()+sPath.getFileName()+"2"+sPath.getFileExtension();
CString s;
s.Format("Couldn't backup %s, so the output file will not overwrite it. Instead, the resulting file will be %s", sPath.getFileFullName(), cmd.sDesiredOutputPath);
AfxMessageBox(s);
}
else
cmd.sDesiredOutputPath = sPath;
}
cmd.pSourceLang = getLangFromCode(qTask->GetSourceLangCode());
if(!cmd.pSourceLang)
throw "You must specify a source language";
CString sTarLangCode = OLE2A(qTask->GetTargetLangCode());
if(cmd.iGoal == CProcessingPrefs::kTargetText)
{
if(sTarLangCode.IsEmpty())
throw "You must specify a target language when doing transfer";
cmd.pTargetLang = theApp.getProject()->getLangFromID(sTarLangCode);
if(!cmd.pTargetLang)
{
sThrow.Format("This project does not have a language with code %s", sTarLangCode);
throwIt;
}
}
if(qTask->GetInputIsInterlinear()) // first need to clean it (de-interlinearize it)
{
// may throw exception
sPath = deinterlinearize(sPath, qTask);
cmd.sMarkersToIncludeOrExclude = OLE2A(qTask->GetInterlinearWordMarker());
cmd.sMarkersToIncludeOrExclude.TrimLeft();
// trim any leading backslash
if(!cmd.sMarkersToIncludeOrExclude.IsEmpty() && cmd.sMarkersToIncludeOrExclude[0] == '\\')
cmd.sMarkersToIncludeOrExclude = cmd.sMarkersToIncludeOrExclude.Mid(1);
if(cmd.sMarkersToIncludeOrExclude.IsEmpty())
throw "You must specify the marker for the text line";
// set up intergen process to remove unwanted empty lines left in by intergen
CIntergenProcess *pI = getIntergenProcess(qTask->GetSourceLangCode());
if(pI)
pI->m_sPostIntergenStripMarker = cmd.sMarkersToIncludeOrExclude;
// add a leading back-slash
cmd.sMarkersToIncludeOrExclude = CString("\\")+cmd.sMarkersToIncludeOrExclude ;
cmd.bIncludeMarkers = TRUE;;
}
else // plain 'ol text, so set the textin text markers
{
cmd.bIncludeMarkers = qTask->GetIncludeLinesWithSpecifiedMarkers();
cmd.sMarkersToIncludeOrExclude = OLE2A(qTask->GetMarkersToIncludeOrExclude());
if(cmd.sMarkersToIncludeOrExclude.IsEmpty())
throw("You must include the text markers to include or exclude");
}
// for now, we don't have a way of passing these parameters to anyone, so we
// just change the values in the TextInModel and set the modified bit of the language
cmd.pSourceLang->getTextInModel().sMarkersToIncludeOrExclude.setData(cmd.sMarkersToIncludeOrExclude);
// radio 0 is include, 1 is exclude
cmd.pSourceLang->getTextInModel().rIncludeOrExcludeMarkers.setData(cmd.bIncludeMarkers?0:1);
cmd.pSourceLang->getLangDoc()->SetModifiedFlag(); // so it will get save and change the control files
pDoc = theApp.OpenDocumentFile(sPath);
if(!pDoc)
{
sThrow.Format("Couldn't open the file: %s", sPath.getFullPath());
throwIt;
}
// bring CStudio to the front during parsing. The caller is responsible
// for bringing itself to the front aftwards
::SetForegroundWindow(theApp.GetMainWnd()->m_hWnd);
int iResult = theApp.RunProcessors(&cmd, pDoc);
if(iResult)
{
sThrow = cmd.sErrorMessage;
throwIt;
}
// put result parameters in the Task Object
CComBSTR bstrOut(cmd.sActualOutputPath);
qTask->PutActualOutputPath(bstrOut.m_str);
}
catch(LPCTSTR lpszError)
{
return Error(lpszError);
}
catch(CString s)
{
return Error(s);
}
return S_OK;
}
STDMETHODIMP CHook::get_LangCodes(VARIANT *pVal)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState())
// TODO: Add your implementation code here
return S_OK;
}
STDMETHODIMP CHook::get_LangCodesString(BSTR *pVal)
{
USES_CONVERSION;
AFX_MANAGE_STATE(AfxGetStaticModuleState())
CProjectDoc *pp = theApp.getProject();
CComBSTR s;
int i;
CTypedPtrArray<CPtrArray , CLangModelsDoc*>& vecLangDocs = pp->getLangDocs();
for(i = 0; i<vecLangDocs.GetSize(); i++)
{
CLangModelsDoc* pDoc = vecLangDocs.ElementAt(i);
CCarlaLanguage *pL = pDoc->getLang();
s += A2OLE(pL->getUniqueID());
if(i<(vecLangDocs.GetSize()-1)) // if not the last one
s += L",";
}
s.CopyTo(pVal);
return S_OK;
}
STDMETHODIMP CHook::get_CurrentIntergenWordMarker(BSTR bstrLangCode, BSTR *pbstrWordMarker)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState())
try
{
// GET THE TEXT MARKER FROM INTERGEN
CIntergenProcess* pI = getIntergenProcess(bstrLangCode);
CComBSTR b(pI->getWordMarker());
*pbstrWordMarker = b.Detach();
}
catch (LPCTSTR lpszError)
{
return Error(lpszError);
}
return S_OK;
}
STDMETHODIMP CHook::get_CurrentIntergenAnalysisMarkers(BSTR bstrLangCode, BSTR *pAnalysisMarkers)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState())
// GET THE ANALYSIS MARKERS
try
{
CIntergenProcess* pIntergenProcess = getIntergenProcess(bstrLangCode);
//CStringArray arAnalysisMarkers;
CString sMarkers = pIntergenProcess->getAnalysisMarkers();
*pAnalysisMarkers = sMarkers.AllocSysString();
}
catch (LPCTSTR lpszError)
{
return Error(lpszError);
}
return S_OK;
}
// LOOKUP THE INTERGEN PROCESS
// Exceptions: LPCTSTR
// Protected (not COM)
CIntergenProcess* CHook::getIntergenProcess(BSTR bstrLangCode)
{
// will throw an exception if not found
CCarlaLanguage* pLang = getLangFromCode(bstrLangCode);
ASSERTX(pLang);
CInterlinearProcessSequence* pSeq = pLang->getInterlinearSequence();
if(!pSeq)
throw ("No Interlinear Sequence was found");
CIntergenProcess* pIntergenProcess= (CIntergenProcess*)pSeq->getFirstProcessOfType(CIntergenProcess::ID());
ASSERTX(pIntergenProcess->IsKindOf(RUNTIME_CLASS(CIntergenProcess)));
if(!pIntergenProcess)
throw ("No Intergen Process was found");
return pIntergenProcess;
}
// Protected (not COM)
CCarlaLanguage* CHook::getLangFromCode(BSTR bstrLangCode)
{
USES_CONVERSION;
CString sLangCode = OLE2A(bstrLangCode);
if(sLangCode.IsEmpty())
throw ("Somehow CarlaStudio was handed an empty language code string");
CCarlaLanguage* pLang = theApp.getProject()->getLangFromID(sLangCode);
if(!pLang)
{
sThrow.Format("This project does not have a language with code %s", sLangCode);
throwIt;
}
return pLang;
}
STDMETHODIMP CHook::get_CurrentTextInIncludeExcludeMarkers(BSTR bstrLang, BSTR *pbstrMarkers)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState())
try
{
CCarlaLanguage* pLang = getLangFromCode(bstrLang);
*pbstrMarkers = pLang->getTextInModel().sMarkersToIncludeOrExclude.getData().AllocSysString();
}
catch (LPCTSTR lpszError)
{
return Error(lpszError);
}
return S_OK;
}
// returns true if the user has specified which markers to inlclude (as opposed
// to which markers to exclude)
STDMETHODIMP CHook::get_CurrentTextInIncludeSpecified(BSTR bstrLang, BOOL *pbInclude)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState())
try
{
CCarlaLanguage* pLang = getLangFromCode(bstrLang);
// radio 0 is include, 1 is exclude
*pbInclude = (pLang->getTextInModel().rIncludeOrExcludeMarkers == 0);
}
catch (LPCTSTR lpszError)
{
return Error(lpszError);
}
return S_OK;
}
// exceptions: LPCTSTRs
// returns path to the file this produces
CString CHook::deinterlinearize(CPathDescriptor& pathInput, ITask* pTask)
{
USES_CONVERSION;
ITaskPtr qTask(pTask);
ofstream fout;
CString sCleanedPath = pathInput.getDirectory() + "_" + pathInput.getFileName() + ".txt";
fout.open(sCleanedPath);
if(!fout.is_open())
{
sThrow.Format("Couldn't create the file for writing the deinterlinearized text: %s", sCleanedPath);
throwIt;
}
try
{
CString sTextMrk;
// this property InterlinearWordMarker, is use only when we're de-interlinearizing
// (using clean). Else MarkersToIncludeOrExclude is relevant.
sTextMrk = OLE2A(qTask->GetInterlinearWordMarker());
sTextMrk.TrimRight();
sTextMrk.TrimLeft();
if(sTextMrk.GetLength() && sTextMrk[0] == '\\') // trim off leading slash
sTextMrk = sTextMrk.Mid(1);
if(sTextMrk.IsEmpty())
throw "The Interlinear Word Marker is empty.";
// break up the string of markers into an array of markers
CParseStream stream(OLE2A(qTask->GetAnalysisMarkers()));
CString sMrk;
CStringArray analysisMarkers;
while(stream.word(sMrk, FALSE))
{
if(sMrk.GetLength() && sMrk[0] == '\\') // trim off leading slash
sMrk = sMrk.Mid(1);
analysisMarkers.Add(sMrk);
}
CSCleaner cleaner;
cleaner.stripITXAnalysis(fout, pathInput.getFullPath(), sTextMrk, analysisMarkers);
//this algorithm stuffed the text onto the previous marker, whatever it was
// this would require that the user specify what all those markers might be
// to ample, so that it would parse the right ones.
//cleaner.cleanITX(fout, pathInput.getFullPath(), sTextMrk, analysisMarkers);
// the blanks algorithm is dangerous because if the blank is missing,
// it will throw away lines after the last analysis line and before
// the next text line (lines like \ch, \v, etc).
//cleaner.cleanITXBlanks(fout, pathInput.getFullPath(), sTextMrk);
}
catch(LPCTSTR lpszError)
{
sThrow.Format("While trying to deinterlinearize %s, got this error:\n%s", pathInput.getFullPath(), lpszError);
throwIt;
}
if(!CPathDescriptor(sCleanedPath).fileExists())
throw("The deinterlinearizing method apparently did not produce a file, or not in the right place.");
return sCleanedPath;
}
// makes multiple backups
BOOL backupFile(LPCTSTR lpszInPath, int nMaxBaks)
{
char lpszBakPath[_MAX_PATH+1];
//sprintf(lpszBakPath, "%s.bak", lpszInPath); // leave the old extension, but add .bak
int nMaxNumber = nMaxBaks + 1;// plus one because we always delete one of the files
// if nMaxBaks is 3, then we go to 4 but delete file 1, leaving three around at any one time
for(int i=1; i <= nMaxNumber; i++)
{
sprintf(lpszBakPath, "%s.%d.bak", lpszInPath, i);
if(-1==_access(lpszBakPath, 00)) // if not found
break;
}
if(i > nMaxNumber) // all numbers used up
i = 1;
// remove the next highest, so we can use that slot next time
// that way, after, say, 1,2,3,4, we'll use 1 and delete 2, so next
// time we'll use 2 and delete 3, etc.
char lpszRemoveBakPath[_MAX_PATH+1];
sprintf(lpszRemoveBakPath, "%s.%d.bak", lpszInPath, (i%nMaxNumber)+1);
remove(lpszRemoveBakPath);
// delete any old backup using this name
remove(lpszBakPath);
// change the name of the input to that of the backup
return CopyFile(lpszInPath, lpszBakPath, FALSE);
} |
e17d9411ed884e7b4e0e32d17a3cadca7b3391bb | 19681bc523d31eaf020f04bb14d31cfcab169c93 | /src/ofx/ofxPDSPSerialOut.cpp | 1ca31bd0899b814f961d3fa2014108563d135eeb | [
"MIT"
] | permissive | hinike/ofxPDSP | 16e6e6e9c759a4a980300a93f3a661ce080b13c9 | b2c7fe4eec7b972e728373601d70f8d989d5c2ab | refs/heads/master | 2020-03-19T15:39:09.261972 | 2018-06-08T14:27:28 | 2018-06-08T14:27:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,660 | cpp | ofxPDSPSerialOut.cpp |
#include "ofxPDSPSerialOut.h"
#ifndef TARGET_OF_IOS
#ifndef __ANDROID__
#define OFXPDSP_SERIALOUTPUTCIRCULARBUFFERSIZE 1024
ofxPDSPSerialOut::ScheduledSerialMessage::ScheduledSerialMessage(){ };
ofxPDSPSerialOut::ScheduledSerialMessage::ScheduledSerialMessage(int channel, float message, chrono::high_resolution_clock::time_point schedule) {
if (channel<1) channel = 1;
if (channel>127) channel = 127;
int msg = (int) message;
if (msg<0) msg = 0;
if (msg>127) msg = 127;
channel = - channel;
this->channel = (signed char) channel;
this->message = (signed char) msg;
this->scheduledTime = schedule;
};
ofxPDSPSerialOut::ScheduledSerialMessage::ScheduledSerialMessage(const ofxPDSPSerialOut::ScheduledSerialMessage &other){
this->channel = other.channel;
this->message = other.message;
this->scheduledTime = other.scheduledTime;
}
ofxPDSPSerialOut::ScheduledSerialMessage& ofxPDSPSerialOut::ScheduledSerialMessage::operator= (const ofxPDSPSerialOut::ScheduledSerialMessage &other){
this->channel = other.channel;
this->message = other.message;
this->scheduledTime = other.scheduledTime;
return *this;
}
ofxPDSPSerialOut::ScheduledSerialMessage::~ScheduledSerialMessage(){}
bool ofxPDSPSerialOut::scheduledSort(const ScheduledSerialMessage &lhs, const ScheduledSerialMessage &rhs ){
return (lhs.scheduledTime < rhs.scheduledTime);
}
//-------------------------------------------------------------------------------------------
ofxPDSPSerialOut::ofxPDSPSerialOut(){
inputs.reserve(128);
messagesToSend.reserve(128);
messagesToSend.clear();
verbose = false;
selectedChannel = 0;
connected = false;
chronoStarted = false;
//midi daemon init
messagesReady = false;
runDaemon = false;
//processing init
circularMax = OFXPDSP_SERIALOUTPUTCIRCULARBUFFERSIZE;
circularBuffer.resize(circularMax);
circularRead = 0;
circularWrite = 0;
//testing
messageCount = 0;
}
ofxPDSPSerialOut::~ofxPDSPSerialOut(){
if(connected){
close();
}
}
void ofxPDSPSerialOut::setVerbose( bool verbose ){
this->verbose = verbose;
}
void ofxPDSPSerialOut::listPorts(){
serial.listDevices();
}
void ofxPDSPSerialOut::openPort(int portIndex, int baudRate){
if(connected){
close();
}
serial.setup( portIndex, baudRate );
if( serial.isInitialized() ){
// set this the right way <-------------------------------------------------------------------------------=====
//if(verbose) cout<<"[pdsp] serial connected to "<<serial.getDeviceList()[portIndex]<<"\n";
startDaemon();
connected = true;
}else{
if(verbose) cout<<"[pdsp] failed serial connection to index "<<portIndex<<"\n";
}
}
void ofxPDSPSerialOut::openPort(string name, int baudRate){
if(connected){
close();
}
serial.setup( name, baudRate );
if( serial.isInitialized() ){
if(verbose) cout<<"[pdsp] serial connected to "<<name<<"\n";
startDaemon();
connected = true;
}else{
if(verbose) cout<<"[pdsp] failed serial connection to "<<name<<"\n";
}
}
void ofxPDSPSerialOut:: close(){
if(connected){
if(verbose) cout<<"[pdsp] shutting down serial out\n";
//stop the daemon before
closeDaemon();
if(serial.isInitialized()){
serial.close();
}
connected = false;
}
}
pdsp::ExtSequencer& ofxPDSPSerialOut::channel(int channelNumber) {
selectedChannel = channelNumber;
return *this;
}
void ofxPDSPSerialOut::linkToMessageBuffer(pdsp::MessageBuffer &messageBuffer) {
#ifndef NDEBUG
cout<<"[pdsp] linking message buffer\n";
#endif
inputs.push_back(&messageBuffer);
channels.push_back(selectedChannel);
}
void ofxPDSPSerialOut::unlinkMessageBuffer(pdsp::MessageBuffer &messageBuffer) {
int i=0;
for (vector<pdsp::MessageBuffer*>::iterator it = inputs.begin(); it != inputs.end(); ++it){
if (*it == &messageBuffer){
inputs.erase(it);
vector<int>::iterator linkedChannels = channels.begin() + i;
channels.erase(linkedChannels);
return;
}
i++;
}
}
void ofxPDSPSerialOut::prepareToPlay( int expectedBufferSize, double sampleRate ){
usecPerSample = 1000000.0 / sampleRate;
}
void ofxPDSPSerialOut::releaseResources() {}
// OK -----------------------------------------------^^^^^^^^^^^-------------
void ofxPDSPSerialOut::process( int bufferSize ) noexcept{
if(connected){
//clear messages
messagesToSend.clear();
//add note messages
int maxBuffer = inputs.size();
if(chronoStarted){
chrono::nanoseconds bufferOffset = chrono::nanoseconds (static_cast<long> ( bufferSize * usecPerSample ));
bufferChrono = bufferChrono + bufferOffset;
}else{
bufferChrono = chrono::high_resolution_clock::now();
chronoStarted = true;
}
for( int i=0; i<maxBuffer; ++i ){
pdsp::MessageBuffer* messageBuffer = inputs[i];
int msg_channel = channels[i];
/* // OLD WAY
bufferChrono = chrono::high_resolution_clock::now();
*/
int bufferMax = messageBuffer->size();
for(int n=0; n<bufferMax; ++n){
//format message to sent
float msg_value = messageBuffer->messages[n].value;
int msg_sample = messageBuffer->messages[n].sample;
chrono::nanoseconds offset = chrono::nanoseconds (static_cast<long> ( msg_sample * usecPerSample ));
chrono::high_resolution_clock::time_point scheduleTime = bufferChrono + offset;
messagesToSend.push_back( ScheduledSerialMessage(msg_channel, msg_value, scheduleTime) );
}
}
//sort messages to send
sort(messagesToSend.begin(), messagesToSend.end(), scheduledSort);
//send to daemon
if( ! messagesToSend.empty()){
prepareForDaemonAndNotify();
}
}//end checking connected
}
void ofxPDSPSerialOut::startDaemon(){ // OK
runDaemon = true;
daemonThread = thread( daemonFunctionWrapper, this );
}
void ofxPDSPSerialOut::prepareForDaemonAndNotify(){
unique_lock<mutex> lck (outMutex);
//send messages in circular buffer
for(ScheduledSerialMessage &msg : messagesToSend){
circularBuffer[circularWrite] = msg;
++circularWrite;
if(circularWrite==circularMax){
circularWrite = 0;
}
}
messagesReady = true;
outCondition.notify_all();
}
void ofxPDSPSerialOut::daemonFunctionWrapper(ofxPDSPSerialOut* parent){
parent->daemonFunction();
}
void ofxPDSPSerialOut::daemonFunction() noexcept{
while (runDaemon){
//midiMutex.lock();
unique_lock<mutex> lck (outMutex);
while(!messagesReady) outCondition.wait(lck);
if(circularRead != circularWrite){
ScheduledSerialMessage& nextMessage = circularBuffer[circularRead];
if( nextMessage.scheduledTime < chrono::high_resolution_clock::now() ){ //we have to process the scheduled midi
// SEND MESSAGES HERE
serial.writeByte( (char)nextMessage.channel );
serial.writeByte( (char)nextMessage.message );
#ifndef NDEBUG
if(verbose) cout << "[pdsp] serial message: channel = "<< (- (int)nextMessage.channel)<< " | value = "<<(int)nextMessage.message<<"\n";
#endif
++circularRead;
if(circularRead == circularMax){
circularRead = 0;
}
}
}else{
messagesReady = false;
}
this_thread::yield();
}
if(verbose) cout<<"[pdsp] closing serial out daemon thread\n";
}
void ofxPDSPSerialOut::closeDaemon(){
runDaemon = false;
unique_lock<mutex> lck (outMutex);
//set messages in circular buffer
messagesReady = true;
outCondition.notify_all();
daemonThread.detach();
}
#endif // __ANDROID__
#endif // TARGET_OF_IOS
|
2da6e8b968bc526f4a4cd3b0bd464d63d10aa33f | 7cce0635a50e8d2db92b7b1bf4ad49fc218fb0b8 | /施工界面程序20120307/Operation20120306/common/LineStruct.cpp | cbf874dfeb57fda3d7d735c124ef09f0157299d7 | [] | no_license | liquanhai/cxm-hitech-matrix428 | dcebcacea58123aabcd9541704b42b3491444220 | d06042a3de79379a77b0e4e276de42de3c1c6d23 | refs/heads/master | 2021-01-20T12:06:23.622153 | 2013-01-24T01:05:10 | 2013-01-24T01:05:10 | 54,619,320 | 2 | 2 | null | null | null | null | GB18030 | C++ | false | false | 1,410 | cpp | LineStruct.cpp | #include "stdafx.h"
#include "LineStruct.h"
CIPList::CIPList()
{
}
CIPList::~CIPList()
{
}
// 得到一个采集站IP地址
unsigned int CIPList::GetCollectIP(unsigned int uiLineNb, unsigned int uiPointNb, unsigned int uiChannelNb)
{
//测道号小于;测点号小于;测线号小于
return uiChannelNb + uiPointNb * 10 + uiLineNb * 1000000;
}
// 得到一个爆炸机IP地址
unsigned int CIPList::GetBlastMachineIP(unsigned int uiNb)
{
//20亿+ 爆炸机号
return uiNb + 2000000000;
}
// 得到一个辅助道IP地址
unsigned int CIPList::GetAuxIP(unsigned int uiNb)
{
//20亿+ 100 + 辅助道号
return uiNb + 2000000000 + 100;
}
// 得到当前主机的一个IP地址
DWORD CIPList::GetLocalIP()
{
char szhn[256];
int nStatus = gethostname(szhn, sizeof(szhn));
if (nStatus == SOCKET_ERROR )
{
return false;
}
struct addrinfo aiHints;
struct addrinfo *aiList = NULL;
memset(&aiHints, 0, sizeof(aiHints));
aiHints.ai_family = AF_INET;
if ((getaddrinfo(szhn, NULL, &aiHints, &aiList)) != 0)
{
return 0;
}
sockaddr_in *pAddr = (sockaddr_in*)(aiList->ai_addr);
do
{
if(pAddr->sin_addr.S_un.S_addr == 0x0100007f)
{
aiList = aiList->ai_next;
pAddr = (sockaddr_in*)(aiList->ai_addr);
}
else
{
return pAddr->sin_addr.S_un.S_addr;
}
} while (pAddr!=NULL);
return 0;
} |
d5120d20f59510eeaf70be7243b430540168ea2b | 904fdcf8cc2762b0d56c4fb399bd41f0be38741d | /adapt/adaptMsg.cpp | 03964c66ca7e3e2030afbeab1b9fc2302b436884 | [] | no_license | arunbali/acached | f4c9b7ba6e2c01ff512eda737d76f213b953ec32 | b42ee05d0096ad7c12e7bd5efd3aa638db0cad71 | refs/heads/master | 2020-06-02T00:40:42.568098 | 2012-08-19T08:05:29 | 2012-08-19T08:05:29 | 5,469,104 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,147 | cpp | adaptMsg.cpp | /*
* adaptMsg.cpp
*
* Created on: Mar 25, 2011
* Author: awara
*/
#include <iostream>
#include <list>
#include <pthread.h>
#include <assert.h>
#include "adaptlog.h"
#include <string.h>
#include <cstdlib>
#include "adaptMsg.h"
namespace _adapt_ {
adaptMsg::adaptMsg(int type) {
INFO(10, "MSG:(%p)Construct::Type:%d", this, type);
this->type = type;
this->pbuf = (char *) malloc(512);
assert(this->pbuf);
this->aMsgClear();
}
int adaptMsg::aMsgClear() {
this->portParent = NULL;
this->subtype = -1;
this->parent = NULL;
this->pbuf = (char *) memset(this->pbuf, 0, 512);
return 0;
}
adaptMsg::~adaptMsg() {
// TODO Auto-generated destructor stub
}
int adaptMsg::aMsgPrint() {
DBUG(ALOG_DALL,
"MSG:(%p)Type:%d Subtype:%d PortParent(%p)Parent(%p)", this, this->type, this->subtype, this->portParent, this->parent);
return 0;
}
adaptMsg * adaptMsg::aMsgGet() {
return (adaptMsg *) this;
}
void adaptMsg::aMsgSetportParent(void *ptr) {
this->portParent = ptr;
}
void *adaptMsg::aMsgGetportParent() {
return (this->portParent);
}
} /* namespace _adapt_ */
|
9cd73e813b7e4bee3d601e7b0c2ffbc8562fef24 | 515a28f08f58aaab7e277c90c7902c21bc8f4125 | /src/lipservice/DTFR/Card6/Nlmax.hpp | b442a1c9117bd286613444b9e00e64950b9ac258 | [
"BSD-2-Clause"
] | permissive | njoy/lipservice | e3bf4c8c07d79a46c13a88976f22ee07e416f4a6 | 1efa5e9452384a7bfc278fde57979c4d91e312c0 | refs/heads/master | 2023-08-04T11:01:04.411539 | 2021-01-20T22:24:17 | 2021-01-20T22:24:17 | 146,359,436 | 0 | 2 | NOASSERTION | 2023-07-25T19:41:10 | 2018-08-27T22:05:50 | C++ | UTF-8 | C++ | false | false | 373 | hpp | Nlmax.hpp | struct Nlmax {
using Value_t = int;
static std::string name(){ return "nlmax"; }
static std::string description(){
return
"nlmax is the number of Legendre neutron tables desired. That is,\n"
"it would be 4 for a P_3 set. nlmax must be > 0.";
}
static Value_t defaultValue(){ return 5; }
static bool verify( Value_t i ){ return 0 < i; }
};
|
8bc776fc794e0d456f83e12cb1c14fc502e62314 | 3d866d3a6c5844a55744092c906bfaab5468ad1a | /librest/include/parameter_pack.h | b03e27d5641977676592ca7ea8964230ee0397cd | [
"MIT"
] | permissive | adaigle/http-cpp | 8536763d2e3677ea581e9934899199be60b1bfa1 | 84139c95f02a6ccf9943f348fef09040027a52d8 | refs/heads/master | 2021-01-10T14:51:10.473520 | 2016-05-11T13:56:00 | 2016-05-11T13:56:00 | 53,694,797 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,741 | h | parameter_pack.h | #ifndef PARAMETER_PACK_H
#define PARAMETER_PACK_H
/// \brief Store a parameter pack as a single type to be applied later to another type.
/// \tparam Args The type to store in the parameter pack.
template <typename ...Args>
struct parameter_pack_type {
/// \brief Apply the stored types of parameter_pack_type to \p T
/// \tparam T The type to which to apply the parameter pack.
template <template<typename ...> class T>
struct apply {
using type = T<Args...>;
};
/// \brief Shorthand for apply<T>::type.
/// \tparam T The type to which to apply the parameter pack.
template <template<typename ...> class T>
using apply_t = typename apply<T>::type;
};
/// \brief Store a parameter pack as a single type to be applied later to another type.
/// \tparam FirstArg The type of the first argument stored in the parameter pack.
/// \tparam Args The type of the rest of the arguments in the parameter pack.
template <typename FirstArg, typename ...Args>
struct parameter_pack_type<FirstArg, Args...> {
/// \brief Apply the stored types of parameter_pack_type to \p T
/// \tparam T The type to which to apply the parameter pack.
template <template<typename ...> class T>
struct apply {
using type = T<FirstArg, Args...>;
};
/// \brief Shorthand for apply<T>::type.
/// \tparam T The type to which to apply the parameter pack.
template <template<typename ...> class T>
using apply_t = typename apply<T>::type;
/// \brief Apply the stored types of parameter_pack_type as a function pointer to \p T.
///
/// Takes the stored types Arg1, Arg2, ..., ArgN and create the type 'Arg1(Arg2, ..., ArgN)'.
using fn_type = FirstArg(Args...);
};
#endif
|
3c72a85be1534ec7301eb00aa0a1471e99cf1c4b | f8ff0df9f02654a0c6fcc223c78a203e9b76d9c9 | /LPC1768CookingTimer/coockingTimer.cpp | fdcf902f5703d3da4c14e591d7e83cbda79c0202 | [] | no_license | SmashKPI/Coocking-Timer | 87efd83af859bfc54b516aad135a8908d860f395 | d01951d583981057bcceb203248fe2b62b7270ae | refs/heads/main | 2023-03-04T21:54:51.301203 | 2021-02-20T22:59:02 | 2021-02-20T22:59:02 | 332,126,757 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,666 | cpp | coockingTimer.cpp | /*******************************************************************************
Name: CookingTimer.cpp
Author: DTsebrii
Date: 02/18/2021
Description: A project to read an user input, convert adc value to a specific
time, and wait for it. The end of a timer will be signilized with a enabled
buzzer.
Used pins:
Serial communication - USBTX and USBRX (Made for troubleshooting)
Potentiometer - Pin 15(Analog IN)
Push button - Pin 16 (InterruptIn)
LED - LED1
Buzzer - Pin 17 (Digital OUT)
*******************************************************************************/
/// LIBRARIES //////////////////////////////////////////////////////////////////
#include "mbed.h"
#include "platform/mbed_thread.h"
#include "Timer.h"
/// CONSTANTS //////////////////////////////////////////////////////////////////
#define TRUE 1
#define FALSE 0
#define SEC 60
#define MIN 60
#define DAY 24 // Added for future use
#define BAUD 9600 // Default baudrate
/// PINS ///////////////////////////////////////////////////////////////////////
Timer timer; // Time counter
Serial pc(USBTX, USBRX, BAUD);
DigitalOut buzzer(p17);
DigitalOut led(LED1);
AnalogIn adc(p15); // ADC pin to read an user input
InterruptIn button(p16); // Works as soon as decission is made
/// GLOBAL VARIABLES ///////////////////////////////////////////////////////////
volatile char decisionFlag = FALSE; // Checks either user presses pushbotton
typedef struct tmr
{
float timeLim; // Var to save the alarm time
float currTime; // Var to save the current time
char sec; // Secundo Counter
char min; // Minute Counter
char hour; // Hour Counter
char buzzState; // Buzzer controller
} tmr_t;
tmr_t alarmClock;
/// FUNCTIONS //////////////////////////////////////////////////////////////////
/*******************************************************************************
Name: initTMR
Author: DTsebrii
Date: 02/20/2021
Input: tptr - tmr_t object pointer
Output: None
Description: Initialize the timer object
*******************************************************************************/
void initTMR(tmr_t* tptr)
{
tptr->timeLim = FALSE;
tptr->currTime = FALSE;
tptr->sec = FALSE;
tptr->min = FALSE;
tptr->hour = FALSE;
tptr->buzzState = FALSE;
} // eo initTMR::
/*******************************************************************************
Name: initSys
Author: DTsebrii
Date: 02/20/2021
Input: None
Output: None
Description: Invoke all system configuration functions within the main ruitine
*******************************************************************************/
void initSys()
{
timer.start();
initTMR(&alarmClock);
} // eo initSys::
/*******************************************************************************
Name: pbPressed
Author: DTsebrii
Date: 02/20/2021
Input: None
Output: None
Description: ISR that occurs during a PB press. It handles the following
procedures:
Controlls the buzzer state
Controlls the decisionFlag state
*******************************************************************************/
void pbPressed()
{
if(alarmClock.buzzState)
{
initTMR(&alarmClock); // Reinitialize the timer parameters
buzzer = FALSE;
}
decisionFlag = !decisionFlag;
} // eo pbPressed::
/*******************************************************************************
Name: countTime
Author: DTsebrii
Date: 02/20/2021
Input: None
Output: None
Description: Function to controll the time flow
*******************************************************************************/
void countTime(tmr_t* tptr)
{
led = FALSE;
tptr->sec++;
if(tptr->sec >= SEC)
{
tptr->sec = 0;
tptr->min++;
}
if(tptr->min >= MIN)
{
tptr->min = 0;
tptr->hour >= DAY ? tptr->hour = 0: tptr->hour++;
}
tptr->currTime = tptr->min;
tptr->currTime += (float)tptr->sec/100;
if(tptr->currTime >= tptr->timeLim) tptr->buzzState = TRUE;
buzzer = tptr->buzzState;
} // eo countTime::
/*******************************************************************************
Name: readTime
Author: DTsebrii
Date: 02/20/2021
Input: None
Output: None
Description: Function to read and interpret the ADC value
*******************************************************************************/
void readTime()
{
float floatPoint = 0;
led = TRUE;
alarmClock.timeLim = (int)(adc*MIN);
floatPoint = adc*MIN - (int)(adc*MIN);
floatPoint *= SEC;
floatPoint = floatPoint/100;
alarmClock.timeLim += floatPoint; // Geting a sec part
} // eo readTime
/*******************************************************************************
Name: display
Author: DTsebrii
Date: 02/20/2021
Input: None
Output: None
Description: Function to dsipplay all variables. Needed for debuging. Should
be commented during normal program work
*******************************************************************************/
void display(){
float adcVal = adc*MIN;
pc.printf("\033[2J\033[1;0HThe Clock Parameters...\n");
pc.printf("\033[2;0HClock is in the following format MM:SS\n");
pc.printf("\033[3;0HClock Counter:\t%02d:%02d\n", alarmClock.min, alarmClock.sec);
pc.printf("\033[4;0HReal ADC Value:\t%f\n", adcVal);
pc,printf("\033[5;0HTime to wait:\t%f\n", alarmClock.timeLim);
pc.printf("\033[6;0HTime value:\t%f", alarmClock.currTime);
pc.printf("\033[7;0HBuzzer State:\t%d\n", alarmClock.buzzState);
pc.printf("\033[8;0HDecisionFlag:\t%d\n", decisionFlag);
} // eo display::
int main()
{
initSys();
button.rise(&pbPressed);
while (TRUE) {
if(timer >= 1.0)
{
display();
timer.reset();
if(decisionFlag)
{
countTime(&alarmClock);
}
else
{
readTime();
}
}
}
}
|
e3c1af1c63245981c29c7405193c1f501a383f7c | d1e1cd394b694d9c7ca656e29e8e85f6a1ef54e4 | /cc/transaction.hpp | 8c4da86216a3363eacc0610976619ef1394c7c88 | [] | no_license | jnmt/toy | a00e56afac8078061bab1ba23c3d8ebcc26f731b | f7ca4c0e0f1fde6cb4acb9537bc12b00f111a18f | refs/heads/master | 2021-11-28T19:26:50.671130 | 2021-11-14T00:45:57 | 2021-11-14T00:45:57 | 194,046,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,983 | hpp | transaction.hpp | #pragma once
#include <vector>
#include <boost/format.hpp>
#include <boost/thread.hpp>
#include "common.hpp"
#define TX_INPROGRESS 0
#define TX_ABORT 1
#define TX_COMMIT 2
class Transaction {
private:
virtual void begin() = 0;
virtual void commit() = 0;
virtual void abort() = 0;
virtual void read(Operation *op) = 0;
virtual void write(Operation *op) = 0;
public:
virtual void execute(const boost::thread::id tid) = 0;
virtual void generateOperations(int numOperations, int readRatio) = 0;
};
class BaseTransaction : Transaction {
protected:
int status;
boost::thread::id threadId;
std::vector<Operation*> operations;
std::map<int,Record*> readSet;
std::map<int,Record*> writeSet;
void begin();
void commit();
void abort();
void read(Operation *op);
void write(Operation *op);
std::vector<Operation*> getOperations();
Record* searchReadSet(int key);
Record* searchWriteSet(int key);
void eraseFromReadSet(int key);
void eraseFromWriteSet(int key);
Record* getRecord(int key);
void debug(boost::format fmt);
public:
BaseTransaction();
~BaseTransaction();
void execute(const boost::thread::id tid);
void generateOperations(int numOperations, int readRatio);
};
class Ss2plTransaction : BaseTransaction {
private:
std::vector<boost::upgrade_mutex*> readLocks;
std::vector<boost::upgrade_mutex*> writeLocks;
void begin();
void commit();
void abort();
void read(Operation *op);
void write(Operation *op);
void eraseFromReadLocks(boost::upgrade_mutex* m);
void releaseLock();
public:
int status;
Ss2plTransaction();
~Ss2plTransaction();
void execute(const boost::thread::id tid);
};
class OccTransaction : BaseTransaction {
private:
int startTxId;
void begin();
void commit();
void abort();
void read(Operation *op);
void write(Operation *op);
bool validate();
void gc();
public:
int status;
OccTransaction();
~OccTransaction();
void execute(const boost::thread::id tid);
};
|
3cb63bc6e8d2ec3193e4b4bed5e06cd6f4f155a2 | 8ecbcd850fd4bc098bbd5a8be3b0efd2d1706c2c | /src/Master/Audio/Audio.h | 99845c1422d651afeb3d3709ec70bfafe2525d79 | [] | no_license | xivitazo/Driver | 1e137a35ce02cd86c7c951b8024041c7030a171a | 1c750067a188f0958ce8f66b618576563d60ad6b | refs/heads/master | 2023-04-13T16:04:36.469521 | 2021-04-21T12:24:37 | 2021-04-21T12:24:37 | 210,957,057 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 701 | h | Audio.h | #ifndef AUDIO_H
#define AUDIO_H
#include "Modulos/AudioMod.h"
#include "conexion.h"
class Audio
{
int ninputs, noutputs;
//Los módulos empiezan a partir del 2, el 0 son las entradas y el 1 las salidas
std::vector <AudioMod *> modulos;
ofSoundBuffer output;
//std::vector <int [2] > inputlink;
std::vector <Conexion *> conexiones;
bool conexionesListas();
public:
Audio(int ninputs, int noutputs);
~Audio();
int processInput(ofSoundBuffer & input);
int getOutput(ofSoundBuffer& output);
int addModulo (AudioMod *modulo);
int addConexion(int input[2], int output[2]);
AudioMod* getModulo(int pos);
bool isOutReady();
};
#endif // AUDIO_H
|
bf05a0f8f524ce57ebb5fd7785353b348e1735af | f1b5bfb65d6b2b7fc4fb49fc2d7999c707e1214f | /Source/Arbiter/Core/Memory/AlignedMemory.hpp | 8bbbf0ee87133f12910a1c5751dfb4b21983f761 | [
"BSD-3-Clause"
] | permissive | cookieniffler/Arbiter | 68ef41c5c055406018dea8d986a44cb5525e24a7 | 271fe56cb9379d9c76704e028e07dfdb9693bd54 | refs/heads/master | 2020-05-27T09:32:45.198703 | 2019-08-06T15:17:28 | 2019-08-06T15:17:28 | 188,567,087 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 302 | hpp | AlignedMemory.hpp | #pragma once
#ifndef __ALIGNEDMEMORY_HPP__
#define __ALIGNEDMEMORY_HPP__
#include <Arbiter/Core/Common/Base.hpp>
ARBITER_NAMESPACE_BEGIN
class AlignedMemory
{
private:
protected:
public:
AlignedMemory();
virtual ~AlignedMemory();
};
ARBITER_NAMESPACE_END
#endif // __ALIGNEDMEMORY_HPP__
|
f8a6cec890403ee96773750e71dce71478594d66 | 843151e566c8cef0cc24c7a185ea95ab68ad4083 | /doc/examples/xray_monolayer/30mN/molgroups.cc | e10bc411411e982b34b2d745e1eab2df75feddf4 | [] | no_license | reflectometry/cspace | ee1c23f2133ab7d9f3dbcd4b9aa3b474e2a7b070 | f6d46c08a339fbfd1ddcc7071ae7fef938a51a0a | refs/heads/master | 2020-06-05T09:14:07.776101 | 2014-12-10T20:17:19 | 2014-12-10T20:17:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 143,830 | cc | molgroups.cc | /*
* molgroups.cc
* Gauss
*
* Created by Frank Heinrich on 27/10/08.
* updated 9-May-2012
* Copyright 2008 __MyCompanyName__. All rights reserved.
*
*/
#include "molgroups.h"
#include "stdio.h"
#include "stdlib.h"
//------------------------------------------------------------------------------------------------------
//Parent Object Implementation
nSLDObj::nSLDObj()
{
bWrapping=true;
absorb=0;
};
nSLDObj::~nSLDObj(){};
double nSLDObj::fnGetAbsorb(double z){return absorb;};
void nSLDObj::fnWriteData2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
double dLowerLimit, dUpperLimit, d, dmirror, dAreaInc, dnSLDInc;
int i;
fprintf(fp, "z%s a%s nsl%s \n",cName, cName, cName);
dLowerLimit=fnGetLowerLimit();
dUpperLimit=fnGetUpperLimit();
d=floor(dLowerLimit/stepsize+0.5)*stepsize;
for (i=0; i<dimension; i++)
{
d=double(i)*stepsize;
dmirror=d-float(2*i)*stepsize;
if ((bWrapping==true) && (dmirror>=dLowerLimit))
{
dAreaInc=fnGetArea(d)+fnGetArea(dmirror);
dnSLDInc=(fnGetnSLD(d)*fnGetArea(d)+fnGetnSLD(dmirror)*fnGetArea(dmirror))/(fnGetArea(d)+fnGetArea(dmirror));
}
else
{
dAreaInc=fnGetArea(d);
dnSLDInc=fnGetnSLD(d);
//printf("Bin %i Area %f nSLD %e nSL %e \n", i, dAreaInc, fnGetnSLD(d), fnGetnSLD(d)*dAreaInc*stepsize);
}
fprintf(fp, "%lf %lf %e \n", d, dAreaInc, dnSLDInc*dAreaInc*stepsize);
};
fprintf(fp, "\n");
}
//Philosophy for this first method: You simply add more and more volume and nSLD to the
//volume and nSLD array. After all objects have filled up those arrays the maximal area is
//determined which is the area per molecule and unfilled volume is filled with bulk solvent.
//Hopefully the fit algorithm finds a physically meaningful solution. There has to be a global
//hydration paramter for the bilayer.
//Returns maximum area
double nSLDObj::fnWriteProfile(double aArea[], double anSL[], int dimension, double stepsize, double dMaxArea)
{
double dLowerLimit, dUpperLimit, d, dAreaInc, dprefactor;
int i;
dLowerLimit=fnGetLowerLimit();
dUpperLimit=fnGetUpperLimit();
if (dUpperLimit==0)
{
dUpperLimit=double(dimension)*stepsize;
}
d=floor(dLowerLimit/stepsize+0.5)*stepsize;
while (d<=dUpperLimit)
{
i=int(d/stepsize);
dprefactor=1;
//printf("Here we are %i, dimension %i \n", i, dimension);
if ((i<0) && (bWrapping==true)) {i=-1*i;};
if ((i==0) && (bWrapping==true)) {dprefactor=2;} //avoid too low filling when mirroring
if ((i>=0) && (i<dimension))
{
dAreaInc=fnGetArea(d);
aArea[i]=aArea[i]+dAreaInc*dprefactor;
if (aArea[i]>dMaxArea) {dMaxArea=aArea[i];};
anSL[i]=anSL[i]+fnGetnSLD(d)*dAreaInc*stepsize*dprefactor;
//printf("Bin %i Area %f total %f nSL %f total %f \n", i, dAreaInc, aArea[i], fnGetnSLD(d)*dAreaInc*stepsize, anSL[i]);
}
d=d+stepsize;
};
return dMaxArea;
};
double nSLDObj::fnWriteProfile(double aArea[], double anSL[], double aAbsorb[], int dimension, double stepsize, double dMaxArea)
{
double dLowerLimit, dUpperLimit, d, dAreaInc, dprefactor;
int i;
dLowerLimit=fnGetLowerLimit();
dUpperLimit=fnGetUpperLimit();
if (dUpperLimit==0)
{
dUpperLimit=double(dimension)*stepsize;
}
d=floor(dLowerLimit/stepsize+0.5)*stepsize;
while (d<=dUpperLimit)
{
i=int(d/stepsize);
dprefactor=1;
//printf("Here we are %i, dimension %i \n", i, dimension);
if ((i<0) && (bWrapping==true)) {i=-1*i;};
if ((i==0) && (bWrapping==true)) {dprefactor=2;} //avoid too low filling when mirroring
if ((i>=0) && (i<dimension))
{
//printf("Bin %i Areainc %f area now %f nSLD %g Absorbinc %g Absorb now %g nSLinc %g nSL now %g \n", i, dAreaInc, aArea[i], fnGetnSLD(d), aAbsorb[i], fnGetAbsorb(d)*dAreaInc*stepsize, fnGetnSLD(d)*dAreaInc*stepsize, anSL[i]);
dAreaInc=fnGetArea(d);
aArea[i]=aArea[i]+dAreaInc*dprefactor;
if (aArea[i]>dMaxArea) {dMaxArea=aArea[i];};
anSL[i]=anSL[i]+fnGetnSLD(d)*dAreaInc*stepsize*dprefactor;
aAbsorb[i]=aAbsorb[i]+fnGetAbsorb(d)*dAreaInc*stepsize*dprefactor;
//printf("Bin %i Area %f total %f nSL %f total %f \n", i, dAreaInc, aArea[i], fnGetnSLD(d)*dAreaInc*stepsize, anSL[i]);
}
d=d+stepsize;
};
return dMaxArea;
};
void nSLDObj::fnOverlayProfile(double aArea[], double anSL[], int dimension, double stepsize, double dMaxArea)
{
double dLowerLimit, dUpperLimit, d, dAreaInc, dprefactor, temparea;
int i;
dLowerLimit=fnGetLowerLimit();
dUpperLimit=fnGetUpperLimit();
if (dUpperLimit==0)
{
dUpperLimit=double(dimension)*stepsize;
}
d=floor(dLowerLimit/stepsize+0.5)*stepsize;
while (d<=dUpperLimit)
{
i=int(d/stepsize);
dprefactor=1;
//printf("Here we are %i, dimension %i, maxarea %f \n", i, dimension, dMaxArea);
if ((i<0) && (bWrapping==true)) {i=-1*i;};
if ((i==0) && (bWrapping==true)) {dprefactor=2;} //avoid too low filling when mirroring
if ((i>=0) && (i<dimension))
{
dAreaInc=fnGetArea(d);
temparea=dAreaInc*dprefactor+aArea[i];
if (temparea>dMaxArea) {
//printf("Bin %i Areainc %f area now %f nSLD %g nSLinc %g nSL now %g \n", i, dAreaInc, aArea[i], fnGetnSLD(d), fnGetnSLD(d)*dAreaInc*stepsize, anSL[i]);
anSL[i]=anSL[i]*(1-((temparea-dMaxArea)/aArea[i])); //eliminate the overfilled portion using original content
anSL[i]=anSL[i]+fnGetnSLD(d)*dAreaInc*stepsize*dprefactor;
aArea[i]=dMaxArea;
}
else {
aArea[i]=aArea[i]+dAreaInc*dprefactor;
anSL[i]=anSL[i]+fnGetnSLD(d)*dAreaInc*stepsize*dprefactor;
}
}
d=d+stepsize;
};
};
void nSLDObj::fnOverlayProfile(double aArea[], double anSL[], double aAbsorb[], int dimension, double stepsize, double dMaxArea)
{
double dLowerLimit, dUpperLimit, d, dAreaInc, dprefactor, temparea;
int i;
dLowerLimit=fnGetLowerLimit();
dUpperLimit=fnGetUpperLimit();
if (dUpperLimit==0)
{
dUpperLimit=double(dimension)*stepsize;
}
d=floor(dLowerLimit/stepsize+0.5)*stepsize;
while (d<=dUpperLimit)
{
i=int(d/stepsize);
dprefactor=1;
//printf("Here we are %i, dimension %i, maxarea %f \n", i, dimension, dMaxArea);
if ((i<0) && (bWrapping==true)) {i=-1*i;};
if ((i==0) && (bWrapping==true)) {dprefactor=2;} //avoid too low filling when mirroring
if ((i>=0) && (i<dimension))
{
dAreaInc=fnGetArea(d);
temparea=dAreaInc*dprefactor+aArea[i];
if (temparea>dMaxArea) {
//printf("Bin %i Areainc %f area now %f nSLD %g Absorbinc %g Absorb now %g nSLinc %g nSL now %g \n", i, dAreaInc, aArea[i], fnGetnSLD(d), aAbsorb[i], fnGetAbsorb(d)*dAreaInc*stepsize, fnGetnSLD(d)*dAreaInc*stepsize, anSL[i]);
anSL[i]=anSL[i]*(1-((temparea-dMaxArea)/aArea[i])); //eliminate the overfilled portion using original content
anSL[i]=anSL[i]+fnGetnSLD(d)*dAreaInc*stepsize*dprefactor;
aAbsorb[i]=aAbsorb[i]*(1-((temparea-dMaxArea)/aArea[i])); //eliminate the overfilled portion using original content
aAbsorb[i]=aAbsorb[i]+fnGetAbsorb(d)*dAreaInc*stepsize*dprefactor;
aArea[i]=dMaxArea;
}
else {
//printf("Bin %i Areainc %f area now %f nSLD %g Absorbinc %g Absorb now %g nSLinc %g nSL now %g \n", i, dAreaInc, aArea[i], fnGetnSLD(d), aAbsorb[i], fnGetAbsorb(d)*dAreaInc*stepsize, fnGetnSLD(d)*dAreaInc*stepsize, anSL[i]);
aArea[i]=aArea[i]+dAreaInc*dprefactor;
anSL[i]=anSL[i]+fnGetnSLD(d)*dAreaInc*stepsize*dprefactor;
aAbsorb[i]=aAbsorb[i]+fnGetAbsorb(d)*dAreaInc*stepsize*dprefactor;
}
}
d=d+stepsize;
};
};
//------------------------------------------------------------------------------------------------------
//Function Object Implementation
//------------------------------------------------------------------------------------------------------
BoxErr::BoxErr(double dz, double dsigma, double dlength, double dvolume, double dnSL, double dnumberfraction=1)
{
z=dz; sigma=dsigma; l=dlength, vol=dvolume, nSL=dnSL, nf=dnumberfraction;
};
BoxErr::~BoxErr(){};
//Gaussian function definition, integral is volume, return value is area at position z
double BoxErr::fnGetArea(double dz) {
return (vol/l)*0.5*(erf((dz-z+0.5*l)/sqrt(2)/sigma)-erf((dz-z-0.5*l)/sqrt(2)/sigma))*nf;
};
//constant nSLD
double BoxErr::fnGetnSLD(double dz) {return nSL/vol;};
//Gaussians are cut off below and above 3 sigma
double BoxErr::fnGetLowerLimit() {return z-0.5*l-3*sigma;};
double BoxErr::fnGetUpperLimit() {return z+0.5*l+3*sigma;};
void BoxErr::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
fprintf(fp, "BoxErr %s z %lf sigma %lf l %lf vol %lf nSL %e nf %lf \n",cName, z, sigma, l, vol, nSL, nf);
nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
}
//------------------------------------------------------------------------------------------------------
Box2Err::Box2Err(double dz, double dsigma1, double dsigma2, double dlength, double dvolume, double dnSL, double dnumberfraction=1)
{
z=dz; sigma1=dsigma1; sigma2=dsigma2; l=dlength, vol=dvolume, nSL=dnSL, nf=dnumberfraction;
};
Box2Err::~Box2Err(){};
//Gaussian function definition, integral is volume, return value is area at position z
double Box2Err::fnGetArea(double dz) {
return (vol/l)*0.5*(erf((dz-z+0.5*l)/sqrt(2)/sigma1)-erf((dz-z-0.5*l)/sqrt(2)/sigma2))*nf;
};
//constant nSLD
double Box2Err::fnGetnSLD(double dz) {return nSL/vol;};
//Gaussians are cut off below and above 3 sigma
double Box2Err::fnGetLowerLimit() {return z-0.5*l-3*sigma1;};
double Box2Err::fnGetUpperLimit() {return z+0.5*l+3*sigma2;};
void Box2Err::fnSetSigma(double sigma)
{
sigma1=sigma;
sigma2=sigma;
}
void Box2Err::fnSetSigma(double dsigma1, double dsigma2)
{
sigma1=dsigma1;
sigma2=dsigma2;
}
void Box2Err::fnSetZ(double dz)
{
z=dz;
};
void Box2Err::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
fprintf(fp, "Box2Err %s z %lf sigma1 %lf sigma2 %lf l %lf vol %lf nSL %e nf %lf \n",cName, z, sigma1, sigma2, l, vol, nSL, nf);
nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
}
//------------------------------------------------------------------------------------------------------
Gaussian::Gaussian(double dz, double dsigma, double dvolume, double dnSL, double dnumberfraction=1)
{
z=dz; sigma=dsigma; vol=dvolume, nSL=dnSL, nf=dnumberfraction;
};
Gaussian::~Gaussian(){};
//Gaussian function definition, integral is volume, return value is area at position z
double Gaussian::fnGetArea(double dz) {return (vol/sqrt(2*3.141592654)/sigma)*exp(-0.5*(z-dz)*(z-dz)/sigma/sigma)*nf;};
//constant nSLD
double Gaussian::fnGetnSLD(double dz) {return nSL/vol;};
//Gaussians are cut off below and above 3 sigma
double Gaussian::fnGetLowerLimit() {return z-3*sigma;};
double Gaussian::fnGetUpperLimit() {return z+3*sigma;};
void Gaussian::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
fprintf(fp, "Gaussian %s z %lf sigma %lf vol %lf nSL %e nf %lf \n",cName, z, sigma, vol, nSL, nf);
nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
}
//------------------------------------------------------------------------------------------------------
Parabolic::Parabolic(double dC, double dH, double dn, double dnSLD, double dnumberfraction=1)
{
C=dC; H=dH, n=dn, nSLD=dnSLD, nf=dnumberfraction;
bWrapping=false;
};
Parabolic::~Parabolic(){};
//Gaussian function definition, integral is volume, return value is area at position z
double Parabolic::fnGetArea(double dz) {
if (dz<H) {return C*(1-pow(dz/H,n))*nf;}
else {return 0;}
};
//constant nSLD
double Parabolic::fnGetnSLD(double dz) {return nSLD;};
//Gaussians are cut off below and above 3 sigma
double Parabolic::fnGetLowerLimit() {return 0;};
double Parabolic::fnGetUpperLimit() {return 0;};
void Parabolic::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
fprintf(fp, "Parabolic %s C %lf H %lf n %lf nSLD %e nf %lf \n",cName, C, H, n, nSLD, nf);
nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
}
//------------------------------------------------------------------------------------------------------
StretchGaussian::StretchGaussian(double dz, double dsigma, double dlength, double dvolume, double dnSL, double dnumberfraction=1)
{
z=dz; sigma=dsigma; l=dlength, vol=dvolume, nSL=dnSL, nf=dnumberfraction;
};
StretchGaussian::~StretchGaussian(){};
//Gaussian function definition, integral is volume, return value is area at position z
double StretchGaussian::fnGetArea(double dz) {
double returnvalue;
double temp, dvgauss;
temp=sqrt(2*3.141592654)*sigma;
dvgauss=vol/(1+l/temp);
if (dz<(z-0.5*l))
{
returnvalue=dvgauss/temp*exp(-0.5*(z-dz-0.5*l)*(z-dz-0.5*l)/sigma*sigma)*nf;
}
else if ((dz>=(z-0.5*l)) && (dz<=(z+0.5*l)))
{
returnvalue=dvgauss/temp*nf;
}
else
{
returnvalue=dvgauss/temp*exp(-0.5*(dz-z-0.5*l)*(dz-z-0.5*l)/sigma*sigma)*nf;
}
return returnvalue;
};
//constant nSLD
double StretchGaussian::fnGetnSLD(double dz) {return nSL/vol;};
//Gaussians are cut off below and above 3 sigma
double StretchGaussian::fnGetLowerLimit() {return z-0.5*l-3*sigma;};
double StretchGaussian::fnGetUpperLimit() {return z+0.5*l+3*sigma;};
void StretchGaussian::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
fprintf(fp, "Gaussian %s z %lf sigma %lf l %lf vol %lf nSL %e nf %lf \n",cName, z, sigma, l, vol, nSL, nf);
nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
}
//------------------------------------------------------------------------------------------------------
// Combined Object Implementation
//------------------------------------------------------------------------------------------------------
PC::PC()
{
cg = new Box2Err(0,0,0,0,0,0,1);
phosphate = new Box2Err(0,0,0,0,0,0,1);
choline = new Box2Err(0,0,0,0,0,0,1);
cg->l=4.21; phosphate->l=3.86; choline->l=6.34; //from fit to Feller data
cg->sigma1=2.53; cg->sigma2=2.29;
phosphate->sigma1=2.29; phosphate->sigma2=2.02;
choline->sigma1=2.02; choline->sigma2=2.26;
//from fit to Feller data
l=9.575; //group cg phosphate choline
//z 15.00 18.44 19.30
//l 4.21 3.86 6.34
cg->vol=147; phosphate->vol=54; choline->vol=120; //nominal values
cg->nSL=3.7755e-4; phosphate->nSL=2.8350e-4; choline->nSL=-6.0930e-5;
cg->nf=1; phosphate->nf=1; choline->nf=1;
fnAdjustParameters();
};
PC::~PC(){
delete cg;
delete phosphate;
delete choline;
};
void PC::fnAdjustParameters(){
cg->z=z-0.5*l+0.5*cg->l; phosphate->z=z-0.5*l+cg->l+0.5*phosphate->l;
choline->z=z+0.5*l-0.5*choline->l;
};
//Return value is area at position z
double PC::fnGetArea(double dz) {
return (cg->fnGetArea(dz)+phosphate->fnGetArea(dz)+choline->fnGetArea(dz))*nf;
};
//get nSLD from molecular subgroups
double PC::fnGetnSLD(double dz) {
double cgarea, pharea, charea, sum;
cgarea=cg->fnGetArea(dz);
pharea=phosphate->fnGetArea(dz);
charea=choline->fnGetArea(dz);
sum=cgarea+pharea+charea;
if (sum==0) {return 0;}
else {
return (cg->fnGetnSLD(dz)*cgarea+
phosphate->fnGetnSLD(dz)*pharea+
choline->fnGetnSLD(dz)*charea)/sum;
}
};
//Use limits of molecular subgroups
double PC::fnGetLowerLimit() {return cg->fnGetLowerLimit();};
double PC::fnGetUpperLimit() {return choline->fnGetUpperLimit();};
void PC::fnSetSigma(double sigma)
{
cg->sigma1=sigma;
cg->sigma2=sigma;
phosphate->sigma1=sigma;
phosphate->sigma2=sigma;
choline->sigma1=sigma;
choline->sigma2=sigma;
};
void PC::fnSetZ(double dz){
z=dz;
fnAdjustParameters();
};
void PC::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
//char *str = new char[80];
fprintf(fp, "PC %s z %lf l %lf nf %lf \n",cName, z, l, nf);
nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
//cg->fnWritePar2File(fp, "cg", dimension, stepsize);
//phosphate->fnWritePar2File(fp, "phosphate", dimension, stepsize);
//choline->fnWritePar2File(fp, "choline", dimension, stepsize);
//delete []str;
}
//------------------------------------------------------------------------------------------------------
PCm::PCm()
{
cg->sigma2=2.53; cg->sigma1=2.29; //from fit to Feller data
phosphate->sigma2=2.29; phosphate->sigma1=2.02;
choline->sigma2=2.02; choline->sigma1=2.26;
fnAdjustParameters();
};
PCm::~PCm() {};
void PCm::fnAdjustParameters(){
cg->z=z+0.5*l-0.5*cg->l; phosphate->z=z+0.5*l-cg->l-0.5*phosphate->l;
choline->z=z-0.5*l+0.5*choline->l;
};
//Use limits of molecular subgroups
double PCm::fnGetLowerLimit() {return cg->fnGetLowerLimit();};
double PCm::fnGetUpperLimit() {return choline->fnGetUpperLimit();};
void PCm::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
//char *str = new char[80];
fprintf(fp, "PCm %s z %lf l %lf nf %lf \n",cName, z, l, nf);
nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
//cg->fnWritePar2File(fp, "cg_m", dimension, stepsize);
//phosphate->fnWritePar2File(fp, "phosphate_m", dimension, stepsize);
//choline->fnWritePar2File(fp, "choline_m", dimension, stepsize);
//delete []str;
}
//-----------------------------------------------------------------------------------------------------------
//Amino Acids
//-----------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
//general implementation
//-----------------------------------------------------------------------------------------------------------
//ExchangeRatio is not yet fully implemented
AminoAcid::AminoAcid()
{
ExchangeRatio=0;
Deuterated=0;
}
double AminoAcid::fnGetnSLD(double z)
{
double temp;
if (Deuterated==1) {temp=1;}
else {temp=0.;}
//correct for deuterated residues
return (nSL-temp*float(nH)*(-3.741e-5)+temp*float(nH)*(6.674e-5))/vol;
}
//-----------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
//Specific implementations
//-----------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------
AA_Lys::AA_Lys()
{
nSL=1.5660e-4;
vol=171.3;
nH=13;
nExch=4;
}
AA_Arg::AA_Arg()
{
nSL=3.4260e-4;
vol=202.1;
nH=13;
nExch=6;
}
AA_His::AA_His()
{
nSL=4.7406e-4;
vol=167.3;
nH=7;
nExch=3;
}
AA_Asn::AA_Asn()
{
nSL=3.4356e-4;
vol=135.2;
nH=6;
nExch=3;
}
AA_Asp::AA_Asp()
{
nSL=3.8343e-4;
vol=124.5;
nH=4;
nExch=1;
}
AA_Cys::AA_Cys()
{
nSL=1.9191e-4;
vol=105.6;
nH=5;
nExch=1;
}
AA_Thr::AA_Thr()
{
nSL=2.1315e-4;
vol=122.1;
nH=7;
nExch=2;
}
AA_Ser::AA_Ser()
{
nSL=2.2149e-4;
vol=99.1;
nH=5;
nExch=2;
}
AA_Gln::AA_Gln()
{
nSL=3.3522e-4;
vol=161.1;
nH=8;
nExch=3;
}
AA_Glu::AA_Glu()
{
nSL=3.7509e-4;
vol=155.1;
nH=6;
nExch=1;
}
AA_Pro::AA_Pro()
{
nSL=2.2158e-4;
vol=129.3;
nH=7;
nExch=0;
}
AA_Gly::AA_Gly()
{
nSL=1.7178e-4;
vol=66.4;
nH=3;
nExch=1;
}
AA_Ala::AA_Ala()
{
nSL=1.6344e-4;
vol=91.5;
nH=5;
nExch=1;
}
AA_Val::AA_Val()
{
nSL=1.4676e-4;
vol=141.7;
nH=9;
nExch=1;
}
AA_Ile::AA_Ile()
{
nSL=1.3842e-4;
vol=168.8;
nH=11;
nExch=1;
}
AA_Leu::AA_Leu()
{
nSL=1.3842e-4;
vol=167.9;
nH=11;
nExch=1;
}
AA_Met::AA_Met()
{
nSL=1.7523e-4;
vol=170.8;
nH=9;
nExch=1;
}
AA_Tyr::AA_Tyr()
{
nSL=4.7073e-4;
vol=203.6;
nH=9;
nExch=2;
}
AA_Phe::AA_Phe()
{
nSL=4.1268e-4;
vol=203.4;
nH=9;
nExch=1;
}
AA_Trp::AA_Trp()
{
nSL=6.0123e-4;
vol=237.6;
nH=10;
nExch=2;
}
//------------------------------------------------------------------------------------------------------
// Monolayer - single PC lipid
//------------------------------------------------------------------------------------------------------
Monolayer::Monolayer(){
substrate = new Box2Err();
lipid = new Box2Err();
methyl = new Box2Err();
substrate->l=20;
substrate->z=10;
substrate->nf=1;
substrate->sigma1=2.0;
rho_substrate=0;
absorb_substrate=0;
volacyllipid=925; //DOPC
nslacyllipid=-2.67e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
hc_substitution=0.;
//fnAdjustParameters();
};
Monolayer::~Monolayer(){
delete substrate;
delete lipid;
delete methyl;
};
void Monolayer::fnAdjustParameters(){
double l_hc;
double V_hc;
double nf_hc_lipid, nSL_hc, absorb_hc;
double c_s_hc, c_A_hc, c_V_hc;
double l_m;
double V_m;
double nf_m_lipid, nSL_m, absorb_m;
double c_s_m, c_A_m, c_V_m;
//set all sigma
fnSetSigma(sigma);
methyl->sigma1=global_rough;
substrate->sigma2=global_rough;
//outer hydrocarbons
l_hc=l_lipid;
nf_hc_lipid=1;
V_hc=nf_hc_lipid*(volacyllipid-volmethyllipid);
nSL_hc=nf_hc_lipid*(nslacyllipid-nslmethyllipid);
absorb_hc=nf_hc_lipid*(absorbacyllipid-absorbmethyllipid);
normarea=V_hc/l_hc;
c_s_hc=vf_bilayer;
c_A_hc=1;
c_V_hc=1;
//printf("%e %e %e \n", normarea, l_hc, nf_hc_lipid);
lipid->l=l_hc;
lipid->vol=V_hc;
lipid->nSL=nSL_hc;
lipid->absorb=absorb_hc;
lipid->nf=c_s_hc*c_A_hc*c_V_hc;
//outher methyl
nf_m_lipid=1;
V_m=nf_m_lipid*volmethyllipid;
l_m=l_hc*V_m/V_hc;
nSL_m=nf_m_lipid*nslmethyllipid;
absorb_m=nf_m_lipid*absorbmethyllipid;
c_s_m=c_s_hc;
c_A_m=1;
c_V_m=1;
methyl->l=l_m;
methyl->vol=V_m;
methyl->nSL=nSL_m;
methyl->absorb=absorb_m;
methyl->nf=c_s_m*c_A_m*c_V_m;
//PC headgroup
headgroup->nf=c_s_hc*c_A_hc*nf_hc_lipid*(1-hc_substitution);
//substrate
substrate->vol=normarea*substrate->l;
substrate->nSL=rho_substrate*substrate->vol;
substrate->absorb=absorb_substrate*substrate->vol;
// set all lengths
methyl->z=substrate->l+0.5*(methyl->l);
lipid->z=methyl->z+0.5*(methyl->l+lipid->l);
headgroup->fnSetZ(lipid->z+0.5*(lipid->l+headgroup->l));
};
//Return value is area at position z
double Monolayer::fnGetArea(double dz) {
return (substrate->fnGetArea(dz)+lipid->fnGetArea(dz)+headgroup->fnGetArea(dz)
+methyl->fnGetArea(dz));
};
//get nSLD from molecular subgroups
double Monolayer::fnGetnSLD(double dz) {
double substratearea, lipidarea, headgrouparea;
double methylarea, sum;
substratearea=substrate->fnGetArea(dz);
lipidarea=lipid->fnGetArea(dz);
headgrouparea=headgroup->fnGetArea(dz);
methylarea=methyl->fnGetArea(dz);
sum=substratearea+lipidarea+headgrouparea+methylarea;
if (sum==0) {return 0;}
else {
return (
substrate->fnGetnSLD(dz)*substratearea+
headgroup->fnGetnSLD(dz)*headgrouparea+
lipid->fnGetnSLD(dz)*lipidarea+
methyl->fnGetnSLD(dz)*methylarea
)/sum;
}
};
//Use limits of molecular subgroups
double Monolayer::fnGetLowerLimit() {return substrate->fnGetLowerLimit();};
double Monolayer::fnGetUpperLimit() {return headgroup->fnGetUpperLimit();};
double Monolayer::fnWriteProfile(double aArea[], double anSLD[], int dimension, double stepsize, double dMaxArea)
{
nSLDObj::fnWriteProfile(aArea,anSLD,dimension,stepsize,dMaxArea);
return normarea;
};
double Monolayer::fnWriteProfile(double aArea[], double anSLD[], double aAbsorb[], int dimension, double stepsize, double dMaxArea)
{
nSLDObj::fnWriteProfile(aArea,anSLD,aAbsorb,dimension,stepsize,dMaxArea);
return normarea;
};
void Monolayer::fnSetSigma(double dsigma)
{
//set all sigma
//sigma=sqrt(2.4*2.4 + global_rough*global_rough);
headgroup->fnSetSigma(dsigma);
lipid->fnSetSigma(dsigma);
methyl->fnSetSigma(dsigma);
}
void Monolayer::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
//char *str = new char[80];
//fprintf(fp, "PC %s z %lf l %lf nf %lf \n",cName, z, l, nf);
//nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
substrate->fnWritePar2File(fp, "substrate", dimension, stepsize);
methyl->fnWritePar2File(fp, "methyl", dimension, stepsize);
lipid->fnWritePar2File(fp, "lipid", dimension, stepsize);
headgroup->fnWritePar2File(fp, "headgroup", dimension, stepsize);
fnWriteConstant(fp, "normarea", normarea, 0, dimension, stepsize);
}
//------------------------------------------------------------------------------------------------------
// Lipid bilayer single lipid
//------------------------------------------------------------------------------------------------------
ssBLM::ssBLM(){
substrate = new Box2Err();
headgroup1= new PCm(); //mirrored PC head group
lipid1 = new Box2Err();
methyl1 = new Box2Err();
methyl2 = new Box2Err();
lipid2 = new Box2Err();
headgroup2 = new PC(); //PC head group
substrate->l=20;
substrate->z=10;
substrate->nf=1;
substrate->sigma1=2.0;
volacyllipid=925;
nslacyllipid=-2.67e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
l_submembrane=3.0;
hc_substitution_1=0.;
hc_substitution_2=0.;
fnAdjustParameters();
};
ssBLM::~ssBLM(){
delete substrate;
delete headgroup1;
delete lipid1;
delete methyl1;
delete methyl2;
delete lipid2;
delete headgroup2;
};
void ssBLM::fnAdjustParameters(){
double l_ohc;
double V_ohc;
double nf_ohc_lipid, nSL_ohc;
double c_s_ohc, c_A_ohc, c_V_ohc;
double l_om;
double V_om;
double nf_om_lipid, nSL_om;
double c_s_om, c_A_om, c_V_om;
double l_ihc;
double V_ihc;
double nf_ihc_lipid, nSL_ihc;
double c_s_ihc, c_A_ihc, c_V_ihc;
double l_im;
double V_im;
double nf_im_lipid, nSL_im;
double c_s_im, c_A_im, c_V_im;
// set all sigma
//sigma=sqrt(2.4*2.4 + global_rough*global_rough);
substrate->sigma2=global_rough;
headgroup1->fnSetSigma(sigma);
lipid1->sigma1=sigma;
lipid1->sigma2=sigma;
methyl1->sigma1=sigma;
methyl1->sigma2=sigma;
methyl2->sigma1=sigma;
methyl2->sigma2=sigma;
lipid2->sigma1=sigma;
lipid2->sigma2=sigma;
headgroup2->fnSetSigma(sigma);
//outer hydrocarbons
l_ohc=l_lipid2;
nf_ohc_lipid=1;
V_ohc=nf_ohc_lipid*(volacyllipid-volmethyllipid);
nSL_ohc=nf_ohc_lipid*(nslacyllipid-nslmethyllipid);
normarea=V_ohc/l_ohc;
c_s_ohc=vf_bilayer;
c_A_ohc=1;
c_V_ohc=1;
lipid2->l=l_ohc;
lipid2->vol=V_ohc;
lipid2->nSL=nSL_ohc;
lipid2->nf=c_s_ohc*c_A_ohc*c_V_ohc;
//outher methyl
nf_om_lipid=1;
V_om=nf_om_lipid*volmethyllipid;
l_om=l_ohc*V_om/V_ohc;
nSL_om=nf_om_lipid*nslmethyllipid;
c_s_om=c_s_ohc;
c_A_om=1;
c_V_om=1;
methyl2->l=l_om;
methyl2->vol=V_om;
methyl2->nSL=nSL_om;
methyl2->nf=c_s_om*c_A_om*c_V_om;
//inner hydrocarbons
l_ihc=l_lipid1;
nf_ihc_lipid=1;
V_ihc=nf_ihc_lipid*(volacyllipid-volmethyllipid);
nSL_ihc=nf_ihc_lipid*(nslacyllipid-nslmethyllipid);
c_s_ihc=vf_bilayer;
c_A_ihc=normarea*l_ihc/V_ihc;
c_V_ihc=1;
lipid1->l=l_ihc;
lipid1->vol=V_ihc;
lipid1->nSL=nSL_ihc;
lipid1->nf=c_s_ihc*c_A_ihc*c_V_ihc;
//inner methyl
nf_im_lipid=nf_ihc_lipid;
V_im=nf_im_lipid*volmethyllipid;
l_im=l_ihc*V_im/V_ihc;
nSL_im=nf_im_lipid*nslmethyllipid;
c_s_im=c_s_ihc;
c_A_im=c_A_ihc;
c_V_im=1;
methyl1->l=l_im;
methyl1->vol=V_im;
methyl1->nSL=nSL_im;
methyl1->nf=c_s_im*c_A_im*c_V_im;
//outer PC headgroup
headgroup2->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid*(1-hc_substitution_2);
//inner PC headgroup
headgroup1->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid*(1-hc_substitution_1);
//substrate
substrate->vol=normarea*substrate->l;
substrate->nSL=rho_substrate*substrate->vol;
// set all lengths
headgroup1->fnSetZ(substrate->l+l_submembrane+0.5*headgroup1->l);
lipid1->z=headgroup1->fnGetZ()+0.5*(headgroup1->l+lipid1->l);
methyl1->z=lipid1->z+0.5*(lipid1->l+methyl1->l);
methyl2->z=methyl1->z+0.5*(methyl1->l+methyl2->l);
lipid2->z=methyl2->z+0.5*(methyl2->l+lipid2->l);
headgroup2->fnSetZ(lipid2->z+0.5*lipid2->l+0.5*headgroup2->l);
};
//Return value is area at position z
double ssBLM::fnGetArea(double dz) {
return (substrate->fnGetArea(dz)+lipid1->fnGetArea(dz)+headgroup1->fnGetArea(dz)
+methyl1->fnGetArea(dz)+methyl2->fnGetArea(dz)+lipid2->fnGetArea(dz)
+headgroup2->fnGetArea(dz));
};
//get nSLD from molecular subgroups
double ssBLM::fnGetnSLD(double dz) {
double substratearea, lipid1area, headgroup1area;
double methyl1area, methyl2area, lipid2area, headgroup2area, sum;
substratearea=substrate->fnGetArea(dz);
lipid1area=lipid1->fnGetArea(dz);
headgroup1area=headgroup1->fnGetArea(dz);
methyl1area=methyl1->fnGetArea(dz);
methyl2area=methyl2->fnGetArea(dz);
lipid2area=lipid2->fnGetArea(dz);
headgroup2area=headgroup2->fnGetArea(dz);
sum=substratearea+lipid1area+headgroup1area+methyl1area
+methyl2area+lipid2area+headgroup2area;
if (sum==0) {return 0;}
else {
return (
substrate->fnGetnSLD(dz)*substratearea+
headgroup1->fnGetnSLD(dz)*headgroup1area+
lipid1->fnGetnSLD(dz)*lipid1area+
methyl1->fnGetnSLD(dz)*methyl1area+
methyl2->fnGetnSLD(dz)*methyl2area+
lipid2->fnGetnSLD(dz)*lipid2area+
headgroup2->fnGetnSLD(dz)*headgroup2area
)/sum;
}
};
//Use limits of molecular subgroups
double ssBLM::fnGetLowerLimit() {return substrate->fnGetLowerLimit();};
double ssBLM::fnGetUpperLimit() {return headgroup2->fnGetUpperLimit();};
double ssBLM::fnWriteProfile(double aArea[], double anSLD[], int dimension, double stepsize, double dMaxArea)
{
nSLDObj::fnWriteProfile(aArea,anSLD,dimension,stepsize,dMaxArea);
return normarea;
};
void ssBLM::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
//char *str = new char[80];
//fprintf(fp, "PC %s z %lf l %lf nf %lf \n",cName, z, l, nf);
//nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
substrate->fnWritePar2File(fp, "substrate", dimension, stepsize);
headgroup1->fnWritePar2File(fp, "headgroup1", dimension, stepsize);
lipid1->fnWritePar2File(fp, "lipid1", dimension, stepsize);
methyl1->fnWritePar2File(fp, "methyl1", dimension, stepsize);
methyl2->fnWritePar2File(fp, "methyl2", dimension, stepsize);
lipid2->fnWritePar2File(fp, "lipid2", dimension, stepsize);
headgroup2->fnWritePar2File(fp, "headgroup2", dimension, stepsize);
fnWriteConstant(fp, "normarea", normarea, 0, dimension, stepsize);
//delete []str;
}
//------------------------------------------------------------------------------------------------------
// Tethered Lipid bilayer - binary system
//------------------------------------------------------------------------------------------------------
tBLM::tBLM(){
substrate = new Box2Err();
bME = new Box2Err();
tether = new Box2Err();
tetherg = new Box2Err();
headgroup1 = new PCm(); //mirrored PC head group
lipid1 = new Box2Err();
methyl1 = new Box2Err();
methyl2 = new Box2Err();
lipid2 = new Box2Err();
headgroup2 = new PC(); //PC head group
substrate->l=20;
substrate->z=10;
substrate->nf=1;
substrate->sigma1=2.0;
bME->vol=110;
bME->nSL=3.243e-5;
bME->l=5.2;
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
volacyllipid=925;
nslacyllipid=-2.67e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=982;
nslacyltether=-2.85e-4;
hc_substitution_1=0;
hc_substitution_2=0;
fnAdjustParameters();
};
tBLM::~tBLM(){
delete substrate;
delete bME;
delete tether;
delete tetherg;
delete headgroup1;
delete lipid1;
delete methyl1;
delete methyl2;
delete lipid2;
delete headgroup2;
};
void tBLM::fnAdjustParameters(){
double l_ohc;
double V_ohc;
double nf_ohc_lipid, nSL_ohc;
double c_s_ohc, c_A_ohc, c_V_ohc;
double l_om;
double V_om;
double nf_om_lipid, nSL_om;
double c_s_om, c_A_om, c_V_om;
double l_ihc;
double V_ihc;
double nf_ihc_lipid,nf_ihc_tether, nSL_ihc;
double c_s_ihc, c_A_ihc, c_V_ihc;
double l_im;
double V_im;
double nf_im_lipid, nf_im_tether, nSL_im;
double c_s_im, c_A_im, c_V_im;
double V_tg;
double c_s_tg, c_A_tg, c_V_tg;
double l_EO,V_EO;
double c_s_EO, c_A_EO, c_V_EO;
double l_bME,V_bME;
double d1;
// set all sigma
//sigma=sqrt(2.4*2.4 + global_rough*global_rough);
substrate->sigma2=global_rough;
bME->sigma1=global_rough;
bME->sigma2=global_rough;
headgroup1->fnSetSigma(sigma);
tether->sigma1=global_rough;
tether->sigma2=sigma;
tetherg->sigma1=sigma;
tetherg->sigma2=sigma;
lipid1->sigma1=sigma;
lipid1->sigma2=sigma;
methyl1->sigma1=sigma;
methyl1->sigma2=sigma;
methyl2->sigma1=sigma;
methyl2->sigma2=sigma;
lipid2->sigma1=sigma;
lipid2->sigma2=sigma;
headgroup2->fnSetSigma(sigma);
//outer hydrocarbons
l_ohc=l_lipid2;
nf_ohc_lipid=1;
V_ohc=nf_ohc_lipid*(volacyllipid-volmethyllipid);
nSL_ohc=nf_ohc_lipid*(nslacyllipid-nslmethyllipid);
normarea=V_ohc/l_ohc;
c_s_ohc=vf_bilayer;
c_A_ohc=1;
c_V_ohc=1;
lipid2->l=l_ohc;
lipid2->vol=V_ohc;
lipid2->nSL=nSL_ohc;
lipid2->nf=c_s_ohc*c_A_ohc*c_V_ohc;
//outher methyl
nf_om_lipid=1;
V_om=nf_om_lipid*volmethyllipid;
l_om=l_ohc*V_om/V_ohc;
nSL_om=nf_om_lipid*nslmethyllipid;
c_s_om=c_s_ohc;
c_A_om=1;
c_V_om=1;
methyl2->l=l_om;
methyl2->vol=V_om;
methyl2->nSL=nSL_om;
methyl2->nf=c_s_om*c_A_om*c_V_om;
//inner hydrocarbons
l_ihc=l_lipid1;
nf_ihc_tether=nf_tether;
nf_ihc_lipid=1-nf_ihc_tether;
V_ihc=nf_ihc_lipid*(volacyllipid-volmethyllipid)+nf_ihc_tether*(volacyltether-volmethyltether);
nSL_ihc=nf_ihc_lipid*(nslacyllipid-nslmethyllipid)+nf_ihc_tether*(nslacyltether-nslmethyltether);
c_s_ihc=vf_bilayer;
c_A_ihc=normarea*l_ihc/V_ihc;
c_V_ihc=1;
lipid1->l=l_ihc;
lipid1->vol=V_ihc;
lipid1->nSL=nSL_ihc;
lipid1->nf=c_s_ihc*c_A_ihc*c_V_ihc;
//inner methyl
nf_im_lipid=nf_ihc_lipid;
nf_im_tether=nf_ihc_tether;
V_im=nf_im_lipid*volmethyllipid+nf_im_tether*volmethyltether;
l_im=l_ihc*V_im/V_ihc;
nSL_im=nf_im_lipid*nslmethyllipid+nf_im_tether*nslmethyltether;
c_s_im=c_s_ihc;
c_A_im=c_A_ihc;
c_V_im=1;
methyl1->l=l_im;
methyl1->vol=V_im;
methyl1->nSL=nSL_im;
methyl1->nf=c_s_im*c_A_im*c_V_im;
//outer PC headgroup
headgroup2->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid*(1-hc_substitution_2);
//inner PC headgroup
headgroup1->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid*(1-hc_substitution_1);
//tether glycerol part
V_tg=tetherg->vol;
c_s_tg=c_s_ihc;
c_A_tg=c_A_ihc;
c_V_tg=nf_ihc_tether;
tetherg->l=tetherg->vol/((volacyltether-volmethyltether)/lipid1->l)/0.9;
tetherg->nf=c_s_tg*c_A_tg*c_V_tg;
//tether EO part
l_EO=l_tether;
V_EO=tether->vol;
c_s_EO=c_s_ihc;
c_A_EO=c_A_ihc;
c_V_EO=nf_ihc_tether;
tether->nf=c_s_EO*c_A_EO*c_V_EO;
tether->l=l_EO;
if ((tether->nf*tether->vol/tether->l)>normarea) {
tether->l=(tether->nf*tether->vol)/normarea;
}
l_tether=tether->l;
//bME
bME->l=5.2;
l_bME=bME->l;
headgroup1->l=9.575;
V_bME=bME->vol;
d1=headgroup1->l+bME->l-tether->l-tetherg->l;
if (d1>0) {
bME->l=bME->l-d1/2;
headgroup1->l=headgroup1->l-d1/2;
}
if ((tether->nf*tether->vol/tether->l+mult_tether*tether->nf*bME->vol/bME->l)>normarea) {
mult_tether=((normarea-tether->nf*tether->vol/tether->l)/(bME->vol/bME->l))/tether->nf;
if (mult_tether<0) {
mult_tether=0;
}
}
bME->nf=tether->nf*mult_tether; //2.333;
//substrate
substrate->vol=normarea*substrate->l;
substrate->nSL=rho_substrate*substrate->vol;
// set all lengths
bME->z=0.5*bME->l+substrate->l;
tether->z=0.5*tether->l+substrate->l;
tetherg->z=tether->z+0.5*tether->l+0.5*tetherg->l;
lipid1->z=tetherg->z+0.5*(tetherg->l+lipid1->l);
headgroup1->fnSetZ(lipid1->z-0.5*lipid1->l-0.5*headgroup1->l);
methyl1->z=lipid1->z+0.5*(lipid1->l+methyl1->l);
methyl2->z=methyl1->z+0.5*(methyl1->l+methyl2->l);
lipid2->z=methyl2->z+0.5*(methyl2->l+lipid2->l);
headgroup2->fnSetZ(lipid2->z+0.5*lipid2->l+0.5*headgroup2->l);
};
//Return value is area at position z
double tBLM::fnGetArea(double dz) {
return (substrate->fnGetArea(dz)+bME->fnGetArea(dz)+tether->fnGetArea(dz)
+tetherg->fnGetArea(dz)+lipid1->fnGetArea(dz)+headgroup1->fnGetArea(dz)
+methyl1->fnGetArea(dz)+methyl2->fnGetArea(dz)+lipid2->fnGetArea(dz)
+headgroup2->fnGetArea(dz));
};
//get nSLD from molecular subgroups
double tBLM::fnGetnSLD(double dz) {
double substratearea, bMEarea, tetherarea, tethergarea, lipid1area, headgroup1area;
double methyl1area, methyl2area, lipid2area, headgroup2area, sum;
substratearea=substrate->fnGetArea(dz);
bMEarea=bME->fnGetArea(dz);
tetherarea=tether->fnGetArea(dz);
tethergarea=tetherg->fnGetArea(dz);
lipid1area=lipid1->fnGetArea(dz);
headgroup1area=headgroup1->fnGetArea(dz);
methyl1area=methyl1->fnGetArea(dz);
methyl2area=methyl2->fnGetArea(dz);
lipid2area=lipid2->fnGetArea(dz);
headgroup2area=headgroup2->fnGetArea(dz);
sum=substratearea+bMEarea+tetherarea+tethergarea+lipid1area+headgroup1area+methyl1area
+methyl2area+lipid2area+headgroup2area;
if (sum==0) {return 0;}
else {
return (
substrate->fnGetnSLD(dz)*substratearea+
bME->fnGetnSLD(dz)*bMEarea+
tether->fnGetnSLD(dz)*tetherarea+
tetherg->fnGetnSLD(dz)*tethergarea+
headgroup1->fnGetnSLD(dz)*headgroup1area+
lipid1->fnGetnSLD(dz)*lipid1area+
methyl1->fnGetnSLD(dz)*methyl1area+
methyl2->fnGetnSLD(dz)*methyl2area+
lipid2->fnGetnSLD(dz)*lipid2area+
headgroup2->fnGetnSLD(dz)*headgroup2area
)/sum;
}
};
//Use limits of molecular subgroups
double tBLM::fnGetLowerLimit() {return substrate->fnGetLowerLimit();};
double tBLM::fnGetUpperLimit() {return headgroup2->fnGetUpperLimit();};
double tBLM::fnWriteProfile(double aArea[], double anSLD[], int dimension, double stepsize, double dMaxArea)
{
nSLDObj::fnWriteProfile(aArea,anSLD,dimension,stepsize,dMaxArea);
return normarea;
};
void tBLM::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
//char *str = new char[80];
//fprintf(fp, "PC %s z %lf l %lf nf %lf \n",cName, z, l, nf);
//nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
substrate->fnWritePar2File(fp, "substrate", dimension, stepsize);
bME->fnWritePar2File(fp, "bME", dimension, stepsize);
tether->fnWritePar2File(fp, "tether", dimension, stepsize);
tetherg->fnWritePar2File(fp, "tetherg", dimension, stepsize);
headgroup1->fnWritePar2File(fp, "headgroup1", dimension, stepsize);
lipid1->fnWritePar2File(fp, "lipid1", dimension, stepsize);
methyl1->fnWritePar2File(fp, "methyl1", dimension, stepsize);
methyl2->fnWritePar2File(fp, "methyl2", dimension, stepsize);
lipid2->fnWritePar2File(fp, "lipid2", dimension, stepsize);
headgroup2->fnWritePar2File(fp, "headgroup2", dimension, stepsize);
fnWriteConstant(fp, "normarea", normarea, 0, dimension, stepsize);
//delete []str;
}
//------------------------------------------------------------------------------------------------------
// Lipid bilayer - binary system
//------------------------------------------------------------------------------------------------------
tBLM_binary::tBLM_binary(){
headgroup1_2= new Box2Err(); //second headgroups
headgroup2_2 = new Box2Err();
headgroup1_2->vol=330; //was 330
headgroup2_2->vol=330; //was 330
headgroup1_2->nSL=6.0012e-4; // was 6.0122e-4
headgroup2_2->nSL=6.0012e-4; // was 6.0122e-4
headgroup1_2->l=9.5;
headgroup2_2->l=9.5;
volacyllipid_2=925;
nslacyllipid_2=-2.67e-4;
volmethyllipid_2=98.8;
nslmethyllipid_2=-9.15e-5;
iSeparateLeafletComposition=0;
fnAdjustParameters();
};
tBLM_binary::~tBLM_binary(){
delete headgroup1_2;
delete headgroup2_2;
};
void tBLM_binary::fnAdjustParameters(){
double l_ohc;
double V_ohc;
double nf_ohc_lipid, nf_ohc_lipid_2, nSL_ohc;
double c_s_ohc, c_A_ohc, c_V_ohc;
double l_om;
double V_om;
double nf_om_lipid, nf_om_lipid_2, nSL_om;
double c_s_om, c_A_om, c_V_om;
double l_ihc;
double V_ihc;
double nf_ihc_lipid, nf_ihc_lipid_2, nf_ihc_tether, nSL_ihc;
double c_s_ihc, c_A_ihc, c_V_ihc;
double l_im;
double V_im;
double nf_im_lipid, nf_im_lipid_2, nf_im_tether, nSL_im;
double c_s_im, c_A_im, c_V_im;
double V_tg;
double c_s_tg, c_A_tg, c_V_tg;
double l_EO,V_EO;
double c_s_EO, c_A_EO, c_V_EO;
double l_bME,V_bME;
double d1;
// set all sigma
//sigma=sqrt(2.4*2.4 + global_rough*global_rough);
substrate->sigma2=global_rough;
bME->sigma1=global_rough;
bME->sigma2=global_rough;
headgroup1->fnSetSigma(sigma);
headgroup1_2->fnSetSigma(sigma);
tether->sigma1=global_rough;
tether->sigma2=sigma;
tetherg->fnSetSigma(sigma);
lipid1->fnSetSigma(sigma);
methyl1->fnSetSigma(sigma);
methyl2->fnSetSigma(sigma);
lipid2->fnSetSigma(sigma);
headgroup2->fnSetSigma(sigma);
headgroup2_2->fnSetSigma(sigma);
//outer hydrocarbons
l_ohc=l_lipid2;
if (iSeparateLeafletComposition==0) {
nf_ohc_lipid =1-nf_lipid_2;
nf_ohc_lipid_2=nf_lipid_2;
}
else{
nf_ohc_lipid =1-nf_lipid2_2;
nf_ohc_lipid_2=nf_lipid2_2;
}
V_ohc=nf_ohc_lipid*(volacyllipid-volmethyllipid)+nf_ohc_lipid_2*(volacyllipid_2-volmethyllipid_2);
nSL_ohc=nf_ohc_lipid*(nslacyllipid-nslmethyllipid)+nf_ohc_lipid_2*(nslacyllipid_2-nslmethyllipid_2);
normarea=V_ohc/l_ohc;
c_s_ohc=vf_bilayer;
c_A_ohc=1;
c_V_ohc=1;
lipid2->l=l_ohc;
lipid2->vol=V_ohc;
lipid2->nSL=nSL_ohc;
lipid2->nf=c_s_ohc*c_A_ohc*c_V_ohc;
//outher methyl
nf_om_lipid =nf_ohc_lipid;
nf_om_lipid_2=nf_ohc_lipid_2;
V_om=nf_om_lipid*volmethyllipid+nf_om_lipid_2*volmethyllipid_2;
l_om=l_ohc*V_om/V_ohc;
nSL_om=nf_om_lipid*nslmethyllipid+nf_om_lipid_2*nslmethyllipid_2;
c_s_om=c_s_ohc;
c_A_om=1;
c_V_om=1;
methyl2->l=l_om;
methyl2->vol=V_om;
methyl2->nSL=nSL_om;
methyl2->nf=c_s_om*c_A_om*c_V_om;
//inner hydrocarbons
l_ihc=l_lipid1;
nf_ihc_tether=nf_tether;
if (iSeparateLeafletComposition==0){
nf_ihc_lipid=(1-nf_ihc_tether)*nf_ohc_lipid;
nf_ihc_lipid_2=(1-nf_ihc_tether)*nf_ohc_lipid_2;
}
else{
nf_ihc_lipid=(1-nf_ihc_tether)*(1-nf_lipid1_2);
nf_ihc_lipid_2=(1-nf_ihc_tether)*(nf_lipid1_2);
}
nf_ihc_lipid=(1-nf_ihc_tether)*nf_ohc_lipid;
nf_ihc_lipid_2=(1-nf_ihc_tether)*nf_ohc_lipid_2;
V_ihc=nf_ihc_lipid*(volacyllipid-volmethyllipid)+nf_ihc_lipid_2*(volacyllipid_2-volmethyllipid_2)+nf_ihc_tether*(volacyltether-volmethyltether);
nSL_ihc=nf_ihc_lipid*(nslacyllipid-nslmethyllipid)+nf_ihc_lipid_2*(nslacyllipid_2-nslmethyllipid_2)+nf_ihc_tether*(nslacyltether-nslmethyltether);
c_s_ihc=vf_bilayer;
c_A_ihc=normarea*l_ihc/V_ihc;
c_V_ihc=1;
lipid1->l=l_ihc;
lipid1->vol=V_ihc;
lipid1->nSL=nSL_ihc;
lipid1->nf=c_s_ihc*c_A_ihc*c_V_ihc;
//inner methyl
nf_im_lipid=nf_ihc_lipid;
nf_im_lipid_2=nf_ihc_lipid_2;
nf_im_tether=nf_ihc_tether;
V_im=nf_im_lipid*volmethyllipid+nf_im_lipid_2*volmethyllipid_2+nf_im_tether*volmethyltether;
l_im=l_ihc*V_im/V_ihc;
nSL_im=nf_im_lipid*nslmethyllipid+nf_im_lipid_2*nslmethyllipid_2+nf_im_tether*nslmethyltether;
c_s_im=c_s_ihc;
c_A_im=c_A_ihc;
c_V_im=1;
methyl1->l=l_im;
methyl1->vol=V_im;
methyl1->nSL=nSL_im;
methyl1->nf=c_s_im*c_A_im*c_V_im;
//outer headgroups
headgroup2->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid*(1-hc_substitution_2);
headgroup2_2->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid_2*(1-hc_substitution_2);
//inner headgroups
headgroup1->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid*(1-hc_substitution_1);
headgroup1_2->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid_2*(1-hc_substitution_1);
//tether glycerol part
V_tg=tetherg->vol;
c_s_tg=c_s_ihc;
c_A_tg=c_A_ihc;
c_V_tg=nf_ihc_tether;
tetherg->l=tetherg->vol/((volacyltether-volmethyltether)/lipid1->l)/0.9;
tetherg->nf=c_s_tg*c_A_tg*c_V_tg;
//tether EO part
l_EO=l_tether;
V_EO=tether->vol;
c_s_EO=c_s_ihc;
c_A_EO=c_A_ihc;
c_V_EO=nf_ihc_tether;
tether->nf=c_s_EO*c_A_EO*c_V_EO;
tether->l=l_EO;
if ((tether->nf*tether->vol/tether->l)>normarea) {
tether->l=(tether->nf*tether->vol)/normarea;
}
l_tether=tether->l;
//bME
bME->l=5.2;
l_bME=bME->l;
headgroup1->l=9.575;
V_bME=bME->vol;
d1=headgroup1->l+bME->l-tether->l-tetherg->l;
if (d1>0) {
bME->l=bME->l-d1/2;
headgroup1->l=headgroup1->l-d1/2;
}
if ((tether->nf*tether->vol/tether->l+mult_tether*tether->nf*bME->vol/bME->l)>normarea) {
mult_tether=((normarea-tether->nf*tether->vol/tether->l)/(bME->vol/bME->l))/tether->nf;
if (mult_tether<0) {
mult_tether=0;
}
}
bME->nf=tether->nf*mult_tether; //2.333;
//substrate
substrate->vol=normarea*substrate->l;
substrate->nSL=rho_substrate*substrate->vol;
// set all lengths
bME->z=0.5*bME->l+substrate->l;
tether->z=0.5*tether->l+substrate->l;
tetherg->z=tether->z+0.5*tether->l+0.5*tetherg->l;
lipid1->z=tetherg->z+0.5*(tetherg->l+lipid1->l);
headgroup1->fnSetZ(lipid1->z-0.5*lipid1->l-0.5*headgroup1->l);
headgroup1_2->fnSetZ(lipid1->z-0.5*lipid1->l-0.5*headgroup1_2->l);
methyl1->z=lipid1->z+0.5*(lipid1->l+methyl1->l);
methyl2->z=methyl1->z+0.5*(methyl1->l+methyl2->l);
lipid2->z=methyl2->z+0.5*(methyl2->l+lipid2->l);
headgroup2->fnSetZ(lipid2->z+0.5*lipid2->l+0.5*headgroup2->l);
headgroup2_2->fnSetZ(lipid2->z+0.5*lipid2->l+0.5*headgroup2_2->l);
};
//Return value is area at position z
double tBLM_binary::fnGetArea(double dz) {
return (substrate->fnGetArea(dz)+bME->fnGetArea(dz)+tether->fnGetArea(dz)
+tetherg->fnGetArea(dz)+lipid1->fnGetArea(dz)+headgroup1->fnGetArea(dz)
+methyl1->fnGetArea(dz)+methyl2->fnGetArea(dz)+lipid2->fnGetArea(dz)
+headgroup2->fnGetArea(dz)+headgroup1_2->fnGetArea(dz)+headgroup2_2->fnGetArea(dz));
};
//get nSLD from molecular subgroups
double tBLM_binary::fnGetnSLD(double dz) {
double substratearea, bMEarea, tetherarea, tethergarea, lipid1area, headgroup1area;
double methyl1area, methyl2area, lipid2area, headgroup2area, sum;
double headgroup1_2_area, headgroup2_2_area;
substratearea=substrate->fnGetArea(dz);
bMEarea=bME->fnGetArea(dz);
tetherarea=tether->fnGetArea(dz);
tethergarea=tetherg->fnGetArea(dz);
lipid1area=lipid1->fnGetArea(dz);
headgroup1area=headgroup1->fnGetArea(dz);
headgroup1_2_area=headgroup1_2->fnGetArea(dz);
methyl1area=methyl1->fnGetArea(dz);
methyl2area=methyl2->fnGetArea(dz);
lipid2area=lipid2->fnGetArea(dz);
headgroup2area=headgroup2->fnGetArea(dz);
headgroup2_2_area=headgroup2_2->fnGetArea(dz);
sum=substratearea+bMEarea+tetherarea+tethergarea+lipid1area+headgroup1area+methyl1area
+methyl2area+lipid2area+headgroup2area+headgroup1_2_area+headgroup2_2_area;
if (sum==0) {return 0;}
else {
return (
substrate->fnGetnSLD(dz)*substratearea+
bME->fnGetnSLD(dz)*bMEarea+
tether->fnGetnSLD(dz)*tetherarea+
tetherg->fnGetnSLD(dz)*tethergarea+
headgroup1->fnGetnSLD(dz)*headgroup1area+
headgroup1_2->fnGetnSLD(dz)*headgroup1_2_area+
lipid1->fnGetnSLD(dz)*lipid1area+
methyl1->fnGetnSLD(dz)*methyl1area+
methyl2->fnGetnSLD(dz)*methyl2area+
lipid2->fnGetnSLD(dz)*lipid2area+
headgroup2->fnGetnSLD(dz)*headgroup2area+
headgroup2_2->fnGetnSLD(dz)*headgroup2_2_area
)/sum;
}
};
//Use limits of molecular subgroups
double tBLM_binary::fnGetLowerLimit() {return substrate->fnGetLowerLimit();};
double tBLM_binary::fnGetUpperLimit()
{
double a,b;
a=headgroup2->fnGetUpperLimit();
b=headgroup2_2->fnGetUpperLimit();
if (a>b) {return a;} else {return b;}
};
double tBLM_binary::fnWriteProfile(double aArea[], double anSLD[], int dimension, double stepsize, double dMaxArea)
{
nSLDObj::fnWriteProfile(aArea,anSLD,dimension,stepsize,dMaxArea);
return normarea;
};
void tBLM_binary::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
//char *str = new char[80];
//fprintf(fp, "PC %s z %lf l %lf nf %lf \n",cName, z, l, nf);
//nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
substrate->fnWritePar2File(fp, "substrate", dimension, stepsize);
bME->fnWritePar2File(fp, "bME", dimension, stepsize);
tether->fnWritePar2File(fp, "tether", dimension, stepsize);
tetherg->fnWritePar2File(fp, "tetherg", dimension, stepsize);
headgroup1->fnWritePar2File(fp, "headgroup1", dimension, stepsize);
headgroup1_2->fnWritePar2File(fp, "headgroup1_2", dimension, stepsize);
lipid1->fnWritePar2File(fp, "lipid1", dimension, stepsize);
methyl1->fnWritePar2File(fp, "methyl1", dimension, stepsize);
methyl2->fnWritePar2File(fp, "methyl2", dimension, stepsize);
lipid2->fnWritePar2File(fp, "lipid2", dimension, stepsize);
headgroup2->fnWritePar2File(fp, "headgroup2", dimension, stepsize);
headgroup2_2->fnWritePar2File(fp, "headgroup2_2", dimension, stepsize);
fnWriteConstant(fp, "normarea", normarea, 0, dimension, stepsize);
//delete []str;
}
//------------------------------------------------------------------------------------------------------
// Lipid bilayer - ternary system
//------------------------------------------------------------------------------------------------------
tBLM_ternary::tBLM_ternary(){
headgroup1_2= new Box2Err(); //second headgroups
headgroup2_2 = new Box2Err();
headgroup1_3= new Box2Err(); //third headgroups
headgroup2_3 = new Box2Err();
headgroup1_2->vol=330; //was 330
headgroup2_2->vol=330; //was 330
headgroup1_2->nSL=6.0012e-4; // was 6.0122e-4
headgroup2_2->nSL=6.0012e-4; // was 6.0122e-4
headgroup1_2->l=9.5;
headgroup2_2->l=9.5;
headgroup1_3->vol=330; //was 330
headgroup2_3->vol=330; //was 330
headgroup1_3->nSL=6.0012e-4; // was 6.0122e-4
headgroup2_3->nSL=6.0012e-4; // was 6.0122e-4
headgroup1_3->l=9.5;
headgroup2_3->l=9.5;
volacyllipid_2=925;
nslacyllipid_2=-2.67e-4;
volmethyllipid_2=98.8;
nslmethyllipid_2=-9.15e-5;
volacyllipid_3=925;
nslacyllipid_3=-2.67e-4;
volmethyllipid_3=98.8;
nslmethyllipid_3=-9.15e-5;
fnAdjustParameters();
};
tBLM_ternary::~tBLM_ternary(){
delete headgroup1_2;
delete headgroup2_2;
delete headgroup1_3;
delete headgroup2_3;
};
void tBLM_ternary::fnAdjustParameters(){
double l_ohc;
double V_ohc;
double nf_ohc_lipid, nf_ohc_lipid_2, nf_ohc_lipid_3, nSL_ohc;
double c_s_ohc, c_A_ohc, c_V_ohc;
double l_om;
double V_om;
double nf_om_lipid, nf_om_lipid_2, nf_om_lipid_3, nSL_om;
double c_s_om, c_A_om, c_V_om;
double l_ihc;
double V_ihc;
double nf_ihc_lipid, nf_ihc_lipid_2, nf_ihc_lipid_3, nf_ihc_tether, nSL_ihc;
double c_s_ihc, c_A_ihc, c_V_ihc;
double l_im;
double V_im;
double nf_im_lipid, nf_im_lipid_2, nf_im_lipid_3, nf_im_tether, nSL_im;
double c_s_im, c_A_im, c_V_im;
double V_tg;
double c_s_tg, c_A_tg, c_V_tg;
double l_EO,V_EO;
double c_s_EO, c_A_EO, c_V_EO;
double l_bME,V_bME;
double d1;
// set all sigma
//sigma=sqrt(2.4*2.4 + global_rough*global_rough);
substrate->sigma2=global_rough;
bME->sigma1=global_rough;
bME->sigma2=global_rough;
headgroup1->fnSetSigma(sigma);
headgroup1_2->fnSetSigma(sigma);
headgroup1_3->fnSetSigma(sigma);
tether->sigma1=global_rough;
tether->sigma2=sigma;
tetherg->fnSetSigma(sigma);
lipid1->fnSetSigma(sigma);
methyl1->fnSetSigma(sigma);
methyl2->fnSetSigma(sigma);
lipid2->fnSetSigma(sigma);
headgroup2->fnSetSigma(sigma);
headgroup2_2->fnSetSigma(sigma);
headgroup2_3->fnSetSigma(sigma);
//outer hydrocarbons
l_ohc=l_lipid2;
nf_ohc_lipid =1-nf_lipid_2-nf_lipid_3;
nf_ohc_lipid_2=nf_lipid_2;
nf_ohc_lipid_3=nf_lipid_3;
V_ohc=nf_ohc_lipid*(volacyllipid-volmethyllipid)+nf_ohc_lipid_2*(volacyllipid_2-volmethyllipid_2)+nf_ohc_lipid_3*(volacyllipid_3-volmethyllipid_3);
nSL_ohc=nf_ohc_lipid*(nslacyllipid-nslmethyllipid)+nf_ohc_lipid_2*(nslacyllipid_2-nslmethyllipid_2)+nf_ohc_lipid_3*(nslacyllipid_3-nslmethyllipid_3);
normarea=V_ohc/l_ohc;
c_s_ohc=vf_bilayer;
c_A_ohc=1;
c_V_ohc=1;
lipid2->l=l_ohc;
lipid2->vol=V_ohc;
lipid2->nSL=nSL_ohc;
lipid2->nf=c_s_ohc*c_A_ohc*c_V_ohc;
//outher methyl
nf_om_lipid =nf_ohc_lipid;
nf_om_lipid_2=nf_ohc_lipid_2;
nf_om_lipid_3=nf_ohc_lipid_3;
V_om=nf_om_lipid*volmethyllipid+nf_om_lipid_2*volmethyllipid_2+nf_om_lipid_3*volmethyllipid_3;
l_om=l_ohc*V_om/V_ohc;
nSL_om=nf_om_lipid*nslmethyllipid+nf_om_lipid_2*nslmethyllipid_2+nf_om_lipid_3*nslmethyllipid_3;
c_s_om=c_s_ohc;
c_A_om=1;
c_V_om=1;
methyl2->l=l_om;
methyl2->vol=V_om;
methyl2->nSL=nSL_om;
methyl2->nf=c_s_om*c_A_om*c_V_om;
//inner hydrocarbons
l_ihc=l_lipid1;
nf_ihc_tether=nf_tether;
nf_ihc_lipid=(1-nf_ihc_tether)*nf_ohc_lipid;
nf_ihc_lipid_2=(1-nf_ihc_tether)*nf_ohc_lipid_2;
nf_ihc_lipid_3=(1-nf_ihc_tether)*nf_ohc_lipid_3;
V_ihc=nf_ihc_lipid*(volacyllipid-volmethyllipid)+nf_ihc_lipid_2*(volacyllipid_2-volmethyllipid_2)+nf_ihc_lipid_3*(volacyllipid_3-volmethyllipid_3)+nf_ihc_tether*(volacyltether-volmethyltether);
nSL_ihc=nf_ihc_lipid*(nslacyllipid-nslmethyllipid)+nf_ihc_lipid_2*(nslacyllipid_2-nslmethyllipid_2)+nf_ihc_lipid_3*(nslacyllipid_3-nslmethyllipid_3)+nf_ihc_tether*(nslacyltether-nslmethyltether);
c_s_ihc=vf_bilayer;
c_A_ihc=normarea*l_ihc/V_ihc;
c_V_ihc=1;
lipid1->l=l_ihc;
lipid1->vol=V_ihc;
lipid1->nSL=nSL_ihc;
lipid1->nf=c_s_ihc*c_A_ihc*c_V_ihc;
//inner methyl
nf_im_lipid=nf_ihc_lipid;
nf_im_lipid_2=nf_ihc_lipid_2;
nf_im_lipid_3=nf_ihc_lipid_3;
nf_im_tether=nf_ihc_tether;
V_im=nf_im_lipid*volmethyllipid+nf_im_lipid_2*volmethyllipid_2+nf_im_lipid_3*volmethyllipid_3+nf_im_tether*volmethyltether;
l_im=l_ihc*V_im/V_ihc;
nSL_im=nf_im_lipid*nslmethyllipid+nf_im_lipid_2*nslmethyllipid_2+nf_im_lipid_3*nslmethyllipid_3+nf_im_tether*nslmethyltether;
c_s_im=c_s_ihc;
c_A_im=c_A_ihc;
c_V_im=1;
methyl1->l=l_im;
methyl1->vol=V_im;
methyl1->nSL=nSL_im;
methyl1->nf=c_s_im*c_A_im*c_V_im;
//outer headgroups
headgroup2->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid*(1-hc_substitution_2);
headgroup2_2->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid_2*(1-hc_substitution_2);
headgroup2_3->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid_3*(1-hc_substitution_2);
//inner headgroups
headgroup1->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid*(1-hc_substitution_1);
headgroup1_2->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid_2*(1-hc_substitution_1);
headgroup1_3->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid_3*(1-hc_substitution_1);
//tether glycerol part
V_tg=tetherg->vol;
c_s_tg=c_s_ihc;
c_A_tg=c_A_ihc;
c_V_tg=nf_ihc_tether;
tetherg->l=tetherg->vol/((volacyltether-volmethyltether)/lipid1->l)/0.9;
tetherg->nf=c_s_tg*c_A_tg*c_V_tg;
//tether EO part
l_EO=l_tether;
V_EO=tether->vol;
c_s_EO=c_s_ihc;
c_A_EO=c_A_ihc;
c_V_EO=nf_ihc_tether;
tether->nf=c_s_EO*c_A_EO*c_V_EO;
tether->l=l_EO;
if ((tether->nf*tether->vol/tether->l)>normarea) {
tether->l=(tether->nf*tether->vol)/normarea;
}
l_tether=tether->l;
//bME
bME->l=5.2;
l_bME=bME->l;
headgroup1->l=9.575;
V_bME=bME->vol;
d1=headgroup1->l+bME->l-tether->l-tetherg->l;
if (d1>0) {
bME->l=bME->l-d1/2;
headgroup1->l=headgroup1->l-d1/2;
}
if ((tether->nf*tether->vol/tether->l+mult_tether*tether->nf*bME->vol/bME->l)>normarea) {
mult_tether=((normarea-tether->nf*tether->vol/tether->l)/(bME->vol/bME->l))/tether->nf;
if (mult_tether<0) {
mult_tether=0;
}
}
bME->nf=tether->nf*mult_tether; //2.333;
//substrate
substrate->vol=normarea*substrate->l;
substrate->nSL=rho_substrate*substrate->vol;
// set all lengths
bME->z=0.5*bME->l+substrate->l;
tether->z=0.5*tether->l+substrate->l;
tetherg->z=tether->z+0.5*tether->l+0.5*tetherg->l;
lipid1->z=tetherg->z+0.5*(tetherg->l+lipid1->l);
headgroup1->fnSetZ(lipid1->z-0.5*lipid1->l-0.5*headgroup1->l);
headgroup1_2->fnSetZ(lipid1->z-0.5*lipid1->l-0.5*headgroup1_2->l);
headgroup1_3->fnSetZ(lipid1->z-0.5*lipid1->l-0.5*headgroup1_3->l);
methyl1->z=lipid1->z+0.5*(lipid1->l+methyl1->l);
methyl2->z=methyl1->z+0.5*(methyl1->l+methyl2->l);
lipid2->z=methyl2->z+0.5*(methyl2->l+lipid2->l);
headgroup2->fnSetZ(lipid2->z+0.5*lipid2->l+0.5*headgroup2->l);
headgroup2_2->fnSetZ(lipid2->z+0.5*lipid2->l+0.5*headgroup2_2->l);
headgroup2_3->fnSetZ(lipid2->z+0.5*lipid2->l+0.5*headgroup2_3->l);
};
//Return value is area at position z
double tBLM_ternary::fnGetArea(double dz) {
return (substrate->fnGetArea(dz)+bME->fnGetArea(dz)+tether->fnGetArea(dz)
+tetherg->fnGetArea(dz)+lipid1->fnGetArea(dz)+headgroup1->fnGetArea(dz)
+methyl1->fnGetArea(dz)+methyl2->fnGetArea(dz)+lipid2->fnGetArea(dz)
+headgroup2->fnGetArea(dz)+headgroup1_2->fnGetArea(dz)+headgroup2_2->fnGetArea(dz)
+headgroup1_3->fnGetArea(dz)+headgroup2_3->fnGetArea(dz));
};
//get nSLD from molecular subgroups
double tBLM_ternary::fnGetnSLD(double dz) {
double substratearea, bMEarea, tetherarea, tethergarea, lipid1area, headgroup1area;
double methyl1area, methyl2area, lipid2area, headgroup2area, sum;
double headgroup1_2_area, headgroup2_2_area;
double headgroup1_3_area, headgroup2_3_area;
substratearea=substrate->fnGetArea(dz);
bMEarea=bME->fnGetArea(dz);
tetherarea=tether->fnGetArea(dz);
tethergarea=tetherg->fnGetArea(dz);
lipid1area=lipid1->fnGetArea(dz);
headgroup1area=headgroup1->fnGetArea(dz);
headgroup1_2_area=headgroup1_2->fnGetArea(dz);
headgroup1_3_area=headgroup1_3->fnGetArea(dz);
methyl1area=methyl1->fnGetArea(dz);
methyl2area=methyl2->fnGetArea(dz);
lipid2area=lipid2->fnGetArea(dz);
headgroup2area=headgroup2->fnGetArea(dz);
headgroup2_2_area=headgroup2_2->fnGetArea(dz);
headgroup2_3_area=headgroup2_3->fnGetArea(dz);
sum=substratearea+bMEarea+tetherarea+tethergarea+lipid1area+headgroup1area+methyl1area
+methyl2area+lipid2area+headgroup2area+headgroup1_2_area+headgroup2_2_area
+headgroup1_3_area+headgroup2_3_area;
if (sum==0) {return 0;}
else {
return (
substrate->fnGetnSLD(dz)*substratearea+
bME->fnGetnSLD(dz)*bMEarea+
tether->fnGetnSLD(dz)*tetherarea+
tetherg->fnGetnSLD(dz)*tethergarea+
headgroup1->fnGetnSLD(dz)*headgroup1area+
headgroup1_2->fnGetnSLD(dz)*headgroup1_2_area+
headgroup1_3->fnGetnSLD(dz)*headgroup1_3_area+
lipid1->fnGetnSLD(dz)*lipid1area+
methyl1->fnGetnSLD(dz)*methyl1area+
methyl2->fnGetnSLD(dz)*methyl2area+
lipid2->fnGetnSLD(dz)*lipid2area+
headgroup2->fnGetnSLD(dz)*headgroup2area+
headgroup2_2->fnGetnSLD(dz)*headgroup2_2_area+
headgroup2_3->fnGetnSLD(dz)*headgroup2_3_area
)/sum;
}
};
//Use limits of molecular subgroups
double tBLM_ternary::fnGetLowerLimit() {return substrate->fnGetLowerLimit();};
double tBLM_ternary::fnGetUpperLimit()
{
double a,b,c;
a=headgroup2->fnGetUpperLimit();
b=headgroup2_2->fnGetUpperLimit();
c=headgroup2_3->fnGetUpperLimit();
if (a>b) {
if (a>c) return a; else return c;}
else{
if (b>c) return b; else return c;}
};
double tBLM_ternary::fnWriteProfile(double aArea[], double anSLD[], int dimension, double stepsize, double dMaxArea)
{
nSLDObj::fnWriteProfile(aArea,anSLD,dimension,stepsize,dMaxArea);
return normarea;
};
void tBLM_ternary::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
//char *str = new char[80];
//fprintf(fp, "PC %s z %lf l %lf nf %lf \n",cName, z, l, nf);
//nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
substrate->fnWritePar2File(fp, "substrate", dimension, stepsize);
bME->fnWritePar2File(fp, "bME", dimension, stepsize);
tether->fnWritePar2File(fp, "tether", dimension, stepsize);
tetherg->fnWritePar2File(fp, "tetherg", dimension, stepsize);
headgroup1->fnWritePar2File(fp, "headgroup1", dimension, stepsize);
headgroup1_2->fnWritePar2File(fp, "headgroup1_2", dimension, stepsize);
headgroup1_3->fnWritePar2File(fp, "headgroup1_3", dimension, stepsize);
lipid1->fnWritePar2File(fp, "lipid1", dimension, stepsize);
methyl1->fnWritePar2File(fp, "methyl1", dimension, stepsize);
methyl2->fnWritePar2File(fp, "methyl2", dimension, stepsize);
lipid2->fnWritePar2File(fp, "lipid2", dimension, stepsize);
headgroup2->fnWritePar2File(fp, "headgroup2", dimension, stepsize);
headgroup2_2->fnWritePar2File(fp, "headgroup2_2", dimension, stepsize);
headgroup2_3->fnWritePar2File(fp, "headgroup2_3", dimension, stepsize);
fnWriteConstant(fp, "normarea", normarea, 0, dimension, stepsize);
//delete []str;
}
//------------------------------------------------------------------------------------------------------
// Lipid bilayer - ternary system
//------------------------------------------------------------------------------------------------------
tBLM_ternary_chol::tBLM_ternary_chol(){
headgroup1_2= new Box2Err(); //second headgroups
headgroup2_2 = new Box2Err();
headgroup1_2->vol=330; //was 330
headgroup2_2->vol=330; //was 330
headgroup1_2->nSL=6.0012e-4; // was 6.0122e-4
headgroup2_2->nSL=6.0012e-4; // was 6.0122e-4
headgroup1_2->l=9.5;
headgroup2_2->l=9.5;
volacyllipid_2=925;
nslacyllipid_2=-2.67e-4;
volmethyllipid_2=98.8;
nslmethyllipid_2=-9.15e-5;
volchol=630;
nslchol=1.3215e-4;
fnAdjustParameters();
};
tBLM_ternary_chol::~tBLM_ternary_chol(){
delete headgroup1_2;
delete headgroup2_2;
};
void tBLM_ternary_chol::fnAdjustParameters(){
double l_ohc;
double V_ohc;
double nf_ohc_lipid, nf_ohc_lipid_2, nf_ohc_chol, nSL_ohc;
double c_s_ohc, c_A_ohc, c_V_ohc;
double l_om;
double V_om;
double nf_om_lipid, nf_om_lipid_2, nSL_om;
double c_s_om, c_A_om, c_V_om;
double l_ihc;
double V_ihc;
double nf_ihc_lipid, nf_ihc_lipid_2, nf_ihc_chol, nf_ihc_tether, nSL_ihc;
double c_s_ihc, c_A_ihc, c_V_ihc;
double l_im;
double V_im;
double nf_im_lipid, nf_im_lipid_2, nf_im_tether, nSL_im;
double c_s_im, c_A_im, c_V_im;
double V_tg;
double c_s_tg, c_A_tg, c_V_tg;
double l_EO,V_EO;
double c_s_EO, c_A_EO, c_V_EO;
double l_bME,V_bME;
double d1;
// set all sigma
//sigma=sqrt(2.4*2.4 + global_rough*global_rough);
substrate->sigma2=global_rough;
bME->sigma1=global_rough;
bME->sigma2=global_rough;
headgroup1->fnSetSigma(sigma);
headgroup1_2->fnSetSigma(sigma);
tether->sigma1=global_rough;
tether->sigma2=sigma;
tetherg->fnSetSigma(sigma);
lipid1->fnSetSigma(sigma);
methyl1->fnSetSigma(sigma);
methyl2->fnSetSigma(sigma);
lipid2->fnSetSigma(sigma);
headgroup2->fnSetSigma(sigma);
headgroup2_2->fnSetSigma(sigma);
//outer hydrocarbons
l_ohc=l_lipid2;
nf_ohc_lipid =1-nf_lipid_2-nf_chol;
nf_ohc_lipid_2=nf_lipid_2;
nf_ohc_chol=nf_chol;
V_ohc=nf_ohc_lipid*(volacyllipid-volmethyllipid)+nf_ohc_lipid_2*(volacyllipid_2-volmethyllipid_2)+nf_ohc_chol*volchol;
nSL_ohc=nf_ohc_lipid*(nslacyllipid-nslmethyllipid)+nf_ohc_lipid_2*(nslacyllipid_2-nslmethyllipid_2)+nf_ohc_chol*nslchol;
normarea=V_ohc/l_ohc;
c_s_ohc=vf_bilayer;
c_A_ohc=1;
c_V_ohc=1;
lipid2->l=l_ohc;
lipid2->vol=V_ohc;
lipid2->nSL=nSL_ohc;
lipid2->nf=c_s_ohc*c_A_ohc*c_V_ohc;
//outher methyl
nf_om_lipid =nf_ohc_lipid;
nf_om_lipid_2=nf_ohc_lipid_2;
V_om=nf_om_lipid*volmethyllipid+nf_om_lipid_2*volmethyllipid_2;
l_om=l_ohc*V_om/V_ohc;
nSL_om=nf_om_lipid*nslmethyllipid+nf_om_lipid_2*nslmethyllipid_2;
c_s_om=c_s_ohc;
c_A_om=1;
c_V_om=1;
methyl2->l=l_om;
methyl2->vol=V_om;
methyl2->nSL=nSL_om;
methyl2->nf=c_s_om*c_A_om*c_V_om;
//inner hydrocarbons
l_ihc=l_lipid1;
nf_ihc_tether=nf_tether;
nf_ihc_lipid=(1-nf_ihc_tether)*nf_ohc_lipid;
nf_ihc_lipid_2=(1-nf_ihc_tether)*nf_ohc_lipid_2;
nf_ihc_chol=(1-nf_ihc_tether)*nf_ohc_chol;
V_ihc=nf_ihc_lipid*(volacyllipid-volmethyllipid)+nf_ihc_lipid_2*(volacyllipid_2-volmethyllipid_2)+nf_ihc_chol*volchol+nf_ihc_tether*(volacyltether-volmethyltether);
nSL_ihc=nf_ihc_lipid*(nslacyllipid-nslmethyllipid)+nf_ihc_lipid_2*(nslacyllipid_2-nslmethyllipid_2)+nf_ihc_chol*nslchol+nf_ihc_tether*(nslacyltether-nslmethyltether);
c_s_ihc=vf_bilayer;
c_A_ihc=normarea*l_ihc/V_ihc;
c_V_ihc=1;
lipid1->l=l_ihc;
lipid1->vol=V_ihc;
lipid1->nSL=nSL_ihc;
lipid1->nf=c_s_ihc*c_A_ihc*c_V_ihc;
//inner methyl
nf_im_lipid=nf_ihc_lipid;
nf_im_lipid_2=nf_ihc_lipid_2;
nf_im_tether=nf_ihc_tether;
V_im=nf_im_lipid*volmethyllipid+nf_im_lipid_2*volmethyllipid_2+nf_im_tether*volmethyltether;
l_im=l_ihc*V_im/V_ihc;
nSL_im=nf_im_lipid*nslmethyllipid+nf_im_lipid_2*nslmethyllipid_2+nf_im_tether*nslmethyltether;
c_s_im=c_s_ihc;
c_A_im=c_A_ihc;
c_V_im=1;
methyl1->l=l_im;
methyl1->vol=V_im;
methyl1->nSL=nSL_im;
methyl1->nf=c_s_im*c_A_im*c_V_im;
//outer headgroups
headgroup2->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid*(1-hc_substitution_2);
headgroup2_2->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid_2*(1-hc_substitution_2);
//inner headgroups
headgroup1->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid*(1-hc_substitution_1);
headgroup1_2->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid_2*(1-hc_substitution_1);
//tether glycerol part
V_tg=tetherg->vol;
c_s_tg=c_s_ihc;
c_A_tg=c_A_ihc;
c_V_tg=nf_ihc_tether;
tetherg->l=tetherg->vol/((volacyltether-volmethyltether)/lipid1->l)/0.9;
tetherg->nf=c_s_tg*c_A_tg*c_V_tg;
//tether EO part
l_EO=l_tether;
V_EO=tether->vol;
c_s_EO=c_s_ihc;
c_A_EO=c_A_ihc;
c_V_EO=nf_ihc_tether;
tether->nf=c_s_EO*c_A_EO*c_V_EO;
tether->l=l_EO;
if ((tether->nf*tether->vol/tether->l)>normarea) {
tether->l=(tether->nf*tether->vol)/normarea;
}
l_tether=tether->l;
//bME
bME->l=5.2;
l_bME=bME->l;
headgroup1->l=9.575;
V_bME=bME->vol;
d1=headgroup1->l+bME->l-tether->l-tetherg->l;
if (d1>0) {
bME->l=bME->l-d1/2;
headgroup1->l=headgroup1->l-d1/2;
}
if ((tether->nf*tether->vol/tether->l+mult_tether*tether->nf*bME->vol/bME->l)>normarea) {
mult_tether=((normarea-tether->nf*tether->vol/tether->l)/(bME->vol/bME->l))/tether->nf;
if (mult_tether<0) {
mult_tether=0;
}
}
bME->nf=tether->nf*mult_tether; //2.333;
//substrate
substrate->vol=normarea*substrate->l;
substrate->nSL=rho_substrate*substrate->vol;
// set all lengths
bME->z=0.5*bME->l+substrate->l;
tether->z=0.5*tether->l+substrate->l;
tetherg->z=tether->z+0.5*tether->l+0.5*tetherg->l;
lipid1->z=tetherg->z+0.5*(tetherg->l+lipid1->l);
headgroup1->fnSetZ(lipid1->z-0.5*lipid1->l-0.5*headgroup1->l);
headgroup1_2->fnSetZ(lipid1->z-0.5*lipid1->l-0.5*headgroup1_2->l);
methyl1->z=lipid1->z+0.5*(lipid1->l+methyl1->l);
methyl2->z=methyl1->z+0.5*(methyl1->l+methyl2->l);
lipid2->z=methyl2->z+0.5*(methyl2->l+lipid2->l);
headgroup2->fnSetZ(lipid2->z+0.5*lipid2->l+0.5*headgroup2->l);
headgroup2_2->fnSetZ(lipid2->z+0.5*lipid2->l+0.5*headgroup2_2->l);
};
//Return value is area at position z
double tBLM_ternary_chol::fnGetArea(double dz) {
return (substrate->fnGetArea(dz)+bME->fnGetArea(dz)+tether->fnGetArea(dz)
+tetherg->fnGetArea(dz)+lipid1->fnGetArea(dz)+headgroup1->fnGetArea(dz)
+methyl1->fnGetArea(dz)+methyl2->fnGetArea(dz)+lipid2->fnGetArea(dz)
+headgroup2->fnGetArea(dz)+headgroup1_2->fnGetArea(dz)+headgroup2_2->fnGetArea(dz));
};
//get nSLD from molecular subgroups
double tBLM_ternary_chol::fnGetnSLD(double dz) {
double substratearea, bMEarea, tetherarea, tethergarea, lipid1area, headgroup1area;
double methyl1area, methyl2area, lipid2area, headgroup2area, sum;
double headgroup1_2_area, headgroup2_2_area;
substratearea=substrate->fnGetArea(dz);
bMEarea=bME->fnGetArea(dz);
tetherarea=tether->fnGetArea(dz);
tethergarea=tetherg->fnGetArea(dz);
lipid1area=lipid1->fnGetArea(dz);
headgroup1area=headgroup1->fnGetArea(dz);
headgroup1_2_area=headgroup1_2->fnGetArea(dz);
methyl1area=methyl1->fnGetArea(dz);
methyl2area=methyl2->fnGetArea(dz);
lipid2area=lipid2->fnGetArea(dz);
headgroup2area=headgroup2->fnGetArea(dz);
headgroup2_2_area=headgroup2_2->fnGetArea(dz);
sum=substratearea+bMEarea+tetherarea+tethergarea+lipid1area+headgroup1area+methyl1area
+methyl2area+lipid2area+headgroup2area+headgroup1_2_area+headgroup2_2_area;
if (sum==0) {return 0;}
else {
return (
substrate->fnGetnSLD(dz)*substratearea+
bME->fnGetnSLD(dz)*bMEarea+
tether->fnGetnSLD(dz)*tetherarea+
tetherg->fnGetnSLD(dz)*tethergarea+
headgroup1->fnGetnSLD(dz)*headgroup1area+
headgroup1_2->fnGetnSLD(dz)*headgroup1_2_area+
lipid1->fnGetnSLD(dz)*lipid1area+
methyl1->fnGetnSLD(dz)*methyl1area+
methyl2->fnGetnSLD(dz)*methyl2area+
lipid2->fnGetnSLD(dz)*lipid2area+
headgroup2->fnGetnSLD(dz)*headgroup2area+
headgroup2_2->fnGetnSLD(dz)*headgroup2_2_area
)/sum;
}
};
//Use limits of molecular subgroups
double tBLM_ternary_chol::fnGetLowerLimit() {return substrate->fnGetLowerLimit();};
double tBLM_ternary_chol::fnGetUpperLimit()
{
double a,b;
a=headgroup2->fnGetUpperLimit();
b=headgroup2_2->fnGetUpperLimit();
if (a>b) return a;
else return b;
};
double tBLM_ternary_chol::fnWriteProfile(double aArea[], double anSLD[], int dimension, double stepsize, double dMaxArea)
{
nSLDObj::fnWriteProfile(aArea,anSLD,dimension,stepsize,dMaxArea);
return normarea;
};
void tBLM_ternary_chol::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
//char *str = new char[80];
//fprintf(fp, "PC %s z %lf l %lf nf %lf \n",cName, z, l, nf);
//nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
substrate->fnWritePar2File(fp, "substrate", dimension, stepsize);
bME->fnWritePar2File(fp, "bME", dimension, stepsize);
tether->fnWritePar2File(fp, "tether", dimension, stepsize);
tetherg->fnWritePar2File(fp, "tetherg", dimension, stepsize);
headgroup1->fnWritePar2File(fp, "headgroup1", dimension, stepsize);
headgroup1_2->fnWritePar2File(fp, "headgroup1_2", dimension, stepsize);
lipid1->fnWritePar2File(fp, "lipid1", dimension, stepsize);
methyl1->fnWritePar2File(fp, "methyl1", dimension, stepsize);
methyl2->fnWritePar2File(fp, "methyl2", dimension, stepsize);
lipid2->fnWritePar2File(fp, "lipid2", dimension, stepsize);
headgroup2->fnWritePar2File(fp, "headgroup2", dimension, stepsize);
headgroup2_2->fnWritePar2File(fp, "headgroup2_2", dimension, stepsize);
fnWriteConstant(fp, "normarea", normarea, 0, dimension, stepsize);
//delete []str;
}
//------------------------------------------------------------------------------------------------------
// Lipid bilayer - quaternary system
//------------------------------------------------------------------------------------------------------
tBLM_quaternary_chol::tBLM_quaternary_chol(){
headgroup1_2= new Box2Err(); //second headgroups
headgroup2_2 = new Box2Err();
headgroup1_3 = new Box2Err();
headgroup2_3 = new Box2Err();
headgroup1_2->vol=330; //was 330
headgroup2_2->vol=330; //was 330
headgroup1_3->vol=330; //was 330
headgroup2_3->vol=330; //was 330
headgroup1_2->nSL=6.0012e-4; // was 6.0122e-4
headgroup2_2->nSL=6.0012e-4; // was 6.0122e-4
headgroup1_3->nSL=6.0012e-4; // was 6.0122e-4
headgroup2_3->nSL=6.0012e-4; // was 6.0122e-4
headgroup1_2->l=9.5;
headgroup2_2->l=9.5;
headgroup1_3->l=9.5;
headgroup2_3->l=9.5;
volacyllipid_2=925;
nslacyllipid_2=-2.67e-4;
volmethyllipid_2=98.8;
nslmethyllipid_2=-9.15e-5;
volacyllipid_3=925;
nslacyllipid_3=-2.67e-4;
volmethyllipid_3=98.8;
nslmethyllipid_3=-9.15e-5;
volchol=630;
nslchol=1.3215e-4;
fnAdjustParameters();
};
tBLM_quaternary_chol::~tBLM_quaternary_chol(){
delete headgroup1_2;
delete headgroup2_2;
delete headgroup1_3;
delete headgroup2_3;
};
void tBLM_quaternary_chol::fnAdjustParameters(){
double l_ohc;
double V_ohc;
double nf_ohc_lipid, nf_ohc_lipid_2, nf_ohc_lipid_3, nf_ohc_chol, nSL_ohc;
double c_s_ohc, c_A_ohc, c_V_ohc;
double l_om;
double V_om;
double nf_om_lipid, nf_om_lipid_2, nf_om_lipid_3, nSL_om;
double c_s_om, c_A_om, c_V_om;
double l_ihc;
double V_ihc;
double nf_ihc_lipid, nf_ihc_lipid_2, nf_ihc_lipid_3, nf_ihc_chol, nf_ihc_tether, nSL_ihc;
double c_s_ihc, c_A_ihc, c_V_ihc;
double l_im;
double V_im;
double nf_im_lipid, nf_im_lipid_2, nf_im_lipid_3, nf_im_tether, nSL_im;
double c_s_im, c_A_im, c_V_im;
double V_tg;
double c_s_tg, c_A_tg, c_V_tg;
double l_EO,V_EO;
double c_s_EO, c_A_EO, c_V_EO;
double l_bME,V_bME;
double d1;
// set all sigma
//sigma=sqrt(2.4*2.4 + global_rough*global_rough);
substrate->sigma2=global_rough;
bME->sigma1=global_rough;
bME->sigma2=global_rough;
headgroup1->fnSetSigma(sigma);
headgroup1_2->fnSetSigma(sigma);
headgroup1_3->fnSetSigma(sigma);
tether->sigma1=global_rough;
tether->sigma2=sigma;
tetherg->fnSetSigma(sigma);
lipid1->fnSetSigma(sigma);
methyl1->fnSetSigma(sigma);
methyl2->fnSetSigma(sigma);
lipid2->fnSetSigma(sigma);
headgroup2->fnSetSigma(sigma);
headgroup2_2->fnSetSigma(sigma);
headgroup2_3->fnSetSigma(sigma);
//outer hydrocarbons
l_ohc=l_lipid2;
nf_ohc_lipid =1-nf_lipid_2-nf_lipid_3-nf_chol;
nf_ohc_lipid_2=nf_lipid_2;
nf_ohc_lipid_3=nf_lipid_3;
nf_ohc_chol=nf_chol;
V_ohc=nf_ohc_lipid*(volacyllipid-volmethyllipid)+nf_ohc_lipid_2*(volacyllipid_2-volmethyllipid_2)+nf_ohc_lipid_3*(volacyllipid_3-volmethyllipid_3)+nf_ohc_chol*volchol;
nSL_ohc=nf_ohc_lipid*(nslacyllipid-nslmethyllipid)+nf_ohc_lipid_2*(nslacyllipid_2-nslmethyllipid_2)+nf_ohc_lipid_3*(nslacyllipid_3-nslmethyllipid_3)+nf_ohc_chol*nslchol;
normarea=V_ohc/l_ohc;
c_s_ohc=vf_bilayer;
c_A_ohc=1;
c_V_ohc=1;
lipid2->l=l_ohc;
lipid2->vol=V_ohc;
lipid2->nSL=nSL_ohc;
lipid2->nf=c_s_ohc*c_A_ohc*c_V_ohc;
//outher methyl
nf_om_lipid =nf_ohc_lipid;
nf_om_lipid_2=nf_ohc_lipid_2;
nf_om_lipid_3=nf_ohc_lipid_3;
V_om=nf_om_lipid*volmethyllipid+nf_om_lipid_2*volmethyllipid_2+nf_om_lipid_3*volmethyllipid_3;
l_om=l_ohc*V_om/V_ohc;
nSL_om=nf_om_lipid*nslmethyllipid+nf_om_lipid_2*nslmethyllipid_2+nf_om_lipid_3*nslmethyllipid_3;
c_s_om=c_s_ohc;
c_A_om=1;
c_V_om=1;
methyl2->l=l_om;
methyl2->vol=V_om;
methyl2->nSL=nSL_om;
methyl2->nf=c_s_om*c_A_om*c_V_om;
//inner hydrocarbons
l_ihc=l_lipid1;
nf_ihc_tether=nf_tether;
nf_ihc_lipid=(1-nf_ihc_tether)*nf_ohc_lipid;
nf_ihc_lipid_2=(1-nf_ihc_tether)*nf_ohc_lipid_2;
nf_ihc_lipid_3=(1-nf_ihc_tether)*nf_ohc_lipid_3;
nf_ihc_chol=(1-nf_ihc_tether)*nf_ohc_chol;
V_ihc=nf_ihc_lipid*(volacyllipid-volmethyllipid)+nf_ihc_lipid_2*(volacyllipid_2-volmethyllipid_2)+nf_ihc_lipid_3*(volacyllipid_3-volmethyllipid_3)+nf_ihc_chol*volchol+nf_ihc_tether*(volacyltether-volmethyltether);
nSL_ihc=nf_ihc_lipid*(nslacyllipid-nslmethyllipid)+nf_ihc_lipid_2*(nslacyllipid_2-nslmethyllipid_2)+nf_ihc_lipid_3*(nslacyllipid_3-nslmethyllipid_3)+nf_ihc_chol*nslchol+nf_ihc_tether*(nslacyltether-nslmethyltether);
c_s_ihc=vf_bilayer;
c_A_ihc=normarea*l_ihc/V_ihc;
c_V_ihc=1;
lipid1->l=l_ihc;
lipid1->vol=V_ihc;
lipid1->nSL=nSL_ihc;
lipid1->nf=c_s_ihc*c_A_ihc*c_V_ihc;
//inner methyl
nf_im_lipid=nf_ihc_lipid;
nf_im_lipid_2=nf_ihc_lipid_2;
nf_im_lipid_3=nf_ihc_lipid_3;
nf_im_tether=nf_ihc_tether;
V_im=nf_im_lipid*volmethyllipid+nf_im_lipid_2*volmethyllipid_2+nf_im_lipid_3*volmethyllipid_3+nf_im_tether*volmethyltether;
l_im=l_ihc*V_im/V_ihc;
nSL_im=nf_im_lipid*nslmethyllipid+nf_im_lipid_2*nslmethyllipid_2+nf_im_lipid_3*nslmethyllipid_3+nf_im_tether*nslmethyltether;
c_s_im=c_s_ihc;
c_A_im=c_A_ihc;
c_V_im=1;
methyl1->l=l_im;
methyl1->vol=V_im;
methyl1->nSL=nSL_im;
methyl1->nf=c_s_im*c_A_im*c_V_im;
//outer headgroups
headgroup2->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid*(1-hc_substitution_2);
headgroup2_2->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid_2*(1-hc_substitution_2);
headgroup2_3->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid_3*(1-hc_substitution_2);
//inner headgroups
headgroup1->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid*(1-hc_substitution_1);
headgroup1_2->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid_2*(1-hc_substitution_1);
headgroup1_3->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid_3*(1-hc_substitution_1);
//tether glycerol part
V_tg=tetherg->vol;
c_s_tg=c_s_ihc;
c_A_tg=c_A_ihc;
c_V_tg=nf_ihc_tether;
tetherg->l=tetherg->vol/((volacyltether-volmethyltether)/lipid1->l)/0.9;
tetherg->nf=c_s_tg*c_A_tg*c_V_tg;
//tether EO part
l_EO=l_tether;
V_EO=tether->vol;
c_s_EO=c_s_ihc;
c_A_EO=c_A_ihc;
c_V_EO=nf_ihc_tether;
tether->nf=c_s_EO*c_A_EO*c_V_EO;
tether->l=l_EO;
if ((tether->nf*tether->vol/tether->l)>normarea) {
tether->l=(tether->nf*tether->vol)/normarea;
}
l_tether=tether->l;
//bME
bME->l=5.2;
l_bME=bME->l;
headgroup1->l=9.575;
V_bME=bME->vol;
d1=headgroup1->l+bME->l-tether->l-tetherg->l;
if (d1>0) {
bME->l=bME->l-d1/2;
headgroup1->l=headgroup1->l-d1/2;
}
if ((tether->nf*tether->vol/tether->l+mult_tether*tether->nf*bME->vol/bME->l)>normarea) {
mult_tether=((normarea-tether->nf*tether->vol/tether->l)/(bME->vol/bME->l))/tether->nf;
if (mult_tether<0) {
mult_tether=0;
}
}
bME->nf=tether->nf*mult_tether; //2.333;
//substrate
substrate->vol=normarea*substrate->l;
substrate->nSL=rho_substrate*substrate->vol;
// set all lengths
bME->z=0.5*bME->l+substrate->l;
tether->z=0.5*tether->l+substrate->l;
tetherg->z=tether->z+0.5*tether->l+0.5*tetherg->l;
lipid1->z=tetherg->z+0.5*(tetherg->l+lipid1->l);
headgroup1->fnSetZ(lipid1->z-0.5*lipid1->l-0.5*headgroup1->l);
headgroup1_2->fnSetZ(lipid1->z-0.5*lipid1->l-0.5*headgroup1_2->l);
headgroup1_3->fnSetZ(lipid1->z-0.5*lipid1->l-0.5*headgroup1_3->l);
methyl1->z=lipid1->z+0.5*(lipid1->l+methyl1->l);
methyl2->z=methyl1->z+0.5*(methyl1->l+methyl2->l);
lipid2->z=methyl2->z+0.5*(methyl2->l+lipid2->l);
headgroup2->fnSetZ(lipid2->z+0.5*lipid2->l+0.5*headgroup2->l);
headgroup2_2->fnSetZ(lipid2->z+0.5*lipid2->l+0.5*headgroup2_2->l);
headgroup2_3->fnSetZ(lipid2->z+0.5*lipid2->l+0.5*headgroup2_3->l);
};
//Return value is area at position z
double tBLM_quaternary_chol::fnGetArea(double dz) {
return (substrate->fnGetArea(dz)+bME->fnGetArea(dz)+tether->fnGetArea(dz)
+tetherg->fnGetArea(dz)+lipid1->fnGetArea(dz)+headgroup1->fnGetArea(dz)
+methyl1->fnGetArea(dz)+methyl2->fnGetArea(dz)+lipid2->fnGetArea(dz)
+headgroup2->fnGetArea(dz)+headgroup1_2->fnGetArea(dz)+headgroup2_2->fnGetArea(dz)
+headgroup1_3->fnGetArea(dz)+headgroup2_3->fnGetArea(dz));
};
//get nSLD from molecular subgroups
double tBLM_quaternary_chol::fnGetnSLD(double dz) {
double substratearea, bMEarea, tetherarea, tethergarea, lipid1area, headgroup1area;
double methyl1area, methyl2area, lipid2area, headgroup2area, sum;
double headgroup1_2_area, headgroup2_2_area, headgroup1_3_area, headgroup2_3_area;
substratearea=substrate->fnGetArea(dz);
bMEarea=bME->fnGetArea(dz);
tetherarea=tether->fnGetArea(dz);
tethergarea=tetherg->fnGetArea(dz);
lipid1area=lipid1->fnGetArea(dz);
headgroup1area=headgroup1->fnGetArea(dz);
headgroup1_2_area=headgroup1_2->fnGetArea(dz);
headgroup1_3_area=headgroup1_3->fnGetArea(dz);
methyl1area=methyl1->fnGetArea(dz);
methyl2area=methyl2->fnGetArea(dz);
lipid2area=lipid2->fnGetArea(dz);
headgroup2area=headgroup2->fnGetArea(dz);
headgroup2_2_area=headgroup2_2->fnGetArea(dz);
headgroup2_3_area=headgroup2_3->fnGetArea(dz);
sum=substratearea+bMEarea+tetherarea+tethergarea+lipid1area+headgroup1area+methyl1area
+methyl2area+lipid2area+headgroup2area+headgroup1_2_area+headgroup2_2_area+headgroup1_3_area+headgroup2_3_area;
if (sum==0) {return 0;}
else {
return (
substrate->fnGetnSLD(dz)*substratearea+
bME->fnGetnSLD(dz)*bMEarea+
tether->fnGetnSLD(dz)*tetherarea+
tetherg->fnGetnSLD(dz)*tethergarea+
headgroup1->fnGetnSLD(dz)*headgroup1area+
headgroup1_2->fnGetnSLD(dz)*headgroup1_2_area+
headgroup1_3->fnGetnSLD(dz)*headgroup1_3_area+
lipid1->fnGetnSLD(dz)*lipid1area+
methyl1->fnGetnSLD(dz)*methyl1area+
methyl2->fnGetnSLD(dz)*methyl2area+
lipid2->fnGetnSLD(dz)*lipid2area+
headgroup2->fnGetnSLD(dz)*headgroup2area+
headgroup2_2->fnGetnSLD(dz)*headgroup2_2_area+
headgroup2_3->fnGetnSLD(dz)*headgroup2_3_area
)/sum;
}
};
//Use limits of molecular subgroups
double tBLM_quaternary_chol::fnGetLowerLimit() {return substrate->fnGetLowerLimit();};
double tBLM_quaternary_chol::fnGetUpperLimit()
{
double a,b,c;
a=headgroup2->fnGetUpperLimit();
b=headgroup2_2->fnGetUpperLimit();
c=headgroup2_3->fnGetUpperLimit();
if (a>b) {
if (a>c) return a;
else return c;}
else {
if (b>c) return b;
else return c;}
};
double tBLM_quaternary_chol::fnWriteProfile(double aArea[], double anSLD[], int dimension, double stepsize, double dMaxArea)
{
nSLDObj::fnWriteProfile(aArea,anSLD,dimension,stepsize,dMaxArea);
return normarea;
};
void tBLM_quaternary_chol::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
//char *str = new char[80];
//fprintf(fp, "PC %s z %lf l %lf nf %lf \n",cName, z, l, nf);
//nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
substrate->fnWritePar2File(fp, "substrate", dimension, stepsize);
bME->fnWritePar2File(fp, "bME", dimension, stepsize);
tether->fnWritePar2File(fp, "tether", dimension, stepsize);
tetherg->fnWritePar2File(fp, "tetherg", dimension, stepsize);
headgroup1->fnWritePar2File(fp, "headgroup1", dimension, stepsize);
headgroup1_2->fnWritePar2File(fp, "headgroup1_2", dimension, stepsize);
headgroup1_3->fnWritePar2File(fp, "headgroup1_3", dimension, stepsize);
lipid1->fnWritePar2File(fp, "lipid1", dimension, stepsize);
methyl1->fnWritePar2File(fp, "methyl1", dimension, stepsize);
methyl2->fnWritePar2File(fp, "methyl2", dimension, stepsize);
lipid2->fnWritePar2File(fp, "lipid2", dimension, stepsize);
headgroup2->fnWritePar2File(fp, "headgroup2", dimension, stepsize);
headgroup2_2->fnWritePar2File(fp, "headgroup2_2", dimension, stepsize);
headgroup2_3->fnWritePar2File(fp, "headgroup2_3", dimension, stepsize);
fnWriteConstant(fp, "normarea", normarea, 0, dimension, stepsize);
//delete []str;
}
//------------------------------------------------------------------------------------------------------
// Lipid bilayer - quaternary system with domains
//------------------------------------------------------------------------------------------------------
tBLM_quaternary_chol_domain::tBLM_quaternary_chol_domain(){
headgroup1_2 = new Box2Err(); //second headgroups
headgroup2_2 = new Box2Err();
headgroup1_3 = new Box2Err();
headgroup2_3 = new Box2Err();
headgroup1_domain = new PCm();
lipid1_domain = new Box2Err();
methyl1_domain = new Box2Err();
methyl2_domain = new Box2Err();
lipid2_domain = new Box2Err();
headgroup2_domain = new PC();
headgroup1_2_domain = new Box2Err();
headgroup2_2_domain = new Box2Err();
headgroup1_3_domain = new Box2Err();
headgroup2_3_domain = new Box2Err();
tetherg_domain = new Box2Err();
tether_domain = new Box2Err();
headgroup1_2->vol=330; //was 330
headgroup2_2->vol=330; //was 330
headgroup1_3->vol=330; //was 330
headgroup2_3->vol=330; //was 330
headgroup1_2->nSL=6.0012e-4; // was 6.0122e-4
headgroup2_2->nSL=6.0012e-4; // was 6.0122e-4
headgroup1_3->nSL=6.0012e-4; // was 6.0122e-4
headgroup2_3->nSL=6.0012e-4; // was 6.0122e-4
headgroup1_2->l=9.5;
headgroup2_2->l=9.5;
headgroup1_3->l=9.5;
headgroup2_3->l=9.5;
headgroup1_2_domain->vol=330; //was 330
headgroup2_2_domain->vol=330; //was 330
headgroup1_3_domain->vol=330; //was 330
headgroup2_3_domain->vol=330; //was 330
headgroup1_2_domain->nSL=6.0012e-4; // was 6.0122e-4
headgroup2_2_domain->nSL=6.0012e-4; // was 6.0122e-4
headgroup1_3_domain->nSL=6.0012e-4; // was 6.0122e-4
headgroup2_3_domain->nSL=6.0012e-4; // was 6.0122e-4
headgroup1_2_domain->l=9.5;
headgroup2_2_domain->l=9.5;
headgroup1_3_domain->l=9.5;
headgroup2_3_domain->l=9.5;
volacyllipid_2=925;
nslacyllipid_2=-2.67e-4;
volmethyllipid_2=98.8;
nslmethyllipid_2=-9.15e-5;
volacyllipid_3=925;
nslacyllipid_3=-2.67e-4;
volmethyllipid_3=98.8;
nslmethyllipid_3=-9.15e-5;
volchol=630;
nslchol=1.3215e-4;
fnAdjustParameters();
};
tBLM_quaternary_chol_domain::~tBLM_quaternary_chol_domain(){
delete headgroup1_2;
delete headgroup2_2;
delete headgroup1_3;
delete headgroup2_3;
delete headgroup1_domain;
delete lipid1_domain;
delete methyl1_domain;
delete methyl2_domain;
delete lipid2_domain;
delete headgroup2_domain;
delete headgroup1_2_domain;
delete headgroup2_2_domain;
delete headgroup1_3_domain;
delete headgroup2_3_domain;
delete tether_domain;
delete tetherg_domain;
};
void tBLM_quaternary_chol_domain::fnAdjustParameters(){
double l_ohc;
double V_ohc;
double nf_ohc_lipid, nf_ohc_lipid_2, nf_ohc_lipid_3, nf_ohc_chol, nSL_ohc;
double c_s_ohc, c_A_ohc, c_V_ohc;
double l_om;
double V_om;
double nf_om_lipid, nf_om_lipid_2, nf_om_lipid_3, nSL_om;
double c_s_om, c_A_om, c_V_om;
double l_ihc;
double V_ihc;
double nf_ihc_lipid, nf_ihc_lipid_2, nf_ihc_lipid_3, nf_ihc_chol, nf_ihc_tether, nSL_ihc;
double c_s_ihc, c_A_ihc, c_V_ihc;
double l_im;
double V_im;
double nf_im_lipid, nf_im_lipid_2, nf_im_lipid_3, nf_im_tether, nSL_im;
double c_s_im, c_A_im, c_V_im;
double V_tg;
double c_s_tg, c_A_tg, c_V_tg;
double l_EO,V_EO;
double c_s_EO, c_A_EO, c_V_EO;
double l_bME,V_bME;
double d1;
// set all sigma
//sigma=sqrt(2.4*2.4 + global_rough*global_rough);
substrate->sigma2=global_rough;
bME->sigma1=global_rough;
bME->sigma2=global_rough;
headgroup1->fnSetSigma(sigma);
headgroup1_2->fnSetSigma(sigma);
headgroup1_3->fnSetSigma(sigma);
tether->sigma1=global_rough;
tether->sigma2=sigma;
tetherg->fnSetSigma(sigma);
lipid1->fnSetSigma(sigma);
methyl1->fnSetSigma(sigma);
methyl2->fnSetSigma(sigma);
lipid2->fnSetSigma(sigma);
headgroup2->fnSetSigma(sigma);
headgroup2_2->fnSetSigma(sigma);
headgroup2_3->fnSetSigma(sigma);
headgroup1_domain->fnSetSigma(sigma);
headgroup1_2_domain->fnSetSigma(sigma);
headgroup1_3_domain->fnSetSigma(sigma);
lipid1_domain->fnSetSigma(sigma);
methyl1_domain->fnSetSigma(sigma);
methyl2_domain->fnSetSigma(sigma);
lipid2_domain->fnSetSigma(sigma);
headgroup2_domain->fnSetSigma(sigma);
headgroup2_2_domain->fnSetSigma(sigma);
headgroup2_3_domain->fnSetSigma(sigma);
tether_domain->sigma1=global_rough;
tether_domain->sigma2=sigma;
tetherg_domain->fnSetSigma(sigma);
//----------------first domain----------------
//outer hydrocarbons
l_ohc=l_lipid2;
nf_ohc_lipid =1-nf_lipid_2-nf_lipid_3-nf_chol;
nf_ohc_lipid_2=nf_lipid_2;
nf_ohc_lipid_3=nf_lipid_3;
nf_ohc_chol=nf_chol;
V_ohc=nf_ohc_lipid*(volacyllipid-volmethyllipid)+nf_ohc_lipid_2*(volacyllipid_2-volmethyllipid_2)+nf_ohc_lipid_3*(volacyllipid_3-volmethyllipid_3)+nf_ohc_chol*volchol;
nSL_ohc=nf_ohc_lipid*(nslacyllipid-nslmethyllipid)+nf_ohc_lipid_2*(nslacyllipid_2-nslmethyllipid_2)+nf_ohc_lipid_3*(nslacyllipid_3-nslmethyllipid_3)+nf_ohc_chol*nslchol;
normarea=V_ohc/l_ohc;
c_s_ohc=vf_bilayer;
c_A_ohc=1;
c_V_ohc=1;
lipid2->l=l_ohc;
lipid2->vol=V_ohc;
lipid2->nSL=nSL_ohc;
lipid2->nf=c_s_ohc*c_A_ohc*c_V_ohc*(1-frac_domain);
//outher methyl
nf_om_lipid =nf_ohc_lipid;
nf_om_lipid_2=nf_ohc_lipid_2;
nf_om_lipid_3=nf_ohc_lipid_3;
V_om=nf_om_lipid*volmethyllipid+nf_om_lipid_2*volmethyllipid_2+nf_om_lipid_3*volmethyllipid_3;
l_om=l_ohc*V_om/V_ohc;
nSL_om=nf_om_lipid*nslmethyllipid+nf_om_lipid_2*nslmethyllipid_2+nf_om_lipid_3*nslmethyllipid_3;
c_s_om=c_s_ohc;
c_A_om=1;
c_V_om=1;
methyl2->l=l_om;
methyl2->vol=V_om;
methyl2->nSL=nSL_om;
methyl2->nf=c_s_om*c_A_om*c_V_om*(1-frac_domain);
//inner hydrocarbons
l_ihc=l_lipid1;
nf_ihc_tether=nf_tether;
nf_ihc_lipid=(1-nf_ihc_tether)*nf_ohc_lipid;
nf_ihc_lipid_2=(1-nf_ihc_tether)*nf_ohc_lipid_2;
nf_ihc_lipid_3=(1-nf_ihc_tether)*nf_ohc_lipid_3;
nf_ihc_chol=(1-nf_ihc_tether)*nf_ohc_chol;
V_ihc=nf_ihc_lipid*(volacyllipid-volmethyllipid)+nf_ihc_lipid_2*(volacyllipid_2-volmethyllipid_2)+nf_ihc_lipid_3*(volacyllipid_3-volmethyllipid_3)+nf_ihc_chol*volchol+nf_ihc_tether*(volacyltether-volmethyltether);
nSL_ihc=nf_ihc_lipid*(nslacyllipid-nslmethyllipid)+nf_ihc_lipid_2*(nslacyllipid_2-nslmethyllipid_2)+nf_ihc_lipid_3*(nslacyllipid_3-nslmethyllipid_3)+nf_ihc_chol*nslchol+nf_ihc_tether*(nslacyltether-nslmethyltether);
c_s_ihc=vf_bilayer;
c_A_ihc=normarea*l_ihc/V_ihc;
c_V_ihc=1;
lipid1->l=l_ihc;
lipid1->vol=V_ihc;
lipid1->nSL=nSL_ihc;
lipid1->nf=c_s_ihc*c_A_ihc*c_V_ihc*(1-frac_domain);
//inner methyl
nf_im_lipid=nf_ihc_lipid;
nf_im_lipid_2=nf_ihc_lipid_2;
nf_im_lipid_3=nf_ihc_lipid_3;
nf_im_tether=nf_ihc_tether;
V_im=nf_im_lipid*volmethyllipid+nf_im_lipid_2*volmethyllipid_2+nf_im_lipid_3*volmethyllipid_3+nf_im_tether*volmethyltether;
l_im=l_ihc*V_im/V_ihc;
nSL_im=nf_im_lipid*nslmethyllipid+nf_im_lipid_2*nslmethyllipid_2+nf_im_lipid_3*nslmethyllipid_3+nf_im_tether*nslmethyltether;
c_s_im=c_s_ihc;
c_A_im=c_A_ihc;
c_V_im=1;
methyl1->l=l_im;
methyl1->vol=V_im;
methyl1->nSL=nSL_im;
methyl1->nf=c_s_im*c_A_im*c_V_im*(1-frac_domain);
//outer headgroups
headgroup2->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid*(1-hc_substitution_2)*(1-frac_domain);
headgroup2_2->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid_2*(1-hc_substitution_2)*(1-frac_domain);
headgroup2_3->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid_3*(1-hc_substitution_2)*(1-frac_domain);
//inner headgroups
headgroup1->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid*(1-hc_substitution_1)*(1-frac_domain);
headgroup1_2->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid_2*(1-hc_substitution_1)*(1-frac_domain);
headgroup1_3->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid_3*(1-hc_substitution_1)*(1-frac_domain);
//tether glycerol part
V_tg=tetherg->vol;
c_s_tg=c_s_ihc;
c_A_tg=c_A_ihc;
c_V_tg=nf_ihc_tether;
tetherg->l=tetherg->vol/((volacyltether-volmethyltether)/lipid1->l)/0.9;
tetherg->nf=c_s_tg*c_A_tg*c_V_tg;
//tether EO part
l_EO=l_tether;
V_EO=tether->vol;
c_s_EO=c_s_ihc;
c_A_EO=c_A_ihc;
c_V_EO=nf_ihc_tether;
tether->nf=c_s_EO*c_A_EO*c_V_EO;
tether->l=l_EO;
if ((tether->nf*tether->vol/tether->l)>normarea) {
tether->l=(tether->nf*tether->vol)/normarea;
}
l_tether=tether->l;
//------------second domain--------------------
//outer hydrocarbons
l_ohc=l_lipid2_domain;
nf_ohc_lipid =1-nf_lipid_2_domain-nf_lipid_3_domain-nf_chol_domain;
nf_ohc_lipid_2=nf_lipid_2_domain;
nf_ohc_lipid_3=nf_lipid_3_domain;
nf_ohc_chol=nf_chol_domain;
V_ohc=nf_ohc_lipid*(volacyllipid-volmethyllipid)+nf_ohc_lipid_2*(volacyllipid_2-volmethyllipid_2)+nf_ohc_lipid_3*(volacyllipid_3-volmethyllipid_3)+nf_ohc_chol*volchol;
nSL_ohc=nf_ohc_lipid*(nslacyllipid-nslmethyllipid)+nf_ohc_lipid_2*(nslacyllipid_2-nslmethyllipid_2)+nf_ohc_lipid_3*(nslacyllipid_3-nslmethyllipid_3)+nf_ohc_chol*nslchol;
normarea_domain=V_ohc/l_ohc;
c_s_ohc=vf_bilayer;
c_A_ohc=1;
c_V_ohc=1;
lipid2_domain->l=l_ohc;
lipid2_domain->vol=V_ohc;
lipid2_domain->nSL=nSL_ohc;
lipid2_domain->nf=c_s_ohc*c_A_ohc*c_V_ohc*frac_domain;
//outher methyl
nf_om_lipid =nf_ohc_lipid;
nf_om_lipid_2=nf_ohc_lipid_2;
nf_om_lipid_3=nf_ohc_lipid_3;
V_om=nf_om_lipid*volmethyllipid+nf_om_lipid_2*volmethyllipid_2+nf_om_lipid_3*volmethyllipid_3;
l_om=l_ohc*V_om/V_ohc;
nSL_om=nf_om_lipid*nslmethyllipid+nf_om_lipid_2*nslmethyllipid_2+nf_om_lipid_3*nslmethyllipid_3;
c_s_om=c_s_ohc;
c_A_om=1;
c_V_om=1;
methyl2_domain->l=l_om;
methyl2_domain->vol=V_om;
methyl2_domain->nSL=nSL_om;
methyl2_domain->nf=c_s_om*c_A_om*c_V_om*frac_domain;
//inner hydrocarbons
l_ihc=l_lipid1_domain;
nf_ihc_tether=nf_tether*l_lipid1/l_lipid1_domain;
nf_ihc_lipid=(1-nf_ihc_tether)*nf_ohc_lipid;
nf_ihc_lipid_2=(1-nf_ihc_tether)*nf_ohc_lipid_2;
nf_ihc_lipid_3=(1-nf_ihc_tether)*nf_ohc_lipid_3;
nf_ihc_chol=(1-nf_ihc_tether)*nf_ohc_chol;
V_ihc=nf_ihc_lipid*(volacyllipid-volmethyllipid)+nf_ihc_lipid_2*(volacyllipid_2-volmethyllipid_2)+nf_ihc_lipid_3*(volacyllipid_3-volmethyllipid_3)+nf_ihc_chol*volchol+nf_ihc_tether*(volacyltether-volmethyltether);
nSL_ihc=nf_ihc_lipid*(nslacyllipid-nslmethyllipid)+nf_ihc_lipid_2*(nslacyllipid_2-nslmethyllipid_2)+nf_ihc_lipid_3*(nslacyllipid_3-nslmethyllipid_3)+nf_ihc_chol*nslchol+nf_ihc_tether*(nslacyltether-nslmethyltether);
c_s_ihc=vf_bilayer;
c_A_ihc=normarea_domain*l_ihc/V_ihc;
c_V_ihc=1;
lipid1_domain->l=l_ihc;
lipid1_domain->vol=V_ihc;
lipid1_domain->nSL=nSL_ihc;
lipid1_domain->nf=c_s_ihc*c_A_ihc*c_V_ihc*frac_domain;
//inner methyl
nf_im_lipid=nf_ihc_lipid;
nf_im_lipid_2=nf_ihc_lipid_2;
nf_im_lipid_3=nf_ihc_lipid_3;
nf_im_tether=nf_ihc_tether;
V_im=nf_im_lipid*volmethyllipid+nf_im_lipid_2*volmethyllipid_2+nf_im_lipid_3*volmethyllipid_3+nf_im_tether*volmethyltether;
l_im=l_ihc*V_im/V_ihc;
nSL_im=nf_im_lipid*nslmethyllipid+nf_im_lipid_2*nslmethyllipid_2+nf_im_lipid_3*nslmethyllipid_3+nf_im_tether*nslmethyltether;
c_s_im=c_s_ihc;
c_A_im=c_A_ihc;
c_V_im=1;
methyl1_domain->l=l_im;
methyl1_domain->vol=V_im;
methyl1_domain->nSL=nSL_im;
methyl1_domain->nf=c_s_im*c_A_im*c_V_im*frac_domain;
//outer headgroups
headgroup2_domain->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid*(1-hc_substitution_2)*frac_domain;
headgroup2_2_domain->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid_2*(1-hc_substitution_2)*frac_domain;
headgroup2_3_domain->nf=c_s_ohc*c_A_ohc*nf_ohc_lipid_3*(1-hc_substitution_2)*frac_domain;
//inner headgroups
headgroup1_domain->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid*(1-hc_substitution_1)*frac_domain;
headgroup1_2_domain->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid_2*(1-hc_substitution_1)*frac_domain;
headgroup1_3_domain->nf=c_s_ihc*c_A_ihc*nf_ihc_lipid_3*(1-hc_substitution_1)*frac_domain;
//tether glycerol part
V_tg=tetherg_domain->vol;
c_s_tg=c_s_ihc;
c_A_tg=c_A_ihc;
c_V_tg=nf_ihc_tether;
tetherg_domain->l=tetherg->vol/((volacyltether-volmethyltether)/lipid1_domain->l)/0.9;
tetherg_domain->nf=c_s_tg*c_A_tg*c_V_tg;
//tether EO part
l_EO=l_tether_domain;
V_EO=tether_domain->vol;
c_s_EO=c_s_ihc;
c_A_EO=c_A_ihc;
c_V_EO=nf_ihc_tether;
tether_domain->nf=c_s_EO*c_A_EO*c_V_EO;
tether_domain->l=l_EO;
if ((tether_domain->nf*tether->vol/tether_domain->l)>normarea_domain) {
tether_domain->l=(tether_domain->nf*tether_domain->vol)/normarea_domain;
}
l_tether_domain=tether_domain->l;
//-------------substrate----------------
//bME
bME->l=5.2;
l_bME=bME->l;
headgroup1->l=9.575;
V_bME=bME->vol;
bME->nf=((1-frac_domain)*tether->nf+frac_domain*tether_domain->nf)*mult_tether; //2.333;
d1=headgroup1->l+bME->l-tether->l-tetherg->l;
if (d1>0) {
bME->l=bME->l-d1/2;
headgroup1->l=headgroup1->l-d1/2;
}
if ((tether->nf*tether->vol/tether->l+mult_tether*tether->nf*bME->vol/bME->l)>normarea) {
mult_tether=((normarea-tether->nf*tether->vol/tether->l)/(bME->vol/bME->l))/tether->nf;
if (mult_tether<0) {
mult_tether=0;
}
}
bME->nf=tether->nf*mult_tether; //2.333;
//substrate
substrate->vol=((1-frac_domain)*normarea+frac_domain*normarea_domain)*substrate->l;
substrate->nSL=rho_substrate*substrate->vol;
// set all lengths
bME->z=0.5*bME->l+substrate->l;
tether->z=0.5*tether->l+substrate->l;
tetherg->z=tether->z+0.5*tether->l+0.5*tetherg->l;
lipid1->z=tetherg->z+0.5*(tetherg->l+lipid1->l);
headgroup1->fnSetZ(lipid1->z-0.5*lipid1->l-0.5*headgroup1->l);
headgroup1_2->fnSetZ(lipid1->z-0.5*lipid1->l-0.5*headgroup1_2->l);
headgroup1_3->fnSetZ(lipid1->z-0.5*lipid1->l-0.5*headgroup1_3->l);
methyl1->z=lipid1->z+0.5*(lipid1->l+methyl1->l);
methyl2->z=methyl1->z+0.5*(methyl1->l+methyl2->l);
lipid2->z=methyl2->z+0.5*(methyl2->l+lipid2->l);
headgroup2->fnSetZ(lipid2->z+0.5*lipid2->l+0.5*headgroup2->l);
headgroup2_2->fnSetZ(lipid2->z+0.5*lipid2->l+0.5*headgroup2_2->l);
headgroup2_3->fnSetZ(lipid2->z+0.5*lipid2->l+0.5*headgroup2_3->l);
tether_domain->z=0.5*tether_domain->l+substrate->l;
tetherg_domain->z=tether_domain->z+0.5*tether_domain->l+0.5*tetherg_domain->l;
lipid1_domain->z=tetherg_domain->z+0.5*(tetherg_domain->l+lipid1_domain->l);
headgroup1_domain->fnSetZ(lipid1_domain->z-0.5*lipid1_domain->l-0.5*headgroup1_domain->l);
headgroup1_2_domain->fnSetZ(lipid1_domain->z-0.5*lipid1_domain->l-0.5*headgroup1_2_domain->l);
headgroup1_3_domain->fnSetZ(lipid1_domain->z-0.5*lipid1_domain->l-0.5*headgroup1_3_domain->l);
methyl1_domain->z=lipid1_domain->z+0.5*(lipid1_domain->l+methyl1_domain->l);
methyl2_domain->z=methyl1_domain->z+0.5*(methyl1_domain->l+methyl2_domain->l);
lipid2_domain->z=methyl2_domain->z+0.5*(methyl2_domain->l+lipid2_domain->l);
headgroup2_domain->fnSetZ(lipid2_domain->z+0.5*lipid2_domain->l+0.5*headgroup2_domain->l);
headgroup2_2_domain->fnSetZ(lipid2_domain->z+0.5*lipid2_domain->l+0.5*headgroup2_2_domain->l);
headgroup2_3_domain->fnSetZ(lipid2_domain->z+0.5*lipid2_domain->l+0.5*headgroup2_3_domain->l);
};
//Return value is area at position z
double tBLM_quaternary_chol_domain::fnGetArea(double dz) {
return (substrate->fnGetArea(dz)+bME->fnGetArea(dz)+tether->fnGetArea(dz)
+tetherg->fnGetArea(dz)+lipid1->fnGetArea(dz)+headgroup1->fnGetArea(dz)
+methyl1->fnGetArea(dz)+methyl2->fnGetArea(dz)+lipid2->fnGetArea(dz)
+headgroup2->fnGetArea(dz)+headgroup1_2->fnGetArea(dz)+headgroup2_2->fnGetArea(dz)
+headgroup1_3->fnGetArea(dz)+headgroup2_3->fnGetArea(dz)+tether_domain->fnGetArea(dz)
+tetherg_domain->fnGetArea(dz)+lipid1_domain->fnGetArea(dz)+headgroup1_domain->fnGetArea(dz)
+methyl1_domain->fnGetArea(dz)+methyl2_domain->fnGetArea(dz)+lipid2_domain->fnGetArea(dz)
+headgroup2_domain->fnGetArea(dz)+headgroup1_2_domain->fnGetArea(dz)+headgroup2_2_domain->fnGetArea(dz)
+headgroup1_3_domain->fnGetArea(dz)+headgroup2_3_domain->fnGetArea(dz));
};
//get nSLD from molecular subgroups
double tBLM_quaternary_chol_domain::fnGetnSLD(double dz) {
double substratearea, bMEarea, tetherarea, tethergarea, lipid1area, headgroup1area;
double methyl1area, methyl2area, lipid2area, headgroup2area, sum;
double headgroup1_2_area, headgroup2_2_area, headgroup1_3_area, headgroup2_3_area;
double tetherarea_domain, tethergarea_domain, lipid1area_domain, headgroup1area_domain;
double methyl1area_domain, methyl2area_domain, lipid2area_domain, headgroup2area_domain;
double headgroup1_2_area_domain, headgroup2_2_area_domain, headgroup1_3_area_domain, headgroup2_3_area_domain;
substratearea=substrate->fnGetArea(dz);
bMEarea=bME->fnGetArea(dz);
tetherarea=tether->fnGetArea(dz);
tethergarea=tetherg->fnGetArea(dz);
lipid1area=lipid1->fnGetArea(dz);
headgroup1area=headgroup1->fnGetArea(dz);
headgroup1_2_area=headgroup1_2->fnGetArea(dz);
headgroup1_3_area=headgroup1_3->fnGetArea(dz);
methyl1area=methyl1->fnGetArea(dz);
methyl2area=methyl2->fnGetArea(dz);
lipid2area=lipid2->fnGetArea(dz);
headgroup2area=headgroup2->fnGetArea(dz);
headgroup2_2_area=headgroup2_2->fnGetArea(dz);
headgroup2_3_area=headgroup2_3->fnGetArea(dz);
tetherarea_domain=tether_domain->fnGetArea(dz);
tethergarea_domain=tetherg_domain->fnGetArea(dz);
lipid1area_domain=lipid1_domain->fnGetArea(dz);
headgroup1area_domain=headgroup1_domain->fnGetArea(dz);
headgroup1_2_area_domain=headgroup1_2_domain->fnGetArea(dz);
headgroup1_3_area_domain=headgroup1_3_domain->fnGetArea(dz);
methyl1area_domain=methyl1_domain->fnGetArea(dz);
methyl2area_domain=methyl2_domain->fnGetArea(dz);
lipid2area_domain=lipid2_domain->fnGetArea(dz);
headgroup2area_domain=headgroup2_domain->fnGetArea(dz);
headgroup2_2_area_domain=headgroup2_2_domain->fnGetArea(dz);
headgroup2_3_area_domain=headgroup2_3_domain->fnGetArea(dz);
sum=substratearea+bMEarea+tetherarea+tethergarea+lipid1area+headgroup1area+methyl1area
+methyl2area+lipid2area+headgroup2area+headgroup1_2_area+headgroup2_2_area+headgroup1_3_area+headgroup2_3_area+
tetherarea_domain+tethergarea_domain+lipid1area_domain+headgroup1area_domain+methyl1area_domain
+methyl2area_domain+lipid2area_domain+headgroup2area_domain+headgroup1_2_area_domain+headgroup2_2_area_domain
+headgroup1_3_area_domain+headgroup2_3_area_domain;
if (sum==0) {return 0;}
else {
return (
substrate->fnGetnSLD(dz)*substratearea+
bME->fnGetnSLD(dz)*bMEarea+
tether->fnGetnSLD(dz)*tetherarea+
tetherg->fnGetnSLD(dz)*tethergarea+
headgroup1->fnGetnSLD(dz)*headgroup1area+
headgroup1_2->fnGetnSLD(dz)*headgroup1_2_area+
headgroup1_3->fnGetnSLD(dz)*headgroup1_3_area+
lipid1->fnGetnSLD(dz)*lipid1area+
methyl1->fnGetnSLD(dz)*methyl1area+
methyl2->fnGetnSLD(dz)*methyl2area+
lipid2->fnGetnSLD(dz)*lipid2area+
headgroup2->fnGetnSLD(dz)*headgroup2area+
headgroup2_2->fnGetnSLD(dz)*headgroup2_2_area+
headgroup2_3->fnGetnSLD(dz)*headgroup2_3_area+
tether_domain->fnGetnSLD(dz)*tetherarea_domain+
tetherg_domain->fnGetnSLD(dz)*tethergarea_domain+
headgroup1_domain->fnGetnSLD(dz)*headgroup1area_domain+
headgroup1_2_domain->fnGetnSLD(dz)*headgroup1_2_area_domain+
headgroup1_3_domain->fnGetnSLD(dz)*headgroup1_3_area_domain+
lipid1_domain->fnGetnSLD(dz)*lipid1area_domain+
methyl1_domain->fnGetnSLD(dz)*methyl1area_domain+
methyl2_domain->fnGetnSLD(dz)*methyl2area_domain+
lipid2_domain->fnGetnSLD(dz)*lipid2area_domain+
headgroup2_domain->fnGetnSLD(dz)*headgroup2area_domain+
headgroup2_2_domain->fnGetnSLD(dz)*headgroup2_2_area_domain+
headgroup2_3_domain->fnGetnSLD(dz)*headgroup2_3_area_domain
)/sum;
}
};
//Use limits of molecular subgroups
double tBLM_quaternary_chol_domain::fnGetLowerLimit() {return substrate->fnGetLowerLimit();};
double tBLM_quaternary_chol_domain::fnGetUpperLimit()
{
double a,b,c,d,e,f,temp;
a=headgroup2->fnGetUpperLimit();
b=headgroup2_2->fnGetUpperLimit();
c=headgroup2_3->fnGetUpperLimit();
d=headgroup2_domain->fnGetUpperLimit();
e=headgroup2_2_domain->fnGetUpperLimit();
f=headgroup2_3_domain->fnGetUpperLimit();
temp=a;
if (b>temp) {temp=b;}
if (c>temp) {temp=c;}
if (d>temp) {temp=d;}
if (e>temp) {temp=e;}
if (f>temp) {temp=f;}
return temp;
};
double tBLM_quaternary_chol_domain::fnWriteProfile(double aArea[], double anSLD[], int dimension, double stepsize, double dMaxArea)
{
nSLDObj::fnWriteProfile(aArea,anSLD,dimension,stepsize,dMaxArea);
return normarea;
};
void tBLM_quaternary_chol_domain::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
//char *str = new char[80];
//fprintf(fp, "PC %s z %lf l %lf nf %lf \n",cName, z, l, nf);
//nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
substrate->fnWritePar2File(fp, "substrate", dimension, stepsize);
bME->fnWritePar2File(fp, "bME", dimension, stepsize);
tether->fnWritePar2File(fp, "tether", dimension, stepsize);
tetherg->fnWritePar2File(fp, "tetherg", dimension, stepsize);
headgroup1->fnWritePar2File(fp, "headgroup1", dimension, stepsize);
headgroup1_2->fnWritePar2File(fp, "headgroup1_2", dimension, stepsize);
headgroup1_3->fnWritePar2File(fp, "headgroup1_3", dimension, stepsize);
lipid1->fnWritePar2File(fp, "lipid1", dimension, stepsize);
methyl1->fnWritePar2File(fp, "methyl1", dimension, stepsize);
methyl2->fnWritePar2File(fp, "methyl2", dimension, stepsize);
lipid2->fnWritePar2File(fp, "lipid2", dimension, stepsize);
headgroup2->fnWritePar2File(fp, "headgroup2", dimension, stepsize);
headgroup2_2->fnWritePar2File(fp, "headgroup2_2", dimension, stepsize);
headgroup2_3->fnWritePar2File(fp, "headgroup2_3", dimension, stepsize);
tether_domain->fnWritePar2File(fp, "tether_domain", dimension, stepsize);
tetherg_domain->fnWritePar2File(fp, "tetherg_domain", dimension, stepsize);
headgroup1_domain->fnWritePar2File(fp, "headgroup1_domain", dimension, stepsize);
headgroup1_2_domain->fnWritePar2File(fp, "headgroup1_2_domain", dimension, stepsize);
headgroup1_3_domain->fnWritePar2File(fp, "headgroup1_3_domain", dimension, stepsize);
lipid1_domain->fnWritePar2File(fp, "lipid1_domain", dimension, stepsize);
methyl1_domain->fnWritePar2File(fp, "methyl1_domain", dimension, stepsize);
methyl2_domain->fnWritePar2File(fp, "methyl2_domain", dimension, stepsize);
lipid2_domain->fnWritePar2File(fp, "lipid2_domain", dimension, stepsize);
headgroup2_domain->fnWritePar2File(fp, "headgroup2_domain", dimension, stepsize);
headgroup2_2_domain->fnWritePar2File(fp, "headgroup2_2_domain", dimension, stepsize);
headgroup2_3_domain->fnWritePar2File(fp, "headgroup2_3_domain", dimension, stepsize);
fnWriteConstant(fp, "normarea", normarea, 0, dimension, stepsize);
//delete []str;
}
//---------------------------------------------------------------------------------------------------------
//Discrete nSL, area profile
//---------------------------------------------------------------------------------------------------------
Discrete::Discrete(double dstartposition, double dnormarea, const char *cFileName)
{
double dz, darea, dnSLProt, dnSLDeut;
int i;
dStartPosition=dstartposition;
normarea=dnormarea;
dProtExchange=0;
dnSLDBulkSolvent=-0.566e-6;
FILE *fp;
fp=fopen(cFileName,"r");
if(fp==NULL) {
printf("Error: can't open file.\n");}
iNumberOfPoints=0;
while(!feof(fp)) {
fscanf(fp, "%lf %lf %lf %lf", &dz, &darea, &dnSLProt, &dnSLDeut);
//printf("%lf %lf %e %e \n", dz, darea, dnSLProt, dnSLDeut);
iNumberOfPoints+=1;
}
rewind(fp);
zcoord = new double[iNumberOfPoints];
area = new double[iNumberOfPoints];
nSLProt = new double[iNumberOfPoints];
nSLDeut = new double[iNumberOfPoints];
i=0;
while(!feof(fp)) {
fscanf(fp, "%lf %lf %lf %lf", &dz, &darea, &dnSLProt, &dnSLDeut);
zcoord[i]=dz;
area[i]=darea;
nSLProt[i]=dnSLProt;
nSLDeut[i]=dnSLDeut;
i+=1;
}
fclose(fp);
dZSpacing=zcoord[1]-zcoord[0];
};
Discrete::~Discrete(){
delete [] zcoord;
delete [] area;
delete [] nSLProt;
delete [] nSLDeut;
};
//Return value is area at position z
double Discrete::fnGetArea(double dz) {
int iBinLow, iBinHigh;
double dFraction, dtemp;
dz=dz-dStartPosition; //internal z for profile
dz=dz/dZSpacing; //floating point bin
iBinHigh=int(ceil(dz)); //get bin for dz
dFraction=modf(dz,&dtemp);
iBinLow=int(dtemp);
if ((iBinLow>=0) && (iBinHigh<iNumberOfPoints)) {
return((dFraction*area[iBinLow]+(1-dFraction)*area[iBinHigh])*nf);
}
else {
return 0;
}
};
//get nSLD from molecular subgroups
double Discrete::fnGetnSLD(double dz) {
int iBinLow, iBinHigh;
double dFraction, dtemp1, dtemp2, dtemp3,dtemp4;
dz=dz-dStartPosition; //internal z for profile
dz=dz/dZSpacing; //floating point bin
iBinHigh=int(ceil(dz)); //get bin for dz
dFraction=modf(dz,&dtemp1);
iBinLow=int(dtemp1);
if((iBinLow>=0) && (iBinHigh<iNumberOfPoints)) {
dtemp1=dFraction*nSLProt[iBinLow]+(1-dFraction)*nSLProt[iBinHigh];
dtemp2=dFraction*nSLDeut[iBinLow]+(1-dFraction)*nSLDeut[iBinHigh];
dtemp3=dProtExchange*(dnSLDBulkSolvent+0.566e-6)/(6.34e-6+0.566e-6);
dtemp4=(dFraction*area[iBinLow]+(1-dFraction)*area[iBinHigh])*dZSpacing;
//printf ("nf %e binlow %i binhigh %i dtemp1 %e dtemp2 %e dtemp3 %e dtemp4 %e areahigh % e protexch %e nSLDBulk %e nSLD %e \n", nf, iBinLow, iBinHigh, dtemp1, dtemp2, dtemp3, dtemp4, area[iBinHigh],dProtExchange,dnSLDBulkSolvent, (((1-dtemp3)*dtemp1+dtemp3*dtemp2)/dtemp4));
return(((1-dtemp3)*dtemp1+dtemp3*dtemp2)/dtemp4);
}
else {
return 0;
}
};
//Use limits of molecular subgroups
double Discrete::fnGetLowerLimit() {return (dStartPosition);}
double Discrete::fnGetUpperLimit() {return (dStartPosition+double(iNumberOfPoints)*dZSpacing);}
void Discrete::fnSetNormarea(double dnormarea)
{
normarea=dnormarea;
};
void Discrete::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
fprintf(fp, "Discrete %s StartPosition %e \n",cName, dStartPosition);
nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
}
//---------------------------------------------------------------------------------------------------------
//Freeform group 4 boxes
//---------------------------------------------------------------------------------------------------------
FreeBox::FreeBox(int n, double dstartposition, double dnSLD, double dnormarea)
{
numberofboxes = n;
startposition = dstartposition;
nSLD=dnSLD;
normarea=dnormarea;
if (n>0) {box1 = new Box2Err(); box1->nf=1;};
if (n>1) {box2 = new Box2Err(); box2->nf=1;};
if (n>2) {box3 = new Box2Err(); box3->nf=1;};
if (n>3) {box4 = new Box2Err(); box4->nf=1;};
if (n>4) {box5 = new Box2Err(); box5->nf=1;};
if (n>5) {box6 = new Box2Err(); box6->nf=1;};
if (n>6) {box7 = new Box2Err(); box7->nf=1;};
if (n>7) {box8 = new Box2Err(); box8->nf=1;};
if (n>8) {box9 = new Box2Err(); box9->nf=1;};
if (n>9) {box10 = new Box2Err(); box10->nf=1;};
fnAdjustParameters();
};
FreeBox::~FreeBox(){
if (numberofboxes>0) {delete box1;};
if (numberofboxes>1) {delete box2;};
if (numberofboxes>2) {delete box3;};
if (numberofboxes>3) {delete box4;};
if (numberofboxes>4) {delete box5;};
if (numberofboxes>5) {delete box6;};
if (numberofboxes>6) {delete box7;};
if (numberofboxes>7) {delete box8;};
if (numberofboxes>8) {delete box9;};
if (numberofboxes>9) {delete box10;};
};
void FreeBox::fnAdjustParameters(){
if (numberofboxes>0) {
box1->z=startposition+0.5*box1->l;
box1->vol=box1->l*normarea*vf1;
box1->nSL=nSLD*box1->vol;
if (numberofboxes>1) {
box2->z=box1->z+0.5*box1->l+0.5*box2->l;
box2->vol=box2->l*normarea*vf2;
box2->nSL=nSLD*box2->vol;
if (numberofboxes>2) {
box3->z=box2->z+0.5*box2->l+0.5*box3->l;
box3->vol=box3->l*normarea*vf3;
box3->nSL=nSLD*box3->vol;
if (numberofboxes>3) {
box4->z=box3->z+0.5*box3->l+0.5*box4->l;
box4->vol=box4->l*normarea*vf4;
box4->nSL=nSLD*box4->vol;
if (numberofboxes>4) {
box5->z=box4->z+0.5*box4->l+0.5*box5->l;
box5->vol=box5->l*normarea*vf5;
box5->nSL=nSLD*box5->vol;
if (numberofboxes>5) {
box6->z=box5->z+0.5*box5->l+0.5*box6->l;
box6->vol=box6->l*normarea*vf6;
box6->nSL=nSLD*box6->vol;
if (numberofboxes>6) {
box7->z=box6->z+0.5*box6->l+0.5*box7->l;
box7->vol=box7->l*normarea*vf7;
box7->nSL=nSLD*box7->vol;
if (numberofboxes>7) {
box8->z=box7->z+0.5*box7->l+0.5*box8->l;
box8->vol=box8->l*normarea*vf8;
box8->nSL=nSLD*box8->vol;
if (numberofboxes>8) {
box9->z=box8->z+0.5*box8->l+0.5*box9->l;
box9->vol=box9->l*normarea*vf9;
box9->nSL=nSLD*box9->vol;
if (numberofboxes>9) {
box10->z=box9->z+0.5*box9->l+0.5*box10->l;
box10->vol=box10->l*normarea*vf10;
box10->nSL=nSLD*box10->vol;
};
};
};
};
};
};
};
};
};
};
};
//Return value is area at position z
double FreeBox::fnGetArea(double dz) {
double sum;
sum=0;
if (numberofboxes>0) {sum=box1->fnGetArea(dz);};
if (numberofboxes>1) {sum=sum+box2->fnGetArea(dz);};
if (numberofboxes>2) {sum=sum+box3->fnGetArea(dz);};
if (numberofboxes>3) {sum=sum+box4->fnGetArea(dz);};
if (numberofboxes>4) {sum=sum+box5->fnGetArea(dz);};
if (numberofboxes>5) {sum=sum+box6->fnGetArea(dz);};
if (numberofboxes>6) {sum=sum+box7->fnGetArea(dz);};
if (numberofboxes>7) {sum=sum+box8->fnGetArea(dz);};
if (numberofboxes>8) {sum=sum+box9->fnGetArea(dz);};
if (numberofboxes>9) {sum=sum+box10->fnGetArea(dz);};
return sum;
};
//get nSLD from molecular subgroups
double FreeBox::fnGetnSLD(double dz) {
//printf("nSLD %e \n", nSLD);
return nSLD;
};
//Use limits of molecular subgroups
double FreeBox::fnGetLowerLimit() {return box1->fnGetLowerLimit();};
double FreeBox::fnGetUpperLimit() {
if (numberofboxes>9) {return box10->fnGetUpperLimit();}
else if (numberofboxes>8) {return box9->fnGetUpperLimit();}
else if (numberofboxes>7) {return box8->fnGetUpperLimit();}
else if (numberofboxes>6) {return box7->fnGetUpperLimit();}
else if (numberofboxes>5) {return box6->fnGetUpperLimit();}
else if (numberofboxes>4) {return box5->fnGetUpperLimit();}
else if (numberofboxes>3) {return box4->fnGetUpperLimit();}
else if (numberofboxes>2) {return box3->fnGetUpperLimit();}
else if (numberofboxes>1) {return box2->fnGetUpperLimit();}
else {return box1->fnGetUpperLimit();}
};
void FreeBox::fnSetSigma(double sigma)
{
if (numberofboxes>0) {box1->sigma1=sigma; box1->sigma2=sigma;};
if (numberofboxes>1) {box2->sigma1=sigma; box2->sigma2=sigma;};
if (numberofboxes>2) {box3->sigma1=sigma; box3->sigma2=sigma;};
if (numberofboxes>3) {box4->sigma1=sigma; box4->sigma2=sigma;};
if (numberofboxes>4) {box5->sigma1=sigma; box5->sigma2=sigma;};
if (numberofboxes>5) {box6->sigma1=sigma; box6->sigma2=sigma;};
if (numberofboxes>6) {box7->sigma1=sigma; box7->sigma2=sigma;};
if (numberofboxes>7) {box8->sigma1=sigma; box8->sigma2=sigma;};
if (numberofboxes>8) {box9->sigma1=sigma; box9->sigma2=sigma;};
if (numberofboxes>9) {box10->sigma1=sigma; box10->sigma2=sigma;};
};
void FreeBox::fnSetStartposition(double dz)
{
startposition=dz;
fnAdjustParameters();
};
void FreeBox::fnSetNormarea(double dnormarea)
{
normarea=dnormarea;
fnAdjustParameters();
};
void FreeBox::fnSetnSLD(double dnSLD)
{
nSLD=dnSLD;
fnAdjustParameters();
};
void FreeBox::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
//char *str = new char[80];
fprintf(fp, "FreeBox %s numberofboxes %i \n",cName, numberofboxes);
nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
//cg->fnWritePar2File(fp, "cg", dimension, stepsize);
//phosphate->fnWritePar2File(fp, "phosphate", dimension, stepsize);
//choline->fnWritePar2File(fp, "choline", dimension, stepsize);
//delete []str;
}
//---------------------------------------------------------------------------------------------------------
//Hermite spline interpolation
//---------------------------------------------------------------------------------------------------------
Hermite::Hermite(int n, double dstartposition, double dnSLD, double dnormarea)
{
numberofcontrolpoints = n;
nSLD=dnSLD;
normarea=dnormarea;
dp = new double[n];
vf = new double[n];
};
Hermite::~Hermite(){
delete [] dp;
delete [] vf;
};
//Return value is area at position z
double Hermite::fnGetArea(double dz) {
double p0, p1, m0, m1, h00, h01, h10, h11, t, dd, t_2, t_3, volfrac;
int interval;
//printf("fnGetArea z %e dp[0] %e dp[5] %e vf[0] %e vf[5] %e", dz, dp[0], dp[5], vf[0], vf[5]);
interval=-1;
for (int i=0; i<(numberofcontrolpoints-1); i++) {
//printf("i %i dz %e dp[i] %e dp[i+1] %e \n", i, dz, dp[i], dp[i+1]);
if ((dp[i]<=dz) && (dp[i+1]>dz)) {
//printf("Found interval %i \n", i);
interval=i;
}
}
if (interval>=0) {
if (interval==0) {
m0=0;
m1=(vf[2]-vf[0])/(dp[2]-dp[0]);
}
else if (interval==(numberofcontrolpoints-2)) {
m0=(vf[interval+1]-vf[interval-1])/(dp[interval+1]-dp[interval-1]);
m1=0;
}
else {
m0=(vf[interval+1]-vf[interval-1])/(dp[interval+1]-dp[interval-1]);
m1=(vf[interval+2]-vf[interval])/(dp[interval+2]-dp[interval]);
}
p0=vf[interval];
p1=vf[interval+1];
dd=dp[interval+1]-dp[interval];
t=(dz-dp[interval])/dd;
t_2=t*t;
t_3=t_2*t;
h00= 2*t_3-3*t_2+1;
h10= t_3-2*t_2+t;
h01=(-2)*t_3+3*t_2;
h11= t_3-t_2;
volfrac=h00*p0+h10*dd*m0+h01*p1+h11*dd*m1;
//printf("m0 %e m1 %e p0 %e p1 %e dd %e dz %e t %e normarea %e", m0, m1, p0, p1, dd, dz, t, normarea);
//printf("vf %e normarea %e \n", volfrac, normarea);
return volfrac*normarea;
}
else {
//printf("zero return");
return 0;
}
};
//get nSLD from molecular subgroups
double Hermite::fnGetnSLD(double dz) {
//printf("nSLD %e \n", nSLD);
return nSLD;
};
//Use limits of molecular subgroups
double Hermite::fnGetLowerLimit() {return dp[0];};
double Hermite::fnGetUpperLimit() {return dp[numberofcontrolpoints-1];}
void Hermite::fnSetNormarea(double dnormarea)
{
normarea=dnormarea;
};
void Hermite::fnSetnSLD(double dnSLD)
{
nSLD=dnSLD;
};
void Hermite::fnWritePar2File(FILE *fp, const char *cName, int dimension, double stepsize)
{
fprintf(fp, "Hermite %s numberofcontrolpoints %i \n",cName, numberofcontrolpoints);
nSLDObj::fnWriteData2File(fp, cName, dimension, stepsize);
}
//-----------------------------------------------------------------------------------------------------------
// Bilayer Library
//-----------------------------------------------------------------------------------------------------------
Monolayer_DOPS::Monolayer_DOPS()
{
headgroup = new Box2Err();
headgroup->vol=260; //PS volume and length are estimates
headgroup->nSL=8.4513e-4;
headgroup->l=7.5;
volacyllipid=925;
nslacyllipid=-2.6688e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
fnAdjustParameters();
}
Monolayer_DOPS::~Monolayer_DOPS()
{
delete headgroup;
}
Monolayer_DPPS::Monolayer_DPPS()
{
headgroup = new Box2Err();
headgroup->vol=260; //PS volume and length are estimates
headgroup->nSL=8.4513e-4;
headgroup->l=7.5;
volacyllipid=789;
nslacyllipid=-3.2502E-04;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
fnAdjustParameters();
}
Monolayer_DPPS::~Monolayer_DPPS()
{
delete headgroup;
}
ssBLM_POPC::ssBLM_POPC()
{
volacyllipid=925;
nslacyllipid=-2.6688e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
fnAdjustParameters();
}
tBLM_HC18_DOPC::tBLM_HC18_DOPC()
{
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
volacyllipid=972;
nslacyllipid=-2.09e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=999;
nslacyltether=-2.25e-4;
fnAdjustParameters();
}
tBLM_HC18_d54DMPC::tBLM_HC18_d54DMPC()
{
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
volacyllipid=735;
nslacyllipid=5.3324E-03;
volmethyllipid=98.8;
nslmethyllipid=5.334e-4;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=999;
nslacyltether=-2.25e-4;
fnAdjustParameters();
}
tBLM_WC14_DOPC::tBLM_WC14_DOPC()
{
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
volacyllipid=972;
nslacyllipid=-2.09e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=850;
nslacyltether=-3.5834e-4;
fnAdjustParameters();
}
tBLM_HC18_POPC_POPA::tBLM_HC18_POPC_POPA()
{
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
volacyllipid=925;
nslacyllipid=-2.67e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=999;
nslacyltether=-2.25e-4;
headgroup1_2->vol=174; //was 174
headgroup2_2->vol=174; //was 174
headgroup1_2->nSL=6.2364e-4; //was 6.2364e-4
headgroup2_2->nSL=6.2364e-4; //was 6.2364e-4
headgroup1_2->l=5;
headgroup2_2->l=5;
volacyllipid_2=925;
nslacyllipid_2=-2.67e-4;
volmethyllipid_2=98.8;
nslmethyllipid_2=-9.15e-5;
fnAdjustParameters();
}
tBLM_HC18_POPC_POPG::tBLM_HC18_POPC_POPG()
{
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
volacyllipid=925;
nslacyllipid=-2.67e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=999;
nslacyltether=-2.25e-4;
headgroup1_2->vol=270; //PG volume and length are estimates
headgroup2_2->vol=270;
headgroup1_2->nSL=7.1472e-4;
headgroup2_2->nSL=7.1472e-4;
headgroup1_2->l=7.8;
headgroup2_2->l=7.8;
volacyllipid_2=925;
nslacyllipid_2=-2.67e-4;
volmethyllipid_2=98.8;
nslmethyllipid_2=-9.15e-5;
fnAdjustParameters();
}
tBLM_HC18_DOPC_DOPS::tBLM_HC18_DOPC_DOPS()
{
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
volacyllipid=972;
nslacyllipid=-2.09e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=999;
nslacyltether=-2.25e-4;
headgroup1_2->vol=260; //PS volume and length are estimates
headgroup2_2->vol=260;
headgroup1_2->nSL=8.4513e-4;
headgroup2_2->nSL=8.4513e-4;
headgroup1_2->l=7.5;
headgroup2_2->l=7.5;
volacyllipid_2=972;
nslacyllipid_2=-2.09e-4;
volmethyllipid_2=98.8;
nslmethyllipid_2=-9.15e-5;
fnAdjustParameters();
}
tBLM_HC18_DOPC_d54DMPC::tBLM_HC18_DOPC_d54DMPC()
{
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
volacyllipid=972;
nslacyllipid=-2.09e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=999;
nslacyltether=-2.25e-4;
headgroup1_2->vol=330;
headgroup2_2->vol=330;
headgroup1_2->nSL=6.0012e-4;
headgroup2_2->nSL=6.0012e-4;
headgroup1_2->l=9.5;
headgroup2_2->l=9.5;
volacyllipid_2=735;
nslacyllipid_2=5.3324E-03;
volmethyllipid_2=98.8;
nslmethyllipid_2=5.334e-4;
fnAdjustParameters();
}
tBLM_HC18_DMPC_d54DMPC::tBLM_HC18_DMPC_d54DMPC()
{
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
volacyllipid=735;
nslacyllipid=-2.9166E-04;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=999;
nslacyltether=-2.25e-4;
headgroup1_2->vol=330;
headgroup2_2->vol=330;
headgroup1_2->nSL=6.0012e-4;
headgroup2_2->nSL=6.0012e-4;
headgroup1_2->l=9.5;
headgroup2_2->l=9.5;
volacyllipid_2=735;
nslacyllipid_2=5.3324E-03;
volmethyllipid_2=98.8;
nslmethyllipid_2=5.334e-4;
fnAdjustParameters();
}
tBLM_WC14_DOPC_DOPS::tBLM_WC14_DOPC_DOPS()
{
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
volacyllipid=972;
nslacyllipid=-2.09e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=850;
nslacyltether=-3.5834e-4;
headgroup1_2->vol=260; //PS volume and length are estimates
headgroup2_2->vol=260;
headgroup1_2->nSL=8.4513e-4;
headgroup2_2->nSL=8.4513e-4;
headgroup1_2->l=7.5;
headgroup2_2->l=7.5;
volacyllipid_2=972;
nslacyllipid_2=-2.09e-4;
volmethyllipid_2=98.8;
nslmethyllipid_2=-9.15e-5;
fnAdjustParameters();
}
tBLM_WC14_DOPC_PIP::tBLM_WC14_DOPC_PIP()
{
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
volacyllipid=972;
nslacyllipid=-2.09e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=850;
nslacyltether=-3.5834e-4;
headgroup1_2->vol=500; //PIP volume and length are estimates
headgroup2_2->vol=500;
headgroup1_2->nSL=1.22e-3;
headgroup2_2->nSL=1.22e-3;
headgroup1_2->l=12.0;
headgroup2_2->l=12.0;
volacyllipid_2=1025;
nslacyllipid_2=-7.5785e-5;
volmethyllipid_2=98.8;
nslmethyllipid_2=-9.15e-5;
fnAdjustParameters();
}
tBLM_HC18_DOPC_PIP::tBLM_HC18_DOPC_PIP()
{
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
volacyllipid=972;
nslacyllipid=-2.09e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=999;
nslacyltether=-2.25e-4;
headgroup1_2->vol=500; //PS volume and length are estimates
headgroup2_2->vol=500;
headgroup1_2->nSL=1.22e-3;
headgroup2_2->nSL=1.22e-3;
headgroup1_2->l=12.0;
headgroup2_2->l=12.0;
volacyllipid_2=1025;
nslacyllipid_2=-7.5785e-5;
volmethyllipid_2=98.8;
nslmethyllipid_2=-9.15e-5;
fnAdjustParameters();
}
tBLM_HC18_DOPC_DOPS_PIP::tBLM_HC18_DOPC_DOPS_PIP()
{
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
volacyllipid=972;
nslacyllipid=-2.09e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=999;
nslacyltether=-2.25e-4;
headgroup1_2->vol=260; //PS volume and length are estimates
headgroup2_2->vol=260;
headgroup1_2->nSL=8.4513e-4;
headgroup2_2->nSL=8.4513e-4;
headgroup1_2->l=7.5;
headgroup2_2->l=7.5;
volacyllipid_2=972;
nslacyllipid_2=-2.09e-4;
volmethyllipid_2=98.8;
nslmethyllipid_2=-9.15e-5;
headgroup1_3->vol=500; //PIP volume and length are estimates
headgroup2_3->vol=500;
headgroup1_3->nSL=1.22e-3;
headgroup2_3->nSL=1.22e-3;
headgroup1_3->l=12.0;
headgroup2_3->l=12.0;
volacyllipid_3=1025;
nslacyllipid_3=-7.5785e-5;
volmethyllipid_3=98.8;
nslmethyllipid_3=-9.15e-5;
fnAdjustParameters();
}
tBLM_WC14_DOPC_DOPS_CHOL::tBLM_WC14_DOPC_DOPS_CHOL()
{
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
volacyllipid=972;
nslacyllipid=-2.09e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=850;
nslacyltether=-3.5834e-4;
headgroup1_2->vol=260; //PS volume and length are estimates
headgroup2_2->vol=260;
headgroup1_2->nSL=8.4513e-4;
headgroup2_2->nSL=8.4513e-4;
headgroup1_2->l=7.5;
headgroup2_2->l=7.5;
volacyllipid_2=972;
nslacyllipid_2=-2.09e-4;
volmethyllipid_2=98.8;
nslmethyllipid_2=-9.15e-5;
volchol=630;
nslchol=1.3215e-4;
fnAdjustParameters();
}
tBLM_HC18_DOPC_DOPS_CHOL::tBLM_HC18_DOPC_DOPS_CHOL()
{
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
volacyllipid=972;
nslacyllipid=-2.09e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=999;
nslacyltether=-2.25e-4;
headgroup1_2->vol=260; //PS volume and length are estimates
headgroup2_2->vol=260;
headgroup1_2->nSL=8.4513e-4;
headgroup2_2->nSL=8.4513e-4;
headgroup1_2->l=7.5;
headgroup2_2->l=7.5;
volacyllipid_2=972;
nslacyllipid_2=-2.09e-4;
volmethyllipid_2=98.8;
nslmethyllipid_2=-9.15e-5;
volchol=630;
nslchol=1.3215e-4;
fnAdjustParameters();
}
tBLM_HC18_DOPC_DOPS_PIP_CHOL::tBLM_HC18_DOPC_DOPS_PIP_CHOL()
{
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
volacyllipid=972;
nslacyllipid=-2.09e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=999;
nslacyltether=-2.25e-4;
headgroup1_2->vol=260; //PS volume and length are estimates
headgroup2_2->vol=260;
headgroup1_2->nSL=8.4513e-4;
headgroup2_2->nSL=8.4513e-4;
headgroup1_2->l=7.5;
headgroup2_2->l=7.5;
volacyllipid_2=972;
nslacyllipid_2=-2.09e-4;
volmethyllipid_2=98.8;
nslmethyllipid_2=-9.15e-5;
volchol=630;
nslchol=1.3215e-4;
headgroup1_3->vol=500; //PIP volume and length are estimates
headgroup2_3->vol=500;
headgroup1_3->nSL=1.22e-3;
headgroup2_3->nSL=1.22e-3;
headgroup1_3->l=12.0;
headgroup2_3->l=12.0;
volacyllipid_3=1025;
nslacyllipid_3=-7.5785e-5;
volmethyllipid_3=98.8;
nslmethyllipid_3=-9.15e-5;
fnAdjustParameters();
}
tBLM_HC18_DOPC_DOPS_PIP_CHOL_domain::tBLM_HC18_DOPC_DOPS_PIP_CHOL_domain()
{
tether->vol=380;
tether->nSL=2.1864e-4;
tetherg->vol=110;
tetherg->nSL=1.8654e-4;
tether_domain->vol=380;
tether_domain->nSL=2.1864e-4;
tetherg_domain->vol=110;
tetherg_domain->nSL=1.8654e-4;
volacyllipid=972;
nslacyllipid=-2.09e-4;
volmethyllipid=98.8;
nslmethyllipid=-9.15e-5;
volmethyltether=98.8;
nslmethyltether=-9.15e-5;
volacyltether=999;
nslacyltether=-2.25e-4;
headgroup1_2->vol=260; //PS volume and length are estimates
headgroup2_2->vol=260;
headgroup1_2->nSL=8.4513e-4;
headgroup2_2->nSL=8.4513e-4;
headgroup1_2->l=7.5;
headgroup2_2->l=7.5;
headgroup1_2_domain->vol=260; //PS volume and length are estimates
headgroup2_2_domain->vol=260;
headgroup1_2_domain->nSL=8.4513e-4;
headgroup2_2_domain->nSL=8.4513e-4;
headgroup1_2_domain->l=7.5;
headgroup2_2_domain->l=7.5;
volacyllipid_2=972;
nslacyllipid_2=-2.09e-4;
volmethyllipid_2=98.8;
nslmethyllipid_2=-9.15e-5;
volchol=630;
nslchol=1.3215e-4;
headgroup1_3->vol=500; //PIP volume and length are estimates
headgroup2_3->vol=500;
headgroup1_3->nSL=1.22e-3;
headgroup2_3->nSL=1.22e-3;
headgroup1_3->l=12.0;
headgroup2_3->l=12.0;
headgroup1_3_domain->vol=500; //PIP volume and length are estimates
headgroup2_3_domain->vol=500;
headgroup1_3_domain->nSL=1.22e-3;
headgroup2_3_domain->nSL=1.22e-3;
headgroup1_3_domain->l=12.0;
headgroup2_3_domain->l=12.0;
volacyllipid_3=1025;
nslacyllipid_3=-7.5785e-5;
volmethyllipid_3=98.8;
nslmethyllipid_3=-9.15e-5;
fnAdjustParameters();
}
//------------------------------------------------------------------------------------------------------
void fnWriteConstant(FILE *fp, const char *cName, double area, double nSLD, int dimension, double stepsize)
{
int i;
double d;
fprintf(fp, "Constant %s area %lf \n",cName, area);
fprintf(fp, "z%s a%s nsl%s \n",cName, cName, cName);
for (i=0; i<dimension; i++)
{
d=double(i)*stepsize;
fprintf(fp, "%lf %lf %e \n", d, area, nSLD*area*stepsize);
};
fprintf(fp,"\n");
}
//------------------------------------------------------------------------------------------------------
double fnClearCanvas(double aArea[], double anSL[], int dimension)
{
int j;
for (j=0; j<dimension; j++) {
aArea[j]=0; anSL[j]=0;
};
return 0;
}
double fnClearCanvas(double aArea[], double anSL[], double aAbsorb[], int dimension)
{
int j;
for (j=0; j<dimension; j++) {
aArea[j]=0; anSL[j]=0; aAbsorb[j]=0;
};
return 0;
}
//------------------------------------------------------------------------------------------------------
// Overlays one canvas onto another
void fnOverlayCanvasOnCanvas(double aArea[], double anSL[], double aArea2[], double anSL2[], int dimension, double dMaxArea)
{
double temparea;
int i;
for(i=0; i<dimension; i++)
{
temparea=aArea2[i]+aArea[i];
if (temparea>dMaxArea)
{
anSL[i]=anSL[i]*(1-((temparea-dMaxArea)/aArea[i])); //eliminate the overfilled portion using original content
anSL[i]=anSL[i]+anSL2[i];
aArea[i]=dMaxArea;
}
else
{
//printf("Bin %i Areainc %f area now %f nSLinc %g nSL now %g \n", i, aArea2[i], aArea[i], anSL2[1], anSL[i]);
aArea[i]=aArea[i]+aArea2[i];
anSL[i]=anSL[i]+anSL2[i];
}
};
};
void fnOverlayCanvasOnCanvas(double aArea[], double anSL[], double aAbsorb[], double aArea2[], double anSL2[], double aAbsorb2[], int dimension, double dMaxArea)
{
double temparea;
int i;
for(i=0; i<dimension; i++)
{
temparea=aArea2[i]+aArea[i];
if (temparea>dMaxArea)
{
anSL[i]=anSL[i]*(1-((temparea-dMaxArea)/aArea[i])); //eliminate the overfilled portion using original content
anSL[i]=anSL[i]+anSL2[i];
aAbsorb[i]=aAbsorb[i]*(1-((temparea-dMaxArea)/aArea[i])); //eliminate the overfilled portion using original content
aAbsorb[i]=aAbsorb[i]+aAbsorb2[i];
aArea[i]=dMaxArea;
}
else
{
//printf("Bin %i Areainc %f area now %f nSLinc %g nSL now %g \n", i, aArea2[i], aArea[i], anSL2[1], anSL[i]);
aArea[i]=aArea[i]+aArea2[i];
anSL[i]=anSL[i]+anSL2[i];
aAbsorb[i]=aAbsorb[i]+aAbsorb2[i];
}
};
};
//------------------------------------------------------------------------------------------------------
//writes out canvas to reflectivity model taking into account bulk nSLD
void fnWriteCanvas2Model(double aArea[], double anSL[], fitinfo fit[], int gaussstart, int dimension, double stepsize, double dMaxArea, double normarea, int modelstart, int modelend)
{
int i, j;
if (dMaxArea!=0) {
for (i=modelstart; i<modelend+1; i++)
for (j=0; j<dimension; j++) {
fit[i].m.rho[j+gaussstart]=(anSL[j]/(normarea*stepsize))+(1-(aArea[j]/normarea))*fit[i].m.rho[fit[i].m.n-1];
}
}
else {
for (i=modelstart; i<modelend+1; i++)
for (j=0; j<dimension; j++) {fit[i].m.rho[j+gaussstart]=fit[i].m.rho[fit[i].m.n-1];}
}
}
void fnWriteCanvas2Model(double aArea[], double anSL[], double aAbsorb[], fitinfo fit[], int gaussstart, int dimension, double stepsize, double dMaxArea, double normarea, int modelstart, int modelend)
{
int i, j;
if (dMaxArea!=0) {
for (i=modelstart; i<modelend+1; i++)
for (j=0; j<dimension; j++) {
//printf("bin %i area %e normarea %e areafraction %e bulk mu %e absorption %e result %e \n",j, aArea[j], normarea, aArea[j]/normarea,fit[i].m.mu[fit[i].m.n-1], aAbsorb[j],(aAbsorb[j]/(normarea*stepsize))+(1-(aArea[j]/normarea))*fit[i].m.mu[fit[i].m.n-1]);
fit[i].m.rho[j+gaussstart]=(anSL[j]/(normarea*stepsize))+(1-(aArea[j]/normarea))*fit[i].m.rho[fit[i].m.n-1];
fit[i].m.mu[j+gaussstart]=(aAbsorb[j]/(normarea*stepsize))+(1-(aArea[j]/normarea))*fit[i].m.mu[fit[i].m.n-1];
}
}
else {
for (i=modelstart; i<modelend+1; i++)
for (j=0; j<dimension; j++) {
fit[i].m.rho[j+gaussstart]=fit[i].m.rho[fit[i].m.n-1];
fit[i].m.mu[j+gaussstart]=fit[i].m.mu[fit[i].m.n-1];
}
}
}
|
c22f97d990a516edd371b0ca727b558ce64dc739 | a72bf12a7f2db6f2bf59161e1298a4261331e127 | /plugkit/src/slice.hpp | f409b614da45f40abeaaf1af847db802015165f7 | [
"MIT"
] | permissive | vaginessa/deplug | 747789cefb396f1137102335b008620bcc57be25 | 2456cbcb05d8285a07360fbd1529a239e520a754 | refs/heads/early-dev | 2023-03-08T11:04:08.629415 | 2018-04-02T14:28:37 | 2018-04-02T14:28:37 | 127,824,553 | 0 | 0 | MIT | 2023-03-03T20:26:42 | 2018-04-02T23:38:12 | C++ | UTF-8 | C++ | false | false | 270 | hpp | slice.hpp | /// @file
/// Binary sequence
#ifndef PLUGKIT_SLICE_H
#define PLUGKIT_SLICE_H
#include "token.hpp"
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
namespace plugkit {
struct Slice {
const char *data;
size_t length;
};
} // namespace plugkit
#endif
|
3257f97743231e759d391580ca86121ccf95edf7 | 02133492ffe43c0a12e506862df2dc2d655c05c9 | /include/Exceptions.h | 3f203bd49f2daa8eb17aea2dc85d6b68e380dbff | [] | no_license | Chris-Jukebox/SPH-Simulation | 37e1e63be3e175d1b998f817556c284095a1dc3f | 32906a648a0af6bf898f7e3092eb224a2ea53506 | refs/heads/master | 2020-05-29T12:31:09.916171 | 2016-01-11T20:51:06 | 2016-01-11T20:51:06 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 441 | h | Exceptions.h | /*
* Copyright © 2015 Jeremy T. Hatcher All Rights Reserved
*/
#pragma once
#include <exception>
#include <string>
class GenericException
{
protected:
std::string m_msg;
public:
explicit GenericException(std::string& message)
:m_msg(message)
{}
explicit GenericException(const char* message)
:m_msg(message)
{}
virtual ~GenericException() throw()
{}
virtual const char* what() const throw() {
return m_msg.c_str();
}
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.