hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | 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 270 | max_issues_repo_name stringlengths 5 116 | 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 270 | max_forks_repo_name stringlengths 5 116 | 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 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
36854349bc4140b9c13391a9bc81af1359dc0491 | 3,102 | cpp | C++ | code/steps/source/model/sg_models/sg_model_test.cpp | changgang/steps | 9b8ea474581885129d1c1a1c3ad40bc8058a7e0a | [
"MIT"
] | 29 | 2019-10-30T07:04:10.000Z | 2022-02-22T06:34:32.000Z | code/steps/source/model/sg_models/sg_model_test.cpp | changgang/steps | 9b8ea474581885129d1c1a1c3ad40bc8058a7e0a | [
"MIT"
] | 1 | 2021-09-25T15:29:59.000Z | 2022-01-05T14:04:18.000Z | code/steps/source/model/sg_models/sg_model_test.cpp | changgang/steps | 9b8ea474581885129d1c1a1c3ad40bc8058a7e0a | [
"MIT"
] | 8 | 2019-12-20T16:13:46.000Z | 2022-03-20T14:58:23.000Z | #include "header/basic/test_macro.h"
#include "header/model/sg_models/sg_model_test.h"
#include "header/basic/utility.h"
#include "header/steps_namespace.h"
#include <cstdlib>
#include <cstring>
#include <istream>
#include <iostream>
#include <cstdio>
#include <cmath>
#ifdef ENABLE_STEPS_TEST
using namespace std;
SG_MODEL_TEST::SG_MODEL_TEST()
{
;
}
void SG_MODEL_TEST::setup()
{
POWER_SYSTEM_DATABASE& psdb = default_toolkit.get_power_system_database();
psdb.clear();
psdb.set_allowed_max_bus_number(100);
psdb.set_system_base_power_in_MVA(100.0);
BUS bus(default_toolkit);
bus.set_bus_number(1);
bus.set_bus_type(PV_TYPE);
bus.set_base_voltage_in_kV(21.0);
bus.set_base_frequency_in_Hz(50.0);
bus.set_positive_sequence_voltage_in_pu(1.0);
bus.set_positive_sequence_angle_in_rad(0.0);
psdb.append_bus(bus);
GENERATOR generator(default_toolkit);
generator.set_generator_bus(1);
generator.set_identifier("#1");
generator.set_status(true);
generator.set_mbase_in_MVA(200.0);
generator.set_source_impedance_in_pu(complex<double>(0.0, 0.1));
generator.set_p_generation_in_MW(100.0);
generator.set_q_generation_in_MVar(30.0);
psdb.append_generator(generator);
}
void SG_MODEL_TEST::tear_down()
{
POWER_SYSTEM_DATABASE& psdb = default_toolkit.get_power_system_database();
psdb.clear();
}
GENERATOR* SG_MODEL_TEST::get_test_generator()
{
DEVICE_ID did;
did.set_device_type(STEPS_GENERATOR);
TERMINAL terminal;
terminal.append_bus(1);
did.set_device_terminal(terminal);
did.set_device_identifier_index(get_index_of_string("#1"));
POWER_SYSTEM_DATABASE& psdb = default_toolkit.get_power_system_database();
return psdb.get_generator(did);
}
SYNC_GENERATOR_MODEL* SG_MODEL_TEST::get_test_sync_generator_model()
{
GENERATOR* genptr = get_test_generator();
if(genptr!=NULL)
return genptr->get_sync_generator_model();
else
return NULL;
}
EXCITER_MODEL* SG_MODEL_TEST::get_test_exciter_model()
{
GENERATOR* genptr = get_test_generator();
if(genptr!=NULL)
return genptr->get_exciter_model();
else
return NULL;
}
STABILIZER_MODEL* SG_MODEL_TEST::get_test_stabilizer_model()
{
GENERATOR* genptr = get_test_generator();
if(genptr!=NULL)
return genptr->get_stabilizer_model();
else
return NULL;
}
COMPENSATOR_MODEL* SG_MODEL_TEST::get_test_compensator_model()
{
GENERATOR* genptr = get_test_generator();
if(genptr!=NULL)
return genptr->get_compensator_model();
else
return NULL;
}
TURBINE_GOVERNOR_MODEL* SG_MODEL_TEST::get_test_turbine_governor_model()
{
GENERATOR* genptr = get_test_generator();
if(genptr!=NULL)
return genptr->get_turbine_governor_model();
else
return NULL;
}
TURBINE_LOAD_CONTROLLER_MODEL* SG_MODEL_TEST::get_test_turbine_load_controller_model()
{
GENERATOR* genptr = get_test_generator();
if(genptr!=NULL)
return genptr->get_turbine_load_controller_model();
else
return NULL;
}
#endif
| 25.219512 | 86 | 0.731464 | [
"model"
] |
369edd2a64ca07e278d73c46a94be50eaaafbdf1 | 917 | cpp | C++ | #1122 Hamiltonian Cycle.cpp | ZachVec/PAT-Advanced | 52ba5989c095ddbee3c297e82a4b3d0d2e0cd449 | [
"MIT"
] | 1 | 2021-12-26T08:34:47.000Z | 2021-12-26T08:34:47.000Z | #1122 Hamiltonian Cycle.cpp | ZachVec/PAT-Advanced | 52ba5989c095ddbee3c297e82a4b3d0d2e0cd449 | [
"MIT"
] | null | null | null | #1122 Hamiltonian Cycle.cpp | ZachVec/PAT-Advanced | 52ba5989c095ddbee3c297e82a4b3d0d2e0cd449 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int main() {
size_t n, m, k;
if(scanf("%zu%zu", &n, &m) != 2) return 0;
vector<vector<bool>> isConnected(n+1, vector<bool>(n+1, false));
for(size_t i = 0, u, v; i < m && scanf("%zu%zu", &u, &v); ++i) {
isConnected[u][v] = isConnected[v][u] = true;
}
if(!scanf("%zu", &k)) return 0;
for(size_t i = 0, sz, front, back; i < k && scanf("%zu%zu", &sz, &front); ++i) {
bool isHamiltonianCycle = sz == n + 1;
vector<bool> hasVisit(n + 1, false);
for(size_t prev = front; --sz && scanf("%zu", &back); prev = back) {
if(!isHamiltonianCycle) continue;
isHamiltonianCycle = isHamiltonianCycle && !hasVisit[back] && isConnected[prev][back];
hasVisit[back] = true;
}
printf("%s\n", isHamiltonianCycle && front == back ? "YES" : "NO");
}
return 0;
} | 35.269231 | 98 | 0.535442 | [
"vector"
] |
36a0072d482626ee819540e0e3b4ce3a4a26e1f5 | 1,955 | hh | C++ | thirdparty/msgpack.hh | falsycat/kingtaker | e329966eedef6d53a08bd62ae592d862148f525c | [
"WTFPL"
] | 3 | 2022-01-09T15:48:33.000Z | 2022-03-07T12:01:45.000Z | thirdparty/msgpack.hh | falsycat/kingtaker | e329966eedef6d53a08bd62ae592d862148f525c | [
"WTFPL"
] | 25 | 2022-02-13T03:12:10.000Z | 2022-03-31T23:36:22.000Z | thirdparty/msgpack.hh | falsycat/kingtaker | e329966eedef6d53a08bd62ae592d862148f525c | [
"WTFPL"
] | null | null | null | #pragma once
#include <string>
#include <string_view>
#include <type_traits>
#include <imgui.h>
#include <msgpack.hpp>
namespace msgpack {
template <typename T>
inline const object& find(const object_map& map, const T& key, const object& def) noexcept {
for (size_t i = 0; i < map.size; ++i) {
const auto& kv = map.ptr[i];
if constexpr (std::is_same<T, std::string>::value) {
const auto& str = kv.key.via.str;
const auto strv = std::string_view(str.ptr, str.size);
if (kv.key.type == type::STR && key == strv) return kv.val;
} else {
if (kv.key == key) return kv.val;
}
}
return def;
}
template <typename T>
inline object find(const object& map, const T& key, object def) noexcept {
return map.type == type::MAP? find(map.via.map, key, def): def;
}
template <typename T1, typename T2>
inline object find(const object& map, const T1& key, T2 def) noexcept {
return find(map, key, object {def});
}
template <typename T>
inline const object& find(const object& map, const T& key) noexcept {
static const object nil_;
return map.type == type::MAP? find(map.via.map, key, nil_): nil_;
}
template <typename T>
inline T as_if(const object& obj, T def) {
obj.convert_if_not_nil(def);
return def;
}
template <>
inline ImVec2 as_if<ImVec2>(const object& obj, ImVec2 def) {
if (obj.type == msgpack::type::NIL) return def;
if (obj.type != msgpack::type::ARRAY) throw msgpack::type_error();
if (obj.via.array.size != 2) throw msgpack::type_error();
return ImVec2(obj.via.array.ptr[0].as<float>(), obj.via.array.ptr[1].as<float>());
}
MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) {
namespace adaptor {
template <>
struct pack<ImVec2> final {
public:
template <typename Stream>
packer<Stream>& operator()(packer<Stream>& pk, ImVec2 const& v) const {
pk.pack_array(2);
pk.pack(v.x);
pk.pack(v.y);
return pk;
}
};
}} // namespace adaptor
} // namespace msgpack
| 27.535211 | 92 | 0.668542 | [
"object"
] |
36a10888eafe9c58666434974fb0ff73ea2b5318 | 2,029 | cc | C++ | 2021/day12/lib.cc | kfarnung/advent-of-code | 74604578379c518bd7ad959e0088ca55a6986515 | [
"MIT"
] | 1 | 2017-12-11T07:08:52.000Z | 2017-12-11T07:08:52.000Z | 2021/day12/lib.cc | kfarnung/advent-of-code | 74604578379c518bd7ad959e0088ca55a6986515 | [
"MIT"
] | 2 | 2020-12-01T08:16:42.000Z | 2021-05-12T04:54:34.000Z | 2021/day12/lib.cc | kfarnung/advent-of-code | 74604578379c518bd7ad959e0088ca55a6986515 | [
"MIT"
] | null | null | null | #include "lib.h"
#include <common/input_parser.h>
#include <deque>
#include <map>
#include <set>
namespace
{
using Graph = std::map<std::string, std::vector<std::string>>;
Graph parse_graph(const std::vector<std::string> &input)
{
Graph graph;
for (const auto &line : input)
{
auto parts = common::splitstr(line, '-');
if (parts[1] != "start" && parts[0] != "end")
{
graph[parts[0]].push_back(parts[1]);
}
if (parts[0] != "start" && parts[1] != "end")
{
graph[parts[1]].push_back(parts[0]);
}
}
return graph;
}
int64_t count_paths(
const Graph &graph,
const bool allow_second_visit,
const std::string ¤t,
const std::set<std::string> &visited,
const bool used_second_visit)
{
if (current == "end")
{
return 1;
}
std::set<std::string> next_visited(visited);
if (!std::isupper(current[0]))
{
next_visited.insert(current);
}
int64_t path_count = 0;
for (const auto &neighbor : graph.at(current))
{
auto already_visited = visited.find(neighbor) != visited.end();
if (already_visited && (!allow_second_visit || used_second_visit))
{
continue;
}
path_count += count_paths(
graph,
allow_second_visit,
neighbor,
next_visited,
used_second_visit || already_visited);
}
return path_count;
}
}
int64_t day12::run_part1(const std::vector<std::string> &input)
{
auto graph = parse_graph(input);
return count_paths(graph, false, "start", {}, false);
}
int64_t day12::run_part2(const std::vector<std::string> &input)
{
auto graph = parse_graph(input);
return count_paths(graph, true, "start", {}, false);
}
| 23.321839 | 78 | 0.519961 | [
"vector"
] |
36a49b6f12f544a21d04f203c0fdaed8e598cdee | 3,800 | cpp | C++ | src/search_engine/relja_retrival/external/KMCode_relja/descriptor/JetLocalDirectional.cpp | kaloyan13/vise2 | 833a8510c7cbac3cbb8ac4569fd51448906e62f3 | [
"BSD-2-Clause"
] | 43 | 2017-07-06T23:44:39.000Z | 2022-03-25T06:53:29.000Z | src/search_engine/relja_retrival/external/KMCode_relja/descriptor/JetLocalDirectional.cpp | kaloyan13/vise2 | 833a8510c7cbac3cbb8ac4569fd51448906e62f3 | [
"BSD-2-Clause"
] | 2 | 2018-11-09T03:52:14.000Z | 2020-03-25T14:08:33.000Z | src/search_engine/relja_retrival/external/KMCode_relja/descriptor/JetLocalDirectional.cpp | kaloyan13/vise2 | 833a8510c7cbac3cbb8ac4569fd51448906e62f3 | [
"BSD-2-Clause"
] | 9 | 2017-07-27T10:55:55.000Z | 2020-12-15T13:42:43.000Z | #include "jetLocalDirectional.h"
void JetLocalDirectional::computeComponents(DARY *img_in){
((JetLocal*)this)->computeComponents(img_in);
if (!isOK())return;
double a_tmp;
double sina=0,cosa=0;
double *val = new double[size];
int inv=0;
val[inv++]=vec[0];
/*1st derivative*/
if(order>=1){
sina=sin(angle);cosa=cos(angle);
val[inv++]=vec[1]*cosa+vec[2]*sina;
a_tmp=(M_PI/2)+angle;
sina=sin(a_tmp);cosa=cos(a_tmp);
val[inv++]=vec[1]*cosa+vec[2]*sina; //equals ZERO if angle==grad direction
}
/*2nd derivative*/
if(order>=2){
val[inv++]=vec[3]*cosa*cosa+2*vec[4]*sina*cosa+vec[5]*sina*sina;
a_tmp=(M_PI/3)+angle;
sina=sin(a_tmp);cosa=cos(a_tmp);
val[inv++]=vec[3]*cosa*cosa+2*vec[4]*sina*cosa+vec[5]*sina*sina;
a_tmp=2*(M_PI/3)+angle;
sina=sin(a_tmp);cosa=cos(a_tmp);
val[inv++]=vec[3]*cosa*cosa+2*vec[4]*sina*cosa+vec[5]*sina*sina;
}
/*3d derivative */
if(order>=3){
sina=sin(angle);cosa=cos(angle);
val[inv++]=vec[6]*cosa*cosa*cosa+3*vec[7]*cosa*cosa*sina+
3*vec[8]*sina*sina*cosa+vec[9]*sina*sina*sina;
a_tmp=(M_PI/4)+angle;
sina=sin(a_tmp);cosa=cos(a_tmp);
val[inv++]=vec[6]*cosa*cosa*cosa+3*vec[7]*cosa*cosa*sina+
3*vec[8]*sina*sina*cosa+vec[9]*sina*sina*sina;
a_tmp=2*(M_PI/4)+angle;
sina=sin(a_tmp);cosa=cos(a_tmp);
val[inv++]=vec[6]*cosa*cosa*cosa+3*vec[7]*cosa*cosa*sina+
3*vec[8]*sina*sina*cosa+vec[9]*sina*sina*sina;
a_tmp=3*(M_PI/4)+angle;
sina=sin(a_tmp);cosa=cos(a_tmp);
val[inv++]=vec[6]*cosa*cosa*cosa+3*vec[7]*cosa*cosa*sina+
3*vec[8]*sina*sina*cosa+vec[9]*sina*sina*sina;
}
/*4th derivative */
if(order>=4){
sina=sin(angle);cosa=cos(angle);
val[inv++]=vec[10]*cosa*cosa*cosa*cosa+4*vec[11]*cosa*cosa*cosa*sina+
6*vec[12]*cosa*cosa*sina*sina+4*vec[13]*cosa*sina*sina*sina+vec[14]*sina*sina*sina*sina;
a_tmp=(M_PI/5)+angle;
sina=sin(a_tmp);cosa=cos(a_tmp);
val[inv++]=vec[10]*cosa*cosa*cosa*cosa+4*vec[11]*cosa*cosa*cosa*sina+
6*vec[12]*cosa*cosa*sina*sina+4*vec[13]*cosa*sina*sina*sina+vec[14]*sina*sina*sina*sina;
a_tmp=2*(M_PI/5)+angle;
sina=sin(a_tmp);cosa=cos(a_tmp);
val[inv++]=vec[10]*cosa*cosa*cosa*cosa+4*vec[11]*cosa*cosa*cosa*sina+
6*vec[12]*cosa*cosa*sina*sina+4*vec[13]*cosa*sina*sina*sina+vec[14]*sina*sina*sina*sina;
a_tmp=3*(M_PI/5)+angle;
sina=sin(a_tmp);cosa=cos(a_tmp);
val[inv++]=vec[10]*cosa*cosa*cosa*cosa+4*vec[11]*cosa*cosa*cosa*sina+
6*vec[12]*cosa*cosa*sina*sina+4*vec[13]*cosa*sina*sina*sina+vec[14]*sina*sina*sina*sina;
a_tmp=4*(M_PI/5)+angle;
sina=sin(a_tmp);cosa=cos(a_tmp);
val[inv++]=vec[10]*cosa*cosa*cosa*cosa+4*vec[11]*cosa*cosa*cosa*sina+
6*vec[12]*cosa*cosa*sina*sina+4*vec[13]*cosa*sina*sina*sina+vec[14]*sina*sina*sina*sina;
//cout << a_tmp << " sin " << sina << " cos " << cosa << endl;
//getchar();
}
allocVec(inv);
for(int i=0;i<size;i++)vec[i]=val[i];
delete[] val;
state=1;
}
void computeJLDDescriptors(DARY *image, vector<CornerDescriptor *> &desc){
JetLocalDirectional * ds=new JetLocalDirectional();
for(unsigned int c=0;c<desc.size();c++){
cout << "\rcompute "<< c<< " "<< flush;
ds->copy(desc[c]);
ds->computeComponents(image);
//ds->changeBase(ds->getSize(),baseJLD);
desc[c]->copy((CornerDescriptor*)ds);
}
for(unsigned int c=0;c<desc.size();c++){
if(!desc[c]->isOK()){
desc.erase((std::vector<CornerDescriptor*>::iterator)&desc[c]);
c--;
}
}
cout<<endl;
}
| 39.175258 | 98 | 0.582632 | [
"vector",
"3d"
] |
36a605ab9e182c1f398161415ec79f40acd37ee7 | 3,486 | hpp | C++ | include/boost/hana/record/mcd.hpp | rbock/hana | 2b76377f91a5ebe037dea444e4eaabba6498d3a8 | [
"BSL-1.0"
] | 2 | 2015-05-07T14:29:13.000Z | 2015-07-04T10:59:46.000Z | include/boost/hana/record/mcd.hpp | rbock/hana | 2b76377f91a5ebe037dea444e4eaabba6498d3a8 | [
"BSL-1.0"
] | null | null | null | include/boost/hana/record/mcd.hpp | rbock/hana | 2b76377f91a5ebe037dea444e4eaabba6498d3a8 | [
"BSL-1.0"
] | null | null | null | /*!
@file
Defines `boost::hana::Record::mcd`.
@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_RECORD_MCD_HPP
#define BOOST_HANA_RECORD_MCD_HPP
#include <boost/hana/record/record.hpp>
#include <boost/hana/comparable/equal_mcd.hpp>
#include <boost/hana/core/datatype.hpp>
#include <boost/hana/core/is_a.hpp>
#include <boost/hana/detail/std/type_traits.hpp>
#include <boost/hana/foldable/mcd.hpp>
#include <boost/hana/map.hpp>
#include <boost/hana/product/product.hpp>
#include <boost/hana/searchable/mcd.hpp>
namespace boost { namespace hana {
//! Minimal complete definition: `members`
struct Record::mcd { };
//! Two `Records` of the same data type `R` are equal if and only if
//! all their members are equal. The members are compared in the
//! same order as they appear in `members<R>`.
template <typename R>
struct Comparable::instance<R, R, when<is_a<Record, R>()>>
: Comparable::equal_mcd
{
template <typename X, typename Y>
static constexpr auto equal_impl(X x, Y y) {
return all(members<R>, [=](auto k_f) {
return equal(second(k_f)(x), second(k_f)(y));
});
}
};
//! Folding a `Record` `R` is equivalent to folding a list of its members,
//! in the same order as they appear in `members<R>`.
template <typename R>
struct Foldable::instance<R, when<is_a<Record, R>()>>
: Foldable::mcd
{
template <typename X, typename S, typename F>
static constexpr auto foldl_impl(X x, S s, F f) {
return foldl(members<R>, s, [=](auto s, auto k_f) {
return f(s, second(k_f)(x));
});
}
template <typename X, typename S, typename F>
static constexpr auto foldr_impl(X x, S s, F f) {
return foldr(members<R>, s, [=](auto k_f, auto s) {
return f(second(k_f)(x), s);
});
}
};
//! Searching a `Record` `r` is equivalent to searching `to<Map>(r)`.
template <typename R>
struct Searchable::instance<R, when<is_a<Record, R>()>>
: Searchable::mcd
{
template <typename X, typename Pred>
static constexpr auto find_impl(X x, Pred pred) {
return fmap(
[=](auto k_f) { return second(k_f)(x); },
find(members<R>, [=](auto k_f) { return pred(first(k_f)); })
);
}
template <typename X, typename Pred>
static constexpr auto any_impl(X x, Pred pred) {
return any(members<R>, [=](auto k_f) { return pred(first(k_f)); });
}
};
//! Converting a `Record` `R` to a `Map` is equivalent to converting its
//! `members<R>` to a `Map`, except the values are replaced by the actual
//! members of the object instead of accessors.
template <typename R>
struct convert<Map, R, detail::std::enable_if_t<is_a<Record, R>()>> {
template <typename X>
static constexpr auto apply(X x) {
return to<Map>(fmap(
[=](auto k_f) {
using P = datatype_t<decltype(k_f)>;
return make_product<P>(first(k_f), second(k_f)(x));
},
members<R>
));
}
};
}} // end namespace boost::hana
#endif // !BOOST_HANA_RECORD_MCD_HPP
| 33.84466 | 79 | 0.587206 | [
"object"
] |
36ad50a31d1c34f8b94ed7c9e8fa87a316fe9923 | 1,065 | cpp | C++ | Challenge-2021-06/26_count_of_smaller_numbers_after_self.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | Challenge-2021-06/26_count_of_smaller_numbers_after_self.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | Challenge-2021-06/26_count_of_smaller_numbers_after_self.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | #include "../header.h"
class FenwickTree {
private:
vector<int> _sums;
int lowbit(int x) {
return x & (-x);
}
public:
FenwickTree(int n): _sums(n + 1, 0) {}
void update(int i, int delta) {
while (i < _sums.size()) {
_sums[i] += delta;
i += lowbit(i);
}
}
int query(int i) {
int sum = 0;
while (i > 0) {
sum += _sums[i];
i -= lowbit(i);
}
return sum;
}
};
class Solution {
public:
vector<int> countSmaller(vector<int>& nums) {
set<int> sorted(nums.begin(), nums.end());
unordered_map<int, int> ranks;
int rank = 0;
for (auto const& num: sorted) {
ranks[num] = ++rank;
}
vector<int> ans;
FenwickTree tree(ranks.size());
for (int i = nums.size() - 1; i >= 0; --i) {
ans.push_back(tree.query(ranks[nums[i]] - 1));
tree.update(ranks[nums[i]], 1);
}
reverse(ans.begin(), ans.end());
return ans;
}
}; | 22.659574 | 58 | 0.462911 | [
"vector"
] |
a5e314e3af018e5fdc48a5895c0e9677ebceab4f | 21,929 | hpp | C++ | phylanx/plugins/matrixops/argminmax_impl.hpp | frzfrsfra4/phylanx | 001fe7081f3a24e56157cdb21b2d126b8953ff5d | [
"BSL-1.0"
] | 1 | 2019-08-17T21:19:57.000Z | 2019-08-17T21:19:57.000Z | phylanx/plugins/matrixops/argminmax_impl.hpp | frzfrsfra4/phylanx | 001fe7081f3a24e56157cdb21b2d126b8953ff5d | [
"BSL-1.0"
] | null | null | null | phylanx/plugins/matrixops/argminmax_impl.hpp | frzfrsfra4/phylanx | 001fe7081f3a24e56157cdb21b2d126b8953ff5d | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2018 Parsa Amini
// Copyright (c) 2018-2019 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(PHYLANX_PRIMITIVES_ARGMINMAX_IMPL_2019_01_19_1130AM)
#define PHYLANX_PRIMITIVES_ARGMINMAX_IMPL_2019_01_19_1130AM
#include <phylanx/config.hpp>
#include <phylanx/execution_tree/primitives/node_data_helpers.hpp>
#include <phylanx/ir/node_data.hpp>
#include <phylanx/plugins/matrixops/argminmax.hpp>
#include <phylanx/util/matrix_iterators.hpp>
#include <phylanx/util/tensor_iterators.hpp>
#include <hpx/include/lcos.hpp>
#include <hpx/include/naming.hpp>
#include <hpx/include/util.hpp>
#include <hpx/throw_exception.hpp>
#include <hpx/util/iterator_facade.hpp>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <blaze/Math.h>
#if defined(PHYLANX_HAVE_BLAZE_TENSOR)
#include <blaze_tensor/Math.h>
#endif
///////////////////////////////////////////////////////////////////////////////
namespace phylanx { namespace execution_tree { namespace primitives
{
///////////////////////////////////////////////////////////////////////////
template <typename Op, typename Derived>
argminmax<Op, Derived>::argminmax(primitive_arguments_type&& operands,
std::string const& name, std::string const& codename)
: primitive_component_base(std::move(operands), name, codename)
{}
///////////////////////////////////////////////////////////////////////////
template <typename Op, typename Derived>
template <typename T>
primitive_argument_type argminmax<Op, Derived>::argminmax0d(
std::size_t numargs, ir::node_data<T>&& arg, std::int64_t axis) const
{
// `axis` is optional
if (numargs == 2)
{
// `axis` can only be -1 or 0
if (axis < -1 || axis > 0)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::primitives::"
"argminmax<Op, Derived>::argminmax0d",
generate_error_message(
"operand axis can only between -1 and 0 for "
"an a operand that is 0d"));
}
}
return primitive_argument_type(std::int64_t(0));
}
template <typename Op, typename Derived>
primitive_argument_type argminmax<Op, Derived>::argminmax0d(
primitive_arguments_type&& args) const
{
std::int64_t axis = -1;
std::size_t numargs = args.size();
if (numargs == 2)
{
axis = extract_scalar_integer_value(args[1], name_, codename_);
}
switch (extract_common_type(args[0]))
{
case node_data_type_bool:
return argminmax0d(numargs, extract_boolean_value_strict(
std::move(args[0]), name_, codename_), axis);
case node_data_type_int64:
return argminmax0d(numargs, extract_integer_value_strict(
std::move(args[0]), name_, codename_), axis);
case node_data_type_double:
return argminmax0d(numargs, extract_numeric_value_strict(
std::move(args[0]), name_, codename_), axis);
case node_data_type_unknown:
return argminmax0d(numargs, extract_numeric_value(
std::move(args[0]), name_, codename_), axis);
default:
break;
}
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::primitives::"
"argminmax<Op, Derived>::argminmax0d",
generate_error_message(
"the arange primitive requires for all arguments to "
"be numeric data types"));
}
///////////////////////////////////////////////////////////////////////////
template <typename Op, typename Derived>
template <typename T>
primitive_argument_type argminmax<Op, Derived>::argminmax1d(
std::size_t numargs, ir::node_data<T>&& arg, std::int64_t axis) const
{
// `axis` is optional
if (numargs == 2)
{
// `axis` can only be -1 or 0
if (axis < -1 || axis > 0)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::primitives::"
"argminmax<Op, Derived>::argminmax1d",
generate_error_message(
"operand axis can only between -1 and 0 for "
"an a operand that is 1d"));
}
}
// a should not be empty
auto a = arg.vector();
if (a.size() == 0)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"argminmax<Op, Derived>::argminmax1d",
generate_error_message(
"attempt to get argminmax of an empty sequence"));
}
// Find the maximum value among the elements
auto max_it = Op{}(a.begin(), a.end());
// Return min/max's index
return primitive_argument_type(
(std::int64_t)(std::distance(a.begin(), max_it)));
}
template <typename Op, typename Derived>
primitive_argument_type argminmax<Op, Derived>::argminmax1d(
primitive_arguments_type&& args) const
{
std::int64_t axis = -1;
std::size_t numargs = args.size();
if (numargs == 2)
{
axis = extract_scalar_integer_value(args[1], name_, codename_);
}
switch (extract_common_type(args[0]))
{
case node_data_type_bool:
return argminmax1d(numargs, extract_boolean_value_strict(
std::move(args[0]), name_, codename_), axis);
case node_data_type_int64:
return argminmax1d(numargs, extract_integer_value_strict(
std::move(args[0]), name_, codename_), axis);
case node_data_type_double:
return argminmax1d(numargs, extract_numeric_value_strict(
std::move(args[0]), name_, codename_), axis);
case node_data_type_unknown:
return argminmax1d(numargs, extract_numeric_value(
std::move(args[0]), name_, codename_), axis);
default:
break;
}
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::primitives::"
"argminmax<Op, Derived>::argminmax1d",
generate_error_message(
"the arange primitive requires for all arguments to "
"be numeric data types"));
}
///////////////////////////////////////////////////////////////////////////
template <typename Op, typename Derived>
template <typename T>
primitive_argument_type argminmax<Op, Derived>::argminmax2d_flatten(
ir::node_data<T>&& arg) const
{
using phylanx::util::matrix_row_iterator;
auto a = arg.matrix();
const matrix_row_iterator<decltype(a)> a_begin(a);
const matrix_row_iterator<decltype(a)> a_end(a, a.rows());
T global_minmax = Op::template initial<T>();
std::size_t global_index = 0ul;
std::size_t passed_rows = 0ul;
for (auto it = a_begin; it != a_end; ++it, ++passed_rows)
{
auto local_minmax = Op{}(it->begin(), it->end());
auto local_minmax_val = *local_minmax;
if (Op::compare(local_minmax_val, global_minmax))
{
global_minmax = local_minmax_val;
global_index = std::distance(it->begin(), local_minmax) +
passed_rows * it->size();
}
}
return primitive_argument_type(std::int64_t(global_index));
}
template <typename Op, typename Derived>
template <typename T>
primitive_argument_type argminmax<Op, Derived>::argminmax2d_0_axis(
ir::node_data<T>&& arg) const
{
auto a = arg.matrix();
using phylanx::util::matrix_column_iterator;
matrix_column_iterator<decltype(a)> a_begin(a);
matrix_column_iterator<decltype(a)> a_end(a, a.columns());
blaze::DynamicVector<std::int64_t> result(a.columns());
auto result_it = result.begin();
for (auto it = a_begin; it != a_end; ++it, ++result_it)
{
auto local_minmax = Op{}(it->begin(), it->end());
*result_it = std::distance(it->begin(), local_minmax);
}
return primitive_argument_type{std::move(result)};
}
template <typename Op, typename Derived>
template <typename T>
primitive_argument_type argminmax<Op, Derived>::argminmax2d_1_axis(
ir::node_data<T>&& arg) const
{
auto a = arg.matrix();
using phylanx::util::matrix_row_iterator;
matrix_row_iterator<decltype(a)> a_begin(a);
matrix_row_iterator<decltype(a)> a_end(a, a.rows());
blaze::DynamicVector<std::int64_t> result(a.rows());
auto result_it = result.begin();
for (auto it = a_begin; it != a_end; ++it, ++result_it)
{
auto local_minmax = Op{}(it->begin(), it->end());
*result_it = std::distance(it->begin(), local_minmax);
}
return primitive_argument_type{std::move(result)};
}
template <typename Op, typename Derived>
template <typename T>
primitive_argument_type argminmax<Op, Derived>::argminmax2d(
std::size_t numargs, ir::node_data<T>&& arg, std::int64_t axis) const
{
// a should not be empty
auto m = arg.matrix();
if (m.rows() == 0 || m.columns() == 0)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"argminmax<Op, Derived>::argminmax2d",
generate_error_message(
"attempt to get argminmax of an empty sequence"));
}
// `axis` is optional
if (numargs == 1)
{
// Option 1: Flatten and find min/max
return argminmax2d_flatten(std::move(arg));
}
// `axis` can only be -2, -1, 0, or 1
if (axis < -2 || axis > 1)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"argminmax<Op, Derived>::argminmax2d",
generate_error_message(
"operand axis can only between -2 and 1 for an an "
"operand that is 2d"));
}
switch (axis)
{
// Option 2: Find min/max among rows
case -2: HPX_FALLTHROUGH;
case 0:
return argminmax2d_0_axis(std::move(arg));
// Option 3: Find min/max among columns
case -1: HPX_FALLTHROUGH;
case 1:
return argminmax2d_1_axis(std::move(arg));
default:
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"argminmax<Op, Derived>::argminmax2d",
generate_error_message(
"operand has an invalid value for the axis parameter"));
}
}
template <typename Op, typename Derived>
primitive_argument_type argminmax<Op, Derived>::argminmax2d(
primitive_arguments_type&& args) const
{
std::int64_t axis = -1;
std::size_t numargs = args.size();
if (numargs == 2)
{
axis = extract_scalar_integer_value(args[1], name_, codename_);
}
switch (extract_common_type(args[0]))
{
case node_data_type_bool:
return argminmax2d(numargs, extract_boolean_value_strict(
std::move(args[0]), name_, codename_), axis);
case node_data_type_int64:
return argminmax2d(numargs, extract_integer_value_strict(
std::move(args[0]), name_, codename_), axis);
case node_data_type_double:
return argminmax2d(numargs, extract_numeric_value_strict(
std::move(args[0]), name_, codename_), axis);
case node_data_type_unknown:
return argminmax2d(numargs, extract_numeric_value(
std::move(args[0]), name_, codename_), axis);
default:
break;
}
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::primitives::"
"argminmax<Op, Derived>::argminmax2d",
generate_error_message(
"the arange primitive requires for all arguments to "
"be numeric data types"));
}
#if defined(PHYLANX_HAVE_BLAZE_TENSOR)
template <typename Op, typename Derived>
template <typename T>
primitive_argument_type argminmax<Op, Derived>::argminmax3d_flatten(
ir::node_data<T>&& arg) const
{
using phylanx::util::matrix_row_iterator;
auto a = arg.tensor();
T global_minmax = Op::template initial<T>();
std::size_t global_index = 0ul;
std::size_t passed_pages = 0ul;
std::size_t rows = blaze::rows(a);
std::size_t columns = blaze::columns(a);
for (std::size_t page = 0; page != blaze::pages(a); ++page, ++passed_pages)
{
auto ps = blaze::pageslice(a, page);
matrix_row_iterator<decltype(ps)> const a_begin(ps);
matrix_row_iterator<decltype(ps)> const a_end(ps, rows);
std::size_t passed_rows = 0ul;
for (auto it = a_begin; it != a_end; ++it, ++passed_rows)
{
auto local_minmax = Op{}(it->begin(), it->end());
auto local_minmax_val = *local_minmax;
if (Op::compare(local_minmax_val, global_minmax))
{
global_minmax = local_minmax_val;
global_index = std::distance(it->begin(), local_minmax) +
passed_pages * rows + passed_rows * columns;
}
}
}
return primitive_argument_type(std::int64_t(global_index));
}
template <typename Op, typename Derived>
template <typename T>
primitive_argument_type argminmax<Op, Derived>::argminmax3d_0_axis(
ir::node_data<T>&& arg) const
{
auto t = arg.tensor();
blaze::DynamicMatrix<std::int64_t> result(t.rows(), t.columns());
for (std::size_t i = 0; i != t.rows(); ++i)
{
auto slice = blaze::rowslice(t, i);
for (std::size_t j = 0; j != t.columns(); ++j)
{
auto row = blaze::row(slice, j);
result(i, j) =
std::distance(row.begin(), Op{}(row.begin(), row.end()));
}
}
return primitive_argument_type{std::move(result)};
}
template <typename Op, typename Derived>
template <typename T>
primitive_argument_type argminmax<Op, Derived>::argminmax3d_1_axis(
ir::node_data<T>&& arg) const
{
auto t = arg.tensor();
blaze::DynamicMatrix<std::int64_t> result(t.pages(), t.columns());
for (std::size_t k = 0; k != t.pages(); ++k)
{
auto slice = blaze::pageslice(t, k);
for (std::size_t j = 0; j != t.columns(); ++j)
{
auto col = blaze::column(slice, j);
result(k, j) =
std::distance(col.begin(), Op{}(col.begin(), col.end()));
}
}
return primitive_argument_type{std::move(result)};
}
template <typename Op, typename Derived>
template <typename T>
primitive_argument_type argminmax<Op, Derived>::argminmax3d_2_axis(
ir::node_data<T>&& arg) const
{
auto t = arg.tensor();
blaze::DynamicMatrix<std::int64_t> result(t.pages(), t.rows());
for (std::size_t k = 0; k != t.pages(); ++k)
{
auto slice = blaze::pageslice(t, k);
for (std::size_t i = 0; i != t.rows(); ++i)
{
auto row = blaze::row(slice, i);
result(k, i) =
std::distance(row.begin(), Op{}(row.begin(), row.end()));
}
}
return primitive_argument_type{std::move(result)};
}
template <typename Op, typename Derived>
template <typename T>
primitive_argument_type argminmax<Op, Derived>::argminmax3d(
std::size_t numargs, ir::node_data<T>&& arg, std::int64_t axis) const
{
// a should not be empty
auto t = arg.tensor();
if (t.pages() == 0 || t.rows() == 0 || t.columns() == 0)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"argminmax<Op, Derived>::argminmax3d",
generate_error_message(
"attempt to get argminmax of an empty sequence"));
}
// `axis` is optional
if (numargs == 1)
{
// Option 1: Flatten and find min/max
return argminmax3d_flatten(std::move(arg));
}
// `axis` can only be -3, -2, -1, 0, 1, or 2
if (axis < -3 || axis > 2)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"argminmax<Op, Derived>::argminmax3d",
generate_error_message(
"operand axis can only between -3 and 2 for an an "
"operand that is 3d"));
}
switch (axis)
{
// Option 1: Find min/max among pages
case -3: HPX_FALLTHROUGH;
case 0:
return argminmax3d_0_axis(std::move(arg));
// Option 2: Find min/max among rows
case -2: HPX_FALLTHROUGH;
case 1:
return argminmax3d_1_axis(std::move(arg));
// Option 3: Find min/max among columns
case -1: HPX_FALLTHROUGH;
case 2:
return argminmax3d_2_axis(std::move(arg));
default:
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"argminmax<Op, Derived>::argminmax3d",
generate_error_message(
"operand has an invalid value for the axis parameter"));
}
}
template <typename Op, typename Derived>
primitive_argument_type argminmax<Op, Derived>::argminmax3d(
primitive_arguments_type&& args) const
{
std::int64_t axis = -1;
std::size_t numargs = args.size();
if (numargs == 2)
{
axis = extract_scalar_integer_value(args[1], name_, codename_);
}
switch (extract_common_type(args[0]))
{
case node_data_type_bool:
return argminmax3d(numargs, extract_boolean_value_strict(
std::move(args[0]), name_, codename_), axis);
case node_data_type_int64:
return argminmax3d(numargs, extract_integer_value_strict(
std::move(args[0]), name_, codename_), axis);
case node_data_type_double:
return argminmax3d(numargs, extract_numeric_value_strict(
std::move(args[0]), name_, codename_), axis);
case node_data_type_unknown:
return argminmax3d(numargs, extract_numeric_value(
std::move(args[0]), name_, codename_), axis);
default:
break;
}
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::primitives::"
"argminmax<Op, Derived>::argminmax3d",
generate_error_message(
"the arange primitive requires for all arguments to "
"be numeric data types"));
}
#endif
///////////////////////////////////////////////////////////////////////////
template <typename Op, typename Derived>
hpx::future<primitive_argument_type> argminmax<Op, Derived>::eval(
primitive_arguments_type const& operands,
primitive_arguments_type const& args, eval_context ctx) const
{
if (operands.empty() || operands.size() > 2)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"argminmax<Op, Derived>::eval",
generate_error_message(
"the argminmax primitive requires exactly one or "
"two operands"));
}
for (auto const& i : operands)
{
if (!valid(i))
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"argminmax<Op, Derived>::eval",
generate_error_message(
"the argminmax primitive requires that the "
"arguments given by the operands array are valid"));
}
}
auto this_ = this->shared_from_this();
return hpx::dataflow(hpx::launch::sync, hpx::util::unwrapping(
[this_ = std::move(this_)](primitive_arguments_type&& args)
-> primitive_argument_type
{
std::size_t a_dims = extract_numeric_value_dimension(
args[0], this_->name_, this_->codename_);
switch (a_dims)
{
case 0:
return this_->argminmax0d(std::move(args));
case 1:
return this_->argminmax1d(std::move(args));
case 2:
return this_->argminmax2d(std::move(args));
#if defined(PHYLANX_HAVE_BLAZE_TENSOR)
case 3:
return this_->argminmax3d(std::move(args));
#endif
default:
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"argminmax<Op, Derived>::eval",
this_->generate_error_message(
"operand a has an invalid number of dimensions"));
}
}),
detail::map_operands(
operands, functional::value_operand{}, args,
name_, codename_, std::move(ctx)));
}
}}}
#endif
| 35.030351 | 83 | 0.552146 | [
"vector",
"3d"
] |
a5e72375d343d7b8022220f50054c4e0f000dc49 | 8,947 | cc | C++ | cvmfs/manifest_fetch.cc | wtsi-hgi/cvmfs | ac781efef859f2f6ec4e12b06f63e3206e52c291 | [
"BSD-3-Clause"
] | null | null | null | cvmfs/manifest_fetch.cc | wtsi-hgi/cvmfs | ac781efef859f2f6ec4e12b06f63e3206e52c291 | [
"BSD-3-Clause"
] | null | null | null | cvmfs/manifest_fetch.cc | wtsi-hgi/cvmfs | ac781efef859f2f6ec4e12b06f63e3206e52c291 | [
"BSD-3-Clause"
] | null | null | null | /**
* This file is part of the CernVM File System.
*/
#include "manifest_fetch.h"
#include <string>
#include <vector>
#include <cassert>
#include "manifest.h"
#include "download.h"
#include "signature.h"
#include "util.h"
using namespace std; // NOLINT
namespace manifest {
/**
* Checks whether the fingerprint of the loaded PEM certificate is listed on the
* whitelist stored in a memory chunk.
*/
static bool VerifyWhitelist(const unsigned char *whitelist,
const unsigned whitelist_size,
const string &expected_repository)
{
const string fingerprint = signature::FingerprintCertificate();
if (fingerprint == "") {
LogCvmfs(kLogSignature, kLogDebug, "invalid fingerprint");
return false;
}
LogCvmfs(kLogSignature, kLogDebug,
"checking certificate with fingerprint %s against whitelist",
fingerprint.c_str());
time_t local_timestamp = time(NULL);
string line;
unsigned payload_bytes = 0;
// Check timestamp (UTC), ignore issue date (legacy)
line = GetLineMem(reinterpret_cast<const char *>(whitelist), whitelist_size);
if (line.length() != 14) {
LogCvmfs(kLogSignature, kLogDebug, "invalid timestamp format");
return false;
}
payload_bytes += 15;
// Expiry date
line = GetLineMem(reinterpret_cast<const char *>(whitelist)+payload_bytes,
whitelist_size-payload_bytes);
if (line.length() != 15) {
LogCvmfs(kLogSignature, kLogDebug, "invalid timestamp format");
return false;
}
struct tm tm_wl;
memset(&tm_wl, 0, sizeof(struct tm));
tm_wl.tm_year = String2Int64(line.substr(1, 4))-1900;
tm_wl.tm_mon = String2Int64(line.substr(5, 2)) - 1;
tm_wl.tm_mday = String2Int64(line.substr(7, 2));
tm_wl.tm_hour = String2Int64(line.substr(9, 2));
tm_wl.tm_min = tm_wl.tm_sec = 0; // exact on hours level
time_t timestamp = timegm(&tm_wl);
LogCvmfs(kLogSignature, kLogDebug,
"whitelist UTC expiry timestamp in localtime: %s",
StringifyTime(timestamp, false).c_str());
if (timestamp < 0) {
LogCvmfs(kLogSignature, kLogDebug, "invalid timestamp");
return false;
}
LogCvmfs(kLogSignature, kLogDebug, "local time: %s",
StringifyTime(local_timestamp, true).c_str());
if (local_timestamp > timestamp) {
LogCvmfs(kLogSignature, kLogDebug | kLogSyslogErr,
"whitelist lifetime verification failed, expired");
return false;
}
payload_bytes += 16;
// Check repository name
line = GetLineMem(reinterpret_cast<const char *>(whitelist)+payload_bytes,
whitelist_size-payload_bytes);
if ((expected_repository != "") && ("N" + expected_repository != line)) {
LogCvmfs(kLogSignature, kLogDebug | kLogSyslogErr,
"repository name on the whitelist does not match "
"(found %s, expected %s)",
line.c_str(), expected_repository.c_str());
return false;
}
payload_bytes += line.length() + 1;
// Search the fingerprint
bool found = false;
do {
line = GetLineMem(reinterpret_cast<const char *>(whitelist)+payload_bytes,
whitelist_size-payload_bytes);
if (line == "--") break;
if (line.substr(0, 59) == fingerprint)
found = true;
payload_bytes += line.length() + 1;
} while (payload_bytes < whitelist_size);
payload_bytes += line.length() + 1;
if (!found) {
LogCvmfs(kLogSignature, kLogDebug,
"the certificate's fingerprint is not on the whitelist");
return false;
}
// Check local blacklist
vector<string> blacklisted_certificates =
signature::GetBlacklistedCertificates();
for (unsigned i = 0; i < blacklisted_certificates.size(); ++i) {
if (blacklisted_certificates[i].substr(0, 59) == fingerprint) {
LogCvmfs(kLogSignature, kLogDebug | kLogSyslogErr,
"blacklisted fingerprint (%s)", fingerprint.c_str());
return false;
}
}
return true;
}
/**
* Downloads and verifies the manifest, the certificate, and the whitelist.
* If base_url is empty, uses the probe_hosts feature from download module.
*/
Failures Fetch(const std::string &base_url, const std::string &repository_name,
const uint64_t minimum_timestamp, const hash::Any *base_catalog,
ManifestEnsemble *ensemble)
{
assert(ensemble);
const bool probe_hosts = base_url == "";
Failures result = kFailUnknown;
int retval;
const string manifest_url = base_url + string("/.cvmfspublished");
download::JobInfo download_manifest(&manifest_url, false, probe_hosts, NULL);
const string whitelist_url = base_url + string("/.cvmfswhitelist");
download::JobInfo download_whitelist(&whitelist_url, false, probe_hosts, NULL);
hash::Any certificate_hash;
string certificate_url = base_url + "/data"; // rest is in manifest
download::JobInfo download_certificate(&certificate_url, true, probe_hosts,
&certificate_hash);
retval = download::Fetch(&download_manifest);
if (retval != download::kFailOk) {
LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogWarn,
"failed to download repository manifest (%d)", retval);
return kFailLoad;
}
// Load Manifest
ensemble->raw_manifest_buf =
reinterpret_cast<unsigned char *>(download_manifest.destination_mem.data);
ensemble->raw_manifest_size = download_manifest.destination_mem.size;
ensemble->manifest =
manifest::Manifest::LoadMem(ensemble->raw_manifest_buf,
ensemble->raw_manifest_size);
if (!ensemble->manifest)
return kFailIncomplete;
// Basic manifest sanity check
if (ensemble->manifest->repository_name() != repository_name) {
LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr,
"repository name does not match (found %s, expected %s)",
ensemble->manifest->repository_name().c_str(),
repository_name.c_str());
result = kFailNameMismatch;
goto cleanup;
}
if (ensemble->manifest->root_path() != hash::Md5(hash::AsciiPtr(""))) {
result = kFailRootMismatch;
goto cleanup;
}
if (ensemble->manifest->publish_timestamp() < minimum_timestamp) {
result = kFailOutdated;
goto cleanup;
}
// Quick way out: hash matches base catalog
if (base_catalog && (ensemble->manifest->catalog_hash() == *base_catalog))
return kFailOk;
// Load certificate
certificate_hash = ensemble->manifest->certificate();
ensemble->FetchCertificate(certificate_hash);
if (!ensemble->cert_buf) {
certificate_url += certificate_hash.MakePath(1, 2) + "X";
retval = download::Fetch(&download_certificate);
if (retval != download::kFailOk) {
result = kFailLoad;
goto cleanup;
}
ensemble->cert_buf =
reinterpret_cast<unsigned char *>(download_certificate.destination_mem.data);
ensemble->cert_size = download_certificate.destination_mem.size;
}
retval = signature::LoadCertificateMem(ensemble->cert_buf,
ensemble->cert_size);
if (!retval) {
result = kFailBadCertificate;
goto cleanup;
}
// Verify manifest
retval = signature::VerifyLetter(ensemble->raw_manifest_buf,
ensemble->raw_manifest_size, false);
if (!retval) {
LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr,
"failed to verify repository manifest");
result = kFailBadSignature;
goto cleanup;
}
// Load whitelist and verify
retval = download::Fetch(&download_whitelist);
if (retval != download::kFailOk) {
result = kFailLoad;
goto cleanup;
}
ensemble->whitelist_buf =
reinterpret_cast<unsigned char *>(download_whitelist.destination_mem.data);
ensemble->whitelist_size = download_whitelist.destination_mem.size;
retval = signature::VerifyLetter(ensemble->whitelist_buf,
ensemble->whitelist_size, true);
if (!retval) {
LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr,
"failed to verify repository whitelist");
result = kFailBadWhitelist;
goto cleanup;
}
retval = VerifyWhitelist(ensemble->whitelist_buf, ensemble->whitelist_size,
repository_name);
if (!retval) {
LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr,
"failed to verify repository certificate against whitelist");
result = kFailBadWhitelist;
goto cleanup;
}
return kFailOk;
cleanup:
delete ensemble->manifest;
ensemble->manifest = NULL;
if (ensemble->raw_manifest_buf) free(ensemble->raw_manifest_buf);
if (ensemble->cert_buf) free(ensemble->cert_buf);
if (ensemble->whitelist_buf) free(ensemble->whitelist_buf);
ensemble->raw_manifest_buf = NULL;
ensemble->cert_buf = NULL;
ensemble->whitelist_buf = NULL;
ensemble->raw_manifest_size = 0;
ensemble->cert_size = 0;
ensemble->whitelist_size = 0;
return result;
}
} // namespace manifest
| 34.148855 | 83 | 0.673857 | [
"vector"
] |
a5e9e6ec91582c84bf781419f20efd80ab58d07a | 1,679 | cc | C++ | cc/nn/NNObserver.cc | kiri11/alpha-zero-cpp | 00f19e65deaa274e7c547d6f5ad5470904fe347c | [
"MIT"
] | 1 | 2020-07-23T16:49:03.000Z | 2020-07-23T16:49:03.000Z | cc/nn/NNObserver.cc | kiri11/alpha-zero-cpp | 00f19e65deaa274e7c547d6f5ad5470904fe347c | [
"MIT"
] | null | null | null | cc/nn/NNObserver.cc | kiri11/alpha-zero-cpp | 00f19e65deaa274e7c547d6f5ad5470904fe347c | [
"MIT"
] | 1 | 2021-04-18T14:39:12.000Z | 2021-04-18T14:39:12.000Z | #include "NNObserver.h"
using namespace Eigen;
void setScheduling(std::thread &th, int policy, int priority) {
sched_param sch_params;
sch_params.sched_priority = priority;
if(pthread_setschedparam(th.native_handle(), policy, &sch_params)) {
std::cerr << "Failed to set Thread scheduling : " << std::strerror(errno) << std::endl;
}
}
NNObserver::NNObserver(NNWrapper& nnwrapper, std::string filename, bool watchFile) :
nnwrapper(nnwrapper), watchFile(watchFile){
if (watchFile){
this->fileWatcher = std::thread(&NNObserver::setup_inotify, this, filename);
setScheduling(this->fileWatcher, SCHED_BATCH, 0);
}
}
NNObserver::~NNObserver(){
if (this->watchFile){
close(this->inotifyFD);
this->fileWatcher.join();
}
}
//todo: error handling
void NNObserver::setup_inotify(std::string file){
this->inotifyFD = inotify_init();
inotify_add_watch(this->inotifyFD, file.c_str(), IN_ATTRIB | IN_MODIFY | IN_CREATE | IN_DELETE );
int buff_size = ( 1024 * ( sizeof (struct inotify_event) + NAME_MAX + 1) );
char buffer[ buff_size ];
fd_set watch_set;
FD_ZERO( &watch_set );
FD_SET( this->inotifyFD, &watch_set );
std::cout << "Watching for updates" << std::endl;
while(fcntl(this->inotifyFD, F_GETFD) != -1) {
struct timeval tv = {120, 0};
if(select( this->inotifyFD+1, &watch_set, NULL, NULL, &tv) == 1){
std::unique_lock lock(*(this->nnwrapper.getModelMutex()));
std::cout << "New model detected" << std::endl;
int length = read( this->inotifyFD, buffer, buff_size );
this->nnwrapper.load(file);
tv = {120, 0};
lock.unlock();
}
}
}
| 29.982143 | 99 | 0.65277 | [
"model"
] |
a5eabc78639ef13924556b31aa7afc22d98043c2 | 4,171 | cc | C++ | src/documents.cc | PaoJiao/slide | fccdcac94e951de113b8f0116084c41974e956da | [
"MIT"
] | null | null | null | src/documents.cc | PaoJiao/slide | fccdcac94e951de113b8f0116084c41974e956da | [
"MIT"
] | null | null | null | src/documents.cc | PaoJiao/slide | fccdcac94e951de113b8f0116084c41974e956da | [
"MIT"
] | null | null | null | #include "documents.h"
#include "base64.h"
#include <iostream>
#include <vector>
#include "debug_print.h"
namespace slide {
Page::Page(const int w, const int h, const std::string &name)
: size_(w, h), name_(name), surface_(nullptr), cr_(nullptr) {}
Page::~Page(void) {
debug_print("Page_b::dtor destroying _surface and _cr");
CairoWrapper::DestroySurface(surface_);
CairoWrapper::Destroy(cr_);
}
Document::Document(const int w, const int h, cairo_surface_t *const psurf,
cairo_t *const pcr, const std::string &name)
: Page(w, h, psurf, pcr, name) { /* intentionally blank */
}
Document::Document(const int w, const int h, const std::string &name)
: Page(w, h, name) { /* intentionally blank */
}
Page::Page(const int w, const int h, cairo_surface_t *const psurf,
cairo_t *const pcr, const std::string &name)
: size_(w, h), surface_(psurf), cr_(pcr),
name_(name) { /* intentionally blank */
}
Page::Page(void)
: size_(0, 0), surface_(0), cr_(0),
name_("No Name Set") { /* intentionally blank */
}
void Page::EnsureInitialised(void) {
if (cr_ == nullptr || surface_ == nullptr) {
InitialiseContext();
}
}
PNG::PNG(const int w, const int h)
: Page(w, h, "No Name Set") { /* Intentionally Blank */
}
PNG::PNG(const int w, const int h, const std::string &name)
: Page(w, h, name) { /* Intentionally Blank */
}
PNG::~PNG(void) { /* Intentionally Blank */
}
int PNG::TextHeight(Style::Style style, float scale) {
EnsureInitialised();
return CairoWrapper::TextHeight(cr_, style, scale);
}
int PNG::TextWidth(const std::string &text, Style::Style style, float scale) {
EnsureInitialised();
return CairoWrapper::TextWidth(cr_, text, style, scale);
}
void PNG::Background(const Color &color) {
EnsureInitialised();
CairoWrapper::Background(cr_, size_.Width(), size_.Width(), color);
}
void PNG::Text(const std::string &text, const Color &color, int x, int y,
Style::Style style, float scale) {
EnsureInitialised();
CairoWrapper::Text(cr_, text, color, x, y, style, scale);
}
void PNG::Save(const std::string filename) {
EnsureInitialised();
CairoWrapper::WriteToPng(surface_, filename.c_str());
}
std::string PNG::DataUri(void) {
EnsureInitialised();
std::vector<unsigned char> raw;
CairoWrapper::WriteToPngStream(
surface_,
[](void *closure, const unsigned char *data, unsigned int length) {
std::vector<unsigned char> *raw =
(std::vector<unsigned char> *)(closure);
for (unsigned int i = 0; i < length; i++) {
raw->push_back(data[i]);
}
return CAIRO_STATUS_SUCCESS;
},
&raw);
return "data:image/png;base64," +
Base64::Encode(raw.data(), raw.size(), true);
}
void PNG::InitialiseContext(void) {
// std::cerr << "PNG::ctor creating surface_ and cr_" << std::endl;
surface_ = CairoWrapper::CreateSurface(size_.Width(), size_.Height());
cr_ = CairoWrapper::Create(surface_);
}
PDF::PDF(const std::string name, const int w, const int h)
: Document(w, h, name) {
/* Intentionally Blank */
}
PDF::~PDF(void) {
// Intentionally blank
}
void PDF::BeginPage(void) {
// intentionally blank
}
void PDF::EndPage(void) { CairoWrapper::ShowPage(cr_); }
int PDF::TextHeight(Style::Style style, float scale) {
EnsureInitialised();
return CairoWrapper::TextHeight(cr_, style, scale);
}
int PDF::TextWidth(const std::string &text, Style::Style style, float scale) {
EnsureInitialised();
return CairoWrapper::TextWidth(cr_, text, style, scale);
}
void PDF::Background(const Color &color) {
EnsureInitialised();
CairoWrapper::Background(cr_, size_.Width(), size_.Height(), color);
}
void PDF::Text(const std::string &text, const Color &color, int x, int y,
Style::Style style, float scale) {
EnsureInitialised();
CairoWrapper::Text(cr_, text, color, x, y, style, scale);
}
void PDF::InitialiseContext(void) {
debug_print("PDF::ctor creating surface_ and cr_");
surface_ =
CairoWrapper::CreatePDFSurface(name_, size_.Width(), size_.Height());
cr_ = CairoWrapper::Create(surface_);
}
} // namespace slide | 28.568493 | 78 | 0.660753 | [
"vector"
] |
a5eeec3299c8da5f8cff6745b816224683a27792 | 3,042 | cpp | C++ | libs/base/file_system.cpp | kdt3rd/gecko | 756a4e4587eb5023495294d9b6c6d80ebd79ebde | [
"MIT"
] | 15 | 2017-10-18T05:08:16.000Z | 2022-02-02T11:01:46.000Z | libs/base/file_system.cpp | kdt3rd/gecko | 756a4e4587eb5023495294d9b6c6d80ebd79ebde | [
"MIT"
] | null | null | null | libs/base/file_system.cpp | kdt3rd/gecko | 756a4e4587eb5023495294d9b6c6d80ebd79ebde | [
"MIT"
] | 1 | 2018-11-10T03:12:57.000Z | 2018-11-10T03:12:57.000Z | // SPDX-License-Identifier: MIT
// Copyright contributors to the gecko project.
#include "file_system.h"
#include <map>
#include <mutex>
#include <system_error>
#ifdef _WIN32
# include "win32_file_system.h"
#else
# include "posix_file_system.h"
#endif
namespace
{
std::mutex theMutex;
std::map<std::string, std::shared_ptr<base::file_system>> &singleton( void )
{
static std::map<std::string, std::shared_ptr<base::file_system>>
theFileSystems{
#ifdef _WIN32
{ "file", std::make_shared<base::win32_file_system>() },
#else
{ "file", std::make_shared<base::posix_file_system>() },
#endif
};
return theFileSystems;
}
} // namespace
////////////////////////////////////////
namespace base
{
////////////////////////////////////////
file_system::~file_system( void ) {}
////////////////////////////////////////
uri file_system::stat( const uri &path, struct stat *buf )
{
lstat( path, buf );
#ifdef _WIN32
throw_not_yet();
#else
uri curpath = path;
int depth = 0;
std::shared_ptr<file_system> fs;
while ( S_ISLNK( buf->st_mode ) )
{
if ( fs )
curpath = fs->readlink(
curpath, static_cast<size_t>( buf->st_size + 1 ) );
else
curpath =
readlink( curpath, static_cast<size_t>( buf->st_size + 1 ) );
fs = get( curpath );
fs->lstat( curpath, buf );
depth++;
if ( depth > 20 )
throw std::system_error(
ELOOP, std::system_category(), path.pretty() );
}
return curpath;
#endif
}
////////////////////////////////////////
void file_system::rmdir_all( const uri &path )
{
struct stat buf;
lstat( path, &buf );
if ( S_ISDIR( buf.st_mode ) )
{
std::vector<uri> paths;
{
auto dir = readdir( path );
while ( ++dir )
paths.push_back( *dir );
}
for ( auto &p: paths )
rmdir_all( p );
rmdir( path );
}
else
unlink( path );
}
////////////////////////////////////////
std::shared_ptr<file_system> file_system::get( const std::string &scheme )
{
precondition( !scheme.empty(), "invalid empty scheme" );
std::unique_lock<std::mutex> lk( theMutex );
auto & fs = singleton();
auto f = fs.find( scheme );
precondition(
f != fs.end(), "no file system registered for scheme {0}", scheme );
return f->second;
}
////////////////////////////////////////
void file_system::add(
const std::string &sch, const std::shared_ptr<file_system> &fs )
{
std::unique_lock<std::mutex> lk( theMutex );
auto & thefs = singleton();
auto f = thefs.find( sch );
precondition(
f == thefs.end() || ( f->second == fs ),
"Multiple file systems registered for same scheme " + sch );
thefs[sch] = fs;
}
////////////////////////////////////////
} // namespace base
| 23.952756 | 77 | 0.50263 | [
"vector"
] |
a5f0dff361315a8775b2deafb39b1fa0c3ac1b2c | 727 | hpp | C++ | src/frame.hpp | ohowland/waygate | 926100c101b30827b52ba9262f3b7dfdbb6f50ad | [
"MIT"
] | null | null | null | src/frame.hpp | ohowland/waygate | 926100c101b30827b52ba9262f3b7dfdbb6f50ad | [
"MIT"
] | null | null | null | src/frame.hpp | ohowland/waygate | 926100c101b30827b52ba9262f3b7dfdbb6f50ad | [
"MIT"
] | null | null | null | #ifndef CAN_FRAME_H_
#define CAN_FRAME_H_
#include <ctime>
namespace can {
class Frame {
public:
Frame()
: m_timestamp(std::time(0)),
m_id(0),
m_len(0),
m_data()
{ }
Frame(const uint32_t t_id, const uint8_t t_len, const unsigned char t_data[])
: m_timestamp(std::time(0)),
m_id(t_id),
m_len(t_len),
m_data(t_data, t_data + t_len)
{ }
auto timestamp() const -> std::time_t { return m_timestamp; }
auto id() const -> uint32_t { return m_id; }
auto data() const -> std::vector<uint8_t> { return m_data; }
private:
const std::time_t m_timestamp;
const uint32_t m_id;
const uint8_t m_len;
const std::vector<uint8_t> m_data;
};
}
#endif | 20.771429 | 81 | 0.620358 | [
"vector"
] |
a5f9cd268369c4731b601b9685ff1f512e7e1fe4 | 4,966 | cpp | C++ | src/PregameScreen.cpp | thamstras/GamesProgramming | b576760cd12c1a13347bc488a2eb3d5a141abac1 | [
"MIT"
] | null | null | null | src/PregameScreen.cpp | thamstras/GamesProgramming | b576760cd12c1a13347bc488a2eb3d5a141abac1 | [
"MIT"
] | null | null | null | src/PregameScreen.cpp | thamstras/GamesProgramming | b576760cd12c1a13347bc488a2eb3d5a141abac1 | [
"MIT"
] | null | null | null | #include "PregameScreen.h"
void transitToGame()
{
// TODO: Finish transition to Game
//Scene::getScene().turn = 1;
//Scene::getScene().loadScene(SCENE_GAME_OURTURN);
Scene::getScene().startGame();
}
PregameScreen::PregameScreen(SDL_Renderer * ren, std::string id) : RenderObject(id)
{
Scene& scene = Scene::getScene();
this->gridWidth = scene.gridWidth;
this->gridHeight = scene.gridHeight;
grid = new bool[100];
for (int i = 0; i < 100; i++)
grid[i] = false;
select = new StaticSprite("selectionsquare", ren, this->id + "_select");
ship1 = new SwapSprite("shipblueprint-2", "shipblueprint-2r", ren, this->id + "_ship1");
ship2 = new SwapSprite("shipblueprint-2", "shipblueprint-2r", ren, this->id + "_ship2");
ship3 = new SwapSprite("shipblueprint-3", "shipblueprint-3r", ren, this->id + "_ship3");
ship4 = new SwapSprite("shipblueprint-3", "shipblueprint-3r", ren, this->id + "_ship4");
ship5 = new SwapSprite("shipblueprint-4", "shipblueprint-4r", ren, this->id + "_ship5");
ship6 = new SwapSprite("shipblueprint-5", "shipblueprint-5r", ren, this->id + "_ship6");
doneButton = new GUIButton(ren, "Done", -100, -100, transitToGame, this->id + "_doneButton");
currentShip = 1;
done = false;
select->moveSprite(-100, -100);
ship1->moveSprite(-100, -100);
ship2->moveSprite(-100, -100);
ship3->moveSprite(-100, -100);
ship4->moveSprite(-100, -100);
ship5->moveSprite(-100, -100);
ship6->moveSprite(-100, -100);
scene.registerRender(ship6);
scene.registerRender(ship5);
scene.registerRender(ship4);
scene.registerRender(ship3);
scene.registerRender(ship2);
scene.registerRender(ship1);
//scene.registerRender(select);
scene.registerRender(doneButton);
}
PregameScreen::~PregameScreen()
{
}
void PregameScreen::update(double simLength)
{
MouseData mouse = Scene::getScene().mouseData;
int mouseGridX = mouse.mouseX / gridWidth;
int mouseGridY = mouse.mouseY / gridHeight;
int selectX = mouseGridX * gridWidth;
int selectY = mouseGridY * gridHeight;
if (!done)
{
select->moveSprite(selectX, selectY);
getCurrentShip()->moveSprite(selectX, selectY);
if (mouse.leftMouseOnce)
{
int shipSize = getCurrentShipSize();
int dir = !(getCurrentShip()->selectedSpriteA);
if (fitsOnGrid(mouseGridX, mouseGridY, shipSize, dir))
{
placeOnGrid(mouseGridX, mouseGridY, shipSize, dir);
currentShip++;
if (currentShip > 6)
showDoneButton();
}
}
if (mouse.rightMouseOnce)
{
getCurrentShip()->swap();
}
}
else {
// Check if remote ready
// transitionToGame();
if (Scene::getScene().remotePlayer->getReady())
transitToGame();
}
}
void PregameScreen::render(SDL_Renderer * ren)
{
}
SwapSprite * PregameScreen::getCurrentShip()
{
switch (currentShip)
{
case 1:
return ship1;
case 2:
return ship2;
case 3:
return ship3;
case 4:
return ship4;
case 5:
return ship5;
case 6:
return ship6;
default:
return ship1;
}
}
int PregameScreen::getCurrentShipSize()
{
switch (currentShip)
{
case 1:
return 2;
case 2:
return 2;
case 3:
return 3;
case 4:
return 3;
case 5:
return 4;
case 6:
return 5;
default:
return 0;
}
}
void PregameScreen::showDoneButton()
{
done = true;
select->moveSprite(-100, -100);
//doneButton->moveButton(400, 500);
ShipData s1 = { 2, ship1->getX()/60, ship1->getY()/60, !(ship1->selectedSpriteA) };
ShipData s2 = { 2, ship2->getX()/60, ship2->getY()/60, !(ship2->selectedSpriteA) };
ShipData s6 = { 5, ship6->getX()/60, ship6->getY()/60, !(ship6->selectedSpriteA) };
ShipData s3 = { 3, ship3->getX()/60, ship3->getY()/60, !(ship3->selectedSpriteA) };
ShipData s4 = { 3, ship4->getX()/60, ship4->getY()/60, !(ship4->selectedSpriteA) };
ShipData s5 = { 4, ship5->getX()/60, ship5->getY()/60, !(ship5->selectedSpriteA) };
Scene::getScene().p1Data.ships[0] = s1;
Scene::getScene().p1Data.ships[1] = s2;
Scene::getScene().p1Data.ships[2] = s3;
Scene::getScene().p1Data.ships[3] = s4;
Scene::getScene().p1Data.ships[4] = s5;
Scene::getScene().p1Data.ships[5] = s6;
}
bool PregameScreen::gridOpen(int X, int Y)
{
if (X > 9 || Y > 9)
return false;
if (X < 0 || Y < 0)
return false;
int i = (Y * 10) + X;
return !grid[i];
}
void PregameScreen::closeGrid(int X, int Y)
{
if (X > 9 || Y > 9)
return;
if (X < 0 || Y < 0)
return;
int i = (Y * 10) + X;
grid[i] = true;
}
bool PregameScreen::fitsOnGrid(int X, int Y, int size, int direction)
{
bool fits = true;
if (direction == 0)
{
for (int i = 0; i < size; i++)
{
if (!gridOpen(X + i, Y))
{
fits = false;
break;
}
}
}
else {
for (int i = 0; i < size; i++)
{
if (!gridOpen(X, Y + i))
{
fits = false;
break;
}
}
}
return fits;
}
void PregameScreen::placeOnGrid(int X, int Y, int size, int direction)
{
if (direction == 0)
{
for (int i = 0; i < size; i++)
{
closeGrid(X + i, Y);
}
}
else {
for (int i = 0; i < size; i++)
{
closeGrid(X, Y + i);
}
}
}
| 21.313305 | 94 | 0.640959 | [
"render"
] |
a5fd5c4ccd00458832af1dcdd9203f3db4aabe42 | 10,688 | cpp | C++ | modules/VideoImporter/src/VideoDataOutputPin.cpp | ConnectedVision/ConnectedVision | 210e49205ca50f73584178b6cedb298a74cea798 | [
"MIT"
] | 3 | 2017-08-12T18:14:00.000Z | 2018-11-19T09:15:35.000Z | modules/VideoImporter/src/VideoDataOutputPin.cpp | ConnectedVision/ConnectedVision | 210e49205ca50f73584178b6cedb298a74cea798 | [
"MIT"
] | null | null | null | modules/VideoImporter/src/VideoDataOutputPin.cpp | ConnectedVision/ConnectedVision | 210e49205ca50f73584178b6cedb298a74cea798 | [
"MIT"
] | 1 | 2018-11-09T15:57:13.000Z | 2018-11-09T15:57:13.000Z | /**
* Connected Vision - https://github.com/ConnectedVision
* MIT License
*/
// template include guard
#ifndef VideoDataOutputPin_def
#define VideoDataOutputPin_def
#include <sstream>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <boost/lexical_cast.hpp>
#include "VideoDataOutputPin.h"
namespace ConnectedVision {
namespace Module {
namespace VideoImporter {
using namespace std;
VideoDataOutputPin::VideoDataOutputPin(VideoImporterModule* module, unsigned int colorspace, std::string mimetype, fp_Encoder encoder)
{
this->videoImportModule = module;
this->ColorSpace = colorspace;
this->MimeType = mimetype;
this->Encoder = encoder;
this->config.clear();
}
VideoDataOutputPin::~VideoDataOutputPin(void)
{
}
/**
* init output pin with config
*
* @param[in] configStr config chain
*
* @return status code (analog to HTTP codes)
*/
void VideoDataOutputPin::init(const std::string& configStr)
{
this->config.parseJson( configStr.c_str() );
}
/**
* get data from module by ID
*
* @param[in] id ID of requested data
* @param[out] response requested data or error response
*
* @return status code (analog to HTTP codes)
*/
int VideoDataOutputPin::getByID(const id_t id, ConnectedVisionResponse &response)
{
return getByIndex(boost::lexical_cast<int64_t>(id.c_str()),response);
}
/**
* get data from module by index
*
* @param[in] index index of requested data
* @param[out] response requested data or error response
*
* @return status code (analog to HTTP codes)
*/
int VideoDataOutputPin::getByIndex(const int64_t index, ConnectedVisionResponse &response)
{
// make sure that video importer is init
videoImportModule->priv->VideoImport_init( this->config );
id_t configID = this->config.get_id();
try
{
boost::shared_ptr<ConnectedVision::Module::VideoImporter::VideoImport> pVideoImportInstance;
{ // first lock the videoImportMap mutex (as scoped section - so that mutex is unlocked as soon as possible)
boost::mutex::scoped_lock(videoImportModule->priv->mutexVideoImportMap);
auto it = videoImportModule->priv->videoImportMap.find(configID);
if (it != videoImportModule->priv->videoImportMap.end())
{
// then get shared pointer of VideoImport instance
pVideoImportInstance = it->second;
}
else
{
return writeError(response, ConnectedVision::HTTP::HTTP_Status_NOT_FOUND, id_t("VideoDataOutputPin"), "not found");
}
}
// now lock the instance mutex
boost::mutex::scoped_lock lock(pVideoImportInstance->m_mutex);
videoImportModule->priv->VideoImport_goToFrameNumber(configID, index, ColorSpace);
response.setContentType(MimeType);
response.setContent(Encoder(configID, &(*pVideoImportInstance), (const unsigned int) ColorSpace));
return ConnectedVision::HTTP::HTTP_Status_OK;
}
catch (runtime_error& e)
{
return writeError(response, ConnectedVision::HTTP::HTTP_Status_ERROR, id_t("VideoDataOutputPin"), string(e.what()) );
}
}
/**
* get data from module by index range
*
* @param[in] start first index of requested data
* @param[in] end last index of requested data
* @param[out] response requested data or error response
*
* @return status code (analog to HTTP codes)
*/
int VideoDataOutputPin::getByIndexRange(const int64_t start, const int64_t end, ConnectedVisionResponse &response)
{
int nRet = getByIndex(start,response);
if (nRet == ConnectedVision::HTTP::HTTP_Status_OK)
{
std::string content = response.getContent();
if (response.getContentType().compare("application/json") == 0)
{
content = "[\n" + content + "\n]\n";
}
response.setContent(content);
}
return nRet;
}
/**
* get data from module by timestamp
*
* @param[in] timestamp timestamp of requested data
* @param[out] response requested data or error response
*
* @return status code (analog to HTTP codes)
*/
int VideoDataOutputPin::getByTimestamp(const timestamp_t timestamp, ConnectedVisionResponse &response)
{
// make sure that video importer is init
videoImportModule->priv->VideoImport_init( this->config );
id_t configID = this->config.get_id();
try
{
boost::shared_ptr<ConnectedVision::Module::VideoImporter::VideoImport> pVideoImportInstance;
{ // first lock the videoImportMap mutex (as scoped section - so that mutex is unlocked as soon as possible)
boost::mutex::scoped_lock(videoImportModule->priv->mutexVideoImportMap);
auto it = videoImportModule->priv->videoImportMap.find(configID);
if (it != videoImportModule->priv->videoImportMap.end())
{
// then get shared pointer of VideoImport instance
pVideoImportInstance = it->second;
}
else
{
return writeError(response, ConnectedVision::HTTP::HTTP_Status_NOT_FOUND, id_t("VideoDataOutputPin"), "not found");
}
}
// now lock the instance mutex
boost::mutex::scoped_lock lock(pVideoImportInstance->m_mutex);
videoImportModule->priv->VideoImport_goToTimestamp(configID, timestamp, ColorSpace);
if (timestamp == pVideoImportInstance->m_Frame.timestamp)
{
response.setContentType(MimeType);
std::string content = Encoder(configID, &(*pVideoImportInstance), (const unsigned int) ColorSpace);
if (MimeType.compare("application/json") == 0)
{
content = "[\n" + content + "\n]\n";
}
response.setContent(content);
return ConnectedVision::HTTP::HTTP_Status_OK;
}
else
{
return writeError(response, ConnectedVision::HTTP::HTTP_Status_NOT_FOUND, id_t("VideoDataOutputPin"), "not found");
}
}
catch (runtime_error& e)
{
return writeError(response, ConnectedVision::HTTP::HTTP_Status_ERROR, id_t("VideoDataOutputPin"), string(e.what()) );
}
}
/**
* get data from module by timestamp before
*
* @param[in] timestamp timestamp of requested data
* @param[out] response requested data or error response
*
* @return status code (analog to HTTP codes)
*/
int VideoDataOutputPin::getBeforeTimestamp(const timestamp_t timestamp, ConnectedVisionResponse &response)
{
// make sure that video importer is init
videoImportModule->priv->VideoImport_init( this->config );
id_t configID = this->config.get_id();
try
{
boost::shared_ptr<ConnectedVision::Module::VideoImporter::VideoImport> pVideoImportInstance;
{ // first lock the videoImportMap mutex (as scoped section - so that mutex is unlocked as soon as possible)
boost::mutex::scoped_lock(videoImportModule->priv->mutexVideoImportMap);
auto it = videoImportModule->priv->videoImportMap.find(configID);
if (it != videoImportModule->priv->videoImportMap.end())
{
// then get shared pointer of VideoImport instance
pVideoImportInstance = it->second;
}
else
{
return writeError(response, ConnectedVision::HTTP::HTTP_Status_NOT_FOUND, id_t("VideoDataOutputPin"), "not found");
}
}
// now lock the instance mutex
boost::mutex::scoped_lock lock(pVideoImportInstance->m_mutex);
videoImportModule->priv->VideoImport_goToTimestamp(configID, timestamp-1, ColorSpace);
if (!(pVideoImportInstance->m_Frame.timestamp < timestamp))
{
videoImportModule->priv->VideoImport_goToFrameNumber(configID, pVideoImportInstance->m_Frame.framenumber - 1, ColorSpace);
}
if (pVideoImportInstance->m_Frame.timestamp < timestamp)
{
response.setContentType(MimeType);
std::string content = Encoder(configID, &(*pVideoImportInstance), (const unsigned int) ColorSpace);
if (MimeType.compare("application/json") == 0)
{
content = "[\n" + content + "\n]\n";
}
response.setContent(content);
return ConnectedVision::HTTP::HTTP_Status_OK;
}
else
{
return writeError(response, ConnectedVision::HTTP::HTTP_Status_NOT_FOUND, id_t("VideoDataOutputPin"), "not found");
}
}
catch (runtime_error& e)
{
return writeError(response, ConnectedVision::HTTP::HTTP_Status_ERROR, id_t("VideoDataOutputPin"), string(e.what()) );
}
}
/**
* get data from module by timestamp after
*
* @param[in] timestamp timestamp of requested data
* @param[out] response requested data or error response
*
* @return status code (analog to HTTP codes)
*/
int VideoDataOutputPin::getAfterTimestamp(const timestamp_t timestamp, ConnectedVisionResponse &response)
{
// make sure that video importer is init
videoImportModule->priv->VideoImport_init( this->config );
id_t configID = this->config.get_id();
try
{
boost::shared_ptr<ConnectedVision::Module::VideoImporter::VideoImport> pVideoImportInstance;
{ // first lock the videoImportMap mutex (as scoped section - so that mutex is unlocked as soon as possible)
boost::mutex::scoped_lock(videoImportModule->priv->mutexVideoImportMap);
auto it = videoImportModule->priv->videoImportMap.find(configID);
if (it != videoImportModule->priv->videoImportMap.end())
{
// then get shared pointer of VideoImport instance
pVideoImportInstance = it->second;
}
else
{
return writeError(response, ConnectedVision::HTTP::HTTP_Status_NOT_FOUND, id_t("VideoDataOutputPin"), "not found");
}
}
// now lock the instance mutex
boost::mutex::scoped_lock lock(pVideoImportInstance->m_mutex);
videoImportModule->priv->VideoImport_goToTimestamp(configID, timestamp+1, ColorSpace);
if (!(pVideoImportInstance->m_Frame.timestamp > timestamp))
{
videoImportModule->priv->VideoImport_goToFrameNumber(configID, pVideoImportInstance->m_Frame.framenumber + 1, ColorSpace);
}
if (pVideoImportInstance->m_Frame.timestamp > timestamp)
{
response.setContentType(MimeType);
std::string content = Encoder(configID, &(*pVideoImportInstance), (const unsigned int) ColorSpace);
if (MimeType.compare("application/json") == 0)
{
content = "[\n" + content + "\n]\n";
}
response.setContent(content);
return ConnectedVision::HTTP::HTTP_Status_OK;
}
else
{
return writeError(response, ConnectedVision::HTTP::HTTP_Status_NOT_FOUND, id_t("VideoDataOutputPin"), "not found");
}
}
catch (runtime_error& e)
{
return writeError(response, ConnectedVision::HTTP::HTTP_Status_ERROR, id_t("VideoDataOutputPin"), string(e.what()) );
}
}
/**
* get data from module by time span
*
* @param[in] start first timestamp of requested data
* @param[in] end last timestamp of requested data
* @param[out] response requested data or error response
*
* @return status code (analog to HTTP codes)
*/
int VideoDataOutputPin::getAllInTimespan(const timestamp_t start, const timestamp_t end, ConnectedVisionResponse &response)
{
return getByTimestamp(start,response);
}
} // namespace VideoImporter
} // namespace Module
} // namespace ConnectedVision
#endif // VideoDataOutputPin_def
| 29.688889 | 134 | 0.731287 | [
"vector"
] |
57065c35f5ce838bf80896ec52474a8ec7c548d3 | 6,800 | cpp | C++ | 3rdparty/diy/examples/simple/simple.cpp | wgq-iapcm/Parvoro- | 9459e1081ff948628358c59207d5fcd8ce60ef8f | [
"BSD-3-Clause"
] | 43 | 2016-10-23T14:52:59.000Z | 2022-03-18T20:47:06.000Z | 3rdparty/diy/examples/simple/simple.cpp | wgq-iapcm/Parvoro- | 9459e1081ff948628358c59207d5fcd8ce60ef8f | [
"BSD-3-Clause"
] | 39 | 2016-11-25T22:14:09.000Z | 2022-01-13T21:44:51.000Z | 3rdparty/diy/examples/simple/simple.cpp | wgq-iapcm/Parvoro- | 9459e1081ff948628358c59207d5fcd8ce60ef8f | [
"BSD-3-Clause"
] | 21 | 2016-11-28T22:08:36.000Z | 2022-03-16T10:31:32.000Z | //
// Simple neighbor communication by creating a linear chain of blocks, each
// block connected to two neighbors (predecessor and successor), except for the
// first and the last blocks, which have only one or the other. Each block
// computes an average of its values and those of its neighbors. The average is
// stored in the block, and the blocks are written to a file in storage.
// Also demonstrates the use of the all_reduce proxy collective in conjunction
// with the neighbor communication.
//
#include <vector>
#include <iostream>
#include <diy/mpi.hpp>
#include <diy/master.hpp>
#include <diy/assigner.hpp>
#include <diy/serialization.hpp>
#include <diy/io/block.hpp>
#include "../opts.h"
#include "block.h"
#define UNUSED(expr) do { (void)(expr); } while (0)
// --- callback functions ---//
//
// compute sum of local values and enqueue the sum
//
void local_sum(Block* b, // local block
const diy::Master::ProxyWithLink& cp) // communication proxy
{
diy::Link* l = cp.link();
// compute local sum
int total = 0;
for (unsigned i = 0; i < b->values.size(); ++i)
total += b->values[i];
std::cout << "Total (" << cp.gid() << "): " << total << std::endl;
// for all neighbor blocks
// enqueue data to be sent to this neighbor block in the next exchange
for (int i = 0; i < l->size(); ++i)
cp.enqueue(l->target(i), total);
// diy collectives (optional) are piggybacking on the enqueue/exchange/dequeue mechanism.
// They are invoked by posting the collective at the time of the enqueue and getting the
// result at the time of the dequeue.
// all_reduce() is the posting of the collective.
cp.all_reduce(total, std::plus<int>());
}
//
// average the values received from the neighbors
//
void average_neighbors(Block* b, // local block
const diy::Master::ProxyWithLink& cp) // communication proxy
{
diy::Link* l = cp.link(); UNUSED(l);
// diy collectives (optional) are piggybacking on the enqueue/exchange/dequeue mechanism.
// They are invoked by posting the collective at the time of the enqueue and getting the
// result at the time of the dequeue.
// cp.get() is the result retrieval.
int all_total = cp.get<int>(); UNUSED(all_total);
// gids of incoming neighbors in the link
std::vector<int> in;
cp.incoming(in);
// for all neighbor blocks
// dequeue data received from this neighbor block in the last exchange
int total = 0;
for (unsigned i = 0; i < in.size(); ++i)
{
int v;
cp.dequeue(in[i], v);
total += v;
}
// compute average and print it
b->average = float(total) / in.size();
std::cout << "Average (" << cp.gid() << "): " << b->average << std::endl;
}
// --- main program ---//
int main(int argc, char* argv[])
{
diy::mpi::environment env(argc, argv); // equivalent of MPI_Init(argc, argv)/MPI_Finalize()
diy::mpi::communicator world; // equivalent of MPI_COMM_WORLD
int nblocks = 128; // global number of blocks
int threads = 4; // allow diy 4 threads for multithreading blocks
int in_memory = 8; // allow diy to keep 8 local blocks in memory
std::string prefix = "./DIY.XXXXXX"; // prefix for temp files for blocks
// moved out of core
bool help;
// get command line arguments
using namespace opts;
Options ops;
ops
>> Option('b', "blocks", nblocks, "number of blocks")
>> Option('t', "thread", threads, "number of threads")
>> Option('m', "memory", in_memory, "maximum blocks to store in memory")
>> Option( "prefix", prefix, "prefix for external storage")
>> Option('h', "help", help, "show help")
;
if (!ops.parse(argc,argv) || help)
{
if (world.rank() == 0)
std::cout << ops;
return 1;
}
// diy initialization
diy::FileStorage storage(prefix); // used for blocks to be moved out of core
diy::Master master(world, // master is the diy top-level object
threads,
in_memory,
&create_block,
&destroy_block,
&storage,
&save_block,
&load_block);
// choice of contiguous or round robin assigner
// diy::ContiguousAssigner assigner(world.size(), nblocks);
diy::RoundRobinAssigner assigner(world.size(), nblocks);
// this example creates a linear chain of blocks
std::vector<int> gids; // global ids of local blocks
assigner.local_gids(world.rank(), gids); // get the gids of local blocks
for (unsigned i = 0; i < gids.size(); ++i) // for the local blocks in this processor
{
int gid = gids[i];
diy::Link* link = new diy::Link; // link is this block's neighborhood
diy::BlockID neighbor;
if (gid < nblocks - 1) // all but the last block in the global domain
{
neighbor.gid = gid + 1; // gid of the neighbor block
neighbor.proc = assigner.rank(neighbor.gid); // process of the neighbor block
link->add_neighbor(neighbor); // add the neighbor block to the link
}
if (gid > 0) // all but the first block in the global domain
{
neighbor.gid = gid - 1;
neighbor.proc = assigner.rank(neighbor.gid);
link->add_neighbor(neighbor);
}
Block* b = new Block; // create a new block
// assign some values for the block
// in this example, simply based on the block global id
for (unsigned j = 0; j < 3; ++j)
b->values.push_back(gid * 3 + j);
master.add(gid, b, link); // add the current local block to the master
}
// compute, exchange, compute
master.foreach(&local_sum); // callback function executed on each local block
master.exchange(); // exchange data between blocks in the link
master.foreach(&average_neighbors); // callback function executed on each local block
// save the results in diy format
diy::io::write_blocks("blocks.out", world, master);
if (world.rank() == 0)
master.prof.output(std::cout);
}
| 38.202247 | 99 | 0.562647 | [
"object",
"vector"
] |
570e6134d550a5476471c8ce803f2ae1ea750a26 | 17,648 | cpp | C++ | src/caffe/mpi.cpp | matex-org/caffe-intel | 8435dc0803542d2b0a5524c3a3c7d2ea9f99da1c | [
"Intel",
"BSD-2-Clause"
] | 1 | 2019-08-16T13:09:38.000Z | 2019-08-16T13:09:38.000Z | src/caffe/mpi.cpp | matex-org/caffe-intel | 8435dc0803542d2b0a5524c3a3c7d2ea9f99da1c | [
"Intel",
"BSD-2-Clause"
] | null | null | null | src/caffe/mpi.cpp | matex-org/caffe-intel | 8435dc0803542d2b0a5524c3a3c7d2ea9f99da1c | [
"Intel",
"BSD-2-Clause"
] | null | null | null | #ifdef USE_MPI
#include <mpi.h>
#endif
#include <glog/logging.h>
#include <stdlib.h>
#include <stdexcept>
#include <string>
#include <unistd.h> // for gethostid()
#include <vector>
#include "caffe/mpi.hpp"
namespace caffe {
namespace mpi {
#ifdef USE_MPI
MPI_Comm default_comm_ = MPI_COMM_WORLD;
MPI_Comm get_comm_default() {
return default_comm_;
}
void set_comm_default(MPI_Comm comm) {
if (MPI_COMM_NULL != comm) {
default_comm_ = comm;
}
else {
throw std::runtime_error("cannot assign MPI_COMM_NULL as default comm");
}
}
void init(int *argc, char ***argv, const std::string &FLAGS_mpi) {
char name[MPI_MAX_PROCESSOR_NAME];
int requested = MPI_THREAD_SINGLE;
int rank = 0;
int size = 0;
int namelen = 0;
if (FLAGS_mpi == "MPI_THREAD_SINGLE") {
LOG(INFO) << "MPI threading level set to MPI_THREAD_SINGLE";
requested = MPI_THREAD_SINGLE;
}
else if (FLAGS_mpi == "MPI_THREAD_FUNNELED") {
LOG(INFO) << "MPI threading level set to MPI_THREAD_FUNNELED";
requested = MPI_THREAD_FUNNELED;
}
else if (FLAGS_mpi == "MPI_THREAD_SERIALIZED") {
LOG(INFO) << "MPI threading level set to MPI_THREAD_SERIALIZED";
requested = MPI_THREAD_SERIALIZED;
}
else if (FLAGS_mpi == "MPI_THREAD_MULTIPLE") {
LOG(INFO) << "MPI threading level set to MPI_THREAD_MULTIPLE";
requested = MPI_THREAD_MULTIPLE;
}
else {
LOG(ERROR) << "unknown FLAGS_mpi provided";
exit(EXIT_FAILURE);
}
if (!initialized()) {
int provided;
if (MPI_SUCCESS != MPI_Init_thread(
argc, argv, requested, &provided)) {
throw std::runtime_error("MPI_Init_thread failed");
}
}
if (requested != query_thread()) {
throw std::runtime_error("MPI threading level does not match requested");
}
if (0 != atexit(finalize)) {
throw std::runtime_error("atexit(caffe::mpi::finalize) failed");
}
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Get_processor_name(name, &namelen);
LOG(INFO) << "Process rank " << rank << " from number of " << size
<< " processes running on " << name;
}
bool initialized() {
int flag;
if (MPI_SUCCESS != MPI_Initialized(&flag)) {
throw std::runtime_error("MPI_Initialized failed");
}
return flag;
}
void finalize() {
if (MPI_SUCCESS != MPI_Finalize()) {
throw std::runtime_error("MPI_Finalize failed");
}
}
int query_thread() {
int provided;
if (MPI_SUCCESS != MPI_Query_thread(&provided)) {
throw std::runtime_error("MPI_Query_thread failed");
}
return provided;
}
MPI_Comm comm_dup(MPI_Comm comm) {
MPI_Comm newcomm;
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Comm_dup(comm, &newcomm)) {
throw std::runtime_error("MPI_Comm_dup failed");
return MPI_COMM_NULL;
}
return newcomm;
}
MPI_Comm comm_split(int color, int key, MPI_Comm comm) {
MPI_Comm newcomm;
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Comm_split(comm, color, key, &newcomm)) {
throw std::runtime_error("MPI_Comm_split failed");
return MPI_COMM_NULL;
}
return newcomm;
}
MPI_Comm comm_create(MPI_Group group, MPI_Comm comm) {
MPI_Comm newcomm;
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Comm_create(comm, group, &newcomm)) {
throw std::runtime_error("MPI_Comm_create failed");
return MPI_COMM_NULL;
}
return newcomm;
}
MPI_Comm comm_create(const std::vector<int> &incl, MPI_Comm comm) {
MPI_Group group_old;
MPI_Group group_new;
MPI_Comm newcomm;
int size;
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
size = comm_size(comm);
if (size != incl.size()) {
throw std::runtime_error("comm_create size mismatch");
return MPI_COMM_NULL;
}
if (MPI_SUCCESS != MPI_Comm_group(comm, &group_old)) {
throw std::runtime_error("MPI_Comm_group failed");
return MPI_COMM_NULL;
}
if (MPI_SUCCESS != MPI_Group_incl(group_old, size, &incl[0], &group_new)) {
throw std::runtime_error("MPI_Group_incl failed");
return MPI_COMM_NULL;
}
if (MPI_SUCCESS != MPI_Comm_create(comm, group_new, &newcomm)) {
throw std::runtime_error("MPI_Comm_create failed");
return MPI_COMM_NULL;
}
return newcomm;
}
void comm_free(MPI_Comm comm) {
if (MPI_SUCCESS != MPI_Comm_free(&comm)) {
throw std::runtime_error("MPI_Comm_free failed");
}
}
int comm_rank(MPI_Comm comm) {
int rank = 0;
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Comm_rank(comm, &rank)) {
throw std::runtime_error("MPI_Comm_size failed");
return 0;
}
return rank;
}
int comm_size(MPI_Comm comm) {
int size = 0;
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Comm_size(comm, &size)) {
throw std::runtime_error("MPI_Comm_size failed");
return 0;
}
return size;
}
int node_rank(MPI_Comm comm) {
int size = 0;
int rank = 0;
int node = 0;
long my_hostid = 0;
long *hostid = NULL;
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
size = comm_size(comm);
rank = comm_rank(comm);
hostid = new long[size];
my_hostid = gethostid();
if (MPI_SUCCESS != MPI_Allgather(&my_hostid, 1, MPI_LONG,
hostid, 1, MPI_LONG, comm)) {
delete [] hostid;
throw std::runtime_error("MPI_Allgather failed");
return 0;
}
for (int i=0; i<rank; ++i) {
if (hostid[i] == hostid[rank]) {
++node;
}
}
delete [] hostid;
return node;
}
int node_size(MPI_Comm comm) {
int size = 0;
int rank = 0;
int node = 0;
long *hostid = NULL;
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
size = comm_size(comm);
rank = comm_rank(comm);
hostid = new long[size];
hostid[rank] = gethostid();
if (MPI_SUCCESS != MPI_Allgather(MPI_IN_PLACE, 0, MPI_LONG,
hostid, 1, MPI_LONG, comm)) {
delete [] hostid;
throw std::runtime_error("MPI_Allgather failed");
return 0;
}
for (int i=0; i<size; ++i) {
if (hostid[i] == hostid[rank]) {
++node;
}
}
delete [] hostid;
return node;
}
template <>
MPI_Datatype datatype<float>() {
return MPI_FLOAT;
}
template <>
MPI_Datatype datatype<double>() {
return MPI_DOUBLE;
}
void allreduce_copy(const float& sendbuf, float& recvbuf, MPI_Op op,
MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Allreduce((void*)&sendbuf, &recvbuf, 1,
MPI_FLOAT, op, comm)) {
throw std::runtime_error("MPI_Allreduce failed (allreduce_copy 1 float)");
}
}
void allreduce_copy(const double& sendbuf, double& recvbuf, MPI_Op op,
MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Allreduce((void*)&sendbuf, &recvbuf, 1,
MPI_DOUBLE, op, comm)) {
throw std::runtime_error("MPI_Allreduce failed (allreduce_copy 1 double)");
}
}
void allreduce_copy(const float* sendbuf, float* recvbuf, int count,
MPI_Op op, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Allreduce((void*)sendbuf, recvbuf, count,
MPI_FLOAT, op, comm)) {
throw std::runtime_error("MPI_Allreduce failed (allreduce_copy float)");
}
}
void allreduce_copy(const double* sendbuf, double* recvbuf, int count,
MPI_Op op, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Allreduce((void*)sendbuf, recvbuf, count,
MPI_DOUBLE, op, comm)) {
throw std::runtime_error("MPI_Allreduce failed (allreduce_copy double)");
}
}
void allreduce(float& buffer, MPI_Op op, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Allreduce(MPI_IN_PLACE, &buffer, 1,
MPI_FLOAT, op, comm)) {
throw std::runtime_error("MPI_Allreduce failed (allreduce 1 float)");
}
}
void allreduce(double& buffer, MPI_Op op, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Allreduce(MPI_IN_PLACE, &buffer, 1,
MPI_DOUBLE, op, comm)) {
throw std::runtime_error("MPI_Allreduce failed (allreduce 1 double)");
}
}
void allreduce(float* buffer, int count, MPI_Op op, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Allreduce(MPI_IN_PLACE, buffer, count,
MPI_FLOAT, op, comm)) {
throw std::runtime_error("MPI_Allreduce failed (allreduce float)");
}
}
void allreduce(double* buffer, int count, MPI_Op op, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Allreduce(MPI_IN_PLACE, buffer, count,
MPI_DOUBLE, op, comm)) {
throw std::runtime_error("MPI_Allreduce failed (allreduce double)");
}
}
void iallreduce(MPI_Request &request, float* buffer, int count, MPI_Op op, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Iallreduce(MPI_IN_PLACE, buffer, count,
MPI_FLOAT, op, comm, &request)) {
throw std::runtime_error("MPI_Iallreduce failed (allreduce float)");
}
}
void iallreduce(MPI_Request &request, double* buffer, int count, MPI_Op op, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Iallreduce(MPI_IN_PLACE, buffer, count,
MPI_DOUBLE, op, comm, &request)) {
throw std::runtime_error("MPI_Iallreduce failed (allreduce double)");
}
}
void bcast(unsigned long &buffer, int root, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Bcast(&buffer, 1, MPI_UNSIGNED_LONG, root, comm)) {
throw std::runtime_error("MPI_Bcast 1 unsigned long failed");
}
}
void bcast(std::vector<int> &buffer, int root, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Bcast(&buffer[0], buffer.size(), MPI_INT, root, comm)) {
throw std::runtime_error("MPI_Bcast vector<int> failed");
}
}
void bcast(signed char* buffer, int count, int root, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Bcast(buffer, count, MPI_CHAR, root, comm)) {
throw std::runtime_error("MPI_Bcast signed char failed");
}
}
void bcast(int* buffer, int count, int root, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Bcast(buffer, count, MPI_INT, root, comm)) {
throw std::runtime_error("MPI_Bcast int failed");
}
}
void bcast(float* buffer, int count, int root, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Bcast(buffer, count, MPI_FLOAT, root, comm)) {
throw std::runtime_error("MPI_Bcast failed");
}
}
bool testall(std::vector<MPI_Request> &requests) {
int flag = 0;
if (MPI_SUCCESS != MPI_Testall(requests.size(), &requests[0], &flag, MPI_STATUSES_IGNORE)) {
throw std::runtime_error("MPI_Waitall failed");
}
return flag;
}
void waitall(std::vector<MPI_Request> &requests) {
if (MPI_SUCCESS != MPI_Waitall(requests.size(), &requests[0], MPI_STATUSES_IGNORE)) {
throw std::runtime_error("MPI_Waitall failed");
}
}
bool test(MPI_Request &request) {
int flag = 0;
if (MPI_SUCCESS != MPI_Test(&request, &flag, MPI_STATUS_IGNORE)) {
throw std::runtime_error("MPI_Test failed");
}
return flag;
}
void bcast(double* buffer, int count, int root, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Bcast(buffer, count, MPI_DOUBLE, root, comm)) {
throw std::runtime_error("MPI_Bcast failed");
}
}
void send(const float* buffer, int count, int dest, int tag, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Send(buffer, count, MPI_FLOAT, dest, tag, comm)) {
throw std::runtime_error("MPI_Send failed (float)");
}
}
void send(const double* buffer, int count, int dest, int tag, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Send(buffer, count, MPI_DOUBLE, dest, tag, comm)) {
throw std::runtime_error("MPI_Send failed (double)");
}
}
void recv(float *buffer, int count, int source, int tag, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Recv(buffer, count, MPI_FLOAT, source, tag, comm, MPI_STATUS_IGNORE)) {
throw std::runtime_error("MPI_Recv failed (float)");
}
}
void recv(double *buffer, int count, int source, int tag, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Recv(buffer, count, MPI_DOUBLE, source, tag, comm, MPI_STATUS_IGNORE)) {
throw std::runtime_error("MPI_Recv failed (double)");
}
}
void sendrecv(const int *sendbuf, int sendcount, int dest, int sendtag,
int *recvbuf, int recvcount, int source, int recvtag,
MPI_Comm comm)
{
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Sendrecv(sendbuf, sendcount, MPI_INT, dest, sendtag,
recvbuf, recvcount, MPI_INT, source, recvtag,
comm, MPI_STATUS_IGNORE)) {
throw std::runtime_error("MPI_Sendrecv failed (int)");
}
}
void sendrecv(const signed char *sendbuf, int sendcount, int dest, int sendtag,
signed char *recvbuf, int recvcount, int source, int recvtag,
MPI_Comm comm)
{
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Sendrecv(sendbuf, sendcount, MPI_CHAR, dest, sendtag,
recvbuf, recvcount, MPI_CHAR, source, recvtag,
comm, MPI_STATUS_IGNORE)) {
throw std::runtime_error("MPI_Sendrecv failed (char)");
}
}
void sendrecv(const float *sendbuf, int sendcount, int dest, int sendtag,
float *recvbuf, int recvcount, int source, int recvtag,
MPI_Comm comm)
{
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Sendrecv(sendbuf, sendcount, MPI_FLOAT, dest, sendtag,
recvbuf, recvcount, MPI_FLOAT, source, recvtag,
comm, MPI_STATUS_IGNORE)) {
throw std::runtime_error("MPI_Sendrecv failed (float)");
}
}
void sendrecv(const double *sendbuf, int sendcount, int dest, int sendtag,
double *recvbuf, int recvcount, int source, int recvtag,
MPI_Comm comm)
{
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Sendrecv(sendbuf, sendcount, MPI_DOUBLE, dest, sendtag,
recvbuf, recvcount, MPI_DOUBLE, source, recvtag,
comm, MPI_STATUS_IGNORE)) {
throw std::runtime_error("MPI_Sendrecv failed (double)");
}
}
void isend(MPI_Request &request, const signed char* buffer, int count, int dest, int tag, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Isend(buffer, count, MPI_CHAR, dest, tag, comm, &request)) {
throw std::runtime_error("MPI_Isend failed (signed char)");
}
}
void isend(MPI_Request &request, const int* buffer, int count, int dest, int tag, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Isend(buffer, count, MPI_INT, dest, tag, comm, &request)) {
throw std::runtime_error("MPI_Isend failed (int)");
}
}
void isend(MPI_Request &request, const float* buffer, int count, int dest, int tag, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Isend(buffer, count, MPI_FLOAT, dest, tag, comm, &request)) {
throw std::runtime_error("MPI_Isend failed (float)");
}
}
void isend(MPI_Request &request, const double* buffer, int count, int dest, int tag, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Isend(buffer, count, MPI_DOUBLE, dest, tag, comm, &request)) {
throw std::runtime_error("MPI_Isend failed (double)");
}
}
void irecv(MPI_Request &request, signed char *buffer, int count, int source, int tag, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Irecv(buffer, count, MPI_CHAR, source, tag, comm, &request)) {
throw std::runtime_error("MPI_Irecv failed (signed char)");
}
}
void irecv(MPI_Request &request, int *buffer, int count, int source, int tag, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Irecv(buffer, count, MPI_INT, source, tag, comm, &request)) {
throw std::runtime_error("MPI_Irecv failed (int)");
}
}
void irecv(MPI_Request &request, float *buffer, int count, int source, int tag, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Irecv(buffer, count, MPI_FLOAT, source, tag, comm, &request)) {
throw std::runtime_error("MPI_Irecv failed (float)");
}
}
void irecv(MPI_Request &request, double *buffer, int count, int source, int tag, MPI_Comm comm) {
if (MPI_COMM_NULL == comm) {
comm = get_comm_default();
}
if (MPI_SUCCESS != MPI_Irecv(buffer, count, MPI_DOUBLE, source, tag, comm, &request)) {
throw std::runtime_error("MPI_Irecv failed (double)");
}
}
#else
int dummy();
#endif
} // namespace mpi
} // namespace caffe
| 25.763504 | 106 | 0.665798 | [
"vector"
] |
57101b158025061f205169039f25b8cc0c34aea8 | 8,154 | cpp | C++ | module/MJplayer.cpp | haochunchang/Mahjong | 3385022d85ba765da47965694d163cfc5ab8e56a | [
"MIT"
] | null | null | null | module/MJplayer.cpp | haochunchang/Mahjong | 3385022d85ba765da47965694d163cfc5ab8e56a | [
"MIT"
] | null | null | null | module/MJplayer.cpp | haochunchang/Mahjong | 3385022d85ba765da47965694d163cfc5ab8e56a | [
"MIT"
] | null | null | null | #include <iostream>
#include <map>
#include <vector>
#include "MJplayer.h"
#include "MJhand.h"
#include "MJcollection.h"
using namespace std;
MJplayer::MJplayer() {
// cout << "Call MJplayer constructor." << endl;
_position = 0;
_money = 0;
_hand = MJhand();
count_angone = 0;
out = vector<vector<int> >(4, vector<int>(9, 0));
// 1 的上家是 4,2 的上家是 1,3 的上家是 2,4 的上家是 3
previousPlayer[1] = 4;
previousPlayer[2] = 1;
previousPlayer[3] = 2;
previousPlayer[4] = 3;
}
MJplayer::MJplayer(int money) {
// cout << "Call MJplayer constructor." << endl;
_position = 0;
_money = money;
// cout << "Money test in MJplayer." << _money << endl;
_hand = MJhand();
count_angone = 0;
out = vector<vector<int> >(4, vector<int>(9, 0));
// 1 的上家是 4,2 的上家是 1,3 的上家是 2,4 的上家是 3
previousPlayer[1] = 4;
previousPlayer[2] = 1;
previousPlayer[3] = 2;
previousPlayer[4] = 3;
}
MJplayer::MJplayer(int pos, int money, MJtile* t, int n) {
// cout << "Call MJplayer constructor with input value." << endl;
_position = pos;
_money = money;
_hand = MJhand(t, n);
count_angone = 0;
out = vector<vector<int> >(4, vector<int>(9, 0));
// 1 的上家是 4,2 的上家是 1,3 的上家是 2,4 的上家是 3
previousPlayer[1] = 4;
previousPlayer[2] = 1;
previousPlayer[3] = 2;
previousPlayer[4] = 3;
}
MJplayer::~MJplayer() {
}
void MJplayer::Set_Pos(int position) {
_position = position;
return;
}
int MJplayer::Get_Pos() const {
return _position;
}
void MJplayer::Set_Mon(int money) {
_money = money;
return;
}
int MJplayer::Get_Mon() const {
// cout << "Money test in MJplayer::Get_Mon." << _money << endl;
return _money;
}
int MJplayer::faceup_len() const {
return _hand.faceup_len();
}
void MJplayer::Set_Hand(MJhand& input) {
_hand = input;
return;
}
void MJplayer::Set_Hand(MJtile* mjtiles, int number) {
_hand = MJhand(mjtiles, number);
return;
}
void MJplayer::Print_Hand() const {
// public showing
cout << _hand;
return;
}
void MJplayer::showhandtoothers(void) {
// only show faceup
_hand.showhandtoothers();
return;
}
void MJplayer::initiate(MJcollection& mjcol) {
_hand.initial(mjcol);
return;
}
void MJplayer::draw(MJcollection& mjcol) {
_hand.draw(mjcol);
return;
}
MJtile MJplayer::play(int index) {
return _hand.play(index);
}
void MJplayer::clear_info(void) {
out = vector<vector<int> >(4, vector<int>(9, 0));
}
// actiontype: nothing=0 eat=1 pong=2 minggone=3 angone=4 bugone=5 hu=7
void MJplayer::act(int type, int param, MJtile& t, MJcollection& mjcol) {
int index = _hand.total_len() - _hand.faceup_len();
switch (type) {
case 7:
if (param == 2)
_hand.huother(t);
if (param == 1)
_hand.huown();
break;
case 1:
_hand.eat(t, param);
break;
case 2:
_hand.pong(t);
break;
case 3:
_hand.minggone(t, mjcol);
break;
case 4:
_hand.angone(index, mjcol);
break;
case 5:
_hand.bugone(index, mjcol);
break;
default:
return;
}
return;
}
void MJplayer::strategy(int position, MJtile t, int &actiontype, int &actionparameter) {
// call after every play
// This one is for human player
int method = 0;
map<int, string> action_map;
action_map[0] = "nothing";
action_map[1] = "吃(eat)";
action_map[2] = "碰(pong)";
action_map[3] = "明槓(minggone)";
action_map[5] = "補槓(bugone)";
action_map[7] = "胡(hu)";
action_map[8] = "出牌(play)";
vector<bool> avail(9, false); // Indicator of available actions
// if 現在出牌的人是上家, check if caneat
avail[0] = true;
if (previousPlayer[_position] == position) {
//cout << "check if caneat: ";
if (_hand.caneat(t)) {
avail[1] = true;
method = _hand.caneat(t);
switch (method) {
case 3:
method = 1;
break;
case 5:
method = 1;
break;
case 6:
method = 2;
break;
case 7:
method = 1;
break;
}
}
}
// check if canpong
if (_hand.canpong(t)) {
avail[2] = true;
}
// check if canminggone
if (_hand.canminggone(t)) {
avail[3] = true;
}
// check if canbugone
// not sure if angone is needed
if (_hand.canbugone(t)) {
avail[5] = true;
}
// check if canhu
if (_hand.canhu(t)) {
avail[7] = true;
}
// your turn, you can play
if (position == _position) {
avail[8] = true;
// draw stage, you must play
if (_hand.stage() == 1) {
avail[0] = false;
}
}
// Prompt user to choose from available actions
fprintf(stdout, "You can do the following actions:\n");
for (int i = 8; i >= 0; i--) {
if (avail[i]) {
fprintf(stdout, "%d: %s\n", i, action_map[i].c_str());
}
}
int a = 0;
int action_count = -1; // 0 if only_one_action else count of available actions
for (int i = 0; i < avail.size(); i++) {
if (avail[i]) action_count++;
}
cout << "Your Hands:" << endl;
for (int i = 0; i < _hand.total_len() + _hand.faceup_len() + _hand.stage(); i++) {
if (i <= _hand.faceup_len() || i > _hand.total_len()) {
cout << " ";
} else if (i == _hand.total_len()) {
cout << " " << i - _hand.faceup_len() << " ";
} else if (i - _hand.faceup_len() < 10) {
cout << " " << i - _hand.faceup_len() << " ";
} else {
cout << " " << i - _hand.faceup_len() << " ";
}
}
cout << endl;
cout << _hand;
if (action_count) {
fprintf(stdout, "Please choose one of the actions above:\n");
fscanf(stdin, "%d", &a);
}
// Default actions in case of invalid input
if (a > 8 || a < 0 || !avail[a]) {
if (position == _position) {
fprintf(stdout, "Default: play a tile\n");
a = 8;
} else {
fprintf(stdout, "Default: do nothing\n");
a = 0;
}
}
cout << "Press \033[1;93mEnter\033[0m ...\n";
cin.sync();
cin.get();
if (a == 8) {
actiontype = 8;
int number = this->decidePlay();
actionparameter = number;
} else if (a == 1) {
actiontype = a;
actionparameter = method;
} else {
actiontype = a;
}
return;
}
int MJplayer::decidePlay(void) {
int pos = 0;
cout << "Which tile do you want to play?" << endl;
cout << "First: 1, Last: " << _hand.total_len() + _hand.stage() - _hand.faceup_len() << endl;
cin >> pos;
if (pos < 1 || pos > _hand.total_len() + _hand.stage()) {
pos = _hand.total_len() + _hand.stage();
}
return pos;
}
void MJplayer::getinfo(int position, int type, MJtile* ts, int tiles_num) {
// type: eat=1 pong=2 minggone=3 angone=4 bugone=5 applique=6
// call after any type above
int suit = ts->suit();
int rank = ts->rank();
if (type == 8) {
// someone play a tile
out[suit - 1][rank - 1] += 1;
} else if (type == 1) {
// someone eat
if (tiles_num == 1) { // (001)
out[suit - 1][rank - 2] += 1;
out[suit - 1][rank - 3] += 1;
} else { // (010)
out[suit - 1][rank] += 1;
out[suit - 1][rank - 2] += 1;
}
} else if (type == 2) {
// someone pong
out[suit - 1][rank - 1] += 2;
} else if (type == 3 || type == 5) {
// someone minggone or bugone
out[suit - 1][rank - 1] = 4;
} else if (type == 4) {
// someone angone
count_angone += 1;
}
previousTile = *ts;
return;
}
bool MJplayer::is_human(void) {
return true;
}
string MJplayer::className(void) {
return "MJplayer";
}
string MJplayer::getFunctionOrder(void) {
return "";
}
| 23.033898 | 97 | 0.524037 | [
"vector"
] |
571537a0542e1c0bb5804da0442282ebaf081ae9 | 5,685 | cc | C++ | Examples/pingpong/client.cc | rolandqi/SoL | 30b36fa4446c5c96f2e1ddc43aa951593ac9f5bf | [
"Apache-2.0"
] | 2 | 2020-05-25T10:23:51.000Z | 2020-06-02T14:51:17.000Z | Examples/pingpong/client.cc | rolandqi/SoL | 30b36fa4446c5c96f2e1ddc43aa951593ac9f5bf | [
"Apache-2.0"
] | null | null | null | Examples/pingpong/client.cc | rolandqi/SoL | 30b36fa4446c5c96f2e1ddc43aa951593ac9f5bf | [
"Apache-2.0"
] | null | null | null | #include <net/Client.h>
#include <base/logging.h>
#include <base/Thread.h>
#include <net/EventLoop.h>
#include <net/EventLoopThreadPool.h>
#include <base/Atomic.h>
// #include <boost/bind.hpp>
// #include <boost/ptr_container/ptr_vector.hpp>
#include <functional>
#include <memory>
#include <utility>
#include <stdio.h>
#include <unistd.h>
#include <algorithm>
#include <memory>
#define MAX_SIZE 1024
class PingpongClient;
struct PingPongContent
{
char size;
char body[MAX_SIZE];
};
class Session
{
public:
Session(EventLoop* loop,
int port,
const string& name,
PingpongClient* owner)
: client_(loop, 1, port),
owner_(owner),
bytesRead_(0),
bytesWritten_(0),
messagesRead_(0)
{
client_.setConnectionCallback(
std::bind(&Session::onConnection, this, _1));
client_.setMessageCallback(
std::bind(&Session::onMessage, this, _1));
start();
}
void start()
{
client_.start();
}
void stop()
{
client_.~Client();
}
int64_t bytesRead() const
{
return bytesRead_;
}
int64_t messagesRead() const
{
return messagesRead_;
}
private:
void onConnection(const int& fd);
void onMessage(int fd);
Client client_;
PingpongClient* owner_;
int64_t bytesRead_;
int64_t bytesWritten_;
int64_t messagesRead_;
};
class PingpongClient
{
public:
PingpongClient(EventLoop* loop,
int port,
int blockSize,
int sessionCount,
int timeout,
int threadCount)
: loop_(loop),
threadPool_(loop),
blockSize_(blockSize),
sessionCount_(sessionCount),
timeout_(timeout)
{
loop->runAfter(timeout, std::bind(&PingpongClient::handleTimeout, this));
if (threadCount > 1)
{
threadPool_.setThreadNum(threadCount);
}
threadPool_.start();
for (int i = 0; i < blockSize; ++i)
{
message_.push_back(static_cast<char>(i % 128));
}
for (int i = 0; i < sessionCount; ++i)
{
char buf[32];
snprintf(buf, sizeof buf, "C%05d", i);
shared_ptr<Session> session(threadPool_.getNextLoop(), port, buf, this);
session->start();
sessions_.push_back(session);
}
}
const string& message() const
{
return message_;
}
const int blockSize() const
{
return blockSize_;
}
void onConnect()
{
if (numConnected_.incrementAndGet() == sessionCount_)
{
LOG_WARN << "all connected";
}
}
void onDisconnect(const int& fd)
{
if (numConnected_.decrementAndGet() == 0)
{
LOG_WARN << "all disconnected";
int64_t totalBytesRead = 0;
int64_t totalMessagesRead = 0;
for (auto it = sessions_.begin(); it != sessions_.end(); ++it)
{
totalBytesRead += it->bytesRead();
totalMessagesRead += it->messagesRead();
}
LOG_WARN << totalBytesRead << " total bytes read";
LOG_WARN << totalMessagesRead << " total messages read";
LOG_WARN << static_cast<double>(totalBytesRead) / static_cast<double>(totalMessagesRead)
<< " average message size";
LOG_WARN << static_cast<double>(totalBytesRead) / (timeout_ * 1024 * 1024)
<< " MiB/s throughput";
conn->getLoop()->queueInLoop(std::bind(&Client::quit, this));
}
}
private:
void quit()
{
loop_->queueInLoop(std::bind(&EventLoop::quit, loop_));
}
void handleTimeout()
{
LOG_WARN << "stop";
std::for_each(sessions_.begin(), sessions_.end(),
std::mem_fn(&Session::stop));
}
EventLoop* loop_;
EventLoopThreadPool threadPool_;
int sessionCount_;
int timeout_;
std::vector<std::stared_ptr<Session>> sessions_;
string message_;
int blockSize_;
AtomicInt32 numConnected_;
};
void Session::onConnection(const int& fd)
{
LOG_INFO << "Server connected!";
owner_->onConnect();
PingPongContent myContent;
myContent.size = owner_->blockSize();
memmove(&myContent.body, owner_->message().c_str(), owner_->blockSize());
int nwrite = writen(fd, reinterpret_cast<char*>(&myContent), static_cast<int>(myContent.size) + 1);
if (nwrite != myContent.size + 1)
{
LOG_INFO << "write failed!";
}
}
int main(int argc, char* argv[])
{
if (argc != 7)
{
fprintf(stderr, "Usage: client <port> <threads> <blocksize> ");
fprintf(stderr, "<sessions> <time>\n");
}
else
{
uint16_t port = static_cast<uint16_t>(atoi(argv[1]));
int threadCount = atoi(argv[2]);
int blockSize = atoi(argv[3]);
int sessionCount = atoi(argv[4]);
int timeout = atoi(argv[5]);
EventLoop loop;
PingpongClient client(&loop, port, blockSize, sessionCount, timeout, threadCount);
loop.loop();
}
}
void Session::onMessage(int fd)
{
PingPongContent myContent;
// receive data: 1 byte length + data.
int nread = readn(fd, &myContent.size, 1); // read out the lenth of the data.
if (nread < 0)
{
LOG_INFO << "Receiving data error in fd: " << fd;
owner_->onDisconnect(fd);
}
nread = readn(fd, myContent.body, myContent.size);
if (myContent.size > 0)
{
LOG_INFO << "receiving data size: "<< static_cast<int>(myContent.size);
}
if (nread != myContent.size)
{
LOG_INFO << "Receiving data error in fd: " << fd;
}
// echo back
int nwrite = writen(fd, reinterpret_cast<char*>(&myContent), static_cast<int>(myContent.size) + 1);
if (nwrite != myContent.size + 1)
{
LOG_INFO << "write failed! write size: " << nwrite;
}
bytesWritten_ += myContent.size;
messagesRead_++;
bytesRead_ += myContent.size;
} | 22.74 | 103 | 0.618821 | [
"vector"
] |
571fe383a182eb6a9d9931b93a3f37a6de29ee06 | 2,786 | cpp | C++ | cpp/mappingdensity/mappingdensity.cpp | KazuCocoa/profilo | 29831cd73e7933a72914d96a20814a285608c539 | [
"Apache-2.0"
] | 1 | 2019-01-14T13:37:12.000Z | 2019-01-14T13:37:12.000Z | cpp/mappingdensity/mappingdensity.cpp | KazuCocoa/profilo | 29831cd73e7933a72914d96a20814a285608c539 | [
"Apache-2.0"
] | null | null | null | cpp/mappingdensity/mappingdensity.cpp | KazuCocoa/profilo | 29831cd73e7933a72914d96a20814a285608c539 | [
"Apache-2.0"
] | null | null | null | // Copyright 2004-present Facebook. All Rights Reserved.
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstring>
#include <fstream>
#include <regex>
#include <sstream>
#include <string>
#include <system_error>
#include <vector>
#include <fb/log.h>
#include <mappingdensity/mappingdensity.h>
#include <procmaps.h>
namespace facebook {
namespace profilo {
namespace mappingdensity {
void dumpMappingDensities(
std::string const& mapRegexStr,
std::string const& outFile,
std::string const& dumpName) {
struct memorymap* maps = memorymap_snapshot(getpid());
if (maps == nullptr) {
FBLOGE("failed to take memorymap snapshot: %s", std::strerror(errno));
return;
}
std::regex mapRegex(mapRegexStr);
size_t maxSize = 0;
for (struct memorymap_vma const* vma = memorymap_first_vma(maps);
vma != nullptr;
vma = memorymap_vma_next(vma)) {
if (!std::regex_search(memorymap_vma_file(vma) ?: "", mapRegex)) {
continue;
}
size_t sz = memorymap_vma_end(vma) - memorymap_vma_start(vma);
if (sz > maxSize) {
maxSize = sz;
}
}
size_t const pageSize = sysconf(_SC_PAGESIZE);
std::vector<uint8_t> buf(maxSize / pageSize + 1);
std::stringstream ss;
ss << outFile << "/mincore_" << dumpName << "_" << getpid();
std::ofstream os(ss.str());
for (struct memorymap_vma const* vma = memorymap_first_vma(maps);
vma != nullptr;
vma = memorymap_vma_next(vma)) {
if (!std::regex_search(memorymap_vma_file(vma) ?: "", mapRegex)) {
continue;
}
int ret = mincore(
reinterpret_cast<void*>(memorymap_vma_start(vma)),
memorymap_vma_end(vma) - memorymap_vma_start(vma),
buf.data());
if (ret != 0) {
FBLOGW(
"failed to get mincore for %s: %s",
memorymap_vma_file(vma),
std::strerror(errno));
}
os << memorymap_vma_file(vma) << std::ends;
os << memorymap_vma_permissions(vma) << std::ends;
uint64_t value;
value = memorymap_vma_start(vma);
os.write(reinterpret_cast<char const*>(&value), sizeof(value));
value = memorymap_vma_end(vma);
os.write(reinterpret_cast<char const*>(&value), sizeof(value));
value = (memorymap_vma_end(vma) - memorymap_vma_start(vma)) / pageSize + 1;
if (ret != 0) {
value = 0;
}
os.write(reinterpret_cast<char const*>(&value), sizeof(value));
os.write(reinterpret_cast<char const*>(buf.data()), value);
if (!os) {
FBLOGE(
"failed to write mapping data for %s to %s: %s",
memorymap_vma_file(vma),
outFile.c_str(),
std::strerror(errno));
break;
}
}
memorymap_destroy(maps);
}
} // namespace mappingdensity
} // namespace profilo
} // namespace facebook
| 27.584158 | 79 | 0.641062 | [
"vector"
] |
5722e9585459e4c62b2616b9f6a9f8f6d0e4810f | 5,593 | cpp | C++ | src/engine_helper.cpp | tomalbrc/rawket-engine | 2b7da4f33c874154120fc2d1529081f4f4ae33c7 | [
"MIT"
] | null | null | null | src/engine_helper.cpp | tomalbrc/rawket-engine | 2b7da4f33c874154120fc2d1529081f4f4ae33c7 | [
"MIT"
] | 1 | 2016-03-18T13:54:22.000Z | 2016-08-11T22:02:28.000Z | src/engine_helper.cpp | tomalbrc/FayEngine | 2b7da4f33c874154120fc2d1529081f4f4ae33c7 | [
"MIT"
] | null | null | null | //
// engine_helper.cpp
// rawket
//
// Created by Tom Albrecht on 12.12.15.
//
//
#include "engine_helper.hpp"
#include "SDL_ttf.h"
#include "texture.hpp"
#include "types.hpp"
#include <fstream>
RKT_NAMESPACE_BEGIN
engine_helper::engine_helper() {
debug_log("engine_helper::engine_helper()");
}
engine_helper::~engine_helper() {
debug_log("engine_helper::~engine_helper");
SDL_JoystickClose(0);
cleanTextureCache();
SDL_DestroyRenderer(m_gameRenderer);
SDL_DestroyWindow(SDL_GL_GetCurrentWindow());
TTF_Quit();
IMG_Quit();
SDL_Quit();
}
engine_helper* engine_helper::getInstance() {
static engine_helper theInstance;
return &theInstance;
}
SDL_Renderer* engine_helper::getRenderer() {
return m_gameRenderer;
}
void engine_helper::setRenderer(SDL_Renderer *r) {
m_gameRenderer = r;
}
app_window_ptr engine_helper::getMainWindow() {
return m_mainWindow;
}
void engine_helper::setMainWindow(app_window_ptr window) {
m_mainWindow = window;
}
void engine_helper::Init() {
if (m_initiated) return;
m_initiated = true;
if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
exit(2);
}
if(TTF_Init() == -1) {
printf("TTF_Init Error: %s\n", TTF_GetError());
exit(2);
}
if (IMG_Init(IMG_INIT_PNG | IMG_INIT_JPG) == -1) {
printf("IMG_Init Error: %s\n", IMG_GetError());
exit(2);
}
// For ios/android
// TODO: Add platform check
SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "1");
SDL_JoystickEventState(SDL_ENABLE);
SDL_JoystickOpen(0);
}
void engine_helper::setEnableVSync(bool enable) {
SDL_SetHint(SDL_HINT_RENDER_VSYNC, enable ? "1":"0");
}
vec2f engine_helper::getDiplaySize() {
SDL_DisplayMode mode;
SDL_GetCurrentDisplayMode(0, &mode);
return vec2f_make(mode.w, mode.h);
}
void engine_helper::cacheTexture(texture_ptr texture, std::string key) {
m_textureCache[key] = texture;
}
void engine_helper::cacheTextures(std::vector<texture_ptr> textures, std::vector<std::string> keys) {
for (int i = 0; i < textures.size(); i++) {
cacheTexture(textures[i], keys[i]);
}
}
void engine_helper::removeTextureForKey(std::string key) {
m_textureCache.erase(key);
}
void engine_helper::removeTextureFromCache(texture_ptr tex) {
for (auto&& iterator = m_textureCache.begin(); iterator != m_textureCache.end(); ++iterator) {
if (iterator->second == tex) {
removeTextureForKey(iterator->first);
break;
}
}
}
texture_ptr engine_helper::getTextureForKey(std::string key) {
return m_textureCache[key];
}
void engine_helper::cleanTextureCache() {
for(auto&& iterator = m_textureCache.begin(); iterator != m_textureCache.end();) {
debug_log("Cleaning up texture named: "+iterator->first+"...");
iterator = m_textureCache.erase(iterator);
}
}
void engine_helper::removeUnusedTextures() {
for(auto&& iterator = m_textureCache.begin(); iterator != m_textureCache.end();) {
if (iterator->second.use_count() == 1) debug_log("Removed unused texture named: "+iterator->first), iterator = m_textureCache.erase(iterator);
else ++iterator;
}
}
/**
* Sets the filtering mode for the renderer.
* The filtering mode is checked when a texture is created and also affects copied textures
* See types.hpp for available FilteringModes
*/
void engine_helper::setGlobalFilteringMode(FilteringMode mode) {
m_filteringMode = mode;
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, std::to_string(mode).c_str());
}
/**
* Returns the current filtering mode for the (main-)renderer
*/
FilteringMode engine_helper::getGlobalFilteringMode() {
return m_filteringMode;
}
void engine_helper::registerApp(std::string organizationName, std::string appName) {
m_basePath = SDL_GetPrefPath(organizationName.c_str(), appName.c_str());
debug_log("Registered Application: " + appName + ", pref base path is: " + m_basePath);
}
/**
* Saves an object for a key. The key is used as filename and '.bin' is appended. The location is SDL_GetPrefPath()
*/
void engine_helper::save(std::string string, std::string key) {
auto path = (m_basePath + key + ".bin").c_str();
std::ofstream file (path, std::ofstream::binary);
if (file.is_open()) file << string, file.close();
else SDL_assert(1);
}
std::string engine_helper::loadString(std::string key) {
std::ifstream file(m_basePath + key + ".bin", std::ifstream::binary);
std::string out;
file >> out;
return out;
}
void engine_helper::save(double value, std::string key) {
auto path = (m_basePath + key + ".bin").c_str();
std::ofstream file (path, std::ofstream::binary);
if (file.is_open()) file << value, file.close();
else SDL_assert(1);
}
double engine_helper::loadDouble(std::string key) {
std::ifstream file(m_basePath + key + ".bin", std::ifstream::binary);
std::string out;
file >> out;
return out.empty() ? 0.0 : std::stod(out);
}
void engine_helper::save(int value, std::string key) {
auto path = (m_basePath + key + ".bin").c_str();
std::ofstream file (path, std::ofstream::binary);
if (file.is_open()) file << value, file.close();
else SDL_assert(1);
}
int engine_helper::loadInt(std::string key) {
std::ifstream file(m_basePath + key + ".bin", std::ifstream::binary);
std::string out;
file >> out;
return out.empty() ? 0 : std::stoi(out);
}
RKT_NAMESPACE_END
| 27.150485 | 150 | 0.670839 | [
"object",
"vector"
] |
572811e9cbcce031815dea86eda296258634b056 | 2,324 | hxx | C++ | opencascade/gp_EulerSequence.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/gp_EulerSequence.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/gp_EulerSequence.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | // Created on: 1993-04-13
// Created by: JCV
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _gp_EulerSequence_HeaderFile
#define _gp_EulerSequence_HeaderFile
//! Enumerates all 24 possible variants of generalized
//! Euler angles, defining general 3d rotation by three
//! rotations around main axes of coordinate system,
//! in different possible orders.
//!
//! The name of the enumeration
//! corresponds to order of rotations, prefixed by type
//! of coordinate system used:
//! - Intrinsic: rotations are made around axes of rotating
//! coordinate system associated with the object
//! - Extrinsic: rotations are made around axes of fixed
//! (static) coordinate system
//!
//! Two specific values are provided for most frequently used
//! conventions: classic Euler angles (intrinsic ZXZ) and
//! yaw-pitch-roll (intrinsic ZYX).
enum gp_EulerSequence
{
//! Classic Euler angles, alias to Intrinsic_ZXZ
gp_EulerAngles,
//! Yaw Pitch Roll (or nautical) angles, alias to Intrinsic_ZYX
gp_YawPitchRoll,
// Tait-Bryan angles (using three different axes)
gp_Extrinsic_XYZ,
gp_Extrinsic_XZY,
gp_Extrinsic_YZX,
gp_Extrinsic_YXZ,
gp_Extrinsic_ZXY,
gp_Extrinsic_ZYX,
gp_Intrinsic_XYZ,
gp_Intrinsic_XZY,
gp_Intrinsic_YZX,
gp_Intrinsic_YXZ,
gp_Intrinsic_ZXY,
gp_Intrinsic_ZYX,
// Proper Euler angles (using two different axes, first and third the same)
gp_Extrinsic_XYX,
gp_Extrinsic_XZX,
gp_Extrinsic_YZY,
gp_Extrinsic_YXY,
gp_Extrinsic_ZYZ,
gp_Extrinsic_ZXZ,
gp_Intrinsic_XYX,
gp_Intrinsic_XZX,
gp_Intrinsic_YZY,
gp_Intrinsic_YXY,
gp_Intrinsic_ZXZ,
gp_Intrinsic_ZYZ
};
#endif // _gp_EulerSequence_HeaderFile
| 30.181818 | 81 | 0.767642 | [
"object",
"3d"
] |
572b55506335e11410ccdacdd8521e5e2c89eee7 | 9,843 | cxx | C++ | smtk/mesh/moab/ModelEntityPointLocator.cxx | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 40 | 2015-02-21T19:55:54.000Z | 2022-01-06T13:13:05.000Z | smtk/mesh/moab/ModelEntityPointLocator.cxx | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 127 | 2015-01-15T20:55:45.000Z | 2021-08-19T17:34:15.000Z | smtk/mesh/moab/ModelEntityPointLocator.cxx | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 27 | 2015-03-04T14:17:51.000Z | 2021-12-23T01:05:42.000Z | //=========================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//=========================================================================
#include "smtk/mesh/moab/ModelEntityPointLocator.h"
#include "smtk/AutoInit.h"
#include "smtk/mesh/core/CellTypes.h"
#include "smtk/mesh/core/MeshSet.h"
#include "smtk/mesh/core/Resource.h"
#include "smtk/mesh/core/TypeSet.h"
#include "smtk/mesh/moab/HandleRangeToRange.h"
#include "smtk/mesh/moab/Interface.h"
#include "smtk/model/EntityRef.h"
SMTK_THIRDPARTY_PRE_INCLUDE
#include "moab/AdaptiveKDTree.hpp"
#include "moab/BoundBox.hpp"
#include "moab/CartVect.hpp"
SMTK_THIRDPARTY_POST_INCLUDE
#include <array>
#include <cmath>
#include <random>
#ifndef M_PI
#define M_PI 3.14159265358979323846264338327950288
#endif
namespace smtk
{
namespace mesh
{
namespace moab
{
ModelEntityPointLocator::ModelEntityPointLocator() = default;
ModelEntityPointLocator::~ModelEntityPointLocator() = default;
bool ModelEntityPointLocator::closestPointOn(
const smtk::model::EntityRef& entity,
std::vector<double>& closestPoints,
const std::vector<double>& sourcePoints,
bool snapToPoint)
{
// Attempt to access the entity's mesh tessellation
smtk::mesh::MeshSet meshTessellation = entity.meshTessellation();
// If the entity has a mesh tessellation, and the mesh backend is moab, and
// the tessellation has triangles...
if (
meshTessellation.isValid() && meshTessellation.resource()->interfaceName() == "moab" &&
meshTessellation.types().hasCell(smtk::mesh::Triangle))
{
//...then we can use Moab's AdaptiveKDTree to find closest points.
const smtk::mesh::moab::InterfacePtr& interface =
std::static_pointer_cast<smtk::mesh::moab::Interface>(
meshTessellation.resource()->interface());
// This option restricts the KD tree from subdividing too much
::moab::FileOptions treeOptions("MAX_DEPTH=13");
// Construct an AdaptiveKDTree
::moab::EntityHandle treeRootSet;
::moab::AdaptiveKDTree tree(
interface->moabInterface(),
smtkToMOABRange(meshTessellation.cells().range()),
&treeRootSet,
&treeOptions);
// Prepare the output for its points
closestPoints.resize(sourcePoints.size());
// For each point, query the tree for the nearest point.
::moab::EntityHandle triangleOut;
for (std::size_t i = 0; i < sourcePoints.size(); i += 3)
{
// Identify the nearest point and the associated triangle
tree.closest_triangle(treeRootSet, &sourcePoints[i], &closestPoints[i], triangleOut);
// If point snapping is selected...
if (snapToPoint)
{
// ...access the three vertices of the nearest triangle
::moab::Range connectivity;
interface->moabInterface()->get_connectivity(&triangleOut, 1, connectivity);
std::array<double, 9> coords;
interface->moabInterface()->get_coords(connectivity, coords.data());
// Compute the squared distance betwen the source point and the vertex
std::array<double, 3> dist2 = { { 0., 0., 0. } };
for (std::size_t j = 0; j < 3; j++)
{
for (std::size_t k = 0; k < 3; k++)
{
double tmp = coords[3 * j + k] - sourcePoints[i + k];
dist2[j] += tmp * tmp;
}
}
// Assign the closest point to the coordinates of the closest vertex
std::size_t index =
std::distance(dist2.begin(), std::min_element(dist2.begin(), dist2.end()));
for (std::size_t j = 0; j < 3; j++)
{
closestPoints[i + j] = coords[3 * index + j];
}
}
}
return true;
}
return false;
}
bool ModelEntityPointLocator::randomPoint(
const smtk::model::EntityRef& entity,
const std::size_t nPoints,
std::vector<double>& points,
const std::size_t seed)
{
// Select random points on an entity based on the following:
//
// J. A. Detwiler, R. Henning, R. A. Johnson, M. G. Marino. "A Generic Surface
// Sampler for Monte Carlo Simulations." IEEE Trans.Nucl.Sci.55:2329-2333,2008
// https://arxiv.org/abs/0802.2960
//
// Here's the ansatz:
// 1. Compute a bounding sphere of radius R and origin O around the geometry
// 2. Randomly select a point D on the bounding sphere
// 3. Compute a disk of radius R through point D and tangent to the bounding
// sphere
// 4. Select a random point P on this disk
// 5. Shoot a ray from P with direction (\hat{\vec{O} - \vec{D}}) through the
// geometry
// 6. If there are multiple intersections along this ray, randomly select one
// of the intersection points
// Attempt to access the entity's mesh tessellation
smtk::mesh::MeshSet meshTessellation = entity.meshTessellation();
// If the entity has a mesh tessellation, and the mesh backend is moab, and
// the tessellation has triangles...
if (
meshTessellation.isValid() && meshTessellation.resource()->interfaceName() == "moab" &&
meshTessellation.types().hasCell(smtk::mesh::Triangle))
{
//...then we can use Moab's AdaptiveKDTree to find closest points.
const smtk::mesh::moab::InterfacePtr& interface =
std::static_pointer_cast<smtk::mesh::moab::Interface>(
meshTessellation.resource()->interface());
// This option restricts the KD tree from subdividing too much
::moab::FileOptions treeOptions("MAX_DEPTH=13");
// Construct an AdaptiveKDTree
::moab::EntityHandle treeRootSet;
::moab::AdaptiveKDTree tree(
interface->moabInterface(),
smtkToMOABRange(meshTessellation.cells().range()),
&treeRootSet,
&treeOptions);
// Prepare the output for its points
points.resize(3 * nPoints);
// Get the bounding box for the tree
::moab::BoundBox box;
tree.get_bounding_box(box);
// Get the diameter and radius of the bounding sphere for the tree
const double diameter = box.diagonal_length();
const double radius = diameter / 2.;
// Get the origin of the bounding sphere for the tree
::moab::CartVect origin;
box.compute_center(origin);
// Create a RNG to sample points on the unit line
std::mt19937 mt(static_cast<unsigned int>(seed));
std::uniform_real_distribution<double> dist(0., 1.0);
// Moab's ray intersection algorithm requires a tolerance. So, here it is.
const double tolerance = 1.e-8;
std::size_t nComputed = 0;
while (nComputed < nPoints)
{
// Select a random point on the surface of our bounding sphere
double theta = M_PI * dist(mt);
double phi = 2. * M_PI * dist(mt);
double sinTheta = std::sin(theta);
double cosTheta = std::cos(theta);
double sinPhi = std::sin(phi);
double cosPhi = std::cos(phi);
const std::array<double, 3> dUnit = { sinTheta * cosPhi, sinTheta * sinPhi, cosTheta };
const std::array<double, 3> d = { radius * dUnit[0], radius * dUnit[1], radius * dUnit[2] };
// Construct a pair of orthonormal vectors tangent to the sphere at the
// above random point
double sinThetaPlusPiOver2 = std::sin(theta + M_PI / 2.);
double cosThetaPlusPiOver2 = std::cos(theta + M_PI / 2.);
double sinPhiPlusPiOver2 = std::sin(phi + M_PI / 2.);
double cosPhiPlusPiOver2 = std::cos(phi + M_PI / 2.);
const std::array<double, 3> tangent1 = { sinThetaPlusPiOver2 * cosPhi,
sinThetaPlusPiOver2 * sinPhi,
cosThetaPlusPiOver2 };
const std::array<double, 3> tangent2 = { sinTheta * cosPhiPlusPiOver2,
sinTheta * sinPhiPlusPiOver2,
cosTheta };
// Construct a random point on a disk with radius equal to the radius of
// our bounding sphere
double bMag = radius * std::sqrt(dist(mt));
double theta2 = 2. * M_PI * dist(mt);
double sinTheta2 = std::sin(theta2);
double cosTheta2 = std::cos(theta2);
const std::array<double, 2> b = { bMag * cosTheta2, bMag * sinTheta2 };
// Superimpose the second random point onto the tangent plane of our
// bounding sphere, and offset the point according to the bounding
// sphere's origin.
std::array<double, 3> p = d;
for (unsigned int i = 0; i < 3; i++)
{
p[i] += b[0] * tangent1[i] + b[1] * tangent2[i] + origin[i];
}
// Finally, the ray trajectory is simply the negative unit d vector
std::array<double, 3> dir = { -dUnit[0], -dUnit[1], -dUnit[2] };
// Compute the intersection of our ray and the surface
std::vector<::moab::EntityHandle> trianglesOut;
std::vector<double> distanceOut;
tree.ray_intersect_triangles(
treeRootSet, tolerance, dir.data(), p.data(), trianglesOut, distanceOut, 0, diameter);
if (!distanceOut.empty())
{
// We randomly select which intersection site to use as our sample point
std::size_t index = static_cast<std::size_t>(distanceOut.size() * dist(mt));
for (std::size_t i = 0; i < 3; i++)
{
points[3 * nComputed + i] = p[i] + distanceOut[index] * dir[i];
}
++nComputed;
}
}
return true;
}
return false;
}
} // namespace moab
} // namespace mesh
} // namespace smtk
smtkDeclareExtension(
SMTKCORE_EXPORT,
moab_model_entity_point_locator,
smtk::mesh::moab::ModelEntityPointLocator);
smtkComponentInitMacro(smtk_moab_model_entity_point_locator_extension);
| 35.663043 | 98 | 0.64076 | [
"mesh",
"geometry",
"vector",
"model"
] |
5739143fadbf009a4add3a6f3aab2478938b01ed | 3,770 | hpp | C++ | include/Org/BouncyCastle/Crypto/Signers/PlainDsaEncoding.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/Org/BouncyCastle/Crypto/Signers/PlainDsaEncoding.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/Org/BouncyCastle/Crypto/Signers/PlainDsaEncoding.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: Org.BouncyCastle.Crypto.Signers.IDsaEncoding
#include "Org/BouncyCastle/Crypto/Signers/IDsaEncoding.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Org::BouncyCastle::Math
namespace Org::BouncyCastle::Math {
// Forward declaring type: BigInteger
class BigInteger;
}
// Completed forward declares
// Type namespace: Org.BouncyCastle.Crypto.Signers
namespace Org::BouncyCastle::Crypto::Signers {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: Org.BouncyCastle.Crypto.Signers.PlainDsaEncoding
class PlainDsaEncoding : public ::Il2CppObject/*, public Org::BouncyCastle::Crypto::Signers::IDsaEncoding*/ {
public:
// Creating value type constructor for type: PlainDsaEncoding
PlainDsaEncoding() noexcept {}
// Creating interface conversion operator: operator Org::BouncyCastle::Crypto::Signers::IDsaEncoding
operator Org::BouncyCastle::Crypto::Signers::IDsaEncoding() noexcept {
return *reinterpret_cast<Org::BouncyCastle::Crypto::Signers::IDsaEncoding*>(this);
}
// Get static field: static public readonly Org.BouncyCastle.Crypto.Signers.PlainDsaEncoding Instance
static Org::BouncyCastle::Crypto::Signers::PlainDsaEncoding* _get_Instance();
// Set static field: static public readonly Org.BouncyCastle.Crypto.Signers.PlainDsaEncoding Instance
static void _set_Instance(Org::BouncyCastle::Crypto::Signers::PlainDsaEncoding* value);
// public System.Byte[] Encode(Org.BouncyCastle.Math.BigInteger n, Org.BouncyCastle.Math.BigInteger r, Org.BouncyCastle.Math.BigInteger s)
// Offset: 0x1248B7C
::Array<uint8_t>* Encode(Org::BouncyCastle::Math::BigInteger* n, Org::BouncyCastle::Math::BigInteger* r, Org::BouncyCastle::Math::BigInteger* s);
// protected Org.BouncyCastle.Math.BigInteger CheckValue(Org.BouncyCastle.Math.BigInteger n, Org.BouncyCastle.Math.BigInteger x)
// Offset: 0x1248C50
Org::BouncyCastle::Math::BigInteger* CheckValue(Org::BouncyCastle::Math::BigInteger* n, Org::BouncyCastle::Math::BigInteger* x);
// protected System.Void EncodeValue(Org.BouncyCastle.Math.BigInteger n, Org.BouncyCastle.Math.BigInteger x, System.Byte[] buf, System.Int32 off, System.Int32 len)
// Offset: 0x1248D08
void EncodeValue(Org::BouncyCastle::Math::BigInteger* n, Org::BouncyCastle::Math::BigInteger* x, ::Array<uint8_t>* buf, int off, int len);
// static private System.Void .cctor()
// Offset: 0x1248E40
static void _cctor();
// public System.Void .ctor()
// Offset: 0x1248EA4
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static PlainDsaEncoding* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("Org::BouncyCastle::Crypto::Signers::PlainDsaEncoding::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<PlainDsaEncoding*, creationType>()));
}
}; // Org.BouncyCastle.Crypto.Signers.PlainDsaEncoding
#pragma pack(pop)
}
DEFINE_IL2CPP_ARG_TYPE(Org::BouncyCastle::Crypto::Signers::PlainDsaEncoding*, "Org.BouncyCastle.Crypto.Signers", "PlainDsaEncoding");
| 59.84127 | 168 | 0.727851 | [
"object"
] |
57448663141ebeea09fbc214612d140a14145722 | 11,440 | cc | C++ | src/pgesv/HPLAI_patrsv.cc | ATestGroup233/HPL-AI | 2eb76d856d9ed2bd565014e1004d735755e061c9 | [
"MIT"
] | 11 | 2021-03-16T11:21:42.000Z | 2022-01-25T20:42:16.000Z | src/pgesv/HPLAI_patrsv.cc | ATestGroup233/HPL-AI | 2eb76d856d9ed2bd565014e1004d735755e061c9 | [
"MIT"
] | 1 | 2021-03-13T18:19:54.000Z | 2021-03-20T14:07:31.000Z | src/pgesv/HPLAI_patrsv.cc | ATestGroup233/HPL-AI | 2eb76d856d9ed2bd565014e1004d735755e061c9 | [
"MIT"
] | 5 | 2021-03-16T11:21:44.000Z | 2022-02-13T05:09:24.000Z | /*
* MIT License
*
* Copyright (c) 2021 WuK
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* Include files
*/
#include "hplai.hh"
#ifdef __cplusplus
extern "C"
{
#endif
#ifdef STDC_HEADERS
void HPLAI_patrsv(
HPL_T_grid *GRID,
HPLAI_T_pmat *AMAT)
#else
void HPLAI_patrsv(GRID, AMAT)
HPL_T_grid *GRID;
HPLAI_T_pmat *AMAT;
#endif
{
/*
* Purpose
* =======
*
* HPLAI_patrsv solves an upper triangular system of linear equations.
*
* The rhs is the last column of the N by N+1 matrix A. The solve starts
* in the process column owning the Nth column of A, so the rhs b may
* need to be moved one process column to the left at the beginning. The
* routine therefore needs a column vector in every process column but
* the one owning b. The result is replicated in all process rows, and
* returned in XR, i.e. XR is of size nq = LOCq( N ) in all processes.
*
* The algorithm uses decreasing one-ring broadcast in process rows and
* columns implemented in terms of synchronous communication point to
* point primitives. The lookahead of depth 1 is used to minimize the
* critical path. This entire operation is essentially ``latency'' bound
* and an estimate of its running time is given by:
*
* (move rhs) lat + N / ( P bdwth ) +
* (solve) ((N / NB)-1) 2 (lat + NB / bdwth) +
* gam2 N^2 / ( P Q ),
*
* where gam2 is an estimate of the Level 2 BLAS rate of execution.
* There are N / NB diagonal blocks. One must exchange 2 messages of
* length NB to compute the next NB entries of the vector solution, as
* well as performing a total of N^2 floating point operations.
*
* Arguments
* =========
*
* GRID (local input) HPL_T_grid *
* On entry, GRID points to the data structure containing the
* process grid information.
*
* AMAT (local input/output) HPLAI_T_pmat *
* On entry, AMAT points to the data structure containing the
* local array information.
*
* ---------------------------------------------------------------------
*/
/*
* .. Local Variables ..
*/
MPI_Comm Ccomm, Rcomm;
HPLAI_T_AFLOAT *A = NULL, *Aprev = NULL, *Aptr, *XC = NULL,
*XR = NULL, *Xd = NULL, *Xdprev = NULL,
*W = NULL;
int Alcol, Alrow, Anpprev, Anp, Anq, Bcol,
Cmsgid, GridIsNotPx1, GridIsNot1xQ, Rmsgid,
Wfr = 0, colprev, kb, kbprev, lda, mycol,
myrow, n, n1, n1p, n1pprev = 0, nb, npcol,
nprow, rowprev, tmp1, tmp2;
/* ..
* .. Executable Statements ..
*/
#ifdef HPL_DETAILED_TIMING
HPL_ptimer(HPL_TIMING_PTRSV);
#endif
if ((n = AMAT->n) <= 0)
return;
nb = AMAT->nb;
lda = AMAT->ld;
A = AMAT->A;
XR = AMAT->X;
(void)HPL_grid_info(GRID, &nprow, &npcol, &myrow, &mycol);
Rcomm = GRID->row_comm;
Rmsgid = MSGID_BEGIN_PTRSV;
Ccomm = GRID->col_comm;
Cmsgid = MSGID_BEGIN_PTRSV + 1;
GridIsNot1xQ = (nprow > 1);
GridIsNotPx1 = (npcol > 1);
/*
* Move the rhs in the process column owning the last column of A.
*/
Mnumroc(Anp, n, nb, nb, myrow, 0, nprow);
Mnumroc(Anq, n, nb, nb, mycol, 0, npcol);
tmp1 = (n - 1) / nb;
Alrow = tmp1 - (tmp1 / nprow) * nprow;
Alcol = tmp1 - (tmp1 / npcol) * npcol;
kb = n - tmp1 * nb;
Aptr = (HPLAI_T_AFLOAT *)(A);
XC = Mptr(Aptr, 0, Anq, lda);
Mindxg2p(n, nb, nb, Bcol, 0, npcol);
if ((Anp > 0) && (Alcol != Bcol))
{
if (mycol == Bcol)
{
(void)HPLAI_send(XC, Anp, Alcol, Rmsgid, Rcomm);
}
else if (mycol == Alcol)
{
(void)HPLAI_recv(XC, Anp, Bcol, Rmsgid, Rcomm);
}
}
Rmsgid = (Rmsgid + 2 >
MSGID_END_PTRSV
? MSGID_BEGIN_PTRSV
: Rmsgid + 2);
if (mycol != Alcol)
{
for (tmp1 = 0; tmp1 < Anp; tmp1++)
XC[tmp1] = HPLAI_rzero;
}
/*
* Set up lookahead
*/
n1 = (npcol - 1) * nb;
n1 = Mmax(n1, nb);
if (Anp > 0)
{
W = (HPLAI_T_AFLOAT *)malloc((size_t)(Mmin(n1, Anp)) * sizeof(HPLAI_T_AFLOAT));
if (W == NULL)
{
HPLAI_pabort(__LINE__, "HPLAI_patrsv", "Memory allocation failed");
}
Wfr = 1;
}
Anpprev = Anp;
Xdprev = XR;
Aprev = Aptr = Mptr(Aptr, 0, Anq, lda);
tmp1 = n - kb;
tmp1 -= (tmp2 = Mmin(tmp1, n1));
MnumrocI(n1pprev, tmp2, Mmax(0, tmp1), nb, nb, myrow, 0, nprow);
if (myrow == Alrow)
{
Anpprev = (Anp -= kb);
}
if (mycol == Alcol)
{
Aprev = (Aptr -= lda * kb);
Anq -= kb;
Xdprev = (Xd = XR + Anq);
if (myrow == Alrow)
{
blas::trsv<HPLAI_T_AFLOAT, HPLAI_T_AFLOAT>(blas::Layout::ColMajor, blas::Uplo::Upper, blas::Op::NoTrans, blas::Diag::NonUnit,
kb, Aptr + Anp, lda, XC + Anp, 1);
blas::copy<HPLAI_T_AFLOAT, HPLAI_T_AFLOAT>(kb, XC + Anp, 1, Xd, 1);
}
}
rowprev = Alrow;
Alrow = MModSub1(Alrow, nprow);
colprev = Alcol;
Alcol = MModSub1(Alcol, npcol);
kbprev = kb;
n -= kb;
tmp1 = n - (kb = nb);
tmp1 -= (tmp2 = Mmin(tmp1, n1));
MnumrocI(n1p, tmp2, Mmax(0, tmp1), nb, nb, myrow, 0, nprow);
/*
* Start the operations
*/
while (n > 0)
{
if (mycol == Alcol)
{
Aptr -= lda * kb;
Anq -= kb;
Xd = XR + Anq;
}
if (myrow == Alrow)
{
Anp -= kb;
}
/*
* Broadcast (decreasing-ring) of previous solution block in previous
* process column, compute partial update of current block and send it
* to current process column.
*/
if (mycol == colprev)
{
/*
* Send previous solution block in process row above
*/
if (myrow == rowprev)
{
if (GridIsNot1xQ)
(void)HPLAI_send(Xdprev, kbprev, MModSub1(myrow, nprow),
Cmsgid, Ccomm);
}
else
{
(void)HPLAI_recv(Xdprev, kbprev, MModAdd1(myrow, nprow),
Cmsgid, Ccomm);
}
/*
* Compute partial update of previous solution block and send it to cur-
* rent column
*/
if (n1pprev > 0)
{
tmp1 = Anpprev - n1pprev;
blas::gemv<HPLAI_T_AFLOAT, HPLAI_T_AFLOAT, HPLAI_T_AFLOAT>(blas::Layout::ColMajor, blas::Op::NoTrans, n1pprev, kbprev,
-HPLAI_rone, Aprev + tmp1, lda, Xdprev, 1, HPLAI_rone,
XC + tmp1, 1);
if (GridIsNotPx1)
(void)HPLAI_send(XC + tmp1, n1pprev, Alcol, Rmsgid, Rcomm);
}
/*
* Finish the (decreasing-ring) broadcast of the solution block in pre-
* vious process column
*/
if ((myrow != rowprev) &&
(myrow != MModAdd1(rowprev, nprow)))
(void)HPLAI_send(Xdprev, kbprev, MModSub1(myrow, nprow),
Cmsgid, Ccomm);
}
else if (mycol == Alcol)
{
/*
* Current column receives and accumulates partial update of previous
* solution block
*/
if (n1pprev > 0)
{
(void)HPLAI_recv(W, n1pprev, colprev, Rmsgid, Rcomm);
blas::axpy<HPLAI_T_AFLOAT, HPLAI_T_AFLOAT>(n1pprev, HPLAI_rone, W, 1, XC + Anpprev - n1pprev, 1);
}
}
/*
* Solve current diagonal block
*/
if ((mycol == Alcol) && (myrow == Alrow))
{
blas::trsv<HPLAI_T_AFLOAT, HPLAI_T_AFLOAT>(blas::Layout::ColMajor, blas::Uplo::Upper, blas::Op::NoTrans, blas::Diag::NonUnit,
kb, Aptr + Anp, lda, XC + Anp, 1);
blas::copy<HPLAI_T_AFLOAT, HPLAI_T_AFLOAT>(kb, XC + Anp, 1, XR + Anq, 1);
}
/*
* Finish previous update
*/
if ((mycol == colprev) && ((tmp1 = Anpprev - n1pprev) > 0))
blas::gemv<HPLAI_T_AFLOAT, HPLAI_T_AFLOAT, HPLAI_T_AFLOAT>(blas::Layout::ColMajor, blas::Op::NoTrans, tmp1, kbprev, -HPLAI_rone,
Aprev, lda, Xdprev, 1, HPLAI_rone, XC, 1);
/*
* Save info of current step and update info for the next step
*/
if (mycol == Alcol)
{
Xdprev = Xd;
Aprev = Aptr;
}
if (myrow == Alrow)
{
Anpprev -= kb;
}
rowprev = Alrow;
colprev = Alcol;
n1pprev = n1p;
kbprev = kb;
n -= kb;
Alrow = MModSub1(Alrow, nprow);
Alcol = MModSub1(Alcol, npcol);
tmp1 = n - (kb = nb);
tmp1 -= (tmp2 = Mmin(tmp1, n1));
MnumrocI(n1p, tmp2, Mmax(0, tmp1), nb, nb, myrow, 0, nprow);
Rmsgid = (Rmsgid + 2 > MSGID_END_PTRSV ? MSGID_BEGIN_PTRSV : Rmsgid + 2);
Cmsgid = (Cmsgid + 2 > MSGID_END_PTRSV ? MSGID_BEGIN_PTRSV + 1 : Cmsgid + 2);
}
/*
* Replicate last solution block
*/
if (mycol == colprev)
(void)MPI_Bcast((void *)(XR), kbprev, HPLAI_MPI_AFLOAT, rowprev, Ccomm);
if (Wfr)
free(W);
#ifdef HPL_DETAILED_TIMING
HPL_ptimer(HPL_TIMING_PTRSV);
#endif
/*
* End of HPLAI_patrsv
*/
}
#ifdef __cplusplus
}
#endif
| 34.666667 | 144 | 0.503409 | [
"vector"
] |
57557fdb2afccb761d1fcef850dbdccd1c7dbb7f | 11,585 | cpp | C++ | src/main.cpp | joshshadik/vandalizer-vr | d827980878457908f25cb585481c792d50012efa | [
"MIT"
] | null | null | null | src/main.cpp | joshshadik/vandalizer-vr | d827980878457908f25cb585481c792d50012efa | [
"MIT"
] | null | null | null | src/main.cpp | joshshadik/vandalizer-vr | d827980878457908f25cb585481c792d50012efa | [
"MIT"
] | null | null | null |
#ifdef USE_WASM
#include <GLES3/gl3.h>
#include <GLES3/gl3platform.h>
#define GLFW_INCLUDE_ES3
#include <emscripten.h>
#include <emscripten/html5.h>
#include <emscripten/vr.h>
#else
#include <GL/glew.h>
#include <GL/GL.h>
#endif
#include <GLFW/glfw3.h>
#include "app.h"
#include "controls.h"
#include "resourceManager.h"
GLFWwindow* window;
static ResourceManager resourceManager;
static App app;
static Controls controls;
static int vrDisplay = -1;
static bool inVR = false;
static glm::mat4 vrProjectionMatrices[2];
static glm::mat4 vrViewMatrices[2];
static glm::ivec2 windowSize = glm::ivec2(1280, 720);
static glm::ivec2 size = windowSize;
double lastTime;
constexpr int GAMEPAD_COUNT = 2;
static int gamepads[GAMEPAD_COUNT];
static int gamepadsConnected = 0;
static void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
controls.setMouseButton(button, action, mods);
}
static void cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
{
controls.setCursorPosition(xpos / size.x, ypos / size.y);
}
static void window_resized(GLFWwindow* window, int width, int height)
{
size = glm::ivec2(width, height);
app.resize(size);
}
#ifdef USE_WASM
void report_result(int result) {
emscripten_cancel_main_loop();
if (result == 0) {
printf("Test successful!\n");
}
else {
printf("Test failed!\n");
}
#ifdef REPORT_RESULT
REPORT_RESULT(result);
#endif
}
EM_BOOL on_pointerlockchange(int eventType, const EmscriptenPointerlockChangeEvent *pointerlockChangeEvent, void *userData) {
printf("pointerlockchange, isActive=%d\n", pointerlockChangeEvent->isActive);
// This is the application-level workaround to sync HTML5 Pointer Lock with glfw cursor state.
if (!pointerlockChangeEvent->isActive) {
printf("pointerlockchange deactivated, so enabling cursor\n");
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
return 0;
}
void vr_init_callback(void* userData)
{
printf("Browser supports WebVR\n");
if (vrDisplay == -1) {
int numDisplays = emscripten_vr_count_displays();
if (numDisplays == 0) {
printf("No VR displays found!\n");
report_result(0);
return;
}
printf("%d VR displays found\n", numDisplays);
int id = -1;
char *devName;
for (int i = 0; i < numDisplays; ++i) {
VRDisplayHandle handle = emscripten_vr_get_display_handle(i);
if (vrDisplay == -1) {
/* Save first found display for more testing */
vrDisplay = handle;
devName = const_cast<char*>(emscripten_vr_get_display_name(handle));
printf("Using VRDisplay '%s' (displayId '%d')\n", devName, vrDisplay);
//VRDisplayCapabilities caps;
//if (!emscripten_vr_get_display_capabilities(handle, &caps)) {
// printf("Error: failed to get display capabilities.\n");
// report_result(1);
// return;
//}
//if (!emscripten_vr_display_connected(vrDisplay)) {
// printf("Error: expected display to be connected.\n");
// report_result(1);
// return;
//}
//printf("Display Capabilities:\n"
// "{hasPosition: %d, hasExternalDisplay: %d, canPresent: %d, maxLayers: %lu}\n",
// caps.hasPosition, caps.hasExternalDisplay, caps.canPresent, caps.maxLayers);
}
}
if (vrDisplay == -1) {
printf("Couln't find a VR display even though at least one was found.\n");
report_result(1);
return;
}
}
}
#endif
void main_loop(bool vr = false)
{
double currTime = glfwGetTime();
/* Poll for and process events */
glfwPollEvents();
app.update(currTime - lastTime);
if (vr)
{
app.overrideViewProjection(vrViewMatrices[0], vrProjectionMatrices[0]);
app.render(glm::ivec4(0, 0, size.x / 2, size.y));
app.overrideViewProjection(vrViewMatrices[1], vrProjectionMatrices[1]);
app.render(glm::ivec4(size.x / 2, 0, size.x / 2, size.y));
}
else
{
app.render(glm::ivec4(0, 0, size.x, size.y));
}
/* Swap front and back buffers */
glfwSwapBuffers(window);
controls.updateStates();
lastTime = currTime;
}
#ifdef USE_WASM
static void printMatrix(float* m) {
printf("{%f, %f, %f, %f,\n"
" %f, %f, %f, %f,\n"
" %f, %f, %f, %f,\n"
" %f, %f, %f, %f}\n",
m[0], m[1], m[2], m[3],
m[4], m[5], m[6], m[7],
m[8], m[9], m[10], m[11],
m[12], m[13], m[14], m[15]);
}
/* Render loop without argument, set in `mainLoop()` */
static void renderLoop() {
if (!inVR)
{
return;
}
VRFrameData data;
if (!emscripten_vr_get_frame_data(vrDisplay, &data)) {
printf("Could not get frame data.\n");
report_result(1);
}
memcpy(&vrViewMatrices[0][0], data.leftViewMatrix, 16 * sizeof(float));
memcpy(&vrViewMatrices[1][0], data.rightViewMatrix, 16 * sizeof(float));
memcpy(&vrProjectionMatrices[0][0], data.leftProjectionMatrix, 16 * sizeof(float));
memcpy(&vrProjectionMatrices[1][0], data.rightProjectionMatrix, 16 * sizeof(float));
int gamepadOffset = 0;
for( int i = 0; i < GAMEPAD_COUNT + gamepadOffset; ++i)
{
if (((gamepadsConnected >> i) & 1) == 1)
{
EmscriptenGamepadEvent gamepadEvent;
emscripten_get_gamepad_status(gamepads[i], &gamepadEvent);
glm::vec3 pos;
glm::quat rot;
if( (gamepadEvent.pose.poseFlags & 1) == 1)
{
pos.x = gamepadEvent.pose.position.x;
pos.y = gamepadEvent.pose.position.y;
pos.z = gamepadEvent.pose.position.z;
}
else
{
gamepadOffset += 1;
continue;
}
if( (gamepadEvent.pose.poseFlags & 8) == 8)
{
rot.x = gamepadEvent.pose.orientation.x;
rot.y = gamepadEvent.pose.orientation.y;
rot.z = gamepadEvent.pose.orientation.z;
rot.w = gamepadEvent.pose.orientation.w;
}
uint64_t pressedFlags = 0;
for( int j = 0; j < gamepadEvent.numButtons; ++j )
{
pressedFlags |= ((uint64_t) gamepadEvent.digitalButton[j] ) << j;
}
for( int aa = 0; aa < gamepadEvent.numAxes; ++aa )
{
if( aa < 4 )
{
controls.setVRControllerAxis(i - gamepadOffset, aa, gamepadEvent.axis[aa]);
}
}
controls.setVRController(i - gamepadOffset, pos, rot, pressedFlags);
}
}
main_loop(true);
if (!emscripten_vr_submit_frame(vrDisplay)) {
printf("Error: Failed to submit frame to VR display %d (second iteration)\n", vrDisplay);
report_result(1);
}
}
static void requestPresentCallback(void* userData) {
if (!emscripten_vr_set_display_render_loop(vrDisplay, renderLoop)) {
printf("Error: Failed to dereference handle while settings display render loop of device %d\n", vrDisplay);
report_result(1);
}
VREyeParameters eyeParams;
emscripten_vr_get_eye_parameters(vrDisplay, (VREye)0, &eyeParams);
glfwSetWindowSize(window, eyeParams.renderWidth * 2, eyeParams.renderHeight);
inVR = true;
}
static EM_BOOL presentVRButtonEvent(int eventType, const EmscriptenMouseEvent* mouseEvent, void* userData)
{
if (mouseEvent->button == 0 && vrDisplay != -1)
{
if (!inVR)
{
VRLayerInit init = {
"canvas",
VR_LAYER_DEFAULT_LEFT_BOUNDS,
VR_LAYER_DEFAULT_RIGHT_BOUNDS
};
if (!emscripten_vr_request_present(vrDisplay, &init, 1, requestPresentCallback, NULL)) {
printf("Request present with default canvas failed.\n");
report_result(1);
return 1;
}
}
else if (inVR)
{
emscripten_vr_cancel_display_render_loop(vrDisplay);
emscripten_vr_exit_present(vrDisplay);
inVR = false;
glfwSetWindowSize(window, windowSize.x, windowSize.y);
}
}
return 0;
}
static EM_BOOL gamepadConnectedEvent(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void* userData)
{
printf("gamepad connected %ld \n", gamepadEvent->index);
for( int i = 0; i < GAMEPAD_COUNT; ++i)
{
if (((gamepadsConnected >> i) & 1) != 1)
{
gamepadsConnected |= (1 << i);
gamepads[i] = gamepadEvent->index;
}
}
return 0;
}
static EM_BOOL gamepadDisconnectedEvent(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void* userData)
{
printf("gamepad disconnected %ld \n", gamepadEvent->index);
for (int i = 0; i < GAMEPAD_COUNT; ++i)
{
if (gamepads[i] == gamepadEvent->index)
{
gamepadsConnected &= ~(1 << i);
}
}
return 0;
}
void main_loop_wasm()
{
if (inVR)
{
}
else
{
main_loop();
}
}
#endif
int main(void)
{
#ifdef _DEBUG
printf("running in debug \n");
#endif
#ifdef USE_WASM
if (!emscripten_vr_init(vr_init_callback, NULL)) {
printf("Browser does not support WebVR\n");
}
else
{
emscripten_set_click_callback("enterVR", nullptr, 1, presentVRButtonEvent);
}
for (int i = 0; i < GAMEPAD_COUNT; ++i)
{
gamepads[i] = -1;
}
gamepadsConnected = 0;
emscripten_set_gamepadconnected_callback(nullptr, true, gamepadConnectedEvent);
emscripten_set_gamepaddisconnected_callback(nullptr, true, gamepadDisconnectedEvent);
#endif
printf("app size: %d bytes \n", sizeof(App));
/* Initialize the library */
if (!glfwInit())
return -1;
//glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
//glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
//glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef USE_WASM
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
#else
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
#endif
glfwWindowHint(GLFW_SAMPLES, 0);
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(windowSize.x, windowSize.y, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
glfwSetWindowSizeCallback(window, window_resized);
/* Make the window's context current */
glfwMakeContextCurrent(window);
#ifdef USE_WASM
#else
glewExperimental = GL_TRUE;
glewInit();
#endif
app.init();
app.resize(size);
app.setControls(&controls);
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetCursorPosCallback(window, cursor_position_callback);
lastTime = glfwGetTime();
#ifdef USE_WASM
emscripten_set_pointerlockchange_callback(NULL, NULL, 0, on_pointerlockchange);
emscripten_set_main_loop(main_loop_wasm, 0, 1);
#else
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
//app.render();
main_loop();
}
#endif
glfwTerminate();
return 0;
} | 26.092342 | 125 | 0.601813 | [
"render"
] |
57597ee333f639c62d83c94c6397f786829d6174 | 8,069 | cpp | C++ | copygc/gc.cpp | knizhnik/cppgc | 43569f51f84281fb2cbef3a8f21d84eaf529195c | [
"Apache-2.0"
] | 16 | 2015-02-11T13:15:01.000Z | 2021-12-21T09:38:35.000Z | copygc/gc.cpp | knizhnik/cppgc | 43569f51f84281fb2cbef3a8f21d84eaf529195c | [
"Apache-2.0"
] | 2 | 2017-08-08T13:02:39.000Z | 2017-11-27T09:50:32.000Z | copygc/gc.cpp | knizhnik/cppgc | 43569f51f84281fb2cbef3a8f21d84eaf529195c | [
"Apache-2.0"
] | 1 | 2015-11-20T16:00:27.000Z | 2015-11-20T16:00:27.000Z | #include <new>
#include "gc.h"
namespace GC
{
ThreadContext<MemoryAllocator> MemoryAllocator::ctx;
Object* MemoryAllocator::_allocate(size_t size)
{
if (allocated > autoStartThreshold) {
gc();
}
size = (size + sizeof(ObjectHeader) + 7) & ~7; // align on 8
if (used + size > defaultSegmentSize) {
MemorySegment* newSegment = freeSegment;
if (newSegment == NULL || size > defaultSegmentSize) {
if (size > defaultSegmentSize) {
newSegment = (MemorySegment*)malloc(sizeof(MemorySegment) + size);
newSegment->next = (MemorySegment*)((size_t)usedSegment + MemorySegment::LARGE_SEGMENT);
} else {
newSegment = (MemorySegment*)malloc(sizeof(MemorySegment) + defaultSegmentSize);
newSegment->next = usedSegment;
}
newSegment->owner = this;
} else {
newSegment = freeSegment;
freeSegment = newSegment->next;
newSegment->next = usedSegment;
}
usedSegment = newSegment;
used = 0;
}
ObjectHeader* hdr = (ObjectHeader*)((char*)(usedSegment + 1) + used);
Object* obj = (Object*)(hdr + 1);
used += size;
allocated += size;
hdr->segment = usedSegment;
if (clonedObject != NULL) {
clonedObject->getHeader()->copy = (size_t)obj | ObjectHeader::GC_COPIED;
}
return obj;
}
void MemoryAllocator::_visit(AnyWeakRef* wref)
{
if (wref->obj != NULL) {
wref->next = weakReferences;
weakReferences = wref;
}
}
void MemoryAllocator::_registerRoot(Root* root)
{
root->next = roots;
roots = root;
}
void MemoryAllocator::_unregisterRoot(Root* root)
{
Root *rp, **rpp;
for (rpp = &roots; (rp = *rpp) != root; rpp = &rp->next) {
assert(rp != NULL);
}
*rpp = rp->next;
}
void MemoryAllocator::_registerPin(Pin* pin)
{
pin->next = pinnedObjects;
pinnedObjects = pin;
}
void MemoryAllocator::_unregisterPin(Pin* pin)
{
Pin *p, **pp;
for (pp = &pinnedObjects; (p = *pp) != pin; pp = &p->next) {
assert(p != NULL);
}
*pp = p->next;
}
Object* MemoryAllocator::_copy(Object* obj)
{
if (obj != NULL) {
ObjectHeader* hdr = obj->getHeader();
if (hdr->copy & ObjectHeader::GC_COPIED) {
return (Object*)(hdr->copy - ObjectHeader::GC_COPIED);
} else if ((Object*)hdr->copy == obj) { // pinned object
hdr->copy = (size_t)obj + ObjectHeader::GC_COPIED;
(void)obj->clone(this);
} else if (hdr->segment->owner == this) {
clonedObject = obj;
obj = obj->clone(this);
clonedObject = NULL;
}
}
return obj;
}
void MemoryAllocator::_copy(Object** refs, size_t nRefs)
{
for (size_t i = 0; i < nRefs; i++) {
refs[i] = _copy(refs[i]);
}
}
void MemoryAllocator::_allowGC()
{
if (allocated > startThreshold) {
_gc();
}
}
MemoryAllocator* MemoryAllocator::getCurrent()
{
MemoryAllocator* allocator = ctx.get();
assert(allocator != NULL);
return allocator;
}
size_t MemoryAllocator::totalAllocated() {
return getCurrent()->_totalAllocated();
}
Object* MemoryAllocator::allocate(size_t size)
{
return getCurrent()->_allocate(size);
}
void MemoryAllocator::visit(AnyWeakRef* wref)
{
MemoryAllocator* curr = ctx.get();
if (curr != NULL) {
curr->_visit(wref);
}
}
void MemoryAllocator::registerRoot(Root* root)
{
getCurrent()->_registerRoot(root);
}
void MemoryAllocator::unregisterRoot(Root* root)
{
getCurrent()->_unregisterRoot(root);
}
Object* MemoryAllocator::copy(Object* obj)
{
if (obj != NULL) {
MemoryAllocator* allocator = getCurrent();
if (allocator != NULL) {
obj = allocator->_copy(obj);
}
}
return obj;
}
void MemoryAllocator::registerPin(Pin* pin)
{
getCurrent()->_registerPin(pin);
}
void MemoryAllocator::unregisterPin(Pin* pin)
{
getCurrent()->_unregisterPin(pin);
}
void MemoryAllocator::gc()
{
getCurrent()->_gc();
}
void MemoryAllocator::allowGC()
{
getCurrent()->_allowGC();
}
MemoryAllocator::MemoryAllocator(size_t segmentSize, size_t gcStartThreshold, size_t gcAutoStartThreshold)
{
usedSegment = NULL;
freeSegment = NULL;
used = defaultSegmentSize = segmentSize;
allocated = 0;
roots = NULL;
clonedObject = NULL;
pinnedObjects = NULL;
startThreshold = gcStartThreshold;
autoStartThreshold = gcAutoStartThreshold;
ctx.set(this);
}
MemoryAllocator::~MemoryAllocator()
{
MemorySegment *curr, *next;
for (curr = freeSegment; curr != NULL; curr = next) {
next = curr->next;
delete curr;
}
for (curr = usedSegment; curr != NULL; curr = next) {
next = (MemorySegment*)((size_t)curr->next & ~MemorySegment::MASK);
delete curr;
}
}
void MemoryAllocator::_gc()
{
size_t saveStartThreshold = autoStartThreshold;
MemorySegment* old = usedSegment;
// Garbage collector will copy accessible objects in new segments
usedSegment = NULL;
autoStartThreshold = (size_t)-1; // disable recusrive start of GC
used = defaultSegmentSize;
weakReferences = NULL;
// First of all pin objects
for (Pin* pin = pinnedObjects; pin != NULL; pin = pin->next) {
ObjectHeader* hdr = pin->obj->getHeader();
hdr->segment->next = (MemorySegment*)((size_t)hdr->segment->next | MemorySegment::PINNED_SEGMENT);
hdr->copy = (size_t)pin->obj;
}
// Now clone objects referenced from pinned objects
for (Pin* pin = pinnedObjects; pin != NULL; pin = pin->next) {
(void)_copy(pin->obj);
}
// And finally copy and adjust all roots
for (Root* root = roots; root != NULL; root = root->next) {
root->copy(this);
}
// Reset all weak references to dead objects
for (AnyWeakRef* wref = weakReferences; wref != NULL; wref = wref->next) {
ObjectHeader* hdr = wref->obj->getHeader();
if (hdr->copy & ObjectHeader::GC_COPIED) {
wref->obj = (Object*)(hdr->copy - ObjectHeader::GC_COPIED);
} else if (hdr->segment->owner == this) {
wref->obj = NULL;
}
}
// Copy phase is done
// Now traverse list of old segments
while (old != NULL) {
size_t next = (size_t)old->next;
if (next & MemorySegment::PINNED_SEGMENT) { // segment contains pinned objects, reclaim it
old->next = (MemorySegment*)((size_t)usedSegment | (next & MemorySegment::LARGE_SEGMENT));
usedSegment = old;
} else {
if (next & MemorySegment::LARGE_SEGMENT) {
delete old;
} else {
old->next = freeSegment;
freeSegment = old;
}
}
old = (MemorySegment*)(next & ~MemorySegment::MASK);
}
allocated = 0;
autoStartThreshold = saveStartThreshold;
}
}
| 30.680608 | 110 | 0.519891 | [
"object"
] |
575b1975ff2f4216c00e465d47509c14150a5cbd | 2,319 | hpp | C++ | redfish-core/include/utils/name_utils.hpp | raviteja-b/bmcweb | 267e39ad24ac55bf965fa8b12c592ce98f7f95ab | [
"Apache-2.0"
] | null | null | null | redfish-core/include/utils/name_utils.hpp | raviteja-b/bmcweb | 267e39ad24ac55bf965fa8b12c592ce98f7f95ab | [
"Apache-2.0"
] | null | null | null | redfish-core/include/utils/name_utils.hpp | raviteja-b/bmcweb | 267e39ad24ac55bf965fa8b12c592ce98f7f95ab | [
"Apache-2.0"
] | null | null | null |
#pragma once
#include <async_resp.hpp>
#include <algorithm>
#include <string>
#include <variant>
#include <vector>
namespace redfish
{
namespace name_util
{
/**
* @brief Populate the collection "Members" from a GetSubTreePaths search of
* inventory
*
* @param[i,o] asyncResp Async response object
* @param[i] path D-bus object path to find the find pretty name
* @param[i] services List of services to exporting the D-bus object path
* @param[i] namePath Json pointer to the name field to update.
*
* @return void
*/
inline void getPrettyName(
const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
const std::string& path,
const std::vector<std::pair<std::string, std::vector<std::string>>>&
services,
const nlohmann::json_pointer<nlohmann::json>& namePath)
{
BMCWEB_LOG_DEBUG << "Get PrettyName for: " << path;
// Ensure we only got one service back
if (services.size() != 1)
{
BMCWEB_LOG_ERROR << "Invalid Service Size " << services.size();
for (const auto& service : services)
{
BMCWEB_LOG_ERROR << "Invalid Service Name: " << service.first;
}
if (asyncResp)
{
messages::internalError(asyncResp->res);
}
return;
}
crow::connections::systemBus->async_method_call(
[asyncResp, path,
namePath](const boost::system::error_code ec,
const std::variant<std::string>& prettyName) {
if (ec)
{
BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
return;
}
const std::string* value = std::get_if<std::string>(&prettyName);
if (!value)
{
BMCWEB_LOG_ERROR << "Failed to get Pretty Name for " << path;
messages::internalError(asyncResp->res);
return;
}
if (value->empty())
{
return;
}
BMCWEB_LOG_DEBUG << "Pretty Name: " << *value;
asyncResp->res.jsonValue[namePath] = *value;
},
services[0].first, path, "org.freedesktop.DBus.Properties", "Get",
"xyz.openbmc_project.Inventory.Item", "PrettyName");
}
} // namespace name_util
} // namespace redfish
| 27.282353 | 77 | 0.573954 | [
"object",
"vector"
] |
575b73a03bbecf0e7c9c437bd48c742303d80a25 | 1,638 | cpp | C++ | modules/gate_ops/bit_group/test_bit_group.cpp | ICHEC/QNLP | 2966c7f71e6979c7ddef62520c3749cf6473fabe | [
"Apache-2.0"
] | 29 | 2020-04-13T04:40:35.000Z | 2021-12-17T11:21:35.000Z | modules/gate_ops/bit_group/test_bit_group.cpp | ICHEC/QNLP | 2966c7f71e6979c7ddef62520c3749cf6473fabe | [
"Apache-2.0"
] | 6 | 2020-03-12T17:40:00.000Z | 2021-01-20T12:15:08.000Z | modules/gate_ops/bit_group/test_bit_group.cpp | ICHEC/QNLP | 2966c7f71e6979c7ddef62520c3749cf6473fabe | [
"Apache-2.0"
] | 9 | 2020-09-28T05:00:30.000Z | 2022-03-04T02:11:49.000Z | /**
* @file test_arithmetic.cpp
* @author Lee J. O'Riordan (lee.oriordan@ichec.ie)
* @brief Tests for quantum arithmetic using the (QFT) implementation.
* @version 0.1
* @date 2019-09-10
*
* @copyright Copyright (c) 2019
*
*/
//#define CATCH_CONFIG_RUNNER
//#define CATCH_CONFIG_MAIN
#include "catch2/catch.hpp"
#include "Simulator.hpp"
#include "IntelSimulator.cpp"
#include <memory>
#include "bit_group.hpp"
using namespace QNLP;
#include <bitset>
/**
* @brief Test BitGroup
*
*/
TEST_CASE("Test bit grouping","[bitgroup]"){
std::size_t num_qubits = 8;
std::vector<std::size_t> reg, aux;
for (int i = 0; i < num_qubits; i++){
if(i < num_qubits-2){ reg.push_back(i); }
else{ aux.push_back(i); }
}
std::cout << reg.size() << " | "<< aux.size() << std::endl;
IntelSimulator sim(num_qubits);
BitGroup<decltype(sim)> bg;
auto& r = sim.getQubitRegister();
/*
SECTION("Group to right |010100>|10> -> |000011>|10>"){
sim.initRegister();
sim.applyGateX(reg[1]);
sim.applyGateX(reg[3]);
sim.applyGateX(aux[0]);
bg.bit_swap_s2e(sim, reg, aux);
sim.PrintStates("Post");
}*/
SECTION("Group to right |010000>|10> + |011000>|10> -> |000001>|10> + |000011>|10>"){
sim.initRegister();
sim.applyGateX(reg[1]);
sim.applyGateH(reg[2]);
sim.applyGateX(aux[0]);
bg.bit_group(sim, reg, aux, true);
sim.PrintStates("PostSuper");
}
}
// 1.00000000 + i * 0.00000000 % |100110> p=1.000000
// 1.00000000 + i * 0.00000000 % |110010> p=1.000000 | 26 | 89 | 0.586691 | [
"vector"
] |
575d2b1dac6af98086dff99c0001611aeee25bae | 1,010 | cpp | C++ | Algorithms/0199.BinaryTreeRightSideView/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/0199.BinaryTreeRightSideView/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/0199.BinaryTreeRightSideView/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | #include <vector>
#include "TreeNode.h"
#include "TreeNodeUtils.h"
#include "gtest/gtest.h"
using CommonLib::TreeNode;
namespace
{
class Solution
{
public:
std::vector<int> rightSideView(TreeNode* root) const
{
if (root == nullptr)
return {};
std::vector<int> result;
traverseTree(root, 1, result);
return result;
}
private:
void traverseTree(TreeNode* root, size_t level, std::vector<int> &data) const
{
if (level > data.size())
data.push_back(root->val);
if (root->right != nullptr)
traverseTree(root->right, level + 1, data);
if (root->left != nullptr)
traverseTree(root->left, level + 1, data);
}
};
}
using CommonLib::Codec;
namespace BinaryTreeRightSideViewTask
{
TEST(BinaryTreeRightSideViewTaskTests, Examples)
{
const Solution solution;
ASSERT_EQ(std::vector<int>({1, 3, 4}), solution.rightSideView(Codec::createTree("[1,2,3,null,5,null,4]").get()));
}
} | 20.2 | 117 | 0.619802 | [
"vector"
] |
575e66d2a53ebcd72e093a69fbd3f0a183463d0b | 2,447 | cpp | C++ | vkoo/src/core/Buffer.cpp | KaiSut0/interactive-hex-meshing | 187c926610ca5617f569405c23ab5a62b189e100 | [
"MIT"
] | 129 | 2021-09-07T17:15:18.000Z | 2022-02-28T08:59:02.000Z | vkoo/src/core/Buffer.cpp | KaiSut0/interactive-hex-meshing | 187c926610ca5617f569405c23ab5a62b189e100 | [
"MIT"
] | 2 | 2021-10-03T07:30:20.000Z | 2022-01-06T16:05:41.000Z | vkoo/src/core/Buffer.cpp | KaiSut0/interactive-hex-meshing | 187c926610ca5617f569405c23ab5a62b189e100 | [
"MIT"
] | 11 | 2021-09-08T11:29:09.000Z | 2022-03-17T08:39:50.000Z | #include "vkoo/core/Buffer.h"
#include "vkoo/core/Device.h"
#include "vkoo/utils.h"
namespace vkoo {
namespace core {
Buffer::Buffer(Device& device, VkDeviceSize size, VkBufferUsageFlags usage,
VkMemoryPropertyFlags properties)
: device_(device), size_(size), mapped_data_{nullptr}, mapped_(false) {
VkBufferCreateInfo buffer_info{};
buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_info.size = size;
buffer_info.usage = usage;
buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VK_CHECK(
vkCreateBuffer(device_.GetHandle(), &buffer_info, nullptr, &handle_));
VkMemoryRequirements mem_requirements;
vkGetBufferMemoryRequirements(device_.GetHandle(), handle_,
&mem_requirements);
VkMemoryAllocateInfo alloc_info{};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = mem_requirements.size;
alloc_info.memoryTypeIndex =
FindMemoryType(device_, mem_requirements.memoryTypeBits, properties);
VK_CHECK(
vkAllocateMemory(device_.GetHandle(), &alloc_info, nullptr, &memory_));
VK_CHECK(vkBindBufferMemory(device_.GetHandle(), handle_, memory_, 0));
}
Buffer::~Buffer() {
if (handle_ != VK_NULL_HANDLE) {
vkDestroyBuffer(device_.GetHandle(), handle_, nullptr);
}
if (memory_ != VK_NULL_HANDLE) {
vkFreeMemory(device_.GetHandle(), memory_, nullptr);
}
}
uint8_t* Buffer::Map() {
if (!mapped_ && !mapped_data_) {
vkMapMemory(device_.GetHandle(), memory_, 0, size_, 0,
reinterpret_cast<void**>(&mapped_data_));
mapped_ = true;
}
return mapped_data_;
}
void Buffer::Unmap() {
if (mapped_) {
vkUnmapMemory(device_.GetHandle(), memory_);
mapped_data_ = nullptr;
mapped_ = false;
}
}
void Buffer::Update(const std::vector<uint8_t>& data, size_t offset) {
Update(data.data(), data.size(), offset);
}
void Buffer::Update(const uint8_t* data, size_t size, size_t offset) {
Map();
std::copy(data, data + size, mapped_data_ + offset);
Unmap();
}
Buffer::Buffer(Buffer&& other)
: device_{other.device_},
size_{other.size_},
handle_{other.handle_},
memory_{other.memory_},
mapped_data_{other.mapped_data_},
mapped_{other.mapped_} {
other.handle_ = VK_NULL_HANDLE;
other.memory_ = VK_NULL_HANDLE;
other.mapped_data_ = nullptr;
other.mapped_ = false;
}
} // namespace core
} // namespace vkoo
| 28.126437 | 77 | 0.702902 | [
"vector"
] |
57650c87d1b8f9fe62c4b79ae6d2ef0f1b3965ac | 8,092 | cpp | C++ | mainwindow.cpp | pbek/QCompilerExplorer | eb5bd0a35715e81af61a43eff3f83921be2b0520 | [
"MIT"
] | 1 | 2021-11-18T05:48:30.000Z | 2021-11-18T05:48:30.000Z | mainwindow.cpp | pbek/QCompilerExplorer | eb5bd0a35715e81af61a43eff3f83921be2b0520 | [
"MIT"
] | null | null | null | mainwindow.cpp | pbek/QCompilerExplorer | eb5bd0a35715e81af61a43eff3f83921be2b0520 | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "compilerservice.h"
#include "settingsdialog.h"
#include "asmparser.h"
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>
#include <QProcess>
#include <QSettings>
#include <QSplitter>
#include <QTemporaryFile>
#include <cxxabi.h>
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
initConnections();
split = new QSplitter();
split->addWidget(ui->codeTextEdit);
split->addWidget(ui->asmTextEdit);
ui->centralwidget->layout()->addWidget(split);
QSettings settings;
auto isIntel = settings.value("intelSyntax").toBool();
ui->isIntelSyntax->setChecked(isIntel);
restoreGeometry(settings.value("geometry").toByteArray());
restoreState(settings.value("windowState").toByteArray());
CompileSvc::instance()->sendRequest(QGodBolt::Endpoints::Languages);
}
MainWindow::~MainWindow()
{
//save the value of intel syntax
QSettings settings;
settings.setValue("intelSyntax", ui->isIntelSyntax->isChecked());
settings.setValue("geometry", saveGeometry());
settings.setValue("windowState", saveState());
delete ui;
}
void MainWindow::setupLanguages(const QByteArray& data)
{
QSettings settings;
const QJsonArray json = QJsonDocument::fromJson(data).array();
ui->languagesComboBox->blockSignals(true);
for (const auto& value : json) {
const auto lang = value["name"].toString();
ui->languagesComboBox->addItem(lang, value["id"].toString());
}
ui->languagesComboBox->blockSignals(false);
auto lang = settings.value(QStringLiteral("lastUsedLanguage")).toString();
ui->languagesComboBox->setCurrentText(lang);
}
void MainWindow::updateCompilerComboBox(const QByteArray& data)
{
QSettings settings;
const QJsonArray json = QJsonDocument::fromJson(data).array();
ui->compilerComboBox->blockSignals(true);
for (const auto& value : json) {
const auto compiler = value["name"].toString();
ui->compilerComboBox->addItem(compiler, value["id"].toString());
}
ui->compilerComboBox->blockSignals(false);
auto compiler = settings.value(QStringLiteral("lastUsedCompilerFor") + ui->languagesComboBox->currentText()).toString();
ui->compilerComboBox->setCurrentText(compiler);
}
void MainWindow::updateAsmTextEdit(const QByteArray& data)
{
// std::cout << "\n\nRecieved:\n"
// << data.toStdString() << "\n";
const QJsonArray assembly = QJsonDocument::fromJson(data).object().value("asm").toArray();
QString asmText;
for (const auto& line : assembly) {
asmText.append(line["text"].toString() + "\n");
}
// qDebug() << asmText;
ui->asmTextEdit->setPlainText(asmText);
}
void MainWindow::initConnections()
{
connect(CompileSvc::instance(), &CompileSvc::languages, this, &MainWindow::setupLanguages);
connect(CompileSvc::instance(), &CompileSvc::compilers, this, &MainWindow::updateCompilerComboBox);
connect(CompileSvc::instance(), &CompileSvc::asmResult, this, &MainWindow::updateAsmTextEdit);
connect(ui->actionSettings, &QAction::triggered, this, &MainWindow::openSettingsDialog);
}
QJsonDocument MainWindow::getCompilationOptions(const QString& source, const QString& userArgs, bool isIntel) const
{
//opt obj
QJsonObject optObj;
optObj["userArguments"] = userArgs;
//compiler options obj
QJsonObject compilerObj;
compilerObj["skipAsm"] = false;
compilerObj["executorRequest"] = false;
//add compileropts to opt obj
optObj["compilerOptions"] = compilerObj;
//filters
QJsonObject filterObj;
filterObj["binary"] = false;
filterObj["commentOnly"] = true;
filterObj["demangle"] = true;
filterObj["directives"] = true;
filterObj["intel"] = isIntel;
filterObj["labels"] = true;
filterObj["execute"] = false;
optObj["filters"] = filterObj;
QJsonObject main;
// main["source"] = "int sum(){ return 2 + 2; }";
main["source"] = source;
main["options"] = optObj;
QJsonDocument doc { main };
return doc;
}
void MainWindow::on_languagesComboBox_currentIndexChanged(const QString& arg1)
{
Q_UNUSED(arg1)
const QString language = ui->languagesComboBox->currentData().toString();
const QString languageId = '/' + language;
CompileSvc::instance()->sendRequest(QGodBolt::Endpoints::Compilers, languageId);
ui->codeTextEdit->setCurrentLanguage(language);
ui->compilerComboBox->clear();
QSettings settings;
settings.setValue("lastUsedLanguage", arg1);
}
void MainWindow::on_compileButton_clicked()
{
if (ui->codeTextEdit->toPlainText().isEmpty())
return;
if (ui->localCheckbox->isChecked()) {
on_compileButtonPress();
return;
}
const QString text = ui->codeTextEdit->toPlainText();
const QString args = ui->argsLineEdit->text();
bool isIntel = ui->isIntelSyntax->isChecked();
auto data = getCompilationOptions(text, args, isIntel);
// qDebug() << data.toJson(QJsonDocument::JsonFormat::Compact);
QString endpoint = "compiler/" + ui->compilerComboBox->currentData().toString() + "/compile";
CompileSvc::instance()->compileRequest(endpoint, data.toJson());
}
void MainWindow::openSettingsDialog()
{
SettingsDialog dialog(this);
connect(&dialog, &SettingsDialog::fontChanged, ui->codeTextEdit, &QCodeEditor::updateFont);
connect(&dialog, &SettingsDialog::fontChanged, ui->asmTextEdit, [this](const QString& f) {
ui->asmTextEdit->setFont(QFont(f));
});
connect(&dialog, &SettingsDialog::fontSizeChanged, ui->asmTextEdit, [this](const qreal f) {
QFont font = ui->asmTextEdit->font();
font.setPointSize(f);
ui->asmTextEdit->setFont(font);
});
connect(&dialog, &SettingsDialog::fontSizeChanged, ui->codeTextEdit, [this](const qreal f) {
QFont font = ui->asmTextEdit->font();
font.setPointSize(f);
ui->codeTextEdit->setFont(font);
});
dialog.exec();
}
void MainWindow::on_compilerComboBox_currentIndexChanged(const QString& arg1)
{
QSettings settings;
settings.setValue("lastUsedCompilerFor" + ui->languagesComboBox->currentText(), arg1);
}
void MainWindow::on_compileButtonPress()
{
if (!ui->localCheckbox->isChecked())
return;
const QString source = ui->codeTextEdit->toPlainText();
QFile f("./x.cpp");
if (f.open(QFile::ReadWrite | QFile::Truncate | QFile::Unbuffered)) {
f.write(source.toUtf8());
bool res = f.waitForBytesWritten(3000);
qDebug () << "Res: " << res;
}
qDebug () << "Starting";
QProcess p;
p.setProgram("g++");
QString args = ui->argsLineEdit->text();
QStringList argsList;
if (!args.isEmpty())
argsList = args.split(QLatin1Char(' '));
argsList.append(QStringLiteral("-S"));
if (ui->isIntelSyntax->isChecked()) {
argsList.append(QStringLiteral("-masm=intel"));;
}
argsList.append({"-fno-asynchronous-unwind-tables",
"-fno-dwarf2-cfi-asm",
"./x.cpp"});
qDebug () << argsList;
p.setArguments(argsList);
p.start();
if (!p.waitForFinished()) {
qDebug () << "Exit status: " << p.exitStatus();
qDebug () << "Error: " << p.readAllStandardError();
return;
}
const QString error = p.readAllStandardError();
if (!error.isEmpty()) {
qDebug () << error;
qDebug () << p.error();
if (error.contains("error:")) {
ui->asmTextEdit->setPlainText("<compilation failed>\n" + error);
return;
}
}
QFile file("./x.s");
if (file.open(QFile::ReadOnly)) {
auto all = file.readAll();
AsmParser p;
QString demangled = p.demangle(std::move(all));
QString cleanAsm = p.process(demangled.toUtf8());
ui->asmTextEdit->setPlainText(cleanAsm);
} else {
qDebug () << "failed to open x.s";
}
}
| 31.609375 | 124 | 0.657192 | [
"geometry",
"object"
] |
577d623cbb983faa1ace8c6b934da7457c6ff5d8 | 332 | cpp | C++ | Dataset/Leetcode/valid/136/339.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/valid/136/339.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/valid/136/339.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
int singleNumber(vector<int>& nums) {
sort(nums.begin(), nums.end());
int i = 0;
for(; i < nums.size() - 1; i+=2) {
if(nums[i] != nums[i + 1]) {
break;
}
}
return i == nums.size() - 2 ? nums[nums.size() - 1] : nums[i];
}
};
| 20.75 | 69 | 0.418675 | [
"vector"
] |
578203933e08c7b06bae95ec0ee6abe029dbeac4 | 4,512 | cpp | C++ | tests/src/OptionalTests.cpp | TemporalResearch/trlang | 3bfb98e074cfcfd7f3f3dfe49afc7931f2366405 | [
"MIT"
] | null | null | null | tests/src/OptionalTests.cpp | TemporalResearch/trlang | 3bfb98e074cfcfd7f3f3dfe49afc7931f2366405 | [
"MIT"
] | null | null | null | tests/src/OptionalTests.cpp | TemporalResearch/trlang | 3bfb98e074cfcfd7f3f3dfe49afc7931f2366405 | [
"MIT"
] | null | null | null | //
// Created by Michael Lynch on 08/05/2021.
//
#include <trlang/functional/optional.hpp>
#include <auto_test.hpp>
#include <catch2/catch.hpp>
TEST_CASE("shouldImplicitlyConvertValueToOptional", "[3]")
{
int value = 3;
trl::optional<int> opt = value;
REQUIRE(opt.value() == value);
}
TEST_CASE("shouldNotHaveValueByDefault", "[3]")
{
trl::optional<int> opt;
REQUIRE_FALSE(opt.has_value());
}
TEST_CASE("shouldImplicitlyConvertStdOptional", "[3]")
{
int value = 3;
trl::optional<int> opt = std::make_optional<int>(3);
REQUIRE(opt.value() == value);
}
TEST_CASE("shouldAllowOperatorPassThrough", "[3]")
{
int value = 5;
trl::optional<int> opt(value);
trl::optional<int> modifiedOpt;
modifiedOpt = opt + 5;
REQUIRE(modifiedOpt.value() == value + 5);
modifiedOpt = opt - 5;
REQUIRE(modifiedOpt.value() == value - 5);
modifiedOpt = opt * 5;
REQUIRE(modifiedOpt.value() == value * 5);
modifiedOpt = opt / 5;
REQUIRE(modifiedOpt.value() == value / 5);
modifiedOpt = value;
REQUIRE(modifiedOpt == opt);
REQUIRE(opt <= modifiedOpt);
REQUIRE(opt >= modifiedOpt);
modifiedOpt = value + 5;
REQUIRE(modifiedOpt != opt);
REQUIRE(opt < modifiedOpt);
REQUIRE(modifiedOpt > opt);
}
TEST_CASE("shouldMakeEmptyOptionalsEqual", "[3]")
{
trl::optional<int> opt1;
trl::optional<int> opt2;
REQUIRE(opt1 == opt2);
}
TEST_CASE("shouldMakeEmptyOptionalLessThanFilled", "[3]")
{
trl::optional<int> empty;
trl::optional<int> filled = 5;
REQUIRE(empty < filled);
}
TEST_CASE("shouldConvertToStringForAutoTestLibrary", "[3]")
{
trl::optional<int> empty;
REQUIRE(auto_test::to_string(empty) == "trl::nullopt");
trl::optional<int> filled = 5;
REQUIRE(auto_test::to_string(filled) == "trl::opt(5)");
}
class Destructable
{
private:
bool& isAlive;
public:
Destructable(bool& aliveFlag):
isAlive(aliveFlag)
{
isAlive = true;
}
~Destructable()
{
isAlive = false;
}
};
TEST_CASE("shouldDestroyOldContentsWhenGivenNewValue", "[3]")
{
bool isAlive = true;
trl::optional<Destructable> opt = Destructable(isAlive);
opt = std::nullopt;
REQUIRE_FALSE(isAlive);
}
struct InstantiationCounter
{
static int instantiationCounter;
InstantiationCounter()
{
instantiationCounter++;
}
InstantiationCounter(const InstantiationCounter& other):
InstantiationCounter()
{
}
static void resetCounter()
{
instantiationCounter = 0;
}
};
int InstantiationCounter::instantiationCounter = 0;
TEST_CASE("shouldCopyContentsOfOtherOptionalNotShare", "[3]")
{
InstantiationCounter::resetCounter();
REQUIRE(InstantiationCounter::instantiationCounter == 0);
trl::optional<InstantiationCounter> opt1 = InstantiationCounter();
// Extra stack object created in assignment
REQUIRE(InstantiationCounter::instantiationCounter == 2);
trl::optional<InstantiationCounter> opt2 = opt1;
REQUIRE(InstantiationCounter::instantiationCounter == 3);
}
TEST_CASE("shouldMapFromOneTypeToAnother", "[3]")
{
int value = 5;
trl::optional<int> opt = value;
trl::optional<double> dOpt = opt.map<double>([&](auto i) {
double dValue = i + 0.5;
return dValue;
});
REQUIRE(dOpt > 5);
REQUIRE(dOpt < 6);
}
TEST_CASE("shouldMapTypeOfEmpty", "[3]")
{
trl::optional<int> opt;
trl::optional<std::string> dOpt = opt.map<std::string>([&](auto i) {
return "Hello world";
});
REQUIRE_FALSE(opt.has_value());
REQUIRE_FALSE(dOpt.has_value());
}
TEST_CASE("shouldFlatMapFromOneTypeToAnotherEmptyType", "[3]")
{
int value = 5;
trl::optional<int> opt = value;
trl::optional<double> dOpt = opt.flatMap<double>([&](auto i) {
return trl::optional<double>();
});
REQUIRE_FALSE(dOpt.has_value());
}
TEST_CASE("shouldFlatMapFromOneTypeToAnotherType", "[3]")
{
int value = 5;
trl::optional<int> opt = value;
trl::optional<std::string> dOpt = opt.flatMap<std::string>([&](auto i) {
trl::optional<std::string> dVal = std::string(i, '#');
return dVal;
});
REQUIRE(dOpt.value().size() == value);
}
TEST_CASE("shouldRunForEachFunction", "[3]")
{
int value = 5;
int otherNumber = 0;
trl::optional<int> opt = value;
opt.forEach([&otherNumber](auto i) {
otherNumber = i;
});
REQUIRE(otherNumber == value);
}
| 21.485714 | 76 | 0.638741 | [
"object"
] |
5783c866d6960a98100d163f94657cc88fde45f7 | 1,323 | cpp | C++ | dynamic programming/474. Ones and Zeroes.cpp | Constantine-L01/leetcode | 1f1e3a8226fcec036370e75c1d69e823d1323392 | [
"MIT"
] | 1 | 2021-04-08T10:33:48.000Z | 2021-04-08T10:33:48.000Z | dynamic programming/474. Ones and Zeroes.cpp | Constantine-L01/leetcode | 1f1e3a8226fcec036370e75c1d69e823d1323392 | [
"MIT"
] | null | null | null | dynamic programming/474. Ones and Zeroes.cpp | Constantine-L01/leetcode | 1f1e3a8226fcec036370e75c1d69e823d1323392 | [
"MIT"
] | 1 | 2021-02-23T05:58:58.000Z | 2021-02-23T05:58:58.000Z | You are given an array of binary strings strs and two integers m and n.
Return the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset.
A set x is a subset of a set y if all elements of x are also elements of y.
Example 1:
Input: strs = ["10","0001","111001","1","0"], m = 5, n = 3
Output: 4
Explanation: The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.
Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.
{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.
class Solution {
public:
int findMaxForm(vector<string>& strs, int m, int n) {
vector<vector<int>> dp(m + 1, vector(n + 1, 0));
for(string str: strs){
int zeroNum = 0;
int oneNum = 0;
for(char c: str){
if(c == '0') {
zeroNum++;
}
else {
oneNum++;
}
}
for(int i = m; i >= zeroNum; i--){
for(int j = n; j >= oneNum; j--){
dp[i][j] = max(dp[i][j], dp[i - zeroNum][j - oneNum] + 1);
}
}
}
return dp[m][n];
}
};
| 31.5 | 109 | 0.484505 | [
"vector"
] |
c232743f415e17ce85a05a7a518b552c03f530f2 | 5,380 | cpp | C++ | source/engine/systems/debug_ui_system/panels/performance_panel.cpp | DatBeQuiet/GLRenderer | 1a2d272e7f7d4e9b5283354fd2fb209621f384ab | [
"MIT"
] | 7 | 2020-07-12T09:38:26.000Z | 2020-11-22T14:04:26.000Z | source/engine/systems/debug_ui_system/panels/performance_panel.cpp | DatBeQuiet/GLRenderer | 1a2d272e7f7d4e9b5283354fd2fb209621f384ab | [
"MIT"
] | null | null | null | source/engine/systems/debug_ui_system/panels/performance_panel.cpp | DatBeQuiet/GLRenderer | 1a2d272e7f7d4e9b5283354fd2fb209621f384ab | [
"MIT"
] | null | null | null | // Copyright (c) 2019 Guillem Costa Miquel, kayter72@gmail.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:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
#include "performance_panel.h"
#include "../../../engine.h"
#include "../../renderer/renderer.h"
#include "../../renderer/gpu_profiler.h"
namespace_begin
PerformancePanel::PerformancePanel()
: BasePanel()
{
std::memset(m_lastsGeometryMs, 0, IM_ARRAYSIZE(m_lastsGeometryMs));
std::memset(m_lastsPBRMs, 0, IM_ARRAYSIZE(m_lastsPBRMs));
std::memset(m_lastsEnvironmentMs, 0, IM_ARRAYSIZE(m_lastsEnvironmentMs));
std::memset(m_lastsPostProcessMs, 0, IM_ARRAYSIZE(m_lastsPostProcessMs));
std::memset(m_lastsSampleToScreenMs, 0, IM_ARRAYSIZE(m_lastsSampleToScreenMs));
}
PerformancePanel::PerformancePanel(const std::string& name)
: BasePanel(name)
{
std::memset(m_lastsGeometryMs, 0, IM_ARRAYSIZE(m_lastsGeometryMs));
std::memset(m_lastsPBRMs, 0, IM_ARRAYSIZE(m_lastsPBRMs));
std::memset(m_lastsEnvironmentMs, 0, IM_ARRAYSIZE(m_lastsEnvironmentMs));
std::memset(m_lastsPostProcessMs, 0, IM_ARRAYSIZE(m_lastsPostProcessMs));
std::memset(m_lastsSampleToScreenMs, 0, IM_ARRAYSIZE(m_lastsSampleToScreenMs));
}
void PerformancePanel::Update()
{
GPUProfiler* profiler = Engine::Get()->renderer->GetGPUProfilerPtr();
if (ImGui::Begin(m_name.c_str()))
{
ImGui::Text("CPU");
ImGui::Separator();
// TODO: This can be heavily improved but it works for now...
ImGui::Text("GPU");
for (int i = 0; i < 49; ++i)
{
m_lastsGeometryMs[i] = m_lastsGeometryMs[i + 1];
m_lastsPBRMs[i] = m_lastsPBRMs[i + 1];
m_lastsEnvironmentMs[i] = m_lastsEnvironmentMs[i + 1];
m_lastsPostProcessMs[i] = m_lastsPostProcessMs[i + 1];
m_lastsSampleToScreenMs[i] = m_lastsSampleToScreenMs[i + 1];
}
m_lastsGeometryMs[IM_ARRAYSIZE(m_lastsGeometryMs) - 1] = profiler->GetQueryResult("Geometry");
m_lastsPBRMs[IM_ARRAYSIZE(m_lastsPBRMs) - 1] = profiler->GetQueryResult("PBR");
m_lastsEnvironmentMs[IM_ARRAYSIZE(m_lastsEnvironmentMs) - 1] = profiler->GetQueryResult("Environment");
m_lastsPostProcessMs[IM_ARRAYSIZE(m_lastsPostProcessMs) - 1] = profiler->GetQueryResult("PostProcessor");
m_lastsSampleToScreenMs[IM_ARRAYSIZE(m_lastsSampleToScreenMs) - 1] = profiler->GetQueryResult("Sample to screen");
float GPmsAvg = 0.f;
float PBRPmsAvg = 0.f;
float EPmsAvg = 0.f;
float PPPmsAvg = 0.f;
float STSPmsAvg = 0.f;
for (int i = 0; i < 50; ++i)
{
GPmsAvg += m_lastsGeometryMs[i];
PBRPmsAvg += m_lastsPBRMs[i];
EPmsAvg += m_lastsEnvironmentMs[i];
PPPmsAvg += m_lastsPostProcessMs[i];
STSPmsAvg += m_lastsSampleToScreenMs[i];
}
GPmsAvg /= 50.f;
PBRPmsAvg /= 50.f;
EPmsAvg /= 50.f;
PPPmsAvg /= 50.f;
STSPmsAvg /= 50.f;
ImGui::Text("Lasts 50 frames avg:");
ImGui::SameLine();
ImGui::TextColored(ImVec4(1.f, 0.f, 0.f, 1.f), "%f ms", (GPmsAvg + PBRPmsAvg + EPmsAvg + PPPmsAvg + STSPmsAvg));
ImGui::Text("Geometry pass:");
ImGui::SameLine();
ImGui::TextColored(ImVec4(0.f, 1.f, 0.f, 1.f), "%f ms", m_lastsGeometryMs[IM_ARRAYSIZE(m_lastsGeometryMs) - 1]);
ImGui::PlotHistogram("##gpp", m_lastsGeometryMs, IM_ARRAYSIZE(m_lastsGeometryMs), 0.f, "Ms", 0.f, GPmsAvg * 2.f, ImVec2(0, 50));
ImGui::Text("PBR pass:");
ImGui::SameLine();
ImGui::TextColored(ImVec4(0.f, 1.f, 0.f, 1.f), "%f ms", m_lastsPBRMs[IM_ARRAYSIZE(m_lastsPBRMs) - 1]);
ImGui::PlotHistogram("##pbrpp", m_lastsPBRMs, IM_ARRAYSIZE(m_lastsPBRMs), 0, "Ms", 0.f, PBRPmsAvg * 2.f, ImVec2(0, 50));
ImGui::Text("Environment pass:");
ImGui::SameLine();
ImGui::TextColored(ImVec4(0.f, 1.f, 0.f, 1.f), "%f ms", m_lastsEnvironmentMs[IM_ARRAYSIZE(m_lastsEnvironmentMs) - 1]);
ImGui::PlotHistogram("##epp", m_lastsEnvironmentMs, IM_ARRAYSIZE(m_lastsEnvironmentMs), 0.f, "Ms", 0.f, EPmsAvg * 2.f, ImVec2(0, 50));
ImGui::Text("Postprocess pass:");
ImGui::SameLine();
ImGui::TextColored(ImVec4(0.f, 1.f, 0.f, 1.f), "%f ms", m_lastsPostProcessMs[IM_ARRAYSIZE(m_lastsPostProcessMs) - 1]);
ImGui::PlotHistogram("##pppp", m_lastsPostProcessMs, IM_ARRAYSIZE(m_lastsPostProcessMs), 0.f, "Ms", 0.f, PPPmsAvg * 2.f, ImVec2(0, 50));
ImGui::Text("Sample to screen pass:");
ImGui::SameLine();
ImGui::TextColored(ImVec4(0.f, 1.f, 0.f, 1.f), "%f ms", m_lastsSampleToScreenMs[IM_ARRAYSIZE(m_lastsSampleToScreenMs) - 1]);
ImGui::PlotHistogram("##sspp", m_lastsSampleToScreenMs, IM_ARRAYSIZE(m_lastsSampleToScreenMs), 0.f, "Ms", 0.f, STSPmsAvg * 2.f, ImVec2(0, 50));
}
ImGui::End();
}
namespace_end
| 43.387097 | 145 | 0.72119 | [
"geometry"
] |
c23e0545aef052cf8d4ea1d64ae9878bc28959ff | 2,055 | hxx | C++ | resources/home/dnanexus/root/include/ROOT/RRootDS.hxx | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | null | null | null | resources/home/dnanexus/root/include/ROOT/RRootDS.hxx | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | null | null | null | resources/home/dnanexus/root/include/ROOT/RRootDS.hxx | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | 1 | 2020-05-28T23:01:44.000Z | 2020-05-28T23:01:44.000Z | // Author: Enrico Guiraud, Danilo Piparo CERN 9/2017
/*************************************************************************
* Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_RROOTTDS
#define ROOT_RROOTTDS
#include "ROOT/RDataFrame.hxx"
#include "ROOT/RDataSource.hxx"
#include <TChain.h>
#include <memory>
namespace ROOT {
namespace RDF {
class RRootDS final : public ROOT::RDF::RDataSource {
private:
unsigned int fNSlots = 0U;
std::string fTreeName;
std::string fFileNameGlob;
mutable TChain fModelChain; // Mutable needed for getting the column type name
std::vector<double *> fAddressesToFree;
std::vector<std::string> fListOfBranches;
std::vector<std::pair<ULong64_t, ULong64_t>> fEntryRanges;
std::vector<std::vector<void *>> fBranchAddresses; // first container-> slot, second -> column;
std::vector<std::unique_ptr<TChain>> fChains;
std::vector<void *> GetColumnReadersImpl(std::string_view, const std::type_info &);
public:
RRootDS(std::string_view treeName, std::string_view fileNameGlob);
~RRootDS();
std::string GetTypeName(std::string_view colName) const;
const std::vector<std::string> &GetColumnNames() const;
bool HasColumn(std::string_view colName) const;
void InitSlot(unsigned int slot, ULong64_t firstEntry);
void FinaliseSlot(unsigned int slot);
std::vector<std::pair<ULong64_t, ULong64_t>> GetEntryRanges();
bool SetEntry(unsigned int slot, ULong64_t entry);
void SetNSlots(unsigned int nSlots);
void Initialise();
};
RDataFrame MakeRootDataFrame(std::string_view treeName, std::string_view fileNameGlob);
} // ns RDF
} // ns ROOT
#endif
| 34.830508 | 98 | 0.617032 | [
"vector"
] |
c24c6974351bbefed4d070da6f922f840007018f | 5,621 | cpp | C++ | src/psac.cpp | patflick/psac | fe93e3644270d0b77131d4fcc72297c948f3d22b | [
"Apache-2.0"
] | 43 | 2015-11-12T01:11:11.000Z | 2022-03-07T13:07:46.000Z | src/psac.cpp | patflick/psac | fe93e3644270d0b77131d4fcc72297c948f3d22b | [
"Apache-2.0"
] | 3 | 2018-09-07T01:33:19.000Z | 2021-11-14T13:09:00.000Z | src/psac.cpp | patflick/psac | fe93e3644270d0b77131d4fcc72297c948f3d22b | [
"Apache-2.0"
] | 11 | 2016-01-29T20:10:56.000Z | 2021-11-01T10:43:32.000Z | /*
* Copyright 2015 Georgia Institute of Technology
*
* 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.
*/
/**
* @file ldss.cpp
* @author Patrick Flick <patrick.flick@gmail.com>
* @brief Executes and times the suffix array construction using
* libdivsufsort.
*/
// include MPI
#include <mpi.h>
// C++ includes
#include <fstream>
#include <iostream>
#include <string>
// using TCLAP for command line parsing
#include <tclap/CmdLine.h>
// distributed suffix array construction
#include <suffix_array.hpp>
#include <check_suffix_array.hpp>
#include <alphabet.hpp>
// suffix tree construction
#include <suffix_tree.hpp>
#include <check_suffix_tree.hpp>
// parallel file block decompose
#include <mxx/env.hpp>
#include <mxx/comm.hpp>
#include <mxx/file.hpp>
#include <mxx/utils.hpp>
// Timer
#include <mxx/timer.hpp>
// TODO differentiate between index types (input param or automatic based on
// size!)
typedef uint64_t index_t;
int main(int argc, char *argv[]) {
// set up MPI
mxx::env e(argc, argv);
mxx::env::set_exception_on_error();
mxx::comm comm = mxx::comm();
mxx::print_node_distribution(comm);
try {
// define commandline usage
TCLAP::CmdLine cmd("Parallel distributed suffix array and LCP construction.");
TCLAP::ValueArg<std::string> fileArg("f", "file", "Input filename.", true, "", "filename");
TCLAP::ValueArg<std::size_t> randArg("r", "random", "Random input size", true, 0, "size");
cmd.xorAdd(fileArg, randArg);
TCLAP::ValueArg<std::string> oArg("o", "outfile", "Output file base name.", false, "", "filename");
cmd.add(oArg);
TCLAP::ValueArg<int> seedArg("s", "seed", "Sets the seed for the ranom input generation", false, 0, "int");
cmd.add(seedArg);
TCLAP::SwitchArg lcpArg("l", "lcp", "Construct the LCP alongside the SA.", false);
cmd.add(lcpArg);
TCLAP::SwitchArg stArg("t", "tree", "Construct the Suffix Tree structute.", false);
cmd.add(stArg);
TCLAP::SwitchArg checkArg("c", "check", "Check correctness of SA (and LCP).", false);
cmd.add(checkArg);
cmd.parse(argc, argv);
// read input file or generate input on master processor
// block decompose input file
std::string local_str;
if (fileArg.getValue() != "") {
local_str = mxx::file_block_decompose(fileArg.getValue().c_str(), MPI_COMM_WORLD);
} else {
// TODO proper distributed random!
local_str = rand_dna(randArg.getValue()/comm.size(), seedArg.getValue() * comm.rank());
}
// TODO differentiate between index types
// run our distributed suffix array construction
mxx::timer t;
double start = t.elapsed();
if (stArg.getValue()) {
// construct SA+LCP+ST
suffix_array<char, size_t, true> sa(comm);
sa.construct(local_str.begin(), local_str.end());
double sa_time = t.elapsed() - start;
// build ST
std::vector<size_t> local_st_nodes = construct_suffix_tree(sa, local_str.begin(), local_str.end(), comm);
double st_time = t.elapsed() - sa_time;
if (comm.rank() == 0) {
std::cerr << "SA time: " << sa_time << " ms" << std::endl;
std::cerr << "ST time: " << st_time << " ms" << std::endl;
std::cerr << "Total : " << sa_time+st_time << " ms" << std::endl;
}
if (checkArg.getValue()) {
gl_check_suffix_tree(local_str, sa, local_st_nodes, comm);
}
if(oArg.getValue() != "") {
std::cerr << "Error, output of ST not supported" << std::endl;
}
} else if (lcpArg.getValue()) {
// construct SA+LCP
suffix_array<char, index_t, true> sa(comm);
sa.construct(local_str.begin(), local_str.end(), true);
double end = t.elapsed() - start;
if (comm.rank() == 0)
std::cerr << "PSAC time: " << end << " ms" << std::endl;
if (checkArg.getValue()) {
gl_check_correct(sa, local_str.begin(), local_str.end(), comm);
}
if (oArg.getValue() != "") {
// output suffix array as binary sa64
mxx::write_ordered(oArg.getValue() + ".sa64", sa.local_SA, comm);
mxx::write_ordered(oArg.getValue() + ".lcp64", sa.local_LCP, comm);
}
} else {
// construct SA
suffix_array<char, index_t, false> sa(comm);
sa.construct(local_str.begin(), local_str.end(), true);
double end = t.elapsed() - start;
if (comm.rank() == 0)
std::cerr << "PSAC time: " << end << " ms" << std::endl;
if (checkArg.getValue()) {
d_check_sa(sa, local_str.begin(), local_str.end(), comm);
}
if (oArg.getValue() != "") {
// output suffix array as binary sa64
mxx::write_ordered(oArg.getValue() + ".sa64", sa.local_SA, comm);
}
}
// catch any TCLAP exception
} catch (TCLAP::ArgException& e) {
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
exit(EXIT_FAILURE);
}
// finalize MPI
//MPI_Finalize();
return 0;
}
| 35.802548 | 113 | 0.613058 | [
"vector"
] |
c24d4f35ac2d589f883019b69f433d9b8fe2e0cb | 1,943 | cpp | C++ | Clerk/UI/TagsPopup.cpp | sergeylenkov/Clerk | b220864e89559207c5eeea113668891236fcbfb9 | [
"MIT"
] | 14 | 2016-11-01T15:48:02.000Z | 2020-07-15T13:00:27.000Z | Clerk/UI/TagsPopup.cpp | sergeylenkov/Clerk | b220864e89559207c5eeea113668891236fcbfb9 | [
"MIT"
] | 29 | 2017-11-16T04:15:33.000Z | 2021-12-22T07:15:42.000Z | Clerk/UI/TagsPopup.cpp | sergeylenkov/Clerk | b220864e89559207c5eeea113668891236fcbfb9 | [
"MIT"
] | 2 | 2018-08-15T15:25:11.000Z | 2019-01-28T12:49:50.000Z | #include "TagsPopup.h"
TagsPopup::TagsPopup(wxWindow *parent) : wxPopupWindow(parent) {
panel = new wxScrolledWindow(this, wxID_ANY);
panel->SetBackgroundColour(*wxLIGHT_GREY);
list = new wxListCtrl(panel, wxID_ANY, wxPoint(0, 0), wxSize(200, 200), wxLC_REPORT | wxLC_NO_HEADER | wxLC_SINGLE_SEL);
list->Bind(wxEVT_LIST_ITEM_ACTIVATED, &TagsPopup::OnListItemDoubleClick, this);
wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
topSizer->Add(list, 0, wxALL, 1);
panel->SetAutoLayout(true);
panel->SetSizer(topSizer);
topSizer->Fit(panel);
SetClientSize(panel->GetSize());
}
TagsPopup::~TagsPopup() {
//
}
void TagsPopup::Update(std::vector<std::shared_ptr<TagViewModel>> tags) {
_tags = tags;
list->ClearAll();
wxListItem col;
col.SetId(0);
col.SetText(_(""));
col.SetWidth(200);
list->InsertColumn(0, col);
for (unsigned int i = 0; i < tags.size(); i++) {
wxListItem listItem;
listItem.SetId(i);
list->InsertItem(listItem);
list->SetItem(i, 0, tags[i]->name);
}
list->SetItemState(0, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
}
void TagsPopup::SelectNext() {
long index = list->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (index != -1 && index < list->GetItemCount() - 1) {
index++;
list->SetItemState(index, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
list->EnsureVisible(index);
}
}
void TagsPopup::SelectPrev() {
long index = list->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (index != -1 && index > 0) {
index--;
list->SetItemState(index, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
list->EnsureVisible(index);
}
}
std::shared_ptr<TagViewModel> TagsPopup::GetSelectedTag() {
long index = list->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (index != -1) {
return _tags[index];
}
return nullptr;
}
void TagsPopup::OnListItemDoubleClick(wxListEvent &event) {
if (OnSelectTag) {
OnSelectTag();
}
} | 22.593023 | 121 | 0.710757 | [
"vector"
] |
c24dfdc79fa215300691a7e1f70a440a53dc9081 | 5,468 | cpp | C++ | wallet/trezor_key_keeper.cpp | coincash/kitap-kabile-hakk-nda | 26616a7d0e8bedc561d031f49190f896faa88233 | [
"Apache-2.0"
] | null | null | null | wallet/trezor_key_keeper.cpp | coincash/kitap-kabile-hakk-nda | 26616a7d0e8bedc561d031f49190f896faa88233 | [
"Apache-2.0"
] | 1 | 2021-07-24T13:50:37.000Z | 2021-07-24T13:50:37.000Z | wallet/trezor_key_keeper.cpp | coincash/kitap-kabile-hakk-nda | 26616a7d0e8bedc561d031f49190f896faa88233 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 The Beam Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "trezor_key_keeper.h"
#include "core/block_rw.h"
#include "utility/logger.h"
namespace beam::wallet
{
using namespace ECC;
using namespace std;
TrezorKeyKeeper::TrezorKeyKeeper()
: m_latestSlot(0)
{
}
TrezorKeyKeeper::~TrezorKeyKeeper()
{
}
Key::IPKdf::Ptr TrezorKeyKeeper::get_OwnerKdf() const
{
auto key = m_hwWallet.getOwnerKeySync();
// TODO: temporary PIN to decrypt owner key, should be removed
std::string pass = "1";
KeyString ks;
ks.SetPassword(Blob(pass.data(), static_cast<uint32_t>(pass.size())));
ks.m_sRes = key;
std::shared_ptr<ECC::HKdfPub> pKdf = std::make_shared<ECC::HKdfPub>();
if (!ks.Import(*pKdf))
{
LOG_ERROR() << "veiw key import failed";
}
return pKdf;
}
Key::IKdf::Ptr TrezorKeyKeeper::get_SbbsKdf() const
{
// !TODO: temporary solution to init SBBS KDF with commitment
Key::IDV kidv{ 0, 0, Key::Type::Regular };
auto key = m_hwWallet.generateKeySync(kidv, true);
Key::IKdf::Ptr sbbsKdf;
ECC::HKdf::Create(sbbsKdf, key.m_X);
return sbbsKdf;
}
void TrezorKeyKeeper::GeneratePublicKeys(const std::vector<Key::IDV>& ids, bool createCoinKey, Callback<PublicKeys>&& resultCallback, ExceptionCallback&& exceptionCallback)
{
}
void TrezorKeyKeeper::GenerateOutputs(Height schemeHeight, const std::vector<Key::IDV>& ids, Callback<Outputs>&& resultCallback, ExceptionCallback&& exceptionCallback)
{
using namespace std;
auto thisHolder = shared_from_this();
shared_ptr<Outputs> result = make_shared<Outputs>();
shared_ptr<exception> storedException;
shared_ptr<future<void>> futureHolder = make_shared<future<void>>();
*futureHolder = do_thread_async(
[thisHolder, this, schemeHeight, ids, result, storedException]()
{
try
{
*result = GenerateOutputsSync(schemeHeight, ids);
}
catch (const exception& ex)
{
*storedException = ex;
}
},
[futureHolder, resultCallback = move(resultCallback), exceptionCallback = move(exceptionCallback), result, storedException]() mutable
{
if (storedException)
{
exceptionCallback(*storedException);
}
else
{
resultCallback(move(*result));
}
futureHolder.reset();
});
}
size_t TrezorKeyKeeper::AllocateNonceSlot()
{
m_latestSlot++;
m_hwWallet.generateNonceSync((uint8_t)m_latestSlot);
return m_latestSlot;
}
IPrivateKeyKeeper::PublicKeys TrezorKeyKeeper::GeneratePublicKeysSync(const std::vector<Key::IDV>& ids, bool createCoinKey)
{
PublicKeys result;
result.reserve(ids.size());
for (const auto& idv : ids)
{
ECC::Point& publicKey = result.emplace_back();
publicKey = m_hwWallet.generateKeySync(idv, createCoinKey);
}
return result;
}
ECC::Point TrezorKeyKeeper::GeneratePublicKeySync(const Key::IDV& id, bool createCoinKey)
{
return m_hwWallet.generateKeySync(id, createCoinKey);
}
IPrivateKeyKeeper::Outputs TrezorKeyKeeper::GenerateOutputsSync(Height schemeHeigh, const std::vector<Key::IDV>& ids)
{
Outputs outputs;
outputs.reserve(ids.size());
for (const auto& kidv : ids)
{
auto& output = outputs.emplace_back(std::make_unique<Output>());
output->m_Commitment = m_hwWallet.generateKeySync(kidv, true);
output->m_pConfidential.reset(new ECC::RangeProof::Confidential);
*output->m_pConfidential = m_hwWallet.generateRangeProofSync(kidv, false);
}
return outputs;
}
ECC::Point TrezorKeyKeeper::GenerateNonceSync(size_t slot)
{
assert(m_latestSlot >= slot);
return m_hwWallet.getNoncePublicSync((uint8_t)slot);
}
ECC::Scalar TrezorKeyKeeper::SignSync(const std::vector<Key::IDV>& inputs, const std::vector<Key::IDV>& outputs, const ECC::Scalar::Native& offset, size_t nonceSlot, const KernelParameters& kernelParamerters, const ECC::Point::Native& publicNonce)
{
HWWallet::TxData txData;
txData.fee = kernelParamerters.fee;
txData.height = kernelParamerters.height;
txData.kernelCommitment = kernelParamerters.commitment;
txData.kernelNonce = publicNonce;
txData.nonceSlot = (uint32_t)nonceSlot;
txData.offset = offset;
return m_hwWallet.signTransactionSync(inputs, outputs, txData);
}
} | 31.976608 | 251 | 0.62564 | [
"vector"
] |
c2543c87b73840b5e6929458f853df7af8ca4b94 | 1,301 | cpp | C++ | src/unsignedzone.cpp | sischkg/nxnsattack | c20896e40187bbcacb5c0255ff8f3cc7d0592126 | [
"MIT"
] | 5 | 2020-05-22T10:01:51.000Z | 2022-01-01T04:45:14.000Z | src/unsignedzone.cpp | sischkg/dns-fuzz-server | 6f45079014e745537c2f564fdad069974e727da1 | [
"MIT"
] | 1 | 2020-06-07T14:09:44.000Z | 2020-06-07T14:09:44.000Z | src/unsignedzone.cpp | sischkg/dns-fuzz-server | 6f45079014e745537c2f564fdad069974e727da1 | [
"MIT"
] | 2 | 2020-03-10T03:06:20.000Z | 2021-07-25T15:07:45.000Z | #include "unsignedzone.hpp"
#include "unsignedzoneimp.hpp"
namespace dns
{
UnsignedZone::UnsignedZone( const Domainname &zone_name )
: mImp( new UnsignedZoneImp( zone_name ) )
{}
void UnsignedZone::add( std::shared_ptr<RRSet> rrset )
{
mImp->add( rrset );
}
MessageInfo UnsignedZone::getAnswer( const MessageInfo &query ) const
{
return mImp->getAnswer( query );
}
UnsignedZone::NodePtr UnsignedZone::findNode( const Domainname &domainname ) const
{
return mImp->findNode( domainname );
}
UnsignedZone::RRSetPtr UnsignedZone::findRRSet( const Domainname &domainname, Type type ) const
{
return mImp->findRRSet( domainname, type );
}
std::vector<std::shared_ptr<RecordDS>> UnsignedZone::getDSRecords() const
{
return mImp->getDSRecords();
}
void UnsignedZone::verify() const
{
mImp->verify();
}
const RRSet &UnsignedZone::getSOA() const
{
return mImp->getSOA();
}
const RRSet &UnsignedZone::getNameServers() const
{
return mImp->getNameServers();
}
std::shared_ptr<RRSet> UnsignedZone::signRRSet( const RRSet &rrset )
{
return mImp->signRRSet( rrset );
}
void UnsignedZone::initialize()
{
UnsignedZoneImp::initialize();
}
}
| 21.683333 | 99 | 0.648732 | [
"vector"
] |
c25e70762b57ab044b8a0539c451d73aaa82fe77 | 7,276 | cpp | C++ | 20.cpp | gabrielivascu/AoC2019 | 59bc479d23da240e74038fc4e866df98188a9b79 | [
"MIT"
] | null | null | null | 20.cpp | gabrielivascu/AoC2019 | 59bc479d23da240e74038fc4e866df98188a9b79 | [
"MIT"
] | null | null | null | 20.cpp | gabrielivascu/AoC2019 | 59bc479d23da240e74038fc4e866df98188a9b79 | [
"MIT"
] | null | null | null | #include "aoc.h"
struct portal_t {
std::string name;
aoc::point_2d_t pos[2];
portal_t() { pos[0] = pos[1] = {-1, -1}; }
portal_t(std::string name, aoc::point_2d_t p) : name(std::move(name)) {
pos[0] = std::move(p);
pos[1] = {-1, -1};
}
auto walk(const aoc::point_2d_t& p) const {
assert(pos[0] == p || pos[1] == p);
return pos[0] == p ? pos[1] : pos[0];
}
};
struct map_t {
std::unordered_map<aoc::point_2d_t, char> tiles;
std::vector<portal_t> portals;
aoc::point_2d_t start;
aoc::point_2d_t end;
int64_t width{0};
int64_t height{0};
map_t() = default;
map_t(const std::vector<std::string>& lines) {
height = lines.size();
width = lines[0].size();
for (int64_t y = 0; y < height; y++) {
for (int64_t x = 0; x < width; x++)
tiles[{x, y}] = lines[y][x];
}
// Find portals.
for (int64_t y = 0; y < height; y++) {
for (int64_t x = 0; x < width; x++) {
aoc::point_2d_t p{x, y};
if (tiles[p] != '.')
continue;
auto u = p.get_down();
auto u_u = p.get_down().get_down();
if (tiles[u] >= 'A' && tiles[u] <= 'Z' && tiles[u_u] >= 'A' && tiles[u_u] <= 'Z') {
assert(add_portal(fmt::format("{}{}", tiles[u_u], tiles[u]), p));
continue;
}
auto d = p.get_up();
auto d_d = p.get_up().get_up();
if (tiles[d] >= 'A' && tiles[d] <= 'Z' && tiles[d_d] >= 'A' && tiles[d_d] <= 'Z') {
assert(add_portal(fmt::format("{}{}", tiles[d], tiles[d_d]), p));
continue;
}
auto l = p.get_left();
auto l_l = p.get_left().get_left();
if (tiles[l] >= 'A' && tiles[l] <= 'Z' && tiles[l_l] >= 'A' && tiles[l_l] <= 'Z') {
assert(add_portal(fmt::format("{}{}", tiles[l_l], tiles[l]), p));
continue;
}
auto r = p.get_right();
auto r_r = p.get_right().get_right();
if (tiles[r] >= 'A' && tiles[r] <= 'Z' && tiles[r_r] >= 'A' && tiles[r_r] <= 'Z') {
assert(add_portal(fmt::format("{}{}", tiles[r], tiles[r_r]), p));
continue;
}
}
}
auto it = std::find_if(portals.begin(), portals.end(), [](const auto& p) { return p.name == "AA"; });
start = it->pos[0];
portals.erase(it);
it = std::find_if(portals.begin(), portals.end(), [](const auto& p) { return p.name == "ZZ"; });
end = it->pos[0];
portals.erase(it);
}
inline bool add_portal(const std::string& name, const aoc::point_2d_t& p) {
auto it = std::find_if(portals.begin(), portals.end(), [&](const auto& p) { return p.name == name; });
if (it == portals.end()) {
portals.emplace_back(name, p);
return true;
}
if (it->pos[1] == aoc::point_2d_t{-1, -1}) {
it->pos[1] = p;
return true;
}
return false;
}
inline bool is_outer(const aoc::point_2d_t& p) const {
return p.y == 2 || p.y == height - 3 || p.x == 2 || p.x == width - 3;
}
};
static int64_t part1_bfs(const map_t& map)
{
auto get_neighbors = [&](const aoc::point_2d_t& p) {
std::vector<aoc::point_2d_t> neighbors;
if (map.tiles.at(p.get_up()) == '.') neighbors.push_back(p.get_up());
if (map.tiles.at(p.get_down()) == '.') neighbors.push_back(p.get_down());
if (map.tiles.at(p.get_left()) == '.') neighbors.push_back(p.get_left());
if (map.tiles.at(p.get_right()) == '.') neighbors.push_back(p.get_right());
auto it = std::find_if(map.portals.begin(), map.portals.end(),
[&](const auto& portal) { return portal.pos[0] == p || portal.pos[1] == p; });
if (it != map.portals.end())
neighbors.push_back(it->walk(p));
return neighbors;
};
std::unordered_set<aoc::point_2d_t> visited = { map.start };
std::unordered_map<aoc::point_2d_t, int64_t> distance = { {map.start, 0} };
std::deque<aoc::point_2d_t> queue = { map.start };
while (!queue.empty()) {
auto point = queue.front();
queue.pop_front();
if (point == map.end)
return distance[point];
for (const auto& neighbor : get_neighbors(point)) {
if (!visited.count(neighbor)) {
queue.push_back(neighbor);
distance[neighbor] = distance[point] + 1;
visited.insert(neighbor);
}
}
}
return -1;
}
static int64_t part2_bfs(const map_t& map)
{
struct node_t {
aoc::point_2d_t pos;
int64_t level{0};
int64_t dist{0};
node_t() = default;
node_t(aoc::point_2d_t pos, int64_t level, int64_t dist) :
pos(std::move(pos)), level(level), dist(dist) {}
bool operator==(const node_t& o) const {
return std::tie(pos, level) == std::tie(o.pos, o.level);
}
bool operator<(const node_t& o) const {
return std::tie(pos, level) < std::tie(o.pos, o.level);
}
};
auto get_neighbors = [&](const node_t& node) {
std::vector<node_t> ret;
if (map.tiles.at(node.pos.get_up()) == '.')
ret.emplace_back(node.pos.get_up(), node.level, node.dist + 1);
if (map.tiles.at(node.pos.get_down()) == '.')
ret.emplace_back(node.pos.get_down(), node.level, node.dist + 1);
if (map.tiles.at(node.pos.get_left()) == '.')
ret.emplace_back(node.pos.get_left(), node.level, node.dist + 1);
if (map.tiles.at(node.pos.get_right()) == '.')
ret.emplace_back(node.pos.get_right(), node.level, node.dist + 1);
auto it = std::find_if(map.portals.begin(), map.portals.end(),
[&](const auto& portal) { return portal.pos[0] == node.pos || portal.pos[1] == node.pos; });
if (it != map.portals.end()) {
if (map.is_outer(node.pos)) {
if (node.level > 0)
ret.emplace_back(it->walk(node.pos), node.level - 1, node.dist + 1);
} else {
ret.emplace_back(it->walk(node.pos), node.level + 1, node.dist + 1);
}
}
return ret;
};
std::set<node_t> visited = { {map.start, 0, 0} };
std::deque<node_t> queue = { {map.start, 0, 0} };
while (!queue.empty()) {
auto node = queue.front();
queue.pop_front();
if (node.pos == map.end && node.level == 0)
return node.dist;
for (const auto& neighbor : get_neighbors(node)) {
if (!visited.count(neighbor)) {
queue.push_back(neighbor);
visited.insert(neighbor);
}
}
}
return -1;
}
int main(int argc, char const *argv[])
{
auto lines = aoc::get_input("20.in");
map_t map{lines};
aoc::println("Part 1: {}", part1_bfs(map));
aoc::println("Part 2: {}", part2_bfs(map));
return 0;
}
| 32.482143 | 110 | 0.489417 | [
"vector"
] |
c25eab139141135233c50c22a3629aa343336b25 | 5,906 | cpp | C++ | image.cpp | mxportocarrero/RGB-D_3DReconstruction | 959c833cd1854d2d7781ae049e6dbb957d1fba72 | [
"MIT"
] | null | null | null | image.cpp | mxportocarrero/RGB-D_3DReconstruction | 959c833cd1854d2d7781ae049e6dbb957d1fba72 | [
"MIT"
] | null | null | null | image.cpp | mxportocarrero/RGB-D_3DReconstruction | 959c833cd1854d2d7781ae049e6dbb957d1fba72 | [
"MIT"
] | null | null | null | #include "image.h"
//Aca lo unico que tenemos que hacer es leer el archivo depth.txt and rgb.txt
//Segun el numero de frame que necesitemos
//Constructor
Image::Image(DataSet * _dataset, int frame_number, int intrinsics){
dataset = _dataset;
noframe = frame_number;
Intrinsics = new Camera(intrinsics); // Los intrinsics son inizializados por defecto
//Leemos la imagen y almacenamos en un objeto cv::Mat
RGB_frame = cv::imread(dataset->getRGB_filename(noframe));
/**
// Probando con undistorsion
cv::Mat cameraMatrix = cv::Mat::eye(3,3,CV_64F); // Matriz para guardar la camera Intrinsics
cv::Mat distCoeffs = cv::Mat::zeros(8, 1,CV_64F); // Aqui guardamos los coeficientes de Distorsion
cameraMatrix.at<double>(0,2) = Intrinsics->cx;
cameraMatrix.at<double>(1,2) = Intrinsics->cy;
cameraMatrix.at<double>(0,0) = Intrinsics->fx;
cameraMatrix.at<double>(1,1) = Intrinsics->fy;
distCoeffs.at<double>(0,0) = 0.2624;
distCoeffs.at<double>(1,0) = -0.9531;
distCoeffs.at<double>(2,0) = -0.0054;
distCoeffs.at<double>(3,0) = 0.0026;
distCoeffs.at<double>(4,0) = 1.1633;
cv::Mat temp = RGB_frame.clone();
cv::undistort(temp,RGB_frame,cameraMatrix,distCoeffs);
**/
DEPTH_frame = cv::imread(dataset->getDEPTH_filename(noframe),cv::IMREAD_ANYDEPTH);
width = RGB_frame.cols;
height = RGB_frame.rows;
pixelCount = width * height;
//Creamos nuestro PointCloud
point_cloud = new PointCloud();
//Creamos referencias a nuestros vectores contenedores
std::vector<vec3> &Points = point_cloud->Points;
std::vector<vec3> &Normals = point_cloud->Normals;
std::vector<vec3> &Colors = point_cloud->Colors;
Points.resize(pixelCount);
Normals.resize(pixelCount);
Colors.resize(pixelCount);
FillPointCloudData();
}
cv::Mat Image::get_RGB_Mat()
{
return RGB_frame;
}
cv::Mat Image::get_DEPTH_Mat()
{
return DEPTH_frame;
}
Eigen::Vector3d Image::get_EigenCoordFromPixel(int u, int v)
{
int i = u + v * FrameWidth;
vec3 c = point_cloud->Points[i];
return Eigen::Vector3d(c.x,c.y,c.z);
}
cv::Point3f Image::get_CVCoordFromPixel(int u, int v)
{
int i = u + v * FrameWidth;
vec3 c = point_cloud->Points[i];
return cv::Point3f(c.x,c.y,c.z);
}
cv::Point3i Image::get_CVColorFromPixel(int u, int v)
{
int i = u + v * FrameWidth;
vec3 c = point_cloud->Colors[i];
return cv::Point3i((int)c.r, (int)c.g, (int)c.b );
}
const PointCloud &Image::getGLPointCloud() const
{
return *point_cloud;
}
vec3 Image::getPointFromPointCloud(int k)
{
return point_cloud->Points[k];
}
vec3 Image::getColorFromPointCloud(int k)
{
return point_cloud->Colors[k];
}
vec3 Image::getNormalFromPointCloud(int k)
{
return point_cloud->Normals[k];
}
void Image::PrintInfo()
{
//Verifiquemos el contenido
for(int i = 10000 ; i < 50000;i++){
auto p = point_cloud->Points[i];
cout << "(" << p.x << "," <<
p.y << "," <<
p.z << ")";
} cout << endl;
}
void Image::FillPointCloudData()
{
//Creamos referencias a nuestros vectores contenedores
std::vector<vec3> &Points = point_cloud->Points;
std::vector<vec3> &Normals = point_cloud->Normals;
std::vector<vec3> &Colors = point_cloud->Colors;
//Estimamos las Coordenadas Locales para cada pixel en el frame
uint16_t *pSource = (uint16_t*) DEPTH_frame.data;
//Pasamos de coordenadas (u,v,s) en 2D a (x,y,z) Coordenadas Locales
for(int v = 0; v < height; v++)
for(int u = 0; u < width; u++){
uint16_t value = (uint16_t) (*(pSource)); // Leyendo los valores para 16 Bits
int i = u + v * width; //Valor para iterar sobre nuestro FlatVector
//int key = cv::waitKey(5000);
//cout << i<<": "<< value << endl;
if(value != 0){
Points[i].z = value / Intrinsics->depthFactor ; // Valor en Z
Points[i].x = (u - Intrinsics->cx) * Points[i].z / Intrinsics->fx; // Valor en X
Points[i].y = (v - Intrinsics->cy) * Points[i].z / Intrinsics->fy; // Valor en X
}else{
Points[i].x = 0;
Points[i].y = 0;
Points[i].z = 0;
}
pSource++;
}
// Registramos los colores
for(int v = 0; v < height; v++)
for(int u = 0; u < width; u++){
int i = u + v * width;
int b = RGB_frame.at<cv::Vec3b>(v,u)[0];
int g = RGB_frame.at<cv::Vec3b>(v,u)[1];
int r = RGB_frame.at<cv::Vec3b>(v,u)[2];
//cout << r << " " << g << " " << b << endl ;
// Podemos realizar un cambio de colores de RGB a GrayScale
// Por el momento solo los guardaremos
// Recordemos que opencv guarda los valores en BGR
// Ojo debemos normalizar por q lee de 0 a 1
Colors[i] = vec3(r,g,b) / 255.0f;
}
//Estimamos las normales(Por el momento valor por defecto)
for(int v = 0; v < height; v++)
for(int u = 0; u < width; u++){
int i = u + v * width;
Normals[i] = vec3(1.0f,1.0f,1.0f);
}
/**
// Codigo para visualizar el Depth Image Correspondiente
double min,max;
cv::minMaxIdx(DEPTH_frame,&min,&max);
cout << "max:" << max << "min:" << min << endl;
cv::Mat adjMap;
//src.convertTo(adjMap,CV_8UC1,(double)255/(256*100),-min); // Coloramiento Uniforme
DEPTH_frame.convertTo(adjMap,CV_8UC1,255/(max-min),-min); // Coloramiento de acuerdo a valores maximos y minimos
cv::Mat FalseColorMap;
cv::applyColorMap(adjMap,FalseColorMap,cv::COLORMAP_BONE);
cv::cvtColor(FalseColorMap,FalseColorMap,CV_BGR2RGB);
cv::imshow("Hola",FalseColorMap);
int key = cv::waitKey(50000);
**/
//Estimamos el Color
//Estimamos las Normales
}
| 30.921466 | 116 | 0.605317 | [
"vector"
] |
c262f9323a7fced0e8802e55164484b78bc6caf7 | 3,952 | cpp | C++ | Source/StomtPlugin/Private/StomtPluginWidget.cpp | SaraKausch/stomt-unreal-plugin | ccf928f70df6cca8e93536ae820d187b3cf93948 | [
"MIT"
] | null | null | null | Source/StomtPlugin/Private/StomtPluginWidget.cpp | SaraKausch/stomt-unreal-plugin | ccf928f70df6cca8e93536ae820d187b3cf93948 | [
"MIT"
] | null | null | null | Source/StomtPlugin/Private/StomtPluginWidget.cpp | SaraKausch/stomt-unreal-plugin | ccf928f70df6cca8e93536ae820d187b3cf93948 | [
"MIT"
] | null | null | null | // Copyright 2018 STOMT GmbH. All Rights Reserved.
#pragma once
#include "StomtPluginWidget.h"
#include "StomtPluginPrivatePCH.h"
#include "StomtRestRequest.h"
#include "StomtLabel.h"
#include "Runtime/Engine/Classes/Components/SceneCaptureComponent2D.h"
UStomtPluginWidget::~UStomtPluginWidget()
{
this->LoginErrorCode = 0;
}
void UStomtPluginWidget::OnConstruction(FString AppID)
{
// Create API Object
if (api == NULL)
{
api = UStomtAPI::ConstructStomtAPI(AppID);
}
else
{
this->api->SetAppID(AppID);
}
this->Config = this->api->Config;
// Request Target Name
UStomtRestRequest* request = this->api->RequestTargetByAppID();
request->OnRequestComplete.AddDynamic(this, &UStomtPluginWidget::OnTargetResponse);
//Lookup EMail
this->IsEMailAlreadyKnown = this->api->Config->GetSubscribed();
this->IsUserLoggedIn = this->api->Config->GetLoggedIn();
}
void UStomtPluginWidget::OnMessageChanged(FString text)
{
if (!text.IsEmpty())
{
this->Message = text;
}
else
{
this->Message = FString(TEXT(""));
}
}
void UStomtPluginWidget::OnSubmit()
{
if (this->Message.IsEmpty())
{
return;
}
// Create Stomt Instance
this->stomt = UStomt::ConstructStomt(this->api->GetTargetID(), !this->IsWish, this->Message);
this->stomt->SetLabels(this->Labels);
this->stomt->SetAnonym(false);
this->api->SetStomtToSend(stomt);
FString LogFileName = FApp::GetProjectName() + FString(TEXT(".log"));
this->api->HandleOfflineStomts();
if (this->UploadLogs)
{
FString logFile = this->api->ReadLogFile(LogFileName);
if (!logFile.IsEmpty())
{
this->api->SendLogFile(logFile, LogFileName);
}
else
{
this->api->IsLogUploadComplete = true;
if (!this->api->UseImageUpload)
{
this->api->SendStomt(stomt);
}
}
}
else
{
this->api->IsLogUploadComplete = true;
if (!this->api->UseImageUpload)
{
this->api->SendStomt(stomt);
}
}
// Check EMail
this->IsEMailAlreadyKnown = this->api->Config->GetSubscribed();
UE_LOG(Stomt, Log, TEXT("Is EMail Already Known: %s"), this->IsEMailAlreadyKnown ? TEXT("true") : TEXT("false"));
}
void UStomtPluginWidget::OnSubmitLastLayer()
{
}
bool UStomtPluginWidget::OnSubmitLogin()
{
if (!this->UserName.IsEmpty() && !this->UserPassword.IsEmpty())
{
UStomtRestRequest* request = this->api->SendLoginRequest(this->UserName, this->UserPassword);
request->OnRequestComplete.AddDynamic(this, &UStomtPluginWidget::OnLoginResponse);
this->LoginErrorCode = 0;
return true;
}
else
{
return false;
}
}
void UStomtPluginWidget::OnSubmitEMail()
{
if (!this->EMail.IsEmpty())
{
this->api->SendSubscription(this->EMail, !UsePhoneNumber);
}
}
void UStomtPluginWidget::OnLogout()
{
this->api->SendLogoutRequest();
}
void UStomtPluginWidget::OnLoginResponse(UStomtRestRequest * LoginRequest)
{
this->LoginErrorCode = LoginRequest->GetResponseCode();
this->IsUserLoggedIn = this->api->Config->GetLoggedIn();
this->api->OnLoginRequestComplete.Broadcast(LoginRequest);
}
void UStomtPluginWidget::OnTargetResponse(UStomtRestRequest * TargetRequest)
{
this->TargetName = this->api->GetTargetName();
UE_LOG(Stomt, Log, TEXT("OnTargetResponse: %s"), *this->TargetName);
this->ImageURL = this->api->GetImageURL();
this->api->OnTargetRequestComplete.Broadcast(TargetRequest);
}
FString UStomtPluginWidget::AppendStomtURLParams(FString url, FString utm_content)
{
url += FString("?utm_source=" + FString("stomt"));
url += FString("&utm_medium=" + FString("sdk"));
url += FString("&utm_campaign=" + FString("unreal"));
url += FString("&utm_term=" + FString(FApp::GetProjectName()) );
if ( !utm_content.IsEmpty() )
{
url += FString("&utm_content=" + utm_content);
}
if ( !this->api->Config->GetAccessToken().IsEmpty() )
{
url += FString("&accesstoken=" + this->api->Config->GetAccessToken() );
}
return url;
}
void UStomtPluginWidget::UploadScreenshot()
{
this->api->SendImageFile(this->api->ReadScreenshotAsBase64());
}
| 22.712644 | 114 | 0.708755 | [
"object"
] |
c266f8283a30e4931b6ebd63efaca8f9ed1da852 | 6,395 | cpp | C++ | Plugins/Engine/Passes.cpp | xycsoscyx/gekengine | cb9c933c6646169c0af9c7e49be444ff6f97835d | [
"MIT"
] | 1 | 2019-04-22T00:10:49.000Z | 2019-04-22T00:10:49.000Z | Plugins/Engine/Passes.cpp | xycsoscyx/gekengine | cb9c933c6646169c0af9c7e49be444ff6f97835d | [
"MIT"
] | null | null | null | Plugins/Engine/Passes.cpp | xycsoscyx/gekengine | cb9c933c6646169c0af9c7e49be444ff6f97835d | [
"MIT"
] | 2 | 2017-10-16T15:40:55.000Z | 2019-04-22T00:10:50.000Z | #include "GEK/API/Renderer.hpp"
#include "Passes.hpp"
namespace Gek
{
ClearData::ClearData(ClearType type, std::string const &data)
: type(type)
{
switch (type)
{
case ClearType::Float:
case ClearType::Target:
floats.set(String::Convert(data, 0.0f));
break;
case ClearType::UInt:
integers.set(String::Convert(data, 0U));
break;
};
}
std::string getFormatSemantic(Video::Format format)
{
switch (format)
{
case Video::Format::R32G32B32A32_FLOAT:
case Video::Format::R16G16B16A16_FLOAT:
case Video::Format::R16G16B16A16_UNORM:
case Video::Format::R10G10B10A2_UNORM:
case Video::Format::R8G8B8A8_UNORM:
case Video::Format::R8G8B8A8_UNORM_SRGB:
case Video::Format::R16G16B16A16_NORM:
case Video::Format::R8G8B8A8_NORM:
return "float4"s;
case Video::Format::R32G32B32_FLOAT:
case Video::Format::R11G11B10_FLOAT:
return "float3"s;
case Video::Format::R32G32_FLOAT:
case Video::Format::R16G16_FLOAT:
case Video::Format::R16G16_UNORM:
case Video::Format::R8G8_UNORM:
case Video::Format::R16G16_NORM:
case Video::Format::R8G8_NORM:
return "float2"s;
case Video::Format::R32_FLOAT:
case Video::Format::R16_FLOAT:
case Video::Format::R16_UNORM:
case Video::Format::R8_UNORM:
case Video::Format::R16_NORM:
case Video::Format::R8_NORM:
case Video::Format::D32_FLOAT_S8X24_UINT:
case Video::Format::D24_UNORM_S8_UINT:
case Video::Format::D32_FLOAT:
case Video::Format::D16_UNORM:
return "float"s;
case Video::Format::R32G32B32A32_UINT:
case Video::Format::R16G16B16A16_UINT:
case Video::Format::R10G10B10A2_UINT:
return "uint4"s;
case Video::Format::R8G8B8A8_UINT:
case Video::Format::R32G32B32_UINT:
return "uint3"s;
case Video::Format::R32G32_UINT:
case Video::Format::R16G16_UINT:
case Video::Format::R8G8_UINT:
return "uint2"s;
case Video::Format::R32_UINT:
case Video::Format::R16_UINT:
case Video::Format::R8_UINT:
return "uint"s;
case Video::Format::R32G32B32A32_INT:
case Video::Format::R16G16B16A16_INT:
case Video::Format::R8G8B8A8_INT:
return "int4"s;
case Video::Format::R32G32B32_INT:
return "int3"s;
case Video::Format::R32G32_INT:
case Video::Format::R16G16_INT:
case Video::Format::R8G8_INT:
return "int2"s;
case Video::Format::R32_INT:
case Video::Format::R16_INT:
case Video::Format::R8_INT:
return "int"s;
};
return String::Empty;
}
std::string getFormatSemantic(Video::Format format, uint32_t count)
{
std::string semantic(getFormatSemantic(format));
if (count > 1)
{
semantic += String::Format("x{}", count);
}
return semantic;
}
ClearType getClearType(std::string const &string)
{
static const std::unordered_map<std::string, ClearType> data =
{
{ "target"s, ClearType::Target },
{ "float"s, ClearType::Float },
{ "uint"s, ClearType::UInt },
};
auto result = data.find(String::GetLower(string));
return (result == std::end(data) ? ClearType::Unknown : result->second);
}
uint32_t getTextureLoadFlags(std::string const &loadFlags)
{
uint32_t flags = 0;
int position = 0;
std::vector<std::string> flagList(String::Split(String::GetLower(loadFlags), ','));
for (auto const &flag : flagList)
{
if (flag == "srgb"s)
{
flags |= Video::TextureLoadFlags::sRGB;
}
}
return flags;
}
uint32_t getTextureFlags(std::string const &createFlags)
{
uint32_t flags = 0;
int position = 0;
std::vector<std::string> flagList(String::Split(String::GetLower(createFlags), ','));
for (auto const &flag : flagList)
{
if (flag == "target"s)
{
flags |= Video::Texture::Flags::RenderTarget;
}
else if (flag == "depth"s)
{
flags |= Video::Texture::Flags::DepthTarget;
}
else if (flag == "unorderedaccess"s)
{
flags |= Video::Texture::Flags::UnorderedAccess;
}
}
return (flags | Video::Texture::Flags::Resource);
}
uint32_t getBufferFlags(std::string const &createFlags)
{
uint32_t flags = 0;
int position = 0;
std::vector<std::string> flagList(String::Split(String::GetLower(createFlags), ','));
for (auto const &flag : flagList)
{
if (flag == "unorderedaccess"s)
{
flags |= Video::Buffer::Flags::UnorderedAccess;
}
else if (flag == "counter"s)
{
flags |= Video::Buffer::Flags::Counter;
}
}
return (flags | Video::Buffer::Flags::Resource);
}
std::unordered_map<std::string, std::string> getAliasedMap(JSON const &node)
{
std::unordered_map<std::string, std::string> aliasedMap;
for (auto &elementNode : node.asType(JSON::EmptyArray))
{
elementNode.visit(
[&](std::string const &elementString)
{
aliasedMap[elementString] = elementString;
},
[&](JSON::Object const &elementObject)
{
auto firstMember = elementObject.begin();
auto &aliasName = firstMember->first;
auto &aliasNode = firstMember->second;
aliasNode.visit(
[&](std::string const &aliasedValue)
{
aliasedMap[aliasName] = std::to_string(aliasedValue);
},
[&](auto const &aliasedValue)
{
});
},
[&](auto const &)
{
});
}
return aliasedMap;
}
}; // namespace Gek | 29.606481 | 93 | 0.541673 | [
"object",
"vector"
] |
c270ddb2ac035df4577ee1167e8b09962b442952 | 2,870 | hpp | C++ | cmdstan/stan/lib/stan_math/stan/math/torsten/dsolve/pmx_integrate_ode_group_rk45.hpp | csetraynor/Torsten | 55b59b8068e2a539346f566ec698c755a9e3536c | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/stan/math/torsten/dsolve/pmx_integrate_ode_group_rk45.hpp | csetraynor/Torsten | 55b59b8068e2a539346f566ec698c755a9e3536c | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/stan/math/torsten/dsolve/pmx_integrate_ode_group_rk45.hpp | csetraynor/Torsten | 55b59b8068e2a539346f566ec698c755a9e3536c | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_TORSTEN_DSOLVE_INTEGRATE_ODE_GROUP_RK45_HPP
#define STAN_MATH_TORSTEN_DSOLVE_INTEGRATE_ODE_GROUP_RK45_HPP
#include <stan/math/torsten/mpi/pmx_population_integrator.hpp>
#include <stan/math/torsten/dsolve/pmx_integrate_ode_rk45.hpp>
#include <stan/math/torsten/dsolve/ode_check.hpp>
namespace torsten {
/**
* Solve population ODE model by delegating the population
* ODE integration task to multiple processors through
* MPI, then gather the results, before generating @c var arrays.
* Each entry has an additional level of nested vector to
* identifiy the individual among a population of ODE parameters/data.
*
* @tparam F Functor type for RHS of ODE
* @tparam Tt type of time
* @tparam T_initial type of initial condition @c y0
* @tparam T_param type of parameter @c theta
* @param f RHS functor of ODE system
* @param y0 initial condition
* @param t0 initial time
* @param ts time steps
* @param theta parameters for ODE
* @param x_r data used in ODE
* @param x_i integer data used in ODE
* @param msgs output stream
* @param rtol relative tolerance
* @param atol absolute tolerance
* @param max_num_step maximum number of integration steps allowed.
* @return res nested vector that contains results for
* (individual i, time j, equation k)
**/
template <typename F, typename Tt, typename T_initial, typename T_param>
Eigen::Matrix<typename torsten::return_t<Tt, T_initial, T_param>::type,
Eigen::Dynamic, Eigen::Dynamic>
pmx_integrate_ode_group_rk45(const F& f,
const std::vector<std::vector<T_initial> >& y0,
double t0,
const std::vector<int>& len,
const std::vector<Tt>& ts,
const std::vector<std::vector<T_param> >& theta,
const std::vector<std::vector<double> >& x_r,
const std::vector<std::vector<int> >& x_i,
std::ostream* msgs = nullptr,
double rtol = 1e-6,
double atol = 1e-6,
long int max_num_step = 1e6) { // NOLINT(runtime/int)
static const char* caller("pmx_integrate_ode_rk45");
dsolve::ode_group_check(y0, t0, len, ts, theta, x_r, x_i, caller);
using scheme_t = boost::numeric::odeint::runge_kutta_dopri5<std::vector<double>, double, std::vector<double>, double>;
dsolve::PMXOdeintIntegrator<scheme_t> integrator(rtol, atol, max_num_step);
torsten::mpi::PMXPopulationIntegrator<F, dsolve::PMXOdeintIntegrator<scheme_t>,
dsolve::PMXOdeintSystem> solver(integrator);
return solver(f, y0, t0, len, ts, theta, x_r, x_i, msgs);
}
}
#endif
| 46.290323 | 122 | 0.635889 | [
"vector",
"model"
] |
c27486280f438b01753a587645164e97387d74d6 | 3,927 | cpp | C++ | book/CH09/S18_Preparing_a_single_frame_of_animation.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | 5 | 2019-03-02T16:29:15.000Z | 2021-11-07T11:07:53.000Z | book/CH09/S18_Preparing_a_single_frame_of_animation.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | null | null | null | book/CH09/S18_Preparing_a_single_frame_of_animation.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | 2 | 2018-07-10T18:15:40.000Z | 2020-01-03T04:02:32.000Z | //
// Created by yangyanjun on 2017/6/23.
//
//
// Chapter: 09 Command Recording and Drawing
// Recipe: 18 Preparing a single frame of animation
#include "../CH02/S15_Acquiring_a_swapchain_image.h"
#include "../CH02/S16_Presenting_an_image.h"
#include "../CH06/S05_Creating_a_framebuffer.h"
#include "S18_Preparing_a_single_frame_of_animation.h"
namespace VKCookbook {
bool PrepareSingleFrameOfAnimation( VkDevice logical_device,
VkQueue graphics_queue,
VkQueue present_queue,
VkSwapchainKHR swapchain,
VkExtent2D swapchain_size,
std::vector<VkImageView> const & swapchain_image_views,
VkImageView depth_attachment,
std::vector<WaitSemaphoreInfo> const & wait_infos,
VkSemaphore image_acquired_semaphore,
VkSemaphore ready_to_present_semaphore,
VkFence finished_drawing_fence,
std::function<bool(VkCommandBuffer, uint32_t, VkFramebuffer)> record_command_buffer,
VkCommandBuffer command_buffer,
VkRenderPass render_pass,
VkDestroyer<VkFramebuffer> & framebuffer ){
uint32_t image_index;
if( !AcquireSwapchainImage( logical_device, swapchain, image_acquired_semaphore, VK_NULL_HANDLE, image_index ) ) {
return false;
}
std::vector<VkImageView> attachments = { swapchain_image_views[image_index] };
if( VK_NULL_HANDLE != depth_attachment ) {
attachments.push_back( depth_attachment );
}
if( !CreateFramebuffer( logical_device, render_pass, attachments, swapchain_size.width, swapchain_size.height, 1, *framebuffer ) ) {
return false;
}
if( !record_command_buffer( command_buffer, image_index, *framebuffer ) ) {
return false;
}
std::vector<WaitSemaphoreInfo> wait_semaphore_infos = wait_infos;
wait_semaphore_infos.push_back( {
image_acquired_semaphore, // VkSemaphore Semaphore
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT // VkPipelineStageFlags WaitingStage
} );
if( !SubmitCommandBuffersToQueue( graphics_queue, wait_semaphore_infos, { command_buffer }, { ready_to_present_semaphore }, finished_drawing_fence ) ) {
return false;
}
PresentInfo present_info = {
swapchain, // VkSwapchainKHR Swapchain
image_index // uint32_t ImageIndex
};
if( !PresentImage( present_queue, { ready_to_present_semaphore }, { present_info } ) ) {
return false;
}
return true;
}
} | 58.61194 | 160 | 0.447925 | [
"vector"
] |
c275dc7f9901e7d2abda59efc081b551d15ab734 | 38,474 | cpp | C++ | main/src/Main/MainSystem.cpp | eapcivil/EXUDYN | 52bddc8c258cda07e51373f68e1198b66c701d03 | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2020-10-06T08:06:25.000Z | 2020-10-06T08:06:25.000Z | main/src/Main/MainSystem.cpp | eapcivil/EXUDYN | 52bddc8c258cda07e51373f68e1198b66c701d03 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | main/src/Main/MainSystem.cpp | eapcivil/EXUDYN | 52bddc8c258cda07e51373f68e1198b66c701d03 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | /** ***********************************************************************************************
* @class MainSystem
* @brief MainSystem and ObjectFactory
* @details Details:
- handling of CSystem
- initialization
- pybind11 interface
- object factory
*
* @author Gerstmayr Johannes
* @date 2018-05-17 (generated)
* @pre ...
*
* @copyright This file is part of Exudyn. Exudyn is free software: you can redistribute it and/or modify it under the terms of the Exudyn license. See 'LICENSE.txt' for more details.
* @note Bug reports, support and further information:
* - email: johannes.gerstmayr@uibk.ac.at
* - weblink: missing
*
*
* *** Example code ***
*
************************************************************************************************ */
#include <chrono> //sleep_for()
#include <thread>
#include "Main/MainSystemData.h"
#include "Main/MainSystem.h"
#include "Pymodules/PybindUtilities.h"
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// SYSTEM FUNCTIONS
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//! reset all lists and deallocate memory
void MainSystem::Reset()
{
mainSystemData.Reset(); //
GetCSystem()->GetSystemData().Reset();
GetCSystem()->GetPythonUserFunctions().Reset();
GetCSystem()->Initialize();
visualizationSystem.Reset();
interactiveMode = false;
}
//! if interAciveMode == true: causes Assemble() to be called; this guarantees that the system is always consistent to be drawn
void MainSystem::InteractiveModeActions()
{
if (GetInteractiveMode())
{
GetCSystem()->Assemble(*this);
GetCSystem()->GetPostProcessData()->SendRedrawSignal();
}
}
//! set user function to be called by solvers at beginning of step (static or dynamic step)
void MainSystem::PySetPreStepUserFunction(const py::object& value)
{
cSystem->GetPythonUserFunctions().preStepFunction = py::cast<std::function <bool(const MainSystem& mainSystem, Real t)>>(value);
cSystem->GetPythonUserFunctions().mainSystem = this;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// VISUALIZATION FUNCTIONS
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//! this function links the VisualizationSystem to a render engine, such that the changes in the graphics structure drawn upon updates, etc.
// This function is called on creation of a main system and automatically links to renderer
bool MainSystem::LinkToRenderEngine()
{
visualizationSystem.LinkToSystemData(&GetCSystem()->GetSystemData());
visualizationSystem.LinkToMainSystem(this);
visualizationSystem.LinkPostProcessData(GetCSystem()->GetPostProcessData());
return true; // visualizationSystem.LinkToRenderEngine(*GetCSystem());
}
//! this function releases the VisualizationSystem from the render engine;
bool MainSystem::DetachRenderEngine()
{
//at the moment nothing is done; but it could remove the links to systemData and postProcessData
return true;
//visualizationSystem.DetachRenderEngine();
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// NODE
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//! this is the hook to the object factory, handling all kinds of objects, nodes, ...
Index MainSystem::AddMainNode(py::dict d)
{
GetCSystem()->SystemHasChanged();
Index ind = GetMainObjectFactory().AddMainNode(*this, d);
InteractiveModeActions();
return ind;
};
NodeIndex MainSystem::AddMainNodePyClass(py::object pyObject)
{
py::dict dictObject;
Index itemIndex = 0;
try
{
if (py::isinstance<py::dict>(pyObject))
{
dictObject = py::cast<py::dict>(pyObject); //convert py::object to dict
}
else //must be itemInterface convertable to dict ==> otherwise raises pybind error
{
dictObject = py::dict(pyObject); //applies dict command to pyObject ==> converts object class to dictionary
}
itemIndex = AddMainNode(dictObject);
}
catch (const EXUexception& ex)
{
PyError("Error in AddNode(...) with dictionary=\n" + EXUstd::ToString(dictObject) +
"\nCheck your python code (negative indices, invalid or undefined parameters, ...)\nException message=\n" + STDstring(ex.what()));
throw(ex); //avoid multiple exceptions trown again (don't know why!)!
}
catch (...) //any other exception
{
PyError("Error in AddNode(...) with dictionary=\n" + EXUstd::ToString(dictObject) +
"\nCheck your python code (negative indices, invalid or undefined parameters, ...)\n");
}
return itemIndex;
//if (py::isinstance<py::dict>(pyObject))
//{
// py::dict dictObject = py::cast<py::dict>(pyObject); //convert py::object to dict
// return AddMainNode(dictObject);
//}
//else //must be itemInterface convertable to dict ==> otherwise raises pybind error
//{
// py::dict dictObject = py::dict(pyObject); //applies dict command to pyObject ==> converts object class to dictionary
// return AddMainNode(dictObject);
//}
}
//! get node's dictionary by name; does not throw a error message
NodeIndex MainSystem::PyGetNodeNumber(STDstring nodeName)
{
Index ind = EXUstd::GetIndexByName(mainSystemData.GetMainNodes(), nodeName);
if (ind != EXUstd::InvalidIndex)
{
return ind;
}
else
{
return EXUstd::InvalidIndex;
}
}
//! hook to read node's dictionary
py::dict MainSystem::PyGetNode(const py::object& itemIndex)
{
Index nodeNumber = EPyUtils::GetNodeIndexSafely(itemIndex);
if (nodeNumber < mainSystemData.GetMainNodes().NumberOfItems())
{
return mainSystemData.GetMainNodes().GetItem(nodeNumber)->GetDictionary();
}
else
{
PyError(STDstring("MainSystem::GetNode: invalid access to node number ") + EXUstd::ToString(nodeNumber));
py::dict d;
return d;
}
}
////! get node's dictionary by name
//py::dict MainSystem::PyGetNodeByName(STDstring nodeName)
//{
// Index ind = (Index)PyGetNodeNumber(nodeName);
// if (ind != EXUstd::InvalidIndex) { return PyGetNode(ind); }
// else
// {
// PyError(STDstring("MainSystem::GetNode: invalid access to node '") + nodeName + "'");
// return py::dict();
// }
//}
//! modify node's dictionary
void MainSystem::PyModifyNode(const py::object& itemIndex, py::dict nodeDict)
{
Index nodeNumber = EPyUtils::GetNodeIndexSafely(itemIndex);
if (nodeNumber < mainSystemData.GetMainNodes().NumberOfItems())
{
GetCSystem()->SystemHasChanged();
mainSystemData.GetMainNodes().GetItem(nodeNumber)->SetWithDictionary(nodeDict);
InteractiveModeActions();
}
else
{
PyError(STDstring("MainSystem::ModifyNode: invalid access to node number ") + EXUstd::ToString(nodeNumber));
}
}
////! modify node's dictionary
//void MainSystem::PyModifyNode(STDstring nodeName, py::dict d)
//{
// Index nodeNumber = PyGetNodeNumber(nodeName);
// if (nodeNumber < mainSystemData.GetMainNodes().NumberOfItems())
// {
// return mainSystemData.GetMainNodes().GetItem(nodeNumber)->SetWithDictionary(d);
// }
// else
// {
// PyError(STDstring("ModifyNodeDictionary: invalid access to node '") + nodeName + "'");
// }
//}
//! get node's default values, which helps for manual writing of python input
py::dict MainSystem::PyGetNodeDefaults(STDstring typeName)
{
py::dict d;
if (typeName.size() == 0) //in case of empty string-->return available default names!
{
PyError(STDstring("MainSystem::GetNodeDefaults: typeName needed'"));
return d;
}
MainNode* node = mainObjectFactory.CreateMainNode(*this, typeName); //create node with name
if (node)
{
d = node->GetDictionary();
delete node->GetCNode();
delete node;
}
else
{
PyError(STDstring("MainSystem::GetNodeDefaults: unknown node type '") + typeName + "'");
}
return d;
}
py::object MainSystem::PyGetNodeOutputVariable(const py::object& itemIndex, OutputVariableType variableType, ConfigurationType configuration) const
{
Index nodeNumber = EPyUtils::GetNodeIndexSafely(itemIndex);
if (nodeNumber < mainSystemData.GetMainNodes().NumberOfItems())
{
return mainSystemData.GetMainNodes().GetItem(nodeNumber)->GetOutputVariable(variableType, configuration);
}
else
{
PyError(STDstring("MainSystem::GetNodeOutputVariable: invalid access to node number ") + EXUstd::ToString(nodeNumber));
return py::int_(EXUstd::InvalidIndex);
//return py::object();
}
}
//! get index in global ODE2 coordinate vector for first node coordinate
Index MainSystem::PyGetNodeODE2Index(const py::object& itemIndex) const
{
Index nodeNumber = EPyUtils::GetNodeIndexSafely(itemIndex);
if (nodeNumber < mainSystemData.GetMainNodes().NumberOfItems())
{
if (mainSystemData.GetMainNodes().GetItem(nodeNumber)->GetCNode()->GetNodeGroup() == CNodeGroup::ODE2variables)
{
return mainSystemData.GetMainNodes().GetItem(nodeNumber)->GetCNode()->GetGlobalODE2CoordinateIndex();
}
else
{
PyError(STDstring("MainSystem::GetNodeODE2Index: invalid access to node number ") + EXUstd::ToString(nodeNumber) + ": not an ODE2 node");
return EXUstd::InvalidIndex;
}
}
else
{
PyError(STDstring("MainSystem::GetNodeODE2Index: invalid access to node number ") + EXUstd::ToString(nodeNumber) + " (index does not exist)");
return EXUstd::InvalidIndex;
}
}
////! call pybind object function, possibly with arguments; empty function, to be overwritten in specialized class
//py::object MainSystem::PyCallNodeFunction(Index nodeNumber, STDstring functionName, py::dict args)
//{
// if (nodeNumber < mainSystemData.GetMainNodes().NumberOfItems())
// {
// return mainSystemData.GetMainNodes().GetItem(nodeNumber)->CallFunction(functionName, args);
// }
// else
// {
// PyError(STDstring("MainSystem::ModifyObject: invalid access to node number ") + EXUstd::ToString(nodeNumber));
// return py::int_(EXUstd::InvalidIndex);
// //return py::object();
// }
//
//}
//! Get (read) parameter 'parameterName' of 'nodeNumber' via pybind / pyhton interface instead of obtaining the whole dictionary with GetDictionary
py::object MainSystem::PyGetNodeParameter(const py::object& itemIndex, const STDstring& parameterName) const
{
Index nodeNumber = EPyUtils::GetNodeIndexSafely(itemIndex);
if (nodeNumber < mainSystemData.GetMainNodes().NumberOfItems())
{
return mainSystemData.GetMainNodes().GetItem(nodeNumber)->GetParameter(parameterName);
}
else
{
PyError(STDstring("MainSystem::GetNodeParameter: invalid access to node number ") + EXUstd::ToString(nodeNumber));
return py::int_(EXUstd::InvalidIndex);
//return py::object();
}
}
//! Set (write) parameter 'parameterName' of 'nodeNumber' to 'value' via pybind / pyhton interface instead of writing the whole dictionary with SetWithDictionary(...)
void MainSystem::PySetNodeParameter(const py::object& itemIndex, const STDstring& parameterName, const py::object& value)
{
Index nodeNumber = EPyUtils::GetNodeIndexSafely(itemIndex);
if (nodeNumber < mainSystemData.GetMainNodes().NumberOfItems())
{
mainSystemData.GetMainNodes().GetItem(nodeNumber)->SetParameter(parameterName, value);
}
else
{
PyError(STDstring("MainSystem::SetNodeParameter: invalid access to node number ") + EXUstd::ToString(nodeNumber));
}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// OBJECT
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//! this is the hook to the object factory, handling all kinds of objects, nodes, ...
Index MainSystem::AddMainObject(py::dict d)
{
GetCSystem()->SystemHasChanged();
Index ind = GetMainObjectFactory().AddMainObject(*this, d);
InteractiveModeActions();
return ind;
};
ObjectIndex MainSystem::AddMainObjectPyClass(py::object pyObject)
{
py::dict dictObject;
Index itemIndex = 0;
try
{
if (py::isinstance<py::dict>(pyObject))
{
dictObject = py::cast<py::dict>(pyObject); //convert py::object to dict
}
else //must be itemInterface convertable to dict ==> otherwise raises pybind error
{
dictObject = py::dict(pyObject); //applies dict command to pyObject ==> converts object class to dictionary
}
itemIndex = AddMainObject(dictObject);
}
catch (const EXUexception& ex)
{
PyError("Error in AddObject(...) with dictionary=\n" + EXUstd::ToString(dictObject) +
"\nCheck your python code (negative indices, invalid or undefined parameters, ...)\nException message=\n" + STDstring(ex.what()));
throw(ex); //avoid multiple exceptions trown again (don't know why!)!
}
catch (...) //any other exception
{
PyError("Error in AddObject(...) with dictionary=\n" + EXUstd::ToString(dictObject) +
"\nCheck your python code (negative indices, invalid or undefined parameters, ...)\n");
}
return itemIndex;
}
//! get object's dictionary by name; does not throw a error message
ObjectIndex MainSystem::PyGetObjectNumber(STDstring itemName)
{
Index ind = EXUstd::GetIndexByName(mainSystemData.GetMainObjects(), itemName);
if (ind != EXUstd::InvalidIndex)
{
return ind;
}
else
{
return EXUstd::InvalidIndex;
}
}
//! hook to read object's dictionary
py::dict MainSystem::PyGetObject(const py::object& itemIndex)
{
Index itemNumber = EPyUtils::GetObjectIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainObjects().NumberOfItems())
{
return mainSystemData.GetMainObjects().GetItem(itemNumber)->GetDictionary();
}
else
{
PyError(STDstring("MainSystem::GetObject: invalid access to object number ") + EXUstd::ToString(itemNumber));
py::dict d;
return d;
}
}
////! get object's dictionary by name
//py::dict MainSystem::PyGetObjectByName(STDstring itemName)
//{
// Index ind = (Index)PyGetObjectNumber(itemName);
// if (ind != EXUstd::InvalidIndex) { return PyGetObject(ind); }
// else
// {
// PyError(STDstring("MainSystem::GetObject: invalid access to object '") + itemName + "'");
// return py::dict();
// }
//}
//! modify object's dictionary
void MainSystem::PyModifyObject(const py::object& itemIndex, py::dict d)
{
Index itemNumber = EPyUtils::GetObjectIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainObjects().NumberOfItems())
{
GetCSystem()->SystemHasChanged();
mainSystemData.GetMainObjects().GetItem(itemNumber)->SetWithDictionary(d);
InteractiveModeActions();
}
else
{
PyError(STDstring("MainSystem::ModifyObject: invalid access to object number ") + EXUstd::ToString(itemNumber));
}
}
//! get object's default values, which helps for manual writing of python input
py::dict MainSystem::PyGetObjectDefaults(STDstring typeName)
{
py::dict d;
if (typeName.size() == 0) //in case of empty string-->return available default names!
{
PyError(STDstring("MainSystem::GetObjectDefaults: typeName needed'"));
return d;
}
MainObject* object = mainObjectFactory.CreateMainObject(*this, typeName); //create object with typeName
if (object)
{
d = object->GetDictionary();
delete object->GetCObject();
delete object;
}
else
{
PyError(STDstring("MainSystem::GetObjectDefaults: unknown object type '") + typeName + "'");
}
return d;
}
////! call pybind object function, possibly with arguments; empty function, to be overwritten in specialized class
//py::object MainSystem::PyCallObjectFunction(const py::object& itemIndex, STDstring functionName, py::dict args)
//{
// if (itemNumber < mainSystemData.GetMainObjects().NumberOfItems())
// {
// return mainSystemData.GetMainObjects().GetItem(itemNumber)->CallFunction(functionName, args);
// }
// else
// {
// PyError(STDstring("MainSystem::ModifyObject: invalid access to object number ") + EXUstd::ToString(itemNumber));
// return py::int_(EXUstd::InvalidIndex);
// //return py::object();
// }
//}
//! Get specific output variable with variable type
py::object MainSystem::PyGetObjectOutputVariable(const py::object& itemIndex, OutputVariableType variableType) const
{
Index itemNumber = EPyUtils::GetObjectIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainObjects().NumberOfItems())
{
if ((Index)mainSystemData.GetMainObjects().GetItem(itemNumber)->GetCObject()->GetType() & (Index)CObjectType::Connector)
{
MarkerDataStructure markerDataStructure;
const bool computeJacobian = false; //not needed for OutputVariables
CObjectConnector* connector = (CObjectConnector*)(mainSystemData.GetMainObjects().GetItem(itemNumber)->GetCObject());
GetCSystem()->ComputeMarkerDataStructure(connector, computeJacobian, markerDataStructure);
return mainSystemData.GetMainObjects().GetItem(itemNumber)->GetOutputVariableConnector(variableType, markerDataStructure);
} else
{
return mainSystemData.GetMainObjects().GetItem(itemNumber)->GetOutputVariable(variableType);
}
}
else
{
PyError(STDstring("MainSystem::GetObjectOutputVariable: invalid access to object number ") + EXUstd::ToString(itemNumber));
return py::int_(EXUstd::InvalidIndex);
//return py::object();
}
}
//! Get specific output variable with variable type; ONLY for bodies;
//py::object MainSystem::PyGetObjectOutputBody(Index objectNumber, OutputVariableType variableType,
// const Vector3D& localPosition, ConfigurationType configuration) //no conversion from py to Vector3D!
py::object MainSystem::PyGetObjectOutputVariableBody(const py::object& itemIndex, OutputVariableType variableType,
const std::vector<Real>& localPosition, ConfigurationType configuration) const
{
if (localPosition.size() == 3)
{
Index itemNumber = EPyUtils::GetObjectIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainObjects().NumberOfItems())
{
const MainObject* mo = mainSystemData.GetMainObjects().GetItem(itemNumber);
//return mainSystemData.GetMainObjects().GetItem(itemNumber)->GetOutputVariableBody(variableType, pos, configuration);
return mo->GetOutputVariableBody(variableType, localPosition, configuration);
}
else
{
PyError(STDstring("MainSystem::GetObjectOutputVariableBody: invalid access to object number ") + EXUstd::ToString(itemNumber));
return py::int_(EXUstd::InvalidIndex);
//return py::object();
}
}
else
{
PyError(STDstring("MainSystem::GetOutputVariableBody: invalid localPosition: expected vector with 3 real values"));
return py::int_(EXUstd::InvalidIndex);
//return py::object();
}
}
//! get output variable from mesh node number of object with type SuperElement (GenericODE2, FFRF, FFRFreduced - CMS) with specific OutputVariableType
py::object MainSystem::PyGetObjectOutputVariableSuperElement(const py::object& itemIndex, OutputVariableType variableType,
Index meshNodeNumber, ConfigurationType configuration) const
{
Index itemNumber = EPyUtils::GetObjectIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainObjects().NumberOfItems())
{
return mainSystemData.GetMainObjects().GetItem(itemNumber)->GetOutputVariableSuperElement(variableType, meshNodeNumber, configuration);
}
else
{
PyError(STDstring("MainSystem::PyGetObjectOutputVariableSuperElement: invalid access to object number ") + EXUstd::ToString(itemNumber));
return py::int_(EXUstd::InvalidIndex);
}
}
//! Get (read) parameter 'parameterName' of 'objectNumber' via pybind / pyhton interface instead of obtaining the whole dictionary with GetDictionary
py::object MainSystem::PyGetObjectParameter(const py::object& itemIndex, const STDstring& parameterName) const
{
Index itemNumber = EPyUtils::GetObjectIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainObjects().NumberOfItems())
{
return mainSystemData.GetMainObjects().GetItem(itemNumber)->GetParameter(parameterName);
}
else
{
PyError(STDstring("MainSystem::GetObjectParameter: invalid access to object number ") + EXUstd::ToString(itemNumber));
return py::int_(EXUstd::InvalidIndex);
//return py::object();
}
}
//! Set (write) parameter 'parameterName' of 'objectNumber' to 'value' via pybind / pyhton interface instead of writing the whole dictionary with SetWithDictionary(...)
void MainSystem::PySetObjectParameter(const py::object& itemIndex, const STDstring& parameterName, const py::object& value)
{
Index itemNumber = EPyUtils::GetObjectIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainObjects().NumberOfItems())
{
mainSystemData.GetMainObjects().GetItem(itemNumber)->SetParameter(parameterName, value);
}
else
{
PyError(STDstring("MainSystem::SetObjectParameter: invalid access to object number ") + EXUstd::ToString(itemNumber));
}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// MARKER
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//! this is the hook to the object factory, handling all kinds of objects, nodes, ...
Index MainSystem::AddMainMarker(py::dict d)
{
GetCSystem()->SystemHasChanged();
Index ind = GetMainObjectFactory().AddMainMarker(*this, d);
InteractiveModeActions();
return ind;
};
MarkerIndex MainSystem::AddMainMarkerPyClass(py::object pyObject)
{
py::dict dictObject;
Index itemIndex = 0;
try
{
if (py::isinstance<py::dict>(pyObject))
{
dictObject = py::cast<py::dict>(pyObject); //convert py::object to dict
}
else //must be itemInterface convertable to dict ==> otherwise raises pybind error
{
dictObject = py::dict(pyObject); //applies dict command to pyObject ==> converts object class to dictionary
}
itemIndex = AddMainMarker(dictObject);
}
catch (const EXUexception& ex)
{
PyError("Error in AddMarker(...) with dictionary=\n" + EXUstd::ToString(dictObject) +
"\nCheck your python code (negative indices, invalid or undefined parameters, ...)\nException message=\n" + STDstring(ex.what()));
throw(ex); //avoid multiple exceptions trown again (don't know why!)!
}
catch (...) //any other exception
{
PyError("Error in AddMarker(...) with dictionary=\n" + EXUstd::ToString(dictObject) +
"\nCheck your python code (negative indices, invalid or undefined parameters, ...)\n");
}
return itemIndex;
}
//! get object's dictionary by name; does not throw a error message
MarkerIndex MainSystem::PyGetMarkerNumber(STDstring itemName)
{
Index ind = EXUstd::GetIndexByName(mainSystemData.GetMainMarkers(), itemName);
if (ind != EXUstd::InvalidIndex)
{
return ind;
}
else
{
return EXUstd::InvalidIndex;
}
}
//! hook to read object's dictionary
py::dict MainSystem::PyGetMarker(const py::object& itemIndex)
{
Index itemNumber = EPyUtils::GetMarkerIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainMarkers().NumberOfItems())
{
return mainSystemData.GetMainMarkers().GetItem(itemNumber)->GetDictionary();
}
else
{
PyError(STDstring("MainSystem::GetMarker: invalid access to marker number ") + EXUstd::ToString(itemNumber));
py::dict d;
return d;
}
}
////! get object's dictionary by name
//py::dict MainSystem::PyGetMarkerByName(STDstring itemName)
//{
// Index ind = (Index)PyGetMarkerNumber(itemName);
// if (ind != EXUstd::InvalidIndex) { return PyGetMarker(ind); }
// else
// {
// PyError(STDstring("MainSystem::GetMarker: invalid access to object '") + itemName + "'");
// return py::dict();
// }
//}
//! modify object's dictionary
void MainSystem::PyModifyMarker(const py::object& itemIndex, py::dict d)
{
Index itemNumber = EPyUtils::GetMarkerIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainMarkers().NumberOfItems())
{
GetCSystem()->SystemHasChanged();
mainSystemData.GetMainMarkers().GetItem(itemNumber)->SetWithDictionary(d);
InteractiveModeActions();
}
else
{
PyError(STDstring("MainSystem::ModifyMarker: invalid access to marker number ") + EXUstd::ToString(itemNumber));
}
}
//! get marker's default values, which helps for manual writing of python input
py::dict MainSystem::PyGetMarkerDefaults(STDstring typeName)
{
py::dict d;
if (typeName.size() == 0) //in case of empty string-->return available default names!
{
PyError(STDstring("MainSystem::GetMarkerDefaults: typeName needed'"));
return d;
}
MainMarker* object = mainObjectFactory.CreateMainMarker(*this, typeName); //create object with typeName
if (object)
{
d = object->GetDictionary();
delete object->GetCMarker();
delete object;
}
else
{
PyError(STDstring("MainSystem::GetMarkerDefaults: unknown object type '") + typeName + "'");
}
return d;
}
//! Get (read) parameter 'parameterName' of 'markerNumber' via pybind / pyhton interface instead of obtaining the whole dictionary with GetDictionary
py::object MainSystem::PyGetMarkerParameter(const py::object& itemIndex, const STDstring& parameterName) const
{
Index itemNumber = EPyUtils::GetMarkerIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainMarkers().NumberOfItems())
{
return mainSystemData.GetMainMarkers().GetItem(itemNumber)->GetParameter(parameterName);
}
else
{
PyError(STDstring("MainSystem::GetMarkerParameter: invalid access to marker number ") + EXUstd::ToString(itemNumber));
return py::int_(EXUstd::InvalidIndex);
//return py::object();
}
}
//! Set (write) parameter 'parameterName' of 'markerNumber' to 'value' via pybind / pyhton interface instead of writing the whole dictionary with SetWithDictionary(...)
void MainSystem::PySetMarkerParameter(const py::object& itemIndex, const STDstring& parameterName, const py::object& value)
{
Index itemNumber = EPyUtils::GetObjectIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainMarkers().NumberOfItems())
{
mainSystemData.GetMainMarkers().GetItem(itemNumber)->SetParameter(parameterName, value);
}
else
{
PyError(STDstring("MainSystem::SetMarkerParameter: invalid access to marker number ") + EXUstd::ToString(itemNumber));
}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// LOAD
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//! this is the hook to the object factory, handling all kinds of objects, nodes, ...
Index MainSystem::AddMainLoad(py::dict d)
{
GetCSystem()->SystemHasChanged();
Index ind = GetMainObjectFactory().AddMainLoad(*this, d);
InteractiveModeActions();
return ind;
};
LoadIndex MainSystem::AddMainLoadPyClass(py::object pyObject)
{
py::dict dictObject;
Index itemIndex = 0;
try
{
if (py::isinstance<py::dict>(pyObject))
{
dictObject = py::cast<py::dict>(pyObject); //convert py::object to dict
}
else //must be itemInterface convertable to dict ==> otherwise raises pybind error
{
dictObject = py::dict(pyObject); //applies dict command to pyObject ==> converts object class to dictionary
}
itemIndex = AddMainLoad(dictObject);
}
catch (const EXUexception& ex)
{
PyError("Error in AddLoad(...) with dictionary=\n" + EXUstd::ToString(dictObject) +
"\nCheck your python code (negative indices, invalid or undefined parameters, ...)\nException message=\n" + STDstring(ex.what()));
throw(ex); //avoid multiple exceptions trown again (don't know why!)!
}
catch (...) //any other exception
{
PyError("Error in AddLoad(...) with dictionary=\n" + EXUstd::ToString(dictObject) +
"\nCheck your python code (negative indices, invalid or undefined parameters, ...)\n");
}
return itemIndex;
}
//! get object's dictionary by name; does not throw a error message
LoadIndex MainSystem::PyGetLoadNumber(STDstring itemName)
{
Index ind = EXUstd::GetIndexByName(mainSystemData.GetMainLoads(), itemName);
if (ind != EXUstd::InvalidIndex)
{
return ind;
}
else
{
return EXUstd::InvalidIndex;
}
}
//! hook to read object's dictionary
py::dict MainSystem::PyGetLoad(const py::object& itemIndex)
{
Index itemNumber = EPyUtils::GetLoadIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainLoads().NumberOfItems())
{
return mainSystemData.GetMainLoads().GetItem(itemNumber)->GetDictionary();
}
else
{
PyError(STDstring("MainSystem::GetLoad: invalid access to load number ") + EXUstd::ToString(itemNumber));
py::dict d;
return d;
}
}
////! get object's dictionary by name
//py::dict MainSystem::PyGetLoadByName(STDstring itemName)
//{
// Index ind = (Index)PyGetLoadNumber(itemName);
// if (ind != EXUstd::InvalidIndex) { return PyGetLoad(ind); }
// else
// {
// PyError(STDstring("MainSystem::GetLoad: invalid access to object '") + itemName + "'");
// return py::dict();
// }
//}
//! modify object's dictionary
void MainSystem::PyModifyLoad(const py::object& itemIndex, py::dict d)
{
Index itemNumber = EPyUtils::GetLoadIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainLoads().NumberOfItems())
{
GetCSystem()->SystemHasChanged();
mainSystemData.GetMainLoads().GetItem(itemNumber)->SetWithDictionary(d);
InteractiveModeActions();
}
else
{
PyError(STDstring("MainSystem::ModifyLoad: invalid access to load number ") + EXUstd::ToString(itemNumber));
}
}
//! get LoadPoint default values, which helps for manual writing of python input
py::dict MainSystem::PyGetLoadDefaults(STDstring typeName)
{
py::dict d;
if (typeName.size() == 0) //in case of empty string-->return available default names!
{
PyError(STDstring("MainSystem::GetLoadDefaults: typeName needed'"));
return d;
}
MainLoad* object = mainObjectFactory.CreateMainLoad(*this, typeName); //create object with typeName
if (object)
{
d = object->GetDictionary();
delete object->GetCLoad();
delete object;
}
else
{
PyError(STDstring("MainSystem::GetLoadDefaults: unknown load type '") + typeName + "'");
}
return d;
}
//! Get current load values, specifically if user-defined loads are used
py::object MainSystem::PyGetLoadValues(const py::object& itemIndex) const
{
Index itemNumber = EPyUtils::GetLoadIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainLoads().NumberOfItems())
{
Real t = GetCSystem()->GetSystemData().GetCData().GetCurrent().GetTime(); //only current time available
return mainSystemData.GetMainLoads().GetItem(itemNumber)->GetLoadValues(t);
}
else
{
PyError(STDstring("MainSystem::GetLoadValues: invalid access to load number ") + EXUstd::ToString(itemNumber));
return py::int_(EXUstd::InvalidIndex);
}
}
//! Get (read) parameter 'parameterName' of 'loadNumber' via pybind / pyhton interface instead of obtaining the whole dictionary with GetDictionary
py::object MainSystem::PyGetLoadParameter(const py::object& itemIndex, const STDstring& parameterName) const
{
Index itemNumber = EPyUtils::GetLoadIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainLoads().NumberOfItems())
{
return mainSystemData.GetMainLoads().GetItem(itemNumber)->GetParameter(parameterName);
}
else
{
PyError(STDstring("MainSystem::GetLoadParameter: invalid access to load number ") + EXUstd::ToString(itemNumber));
return py::int_(EXUstd::InvalidIndex);
//return py::object();
}
}
//! Set (write) parameter 'parameterName' of 'loadNumber' to 'value' via pybind / pyhton interface instead of writing the whole dictionary with SetWithDictionary(...)
void MainSystem::PySetLoadParameter(const py::object& itemIndex, const STDstring& parameterName, const py::object& value)
{
Index itemNumber = EPyUtils::GetLoadIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainLoads().NumberOfItems())
{
mainSystemData.GetMainLoads().GetItem(itemNumber)->SetParameter(parameterName, value);
}
else
{
PyError(STDstring("MainSystem::SetLoadParameter: invalid access to load number ") + EXUstd::ToString(itemNumber));
}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// SENSOR
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//! this is the hook to the object factory, handling all kinds of objects, nodes, ...
Index MainSystem::AddMainSensor(py::dict d)
{
GetCSystem()->SystemHasChanged();
Index ind = GetMainObjectFactory().AddMainSensor(*this, d);
InteractiveModeActions();
return ind;
};
SensorIndex MainSystem::AddMainSensorPyClass(py::object pyObject)
{
py::dict dictObject;
Index itemIndex = 0;
try
{
if (py::isinstance<py::dict>(pyObject))
{
dictObject = py::cast<py::dict>(pyObject); //convert py::object to dict
}
else //must be itemInterface convertable to dict ==> otherwise raises pybind error
{
dictObject = py::dict(pyObject); //applies dict command to pyObject ==> converts object class to dictionary
}
itemIndex = AddMainSensor(dictObject);
}
catch (const EXUexception& ex)
{
PyError("Error in AddSensor(...) with dictionary=\n" + EXUstd::ToString(dictObject) +
"\nCheck your python code (negative indices, invalid or undefined parameters, ...)\nException message=\n" + STDstring(ex.what()));
throw(ex); //avoid multiple exceptions trown again (don't know why!)!
}
catch (...) //any other exception
{
PyError("Error in AddSensor(...) with dictionary=\n" + EXUstd::ToString(dictObject) +
"\nCheck your python code (negative indices, invalid or undefined parameters, ...)\n");
}
return itemIndex;
}
//! get object's dictionary by name; does not throw a error message
SensorIndex MainSystem::PyGetSensorNumber(STDstring itemName)
{
Index ind = EXUstd::GetIndexByName(mainSystemData.GetMainSensors(), itemName);
if (ind != EXUstd::InvalidIndex)
{
return ind;
}
else
{
return EXUstd::InvalidIndex;
}
}
//! hook to read object's dictionary
py::dict MainSystem::PyGetSensor(const py::object& itemIndex)
{
Index itemNumber = EPyUtils::GetSensorIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainSensors().NumberOfItems())
{
return mainSystemData.GetMainSensors().GetItem(itemNumber)->GetDictionary();
}
else
{
PyError(STDstring("MainSystem::GetSensor: invalid access to sensor number ") + EXUstd::ToString(itemNumber));
py::dict d;
return d;
}
}
////! get object's dictionary by name
//py::dict MainSystem::PyGetSensorByName(STDstring itemName)
//{
// Index ind = (Index)PyGetSensorNumber(itemName);
// if (ind != EXUstd::InvalidIndex) { return PyGetSensor(ind); }
// else
// {
// PyError(STDstring("MainSystem::GetSensor: invalid access to object '") + itemName + "'");
// return py::dict();
// }
//}
//! modify object's dictionary
void MainSystem::PyModifySensor(const py::object& itemIndex, py::dict d)
{
Index itemNumber = EPyUtils::GetSensorIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainSensors().NumberOfItems())
{
GetCSystem()->SystemHasChanged();
mainSystemData.GetMainSensors().GetItem(itemNumber)->SetWithDictionary(d);
InteractiveModeActions();
}
else
{
PyError(STDstring("MainSystem::ModifySensor: invalid access to sensor number ") + EXUstd::ToString(itemNumber));
}
}
//! get Sensor's default values, which helps for manual writing of python input
py::dict MainSystem::PyGetSensorDefaults(STDstring typeName)
{
py::dict d;
if (typeName.size() == 0) //in case of empty string-->return available default names!
{
PyError(STDstring("MainSystem::GetSensorDefaults: typeName needed'"));
return d;
}
MainSensor* object = mainObjectFactory.CreateMainSensor(*this, typeName); //create object with typeName
if (object)
{
d = object->GetDictionary();
delete object->GetCSensor();
delete object;
}
else
{
PyError(STDstring("MainSystem::GetSensorDefaults: unknown sensor type '") + typeName + "'");
}
return d;
}
//! get sensor's values
py::object MainSystem::PyGetSensorValues(const py::object& itemIndex, ConfigurationType configuration)
{
Index itemNumber = EPyUtils::GetSensorIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainSensors().NumberOfItems())
{
return mainSystemData.GetMainSensors().GetItem(itemNumber)->GetSensorValues(GetCSystem()->GetSystemData(), configuration);
}
else
{
PyError(STDstring("MainSystem::GetSensorValues: invalid access to sensor number ") + EXUstd::ToString(itemNumber));
return py::int_(EXUstd::InvalidIndex);
}
}
//! Get (read) parameter 'parameterName' of 'sensorNumber' via pybind / pyhton interface instead of obtaining the whole dictionary with GetDictionary
py::object MainSystem::PyGetSensorParameter(const py::object& itemIndex, const STDstring& parameterName) const
{
Index itemNumber = EPyUtils::GetSensorIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainSensors().NumberOfItems())
{
return mainSystemData.GetMainSensors().GetItem(itemNumber)->GetParameter(parameterName);
}
else
{
PyError(STDstring("MainSystem::GetSensorParameter: invalid access to sensor number ") + EXUstd::ToString(itemNumber));
return py::int_(EXUstd::InvalidIndex);
//return py::object();
}
}
//! Set (write) parameter 'parameterName' of 'SensorNumber' to 'value' via pybind / pyhton interface instead of writing the whole dictionary with SetWithDictionary(...)
void MainSystem::PySetSensorParameter(const py::object& itemIndex, const STDstring& parameterName, const py::object& value)
{
Index itemNumber = EPyUtils::GetSensorIndexSafely(itemIndex);
if (itemNumber < mainSystemData.GetMainSensors().NumberOfItems())
{
mainSystemData.GetMainSensors().GetItem(itemNumber)->SetParameter(parameterName, value);
}
else
{
PyError(STDstring("MainSystem::SetSensorParameter: invalid access to sensor number ") + EXUstd::ToString(itemNumber));
}
}
| 35.008189 | 185 | 0.681837 | [
"mesh",
"render",
"object",
"vector"
] |
c2782741e29db52b87a48107bbd8ac857db8aa2c | 2,354 | hpp | C++ | miniFE-sycl/basic/LockingMatrix.hpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 692 | 2015-11-12T13:56:43.000Z | 2022-03-30T03:45:59.000Z | miniFE-sycl/basic/LockingMatrix.hpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 1,096 | 2015-11-12T09:08:22.000Z | 2022-03-31T21:48:41.000Z | miniFE-sycl/basic/LockingMatrix.hpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 224 | 2015-11-12T21:17:03.000Z | 2022-03-30T00:57:48.000Z | #ifndef _LockingMatrix_hpp_
#define _LockingMatrix_hpp_
//@HEADER
// ************************************************************************
//
// miniFE: simple finite-element assembly and linear-solve
// Copyright (2006) Sandia Corporation
//
// Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
// license for use of this work by or on behalf of the U.S. Government.
//
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
// Questions? Contact Michael A. Heroux (maherou@sandia.gov)
//
// ************************************************************************
//@HEADER
#include <vector>
#include <Lock.hpp>
namespace miniFE {
template<typename MatrixType>
class LockingMatrix {
public:
typedef typename MatrixType::GlobalOrdinalType GlobalOrdinal;
typedef typename MatrixType::ScalarType Scalar;
LockingMatrix(MatrixType& A) : A_(A), myFirstRow_(0), myLastRow_(0), numMyRows_(0), row_locks_()
{
if (A_.rows.size() > 0) {
myFirstRow_ = A_.rows[0];
myLastRow_ = A_.rows[A_.rows.size()-1];
}
numMyRows_ = myLastRow_-myFirstRow_+1;
row_locks_.resize(numMyRows_);
}
void sum_in(GlobalOrdinal row, size_t row_len, const GlobalOrdinal* col_indices, const Scalar* values)
{
int local_row = row - myFirstRow_;
if (local_row >= 0 && local_row < numMyRows_) {
LockM<int> lock(row_locks_[local_row]);
sum_into_row(row, row_len, col_indices, values, A_);
}
}
private:
MatrixType& A_;
GlobalOrdinal myFirstRow_;
GlobalOrdinal myLastRow_;
size_t numMyRows_;
std::vector<tbb::atomic<int> > row_locks_;
};
}//namespace miniFE
#endif
| 31.386667 | 104 | 0.667375 | [
"vector"
] |
c27dd10be4be9441d33a4c1cd4654dd0d6fa509a | 4,278 | cpp | C++ | ED2/MatrixList.cpp | FabianaFerreira/topicos-matematica-aplicada | 71e0aef768b2d87511f698ab811faa49c172fa42 | [
"MIT"
] | null | null | null | ED2/MatrixList.cpp | FabianaFerreira/topicos-matematica-aplicada | 71e0aef768b2d87511f698ab811faa49c172fa42 | [
"MIT"
] | null | null | null | ED2/MatrixList.cpp | FabianaFerreira/topicos-matematica-aplicada | 71e0aef768b2d87511f698ab811faa49c172fa42 | [
"MIT"
] | null | null | null | /* ---------------------------------------
Fabiana Ferreira Fonseca
Universidade Federal do Rio de Janeiro
DRE: 115037241
----------------------------------------*/
#include "MatrixList.h"
#include "functions.h"
MatrixList::MatrixList(){};
MatrixList::MatrixList(std::string filename)
{
char index;
unsigned lines, columns;
std::vector<float> matrixLine;
float element;
std::ifstream f;
f.open(filename);
if (!f)
{
std::cout << "Unable to open file" << std::endl;
exit(1); // terminate with error
};
while (!f.eof())
{
f >> index >> lines >> columns;
for (int i = 0; i < lines; i++)
{
matrixLine.clear();
for (int j = 0; j < columns; j++)
{
f >> element;
matrixLine.push_back(element);
}
m_matrixList[index].push_back(matrixLine);
}
}
f.close();
};
// Read matrix list from file. If `append` is true, then append the new
// matrix list content to the current one, overwriting existing indexes.
// If `append` is false, set the matrix list content to the file data.
void MatrixList::readFile(std::string filename, bool append = false)
{
char index;
unsigned lines, columns;
std::vector<float> matrixLine;
std::map<char, Matrix> tempMatrixList;
float element;
bool wasEmpty = (m_matrixList.size() == 0);
std::cout << "Construtor arquivo" << std::endl;
std::ifstream f;
f.open(filename);
if (!f)
{
std::cout << "Unable to open file";
exit(1); // terminate with error
};
while (!f.eof())
{
f >> index >> lines >> columns;
for (int i = 0; i < lines; i++)
{
matrixLine.clear();
for (int j = 0; j < columns; j++)
{
f >> element;
matrixLine.push_back(element);
}
if (append || wasEmpty)
m_matrixList[index].push_back(matrixLine);
else
tempMatrixList[index].push_back(matrixLine);
}
}
f.close();
if (!append)
m_matrixList = tempMatrixList;
}
void MatrixList::save(std::string filename)
{
std::ofstream f;
f.open(filename);
if (!f)
{
std::cout << "Unable to open file";
exit(1); // terminate with error
};
unsigned counter = 0;
for (auto const &x : m_matrixList)
{
Matrix matrix = x.second;
unsigned lines = matrix.size();
unsigned columns = matrix[0].size();
f << x.first << " " << lines << " " << columns << std::endl;
for (unsigned i = 0; i < lines; i++)
{
for (unsigned j = 0; j < columns; j++)
{
f << matrix.at(i).at(j);
if (j != (columns - 1))
f << " ";
}
if ((i != (lines - 1)) || (counter != (m_matrixList.size() - 1)))
f << std::endl;
}
if (counter != (m_matrixList.size() - 1))
f << std::endl;
counter++;
}
f.close();
}
void MatrixList::list()
{
if (m_matrixList.size() == 0)
{
std::cout << "Empty matrix list" << std::endl;
return;
}
for (auto const &x : m_matrixList)
{
Matrix matrix = x.second;
unsigned lines = matrix.size();
unsigned columns = matrix[0].size();
std::cout << "Matrix " << x.first << " (" << lines << "," << columns << ")\n";
printMatrix(matrix);
std::cout << std::endl;
}
}
Matrix MatrixList::get(char index)
{
return m_matrixList[index];
}
// Add or modify a matrix of the list given an index
void MatrixList::insert(char index, Matrix newMatrix)
{
m_matrixList[index] = newMatrix;
}
// Add a identify of dimension 'n x n' on a given index
void MatrixList::insertIdentity(char index, unsigned n)
{
Matrix identity;
for (unsigned i = 0; i < n; i++)
{
identity.push_back(std::vector<float>(n, 0));
identity.at(i).at(i) = 1;
}
this->insert(index, identity);
}
void MatrixList::remove(char index)
{
m_matrixList.erase(index);
}
void MatrixList::clear()
{
m_matrixList.clear();
} | 23.377049 | 86 | 0.514493 | [
"vector"
] |
c28fcd276e5f79138f438cb9cd7cdfa5648e451f | 8,229 | cc | C++ | centreon-engine/src/retention/downtime.cc | centreon/centreon-collect | e63fc4d888a120d588a93169e7d36b360616bdee | [
"Unlicense"
] | 8 | 2020-07-26T09:12:02.000Z | 2022-03-30T17:24:29.000Z | centreon-engine/src/retention/downtime.cc | centreon/centreon-collect | e63fc4d888a120d588a93169e7d36b360616bdee | [
"Unlicense"
] | 47 | 2020-06-18T12:11:37.000Z | 2022-03-16T10:28:56.000Z | centreon-engine/src/retention/downtime.cc | centreon/centreon-collect | e63fc4d888a120d588a93169e7d36b360616bdee | [
"Unlicense"
] | 5 | 2020-06-29T14:22:02.000Z | 2022-03-17T10:34:10.000Z | /*
** Copyright 2011-2013 Merethis
**
** This file is part of Centreon Engine.
**
** Centreon Engine is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Engine 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 Centreon Engine. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include "com/centreon/engine/downtimes/downtime.hh"
#include "com/centreon/engine/retention/downtime.hh"
#include "com/centreon/engine/string.hh"
using namespace com::centreon::engine;
#define SETTER(type, method) \
&retention::object::setter<retention::downtime, type, \
&retention::downtime::method>::generic
retention::downtime::setters const retention::downtime::_setters[] = {
{"author", SETTER(std::string const&, _set_author)},
{"comment", SETTER(std::string const&, _set_comment_data)},
{"downtime_id", SETTER(unsigned long, _set_downtime_id)},
{"duration", SETTER(unsigned long, _set_duration)},
{"end_time", SETTER(time_t, _set_end_time)},
{"entry_time", SETTER(time_t, _set_entry_time)},
{"fixed", SETTER(bool, _set_fixed)},
{"host_name", SETTER(std::string const&, _set_host_name)},
{"service_description",
SETTER(std::string const&, _set_service_description)},
{"start_time", SETTER(time_t, _set_start_time)},
{"triggered_by", SETTER(unsigned long, _set_triggered_by)}};
/**
* Constructor.
*
* @param[in] type This is a host or service downtime.
*/
retention::downtime::downtime(type_id downtime_type)
: object(object::downtime),
_downtime_id(0),
_downtime_type(downtime_type),
_duration(0),
_end_time(0),
_entry_time(0),
_fixed(false),
_start_time(0),
_triggered_by(0) {}
/**
* Copy constructor.
*
* @param[in] right Object to copy.
*/
retention::downtime::downtime(downtime const& right) : object(right) {
operator=(right);
}
/**
* Destructor.
*/
retention::downtime::~downtime() throw() {}
/**
* Copy operator.
*
* @param[in] right Object to copy.
*
* @return This object.
*/
retention::downtime& retention::downtime::operator=(downtime const& right) {
if (this != &right) {
object::operator=(right);
_author = right._author;
_comment_data = right._comment_data;
_downtime_id = right._downtime_id;
_downtime_type = right._downtime_type;
_duration = right._duration;
_end_time = right._end_time;
_entry_time = right._entry_time;
_fixed = right._fixed;
_host_name = right._host_name;
_service_description = right._service_description;
_start_time = right._start_time;
_triggered_by = right._triggered_by;
}
return (*this);
}
/**
* Equal operator.
*
* @param[in] right The object to compare.
*
* @return True if is the same object, otherwise false.
*/
bool retention::downtime::operator==(downtime const& right) const throw() {
return (
object::operator==(right) && _author == right._author &&
_comment_data == right._comment_data &&
_downtime_id == right._downtime_id &&
_downtime_type == right._downtime_type && _duration == right._duration &&
_end_time == right._end_time && _entry_time == right._entry_time &&
_fixed == right._fixed && _host_name == right._host_name &&
_service_description == right._service_description &&
_start_time == right._start_time && _triggered_by == right._triggered_by);
}
/**
* Not equal operator.
*
* @param[in] right The object to compare.
*
* @return True if is not the same object, otherwise false.
*/
bool retention::downtime::operator!=(downtime const& right) const throw() {
return (!operator==(right));
}
/**
* Set new value on specific property.
*
* @param[in] key The property to set.
* @param[in] value The new value.
*
* @return True on success, otherwise false.
*/
bool retention::downtime::set(char const* key, char const* value) {
for (unsigned int i(0); i < sizeof(_setters) / sizeof(_setters[0]); ++i)
if (!strcmp(_setters[i].name, key))
return ((_setters[i].func)(*this, value));
return (false);
}
/**
* Get author.
*
* @return The author.
*/
std::string retention::downtime::author() const throw() {
return (_author);
}
/**
* Get comment_data.
*
* @return The comment_data.
*/
std::string retention::downtime::comment_data() const throw() {
return (_comment_data);
}
/**
* Get downtime_id.
*
* @return The downtime_id.
*/
unsigned long retention::downtime::downtime_id() const throw() {
return (_downtime_id);
}
/**
* Get downtime_type.
*
* @return The downtime_type.
*/
retention::downtime::type_id retention::downtime::downtime_type() const
throw() {
return (_downtime_type);
}
/**
* Get duration.
*
* @return The duration.
*/
unsigned long retention::downtime::duration() const throw() {
return (_duration);
}
/**
* Get end_time.
*
* @return The end_time.
*/
time_t retention::downtime::end_time() const throw() {
return (_end_time);
}
/**
* Get entry_time.
*
* @return The entry_time.
*/
time_t retention::downtime::entry_time() const throw() {
return (_entry_time);
}
/**
* Get fixed.
*
* @return The fixed.
*/
bool retention::downtime::fixed() const throw() {
return (_fixed);
}
/**
* Get host_name.
*
* @return The host_name.
*/
std::string retention::downtime::host_name() const throw() {
return (_host_name);
}
/**
* Get service_description.
*
* @return The service_description.
*/
std::string retention::downtime::service_description() const throw() {
return (_service_description);
}
/**
* Get start_time.
*
* @return The start_time.
*/
time_t retention::downtime::start_time() const throw() {
return (_start_time);
}
/**
* Get triggered_by.
*
* @return The triggered_by.
*/
unsigned long retention::downtime::triggered_by() const throw() {
return (_triggered_by);
}
/**
* Set author.
*
* @param[in] value The new author.
*/
bool retention::downtime::_set_author(std::string const& value) {
_author = value;
return (true);
}
/**
* Set comment_data.
*
* @param[in] value The new comment_data.
*/
bool retention::downtime::_set_comment_data(std::string const& value) {
_comment_data = value;
return (true);
}
/**
* Set downtime_id.
*
* @param[in] value The new downtime_id.
*/
bool retention::downtime::_set_downtime_id(unsigned long value) {
_downtime_id = value;
return (true);
}
/**
* Set duration.
*
* @param[in] value The new duration.
*/
bool retention::downtime::_set_duration(unsigned long value) {
_duration = value;
return (true);
}
/**
* Set end_time.
*
* @param[in] value The new end_time.
*/
bool retention::downtime::_set_end_time(time_t value) {
_end_time = value;
return (true);
}
/**
* Set entry_time.
*
* @param[in] value The new entry_time.
*/
bool retention::downtime::_set_entry_time(time_t value) {
_entry_time = value;
return (true);
}
/**
* Set fixed.
*
* @param[in] value The new fixed.
*/
bool retention::downtime::_set_fixed(bool value) {
_fixed = value;
return (true);
}
/**
* Set host_name.
*
* @param[in] value The new host_name.
*/
bool retention::downtime::_set_host_name(std::string const& value) {
_host_name = value;
return (true);
}
/**
* Set service_description.
*
* @param[in] value The new service_description.
*/
bool retention::downtime::_set_service_description(std::string const& value) {
_service_description = value;
return (true);
}
/**
* Set start_time.
*
* @param[in] value The new start_time.
*/
bool retention::downtime::_set_start_time(time_t value) {
_start_time = value;
return (true);
}
/**
* Set triggered_by.
*
* @param[in] value The new triggered_by.
*/
bool retention::downtime::_set_triggered_by(unsigned long value) {
_triggered_by = value;
return (true);
}
| 22.669421 | 80 | 0.668246 | [
"object"
] |
c28fd589252c83d9f6969090a81d8188a9bdc198 | 7,660 | cpp | C++ | src/Xtb/Xtb/Wrapper/GFNFFWrapper.cpp | qcscine/xtb_wrapper | 5295244771ed5efe3d9e1582e07ed9d26545d387 | [
"BSD-3-Clause"
] | null | null | null | src/Xtb/Xtb/Wrapper/GFNFFWrapper.cpp | qcscine/xtb_wrapper | 5295244771ed5efe3d9e1582e07ed9d26545d387 | [
"BSD-3-Clause"
] | null | null | null | src/Xtb/Xtb/Wrapper/GFNFFWrapper.cpp | qcscine/xtb_wrapper | 5295244771ed5efe3d9e1582e07ed9d26545d387 | [
"BSD-3-Clause"
] | 1 | 2022-02-04T13:40:00.000Z | 2022-02-04T13:40:00.000Z | /**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
/* Internal Includes */
#include "Xtb/Wrapper/GFNFFWrapper.h"
#include "Xtb/Wrapper/XtbSettings.h"
/* External Include */
#include <Utils/Bonds/BondOrderCollection.h>
#include <Utils/CalculatorBasics/ResultsAutoCompleter.h>
#include <Utils/GeometricDerivatives/NumericalHessianCalculator.h>
#include <Utils/Scf/LcaoUtils/ElectronicOccupation.h>
#include <Utils/Solvation/ImplicitSolvation.h>
#include <Utils/UniversalSettings/SettingsNames.h>
#include <xtb.h>
#include <boost/exception/diagnostic_information.hpp>
namespace Scine {
namespace Xtb {
std::mutex GFNFFWrapper::_mtx;
const Scine::Utils::Results& GFNFFWrapper::calculate(std::string /* dummy */) {
const int nCores = _settings.getInt(Utils::SettingsNames::externalProgramNProcs);
#if defined(_OPENMP)
omp_set_dynamic(0); // Explicitly disable dynamic teams
omp_set_num_threads(nCores);
#endif
// Prepare Data
const int natoms = _structure->size();
auto elements = _structure->getElements();
Eigen::VectorXi attyp(natoms);
for (int i = 0; i < natoms; i++) {
attyp[i] = Scine::Utils::ElementInfo::Z(elements[i]);
}
const double charge = _settings.getInt(Utils::SettingsNames::molecularCharge); // double because xtb wants double
const int uhf = _settings.getInt(Utils::SettingsNames::spinMultiplicity) - 1;
auto coord = _structure->getPositions();
// Prepare XTB classes
xtb_TEnvironment env = xtb_newEnvironment();
xtb_TCalculator calc = xtb_newCalculator();
xtb_TResults res = xtb_newResults();
xtb_TMolecule mol = xtb_newMolecule(env, &natoms, attyp.data(), coord.data(), &charge, &uhf, nullptr, nullptr);
if (xtb_checkEnvironment(env) != 0) {
xtb_showEnvironment(env, nullptr);
_cleanDataStructures(env, calc, res, mol);
throw std::runtime_error("XTB molecule setup failed.");
}
// Setup XTB model
_mtx.lock();
xtb_loadGFNFF(env, mol, calc, nullptr);
_mtx.unlock();
if (xtb_checkEnvironment(env) != 0) {
xtb_showEnvironment(env, nullptr);
_cleanDataStructures(env, calc, res, mol);
throw std::runtime_error("XTB method setup failed.");
}
// Apply settings
double acc = _settings.getDouble(Utils::SettingsNames::selfConsistenceCriterion) / 1e-6; // to arrive at Xtb accuracy
// value
xtb_setAccuracy(env, calc, acc);
xtb_setMaxIter(env, calc, _settings.getInt(Utils::SettingsNames::maxScfIterations));
xtb_setElectronicTemp(env, calc, _settings.getDouble(Utils::SettingsNames::electronicTemperature));
xtb_setVerbosity(env, _settings.getInt("print_level"));
if (Utils::Solvation::ImplicitSolvation::solvationNeededAndPossible(_availableSolvationModels, _settings)) {
std::string solvent = _settings.getString(Utils::SettingsNames::solvent);
std::for_each(solvent.begin(), solvent.end(), [](char& c) { c = ::tolower(c); });
std::vector<std::string> availableSolvents = {"acetone", "acetonitrile", "benzene", "ch2cl2", "chcl3", "cs2", "dmf",
"dmso", "ether", "toluene", "thf", "water", "h2o"};
if (std::find(availableSolvents.begin(), availableSolvents.end(), solvent) == availableSolvents.end()) {
_cleanDataStructures(env, calc, res, mol);
throw std::runtime_error("The given solvent is not available for implicit solvation within GFNFF.");
}
double temp = _settings.getDouble("temperature");
int state = 3; // 1 bar of ideal gas and 1 mol/L of liquid solution
int grid = 230; // n_grid_points, xtb default value
xtb_setSolvent(env, calc, &solvent[0], &state, &temp, &grid);
}
// Run XTB singlepoint
try {
xtb_singlepoint(env, mol, calc, res);
}
catch (...) {
_cleanDataStructures(env, calc, res, mol);
throw Core::UnsuccessfulCalculationException("Xtb calculation failed:\n" +
boost::current_exception_diagnostic_information());
}
if (xtb_checkEnvironment(env) != 0) {
// necessary raw pointers for xtb wrapper
const int buffersize = 512;
char error[buffersize] = "";
xtb_getError(env, &error[0], &buffersize);
std::string errorMessage(error);
xtb_showEnvironment(env, nullptr);
_cleanDataStructures(env, calc, res, mol);
throw Core::UnsuccessfulCalculationException("Xtb calculation failed:\n" + errorMessage);
}
// Parse output
this->_results = Scine::Utils::Results();
// - Energy
double energy = 0.0;
xtb_getEnergy(env, res, &energy);
if (xtb_checkEnvironment(env) != 0) {
xtb_showEnvironment(env, nullptr);
this->_results.set<Scine::Utils::Property::SuccessfulCalculation>(false);
_cleanDataStructures(env, calc, res, mol);
throw std::runtime_error("Could not read XTB energy.");
}
this->_results.set<Scine::Utils::Property::Energy>(energy);
// - Gradients
if (_requiredProperties.containsSubSet(Scine::Utils::Property::Gradients)) {
Utils::GradientCollection grad = Utils::GradientCollection::Zero(natoms, 3);
xtb_getGradient(env, res, grad.data());
if (xtb_checkEnvironment(env) != 0) {
xtb_showEnvironment(env, nullptr);
this->_results.set<Scine::Utils::Property::SuccessfulCalculation>(false);
_cleanDataStructures(env, calc, res, mol);
throw std::runtime_error("Could not read XTB gradients.");
}
this->_results.set<Scine::Utils::Property::Gradients>(grad);
}
// - Occupation
auto occupation = Scine::Utils::LcaoUtils::ElectronicOccupation();
if (uhf == 0) {
occupation.fillLowestRestrictedOrbitalsWithElectrons(attyp.sum() - static_cast<int>(charge));
}
else {
int alpha = (attyp.sum() - static_cast<int>(charge) + uhf) / 2;
int beta = (attyp.sum() - static_cast<int>(charge) - uhf) / 2;
occupation.fillLowestUnrestrictedOrbitals(alpha, beta);
}
this->_results.set<Scine::Utils::Property::ElectronicOccupation>(occupation);
// Calculate Hessian
if (_requiredProperties.containsSubSet(Scine::Utils::Property::Hessian) or
_requiredProperties.containsSubSet(Scine::Utils::Property::Thermochemistry)) {
Utils::NumericalHessianCalculator hessianCalculator(*this);
auto numericalResult = hessianCalculator.calculate();
this->_results.set<Utils::Property::Hessian>(numericalResult.take<Utils::Property::Hessian>());
}
// set successful to be able to autocomplete thermochemistry
this->_results.set<Scine::Utils::Property::SuccessfulCalculation>(true);
_settings.modifyString(Utils::SettingsNames::spinMode,
Utils::SpinModeInterpreter::getStringFromSpinMode(Utils::SpinMode::RestrictedOpenShell));
this->_results.set<Scine::Utils::Property::ProgramName>(program);
// - Thermochemistry
if (_requiredProperties.containsSubSet(Scine::Utils::Property::Hessian) or
_requiredProperties.containsSubSet(Scine::Utils::Property::Thermochemistry)) {
Scine::Utils::ResultsAutoCompleter completer(*_structure);
completer.setTemperature(_settings.getDouble(Utils::SettingsNames::temperature));
completer.setMolecularSymmetryNumber(_settings.getInt(Utils::SettingsNames::symmetryNumber));
completer.addOneWantedProperty(Scine::Utils::Property::Thermochemistry);
completer.generateProperties(this->_results, *_structure);
}
// Clean XTB data structures
_cleanDataStructures(env, calc, res, mol);
return this->_results;
}
} /* namespace Xtb */
} /* namespace Scine */
| 43.771429 | 120 | 0.701567 | [
"vector",
"model"
] |
c2958493529754bc893d10657ea5cb9a5e613964 | 4,819 | cpp | C++ | Clustering/k-means Clustering.cpp | PetarV-/Machine-Learning | 9f5da3bc49f81895e04e3c6d7677f4c0dc8760b9 | [
"MIT"
] | 9 | 2018-07-22T11:03:22.000Z | 2022-01-02T11:45:33.000Z | Clustering/k-means Clustering.cpp | PetarV-/Machine-Learning | 9f5da3bc49f81895e04e3c6d7677f4c0dc8760b9 | [
"MIT"
] | null | null | null | Clustering/k-means Clustering.cpp | PetarV-/Machine-Learning | 9f5da3bc49f81895e04e3c6d7677f4c0dc8760b9 | [
"MIT"
] | 6 | 2017-04-18T16:53:27.000Z | 2020-02-18T04:48:32.000Z | /*
Petar 'PetarV' Velickovic
Algorithm: k-means Clustering (Lloyd's Algorithm)
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <assert.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <complex>
using namespace std;
typedef long long lld;
/*
The k-means Clustering algorithm aims to partition a set of observed points in a
multi-dimensional space into k subsets (clusters).
In general, finding the optimal means is an NP-hard problem, and therefore a heuristic
approach (Lloyd's Algorithm) is performed; initially, k means are selected at random,
and then each observation is assigned into the cluster corresponding to the mean which
is closest to it. The means are then updated and the procedure is iterated until
convergence is achieved. As this heuristic is very efficient, one may run it multiple times
(with different initial conditions) and choose the most-preferred clustering.
*/
double sq_distance(vector<double> &a, vector<double> &b)
{
assert(a.size() == b.size());
double ret = 0.0;
for (int i=0;i<a.size();i++)
{
ret += (a[i] - b[i]) * (a[i] - b[i]);
}
return ret;
}
vector<vector<int> > k_means(vector<vector<double> > &pts, int k)
{
int n = pts.size();
int d = pts[0].size();
assert(n >= k);
/*
Here, Forgy initialisation is used: initially one randomly chooses k
of the observations to serve as the initial means.
Another approach is random initialisation: initially assigning each
observation to a cluster, and then computing means from there.
*/
vector<vector<double> > means;
means.resize(k);
set<int> chosen;
for (int i=0;i<k;i++)
{
int id;
do
{
id = rand() % n;
} while (chosen.count(id) > 0);
means[i].resize(d);
for (int j=0;j<d;j++) means[i][j] = pts[id][j];
chosen.insert(id);
}
vector<int> cluster_assigned;
cluster_assigned.resize(n);
for (int i=0;i<n;i++) cluster_assigned[i] = 0;
bool change;
do
{
change = false;
// Assignment step: assign each observation to closest mean's cluster
for (int i=0;i<n;i++)
{
double best_dist = 0.0;
int best_mean = -1;
for (int j=0;j<k;j++)
{
double curr_dist = sq_distance(pts[i], means[j]);
if (best_mean == -1 || best_dist > curr_dist)
{
best_dist = curr_dist;
best_mean = j;
}
}
if (best_mean != cluster_assigned[i]) change = true;
cluster_assigned[i] = best_mean;
}
// Update step: recompute the means for each cluster
vector<int> counts;
counts.resize(k);
for (int i=0;i<k;i++)
{
for (int j=0;j<d;j++)
{
means[i][j] = 0.0;
}
}
for (int i=0;i<n;i++)
{
counts[cluster_assigned[i]]++;
for (int j=0;j<d;j++)
{
means[cluster_assigned[i]][j] += pts[i][j];
}
}
for (int i=0;i<k;i++)
{
assert(counts[i] > 0);
for (int j=0;j<d;j++)
{
means[i][j] /= counts[i];
}
}
} while (change); // Iterate until convergence
// Reconstruct the clustering
vector<vector<int> > ret;
ret.resize(k);
for (int i=0;i<n;i++)
{
ret[cluster_assigned[i]].push_back(i);
}
return ret;
}
int main()
{
// Generate an easily separable test set
int n = 50;
int d = 2;
int k = 4;
vector<vector<double> > points;
int pos[4][2] = {{0, 0}, {5, 0}, {0, 5}, {5, 5}};
for (int i=0;i<k;i++)
{
for (int j=0;j<n;j++)
{
vector<double> coords;
coords.resize(d);
for (int k=0;k<d;k++)
{
double rnd = (double)rand() / RAND_MAX;
double delta = 2 * rnd;
if (rand() % 2) delta *= -1;
coords.push_back(pos[i][k] + delta);
}
points.push_back(coords);
}
}
vector<vector<int> > ret = k_means(points, k);
printf("k-means clustering found the following clusters:\n");
for (int i=0;i<ret.size();i++)
{
printf("{");
for (int j=0;j<ret[i].size();j++)
{
printf("%d%s", ret[i][j], (j != ret[i].size() - 1) ? ", " : "}\n");
}
}
return 0;
}
| 25.497354 | 93 | 0.512139 | [
"vector"
] |
c2a6042597119184bd5f029ed85005ce8c298ccf | 3,483 | cpp | C++ | src/Lynx/Components/CameraComponent.cpp | ichi-raven/LynxEngine | c3541498e15d526f78f80ece1ce8a725457ae1c1 | [
"MIT"
] | null | null | null | src/Lynx/Components/CameraComponent.cpp | ichi-raven/LynxEngine | c3541498e15d526f78f80ece1ce8a725457ae1c1 | [
"MIT"
] | null | null | null | src/Lynx/Components/CameraComponent.cpp | ichi-raven/LynxEngine | c3541498e15d526f78f80ece1ce8a725457ae1c1 | [
"MIT"
] | null | null | null | #include <Lynx/Components/CameraComponent.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/quaternion.hpp>
#include <iostream>//debug
namespace Lynx
{
CameraComponent::CameraComponent()
{
mEnable = true;
mLookPos = glm::vec3(0, 0, 10.f);
mUp = glm::vec3(0, 1.f, 0);
mFovY = glm::radians(45.f);
mAspect = 640.f / 480.f;//適当、設定すべきである
mNear = 0.1f;
mFar = static_cast<float>(1e6);
}
void CameraComponent::setEnable(bool flag)
{
mEnable = flag;
}
void CameraComponent::setEnable()
{
mEnable = !mEnable;
}
const bool CameraComponent::getEnable() const
{
return mEnable;
}
void CameraComponent::setTransform(const Transform& transform)
{
mTransform = transform;
}
Transform& CameraComponent::getTransform()
{
return mTransform;
}
const Transform& CameraComponent::getTransform() const
{
return mTransform;
}
void CameraComponent::setViewParam(const glm::vec3& lookPos, const glm::vec3& up)
{
mLookPos = lookPos;
mUp = up;
}
void CameraComponent::setLookAt(const glm::vec3& lookPos)
{
mLookPos = lookPos;
}
const glm::vec3& CameraComponent::getLookAt() const
{
return mLookPos;
}
void CameraComponent::setUpDir(const glm::vec3& up)
{
mUp = up;
}
const glm::vec3& CameraComponent::getUpDir() const
{
return mUp;
}
void CameraComponent::setProjectionParam(float fovAngle, uint32_t width, uint32_t height, float near, float far)
{
mFovY = glm::radians(fovAngle);
setAspectAuto(width, height);
mNear = near;
mFar = far;
}
void CameraComponent::setFovY(float fovAngle)
{
mFovY = fovAngle;
}
const float CameraComponent::getFovY() const
{
return mFovY;
}
void CameraComponent::setAspect(float aspect)
{
mAspect = aspect;
}
void CameraComponent::setAspectAuto(uint32_t screenWidth, uint32_t screenHeight)
{
mAspect = 1.f * screenWidth / screenHeight;
}
const float CameraComponent::getAspect() const
{
return mAspect;
}
void CameraComponent::setNearFar(float near, float far)
{
mNear = near;
mFar = far;
}
const float CameraComponent::getNear() const
{
return mNear;
}
const float CameraComponent::getFar() const
{
return mFar;
}
const glm::mat4& CameraComponent::getViewMatrix() const
{
return mView;
}
const glm::mat4& CameraComponent::getProjectionMatrix() const
{
return mProjection;
}
void CameraComponent::update()
{
mTransform.update();
mView = glm::lookAtRH(mTransform.getPos(), mLookPos, mUp);
mProjection = glm::perspective(mFovY, mAspect, mNear, mFar);
mProjection[1][1] *= -1;
// std::cout << "view : \n";
// for(int i = 0; i < 4; ++i)
// {
// for(int j = 0; j < 4; ++j)
// std::cout << mView[i][j] << " ";
// std::cout << "\n";
// }
// std::cout << "projection : \n";
// for(int i = 0; i < 4; ++i)
// {
// for(int j = 0; j < 4; ++j)
// std::cout << mProjection[i][j] << " ";
// std::cout << "\n";
// }
}
} | 21.76875 | 116 | 0.549526 | [
"transform"
] |
c2a7763ff000f8d6f7452b9d39cda087339f5dc0 | 7,424 | cpp | C++ | src/core/mesh/qgsmeshlayerutils.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | src/core/mesh/qgsmeshlayerutils.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | src/core/mesh/qgsmeshlayerutils.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | 1 | 2021-12-25T08:40:30.000Z | 2021-12-25T08:40:30.000Z | /***************************************************************************
qgsmeshlayerutils.cpp
--------------------------
begin : August 2018
copyright : (C) 2018 by Martin Dobias
email : wonder dot sk at gmail dot com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsmeshlayerutils.h"
#include "qgsmeshtimesettings.h"
#include <limits>
#include <QTime>
#include <QDateTime>
///@cond PRIVATE
QVector<double> QgsMeshLayerUtils::calculateMagnitudes( const QgsMeshDataBlock &block )
{
Q_ASSERT( QgsMeshDataBlock::ActiveFlagInteger != block.type() );
int count = block.count();
QVector<double> ret( count );
for ( int i = 0; i < count; ++i )
{
double mag = block.value( i ).scalar();
ret[i] = mag;
}
return ret;
}
void QgsMeshLayerUtils::boundingBoxToScreenRectangle( const QgsMapToPixel &mtp,
const QSize &outputSize,
const QgsRectangle &bbox,
int &leftLim,
int &rightLim,
int &topLim,
int &bottomLim )
{
QgsPointXY ll = mtp.transform( bbox.xMinimum(), bbox.yMinimum() );
QgsPointXY ur = mtp.transform( bbox.xMaximum(), bbox.yMaximum() );
topLim = std::max( int( ur.y() ), 0 );
bottomLim = std::min( int( ll.y() ), outputSize.height() - 1 );
leftLim = std::max( int( ll.x() ), 0 );
rightLim = std::min( int( ur.x() ), outputSize.width() - 1 );
}
static void lamTol( double &lam )
{
const static double eps = 1e-6;
if ( ( lam < 0.0 ) && ( lam > -eps ) )
{
lam = 0.0;
}
}
static bool E3T_physicalToBarycentric( const QgsPointXY &pA, const QgsPointXY &pB, const QgsPointXY &pC, const QgsPointXY &pP,
double &lam1, double &lam2, double &lam3 )
{
if ( pA == pB || pA == pC || pB == pC )
return false; // this is not a valid triangle!
// Compute vectors
QgsVector v0( pC - pA );
QgsVector v1( pB - pA );
QgsVector v2( pP - pA );
// Compute dot products
double dot00 = v0 * v0;
double dot01 = v0 * v1;
double dot02 = v0 * v2;
double dot11 = v1 * v1;
double dot12 = v1 * v2;
// Compute barycentric coordinates
double invDenom = 1.0 / ( dot00 * dot11 - dot01 * dot01 );
lam1 = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
lam2 = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
lam3 = 1.0 - lam1 - lam2;
// Apply some tolerance to lam so we can detect correctly border points
lamTol( lam1 );
lamTol( lam2 );
lamTol( lam3 );
// Return if POI is outside triangle
if ( ( lam1 < 0 ) || ( lam2 < 0 ) || ( lam3 < 0 ) )
{
return false;
}
return true;
}
double QgsMeshLayerUtils::interpolateFromVerticesData( const QgsPointXY &p1, const QgsPointXY &p2, const QgsPointXY &p3,
double val1, double val2, double val3, const QgsPointXY &pt )
{
double lam1, lam2, lam3;
if ( !E3T_physicalToBarycentric( p1, p2, p3, pt, lam1, lam2, lam3 ) )
return std::numeric_limits<double>::quiet_NaN();
return lam1 * val3 + lam2 * val2 + lam3 * val1;
}
double QgsMeshLayerUtils::interpolateFromFacesData( const QgsPointXY &p1, const QgsPointXY &p2, const QgsPointXY &p3,
double val, const QgsPointXY &pt )
{
double lam1, lam2, lam3;
if ( !E3T_physicalToBarycentric( p1, p2, p3, pt, lam1, lam2, lam3 ) )
return std::numeric_limits<double>::quiet_NaN();
return val;
}
QgsRectangle QgsMeshLayerUtils::triangleBoundingBox( const QgsPointXY &p1, const QgsPointXY &p2, const QgsPointXY &p3 )
{
// p1
double xMin = p1.x();
double xMax = p1.x();
double yMin = p1.y();
double yMax = p1.y();
//p2
xMin = ( ( xMin < p2.x() ) ? xMin : p2.x() );
xMax = ( ( xMax > p2.x() ) ? xMax : p2.x() );
yMin = ( ( yMin < p2.y() ) ? yMin : p2.y() );
yMax = ( ( yMax > p2.y() ) ? yMax : p2.y() );
// p3
xMin = ( ( xMin < p3.x() ) ? xMin : p3.x() );
xMax = ( ( xMax > p3.x() ) ? xMax : p3.x() );
yMin = ( ( yMin < p3.y() ) ? yMin : p3.y() );
yMax = ( ( yMax > p3.y() ) ? yMax : p3.y() );
QgsRectangle bbox( xMin, yMin, xMax, yMax );
return bbox;
}
QString QgsMeshLayerUtils::formatTime( double hours, const QgsMeshTimeSettings &settings )
{
QString ret;
if ( settings.useAbsoluteTime() )
{
QString format( settings.absoluteTimeFormat() );
QDateTime dateTime( settings.absoluteTimeReferenceTime() );
int seconds = static_cast<int>( hours * 3600.0 );
dateTime = dateTime.addSecs( seconds );
ret = dateTime.toString( format );
if ( ret.isEmpty() ) // error
ret = dateTime.toString();
}
else
{
QString format( settings.relativeTimeFormat() );
format = format.trimmed();
hours = hours + settings.relativeTimeOffsetHours();
int totalHours = static_cast<int>( hours );
if ( format == QStringLiteral( "hh:mm:ss.zzz" ) )
{
int ms = static_cast<int>( hours * 3600.0 * 1000 );
int seconds = ms / 1000;
int z = ms % 1000;
int m = seconds / 60;
int s = seconds % 60;
int h = m / 60;
m = m % 60;
ret = QStringLiteral( "%1:%2:%3.%4" ).
arg( h, 2, 10, QLatin1Char( '0' ) ).
arg( m, 2, 10, QLatin1Char( '0' ) ).
arg( s, 2, 10, QLatin1Char( '0' ) ).
arg( z, 3, 10, QLatin1Char( '0' ) );
}
else if ( format == QStringLiteral( "hh:mm:ss" ) )
{
int seconds = static_cast<int>( hours * 3600.0 );
int m = seconds / 60;
int s = seconds % 60;
int h = m / 60;
m = m % 60;
ret = QStringLiteral( "%1:%2:%3" ).
arg( h, 2, 10, QLatin1Char( '0' ) ).
arg( m, 2, 10, QLatin1Char( '0' ) ).
arg( s, 2, 10, QLatin1Char( '0' ) );
}
else if ( format == QStringLiteral( "d hh:mm:ss" ) )
{
int seconds = static_cast<int>( hours * 3600.0 );
int m = seconds / 60;
int s = seconds % 60;
int h = m / 60;
m = m % 60;
int d = totalHours / 24;
h = totalHours % 24;
ret = QStringLiteral( "%1 d %2:%3:%4" ).
arg( d ).
arg( h, 2, 10, QLatin1Char( '0' ) ).
arg( m, 2, 10, QLatin1Char( '0' ) ).
arg( s, 2, 10, QLatin1Char( '0' ) );
}
else if ( format == QStringLiteral( "d hh" ) )
{
int d = totalHours / 24;
int h = totalHours % 24;
ret = QStringLiteral( "%1 d %2" ).
arg( d ).
arg( h );
}
else if ( format == QStringLiteral( "d" ) )
{
int d = totalHours / 24;
ret = QStringLiteral( "%1" ).arg( d );
}
else if ( format == QStringLiteral( "ss" ) )
{
int seconds = static_cast<int>( hours * 3600.0 );
ret = QStringLiteral( "%1" ).arg( seconds );
}
else // "hh"
{
ret = QStringLiteral( "%1" ).arg( hours );
}
}
return ret;
}
///@endcond
| 31.193277 | 126 | 0.525189 | [
"transform"
] |
c2a7e99c27e014d348138e45319c166b80e0613c | 3,216 | cc | C++ | img_analysis/src/img_vent.cc | CodeMasterBond/isaac | b21a533cf30eed012fe12ece047b6d87418d7c6f | [
"Apache-2.0"
] | 19 | 2021-11-18T19:29:16.000Z | 2022-02-23T01:55:51.000Z | img_analysis/src/img_vent.cc | CodeMasterBond/isaac | b21a533cf30eed012fe12ece047b6d87418d7c6f | [
"Apache-2.0"
] | 13 | 2021-11-30T17:14:46.000Z | 2022-03-22T21:38:33.000Z | img_analysis/src/img_vent.cc | CodeMasterBond/isaac | b21a533cf30eed012fe12ece047b6d87418d7c6f | [
"Apache-2.0"
] | 6 | 2021-12-03T02:38:21.000Z | 2022-02-23T01:52:03.000Z | /* Copyright (c) 2021, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
*
* All rights reserved.
*
* The "ISAAC - Integrated System for Autonomous and Adaptive Caretaking
* platform" software is licensed under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include <img_analysis/img_vent.h>
namespace img_analysis {
ImgVent::ImgVent() {
// Read the configuration
config_reader::ConfigReader config_params;
// Set the config path to ISAAC
char *path = getenv("CUSTOM_CONFIG_DIR");
if (path != NULL)
config_params.SetPath(path);
config_params.AddFile("anomaly/img_vent.config");
if (!config_params.ReadFiles()) ROS_FATAL("Couldn't read config file");
// Get the name of the CNN
std::string network_name;
if (!config_params.GetStr("network_name", &network_name))
ROS_FATAL("Could not find row 'network_name' in table");
// Set the config path back to freeflyer
path = getenv("ASTROBEE_CONFIG_DIR");
if (path != NULL)
config_params.SetPath(path);
// Set the model path to to resources
char *model_path = getenv("ISAAC_CNN_DIR");
if (model_path == NULL)
ROS_ERROR("Path containing CNN models not specified");
// Upload the model
try {
// Deserialize the ScriptModule from a file using torch::jit::load().
module_ = torch::jit::load(std::string(model_path) + "/" + network_name);
}
catch (const c10::Error& e) {
ROS_ERROR_STREAM("error loading the model\n");
return;
}
// ROS_ERROR("ok");
}
int ImgVent::AnalysePic(cv::Mat input_img) {
std::stringstream buffer_print;
// Resize the input image and transform
cv::resize(input_img, input_img, cv::Size(244, 244), 0, 0, cv::INTER_CUBIC);
// Create the tensor
at::Tensor input_tensor;
input_tensor = torch::from_blob(input_img.data,
{ 1, input_img.rows, input_img.cols, 3 }, at::kByte).to(at::kFloat);
input_tensor = input_tensor.permute({ 0, 3, 1, 2 }); // convert to CxHxW
// Convert data from 0->255 to 0->1
input_tensor = input_tensor.div(255);
// Normalize channels
std::vector<at::Tensor> splits = input_tensor.split(1, 1);
splits[2] = splits[2].sub(0.485).div(0.229); // Normalize channel G
splits[1] = splits[1].sub(0.456).div(0.224); // Normalize channel B
splits[0] = splits[0].sub(0.406).div(0.225); // Normalize channel R
input_tensor = at::cat({splits[2], splits[1], splits[0]}, 1);
at::Tensor output = module_.forward({input_tensor}).toTensor();
output = output.exp();
return output.argmax().item().to<int64_t>();
}
} // namespace img_analysis
| 36.134831 | 80 | 0.675995 | [
"vector",
"model",
"transform"
] |
c2b9a667b54350ee547b23b036a36c716c7cf542 | 4,145 | hpp | C++ | libcore/src/util/BoundingInfo.hpp | danielrh/sirikata | 063740f96f24f6f60b047453f7254297d1a33f29 | [
"BSD-3-Clause"
] | 3 | 2015-12-23T14:26:05.000Z | 2016-05-09T04:05:51.000Z | libcore/src/util/BoundingInfo.hpp | danielrh/sirikata | 063740f96f24f6f60b047453f7254297d1a33f29 | [
"BSD-3-Clause"
] | null | null | null | libcore/src/util/BoundingInfo.hpp | danielrh/sirikata | 063740f96f24f6f60b047453f7254297d1a33f29 | [
"BSD-3-Clause"
] | null | null | null | /* Meru
* BoundingInfo.hpp
*
* Copyright (c) 2009, Stanford University
* 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 Sirikata 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.
*/
#ifndef _BOUNDING_INFO_HPP_
#define _BOUNDING_INFO_HPP_
#include "Vector3.hpp"
#include "BoundingBox.hpp"
#include "BoundingSphere.hpp"
namespace Sirikata {
/** BoundingInfo represents a 3D axis aligned bounding box and a radius around it. Used for bounding a centered mesh. Use BoundingBox for spacial information */
class SIRIKATA_EXPORT BoundingInfo {
public:
/** Construct a degenerate bounding box. */
BoundingInfo();
/** Construct a bounding box with the given minimum and maximum
* points.
* \param bbmin minimum point of bounding box
* \param bbmax maximum point of bounding box
* \param radius is the radial size of the boudning box (not necessarily diagonal size
*/
BoundingInfo(const Vector3f& bbmin, const Vector3f& bbmax, float32 radius);
/** Construct a bounding box with the given minimum and maximum
* points.
* \param bbmin minimum point of bounding box
* \param bbmax maximum point of bounding box
* note the radius is calculated from the impoverished information
*/
BoundingInfo(const Vector3f& bbmin, const Vector3f& bbmax);
/** Construct a bounding box centered at the origin which encompasses
* a sphere with the given radius.
*/
explicit BoundingInfo(float32 radius);
/** Construct a bounding box which encompasses the given
* bounding sphere.
*/
explicit BoundingInfo(const BoundingSphere<float32>& bs);
BoundingInfo scale(const Vector3f &scale)const;
/** Returns the minimum point of the bounding box. */
const Vector3f& min() const{return mMin;}
/** Returns the maximum point of the bounding box. */
const Vector3f& max() const{return mMax;}
/** Returns the diagonal vector of the bounding box, i.e. max - min. */
Vector3f diag() const;
/** Returns the center of the bounding box. */
Vector3f center() const;
BoundingBox<float32> boundingBox()const;
/** Returns the union of this bounding box with the given bounding box. */
BoundingInfo merge(const BoundingBox<float32>& bbox) const;
/** Returns the union of this bounding box with the given bounding box. */
BoundingInfo merge(const BoundingInfo& bbox) const;
/** Returns the union of this bounding box with the given point. */
BoundingInfo merge(const Vector3f& point) const;
float32 radius()const { return mRadius; }
private:
Vector3f mMin;
float32 mRadius;
Vector3f mMax;
}; // class Bounding Box
} // namespace Meru
#endif //_BOUNDING_BOX_HPP_
| 43.631579 | 161 | 0.727141 | [
"mesh",
"vector",
"3d"
] |
c2bc37d95cef0358000bc58549cbf46bdcd280ce | 2,088 | hh | C++ | src/lib/MeshFEM/GlobalBenchmark.hh | pbedenbaugh/MeshFEM | 742d609d4851582ffb9c5616774fc2ef489e2f88 | [
"MIT"
] | null | null | null | src/lib/MeshFEM/GlobalBenchmark.hh | pbedenbaugh/MeshFEM | 742d609d4851582ffb9c5616774fc2ef489e2f88 | [
"MIT"
] | null | null | null | src/lib/MeshFEM/GlobalBenchmark.hh | pbedenbaugh/MeshFEM | 742d609d4851582ffb9c5616774fc2ef489e2f88 | [
"MIT"
] | null | null | null | #ifndef GLOBALBENCHMARK_HH
#define GLOBALBENCHMARK_HH
#include <vector>
#include <string>
#include <iostream>
#include <MeshFEM_export.h>
#ifdef BENCHMARK
#include <MeshFEM/Timer.hh>
MESHFEM_EXPORT extern Timer g_timer;
MESHFEM_EXPORT extern std::vector<std::string> g_benchmarkMessages;
inline void BENCHMARK_START_TIMER_SECTION(const std::string &name) { g_timer.startSection(name); }
inline void BENCHMARK_STOP_TIMER_SECTION(const std::string &name) { g_timer.stopSection(name); }
inline void BENCHMARK_START_TIMER(const std::string &name) { g_timer.start(name); }
inline void BENCHMARK_STOP_TIMER(const std::string &name) { g_timer.stop(name); }
inline void BENCHMARK_RESET() { g_timer.reset(); }
inline void BENCHMARK_ADD_MESSAGE(const std::string &msg) {
g_benchmarkMessages.push_back(msg);
}
inline void BENCHMARK_CLEAR_MESSAGES() { g_benchmarkMessages.clear(); }
inline void BENCHMARK_REPORT() {
for (const auto &message : g_benchmarkMessages)
std::cout << message << std::endl;
g_timer.report(std::cout);
}
inline void BENCHMARK_REPORT_NO_MESSAGES() {
g_timer.report(std::cout);
}
#else
inline void BENCHMARK_START_TIMER_SECTION(const std::string &/* name */) { }
inline void BENCHMARK_STOP_TIMER_SECTION(const std::string &/* name */) { }
inline void BENCHMARK_START_TIMER(const std::string &/* name */) { }
inline void BENCHMARK_STOP_TIMER(const std::string &/* name */) { }
inline void BENCHMARK_RESET() { }
inline void BENCHMARK_ADD_MESSAGE(const std::string &/* msg */) { }
inline void BENCHMARK_CLEAR_MESSAGES() { }
inline void BENCHMARK_REPORT() { }
inline void BENCHMARK_REPORT_NO_MESSAGES() { }
#endif
struct BENCHMARK_SCOPED_TIMER_SECTION {
BENCHMARK_SCOPED_TIMER_SECTION(const std::string &name) : m_name(name) {
BENCHMARK_START_TIMER_SECTION(name);
}
~BENCHMARK_SCOPED_TIMER_SECTION() {
BENCHMARK_STOP_TIMER_SECTION(m_name);
}
private:
std::string m_name;
};
#endif /* end of include guard: GLOBALBENCHMARK_HH */
| 33.677419 | 98 | 0.71887 | [
"vector"
] |
c2c55bcec1ec44649ac96c1204d4aa44379398e5 | 10,355 | cpp | C++ | source/hw2.cpp | bluemner/image_processing | e5e6a611b4a4a011ea14d6eaac921c8f54300d97 | [
"MIT"
] | null | null | null | source/hw2.cpp | bluemner/image_processing | e5e6a611b4a4a011ea14d6eaac921c8f54300d97 | [
"MIT"
] | null | null | null | source/hw2.cpp | bluemner/image_processing | e5e6a611b4a4a011ea14d6eaac921c8f54300d97 | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <thread>
#define _USE_MATH_DEFINES
#include <cmath>
#include "../headers/PGM.hpp"
#define T double
#define B 256
#define __SIGMA__ 5
void apply_mask(const int segment_start, // start of segment
const int segment_size, // segment size
const int mask_size, // size of mask
T** mask, // mask
const int y_dimension, // image height
const int x_dimension, // image width
unsigned char * original,
unsigned char * filtered)
{
int k_shift = 0;
int l_shift = 0;
T temp_0 =0;
T temp_1 =0;
for(int i =0; i<x_dimension; i++){
for(int j=segment_start; j< segment_size; j++){
for(int k=0; k < mask_size; k++){
for(int l=0;l < mask_size; l++){
//filtered[j*image_width+ i] = mask[k-i][l-j] *filtered[j*image_width+ i];
k_shift = i - k / 2;
l_shift = j - l / 2;
if( k_shift < 0 || k_shift >= x_dimension){
k_shift=0;
}
if( l_shift < 0 || l_shift >=y_dimension ){
l_shift=0;
}
filtered[j*x_dimension+ i] += mask[l][k] * original[l_shift*x_dimension+k_shift ];
temp_0 += mask[l][k] * original[l_shift*x_dimension+k_shift ];
temp_1 += mask[l][k];
}
}
filtered[j*x_dimension+ i] = (unsigned char) (temp_0 / temp_1); ///
temp_0 =0;
temp_1 =0;
if(i+1 == x_dimension && j+1==segment_size )
std::cout<<"Done with Row::"<< j << std::endl;
}
}
std::cout << "Exiting thread" <<std::endl;
}
void get_gaussian_mask(const int size, T** mask)
{
// 5 /2 = 2;
int mp =(int) size / 2;
T sigma = (T) __SIGMA__;
T r;
T s = 2.0 * sigma * sigma;
T sum = 0.0;
std::cout<< "mp:\t" <<mp<< "\t"<< (-1* mp) << std::endl;
for(int i = (-1* mp); i<= mp; i++){
for(int j = (-1* mp); j<= mp; j++){
r = sqrt(i*i + j*j);
mask[i + mp][j + mp] = (exp(-(r*r)/s))/(M_PI * s);
sum += mask[i + mp][j + mp];
}
}
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
mask[i][j] /= sum;
}
}
}
void apply_bilateral_filtering_mask(
const int segment_start, // start of segment
const int segment_size, // segment size
const int mask_size, // size of mask
T** mask, // mask
const int mask_2_size,
T* mask_2,
const int y_dimension, // image height
const int x_dimension, // image width
unsigned char * original,
unsigned char * filtered)
{
int k_shift = 0;
int l_shift = 0;
T temp_0 =0;
T temp_1 =0;
for(int i =0; i<x_dimension; i++){
for(int j=segment_start; j< segment_size; j++){
for(int k=0; k < mask_size; k++){
for(int l=0;l < mask_size; l++){
//filtered[j*image_width+ i] = mask[k-i][l-j] *filtered[j*image_width+ i];
k_shift = i - k / 2;
l_shift = j - l / 2;
if( k_shift < 0 || k_shift >= x_dimension){
k_shift=0;
}
if( l_shift < 0 || l_shift >=y_dimension ){
l_shift=0;
}
int abs_ps = (int) abs(original[l_shift*x_dimension+k_shift ]- original[j * x_dimension + i]);
// filtered[j*x_dimension+ i] += mask[l][k]
// * original[l_shift*x_dimension+k_shift ]
// * mask_2[abs_ps];
temp_0 += mask[l][k] *mask_2[abs_ps]* original[l_shift*x_dimension+k_shift ] ;
temp_1 += mask[l][k] *mask_2[abs_ps] ; // mask_2[abs_ps]
}
}
filtered[j*x_dimension+ i] = (unsigned char) floor(temp_0 / temp_1);
temp_0 =0;
temp_1 =0;
if(i+1 == x_dimension && j+1==segment_size )
std::cout<<"Done with Row::"<< j << std::endl;
}
}
std::cout << "Exiting thread" <<std::endl;
}
void bilateral_filtering_mask(const int mask_1_size, T** mask_1, const int mask_2_size , T* mask_2)
{
// 5 /2 = 2;
int mp =(int) mask_1_size / 2;
T sigma_s = __SIGMA__, sigma_r =__SIGMA__;
T rs = 2.0 * sigma_r * sigma_s;
T s = 2.0 * sigma_s * sigma_s;
T sum = 0.0;
std::cout<< "mp:\t" <<mp<< "\t"<< (-1* mp) << std::endl;
for(int i = (-1* mp); i<= mp; i++){
for(int j = (-1* mp); j<= mp; j++){
mask_1[i+mp][j+mp] = exp(-(i*i+j*j)/(s));
}
}
for(int i=0; i<mask_2_size; i++){
mask_2[i] = exp(-((i)/rs));
}
}
void print(const int size, T** mask){
for(int i=0; i< size; i++){
for(int j=0; j<size; j++){
std::cout<< std::setprecision(16);
std::cout<< mask[i][j] << "\t";
}
std::cout << std::endl;
}
}
/*
*
* argc - argument count
* argv - argument vector
*
*/
int main(int argc, char * argv[]){
if (argc < 6){
std::cout << "Usage:" << std::endl;
std::cout << "\t<file_path_original>" << std::endl;
std::cout << "\t<file_path_new_bilateral_filtering>" << std::endl;
std::cout << "\t<file_path_new_gaussian>" << std::endl;
std::cout << "\t<mask_size>" << std::endl;
std::cout << "\t<cpu_thread_count>" << std::endl;
exit(-1);
}
std::string file_path_original = std::string(argv[1]);
std::string file_path_new_bilateral_filtering = std::string(argv[2]);
std::string file_path_new_gaussian = std::string(argv[3]);
int mask_size = std::stoi(argv[4]);
int thread_count = std::stoi(argv[5]);
if(mask_size < 1 || thread_count < 1){
std::cerr << "mask_size >=1 & thread_count >=1" <<std::endl;
return -1;
}else if(mask_size % 2 == 0){
std::cerr << "Mask size should be an odd number" <<std::endl;
return -1;
}
int x_dimension = 0, y_dimension = 0;
std::vector<unsigned char> image;
UWM::PGM().read(file_path_original, image, x_dimension, y_dimension);
unsigned char * test_image= image.data();
//UWM::PGM().read(file_path_original, test_image, x_dimension, y_dimension);
std::cout<<"Image Loaded"<< std::endl;
// Memory allocation
T** mask = new T*[mask_size];
for(int i = 0; i < mask_size; i++){
mask[i] = new T[mask_size];
for(int j=0; j<mask_size; j++){
mask[i][j] = (T) 0.0;
}
}
int mask_2_size = B;
T* mask_2 = new T[mask_2_size]; // This should be change if using more then 256 for storage
get_gaussian_mask(mask_size, mask);
print(mask_size,mask);
unsigned char * fi = new unsigned char[x_dimension * y_dimension];
unsigned char * gi = new unsigned char[x_dimension * y_dimension];
std::vector<std::thread> thread_list;
int segment_size = y_dimension / thread_count;
int segment_size_adj = y_dimension / thread_count;
int segment_mod = y_dimension % thread_count;
int segment_start =0;
for( int current_thread = 0 ; current_thread < thread_count; ++current_thread )
{
if(segment_mod > 0){
segment_size_adj = segment_start + segment_size + 1;
--segment_mod;
}else{
segment_size_adj = segment_start+ segment_size;
}
std::cout<<"Thread::"<< current_thread <<std::endl;
std::cout<<"Start::"<< segment_start <<std::endl;
std::cout<<"End::"<< segment_size_adj <<std::endl;
thread_list.push_back(
std::thread(apply_mask,segment_start,
segment_size_adj, mask_size,
mask,
y_dimension,
x_dimension,
test_image,
gi)
);
segment_start = segment_size_adj;
}
//apply_mask(0,y_dimension , mask_size,mask,y_dimension, x_dimension,test_image, fi);
/*
bilateral_filtering(
const int segment_start,
const int segment_size,
const int mask_size,
const int y_dimension, // image height
const int x_dimension, // image width
unsigned char * original,
unsigned char * filtered)
*/
for(int i = 0 ; i < thread_list.size(); ++i){
thread_list[i].join();
}
for(int i = 0; i < mask_size; i++){
for(int j=0; j<mask_size; j++){
mask[i][j] = (T) 0.0;
}
}
std::cout<<"BI"<<std::endl;
bilateral_filtering_mask(mask_size, mask, mask_2_size , mask_2);
print(mask_size,mask);
/*
const int segment_start, // start of segment
const int segment_size, // segment size
const int mask_size, // size of mask
T** mask, // mask
const int mask_2_size,
T* mask_2,
const int y_dimension, // image height
const int x_dimension, // image width
unsigned char * original,
unsigned char * filtered
*/
apply_bilateral_filtering_mask(0,y_dimension , mask_size,mask, mask_2_size, mask_2,y_dimension, x_dimension,test_image, fi);
std::cout<<"Saving..."<<std::endl;
UWM::PGM().write(file_path_new_bilateral_filtering,fi , x_dimension, y_dimension);
UWM::PGM().write(file_path_new_gaussian,gi, x_dimension, y_dimension);
int alt_x = x_dimension * 3 + 20;
unsigned char * temp_stich = new unsigned char[alt_x * y_dimension];
for(int i =0; i<x_dimension; i++){// columns
for(int j=0; j<y_dimension; j++){//rows
temp_stich[j*alt_x +i]=test_image[j*x_dimension+i];
temp_stich[j*alt_x +i+x_dimension+10]=fi[j*x_dimension+i];
temp_stich[j*alt_x +i+2*x_dimension+20]=gi[j*x_dimension+i];
}
}
UWM::PGM().write("STICH_SOURCE_BIF_GF.pgm",temp_stich, alt_x, y_dimension);
delete temp_stich;
// Clean up
for(int i = 0; i < mask_size; i++){
delete mask[i];
}
delete mask;
delete mask_2;
delete fi;
delete gi;
return 0;
} | 32.873016 | 128 | 0.526026 | [
"vector"
] |
c2c98d6777310abf38ec4f3289e3fa4fd6dc0766 | 3,285 | hpp | C++ | src/operator/denominator.hpp | susilehtola/aquarius | 9160e73bd7e3e0d8d97b10d00d9a4860aee709d2 | [
"BSD-3-Clause"
] | 18 | 2015-02-11T15:02:39.000Z | 2021-09-24T13:10:12.000Z | src/operator/denominator.hpp | susilehtola/aquarius | 9160e73bd7e3e0d8d97b10d00d9a4860aee709d2 | [
"BSD-3-Clause"
] | 21 | 2015-06-23T13:32:29.000Z | 2022-02-15T20:14:42.000Z | src/operator/denominator.hpp | susilehtola/aquarius | 9160e73bd7e3e0d8d97b10d00d9a4860aee709d2 | [
"BSD-3-Clause"
] | 8 | 2016-01-09T23:36:21.000Z | 2019-11-19T14:22:34.000Z | #ifndef _AQUARIUS_OPERATOR_DENOMINATOR_HPP_
#define _AQUARIUS_OPERATOR_DENOMINATOR_HPP_
#include "util/global.hpp"
#include "1eoperator.hpp"
#include "mooperator.hpp"
namespace aquarius
{
namespace op
{
template <typename T>
class Denominator : public op::MOOperator
{
protected:
vector<vector<T>> dA, da, dI, di;
public:
template <typename Derived>
Denominator(const OneElectronOperatorBase<T,Derived>& F)
: MOOperator(F)
{
int n = vrt.group.getNumIrreps();
dA.resize(n);
da.resize(n);
dI.resize(n);
di.resize(n);
for (int j = 0;j < n;j++)
{
dA[j].resize(vrt.nalpha[j]);
da[j].resize(vrt.nbeta[j]);
dI[j].resize(occ.nalpha[j]);
di[j].resize(occ.nbeta[j]);
vector<int> irreps(2,j);
if (arena.rank == 0)
{
int nA = dA[j].size();
int na = da[j].size();
int nI = dI[j].size();
int ni = di[j].size();
{
vector<tkv_pair<T>> pairs(nA);
for (int i = 0;i < nA;i++) pairs[i].k = i+i*nA;
F.getAB()({1,0},{1,0}).getRemoteData(irreps, pairs);
for (int i = 0;i < nA;i++) dA[j][pairs[i].k/nA] = -pairs[i].d;
}
{
vector<tkv_pair<T>> pairs(na);
for (int i = 0;i < na;i++) pairs[i].k = i+i*na;
F.getAB()({0,0},{0,0}).getRemoteData(irreps, pairs);
for (int i = 0;i < na;i++) da[j][pairs[i].k/na] = -pairs[i].d;
}
{
vector<tkv_pair<T>> pairs(nI);
for (int i = 0;i < nI;i++) pairs[i].k = i+i*nI;
F.getIJ()({0,1},{0,1}).getRemoteData(irreps, pairs);
for (int i = 0;i < nI;i++) dI[j][pairs[i].k/nI] = pairs[i].d;
}
{
vector<tkv_pair<T>> pairs(ni);
for (int i = 0;i < ni;i++) pairs[i].k = i+i*ni;
F.getIJ()({0,0},{0,0}).getRemoteData(irreps, pairs);
for (int i = 0;i < ni;i++) di[j][pairs[i].k/ni] = pairs[i].d;
}
}
else
{
F.getAB()({1,0},{1,0}).getRemoteData(irreps);
F.getAB()({0,0},{0,0}).getRemoteData(irreps);
F.getIJ()({0,1},{0,1}).getRemoteData(irreps);
F.getIJ()({0,0},{0,0}).getRemoteData(irreps);
}
arena.comm().Bcast(dA[j], 0);
arena.comm().Bcast(da[j], 0);
arena.comm().Bcast(dI[j], 0);
arena.comm().Bcast(di[j], 0);
}
}
const vector<vector<T>>& getDA() const { return dA; }
const vector<vector<T>>& getDa() const { return da; }
const vector<vector<T>>& getDI() const { return dI; }
const vector<vector<T>>& getDi() const { return di; }
};
}
}
#endif
| 32.524752 | 86 | 0.408524 | [
"vector"
] |
c2dbbd3969b5760536dbcb3721f5d7571264b843 | 494 | cpp | C++ | Courses/Synapse-Beginner-Regular-Season-2/Class-05-Recursion/Long-Contest-Code/B_Reverse_Root.cpp | shihab4t/Competitive-Programming | e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be | [
"Unlicense"
] | 3 | 2021-06-15T01:19:23.000Z | 2022-03-16T18:23:53.000Z | Courses/Synapse-Beginner-Regular-Season-2/Class-05-Recursion/Long-Contest-Code/B_Reverse_Root.cpp | shihab4t/Competitive-Programming | e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be | [
"Unlicense"
] | null | null | null | Courses/Synapse-Beginner-Regular-Season-2/Class-05-Recursion/Long-Contest-Code/B_Reverse_Root.cpp | shihab4t/Competitive-Programming | e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long int llint;
#define endn '\n'
#define pb push_back
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
llint n;
vector<double> sq_n;
while (cin >> n) {
sq_n.pb(sqrt(n));
}
int len = sq_n.size();
for (int i = len-1; i >= 0; i--) {
cout << fixed << setprecision(4) << sq_n[i] << endn;
}
}
// Solved By: shihab4t
// Tuesday, August 17, 2021 | 02:55:50 AM (+06) | 20.583333 | 60 | 0.564777 | [
"vector"
] |
c2dca9a6a13db2518825c74a2a8d4e282e13a055 | 2,909 | hpp | C++ | parser/spirit/syntax/Properties.hpp | Vitaliy-Grigoriev/PDL | da528e34e91add4e11415e31e01535db04e7043f | [
"MIT"
] | 1 | 2019-09-23T08:27:31.000Z | 2019-09-23T08:27:31.000Z | parser/spirit/syntax/Properties.hpp | Vitaliy-Grigoriev/PDL | da528e34e91add4e11415e31e01535db04e7043f | [
"MIT"
] | null | null | null | parser/spirit/syntax/Properties.hpp | Vitaliy-Grigoriev/PDL | da528e34e91add4e11415e31e01535db04e7043f | [
"MIT"
] | null | null | null | #pragma once
#include "Types.hpp"
#include "Methods.hpp"
#include <optional>
namespace pdl::spirit::syntax::properties {
struct RootProperty : Annotation<RootProperty>
{
[[maybe_unused]]
bool discovered = false;
};
struct NextProtocolProperty : Annotation<NextProtocolProperty>
{
std::vector<Identifier> protocols;
};
struct DefaultProperty : Annotation<DefaultProperty>
{
std::optional<literal::DefaultValue> value;
};
struct DefinitionProperty : Annotation<DefinitionProperty>
{
literal::Definition value;
};
struct PriorityProperty : Annotation<PriorityProperty>
{
uint16_t value = 0;
};
struct IeeeProperty : Annotation<IeeeProperty>
{
literal::Definition ieee;
};
struct RfcProperty : Annotation<RfcProperty>
{
uint16_t rfc = 0;
literal::Definition section;
};
struct RequiredProperty : Annotation<RequiredProperty>
{
[[maybe_unused]]
bool discovered = false;
};
struct VariableProperty : Annotation<VariableProperty>
{
[[maybe_unused]]
bool discovered = false;
};
struct FinalProperty : Annotation<FinalProperty>
{
[[maybe_unused]]
bool discovered = false;
};
struct ConstProperty : Annotation<ConstProperty>
{
[[maybe_unused]]
bool discovered = false;
};
struct CalculatedProperty : Annotation<CalculatedProperty>
{
[[maybe_unused]]
bool discovered = false;
};
struct EndianProperty : Annotation<EndianProperty>
{
types::EndianType type = types::EndianType::Little;
};
struct IdProperty : Annotation<IdProperty>
{
literal::Id id;
methods::PrefixMethod prefix;
};
} // namespace properties.
BOOST_FUSION_ADAPT_STRUCT(pdl::spirit::syntax::properties::RootProperty, discovered)
BOOST_FUSION_ADAPT_STRUCT(pdl::spirit::syntax::properties::NextProtocolProperty, protocols)
BOOST_FUSION_ADAPT_STRUCT(pdl::spirit::syntax::properties::DefaultProperty, value)
BOOST_FUSION_ADAPT_STRUCT(pdl::spirit::syntax::properties::DefinitionProperty, value)
BOOST_FUSION_ADAPT_STRUCT(pdl::spirit::syntax::properties::PriorityProperty, value)
BOOST_FUSION_ADAPT_STRUCT(pdl::spirit::syntax::properties::IeeeProperty, ieee)
BOOST_FUSION_ADAPT_STRUCT(pdl::spirit::syntax::properties::RfcProperty, rfc, section)
BOOST_FUSION_ADAPT_STRUCT(pdl::spirit::syntax::properties::RequiredProperty, discovered)
BOOST_FUSION_ADAPT_STRUCT(pdl::spirit::syntax::properties::VariableProperty, discovered)
BOOST_FUSION_ADAPT_STRUCT(pdl::spirit::syntax::properties::FinalProperty, discovered)
BOOST_FUSION_ADAPT_STRUCT(pdl::spirit::syntax::properties::ConstProperty, discovered)
BOOST_FUSION_ADAPT_STRUCT(pdl::spirit::syntax::properties::CalculatedProperty, discovered)
BOOST_FUSION_ADAPT_STRUCT(pdl::spirit::syntax::properties::EndianProperty, type)
BOOST_FUSION_ADAPT_STRUCT(pdl::spirit::syntax::properties::IdProperty, id, prefix)
| 27.971154 | 96 | 0.747336 | [
"vector"
] |
12403b36123511dd3202bf283e8eeea4d160e1aa | 4,905 | cpp | C++ | lab 1/Table_Lab_1/GeneratedFiles/Debug/moc_table_main_window.cpp | AlexandrPuryshev/Computer-graphics | b99c560fbbcadb2ff96c8d5fcaa60d4f718337de | [
"MIT"
] | 2 | 2015-10-07T07:55:46.000Z | 2015-10-07T08:28:28.000Z | lab 1/Table_Lab_1/GeneratedFiles/Debug/moc_table_main_window.cpp | AlexandrPuryshev/Computer-graphics | b99c560fbbcadb2ff96c8d5fcaa60d4f718337de | [
"MIT"
] | 1 | 2015-10-07T07:43:00.000Z | 2015-10-07T07:43:00.000Z | lab 1/Table_Lab_1/GeneratedFiles/Debug/moc_table_main_window.cpp | AlexandrPuryshev/Computer-graphics | b99c560fbbcadb2ff96c8d5fcaa60d4f718337de | [
"MIT"
] | null | null | null | /****************************************************************************
** Meta object code from reading C++ file 'table_main_window.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../table_main_window.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'table_main_window.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.5.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_Table_Main_Window_t {
QByteArrayData data[13];
char stringdata0[116];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_Table_Main_Window_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_Table_Main_Window_t qt_meta_stringdata_Table_Main_Window = {
{
QT_MOC_LITERAL(0, 0, 17), // "Table_Main_Window"
QT_MOC_LITERAL(1, 18, 13), // "addButtonSlot"
QT_MOC_LITERAL(2, 32, 0), // ""
QT_MOC_LITERAL(3, 33, 16), // "deleteButtonSlot"
QT_MOC_LITERAL(4, 50, 11), // "viewDiagram"
QT_MOC_LITERAL(5, 62, 8), // "newTable"
QT_MOC_LITERAL(6, 71, 4), // "open"
QT_MOC_LITERAL(7, 76, 4), // "save"
QT_MOC_LITERAL(8, 81, 7), // "save_as"
QT_MOC_LITERAL(9, 89, 5), // "about"
QT_MOC_LITERAL(10, 95, 11), // "WriteInFile"
QT_MOC_LITERAL(11, 107, 6), // "QFile&"
QT_MOC_LITERAL(12, 114, 1) // "f"
},
"Table_Main_Window\0addButtonSlot\0\0"
"deleteButtonSlot\0viewDiagram\0newTable\0"
"open\0save\0save_as\0about\0WriteInFile\0"
"QFile&\0f"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_Table_Main_Window[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
9, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 59, 2, 0x08 /* Private */,
3, 0, 60, 2, 0x08 /* Private */,
4, 0, 61, 2, 0x08 /* Private */,
5, 0, 62, 2, 0x08 /* Private */,
6, 0, 63, 2, 0x08 /* Private */,
7, 0, 64, 2, 0x08 /* Private */,
8, 0, 65, 2, 0x08 /* Private */,
9, 0, 66, 2, 0x08 /* Private */,
10, 1, 67, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, 0x80000000 | 11, 12,
0 // eod
};
void Table_Main_Window::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Table_Main_Window *_t = static_cast<Table_Main_Window *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->addButtonSlot(); break;
case 1: _t->deleteButtonSlot(); break;
case 2: _t->viewDiagram(); break;
case 3: _t->newTable(); break;
case 4: _t->open(); break;
case 5: _t->save(); break;
case 6: _t->save_as(); break;
case 7: _t->about(); break;
case 8: _t->WriteInFile((*reinterpret_cast< QFile(*)>(_a[1]))); break;
default: ;
}
}
}
const QMetaObject Table_Main_Window::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_Table_Main_Window.data,
qt_meta_data_Table_Main_Window, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *Table_Main_Window::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *Table_Main_Window::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_Table_Main_Window.stringdata0))
return static_cast<void*>(const_cast< Table_Main_Window*>(this));
return QMainWindow::qt_metacast(_clname);
}
int Table_Main_Window::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 9)
qt_static_metacall(this, _c, _id, _a);
_id -= 9;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 9)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 9;
}
return _id;
}
QT_END_MOC_NAMESPACE
| 33.141892 | 97 | 0.606932 | [
"object"
] |
124915eb189227dea15ad355eea19662ba3b371e | 3,792 | cpp | C++ | core/src/engine.cpp | intel/clGPU | bf099c547a17d12a81c23314a54fc7fe175a86a7 | [
"Apache-2.0"
] | 61 | 2018-02-20T06:01:50.000Z | 2021-09-08T05:55:44.000Z | core/src/engine.cpp | intel/clGPU | bf099c547a17d12a81c23314a54fc7fe175a86a7 | [
"Apache-2.0"
] | 2 | 2018-04-21T06:59:30.000Z | 2019-01-12T17:08:54.000Z | core/src/engine.cpp | intel/clGPU | bf099c547a17d12a81c23314a54fc7fe175a86a7 | [
"Apache-2.0"
] | 19 | 2018-02-19T17:18:04.000Z | 2021-02-25T02:00:53.000Z | // Copyright (c) 2017-2018 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.
#include "engine.hpp"
namespace iclgpu
{
direction buffer_binding::set_direction(direction dir)
{
auto result = _direction;
_direction = dir;
return result;
}
void* buffer_binding::get_host_ptr() const
{
if (_host_ptr == nullptr)
{
auto engine = get_owning_engine();
if (!engine)
throw std::logic_error("Blob: neigher host pointer or engine defined");
auto buffer = get_buffer(engine);
_host_ptr = buffer->get_host_ptr();
}
return _host_ptr;
}
void buffer_binding::reset_host_ptr() const
{
if (get_owning_engine())
{
_host_ptr = nullptr;
}
}
void buffer_binding::size(size_t size)
{
if (_capacity == 0)
_capacity = _size = size;
else if (_capacity < size)
throw std::logic_error("Capacity is less than requested size");
else
_size = size;
}
std::shared_ptr<buffer> buffer_binding::get_buffer(const std::shared_ptr<engine>& engine) const
{
auto it = _buffers.find(engine);
if (it != _buffers.end())
return it->second;
auto buffer = engine->create_buffer(_capacity, get_host_ptr());
_buffers.insert({engine, buffer});
return buffer;
}
void commands_sequence::push_back(const std::shared_ptr<command>& command)
{
if (auto seq = std::dynamic_pointer_cast<commands_sequence>(command))
{
for (auto& cmd : seq->_commands)
{
push_back(cmd);
}
}
else
{
_commands.push_back(command);
}
}
std::shared_ptr<event> commands_sequence::submit(const std::vector<std::shared_ptr<event>>& dependencies,
const command_queue& queue)
{
auto deps = dependencies;
for (auto& cmd : _commands)
{
deps = {cmd->submit(deps, queue)};
}
return deps.size() == 1 ? deps[0] : get_engine()->get_raise_event_command()->submit(deps, queue);
}
void commands_parallel::add(const std::shared_ptr<command>& command)
{
if (auto seq = std::dynamic_pointer_cast<commands_parallel>(command))
{
for (auto& cmd : seq->_commands)
{
add(cmd);
}
}
else
{
_commands.push_back(command);
}
}
std::shared_ptr<event> commands_parallel::submit(const std::vector<std::shared_ptr<event>>& dependencies,
const command_queue& queue)
{
std::vector<std::shared_ptr<event>> deps;
for (auto& cmd : _commands)
{
deps.push_back(cmd->submit(dependencies, queue));
}
return deps.size() == 1 ? deps[0] : get_engine()->get_raise_event_command()->submit(deps, queue);
}
kernel_options::kernel_options(const nd_range& work_size, const nd_range& parallel_size)
: _work_size(work_size)
, _parallel_size(parallel_size)
{
if (_work_size.dimensions() == 0)
throw std::invalid_argument("work_size");
if (_parallel_size.dimensions() > 0 && _work_size.dimensions() != _parallel_size.dimensions())
throw std::invalid_argument("work and parallel sizes dimensions do not match");
}
}
| 28.511278 | 105 | 0.629219 | [
"vector"
] |
124a498f5bddec61e736e317e0d881f8c454d41a | 5,773 | cc | C++ | ui/base/accelerators/accelerator_manager.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | ui/base/accelerators/accelerator_manager.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | ui/base/accelerators/accelerator_manager.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/base/accelerators/accelerator_manager.h"
#include <ostream>
#include "base/check.h"
#include "base/containers/contains.h"
namespace ui {
AcceleratorManager::AcceleratorManager() = default;
AcceleratorManager::~AcceleratorManager() = default;
void AcceleratorManager::Register(
const std::vector<ui::Accelerator>& accelerators,
HandlerPriority priority,
AcceleratorTarget* target) {
DCHECK(target);
for (const ui::Accelerator& accelerator : accelerators) {
accelerators_.GetOrInsertDefault(accelerator)
.RegisterWithPriority(target, priority);
}
}
void AcceleratorManager::Unregister(const Accelerator& accelerator,
AcceleratorTarget* target) {
DCHECK(target);
AcceleratorTargetInfo* target_info = accelerators_.Find(accelerator);
DCHECK(target_info) << "Unregistering non-existing accelerator";
const bool was_registered = target_info->Unregister(target);
DCHECK(was_registered) << "Unregistering accelerator for wrong target";
// If the last target for the accelerator is removed, then erase the
// entry from the map.
if (!target_info->HasTargets())
accelerators_.Erase(accelerator);
}
void AcceleratorManager::UnregisterAll(AcceleratorTarget* target) {
for (auto map_iter = accelerators_.begin();
map_iter != accelerators_.end();) {
AcceleratorTargetInfo& target_info = map_iter->second;
// Unregister the target and remove the entry if it was the last target.
const bool was_registered = target_info.Unregister(target);
if (was_registered && !target_info.HasTargets()) {
Accelerator key_to_remove = map_iter->first;
++map_iter;
accelerators_.Erase(key_to_remove);
continue;
}
DCHECK(target_info.HasTargets());
++map_iter;
}
}
bool AcceleratorManager::IsRegistered(const Accelerator& accelerator) const {
const AcceleratorTargetInfo* target_info = accelerators_.Find(accelerator);
// If the accelerator is in the map, the target list should not be empty.
DCHECK(!target_info || target_info->HasTargets());
return target_info != nullptr;
}
bool AcceleratorManager::Process(const Accelerator& accelerator) {
const AcceleratorTargetInfo* target_info = accelerators_.Find(accelerator);
if (!target_info)
return false;
// If the accelerator is in the map, the target list should not be empty.
DCHECK(target_info->HasTargets());
// We have to copy the target list here, because processing the accelerator
// event handler may modify the list.
AcceleratorTargetInfo target_info_copy(*target_info);
return target_info_copy.TryProcess(accelerator);
}
bool AcceleratorManager::HasPriorityHandler(
const Accelerator& accelerator) const {
const AcceleratorTargetInfo* target_info = accelerators_.Find(accelerator);
return target_info && target_info->HasPriorityHandler();
}
AcceleratorManager::AcceleratorTargetInfo::AcceleratorTargetInfo() = default;
AcceleratorManager::AcceleratorTargetInfo::AcceleratorTargetInfo(
const AcceleratorManager::AcceleratorTargetInfo& other) = default;
AcceleratorManager::AcceleratorTargetInfo&
AcceleratorManager::AcceleratorTargetInfo::operator=(
const AcceleratorManager::AcceleratorTargetInfo& other) = default;
AcceleratorManager::AcceleratorTargetInfo::~AcceleratorTargetInfo() = default;
void AcceleratorManager::AcceleratorTargetInfo::RegisterWithPriority(
AcceleratorTarget* target,
HandlerPriority priority) {
DCHECK(!Contains(target)) << "Registering the same target multiple times";
// All priority accelerators go to the front of the line.
if (priority == kHighPriority) {
DCHECK(!has_priority_handler_)
<< "Only one high-priority handler can be registered";
targets_.push_front(target);
// Mark that we have a priority accelerator at the front.
has_priority_handler_ = true;
} else {
// We are registering a normal priority handler. If no priority
// accelerator handler has been registered before us, just add the new
// handler to the front. Otherwise, register it after the first (only)
// priority handler.
if (has_priority_handler_) {
DCHECK(!targets_.empty());
targets_.insert(++targets_.begin(), target);
} else {
targets_.push_front(target);
}
}
// Post condition. Ensure there's at least one target.
DCHECK(!targets_.empty());
}
bool AcceleratorManager::AcceleratorTargetInfo::Unregister(
AcceleratorTarget* target) {
DCHECK(!targets_.empty());
// Only one priority handler is allowed, so if we remove the first element we
// no longer have a priority target.
if (targets_.front() == target)
has_priority_handler_ = false;
// Attempt to remove the target and return true if it was present.
const size_t original_target_count = targets_.size();
targets_.remove(target);
return original_target_count != targets_.size();
}
bool AcceleratorManager::AcceleratorTargetInfo::TryProcess(
const Accelerator& accelerator) {
DCHECK(!targets_.empty());
for (AcceleratorTarget* target : targets_) {
if (target->CanHandleAccelerators() &&
target->AcceleratorPressed(accelerator)) {
return true;
}
}
return false;
}
bool AcceleratorManager::AcceleratorTargetInfo::HasPriorityHandler() const {
DCHECK(!targets_.empty());
return has_priority_handler_ && targets_.front()->CanHandleAccelerators();
}
bool AcceleratorManager::AcceleratorTargetInfo::Contains(
AcceleratorTarget* target) const {
DCHECK(target);
return base::Contains(targets_, target);
}
} // namespace ui
| 33.369942 | 79 | 0.741036 | [
"vector"
] |
12556f47208705e87576ea8f8d946c6969cd78e2 | 965 | hpp | C++ | Source/Shared/engine/cfc/stl/stl_pimpl.hpp | JJoosten/IndirectOcclusionCulling | 0376da0f9bdb14e67238a5b54e928e50ee33aef6 | [
"MIT"
] | 19 | 2016-08-16T10:19:07.000Z | 2018-12-04T01:00:00.000Z | Source/Shared/engine/cfc/stl/stl_pimpl.hpp | JJoosten/IndirectOcclusionCulling | 0376da0f9bdb14e67238a5b54e928e50ee33aef6 | [
"MIT"
] | 1 | 2016-08-18T04:23:19.000Z | 2017-01-26T22:46:44.000Z | Source/Shared/engine/cfc/stl/stl_pimpl.hpp | JJoosten/IndirectOcclusionCulling | 0376da0f9bdb14e67238a5b54e928e50ee33aef6 | [
"MIT"
] | 1 | 2019-09-23T10:49:36.000Z | 2019-09-23T10:49:36.000Z | #pragma once
#include "stl_common.hpp"
template <class T, int size> class stl_pimpl
{
public:
stl_pimpl() : m_impl(nullptr) {}
~stl_pimpl()
{
stl_assert(m_impl == nullptr); // object needs to be destroyed
}
inline T* operator ->() const
{
stl_assert(m_impl != nullptr); // need to have a valid object
return m_impl;
}
template <bool dummy=false> void init()
{
static_assert(sizeof(T) <= sizeof(m_buffer), "pimpl buffer is too small to initialize object"); // data buffer needs to be large enough to fit data
stl_assert(m_impl == nullptr); // there can't be a valid object yet
m_impl = new (m_buffer) T();
}
template<bool dummy=false> void destroy()
{
stl_assert(m_impl != nullptr); // needs to have a valid object
m_impl->~T();
m_impl = nullptr;
}
T* get()
{
stl_assert(m_impl != nullptr); // need to have a valid object
return m_impl;
}
protected:
char m_buffer[size - sizeof(T*)];
T* m_impl;
}; | 21.444444 | 149 | 0.656995 | [
"object"
] |
1258a9439239a48aa5bccf0d47338a89977c3abd | 1,776 | hpp | C++ | src/tests/test_scheduler.hpp | victimsnino/ReactivePlusPlus | bb187cc52936bce7c1ef4899d7dbb9c970cef291 | [
"MIT"
] | 1 | 2022-03-19T20:15:50.000Z | 2022-03-19T20:15:50.000Z | src/tests/test_scheduler.hpp | victimsnino/ReactivePlusPlus | bb187cc52936bce7c1ef4899d7dbb9c970cef291 | [
"MIT"
] | 12 | 2022-03-22T21:18:14.000Z | 2022-03-30T05:37:58.000Z | src/tests/test_scheduler.hpp | victimsnino/ReactivePlusPlus | bb187cc52936bce7c1ef4899d7dbb9c970cef291 | [
"MIT"
] | null | null | null | // ReactivePlusPlus library
//
// Copyright Aleksey Loginov 2022 - present.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/victimsnino/ReactivePlusPlus
#pragma once
#include <rpp/schedulers.hpp>
static rpp::schedulers::time_point s_current_time{ std::chrono::seconds{0} };
class test_scheduler final : public rpp::schedulers::details::scheduler_tag
{
public:
class worker_strategy
{
public:
worker_strategy(const rpp::subscription_base& sub,
std::shared_ptr<std::vector<rpp::schedulers::time_point>> schedulings)
: m_sub{ sub }
, m_schedulings{ schedulings } {}
void defer_at(rpp::schedulers::time_point time_point, std::invocable auto&& fn) const
{
if (m_sub.is_subscribed())
{
m_schedulings->push_back(time_point);
fn();
}
}
static rpp::schedulers::time_point now() { return s_current_time; }
private:
rpp::subscription_base m_sub;
std::shared_ptr<std::vector<rpp::schedulers::time_point>> m_schedulings;
};
test_scheduler() {}
rpp::schedulers::worker<worker_strategy> create_worker(const rpp::subscription_base& sub = {}) const
{
return rpp::schedulers::worker<worker_strategy>{sub, m_schedulings};
}
const auto& get_schedulings() const { return *m_schedulings; }
private:
std::shared_ptr<std::vector<rpp::schedulers::time_point>> m_schedulings = std::make_shared<std::vector<
rpp::schedulers::time_point>>();
}; | 32.290909 | 107 | 0.630631 | [
"vector"
] |
125a2790a9665c2cda688f4edbd42fa06031da9d | 7,619 | cpp | C++ | Source/SystemQOR/MSWindows/WinQL/COM/Server/OLE/WinQLOLEContainer.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 9 | 2016-05-27T01:00:39.000Z | 2021-04-01T08:54:46.000Z | Source/SystemQOR/MSWindows/WinQL/COM/Server/OLE/WinQLOLEContainer.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 1 | 2016-03-03T22:54:08.000Z | 2016-03-03T22:54:08.000Z | Source/SystemQOR/MSWindows/WinQL/COM/Server/OLE/WinQLOLEContainer.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 4 | 2016-05-27T01:00:43.000Z | 2018-08-19T08:47:49.000Z | //WinQLOLEContainer.cpp
// Copyright Querysoft Limited 2013, 2015, 2017
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include "WinQL/CodeServices/WinQLPolicy.h"
#include "WinQL/Application/Threading/WinQLCriticalSection.h"
#include "WinQL/Application/ErrorSystem/WinQLError.h"
#include "WinQL/COM/Server/OLE/WinQLOLEContainer.h"
#include "WinQAPI/OLE32.h"
//--------------------------------------------------------------------------------
namespace nsWin32
{
__QOR_IMPLEMENT_OCLASS_LUID( COLEContainer );
__QCMP_WARNING_PUSH
__QCMP_WARNING_DISABLE( __QCMP_WARN_THIS_USED_IN_BASE_INIT_LIST )
//--------------------------------------------------------------------------------
COLEContainer::COLEContainer() :
m_OleClientSitePtr( this )
, m_AdviseSinkPtr( this )
, m_MessageFilterPtr( this )
, m_OleItemContainerPtr( this )
, m_PersistFilePtr( this )
, m_ClassFactoryPtr( this )
, m_OleInPlaceSitePtr( this )
, m_OleInPlaceFramePtr( this )
, m_OleInPlaceObjectPtr( this )
, m_DropSourcePtr( this )
, m_DropTargetPtr( this )
, m_DataObjectPtr( this )
{
_WINQ_FCONTEXT( "COLEContainer::COLEContainer" );
}
__QCMP_WARNING_POP
//--------------------------------------------------------------------------------
COLEContainer::~COLEContainer()
{
_WINQ_FCONTEXT( "COLEContainer::~COLEContainer" );
}
//--------------------------------------------------------------------------------
//Guarantee availaility of required interfaces
void COLEContainer::Initialize()
{
_WINQ_FCONTEXT( "COLEContainer::Initialize" );
IOleClientSite* pClientSite = m_OleClientSitePtr;
IAdviseSink* pAdviseSink = m_AdviseSinkPtr;
}
//--------------------------------------------------------------------------------
long COLEContainer::OleCreateDefaultHandler( const GUID& clsid, IUnknown* pUnkOuter, const GUID& riid, void** lplpObj )
{
_WINQ_FCONTEXT( "COLEContainer::OleCreateDefaultHandler" );
long lResult = -1;
__QOR_PROTECT
{
lResult = m_Library.OleCreateDefaultHandler( reinterpret_cast< REFCLSID >( clsid ),
reinterpret_cast< ::LPUNKNOWN >( pUnkOuter ),
reinterpret_cast< REFIID >( riid ), lplpObj );
}__QOR_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
long COLEContainer::OleCreateEmbeddingHelper( const GUID& clsid, IUnknown* pUnkOuter, unsigned long flags, IClassFactory* pCF, const GUID& riid, void** lplpObj )
{
_WINQ_FCONTEXT( "COLEContainer::OleCreateEmbeddingHelper" );
long lResult = -1;
__QOR_PROTECT
{
lResult = m_Library.OleCreateEmbeddingHelper( reinterpret_cast< REFCLSID >( clsid ),
reinterpret_cast< ::LPUNKNOWN >( pUnkOuter ), flags,
reinterpret_cast< ::LPCLASSFACTORY >( pCF ),
reinterpret_cast< REFIID >( riid ), lplpObj );
}__QOR_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
long COLEContainer::OleCreate( const GUID& rclsid, const GUID& riid, unsigned long renderopt, FormatEtc* pFormatEtc, IStorage* pStg )
{
_WINQ_FCONTEXT( "COLEContainer::OleCreate" );
long lResult = -1;
__QOR_PROTECT
{
lResult = m_Library.OleCreate( reinterpret_cast< REFCLSID >( rclsid ),
reinterpret_cast< REFIID >( riid ), renderopt,
reinterpret_cast< ::LPFORMATETC >( pFormatEtc ),
reinterpret_cast< ::LPOLECLIENTSITE >( Internal_Interface< IOleClientSite >() ),
reinterpret_cast< ::LPSTORAGE >( pStg ),
reinterpret_cast< void** >( &m_pContained ) );
}__QOR_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
long COLEContainer::OleCreateEx( const GUID& rclsid, const GUID& riid, unsigned long dwFlags, unsigned long renderopt, unsigned long cFormats, unsigned long* rgAdvf, FormatEtc* rgFormatEtc, unsigned long* rgdwConnection, IStorage* pStg )
{
_WINQ_FCONTEXT( "COLEContainer::OleCreateEx" );
long lResult = -1;
__QOR_PROTECT
{
lResult = m_Library.OleCreateEx( reinterpret_cast< REFCLSID >( rclsid ),
reinterpret_cast< REFIID >( riid ), dwFlags, renderopt, cFormats, rgAdvf,
reinterpret_cast< ::LPFORMATETC >( rgFormatEtc ),
reinterpret_cast< ::IAdviseSink* >( Internal_Interface< IAdviseSink >() ), rgdwConnection,
reinterpret_cast< ::LPOLECLIENTSITE >( Internal_Interface< IOleClientSite >() ),
reinterpret_cast< ::LPSTORAGE >( pStg ),
reinterpret_cast< void** >( &m_pContained ) );
}__QOR_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
bool COLEContainer::OleIsRunning()
{
_WINQ_FCONTEXT( "COLEContainer::OleIsRunning" );
bool bResult = false;
__QOR_PROTECT
{
IOleObject* pObject;
if( m_pContained )
{
long lResult = m_pContained->QueryInterface( IOleObject_IID, reinterpret_cast< void** >( &pObject ) );
if( lResult == S_OK )
{
lResult = m_Library.OleIsRunning( reinterpret_cast< ::LPOLEOBJECT >( pObject ) ) ? true : false;
pObject->Release();
}
}
}__QOR_ENDPROTECT
return bResult;
}
//--------------------------------------------------------------------------------
long COLEContainer::OleNoteObjectVisible( bool bVisible )
{
_WINQ_FCONTEXT( "COLEContainer::OleNoteObjectVisible" );
long lResult = -1;
__QOR_PROTECT
{
if( m_pContained )
{
lResult = m_Library.OleNoteObjectVisible( reinterpret_cast< ::LPUNKNOWN >( m_pContained ), bVisible ? 1 : 0 );
}
}__QOR_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
long COLEContainer::TellObjectItsContained( bool bContained )
{
_WINQ_FCONTEXT( "COLEContainer::TellObjectItsContained" );
long lResult = -1;
__QOR_PROTECT
{
if( m_pContained )
{
lResult = m_Library.OleSetContainedObject( reinterpret_cast< ::LPUNKNOWN >( m_pContained ), bContained );
}
}__QOR_ENDPROTECT
return lResult;
}
//--------------------------------------------------------------------------------
long COLEContainer::OleRun()
{
_WINQ_FCONTEXT( "COLEContainer::OleRun" );
long lResult = -1;
__QOR_PROTECT
{
if( m_pContained )
{
lResult = m_Library.OleRun( reinterpret_cast< ::LPUNKNOWN >( m_pContained ) );
}
}__QOR_ENDPROTECT
return lResult;
}
}//nsWin32
| 37.165854 | 238 | 0.63801 | [
"object"
] |
125c6f094dbab25afb4fdc2f5a02a7fd5d50aa7f | 28,840 | cc | C++ | alljoyn_core/unit_test/SecurityTestHelper.cc | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 33 | 2018-01-12T00:37:43.000Z | 2022-03-24T02:31:36.000Z | alljoyn_core/unit_test/SecurityTestHelper.cc | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 1 | 2020-01-05T05:51:27.000Z | 2020-01-05T05:51:27.000Z | alljoyn_core/unit_test/SecurityTestHelper.cc | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 30 | 2017-12-13T23:24:00.000Z | 2022-01-25T02:11:19.000Z | /******************************************************************************
* Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source
* Project (AJOSP) Contributors and others.
*
* SPDX-License-Identifier: Apache-2.0
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution, and is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Open Connectivity Foundation and Contributors to AllSeen
* Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
#include "SecurityTestHelper.h"
#include <qcc/KeyInfoECC.h>
#include <qcc/Thread.h>
#include <qcc/Util.h>
#include <alljoyn/AllJoynStd.h>
#include <alljoyn/PermissionConfigurator.h>
#include <alljoyn/SecurityApplicationProxy.h>
#include <alljoyn/TransportMask.h>
#include "ajTestCommon.h"
#include "CredentialAccessor.h"
QStatus SecurityTestHelper::GetGUID(ajn::BusAttachment& bus, qcc::GUID128& guid)
{
ajn::CredentialAccessor ca(bus);
return ca.GetGuid(guid);
}
QStatus SecurityTestHelper::GetPeerGUID(ajn::BusAttachment& bus, qcc::String& peerName, qcc::GUID128& peerGuid)
{
ajn::CredentialAccessor ca(bus);
return ca.GetPeerGuid(peerName, peerGuid);
}
QStatus SecurityTestHelper::GetAppPublicKey(ajn::BusAttachment& bus, qcc::ECCPublicKey& publicKey)
{
qcc::KeyInfoNISTP256 keyInfo;
QStatus status = bus.GetPermissionConfigurator().GetSigningPublicKey(keyInfo);
if (ER_OK != status) {
return status;
}
publicKey = *keyInfo.GetPublicKey();
return status;
}
QStatus SecurityTestHelper::RetrievePublicKeyFromMsgArg(const ajn::MsgArg& arg, qcc::ECCPublicKey* pubKey)
{
uint8_t keyFormat;
ajn::MsgArg* variantArg;
QStatus status = arg.Get("(yv)", &keyFormat, &variantArg);
if (ER_OK != status) {
return status;
}
if (keyFormat != qcc::KeyInfo::FORMAT_ALLJOYN) {
return status;
}
uint8_t* kid;
size_t kidLen;
uint8_t keyUsageType, keyType;
ajn::MsgArg* keyVariantArg;
status = variantArg->Get("(ayyyv)", &kidLen, &kid, &keyUsageType, &keyType, &keyVariantArg);
if (ER_OK != status) {
return status;
}
if ((keyUsageType != qcc::KeyInfo::USAGE_SIGNING) && (keyUsageType != qcc::KeyInfo::USAGE_ENCRYPTION)) {
return status;
}
if (keyType != qcc::KeyInfoECC::KEY_TYPE) {
return status;
}
uint8_t algorithm, curve;
ajn::MsgArg* curveVariant;
status = keyVariantArg->Get("(yyv)", &algorithm, &curve, &curveVariant);
if (ER_OK != status) {
return status;
}
if (curve != qcc::Crypto_ECC::ECC_NIST_P256) {
return status;
}
uint8_t* xCoord;
uint8_t* yCoord;
size_t xLen, yLen;
status = curveVariant->Get("(ayay)", &xLen, &xCoord, &yLen, &yCoord);
if (ER_OK != status) {
return status;
}
if ((xLen != qcc::ECC_COORDINATE_SZ) || (yLen != qcc::ECC_COORDINATE_SZ)) {
return status;
}
return pubKey->Import(xCoord, xLen, yCoord, yLen);
}
QStatus SecurityTestHelper::RetrieveDSAPublicKeyFromKeyStore(ajn::BusAttachment& bus, qcc::ECCPublicKey* publicKey)
{
ajn::CredentialAccessor ca(bus);
return ca.GetDSAPublicKey(*publicKey);
}
void SecurityTestHelper::CreatePermissivePolicyAll(ajn::PermissionPolicy& policy, uint32_t version) {
policy.SetVersion(version);
{
ajn::PermissionPolicy::Acl acls[1];
{
ajn::PermissionPolicy::Peer peers[1];
peers[0].SetType(ajn::PermissionPolicy::Peer::PEER_ALL);
acls[0].SetPeers(1, peers);
}
{
ajn::PermissionPolicy::Rule rules[1];
rules[0].SetObjPath("*");
rules[0].SetInterfaceName("*");
{
ajn::PermissionPolicy::Rule::Member members[1];
members[0].Set("*",
ajn::PermissionPolicy::Rule::Member::NOT_SPECIFIED,
ajn::PermissionPolicy::Rule::Member::ACTION_PROVIDE |
ajn::PermissionPolicy::Rule::Member::ACTION_MODIFY |
ajn::PermissionPolicy::Rule::Member::ACTION_OBSERVE);
rules[0].SetMembers(1, members);
}
acls[0].SetRules(1, rules);
}
policy.SetAcls(1, acls);
}
}
void SecurityTestHelper::CreatePermissivePolicyAnyTrusted(ajn::PermissionPolicy& policy, uint32_t version) {
policy.SetVersion(version);
{
ajn::PermissionPolicy::Acl acls[1];
{
ajn::PermissionPolicy::Peer peers[1];
peers[0].SetType(ajn::PermissionPolicy::Peer::PEER_ANY_TRUSTED);
acls[0].SetPeers(1, peers);
}
{
ajn::PermissionPolicy::Rule rules[1];
rules[0].SetObjPath("*");
rules[0].SetInterfaceName("*");
{
ajn::PermissionPolicy::Rule::Member members[1];
members[0].Set("*",
ajn::PermissionPolicy::Rule::Member::NOT_SPECIFIED,
ajn::PermissionPolicy::Rule::Member::ACTION_PROVIDE |
ajn::PermissionPolicy::Rule::Member::ACTION_MODIFY |
ajn::PermissionPolicy::Rule::Member::ACTION_OBSERVE);
rules[0].SetMembers(1, members);
}
acls[0].SetRules(1, rules);
}
policy.SetAcls(1, acls);
}
}
void SecurityTestHelper::UpdatePolicyWithValuesFromDefaultPolicy(const ajn::PermissionPolicy& defaultPolicy,
ajn::PermissionPolicy& policy,
bool keepCAentry,
bool keepAdminGroupEntry,
bool keepInstallMembershipEntry) {
size_t aclsCount = policy.GetAclsSize();
if (keepCAentry) {
++aclsCount;
}
if (keepAdminGroupEntry) {
++aclsCount;
}
if (keepInstallMembershipEntry) {
++aclsCount;
}
ajn::PermissionPolicy::Acl* acls = new ajn::PermissionPolicy::Acl[aclsCount];
size_t idx = 0;
for (size_t itAcl = 0; itAcl < defaultPolicy.GetAclsSize(); ++itAcl) {
const ajn::PermissionPolicy::Acl& acl = defaultPolicy.GetAcls()[itAcl];
if (acl.GetPeersSize() > 0) {
ajn::PermissionPolicy::Peer::PeerType peerType = acl.GetPeers()[0].GetType();
if ((peerType == ajn::PermissionPolicy::Peer::PEER_FROM_CERTIFICATE_AUTHORITY && keepCAentry) ||
(peerType == ajn::PermissionPolicy::Peer::PEER_WITH_MEMBERSHIP && keepAdminGroupEntry) ||
(peerType == ajn::PermissionPolicy::Peer::PEER_WITH_PUBLIC_KEY && keepInstallMembershipEntry)) {
acls[idx++] = acl;
}
}
}
for (size_t itAcl = 0; itAcl < policy.GetAclsSize(); ++itAcl) {
QCC_ASSERT(idx < aclsCount);
acls[idx++] = policy.GetAcls()[itAcl];
}
policy.SetAcls(aclsCount, acls);
delete [] acls;
}
QStatus SecurityTestHelper::CreateAllInclusiveManifest(ajn::Manifest& manifest)
{
const size_t manifestSize = 1;
ajn::PermissionPolicy::Rule manifestRules[manifestSize];
manifestRules[0].SetObjPath("*");
manifestRules[0].SetInterfaceName("*");
{
ajn::PermissionPolicy::Rule::Member member[3];
member[0].Set("*", ajn::PermissionPolicy::Rule::Member::METHOD_CALL,
ajn::PermissionPolicy::Rule::Member::ACTION_PROVIDE |
ajn::PermissionPolicy::Rule::Member::ACTION_MODIFY);
member[1].Set("*", ajn::PermissionPolicy::Rule::Member::SIGNAL,
ajn::PermissionPolicy::Rule::Member::ACTION_PROVIDE |
ajn::PermissionPolicy::Rule::Member::ACTION_OBSERVE);
member[2].Set("*", ajn::PermissionPolicy::Rule::Member::PROPERTY,
ajn::PermissionPolicy::Rule::Member::ACTION_PROVIDE |
ajn::PermissionPolicy::Rule::Member::ACTION_MODIFY |
ajn::PermissionPolicy::Rule::Member::ACTION_OBSERVE);
manifestRules[0].SetMembers(ArraySize(member), member);
}
return manifest->SetRules(manifestRules, manifestSize);
}
QStatus SecurityTestHelper::SignManifest(ajn::BusAttachment& issuerBus,
const std::vector<uint8_t>& subjectThumbprint,
ajn::Manifest& manifest)
{
return issuerBus.GetPermissionConfigurator().SignManifest(subjectThumbprint, manifest);
}
QStatus SecurityTestHelper::SignManifest(ajn::BusAttachment& issuerBus,
const qcc::CertificateX509& subjectCertificate,
ajn::Manifest& manifest)
{
return issuerBus.GetPermissionConfigurator().ComputeThumbprintAndSignManifest(subjectCertificate, manifest);
}
QStatus SecurityTestHelper::SignManifest(ajn::BusAttachment& issuerBus,
const qcc::CertificateX509& subjectCertificate,
AJ_PCSTR unsignedManifestXml,
std::string& signedManifestXml)
{
ajn::CredentialAccessor ca(issuerBus);
qcc::ECCPrivateKey privateKey;
AJ_PSTR signedManifestXmlC = nullptr;
QStatus status = ca.GetDSAPrivateKey(privateKey);
if (ER_OK != status) {
return status;
}
status = ajn::SecurityApplicationProxy::SignManifest(subjectCertificate, privateKey, unsignedManifestXml, &signedManifestXmlC);
if (ER_OK != status) {
return status;
}
signedManifestXml = signedManifestXmlC;
ajn::SecurityApplicationProxy::DestroySignedManifest(signedManifestXmlC);
return ER_OK;
}
QStatus SecurityTestHelper::SignManifests(ajn::BusAttachment& issuerBus,
const qcc::CertificateX509& subjectCertificate,
std::vector<ajn::Manifest>& manifests)
{
for (ajn::Manifest manifest : manifests) {
QStatus status = SignManifest(issuerBus, subjectCertificate, manifest);
if (ER_OK != status) {
return status;
}
}
return ER_OK;
}
QStatus SecurityTestHelper::CreateIdentityCert(ajn::BusAttachment& issuerBus,
const qcc::String& serial,
const qcc::String& subject,
const qcc::ECCPublicKey* subjectPubKey,
const qcc::String& alias,
qcc::IdentityCertificate& cert,
uint32_t expiredInSecs,
bool setEmptyAKI)
{
qcc::GUID128 issuer(0);
GetGUID(issuerBus, issuer);
QStatus status = ER_CRYPTO_ERROR;
cert.SetSerial(reinterpret_cast<const uint8_t*>(serial.data()), serial.size());
qcc::String issuerStr = issuer.ToString();
cert.SetIssuerCN(reinterpret_cast<const uint8_t*>(issuerStr.data()), issuerStr.size());
cert.SetSubjectCN(reinterpret_cast<const uint8_t*>(subject.data()), subject.size());
cert.SetSubjectPublicKey(subjectPubKey);
cert.SetAlias(alias);
qcc::CertificateX509::ValidPeriod validity;
BuildValidity(validity, expiredInSecs);
cert.SetValidity(&validity);
/* use the issuer bus to sign the cert */
ajn::PermissionConfigurator& pc = issuerBus.GetPermissionConfigurator();
if (setEmptyAKI) {
ajn::CredentialAccessor ca(issuerBus);
qcc::ECCPrivateKey privateKey;
status = ca.GetDSAPrivateKey(privateKey);
if (ER_OK != status) {
return status;
}
status = cert.Sign(&privateKey);
} else {
status = pc.SignCertificate(cert);
}
if (ER_OK != status) {
return status;
}
qcc::KeyInfoNISTP256 keyInfo;
pc.GetSigningPublicKey(keyInfo);
status = cert.Verify(keyInfo.GetPublicKey());
if (ER_OK != status) {
return status;
}
return ER_OK;
}
QStatus SecurityTestHelper::CreateIdentityCert(ajn::BusAttachment& issuerBus,
const qcc::String& serial,
const qcc::String& subject,
const qcc::ECCPublicKey* subjectPubKey,
const qcc::String& alias,
qcc::String& der,
uint32_t expiredInSecs)
{
qcc::IdentityCertificate cert;
QStatus status = CreateIdentityCert(issuerBus, serial, subject, subjectPubKey, alias, cert, expiredInSecs);
if (ER_OK != status) {
return status;
}
return cert.EncodeCertificateDER(der);
}
QStatus SecurityTestHelper::CreateIdentityCertChain(ajn::BusAttachment& caBus,
ajn::BusAttachment& issuerBus,
const qcc::String& serial,
const qcc::String& subject,
const qcc::ECCPublicKey* subjectPubKey,
const qcc::String& alias,
qcc::IdentityCertificate* certChain,
size_t chainCount,
uint32_t expiredInSecs)
{
if (chainCount > 3) {
return ER_INVALID_DATA;
}
QStatus status = ER_CRYPTO_ERROR;
qcc::GUID128 ca(0);
GetGUID(caBus, ca);
qcc::String caStr = ca.ToString();
ajn::PermissionConfigurator& caPC = caBus.GetPermissionConfigurator();
if (chainCount == 3) {
/* generate the self signed CA cert */
qcc::String caSerial = serial + "02";
certChain[2].SetSerial(reinterpret_cast<const uint8_t*>(caSerial.data()), caSerial.size());
certChain[2].SetIssuerCN(reinterpret_cast<const uint8_t*>(caStr.data()), caStr.size());
certChain[2].SetSubjectCN(reinterpret_cast<const uint8_t*>(caStr.data()), caStr.size());
qcc::CertificateX509::ValidPeriod validity;
BuildValidity(validity, expiredInSecs);
certChain[2].SetValidity(&validity);
certChain[2].SetCA(true);
qcc::KeyInfoNISTP256 keyInfo;
caPC.GetSigningPublicKey(keyInfo);
certChain[2].SetSubjectPublicKey(keyInfo.GetPublicKey());
status = caPC.SignCertificate(certChain[2]);
if (ER_OK != status) {
return status;
}
}
/* generate the issuer cert */
qcc::GUID128 issuer(0);
GetGUID(issuerBus, issuer);
qcc::String issuerStr = issuer.ToString();
qcc::String issuerSerial = serial + "01";
certChain[1].SetSerial(reinterpret_cast<const uint8_t*>(issuerSerial.data()), issuerSerial.size());
certChain[1].SetIssuerCN(reinterpret_cast<const uint8_t*>(caStr.data()), caStr.size());
certChain[1].SetSubjectCN(reinterpret_cast<const uint8_t*>(issuerStr.data()), issuerStr.size());
qcc::CertificateX509::ValidPeriod validity;
BuildValidity(validity, expiredInSecs);
certChain[1].SetValidity(&validity);
certChain[1].SetCA(true);
ajn::PermissionConfigurator& pc = issuerBus.GetPermissionConfigurator();
qcc::KeyInfoNISTP256 keyInfo;
pc.GetSigningPublicKey(keyInfo);
certChain[1].SetSubjectPublicKey(keyInfo.GetPublicKey());
status = caPC.SignCertificate(certChain[1]);
if (ER_OK != status) {
return status;
}
/* generate the leaf cert */
certChain[0].SetSerial(reinterpret_cast<const uint8_t*>(serial.data()), serial.size());
certChain[0].SetIssuerCN(reinterpret_cast<const uint8_t*>(issuerStr.data()), issuerStr.size());
certChain[0].SetSubjectCN(reinterpret_cast<const uint8_t*>(subject.data()), subject.size());
certChain[0].SetSubjectPublicKey(subjectPubKey);
certChain[0].SetAlias(alias);
certChain[0].SetValidity(&validity);
/* use the issuer bus to sign the cert */
status = pc.SignCertificate(certChain[0]);
if (ER_OK != status) {
return status;
}
status = certChain[0].Verify(certChain[1].GetSubjectPublicKey());
if (ER_OK != status) {
return status;
}
return ER_OK;
}
QStatus SecurityTestHelper::CreateMembershipCert(const qcc::String& serial,
ajn::BusAttachment& signingBus,
const qcc::String& subject,
const qcc::ECCPublicKey* subjectPubKey,
const qcc::GUID128& guild,
qcc::MembershipCertificate& cert,
bool delegate,
uint32_t expiredInSecs,
bool setEmptyAKI)
{
qcc::GUID128 issuer(0);
GetGUID(signingBus, issuer);
if (subject.empty()) {
return ER_BAD_ARG_3;
}
cert.SetSerial(reinterpret_cast<const uint8_t*>(serial.data()), serial.size());
qcc::String issuerStr = issuer.ToString();
cert.SetIssuerCN(reinterpret_cast<const uint8_t*>(issuerStr.data()), issuerStr.size());
cert.SetSubjectCN(reinterpret_cast<const uint8_t*>(subject.data()), subject.size());
cert.SetSubjectPublicKey(subjectPubKey);
cert.SetGuild(guild);
cert.SetCA(delegate);
qcc::CertificateX509::ValidPeriod validity;
BuildValidity(validity, expiredInSecs);
cert.SetValidity(&validity);
/* use the signing bus to sign the cert */
ajn::PermissionConfigurator& pc = signingBus.GetPermissionConfigurator();
QStatus status = ER_CRYPTO_ERROR;
if (setEmptyAKI) {
ajn::CredentialAccessor ca(signingBus);
qcc::ECCPrivateKey privateKey;
status = ca.GetDSAPrivateKey(privateKey);
if (ER_OK != status) {
return status;
}
status = cert.Sign(&privateKey);
} else {
status = pc.SignCertificate(cert);
}
return status;
}
QStatus SecurityTestHelper::CreateMembershipCert(const qcc::String& serial,
ajn::BusAttachment& signingBus,
const qcc::String& subject,
const qcc::ECCPublicKey* subjectPubKey,
const qcc::GUID128& guild,
qcc::String& der,
bool delegate,
uint32_t expiredInSecs)
{
qcc::MembershipCertificate cert;
QStatus status = CreateMembershipCert(serial, signingBus, subject, subjectPubKey, guild, cert, delegate, expiredInSecs);
if (ER_OK != status) {
return status;
}
return cert.EncodeCertificateDER(der);
}
QStatus SecurityTestHelper::InstallMembership(const qcc::String& serial,
ajn::BusAttachment& bus,
const qcc::String& remoteObjName,
ajn::BusAttachment& signingBus,
const qcc::String& subject,
const qcc::ECCPublicKey* subjectPubKey,
const qcc::GUID128& guild)
{
ajn::SecurityApplicationProxy saProxy(bus, remoteObjName.c_str());
QStatus status;
qcc::MembershipCertificate certs[1];
status = CreateMembershipCert(serial, signingBus, subject, subjectPubKey, guild, certs[0]);
if (status != ER_OK) {
return status;
}
return saProxy.InstallMembership(certs, 1);
}
QStatus SecurityTestHelper::InstallMembershipChain(ajn::BusAttachment& topBus,
ajn::BusAttachment& secondBus,
const qcc::String& serial0,
const qcc::String& serial1,
const qcc::String& remoteObjName,
const qcc::String& secondSubject,
const qcc::ECCPublicKey* secondPubKey,
const qcc::String& targetSubject,
const qcc::ECCPublicKey* targetPubKey,
const qcc::GUID128& guild,
bool setEmptyAKI)
{
ajn::SecurityApplicationProxy saSecondProxy(secondBus, remoteObjName.c_str());
/* create the second cert first -- with delegate on */
qcc::MembershipCertificate certs[2];
QStatus status = CreateMembershipCert(serial1, topBus, secondSubject, secondPubKey, guild, certs[1], true, 3600, setEmptyAKI);
if (status != ER_OK) {
return status;
}
/* create the leaf cert signed by the subject */
status = CreateMembershipCert(serial0, secondBus, targetSubject, targetPubKey, guild, certs[0], false, 3600, setEmptyAKI);
if (status != ER_OK) {
return status;
}
/* install cert chain */
return saSecondProxy.InstallMembership(certs, 2);
}
QStatus SecurityTestHelper::InstallMembershipChain(ajn::BusAttachment& caBus,
ajn::BusAttachment& intermediateBus,
ajn::BusAttachment& targetBus,
qcc::String& leafSerial,
const qcc::GUID128& sgID)
{
qcc::MembershipCertificate certs[3];
/* create the top cert first self signed CA cert with delegate on */
ajn::PermissionConfigurator& caPC = caBus.GetPermissionConfigurator();
qcc::String caSerial = leafSerial + "02";
qcc::KeyInfoNISTP256 keyInfo;
caPC.GetSigningPublicKey(keyInfo);
qcc::GUID128 subject(0);
GetGUID(caBus, subject);
QStatus status = CreateMembershipCert(caSerial, caBus, subject.ToString(), keyInfo.GetPublicKey(), sgID, certs[2], true);
if (status != ER_OK) {
return status;
}
/* create the intermediate cert with delegate on */
ajn::PermissionConfigurator& intermediatePC = intermediateBus.GetPermissionConfigurator();
qcc::String intermediateSerial = leafSerial + "01";
intermediatePC.GetSigningPublicKey(keyInfo);
GetGUID(intermediateBus, subject);
status = CreateMembershipCert(intermediateSerial, caBus, subject.ToString(), keyInfo.GetPublicKey(), sgID, certs[1], true);
if (status != ER_OK) {
return status;
}
/* create the leaf cert delegate off */
ajn::PermissionConfigurator& targetPC = targetBus.GetPermissionConfigurator();
targetPC.GetSigningPublicKey(keyInfo);
GetGUID(targetBus, subject);
status = CreateMembershipCert(leafSerial, intermediateBus, subject.ToString(), keyInfo.GetPublicKey(), sgID, certs[0]);
if (status != ER_OK) {
return status;
}
/* install cert chain */
ajn::SecurityApplicationProxy saProxy(intermediateBus, targetBus.GetUniqueName().c_str());
return saProxy.InstallMembership(certs, ArraySize(certs));
}
QStatus SecurityTestHelper::SetCAFlagOnCert(ajn::BusAttachment& issuerBus, qcc::CertificateX509& certificate)
{
certificate.SetCA(true);
ajn::PermissionConfigurator& pc = issuerBus.GetPermissionConfigurator();
return pc.SignCertificate(certificate);
}
QStatus SecurityTestHelper::LoadCertificateBytes(ajn::Message& msg, qcc::CertificateX509& cert)
{
uint8_t encoding;
uint8_t* encoded;
size_t encodedLen;
QStatus status = msg->GetArg(0)->Get("(yay)", &encoding, &encodedLen, &encoded);
if (ER_OK != status) {
return status;
}
status = ER_NOT_IMPLEMENTED;
if (encoding == qcc::CertificateX509::ENCODING_X509_DER) {
status = cert.DecodeCertificateDER(qcc::String((const char*) encoded, encodedLen));
} else if (encoding == qcc::CertificateX509::ENCODING_X509_DER_PEM) {
status = cert.DecodeCertificatePEM(qcc::String((const char*) encoded, encodedLen));
}
return status;
}
bool SecurityTestHelper::IsPermissionDeniedError(QStatus status, ajn::Message& msg)
{
if (ER_PERMISSION_DENIED == status) {
return true;
}
if (ER_BUS_REPLY_IS_ERROR_MESSAGE == status) {
qcc::String errorMsg;
const char* errorName = msg->GetErrorName(&errorMsg);
if (errorName == nullptr) {
return false;
}
if (strcmp(errorName, "org.alljoyn.Bus.Security.Error.PermissionDenied") == 0) {
return true;
}
if (strcmp(errorName, "org.alljoyn.Bus.ErStatus") != 0) {
return false;
}
if (errorMsg == "ER_PERMISSION_DENIED") {
return true;
}
}
return false;
}
QStatus SecurityTestHelper::ReadClaimResponse(ajn::Message& msg, qcc::ECCPublicKey* pubKey)
{
return RetrievePublicKeyFromMsgArg(*msg->GetArg(0), pubKey);
}
QStatus SecurityTestHelper::JoinPeerSession(ajn::BusAttachment& initiator, ajn::BusAttachment& responder, ajn::SessionId& sessionId)
{
ajn::SessionOpts opts(ajn::SessionOpts::TRAFFIC_MESSAGES, false, ajn::SessionOpts::PROXIMITY_ANY, ajn::TRANSPORT_ANY);
QStatus status = ER_FAIL;
const size_t maxAttempts = 30;
for (size_t attempt = 0; attempt < maxAttempts; attempt++) {
status = initiator.JoinSession(responder.GetUniqueName().c_str(),
ALLJOYN_SESSIONPORT_PERMISSION_MGMT, nullptr, sessionId, opts);
if (ER_OK == status) {
return status;
}
/* sleep a few seconds since the responder may not yet setup the listener port */
qcc::Sleep(WAIT_TIME_100);
}
return status;
}
void SecurityTestHelper::CallDeprecatedSetPSK(ajn::DefaultECDHEAuthListener* authListener, const uint8_t* pskBytes, size_t pskLength)
{
/*
* This function suppresses compiler warnings when calling SetPSK, which is deprecated.
* ECHDE_PSK is deprecated as of 16.04, but we still test it, per the Alliance deprecation policy.
* ASACORE-2762 tracks removal of the ECDHE_PSK tests (and this function can be removed as a part of that work).
* https://jira.allseenalliance.org/browse/ASACORE-2762
*/
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
#if defined(QCC_OS_GROUP_WINDOWS)
#pragma warning(push)
#pragma warning(disable: 4996)
#endif
QCC_VERIFY(ER_OK == authListener->SetPSK(pskBytes, pskLength));
#if defined(QCC_OS_GROUP_WINDOWS)
#pragma warning(pop)
#endif
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
}
void SecurityTestHelper::UnwrapStrings(const std::vector<std::string>& strings, std::vector<AJ_PCSTR>& unwrapped)
{
unwrapped.resize(strings.size());
for (std::vector<std::string>::size_type i = 0; i < strings.size(); i++) {
unwrapped[i] = strings[i].c_str();
}
}
void SecurityTestHelper::BuildValidity(qcc::CertificateX509::ValidPeriod& validity, uint32_t expiredInSecs)
{
validity.validFrom = qcc::GetEpochTimestamp() / 1000;
validity.validTo = validity.validFrom + expiredInSecs;
}
| 40.67701 | 133 | 0.597122 | [
"vector"
] |
1262265df8d8a18b6150c4248450717afd2c6225 | 619 | hpp | C++ | lumino/LuminoEngine/src/Physics/PhysicsDebugRenderer.hpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 113 | 2020-03-05T01:27:59.000Z | 2022-03-28T13:20:51.000Z | lumino/LuminoEngine/src/Physics/PhysicsDebugRenderer.hpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 35 | 2016-04-18T06:14:08.000Z | 2020-02-09T15:51:58.000Z | lumino/LuminoEngine/src/Physics/PhysicsDebugRenderer.hpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 12 | 2020-12-21T12:03:59.000Z | 2021-12-15T02:07:49.000Z | #pragma once
namespace ln {
namespace detail {
// 3D/ 2D 共通の描画キャッシュ。
class PhysicsDebugRenderer
{
public:
static const size_t MaxVertexCount = 8192;
void init();
void render(RenderingContext* context);
void addLineVertex(const Vector3& v, const Color& c);
void addTriangleVertex(const Vector3& v, const Color& c);
void drawLine(const Vector3& p1, const Vector3& p2, const Color& color1, const Color& color2);
private:
Ref<VertexBuffer> m_linesBuffer;
Ref<VertexBuffer> m_trianglesBuffer;
size_t m_linesVertexCount;
size_t m_trianglesVertexCount;
};
} // namespace detail
} // namespace ln
| 21.344828 | 95 | 0.743134 | [
"render",
"3d"
] |
1265df286545538f6d64a49ef93df1436d0b5f27 | 4,134 | hpp | C++ | cpp/nameq.hpp | ninchat/nameq | 6769f0dbd4c920dd38c2c93b5042d242fcc910bb | [
"MIT"
] | null | null | null | cpp/nameq.hpp | ninchat/nameq | 6769f0dbd4c920dd38c2c93b5042d242fcc910bb | [
"MIT"
] | null | null | null | cpp/nameq.hpp | ninchat/nameq | 6769f0dbd4c920dd38c2c93b5042d242fcc910bb | [
"MIT"
] | null | null | null | #ifndef NAMEQ_HPP
#define NAMEQ_HPP
#include <map>
#include <string>
#include <vector>
#ifndef NAMEQ_NOEXCEPT
# include <boost/config.hpp>
# define NAMEQ_NOEXCEPT BOOST_NOEXCEPT
#endif
#ifndef NAMEQ_EXPORT
# ifdef __GNUC__
# define NAMEQ_EXPORT __attribute__ ((visibility ("default")))
# else
# define NAMEQ_EXPORT
# endif
#endif
/**
*/
#define NAMEQ_DEFAULT_FEATURE_DIR "/etc/nameq/features"
/**
*/
#define NAMEQ_DEFAULT_STATE_DIR "/run/nameq/state"
/**
*/
namespace nameq {
/**
* Add or update a local feature.
*
* @param name
* @param data must be a valid JSON document.
* @param feature_dir
* @return true on success and false on error.
*/
bool set_feature(const std::string &name, const std::string &data, const char *feature_dir = NAMEQ_DEFAULT_FEATURE_DIR) NAMEQ_NOEXCEPT NAMEQ_EXPORT;
/**
* Remove a local feature. Redundant calls are ok.
*
* @param name
* @param feature_dir
* @return true if it was removed or it didn't exist, and false on error.
*/
bool remove_feature(const std::string &name, const char *feature_dir = NAMEQ_DEFAULT_FEATURE_DIR) NAMEQ_NOEXCEPT NAMEQ_EXPORT;
/**
* Removes a local feature upon destruction.
*/
class FeatureContext {
public:
/**
* @param name is copied.
* @param feature_dir is NOT copied, it must outlive the FeatureContext.
*/
explicit FeatureContext(const std::string &name, const char *feature_dir = NAMEQ_DEFAULT_FEATURE_DIR):
m_name(name),
m_feature_dir(feature_dir)
{
}
~FeatureContext() NAMEQ_NOEXCEPT
{
remove_feature(m_name, m_feature_dir);
}
/**
* Add or update a local feature.
*
* @param data must be a valid JSON document.
* @return true on success and false on error.
*/
bool set(const std::string &data) NAMEQ_NOEXCEPT
{
return set_feature(m_name, data, m_feature_dir);
}
private:
FeatureContext(const FeatureContext &);
FeatureContext &operator=(const FeatureContext &);
const std::string m_name;
const char *const m_feature_dir;
};
/**
*/
class Feature {
public:
Feature() NAMEQ_NOEXCEPT
{
}
Feature(const std::string &name, const std::string &host, const std::string &data):
name(name),
host(host),
data(data)
{
}
Feature(const Feature &other):
name(other.name),
host(other.host),
data(other.data)
{
}
Feature &operator=(const Feature &other)
{
name = other.name;
host = other.host;
data = other.data;
return *this;
}
/**
*/
std::string name;
/**
*/
std::string host;
/**
*/
std::string data;
};
/**
* Usage:
*
* 1. init()
* 2. read() while not empty
* 3. wait until fd() is readable
* 4. goto 2 unless you want to stop
* 5. close()
*/
class FeatureMonitor
{
typedef std::map<int, std::string> WatchDirs;
typedef std::map<std::string, int> DirWatches;
public:
typedef std::vector<Feature> Buffer;
FeatureMonitor() NAMEQ_NOEXCEPT
{
}
~FeatureMonitor() NAMEQ_NOEXCEPT
{
close();
}
/**
* Must not be called multiple times, unless close is called in between.
*
* @param state_dir is copied.
* @return 0 on success, and -1 on error with errno set.
*/
int init(const char *state_dir = NAMEQ_DEFAULT_STATE_DIR) NAMEQ_NOEXCEPT NAMEQ_EXPORT;
/**
* Get pending features updates.
*
* @param output is appended to.
* @return 0 on success, and -1 on error with errno set.
*/
int read(Buffer &output) NAMEQ_NOEXCEPT NAMEQ_EXPORT;
/**
* A file descriptor which may be used to wait for feature updates. Wait
* for its readability with select/poll/etc.
*
* @return a file descriptor if init has been called successfully, and
* close hasn't been called yet.
*/
int fd() NAMEQ_NOEXCEPT
{
return m.fd;
}
/**
* May be called multiple times, even if init hasn't been called.
*/
void close() NAMEQ_NOEXCEPT NAMEQ_EXPORT;
private:
FeatureMonitor(const FeatureMonitor &);
FeatureMonitor &operator=(const FeatureMonitor &);
struct Methods;
struct Members {
Members() NAMEQ_NOEXCEPT:
fd(-1)
{
}
int fd;
std::string root_dir;
int root_watch;
WatchDirs feature_watch_dirs;
DirWatches feature_dir_watches;
Buffer buffer;
};
Members m;
};
} // namespace nameq
#endif
| 18.876712 | 148 | 0.694001 | [
"vector"
] |
126799e7f4d41b3a05376f4d21228caf60b743ae | 450 | hpp | C++ | project/3D_Scenegraph/Light.hpp | mhooITU/GameProgramming2021 | 96225cfdb9282b5b36b8815d3d166142b9e9fc10 | [
"MIT"
] | 47 | 2017-07-27T11:12:05.000Z | 2021-07-02T19:45:23.000Z | project/3D_Scenegraph/Light.hpp | mhooITU/GameProgramming2021 | 96225cfdb9282b5b36b8815d3d166142b9e9fc10 | [
"MIT"
] | 7 | 2018-06-07T13:59:46.000Z | 2020-10-08T12:14:58.000Z | project/3D_Scenegraph/Light.hpp | mhooITU/GameProgramming2021 | 96225cfdb9282b5b36b8815d3d166142b9e9fc10 | [
"MIT"
] | 19 | 2017-09-04T10:54:24.000Z | 2020-11-03T17:55:10.000Z | //
// Created by Morten Nobel Jørgensen on 2018-11-08.
//
#pragma once
#include <sre/Mesh.hpp>
#include <sre/Camera.hpp>
#include <sre/Light.hpp>
#include "GameObject.hpp"
#include <sre/Material.hpp>
#include "Transform.hpp"
#include "Updatable.hpp"
class Light : public Component {
public:
Light(GameObject* gameObject);
void debugGUI() override ;
sre::Light& getLight();
private:
Transform* transform;
sre::Light light;
}; | 17.307692 | 51 | 0.693333 | [
"mesh",
"transform"
] |
12689440ab07a5d824d0da720aceaec23b48411e | 15,171 | cpp | C++ | source/render.cpp | GabrielRavier/CaveStoryRecoded | dc7205398a1e81cdd1baf671edb706e010133046 | [
"MIT"
] | 4 | 2019-02-09T19:01:19.000Z | 2021-04-21T03:14:27.000Z | source/render.cpp | GabrielRavier/CaveStoryRecoded | dc7205398a1e81cdd1baf671edb706e010133046 | [
"MIT"
] | 7 | 2018-10-11T19:29:01.000Z | 2019-01-14T17:23:39.000Z | source/render.cpp | GabrielRavier/CaveStoryRecoded | dc7205398a1e81cdd1baf671edb706e010133046 | [
"MIT"
] | 2 | 2018-10-07T16:45:08.000Z | 2019-01-04T03:40:08.000Z | #include "render.h"
#include <string>
#include "SDL.h"
#include "lodepng/lodepng.h"
#include "game.h"
#include "main.h"
#include "common.h"
#include "input.h"
#include "log.h"
#include "filesystem.h"
#include "shiftJISToUTF8.h"
#ifdef USE_ICONS_SDL2
#include "icon_mini.h"
#endif
using namespace std::string_literals;
SDL_Window *gWindow;
SDL_Renderer *gRenderer;
SDL_Rect gRcDraw = {0, 0, 0, 0};
SDL_Rect gImageRectangle = {0, 0, 0, 0};
SDL_Rect gDrawRectangle = {0, 0, 0, 0};
SDL_Rect gCliprect = {0, 0, 0, 0};
int gScreenWidth = 320;
int gScreenHeight = 240;
int gScreenScale = 2;
bool gDisplayFpsCounter = false;
int gPrevWidth = 0;
int gPrevHeight = 0;
int gPrevScale = 0;
int gCharWidth = 24;
int gCharHeight = 24;
int gCharScale = 2;
int gFramewait = 20; //17 for 60-ish fps
uint32_t gWindowFlags = 0;
bool gConvertFromShiftJISToUTF8BeforeRender = false;
static SDL_Surface *gCursorSurface;
static SDL_Cursor *gCursor;
static SDL_Surface* loadPNGToSurface(const std::string& path)
{
SDL_Surface *surface = nullptr;
unsigned char *pixel_buffer;
unsigned int width;
unsigned int height;
if (const unsigned int error = lodepng_decode32_file(&pixel_buffer, &width, &height, path.c_str()))
doCustomError("loadPNGToSurface failed!\n\nlodepng error: "s + lodepng_error_text(error) + "\nFile : " + path);
else
{
// We don't use SDL_CreateRGBSurfaceWithFormatFrom because then the pixel data wouldn't
// automatically be freed when the surface is destroyed, so we have to do this trickery instead.
surface = SDL_CreateRGBSurfaceWithFormat(0, width, height, 0, SDL_PIXELFORMAT_RGBA32);
if (surface == nullptr)
doCustomError("loadPNGToSurface failed!\n\nSDL2 error: "s + SDL_GetError() + "\nFile : " + path);
else
for (unsigned int i = 0; i < height; ++i)
memcpy(static_cast<unsigned char*>(surface->pixels) + (i * surface->pitch), pixel_buffer + (i * width * 4), width * 4);
free(pixel_buffer);
}
return surface;
}
static SDL_Texture* loadPNGToTexture(SDL_Renderer *localRenderer, const std::string& path)
{
SDL_Texture *texture = nullptr;
SDL_Surface *surface = loadPNGToSurface(path);
if (surface)
{
texture = SDL_CreateTextureFromSurface(localRenderer, surface);
if (texture == nullptr)
doCustomError("loadPNGToTexture failed!\n\nSDL2 error: "s + SDL_GetError());
SDL_FreeSurface(surface);
}
return texture;
}
static SDL_Texture* loadBMPToTexture(SDL_Renderer *rend, const std::string& path)
{
SDL_Texture *texture = nullptr;
SDL_Surface *surf = SDL_LoadBMP(path.c_str());
if (surf)
{
SDL_SetColorKey(surf, 1, 0);
texture = SDL_CreateTextureFromSurface(rend, surf);
if (texture == nullptr)
doCustomError("loadBMPToTexture failed!\n\nSDL2 error: "s + SDL_GetError());
SDL_FreeSurface(surf);
}
return texture;
}
//Create window
int createWindow(int width, int height, int scale)
{
const int createWidth = width * scale;
const int createHeight = height * scale;
gScreenWidth = width;
gScreenHeight = height;
gScreenScale = scale;
//Set window
if (!gWindow)
{
gWindow = SDL_CreateWindow("Cave Story Recoded",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
createWidth, createHeight,
gWindowFlags);
#ifdef USE_ICONS_SDL2
// Set the window icon.
// Note that we skip this on Windows since we do it natively.
unsigned char *pixel_buffer;
unsigned int width;
unsigned int height;
if (!lodepng_decode32(&pixel_buffer, &width, &height, res_icon_mini_png, res_icon_mini_png_len))
{
SDL_Surface *surface = SDL_CreateRGBSurfaceWithFormatFrom(pixel_buffer, width, height, 0, width * 4, SDL_PIXELFORMAT_RGBA32);
if (surface)
{
SDL_SetWindowIcon(gWindow, surface);
SDL_FreeSurface(surface);
}
free(pixel_buffer);
}
#endif
}
else
SDL_SetWindowSize(gWindow, createWidth, createHeight);
if (gWindowFlags == SDL_WINDOW_FULLSCREEN)
SDL_SetWindowFullscreen(gWindow, SDL_WINDOW_FULLSCREEN);
//Set renderer
if (!gRenderer)
{
gRenderer = SDL_CreateRenderer(gWindow, -1, 0);
SDL_SetRenderDrawBlendMode(gRenderer, SDL_BLENDMODE_BLEND);
if (gRenderer == nullptr)
logError("Couldn't create renderer! SDL2 error: "s + SDL_GetError());
}
// TODO free these when closing-down
gCursorSurface = loadPNGToSurface("data/Cursor/cursor_normal.png");
if (gCursorSurface)
{
gCursor = SDL_CreateColorCursor(gCursorSurface, 0, 0); // Don't worry, the hotspots are accurate to the original files
if (gCursor)
SDL_SetCursor(gCursor);
else
logError("Couldn't create cursor");
}
else
logError("Couldn't load cursor image (is the file missing ?)");
return 0;
}
void switchScreenMode()
{
gWindowFlags ^= SDL_WINDOW_FULLSCREEN_DESKTOP;
//Unlike gPrevWidth and Height, this is used for fixing the view when going between fullscreen and windowed mode
const int lastWidth = gScreenWidth;
const int lastHeight = gScreenHeight;
if (gWindowFlags & SDL_WINDOW_FULLSCREEN_DESKTOP)
{
SDL_DisplayMode dm;
if (SDL_GetDesktopDisplayMode(0, &dm) != 0)
doError();
gPrevWidth = gScreenWidth;
gPrevHeight = gScreenHeight;
gPrevScale = gScreenScale;
gScreenWidth = (dm.w * 240) / dm.h;
gScreenHeight = 240;
gScreenScale = dm.h / 240;
}
else
{
gScreenWidth = gPrevWidth;
gScreenHeight = gPrevHeight;
gScreenScale = gPrevScale;
}
//Scale renderer to proper proportions
SDL_RenderSetLogicalSize(gRenderer, gScreenWidth * gScreenScale, gScreenHeight * gScreenScale);
//Ensure that the view is shifted properly
gViewport.x += (lastWidth - gScreenWidth) * 0x100;
gViewport.y += (lastHeight - gScreenHeight) * 0x100;
//Set window properties
SDL_SetWindowSize(gWindow, gScreenWidth * gScreenScale, gScreenHeight * gScreenScale);
SDL_SetWindowFullscreen(gWindow, gWindowFlags);
}
uint32_t calculateFPS()
{
static bool hasFunctionBeenExecuted = false;
static uint32_t ticksAtStart = 0;
if (!hasFunctionBeenExecuted)
{
ticksAtStart = SDL_GetTicks();
hasFunctionBeenExecuted = true;
}
const uint32_t tickCount = SDL_GetTicks();
static uint32_t timeElapsed = 0;
++timeElapsed;
static uint32_t currentRetVal;
if (ticksAtStart + 1000 <= tickCount)
{
ticksAtStart += 1000;
currentRetVal = timeElapsed;
timeElapsed = 0;
}
return currentRetVal;
}
void drawFPS()
{
if (gDisplayFpsCounter)
drawNumber(calculateFPS(), gScreenWidth - 40, 8, false);
}
bool drawWindow()
{
while (true)
{
if (!handleEvents())
return false;
//framerate limiter
static uint32_t timePrev;
const uint32_t timeNow = SDL_GetTicks();
if (timeNow >= timePrev + gFramewait)
{
if (timeNow >= timePrev + 100)
timePrev = timeNow; // If the timer is freakishly out of sync, panic and reset it, instead of spamming frames for who-knows how long
else
timePrev += gFramewait;
break;
}
SDL_Delay(1);
}
drawFPS();
SDL_RenderPresent(gRenderer);
return true;
}
void captureScreen(enum TextureNums texture_id)
{
//Destroy previously existing texture and load new one
if (gSprites[texture_id] != nullptr)
SDL_DestroyTexture(gSprites[texture_id]);
int width, height;
SDL_GetRendererOutputSize(gRenderer, &width, &height);
// The depth parameter here is unused. Be aware, it will be removed in SDL 2.1.
SDL_Surface *surface = SDL_CreateRGBSurfaceWithFormat(SDL_TEXTUREACCESS_TARGET, width, height, 0, SDL_PIXELFORMAT_RGB888);
SDL_RenderReadPixels(gRenderer, nullptr, SDL_PIXELFORMAT_RGB888, surface->pixels, surface->pitch);
gSprites[texture_id] = SDL_CreateTextureFromSurface(gRenderer, surface);
SDL_FreeSurface(surface);
}
void createTextureBuffer(enum TextureNums texture_id, int width, int height)
{
//Destroy previously existing texture and load new one
if (gSprites[texture_id] != nullptr)
SDL_DestroyTexture(gSprites[texture_id]);
gSprites[texture_id] = SDL_CreateTexture(gRenderer, SDL_PIXELFORMAT_RGB888, SDL_TEXTUREACCESS_TARGET, width, height);
}
//Texture and drawing stuff
void loadImage(const std::string& file, SDL_Texture **tex)
{
if (tex == nullptr)
doCustomError("tex was nullptr in loadImage");
//Destroy previously existing texture and load new one
if (*tex != nullptr)
SDL_DestroyTexture(*tex);
//loads either a png or bmp
if(fileExists("data/" + file + ".png"))
*tex = loadPNGToTexture(gRenderer, "data/" + file + ".png");
if (fileExists("data/" + file + ".bmp"))
*tex = loadBMPToTexture(gRenderer, "data/" + file + ".bmp");
//Error if anything failed
if (*tex == nullptr)
doError();
//Set to transparent, error if failed
if (SDL_SetTextureBlendMode(*tex, SDL_BLENDMODE_BLEND) != 0)
doError();
}
//loads images with limited colors
uint8_t gColorValTbl[] = { 0, 52, 87, 116, 144, 172, 206, 255 };
void loadImageBad(const std::string& file, SDL_Texture **tex)
{
SDL_Surface *surface;
if (tex == nullptr)
doCustomError("tex was nullptr in loadImage");
//Destroy previously existing texture and load new one
if (*tex != nullptr)
SDL_DestroyTexture(*tex);
surface = loadPNGToSurface(file);
if (surface->format->palette != nullptr)
{
SDL_Color *colors = new SDL_Color[4 * surface->format->palette->ncolors]();
for (int c = 0; c < surface->format->palette->ncolors; c++)
{
colors[c].r = gColorValTbl[(surface->format->palette->colors[c].r * (sizeof(gColorValTbl) - 1)) / 0xFF];
colors[c].g = gColorValTbl[(surface->format->palette->colors[c].g * (sizeof(gColorValTbl) - 1)) / 0xFF];
colors[c].b = gColorValTbl[(surface->format->palette->colors[c].b * (sizeof(gColorValTbl) - 1)) / 0xFF];
colors[c].a = surface->format->palette->colors[c].a;
}
SDL_SetPaletteColors(surface->format->palette, colors, 0, surface->format->palette->ncolors);
delete[] colors;
}
else
{
uint8_t *pixel = static_cast<uint8_t*>(surface->pixels);
for (int p = 0; p < surface->w*surface->h; p++)
if (pixel[p])
pixel[p] = gColorValTbl[(pixel[p] * (sizeof(gColorValTbl) - 1)) / 0xFF];
}
*tex = SDL_CreateTextureFromSurface(gRenderer, surface);
//Error if anything failed
if (*tex == nullptr)
doError();
//Set to transparent, error if failed
if (SDL_SetTextureBlendMode(*tex, SDL_BLENDMODE_BLEND) != 0)
doError();
}
//Drawing functions
void setCliprect(const RECT *rect)
{
//All of this code should be pretty self explanatory
if (rect != nullptr)
{
gCliprect = { rect->left * gScreenScale, rect->top * gScreenScale, (rect->right - rect->left) * gScreenScale, (rect->bottom - rect->top) * gScreenScale };
SDL_RenderSetClipRect(gRenderer, &gCliprect);
}
else
SDL_RenderSetClipRect(gRenderer, nullptr);
}
void drawTexture(SDL_Texture *texture, const RECT *rect, int x, int y)
{
//Set framerect
if (rect)
{
gImageRectangle = { rect->left, rect->top, rect->right - rect->left, rect->bottom - rect->top };
//Set drawrect, with defined width and height
gRcDraw.x = x * gScreenScale;
gRcDraw.y = y * gScreenScale;
gRcDraw.w = gImageRectangle.w * gScreenScale;
gRcDraw.h = gImageRectangle.h * gScreenScale;
//Draw to screen, error if failed
if (SDL_RenderCopy(gRenderer, texture, &gImageRectangle, &gRcDraw) != 0)
doError();
}
else
{
int w, h;
SDL_QueryTexture(texture, nullptr, nullptr, &w, &h);
gRcDraw.x = (x-(w/2)) * gScreenScale;
gRcDraw.y = (y-(h/2)) * gScreenScale;
gRcDraw.w = w * gScreenScale;
gRcDraw.h = h * gScreenScale;
if (SDL_RenderCopy(gRenderer, texture, nullptr, &gRcDraw) != 0)
doError();
}
}
void drawTextureNoScale(SDL_Texture *texture, const RECT *rect, int x, int y)
{
//Set framerect
if (rect)
{
gImageRectangle = { rect->left, rect->top, rect->right - rect->left, rect->bottom - rect->top };
//Set drawrect, with defined width and height
gRcDraw.x = x;
gRcDraw.y = y;
gRcDraw.w = gImageRectangle.w;
gRcDraw.h = gImageRectangle.h;
//Draw to screen, error if failed
if (SDL_RenderCopy(gRenderer, texture, &gImageRectangle, &gRcDraw) != 0)
doError();
}
else
{
int w, h;
SDL_QueryTexture(texture, nullptr, nullptr, &w, &h);
gRcDraw.x = x;
gRcDraw.y = y;
gRcDraw.w = w;
gRcDraw.h = h;
if (SDL_RenderCopy(gRenderer, texture, nullptr, &gRcDraw) != 0)
doError();
}
}
void drawTextureSize(SDL_Texture *texture, const RECT *rect, int x, int y, int w, int h)
{
//Set framerect
gImageRectangle = { rect->left, rect->top, rect->right - rect->left, rect->bottom - rect->top };
//Set drawrect, with defined width and height
gRcDraw.x = x * gScreenScale;
gRcDraw.y = y * gScreenScale;
gRcDraw.w = w * gScreenScale;
gRcDraw.h = h * gScreenScale;
//Draw to screen, error if failed
if (SDL_RenderCopy(gRenderer, texture, &gImageRectangle, &gRcDraw) != 0)
doError();
}
void drawNumber(int value, int x, int y, bool bZero)
{
RECT numbRect;
int offset = 0;
int pos = 1000; //Replacing an array a day keeps The Doctor away
//Cap value
if (value > 9999)
value = 9999;
int count = 0;
while (offset < 4)
{
int drawValue = 0;
//Get value of this digit
while (pos <= value)
{
value -= pos;
++drawValue;
++count;
}
if ((bZero && offset == 2) || count != 0 || offset == 3) //bZero just makes the second from the right character always draw
{
//Set rect and draw
numbRect = { drawValue << 3, 56, (drawValue + 1) << 3, 64 };
drawTexture(gSprites[26], &numbRect, x + (offset << 3), y);
}
//Change checking digit
offset++;
pos /= 10;
}
}
bool isMultibyte(uint8_t c) attrConst;
bool isMultibyte(uint8_t c) //Shift-JIS
{
if (c > 0x80u && c <= 0x9Fu)
return true;
return !(c <= 0xDFu || c > 0xEFu);
}
void drawString(int x, int y, const std::string& str, const uint8_t *flag)
{
RECT rcChar;
std::string realStr;
if (gConvertFromShiftJISToUTF8BeforeRender)
realStr = shiftJISToUTF8::convert(str);
else
realStr = str;
for (int i = 0; str[i]; i++)
{
//Get separation value from flag array
int sep = 6;
if (flag != nullptr && flag[i] & 1)
sep = 5;
//Circle thing
if (flag != nullptr && flag[i] & 2)
{
rcChar = { 64, 48, 72, 56 };
drawTexture(gSprites[TEX_TEXTBOX], &rcChar, x + (i * sep), y + 2);
}
else
{
//Set framerect to what it's supposed to be
const int drawIndex = i;
if (isMultibyte(str[i]))
{
const int localChar = 0x81 + str[i + 1] + ((str[i] - 0x81) * 0x100);
rcChar.left = ((localChar % 32) * gCharWidth);
rcChar.top = ((localChar >> 5) * gCharHeight);
rcChar.right = rcChar.left + gCharWidth;
rcChar.bottom = rcChar.top + gCharHeight;
i++;
}
else
{
rcChar.left = ((str[i] % 32) * gCharWidth);
rcChar.top = ((str[i] >> 5) * gCharHeight);
rcChar.right = rcChar.left + gCharWidth;
rcChar.bottom = rcChar.top + gCharHeight;
}
//Draw to the screen
drawTextureSize(gSprites[0x26], &rcChar, x + (drawIndex * sep), y, gCharWidth / gCharScale, gCharHeight / gCharScale);
}
}
}
void drawRect(int x, int y, int w, int h)
{
//Map this onto an SDL_Rect
gDrawRectangle.x = x * gScreenScale;
gDrawRectangle.y = y * gScreenScale;
gDrawRectangle.w = w * gScreenScale;
gDrawRectangle.h = h * gScreenScale;
//Render onto the screen
SDL_RenderFillRect(gRenderer, &gDrawRectangle);
}
| 25.933333 | 156 | 0.693824 | [
"render"
] |
12831be9a3bc6b8dbefa43a4f22f7faaaccdca4a | 12,166 | cpp | C++ | apps/opencs/view/render/textoverlay.cpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | apps/opencs/view/render/textoverlay.cpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | apps/opencs/view/render/textoverlay.cpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | #include "textoverlay.hpp"
#include <OgreCamera.h>
#include <OgreMaterialManager.h>
#include <OgreTechnique.h>
#include <OgreOverlayManager.h>
#include <OgreOverlayContainer.h>
#include <OgreFontManager.h>
#include <OgreTextAreaOverlayElement.h>
#include <OgreEntity.h>
#include <OgreViewport.h>
#include <OgreRoot.h>
#include <OgreHardwarePixelBuffer.h>
namespace CSVRender
{
// Things to do:
// - configurable font size in pixels (automatically calulate everything else from it)
// - configurable texture to use
// - try material script
// - decide whether to use QPaint (http://www.ogre3d.org/tikiwiki/Ogre+overlays+using+Qt)
// http://www.ogre3d.org/tikiwiki/ObjectTextDisplay
// http://www.ogre3d.org/tikiwiki/MovableTextOverlay
// http://www.ogre3d.org/tikiwiki/Creating+dynamic+textures
// http://www.ogre3d.org/tikiwiki/ManualObject
TextOverlay::TextOverlay(const Ogre::MovableObject* obj, const Ogre::Camera* camera, const Ogre::String& id)
: mOverlay(0), mCaption(""), mDesc(""), mEnabled(true), mCamera(camera), mObj(obj), mId(id)
, mOnScreen(false) , mInstance(0), mFontHeight(16) // FIXME: make font height configurable
{
if(id == "" || !camera || !obj)
throw std::runtime_error("TextOverlay could not be created.");
// setup font
Ogre::FontManager &fontMgr = Ogre::FontManager::getSingleton();
if (fontMgr.resourceExists("DejaVuLGC"))
mFont = fontMgr.getByName("DejaVuLGC","General");
else
{
mFont = fontMgr.create("DejaVuLGC","General");
mFont->setType(Ogre::FT_TRUETYPE);
mFont->setSource("DejaVuLGCSansMono.ttf");
mFont->setTrueTypeSize(mFontHeight);
mFont->setTrueTypeResolution(96);
}
if(!mFont.isNull())
mFont->load();
else
throw std::runtime_error("TextOverlay font not loaded.");
// setup overlay
Ogre::OverlayManager &overlayMgr = Ogre::OverlayManager::getSingleton();
mOverlay = overlayMgr.getByName("CellIDPanel"+mId+Ogre::StringConverter::toString(mInstance));
// FIXME: this logic is badly broken as it is possible to delete an earlier instance
while(mOverlay != NULL)
{
mInstance++;
mOverlay = overlayMgr.getByName("CellIDPanel"+mId+Ogre::StringConverter::toString(mInstance));
}
mOverlay = overlayMgr.create("CellIDPanel"+mId+Ogre::StringConverter::toString(mInstance));
// create texture
Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName("DynamicTransBlue");
if(texture.isNull())
{
texture = Ogre::TextureManager::getSingleton().createManual(
"DynamicTransBlue", // name
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TEX_TYPE_2D, // type
8, 8, // width & height
0, // number of mipmaps
Ogre::PF_BYTE_BGRA, // pixel format
Ogre::TU_DEFAULT); // usage; should be TU_DYNAMIC_WRITE_ONLY_DISCARDABLE for
// textures updated very often (e.g. each frame)
Ogre::HardwarePixelBufferSharedPtr pixelBuffer = texture->getBuffer();
pixelBuffer->lock(Ogre::HardwareBuffer::HBL_NORMAL);
const Ogre::PixelBox& pixelBox = pixelBuffer->getCurrentLock();
uint8_t* pDest = static_cast<uint8_t*>(pixelBox.data);
// Fill in some pixel data. This will give a semi-transparent blue,
// but this is of course dependent on the chosen pixel format.
for (size_t j = 0; j < 8; j++)
{
for(size_t i = 0; i < 8; i++)
{
*pDest++ = 255; // B
*pDest++ = 0; // G
*pDest++ = 0; // R
*pDest++ = 63; // A
}
pDest += pixelBox.getRowSkip() * Ogre::PixelUtil::getNumElemBytes(pixelBox.format);
}
pixelBuffer->unlock();
}
// setup material for containers
Ogre::MaterialPtr mQuadMaterial = Ogre::MaterialManager::getSingleton().getByName(
"TransOverlayMaterial");
if(mQuadMaterial.isNull())
{
Ogre::MaterialPtr mQuadMaterial = Ogre::MaterialManager::getSingleton().create(
"TransOverlayMaterial",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true );
Ogre::Pass *pass = mQuadMaterial->getTechnique( 0 )->getPass( 0 );
pass->setLightingEnabled( false );
pass->setDepthWriteEnabled( false );
pass->setSceneBlending( Ogre::SBT_TRANSPARENT_ALPHA );
Ogre::TextureUnitState *tex = pass->createTextureUnitState("MyCustomState", 0);
tex->setTextureName("DynamicTransBlue");
tex->setTextureFiltering( Ogre::TFO_ANISOTROPIC );
mQuadMaterial->load();
}
mContainer = static_cast<Ogre::OverlayContainer*>(overlayMgr.createOverlayElement(
"Panel", "container"+mId +"#"+Ogre::StringConverter::toString(mInstance)));
mContainer->setMaterialName("TransOverlayMaterial");
mOverlay->add2D(mContainer);
// setup text area overlay element
mElement = static_cast<Ogre::TextAreaOverlayElement*>(overlayMgr.createOverlayElement(
"TextArea", "text"+mId +"#"+Ogre::StringConverter::toString(mInstance)));
mElement->setMetricsMode(Ogre::GMM_RELATIVE);
mElement->setDimensions(1.0, 1.0);
mElement->setMetricsMode(Ogre::GMM_PIXELS);
mElement->setPosition(2*fontHeight()/3, 1.3*fontHeight()/3); // 1.3 & 2 = fudge factor
mElement->setFontName("DejaVuLGC");
mElement->setCharHeight(fontHeight()); // NOTE: seems that this is required as well as font->setTrueTypeSize()
mElement->setHorizontalAlignment(Ogre::GHA_LEFT);
//mElement->setColour(Ogre::ColourValue(1.0, 1.0, 1.0)); // R, G, B
mElement->setColour(Ogre::ColourValue(1.0, 1.0, 0)); // yellow
mContainer->addChild(mElement);
mOverlay->show();
}
void TextOverlay::getScreenCoordinates(const Ogre::Vector3& position, Ogre::Real& x, Ogre::Real& y)
{
Ogre::Vector3 hcsPosition = mCamera->getProjectionMatrix() * (mCamera->getViewMatrix() * position);
x = 1.0f - ((hcsPosition.x * 0.5f) + 0.5f); // 0 <= x <= 1 // left := 0,right := 1
y = ((hcsPosition.y * 0.5f) + 0.5f); // 0 <= y <= 1 // bottom := 0,top := 1
}
void TextOverlay::getMinMaxEdgesOfAABBIn2D(float& MinX, float& MinY, float& MaxX, float& MaxY,
bool top)
{
MinX = 0, MinY = 0, MaxX = 0, MaxY = 0;
float X[4]; // the 2D dots of the AABB in screencoordinates
float Y[4];
if(!mObj->isInScene())
return;
const Ogre::AxisAlignedBox &AABB = mObj->getWorldBoundingBox(true); // the AABB of the target
Ogre::Vector3 cornersOfAABB[4];
if(top)
{
cornersOfAABB[0] = AABB.getCorner(Ogre::AxisAlignedBox::FAR_LEFT_TOP);
cornersOfAABB[1] = AABB.getCorner(Ogre::AxisAlignedBox::FAR_RIGHT_TOP);
cornersOfAABB[2] = AABB.getCorner(Ogre::AxisAlignedBox::NEAR_LEFT_TOP);
cornersOfAABB[3] = AABB.getCorner(Ogre::AxisAlignedBox::NEAR_RIGHT_TOP);
}
else
{
cornersOfAABB[0] = AABB.getCorner(Ogre::AxisAlignedBox::FAR_LEFT_BOTTOM);
cornersOfAABB[1] = AABB.getCorner(Ogre::AxisAlignedBox::FAR_RIGHT_BOTTOM);
cornersOfAABB[2] = AABB.getCorner(Ogre::AxisAlignedBox::NEAR_LEFT_BOTTOM);
cornersOfAABB[3] = AABB.getCorner(Ogre::AxisAlignedBox::NEAR_RIGHT_BOTTOM);
}
//The normal vector of the plane. This points directly infront of the camera.
Ogre::Vector3 cameraPlainNormal = mCamera->getDerivedOrientation().zAxis();
//the plane that devides the space before and behind the camera.
Ogre::Plane CameraPlane = Ogre::Plane(cameraPlainNormal, mCamera->getDerivedPosition());
for (int i = 0; i < 4; i++)
{
X[i] = 0;
Y[i] = 0;
getScreenCoordinates(cornersOfAABB[i],X[i],Y[i]); // transfor into 2d dots
if (CameraPlane.getSide(cornersOfAABB[i]) == Ogre::Plane::NEGATIVE_SIDE)
{
if (i == 0) // accept the first set of values, no matter how bad it might be.
{
MinX = X[i];
MinY = Y[i];
MaxX = X[i];
MaxY = Y[i];
}
else // now compare if you get "better" values
{
if (MinX > X[i]) MinX = X[i];
if (MinY > Y[i]) MinY = Y[i];
if (MaxX < X[i]) MaxX = X[i];
if (MaxY < Y[i]) MaxY = Y[i];
}
}
else
{
MinX = 0;
MinY = 0;
MaxX = 0;
MaxY = 0;
break;
}
}
}
TextOverlay::~TextOverlay()
{
Ogre::OverlayManager::OverlayMapIterator iter = Ogre::OverlayManager::getSingleton().getOverlayIterator();
if(!iter.hasMoreElements())
mOverlay->hide();
Ogre::OverlayManager *overlayMgr = Ogre::OverlayManager::getSingletonPtr();
mContainer->removeChild("text"+mId+"#"+Ogre::StringConverter::toString(mInstance));
mOverlay->remove2D(mContainer);
if(!iter.hasMoreElements())
overlayMgr->destroy(mOverlay);
}
void TextOverlay::show(bool show)
{
if(show && mOnScreen)
mContainer->show();
else
mContainer->hide();
}
void TextOverlay::enable(bool enable)
{
if(enable == mOverlay->isVisible())
return;
mEnabled = enable;
if(enable)
mOverlay->show();
else
mOverlay->hide();
}
bool TextOverlay::isEnabled()
{
return mEnabled;
}
void TextOverlay::setCaption(const Ogre::String& text)
{
if(mCaption == text)
return;
mCaption = text;
mElement->setCaption(text);
}
void TextOverlay::setDesc(const Ogre::String& text)
{
if(mDesc == text)
return;
mDesc = text;
mElement->setCaption(mCaption + ((text == "") ? "" : ("\n" + text)));
}
Ogre::FontPtr TextOverlay::getFont()
{
return mFont;
}
int TextOverlay::textWidth()
{
float captionWidth = 0;
float descWidth = 0;
for(Ogre::String::const_iterator i = mCaption.begin(); i < mCaption.end(); ++i)
{
if(*i == 0x0020)
captionWidth += getFont()->getGlyphAspectRatio(0x0030);
else
captionWidth += getFont()->getGlyphAspectRatio(*i);
}
for(Ogre::String::const_iterator i = mDesc.begin(); i < mDesc.end(); ++i)
{
if(*i == 0x0020)
descWidth += getFont()->getGlyphAspectRatio(0x0030);
else
descWidth += getFont()->getGlyphAspectRatio(*i);
}
captionWidth *= fontHeight();
descWidth *= fontHeight();
return (int) std::max(captionWidth, descWidth);
}
int TextOverlay::fontHeight()
{
return mFontHeight;
}
void TextOverlay::update()
{
float min_x, max_x, min_y, max_y;
getMinMaxEdgesOfAABBIn2D(min_x, min_y, max_x, max_y, false);
if ((min_x>0.0) && (max_x<1.0) && (min_y>0.0) && (max_y<1.0))
{
mOnScreen = true;
mContainer->show();
}
else
{
mOnScreen = false;
mContainer->hide();
return;
}
getMinMaxEdgesOfAABBIn2D(min_x, min_y, max_x, max_y);
Ogre::OverlayManager &overlayMgr = Ogre::OverlayManager::getSingleton();
float viewportWidth = std::max(overlayMgr.getViewportWidth(), 1); // zero at the start
float viewportHeight = std::max(overlayMgr.getViewportHeight(), 1); // zero at the start
int width = fontHeight()*2/3 + textWidth() + fontHeight()*2/3; // add margins
int height = fontHeight()/3 + fontHeight() + fontHeight()/3;
if(mDesc != "")
height = fontHeight()/3 + 2*fontHeight() + fontHeight()/3;
float relTextWidth = width / viewportWidth;
float relTextHeight = height / viewportHeight;
float posX = 1 - (min_x + max_x + relTextWidth)/2;
float posY = 1 - max_y - (relTextHeight-fontHeight()/3/viewportHeight);
mContainer->setMetricsMode(Ogre::GMM_RELATIVE);
mContainer->setPosition(posX, posY);
mContainer->setDimensions(relTextWidth, relTextHeight);
mPos = QRect(posX*viewportWidth, posY*viewportHeight, width, height);
}
QRect TextOverlay::container()
{
return mPos;
}
}
| 33.794444 | 114 | 0.624692 | [
"vector"
] |
128736f923ec842aead8abf212bc9f3167444ede | 717 | cpp | C++ | AtCoder/abc100/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | AtCoder/abc100/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | 1 | 2021-10-19T08:47:23.000Z | 2022-03-07T05:23:56.000Z | AtCoder/abc100/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int D, N, ans = 0; cin >> D >> N;
int i = 0, j = 1;
if (D == 0) {
if (N == 100) ans = 101;
else {
while(i < N) {
if (j % 100 != 0) i++, ans = j, j++;
}
}
}
else if (D == 1) {
j = 100;
while(i < N) {
if (j % 100 == 0) i++, ans = j, j += 100;
}
if (N == 100) ans = 10100;
}
else if (D == 2) {
j = 10000;
while(i < N) {
if (j % 10000 == 0) i++, ans = j, j += 10000;
}
if (N == 100) ans = 1010000;
}
cout << ans << endl;
}
| 21.727273 | 57 | 0.359833 | [
"vector"
] |
12875b7353ad025d2ef71ec6132f5203779a4523 | 1,235 | hpp | C++ | src/engine/scene.hpp | dfintha/gldemo | e4ff3bce6a6e25a1081208937405ca3202eac60e | [
"WTFPL"
] | null | null | null | src/engine/scene.hpp | dfintha/gldemo | e4ff3bce6a6e25a1081208937405ca3202eac60e | [
"WTFPL"
] | null | null | null | src/engine/scene.hpp | dfintha/gldemo | e4ff3bce6a6e25a1081208937405ca3202eac60e | [
"WTFPL"
] | null | null | null | #if !defined(GENGINE_ENGINE_SCENE)
#define GENGINE_ENGINE_SCENE
#include "engine/camera.hpp"
#include "engine/shader_program.hpp"
#include "geometry/vector.hpp"
#include "gl.hpp"
namespace obj {
class object_base;
}
#include <memory>
#include <vector>
namespace eng {
struct scene {
int width, height;
bool grab_mouse;
bool full_screen;
eng::camera cam;
eng::shader_program program;
geo::vector light_position;
geo::vector light_color;
geo::vector ambient_color;
geo::vector background_color;
std::vector<std::shared_ptr<obj::object_base>> objects;
scene() :
width(1000),
height(700),
grab_mouse(false),
full_screen(false),
cam(),
program(),
light_position(),
light_color(),
ambient_color(),
background_color(),
objects()
{ }
scene(const scene&) = default;
scene(scene&&) = default;
scene& operator=(const scene&) = default;
scene& operator=(scene&&) = default;
~scene() noexcept = default;
inline void toggle_full_screen() {
if (full_screen) {
glutReshapeWindow(width, height);
glutPositionWindow(100, 100);
} else {
glutFullScreen();
}
full_screen = !full_screen;
}
};
}
#endif
| 19.603175 | 57 | 0.655061 | [
"geometry",
"vector"
] |
12991fe895bd5207f7bc85b6b00386c6a7417b37 | 4,780 | hpp | C++ | src/moonlight/moonlight/protocol.hpp | games-on-whales/wolf | cd5aa47e0547d1bc7b093fb6cdd0582eae78b391 | [
"MIT"
] | 1 | 2021-12-30T13:15:05.000Z | 2021-12-30T13:15:05.000Z | src/moonlight/moonlight/protocol.hpp | games-on-whales/wolf | cd5aa47e0547d1bc7b093fb6cdd0582eae78b391 | [
"MIT"
] | null | null | null | src/moonlight/moonlight/protocol.hpp | games-on-whales/wolf | cd5aa47e0547d1bc7b093fb6cdd0582eae78b391 | [
"MIT"
] | null | null | null | #pragma once
#include "config.hpp"
#include "data-structures.hpp"
#include <boost/property_tree/ptree.hpp>
namespace pt = boost::property_tree;
namespace moonlight {
constexpr auto M_VERSION = "7.1.431.0";
constexpr auto M_GFE_VERSION = "3.23.0.74";
/**
* @brief Step 1: GET server status
*
* @param config: local state: ip, mac address, already paired clients.
* @param isServerBusy: true if we are already running a streaming session
* @param current_appid: -1 if no app is running, otherwise the ID as defined in the app list
* @param display_modes: a list of supported display modes for the current server
* @param clientID: used to check if it's already paired
*
* @return ptree the XML response to be sent
*/
pt::ptree serverinfo(const Config &config,
bool isServerBusy,
int current_appid,
const std::vector<DisplayMode> &display_modes,
const std::string &clientID);
/**
* @brief Step 2: PAIR a new client
*
* Defines the Moonlight client/server pairing protocol
*/
namespace pair {
/**
* @brief Pair, phase 1:
*
* Moonlight will send a salt and client certificate, we'll also need the user provided pin.
*
* PIN and SALT will be used to derive a shared AES key that needs to be stored
* in order to be used to decrypt in the next phases (see `gen_aes_key`).
*
* At this stage we only have to send back our public certificate (`plaincert`).
*
* @return pair<ptree, string> the XML response and the AES key to be used in the next steps
*/
std::pair<pt::ptree, std::string>
get_server_cert(const std::string &user_pin, const std::string &salt, const std::string &server_cert_pem);
/**
* @brief will derive a common AES key given the salt and the user provided pin
*
* This method needs to match what Moonlight is doing internally otherwise we wouldn't be able to decrypt the
* client challenge.
*
* @return `SHA256(SALT + PIN)[0:16]`
*/
std::string gen_aes_key(const std::string &salt, const std::string &pin);
/**
* @brief Pair, phase 2
*
* Using the AES key that we generated in the phase 1 we have to decrypt the client challenge,
*
* We generate a SHA256 hash with the following:
* - Decrypted challenge
* - Server certificate signature
* - Server secret: a randomly generated secret
*
* The hash + server_challenge will then be AES encrypted and sent as the `challengeresponse` in the returned XML
*
* @return pair<ptree, pair<string, string>> the response and the pair of generated:
* server_secret, server_challenge
*/
std::pair<pt::ptree, std::pair<std::string, std::string>>
send_server_challenge(const std::string &aes_key,
const std::string &client_challenge,
const std::string &server_cert_signature,
const std::string &server_secret = crypto::random(16),
const std::string &server_challenge = crypto::random(16));
/**
* @brief Pair, phase 3
*
* Moonlight will send back a `serverchallengeresp`: an AES encrypted client hash,
* we have to send back the `pairingsecret`:
* using our private key we have to sign the certificate_signature + server_secret (generated in phase 2)
*
* @return pair<ptree, string> the response and the decrypted client_hash
*/
std::pair<pt::ptree, std::string> get_client_hash(const std::string &aes_key,
const std::string &server_secret,
const std::string &server_challenge_resp,
const std::string &server_cert_private_key);
/**
* @brief Pair, phase 4 (final)
*
* We now have to use everything we exchanged before in order to verify and finally pair the clients
*
* We'll check the client_hash obtained at phase 3, it should contain the following:
* - The original server_challenge
* - The signature of the X509 client_cert
* - The unencrypted client_pairing_secret
* We'll check that SHA256(server_challenge + client_public_cert_signature + client_secret) == client_hash
*
* Then using the client certificate public key we should be able to verify that
* the client secret has been signed by Moonlight
*
* @return ptree: The XML response will contain:
* paired = 1, if all checks are fine
* paired = 0, otherwise
*/
pt::ptree client_pair(const std::string &aes_key,
const std::string &server_challenge,
const std::string &client_hash,
const std::string &client_pairing_secret,
const std::string &client_public_cert_signature,
const std::string &client_cert_public_key);
} // namespace pair
} // namespace moonlight | 38.861789 | 113 | 0.673222 | [
"vector"
] |
129eab7c78311985560ced7b304d97e80e4e0da0 | 13,224 | cc | C++ | src/world.cc | obs145628/2048-ai | cdcd27106e390718188c9f4d753d30f6af8f8208 | [
"MIT"
] | null | null | null | src/world.cc | obs145628/2048-ai | cdcd27106e390718188c9f4d753d30f6af8f8208 | [
"MIT"
] | null | null | null | src/world.cc | obs145628/2048-ai | cdcd27106e390718188c9f4d753d30f6af8f8208 | [
"MIT"
] | null | null | null | #include "world.hh"
#include <algorithm>
#include <cassert>
#include <ai/shell/date.hh>
#include <ai/sfml/sf-app.hh>
#include <ai/shell/grid.hh>
#include <ai/shell/shell-sprite.hh>
#include <ai/shell/shell.hh>
namespace
{
constexpr int GRID_SIZE = 600;
constexpr int MARGIN = 20;
constexpr int FONT_SIZE = 150;
const sf::Color BORDER_COLOR(187, 173, 160);
const sf::Color BG_COLORS[] =
{
sf::Color(205, 192, 180), //empty
sf::Color(238, 228, 218), //2
sf::Color(237, 224, 200), //4
sf::Color(242, 177, 121), //8
sf::Color(242, 177, 121), //16
sf::Color(246, 124, 95), //32
sf::Color(246, 94, 59), //64
sf::Color(237, 207, 114), //128
sf::Color(237, 204, 97), //256
sf::Color(237, 200, 80), //512
sf::Color(237, 197, 63), //1024
sf::Color(237, 194, 46), //2048
sf::Color(0, 0, 0), //4096
sf::Color(0, 0, 0), //8192
sf::Color(0, 0, 0), //16384
sf::Color(0, 0, 0), //32768
sf::Color(0, 0, 0), //65536
sf::Color(0, 0, 0), //131072
};
const sf::Color FG_COLORS[] =
{
sf::Color(205, 192, 180), //empty
sf::Color(119, 110, 101), //2
sf::Color(119, 110, 101), //4
sf::Color(255, 255, 255), //8
sf::Color(255, 255, 255), //16
sf::Color(255, 255, 255), //32
sf::Color(255, 255, 255), //64
sf::Color(255, 255, 255), //128
sf::Color(255, 255, 255), //256
sf::Color(255, 255, 255), //512
sf::Color(255, 255, 255), //1024
sf::Color(255, 255, 255), //2048
sf::Color(255, 255, 255), //4096
sf::Color(255, 255, 255), //8192
sf::Color(255, 255, 255), //16384
sf::Color(255, 255, 255), //32768
sf::Color(255, 255, 255), //65536
sf::Color(255, 255, 255), //131072
};
int pow2(int n)
{
int res = 1;
for (int i = 0; i < n; ++i)
res *= 2;
return res;
}
static const std::string GRID_LABELS[] =
{
" ",
" 2 ",
" 4 ",
" 8 ",
" 16 ",
" 32 ",
" 64 ",
" 128 ",
" 256 ",
" 512 ",
"1024 ",
"2048 ",
"4096 ",
"8192 ",
"16384",
"32768",
};
static const char* GRID_FGS[] =
{
Shell::FG_DEFAULT,
Shell::FG_BLACK,
Shell::FG_BLACK,
Shell::FG_BLACK,
Shell::FG_BLACK,
Shell::FG_BLACK,
Shell::FG_BLACK,
Shell::FG_BLACK,
Shell::FG_BLACK,
Shell::FG_BLACK,
Shell::FG_BLACK,
Shell::FG_BLACK,
Shell::FG_WHITE,
Shell::FG_WHITE,
Shell::FG_WHITE,
Shell::FG_WHITE,
};
static const char* GRID_BGS[] =
{
Shell::BG_DEFAULT,
Shell::BG_LGRAY,
Shell::BG_DGRAY,
Shell::BG_LGREEN,
Shell::BG_GREEN,
Shell::BG_LYELLOW,
Shell::BG_YELLOW,
Shell::BG_LRED,
Shell::BG_RED,
Shell::BG_LMAGENTA,
Shell::BG_MAGENTA,
Shell::BG_BLUE,
Shell::BG_BLACK,
Shell::BG_BLACK,
Shell::BG_BLACK,
Shell::BG_BLACK
};
}
namespace to48 {
void World::serialize_actions(const std::vector<int>& actions,
std::ostream& os)
{
os << actions[0] << " " << actions[1] << std::endl;
os << actions[2] << " " << actions[3] << std::endl;
for (std::size_t i = 4; i < actions.size(); i += 3)
os << actions[i] << " " << actions[i + 1] << " " << actions[i + 2] << std::endl;
}
std::vector<int> World::unserialize_actions(std::istream& is)
{
std::vector<int> res;
while (!is.eof())
{
int val;
is >> val;
res.push_back(val);
}
if ((res.size() - 4) % 3 * 3 != res.size() - 4)
res.pop_back();
return res;
}
World::World(std::size_t size)
: size_(size), score_(0), data_(size_ * size_, 0)
{
assert(size_ >= 2);
font_.loadFromFile("../misc/courier.ttf");
reset();
}
std::size_t World::size_get() const
{
return size_;
}
long World::delta_get() const
{
return delta_;
}
const std::vector<int>& World::actions_get() const
{
return actions_;
}
int World::cell_get(std::size_t row, std::size_t col) const
{
assert(row < size_);
assert(col < size_);
return data_[row * size_ + col];
}
int World::cell_get(std::size_t pos) const
{
assert(pos < size_ * size_);
return data_[pos];
}
void World::cell_set(std::size_t row, std::size_t col, int val)
{
assert(row < size_);
assert(col < size_);
data_[row * size_ + col] = val;
}
void World::cell_set(std::size_t pos, int val)
{
assert(pos < size_ * size_);
data_[pos] = val;
}
std::size_t World::score_get() const
{
return score_;
}
void World::score_set(std::size_t score)
{
score_ = score;
}
void World::delta_set(long delta)
{
delta_ = delta;
}
void World::reset()
{
std::fill(data_.begin(), data_.end(), 0);
score_ = 0;
delta_ = 0;
actions_.clear();
}
void World::add_rand()
{
int val = 1 + (rand_.int32_get() % 10) / 9;
int pos;
while (true)
{
pos = rand_.int32_get() % (size_ * size_);
if (data_[pos])
continue;
data_[pos] = val;
break;
}
actions_.push_back(pos);
actions_.push_back(val);
}
void World::add_num(std::size_t pos, int val)
{
assert(pos < size_ * size_);
data_[pos] = val;
actions_.push_back(pos);
actions_.push_back(val);
}
void World::render_gui()
{
auto& win = SfApp::instance();
if (!win.isOpen())
win.create(sf::VideoMode(800, 800), "2048");
int n = size_;
int square_size = GRID_SIZE / n;
int grid_size = square_size * n;
win.poll_events();
win.clear(sf::Color::White);
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) {
int val = cell_get(i, j);
int x = MARGIN + j * square_size;
int y = MARGIN + i * square_size;
win.fill_rect(x, y, square_size, square_size,
BG_COLORS[val]);
sf::Text text;
text.setFont(font_);
text.setString(std::to_string(pow2(val)));
text.setCharacterSize(FONT_SIZE / n);
text.setFillColor(FG_COLORS[val]);
auto size = text.getLocalBounds();
text.setPosition(x + (square_size - size.width) / 2,
y + (square_size - size.height) / 2);
win.draw(text);
}
for (int i = 0; i <= n; ++i) {
win.draw_line(MARGIN, MARGIN + square_size * i,
MARGIN + grid_size, MARGIN + square_size * i,
BORDER_COLOR);
win.draw_line(MARGIN + square_size * i, MARGIN,
MARGIN + square_size * i, MARGIN + grid_size,
BORDER_COLOR);
}
sf::Text score_text;
score_text.setFont(font_);
score_text.setString("score: " + std::to_string(score_));
score_text.setCharacterSize(FONT_SIZE / 6);
score_text.setFillColor(sf::Color::Black);
score_text.setPosition(MARGIN, MARGIN + grid_size + 1 * square_size / 4);
win.draw(score_text);
sf::Text delta_text;
delta_text.setFont(font_);
delta_text.setString("delta: " + std::to_string(delta_));
delta_text.setCharacterSize(FONT_SIZE / 6);
delta_text.setFillColor(sf::Color::Black);
delta_text.setPosition(MARGIN, MARGIN + grid_size + 1 * square_size / 2);
win.draw(delta_text);
win.display();
}
void World::render_cli()
{
auto& cvs = ShellCanvas::instance();
cvs.clear();
cvs.draw_string(0, 0, "Delta: " + std::to_string(delta_));
cvs.draw_string(0, 1, "Score: " + std::to_string(score_));
Grid res(size_, size_);
for (std::size_t i = 0; i < size_; ++i)
for (std::size_t j = 0; j < size_; ++j)
{
auto val = cell_get(i, j);
res.at(i, j) = GRID_LABELS[val];
res.fg_set(i, j, GRID_FGS[val]);
res.bg_set(i, j, GRID_BGS[val]);
}
cvs.draw_sprite(2, 2, res.to_sprite());
cvs.render();
}
std::size_t World::move_left()
{
std::size_t n = size_;
std::size_t reward = 0;
for (std::size_t i = 0; i < n; ++i)
{
std::size_t level = 0;
bool can_fusion = false;
while (level < n)
{
std::size_t j = level;
while (j < n && cell_get(i, j) == 0)
++j;
if (j == n)
break;
int val = cell_get(i, j);
cell_set(i, j, 0);
if (can_fusion && val == cell_get(i, level - 1))
{
cell_set(i, level - 1, val + 1);
reward += pow2(val + 1);
can_fusion = false;
}
else
{
cell_set(i, level, val);
can_fusion = true;
++level;
}
}
}
return reward;
}
std::size_t World::move_right()
{
/*
flip_();
auto reward = move_left();
flip_();
return reward;
*/
std::size_t n = size_;
std::size_t reward = 0;
for (std::size_t i = 0; i < n; ++i)
{
std::size_t level = n -1;
bool can_fusion = false;
while (level < n)
{
std::size_t j = level;
while (j < n && cell_get(i, j) == 0)
--j;
if (j > n)
break;
int val = cell_get(i, j);
cell_set(i, j, 0);
if (can_fusion && val == cell_get(i, level + 1))
{
cell_set(i, level + 1, val + 1);
reward += pow2(val + 1);
can_fusion = false;
}
else
{
cell_set(i, level, val);
can_fusion = true;
--level;
}
}
}
return reward;
}
std::size_t World::move_up()
{
/*
transpose_();
auto reward = move_left();
transpose_();
return reward;
*/
std::size_t n = size_;
std::size_t reward = 0;
for (std::size_t i = 0; i < n; ++i)
{
std::size_t level = 0;
bool can_fusion = false;
while (level < n)
{
std::size_t j = level;
while (j < n && cell_get(j, i) == 0)
++j;
if (j == n)
break;
int val = cell_get(j, i);
cell_set(j, i, 0);
if (can_fusion && val == cell_get(level - 1, i))
{
cell_set(level - 1, i, val + 1);
reward += pow2(val + 1);
can_fusion = false;
}
else
{
cell_set(level, i, val);
can_fusion = true;
++level;
}
}
}
return reward;
}
std::size_t World::move_down()
{
/*
transpose_();
auto reward = move_right();
transpose_();
return reward;
*/
std::size_t n = size_;
std::size_t reward = 0;
for (std::size_t i = 0; i < n; ++i)
{
std::size_t level = n -1;
bool can_fusion = false;
while (level < n)
{
std::size_t j = level;
while (j < n && cell_get(j, i) == 0)
--j;
if (j > n)
break;
int val = cell_get(j, i);
cell_set(j, i, 0);
if (can_fusion && val == cell_get(level + 1, i))
{
cell_set(level + 1, i, val + 1);
reward += pow2(val + 1);
can_fusion = false;
}
else
{
cell_set(level, i, val);
can_fusion = true;
--level;
}
}
}
return reward;
}
std::size_t World::take_action(action_t action, bool check)
{
assert(action < 4);
if (check)
assert(is_action_valid(action));
std::size_t reward;
if (action == ACTION_LEFT)
reward = move_left();
else if (action == ACTION_RIGHT)
reward = move_right();
else if (action == ACTION_UP)
reward = move_up();
else
reward = move_down();
score_ += reward;
actions_.push_back(action);
return reward;
}
void World::play_actions(const std::vector<int>& actions)
{
reset();
add_num(actions[0], actions[1]);
add_num(actions[2], actions[3]);
for (std::size_t i = 4; i < actions.size(); i += 3)
{
take_action(actions[i]);
add_num(actions[i + 1], actions[i + 2]);
}
}
bool World::is_action_valid(action_t action) const
{
World copy(size_);
std::copy(data_.begin(), data_.end(), copy.data_.begin());
copy.take_action(action, false);
return !std::equal(data_.begin(), data_.end(), copy.data_.begin());
}
bool World::is_finished() const
{
for (action_t a = 0; a < 4; ++a)
if (is_action_valid(a))
return false;
return true;
}
void World::serialize(std::ostream& os) const
{
for (std::size_t i = 0; i < size_ * size_; ++i)
os << cell_get(i) << " ";
os << score_;
}
void World::write_actions(std::ostream& os) const
{
serialize_actions(actions_, os);
}
void World::read_actions(std::istream& is)
{
play_actions(unserialize_actions(is));
}
void World::write_full(std::ostream& os) const
{
World copy(size_);
copy.add_num(actions_[0], actions_[1]);
os << actions_[0] << " " << actions_[1] << std::endl;
copy.serialize(os);
os << std::endl;
copy.add_num(actions_[2], actions_[3]);
os << actions_[2] << " " << actions_[3] << std::endl;
copy.serialize(os);
os << std::endl;
for (std::size_t i = 4; i < actions_.size(); i += 3)
{
copy.take_action(actions_[i]);
copy.add_num(actions_[i + 1], actions_[i + 2]);
os << actions_[i] << " " << actions_[i + 1] << " "
<< actions_[i + 2] << std::endl;
copy.serialize(os);
os << std::endl;
}
}
void World::flip_()
{
std::vector<int> data(size_ * size_);
for (std::size_t i = 0; i < size_; ++i)
for (std::size_t j = 0; j < size_; ++j)
data[i * size_ + j] = data_[i * size_ + size_ - 1 - j];
data_ = data;
}
void World::transpose_()
{
std::vector<int> data(size_ * size_);
for (std::size_t i = 0; i < size_; ++i)
for (std::size_t j = 0; j < size_; ++j)
data[i * size_ + j] = data_[j * size_ + i];
data_ = data;
}
}
| 20.990476 | 85 | 0.547111 | [
"render",
"vector"
] |
12a18cb0ae23278d0d5a3eb595ba2a2b3f5daad2 | 2,632 | cpp | C++ | 17-database-xml/17-7/sqlmodel/mainwindow.cpp | Franklin-Qi/qtcreator-example | 5d573f961c3255fbf740991996f935092cc62018 | [
"MIT"
] | null | null | null | 17-database-xml/17-7/sqlmodel/mainwindow.cpp | Franklin-Qi/qtcreator-example | 5d573f961c3255fbf740991996f935092cc62018 | [
"MIT"
] | null | null | null | 17-database-xml/17-7/sqlmodel/mainwindow.cpp | Franklin-Qi/qtcreator-example | 5d573f961c3255fbf740991996f935092cc62018 | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSqlQueryModel>
#include <QSqlTableModel>
#include <QSqlRelationalTableModel>
#include <QTableView>
#include <QDebug>
#include <QMessageBox>
#include <QSqlError>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
model = new QSqlTableModel(this);
model->setTable("student");
model->select();
// 设置编辑策略
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
ui->tableView->setModel(model);
}
MainWindow::~MainWindow()
{
delete ui;
}
// 提交修改按钮
void MainWindow::on_pushButton_clicked()
{
// 开始事务操作
model->database().transaction();
if (model->submitAll()) {
if(model->database().commit()) // 提交
QMessageBox::information(this, tr("tableModel"),
tr("数据修改成功!"));
} else {
model->database().rollback(); // 回滚
QMessageBox::warning(this, tr("tableModel"),
tr("数据库错误: %1").arg(model->lastError().text()),
QMessageBox::Ok);
}
}
// 撤销修改按钮
void MainWindow::on_pushButton_2_clicked()
{
model->revertAll();
}
// 查询按钮,进行筛选
void MainWindow::on_pushButton_5_clicked()
{
QString name = ui->lineEdit->text();
// 根据姓名进行筛选,一定要使用单引号
model->setFilter(QString("name = '%1'").arg(name));
model->select();
}
// 显示全表按钮
void MainWindow::on_pushButton_6_clicked()
{
model->setTable("student");
model->select();
}
// 按id升序排列按钮
void MainWindow::on_pushButton_7_clicked()
{
//id字段,即第0列,升序排列
model->setSort(0, Qt::AscendingOrder);
model->select();
}
// 按id降序排列按钮
void MainWindow::on_pushButton_8_clicked()
{
model->setSort(0, Qt::DescendingOrder);
model->select();
}
// 删除选中行按钮
void MainWindow::on_pushButton_4_clicked()
{
// 获取选中的行
int curRow = ui->tableView->currentIndex().row();
// 删除该行
model->removeRow(curRow);
int ok = QMessageBox::warning(this,tr("删除当前行!"),
tr("你确定删除当前行吗?"), QMessageBox::Yes, QMessageBox::No);
if(ok == QMessageBox::No)
{ // 如果不删除,则撤销
model->revertAll();
} else { // 否则提交,在数据库中删除该行
model->submitAll();
}
}
// 添加记录按钮
void MainWindow::on_pushButton_3_clicked()
{
// 获得表的行数
int rowNum = model->rowCount();
int id = 10;
// 添加一行
model->insertRow(rowNum);
model->setData(model->index(rowNum, 0), id);
// 可以直接提交
//model->submitAll();
}
| 21.933333 | 88 | 0.580547 | [
"model"
] |
12a48d6dbccbaebea282750c571afcb5f537b246 | 29,827 | cpp | C++ | NSWNGAME/cocos2d/cocos/editor-support/cocostudio/WidgetReader/LayoutReader/LayoutReader.cpp | nomagame/NSWE-GAME | d3be61ef2211dae92ced07b1eaf24fd51db36d87 | [
"MIT"
] | 22 | 2015-04-09T06:45:38.000Z | 2017-10-16T15:45:30.000Z | NSWNGAME/cocos2d/cocos/editor-support/cocostudio/WidgetReader/LayoutReader/LayoutReader.cpp | nomagame/NSWE-GAME | d3be61ef2211dae92ced07b1eaf24fd51db36d87 | [
"MIT"
] | 1 | 2016-09-20T10:54:53.000Z | 2016-09-20T10:54:53.000Z | NSWNGAME/cocos2d/cocos/editor-support/cocostudio/WidgetReader/LayoutReader/LayoutReader.cpp | nomagame/NSWE-GAME | d3be61ef2211dae92ced07b1eaf24fd51db36d87 | [
"MIT"
] | 32 | 2015-01-20T07:58:44.000Z | 2018-08-03T15:12:47.000Z |
#include "LayoutReader.h"
#include "ui/UILayout.h"
#include "cocostudio/CocoLoader.h"
#include "ui/UIScrollView.h"
#include "ui/UIPageView.h"
#include "ui/UIListView.h"
#include "cocostudio/CSParseBinary.pb.h"
#include "tinyxml2/tinyxml2.h"
USING_NS_CC;
using namespace ui;
namespace cocostudio
{
static const char* P_CapInsetsX = "capInsetsX";
static const char* P_CapInsetsY = "capInsetsY";
static const char* P_CapInsetsWidth = "capInsetsWidth";
static const char* P_CapInsetsHeight = "capInsetsHeight";
static const char* P_ClipAble = "clipAble";
static const char* P_BackGroundScale9Enable = "backGroundScale9Enable";
static const char* P_BgColorR = "bgColorR";
static const char* P_BgColorG = "bgColorG";
static const char* P_BgColorB = "bgColorB";
static const char* P_BgStartColorR = "bgStartColorR";
static const char* P_BgStartColorG = "bgStartColorG";
static const char* P_BgStartColorB = "bgStartColorB";
static const char* P_BgEndColorR = "bgEndColorR";
static const char* P_BgEndColorG = "bgEndColorG";
static const char* P_BgEndColorB = "bgEndColorB";
static const char* P_VectorX = "vectorX";
static const char* P_VectorY = "vectorY";
static const char* P_BgColorOpacity = "bgColorOpacity";
static const char* P_ColorType = "colorType";
static const char* P_BackGroundImageData = "backGroundImageData";
static const char* P_LayoutType = "layoutType";
static LayoutReader* instanceLayoutReader = nullptr;
IMPLEMENT_CLASS_WIDGET_READER_INFO(LayoutReader)
LayoutReader::LayoutReader()
{
}
LayoutReader::~LayoutReader()
{
}
LayoutReader* LayoutReader::getInstance()
{
if (!instanceLayoutReader)
{
instanceLayoutReader = new (std::nothrow) LayoutReader();
}
return instanceLayoutReader;
}
void LayoutReader::setPropsFromBinary(cocos2d::ui::Widget *widget, CocoLoader *cocoLoader, stExpCocoNode *cocoNode)
{
WidgetReader::setPropsFromBinary(widget, cocoLoader, cocoNode);
Layout* panel = static_cast<Layout*>(widget);
stExpCocoNode *stChildArray = cocoNode->GetChildArray(cocoLoader);
this->beginSetBasicProperties(widget);
int cr=0, cg = 0, cb = 0;
int scr=0, scg=0, scb=0;
int ecr=0, ecg=0, ecb= 0;
float bgcv1 = 0.0f, bgcv2= 0.0f;
float capsx = 0.0f, capsy = 0.0, capsWidth = 0.0, capsHeight = 0.0f;
Layout::Type layoutType = Layout::Type::ABSOLUTE;
int bgColorOpacity = panel->getBackGroundColorOpacity();
for (int i = 0; i < cocoNode->GetChildNum(); ++i) {
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue(cocoLoader);
//read all basic properties of widget
CC_BASIC_PROPERTY_BINARY_READER
//read all color related properties of widget
CC_COLOR_PROPERTY_BINARY_READER
else if(key == P_AdaptScreen){
_isAdaptScreen = valueToBool(value);
}
else if( key == P_ClipAble){
panel->setClippingEnabled(valueToBool(value));
}else if(key == P_BackGroundScale9Enable){
panel->setBackGroundImageScale9Enabled(valueToBool(value));
}else if(key == P_BgColorR){
cr = valueToInt(value);
}else if(key == P_BgColorG){
cg = valueToInt(value);
}else if(key == P_BgColorB)
{
cb = valueToInt(value);
}else if(key == P_BgStartColorR){
scr = valueToInt(value);
}else if(key == P_BgStartColorG){
scg = valueToInt(value);
}else if(key == P_BgStartColorB)
{
scb = valueToInt(value);
}
else if(key == P_BgEndColorR){
ecr = valueToInt(value);
}else if(key == P_BgEndColorG){
ecg = valueToInt(value);
}else if(key == P_BgEndColorB)
{
ecb = valueToInt(value);
}else if (key == P_VectorX){
bgcv1 = valueToFloat(value);
}else if(key == P_VectorY){
bgcv2 = valueToFloat(value);
}else if(key == P_BgColorOpacity){
bgColorOpacity = valueToInt(value);
}else if( key == P_ColorType){
panel->setBackGroundColorType(Layout::BackGroundColorType(valueToInt(value)));
}else if (key == P_BackGroundImageData){
stExpCocoNode *backGroundChildren = stChildArray[i].GetChildArray(cocoLoader);
if (backGroundChildren) {
std::string resType = backGroundChildren[2].GetValue(cocoLoader);;
Widget::TextureResType imageFileNameType = (Widget::TextureResType)valueToInt(resType);
std::string backgroundValue = this->getResourcePath(cocoLoader, &stChildArray[i], imageFileNameType);
panel->setBackGroundImage(backgroundValue, imageFileNameType);
}
}else if(key == P_CapInsetsX){
capsx = valueToFloat(value);
}else if(key == P_CapInsetsY){
capsy = valueToFloat(value);
}else if(key == P_CapInsetsWidth){
capsWidth = valueToFloat(value);
}else if(key == P_CapInsetsHeight){
capsHeight = valueToFloat(value);
}else if (key == P_LayoutType){
layoutType = (Layout::Type)valueToInt(value);
}
}
panel->setBackGroundColor(Color3B(scr, scg, scb),Color3B(ecr, ecg, ecb));
panel->setBackGroundColor(Color3B(cr, cg, cb));
panel->setBackGroundColorVector(Vec2(bgcv1, bgcv2));
panel->setBackGroundColorOpacity(bgColorOpacity);
panel->setBackGroundImageColor(Color3B(_color.r, _color.g, _color.b));
panel->setBackGroundImageOpacity(_opacity);
if (panel->isBackGroundImageScale9Enabled()) {
panel->setBackGroundImageCapInsets(Rect(capsx, capsy, capsWidth, capsHeight));
}
panel->setLayoutType(layoutType);
this->endSetBasicProperties(widget);
}
void LayoutReader::setPropsFromJsonDictionary(Widget *widget, const rapidjson::Value &options)
{
WidgetReader::setPropsFromJsonDictionary(widget, options);
Layout* panel = static_cast<Layout*>(widget);
/* adapt screen gui */
float w = 0, h = 0;
bool adaptScrenn = DICTOOL->getBooleanValue_json(options, P_AdaptScreen);
if (adaptScrenn)
{
Size screenSize = CCDirector::getInstance()->getWinSize();
w = screenSize.width;
h = screenSize.height;
}
else
{
w = DICTOOL->getFloatValue_json(options, P_Width);
h = DICTOOL->getFloatValue_json(options, P_Height);
}
panel->setContentSize(Size(w, h));
/**/
panel->setClippingEnabled(DICTOOL->getBooleanValue_json(options, P_ClipAble));
bool backGroundScale9Enable = DICTOOL->getBooleanValue_json(options, P_BackGroundScale9Enable);
panel->setBackGroundImageScale9Enabled(backGroundScale9Enable);
int cr;
int cg;
int cb;
int scr;
int scg;
int scb;
int ecr;
int ecg;
int ecb;
if (dynamic_cast<ui::PageView*>(widget)) {
cr = DICTOOL->getIntValue_json(options, P_BgColorR,150);
cg = DICTOOL->getIntValue_json(options, P_BgColorG,150);
cb = DICTOOL->getIntValue_json(options, P_BgColorB,100);
scr = DICTOOL->getIntValue_json(options, P_BgStartColorR,255);
scg = DICTOOL->getIntValue_json(options, P_BgStartColorG,255);
scb = DICTOOL->getIntValue_json(options, P_BgStartColorB,255);
ecr = DICTOOL->getIntValue_json(options, P_BgEndColorR,255);
ecg = DICTOOL->getIntValue_json(options, P_BgEndColorG,150);
ecb = DICTOOL->getIntValue_json(options, P_BgEndColorB,100);
}else if(dynamic_cast<ui::ListView*>(widget)){
cr = DICTOOL->getIntValue_json(options, P_BgColorR,150);
cg = DICTOOL->getIntValue_json(options, P_BgColorG,150);
cb = DICTOOL->getIntValue_json(options, P_BgColorB,255);
scr = DICTOOL->getIntValue_json(options, P_BgStartColorR,255);
scg = DICTOOL->getIntValue_json(options, P_BgStartColorG,255);
scb = DICTOOL->getIntValue_json(options, P_BgStartColorB,255);
ecr = DICTOOL->getIntValue_json(options, P_BgEndColorR,150);
ecg = DICTOOL->getIntValue_json(options, P_BgEndColorG,150);
ecb = DICTOOL->getIntValue_json(options, P_BgEndColorB,255);
}else if(dynamic_cast<ui::ScrollView*>(widget)){
cr = DICTOOL->getIntValue_json(options, P_BgColorR,255);
cg = DICTOOL->getIntValue_json(options, P_BgColorG,150);
cb = DICTOOL->getIntValue_json(options, P_BgColorB,100);
scr = DICTOOL->getIntValue_json(options, P_BgStartColorR,255);
scg = DICTOOL->getIntValue_json(options, P_BgStartColorG,255);
scb = DICTOOL->getIntValue_json(options, P_BgStartColorB,255);
ecr = DICTOOL->getIntValue_json(options, P_BgEndColorR,255);
ecg = DICTOOL->getIntValue_json(options, P_BgEndColorG,150);
ecb = DICTOOL->getIntValue_json(options, P_BgEndColorB,100);
}else{
cr = DICTOOL->getIntValue_json(options, P_BgColorR,150);
cg = DICTOOL->getIntValue_json(options, P_BgColorG,200);
cb = DICTOOL->getIntValue_json(options, P_BgColorB,255);
scr = DICTOOL->getIntValue_json(options, P_BgStartColorR,255);
scg = DICTOOL->getIntValue_json(options, P_BgStartColorG,255);
scb = DICTOOL->getIntValue_json(options, P_BgStartColorB,255);
ecr = DICTOOL->getIntValue_json(options, P_BgEndColorR,150);
ecg = DICTOOL->getIntValue_json(options, P_BgEndColorG,200);
ecb = DICTOOL->getIntValue_json(options, P_BgEndColorB,255);
}
float bgcv1 = DICTOOL->getFloatValue_json(options, P_VectorX);
float bgcv2 = DICTOOL->getFloatValue_json(options, P_VectorY,-0.5);
panel->setBackGroundColorVector(Vec2(bgcv1, bgcv2));
int co = DICTOOL->getIntValue_json(options, P_BgColorOpacity,100);
int colorType = DICTOOL->getIntValue_json(options, P_ColorType,1);
panel->setBackGroundColorType(Layout::BackGroundColorType(colorType));
panel->setBackGroundColor(Color3B(scr, scg, scb),Color3B(ecr, ecg, ecb));
panel->setBackGroundColor(Color3B(cr, cg, cb));
panel->setBackGroundColorOpacity(co);
const rapidjson::Value& imageFileNameDic = DICTOOL->getSubDictionary_json(options, P_BackGroundImageData);
int imageFileNameType = DICTOOL->getIntValue_json(imageFileNameDic, P_ResourceType);
std::string imageFileName = this->getResourcePath(imageFileNameDic, P_Path, (Widget::TextureResType)imageFileNameType);
panel->setBackGroundImage(imageFileName, (Widget::TextureResType)imageFileNameType);
if (backGroundScale9Enable)
{
float cx = DICTOOL->getFloatValue_json(options, P_CapInsetsX);
float cy = DICTOOL->getFloatValue_json(options, P_CapInsetsY);
float cw = DICTOOL->getFloatValue_json(options, P_CapInsetsWidth,1);
float ch = DICTOOL->getFloatValue_json(options, P_CapInsetsHeight,1);
panel->setBackGroundImageCapInsets(Rect(cx, cy, cw, ch));
}
panel->setLayoutType((Layout::Type)DICTOOL->getIntValue_json(options, P_LayoutType));
int bgimgcr = DICTOOL->getIntValue_json(options, P_ColorR,255);
int bgimgcg = DICTOOL->getIntValue_json(options, P_ColorG,255);
int bgimgcb = DICTOOL->getIntValue_json(options, P_ColorB,255);
panel->setBackGroundImageColor(Color3B(bgimgcr, bgimgcg, bgimgcb));
int bgimgopacity = DICTOOL->getIntValue_json(options, P_Opacity, 255);
panel->setBackGroundImageOpacity(bgimgopacity);
WidgetReader::setColorPropsFromJsonDictionary(widget, options);
}
void LayoutReader::setPropsFromProtocolBuffers(ui::Widget *widget, const protocolbuffers::NodeTree &nodeTree)
{
WidgetReader::setPropsFromProtocolBuffers(widget, nodeTree);
Layout* panel = static_cast<Layout*>(widget);
const protocolbuffers::PanelOptions& options = nodeTree.paneloptions();
std::string protocolBuffersPath = GUIReader::getInstance()->getFilePath();
panel->setClippingEnabled(options.clipable());
bool backGroundScale9Enable = options.backgroundscale9enable();
panel->setBackGroundImageScale9Enabled(backGroundScale9Enable);
int cr;
int cg;
int cb;
int scr;
int scg;
int scb;
int ecr;
int ecg;
int ecb;
if (dynamic_cast<ui::PageView*>(widget))
{
cr = options.has_bgcolorr() ? options.bgcolorr() : 150;
cg = options.has_bgcolorg() ? options.bgcolorg() : 150;
cb = options.has_bgcolorb() ? options.bgcolorb() : 150;
scr = options.has_bgstartcolorr() ? options.bgstartcolorr() : 255;
scg = options.has_bgstartcolorg() ? options.bgstartcolorg() : 255;
scb = options.has_bgstartcolorb() ? options.bgstartcolorb() : 255;
ecr = options.has_bgendcolorr() ? options.bgendcolorr() : 255;
ecg = options.has_bgendcolorg() ? options.bgendcolorg() : 150;
ecb = options.has_bgendcolorb() ? options.bgendcolorb() : 100;
}
else if(dynamic_cast<ui::ListView*>(widget))
{
cr = options.has_bgcolorr() ? options.bgcolorr() : 150;
cg = options.has_bgcolorg() ? options.bgcolorg() : 150;
cb = options.has_bgcolorb() ? options.bgcolorb() : 255;
scr = options.has_bgstartcolorr() ? options.bgstartcolorr() : 255;
scg = options.has_bgstartcolorg() ? options.bgstartcolorg() : 255;
scb = options.has_bgstartcolorb() ? options.bgstartcolorb() : 255;
ecr = options.has_bgendcolorr() ? options.bgendcolorr() : 150;
ecg = options.has_bgendcolorg() ? options.bgendcolorg() : 150;
ecb = options.has_bgendcolorb() ? options.bgendcolorb() : 255;
}
else if(dynamic_cast<ui::ScrollView*>(widget))
{
cr = options.has_bgcolorr() ? options.bgcolorr() : 255;
cg = options.has_bgcolorg() ? options.bgcolorg() : 150;
cb = options.has_bgcolorb() ? options.bgcolorb() : 100;
scr = options.has_bgstartcolorr() ? options.bgstartcolorr() : 255;
scg = options.has_bgstartcolorg() ? options.bgstartcolorg() : 255;
scb = options.has_bgstartcolorb() ? options.bgstartcolorb() : 255;
ecr = options.has_bgendcolorr() ? options.bgendcolorr() : 255;
ecg = options.has_bgendcolorg() ? options.bgendcolorg() : 150;
ecb = options.has_bgendcolorb() ? options.bgendcolorb() : 100;
}
else
{
cr = options.has_bgcolorr() ? options.bgcolorr() : 150;
cg = options.has_bgcolorg() ? options.bgcolorg() : 200;
cb = options.has_bgcolorb() ? options.bgcolorb() : 255;
scr = options.has_bgstartcolorr() ? options.bgstartcolorr() : 255;
scg = options.has_bgstartcolorg() ? options.bgstartcolorg() : 255;
scb = options.has_bgstartcolorb() ? options.bgstartcolorb() : 255;
ecr = options.has_bgendcolorr() ? options.bgendcolorr() : 150;
ecg = options.has_bgendcolorg() ? options.bgendcolorg() : 200;
ecb = options.has_bgendcolorb() ? options.bgendcolorb() : 255;
}
float bgcv1 = 0.0f;
float bgcv2 = -0.5f;
if(options.has_vectorx())
{
bgcv1 = options.vectorx();
}
if(options.has_vectory())
{
bgcv2 = options.vectory();
}
panel->setBackGroundColorVector(Vec2(bgcv1, bgcv2));
int co = options.has_bgcoloropacity() ? options.bgcoloropacity() : 100;
int colorType = options.has_colortype() ? options.colortype() : 1;
panel->setBackGroundColorType(Layout::BackGroundColorType(colorType));
panel->setBackGroundColor(Color3B(scr, scg, scb),Color3B(ecr, ecg, ecb));
panel->setBackGroundColor(Color3B(cr, cg, cb));
panel->setBackGroundColorOpacity(co);
const protocolbuffers::ResourceData& imageFileNameDic = options.backgroundimagedata();
int imageFileNameType = imageFileNameDic.resourcetype();
std::string imageFileName = this->getResourcePath(imageFileNameDic.path(), (Widget::TextureResType)imageFileNameType);
panel->setBackGroundImage(imageFileName, (Widget::TextureResType)imageFileNameType);
if (backGroundScale9Enable)
{
float cx = options.capinsetsx();
float cy = options.capinsetsy();
float cw = options.has_capinsetswidth() ? options.capinsetswidth() : 1;
float ch = options.has_capinsetsheight() ? options.capinsetsheight() : 1;
panel->setBackGroundImageCapInsets(Rect(cx, cy, cw, ch));
bool sw = options.has_scale9width();
bool sh = options.has_scale9height();
if (sw && sh)
{
float swf = options.scale9width();
float shf = options.scale9height();
panel->setContentSize(Size(swf, shf));
}
}
panel->setLayoutType((Layout::Type)options.layouttype());
const protocolbuffers::WidgetOptions& widgetOptions = nodeTree.widgetoptions();
int red = widgetOptions.has_colorr() ? widgetOptions.colorr() : 255;
int green = widgetOptions.has_colorg() ? widgetOptions.colorg() : 255;
int blue = widgetOptions.has_colorb() ? widgetOptions.colorb() : 255;
panel->setColor(Color3B(red, green, blue));
int opacity = widgetOptions.has_alpha() ? widgetOptions.alpha() : 255;
panel->setOpacity(opacity);
// other commonly protperties
setAnchorPointForWidget(widget, nodeTree);
bool flipX = widgetOptions.flipx();
bool flipY = widgetOptions.flipy();
if (flipX)
{
widget->setFlippedX(flipX);
}
if (flipY)
{
widget->setFlippedY(flipY);
}
}
void LayoutReader::setPropsFromXML(cocos2d::ui::Widget *widget, const tinyxml2::XMLElement *objectData)
{
WidgetReader::setPropsFromXML(widget, objectData);
Layout* panel = static_cast<Layout*>(widget);
std::string xmlPath = GUIReader::getInstance()->getFilePath();
bool scale9Enabled = false;
float width = 0.0f, height = 0.0f;
float cx = 0.0f, cy = 0.0f, cw = 0.0f, ch = 0.0f;
Layout::BackGroundColorType colorType = Layout::BackGroundColorType::NONE;
int color_opacity = 255, bgimg_opacity = 255, opacity = 255;
int red = 255, green = 255, blue = 255;
int bgimg_red = 255, bgimg_green = 255, bgimg_blue = 255;
int singleRed = 255, singleGreen = 255, singleBlue = 255;
int start_red = 255, start_green = 255, start_blue = 255;
int end_red = 255, end_green = 255, end_blue = 255;
float vector_color_x = 0.0f, vector_color_y = -0.5f;
int resourceType = 0;
std::string path = "", plistFile = "";
// attributes
const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute();
while (attribute)
{
std::string name = attribute->Name();
std::string value = attribute->Value();
if (name == "ClipAble")
{
panel->setClippingEnabled((value == "True") ? true : false);
}
else if (name == "ComboBoxIndex")
{
colorType = (Layout::BackGroundColorType)atoi(value.c_str());
}
else if (name == "BackColorAlpha")
{
color_opacity = atoi(value.c_str());
}
else if (name == "Alpha")
{
opacity = atoi(value.c_str());
bgimg_opacity = atoi(value.c_str());
}
else if (name == "Scale9Enable")
{
scale9Enabled = (value == "True") ? true : false;
}
else if (name == "Scale9OriginX")
{
cx = atof(value.c_str());
}
else if (name == "Scale9OriginY")
{
cy = atof(value.c_str());
}
else if (name == "Scale9Width")
{
cw = atof(value.c_str());
}
else if (name == "Scale9Height")
{
ch = atof(value.c_str());
}
attribute = attribute->Next();
}
// child elements
const tinyxml2::XMLElement* child = objectData->FirstChildElement();
while (child)
{
std::string name = child->Name();
if (name == "Size")
{
attribute = child->FirstAttribute();
while (attribute)
{
name = attribute->Name();
std::string value = attribute->Value();
if (name == "X")
{
width = atof(value.c_str());
}
else if (name == "Y")
{
height = atof(value.c_str());
}
attribute = attribute->Next();
}
}
else if (name == "CColor")
{
attribute = child->FirstAttribute();
while (attribute)
{
name = attribute->Name();
std::string value = attribute->Value();
if (name == "R")
{
red = atoi(value.c_str());
bgimg_red = atoi(value.c_str());
}
else if (name == "G")
{
green = atoi(value.c_str());
bgimg_green = atoi(value.c_str());
}
else if (name == "B")
{
blue = atoi(value.c_str());
bgimg_blue = atoi(value.c_str());
}
attribute = attribute->Next();
}
}
else if (name == "SingleColor")
{
attribute = child->FirstAttribute();
while (attribute)
{
name = attribute->Name();
std::string value = attribute->Value();
if (name == "R")
{
singleRed = atoi(value.c_str());
}
else if (name == "G")
{
singleGreen = atoi(value.c_str());
}
else if (name == "B")
{
singleBlue = atoi(value.c_str());
}
attribute = attribute->Next();
}
}
else if (name == "EndColor")
{
attribute = child->FirstAttribute();
while (attribute)
{
name = attribute->Name();
std::string value = attribute->Value();
if (name == "R")
{
end_red = atoi(value.c_str());
}
else if (name == "G")
{
end_green = atoi(value.c_str());
}
else if (name == "B")
{
end_blue = atoi(value.c_str());
}
attribute = attribute->Next();
}
}
else if (name == "FirstColor")
{
attribute = child->FirstAttribute();
while (attribute)
{
name = attribute->Name();
std::string value = attribute->Value();
if (name == "R")
{
start_red = atoi(value.c_str());
}
else if (name == "G")
{
start_green = atoi(value.c_str());
}
else if (name == "B")
{
start_blue = atoi(value.c_str());
}
attribute = attribute->Next();
}
}
else if (name == "ColorVector")
{
attribute = child->FirstAttribute();
while (attribute)
{
name = attribute->Name();
std::string value = attribute->Value();
if (name == "ScaleX")
{
vector_color_x = atof(value.c_str());
}
else if (name == "ScaleY")
{
vector_color_y = atof(value.c_str());
}
attribute = attribute->Next();
}
}
else if (name == "FileData")
{
attribute = child->FirstAttribute();
while (attribute)
{
name = attribute->Name();
std::string value = attribute->Value();
if (name == "Path")
{
path = value;
}
else if (name == "Type")
{
resourceType = (value == "Normal" || value == "Default" || value == "MarkedSubImage") ? 0 : 1;
}
else if (name == "Plist")
{
plistFile = value;
}
attribute = attribute->Next();
}
}
child = child->NextSiblingElement();
}
panel->setBackGroundColorType(colorType);
switch (colorType)
{
case Layout::BackGroundColorType::SOLID:
panel->setBackGroundColor(Color3B(singleRed, singleGreen, singleBlue));
break;
case Layout::BackGroundColorType::GRADIENT:
panel->setBackGroundColor(Color3B(start_red, start_green, start_blue),
Color3B(end_red, end_green, end_blue));
panel->setBackGroundColorVector(Vec2(vector_color_x, vector_color_y));
break;
default:
break;
}
panel->setColor(Color3B(red, green, blue));
panel->setOpacity(opacity);
panel->setBackGroundColorOpacity(color_opacity);
switch (resourceType)
{
case 0:
{
panel->setBackGroundImage(xmlPath + path, Widget::TextureResType::LOCAL);
break;
}
case 1:
{
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(xmlPath + plistFile);
panel->setBackGroundImage(path, Widget::TextureResType::PLIST);
break;
}
default:
break;
}
if (path != "")
{
if (scale9Enabled)
{
panel->setBackGroundImageScale9Enabled(scale9Enabled);
panel->setBackGroundImageCapInsets(Rect(cx, cy, cw, ch));
panel->setContentSize(Size(width, height));
}
}
}
}
| 38.887875 | 127 | 0.523117 | [
"solid"
] |
12a6fb2fdef3b8b1890a973d30f158c14ca54638 | 7,118 | cpp | C++ | mpcplus/src/lyrics_fetcher.cpp | doctorfree/mpcplus | 405b62179871cdb8a708b592fdda7c0af378953a | [
"MIT"
] | 1 | 2022-03-30T22:00:36.000Z | 2022-03-30T22:00:36.000Z | mpcplus/src/lyrics_fetcher.cpp | doctorfree/mpcplus | 405b62179871cdb8a708b592fdda7c0af378953a | [
"MIT"
] | null | null | null | mpcplus/src/lyrics_fetcher.cpp | doctorfree/mpcplus | 405b62179871cdb8a708b592fdda7c0af378953a | [
"MIT"
] | null | null | null | /***************************************************************************
* Copyright (C) 2008-2021 by Andrzej Rybczak *
* andrzej@rybczak.net *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#include "config.h"
#include "curl_handle.h"
#include <cstdlib>
#include <cstring>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/regex.hpp>
#include "charset.h"
#include "lyrics_fetcher.h"
#include "utility/html.h"
#include "utility/string.h"
std::istream &operator>>(std::istream &is, LyricsFetcher_ &fetcher)
{
std::string s;
is >> s;
if (s == "azlyrics")
fetcher = std::make_unique<AzLyricsFetcher>();
else if (s == "genius")
fetcher = std::make_unique<GeniusFetcher>();
else if (s == "musixmatch")
fetcher = std::make_unique<MusixmatchFetcher>();
else if (s == "sing365")
fetcher = std::make_unique<Sing365Fetcher>();
else if (s == "metrolyrics")
fetcher = std::make_unique<MetrolyricsFetcher>();
else if (s == "justsomelyrics")
fetcher = std::make_unique<JustSomeLyricsFetcher>();
else if (s == "jahlyrics")
fetcher = std::make_unique<JahLyricsFetcher>();
else if (s == "plyrics")
fetcher = std::make_unique<PLyricsFetcher>();
else if (s == "tekstowo")
fetcher = std::make_unique<TekstowoFetcher>();
else if (s == "zeneszoveg")
fetcher = std::make_unique<ZeneszovegFetcher>();
else if (s == "internet")
fetcher = std::make_unique<InternetLyricsFetcher>();
else
is.setstate(std::ios::failbit);
return is;
}
const char LyricsFetcher::msgNotFound[] = "Not found";
LyricsFetcher::Result LyricsFetcher::fetch(const std::string &artist,
const std::string &title)
{
Result result;
result.first = false;
std::string url = urlTemplate();
boost::replace_all(url, "%artist%", Curl::escape(artist));
boost::replace_all(url, "%title%", Curl::escape(title));
std::string data;
CURLcode code = Curl::perform(data, url, "", true);
if (code != CURLE_OK)
{
result.second = curl_easy_strerror(code);
return result;
}
auto lyrics = getContent(regex(), data);
if (lyrics.empty() || notLyrics(data))
{
//std::cerr << "Data: " << data << "\n";
//std::cerr << "Empty: " << lyrics.empty() << "\n";
//std::cerr << "Not Lyrics: " << notLyrics(data) << "\n";
result.second = msgNotFound;
return result;
}
data.clear();
for (auto it = lyrics.begin(); it != lyrics.end(); ++it)
{
postProcess(*it);
if (!it->empty())
{
data += *it;
if (it != lyrics.end() - 1)
data += "\n\n";
}
}
result.second = data;
result.first = true;
return result;
}
std::vector<std::string> LyricsFetcher::getContent(const char *regex_,
const std::string &data)
{
std::vector<std::string> result;
boost::regex rx(regex_);
auto first = boost::sregex_iterator(data.begin(), data.end(), rx);
auto last = boost::sregex_iterator();
for (; first != last; ++first)
{
std::string content;
for (size_t i = 1; i < first->size(); ++i)
content += first->str(i);
result.push_back(std::move(content));
}
return result;
}
void LyricsFetcher::postProcess(std::string &data) const
{
data = unescapeHtmlUtf8(data);
stripHtmlTags(data);
// Remove indentation from each line and collapse multiple newlines into one.
std::vector<std::string> lines;
boost::split(lines, data, boost::is_any_of("\n"));
for (auto &line : lines)
boost::trim(line);
std::unique(lines.begin(), lines.end(), [](std::string &a, std::string &b) {
return a.empty() && b.empty();
});
data = boost::algorithm::join(lines, "\n");
boost::trim(data);
}
/**********************************************************************/
LyricsFetcher::Result GoogleLyricsFetcher::fetch(const std::string &artist,
const std::string &title)
{
Result result;
result.first = false;
std::string search_str;
if (siteKeyword() != nullptr)
{
search_str += "site:";
search_str += Curl::escape(siteKeyword());
}
else
search_str = "lyrics";
search_str += "+";
search_str += Curl::escape(artist);
search_str += "+";
search_str += Curl::escape(title);
std::string google_url = "http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-8&q=";
google_url += search_str;
google_url += "&btnI=I%27m+Feeling+Lucky";
std::string data;
CURLcode code = Curl::perform(data, google_url, google_url);
if (code != CURLE_OK)
{
result.second = curl_easy_strerror(code);
return result;
}
auto urls = getContent("<A HREF=\"http://www.google.com/url\\?q=(.*?)\">here</A>", data);
if (urls.empty() || !isURLOk(urls[0]))
{
result.second = msgNotFound;
return result;
}
data = unescapeHtmlUtf8(urls[0]);
URL = data.c_str();
return LyricsFetcher::fetch("", "");
}
bool GoogleLyricsFetcher::isURLOk(const std::string &url)
{
return url.find(siteKeyword()) != std::string::npos;
}
/**********************************************************************/
bool MetrolyricsFetcher::isURLOk(const std::string &url)
{
// it sometimes return link to sitemap.xml, which is huge so we need to discard it
return GoogleLyricsFetcher::isURLOk(url) && url.find("sitemap") == std::string::npos;
}
/**********************************************************************/
LyricsFetcher::Result InternetLyricsFetcher::fetch(const std::string &artist,
const std::string &title)
{
GoogleLyricsFetcher::fetch(artist, title);
LyricsFetcher::Result result;
result.first = false;
result.second = "The following site may contain lyrics for this song: ";
result.second += URL;
return result;
}
bool InternetLyricsFetcher::isURLOk(const std::string &url)
{
URL = url;
return false;
}
| 31.082969 | 90 | 0.577409 | [
"vector"
] |
12a9e30aa16f375d947b1e1ea19da8dd80362dc4 | 1,959 | hpp | C++ | src/graphics/image_loader.hpp | mnewhouse/izieditor | 0a7f300737de9ab5a2a9a02c1a8c786083e71054 | [
"MIT"
] | null | null | null | src/graphics/image_loader.hpp | mnewhouse/izieditor | 0a7f300737de9ab5a2a9a02c1a8c786083e71054 | [
"MIT"
] | null | null | null | src/graphics/image_loader.hpp | mnewhouse/izieditor | 0a7f300737de9ab5a2a9a02c1a8c786083e71054 | [
"MIT"
] | null | null | null | /*
* The MIT License (MIT)
*
* IziEditor
* Copyright (c) 2015 Martin Newhouse
*
* 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 IMAGE_LOADER_HPP
#define IMAGE_LOADER_HPP
#include <SFML/Graphics/Image.hpp>
#include <string>
#include <exception>
#include <vector>
#include <unordered_map>
namespace graphics
{
struct ImageLoadError
: std::runtime_error
{
ImageLoadError(std::string file_path);
const std::string& file_path() const;
private:
std::string file_path_;
};
class ImageLoader
{
public:
const sf::Image& load_from_file(const std::string& file_name);
const sf::Image* load_from_file(const std::string& file_name, std::nothrow_t);
private:
const sf::Image* load_from_file_impl(const std::string& file_name);
std::unordered_map<std::string, sf::Image> image_map_;
std::vector<char> file_buffer_;
};
}
#endif | 31.095238 | 86 | 0.722818 | [
"vector"
] |
12aaf0a8fd6359e38298b8622a88b38d9649452f | 6,575 | cpp | C++ | NumberWithUnits.cpp | oz105/Number_with_units-b | b9ca2ea6ef74b7c586b097b0950ee085b5905243 | [
"MIT"
] | null | null | null | NumberWithUnits.cpp | oz105/Number_with_units-b | b9ca2ea6ef74b7c586b097b0950ee085b5905243 | [
"MIT"
] | null | null | null | NumberWithUnits.cpp | oz105/Number_with_units-b | b9ca2ea6ef74b7c586b097b0950ee085b5905243 | [
"MIT"
] | null | null | null | #include <fstream>
#include <sstream>
#include <math.h>
#include "NumberWithUnits.hpp"
using namespace std;
namespace ariel{
static map<string,map <string, double>> unit_map ;
static vector<pair<string,string>> types ;
const float TOLERANCE = 0.001;
const int ZERO = 0 ;
const int ONE = 1 ;
NumberWithUnits::NumberWithUnits(const double& value,const string& type) {
if(unit_map.count(type) != 0) {this->m_value = value; this->m_type = type;}
else {throw invalid_argument {"the unit not in the file"};}
}
void NumberWithUnits::read_units(ifstream& file){
string line;
double num_1 = 0;
double num_2 = 0;
string from;
string to;
string equal ;
while(getline(file, line)){
std::stringstream linestream(line);
linestream >> skipws >> num_1;
linestream >> skipws >> from;
linestream >> skipws >> equal;
if(equal != "="){
throw invalid_argument("wrong format ");
}
linestream >> skipws >> num_2;
linestream >> skipws >> to;
unit_map [from][to] = num_2 ;
unit_map[to][from] = 1/num_2 ;
types.emplace_back(from,to);
types.emplace_back(to,from);
for (auto & ty : types) {
string num_1 = ty.first;
string num_2 = ty.second;
for (auto & curr : unit_map[num_2]) {
string num_3 = curr.first;
if(num_3 == num_1) {continue;}
double update = unit_map[num_2][num_3] * unit_map[num_1][num_2];
unit_map[num_1][num_3] = update ;
unit_map[num_3][num_1] = 1/update;
}
}
}
}
static NumberWithUnits convert_to(const string &from, const string &to, double value){
if(from.empty()||to.empty()){
throw invalid_argument{"cant be empty"} ;
}
if (from == to) {
NumberWithUnits ans(value, from);
return ans ;
}
else{
try
{
double val = unit_map.at(from).at(to) * value ;
NumberWithUnits ans(val, from);
return ans ;
}
catch(const std::exception& e)
{
throw invalid_argument{"Units do not match - ["+from+"]"+" cannot be converted to ["+to+"]"};
}
}
}
NumberWithUnits NumberWithUnits::operator + (const NumberWithUnits& num){
double conv = convert_to(num.m_type,this->m_type,num.m_value).m_value;
return NumberWithUnits {this->m_value + conv , this->m_type};
}
NumberWithUnits & NumberWithUnits::operator += (const NumberWithUnits& num) {
double conv = convert_to(num.m_type,this->m_type,num.m_value).m_value;
this->m_value = this->m_value + conv;
return *this;
}
NumberWithUnits NumberWithUnits::operator - (const NumberWithUnits& num){
double conv= convert_to(num.m_type,this->m_type,num.m_value).m_value;
return NumberWithUnits {this->m_value - conv , this->m_type};
}
NumberWithUnits & NumberWithUnits::operator -= (const NumberWithUnits& num){
double conv = convert_to(num.m_type,this->m_type,num.m_value).m_value;
this->m_value = this->m_value - conv;
return *this;
}
NumberWithUnits operator * (const NumberWithUnits& num, double n){
return NumberWithUnits {num.m_value * n , num.m_type};
}
NumberWithUnits operator * (double n, const NumberWithUnits& num){
return NumberWithUnits {num.m_value * n , num.m_type};
}
bool operator > (const NumberWithUnits &num_1 , const NumberWithUnits& num_2){
double conv = convert_to(num_2.m_type,num_1.m_type,num_2.m_value).m_value;
return (num_1.m_value > conv);
}
bool operator >= (const NumberWithUnits& num_1 , const NumberWithUnits& num_2){
return ((num_1 == num_2) || (num_1 > num_2));
}
bool operator < (const NumberWithUnits& num_1 , const NumberWithUnits& num_2){
double conv = convert_to(num_2.m_type,num_1.m_type,num_2.m_value).m_value;
return (num_1.m_value < conv);
}
bool operator <= (const NumberWithUnits& num_1 , const NumberWithUnits& num_2){
return ((num_1 == num_2) || (num_1 < num_2));
}
bool operator == (const NumberWithUnits& num_1 , const NumberWithUnits& num_2){
double conv = convert_to(num_2.m_type,num_1.m_type,num_2.m_value).m_value;
return (abs(num_1.m_value - conv) <= TOLERANCE);
}
bool operator != (const NumberWithUnits& num_1 , const NumberWithUnits& num_2){
return (!(num_1 == num_2));
}
//Input and Output
ostream& operator<<(std::ostream &os, const NumberWithUnits &num){
os << num.m_value << '[' << num.m_type << ']' ;
return os;
}
istream & operator>>(std::istream &in, NumberWithUnits &num){
string str;
//check input format
getline (in, str,']');
string value;
string type;
uint first = str.find('['); // find the index of first '['
uint end = str.length();
for (uint i = 0; i < first; i++) {
if (str.at(i) == ' ') {} // skip whitespace
else {
value += str.at(i);
}
}
for (uint i = first + 1; i < end; i++) {
if (str.at(i) == ' ') {} // skip whitespace
else {
type += str.at(i);
}
}
num.m_value = stod(value); // stod change string to double https://www.cplusplus.com/reference/string/stod/
num.m_type = type;
if(unit_map.count(num.m_type) != 0){return in;}
throw invalid_argument {"the unit not in the file"};
}
} | 41.352201 | 119 | 0.505703 | [
"vector"
] |
12ac1403f5ffc22933fcc50beeb1a4ac2e436681 | 17,894 | cpp | C++ | B2G/gecko/uriloader/exthandler/os2/nsMIMEInfoOS2.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/uriloader/exthandler/os2/nsMIMEInfoOS2.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/uriloader/exthandler/os2/nsMIMEInfoOS2.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set sw=2 sts=2 et cin: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifdef MOZ_OS2_HIGH_MEMORY
// os2safe.h has to be included before os2.h, needed for high mem
#include <os2safe.h>
#endif
#include "nsMIMEInfoOS2.h"
#include "nsOSHelperAppService.h"
#include "nsExternalHelperAppService.h"
#include "nsCExternalHandlerService.h"
#include "nsReadableUtils.h"
#include "nsIProcess.h"
#include "nsNetUtil.h"
#include "nsDirectoryServiceDefs.h"
#include "nsIVariant.h"
#include "nsArrayEnumerator.h"
#include "nsIRwsService.h"
#include <stdlib.h>
#include "mozilla/Preferences.h"
using namespace mozilla;
//------------------------------------------------------------------------
#define SALT_SIZE 8
#define TABLE_SIZE 36
static const PRUnichar table[] =
{ 'a','b','c','d','e','f','g','h','i','j',
'k','l','m','n','o','p','q','r','s','t',
'u','v','w','x','y','z','0','1','2','3',
'4','5','6','7','8','9'};
// reduces overhead by preventing calls to nsRwsService when it isn't present
static bool sUseRws = true;
//------------------------------------------------------------------------
NS_IMPL_ISUPPORTS_INHERITED1(nsMIMEInfoOS2, nsMIMEInfoBase, nsIPropertyBag)
nsMIMEInfoOS2::~nsMIMEInfoOS2()
{
}
//------------------------------------------------------------------------
// if the helper application is a DOS app, create an 8.3 filename
static nsresult Make8Dot3Name(nsIFile *aFile, nsACString& aPath)
{
nsAutoCString leafName;
aFile->GetNativeLeafName(leafName);
const char *lastDot = strrchr(leafName.get(), '.');
char suffix[8] = "";
if (lastDot) {
strncpy(suffix, lastDot, 4);
suffix[4] = '\0';
}
nsCOMPtr<nsIFile> tempPath;
nsresult rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(tempPath));
NS_ENSURE_SUCCESS(rv, rv);
nsAutoString saltedTempLeafName;
do {
saltedTempLeafName.Truncate();
// this salting code was ripped directly from the profile manager.
// turn PR_Now() into milliseconds since epoch 1058 & salt rand with that
double fpTime;
LL_L2D(fpTime, PR_Now());
srand((uint)(fpTime * 1e-6 + 0.5));
for (int32_t i=0; i < SALT_SIZE; i++)
saltedTempLeafName.Append(table[(rand()%TABLE_SIZE)]);
AppendASCIItoUTF16(suffix, saltedTempLeafName);
rv = aFile->CopyTo(tempPath, saltedTempLeafName);
} while (NS_FAILED(rv));
nsCOMPtr<nsPIExternalAppLauncher>
helperAppService(do_GetService(NS_EXTERNALHELPERAPPSERVICE_CONTRACTID));
if (!helperAppService)
return NS_ERROR_FAILURE;
tempPath->Append(saltedTempLeafName);
helperAppService->DeleteTemporaryFileOnExit(tempPath);
tempPath->GetNativePath(aPath);
return rv;
}
//------------------------------------------------------------------------
// opens a file using the selected program or WPS object
NS_IMETHODIMP nsMIMEInfoOS2::LaunchWithFile(nsIFile *aFile)
{
nsresult rv = NS_OK;
nsCOMPtr<nsIFile> application;
if (mPreferredAction == useHelperApp) {
nsCOMPtr<nsILocalHandlerApp> localHandlerApp =
do_QueryInterface(mPreferredApplication, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = localHandlerApp->GetExecutable(getter_AddRefs(application));
NS_ENSURE_SUCCESS(rv, rv);
} else if (mPreferredAction == useSystemDefault) {
application = mDefaultApplication;
} else {
return NS_ERROR_INVALID_ARG;
}
nsAutoCString filePath;
aFile->GetNativePath(filePath);
// if there's no program, use the WPS to open the file
if (!application) {
rv = NS_ERROR_FAILURE;
// if RWS is enabled, see if nsOSHelperAppService provided a handle for
// the app associated with this file; if so, use it to open the file;
if (sUseRws) {
uint32_t appHandle;
GetDefaultAppHandle(&appHandle);
if (appHandle) {
nsCOMPtr<nsIRwsService> rwsSvc(do_GetService("@mozilla.org/rwsos2;1"));
if (!rwsSvc) {
sUseRws = false;
} else {
// this call is identical to dropping the file on a program's icon;
// it ensures filenames with multiple dots are handled correctly
rv = rwsSvc->OpenWithAppHandle(filePath.get(), appHandle);
}
}
}
// if RWS isn't present or fails, open it using a PM call
if (NS_FAILED(rv)) {
if (WinSetObjectData(WinQueryObject(filePath.get()), "OPEN=DEFAULT"))
rv = NS_OK;
}
return rv;
}
// open the data file using the specified program file
nsAutoCString appPath;
if (application) {
application->GetNativePath(appPath);
}
ULONG ulAppType;
DosQueryAppType(appPath.get(), &ulAppType);
if (ulAppType & (FAPPTYP_DOS |
FAPPTYP_WINDOWSPROT31 |
FAPPTYP_WINDOWSPROT |
FAPPTYP_WINDOWSREAL)) {
rv = Make8Dot3Name(aFile, filePath);
NS_ENSURE_SUCCESS(rv, rv);
}
filePath.Insert('\"', 0);
filePath.Append('\"');
// if RWS is enabled, have the WPS open the file using the selected app;
// this lets the user specify commandline args in the exe's WPS notebook
rv = NS_ERROR_FAILURE;
if (sUseRws) {
nsCOMPtr<nsIRwsService> rwsSvc(do_GetService("@mozilla.org/rwsos2;1"));
if (!rwsSvc) {
sUseRws = false;
} else {
rv = rwsSvc->OpenWithAppPath(filePath.get(), appPath.get());
}
}
// if RWS isn't present or fails, use Moz facilities to run the program
if (NS_FAILED(rv)) {
nsCOMPtr<nsIProcess> process = do_CreateInstance(NS_PROCESS_CONTRACTID);
if (NS_FAILED(rv = process->Init(application)))
return rv;
const char *strPath = filePath.get();
return process->Run(false, &strPath, 1);
}
return rv;
}
//------------------------------------------------------------------------
// if there's a description, there's a handler (which may be the WPS)
NS_IMETHODIMP nsMIMEInfoOS2::GetHasDefaultHandler(bool *_retval)
{
*_retval = !mDefaultAppDescription.IsEmpty();
return NS_OK;
}
//------------------------------------------------------------------------
// copied directly from nsMIMEInfoImpl
NS_IMETHODIMP
nsMIMEInfoOS2::GetDefaultDescription(nsAString& aDefaultDescription)
{
if (mDefaultAppDescription.IsEmpty() && mDefaultApplication)
mDefaultApplication->GetLeafName(aDefaultDescription);
else
aDefaultDescription = mDefaultAppDescription;
return NS_OK;
}
//------------------------------------------------------------------------
// Get() is new, Set() is an override; they permit nsOSHelperAppService
// to reorder the default & preferred app handlers
void nsMIMEInfoOS2::GetDefaultApplication(nsIFile **aDefaultAppHandler)
{
*aDefaultAppHandler = mDefaultApplication;
NS_IF_ADDREF(*aDefaultAppHandler);
return;
}
void nsMIMEInfoOS2::SetDefaultApplication(nsIFile *aDefaultApplication)
{
mDefaultApplication = aDefaultApplication;
return;
}
//------------------------------------------------------------------------
// gets/sets the handle of the WPS object associated with this mimetype
void nsMIMEInfoOS2::GetDefaultAppHandle(uint32_t *aHandle)
{
if (aHandle) {
if (mDefaultAppHandle <= 0x10000 || mDefaultAppHandle >= 0x40000)
mDefaultAppHandle = 0;
*aHandle = mDefaultAppHandle;
}
return;
}
void nsMIMEInfoOS2::SetDefaultAppHandle(uint32_t aHandle)
{
if (aHandle <= 0x10000 || aHandle >= 0x40000)
mDefaultAppHandle = 0;
else
mDefaultAppHandle = aHandle;
return;
}
//------------------------------------------------------------------------
nsresult nsMIMEInfoOS2::LoadUriInternal(nsIURI *aURL)
{
nsresult rv;
NS_ENSURE_TRUE(Preferences::GetRootBranch(), NS_ERROR_FAILURE);
/* Convert SimpleURI to StandardURL */
nsCOMPtr<nsIURI> uri = do_CreateInstance(NS_STANDARDURL_CONTRACTID, &rv);
if (NS_FAILED(rv)) {
return NS_ERROR_FAILURE;
}
nsAutoCString urlSpec;
aURL->GetSpec(urlSpec);
uri->SetSpec(urlSpec);
/* Get the protocol so we can look up the preferences */
nsAutoCString uProtocol;
uri->GetScheme(uProtocol);
nsAutoCString branchName = NS_LITERAL_CSTRING("applications.") + uProtocol;
nsAutoCString prefName = branchName + branchName;
nsAdoptingCString prefString = Preferences::GetCString(prefName.get());
nsAutoCString applicationName;
nsAutoCString parameters;
if (prefString.IsEmpty()) {
char szAppFromINI[CCHMAXPATH];
char szParamsFromINI[MAXINIPARAMLENGTH];
/* did OS2.INI contain application? */
rv = GetApplicationAndParametersFromINI(uProtocol,
szAppFromINI, sizeof(szAppFromINI),
szParamsFromINI, sizeof(szParamsFromINI));
if (NS_SUCCEEDED(rv)) {
applicationName = szAppFromINI;
parameters = szParamsFromINI;
} else {
return NS_ERROR_FAILURE;
}
}
// Dissect the URI
nsAutoCString uURL, uUsername, uPassword, uHost, uPort, uPath;
nsAutoCString uEmail, uGroup;
int32_t iPort;
// when passing to OS/2 apps later, we need ASCII URLs,
// UTF-8 would probably not get handled correctly
aURL->GetAsciiSpec(uURL);
uri->GetAsciiHost(uHost);
uri->GetUsername(uUsername);
NS_UnescapeURL(uUsername);
uri->GetPassword(uPassword);
NS_UnescapeURL(uPassword);
uri->GetPort(&iPort);
/* GetPort returns -1 if there is no port in the URI */
if (iPort != -1)
uPort.AppendInt(iPort);
uri->GetPath(uPath);
NS_UnescapeURL(uPath);
// One could use nsIMailtoUrl to get email and newsgroup,
// but it is probably easier to do that quickly by hand here
// uEmail is both email address and message id for news
uEmail = uUsername + NS_LITERAL_CSTRING("@") + uHost;
// uPath can almost be used as newsgroup and as channel for IRC
// but strip leading "/"
uGroup = Substring(uPath, 1, uPath.Length());
NS_NAMED_LITERAL_CSTRING(url, "%url%");
NS_NAMED_LITERAL_CSTRING(username, "%username%");
NS_NAMED_LITERAL_CSTRING(password, "%password%");
NS_NAMED_LITERAL_CSTRING(host, "%host%");
NS_NAMED_LITERAL_CSTRING(port, "%port%");
NS_NAMED_LITERAL_CSTRING(email, "%email%");
NS_NAMED_LITERAL_CSTRING(group, "%group%");
NS_NAMED_LITERAL_CSTRING(msgid, "%msgid%");
NS_NAMED_LITERAL_CSTRING(channel, "%channel%");
bool replaced = false;
if (applicationName.IsEmpty() && parameters.IsEmpty()) {
/* Put application name in parameters */
applicationName.Append(prefString);
branchName.Append(".");
prefName = branchName + NS_LITERAL_CSTRING("parameters");
prefString = Preferences::GetCString(prefName.get());
/* If parameters have been specified, use them instead of the separate entities */
if (!prefString.IsEmpty()) {
parameters.Append(" ");
parameters.Append(prefString);
int32_t pos = parameters.Find(url.get());
if (pos != kNotFound) {
nsAutoCString uURL;
aURL->GetSpec(uURL);
NS_UnescapeURL(uURL);
uURL.Cut(0, uProtocol.Length()+1);
parameters.Replace(pos, url.Length(), uURL);
replaced = true;
}
} else {
/* port */
if (!uPort.IsEmpty()) {
prefName = branchName + NS_LITERAL_CSTRING("port");
prefString = Preferences::GetCString(prefName.get());
if (!prefString.IsEmpty()) {
parameters.Append(" ");
parameters.Append(prefString);
}
}
/* username */
if (!uUsername.IsEmpty()) {
prefName = branchName + NS_LITERAL_CSTRING("username");
prefString = Preferences::GetCString(prefName.get());
if (!prefString.IsEmpty()) {
parameters.Append(" ");
parameters.Append(prefString);
}
}
/* password */
if (!uPassword.IsEmpty()) {
prefName = branchName + NS_LITERAL_CSTRING("password");
prefString = Preferences::GetCString(prefName.get());
if (!prefString.IsEmpty()) {
parameters.Append(" ");
parameters.Append(prefString);
}
}
/* host */
if (!uHost.IsEmpty()) {
prefName = branchName + NS_LITERAL_CSTRING("host");
prefString = Preferences::GetCString(prefName.get());
if (!prefString.IsEmpty()) {
parameters.Append(" ");
parameters.Append(prefString);
}
}
}
}
#ifdef DEBUG_peter
printf("uURL=%s\n", uURL.get());
printf("uUsername=%s\n", uUsername.get());
printf("uPassword=%s\n", uPassword.get());
printf("uHost=%s\n", uHost.get());
printf("uPort=%s\n", uPort.get());
printf("uPath=%s\n", uPath.get());
printf("uEmail=%s\n", uEmail.get());
printf("uGroup=%s\n", uGroup.get());
#endif
int32_t pos;
pos = parameters.Find(url.get());
if (pos != kNotFound) {
replaced = true;
parameters.Replace(pos, url.Length(), uURL);
}
pos = parameters.Find(username.get());
if (pos != kNotFound) {
replaced = true;
parameters.Replace(pos, username.Length(), uUsername);
}
pos = parameters.Find(password.get());
if (pos != kNotFound) {
replaced = true;
parameters.Replace(pos, password.Length(), uPassword);
}
pos = parameters.Find(host.get());
if (pos != kNotFound) {
replaced = true;
parameters.Replace(pos, host.Length(), uHost);
}
pos = parameters.Find(port.get());
if (pos != kNotFound) {
replaced = true;
parameters.Replace(pos, port.Length(), uPort);
}
pos = parameters.Find(email.get());
if (pos != kNotFound) {
replaced = true;
parameters.Replace(pos, email.Length(), uEmail);
}
pos = parameters.Find(group.get());
if (pos != kNotFound) {
replaced = true;
parameters.Replace(pos, group.Length(), uGroup);
}
pos = parameters.Find(msgid.get());
if (pos != kNotFound) {
replaced = true;
parameters.Replace(pos, msgid.Length(), uEmail);
}
pos = parameters.Find(channel.get());
if (pos != kNotFound) {
replaced = true;
parameters.Replace(pos, channel.Length(), uGroup);
}
// If no replacement variable was used, the user most likely uses the WPS URL
// object and does not know about the replacement variables.
// Just append the full URL.
if (!replaced) {
parameters.Append(" ");
parameters.Append(uURL);
}
const char *params[3];
params[0] = parameters.get();
#ifdef DEBUG_peter
printf("params[0]=%s\n", params[0]);
#endif
int32_t numParams = 1;
nsCOMPtr<nsIFile> application;
rv = NS_NewNativeLocalFile(nsDependentCString(applicationName.get()), false, getter_AddRefs(application));
if (NS_FAILED(rv)) {
/* Maybe they didn't qualify the name - search path */
char szAppPath[CCHMAXPATH];
APIRET rc = DosSearchPath(SEARCH_IGNORENETERRS | SEARCH_ENVIRONMENT,
"PATH", applicationName.get(),
szAppPath, sizeof(szAppPath));
if (rc == NO_ERROR) {
rv = NS_NewNativeLocalFile(nsDependentCString(szAppPath), false, getter_AddRefs(application));
}
if (NS_FAILED(rv) || (rc != NO_ERROR)) {
/* Try just launching it with COMSPEC */
rv = NS_NewNativeLocalFile(nsDependentCString(getenv("COMSPEC")), false, getter_AddRefs(application));
if (NS_FAILED(rv)) {
return rv;
}
params[0] = "/c";
params[1] = applicationName.get();
params[2] = parameters.get();
numParams = 3;
}
}
nsCOMPtr<nsIProcess> process = do_CreateInstance(NS_PROCESS_CONTRACTID);
if (NS_FAILED(rv = process->Init(application)))
return rv;
if (NS_FAILED(rv = process->Run(false, params, numParams)))
return rv;
return NS_OK;
}
//------------------------------------------------------------------------
// nsIPropertyBag
//------------------------------------------------------------------------
NS_IMETHODIMP
nsMIMEInfoOS2::GetEnumerator(nsISimpleEnumerator **_retval)
{
nsCOMArray<nsIVariant> properties;
nsCOMPtr<nsIVariant> variant;
GetProperty(NS_LITERAL_STRING("defaultApplicationIconURL"), getter_AddRefs(variant));
if (variant)
properties.AppendObject(variant);
GetProperty(NS_LITERAL_STRING("customApplicationIconURL"), getter_AddRefs(variant));
if (variant)
properties.AppendObject(variant);
return NS_NewArrayEnumerator(_retval, properties);
}
//------------------------------------------------------------------------
NS_IMETHODIMP
nsMIMEInfoOS2::GetProperty(const nsAString& aName, nsIVariant **_retval)
{
nsresult rv = NS_ERROR_FAILURE;
if (aName.EqualsLiteral(PROPERTY_DEFAULT_APP_ICON_URL)) {
rv = GetIconURLVariant(mDefaultApplication, _retval);
} else {
if (aName.EqualsLiteral(PROPERTY_CUSTOM_APP_ICON_URL) &&
mPreferredApplication) {
// find file from handler
nsCOMPtr<nsIFile> appFile;
nsCOMPtr<nsILocalHandlerApp> localHandlerApp =
do_QueryInterface(mPreferredApplication, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = localHandlerApp->GetExecutable(getter_AddRefs(appFile));
NS_ENSURE_SUCCESS(rv, rv);
rv = GetIconURLVariant(appFile, _retval);
}
}
return rv;
}
//------------------------------------------------------------------------
NS_IMETHODIMP
nsMIMEInfoOS2::GetIconURLVariant(nsIFile *aApplication, nsIVariant **_retval)
{
nsresult rv = CallCreateInstance("@mozilla.org/variant;1", _retval);
NS_ENSURE_SUCCESS(rv, rv);
nsAutoCString fileURLSpec;
if (aApplication)
NS_GetURLSpecFromFile(aApplication, fileURLSpec);
else {
GetPrimaryExtension(fileURLSpec);
fileURLSpec.Insert(NS_LITERAL_CSTRING("moztmp."), 0);
}
nsAutoCString iconURLSpec(NS_LITERAL_CSTRING("moz-icon://"));
iconURLSpec += fileURLSpec;
nsCOMPtr<nsIWritableVariant> writable(do_QueryInterface(*_retval));
writable->SetAsAUTF8String(iconURLSpec);
return NS_OK;
}
| 30.798623 | 109 | 0.639656 | [
"object"
] |
12b4c34500ca4f2f84298620f0be3c49d2b82600 | 1,217 | cpp | C++ | cpp-src/src/algorithms/hacker-rank/implementation/the_birthday_bar_test.cpp | josnelihurt/algorithms | 0c130d37b1dac225a62a36d6ec126a4f98a9faae | [
"Unlicense"
] | null | null | null | cpp-src/src/algorithms/hacker-rank/implementation/the_birthday_bar_test.cpp | josnelihurt/algorithms | 0c130d37b1dac225a62a36d6ec126a4f98a9faae | [
"Unlicense"
] | null | null | null | cpp-src/src/algorithms/hacker-rank/implementation/the_birthday_bar_test.cpp | josnelihurt/algorithms | 0c130d37b1dac225a62a36d6ec126a4f98a9faae | [
"Unlicense"
] | null | null | null | #include "the_birthday_bar.h"
#include "gtest/gtest.h"
using namespace the_birthday_bar;
using namespace std;
TEST(TBB, sampleTestCase10){
vector<int> s{
3, 5, 4, 1, 2, 5, 3, 4, 3, 2, 1, 1, 2, 4, 2, 3, 4, 5, 3, 1, 2, 5, 4, 5, 4, 1, 1, 5, 3, 1, 4, 5, 2, 3, 2, 5, 2, 5, 2, 2, 1, 5, 3, 2, 5, 1, 2, 4, 3, 1, 5, 1, 3, 3, 5};
auto d = 18;
auto m = 6;
auto result = birthday(s, d, m);
EXPECT_EQ(result, 10);
}
TEST(TBB, sampleTestCaseD1M1){
vector<int> s{1, 1, 1, 1, 1};
auto d = 1;
auto m = 1;
auto result = birthday(s, d, m);
EXPECT_EQ(result, 5);
}
TEST(TBB, sampleTestCaseD0){
vector<int> s{4, 0, 0, 0, 1};
auto d = 0;
auto m = 2;
auto result = birthday(s, d, m);
EXPECT_EQ(result, 2);
}
TEST(TBB, sampleTestCaseM0){
vector<int> s{4,0,0,1,1};
auto d = 4;
auto m = 0;
auto result = birthday(s, d, m);
EXPECT_EQ(result, 0);
}
TEST(TBB, sampleTestCase2){
vector<int> s{4};
auto d = 4;
auto m = 1;
auto result = birthday(s, d, m);
EXPECT_EQ(result, 1);
}
TEST(TBB, sampleTestCase0){
vector<int> s{2, 2, 1, 3, 2};
auto d = 4;
auto m = 2;
auto result = birthday(s, d, m);
EXPECT_EQ(result, 2);
}
| 24.34 | 173 | 0.541495 | [
"vector"
] |
52125bfe251542d163f8cdd173df2230f33104c8 | 1,935 | cc | C++ | codelab/neon_minimum.cc | pkufool/cpp_neon_play | 5e59ead0f17e79dc2210cfd4c22a3631bf4886c0 | [
"MIT"
] | null | null | null | codelab/neon_minimum.cc | pkufool/cpp_neon_play | 5e59ead0f17e79dc2210cfd4c22a3631bf4886c0 | [
"MIT"
] | null | null | null | codelab/neon_minimum.cc | pkufool/cpp_neon_play | 5e59ead0f17e79dc2210cfd4c22a3631bf4886c0 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <random>
#include <ctime>
#include <arm_neon.h>
float NeonMinimum(const float* in, const size_t size) {
const float* in_data = in;
const float* const in_data_end = in + size;
float32x4_t min = vdupq_n_f32(std::numeric_limits<float>::max());
for (; in_data + 4 <= in_data_end; in_data += 4) {
const float32x4_t v1 = vld1q_f32(
reinterpret_cast<const float32_t *>(in_data));
min = vminq_f32(v1, min);
}
// Get the minimum float among the 4 floats in the SIMD register.
float32x2_t min1 = vget_low_f32(min);
float32x2_t min2 = vget_high_f32(min);
min1 = vmin_f32(min1, min2);
float ret_min = (vget_lane_f32(min1, 0) < vget_lane_f32(min1, 1)) ?
vget_lane_f32(min1, 0) : vget_lane_f32(min1, 1);
// Get the minimum among the ret_min and the rest floats in the input array
// which couldn't be fitted into 4-bytes SIMD register.
for (; in_data < in_data_end; ++in_data) {
if (ret_min > *in_data) {
ret_min = *in_data;
}
}
return ret_min;
}
float Minimum(const float* in, const size_t size) {
const float* in_data = in;
const float* in_data_end = in + size;
float ret_min = std::numeric_limits<float>::max();
for (; in_data < in_data_end; ++in_data) {
if (ret_min > *in_data) {
ret_min = *in_data;
}
}
return ret_min;
}
int main() {
int num = 1000;
float v[num];
std::default_random_engine e;
std::uniform_real_distribution<float> u(0, 1);
for (int i = 0; i < num; ++i) {
v[i] = u(e);
}
std::clock_t start;
start = std::clock();
std::cout << "Slow Minimum : " << Minimum(v, num)
<< " use time : " << (std::clock() - start) / (double)CLOCKS_PER_SEC * 1e6
<< "." << std::endl;
start = std::clock();
std::cout << "Neon Minimum : " << NeonMinimum(v, num)
<< " use time : " << (std::clock() - start) / (double)CLOCKS_PER_SEC * 1e6
<< "." << std::endl;
}
| 30.234375 | 80 | 0.62584 | [
"vector"
] |
5225c9c626d5c85971528fa7a1426832ebaf2b75 | 1,425 | cpp | C++ | src/Encryption.cpp | teunvw14/keylogger | 541b464fc9241bfd6a17bd12776f55eabb64cc12 | [
"MIT"
] | null | null | null | src/Encryption.cpp | teunvw14/keylogger | 541b464fc9241bfd6a17bd12776f55eabb64cc12 | [
"MIT"
] | null | null | null | src/Encryption.cpp | teunvw14/keylogger | 541b464fc9241bfd6a17bd12776f55eabb64cc12 | [
"MIT"
] | null | null | null | #include <vector>
#include <string>
#include "encryption.h"
namespace Base64
{
const std::string &BASE64_CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string base64_encode(const std::string &stringToEncode)
{
std::string ret;
int val = 0;
int bits = -6;
const unsigned int b63 = 0x3F;
std::string encryptedString = "";
for(const auto &character : stringToEncode)
{
val = (val << 8) + character;
bits += 8;
while(bits >= 0)
{
ret.push_back(BASE64_CODES[(val >> bits) & b63]);
bits -= 6;
}
}
if (bits > -6)
ret.push_back(BASE64_CODES[((val << 8) >> (bits + 8)) & b63]);
while(ret.size() % 4)
ret.push_back('=');
return ret;
}
}
namespace Encryption
{
std::string EncryptB64( std::string s)
{
std::string SALT1 = "DZ6k6uarM";
std::string SALT2 = "Hiqn0jvTf";
std::string SALT3 = "IPjf56y8";
s = SALT1 + s + SALT2 + SALT3;
s = Base64::base64_encode(s);
s.insert(7, SALT2);
s += SALT1;
s = Base64::base64_encode(s);
s = SALT2 + SALT1 + s;
s = Base64::base64_encode(s);
s.insert(1, "m");
s = Base64::base64_encode(s);
return s;
}
} | 22.983871 | 105 | 0.503158 | [
"vector"
] |
52348470b9b542d1d93cf3e34b948efd8a23fff3 | 15,365 | cpp | C++ | co_scan/src/geodesic/BaseModel.cpp | LXYYY/CoScan | abd87b9e004cdf683b458d76cb93e62485aeba3c | [
"MIT"
] | 15 | 2020-03-31T01:54:43.000Z | 2022-03-31T16:27:29.000Z | co_scan/src/geodesic/BaseModel.cpp | LXYYY/CoScan | abd87b9e004cdf683b458d76cb93e62485aeba3c | [
"MIT"
] | 1 | 2022-03-18T10:27:55.000Z | 2022-03-31T16:18:47.000Z | co_scan/src/geodesic/BaseModel.cpp | LXYYY/CoScan | abd87b9e004cdf683b458d76cb93e62485aeba3c | [
"MIT"
] | 7 | 2020-04-01T13:05:28.000Z | 2021-03-08T04:58:01.000Z | #include "BaseModel.h"
#include "Parameters.h"
//#include <windows.h> // dsy: comment out.
//#include "gl\gl.h" // dsy: comment out.
//#include "gl\glu.h" // dsy: comment out.
#include <float.h>
#include <iostream>
//#include "gl\glut.h"
//#pragma comment(lib, "OPENGL32.LIB") // dsy: comment out.
//#pragma comment(lib, "GLU32.LIB") // dsy: comment out.
#include <fstream>
#include <sstream>
#include <algorithm>
using namespace std;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CBaseModel::CBaseModel(const string& filename) : m_filename(filename)
{
}
/*
void CBaseModel::Render() const
{
glPushMatrix();
GLint shadeModel;
glGetIntegerv(GL_SHADE_MODEL, &shadeModel);
if (shadeModel == GL_SMOOTH)
{
for (int i = 0; i < GetNumOfFaces(); ++i)
{
glBegin(GL_POLYGON);
for (int j = 0; j < 3; ++j)
{
const CPoint3D &pt = Vert(Face(i)[j]);
if (!m_NormalsToVerts.empty())
{
const CPoint3D &normal = Normal(Face(i)[j]);
glNormal3f((float)normal.x, (float)normal.y, (float)normal.z);
}
glVertex3f((float)pt.x, (float)pt.y, (float)pt.z);
}
glEnd();
}
}
else
{
for (int i = 0; i < GetNumOfFaces(); ++i)
{
glBegin(GL_POLYGON);
CPoint3D normal = VectorCross(Vert(Face(i)[0]), Vert(Face(i)[1]), Vert(Face(i)[2]));
normal.Normalize();
glNormal3f((float)normal.x, (float)normal.y, (float)normal.z);
for (int j = 0; j < 3; ++j)
{
const CPoint3D &pt = Vert(Face(i)[j]);
glVertex3f((float)pt.x, (float)pt.y, (float)pt.z);
}
glEnd();
}
}
glPopMatrix();
}
*/
void CBaseModel::ComputeScaleAndNormals()
{
if (m_Verts.empty())
return;
m_NormalsToVerts.resize(m_Verts.size(), CPoint3D(0, 0, 0));
CPoint3D center(0, 0, 0);
double sumArea(0);
CPoint3D sumNormal(0, 0, 0);
double deta(0);
for (int i = 0; i < (int)m_Faces.size(); ++i)
{
CPoint3D normal = VectorCross(Vert(Face(i)[0]),
Vert(Face(i)[1]),
Vert(Face(i)[2]));
double area = normal.Len();
CPoint3D gravity3 = Vert(Face(i)[0]) + Vert(Face(i)[1]) + Vert(Face(i)[2]);
center += area * gravity3;
sumArea += area;
sumNormal += normal;
deta += gravity3 ^ normal;
normal.x /= area;
normal.y /= area;
normal.z /= area;
for (int j = 0; j < 3; ++j)
{
m_NormalsToVerts[Face(i)[j]] += normal;
}
}
center /= sumArea * 3;
deta -= 3 * (center ^ sumNormal);
if (true)//deta > 0)
{
for (int i = 0; i < GetNumOfVerts(); ++i)
{
if (fabs(m_NormalsToVerts[i].x)
+ fabs(m_NormalsToVerts[i].y)
+ fabs(m_NormalsToVerts[i].z) >= FLT_EPSILON)
{
m_NormalsToVerts[i].Normalize();
}
}
}
else
{
for (int i = 0; i < GetNumOfFaces(); ++i)
{
int temp = m_Faces[i][0];
m_Faces[i][0] = m_Faces[i][1];
m_Faces[i][1] = temp;
}
for (int i = 0; i < GetNumOfVerts(); ++i)
{
if (fabs(m_NormalsToVerts[i].x)
+ fabs(m_NormalsToVerts[i].y)
+ fabs(m_NormalsToVerts[i].z) >= FLT_EPSILON)
{
double len = m_NormalsToVerts[i].Len();
m_NormalsToVerts[i].x /= -len;
m_NormalsToVerts[i].y /= -len;
m_NormalsToVerts[i].z /= -len;
}
}
}
CPoint3D ptUp(m_Verts[0]);
CPoint3D ptDown(m_Verts[0]);
for (int i = 1; i < GetNumOfVerts(); ++i)
{
if (m_Verts[i].x > ptUp.x)
ptUp.x = m_Verts[i].x;
else if (m_Verts[i].x < ptDown.x)
ptDown.x = m_Verts[i].x;
if (m_Verts[i].y > ptUp.y)
ptUp.y = m_Verts[i].y;
else if (m_Verts[i].y < ptDown.y)
ptDown.y = m_Verts[i].y;
if (m_Verts[i].z > ptUp.z)
ptUp.z = m_Verts[i].z;
else if (m_Verts[i].z < ptDown.z)
ptDown.z = m_Verts[i].z;
}
double maxEdgeLenOfBoundingBox = -1;
if (ptUp.x - ptDown.x > maxEdgeLenOfBoundingBox)
maxEdgeLenOfBoundingBox = ptUp.x - ptDown.x;
if (ptUp.y - ptDown.y > maxEdgeLenOfBoundingBox)
maxEdgeLenOfBoundingBox = ptUp.y - ptDown.y;
if (ptUp.z - ptDown.z > maxEdgeLenOfBoundingBox)
maxEdgeLenOfBoundingBox = ptUp.z - ptDown.z;
m_scale = maxEdgeLenOfBoundingBox / 2;
//m_center = center;
//m_ptUp = ptUp;
//m_ptDown = ptDown;
}
void CBaseModel::LoadModel()
{
ReadFile(m_filename);
ComputeScaleAndNormals();
}
string CBaseModel::GetFileShortNameWithoutExtension() const
{
int pos = (int)m_filename.size() - 1;
while (pos >= 0)
{
if (m_filename[pos] == '\\')
break;
--pos;
}
++pos;
int pos2 = (int)m_filename.size() - 1;
while (pos2 >= 0)
{
if (m_filename[pos2] == '.')
break;
--pos2;
}
string str(m_filename.substr(pos, pos2 - pos));
return str;
}
string CBaseModel::GetFileShortName() const
{
int pos = (int)m_filename.size() - 1;
while (pos >= 0)
{
if (m_filename[pos] == '\\')
break;
--pos;
}
++pos;
string str(m_filename.substr(pos));
return str;
}
string CBaseModel::GetFileFullName() const
{
return m_filename;
}
void CBaseModel::ReadObjFile(const string& filename)
{
ifstream in(filename.c_str());
if (in.fail())
{
throw "fail to read file";
}
char buf[256];
while (in.getline(buf, sizeof buf))
{
istringstream line(buf);
string word;
line >> word;
if (word == "v")
{
CPoint3D pt;
line >> pt.x;
line >> pt.y;
line >> pt.z;
m_Verts.push_back(pt);
}
else if (word == "f")
{
CFace face;
int tmp;
vector<int> polygon;
polygon.reserve(4);
while (line >> tmp)
{
polygon.push_back(tmp);
char tmpBuf[256];
line.getline(tmpBuf, sizeof tmpBuf, ' ');
}
for (int j = 1; j < (int)polygon.size() - 1; ++j)
{
face[0] = polygon[0] - 1;
face[1] = polygon[j] - 1;
face[2] = polygon[j + 1] - 1;
m_Faces.push_back(face);
}
}
else
{
continue;
}
}
//m_Verts.swap(vector<CPoint3D>(m_Verts)); // dsy: comment out.
//m_Faces.swap(vector<CFace>(m_Faces)); // dsy: comment out.
in.close();
}
void CBaseModel::ReadFile(const string& filename)
{
int nDot = (int)filename.rfind('.');
if (nDot == -1)
{
throw "File name doesn't contain a dot!";
}
string extension = filename.substr(nDot + 1);
if (extension == "obj")
{
ReadObjFile(filename);
}
else if (extension == "off")
{
ReadOffFile(filename);
}
else if (extension == "m")
{
ReadMFile(filename);
}
else
{
throw "This format can't be handled!";
}
}
void CBaseModel::ReadOffFile(const string& filename)
{
ifstream in(filename.c_str());
if (in.fail())
{
throw "fail to read file";
}
char buf[256];
in.getline(buf, sizeof buf);
int vertNum, faceNum, edgeNum;
in >> vertNum >> faceNum >> edgeNum;
for (int i = 0; i < vertNum; ++i)
{
CPoint3D pt;
in >> pt.x;
in >> pt.y;
in >> pt.z;
m_Verts.push_back(pt);
}
//m_Verts.swap(vector<CPoint3D>(m_Verts)); // dsy: comment out.
int degree;
while (in >> degree)
{
int first, second;
in >> first >> second;
for (int i = 0; i < degree - 2; ++i)
{
CFace f;
f[0] = first;
f[1] = second;
in >> f[2];
m_Faces.push_back(f);
second = f[2];
}
}
in.close();
//m_Faces.swap(vector<CFace>(m_Faces)); // dsy: comment out.
}
void CBaseModel::ReadMFile(const string& filename)
{
ifstream in(filename.c_str());
if (in.fail())
{
throw "fail to read file";
}
char buf[256];
while (in.getline(buf, sizeof buf))
{
istringstream line(buf);
if (buf[0] == '#')
continue;
string word;
line >> word;
if (word == "Vertex")
{
int tmp;
line >> tmp;
CPoint3D pt;
line >> pt.x;
line >> pt.y;
line >> pt.z;
m_Verts.push_back(pt);
}
else if (word == "Face")
{
CFace face;
int tmp;
line >> tmp;
vector<int> polygon;
polygon.reserve(4);
while (line >> tmp)
{
polygon.push_back(tmp);
}
for (int j = 1; j < (int)polygon.size() - 1; ++j)
{
face[0] = polygon[0] - 1;
face[1] = polygon[j] - 1;
face[2] = polygon[j + 1] - 1;
m_Faces.push_back(face);
}
}
else
{
continue;
}
}
//m_Verts.swap(vector<CPoint3D>(m_Verts)); // dsy: comment out.
//m_Faces.swap(vector<CFace>(m_Faces)); // dsy: comment out.
in.close();
}
void CBaseModel::SaveMFile(const string& filename) const
{
ofstream outFile(filename.c_str());
for (int i = 0; i < (int)GetNumOfVerts(); ++i)
{
outFile << "Vertex " << i + 1 << " " << Vert(i).x << " " << Vert(i).y << " " << Vert(i).z << endl;
}
int cnt(0);
for (int i = 0; i < (int)GetNumOfFaces(); ++i)
{
if (m_UselessFaces.find(i) != m_UselessFaces.end())
continue;
outFile <<"Face " << ++cnt << " " << Face(i)[0] + 1 << " " << Face(i)[1] + 1 << " " << Face(i)[2] + 1 << endl;
}
outFile.close();
}
void CBaseModel::SaveOffFile(const string& filename) const
{
ofstream outFile(filename.c_str());
outFile << "OFF" << endl;
outFile << GetNumOfVerts() << " " << GetNumOfFaces() << " " << 0 << endl;
for (int i = 0; i < (int)GetNumOfVerts(); ++i)
{
outFile << Vert(i).x << " " << Vert(i).y << " " << Vert(i).z << endl;
}
for (int i = 0; i < (int)GetNumOfFaces(); ++i)
{
if (m_UselessFaces.find(i) != m_UselessFaces.end())
continue;
outFile << 3 << " " << Face(i)[0]<< " " << Face(i)[1] << " " << Face(i)[2] << endl;
}
outFile.close();
}
void CBaseModel::SaveObjFile(const string& filename) const
{
ofstream outFile(filename.c_str());
outFile << "g " << filename.substr(filename.rfind("\\") + 1, filename.rfind('.') - filename.rfind("\\") - 1) << endl;
for (int i = 0; i < (int)GetNumOfVerts(); ++i)
{
outFile << "v " << Vert(i).x << " " << Vert(i).y << " " << Vert(i).z << endl;
}
for (int i = 0; i < (int)GetNumOfFaces(); ++i)
{
if (m_UselessFaces.find(i) != m_UselessFaces.end())
continue;
outFile << "f " << Face(i)[0] + 1 << " " << Face(i)[1] + 1<< " " << Face(i)[2] + 1<< endl;
}
outFile.close();
}
void CBaseModel::SaveScalarFieldObjFile(const vector<double>& vals, const string& filename) const
{
ofstream outFile(filename.c_str());
outFile << "g " << filename.substr(filename.rfind("\\") + 1, filename.rfind('.') - filename.rfind("\\") - 1) << endl;
outFile << "# maxDis: " << *max_element(vals.begin(), vals.end()) << endl;
for (int i = 0; i < (int)GetNumOfVerts(); ++i)
{
outFile << "v " << Vert(i).x << " " << Vert(i).y << " " << Vert(i).z << endl;
}
for (int i = 0; i < (int)vals.size(); ++i)
{
outFile << "vt " << vals[i] << " " << 0 << endl;
}
for (int i = 0; i < (int)GetNumOfFaces(); ++i)
{
if (m_UselessFaces.find(i) != m_UselessFaces.end())
continue;
outFile << "f " << Face(i)[0] + 1 << "/" << Face(i)[0] + 1
<< " " << Face(i)[1] + 1 << "/" << Face(i)[1] + 1
<< " " << Face(i)[2] + 1 << "/" << Face(i)[2] + 1 << endl;
}
outFile.close();
}
void CBaseModel::SaveScalarFieldObjFile(const vector<double>& vals, const string& comments, const string& filename) const
{
ofstream outFile(filename.c_str());
outFile << "g " << filename.substr(filename.rfind("\\") + 1, filename.rfind('.') - filename.rfind("\\") - 1) << endl;
outFile << comments << endl;
for (int i = 0; i < (int)GetNumOfVerts(); ++i)
{
outFile << "v " << Vert(i).x << " " << Vert(i).y << " " << Vert(i).z << endl;
}
for (int i = 0; i < (int)vals.size(); ++i)
{
outFile << "vt " << vals[i] << " " << 0 << endl;
}
for (int i = 0; i < (int)GetNumOfFaces(); ++i)
{
if (m_UselessFaces.find(i) != m_UselessFaces.end())
continue;
outFile << "f " << Face(i)[0] + 1 << "/" << Face(i)[0] + 1
<< " " << Face(i)[1] + 1 << "/" << Face(i)[1] + 1
<< " " << Face(i)[2] + 1 << "/" << Face(i)[2] + 1 << endl;
}
outFile.close();
}
void CBaseModel::SaveScalarFieldObjFile(const vector<double>& vals, double maxV, const string& filename) const
{
ofstream outFile(filename.c_str());
outFile << "g " << filename.substr(filename.rfind("\\") + 1, filename.rfind('.') - filename.rfind("\\") - 1) << endl;
outFile << "# maxValue = " << *max_element(vals.begin(), vals.end()) / maxV << endl;
for (int i = 0; i < (int)GetNumOfVerts(); ++i)
{
outFile << "v " << Vert(i).x << " " << Vert(i).y << " " << Vert(i).z << endl;
}
for (int i = 0; i < (int)vals.size(); ++i)
{
outFile << "vt " << vals[i] / maxV << " " << 0 << endl;
}
for (int i = 0; i < (int)GetNumOfFaces(); ++i)
{
if (m_UselessFaces.find(i) != m_UselessFaces.end())
continue;
outFile << "f " << Face(i)[0] + 1 << "/" << Face(i)[0] + 1
<< " " << Face(i)[1] + 1 << "/" << Face(i)[1] + 1
<< " " << Face(i)[2] + 1 << "/" << Face(i)[2] + 1 << endl;
}
outFile.close();
}
void CBaseModel::SavePamametrizationObjFile(const vector<pair<double, double>>& uvs, const string& filename) const
{
ofstream outFile(filename.c_str());
outFile << "g " << filename.substr(filename.rfind("\\") + 1, filename.rfind('.') - filename.rfind("\\") - 1) << endl;
for (int i = 0; i < (int)GetNumOfVerts(); ++i)
{
outFile << "v " << Vert(i).x << " " << Vert(i).y << " " << Vert(i).z << endl;
}
for (int i = 0; i < (int)uvs.size(); ++i)
{
outFile << "vt " << uvs[i].first << " " << uvs[i].second << endl;
}
for (int i = 0; i < (int)GetNumOfFaces(); ++i)
{
if (m_UselessFaces.find(i) != m_UselessFaces.end())
continue;
outFile << "f " << Face(i)[0] + 1 << "/" << Face(i)[0] + 1
<< " " << Face(i)[1] + 1 << "/" << Face(i)[1] + 1
<< " " << Face(i)[2] + 1 << "/" << Face(i)[2] + 1 << endl;
}
outFile.close();
}
void CBaseModel::PrintInfo(ostream& out) const
{
out << "Model info is as follows.\n";
out << "Name: " << GetFileShortName() << endl;
out << "VertNum = " << GetNumOfVerts() << endl;
out << "FaceNum = " << GetNumOfFaces() << endl;
out << "Scale = " << m_scale << endl;
}
CPoint3D CBaseModel::GetShiftVertex(int indexOfVert) const
{
return Vert(indexOfVert) + Normal(indexOfVert) * RateOfNormalShift * GetScale();
}
//CPoint3D CBaseModel::ShiftVertex(int indexOfVert, double epsilon) const
//{
// return Vert(indexOfVert) + Normal(indexOfVert) * epsilon;
//}
int CBaseModel::GetVertexID(const CPoint3D& pt) const
{
double dis = DBL_MAX;
int id;
for (int i = 0; i < GetNumOfVerts(); ++i)
{
if ((Vert(i) - pt).Len() < dis)
{
id = i;
dis = (Vert(id)-pt).Len();
}
}
return id;
}
string CBaseModel::GetComments(const char* filename)
{
ifstream in(filename);
char buf[256];
string result;
while (in.getline(buf, sizeof buf))
{
if (buf[0] == '#')
{
result += buf;
result += "\n";
}
}
in.close();
return result;
}
vector<double> CBaseModel::GetScalarField(string filename)
{
vector<double> scalarField;
ifstream in(filename);
char buf[256];
while (in.getline(buf, sizeof buf))
{
istringstream line(buf);
string word;
line >> word;
if (word == "vt")
{
double value;
line >> value;
scalarField.push_back(value);
}
}
in.close();
return scalarField;
}
void CBaseModel::SetFaces(const vector<CBaseModel::CFace>& faces)
{
m_Faces = faces;
}
const vector<CBaseModel::CFace>& CBaseModel::GetFaces() const
{
return m_Faces;
} | 24.943182 | 122 | 0.546957 | [
"render",
"vector",
"model"
] |
523759651358dbb04b745b889e5c7e7ab5ece524 | 5,252 | cpp | C++ | fkie_iop_manipulator_joint_position_sensor/src/urn_jaus_jss_manipulator_ManipulatorJointPositionSensor/ManipulatorJointPositionSensor_ReceiveFSM.cpp | fkie/iop_jaus_manipulator | d147d14a212fa57f52349c5ec937817591ef7d9c | [
"BSD-3-Clause"
] | null | null | null | fkie_iop_manipulator_joint_position_sensor/src/urn_jaus_jss_manipulator_ManipulatorJointPositionSensor/ManipulatorJointPositionSensor_ReceiveFSM.cpp | fkie/iop_jaus_manipulator | d147d14a212fa57f52349c5ec937817591ef7d9c | [
"BSD-3-Clause"
] | null | null | null | fkie_iop_manipulator_joint_position_sensor/src/urn_jaus_jss_manipulator_ManipulatorJointPositionSensor/ManipulatorJointPositionSensor_ReceiveFSM.cpp | fkie/iop_jaus_manipulator | d147d14a212fa57f52349c5ec937817591ef7d9c | [
"BSD-3-Clause"
] | null | null | null |
#include "urn_jaus_jss_manipulator_ManipulatorJointPositionSensor/ManipulatorJointPositionSensor_ReceiveFSM.h"
#include <moveit/robot_model_loader/robot_model_loader.h>
#include <fkie_iop_component/iop_component.h>
#include <fkie_iop_component/iop_config.h>
#include "urn_jaus_jss_manipulator_ManipulatorSpecificationService/ManipulatorSpecificationServiceService.h"
using namespace JTS;
using namespace urn_jaus_jss_manipulator_ManipulatorSpecificationService;
namespace urn_jaus_jss_manipulator_ManipulatorJointPositionSensor
{
ManipulatorJointPositionSensor_ReceiveFSM::ManipulatorJointPositionSensor_ReceiveFSM(urn_jaus_jss_core_Transport::Transport_ReceiveFSM* pTransport_ReceiveFSM, urn_jaus_jss_core_Events::Events_ReceiveFSM* pEvents_ReceiveFSM)
{
/*
* If there are other variables, context must be constructed last so that all
* class variables are available if an EntryAction of the InitialState of the
* statemachine needs them.
*/
context = new ManipulatorJointPositionSensor_ReceiveFSMContext(*this);
this->pTransport_ReceiveFSM = pTransport_ReceiveFSM;
this->pEvents_ReceiveFSM = pEvents_ReceiveFSM;
}
ManipulatorJointPositionSensor_ReceiveFSM::~ManipulatorJointPositionSensor_ReceiveFSM()
{
delete context;
}
void ManipulatorJointPositionSensor_ReceiveFSM::setupNotifications()
{
pEvents_ReceiveFSM->registerNotification("Receiving_Ready", ieHandler, "InternalStateChange_To_ManipulatorJointPositionSensor_ReceiveFSM_Receiving_Ready", "Events_ReceiveFSM");
pEvents_ReceiveFSM->registerNotification("Receiving", ieHandler, "InternalStateChange_To_ManipulatorJointPositionSensor_ReceiveFSM_Receiving_Ready", "Events_ReceiveFSM");
registerNotification("Receiving_Ready", pEvents_ReceiveFSM->getHandler(), "InternalStateChange_To_Events_ReceiveFSM_Receiving_Ready", "ManipulatorJointPositionSensor_ReceiveFSM");
registerNotification("Receiving", pEvents_ReceiveFSM->getHandler(), "InternalStateChange_To_Events_ReceiveFSM_Receiving", "ManipulatorJointPositionSensor_ReceiveFSM");
iop::Component &cmp = iop::Component::get_instance();
ManipulatorSpecificationServiceService *spec_srv = static_cast<ManipulatorSpecificationServiceService*>(cmp.get_service("ManipulatorSpecificationService"));
if (spec_srv != NULL) {
p_joint_names = spec_srv->pManipulatorSpecificationService_ReceiveFSM->getJointNames();
} else {
throw std::runtime_error("[PrimitiveManipulator] no ManipulatorSpecificationService in configuration found! Please include its plugin first (in the list)!");
}
for (unsigned int index = 0; index < p_joint_names.size(); index++) {
p_joint_positions[p_joint_names[index]] = 0.;
}
iop::Config cfg("~PrimitiveManipulator");
p_sub_jointstates = cfg.subscribe<sensor_msgs::JointState>("joint_states", 1, &ManipulatorJointPositionSensor_ReceiveFSM::pJoinStateCallback, this);
pEvents_ReceiveFSM->get_event_handler().register_query(QueryJointPositions::ID);
}
void ManipulatorJointPositionSensor_ReceiveFSM::sendQueryJointPositionsAction(QueryJointPositions msg, Receive::Body::ReceiveRec transportData)
{
/// Insert User Code HERE
JausAddress sender = transportData.getAddress();
ROS_DEBUG_NAMED("ManipulatorJointPositionSensor", "sendReportJointPositionAction to %s", sender.str().c_str());
p_mutex.lock();
this->sendJausMessage(p_report_joint_positions, sender);
p_mutex.unlock();
}
void ManipulatorJointPositionSensor_ReceiveFSM::pJoinStateCallback(const sensor_msgs::JointState::ConstPtr& joint_state)
{
// create index map
p_mutex.lock();
std::map<std::string, int> indexes;
std::vector<std::string>::iterator it_jn;
for (it_jn=p_joint_names.begin(); it_jn != p_joint_names.end(); ++it_jn) {
int index = -1;
for (unsigned int i = 0; i < joint_state->name.size(); i++) {
if (it_jn->compare(joint_state->name[i]) == 0) {
index = i;
break;
}
}
indexes[*it_jn] = index;
}
// get joint positions from joint_state
std::map<std::string, int>::iterator it_ids;
for (it_ids=indexes.begin(); it_ids != indexes.end(); ++it_ids) {
if (it_ids->second > -1) {
p_joint_positions[it_ids->first] = joint_state->position[it_ids->second];
} else {
p_joint_positions[it_ids->first] = 0.;
}
}
// std::map<std::string, float>::iterator it_ps;
// for (unsigned int index = 0; index < p_joint_names.size(); index++) {
// printf(" %s: %f\n", p_joint_names[index].c_str(), p_joint_positions[p_joint_names[index]]);
// }
// delete all positions first
while (p_report_joint_positions.getBody()->getJointPositionList()->getNumberOfElements() > 0) {
p_report_joint_positions.getBody()->getJointPositionList()->deleteLastElement();
}
std::map<std::string, float>::iterator it_ps;
for (unsigned int index = 0; index < p_joint_names.size(); index++) {
ReportJointPositions::Body::JointPositionList::JointPositionRec joint_position;
// TODO: read from config the type of the joint and use radians or meters
joint_position.getJointPosition()->setRadianAsUnsignedIntegerAt0(p_joint_positions[p_joint_names[index]]);
p_report_joint_positions.getBody()->getJointPositionList()->addElement(joint_position);
}
pEvents_ReceiveFSM->get_event_handler().set_report(QueryJointPositions::ID, &p_report_joint_positions);
p_mutex.unlock();
}
};
| 44.508475 | 223 | 0.796268 | [
"vector"
] |
52530d918320d3af9012c39c609e090db70d2ccc | 2,653 | cpp | C++ | Game/SceneInGame/BackgroundBehaviour.cpp | mipelius/spacegame | 7cbc62d6b47afdea11a7775d25f9e91c900cc627 | [
"MIT"
] | null | null | null | Game/SceneInGame/BackgroundBehaviour.cpp | mipelius/spacegame | 7cbc62d6b47afdea11a7775d25f9e91c900cc627 | [
"MIT"
] | null | null | null | Game/SceneInGame/BackgroundBehaviour.cpp | mipelius/spacegame | 7cbc62d6b47afdea11a7775d25f9e91c900cc627 | [
"MIT"
] | null | null | null | // MIT License
//
// This file is part of SpaceGame.
// Copyright (c) 2014-2018 Miika Pelkonen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "MusicManager.h"
#include "BackgroundBehaviour.h"
#include "Tile2D.h"
#include "Tile2DMath.h"
#include "Camera.h"
#include "GameObject.h"
#include "AudioSource.h"
#include "t2Time.h"
#include "AudioClip.h"
#include "Resources.h"
void BackgroundBehaviour::awake() {
bg_ = gameObject()->getComponent<Background>();
}
void BackgroundBehaviour::update() {
}
void BackgroundBehaviour::lateUpdate() {
Camera* camera = Tile2D::canvas().getCamera();
float opacity = bg_->getOpacity();
if (area_.hasPointInside(camera->getPosition())) {
MusicManager::getInstance()->play(music_);
opacity += fadeInOutSpeed_ * Tile2D::time().getDeltaTime();
} else {
opacity -= fadeInOutSpeed_ * Tile2D::time().getDeltaTime();
}
Mathf::clamp(opacity, 0.0f, 1.0f);
bg_->setOpacity(opacity);
}
void BackgroundBehaviour::setArea(const Rect &area) {
BackgroundBehaviour::area_ = area;
}
void BackgroundBehaviour::deserialize(const json::Object &jsonObject) {
if (jsonObject.HasKey("area")) {
area_.deserialize(jsonObject["area"].ToObject());
}
if (jsonObject.HasKey("fadeOutSpeed")) {
fadeInOutSpeed_ = jsonObject["fadeOutSpeed"].ToFloat();
}
if (jsonObject.HasKey("music")) {
auto musicName = jsonObject["music"].ToString();
music_ = Tile2D::resources().audioClips[musicName];
}
}
Tile2DComponent *BackgroundBehaviour::clone() {
return new BackgroundBehaviour(*this);
}
| 32.353659 | 81 | 0.713532 | [
"object"
] |
525b951b787e2678a26e601d80be6f5eb45dea1a | 2,891 | cpp | C++ | LinaGraphics/src/Rendering/Shader.cpp | zeta1999/LinaEngine | 554a2dda68edb3dd121da67a00064ba741a7864f | [
"MIT"
] | 261 | 2018-10-14T19:14:47.000Z | 2022-03-31T23:38:29.000Z | LinaGraphics/src/Rendering/Shader.cpp | zeta1999/LinaEngine | 554a2dda68edb3dd121da67a00064ba741a7864f | [
"MIT"
] | 38 | 2018-10-14T18:39:53.000Z | 2021-12-06T17:36:17.000Z | LinaGraphics/src/Rendering/Shader.cpp | inanevin/LinaEngine | 554a2dda68edb3dd121da67a00064ba741a7864f | [
"MIT"
] | 26 | 2018-10-31T16:13:35.000Z | 2022-03-25T08:43:34.000Z | /*
This file is a part of: Lina Engine
https://github.com/inanevin/LinaEngine
Author: Inan Evin
http://www.inanevin.com
Copyright (c) [2018-2020] [Inan Evin]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "Rendering/Shader.hpp"
#include "Rendering/RenderEngine.hpp"
#include "Utility/UtilityFunctions.hpp"
namespace LinaEngine::Graphics
{
std::map<int, Shader*> Shader::s_loadedShaders;
Shader& Shader::CreateShader(const std::string& path, bool usesGeometryShader)
{
std::string shaderText;
Utility::LoadTextFileWithIncludes(shaderText, path, "#include");
Shader* shader = new Shader();
shader->Construct(RenderEngine::GetRenderDevice(), shaderText, usesGeometryShader);
shader->m_path = path;
s_loadedShaders[shader->GetID()] = shader;
return *shader;
}
Shader& Shader::GetShader(const std::string& path)
{
const auto it = std::find_if(s_loadedShaders.begin(), s_loadedShaders.end(), [path]
(const auto& item) -> bool { return item.second->GetPath().compare(path) == 0; });
if (it == s_loadedShaders.end())
{
// Mesh not found.
LINA_CORE_WARN("Shader with the path {0} was not found, returning un-constructed shader", path);
return Shader();
}
return *it->second;
}
Shader& Shader::GetShader(int id)
{
return *s_loadedShaders[id];
}
bool Shader::ShaderExists(const std::string& path)
{
const auto it = std::find_if(s_loadedShaders.begin(), s_loadedShaders.end(), [path]
(const auto& it) -> bool { return it.second->GetPath().compare(path) == 0; });
return it != s_loadedShaders.end();
}
bool Shader::ShaderExists(int id)
{
if (id < 0) return false;
return !(s_loadedShaders.find(id) == s_loadedShaders.end());
}
void Shader::UnloadAll()
{
// Delete textures.
for (std::map<int, Shader*>::iterator it = s_loadedShaders.begin(); it != s_loadedShaders.end(); it++)
delete it->second;
s_loadedShaders.clear();
}
} | 32.122222 | 104 | 0.733656 | [
"mesh"
] |
52632d7ce5cc87a4ec8d00c392b0f694478ba8a7 | 14,344 | cpp | C++ | apps/changedet/src/main.cpp | ln1equals0/litiv-a | 4a82fbc570b7abecb40a03d9e08cf42920f07fce | [
"Apache-2.0"
] | null | null | null | apps/changedet/src/main.cpp | ln1equals0/litiv-a | 4a82fbc570b7abecb40a03d9e08cf42920f07fce | [
"Apache-2.0"
] | null | null | null | apps/changedet/src/main.cpp | ln1equals0/litiv-a | 4a82fbc570b7abecb40a03d9e08cf42920f07fce | [
"Apache-2.0"
] | null | null | null |
// This file is part of the LITIV framework; visit the original repository at
// https://github.com/plstcharles/litiv for more information.
//
// Copyright 2015 Pierre-Luc St-Charles; pierre-luc.st-charles<at>polymtl.ca
//
// 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.
// @@@ imgproc gpu algo does not support mipmapping binding yet
// @@@ test compute shader group size vs shared mem usage
// @@@ support non-integer textures top level (alg)? need to replace all ui-stores by float-stores, rest is ok
#include "litiv/datasets.hpp"
#include "litiv/video.hpp"
////////////////////////////////
#define WRITE_IMG_OUTPUT 0
#define EVALUATE_OUTPUT 0
#define DISPLAY_OUTPUT 1
////////////////////////////////
#define USE_PAWCS 1
#define USE_LOBSTER 0
#define USE_SUBSENSE 0
////////////////////////////////
#define USE_GLSL_IMPL 0
#define USE_CUDA_IMPL 0
#define USE_OPENCL_IMPL 0
////////////////////////////////
#define DATASET_ID Dataset_CDnet // comment this line to fall back to custom dataset definition
#define DATASET_OUTPUT_PATH "results_test" // will be created in the app's working directory if using a custom dataset
#define DATASET_PRECACHING 1
#define DATASET_SCALE_FACTOR 1.0
#define DATASET_WORKTHREADS 1
////////////////////////////////
#define USE_GPU_IMPL (USE_GLSL_IMPL||USE_CUDA_IMPL||USE_OPENCL_IMPL)
#if (USE_GLSL_IMPL+USE_CUDA_IMPL+USE_OPENCL_IMPL)>1
#error "Must specify a single impl."
#elif (USE_LOBSTER+USE_SUBSENSE+USE_PAWCS)!=1
#error "Must specify a single algorithm."
#endif //USE_...
#ifndef DATASET_ID
#define DATASET_ID Dataset_Custom
#define DATASET_PARAMS \
"@@@@", /* => const std::string& sDatasetName */ \
"@@@@", /* => const std::string& sDatasetDirPath */ \
DATASET_OUTPUT_PATH, /* => const std::string& sOutputDirPath */ \
"segm_mask_", /* => const std::string& sOutputNamePrefix */ \
".png", /* => const std::string& sOutputNameSuffix */ \
std::vector<std::string>{"@@@","@@@","@@@","..."}, /* => const std::vector<std::string>& vsWorkBatchDirs */ \
std::vector<std::string>{"@@@","@@@","@@@","..."}, /* => const std::vector<std::string>& vsSkippedDirTokens */ \
std::vector<std::string>{"@@@","@@@","@@@","..."}, /* => const std::vector<std::string>& vsGrayscaleDirTokens */ \
bool(WRITE_IMG_OUTPUT), /* => bool bSaveOutput */ \
bool(EVALUATE_OUTPUT), /* => bool bUseEvaluator */ \
bool(USE_GPU_IMPL), /* => bool bForce4ByteDataAlign */ \
DATASET_SCALE_FACTOR /* => double dScaleFactor */
#else //defined(DATASET_ID)
#define DATASET_PARAMS \
DATASET_OUTPUT_PATH, /* => const std::string& sOutputDirName */ \
bool(WRITE_IMG_OUTPUT), /* => bool bSaveOutput */ \
bool(EVALUATE_OUTPUT), /* => bool bUseEvaluator */ \
bool(USE_GPU_IMPL), /* => bool bForce4ByteDataAlign */ \
DATASET_SCALE_FACTOR /* => double dScaleFactor */
#endif //defined(DATASET_ID)
void Analyze(std::string sWorkerName, lv::IDataHandlerPtr pBatch);
#if USE_GLSL_IMPL
constexpr lv::ParallelAlgoType eImplTypeEnum = lv::GLSL;
#else // USE_..._IMPL
constexpr lv::ParallelAlgoType eImplTypeEnum = lv::NonParallel;
#endif // USE_..._IMPL
using DatasetType = lv::Dataset_<lv::DatasetTask_Segm,lv::DATASET_ID,eImplTypeEnum>;
#if USE_LOBSTER
using BackgroundSubtractorType = BackgroundSubtractorLOBSTER_<eImplTypeEnum>;
#elif USE_SUBSENSE
using BackgroundSubtractorType = BackgroundSubtractorSuBSENSE_<eImplTypeEnum>;
#elif USE_PAWCS
using BackgroundSubtractorType = BackgroundSubtractorPAWCS_<eImplTypeEnum>;
#endif //USE_...
int main(int, char**) {
try {
DatasetType::Ptr pDataset = DatasetType::create(DATASET_PARAMS);
lv::IDataHandlerPtrArray vpBatches = pDataset->getBatches(false);
const size_t nTotPackets = pDataset->getInputCount();
const size_t nTotBatches = vpBatches.size();
if(nTotBatches==0 || nTotPackets==0)
lvError_("Could not parse any data for dataset '%s'",pDataset->getName().c_str());
std::cout << "Parsing complete. [" << nTotBatches << " batch(es)]" << std::endl;
std::cout << "\n[" << lv::getTimeStamp() << "]\n" << std::endl;
std::cout << "Executing algorithm with " << (USE_GPU_IMPL?1:DATASET_WORKTHREADS) << " thread(s)..." << std::endl;
lv::WorkerPool<(USE_GPU_IMPL?1:DATASET_WORKTHREADS)> oPool;
std::vector<std::future<void>> vTaskResults;
for(lv::IDataHandlerPtr pBatch : vpBatches)
vTaskResults.push_back(oPool.queueTask(Analyze,std::to_string(nTotBatches-vpBatches.size()+1)+"/"+std::to_string(nTotBatches),pBatch));
for(std::future<void>& oTaskRes : vTaskResults)
oTaskRes.get();
pDataset->writeEvalReport();
}
catch(const cv::Exception& e) {std::cout << "\n!!!!!!!!!!!!!!\nTop level caught cv::Exception:\n" << e.what() << "\n!!!!!!!!!!!!!!\n" << std::endl; return -1;}
catch(const std::exception& e) {std::cout << "\n!!!!!!!!!!!!!!\nTop level caught std::exception:\n" << e.what() << "\n!!!!!!!!!!!!!!\n" << std::endl; return -1;}
catch(...) {std::cout << "\n!!!!!!!!!!!!!!\nTop level caught unhandled exception\n!!!!!!!!!!!!!!\n" << std::endl; return -1;}
std::cout << "\n[" << lv::getTimeStamp() << "]\n" << std::endl;
return 0;
}
#if (HAVE_GLSL && USE_GLSL_IMPL)
void Analyze(std::string sWorkerName, lv::IDataHandlerPtr pBatch) {
srand(0); // for now, assures that two consecutive runs on the same data return the same results
//srand((unsigned int)time(NULL));
try {
DatasetType::WorkBatch& oBatch = dynamic_cast<DatasetType::WorkBatch&>(*pBatch);
lvAssert(oBatch.getInputPacketType()==lv::ImagePacket && oBatch.getOutputPacketType()==lv::ImagePacket);
lvAssert(oBatch.getFrameCount()>1);
if(DATASET_PRECACHING)
oBatch.startPrecaching(EVALUATE_OUTPUT);
const std::string sCurrBatchName = lv::clampString(oBatch.getName(),12);
std::cout << "\t\t" << sCurrBatchName << " @ init [" << sWorkerName << "]" << std::endl;
const size_t nTotPacketCount = oBatch.getFrameCount();
lv::gl::Context oContext(oBatch.getFrameSize(),oBatch.getName()+" [GPU]",DISPLAY_OUTPUT==0);
std::shared_ptr<IBackgroundSubtractor_<lv::GLSL>> pAlgo = std::make_shared<BackgroundSubtractorType>();
#if DISPLAY_OUTPUT>1
cv::DisplayHelperPtr pDisplayHelper = cv::DisplayHelper::create(oBatch.getName(),oBatch.getOutputPath()+"../");
pAlgo->m_pDisplayHelper = pDisplayHelper;
#endif //DISPLAY_OUTPUT>1
const double dDefaultLearningRate = pAlgo->getDefaultLearningRate();
oBatch.initialize_gl(pAlgo);
oContext.setWindowSize(oBatch.getIdealGLWindowSize());
oBatch.startProcessing();
size_t nNextIdx = 1;
while(nNextIdx<=nTotPacketCount) {
if(!((nNextIdx+1)%100))
std::cout << "\t\t" << sCurrBatchName << " @ F:" << std::setfill('0') << std::setw(lv::digit_count((int)nTotPacketCount)) << nNextIdx+1 << "/" << nTotPacketCount << " [" << sWorkerName << "]" << std::endl;
const double dCurrLearningRate = nNextIdx<=100?1:dDefaultLearningRate;
oBatch.apply_gl(pAlgo,nNextIdx++,false,dCurrLearningRate);
//pGLSLAlgoEvaluator->apply_gl(oNextGTMask);
glErrorCheck;
if(oContext.pollEventsAndCheckIfShouldClose())
break;
#if DISPLAY_OUTPUT>0
if(oContext.getKeyPressed('q'))
break;
oContext.swapBuffers(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
#if DISPLAY_OUTPUT>1
const int nKeyPressed = pDisplayHelper->waitKey();
if(nKeyPressed==(int)'q')
break;
#endif //DISPLAY_OUTPUT>1
#endif //DISPLAY_OUTPUT>0
}
oBatch.stopProcessing();
const double dTimeElapsed = oBatch.getFinalProcessTime();
const double dProcessSpeed = (double)(nNextIdx-1)/dTimeElapsed;
std::cout << "\t\t" << sCurrBatchName << " @ end [" << sWorkerName << "] (" << std::fixed << std::setw(4) << dTimeElapsed << " sec, " << std::setw(4) << dProcessSpeed << " Hz)" << std::endl;
oBatch.writeEvalReport(); // this line is optional; it allows results to be read before all batches are processed
}
catch(const lv::Exception& e) {
std::cout << "\nAnalyze caught Exception:\n" << e.what();
const std::string sContextErrMsg = lv::gl::Context::getLatestErrorMessage();
if(!sContextErrMsg.empty())
std::cout << "\nContext error: " << sContextErrMsg << "\n" << std::endl;
}
catch(const cv::Exception& e) {std::cout << "\nAnalyze caught cv::Exception:\n" << e.what() << "\n" << std::endl;}
catch(const std::exception& e) {std::cout << "\nAnalyze caught std::exception:\n" << e.what() << "\n" << std::endl;}
catch(...) {std::cout << "\nAnalyze caught unhandled exception\n" << std::endl;}
try {
if(pBatch->isProcessing())
dynamic_cast<DatasetType::WorkBatch&>(*pBatch).stopProcessing();
} catch(...) {
std::cout << "\nAnalyze caught unhandled exception while attempting to stop batch processing.\n" << std::endl;
throw;
}
}
#elif (HAVE_CUDA && USE_CUDA_IMPL)
static_assert(false,"missing impl");
#elif (HAVE_OPENCL && USE_OPENCL_IMPL)
static_assert(false,"missing impl");
#elif !USE_GPU_IMPL
void Analyze(std::string sWorkerName, lv::IDataHandlerPtr pBatch) {
srand(0); // for now, assures that two consecutive runs on the same data return the same results
//srand((unsigned int)time(NULL));
try {
DatasetType::WorkBatch& oBatch = dynamic_cast<DatasetType::WorkBatch&>(*pBatch);
lvAssert(oBatch.getInputPacketType()==lv::ImagePacket && oBatch.getOutputPacketType()==lv::ImagePacket);
lvAssert(oBatch.getFrameCount()>1);
if(DATASET_PRECACHING)
oBatch.startPrecaching(EVALUATE_OUTPUT);
const std::string sCurrBatchName = lv::clampString(oBatch.getName(),12);
std::cout << "\t\t" << sCurrBatchName << " @ init [" << sWorkerName << "]" << std::endl;
const size_t nTotPacketCount = oBatch.getFrameCount();
const cv::Mat& oROI = oBatch.getFrameROI();
size_t nCurrIdx = 0;
cv::Mat oCurrInput = oBatch.getInput(nCurrIdx).clone();
lvAssert(!oCurrInput.empty() && oCurrInput.isContinuous());
cv::Mat oCurrFGMask(oBatch.getFrameSize(),CV_8UC1,cv::Scalar_<uchar>(0));
std::shared_ptr<IBackgroundSubtractor> pAlgo = std::make_shared<BackgroundSubtractorType>();
const double dDefaultLearningRate = pAlgo->getDefaultLearningRate();
pAlgo->initialize(oCurrInput,oROI);
#if DISPLAY_OUTPUT>0
cv::DisplayHelperPtr pDisplayHelper = cv::DisplayHelper::create(oBatch.getName(),oBatch.getOutputPath()+"../");
pAlgo->m_pDisplayHelper = pDisplayHelper;
#endif //DISPLAY_OUTPUT>0
oBatch.startProcessing();
while(nCurrIdx<nTotPacketCount) {
if(!((nCurrIdx+1)%100))
std::cout << "\t\t" << sCurrBatchName << " @ F:" << std::setfill('0') << std::setw(lv::digit_count((int)nTotPacketCount)) << nCurrIdx+1 << "/" << nTotPacketCount << " [" << sWorkerName << "]" << std::endl;
const double dCurrLearningRate = nCurrIdx<=100?1:dDefaultLearningRate;
oCurrInput = oBatch.getInput(nCurrIdx);
pAlgo->apply(oCurrInput,oCurrFGMask,dCurrLearningRate);
#if DISPLAY_OUTPUT>0
cv::Mat oCurrBGImg;
pAlgo->getBackgroundImage(oCurrBGImg);
if(!oROI.empty()) {
cv::bitwise_or(oCurrBGImg,UCHAR_MAX/2,oCurrBGImg,oROI==0);
cv::bitwise_or(oCurrFGMask,UCHAR_MAX/2,oCurrFGMask,oROI==0);
}
pDisplayHelper->display(oCurrInput,oCurrBGImg,oBatch.getColoredMask(oCurrFGMask,nCurrIdx),nCurrIdx);
const int nKeyPressed = pDisplayHelper->waitKey();
if(nKeyPressed==(int)'q')
break;
#endif //DISPLAY_OUTPUT>0
oBatch.push(oCurrFGMask,nCurrIdx++);
}
oBatch.stopProcessing();
const double dTimeElapsed = oBatch.getFinalProcessTime();
const double dProcessSpeed = (double)nCurrIdx/dTimeElapsed;
std::cout << "\t\t" << sCurrBatchName << " @ end [" << sWorkerName << "] (" << std::fixed << std::setw(4) << dTimeElapsed << " sec, " << std::setw(4) << dProcessSpeed << " Hz)" << std::endl;
oBatch.writeEvalReport(); // this line is optional; it allows results to be read before all batches are processed
}
catch(const cv::Exception& e) {std::cout << "\nAnalyze caught cv::Exception:\n" << e.what() << "\n" << std::endl;}
catch(const std::exception& e) {std::cout << "\nAnalyze caught std::exception:\n" << e.what() << "\n" << std::endl;}
catch(...) {std::cout << "\nAnalyze caught unhandled exception\n" << std::endl;}
try {
if(pBatch->isProcessing())
dynamic_cast<DatasetType::WorkBatch&>(*pBatch).stopProcessing();
} catch(...) {
std::cout << "\nAnalyze caught unhandled exception while attempting to stop batch processing.\n" << std::endl;
throw;
}
}
#endif //(!USE_GPU_IMPL)
| 57.376 | 221 | 0.612521 | [
"vector"
] |
52647a8d720c58a99baf7267be6ae650939b4ed0 | 10,242 | cpp | C++ | tests/cpp/core/TextureSwitcherTests.cpp | BlueBrain/Tide | 01e0518117509eaa0ccd9d79f067f385b641247c | [
"BSD-2-Clause"
] | 47 | 2016-07-12T02:00:11.000Z | 2021-07-06T17:50:53.000Z | tests/cpp/core/TextureSwitcherTests.cpp | BlueBrain/Tide | 01e0518117509eaa0ccd9d79f067f385b641247c | [
"BSD-2-Clause"
] | 135 | 2016-03-24T14:02:26.000Z | 2019-10-25T09:43:59.000Z | tests/cpp/core/TextureSwitcherTests.cpp | BlueBrain/Tide | 01e0518117509eaa0ccd9d79f067f385b641247c | [
"BSD-2-Clause"
] | 17 | 2016-03-23T13:34:48.000Z | 2022-03-21T03:21:54.000Z | /*********************************************************************/
/* Copyright (c) 2017, EPFL/Blue Brain Project */
/* Raphael Dumusc <raphael.dumusc@epfl.ch> */
/* 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 ECOLE POLYTECHNIQUE */
/* FEDERALE DE LAUSANNE ''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 ECOLE */
/* POLYTECHNIQUE FEDERALE DE LAUSANNE 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. */
/* */
/* The views and conclusions contained in the software and */
/* documentation are those of the authors and should not be */
/* interpreted as representing official policies, either expressed */
/* or implied, of Ecole polytechnique federale de Lausanne. */
/*********************************************************************/
#define BOOST_TEST_MODULE TextureSwitcherTests
#include <boost/test/unit_test.hpp>
#include "data/Image.h"
#include "qml/TextureSwitcher.h"
class MockTextureNode : public TextureNode
{
public:
explicit MockTextureNode(const TextureFormat f)
: format{f}
{
}
virtual QRectF getCoord() const { return coord; }
virtual void setCoord(const QRectF& rect) { coord = rect; }
virtual void uploadTexture(const Image& im) { image = &im; }
virtual void swap() { swapped = true; }
TextureFormat format;
QRectF coord;
const Image* image = nullptr;
bool swapped = false;
};
class MockTextureNodeFactory : public TextureNodeFactory
{
public:
std::unique_ptr<TextureNode> create(TextureFormat format) final
{
return std::make_unique<MockTextureNode>(format);
}
bool needToChangeNodeType(TextureFormat a, TextureFormat b) const final
{
return a != b;
}
};
class MockImage : public Image
{
public:
MockImage() = default;
MockImage(TextureFormat format)
: _format{format}
{
}
int getWidth() const { return 0; }
int getHeight() const { return 0; }
const uint8_t* getData(uint) const { return nullptr; }
TextureFormat getFormat() const { return _format; }
uint getGLPixelFormat() const { return 0; }
private:
TextureFormat _format = TextureFormat::rgba;
};
class MockTextureSwitcher : public TextureSwitcher
{
public:
void aboutToSwitch(TextureNode&, TextureNode&) final
{
switchedTextureNodes = true;
}
bool switchedTextureNodes = false;
};
inline std::ostream& operator<<(std::ostream& str, const TextureFormat t)
{
switch (t)
{
case TextureFormat::rgba:
str << "rgba";
break;
case TextureFormat::yuv420:
str << "yuv420";
break;
case TextureFormat::yuv422:
str << "yuv422";
break;
case TextureFormat::yuv444:
str << "yuv444";
break;
default:
str << "INVALID";
break;
}
return str;
}
struct Fixture
{
MockTextureNodeFactory factory;
MockTextureSwitcher switcher;
std::unique_ptr<TextureNode> textureNode;
};
BOOST_FIXTURE_TEST_CASE(update_null_texture_with_no_image_returns_null, Fixture)
{
switcher.update(textureNode, factory);
BOOST_CHECK(textureNode == nullptr);
}
BOOST_FIXTURE_TEST_CASE(update_null_texture_with_image_returns_texture, Fixture)
{
auto image = std::make_shared<MockImage>(TextureFormat::yuv422);
switcher.setNextImage(image);
switcher.update(textureNode, factory);
BOOST_REQUIRE(textureNode != nullptr);
auto node = dynamic_cast<MockTextureNode*>(textureNode.get());
BOOST_REQUIRE(node != nullptr);
BOOST_CHECK_EQUAL(node->format, image->getFormat());
BOOST_CHECK(!switcher.switchedTextureNodes);
}
BOOST_FIXTURE_TEST_CASE(updating_texture_multiple_times_returns_input, Fixture)
{
auto image = std::make_shared<MockImage>(TextureFormat::yuv422);
switcher.setNextImage(image);
switcher.update(textureNode, factory);
BOOST_REQUIRE(textureNode != nullptr);
const auto firstTextureNode = textureNode.get();
for (int i = 0; i < 10; ++i)
{
switcher.update(textureNode, factory);
BOOST_CHECK_EQUAL(textureNode.get(), firstTextureNode);
}
BOOST_CHECK(!switcher.switchedTextureNodes);
}
struct ImagesFixture : public Fixture
{
std::vector<ImagePtr> images;
ImagesFixture()
{
for (int i = 0; i < 10; ++i)
images.emplace_back(std::make_shared<MockImage>());
}
void updateSwitcher(ImagePtr image)
{
switcher.setNextImage(image);
switcher.requestSwap();
switcher.update(textureNode, factory);
}
};
BOOST_FIXTURE_TEST_CASE(swap_without_new_images_does_not_work, ImagesFixture)
{
updateSwitcher(images[0]);
switcher.update(textureNode, factory);
auto& node = dynamic_cast<MockTextureNode&>(*textureNode);
BOOST_REQUIRE(node.swapped);
BOOST_REQUIRE_EQUAL(node.image, images[0].get());
node.swapped = false;
for (int i = 0; i < 10; ++i)
{
switcher.requestSwap();
switcher.update(textureNode, factory);
node = dynamic_cast<MockTextureNode&>(*textureNode);
BOOST_CHECK_EQUAL(node.image, images[0].get());
BOOST_CHECK(!node.swapped);
}
BOOST_CHECK(!switcher.switchedTextureNodes);
}
BOOST_FIXTURE_TEST_CASE(update_image_multiple_times_without_swap, ImagesFixture)
{
for (int i = 0; i < 10; ++i)
{
switcher.setNextImage(images[i]);
switcher.update(textureNode, factory);
auto& node = dynamic_cast<MockTextureNode&>(*textureNode);
BOOST_CHECK_EQUAL(node.image, images[i].get());
BOOST_CHECK(!node.swapped);
}
BOOST_CHECK(!switcher.switchedTextureNodes);
}
BOOST_FIXTURE_TEST_CASE(update_and_swap_texture_multiple_times, ImagesFixture)
{
for (int i = 0; i < 10; ++i)
{
updateSwitcher(images[i]);
auto& node = dynamic_cast<MockTextureNode&>(*textureNode);
BOOST_CHECK_EQUAL(node.image, images[i].get());
BOOST_CHECK(node.swapped || i == 0);
node.swapped = false;
}
BOOST_CHECK(!switcher.switchedTextureNodes);
}
BOOST_FIXTURE_TEST_CASE(switch_texture_type_once, ImagesFixture)
{
for (int i = 0; i < 5; ++i)
images[i] = std::make_shared<MockImage>(TextureFormat::yuv444);
for (int i = 0; i < 10; ++i)
{
updateSwitcher(images[i]);
auto& node = dynamic_cast<MockTextureNode&>(*textureNode);
// When switching texture type, the image is uploaded to an internal
// texture node and the previous texture node is swapped + returned.
// The new image is "seen" here after the next swap (one frame delay).
BOOST_CHECK_EQUAL(node.image, images[i].get());
BOOST_CHECK_EQUAL(node.format, images[i]->getFormat());
BOOST_CHECK(node.swapped || i == 0);
node.swapped = false;
BOOST_CHECK(!switcher.switchedTextureNodes || i == 0 || i == 5);
switcher.switchedTextureNodes = false;
}
}
BOOST_FIXTURE_TEST_CASE(switch_texture_type_twice, ImagesFixture)
{
for (int i = 0; i < 5; ++i)
images[i] = std::make_shared<MockImage>(TextureFormat::yuv444);
images[5] = std::make_shared<MockImage>(TextureFormat::yuv420);
for (int i = 0; i < 10; ++i)
{
updateSwitcher(images[i]);
auto& node = dynamic_cast<MockTextureNode&>(*textureNode);
BOOST_CHECK_EQUAL(node.image, images[i].get());
BOOST_CHECK_EQUAL(node.format, images[i]->getFormat());
BOOST_CHECK(node.swapped || i == 0);
node.swapped = false;
BOOST_CHECK(!switcher.switchedTextureNodes || i == 0 || i == 5 ||
i == 6);
switcher.switchedTextureNodes = false;
}
}
BOOST_FIXTURE_TEST_CASE(switch_texture_type_repeatedly, ImagesFixture)
{
for (int i = 0; i < 10; ++i)
images[i] = std::make_shared<MockImage>(TextureFormat(i % 4));
for (int i = 0; i < 10; ++i)
{
updateSwitcher(images[i]);
auto& node = dynamic_cast<MockTextureNode&>(*textureNode);
BOOST_CHECK_EQUAL(node.image, images[i].get());
BOOST_CHECK_EQUAL(node.format, images[i]->getFormat());
BOOST_CHECK(node.swapped || i == 0);
node.swapped = false;
BOOST_CHECK(switcher.switchedTextureNodes || i == 0);
switcher.switchedTextureNodes = false;
}
}
| 33.913907 | 80 | 0.611502 | [
"vector"
] |
52691958965593ee1f0ada7f01086b025c4108d3 | 190 | hpp | C++ | src/afk/physics/shape/Box.hpp | christocs/ICT398 | 9fd7c17a72985ac2eb59a13c1d3761598e544771 | [
"ISC"
] | null | null | null | src/afk/physics/shape/Box.hpp | christocs/ICT398 | 9fd7c17a72985ac2eb59a13c1d3761598e544771 | [
"ISC"
] | null | null | null | src/afk/physics/shape/Box.hpp | christocs/ICT398 | 9fd7c17a72985ac2eb59a13c1d3761598e544771 | [
"ISC"
] | null | null | null | #pragma once
#include "glm/vec3.hpp"
namespace afk {
namespace physics {
namespace shape {
/**
* Box, as half extents
*/
using Box = glm::vec3;
}
}
}
| 12.666667 | 29 | 0.526316 | [
"shape"
] |
526c7a498e72a2b52e3eb70014116f7cd66fa74f | 8,889 | cc | C++ | cc/layers/picture_layer.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 1 | 2020-09-15T08:43:34.000Z | 2020-09-15T08:43:34.000Z | cc/layers/picture_layer.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | cc/layers/picture_layer.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/layers/picture_layer.h"
#include "base/auto_reset.h"
#include "base/trace_event/trace_event.h"
#include "cc/layers/content_layer_client.h"
#include "cc/layers/picture_layer_impl.h"
#include "cc/playback/recording_source.h"
#include "cc/proto/cc_conversions.h"
#include "cc/proto/gfx_conversions.h"
#include "cc/proto/layer.pb.h"
#include "cc/trees/layer_tree_host.h"
#include "cc/trees/layer_tree_impl.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"
#include "ui/gfx/geometry/rect_conversions.h"
namespace cc {
scoped_refptr<PictureLayer> PictureLayer::Create(ContentLayerClient* client) {
return make_scoped_refptr(new PictureLayer(client));
}
PictureLayer::PictureLayer(ContentLayerClient* client)
: client_(client),
instrumentation_object_tracker_(id()),
update_source_frame_number_(-1),
is_mask_(false),
nearest_neighbor_(false) {}
PictureLayer::PictureLayer(ContentLayerClient* client,
std::unique_ptr<RecordingSource> source)
: PictureLayer(client) {
recording_source_ = std::move(source);
}
PictureLayer::~PictureLayer() {
}
std::unique_ptr<LayerImpl> PictureLayer::CreateLayerImpl(
LayerTreeImpl* tree_impl) {
return PictureLayerImpl::Create(tree_impl, id(), is_mask_);
}
void PictureLayer::PushPropertiesTo(LayerImpl* base_layer) {
Layer::PushPropertiesTo(base_layer);
TRACE_EVENT0("cc", "PictureLayer::PushPropertiesTo");
PictureLayerImpl* layer_impl = static_cast<PictureLayerImpl*>(base_layer);
// TODO(danakj): Make is_mask_ a constructor parameter for PictureLayer.
DCHECK_EQ(layer_impl->is_mask(), is_mask_);
DropRecordingSourceContentIfInvalid();
layer_impl->SetNearestNeighbor(nearest_neighbor_);
// Preserve lcd text settings from the current raster source.
bool can_use_lcd_text = layer_impl->RasterSourceUsesLCDText();
scoped_refptr<RasterSource> raster_source =
recording_source_->CreateRasterSource(can_use_lcd_text);
layer_impl->set_gpu_raster_max_texture_size(
layer_tree_host()->device_viewport_size());
layer_impl->UpdateRasterSource(raster_source, &last_updated_invalidation_,
nullptr);
DCHECK(last_updated_invalidation_.IsEmpty());
}
void PictureLayer::SetLayerTreeHost(LayerTreeHost* host) {
Layer::SetLayerTreeHost(host);
if (!host)
return;
if (!recording_source_)
recording_source_.reset(new RecordingSource);
recording_source_->SetSlowdownRasterScaleFactor(
host->debug_state().slow_down_raster_scale_factor);
// If we need to enable image decode tasks, then we have to generate the
// discardable images metadata.
const LayerTreeSettings& settings = layer_tree_host()->settings();
recording_source_->SetGenerateDiscardableImagesMetadata(
settings.image_decode_tasks_enabled);
}
void PictureLayer::SetNeedsDisplayRect(const gfx::Rect& layer_rect) {
DCHECK(!layer_tree_host() || !layer_tree_host()->in_paint_layer_contents());
if (recording_source_)
recording_source_->SetNeedsDisplayRect(layer_rect);
Layer::SetNeedsDisplayRect(layer_rect);
}
bool PictureLayer::Update() {
update_source_frame_number_ = layer_tree_host()->source_frame_number();
bool updated = Layer::Update();
gfx::Size layer_size = paint_properties().bounds;
recording_source_->SetBackgroundColor(SafeOpaqueBackgroundColor());
recording_source_->SetRequiresClear(!contents_opaque() &&
!client_->FillsBoundsCompletely());
TRACE_EVENT1("cc", "PictureLayer::Update",
"source_frame_number",
layer_tree_host()->source_frame_number());
devtools_instrumentation::ScopedLayerTreeTask update_layer(
devtools_instrumentation::kUpdateLayer, id(), layer_tree_host()->id());
// UpdateAndExpandInvalidation will give us an invalidation that covers
// anything not explicitly recorded in this frame. We give this region
// to the impl side so that it drops tiles that may not have a recording
// for them.
DCHECK(client_);
updated |= recording_source_->UpdateAndExpandInvalidation(
client_, &last_updated_invalidation_, layer_size,
update_source_frame_number_, RecordingSource::RECORD_NORMALLY);
if (updated) {
SetNeedsPushProperties();
} else {
// If this invalidation did not affect the recording source, then it can be
// cleared as an optimization.
last_updated_invalidation_.Clear();
}
return updated;
}
void PictureLayer::SetIsMask(bool is_mask) {
is_mask_ = is_mask;
}
sk_sp<SkPicture> PictureLayer::GetPicture() const {
// We could either flatten the RecordingSource into a single
// SkPicture, or paint a fresh one depending on what we intend to do with the
// picture. For now we just paint a fresh one to get consistent results.
if (!DrawsContent())
return nullptr;
gfx::Size layer_size = bounds();
std::unique_ptr<RecordingSource> recording_source(new RecordingSource);
Region recording_invalidation;
recording_source->UpdateAndExpandInvalidation(
client_, &recording_invalidation, layer_size, update_source_frame_number_,
RecordingSource::RECORD_NORMALLY);
scoped_refptr<RasterSource> raster_source =
recording_source->CreateRasterSource(false);
return raster_source->GetFlattenedPicture();
}
bool PictureLayer::IsSuitableForGpuRasterization() const {
return recording_source_->IsSuitableForGpuRasterization();
}
void PictureLayer::ClearClient() {
client_ = nullptr;
UpdateDrawsContent(HasDrawableContent());
}
void PictureLayer::SetNearestNeighbor(bool nearest_neighbor) {
if (nearest_neighbor_ == nearest_neighbor)
return;
nearest_neighbor_ = nearest_neighbor;
SetNeedsCommit();
}
bool PictureLayer::HasDrawableContent() const {
return client_ && Layer::HasDrawableContent();
}
void PictureLayer::SetTypeForProtoSerialization(proto::LayerNode* proto) const {
proto->set_type(proto::LayerNode::PICTURE_LAYER);
}
void PictureLayer::LayerSpecificPropertiesToProto(
proto::LayerProperties* proto) {
Layer::LayerSpecificPropertiesToProto(proto);
DropRecordingSourceContentIfInvalid();
proto::PictureLayerProperties* picture = proto->mutable_picture();
recording_source_->ToProtobuf(
picture->mutable_recording_source(),
layer_tree_host()->image_serialization_processor());
RegionToProto(last_updated_invalidation_, picture->mutable_invalidation());
picture->set_is_mask(is_mask_);
picture->set_nearest_neighbor(nearest_neighbor_);
picture->set_update_source_frame_number(update_source_frame_number_);
last_updated_invalidation_.Clear();
}
void PictureLayer::FromLayerSpecificPropertiesProto(
const proto::LayerProperties& proto) {
Layer::FromLayerSpecificPropertiesProto(proto);
const proto::PictureLayerProperties& picture = proto.picture();
// If this is a new layer, ensure it has a recording source. During layer
// hierarchy deserialization, ::SetLayerTreeHost(...) is not called, but
// instead the member is set directly, so it needs to be set here explicitly.
if (!recording_source_)
recording_source_.reset(new RecordingSource);
recording_source_->FromProtobuf(
picture.recording_source(),
layer_tree_host()->image_serialization_processor());
Region new_invalidation = RegionFromProto(picture.invalidation());
last_updated_invalidation_.Swap(&new_invalidation);
is_mask_ = picture.is_mask();
nearest_neighbor_ = picture.nearest_neighbor();
update_source_frame_number_ = picture.update_source_frame_number();
}
void PictureLayer::RunMicroBenchmark(MicroBenchmark* benchmark) {
benchmark->RunOnLayer(this);
}
void PictureLayer::DropRecordingSourceContentIfInvalid() {
int source_frame_number = layer_tree_host()->source_frame_number();
gfx::Size recording_source_bounds = recording_source_->GetSize();
gfx::Size layer_bounds = bounds();
if (paint_properties().source_frame_number == source_frame_number)
layer_bounds = paint_properties().bounds;
// If update called, then recording source size must match bounds pushed to
// impl layer.
DCHECK(update_source_frame_number_ != source_frame_number ||
layer_bounds == recording_source_bounds)
<< " bounds " << layer_bounds.ToString() << " recording source "
<< recording_source_bounds.ToString();
if (update_source_frame_number_ != source_frame_number &&
recording_source_bounds != layer_bounds) {
// Update may not get called for the layer (if it's not in the viewport
// for example), even though it has resized making the recording source no
// longer valid. In this case just destroy the recording source.
recording_source_->SetEmptyBounds();
}
}
} // namespace cc
| 36.281633 | 80 | 0.759928 | [
"geometry"
] |
527754d8ad7d03b6040b6f4b1d3bf70e90aeab39 | 696 | cpp | C++ | Leetcode/Merge_Sorted_Array_in_the_first_Array.cpp | anishacharya/Cracking-Coding-Interviews | f94e70c240ad9a76eddf22b8f4d5b4185c611a71 | [
"MIT"
] | 1 | 2019-03-24T12:35:43.000Z | 2019-03-24T12:35:43.000Z | Leetcode/Merge_Sorted_Array_in_the_first_Array.cpp | anishacharya/Cracking-Coding-Interviews | f94e70c240ad9a76eddf22b8f4d5b4185c611a71 | [
"MIT"
] | null | null | null | Leetcode/Merge_Sorted_Array_in_the_first_Array.cpp | anishacharya/Cracking-Coding-Interviews | f94e70c240ad9a76eddf22b8f4d5b4185c611a71 | [
"MIT"
] | null | null | null | class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
int k=m+n-1;
int i=m-1;
int j=n-1;
while(i>=0 && j>=0)
{
if(nums1[i]>=nums2[j])
{
nums1[k]=nums1[i];
i--;
k--;
}
else if(nums1[i]<nums2[j])
{
nums1[k]=nums2[j];
j--;
k--;
}
}
while(j>=0)
{
nums1[k]=nums2[j];
j--;
k--;
}
}
};
| 22.451613 | 69 | 0.248563 | [
"vector"
] |
52799a2d5345366beeaa18c419de55d47f6070b1 | 6,356 | cpp | C++ | Base/SkGraphicsPipeline.cpp | unrealflow/LearnVulkan | 998ff2fcb99dcb4bb29b601187b21b2c16a4c6f3 | [
"MIT"
] | null | null | null | Base/SkGraphicsPipeline.cpp | unrealflow/LearnVulkan | 998ff2fcb99dcb4bb29b601187b21b2c16a4c6f3 | [
"MIT"
] | null | null | null | Base/SkGraphicsPipeline.cpp | unrealflow/LearnVulkan | 998ff2fcb99dcb4bb29b601187b21b2c16a4c6f3 | [
"MIT"
] | null | null | null | #include "SkGraphicsPipeline.h"
void SkGraphicsPipeline::CreateGraphicsPipeline(uint32_t subpass, uint32_t attachCount,
const std::vector<VkVertexInputBindingDescription> *inputBindings,
const std::vector<VkVertexInputAttributeDescription> *inputAttributes)
{
fprintf(stderr, "Create Pipeline...\n");
SetInput(inputBindings, inputAttributes);
VkPipelineShaderStageCreateInfo vertShaderStageInfo = {};
vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
vertShaderStageInfo.module = vertShaderModule;
vertShaderStageInfo.pName = "main";
VkPipelineShaderStageCreateInfo fragShaderStageInfo = {};
fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
fragShaderStageInfo.module = fragShaderModule;
fragShaderStageInfo.pName = "main";
VkPipelineShaderStageCreateInfo shaderStages[] = {vertShaderStageInfo, fragShaderStageInfo};
VkPipelineInputAssemblyStateCreateInfo inputAssembly = {};
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
inputAssembly.primitiveRestartEnable = VK_FALSE;
VkViewport viewport = {};
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = (float)appBase->width;
viewport.height = (float)appBase->height;
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor = {};
scissor.offset = {0, 0};
scissor.extent = appBase->getExtent();
VkPipelineViewportStateCreateInfo viewportState = {};
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportState.viewportCount = 1;
viewportState.pViewports = &viewport;
viewportState.scissorCount = 1;
viewportState.pScissors = &scissor;
VkPipelineRasterizationStateCreateInfo rasterizer = {};
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = VK_CULL_MODE_NONE;
rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;
rasterizer.depthBiasEnable = VK_FALSE;
VkPipelineMultisampleStateCreateInfo multisampling = {};
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling.sampleShadingEnable = VK_FALSE;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
std::vector<VkPipelineColorBlendAttachmentState> colorBlendAttachments = {};
colorBlendAttachments.resize(attachCount);
colorBlendAttachments[0].colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
colorBlendAttachments[0].blendEnable = VK_FALSE;
for (size_t i = 1; i < colorBlendAttachments.size(); i++)
{
colorBlendAttachments[i] = colorBlendAttachments[0];
}
VkPipelineDepthStencilStateCreateInfo depthStencilStateCreateInfo{};
depthStencilStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
depthStencilStateCreateInfo.depthTestEnable = true;
depthStencilStateCreateInfo.depthWriteEnable = true;
depthStencilStateCreateInfo.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
depthStencilStateCreateInfo.front = depthStencilStateCreateInfo.back;
depthStencilStateCreateInfo.back.compareOp = VK_COMPARE_OP_ALWAYS;
VkPipelineColorBlendStateCreateInfo colorBlending = {};
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
colorBlending.logicOpEnable = VK_FALSE;
colorBlending.logicOp = VK_LOGIC_OP_COPY;
colorBlending.attachmentCount = static_cast<uint32_t>(colorBlendAttachments.size());
colorBlending.pAttachments = colorBlendAttachments.data();
colorBlending.blendConstants[0] = 0.0f;
colorBlending.blendConstants[1] = 0.0f;
colorBlending.blendConstants[2] = 0.0f;
colorBlending.blendConstants[3] = 0.0f;
VkPipelineDynamicStateCreateInfo dynamicState = {};
std::vector<VkDynamicState> dynamicStateEnables = {
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR};
if (useDynamic)
{
dynamicState = SkInit::pipelineDynamicStateCreateInfo(
dynamicStateEnables.data(),
static_cast<uint32_t>(dynamicStateEnables.size()));
}
VkGraphicsPipelineCreateInfo pipelineInfo = {};
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineInfo.stageCount = 2;
pipelineInfo.pStages = shaderStages;
pipelineInfo.pVertexInputState = &vertexInputInfo;
pipelineInfo.pInputAssemblyState = &inputAssembly;
pipelineInfo.pViewportState = &viewportState;
pipelineInfo.pRasterizationState = &rasterizer;
pipelineInfo.pMultisampleState = &multisampling;
pipelineInfo.pColorBlendState = &colorBlending;
pipelineInfo.pDepthStencilState = &depthStencilStateCreateInfo;
pipelineInfo.layout = this->pipelineLayout;
pipelineInfo.renderPass = appBase->renderPass;
pipelineInfo.subpass = subpass;
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
pipelineInfo.pDynamicState = useDynamic ? &dynamicState : nullptr;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(appBase->device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &pipeline));
}
void SkGraphicsPipeline::CmdDraw(VkCommandBuffer cmd)
{
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, this->pipeline);
// vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, this->pipelineLayout, 0, 1, &this->descriptorSet, 0, nullptr);
if (useDynamic)
{
vkCmdSetViewport(cmd, 0, 1, &viewport);
vkCmdSetScissor(cmd, 0, 1, &scissor);
}
if (meshes.empty())
{
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, this->pipelineLayout, 0, 1, &this->defaultDesSet, 0, nullptr);
vkCmdDraw(cmd, 3, 1, 0, 0);
return;
}
for (size_t j = 0; j < meshes.size(); j++)
{
meshes[j]->CmdDraw(cmd);
}
} | 46.394161 | 152 | 0.757395 | [
"vector"
] |
52819955ac5dc61c6423449c90bb7372fcfb2970 | 14,376 | cpp | C++ | Sources/Graph.cpp | Petititi/imGraph | 068890ffe2f8fa1fb51bc95b8d9296cc79737fac | [
"BSD-3-Clause"
] | 2 | 2015-01-12T11:27:45.000Z | 2015-03-25T18:24:38.000Z | Sources/Graph.cpp | Petititi/imGraph | 068890ffe2f8fa1fb51bc95b8d9296cc79737fac | [
"BSD-3-Clause"
] | 30 | 2015-01-07T11:59:07.000Z | 2015-04-24T13:02:01.000Z | Sources/Graph.cpp | Petititi/imGraph | 068890ffe2f8fa1fb51bc95b8d9296cc79737fac | [
"BSD-3-Clause"
] | 1 | 2018-12-20T12:18:18.000Z | 2018-12-20T12:18:18.000Z |
#include "Graph.h"
#ifdef _WIN32
#pragma warning(disable:4503)
#pragma warning(push)
#pragma warning(disable:4996 4251 4275 4800)
#endif
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp> // includes all needed Boost.Filesystem declarations
#include <boost/regex.hpp>
#include <boost/algorithm/string_regex.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/thread/lock_guard.hpp>
#ifdef _WIN32
#pragma warning(pop)
#endif
#include "ProcessManager.h"
#include "blocks/ParamValidator.h"
#include "SubBlock.h"
using namespace std;
using namespace charliesoft;
using namespace boost::filesystem;
using boost::recursive_mutex;
using boost::property_tree::ptree;
using boost::lexical_cast;
using boost::lock_guard;
namespace charliesoft
{
bool GraphOfProcess::_pauseProcess = false;
GraphOfProcess::GraphOfProcess()
{
_pauseProcess = false;
_parent = NULL;
_subBlock = NULL;
};
GraphOfProcess::~GraphOfProcess()
{
stop();
waitUntilEnd(5000);//15s
for (size_t i = 0; i < _vertices.size(); i++)
{
Block* b = _vertices[i];
delete b;
}
_vertices.clear();
}
void GraphOfProcess::addNewProcess(Block* block){
_vertices.push_back(block);
block->setGraph(this);
//if graph is running, start it:
if (!_runningThread.empty())
{
block->markAsUnprocessed();
_runningThread[block] = boost::thread(boost::ref(*block));
}
};
void GraphOfProcess::deleteProcess(Block* process){
extractProcess(process);//remove the process from the graph
delete process;//free memory
};
void GraphOfProcess::extractProcess(Block* process){
//remove every links:
for (auto& outParam : process->_myOutputs)
outParam.second = Not_A_Value();
for (auto& inParam : process->_myInputs)
inParam.second = Not_A_Value();
for (auto it = _vertices.begin();
it != _vertices.end(); it++)
{
if (*it == process)
{
_vertices.erase(it);
for (auto& waitThread : _waitingForRendering)
{
if (waitThread.first != process)
waitThread.second.erase(process);
}
auto& waitThreadDelete = _waitingForRendering.find(process);
if (waitThreadDelete != _waitingForRendering.end())
{
waitThreadDelete->second.clear();
_waitingForRendering.erase(waitThreadDelete);
}
auto& it = _runningThread.find(process);
if (it != _runningThread.end())
{
it->second.interrupt();
it->second.join();//wait for the end...
_runningThread.erase(it);
}
return;
}
}
};
void GraphOfProcess::removeLink(const BlockLink& l)
{
*(l._to->getParam(l._toParam, true)) = Not_A_Value();
}
void GraphOfProcess::createLink(Block* src, std::string paramName, Block* dest, std::string paramNameDest)
{
src->linkParam(paramName, dest, paramNameDest);
}
std::vector<Block*>& GraphOfProcess::getVertices()
{
return _vertices;
}
void GraphOfProcess::updateAncestors(Block* process)
{
//wait for every direct linked ancestors:
//Is there old parameters? -> if yes, we wait for update, else we process the block right now:
for (auto it = process->_myInputs.begin(); it != process->_myInputs.end(); it++)
{
ParamValue* linkedBlock = it->second.get<ParamValue*>();
if (linkedBlock!=NULL)
{
//we have an ancestor! We ask for an update:
linkedBlock->update();
}
}
}
void GraphOfProcess::shouldWaitAncestors(Block* process)
{
boost::unique_lock<boost::mutex> lock(_mtx);
//should we wait for a process? (depending on the block type)
if (process->getTypeExec() == Block::asynchrone)
return;//no need to wait
//wait for every direct linked ancestors:
//Is there old parameters? -> if yes, we wait for update, else we process the block right now:
for (auto it = process->_myInputs.begin(); it != process->_myInputs.end(); it++)
{
if (it->second.isLinked())
{
ParamValue* other = it->second.get<ParamValue*>();
while (!it->second.isNew())
{//we have to wait for any update!
//std::cout << "--- " << _STR(process->getName()) << " -> Wait " << _STR(it->second.getName()) << endl;
process->setState(Block::waitingChild);
other->getBlock()->waitProducers(lock);//wait for parameter update!
//std::cout << "--- " << _STR(process->getName()) << " <- unblock " << _STR(it->second.getName()) << endl;
}
}
}//ok, every ancestor have produced a value!
if (NULL != _subBlock)
{
for (auto link : _subBlock->externBlocksInput)
{
try
{
if (link._to == process)
{
ParamValue* distVal = link._to->getParam(link._toParam, true);
if (distVal->isDefaultValue() || !distVal->isNew())
{
//std::cout << "--- subBlock_" << _STR(link._to->getName()) << " -> Wait " << _STR(link._fromParam) << endl;
process->setState(Block::waitingChild);
_subBlock->waitUpdateParams(lock);//wait for parameter update!
//std::cout << "--- subBlock_" << _STR(link._to->getName()) << " <- unblock " << _STR(link._fromParam) << endl;
}
}
}
catch (...)
{
//nothing to do...
}
}
}
}
void GraphOfProcess::clearWaitingList(Block* process)
{
boost::unique_lock<boost::mutex> lock(_mtx);
_waitingForRendering[process].clear();
cout << "___clearWaitingList___" << endl;
}
void GraphOfProcess::shouldWaitConsumers(Block* process)
{
boost::unique_lock<boost::mutex> lock(_mtx);
//should we wait for a process? (depending on the block type)
if (process!=NULL && process->getTypeExec() == Block::synchrone)
{
//wait for the childs of this process. They have to be fully rendered before we rerun this block!
for (auto it = process->_myOutputs.begin(); it != process->_myOutputs.end(); it++)
{
//wait for threads consumption
std::set<ParamValue*>& listeners = it->second.getListeners();
for (auto listener : listeners)
{
if (listener->isLinked() && listener->isNew())//this param is still not consumed...
{
_waitingForRendering[process].insert(listener->getBlock());
}
}
}
}
if (process == NULL && _subBlock != NULL)
{
process = _subBlock;
for (auto& threads : _runningThread)
{
if (threads.first->getState() != Block::waitingChild &&
threads.first->getState() != Block::waitingConsumers &&
threads.first->getState() != Block::stopped)
_waitingForRendering[process].insert(threads.first);
}
}
if (process != NULL && !_waitingForRendering[process].empty())
{
process->setState(Block::waitingConsumers);
process->waitConsumers(lock);//wait for parameter update! Will be waked up when _waitingForRendering is empty!
}
}
void GraphOfProcess::blockProduced(Block* process, bool fullyRendered)
{
boost::unique_lock<boost::mutex> lock(_mtx);/*
if (fullyRendered)
std::cout << " \t\t\t " << _STR(process->getName()) << " Produced!" << endl;
else
std::cout << " \t\t\t " << _STR(process->getName()) << " partially rendered!" << endl;*/
//wake up linked output blocks
process->notifyProduction();
if (fullyRendered)
{
//remove this block for every waiting thread:
for (auto& waitThread : _waitingForRendering)
{
if (waitThread.first != process)
{
waitThread.second.erase(process);
if (waitThread.second.empty())
waitThread.first->wakeUpFromConsumers();
}
}
}
}
void GraphOfProcess::stop(bool delegateParent, bool waitEnd, bool stopAll)
{
if (_parent != NULL && delegateParent)
return _parent->stop(delegateParent, waitEnd);
if (stopAll)
{
for (auto& it = _runningThread.begin(); it != _runningThread.end(); it++)
it->second.interrupt();
}
if (waitEnd)
waitUntilEnd(15000);//15s
}
void GraphOfProcess::waitUntilEnd(size_t max_ms_time)
{
auto _time_start = boost::posix_time::microsec_clock::local_time();
for (auto& it = _runningThread.begin(); it != _runningThread.end(); it++)
{
if (it->first->getState() != Block::stopped && it->second.joinable())
{
if (max_ms_time == 0)
it->second.join();
else
{
if (!it->second.timed_join(boost::posix_time::milliseconds(max_ms_time)))
return;//quit because we can't stop the process
boost::posix_time::ptime time_end(boost::posix_time::microsec_clock::local_time());
boost::posix_time::time_duration duration(time_end - _time_start);
if (duration.total_milliseconds() >= max_ms_time)
return;
max_ms_time -= static_cast<size_t>(duration.total_milliseconds());
}
}
}
_runningThread.clear();
}
bool GraphOfProcess::run(bool singleShot, bool delegateParent)
{
if (_parent != NULL && delegateParent)
return _parent->run(singleShot);
stop(delegateParent);//just in case...
_pauseProcess = false;
bool res = true;
for (auto it = _vertices.begin();
it != _vertices.end(); it++)
{
(*it)->markAsUnprocessed();
(*it)->setExecuteOnlyOnce(singleShot);
_runningThread[*it] = boost::thread(boost::ref(**it));
}
return res;
}
bool GraphOfProcess::switchPause(bool delegateParent)
{
if (_parent != NULL && delegateParent)
return _parent->switchPause();
_pauseProcess = !_pauseProcess;
if (!_pauseProcess)
{
//wake up threads:
for (auto it = _vertices.begin();
it != _vertices.end(); it++)
(*it)->wakeUpFromPause();
}
return _pauseProcess;
}
void GraphOfProcess::saveGraph(boost::property_tree::ptree& tree) const
{
for (auto it = _vertices.begin();
it != _vertices.end(); it++)
tree.add_child("GraphOfProcess.Block", (*it)->getXML());
}
bool GraphOfProcess::initChildDatas(Block* block, std::set<Block*>& listOfRenderedBlocks)
{
if (listOfRenderedBlocks.find(block) != listOfRenderedBlocks.end())
return false;//nothing to do...
if (block->getState() != Block::stopped && block->getState() != Block::paused)
return true;//block is running, the value will be updated automatically!
listOfRenderedBlocks.insert(block);
//take one shot of block to init output:
try
{
block->init();
block->run(true);
block->release();
//now render every childs.
set<Block*> renderBlocks;
for (auto it = block->_myOutputs.begin(); it != block->_myOutputs.end(); it++)
{
//wake up the threads, if any!
std::set<ParamValue*>& listeners = it->second.getListeners();
for (auto listener : listeners)
{
if (listener->isLinked())
{
Block* consumer = listener->getBlock();
if (consumer != NULL && consumer->isReadyToRun(true))
renderBlocks.insert(consumer);
}
}
}
for (Block* consumer : renderBlocks)
{
if (listOfRenderedBlocks.find(consumer) == listOfRenderedBlocks.end())
initChildDatas(consumer, listOfRenderedBlocks);
}
}
catch (cv::Exception& e)
{
block->addErrorMsg(e.what());
std::cout << "exception caught: " << e.what() << std::endl;
return false;
}
return true;
}
void GraphOfProcess::fromGraph(boost::property_tree::ptree& tree,
std::map<unsigned int, ParamValue*>& addressesMap)
{
boost::optional<ptree&> vertices = tree.get_child_optional("GraphOfProcess");
vector < std::pair<ParamValue*, unsigned int> > toUpdate;
vector<ConditionOfRendering*> condToUpdate;
if (vertices)
{
for (ptree::iterator it = vertices->begin(); it != vertices->end(); it++)
{
if (it->first.compare("Block") == 0)
{
ptree *block = &it->second;
string name = block->get("name", "Error");
Block* tmp = ProcessManager::getInstance()->createAlgoInstance(name);
if (tmp != NULL)
{
addNewProcess(tmp);
tmp->initFromXML(block, toUpdate, addressesMap, condToUpdate);
}
}
}
//now make links:
for (auto valToUpdate : toUpdate)
{
Block* fromBlock = valToUpdate.first != NULL ? valToUpdate.first->getBlock() : NULL;
ParamValue* secondVal = addressesMap[valToUpdate.second];
Block* toBlock = secondVal != NULL ? secondVal->getBlock() : NULL;
if (fromBlock != NULL && toBlock != NULL)
{
try
{
createLink(toBlock, secondVal->getName(), fromBlock, valToUpdate.first->getName());
}
catch (ErrorValidator& e)
{//algo doesn't accept this value!
//QMessageBox::warning(this, _QT("ERROR_GENERIC_TITLE"), e.errorMsg.c_str());
std::cout << e.errorMsg << std::endl;
}
}
}
//and set correct values of conditions:
for (auto cond : condToUpdate)
{
if (cond->getCategory_left() == 1)//output of block:
{
unsigned int addr = static_cast<unsigned int>(cond->getOpt__valueleft().get<double>() + 0.5);
cond->setValue(true, addressesMap[addr]);
}
if (cond->getCategory_right() == 1)//output of block:
{
unsigned int addr = static_cast<unsigned int>(cond->getOpt__valueright().get<double>() + 0.5);
cond->setValue(false, addressesMap[addr]);
}
}
//first look for edges who are ready to run:
set<Block*> renderedBlocks;
for (auto it = _vertices.begin();
it != _vertices.end(); it++)
{
if ((*it)->isReadyToRun(true))
initChildDatas(*it, renderedBlocks);//and init him and output childs
}
}
}
} | 31.252174 | 126 | 0.601976 | [
"render",
"vector"
] |
528aa31daae5e32c27a56dc4280c8a60e1f6ba9a | 5,614 | cpp | C++ | src/PlannerUI.cpp | njw1204/IIKH | 48be7f34262ab6217ebe7eede45a1dee5d22cc2c | [
"MIT"
] | null | null | null | src/PlannerUI.cpp | njw1204/IIKH | 48be7f34262ab6217ebe7eede45a1dee5d22cc2c | [
"MIT"
] | null | null | null | src/PlannerUI.cpp | njw1204/IIKH | 48be7f34262ab6217ebe7eede45a1dee5d22cc2c | [
"MIT"
] | 1 | 2020-10-24T07:20:02.000Z | 2020-10-24T07:20:02.000Z | #include "PlannerUI.h"
#include "RecipeUI.h"
#include "RecipeDatabase.h"
#include "Date.h"
#include "Plan.h"
#include "util.h"
#include <climits>
#include <cstdlib>
using namespace std;
void PlannerUI::showPlannerForm()
{
if (rdb.getRecipesList().empty())
{
cout << endl;
cout << " You don't have any recipes!" << endl;
cout << " Please add some recipes to the database." << endl;
cout << endl;
cout << " Press Enter to Continue... ";
waitEnter();
return;
}
Plan plan;
vector<Date>& dates = plan.getDates();
for (int i = 1; ; i++)
{
clrscr();
cout << endl;
cout << " ######################" << endl;
cout << " ## ##" << endl;
cout << " ## Meal Planner ##" << endl;
cout << " ## ##" << endl;
cout << " ######################" << endl;
cout << endl;
cout << " (Input 0 to print & save a file)" << endl;
cout << " (Input -1 to quit)" << endl;
for (int j = 1; j < i; j++) {
cout << endl;
cout << endl;
cout << " [Day " << j << "]" << endl;
cout << " " << dates[j - 1].toString() << " Saved." << endl;;
}
int year, month, day;
Date date;
cout << endl;
cout << endl;
cout << " [Day " << i << "]" << endl;
cout << " Date (yyyy mm dd) : ";
cin >> year;
if (year == -1)
{
return;
}
if (year == 0)
{
clrscr();
Plan plan;
plan.setDates(dates);
plan.printPlan();
plan.writePlanToFile("plan.txt");
cin.ignore(INT_MAX, '\n');
cout << endl << endl;
cout << " Success! Write the plan to \"plan.txt\". Check the file." << endl;
cout << " Press Enter to Continue... ";
waitEnter();
break;
}
cin >> month >> day;
cin.ignore(INT_MAX, '\n');
if (!date.init(year, month, day))
{
cout << endl;
cout << " Invalid Date! Please write again." << endl;
cout << " Press Enter to Continue... ";
waitEnter();
i--;
continue;
}
makeDailyPlan(date);
dates.push_back(date);
}
}
void PlannerUI::makeDailyPlan(Date& date)
{
RecipeUI rui = RecipeUI(rdb);
while (true)
{
clrscr();
cout << endl;
cout << " Daily Plan Menu (" << date.toString() << ")" << endl;
cout << endl;
cout << " #############################" << endl;
cout << " ## ##" << endl;
cout << " ## 1. Add to Breakfast ##" << endl;
cout << " ## 2. Add to Lunch ##" << endl;
cout << " ## 3. Add to Dinner ##" << endl;
cout << " ## 4. Set People Count ##" << endl;
cout << " ## 5. Show daily plan ##" << endl;
cout << " ## 0. Save & Exit ##" << endl;
cout << " ## ##" << endl;
cout << " #############################" << endl;
cout << endl;
cout << " Select Operation Number : ";
int selector;
cin >> selector;
cin.ignore(INT_MAX, '\n');
int mealType, id;
string input;
Recipe recipe(-1);
switch (selector)
{
case 0:
return;
case 1: case 2: case 3:
mealType = selector;
clrscr();
cout << endl;
cout << " Pick a recipe that you want to add" << endl;
id = rui.showRecipeList(false);
if (id == -1) break;
clrscr();
recipe = rdb.getRecipe(id);
recipe.printRecipe();
cout << endl;
cout << " Do you really want to use this recipe? (Y/N) : ";
cin >> input;
if (input != "Y" && input != "y") break;
switch (mealType)
{
case 1:
date.getBreakfast().addMenu(recipe);
break;
case 2:
date.getLunch().addMenu(recipe);
break;
case 3:
date.getDinner().addMenu(recipe);
}
cin.ignore(INT_MAX, '\n');
cout << endl;
cout << " Commited." << endl;
cout << " Press Enter to Continue... ";
waitEnter();
break;
case 4:
int breakfastP, lunchP, dinnerP;
cout << endl;
cout << " 1) Breakfast People Count : ";
cin >> breakfastP;
cout << " 2) Lunch People Count : ";
cin >> lunchP;
cout << " 3) Dinner People Count : ";
cin >> dinnerP;
date.getBreakfast().setPeople(breakfastP);
date.getLunch().setPeople(lunchP);
date.getDinner().setPeople(dinnerP);
cin.ignore(INT_MAX, '\n');
cout << endl;
cout << " Commited." << endl;
cout << " Press Enter to Continue... ";
waitEnter();
break;
case 5:
vector<Date> tempDates;
Plan plan;
tempDates.push_back(date);
plan.setDates(tempDates);
clrscr();
plan.printPlan();
cout << endl;
cout << " Press Enter to Continue... ";
waitEnter();
}
}
}
| 27.519608 | 88 | 0.405415 | [
"vector"
] |
52985af8e88310bc5ead0a54c1109b72727debb1 | 7,789 | cpp | C++ | calc.cpp | K-JW/JetAnalysor | 7fc98a8782e2e3624335bb01e44b635857cd0974 | [
"MIT"
] | 1 | 2020-05-24T07:56:51.000Z | 2020-05-24T07:56:51.000Z | calc.cpp | K-JW/JetAnalysor | 7fc98a8782e2e3624335bb01e44b635857cd0974 | [
"MIT"
] | null | null | null | calc.cpp | K-JW/JetAnalysor | 7fc98a8782e2e3624335bb01e44b635857cd0974 | [
"MIT"
] | null | null | null | //example hepmc reader
#include "utils.h"
#include "jetSelector.h"
#include "calcDeltaPhiDist.h"
#include "distCalculator.h"
#include <HepMC/IO_GenEvent.h>
#include <HepMC/GenEvent.h>
#include <HepMC/GenVertex.h>
#include <fastjet/PseudoJet.hh>
#include <fastjet/ClusterSequence.hh>
#include <fastjet/Selector.hh>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
using namespace fastjet;
const static double PI = 3.1415926;
const static double R_jet = 0.3;
JetDefinition jet_def(antikt_algorithm, R_jet);
Selector select_akt = SelectorAbsEtaMax(1.6) && SelectorPtMin(30.);
double weight_total = 0.;
double phi_bin[10] = {0, 0.31, 0.94, 1.25, 1.72, 2.20, 2.51, 2.82, 2.98, 3.14};
double weight_for_bin[10] = {0.};
double x_bin[10] = {0.10, 0.30, 0.50, 0.70, 0.90, 1.10, 1.30, 1.50, 1.70, 1.90};
double weight_for_bin_for_x_jz[10] = {0.};
int main(int argc, char *argv[]) {
if (argc == 1) {
cout << " " << "ERROR: Please supply HepMC file as argument..." << endl;
return 1;
}
ifstream in_file(argv[1]);
if (!in_file.is_open()) {
cout << "Can't open file." << endl;
exit(EXIT_FAILURE);
}
while (!in_file.eof()) {
int event_id, pdg_code, partons_num, Z_daughter_pdg_code;
double Z_daughter_1_x, Z_daughter_1_y, Z_daughter_1_z, Z_daughter_1_energy;
double Z_daughter_2_x, Z_daughter_2_y, Z_daughter_2_z, Z_daughter_2_energy;
double px, py, pz, energy, temp;
double weight0, weight1, weight2, weight3, weight4;
double eta, pT;
bool isContinueFind = false;
in_file >> event_id >> partons_num >> weight0 >> weight1
>> weight2 >> weight3 >> weight4;
in_file >> Z_daughter_pdg_code >> Z_daughter_1_x >> Z_daughter_1_y
>> Z_daughter_1_z >> Z_daughter_1_energy >> temp;
in_file >> Z_daughter_pdg_code >> Z_daughter_2_x >> Z_daughter_2_y
>> Z_daughter_2_z >> Z_daughter_2_energy >> temp;
double Z_daughter1_pT = sqrt(pow(Z_daughter_1_x, 2) + pow(Z_daughter_1_y, 2));
double Z_daughter1_p = sqrt(pow(Z_daughter_1_x, 2) + pow(Z_daughter_1_y, 2)
+ pow(Z_daughter_1_z, 2));
double Z_daught1_eta = (1.0 / 2.0) * log((Z_daughter1_p + Z_daughter_1_z) / (
Z_daughter1_p - Z_daughter_1_z
) );
double Z_daughter1_phi = acos(Z_daughter_1_x / Z_daughter1_pT );
if (Z_daughter_1_y < 0) Z_daughter1_phi = 2 * PI - Z_daughter1_phi;
double Z_daughter2_pT = sqrt(pow(Z_daughter_2_x, 2) + pow(Z_daughter_2_y, 2));
double Z_daughter2_p = sqrt(pow(Z_daughter_2_x, 2) + pow(Z_daughter_2_y, 2)
+ pow(Z_daughter_2_z, 2));
double Z_daught2_eta = (1.0 / 2.0) * log((Z_daughter2_p + Z_daughter_2_z) / (
Z_daughter2_p - Z_daughter_2_z
) );
double Z_daughter2_phi = acos(Z_daughter_2_x / Z_daughter2_pT );
if (Z_daughter_2_y < 0) Z_daughter2_phi = 2 * PI - Z_daughter2_phi;
double Z_pT = sqrt(pow(Z_daughter_1_x + Z_daughter_2_x, 2) + pow(
Z_daughter_1_y + Z_daughter_2_y, 2
));
double Z_p = sqrt(pow(Z_daughter_1_x + Z_daughter_2_x, 2) + pow(
Z_daughter_1_y + Z_daughter_2_y, 2
) + pow(Z_daughter_1_z + Z_daughter_2_z, 2));
double Z_rap = (1.0 / 2.0) * log(
(Z_daughter_1_energy + Z_daughter_2_energy + Z_daughter_1_z + Z_daughter_2_z) / (
Z_daughter_1_energy + Z_daughter_2_energy - Z_daughter_1_z - Z_daughter_2_z
)
);
double Z_mass = sqrt(pow(Z_daughter_1_energy + Z_daughter_2_energy, 2) -
pow(Z_p, 2));
double Z_eta = (1.0 / 2.0) * log(
(Z_p + Z_daughter_1_z + Z_daughter_2_z) / (
Z_p - Z_daughter_1_z - Z_daughter_2_z
)
);
double Z_phi = acos((Z_daughter_1_x + Z_daughter_2_x) / Z_pT);
if ((Z_daughter_2_y + Z_daughter_1_y) < 0) Z_phi = 2 * PI - Z_phi;
// if (abs(Z_daughter_pdg_code) == 11 || abs(Z_daughter_pdg_code) == 13) {
// if (Z_mass >= 70.0 && Z_mass <=110 && Z_pT >= 60 ) {
// weight_total += weight0 / weight2;
// isContinueFind = true;
// }
// }
if (abs(Z_daughter_pdg_code) == 11) {
if (fabs(Z_daught1_eta) < 1.44 || (fabs(Z_daught1_eta) > 1.57 &&
fabs(Z_daught1_eta) < 2.5) ) {
//
if (fabs(Z_daught2_eta) < 1.44 || (fabs(Z_daught2_eta) > 1.57 &&
fabs(Z_daught2_eta) < 2.5) ) {
if (Z_daughter1_pT > 20. && Z_daughter2_pT > 20 && Z_mass > 70 &&
Z_mass < 110 && Z_pT > 60 && fabs(Z_rap) < 2.5 ) {
//
weight_total += weight0 / weight2;
isContinueFind = true;
}
}
}
}
if (abs(Z_daughter_pdg_code) == 13) {
if (fabs(Z_daught1_eta) < 2.4) {
if (fabs(Z_daught2_eta) < 2.4) {
if (Z_daughter1_pT > 10. && Z_daughter2_pT > 10 && Z_mass > 70 &&
Z_mass < 110 && Z_pT > 60 && fabs(Z_rap) < 2.5 ) {
//
weight_total += weight0 / weight2;
isContinueFind = true;
}
}
}
}
vector<PseudoJet> pseudo_jets;
for ( unsigned i = 0; i < partons_num - 2; i++) {
in_file >> pdg_code >> px >> py >> pz >> energy >> temp;
PseudoJet tmp(px, py, pz, energy);
pseudo_jets.emplace_back(tmp);
}
if (isContinueFind) {
ClusterSequence cluster(pseudo_jets, jet_def);
vector<PseudoJet> jets = sorted_by_pt(select_akt(cluster.inclusive_jets()));
if (jets.size() > 0) {
for (const auto jet : jets) {
double delta_phi = fabs(jet.phi() - Z_phi);
delta_phi = delta_phi > PI ? 2 * PI - delta_phi : delta_phi;
for (unsigned i = 0; i < 9; i++) {
if (delta_phi >= phi_bin[i] && delta_phi < phi_bin[i + 1]) {
weight_for_bin[i + 1] += weight0 / weight2;
}
if (delta_phi > 7 * PI / 8.0) {
double x_jZ = jet.perp() / Z_pT;
// cout << "Found!: " << x_jZ << endl;
if (x_jZ >= x_bin[i] && x_jZ < x_bin[i + 1]) {
weight_for_bin_for_x_jz[i + 1] += weight0 / weight2;
}
}
}
}
}
isContinueFind = false;
}
}
std::ofstream delta_phi_dist_file;
const char *out_delta_phi_dist_file = "deltaPhiDist.dat";
delta_phi_dist_file.open(out_delta_phi_dist_file);
std::ofstream transverse_momentum_dist_file;
const char *out_trans_mome_dist_file = "transverse_momentum_dist_file.dat";
transverse_momentum_dist_file.open(out_trans_mome_dist_file);
for(unsigned i = 1; i < 10; i++) {
// cout << "weight_for_bin: " << weight_for_bin[i]
// << ", phi_bin[i]: " << phi_bin[i] << ", "
// << "phi_bin[i - 1]: " << phi_bin[i - 1] << endl;
delta_phi_dist_file << phi_bin[i]
<< ", " << weight_for_bin[i] / weight_total / (phi_bin[i] - phi_bin[i - 1]) << endl;
transverse_momentum_dist_file << x_bin[i] << ", "
<< weight_for_bin_for_x_jz[i] / weight_total / (x_bin[i] - x_bin[i - 1]) << endl;
}
return 0;
} //end main
| 39.94359 | 96 | 0.540634 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.