hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
b0219fea4a2dbc6965d773176c68dfe25e5ebb5b
878
h
C
Mara2Dtest/src/Vector2.h
Toivotak/Mara2Dexe
faf2792f7b6e92f6a5dea836c5f4bfa076590c1b
[ "MIT" ]
null
null
null
Mara2Dtest/src/Vector2.h
Toivotak/Mara2Dexe
faf2792f7b6e92f6a5dea836c5f4bfa076590c1b
[ "MIT" ]
null
null
null
Mara2Dtest/src/Vector2.h
Toivotak/Mara2Dexe
faf2792f7b6e92f6a5dea836c5f4bfa076590c1b
[ "MIT" ]
null
null
null
#pragma once #include <iostream> /* 2d vector class with operators for easier manipulatios */ namespace Mara { struct Vector2 { int x; int y; float xpos; float ypos; Vector2(); Vector2(int x, int y); Vector2(float x, float y); Vector2& Add(const Vector2& vec); Vector2& Subtract(const Vector2& vec); Vector2& Multiply(const Vector2& vec); Vector2& Divide(const Vector2& vec); friend Vector2 operator+(Vector2& v1, Vector2& v2); friend Vector2 operator-(Vector2& v1, Vector2& v2); friend Vector2 operator*(Vector2& v1, Vector2& v2); friend Vector2 operator/(Vector2& v1, Vector2& v2); Vector2& operator+=(const Vector2& vec); Vector2& operator-=(const Vector2& vec); Vector2& operator*=(const Vector2& vec); Vector2& operator/=(const Vector2& vec); friend std::ostream& operator<<(std::ostream& stream, const Vector2& vec); }; }
24.388889
76
0.693622
[ "vector" ]
b02574be9c9c11010885ec765e74154c923d1f89
4,826
h
C
include/Environment.h
shieldai/AdaptiveShielding
d281b5541139a3e9e6de003392790bb2298075c6
[ "MIT" ]
null
null
null
include/Environment.h
shieldai/AdaptiveShielding
d281b5541139a3e9e6de003392790bb2298075c6
[ "MIT" ]
null
null
null
include/Environment.h
shieldai/AdaptiveShielding
d281b5541139a3e9e6de003392790bb2298075c6
[ "MIT" ]
null
null
null
#ifndef INCLUDE_ENVIRONMENT_H_ #define INCLUDE_ENVIRONMENT_H_ #include <vector> #include <string> #include <cassert> #include "Util.h" /** @class Environment * Keeps track of the simulations environment and adapts properties on observations. */ class Environment { private: std::vector<std::string> labels; std::vector<float> probabilities; std::vector<int> weights; std::vector<int> stateSpace; // STAT std::vector<int> vehicleNumbers; std::vector<size_t> allVehicleNumbers; std::vector<size_t> allNewVehicleNumbers; std::vector<int> haltingNumbers; std::vector<int> environmentTracking_; public: Environment() = default;; /** @brief Constructor for the Environment Class. * Initializes the Class with given values (labels, probabilities, state space). * The remaining fields initialized with default values. * * @param labels A list of Strings of the lane labels. * @param probabilities A list of Floats of the probabilities values. * @param weights A list of Integers of the weight values. (UNUSED) * @param state_space A list of Integers of the max. state values. */ Environment(const std::vector<std::string> &labels, const std::vector<float> &probabilities, const std::vector<int> &weights, const std::vector<int> &state_space); /** @brief Constructor for the Environment Class. * Initializes the Class with minimal information (labels). * The remaining fields initialized with default values. * * @param labels A list of Strings of the lane labels. * @param weights A list of Integers of the weight values. (UNUSED) */ Environment(std::vector<std::string> &lanes, std::vector<int> &weights); /** @brief Check the Class fields. * * @return True if class is ok, False otherwise. */ bool check() const; /** @brief Update weights, dimension is fixed. * * @param weights A list of Integers with weight values. */ void updateWeights(const std::vector<int> &weights); /** @brief Update probabilities, on observation. */ void updateProbabilities(); /** @brief Update state space, dimension is fixed. * The state space should only grow. * * @param stateSpace A list of Integers of the lane sizes. */ void updateStateSpace(const std::vector<int> &stateSpace); /** @brief Set state space. * * @param stateSpace A list of Integers of the lane sizes. */ void setStateSpace(const std::vector<int> &stateSpace); /** @brief Update halting vehicle numbers on lane on observations. * * @param haltingNumbers A list of Integers with halting vehicle number. */ void updateHaltingNumbers(const std::vector<int> &haltingNumbers); /** @brief Update vehicle numbers on lane on observations. * * @param vehicleNumbers A list of Integers with vehicle number. */ void updateVehicleNumbers(const std::vector<int> &vehicleNumbers); /** @brief Used to load values from configuration. Update fields with given Object. * The method corrects the probabilities, weights and state space order by identify the labels. * * @param environment A environment object. */ void updateProperties(Environment &environment); /** @brief Get the state space labels. * * @return A list of Strings of the state space labels. */ std::vector<std::string> getStateSpaceLabels() const; /** @brief Get the state space size. * * @return A list of Integers with the state space size. */ std::vector<int> getStateSpace() const; /** @brief Get the weights. * * @return A list of Integers with weights values. */ std::vector<int> getWeights() const; /** @brief Get the probabilities. * * @return A list of Floats of the probabilities values. */ std::vector<float> getProbabilities() const; /** @brief Get the halting vehicles. * * @return A list of Integers with halting vehicles. */ std::vector<int> getHaltingNumbers(); /** @brief Get the vehicles. * * @return A list of Integers with vehicles. */ std::vector<int> getVehicleNumbers(); /** @brief Get the state space with the probability values. * * @return A output String. */ std::string getStateSpaceString() const; /** @brief Get the state space with the probability values. * * @return A output String. */ std::string getStateSpaceSizeString() const; private: /** @brief Update probabilities, dimension is fixed. * * @param probabilities A list of Floats of the probabilities values. */ void updateProbabilities(const std::vector<float> &probabilities); /** @brief Get a normal distributed form the latest lane states. * * @return A list of Floats of the probabilities values. */ std::vector<float> getPMF(); }; #endif //INCLUDE_ENVIRONMENT_H_
29.607362
97
0.691256
[ "object", "vector" ]
e5cb0e1eb05f31af0ca57d7d1e3a52adcc9eef63
3,329
h
C
lib/time_evolution.h
gwpark-git/dynamics_of_networks_and_colloids
0b0a3687533379ec75171ae6b906aeff5bedfbba
[ "MIT" ]
null
null
null
lib/time_evolution.h
gwpark-git/dynamics_of_networks_and_colloids
0b0a3687533379ec75171ae6b906aeff5bedfbba
[ "MIT" ]
null
null
null
lib/time_evolution.h
gwpark-git/dynamics_of_networks_and_colloids
0b0a3687533379ec75171ae6b906aeff5bedfbba
[ "MIT" ]
null
null
null
#ifndef TIME_EVOLUTION_H #define TIME_EVOLUTION_H #include "geometry.h" #include "potential.h" #include "fstream" #include "association.h" #include <mkl.h> namespace INTEGRATOR { namespace EULER { double cal_repulsion_force_R_boost (POTENTIAL_SET& POTs, MATRIX& given_vec, MKL_LONG index_particle, RDIST& R_boost); double cal_repulsion_force_R_boost_with_RF (POTENTIAL_SET& POTs, MATRIX& given_vec, MKL_LONG index_particle, RDIST& R_boost, double& RF_repulsion_xx, double& RF_repulsion_yy, double& RF_repulsion_zz, double& RF_repulsion_xy, double& RF_repulsion_xz, double& RF_repulsion_yz, double& energy_repulsive_potential); double cal_random_force_boost (POTENTIAL_SET& POTs, MATRIX& given_vec, gsl_rng* r_boost); double cal_random_force_boost_simplified (POTENTIAL_SET& POTs, MATRIX& given_vec, gsl_rng* r_boost); double cal_connector_force_boost (POTENTIAL_SET& POTs, CONNECTIVITY& CONNECT, MATRIX& given_vec, MKL_LONG given_index, MATRIX** R_minimum_vec_boost, MATRIX* R_minimum_distance_boost); double cal_connector_force_boost_with_RF (POTENTIAL_SET& POTs, CONNECTIVITY& CONNECT, MATRIX& given_vec, MKL_LONG given_index, MATRIX** R_minimum_vec_boost, MATRIX* R_minimum_distance_boost, double& RF_connector_xx, double& RF_connector_yy, double& RF_connector_zz, double& RF_connector_xy, double& RF_connector_xz, double& RF_connector_yz, double& energy_elastic_potential); } namespace EULER_ASSOCIATION { double cal_connector_force_boost (POTENTIAL_SET& POTs, ASSOCIATION& CONNECT, MATRIX& given_vec, MKL_LONG given_index, MATRIX** R_minimum_vec_boost, MATRIX* R_minimum_distance_boost); double cal_connector_force_boost_with_RF (POTENTIAL_SET& POTs, ASSOCIATION& CONNECT, MATRIX& given_vec, MKL_LONG given_index, MATRIX** R_minimum_vec_boost, MATRIX* R_minimum_distance_boost, double& RF_connector_xx, double& RF_connector_yy, double& RF_connector_zz, double& RF_connector_xy, double& RF_connector_xz, double& RF_connector_yz, double& energy_elastic_potential); } } namespace ANALYSIS { double CAL_ENERGY_BROWNIAN (POTENTIAL_SET& POTs, MATRIX& mat_energy, double time); double CAL_ENERGY_R_boost (POTENTIAL_SET& POTs, MATRIX& mat_energy, double time, RDIST& R_boost); double cal_potential_energy_R_boost (POTENTIAL_SET& POTs, RDIST& R_boost); double cal_total_energy_R_boost (POTENTIAL_SET& POTs, RDIST& R_boost); namespace DUMBBELL { double CAL_ENERGY_R_boost(POTENTIAL_SET& POTs, CONNECTIVITY& CONNECT, MATRIX& mat_energy, double time, RDIST& R_boost); // note that this functionality is subect to re-define. It is due to the fact that RDIST is not necessary for the dumbbell model, but it is used for using the same interface with stochastic HEUR simulation double cal_potential_energy_R_boost(POTENTIAL_SET& POTs, CONNECTIVITY& CONNECT, RDIST& R_boost); } namespace ANAL_ASSOCIATION { double CAL_ENERGY_R_boost (POTENTIAL_SET& POTs, ASSOCIATION& CONNECT, MATRIX& mat_energy, double time, RDIST& R_boost); double cal_potential_energy_R_boost (POTENTIAL_SET& POTs, ASSOCIATION& CONNECT, RDIST& R_boost); } } #endif
33.626263
324
0.753379
[ "geometry", "model" ]
e5d4d900d2664363a8530c16673f67c255895e79
12,026
h
C
src/include/container/bplustree/tree.h
rickard1117/PidanDB
6955f6913cb404a0f09a5e44c07f36b0729c0a78
[ "MIT" ]
7
2020-08-01T04:09:15.000Z
2021-08-08T17:26:19.000Z
src/include/container/bplustree/tree.h
rickard1117/PidanDB
6955f6913cb404a0f09a5e44c07f36b0729c0a78
[ "MIT" ]
null
null
null
src/include/container/bplustree/tree.h
rickard1117/PidanDB
6955f6913cb404a0f09a5e44c07f36b0729c0a78
[ "MIT" ]
2
2020-09-16T02:29:52.000Z
2020-09-28T10:51:38.000Z
#pragma once #include <atomic> #include <fstream> #include <functional> #include <thread> #include "common/macros.h" #include "common/type.h" #include "container/bplustree/node.h" namespace pidan { // 一个垃圾节点,等待被GC的回收 struct GarbageNode { Node *node{nullptr}; GarbageNode *next{nullptr}; }; // 一个EpochNode存储了一个Epoch周期中待回收的垃圾数据 struct EpochNode { // 当前Epoch中活跃的线程数 std::atomic<uint64_t> active_thread_count{0}; // 当前Epoch中待回收的垃圾节点链表 std::atomic<GarbageNode *> garbage_list{nullptr}; // 下一个EpochNode EpochNode *next{nullptr}; }; class EpochManager { public: DISALLOW_COPY_AND_MOVE(EpochManager); EpochManager() : head_epoch_(new EpochNode()), current_epoch_(head_epoch_){}; ~EpochManager() { Stop(); } // 启动一个线程,不断地去更新epoch void Start() { terminate_.store(false); thread_ = new std::thread([this] { while (!terminate_) { this->PerformGC(); this->CreateNewEpoch(); std::this_thread::sleep_for(std::chrono::milliseconds(BPLUSTREE_EPOCH_INTERVAL)); } }); } void Stop() { terminate_.store(true); if (thread_ != nullptr) { thread_->join(); delete thread_; } } EpochNode *JoinEpoch() { // 我们必须保证join的Epoch和leave的Epoch是同一个 EpochNode *epoch = current_epoch_; current_epoch_->active_thread_count.fetch_add(1); return current_epoch_; } void LeaveEpoch(EpochNode *epoch) { epoch->active_thread_count.fetch_sub(1); } // 增加一个待回收的Node,会在其他线程调用 void AddGarbageNode(Node *node) { // 这里要copy一份current_epoch_的复制,因为GC线程可能会调用CreateNewEpoch EpochNode *epoch = current_epoch_; auto *garbage = new GarbageNode(); garbage->node = node; garbage->next = epoch->garbage_list.load(); for (;;) { auto result = epoch->garbage_list.compare_exchange_strong(garbage->next, garbage); if (result) { break; } // 如果CAS失败,那么garbage->next会更新为epoch->garbage_list的新值,则继续重试就好了。 } } void PerformGC() { for (;;) { if (head_epoch_ == current_epoch_) { // 我们至少要保留一个epoch return; } // 从head开始遍历epoch node链表 if (head_epoch_->active_thread_count.load() > 0) { return; } // 已经没有线程在这个epoch上了,可以直接释放它所有的garbage节点。 while (head_epoch_->garbage_list != nullptr) { GarbageNode *garbage_node = head_epoch_->garbage_list.load(); delete garbage_node->node; head_epoch_->garbage_list = head_epoch_->garbage_list.load()->next; delete garbage_node; #ifndef NDEBUG garbage_node_del_num_.fetch_add(1); #endif } EpochNode *epoch = head_epoch_; head_epoch_ = head_epoch_->next; delete epoch; #ifndef NDEBUG epoch_del_num_.fetch_add(1); #endif } } #ifndef NDEBUG uint32_t GarbageNodeDelNum() { return garbage_node_del_num_.load(); } #endif void CreateNewEpoch() { auto *new_epoch = new EpochNode(); current_epoch_->next = new_epoch; current_epoch_ = new_epoch; } private: // Epoch链表的头结点,不需要atomic因为只有GC线程会修改和读取它 EpochNode *head_epoch_; // 当前Epoch所在的节点,不需要atomic因为只有GC线程会修改,业务线程虽然会读取,但是读到旧数据也没关系 EpochNode *current_epoch_; std::atomic<bool> terminate_{true}; std::thread *thread_{nullptr}; #ifndef NDEBUG std::atomic<uint32_t> garbage_node_del_num_{0}; // 删除的垃圾节点的数量 std::atomic<uint32_t> epoch_del_num_{0}; // 删除的epoch节点的数量 #endif }; // 支持变长key,定长value,非重复key的线程安全B+树。 template <typename KeyType, typename ValueType> class BPlusTree { public: BPlusTree() : root_(new LNode) { } // 查找key对应的value,找到返回true,否则返回false。 bool Lookup(const KeyType &key, ValueType *value) const { for (;;) { Node *node = root_.load(); bool need_restart = false; EpochNode *epoch = epoch_manager_.JoinEpoch(); bool result = StartLookup(node, nullptr, INVALID_OLC_LOCK_VERSION, key, value, &need_restart); epoch_manager_.LeaveEpoch(epoch); if (need_restart) { // 查找失败,需要重启整个流程。 continue; } return result; } } // 插入一对key value,要求key是唯一的。如果key已经存在则返回false,并将value设置为已经存在的值。 // 插入成功返回true,不对value做任何改动。 bool InsertUnique(const KeyType &key, const ValueType &value, ValueType *old_val) { for (;;) { Node *node = root_.load(); bool need_restart = false; EpochNode *epoch = epoch_manager_.JoinEpoch(); bool result = StartInsertUnique(node, nullptr, INVALID_OLC_LOCK_VERSION, key, value, old_val, &need_restart); epoch_manager_.LeaveEpoch(epoch); if (need_restart) { continue; } return result; } } // 查找key,如果找到,返回true并返回对应的Value值。如果没找到则返回false并构造一个新的value。 bool CreateIfNotExist(const KeyType &key, ValueType *new_val, const std::function<ValueType(void)> &creater) { for (;;) { } } // 只是测试用 void DrawTreeDot(const std::string &filename) { std::ofstream out(filename); out << "digraph g { " << '\n'; out << "node [shape = record,height=0.1];" << '\n'; IDGenerator g; draw_node(root_, out, g.gen(), g); out << "}" << '\n'; } private: using LNode = LeafNode<KeyType, ValueType>; using INode = InnerNode<KeyType>; class IDGenerator { public: IDGenerator() : id_(0) {} size_t gen() { return id_++; } private: size_t id_; }; void draw_node(Node *node, std::ofstream &ofs, size_t my_id, IDGenerator &g) { std::string my_id_s = std::to_string(my_id); ofs.flush(); if (!node->IsLeaf()) { INode *inner = static_cast<INode *>(node); ofs << "node" << my_id_s << "[label = \""; for (uint16_t i = 0; i < inner->key_map_.size(); i++) { ofs << "<f" << std::to_string(i) << ">"; ofs << "|" << inner->key_map_.KeyAt(i).ToString() << "|"; } ofs << "<f" << inner->key_map_.size() << ">\"];\n"; size_t childid = g.gen(); ofs << "\"node" << my_id_s << "\"" << ":f" << "0" << "->" << "\"node" << std::to_string(childid) << "\"\n"; draw_node(inner->first_child_, ofs, childid, g); for (uint16_t i = 0; i < inner->key_map_.size(); i++) { childid = g.gen(); ofs << "\"node" << my_id_s << "\"" << ":f" << std::to_string(i + 1) << "->" << "\"node" << std::to_string(childid) << "\"\n"; draw_node(inner->key_map_.ValueAt(i), ofs, childid, g); } return; } LNode *leaf = static_cast<LNode *>(node); for (uint16_t i = 0; i < leaf->key_map_.size(); i++) { if (i > 0) { ofs << "|"; } ofs << leaf->key_map_.KeyAt(i).ToString(); } ofs << "\"];\n"; } // 从node节点开始,向树中插入key value,插入失败返回false,否则返回true。 bool StartInsertUnique(Node *node, INode *parent, uint64_t parent_version, const KeyType &key, const ValueType &val, ValueType *old_val, bool *need_restart) { uint64_t version; if (!node->ReadLockOrRestart(&version)) { *need_restart = true; return false; } if (!node->IsLeaf()) { INode *inner = static_cast<INode *>(node); if (!inner->EnoughSpaceFor(MAX_KEY_SIZE)) { // 节点空间不足,要分裂。 if (parent) { if (!parent->UpgradeToWriteLockOrRestart(parent_version)) { *need_restart = true; return false; } } if (!inner->UpgradeToWriteLockOrRestart(version)) { if (parent) { parent->WriteUnlock(); } *need_restart = true; return false; } // TODO: 这个地方有疑问,到底应不应该判断。 if (parent == nullptr && (inner != root_.load())) { // node原本是根节点,但是同时有其他线程在此线程对根节点加写锁之前已经将根节点分裂或删除了 // 此时虽然加写锁可以成功,但根节点已经是新的节点了,因此要重启。 inner->WriteUnlock(); *need_restart = true; return false; } KeyType split_key; INode *sibling = inner->Split(&split_key); if (parent) { bool result = parent->Insert(split_key, sibling); assert(result); } else { root_ = new INode(inner->level() + 1, inner, sibling, split_key); } inner->WriteUnlock(); if (parent) { parent->WriteUnlock(); } // 分裂完毕,重新开始插入流程。 *need_restart = true; return false; } if (parent) { if (!parent->ReadUnlockOrRestart(parent_version)) { *need_restart = true; return false; } } Node *child = inner->FindChild(key); if (!inner->CheckOrRestart(version)) { *need_restart = true; return false; } return StartInsertUnique(child, inner, version, key, val, old_val, need_restart); } LNode *leaf = static_cast<LNode *>(node); if (leaf->Exists(key, old_val)) { if (!leaf->ReadUnlockOrRestart(version)) { *need_restart = true; } else { *need_restart = false; } return false; } if (!leaf->EnoughSpaceFor(MAX_KEY_SIZE)) { if (parent) { // leaf节点要分裂,会向父节点插入key,要先拿到父节点的写锁。 // 之前访问父节点已经保证了父节点的空间足够,如果在访问后父节点发生了改动,那么这里会加锁失败。 if (!parent->UpgradeToWriteLockOrRestart(parent_version)) { *need_restart = true; return false; } } if (!leaf->UpgradeToWriteLockOrRestart(version)) { *need_restart = true; if (parent) { parent->WriteUnlock(); } return false; } // TODO: 这个地方有疑问,到底应不应该判断。 if (parent == nullptr && (node != root_)) { // node原本是根节点,但是同时有其他线程在此线程对根节点加写锁之前已经将根节点分裂或删除了 // 此时虽然加写锁可以成功,但根节点已经是新的节点了,因此要重启。 leaf->WriteUnlock(); *need_restart = true; return false; } KeyType split_key; LNode *sibling = leaf->Split(&split_key); if (parent) { bool result = parent->Insert(split_key, sibling); assert(result); } else { // 当前节点是leaf node,那么父节点的level必须是1 root_ = new INode(1, leaf, sibling, split_key); } // TODO : 分裂完毕了,此时是否可以直接将key插入到leaf或者sibling节点了,还是需要再重启一次? // if (key < split_key) { // leaf->Insert(key, val); // } else { // sibling->Insert(key, val); // } leaf->WriteUnlock(); if (parent) { parent->WriteUnlock(); } *need_restart = true; return false; } else { // leaf 节点空间足够,直接插入不需要再对父节点加写锁了 if (!leaf->UpgradeToWriteLockOrRestart(version)) { *need_restart = true; return false; } if (parent) { if (!parent->ReadUnlockOrRestart(parent_version)) { *need_restart = true; leaf->WriteUnlock(); return false; } } leaf->Insert(key, val); leaf->WriteUnlock(); return true; } } // 从节点node开始查找key,没有找到则返回false bool StartLookup(const Node *node, const Node *parent, const uint64_t parent_version, const KeyType &key, ValueType *val, bool *need_restart) const { // a_.fetch_add(1); uint64_t version; if (!node->ReadLockOrRestart(&version)) { *need_restart = true; return false; } if (parent) { if (!parent->ReadUnlockOrRestart(parent_version)) { *need_restart = true; return false; } } if (node->IsLeaf()) { const LNode *leaf = static_cast<const LNode *>(node); bool result = leaf->FindValue(key, val); if (!leaf->ReadUnlockOrRestart(version)) { *need_restart = true; return false; } *need_restart = false; return result; } const INode *inner = static_cast<const INode *>(node); const Node *child = inner->FindChild(key); assert(child != nullptr); // 这里需要再次检查,以保证child指针的有效性。 if (!inner->CheckOrRestart(version)) { *need_restart = true; return false; } return StartLookup(child, node, version, key, val, need_restart); } private: std::atomic<Node *> root_; mutable EpochManager epoch_manager_; }; // 画出树的dot图,仅用于测试 void DrawTreeDot(const std::string &filename); } // namespace pidan
27.394077
118
0.594296
[ "shape" ]
e5dd6df55ffb717a0117951edc50c0aa7c12399a
15,279
h
C
lib/include/vkHelper.h
tomix1024/glTF-IBL-Sampler
7326e694d5abc8b55e27a27375cfbd11bf91d6d3
[ "Apache-2.0" ]
57
2019-10-02T16:13:00.000Z
2022-02-26T17:46:37.000Z
lib/include/vkHelper.h
tomix1024/glTF-IBL-Sampler
7326e694d5abc8b55e27a27375cfbd11bf91d6d3
[ "Apache-2.0" ]
16
2019-09-27T10:43:20.000Z
2021-10-17T21:04:51.000Z
lib/include/vkHelper.h
tomix1024/glTF-IBL-Sampler
7326e694d5abc8b55e27a27375cfbd11bf91d6d3
[ "Apache-2.0" ]
7
2020-02-23T21:03:53.000Z
2022-01-01T07:41:04.000Z
#pragma once #include <vulkan/vulkan.h> #include <vector> namespace IBLLib { class vkHelper { friend class DescriptorSetInfo; public: vkHelper(); ~vkHelper(); VkResult initialize(uint32_t _phyDeviceIndex = 0u, uint32_t _descriptorPoolSizeFactor = 1u, bool _debugOutput = true); void shutdown(); VkResult createCommandBuffer(VkCommandBuffer& _outCmdBuffer, VkCommandBufferLevel _level = VK_COMMAND_BUFFER_LEVEL_PRIMARY) const; // command buffers are owned by this vkHelper instance, do not reset or destory manually VkResult createCommandBuffers(std::vector<VkCommandBuffer>& _outCmdBuffers, uint32_t _count, VkCommandBufferLevel _level = VK_COMMAND_BUFFER_LEVEL_PRIMARY) const; void destroyCommandBuffer(VkCommandBuffer _cmdBuffer) const; VkResult beginCommandBuffer(VkCommandBuffer _cmdBuffer, VkCommandBufferUsageFlags _flags = 0u) const; VkResult beginCommandBuffers(const std::vector<VkCommandBuffer>& _cmdBuffers, VkCommandBufferUsageFlags _flags = 0u) const; VkResult endCommandBuffer(VkCommandBuffer _cmdBuffers) const; VkResult endCommandBuffers(const std::vector<VkCommandBuffer>& _cmdBuffers) const; VkResult executeCommandBuffer(VkCommandBuffer _cmdBuffer) const; // make sure there are no dependencies between command buffers. this method is blocking VkResult executeCommandBuffers(const std::vector<VkCommandBuffer>& _cmdBuffers) const; VkResult loadShaderModule(VkShaderModule& _outShader, const uint32_t* _spvBlob, size_t _spvBlobByteSize); // shader module is owned by this vkHelper instance VkResult loadShaderModule(VkShaderModule& _outShader, const char* _path); // TODO: refactor descriptor sets / pipeline layouts into another helper class ? // layouts are owned by this vkHelper instance, do not destory manually VkResult createDecriptorSetLayout(VkDescriptorSetLayout& _outLayout, const VkDescriptorSetLayoutCreateInfo* _pCreateInfo); // this variant adds the created layout to the end of _outLayouts VkResult addDecriptorSetLayout(std::vector<VkDescriptorSetLayout>& _outLayouts, const VkDescriptorSetLayoutCreateInfo* _pCreateInfo); // sets are owned by this vkHelper instance descriptor pool, dont free manually VkResult createDescriptorSet(VkDescriptorSet& _outDescriptorSet, VkDescriptorSetLayout _layout) const; // sets are owned by this vkHelper instance descriptor pool, dont free manually VkResult createDescriptorSets(std::vector<VkDescriptorSet>& _outDescriptorSets, const std::vector<VkDescriptorSetLayout>& _layouts) const; void bindDescriptorSets(VkCommandBuffer _cmdBuffer, VkPipelineLayout _layout, const std::vector<VkDescriptorSet>& _descriptorSets, VkPipelineBindPoint _bindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, uint32_t _firstSet = 0u, const std::vector<uint32_t>& _dynamicOffsets = {}) const; void bindDescriptorSet(VkCommandBuffer _cmdBuffer, VkPipelineLayout _layout, const VkDescriptorSet _descriptorSets, VkPipelineBindPoint _bindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, uint32_t _firstSet = 0u, const std::vector<uint32_t> & _dynamicOffsets = {}) const; void updateDescriptorSets(const std::vector<VkWriteDescriptorSet>& _writes = {}, const std::vector<VkCopyDescriptorSet>& _copies = {}) const; VkResult createPipelineLayout(VkPipelineLayout& _outLayout, const VkDescriptorSetLayout _descriptorLayouts, const std::vector<VkPushConstantRange>& _pushConstantRanges = {}); // layouts are owned by this vkHelper instance, do not destory manually VkResult createPipelineLayout(VkPipelineLayout& _outLayout, const std::vector<VkDescriptorSetLayout>& _descriptorLayouts, const std::vector<VkPushConstantRange>& _pushConstantRanges = {}); // pipelines are owned by this vkHelper instance, do not destory manually VkResult createPipeline(VkPipeline& _outPipeline, const VkGraphicsPipelineCreateInfo* _pCreateInfo); // renderpasses are owned by this vkHelper instance, do not destory manually VkResult createRenderPass(VkRenderPass& _outRenderPass, const VkRenderPassCreateInfo* _pCreateInfo); // returns true if memory type is supported by the device bool getMemoryTypeIndex(const VkMemoryRequirements& _requirements, VkMemoryPropertyFlags _properties, uint32_t& _outIndex); VkResult createBufferAndAllocate(VkBuffer& _outBuffer, uint32_t _byteSize, VkBufferUsageFlags _usage, VkMemoryPropertyFlags _memoryFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VkSharingMode _sharingMode = VK_SHARING_MODE_EXCLUSIVE, VkBufferCreateFlags _flags = 0u); void destroyBuffer(VkBuffer _buffer); VkResult writeBufferData(VkBuffer _buffer, const void* _pData, size_t _bytes); VkResult readBufferData(VkBuffer _buffer, void* _pData, size_t _bytes, size_t _offset=0u); VkResult createImage2DAndAllocate(VkImage& _outImage, uint32_t _width, uint32_t _height, VkFormat _format, VkImageUsageFlags _usage, uint32_t _mipLevels = 1u, uint32_t _arrayLayers = 1u, VkImageTiling _tiling = VK_IMAGE_TILING_OPTIMAL, VkMemoryPropertyFlags _memoryFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VkSharingMode _sharingMode = VK_SHARING_MODE_EXCLUSIVE, VkImageCreateFlags _flags = 0); void destroyImage(VkImage _image); VkResult createImageView(VkImageView& _outView, VkImage _image, VkImageSubresourceRange _range = { VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u }, VkFormat _format = VK_FORMAT_UNDEFINED, VkImageViewType _type = VK_IMAGE_VIEW_TYPE_2D, VkComponentMapping _swizzle = { VK_COMPONENT_SWIZZLE_IDENTITY , VK_COMPONENT_SWIZZLE_IDENTITY ,VK_COMPONENT_SWIZZLE_IDENTITY ,VK_COMPONENT_SWIZZLE_IDENTITY }); void copyBufferToBasicImage2D(VkCommandBuffer _cmdBuffer, VkBuffer _src, VkImage _dst) const; void copyImage2DToBuffer(VkCommandBuffer _cmdBuffer, VkImage _src, VkBuffer _dst, VkImageSubresourceLayers _imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT ,0u, 0u, 1u}) const; void copyImage2DToBuffer(VkCommandBuffer _cmdBuffer, VkImage _src, VkBuffer _dst, const VkBufferImageCopy& _region) const; void imageBarrier(VkCommandBuffer _cmdBuffer, VkImage _image, VkImageLayout _oldLayout, VkImageLayout _newLayout, VkPipelineStageFlags _srcStage, VkAccessFlags _srcAccess, VkPipelineStageFlags _dstStage, VkAccessFlags _dstAccess, VkImageSubresourceRange _subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u}) const; void transitionImageToTransferWrite(VkCommandBuffer _cmdBuffer, VkImage _image, VkImageLayout _oldLayout = VK_IMAGE_LAYOUT_UNDEFINED) const { // TODO: lookup old layout from m_images info and write new layout back to info imageBarrier(_cmdBuffer, _image, _oldLayout, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0u, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); } void transitionImageToShaderRead(VkCommandBuffer _cmdBuffer, VkImage _image, VkImageLayout _oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) const { imageBarrier(_cmdBuffer, _image, _oldLayout, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT); } void transitionImageToTransferRead(VkCommandBuffer _cmdBuffer, VkImage _image, VkImageLayout _oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) const { imageBarrier(_cmdBuffer, _image, _oldLayout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // src stage, access VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT);//dst stage, access } // framebuffer are owned by this vkHelper instance, do not destory manually VkResult createFramebuffer(VkFramebuffer& _outFramebuffer, VkRenderPass _renderPass, uint32_t _width, uint32_t _height, const std::vector<VkImageView>& _attachments, uint32_t _layers = 1u); // simpler helper function using views attached to VkImage VkResult createFramebuffer(VkFramebuffer& _outFramebuffer, VkRenderPass _renderPass, VkImage _image); void beginRenderPass(VkCommandBuffer _cmdBuffer, VkRenderPass _renderPass, VkFramebuffer _framebuffer, const VkRect2D& _area, const std::vector<VkClearValue>& _clearValues = {}, VkSubpassContents _contents = VK_SUBPASS_CONTENTS_INLINE) const; void endRenderPass(VkCommandBuffer _cmdBuffer) const { vkCmdEndRenderPass(_cmdBuffer); }; void fillSamplerCreateInfo(VkSamplerCreateInfo& _samplerInfo); VkResult createSampler(VkSampler& _outSampler, VkSamplerCreateInfo _info); const VkImageCreateInfo* getCreateInfo(const VkImage _image); private: struct Buffer { VkBufferCreateInfo info{}; VkBuffer buffer = VK_NULL_HANDLE; VkDeviceMemory memory = VK_NULL_HANDLE; void destroy(VkDevice _device); }; struct Image { VkImageCreateInfo info{}; VkImage image = VK_NULL_HANDLE; VkDeviceMemory memory = VK_NULL_HANDLE; std::vector<VkImageView> views; void destroy(VkDevice _device); }; VkInstance m_instance = VK_NULL_HANDLE; VkPhysicalDevice m_physicalDevice = VK_NULL_HANDLE; VkPhysicalDeviceFeatures m_deviceFeatures{}; VkPhysicalDeviceMemoryProperties m_memoryProperties{}; VkDevice m_logicalDevice = VK_NULL_HANDLE; VkQueue m_queue = VK_NULL_HANDLE; uint32_t m_queueFamilyIndex = 0u; VkCommandPool m_commandPool = VK_NULL_HANDLE; VkDescriptorPool m_descriptorPool = VK_NULL_HANDLE; VkPipelineCache m_pipelineCache = VK_NULL_HANDLE; std::vector<VkShaderModule> m_shaderModules; std::vector<VkDescriptorSetLayout> m_descriptorSetLayouts; std::vector<VkPipelineLayout> m_pipelineLayouts; std::vector<VkPipeline> m_pipelines; std::vector<VkRenderPass> m_renderPasses; std::vector<VkFramebuffer> m_frameBuffers; std::vector<Buffer> m_buffers; std::vector<Image> m_images; std::vector<VkSampler> m_samplers; bool m_debugOutputEnabled; }; class SpecConstantFactory { public: template <class T> void addConstant(const T& _data, const uint32_t _constantId = UINT32_MAX) { m_entries.emplace_back(); VkSpecializationMapEntry& entry = m_entries.back(); entry.constantID = _constantId == UINT32_MAX ? m_constantId++ : _constantId; entry.offset = static_cast<uint32_t>(m_data.size()); entry.size = sizeof(T); // reserve space m_data.resize(entry.offset + entry.size); memcpy(m_data.data() + entry.offset, &_data, entry.size); } const VkSpecializationInfo* getInfo(); private: uint32_t m_constantId = 0u; VkSpecializationInfo m_info; std::vector<VkSpecializationMapEntry> m_entries; std::vector<uint8_t> m_data; }; class DescriptorSetInfo { public: void addCombinedImageSampler(VkSampler _sampler, VkImageView _imageView, VkImageLayout _imageLayout, uint32_t _binding = UINT32_MAX, VkShaderStageFlags _stages = VK_SHADER_STAGE_FRAGMENT_BIT); void addUniform(VkBuffer _uniform, VkDeviceSize _offset = 0u, VkDeviceSize _range = VK_WHOLE_SIZE, uint32_t _binding = UINT32_MAX, VkShaderStageFlags _stages = VK_SHADER_STAGE_ALL_GRAPHICS); // helper function that creates layout and descriptor set and VkWriteDescriptorSets VkResult create(vkHelper& _instance, std::vector<VkDescriptorSetLayout>& _outLayouts, std::vector<VkDescriptorSet>& _outDescriptorSets); VkResult create(vkHelper& _instance, VkDescriptorSetLayout& _outLayout, VkDescriptorSet& _outDescriptorSet); const VkDescriptorSetLayoutCreateInfo* getLayoutCreateInfo(); const std::vector<VkWriteDescriptorSet>& getWrites() const { return m_writes; } private: void addBinding(VkDescriptorType _type, uint32_t _count = 1u, VkShaderStageFlags _stages = VK_SHADER_STAGE_ALL_GRAPHICS, uint32_t _binding = UINT32_MAX, const VkSampler * _immutableSampler = nullptr); private: struct Resource { Resource(VkBuffer _buffer, VkDeviceSize _offset = 0u, VkDeviceSize _range = VK_WHOLE_SIZE) : buffer({ _buffer, _offset, _range }) {} Resource(VkSampler _sampler, VkImageView _imageView, VkImageLayout _imageLayout) : image({ _sampler, _imageView, _imageLayout }) {} union { VkDescriptorBufferInfo buffer; VkDescriptorImageInfo image; }; }; std::vector<VkDescriptorSetLayoutBinding> m_bindings; std::vector<Resource> m_resources; std::vector<VkWriteDescriptorSet> m_writes; VkDescriptorSetLayout m_layout = VK_NULL_HANDLE; VkDescriptorSet m_descriptorSet = VK_NULL_HANDLE; VkDescriptorSetLayoutCreateInfo m_layoutCreateInfo{}; }; class GraphicsPipelineDesc { public: GraphicsPipelineDesc(); // TODO: copy semantics void addShaderStage(VkShaderModule _shaderModule, VkShaderStageFlagBits _stage, const char* _entryPoint, const VkSpecializationInfo* _specInfo = nullptr); //offset is a byte offset of this attribute relative to the start of an element in the vertex input binding. void addVertexAttribute(VkFormat _format, uint32_t _binding, uint32_t _offset, uint32_t _location = UINT32_MAX); void addVertexBinding(uint32_t _binding, uint32_t _stride, VkVertexInputRate _rate = VK_VERTEX_INPUT_RATE_VERTEX); void addColorBlendAttachment(const VkPipelineColorBlendAttachmentState& _attachment, const uint32_t _count = 1u); void setPrimitiveTopology(VkPrimitiveTopology _topology, bool _enablePrimitiveRestart = false); void setRenderPass(VkRenderPass _renderPass); void setPipelineLayout(VkPipelineLayout _pipelineLayout); void setViewportExtent(VkExtent2D _extent); const VkGraphicsPipelineCreateInfo* getInfo(); private: VkGraphicsPipelineCreateInfo m_info{}; std::vector<VkPipelineShaderStageCreateInfo> m_shaderStages; VkPipelineVertexInputStateCreateInfo m_vertexInput{}; std::vector<VkVertexInputAttributeDescription> m_vertexAttributes; std::vector<VkVertexInputBindingDescription> m_vertexBindings; std::vector<VkPipelineColorBlendAttachmentState> m_colorBlendAttachments; VkPipelineInputAssemblyStateCreateInfo m_inputAssembly{}; VkPipelineTessellationStateCreateInfo m_tesselationState{}; VkViewport m_viewport{}; VkRect2D m_viewportScissor {}; VkPipelineViewportStateCreateInfo m_viewportState{}; VkPipelineRasterizationStateCreateInfo m_rasterState{}; VkPipelineMultisampleStateCreateInfo m_multiSample{}; VkPipelineDepthStencilStateCreateInfo m_depthStencilState{}; VkPipelineColorBlendStateCreateInfo m_colorBlendState{}; VkPipelineDynamicStateCreateInfo m_dynamicState{}; }; class RenderPassDesc { public: RenderPassDesc(); // TODO: copy semantics void addAttachment( VkFormat _format = VK_FORMAT_R8G8B8A8_SRGB, VkAttachmentLoadOp _loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, VkAttachmentStoreOp _storeOp = VK_ATTACHMENT_STORE_OP_STORE, VkSampleCountFlagBits _sampleCount = VK_SAMPLE_COUNT_1_BIT, VkImageLayout _initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, VkImageLayout _finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VkAttachmentLoadOp _stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, VkAttachmentStoreOp _stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE); // TODO: suppasses & dependencies const VkRenderPassCreateInfo* getInfo(); private: VkRenderPassCreateInfo m_info{}; VkSubpassDescription m_subpass{}; //VkSubpassDependency m_subpassDependency{}; std::vector<VkAttachmentReference> m_attachmentRefs; std::vector<VkAttachmentDescription> m_attachments; }; } // IBLLib
46.582317
393
0.813993
[ "vector" ]
e5ddb8a64d7b42b0df5466ac7c64c3bd580515ba
3,261
h
C
AI/Common/Game/Region.h
martinkro/gamedevelop-ai
78815089b96dff11e50a0ffb1880320acd22b109
[ "MIT" ]
null
null
null
AI/Common/Game/Region.h
martinkro/gamedevelop-ai
78815089b96dff11e50a0ffb1880320acd22b109
[ "MIT" ]
null
null
null
AI/Common/Game/Region.h
martinkro/gamedevelop-ai
78815089b96dff11e50a0ffb1880320acd22b109
[ "MIT" ]
null
null
null
#ifndef REGION_H #define REGION_H //------------------------------------------------------------------------ // // Name: Region.h // // Desc: Defines a rectangular region. A region has an identifying // number, and four corners. // // Author: Mat Buckland (fup@ai-junkie.com) // //------------------------------------------------------------------------ #include <math.h> #include "2D/Vector2D.h" #include "misc/Cgdi.h" #include "misc/utils.h" #include "misc/Stream_Utility_Functions.h" class Region { public: enum region_modifier{halfsize, normal}; protected: double m_dTop; double m_dLeft; double m_dRight; double m_dBottom; double m_dWidth; double m_dHeight; Vector2D m_vCenter; int m_iID; public: Region():m_dTop(0),m_dBottom(0),m_dLeft(0),m_dRight(0) {} Region(double left, double top, double right, double bottom, int id = -1):m_dTop(top), m_dRight(right), m_dLeft(left), m_dBottom(bottom), m_iID(id) { //calculate center of region m_vCenter = Vector2D( (left+right)*0.5, (top+bottom)*0.5 ); m_dWidth = fabs(right-left); m_dHeight = fabs(bottom-top); } virtual ~Region(){} virtual inline void Render(bool ShowID)const; //returns true if the given position lays inside the region. The //region modifier can be used to contract the region bounderies inline bool Inside(Vector2D pos, region_modifier r)const; //returns a vector representing a random location //within the region inline Vector2D GetRandomPosition()const; //------------------------------- double Top()const{return m_dTop;} double Bottom()const{return m_dBottom;} double Left()const{return m_dLeft;} double Right()const{return m_dRight;} double Width()const{return fabs(m_dRight - m_dLeft);} double Height()const{return fabs(m_dTop - m_dBottom);} double Length()const{return max(Width(), Height());} double Breadth()const{return min(Width(), Height());} Vector2D Center()const{return m_vCenter;} int ID()const{return m_iID;} }; inline Vector2D Region::GetRandomPosition()const { return Vector2D(RandInRange(m_dLeft, m_dRight), RandInRange(m_dTop, m_dBottom)); } inline bool Region::Inside(Vector2D pos, region_modifier r=normal)const { if (r == normal) { return ((pos.x > m_dLeft) && (pos.x < m_dRight) && (pos.y > m_dTop) && (pos.y < m_dBottom)); } else { const double marginX = m_dWidth * 0.25; const double marginY = m_dHeight * 0.25; return ((pos.x > (m_dLeft+marginX)) && (pos.x < (m_dRight-marginX)) && (pos.y > (m_dTop+marginY)) && (pos.y < (m_dBottom-marginY))); } } inline void Region::Render(bool ShowID = 0)const { gdi->HollowBrush(); gdi->GreenPen(); gdi->Rect(m_dLeft, m_dTop, m_dRight, m_dBottom); if (ShowID) { gdi->TextColor(Cgdi::green); gdi->TextAtPos(Center(), ttos(ID())); } } #endif
24.518797
75
0.558418
[ "render", "vector" ]
e5f3fa0791fdc911c1f1b227220457346f667af5
7,063
h
C
src/parser/VVC/pic_parameter_set_rbsp.h
bitmovin/vvDecPlayer
08bfe881b61be9e300737a253936f25099281bea
[ "MIT" ]
5
2021-11-11T03:17:49.000Z
2022-03-29T16:00:21.000Z
src/parser/VVC/pic_parameter_set_rbsp.h
bitmovin/vvDecPlayer
08bfe881b61be9e300737a253936f25099281bea
[ "MIT" ]
2
2022-01-26T22:37:54.000Z
2022-03-17T12:27:18.000Z
src/parser/VVC/pic_parameter_set_rbsp.h
bitmovin/vvDecPlayer
08bfe881b61be9e300737a253936f25099281bea
[ "MIT" ]
5
2022-02-26T08:54:19.000Z
2022-03-05T02:39:02.000Z
/* MIT License Copyright (c) 2021 Christian Feldmann <christian.feldmann@gmx.de> <christian.feldmann@bitmovin.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "NalUnitVVC.h" #include "commonMaps.h" #include "parser/common/SubByteReaderLogging.h" #include "rbsp_trailing_bits.h" namespace parser::vvc { class pic_parameter_set_rbsp : public NalRBSP { public: pic_parameter_set_rbsp() = default; ~pic_parameter_set_rbsp() = default; void parse(reader::SubByteReaderLogging &reader, SPSMap &spsMap); unsigned pps_pic_parameter_set_id{}; unsigned pps_seq_parameter_set_id{}; bool pps_mixed_nalu_types_in_pic_flag{}; unsigned pps_pic_width_in_luma_samples{}; unsigned pps_pic_height_in_luma_samples{}; bool pps_conformance_window_flag{}; unsigned pps_conf_win_left_offset{}; unsigned pps_conf_win_right_offset{}; unsigned pps_conf_win_top_offset{}; unsigned pps_conf_win_bottom_offset{}; bool pps_scaling_window_explicit_signalling_flag{}; int pps_scaling_win_left_offset{}; int pps_scaling_win_right_offset{}; int pps_scaling_win_top_offset{}; int pps_scaling_win_bottom_offset{}; bool pps_output_flag_present_flag{}; bool pps_no_pic_partition_flag{}; bool pps_subpic_id_mapping_present_flag{}; unsigned pps_num_subpics_minus1{}; unsigned pps_subpic_id_len_minus1{}; vector<unsigned> pps_subpic_id{}; unsigned pps_log2_ctu_size_minus5{}; unsigned pps_num_exp_tile_columns_minus1{}; unsigned pps_num_exp_tile_rows_minus1{}; vector<unsigned> pps_tile_column_width_minus1{}; vector<unsigned> pps_tile_row_height_minus1{}; bool pps_loop_filter_across_tiles_enabled_flag{}; bool pps_rect_slice_flag{true}; bool pps_single_slice_per_subpic_flag{}; unsigned pps_num_slices_in_pic_minus1{}; bool pps_tile_idx_delta_present_flag{}; vector<unsigned> pps_slice_width_in_tiles_minus1{}; vector<unsigned> pps_slice_height_in_tiles_minus1{}; umap_1d<unsigned> pps_num_exp_slices_in_tile{}; vector2d<unsigned> pps_exp_slice_height_in_ctus_minus1{}; vector<int> pps_tile_idx_delta_val{}; bool pps_loop_filter_across_slices_enabled_flag{}; bool pps_cabac_init_present_flag{}; vector<unsigned> pps_num_ref_idx_default_active_minus1{}; bool pps_rpl1_idx_present_flag{}; bool pps_weighted_pred_flag{}; bool pps_weighted_bipred_flag{}; bool pps_ref_wraparound_enabled_flag{}; unsigned pps_pic_width_minus_wraparound_offset{}; int pps_init_qp_minus26{}; bool pps_cu_qp_delta_enabled_flag{}; bool pps_chroma_tool_offsets_present_flag{}; int pps_cb_qp_offset{}; int pps_cr_qp_offset{}; bool pps_joint_cbcr_qp_offset_present_flag{}; int pps_joint_cbcr_qp_offset_value{}; bool pps_slice_chroma_qp_offsets_present_flag{}; bool pps_cu_chroma_qp_offset_list_enabled_flag{}; unsigned pps_chroma_qp_offset_list_len_minus1{}; vector<int> pps_cb_qp_offset_list{}; vector<int> pps_cr_qp_offset_list{}; vector<int> pps_joint_cbcr_qp_offset_list{}; bool pps_deblocking_filter_control_present_flag{}; bool pps_deblocking_filter_override_enabled_flag{}; bool pps_deblocking_filter_disabled_flag{}; bool pps_dbf_info_in_ph_flag{}; int pps_luma_beta_offset_div2{}; int pps_luma_tc_offset_div2{}; int pps_cb_beta_offset_div2{}; int pps_cb_tc_offset_div2{}; int pps_cr_beta_offset_div2{}; int pps_cr_tc_offset_div2{}; bool pps_rpl_info_in_ph_flag{}; bool pps_sao_info_in_ph_flag{}; bool pps_alf_info_in_ph_flag{}; bool pps_wp_info_in_ph_flag{}; bool pps_qp_delta_info_in_ph_flag{}; bool pps_picture_header_extension_present_flag{}; bool pps_slice_header_extension_present_flag{}; bool pps_extension_flag{}; bool pps_extension_data_flag{}; rbsp_trailing_bits rbsp_trailing_bits_instance; vector<unsigned> ColWidthVal; unsigned NumTileColumns; // Size of ColWidthVal vector<unsigned> RowHeightVal; unsigned NumTileRows; // Size of RowHeightVal unsigned NumTilesInPic; vector<unsigned> TileColBdVal; vector<unsigned> TileRowBdVal; vector<unsigned> CtbToTileColBd; vector<unsigned> ctbToTileColIdx; vector<unsigned> CtbToTileRowBd; vector<unsigned> ctbToTileRowIdx; vector<unsigned> SubpicWidthInTiles; vector<unsigned> SubpicHeightInTiles; vector<bool> subpicHeightLessThanOneTileFlag; vector<unsigned> SliceTopLeftTileIdx; umap_1d<unsigned> sliceWidthInTiles; umap_1d<unsigned> sliceHeightInTiles; umap_1d<unsigned> NumSlicesInTile; umap_1d<unsigned> sliceHeightInCtus; umap_2d<unsigned> CtbAddrInSlice; umap_1d<unsigned> NumCtusInSlice; vector<unsigned> NumSlicesInSubpic; umap_1d<unsigned> SubpicIdxForSlice; umap_1d<unsigned> SubpicLevelSliceIdx; vector<unsigned> SubpicIdVal; unsigned PicWidthInCtbsY{}; unsigned PicHeightInCtbsY{}; unsigned PicSizeInCtbsY{}; unsigned PicWidthInMinCbsY{}; unsigned PicHeightInMinCbsY{}; unsigned PicSizeInMinCbsY{}; unsigned PicSizeInSamplesY{}; unsigned PicWidthInSamplesC{}; unsigned PicHeightInSamplesC{}; private: void calculateTileRowsAndColumns(); void calculateTilesInSlices(std::shared_ptr<seq_parameter_set_rbsp> sps); }; } // namespace parser::vvc
43.067073
78
0.699844
[ "vector" ]
f902d6b812d9242786adc1385ab818922f6c39b7
13,439
h
C
DX11_ECSEngine/Components.h
SButtan93-dev/DX11Starter_ECSEngine
4031431f5c617155e82c8c901fc22a3046488dac
[ "MIT" ]
2
2021-02-28T15:36:22.000Z
2021-05-21T13:48:35.000Z
DX11_ECSEngine/Components.h
SButtan93-dev/DX11Starter_ECSEngine
4031431f5c617155e82c8c901fc22a3046488dac
[ "MIT" ]
1
2021-03-15T04:08:32.000Z
2021-03-15T04:08:32.000Z
DX11_ECSEngine/Components.h
SButtan93-dev/DX11Starter_ECSEngine
4031431f5c617155e82c8c901fc22a3046488dac
[ "MIT" ]
null
null
null
#pragma once #include <Windows.h> #include <d3d11.h> #include <string> #include <map> #include <unordered_map> #include <vector> #include <string> #include <d3dcompiler.h> #include <DirectXMath.h> #include "assimp/Importer.hpp" #include "Assimp/assimp/scene.h" #include "Assimp/assimp/postprocess.h" #pragma comment(lib, "d3d11.lib") // ------------------------------------------------- // Contains info about a single Sampler in a shader // ------------------------------------------------- struct BasicSampler { unsigned int Index; // The raw index of the Sampler unsigned int BindIndex; // The register of the Sampler }; // --------------------------------------- // Window screen handle and debug options // --------------------------------------- struct RenderWindow { HINSTANCE hInstance; // The handle to the application std::string titleBarText; // Custom text in window's title bar bool titleBarStats; // Show extra stats in title bar? HWND hWnd; }; // -------------------------------------------------------- // Contains info about a single SRV in a shader // -------------------------------------------------------- struct BasicSRV { unsigned int Index; // The raw index of the SRV unsigned int BindIndex; // The register of the SRV }; // --------------------------------------------------- // Local component, entity could be released once set, // for now it exists with the entity in the registry // --------------------------------------------------- struct RenderWindowDimensions { // Size of the window's client area unsigned int width; unsigned int height; }; // ------------------------------------ // Main GPU variables handled by D3D11 // ------------------------------------ struct RendererMainVars { //D3D_FEATURE_LEVEL dxFeatureLevel; IDXGISwapChain* swapChain = 0; ID3D11Device* device = 0; ID3D11DeviceContext* context = 0; ID3D11RenderTargetView* backBufferRTV = 0; ID3D11DepthStencilView* depthStencilView = 0; D3D_FEATURE_LEVEL dxFeatureLevel; }; // ------------------------------------------------------------------------- // Vertex variables for creating and storing buffers transferred to the GPU // -------------------------------------------------------------------------- struct VertexShaderVars { bool shaderValid; ID3DBlob* shaderBlob; ID3D11Buffer* ConstantBuffer; unsigned int constantBufferCount; }; // ------------------------------------------------------------------------ // Pixel variables for creating and storing buffers transferred to the GPU // ------------------------------------------------------------------------ struct PixelShaderVars { bool shaderValid; ID3DBlob* shaderBlob = 0; ID3D11Buffer* ConstantBuffer = 0; unsigned int constantBufferCount; }; // -----------------------------Sky------------------------------------------- // Vertex variables for creating and storing sky buffers transferred to the GPU // ---------------------------------------------------------------------------- struct SkyVS_Vars { bool shaderValid; ID3DBlob* shaderBlob; ID3D11Buffer* ConstantBuffer; unsigned int constantBufferCount; }; // ---------------------------Sky---------------------------------------------- // Pixel variables for creating and storing sky buffers transferred to the GPU // ---------------------------------------------------------------------------- struct SkyPS_Vars { bool shaderValid; ID3DBlob* shaderBlob = 0; ID3D11Buffer* ConstantBuffer = 0; unsigned int constantBufferCount; }; // ------------------------------------------------------------------------------- // - Attempt to create inputLayout for the vertex shader // - Can be loaded for more shaders for every material, for now it is // attaching with 1 vs and ps i.e. the two .hlsl files // ------------------------------------------------------------------------------- struct InputLayoutVertexShader { bool perInstanceCompatible; ID3D11InputLayout* inputLayout = 0; ID3D11VertexShader* shader = 0; }; // --------------------------------------- // Pixel shader // Load more shaders for every material // --------------------------------------- struct PixelShader { ID3D11PixelShader* shader = 0; }; // ----------------------------------- // Sky vertex shader & input layout // ----------------------------------- struct SkyVarsVertexShader { bool perInstanceCompatible; ID3D11InputLayout* inputLayout = 0; ID3D11VertexShader* shader = 0; }; // ----------------- // Sky pixel shader // ----------------- struct SkyVarsPixelShader { ID3D11PixelShader* shader = 0; }; // ------------------------------------------------------------------------ // - String names passed for creating the two shaders // - Could create the instances of same component // and attach to the same entity to load more shader files in 1 for loop // ------------------------------------------------------------------------ struct ShaderStrings { LPCWSTR vertexShaderString; LPCWSTR pixelShaderString; }; // ------------------------------------------------------------------------ // - String names passed for creating the two shaders // - Could create the instances of same component // and attach to the same entity to load more shader files in 1 for loop // ------------------------------------------------------------------------ struct ShaderStringsSky { LPCWSTR SkyVertexShaderString; LPCWSTR SkyPixelShaderString; }; // -------------------------------------------------------- // Used by simple shaders to store information about // specific variables in constant buffers // -------------------------------------------------------- struct ShaderVariableInfo { unsigned int ByteOffset; unsigned int Size; unsigned int ConstantBufferIndex; }; // ------------------------------------------ // Contains information about a specific // constant buffer in a shader, as well as // the local data buffer for it // ------------------------------------------ struct ConstantBufferInfo { std::string Name; unsigned int Size; unsigned int BindIndex; ID3D11Buffer* ConstantBuffer = 0; unsigned char* LocalDataBuffer; std::vector<ShaderVariableInfo> Variables; }; // ---------------------------Part (1/2)--------------------------------------- // - Vertex shader contents extracted from .hlsl // - Expand for more vertex shaders and search from library with key // ---------------------------------------------------------------------------- struct VertexShaderBuffVars { ConstantBufferInfo* constantBuffers = 0; // For index-based lookup std::vector<BasicSRV*> shaderResourceViews = {0}; std::vector<BasicSampler*> samplerStates = {0}; std::unordered_map<std::string, ConstantBufferInfo*> cbTable; std::unordered_map<std::string, ShaderVariableInfo> varTable; std::unordered_map<std::string, BasicSRV*> textureTable; std::unordered_map<std::string, BasicSampler*> samplerTable; }; // ------------------------------Part (2/2)--------------------------------- // - Pixel shader contents extracted from .hlsl // - Expand for more vertex shaders and search from library with key // ------------------------------------------------------------------------- struct PixelShaderBuffVars { ConstantBufferInfo* constantBuffers; // For index-based lookup std::vector<BasicSRV*> shaderResourceViews; std::vector<BasicSampler*> samplerStates; std::unordered_map<std::string, ConstantBufferInfo*> cbTable; std::unordered_map<std::string, ShaderVariableInfo> varTable; std::unordered_map<std::string, BasicSRV*> textureTable; std::unordered_map<std::string, BasicSampler*> samplerTable; }; //-------------------------Sky Resources--------------------------------------- // ---------------------------Part (1/2)--------------------------------------- // - Vertex shader contents extracted from .hlsl // - Expand for more vertex shaders and search from library with key // ---------------------------------------------------------------------------- struct VertexShaderBuffSkyVars { ConstantBufferInfo* constantBuffers = 0; // For index-based lookup std::vector<BasicSRV*> shaderResourceViews = { 0 }; std::vector<BasicSampler*> samplerStates = { 0 }; std::unordered_map<std::string, ConstantBufferInfo*> cbTable; std::unordered_map<std::string, ShaderVariableInfo> varTable; std::unordered_map<std::string, BasicSRV*> textureTable; std::unordered_map<std::string, BasicSampler*> samplerTable; }; //------------------------------Sky Resources------------------------------- // ------------------------------Part (2/2)--------------------------------- // - Pixel shader contents extracted from .hlsl // - Expand for more vertex shaders and search from library with key // ------------------------------------------------------------------------- struct PixelShaderBuffSkyVars { ConstantBufferInfo* constantBuffers; // For index-based lookup std::vector<BasicSRV*> shaderResourceViews; std::vector<BasicSampler*> samplerStates; std::unordered_map<std::string, ConstantBufferInfo*> cbTable; std::unordered_map<std::string, ShaderVariableInfo> varTable; std::unordered_map<std::string, BasicSRV*> textureTable; std::unordered_map<std::string, BasicSampler*> samplerTable; }; // --------------------------------------------- // Store mesh buffers after loading into device. // --------------------------------------------- struct MeshRenderVars { ID3D11Buffer* vb; ID3D11Buffer* ib; int numIndices; }; // -------------------Sky mesh ------------------ // Store mesh buffers after loading into device. // --------------------------------------------- struct MeshRenderVarsSky { ID3D11Buffer* vb; ID3D11Buffer* ib; int numIndices; }; // ------------------------ // Sky file format buffers // ------------------------ struct SkyVars { ID3D11ShaderResourceView* skySRV; ID3D11RasterizerState* skyRasterState; ID3D11DepthStencilState* skyDepthState; }; // ------------------------- // Calculate for each frame // ------------------------- struct TimeData { // Timing related data double perfCounterSeconds; float totalTime; float deltaTime; __int64 startTime; __int64 currentTime; __int64 previousTime; }; // ----------------- // window titlebar // ----------------- struct FPSData { // FPS calculation int fpsFrameCount; float fpsTimeElapsed; }; // --------------------------------------------------------- // A custom vertex definition // - Calculate and store position, uv space, normal & Bone info // to the camera for each mesh entity passed to the shader // --------------------------------------------------------- struct Vertex { DirectX::XMFLOAT3 Position; // The position of the vertex DirectX::XMFLOAT2 UV; // UV Coordinate for texturing DirectX::XMFLOAT3 Normal; // Normal for lighting DirectX::XMINT4 BoneIDs; DirectX::XMFLOAT4 Weights; }; // ------------------------------------------------------------- // - Pass 'worldMatrix' to vertex shader // each frame for each entity // - Could change transform component for each mesh every frame // ------------------------------------------------------------- struct MeshEntityData { DirectX::XMFLOAT4X4 worldMatrix; DirectX::XMFLOAT3 position; DirectX::XMFLOAT3 rotation; DirectX::XMFLOAT3 scale; }; // ------------------------------------------------------------- // - Pass 'worldMatrix' to vertex shader // each frame for each entity // - Could change transform component for each mesh every frame // ------------------------------------------------------------- struct MeshEntityDataSky { DirectX::XMFLOAT4X4 worldMatrix; DirectX::XMFLOAT3 position; DirectX::XMFLOAT3 rotation; DirectX::XMFLOAT3 scale; }; // -------------- // Bone resources // -------------- struct BoneInfo { DirectX::XMMATRIX BoneOffset; DirectX::XMMATRIX FinalTransformation; }; struct MeshBoneData { std::map<std::string, UINT> mBoneMapping; // maps a bone name to its index std::vector<BoneInfo> mBoneInfo; UINT mNumBones; DirectX::XMMATRIX GlobalInverseTransform; }; // ------------------- // Texture resources // ------------------- struct TextureData { ID3D11ShaderResourceView* crateSRV; // Need one of these PER TEXTURE! ID3D11ShaderResourceView* rustSRV; ID3D11ShaderResourceView* specSRV; ID3D11SamplerState* sampler; // Need at LEAST one per program (special fx may require their own) }; // ----------------------------------------------------------- // - Pass view & proj matrices each frame to vertex shader // - Use transforms with windows call proc 'ProcessMessage()' // to modify data before sending to GPU // - Need to implement logic for rotations // ----------------------------------------------------------- struct CameraComponents { // Camera matrices DirectX::XMFLOAT4X4 viewMatrix; DirectX::XMFLOAT4X4 projMatrix; // Transformations DirectX::XMFLOAT3 startPosition; DirectX::XMFLOAT3 position; DirectX::XMFLOAT4 rotation; float xRotation; float yRotation; }; // NA class Components { public: Components(); ~Components(); };
30.132287
98
0.529727
[ "mesh", "vector", "transform" ]
f918ed894a86b3c670fa54159aca4992b8268173
4,212
h
C
src/pillowtalk.h
jubos/pillowtalk
75ea5f071495fb181d55ff7833db3dbd7ab5a676
[ "MIT" ]
10
2015-04-04T15:07:46.000Z
2020-05-27T02:35:21.000Z
src/pillowtalk.h
AutomationIntegrated/pillowtalk
75ea5f071495fb181d55ff7833db3dbd7ab5a676
[ "MIT" ]
null
null
null
src/pillowtalk.h
AutomationIntegrated/pillowtalk
75ea5f071495fb181d55ff7833db3dbd7ab5a676
[ "MIT" ]
5
2015-12-16T18:26:19.000Z
2021-12-06T03:31:47.000Z
// // Copyright (c) 2009, Curtis Spencer. All rights reserved. // #ifndef __PILLOWTALK__H_ #define __PILLOWTALK__H_ #ifdef __cplusplus extern "C" { #endif typedef enum {PT_MAP,PT_ARRAY,PT_NULL, PT_BOOLEAN, PT_INTEGER, PT_DOUBLE, PT_STRING, PT_KEY_VALUE} pt_type_t; typedef struct { pt_type_t type; } pt_node_t; typedef struct { pt_node_t* root; long response_code; char* raw_json; int raw_json_len; } pt_response_t; // Opaque type for iterator typedef struct { } pt_iterator_t; void pt_init(); void pt_cleanup(); void pt_free_node(pt_node_t* node); void pt_free_response(pt_response_t* res); /***** HTTP Related Functions ******/ pt_response_t* pt_delete(const char* server_target); pt_response_t* pt_put(const char* server_target, pt_node_t* document); pt_response_t* pt_put_raw(const char* server_target, const char* data, unsigned int data_len); /* * Do an HTTP get request on the target and parse the resulting JSON into the * pt_response object */ pt_response_t* pt_get(const char* server_target); /* * This will just do a get against the server target and not try to parse it at all. * It is useful for doing your own parsing with the resultant JSON */ pt_response_t* pt_unparsed_get(const char* server_target); /***** Node Related Functions ******/ /* * Once you have a node, you can call various functions on it, and most will * return NULL if you do it on the wrong type. Check the type attribute of the * pt_node_t to ensure you are doing the correct operation. */ pt_node_t* pt_map_get(pt_node_t* map,const char* key); unsigned int pt_array_len(pt_node_t* array); pt_node_t* pt_array_get(pt_node_t* array, unsigned int idx); int pt_is_null(pt_node_t* null); int pt_boolean_get(pt_node_t* boolean); int pt_integer_get(pt_node_t* integer); double pt_double_get(pt_node_t* dbl); const char* pt_string_get(pt_node_t* string); /* * The following functions are used to change a pt_node_t to do update * operations or get new json strings */ void pt_map_set(pt_node_t* map, const char* key, pt_node_t* value); void pt_map_unset(pt_node_t* map, const char* key); pt_node_t* pt_null_new(); pt_node_t* pt_bool_new(int boolean); pt_node_t* pt_integer_new(int integer); pt_node_t* pt_double_new(double dbl); pt_node_t* pt_string_new(const char* str); pt_node_t* pt_map_new(); pt_node_t* pt_array_new(); void pt_array_push_back(pt_node_t* array, pt_node_t* elem); void pt_array_push_front(pt_node_t* array, pt_node_t* elem); /* * This will remove elem if it exists in the array and free it as well, so * don't use elem after this */ void pt_array_remove(pt_node_t* array, pt_node_t* elem); /* * Build an iterator from an array/map node. If you pass in an unsupported * node it will return NULL */ pt_iterator_t* pt_iterator(pt_node_t* node); /* * This returns the next node in the iterator back and NULL when complete. * * The key char** is also set to the key of a key value pair if you are * iterating through a map * */ pt_node_t* pt_iterator_next(pt_iterator_t* iter, const char** key); /* * Convert a pt_node_t structure into a raw json string */ char* pt_to_json(pt_node_t* root, int beautify); /* * Take a raw json string and turn it into a pillowtalk structure */ pt_node_t* pt_from_json(const char* json); /* * Merge additions into an existing pt_node * * For example if your root looks like this * { * "name" : "Curtis", * "favorite_food" : "Bread" * } * * and your additions look like this * * { * "favorite_game" : "Street Fighter II" * } * * then the resulting json in root would be * * { * "name" : "Curtis", * "favorite_food" : "Bread", * "favorite_game" : "Street Fighter II" * } * * @return a nonzero error code if something cannot properly be merged. For * example, if a key in the root is an array and the additions has it as a hash * then it will give up there, but it won't rollback so be careful. */ int pt_map_update(pt_node_t* root, pt_node_t* additions,int append); /* * This method is useful if you want to clone a root you are working on to make * changes to it */ pt_node_t* pt_clone(pt_node_t* root); #ifdef __cplusplus } #endif #endif // _PILLOWTALK_H_
25.682927
109
0.728395
[ "object" ]
f9204ca9243b389fd91a041d5d44aac197b45888
10,055
h
C
task-movement/Koala/container/joinsets.h
miloszc/task-movement
26b40595b590b0fcc3c226fbe8576faa3b5c1244
[ "MIT" ]
null
null
null
task-movement/Koala/container/joinsets.h
miloszc/task-movement
26b40595b590b0fcc3c226fbe8576faa3b5c1244
[ "MIT" ]
19
2019-02-15T09:04:22.000Z
2020-06-23T21:42:29.000Z
task-movement/Koala/container/joinsets.h
miloszc/task-movement
26b40595b590b0fcc3c226fbe8576faa3b5c1244
[ "MIT" ]
1
2019-05-04T16:12:25.000Z
2019-05-04T16:12:25.000Z
#ifndef KOALA_JOINABLE_SETS_H #define KOALA_JOINABLE_SETS_H /** \file joinsets.h * \brief Joinable sets (optional). */ #include <cassert> #include <map> #include "../container/assoctab.h" #include "../container/localarray.h" #include "../container/set.h" namespace Koala { /** \brief Auxiliary structure for joinable sets. * * The structure represents joinable set. */ template< class Klucz > class JSPartDesrc { template< class K,class Cont > friend class JoinableSets; JSPartDesrc *parent,*next,*first,*last; unsigned int deg,size; Klucz key; public: /** \brief Constructor */ JSPartDesrc() {} }; namespace Privates { template <class Klucz> struct JoinSetsIntPseudoMap { typedef JSPartDesrc< Klucz > * ValType; std::vector<std::pair<ValType,bool> > cont; JoinSetsIntPseudoMap(int asize=0) : cont(asize) {} void clear() { cont.clear(); } void reserve(int asize) { cont.resize(asize); } bool hasKey(int arg) const { koalaAssert( arg>=0 && arg < cont.size(),ContExcOutpass ); return cont[arg].second; } ValType& operator[](int arg) { koalaAssert( arg>=0 && arg < cont.size(),ContExcOutpass ); cont[arg].second=true; return cont[arg].first; } ValType operator[](int arg) const { koalaAssert( arg>=0 && arg < cont.size(),ContExcOutpass ); if (!cont[arg].second) return ValType(); return cont[arg].first; } }; template <class Klucz> struct JoinSetsAssocContSwitch { typedef JoinSetsIntPseudoMap< Klucz > Type; }; template <class T> struct JoinSetsAssocContSwitch<T*> { typedef AssocArray< T*,JSPartDesrc< T* > * > Type; }; } /** \brief Joinable Sets. * * Class of disjoint sets. Useful when: * - the set of elements is known in advance, * - fast operations of joining two or more sets is required. * * In other words JoinableSets class can by used to represent various partitions of set with fast union. * The structure is used for example in the implementation of Kruskal algorithm for minimal weight spanning tree. * \tparam ITEM class of stored element. * \tparam AssocContainer type of internal associative array. <tt>ITEM->JSPartDesrc< ITEM > *</tt>. * If it is AssocArray then the key should point at object witch includes field AssocKeyContReg \a assocReg. * \ingroup cont*/ // template< class ITEM, class AssocContainer = AssocArray< ITEM,JSPartDesrc< ITEM > * > > template< class ITEM, class AssocContainer = typename Privates::JoinSetsAssocContSwitch<ITEM>::Type > class JoinableSets { protected: AssocContainer mapa; JSPartDesrc< ITEM > *bufor; size_t siz,part_no,maxsize; public: typedef JSPartDesrc< ITEM > *Repr; /**<\brief Identifier of set.*/ typedef ITEM ElemType; /**<\brief Element of set.*/ /** \brief Constructor. * * \param n the minimal capacity of the set of all elements.*/ JoinableSets( unsigned int n = 0 ); /** \brief Copy constructor.*/ JoinableSets( const JoinableSets< ITEM,AssocContainer > & ); /** \brief Content copy operator.*/ JoinableSets &operator=( const JoinableSets< ITEM,AssocContainer > & ); ~JoinableSets() { resize( 0 ); } /** \brief Resize. * * The method clears the set and change the maximal number of elements. * \param n the new number of elements.*/ void resize( unsigned int n ); /** \brief Get number of elements. * * \return the number of all elements in the container (in all sets). */ int size() const { return siz; } /** \brief Get number of elements in set identified by \a s. * * \param s identifier of set. * \return the number of elements in set identified by \a s. */ int size( typename JoinableSets< ITEM >::Repr s) const; /** \brief Get number of elements in set element \a i is in. * * \param i the reference to the element the tested set is in. * \return the number of elements in the set that includes \a i or 0 if there is no such element. */ int size( const ITEM &i ) const; /** \brief Test if empty. * * \return true if the container is empty, false otherwise. */ bool empty() const { return siz == 0; } /** \copydoc empty */ bool operator!() const { return empty(); } /** \brief Delete all elements. * * The method deletes all the elements from container, the capacity becomes 0. */ void clear() { resize( 0 ); } /** \brief Get the number of parts. * * \return the number of sets in container. */ int getSetNo() const { return part_no; } /** \brief Get elements. * * The method gets all the elements from and writes them down in \a iter. * \param[out] iter the output iterator to the container with all elements. * \tparam Iter the type of iterator. * \return the number of elements.*/ template< class Iter > int getElements( Iter iter ) const; /** \brief Get identifiers. * * The method puts the identifiers of sets to \a iter. * \param[out] iter the iterator to the container with sets identifiers JSPartDesrc< ITEM > *. * \tparam Iter the type of iterator * \return the number of parts.*/ template< class Iter > int getSetIds( Iter iter) const; /** \brief Get elements of part. * * The method gets all the elements of part identifier \a s. The result is kept in container \a iter. * \param s the identifier (representative) of set part (subset). * \param[out] iter the iterator to the container with all the elements of part \a s. * \tparam Iter the type of iterator. * \return the number of elements in the part.*/ template< class Iter > int getSet( typename JoinableSets< ITEM >::Repr s, Iter iter ) const; /** \brief Get elements of part. * * The method gets all the elements of part containing the element \a i. The result is kept in container \a iter. * \param i the reference element that identifies the considered set. * \param[out] iter the iterator to the container with all the elements of set \a i is included. * \tparam Iter the type of iterator. * \return the number of elements in the part.*/ template< class Iter > int getSet( const ITEM &i, Iter iter ) const { return getSet( getSetId( i ),iter ); } /** \brief Make single element. * * The method creates new part with new single element. This is the only method of adding new elements to joinable set. * \param i the added element. * \return the identifier of the new created part or 0 if the element \a i already belongs to any part. */ inline typename JoinableSets< ITEM >::Repr makeSinglet( const ITEM &i ); /** \brief Get set identifier. * * The method gets the identifier of part the element \a i belongs to. * \param i the considered element. * \return the identifier of part the element belongs to or 0 if there is no such element in set like \a i.*/ inline typename JoinableSets<ITEM>::Repr getSetId( const ITEM &i ) const; /** \brief Get set identifier. * * The method gets the current identifier of the set, for which the subset represented by identifier \a s now belongs to. * \param s the identifier of the set that is now a part of a bigger set. * \return the identifier of part, the block \a s is subset of.*/ inline typename JoinableSets<ITEM>::Repr getSetId( typename JoinableSets< ITEM >::Repr s ) const; /** \brief Join parts. * * The method joins two parts represented by the identifiers \a a and \a b. The method does nothing if \a a = \a b. * \param a the identifier of the first part. * \param b the identifier of the second part. * \return the identifier of new joined set or NULL if \a a was equal to \a b. */ inline typename JoinableSets<ITEM>::Repr join( typename JoinableSets< ITEM >::Repr a, typename JoinableSets< ITEM >::Repr b ); /** \brief Join parts. * * The method joins two parts represented by the identifiers \a a and \a b. The method does nothing if \a a and \a b belong to the same set. * \param a the element from the first part. * \param b the element from the second part. * \return the identifier of new joined set. Or NULL if \a a or \a b are not in the domain or if they belong to the same set.*/ inline typename JoinableSets< ITEM >::Repr join( const ITEM &a, const ITEM &b ); /** \brief Join parts. * * The method joins two parts represented by the identifier \a a and element \a b. The method does nothing if element \a b belongs to the set represented by \a a. * \param a the identifier of the first part. * \param b the element from the second part. * \return the identifier of new joined set. Or NULL if \a b is not in the domain or if \a b already belongs to set the set \a a.*/ inline typename JoinableSets< ITEM >::Repr join( typename JoinableSets< ITEM >::Repr a, const ITEM &b ); /** \brief Join parts. * * The method joins two parts represented by the identifiers \a a and \a b. The method does nothing if element \a a belongs to the set represented by \a b. * \param a the element from the first part. * \param b the identifier of the second part. * \return the identifier of new joined set. Or NULL if \a a is not in the domain or if \a a already belongs to set the set \a b.*/ inline typename JoinableSets< ITEM >::Repr join( const ITEM &a, typename JoinableSets< ITEM >::Repr b ); }; /** \brief Overloaded output operator. * * The overloaded shift operator for std::ostream and JoinableSets. Allows to print easily all the elements of JoinalbeSets . * \related JoinableSets */ template< typename Element, typename Cont > std::ostream &operator<<( std::ostream &,const JoinableSets< Element,Cont > & ); #include "joinsets.hpp" } #endif
39.586614
165
0.659274
[ "object", "vector" ]
f929af539a26f11babb62907f7d07637e85c26fb
18,016
c
C
sdk-6.5.20/src/examples/xgs/maverick2/mpls/vpws_frr.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/src/examples/xgs/maverick2/mpls/vpws_frr.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/src/examples/xgs/maverick2/mpls/vpws_frr.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
/* * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenSDK/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ /* * Feature : VPWS with failover * * Usage : BCM.0> cint vpws_frr.c * * config : mpls_config.bcm * * Log file : vpws_frr_log.txt * * Test Topology : * * +------------------------------+ * | | * | | * | +-----------------+ * access_port | | network_primary_port * +----------------+ SWITCH | * | | * | | * | +-----------------+ * | | network_backup_port * | | * +------------------------------+ * Summary: * ======== * This Cint example to show configuration of VPWS with failover/protection * switching mechanism using BCM APIs. * * Detailed steps done in the CINT script: * ======================================= * 1) Step1 - Test Setup (Done in test_setup()): * ============================================= * a) Selects three ports and configure them in Loopback mode. Out of these * two ports, one port is used as access_port and the other as * network_ports (primary & backup). * * b) Install an IFP rule to copy incoming packets to CPU and start * packet watcher. * * Note: IFP rule is meant for a testing purpose only (Internal) and it is * nothing to do with an actual functional test. * * 2) Step2 - Configuration (Done in config_vpws_frr()): * ========================================================= * a) Configure a basic VPWS Tunnel initiation/termination flow with failover * functional scenario and does the necessary configurations of vlan, * interface and next hop. * * 3) Step3 - Verification (Done in verify()): * =========================================== * a) Check the configurations by 'vlan show', 'l3 intf show' and * 'l3 egress show'. * * b) Transmit the customer packet with single VLAN on access port, then set * the failoverId and resend the same customer packet on access port. * The contents of the packet are printed on screen. * * c) Expected Result: * =================== * We can see that VPWS tunnel initiation flows out of network_primary_port * (primary-path) for the first packet and after setting failoverId, * egress traffic switchovers to network_backup_port (backup-path). * The contents of the packet are printed on screen. * Also run the 'show c' to check the Tx/Rx packet stats/counters. */ /* Reset C interpreter*/ cint_reset(); bcm_port_t access_port; bcm_port_t network_primary_port; bcm_port_t network_backup_port; bcm_failover_t failoverId = 0; /* * This function is written so that hardcoding of port * numbers in Cint scripts is removed. This function gives * required number of ports */ bcm_error_t portNumbersGet(int unit, int *port_list, int num_ports) { int i = 0, port = 0, rv = 0; bcm_port_config_t configP; bcm_pbmp_t ports_pbmp; rv = bcm_port_config_get(unit, &configP); if (BCM_FAILURE(rv)) { printf("\nError in retrieving port configuration: %s.\n",bcm_errmsg(rv)); return rv; } ports_pbmp = configP.e; for (i= 1; i < BCM_PBMP_PORT_MAX; i++) { if (BCM_PBMP_MEMBER(&ports_pbmp, i) && (port < num_ports)) { port_list[port] = i; port++; } } if ((0 == port) || (port != num_ports)) { printf("portNumbersGet() failed \n"); return -1; } return BCM_E_NONE; } /* * Configures the port in loopback mode and installs * an IFP rule. This IFP rule copies the packets ingressing * on the specified port to CPU. */ bcm_error_t ingress_port_setup(int unit, bcm_port_t port) { bcm_field_qset_t qset; bcm_field_group_t group; bcm_field_entry_t entry; BCM_IF_ERROR_RETURN(bcm_port_loopback_set(unit, port, BCM_PORT_LOOPBACK_MAC)); BCM_IF_ERROR_RETURN(bcm_port_discard_set(unit, port, BCM_PORT_DISCARD_NONE)); BCM_FIELD_QSET_INIT(qset); BCM_FIELD_QSET_ADD(qset, bcmFieldQualifyInPort); BCM_IF_ERROR_RETURN(bcm_field_group_create(unit, qset, BCM_FIELD_GROUP_PRIO_ANY, &group)); BCM_IF_ERROR_RETURN(bcm_field_entry_create(unit, group, &entry)); BCM_IF_ERROR_RETURN(bcm_field_qualify_InPort(unit, entry, port, BCM_FIELD_EXACT_MATCH_MASK)); BCM_IF_ERROR_RETURN(bcm_field_action_add(unit, entry, bcmFieldActionCopyToCpu, 0, 0)); BCM_IF_ERROR_RETURN(bcm_field_entry_install(unit, entry)); return BCM_E_NONE; } /* * Configures the port in loopback mode and installs * an IFP rule. This IFP rule copies the packets ingressing * on the specified port to CPU. Port is also configured * to discard all packets. This is to avoid continuous * loopback of the packet. */ bcm_error_t egress_port_setup(int unit, bcm_port_t port) { bcm_field_qset_t qset; bcm_field_group_t group; bcm_field_entry_t entry; BCM_IF_ERROR_RETURN(bcm_port_loopback_set(unit, port, BCM_PORT_LOOPBACK_MAC)); BCM_IF_ERROR_RETURN(bcm_port_discard_set(unit, port, BCM_PORT_DISCARD_ALL)); BCM_FIELD_QSET_INIT(qset); BCM_FIELD_QSET_ADD(qset, bcmFieldQualifyInPort); BCM_IF_ERROR_RETURN(bcm_field_group_create(unit, qset, BCM_FIELD_GROUP_PRIO_ANY, &group)); BCM_IF_ERROR_RETURN(bcm_field_entry_create(unit, group, &entry)); BCM_IF_ERROR_RETURN(bcm_field_qualify_InPort(unit, entry, port, BCM_FIELD_EXACT_MATCH_MASK)); BCM_IF_ERROR_RETURN(bcm_field_action_add(unit, entry, bcmFieldActionCopyToCpu, 0, 0)); BCM_IF_ERROR_RETURN(bcm_field_entry_install(unit, entry)); return BCM_E_NONE; } /* * Test Setup: * This functions gets the port numbers and sets up ingress and * egress ports. Check ingress_port_setup() and egress_port_setup(). */ bcm_error_t test_setup(int unit) { int port_list[3], i; if (BCM_E_NONE != portNumbersGet(unit, port_list, 3)) { printf("portNumbersGet() failed\n"); return -1; } access_port = port_list[0]; network_primary_port = port_list[1]; network_backup_port = port_list[2]; if (BCM_E_NONE != ingress_port_setup(unit, access_port)) { printf("ingress_port_setup() failed for port %d\n", access_port); return -1; } for (i = 1; i <= 2; i++) { if (BCM_E_NONE != egress_port_setup(unit, port_list[i])) { printf("egress_port_setup() failed for port %d\n", port_list[i]); return -1; } } bshell(unit, "pw start report +raw +decode"); return BCM_E_NONE; } void verify(int unit) { char str[512]; bshell(unit, "hm ieee"); bshell(unit, "vlan show"); bshell(unit, "l3 intf show"); bshell(unit, "l3 egress show"); bshell(unit, "clear c"); BCM_IF_ERROR_RETURN(bcm_port_discard_set(unit, access_port, BCM_PORT_DISCARD_NONE)); BCM_IF_ERROR_RETURN(bcm_port_discard_set(unit, network_primary_port, BCM_PORT_DISCARD_ALL)); BCM_IF_ERROR_RETURN(bcm_port_discard_set(unit, network_backup_port, BCM_PORT_DISCARD_ALL)); printf("\na) Sending a customer packet with Single VLAN to access_port:%d\n", access_port); snprintf(str, 512, "tx 1 pbm=%d data=0x000000000001000000AABBCC8100001508004500002E0000000040FFA920BEA80A0104040404000102030405060708090A0B0C0D0E0F10111213141516171819ED54ED54; sleep quiet 1", access_port); bshell(unit, str); bshell(unit, "show c"); bshell(unit, "sleep 1"); bshell(unit, "clear c"); print "Switch-over from primary-path to backup/protection-path"; /* Set Failover, traffic going through backup path */ BCM_IF_ERROR_RETURN(bcm_failover_set(unit, failoverId, 1)); printf("\nb) Re-Sending a customer packet with Single VLAN to access_port:%d\n", access_port); snprintf(str, 512, "tx 1 pbm=%d data=0x000000000001000000AABBCC8100001508004500002E0000000040FFA920BEA80A0104040404000102030405060708090A0B0C0D0E0F10111213141516171819ED54ED54; sleep quiet 1", access_port); bshell(unit, str); bshell(unit, "show c"); bshell(unit, "sleep 1"); bshell(unit, "clear c"); return; } bcm_error_t config_vpws_frr(int unit) { bcm_port_t c_port = access_port; bcm_port_t p_port_backup = network_backup_port; bcm_port_t p_port_primary = network_primary_port; bcm_gport_t c_gport, p_gport_backup, p_gport_primary; bcm_vlan_t c_vid = 21; bcm_vlan_t p_vid_backup = 22; bcm_vlan_t p_vid_primary = 23; bcm_mpls_vpn_config_t vpn_info; int intf_id_backup = 1; int intf_id_primary = 2; int ttl = 16; uint32 tunnel_label_init_backup = 0x111; /* 273 */ uint32 tunnel_label_init_primary = 0x555; /* 1365 */ uint32 vc_label_term_backup = 0x333; /* 819 */ uint32 vc_label_term_primary = 0x777; /* 1911 */ uint32 vc_label_init_backup = 0x444; /* 1092 */ uint32 vc_label_init_primary = 0x666; /* 1638 */ bcm_l3_egress_t l3_egress_backup; bcm_if_t l3_egr_obj_backup; bcm_l3_egress_t l3_egress_primary; bcm_if_t l3_egr_obj_primary; bcm_l3_intf_t l3_intf_backup; bcm_l3_intf_t l3_intf_primary; bcm_mpls_egress_label_t mpls_egress_label[2]; bcm_mac_t remote_mac_backup = {00, 00, 00, 00, 00, 01}; bcm_mac_t local_mac_backup = {00, 00, 00, 00, 11, 11}; bcm_mac_t remote_mac_primary = {00, 00, 00, 00, 00, 02}; bcm_mac_t local_mac_primary = {00, 00, 00, 00, 22, 22}; bcm_mpls_port_t cust_mpls_port; /* customer port */ bcm_mpls_port_t service_mpls_port_backup; /* provider port */ bcm_mpls_port_t service_mpls_port_primary; /* provider port */ /* Init Failover */ bcm_failover_init(unit); /* * Initialize gport values */ BCM_IF_ERROR_RETURN(bcm_port_gport_get(unit, c_port, &c_gport)); printf("c_gport=0x%x\n", c_gport); BCM_IF_ERROR_RETURN(bcm_port_gport_get(unit, p_port_backup, &p_gport_backup)); printf("c_gport=0x%x\n", p_gport_backup); BCM_IF_ERROR_RETURN(bcm_port_gport_get(unit, p_port_primary, &p_gport_primary)); printf("c_gport=0x%x\n", p_gport_primary); /* Create VLANs */ BCM_IF_ERROR_RETURN(bcm_vlan_create(unit, c_vid)); BCM_IF_ERROR_RETURN(bcm_vlan_gport_add(unit, c_vid, c_gport, 0)); BCM_IF_ERROR_RETURN(bcm_vlan_create(unit, p_vid_backup)); BCM_IF_ERROR_RETURN(bcm_vlan_gport_add(unit, p_vid_backup, p_gport_backup, 0)); BCM_IF_ERROR_RETURN(bcm_vlan_create(unit, p_vid_primary)); BCM_IF_ERROR_RETURN(bcm_vlan_gport_add(unit, p_vid_primary, p_gport_primary, 0)); /* * Enable L3 egress mode & VLAN translation */ BCM_IF_ERROR_RETURN(bcm_switch_control_set(unit, bcmSwitchL3EgressMode, 1)); BCM_IF_ERROR_RETURN(bcm_vlan_control_set(unit, bcmVlanTranslate, 1)); BCM_IF_ERROR_RETURN(bcm_switch_control_set(unit, bcmSwitchL2StaticMoveToCpu, 1)); /* * Create tunnel A - failover */ /* Create L3 interface for MPLS tunnel A */ bcm_l3_intf_t_init(&l3_intf_backup); l3_intf_backup.l3a_flags |= BCM_L3_WITH_ID | BCM_L3_ADD_TO_ARL; l3_intf_backup.l3a_intf_id = intf_id_backup; sal_memcpy(l3_intf_backup.l3a_mac_addr, local_mac_backup, 6); l3_intf_backup.l3a_vid = p_vid_backup; BCM_IF_ERROR_RETURN(bcm_l3_intf_create(unit, &l3_intf_backup)); /* Set MPLS tunnel initiator A */ bcm_mpls_egress_label_t_init(&mpls_egress_label[0]); bcm_mpls_egress_label_t_init(&mpls_egress_label[1]); mpls_egress_label[0].flags = BCM_MPLS_EGRESS_LABEL_TTL_SET; mpls_egress_label[0].label = tunnel_label_init_backup; mpls_egress_label[0].ttl = ttl; BCM_IF_ERROR_RETURN(bcm_mpls_tunnel_initiator_set(unit, l3_intf_backup.l3a_intf_id, 1, mpls_egress_label)); /* Create L3 egress object for MPLS tunnel A */ bcm_l3_egress_t_init(&l3_egress_backup); l3_egress_backup.intf = intf_id_backup; sal_memcpy(l3_egress_backup.mac_addr, remote_mac_backup, 6); l3_egress_backup.vlan = p_vid_backup; l3_egress_backup.port = p_gport_backup; BCM_IF_ERROR_RETURN(bcm_l3_egress_create(unit, 0, &l3_egress_backup, &l3_egr_obj_backup)); /* Create Failover object */ BCM_IF_ERROR_RETURN(bcm_failover_create(unit, 0, &failoverId)); print("Failover group %d\n", failoverId); /* * Create tunnel B - primary */ /* Create L3 interface for MPLS tunnel B */ bcm_l3_intf_t_init(&l3_intf_primary); l3_intf_primary.l3a_flags = BCM_L3_WITH_ID | BCM_L3_ADD_TO_ARL; l3_intf_primary.l3a_intf_id = intf_id_primary; sal_memcpy(l3_intf_primary.l3a_mac_addr, local_mac_primary, 6); l3_intf_primary.l3a_vid = p_vid_primary; BCM_IF_ERROR_RETURN(bcm_l3_intf_create(unit, &l3_intf_primary)); /* Set MPLS tunnel initiator B */ bcm_mpls_egress_label_t_init(&mpls_egress_label[0]); bcm_mpls_egress_label_t_init(&mpls_egress_label[1]); mpls_egress_label[0].flags = BCM_MPLS_EGRESS_LABEL_TTL_SET; mpls_egress_label[0].label = tunnel_label_init_primary; mpls_egress_label[0].ttl = ttl; BCM_IF_ERROR_RETURN(bcm_mpls_tunnel_initiator_set(unit, intf_id_primary, 1, mpls_egress_label)); /* Create L3 egress object for MPLS tunnel B */ bcm_l3_egress_t_init(&l3_egress_primary); l3_egress_primary.intf = intf_id_primary; l3_egress_primary.port = p_gport_primary; l3_egress_primary.vlan = p_vid_primary; /* VLAN field not used, but API requires it to be a valid VLAN */ sal_memcpy(l3_egress_primary.mac_addr, remote_mac_primary, 6); BCM_IF_ERROR_RETURN(bcm_l3_egress_create(unit, 0, &l3_egress_primary, &l3_egr_obj_primary)); /* * Create VPWS VPN */ bcm_mpls_vpn_config_t_init(&vpn_info); vpn_info.flags = BCM_MPLS_VPN_VPWS; BCM_IF_ERROR_RETURN(bcm_mpls_vpn_id_create(unit, &vpn_info)); printf("vpn_id=%d\n", vpn_info.vpn); /* * Add customer facing port to VPN */ bcm_mpls_port_t_init(&cust_mpls_port); cust_mpls_port.port = c_gport; cust_mpls_port.criteria = BCM_MPLS_PORT_MATCH_PORT_VLAN; cust_mpls_port.match_vlan = c_vid; BCM_IF_ERROR_RETURN(bcm_mpls_port_add(unit, vpn_info.vpn, &cust_mpls_port)); printf("MPLS port 1 = 0x%x\n", cust_mpls_port.mpls_port_id); /* * Add failover provider port (_backup) to VPN */ bcm_mpls_port_t_init(&service_mpls_port_backup); service_mpls_port_backup.flags = BCM_MPLS_PORT_EGRESS_TUNNEL | BCM_MPLS_PORT_NETWORK | BCM_MPLS_PORT_COUNTED; service_mpls_port_backup.port = p_gport_backup; service_mpls_port_backup.criteria = BCM_MPLS_PORT_MATCH_LABEL; service_mpls_port_backup.match_label = vc_label_term_backup; service_mpls_port_backup.egress_tunnel_if = l3_egr_obj_backup; service_mpls_port_backup.egress_label.flags |= BCM_MPLS_EGRESS_LABEL_TTL_SET; service_mpls_port_backup.egress_label.label = vc_label_init_backup; service_mpls_port_backup.egress_label.ttl = ttl; BCM_IF_ERROR_RETURN(bcm_mpls_port_add (unit, vpn_info.vpn, &service_mpls_port_backup)); printf("MPLS port 2 = 0x%x\n", service_mpls_port_backup.mpls_port_id); /* * Add primary service provider facing MPLS port (_primary) to VPN */ bcm_mpls_port_t_init(&service_mpls_port_primary); service_mpls_port_primary.flags = BCM_MPLS_PORT_EGRESS_TUNNEL | BCM_MPLS_PORT_NETWORK | BCM_MPLS_PORT_COUNTED; service_mpls_port_primary.port = p_gport_primary; service_mpls_port_primary.criteria = BCM_MPLS_PORT_MATCH_LABEL; service_mpls_port_primary.match_label = vc_label_term_backup; service_mpls_port_primary.egress_tunnel_if = l3_egr_obj_primary; /* Failover group and port ID */ service_mpls_port_primary.failover_id = failoverId; service_mpls_port_primary.failover_port_id = service_mpls_port_backup.mpls_port_id; service_mpls_port_primary.egress_label.flags |= BCM_MPLS_EGRESS_LABEL_TTL_SET; service_mpls_port_primary.egress_label.label = vc_label_init_primary; service_mpls_port_primary.egress_label.ttl = ttl; BCM_IF_ERROR_RETURN(bcm_mpls_port_add (unit, vpn_info.vpn, &service_mpls_port_primary)); printf("MPLS port 3 = 0x%x\n", service_mpls_port_primary.mpls_port_id); /* ======================================================================= */ /* Before setting failover, PW is using tunnel _primary */ return BCM_E_NONE; } /* * execute: * This function does the following * a) test setup * b) actual configuration (Done in config_vpws_frr()) * c) demonstrates the functionality(done in verify()). */ bcm_error_t execute(void) { bcm_error_t rv; int unit = 0; print "config show; attach; cancun stat; version"; bshell(unit, "config show; a ; cancun stat; version"); print "~~~ #1) test_setup(): ** start **"; if (BCM_FAILURE((rv = test_setup(unit)))) { printf("test_setup() failed.\n"); return -1; } print "~~~ #1) test_setup(): ** end **"; print "~~~ #2) config_vpws_frr(): ** start **"; if (BCM_FAILURE((rv = config_vpws_frr(unit)))) { printf("config_vpws_frr() failed.\n"); return -1; } print "~~~ #2) config_vpws_frr(): ** end **"; print "~~~ #3) verify(): ** start **"; verify(unit); print "~~~ #3) verify(): ** end **"; return BCM_E_NONE; } const char *auto_execute = (ARGC == 1) ? ARGV[0] : "YES"; if (!sal_strcmp(auto_execute, "YES")) { print "execute(): Start"; print execute(); print "execute(): End"; }
37.533333
210
0.673956
[ "object" ]
f92d853394cc3273ce9fdd2c0486f5693e62feab
4,046
h
C
JustinGXEngine/Object.h
jdsilv17/Custom-Engine
823f021aa2efceb80aa426f3f3eae9da2769ccef
[ "MIT" ]
null
null
null
JustinGXEngine/Object.h
jdsilv17/Custom-Engine
823f021aa2efceb80aa426f3f3eae9da2769ccef
[ "MIT" ]
null
null
null
JustinGXEngine/Object.h
jdsilv17/Custom-Engine
823f021aa2efceb80aa426f3f3eae9da2769ccef
[ "MIT" ]
null
null
null
#pragma once #include <DirectXMath.h> class Object { public: Object(); Object(const DirectX::XMMATRIX& _world); Object(const DirectX::XMFLOAT4X4& _world); Object(const Object& that); Object& operator=(const Object& that); const DirectX::XMMATRIX& GetWorldMatrix() const; const DirectX::XMFLOAT4X4& GetWorldFloat4X4() const; // Transform const DirectX::XMMATRIX& GetTransformMatrix() const; const DirectX::XMFLOAT4X4& GetTransformFloat4X4() const; // Postion const DirectX::XMVECTOR& GetPositionVector() const; const DirectX::XMFLOAT4& GetPositionFloat4() const; // Rotation const DirectX::XMVECTOR& GetRotationVector() const; const DirectX::XMFLOAT3& GetRotationFloat4() const; // Scale const DirectX::XMVECTOR& GetScaleVector() const; const DirectX::XMFLOAT3& GetScaleFloat4() const; // Directions const DirectX::XMVECTOR& GetForwardVector() const; const DirectX::XMFLOAT3& GetForwardFloat3() const; const DirectX::XMVECTOR& GetBackwardVector() const; const DirectX::XMFLOAT3& GetBackwardFloat3() const; const DirectX::XMVECTOR& GetUpVector() const; const DirectX::XMFLOAT3& GetUpFloat3() const; const DirectX::XMVECTOR& GetLeftVector() const; const DirectX::XMFLOAT3& GetLeftFloat3() const; const DirectX::XMVECTOR& GetRightVector() const; const DirectX::XMFLOAT3& GetRightFloat3() const; void SetWorld(const DirectX::XMMATRIX& mat); void SetWorld(DirectX::XMFLOAT4X4 mat); void SetLookAt(const DirectX::XMVECTOR& position, const DirectX::XMVECTOR& target, const DirectX::XMVECTOR& up); void SetLookAt(const DirectX::XMVECTOR& zAxis, const DirectX::XMVECTOR& up); void SetTurnTo(const DirectX::XMMATRIX& mat, const DirectX::XMVECTOR& target, const float& deltaTime); //void SetTurnTo(DirectX::XMFLOAT4X4 mat); // Transform void SetTransform(const DirectX::XMMATRIX& mat); void SetTransform(DirectX::XMFLOAT4X4 mat); // Postion void SetPosition(const DirectX::XMVECTOR& pos); void SetPosition(float x, float y, float z); // Rotation void SetRotation(const DirectX::XMVECTOR& rot); void SetRotation(float x, float y, float z); // Scale void SetScale(const DirectX::XMVECTOR& scale); void SetScale(float x, float y, float z); void SetForwardVector(const DirectX::XMVECTOR& forward); void SetBackwardVector(const DirectX::XMVECTOR& backward); void SetUpVector(const DirectX::XMVECTOR& up); void SetLeftVector(const DirectX::XMVECTOR& left); void SetRightVector(const DirectX::XMVECTOR& right); // Postion void UpdatePosition(const DirectX::XMVECTOR& pos); void UpdatePosition(float x, float y, float z); // Rotation void UpdateRotation(const DirectX::XMVECTOR& rot); void UpdateRotation(float x, float y, float z); // Scale void UpdateScale(const DirectX::XMVECTOR& scale); void UpdateScale(float x, float y, float z); const DirectX::XMVECTOR FORWARD = DirectX::XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f); const DirectX::XMVECTOR BACKWARD = DirectX::XMVectorSet(0.0f, 0.0f, -1.0f, 0.0f); const DirectX::XMVECTOR UP = DirectX::XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f); const DirectX::XMVECTOR LEFT = DirectX::XMVectorSet(-1.0f, 0.0f, 0.0f, 0.0f); const DirectX::XMVECTOR RIGHT = DirectX::XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f); private: DirectX::XMMATRIX World_M; DirectX::XMFLOAT4X4 World_F; DirectX::XMMATRIX LookAt_M; DirectX::XMFLOAT4X4 LookAt_F; DirectX::XMMATRIX TurnTo_M; DirectX::XMFLOAT4X4 turnTo_F; DirectX::XMMATRIX Transform_M; DirectX::XMFLOAT4X4 Transform_F; DirectX::XMVECTOR Pos_V; DirectX::XMFLOAT4 Pos_F4; DirectX::XMVECTOR Rot_V; DirectX::XMFLOAT3 Rot_F3; DirectX::XMVECTOR Scale_V; DirectX::XMFLOAT3 Scale_F3; DirectX::XMVECTOR foward_V; DirectX::XMFLOAT3 foward_F3; DirectX::XMVECTOR backward_V; DirectX::XMFLOAT3 backward_F3; DirectX::XMVECTOR up_V; DirectX::XMFLOAT3 up_F3; DirectX::XMVECTOR left_V; DirectX::XMFLOAT3 left_F3; DirectX::XMVECTOR right_V; DirectX::XMFLOAT3 right_F3; bool PositionChanged = false; bool RotationChanged = false; bool ScaleChanged = false; void UpdateWorldMatrix(); void UpdateTransform(); };
32.894309
113
0.757291
[ "object", "transform" ]
f93cd07f418e324507085dad2d5cd54219891121
28,984
c
C
archive/MimeTeX/gfuntype.c
sytelus/Eq2Img
d2ab44893dc05fbda7f79995c6eec466914e3487
[ "Net-SNMP", "Xnet", "X11" ]
1
2019-04-12T12:30:22.000Z
2019-04-12T12:30:22.000Z
archive/MimeTeX/gfuntype.c
sytelus/Eq2Img
d2ab44893dc05fbda7f79995c6eec466914e3487
[ "Net-SNMP", "Xnet", "X11" ]
null
null
null
archive/MimeTeX/gfuntype.c
sytelus/Eq2Img
d2ab44893dc05fbda7f79995c6eec466914e3487
[ "Net-SNMP", "Xnet", "X11" ]
null
null
null
/**************************************************************************** * * Copyright (c) 2002, John Forkosh Associates, Inc. All rights reserved. * -------------------------------------------------------------------------- * This file is part of mimeTeX, which is free software. You may redistribute * and/or modify it under the terms of the GNU General Public License, * version 2 or later, as published by the Free Software Foundation. * MimeTeX is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY, not even the implied warranty of MERCHANTABILITY. * See the GNU General Public License for specific details. * By using mimeTeX, you warrant that you have read, understood and * agreed to these terms and conditions, and that you are at least 18 years * of age and possess the legal right and ability to enter into this * agreement and to use mimeTeX in accordance with it. * Your mimeTeX distribution should contain a copy of the GNU General * Public License. If not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * -------------------------------------------------------------------------- * * Program: gfuntype [-n fontname] [-m msglevel] [infile [outfile]] * * Purpose: Parses output from gftype -i * and writes pixel bitmap data of the characters * in a format suitable for a C header file, etc. * * -------------------------------------------------------------------------- * * Command-line Arguments: * --- args can be in any order --- * infile name of input file * (defaults to stdin if no filenames given) * outfile name of output file * (defaults to stdout if <2 filenames given) * -m msglevel verbose if msglevel>=9 (vv if >=99) * -n fontname string used for fontname * (defaults to noname) * * Exits: 0=success, 1=some error * * Notes: o To compile * cc gfuntype.c mimetex.c -lm -o gfuntype * needs mimetex.c and mimetex.h * * Source: gfuntype.c * * -------------------------------------------------------------------------- * Revision History: * 09/22/02 J.Forkosh Installation. * ****************************************************************************/ /* -------------------------------------------------------------------------- standard headers, program parameters, global data and macros -------------------------------------------------------------------------- */ /* --- standard headers --- */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> /* --- application headers --- */ /* #define SIGNEDCHAR */ #include "mimetex.h" /* --- parameters either -D defined on cc line, or defaulted here --- */ #ifndef MSGLEVEL #define MSGLEVEL 0 #endif /* --- message level (verbose test) --- */ static int msglevel = MSGLEVEL; /* verbose if msglevel >= 9 */ static FILE *msgfp; /* verbose output goes here */ /* --- miscellaneous other data --- */ #define CORNER_STUB ".<--" /* start of upper,lower-left line */ #define TYPECAST "(pixbyte *)" /* typecast for pixmap string */ /* ========================================================================== * Function: main() for gfuntype.c * Purpose: interprets command-line args, etc * -------------------------------------------------------------------------- * Command-Line Arguments: * See above * -------------------------------------------------------------------------- * Returns: 0=success, 1=some error * -------------------------------------------------------------------------- * Notes: o * ======================================================================= */ /* --- entry point --- */ int main ( int argc, char *argv[] ) { /* -------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ int argnum = 0; /* argv[] index for command-line args */ int inarg=0, outarg=0; /* argv[] indexes for infile, outfile */ int iserror = 1; /* error signal */ int charnum, /* character number (nextchar->charnum) */ nchars = 0; /* #chars in font */ char fontname[99] = "noname", /* font name */ *getcharname(); /* get character name from its number */ FILE /* *fopen(),*/ *infp=stdin, *outfp=stdout; /* init file pointers */ chardef *getnextchar(), *nextchar, /* read and parse next char in infp */ *fontdef[256]; /* chars stored using charnum as index */ int cstruct_chardef(); /* emit C struct for a character map */ int type_raster(); /* display debugging output */ char *copyright = /* copyright, gnu/gpl notice */ "+-----------------------------------------------------------------------+\n" "|gfuntype ver 1.00, Copyright(c) 2002-2003, John Forkosh Associates, Inc|\n" "+-----------------------------------------------------------------------+\n" "| gfuntype is free software licensed to you under terms of the GNU/GPL, |\n" "| and comes with absolutely no warranty whatsoever. |\n" "+-----------------------------------------------------------------------+"; /* -------------------------------------------------------------------------- interpret command-line arguments -------------------------------------------------------------------------- */ while ( argc > ++argnum ) /* check for flags and filenames */ if ( *argv[argnum] == '-' ) /* got some '-' flag */ { char flag = tolower(*(argv[argnum]+1)); /* char following '-' */ argnum++; /* arg following flag is usually its value */ switch ( flag ) /* see what user wants to tell us */ { /* --- no usage for clueless users yet --- */ default: exit(iserror); /* exit quietly for unrecognized input */ /* --- adjustable program parameters (not checking input) --- */ case 'm': msglevel = atoi(argv[argnum]); break; case 'n': strcpy(fontname,argv[argnum]); break; } /* --- end-of-switch() --- */ } /* --- end-of-if(*argv[]=='-') --- */ else /* this arg not a -flag, so it must be... */ if ( inarg == 0 ) /* no infile arg yet */ inarg = argnum; /* so use this one */ else /* we already have an infile arg */ if ( outarg == 0 ) /* but no outfile arg yet */ outarg = argnum; /* so use this one */ /* --- set verbose file ptr --- */ msgfp = (outarg>0? stdout : stderr); /* use stdout or stderr */ /* --- emit copyright, gnu/gpl notice --- */ fprintf(msgfp,"%s\n",copyright); /* display copyright, gnu/gpl info */ /* --- display input args if verbose output --- */ if ( msglevel >= 9 ) /* verbose output requested */ fprintf(msgfp,"gfuntype> infile=%s, outfile=%s, fontname=%s\n", (inarg>0?argv[inarg]:"stdin"), (outarg>0?argv[outarg]:"stdout"), fontname); /* -------------------------------------------------------------------------- initialization -------------------------------------------------------------------------- */ /* --- initialize font[] array --- */ for ( charnum=0; charnum<256; charnum++ ) /*for each possible char in font*/ fontdef[charnum] = (chardef *)NULL; /* char doesn't exist yet */ /* --- open input file (if necessary) --- */ if ( inarg > 0 ) /* input from file, not from stdin */ if ( (infp = fopen(argv[inarg],"r")) == NULL ) /*try to open input file*/ { fprintf(msgfp,"gfuntype> can't open %s for read\n",argv[inarg]); goto end_of_job; } /* report error and quit */ /* -------------------------------------------------------------------------- process input file -------------------------------------------------------------------------- */ while ( (nextchar=getnextchar(infp)) != NULL ) /* get each char in file */ { /* --- display character info --- */ if ( msglevel >= 9 ) /* verbose output requested */ fprintf(msgfp,"gfuntype> Char#%3d, loc %4d: ul=(%d,%d) ll=(%d,%d)\n", nextchar->charnum, nextchar->location, nextchar->topleftcol,nextchar->toprow, nextchar->botleftcol,nextchar->botrow); if ( msglevel >= 19 ) /* if a bit more verbose */ type_raster(&(nextchar->image),msgfp); /*display ascii image of raster*/ /* --- store character in font */ charnum = nextchar->charnum; /* get char number of char in font */ if ( charnum>=0 && charnum<=255 ) /* check for valid range */ fontdef[charnum] = nextchar; /* store char in font */ } /* --- end-of-while(charnum>0) --- */ /* -------------------------------------------------------------------------- generate output file -------------------------------------------------------------------------- */ /* --- open output file (if necessary) --- */ if ( outarg > 0 ) /* output to a file, not to stdout */ if ( (outfp = fopen(argv[outarg],"w")) == NULL ) /*try to open output file*/ { fprintf(msgfp,"gfuntype> can't open %s for write\n",argv[outarg]); goto end_of_job; } /* report error and quit */ /* --- header lines --- */ fprintf(outfp,"/%c --- fontdef for %s --- %c/\n", '*',fontname,'*'); fprintf(outfp,"static\tchardef %c%s[] =\n {\n", ' ',fontname); /* --- write characters comprising font --- */ for ( charnum=0; charnum<256; charnum++ ) /*for each possible char in font*/ if ( fontdef[charnum] != (chardef *)NULL ) /*check if char exists in font*/ { if ( ++nchars > 1 ) /* bump count */ fprintf(outfp,",\n"); /* and terminate preceding chardef */ fprintf(outfp," /%c --- pixel bitmap for %s char#%d %s --- %c/\n", '*',fontname,charnum,getcharname(fontname,charnum),'*'); cstruct_chardef(fontdef[charnum],outfp,6); } /*emit chardef as struct*/ else if(0)fprintf(outfp,"NULL"); /* no character in this position */ /* --- write trailer chardef and closing brace --- */ fprintf(outfp,",\n"); /* finish up last map from loop */ fprintf(outfp," /%c --- trailer --- %c/\n",'*','*'); /* trailer... */ fprintf(outfp," { -99, -999, 0,0,0,0, { 0,0,0, %s\"\\0\" } }\n", TYPECAST); fprintf(outfp," } ;\n"); /* terminating }; for fontdef */ /* -------------------------------------------------------------------------- end-of-job -------------------------------------------------------------------------- */ /* --- reset error status for okay exit --- */ iserror = 0; /* --- close files (if they're open and not stdin/out) --- */ end_of_job: if ( infp!=NULL && infp!=stdin ) fclose( infp); if ( outfp!=NULL && outfp!=stdout ) fclose(outfp); exit ( iserror ); } /* --- end-of-function main() --- */ /* ========================================================================== * Function: getnextchar ( fp ) * Purpose: Reads and parses the next character definition on fp, * and returns a new chardef struct describing that character. * -------------------------------------------------------------------------- * Arguments: fp (I) FILE * to input file * (containing output from gftype -i) * Returns: ( chardef * ) ptr to chardef struct describing character, * or NULL for eof or any error * -------------------------------------------------------------------------- * Notes: o fp is left so the next line read from it will be * the one following the final .<-- line. * ======================================================================= */ /* --- entry point --- */ chardef *getnextchar ( FILE *fp ) { /* -------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ chardef *new_chardef(), *nextchar=(chardef *)NULL; /*ptr returned to caller*/ int delete_chardef(); /* free allocated memory if error */ int findnextchar(), charnum,location; /* get header line for next char */ int rasterizechar(); /* ascii image --> raster pixmap */ int parsecorner(); /* get col,row from ".<--" line */ char *readaline(); /* read next line from fp */ /* -------------------------------------------------------------------------- initialization -------------------------------------------------------------------------- */ /* --- find and interpret header line for next character --- */ charnum = findnextchar(fp,&location); /* read and parse header line */ if ( charnum < 0 ) goto error; /* eof or error, no more chars */ /* --- allocate a new chardef struct and begin populating it --- */ if ( (nextchar=new_chardef()) /* allocate a new chardef */ == (chardef *)NULL ) goto error; /* and quit if we failed */ nextchar->charnum = charnum; /* store charnum in struct */ nextchar->location = location; /* and location */ /* --- get upper-left corner line --- */ if ( !parsecorner(readaline(fp), /* parse corner line */ &(nextchar->toprow),&(nextchar->topleftcol)) ) /* row and col from line */ goto error; /* and quit if failed */ /* -------------------------------------------------------------------------- interpret character image (and parse terminating corner line) -------------------------------------------------------------------------- */ /* --- read ascii character image and interpret as integer bitmap --- */ if ( rasterizechar(fp,&nextchar->image) != 1 ) /* parse image of char */ goto error; /* and quit if failed */ /* --- get lower-left corner line --- */ if ( !parsecorner(readaline(NULL), /* reread and parse corner line */ &(nextchar->botrow),&(nextchar->botleftcol)) ) /* row and col from line */ goto error; /* and quit if failed */ /* -------------------------------------------------------------------------- done -------------------------------------------------------------------------- */ goto end_of_job; /* skip error return if successful */ error: if ( nextchar != (chardef *)NULL ) /* have an allocated chardef */ delete_chardef(nextchar); /* so deallocate it */ nextchar = (chardef *)NULL; /* and reset ptr to null for error */ end_of_job: return ( nextchar ); /* back with chardef or null */ } /* --- end-of-function getnextchar() --- */ /* ========================================================================== * Function: getcharname ( fontname, charnum ) * Purpose: Looks up charnum for the family specified by fontname * and returns the corresponding charname. * -------------------------------------------------------------------------- * Arguments: fontname (I) char * containing fontname for font family * charnum (I) int containing the character number * whose corresponding name is wanted. * Returns: ( char * ) ptr to character name * or NULL if charnum not found in table * -------------------------------------------------------------------------- * Notes: o * ======================================================================= */ /* --- entry point --- */ char *getcharname ( char *fontname, int charnum ) { /* -------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ /* --- recognized font family names and our corresponding numbers --- */ static char *fnames[] = { "cmr","cmmi","cmsy","cmex",NULL }; static int fnums[] = { CMR10,CMMI10,CMSY10,CMEX10, -1 }; static char *noname = "(noname)"; /* char name returned if lookup fails */ /* --- other local declarations --- */ char *charname = noname; /* character name returned to caller */ char flower[99] = "noname"; /* lowercase caller's fontname */ int ifamily = 0, /* fnames[] (and fnums[]) index */ ichar = 0; /* -------------------------------------------------------------------------- lowercase caller's fontname and look it up in fnames[] -------------------------------------------------------------------------- */ /* --- lowercase caller's fontname --- */ for ( ichar=0; *fontname!='\000'; ichar++,fontname++ )/*lowercase each char*/ flower[ichar] = (isalpha(*fontname)? tolower(*fontname) : *fontname); flower[ichar] = '\000'; /* null-terminate lowercase fontname */ if ( strlen(flower) < 2 ) goto end_of_job; /* no lookup match possible */ /* --- look up lowercase fontname in our fnames[] table --- */ for ( ifamily=0; ;ifamily++ ) /* check fnames[] for flower */ if ( fnames[ifamily] == NULL ) goto end_of_job; /* quit at end-of-table */ else if ( strstr(flower,fnames[ifamily]) != NULL ) break; /* found it */ ifamily = fnums[ifamily]; /* xlate index to font family number */ /* -------------------------------------------------------------------------- now look up name for caller's charnum in ifamily, and return it to caller -------------------------------------------------------------------------- */ /* --- search symtable[] for charnum in ifamily --- */ for ( ichar=0; ;ichar++ ) /*search symtable[] for charnum in ifamily*/ if ( symtable[ichar].symbol == NULL ) goto end_of_job; /* end-of-table */ else if ( symtable[ichar].family == ifamily /* found desired family */ && symtable[ichar].handler == NULL ) /* and char isn't a "dummy" */ if ( symtable[ichar].charnum == charnum ) break; /* found charnum */ /* --- return corresponding charname to caller --- */ charname = symtable[ichar].symbol; /* pointer to symbol name in table */ end_of_job: return ( charname ); } /* --- end-of-function getcharname() --- */ /* ========================================================================== * Function: findnextchar ( fp, location ) * Purpose: Finds next "beginning of char" line in fp * and returns the character number, * and (optionally) location if arg provided. * -------------------------------------------------------------------------- * Arguments: fp (I) FILE * to input file * (containing output from gftype -i) * location (O) int * returning "location" of character * (or pass NULL and it won't be returned) * Returns: ( int ) character number, * or -1 for eof or any error * -------------------------------------------------------------------------- * Notes: o fp is left so the next line read from it will be * the one following the "beginning of char" line * ======================================================================= */ /* --- entry point --- */ int findnextchar ( FILE *fp, int *location ) { /* -------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ static char keyword[99]="beginning of char "; /*signals start of next char*/ char *readaline(), *line; /* read next line from fp */ char *strstr(), *strchr(), *delim; /* search line for substring, char */ char token[99]; /* token extracted from line */ int charnum = (-1); /* character number returned to caller */ /* -------------------------------------------------------------------------- keep reading lines until eof or keyword found -------------------------------------------------------------------------- */ while ( (line=readaline(fp)) != NULL ) /* read lines until eof */ { if ( msglevel >= 999 ) /* very, very verbose output requested */ fprintf(msgfp,"nextchar> line = %s\n",line); if ( (delim=strstr(line,keyword)) != NULL ) /* found keyword on line */ { /* --- get character number from line --- */ strcpy(token,delim+strlen(keyword)); /* char num follows keyword */ charnum = atoi(token); /* interpret token as integer charnum */ /* --- get location at beginning of line --- */ if ( location != (int *)NULL ) /* caller wants location returned */ if ( (delim=strchr(line,':')) != NULL ) /* location precedes colon */ { *delim = '\000'; /* terminate line after location */ *location = atoi(line); } /* interpret location as integer */ break; /* back to caller with charnum */ } /* --- end-of-if(delim!=NULL) --- */ } /* --- end-of-while(line!=NULL) --- */ return ( charnum ); /* back to caller with char number or -1 */ } /* --- end-of-function findnextchar() --- */ /* ========================================================================== * Function: rasterizechar ( fp, rp ) * Purpose: Reads and parses subsequent lines from fp * (until a terminating ".<--" line), * representing the ascii image of the character in fp, * and returns the results in raster struct rp * -------------------------------------------------------------------------- * Arguments: fp (I) FILE * to input file * (containing output from gftype -i) * positioned immediately after top .<-- line, * ready to read first line of ascii image * rp (O) raster * returning the rasterized * character represented on fp as an ascii image * Returns: ( int ) 1=okay, or 0=eof or any error * -------------------------------------------------------------------------- * Notes: o fp is left so the last line (already) read from it * contains the terminating .<-- corner information * (readaline(NULL) will reread this last line) * o char images on fp can be no wider than 31 pixels * ======================================================================= */ /* --- entry point --- */ int rasterizechar ( FILE *fp, raster *image ) { /* -------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ char *readaline(), *line; /* read next scan line for char from fp */ unsigned char bitvec[512][64]; /* scan lines parsed (up to 512x512 bits) */ int height = 0, /* #scan lines in fp comprising char */ width = 0, /* #chars on longest scan line */ pixsz = 1; /* default #bits per pixel, 1=bitmap */ int iscan, ipixel=0, /* bitvec[] index, raster pixel map index */ ibit; /* bit along scan (i.e., 0...width-1) */ int isokay = 0; /* returned status, init for failure */ /* -------------------------------------------------------------------------- read lines till ".<--" terminator, and construct one vector[] int per line -------------------------------------------------------------------------- */ while ( (line=readaline(fp)) != NULL ) /* read lines until eof */ { /* --- allocations and declarations --- */ int icol, ncols=strlen(line); /* line[] column index, #cols in line[] */ /* --- check for end-of-char (when we encounter corner line) --- */ if ( memcmp(line,CORNER_STUB,strlen(CORNER_STUB)) == 0 ) /* corner line */ break; /* so done with loop */ /* --- parse line (encode asterisks comprising character image) --- */ memset(bitvec[height],0,64); /* first zero out all bits */ for ( icol=0; icol<ncols; icol++ ) /* now check line[] for asterisks */ if ( line[icol] == '*' ) /* we want to set this bit */ { setlongbit(bitvec[height],icol); /* set bit */ if ( icol >= width ) width=icol+1; } /* and check for new width */ height++; /* bump character height */ } /* --- end-of-while(line!=NULL) --- */ if ( height<1 || width<1 ) /* some problem parsing character */ goto end_of_job; /* so quit */ /* -------------------------------------------------------------------------- allocate image raster pixmap for character -------------------------------------------------------------------------- */ if ( image->pixmap != NULL ) /* hmm, somebody already allocated memory */ free((void *)image->pixmap); /* just free it */ image->width = width; /* set image width within raster struct */ image->height = height; /* and height */ image->pixsz = pixsz; /* #bits per pixel, 1=bitmap or 8=bytemap */ if ( (image->pixmap = (unsigned char *)malloc(pixmapsz(image))) == NULL ) goto end_of_job; /* quit if failed to allocate pixmap */ /* -------------------------------------------------------------------------- copy each integer in bitvec[] to raster pixmap, bit by bit -------------------------------------------------------------------------- */ for ( iscan=0; iscan<height; iscan++ ) /* for each integer in vector[] */ for ( ibit=0; ibit<width; ibit++ ) /* for all bits in this scan */ { if ( getlongbit(bitvec[iscan],ibit) != 0 ) /* check current scan pixel */ { setlongbit(image->pixmap,ipixel); } else /*turn off corresponding raster bit*/ { unsetlongbit(image->pixmap,ipixel); } ipixel++; /* bump image raster pixel */ } /* --- end-of-for(iscan,ibit) --- */ /* -------------------------------------------------------------------------- done -------------------------------------------------------------------------- */ isokay = 1; /* reset flag for success */ end_of_job: return ( isokay ); /* back with 1=success, 0=failure */ } /* --- end-of-function rasterizechar() --- */ /* ========================================================================== * Function: parsecorner ( line, row, col ) * Purpose: Parses a "pixel corner" line (upper left or lower left) * and returns the (col,row) information on it as integers. * -------------------------------------------------------------------------- * Arguments: line (I) char * to input line containing * ".<--This pixel's..." to be parsed * row (O) int * returning the (,row) * col (O) int * returning the (col,) * Returns: ( int ) 1 if successful, or 0 for any error * -------------------------------------------------------------------------- * Notes: o * ======================================================================= */ /* --- entry point --- */ int parsecorner ( char *line, int *row, int *col ) { /* -------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ int isokay = 0; /* success/fail flag, init for failure */ char field[99], *delim; /*(col,row) field and ptr to various delims*/ /* -------------------------------------------------------------------------- extract (col,row) field from line, and interpret col and row as integers -------------------------------------------------------------------------- */ /* --- first, check beginning of line --- */ if ( line == (char *)NULL ) goto end_of_job; /* no line supplied by caller */ if ( memcmp(line,CORNER_STUB,strlen(CORNER_STUB)) != 0 ) /*not valid corner*/ goto end_of_job; /* so quit */ /* --- extract col,row field from line --- */ if ( (delim=strchr(line,'(')) == NULL ) goto end_of_job; /*find open paren*/ strncpy(field,delim+1,10); /* extract next 10 chars */ field[10] = '\000'; /* and null-terminate field */ if ( (delim=strchr(field,')')) == NULL ) goto end_of_job; /*find close paren*/ *delim = '\000'; /* terminate field at close paren */ /* --- interpret col,row as integers --- */ if ( (delim=strchr(field,',')) == NULL ) goto end_of_job; /* find comma */ *delim = '\000'; /* break field into col and row */ if ( col != (int *)NULL ) /* caller gave us ptr for col */ *col = atoi(field); /* so return it to him */ if ( row != (int *)NULL ) /* caller gave us ptr for row */ *row = atoi(delim+1); /* so return it to him */ /* -------------------------------------------------------------------------- done -------------------------------------------------------------------------- */ isokay = 1; /* reset flag for success */ end_of_job: return ( isokay ); /* back with success/fail flag */ } /* --- end-of-function parsecorner() --- */ /* ========================================================================== * Function: readaline ( fp ) * Purpose: Reads a line from fp, strips terminating newline, * and returns ptr to internal buffer * -------------------------------------------------------------------------- * Arguments: fp (I) FILE * to input file to be read. * If null, returns line previously read. * Returns: ( char * ) internal buffer containing line read, * or NULL for eof or error. * -------------------------------------------------------------------------- * Notes: o fp is left on the line following the returned line * ======================================================================= */ /* --- entry point --- */ char *readaline ( FILE *fp ) { /* -------------------------------------------------------------------------- Allocations and Declarations -------------------------------------------------------------------------- */ static char buffer[1024]; /* static buffer if caller supplies none */ char *fgets(), *bufptr=buffer; /* read line from fp */ char *strchr(), *delim; /* remove terminating newline */ /* -------------------------------------------------------------------------- Read line and strip trailing newline -------------------------------------------------------------------------- */ if ( fp != NULL ) /*if null, return previous line read*/ if ( (bufptr=fgets(buffer,1023,fp)) /* read next line from fp */ != NULL ) /* and check that we succeeded */ { if ( (delim=strchr(bufptr,'\n')) /* look for terminating newline */ != NULL ) /* and check that we found it */ *delim = '\000'; /* truncate line at newline */ } /* --- end-of-if(fgets()!=NULL) --- */ return ( bufptr ); /*back to caller with buffer or null*/ } /* --- end-of-function readaline() --- */ /* --- end-of-file gfuntype.c --- */
52.412297
78
0.484474
[ "vector", "3d" ]
f94ecfef7dfad8b4ebd1c5ce05e50ead2585b078
4,678
h
C
lib/src/includes/signed_video_common.h
AxisCommunications/signed-video-framework
39ce18aad51b0c05e7f8ef806d497673dc0aec7c
[ "MIT" ]
13
2021-12-10T13:30:10.000Z
2022-03-13T14:26:14.000Z
lib/src/includes/signed_video_common.h
AxisCommunications/signed-video-framework
39ce18aad51b0c05e7f8ef806d497673dc0aec7c
[ "MIT" ]
7
2021-12-10T15:36:51.000Z
2022-02-09T10:17:04.000Z
lib/src/includes/signed_video_common.h
AxisCommunications/signed-video-framework
39ce18aad51b0c05e7f8ef806d497673dc0aec7c
[ "MIT" ]
null
null
null
/** * MIT License * * Copyright (c) 2021 Axis Communications AB * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next paragraph) shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __SIGNED_VIDEO_COMMON_H__ #define __SIGNED_VIDEO_COMMON_H__ typedef struct _signed_video_t signed_video_t; /** * @brief Signed Video Return Code * * The error codes are categorized as * -(01-09): hardware issues like memory failure * -(10-19): user input errors like invalid parameters * -(20-29): internal or external signing errors * -(30-39): internal authentication errors * -100: unknown failure */ typedef enum { SV_OK = 0, // No error SV_MEMORY = -1, // Memory related failure SV_INVALID_PARAMETER = -10, // Invalid input parameter to function SV_NOT_SUPPORTED = -12, // The operation is not supported SV_INCOMPATIBLE_VERSION = -15, // Incompatible software version SV_EXTERNAL_ERROR = -20, // Failure in external code, e.g., plugin or OpenSSL SV_VENDOR_ERROR = -21, // Failure in vendor specific code SV_AUTHENTICATION_ERROR = -30, // Failure related to validating the authenticity SV_UNKNOWN_FAILURE = -100, // Unknown failure } SignedVideoReturnCode; /** * Signed Video Codec Type * * The following codecs are supported. The codec in use when creating the signed video session. */ typedef enum { SV_CODEC_H264 = 0, SV_CODEC_H265 = 1, SV_CODEC_NUM } SignedVideoCodec; /** * @brief Create a new signed video session. * * Creates a signed_video_t object which the user should keep across the entire streaming session. * The user is responsible to free the memory at the end of the session by calling the * signed_video_free() function. The returned struct can be used for either signing a video, or * validating the authenticity of a video. * * @param codec The codec used in this session. * * @returns A pointer to signed_video_t struct, allocated and initialized. A null pointer is * returned if memory could not be allocated. */ signed_video_t* signed_video_create(SignedVideoCodec codec); /** * @brief Frees the memory of the signed_video_t object. * * All memory allocated to and by the signed_video_t object will be freed. This will affectivly end * the signed video session. * * @param self Pointer to the object which memory to free. */ void signed_video_free(signed_video_t* self); /** * @brief Resets the session to allow for, e.g., scrubbing signed video * * Resets the session and puts it in a pre-stream state, that is, waiting for a new GOP. Once a new * GOP is found the operations start over. * * For the signing part, this means starting to produce the required SEI-NALUs needed for * authentication. For the authentication part, this should be used when scrubbing the video. * Otherwise the lib will fail authentication due to skipped NALUs. * * @param self Signed Video session in use * * @returns A Signed Video Return Code (SignedVideoReturnCode) */ SignedVideoReturnCode signed_video_reset(signed_video_t* self); /** * @brief Returns the current software version as a null-terminated string. * * @returns A string with the current software version */ const char* signed_video_get_version(); /** * @brief Compares two Signed Video versions * * @param version1 Version string to compare against |version2| * @param version2 Version string to compare against |version1| * * @returns 0 if |version1| is equal to |version2| * 1 if |version1| is newer than |version2| * 2 if |version1| is older than |version2| * -1 Failure */ int signed_video_compare_versions(const char* version1, const char* version2); #endif // __SIGNED_VIDEO_COMMON_H__
38.03252
100
0.744763
[ "object" ]
f9506c6c8037539a1372239b74f8f3d99321ffaa
2,626
h
C
include/ipfs_curl/ipfs.h
jmjatlanta/ipfs_curl
b934f59a12b0cb475b38c07e635f7ee27aecadde
[ "MIT" ]
2
2017-11-18T02:28:12.000Z
2018-10-29T17:53:56.000Z
include/ipfs_curl/ipfs.h
jmjatlanta/ipfs_curl
b934f59a12b0cb475b38c07e635f7ee27aecadde
[ "MIT" ]
null
null
null
include/ipfs_curl/ipfs.h
jmjatlanta/ipfs_curl
b934f59a12b0cb475b38c07e635f7ee27aecadde
[ "MIT" ]
null
null
null
/* * IPFS.h * * Created on: Oct 20, 2016 * Author: JohnJones */ #pragma once #include <string> #include <sstream> #include "curl_easy.h" #include "rapidjson/Document.h" namespace ipfs_curl { class IPFS { public: IPFS(); IPFS(std::string ip, int port, int apiPort) : gatewayIP(ip), gatewayPort(port), gatewayApiPort(apiPort) {} virtual ~IPFS(); public: std::ostringstream cat(std::string hash) { std::stringstream url; url << "http://" << gatewayIP << ":" << gatewayPort << "/ipfs/" << hash; return curl(url.str()); } std::string add(std::string content) { std::stringstream url; url << "http://" << gatewayIP << ":" << gatewayApiPort << "/api/v0/add?stream-channels=true"; rapidjson::Document json = curl_json(url.str(), content); return json["Hash"].GetString(); } std::string ls(std::string hash) { std::stringstream url; url << "http://" << gatewayIP << ":" << gatewayApiPort << "/api/v0/ls/" << hash; rapidjson::Document json = curl_json(url.str()); return json["Objects"][0]["Links"].GetString(); } std::string size(std::string hash) { std::stringstream url; url << "http://" << gatewayIP << ":" << gatewayApiPort << "/api/v0/object/stat/" << hash; rapidjson::Document json = curl_json(url.str()); return json["CumulativeSize"].GetString(); } std::string pinAdd(std::string hash) { std::stringstream url; url << "http://" << gatewayIP << ":" << gatewayApiPort << "/api/v0/pin/add" << hash; rapidjson::Document json = curl_json(url.str()); return json.GetString(); } std::string version() { std::stringstream url; url << "http://" << gatewayIP << ":" << gatewayApiPort << "/api/v0/version"; rapidjson::Document json = curl_json(url.str()); return json["Version"].GetString(); } private: std::string gatewayIP; int gatewayPort; int gatewayApiPort; private: rapidjson::Document curl_json(std::string url, std::string data = "") { std::string curlResult = curl(url, data).str(); rapidjson::Document json; json.Parse(curlResult.c_str()); return json; } std::ostringstream curl(std::string url, std::string data = "") { std::ostringstream output; curl::curl_ios<std::ostringstream> writer(output); curl::curl_easy easy(writer); easy.add<CURLOPT_URL>(url.c_str()); //easy.add<CURLOPT_RETURNTRANSFER>(1L); easy.add<CURLOPT_TIMEOUT>(5); easy.add<CURLOPT_HEADER>(0); //easy.add<CURLOPT_BINARYTRANSFER>(1); try { easy.perform(); } catch (curl::curl_easy_exception& error) { curl::curlcpp_traceback errors = error.get_traceback(); error.print_traceback(); } return output; } }; } /* namespace ipfs_curl */
29.177778
95
0.65575
[ "object" ]
f955110e78bcd152bec9a1fa962965964162a442
2,106
h
C
ZAPD/Declaration.h
Dragorn421/ZAPD
e02e151c91d006279c4cb75636fead5d1663c7d3
[ "MIT" ]
null
null
null
ZAPD/Declaration.h
Dragorn421/ZAPD
e02e151c91d006279c4cb75636fead5d1663c7d3
[ "MIT" ]
9
2020-12-29T00:20:37.000Z
2020-12-29T01:57:42.000Z
ZAPD/Declaration.h
Dragorn421/ZAPD
e02e151c91d006279c4cb75636fead5d1663c7d3
[ "MIT" ]
1
2021-01-02T03:19:49.000Z
2021-01-02T03:19:49.000Z
#pragma once #include <string> #include <vector> enum class DeclarationAlignment { None, Align4, Align8, Align16 }; enum class DeclarationPadding { None, Pad4, Pad8, Pad16 }; class Declaration { public: DeclarationAlignment alignment; DeclarationPadding padding; size_t size; std::string preText = ""; std::string text = ""; std::string rightText = ""; std::string postText = ""; std::string preComment = ""; std::string postComment = ""; std::string varType = ""; std::string varName = ""; std::string includePath = ""; bool isExternal = false; bool isArray = false; size_t arrayItemCnt = 0; std::string arrayItemCntStr = ""; std::vector<uint32_t> references; bool isUnaccounted = false; bool isPlaceholder = false; Declaration(DeclarationAlignment nAlignment, size_t nSize, std::string nVarType, std::string nVarName, bool nIsArray, std::string nText); Declaration(DeclarationAlignment nAlignment, DeclarationPadding nPadding, size_t nSize, std::string nVarType, std::string nVarName, bool nIsArray, std::string nText); Declaration(DeclarationAlignment nAlignment, size_t nSize, std::string nVarType, std::string nVarName, bool nIsArray, size_t nArrayItemCnt, std::string nText); Declaration(DeclarationAlignment nAlignment, size_t nSize, std::string nVarType, std::string nVarName, bool nIsArray, std::string nArrayItemCntStr, std::string nText); Declaration(DeclarationAlignment nAlignment, size_t nSize, std::string nVarType, std::string nVarName, bool nIsArray, size_t nArrayItemCnt, std::string nText, bool nIsExternal); Declaration(DeclarationAlignment nAlignment, DeclarationPadding nPadding, size_t nSize, std::string nVarType, std::string nVarName, bool nIsArray, size_t nArrayItemCnt, std::string nText); Declaration(std::string nIncludePath, size_t nSize, std::string nVarType, std::string nVarName); protected: Declaration(DeclarationAlignment nAlignment, DeclarationPadding nPadding, size_t nSize, std::string nText); };
32.4
97
0.722222
[ "vector" ]
f95b4f8d2257bde1a03c23195e318d0b4c2be7e4
2,308
h
C
idhook.h
gamehacked/Viking-Wpt
0f204f2700e0c37e58b7f2efee5ace0a3ac892b2
[ "MIT" ]
2
2019-07-08T07:22:58.000Z
2021-09-17T03:52:10.000Z
idhook.h
gamehacked/Viking-Wpt
0f204f2700e0c37e58b7f2efee5ace0a3ac892b2
[ "MIT" ]
null
null
null
idhook.h
gamehacked/Viking-Wpt
0f204f2700e0c37e58b7f2efee5ace0a3ac892b2
[ "MIT" ]
2
2018-03-11T15:17:11.000Z
2021-09-17T03:52:13.000Z
///// ///// CBOBY V2 [Revision by ETK] ///// ///// By [boy_scout][boyscout_etk@hotmail.com] ///// ///// [2011][www.etalking.com.ar] ///// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "players.h" class IdHook { public: int FirstKillPlayer[MAX_VPLAYERS]; int SameCheat[MAX_VPLAYERS]; void ClearPlayer(); void RelistPlayer(); void AddPlayer(int ax); struct Player; struct PlayerEntry{ PlayerEntry() :player(0){} char name[256]; char content[256]; Player* player; }; struct Player { Player():parent(0),selection(0),seekselection(0){} void boundSelection() { // wrap around if(selection<0) { selection = items.size()-1; seekselection = 2;} else if(selection >= (int)items.size()) { selection = 0; seekselection = 0;} if(selection==items.size()-1){seekselection = 2;} else if(selection==items.size()-2){seekselection = 1;} else {seekselection = 0;} } void boundSelection1() { // wrap around if(selection<0) { selection = 0; } else if(selection >= (int)items.size()-3) { if(seekselection == 0) selection = items.size()-3; else if(seekselection == 1) selection = items.size()-2; else if(seekselection == 2) selection = items.size()-1; } else { if(seekselection == 1) selection = items.size()-2; else if(seekselection == 2) selection = items.size()-1; } } Player* parent; string name; int selection; int seekselection; vector<PlayerEntry> items; }; IdHook():basePlayer(0){} void init(); struct Player* basePlayer; }; void func_relistplayer(); void func_clearallplayer(); void func_addplayer(); void player_describe_current(); void func_player_list(); void func_player_select(); void func_player_back(); void func_player_up(); void func_player_down(); void relistplayermenu(); bool gPlayerActive(); void drawPlayer(int x, int y, int w); void func_first_kill_mode(); extern bool player_active; extern char gHudMessage[256]; extern IdHook idhook;
24.553191
167
0.561958
[ "vector" ]
c3c1f2258256430e8280c1fd1d436d12bf9a780a
7,382
h
C
sources/ippcp/pcpsms4_l9cn.h
ntyukaev/ipp-crypto
19b408cfd21a59f994b64dd47b18eb0c2f94e4e0
[ "Apache-2.0" ]
30
2017-07-26T20:03:19.000Z
2021-10-14T23:38:54.000Z
sources/ippcp/pcpsms4_l9cn.h
ntyukaev/ipp-crypto
19b408cfd21a59f994b64dd47b18eb0c2f94e4e0
[ "Apache-2.0" ]
9
2018-09-25T18:32:42.000Z
2022-02-18T12:23:40.000Z
sources/ippcp/pcpsms4_l9cn.h
ntyukaev/ipp-crypto
19b408cfd21a59f994b64dd47b18eb0c2f94e4e0
[ "Apache-2.0" ]
14
2017-08-31T19:53:23.000Z
2021-02-27T01:08:14.000Z
/******************************************************************************* * Copyright 2019-2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* // // Purpose: // Cryptography Primitive. // SMS4 encryption/decryption // // Contents: // affine() // sBox() // L() // TRANSPOSE_INP() // TRANSPOSE_OUT() // */ #if (_IPP>=_IPP_H9) || (_IPP32E>=_IPP32E_L9) #ifndef __SMS4_SBOX_L9_H_ #define __SMS4_SBOX_L9_H_ #include "owndefs.h" #include "owncp.h" static __ALIGN32 Ipp8u inpMaskLO[] = {0x65,0x41,0xfd,0xd9,0x0a,0x2e,0x92,0xb6,0x0f,0x2b,0x97,0xb3,0x60,0x44,0xf8,0xdc, 0x65,0x41,0xfd,0xd9,0x0a,0x2e,0x92,0xb6,0x0f,0x2b,0x97,0xb3,0x60,0x44,0xf8,0xdc}; static __ALIGN32 Ipp8u inpMaskHI[] = {0x00,0xc9,0x67,0xae,0x80,0x49,0xe7,0x2e,0x4a,0x83,0x2d,0xe4,0xca,0x03,0xad,0x64, 0x00,0xc9,0x67,0xae,0x80,0x49,0xe7,0x2e,0x4a,0x83,0x2d,0xe4,0xca,0x03,0xad,0x64}; static __ALIGN32 Ipp8u outMaskLO[] = {0xd3,0x59,0x38,0xb2,0xcc,0x46,0x27,0xad,0x36,0xbc,0xdd,0x57,0x29,0xa3,0xc2,0x48, 0xd3,0x59,0x38,0xb2,0xcc,0x46,0x27,0xad,0x36,0xbc,0xdd,0x57,0x29,0xa3,0xc2,0x48}; static __ALIGN32 Ipp8u outMaskHI[] = {0x00,0x50,0x14,0x44,0x89,0xd9,0x9d,0xcd,0xde,0x8e,0xca,0x9a,0x57,0x07,0x43,0x13, 0x00,0x50,0x14,0x44,0x89,0xd9,0x9d,0xcd,0xde,0x8e,0xca,0x9a,0x57,0x07,0x43,0x13}; static __ALIGN32 Ipp8u maskSrows[] = {0x00,0x0d,0x0a,0x07,0x04,0x01,0x0e,0x0b,0x08,0x05,0x02,0x0f,0x0c,0x09,0x06,0x03, 0x00,0x0d,0x0a,0x07,0x04,0x01,0x0e,0x0b,0x08,0x05,0x02,0x0f,0x0c,0x09,0x06,0x03}; static __ALIGN16 Ipp8u encKey[] = {0x63,0x63,0x63,0x63,0x63,0x63,0x63,0x63,0x63,0x63,0x63,0x63,0x63,0x63,0x63,0x63}; static __ALIGN32 Ipp8u lowBits4[] = {0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f, 0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f}; static __ALIGN32 Ipp8u swapBytes[] = {3,2,1,0, 7,6,5,4, 11,10,9,8, 15,14,13,12, 3,2,1,0, 7,6,5,4, 11,10,9,8, 15,14,13,12}; static __ALIGN32 Ipp8u permMask[] = {0x00,0x00,0x00,0x00, 0x04,0x00,0x00,0x00, 0x01,0x00,0x00,0x00, 0x05,0x00,0x00,0x00, 0x02,0x00,0x00,0x00, 0x06,0x00,0x00,0x00, 0x03,0x00,0x00,0x00, 0x07,0x00,0x00,0x00}; static __ALIGN32 Ipp8u affineIn[] = { 0x52,0xBC,0x2D,0x02,0x9E,0x25,0xAC,0x34, 0x52,0xBC,0x2D,0x02,0x9E,0x25,0xAC,0x34, 0x52,0xBC,0x2D,0x02,0x9E,0x25,0xAC,0x34, 0x52,0xBC,0x2D,0x02,0x9E,0x25,0xAC,0x34 }; static __ALIGN32 Ipp8u affineOut[] = { 0x19,0x8b,0x6c,0x1e,0x51,0x8e,0x2d,0xd7, 0x19,0x8b,0x6c,0x1e,0x51,0x8e,0x2d,0xd7, 0x19,0x8b,0x6c,0x1e,0x51,0x8e,0x2d,0xd7, 0x19,0x8b,0x6c,0x1e,0x51,0x8e,0x2d,0xd7 }; #define M256(mem) (*((__m256i*)((Ipp8u*)(mem)))) #define M128(mem) (*((__m128i*)((Ipp8u*)(mem)))) /* // // AES and SMS4 ciphers both based on composite field GF(2^8). // This affine transformation transforms 16 bytes // from SMS4 representation to AES representation or vise versa // depending on passed masks. // */ __FORCEINLINE __m256i affine(__m256i x, __m256i maskLO, __m256i maskHI) { __m256i T1 = _mm256_and_si256(_mm256_srli_epi64(x, 4), M256(lowBits4)); __m256i T0 = _mm256_and_si256(x, M256(lowBits4)); T0 = _mm256_shuffle_epi8(maskLO, T0); T1 = _mm256_shuffle_epi8(maskHI, T1); return _mm256_xor_si256(T0, T1); } __FORCEINLINE __m256i AES_ENC_LAST(__m256i x, __m128i key) { __m128i t0 = _mm256_extracti128_si256(x, 0); __m128i t1 = _mm256_extracti128_si256(x, 1); t0 = _mm_aesenclast_si128(t0, key); t1 = _mm_aesenclast_si128(t1, key); x = _mm256_inserti128_si256(x, t0, 0); x = _mm256_inserti128_si256(x, t1, 1); return x; } /* // // GF(256) is isomorfic. // Encoding/decoding data of SM4 and AES are elements of GF(256). // The difference in representation only. // (It happend due to using different generating polynomials in SM4 and AES representations). // Doing data conversion from SM4 to AES domain // lets use AES specific intrinsics to perform less expensive SMS4 S-box computation. // // Original SMS4 S-box algorithm is converted to the following: // // - transform data from SMS4 representation to AES representation // - compute S-box value using _mm_aesenclast_si128 with special key // - re-shuffle data after _mm_aesenclast_si128 that shuffle it inside // - transform data back from AES representation to SMS4 representation // */ __FORCEINLINE __m256i sBox(__m256i block) { block = affine(block, M256(inpMaskLO), M256(inpMaskHI)); block = AES_ENC_LAST(block, M128(encKey)); block = _mm256_shuffle_epi8(block, M256(maskSrows)); block = affine(block, M256(outMaskLO), M256(outMaskHI)); return block; } __FORCEINLINE __m256i L(__m256i x) { __m256i T = _mm256_xor_si256(_mm256_slli_epi32(x, 2), _mm256_srli_epi32(x,30)); T = _mm256_xor_si256(T, _mm256_slli_epi32 (x,10)); T = _mm256_xor_si256(T, _mm256_srli_epi32 (x,22)); T = _mm256_xor_si256(T, _mm256_slli_epi32 (x,18)); T = _mm256_xor_si256(T, _mm256_srli_epi32 (x,14)); T = _mm256_xor_si256(T, _mm256_slli_epi32 (x,24)); T = _mm256_xor_si256(T, _mm256_srli_epi32 (x, 8)); return T; } /* // inp: T0, T1, T2, T3 // out: K0, K1, K2, K3 */ #define TRANSPOSE_INP(K0,K1,K2,K3, T0,T1,T2,T3) \ K0 = _mm256_unpacklo_epi32(T0, T1); \ K1 = _mm256_unpacklo_epi32(T2, T3); \ K2 = _mm256_unpackhi_epi32(T0, T1); \ K3 = _mm256_unpackhi_epi32(T2, T3); \ \ T0 = _mm256_unpacklo_epi64(K0, K1); \ T1 = _mm256_unpacklo_epi64(K2, K3); \ T2 = _mm256_unpackhi_epi64(K0, K1); \ T3 = _mm256_unpackhi_epi64(K2, K3); \ \ K2 = _mm256_permutevar8x32_epi32(T1, M256(permMask)); \ K1 = _mm256_permutevar8x32_epi32(T2, M256(permMask)); \ K3 = _mm256_permutevar8x32_epi32(T3, M256(permMask)); \ K0 = _mm256_permutevar8x32_epi32(T0, M256(permMask)) /* // inp: K0, K1, K2, K3 // out: T0, T1, T2, T3 */ #define TRANSPOSE_OUT(T0,T1,T2,T3, K0,K1,K2,K3) \ T0 = _mm256_unpacklo_epi32(K1, K0); \ T1 = _mm256_unpacklo_epi32(K3, K2); \ T2 = _mm256_unpackhi_epi32(K1, K0); \ T3 = _mm256_unpackhi_epi32(K3, K2); \ \ K0 = _mm256_unpacklo_epi64(T1, T0); \ K1 = _mm256_unpacklo_epi64(T3, T2); \ K2 = _mm256_unpackhi_epi64(T1, T0); \ K3 = _mm256_unpackhi_epi64(T3, T2); \ \ T0 = _mm256_permute2x128_si256(K0, K2, 0x20); \ T1 = _mm256_permute2x128_si256(K1, K3, 0x20); \ T2 = _mm256_permute2x128_si256(K0, K2, 0x31); \ T3 = _mm256_permute2x128_si256(K1, K3, 0x31) #endif /* __SMS4_SBOX_L9_H_ */ #endif /* _IPP_G9, _IPP32E_L9 */
39.688172
122
0.663912
[ "transform" ]
c3c3606135ba68902420e9ed34f7a1d792695ef6
5,359
c
C
src/graphics.c
kovleventer/BorderGenerator
44ea65ea77133d8a000e381a3f9eb80f8fa8039f
[ "MIT" ]
2
2017-12-04T12:44:26.000Z
2017-12-04T19:10:47.000Z
src/graphics.c
kovleventer/BorderGenerator
44ea65ea77133d8a000e381a3f9eb80f8fa8039f
[ "MIT" ]
null
null
null
src/graphics.c
kovleventer/BorderGenerator
44ea65ea77133d8a000e381a3f9eb80f8fa8039f
[ "MIT" ]
null
null
null
#include "graphics.h" #include "functions.h" void render(SDL_Surface* main, SDL_Surface* map, SDL_Surface* borders, List* capitals, bool isGenerated) { // Heightmap SDL_BlitSurface(map, NULL, main, NULL); // Borders if (isGenerated) { SDL_BlitSurface(borders, NULL, main, NULL); } // Capitals for (List* iter = capitals; iter != NULL; iter = iter->next) { int x = iter->capital.position.x; int y = iter->capital.position.y; filledCircleRGBA(main, x, y, 10, 255, 0, 0, 255); } // Information texts uint32_t color = 0x0000FFFF; stringColor(main, 10, 10, "Press 'r' to render the current borders", color); stringColor(main, 10, 30, "Press 's' to save the current capitals", color); stringColor(main, 10, 50, "Press 'c' to clear the list of capitals", color); stringColor(main, 10, 70, "Press keys 0-8 to change the distance calculation function", color); SDL_Flip(main); } List* get_clicked(int x, int y, List* l) { for (List* iter = l; iter != NULL; iter = iter->next) { // Implements a search and a distance calculator in one method int dx = iter->capital.position.x - x; int dy = iter->capital.position.y - y; if (dx * dx + dy * dy < 100) { return iter; } } return NULL; } void start(void) { // Declaring variables // Screen width and height are aligned to heightmap int scrW = 1201 * 8 / 9 + 1; int scrH = 1201 * 5 / 9 + 1; SDL_Surface* mainScreen; SDL_Surface* mapScreen; SDL_Surface* bordersScreen; bool isGenerated = false; char heightmapPath[] = "data/merged.hgta"; char capitalsPath[] = "data/capitals.txt"; // Initializing SDL SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER); mainScreen = SDL_SetVideoMode(scrW, scrH, 0, SDL_ANYFORMAT); if (!mainScreen) { fprintf(stderr, "Can not open window\n"); exit(1); } SDL_WM_SetCaption("Border Generator", "Border Generator"); srand(time(NULL)); // Initializing variables and data Heightmap heightmap = read_heightmap(heightmapPath, scrW, scrH); mapScreen = heightmap_to_surface(heightmap); List* capitals = read_capitals(capitalsPath); bordersScreen = SDL_CreateRGBSurface(0, scrW, scrH, 32, 0, 0, 0, 0); SDL_SetAlpha(bordersScreen, SDL_SRCALPHA, 127); // Distance calculation functions int (*functions[])(int, int) = { no_height, basic_height, delta_height, tanh_height, relu_height, elu_height, softplus_height, sqrt_height, sine_height }; int funcIndex = 1; // Mainloop render(mainScreen, mapScreen, bordersScreen, capitals, isGenerated); List* clicked = NULL; bool quit = false; SDL_Event ev; while(!quit) { SDL_WaitEvent(&ev); switch (ev.type) { case SDL_QUIT: // Quits the program quit = true; break; case SDL_MOUSEBUTTONDOWN: if (ev.button.button == SDL_BUTTON_LEFT) { // Left clicking on a point makes it be able to be dragged clicked = get_clicked(ev.button.x, ev.button.y, capitals); if (clicked == NULL) { // If no point is clicked, a new one is inserted with a random color capitals = ll_add_item(capitals, (Capital){ (Point){ .x = ev.button.x, .y = ev.button.y }, (SDL_Color){ rand() % 255, rand() % 255, rand() % 255 } }); } } else if (ev.button.button == SDL_BUTTON_RIGHT) { // Right clicking on a pont removes it capitals = ll_remove_item(capitals, get_clicked(ev.button.x, ev.button.y, capitals)); // Right clicking nowhere does nothing } // Clicking possibly alters the capitals and invalidates the generated borders isGenerated = false; render(mainScreen, mapScreen, bordersScreen, capitals, isGenerated); break; case SDL_KEYDOWN: switch (ev.key.keysym.sym) { case SDLK_s: // S saves the capitals to a file save_capitals(capitalsPath, capitals); break; case SDLK_0: case SDLK_1: case SDLK_2: case SDLK_3: case SDLK_4: case SDLK_5: case SDLK_6: case SDLK_7: case SDLK_8: // Keys 0-8 generates borders again with a different function if required isGenerated = isGenerated && ((ev.key.keysym.sym - SDLK_0) == funcIndex); funcIndex = ev.key.keysym.sym - SDLK_0; case SDLK_r: // R generates and renders the borders if (!isGenerated) { voronoi(heightmap, capitals, bordersScreen, functions[funcIndex]); isGenerated = true; render(mainScreen, mapScreen, bordersScreen, capitals, isGenerated); } break; case SDLK_c: // C deletes all capitals capitals = ll_free_list(capitals); isGenerated = false; render(mainScreen, mapScreen, bordersScreen, capitals, isGenerated); } break; case SDL_MOUSEMOTION: // Drag'n'drop functionality // Rendering on mousemotion is rather expensive // However since actual rendering is quite fast, it is not a big problem if (clicked != NULL) { int x = ev.motion.x; int y = ev.motion.y; clicked->capital.position.x = x; clicked->capital.position.y = y; isGenerated = false; render(mainScreen, mapScreen, bordersScreen, capitals, isGenerated); } break; case SDL_MOUSEBUTTONUP: // The drop part of drag'n'drop clicked = NULL; break; } } // Cleanup ll_free_list(capitals); free_heightmap(heightmap); SDL_FreeSurface(mapScreen); SDL_FreeSurface(bordersScreen); SDL_Quit(); }
30.106742
106
0.668968
[ "render" ]
c3cc529f91ec15b73a0a95f88b534225b0c0192e
1,284
h
C
tests/folds_test_case.h
juruen/cavalieri
c3451579193fc8f081b6228ae295b463a0fd23bd
[ "MIT" ]
54
2015-01-14T21:11:56.000Z
2021-06-27T13:29:40.000Z
tests/folds_test_case.h
juruen/cavalieri
c3451579193fc8f081b6228ae295b463a0fd23bd
[ "MIT" ]
null
null
null
tests/folds_test_case.h
juruen/cavalieri
c3451579193fc8f081b6228ae295b463a0fd23bd
[ "MIT" ]
10
2015-07-15T05:09:34.000Z
2019-01-10T07:32:02.000Z
#ifndef FOLDS_TEST_CASE #define FOLDS_TEST_CASE #include <folds/folds.h> TEST(sum_test_case, test) { std::vector<Event> v; std::vector<Event> events(5); for (auto & e: events) { e.set_metric_d(1); } ASSERT_EQ(5, sum(events).metric_d()); } TEST(product_test_case, test) { std::vector<Event> v; std::vector<Event> events(5); for (auto & e: events) { e.set_metric_d(2); } ASSERT_EQ(1<<5, product(events).metric_d()); } TEST(difference_test_case, test) { std::vector<Event> v; std::vector<Event> events(3); for (auto & e: events) { e.set_metric_d(1); } ASSERT_EQ(-1, difference(events).metric_d()); } TEST(mean_test_case, test) { std::vector<Event> v; std::vector<Event> events(3); for (size_t i = 1; i < 4; i++) { events[i - 1].set_metric_d(i); } ASSERT_EQ(2, mean(events).metric_d()); } TEST(maximum_test_case, test) { std::vector<Event> v; std::vector<Event> events(3); for (size_t i = 1; i < 4; i++) { events[i - 1].set_metric_d(i); } ASSERT_EQ(3, maximum(events).metric_d()); } TEST(minimum_test_case, test) { std::vector<Event> v; std::vector<Event> events(3); for (size_t i = 1; i < 4; i++) { events[i - 1].set_metric_d(i); } ASSERT_EQ(1, minimum(events).metric_d()); } #endif
16.253165
47
0.622274
[ "vector" ]
c3d04c1599b81c6e50d1859f5851b8ab9f55ffcb
1,382
h
C
NE/HyperNEAT/NEAT/include/NEAT_GPUANN.h
LMBernardo/HyperNEAT
8ebee6fda17dcf20dd0c6c081dc8681557c1faad
[ "BSD-3-Clause" ]
85
2015-02-08T20:36:17.000Z
2021-11-14T20:38:31.000Z
NE/HyperNEAT/NEAT/include/NEAT_GPUANN.h
LMBernardo/HyperNEAT
8ebee6fda17dcf20dd0c6c081dc8681557c1faad
[ "BSD-3-Clause" ]
9
2015-01-28T16:33:19.000Z
2020-04-12T23:03:28.000Z
NE/HyperNEAT/NEAT/include/NEAT_GPUANN.h
LMBernardo/HyperNEAT
8ebee6fda17dcf20dd0c6c081dc8681557c1faad
[ "BSD-3-Clause" ]
27
2015-01-28T16:33:30.000Z
2021-08-12T05:04:39.000Z
#ifndef GPUANN_H_INCLUDED #define GPUANN_H_INCLUDED #include "NEAT_Network.h" #include "NEAT_NetworkNode.h" #include "NEAT_NetworkLink.h" #include "NEAT_NetworkIndexedLink.h" #include "NEAT_FastLayeredNetwork.h" namespace NEAT { /** * The GPUANN class is designed to be faster at the cost * of being less dynamic. Adding/Removing links and nodes * is not supported with this network. */ class GPUANN : public FastLayeredNetwork<float> { public: /** * (Constructor) Create a Network with the inputed toplogy */ NEAT_DLL_EXPORT GPUANN( const vector<NetworkLayer<float> > &_layers ); /** * (Constructor) Empty Constructor */ NEAT_DLL_EXPORT GPUANN(); NEAT_DLL_EXPORT virtual ~GPUANN(); /** * update: This updates the network. * If the network has not been updated since construction or * reinitialize(), the network will be activated. This means * it will update (1+ExtraActivationUpdates+iterations) times! * Otherwise, it will update (iterations) times. If you do not * want the extra updates, call dummyActivation() before the first * update. */ NEAT_DLL_EXPORT virtual void update(); protected: }; } #endif // FASTNETWORK_H_INCLUDED
25.127273
74
0.631693
[ "vector" ]
c3f741748ce719b49478effcc591ad9a29f85795
1,707
h
C
include/drivers/ioapic.h
13824125580/zephyr-rr
531cd1b8d0663172dc6b4dd7cdfe91c26304706c
[ "Apache-2.0" ]
9
2016-10-07T15:31:17.000Z
2019-02-21T05:32:59.000Z
include/drivers/ioapic.h
13824125580/zephyr-rr
531cd1b8d0663172dc6b4dd7cdfe91c26304706c
[ "Apache-2.0" ]
2
2016-08-30T01:28:57.000Z
2017-09-27T01:50:28.000Z
include/drivers/ioapic.h
13824125580/zephyr-rr
531cd1b8d0663172dc6b4dd7cdfe91c26304706c
[ "Apache-2.0" ]
5
2016-06-11T07:44:20.000Z
2021-06-12T17:41:37.000Z
/* ioapic.h - public IOAPIC APIs */ /* * Copyright (c) 2012-2015 Wind River Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __INCioapich #define __INCioapich #include <drivers/loapic.h> #ifdef __cplusplus extern "C" { #endif /* * Redirection table entry bits: lower 32 bit * Used as flags argument in ioapic_irq_set */ #define IOAPIC_INT_MASK 0x00010000 #define IOAPIC_TRIGGER_MASK 0x00008000 #define IOAPIC_LEVEL 0x00008000 #define IOAPIC_EDGE 0x00000000 #define IOAPIC_REMOTE 0x00004000 #define IOAPIC_LOW 0x00002000 #define IOAPIC_HIGH 0x00000000 #define IOAPIC_LOGICAL 0x00000800 #define IOAPIC_PHYSICAL 0x00000000 #define IOAPIC_FIXED 0x00000000 #define IOAPIC_LOWEST 0x00000100 #define IOAPIC_SMI 0x00000200 #define IOAPIC_NMI 0x00000400 #define IOAPIC_INIT 0x00000500 #define IOAPIC_EXTINT 0x00000700 #ifndef _ASMLANGUAGE #include <device.h> void _ioapic_irq_enable(unsigned int irq); void _ioapic_irq_disable(unsigned int irq); void _ioapic_int_vec_set(unsigned int irq, unsigned int vector); void _ioapic_irq_set(unsigned int irq, unsigned int vector, uint32_t flags); #endif /* _ASMLANGUAGE */ #ifdef __cplusplus } #endif #endif /* __INCioapich */
27.532258
76
0.783245
[ "vector" ]
c3fa0b5d3c5d228ee9e31953c6cbc2f296cef0e1
18,746
h
C
rx621_sample/vect.h
radioshack16/rx621_sample
993734723d7114cc622f360981f99ed60675b32f
[ "MIT" ]
1
2017-06-12T13:00:22.000Z
2017-06-12T13:00:22.000Z
rx621_sample/vect.h
radioshack16/rx621_sample
993734723d7114cc622f360981f99ed60675b32f
[ "MIT" ]
null
null
null
rx621_sample/vect.h
radioshack16/rx621_sample
993734723d7114cc622f360981f99ed60675b32f
[ "MIT" ]
null
null
null
/***********************************************************************/ /* */ /* FILE :vect.h */ /* DATE :Sat, May 07, 2016 */ /* DESCRIPTION :Definition of Vector */ /* CPU TYPE :RX62N */ /* */ /* This file is generated by Renesas Project Generator (Ver.4.53). */ /* NOTE:THIS IS A TYPICAL EXAMPLE. */ /* */ /***********************************************************************/ /************************************************************************ * * Device : RX/RX600/RX62N * * File Name : vect.h * * Abstract : Definition of Vector. * * History : 1.00 (2010-03-05) [Hardware Manual Revision : 0.50] * : 1.01 (2010-03-15) [Hardware Manual Revision : 0.50] * : 1.02 (2011-06-20) [Hardware Manual Revision : 1.0] * * NOTE : THIS IS A TYPICAL EXAMPLE. * * Copyright (C) 2010 (2011) Renesas Electronics Corporation. * and Renesas Solutions Corp. * ************************************************************************/ // Exception(Supervisor Instruction) #pragma interrupt (Excep_SuperVisorInst) void Excep_SuperVisorInst(void); // Exception(Undefined Instruction) #pragma interrupt (Excep_UndefinedInst) void Excep_UndefinedInst(void); // Exception(Floating Point) #pragma interrupt (Excep_FloatingPoint) void Excep_FloatingPoint(void); // NMI #pragma interrupt (NonMaskableInterrupt) void NonMaskableInterrupt(void); // Dummy #pragma interrupt (Dummy) void Dummy(void); // BRK #pragma interrupt (Excep_BRK(vect=0)) void Excep_BRK(void); // vector 1 reserved // vector 2 reserved // vector 3 reserved // vector 4 reserved // vector 5 reserved // vector 6 reserved // vector 7 reserved // vector 8 reserved // vector 9 reserved // vector 10 reserved // vector 11 reserved // vector 12 reserved // vector 13 reserved // vector 14 reserved // vector 15 reserved // BUSERR #pragma interrupt (Excep_BUSERR(vect=16)) void Excep_BUSERR(void); // vector 17 reserved // vector 18 reserved // vector 19 reserved // vector 20 reserved // FCU_FCUERR #pragma interrupt (Excep_FCU_FCUERR(vect=21)) void Excep_FCU_FCUERR(void); // vector 22 reserved // FCU_FRDYI #pragma interrupt (Excep_FCU_FRDYI(vect=23)) void Excep_FCU_FRDYI(void); // vector 24 reserved // vector 25 reserved // vector 26 reserved // ICU SWINT #pragma interrupt (Excep_ICU_SWINT(vect=27)) void Excep_ICU_SWINT(void); // CMTU0_CMT0 #pragma interrupt (Excep_CMTU0_CMT0(vect=28)) void Excep_CMTU0_CMT0(void); // CMTU0_CMT1 #pragma interrupt (Excep_CMTU0_CMT1(vect=29)) void Excep_CMTU0_CMT1(void); // CMTU1_CMT2 #pragma interrupt (Excep_CMTU1_CMT2(vect=30)) void Excep_CMTU1_CMT2(void); // CMTU1_CMT3 #pragma interrupt (Excep_CMTU1_CMT3(vect=31)) void Excep_CMTU1_CMT3(void); // ETHER EINT #pragma interrupt (Excep_ETHER_EINT(vect=32)) void Excep_ETHER_EINT(void); // vector 33 reserved // vector 34 reserved // vector 35 reserved // USB0 D0FIFO0 #pragma interrupt (Excep_USB0_D0FIFO0(vect=36)) void Excep_USB0_D0FIFO0(void); // USB0 D1FIFO0 #pragma interrupt (Excep_USB0_D1FIFO0(vect=37)) void Excep_USB0_D1FIFO0(void); // USB0 USBI0 #pragma interrupt (Excep_USB0_USBI0(vect=38)) void Excep_USB0_USBI0(void); // vector 39 reserved // USB1 D0FIFO1 #pragma interrupt (Excep_USB1_D0FIFO1(vect=40)) void Excep_USB1_D0FIFO1(void); // USB1 D1FIFO1 #pragma interrupt (Excep_USB1_D1FIFO1(vect=41)) void Excep_USB1_D1FIFO1(void); // USB1 USBI1 #pragma interrupt (Excep_USB1_USBI1(vect=42)) void Excep_USB1_USBI1(void); // vector 43 reserved // RSPI0 SPEI0 #pragma interrupt (Excep_RSPI0_SPEI0(vect=44)) void Excep_RSPI0_SPEI0(void); // RSPI0 SPRI0 #pragma interrupt (Excep_RSPI0_SPRI0(vect=45)) void Excep_RSPI0_SPRI0(void); // RSPI0 SPTI0 #pragma interrupt (Excep_RSPI0_SPTI0(vect=46)) void Excep_RSPI0_SPTI0(void); // RSPI0 SPII0 #pragma interrupt (Excep_RSPI0_SPII0(vect=47)) void Excep_RSPI0_SPII0(void); // RSPI1 SPEI1 #pragma interrupt (Excep_RSPI1_SPEI1(vect=48)) void Excep_RSPI1_SPEI1(void); // RSPI1 SPRI1 #pragma interrupt (Excep_RSPI1_SPRI1(vect=49)) void Excep_RSPI1_SPRI1(void); // RSPI1 SPTI1 #pragma interrupt (Excep_RSPI1_SPTI1(vect=50)) void Excep_RSPI1_SPTI1(void); // RSPI1 SPII1 #pragma interrupt (Excep_RSPI1_SPII1(vect=51)) void Excep_RSPI1_SPII1(void); // vector 52 reserved // vector 53 reserved // vector 54 reserved // vector 55 reserved // CAN0 ERS0 #pragma interrupt (Excep_CAN0_ERS0(vect=56)) void Excep_CAN0_ERS0(void); // CAN0 RXF0 #pragma interrupt (Excep_CAN0_RXF0(vect=57)) void Excep_CAN0_RXF0(void); // CAN0 TXF0 #pragma interrupt (Excep_CAN0_TXF0(vect=58)) void Excep_CAN0_TXF0(void); // CAN0 RXM0 #pragma interrupt (Excep_CAN0_RXM0(vect=59)) void Excep_CAN0_RXM0(void); // CAN0 TXM0 #pragma interrupt (Excep_CAN0_TXM0(vect=60)) void Excep_CAN0_TXM0(void); // vector 61 reserved // RTC PRD #pragma interrupt (Excep_RTC_PRD(vect=62)) void Excep_RTC_PRD(void); // RTC CUP #pragma interrupt (Excep_RTC_CUP(vect=63)) void Excep_RTC_CUP(void); // IRQ0 #pragma interrupt (Excep_IRQ0(vect=64)) void Excep_IRQ0(void); // IRQ1 #pragma interrupt (Excep_IRQ1(vect=65)) void Excep_IRQ1(void); // IRQ2 #pragma interrupt (Excep_IRQ2(vect=66)) void Excep_IRQ2(void); // IRQ3 #pragma interrupt (Excep_IRQ3(vect=67)) void Excep_IRQ3(void); // IRQ4 #pragma interrupt (Excep_IRQ4(vect=68)) void Excep_IRQ4(void); // IRQ5 #pragma interrupt (Excep_IRQ5(vect=69)) void Excep_IRQ5(void); // IRQ6 #pragma interrupt (Excep_IRQ6(vect=70)) void Excep_IRQ6(void); // IRQ7 #pragma interrupt (Excep_IRQ7(vect=71)) void Excep_IRQ7(void); // IRQ8 #pragma interrupt (Excep_IRQ8(vect=72)) void Excep_IRQ8(void); // IRQ9 #pragma interrupt (Excep_IRQ9(vect=73)) void Excep_IRQ9(void); // IRQ10 #pragma interrupt (Excep_IRQ10(vect=74)) void Excep_IRQ10(void); // IRQ11 #pragma interrupt (Excep_IRQ11(vect=75)) void Excep_IRQ11(void); // IRQ12 #pragma interrupt (Excep_IRQ12(vect=76)) void Excep_IRQ12(void); // IRQ13 #pragma interrupt (Excep_IRQ13(vect=77)) void Excep_IRQ13(void); // IRQ14 #pragma interrupt (Excep_IRQ14(vect=78)) void Excep_IRQ14(void); // IRQ15 #pragma interrupt (Excep_IRQ15(vect=79)) void Excep_IRQ15(void); // vector 80 reserved // vector 81 reserved // vector 82 reserved // vector 83 reserved // vector 84 reserved // vector 85 reserved // vector 86 reserved // vector 87 reserved // vector 88 reserved // vector 89 reserved // USB RESUME USBR0 #pragma interrupt (Excep_USB_USBR0(vect=90)) void Excep_USB_USBR0(void); // USB RESUME USBR1 #pragma interrupt (Excep_USB_USBR1(vect=91)) void Excep_USB_USBR1(void); // RTC ALM #pragma interrupt (Excep_RTC_ALM(vect=92)) void Excep_RTC_ALM(void); // vector 93 reserved // vector 94 reserved // vector 95 reserved // WDT_WOVI #pragma interrupt (Excep_WDT_WOVI(vect=96)) void Excep_WDT_WOVI(void); // vector 97 reserved // AD0_ADI0 #pragma interrupt (Excep_AD0_ADI0(vect=98)) void Excep_AD0_ADI0(void); // AD1_ADI1 #pragma interrupt (Excep_AD1_ADI1(vect=99)) void Excep_AD1_ADI1(void); // vector 100 reserved // vector 101 reserved // S12AD ADI12 #pragma interrupt (Excep_S12AD_ADI12(vect=102)) void Excep_S12AD_ADI12(void); // vector 103 reserved // vector 104 reserved // vector 105 reserved // vector 106 reserved // vector 107 reserved // vector 108 reserved // vector 109 reserved // vector 110 reserved // vector 111 reserved // vector 112 reserved // vector 113 reserved // MTU0 TGIA0 #pragma interrupt (Excep_MTU0_TGIA0(vect=114)) void Excep_MTU0_TGIA0(void); // MTU0 TGIB0 #pragma interrupt (Excep_MTU0_TGIB0(vect=115)) void Excep_MTU0_TGIB0(void); // MTU0 TGIC0 #pragma interrupt (Excep_MTU0_TGIC0(vect=116)) void Excep_MTU0_TGIC0(void); // MTU0 TGID0 #pragma interrupt (Excep_MTU0_TGID0(vect=117)) void Excep_MTU0_TGID0(void); // MTU0 TCIV0 #pragma interrupt (Excep_MTU0_TCIV0(vect=118)) void Excep_MTU0_TCIV0(void); // MTU0 TGIE0 #pragma interrupt (Excep_MTU0_TGIE0(vect=119)) void Excep_MTU0_TGIE0(void); // MTU0 TGIF0 #pragma interrupt (Excep_MTU0_TGIF0(vect=120)) void Excep_MTU0_TGIF0(void); // MTU1 TGIA1 #pragma interrupt (Excep_MTU1_TGIA1(vect=121)) void Excep_MTU1_TGIA1(void); // MTU1 TGIB1 #pragma interrupt (Excep_MTU1_TGIB1(vect=122)) void Excep_MTU1_TGIB1(void); // MTU1 TCIV1 #pragma interrupt (Excep_MTU1_TCIV1(vect=123)) void Excep_MTU1_TCIV1(void); // MTU1 TCIU1 #pragma interrupt (Excep_MTU1_TCIU1(vect=124)) void Excep_MTU1_TCIU1(void); // MTU2 TGIA2 #pragma interrupt (Excep_MTU2_TGIA2(vect=125)) void Excep_MTU2_TGIA2(void); // MTU2 TGIB2 #pragma interrupt (Excep_MTU2_TGIB2(vect=126)) void Excep_MTU2_TGIB2(void); // MTU2 TCIV2 #pragma interrupt (Excep_MTU2_TCIV2(vect=127)) void Excep_MTU2_TCIV2(void); // MTU2 TCIU2 #pragma interrupt (Excep_MTU2_TCIU2(vect=128)) void Excep_MTU2_TCIU2(void); // MTU3 TGIA3 #pragma interrupt (Excep_MTU3_TGIA3(vect=129)) void Excep_MTU3_TGIA3(void); // MTU3 TGIB3 #pragma interrupt (Excep_MTU3_TGIB3(vect=130)) void Excep_MTU3_TGIB3(void); // MTU3 TGIC3 #pragma interrupt (Excep_MTU3_TGIC3(vect=131)) void Excep_MTU3_TGIC3(void); // MTU3 TGID3 #pragma interrupt (Excep_MTU3_TGID3(vect=132)) void Excep_MTU3_TGID3(void); // MTU3 TCIV3 #pragma interrupt (Excep_MTU3_TCIV3(vect=133)) void Excep_MTU3_TCIV3(void); // MTU4 TGIA4 #pragma interrupt (Excep_MTU4_TGIA4(vect=134)) void Excep_MTU4_TGIA4(void); // MTU4 TGIB4 #pragma interrupt (Excep_MTU4_TGIB4(vect=135)) void Excep_MTU4_TGIB4(void); // MTU4 TGIC4 #pragma interrupt (Excep_MTU4_TGIC4(vect=136)) void Excep_MTU4_TGIC4(void); // MTU4 TGID4 #pragma interrupt (Excep_MTU4_TGID4(vect=137)) void Excep_MTU4_TGID4(void); // MTU4 TCIV4 #pragma interrupt (Excep_MTU4_TCIV4(vect=138)) void Excep_MTU4_TCIV4(void); // MTU5 TCIU5 #pragma interrupt (Excep_MTU5_TCIU5(vect=139)) void Excep_MTU5_TCIU5(void); // MTU5 TCIV5 #pragma interrupt (Excep_MTU5_TCIV5(vect=140)) void Excep_MTU5_TCIV5(void); // MTU5 TCIW5 #pragma interrupt (Excep_MTU5_TCIW5(vect=141)) void Excep_MTU5_TCIW5(void); // MTU6 TGIA6 #pragma interrupt (Excep_MTU6_TGIA6(vect=142)) void Excep_MTU6_TGIA6(void); // MTU6 TGIB6 #pragma interrupt (Excep_MTU6_TGIB6(vect=143)) void Excep_MTU6_TGIB6(void); // MTU6 TGIC6 #pragma interrupt (Excep_MTU6_TGIC6(vect=144)) void Excep_MTU6_TGIC6(void); // MTU6 TGID6 #pragma interrupt (Excep_MTU6_TGID6(vect=145)) void Excep_MTU6_TGID6(void); // MTU6 TCIV6 #pragma interrupt (Excep_MTU6_TCIV6(vect=146)) void Excep_MTU6_TCIV6(void); // MTU6 TGIE6 #pragma interrupt (Excep_MTU6_TGIE6(vect=147)) void Excep_MTU6_TGIE6(void); // MTU6 TGIF6 #pragma interrupt (Excep_MTU6_TGIF6(vect=148)) void Excep_MTU6_TGIF6(void); // MTU7 TGIA7 #pragma interrupt (Excep_MTU7_TGIA7(vect=149)) void Excep_MTU7_TGIA7(void); // MTU7 TGIB7 #pragma interrupt (Excep_MTU7_TGIB7(vect=150)) void Excep_MTU7_TGIB7(void); // MTU7 TCIV7 #pragma interrupt (Excep_MTU7_TCIV7(vect=151)) void Excep_MTU7_TCIV7(void); // MTU7 TCIU7 #pragma interrupt (Excep_MTU7_TCIU7(vect=152)) void Excep_MTU7_TCIU7(void); // MTU8 TGIA8 #pragma interrupt (Excep_MTU8_TGIA8(vect=153)) void Excep_MTU8_TGIA8(void); // MTU8 TGIB8 #pragma interrupt (Excep_MTU8_TGIB8(vect=154)) void Excep_MTU8_TGIB8(void); // MTU8 TCIV8 #pragma interrupt (Excep_MTU8_TCIV8(vect=155)) void Excep_MTU8_TCIV8(void); // MTU8 TCIU8 #pragma interrupt (Excep_MTU8_TCIU8(vect=156)) void Excep_MTU8_TCIU8(void); // MTU9 TGIA9 #pragma interrupt (Excep_MTU9_TGIA9(vect=157)) void Excep_MTU9_TGIA9(void); // MTU9 TGIB9 #pragma interrupt (Excep_MTU9_TGIB9(vect=158)) void Excep_MTU9_TGIB9(void); // MTU9 TGIC9 #pragma interrupt (Excep_MTU9_TGIC9(vect=159)) void Excep_MTU9_TGIC9(void); // MTU9 TGID9 #pragma interrupt (Excep_MTU9_TGID9(vect=160)) void Excep_MTU9_TGID9(void); // MTU9 TCIV9 #pragma interrupt (Excep_MTU9_TCIV9(vect=161)) void Excep_MTU9_TCIV9(void); // MTU10 TGIA10 #pragma interrupt (Excep_MTU10_TGIA10(vect=162)) void Excep_MTU10_TGIA10(void); // MTU10 TGIB10 #pragma interrupt (Excep_MTU10_TGIB10(vect=163)) void Excep_MTU10_TGIB10(void); // MTU10 TGIC10 #pragma interrupt (Excep_MTU10_TGIC10(vect=164)) void Excep_MTU10_TGIC10(void); // MTU10 TGID10 #pragma interrupt (Excep_MTU10_TGID10(vect=165)) void Excep_MTU10_TGID10(void); // MTU10 TCIV10 #pragma interrupt (Excep_MTU10_TCIV10(vect=166)) void Excep_MTU10_TCIV10(void); // MTU11 TCIU11 #pragma interrupt (Excep_MTU11_TCIU11(vect=167)) void Excep_MTU11_TCIU11(void); // MTU11 TCIV11 #pragma interrupt (Excep_MTU11_TCIV11(vect=168)) void Excep_MTU11_TCIV11(void); // MTU11 TCIW11 #pragma interrupt (Excep_MTU11_TCIW11(vect=169)) void Excep_MTU11_TCIW11(void); // POE OEI1 #pragma interrupt (Excep_POE_OEI1(vect=170)) void Excep_POE_OEI1(void); // POE OEI1 #pragma interrupt (Excep_POE_OEI2(vect=171)) void Excep_POE_OEI2(void); // POE OEI1 #pragma interrupt (Excep_POE_OEI3(vect=172)) void Excep_POE_OEI3(void); // POE OEI1 #pragma interrupt (Excep_POE_OEI4(vect=173)) void Excep_POE_OEI4(void); // TMR0_CMI0A #pragma interrupt (Excep_TMR0_CMI0A(vect=174)) void Excep_TMR0_CMI0A(void); // TMR0_CMI0B #pragma interrupt (Excep_TMR0_CMI0B(vect=175)) void Excep_TMR0_CMI0B(void); // TMR0_OV0I #pragma interrupt (Excep_TMR0_OV0I(vect=176)) void Excep_TMR0_OV0I(void); // TMR1_CMI1A #pragma interrupt (Excep_TMR1_CMI1A(vect=177)) void Excep_TMR1_CMI1A(void); // TMR1_CMI1B #pragma interrupt (Excep_TMR1_CMI1B(vect=178)) void Excep_TMR1_CMI1B(void); // TMR1_OV1I #pragma interrupt (Excep_TMR1_OV1I(vect=179)) void Excep_TMR1_OV1I(void); // TMR2_CMI2A #pragma interrupt (Excep_TMR2_CMI2A(vect=180)) void Excep_TMR2_CMI2A(void); // TMR2_CMI2B #pragma interrupt (Excep_TMR2_CMI2B(vect=181)) void Excep_TMR2_CMI2B(void); // TMR2_OV2I #pragma interrupt (Excep_TMR2_OV2I(vect=182)) void Excep_TMR2_OV2I(void); // TMR3_CMI3A #pragma interrupt (Excep_TMR3_CMI3A(vect=183)) void Excep_TMR3_CMI3A(void); // TMR3_CMI3B #pragma interrupt (Excep_TMR3_CMI3B(vect=184)) void Excep_TMR3_CMI3B(void); // TMR3_OV3I #pragma interrupt (Excep_TMR3_OV3I(vect=185)) void Excep_TMR3_OV3I(void); // vector 186 reserved // vector 187 reserved // vector 188 reserved // vector 189 reserved // vector 190 reserved // vector 191 reserved // vector 192 reserved // vector 193 reserved // vector 194 reserved // vector 195 reserved // vector 196 reserved // vector 197 reserved // DMACA DMAC0 #pragma interrupt (Excep_DMACA_DMAC0(vect=198)) void Excep_DMACA_DMAC0(void); // DMAC DMAC1 #pragma interrupt (Excep_DMACA_DMAC1(vect=199)) void Excep_DMACA_DMAC1(void); // DMAC DMAC2 #pragma interrupt (Excep_DMACA_DMAC2(vect=200)) void Excep_DMACA_DMAC2(void); // DMAC DMAC3 #pragma interrupt (Excep_DMACA_DMAC3(vect=201)) void Excep_DMACA_DMAC3(void); // EXDMAC DMAC0 #pragma interrupt (Excep_EXDMAC_DMAC0(vect=202)) void Excep_EXDMAC_DMAC0(void); // EXDMAC DMAC1 #pragma interrupt (Excep_EXDMAC_DMAC1(vect=203)) void Excep_EXDMAC_DMAC1(void); // vector 203 reserved // vector 204 reserved // vector 205 reserved // vector 206 reserved // vector 207 reserved // vector 208 reserved // vector 209 reserved // vector 210 reserved // vector 211 reserved // vector 212 reserved // vector 213 reserved // SCI0_ERI0 #pragma interrupt (Excep_SCI0_ERI0(vect=214)) void Excep_SCI0_ERI0(void); // SCI0_RXI0 #pragma interrupt (Excep_SCI0_RXI0(vect=215)) void Excep_SCI0_RXI0(void); // SCI0_TXI0 #pragma interrupt (Excep_SCI0_TXI0(vect=216)) void Excep_SCI0_TXI0(void); // SCI0_TEI0 #pragma interrupt (Excep_SCI0_TEI0(vect=217)) void Excep_SCI0_TEI0(void); // SCI1_ERI1 #pragma interrupt (Excep_SCI1_ERI1(vect=218)) void Excep_SCI1_ERI1(void); // SCI1_RXI1 #pragma interrupt (Excep_SCI1_RXI1(vect=219)) void Excep_SCI1_RXI1(void); // SCI1_TXI1 #pragma interrupt (Excep_SCI1_TXI1(vect=220)) void Excep_SCI1_TXI1(void); // SCI1_TEI1 #pragma interrupt (Excep_SCI1_TEI1(vect=221)) void Excep_SCI1_TEI1(void); // SCI2_ERI2 #pragma interrupt (Excep_SCI2_ERI2(vect=222)) void Excep_SCI2_ERI2(void); // SCI2_RXI2 #pragma interrupt (Excep_SCI2_RXI2(vect=223)) void Excep_SCI2_RXI2(void); // SCI2_TXI2 #pragma interrupt (Excep_SCI2_TXI2(vect=224)) void Excep_SCI2_TXI2(void); // SCI2_TEI2 #pragma interrupt (Excep_SCI2_TEI2(vect=225)) void Excep_SCI2_TEI2(void); // SCI3_ERI3 #pragma interrupt (Excep_SCI3_ERI3(vect=226)) void Excep_SCI3_ERI3(void); // SCI3_RXI3 #pragma interrupt (Excep_SCI3_RXI3(vect=227)) void Excep_SCI3_RXI3(void); // SCI3_TXI3 #pragma interrupt (Excep_SCI3_TXI3(vect=228)) void Excep_SCI3_TXI3(void); // SCI3_TEI3 #pragma interrupt (Excep_SCI3_TEI3(vect=229)) void Excep_SCI3_TEI3(void); // vector 230 reserved // vector 231 reserved // vector 232 reserved // vector 233 reserved // SCI5_ERI5 #pragma interrupt (Excep_SCI5_ERI5(vect=234)) void Excep_SCI5_ERI5(void); // SCI5_RXI5 #pragma interrupt (Excep_SCI5_RXI5(vect=235)) void Excep_SCI5_RXI5(void); // SCI5_TXI5 #pragma interrupt (Excep_SCI5_TXI5(vect=236)) void Excep_SCI5_TXI5(void); // SCI5_TEI5 #pragma interrupt (Excep_SCI5_TEI5(vect=237)) void Excep_SCI5_TEI5(void); // SCI6_ERI6 #pragma interrupt (Excep_SCI6_ERI6(vect=238)) void Excep_SCI6_ERI6(void); // SCI6_RXI6 #pragma interrupt (Excep_SCI6_RXI6(vect=239)) void Excep_SCI6_RXI6(void); // SCI6_TXI6 #pragma interrupt (Excep_SCI6_TXI6(vect=240)) void Excep_SCI6_TXI6(void); // SCI6_TEI6 #pragma interrupt (Excep_SCI6_TEI6(vect=241)) void Excep_SCI6_TEI6(void); // vector 242 reserved // vector 243 reserved // vector 244 reserved // vector 245 reserved // RIIC0_EEI0 #pragma interrupt (Excep_RIIC0_EEI0(vect=246)) void Excep_RIIC0_EEI0(void); // RIIC0_RXI0 #pragma interrupt (Excep_RIIC0_RXI0(vect=247)) void Excep_RIIC0_RXI0(void); // RIIC0_TXI0 #pragma interrupt (Excep_RIIC0_TXI0(vect=248)) void Excep_RIIC0_TXI0(void); // RIIC0_TEI0 #pragma interrupt (Excep_RIIC0_TEI0(vect=249)) void Excep_RIIC0_TEI0(void); // RIIC1_EEI1 #pragma interrupt (Excep_RIIC1_EEI1(vect=250)) void Excep_RIIC1_EEI1(void); // RIIC1_RXI1 #pragma interrupt (Excep_RIIC1_RXI1(vect=251)) void Excep_RIIC1_RXI1(void); // RIIC1_TXI1 #pragma interrupt (Excep_RIIC1_TXI1(vect=252)) void Excep_RIIC1_TXI1(void); // RIIC1_TEI1 #pragma interrupt (Excep_RIIC1_TEI1(vect=253)) void Excep_RIIC1_TEI1(void); // vector 254 reserved // vector 255 reserved //;<<VECTOR DATA START (POWER ON RESET)>> //;Power On Reset PC extern void PowerON_Reset_PC(void); //;<<VECTOR DATA END (POWER ON RESET)>>
22.722424
147
0.731249
[ "vector" ]
7f0c0501ceff273a66a2e713477bc48d4bccb9ca
3,445
h
C
LambdaEngine/Include/Rendering/ParticleRenderer.h
IbexOmega/CrazyCanvas
f60f01aaf9c988e4da8990dc1ef3caac20cecf7e
[ "MIT" ]
18
2020-09-04T08:00:54.000Z
2021-08-29T23:04:45.000Z
LambdaEngine/Include/Rendering/ParticleRenderer.h
IbexOmega/LambdaEngine
f60f01aaf9c988e4da8990dc1ef3caac20cecf7e
[ "MIT" ]
32
2020-09-12T19:24:50.000Z
2020-12-11T14:29:44.000Z
LambdaEngine/Include/Rendering/ParticleRenderer.h
IbexOmega/LambdaEngine
f60f01aaf9c988e4da8990dc1ef3caac20cecf7e
[ "MIT" ]
2
2020-12-15T15:36:13.000Z
2021-03-27T14:27:02.000Z
#pragma once #include "RenderGraphTypes.h" #include "CustomRenderer.h" #include "Rendering/Core/API/DescriptorCache.h" namespace LambdaEngine { struct DescriptorBindingData { const Buffer* pBuffers = nullptr; uint64 Offset = 0; uint64 SizeInByte = 0; }; class ParticleRenderer : public CustomRenderer { public: ParticleRenderer(); ~ParticleRenderer(); bool Init(); void SetCurrentParticleCount(uint32 particleCount, uint32 emitterCount) { m_ParticleCount = particleCount; m_EmitterCount = emitterCount; }; virtual bool RenderGraphInit(const CustomRendererRenderGraphInitDesc* pPreInitDesc) override final; virtual void Update(Timestamp delta, uint32 modFrameIndex, uint32 backBufferIndex) override final; virtual void UpdateTextureResource(const String& resourceName, const TextureView* const* ppPerImageTextureViews, const TextureView* const* ppPerSubImageTextureViews, const Sampler* const* ppPerImageSamplers, uint32 imageCount, uint32 subImageCount, bool backBufferBound) override final; virtual void UpdateBufferResource(const String& resourceName, const Buffer* const* ppBuffers, uint64* pOffsets, uint64* pSizesInBytes, uint32 count, bool backBufferBound) override final; virtual void Render( uint32 modFrameIndex, uint32 backBufferIndex, CommandList** ppFirstExecutionStage, CommandList** ppSecondaryExecutionStage, bool Sleeping) override final; FORCEINLINE virtual FPipelineStageFlag GetFirstPipelineStage() const override final { return FPipelineStageFlag::PIPELINE_STAGE_FLAG_VERTEX_SHADER; } FORCEINLINE virtual FPipelineStageFlag GetLastPipelineStage() const override final { return FPipelineStageFlag::PIPELINE_STAGE_FLAG_PIXEL_SHADER; } virtual const String& GetName() const override final { static String name = RENDER_GRAPH_PARTICLE_RENDER_STAGE_NAME; return name; } private: bool CreatePipelineLayout(); bool CreateDescriptorSets(); bool CreateShaders(); bool CreateCommandLists(); bool CreateRenderPass(RenderPassAttachmentDesc* pColorAttachmentDesc, RenderPassAttachmentDesc* pDepthStencilAttachmentDesc); bool CreatePipelineState(); private: bool m_Initilized = false; bool m_MeshShaders = false; uint32 m_ParticleCount; uint32 m_EmitterCount; GUID_Lambda m_MeshShaderGUID = 0; GUID_Lambda m_PixelShaderGUID = 0; GUID_Lambda m_VertexShaderGUID = 0; const Buffer* m_pIndirectBuffer = nullptr; const Buffer* m_pIndexBuffer = nullptr; TSharedRef<const TextureView> m_RenderTarget = nullptr; TSharedRef<const TextureView> m_DepthStencil = nullptr; TSharedRef<RenderPass> m_RenderPass = nullptr; uint64 m_PipelineStateID = 0; TSharedRef<PipelineLayout> m_PipelineLayout = nullptr; TSharedRef<DescriptorHeap> m_DescriptorHeap = nullptr; // Descriptor sets TSharedRef<DescriptorSet> m_VertexInstanceDescriptorSet = nullptr; TSharedRef<DescriptorSet> m_AtlasTexturesDescriptorSet = nullptr; TSharedRef<DescriptorSet> m_AtlasInfoBufferDescriptorSet = nullptr; TSharedRef<DescriptorSet> m_PerFrameBufferDescriptorSet; DescriptorCache m_DescriptorCache; uint32 m_BackBufferCount = 0; CommandAllocator** m_ppGraphicCommandAllocators = nullptr; CommandList** m_ppGraphicCommandLists = nullptr; private: static ParticleRenderer* s_pInstance; }; }
35.885417
288
0.771263
[ "render" ]
7f0cc7e1275a00dfa224d3447c25f30ab0a900e7
11,272
h
C
gui/source/gui_attributes_editor.h
awarnke/crystal-facet-uml
89da1452379c53aef473b4dc28501a6b068d66a9
[ "Apache-2.0" ]
1
2021-06-06T05:57:21.000Z
2021-06-06T05:57:21.000Z
gui/source/gui_attributes_editor.h
awarnke/crystal-facet-uml
89da1452379c53aef473b4dc28501a6b068d66a9
[ "Apache-2.0" ]
1
2021-08-30T17:42:27.000Z
2021-08-30T17:42:27.000Z
gui/source/gui_attributes_editor.h
awarnke/crystal-facet-uml
89da1452379c53aef473b4dc28501a6b068d66a9
[ "Apache-2.0" ]
null
null
null
/* File: gui_attributes_editor.h; Copyright and License: see below */ #ifndef GUI_ATTRIBUTES_EDITOR_H #define GUI_ATTRIBUTES_EDITOR_H /* public file for the doxygen documentation: */ /*! \file * \brief Provides data to editing widgets and reacts on user events */ #include "gui_simple_message_to_user.h" #include "gui_resources.h" #include "gui_attributes_editor_types.h" #include "storage/data_database_reader.h" #include "storage/data_database.h" #include "storage/data_change_message.h" #include "data_classifier.h" #include "data_diagram.h" #include "data_feature.h" #include "data_relationship.h" #include "ctrl_controller.h" #include "data_id.h" #include <gtk/gtk.h> /*! * \brief enumeration on tools */ enum gui_attributes_editor_sync_dir_enum { GUI_ATTRIBUTES_EDITOR_SYNC_DIR_DB_TO_GUI = 0, /*!< default sync direction: data changes update gui widgets */ GUI_ATTRIBUTES_EDITOR_SYNC_DIR_GUI_TO_DB, /*!< gui widgets must not be updated till user changes are written back to db */ }; typedef enum gui_attributes_editor_sync_dir_enum gui_attributes_editor_sync_dir_t; /*! * \brief attributes of the gui_attributes_editor_t */ struct gui_attributes_editor_struct { data_database_reader_t *db_reader; /*!< pointer to external database reader */ ctrl_controller_t *controller; /*!< pointer to external controller */ data_database_t *database; /*!< pointer to external data_database_t */ gui_simple_message_to_user_t *message_to_user; /*!< pointer to external gui_simple_message_to_user_t */ gui_attributes_editor_sync_dir_t sync_dir; /*!< flag that indicates if changes to database shall overwrite user input */ data_id_t selected_object_id; /*!< id of the object which is currently edited */ data_diagram_t private_diagram_cache; /*!< own instance of a diagram cache */ data_classifier_t private_classifier_cache; /*!< own instance of a classifier cache */ data_feature_t private_feature_cache; /*!< own instance of a feature cache */ data_relationship_t private_relationship_cache; /*!< own instance of a relationship cache */ data_id_t latest_created_id; /*!< id of the latest created object, allows to check if the selected object is new */ data_id_t second_latest_id; /*!< id of the second latest created object, needed if a classifier and a containment relation are created together. */ gui_attributes_editor_types_t type_lists; /*!< own instance of type lists */ GtkLabel *id_label; /*!< pointer to external id label widget */ GtkEntry *name_entry; /*!< pointer to external text entry widget */ GtkEntry *stereotype_entry; /*!< pointer to external text entry widget */ GtkComboBox *type_combo_box; /*!< pointer to external combo box widget */ GtkIconView *type_icon_grid; /*!< pointer to external icon view widget */ GtkTextView *description_text_view; /*!< pointer to external text view widget */ GtkButton *commit_button; /*!< pointer to external button widget */ }; typedef struct gui_attributes_editor_struct gui_attributes_editor_t; /*! * \brief initializes the gui_attributes_editor_t struct * * \param this_ pointer to own object attributes * \param id_label pointer to id-label widget * \param name_entry pointer to text entry widget * \param stereotype_entry pointer to external text entry widget * \param type_combo_box pointer to external combo box widget * \param type_icon_grid pointer to external type-icons view widget * \param description_text_view pointer to text entry widget * \param commit_button pointer to button widget * \param resources pointer to a resource provider * \param controller pointer to the controller object to use * \param db_reader pointer to the database reader object to use * \param database pointer to the database object to use, used to flush the database if requested * \param message_to_user pointer to the message_to_user object to use */ void gui_attributes_editor_init ( gui_attributes_editor_t *this_, GtkLabel *id_label, GtkEntry *name_entry, GtkEntry *stereotype_entry, GtkComboBox *type_combo_box, GtkIconView *type_icon_grid, GtkTextView *description_text_view, GtkButton *commit_button, gui_resources_t *resources, ctrl_controller_t *controller, data_database_reader_t *db_reader, data_database_t *database, gui_simple_message_to_user_t *message_to_user ); /*! * \brief destroys the gui_attributes_editor_t struct * * \param this_ pointer to own object attributes */ void gui_attributes_editor_destroy ( gui_attributes_editor_t *this_ ); /*! * \brief redraws the textedit widgets. * * \param this_ pointer to own object attributes */ void gui_attributes_editor_update_widgets ( gui_attributes_editor_t *this_ ); /*! * \brief commits changed properties to the database. * * \param this_ pointer to own object attributes */ void gui_attributes_editor_commit_changes ( gui_attributes_editor_t *this_ ); /*! * \brief prints the gui_attributes_editor_t struct to the trace output * * \param this_ pointer to own object attributes */ void gui_attributes_editor_trace ( const gui_attributes_editor_t *this_ ); /* ================================ USER INPUT CALLBACKS ================================ */ /*! * \brief callback that informs that the focus of a widget is lost */ gboolean gui_attributes_editor_name_focus_lost_callback ( GtkWidget *widget, GdkEvent *event, gpointer user_data ); /*! * \brief callback that informs that enter was pressed */ void gui_attributes_editor_name_enter_callback ( GtkEntry *widget, gpointer user_data ); /*! * \brief callback that informs that the focus of a widget is lost */ gboolean gui_attributes_editor_stereotype_focus_lost_callback ( GtkWidget *widget, GdkEvent *event, gpointer user_data ); /*! * \brief callback that informs that enter was pressed */ void gui_attributes_editor_stereotype_enter_callback ( GtkEntry *widget, gpointer user_data ); /*! * \brief callback that informs that the type in the combo box changed */ void gui_attributes_editor_type_changed_callback ( GtkComboBox *widget, gpointer user_data ); /*! * \brief callback that informs that an entry of the shortlist of type icons was activated */ void gui_attributes_editor_type_shortlist_callback ( GtkIconView *iconview, GtkTreePath *path, gpointer user_data ); /*! * \brief callback that informs that the focus of a widget is lost */ gboolean gui_attributes_editor_description_focus_lost_callback ( GtkWidget *widget, GdkEvent *event, gpointer user_data ); /*! * \brief callback that informs that the commit button was pressed */ void gui_attributes_editor_commit_clicked_callback (GtkButton *button, gpointer user_data ); /* ================================ SELECTION or MODEL CHANGED CALLBACKS ================================ */ /*! * \brief callback that informs that another object was selected */ void gui_attributes_editor_selected_object_changed_callback( GtkWidget *widget, data_id_t *id, gpointer user_data ); /*! * \brief callback that informs that the data of an object changed */ void gui_attributes_editor_data_changed_callback( GtkWidget *widget, data_change_message_t *msg, gpointer user_data ); /* ================================ PRIVATE METHODS ================================ */ /*! * \brief loads an object into cache (even if this object is already cached). * * \param this_ pointer to own object attributes * \param id identifier of the object to be loaded */ void gui_attributes_editor_private_load_object ( gui_attributes_editor_t *this_, data_id_t id ); /*! * \brief commits changes to the objects name to the controller. * * If the name is not modified, nothing happens. * \param this_ pointer to own object attributes */ void gui_attributes_editor_private_name_commit_changes ( gui_attributes_editor_t *this_ ); /*! * \brief commits changes to the objects stereotype to the controller. * * If the stereotype is not modified, nothing happens. * \param this_ pointer to own object attributes */ void gui_attributes_editor_private_stereotype_commit_changes ( gui_attributes_editor_t *this_ ); /*! * \brief commits changes to the objects type to the controller. * * If the type is not modified, nothing happens. * \param this_ pointer to own object attributes * \param obj_type obj_type new object type to be set. This has to be read out from the type selection widgets by the caller */ void gui_attributes_editor_private_type_commit_changes ( gui_attributes_editor_t *this_, int obj_type ); /*! * \brief commits changes to the objects description to the controller. * * If the description is not modified, nothing happens. * \param this_ pointer to own object attributes */ void gui_attributes_editor_private_description_commit_changes ( gui_attributes_editor_t *this_ ); /*! * \brief redraws the widget using the cached data loaded by gui_attributes_editor_private_load_object from the database. * * \param this_ pointer to own object attributes */ void gui_attributes_editor_private_id_update_view ( gui_attributes_editor_t *this_ ); /*! * \brief redraws the widget using the cached data loaded by gui_attributes_editor_private_load_object from the database. * * \param this_ pointer to own object attributes */ void gui_attributes_editor_private_name_update_view ( gui_attributes_editor_t *this_ ); /*! * \brief redraws the widget using the cached data loaded by gui_attributes_editor_private_load_object from the database. * * \param this_ pointer to own object attributes */ void gui_attributes_editor_private_stereotype_update_view ( gui_attributes_editor_t *this_ ); /*! * \brief redraws the widget using the cached data loaded by gui_attributes_editor_private_load_object from the database. * * \param this_ pointer to own object attributes */ void gui_attributes_editor_private_type_update_view ( gui_attributes_editor_t *this_ ); /*! * \brief redraws the widget using the cached data loaded by gui_attributes_editor_private_load_object from the database. * * \param this_ pointer to own object attributes */ void gui_attributes_editor_private_description_update_view ( gui_attributes_editor_t *this_ ); #endif /* GUI_ATTRIBUTES_EDITOR_H */ /* Copyright 2016-2022 Andreas Warnke Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */
40.84058
152
0.732523
[ "object", "model" ]
7f0d01bd66d0f3b1ba69259fa97bfa13847cfbe0
1,574
h
C
MultiDeviceInferencePipeline/inference/conf/ExecutionSettings.h
semberecki/AGX
c5979185543ab54e25908a8ee42744126e2acddf
[ "Apache-2.0" ]
1
2021-04-16T10:20:08.000Z
2021-04-16T10:20:08.000Z
MultiDeviceInferencePipeline/inference/conf/ExecutionSettings.h
semberecki/AGX
c5979185543ab54e25908a8ee42744126e2acddf
[ "Apache-2.0" ]
null
null
null
MultiDeviceInferencePipeline/inference/conf/ExecutionSettings.h
semberecki/AGX
c5979185543ab54e25908a8ee42744126e2acddf
[ "Apache-2.0" ]
null
null
null
/*************************************************************************************************** * Copyright (c) 2018-2019 NVIDIA Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Project: MultiDeviceInferencePipeline > Inference * * File: DL4AGX/MultiDeviceInferencePipeline/inference/conf/ExecutionSettings.h * * Description: Struct to hold execution settings for the application ***************************************************************************************************/ #pragma once #include <map> #include <string> #include <vector> namespace multideviceinferencepipeline { namespace inference { namespace conf { struct ExecutionSettings { std::vector<std::string> inFiles; std::vector<std::string> outFiles; uint32_t batchSize; bool profile; uint32_t iters = 1; uint32_t timed_iters = 0; float detectionThreshold = 0.5; std::map<std::string, EngineSettings> pipelineBindings; }; } //namespace conf } //namespace inference } //namespace multideviceinferencepipeline
33.489362
101
0.651842
[ "vector" ]
7f0d31799efb55dbee6f3eab56560893fad80a07
10,922
h
C
zircon/system/ulib/fbl/include/fbl/wavl_tree_best_node_observer.h
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
5
2022-01-10T20:22:17.000Z
2022-01-21T20:14:17.000Z
zircon/system/ulib/fbl/include/fbl/wavl_tree_best_node_observer.h
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
1
2022-03-01T01:12:04.000Z
2022-03-01T01:17:26.000Z
zircon/system/ulib/fbl/include/fbl/wavl_tree_best_node_observer.h
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2021 The Fuchsia Authors // // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT #ifndef FBL_WAVL_TREE_BEST_NODE_OBSERVER_H_ #define FBL_WAVL_TREE_BEST_NODE_OBSERVER_H_ #include <zircon/assert.h> #include <fbl/macros.h> namespace fbl { // WAVLTreeBestNodeObserver // // Definition of a WAVLTreeObserver which helps to automate the process of // maintaining a "best value in this subtree" invariant inside of a WAVL tree. // // For example, consider a set of objects, each of which has an "Priority" and // an "Awesomeness" property. If a user is maintaining a collection of these // objects indexed by "Priority", they may want to be able to easily answer // questions about the maximum "Awesomeness" of sets of objects partitioned by // priority. If every member in the tree also maintained a "maximum Awesomeness // for my subtree" value, then the following questions can be easily answered. // // 1) What is the maximum awesomeness across all members of the tree? This is // the maximum subtree awesomeness of the root node of the tree. // 2) What is the maximum awesomeness across all members of the tree with a // priority > X? This is the maximum subtree awesomeness of // tree.upper_bound(X) (if such a node exists). // // WAVLTreeBestNodeObserver implements all of the observer hooks needed to // maintain such an invariant based on a set of Traits defined by the user which // allow the WAVLTreeBestNodeObserver to know when one node has a "better" value // than another node, and to access the per-node storage which holds the "best" // value for a subtree. // // Traits implementations should contain the following definitions: // // struct Traits { // // TODO(johngro): When we are allowed to use C++20, make this a more formal // // concept definition. // // Returns a node's value. In the example above, this is the node's "awesomeness". // static ValueType GetValue(const Object& node) { ... } // // // Returns the current "best" value of the subtree rooted at node. // static ValueType GetSubtreeBest(const Object& node) { ... } // // // Compares two values, and returns true if |a| is "better" than |b|. Otherwise false. // static bool Compare(ValueType a, ValueType b) { ... } // // // Assigns the value |val| to the node's subtree-best storage. // static void AssignBest(Object& node, ValueType val) { ... } // // // Resets the value node's subtree-best storage. Called when nodes are // // being removed from their tree. Note that users don't _have_ to make use // // of this hook if they do not care about stale values being stored in their // // subtree-best storage. // static void ResetBest(Object& target) { ... } // }; // // The Traits used for the "awesomness" example given above might look like the // following if "awesomeness" was expressed as a strictly positive uint32_t: // // struct AwesomeObj { // // ... // constexpr uint32_t kInvalidAwesomeness = 0; // uint32_t priority; // uint32_t awesomeness; // uint32_t subtree_best{kInvalidAwesomeness}; // }; // // struct MaxAwesomeTraits { // static uint32_t GetValue(const AwesomeObj& node) { return node.awesomness; } // static uint32_t GetSubtreeBest(const AwesomeObj& node) { return node.subtree_best; } // static bool Compare(uint32_t a, uint32_t b) { return a > b; } // static void AssignBest(AwesomeObj& node, uint32_t val) { node.subtree_best = val; } // static void ResetBest(AwesomeObj& target) { // node.subtree_best = AwesomeObj::kInvalidAwesomeness; // } // }; // // using MaxAwesomeObserver = fbl::WAVLReeBestNodeObserver<MaxAwesomeTraits>; // // In addition to the traits which define the "best" value to maintain, // WAVLTreeBestNodeObserver has two more boolean template parameters which can // be used to control behavior. They are: // // AllowInsertOrFindCollision // AllowInsertOrReplaceCollision // // By default, both of these values are |true|. If a collision happens during // either an insert_or_find or an insert_or_replace operation, the "best value" // invariant will be maintained. On the other hand, if a user knows that they // will never encounter collisions as a result of one or the other (or both) of // these operations, they may set the appropriate Allow template argument to // false, causing the WAVLTreeBestNodeObserver to fail a ZX_DEBUG_ASSERT in the // case that associated collision is ever encountered during operation. // template <typename Traits, bool AllowInsertOrFindCollision = true, bool AllowInsertOrReplaceCollision = true> struct WAVLTreeBestNodeObserver { private: DECLARE_HAS_MEMBER_FN(has_on_insert_collision, OnInsertCollision); DECLARE_HAS_MEMBER_FN(has_on_insert_replace, OnInsertReplace); public: template <typename Iter> static void RecordInsert(Iter node) { Traits::AssignBest(*node, Traits::GetValue(*node)); } template <typename T, typename Iter> static void RecordInsertCollision(T* node, Iter collision) { // |node| did not actually end up getting inserted into the tree, but all of // the node down until collision we updated during the descent during calls // to RecordInsertTraverse. We need to restore the "best" invariant by // re-computing the proper values starting from collision, up until we reach // root. ZX_DEBUG_ASSERT(AllowInsertOrFindCollision); RecomputeUntilRoot(collision); } template <typename Iter, typename T> static void RecordInsertReplace(Iter node, T* replacement) { // |node| is still in the tree, but it is about to be replaced by // |replacement|. Update the value of |node| to hold the value of // |replacement|, then propagate the value up the tree to the root (as we do // in the case of an erase operation). Once we are finished, transfer the // computed "best" value for for |node|'s subtree over to replacement, then // reset the value of node (as it is just about to be removed from the tree, // and replaced with |replacement|). ZX_DEBUG_ASSERT(AllowInsertOrReplaceCollision); UpdateBest(Traits::GetValue(*replacement), node); RecomputeUntilRoot(node.parent()); Traits::AssignBest(*replacement, Traits::GetSubtreeBest(*node)); Traits::ResetBest(*node); } template <typename T, typename Iter> static void RecordInsertTraverse(T* node, Iter ancestor) { // If the value of |node| is better than the value of the ancestor we just // traversed, update the |ancestor| to hold |node|'s value. const auto node_val = Traits::GetValue(*node); if (Traits::Compare(node_val, Traits::GetSubtreeBest(*ancestor))) { Traits::AssignBest(*ancestor, node_val); } } // Rotations are used to adjust the height of nodes that are out of balance. // During a rotation, the pivot takes the position of the parent, and takes over // storing the "best" value for the subtree, as all of the nodes in the // overall subtree remain the same. The original parent inherits the lr_child // of the pivot, potentially invalidating its new subtree and requiring an // update. // // The following diagrams the relationship of the nodes in a left rotation: // // ::After:: ::Before:: | // | // pivot parent | // / \ / \ | // parent rl_child <----------- sibling pivot | // / \ / \ | // sibling lr_child lr_child rl_child | // // In a right rotation, all of the relationships are reflected. However, this // does not affect the update logic. template <typename Iter> static void RecordRotation(Iter pivot, Iter lr_child, Iter rl_child, Iter parent, Iter sibling) { // |pivot| is about to take |parent|'s place in the tree. The overall // subtree maintains the same "best" value, so |pivot| can just take // |parent|'s best value.. Traits::AssignBest(*pivot, Traits::GetSubtreeBest(*parent)); // The descendents of |sibling|, |lr_child|, and |rl_child| are not // changing, meaning that we do not need to take any action to update their // current best subtree values. // // |parent|, on the other hand, is becoming the root of a new subtree with // |sibling| and |lr_child| as its new children. Select the new best value // for the subtree rooted at |parent| from these three options. // auto best = Traits::GetValue(*parent); if (sibling) { const auto sibling_best = Traits::GetSubtreeBest(*sibling); if (Traits::Compare(sibling_best, best)) { best = sibling_best; } } if (lr_child) { const auto lr_child_best = Traits::GetSubtreeBest(*lr_child); if (Traits::Compare(lr_child_best, best)) { best = lr_child_best; } } Traits::AssignBest(*parent, best); } template <typename T, typename Iter> static void RecordErase(T* node, Iter invalidated) { // When a node is removed all of the ancestors become invalidated up to // the root. Traverse up the tree from the point of invalidation and // restore the subtree invariant. Note, there will be no invalidated node // in the case that this was the last node removed. RecomputeUntilRoot(invalidated); // |node| is leaving the tree. Give our Traits the opportunity to reset // its "best" value. Traits::ResetBest(*node); } // Promotion/Demotion/DoubleRotation count hooks are not needed to maintain // our "best" invariant. static void RecordInsertPromote() {} static void RecordInsertRotation() {} static void RecordInsertDoubleRotation() {} static void RecordEraseDemote() {} static void RecordEraseRotation() {} static void RecordEraseDoubleRotation() {} private: template <typename Iter> static void RecomputeUntilRoot(Iter current) { for (; current; current = current.parent()) { UpdateBest(Traits::GetValue(*current), current); } } template <typename ValueType, typename Iter> static void UpdateBest(ValueType value, Iter node) { if (Iter left = node.left(); left) { ValueType left_best = Traits::GetSubtreeBest(*left); if (Traits::Compare(left_best, value)) { value = left_best; } } if (Iter right = node.right(); right) { ValueType right_best = Traits::GetSubtreeBest(*right); if (Traits::Compare(right_best, value)) { value = right_best; } } Traits::AssignBest(*node, value); } }; } // namespace fbl #endif // FBL_WAVL_TREE_BEST_NODE_OBSERVER_H_
42.498054
99
0.681102
[ "object" ]
7f1331d4d243be6d11050fd2067318406742a9b5
1,201
h
C
Engine/Source/Editor/Layers/Public/LayersModule.h
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Editor/Layers/Public/LayersModule.h
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Editor/Layers/Public/LayersModule.h
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #pragma once #include "ModuleInterface.h" /** * The module holding all of the UI related peices for Layers */ class FLayersModule : public IModuleInterface { public: /** * Called right after the module DLL has been loaded and the module object has been created */ virtual void StartupModule(); /** * Called before the module is unloaded, right before the module object is destroyed. */ virtual void ShutdownModule(); /** * Creates a Layer Browser widget */ virtual TSharedRef<class SWidget> CreateLayerBrowser(); /** * Creates a widget that represents the layers the specified actors share in common as a cloud */ virtual TSharedRef< class SWidget> CreateLayerCloud( const TArray< TWeakObjectPtr< AActor > >& Actors ); /** Delegates to be called to extend the layers menus */ DECLARE_DELEGATE_RetVal_OneParam( TSharedRef<FExtender>, FLayersMenuExtender, const TSharedRef<FUICommandList>); virtual TArray<FLayersMenuExtender>& GetAllLayersMenuExtenders() {return LayersMenuExtenders;} private: /** All extender delegates for the layers menus */ TArray<FLayersMenuExtender> LayersMenuExtenders; };
26.688889
113
0.752706
[ "object" ]
7f19383c6918ecbdae5adfffcc49d87cdba9635e
1,731
h
C
ARCo UI/ARCo UI/Navigator/URL Patterns/ARCURLNavigatorPattern.h
7studios/RestRocket
4b8eee466d74386d85dea4784b13a712683d518f
[ "Apache-2.0" ]
null
null
null
ARCo UI/ARCo UI/Navigator/URL Patterns/ARCURLNavigatorPattern.h
7studios/RestRocket
4b8eee466d74386d85dea4784b13a712683d518f
[ "Apache-2.0" ]
null
null
null
ARCo UI/ARCo UI/Navigator/URL Patterns/ARCURLNavigatorPattern.h
7studios/RestRocket
4b8eee466d74386d85dea4784b13a712683d518f
[ "Apache-2.0" ]
null
null
null
// // ARCURLNavigatorPattern.h // ARCo Example // // Created by GREGORY GENTLING on 9/10/11. // Copyright (c) 2011 __MyCompanyName__. All rights reserved. // #import <Foundation/Foundation.h> #import "ARCPatternTEXT.h" #import "ARCURLPattern.h" @interface ARCURLNavigatorPattern : ARCURLPattern { Class _targetClass; id _targetObject; ARCURLArgumentType _navigationMode; NSString* _parentURL; NSInteger _transition; NSInteger _argumentCount; UIModalPresentationStyle _modalPresentationStyle; } @property (nonatomic, assign) Class targetClass; @property (nonatomic, strong) id targetObject; @property (nonatomic, readonly) ARCURLArgumentType navigationMode; @property (nonatomic, copy) NSString* parentURL; @property (nonatomic, assign) NSInteger transition; @property (nonatomic, assign) NSInteger argumentCount; @property (nonatomic, readonly) BOOL isUniversal; @property (nonatomic, readonly) BOOL isFragment; @property (nonatomic, assign) UIModalPresentationStyle modalPresentationStyle; - (id)initWithTarget:(id)target; - (id)initWithTarget:(id)target mode:(ARCURLArgumentType)navigationMode; - (void)compile; - (BOOL)matchURL:(NSURL*)URL; - (id)invoke:(id)target withURL:(NSURL*)URL query:(NSDictionary*)query; /** * either instantiates an object or delegates object creation * depending on current configuration * @return the newly created object or nil if something went wrong */ - (id)createObjectFromURL:(NSURL*)URL query:(NSDictionary*)query; @end
32.660377
78
0.670133
[ "object" ]
7f1c1e4859e72d35712cd28e1d29a5c8ce9824bd
15,137
h
C
src/gausskernel/storage/mot/fdw_adapter/mot_internal.h
Yanci0/openGauss-server
b2ff10be1367c77f2fda396d6c12ffa3c25874c7
[ "MulanPSL-1.0" ]
360
2020-06-30T14:47:34.000Z
2022-03-31T15:21:53.000Z
src/gausskernel/storage/mot/fdw_adapter/mot_internal.h
Yanci0/openGauss-server
b2ff10be1367c77f2fda396d6c12ffa3c25874c7
[ "MulanPSL-1.0" ]
4
2020-06-30T15:09:16.000Z
2020-07-14T06:20:03.000Z
src/gausskernel/storage/mot/fdw_adapter/mot_internal.h
futurewei-cloud/chogori-opengauss
f43410e1643c887819e718d9baceb9e853ad9574
[ "MulanPSL-1.0" ]
133
2020-06-30T14:47:36.000Z
2022-03-25T15:29:00.000Z
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * ------------------------------------------------------------------------- * * mot_internal.h * MOT Foreign Data Wrapper internal interfaces to the MOT engine. * * IDENTIFICATION * src/gausskernel/storage/mot/fdw_adapter/mot_internal.h * * ------------------------------------------------------------------------- */ #ifndef MOT_INTERNAL_H #define MOT_INTERNAL_H #include <map> #include <string> #include "catalog_column_types.h" #include "foreign/fdwapi.h" #include "nodes/nodes.h" #include "nodes/makefuncs.h" #include "utils/numeric.h" #include "utils/numeric_gs.h" #include "pgstat.h" #include "global.h" #include "mot_fdw_error.h" #include "mot_fdw_xlog.h" #include "mot_engine.h" #include "bitmapset.h" #include "storage/mot/jit_exec.h" #include "mot_match_index.h" using std::map; using std::string; #define MIN_DYNAMIC_PROCESS_MEMORY 2 * 1024 * 1024 #define MOT_INSERT_FAILED_MSG "Insert failed" #define MOT_UPDATE_FAILED_MSG "Update failed" #define MOT_DELETE_FAILED_MSG "Delete failed" #define MOT_UNIQUE_VIOLATION_MSG "duplicate key value violates unique constraint \"%s\"" #define MOT_UNIQUE_VIOLATION_DETAIL "Key %s already exists." #define MOT_TABLE_NOTFOUND "Table \"%s\" doesn't exist" #define MOT_UPDATE_INDEXED_FIELD_NOT_SUPPORTED "Update indexed field \"%s\" in table \"%s\" is not supported" #define NULL_DETAIL ((char*)nullptr) #define abortParentTransaction(msg, detail) \ ereport(ERROR, \ (errmodule(MOD_MOT), errcode(ERRCODE_FDW_ERROR), errmsg(msg), (detail != nullptr ? errdetail(detail) : 0))); #define abortParentTransactionParams(error, msg, msg_p, detail, detail_p) \ ereport(ERROR, (errmodule(MOD_MOT), errcode(error), errmsg(msg, msg_p), errdetail(detail, detail_p))); #define abortParentTransactionParamsNoDetail(error, msg, ...) \ ereport(ERROR, (errmodule(MOD_MOT), errcode(error), errmsg(msg, __VA_ARGS__))); #define isMemoryLimitReached() \ { \ if (MOTAdaptor::m_engine->IsSoftMemoryLimitReached()) { \ MOT_LOG_ERROR("Maximum logical memory capacity %lu bytes of allowed %lu bytes reached", \ (uint64_t)MOTAdaptor::m_engine->GetCurrentMemoryConsumptionBytes(), \ (uint64_t)MOTAdaptor::m_engine->GetHardMemoryLimitBytes()); \ ereport(ERROR, \ (errmodule(MOD_MOT), \ errcode(ERRCODE_OUT_OF_LOGICAL_MEMORY), \ errmsg("You have reached a maximum logical capacity"), \ errdetail("Only destructive operations are allowed, please perform database cleanup to free some " \ "memory."))); \ } \ } namespace MOT { class Table; class Index; class IndexIterator; class Column; class MOTEngine; } // namespace MOT #ifndef MOTFdwStateSt typedef struct MOTFdwState_St MOTFdwStateSt; #endif typedef enum : uint8_t { SORTDIR_NONE = 0, SORTDIR_ASC = 1, SORTDIR_DESC = 2 } SORTDIR_ENUM; typedef enum : uint8_t { FDW_LIST_STATE = 1, FDW_LIST_BITMAP = 2 } FDW_LIST_TYPE; typedef struct Order_St { SORTDIR_ENUM m_order; int m_lastMatch; int m_cols[MAX_KEY_COLUMNS]; void init() { m_order = SORTDIR_NONE; m_lastMatch = -1; for (uint32_t i = 0; i < MAX_KEY_COLUMNS; i++) m_cols[i] = 0; } } OrderSt; #define MOT_REC_TID_NAME "ctid" typedef struct MOTRecConvert { union { uint64_t m_ptr; ItemPointerData m_self; /* SelfItemPointer */ } m_u; } MOTRecConvertSt; #define SORT_STRATEGY(x) ((x == BTGreaterStrategyNumber) ? SORTDIR_DESC : SORTDIR_ASC) struct MOTFdwState_St { ::TransactionId m_txnId; bool m_allocInScan; CmdType m_cmdOper; SORTDIR_ENUM m_order; bool m_hasForUpdate; Oid m_foreignTableId; AttrNumber m_numAttrs; AttrNumber m_ctidNum; uint16_t m_numExpr; uint8_t* m_attrsUsed; uint8_t* m_attrsModified; // this will be merged into attrs_used in BeginModify List* m_remoteConds; List* m_remoteCondsOrig; List* m_localConds; List* m_execExprs; ExprContext* m_econtext; double m_startupCost; double m_totalCost; MatchIndex* m_bestIx; MatchIndex* m_paramBestIx; MatchIndex m_bestIxBuf; // ENGINE MOT::Table* m_table; MOT::IndexIterator* m_cursor[2] = {nullptr, nullptr}; MOT::TxnManager* m_currTxn; void* m_currItem = nullptr; uint32_t m_rowsFound = 0; bool m_cursorOpened = false; MOT::MaxKey m_stateKey[2]; bool m_forwardDirectionScan; MOT::AccessType m_internalCmdOper; }; class MOTAdaptor { public: static void Init(); static void Destroy(); static void NotifyConfigChange(); static inline void GetCmdOper(MOTFdwStateSt* festate) { switch (festate->m_cmdOper) { case CMD_SELECT: if (festate->m_hasForUpdate) { festate->m_internalCmdOper = MOT::AccessType::RD_FOR_UPDATE; } else { festate->m_internalCmdOper = MOT::AccessType::RD; } break; case CMD_DELETE: festate->m_internalCmdOper = MOT::AccessType::DEL; break; case CMD_UPDATE: festate->m_internalCmdOper = MOT::AccessType::WR; break; case CMD_INSERT: festate->m_internalCmdOper = MOT::AccessType::INS; break; case CMD_UNKNOWN: case CMD_MERGE: case CMD_UTILITY: case CMD_NOTHING: default: festate->m_internalCmdOper = MOT::AccessType::INV; break; } } static MOT::TxnManager* InitTxnManager( const char* callerSrc, MOT::ConnectionId connection_id = INVALID_CONNECTION_ID); static void DestroyTxn(int status, Datum ptr); static void DeleteTablePtr(MOT::Table* t); static MOT::RC CreateTable(CreateForeignTableStmt* table, TransactionId tid); static MOT::RC CreateIndex(IndexStmt* index, TransactionId tid); static MOT::RC DropIndex(DropForeignStmt* stmt, TransactionId tid); static MOT::RC DropTable(DropForeignStmt* stmt, TransactionId tid); static MOT::RC TruncateTable(Relation rel, TransactionId tid); static MOT::RC VacuumTable(Relation rel, TransactionId tid); static uint64_t GetTableIndexSize(uint64_t tabId, uint64_t ixId); static MotMemoryDetail* GetMemSize(uint32_t* nodeCount, bool isGlobal); static MotSessionMemoryDetail* GetSessionMemSize(uint32_t* sessionCount); static MOT::RC ValidateCommit(); static void RecordCommit(uint64_t csn); static MOT::RC Commit(uint64_t csn); // Does both ValidateCommit and RecordCommit static void EndTransaction(); static void Rollback(); static MOT::RC Prepare(); static void CommitPrepared(uint64_t csn); static void RollbackPrepared(); static MOT::RC InsertRow(MOTFdwStateSt* fdwState, TupleTableSlot* slot); static MOT::RC UpdateRow(MOTFdwStateSt* fdwState, TupleTableSlot* slot, MOT::Row* currRow); static MOT::RC DeleteRow(MOTFdwStateSt* fdwState, TupleTableSlot* slot); /* Convertors */ inline static void PGNumericToMOT(const Numeric n, MOT::DecimalSt& d) { int sign = NUMERIC_SIGN(n); d.m_hdr.m_flags = 0; d.m_hdr.m_flags |= (sign == NUMERIC_POS ? DECIMAL_POSITIVE : (sign == NUMERIC_NEG ? DECIMAL_NEGATIVE : ((sign == NUMERIC_NAN) ? DECIMAL_NAN : 0))); d.m_hdr.m_ndigits = NUMERIC_NDIGITS(n); d.m_hdr.m_scale = NUMERIC_DSCALE(n); d.m_hdr.m_weight = NUMERIC_WEIGHT(n); d.m_round = 0; if (d.m_hdr.m_ndigits > 0) { errno_t erc = memcpy_s(d.m_digits, DECIMAL_MAX_SIZE - sizeof(MOT::DecimalSt), (void*)NUMERIC_DIGITS(n), d.m_hdr.m_ndigits * sizeof(NumericDigit)); securec_check(erc, "\0", "\0"); } } inline static Numeric MOTNumericToPG(MOT::DecimalSt* d) { NumericVar v; v.ndigits = d->m_hdr.m_ndigits; v.dscale = d->m_hdr.m_scale; v.weight = (int)(int16_t)(d->m_hdr.m_weight); v.sign = (d->m_hdr.m_flags & DECIMAL_POSITIVE ? NUMERIC_POS : (d->m_hdr.m_flags & DECIMAL_NEGATIVE ? NUMERIC_NEG : ((d->m_hdr.m_flags & DECIMAL_NAN) ? DECIMAL_NAN : 0))); v.buf = (NumericDigit*)&d->m_round; v.digits = (NumericDigit*)d->m_digits; return makeNumeric(&v); } // data conversion static void DatumToMOT(MOT::Column* col, Datum datum, Oid type, uint8_t* data); static void DatumToMOTKey(MOT::Column* col, Oid datumType, Datum datum, Oid colType, uint8_t* data, size_t len, KEY_OPER oper, uint8_t fill = 0x00); static void MOTToDatum(MOT::Table* table, const Form_pg_attribute attr, uint8_t* data, Datum* value, bool* is_null); static void PackRow(TupleTableSlot* slot, MOT::Table* table, uint8_t* attrs_used, uint8_t* destRow); static void PackUpdateRow(TupleTableSlot* slot, MOT::Table* table, const uint8_t* attrs_used, uint8_t* destRow); static void UnpackRow(TupleTableSlot* slot, MOT::Table* table, const uint8_t* attrs_used, uint8_t* srcRow); // scan helpers static void OpenCursor(Relation rel, MOTFdwStateSt* festate); static bool IsScanEnd(MOTFdwStateSt* festate); static void CreateKeyBuffer(Relation rel, MOTFdwStateSt* festate, int start); // planning helpers static bool SetMatchingExpr(MOTFdwStateSt* state, MatchIndexArr* marr, int16_t colId, KEY_OPER op, Expr* expr, Expr* parent, bool set_local); static MatchIndex* GetBestMatchIndex( MOTFdwStateSt* festate, MatchIndexArr* marr, int numClauses, bool setLocal = true); inline static int32_t AddParam(List** params, Expr* expr) { int32_t index = 0; ListCell* cell = nullptr; foreach (cell, *params) { ++index; if (equal(expr, (Node*)lfirst(cell))) { break; } } if (cell == nullptr) { /* add the parameter to the list */ ++index; *params = lappend(*params, expr); } return index; } static MOT::MOTEngine* m_engine; static bool m_initialized; static bool m_callbacks_initialized; private: /** * @brief Adds all the columns. * @param table Table object being created. * @param tableElts Column definitions list. * @param[out] hasBlob Whether any column is a blob. * NOTE: On failure, table object will be deleted and ereport will be done. */ static void AddTableColumns(MOT::Table* table, List* tableElts, bool& hasBlob); static void ValidateCreateIndex(IndexStmt* index, MOT::Table* table, MOT::TxnManager* txn); static void VarcharToMOTKey(MOT::Column* col, Oid datumType, Datum datum, Oid colType, uint8_t* data, size_t len, KEY_OPER oper, uint8_t fill); static void FloatToMOTKey(MOT::Column* col, Oid datumType, Datum datum, uint8_t* data); static void NumericToMOTKey(MOT::Column* col, Oid datumType, Datum datum, uint8_t* data); static void TimestampToMOTKey(MOT::Column* col, Oid datumType, Datum datum, uint8_t* data); static void TimestampTzToMOTKey(MOT::Column* col, Oid datumType, Datum datum, uint8_t* data); static void DateToMOTKey(MOT::Column* col, Oid datumType, Datum datum, uint8_t* data); }; inline MOT::TxnManager* GetSafeTxn(const char* callerSrc, ::TransactionId txn_id = 0) { if (!u_sess->mot_cxt.txn_manager) { MOTAdaptor::InitTxnManager(callerSrc); if (u_sess->mot_cxt.txn_manager != nullptr) { if (txn_id != 0) { u_sess->mot_cxt.txn_manager->SetTransactionId(txn_id); } } else { report_pg_error(MOT_GET_ROOT_ERROR_RC()); } } return u_sess->mot_cxt.txn_manager; } extern void EnsureSafeThreadAccess(); inline List* BitmapSerialize(List* result, uint8_t* bitmap, int16_t len) { // set list type to FDW_LIST_BITMAP result = lappend(result, makeConst(INT4OID, -1, InvalidOid, 4, FDW_LIST_BITMAP, false, true)); for (int i = 0; i < len; i++) result = lappend(result, makeConst(INT1OID, -1, InvalidOid, 1, Int8GetDatum(bitmap[i]), false, true)); return result; } inline void BitmapDeSerialize(uint8_t* bitmap, int16_t len, ListCell** cell) { if (cell != nullptr && *cell != nullptr) { int type = ((Const*)lfirst(*cell))->constvalue; if (type == FDW_LIST_BITMAP) { *cell = lnext(*cell); for (int i = 0; i < len; i++) { bitmap[i] = (uint8_t)((Const*)lfirst(*cell))->constvalue; *cell = lnext(*cell); } } } } inline void CleanCursors(MOTFdwStateSt* state) { for (int i = 0; i < 2; i++) { if (state->m_cursor[i]) { state->m_cursor[i]->Invalidate(); state->m_cursor[i]->Destroy(); delete state->m_cursor[i]; state->m_cursor[i] = NULL; } } } inline void CleanQueryStatesOnError(MOT::TxnManager* txn) { if (txn != nullptr) { for (auto& itr : txn->m_queryState) { MOTFdwStateSt* state = (MOTFdwStateSt*)itr.second; if (state != nullptr) { CleanCursors(state); } } txn->m_queryState.clear(); } } MOTFdwStateSt* InitializeFdwState(void* fdwState, List** fdwExpr, uint64_t exTableID); void* SerializeFdwState(MOTFdwStateSt* state); void ReleaseFdwState(MOTFdwStateSt* state); #endif // MOT_INTERNAL_H
38.128463
120
0.60732
[ "object" ]
b20d4873fc043da14af5e63f562393b1392e3ddc
241
h
C
stdafx.h
Const-me/SimdPrecisionTest
7b009df3061e78781e9860dbf48a8cb20d7ec609
[ "MIT" ]
null
null
null
stdafx.h
Const-me/SimdPrecisionTest
7b009df3061e78781e9860dbf48a8cb20d7ec609
[ "MIT" ]
null
null
null
stdafx.h
Const-me/SimdPrecisionTest
7b009df3061e78781e9860dbf48a8cb20d7ec609
[ "MIT" ]
null
null
null
#pragma once #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <windows.h> #include <stdio.h> #include <array> #include <vector> #include <algorithm> #include <atltypes.h> #include <atlstr.h> #include <atlpath.h> #include <atlfile.h>
15.0625
27
0.738589
[ "vector" ]
b225bd3650c24c9b10a3cd7899fcf3558985ab29
841
c
C
d/avatars/cyric/test1.c
gesslar/shadowgate
97ce5d33a2275bb75c0cf6556602564b7870bc77
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/avatars/cyric/test1.c
gesslar/shadowgate
97ce5d33a2275bb75c0cf6556602564b7870bc77
[ "MIT" ]
null
null
null
d/avatars/cyric/test1.c
gesslar/shadowgate
97ce5d33a2275bb75c0cf6556602564b7870bc77
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
#include <std.h> inherit WEAPON; void create(){ ::create(); set_name("testweap"); set_id(({ "test" })); set_short("test"); set_long( @AVATAR ok1 AVATAR ); set_weight(1); set_value(100); set_type("slashing"); set_prof_type("small blades"); set_size(1); set_wc(1,6); set_large_wc(1,8); set_property("enchantment",2); set_ac(0); set_wield((:TO,"wield_func":)); set_unwield((:TO,"unwield_func":)); set_hit((:TO,"hit_func":)); } int wield_func(){ tell_room(environment(ETO),"",ETO); tell_object(ETO,""); return 1; } int unwield_func(){ tell_room(environment(ETO),"",ETO); tell_object(ETO,""); return 1; } int hit_func(object targ){ if(!objectp(targ)) return 0; if(!objectp(ETO)) return 0; if(random(1000) < ){ tell_room(environment(query_wielded()),"",({ETO,targ})); tell_object(ETO,""); tell_object(targ,""); } }
18.282609
57
0.657551
[ "object" ]
b227ad367a629b89a157f52181419767592a6870
3,528
c
C
src/z80asm/strlist.c
andydansby/z88dk-mk2
51c15f1387293809c496f5eaf7b196f8a0e9b66b
[ "ClArtistic" ]
1
2020-09-15T08:35:49.000Z
2020-09-15T08:35:49.000Z
src/z80asm/strlist.c
andydansby/z88dk-MK2
51c15f1387293809c496f5eaf7b196f8a0e9b66b
[ "ClArtistic" ]
null
null
null
src/z80asm/strlist.c
andydansby/z88dk-MK2
51c15f1387293809c496f5eaf7b196f8a0e9b66b
[ "ClArtistic" ]
null
null
null
/* ZZZZZZZZZZZZZZZZZZZZ 8888888888888 00000000000 ZZZZZZZZZZZZZZZZZZZZ 88888888888888888 0000000000000 ZZZZZ 888 888 0000 0000 ZZZZZ 88888888888888888 0000 0000 ZZZZZ 8888888888888 0000 0000 AAAAAA SSSSSSSSSSS MMMM MMMM ZZZZZ 88888888888888888 0000 0000 AAAAAAAA SSSS MMMMMM MMMMMM ZZZZZ 8888 8888 0000 0000 AAAA AAAA SSSSSSSSSSS MMMMMMMMMMMMMMM ZZZZZ 8888 8888 0000 0000 AAAAAAAAAAAA SSSSSSSSSSS MMMM MMMMM MMMM ZZZZZZZZZZZZZZZZZZZZZ 88888888888888888 0000000000000 AAAA AAAA SSSSS MMMM MMMM ZZZZZZZZZZZZZZZZZZZZZ 8888888888888 00000000000 AAAA AAAA SSSSSSSSSSS MMMM MMMM Copyright (C) Paulo Custodio, 2011-2012 List of strings (e.g. include path); strings kept in strpool.h */ /* $Header: /cvsroot/z88dk/z88dk/src/z80asm/strlist.c,v 1.1 2012/05/24 21:42:42 pauloscustodio Exp $ */ /* $Log: strlist.c,v $ /* Revision 1.1 2012/05/24 21:42:42 pauloscustodio /* CH_0011 : new string list class to hold lists of strings /* /* /* */ #include "memalloc.h" /* before any other include */ #include "strlist.h" #include "strpool.h" /*----------------------------------------------------------------------------- * Define the class *----------------------------------------------------------------------------*/ DEF_CLASS( StrList ); void StrList_init( StrList *self ) { /* force init strpool to make sure StrList is destroyed before StrPool */ strpool_init(); TAILQ_INIT( &self->head ); } void StrList_copy( StrList *self ) { StrListElem *elem, *new_elem; TAILQ_HEAD( , StrListElem ) old_head; /* save old head from original object */ memcpy( &old_head, &self->head, sizeof( old_head ) ); /* create new list and copy element by element from old_head */ TAILQ_INIT( &self->head ); TAILQ_FOREACH( elem, &old_head, entries ) { new_elem = xcalloc_struct( StrListElem ); new_elem->string = elem->string; /* point to same string at strpool */ TAILQ_INSERT_TAIL( &self->head, new_elem, entries ); } } void StrList_fini( StrList *self ) { StrListElem *elem; while ( elem = TAILQ_FIRST( &self->head ) ) { TAILQ_REMOVE( &self->head, elem, entries ); xfree( elem ); } } /*----------------------------------------------------------------------------- * append a string to the list *----------------------------------------------------------------------------*/ void StrList_append( StrList *self, char *string ) { StrListElem *elem; elem = xcalloc_struct( StrListElem ); elem->string = strpool_add( string ); TAILQ_INSERT_TAIL( &self->head, elem, entries ); } /*----------------------------------------------------------------------------- * itereate through list *----------------------------------------------------------------------------*/ void StrList_first( StrList *self, StrListElem **iter ) { *iter = NULL; } char *StrList_next( StrList *self, StrListElem **iter ) { if ( *iter == NULL ) { *iter = TAILQ_FIRST( &self->head ); /* first time */ } else { *iter = TAILQ_NEXT( *iter, entries ); /* 2nd and following */ } return *iter == NULL ? NULL : ( *iter )->string; }
33.6
114
0.518991
[ "object" ]
b22b210308c6d53061c4b827f479cb46f36aff70
1,200
h
C
Libraries/StdUtils/StdClassFactory.h
NeuroRoboticTech/AnimatLabPublicSource
c5b23f8898513582afb7891eb994a7bd40a89f08
[ "BSD-3-Clause" ]
8
2015-01-09T21:59:50.000Z
2021-04-14T14:08:47.000Z
Libraries/StdUtils/StdClassFactory.h
NeuroRoboticTech/AnimatLabPublicSource
c5b23f8898513582afb7891eb994a7bd40a89f08
[ "BSD-3-Clause" ]
null
null
null
Libraries/StdUtils/StdClassFactory.h
NeuroRoboticTech/AnimatLabPublicSource
c5b23f8898513582afb7891eb994a7bd40a89f08
[ "BSD-3-Clause" ]
2
2018-12-21T02:58:30.000Z
2020-08-12T11:44:39.000Z
/** \file StdClassFactory.h \brief Declares the standard class factory class. **/ #pragma once namespace StdUtils { /** \brief Standard class factory. \details This is a standard interface used for all class factories. To make your library able able to be loaded you need to derive a class from this and then implement the GetStdClassFactory method within your new DLL. \author dcofer \date 5/3/2011 **/ class STD_UTILS_PORT IStdClassFactory { public: IStdClassFactory(); virtual ~IStdClassFactory(); /** \brief Creates an object of the specified class and object types. \author dcofer \date 5/3/2011 \param strClassType Type of the class. \param strObjectType Type of the object. \param bThrowError true to throw error if there is a problem. \return null if it fails and bThrowError is false, else a pointer to the created object. **/ virtual CStdSerialize *CreateObject(std::string strClassType, std::string strObjectType, bool bThrowError = true) = 0; static IStdClassFactory *LoadModule(std::string strModuleName, bool bThrowError = true); }; typedef IStdClassFactory *(*GetClassFactory)(void); } //StdUtils
25.531915
120
0.724167
[ "object" ]
b22ca55703aebbd962b50f84683f5191f6583757
412
c
C
test/libccc/monad/object.c
LexouDuck/libft
af06b5b8f0ac51e1a461cbe58a7be6410c4348d5
[ "MIT" ]
6
2021-02-09T08:50:35.000Z
2021-09-15T14:29:31.000Z
test/libccc/monad/object.c
LexouDuck/libccc
73a923a484ceb1fa6eaa863a151614d1327b4af8
[ "MIT" ]
16
2021-03-13T23:13:35.000Z
2022-03-29T08:42:14.000Z
test/libccc/monad/object.c
LexouDuck/libccc
73a923a484ceb1fa6eaa863a151614d1327b4af8
[ "MIT" ]
2
2020-06-09T03:10:56.000Z
2020-11-04T12:40:04.000Z
#include "libccc/monad/object.h" #include "test.h" /* ** ************************************************************************** *| ** Test Suite Function *| ** ************************************************************************** *| */ int testsuite_monad_object(void) { print_suite_title("libccc/monad/object"); // TODO return (OK); }
18.727273
80
0.313107
[ "object" ]
b235c3de31222ea880c1f64f3280269756c0ce75
1,356
h
C
pandatool/src/lwoegg/cLwoPoints.h
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
3
2020-01-02T08:43:36.000Z
2020-07-05T08:59:02.000Z
pandatool/src/lwoegg/cLwoPoints.h
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
pandatool/src/lwoegg/cLwoPoints.h
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
1
2020-03-11T17:38:45.000Z
2020-03-11T17:38:45.000Z
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file cLwoPoints.h * @author drose * @date 2001-04-25 */ #ifndef CLWOPOINTS_H #define CLWOPOINTS_H #include "pandatoolbase.h" #include "lwoPoints.h" #include "eggVertexPool.h" #include "pointerTo.h" #include "pmap.h" class LwoToEggConverter; class LwoVertexMap; class CLwoLayer; /** * This class is a wrapper around LwoPoints and stores additional information * useful during the conversion-to-egg process. */ class CLwoPoints { public: INLINE CLwoPoints(LwoToEggConverter *converter, const LwoPoints *points, CLwoLayer *layer); void add_vmap(const LwoVertexMap *lwo_vmap); bool get_uv(const string &uv_name, int n, LPoint2 &uv) const; void make_egg(); void connect_egg(); LwoToEggConverter *_converter; CPT(LwoPoints) _points; CLwoLayer *_layer; PT(EggVertexPool) _egg_vpool; // A number of vertex maps of different types may be associated, but we only // care about some of the types here. typedef pmap<string, const LwoVertexMap *> VMap; VMap _txuv; VMap _pick; }; #include "cLwoPoints.I" #endif
22.983051
78
0.724189
[ "3d" ]
b236546f12bbf04d71b084f6b3ef003197894921
3,201
h
C
JSPatchX/JPObjcIndex/ObjcParser/objcParser.h
bang590/JSPatchX
e097558b4f1b3a32cb8720225f4d919af19e18b9
[ "MIT" ]
829
2016-04-18T05:56:16.000Z
2021-12-24T07:00:47.000Z
JSPatchX/JPObjcIndex/ObjcParser/objcParser.h
bang590/JSPatchX
e097558b4f1b3a32cb8720225f4d919af19e18b9
[ "MIT" ]
6
2016-09-29T08:04:28.000Z
2017-02-08T08:49:57.000Z
JSPatchX/JPObjcIndex/ObjcParser/objcParser.h
bang590/JSPatchX
e097558b4f1b3a32cb8720225f4d919af19e18b9
[ "MIT" ]
100
2016-04-18T06:55:14.000Z
2020-04-16T09:10:09.000Z
// // objcParser.h // JSPatchX // // Created by louis on 4/16/16. // Copyright (c) 2016年 louis. All rights reserved. // #ifndef __objcParser__ #define __objcParser__ #include <stdio.h> #include <string> #include <vector> #include "objcLex.h" using namespace std; class FileSymbol; //toplevel symbol class ImportSymbol; class InterfaceSymbol; class ProtocolSymbol; //sub level symbol class MethodSymbol; class PropertySymbol; class ArgSymbol; #define PARSER_DONE 0 #define PARSER_ERROR 1 typedef enum { ST_File, ST_Import, ST_Interface, ST_Protocol, ST_Method, ST_Property, ST_Arg, ST_Unknown, } SymbolType; class Node{ public: vector<Node*> childs; int type; int lineNum; public: Node(){ type = ST_Unknown; } virtual ~Node(){ for (int i = 0; i < childs.size(); ++i) { delete childs[i]; } childs.clear(); } template<class T> T * parseAndAdd(ObjcLex *lex){ T *n = new T(); n->lineNum = lex->lineNum; int ret = n->parse(lex); if (ret == PARSER_DONE){ childs.push_back(n); return n; } delete n; n = NULL; return n; } virtual int parse(ObjcLex *lex) = 0; protected: int checkToken(ObjcLex *lex, int ttype){ return lex->curToken().type == ttype; } int checkAndNext(ObjcLex *lex, int ttype){ if (checkToken(lex, ttype)) { lex->next(); return 1; } return 0; } }; class FileSymbol: public Node{ public: virtual int parse(ObjcLex *lex); public: vector<ImportSymbol *> imports; vector<InterfaceSymbol *> interfaces; vector<ProtocolSymbol *> protocols; }; class ImportSymbol: public Node{ public: virtual int parse(ObjcLex *lex); public: string path; int isSys; }; class InterfaceSymbol: public Node{ public: virtual int parse(ObjcLex *lex); public: string clsName; string cateName; string superClsName; int isCategory; vector<string> protocols; vector<MethodSymbol *> methods; vector<PropertySymbol *> properties; }; class ProtocolSymbol: public Node{ public: virtual int parse(ObjcLex *lex); public: string protoName; vector<string> protocols; vector<MethodSymbol *> methods; vector<PropertySymbol *> properties; }; class MethodSymbol: public Node{ public: virtual int parse(ObjcLex *lex); public: string methodName; string returnType; vector<ArgSymbol *> args; int isClassMethod; }; class PropertySymbol: public Node{ public: virtual int parse(ObjcLex *lex); public: string propertyName; vector<string> attributes; //readonly, copy, retain ... string propertyType; }; class ArgSymbol: public Node{ public: virtual int parse(ObjcLex *lex); public: string selector; //optional string argType; //optional string argName; //required }; #endif /* defined(__objcParser__) */
20.00625
68
0.595751
[ "vector" ]
b23fbf24554cd4c426c5796c4c9aa10c530534ba
785
h
C
Sources/ECS/Component.h
friendshipismagic/dash-engine
1eec827665e6396e6cd1f41c839769a92583b820
[ "Beerware" ]
null
null
null
Sources/ECS/Component.h
friendshipismagic/dash-engine
1eec827665e6396e6cd1f41c839769a92583b820
[ "Beerware" ]
null
null
null
Sources/ECS/Component.h
friendshipismagic/dash-engine
1eec827665e6396e6cd1f41c839769a92583b820
[ "Beerware" ]
null
null
null
/* * ---------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * <clement@decoodt.eu> wrote this file. As long as you retain this notice you * can do whatever you want with this stuff. If we meet some day, and you think * this stuff is worth it, you can buy me a beer in return Clement Decoodt * ---------------------------------------------------------------------------- */ #pragma once #include "ECS/Entity.h" #include <vector> namespace ECS { // /!\ This is a pure abstract class in which every component should // inherit! class Component { public: // Connect virtual void connect_entity(ECS::Entity); private: // List of connected entities std::vector<ECS::Entity> list_of_entities; }; }
28.035714
79
0.556688
[ "vector" ]
b25209fa88c42ffeeacdae81034594ecb2697fe9
837
h
C
SatteliteSimulator/Entry/CmdList.h
avlo2000/DronMovementManager
23f73a0824165e26f18717a917aeacc63853dc8f
[ "MIT" ]
2
2019-06-24T14:09:14.000Z
2019-06-24T14:09:16.000Z
SatteliteSimulator/Entry/CmdList.h
avlo2000/DronMovementManager
23f73a0824165e26f18717a917aeacc63853dc8f
[ "MIT" ]
null
null
null
SatteliteSimulator/Entry/CmdList.h
avlo2000/DronMovementManager
23f73a0824165e26f18717a917aeacc63853dc8f
[ "MIT" ]
1
2019-02-09T13:23:28.000Z
2019-02-09T13:23:28.000Z
#pragma once #include<string> #include <string> namespace simulator { struct CmdList { public: const std::string help = "help"; const std::string exit = "exit"; #pragma region Satellite commands const std::string createDefault = "add";//name of satellite as param const std::string loadSat = "add -load";//name of satellite and path to saved nn as params const std::string sats = "list";//outputs list of satallites #pragma endregion #pragma region Simulation commands const std::string simStep = "step ";//time as param const std::string simulate = "simulate "; //time as param const std::string control = "control ";//name of satellite and 3D vector of rotation speeds as params const std::string powerToWheel = "pow ";//name of satellite number of wheel and work in Jouels as params #pragma endregion }; }
29.892857
106
0.72282
[ "vector", "3d" ]
b260afdae11d3d73405ddef0360d7c55c39421c9
5,855
h
C
aws-cpp-sdk-kafkaconnect/include/aws/kafkaconnect/model/AutoScaling.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-kafkaconnect/include/aws/kafkaconnect/model/AutoScaling.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-kafkaconnect/include/aws/kafkaconnect/model/AutoScaling.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/kafkaconnect/KafkaConnect_EXPORTS.h> #include <aws/kafkaconnect/model/ScaleInPolicy.h> #include <aws/kafkaconnect/model/ScaleOutPolicy.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace KafkaConnect { namespace Model { /** * <p>Specifies how the connector scales.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/kafkaconnect-2021-09-14/AutoScaling">AWS * API Reference</a></p> */ class AWS_KAFKACONNECT_API AutoScaling { public: AutoScaling(); AutoScaling(Aws::Utils::Json::JsonView jsonValue); AutoScaling& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The maximum number of workers allocated to the connector.</p> */ inline int GetMaxWorkerCount() const{ return m_maxWorkerCount; } /** * <p>The maximum number of workers allocated to the connector.</p> */ inline bool MaxWorkerCountHasBeenSet() const { return m_maxWorkerCountHasBeenSet; } /** * <p>The maximum number of workers allocated to the connector.</p> */ inline void SetMaxWorkerCount(int value) { m_maxWorkerCountHasBeenSet = true; m_maxWorkerCount = value; } /** * <p>The maximum number of workers allocated to the connector.</p> */ inline AutoScaling& WithMaxWorkerCount(int value) { SetMaxWorkerCount(value); return *this;} /** * <p>The number of microcontroller units (MCUs) allocated to each connector * worker. The valid values are 1,2,4,8.</p> */ inline int GetMcuCount() const{ return m_mcuCount; } /** * <p>The number of microcontroller units (MCUs) allocated to each connector * worker. The valid values are 1,2,4,8.</p> */ inline bool McuCountHasBeenSet() const { return m_mcuCountHasBeenSet; } /** * <p>The number of microcontroller units (MCUs) allocated to each connector * worker. The valid values are 1,2,4,8.</p> */ inline void SetMcuCount(int value) { m_mcuCountHasBeenSet = true; m_mcuCount = value; } /** * <p>The number of microcontroller units (MCUs) allocated to each connector * worker. The valid values are 1,2,4,8.</p> */ inline AutoScaling& WithMcuCount(int value) { SetMcuCount(value); return *this;} /** * <p>The minimum number of workers allocated to the connector.</p> */ inline int GetMinWorkerCount() const{ return m_minWorkerCount; } /** * <p>The minimum number of workers allocated to the connector.</p> */ inline bool MinWorkerCountHasBeenSet() const { return m_minWorkerCountHasBeenSet; } /** * <p>The minimum number of workers allocated to the connector.</p> */ inline void SetMinWorkerCount(int value) { m_minWorkerCountHasBeenSet = true; m_minWorkerCount = value; } /** * <p>The minimum number of workers allocated to the connector.</p> */ inline AutoScaling& WithMinWorkerCount(int value) { SetMinWorkerCount(value); return *this;} /** * <p>The sacle-in policy for the connector.</p> */ inline const ScaleInPolicy& GetScaleInPolicy() const{ return m_scaleInPolicy; } /** * <p>The sacle-in policy for the connector.</p> */ inline bool ScaleInPolicyHasBeenSet() const { return m_scaleInPolicyHasBeenSet; } /** * <p>The sacle-in policy for the connector.</p> */ inline void SetScaleInPolicy(const ScaleInPolicy& value) { m_scaleInPolicyHasBeenSet = true; m_scaleInPolicy = value; } /** * <p>The sacle-in policy for the connector.</p> */ inline void SetScaleInPolicy(ScaleInPolicy&& value) { m_scaleInPolicyHasBeenSet = true; m_scaleInPolicy = std::move(value); } /** * <p>The sacle-in policy for the connector.</p> */ inline AutoScaling& WithScaleInPolicy(const ScaleInPolicy& value) { SetScaleInPolicy(value); return *this;} /** * <p>The sacle-in policy for the connector.</p> */ inline AutoScaling& WithScaleInPolicy(ScaleInPolicy&& value) { SetScaleInPolicy(std::move(value)); return *this;} /** * <p>The sacle-out policy for the connector.</p> */ inline const ScaleOutPolicy& GetScaleOutPolicy() const{ return m_scaleOutPolicy; } /** * <p>The sacle-out policy for the connector.</p> */ inline bool ScaleOutPolicyHasBeenSet() const { return m_scaleOutPolicyHasBeenSet; } /** * <p>The sacle-out policy for the connector.</p> */ inline void SetScaleOutPolicy(const ScaleOutPolicy& value) { m_scaleOutPolicyHasBeenSet = true; m_scaleOutPolicy = value; } /** * <p>The sacle-out policy for the connector.</p> */ inline void SetScaleOutPolicy(ScaleOutPolicy&& value) { m_scaleOutPolicyHasBeenSet = true; m_scaleOutPolicy = std::move(value); } /** * <p>The sacle-out policy for the connector.</p> */ inline AutoScaling& WithScaleOutPolicy(const ScaleOutPolicy& value) { SetScaleOutPolicy(value); return *this;} /** * <p>The sacle-out policy for the connector.</p> */ inline AutoScaling& WithScaleOutPolicy(ScaleOutPolicy&& value) { SetScaleOutPolicy(std::move(value)); return *this;} private: int m_maxWorkerCount; bool m_maxWorkerCountHasBeenSet; int m_mcuCount; bool m_mcuCountHasBeenSet; int m_minWorkerCount; bool m_minWorkerCountHasBeenSet; ScaleInPolicy m_scaleInPolicy; bool m_scaleInPolicyHasBeenSet; ScaleOutPolicy m_scaleOutPolicy; bool m_scaleOutPolicyHasBeenSet; }; } // namespace Model } // namespace KafkaConnect } // namespace Aws
30.815789
133
0.676857
[ "model" ]
b270aa791835b7a4a0f7665aaccb90900601b6cb
7,944
h
C
Source/Controls/ListControlPackage/GuiListControlItemArrangers.h
vczh2/GacUI
ce100ec13357bbf03ed3d2040c48d6b2b2fefd2f
[ "RSA-MD" ]
2
2018-10-17T16:00:01.000Z
2018-11-20T07:53:20.000Z
Source/Controls/ListControlPackage/GuiListControlItemArrangers.h
vczh2/GacUI
ce100ec13357bbf03ed3d2040c48d6b2b2fefd2f
[ "RSA-MD" ]
null
null
null
Source/Controls/ListControlPackage/GuiListControlItemArrangers.h
vczh2/GacUI
ce100ec13357bbf03ed3d2040c48d6b2b2fefd2f
[ "RSA-MD" ]
null
null
null
/*********************************************************************** Vczh Library++ 3.0 Developer: Zihan Chen(vczh) GacUI::Control System Interfaces: ***********************************************************************/ #ifndef VCZH_PRESENTATION_CONTROLS_GUILISTCONTROLITEMARRANGERS #define VCZH_PRESENTATION_CONTROLS_GUILISTCONTROLITEMARRANGERS #include "GuiListControls.h" namespace vl { namespace presentation { namespace controls { /*********************************************************************** Predefined ItemArranger ***********************************************************************/ namespace list { /// <summary>Ranged item arranger. This arranger implements most of the common functionality for those arrangers that display a continuing subset of item at a time.</summary> class RangedItemArrangerBase : public Object, virtual public GuiListControl::IItemArranger, public Description<RangedItemArrangerBase> { protected: using ItemStyleRecord = collections::Pair<GuiListControl::ItemStyle*, GuiSelectableButton*>; typedef collections::List<ItemStyleRecord> StyleList; GuiListControl* listControl = nullptr; GuiListControl::IItemArrangerCallback* callback = nullptr; GuiListControl::IItemProvider* itemProvider = nullptr; bool suppressOnViewChanged = false; Rect viewBounds; vint startIndex = 0; StyleList visibleStyles; protected: void InvalidateAdoptedSize(); vint CalculateAdoptedSize(vint expectedSize, vint count, vint itemSize); ItemStyleRecord CreateStyle(vint index); void DeleteStyle(ItemStyleRecord style); compositions::GuiBoundsComposition* GetStyleBounds(ItemStyleRecord style); void ClearStyles(); void OnViewChangedInternal(Rect oldBounds, Rect newBounds); virtual void RearrangeItemBounds(); virtual void BeginPlaceItem(bool forMoving, Rect newBounds, vint& newStartIndex) = 0; virtual void PlaceItem(bool forMoving, vint index, ItemStyleRecord style, Rect viewBounds, Rect& bounds, Margin& alignmentToParent) = 0; virtual bool IsItemOutOfViewBounds(vint index, ItemStyleRecord style, Rect bounds, Rect viewBounds) = 0; virtual bool EndPlaceItem(bool forMoving, Rect newBounds, vint newStartIndex) = 0; virtual void InvalidateItemSizeCache() = 0; virtual Size OnCalculateTotalSize() = 0; public: /// <summary>Create the arranger.</summary> RangedItemArrangerBase(); ~RangedItemArrangerBase(); void OnAttached(GuiListControl::IItemProvider* provider)override; void OnItemModified(vint start, vint count, vint newCount)override; void AttachListControl(GuiListControl* value)override; void DetachListControl()override; GuiListControl::IItemArrangerCallback* GetCallback()override; void SetCallback(GuiListControl::IItemArrangerCallback* value)override; Size GetTotalSize()override; GuiListControl::ItemStyle* GetVisibleStyle(vint itemIndex)override; vint GetVisibleIndex(GuiListControl::ItemStyle* style)override; void ReloadVisibleStyles()override; void OnViewChanged(Rect bounds)override; }; /// <summary>Fixed height item arranger. This arranger lists all item with the same height value. This value is the maximum height of all minimum heights of displayed items.</summary> class FixedHeightItemArranger : public RangedItemArrangerBase, public Description<FixedHeightItemArranger> { private: vint pi_width = 0; vint pim_rowHeight = 0; protected: vint rowHeight = 1; virtual vint GetWidth(); virtual vint GetYOffset(); void BeginPlaceItem(bool forMoving, Rect newBounds, vint& newStartIndex)override; void PlaceItem(bool forMoving, vint index, ItemStyleRecord style, Rect viewBounds, Rect& bounds, Margin& alignmentToParent)override; bool IsItemOutOfViewBounds(vint index, ItemStyleRecord style, Rect bounds, Rect viewBounds)override; bool EndPlaceItem(bool forMoving, Rect newBounds, vint newStartIndex)override; void InvalidateItemSizeCache()override; Size OnCalculateTotalSize()override; public: /// <summary>Create the arranger.</summary> FixedHeightItemArranger(); ~FixedHeightItemArranger(); vint FindItem(vint itemIndex, compositions::KeyDirection key)override; bool EnsureItemVisible(vint itemIndex)override; Size GetAdoptedSize(Size expectedSize)override; }; /// <summary>Fixed size multiple columns item arranger. This arranger adjust all items in multiple lines with the same size. The width is the maximum width of all minimum widths of displayed items. The same to height.</summary> class FixedSizeMultiColumnItemArranger : public RangedItemArrangerBase, public Description<FixedSizeMultiColumnItemArranger> { private: Size pim_itemSize; protected: Size itemSize{ 1,1 }; void CalculateRange(Size itemSize, Rect bounds, vint count, vint& start, vint& end); void BeginPlaceItem(bool forMoving, Rect newBounds, vint& newStartIndex)override; void PlaceItem(bool forMoving, vint index, ItemStyleRecord style, Rect viewBounds, Rect& bounds, Margin& alignmentToParent)override; bool IsItemOutOfViewBounds(vint index, ItemStyleRecord style, Rect bounds, Rect viewBounds)override; bool EndPlaceItem(bool forMoving, Rect newBounds, vint newStartIndex)override; void InvalidateItemSizeCache()override; Size OnCalculateTotalSize()override; public: /// <summary>Create the arranger.</summary> FixedSizeMultiColumnItemArranger(); ~FixedSizeMultiColumnItemArranger(); vint FindItem(vint itemIndex, compositions::KeyDirection key)override; bool EnsureItemVisible(vint itemIndex)override; Size GetAdoptedSize(Size expectedSize)override; }; /// <summary>Fixed size multiple columns item arranger. This arranger adjust all items in multiple columns with the same height. The height is the maximum width of all minimum height of displayed items. Each item will displayed using its minimum width.</summary> class FixedHeightMultiColumnItemArranger : public RangedItemArrangerBase, public Description<FixedHeightMultiColumnItemArranger> { private: vint pi_currentWidth = 0; vint pi_totalWidth = 0; vint pim_itemHeight = 0; protected: vint itemHeight; void CalculateRange(vint itemHeight, Rect bounds, vint& rows, vint& startColumn); void BeginPlaceItem(bool forMoving, Rect newBounds, vint& newStartIndex)override; void PlaceItem(bool forMoving, vint index, ItemStyleRecord style, Rect viewBounds, Rect& bounds, Margin& alignmentToParent)override; bool IsItemOutOfViewBounds(vint index, ItemStyleRecord style, Rect bounds, Rect viewBounds)override; bool EndPlaceItem(bool forMoving, Rect newBounds, vint newStartIndex)override; void InvalidateItemSizeCache()override; Size OnCalculateTotalSize()override; public: /// <summary>Create the arranger.</summary> FixedHeightMultiColumnItemArranger(); ~FixedHeightMultiColumnItemArranger(); vint FindItem(vint itemIndex, compositions::KeyDirection key)override; bool EnsureItemVisible(vint itemIndex)override; Size GetAdoptedSize(Size expectedSize)override; }; } } } } #endif
47.285714
266
0.674471
[ "object" ]
b272f743c14c7fd101438d69008ca43787d30436
5,236
h
C
dev/Gems/CryLegacy/Code/Source/CryAISystem/Navigation/MNM/OffGridLinks.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/CryLegacy/Code/Source/CryAISystem/Navigation/MNM/OffGridLinks.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/CryLegacy/Code/Source/CryAISystem/Navigation/MNM/OffGridLinks.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #ifndef CRYINCLUDE_CRYAISYSTEM_NAVIGATION_MNM_OFFGRIDLINKS_H #define CRYINCLUDE_CRYAISYSTEM_NAVIGATION_MNM_OFFGRIDLINKS_H #pragma once #include "../MNM/MNM.h" struct NavigationMesh; struct IAIPathAgent; namespace MNM { ////////////////////////////////////////////////////////////////////////// /// One of this objects is bound to every Navigation Mesh /// Keeps track of off-mesh links per Tile /// Each tile can have up to 1024 Triangle links (limited by the Tile link structure within the mesh) /// /// Some triangles in the NavigationMesh will have a special link with an index /// which allows to access this off-mesh data struct OffMeshNavigation { private: ////////////////////////////////////////////////////////////////////////// //Note: This structure could hold any data for the link // For the time being it will store the necessary SO info to interface with the current SO system struct TriangleLink { TriangleID startTriangleID; TriangleID endTriangleID; OffMeshLinkID linkID; }; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// struct TileLinks { TileLinks() : triangleLinks(NULL) , triangleLinkCount(0) { } ~TileLinks() { SAFE_DELETE_ARRAY(triangleLinks); } void CopyLinks(TriangleLink* links, uint16 linkCount); TriangleLink* triangleLinks; uint16 triangleLinkCount; }; public: struct QueryLinksResult { QueryLinksResult(const TriangleLink* _firstLink, uint16 _linkCount) : pFirstLink(_firstLink) , currentLink(0) , linkCount(_linkCount) { } WayTriangleData GetNextTriangle() const { if (currentLink < linkCount) { currentLink++; return WayTriangleData(pFirstLink[currentLink - 1].endTriangleID, pFirstLink[currentLink - 1].linkID); } return WayTriangleData(0, 0); } private: const TriangleLink* pFirstLink; mutable uint16 currentLink; uint16 linkCount; }; #if DEBUG_MNM_ENABLED struct ProfileMemoryStats { ProfileMemoryStats() : offMeshTileLinksMemory(0) , smartObjectInfoMemory(0) , totalSize(0) { } size_t offMeshTileLinksMemory; size_t smartObjectInfoMemory; size_t totalSize; }; #endif OffMeshNavigation(); OffMeshLinkPtr AddLink(NavigationMesh& navigationMesh, const TriangleID startTriangleID, const TriangleID endTriangleID, OffMeshLink& linkData, OffMeshLinkID& linkID, bool refData); void RemoveLink(NavigationMesh& navigationMesh, const TriangleID boundTriangleID, const OffMeshLinkID linkID); void InvalidateLinks(const TileID tileID); QueryLinksResult GetLinksForTriangle(const TriangleID triangleID, const uint16 index) const; const OffMeshLink* GetObjectLinkInfo(const OffMeshLinkID linkID) const; OffMeshLink* GetObjectLinkInfo(const OffMeshLinkID linkID); QueryLinksResult GetLookupsForTriangle(const TriangleID triangleID) const; bool CanUseLink(IEntity* pRequester, const OffMeshLinkID linkID, float* costMultiplier, float pathSharingPenalty = 0) const; #if DEBUG_MNM_ENABLED ProfileMemoryStats GetMemoryStats(ICrySizer* pSizer) const; #endif private: void AddLookupLink(const TriangleID startTriangleID, const TriangleID endTriangleID, const OffMeshLinkID linkID); void RemoveLookupLink(const TriangleID boundTriangleID, const OffMeshLinkID linkID); bool RemoveLinkData(const OffMeshLinkID linkID); struct STileLinks { TileLinks links; TileLinks lookups; }; typedef std__hash_map<TileID, STileLinks> TTilesLinks; typedef std__hash_map<OffMeshLinkID, OffMeshLinkPtr> TOffMeshObjectLinks; TTilesLinks m_tilesLinks; static OffMeshLinkID m_linkIDGenerator; TOffMeshObjectLinks m_offmeshLinks; }; } #endif // CRYINCLUDE_CRYAISYSTEM_NAVIGATION_MNM_OFFGRIDLINKS_H
34.906667
189
0.607143
[ "mesh" ]
b2730b8bfc9c02230b56464d42c081df918848e4
82,114
c
C
src/cmd/doc.c
embedthis/ejscript
ccf3be9022c584bd12ce412b9902645fb49b95cc
[ "Apache-2.0", "Zlib", "BSD-2-Clause", "MIT" ]
32
2015-07-11T15:09:33.000Z
2022-02-08T09:33:25.000Z
src/cmd/doc.c
embedthis/ejscript
ccf3be9022c584bd12ce412b9902645fb49b95cc
[ "Apache-2.0", "Zlib", "BSD-2-Clause", "MIT" ]
14
2015-06-16T18:07:10.000Z
2020-11-27T01:43:54.000Z
src/cmd/doc.c
embedthis/ejscript
ccf3be9022c584bd12ce412b9902645fb49b95cc
[ "Apache-2.0", "Zlib", "BSD-2-Clause", "MIT" ]
10
2016-07-18T06:00:06.000Z
2021-02-08T14:06:26.000Z
/** doc.c - Documentation generator Copyright (c) All Rights Reserved. See details at the end of the file. */ /* Supported documentation keywords and format. The element "one liner" is the first sentance. Rest of description can continue from here and can include embedded html. @param argName Description (Up to next @, case matters on argName) @default argName DefaultValue (Up to next @, case matters on argName) @return Sentence (Can use return or returns. If sentance starts with lower case, then start sentance with "Call returns". @event eventName Description (Up to next @, case matters on eventName) @option argName Description (Up to next @, case matters on argName) @throws ExceptionType Explanation (Up to next @) @see Keyword keyword ... (Case matters) @example Description (Up to next @) @stability kind (prototype | evolving | stable | mature | deprecated] @deprecated version Same as @stability deprecated @requires ECMA (Emit: configuration requires --ejs-ecma) @spec (ecma-262, ecma-357, ejs-11) @hide (Hides this entry) */ /********************************** Includes **********************************/ #include "ejsmod.h" /*********************************** Locals ***********************************/ /* Structures used when sorting lists */ typedef struct FunRec { EjsName qname; EjsFunction *fun; EjsObj *obj; int slotNum; EjsObj *owner; EjsName ownerName; EjsTrait *trait; } FunRec; typedef struct ClassRec { EjsName qname; EjsBlock *block; int slotNum; EjsTrait *trait; } ClassRec; typedef struct PropRec { EjsName qname; EjsObj *obj; int slotNum; EjsTrait *trait; EjsObj *vp; } PropRec; typedef struct List { char *name; MprList *list; } List; static Ejs *ejs; /**************************** Forward Declarations ****************************/ static void addUniqueItem(MprList *list, cchar *item); static void addUniqueClass(MprList *list, ClassRec *item); static MprList *buildClassList(EjsMod *mp, cchar *namespace); static void buildMethodList(EjsMod *mp, MprList *methods, EjsObj *obj, EjsObj *owner, EjsName ownerName); static void buildPropertyList(EjsMod *mp, MprList *list, EjsAny *obj, int numInherited); static int compareClasses(ClassRec **c1, ClassRec **c2); static int compareFunctions(FunRec **f1, FunRec **f2); static int compareProperties(PropRec **p1, PropRec **p2); static int compareStrings(EjsString **q1, EjsString **q2); static int compareNames(char **q1, char **q2); static EjsDoc *crackDoc(EjsMod *mp, EjsDoc *doc, EjsName qname); static MprFile *createFile(EjsMod *mp, char *name); static MprKeyValue *createKeyPair(wchar *key, wchar *value); static cchar *demangle(Ejs *ejs, EjsString *name); static void fixupDoc(Ejs *ejs, EjsDoc *doc); static char *fmtAccessors(int attributes); static char *fmtAttributes(EjsAny *vp, int attributes, int klass); static char *fmtClassUrl(Ejs *ejs, EjsName qname); static char *fmtDeclaration(Ejs *ejs, EjsName qname); static char *fmtNamespace(Ejs *ejs, EjsName qname); static char *fmtSpace(Ejs *ejs, EjsName qname); static char *fmtType(Ejs *ejs, EjsName qname); static char *fmtTypeReference(Ejs *ejs, EjsName qname); static EjsString *fmtModule(Ejs *ejs, EjsString *name); static wchar *formatExample(Ejs *ejs, EjsString *example); static int generateMethodTable(EjsMod *mp, MprList *methods, EjsObj *obj, int instanceMethods); static void generateClassPage(EjsMod *mp, EjsObj *obj, EjsName name, EjsTrait *trait, EjsDoc *doc); static void generateClassPages(EjsMod *mp); static void generateClassPageHeader(EjsMod *mp, EjsObj *obj, EjsName name, EjsTrait *trait, EjsDoc *doc); static int generateClassPropertyTableEntries(EjsMod *mp, EjsObj *obj, MprList *properties); static void generateClassList(EjsMod *mp, cchar *namespace); static void generateContentFooter(EjsMod *mp); static void generateContentHeader(EjsMod *mp, cchar *fmt, ... ); static void generateHomeFrameset(EjsMod *mp); static void generateHomeNavigation(EjsMod *mp) ; static void generateHomePages(EjsMod *mp); static void generateHomeTitle(EjsMod *mp); static void generateHtmlFooter(EjsMod *mp); static void generateHtmlHeader(EjsMod *mp, cchar *script, cchar *title, ... ); static void generateImages(EjsMod *mp); static void generateOverview(EjsMod *mp); static void generateMethod(EjsMod *mp, FunRec *fp); static void generateMethodDetail(EjsMod *mp, MprList *methods); static void generateNamespace(EjsMod *mp, cchar *namespace); static void generateNamespaceClassTable(EjsMod *mp, cchar *namespace); static int generateNamespaceClassTableEntries(EjsMod *mp, cchar *namespace); static void generateNamespaceList(EjsMod *mp); static void generatePropertyTable(EjsMod *mp, EjsObj *obj); static cchar *getDefault(EjsDoc *doc, cchar *key); static EjsDoc *getDoc(Ejs *ejs, cchar *tag, void *block, int slotNum); static EjsDoc *getDuplicateDoc(Ejs *ejs, wchar *duplicate); static void getKeyValue(wchar *str, wchar **key, wchar **value); static char *getFilename(cchar *name); static int getPropertyCount(Ejs *ejs, EjsObj *obj); static bool match(wchar *last, cchar *key); static void prepDocStrings(EjsMod *mp, EjsObj *obj, EjsName name, EjsTrait *trait, EjsDoc *doc); static void out(EjsMod *mp, char *fmt, ...); static wchar *skipAtWord(wchar *str); /*********************************** Code *************************************/ int emCreateDoc(EjsMod *mp) { ejs = mp->ejs; if (ejs->doc == 0) { ejs->doc = mprCreateHash(EJS_DOC_HASH_SIZE, 0); if (ejs->doc == 0) { return MPR_ERR_MEMORY; } } generateImages(mp); generateClassPages(mp); generateHomePages(mp); return 0; } static void generateImages(EjsMod *mp) { DocFile *df; MprFile *file; char *path; for (df = docFiles; df->path; df++) { path = mprJoinPath(mp->docDir, df->path); mprMakeDir(mprGetPathDir(path), 0775, -1, -1, 1); file = mprOpenFile(path, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644); if (file == 0) { mprLog("ejs doc", 0, "Cannot create %s", path); mp->errorCount++; return; } if (mprWriteFile(file, df->data, df->size) != df->size) { mprLog("ejs doc", 0, "Cannot write to buffer"); mp->errorCount++; return; } mprCloseFile(file); } } static void generateHomePages(EjsMod *mp) { generateHomeFrameset(mp); generateHomeTitle(mp); generateHomeNavigation(mp); generateNamespaceList(mp); generateOverview(mp); } static void generateHomeFrameset(EjsMod *mp) { cchar *script; mprCloseFile(mp->file); mp->file = createFile(mp, "index.html"); if (mp->file == 0) { return; } script = "function loaded() { content.location.href = '__overview-page.html'; }"; generateHtmlHeader(mp, script, "Home"); out(mp, "<frameset rows='90,*' border='0' onload='loaded()'>\n"); out(mp, " <frame src='title.html' name='title' scrolling='no' frameborder='0'>\n"); out(mp, " <frameset cols='200,*' border='2' framespacing='0'>\n"); out(mp, " <frame src='__navigation-left.html' name='navigation' scrolling='auto' frameborder='1'>\n"); out(mp, " <frame src='__overview-page.html' name='content' scrolling='auto' frameborder='1'>\n"); out(mp, " </frameset>\n"); out(mp, " <noframes><body><p>Please use a frames capable client to view this documentation.</p></body></noframes>"); out(mp, "</frameset>\n"); out(mp, "</html>\n"); mprCloseFile(mp->file); mp->file = 0; } static void generateHomeTitle(EjsMod *mp) { mprCloseFile(mp->file); mp->file = createFile(mp, "title.html"); if (mp->file == 0) { return; } generateHtmlHeader(mp, NULL, "title"); out(mp, "<body>\n" "<div class=\"body\">\n" " <div class=\"top\">\n" " <map name=\"home\" id=\"home\">\n" " <area coords=\"5,15,200,150\" href=\"index.html\" alt=\"doc\"/>\n" " </map>\n" " <div class=\"version\">%s %s</div>\n" " <div class=\"menu\">\n" " <a href=\"https://embedthis.com/ejs/\" target=\"_top\">Ejscript Home</a>\n" " &gt; <a href=\"index.html\" class=\"menu\" target=\"_top\">Documentation Home</a>\n" " </div>\n" " <div class=\"search\">\n" " <form class=\"smallText\" action=\"search.php\" method=\"post\" name=\"searchForm\" id=\"searchForm\"></form>&nbsp;\n" " <input class=\"smallText\" type=\"text\" name=\"search\" align=\"right\" id=\"searchInput\" size=\"15\" \n" " maxlength=\"50\" value=\"Search\"/>\n" " </div>\n" "</div>\n", ME_TITLE, ME_VERSION); generateHtmlFooter(mp); mprCloseFile(mp->file); mp->file = 0; } static void generateHomeNavigation(EjsMod *mp) { mprCloseFile(mp->file); mp->file = createFile(mp, "__navigation-left.html"); if (mp->file == 0) { return; } generateHtmlHeader(mp, NULL, "Navigation"); out(mp, "<frameset rows='34%%,*' border='1' framespacing='1'>\n"); out(mp, " <frame src='__all-namespaces.html' name='namespaces' scrolling='yes' />\n"); out(mp, " <frame src='__all-classes.html' name='classes' scrolling='yes' />\n"); out(mp, " <noframes><body><p>Please use a frames capable client to view this documentation.</p></body></noframes>"); out(mp, "</frameset>\n"); out(mp, "</html>\n"); mprCloseFile(mp->file); mp->file = 0; } static void generateNamespaceList(EjsMod *mp) { Ejs *ejs; EjsType *type; EjsTrait *trait; EjsName qname; EjsDoc *doc; MprList *namespaces; cchar *namespace; int count, slotNum, next; ejs = mp->ejs; mp->file = createFile(mp, "__all-namespaces.html"); if (mp->file == 0) { mp->errorCount++; return; } generateHtmlHeader(mp, NULL, "Namespaces"); out(mp, "<body>\n"); out(mp, "<div class='navigation'>\n"); out(mp, "<h3>Namespaces</h3>\n"); out(mp, "<table class='navigation' title='namespaces'>\n"); /* Build a sorted list of namespaces used by classes */ namespaces = mprCreateList(0, 0); count = ejsGetLength(ejs, ejs->global); for (slotNum = 0; slotNum < count; slotNum++) { trait = ejsGetPropertyTraits(ejs, ejs->global, slotNum); if (trait == 0) { continue; } type = ejsGetProperty(ejs, ejs->global, slotNum); qname = ejsGetPropertyName(ejs, ejs->global, slotNum); if (type == 0 || !ejsIsType(ejs, type) || qname.name == 0 || ejsStartsWithAsc(ejs, qname.space, "internal-") >= 0) { continue; } doc = getDoc(ejs, "class", ejs->global, slotNum); if (doc && !doc->hide) { addUniqueItem(namespaces, fmtNamespace(ejs, qname)); } } mprSortList(namespaces, (MprSortProc) compareNames, 0); out(mp, "<tr><td><a href='__all-classes.html' target='classes'>All Namespaces</a></td></tr>\n"); for (next = 0; (namespace = (cchar*) mprGetNextItem(namespaces, &next)) != 0; ) { out(mp, "<tr><td><a href='%s-classes.html' target='classes'>%s</a></td></tr>\n", namespace, namespace); } out(mp, "</table>\n"); out(mp, "</div>\n"); generateHtmlFooter(mp); mprCloseFile(mp->file); mp->file = 0; /* Generate namespace overviews and class list files for each namespace */ for (next = 0; (namespace = (cchar*) mprGetNextItem(namespaces, &next)) != 0; ) { generateNamespace(mp, namespace); } generateNamespace(mp, "__all"); } static void generateNamespace(EjsMod *mp, cchar *namespace) { char *path; path = sjoin(namespace, ".html", NULL); mp->file = createFile(mp, path); if (mp->file == 0) { mp->errorCount++; return; } if (strcmp(namespace, "__all") == 0) { generateContentHeader(mp, "All Namespaces"); generateNamespaceClassTable(mp, namespace); } else { generateContentHeader(mp, "Namespace %s", namespace); generateNamespaceClassTable(mp, namespace); } generateContentFooter(mp); mprCloseFile(mp->file); mp->file = 0; /* Generate an overview page */ generateClassList(mp, namespace); } static void generateNamespaceClassTable(EjsMod *mp, cchar *namespace) { int count; out(mp, "<a name='Classes'></a>\n"); if (strcmp(namespace, "__all") == 0) { out(mp, "<h2 class='classSection'>All Classes</h2>\n"); } else { out(mp, "<h2 class='classSection'>%s Classes</h2>\n", namespace); } out(mp, "<table class='itemTable' title='classes'>\n"); out(mp, " <tr><th>Class</th><th width='95%%'>Description</th></tr>\n"); count = generateNamespaceClassTableEntries(mp, namespace); if (count == 0) { out(mp, " <tr><td colspan='4'>No properties defined</td></tr>"); } out(mp, "</table>\n\n"); } /* Table of classes in the namespace overview page */ static int generateNamespaceClassTableEntries(EjsMod *mp, cchar *namespace) { Ejs *ejs; EjsName qname; EjsDoc *doc; ClassRec *crec; MprList *classes; char *fmtName; int next; ejs = mp->ejs; classes = buildClassList(mp, namespace); for (next = 0; (crec = (ClassRec*) mprGetNextItem(classes, &next)) != 0; ) { qname = crec->qname; fmtName = fmtType(ejs, crec->qname); out(mp, " <tr><td><a href='%s' target='content'>%@</a></td>", getFilename(fmtName), qname.name); if (crec->block == ejs->global && mp->firstGlobal == ejsGetLength(ejs, ejs->global)) { continue; } doc = getDoc(ejs, "class", crec->block ? crec->block : ejs->global, crec->slotNum); if (doc && !doc->hide) { out(mp, "<td>%w</td></tr>\n", doc->brief); } else { out(mp, "<td>&nbsp;</td></tr>\n"); } } return mprGetListLength(classes); } static MprList *buildClassList(EjsMod *mp, cchar *namespace) { Ejs *ejs; EjsType *type; EjsTrait *trait; EjsDoc *doc; EjsName qname; ClassRec *crec; MprList *classes; int count, slotNum; ejs = mp->ejs; /* Build a sorted list of classes */ classes = mprCreateList(0, 0); count = ejsGetLength(ejs, ejs->global); for (slotNum = 0; slotNum < count; slotNum++) { trait = ejsGetPropertyTraits(ejs, ejs->global, slotNum); if (trait == 0) { continue; } doc = getDoc(ejs, "class", ejs->global, slotNum); if (doc == 0 || doc->hide) { continue; } type = ejsGetProperty(ejs, ejs->global, slotNum); qname = ejsGetPropertyName(ejs, ejs->global, slotNum); if (type == 0 || !ejsIsType(ejs, type) || qname.name == 0) { continue; } if (strcmp(namespace, "__all") != 0 && strcmp(namespace, fmtNamespace(ejs, qname)) != 0) { continue; } /* Suppress the core language types (should not appear as classes) */ if (ejsCompareAsc(ejs, qname.space, EJS_EJS_NAMESPACE) == 0) { if (ejsCompareAsc(ejs, qname.name, "int") == 0 || ejsCompareAsc(ejs, qname.name, "long") == 0 || ejsCompareAsc(ejs, qname.name, "decimal") == 0 || ejsCompareAsc(ejs, qname.name, "boolean") == 0 || ejsCompareAsc(ejs, qname.name, "double") == 0 || ejsCompareAsc(ejs, qname.name, "string") == 0) { continue; } } /* Other fixups */ if (ejsStartsWithAsc(ejs, qname.space, "internal") >= 0|| ejsCompareAsc(ejs, qname.space, "private") == 0) { continue; } crec = mprAlloc(sizeof(ClassRec)); crec->qname = qname; crec->trait = trait; crec->block = ejs->global; crec->slotNum = slotNum; addUniqueClass(classes, crec); } /* Add a special type "Global" */ if (strcmp(namespace, "__all") == 0) { if (mp->firstGlobal < ejsGetLength(ejs, ejs->global)) { crec = mprAlloc(sizeof(ClassRec)); crec->qname = N(EJS_EJS_NAMESPACE, EJS_GLOBAL); crec->block = ejs->global; crec->slotNum = ejsLookupProperty(ejs, ejs->global, crec->qname); addUniqueClass(classes, crec); } } mprSortList(classes, (MprSortProc) compareClasses, 0); return classes; } static void generateClassList(EjsMod *mp, cchar *namespace) { Ejs *ejs; MprList *classes; ClassRec *crec; cchar *className, *fmtName; char *path, script[ME_MAX_PATH], *cp; int next; ejs = mp->ejs; path = sjoin(namespace, "-classes.html", NULL); mp->file = createFile(mp, path); if (mp->file == 0) { mp->errorCount++; return; } /* Create the header and auto-load a namespace overview. We do this here because the class list is loaded when the user selects a namespace. */ fmt(script, sizeof(script), "parent.parent.content.location = \'%s.html\';", namespace); generateHtmlHeader(mp, script, "%s Class List", namespace); out(mp, "<body>\n"); out(mp, "<div class='navigation'>\n"); if (strcmp(namespace, "__all") == 0) { out(mp, "<h3>All Classes</h3>\n"); } else { out(mp, "<h3>%s Classes</h3>\n", namespace); } out(mp, "<table class='navigation' title='classList'>\n"); classes = buildClassList(mp, namespace); for (next = 0; (crec = (ClassRec*) mprGetNextItem(classes, &next)) != 0; ) { /* Strip namespace portion */ fmtName = fmtType(ejs, crec->qname); if ((cp = strrchr(fmtName, '.')) != 0) { className = ++cp; } else { className = fmtName; } if ((cp = strrchr(className, ':')) != 0) { className = ++cp; } out(mp, "<tr><td><a href='%s' target='content'>%s</a></td></tr>\n", getFilename(fmtName), className); } out(mp, "</table>\n"); out(mp, "</div>\n"); out(mp, "&nbsp;<br/>"); generateHtmlFooter(mp); mprCloseFile(mp->file); mp->file = 0; } static void generateOverview(EjsMod *mp) { mprCloseFile(mp->file); mp->file = createFile(mp, "__overview-page.html"); if (mp->file == 0) { mp->errorCount++; return; } generateContentHeader(mp, "Overview"); out(mp, "<h1>%s %s</h1>", ME_TITLE, ME_VERSION); out(mp, "<p>Embedthis Ejscript is an implementation of the Javascript (ECMA 262) language.</p>"); out(mp, "<p>See <a href='https://embedthis.com/ejs/' target='new'>https://embedthis.com/ejs/</a> for " "product details and downloads.</p>"); out(mp, "<h2>Documentation Conventions</h2>"); out(mp, "<p>APIs are grouped into Namespaces for logical ordering. Within each namespace, classes, methods " "and properties are defined. For each method parameters, events and options are described.</p>"); out(mp, "<h4>Default Values</h4>"); out(mp, "<p>Method parameters can take default values if an actual parameter is not provided when calling the API. " "The default value is listed in the method signature in the form \"name: Type = defaultValue\". The default " "value is also listed in the <em>Parameters</em> section.</p>"); generateContentFooter(mp); mprCloseFile(mp->file); mp->file = 0; } static void generateHtmlHeader(EjsMod *mp, cchar *script, cchar *fmt, ... ) { char *title; va_list args; va_start(args, fmt); title = sfmtv(fmt, args); va_end(args); /* Header + Style sheet */ out(mp, "<!DOCTYPE html>\n"); out(mp, "<html>\n"); out(mp, "<head>\n <title>%s</title>\n\n", title); out(mp, " <link rel=\"stylesheet\" type=\"text/css\" href=\"doc.css\" />\n"); if (script) { out(mp, " <script type=\"text/javascript\">\n %s\n </script>\n", script); } out(mp, "</head>\n\n"); } static void generateContentHeader(EjsMod *mp, cchar *fmt, ... ) { va_list args; char *title; va_start(args, fmt); title = sfmtv(fmt, args); va_end(args); generateHtmlHeader(mp, NULL, title); out(mp, "<body>\n<div class='body'>\n\n"); out(mp, "<div class=\"content\">\n\n"); } static void generateTerms(EjsMod *mp) { out(mp, "<div class=\"terms\">\n" " <p class=\"terms\">\n" " <a href=\"https://embedthis.com/\">" " Embedthis Software LLC, 2003-2014. All rights reserved. " "Embedthis is a trademark of Embedthis Software LLC.</a>\n" " </p>\n" "</div>"); } static void generateHtmlFooter(EjsMod *mp) { out(mp, "</body>\n</html>\n"); } static void generateContentFooter(EjsMod *mp) { generateTerms(mp); out(mp, "</div>\n"); out(mp, "</div>\n"); generateHtmlFooter(mp); } static MprFile *createFile(EjsMod *mp, char *name) { MprFile *file; char *path; path = mp->path = mprJoinPath(mp->docDir, name); file = mprOpenFile(path, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (file == 0) { mprLog("ejs doc", 0, "Cannot open %s", path); mp->errorCount++; return 0; } return file; } /* Generate one page per class/type */ static void generateClassPages(EjsMod *mp) { Ejs *ejs; EjsType *type; EjsTrait *trait; EjsDoc *doc; EjsName qname; char key[32]; int count, slotNum; ejs = mp->ejs; count = ejsGetLength(ejs, ejs->global); for (slotNum = mp->firstGlobal; slotNum < count; slotNum++) { type = ejsGetProperty(ejs, ejs->global, slotNum); qname = ejsGetPropertyName(ejs, ejs->global, slotNum); if (type == 0 || !ejsIsType(ejs, type) || qname.name == 0 || ejsStartsWithAsc(ejs, qname.space, "internal-") >= 0) { continue; } /* Setup the output path, but create the file on demand when output is done */ mprCloseFile(mp->file); mp->file = 0; mp->path = mprJoinPath(mp->docDir, getFilename(fmtType(ejs, type->qname))); if (mp->path == 0) { return; } trait = ejsGetPropertyTraits(ejs, ejs->global, slotNum); doc = getDoc(ejs, "class", ejs->global, slotNum); if (doc && !doc->hide) { generateClassPage(mp, (EjsObj*) type, qname, trait, doc); } mprCloseFile(mp->file); mp->file = 0; } /* Finally do one page specially for "global" TODO - Functionalize */ trait = mprAlloc(sizeof(EjsTrait)); doc = mprAlloc(sizeof(EjsDoc)); doc->docString = ejsCreateStringFromAsc(ejs, "Global object containing all global functions and variables."); doc->returns = doc->example = doc->description = NULL; doc->trait = trait; fmt(key, sizeof(key), "%Lx %d", PTOL(0), 0); mprAddKey(ejs->doc, key, doc); slotNum = ejsGetLength(ejs, ejs->global); qname = N(EJS_EJS_NAMESPACE, EJS_GLOBAL); mp->file = createFile(mp, getFilename(fmtType(ejs, qname))); if (mp->file == 0) { return; } generateClassPage(mp, ejs->global, qname, trait, doc); mprCloseFile(mp->file); mp->file = 0; } static void generateClassPage(EjsMod *mp, EjsObj *obj, EjsName name, EjsTrait *trait, EjsDoc *doc) { MprList *methods; int count; prepDocStrings(mp, obj, name, trait, doc); if (doc->hide) { return; } generateClassPageHeader(mp, obj, name, trait, doc); generatePropertyTable(mp, obj); methods = mprCreateList(0, 0); buildMethodList(mp, methods, obj, obj, name); if (ejsIsType(ejs, obj)) { buildMethodList(mp, methods, (EjsObj*) ((EjsType*) obj)->prototype, obj, name); } count = generateMethodTable(mp, methods, obj, 0); count += generateMethodTable(mp, methods, obj, 1); if (count > 0) { generateMethodDetail(mp, methods); } generateContentFooter(mp); } static void prepDocStrings(EjsMod *mp, EjsObj *obj, EjsName qname, EjsTrait *typeTrait, EjsDoc *doc) { Ejs *ejs; EjsType *type; EjsTrait *trait; EjsPot *prototype; EjsName pname; EjsDoc *dp; char *combined; int slotNum, numProp, numInherited; ejs = mp->ejs; if (doc) { crackDoc(mp, doc, qname); } type = ejsIsType(ejs, obj) ? (EjsType*) obj : 0; if (type && type->hasConstructor) { slotNum = ejsLookupProperty(ejs, ejs->global, type->qname); dp = getDoc(ejs, "fun", ejs->global, slotNum); if (dp) { crackDoc(mp, dp, type->qname); } } /* Loop over all the static properties */ numProp = ejsGetLength(ejs, obj); for (slotNum = 0; slotNum < numProp; slotNum++) { trait = ejsGetPropertyTraits(ejs, obj, slotNum); if (trait == 0) { continue; } dp = getDoc(ejs, NULL, obj, slotNum); if (dp) { pname = ejsGetPropertyName(ejs, obj, slotNum); combined = sfmt("%@.%@", qname.name, pname.name); crackDoc(mp, dp, EN(combined)); } } /* Loop over all the instance properties */ if (type) { prototype = type->prototype; if (prototype) { numInherited = type->numInherited; if (ejsGetLength(ejs, prototype) > 0) { for (slotNum = numInherited; slotNum < prototype->numProp; slotNum++) { trait = ejsGetPropertyTraits(ejs, prototype, slotNum); if (trait == 0) { continue; } doc = getDoc(ejs, NULL, prototype, slotNum); if (doc) { pname = ejsGetPropertyName(ejs, (EjsObj*) prototype, slotNum); crackDoc(mp, doc, qname); } } } } } } static void generateClassPageHeader(EjsMod *mp, EjsObj *obj, EjsName qname, EjsTrait *trait, EjsDoc *doc) { Ejs *ejs; EjsType *t, *type; EjsString *modName; cchar *see; int next, count; ejs = mp->ejs; assert(ejsIsBlock(ejs, obj)); if (!ejsIsType(ejs, obj)) { generateContentHeader(mp, "Global Functions and Variables"); out(mp, "<a name='top'></a>\n"); out(mp, "<h1 class='className'>Global Functions and Variables</h1>\n"); } else { generateContentHeader(mp, "Class %@", qname.name); out(mp, "<a name='top'></a>\n"); out(mp, "<h1 class='className'>%@</h1>\n", qname.name); } out(mp, "<div class='classBlock'>\n"); if (ejsIsType(ejs, obj)) { type = (EjsType*) obj; out(mp, "<table class='classHead' title='%@'>\n", qname.name); if (type && type->module) { modName = fmtModule(ejs, type->module->name); out(mp, " <tr><td><strong>Module</strong></td><td>%@</td></tr>\n", modName); } out(mp, " <tr><td><strong>Definition</strong></td><td>%s class %@</td></tr>\n", fmtAttributes(obj, trait->attributes, 1), qname.name); if (type && type->baseType) { out(mp, " <tr><td><strong>Inheritance</strong></td><td>%@", qname.name); for (t = type->baseType; t; t = t->baseType) { out(mp, " <img src='images/inherit.gif' alt='inherit'/> %s", fmtTypeReference(ejs, t->qname)); } } if (doc) { if (doc->requires) { out(mp, "<tr><td><strong>Requires</strong></td><td>configure --ejs-%s</td></tr>\n", doc->requires); } if (doc->spec) { out(mp, "<tr><td><strong>Specified</strong></td><td>%s</td></tr>\n", doc->spec); } if (doc->stability) { out(mp, "<tr><td><strong>Stability</strong></td><td>%s</td></tr>\n", doc->stability); } if (doc->example) { out(mp, "<tr><td><strong>Example</strong></td><td><pre>%s</pre></td></tr>\n", doc->example); } } out(mp, " </td></tr>\n"); out(mp, "</table>\n\n"); } if (doc) { out(mp, "<p class='classBrief'>%s</p>\n\n", doc->brief); if (doc->description) { out(mp, "<p class='classDescription'>%s</p>\n\n", doc->description); } count = mprGetListLength(doc->see); if (count > 0) { out(mp, "<h3>See Also</h3><p class='detail'>\n"); for (next = 0; (see = mprGetNextItem(doc->see, &next)) != 0; ) { out(mp, "<a href='%s'>%s</a>%s\n", getFilename(see), see, (count == next) ? "" : ", "); } out(mp, "</p>\n"); } } out(mp, "</div>\n\n\n"); out(mp, "<hr />\n"); } static int getPropertyCount(Ejs *ejs, EjsObj *obj) { EjsObj *vp; EjsPot *prototype; EjsTrait *trait; EjsType *type; int limit, count, slotNum; count = 0; limit = ejsGetLength(ejs, obj); for (slotNum = 0; slotNum < limit; slotNum++) { vp = ejsGetProperty(ejs, obj, slotNum); if (vp) { trait = ejsGetPropertyTraits(ejs, obj, slotNum); if (trait && trait->attributes & (EJS_TRAIT_GETTER | EJS_TRAIT_SETTER)) { count++; } else if (!ejsIsFunction(ejs, vp)) { count++; } } } if (ejsIsType(ejs, obj)) { type = (EjsType*) obj; if (type->prototype) { prototype = type->prototype; limit = ejsGetLength(ejs, prototype); for (slotNum = 0; slotNum < limit; slotNum++) { vp = ejsGetProperty(ejs, prototype, slotNum); if (vp && !ejsIsFunction(ejs, vp)) { count++; } } } } return count; } static void generatePropertyTable(EjsMod *mp, EjsObj *obj) { Ejs *ejs; EjsType *type; MprList *list; int count; ejs = mp->ejs; list = mprCreateList(0, 0); buildPropertyList(mp, list, obj, 0); type = 0; if (ejsIsType(ejs, obj)) { type = (EjsType*) obj; if (type->prototype) { buildPropertyList(mp, list, type->prototype, type->numInherited); } } mprSortList(list, (MprSortProc) compareProperties, 0); out(mp, "<a name='Properties'></a>\n"); out(mp, "<h2 class='classSection'>Properties</h2>\n"); if (mprGetListLength(list) > 0) { out(mp, "<table class='itemTable' title='properties'>\n"); out(mp, " <tr><th>Qualifiers</th><th>Property</th><th>Type</th><th width='95%%'>Description</th></tr>\n"); count = generateClassPropertyTableEntries(mp, obj, list); out(mp, "</table>\n\n"); } else { out(mp, " <p>(No own properties defined)</p>"); } if (type && type->baseType) { count = getPropertyCount(ejs, (EjsObj*) type->baseType); if (count > 0) { out(mp, "<p class='inheritedLink'><a href='%s#Properties'><i>Inherited Properties</i></a></p>\n\n", fmtClassUrl(ejs, type->baseType->qname)); } } out(mp, "<hr />\n"); } /* Generate the entries for class properties. Will be called once for static properties and once for instance properties */ static void buildPropertyList(EjsMod *mp, MprList *list, EjsAny *obj, int numInherited) { Ejs *ejs; EjsTrait *trait; EjsName qname; EjsObj *vp; EjsDoc *doc; PropRec *prec; int start, slotNum, numProp; ejs = mp->ejs; /* Loop over all the (non-inherited) properties */ start = (obj == ejs->global) ? mp->firstGlobal : numInherited; numProp = ejsGetLength(ejs, obj); for (slotNum = start; slotNum < numProp; slotNum++) { vp = ejsGetProperty(ejs, obj, slotNum); trait = ejsGetPropertyTraits(ejs, obj, slotNum); qname = ejsGetPropertyName(ejs, obj, slotNum); if (trait) { if (trait->attributes & (EJS_TRAIT_GETTER | EJS_TRAIT_SETTER)) { doc = getDoc(ejs, "fun", obj, slotNum); } else { doc = getDoc(ejs, NULL, obj, slotNum); } if (doc && doc->hide) { continue; } } if (vp == 0 || ejsIsType(ejs, vp) || qname.name == 0 || trait == 0) { continue; } if (ejsIsFunction(ejs, vp) && !(trait->attributes & (EJS_TRAIT_GETTER | EJS_TRAIT_SETTER))) { continue; } if (ejsCompareAsc(ejs, qname.space, EJS_PRIVATE_NAMESPACE) == 0 || ejsContainsAsc(ejs, qname.space, ",private]") >= 0) { continue; } prec = mprAlloc(sizeof(PropRec)); prec->qname = qname; prec->obj = obj; prec->slotNum = slotNum; prec->trait = trait; prec->vp = vp; mprAddItem(list, prec); } } /* Generate the entries for class properties. Will be called once for static properties and once for instance properties */ static int generateClassPropertyTableEntries(EjsMod *mp, EjsObj *obj, MprList *properties) { Ejs *ejs; EjsType *type; EjsTrait *trait; EjsName qname; EjsObj *vp; EjsDoc *doc; EjsFunction *fun; PropRec *prec; cchar *tname; int count, next, attributes; ejs = mp->ejs; count = 0; type = ejsIsType(ejs, obj) ? (EjsType*) obj : 0; for (next = 0; (prec = (PropRec*) mprGetNextItem(properties, &next)) != 0; ) { vp = prec->vp; trait = prec->trait; qname = prec->qname; if (ejsStartsWithAsc(ejs, qname.space, "internal") >= 0|| ejsContainsAsc(ejs, qname.space, "private") >= 0) { continue; } if (isalpha((uchar) qname.name->value[0])) { out(mp, "<a name='%@'></a>\n", qname.name); } attributes = trait->attributes; if (type && qname.space == type->qname.space) { out(mp, " <tr><td nowrap align='center'>%s</td><td>%@</td>", fmtAttributes(vp, attributes, 0), qname.name); } else { out(mp, " <tr><td nowrap align='center'>%s %s</td><td>%@</td>", fmtNamespace(ejs, qname), fmtAttributes(vp, attributes, 0), qname.name); } if (trait->attributes & EJS_TRAIT_GETTER) { fun = (EjsFunction*) vp; if (fun->resultType) { tname = fmtType(ejs, fun->resultType->qname); if (scaselesscmp(tname, "intrinsic::Void") == 0) { out(mp, "<td>&nbsp;</td>"); } else { out(mp, "<td>%s</td>", fmtTypeReference(ejs, fun->resultType->qname)); } } else { out(mp, "<td>&nbsp;</td>"); } } else if (trait->type) { out(mp, "<td>%s</td>", fmtTypeReference(ejs, trait->type->qname)); } else { out(mp, "<td>&nbsp;</td>"); } doc = getDoc(ejs, NULL, prec->obj, prec->slotNum); if (doc) { out(mp, "<td>%s %s</td></tr>\n", doc->brief, doc->description ? doc->description : ""); } else { out(mp, "<td>&nbsp;</td></tr>\n"); } count++; } return count; } static void buildMethodList(EjsMod *mp, MprList *methods, EjsObj *obj, EjsObj *owner, EjsName ownerName) { Ejs *ejs; EjsTrait *trait; EjsName qname; EjsObj *vp; EjsFunction *fun; EjsDoc *doc; EjsType *type; FunRec *fp; int slotNum, numProp, numInherited; ejs = mp->ejs; if (ejsIsType(ejs, owner) && !ejsIsPrototype(ejs, obj) && ((EjsType*) owner)->hasConstructor) { type = (EjsType*) owner; slotNum = ejsLookupProperty(ejs, ejs->global, ownerName); assert(slotNum >= 0); fp = mprAlloc(sizeof(FunRec)); fp->fun = (EjsFunction*) type; fp->obj = ejs->global; fp->slotNum = slotNum; fp->owner = ejs->global; fp->ownerName = type->qname; fp->qname = type->qname; fp->trait = ejsGetPropertyTraits(ejs, ejs->global, slotNum); if (fp->trait) { doc = getDoc(ejs, "fun", ejs->global, slotNum); if (doc && !doc->hide) { mprAddItem(methods, fp); } } } numProp = ejsGetLength(ejs, obj); numInherited = 0; if (ejsIsPrototype(ejs, obj)) { numInherited = ((EjsType*) owner)->numInherited; } slotNum = (obj == ejs->global) ? mp->firstGlobal : numInherited; for (; slotNum < numProp; slotNum++) { vp = ejsGetProperty(ejs, obj, slotNum); trait = ejsGetPropertyTraits(ejs, obj, slotNum); qname = ejsGetPropertyName(ejs, obj, slotNum); if (ejsIsType(ejs, vp)) { doc = getDoc(ejs, "class", obj, slotNum); if (doc && doc->hide) { continue; } } fun = (EjsFunction*) vp; if (trait->attributes & (EJS_TRAIT_GETTER | EJS_TRAIT_SETTER)) { continue; } if (trait) { doc = getDoc(ejs, "fun", obj, slotNum); if (doc && doc->hide) { continue; } } if (vp == 0 || !ejsIsFunction(ejs, vp) || qname.name == 0 || trait == 0) { continue; } if (ejsCompareAsc(ejs, qname.space, EJS_INIT_NAMESPACE) == 0) { continue; } if (ejsCompareAsc(ejs, qname.space, EJS_PRIVATE_NAMESPACE) == 0 || ejsContainsAsc(ejs, qname.space, ",private]") >= 0) { continue; } if (ejsStartsWithAsc(ejs, qname.space, "internal") >= 0) { continue; } fp = mprAlloc(sizeof(FunRec)); fp->fun = fun; fp->obj = obj; fp->slotNum = slotNum; fp->owner = owner; fp->ownerName = ownerName; fp->qname = qname; fp->trait = trait; mprAddItem(methods, fp); } mprSortList(methods, (MprSortProc) compareFunctions, 0); } static int generateMethodTable(EjsMod *mp, MprList *methods, EjsObj *obj, int instanceMethods) { Ejs *ejs; EjsType *type; EjsTrait *trait, *argTrait; EjsName qname, argName; EjsDoc *doc; EjsFunction *fun; FunRec *fp; cchar *defaultValue; int i, count, next, emitTable; ejs = mp->ejs; type = ejsIsType(ejs, obj) ? ((EjsType*) obj) : 0; if (instanceMethods) { out(mp, "<a name='InstanceMethods'></a>\n"); out(mp, "<h2 class='classSection'>%@ Instance Methods</h2>\n", (type) ? type->qname.name : ejsCreateStringFromAsc(ejs, "Global")); } else { out(mp, "<a name='ClassMethods'></a>\n"); out(mp, "<h2 class='classSection'>%@ Class Methods</h2>\n", (type) ? type->qname.name : ejsCreateStringFromAsc(ejs, "Global")); } /* Output each method */ count = emitTable = 0; for (next = 0; (fp = (FunRec*) mprGetNextItem(methods, &next)) != 0; ) { qname = fp->qname; trait = fp->trait; fun = fp->fun; if (!emitTable) { out(mp, "<table class='apiIndex' title='methods'>\n"); out(mp, " <tr><th>Qualifiers</th><th width='95%%'>Method</th></tr>\n"); emitTable = 1; } if (ejsCompareAsc(ejs, qname.space, EJS_INIT_NAMESPACE) == 0) { continue; } if (instanceMethods) { if (trait->attributes & EJS_PROP_STATIC) { continue; } } else { if (!(trait->attributes & EJS_PROP_STATIC)) { continue; } } if (type && qname.space == type->qname.space) { out(mp, " <tr class='apiDef'><td class='apiType'>%s</td>", fmtAttributes(fun, trait->attributes, 0)); } else { out(mp, " <tr class='apiDef'><td class='apiType'>%s %s</td>", fmtNamespace(ejs, qname), fmtAttributes(fun, trait->attributes, 0)); } out(mp, "<td><a href='#%@'><b>%s</b></a>(", qname.name, demangle(ejs, qname.name)); doc = getDoc(ejs, "fun", fp->obj, fp->slotNum); for (i = 0; i < (int) fun->numArgs; ) { argName = ejsGetPropertyName(ejs, fun->activation, i); argTrait = ejsGetPropertyTraits(ejs, fun->activation, i); if (argTrait->type) { out(mp, "%s: %s", fmtDeclaration(ejs, argName), fmtTypeReference(ejs, argTrait->type->qname)); } else { out(mp, "%s", fmtDeclaration(ejs, argName)); } if (doc) { defaultValue = getDefault(doc, ejsToMulti(ejs, argName.name)); if (defaultValue) { out(mp, " = %s", defaultValue); } } if (++i < (int) fun->numArgs) { out(mp, ", "); } } out(mp, ")"); if (fun->resultType) { out(mp, ": %s", fmtTypeReference(ejs, fun->resultType->qname)); } out(mp, "</tr>"); if (doc) { out(mp, "<tr class='apiBrief'><td>&nbsp;</td><td>%s</td></tr>\n", doc->brief); } count++; } if (count == 0) { out(mp, " <p>(No own %s methods defined)</p>", instanceMethods ? "instance" : "class"); } out(mp, "</table>\n\n"); if (type && type->baseType) { out(mp, "<p class='inheritedLink'><a href='%s#InstanceMethods'><i>Inherited Methods</i></a></p>\n\n", fmtClassUrl(ejs, type->baseType->qname)); } out(mp, "<hr />\n"); return count; } static void generateMethodDetail(EjsMod *mp, MprList *methods) { FunRec *fp; int next; out(mp, "<h2>Method Detail</h2>\n"); for (next = 0; (fp = (FunRec*) mprGetNextItem(methods, &next)) != 0; ) { generateMethod(mp, fp); } } static void checkArgs(EjsMod *mp, Ejs *ejs, EjsName ownerName, EjsFunction *fun, EjsName qname, EjsDoc *doc) { EjsName argName; MprKeyValue *param; cchar *key; int i, next; for (i = 0; i < (int) fun->numArgs; i++) { argName = ejsGetPropertyName(ejs, fun->activation, i); for (next = 0; (param = mprGetNextItem(doc->params, &next)) != 0; ) { key = param->key; if (strncmp(key, "...", 3) == 0) { key += 3; } if (strcmp(key, ejsToMulti(ejs, argName.name)) == 0) { break; } } if (param == 0) { if (mp->warnOnError) { mprLog("ejs", 0, "Missing documentation for parameter \"%@\" in function \"%@\" in type \"%@\"", argName.name, qname.name, ownerName.name); } } } } static int findArg(Ejs *ejs, EjsFunction *fun, cchar *name) { EjsName argName; int i; if (strncmp(name, "...", 3) == 0) { name += 3; } for (i = 0; i < (int) fun->numArgs; i++) { argName = ejsGetPropertyName(ejs, fun->activation, i); if (argName.name && ejsCompareAsc(ejs, argName.name, name) == 0) { return i; } } return EJS_ERR; } /* Lookup to see if there is doc about a default value for a parameter */ static cchar *getDefault(EjsDoc *doc, cchar *key) { MprKeyValue *def; int next; for (next = 0; (def = mprGetNextItem(doc->defaults, &next)) != 0; ) { if (strcmp(def->key, key) == 0) { return def->value; } } return 0; } static void generateMethod(EjsMod *mp, FunRec *fp) { Ejs *ejs; EjsType *type; EjsTrait *trait, *argTrait; EjsName qname, argName, throwName; EjsFunction *fun; EjsObj *obj; EjsDoc *doc; EjsLookup lookup; MprKeyValue *param, *thrown, *option, *event; cchar *defaultValue, *accessorSep, *spaceSep; char *see, *description, *setType; int i, count, next, slotNum; ejs = mp->ejs; obj = fp->obj; slotNum = fp->slotNum; type = ejsIsType(ejs, obj) ? (EjsType*) obj : 0; fun = (EjsFunction*) ejsGetProperty(ejs, obj, slotNum); assert(ejsIsFunction(ejs, fun)); qname = ejsGetPropertyName(ejs, obj, slotNum); trait = ejsGetPropertyTraits(ejs, obj, slotNum); doc = getDoc(ejs, "fun", obj, slotNum); if (doc && doc->hide) { return; } if (doc == 0 || doc->brief == 0) { if (mp->warnOnError) { if (!ejsIsType(ejs, fun)) { /* Don't warn about default constructors */ if (mp->warnOnError) { mprLog("ejs", 0, "Missing documentation for \"%@.%@\"", fp->ownerName.name, qname.name); } } } return; } if (isalpha((uchar) qname.name->value[0])) { out(mp, "<a name='%@'></a>\n", qname.name); } if (type && qname.space == type->qname.space) { out(mp, "<div class='api'>\n"); out(mp, "<div class='apiSig'>%s %@(", fmtAttributes(fun, trait->attributes, 0), qname.name); } else { accessorSep = (trait->attributes & (EJS_TRAIT_GETTER | EJS_TRAIT_SETTER)) ? " ": ""; spaceSep = qname.space->value[0] ? " ": ""; out(mp, "<div class='api'>\n"); out(mp, "<div class='apiSig'>%s %s%s %s%s %s(", fmtAttributes(fun, trait->attributes & ~(EJS_TRAIT_GETTER | EJS_TRAIT_SETTER), 0), spaceSep, fmtSpace(ejs, qname), accessorSep, fmtAccessors(trait->attributes), demangle(ejs, qname.name)); } for (i = 0; i < (int) fun->numArgs; ) { argName = ejsGetPropertyName(ejs, fun->activation, i); argTrait = ejsGetPropertyTraits(ejs, fun->activation, i); if (argTrait->type) { out(mp, "%s: %s", fmtDeclaration(ejs, argName), fmtTypeReference(ejs, argTrait->type->qname)); } else { out(mp, "%s", fmtDeclaration(ejs, argName)); } if (doc) { defaultValue = getDefault(doc, ejsToMulti(ejs, argName.name)); if (defaultValue) { out(mp, " = %s", defaultValue); } } if (++i < (int) fun->numArgs) { out(mp, ", "); } } out(mp, ")"); if (fun->resultType) { out(mp, ": %s", fmtTypeReference(ejs, fun->resultType->qname)); } out(mp, "\n</div>\n"); if (doc) { out(mp, "<div class='apiDetail'>\n"); out(mp, "<dl><dt>Description</dt></dd><dd>%s %s</dd></dl>\n", doc->brief, doc->description ? doc->description : ""); count = mprGetListLength(doc->params); if (count > 0) { out(mp, "<dl><dt>Parameters</dt>\n"); out(mp, "<dd><table class='parameters' title='parameters'>\n"); checkArgs(mp, ejs, fp->ownerName, fun, qname, doc); for (next = 0; (param = mprGetNextItem(doc->params, &next)) != 0; ) { defaultValue = getDefault(doc, param->key); i = findArg(ejs, fun, param->key); if (i < 0) { mprLog("ejs doc", 0, "Bad @param reference for \"%s\" in function \"%@\" in type \"%@\"", param->key, qname.name, fp->ownerName.name); } else { argName = ejsGetPropertyName(ejs, fun->activation, i); argTrait = ejsGetPropertyTraits(ejs, fun->activation, i); out(mp, "<tr class='param'><td class='param'>"); description = param->value; setType = 0; if (description && description[0] == ':') { setType = ssplit(sclone(&description[1]), " ", &description); } if (argTrait->type) { out(mp, "%s: %s ", fmtDeclaration(ejs, argName), fmtTypeReference(ejs, argTrait->type->qname)); } else if (setType && *setType) { out(mp, "%s: %s", fmtDeclaration(ejs, argName), setType); } else { out(mp, "%s ", fmtDeclaration(ejs, argName)); } out(mp, "</td><td>%s", description); if (defaultValue) { if (scontains(description, "Not implemented") == NULL) { out(mp, " [default: %s]", defaultValue); } } } out(mp, "</td></tr>"); } out(mp, "</table></dd>\n"); out(mp, "</dl>"); } count = mprGetListLength(doc->options); if (count > 0) { out(mp, "<dl><dt>Options</dt>\n"); out(mp, "<dd><table class='parameters' title='options'>\n"); for (next = 0; (option = mprGetNextItem(doc->options, &next)) != 0; ) { out(mp, "<td class='param'>%s</td><td>%s</td>", option->key, option->value); out(mp, "</tr>\n"); } out(mp, "</table></dd>\n"); out(mp, "</dl>"); } count = mprGetListLength(doc->events); if (count > 0) { out(mp, "<dl><dt>Events</dt>\n"); out(mp, "<dd><table class='parameters' title='events'>\n"); for (next = 0; (event = mprGetNextItem(doc->events, &next)) != 0; ) { out(mp, "<td class='param'>%s</td><td>%s</td>", event->key, event->value); out(mp, "</tr>\n"); } out(mp, "</table></dd>\n"); out(mp, "</dl>"); } if (doc->returns) { out(mp, "<dl><dt>Returns</dt>\n<dd>%s</dd></dl>\n", doc->returns); } count = mprGetListLength(doc->throws); if (count > 0) { out(mp, "<dl><dt>Throws</dt><dd>\n"); for (next = 0; (thrown = (MprKeyValue*) mprGetNextItem(doc->throws, &next)) != 0; ) { // TODO Functionalize ejs->state->bp = ejs->global; if ((slotNum = ejsLookupVar(ejs, ejs->global, EN(thrown->key), &lookup)) < 0) { continue; } throwName = lookup.name; out(mp, "<a href='%s'>%s</a>: %s%s\n", getFilename(fmtType(ejs, throwName)), thrown->key, thrown->value, (count == next) ? "" : ", "); } out(mp, "</dd>\n"); out(mp, "</dl>"); } if (doc->requires) { out(mp, "<dl><dt>Requires</dt>\n<dd>configure --ejs-%s</dd></dl>\n", doc->requires); } if (doc->spec) { out(mp, "<dl><dt>Specified</dt>\n<dd>%s</dd></dl>\n", doc->spec); } if (doc->stability) { out(mp, "<dl><dt>Stability</dt>\n<dd>%s</dd></dl>\n", doc->stability); } if (doc->example) { out(mp, "<dl><dt>Example</dt>\n<dd><pre>%s</pre></dd></dl>\n", doc->example); } count = mprGetListLength(doc->see); if (count > 0) { out(mp, "<dl><dt>See Also</dt>\n<dd>\n"); for (next = 0; (see = mprGetNextItem(doc->see, &next)) != 0; ) { out(mp, "<a href='%s'>%s</a>%s\n", getFilename(see), see, (count == next) ? "" : ", "); } out(mp, "</dd></dl>\n"); } out(mp, "</div>\n"); } out(mp, "</div>\n"); out(mp, "<hr />\n"); } static char *fmtAttributes(EjsAny *vp, int attributes, int klass) { static char attributeBuf[256]; attributeBuf[0] = '\0'; /* Order to look best */ if (attributes & EJS_PROP_STATIC) { strcat(attributeBuf, "static "); } /* Types are can also be constructor functions. Need klass parameter to differentiate */ if (ejsIsType(ejs, vp) && klass) { if (attributes & EJS_TYPE_FINAL) { strcat(attributeBuf, "final "); } if (attributes & EJS_TYPE_DYNAMIC_INSTANCES) { strcat(attributeBuf, "dynamic "); } } else if (ejsIsFunction(ejs, vp)) { if (attributes & EJS_FUN_OVERRIDE) { strcat(attributeBuf, "override "); } if (attributes & EJS_TRAIT_GETTER) { strcat(attributeBuf, "get "); } if (attributes & EJS_TRAIT_SETTER) { strcat(attributeBuf, "set "); } } else { if (attributes & EJS_TRAIT_READONLY) { strcat(attributeBuf, "const "); } } return attributeBuf; } static char *fmtAccessors(int attributes) { static char attributeBuf[256]; attributeBuf[0] = '\0'; if (attributes & EJS_TRAIT_GETTER) { strcat(attributeBuf, "get "); } if (attributes & EJS_TRAIT_SETTER) { strcat(attributeBuf, "set "); } return attributeBuf; } static wchar *joinLines(wchar *str) { wchar *cp, *np; for (cp = str; cp && *cp; cp++) { if (*cp == '\n') { for (np = &cp[1]; *np; np++) { if (!isspace((uchar) *np)) { break; } } if (!isspace((uchar) *np)) { *cp = ' '; } } } return str; } /* Merge in @duplicate entries */ static wchar *mergeDuplicates(Ejs *ejs, EjsMod *mp, EjsName qname, EjsDoc *doc, wchar *spec) { EjsDoc *dup; wchar *next, *duplicate, *mark; if ((next = mcontains(spec, "@duplicate")) == 0) { return spec; } next = spec = wclone(spec); while ((next = mcontains(next, "@duplicate")) != 0) { mark = next; mtok(next, " \t\n\r", &next); if ((duplicate = mtok(next, " \t\n\r", &next)) == 0) { break; } if ((dup = getDuplicateDoc(ejs, duplicate)) == 0) { mprLog("ejs doc", 0, "Cannot find @duplicate directive %s for %s", duplicate, qname.name); } else { crackDoc(mp, dup, WEN(duplicate)); mprCopyListContents(doc->params, dup->params); mprCopyListContents(doc->options, dup->options); mprCopyListContents(doc->events, dup->events); mprCopyListContents(doc->see, dup->see); mprCopyListContents(doc->throws, dup->throws); doc->brief = dup->brief; doc->description = dup->description; doc->example = dup->example; doc->requires = dup->requires; doc->returns = dup->returns; doc->stability = dup->stability; doc->spec = dup->spec; } memmove(mark, next, wlen(next) + 1); next = mark; } return spec; } /* Cleanup text. Remove leading comments and "*" that are part of the comment and not part of the doc. */ static void prepText(wchar *str) { wchar *dp, *cp; dp = cp = str; while (isspace((uchar) *cp) || *cp == '*') { cp++; } while (*cp) { if (cp[0] == '\n') { *dp++ = '\n'; for (cp++; (isspace((uchar) *cp) || *cp == '*'); cp++) { if (*cp == '\n') { *dp++ = '\n'; } } if (*cp == '\0') { cp--; break; } } else { *dp++ = *cp++; } } *dp = '\0'; } static EjsDoc *crackDoc(EjsMod *mp, EjsDoc *doc, EjsName qname) { Ejs *ejs; EjsDoc *dup; MprKeyValue *pair; wchar *value, *key, *line, *str, *next, *cp, *token, *nextWord, *word, *duplicate; wchar *thisBrief, *thisDescription, *start; ejs = mp->ejs; if (doc->cracked) { return doc; } doc->cracked = 1; doc->params = mprCreateList(0, 0); doc->options = mprCreateList(0, 0); doc->events = mprCreateList(0, 0); doc->defaults = mprCreateList(0, 0); doc->see = mprCreateList(0, 0); doc->throws = mprCreateList(0, 0); str = wclone(doc->docString->value); if (str == NULL) { return doc; } prepText(str); if (mcontains(str, "@hide") || mcontains(str, "@hidden")) { doc->hide = 1; } else if (mcontains(str, "@deprecate") || mcontains(str, "@deprecated")) { doc->deprecated = 1; } str = mergeDuplicates(ejs, mp, qname, doc, str); thisDescription = NULL; thisBrief = NULL; next = str; if (str[0] != '@') { if ((thisBrief = mtok(str, "@", &next)) == 0) { thisBrief = NULL; } else { for (cp = thisBrief; *cp; cp++) { if (*cp == '.' && (isspace((uchar) cp[1]) || *cp == '*')) { cp++; *cp++ = '\0'; thisDescription = mtrim(cp, " \t\n", MPR_TRIM_BOTH); break; } } } } doc->brief = wjoin(doc->brief, thisBrief, NULL); doc->description = wjoin(doc->description, thisDescription, NULL); mtrim(doc->brief, " \t\r\n", MPR_TRIM_BOTH); mtrim(doc->description, " \t\r\n", MPR_TRIM_BOTH); assert(doc->brief); assert(doc->description); /* This is what we are parsing: One liner is the first sentance. Rest of description can continue from here and can include embedded html @param argName Description (Up to next @, case matters on argName) @default argName DefaultValue (Up to next @, case matters on argName) @return Sentence (Can use return or returns. If sentance starts with lower case, then start sentance with "Call returns". @option argName Description (Up to next @, case matters on argName) @event eventName Description (Up to next @, case matters on argName) @throws ExceptionType Explanation (Up to next @) @see Keyword keyword ... (Case matters) @example Description (Up to next @) @stability kind (prototype | evolving | stable | mature | deprecated] @deprecated version Same as @stability deprecated @requires ECMA (Emit: configuration requires --ejs-ecma) @spec (ecma-262, ecma-357, ejs-11) @hide (Hides this entry) Only functions can use return and param. */ start = next; while (next) { token = next; for (cp = next; cp ; ) { mtok(cp, "@", &cp); if (cp && cp[-2] == '\\') { cp[-1] = '@'; cp[-2] = ' '; } else { next = cp; break; } } line = skipAtWord(token); if (token > &start[2] && token[-2] == '\\') { continue; } if (match(token, "duplicate")) { duplicate = mtrim(line, " \t\n", MPR_TRIM_BOTH); if ((dup = getDuplicateDoc(ejs, duplicate)) == 0) { mprLog("ejs doc", 0, "Cannot find @duplicate directive %s for %@", duplicate, qname.name); } else { crackDoc(mp, dup, WEN(duplicate)); mprCopyListContents(doc->params, dup->params); mprCopyListContents(doc->options, dup->options); mprCopyListContents(doc->events, dup->events); mprCopyListContents(doc->see, dup->see); mprCopyListContents(doc->throws, dup->throws); doc->brief = mrejoin(doc->brief, " ", dup->brief, NULL); doc->description = mrejoin(doc->description, " ", dup->description, NULL); if (dup->example) { if (doc->example) { doc->example = mrejoin(doc->example, " ", dup->example, NULL); } else { doc->example = dup->example; } } if (dup->requires) { if (doc->requires) { doc->requires = mrejoin(doc->requires, " ", dup->requires, NULL); } else { doc->requires = dup->requires; } } if (dup->returns && doc->returns == 0) { doc->returns = dup->returns; } if (dup->stability && doc->stability == 0) { doc->stability = dup->stability; } if (dup->spec && doc->spec == 0) { doc->spec = dup->spec; } } } else if (match(token, "example") || match(token, "examples")) { doc->example = formatExample(ejs, doc->docString); } else if (match(token, "event")) { getKeyValue(line, &key, &value); value = joinLines(value); if (key && *key) { pair = createKeyPair(key, value); mprAddItem(doc->events, pair); } } else if (match(token, "option")) { getKeyValue(line, &key, &value); value = joinLines(value); if (key && *key) { pair = createKeyPair(key, value); mprAddItem(doc->options, pair); } } else if (match(token, "param")) { getKeyValue(line, &key, &value); value = joinLines(value); if (key && *key) { key = mtrim(key, ".", MPR_TRIM_BOTH); pair = createKeyPair(key, value); mprAddItem(doc->params, pair); } } else if (match(token, "default")) { getKeyValue(line, &key, &value); value = joinLines(value); if (key && *key) { pair = createKeyPair(key, value); mprAddItem(doc->defaults, pair); } } else if (match(token, "deprecated")) { doc->hide = 1; doc->deprecated = 1; doc->stability = amtow("deprecated", NULL); } else if (match(token, "hide") || match(token, "hidden")) { doc->hide = 1; } else if (match(token, "spec")) { doc->spec = mtrim(line, " \t\n", MPR_TRIM_BOTH); wlower(doc->spec); } else if (match(token, "stability")) { doc->stability = mtrim(line, " \t", MPR_TRIM_BOTH); wlower(doc->stability); } else if (match(token, "requires")) { doc->requires = mtrim(line, " \t", MPR_TRIM_BOTH); wlower(doc->requires); } else if (match(token, "return") || match(token, "returns")) { line = joinLines(line); doc->returns = mtrim(line, " \t", MPR_TRIM_BOTH); } else if (match(token, "throw") || match(token, "throws")) { getKeyValue(line, &key, &value); value = joinLines(value); pair = createKeyPair(key, value); mprAddItem(doc->throws, pair); } else if (match(token, "see") || match(token, "seeAlso")) { nextWord = line; do { word = nextWord; mtok(word, " \t\r\n", &nextWord); mprAddItem(doc->see, mtrim(word, " \t", MPR_TRIM_BOTH)); } while (nextWord && *nextWord); } } fixupDoc(ejs, doc); return doc; } static wchar *fixSentence(wchar *str) { wchar *buf; size_t len; if (str == 0 || *str == '\0') { return 0; } /* Copy the string and grow by 1 byte (plus null) to allow for a trailing period. */ len = wlen(str) + 2 * sizeof(wchar); if ((buf = mprAlloc(len)) == 0) { return 0; } wcopy(buf, len, str); str = buf; str[0] = toupper((uchar) str[0]); /* Append a "." if the string does not appear to contain HTML tags */ if (mcontains(str, "</") == 0) { /* Trim period and re-add */ str = mtrim(str, " \t\r\n.", MPR_TRIM_BOTH); len = wlen(str); if (str[len - 1] != '.') { str = sjoin(str, ".", NULL); } } else { str = mtrim(str, " \t\r\n", MPR_TRIM_BOTH); } return str; } static wchar *formatExample(Ejs *ejs, EjsString *docString) { wchar *example, *cp, *end, *buf, *dp; int i, indent; if ((example = mcontains(docString->value, "@example")) != 0) { example += 8; for (cp = example; *cp && *cp != '\n'; cp++) {} if (*cp == '\n') { cp++; } example = cp; for (end = example; *end; end++) { if (*end == '@' && (end == example || end[-1] != '\\')) { break; } } for (indent = 0; *cp == '\t' || *cp == ' '; indent++, cp++) {} buf = mprAlloc(wlen(example) * 4 + 2); for (cp = example, dp = buf; *cp && cp < end; ) { for (i = 0; i < indent && *cp && isspace((uchar) *cp) && *cp != '\n'; i++, cp++) {} for (; *cp && *cp != '\n'; ) { if (*cp == '<' && cp[1] == '%') { mtow(dp, 5, "&lt;", 4); dp += 4; cp++; *dp++ = *cp++; } else if (*cp == '%' && cp[1] == '>') { *dp++ = *cp++; mtow(dp, 5, "&gt;", 4); dp += 4; cp++; } else { *dp++ = *cp++; } } if (*cp == '\n') { *dp++ = *cp++; } *dp = '\0'; } for (--dp; dp > example && isspace((uchar) *dp); dp--) {} *++dp = '\0'; return buf; } return NULL; } static wchar *wikiFormat(Ejs *ejs, wchar *start) { EjsLookup lookup; EjsName qname; MprBuf *buf; wchar *end, *cp, *klass, *property, *str, *pref, *space; ssize len; int slotNum, sentence; if (start == 0 || *start == '\0') { return NULL; } buf = mprCreateBuf(-1, -1); end = &start[wlen(start)]; for (str = start; str < end && *str; str++) { /* FUTURE -- expand this to support basic markdown */ if (str[0] == '\n' && str[1] == '\n') { /* Two blank lines forces a blank line in the output */ mprPutStringToWideBuf(buf, "<br/><br/>"); str++; } else if (*str == '$') { if (str[1] == '$') { mprPutCharToWideBuf(buf, *str); continue; } if ((str > start && (str[-1] == '$' || str[-1] == '\\'))) { /* Remove backquote */ mprAdjustBufEnd(buf, - (int) sizeof(wchar)); mprPutCharToWideBuf(buf, *str); continue; } /* Dollar reference expansion */ klass = &str[1]; for (cp = &str[1]; *cp; cp++) { if (isspace((uchar) *cp)) { break; } } len = cp - str; str = cp; if (isspace((uchar) *cp)) { cp--; } klass = snclone(klass, len); sentence = (klass[wlen(klass) - 1] == '.'); assert(strcmp(klass, "ejs.web::Request") != 0); if (scontains(klass, "::")) { space = ssplit(klass, "::", &klass); } else { space = ""; } if ((property = wchr(klass, '.')) != 0) { *property++ = '\0'; if (*property == '\0') { property = klass; klass = 0; } } else { property = klass; klass = 0; } pref = strim(property, "(), \t", MPR_TRIM_END); klass = mtrim(klass, "., \t", MPR_TRIM_BOTH); property = mtrim(property, "., \t", MPR_TRIM_BOTH); if (klass) { // TODO Functionalize ejs->state->bp = ejs->global; if ((slotNum = ejsLookupVar(ejs, ejs->global, N(space, klass), &lookup)) < 0) { if (klass) { mprPutToBuf(buf, "%s.%s", klass, property); } else { mprPutStringToBuf(buf, property); } } else { qname = lookup.name; if (property) { mprPutToBuf(buf, "<a href='%s#%s'>%s.%s</a>", getFilename(fmtType(ejs, qname)), pref, klass, property); } else { mprPutToBuf(buf, "<a href='%s'>%s</a>", getFilename(fmtType(ejs, qname)), klass); } } } else { mprPutToBuf(buf, "<a href='#%s'>%s</a>", pref, property); } if (sentence) { mprPutCharToWideBuf(buf, '.'); } mprPutCharToWideBuf(buf, ' '); } else { mprPutCharToWideBuf(buf, *str); } } mprAddNullToWideBuf(buf); return (wchar*) mprGetBufStart(buf); } static void fixupDoc(Ejs *ejs, EjsDoc *doc) { MprKeyValue *pair; int next; doc->brief = wikiFormat(ejs, fixSentence(doc->brief)); doc->description = wikiFormat(ejs, fixSentence(doc->description)); doc->returns = wikiFormat(ejs, fixSentence(doc->returns)); doc->stability = fixSentence(doc->stability); doc->requires = wikiFormat(ejs, fixSentence(doc->requires)); if (doc->spec) { if (mcmp(doc->spec, "ejs") == 0) { doc->spec = mfmt("ejscript-%d.%d", ME_MAJOR_VERSION, ME_MINOR_VERSION); } } else { doc->spec = NULL; } if (doc->example == 0) { doc->example = NULL; } for (next = 0; (pair = mprGetNextItem(doc->events, &next)) != 0; ) { pair->value = wikiFormat(ejs, fixSentence(pair->value)); } for (next = 0; (pair = mprGetNextItem(doc->options, &next)) != 0; ) { pair->value = wikiFormat(ejs, fixSentence(pair->value)); } for (next = 0; (pair = mprGetNextItem(doc->params, &next)) != 0; ) { pair->value = wikiFormat(ejs, fixSentence(pair->value)); } /* Don't fix the default value */ } static void out(EjsMod *mp, char *fmt, ...) { va_list args; char *buf; if (mp->file == 0) { mp->file = mprOpenFile(mp->path, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (mp->file == 0) { mprLog("ejs doc", 0, "Cannot open %s", mp->path); mp->errorCount++; return; } } va_start(args, fmt); buf = sfmtv(fmt, args); if (mprWriteFileString(mp->file, buf) < 0) { mprLog("ejs doc", 0, "Cannot write to buffer"); } } static EjsString *fmtModule(Ejs *ejs, EjsString *name) { if (ejsCompareAsc(ejs, name, EJS_DEFAULT_MODULE) == 0) { return ESV(empty); } return name; } static char *fmtClassUrl(Ejs *ejs, EjsName qname) { return getFilename(fmtType(ejs, qname)); } static char *fmtNamespace(Ejs *ejs, EjsName qname) { static char buf[256]; cchar *space; char *cp; space = ejsToMulti(ejs, qname.space); if (space[0] == '[') { scopy(buf, sizeof(buf), &space[1]); } else { scopy(buf, sizeof(buf), space); } if (buf[strlen(buf) - 1] == ']') { buf[strlen(buf) - 1] = '\0'; } if (strcmp(buf, "ejs") == 0) { buf[0] = '\0'; } else if (strcmp(buf, "public") == 0) { buf[0] = '\0'; } else if ((cp = strrchr(buf, ',')) != 0) { ++cp; if (strcmp(cp, EJS_PUBLIC_NAMESPACE) == 0) { strcpy(buf, EJS_PUBLIC_NAMESPACE); } else if (strcmp(cp, EJS_PRIVATE_NAMESPACE) == 0 || strcmp(cp, EJS_CONSTRUCTOR_NAMESPACE) == 0 || strcmp(cp, EJS_INIT_NAMESPACE) == 0) { /* Suppress "private" as they are the default for namespaces and local vars */ buf[0] = '\0'; } } if (strcmp(buf, EJS_PRIVATE_NAMESPACE) == 0 || strcmp(buf, EJS_CONSTRUCTOR_NAMESPACE) == 0 || strcmp(buf, EJS_INIT_NAMESPACE) == 0) { buf[0] = '\0'; } return buf; } static char *fmtType(Ejs *ejs, EjsName qname) { static char buf[ME_MAX_PATH]; char *namespace; namespace = fmtNamespace(ejs, qname); if (strcmp(namespace, EJS_PUBLIC_NAMESPACE) == 0) { *namespace = '\0'; } if (*namespace) { if (*namespace) { fmt(buf, sizeof(buf), "%s::%@", namespace, qname.name); } else { fmt(buf, sizeof(buf), "%@", qname.name); } } else { fmt(buf, sizeof(buf), "%@", qname.name); } return buf; } /* Map lower case names with a "l-" prefix for systems with case insensitive names */ static char *getFilename(cchar *name) { static char buf[ME_MAX_PATH]; char *cp, *sp; scopy(buf, sizeof(buf), name); if ((cp = strstr(buf, "::")) != 0) { *cp++ = '-'; if (islower((int) cp[1])) { *cp++ = '-'; for (sp = cp; *sp; ) { *cp++ = *sp++; } } else { for (sp = cp + 1; *sp; ) { *cp++ = *sp++; } } *cp = '\0'; } scopy(&buf[strlen(buf)], sizeof(buf) - (int) strlen(buf) - 1, ".html"); return buf; } static char *fmtTypeReference(Ejs *ejs, EjsName qname) { static char buf[ME_MAX_PATH]; char *typeName; typeName = fmtType(ejs, qname); fmt(buf, sizeof(buf), "<a href='%s'>%@</a>", getFilename(typeName), qname.name); return buf; } static char *fmtSpace(Ejs *ejs, EjsName qname) { static char buf[ME_MAX_PATH]; char *namespace; namespace = fmtNamespace(ejs, qname); if (namespace[0]) { fmt(buf, sizeof(buf), "%@", qname.space); } else { buf[0] = '\0'; } return buf; } static char *fmtDeclaration(Ejs *ejs, EjsName qname) { static char buf[ME_MAX_PATH]; char *namespace; namespace = fmtNamespace(ejs, qname); if (namespace[0]) { fmt(buf, sizeof(buf), "%@ %s", qname.space, demangle(ejs, qname.name)); } else { fmt(buf, sizeof(buf), "%s", demangle(ejs, qname.name)); } return buf; } static bool match(wchar *last, cchar *key) { int len; assert(last); assert(key && *key); len = (int) strlen(key); return mncmp(last, key, len) == 0; } static wchar *skipAtWord(wchar *str) { while (!isspace((uchar) *str) && *str) str++; while (isspace((uchar) *str)) str++; return str; } static void getKeyValue(wchar *str, wchar **key, wchar **value) { wchar *end; for (end = str; *end && !isspace((uchar) *end); end++) ; if (end) { *end = '\0'; } if (key) { *key = mtrim(str, " \t", MPR_TRIM_BOTH); } for (str = end + 1; *str && isspace((uchar) *str); str++) { ; } if (value) { *value = mtrim(str, " \t", MPR_TRIM_BOTH); } } static int compareProperties(PropRec **p1, PropRec **p2) { return compareStrings(&(*p1)->qname.name, &(*p2)->qname.name); } static int compareFunctions(FunRec **f1, FunRec **f2) { return compareStrings(&(*f1)->qname.name, &(*f2)->qname.name); } static int compareClasses(ClassRec **c1, ClassRec **c2) { return compareStrings(&(*c1)->qname.name, &(*c2)->qname.name); } static cchar *demangle(Ejs *ejs, EjsString *name) { return ejsToMulti(ejs, name); } static cchar *demangleCESV(cchar *name) { return name; } static int compareNames(char **q1, char **q2) { cchar *s1, *s2, *cp; s1 = demangleCESV(*q1); s2 = demangleCESV(*q2); /* Don't sort on the namespace portions of the name */ if ((cp = strrchr(s1, ':')) != 0) { s1 = cp + 1; } if ((cp = strrchr(s2, ':')) != 0) { s2 = cp + 1; } return scmp(s1, s2); } static int compareStrings(EjsString **q1, EjsString **q2) { cchar *s1, *s2, *cp; s1 = demangle(ejs, *q1); s2 = demangle(ejs, *q2); /* Don't sort on the namespace portions of the name */ if ((cp = strrchr(s1, ':')) != 0) { s1 = cp + 1; } if ((cp = strrchr(s2, ':')) != 0) { s2 = cp + 1; } return scmp(s1, s2); } static void addUniqueItem(MprList *list, cchar *item) { cchar *p; int next; if (item == 0 || *item == '\0') { return; } for (next = 0; (p = mprGetNextItem(list, &next)) != 0; ) { if (strcmp(p, item) == 0) { return; } } mprAddItem(list, sclone(item)); } static void addUniqueClass(MprList *list, ClassRec *item) { ClassRec *p; int next; if (item == 0) { return; } for (next = 0; (p = (ClassRec*) mprGetNextItem(list, &next)) != 0; ) { if (p->qname.name == item->qname.name) { if (p->qname.space == item->qname.space) { return; } } } mprAddItem(list, item); } static EjsDoc *getDoc(Ejs *ejs, cchar *tag, void *obj, int slotNum) { EjsObj *vp; char key[32]; vp = ejsGetProperty(ejs, obj, slotNum); if (tag == 0) { if (ejsIsType(ejs, vp)) { tag = "class"; } else if (ejsIsFunction(ejs, vp)) { tag = "fun"; } else { tag = "var"; } } fmt(key, sizeof(key), "%s %Lx %d", tag, PTOL(obj), slotNum); return mprLookupKey(ejs->doc, key); } static EjsDoc *getDuplicateDoc(Ejs *ejs, wchar *duplicate) { EjsDoc *doc; EjsObj *vp; EjsLookup lookup; wchar *space, *klass, *property; int slotNum; space = wclone(duplicate); if ((klass = mcontains(space, "::")) != 0) { *klass = '\0'; klass += 2; } else { klass = space; space = ""; } if ((property = wchr(klass, '.')) != 0) { *property++ = '\0'; } // TODO Functionalize ejs->state->bp = ejs->global; if ((slotNum = ejsLookupVar(ejs, ejs->global, WN(space, klass), &lookup)) < 0) { return 0; } if (property == 0) { doc = getDoc(ejs, NULL, ejs->global, slotNum); } else { vp = ejsGetProperty(ejs, ejs->global, slotNum); if ((slotNum = ejsLookupVar(ejs, vp, WEN(property), &lookup)) < 0) { if (ejsIsType(ejs, vp)) { vp = (EjsObj*) ((EjsType*) vp)->prototype; if ((slotNum = ejsLookupVar(ejs, vp, WEN(property), &lookup)) < 0) { return 0; } } } doc = getDoc(ejs, NULL, (EjsBlock*) vp, slotNum); } if (doc) { if (doc->docString == NULL || doc->docString->value[0] == '\0') { mprLog("ejs doc", 0, "Duplicate entry \"%s\" provides no description", duplicate); return 0; } } return doc; } static MprKeyValue *createKeyPair(wchar *key, wchar *value) { MprKeyValue *pair; pair = mprAlloc(sizeof(MprKeyValue)); if (pair == 0) { return 0; } pair->key = wclone(key); pair->value = mtrim(wclone(value), " ", MPR_TRIM_BOTH); return pair; } /* @copy default Copyright (c) Embedthis Software. All Rights Reserved. This software is distributed under commercial and open source licenses. You may use the Embedthis Open Source license or you may acquire a commercial license from Embedthis Software. You agree to be fully bound by the terms of either license. Consult the LICENSE.md distributed with this software for full details and other copyrights. Local variables: tab-width: 4 c-basic-offset: 4 End: vim: sw=4 ts=4 expandtab @end */
31.618791
134
0.50643
[ "object" ]
b278eff15cd13875c67cde16c2de85c8cf4d7f22
2,021
h
C
includes/object.h
heinthanth/meon
72a7b54abb0b37c8e98f059cd43c8cc19ea89519
[ "MIT" ]
1
2021-02-14T09:36:03.000Z
2021-02-14T09:36:03.000Z
includes/object.h
heinthanth/meon-craftinginterpreters
72a7b54abb0b37c8e98f059cd43c8cc19ea89519
[ "MIT" ]
null
null
null
includes/object.h
heinthanth/meon-craftinginterpreters
72a7b54abb0b37c8e98f059cd43c8cc19ea89519
[ "MIT" ]
null
null
null
#ifndef meon_object_h #define meon_object_h #include "common.h" #include "chunk.h" #include "value.h" #define OBJ_TYPE(value) (AS_OBJ(value)->t) #define IS_STRING(value) check_object_t(value, OBJECT_STRING) #define IS_CLOSURE(value) check_object_t(value, OBJECT_CLOSURE) #define IS_FUNCTION(value) check_object_t(value, OBJECT_FUNCTION) #define IS_NATIVE(value) check_object_t(value, OBJECT_NATIVE) #define AS_CLOSURE(value) ((ObjectClosure *)AS_OBJ(value)) #define AS_FUNCTION(value) ((ObjectFunction *)AS_OBJ(value)) #define AS_NATIVE(value) (((ObjectNative *)AS_OBJ(value))->function) #define AS_STRING(value) ((ObjectString *)AS_OBJ(value)) #define AS_CSTRING(value) (((ObjectString *)AS_OBJ(value))->chars) typedef enum { OBJECT_STRING, OBJECT_FUNCTION, OBJECT_NATIVE, OBJECT_CLOSURE, OBJECT_UPVALUE, } object_t; struct Object { object_t t; struct Object *next; bool isMarked; }; typedef struct { Object object; int argsCount; int upvalueCount; Chunk chunk; ObjectString *name; } ObjectFunction; typedef Value (*NativeFn)(int argCount, Value *args); typedef struct { Object object; NativeFn function; } ObjectNative; struct ObjectString { Object object; int length; char *chars; uint32_t hash; }; typedef struct ObjectUpvalue { Object obj; Value *location; Value closed; struct ObjectUpvalue *next; } ObjectUpvalue; typedef struct { Object obj; ObjectFunction *function; ObjectUpvalue **upvalues; int upvalueCount; } ObjectClosure; ObjectFunction *newFunction(); ObjectNative *newNative(NativeFn function); ObjectClosure *newClosure(ObjectFunction *function); ObjectUpvalue *newUpvalue(Value *slot); ObjectString *takeString(char *chars, int length); ObjectString *cpString(const char *chars, int length); static inline bool check_object_t(Value value, object_t t) { return IS_OBJ(value) && AS_OBJ(value)->t == t; } void printObject(Value value); char *object2string(Value value); #endif
21.731183
68
0.73528
[ "object" ]
b27dfdfc40a1191c7ee3b139d759e7f97c082456
16,909
c
C
src/examples/bind_groups.c
samdauwe/webgpu-native-examples
9ac5dd17d37cfeed8b2de39b2668108d6ecbee69
[ "Apache-2.0" ]
33
2021-05-09T03:45:28.000Z
2022-03-31T06:35:32.000Z
src/examples/bind_groups.c
samdauwe/webgpu-native-examples
9ac5dd17d37cfeed8b2de39b2668108d6ecbee69
[ "Apache-2.0" ]
2
2021-12-12T20:04:35.000Z
2022-01-07T16:26:12.000Z
src/examples/bind_groups.c
samdauwe/webgpu-native-examples
9ac5dd17d37cfeed8b2de39b2668108d6ecbee69
[ "Apache-2.0" ]
1
2021-11-06T07:24:03.000Z
2021-11-06T07:24:03.000Z
#include "example_base.h" #include "examples.h" #include <string.h> #include "../webgpu/gltf_model.h" #include "../webgpu/imgui_overlay.h" #include "../webgpu/texture.h" /* -------------------------------------------------------------------------- * * WebGPU Example - Using Bind Groups * * Bind groups are used to pass data to shader binding points. This example sets * up bind groups & layouts, creates a single render pipeline based on the bind * group layout and renders multiple objects with different bind groups. * * Ref: * https://github.com/SaschaWillems/Vulkan/blob/master/examples/descriptorsets/descriptorsets.cpp * -------------------------------------------------------------------------- */ static bool animate = true; struct view_matrices_t { mat4 projection; mat4 view; mat4 model; } view_matrices_t; typedef struct cube_t { struct view_matrices_t matrices; WGPUBindGroup bind_group; texture_t texture; WGPUBuffer uniform_buffer; vec3 rotation; } cube_t; static cube_t cubes[2] = {0}; static struct gltf_model_t* model; // Render pass descriptor for frame buffer writes static WGPURenderPassColorAttachment rp_color_att_descriptors[1]; static WGPURenderPassDescriptor render_pass_desc; static WGPURenderPipeline pipeline; static WGPUPipelineLayout pipeline_layout; static WGPUBindGroupLayout bind_group_layout; // Other variables static const char* example_title = "Using Bind Groups"; static bool prepared = false; static void setup_camera(wgpu_example_context_t* context) { context->camera = camera_create(); context->camera->type = CameraType_LookAt; camera_set_perspective(context->camera, 60.0f, context->window_size.aspect_ratio, 0.1f, 512.0f); camera_set_rotation(context->camera, (vec3){0.0f, 0.0f, 0.0f}); camera_set_translation(context->camera, (vec3){0.0f, 0.0f, -5.0f}); } static void load_assets(wgpu_context_t* wgpu_context) { const uint32_t gltf_loading_flags = WGPU_GLTF_FileLoadingFlags_PreTransformVertices | WGPU_GLTF_FileLoadingFlags_PreMultiplyVertexColors | WGPU_GLTF_FileLoadingFlags_DontLoadImages; model = wgpu_gltf_model_load_from_file(&(wgpu_gltf_model_load_options_t){ .wgpu_context = wgpu_context, .filename = "models/cube.gltf", .file_loading_flags = gltf_loading_flags, }); cubes[0].texture = wgpu_create_texture_from_file( wgpu_context, "textures/crate01_color_height_rgba.ktx", NULL); cubes[1].texture = wgpu_create_texture_from_file( wgpu_context, "textures/crate02_color_height_rgba.ktx", NULL); } /* * Set up bind groups and set layout */ static void setup_bind_groups(wgpu_context_t* wgpu_context) { /* * Bind group layout * * The layout describes the shader bindings and types used for a certain * descriptor layout and as such must match the shader bindings * * Shader bindings used in this example: * * VS: * layout (set = 0, binding = 0) uniform UBOMatrices * * FS: * layout (set = 0, binding = 1) uniform texture2D ...; * layout (set = 0, binding = 2) uniform sampler ...; */ WGPUBindGroupLayoutEntry bind_group_layout_entries[3] = {0}; /* * Binding 0: Uniform buffers (used to pass matrices) */ bind_group_layout_entries[0] = (WGPUBindGroupLayoutEntry) { // Shader binding point .binding = 0, // Accessible from the vertex shader only (flags can be combined to make it // accessible to multiple shader stages) .visibility = WGPUShaderStage_Vertex, .buffer = (WGPUBufferBindingLayout) { .type = WGPUBufferBindingType_Uniform, .hasDynamicOffset = false, .minBindingSize = sizeof(view_matrices_t), }, .sampler = {0}, }; /* * Binding 1: Image view (used to pass per object texture information) */ bind_group_layout_entries[1] = (WGPUBindGroupLayoutEntry) { .binding = 1, // Accessible from the fragment shader only .visibility = WGPUShaderStage_Fragment, .texture = (WGPUTextureBindingLayout) { .sampleType = WGPUTextureSampleType_Float, .viewDimension = WGPUTextureViewDimension_2D, .multisampled = false, }, .storageTexture = {0}, }; /* * Binding 2: Image sampler (used to pass per object texture information) */ bind_group_layout_entries[2] = (WGPUBindGroupLayoutEntry) { .binding = 2, .visibility = WGPUShaderStage_Fragment, .sampler = (WGPUSamplerBindingLayout){ .type=WGPUSamplerBindingType_Filtering, }, .texture = {0}, }; // Create the bind group layout bind_group_layout = wgpuDeviceCreateBindGroupLayout( wgpu_context->device, &(WGPUBindGroupLayoutDescriptor){ .entryCount = (uint32_t)ARRAY_SIZE(bind_group_layout_entries), .entries = bind_group_layout_entries, }); ASSERT(bind_group_layout != NULL) /* * Bind groups * * Using the shared bind group layout we will now allocate the bind groups. * * Bind groups contain the actual descriptor for the objects (buffers, images) * used at render time. */ for (uint8_t i = 0; i < (uint8_t)ARRAY_SIZE(cubes); ++i) { cube_t* cube = &cubes[i]; WGPUBindGroupEntry bind_group_entries[3] = {0}; /* * Binding 0: Object matrices Uniform buffer */ bind_group_entries[0] = (WGPUBindGroupEntry){ // Binding 0: Uniform buffer (Vertex shader) .binding = 0, .buffer = cube->uniform_buffer, .offset = 0, .size = sizeof(view_matrices_t), }; /* * Binding 1: Object texture view */ bind_group_entries[1] = (WGPUBindGroupEntry){ // Binding 1: Fragment shader color map image view .binding = 1, .textureView = cube->texture.view, }; /* * Binding 2: Object texture sampler */ bind_group_entries[2] = (WGPUBindGroupEntry){ // Binding 2: Fragment shader color map image sampler .binding = 2, .sampler = cube->texture.sampler, }; // Create the bind group cube->bind_group = wgpuDeviceCreateBindGroup( wgpu_context->device, &(WGPUBindGroupDescriptor){ .layout = bind_group_layout, .entryCount = (uint32_t)ARRAY_SIZE(bind_group_entries), .entries = bind_group_entries, }); ASSERT(cube->bind_group != NULL) } } static void setup_render_pass(wgpu_context_t* wgpu_context) { // Color attachment rp_color_att_descriptors[0] = (WGPURenderPassColorAttachment) { .view = NULL, .loadOp = WGPULoadOp_Clear, .storeOp = WGPUStoreOp_Store, .clearColor = (WGPUColor) { .r = 0.0f, .g = 0.0f, .b = 0.0f, .a = 1.0f, }, }; // Depth attachment wgpu_setup_deph_stencil(wgpu_context, NULL); // Render pass descriptor render_pass_desc = (WGPURenderPassDescriptor){ .colorAttachmentCount = 1, .colorAttachments = rp_color_att_descriptors, .depthStencilAttachment = &wgpu_context->depth_stencil.att_desc, }; } static void prepare_pipelines(wgpu_context_t* wgpu_context) { // Create a pipeline layout used for our graphics pipeline pipeline_layout = wgpuDeviceCreatePipelineLayout( wgpu_context->device, &(WGPUPipelineLayoutDescriptor){ .bindGroupLayoutCount = 1, // The pipeline layout is based on the bind group layout we created above .bindGroupLayouts = &bind_group_layout, }); ASSERT(pipeline_layout != NULL) // Construct the different states making up the pipeline // Primitive state WGPUPrimitiveState primitive_state_desc = { .topology = WGPUPrimitiveTopology_TriangleList, .frontFace = WGPUFrontFace_CCW, .cullMode = WGPUCullMode_Back, }; // Color target state WGPUBlendState blend_state = wgpu_create_blend_state(false); WGPUColorTargetState color_target_state_desc = (WGPUColorTargetState){ .format = wgpu_context->swap_chain.format, .blend = &blend_state, .writeMask = WGPUColorWriteMask_All, }; // Depth stencil state WGPUDepthStencilState depth_stencil_state_desc = wgpu_create_depth_stencil_state(&(create_depth_stencil_state_desc_t){ .format = WGPUTextureFormat_Depth24PlusStencil8, .depth_write_enabled = true, }); // Vertex buffer layout WGPU_GLTF_VERTEX_BUFFER_LAYOUT( cube, // Location 0: Position WGPU_GLTF_VERTATTR_DESC(0, WGPU_GLTF_VertexComponent_Position), // Location 1: Vertex normal WGPU_GLTF_VERTATTR_DESC(1, WGPU_GLTF_VertexComponent_Normal), // Location 2: Texture coordinates WGPU_GLTF_VERTATTR_DESC(2, WGPU_GLTF_VertexComponent_UV), // Location 3: Vertex color WGPU_GLTF_VERTATTR_DESC(3, WGPU_GLTF_VertexComponent_Color)); // Vertex state WGPUVertexState vertex_state_desc = wgpu_create_vertex_state( wgpu_context, &(wgpu_vertex_state_t){ .shader_desc = (wgpu_shader_desc_t){ // Vertex shader SPIR-V .file = "shaders/bind_groups/cube.vert.spv", }, .buffer_count = 1, .buffers = &cube_vertex_buffer_layout, }); // Fragment state WGPUFragmentState fragment_state_desc = wgpu_create_fragment_state( wgpu_context, &(wgpu_fragment_state_t){ .shader_desc = (wgpu_shader_desc_t){ // Fragment shader SPIR-V .file = "shaders/bind_groups/cube.frag.spv", }, .target_count = 1, .targets = &color_target_state_desc, }); // Multisample state WGPUMultisampleState multisample_state_desc = wgpu_create_multisample_state_descriptor( &(create_multisample_state_desc_t){ .sample_count = 1, }); // Create rendering pipeline using the specified states pipeline = wgpuDeviceCreateRenderPipeline( wgpu_context->device, &(WGPURenderPipelineDescriptor){ .label = "cube_render_pipeline", .layout = pipeline_layout, .primitive = primitive_state_desc, .vertex = vertex_state_desc, .fragment = &fragment_state_desc, .depthStencil = &depth_stencil_state_desc, .multisample = multisample_state_desc, }); // Partial cleanup WGPU_RELEASE_RESOURCE(ShaderModule, vertex_state_desc.module); WGPU_RELEASE_RESOURCE(ShaderModule, fragment_state_desc.module); } static void update_uniform_buffers(wgpu_example_context_t* context) { static vec3 translations[2] = { {-2.0f, 0.0f, 0.0f}, // Cube 1 {1.5f, 0.5f, 0.0f}, // Cube 2 }; camera_t* camera = context->camera; for (uint8_t i = 0; i < (uint8_t)ARRAY_SIZE(cubes); ++i) { cube_t* cube = &cubes[i]; glm_mat4_identity(cube->matrices.model); glm_translate(cube->matrices.model, translations[i]); glm_mat4_copy(camera->matrices.perspective, cube->matrices.projection); glm_mat4_copy(camera->matrices.view, cube->matrices.view); glm_rotate(cube->matrices.model, glm_rad(cube->rotation[0]), (vec3){1.0f, 0.0f, 0.0f}); glm_rotate(cube->matrices.model, glm_rad(cube->rotation[1]), (vec3){0.0f, 1.0f, 0.0f}); glm_rotate(cube->matrices.model, glm_rad(cube->rotation[2]), (vec3){0.0f, 0.0f, 1.0f}); glm_scale(cube->matrices.model, (vec3){0.25f, 0.25f, 0.25f}); wgpu_queue_write_buffer(context->wgpu_context, cube->uniform_buffer, 0, &cube->matrices, sizeof(view_matrices_t)); } } static void prepare_uniform_buffers(wgpu_example_context_t* context) { // Vertex shader matrix uniform buffer block for (uint8_t i = 0; i < (uint8_t)ARRAY_SIZE(cubes); ++i) { cube_t* cube = &cubes[i]; WGPUBufferDescriptor uniform_buffer_desc = { .usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst, .size = sizeof(view_matrices_t), .mappedAtCreation = false, }; cube->uniform_buffer = wgpuDeviceCreateBuffer(context->wgpu_context->device, &uniform_buffer_desc); ASSERT(cube->uniform_buffer != NULL); } update_uniform_buffers(context); } static int example_initialize(wgpu_example_context_t* context) { if (context) { setup_camera(context); load_assets(context->wgpu_context); prepare_uniform_buffers(context); setup_bind_groups(context->wgpu_context); prepare_pipelines(context->wgpu_context); setup_render_pass(context->wgpu_context); prepared = true; return 0; } return 1; } static void example_on_update_ui_overlay(wgpu_example_context_t* context) { if (imgui_overlay_header("Settings")) { imgui_overlay_checkBox(context->imgui_overlay, "Animate", &animate); } } static WGPUCommandBuffer build_command_buffer(wgpu_context_t* wgpu_context) { // Set target frame buffer rp_color_att_descriptors[0].view = wgpu_context->swap_chain.frame_buffer; // Create command encoder wgpu_context->cmd_enc = wgpuDeviceCreateCommandEncoder(wgpu_context->device, NULL); // Create render pass encoder for encoding drawing commands wgpu_context->rpass_enc = wgpuCommandEncoderBeginRenderPass( wgpu_context->cmd_enc, &render_pass_desc); // Bind the rendering pipeline wgpuRenderPassEncoderSetPipeline(wgpu_context->rpass_enc, pipeline); // Set viewport wgpuRenderPassEncoderSetViewport( wgpu_context->rpass_enc, 0.0f, 0.0f, (float)wgpu_context->surface.width, (float)wgpu_context->surface.height, 0.0f, 1.0f); // Set scissor rectangle wgpuRenderPassEncoderSetScissorRect(wgpu_context->rpass_enc, 0u, 0u, wgpu_context->surface.width, wgpu_context->surface.height); // Render cubes with separate bind groups for (uint8_t i = 0; i < (uint8_t)ARRAY_SIZE(cubes); ++i) { // Bind the cube's bind group. This tells the command buffer to use the // uniform buffer and image set for this cube wgpuRenderPassEncoderSetBindGroup(wgpu_context->rpass_enc, 0, cubes[i].bind_group, 0, 0); wgpu_gltf_model_draw(model, (wgpu_gltf_model_render_options_t){0}); } // End render pass wgpuRenderPassEncoderEndPass(wgpu_context->rpass_enc); WGPU_RELEASE_RESOURCE(RenderPassEncoder, wgpu_context->rpass_enc) // Draw ui overlay draw_ui(wgpu_context->context, example_on_update_ui_overlay); // Get command buffer WGPUCommandBuffer command_buffer = wgpu_get_command_buffer(wgpu_context->cmd_enc); WGPU_RELEASE_RESOURCE(CommandEncoder, wgpu_context->cmd_enc) return command_buffer; } static int example_draw(wgpu_example_context_t* context) { // Prepare frame prepare_frame(context); // Command buffer to be submitted to the queue wgpu_context_t* wgpu_context = context->wgpu_context; wgpu_context->submit_info.command_buffer_count = 1; wgpu_context->submit_info.command_buffers[0] = build_command_buffer(context->wgpu_context); // Submit to queue submit_command_buffers(context); // Submit frame submit_frame(context); return 0; } static int example_render(wgpu_example_context_t* context) { if (!prepared) { return 1; } const int draw_result = example_draw(context); if (animate) { cubes[0].rotation[0] += 2.5f * context->frame_timer; if (cubes[0].rotation[0] > 360.0f) { cubes[0].rotation[0] -= 360.0f; } cubes[1].rotation[1] += 2.0f * context->frame_timer; if (cubes[1].rotation[1] > 360.0f) { cubes[1].rotation[1] -= 360.0f; } update_uniform_buffers(context); } return draw_result; } static void example_on_view_changed(wgpu_example_context_t* context) { update_uniform_buffers(context); } static void example_destroy(wgpu_example_context_t* context) { camera_release(context->camera); wgpu_gltf_model_destroy(model); for (uint8_t i = 0; i < (uint8_t)ARRAY_SIZE(cubes); ++i) { wgpu_destroy_texture(&cubes[i].texture); WGPU_RELEASE_RESOURCE(Buffer, cubes[i].uniform_buffer) WGPU_RELEASE_RESOURCE(BindGroup, cubes[i].bind_group) } WGPU_RELEASE_RESOURCE(RenderPipeline, pipeline) WGPU_RELEASE_RESOURCE(PipelineLayout, pipeline_layout) WGPU_RELEASE_RESOURCE(BindGroupLayout, bind_group_layout) } void example_bind_groups(int argc, char* argv[]) { // clang-format off example_run(argc, argv, &(refexport_t){ .example_settings = (wgpu_example_settings_t){ .title = example_title, .overlay = true, }, .example_initialize_func = &example_initialize, .example_render_func = &example_render, .example_destroy_func = &example_destroy, .example_on_view_changed_func = &example_on_view_changed, }); // clang-format on }
32.330784
97
0.679283
[ "render", "object", "model" ]
b292722ae918e6ad529b0432d237522923aa096b
1,828
h
C
open/Inspur/code/resnet/schedule/src/schedule/gpu_schedule_node.h
EldritchJS/inference_results_v0.5
5552490e184d9fc342d871fcc410ac423ea49053
[ "Apache-2.0" ]
null
null
null
open/Inspur/code/resnet/schedule/src/schedule/gpu_schedule_node.h
EldritchJS/inference_results_v0.5
5552490e184d9fc342d871fcc410ac423ea49053
[ "Apache-2.0" ]
null
null
null
open/Inspur/code/resnet/schedule/src/schedule/gpu_schedule_node.h
EldritchJS/inference_results_v0.5
5552490e184d9fc342d871fcc410ac423ea49053
[ "Apache-2.0" ]
1
2019-12-05T18:53:17.000Z
2019-12-05T18:53:17.000Z
#pragma once #include "../common/macro.h" #include "../config/node.h" #include "../config/parser.h" #include "inner_thread.h" #include "data_set.h" #include "blocking_queue.h" #include "schedule.h" using namespace std; namespace schedule { class GpuScheduleParam { CREATE_SIMPLE_ATTR_SET_GET(m_thread_num, size_t) CREATE_SIMPLE_ATTR_SET_GET(m_queue_depth, size_t) CREATE_SIMPLE_ATTR_SET_GET(m_batch_size, size_t) public: void Construct(GpuScheduleParam& param) { m_thread_num = param.m_thread_num; m_queue_depth = param.m_queue_depth; m_batch_size = param.m_batch_size; } GpuScheduleParam(size_t thread_num, size_t queue_depth, size_t batch_size) { m_thread_num = thread_num; m_queue_depth = queue_depth; m_batch_size = batch_size; } GpuScheduleParam(GpuScheduleParam& param) { Construct(param); } GpuScheduleParam(GpuScheduleParam&& param) noexcept { Construct(param); } GpuScheduleParam& operator=(GpuScheduleParam&& param) noexcept { Construct(param); return *this; } virtual ~GpuScheduleParam() {}; }; class GpuScheduleNode : public ScheduleNode, public InnerThread { CREATE_SIMPLE_ATTR_SET_GET(m_param, GpuScheduleParam) public: GpuScheduleNode(string name, string type, vector<string> bottom, vector<string> top, GpuScheduleParam param) : ScheduleNode(name, type, bottom, top), InnerThread(param.get_m_thread_num()), m_param(param) {}; ~GpuScheduleNode() {}; void Init(); void Run(); void Finalize(); void EntryMulti(size_t thread_id); }; class InputFile; class GpuScheduleNodeParser : public NodeParser { public: GpuScheduleNodeParser(InputFile* pfile, Config* pconf) : NodeParser(pfile, pconf) {}; ~GpuScheduleNodeParser() {}; shared_ptr<GpuScheduleNode> Run(Node node); GpuScheduleParam ParseParam(); }; }
25.388889
87
0.741247
[ "vector" ]
b2977a9c5f8c1ffb6e9d79ea6c2d1f364d686ef9
1,957
c
C
src/minigames/worms/update.c
OutbackMan/tetris
617b54770aa239ee92dfb8f4f71df2ce7f8d4449
[ "CC-BY-4.0", "MIT" ]
null
null
null
src/minigames/worms/update.c
OutbackMan/tetris
617b54770aa239ee92dfb8f4f71df2ce7f8d4449
[ "CC-BY-4.0", "MIT" ]
4
2018-05-14T05:31:19.000Z
2018-05-14T06:11:46.000Z
src/minigames/worms/update.c
OutbackMan/tetris
617b54770aa239ee92dfb8f4f71df2ce7f8d4449
[ "CC-BY-4.0", "MIT" ]
null
null
null
GAME_HOT GAME_INTERNAL void game_update(G_Game* game, float delta_time) { system_physics(game, delta_time); for (all_physics_objects) { obj->ay += 2.0f; // gravity obj->vx += obj->ax * delta_time; obj->vy += obj->ay * delta_time; float potential_x = obj->px + obj->vx * delta_time; float potential_y = obj->py + obj->vy * delta_time; obj->ax = 0.0f; obj->ay = 0.0f; obj->is_stable = false; float collision_angle = atan2f(obj->vx, obj->vy); float response_x = 0.0f; float response_y = 0.0f; bool collision_encountered = false; // circle and rectangle collisions take similar times to perform, so pick the one that makes most sense for context and that allows to minimise function calls // iterate through semicircle // have arbitrarily chosen small increment to ensure a sufficient amount of pixels are tested for (float r = collision_angle - PI / 2; r < collision_angle + PI / 2; r += PI / 8.0f) { float test_pos_x = obj->collision_radius * cosf(r) + potential_x; float test_pos_y = obj->collision_radius * sinf(r) + potential_y; // clamp test values (always do when reading from memory) if (map[(int)test_pos_y * map_width + (int)test_pos_x] != SKY) { response_x += potential_x - test_pos_x; response_y += potential_y - test_pos_y; collision_encountered = true; } } if (collision_encountered) { // response vector as normal to tangent of terrain // used for reflection calculation for bounce obj->stable = true; float velocity_magnitude = sqrtf(obj->px*obj->px + obj->py*obj->py); float response_magnitude = sqrtf(response_x*response_x + response_y*response_y); // calculate reflection vector // account for friction } else { obj->px = potential_x; obj->py = potential_y; } if (obj->is_dead) { int on_dead_response = dead_response(obj); if (on_dead_response == EXPLODE) { boom(x, y); } } if (fire_weapon) { } } }
30.107692
160
0.67859
[ "vector" ]
c32de713afc88786396f8a6bb5913c6bce21641c
2,214
h
C
S0006E-Graphics/lab-env-master/projects/GPLabb1/code/vector3D.h
miraz12/Projects
ae24a4caa347f74f7ccc36014e8f7b0f801d47db
[ "MIT" ]
null
null
null
S0006E-Graphics/lab-env-master/projects/GPLabb1/code/vector3D.h
miraz12/Projects
ae24a4caa347f74f7ccc36014e8f7b0f801d47db
[ "MIT" ]
null
null
null
S0006E-Graphics/lab-env-master/projects/GPLabb1/code/vector3D.h
miraz12/Projects
ae24a4caa347f74f7ccc36014e8f7b0f801d47db
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <iostream> #include <cmath> class vector3D { public: float* Varray; int SIZE; vector3D(void) { this->Varray = new float[3]; SIZE = 3; } vector3D::~vector3D(void) { } //�verlagrar brackets f�r att kunna skriva a[x] = 1; float& operator[](int n) { return this->Varray[n]; } //Till�ter addition med en vektor och en vektor inline vector3D& operator+(const vector3D& m) { vector3D temp = *this; for (int i = 0; i < SIZE; i++) { temp.Varray[i] += m.Varray[i]; } std::cout << temp; return temp; } //Till�ter subtraktion med en vektor och en vektor inline vector3D& operator-(const vector3D& m) { vector3D temp = *this; for (int i = 0; i < SIZE; i++) { temp.Varray[i] -= m.Varray[i]; } std::cout << temp; return temp; } //Skickar tillbaka produkten av en vektor och en float inline vector3D& operator*(float m) { vector3D temp = *this; for (int i = 0; i < SIZE; i++) { temp.Varray[i] *= m; } std::cout << temp; return temp; } //Skal�rprodukten inline float dott(vector3D m) { float p = 0; for (int i = 0; i < this->length(); i++) { p += this->Varray[i] * m.Varray[i]; } std::cout << p << "\n"; return p; } //Kryssprodukten inline vector3D cross(vector3D m) { vector3D v; v.Varray[0] = (this->Varray[1] * m.Varray[2]) - (this->Varray[2] * m.Varray[1]); v.Varray[1] = (this->Varray[2] * m.Varray[0]) - (this->Varray[0] * m.Varray[2]); v.Varray[2] = (this->Varray[0] * m.Varray[1]) - (this->Varray[1] * m.Varray[0]); return v; } //Ger l�ngden av en vektor inline float length(void) { float l = 0; for (int i = 0; i < SIZE; i++) { l += pow(this->Varray[i], 2); } return sqrt(l); } //Normaliserar vektorn inline void normalize(void) { float l = this->length(); for (int i = 0; i < SIZE; i++) { this->Varray[i] = (this->Varray[i] / l); } } //S�tter alla v�rden i vektorn till "v" inline void setValues(float v) { for (int i = 0; i < SIZE; i++) { this->Varray[i] = v; } } //Till�ter en att skriva ut en vector med ostream inline friend std::ostream& operator<<(std::ostream& os, vector3D m) { for (int i = 0; i < m.SIZE; i++) { os << m.Varray[i] << "\t"; os << std::endl; } return os; } };
14.376623
81
0.595303
[ "vector" ]
c3321fb569c4820f22d854a5271b908c8779bfd3
2,203
h
C
DarkSpace/TraitOrbit.h
SnipeDragon/darkspace
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
[ "MIT" ]
1
2016-05-22T21:28:29.000Z
2016-05-22T21:28:29.000Z
DarkSpace/TraitOrbit.h
SnipeDragon/darkspace
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
[ "MIT" ]
null
null
null
DarkSpace/TraitOrbit.h
SnipeDragon/darkspace
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
[ "MIT" ]
null
null
null
/* TraitOrbit.h This trait allows the noun to orbit other nouns (c)2004 Palestar Inc, Richard Lyle */ #ifndef TRAITORBIT_H #define TRAITORBIT_H #include "World/Trait.h" #include "World/TraitMovement.h" #include "NounGame.h" #include "GameDll.h" //---------------------------------------------------------------------------- class DLL TraitOrbit : public Trait { public: DECLARE_WIDGET_CLASS(); DECLARE_PROPERTY_LIST(); // Construction TraitOrbit(); //! Widget interface bool read( const InStream & input ); bool write( const OutStream & output ); // Trait interface void initialize(); void simulate( dword nTick ); // Accessors Noun * orbiting() const; // object we are orbiting float orbitDistance() const; // distance from the object float orbitPosition() const; // position around the object in radians float orbitVelocity() const; // orbital velocity in radians per second float rotationalVelocity() const; // rotational velocity in radians per second // Mutators void setOrbit( Noun * pOrbit, float fDistance, float fPosition, float fVelocity, dword nTick ); void setRotationalVelocity( float a_fRotVelocity ); void breakOrbit(); void dynamics( dword nTick ); private: // Data Noun::wRef m_pOrbiting; // who are we oribiting float m_fOrbitDistance; // distance from the object float m_fOrbitPosition; // in radians float m_fOrbitVelocity; // in r/s float m_fRotVelocity; dword m_nBaseTick; Vector3 m_vLastPosition; TraitMovement::WeakRef m_pMovement; }; //---------------------------------------------------------------------------- inline Noun * TraitOrbit::orbiting() const { return m_pOrbiting; } inline float TraitOrbit::orbitDistance() const { return m_fOrbitDistance; } inline float TraitOrbit::orbitPosition() const { return m_fOrbitPosition; } inline float TraitOrbit::orbitVelocity() const { return m_fOrbitVelocity; } inline float TraitOrbit::rotationalVelocity() const { return m_fRotVelocity; } //---------------------------------------------------------------------------- #endif //---------------------------------------------------------------------------- //EOF
22.479592
81
0.621425
[ "object" ]
c332fa398aeb8ff52e9e2abc0850c2faadfa2260
2,261
h
C
q1/mac937_hw16_stack.h
mike10004/cs-bridge-2020-hw16
bc8ff6f7cf7b63c74dbe963c540fe1b11c4288dc
[ "MIT" ]
null
null
null
q1/mac937_hw16_stack.h
mike10004/cs-bridge-2020-hw16
bc8ff6f7cf7b63c74dbe963c540fe1b11c4288dc
[ "MIT" ]
null
null
null
q1/mac937_hw16_stack.h
mike10004/cs-bridge-2020-hw16
bc8ff6f7cf7b63c74dbe963c540fe1b11c4288dc
[ "MIT" ]
null
null
null
#ifndef HW16_MAC937_HW16_STACK_H #define HW16_MAC937_HW16_STACK_H #include <cassert> #include <vector> #include <iostream> template<class T> struct StackNode { public: StackNode(const T& content, StackNode<T>* under) : content(content), under(under) {} T content; StackNode<T>* under; }; template<class T> class Stack { public: Stack() : top_(nullptr) {} ~Stack(); void Push(const T& element); T Pop(bool& valid); T Pop(); void Clear(); bool IsEmpty() const; std::vector<T> CopyToVector() const; Stack(Stack<T>& other); Stack<T>& operator=(const Stack<T>& other); private: StackNode<T>* top_; StackNode<T>* Clone(const StackNode<T>* node) const; }; template<class T> Stack<T>::~Stack() { Clear(); } template<class T> void Stack<T>::Push(const T &element) { StackNode<T>* new_top = new StackNode<T>(element, top_); top_ = new_top; } template<class T> T Stack<T>::Pop(bool& valid) { if (top_ == nullptr) { valid = false; return T(); } valid = true; StackNode<T>* top = top_; T top_value = top->content; top_ = top->under; delete top; return top_value; } template<class T> T Stack<T>::Pop() { bool valid; return Pop(valid); } template<class T> void Stack<T>::Clear() { while (top_ != nullptr) { StackNode<T>* top = top_; top_ = top->under; delete top; } } template<class T> bool Stack<T>::IsEmpty() const { return top_ == nullptr; } template<class T> std::vector<T> Stack<T>::CopyToVector() const { std::vector<T> items; for (StackNode<T>* current = top_; current != nullptr; current = current->under) { items.push_back(current->content); } return items; } template <class T> Stack<T>& Stack<T>::operator=(const Stack<T>& other) { if (this == &other) { return *this; } Clear(); top_ = Clone(other.top_); return *this; } template<class T> Stack<T>::Stack(Stack<T> &other) { *this = other; } template<class T> StackNode<T> *Stack<T>::Clone(const StackNode<T> *node) const { if (node == nullptr) { return nullptr; } return new StackNode<T>(node->content, Clone(node->under)); } #endif //HW16_MAC937_HW16_STACK_H
20.00885
88
0.612119
[ "vector" ]
c333f9e96a5e4eecb43cbb6ea43c4a916ec45ef0
7,415
h
C
gui/QvisSaveWindow.h
ahota/visit_ospray
d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9
[ "BSD-3-Clause" ]
null
null
null
gui/QvisSaveWindow.h
ahota/visit_ospray
d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9
[ "BSD-3-Clause" ]
null
null
null
gui/QvisSaveWindow.h
ahota/visit_ospray
d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9
[ "BSD-3-Clause" ]
null
null
null
/***************************************************************************** * * Copyright (c) 2000 - 2014, Lawrence Livermore National Security, LLC * Produced at the Lawrence Livermore National Laboratory * LLNL-CODE-442911 * All rights reserved. * * This file is part of VisIt. For details, see https://visit.llnl.gov/. The * full copyright notice is contained in the file COPYRIGHT located at the root * of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html. * * 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 disclaimer below. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the disclaimer (as noted below) in the * documentation and/or other materials provided with the distribution. * - Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY, * LLC, THE U.S. DEPARTMENT OF ENERGY 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. * *****************************************************************************/ #ifndef QVIS_SAVE_WINDOW_H #define QVIS_SAVE_WINDOW_H #include <gui_exports.h> #include <QvisPostableWindowObserver.h> // Forward declarations. class QCheckBox; class QComboBox; class QGroupBox; class QLabel; class QLineEdit; class QPushButton; class QSlider; class SaveWindowAttributes; class QRadioButton; class QButtonGroup; class QvisOpacitySlider; // **************************************************************************** // Class: QvisSaveWindow // // Purpose: // This class contains the code necessary to create a window that // observes the save image attributes. // // Notes: // // Programmer: Brad Whitlock // Creation: Fri Feb 9 16:46:07 PST 2001 // // Modifications: // Brad Whitlock, Wed Jan 23 15:13:23 PST 2002 // Added quality and progressive toggles. // // Hank Childs, Fri May 24 07:45:52 PDT 2002 // Renamed SaveImageAtts to SaveWindowAtts. Added support for STL. // // Hank Childs, Sun May 26 17:31:18 PDT 2002 // Added a toggle for binary vs ASCII. // // Kathleen Bonnell, Thu Nov 13 12:14:30 PST 2003 // Added combo box for compression type. // // Brad Whitlock, Fri Jul 30 15:14:44 PST 2004 // Added save path and a slot to save the image. // // Kathleen Bonnell, Wed Dec 15 08:20:11 PST 2004 // Added slot 'saveButtonClicked'. // // Jeremy Meredith, Thu Apr 5 17:23:37 EDT 2007 // Added button to force a merge of parallel geometry. // // Brad Whitlock, Wed Apr 9 10:56:15 PDT 2008 // QString for caption, shortName. // // Hank Childs, Thu Jul 22 09:55:03 PDT 2010 // Added support for multi-window saves. Also re-orged window some to // put check boxes close to the functionality they go with. // // Brad Whitlock, Wed Aug 25 13:32:46 PDT 2010 // I moved some code into helper methods. // // **************************************************************************** class GUI_API QvisSaveWindow : public QvisPostableWindowObserver { Q_OBJECT public: QvisSaveWindow(SaveWindowAttributes *subj, const QString &caption = QString::null, const QString &shortName = QString::null, QvisNotepadArea *notepad = 0); virtual ~QvisSaveWindow(); public slots: virtual void apply(); protected: virtual void CreateWindowContents(); void UpdateWindow(bool doAll); void GetCurrentValues(int which_widget); void Apply(bool ignore = false); QWidget *StandardTab(QWidget *); QWidget *AdvancedTab(QWidget *); protected slots: void outputToCurrentDirectoryToggled(bool); void processOutputDirectoryText(); void processFilenameText(); void familyToggled(bool); void stereoToggled(bool); void fileFormatChanged(int); void resConstraintToggled(bool); void processWidthText(); void processHeightText(); void progressiveToggled(bool); void binaryToggled(bool); void qualityChanged(int); void screenCaptureToggled(bool); void saveTiledToggled(bool); void compressionTypeChanged(int); void saveWindow(); void selectOutputDirectory(); void saveButtonClicked(); void forceMergeToggled(bool); void advancedMultiWinSaveToggled(bool); void processmwsWidthText(); void processmwsHeightText(); void mwsWindowComboBoxChanged(int); void processmwsIndWidthText(); void processmwsIndHeightText(); void processmwsPosXText(); void processmwsPosYText(); void mwsLayerComboBoxChanged(int); void omitWindowCheckBoxToggled(bool); void imageTransparencyChanged(int); private: int currentWindow; QCheckBox *outputToCurrentDirectoryCheckBox; QLabel *outputDirectoryLabel; QLineEdit *outputDirectoryLineEdit; QPushButton *outputDirectorySelectButton; QLineEdit *filenameLineEdit; QCheckBox *familyCheckBox; QCheckBox *stereoCheckBox; QCheckBox *stereoCheckBox2; QComboBox *fileFormatComboBox; QLabel *qualityLabel; QSlider *qualitySlider; QLabel *compressionTypeLabel; QComboBox *compressionTypeComboBox; QCheckBox *progressiveCheckBox; QCheckBox *binaryCheckBox; QGroupBox *resolutionBox; QButtonGroup *resConstraintButtonGroup; QRadioButton *noResButton; QRadioButton *oneToOneResButton; QRadioButton *screenResButton; QLineEdit *widthLineEdit; QLineEdit *heightLineEdit; QCheckBox *screenCaptureCheckBox; QCheckBox *saveTiledCheckBox; QCheckBox *forceMergeCheckBox; QCheckBox *advancedMultiWinSaveCheckBox; QLineEdit *mwsWidthLineEdit; QLineEdit *mwsHeightLineEdit; QComboBox *mwsWindowComboBox; QLineEdit *mwsIndWidthLineEdit; QLineEdit *mwsIndHeightLineEdit; QLineEdit *mwsPosXLineEdit; QLineEdit *mwsPosYLineEdit; QComboBox *mwsLayerComboBox; QCheckBox *omitWindowCheckBox; QvisOpacitySlider *imageTransparency; SaveWindowAttributes *saveWindowAtts; }; #endif
37.449495
79
0.667701
[ "geometry" ]
c33dd440a23602052fc1ca380e0a96703296877b
1,261
h
C
homeworks/ConsLawWithSource/templates/consformevl.h
kryo4096/NPDECODES
3498c0e4abec6ba21447849ba2ddc9286c068ea1
[ "MIT" ]
15
2019-04-29T11:28:56.000Z
2022-03-22T05:10:58.000Z
homeworks/ConsLawWithSource/templates/consformevl.h
kryo4096/NPDECODES
3498c0e4abec6ba21447849ba2ddc9286c068ea1
[ "MIT" ]
12
2020-02-29T15:05:58.000Z
2022-02-21T13:51:07.000Z
homeworks/ConsLawWithSource/templates/consformevl.h
kryo4096/NPDECODES
3498c0e4abec6ba21447849ba2ddc9286c068ea1
[ "MIT" ]
26
2020-01-09T15:59:23.000Z
2022-03-24T16:27:33.000Z
// Demonstration code for course Numerical Methods for Partial Differential // Equations Author: R. Hiptmair, SAM, ETH Zurich Date: May 2020 #ifndef CONSFORMEVL_H_ #define CONSFORMEVL_H_ #include <Eigen/Dense> namespace ConsFV { using namespace Eigen; // \ref{cpp:fluxdiff} in lecture notes // arguments: (Finite) state vector \Blue{$\mu$} of cell averages, see // \eqref{eq:cellavg} // Functor \Blue{$F : \mathbb R \times \mathbb R \mapsto \mathbb R$}, 2-point // numerical flux // return value: Vector with differences of numerical fluxes, which provides // the right hand side of \eqref{eq:2pcf} template <typename FunctionF> VectorXd fluxdiff(const VectorXd &mu, FunctionF &&F) { unsigned n = mu.size(); // length of state vector VectorXd fd = VectorXd::Zero(n); // return vector // constant continuation of data for \Blue{$x\leq a$}! fd[0] = F(mu[0], mu[1]) - F(mu[0], mu[0]); for (unsigned j = 1; j < n - 1; ++j) { fd[j] = F(mu[j], mu[j + 1]) - F(mu[j - 1], mu[j]); // see \eqref{eq:2pcf} } // constant continuation of data for \Blue{$x\geq b$}! fd[n - 1] = F(mu[n - 1], mu[n - 1]) - F(mu[n - 2], mu[n - 1]); // Efficient thanks to return value optimization (RVO) return fd; } } // namespace ConsFV #endif
31.525
78
0.648692
[ "vector" ]
c340f13beda4ccf55bb5fec374b5c40dde619f7a
1,240
c
C
src/enemy_chase.c
HHP267/Game2D
d9ac052d91c35c0371a3baa8ef48865b7d3faaa5
[ "MIT" ]
null
null
null
src/enemy_chase.c
HHP267/Game2D
d9ac052d91c35c0371a3baa8ef48865b7d3faaa5
[ "MIT" ]
null
null
null
src/enemy_chase.c
HHP267/Game2D
d9ac052d91c35c0371a3baa8ef48865b7d3faaa5
[ "MIT" ]
null
null
null
#include "simple_logger.h" #include <SDL.h> #include "entity.h" #include "player.h" #include "enemy_chase.h" #include "shape.h" typedef struct{ int speed; float accel; float health, maxHealth; }ChaserStats; static ChaserStats data = { 3, 2.4, 0, 100 }; Entity *chaserSpawn(Vector2D position) { Entity *ent; ent = entity_new(); if (!ent) { slog("Failed to create walker"); return NULL; } ent->sprite = gf2d_sprite_load_image("images/monsterGreen.png", 56, 56, 16); ent->w = 55; ent->h = 49; vector2d_copy(ent->position, position); vector2d_set(ent->flip, 0, 0); vector2d_set(ent->facing, 1, 0); ent->frameRate = 0.1; ent->frameCount = 16; ent->update = chaserUpdate; ent->player = false; ent->enemy = true; ent->platform = false; ent->collect = false; ent->enter = false; ent->warp = false; return ent; } void chaserUpdate(Entity *self) { if (self->facing.x == -1) { self->velocity.x = 1.5; if (self->position.x >= 1150) { self->flip.x = 0; self->facing.x = 1; } } else if (self->facing.x == 1) { self->position.x = -1.5; if (self->position.x <= 650) { self->flip.x = 1; self->facing.x = -1; } } } /**/
17.971014
78
0.590323
[ "shape" ]
c34cf9f6355069eb0f7e0f3a795247b4a9773f4e
1,823
h
C
es-app/src/GameCollection.h
alextinti83/RetroStation
367249bdd2349db081001a8b8ea9111dc8a46f90
[ "Apache-2.0", "MIT" ]
1
2017-06-26T14:27:12.000Z
2017-06-26T14:27:12.000Z
es-app/src/GameCollection.h
alextinti83/RetroStation
367249bdd2349db081001a8b8ea9111dc8a46f90
[ "Apache-2.0", "MIT" ]
21
2017-05-14T19:36:37.000Z
2017-06-09T17:52:21.000Z
es-app/src/GameCollection.h
talex-tnt/RetroStation
367249bdd2349db081001a8b8ea9111dc8a46f90
[ "Apache-2.0", "MIT" ]
null
null
null
#pragma once #include <string> #include <map> #include <assert.h> #include "boost/filesystem/path.hpp" class FileData; class GameCollection { public: class Game { public: public: Game() : m_filedata(nullptr) { } Game(const FileData& fd) : m_filedata(&fd) { } const FileData& GetFiledata() const { assert(m_filedata); return *m_filedata; } bool IsValid() const { return m_filedata != nullptr; } private: const FileData* m_filedata; }; public: enum class Tag { None, Highlight, Hide }; GameCollection(const std::string& name, const std::string& folderPath); void Rename(const std::string& name); void EraseFile(); bool Deserialize(); bool Serialize(); bool HasGame(const FileData& filedata) const; void AddGame(const FileData& filedata); void RemoveGame(const FileData& filedata); void ClearAllGames(); const std::string& GetName() const; std::size_t GetGameCount() const; bool HasTag(Tag tag) const; void SetTag(Tag tag); GameCollection::Tag GetTag() const; // since we serialize/deserialize only key // we need to map filedatas to their respective key void ReplacePlaceholder(const FileData& filedata); public: static std::string GetTagName(Tag tag); static const std::vector<Tag> GetTags(); private: std::string GetFilePath(const boost::filesystem::path& folderPath) const; bool Deserialize(const boost::filesystem::path& folderPath); bool Serialize(const boost::filesystem::path& folderPath); std::string GetKey(const FileData& filedata) const; private: std::string m_name; std::string m_folderPath; using GamesMap = std::map<std::string, Game>; GamesMap mGamesMap; Tag m_tag; std::size_t m_invalidCount; private: static const std::map<GameCollection::Tag, std::string> k_tagsNames; static const std::map<std::string, GameCollection::Tag> k_namesTags; };
24.635135
81
0.735052
[ "vector" ]
c3548d85e91c041d192915f1757f3714f3fa10d2
892
h
C
Development/HeadMovement/Core/include/Stopwatch.h
sheldonrobinson/face-gesture-api
3c92f6033d667445067643399a73478f9449ebe2
[ "BSD-3-Clause" ]
null
null
null
Development/HeadMovement/Core/include/Stopwatch.h
sheldonrobinson/face-gesture-api
3c92f6033d667445067643399a73478f9449ebe2
[ "BSD-3-Clause" ]
null
null
null
Development/HeadMovement/Core/include/Stopwatch.h
sheldonrobinson/face-gesture-api
3c92f6033d667445067643399a73478f9449ebe2
[ "BSD-3-Clause" ]
null
null
null
#pragma once //! Class for time measurement. extern "C++" class __declspec(dllexport) Stopwatch { public: //! Constructor Stopwatch(void); //! Destructor ~Stopwatch(void); //! Reset timer. void Reset(void); //! Calculate frame per second from time delay. double GetFPS(void) const; //! Returns the elapsed time between the declaration of object (or since the last call of Reset method) and current time in second. double GetElapsedTimeSec(void) const; //! Returns the elapsed time between the declaration of object (or since the last call of Reset method) and current time in milli second. double GetElapsedTimeMilliSec(void) const; //! Returns the elapsed time between the declaration of object and current time in millisecond. double GetElapsedTimeFromStartSec(void) const; private: double elapsedTimeSec_; double startTime_; };
27.030303
141
0.726457
[ "object" ]
c360aa1c49a9e4d5b11953ec8f9040330d260198
20,739
c
C
src/nicaea_2.5/Cosmo/src/sn1a.c
danielgruen/ccv
722db5bab850bccba3c7c003e0416cefa6d94c62
[ "MIT" ]
2
2017-08-11T20:38:17.000Z
2021-01-08T03:19:03.000Z
src/nicaea_2.5/Cosmo/src/sn1a.c
danielgruen/ccv
722db5bab850bccba3c7c003e0416cefa6d94c62
[ "MIT" ]
null
null
null
src/nicaea_2.5/Cosmo/src/sn1a.c
danielgruen/ccv
722db5bab850bccba3c7c003e0416cefa6d94c62
[ "MIT" ]
null
null
null
/* ============================================================ * * sn1a.c * * Pierre Astier, Martin Kilbinger 2006-2009 * * ============================================================ */ #include "sn1a.h" cosmo_SN *init_parameters_SN(double OMEGAM, double OMEGADE, double W0_DE, double W1_DE, double *W_POLY_DE, int N_POLY_DE, double H100, double OMEGAB, double OMEGANUMASS, double NEFFNUMASS, double NORM, double NSPEC, nonlinear_t NONLINEAR, transfer_t TRANSFER, growth_t GROWTH, de_param_t DEPARAM, norm_t normmode, chi2mode_t CHI2MODE, double THETA1[], double THETA2[], double BETA_D, double AMIN, error **err) { cosmo_SN *res; int i; res = (cosmo_SN*)malloc_err(sizeof(cosmo_SN), err); forwardError(*err, __LINE__, NULL); res->cosmo = init_parameters(OMEGAM, OMEGADE, W0_DE, W1_DE, W_POLY_DE, N_POLY_DE, H100, OMEGAB, OMEGANUMASS, NEFFNUMASS, NORM, NSPEC, NONLINEAR, TRANSFER, GROWTH, DEPARAM, normmode, AMIN, err); forwardError(*err, __LINE__, 0); for (i=0; i<NDER; i++) { res->Theta1[i] = THETA1[i]; } for (i=0; i<NLCP; i++) { res->Theta2[i] = THETA2[i]; res->Theta2_denom[i] = THETA2[i]; } res->beta_d = BETA_D; res->chi2mode = CHI2MODE; return res; } cosmo_SN *copy_parameters_SN_only(cosmo_SN *source, error **err) { cosmo_SN* res; res = init_parameters_SN(source->cosmo->Omega_m, source->cosmo->Omega_de, source->cosmo->w0_de, source->cosmo->w1_de, source->cosmo->w_poly_de, source->cosmo->N_poly_de, source->cosmo->h_100, source->cosmo->Omega_b, source->cosmo->Omega_nu_mass, source->cosmo->Neff_nu_mass, source->cosmo->normalization, source->cosmo->n_spec, source->cosmo->nonlinear, source->cosmo->transfer, source->cosmo->growth, source->cosmo->de_param, source->cosmo->normmode, source->chi2mode, source->Theta1, source->Theta2, source->beta_d, source->cosmo->a_min, err); forwardError(*err, __LINE__, NULL); return res; } void read_cosmological_parameters_SN(cosmo_SN **self, FILE *F, error **err) { cosmo_SN *tmp; struct { char cosmo_file[128], nofz_file[128]; } tmp2; config_element c = {0, 0.0, ""}; FILE *FD; int i; char stmp[128]; tmp = set_cosmological_parameters_to_default_SN(err); forwardError(*err, __LINE__,); CONFIG_READ_S(&tmp2, cosmo_file, s, F, c, err); if (strcmp(tmp2.cosmo_file, "-")!=0) { FD = fopen_err(tmp2.cosmo_file, "r", err); forwardError(*err, __LINE__,); } else { FD = F; } read_cosmological_parameters(&tmp->cosmo, FD, err); forwardError(*err, __LINE__,); if (strcmp(tmp2.cosmo_file, "-")!=0) fclose(FD); /* SNIa parameters */ //CONFIG_READ_ARR(tmp, Theta1, d, i, NDER, s, F, c, err); /* Photometric calibrations */ CONFIG_READ_ARR(tmp, Theta2, d, i, NLCP, stmp, F, c, err); /* -M, alpha, -beta */ tmp->beta_d = tmp->stretch = tmp->color = 0.0; *self = copy_parameters_SN_only(tmp, err); forwardError(*err, __LINE__,); free_parameters_SN(&tmp); } void updateFrom_SN(cosmo_SN* avant, cosmo_SN* apres, error **err) { updateFrom(avant->cosmo, apres->cosmo, err); forwardError(*err, __LINE__,); } cosmo_SN* set_cosmological_parameters_to_default_SN(error **err) { int i; double theta1[NDER], theta2[NLCP], h100, amin, beta_d; for (i=0; i<NDER; i++) theta1[i] = 0.0; /* Astier 2006 */ h100 = 0.7; theta2[0] = 19.31 - 5.0*log10(h100/0.7); /* - M */ theta2[1] = 1.52; /* alpha */ theta2[2] = -1.57; /* -beta */ theta2[3] = 0.0; /* -beta_z */ beta_d = 0.0; amin = 1.0/(1.0+2.0); /* zmax of 2 is enough for SNLS */ return init_parameters_SN(0.26,0.74,-1.0,0.0,NULL,0,h100,0.04,0.0,0.0,0.85, 1.0,smith03,eisenhu,growth_de,linder,norm_s8, chi2_simple,theta1,theta2,beta_d,amin,err); } cosmo_SN* set_cosmological_parameters_to_best_fit_SNLS_WMAP5(error **err) { int i; double theta1[NDER], theta2[NLCP], h100, amin, beta_d; for (i=0; i<NDER; i++) theta1[i] = 0.0; /* Kilbinger et al. 2009 */ h100 = 0.719; theta2[0] = 19.3137 - 5.0*log10(h100/0.7); /* - M */ theta2[1] = 1.62; /* alpha */ theta2[2] = -1.80; /* -beta */ theta2[3] = 0.0; /* -beta_z */ beta_d = 0.0; amin = 1.0/(1.0+2.0); /* zmax of 2 is enough for SNLS */ return init_parameters_SN(0.257,0.743,-1.025,0.0,NULL,0,h100,0.0433,0.0,0.0,0.807, 0.962,smith03,eisenhu,growth_de,linder,norm_s8, chi2_simple,theta1,theta2,beta_d,amin,err); } cosmo_SN* set_cosmological_parameters_to_best_fit_SNLS(error **err) { int i; double theta1[NDER], theta2[NLCP], h100, amin, beta_d; for (i=0; i<NDER; i++) theta1[i] = 0.0; h100 = 0.719; theta2[0] = 19.306 - 5.0*log10(h100/0.7); /* - M */ theta2[1] = 1.515; /* alpha */ theta2[2] = -1.56; /* -beta */ theta2[3] = 0.0; /* -beta_z */ beta_d = 0.0; amin = 1.0/(1.0+2.0); /* zmax of 2 is enough for SNLS */ return init_parameters_SN(0.266,0.734,-1.0,0.0,NULL,0,h100,0.0433,0.0,0.0,0.807, 0.962,smith03,eisenhu,growth_de,linder,norm_s8, chi2_simple,theta1,theta2,beta_d,amin,err); } cosmo_SN* set_cosmological_parameters_to_best_fit_Union(error **err) { int i; double theta1[NDER], theta2[NLCP], h100, amin, beta_d; for (i=0; i<NDER; i++) theta1[i] = 0.0; h100 = 0.719; theta2[0] = 19.31 - 5.0*log10(h100/0.7); /* - M */ theta2[1] = 1.37; /* alpha */ theta2[2] = -2.45; /* -beta */ theta2[3] = 0.0; /* -beta_z */ beta_d = 0.0; amin = 1.0/(1.0+2.0); /* zmax of 2 is enough for Union */ return init_parameters_SN(0.291,0.709,-1.0,0.0,NULL,0,h100,0.0433,0.0,0.0,0.807, 0.962,smith03,eisenhu,growth_de,linder,norm_s8, chi2_simple,theta1,theta2,beta_d,amin,err); } cosmo_SN* set_cosmological_parameters_to_EdS_SN(error **err) { int i; double theta1[NDER], theta2[NLCP], h100, amin, beta_d; for (i=0; i<NDER; i++) theta1[i] = 0.0; /* Astier 2006 */ h100 = 0.7; theta2[0] = 19.31 - 5.0*log10(h100/0.7); /* - M */ theta2[1] = 1.52; theta2[2] = -1.57; theta2[3] = 0.0; beta_d = 0.0; amin = 1.0/(1.0+2.0); /* zmax of 2 is enough for SNLS */ return init_parameters_SN(1.0,0.0,-1.0,0.0,NULL,0,h100,0.04,0.0,0.0,0.85,1.0, smith03,eisenhu,growth_de,linder,norm_s8, chi2_simple,theta1,theta2,beta_d,amin,err); } void free_parameters_SN(cosmo_SN **self) { cosmo_SN *s; s = *self; free_parameters(&(s->cosmo)); free(s); s = NULL; } /* ************ I/O stuff */ void dump_param_SN(cosmo_SN *self, FILE *F) { int i; if (F==NULL) F = stderr; dump_param(self->cosmo, F); fprintf(F, "# "); for (i=0; i<NDER; i++) fprintf(F, " Th1%d", i); for (i=0; i<NLCP; i++) fprintf(F, " Th2%d", i); fprintf(F, " m\n"); fprintf(F, "# "); for (i=0; i<NDER; i++) fprintf(F, "% .3f", self->Theta1[i]); for (i=0; i<NLCP; i++) fprintf(F, "% 7.3f", self->Theta2[i]); fprintf(F, " %d\n", self->chi2mode); } /* Reads a single line of supernovae data */ void readSnData(char *line, SnData *sndata, sndatformat_t sndatformat, error **err) { char nm[100], *p=line; int ok, k; int nread=0; ok = sscanf(p,"%s %n",nm, &nread); testErrorRet(ok!=1, ce_file, "Bad line", *err, __LINE__,); /* on s'en fou du nom */ p += nread; ok = read_double(&p,&(sndata->z)); testErrorRet(ok==0, ce_file, "Bad line", *err, __LINE__, ); ok = read_double(&p,&(sndata->musb)); testErrorRet(ok==0, ce_file, "Bad line", *err, __LINE__, ); ok = read_double(&p,&(sndata->cov[0][0])); testErrorRet(ok==0, ce_file, "Bad line", *err, __LINE__, ); ok = read_double(&p,&(sndata->s)); testErrorRet(ok==0, ce_file, "Bad line", *err, __LINE__, ); ok = read_double(&p,&(sndata->cov[1][1])); testErrorRet(ok==0, ce_file, "Bad line", *err, __LINE__, ); ok = read_double (&p,&(sndata->c)); testErrorRet(ok==0, ce_file, "Bad line", *err, __LINE__, ); ok = read_double(&p,&(sndata->cov[2][2])); testErrorRet(ok==0, ce_file, "Bad line", *err, __LINE__, ); ok = read_double(&p,&(sndata->cov[0][1])); testErrorRet(ok==0, ce_file, "Bad line", *err, __LINE__, ); ok = read_double(&p,&(sndata->cov[0][2])); testErrorRet(ok==0, ce_file, "Bad line", *err, __LINE__, ); ok = read_double(&p,&(sndata->cov[1][2])); // convert diagonal r.m.s. to variance sndata->cov[0][0] *= sndata->cov[0][0]; sndata->cov[1][1] *= sndata->cov[1][1]; sndata->cov[2][2] *= sndata->cov[2][2]; // symetrise sndata->cov[1][0] = sndata->cov[0][1]; sndata->cov[2][0] = sndata->cov[0][2]; sndata->cov[2][1] = sndata->cov[1][2]; for (k=0; k<NDER; ++k) { if (sndatformat==SNLS_firstyear) { ok = read_double(&p,&(sndata->derivative[k])); testErrorRet(ok==0, ce_file, "Bad line", *err, __LINE__, ); } else { sndata->derivative[k] = 0; } } } /* Reads a file with supernovae data */ SnSample *SnSample_read(const char *FileName, sndatformat_t sndatformat, error **err) { int i, cur=-1, Nsample, dummy; double peculiar_vel, int_disp; SnSample *sn; char key[256], line[4096], *sval; FILE *f; //fprintf(stderr, "Reading %s\n", FileName); /* default values */ int_disp = 0.13; peculiar_vel = 300.0; sn = malloc_err(sizeof(SnSample), err); forwardError(*err, __LINE__, NULL); sn->W1 = NULL; sn->W1dim = 0; sn->logdetW1 = 0.0; f = fopen(FileName,"r"); if (f==NULL) { sprintf(line, "Could not open file %s", FileName); *err = addError(ce_file, line, *err, __LINE__); return NULL; } /* Read twice: 1st time for header and number of lines, 2nd time read data */ for (i=0,Nsample=0; i<=1; i++) { if (i==1) { sn->data = (SnData*)malloc_err(Nsample*sizeof(SnData), err); forwardError(*err, __LINE__, NULL); fseek(f, 0, SEEK_SET); cur = 0; } while (fgets(line,4096,f)) { if (line[0] == '#') continue; // comment if (line[strlen(line)-1] == '\n') line[strlen(line)-1] = '\0'; if (line[0] == '@') { if (i==1) continue; sval = key+128; if (sscanf(line+1,"%s %s",key,sval) != 2) { *err = addError(ce_file, "Could not read line", *err, __LINE__); /* Pierre: continue */ return NULL; } if (strcmp(key,"INSTRINSIC_DISPERSION")==0) if (!read_double(&sval,&int_disp)) { *err = addError(ce_file, "Could not read line", *err, __LINE__); return NULL; } if (strcmp(key,"PECULIAR_VELOCITY")==0) if (!read_double(&sval,&peculiar_vel)) { *err = addError(ce_file, "Could not read line", *err, __LINE__); return NULL; } if (strcmp(key,"THETA1_ERRORS")==0 && (NDER != 0)) { if (i==0) { sn->W1 = readASCII(sval, &(sn->W1dim), &dummy, err); forwardError(*err, __LINE__, NULL); testErrorRet(sn->W1dim!=dummy, ce_nonsquare, "Not a square matrix", *err, __LINE__, NULL); sm2_inverse(sn->W1, sn->W1dim, err); forwardError(*err, __LINE__, NULL); } } } else // read data { if (i==0) { Nsample++; } else { readSnData(line, sn->data+cur, sndatformat, err); forwardError(*err, __LINE__, 0); cur++; } } } /* while line */ } /* for i */ sn->int_disp = int_disp; sn->sig_mu_pec_vel = 5.0*peculiar_vel/3.0e5/log(10.0); sn->Nsample = Nsample; for (i=0,sn->logdetW1=0.0; i<sn->W1dim; i++) { sn->logdetW1 += log(sn->W1[i*sn->W1dim+i]); } return sn; } /* Prints SN Sample to file */ void out_SnSample(const SnSample *sn, FILE *F) { int i, j, k; FILE *OUT; if (F==NULL) OUT = stdout; else OUT = F; fprintf(OUT, "# SnSample\n"); fprintf(OUT, "# Nsample = %d int_disp = %f sig_mu_pec_vel = %g\n", sn->Nsample, sn->int_disp, sn->sig_mu_pec_vel); fprintf(OUT, "# z musb s c dl mu_c derivative[8] covd[%d][%d]\n", NLCP, NLCP); for (i=0; i<sn->Nsample; i++) { fprintf(OUT, "%f %f %f %f %7.2f %f", sn->data[i].z, sn->data[i].musb, sn->data[i].s, sn->data[i].c, sn->data[i].dl, sn->data[i].mu_c); fprintf(OUT, " "); for (j=0; j<NDER; j++) { fprintf(OUT, " % f", sn->data[i].derivative[j]); } fprintf(OUT, " "); for (j=0; j<NLCP; j++) { for (k=0; k<NLCP; k++) { fprintf(OUT, " % .3e", sn->data[i].cov[j][k]); } } fprintf(OUT, "\n"); } } void out_model(const cosmo_SN *cosmo, FILE *F, error **err) { double z, dlum; fprintf(F, "# z Dlum [Mpc/h] mu_c\n"); for (z=0.002; z<=1.5; z+=0.002) { dlum = D_lum(cosmo->cosmo, 1.0/(1.0+z), err); forwardError(*err, __LINE__,); fprintf(F, "%f %10.3f % f\n", z, dlum, distance_module(cosmo->cosmo, dlum, err)); forwardError(*err, __LINE__,); } } void SetDl(cosmo_SN *self, SnSample *sn, error **err) { int i; for (i=0; i<sn->Nsample; i++) { sn->data[i].dl = D_lum(self->cosmo, 1.0/(sn->data[i].z+1.0), err); forwardError(*err, __LINE__,); testErrorRet(sn->data[i].dl<=0, ce_negative, "D_lum not positive", *err, __LINE__,); /* Distance module is 5 log10(dl/10pc). The dependence on the Hubble constant is put into the (nuissance) parameter M (Theta2[0]) */ sn->data[i].mu_c = distance_module(self->cosmo, sn->data[i].dl, err); forwardError(*err, __LINE__,); } } /* Returns Theta2^T * cov * Theta2 with Theta2 = (1, alpha, -beta) and cov = cov(m_B^*,s,c) * * For chi2mode=chi2_beta_z, Theta2[2] = -beta + beta_z*z. */ double DistModVariance(const SnData *snd, const double *Theta2) { double res; res = snd->cov[0][0]+2.0*Theta2[1]*(snd->cov[0][1]+Theta2[2]*snd->cov[1][2]) +2.0*Theta2[2]*snd->cov[0][2]+snd->cov[1][1]*Theta2[1]*Theta2[1] +snd->cov[2][2]*Theta2[2]*Theta2[2]; return res; } /* Returns the scalar product x^T * A * x */ double vect_scalar_product(const double *x, const double *A, int N) { int i, j; double res; for (j=0,res=0.0; j<N; j++) { for (i=0; i<N; i++) { res += x[i]*A[i+j*N]*x[j]; } } return res; } double int_for_Nhalo_z(double z, void *intpar, error **err) { cosmo *self; double res; self = (cosmo*)intpar; res = dsqr(1.0+z)/sqrt(Esqr(self, 1.0/(1.0+z), 0, err)); forwardError(*err, __LINE__, 0.0); /* Correction for rest-frame shift of absorption wave-length */ res *= pow(1.0+z, 1.2); return res; } double Nhalo_z(cosmo *self, double z, error **err) { double res; double sigma, n; /* Menard et al. 2009 */ n = 0.037; /* Mpc^-3 h^-1 */ sigma = 0.01*pi; /* Mpc^2 */ res = sm2_qromberg(int_for_Nhalo_z, (void*)self, 0.0, z, 1.0e-6, err); forwardError(*err, __LINE__, 0.0); return res*R_HUBBLE*sigma*n; } double chi2_SN_residual(const cosmo_SN *cosmo, const SnSample *sn, error **err) { int i, j, k; double chi2, logdetC, res, x[3], tmp; mvdens *g; g = mvdens_alloc(3, err); forwardError(*err, __LINE__, 0.0); for (i=0,chi2=0.0,logdetC=0.0; i<sn->Nsample; i++) { /* === Data === */ g->mean[0] = sn->data[i].musb; g->mean[1] = sn->data[i].s; g->mean[2] = sn->data[i].c; /* === Model === */ x[0] = -cosmo->Theta2[0] - cosmo->Theta2[1]*(cosmo->stretch-1.0) - cosmo->Theta2[2]*cosmo->color + sn->data[i].mu_c; x[1] = cosmo->stretch; x[2] = cosmo->color; /* Covariance */ for (j=0; j<3; j++) { for (k=0; k<3; k++) { g->std[j*3+k] = sn->data[i].cov[j][k]; } } g->std[0] += dsqr(sn->int_disp) + dsqr(sn->sig_mu_pec_vel/sn->data[i].z); res = (g->mean[1]-x[1]) * 1 * (g->mean[1]-x[1]); goto end; tmp = sm2_inverse(g->std, 3, err); forwardError(*err, __LINE__, 0.0); logdetC += log(tmp); res = 0.0; for (j=0; j<3; j++) { for (k=0; k<3; k++) { res += (g->mean[j]-x[j]) * g->std[j*3+k] * (g->mean[k]-x[k]); } } end: chi2 += res; } mvdens_free(&g); return -0.5*(chi2 + logdetC); } /* ============================================================ * * Returns the negative log-likelihood. * * Variables: Theta2[0] = -M, Theta2[1] = alpha, * * Theta2[2] = -beta. * * ============================================================ */ double chi2_SN(const cosmo_SN *cosmo, const SnSample *sn, mvdens *data_beta_d, int wTheta1, int add_logdetCov, error **err) { double chi2, res, res_all, wi, mu_meas, sigintsqr, kTheta1, Theta2[NLCP], Theta2_betaz[NLCP], logdetC, dmv; double c_d; int i, j; if (cosmo->chi2mode==chi2_residual) { res = chi2_SN_residual(cosmo, sn, err); forwardError(*err, __LINE__, 0.0); return res; } for (i=0; i<NLCP; i++) Theta2[i] = cosmo->Theta2[i]; if (cosmo->chi2mode==chi2_Theta2_denom_fixed) { /* Copy the fixed denominator values for alpha and beta */ Theta2[1] = cosmo->Theta2_denom[1]; Theta2[2] = cosmo->Theta2_denom[2]; } sigintsqr = dsqr(sn->int_disp); for (i=0,chi2=0.0,logdetC=0.0; i<sn->Nsample; i++) { /* m - M */ mu_meas = sn->data[i].musb + cosmo->Theta2[0]; if (cosmo->chi2mode!=chi2_no_sc) { if (cosmo->chi2mode!=chi2_betaz) { /* Add stretch and color terms alpha*(s-1) - beta*c */ mu_meas += cosmo->Theta2[1]*(sn->data[i].s-1.0) + cosmo->Theta2[2]*sn->data[i].c; if (cosmo->chi2mode==chi2_dust) { /* Correction for intergalactic dust along line of sight: * * add (beta - beta_d)*c_d */ c_d = sn->data[i].dust; mu_meas += -cosmo->Theta2[2]*c_d - cosmo->beta_d*c_d; /* Approximation: linear law */ //mu_meas += -cosmo->Theta2[2]*2.0*1e-2*sn->data[i].z // -3.0*2.0*1e-2*sn->data[i].z; } dmv = DistModVariance(&(sn->data[i]), Theta2); } else { /* beta = beta_0 + beta_1*z */ mu_meas += cosmo->Theta2[1]*(sn->data[i].s-1.0) + (cosmo->Theta2[2] + cosmo->Theta2[3]*sn->data[i].z)*sn->data[i].c; Theta2_betaz[0] = Theta2[0]; Theta2_betaz[1] = Theta2[1]; Theta2_betaz[2] = Theta2[2] + Theta2[3]*sn->data[i].z; /* Include beta_z in the error */ dmv = DistModVariance(&(sn->data[i]), Theta2_betaz); } } else { /* No stretch and color */ dmv = sn->data[i].cov[0][0]; } /* Weight = inverse variance */ wi = 1.0/(sigintsqr + dmv + dsqr(sn->sig_mu_pec_vel/sn->data[i].z)); //+ dsqr(0.093*sn->data[i].z)); // Lensing correction (Kowalski08) if (wTheta1) { /* Take into account Theta1 (zero-points) */ for (j=0,kTheta1=0.0; j<NDER; j++) kTheta1 += cosmo->Theta1[j]*sn->data[i].derivative[j]; } else { kTheta1 = 0.0; } chi2 += wi*dsqr(mu_meas + kTheta1 - sn->data[i].mu_c); /* |C| = Product_i [ w_i^{-1} ]; log|C| = - Sum_i [ w_i ] */ logdetC -= log(wi); } /* Add up everything */ res_all = -0.5*(sn->Nsample*ln2pi + chi2); /* Adding the covariance-term is correct for the log-likelihood in a Bayesian * * context. However, it leads to a biased estimation of parameters, in * * particular for alpha and beta (J. Guy, P. Astier, priv. comm.) */ if (add_logdetCov==1) { res = -0.5*logdetC; res_all += res; } /* Zero-points (Kilbinger et al. 2009) */ if (wTheta1==1) { /* TODO: use mvdens_log_pdf */ testErrorRet(sn->W1==NULL, io_null, "Matrix for zero-points W1 not initialised", *err, __LINE__, 0.0); chi2 = vect_scalar_product(cosmo->Theta1, sn->W1, sn->W1dim); res = -0.5*(sn->W1dim*ln2pi + chi2 + sn->logdetW1); res_all += res; } /* Dust (Menard, Kilbinger & Scranton 2009) */ /* In case of beta_d=const=data_beta_d->mean[0] this term is not added */ if (cosmo->chi2mode==chi2_dust && data_beta_d!=NULL) { res = mvdens_log_pdf(data_beta_d, &(cosmo->beta_d), err); forwardError(*err, __LINE__, 0.0); res_all += res; } return res_all; } /* SNIa distance modulus. To make it independent of the Hubble constant, the * * H_0-dependence from w(z) is divided out -> 5 log(d_L/h) + 25. */ double distance_module(cosmo *self, double dlum, error **err) { testErrorRet(dlum<0, ce_negative, "Luminosity distance is negative", *err, __LINE__, -1); return 5.0*log10(dlum/self->h_100) + 25; }
29.669528
98
0.562274
[ "model" ]
c365bb2b08d156a096e63946bb48a57be5a2371d
1,339
h
C
sourceCode/communication/tubes/commTube.h
mdecourse/CoppeliaSimLib
934e65b4b6ea5a07d08919ae35c50fd3ae960ef2
[ "RSA-MD" ]
null
null
null
sourceCode/communication/tubes/commTube.h
mdecourse/CoppeliaSimLib
934e65b4b6ea5a07d08919ae35c50fd3ae960ef2
[ "RSA-MD" ]
null
null
null
sourceCode/communication/tubes/commTube.h
mdecourse/CoppeliaSimLib
934e65b4b6ea5a07d08919ae35c50fd3ae960ef2
[ "RSA-MD" ]
null
null
null
#pragma once #include <string> #include <vector> class CCommTube { public: CCommTube(int header,const char* identifier,int firstPartner,bool killAtSimulationEnd,int readBufferSize); ~CCommTube(); bool isConnected(); void connectPartner(int secondPartner,bool killAtSimulationEnd,int readBufferSize); bool disconnectPartner(int partner); // return value true means this object needs destruction bool simulationEnded(); // return value true means this object needs destruction bool writeData(int partner,char* data,int dataSize); // data is not copied! char* readData(int partner,int& dataSize); // data is not copied! bool isPartnerThere(int partner); bool isSameHeaderAndIdentifier(int header,const char* identifier); int getTubeStatus(int tubeHandle,int& readBufferFill,int& writeBufferFill); // -1: not existant, 0: not connected, 1: connected protected: void _removeAllPackets(); void _removePacketsOfPartner(int partnerIndex); void _swapPartners(); int _header; std::string _identifier; int _partner[2]; bool _killPartnerAtSimulationEnd[2]; // false --> don't kill int _readBufferSizes[2]; std::vector<char*> _packets[2]; // _packets[0] is from partner2 to partner1, packets[1] is from partner1 to partner2 std::vector<int> _packetSizes[2]; };
36.189189
131
0.735624
[ "object", "vector" ]
c36836c3a4c53b777150df5dea4f6ecc79a99603
9,800
h
C
src/avt/Pipeline/Sources/avtOriginatingSource.h
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
226
2018-12-29T01:13:49.000Z
2022-03-30T19:16:31.000Z
src/avt/Pipeline/Sources/avtOriginatingSource.h
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
5,100
2019-01-14T18:19:25.000Z
2022-03-31T23:08:36.000Z
src/avt/Pipeline/Sources/avtOriginatingSource.h
visit-dav/vis
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
[ "BSD-3-Clause" ]
84
2019-01-24T17:41:50.000Z
2022-03-10T10:01:46.000Z
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt // Project developers. See the top-level LICENSE file for dates and other // details. No copyright assignment is required to contribute to VisIt. // ************************************************************************* // // avtOriginatingSource.h // // ************************************************************************* // #ifndef AVT_ORIGINATING_SOURCE_H #define AVT_ORIGINATING_SOURCE_H #include <pipeline_exports.h> #include <void_ref_ptr.h> #include <avtQueryableSource.h> #include <avtDataRequest.h> #include <avtContract.h> class vtkObject; class avtInlinePipelineSource; class avtMetaData; typedef avtDataRequest_p (*LoadBalanceFunction)(void *, avtContract_p); typedef bool (*StreamingCheckFunction)(void *,avtContract_p); typedef void (*InitializeProgressCallback)(void *, int); // **************************************************************************** // Class: avtOriginatingSource // // Purpose: // This is the originator of a pipeline's update/execute cycle. As such, // it owns the actual pipeline object. // // Programmer: Hank Childs // Creation: May 23, 2001 // // Modifications: // // Jeremy Meredith, Thu Sep 20 01:01:49 PDT 2001 // Added dynamic checker callback function so it can make determinations // about the network it will execute. // // Hank Childs, Thu Oct 25 16:44:24 PDT 2001 // Add a virtual function for whether or not this source permits dynamic // load balancing. // // Kathleen Bonnell, Fri Nov 15 09:07:36 PST 2002 // Added virtual method Query. // // Hank Childs, Mon Jul 28 16:33:34 PDT 2003 // Derived from avtQueryableSource instead of avtDataObjectSource. // // Kathleen Bonnell, Wed Nov 12 18:26:21 PST 2003 // Added virtual method FindElementForPoint. // // Kathleen Bonnell, Mon Dec 22 14:48:57 PST 2003 // Added virtual method GetDomainName. // // Kathleen Bonnell, Tue May 25 16:16:25 PDT 2004 // Add virtual method 'QueryZoneCenter'. // // Jeremy Meredith, Wed Jun 9 09:13:39 PDT 2004 // Added species aux data. // // Kathleen Bonnell, Thu Jun 10 18:31:22 PDT 2004 // Renamed QueryZoneCenter to QueryCoords, added bool arg. // // Kathleen Bonnell, Thu Dec 16 17:16:33 PST 2004 // Added another bool arg to QueryCoords. // // Kathleen Bonnell, Mon Jan 3 13:40:42 PST 2005 // Added GetSIL method. // // Kathleen Bonnell, Tue Jan 25 07:59:28 PST 2005 // Added const char *arg to QueryCoords. // // Hank Childs, Wed Feb 7 13:18:28 PST 2007 // Add support for progress from time queries. // // Hank Childs, Tue Feb 19 19:45:43 PST 2008 // Rename "dynamic" to "streaming", since we really care about whether we // are streaming, not about whether we are doing dynamic load balancing. // And the two are no longer synonymous. // // Hank Childs, Thu Jun 12 16:12:38 PDT 2008 // Add method CanDoStreaming. // // Hank Childs, Thu Aug 26 16:57:24 PDT 2010 // Add data member for the last contract. // // Hank Childs, Fri Nov 26 16:26:55 PST 2010 // Add support for caching of arbitrary objects. // // Hank Childs, Tue Dec 11 14:39:58 PST 2012 // Add method for getting last data selections. // // Kathleen Biagas, Mon Jun 5 16:41:17 PDT 2017 // Added ResetAllExtents. // // **************************************************************************** class PIPELINE_API avtOriginatingSource : virtual public avtQueryableSource { friend class avtInlinePipelineSource; public: avtOriginatingSource(); virtual ~avtOriginatingSource(); virtual avtOriginatingSource *GetOriginatingSource(void) { return this;}; avtMetaData *GetMetaData(void) { return metadata; }; void GetMeshAuxiliaryData(const char *type, void *args, avtContract_p, VoidRefList &); void GetVariableAuxiliaryData(const char *type, void *args, avtContract_p, VoidRefList &); void GetMaterialAuxiliaryData(const char *type, void *args, avtContract_p, VoidRefList &); void GetSpeciesAuxiliaryData(const char *type, void *args, avtContract_p, VoidRefList &); virtual vtkObject *FetchArbitraryVTKObject(const char *name, int dom, int ts, const char *type); virtual void StoreArbitraryVTKObject(const char *name, int dom, int ts, const char *type, vtkObject *); virtual void_ref_ptr FetchArbitraryRefPtr(const char *name, int dom, int ts, const char *type); virtual void StoreArbitraryRefPtr(const char *name, int dom, int ts, const char *type, void_ref_ptr); virtual bool Update(avtContract_p); virtual void ResetAllExtents(void); virtual bool CanDoStreaming(avtContract_p) {return true;} static void SetLoadBalancer(LoadBalanceFunction,void *); static void SetStreamingChecker(StreamingCheckFunction, void *); static void RegisterInitializeProgressCallback( InitializeProgressCallback, void *); void SetNumberOfExecutions(int numEx) { numberOfExecutions = numEx; haveIssuedProgress = false; }; virtual avtDataRequest_p GetFullDataRequest(void); avtContract_p GetGeneralContract(void); std::vector<avtDataSelection_p> GetSelectionsForLastExecution(void); // Define this so derived types don't have to. virtual void Query(PickAttributes *){;}; virtual avtSIL *GetSIL(int){return NULL;}; virtual bool FindElementForPoint(const char*, const int, const int, const char*, double[3], int &) { return false;}; virtual void GetDomainName(const std::string &, const int, const int, std::string &) {;}; virtual bool QueryCoords(const std::string &, const int, const int, const int, double[3], const bool, const bool = false, const char *mn=NULL) { (void)mn; return false;}; protected: avtMetaData *metadata; static InitializeProgressCallback initializeProgressCallback; static void *initializeProgressCallbackArgs; virtual bool FetchData(avtDataRequest_p) = 0; virtual void FetchMeshAuxiliaryData(const char *type, void *args, avtDataRequest_p, VoidRefList &); virtual void FetchVariableAuxiliaryData(const char *type, void *args, avtDataRequest_p, VoidRefList &); virtual void FetchMaterialAuxiliaryData(const char *type, void *args, avtDataRequest_p, VoidRefList &); virtual void FetchSpeciesAuxiliaryData(const char *type, void *args, avtDataRequest_p, VoidRefList &); avtDataRequest_p BalanceLoad(avtContract_p); virtual bool UseLoadBalancer(void) { return true; }; virtual bool ArtificialPipeline(void) { return false; }; virtual int NumStagesForFetch(avtDataRequest_p); private: static LoadBalanceFunction loadBalanceFunction; static void *loadBalanceFunctionArgs; static StreamingCheckFunction streamingCheckFunction; static void *streamingCheckFunctionArgs; void InitPipeline(avtContract_p); virtual bool CanDoStreaming(void); // These data members are important when there are multiple executions, like // with the time loop filter. This information is important to keep track // of progress. int numberOfExecutions; bool haveIssuedProgress; protected: avtContract_p lastContract; }; #endif
43.75
91
0.512245
[ "object", "vector" ]
c36f1e84760c8c5c67fd92e2120b535047ee30bf
927
h
C
parser/parser.h
stormprograms/Storm
63a8184ac264a19cfd5135e91d58e8add2b67d4c
[ "MIT" ]
2
2020-03-05T13:48:19.000Z
2020-05-14T04:44:57.000Z
parser/parser.h
stormprograms/Storm
63a8184ac264a19cfd5135e91d58e8add2b67d4c
[ "MIT" ]
6
2020-03-03T16:41:48.000Z
2020-04-25T18:14:55.000Z
parser/parser.h
stormprograms/Storm
63a8184ac264a19cfd5135e91d58e8add2b67d4c
[ "MIT" ]
null
null
null
#pragma once #include "svalues.h" #include "functions.h" #include "storm_calls.h" inline struct parser_t { std::string outfile; std::vector<std::string> splicedProgram; /* * ".data" in nasm, initialized with data indicator for full program * * structured like this in bytecode * * data * [0] type "value" ; for initialized * [1] res ; for uninitialized * * text * ... */ std::vector<uint8_t> data = {0x0C}; // ".text" in nasm, initialized with text indicator for full program and main function declaration std::vector<uint8_t> text; // first function should be {1}, as main is {0} std::vector<function> functions; std::vector<variable> vars; } parser; template<class T> T find(std::string name) { return T(); }; template<> variable find<variable>(std::string name); template<> function find<function>(std::string name); // Separate the program into lines; void lexer(std::string contents);
22.609756
99
0.691478
[ "vector" ]
c376e0f0f6e3102cb8a3fd3b36e72f6069a45eb9
1,008
c
C
mooc42-dongfei-algo/class6/unique_path2.c
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
2
2019-03-20T17:05:59.000Z
2019-10-15T07:56:45.000Z
mooc42-dongfei-algo/class6/unique_path2.c
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
6
2019-12-04T06:08:32.000Z
2021-05-10T20:22:47.000Z
mooc42-dongfei-algo/class6/unique_path2.c
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
null
null
null
class Solution { public: int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { if(obstacleGrid.empty() || obstacleGrid[0].empty()) { return 0; } int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); int dp[m][n]; //下面初始dp的时候需要根据obstacleGrid的值来确定 dp[0][0] = (obstacleGrid[0][0] == 0 ? 1 : 0); //我们需要注意m x 1以及1 x n的初始化 for(int i = 1; i < m; i++) { dp[i][0] = ((dp[i - 1][0] == 1 && obstacleGrid[i][0] == 0) ? 1 : 0); } for(int j = 1; j < n; j++) { dp[0][j] = ((dp[0][j - 1] == 1 && obstacleGrid[0][j] == 0) ? 1 : 0); } for(int i = 1; i < m; i++) { for(int j = 1; j < n; j++) { if(obstacleGrid[i][j] == 1) { dp[i][j] = 0; } else { dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } } return dp[m - 1][n - 1]; } };
25.846154
80
0.380952
[ "vector" ]
c37856cbba7717eef729b927f9e1ea96ee6b41a0
3,333
h
C
vox.render/ui/widgets/panel_transformable.h
ArcheGraphics/Arche-cpp
da6770edd4556a920b3f7298f38176107caf7e3a
[ "MIT" ]
8
2022-02-15T12:54:57.000Z
2022-03-30T16:35:58.000Z
vox.render/ui/widgets/panel_transformable.h
yangfengzzz/DigitalArche
da6770edd4556a920b3f7298f38176107caf7e3a
[ "MIT" ]
null
null
null
vox.render/ui/widgets/panel_transformable.h
yangfengzzz/DigitalArche
da6770edd4556a920b3f7298f38176107caf7e3a
[ "MIT" ]
null
null
null
// Copyright (c) 2022 Feng Yang // // I am making my contributions/submissions to this project solely in my // personal capacity and am not conveying any rights to any intellectual // property of any third parties. #ifndef panel_transformable_hpp #define panel_transformable_hpp #include <vector> #include <memory> #include "vector2.h" #include "event.h" #include "ui/widgets/panel.h" #include "ui/widgets/alignment.h" namespace vox { namespace ui { /** * APanelTransformable is a panel that is localized in the canvas */ class PanelTransformable : public Panel { public: /** * Create a APanelTransformable * @param p_defaultPosition p_defaultPosition * @param p_defaultSize p_defaultSize * @param p_defaultHorizontalAlignment p_defaultHorizontalAlignment * @param p_defaultVerticalAlignment p_defaultVerticalAlignment * @param p_ignoreConfigFile p_ignoreConfigFile */ PanelTransformable(const Vector2F &p_defaultPosition = Vector2F(-1.f, -1.f), const Vector2F &p_defaultSize = Vector2F(-1.f, -1.f), HorizontalAlignment p_defaultHorizontalAlignment = HorizontalAlignment::LEFT, VerticalAlignment p_defaultVerticalAlignment = VerticalAlignment::TOP, bool p_ignoreConfigFile = false); /** * Defines the position of the panel * @param p_position p_position */ void setPosition(const Vector2F &p_position); /** * Defines the size of the panel * @param p_size p_size */ void setSize(const Vector2F &p_size); /** * Defines the alignment of the panel * @param p_horizontalAlignment p_horizontalAlignment * @param p_verticalAligment p_verticalAligment */ void setAlignment(HorizontalAlignment p_horizontalAlignment, VerticalAlignment p_verticalAligment); /** * Returns the current position of the panel */ const Vector2F &position() const; /** * Returns the current size of the panel */ const Vector2F &size() const; /** * Returns the current horizontal alignment of the panel */ HorizontalAlignment horizontalAlignment() const; /** * Returns the current vertical alignment of the panel */ VerticalAlignment verticalAlignment() const; protected: void update(); virtual void _draw_Impl() = 0; private: Vector2F calculatePositionAlignmentOffset(bool p_default = false); void updatePosition(); void updateSize(); void copyImGuiPosition(); void copyImGuiSize(); public: bool autoSize = true; protected: Vector2F _defaultPosition; Vector2F _defaultSize; HorizontalAlignment _defaultHorizontalAlignment; VerticalAlignment _defaultVerticalAlignment; bool _ignoreConfigFile; Vector2F _position = Vector2F(0.0f, 0.0f); Vector2F _size = Vector2F(0.0f, 0.0f); bool _positionChanged = false; bool _sizeChanged = false; HorizontalAlignment _horizontalAlignment = HorizontalAlignment::LEFT; VerticalAlignment _verticalAlignment = VerticalAlignment::TOP; bool _alignmentChanged = false; bool _firstFrame = true; }; } } #endif /* panel_transformable_hpp */
27.097561
100
0.678968
[ "vector" ]
c37d0a7c9ccbedd20aa97b75a9e5b45dff92fc1c
1,786
h
C
www/public/example/trip-vehicle.h
jamjpan/libezrs
0c5e92f2ab3bc9acf9c8e62d76f77b8122ded850
[ "MIT" ]
27
2018-03-28T07:53:58.000Z
2021-05-23T11:55:42.000Z
www/public/example/trip-vehicle.h
jamjpan/libezrs
0c5e92f2ab3bc9acf9c8e62d76f77b8122ded850
[ "MIT" ]
25
2018-04-03T13:33:50.000Z
2019-09-30T05:40:01.000Z
www/public/example/trip-vehicle.h
jamjpan/libezrs
0c5e92f2ab3bc9acf9c8e62d76f77b8122ded850
[ "MIT" ]
8
2019-07-31T07:45:55.000Z
2021-04-19T12:56:53.000Z
#include <unordered_map> #include <vector> #include <omp.h> #include <algorithm> /* std::find, std::nth_element */ #include <chrono> #include <ctime> #include <exception> #include <iostream> /* std::endl */ #include <vector> #include "glpk/glpk.h" #include "libcargo.h" using namespace cargo; const int BATCH = 30; const int TOP_CUST = 30; // customers per vehicle for rv-graph //const int TRIP_MAX = 30000; // maximum number of trips per batch // const int TOP_CUST = 8; // customers per vehicle for rv-graph const int TRIP_MAX = 12000; // maximum number of trips per batch typedef int SharedTripId; typedef std::vector<Customer> SharedTrip; class CargoWeb : public RSAlgorithm { public: CargoWeb(); int unassign_penalty = -1; /* My overrides */ virtual void handle_vehicle(const Vehicle &); virtual void match(); virtual void listen(bool skip_assigned = true, bool skip_delayed = true); private: Grid grid_; /* Vector of GTrees for parallel sp */ std::vector<GTree::G_Tree> gtre_; /* Workspace variables */ std::unordered_map<CustId, bool> is_matched; tick_t timeout_rv_0; tick_t timeout_rtv_0; SharedTripId stid_; dict<CustId, std::vector<SharedTripId>> cted_; // cust-trip edges dict<SharedTripId, SharedTrip> trip_; // trip lookup bool travel(const Vehicle &, // Can this vehl... const std::vector<Customer> &, // ...serve these custs? DistInt &, // cost of serving std::vector<Stop> &, // resultant schedule std::vector<Wayp> &, // resultant route GTree::G_Tree &); // gtree to use for sp SharedTripId add_trip(const SharedTrip &); void reset_workspace(); };
26.656716
75
0.643337
[ "vector" ]
c37e22a0bf6ff53300fb55e5f91385685d533ab2
491
h
C
MAKCategories/NSObject/NSObject+MAKObjectCaching.h
mr-casual/MAKCategories
483cbd13d759ebc08e7174d984236d61b95d6688
[ "MIT" ]
null
null
null
MAKCategories/NSObject/NSObject+MAKObjectCaching.h
mr-casual/MAKCategories
483cbd13d759ebc08e7174d984236d61b95d6688
[ "MIT" ]
null
null
null
MAKCategories/NSObject/NSObject+MAKObjectCaching.h
mr-casual/MAKCategories
483cbd13d759ebc08e7174d984236d61b95d6688
[ "MIT" ]
null
null
null
// // NSObject+MAKObjectCaching.h // MAKToolKit // // Created by Martin Kloepfel on 15.06.15. // Copyright (c) 2015 Martin Kloepfel. All rights reserved. // #import <Foundation/Foundation.h> /** This category is used for caching an object on an other object. //TODO: write better comment^^ */ @interface NSObject (MAKObjectCaching) - (void)setCachingObject:(id)object forKey:(id <NSCopying>)key; - (id)cachingObjectForKey:(id)key; - (void)removeCachingObjectForKey:(id)key; @end
21.347826
98
0.723014
[ "object" ]
c380a12607f1f77153fc997bac1bd42ab380afcc
3,454
h
C
External/astrometry.net/astrometry/include/mathutil.h
simonct/CoreAstro
eafd0aea314c427da616e1707a49aaeaf5ea6991
[ "OML" ]
3
2015-08-29T06:56:58.000Z
2016-11-15T10:35:59.000Z
External/astrometry.net/astrometry/include/mathutil.h
simonct/CoreAstro
eafd0aea314c427da616e1707a49aaeaf5ea6991
[ "OML" ]
null
null
null
External/astrometry.net/astrometry/include/mathutil.h
simonct/CoreAstro
eafd0aea314c427da616e1707a49aaeaf5ea6991
[ "OML" ]
null
null
null
/* This file is part of the Astrometry.net suite. Copyright 2006, 2007 Dustin Lang, Keir Mierle and Sam Roweis. The Astrometry.net suite is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. The Astrometry.net suite 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 the Astrometry.net suite ; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MATHUTIL_H #define MATHUTIL_H #include "keywords.h" /* Given a point "pt", computes two unit vectors that are tangent to the point and perpendicular to each other. */ void tan_vectors(const double* pt, double* vec1, double* vec2); int invert_2by2(const double A[2][2], double Ainv[2][2]); int invert_2by2_arr(const double* A, double* Ainv); int is_power_of_two(unsigned int x); void matrix_matrix_3(double* m1, double* m2, double* result); void matrix_vector_3(double* m, double* v, double* result); double dot_product_3(double* v1, double* v2); double vector_length_3(double* v); double vector_length_squared_3(double* v); double inverse_3by3(double *matrix); void image_to_xyz(double uu, double vv, double* s, double* transform); void fit_transform(double* star, double* field, int N, double* trans); double uniform_sample(double low, double high); double gaussian_sample(double mean, double stddev); // just drop partial blocks off the end. #define EDGE_TRUNCATE 0 // just average the pixels in partial blocks. #define EDGE_AVERAGE 1 int get_output_image_size(int W, int H, int blocksize, int edgehandling, int* outw, int* outh); #define SIGN(x) (((x) == 0) ? 0.0 : (((x) > 0) ? 1.0 : -1.0)) /** Average the image in "blocksize" x "blocksize" blocks, placing the output in the "output" image. The output image will have size "*newW" by "*newH". If you pass "output = NULL", memory will be allocated for the output image. It is valid to pass in "output" = "image". The output image is returned. */ float* average_image_f(const float* image, int W, int H, int blocksize, int edgehandling, int* newW, int* newH, float* output); float* average_weighted_image_f(const float* image, const float* weight, int W, int H, int blocksize, int edgehandling, int* newW, int* newH, float* output, float nilval); Const InlineDeclare int imax(int a, int b); Const InlineDeclare int imin(int a, int b); InlineDeclare double distsq_exceeds(double* d1, double* d2, int D, double limit); Const InlineDeclare double square(double d); // note, this function works on angles in degrees; it wraps around // at 360. Const InlineDeclare int inrange(double ra, double ralow, double rahigh); InlineDeclare double distsq(const double* d1, const double* d2, int D); InlineDeclare void cross_product(double* v1, double* v2, double* cross); InlineDeclare void normalize(double* x, double* y, double* z); InlineDeclare void normalize_3(double* xyz); #ifdef INCLUDE_INLINE_SOURCE #define InlineDefine InlineDefineH #include "mathutil.inc" #undef InlineDefine #endif #endif
30.566372
81
0.733353
[ "transform" ]
c381a9b74c5dba569f060c9186d0c24573a883d3
7,666
h
C
tensorrt-laboratory/core/include/tensorrt/laboratory/core/pool.h
ryanleary/tensorrt-laboratory
1bb2151bfdffbb2e72b1a096e41b67602789c445
[ "BSD-3-Clause" ]
4
2020-01-16T13:50:28.000Z
2021-12-08T09:35:13.000Z
tensorrt-laboratory/core/include/tensorrt/laboratory/core/pool.h
ryanleary/tensorrt-laboratory
1bb2151bfdffbb2e72b1a096e41b67602789c445
[ "BSD-3-Clause" ]
5
2020-03-24T17:57:33.000Z
2022-03-12T00:07:08.000Z
tensorrt-laboratory/core/include/tensorrt/laboratory/core/pool.h
ryanleary/tensorrt-laboratory
1bb2151bfdffbb2e72b1a096e41b67602789c445
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION 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 ``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. */ #pragma once #include <condition_variable> #include <memory> #include <mutex> #include <queue> namespace trtlab { /** * @brief Templated Thread-safe Queue * * A simple thread-safe queue using a mutex and a condition variable. This * class is derived from `std::enabled_shared_from_this` which requires it * to be create using `std::make_shared`. * * @tparam T */ template<typename T> class Queue : public std::enable_shared_from_this<Queue<T>> { protected: Queue() = default; public: /** * @brief Factory function to properly create a Queue. * * @return std::shared_ptr<Queue<T>> */ static std::shared_ptr<Queue<T>> Create() { return std::shared_ptr<Queue<T>>(new Queue<T>()); } Queue(Queue&& other) { std::lock_guard<std::mutex> lock(other.mutex_); queue_ = std::move(other.queue_); } virtual ~Queue() {} /** * @brief Push a new value of T to the Queue * * @param value */ void Push(T value) { { std::lock_guard<std::mutex> lock(mutex_); queue_.push(std::move(value)); } cond_.notify_one(); } /** * @brief Pop the Front object from the Queue and return. * * @return T */ T Pop() { std::unique_lock<std::mutex> lock(mutex_); cond_.wait(lock, [this] { return !queue_.empty(); }); T value = std::move(queue_.front()); queue_.pop(); return value; } /** * @brief Numbe of items in the Queue * * @return std::size_t */ std::size_t Size() { std::lock_guard<std::mutex> lock(mutex_); return queue_.size(); } private: mutable std::mutex mutex_; std::queue<T> queue_; std::condition_variable cond_; }; /** * @brief Pool of ResourceType * * Pool of ResourceTypes implemented as a Queue. * * A unique aspect of this Pool object is the return type of the Pop method. While the * Pool consists of shared_ptr's to objects of ResourceType typically created with the * the std::default_deleter. The Pop method of this Pool clsss returned a different * type of shared_ptr<ResourceType> than the object pushed to the Pool. The difference * is that the returned shared_ptr uses a custom deleter thereby creating a new logic * block for tracking this shared_ptr. Rather than freeing the object in question, * the custom deleter captures both the original shared_ptr from the pool and the * shared_ptr of the Pool (shared_from_this), and uses those captured values to return * the original shared_ptr (with the default_deleter) to the Pool. * * By holding a reference to the pool in the custom deleter of the returned shared_ptr, * we ensure that the pool can not be deallocated while resources have been checked out. * * The custom shared_ptr also helps ensure resources are returned to the pool even if the * thread using the resources throws an exception. * * @tparam T */ template<typename ResourceType> class Pool : public Queue<std::shared_ptr<ResourceType>> { protected: using Queue<std::shared_ptr<ResourceType>>::Queue; public: /** * @brief Factory function for creating a Pool. * * @return std::shared_ptr<Pool<ResourceType>> */ static std::shared_ptr<Pool<ResourceType>> Create() { return std::shared_ptr<Pool<ResourceType>>(new Pool<ResourceType>()); } /** * @brief Acquire a shared pointer to a ResourceType held by the Pool. * * Returns a shared_ptr<ResourceType> with a custom deleter that return the * Resource object by to the pool when the reference count of the shared_ptr * goes to zero. * * @return std::shared_ptr<ResourceType> */ std::shared_ptr<ResourceType> Pop() { return Pop([](ResourceType* ptr) {}); } /** * @brief Acquire a shared pointer to a ResourceType held by the Pool. * * Returns a shared_ptr<ResourceType> with a custom deleter that return the * Resource object by to the pool when the reference count of the shared_ptr * goes to zero. * * onReturn will be executed prior to the object being returned to the pool. * onReturn is passed the raw pointer to the ResourceType. * * @param onReturn * @return std::shared_ptr<ResourceType> */ std::shared_ptr<ResourceType> Pop(std::function<void(ResourceType*)> onReturn) { auto pool_ptr = this->shared_from_this(); auto from_pool = Queue<std::shared_ptr<ResourceType>>::Pop(); std::shared_ptr<ResourceType> ptr(from_pool.get(), [from_pool, pool_ptr, onReturn](auto p) mutable { onReturn(p); pool_ptr->Push(std::move(from_pool)); pool_ptr.reset(); }); return ptr; } /** * @brief Pop/Dequeue a shared pointer to a ResourceType object. * * Unlike the Pop() that provides a shared_ptr whose Deleter returns the object * to the Pool; this method permanently removes the object from the Pool. * * @return std::shared_ptr<ResourceType> * @see Pop() */ std::shared_ptr<ResourceType> PopWithoutReturn() { return Queue<std::shared_ptr<ResourceType>>::Pop(); } /** * @brief Instantiates and Pushes a new Resource object. * * @param newObj Raw pointer to an object of ResourceType */ void EmplacePush(ResourceType* newObj) { this->Push(std::shared_ptr<ResourceType>(newObj)); } /** * @brief Instantiates and Pushes a new Resource object. * * Forwards the arguments passed to this method to the ResourceType constructor. * * @tparam Args * @param args */ template<typename... Args> void EmplacePush(Args&&... args) { EmplacePush(new ResourceType(std::forward<Args>(args)...)); } }; } // namespace trtlab
33.475983
99
0.653405
[ "object" ]
c384bc1c8468370d4f95d0af9c3d8c7cb65e0bf8
832
h
C
include/il2cpp/System/Action_ValueTuple_Int32Enum__int__.h
martmists-gh/BDSP
d6326c5d3ad9697ea65269ed47aa0b63abac2a0a
[ "MIT" ]
1
2022-01-15T20:20:27.000Z
2022-01-15T20:20:27.000Z
include/il2cpp/System/Action_ValueTuple_Int32Enum__int__.h
martmists-gh/BDSP
d6326c5d3ad9697ea65269ed47aa0b63abac2a0a
[ "MIT" ]
null
null
null
include/il2cpp/System/Action_ValueTuple_Int32Enum__int__.h
martmists-gh/BDSP
d6326c5d3ad9697ea65269ed47aa0b63abac2a0a
[ "MIT" ]
null
null
null
#pragma once #include "il2cpp.h" void System_Action_ValueTuple_Int32Enum__int_____ctor (System_Action_ValueTuple_Int32Enum__int___o* __this, Il2CppObject* object, intptr_t method, const MethodInfo* method_info); void System_Action_ValueTuple_Int32Enum__int____Invoke (System_Action_ValueTuple_Int32Enum__int___o* __this, System_ValueTuple_Int32Enum__int__o obj, const MethodInfo* method_info); System_IAsyncResult_o* System_Action_ValueTuple_Int32Enum__int____BeginInvoke (System_Action_ValueTuple_Int32Enum__int___o* __this, System_ValueTuple_Int32Enum__int__o obj, System_AsyncCallback_o* callback, Il2CppObject* object, const MethodInfo* method_info); void System_Action_ValueTuple_Int32Enum__int____EndInvoke (System_Action_ValueTuple_Int32Enum__int___o* __this, System_IAsyncResult_o* result, const MethodInfo* method_info);
92.444444
260
0.893029
[ "object" ]
c38b983cd361926e0e99ec4499f1319a7c3da365
2,886
h
C
d3d/dgal_wrap.h
cmpute/d3d
dbe43e5608653c5b743423541a80e388e13be771
[ "MIT" ]
27
2020-04-16T22:24:47.000Z
2022-01-12T08:23:43.000Z
d3d/dgal_wrap.h
cmpute/d3d
dbe43e5608653c5b743423541a80e388e13be771
[ "MIT" ]
2
2020-08-11T07:03:35.000Z
2021-02-05T06:43:26.000Z
d3d/dgal_wrap.h
cmpute/d3d
dbe43e5608653c5b743423541a80e388e13be771
[ "MIT" ]
6
2020-04-16T21:49:50.000Z
2022-01-26T15:38:47.000Z
#pragma once #include <dgal/geometry.hpp> #include "d3d/common.h" bool box3dr_contains(float x, float y, float z, float lx, float ly, float lz, float rz, float xq, float yq, float zq) { dgal::Quad2<float> box = dgal::poly2_from_xywhr(x, y, lx, ly, rz); dgal::AABox2<float> aabox = dgal::aabox2_from_poly2(box); dgal::Point2<float> p {.x=xq, .y=yq}; if (zq > z + lz/2 || zq < z - lz/2) return false; if (!aabox.contains(p)) return false; if (!box.contains(p)) return false; return true; } float box3dr_pdist(float x, float y, float z, float lx, float ly, float lz, float rz, float xq, float yq, float zq) { dgal::Quad2<float> box = dgal::poly2_from_xywhr(x, y, lx, ly, rz); dgal::Point2<float> p {.x=xq, .y=yq}; float dist2d = distance(box, p); float distz; if (zq > z) distz = z + lz / 2 - zq; else distz = zq - z + lz / 2; if (distz > 0) if (dist2d > 0) return dgal::_min(distz, dist2d); else return dist2d; else if (dist2d > 0) return distz; else return -hypot(distz, dist2d); } float box3dr_iou(float x1, float y1, float z1, float lx1, float ly1, float lz1, float rz1, float x2, float y2, float z2, float lx2, float ly2, float lz2, float rz2) { dgal::Quad2<float> box1 = dgal::poly2_from_xywhr(x1, y1, lx1, ly1, rz1), box2 = dgal::poly2_from_xywhr(x2, y2, lx2, ly2, rz2); float iou2d = dgal::iou(box1, box2); float z1max = z1 + lz1 / 2; float z1min = z1 - lz1 / 2; float z2max = z2 + lz2 / 2; float z2min = z2 - lz2 / 2; float imax = dgal::_min(z1max, z2max); float imin = dgal::_max(z1min, z2min); float umax = dgal::_max(z1max, z2max); float umin = dgal::_min(z1min, z2min); float i = dgal::_max(imax - imin, 0.f); float u = dgal::_max(umax - umin, float(1e-6)); float ziou = i / u; return iou2d * ziou; } float box3d_iou(float x1, float y1, float z1, float lx1, float ly1, float lz1, float rz1, float x2, float y2, float z2, float lx2, float ly2, float lz2, float rz2) { dgal::Quad2<float> box1 = dgal::poly2_from_xywhr(x1, y1, lx1, ly1, rz1), box2 = dgal::poly2_from_xywhr(x2, y2, lx2, ly2, rz2); float iou2d = dgal::iou(dgal::aabox2_from_poly2(box1), dgal::aabox2_from_poly2(box2)); float z1max = z1 + lz1 / 2; float z1min = z1 - lz1 / 2; float z2max = z2 + lz2 / 2; float z2min = z2 - lz2 / 2; float imax = dgal::_min(z1max, z2max); float imin = dgal::_max(z1min, z2min); float umax = dgal::_max(z1max, z2max); float umin = dgal::_min(z1min, z2min); float i = dgal::_max(imax - imin, 0.f); float u = dgal::_max(umax - umin, float(1e-6)); float ziou = i / u; return iou2d * ziou; }
31.369565
117
0.578309
[ "geometry" ]
c39b8148a464c372e3b6348195fd726d93efe37c
1,716
h
C
Lib/OakModel/ContainerDefBuilderData.h
vilaversoftware/OakModelView
c24d30b711fe0f2fdc336f2623dd9bc555867a9d
[ "Apache-2.0" ]
null
null
null
Lib/OakModel/ContainerDefBuilderData.h
vilaversoftware/OakModelView
c24d30b711fe0f2fdc336f2623dd9bc555867a9d
[ "Apache-2.0" ]
null
null
null
Lib/OakModel/ContainerDefBuilderData.h
vilaversoftware/OakModelView
c24d30b711fe0f2fdc336f2623dd9bc555867a9d
[ "Apache-2.0" ]
null
null
null
/* * OakModelView (http://oakmodelview.com/) * Author: Mikkel Nøhr Løvgreen (mikkel@oakmodelview.com) * ------------------------------------------------------------------------ * Licensed to Vilaversoftware IVS who licenses this file to you under the * Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <memory> #include <string> #include <vector> namespace Oak::Model { class NodeDef; typedef std::shared_ptr<NodeDef> NodeDefSPtr; class NodeDefBuilder; typedef std::shared_ptr<NodeDefBuilder> NodeDefBuilderSPtr; // ============================================================================= // Class definition // ============================================================================= class ContainerDefBuilderData { public: ContainerDefBuilderData(); virtual ~ContainerDefBuilderData() {} void validate(std::vector<std::string> &errorMessages) const; bool set(NodeDefBuilderSPtr builder, std::vector<NodeDefSPtr> nodeDefList) const; int minCount = 0; int maxCount = std::numeric_limits<int>::max(); std::string name; std::string variantId; }; typedef std::unique_ptr<ContainerDefBuilderData> ContainerDefBuilderDataUPtr; } // namespace Oak::Model
31.2
85
0.643939
[ "vector", "model" ]
c3a48120089cb5d4f327da716740af230b2fd505
355
h
C
component/gui/example/ui_menu.h
eboxmaker/eboxFramework-rtt
9718678422f56faec1cf21a6a8fd3f72441bea33
[ "MIT" ]
115
2018-08-12T08:41:17.000Z
2022-03-08T07:43:48.000Z
component/gui/example/ui_menu.h
eboxmaker/eboxFramework-rtt
9718678422f56faec1cf21a6a8fd3f72441bea33
[ "MIT" ]
4
2018-08-13T10:14:55.000Z
2019-07-03T06:54:10.000Z
component/gui/example/ui_menu.h
eboxmaker/eboxFramework-rtt
9718678422f56faec1cf21a6a8fd3f72441bea33
[ "MIT" ]
59
2018-09-02T21:54:25.000Z
2022-01-13T02:28:28.000Z
#ifndef __UI_MENU_H #define __UI_MENU_H #include "gui_page.h" class MenuPage:public GuiPage { public: MenuPage(String name):GuiPage(name){}; virtual ~MenuPage(){}; virtual void create(); virtual void show(); virtual void loop(); virtual void event(Object *sender,GuiMessage *msg); }; extern MenuPage *pageMenu; #endif
14.2
55
0.678873
[ "object" ]
c3a5d47fed9f6ee880eaad2333473ba7f3f509f7
2,347
h
C
dev/Gems/TextureAtlas/Code/Source/TextureAtlasImpl.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
8
2019-10-07T16:33:47.000Z
2020-12-07T03:59:58.000Z
dev/Gems/TextureAtlas/Code/Source/TextureAtlasImpl.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
null
null
null
dev/Gems/TextureAtlas/Code/Source/TextureAtlasImpl.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
5
2020-08-27T20:44:18.000Z
2021-08-21T22:54:11.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #pragma once #include <AzCore/Component/Component.h> #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/Asset/AssetCommon.h> #include "TextureAtlas/TextureAtlas.h" #include "TextureAtlas/TextureAtlasBus.h" #include <ITexture.h> namespace TextureAtlasNamespace { class TextureAtlasImpl: public TextureAtlas { public: AZ_CLASS_ALLOCATOR(TextureAtlasImpl, AZ::SystemAllocator, 0); AZ_TYPE_INFO(TextureAtlasImpl, "{2CA51C61-1B5F-4480-A257-F28D8944AA35}"); TextureAtlasImpl(); TextureAtlasImpl(AtlasCoordinateSets handles); ~TextureAtlasImpl(); static void Reflect(AZ::ReflectContext* context); //! Retrieve a coordinate set from the Atlas by its handle AtlasCoordinates GetAtlasCoordinates(const AZStd::string& handle) const override; //! Links this atlas to an image pointer void SetTexture(ITexture* image) override; //! Returns the image linked to this atlas ITexture* GetTexture() const override; //! Replaces the mappings of this Texture Atlas Object, with the source's mappings void OverwriteMappings(TextureAtlasImpl* source); //! Returns the width of the atlas int GetWidth() const override { return m_width; } //! Sets the width of the atlas void SetWidth(int value) { m_width = value; } //! Returns the height of the atlas int GetHeight() const override { return m_height; } //! Sets the height of the atlas void SetHeight(int value) { m_height = value; } private: AZStd::unordered_map<AZStd::string, AtlasCoordinates> m_data; ITexture* m_image; int m_width; int m_height; }; } // namespace TextureAtlasNamespace
34.514706
90
0.685982
[ "object" ]
0f1ec6c6d7da62b57880c548fa4d9c506928d856
534
h
C
YouLocal/API/PersistencyManager.h
mvelikov/notifications-ios-app-example
0c83b300f5104e6cbe0dcbeafdfa45df77bee6ea
[ "MIT" ]
null
null
null
YouLocal/API/PersistencyManager.h
mvelikov/notifications-ios-app-example
0c83b300f5104e6cbe0dcbeafdfa45df77bee6ea
[ "MIT" ]
null
null
null
YouLocal/API/PersistencyManager.h
mvelikov/notifications-ios-app-example
0c83b300f5104e6cbe0dcbeafdfa45df77bee6ea
[ "MIT" ]
null
null
null
// // PersistencyManager.h // Mapa.bg // // Created by Mihail Velikov on 1/7/15. // Copyright (c) 2015 Mapa.bg. All rights reserved. // #import <Foundation/Foundation.h> #import "Collection.h" @interface PersistencyManager : NSObject - (NSArray *) objects; - (void) setObjectsFromArray: (NSArray*) array; - (void) setObjectsFromDictionary: (NSDictionary*) dictionary; - (void) clearObjects; - (void) addObject: (id) object; - (int) total; - (int) perPage; - (int) currentPage; - (int) lastPage; - (int) from; - (int) to; @end
19.777778
62
0.679775
[ "object" ]
0f2e982e611da2c298ce4e45206f5c6b7b211e55
9,039
h
C
Code/Widgets/vtkMimxCreateElementSetWidgetFEMesh.h
Piyusha23/IAFEMesh
e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f
[ "BSD-4-Clause-UC" ]
null
null
null
Code/Widgets/vtkMimxCreateElementSetWidgetFEMesh.h
Piyusha23/IAFEMesh
e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f
[ "BSD-4-Clause-UC" ]
null
null
null
Code/Widgets/vtkMimxCreateElementSetWidgetFEMesh.h
Piyusha23/IAFEMesh
e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f
[ "BSD-4-Clause-UC" ]
null
null
null
/*========================================================================= Program: MIMX Meshing Toolkit Module: $RCSfile: vtkMimxCreateElementSetWidgetFEMesh.h,v $ Language: C++ Date: $Date: 2013/01/29 22:07:08 $ Version: $Revision: 1.2 $ Musculoskeletal Imaging, Modelling and Experimentation (MIMX) Center for Computer Aided Design The University of Iowa Iowa City, IA 52242 http://www.ccad.uiowa.edu/mimx/ Copyright (c) The University of Iowa. All rights reserved. See MIMXCopyright.txt or http://www.ccad.uiowa.edu/mimx/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // .NAME vtkMimxCreateElementSetWidgetFEMesh - a widget to manipulate 3D parallelopipeds // // .SECTION Description // This widget was designed with the aim of visualizing / probing cuts on // a skewed image data / structured grid. // // .SECTION Interaction // The widget allows you to create a parallelopiped (defined by 8 handles). // The widget is initially placed by using the "PlaceWidget" method in the // representation class. After the widget has been created, the following // interactions may be used to manipulate it : // 1) Click on a handle and drag it around moves the handle in space, while // keeping the same axis alignment of the parallelopiped // 2) Dragging a handle with the shift button pressed resizes the piped // along an axis. // 3) Control-click on a handle creates a chair at that position. (A chair // is a depression in the piped that allows you to visualize cuts in the // volume). // 4) Clicking on a chair and dragging it around moves the chair within the // piped. // 5) Shift-click on the piped enables you to translate it. // // .SECTION Caveats // .SECTION See Also vtkParallelopipedRepresentation #ifndef __vtkMimxCreateElementSetWidgetFEMesh_h #define __vtkMimxCreateElementSetWidgetFEMesh_h #include "vtkAbstractWidget.h" #include "vtkUnstructuredGrid.h" #include "vtkActor.h" #include "vtkMimxWidgetsWin32Header.h" class vtkActor; class vtkCellPicker; class vtkDataSet; class vtkIdList; class vtkInteractorStyleRubberBandPick; class vtkPointLocator; class vtkPolyDataMapper; class vtkRenderedAreaPicker; class vtkUnstructuredGrid; class vtkGeometryFilter; class vtkPolyData; class vtkExtractCells; class vtkDataSetMapper; class VTK_MIMXWIDGETS_EXPORT vtkMimxCreateElementSetWidgetFEMesh : public vtkAbstractWidget { public: // Description: // Instantiate the object. static vtkMimxCreateElementSetWidgetFEMesh *New(); vtkTypeRevisionMacro(vtkMimxCreateElementSetWidgetFEMesh,vtkAbstractWidget); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Override the superclass method. This is a composite widget, (it internally // consists of handle widgets). We will override the superclass method, so // that we can pass the enabled state to the internal widgets as well. virtual void SetEnabled(int); // Description: // Methods to change the whether the widget responds to interaction. // Overridden to pass the state to component widgets. // vtkSetObjectMacro(InputActor, vtkActor); // vtkGetObjectMacro(SelectedCellIds, vtkIdList); vtkGetObjectMacro(SelectedPointIds, vtkIdList); vtkSetMacro(BooleanState, int); vtkSetMacro(DimensionState, int); vtkGetObjectMacro(SelectedGrid, vtkUnstructuredGrid); void CreateDefaultRepresentation(){} void ComputeSelectedPointIds(vtkDataSet *SelectedUGrid, vtkMimxCreateElementSetWidgetFEMesh *Self); void AcceptSelectedMesh(vtkMimxCreateElementSetWidgetFEMesh *Self); void SetInput(vtkUnstructuredGrid *input); void SetCellSelectionState(int Selection); void SetEditMeshState(int MeshType); void ClearSelections(); enum EditMeshType { FullMesh = 0, SelectedMesh }; enum BooleanType { Add = 0, Subtract }; enum DimensionType { Volume = 0, Surface }; void SetInputOpacity(double Val); protected: vtkMimxCreateElementSetWidgetFEMesh(); ~vtkMimxCreateElementSetWidgetFEMesh(); static void CrtlMouseMoveCallback (vtkAbstractWidget* ); static void ShiftMouseMoveCallback (vtkAbstractWidget* ); static void CrtlLeftButtonDownCallback (vtkAbstractWidget* ); static void CrtlLeftButtonUpCallback (vtkAbstractWidget* ); static void ShiftLeftButtonDownCallback (vtkAbstractWidget* ); static void ShiftLeftButtonUpCallback (vtkAbstractWidget* ); static void LeftButtonUpCallback (vtkAbstractWidget* ); static void LeftButtonDownCallback (vtkAbstractWidget* ); static void RightButtonUpCallback (vtkAbstractWidget* ); static void RightButtonDownCallback (vtkAbstractWidget* ); static void MouseMoveCallback (vtkAbstractWidget* ); static void SelectCellsOnSurfaceFunction(vtkMimxCreateElementSetWidgetFEMesh *Self); static void SelectVisibleCellsOnSurfaceFunction(vtkMimxCreateElementSetWidgetFEMesh *Self); static void SelectCellsThroughFunction(vtkMimxCreateElementSetWidgetFEMesh *Self); static void SelectIndividualCellFunction(vtkMimxCreateElementSetWidgetFEMesh *Self); static void SelectIndividualSurfaceCellFunction(vtkMimxCreateElementSetWidgetFEMesh *Self); static void SelectMultipleCellFunction(vtkMimxCreateElementSetWidgetFEMesh *Self); static void AddDeleteSelectedElement(vtkMimxCreateElementSetWidgetFEMesh *Self); void ComputeExtractedCellIds( vtkMimxCreateElementSetWidgetFEMesh *self, vtkDataSet *DataSet); void ComputeExtractedCellIdsSurface( vtkMimxCreateElementSetWidgetFEMesh *self, vtkDataSet *DataSet); int ComputeOriginalCellNumber( vtkMimxCreateElementSetWidgetFEMesh *self, vtkIdList *PtIds); int ComputeOriginalCellNumberFromSelectedSurfaceMesh( vtkMimxCreateElementSetWidgetFEMesh *self, vtkIdList *PtIds); void DeleteExtractedCells(vtkMimxCreateElementSetWidgetFEMesh *Self); int DoesCellBelong(int CellNum, vtkMimxCreateElementSetWidgetFEMesh *Self); int GetCellNumGivenFaceIds(vtkIdList *PtIds, vtkMimxCreateElementSetWidgetFEMesh *Self); int GetCellNumGivenFaceIdsSelectedMesh(vtkIdList *PtIds, vtkMimxCreateElementSetWidgetFEMesh *Self); int GetFaceNumGivenCellNumFaceIds(int CellNum, vtkIdList *PtIds, vtkPolyData *Surface, vtkMimxCreateElementSetWidgetFEMesh *Self); static void ExtractElementsBelongingToAFace(vtkMimxCreateElementSetWidgetFEMesh *Self); // for surface mesh selection of elements belonging to a face static void ExtractElementsBelongingToAFaceSurface(vtkMimxCreateElementSetWidgetFEMesh *Self); int GetCellNumGivenFaceIdsSurface(vtkIdList *PtIds, vtkMimxCreateElementSetWidgetFEMesh *Self); int GetFaceNumGivenCellNumFaceIdsSurface(int CellNum, vtkIdList *PtIds, vtkPolyData *Surface, vtkMimxCreateElementSetWidgetFEMesh *Self); // vtkIdList *ExtractedCellIds; vtkIdList *SelectedPointIds; vtkIdList *DeleteCellIds; vtkIdList *SelectedCellIds; //BTX // Description: // Events invoked by this widget int WidgetEvent; enum WidgetEventIds { Start = 0, Outside, CrtlLeftMouseButtonDown, CrtlLeftMouseButtonUp, CrtlLeftMouseButtonMove, VTKLeftButtonDown, VTKMouseMove, CrtlRightMouseButtonDown, ShiftLeftMouseButtonDown, ShiftLeftMouseButtonUp, ShiftMouseMove, LeftMouseButtonUp, LeftMouseButtonDown, RightMouseButtonUp, RightMouseButtonDown, MouseMove }; //ETX enum CellSelectionType { SelectCellsThrough = 0, SelectCellsOnSurface, SelectVisibleCellsOnSurface, SelectIndividualCell, SelectMultipleCells }; int EditMeshState; int CellSelectionState; int BooleanState; vtkInteractorStyleRubberBandPick *RubberBandStyle; vtkRenderedAreaPicker *AreaPicker; vtkUnstructuredGrid *InputVolume; vtkUnstructuredGrid *Input; vtkDataSetMapper *InputMapper; vtkIdType PickX0; vtkIdType PickY0; vtkIdType PickX1; vtkIdType PickY1; vtkIdType PickStatus; vtkActor *InputActor; //vtkActor *ExtractedActor; vtkPointLocator *PointLocator; vtkPoints *LocatorPoints; vtkPointLocator *InputLocator; vtkPoints *InputPoints; vtkGeometryFilter *SurfaceFilter; vtkPolyDataMapper *SurfaceMapper; vtkActor *SurfaceActor; vtkUnstructuredGrid *ExtractedGrid; vtkGeometryFilter *ExtractedSurfaceFilter; vtkPolyDataMapper *ExtractedSurfaceMapper; vtkActor *ExtractedSurfaceActor; vtkExtractCells *ExtractedCells; vtkDataSetMapper *ExtractedMapper; vtkActor *ExtractedActor; vtkExtractCells *SelectedCells; vtkUnstructuredGrid *SelectedGrid; vtkDataSetMapper *SelectedMapper; vtkActor *SelectedActor; double LineWidth; private: vtkMimxCreateElementSetWidgetFEMesh(const vtkMimxCreateElementSetWidgetFEMesh&); //Not implemented void operator=(const vtkMimxCreateElementSetWidgetFEMesh&); //Not implemented int MeshType; int DimensionState; }; #endif
36.011952
102
0.782277
[ "mesh", "object", "3d" ]
0f30dbdea5009d99f6f932858944f10814bff706
1,921
h
C
src/attributes/PaletteColourTechniqueWrapper.h
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
41
2018-12-07T23:10:50.000Z
2022-02-19T03:01:49.000Z
src/attributes/PaletteColourTechniqueWrapper.h
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
59
2019-01-04T15:43:30.000Z
2022-03-31T09:48:15.000Z
src/attributes/PaletteColourTechniqueWrapper.h
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
13
2019-01-07T14:36:33.000Z
2021-09-06T14:48:36.000Z
/******************************* LICENSE ******************************* * (C) Copyright 1996-2016 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. ******************************* LICENSE *******************************/ /*! \filePaletteColourTechniqueAttributes.h \brief Definition of PaletteColourTechnique Attributes class. This file is automatically generated. Do Not Edit! Generated: */ #ifndef PaletteColourTechniqueWrapper_H #define PaletteColourTechniqueWrapper_H #include "magics.h" #include "ParameterManager.h" #include "Factory.h" #include "ColourTechnique.h" #include "ColourTechniqueWrapper.h" namespace magics { class MagRequest; class PaletteColourTechniqueWrapper: public ColourTechniqueWrapper { public: // -- constructor PaletteColourTechniqueWrapper(); PaletteColourTechniqueWrapper(PaletteColourTechnique*); // -- destructor virtual ~PaletteColourTechniqueWrapper(); virtual void set(const MagRequest&); PaletteColourTechnique* me() { return palettecolourtechnique_; } virtual PaletteColourTechnique* object() { return palettecolourtechnique_; } virtual void object(PaletteColourTechnique* o) { // Remember to delete the previous object palettecolourtechnique_ = o; ColourTechniqueWrapper::object(o); } protected: PaletteColourTechnique* palettecolourtechnique_; // -- method virtual void print(ostream&) const; private: string tag_; friend ostream& operator<<(ostream& s,const PaletteColourTechniqueWrapper& p) { p.print(s); return s; } }; } // namespace magics #endif
20.655914
81
0.698594
[ "object" ]
0f4abbf238558df9ab4ca1fc47f5b237ac6f54dd
2,063
h
C
src/nodes/mec/MECPlatform/MECServices/LocationService/resources/LocationResource.h
talal00/Simu5G
ffbdda3e4cd873b49d7022912fe25e39d1a503e8
[ "Intel" ]
58
2021-04-15T09:20:26.000Z
2022-03-31T08:52:23.000Z
src/nodes/mec/MECPlatform/MECServices/LocationService/resources/LocationResource.h
talal00/Simu5G
ffbdda3e4cd873b49d7022912fe25e39d1a503e8
[ "Intel" ]
34
2021-05-14T15:05:36.000Z
2022-03-31T20:51:33.000Z
src/nodes/mec/MECPlatform/MECServices/LocationService/resources/LocationResource.h
talal00/Simu5G
ffbdda3e4cd873b49d7022912fe25e39d1a503e8
[ "Intel" ]
30
2021-04-16T05:46:13.000Z
2022-03-28T15:26:29.000Z
// // Simu5G // // Authors: Giovanni Nardini, Giovanni Stea, Antonio Virdis (University of Pisa) // // This file is part of a software released under the license included in file // "license.pdf". Please read LICENSE and README files before using it. // The above files and the present reference are part of the software itself, // and cannot be removed from it. // #ifndef _LOCATION_H_ #define _LOCATION_H_ #include "common/LteCommon.h" #include <set> #include <map> #include "nodes/mec/MECPlatform/MECServices/Resources/TimeStamp.h" #include "common/binder/Binder.h" #include "inet/networklayer/contract/ipv4/Ipv4Address.h" #include "nodes/mec/MECPlatform/MECServices/LocationService/resources/UserInfo.h" //#include "inet/common/geometry/common/Coord.h" using namespace omnetpp; class CellInfo; class LocationResource : public AttributeBase { public: /** * the constructor takes a vector of te eNodeBs connceted to the MeHost * and creates a CellInfo object */ LocationResource(); LocationResource(std::string& baseUri, std::set<cModule*>& eNodeBs, Binder* binder); virtual ~LocationResource(); nlohmann::ordered_json toJson() const override; void addEnodeB(std::set<cModule*>& eNodeBs); void addEnodeB(cModule* eNodeB); void addBinder(Binder* binder); void setBaseUri(const std::string& baseUri); nlohmann::ordered_json toJsonCell(std::vector<MacCellId>& cellsID) const; nlohmann::ordered_json toJsonUe(std::vector<inet::Ipv4Address>& uesID) const; nlohmann::ordered_json toJson(std::vector<MacNodeId>& cellsID, std::vector<inet::Ipv4Address>& uesID) const; protected: //better mappa <cellID, Cellinfo> Binder *binder_; TimeStamp timestamp_; std::map<MacCellId, CellInfo*> eNodeBs_; std::string baseUri_; UserInfo getUserInfoByNodeId(MacNodeId nodeId, MacCellId cellId) const; User getUserByNodeId(MacNodeId nodeId, MacCellId cellId) const; nlohmann::ordered_json getUserListPerCell(std::map<MacCellId, CellInfo *>::const_iterator it) const; }; #endif // _LOCATION_H_
30.791045
110
0.748425
[ "geometry", "object", "vector" ]
0f6ebed165e099d99935a889c269c001ade11615
8,459
h
C
Libraries/gtkmm/include/gtkmm/gtkmm/cellrendererprogress.h
utilForever/Wings
1dbf0c88cf3cc97b48788c23abc50c32447e228a
[ "MIT" ]
3
2017-01-19T09:30:50.000Z
2017-03-20T10:47:20.000Z
Libraries/gtkmm/include/gtkmm/gtkmm/cellrendererprogress.h
utilForever/Wings
1dbf0c88cf3cc97b48788c23abc50c32447e228a
[ "MIT" ]
null
null
null
Libraries/gtkmm/include/gtkmm/gtkmm/cellrendererprogress.h
utilForever/Wings
1dbf0c88cf3cc97b48788c23abc50c32447e228a
[ "MIT" ]
2
2017-01-19T09:32:19.000Z
2021-03-15T16:00:43.000Z
// -*- c++ -*- // Generated by gmmproc 2.44.0 -- DO NOT MODIFY! #ifndef _GTKMM_CELLRENDERERPROGRESS_H #define _GTKMM_CELLRENDERERPROGRESS_H #include <glibmm/ustring.h> #include <sigc++/sigc++.h> /* Copyright (C) 2004 The gtkmm Development Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <gtkmm/cellrenderer.h> #include <gtkmm/orientable.h> #ifndef DOXYGEN_SHOULD_SKIP_THIS typedef struct _GtkCellRendererProgress GtkCellRendererProgress; typedef struct _GtkCellRendererProgressClass GtkCellRendererProgressClass; #endif /* DOXYGEN_SHOULD_SKIP_THIS */ #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace Gtk { class CellRendererProgress_Class; } // namespace Gtk #endif //DOXYGEN_SHOULD_SKIP_THIS namespace Gtk { /** Renders numbers as progress bars. * * @ingroup TreeView * @newin{2,6} */ class CellRendererProgress : public CellRenderer, public Orientable { public: #ifndef DOXYGEN_SHOULD_SKIP_THIS typedef CellRendererProgress CppObjectType; typedef CellRendererProgress_Class CppClassType; typedef GtkCellRendererProgress BaseObjectType; typedef GtkCellRendererProgressClass BaseClassType; #endif /* DOXYGEN_SHOULD_SKIP_THIS */ virtual ~CellRendererProgress(); #ifndef DOXYGEN_SHOULD_SKIP_THIS private: friend class CellRendererProgress_Class; static CppClassType cellrendererprogress_class_; // noncopyable CellRendererProgress(const CellRendererProgress&); CellRendererProgress& operator=(const CellRendererProgress&); protected: explicit CellRendererProgress(const Glib::ConstructParams& construct_params); explicit CellRendererProgress(GtkCellRendererProgress* castitem); #endif /* DOXYGEN_SHOULD_SKIP_THIS */ public: /** Get the GType for this class, for use with the underlying GObject type system. */ static GType get_type() G_GNUC_CONST; #ifndef DOXYGEN_SHOULD_SKIP_THIS static GType get_base_type() G_GNUC_CONST; #endif ///Provides access to the underlying C GtkObject. GtkCellRendererProgress* gobj() { return reinterpret_cast<GtkCellRendererProgress*>(gobject_); } ///Provides access to the underlying C GtkObject. const GtkCellRendererProgress* gobj() const { return reinterpret_cast<GtkCellRendererProgress*>(gobject_); } public: //C++ methods used to invoke GTK+ virtual functions: protected: //GTK+ Virtual Functions (override these to change behaviour): //Default Signal Handlers:: private: public: CellRendererProgress(); /** Value of the progress bar. * * You rarely need to use properties because there are get_ and set_ methods for almost all of them. * @return A PropertyProxy that allows you to get or set the value of the property, * or receive notification when the value of the property changes. */ Glib::PropertyProxy< int > property_value() ; /** Value of the progress bar. * * You rarely need to use properties because there are get_ and set_ methods for almost all of them. * @return A PropertyProxy_ReadOnly that allows you to get the value of the property, * or receive notification when the value of the property changes. */ Glib::PropertyProxy_ReadOnly< int > property_value() const; /** Text on the progress bar. * * You rarely need to use properties because there are get_ and set_ methods for almost all of them. * @return A PropertyProxy that allows you to get or set the value of the property, * or receive notification when the value of the property changes. */ Glib::PropertyProxy< Glib::ustring > property_text() ; /** Text on the progress bar. * * You rarely need to use properties because there are get_ and set_ methods for almost all of them. * @return A PropertyProxy_ReadOnly that allows you to get the value of the property, * or receive notification when the value of the property changes. */ Glib::PropertyProxy_ReadOnly< Glib::ustring > property_text() const; /** Set this to positive values to indicate that some progress is made, but you don't know how much. * * You rarely need to use properties because there are get_ and set_ methods for almost all of them. * @return A PropertyProxy that allows you to get or set the value of the property, * or receive notification when the value of the property changes. */ Glib::PropertyProxy< int > property_pulse() ; /** Set this to positive values to indicate that some progress is made, but you don't know how much. * * You rarely need to use properties because there are get_ and set_ methods for almost all of them. * @return A PropertyProxy_ReadOnly that allows you to get the value of the property, * or receive notification when the value of the property changes. */ Glib::PropertyProxy_ReadOnly< int > property_pulse() const; /** The horizontal text alignment, from 0 (left) to 1 (right). Reversed for RTL layouts. * * You rarely need to use properties because there are get_ and set_ methods for almost all of them. * @return A PropertyProxy that allows you to get or set the value of the property, * or receive notification when the value of the property changes. */ Glib::PropertyProxy< float > property_text_xalign() ; /** The horizontal text alignment, from 0 (left) to 1 (right). Reversed for RTL layouts. * * You rarely need to use properties because there are get_ and set_ methods for almost all of them. * @return A PropertyProxy_ReadOnly that allows you to get the value of the property, * or receive notification when the value of the property changes. */ Glib::PropertyProxy_ReadOnly< float > property_text_xalign() const; /** The vertical text alignment, from 0 (top) to 1 (bottom). * * You rarely need to use properties because there are get_ and set_ methods for almost all of them. * @return A PropertyProxy that allows you to get or set the value of the property, * or receive notification when the value of the property changes. */ Glib::PropertyProxy< float > property_text_yalign() ; /** The vertical text alignment, from 0 (top) to 1 (bottom). * * You rarely need to use properties because there are get_ and set_ methods for almost all of them. * @return A PropertyProxy_ReadOnly that allows you to get the value of the property, * or receive notification when the value of the property changes. */ Glib::PropertyProxy_ReadOnly< float > property_text_yalign() const; /** Invert the direction in which the progress bar grows. * * You rarely need to use properties because there are get_ and set_ methods for almost all of them. * @return A PropertyProxy that allows you to get or set the value of the property, * or receive notification when the value of the property changes. */ Glib::PropertyProxy< bool > property_inverted() ; /** Invert the direction in which the progress bar grows. * * You rarely need to use properties because there are get_ and set_ methods for almost all of them. * @return A PropertyProxy_ReadOnly that allows you to get the value of the property, * or receive notification when the value of the property changes. */ Glib::PropertyProxy_ReadOnly< bool > property_inverted() const; virtual Glib::PropertyProxy_Base _property_renderable(); }; } // namespace Gtk namespace Glib { /** A Glib::wrap() method for this object. * * @param object The C instance. * @param take_copy False if the result should take ownership of the C instance. True if it should take a new copy or ref. * @result A C++ instance that wraps this C instance. * * @relates Gtk::CellRendererProgress */ Gtk::CellRendererProgress* wrap(GtkCellRendererProgress* object, bool take_copy = false); } //namespace Glib #endif /* _GTKMM_CELLRENDERERPROGRESS_H */
35.84322
124
0.746187
[ "object" ]
6683b62a28132addac2227adae92547514a313dd
1,787
h
C
mainwindow.h
C10H16N5O12P3/installer
f1bc53b3699309b54f5f2675aa5ef7c5678126fa
[ "MIT" ]
null
null
null
mainwindow.h
C10H16N5O12P3/installer
f1bc53b3699309b54f5f2675aa5ef7c5678126fa
[ "MIT" ]
null
null
null
mainwindow.h
C10H16N5O12P3/installer
f1bc53b3699309b54f5f2675aa5ef7c5678126fa
[ "MIT" ]
null
null
null
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkRequest> #include <QtNetwork/QNetworkReply> #include <QtCore/QJsonDocument> #include <QtCore/QJsonArray> #include <QtCore/QJsonObject> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class QLabel; struct ReleaseInfo { QString tagName; bool isPrerelease; QString releaseName; QString publishTime; QString body; QUrl linux64Url; QUrl windows32Url; QUrl windows64Url; QUrl webglUrl; ReleaseInfo(QJsonObject const& obj); inline QUrl const& getCurrentOsUrl() { #if defined(Q_OS_WIN32) return windows32Url; #elif defined(Q_OS_WIN64) return windows64Url; #elif defined(Q_OS_LINUX) return linux64Url; #endif } }; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: Ui::MainWindow *ui; QNetworkAccessManager* m_NetworkMgr; std::vector<ReleaseInfo> m_Releases; std::vector<int> m_ReleaseFiltered; private: void startDownload(QUrl const& url, std::function<void(QNetworkReply*)> callback); void setLabelImage(QLabel* label, QString path); QJsonDocument getReleasesJson(); void updateReleaseList(); void fetchVersions(); void applyFilter(); void updateVersionCombobox(); ReleaseInfo const& getSelectedRelease(); public slots: void sslError(QNetworkReply* reply, const QList<QSslError> &errors); void onDownloadBtnClick(); void onRefreshBtnClick(); void onPlayBtnClick(); void onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal); void onVersionIndexChanged(int idx); }; #endif // MAINWINDOW_H
22.910256
86
0.731393
[ "vector" ]
668d9df555c3c3ec7dd384a75ebe418ccbda187e
9,637
h
C
Voltron/Source/QuestionsDEntrevue/LeetCode/LeetCodeQuestions.h
ernestyalumni/HrdwCCppCUDA
17ed937dea06431a4d5ca103f993ea69a6918734
[ "MIT" ]
1
2018-02-09T19:44:51.000Z
2018-02-09T19:44:51.000Z
Voltron/Source/QuestionsDEntrevue/LeetCode/LeetCodeQuestions.h
ernestyalumni/HrdwCCppCUDA
17ed937dea06431a4d5ca103f993ea69a6918734
[ "MIT" ]
null
null
null
Voltron/Source/QuestionsDEntrevue/LeetCode/LeetCodeQuestions.h
ernestyalumni/HrdwCCppCUDA
17ed937dea06431a4d5ca103f993ea69a6918734
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------ /// \file LeetCodeQuestions.h /// \author Ernest Yeung /// \brief /// /// \ref https://leetcode.com/explore/learn/card/data-structure-tree/134/traverse-a-tree/992/ /// \ref LeetCode, Binary Trees //----------------------------------------------------------------------------- #ifndef QUESTIONS_D_ENTREVUE_LEETCODE_LEETCODE_QUESTIONS_H #define QUESTIONS_D_ENTREVUE_LEETCODE_LEETCODE_QUESTIONS_H #include <deque> #include <iterator> // std::distance #include <map> #include <optional> #include <sstream> #include <string> #include <utility> // std::make_pair, std::pair #include <vector> namespace QuestionsDEntrevue { namespace LeetCode { //------------------------------------------------------------------------------ /// \url https://leetcode.com/problems/valid-parentheses/ /// \name 20. Valid Parentheses. Easy. /// \brief Given a string s containing just the characters '(', ')', '{', '}', /// and '[', ']', determine if input string is valid. /// /// \details Use stack. //------------------------------------------------------------------------------ bool is_valid_parentheses(std::string s); //------------------------------------------------------------------------------ /// \url https://leetcode.com/problems/longest-valid-parentheses/ /// \name 32. Longest Valid Parentheses. Hard. /// \brief Given a string containing just the characters '(' and ')', find the /// length of the longest valid (well-formed) parentheses substring. /// /// Use the fact that we keep track of indices in the stack and that we can /// always access the value on the string through the index. //------------------------------------------------------------------------------ int longest_valid_parentheses(std::string s); //------------------------------------------------------------------------------ /// \url https://leetcode.com/problems/maximum-subarray/ /// \name 53. Maximum Subarray. /// \brief Given an integer array nums, find the contiguous subarray (containing /// at least one number) which has the largest sum and return its sum. /// /// \details Brute force is O(N^3) or O(N^2) as you check every subarray /// starting from I = 0, 1, ... N - 1, and ending at J = 0, 1, ... N- 1. /// For all linear array problems, aim to solve in O(N) linear time. /// Don't think of tables, think of what is the subproblem? /// Key observation, at an element and if at that element, J is index of that /// element, what is the max contiguous subarray? /// /// Other key observation is that max contiguous subarray for entire array must /// end on a element in the array. That's why we can ask the subproblem, what's /// the max contiguous subarray with condition that it ends at index J. /// /// \url https://youtu.be/2MmGzdiKR9Y /// /// Easy. //------------------------------------------------------------------------------ int max_subarray(std::vector<int>& nums); //------------------------------------------------------------------------------ /// \url https://leetcode.com/problems/climbing-stairs/description/ /// \name 70. Climbing Stairs. /// \brief You are climbing a stair case. It takes n steps to reach the top. /// /// \details Each time you can either climb 1 or 2 steps. //------------------------------------------------------------------------------ int climb_stairs(int n); int climb_stairs_iterative(const int n); //------------------------------------------------------------------------------ /// \url https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ /// \name 121. Best Time to Buy and Sell Stock. /// \brief You are climbing a stair case. It takes n steps to reach the top. /// /// \details Each time you can either climb 1 or 2 steps. /// /// Traverse from left to get minimum buy prices dependent on time. /// Traverse from right to get maximum sell prices dependent on time. /// Traverse all 3 to get maximum profit at any time t. Then take max. //------------------------------------------------------------------------------ int max_profit(std::vector<int>& prices); //------------------------------------------------------------------------------ /// \url https://leetcode.com/problems/coin-change/ /// \name 322. Coin Change /// \brief You are given coins of different denominations and a total amount of /// money amount. Write a function to compute the fewest number of coins that /// you need to make up that amount. /// \details If that amount of money cannot be made up by any combination of the /// coins, return -1. /// /// Medium. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ /// \details Iterative approach. /// 1 <= coins.length <= 12 //------------------------------------------------------------------------------ int coin_change_bottom_up(std::vector<int>& coins, int amount); int coin_change_top_down( std::vector<int>& coins, int amount); int coin_change_top_down_step( std::vector<int>& coins, int amount, std::map<int, int>& min_coins); //------------------------------------------------------------------------------ /// \details Recursive approach. //------------------------------------------------------------------------------ int min_coin_change_recursive_step( std::vector<int>& coins, const int smallest_coinage, std::vector<std::optional<int>>& min_coins_for_amount, int amount); int coin_change_recursive(std::vector<int>& coins, int amount); //------------------------------------------------------------------------------ /// \url https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/ /// \name 363. Max Sum of Rectangle No Larger Than K. /// \ref https://www.youtube.com/watch?v=-FgseNO-6Gk /// Back To Back SWE, Maximum Sum Rectangle In A 2D Matrix - Kadane's Algorithm //------------------------------------------------------------------------------ int max_sum_submatrix(std::vector<std::vector<int>>& matrix); std::pair<int, std::pair<std::size_t, std::size_t>> find_subrow_max( std::vector<int>& row); //------------------------------------------------------------------------------ /// \url https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ /// \name 647. Palindromic Substrings. /// \brief Given a string, your task is to count how many palindromic substrings /// in this string. /// \details Consider using multiple variables, pointers. /// /// Runtime: 12 ms, faster than 60.36% of C++ online submissions for Palindromic /// Substrings. /// Memory Usage: 6.7 MB, less than 5.03% of C++ online submissions for /// Palindromic Substrings. /// /// cf. https://youtu.be/r1MXwyiGi_U /// Top 10 Algorithms for the Coding Interview (for software engineers), /// TechLead, Jun 27, 2019. /// 1. DFS, 2. BFS, 3. Matching Parentheses, 4. Hash Tables, 5. Variables, ptrs /// manipulation, 6. reversing linked list, 7. sorting fundamentals (quick, /// merge, bubble sort, runtime of sort, time/space complexity), 8. recursion, /// 9. custom data structures (OOP), 10. Binary search. /// https://www.youtube.com/watch?v=r1MXwyiGi_U&lc=UgwGnloT3M405KnWQnd4AaABAg //------------------------------------------------------------------------------ int count_palindromic_substrings(std::string s); //------------------------------------------------------------------------------ /// \details Given length l, number of operations (comparisons) is l / 2 in /// worst case (worse case is that it's a palindrome). //------------------------------------------------------------------------------ inline auto check_palindrome = [](auto start_iter, auto end_iter) -> bool { bool is_palindrome {true}; // std::distance is the number of hops from start_iter to end_iter. while (std::distance(start_iter, end_iter) >= 0) { if (*start_iter == *end_iter) { ++start_iter; --end_iter; } else { is_palindrome = false; break; } } return is_palindrome; }; inline auto find_even_size_palindromes = []( auto start_limit, auto end_limit, auto start_iter) -> int { int count {0}; auto end_iter = start_iter + 1; while (end_iter != end_limit && std::distance(start_limit, start_iter) >= 0) { if (*start_iter == *end_iter) { ++count; ++end_iter; --start_iter; } else { break; } } return count; }; inline auto find_odd_size_palindromes = []( auto start_limit, auto end_limit, auto start_iter) { // Count a single letter to be a palindrome itself. int count {1}; auto end_iter = start_iter + 1; --start_iter; while (end_iter != end_limit && std::distance(start_limit, start_iter) >= 0) { if (*start_iter == *end_iter) { ++count; ++end_iter; --start_iter; } else { break; } } return count; }; //------------------------------------------------------------------------------ /// \url https://leetcode.com/problems/palindromic-substrings/solution/ /// \brief Expand around center. /// Let N be the length of the string. The middle of the palindrome could be in /// 1 of 2N-1 total positions: either at the letter, or in between 2 letters. /// Thus, count the number of letters, N, and number of positions in between 2 /// letters, N - 1 -> N + N - 1 = 2N - 1 //------------------------------------------------------------------------------ int count_palindromic_substrings_simple(std::string s); } // namespace LeetCode } // namespace QuestionsDEntrevue #endif // QUESTIONS_D_ENTREVUE_LEETCODE_LEETCODE_QUESTIONS_H
37.065385
93
0.544568
[ "vector" ]
6693741273da3460bf5b612f739ad14f24c2679d
945
h
C
include/game/world/cursor_handler.h
codeka/ravaged-planets
ab20247b3829414e71b58c9a6e926bddf41f1da5
[ "Apache-2.0" ]
null
null
null
include/game/world/cursor_handler.h
codeka/ravaged-planets
ab20247b3829414e71b58c9a6e926bddf41f1da5
[ "Apache-2.0" ]
null
null
null
include/game/world/cursor_handler.h
codeka/ravaged-planets
ab20247b3829414e71b58c9a6e926bddf41f1da5
[ "Apache-2.0" ]
3
2017-07-17T22:24:17.000Z
2019-10-15T18:37:15.000Z
#pragma once namespace ent { class entity; class entity_manager; } namespace game { class terrain; /** * This class "handles" the cursor. That is, it remembers which entity (if any) is currently under the cursor as well * what happens when you click the mouse button. */ class cursor_handler { private: std::vector<int> _keybind_tokens; ent::entity_manager *_entities; terrain *_terrain; std::weak_ptr<ent::entity> _last_highlighted; std::weak_ptr<ent::entity> _entity_under_cursor; // this is called when the "select" button is pressed (left mouse button by default) void on_key_select(std::string keyname, bool is_down); // this is called when the "deselect" button is pressed (right mouse button by default) void on_key_deselect(std::string keyname, bool is_down); public: cursor_handler(); ~cursor_handler(); void initialize(); void update(); void destroy(); }; }
24.230769
118
0.702646
[ "vector" ]
66b97a597857807b0cfb936938f79ee220353f16
90,536
h
C
VSBellNew/include/prim-string.h
haskellstudio/belle_old
a5ce86954b61dbacde1d1bf24472d95246be45e5
[ "BSD-2-Clause" ]
null
null
null
VSBellNew/include/prim-string.h
haskellstudio/belle_old
a5ce86954b61dbacde1d1bf24472d95246be45e5
[ "BSD-2-Clause" ]
null
null
null
VSBellNew/include/prim-string.h
haskellstudio/belle_old
a5ce86954b61dbacde1d1bf24472d95246be45e5
[ "BSD-2-Clause" ]
null
null
null
/* ============================================================================== Copyright 2007-2013, 2017 William Andrew Burnson Copyright 2013-2016 Robert Taub Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ============================================================================== */ #ifndef PRIM_INCLUDE_STRING_H #define PRIM_INCLUDE_STRING_H #ifndef PRIM_LIBRARY #error This file can not be included individually. Include prim.h instead. #endif namespace PRIM_NAMESPACE { namespace meta { ///Character used for when a bad Unicode character sequence is decoded. static const unicode BadCharacter = 0xfffd; //Unicode replacement character } /**Efficient flat container of linked substrings. The string is equally fast at append, prepend, insert, and erase, with nearly constant manipulation speed with respect to string length.*/ class String { public: /**Representation of a UTF-32 string stored in system endianness. Since it is just an array of unicode values, it does not have any string operation methods. To use those methods, append the String::UTF32 to an empty string.*/ typedef Array<unicode> UTF32; private: ///Container of linked-substrings. mutable Array<byte> Data; ///Total length of the combined fragments. mutable count InternalLength; ///Starting position of the last fragment. mutable count LastFragmentIndex; ///Precision of number to string conversions. mutable count NumberPrecision; public: ///Standard streams that can be attached to the string. enum StreamAttachment { StandardInput, StandardOutput, StandardError, NotAttached }; private: ///Stream to which this string is attached StreamAttachment AttachedStream; PRIM_PAD(StreamAttachment) //--------// //Iterator// //--------// //Iterator needs to access the Data member. friend class Iterator; ///Internal iterator used by the string manipulator methods. class Iterator { public: ///String character index at the fragment beginning count i; ///Index of the fragment data count f; ///Length of the fragment count n; ///Location of the previous next-marker count p; ///Delay mechanism so that copied iterators will begin correctly. bool DelayIterator; PRIM_PAD(bool) ///Resets the iterator to the beginning of the string void Reset() { i = 0; f = 1; n = 0; p = 1; DelayIterator = false; } ///Constructor from integer to initialize from default parameter. Iterator() { Reset(); } ///Copy constructor with delay mechanism turned on Iterator(const Iterator& Other) : i(Other.i), f(Other.f), n(Other.n), DelayIterator(true) {} ///Assignment operator with delay mechanism turned on Iterator& operator = (const Iterator& Other) { i = Other.i; f = Other.f; n = Other.n; DelayIterator = true; return *this; } ///Hops to the next fragment. count Next(const String* s) { //If delaying hold off for one iteration if the fragment is valid. if(DelayIterator and f != 1) { DelayIterator = false; return -1; } //If starting go to the first fragment. if(f == 1) { i = 0; f = count(s->ReadMarker(1)); n = count(s->ReadMarker(f)); return f; } //If the end of the string is reached just leave. if(n == 0) return 0; //Increase string index. i += n; //Determine next fragment length. p = f + 4 + n; f = count(s->ReadMarker(p)); if(not f) n = 0; else n = count(s->ReadMarker(f)); return f; } ///Checks whether the requested character index is in this fragment. inline bool Contains(count j) { return j >= i and j < i + n; } }; ///The default iterator is used for Get() operations. mutable Iterator DefaultIterator; //-------------------// //Character Retrieval// //-------------------// ///Gets a character at the specified index. inline byte Get(count i) const { //If index is out of bounds return null. if(i < 0 or i >= InternalLength) return 0; //If the iterator is not useful then reset it. if(i < DefaultIterator.i) DefaultIterator.Reset(); //Start iterating on the current fragment. DefaultIterator.DelayIterator = true; while(DefaultIterator.Next(this)) { if(i < DefaultIterator.i + DefaultIterator.n) return Data[DefaultIterator.f + 4 + (i - DefaultIterator.i)]; } return 0; } //--------------// //Marker Control// //--------------// ///Reads a marker at some index. inline uint32 ReadMarker(count Index) const { #ifdef PRIM_DEBUG_INTERNAL //Sanity check--debug only. if(Index < 0 or Index + 4 > Data.n()) { PrintData(); std::cout << "The requested marker position is bad." << std::endl; std::cout.flush(); } #endif uint32 v = 0; Memory::MemCopy(&v, &Data[Index], sizeof(v)); return v; } ///Writes a marker value at some index. inline void WriteMarker(count Index, uint32 Value) { #ifdef PRIM_DEBUG_INTERNAL //Sanity check--debug only. if(Index < 0 or Index + 4 > Data.n()) { PrintData(); std::cout << "The requested marker position is bad." << std::endl; std::cout.flush(); } #endif Memory::MemCopy(&Data[Index], &Value, sizeof(Value)); } ///Writes a fragment assuming space for it has been allocated. void WriteFragment(count Index, count Length, const byte* Fragment, count Next) { WriteMarker(Index, uint32(Length)); WriteMarker(Index + 4 + Length, uint32(Next)); Memory::Copy(&Data[Index + 4], Fragment, Length); } //------------// //Optimization// //------------// /**Ensures that the string will never exceed twice its length in its representation. For example, this happens when a lot of short strings are inserted causing the majority of the data to be link data.*/ void CollapseBloatedLinks() { if(Data.n() > InternalLength * 2) Merge(); } //-----// //Debug// //-----// ///Binary dump of current string array data. Debug use only. void PrintData() const { #ifdef PRIM_DEBUG_INTERNAL std::cout << std::endl << "BEGIN (ROWS CONTAIN 16 BYTES)" << std::endl; std::cout << "0 1 2 3 4 5 6 7 8" " 9 10 11 12 13 14 15" << std::endl; std::cout << "=----=----=----=----=----=----=----=----=" "----=----==---==---==---==---==---==---"; for(count i = 0; i < Data.n(); i++) { if(i % (80 / 5) == 0) std::cout << std::endl; byte c = Data[i]; if(c >= byte(' ') and c <= byte('~')) std::cout << ascii(c); else std::cout << " "; if(c < 10) std::cout << " " << int(c); else if(c < 100) std::cout << " " << int(c); else std::cout << "" << int(c); std::cout << " "; } std::cout << std::endl; std::cout << "LAST FRAGMENT INDEX: " << LastFragmentIndex << std::endl; std::cout << "INTERNAL LENGTH: " << InternalLength << std::endl; std::cout << "END" << std::endl; #endif } ///Checks the internal consistency of the string. Debug use only. bool CheckConsistency() { #ifdef PRIM_DEBUG_INTERNAL //Check empty string. if(InternalLength == 0) { if(Data.n() != 0 or LastFragmentIndex != 0) { std::cout << "Bad empty string" << std::endl; std::cout.flush(); PrintData(); return false; } } if(Data.n() == 0) { if(InternalLength != 0 or LastFragmentIndex != 0) { std::cout << "Bad empty string" << std::endl; std::cout.flush(); PrintData(); return false; } } if(LastFragmentIndex == 0) { if(InternalLength != 0 or LastFragmentIndex != 0) { std::cout << "Bad empty string" << std::endl; std::cout.flush(); PrintData(); return false; } else return true; } if(Data[0] != 0) { std::cout << "Bad null boundary character" << std::endl; std::cout.flush(); PrintData(); return false; } Iterator q; count ActualLength = 0; count LastF = 0; while(q.Next(this)) { LastF = q.f; ActualLength += q.n; } if(ActualLength != InternalLength) { std::cout << "Bad internal length (expected " << ActualLength << ")" << std::endl; std::cout.flush(); PrintData(); return false; } if(LastF != LastFragmentIndex) { std::cout << "Bad last fragment index (expected " << LastF << ")" << std::endl; std::cout.flush(); PrintData(); return false; } #endif return true; } public: ///Represents an interval of characters in a string by index. typedef Complex<count> Span; //----------------// //Number Precision// //----------------// ///Sets the current floating-point conversion precision. void Precision(count NewPrecision) { if(NewPrecision < 1) NewPrecision = 1; else if(NewPrecision > 18) NewPrecision = 18; NumberPrecision = NewPrecision; } ///Gets the current floating-point conversion precision. count Precision(void) { return NumberPrecision; } //------------------------// //Fundamental Manipulators// //------------------------// ///Appends a byte fragment of a certain length. void Append(const byte* Fragment, count Length) { //If there is no content to add, then just leave. if(Length <= 0 or not Fragment) return; AppendToStream(Fragment, Length); if(InternalLength == 0) { //Create first fragment of initially empty string. Data.n(1 + 4 + 4 + Length + 4); Data[0] = 0; WriteMarker(1, 5); WriteFragment(5, Length, Fragment, 0); LastFragmentIndex = 5; } else if(LastFragmentIndex + 4 + count(ReadMarker(LastFragmentIndex)) + 4 == Data.n()) { //The last fragment is at the end, so it can be extended. Data.n(Data.n() + Length); count OldFragmentLength = count(ReadMarker(LastFragmentIndex)); count NewFragmentLength = OldFragmentLength + Length; WriteMarker(LastFragmentIndex, uint32(NewFragmentLength)); Memory::Copy(&Data[LastFragmentIndex + 4 + OldFragmentLength], Fragment, Length); WriteMarker(LastFragmentIndex + 4 + NewFragmentLength, 0); } else { //The last fragment not at the end, so a new fragment must be created. count OldStringLength = Data.n(); Data.n(OldStringLength + 4 + Length + 4); WriteMarker(LastFragmentIndex + 4 + count(ReadMarker(LastFragmentIndex)), uint32(OldStringLength)); WriteFragment(OldStringLength, Length, Fragment, 0); LastFragmentIndex = OldStringLength; } //Increase the internal length. InternalLength += Length; //Reset the default iterator. DefaultIterator.Reset(); //Optimize links. CollapseBloatedLinks(); } ///Appends a number with a given precision and format. void Append(float64 v, count Precision, bool ScientificNotation); ///Prepends a byte string of a certain length. void Prepend(const byte* Fragment, count Length) { //If there is no content to add, then just leave. if(Length <= 0 or not Fragment) return; /*Prepend is equivalent to Append for length zero string, so use the simpler Append.*/ if(InternalLength == 0) { Append(Fragment, Length); return; } //Add a new fragment containing the prepended string. uint32 OriginalFirstFragment = ReadMarker(1); count OldStringLength = Data.n(); Data.n(OldStringLength + Length + 4 + 4); WriteFragment(OldStringLength, Length, Fragment, count(OriginalFirstFragment)); WriteMarker(1, uint32(OldStringLength)); InternalLength += Length; //Reset the default iterator. DefaultIterator.Reset(); //Optimize string. CollapseBloatedLinks(); } /**Combines all the string fragments to form a single contiguous string. It returns a pointer to the byte or ASCII data. The end of the string will always contain a null-terminator regardless of the string contents. Note that Merge is declared const because it only changes the representation of the content of the string, not the content itself.*/ const ascii* Merge() const { /*#voodoo This is a little bit spurious, but it prevents having to allocate array space on the heap for a null string. Since InternalLength is zero, the zero-length ascii* null-terminated string can be set here.*/ if(InternalLength == 0) return reinterpret_cast<const ascii*>(&InternalLength); /*If already merged, do not create a new copy. This is determined by checking whether the string takes up the smallest possible space.*/ if(Data.n() == 1 + 4 + 4 + InternalLength + 4) return reinterpret_cast<ascii*>(&Data[1 + 4 + 4]); //Create an array to the flattened string data. Array<byte> FlatData; FlatData.n(1 + 4 + 4 + InternalLength + 4); FlatData[0] = 0; //Alignment-safe copy {uint32 v = 1 + 4; Memory::MemCopy(&FlatData[1], &v, sizeof(v));} {uint32 v = uint32(InternalLength); Memory::MemCopy(&FlatData[5], &v, sizeof(v));} {uint32 v = 0; Memory::MemCopy(&FlatData[1 + 4 + 4 + InternalLength], &v, sizeof(v));} //Location of flattened string in data byte* NewString = &FlatData[1 + 4 + 4]; //Iterate through fragments and copy substrings one by one. Iterator q; while(q.Next(this)) Memory::Copy(&NewString[q.i], &Data[q.f + 4], q.n); //Swap array data so that the old data goes out of scope. Data.SwapWith(FlatData); LastFragmentIndex = 1 + 4; //Reset the default iterator. DefaultIterator.Reset(); //Return pointer to new string. return reinterpret_cast<ascii*>(&Data[1 + 4 + 4]); } ///Inserts a fragment before the character at the index. void Insert(const byte* Fragment, count Length, count IndexBefore) { //If there is no content to add, then just leave. if(Length <= 0 or not Fragment) return; //If index is 0 or below, then this is a prepend. if(IndexBefore <= 0) { Prepend(Fragment, Length); return; } //If index is n or above, then this is an append. if(IndexBefore >= InternalLength) { Append(Fragment, Length); return; } //Add length of incoming fragment to length of total string. InternalLength += Length; Iterator q; while(q.Next(this)) { if(q.i + q.n == IndexBefore) { //Inserting in between two fragments. count OldLength = Data.n(); Data.n(OldLength + 4 + Length + 4); count NextIndex = q.f + 4 + q.n; count RightFragment = count(ReadMarker(NextIndex)); WriteFragment(OldLength, Length, Fragment, RightFragment); WriteMarker(NextIndex, uint32(OldLength)); break; } else if(q.Contains(IndexBefore)) { count IndexInFragment = IndexBefore - q.i; count OldLength = Data.n(); /*There will always be at least one character on the left, since the above case takes care of fragment insert.*/ //-----// //Cases// //-----// //1) Partition (large enough to hold NEXTLENG and 1 char each side) if(q.n - IndexInFragment > 8) { count SquashStart = q.f + 4 + IndexInFragment; uint32 SquashedCharacters[2] = {ReadMarker(SquashStart), ReadMarker(SquashStart + 4)}; Data.n(OldLength + 4 + (4 + 4) + Length + 4); //Write fragment A length. WriteMarker(q.f, uint32(IndexInFragment)); //Write fragment A pointer. WriteMarker(SquashStart, uint32(OldLength)); //Write fragment C length (pointer does not change). WriteMarker(SquashStart + 4, uint32(q.n - IndexInFragment - (4 + 4))); //Write fragment B length. WriteMarker(OldLength, uint32(Length + (4 + 4))); //Copy fragment B data. Memory::Copy(&Data[OldLength + 4], Fragment, Length); //Copy fragment B first squash part data. WriteMarker(OldLength + 4 + Length, SquashedCharacters[0]); //Copy fragment B second squash part data. WriteMarker(OldLength + 4 + Length + 4, SquashedCharacters[1]); //Write fragment B pointer. WriteMarker(OldLength + 4 + Length + 4 + 4, uint32(SquashStart + 4)); //Update last fragment index if necessary. if(LastFragmentIndex == q.f) LastFragmentIndex = SquashStart + 4; } /*2) Total absorb and collapse. There is no space for pointer redirection in the existing fragment.*/ else if(q.n < 1 + (4 + 4) + 1) { //Precalculate some constants. count LeftSideLength = IndexBefore - q.i; count RightSideLength = q.n - LeftSideLength; count NewFragmentLength = LeftSideLength + Length + RightSideLength; //Resize the data array to make room for the new fragment. Data.n(OldLength + 4 + LeftSideLength + Length + RightSideLength + 4); //Point previous fragment to new fragment. WriteMarker(q.p, uint32(OldLength)); //Length of new conflated fragment. WriteMarker(OldLength, uint32(NewFragmentLength)); //Subfragment 1 (left) copy Memory::Copy(&Data[OldLength + 4], &Data[q.f + 4], LeftSideLength); //Subfragment 2 (incoming) copy Memory::Copy(&Data[OldLength + 4 + LeftSideLength], Fragment, Length); //Subfragment 3 (right) copy Memory::Copy(&Data[OldLength + 4 + LeftSideLength + Length], &Data[q.f + 4 + LeftSideLength], RightSideLength); //Pointer to next fragment WriteMarker(OldLength + 4 + NewFragmentLength, ReadMarker(q.f + 4 + q.n)); //Clear out original fragment. Memory::Clear(&Data[q.f], q.n + 8); //Update last fragment index. if(LastFragmentIndex == q.f) LastFragmentIndex = OldLength; //Update iterator. q.f = OldLength; q.n = NewFragmentLength; } //3) Right-side absorb else { //Precalculate some constants. count EightCharAbsorbStart = q.f + 4 + q.n - 8; count LeftSideLength = (IndexBefore - q.i) - (q.n - 8); count RightSideLength = 8 - LeftSideLength; count NewFragmentLength = LeftSideLength + Length + RightSideLength; //Resize the data array to make room for the new fragment. Data.n(OldLength + 4 + LeftSideLength + Length + RightSideLength + 4); //Length of new amalgamated fragment. WriteMarker(OldLength, uint32(NewFragmentLength)); //Subfragment 1 (left) copy Memory::Copy(&Data[OldLength + 4], &Data[EightCharAbsorbStart], LeftSideLength); //Subfragment 2 (incoming) copy Memory::Copy(&Data[OldLength + 4 + LeftSideLength], Fragment, Length); //Subfragment 3 (right) copy Memory::Copy(&Data[OldLength + 4 + LeftSideLength + Length], &Data[EightCharAbsorbStart + LeftSideLength], RightSideLength); //Pointer to next fragment WriteMarker(OldLength + 4 + NewFragmentLength, ReadMarker(q.f + 4 + q.n)); //Pointer to new fragment from old fragment WriteMarker(EightCharAbsorbStart, uint32(OldLength)); //Update old fragment length. WriteMarker(q.f, uint32(EightCharAbsorbStart - (q.f + 4))); //Clear out original fragment. Memory::Clear(&Data[EightCharAbsorbStart + 4], 8); //Update last fragment index. if(LastFragmentIndex == q.f) LastFragmentIndex = OldLength; //Update iterator. q.n = count(ReadMarker(q.f)); } //Insert is finished. break; } } //Reset the default iterator. DefaultIterator.Reset(); } /**Erases any characters that exist from i to j. If j < i, then no characters are erased.*/ void Erase(count i, count j) { Iterator q; //If no characters to erase, then leave. if(not InternalLength) return; //If j < i, then no characters should be erased. if(j < i) return; //If i >= n or j < 0 then no characters need to be erased. if(i >= InternalLength or j < 0) return; //If i is out of bounds, then bring it back in bounds. if(i < 0) i = 0; //If j is out of bounds, then bring it back in bounds. if(j >= InternalLength) j = InternalLength - 1; //Calculate number of characters to erase. count EraseLength = j - i + 1; //If erasing the whole string, just clear it. if(EraseLength == InternalLength) { Clear(); return; } //Subtract length of erased portion. InternalLength -= ((j + 1) - i); //Tracks the last seen fragment for last fragment index update. Iterator LastSeenFragment = q; while(q.Next(this)) { //Get the left and right boundaries of the fragment. count l = q.i, r = q.i + q.n - 1; if(r < i) { //The iterator has not hit an erasure point yet. LastSeenFragment = q; } else if(l > j) { /*The iterator is past the erasure point, so the iterator may stop. Also, since this means the last fragment was not touched, the last fragment index does not change either.*/ break; } else if(i <= l and j >= r) { //The entire fragment may be erased. //Calculate the previous pointer position. count PrevPointerPosition; if(LastSeenFragment.f != 1) { PrevPointerPosition = LastSeenFragment.f + 4 + count(ReadMarker(LastSeenFragment.f)); } else PrevPointerPosition = 1; //Update previous pointer. WriteMarker(PrevPointerPosition, ReadMarker(q.f + 4 + q.n)); //Do not clear the next pointer since iteration must continue. Memory::Clear(&Data[q.f], 4 + q.n); //If the last fragment was cleared, update the last fragment index. if(q.f == LastFragmentIndex) LastFragmentIndex = LastSeenFragment.f; } else if(i <= l and (j >= l and j < r)) { //Perform a left trim. //Make a new length. count NewFragmentPosition = q.f + (j + 1 - q.i); WriteMarker(NewFragmentPosition, uint32(q.n - (j + 1 - q.i))); //Calculate the previous pointer position. count PrevPointerPosition; if(LastSeenFragment.f != 1) { PrevPointerPosition = LastSeenFragment.f + 4 + count(ReadMarker(LastSeenFragment.f)); } else PrevPointerPosition = 1; //Update previous pointer. WriteMarker(PrevPointerPosition, uint32(NewFragmentPosition)); //If the last fragment was cleared, update the last fragment index. if(q.f == LastFragmentIndex) LastFragmentIndex = NewFragmentPosition; //By definition the erasing is over if left trim was used. break; } else if(j >= r and (i > l and i <= r)) { //Perform a right trim. //Move next pointer down. count FragmentALength = i - q.i; WriteMarker(q.f + 4 + FragmentALength, ReadMarker(q.f + 4 + q.n)); /*Update iterator so it does not break when it looks for the pointer, and also adjust bounds of erasure so erase does not overshoot.*/ j -= q.n - FragmentALength; q.n = FragmentALength; //Adjust length. WriteMarker(q.f, uint32(FragmentALength)); //Remember that this fragment was kept. LastSeenFragment = q; } else { /*Excise within fragment. There are three cases: 1) Large excise, in middle of long fragment 2) Small excise, in middle of long fragment 3) Small excise near right edge of long fragment*/ if(EraseLength < (4 + 4)) { //Small excise if((i - q.i) + (4 + 4) < q.n) { //In middle: create new fragment for squashed characters. count SquashedLength = (4 + 4) - EraseLength; count SquashedStart = q.f + 4 + (j + 1 - q.i); count NewFragmentStart = Data.n(); count FragmentALength = i - q.i; count FragmentBStart = q.f + 4 + FragmentALength + 4; count FragmentBLength = q.n - FragmentALength - (4 + 4); //Create a new fragment for the squashed characters. Data.n(NewFragmentStart + 4 + SquashedLength + 4); WriteMarker(NewFragmentStart, uint32(SquashedLength)); Memory::Copy(&Data[NewFragmentStart + 4], &Data[SquashedStart], SquashedLength); WriteMarker(NewFragmentStart + 4 + SquashedLength, uint32(FragmentBStart)); //Update fragment A length. WriteMarker(q.f, uint32(FragmentALength)); //Point fragment A to the squashed fragment. WriteMarker(q.f + 4 + FragmentALength, uint32(NewFragmentStart)); //Set fragment B length. WriteMarker(q.f + 4 + FragmentALength + 4, uint32(FragmentBLength)); //If the last fragment was altered, update last fragment index. if(q.f == LastFragmentIndex) LastFragmentIndex = FragmentBStart; } else { //Near right edge: shift characters down including pointer. count ShiftStart = q.f + 4 + (i - q.i); count ShiftDistance = EraseLength; count ShiftSize = q.n - (j + 1 - q.i) + 4; for(count k = ShiftStart; k < ShiftStart + ShiftSize; k++) Data[k] = Data[k + ShiftDistance]; //Update the fragment length. WriteMarker(q.f, uint32(q.n - EraseLength)); /*Since fragment beginnings were not created or altered, there is no need to update the last fragment index.*/ } } else { /*Note that it is implied that since this is not a fragment trim operation, the maximum value of 'j' is the position of the second- to-last character of the fragment. Thus, with an erase length of at least 4 + 4, there will be enough room in the erasure space to create a new length-pointer marker.*/ /*Large excise using pointers to skip erased section. Fragment is split into two fragments A and B using erased character space for the length-pointer markers.*/ //Adjust fragment A length. count FragmentALength = i - q.i; WriteMarker(q.f, uint32(FragmentALength)); //Write fragment A pointer to fragment B. count FragmentBStart = q.f + 4 + ((j + 1) - q.i) - 4; WriteMarker(q.f + 4 + FragmentALength, uint32(FragmentBStart)); //Write fragment B length (fragment B pointer to next is the same). count FragmentBLength = q.n - (j - q.i) - 1; WriteMarker(FragmentBStart, uint32(FragmentBLength)); //Clear any additional erased space. Memory::Clear(&Data[q.f + 4 + FragmentALength + 4], EraseLength - (4 + 4)); //If the last fragment was altered, update the last fragment index. if(q.f == LastFragmentIndex) LastFragmentIndex = FragmentBStart; } /*Since the excise occurred within the fragment, the operation is complete.*/ break; } } //Reset the default iterator. DefaultIterator.Reset(); } ///Erase a single character at the given index. void Erase(count i) {Erase(i, i);} ///Erase the last character of the string. void EraseLast() {Erase(n() - 1);} ///Erase the first character of the string. void EraseFirst() {Erase(0);} /**Erases the given ending from the string if it exists. Returns whether or not the erase took place.*/ bool EraseEnding(const ascii* s) { if(not EndsWith(s)) return false; Erase(n() - LengthOf(s), n() - 1); return true; } /**Erases the given beginning from the string if it exists. Returns whether or not the erase took place.*/ bool EraseBeginning(const ascii* s) { if(not StartsWith(s)) return false; Erase(0, LengthOf(s) - 1); return true; } ///Removes the given quote characters if they exist. void Unquote(unicode QuoteCharacter = '"') { String s(QuoteCharacter); if(StartsWith(s) and EndsWith(s)) EraseFirst(), EraseLast(); } ///Returns this string with the given quote characters removed. String Unquoted(unicode QuoteCharacter = '"') const { String s = *this; s.Unquote(QuoteCharacter); return s; } ///Wrapper to insert null-terminated string. void Insert(const ascii* s, count IndexBefore) { Insert(reinterpret_cast<const byte*>(s), LengthOf(s), IndexBefore); } ///Wrapper to append null-terminated string. void Append(const ascii* s) { Append(reinterpret_cast<const byte*>(s), LengthOf(s)); } ///Wrapper to prepend null-terminated string. void Prepend(const ascii* s) { Prepend(reinterpret_cast<const byte*>(s), LengthOf(s)); } ///Clears the string so that it is zero-length and has no data on the heap. inline void Clear() { //Remove any attached stream. AttachedStream = NotAttached; //Zero out the members. Data.n(LastFragmentIndex = InternalLength = 0); //Set precision to default. NumberPrecision = 5; //Reset the default iterator. DefaultIterator.Reset(); } ///Attaches the string to one of the standard streams. void Attach(StreamAttachment StreamToAttachTo); private: ///Appends the fragment to the current attached stream. void AppendToStream(const byte* Fragment, count Length); public: /**Replaces a fragment with another string. The method first erases the fragment to be replaced and then inserts the new string.*/ void Replace(count SourceIndex, count SourceLength, const byte* Destination, count DestinationLength) { Erase(SourceIndex, SourceIndex + SourceLength - 1); Insert(Destination, DestinationLength, SourceIndex); } ///Wrapper to replace fragment with null-terminated string. void Replace(count SourceIndex, count SourceLength, const ascii* Destination) { Replace(SourceIndex, SourceLength, reinterpret_cast<const byte*>(Destination), LengthOf(Destination)); } //------------------// //Character Indexing// //------------------// ///Gets a character at the specified index. inline byte operator [] (count i) const { return Get(i); } //----------------// //Find and Replace// //----------------// /**Finds the next occurrence of the source string. Returns -1 if no match is found. Use StartIndex to start the find at a different position. Also, if StartIndex is less than 0, then no find occurs and -1 is returned.*/ count Find(const byte* Source, count SourceLength, count StartIndex) const { if(not Source or SourceLength == 0 or InternalLength == 0 or StartIndex < 0) return -1; count MaxCharacter = InternalLength - SourceLength; if(Data.n() == 1 + 4 + 4 + InternalLength + 4) { //Take advantage of a merged string by randomly accessing. const byte* StringStart = reinterpret_cast<const byte*>(&(Merge()[StartIndex])); for(count i = StartIndex; i <= MaxCharacter; i++, StringStart++) { bool MatchFound = true; for(count j = 0; j < SourceLength; j++) { if(StringStart[j] != Source[j]) { MatchFound = false; break; } } if(MatchFound) return i; } } else { /*If not merged use the slower but more string-manipulation friendly find, which uses an iterator.*/ for(count i = StartIndex; i <= MaxCharacter; i++) { bool MatchFound = true; for(count j = 0; j < SourceLength; j++) { if(Get(i + j) != Source[j]) { MatchFound = false; break; } } if(MatchFound) return i; } } return -1; } ///Finds next occurrence of source string. count Find(const ascii* Source, count StartIndex) const { return Find(reinterpret_cast<const byte*>(Source), LengthOf(Source), StartIndex); } ///Finds first occurrence of source string. count Find(const ascii* Source) const { return Find(Source, 0); } /**Globally replaces source string with destination string. Returns the number of replacements made. Since global replacement can make a lot of changes to the string, this can create many internal links. To prevent this from slowing down replaces on a long string with many replaces, the string must be merged at an interval of replacements that can be adjusted with MergeEvery.*/ count Replace(const ascii* Source, const ascii* Destination, count MergeEvery = 30) { return Replace(reinterpret_cast<const byte*>(Source), LengthOf(Source), reinterpret_cast<const byte*>(Destination), LengthOf(Destination), MergeEvery); } /**Global replace by byte-wise block of data. Generally, you should use the null-terminated string Replace method unless for the search or replace term could contain a null.*/ count Replace(const byte* Source, count SourceLength, const byte* Destination, count DestinationLength, count MergeEvery = 30) { //Make sure the merge every interval is reasonable. MergeEvery = Max(count(1), Min(count(1000), MergeEvery)); count Replacements = 0; //For each occurrence of the source, replace it with the destination. count Next = Find(Source, SourceLength, 0); while(Next != -1) { Replace(Next, SourceLength, Destination, DestinationLength); Replacements++; /*If there are a ton of replacements happening, then merge every now and then to prevent iterations from taking up a lot of time.*/ if(Replacements % MergeEvery == 0) Merge(); Next = Find(Source, SourceLength, Next + DestinationLength); } //Return the number of replacements made. return Replacements; } ///Returns whether the string contains the source string. bool Contains(const ascii* Source) const { return Find(Source) != -1; } ///Returns a substring of characters between two indices inclusively. String Substring(count i, count j) const { if(i < 0 or j < i or j >= n()) return ""; return String(reinterpret_cast<const byte*>(&(Merge()[i])), j - i + 1); } ///Returns a substring of characters between two indices inclusively. String Substring(String::Span Selection) const { return Substring(Selection.i(), Selection.j()); } /**Returns the start and end index of the next string containing the tokens. If no start is found then <-1, -1> is returned. If a start is found, but no end is found then <Start Index, -1> is returned. If no span is found, then BetweenText will be empty as well.*/ String::Span FindBetween(const ascii* Begin, const ascii* End, String& BetweenText, count StartIndex = 0) const { BetweenText = ""; count StartPlace = Find(Begin, StartIndex); if(StartPlace == -1) return String::Span(-1, -1); count BeginLength = LengthOf(Begin); count EndPlace = Find(End, StartPlace + BeginLength); if(EndPlace == -1) return String::Span(StartPlace, -1); BetweenText = Substring(String::Span(StartPlace + BeginLength, EndPlace - 1)); return String::Span(StartPlace, EndPlace + LengthOf(End) - 1); } /**Finds which pair of tokens is next. Returns the index if one is found, and otherwise, or if the lists are not of equal size, returns -1. Call FindBetween using the given tokens to then determine the location of the token pair.*/ count FindBetweenAmong(const List<String>& StartTokens, const List<String>& EndTokens, String::Span& Location, String& BetweenText, count StartIndex = 0) const { if(StartTokens.n() != EndTokens.n()) return -1; count LeastIndex = -1, IndexOfFound = -1; for(count i = 0; i < StartTokens.n(); i++) { String FindBetweenText; String::Span Next = FindBetween(StartTokens[i], EndTokens[i], FindBetweenText, StartIndex); if(Next.j() == -1) continue; if(Next.i() < LeastIndex or LeastIndex == -1) { Location = Next; BetweenText = FindBetweenText; LeastIndex = Next.i(); IndexOfFound = i; } } return IndexOfFound; } ///Converts all line endings (LF, CR, CRLF) to LF. void LineEndingsToLF() { Replace("\r\n", "\r"); Replace("\r", "\n"); Merge(); } ///Converts all line endings (LF, CR, CRLF) to CRLF. void LineEndingsToCRLF() { LineEndingsToLF(); Replace("\n", "\r\n"); Merge(); } ///Tokenizes the string by a delimiter and returns a list of strings. List<String> Tokenize(String Delimiter, bool RemoveEmptyEntries = false) const { //Make a copy of the string. String s = *this; //Add tokens at beginning and ending for using FindBetween. s.Prepend(Delimiter.Merge()); s.Append(Delimiter.Merge()); //Parse the paths into a list. List<String> Result; String::Span Location; String NextResult; while((Location = s.FindBetween(Delimiter, Delimiter, NextResult, Location.j())).j() != -1) Result.Add(NextResult); //Remove empty entries if requested. if(RemoveEmptyEntries) for(count i = Result.n() - 1; i >= 0; i--) if(not Result[i]) Result.Remove(i); //Return the list of tokenized strings. return Result; } /**Removes all whitespace at the beginning and ending of the string. This is just removing spaces, line feeds, carriage returns, and tabs. It does not take into account the Unicode definition of whitespace.*/ void Trim() { while(StartsWith(" ") or StartsWith("\n") or StartsWith("\r") or StartsWith("\t")) EraseFirst(); while(EndsWith(" ") or EndsWith("\n") or EndsWith("\r") or EndsWith("\t")) EraseLast(); } //----------------// //Operator Appends// //----------------// //String used for newlines ///Unix and Mac newline static const ascii* LF; ///Microsoft Windows newline static const ascii* CRLF; ///Global newline operator for ++ operations static const ascii* Newline; ///Appends a space to the string. void operator -- (int Dummy) { (void)Dummy; Append(" "); } ///Appends a new line to the string. void operator ++ (int Dummy) { (void)Dummy; Append(Newline); } ///Returns whether the string starts with the source. bool StartsWith(const ascii* Source) const { if(not Source) return false; return Find(Source) == 0; } ///Returns whether the string ends with the source. bool EndsWith(const ascii* Source) const { if(not Source) return false; count SourceLength = LengthOf(Source); return Find(reinterpret_cast<const byte*>(Source), SourceLength, InternalLength - SourceLength) != -1; } ///Returns whether the string matches the other byte for byte. bool operator == (const ascii* Other) const { if(LengthOf(Other) != n()) return false; if(n() == 0) return true; const ascii* This = Merge(); for(count i = n() - 1; i >= 0; i--) if(This[i] != Other[i]) return false; return true; } ///Returns the opposite of the equivalence operator test. bool operator != (const ascii* Other) const { return not (*this == Other); } //----------------// //Stream Appending// //----------------// ///Appends a bool using the familiar standard stream << operator. String& operator << (bool v); ///Appends an uint8 using the familiar standard stream << operator. String& operator << (uint8 v); //Skipping int8 since it will be handled as ascii. ///Appends an uint16 using the familiar standard stream << operator. String& operator << (uint16 v); ///Appends an int16 using the familiar standard stream << operator. String& operator << (int16 v); ///Appends an uint32 using the familiar standard stream << operator. String& operator << (uint32 v); ///Appends an int32 using the familiar standard stream << operator. String& operator << (int32 v); ///Appends an uint64 using the familiar standard stream << operator. String& operator << (uint64 v); ///Appends an int64 using the familiar standard stream << operator. String& operator << (int64 v); ///Appends a float32 using the familiar standard stream << operator. String& operator << (float32 v); ///Appends a float64 using the familiar standard stream << operator. String& operator << (float64 v); ///Appends a float80 using the familiar standard stream << operator. String& operator << (float80 v); ///Appends a void pointer using the familiar standard stream << operator. String& operator << (const void* v); ///Appends a smart pointer using the familiar standard stream << operator. template <class T> String& operator << (const Pointer<T>& p) { //Show number of references. String s; s >> reinterpret_cast<const void*>(p.Raw()) << "+" << p.n(); //Also show number of weak pointers if they exist. if(p.n(true) != p.n(false)) s << "-" << (p.n(true) - p.n(false)); Append(s.Merge()); return *this; } ///Appends a vector to the stream. template <class T> String& operator << (const Complex<T>& v) { String s; if(v.IsEmpty()) s >> "(Empty)"; else s >> "(" << v.x << ", " << v.y << ")"; Append(s.Merge()); return *this; } ///Appends an array to the stream. template <class T> String& operator << (const Array<T>& a) { String s; s >> "["; for(count i = 0; i < a.n(); i++) { if(i) s << ", "; s << a[i]; } s << "]"; Append(s.Merge()); return *this; } ///Appends a list to the stream. template <class T> String& operator << (const List<T>& a) { String s; s >> "{"; for(count i = 0; i < a.n(); i++) { if(i) s << ", "; s << a[i]; } s << "}"; Append(s.Merge()); return *this; } ///Appends a tree to the stream. template <class K, class V> String& operator << (const Tree<K, V>& a) { String s; s >> "{"; typename Tree<K, V>::Iterator It; bool First = true; for(It.Begin(a); It.Iterating(); It.Next(), First = false) { if(not First) s << ", "; s << It.Key() << ":" << It.Value(); } s << "}"; Append(s.Merge()); return *this; } ///Appends a matrix to the stream. template <class T> String& operator << (const Matrix<T>& M) { //Return the empty matrix if there are no elements. if(M.mn() == 0) { Append("or"); return *this; } //Create a matrix of strings. Matrix<String> S(M.m(), M.n()); for(count j = 0; j < M.n(); j++) { count MaxLength = 0; for(count i = 0; i < M.m(); i++) { S(i, j) << M.ij(i, j); MaxLength = Max(MaxLength, S(i, j).c()); } //Normalize the lengths of each column. for(count i = 0; i < M.m(); i++) for(count k = S(i, j).c(); k < MaxLength; k++) S(i, j) << " "; } //Create the matrix string. String Out; for(count i = 0; i < M.m(); i++) { Out++; Out << "|"; for(count j = 0; j < M.n(); j++) Out << S(i, j) << (j < M.n() - 1 ? " " : "|"); } Out++; Append(Out.Merge()); return *this; } ///Appends a letter using the familiar standard stream << operator. String& operator << (ascii c) { Append(reinterpret_cast<byte*>(&c), 1); return *this; } ///Appends a string using the familiar standard stream << operator. String& operator << (const ascii* s) { Append(s); return *this; } ///Appends a string using the familiar standard stream << operator. String& operator << (const String& s) { Append(reinterpret_cast<const byte*>(s.Merge()), s.n()); return *this; } ///Appends a newline if string is not empty and then applies << operator. template <class T> String& operator >> (const T& v) { if(InternalLength != 0) Append(Newline); *this << v; return *this; } ///Concatenates this string with another object. template <class T> String operator + (const T& v) const { String s = *this; s << v; return s; } //------// //Length// //------// ///Returns the number of characters in a null-terminated string. static count LengthOf(const ascii* s); ///Returns the number of bytes in the string. inline count n() const {return InternalLength;} //----------------------// //Constructor-Destructor// //----------------------// ///Constructor creates an empty string. inline String() {Clear();} ///Constructs a string that is attached to one of the standard streams. String(StreamAttachment StreamToAttachTo) { Clear(); Attach(StreamToAttachTo); } ///Copy constructor to initialize string with contents of other string. String(const ascii* Other) {Clear(); Append(Other);} ///Copy constructor to initialize string with contents of other string. String(const byte* Other, count Length) {Clear(); Append(Other, Length);} ///Appends a bool during construction. String(bool v) {Clear(); (*this) << v;} ///Appends an uint8 during construction. String(uint8 v) {Clear(); (*this) << v;} //Skipping int8 since it will be handled as ascii. ///Appends a letter during construction. String(ascii c) {Clear(); (*this) << c;} ///Appends an uint16 during construction. String(uint16 v) {Clear(); (*this) << v;} ///Appends an int16 during construction. String(int16 v) {Clear(); (*this) << v;} //Skipping uint32 since it will be handled as unicode. ///Constructor to initialize string with a unicode codepoint. String(unicode Codepoint) {Clear(); Append(Codepoint);} ///Appends an int32 during construction. String(int32 v) {Clear(); (*this) << v;} ///Appends an uint64 during construction. String(uint64 v) {Clear(); (*this) << v;} ///Appends an int64 during construction. String(int64 v) {Clear(); (*this) << v;} ///Appends a float32 during construction. String(float32 v) {Clear(); (*this) << v;} ///Appends a float64 during construction. String(float64 v) {Clear(); (*this) << v;} ///Appends a float80 during construction. String(float80 v) {Clear(); (*this) << v;} ///Appends a void pointer during construction. String(void* v) {Clear(); (*this) << v;} ///Appends a smart pointer during construction. template <class T> String(const Pointer<T>& p) {Clear(); (*this) << p;} ///Appends a vector during construction. template <class T> String(const Complex<T>& v) {Clear(); (*this) << v;} ///Appends an array during construction. template <class T> String(const Array<T>& a) {Clear(); (*this) << a;} ///Appends a list during construction. template <class T> String(const List<T>& a) {Clear(); (*this) << a;} ///Appends a tree during construction. template <class K, class V> String(const Tree<K, V>& a) { Clear(); (*this) << a; } ///Appends a matrix during construction. template <class T> String(const Matrix<T>& M) {Clear(); (*this) << M;} //----------// //Assignment// //----------// ///Assigns string to contents of other string. String& operator = (const ascii* Other) { Clear(); Append(Other); return *this; } ///Assigns string to a bool. String& operator = (bool v) {Clear(); return (*this) << v;} ///Assigns string to an uint8. String& operator = (uint8 v) {Clear(); return (*this) << v;} //Skipping int8 since it will be handled as ascii. ///Assigns string to a letter. String& operator = (ascii c) {Clear(); return (*this) << c;} ///Assigns string to an uint16. String& operator = (uint16 v) {Clear(); return (*this) << v;} ///Assigns string to an int16. String& operator = (int16 v) {Clear(); return (*this) << v;} //Skipping uint32 since it will be handle as unicode. ///Assigns string to a unicode codepoint. String& operator = (unicode Codepoint) { Clear(); Append(Codepoint); return *this; } ///Assigns string to an int32. String& operator = (int32 v) {Clear(); return (*this) << v;} ///Assigns string to an uint64. String& operator = (uint64 v) {Clear(); return (*this) << v;} ///Assigns string to an int64. String& operator = (int64 v) {Clear(); return (*this) << v;} ///Assigns string to a float32. String& operator = (float32 v) {Clear(); return (*this) << v;} ///Assigns string to a float64. String& operator = (float64 v) {Clear(); return (*this) << v;} ///Assigns string to a float80. String& operator = (float80 v) {Clear(); return (*this) << v;} ///Assigns string to a void pointer. String& operator = (void* v) {Clear(); return (*this) << v;} ///Assigns string to a smart pointer. template <class T> String& operator = (const Pointer<T>& p) { Clear(); return (*this) << p; } ///Assigns string to a vector. template <class T> String& operator = (const Complex<T>& v) { Clear(); return (*this) << v; } ///Assigns string to an array. template <class T> String& operator = (const Array<T>& a) { Clear(); return (*this) << a; } ///Assigns string to a list. template <class T> String& operator = (const List<T>& a) { Clear(); return (*this) << a; } ///Assigns string to a list. template <class K, class V> String& operator = (const Tree<K, V>& a) { Clear(); return (*this) << a; } ///Assigns string to a matrix. template <class T> String& operator = (const Matrix<T>& M) { Clear(); return (*this) << M; } //---------// //Operators// //---------// ///Automatic conversion to const ascii* where possible. inline operator const ascii* () const {return Merge();} /**Returns whether or not the string is not empty. The following shows how this can be used in an if-statement: \code * String s; * ... * if(s) * c >> "s contains something"; * else * c >> "s is empty"; \endcode */ inline operator bool() const {return n() > 0;} //---------------------// //Conversion to Numbers// //---------------------// ///Attempts to convert the string to a number. number ToNumber() const; //--------------// //Hex Conversion// //--------------// private: ///Give UUIDv4 access to the hex utilities here. friend class UUIDv4; ///Lookup table for hexadecimal to digit conversion. static const byte HexMap[256]; ///Converts a byte into two hexadecimal digits. static void ToHex(byte Data, ascii& High, ascii& Low) { ascii DataHigh = ascii(Data >> 4); ascii DataLow = ascii(Data % 16); High = (DataHigh < 10 ? DataHigh + '0' : (DataHigh - 10) + 'a'); Low = (DataLow < 10 ? DataLow + '0' : (DataLow - 10) + 'a'); } public: ///Converts hex string to byte array. static Array<byte> Hex(const String& HexString) { //Clear the output array. Array<byte> ByteArray; //Get access to merged string. const byte* d = reinterpret_cast<const byte*>(HexString.Merge()); //Must have even number of hex digits. if(HexString.n() % 2 != 0) return ByteArray; //Set the array size. ByteArray.n(HexString.n() / 2); //Go through pairs of characters and set the bytes of the array. for(count i = 0, j = 0; i < HexString.n(); i += 2, j++) { byte h = HexMap[count(d[i])], l = HexMap[count(d[i + 1])]; //If an unexpected character occurs, then abort with a null array. if(h >= 16 or l >= 16) { ByteArray.Clear(); break; } ByteArray[j] = byte((h << 4) + l); } return ByteArray; } ///Converts byte array to hex string. static String Hex(const Array<byte>& ByteArray) { Array<ascii> HexedArray(ByteArray.n() * 2); for(count i = 0; i < ByteArray.n(); i++) { ascii High = 0, Low = 0; ToHex(ByteArray[i], High, Low); HexedArray[i * 2] = High; HexedArray[i * 2 + 1] = Low; } return String(reinterpret_cast<byte*>(&HexedArray.a()), HexedArray.n()); } /**Converts a number written in hex to an integer ignoring non-hex letters. Returns zero in case of an overflow.*/ uint64 ToHexNumber() const { const byte* d = reinterpret_cast<const byte*>(Merge()); uint64 CurrentValue = 0; uint64 PreviousValue = 0; for(count i = 0; i < n(); i++) { uint64 Digit = HexMap[count(d[i])]; if(Digit < 16) CurrentValue = CurrentValue * uint64(16) + Digit; if(PreviousValue * 16 < PreviousValue || CurrentValue < PreviousValue) return 0; PreviousValue = CurrentValue; } return CurrentValue; } //---------------// //Case Conversion// //---------------// ///Returns the Latin Basic and Latin-1 uppercase of the string. String ToUpper() const { return ToLatin1Upper(); } ///Returns the Latin Basic and Latin-1 lowercase of the string. String ToLower() const { return ToLatin1Lower(); } ///Returns the Latin Basic and Latin-1 title case of the string. String ToTitle() const { return ToLatin1Title(); } ///Sanitizes to an identifier suitable for common programming languages. String ToIdentifier() const { String In = Merge(); //Convert special characters to numbers. const char* Filter[32] = {"`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "=", "+", "{", "[", "}", "]", "|", "\\", ";", ":", "\"", "'", "<", ",", ">", ".", "/", "?", " "}; Array<String> Filters(Filter, 32); for(count i = 0; i < Filters.n(); i++) In.Replace(Filters[i], "_"); //Prefix leading numbers and underscores with text. const char* Number[11] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "_"}; Array<String> Numbers(Number, 11); for(count i = 0; i < Numbers.n(); i++) if(In.StartsWith(Numbers[i])) In.Prepend("n"); return In; } ///Given an absolute filename returns the path with trailing slash. String ToPath() const { String Filename = Merge(); for(count i = Filename.n() - 1; i > 0; i--) { if(Filename[i] == '/' or Filename[i] == '\\') { Filename.Erase(i + 1, Filename.n() - 1); return Filename; } } return ""; } ///Given an absolute filename returns the filename with no path. String ToFilename() const { String Filename = Merge(); for(count i = Filename.n() - 1; i > 0; i--) { if(Filename[i] == '/' or Filename[i] == '\\') { Filename.Erase(0, i); return Filename; } } return Filename; } ///Returns the Latin-1 uppercase character equivalent. static unicode ToLatin1Upper(unicode c) { if(c >= 'a' and c <= 'z') c -= ('a' - 'A'); else if(c >= 0xE0 and c <= 0xFE and c != 0xF7) c -= 0x20; else if(c == 0xDF) c = 0x1E9E; else if(c == 0xFF) c = 0x0178; return c; } ///Returns the Latin-1 lowercase character equivalent. static unicode ToLatin1Lower(unicode c) { if(c >= 'A' and c <= 'Z') c += ('a' - 'A'); else if(c >= 0xC0 and c <= 0xDE and c != 0xD7) c += 0x20; else if(c == 0x1E9E) c = 0xDF; else if(c == 0x0178) c = 0xFF; return c; } ///Uppercases any Latin Basic or Latin-1 characters. String ToLatin1Upper() const { const byte* ReadPosition = reinterpret_cast<const byte*>(Merge()); const byte* EndMarker = &ReadPosition[InternalLength]; String s; while(ReadPosition != EndMarker) s.Append(ToLatin1Upper(Decode(ReadPosition, EndMarker))); return s; } ///Lowercases any Latin Basic or Latin-1 characters. String ToLatin1Lower() const { const byte* ReadPosition = reinterpret_cast<const byte*>(Merge()); const byte* EndMarker = &ReadPosition[InternalLength]; String s; while(ReadPosition != EndMarker) s.Append(ToLatin1Lower(Decode(ReadPosition, EndMarker))); return s; } ///Title-cases any Latin Basic or Latin-1 characters. String ToLatin1Title() const { const byte* ReadPosition = reinterpret_cast<const byte*>(Merge()); const byte* EndMarker = &ReadPosition[InternalLength]; String s; bool InitialCharacter = true; while(ReadPosition != EndMarker) { unicode c = Decode(ReadPosition, EndMarker); if(c == 0x20) InitialCharacter = true; else if(InitialCharacter) c = ToLatin1Upper(c), InitialCharacter = false; else c = ToLatin1Lower(c); s.Append(c); } return s; } //-----// //UTF-8// //-----// /*Encodes and decodes UTF-8 in a String. Internally, String is a byte array with no inherent encoding. String simply provides a means to safely encode and decode a string as UTF-8. It will filter out bad character sequences as a part of encoding and decoding, but it does nothing to ensure that the string data is valid UTF-8 since String does not have an explicit encoding.*/ private: ///Lookup table for codepoint bias static const unicode CodepointBias[256]; ///Lookup table for octet classification static const count OctetClassification[256]; /*Given an octet class, the encoded value must be at least this number. Otherwise, the value is overlong (has been encoded with higher octet class than strictly necessary.*/ static const count OverlongThresholds[7]; public: /**Decodes the next character of a UTF-8 string according to the ISO 10646-1:2000 standard for safely decoding an arbitrary byte stream as UTF-8. StreamEnd is the location of the first out-of-bounds byte. It is the responsibility of the caller to make sure that Stream < StreamEnd. The method does handle a sudden stream termination in the middle of a multi-byte UTF-8 sequence.*/ static unicode Decode(const byte*& Stream, const byte* StreamEnd) { byte Octet1, Octet2, Octet3, Octet4, Octet5, Octet6; unicode Value = meta::BadCharacter; //Classify by initial octet. Octet1 = *Stream++; //Assumes caller knows Stream < StreamEnd. count OctetClass = OctetClassification[Octet1]; if(OctetClass == 1) //ASCII character return Octet1; //No need to validate since ASCII is always valid. else if(OctetClass == 2 and Stream != StreamEnd) //2-octet sequence { Octet2 = *Stream; if(OctetClassification[Octet2] == 0 and ++Stream) Value = CodepointBias[Octet1] + CodepointBias[Octet2]; } else if(OctetClass == 3 and Stream != StreamEnd) //3-octet sequence { Octet2 = *Stream; if(OctetClassification[Octet2] == 0 and ++Stream != StreamEnd) { Octet3 = *Stream; if(OctetClassification[Octet3] == 0 and ++Stream) { Value = CodepointBias[Octet1] + (CodepointBias[Octet2] << 6) + CodepointBias[Octet3]; } } } else if(OctetClass == 4 and Stream != StreamEnd) //4-octet sequence { Octet2 = *Stream; if(OctetClassification[Octet2] == 0 and ++Stream != StreamEnd) { Octet3 = *Stream; if(OctetClassification[Octet3] == 0 and ++Stream != StreamEnd) { Octet4 = *Stream; if(OctetClassification[Octet4] == 0 and ++Stream) { Value = CodepointBias[Octet1] + (CodepointBias[Octet2] << 12) + (CodepointBias[Octet3] << 6) + CodepointBias[Octet4]; } } } } else if(OctetClass == 5 and Stream != StreamEnd) //5-octet sequence (bad) { Octet2 = *Stream; if(OctetClassification[Octet2] == 0 and ++Stream != StreamEnd) { Octet3 = *Stream; if(OctetClassification[Octet3] == 0 and ++Stream != StreamEnd) { Octet4 = *Stream; if(OctetClassification[Octet4] == 0 and ++Stream != StreamEnd) { Octet5 = *Stream; if(OctetClassification[Octet5] == 0 and ++Stream) { Value = CodepointBias[Octet1] + (CodepointBias[Octet2] << 18) + (CodepointBias[Octet3] << 12) + (CodepointBias[Octet4] << 6) + CodepointBias[Octet5]; } } } } } else if(OctetClass == 6 and Stream != StreamEnd) //6-octet sequence (bad) { Octet2 = *Stream; if(OctetClassification[Octet2] == 0 and ++Stream != StreamEnd) { Octet3 = *Stream; if(OctetClassification[Octet3] == 0 and ++Stream != StreamEnd) { Octet4 = *Stream; if(OctetClassification[Octet4] == 0 and ++Stream != StreamEnd) { Octet5 = *Stream; if(OctetClassification[Octet5] == 0 and ++Stream != StreamEnd) { Octet6 = *Stream; if(OctetClassification[Octet6] == 0 and ++Stream) { Value = CodepointBias[Octet1] + (CodepointBias[Octet2] << 24) + (CodepointBias[Octet3] << 18) + (CodepointBias[Octet4] << 12) + (CodepointBias[Octet5] << 6) + CodepointBias[Octet6]; } } } } } } //Check for overlongs forms. if(OctetClass >= 1 and OctetClass <= 6 and Value < unicode(OverlongThresholds[OctetClass])) Value = meta::BadCharacter; //Check if value is above maximum usable Unicode point. if(Value > 0x10FFFF) Value = meta::BadCharacter; /*Strip any UTF-16 surrogates and illegal code positions that are invalid in UTF-8.*/ if(Value == 0xD800 or Value == 0xDB7F or Value == 0xDB80 or Value == 0xDBFF or Value == 0xDC00 or Value == 0xDF80 or Value == 0xDFFF or Value == 0xFFFE or Value == 0xFFFF) Value = meta::BadCharacter; return Value; } ///Reads the string to determine if it is a valid UTF-8 string. bool IsUTF8() const { const byte* a = reinterpret_cast<const byte*>(Merge()); const byte* z = a + n(); unicode d; do { d = Decode(a, z); if(d == meta::BadCharacter) return false; } while(d); return true; } /**Reads the string to determine if it is a valid ASCII string. Note that non-printable characters aside from tab, line space, carriage return are excluded (other control characters will cause the string to not report as ASCII).*/ bool IsASCII() const { const byte* a = reinterpret_cast<const byte*>(Merge()); byte d; do { d = *a++; if(d != 0 and d != 9 and d != 10 and d != 13 and not (d >= 32 and d <= 126)) return false; } while(d); return true; } /**Reads the string to determine if it is a valid Latin-1 string (conforms to ISO-8859-1).*/ bool IsLatin1() const { if(IsASCII()) return true; if(IsUTF8()) return false; const byte* a = reinterpret_cast<const byte*>(Merge()); byte d; do { d = *a++; if(d != 0 and d != 9 and d != 10 and d != 13 and not (d >= 32 and d <= 126) and not (d >= 160)) return false; } while(d); return true; } ///Returns whether the character is alphanumeric. static bool IsAlphanumeric(unicode c) { return (c >= '0' and c <= '9') or (c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z'); } ///Returns whether the character is alphanumeric. static bool IsAlphanumeric(ascii c) { return IsAlphanumeric(unicode(c)); } ///Returns the canonical lorem ipsum filler text. static String LoremIpsum() { return "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed " "do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim " "ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut " "aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit " "in voluptate velit esse cillum dolore eu fugiat nulla pariatur. " "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui " "officia deserunt mollit anim id est laborum."; } class UTF16 { public: enum ByteOrder { ByteOrderUnspecified = 0x0, ByteOrderLE = 0xfffe, ByteOrderBE = 0xfeff }; ///Detects the presence of a BOM at the beginning of the string. static ByteOrder BOM(const String& In) { return BOM(StringToUTF16Pointer(In)); } /**Uses common characters (space 0x20, line feed 0x0A) to find byte order. If there are more 0x2000 and 0x0A00 values than 0x0020 and 0x00A0 values, then the byte order is guessed to be little-endian. Likewise, if there are more 0x0020 and 0x00A0 values than 0x2000 and 0x0A00 values then the byte order is guessed to be big-endian. If neither is found, the byte order is unspecified. Note that this method assumes that the input is a UTF-16 string.*/ static ByteOrder GuessByteOrder(const String& In) { return GuessByteOrder( StringToUTF16Pointer(In), ByteOrderSearchLength(In)); } static bool IsUTF16(const String& In) { return BOM(In) != ByteOrderUnspecified or GuessByteOrder(In) != ByteOrderUnspecified; } static String Decode(const String& In) { ByteOrder AssumedByteOrder = BOM(In); if(AssumedByteOrder == ByteOrderUnspecified) AssumedByteOrder = GuessByteOrder(In); String Out; Decode(StringToUTF16Pointer(In), &StringToUTF16Pointer(In)[In.n() / 2], AssumedByteOrder, Out); if(not Out) Out = In; return Out; } private: static count ByteOrderSearchLength(const String& In) { count SearchLength = 0; if(In.n() % 2 == 0) SearchLength = Min(In.n() / 2, count(1024)); return SearchLength; } static void Decode(const uint16* In, const uint16* InEnd, ByteOrder ByteOrderToUse, String& Out) { Out.Clear(); if(ByteOrderToUse == ByteOrderUnspecified) return; uint16 BEMask = ByteOrderToUse == ByteOrderBE ? 0xffff : 0x0000; uint16 LEMask = ByteOrderToUse == ByteOrderLE ? 0xffff : 0x0000; if(BOM(In) != ByteOrderUnspecified) In++; const uint8* Bytes = UTF16ToBytePointer(In); const uint8* BytesEnd = UTF16ToBytePointer(InEnd); while(Bytes and Bytes < BytesEnd) { uint16 a1 = *Bytes++; uint16 b1 = *Bytes++; uint16 w1 = (((a1 << 8) + b1) & BEMask) + (((b1 << 8) + a1) & LEMask); unicode u = meta::BadCharacter; if(w1 < 0xd800 or w1 > 0xdfff) u = unicode(w1); else if(Bytes < BytesEnd) { uint16 a2 = *Bytes++; uint16 b2 = *Bytes++; uint16 w2 = (((a2 << 8) + b2) & BEMask) + (((b2 << 8) + a2) & LEMask); if(w2 >= 0xdc00 and w2 <= 0xdfff) u = (unicode(w1 & 0x3ff) << 10) + unicode(w2 & 0x3ff) + unicode(0x10000); } Out.Append(u); } } ///Detects the presence of a BOM at the beginning of the string. static ByteOrder BOM(const uint16* In) { ByteOrder DetectedBOM = ByteOrderUnspecified; if(In and *In) { byte a = UTF16ToBytePointer(In)[0], b = UTF16ToBytePointer(In)[1]; if(a == 0xff and b == 0xfe) DetectedBOM = ByteOrderLE; else if(a == 0xfe and b == 0xff) DetectedBOM = ByteOrderBE; } return DetectedBOM; } /**Uses common characters (space 0x20, line feed 0x0A) to find byte order. If there are more 0x2000 and 0x0A00 values than 0x0020 and 0x00A0 values, then the byte order is guessed to be little-endian. Likewise, if there are more 0x0020 and 0x00A0 values than 0x2000 and 0x0A00 values then the byte order is guessed to be big-endian. If neither is found, the byte order is unspecified. Note that this method assumes that the input is a UTF-16 string.*/ static ByteOrder GuessByteOrder(const uint16* In, count MaximumSearchLength) { count LEPoints = 0, BEPoints = 0; count BytesExamined = 0; while(In and *In and BytesExamined++ < MaximumSearchLength) { uint8 a = UTF16ToBytePointer(In)[0]; uint8 b = UTF16ToBytePointer(In++)[1]; if(not a and (b == 0x0a or b == 0x20)) BEPoints++; if(not b and (a == 0x0a or a == 0x20)) LEPoints++; } ByteOrder GuessedByteOrder = ByteOrderUnspecified; if(LEPoints > BEPoints) GuessedByteOrder = ByteOrderLE; else if(BEPoints > LEPoints) GuessedByteOrder = ByteOrderBE; return GuessedByteOrder; } static const uint16* StringToUTF16Pointer(const String& In) { return reinterpret_cast<const uint16*>(In.Merge()); } static const byte* UTF16ToBytePointer(const uint16* In) { return reinterpret_cast<const byte*>(In); } }; /**Attempts to convert the string to UTF-8. It first attempts to detect the encoding as UTF-8 or Latin-1. If the string is in Latin-1, then it will convert the string to UTF-8. If the encoding can not be detected then the method will return false and leave the string untouched.*/ bool ConvertToUTF8() { bool Success = true; if(IsUTF8()); else if(UTF16::IsUTF16(*this)) *this = UTF16::Decode(*this); else if(IsLatin1()) { String s; for(count i = 0; i < n(); i++) s.Append(unicode(Get(i))); *this = s; } else Success = false; return Success; } /**Removes all non-ASCII characters including rare control characters. Returns whether the string was changed.*/ bool ForceToASCII() { bool WasChanged = false; for(count i = n() - 1; i >= 0; i--) { byte b = Get(i); if(b != 9 and b != 10 and b != 13 and not (b >= 32 and b <= 126)) { Erase(i, i); WasChanged = true; } } Merge(); return WasChanged; } /**Forces to UTF-8 and removes rare control characters. Returns whether the string was changed.*/ bool ForceToUTF8() { const byte* a = reinterpret_cast<const byte*>(Merge()); const byte* z = a + n(); String NewString; unicode d; do { if((d = Decode(a, z))) { if(d != 9 and d != 10 and d != 13 and not (d >= 32 and d <= 126) and d < 128) d = meta::BadCharacter; NewString << d; } } while(d); bool WasChanged = *this != NewString; *this = NewString; return WasChanged; } ///Calculates the number of UTF-8 characters in the string. count Characters() const { const byte* Start = reinterpret_cast<const byte*>(Merge()); const byte* ReadPosition = Start; const byte* EndMarker = &Start[n()]; count CharacterCount = 0; while(ReadPosition != EndMarker) { Decode(ReadPosition, EndMarker); CharacterCount++; } return CharacterCount; } ///Calculates the number of UTF-8 characters in the string. count c() const {return Characters();} /**Translates a character index to a byte index in UTF-8. If the character is negative or if the character is beyond the null-terminator, then -1 is returned. The null-terminator is considered a valid character from the perspective of indexing.*/ count CharacterIndex(count c) const { if(not c) return 0; if(c < 0) return -1; const byte* Start = reinterpret_cast<const byte*>(Merge()); const byte* ReadPosition = Start; const byte* EndMarker = &Start[n()]; count CharacterCount = 0; while(ReadPosition != EndMarker) { Decode(ReadPosition, EndMarker); if(++CharacterCount == c) return count(ReadPosition - Start); } return -1; } ///Shorthand for CharacterIndex(). count ci(count Character) const {return CharacterIndex(Character);} ///Returns the unicode value of the c-th character. unicode cth(count c) const { count i = CharacterIndex(c); if(i < 0) return 0; const byte* Start = reinterpret_cast<const byte*>(Merge()); const byte* ReadPosition = &Start[i]; const byte* EndMarker = &Start[n()]; return Decode(ReadPosition, EndMarker); } ///Decodes an entire byte array to a String::UTF32. static void DecodeStream(const byte* Start, count Length, String::UTF32& Output) { const byte* ReadPosition = Start; const byte* EndMarker = &Start[Length]; Output.n(0); while(ReadPosition != EndMarker) Output.Add(Decode(ReadPosition, EndMarker)); } ///Decodes the current string to a String::UTF32. void DecodeTo(String::UTF32& Output) const { DecodeStream(reinterpret_cast<const byte*>(Merge()), n(), Output); } /**Appends a Unicode codepoint to the string as UTF-8. If the character is not representable as a valid Unicode codepoint, then it is substituted with the bad character symbol defined at meta::BadCharacter.*/ inline void Append(unicode Codepoint) { //Create an alias of the incoming variable. unicode d = Codepoint; //Do not encode an illegal character. if(d > 0x10FFFF or d == 0xD800 or d == 0xDB7F or d == 0xDB80 or d == 0xDBFF or d == 0xDC00 or d == 0xDF80 or d == 0xDFFF or d == 0xFFFE or d == 0xFFFF) d = meta::BadCharacter; //Encode the codepoint in between 1 and 4 octets. byte e[4] = {0, 0, 0, 0}; if(d < 0x80) //1 octet { e[0] = byte(d); Append(&e[0], 1); } else if(d < 0x800) //2 octets { e[0] = byte(((d >> 6) & 0x1F) + 0xC0); //110xxxxx e[1] = byte((d & 0x3F) + 0x80); //10xxxxxx Append(&e[0], 2); } else if(d < 0x10000) //3 octets { e[0] = byte(((d >> 12) & 0x0F) + 0xE0); //1110xxxx e[1] = byte(((d >> 6) & 0x3F) + 0x80); //10xxxxxx e[2] = byte((d & 0x3F) + 0x80); //10xxxxxx Append(&e[0], 3); } else //4 octets { e[0] = byte(((d >> 18) & 0x07) + 0xF0); //11110xxx e[1] = byte(((d >> 12) & 0x3F) + 0x80); //10xxxxxx e[2] = byte(((d >> 6) & 0x3F) + 0x80); //10xxxxxx e[3] = byte((d & 0x3F) + 0x80); //10xxxxxx Append(&e[0], 4); } } ///Appends an array of codepoints to the string as UTF-8. void Append(const String::UTF32& Codepoints) { for(count i = 0; i < Codepoints.n(); i++) Append(Codepoints[i]); } ///Returns true if the left is (binary-string wise) greater than the right. bool operator < (const String& Other) const; ///Returns true if the left is (binary-string wise) greater than the right. bool operator > (const String& Other) const; ///Less than or equal operator. bool operator <= (const String& Other) const { return *this < Other or *this == Other; } ///Greater than or equal operator. bool operator >= (const String& Other) const { return *this > Other or *this == Other; } }; #ifdef PRIM_COMPILE_INLINE const ascii* String::LF = "\x0A"; //Practically equivalent to '\n' const ascii* String::CRLF = "\x0D\x0A"; //Practically equivalent to '\r\n' #ifdef PRIM_ENVIRONMENT_WINDOWS const ascii* String::Newline = "\x0A"; //Windows is mostly happy with LF. #else const ascii* String::Newline = "\x0A"; #endif void String::AppendToStream(const byte* Fragment, count Length) { if(AttachedStream == StandardOutput) { fwrite(reinterpret_cast<const void*>(Fragment), 1, size_t(Length), stdout); fflush(stdout); } else if(AttachedStream == StandardError) { fwrite(reinterpret_cast<const void*>(Fragment), 1, size_t(Length), stderr); fflush(stderr); } } void String::Attach(StreamAttachment StreamToAttachTo) { AttachedStream = StreamToAttachTo; if(AttachedStream == StandardInput) { std::string s; std::cin >> s; Append(reinterpret_cast<const byte*>(s.c_str()), count(s.size())); } } bool String::operator < (const String& Other) const { return strcmp(Merge(), Other.Merge()) < 0; } bool String::operator > (const String& Other) const { return strcmp(Merge(), Other.Merge()) > 0; } String& String::operator << (bool v) { (*this) << (v ? "True" : "False"); return *this; } String& String::operator << (uint8 v) { std::stringstream ss; ss << int32(v); char BufferData[32]; ss.read(&BufferData[0], 32); Append(reinterpret_cast<byte*>(&BufferData[0]), count(ss.gcount())); return *this; } String& String::operator << (uint16 v) { std::stringstream ss; ss << v; char BufferData[32]; ss.read(&BufferData[0], 32); Append(reinterpret_cast<byte*>(&BufferData[0]), count(ss.gcount())); return *this; } String& String::operator << (int16 v) { std::stringstream ss; ss << v; char BufferData[32]; ss.read(&BufferData[0], 32); Append(reinterpret_cast<byte*>(&BufferData[0]), count(ss.gcount())); return *this; } String& String::operator << (unicode v) { Append(v); return *this; } String& String::operator << (int32 v) { std::stringstream ss; ss << v; char BufferData[32]; ss.read(&BufferData[0], 32); Append(reinterpret_cast<byte*>(&BufferData[0]), count(ss.gcount())); return *this; } String& String::operator << (uint64 v) { std::stringstream ss; ss << v; char BufferData[32]; ss.read(&BufferData[0], 32); Append(reinterpret_cast<byte*>(&BufferData[0]), count(ss.gcount())); return *this; } String& String::operator << (int64 v) { std::stringstream ss; ss << v; char BufferData[32]; ss.read(&BufferData[0], 32); Append(reinterpret_cast<byte*>(&BufferData[0]), count(ss.gcount())); return *this; } void String::Append(float64 v, count Precision = 17, bool ScientificNotation = true) { if(Limits<float64>::IsEqual(v, Limits<float64>::Infinity())) { *this << Constants::Infinity(); return; } else if(Limits<float64>::IsEqual(v, Limits<float64>::NegativeInfinity())) { *this << "-" << Constants::Infinity(); return; } else if(Limits<float64>::IsNaN(v)) { *this << Constants::NullSet(); return; } if(Precision < 1) Precision = 1; else if(Precision > 17) Precision = 17; if(ScientificNotation) { std::stringstream ss; ss.precision(int(Precision)); ss << v; char BufferData[32]; Memory::MemSet(BufferData, 0, 32); ss.read(&BufferData[0], 32); Append(reinterpret_cast<byte*>(&BufferData[0]), LengthOf(BufferData)); } else { v = Chop(v, 1.0e-16); if(Abs(v) >= 1.0e+16) v = 1.0e+16 * Sign(v); std::stringstream ss; ss.precision(int(Precision)); ss.setf(std::ios::fixed, std::ios::floatfield); ss << v; char BufferData[32]; Memory::MemSet(BufferData, 0, 32); ss.read(&BufferData[0], 32); //Remove trailing zeroes. for(count i = LengthOf(BufferData) - 1; i > 1; i--) { if(BufferData[i] == '0' and BufferData[i - 1] != '.') BufferData[i] = 0; else break; } Append(reinterpret_cast<byte*>(&BufferData[0]), LengthOf(BufferData)); } } String& String::operator << (float64 v) { Append(v, NumberPrecision, false); return *this; } String& String::operator << (float32 v) { return (*this) << (float64(v)); } String& String::operator << (float80 v) { return (*this) << (float64(v)); } String& String::operator << (const void* v) { std::stringstream ss; ss << v; char BufferData[32]; ss.read(&BufferData[0], 32); Append(reinterpret_cast<byte*>(&BufferData[0]), count(ss.gcount())); return *this; } count String::LengthOf(const ascii* s) { if(not s) return 0; return count(strchr(s, 0) - s); } number String::ToNumber() const { return number(atof(Merge())); } const unicode String::CodepointBias[256] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x0, 0x40, 0x80, 0xC0, 0x100, 0x140, 0x180, 0x1C0, 0x200, 0x240, 0x280, 0x2C0, 0x300, 0x340, 0x380, 0x3C0, 0x400, 0x440, 0x480, 0x4C0, 0x500, 0x540, 0x580, 0x5C0, 0x600, 0x640, 0x680, 0x6C0, 0x700, 0x740, 0x780, 0x7C0, 0x0, 0x1000, 0x2000, 0x3000, 0x4000, 0x5000, 0x6000, 0x7000, 0x8000, 0x9000, 0xA000, 0xB000, 0xC000, 0xD000, 0xE000, 0xF000, 0x0, 0x40000, 0x80000, 0xC0000, 0x100000, 0x140000, 0x180000, 0x1C0000, 0x0, 0x1000000, 0x2000000, 0x3000000, 0x0, 0x4000000, 0, 0}; const count String::OctetClassification[256] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, -1, -1}; const count String::OverlongThresholds[7] = {0, 0, 0x80, 0x800, 0x10000, 0x200000, 0x4000000}; /*Lookup table to map ASCII byte codes to hexadecimal digits. Anything that is a hexadecimal digit is mapped to its corresponding value, and anything else is mapped to 16, indicating it is not a valid hexadecimal digit.*/ const byte String::HexMap[256] = {16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 16, 16, 16, 16, 16, 16, 10, 11, 12, 13, 14, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 10, 11, 12, 13, 14, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16}; #endif } #endif
31.165577
80
0.568724
[ "object", "vector" ]
66bcd4864c729f684fb3bcd84a110e76275f2266
3,677
h
C
exegesis/x86/cleanup_instruction_set_operand_info.h
the-eager-ghosts/EXEgesis
ca6ab91c0e1f617881a34c8e794ea37466229590
[ "Apache-2.0" ]
201
2017-05-12T05:04:55.000Z
2022-03-14T15:49:37.000Z
exegesis/x86/cleanup_instruction_set_operand_info.h
the-eager-ghosts/EXEgesis
ca6ab91c0e1f617881a34c8e794ea37466229590
[ "Apache-2.0" ]
7
2017-05-22T11:52:06.000Z
2022-02-26T16:30:46.000Z
exegesis/x86/cleanup_instruction_set_operand_info.h
the-eager-ghosts/EXEgesis
ca6ab91c0e1f617881a34c8e794ea37466229590
[ "Apache-2.0" ]
35
2017-05-16T04:00:06.000Z
2022-02-27T03:37:16.000Z
// Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Contains the library of InstructionSetProto transformations that add // structured information about the operands of the instructions. #ifndef EXEGESIS_X86_CLEANUP_INSTRUCTION_SET_OPERAND_INFO_H_ #define EXEGESIS_X86_CLEANUP_INSTRUCTION_SET_OPERAND_INFO_H_ #include "absl/status/status.h" #include "exegesis/proto/instructions.pb.h" namespace exegesis { namespace x86 { // Adds more implicit info about VMX instructions. absl::Status AddVmxOperandInfo(InstructionSetProto* instruction_set); // VMFUNC uses EAX as input register but this info is not parseable by current // heuristics. This transform manually defines it. absl::Status FixVmFuncOperandInfo(InstructionSetProto* instruction_set); // Directly sets properties of the first operand of the MOVDIR64B instruction. // The first (modrm.reg-encoded) operand is a general purpose register, but it // is interpreted as an address. absl::Status AddMovdir64BOperandInfo(InstructionSetProto* instruction_set); // Directly sets properties of the first operand of the UMONITOR instruction. // The instruction accepts a single register absl::Status AddUmonitorOperandInfo(InstructionSetProto* instruction_set); // Adds detailed information about operands to the vendor syntax section. // Assumes that this section already has operand names in the format used by the // Intel manual, and so is the encoding scheme of the instruction proto. This // function replaces any existing operand information in the vendor syntax so // that the i-th operand structure corresponds to the i-th operand of the // instruction in the vendor syntax specification. // Note that this instruction depends on the output of RenameOperands. absl::Status AddOperandInfo(InstructionSetProto* instruction_set); // Applies heuristics to determine the usage patterns of operands with unknown // usage patterns. For example, VEX.vvvv are implicitly read from except when // specified. This transforms explictly sets usage to USAGE_READ. Also, implicit // registers (e.g. in ADD AL, imm8) are usually missing usage in the SDM. absl::Status AddMissingOperandUsage(InstructionSetProto* instruction_set); // Adds USAGE_READ to the last operadn of VBLEND instructions. As of May 2018, // the operand usage is missing for the last operand across multiple versions of // the instruction. absl::Status AddMissingOperandUsageToVblendInstructions( InstructionSetProto* instruction_set); // Adds RegisterClass to every operand in vendor_syntax. absl::Status AddRegisterClassToOperands(InstructionSetProto* instruction_set); // Adds VEX operand usage informamtion to instructions where it is missing. This // information used to be a part of the instruction encoding specification in // the SDM, but it was removed starting with the November 2018 version of the // manual. This transform reconstructs the info from the other available // information about the instruction. absl::Status AddMissingVexVOperandUsage(InstructionSetProto* instruction_set); } // namespace x86 } // namespace exegesis #endif // EXEGESIS_X86_CLEANUP_INSTRUCTION_SET_OPERAND_INFO_H_
47.141026
80
0.802013
[ "transform" ]
66c6258ed33a192d0cf2622ce59110fefc377463
4,505
h
C
pepnovo/src/DatFile.h
compomics/jwrapper-pepnovo
1bd21a4910d7515dfab7747711917176a6b5ce99
[ "Apache-2.0" ]
null
null
null
pepnovo/src/DatFile.h
compomics/jwrapper-pepnovo
1bd21a4910d7515dfab7747711917176a6b5ce99
[ "Apache-2.0" ]
null
null
null
pepnovo/src/DatFile.h
compomics/jwrapper-pepnovo
1bd21a4910d7515dfab7747711917176a6b5ce99
[ "Apache-2.0" ]
null
null
null
#ifndef __DATFILE_H__ #define __DATFILE_H__ #include "PeakList.h" class SingleSpectrumHeader; // fwd dclr struct Peak; const size_t DAT_HEADER_SIZE = sizeof(clusterIdx_t) + sizeof(longInt8_t) + 2*sizeof(mass_t); const size_t DAT_BUFFER_SIZE = 1179648; // offset to the position of the sqs field in the header of a DAT spectrum // this location can be computed by looking in SingleSpectrumHeader::scanDatSpectrumHeaderFromBuffer() const size_t DAT_OFFSET_OF_SQS = 2*sizeof(unsigned int) + 4*sizeof(mass_t) + 3*sizeof(short) + 4*sizeof(int) + 2*sizeof(float); struct DatSpectrumStats { public: // two spectra can have the same m/z (since there is only limited precision) // this can mess things up when they are written (violate some of the asserts) // so to avoid this problem we can use a more sophisticated sort that will not // assign a random to spectra with the same m/z bool operator< (const DatSpectrumStats& rhs) const { return (mOverZ < rhs.mOverZ || mOverZ == rhs.mOverZ && fileIdx <rhs.fileIdx || mOverZ == rhs.mOverZ && fileIdx==rhs.fileIdx && filePosition <rhs.filePosition); } unsigned int fileIdx; long filePosition; mass_t mOverZ; unsigned int numPeaks; size_t clusterWritePos; // filled in after sorting the stats size_t peakWritePos; // filled in after sorting the stats }; class DatFile { public: DatFile() : indOpen_(0), fileIdx_(MAX_UINT), archiveFileIndex_(MIN_INT), path_(""), numSpectra_(0), numPeaks_(0), minMOverZ_(MAX_FLOAT), maxMOverZ_(0.0), bufferEndStreamPosition_(0), bufferSize_(0), bufferPosition_(0), bufferEnd_(0), numSpectraRead_(0), stream_(0), buffer_(0) {} ~DatFile(); bool operator< (const DatFile& rhs) const { return (minMOverZ_ < rhs.minMOverZ_); } // reads all the header information from a dat file and adds ito to the vector bool readAndAddDatSpectrumStats(vector<DatSpectrumStats>& headerStats, unsigned int fileIdx); bool readSpectrum(const DatSpectrumStats& stats, SingleSpectrumHeader* header, Peak* peaks); void readDatSpectraToStorage( const Config* config, const vector<DatSpectrumStats>& datStats, const int datFileIdx, SingleSpectrumHeader* headersStorage, // Peak* peaksStroge, size_t& numSpectraReadFromDat, size_t& numPeaksReadFromDat, size_t startIdx, size_t endIdx ); // reads spectrum to buffer directly without processing, reports the number of bytes // If this is the last spectrum in the file or there is problem returns false, otherwise true. bool getNextDatSpectrum(char*& spec, size_t& numBytes, float* sqs=NULL, long* peakPosition=NULL, char** peaksBufferPosition=NULL); size_t writePeakList(const PeakList& pl, const SingleSpectrumHeader* newHeader=0); size_t writeSpectrumFromBuffer(const char* buffer, size_t numBytes); // opens reads the statistics on number of spectra, peaks, and m/z's and closes // doesn't allocate buffer void peekAtStats(const char* path); bool openForReading(const char* path = 0); bool closeAfterReading(); bool openForWriting(const char* path, int verboseLevel = 0); bool closeAfterWriting(); bool getIndOpen() const { return indOpen_; } void addSpectrumToStats(mass_t mz, unsigned int numPeaks); const string& getPath() const { return path_; } void setPath(const string& p) { path_ = p; } size_t getFileIdx() const { return fileIdx_; } void setFileIdx(size_t i) { fileIdx_ = i; } int getAarchiveFileIndex() const { return archiveFileIndex_; } void setArchiveFileIndex(int i) { archiveFileIndex_ = i; } longInt8_t getNumPeaks() const { return numPeaks_; } clusterIdx_t getNumSpectra() const { return numSpectra_; } mass_t getMinMOverZ() const { return minMOverZ_; } mass_t getMaxMOverZ() const { return maxMOverZ_; } private: bool indOpen_; string path_; size_t fileIdx_; int archiveFileIndex_; clusterIdx_t numSpectra_; longInt8_t numPeaks_; mass_t minMOverZ_; mass_t maxMOverZ_; // buffer for reading/writing spectra long bufferEndStreamPosition_; // holds current location of the input file stream size_t bufferSize_; size_t bufferPosition_; size_t bufferEnd_; size_t numSpectraRead_; FILE* stream_; char* buffer_; void flushBuffer(); void init(bool indClearPath = true); }; #endif
31.284722
103
0.707436
[ "vector" ]
66ca4f0bae0411ad74606dcbfa3fc125d78d0ea3
5,387
h
C
Embarcadero/OpenGL/MD2 ray picking/Classes/QR_3D/QR_Effects/QR_MSAA_OpenGL_Effect.h
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
1
2022-03-22T14:41:15.000Z
2022-03-22T14:41:15.000Z
Embarcadero/OpenGL/MD2 ray picking/Classes/QR_3D/QR_Effects/QR_MSAA_OpenGL_Effect.h
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
null
null
null
Embarcadero/OpenGL/MD2 ray picking/Classes/QR_3D/QR_Effects/QR_MSAA_OpenGL_Effect.h
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
null
null
null
/**************************************************************************** * ==> QR_MSAA_OpenGL_Effect -----------------------------------------------* **************************************************************************** * Description : Post-processing multi sampled anti aliasing effect for * * OpenGL renderer * * Developer : Jean-Milost Reymond * **************************************************************************** * MIT License - QR Engine * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to * * the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************/ #ifndef QR_MSAA_OPENGL_EFFECTH #define QR_MSAA_OPENGL_EFFECTH // qr engine #include "QR_Types.h" #include "QR_PostProcessingEffect.h" #include "QR_Shader_OpenGL.h" #include "QR_Renderer_OpenGL.h" // openGL #if defined (OS_WIN) #define GLEW_STATIC #include <GL/glew.h> #include <gl/gl.h> #elif defined (OS_OSX) #ifdef USE_OPENGL_DIRECT_MODE #include <ES1/gl.h> #else #include <ES2/gl.h> #include <ES2/glext.h> #endif #endif /** * Post-processing multi sampled anti aliasing effect for OpenGL renderer *@note This class is cross-platform *@author Jean-Milost Reymond */ class QR_MSAA_OpenGL_Effect : public QR_PostProcessingEffect { public: /** * Constructor *@param pRenderer - renderer to use to draw the scene *@param width - screen width, in pixels *@param height - screen height, in pixels *@param vertexShaderFileName - vertex shader file name to use *@param fragmentShaderFileName - fragment shader file name to use */ QR_MSAA_OpenGL_Effect(QR_Renderer_OpenGL* pRenderer, QR_UInt32 width, QR_UInt32 height, const std::string& vertexShaderFileName = "", const std::string& fragmentShaderFileName = ""); /** * Destructor */ virtual ~QR_MSAA_OpenGL_Effect(); /** * Configures effect */ virtual void Configure(); /** * Begins effect */ virtual void Begin(); /** * Ends effect */ virtual void End(); /** * Sets the effect size *@param width - new width to set *@param height - new height to set */ virtual void SetSize(QR_UInt32 width, QR_UInt32 height); private: QR_Renderer_OpenGL* m_pRenderer; QR_UInt32 m_Width; QR_UInt32 m_Height; GLuint m_FrameBuffer; GLuint m_RenderBufferObject; GLuint m_IntermediateFBO; GLuint m_Texture; QR_Shader_OpenGL m_Shader; M_Precision m_Vertices[16]; /** * Constructor *@note Cannot construct object of this type without a size */ QR_MSAA_OpenGL_Effect(); /** * Generates a new frame buffer for the effect */ void GenerateFrameBuffer(); /** * Deletes the current frame buffer */ void DeleteFrameBuffer(); /** * Generates a texture compatible with multi sampling operations *@param samples - samples *@return texture identifier */ GLuint GenerateMultiSampleTexture(GLuint samples); /** * Generates a texture for attachment to final render surface *@param depth - color depth *@param stencil - if true, stencil buffer will be used *@return texture identifier */ GLuint GenerateAttachmentTexture(GLboolean depth, GLboolean stencil); }; #endif
36.89726
79
0.517728
[ "render", "object" ]
66d8f6c9d52fa7cecc054fe23d6dd16de50f0287
15,396
h
C
c++/src/capnproto/message.h
sbinet/capnproto
9ebc30203b50178eaf6ee094454d53576fc0ff17
[ "BSD-2-Clause" ]
null
null
null
c++/src/capnproto/message.h
sbinet/capnproto
9ebc30203b50178eaf6ee094454d53576fc0ff17
[ "BSD-2-Clause" ]
null
null
null
c++/src/capnproto/message.h
sbinet/capnproto
9ebc30203b50178eaf6ee094454d53576fc0ff17
[ "BSD-2-Clause" ]
1
2018-03-23T17:54:48.000Z
2018-03-23T17:54:48.000Z
// Copyright (c) 2013, Kenton Varda <temporal@gmail.com> // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY 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 <cstddef> #include <memory> #include "macros.h" #include "type-safety.h" #include "layout.h" #ifndef CAPNPROTO_MESSAGE_H_ #define CAPNPROTO_MESSAGE_H_ namespace capnproto { namespace internal { class ReaderArena; class BuilderArena; } class Segment; typedef Id<uint32_t, Segment> SegmentId; // ======================================================================================= class ErrorReporter { // Abstract interface for a class which receives notification of errors found in an input message. public: virtual ~ErrorReporter(); virtual void reportError(const char* description) = 0; // Reports an error discovered while validating a message. This happens lazily, as the message // is traversed. E.g., it can happen when a get() accessor is called for a sub-struct or list, // and that object is found to be out-of-bounds or has the wrong type. // // This method can throw an exception. If it does not, then the getter that was called will // return the default value. Returning a default value is sufficient to prevent invalid messages // from being a security threat, since an attacker could always construct a valid message // containing the default value to get the same effect. However, returning a default value is // not ideal when handling messages that were accidentally corrupted -- it may lead to the wrong // behavior, e.g. storing the wrong data to disk, which could cause further problems down the // road. Therefore, throwing an exception is preferred -- if your code is exception-safe, of // course. }; ErrorReporter* getThrowingErrorReporter(); // Returns a singleton ErrorReporter which throws an exception (deriving from std::exception) on // error. ErrorReporter* getStderrErrorReporter(); // Returns a singleton ErrorReporter which prints a message to stderr on error, then replaces the // invalid data with the default value. ErrorReporter* getIgnoringErrorReporter(); // Returns a singleton ErrorReporter which silently replaces invalid data with its default value. struct ReaderOptions { // Options controlling how data is read. uint64_t traversalLimitInWords = 8 * 1024 * 1024; // Limits how many total words of data are allowed to be traversed. Traversal is counted when // a new struct or list builder is obtained, e.g. from a get() accessor. This means that calling // the getter for the same sub-struct multiple times will cause it to be double-counted. Once // the traversal limit is reached, an error will be reported. // // This limit exists for security reasons. It is possible for an attacker to construct a message // in which multiple pointers point at the same location. This is technically invalid, but hard // to detect. Using such a message, an attacker could cause a message which is small on the wire // to appear much larger when actually traversed, possibly exhausting server resources leading to // denial-of-service. // // It makes sense to set a traversal limit that is much larger than the underlying message. // Together with sensible coding practices (e.g. trying to avoid calling sub-object getters // multiple times, which is expensive anyway), this should provide adequate protection without // inconvenience. // // The default limit is 64 MiB. This may or may not be a sensible number for any given use case, // but probably at least prevents easy exploitation while also avoiding causing problems in most // typical cases. uint nestingLimit = 64; // Limits how deeply-nested a message structure can be, e.g. structs containing other structs or // lists of structs. // // Like the traversal limit, this limit exists for security reasons. Since it is common to use // recursive code to traverse recursive data structures, an attacker could easily cause a stack // overflow by sending a very-deeply-nested (or even cyclic) message, without the message even // being very large. The default limit of 64 is probably low enough to prevent any chance of // stack overflow, yet high enough that it is never a problem in practice. ErrorReporter* errorReporter = getThrowingErrorReporter(); // How to report errors. }; class MessageReader { public: MessageReader(ReaderOptions options); // It is suggested that subclasses take ReaderOptions as a constructor parameter, but give it a // default value of "ReaderOptions()". The base class constructor doesn't have a default value // in order to remind subclasses that they really need to give the user a way to provide this. virtual ~MessageReader(); virtual ArrayPtr<const word> getSegment(uint id) = 0; // Gets the segment with the given ID, or returns null if no such segment exists. // // Normally getSegment() will only be called once for each segment ID. Subclasses can call // reset() to clear the segment table and start over with new segments. inline const ReaderOptions& getOptions(); // Get the options passed to the constructor. template <typename RootType> typename RootType::Reader getRoot(); private: ReaderOptions options; // Space in which we can construct a ReaderArena. We don't use ReaderArena directly here // because we don't want clients to have to #include arena.h, which itself includes a bunch of // big STL headers. We don't use a pointer to a ReaderArena because that would require an // extra malloc on every message which could be expensive when processing small messages. void* arenaSpace[15]; bool allocatedArena; internal::ReaderArena* arena() { return reinterpret_cast<internal::ReaderArena*>(arenaSpace); } internal::StructReader getRoot(const word* defaultValue); }; class MessageBuilder { public: MessageBuilder(); virtual ~MessageBuilder(); virtual ArrayPtr<word> allocateSegment(uint minimumSize) = 0; // Allocates an array of at least the given number of words, throwing an exception or crashing if // this is not possible. It is expected that this method will usually return more space than // requested, and the caller should use that extra space as much as possible before allocating // more. The returned space remains valid at least until the MessageBuilder is destroyed. template <typename RootType> typename RootType::Builder initRoot(); template <typename RootType> typename RootType::Builder getRoot(); ArrayPtr<const ArrayPtr<const word>> getSegmentsForOutput(); private: // Space in which we can construct a BuilderArena. We don't use BuilderArena directly here // because we don't want clients to have to #include arena.h, which itself includes a bunch of // big STL headers. We don't use a pointer to a BuilderArena because that would require an // extra malloc on every message which could be expensive when processing small messages. void* arenaSpace[15]; bool allocatedArena = false; internal::BuilderArena* arena() { return reinterpret_cast<internal::BuilderArena*>(arenaSpace); } internal::SegmentBuilder* getRootSegment(); internal::StructBuilder initRoot(const word* defaultValue); internal::StructBuilder getRoot(const word* defaultValue); }; template <typename RootType> static typename RootType::Reader readMessageTrusted(const word* data); // IF THE INPUT IS INVALID, THIS MAY CRASH, CORRUPT MEMORY, CREATE A SECURITY HOLE IN YOUR APP, // MURDER YOUR FIRST-BORN CHILD, AND/OR BRING ABOUT ETERNAL DAMNATION ON ALL OF HUMANITY. DO NOT // USE UNLESS YOU UNDERSTAND THE CONSEQUENCES. // // Given a pointer to a known-valid message located in a single contiguous memory segment, // returns a reader for that message. No bounds-checking will be done while tranversing this // message. Use this only if you are absolutely sure that the input data is a valid message // created by your own system. Never use this to read messages received from others. // // To create a trusted message, build a message using a MallocAllocator whose preferred segment // size is larger than the message size. This guarantees that the message will be allocated as a // single segment, meaning getSegmentsForOutput() returns a single word array. That word array // is your message; you may pass a pointer to its first word into readTrusted() to read the // message. // // This can be particularly handy for embedding messages in generated code: you can // embed the raw bytes (using AlignedData) then make a Reader for it using this. This is the way // default values are embedded in code generated by the Cap'n Proto compiler. E.g., if you have // a message MyMessage, you can read its default value like so: // MyMessage::Reader reader = Message<MyMessage>::ReadTrusted(MyMessage::DEFAULT.words); // ======================================================================================= class SegmentArrayMessageReader: public MessageReader { // A simple MessageReader that reads from an array of word arrays representing all segments. // In particular you can read directly from the output of MessageBuilder::getSegmentsForOutput() // (although it would probably make more sense to call builder.getRoot().asReader() in that case). public: SegmentArrayMessageReader(ArrayPtr<const ArrayPtr<const word>> segments, ReaderOptions options = ReaderOptions()); // Creates a message pointing at the given segment array, without taking ownership of the // segments. All arrays passed in must remain valid until the MessageReader is destroyed. CAPNPROTO_DISALLOW_COPY(SegmentArrayMessageReader); ~SegmentArrayMessageReader(); virtual ArrayPtr<const word> getSegment(uint id) override; private: ArrayPtr<const ArrayPtr<const word>> segments; }; enum class AllocationStrategy: uint8_t { FIXED_SIZE, // The builder will prefer to allocate the same amount of space for each segment with no // heuristic growth. It will still allocate larger segments when the preferred size is too small // for some single object. This mode is generally not recommended, but can be particularly useful // for testing in order to force a message to allocate a predictable number of segments. Note // that you can force every single object in the message to be located in a separate segment by // using this mode with firstSegmentWords = 0. GROW_HEURISTICALLY // The builder will heuristically decide how much space to allocate for each segment. Each // allocated segment will be progressively larger than the previous segments on the assumption // that message sizes are exponentially distributed. The total number of segments that will be // allocated for a message of size n is O(log n). }; constexpr uint SUGGESTED_FIRST_SEGMENT_WORDS = 1024; constexpr AllocationStrategy SUGGESTED_ALLOCATION_STRATEGY = AllocationStrategy::GROW_HEURISTICALLY; class MallocMessageBuilder: public MessageBuilder { // A simple MessageBuilder that uses malloc() (actually, calloc()) to allocate segments. This // implementation should be reasonable for any case that doesn't require writing the message to // a specific location in memory. public: explicit MallocMessageBuilder(uint firstSegmentWords = 1024, AllocationStrategy allocationStrategy = SUGGESTED_ALLOCATION_STRATEGY); // Creates a BuilderContext which allocates at least the given number of words for the first // segment, and then uses the given strategy to decide how much to allocate for subsequent // segments. When choosing a value for firstSegmentWords, consider that: // 1) Reading and writing messages gets slower when multiple segments are involved, so it's good // if most messages fit in a single segment. // 2) Unused bytes will not be written to the wire, so generally it is not a big deal to allocate // more space than you need. It only becomes problematic if you are allocating many messages // in parallel and thus use lots of memory, or if you allocate so much extra space that just // zeroing it out becomes a bottleneck. // The defaults have been chosen to be reasonable for most people, so don't change them unless you // have reason to believe you need to. explicit MallocMessageBuilder(ArrayPtr<word> firstSegment, AllocationStrategy allocationStrategy = SUGGESTED_ALLOCATION_STRATEGY); // This version always returns the given array for the first segment, and then proceeds with the // allocation strategy. This is useful for optimization when building lots of small messages in // a tight loop: you can reuse the space for the first segment. // // firstSegment MUST be zero-initialized. MallocMessageBuilder's destructor will write new zeros // over any space that was used so that it can be reused. CAPNPROTO_DISALLOW_COPY(MallocMessageBuilder); virtual ~MallocMessageBuilder(); virtual ArrayPtr<word> allocateSegment(uint minimumSize) override; private: uint nextSize; AllocationStrategy allocationStrategy; bool ownFirstSegment; void* firstSegment; struct MoreSegments; std::unique_ptr<MoreSegments> moreSegments; }; // ======================================================================================= // implementation details inline const ReaderOptions& MessageReader::getOptions() { return options; } template <typename RootType> inline typename RootType::Reader MessageReader::getRoot() { return typename RootType::Reader(getRoot(RootType::DEFAULT.words)); } template <typename RootType> inline typename RootType::Builder MessageBuilder::initRoot() { return typename RootType::Builder(initRoot(RootType::DEFAULT.words)); } template <typename RootType> inline typename RootType::Builder MessageBuilder::getRoot() { return typename RootType::Builder(getRoot(RootType::DEFAULT.words)); } template <typename RootType> typename RootType::Reader readMessageTrusted(const word* data) { return typename RootType::Reader(internal::StructReader::readRootTrusted( data, RootType::DEFAULT.words)); } } // namespace capnproto #endif // CAPNPROTO_MESSAGE_H_
47.813665
100
0.75039
[ "object" ]
66dbc1efa531b09ec62bc59cb344a4e175b486cb
4,808
h
C
C/ellipsoids.h
yketa/Umea-universitet---Spring-2017---code
eff7b22727a2e78705b360ed5c47e551bff59f09
[ "MIT" ]
null
null
null
C/ellipsoids.h
yketa/Umea-universitet---Spring-2017---code
eff7b22727a2e78705b360ed5c47e551bff59f09
[ "MIT" ]
null
null
null
C/ellipsoids.h
yketa/Umea-universitet---Spring-2017---code
eff7b22727a2e78705b360ed5c47e551bff59f09
[ "MIT" ]
null
null
null
#ifndef ELLIPSOIDS_H #define ELLIPSOIDS_H #include "param.h" #include "maths.h" /*STRUCTURES*/ typedef struct Overlap{ /*DESCRIBES THE INTERACTIONS BETWEEN PARTICLES*/ /*defined per couple of particles*/ /*Communication between functions*/ int overlapping; /*boolean ; 1 = overlapping / 0 = not overlapping*/ /*Variables for the computation of forces*/ double mu; /*resclaing factor for the ellipsoids to be externally tangent*/ /*refreshed only if overlap.overlapping*/ double r_c[3]; /*contact point*/ double r_c1[3]; /*contact point on particle 1*/ double r_c2[3]; /*contact point on particle 2*/ double v1c2[3]; /*local velocity of particle 1 at its point of contact with particle 2*/ double v2c1[3]; /*local velocity of particle 2 at its point of contact with particle 1*/ /*variables for measurements*/ double r_c1_in1[3]; /*coordinates of the contact point on the surface of particle 1 in particle 1 frame*/ double r_c2_in2[3]; /*coordinates of the contact point on the surface of particle 2 in particle 2 frame*/ /*error checking*/ double err; /*error on the determination of the root of polynomial H_{AB}*/ } Overlap; typedef struct SizeEllipsoid{ /*DESCRIBES THE PHYSICAL PARAMETERS OF THE PARTICLES*/ /*chosen*/ double m; /*mass of the ellipsoid*/ double R; /*nominal radius*/ double major; /*coefficient of the major axis*/ double minor; /*coefficient of the minor axis*/ /*inferred*/ double ax[3]; /*semi-axes of the ellipsoid*/ double I[3]; /*moments of inertia of the ellipsoid*/ int axMax; /*index of the longest axis*/ } SizeEllipsoid; typedef struct Ellipsoid{ /*DESCRIBES THE PARTICLES AND THEIR MOVEMENTS*/ /*Variables to measure*/ double r[3]; /*centre of the ellipsoid*/ double v[3]; /*velocity of the elliposoid*/ double q[4]; /*quaternion of the ellipsoid*/ double w[3]; /*rotation vector of the particle in the body frame*/ /*Description of the ellipsoid*/ int size; /*index of the size of the ellipsoid*/ double Q[9]; /*rotation matrix associated to q*/ } Ellipsoid; typedef struct Forces{ /*DESCRIBES THE EVOLUTION OF THE MOVEMENTS OF THE PARTICLES*/ /*Forces*/ double el[3]; /*elastic forces*/ double dis[3]; /*dissipative forces*/ /*Moments*/ double M[3]; /*moments of forces*/ /*Quaternions*/ double wdot[3]; /*first derivative of the rotation vector in the body frame*/ } Forces; /*PROTOTYPES*/ void rotation_matrix(Ellipsoid *ellipsoid); /*Updates the rotation matrix associated to ellipsoid->q.*/ double belonging_function(Ellipsoid *ellipsoid, SizeEllipsoid *sizes, double *vec); /*Returns the belonging fonction of ellipsoid, with semi-axes ax, evaluated in vec.*/ void omega(double *w, Ellipsoid *ellipsoid); /*Associates w to the rotation vector of ellipsoid.*/ void qdot(double *qp, Ellipsoid *ellipsoid); /*Associates qp to the first derivative of the quaternion of ellipsoid.*/ void wdot(Ellipsoid *ellipsoid, SizeEllipsoid *sizes, Forces *forces); /*Associates to forces->wdot the first derivative of the rotation vector of the ellipsoid.*/ void n_surface_vec(double *n, Ellipsoid *ellipsoid, SizeEllipsoid *sizes, double *vec); /*Associates n to the non-unit surface vector of ellipsoid, whose semi-axes are ax, at vec.*/ void inv_red_bel(double *Binv, Ellipsoid *ellipsoids, SizeEllipsoid *sizes); /*Associates Binv to the inverse of the reduced belonging matrix of ellipsoid.*/ void adj_y_ab(double *adj, double *Bainv, double *Bbinv); /*Associates to adj the adjoint of the matrix Y_{AB} defined by the inverses of the reduced belonging matrix of the ellipsoids, Bainv and Bbinv. Coefficients calculated with Mathematica.*/ void p_ab(double *pab, double *adj, double *rab); /*Associates to pab the coefficients of the polynomial P_{AB} corresponding to the ajoint adj of Y_{AB} and ellipsoids whose centers are separated by vector rab = \vec{r_B} - \vec{r_A}.*/ void q_ab(double *det, double *Bainv, double *Bbinv); /*Associated to det the coefficients of the determinant of the matrix Y_{AB} defined the inverses of the reduced belonging matrix of the ellipsoids, Bainv and Bbinv. Coefficients calculated with Mathematica.*/ double root_Haley_pol_hAB(double *hab, double *dhab, double start, double epsilon); /*Returns the root of the polynomial H_{AB} closed to start, found with the Haley's method with a precision epsilon, in the interval ]0,1[.*/ double eval_pol(double *coef, int deg, double x); /*Evaluates the polynomial of coefficients coef, degree deg in x using the Horner's rule.*/ void contact(Par *par, Overlap *overlap, SizeEllipsoid *sizes, Ellipsoid *ellipsoid1, Ellipsoid *ellipsoid2); /*Updates the contact points between ellipsoid1 and ellipsoid2. Algorithm described in subsection 2.5.1 — based on Perram and Wertheim, J. of Comp. Phys., 1995*/ #endif
40.403361
106
0.745424
[ "vector" ]
66de257675aa2c2a2e27030e021bd6185076baee
1,536
h
C
inc/object_container.h
emiflake/RTv1
76f8f799d7e89c69b3c6c90cd77288fd32e2b56b
[ "MIT" ]
null
null
null
inc/object_container.h
emiflake/RTv1
76f8f799d7e89c69b3c6c90cd77288fd32e2b56b
[ "MIT" ]
2
2019-09-23T17:00:16.000Z
2019-09-23T17:00:22.000Z
inc/object_container.h
emiflake/RTv1
76f8f799d7e89c69b3c6c90cd77288fd32e2b56b
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* :::::::: */ /* object_container.h :+: :+: */ /* +:+ */ /* By: nmartins <nmartins@student.codam.nl> +#+ */ /* +#+ */ /* Created: 2019/09/23 16:00:23 by nmartins #+# #+# */ /* Updated: 2019/10/16 18:46:04 by nmartins ######## odam.nl */ /* */ /* ************************************************************************** */ #ifndef OBJECT_CONTAINER_H # define OBJECT_CONTAINER_H # include "object.h" typedef struct s_object_node { t_object *object; struct s_object_node *next; } t_object_node; typedef struct s_object_container { t_object_node *root; } t_object_container; t_object_container *container_make(void); void container_push_object( t_object_node **container, t_object *obj); bool container_does_intersect( const t_object_container *container, const t_ray *ray); bool container_intersect( const t_object_container *container, const t_ray *ray, t_intersection *isect); void container_free( t_object_node *node); #endif
36.571429
80
0.400391
[ "object" ]
66f6d13dc2771607c9f68d5df3d8a93bf5874269
6,930
h
C
syzygy/reorder/basic_block_optimizer.h
nzeh/syzygy
3573e3d458dbb4285753c28a7cb42ced739f9f55
[ "Apache-2.0" ]
343
2015-01-07T05:58:44.000Z
2022-03-15T14:55:21.000Z
syzygy/reorder/basic_block_optimizer.h
nzeh/syzygy-nzeh
3757e53f850644721284073de318e218224dd411
[ "Apache-2.0" ]
61
2015-03-19T18:20:21.000Z
2019-10-23T12:58:23.000Z
syzygy/reorder/basic_block_optimizer.h
nzeh/syzygy-nzeh
3757e53f850644721284073de318e218224dd411
[ "Apache-2.0" ]
66
2015-01-20T15:35:05.000Z
2021-11-25T16:49:41.000Z
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SYZYGY_REORDER_BASIC_BLOCK_OPTIMIZER_H_ #define SYZYGY_REORDER_BASIC_BLOCK_OPTIMIZER_H_ #include <string> #include "base/strings/string_piece.h" #include "syzygy/block_graph/basic_block.h" #include "syzygy/block_graph/basic_block_subgraph.h" #include "syzygy/block_graph/block_graph.h" #include "syzygy/grinder/basic_block_util.h" #include "syzygy/pe/image_layout.h" #include "syzygy/pe/pe_file.h" #include "syzygy/pe/pe_transform_policy.h" #include "syzygy/reorder/reorderer.h" namespace reorder { // A class to optimize the basic-block placement of a block ordering, given // basic-block entry count data. class BasicBlockOptimizer { public: typedef grinder::basic_block_util::IndexedFrequencyInformation IndexedFrequencyInformation; typedef pe::ImageLayout ImageLayout; typedef Reorderer::Order Order; // A helper class with utility functions used by the optimization functions. // Exposed as public to facilitate unit-testing. class BasicBlockOrderer; // Constructor. BasicBlockOptimizer(); // @returns the name that will be assigned to the cold block section. const std::string& cold_section_name() const { return cold_section_name_; } // Set the name that will be assigned to the cold block section. void set_cold_section_name(const base::StringPiece& value) { DCHECK(!value.empty()); value.CopyToString(&cold_section_name_); } // Basic-block optimize the given @p order. bool Optimize(const ImageLayout& image_layout, const IndexedFrequencyInformation& entry_counts, Order* order); protected: typedef block_graph::BlockGraph BlockGraph; typedef block_graph::ConstBlockVector ConstBlockVector; // Optimize the layout of all basic-blocks in a block. static bool OptimizeBlock(const pe::PETransformPolicy& policy, const BlockGraph::Block* block, const ImageLayout& image_layout, const IndexedFrequencyInformation& entry_counts, Order::BlockSpecVector* warm_block_specs, Order::BlockSpecVector* cold_block_specs); // Optimize the layout of all basic-blocks in a section, as defined by the // given @p section_spec and the original @p image_layout. static bool OptimizeSection(const pe::PETransformPolicy& policy, const ImageLayout& image_layout, const IndexedFrequencyInformation& entry_counts, const ConstBlockVector& explicit_blocks, Order::SectionSpec* orig_section_spec, Order::BlockSpecVector* warm_block_specs, Order::BlockSpecVector* cold_block_specs); // The name of the (new) section in which to place cold blocks and // basic-blocks. std::string cold_section_name_; private: DISALLOW_COPY_AND_ASSIGN(BasicBlockOptimizer); }; // A helper class which generates warm and cold basic-block orderings for // a given basic-block subgraph. class BasicBlockOptimizer::BasicBlockOrderer { public: typedef block_graph::BasicBlock BasicBlock; typedef block_graph::BasicBlockSubGraph BasicBlockSubGraph; typedef block_graph::BasicCodeBlock BasicCodeBlock; typedef block_graph::BasicDataBlock BasicDataBlock; typedef std::set<const BasicBlock*> BasicBlockSet; typedef BlockGraph::Offset Offset; typedef BlockGraph::Size Size; typedef grinder::basic_block_util::EntryCountType EntryCountType; typedef grinder::basic_block_util::IndexedFrequencyInformation IndexedFrequencyInformation; typedef grinder::basic_block_util::RelativeAddress RelativeAddress; BasicBlockOrderer(const BasicBlockSubGraph& subgraph, const RelativeAddress& addr, Size size, const IndexedFrequencyInformation& entry_counts); // Get the number of times the block itself was entered. This assumes that // the entry point of the block is its first basic block. bool GetBlockEntryCount(EntryCountType* entry_count) const; // Generate an ordered list or warm and cold basic blocks. The warm basic- // blocks are ordered such that branches are straightened for the most common // successor. The cold basic-blocks are maintained in their original ordering // in the block. bool GetBasicBlockOrderings(Order::OffsetVector* warm_basic_blocks, Order::OffsetVector* cold_basic_blocks) const; protected: // Get the number of times a given code basic-block was entered. bool GetBasicBlockEntryCount(const BasicCodeBlock* code_bb, EntryCountType* entry_count) const; // Get the warmest not-yet-placed successor to the given code basic-block. // This may yield a NULL pointer, denoting either no successor, or no not- // yet-placed successor. bool GetWarmestSuccessor(const BasicCodeBlock* code_bb, const BasicBlockSet& placed_bbs, const BasicBlock** succ_bb) const; // Get the collection of the targets referenced from a given jmp instruction // sorted in order of decreasing entry count (i.e., highest entry count // first). Note that the sort is stable, targets having the same entry counts // are returned in the same relative order as originally in the jump table. bool GetSortedJumpTargets(const block_graph::Instruction& jmp_inst, std::vector<const BasicCodeBlock*>* targets) const; // Add all data basic-blocks referenced from @p code_bb to @p warm_references. bool AddWarmDataReferences(const BasicCodeBlock* code_bb, BasicBlockSet* warm_references) const; // Recursively add @p data_bb and all data basic-blocks referenced by // @p data_bb to @p warm references. void AddRecursiveDataReferences(const BasicDataBlock* data_bb, BasicBlockSet* warm_references) const; protected: const BasicBlockSubGraph& subgraph_; const RelativeAddress& addr_; const Size size_; const IndexedFrequencyInformation& entry_counts_; private: DISALLOW_COPY_AND_ASSIGN(BasicBlockOrderer); }; } // namespace reorder #endif // SYZYGY_REORDER_BASIC_BLOCK_OPTIMIZER_H_
42
80
0.717749
[ "vector" ]
66fb074aa6d07da70a8b283a29055809910e5e05
15,495
h
C
libdai/include/dai/dfactor.h
akxlr/tbp
bde86b6156c9fd70cd26001621db397100355003
[ "MIT" ]
11
2018-01-31T16:14:28.000Z
2021-06-22T03:45:11.000Z
libdai/include/dai/dfactor.h
akxlr/tbp
bde86b6156c9fd70cd26001621db397100355003
[ "MIT" ]
1
2019-05-25T08:20:58.000Z
2020-02-17T10:58:55.000Z
libdai/include/dai/dfactor.h
akxlr/tbp
bde86b6156c9fd70cd26001621db397100355003
[ "MIT" ]
3
2018-12-13T11:49:22.000Z
2021-12-31T03:19:26.000Z
/// \file /// \brief Defines DFactor class which represents decomposed factors in probability distributions. #ifndef __defined_libdai_dfactor_h #define __defined_libdai_dfactor_h #include <iostream> #include <functional> #include <cmath> #include <dai/prob.h> #include <dai/varset.h> #include <dai/index.h> #include <dai/util.h> #include <initializer_list> #include <Eigen/Dense> #include <random> #include <dai/dfactor_macros.h> // Also includes realfactor.h, because DFactor has asTFactor() function #include <dai/realfactor.h> #define EXACT_THRESHOLD 1 // Possible reweightings: // "NORMONLY": Normalise only // "MAXNORM": Every term (rank one tensor) is divided by its max and corresponding weight multiplied by this, so that each term has max-norm 1. Then normalise. // "MINVAR": Reweighting to minimise sum-of-component variance. Then normalise. // Normalise here means make the total probability mass 1 (not the weight sum). We do this for numerical reasons. // We never normalise the weight sum to be 1, since sampler in multiply method doesn't require normalised weights. #define REWEIGHT_NORMONLY 0 #define REWEIGHT_MAXNORM 1 #define REWEIGHT_MINVAR 2 #define REWEIGHT_METHOD REWEIGHT_MAXNORM namespace dai { extern int tbp_sample_size; class DFactor { public: std::vector<int> var_labels; VarSet vs; Eigen::VectorXd weights; std::vector<Eigen::MatrixXd> factors; public: /// \name Constructors and destructors //@{ /// Constructs factor depending on no variables with value \a p /* USED_BY_JTREE */ // TODO No idea what this is for; probably need to add a 1 to weights or factors DFactor (double p = 1 ); /// Constructs factor depending on the variable \a v with uniform distribution DFactor( const Var &v ); /// Constructs factor depending on variables in \a vars with uniform distribution DFactor( const VarSet& vars ); /// Constructs factor depending on variables in \a vars with all values set to \a p /* USED_BY_JTREE */ DFactor( const VarSet& vars, double p ); /// Constructs factor depending on variables in \a vars, copying the values from a std::vector<> /** \tparam S Type of values of \a x * \param vars contains the variables that the new factor should depend on. * \param x Vector with values to be copied. */ template<typename S> DFactor( const VarSet& vars, const std::vector<S> &x ) { DFACTOR_NOT_IMPL; } /// Constructs factor depending on variables in \a vars, copying the values from an array /** \param vars contains the variables that the new factor should depend on. * \param p Points to array of values to be added. */ DFactor( const VarSet& vars, const double* p ); /// Constructs factor depending on variables in \a vars, copying the values from \a p DFactor( const VarSet& vars, const TProb<double> &p ); /// Constructs factor depending on variables in \a vars, permuting the values given in \a p accordingly DFactor( const std::vector<Var> &vars, const std::vector<double> &p ); DFactor(const std::vector<int> v, const Eigen::VectorXd w, const std::vector<Eigen::MatrixXd> f); //@} /// \name Get/set individual entries //@{ /// Sets \a i 'th entry to \a val /* USED_BY_JTREE */ void set( size_t i, double val ); /// Gets \a i 'th entry double get( size_t i ) const; //@} /// \name Queries //@{ /// Returns constant reference to value vector const TProb<double>& p() const; /// Returns reference to value vector /* USED_BY_JTREE */ TProb<double>& p(); /// Returns a copy of the \a i 'th entry of the value vector /* USED_BY_JTREE */ double operator[] (size_t i) const; /// Returns constant reference to variable set (i.e., the variables on which the factor depends) /* USED_BY_JTREE */ const VarSet& vars() const; /// Returns reference to variable set (i.e., the variables on which the factor depends) /* USED_BY_JTREE */ VarSet& vars(); /// Returns the number of possible joint states of the variables on which the factor depends, \f$\prod_{l\in L} S_l\f$ /** \note This is equal to the length of the value vector. */ size_t nrStates() const; /// Returns the Shannon entropy of \c *this, \f$-\sum_i p_i \log p_i\f$ double entropy() const; /// Returns maximum of all values double max() const; /// Returns minimum of all values double min() const; /// Returns sum of all values double sum() const; /// Returns sum of absolute values double sumAbs() const; /// Returns maximum absolute value of all values double maxAbs() const; /// Returns \c true if one or more values are NaN bool hasNaNs() const; /// Returns \c true if one or more values are negative bool hasNegatives() const; /// Returns strength of this factor (between variables \a i and \a j), as defined in eq. (52) of [\ref MoK07b] double strength( const Var &i, const Var &j ) const; /// Comparison bool operator==( const DFactor& y ) const; /// Formats a factor as a string std::string toString() const; //@} /// \name Unary transformations //@{ /// Returns negative of \c *this DFactor operator- () const; /// Returns pointwise absolute value DFactor abs() const; /// Returns pointwise exponent DFactor exp() const; /// Returns pointwise logarithm /** If \a zero == \c true, uses <tt>log(0)==0</tt>; otherwise, <tt>log(0)==-Inf</tt>. */ DFactor log(bool zero=false) const; /// Returns pointwise inverse /** If \a zero == \c true, uses <tt>1/0==0</tt>; otherwise, <tt>1/0==Inf</tt>. */ DFactor inverse(bool zero=true) const; /// Returns normalized copy of \c *this, using the specified norm /** \throw NOT_NORMALIZABLE if the norm is zero */ DFactor normalized( ProbNormType norm=NORMPROB ) const; //@} /// \name Unary operations //@{ /// Draws all values i.i.d. from a uniform distribution on [0,1) DFactor& randomize(); /// Sets all values to \f$1/n\f$ where \a n is the number of states DFactor& setUniform(); /// Applies absolute value pointwise DFactor& takeAbs(); /// Applies exponent pointwise DFactor& takeExp(); /// Applies logarithm pointwise /** If \a zero == \c true, uses <tt>log(0)==0</tt>; otherwise, <tt>log(0)==-Inf</tt>. */ DFactor& takeLog( bool zero = false ); /// Normalizes factor using the specified norm /** \throw NOT_NORMALIZABLE if the norm is zero */ /* USED_BY_JTREE */ double normalize( ProbNormType norm=NORMPROB ); //@} /// \name Operations with scalars //@{ /// Sets all values to \a x /* USED_BY_JTREE */ DFactor& fill (double x); /// Adds scalar \a x to each value DFactor& operator+= (double x); /// Subtracts scalar \a x from each value DFactor& operator-= (double x); /// Multiplies each value with scalar \a x DFactor& operator*= (double x); /// Divides each entry by scalar \a x DFactor& operator/= (double x); /// Raises values to the power \a x DFactor& operator^= (double x); //@} /// \name Transformations with scalars //@{ /// Returns sum of \c *this and scalar \a x DFactor operator+ (double x) const; /// Returns difference of \c *this and scalar \a x DFactor operator- (double x) const; /// Returns product of \c *this with scalar \a x DFactor operator* (double x) const; /// Returns quotient of \c *this with scalar \a x DFactor operator/ (double x) const; /// Returns \c *this raised to the power \a x DFactor operator^ (double x) const; //@} /// \name Operations with other factors //@{ /// Applies binary operation \a op on two factors, \c *this and \a g /** \tparam binOp Type of function object that accepts two arguments of type \a T and outputs a type \a T * \param g Right operand * \param op Operation of type \a binOp */ /* USED_BY_JTREE */ template<typename binOp> DFactor& binaryOp( const DFactor &g, binOp op ); /// Adds \a g to \c *this /** The sum of two factors is defined as follows: if * \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$g : \prod_{m\in M} X_m \to [0,\infty)\f$, then * \f[f+g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) + g(x_M).\f] */ DFactor& operator+= (const DFactor& g); /// Subtracts \a g from \c *this /** The difference of two factors is defined as follows: if * \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$g : \prod_{m\in M} X_m \to [0,\infty)\f$, then * \f[f-g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) - g(x_M).\f] */ DFactor& operator-= (const DFactor& g); /// Multiplies \c *this with \a g /** The product of two factors is defined as follows: if * \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$g : \prod_{m\in M} X_m \to [0,\infty)\f$, then * \f[fg : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) g(x_M).\f] */ /* USED_BY_JTREE */ DFactor& operator*= (const DFactor& g); /// Divides \c *this by \a g (where division by zero yields zero) /** The quotient of two factors is defined as follows: if * \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$g : \prod_{m\in M} X_m \to [0,\infty)\f$, then * \f[\frac{f}{g} : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto \frac{f(x_L)}{g(x_M)}.\f] */ DFactor& operator/= (const DFactor& g); //@} /// \name Transformations with other factors //@{ /// Returns result of applying binary operation \a op on two factors, \c *this and \a g /** \tparam binOp Type of function object that accepts two arguments of type \a T and outputs a type \a T * \param g Right operand * \param op Operation of type \a binOp */ /* USED_BY_JTREE */ template<typename binOp> DFactor binaryTr( const DFactor &g, binOp op ) const; /// Returns sum of \c *this and \a g /** The sum of two factors is defined as follows: if * \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$g : \prod_{m\in M} X_m \to [0,\infty)\f$, then * \f[f+g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) + g(x_M).\f] */ DFactor operator+ (const DFactor& g) const; /// Returns \c *this minus \a g /** The difference of two factors is defined as follows: if * \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$g : \prod_{m\in M} X_m \to [0,\infty)\f$, then * \f[f-g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) - g(x_M).\f] */ DFactor operator- (const DFactor& g) const; /// Returns product of \c *this with \a g /** The product of two factors is defined as follows: if * \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$g : \prod_{m\in M} X_m \to [0,\infty)\f$, then * \f[fg : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) g(x_M).\f] */ DFactor operator* (const DFactor& g) const; /// Returns quotient of \c *this by \a f (where division by zero yields zero) /** The quotient of two factors is defined as follows: if * \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$g : \prod_{m\in M} X_m \to [0,\infty)\f$, then * \f[\frac{f}{g} : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto \frac{f(x_L)}{g(x_M)}.\f] */ /* USED_BY_JTREE */ DFactor operator/ (const DFactor& g) const; //@} /// \name Miscellaneous operations //@{ /// Returns a slice of \c *this, where the subset \a vars is in state \a varsState /** \pre \a vars sould be a subset of vars() * \pre \a varsState < vars.nrStates() * * The result is a factor that depends on the variables of *this except those in \a vars, * obtained by setting the variables in \a vars to the joint state specified by the linear index * \a varsState. Formally, if \c *this corresponds with the factor \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$, * \f$M \subset L\f$ corresponds with \a vars and \a varsState corresponds with a mapping \f$s\f$ that * maps a variable \f$x_m\f$ with \f$m\in M\f$ to its state \f$s(x_m) \in X_m\f$, then the slice * returned corresponds with the factor \f$g : \prod_{l \in L \setminus M} X_l \to [0,\infty)\f$ * defined by \f$g(\{x_l\}_{l\in L \setminus M}) = f(\{x_l\}_{l\in L \setminus M}, \{s(x_m)\}_{m\in M})\f$. */ DFactor slice( const VarSet& vars, size_t varsState ) const; /// Embeds this factor in a larger VarSet /** \pre vars() should be a subset of \a vars * * If *this corresponds with \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$L \subset M\f$, then * the embedded factor corresponds with \f$g : \prod_{m\in M} X_m \to [0,\infty) : x \mapsto f(x_L)\f$. */ DFactor embed(const VarSet & vars) const; /// Returns marginal on \a vars, obtained by summing out all variables except those in \a vars, and normalizing the result if \a normed == \c true DFactor marginal(const VarSet &vars, bool normed=true) const; /// Returns max-marginal on \a vars, obtained by maximizing all variables except those in \a vars, and normalizing the result if \a normed == \c true DFactor maxMarginal(const VarSet &vars, bool normed=true) const; void reweight(); TFactor<Real> asTFactor() const; double weightSum() const { return weights.sum(); }; //@} }; /// Writes a factor to an output stream /** \relates DFactor */ std::ostream& operator<< (std::ostream& os, const DFactor& f); /// Returns distance between two factors \a f and \a g, according to the distance measure \a dt /** \relates DFactor * \pre f.vars() == g.vars() */ double dist( const DFactor &f, const DFactor &g, ProbDistType dt ); /// Returns the pointwise maximum of two factors /** \relates DFactor * \pre f.vars() == g.vars() */ DFactor max( const DFactor &f, const DFactor &g ); /// Returns the pointwise minimum of two factors /** \relates DFactor * \pre f.vars() == g.vars() */ DFactor min( const DFactor &f, const DFactor &g ); /// Calculates the mutual information between the two variables that \a f depends on, under the distribution given by \a f /** \relates DFactor * \pre f.vars().size() == 2 */ double MutualInfo(const DFactor &f); } // end of namespace dai #endif
37.427536
159
0.5909
[ "object", "vector" ]
0f04cd8d7ed1446c5f8a7775f682d75db0ede0d5
2,759
h
C
src/Grid/Grid.h
AlexIII/GRAFEN
9643b13350dbbce5355a02715270f1e481aacf94
[ "MIT" ]
1
2019-09-09T03:44:40.000Z
2019-09-09T03:44:40.000Z
src/Grid/Grid.h
AlexIII/GRAFEN
9643b13350dbbce5355a02715270f1e481aacf94
[ "MIT" ]
null
null
null
src/Grid/Grid.h
AlexIII/GRAFEN
9643b13350dbbce5355a02715270f1e481aacf94
[ "MIT" ]
1
2019-09-14T20:30:21.000Z
2019-09-14T20:30:21.000Z
#pragma once #include <stdint.h> #include <iostream> #include <fstream> #include <string> #include <vector> #include <functional> #include <math.h> #define __int32 int class Grid { private: __int32 ReadInt32(std::ifstream* fs); double ReadDouble(std::ifstream* fs); void WriteInt32(std::ofstream* fs, __int32 value); void WriteDouble(std::ofstream* fs, double value); bool Init(); public: std::vector<double> data; int nRow; int nCol; double xLL; double yLL; double xSize; double ySize; double zMin; double zMax; double Rotation; double BlankValue; std::string fname; public: Grid(); Grid(const std::string &fileName); static Grid GenerateEmptyGrid(Grid& grid); double getAverage(); double getMin(); double getMax(); const double& at(const int col, const int row) const { return data[row*nCol + col]; } double& at(const int col, const int row) { return data[row*nCol + col]; } double xAt(const int col) const { return xLL + col * xSize; } double yAt(const int row) const { return yLL + row * ySize; } double width() const { return (nCol - 1) * xSize; } double height() const { return (nRow - 1) * ySize; } double mean() const { int count = 0; double mean = 0; forEach([&BlankValue = BlankValue, &count, &mean](int, int, const double &v) { if (v == BlankValue) return; mean += v; ++count; }); return count? mean / count : 0; } void forEach(const std::function<void(int, int, double&)>& f) { for (int i = 0; i < nCol; ++i) for (int j = 0; j < nRow; ++j) f(i, j, at(i, j)); } void forEach(const std::function<void(int, int, const double&)>& f) const { for (int i = 0; i < nCol; ++i) for (int j = 0; j < nRow; ++j) f(i, j, at(i, j)); } void setBlanksTo(const double bv) { forEach([&BlankValue = BlankValue, &bv](int, int, double& val) { if (val == BlankValue) val = bv; }); } Grid& upScale(const int xFactor, const int yFactor) { upScaleX(xFactor); upScaleY(yFactor); return *this; } void upScaleX(const int factor) { std::vector<double> newData(nRow*nCol*factor); for (int i = 0; i < nRow*nCol; ++i) for (int k = 0; k < factor; ++k) newData[i*factor+k] = data[i]; data = newData; nCol *= factor; xSize /= double(factor); } void upScaleY(const int factor) { std::vector<double> newData(nRow*nCol*factor); for (int i = 0; i < nRow; ++i) for (int j = 0; j < nCol; ++j) for (int k = 0; k < factor; ++k) newData[i*nCol*factor + k*nCol + j] = data[i*nCol + j]; data = newData; nRow *= factor; ySize /= double(factor); } bool Read(const std::string &fileName); bool Read(); bool Write(const std::string &fileName); bool Write(); }; std::ostream& operator<<(std::ostream& os, const Grid& g);
22.25
80
0.625951
[ "vector" ]
0f096fb34384a9b470eefc06f96aa29deeb3e374
593
c
C
d/magic/obj/timemass.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/magic/obj/timemass.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/magic/obj/timemass.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
#include <std.h>; inherit OBJECT; object spell; void create(){ ::create(); set_name("silvery haze"); set_id( ({"haze","silvery haze","time hop haze"}) ); set_short("%^BOLD%^A %^RESET%^s%^BOLD%^i%^RESET%^l%^BOLD%^v" "%^RESET%^e%^BOLD%^r%^RESET%^y %^BOLD%^haze%^RESET%^"); set_long("A strange %^RESET%^s%^BOLD%^i%^RESET%^l%^BOLD%^v%^RESET%^" "e%^BOLD%^r%^RESET%^y haze hangs in the air here, coalescing into " "a vaguely humanoid shape before dissipating and reforming again."); set_weight(450); } void set_spell(object ob){ spell=ob; return 1; }
25.782609
74
0.608769
[ "object", "shape" ]
5865a2f62335a533b87dd0301d179f25a02fe598
805
h
C
CsPlugin/Source/CsCore/Public/Animation/AnimNotifies/CsAnimNotify_PlaySound.h
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
2
2019-03-17T10:43:53.000Z
2021-04-20T21:24:19.000Z
CsPlugin/Source/CsCore/Public/Animation/AnimNotifies/CsAnimNotify_PlaySound.h
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
CsPlugin/Source/CsCore/Public/Animation/AnimNotifies/CsAnimNotify_PlaySound.h
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "Animation/AnimNotifies/AnimNotify.h" // Types #include "Managers/Sound/CsTypes_Sound.h" #include "CsAnimNotify_PlaySound.generated.h" class UAnimSequenceBase; class USkeletalMeshComponent; UCLASS(const, hidecategories=Object, collapsecategories, meta=(DisplayName="Custom Play Sound")) class CSCORE_API UCsAnimNotify_PlaySound : public UAnimNotify { GENERATED_BODY() public: UCsAnimNotify_PlaySound(); // Begin UAnimNotify interface virtual FString GetNotifyName_Implementation() const override; virtual void Notify(USkeletalMeshComponent* MeshComp, UAnimSequenceBase* Animation) override; // End UAnimNotify interface UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "AnimNotify") FCsSound Sound; };
28.75
96
0.81118
[ "object" ]
586b6f18cdc7f35f1f7bc235ac1a6d74fc10804a
1,325
h
C
Source/GlyphVR/Glyph.h
FlippRipp/GlyphVR
3c52816e0513f50407f2f3c2fb600fb94142eb63
[ "MIT" ]
null
null
null
Source/GlyphVR/Glyph.h
FlippRipp/GlyphVR
3c52816e0513f50407f2f3c2fb600fb94142eb63
[ "MIT" ]
null
null
null
Source/GlyphVR/Glyph.h
FlippRipp/GlyphVR
3c52816e0513f50407f2f3c2fb600fb94142eb63
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "Glyph.generated.h" UENUM(Blueprintable) enum class GlyphEnum : uint8 { SpellCircle UMETA(DisplayName = "SpellCircle"), //0 //Element glyphs Air UMETA(DisplayName = "Air"), //Myr 1 Fire UMETA(DisplayName = "Fire"), //Sif 2 Earth UMETA(DisplayName = "Earth"), //Lod 3 Water UMETA(DisplayName = "Water"), //Nar 4 Light UMETA(DisplayName = "Light"), //Fax 5 Dark UMETA(DisplayName = "Dark"), //Nyx 6 //Shape glyphs Beam UMETA(DisplayName = "Beam"), //ark 7 Projectile UMETA(DisplayName = "Projectile"), //Mol 8 Buff UMETA(DisplayName = "Buff"), //kas 9 Shield UMETA(DisplayName = "Shield"), //Bir 10 Default UMETA(DisplayName = "Default") //Bir 10 }; UENUM(Blueprintable) enum class GlyphCombosEnum : uint8 { //Element glyph Combos Frost UMETA(DisplayName = "Frost"), //air & dark }; UCLASS() class GLYPHVR_API AGlyph : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AGlyph(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; };
23.660714
78
0.691321
[ "shape" ]
586ef37073c0928cafd0c90bb2bb76be48373d0f
5,538
h
C
moveit_core/collision_detection/include/moveit/collision_detection/grid_based_world.h
dyouakim/moveit
fc103e75a7bc6c09b6b7c32aaa12f84283e09bba
[ "BSD-3-Clause" ]
null
null
null
moveit_core/collision_detection/include/moveit/collision_detection/grid_based_world.h
dyouakim/moveit
fc103e75a7bc6c09b6b7c32aaa12f84283e09bba
[ "BSD-3-Clause" ]
null
null
null
moveit_core/collision_detection/include/moveit/collision_detection/grid_based_world.h
dyouakim/moveit
fc103e75a7bc6c09b6b7c32aaa12f84283e09bba
[ "BSD-3-Clause" ]
1
2019-12-14T13:01:03.000Z
2019-12-14T13:01:03.000Z
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2016, Andrew Dornbush // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////////////////////////// /// \author Andrew Dornbush /// Dina Youakim #ifndef grid_based_world_h #define grid_based_world_h // standard includes #include <memory> #include <string> #include <vector> // system includes #include <moveit_msgs/CollisionObject.h> #include <octomap_msgs/OctomapWithPose.h> #include <smpl/occupancy_grid.h> #include <shape_msgs/MeshTriangle.h> #include <visualization_msgs/MarkerArray.h> #include <moveit/collision_detection/world.h> namespace collision_detection { MOVEIT_CLASS_FORWARD(GridWorld); class GridWorld : public World { public: GridWorld(sbpl::OccupancyGrid* grid); GridWorld(GridWorld& world); GridWorld(const World& world, sbpl::OccupancyGrid* grid); ~GridWorld(); sbpl::OccupancyGrid* grid(); const sbpl::OccupancyGrid* grid() const; /** \brief Add shapes to an object in the map. * This function makes repeated calls to addToObjectInternal() to add the * shapes one by one. * \note This function does NOT call the addToObject() variant that takes * a single shape and a single pose as input. */ void addToObject(const std::string& id, const bool is_manip_obj, const std::vector<shapes::ShapeConstPtr>& shapes, const EigenSTL::vector_Affine3d& poses); /** \brief Add a shape to an object. * If the object already exists, this call will add the shape to the object * at the specified pose. Otherwise, the object is created and the * specified shape is added. This calls addToObjectInternal(). */ void addToObject(const std::string& id, const bool is_manip_obj, const shapes::ShapeConstPtr& shape, const Eigen::Affine3d& pose); /** \brief Update the pose of a shape in an object. Shape equality is * verified by comparing pointers. Returns true on success. */ bool moveShapeInObject(const std::string& id, const shapes::ShapeConstPtr& shape, const Eigen::Affine3d& pose); /** \brief Remove shape from object. * Shape equality is verified by comparing pointers. Ownership of the * object is renounced (i.e. object is deleted if no external references * exist) if this was the last shape in the object. * Returns true on success and false if the object did not exist or did not * contain the shape. */ bool removeShapeFromObject(const std::string& id, const shapes::ShapeConstPtr& shape); /** \brief Remove a particular object. * If there are no external pointers to the corresponding instance of * Object, the memory is freed. * Returns true on success and false if no such object was found. */ bool removeObject(const std::string& id); /** \brief Clear all objects. * If there are no other pointers to corresponding instances of Objects, * the memory is freed. */ void clearObjects(); void setPadding(double padding); double padding() const; void printObjectsSize(); private: sbpl::OccupancyGrid* m_grid; // set of collision objects std::map<std::string, ObjectConstPtr> m_object_map; // voxelization of objects in the grid reference frame typedef std::vector<Eigen::Vector3d> VoxelList; std::map<std::string, std::vector<VoxelList>> m_object_voxel_map; double m_padding; bool insertObjectInGrid(const ObjectConstPtr& object); bool removeObjectFromGrid(const std::string& object_name); bool removeObjectFromGrid(const ObjectConstPtr& object); bool moveShapesInGrid(const ObjectConstPtr& object); bool insertShapesInGrid(const ObjectConstPtr& object); bool removeShapesFromGrid(const ObjectConstPtr& object); /// \brief Reset the underlying occupancy grid. /// /// Resets the WorldCollisionModel by clearing the underlying occupancy grid void reset(); }; } // namespace collision #endif
39
134
0.711087
[ "object", "shape", "vector" ]
586f944ab388b1a278233f48fe6c7e3ef6f16db2
2,926
h
C
ModelingProject1/SourceCode/Game Core/GameSound.h
OscarRPR/samurai-reborn
9354e18942c220f687bf1b54649e19541b19157b
[ "MIT" ]
1
2015-10-11T01:26:08.000Z
2015-10-11T01:26:08.000Z
ModelingProject1/SourceCode/Game Core/GameSound.h
OscarRPR/samurai-reborn
9354e18942c220f687bf1b54649e19541b19157b
[ "MIT" ]
null
null
null
ModelingProject1/SourceCode/Game Core/GameSound.h
OscarRPR/samurai-reborn
9354e18942c220f687bf1b54649e19541b19157b
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include <fmod.hpp> #include <fmod_errors.h> #include <PlayerSpriteStates.h> #include <File.h> /* **ID's** SoundID: 0 = characterSound 1 = Menu/LevelSound StateID: 0 = attackSound 1 = groundhitSound 2 = runningSound 3 = Still Attack Sound **Files Layout** Musics.txt: 0 = Panda sounds 1 = Meerkat Sounds LevelSounds.txt: 0 = Level One 1 = SMainMenu 0 = Background Music 1 = Selection sound 2 = SPlayerSelection 0 = Background Music 1 = Selection sound 3 = PauseMenu 0 = Background Music 1 = Selection sound 4 = SoundMenu 0 = Background Music 1 = Selection sound **Channels** Channel[0] = SE = on going sounds/music Channel[1] = MUS = one time, multiple use sounds/chunks Channel[2] = RS = partial duration sounds ch[0] = Additional musics ch[1] = Additional effects **Volume** Max value = 1.0f Min Value = 0.0f volumeValues[0] = Value for the musics volume volumeValues[1] = Value for the effects volume */ class GameSound { public: GameSound(void); ~GameSound(); static GameSound* getInstance(); bool initSound(); void closeAll(); void ERRCHECK(FMOD_RESULT); void pauseSystem(); void unpauseSystem(); void clearAuxiliarSystem(); void initSounds(int characterID, int soundType); void splitFileSounds(std::string line, int soundType); void upVolume(int channelID, float increasingValue); void downVolume(int channelID, float decreasingValue); float getVolume(int channelID); void upOverallVolume(float increasingValue); void downOverallVolume(float decreasingValue); void upMusicVolume(float increasingValue); void downMusicVolume(float decreasingValue); void upEffectsVolume(float increasingValue); void downEffectsVolume(float decreasingValue); void loadChunk(int row, int soundType, int soundID); void loadSound(int row, int soundType, int soundID); void playAdditionalSound(int row, int soundType, int soundID); void playAdditionalChunk(int row, int soundType, int soundID); void playSound(int row, int soundType, int soundID); void closeSound(); void stateSoundsHandling(GameCoreStates::SpriteState previousState); std::string soundSelection(int soundType, int soundID); float getMusicVolume(); float getEffectsVolume(); private: std::vector< std::string > ambienceSounds; std::vector< std::string > statesSounds; std::string sFilename; std::string lFilename; static bool instanceFlag; const char* currentSound; static GameSound* gameSound; FMOD::System* system; FMOD::Sound* sound; FMOD::Sound* chunks[3]; FMOD::Channel* channel[3]; FMOD_RESULT result; FMOD::Sound* sd; FMOD::Channel* ch[2]; FMOD::System* syste; FMOD_RESULT res; float volumeValues[2]; };
25.008547
72
0.689337
[ "vector" ]
587ebba43be49c1308cd6e4d7e0d2b7a25a03025
4,370
h
C
src/bittorrent/service.h
i96751414/torrest-cpp
1a975c598c316a9801d5b1b9d83908ba05084fc3
[ "MIT" ]
null
null
null
src/bittorrent/service.h
i96751414/torrest-cpp
1a975c598c316a9801d5b1b9d83908ba05084fc3
[ "MIT" ]
null
null
null
src/bittorrent/service.h
i96751414/torrest-cpp
1a975c598c316a9801d5b1b9d83908ba05084fc3
[ "MIT" ]
1
2021-12-06T05:52:29.000Z
2021-12-06T05:52:29.000Z
#ifndef TORREST_SERVICE_H #define TORREST_SERVICE_H #include <regex> #include <mutex> #include <vector> #include <atomic> #include <condition_variable> #include <memory> #include "spdlog/spdlog.h" #include "libtorrent/settings_pack.hpp" #include "libtorrent/session.hpp" #include "settings/settings.h" #include "torrent.h" #include "file.h" #include "settings.h" namespace torrest { namespace bittorrent { struct ServiceStatus { double progress; std::int64_t download_rate; std::int64_t upload_rate; int num_torrents; bool paused; }; class Service { public: explicit Service(const settings::Settings &pSettings); ~Service(); void reconfigure(const settings::Settings &pSettings, bool pReset); std::shared_ptr<Torrent> get_torrent(const std::string &pInfoHash) const; std::vector<std::shared_ptr<Torrent>> get_torrents() const; void remove_torrent(const std::string &pInfoHash, bool pRemoveFiles); std::string add_magnet(const std::string &pMagnet, bool pDownload); std::string add_torrent_data(const char *pData, int pSize, bool pDownload); std::string add_torrent_file(const std::string &pFile, bool pDownload); ServiceStatus get_status() const; void pause(); void resume(); private: void check_save_resume_data_handler(); void consume_alerts_handler(); void progress_handler(); void update_progress(); void handle_save_resume_data(const libtorrent::save_resume_data_alert *pAlert); void handle_metadata_received(const libtorrent::metadata_received_alert *pAlert); void handle_state_changed(const libtorrent::state_changed_alert *pAlert); void configure(const settings::Settings &pSettings); void set_buffering_rate_limits(bool pEnable); void remove_torrents(); void add_torrent_with_params(libtorrent::add_torrent_params &pTorrentParams, const std::string &pInfoHash, bool pIsResumeData, bool pDownload); std::string add_torrent_file(const std::string &pFile, bool pDownload, bool pSaveFile); std::string add_magnet(const std::string &pMagnet, bool pDownload, bool pSaveMagnet); void add_torrent_with_resume_data(const std::string &pFile); void load_torrent_files(); std::vector<std::shared_ptr<Torrent>>::const_iterator find_torrent(const std::string &pInfoHash, bool pMustFind = true) const; bool has_torrent(const std::string &pInfoHash) const; std::string get_parts_file(const std::string &pInfoHash) const; std::string get_fast_resume_file(const std::string &pInfoHash) const; std::string get_torrent_file(const std::string &pInfoHash) const; std::string get_magnet_file(const std::string &pInfoHash) const; void delete_parts_file(const std::string &pInfoHash) const; void delete_fast_resume_file(const std::string &pInfoHash) const; void delete_torrent_file(const std::string &pInfoHash) const; void delete_magnet_file(const std::string &pInfoHash) const; bool wait_for_abort(const int &pSeconds); bool wait_for_abort(const std::chrono::seconds &pSeconds); const std::regex mPortRegex = std::regex(":\\d+$"); const std::regex mWhiteSpaceRegex = std::regex("\\s+"); const std::regex mIpRegex = std::regex("\\.\\d+"); std::shared_ptr<spdlog::logger> mLogger; std::shared_ptr<spdlog::logger> mAlertsLogger; libtorrent::settings_pack mSettingsPack; std::shared_ptr<libtorrent::session> mSession; std::vector<std::shared_ptr<Torrent>> mTorrents; std::shared_ptr<ServiceSettings> mSettings; mutable std::mutex mTorrentsMutex; mutable std::mutex mServiceMutex; mutable std::mutex mCvMutex; std::condition_variable mCv; std::vector<std::thread> mThreads; std::atomic<bool> mIsRunning; std::int64_t mDownloadRate; std::int64_t mUploadRate; double mProgress; bool mRateLimited; }; }} #endif //TORREST_SERVICE_H
31.438849
104
0.659039
[ "vector" ]
588d44f1c5354f1439cfc7d39054b653982bf283
6,924
h
C
src/ai/server/Server.h
sagpant/simpleai
db3acd891f46f67ae70c271bf88a46e6e6b28b0f
[ "Zlib" ]
173
2015-01-01T23:01:47.000Z
2022-03-05T23:12:24.000Z
src/ai/server/Server.h
mgerhardy/simpleai
db3acd891f46f67ae70c271bf88a46e6e6b28b0f
[ "Zlib" ]
31
2015-01-24T08:07:50.000Z
2019-10-08T19:12:30.000Z
src/ai/server/Server.h
mgerhardy/simpleai
db3acd891f46f67ae70c271bf88a46e6e6b28b0f
[ "Zlib" ]
14
2015-08-23T21:25:32.000Z
2022-03-02T05:33:38.000Z
/** * @file */ #pragma once #include "common/Thread.h" #include "tree/TreeNode.h" #include <unordered_set> #include "Network.h" #include "zone/Zone.h" #include "AIRegistry.h" #include "AIStateMessage.h" #include "AINamesMessage.h" #include "AIStubTypes.h" #include "AICharacterDetailsMessage.h" #include "AICharacterStaticMessage.h" #include "ProtocolHandlerRegistry.h" #include "conditions/ConditionParser.h" #include "tree/TreeNodeParser.h" #include "tree/TreeNodeImpl.h" namespace ai { class AIStateNode; class AIStateNodeStatic; class SelectHandler; class PauseHandler; class ResetHandler; class StepHandler; class ChangeHandler; class AddNodeHandler; class DeleteNodeHandler; class UpdateNodeHandler; class NopHandler; /** * @brief The server can serialize the state of the @ai{AI} and broadcast it to all connected clients. * * If you start a server, you can add the @ai{AI} instances to it by calling @ai{addZone()}. If you do so, make * sure to remove it when you remove that particular @ai{Zone} instance from your world. You should not do that * from different threads. The server should only be managed from one thread. * * The server will broadcast the world state - that is: It will send out an @ai{AIStateMessage} to all connected * clients. If someone selected a particular @ai{AI} instance by sending @ai{AISelectMessage} to the server, it * will also broadcast an @ai{AICharacterDetailsMessage} to all connected clients. * * You can only debug one @ai{Zone} at the same time. The debugging session is shared between all connected clients. */ class Server: public INetworkListener { protected: typedef std::unordered_set<Zone*> Zones; typedef Zones::const_iterator ZoneConstIter; typedef Zones::iterator ZoneIter; Zones _zones; AIRegistry& _aiRegistry; Network _network; CharacterId _selectedCharacterId; int64_t _time; SelectHandler *_selectHandler; PauseHandler *_pauseHandler; ResetHandler *_resetHandler; StepHandler *_stepHandler; ChangeHandler *_changeHandler; AddNodeHandler *_addNodeHandler; DeleteNodeHandler *_deleteNodeHandler; UpdateNodeHandler *_updateNodeHandler; NopHandler _nopHandler; std::atomic_bool _pause; // the current active debugging zone std::atomic<Zone*> _zone; ReadWriteLock _lock = {"server"}; std::vector<std::string> _names; uint32_t _broadcastMask = 0u; enum EventType { EV_SELECTION, EV_STEP, EV_UPDATESTATICCHRDETAILS, EV_NEWCONNECTION, EV_ZONEADD, EV_ZONEREMOVE, EV_PAUSE, EV_RESET, EV_SETDEBUG, EV_MAX }; struct Event { union { CharacterId characterId; int64_t stepMillis; Zone* zone; Client* newClient; bool pauseState; } data; std::string strData = ""; EventType type; }; std::vector<Event> _events; void resetSelection(); void addChildren(const TreeNodePtr& node, std::vector<AIStateNodeStatic>& out) const; void addChildren(const TreeNodePtr& node, AIStateNode& parent, const AIPtr& ai) const; // only call these from the Server::update method void broadcastState(const Zone* zone); void broadcastCharacterDetails(const Zone* zone); void broadcastStaticCharacterDetails(const Zone* zone); void onConnect(Client* client) override; void onDisconnect(Client* client) override; void handleEvents(Zone* zone, bool pauseState); void enqueueEvent(const Event& event); public: Server(AIRegistry& aiRegistry, short port = 10001, const std::string& hostname = "0.0.0.0"); virtual ~Server(); /** * @brief Start to listen on the specified port */ bool start(); /** * @brief Update the specified node with the given values for the specified @ai{ICharacter} and all the * other characters that are using the same behaviour tree instance * * @param[in] characterId The id of the character where we want to update the specified node * @param[in] nodeId The id of the @ai{TreeNode} to update with the new values * @param[in] name The new name for the node * @param[in] type The new node type (including parameters) * @param[in] condition The new condition (including parameters) * * @see @c TreeNodeParser * @see @c ConditionParser */ bool updateNode(const CharacterId& characterId, int32_t nodeId, const std::string& name, const std::string& type, const std::string& condition); /** * @brief Add a new node with the given values to the specified @ai{ICharacter} and all the * other characters that are using the same behaviour tree instance * * @param[in] characterId The id of the @ai{ICharacter} where we want to add the specified node * @param[in] parentNodeId The id of the @ai{TreeNode} to attach the new @ai{TreeNode} as children * @param[in] name The new name for the node * @param[in] type The new node type (including parameters) * @param[in] condition The new condition (including parameters) * * @see @ai{TreeNodeParser} * @see @ai{ConditionParser} */ bool addNode(const CharacterId& characterId, int32_t parentNodeId, const std::string& name, const std::string& type, const std::string& condition); /** * @brief Delete the specified node from the @ai{ICharacter}'s behaviour tree and all the * other characters that are using the same behaviour tree instance * * @param[in] characterId The id of the @ai{ICharacter} where we want to delete the specified node * @param[in] nodeId The id of the @ai{TreeNode} to delete */ bool deleteNode(const CharacterId& characterId, int32_t nodeId); /** * @brief Adds a new zone to this server instance that can be debugged. The server does not own this pointer * so it also doesn't free it. Every @ai{Zone} that is added here, will be part of the @ai{AINamesMessage}. * * @param zone The @ai{Zone} that should be made available for debugging. * * @note This locks the server instance */ void addZone(Zone* zone); /** * @brief Removes a @ai{Zone} from the server. After this call the given zone is no longer available for debugging * purposes. * * @note This locks the server instance */ void removeZone(Zone* zone); /** * @brief Activate the debugging for this particular zone. And disables the debugging for every other zone * * @note This locks the server instance */ void setDebug(const std::string& zoneName); /** * @brief Resets the @ai{AI} states */ void reset(); /** * @brief Select a particular character (resp. @ai{AI} instance) and send detail * information to all the connected clients for this entity. */ void select(const ClientId& clientId, const CharacterId& id); /** * @brief Will pause/unpause the execution of the behaviour trees for all watched @ai{AI} instances. */ void pause(const ClientId& clientId, bool pause); /** * @brief Performs one step of the @ai{AI} in pause mode */ void step(int64_t stepMillis = 1L); /** * @brief call this to update the server - should get called somewhere from your game tick */ void update(int64_t deltaTime); }; }
31.616438
148
0.736568
[ "vector" ]
58976f0177bc1a55f79d98dddd68349b18389ffa
3,163
h
C
src/devices/sound/ym2154.h
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/devices/sound/ym2154.h
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/devices/sound/ym2154.h
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Aaron Giles #ifndef MAME_SOUND_YM2154_H #define MAME_SOUND_YM2154_H #pragma once //************************************************************************** // TYPE DEFINITIONS //************************************************************************** DECLARE_DEVICE_TYPE(YM2154, ym2154_device) // ======================> ym2154_device class ym2154_device : public device_t, public device_sound_interface, public device_memory_interface { static constexpr uint8_t ADDR_SHIFT = 6; public: // internal constructor ym2154_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock); // configuration helpers auto irq_handler() { return m_update_irq.bind(); } auto io_read_handler() { return m_io_read.bind(); } auto io_write_handler() { return m_io_write.bind(); } // register reads u8 read(offs_t offset); // register writes void write(offs_t offset, u8 data); protected: // device-level overrides virtual void device_start() override; virtual void device_reset() override; virtual void device_clock_changed() override; virtual void device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr) override; // sound overrides virtual void sound_stream_update(sound_stream &stream, std::vector<read_stream_view> const &inputs, std::vector<write_stream_view> &outputs) override; // memory space configuration virtual space_config_vector memory_space_config() const override; private: struct channel { channel() : m_pos(0xfffffff), m_start(0), m_end(0), m_panpot(0), m_output_level(0), m_rate(0) { } void reset() { m_pos = 0; m_start = m_end = 0; m_panpot = 0; m_output_level = 0; m_rate = 0; } void start() { m_pos = m_start << ADDR_SHIFT; } uint32_t m_pos; uint16_t m_start; uint16_t m_end; uint8_t m_panpot; uint8_t m_output_level; uint8_t m_rate; }; // internal helpers u32 sample_rate() const { return device_t::clock() / 18 / 6; } void update_irq_state(u8 state) { if (m_irq_state != state) { m_irq_state = state; m_update_irq(state); } } // internal state sound_stream *m_stream; // sound stream emu_timer *m_timer; // two timers uint16_t m_timer_count; // current timer count uint8_t m_timer_enable; // timer enable uint8_t m_irq_state; // current IRQ state uint8_t m_irq_count; // current IRQ count uint8_t m_total_level; // master volume channel m_channel[12]; // output channels devcb_write_line m_update_irq; // IRQ update callback devcb_read8 m_io_read; // input port handler devcb_write8 m_io_write; // output port handler address_space_config const m_group0_config; // address space 0 config address_space_config const m_group1_config; // address space 1 config optional_memory_region m_group0_region; // group 0 memory region optional_memory_region m_group1_region; // group 1 memory region }; #endif // MAME_SOUND_YM2154_H
31.63
151
0.654126
[ "vector" ]
5897b1c7942d6d3bd5887bc4e479b382818ce2b0
468
h
C
Pdf/pdfix_sdk_example_cpp-master/include/pdfixsdksamples/ParsePageContent.h
laoola/ProjectCode
498a66cb9274f6bb7cca0d6e6052304d61740ba2
[ "Unlicense" ]
1
2021-08-23T05:56:09.000Z
2021-08-23T05:56:09.000Z
Pdf/pdfix_sdk_example_cpp-master/include/pdfixsdksamples/ParsePageContent.h
laoola/ProjectCode
498a66cb9274f6bb7cca0d6e6052304d61740ba2
[ "Unlicense" ]
null
null
null
Pdf/pdfix_sdk_example_cpp-master/include/pdfixsdksamples/ParsePageContent.h
laoola/ProjectCode
498a66cb9274f6bb7cca0d6e6052304d61740ba2
[ "Unlicense" ]
null
null
null
#pragma once #include <string> #include <iostream> #include "Pdfix.h" using namespace PDFixSDK; namespace ParsePageContent { // ProcessObject gets the value of the object. void ProcessPageObject(PdsPageObject* obj, std::ostream& ss, std::string indent); // Iterates all documents bookmars. void Run( const std::wstring& open_path, // source PDF document std::ostream& output, // output document int page_num ); }
23.4
81
0.673077
[ "object" ]
5898e103e769382a00701c491ec76e4d1fc38909
1,146
h
C
codes/include/engine/threadloop.h
liangpengcheng/tng
01c6517f734d5db01f7d59bf95b225f6d1642b6e
[ "BSD-3-Clause" ]
3
2016-04-16T06:24:20.000Z
2018-09-29T13:36:51.000Z
codes/include/engine/threadloop.h
liangpengcheng/tng
01c6517f734d5db01f7d59bf95b225f6d1642b6e
[ "BSD-3-Clause" ]
null
null
null
codes/include/engine/threadloop.h
liangpengcheng/tng
01c6517f734d5db01f7d59bf95b225f6d1642b6e
[ "BSD-3-Clause" ]
3
2016-04-29T11:46:08.000Z
2019-09-16T03:27:30.000Z
#pragma once #include "core/os.h" #include "engine/engine_macros.h" #include "core/refobject.h" #include "uv/include/uv.h" #include "core/threadfun.h" #include <unordered_map> namespace tng { /** Loop One Loop is one thread */ class Service; class ENGINE_API Loop:public RefCountedObject { public: typedef std::unordered_map<string, Service*> ServiceMap; enum RUN_VALUE { NORMAL, EXIT, }; Loop(); virtual ~Loop(); virtual bool Create(); virtual void Destory(); virtual void Start(); void DestoryNextFrame(){destory_ = true;} void WaitThreadEnd(); void Update(void*); void AddService(const string& service_name, Service* service); void RemoveService(const string& service); Service* GetService(const string& service); protected: tick_t lastUpdateTime_; void createThread(); Thread* work_thread_; AtomicCounter destory_; ServiceMap service_map_; Mutex service_lock_; std::vector<string> deletelist_; }; /** main thread */ class ENGINE_API DefaultLoop:public Loop { public: virtual void Start(); //virtual bool Create(); }; }
20.464286
67
0.680628
[ "vector" ]
589db89f3ce36c555b2420229a1f795ce82d6b2e
12,366
c
C
vlc_linux/vlc-3.0.16/src/modules/modules.c
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
vlc_linux/vlc-3.0.16/src/modules/modules.c
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
vlc_linux/vlc-3.0.16/src/modules/modules.c
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
/***************************************************************************** * modules.c : Builtin and plugin modules management functions ***************************************************************************** * Copyright (C) 2001-2011 VLC authors and VideoLAN * $Id: 3ad50fb39153f3257304f1bad35c172e4b6526a5 $ * * Authors: Sam Hocevar <sam@zoy.org> * Ethan C. Baldridge <BaldridgeE@cadmus.com> * Hans-Peter Jansen <hpj@urpla.net> * Gildas Bazin <gbazin@videolan.org> * Rémi Denis-Courmont * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <stdlib.h> #include <string.h> #ifdef ENABLE_NLS # include <libintl.h> #endif #include <assert.h> #include <vlc_common.h> #include <vlc_modules.h> #include "libvlc.h" #include "config/configuration.h" #include "vlc_arrays.h" #include "modules/modules.h" /** * Checks whether a module implements a capability. * * \param m the module * \param cap the capability to check * \return true if the module has the capability */ bool module_provides (const module_t *m, const char *cap) { return !strcmp (module_get_capability (m), cap); } /** * Get the internal name of a module * * \param m the module * \return the module name */ const char *module_get_object( const module_t *m ) { if (unlikely(m->i_shortcuts == 0)) return "unnamed"; return m->pp_shortcuts[0]; } /** * Get the human-friendly name of a module. * * \param m the module * \param long_name TRUE to have the long name of the module * \return the short or long name of the module */ const char *module_get_name( const module_t *m, bool long_name ) { if( long_name && ( m->psz_longname != NULL) ) return m->psz_longname; if (m->psz_shortname != NULL) return m->psz_shortname; return module_get_object (m); } /** * Get the help for a module * * \param m the module * \return the help */ const char *module_get_help( const module_t *m ) { return m->psz_help; } /** * Gets the capability of a module * * \param m the module * \return the capability, or "none" if unspecified */ const char *module_get_capability (const module_t *m) { return (m->psz_capability != NULL) ? m->psz_capability : "none"; } /** * Get the score for a module * * \param m the module * return the score for the capability */ int module_get_score( const module_t *m ) { return m->i_score; } /** * Translate a string using the module's text domain * * \param m the module * \param str the American English ASCII string to localize * \return the gettext-translated string */ const char *module_gettext (const module_t *m, const char *str) { if (unlikely(str == NULL || *str == '\0')) return ""; #ifdef ENABLE_NLS const char *domain = m->plugin->textdomain; return dgettext ((domain != NULL) ? domain : PACKAGE_NAME, str); #else (void)m; return str; #endif } #undef module_start int module_start (vlc_object_t *obj, const module_t *m) { int (*activate) (vlc_object_t *) = m->pf_activate; return (activate != NULL) ? activate (obj) : VLC_SUCCESS; } #undef module_stop void module_stop (vlc_object_t *obj, const module_t *m) { void (*deactivate) (vlc_object_t *) = m->pf_deactivate; if (deactivate != NULL) deactivate (obj); } static bool module_match_name (const module_t *m, const char *name) { /* Plugins with zero score must be matched explicitly. */ if (!strcasecmp ("any", name)) return m->i_score > 0; for (unsigned i = 0; i < m->i_shortcuts; i++) if (!strcasecmp (m->pp_shortcuts[i], name)) return true; return false; } static int module_load (vlc_object_t *obj, module_t *m, vlc_activate_t init, va_list args) { int ret = VLC_SUCCESS; if (module_Map(obj, m->plugin)) return VLC_EGENERIC; if (m->pf_activate != NULL) { va_list ap; va_copy (ap, args); ret = init (m->pf_activate, ap); va_end (ap); } if (ret != VLC_SUCCESS) vlc_objres_clear(obj); return ret; } #undef vlc_module_load /** * Finds and instantiates the best module of a certain type. * All candidates modules having the specified capability and name will be * sorted in decreasing order of priority. Then the probe callback will be * invoked for each module, until it succeeds (returns 0), or all candidate * module failed to initialize. * * The probe callback first parameter is the address of the module entry point. * Further parameters are passed as an argument list; it corresponds to the * variable arguments passed to this function. This scheme is meant to * support arbitrary prototypes for the module entry point. * * \param obj VLC object * \param capability capability, i.e. class of module * \param name name of the module asked, if any * \param strict if true, do not fallback to plugin with a different name * but the same capability * \param probe module probe callback * \return the module or NULL in case of a failure */ module_t *vlc_module_load(vlc_object_t *obj, const char *capability, const char *name, bool strict, vlc_activate_t probe, ...) { char *var = NULL; if (name == NULL || name[0] == '\0') name = "any"; /* Deal with variables */ if (name[0] == '$') { var = var_InheritString (obj, name + 1); name = (var != NULL) ? var : "any"; } /* Find matching modules */ module_t **mods; ssize_t total = module_list_cap (&mods, capability); msg_Dbg (obj, "looking for %s module matching \"%s\": %zd candidates", capability, name, total); if (total <= 0) { module_list_free (mods); msg_Dbg (obj, "no %s modules", capability); return NULL; } module_t *module = NULL; const bool b_force_backup = obj->obj.force; /* FIXME: remove this */ va_list args; va_start(args, probe); while (*name) { char buf[32]; size_t slen = strcspn (name, ","); if (likely(slen < sizeof (buf))) { memcpy(buf, name, slen); buf[slen] = '\0'; } name += slen; name += strspn (name, ","); if (unlikely(slen >= sizeof (buf))) continue; const char *shortcut = buf; assert (shortcut != NULL); if (!strcasecmp ("none", shortcut)) goto done; obj->obj.force = strict && strcasecmp ("any", shortcut); for (ssize_t i = 0; i < total; i++) { module_t *cand = mods[i]; if (cand == NULL) continue; // module failed in previous iteration if (!module_match_name (cand, shortcut)) continue; mods[i] = NULL; // only try each module once at most... int ret = module_load (obj, cand, probe, args); switch (ret) { case VLC_SUCCESS: module = cand; /* fall through */ case VLC_ETIMEOUT: goto done; } } } /* None of the shortcuts matched, fall back to any module */ if (!strict) { obj->obj.force = false; for (ssize_t i = 0; i < total; i++) { module_t *cand = mods[i]; if (cand == NULL || module_get_score (cand) <= 0) continue; int ret = module_load (obj, cand, probe, args); switch (ret) { case VLC_SUCCESS: module = cand; /* fall through */ case VLC_ETIMEOUT: goto done; } } } done: va_end (args); obj->obj.force = b_force_backup; module_list_free (mods); free (var); if (module != NULL) { msg_Dbg (obj, "using %s module \"%s\"", capability, module_get_object (module)); vlc_object_set_name (obj, module_get_object (module)); } else msg_Dbg (obj, "no %s modules matched", capability); return module; } #undef vlc_module_unload /** * Deinstantiates a module. * \param module the module pointer as returned by vlc_module_load() * \param deinit deactivation callback */ void vlc_module_unload(vlc_object_t *obj, module_t *module, vlc_deactivate_t deinit, ...) { if (module->pf_deactivate != NULL) { va_list ap; va_start(ap, deinit); deinit(module->pf_deactivate, ap); va_end(ap); } vlc_objres_clear(obj); } static int generic_start(void *func, va_list ap) { vlc_object_t *obj = va_arg(ap, vlc_object_t *); int (*activate)(vlc_object_t *) = func; return activate(obj); } static void generic_stop(void *func, va_list ap) { vlc_object_t *obj = va_arg(ap, vlc_object_t *); void (*deactivate)(vlc_object_t *) = func; deactivate(obj); } #undef module_need module_t *module_need(vlc_object_t *obj, const char *cap, const char *name, bool strict) { return vlc_module_load(obj, cap, name, strict, generic_start, obj); } #undef module_unneed void module_unneed(vlc_object_t *obj, module_t *module) { msg_Dbg(obj, "removing module \"%s\"", module_get_object(module)); vlc_module_unload(obj, module, generic_stop, obj); } /** * Get a pointer to a module_t given it's name. * * \param name the name of the module * \return a pointer to the module or NULL in case of a failure */ module_t *module_find (const char *name) { size_t count; module_t **list = module_list_get (&count); assert (name != NULL); for (size_t i = 0; i < count; i++) { module_t *module = list[i]; if (unlikely(module->i_shortcuts == 0)) continue; if (!strcmp (module->pp_shortcuts[0], name)) { module_list_free (list); return module; } } module_list_free (list); return NULL; } /** * Tell if a module exists * * \param psz_name th name of the module * \return TRUE if the module exists */ bool module_exists (const char * psz_name) { return module_find (psz_name) != NULL; } /** * Get the configuration of a module * * \param module the module * \param psize the size of the configuration returned * \return the configuration as an array */ module_config_t *module_config_get( const module_t *module, unsigned *restrict psize ) { const vlc_plugin_t *plugin = module->plugin; if (plugin->module != module) { /* For backward compatibility, pretend non-first modules have no * configuration items. */ *psize = 0; return NULL; } unsigned i,j; size_t size = plugin->conf.size; module_config_t *config = vlc_alloc( size, sizeof( *config ) ); assert( psize != NULL ); *psize = 0; if( !config ) return NULL; for( i = 0, j = 0; i < size; i++ ) { const module_config_t *item = plugin->conf.items + i; if( item->b_internal /* internal option */ || item->b_removed /* removed option */ ) continue; memcpy( config + j, item, sizeof( *config ) ); j++; } *psize = j; return config; } /** * Release the configuration * * \param the configuration * \return nothing */ void module_config_free( module_config_t *config ) { free( config ); }
26.088608
86
0.599062
[ "object" ]
58bb65f9c3409f8328ee6ed7aad1f3f7e601561c
3,162
h
C
cued-rnnlm.v1.1.evaloncpu/rnnlm.h
JJorgeDSIC/CUED-RNNLM-Toolkit-Adapted
109937a2dc275403108271f1ff1735104eeee47a
[ "BSD-3-Clause" ]
1
2021-11-27T10:31:01.000Z
2021-11-27T10:31:01.000Z
cued-rnnlm.v1.1.evaloncpu/rnnlm.h
JJorgeDSIC/CUED-RNNLM-Toolkit-Adapted
109937a2dc275403108271f1ff1735104eeee47a
[ "BSD-3-Clause" ]
null
null
null
cued-rnnlm.v1.1.evaloncpu/rnnlm.h
JJorgeDSIC/CUED-RNNLM-Toolkit-Adapted
109937a2dc275403108271f1ff1735104eeee47a
[ "BSD-3-Clause" ]
null
null
null
#include "head.h" #include "layer.h" #include "cudamatrix.h" #include "fileops.h" #include "DataType.h" #include <omp.h> #include <random> #include <algorithm> typedef mt19937_64 rng_type; class RNNLM { protected: string inmodelfile, outmodelfile, trainfile, validfile, testfile, inputwlist, outputwlist, nglmstfile, sampletextfile, feafile, nceunigramfile, uglmfile; vector<int> layersizes; map<string, int> inputmap, outputmap; vector<string> inputvec, outputvec, ooswordsvec, layertypes; vector<float> ooswordsprob; vector<vector<matrix *> > neu_ac_chunk; vector<layer *> layers; vector<matrix *> neu_ac, neu_er; auto_timer timer; // used for cuedrnnlm v1.1 int succwindowlength, num_sulayer, succmergelayer; int *succwords; vector<int> succlayersizes; vector<layer *> layer1_succ, layers_succ; vector<matrix *> neu_ac_succ, neu_ac1_succ; float logp, llogp, gradient_cutoff, l2reg, alpha, momentum, min_improvement, nwordspersec, lognorm, vrpenalty, lognorm_output, log_num_noise, lognormconst, lambda, version, diaginit, dropoutrate, lmscale, ip, smoothvalue; double trnlognorm_mean, lognorm_mean, lognorm_var; int rand_seed, deviceid, minibatch, chunksize, debug, iter, lrtunemode, traincritmode, inputlayersize, outputlayersize, num_layer, wordcn, trainwordcnt, validwordcnt, independent, inStartindex, inOOSindex, cachesize, outEndindex, outOOSindex, k, counter, mbcntiter, mbcnt, fullvocsize, prevword, curword, num_oosword, nsample, nthread; int *host_prevwords, *host_curwords, *mbfeaindices; bool alpha_divide, binformat, flag_nceunigram, linearintplt; auto_timer timer_sampler, timer_forward, timer_output, timer_backprop, timer_hidden; public: RNNLM(string inmodelfile_1, string inputwlist_1, string outputwlist_1, int fvocsize, bool bformat, int debuglevel, int mbsize=1, int cksize=1, int dev=0); ~RNNLM(); bool calppl (string testfilename, float lambda, string nglmfile); bool calnbest (string testfilename, float lambda, string nglmfile); float host_forward (int prevword, int curword); void InitVariables (); void LoadRNNLM(string modelname); void LoadTextRNNLM_new(string modelname); void ReadWordlist (string inputlist, string outputlist); void printPPLInfo (); void init(); void setNthread (int n) {nthread = n;} void setLmscale (float v) {lmscale = v;} void setIp (float v) {ip = v;} void setSmoothValue (float v) { smoothvalue = v; layers[num_layer-1]->setSmoothValue (smoothvalue); } void setLinearIntplt (bool flag){linearintplt = flag;} void setFullVocsize (int n); void setIndependentmode (int v); void allocRNNMem (bool flag_alloclayers=true); void allocWordMem (); void host_HandleSentEnd_fw (); void initHiddenAc (); // functions for using additional feature file in input layer void ReadFeaFile (string str) { feafile = str; layers[0]->ReadFeaFile (feafile); } };
34.369565
158
0.697343
[ "vector" ]