hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count 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 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count 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 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0a20b224df22148e34f8f09e929d28394b7c6c9a | 18,357 | hpp | C++ | accessor/scaled_reduced_row_major.hpp | JakubTrzcskni/ginkgo | 8a9988b9c3f8c4ff59fae30050575311f230065e | [
"BSD-3-Clause"
] | null | null | null | accessor/scaled_reduced_row_major.hpp | JakubTrzcskni/ginkgo | 8a9988b9c3f8c4ff59fae30050575311f230065e | [
"BSD-3-Clause"
] | null | null | null | accessor/scaled_reduced_row_major.hpp | JakubTrzcskni/ginkgo | 8a9988b9c3f8c4ff59fae30050575311f230065e | [
"BSD-3-Clause"
] | null | null | null | /*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2022, the Ginkgo authors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************<GINKGO LICENSE>*******************************/
#ifndef GKO_ACCESSOR_SCALED_REDUCED_ROW_MAJOR_HPP_
#define GKO_ACCESSOR_SCALED_REDUCED_ROW_MAJOR_HPP_
#include <array>
#include <cinttypes>
#include <type_traits>
#include <utility>
#include "accessor_helper.hpp"
#include "index_span.hpp"
#include "range.hpp"
#include "scaled_reduced_row_major_reference.hpp"
#include "utils.hpp"
namespace gko {
/**
* @brief The accessor namespace.
*
* @ingroup accessor
*/
namespace acc {
namespace detail {
// In case of a const type, do not provide a write function
template <int Dimensionality, typename Accessor, typename ScalarType,
bool = std::is_const<ScalarType>::value>
struct enable_write_scalar {
using scalar_type = ScalarType;
};
// In case of a non-const type, enable the write function
template <int Dimensionality, typename Accessor, typename ScalarType>
struct enable_write_scalar<Dimensionality, Accessor, ScalarType, false> {
static_assert(Dimensionality >= 1,
"Dimensionality must be a positive number!");
using scalar_type = ScalarType;
/**
* Writes the scalar value at the given indices.
* The number of indices must be equal to the number of dimensions, even
* if some of the indices are ignored (depending on the scalar mask).
*
* @param value value to write
* @param indices indices where to write the value
*
* @returns the written value.
*/
template <typename... Indices>
constexpr GKO_ACC_ATTRIBUTES scalar_type
write_scalar_masked(scalar_type value, Indices&&... indices) const
{
static_assert(sizeof...(Indices) == Dimensionality,
"Number of indices must match dimensionality!");
scalar_type* GKO_ACC_RESTRICT rest_scalar = self()->scalar_;
return rest_scalar[self()->compute_mask_scalar_index(
std::forward<Indices>(indices)...)] = value;
}
/**
* Writes the scalar value at the given indices.
* Only the actually used indices must be provided, meaning the number of
* specified indices must be equal to the number of set bits in the
* scalar mask.
*
* @param value value to write
* @param indices indices where to write the value
*
* @returns the written value.
*/
template <typename... Indices>
constexpr GKO_ACC_ATTRIBUTES scalar_type
write_scalar_direct(scalar_type value, Indices&&... indices) const
{
scalar_type* GKO_ACC_RESTRICT rest_scalar = self()->scalar_;
return rest_scalar[self()->compute_direct_scalar_index(
std::forward<Indices>(indices)...)] = value;
}
private:
constexpr GKO_ACC_ATTRIBUTES const Accessor* self() const
{
return static_cast<const Accessor*>(this);
}
};
} // namespace detail
/**
* The scaled_reduced_row_major class allows a storage format that is different
* from the arithmetic format (which is returned from the brace operator).
* Additionally, a scalar is used when reading and writing data to allow for
* a shift in range.
* As storage, the StorageType is used.
*
* This accessor uses row-major access. For example, for three dimensions,
* neighboring z coordinates are next to each other in memory, followed by y
* coordinates and then x coordinates.
*
* @tparam Dimensionality The number of dimensions managed by this accessor
*
* @tparam ArithmeticType Value type used for arithmetic operations and
* for in- and output
*
* @tparam StorageType Value type used for storing the actual value to memory
*
* @tparam ScalarMask Binary mask that marks which indices matter for the
* scalar selection (set bit means the corresponding index
* needs to be considered, 0 means it is not). The least
* significand bit corresponds to the last index dimension,
* the second least to the second last index dimension, and
* so on.
* For example, the mask = 0b011101 means that for the 5d
* indices (x1, x2, x3, x4, x5), (x1, x2, x3, x5) are
* considered for the scalar, making the scalar itself 4d.
*
* @note This class only manages the accesses and not the memory itself.
*/
template <std::size_t Dimensionality, typename ArithmeticType,
typename StorageType, std::uint64_t ScalarMask>
class scaled_reduced_row_major
: public detail::enable_write_scalar<
Dimensionality,
scaled_reduced_row_major<Dimensionality, ArithmeticType, StorageType,
ScalarMask>,
ArithmeticType, std::is_const<StorageType>::value> {
public:
using arithmetic_type = std::remove_cv_t<ArithmeticType>;
using storage_type = StorageType;
static constexpr auto dimensionality = Dimensionality;
static constexpr auto scalar_mask = ScalarMask;
static constexpr bool is_const{std::is_const<storage_type>::value};
using scalar_type =
std::conditional_t<is_const, const arithmetic_type, arithmetic_type>;
using const_accessor =
scaled_reduced_row_major<dimensionality, arithmetic_type,
const storage_type, ScalarMask>;
static_assert(!is_complex<ArithmeticType>::value &&
!is_complex<StorageType>::value,
"Both arithmetic and storage type must not be complex!");
static_assert(Dimensionality >= 1,
"Dimensionality must be a positive number!");
static_assert(dimensionality <= 32,
"Only Dimensionality <= 32 is currently supported");
// Allow access to both `scalar_` and `compute_mask_scalar_index()`
friend class detail::enable_write_scalar<
dimensionality, scaled_reduced_row_major, scalar_type>;
friend class range<scaled_reduced_row_major>;
protected:
static constexpr std::size_t scalar_dim{
helper::count_mask_dimensionality<scalar_mask, dimensionality>()};
static constexpr std::size_t scalar_stride_dim{
scalar_dim == 0 ? 0 : (scalar_dim - 1)};
using dim_type = std::array<size_type, dimensionality>;
using storage_stride_type = std::array<size_type, dimensionality - 1>;
using scalar_stride_type = std::array<size_type, scalar_stride_dim>;
using reference_type =
reference_class::scaled_reduced_storage<arithmetic_type, StorageType>;
private:
using index_type = std::int64_t;
protected:
/**
* Creates the accessor for an already allocated storage space with a
* stride. The first stride is used for computing the index for the first
* index, the second stride for the second index, and so on.
*
* @param size multidimensional size of the memory
* @param storage pointer to the block of memory containing the storage
* @param storage_stride stride array used for memory accesses to storage
* @param scalar pointer to the block of memory containing the scalar
* values.
* @param scalar_stride stride array used for memory accesses to scalar
*/
constexpr GKO_ACC_ATTRIBUTES scaled_reduced_row_major(
dim_type size, storage_type* storage,
storage_stride_type storage_stride, scalar_type* scalar,
scalar_stride_type scalar_stride)
: size_(size),
storage_{storage},
storage_stride_(storage_stride),
scalar_{scalar},
scalar_stride_(scalar_stride)
{}
/**
* Creates the accessor for an already allocated storage space with a
* stride. The first stride is used for computing the index for the first
* index, the second stride for the second index, and so on.
*
* @param size multidimensional size of the memory
* @param storage pointer to the block of memory containing the storage
* @param stride stride array used for memory accesses to storage
* @param scalar pointer to the block of memory containing the scalar
* values.
*/
constexpr GKO_ACC_ATTRIBUTES scaled_reduced_row_major(
dim_type size, storage_type* storage, storage_stride_type stride,
scalar_type* scalar)
: scaled_reduced_row_major{
size, storage, stride, scalar,
helper::compute_default_masked_row_major_stride_array<
scalar_mask, scalar_stride_dim, dimensionality>(size)}
{}
/**
* Creates the accessor for an already allocated storage space.
* It is assumed that all accesses are without padding.
*
* @param size multidimensional size of the memory
* @param storage pointer to the block of memory containing the storage
* @param scalar pointer to the block of memory containing the scalar
* values.
*/
constexpr GKO_ACC_ATTRIBUTES scaled_reduced_row_major(dim_type size,
storage_type* storage,
scalar_type* scalar)
: scaled_reduced_row_major{
size, storage,
helper::compute_default_row_major_stride_array(size), scalar}
{}
/**
* Creates an empty accessor (pointing nowhere with an empty size)
*/
constexpr GKO_ACC_ATTRIBUTES scaled_reduced_row_major()
: scaled_reduced_row_major{{0, 0, 0}, nullptr, nullptr}
{}
public:
/**
* Creates a scaled_reduced_row_major range which contains a read-only
* version of the current accessor.
*
* @returns a scaled_reduced_row_major major range which is read-only.
*/
constexpr GKO_ACC_ATTRIBUTES range<const_accessor> to_const() const
{
return range<const_accessor>{size_, storage_, storage_stride_, scalar_,
scalar_stride_};
}
/**
* Reads the scalar value at the given indices. Only indices where the
* scalar mask bit is set are considered, the others are ignored.
*
* @param indices indices which data to access
*
* @returns the scalar value at the given indices.
*/
template <typename... Indices>
constexpr GKO_ACC_ATTRIBUTES scalar_type
read_scalar_masked(Indices&&... indices) const
{
const arithmetic_type* GKO_ACC_RESTRICT rest_scalar = scalar_;
return rest_scalar[compute_mask_scalar_index(
std::forward<Indices>(indices)...)];
}
/**
* Reads the scalar value at the given indices. Only the actually used
* indices must be provided, meaning the number of specified indices must
* be equal to the number of set bits in the scalar mask.
*
* @param indices indices which data to access
*
* @returns the scalar value at the given indices.
*/
template <typename... Indices>
constexpr GKO_ACC_ATTRIBUTES scalar_type
read_scalar_direct(Indices&&... indices) const
{
const arithmetic_type* GKO_ACC_RESTRICT rest_scalar = scalar_;
return rest_scalar[compute_direct_scalar_index(
std::forward<Indices>(indices)...)];
}
/**
* Returns the length in dimension `dimension`.
*
* @param dimension a dimension index
*
* @returns length in dimension `dimension`
*/
constexpr GKO_ACC_ATTRIBUTES size_type length(size_type dimension) const
{
return dimension < dimensionality ? size_[dimension] : 1;
}
/**
* Returns the stored value for the given indices. If the storage is const,
* a value is returned, otherwise, a reference is returned.
*
* @param indices indices which value is supposed to access
*
* @returns the stored value if the accessor is const (if the storage type
* is const), or a reference if the accessor is non-const
*/
template <typename... Indices>
constexpr GKO_ACC_ATTRIBUTES std::enable_if_t<
are_all_integral<Indices...>::value,
std::conditional_t<is_const, arithmetic_type, reference_type>>
operator()(Indices... indices) const
{
return reference_type{storage_ + compute_index(indices...),
read_scalar_masked(indices...)};
}
/**
* Returns a sub-range spinning the current range (x1_span, x2_span, ...)
*
* @param spans span for the indices
*
* @returns a sub-range for the given spans.
*/
template <typename... SpanTypes>
constexpr GKO_ACC_ATTRIBUTES
std::enable_if_t<helper::are_index_span_compatible<SpanTypes...>::value,
range<scaled_reduced_row_major>>
operator()(SpanTypes... spans) const
{
return helper::validate_index_spans(size_, spans...),
range<scaled_reduced_row_major>{
dim_type{
(index_span{spans}.end - index_span{spans}.begin)...},
storage_ + compute_index((index_span{spans}.begin)...),
storage_stride_,
scalar_ +
compute_mask_scalar_index(index_span{spans}.begin...),
scalar_stride_};
}
/**
* Returns the size of the accessor
*
* @returns the size of the accessor
*/
constexpr GKO_ACC_ATTRIBUTES dim_type get_size() const { return size_; }
/**
* Returns a const reference to the storage stride array of size
* dimensionality - 1
*
* @returns a const reference to the storage stride array of size
* dimensionality - 1
*/
constexpr GKO_ACC_ATTRIBUTES const storage_stride_type& get_storage_stride()
const
{
return storage_stride_;
}
/**
* Returns a const reference to the scalar stride array
*
* @returns a const reference to the scalar stride array
*/
constexpr GKO_ACC_ATTRIBUTES const scalar_stride_type& get_scalar_stride()
const
{
return scalar_stride_;
}
/**
* Returns the pointer to the storage data
*
* @returns the pointer to the storage data
*/
constexpr GKO_ACC_ATTRIBUTES storage_type* get_stored_data() const
{
return storage_;
}
/**
* Returns a const pointer to the storage data
*
* @returns a const pointer to the storage data
*/
constexpr GKO_ACC_ATTRIBUTES const storage_type* get_const_storage() const
{
return storage_;
}
/**
* Returns the pointer to the scalar data
*
* @returns the pointer to the scalar data
*/
constexpr GKO_ACC_ATTRIBUTES scalar_type* get_scalar() const
{
return scalar_;
}
/**
* Returns a const pointer to the scalar data
*
* @returns a const pointer to the scalar data
*/
constexpr GKO_ACC_ATTRIBUTES const scalar_type* get_const_scalar() const
{
return scalar_;
}
protected:
template <typename... Indices>
constexpr GKO_ACC_ATTRIBUTES size_type
compute_index(Indices&&... indices) const
{
static_assert(sizeof...(Indices) == dimensionality,
"Number of indices must match dimensionality!");
return helper::compute_row_major_index<index_type, dimensionality>(
size_, storage_stride_, std::forward<Indices>(indices)...);
}
template <typename... Indices>
constexpr GKO_ACC_ATTRIBUTES size_type
compute_mask_scalar_index(Indices&&... indices) const
{
static_assert(sizeof...(Indices) == dimensionality,
"Number of indices must match dimensionality!");
return helper::compute_masked_index<index_type, scalar_mask,
scalar_stride_dim>(
size_, scalar_stride_, std::forward<Indices>(indices)...);
}
template <typename... Indices>
constexpr GKO_ACC_ATTRIBUTES size_type
compute_direct_scalar_index(Indices&&... indices) const
{
static_assert(
sizeof...(Indices) == scalar_dim,
"Number of indices must match number of set bits in scalar mask!");
return helper::compute_masked_index_direct<index_type, scalar_mask,
scalar_stride_dim>(
size_, scalar_stride_, std::forward<Indices>(indices)...);
}
private:
const dim_type size_;
storage_type* const storage_;
const storage_stride_type storage_stride_;
scalar_type* const scalar_;
const scalar_stride_type scalar_stride_;
};
} // namespace acc
} // namespace gko
#endif // GKO_ACCESSOR_SCALED_REDUCED_ROW_MAJOR_HPP_
| 36.861446 | 80 | 0.661873 |
0a2345ce151ac883b882315f001ad2d8196644a1 | 3,195 | cpp | C++ | src/classical/xmg/xmg_path.cpp | eletesta/cirkit | 6d0939798ea25cecf92306ce796be154139b94f5 | [
"MIT"
] | null | null | null | src/classical/xmg/xmg_path.cpp | eletesta/cirkit | 6d0939798ea25cecf92306ce796be154139b94f5 | [
"MIT"
] | null | null | null | src/classical/xmg/xmg_path.cpp | eletesta/cirkit | 6d0939798ea25cecf92306ce796be154139b94f5 | [
"MIT"
] | null | null | null | /* CirKit: A circuit toolkit
* Copyright (C) 2009-2015 University of Bremen
* Copyright (C) 2015-2017 EPFL
*
* 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 "xmg_path.hpp"
#include <vector>
#include <boost/range/algorithm.hpp>
namespace cirkit
{
/******************************************************************************
* Types *
******************************************************************************/
/******************************************************************************
* Private functions *
******************************************************************************/
/******************************************************************************
* Public functions *
******************************************************************************/
std::vector<std::vector<xmg_node>> xmg_find_critical_paths( xmg_graph& xmg )
{
/* dynamic programming to compute each node delay */
std::vector<std::pair<xmg_node, unsigned>> delays( xmg.size(), std::make_pair( 0, 0 ) );
for ( auto node : xmg.topological_nodes() )
{
if ( xmg.is_input( node ) )
{
delays[node] = {node, 0u};
}
else
{
for ( auto child : xmg.children( node ) )
{
if ( delays[child.node].second + 1 >= delays[node].second )
{
delays[node].first = child.node;
delays[node].second = delays[child.node].second + 1;
}
}
}
}
std::vector<std::vector<xmg_node>> critical_paths;
for ( const auto& output : xmg.outputs() )
{
std::vector<xmg_node> path;
path.push_back( output.first.node );
while ( delays[path.back()].first != path.back() )
{
path.push_back( delays[path.back()].first );
}
boost::reverse( path );
critical_paths.push_back( path );
}
return critical_paths;
}
}
// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:
| 32.938144 | 90 | 0.533333 |
0a24dde8f169bcf2ef83da543811e80997893197 | 347 | cpp | C++ | Dataset/Leetcode/train/94/88.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/94/88.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/94/88.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
void inorder(TreeNode*root,vector <int> & res)
{
if (root!=nullptr) return;
inorder (root->left,res);
res.push_back(root->val);
inorder(root->right,res);
}
vector<int> XXX(TreeNode* root) {
vector <int> vec;
inorder(root,vec);
return vec;
}
};
| 19.277778 | 51 | 0.541787 |
0a25d69676aae709b47041e5d6b4f6c8a7db1610 | 924 | cpp | C++ | main.cpp | hnqiu/cpp-test | ec3eafd3126be8468ba4f2d6a26c5863659aa8e3 | [
"MIT"
] | 1 | 2019-03-21T04:06:13.000Z | 2019-03-21T04:06:13.000Z | main.cpp | hnqiu/cpp-test | ec3eafd3126be8468ba4f2d6a26c5863659aa8e3 | [
"MIT"
] | null | null | null | main.cpp | hnqiu/cpp-test | ec3eafd3126be8468ba4f2d6a26c5863659aa8e3 | [
"MIT"
] | null | null | null | /* Copyright (C) 2019 hnqiu. All rights reserved.
* Licensed under the MIT License. See LICENSE for details.
*/
#include <iostream>
#include "string_test.h"
#include "sizeof_test.h"
#include "continue_test.h"
#include "return_list_test.h"
#include "return_pointer_to_array_test.h"
#include "class_test.h"
#include "cons_des.h"
#include "inheritance_test.h"
#include "template_test.h"
#include "operator_test.h"
#include "predicate_test.h"
#include "bitset_test.h"
#include "clock_test.h"
int main(int argc, char *argv[]) {
//string_test();
//sizeof_test();
//continue_test();
//return_list_test();
//return_pointer_to_array_test();
//class_test();
//smart_ptr_test();
//cons_des();
//inheritance_test();
//template_test();
//template_test_v2();
//operator_test();
// predicate_test();
bitset_test();
c_clock_test();
cpp_clock_test();
return 0;
}
| 22.536585 | 59 | 0.675325 |
0a266fc73810200877750334d795b4558aaf7381 | 1,531 | cpp | C++ | src/vector_types.cpp | DoubleJump/waggle | 06a2fb07d7e3678f990396d1469cf4f85e3863a1 | [
"MIT"
] | 1 | 2021-04-30T11:14:32.000Z | 2021-04-30T11:14:32.000Z | src/vector_types.cpp | DoubleJump/waggle | 06a2fb07d7e3678f990396d1469cf4f85e3863a1 | [
"MIT"
] | null | null | null | src/vector_types.cpp | DoubleJump/waggle | 06a2fb07d7e3678f990396d1469cf4f85e3863a1 | [
"MIT"
] | null | null | null | struct Vec2
{
f32 x, y;
f32& operator[](int i){ return (&x)[i]; }
};
struct Vec3
{
f32 x, y, z;
f32& operator[](int i){ return (&x)[i]; }
};
static Vec3 vec3_up = {0,1,0};
static Vec3 vec3_down = {0,-1,0};
static Vec3 vec3_left = {-1,0,0};
static Vec3 vec3_right = {1,0,0};
static Vec3 vec3_forward = {0,0,1};
static Vec3 vec3_back = {0,0,-1};
static Vec3 vec3_zero = {0,0,0};
static Vec3 vec3_one = {1,1,1};
struct Vec4
{
f32 x, y, z, w;
f32& operator[](int i){ return (&x)[i]; }
};
struct Mat3
{
f32 m[9];
f32& operator[](int i){ return m[i]; }
};
struct Mat4
{
f32 m[16];
f32& operator[](int i){ return m[i]; };
};
struct Ray
{
Vec3 origin;
Vec3 direction;
f32 length;
};
struct AABB
{
Vec3 min;
Vec3 max;
};
struct Bezier_Segment
{
Vec3 a,b,c,d;
};
struct Triangle
{
Vec3 a,b,c;
};
struct Plane
{
Vec3 position;
Vec3 normal;
};
struct Sphere
{
Vec3 position;
f32 radius;
};
struct Capsule
{
Vec3 position;
f32 radius;
f32 height;
};
struct Hit_Info
{
b32 hit;
Vec3 point;
Vec3 normal;
f32 t;
};
enum struct Float_Primitive
{
F32 = 0,
VEC2 = 1,
VEC3 = 2,
VEC4 = 3,
QUATERNION = 4,
};
static u32
get_stride(Float_Primitive p)
{
switch(p)
{
case Float_Primitive::F32: return 1;
case Float_Primitive::VEC2: return 2;
case Float_Primitive::VEC3: return 3;
case Float_Primitive::VEC4: return 4;
case Float_Primitive::QUATERNION: return 4;
}
} | 13.918182 | 46 | 0.580666 |
0a26a32a3eaa6c15d09010643fef518594583b5f | 1,202 | cpp | C++ | src/example/greating_client.cpp | Nekrolm/grpc_callback | 1f0db9f2dd60afe1fac400e6541698d8f1fc4c34 | [
"WTFPL"
] | 3 | 2019-07-27T16:01:01.000Z | 2022-03-01T00:09:19.000Z | src/example/greating_client.cpp | Nekrolm/grpc_callback | 1f0db9f2dd60afe1fac400e6541698d8f1fc4c34 | [
"WTFPL"
] | null | null | null | src/example/greating_client.cpp | Nekrolm/grpc_callback | 1f0db9f2dd60afe1fac400e6541698d8f1fc4c34 | [
"WTFPL"
] | null | null | null | #include "greating_client.h"
#include <grpcpp/channel.h>
#include <functional>
#include <thread>
#include <memory>
#include <grpc/simplified_async_callback_api.h>
GreatingClient::GreatingClient(std::shared_ptr<grpc::Channel> ch) :
stub_(test::Greeting::NewStub(ch))
{}
GreatingClient::~GreatingClient()
{}
void GreatingClient::greeting(const std::string& name)
{
test::HelloRequest request;
request.set_name(name);
grpc::simple_responce_handler_t<test::HelloReply> callback = [](std::shared_ptr<test::HelloReply> reply,
std::shared_ptr<grpc::Status> status) {
if (status->ok())
std::cout << reply->message() << std::endl;
else
std::cout << "failed!" << std::endl;
};
client_.request(stub_.get(), &test::Greeting::Stub::AsyncSayHello, request, callback);
}
| 35.352941 | 116 | 0.46589 |
0a2a3b88dd3554373e63dcb5ff92d9a0bd52f202 | 10,241 | hxx | C++ | src/Utils/Table.hxx | ebertolazzi/Malloc | 4c1f8950cd631c185e141aaccfe0cd53daa91490 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | src/Utils/Table.hxx | ebertolazzi/Malloc | 4c1f8950cd631c185e141aaccfe0cd53daa91490 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | src/Utils/Table.hxx | ebertolazzi/Malloc | 4c1f8950cd631c185e141aaccfe0cd53daa91490 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | /*--------------------------------------------------------------------------*\
| |
| Copyright (C) 2021 |
| |
| , __ , __ |
| /|/ \ /|/ \ |
| | __/ _ ,_ | __/ _ ,_ |
| | \|/ / | | | | \|/ / | | | |
| |(__/|__/ |_/ \_/|/|(__/|__/ |_/ \_/|/ |
| /| /| |
| \| \| |
| |
| Enrico Bertolazzi |
| Dipartimento di Ingegneria Industriale |
| Universita` degli Studi di Trento |
| email: enrico.bertolazzi@unitn.it |
| |
\*--------------------------------------------------------------------------*/
///
/// eof: Table.hxx
///
/*\
Based on terminal-table:
https://github.com/Bornageek/terminal-table
Copyright 2015 Andreas Wilhelm
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.
\*/
namespace Utils {
namespace Table {
using std::string;
using std::vector;
class Table;
typedef int integer;
enum Alignment { LEFT, RIGHT, CENTER };
class Style {
private:
char m_border_top = '-';
char m_border_top_mid = '+';
char m_border_top_left = '+';
char m_border_top_right = '+';
char m_border_bottom = '-';
char m_border_bottom_mid = '+';
char m_border_bottom_left = '+';
char m_border_bottom_right = '+';
char m_border_left = '|';
char m_border_left_mid = '+';
char m_border_mid = '-';
char m_border_mid_mid = '+';
char m_border_right = '|';
char m_border_right_mid = '+';
char m_border_middle = '|';
integer m_padding_left = 1;
integer m_padding_right = 1;
Alignment m_Align = Alignment::LEFT;
integer m_Width = 0;
public:
Style() = default;
char border_top() const { return m_border_top; }
void border_top( char borderStyle ) { m_border_top = borderStyle; }
char border_top_mid() const { return m_border_top_mid; }
void border_top_mid( char borderStyle ) { m_border_top_mid = borderStyle; }
char border_top_left() const { return m_border_top_left; }
void border_top_left( char borderStyle ) { m_border_top_left = borderStyle; }
char border_top_right() const { return m_border_top_right; }
void border_top_right( char borderStyle ) { m_border_top_right = borderStyle; }
char border_bottom() const { return m_border_bottom; }
void border_bottom( char borderStyle ) { m_border_bottom = borderStyle; }
char border_bottom_mid() const { return m_border_bottom_mid; }
void border_bottom_mid( char borderStyle ) { m_border_bottom_mid = borderStyle; }
char border_bottom_left() const { return m_border_bottom_left; }
void border_bottom_left( char borderStyle ) { m_border_bottom_left = borderStyle; }
char border_bottom_right() const { return m_border_bottom_right; }
void border_bottom_right( char borderStyle) { m_border_bottom_right = borderStyle; }
char border_left() const { return m_border_left; }
void border_left( char borderStyle ) { m_border_left = borderStyle; }
char border_left_mid() const { return m_border_left_mid; }
void border_left_mid( char borderStyle ) { m_border_left_mid = borderStyle; }
char border_mid() const { return m_border_mid; }
void border_mid( char borderStyle ) { m_border_mid = borderStyle; }
char border_mid_mid() const { return m_border_mid_mid; }
void border_mid_mid( char borderStyle ) { m_border_mid_mid = borderStyle; }
char border_right() const { return m_border_right; }
void border_right( char borderStyle ) { m_border_right = borderStyle; }
char border_right_mid() const { return m_border_right_mid; }
void border_right_mid( char borderStyle ) { m_border_right_mid = borderStyle; }
char border_middle() const { return m_border_middle; }
void border_middle( char borderStyle ) { m_border_middle = borderStyle; }
integer padding_left() const { return m_padding_left; }
void padding_left( integer padding ) { m_padding_left = padding; }
integer padding_right() const { return m_padding_right; }
void padding_right( integer padding ) { m_padding_right = padding; }
Alignment alignment() const { return m_Align; }
void alignment( Alignment align ) { m_Align = align; }
integer width() const { return m_Width; }
void width( integer width ) { m_Width = width; }
};
class Cell {
private:
Table * m_Table = nullptr;
std::string m_Value = "";
Alignment m_Align = Alignment::LEFT;
integer m_col_span = 1;
integer m_Width = 0;
public:
Cell() = default;
explicit
Cell(
Table* table,
std::string const & val = "",
integer col_span = 1
);
std::string const & value() const { return m_Value; }
void value( std::string const & val ) { m_Value = val; }
Alignment alignment() const { return m_Align; }
void alignment( Alignment align ) { m_Align = align; }
integer col_span() const { return m_col_span; }
void col_span( integer col_span ) { m_col_span = col_span; }
integer width( integer col ) const;
integer height() const;
integer maximum_line_width() const;
std::string line( integer idx ) const;
void trim_line( std::string & line ) const;
std::string render( integer line, integer col ) const;
};
class Row {
protected:
typedef std::vector<Cell> vecCell;
typedef std::vector<std::string> vecstr;
Table * m_Table = nullptr;
vecCell m_Cells;
public:
Row() = default;
explicit
Row(
Table * table,
vecstr const & cells = vecstr()
);
Table const * table() const { return m_Table; }
//vecCell & cells() { return m_Cells; }
void cells( vecstr const & cells );
integer num_cells() const { return integer(m_Cells.size()); }
integer cell_width( integer idx ) const;
void cell_col_span( integer idx, integer span );
void cell( std::string const & value );
//Cell& cell( integer idx ) { return m_Cells[idx]; }
Cell const & operator [] ( integer idx ) const { return m_Cells[idx]; }
Cell & operator [] ( integer idx ) { return m_Cells[idx]; }
integer height() const;
std::string render() const;
};
class Table {
public:
typedef std::vector<Row> vecRow;
typedef std::vector<Cell> vecCell;
typedef std::vector<string> vecstr;
typedef std::vector<vecstr> vecvecstr;
typedef int integer;
private:
Style m_Style;
std::string m_Title;
Row m_Headings;
vecRow m_Rows;
public:
Table() = default;
explicit
Table(
Style const & style,
vecvecstr const & rows = vecvecstr()
)
: m_Style(style) {
this->rows(rows);
}
void
setup(
Style const & style,
vecvecstr const & rows = vecvecstr()
) {
m_Style = style;
this->rows(rows);
}
void align_column( integer n, Alignment align );
void add_row( vecstr const & row );
integer cell_spacing() const;
integer cell_padding() const;
vecCell column( integer n ) const;
integer column_width( integer n ) const;
integer num_columns() const;
Style const & style() const { return m_Style; }
void style( Style const & style ) { m_Style = style; }
std::string const & title() const { return m_Title; }
void title( std::string const & title ) { m_Title = title; }
Row const & headings() const { return m_Headings; }
void headings( vecstr const & headings );
Row & row( integer n );
Row const & row( integer n ) const;
Row & operator [] ( integer n ) { return this->row(n); }
Row const & operator [] ( integer n ) const { return this->row(n); }
Cell & operator () ( integer i, integer j ) { return (*this)[i][j]; }
Cell const & operator () ( integer i, integer j ) const { return (*this)[i][j]; }
vecRow const & rows() const { return m_Rows; }
void rows( vecvecstr const & rows );
std::string
render_separator(
char left,
char mid,
char right,
char sep
) const;
std::string render() const;
};
}
}
inline
Utils::ostream_type&
operator << ( Utils::ostream_type& stream, Utils::Table::Row const & row ) {
return stream << row.render();
}
inline
Utils::ostream_type&
operator << ( Utils::ostream_type& stream, Utils::Table::Table const & table ) {
return stream << table.render();
}
///
/// eof: Table.hxx
///
| 31.318043 | 90 | 0.545357 |
0a2b9aa43d2163f100733f5db0c10da558261d11 | 674 | cpp | C++ | Zadanie 3-2 nowe/src/main.cpp | Jakub-Serafin/pm-lab-3-sn | 70027bc7da56b2cba7cf17d3a34beb5602737111 | [
"Apache-2.0"
] | null | null | null | Zadanie 3-2 nowe/src/main.cpp | Jakub-Serafin/pm-lab-3-sn | 70027bc7da56b2cba7cf17d3a34beb5602737111 | [
"Apache-2.0"
] | null | null | null | Zadanie 3-2 nowe/src/main.cpp | Jakub-Serafin/pm-lab-3-sn | 70027bc7da56b2cba7cf17d3a34beb5602737111 | [
"Apache-2.0"
] | null | null | null | #include <Arduino.h>
#include <stdint.h>
#define FOSC 16000000
#define BAUD 9600
#define MY_UBRR (FOSC/16/BAUD-1)
#define USE_UART_RX_IRQ 1
char ReceivedChar;
char Message[] = "Hello";
char * pMessage = Message;
void setup(){
UBRR0H=(MY_UBRR>>8);
UBRR0L= MY_UBRR;
UCSR0B |= (1<< RXEN0)| (1<< TXEN0);
UCSR0C|= (1<< UCSZ01)| (1<< UCSZ00);
while(*pMessage){
while (!(UCSR0A &(1<<UDRE0)) );
UDR0 = *pMessage;
pMessage++;
}
#if (USE_UART_RX_IRQ == 1)
UCSR0B |=(1<< RXCIE0);
#endif
}
void loop(){
#if (USE_UART_RX_IRQ ==0)
#endif
}
#if (USE_UART_RX_IRQ == 1)
ISR (USART_RX_vect){
ReceivedChar = UDR0;
UDR0 = ReceivedChar;
}
#endif
//to jest zadanie 3-2-4 | 17.736842 | 38 | 0.646884 |
0a2d06bc7e22d43976c5d56ab0c34f1f7e1b7e70 | 339 | cpp | C++ | Competitive Programing Problem Solutions/C++ Tutorial-Code - OOP/m4-d.cpp | BIJOY-SUST/ACM---ICPC | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | 1 | 2022-02-27T12:07:59.000Z | 2022-02-27T12:07:59.000Z | Competitive Programing Problem Solutions/C++ Tutorial-Code - OOP/m4-d.cpp | BIJOY-SUST/Competitive-Programming | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | null | null | null | Competitive Programing Problem Solutions/C++ Tutorial-Code - OOP/m4-d.cpp | BIJOY-SUST/Competitive-Programming | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int factorial(int n){
return (n == 1 || n == 0) ? 1 : factorial(n - 1)*n;
}
int main(){
int T,N,M;
cin>>T;
while(T--){
int ans;
cin>>N>>M;
ans = factorial(N+M-1)/(factorial(N)*factorial(M-1));
cout<<ans<<endl;
}
return 0;
}
| 19.941176 | 62 | 0.471976 |
0a2d609e9dbd9540d570fb36b415739333d2abb0 | 387 | cpp | C++ | clang/test/SemaCXX/lookup-through-linkage.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | 605 | 2019-10-18T01:15:54.000Z | 2022-03-31T14:31:04.000Z | clang/test/SemaCXX/lookup-through-linkage.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | 3,180 | 2019-10-18T01:21:21.000Z | 2022-03-31T23:25:41.000Z | clang/test/SemaCXX/lookup-through-linkage.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | 275 | 2019-10-18T05:27:22.000Z | 2022-03-30T09:04:21.000Z | // RUN: %clang_cc1 %s -verify
// expected-no-diagnostics
extern "C++" {
namespace A {
namespace B {
int bar;
}
} // namespace A
namespace C {
void foo() {
using namespace A;
(void)B::bar;
}
} // namespace C
}
extern "C" {
extern "C++" {
namespace D {
namespace E {
int bar;
}
} // namespace A
namespace F {
void foo() {
using namespace D;
(void)E::bar;
}
} // namespace C
}
}
| 11.382353 | 29 | 0.602067 |
0a2ed7375825eafbffc9a933d77cf1f6cfc96180 | 685 | cpp | C++ | src/QtYangVrRecord/src/video/yangrecordwin.cpp | yangxinghai/yangrecord | 787eaca132df1e427f5fc5b4391db1436d481088 | [
"MIT"
] | 1 | 2021-11-11T02:06:55.000Z | 2021-11-11T02:06:55.000Z | src/QtYangVrRecord/src/video/yangrecordwin.cpp | yangxinghai/yangrecord | 787eaca132df1e427f5fc5b4391db1436d481088 | [
"MIT"
] | null | null | null | src/QtYangVrRecord/src/video/yangrecordwin.cpp | yangxinghai/yangrecord | 787eaca132df1e427f5fc5b4391db1436d481088 | [
"MIT"
] | 1 | 2022-01-24T07:59:48.000Z | 2022-01-24T07:59:48.000Z | #include "yangrecordwin.h"
#include "yangutil/yangtype.h"
#include <QMenu>
#include <QAction>
#include <QDebug>
//#include "../tooltip/RDesktopTip.h"
#include "../yangwinutil/yangrecordcontext.h"
YangRecordWin::YangRecordWin(QWidget *parent):QWidget(parent)
{
m_hb=new QHBoxLayout();
m_hb->setMargin(0);
m_hb->setSpacing(1);
setLayout(m_hb);
this->setAutoFillBackground(true);
//m_selectUser=nullptr;
vwin=nullptr;
//this->setWidget(m_centerWdiget);
}
YangRecordWin::~YangRecordWin()
{
// m_mh=nullptr;
//m_selectUser=nullptr;
// if(1) return;
YANG_DELETE(vwin);
YANG_DELETE(m_hb);
}
void YangRecordWin::init(){
}
| 15.222222 | 61 | 0.671533 |
0a2f8e4a67a74949a182496fb002fdf38f79a3e7 | 5,912 | cpp | C++ | Sources/CEigenBridge/eigen_dbl.cpp | taketo1024/swm-eigen | 952ecdb73a2739641e75909c8d9e724e32b2ed0f | [
"MIT"
] | 6 | 2021-09-19T07:55:41.000Z | 2021-11-10T00:43:47.000Z | Sources/CEigenBridge/eigen_dbl.cpp | taketo1024/swm-eigen | 952ecdb73a2739641e75909c8d9e724e32b2ed0f | [
"MIT"
] | null | null | null | Sources/CEigenBridge/eigen_dbl.cpp | taketo1024/swm-eigen | 952ecdb73a2739641e75909c8d9e724e32b2ed0f | [
"MIT"
] | null | null | null | //
// File.cpp
//
//
// Created by Taketo Sano on 2021/06/10.
//
#import "eigen_dbl.h"
#import <iostream>
#import <Eigen/Eigen>
using namespace std;
using namespace Eigen;
using R = double;
using Mat = Matrix<R, Dynamic, Dynamic>;
void *eigen_dbl_init(int_t rows, int_t cols) {
Mat *A = new Mat(rows, cols);
A->setZero();
return static_cast<void *>(A);
}
void eigen_dbl_free(void *ptr) {
Mat *A = static_cast<Mat *>(ptr);
delete A;
}
void eigen_dbl_copy(void *from, void *to) {
Mat *A = static_cast<Mat *>(from);
Mat *B = static_cast<Mat *>(to);
*B = *A;
}
double eigen_dbl_get_entry(void *a, int_t i, int_t j) {
Mat *A = static_cast<Mat *>(a);
return A->coeff(i, j);
}
void eigen_dbl_set_entry(void *a, int_t i, int_t j, double r) {
Mat *A = static_cast<Mat *>(a);
A->coeffRef(i, j) = r;
}
void eigen_dbl_copy_entries(void *a, double *vals) {
Mat *A = static_cast<Mat *>(a);
for(int_t i = 0; i < A->rows(); i++) {
for(int_t j = 0; j < A->cols(); j++) {
*(vals++) = A->coeff(i, j);
}
}
}
int_t eigen_dbl_rows(void *a) {
Mat *A = static_cast<Mat *>(a);
return A->rows();
}
int_t eigen_dbl_cols(void *a) {
Mat *A = static_cast<Mat *>(a);
return A->cols();
}
bool eigen_dbl_is_zero(void *a) {
Mat *A = static_cast<Mat *>(a);
return A->isZero();
}
double eigen_dbl_det(void *a) {
Mat *A = static_cast<Mat *>(a);
return A->determinant();
}
double eigen_dbl_trace(void *a) {
Mat *A = static_cast<Mat *>(a);
return A->trace();
}
void eigen_dbl_inv(void *a, void *b) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
*B = A->inverse();
}
void eigen_dbl_transpose(void *a, void *b) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
*B = A->transpose();
}
void eigen_dbl_submatrix(void *a, int_t i, int_t j, int_t h, int_t w, void *b) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
*B = A->block(i, j, h, w);
}
void eigen_dbl_concat(void *a, void *b, void *c) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
Mat *C = static_cast<Mat *>(c);
C->leftCols(A->cols()) = *A;
C->rightCols(B->cols()) = *B;
}
void eigen_dbl_stack(void *a, void *b, void *c) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
Mat *C = static_cast<Mat *>(c);
C->topRows(A->rows()) = *A;
C->bottomRows(B->rows()) = *B;
}
void eigen_dbl_perm_rows(void *a, perm_t p, void *b) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
Eigen::VectorXi indices(p.length);
for(int_t i = 0; i < p.length; ++i) {
indices[i] = p.indices[i];
}
PermutationMatrix<Eigen::Dynamic> P(indices);
*B = P * (*A);
}
void eigen_dbl_perm_cols(void *a, perm_t p, void *b) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
Eigen::VectorXi indices(p.length);
for(int_t i = 0; i < p.length; ++i) {
indices[i] = p.indices[i];
}
PermutationMatrix<Eigen::Dynamic> P(indices);
*B = (*A) * P.transpose();
}
bool eigen_dbl_eq(void *a, void *b) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
return (*A).isApprox(*B);
}
void eigen_dbl_add(void *a, void *b, void *c) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
Mat *C = static_cast<Mat *>(c);
*C = *A + *B;
}
void eigen_dbl_neg(void *a, void *b) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
*B = -(*A);
}
void eigen_dbl_minus(void *a, void *b, void *c) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
Mat *C = static_cast<Mat *>(c);
*C = *A - *B;
}
void eigen_dbl_mul(void *a, void *b, void *c) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
Mat *C = static_cast<Mat *>(c);
*C = (*A) * (*B);
}
void eigen_dbl_scal_mul(double r, void *a, void *b) {
Mat *A = static_cast<Mat *>(a);
Mat *B = static_cast<Mat *>(b);
*B = r * (*A);
}
void eigen_dbl_lu(void *a, perm_t p, perm_t q, void *l, void *u) {
Mat *A = static_cast<Mat *>(a);
Mat *L = static_cast<Mat *>(l);
Mat *U = static_cast<Mat *>(u);
int_t n = A->rows();
int_t m = A->cols();
if(n == 0 || m == 0) {
L->resize(n, 0);
U->resize(0, m);
} else {
using LU = FullPivLU<Mat>;
LU lu(*A);
int_t r = lu.rank();
// make P
LU::PermutationPType::IndicesType P = lu.permutationP().indices();
for(int_t i = 0; i < n; ++i) {
p.indices[i] = P[i];
}
// make Q
LU::PermutationQType::IndicesType Q = lu.permutationQ().indices();
for(int_t i = 0; i < m; ++i) {
q.indices[i] = Q[i];
}
// make L
L->resize(n, r);
L->setIdentity();
L->triangularView<StrictlyLower>() = lu.matrixLU().block(0, 0, n, r);
// make U
U->resize(r, m);
U->triangularView<Upper>() = lu.matrixLU().block(0, 0, r, m);
}
}
void eigen_dbl_solve_lt(void *l, void *b, void *x) {
Mat *L = static_cast<Mat *>(l);
Mat *B = static_cast<Mat *>(b);
Mat *X = static_cast<Mat *>(x);
using DMat = Matrix<R, Dynamic, Dynamic>;
DMat b_ = *B;
DMat x_ = L->triangularView<Lower>().solve(b_);
*X = x_.sparseView();
}
void eigen_dbl_solve_ut(void *u, void *b, void *x) {
Mat *U = static_cast<Mat *>(u);
Mat *B = static_cast<Mat *>(b);
Mat *X = static_cast<Mat *>(x);
using DMat = Matrix<R, Dynamic, Dynamic>;
DMat b_ = *B;
DMat x_ = U->triangularView<Upper>().solve(b_);
*X = x_.sparseView();
}
void eigen_dbl_dump(void *ptr) {
Mat *m = static_cast<Mat *>(ptr);
cout << *m << endl;
}
| 24.03252 | 80 | 0.538058 |
0a30f745e13504ad1b5ed62319ce67bdfb9ab3f3 | 7,152 | inl | C++ | MathLib/Include/CoordinatePoints.inl | bgin/MissileSimulation | 90adcbf1c049daafb939f3fe9f9dfe792f26d5df | [
"MIT"
] | 23 | 2016-08-28T23:20:12.000Z | 2021-12-15T14:43:58.000Z | MathLib/Include/CoordinatePoints.inl | bgin/MissileSimulation | 90adcbf1c049daafb939f3fe9f9dfe792f26d5df | [
"MIT"
] | 1 | 2018-06-02T21:29:51.000Z | 2018-06-05T05:59:31.000Z | MathLib/Include/CoordinatePoints.inl | bgin/MissileSimulation | 90adcbf1c049daafb939f3fe9f9dfe792f26d5df | [
"MIT"
] | 1 | 2019-07-04T22:38:22.000Z | 2019-07-04T22:38:22.000Z |
mathlib::CoordPoints<__m128>::CoordPoints() {
/*Initialize coordinates to zero*/
this->m_F32Coord3D = _mm_setzero_ps();
}
mathlib::CoordPoints<__m128>::CoordPoints(_In_ const float x, _In_ const float y, _In_ const float z) :
m_F32Coord3D(_mm_set_ps(NAN_FLT, z, y, x)) {
}
mathlib::CoordPoints<__m128>::CoordPoints(_In_ const float s) :
m_F32Coord3D(_mm_set_ps(NAN_FLT, s, s, s)) {
}
mathlib::CoordPoints<__m128>::CoordPoints(_In_ const double x, _In_ const double y, _In_ const double z) :
/* Warning: Precion is lost from ~16 digits to ~8*/
m_F32Coord3D(_mm256_cvtpd_ps(_mm256_set_pd(NAN_DBL, z, y, x))) {
}
mathlib::CoordPoints<__m128>::CoordPoints(_In_ float(&ar)[4]) :
m_F32Coord3D(_mm_loadu_ps(&ar[0])) {
}
mathlib::CoordPoints<__m128>::CoordPoints(_In_ const std::initializer_list<float> &list) :
m_F32Coord3D(_mm_loadu_ps(&list.begin()[0])){
}
mathlib::CoordPoints<__m128>::CoordPoints(_In_ const __m128 &v) :
m_F32Coord3D(v) {
}
mathlib::CoordPoints<__m128>::CoordPoints(_In_ const CoordPoints &rhs) :
m_F32Coord3D(rhs.m_F32Coord3D){
}
mathlib::CoordPoints<__m128>::CoordPoints(_In_ CoordPoints &&rhs) :
m_F32Coord3D(std::move(rhs.m_F32Coord3D)) {
}
auto mathlib::CoordPoints<__m128>::operator=(_In_ const CoordPoints &rhs)->mathlib::CoordPoints<__m128> &{
if (this == &rhs) return (*this);
this->m_F32Coord3D = rhs.m_F32Coord3D;
return (*this);
}
auto mathlib::CoordPoints<__m128>::operator=(_In_ const CoordPoints &&rhs)->mathlib::CoordPoints<__m128> & {
if (this == &rhs) return (*this);
this->m_F32Coord3D = std::move(rhs.m_F32Coord3D);
return (*this);
}
auto mathlib::CoordPoints<__m128>::operator+=(_In_ const CoordPoints &rhs)->mathlib::CoordPoints<__m128> & {
this->m_F32Coord3D = _mm_add_ps(this->m_F32Coord3D, rhs.m_F32Coord3D);
return (*this);
}
auto mathlib::CoordPoints<__m128>::operator+=(_In_ const float s)->mathlib::CoordPoints<__m128> & {
this->m_F32Coord3D = _mm_add_ps(this->m_F32Coord3D,_mm_set_ps(NAN_FLT, s, s, s));
return (*this);
}
auto mathlib::CoordPoints<__m128>::operator-=(_In_ const CoordPoints &rhs)->mathlib::CoordPoints<__m128> & {
this->m_F32Coord3D = _mm_sub_ps(this->m_F32Coord3D, rhs.m_F32Coord3D);
return (*this);
}
auto mathlib::CoordPoints<__m128>::operator-=(_In_ const float s)->mathlib::CoordPoints<__m128> & {
this->m_F32Coord3D = _mm_sub_ps(this->m_F32Coord3D, _mm_set_ps(NAN_FLT, s, s, s));
return (*this);
}
auto mathlib::CoordPoints<__m128>::operator*=(_In_ const CoordPoints &rhs)->mathlib::CoordPoints<__m128> & {
this->m_F32Coord3D = _mm_mul_ps(this->m_F32Coord3D, rhs.m_F32Coord3D);
return (*this);
}
auto mathlib::CoordPoints<__m128>::operator*=(_In_ const float s)->mathlib::CoordPoints<__m128> & {
this->m_F32Coord3D = _mm_mul_ps(this->m_F32Coord3D, _mm_set_ps(NAN_FLT, s, s, s));
return (*this);
}
auto mathlib::CoordPoints<__m128>::operator/=(_In_ const CoordPoints &rhs)->mathlib::CoordPoints<__m128> & {
if (!(_mm_testz_ps(rhs.m_F32Coord3D, _mm_set_ps(NAN_FLT, 0.f, 0.f, 0.f)))){
this->m_F32Coord3D = _mm_mul_ps(this->m_F32Coord3D, _mm_rcp_ps(rhs.m_F32Coord3D));
return (*this);
}
}
auto mathlib::CoordPoints<__m128>::operator/=(_In_ const float s)->mathlib::CoordPoints<__m128> & {
if (s != 0.f){
float inv_s{ 1.f / s };
this->m_F32Coord3D = _mm_mul_ps(this->m_F32Coord3D, _mm_set_ps(NAN_FLT, inv_s, inv_s, inv_s));
return (*this);
}
}
auto mathlib::CoordPoints<__m128>::operator==(_In_ const CoordPoints &rhs)const-> __m128 {
return (_mm_cmpeq_ps(this->m_F32Coord3D, rhs.m_F32Coord3D));
}
auto mathlib::CoordPoints<__m128>::operator==(_In_ const float s)const-> __m128 {
// 3rd scalar counting from 0 = Don't care
return (_mm_cmpeq_ps(this->m_F32Coord3D, _mm_set_ps(NAN_FLT, s, s, s)));
}
auto mathlib::CoordPoints<__m128>::operator!=(_In_ const CoordPoints &rhs)const-> __m128 {
return (_mm_cmpneq_ps(this->m_F32Coord3D, rhs.m_F32Coord3D));
}
auto mathlib::CoordPoints<__m128>::operator!=(_In_ const float s)const-> __m128 {
// 3rd scalar counting from 0 = Don't care
return (_mm_cmpneq_ps(this->m_F32Coord3D, _mm_set_ps(NAN_FLT, s, s, s)));
}
mathlib::CoordPoints<__m128>::operator __m128 () {
return this->m_F32Coord3D;
}
mathlib::CoordPoints<__m128>::operator __m128 const () const {
return this->m_F32Coord3D;
}
auto mathlib::operator<<(_In_ std::ostream &os, _In_ const mathlib::CoordPoints<__m128> &rhs)->std::ostream & {
os << "X: " << reinterpret_cast<const double*>(&rhs.m_F32Coord3D)[0] << std::endl;
os << "Y: " << reinterpret_cast<const double*>(&rhs.m_F32Coord3D)[1] << std::endl;
os << "Z: " << reinterpret_cast<const double*>(&rhs.m_F32Coord3D)[2] << std::endl;
return os;
}
inline auto mathlib::CoordPoints<__m128>::getF32Coord3D()const-> __m128 {
return this->m_F32Coord3D;
}
inline auto mathlib::CoordPoints<__m128>::X()const->float {
return (reinterpret_cast<const double*>(&this->m_F32Coord3D)[0]);
}
inline auto mathlib::CoordPoints<__m128>::Y()const->float {
return (reinterpret_cast<const double*>(&this->m_F32Coord3D)[1]);
}
inline auto mathlib::CoordPoints<__m128>::Z()const->float {
return (reinterpret_cast<const double*>(&this->m_F32Coord3D)[2]);
}
inline auto mathlib::CoordPoints<__m128>::CArray()->double * {
double* pF32Coord3D = nullptr;
pF32Coord3D = reinterpret_cast<double*>(&this->m_F32Coord3D);
return (pF32Coord3D);
}
inline auto mathlib::CoordPoints<__m128>::CArray()const->const double * {
const double* pF32Coord3D = nullptr;
pF32Coord3D = reinterpret_cast<const double*>(&this->m_F32Coord3D);
return (pF32Coord3D);
}
inline auto mathlib::CoordPoints<__m128>::setX(_In_ const float s)->void {
this->m_F32Coord3D.m128_f32[0] = s;
}
inline auto mathlib::CoordPoints<__m128>::setY(_In_ const float s)->void {
this->m_F32Coord3D.m128_f32[1] = s;
}
inline auto mathlib::CoordPoints<__m128>::setZ(_In_ const float s)->void {
this->m_F32Coord3D.m128_f32[2] = s;
}
inline auto mathlib::CoordPoints<__m128>::magnitude()const->float {
auto temp(_mm_mul_ps(this->m_F32Coord3D, this->m_F32Coord3D));
return (reinterpret_cast<const double*>(&temp)[0] +
reinterpret_cast<const double*>(&temp)[1] +
reinterpret_cast<const double*>(&temp)[2]);
}
inline auto mathlib::CoordPoints<__m128>::perpendicular()const->float {
auto temp(_mm_mul_ps(this->m_F32Coord3D, this->m_F32Coord3D));
return (reinterpret_cast<const double*>(&temp)[0] + reinterpret_cast<const double*>(&temp)[1]);
}
inline auto mathlib::CoordPoints<__m128>::rho()const->float {
return (std::sqrt(this->perpendicular()));
}
inline auto mathlib::CoordPoints<__m128>::phi()const->float {
return((this->X() == 0.f && this->Y() == 0.f) ? 0.f : std::atan2(this->X(), this->Y()));
}
inline auto mathlib::CoordPoints<__m128>::theta()const->float {
return ((this->X() == 0.f && this->Y() == 0.f && this->Z()) ? 0.f : std::atan2(this->rho(), this->Z()));
} | 31.646018 | 115 | 0.685263 |
0a37e91c00ea720fe4fc3942d74ef52cc8dae67b | 3,082 | cpp | C++ | old.c++/AGIResources/PlatformAbstractionLayer_POSIX.cpp | princess-rosella/sierra-agi-resources | 2755e7b04a4f9782ced4530016e4374ca5b7985b | [
"MIT"
] | null | null | null | old.c++/AGIResources/PlatformAbstractionLayer_POSIX.cpp | princess-rosella/sierra-agi-resources | 2755e7b04a4f9782ced4530016e4374ca5b7985b | [
"MIT"
] | null | null | null | old.c++/AGIResources/PlatformAbstractionLayer_POSIX.cpp | princess-rosella/sierra-agi-resources | 2755e7b04a4f9782ced4530016e4374ca5b7985b | [
"MIT"
] | null | null | null | //
// PlatformAbstractionLayer_POSIX.cpp
// AGI
//
// Copyright (c) 2018 Princess Rosella. All rights reserved.
//
#include "AGIResources.hpp"
#include "PlatformAbstractionLayer_POSIX.hpp"
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <vector>
using namespace AGI::Resources;
PlatformAbstractionLayer_POSIX_FileDescriptor::PlatformAbstractionLayer_POSIX_FileDescriptor(int desc) : _desc(desc) {
}
PlatformAbstractionLayer_POSIX_FileDescriptor::~PlatformAbstractionLayer_POSIX_FileDescriptor() {
if (_desc >= 0)
close(_desc);
}
ssize_t PlatformAbstractionLayer_POSIX_FileDescriptor::readall(void* data, size_t length) {
ssize_t readed = 0;
while (length) {
ssize_t thisRead = read(_desc, data, length);
if (thisRead < 0)
return thisRead;
else if (thisRead == 0)
break;
data = ((uint8_t*)data) + thisRead;
length -= thisRead;
}
if (length)
memset(data, 0, length);
return readed;
}
PlatformAbstractionLayer_POSIX::PlatformAbstractionLayer_POSIX(const std::string& folder) : _folder(folder) {
if (_folder.length() == 0) {
_folder = "./";
return;
}
if (_folder[_folder.length() - 1] == '/')
return;
_folder += '/';
}
std::string PlatformAbstractionLayer_POSIX::fullPathName(const char* fileName) const {
return _folder + fileName;
}
bool PlatformAbstractionLayer_POSIX::fileExists(const char* fileName) const {
if (access(fullPathName(fileName).c_str(), R_OK))
return false;
return true;
}
size_t PlatformAbstractionLayer_POSIX::fileSize(const char* fileName) const {
struct stat st;
if (stat(fullPathName(fileName).c_str(), &st))
return (size_t)-1u;
return (size_t)st.st_size;
}
bool PlatformAbstractionLayer_POSIX::fileRead(const char* fileName, size_t offset, void* data, size_t length) const {
std::unique_ptr<PlatformAbstractionLayer_POSIX_FileDescriptor> fd(new PlatformAbstractionLayer_POSIX_FileDescriptor(open(fullPathName(fileName).c_str(), O_RDONLY)));
if (offset) {
if (lseek(fd->desc(), offset, SEEK_SET) == -1)
throw std::runtime_error(strerror(errno));
}
if (fd->readall(data, length) < 0)
throw std::runtime_error(strerror(errno));
return true;
}
std::vector<std::string> PlatformAbstractionLayer_POSIX::fileList() const {
DIR *dir = opendir(_folder.c_str());
if (!dir)
return std::vector<std::string>();
std::vector<std::string> files;
while (struct dirent *entry = readdir(dir)) {
std::string name(entry->d_name, entry->d_namlen);
if (name == "." || name == ".." || name[0] == '.')
continue;
files.push_back(name);
}
closedir(dir);
return files;
}
std::string AGI::Resources::format(const char* format, ...) {
va_list va;
char buffer[2048];
va_start(va, format);
vsnprintf(buffer, sizeof(buffer), format, va);
va_end(va);
return buffer;
}
| 24.854839 | 169 | 0.658014 |
0a3c83602b58e93c47389718b0ec4248917f4c0e | 3,644 | cpp | C++ | PitchedDelay/Source/dsp/simpledetune.cpp | elk-audio/lkjb-plugins | 8cbff01864bdb76493361a46f56d7073d49698da | [
"MIT"
] | 82 | 2016-12-02T20:02:30.000Z | 2022-03-12T22:38:30.000Z | PitchedDelay/Source/dsp/simpledetune.cpp | elk-audio/lkjb-plugins | 8cbff01864bdb76493361a46f56d7073d49698da | [
"MIT"
] | 6 | 2018-01-19T21:44:46.000Z | 2022-03-08T08:46:19.000Z | PitchedDelay/Source/dsp/simpledetune.cpp | elk-audio/lkjb-plugins | 8cbff01864bdb76493361a46f56d7073d49698da | [
"MIT"
] | 16 | 2016-04-13T08:31:36.000Z | 2022-03-01T03:04:42.000Z | #include "simpledetune.h"
DetunerBase::DetunerBase(int bufmax)
: bufMax(bufmax),
windowSize(0),
sampleRate(44100),
buf(bufMax),
win(bufMax)
{
clear();
setWindowSize(bufMax);
}
void DetunerBase::clear()
{
pos0 = 0;
pos1 = 0.f;
pos2 = 0.f;
for(int i=0;i<bufMax;i++)
buf[i] = 0;
}
void DetunerBase::setWindowSize(int size, bool force)
{
//recalculate crossfade window
if (windowSize != size || force)
{
windowSize = size;
if (windowSize >= bufMax)
windowSize = bufMax;
//bufres = 1000.0f * (float)windowSize / sampleRate;
double p=0.0;
double dp = 6.28318530718 / windowSize;
for(int i=0;i<windowSize;i++)
{
win[i] = (float)(0.5 - 0.5 * cos(p));
p+=dp;
}
}
}
void DetunerBase::setPitchSemitones(float newPitch)
{
dpos2 = (float)pow(1.0594631f, newPitch);
dpos1 = 1.0f / dpos2;
}
void DetunerBase::setPitch(float newPitch)
{
dpos2 = newPitch;
dpos1 = 1.0f / dpos2;
}
void DetunerBase::setSampleRate(float newSampleRate)
{
if (sampleRate != newSampleRate)
{
sampleRate = newSampleRate;
setWindowSize(windowSize, true);
}
}
void DetunerBase::processBlock(float* data, int numSamples)
{
float a, b, c, d;
float x;
float p1 = pos1;
float p1f;
float d1 = dpos1;
float p2 = pos2;
float d2 = dpos2;
int p0 = pos0;
int p1i;
int p2i;
int l = windowSize-1;
int lh = windowSize>>1;
float lf = (float) windowSize;
for (int i=0; i<numSamples; ++i)
{
a = data[i];
b = a;
c = 0;
d = 0;
--p0 &= l;
*(buf + p0) = (a); //input
p1 -= d1;
if(p1<0.0f)
p1 += lf; //output
p1i = (int) p1;
p1f = p1 - (float) p1i;
a = *(buf + p1i);
++p1i &= l;
a += p1f * (*(buf + p1i) - a); //linear interpolation
p2i = (p1i + lh) & l; //180-degree ouptut
b = *(buf + p2i);
++p2i &= l;
b += p1f * (*(buf + p2i) - b); //linear interpolation
p2i = (p1i - p0) & l; //crossfade
x = *(win + p2i);
//++p2i &= l;
//x += p1f * (*(win + p2i) - x); //linear interpolation (doesn't do much)
c += b + x * (a - b);
p2 -= d2; //repeat for downwards shift - can't see a more efficient way?
if(p2<0.0f) p2 += lf; //output
p1i = (int) p2;
p1f = p2 - (float) p1i;
a = *(buf + p1i);
++p1i &= l;
a += p1f * (*(buf + p1i) - a); //linear interpolation
p2i = (p1i + lh) & l; //180-degree ouptut
b = *(buf + p2i);
++p2i &= l;
b += p1f * (*(buf + p2i) - b); //linear interpolation
p2i = (p1i - p0) & l; //crossfade
x = *(win + p2i);
//++p2i &= l;
//x += p1f * (*(win + p2i) - x); //linear interpolation (doesn't do much)
d += b + x * (a - b);
data[i] = d;
}
pos0=p0;
pos1=p1;
pos2=p2;
}
int DetunerBase::getWindowSize()
{
return windowSize;
}
// ==============================================================================================================
Detune::Detune(const String& name_, int windowSize)
: name(name_),
tunerL(windowSize),
tunerR(windowSize)
{
}
void Detune::prepareToPlay(double sampleRate, int /*blockSize*/)
{
tunerL.setSampleRate((float) sampleRate);
tunerR.setSampleRate((float) sampleRate);
}
void Detune::processBlock(float* chL, float* chR, int numSamples)
{
tunerL.processBlock(chL, numSamples);
tunerR.processBlock(chR, numSamples);
}
void Detune::processBlock(float* ch, int numSamples)
{
tunerL.processBlock(ch, numSamples);
}
void Detune::setPitch(float newPitch)
{
tunerL.setPitch(newPitch);
tunerR.setPitch(newPitch);
}
int Detune::getLatency()
{
return tunerL.getWindowSize();
}
void Detune::clear()
{
tunerL.clear();
tunerR.clear();
}
String Detune::getName()
{
return name;
}
| 18.591837 | 113 | 0.572448 |
0a3e70e44718dea8c998736ac815ba9c233a23c2 | 1,261 | cc | C++ | src/flow/transform/EmptyBlockElimination.cc | christianparpart/libflow | 29c8a4b4c1ba140c1a3998dcb84885386d312787 | [
"Unlicense"
] | null | null | null | src/flow/transform/EmptyBlockElimination.cc | christianparpart/libflow | 29c8a4b4c1ba140c1a3998dcb84885386d312787 | [
"Unlicense"
] | null | null | null | src/flow/transform/EmptyBlockElimination.cc | christianparpart/libflow | 29c8a4b4c1ba140c1a3998dcb84885386d312787 | [
"Unlicense"
] | null | null | null | // This file is part of the "x0" project, http://github.com/christianparpart/libflow//
// (c) 2009-2014 Christian Parpart <trapni@gmail.com>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
#include <flow/transform/EmptyBlockElimination.h>
#include <flow/ir/BasicBlock.h>
#include <flow/ir/IRHandler.h>
#include <flow/ir/Instructions.h>
#include <list>
namespace flow {
bool EmptyBlockElimination::run(IRHandler* handler) {
std::list<BasicBlock*> eliminated;
for (BasicBlock* bb : handler->basicBlocks()) {
if (bb->instructions().size() != 1) continue;
if (BrInstr* br = dynamic_cast<BrInstr*>(bb->getTerminator())) {
BasicBlock* newSuccessor = br->targetBlock();
eliminated.push_back(bb);
if (bb == handler->getEntryBlock()) {
handler->setEntryBlock(bb);
break;
} else {
for (BasicBlock* pred : bb->predecessors()) {
pred->getTerminator()->replaceOperand(bb, newSuccessor);
}
}
}
}
for (BasicBlock* bb : eliminated) {
bb->parent()->erase(bb);
}
return eliminated.size() > 0;
}
} // namespace flow
| 28.659091 | 86 | 0.656622 |
0a4602ec6f7a003112d67433dac9b55f964d6207 | 17,254 | cpp | C++ | src/Microsoft.DotNet.Wpf/src/WpfGfx/core/common/exports.cpp | nsivov/wpf | d36941860f05dd7a09008e99d1bcd635b0a69fdb | [
"MIT"
] | 2 | 2020-05-18T17:00:43.000Z | 2021-12-01T10:00:29.000Z | src/Microsoft.DotNet.Wpf/src/WpfGfx/core/common/exports.cpp | nsivov/wpf | d36941860f05dd7a09008e99d1bcd635b0a69fdb | [
"MIT"
] | 5 | 2020-05-05T08:05:01.000Z | 2021-12-11T21:35:37.000Z | src/Microsoft.DotNet.Wpf/src/WpfGfx/core/common/exports.cpp | nsivov/wpf | d36941860f05dd7a09008e99d1bcd635b0a69fdb | [
"MIT"
] | 4 | 2020-05-04T06:43:25.000Z | 2022-02-20T12:02:50.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
//
//
//-------------------------------------------------------------------------
#include "precomp.hpp"
//+------------------------------------------------------------------------
//
// Function: MIL3DCalcProjected2DBounds
//
// Synopsis: Computes the 2D screen bounds of the CMilPointAndSize3F after
// projecting with the current 3D world, view, and projection
// transforms and clipping to the camera's Near and Far
// planes.
//
//-------------------------------------------------------------------------
extern "C"
HRESULT WINAPI
MIL3DCalcProjected2DBounds(
__in_ecount(1) const CMatrix<CoordinateSpace::Local3D,CoordinateSpace::PageInPixels> *pFullTransform3D,
__in_ecount(1) const CMilPointAndSize3F *pboxBounds,
__out_ecount(1) CRectF<CoordinateSpace::PageInPixels> *prcTargetRect
)
{
HRESULT hr = S_OK;
CFloatFPU oGuard;
if (pFullTransform3D == NULL || pboxBounds == NULL || prcTargetRect == NULL)
{
IFC(E_INVALIDARG);
}
CalcProjectedBounds(*pFullTransform3D, pboxBounds, prcTargetRect);
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Calculate a mask for the number of "bits to mask" at a "bit offset" from
// the left (high-order bit) of a single byte.
//
// Consider this example:
//
// bitOffset=3
// bitsToMask=3
//
// In memory, this is laid out as:
//
// -------------------------------------------------
// | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
// -------------------------------------------------
// <--- bitOffset --->
// <-- bitsToMask -->
//
// The general algorithm is to start with 0xFF, shift to the right such that
// only bitsToMask number of bits are left on, and then shift back to the
// left to align with the requested bitOffset.
//
// The result will be:
//
// -------------------------------------------------
// | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 |
// -------------------------------------------------
//
//------------------------------------------------------------------------------
BYTE
GetOffsetMask(
__in_range(0, 7) UINT bitOffset,
__in_range(1, 8) UINT bitsToMask
)
{
Assert((bitOffset + bitsToMask) <= 8);
BYTE mask = 0xFF;
UINT maskShift = 8 - bitsToMask;
mask = static_cast<BYTE>(mask >> maskShift);
mask <<= (maskShift - bitOffset);
return mask;
}
//+-----------------------------------------------------------------------------
//
// Return the next byte (or partial byte) from the input buffer starting at the
// specified bit offset and containing no more than the specified remaining
// bits to copy. In the case of a partial byte, the results are left-aligned.
//
// Consider this example:
//
// inputBufferOffsetInBits=5
// bitsRemainingToCopy=4
//
// In memory, this is laid out as:
//
// ---------------------------------------------------------------
// | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | 7 | 6 ...
// ---------------------------------------------------------------
// <-- inputBufferOffsetInBits -->
// <- bitsRemainingToCopy->
//
// The result will be a single byte containing the 3 lower bits of the first
// byte plus the 1 upper bit of the second byte.
//
//------------------------------------------------------------------------------
BYTE
GetNextByteFromInputBuffer(
__in_bcount(2) BYTE * pInputBuffer, // Some cases only require 1 byte...
__in_range(0, 7) UINT inputBufferOffsetInBits,
__in_range(1, UINT_MAX) UINT bitsRemainingToCopy
)
{
// bitsRemainingToCopy could be some huge number. We only care about the
// next byte's worth.
if (bitsRemainingToCopy > 8) bitsRemainingToCopy = 8;
if (inputBufferOffsetInBits == 0)
{
BYTE mask = GetOffsetMask(0, bitsRemainingToCopy);
return pInputBuffer[0] & mask;
}
BYTE nextByte = 0;
UINT bitsFromFirstByte = 8 - inputBufferOffsetInBits;
// Read from the first byte. The results are left-aligned.
BYTE mask = GetOffsetMask(inputBufferOffsetInBits, bitsFromFirstByte);
nextByte = pInputBuffer[0] & mask;
nextByte <<= inputBufferOffsetInBits;
bitsRemainingToCopy -= bitsFromFirstByte;
// Read from the second byte, if needed
if (bitsRemainingToCopy > 0)
{
// Note: bitsRemainingToCopy and bitsFromFirstByte are both small
// numbers, so addition is safe from overflow.
if (bitsRemainingToCopy + bitsFromFirstByte == 8)
{
// This is a common case where we are reading 8 bits of data
// straddled across a byte boundary. We can simply invert the
// mask from the first byte for the second byte.
mask = ~mask;
}
else
{
mask = GetOffsetMask(0, bitsRemainingToCopy);
}
nextByte |= static_cast<BYTE>(pInputBuffer[1] & mask) >> bitsFromFirstByte;
}
return nextByte;
}
//+-----------------------------------------------------------------------------
//
// Copies bytes and partial bytes from the input buffer to the output buffer.
// This function handles the case where the bit offsets are different for the
// input and output buffers.
//
//------------------------------------------------------------------------------
VOID
CopyUnalignedPixelBuffer(
__out_bcount(outputBufferSize) BYTE * pOutputBuffer,
__in_range(1, UINT_MAX) UINT outputBufferSize,
__in_range(1, UINT_MAX) UINT outputBufferStride,
__in_range(0, 7) UINT outputBufferOffsetInBits,
__in_bcount(inputBufferSize) BYTE * pInputBuffer,
__in_range(1, UINT_MAX) UINT inputBufferSize,
__in_range(1, UINT_MAX) UINT inputBufferStride,
__in_range(0, 7) UINT inputBufferOffsetInBits,
__in_range(1, UINT_MAX) UINT height,
__in_range(1, UINT_MAX) UINT copyWidthInBits
)
{
for (UINT row = 0; row < height; row++)
{
UINT bitsRemaining = copyWidthInBits;
BYTE * pInputPosition = pInputBuffer;
BYTE * pOutputPosition = pOutputBuffer;
while (bitsRemaining > 0)
{
BYTE nextByte = GetNextByteFromInputBuffer(
pInputPosition,
inputBufferOffsetInBits,
bitsRemaining);
if (bitsRemaining >= 8)
{
if (outputBufferOffsetInBits == 0)
{
// The output buffer is at a byte boundary, so we can just
// write the next byte.
pOutputPosition[0] = nextByte;
}
else
{
// The output buffer has a bit-offset, so the next byte
// will straddle two bytes.
UINT bitsCopiedToFirstByte = 8 - outputBufferOffsetInBits;
// Write to the first byte...
BYTE mask = GetOffsetMask(outputBufferOffsetInBits, bitsCopiedToFirstByte);
pOutputPosition[0] = (pOutputPosition[0] & ~mask) | (static_cast<BYTE>(nextByte >> outputBufferOffsetInBits) & mask);
// Write to the second byte...
pOutputPosition[1] = static_cast<BYTE>((pOutputPosition[1] & mask) | ((nextByte << bitsCopiedToFirstByte) & ~mask));
}
bitsRemaining -= 8;
}
else
{
// Note: by the time we get to this condition, both bitsRemaining and
// outputBufferOffsetInBits are both small numbers, making them safe
// from overflow.
UINT relativeOffsetOfLastBit = outputBufferOffsetInBits + bitsRemaining;
if (relativeOffsetOfLastBit <= 8)
{
// The remaining bits fit inside a single byte.
BYTE mask = GetOffsetMask(outputBufferOffsetInBits, bitsRemaining);
pOutputPosition[0] = (pOutputPosition[0] & ~mask) | (static_cast<BYTE>(nextByte >> outputBufferOffsetInBits) & mask);
}
else
{
// The remaining bits will cross a byte boundary.
UINT bitsCopiedToFirstByte = 8 - outputBufferOffsetInBits;
// Write to the first byte...
BYTE mask = GetOffsetMask(outputBufferOffsetInBits, bitsCopiedToFirstByte);
pOutputPosition[0] = (pOutputPosition[0] & ~mask) | (static_cast<BYTE>(nextByte >> outputBufferOffsetInBits) & mask);
// Write to the second byte...
mask = GetOffsetMask(0, bitsRemaining - bitsCopiedToFirstByte);
pOutputPosition[1] = static_cast<BYTE>((pOutputPosition[1] & ~mask) | ((nextByte << bitsCopiedToFirstByte) & mask));
}
bitsRemaining = 0;
}
pOutputPosition++;
pInputPosition++;
}
pOutputBuffer += outputBufferStride;
pInputBuffer += inputBufferStride;
}
}
//+-----------------------------------------------------------------------------
//
// MilUtility_CopyPixelBuffer
//
// This function copies memory from the input buffer to the output buffer,
// with explicit support for sub-byte pixel formats. Generally speaking, this
// functions treats memory as 2D (width*height). However, the width of the
// buffer often differs from the natural width of the pixels (width *
// bits-per-pixel, converted to bytes), due to memory alignment requirements.
// The actual distance between adjacent rows is known as the stride, and this
// is always specified in bytes.
//
// The buffers are therefore specified by a pointer, a size, and a stride.
// As usual, the size and stride are specified in bytes.
//
// However, the requested area to copy is specified in bits. This includes
// bit offsets into both the input and output buffers, as well as number of
// bits to copy for each row. The number of rows to copy is specified as the
// height. The bit offsets must only specify the offset within the first
// byte (they must range from 0 to 7, inclusive). The buffer pointers should
// be adjusted before calling this method if the bit offset is large.
//
//------------------------------------------------------------------------------
extern "C"
HRESULT WINAPI
MilUtility_CopyPixelBuffer(
__out_bcount(outputBufferSize) BYTE* pOutputBuffer,
UINT outputBufferSize,
UINT outputBufferStride,
UINT outputBufferOffsetInBits,
__in_bcount(inputBufferSize) BYTE* pInputBuffer,
UINT inputBufferSize,
UINT inputBufferStride,
UINT inputBufferOffsetInBits,
UINT height,
UINT copyWidthInBits
)
{
HRESULT hr = S_OK;
if (height == 0 || copyWidthInBits == 0)
{
// Nothing to do.
goto Cleanup;
}
if (outputBufferOffsetInBits > 7 || inputBufferOffsetInBits > 7)
{
// Bit offsets should be 0..7, inclusive.
IFC(E_INVALIDARG);
}
UINT minimumOutputBufferStrideInBits;
minimumOutputBufferStrideInBits = 0;
IFC(UIntAdd(outputBufferOffsetInBits, copyWidthInBits, &minimumOutputBufferStrideInBits));
UINT minimumOutputBufferStride;
minimumOutputBufferStride = BitsToBytes(minimumOutputBufferStrideInBits);
if (outputBufferStride < minimumOutputBufferStride)
{
// The stride of the output buffer is too small.
IFC(E_INVALIDARG);
}
UINT minimumOutputBufferSize;
minimumOutputBufferSize = 0;
IFC(UIntMult(outputBufferStride, (height-1), &minimumOutputBufferSize));
IFC(UIntAdd(minimumOutputBufferSize, minimumOutputBufferStride, &minimumOutputBufferSize));
if (outputBufferSize < minimumOutputBufferSize)
{
// The output buffer is too small.
IFC(E_INVALIDARG);
}
UINT minimumInputBufferStrideInBits;
minimumInputBufferStrideInBits = 0;
IFC(UIntAdd(inputBufferOffsetInBits, copyWidthInBits, &minimumInputBufferStrideInBits));
UINT minimumInputBufferStride;
minimumInputBufferStride = BitsToBytes(minimumInputBufferStrideInBits);
if (inputBufferStride < minimumInputBufferStride)
{
// The stride of the input buffer is too small.
IFC(E_INVALIDARG);
}
UINT minimumInputBufferSize;
minimumInputBufferSize = 0;
IFC(UIntMult(inputBufferStride, (height-1), &minimumInputBufferSize));
IFC(UIntAdd(minimumInputBufferSize, minimumInputBufferStride, &minimumInputBufferSize));
if (inputBufferSize < minimumInputBufferSize)
{
// The input buffer is too small.
IFC(E_INVALIDARG);
}
if (outputBufferOffsetInBits != inputBufferOffsetInBits)
{
CopyUnalignedPixelBuffer(
pOutputBuffer,
outputBufferSize,
outputBufferStride,
outputBufferOffsetInBits,
pInputBuffer,
inputBufferSize,
inputBufferStride,
inputBufferOffsetInBits,
height,
copyWidthInBits);
}
else
{
// Since the input and output offsets are the same, we use more general
// variable names here.
UINT minimumBufferStrideInBits = minimumInputBufferStrideInBits;
UINT minimumBufferStride = minimumInputBufferStride;
UINT bufferOffsetInBits = inputBufferOffsetInBits;
UINT finalByteOffset = minimumBufferStride - 1;
if ((bufferOffsetInBits == 0) && (copyWidthInBits % 8 == 0))
{
if (minimumBufferStride == inputBufferStride &&
inputBufferStride == outputBufferStride)
{
// Fast-Path
// The input and output buffers are on byte boundaries, both
// share the same stride, and we are copying the entire
// stride of each row. These conditions allow us to do a
// single large memory copy instead of multiple copies per row.
memcpy(pOutputBuffer, pInputBuffer, inputBufferStride*height);
}
else
{
// We are copying whole bytes from the input buffer to the
// output buffer, but we still need to copy row-by-row since
// the width is not the same as the stride.
for (UINT i = 0; i < height; i++)
{
memcpy(pOutputBuffer, pInputBuffer, minimumBufferStride);
pOutputBuffer += outputBufferStride;
pInputBuffer += inputBufferStride;
}
}
}
else if (finalByteOffset == 0)
{
// If the first byte is also the final byte, we need to double mask.
BYTE mask = GetOffsetMask(bufferOffsetInBits, copyWidthInBits);
for (UINT i = 0; i < height; i++)
{
pOutputBuffer[0] = (pOutputBuffer[0] & ~mask) | (pInputBuffer[0] & mask);
pOutputBuffer += outputBufferStride;
pInputBuffer += inputBufferStride;
}
}
else
{
// In this final case:
// - only part of either the first or last byte should be copied,
// - the first byte is not the last byte,
// - and there are between 0 and n whole bytes in between to copy.
bool firstByteIsWhole = bufferOffsetInBits == 0;
bool finalByteIsWhole = minimumBufferStrideInBits % 8 == 0;
UINT wholeBytesPerRow = minimumBufferStride - (finalByteIsWhole ? 0 : 1) - (firstByteIsWhole ? 0 : 1);
for (UINT i = 0; i < height; i++)
{
if (!firstByteIsWhole)
{
BYTE mask = GetOffsetMask(bufferOffsetInBits, 8 - bufferOffsetInBits);
pOutputBuffer[0] = (pOutputBuffer[0] & ~mask) | (pInputBuffer[0] & mask);
}
if (wholeBytesPerRow > 0)
{
UINT firstByteOffset = (firstByteIsWhole ? 0 : 1);
memcpy(
pOutputBuffer + firstByteOffset,
pInputBuffer + firstByteOffset,
wholeBytesPerRow);
}
if (!finalByteIsWhole)
{
BYTE mask = GetOffsetMask(0, minimumBufferStrideInBits % 8);
pOutputBuffer[finalByteOffset] = (pOutputBuffer[finalByteOffset] & ~mask) | (pInputBuffer[finalByteOffset] & mask);
}
pOutputBuffer += outputBufferStride;
pInputBuffer += inputBufferStride;
}
}
}
Cleanup:
RRETURN(hr);
}
| 36.946467 | 137 | 0.561261 |
0a46470e941be66cd0e253e942162108a6e2ef6a | 932 | cpp | C++ | 242_b.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | 242_b.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | 242_b.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | // Created by Tanuj Jain
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<int,int> pii;
template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int t;
cin>>t;
//set<pair<int,int>,int>st;
int l=INT_MAX;
int r=-1;
vector<pair<int,int>>v;
for(int i=0;i<t;i++)
{
int a,b;
cin>>a>>b;
l=min(l,a);
r=max(r,b);
v.pb({a,b});
//st.insert{a,b};
}
for(int i=0;i<t;i++)
{
if(v[i].first==l && v[i].second==r)
{
cout<<i+1;
return 0;
}
}
cout<<-1;
return 0;
} | 18.64 | 106 | 0.60515 |
0a48c1aaf97bfabf334b622ab83745318c6af1be | 2,851 | hpp | C++ | src/Omega_h_vtk.hpp | matz-e/omega_h | a43850787b24f96d50807cee5688f09259e96b75 | [
"BSD-2-Clause-FreeBSD"
] | 44 | 2019-01-23T03:37:18.000Z | 2021-08-24T02:20:29.000Z | src/Omega_h_vtk.hpp | matz-e/omega_h | a43850787b24f96d50807cee5688f09259e96b75 | [
"BSD-2-Clause-FreeBSD"
] | 67 | 2019-01-29T15:35:42.000Z | 2021-08-17T20:42:40.000Z | src/Omega_h_vtk.hpp | matz-e/omega_h | a43850787b24f96d50807cee5688f09259e96b75 | [
"BSD-2-Clause-FreeBSD"
] | 29 | 2019-01-14T21:33:32.000Z | 2021-08-10T11:35:24.000Z | #ifndef OMEGA_H_VTK_HPP
#define OMEGA_H_VTK_HPP
#include <iosfwd>
#include <string>
#include <vector>
#include <Omega_h_comm.hpp>
#include <Omega_h_defines.hpp>
#include <Omega_h_file.hpp>
namespace Omega_h {
class Mesh;
namespace vtk {
filesystem::path get_pvtu_path(filesystem::path const& step_path);
filesystem::path get_pvd_path(filesystem::path const& root_path);
void write_pvtu(std::ostream& stream, Mesh* mesh, Int cell_dim,
filesystem::path const& piecepath, TagSet const& tags);
void write_pvtu(filesystem::path const& filename, Mesh* mesh, Int cell_dim,
filesystem::path const& piecepath, TagSet const& tags);
std::streampos write_initial_pvd(
filesystem::path const& root_path, Real restart_time);
void update_pvd(filesystem::path const& root_path, std::streampos* pos_inout,
I64 step, Real time);
void read_vtu(std::istream& stream, CommPtr comm, Mesh* mesh);
void read_vtu_ents(std::istream& stream, Mesh* mesh);
void read_pvtu(std::istream& stream, CommPtr comm, I32* npieces_out,
std::string* vtupath_out, Int* nghost_layers_out);
void read_pvtu(filesystem::path const& pvtupath, CommPtr comm, I32* npieces_out,
filesystem::path* vtupath_out, Int* nghost_layers_out);
void read_pvd(std::istream& stream, std::vector<Real>* times_out,
std::vector<filesystem::path>* pvtupaths_out);
void read_pvd(filesystem::path const& pvdpath, std::vector<Real>* times_out,
std::vector<filesystem::path>* pvtupaths_out);
template <bool is_signed, std::size_t size>
struct IntTraits;
template <std::size_t size>
struct FloatTraits;
void write_vtkfile_vtu_start_tag(std::ostream& stream, bool compress);
void write_p_tag(std::ostream& stream, TagBase const* tag, Int space_dim);
void write_tag(
std::ostream& stream, TagBase const* tag, Int space_dim, bool compress);
template <typename T>
void write_p_data_array(
std::ostream& stream, std::string const& name, Int ncomps);
template <typename T_osh, typename T_vtk = T_osh>
void write_array(std::ostream& stream, std::string const& name, Int ncomps,
Read<T_osh> array, bool compress);
#define OMEGA_H_EXPL_INST_DECL(T) \
extern template void write_p_data_array<T>( \
std::ostream & stream, std::string const& name, Int ncomps); \
extern template void write_array(std::ostream& stream, \
std::string const& name, Int ncomps, Read<T> array, bool compress);
OMEGA_H_EXPL_INST_DECL(I8)
OMEGA_H_EXPL_INST_DECL(I32)
OMEGA_H_EXPL_INST_DECL(I64)
OMEGA_H_EXPL_INST_DECL(Real)
#undef OMEGA_H_EXPL_INST_DECL
extern template void write_array<Real, std::uint8_t>(std::ostream& stream,
std::string const& name, Int ncomps, Read<Real> array, bool compress);
} // namespace vtk
} // end namespace Omega_h
#endif
| 32.397727 | 80 | 0.726061 |
0a4c6282a0249bac1a4d6dbfb95bf3dd1d8c4009 | 23,969 | cxx | C++ | osprey/be/lno/sclrze.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/be/lno/sclrze.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/be/lno/sclrze.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 2002, 2003, 2004, 2005, 2006 PathScale, Inc. All Rights Reserved.
*/
/*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU General Public License along
with this program; if not, write the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston MA 02111-1307, USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
// Array Scalarization
// -------------------
//
// Description:
//
// In loops, convert things that look like
// do i
// a[i] = ...
// ... = a[i]
//
// into
//
// do i
// t = ...
// a[i] = t
// ... = t
//
// This is useful because
// 1) It gets rid of loads
// 2) If it gets rid of all the loads to a local array then
// the array equivalencing algorithm will get rid of the array
//
// Because SWP will do 1 as well as we do, we'll only apply this
// algorithm to local arrays (Although it's trivial to change this).
//
/* ====================================================================
* ====================================================================
*
* Module: sclrze.cxx
* $Revision: 1.7 $
* $Date: 05/04/07 19:50:39-07:00 $
* $Author: kannann@iridot.keyresearch $
* $Source: be/lno/SCCS/s.sclrze.cxx $
*
* Revision history:
* dd-mmm-94 - Original Version
*
* Description: Scalarize arrays
*
* ====================================================================
* ====================================================================
*/
#ifdef USE_PCH
#include "lno_pch.h"
#endif // USE_PCH
#pragma hdrstop
const static char *source_file = __FILE__;
const static char *rcs_id = "$Source: be/lno/SCCS/s.sclrze.cxx $ $Revision: 1.7 $";
#include <sys/types.h>
#include "lnopt_main.h"
#include "dep_graph.h"
#include "lwn_util.h"
#include "opt_du.h"
#include "reduc.h"
#include "sclrze.h"
#include "lnoutils.h"
static void Process_Store(WN *, VINDEX16 , ARRAY_DIRECTED_GRAPH16 *, BOOL,
BOOL, REDUCTION_MANAGER *red_manager);
static BOOL Intervening_Write(INT,VINDEX16,
VINDEX16 ,ARRAY_DIRECTED_GRAPH16 *);
static BOOL Is_Invariant(ACCESS_ARRAY *store, WN *store_wn);
static BOOL MP_Problem(WN *wn1, WN *wn2);
static HASH_TABLE<ST *, INT> * Array_Use_Hash;
static int DSE_Count = 0;
extern BOOL ST_Has_Dope_Vector(ST *);
// Query whether 'st' represents a local variable.
static BOOL Is_Local_Var(ST * st)
{
if ((ST_sclass(st) == SCLASS_AUTO)
&& (ST_base_idx(st) == ST_st_idx(st))
&& !ST_has_nested_ref(st)
&& (ST_class(st) == CLASS_VAR))
return TRUE;
return FALSE;
}
// Query whether use references to 'st' is tracked in "Mark_Array_Uses".
// Limit to local allocate arrays.
static BOOL Is_Tracked(ST * st)
{
return (Is_Local_Var(st) && ST_Has_Dope_Vector(st));
}
// bit mask for symbol attributes.
#define HAS_ESCAPE_USE 1 // has a use not reachable by a dominating def.
#define ADDR_TAKEN 2 // is address-taken.
#define HAS_USE 4 // has a use.
#define IS_ALLOC 8 // is allocated/dealloacted.
// Query whether 'store_wn' is dead, i.e., its address is not taken and it has no use.
static BOOL Is_Dead_Store(WN * store_wn)
{
OPERATOR opr = WN_operator(store_wn);
if (!OPERATOR_is_scalar_store(opr)) {
WN * base = WN_array_base(WN_kid(store_wn,1));
if (WN_has_sym(base)) {
ST * st = WN_st(base);
if (st && Is_Tracked(st)
&& Array_Use_Hash
&& (Array_Use_Hash->Find(st) == IS_ALLOC))
return TRUE;
}
}
return FALSE;
}
// Given an array reference 'load_wn", query where there exists a reaching def that dominates it.
static BOOL Has_Dom_Reaching_Def(ARRAY_DIRECTED_GRAPH16 * dep_graph, WN * load_wn)
{
OPERATOR opr = WN_operator(load_wn);
if (!OPERATOR_is_load(opr) || OPERATOR_is_scalar_load(opr))
return FALSE;
VINDEX16 v = dep_graph->Get_Vertex(load_wn);
if (!v)
return FALSE;
WN * kid = WN_kid0(load_wn);
if (WN_operator(kid) != OPR_ARRAY)
return FALSE;
ACCESS_ARRAY * load = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map, kid);
if (!load)
return FALSE;
for (EINDEX16 e = dep_graph->Get_In_Edge(v); e; e = dep_graph->Get_Next_In_Edge(e)) {
VINDEX16 source = dep_graph->Get_Source(e);
WN * store_wn = dep_graph->Get_Wn(source);
OPERATOR opr = WN_operator(store_wn);
if (OPERATOR_is_store(opr) && !OPERATOR_is_scalar_store(opr)) {
kid = WN_kid1(store_wn);
if (WN_operator(kid) != OPR_ARRAY)
continue;
ACCESS_ARRAY * store = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map, kid);
if (Equivalent_Access_Arrays(store,load,store_wn,load_wn)
&& (DEPV_COMPUTE::Base_Test(store_wn,NULL,load_wn,NULL) == DEP_CONTINUE)) {
if (Dominates(store_wn, load_wn)
&& !Intervening_Write(dep_graph->Depv_Array(e)->Max_Level(),
source, v, dep_graph)
&& !MP_Problem(store_wn, load_wn))
return TRUE;
}
}
}
return FALSE;
}
// Given an array reference 'store_wn', query whether there exists a kill that post-dominates it.
static BOOL Has_Post_Dom_Kill(ARRAY_DIRECTED_GRAPH16 * dep_graph, WN * store_wn)
{
OPERATOR opr = WN_operator(store_wn);
if (!OPERATOR_is_store(opr) || OPERATOR_is_scalar_store(opr))
return FALSE;
VINDEX16 v = dep_graph->Get_Vertex(store_wn);
if (!v)
return FALSE;
WN * kid = WN_kid1(store_wn);
if (WN_operator(kid) != OPR_ARRAY)
return FALSE;
WN * base = WN_array_base(kid);
if (!WN_has_sym(base))
return FALSE;
ST * st = WN_st(base);
// limit it to local non-address-taken arrays.
if (!Is_Local_Var(st) || !Array_Use_Hash
|| ((Array_Use_Hash->Find(st) & ADDR_TAKEN) != 0))
return FALSE;
ACCESS_ARRAY * store = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map, kid);
if (!store)
return FALSE;
for (EINDEX16 e = dep_graph->Get_Out_Edge(v); e; e = dep_graph->Get_Next_Out_Edge(e)) {
VINDEX16 sink = dep_graph->Get_Sink(e);
WN * kill_wn = dep_graph->Get_Wn(sink);
if (kill_wn == store_wn)
continue;
OPERATOR opr = WN_operator(kill_wn);
if (OPERATOR_is_store(opr) && !OPERATOR_is_scalar_store(opr)) {
kid = WN_kid1(kill_wn);
if (WN_operator(kid) != OPR_ARRAY)
continue;
ACCESS_ARRAY * kill = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map, kid);
if (Equivalent_Access_Arrays(store, kill, store_wn, kill_wn)
&& (DEPV_COMPUTE::Base_Test(store_wn, NULL, kill_wn, NULL) == DEP_CONTINUE)) {
if ((LWN_Get_Parent(store_wn) == LWN_Get_Parent(kill_wn))
&& !MP_Problem(store_wn, kill_wn)) {
WN * next = WN_next(store_wn);
while (next) {
if (next == kill_wn)
return TRUE;
next = WN_next(next);
}
}
}
}
}
return FALSE;
}
// Check usage of a local allocate array.
static void Check_use(ST * st, WN * wn, ARRAY_DIRECTED_GRAPH16 * dep_graph, BOOL escape)
{
if (st && Is_Tracked(st)) {
int val = Array_Use_Hash->Find(st);
val |= HAS_USE;
if (escape || !Has_Dom_Reaching_Def(dep_graph, wn)) {
val |= HAS_ESCAPE_USE;
}
if (val) {
Array_Use_Hash->Find_And_Set(st, val);
}
}
}
// Check use references to local allocate arrays and mark attributes.
// Limit it to Fortran programs currently.
static void Mark_Array_Uses(ARRAY_DIRECTED_GRAPH16 * dep_graph, WN * wn)
{
FmtAssert(Array_Use_Hash, ("Expect a hash table."));
WN * kid;
ST * st;
OPERATOR opr = WN_operator(wn);
switch (opr) {
case OPR_BLOCK:
kid = WN_first(wn);
while (kid) {
Mark_Array_Uses(dep_graph, kid);
kid = WN_next(kid);
}
break;
case OPR_LDA:
st = WN_st(wn);
if (Is_Tracked(st)) {
int val = Array_Use_Hash->Find(st);
BOOL is_pure = FALSE;
WN * wn_p = LWN_Get_Parent(wn);
if (wn_p && ST_Has_Dope_Vector(st)) {
OPERATOR p_opr = WN_operator(wn_p);
if (p_opr == OPR_PARM) {
wn_p = LWN_Get_Parent(wn_p);
if (wn_p
&& (WN_operator(wn_p) == OPR_CALL)) {
char * name = ST_name(WN_st_idx(wn_p));
if ((strcmp(name, "_DEALLOCATE") == 0)
|| (strcmp(name, "_DEALLOC") == 0)
|| (strcmp(name, "_F90_ALLOCATE_B") == 0)) {
is_pure = TRUE;
val |= IS_ALLOC;
}
}
}
else if ((p_opr == OPR_STID) && WN_has_sym(wn_p)) {
ST * p_st = WN_st(wn_p);
TY_IDX ty = ST_type(p_st);
if (strncmp(TY_name(ty), ".alloctemp.", 11) == 0)
is_pure = TRUE;
}
}
if (!is_pure)
val |= ADDR_TAKEN;
if (val) {
Array_Use_Hash->Find_And_Set(st, val);
}
}
break;
case OPR_LDID:
if (WN_has_sym(wn)) {
st = WN_st(wn);
WN * store = Find_Containing_Store(wn);
if (store && (WN_operator(store) == OPR_STID)
&& (WN_st(store) != st)) {
if (WN_kid0(store) == wn) {
// Be conservative for direct assignment to a different variable.
// Consider it as an escape use.
Check_use(st, wn, dep_graph, TRUE);
}
else
Check_use(st, wn, dep_graph, FALSE);
}
// Flag ADDR_TAKEN bit for parameters passed by reference.
WN * wn_p = LWN_Get_Parent(wn);
if (wn_p && (WN_operator(wn_p) == OPR_PARM)) {
INT flag = WN_flag(wn_p);
if (flag & WN_PARM_BY_REFERENCE) {
int val = Array_Use_Hash->Find(st);
val |= ADDR_TAKEN;
if (val) {
Array_Use_Hash->Find_And_Set(st, val);
}
}
}
}
break;
case OPR_ILOAD:
kid = WN_kid0(wn);
if (WN_operator(kid) == OPR_ARRAY) {
WN * base = WN_array_base(kid);
if (WN_has_sym(base)) {
st = WN_st(base);
Check_use(st, wn, dep_graph, FALSE);
}
}
break;
default:
;
}
if (opr == OPR_FUNC_ENTRY)
Mark_Array_Uses(dep_graph,WN_func_body(wn));
else {
INT start = (opr == OPR_ARRAY) ? 1 : 0;
for (INT kidno = start; kidno < WN_kid_count(wn); kidno++) {
kid = WN_kid(wn, kidno);
Mark_Array_Uses(dep_graph, kid);
}
}
}
void Scalarize_Arrays(ARRAY_DIRECTED_GRAPH16 *dep_graph,
BOOL do_variants, BOOL do_invariants, REDUCTION_MANAGER *red_manager, WN * wn)
{
if (Get_Trace(TP_LNOPT,TT_LNO_SCLRZE)) {
fprintf(TFile,"Scalarizing arrays \n");
}
Array_Use_Hash = NULL;
PU & pu = Get_Current_PU();
if (Do_Aggressive_Fuse && wn
&& ((PU_src_lang(Get_Current_PU()) & PU_F90_LANG)
|| (PU_src_lang(Get_Current_PU()) & PU_F77_LANG))) {
ST * st;
INT i;
Array_Use_Hash = CXX_NEW((HASH_TABLE<ST *, INT>) (100, &LNO_default_pool),
&LNO_default_pool);
Mark_Array_Uses(Array_Dependence_Graph, wn);
}
// search for a store
VINDEX16 v;
VINDEX16 v_next;
DSE_Count = 0;
for (v = dep_graph->Get_Vertex(); v; v = v_next) {
v_next = dep_graph->Get_Next_Vertex_In_Edit(v);
if (!dep_graph->Vertex_Is_In_Graph(v))
continue;
WN *wn = dep_graph->Get_Wn(v);
OPCODE opcode = WN_opcode(wn);
if (OPCODE_is_store(opcode) && (WN_kid_count(wn) == 2)) {
WN *array = WN_kid1(wn);
if (WN_operator(array) == OPR_ARRAY) {
WN *base = WN_array_base(array);
OPERATOR base_oper = WN_operator(base);
if ((base_oper == OPR_LDID) || (base_oper == OPR_LDA)) {
ST *st = WN_st(base);
// is it local
#ifdef _NEW_SYMTAB
if (ST_level(st) == CURRENT_SYMTAB) {
#else
if (ST_symtab_id(st) == SYMTAB_id(Current_Symtab)) {
#endif
if (ST_sclass(st) == SCLASS_AUTO &&
ST_base_idx(st) == ST_st_idx(st)) {
if (!ST_has_nested_ref(st))
Process_Store(wn,v,dep_graph,do_variants,do_invariants,
red_manager);
}
}
else if (Is_Global_As_Local(st)) {
Process_Store(wn,v,dep_graph,do_variants,do_invariants, red_manager);
}
}
}
}
}
if (DSE_Count > 0) {
if (Get_Trace(TP_LNOPT,TT_LNO_SCLRZE))
printf("####Func: %d scalar replacement delete %d stores.\n", Current_PU_Count(), DSE_Count);
}
if (Array_Use_Hash)
CXX_DELETE(Array_Use_Hash, &LNO_default_pool);
}
// Given a store to an array element 'wn', query whether it is read outside its enclosing loop
// assuming unequal acccess arrays refer to disjointed locations.
static BOOL Live_On_Exit(WN * wn)
{
ARRAY_DIRECTED_GRAPH16 * adg = Array_Dependence_Graph;
OPERATOR opr = WN_operator(wn);
FmtAssert(OPERATOR_is_store(opr) && !OPERATOR_is_scalar_store(opr), ("Expect a store."));
VINDEX16 v = adg->Get_Vertex(wn);
if (!v)
return TRUE;
WN * kid = WN_kid1(wn);
if (WN_operator(kid) != OPR_ARRAY)
return TRUE;
ACCESS_ARRAY * store = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map, kid);
if (!store)
return TRUE;
WN * loop_st = Enclosing_Loop(wn);
for (EINDEX16 e = adg->Get_Out_Edge(v); e; e = adg->Get_Next_Out_Edge(e)) {
VINDEX16 sink = adg->Get_Sink(e);
WN * load_wn = adg->Get_Wn(sink);
OPERATOR opr = WN_operator(load_wn);
if (OPERATOR_is_load(opr) && !OPERATOR_is_scalar_load(opr)) {
kid = WN_kid0(load_wn);
if (WN_operator(kid) != OPR_ARRAY)
continue;
if (Enclosing_Loop(load_wn) == loop_st)
continue;
ACCESS_ARRAY * load = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map, kid);
if (Equivalent_Access_Arrays(store,load,wn,load_wn)
&& (DEPV_COMPUTE::Base_Test(wn,NULL,load_wn,NULL) == DEP_CONTINUE)) {
return TRUE;
}
}
}
return FALSE;
}
// Query whether 'wn' is located in a loop nest that allows dead store removal
// after scalarization.
static BOOL Do_Sclrze_Dse(WN * wn)
{
WN * wn_p = LWN_Get_Parent(wn);
while (wn_p) {
if (WN_operator(wn_p) == OPR_DO_LOOP) {
DO_LOOP_INFO * dli = Get_Do_Loop_Info(wn_p);
if (dli && (dli->Sclrze_Dse == 1))
return TRUE;
}
wn_p = LWN_Get_Parent(wn_p);
}
return FALSE;
}
// Delete 'store_wn'.
static void Delete_Store(WN * store_wn, ARRAY_DIRECTED_GRAPH16 * dep_graph)
{
UINT32 limit = LNO_Sclrze_Dse_Limit;
if ((limit > 0) && (DSE_Count > limit))
return;
LWN_Update_Dg_Delete_Tree(store_wn, dep_graph);
LWN_Delete_Tree(store_wn);
DSE_Count++;
}
// Process a store.
static void Process_Store(WN *store_wn, VINDEX16 v,
ARRAY_DIRECTED_GRAPH16 *dep_graph, BOOL do_variants,
BOOL do_invariants, REDUCTION_MANAGER *red_manager)
{
#ifdef TARG_X8664
// Do not sclrze vector stores.
if (MTYPE_is_vector(WN_desc(store_wn))) return;
#endif
#ifdef KEY // Bug 6162 - can not scalarize to MTYPE_M pregs.
if (WN_desc(store_wn) == MTYPE_M) return;
#endif
if (Inside_Loop_With_Goto(store_wn)) return;
INT debug = Get_Trace(TP_LNOPT,TT_LNO_SCLRZE);
BOOL scalarized_this_store = FALSE;
WN_OFFSET preg_num=0;
ST *preg_st=0;
WN *preg_store = NULL;
ACCESS_ARRAY *store =
(ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map,WN_kid1(store_wn));
if (debug) {
fprintf(TFile,"Processing the store ");
store->Print(TFile);
fprintf(TFile,"\n");
}
if (Do_Aggressive_Fuse) {
if (Is_Dead_Store(store_wn)) {
if (!red_manager || (red_manager->Which_Reduction(store_wn) == RED_NONE)) {
Delete_Store(store_wn, dep_graph);
return;
}
}
}
BOOL is_invariant = Is_Invariant(store,store_wn);
if (!do_variants && !is_invariant) {
return;
}
if (!do_invariants && is_invariant) {
return;
}
// Don't scalarize reductions as that will break the reduction
if (red_manager && (red_manager->Which_Reduction(store_wn) != RED_NONE)) {
return;
}
char preg_name[20];
TYPE_ID store_type = WN_desc(store_wn);
TYPE_ID type = Promote_Type(store_type);
EINDEX16 e,next_e=0;
BOOL all_loads_scalarized = TRUE;
BOOL has_post_dom_kill = FALSE;
if (Do_Aggressive_Fuse)
has_post_dom_kill = Has_Post_Dom_Kill(dep_graph, store_wn);
for (e = dep_graph->Get_Out_Edge(v); e; e=next_e) {
next_e = dep_graph->Get_Next_Out_Edge(e);
VINDEX16 sink = dep_graph->Get_Sink(e);
WN *load_wn = dep_graph->Get_Wn(sink);
OPCODE opcode = WN_opcode(load_wn);
if (OPCODE_is_load(opcode)) {
if (OPCODE_operator(opcode) != OPR_LDID &&
// Do not scalarize MTYPE_M loads as this may result in a parent MTYPE_M store
// having a child that is not MTYPE_M and function 'Add_def' may not be able to
// handle such stores during coderep creation. The check here catches 'uses' involving
// MTYPE_M whereas the check at the beginning of 'Process_Store' catches 'defs'.
(WN_rtype(load_wn) != MTYPE_M) && (WN_desc(load_wn) != MTYPE_M)) {
ACCESS_ARRAY *load = (ACCESS_ARRAY *)
WN_MAP_Get(LNO_Info_Map,WN_kid0(load_wn));
if (WN_operator(WN_kid0(load_wn)) == OPR_ARRAY &&
Equivalent_Access_Arrays(store,load,store_wn,load_wn) &&
(DEPV_COMPUTE::Base_Test(store_wn,NULL,load_wn,NULL) ==
DEP_CONTINUE)
#ifdef KEY
&&
//Bug 9134: scalarizing only if store to and load from the same field
WN_field_id(store_wn)==WN_field_id(load_wn)
#endif
) {
BOOL scalarized_this_load = FALSE;
if (Dominates(store_wn,load_wn)) {
if (!red_manager ||
(red_manager->Which_Reduction(store_wn) == RED_NONE)) {
if (!Intervening_Write(dep_graph->Depv_Array(e)->Max_Level(),
v,sink,dep_graph)) {
if (!MP_Problem(store_wn,load_wn)) {
scalarized_this_load = TRUE;
if (!scalarized_this_store) {
if (debug) {
fprintf(TFile,"Scalarizing the load ");
load->Print(TFile);
fprintf(TFile,"\n");
}
// Create a new preg
preg_st = MTYPE_To_PREG(type);
char *array_name =
ST_name(WN_st(WN_array_base(WN_kid1(store_wn))));
INT length = strlen(array_name);
if (length < 18) {
strcpy(preg_name,array_name);
preg_name[length] = '_';
preg_name[length+1] = '1';
preg_name[length+2] = 0;
#ifdef _NEW_SYMTAB
preg_num = Create_Preg(type,preg_name);
} else {
preg_num = Create_Preg(type, NULL);
}
#else
preg_num = Create_Preg(type,preg_name, NULL);
} else {
preg_num = Create_Preg(type, NULL, NULL);
}
#endif
// replace A[i] = x with "preg = x; A[i] = preg"
OPCODE preg_s_opcode = OPCODE_make_op(OPR_STID,MTYPE_V,type);
// Insert CVTL if necessary (854441)
WN *wn_value = WN_kid0(store_wn);
if (MTYPE_byte_size(store_type) < MTYPE_byte_size(type))
wn_value = LWN_Int_Type_Conversion(wn_value, store_type);
preg_store = LWN_CreateStid(preg_s_opcode,preg_num,
preg_st, Be_Type_Tbl(type),wn_value);
WN_Set_Linenum(preg_store,WN_Get_Linenum(store_wn));
LWN_Copy_Frequency_Tree(preg_store,store_wn);
LWN_Insert_Block_Before(LWN_Get_Parent(store_wn),
store_wn,preg_store);
OPCODE preg_l_opcode = OPCODE_make_op(OPR_LDID, type,type);
WN *preg_load = WN_CreateLdid(preg_l_opcode,preg_num,
preg_st, Be_Type_Tbl(type));
LWN_Copy_Frequency(preg_load,store_wn);
WN_kid0(store_wn) = preg_load;
LWN_Set_Parent(preg_load,store_wn);
Du_Mgr->Add_Def_Use(preg_store,preg_load);
}
scalarized_this_store = TRUE;
// replace the load with the use of the preg
WN *new_load = WN_CreateLdid(OPCODE_make_op(OPR_LDID,
type,type),preg_num,preg_st,Be_Type_Tbl(type));
LWN_Copy_Frequency_Tree(new_load,load_wn);
WN *parent = LWN_Get_Parent(load_wn);
for (INT i = 0; i < WN_kid_count(parent); i++) {
if (WN_kid(parent,i) == load_wn) {
WN_kid(parent,i) = new_load;
LWN_Set_Parent(new_load,parent);
LWN_Update_Dg_Delete_Tree(load_wn, dep_graph);
LWN_Delete_Tree(load_wn);
break;
}
}
// update def-use for scalar
Du_Mgr->Add_Def_Use(preg_store,new_load);
}
}
if (!scalarized_this_load)
all_loads_scalarized = FALSE;
}
}
}
}
}
}
if (Do_Aggressive_Fuse) {
OPERATOR opr = WN_operator(store_wn);
if (!OPERATOR_is_scalar_store(opr)
&& scalarized_this_store && all_loads_scalarized) {
WN * base = WN_array_base(WN_kid(store_wn,1));
if (WN_has_sym(base)) {
ST * st = WN_st(base);
if (st) {
int val = Array_Use_Hash ? Array_Use_Hash->Find(st) : 0;
if (Is_Global_As_Local(st) && ST_Has_Dope_Vector(st)) {
if (Do_Sclrze_Dse(store_wn)
&& !Live_On_Exit(store_wn)
&& (ST_export(st) == EXPORT_LOCAL)) {
Delete_Store(store_wn, dep_graph);
}
}
else if (val && ((val & ADDR_TAKEN) == 0)
&& ((val & IS_ALLOC) != 0)) {
if (has_post_dom_kill
|| ((val & HAS_ESCAPE_USE) == 0)) {
Delete_Store(store_wn, dep_graph);
}
}
}
}
}
}
}
// Given that there is a must dependence between store and load,
// is there ary other store that might occur between the the store and the
// load
// If there exists a store2, whose maximum dependence level wrt the
// load is greater than store's dependence level (INT level below),
// then store2 is intervening.
//
// If there exists a store2 whose maximum dependence level is equal
// to store's, and there a dependence from store to store2 with dependence
// level >= the previous level, then store2 is intervening
static BOOL Intervening_Write(INT level,VINDEX16 store_v,
VINDEX16 load_v,ARRAY_DIRECTED_GRAPH16 *dep_graph)
{
EINDEX16 e;
for (e=dep_graph->Get_In_Edge(load_v); e; e=dep_graph->Get_Next_In_Edge(e)) {
INT level2 = dep_graph->Depv_Array(e)->Max_Level();
if (level2 > level) {
return TRUE;
} else if (level2 == level) {
VINDEX16 store2_v = dep_graph->Get_Source(e);
EINDEX16 store_store_edge = dep_graph->Get_Edge(store_v,store2_v);
if (store_store_edge) {
INT store_store_level =
dep_graph->Depv_Array(store_store_edge)->Max_Level();
if (store_store_level >= level) {
return TRUE;
}
}
}
}
return FALSE;
}
// Is this reference invariant in its inner loop
static BOOL Is_Invariant(ACCESS_ARRAY *store, WN *store_wn)
{
// find the do loop info of the store
WN *wn = LWN_Get_Parent(store_wn);
while (WN_opcode(wn) != OPC_DO_LOOP) {
wn = LWN_Get_Parent(wn);
}
DO_LOOP_INFO *dli = Get_Do_Loop_Info(wn);
INT depth = dli->Depth;
if (store->Too_Messy || (store->Non_Const_Loops() > depth)) {
return FALSE;
}
for (INT i=0; i<store->Num_Vec(); i++) {
ACCESS_VECTOR *av = store->Dim(i);
if (av->Too_Messy || av->Loop_Coeff(depth)) {
return FALSE;
}
}
return TRUE;
}
// Don't scalarize across parallel boundaries
static BOOL MP_Problem(WN *wn1, WN *wn2)
{
if (Contains_MP) {
WN *mp1 = LWN_Get_Parent(wn1);
while (mp1 && (!Is_Mp_Region(mp1)) &&
((WN_opcode(mp1) != OPC_DO_LOOP) || !Do_Loop_Is_Mp(mp1))) {
mp1 = LWN_Get_Parent(mp1);
}
WN *mp2 = LWN_Get_Parent(wn2);
while (mp2 && (!Is_Mp_Region(mp2)) &&
((WN_opcode(mp2) != OPC_DO_LOOP) || !Do_Loop_Is_Mp(mp2))) {
mp2 = LWN_Get_Parent(mp2);
}
if ((mp1 || mp2) && (mp1 != mp2)) return TRUE;
}
return FALSE;
}
| 29.664604 | 99 | 0.640285 |
aea7c59a3ea32c550a43c96fec471d47ad18a07b | 2,847 | cc | C++ | src/base128.cc | niw/node-base128 | 791f61ab1926a1dd5bbbf07aab54c638d5fb15f5 | [
"MIT"
] | 16 | 2015-06-20T09:48:26.000Z | 2021-03-15T03:29:48.000Z | src/base128.cc | niw/node-base128 | 791f61ab1926a1dd5bbbf07aab54c638d5fb15f5 | [
"MIT"
] | 1 | 2017-09-24T15:51:19.000Z | 2017-09-24T15:51:19.000Z | src/base128.cc | niw/node-base128 | 791f61ab1926a1dd5bbbf07aab54c638d5fb15f5 | [
"MIT"
] | 1 | 2019-04-06T04:00:33.000Z | 2019-04-06T04:00:33.000Z | #include <node.h>
#include <nan.h>
#define THROW_BAD_ARGS Nan::ThrowTypeError("Bad argument")
#define THROW_NOT_ENOUGH_BUFFER Nan::ThrowTypeError("Not enough buffer")
NAN_METHOD(Decode) {
if(info.Length() < 2 ||
!node::Buffer::HasInstance(info[0]) ||
!node::Buffer::HasInstance(info[1])) {
THROW_BAD_ARGS;
return;
}
v8::Local<v8::Object> buffer_obj = info[0]->ToObject();
v8::Local<v8::Object> result_obj = info[1]->ToObject();
char * const data = node::Buffer::Data(buffer_obj);
char * const res = node::Buffer::Data(result_obj);
const size_t data_size = node::Buffer::Length(buffer_obj);
const size_t res_size = node::Buffer::Length(result_obj);
if(res_size < data_size * 7 / 8) {
THROW_NOT_ENOUGH_BUFFER;
return;
}
int carry_size = 0;
unsigned char carry_bits = 0x00;
size_t i, j;
for(i = 0, j = 0; i < data_size && j < res_size; ++i) {
unsigned char c = data[i];
if(c & 0x80) {
THROW_BAD_ARGS;
return;
}
c = c & 0x7F;
if(carry_size == 0) {
carry_size = 7;
carry_bits = c;
continue;
}
const int mask_size = 8 - carry_size;
const unsigned char mask = (1 << mask_size) - 1;
res[j++] = carry_bits | ((c & mask) << carry_size);
carry_bits = c >> mask_size;
--carry_size;
}
if(i < data_size || carry_bits) {
THROW_BAD_ARGS;
return;
}
info.GetReturnValue().Set(Nan::New((uint32_t)j));
}
NAN_METHOD(Encode) {
if(info.Length() < 2 ||
!node::Buffer::HasInstance(info[0]) ||
!node::Buffer::HasInstance(info[1])) {
THROW_BAD_ARGS;
return;
}
v8::Local<v8::Object> buffer_obj = info[0]->ToObject();
v8::Local<v8::Object> result_obj = info[1]->ToObject();
char * const data = node::Buffer::Data(buffer_obj);
char * const res = node::Buffer::Data(result_obj);
const size_t data_size = node::Buffer::Length(buffer_obj);
const size_t res_size = node::Buffer::Length(result_obj);
const size_t bits_size = data_size * 8;
if(res_size < bits_size / 7 + (bits_size % 7 ? 1 : 0)) {
THROW_NOT_ENOUGH_BUFFER;
return;
}
int carry_size = 0;
unsigned char carry_bits = 0x00;
size_t i, j;
for(i = 0, j = 0; i < data_size && j < res_size; ++j) {
if(carry_size == 7) {
res[j] = carry_bits;
carry_size = 0;
carry_bits = 0x00;
continue;
}
const unsigned char c = data[i++];
const int mask_size = 7 - carry_size;
const unsigned char mask = (1 << mask_size) - 1;
res[j] = ((c & mask) << carry_size) | carry_bits;
carry_bits = c >> mask_size;
++carry_size;
}
if(carry_size) {
res[j++] = carry_bits;
}
info.GetReturnValue().Set(Nan::New((uint32_t)j));
}
NAN_MODULE_INIT(init) {
Nan::Export(target, "decode", Decode);
Nan::Export(target, "encode", Encode);
}
NODE_MODULE(base128, init);
| 24.333333 | 72 | 0.616438 |
aea91cb28aa59ddadacb795cd728da5735946be3 | 5,910 | cpp | C++ | src/eds/http/headers.cpp | panyam/halley | 1bc8e9fe890d585c8ca524d6070591af656e206b | [
"Apache-2.0"
] | null | null | null | src/eds/http/headers.cpp | panyam/halley | 1bc8e9fe890d585c8ca524d6070591af656e206b | [
"Apache-2.0"
] | null | null | null | src/eds/http/headers.cpp | panyam/halley | 1bc8e9fe890d585c8ca524d6070591af656e206b | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
/*!
* 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 headers.cpp
*
* \brief
* All things http headers.
*
* \version
* - Sri Panyam 05/03/2009
* Created
*
*****************************************************************************/
#include "../utils.h"
#include "headers.h"
const SString TRUE_STRING = "true";
const SString FALSE_STRING = "false";
//! CLears the header table so we can start over again
void SHeaderTable::Reset()
{
closeConnection = false;
locked = false;
headers.clear();
}
//! Write the headers to the stream
int SHeaderTable::WriteToStream(std::ostream &output)
{
// write all headers!
HeaderMap::const_iterator iter = headers.begin();
for (;iter != headers.end();++iter)
{
output << iter->first << ": " << iter->second << URLUtils::CRLF;
SLogger::Get()->Log("DEBUG: Header %s: %s\n", iter->first.c_str(), iter->second.c_str());
}
// and an extra URLUtils::CRLF
output << URLUtils::CRLF;
output.flush();
return 0;
}
//! Writes the headers to a file descriptor
int SHeaderTable::WriteToFD(int fd)
{
SStringStream buffer;
WriteToStream(buffer);
SString outStr(buffer.str());
return SEDSUtils::SendFully(fd, outStr.c_str(), outStr.size());
}
// Reads a http header.
// Headers are read till a line with only a CRLF is found.
bool SHeaderTable::ReadNextHeader(std::istream &input, SString &name, SString &value)
{
SString line = URLUtils::ReadTillCrLf(input);
return ParseHeaderLine(line, name, value);
}
bool SHeaderTable::ReadHeaders(std::istream &input)
{
SString headerName;
SString headerValue;
// read all header lines
while (ReadNextHeader(input, headerName, headerValue)) { }
return !input.bad() && !input.eof();
}
//! Parses header line
bool SHeaderTable::ParseHeaderLine(const SString &line, SString &name, SString &value)
{
const char *pStart = line.c_str();
while (isspace(*pStart)) pStart++;
const char *pCurr = pStart;
// empty line?
if (*pCurr == 0) return false;
while (!URLUtils::iscontrol(*pCurr) && !URLUtils::isseperator(*pCurr))
pCurr++;
// found a colon?
if (*pCurr != ':') return false;
const char *pHeaderEnd = pCurr;
// skip the colon
pCurr++;
while (isspace(*pCurr)) pCurr++;
name = SString(pStart, pHeaderEnd - pStart);
value = SString(pCurr);
SLogger::Get()->Log("DEBUG: Header %s: %s\n", name.c_str(), value.c_str());
SetHeader(name, value);
return true;
}
// Tells if a header exists
bool SHeaderTable::HasHeader(const SString &name) const
{
HeaderMap::const_iterator iter = headers.find(name);
return iter != headers.end();
}
// Gets a header
SString SHeaderTable::Header(const SString &name) const
{
HeaderMap::const_iterator iter = headers.find(name);
if (iter == headers.end())
return "";
else
return iter->second;
}
//! Returns a header if it exists
bool SHeaderTable::HeaderIfExists(const SString &name, SString &value)
{
HeaderMap::const_iterator iter = headers.find(name);
if (iter == headers.end())
return false;
value = iter->second;
return true;
}
// Sets a header value - if it already exists, this value is appended to it.
void SHeaderTable::SetHeader(const SString &name, const SString &value, bool append)
{
if (locked) return ;
HeaderMap::iterator iter = headers.find(name);
if (iter != headers.end())
{
if (append)
{
SStringStream newvalue;
newvalue << iter->second << "," << value;
headers.insert(HeaderPair(name, newvalue.str()));
}
else
{
headers[name] = value;
}
}
else
{
headers.insert(HeaderPair(name, value));
}
if ((strcasecmp(name.c_str(), "Connection") == 0) &&
(strcasecmp(value.c_str(), "close") == 0))
{
closeConnection = true;
}
if (strcasecmp(name.c_str(), "content-length") == 0)
{
// contentLength = atoi(value.c_str());
}
}
//! Sets the value of an bool typed header
void SHeaderTable::SetBoolHeader(const SString &name, bool value)
{
SetHeader(name, value ? TRUE_STRING : FALSE_STRING);
}
//! Sets the value of an int typed header
void SHeaderTable::SetUIntHeader(const SString &name, unsigned value)
{
char valueStr[64];
sprintf(&valueStr[0], "%u", value);
SetHeader(name, &valueStr[0]);
}
//! Sets the value of an int typed header
void SHeaderTable::SetIntHeader(const SString &name, int value)
{
char valueStr[64];
sprintf(valueStr, "%d", value);
SetHeader(name, &valueStr[0]);
}
//! Sets the value of an double typed header
void SHeaderTable::SetDoubleHeader(const SString &name, double value)
{
char valueStr[64];
sprintf(valueStr, "%f", value);
SetHeader(name, &valueStr[0]);
}
// Removes a header
SString SHeaderTable::RemoveHeader(const SString &name)
{
if ( ! locked)
{
HeaderMap::iterator iter = headers.find(name);
if (iter != headers.end())
{
headers.erase(iter);
return iter->second;
}
}
return "";
}
| 25.921053 | 102 | 0.607614 |
aeab5fab1b6bc6bce7acf07a3e3bb4f1379c8f8a | 675 | hpp | C++ | ablateLibrary/flow/fluxDifferencer/offFluxDifferencer.hpp | pakserep/ablate | 8c8443de8a252b03b3535f7c48b7a50aac1e56e4 | [
"BSD-3-Clause"
] | null | null | null | ablateLibrary/flow/fluxDifferencer/offFluxDifferencer.hpp | pakserep/ablate | 8c8443de8a252b03b3535f7c48b7a50aac1e56e4 | [
"BSD-3-Clause"
] | null | null | null | ablateLibrary/flow/fluxDifferencer/offFluxDifferencer.hpp | pakserep/ablate | 8c8443de8a252b03b3535f7c48b7a50aac1e56e4 | [
"BSD-3-Clause"
] | null | null | null | #ifndef ABLATELIBRARY_OFFFLUXDIFFERENCER_HPP
#define ABLATELIBRARY_OFFFLUXDIFFERENCER_HPP
#include "fluxDifferencer.hpp"
namespace ablate::flow::fluxDifferencer {
/**
* Turns off all flow through the flux differencer. This is good for testing.
*/
class OffFluxDifferencer : public fluxDifferencer::FluxDifferencer {
private:
static void OffDifferencerFunction(PetscReal Mm, PetscReal* sPm, PetscReal* sMm, PetscReal Mp, PetscReal* sPp, PetscReal* sMp);
public:
FluxDifferencerFunction GetFluxDifferencerFunction() override { return OffDifferencerFunction; }
};
} // namespace ablate::flow::fluxDifferencer
#endif // ABLATELIBRARY_OFFFLUXDIFFERENCER_HPP
| 35.526316 | 131 | 0.795556 |
aeb7b7e5ef4835f5aab62c5420c65d825046fad1 | 1,426 | cpp | C++ | main/Main.cpp | Cararasu/holodec | d716d95a787ab7872a49a5c4fb930dc37be95ac7 | [
"MIT"
] | 215 | 2017-06-22T16:23:52.000Z | 2022-01-27T23:33:37.000Z | main/Main.cpp | Cararasu/holodec | d716d95a787ab7872a49a5c4fb930dc37be95ac7 | [
"MIT"
] | 4 | 2017-06-29T16:49:28.000Z | 2019-02-07T19:58:57.000Z | main/Main.cpp | Cararasu/holodec | d716d95a787ab7872a49a5c4fb930dc37be95ac7 | [
"MIT"
] | 21 | 2017-10-14T02:10:41.000Z | 2021-07-13T06:08:38.000Z | #include "Main.h"
#include <fstream>
using namespace holodec;
Main* Main::g_main;
bool Main::registerArchitecture (Architecture* arch) {
for (Architecture * a : architectures)
if (caseCmpHString (a->name, arch->name))
return false;
architectures.push_back (arch);
return true;
}
Architecture* Main::getArchitecture (HString arch) {
for (Architecture * a : architectures)
if (caseCmpHString (a->name, arch))
return a;
return nullptr;
}
bool Main::registerFileFormat (FileFormat* fileformat) {
for (FileFormat * ff : fileformats)
if (caseCmpHString (ff->name, fileformat->name))
return false;
fileformats.push_back (fileformat);
return true;
}
FileFormat* Main::getFileFormat (HString fileformat) {
for (FileFormat * ff : fileformats)
if (caseCmpHString (ff->name, fileformat))
return ff;
return nullptr;
}
File* Main::loadDataFromFile (HString file) {
std::ifstream t (file.cstr(), std::ios_base::binary);
size_t size;
std::vector<uint8_t> data;
if (t) {
t.seekg (0, t.end);
size = (size_t) t.tellg();
data.resize(size);
t.seekg (0, t.beg);
uint64_t offset = 0;
while (offset < size) {
t.read((char*)data.data() + offset, size);
uint64_t read = t.gcount();
if (read == 0)
break;
offset += read;
printf("Read %zu chars\n", t.gcount());
}
return new File(file, data);
}
return nullptr;
}
void holodec::Main::initMain() {
g_main = new Main();
}
| 21.283582 | 56 | 0.671809 |
aec031dfa142d090bef5a69895f524840deb7403 | 4,775 | cc | C++ | diplomacy_research/proto/diplomacy_tensorflow/core/protobuf/master_service.pb.cc | wwongkamjan/dipnet_press | 787263c1b9484698904f525c8d78d0e333e1c0d9 | [
"MIT"
] | 39 | 2019-09-06T13:42:24.000Z | 2022-03-18T18:38:43.000Z | diplomacy_research/proto/diplomacy_tensorflow/core/protobuf/master_service.pb.cc | wwongkamjan/dipnet_press | 787263c1b9484698904f525c8d78d0e333e1c0d9 | [
"MIT"
] | 9 | 2019-09-19T22:35:32.000Z | 2022-02-24T18:04:57.000Z | diplomacy_research/proto/diplomacy_tensorflow/core/protobuf/master_service.pb.cc | wwongkamjan/dipnet_press | 787263c1b9484698904f525c8d78d0e333e1c0d9 | [
"MIT"
] | 8 | 2019-10-16T21:09:14.000Z | 2022-02-23T05:20:37.000Z | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: diplomacy_tensorflow/core/protobuf/master_service.proto
#include "diplomacy_tensorflow/core/protobuf/master_service.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// This is a temporary google only hack
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
namespace diplomacy {
namespace tensorflow {
namespace grpc {
} // namespace grpc
} // namespace tensorflow
} // namespace diplomacy
namespace protobuf_diplomacy_5ftensorflow_2fcore_2fprotobuf_2fmaster_5fservice_2eproto {
void InitDefaults() {
}
const ::google::protobuf::uint32 TableStruct::offsets[1] = {};
static const ::google::protobuf::internal::MigrationSchema* schemas = NULL;
static const ::google::protobuf::Message* const* file_default_instances = NULL;
void protobuf_AssignDescriptors() {
AddDescriptors();
AssignDescriptors(
"diplomacy_tensorflow/core/protobuf/master_service.proto", schemas, file_default_instances, TableStruct::offsets,
NULL, NULL, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static ::google::protobuf::internal::once_flag once;
::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
}
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n7diplomacy_tensorflow/core/protobuf/mas"
"ter_service.proto\022\031diplomacy.tensorflow."
"grpc\032/diplomacy_tensorflow/core/protobuf"
"/master.proto2\203\010\n\rMasterService\022h\n\rCreat"
"eSession\022*.diplomacy.tensorflow.CreateSe"
"ssionRequest\032+.diplomacy.tensorflow.Crea"
"teSessionResponse\022h\n\rExtendSession\022*.dip"
"lomacy.tensorflow.ExtendSessionRequest\032+"
".diplomacy.tensorflow.ExtendSessionRespo"
"nse\022n\n\017PartialRunSetup\022,.diplomacy.tenso"
"rflow.PartialRunSetupRequest\032-.diplomacy"
".tensorflow.PartialRunSetupResponse\022V\n\007R"
"unStep\022$.diplomacy.tensorflow.RunStepReq"
"uest\032%.diplomacy.tensorflow.RunStepRespo"
"nse\022e\n\014CloseSession\022).diplomacy.tensorfl"
"ow.CloseSessionRequest\032*.diplomacy.tenso"
"rflow.CloseSessionResponse\022b\n\013ListDevice"
"s\022(.diplomacy.tensorflow.ListDevicesRequ"
"est\032).diplomacy.tensorflow.ListDevicesRe"
"sponse\022P\n\005Reset\022\".diplomacy.tensorflow.R"
"esetRequest\032#.diplomacy.tensorflow.Reset"
"Response\022e\n\014MakeCallable\022).diplomacy.ten"
"sorflow.MakeCallableRequest\032*.diplomacy."
"tensorflow.MakeCallableResponse\022b\n\013RunCa"
"llable\022(.diplomacy.tensorflow.RunCallabl"
"eRequest\032).diplomacy.tensorflow.RunCalla"
"bleResponse\022n\n\017ReleaseCallable\022,.diploma"
"cy.tensorflow.ReleaseCallableRequest\032-.d"
"iplomacy.tensorflow.ReleaseCallableRespo"
"nseBq\n\032org.tensorflow.distruntimeB\023Maste"
"rServiceProtosP\001Z<github.com/tensorflow/"
"tensorflow/tensorflow/go/core/protobufb\006"
"proto3"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 1286);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"diplomacy_tensorflow/core/protobuf/master_service.proto", &protobuf_RegisterTypes);
::protobuf_diplomacy_5ftensorflow_2fcore_2fprotobuf_2fmaster_2eproto::AddDescriptors();
}
void AddDescriptors() {
static ::google::protobuf::internal::once_flag once;
::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at dynamic initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_diplomacy_5ftensorflow_2fcore_2fprotobuf_2fmaster_5fservice_2eproto
namespace diplomacy {
namespace tensorflow {
namespace grpc {
// @@protoc_insertion_point(namespace_scope)
} // namespace grpc
} // namespace tensorflow
} // namespace diplomacy
namespace google {
namespace protobuf {
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
| 39.139344 | 119 | 0.770681 |
aec0575a03cec24039c6073cf35b9875a7db2962 | 353 | hpp | C++ | SDLTest.hpp | gazpachian/ScrabookDL | 70424e4d866d17d95539242ba86ad0841f030091 | [
"MIT"
] | null | null | null | SDLTest.hpp | gazpachian/ScrabookDL | 70424e4d866d17d95539242ba86ad0841f030091 | [
"MIT"
] | null | null | null | SDLTest.hpp | gazpachian/ScrabookDL | 70424e4d866d17d95539242ba86ad0841f030091 | [
"MIT"
] | null | null | null | #include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <stdio.h>
#include <string>
#include <algorithm>
#include <tr1/memory>
#include "vector.hpp"
#include "controller.hpp"
#include "render.hpp"
//Window constants
const Vector2 DEF_SCREEN_DIMS(1200, 675);
const Vector3 DEF_BG_COL(0xFD, 0xF6, 0xE3);
const char * window_title = "Title of window";
| 23.533333 | 46 | 0.745042 |
aeca4b2a297c118a8eb65076e18adcd6c73e2e56 | 6,680 | cpp | C++ | Interaction/albaDevice.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | 9 | 2018-11-19T10:15:29.000Z | 2021-08-30T11:52:07.000Z | Interaction/albaDevice.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Interaction/albaDevice.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2018-06-10T22:56:29.000Z | 2019-12-12T06:22:56.000Z | /*=========================================================================
Program: ALBA (Agile Library for Biomedical Applications)
Module: albaDevice
Authors: Marco Petrone
Copyright (c) BIC
All rights reserved. See Copyright.txt or
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.
=========================================================================*/
// to be includes first: includes wxWindows too...
#include "albaDefines.h"
// base includes
#include "albaDevice.h"
#include "mmuIdFactory.h"
// GUI
#include "albaGUI.h"
// serialization
#include "albaStorageElement.h"
//------------------------------------------------------------------------------
// Events
//------------------------------------------------------------------------------
ALBA_ID_IMP(albaDevice::DEVICE_NAME_CHANGED)
ALBA_ID_IMP(albaDevice::DEVICE_STARTED)
ALBA_ID_IMP(albaDevice::DEVICE_STOPPED)
albaCxxTypeMacro(albaDevice)
//------------------------------------------------------------------------------
albaDevice::albaDevice()
//------------------------------------------------------------------------------
{
m_Gui = NULL;
m_ID = 0;
m_Start = false;
m_AutoStart = false; // auto is enabled when device is started the first time
m_Locked = false;
m_PersistentFalg = false;
}
//------------------------------------------------------------------------------
albaDevice::~albaDevice()
//------------------------------------------------------------------------------
{
}
//------------------------------------------------------------------------------
void albaDevice::SetName(const char *name)
//------------------------------------------------------------------------------
{
Superclass::SetName(name);
InvokeEvent(this,DEVICE_NAME_CHANGED); // send event to device manager (up)
}
//------------------------------------------------------------------------------
int albaDevice::InternalInitialize()
//------------------------------------------------------------------------------
{
int ret=Superclass::InternalInitialize();
m_AutoStart = 1; // enable auto starting of device
// update the GUI if present
return ret;
}
//------------------------------------------------------------------------------
int albaDevice::Start()
//------------------------------------------------------------------------------
{
if (Initialize())
return ALBA_ERROR;
// send an event to advise interactors this device has been started
InvokeEvent(this,DEVICE_STARTED,MCH_INPUT);
return ALBA_OK;
}
//------------------------------------------------------------------------------
void albaDevice::Stop()
//------------------------------------------------------------------------------
{
if (!m_Initialized)
return;
Shutdown();
// send an event to advise interactors this device has been stopped
InvokeEvent(this,DEVICE_STOPPED,MCH_INPUT);
}
//----------------------------------------------------------------------------
albaGUI *albaDevice::GetGui()
//----------------------------------------------------------------------------
{
if (!m_Gui)
CreateGui();
return m_Gui;
}
//----------------------------------------------------------------------------
void albaDevice::CreateGui()
//----------------------------------------------------------------------------
{
/* //SIL. 07-jun-2006 :
assert(m_Gui == NULL);
m_Gui = new albaGUI(this);
m_Gui->String(ID_NAME,"name",&m_Name);
m_Gui->Divider();
m_Gui->Button(ID_ACTIVATE,"activate device");
m_Gui->Button(ID_SHUTDOWN,"shutdown device");
m_Gui->Bool(ID_AUTO_START,"auto start",&m_AutoStart,0,"automatically start device on application startup");
m_Gui->Enable(ID_ACTIVATE,!IsInitialized());
m_Gui->Enable(ID_SHUTDOWN,IsInitialized()!=0);
*/
assert(m_Gui == NULL);
m_Gui = new albaGUI(this);
m_Gui->String(ID_NAME,"name",&m_Name);
m_Gui->Divider();
m_Gui->Bool(ID_ACTIVATE,"start",&m_Start,0,"activate/deactivate this device");
m_Gui->Bool(ID_AUTO_START,"auto start",&m_AutoStart,0,"automatically activate device on application startup");
//m_Gui->Enable(ID_ACTIVATE,!IsInitialized());
//m_Gui->Enable(ID_SHUTDOWN,IsInitialized()!=0);
m_Gui->Divider();
}
//----------------------------------------------------------------------------
void albaDevice::UpdateGui()
//----------------------------------------------------------------------------
{
if (m_Gui)
{
//m_Gui->Enable(ID_ACTIVATE,!IsInitialized());
//m_Gui->Enable(ID_SHUTDOWN,IsInitialized()!=0);
m_Start = IsInitialized();
m_Gui->Update();
}
}
//----------------------------------------------------------------------------
void albaDevice::OnEvent(albaEventBase *e)
//----------------------------------------------------------------------------
{
albaEvent *ev = albaEvent::SafeDownCast(e);
if (ev&& ev->GetSender()==m_Gui)
{
switch(ev->GetId())
{
case ID_NAME:
SetName(m_Name); // force sending an event
break;
case ID_ACTIVATE:
if(m_Start) // user request to Start
{
if (Initialize())
albaErrorMessage("Cannot Initialize Device","I/O Error");
}
else // user request to Stop
{
Shutdown();
}
UpdateGui();
break;
/* //SIL. 07-jun-2006 :
case ID_SHUTDOWN:
Shutdown();
UpdateGui();
break;
*/
}
return;
}
else
{
// pass event to superclass to be processed
Superclass::OnEvent(e);
}
}
//------------------------------------------------------------------------------
int albaDevice::InternalStore(albaStorageElement *node)
//------------------------------------------------------------------------------
{
if (node->StoreText("Name",m_Name)==ALBA_OK && \
node->StoreInteger("ID",(m_ID-MIN_DEVICE_ID))==ALBA_OK && \
node->StoreInteger("AutoStart",m_AutoStart)==ALBA_OK)
return ALBA_OK;
return ALBA_ERROR;
}
//------------------------------------------------------------------------------
int albaDevice::InternalRestore(albaStorageElement *node)
//------------------------------------------------------------------------------
{
// Device Name
if (node->RestoreText("Name",m_Name)==ALBA_OK)
{
int dev_id;
node->RestoreInteger("ID",dev_id);
SetID(dev_id+MIN_DEVICE_ID);
int flag;
// AutoStart flag (optional)
if (node->RestoreInteger("AutoStart",flag)==ALBA_OK)
{
SetAutoStart(flag!=0);
}
// the ID???
return ALBA_OK;
}
return ALBA_ERROR;
}
| 29.688889 | 112 | 0.448054 |
aecd7dece280518c3882099caebe07274c7374ae | 1,525 | cpp | C++ | src/easy/trick-or-treat/solutions/c++/solution.cpp | rdtsc/codeeval-solutions | d5c06baf89125e9e9f4b163ee57e5a8f7e73e717 | [
"MIT"
] | null | null | null | src/easy/trick-or-treat/solutions/c++/solution.cpp | rdtsc/codeeval-solutions | d5c06baf89125e9e9f4b163ee57e5a8f7e73e717 | [
"MIT"
] | null | null | null | src/easy/trick-or-treat/solutions/c++/solution.cpp | rdtsc/codeeval-solutions | d5c06baf89125e9e9f4b163ee57e5a8f7e73e717 | [
"MIT"
] | null | null | null | #include <cassert>
#include <fstream>
#include <iostream>
#include <limits>
template<typename T>
static bool extractFrom(std::istream& inputStream,
const char delimiter,
T& value)
{
static constexpr auto ignoreLimit =
std::numeric_limits<std::streamsize>::max();
return inputStream.ignore(ignoreLimit, delimiter) >> value;
}
template<typename T, typename... Values>
static bool extractFrom(std::istream& inputStream,
const char delimiter,
T& value,
Values&... values)
{
return ::extractFrom(inputStream, delimiter, value) &&
::extractFrom(inputStream, delimiter, values...);
}
int main(const int argc, const char* const argv[])
{
// Getting away with no error checking throughout because CodeEval makes some
// strong guarantees about our runtime environment. No need to pay when we're
// being benchmarked. Don't forget to define NDEBUG prior to submitting!
assert(argc >= 2 && "Expecting at least one command-line argument.");
std::ifstream inputStream(argv[1]);
assert(inputStream && "Failed to open input stream.");
unsigned v = 0, z = 0, w = 0, h = 0;
while(::extractFrom(inputStream, ':', v, z, w, h))
{
const auto take = v * 3 + // Vampires.
z * 4 + // Zombies.
w * 5; // Witches.
const auto loot = (take * h),
shares = (v + z + w);
std::cout << (loot / shares) << '\n';
}
}
| 29.326923 | 79 | 0.594098 |
aed084fb525b5f25e7ee5eed598324734eff4068 | 1,580 | cpp | C++ | src/effect_cas.cpp | stephanlachnit/vkBasalt | dd6a067b7eada67f4f34e56054ef24264f6856d7 | [
"Zlib"
] | 748 | 2019-10-20T14:21:20.000Z | 2022-03-22T05:53:42.000Z | src/effect_cas.cpp | stephanlachnit/vkBasalt | dd6a067b7eada67f4f34e56054ef24264f6856d7 | [
"Zlib"
] | 160 | 2019-10-20T16:35:47.000Z | 2022-03-30T19:21:56.000Z | src/effect_cas.cpp | stephanlachnit/vkBasalt | dd6a067b7eada67f4f34e56054ef24264f6856d7 | [
"Zlib"
] | 58 | 2019-10-20T19:15:01.000Z | 2022-01-02T01:16:08.000Z | #include "effect_cas.hpp"
#include <cstring>
#include "image_view.hpp"
#include "descriptor_set.hpp"
#include "buffer.hpp"
#include "renderpass.hpp"
#include "graphics_pipeline.hpp"
#include "framebuffer.hpp"
#include "shader.hpp"
#include "sampler.hpp"
#include "shader_sources.hpp"
namespace vkBasalt
{
CasEffect::CasEffect(LogicalDevice* pLogicalDevice,
VkFormat format,
VkExtent2D imageExtent,
std::vector<VkImage> inputImages,
std::vector<VkImage> outputImages,
Config* pConfig)
{
float sharpness = pConfig->getOption<float>("casSharpness", 0.4f);
vertexCode = full_screen_triangle_vert;
fragmentCode = cas_frag;
VkSpecializationMapEntry sharpnessMapEntry;
sharpnessMapEntry.constantID = 0;
sharpnessMapEntry.offset = 0;
sharpnessMapEntry.size = sizeof(float);
VkSpecializationInfo fragmentSpecializationInfo;
fragmentSpecializationInfo.mapEntryCount = 1;
fragmentSpecializationInfo.pMapEntries = &sharpnessMapEntry;
fragmentSpecializationInfo.dataSize = sizeof(float);
fragmentSpecializationInfo.pData = &sharpness;
pVertexSpecInfo = nullptr;
pFragmentSpecInfo = &fragmentSpecializationInfo;
init(pLogicalDevice, format, imageExtent, inputImages, outputImages, pConfig);
}
CasEffect::~CasEffect()
{
}
} // namespace vkBasalt
| 30.980392 | 86 | 0.635443 |
aed3281640470573c0c4ef23e1888bd1b850ecee | 403 | cpp | C++ | Rafflesia/main.cpp | TelepathicFart/Rafflesia | 9376e06b5a7ab3f712677f31504021c1b62c3f09 | [
"MIT"
] | 5 | 2021-05-11T02:52:31.000Z | 2021-09-03T05:10:53.000Z | Rafflesia/main.cpp | TelepathicFart/Rafflesia | 9376e06b5a7ab3f712677f31504021c1b62c3f09 | [
"MIT"
] | null | null | null | Rafflesia/main.cpp | TelepathicFart/Rafflesia | 9376e06b5a7ab3f712677f31504021c1b62c3f09 | [
"MIT"
] | 1 | 2022-02-24T13:56:26.000Z | 2022-02-24T13:56:26.000Z | #include <QtWidgets>
#include "MainWindow.h"
#include <istream>
#include <fstream>
int main(int argc, char *argv[])
{
#if defined(Q_OS_WIN)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QApplication app(argc, argv);
MainWindow window;
window.show();
window.setWindowTitle(QApplication::translate("toplevel", "Top-level widget"));
return app.exec();
}
| 18.318182 | 83 | 0.704715 |
aed923244e3a075b6566c3fb94879181634bcba8 | 1,094 | cpp | C++ | projects/Test_SkeletalAnimation/src/main.cpp | codeonwort/pathosengine | ea568afeac9af3ebe3f2e53cc5abeecb40714466 | [
"MIT"
] | 11 | 2016-08-30T12:01:35.000Z | 2021-12-29T15:34:03.000Z | projects/Test_SkeletalAnimation/src/main.cpp | codeonwort/pathosengine | ea568afeac9af3ebe3f2e53cc5abeecb40714466 | [
"MIT"
] | 9 | 2016-05-19T03:14:22.000Z | 2021-01-17T05:45:52.000Z | projects/Test_SkeletalAnimation/src/main.cpp | codeonwort/pathosengine | ea568afeac9af3ebe3f2e53cc5abeecb40714466 | [
"MIT"
] | null | null | null | #include "world2.h"
#include "pathos/core_minimal.h"
using namespace std;
using namespace pathos;
constexpr int32 WINDOW_WIDTH = 1920;
constexpr int32 WINDOW_HEIGHT = 1080;
constexpr char* WINDOW_TITLE = "Test: Skeletal Animation";
constexpr float FOVY = 60.0f;
const vector3 CAMERA_POSITION = vector3(0.0f, 0.0f, 300.0f);
constexpr float CAMERA_Z_NEAR = 1.0f;
constexpr float CAMERA_Z_FAR = 10000.0f;
int main(int argc, char** argv) {
EngineConfig conf;
conf.windowWidth = WINDOW_WIDTH;
conf.windowHeight = WINDOW_HEIGHT;
conf.title = WINDOW_TITLE;
conf.rendererType = ERendererType::Deferred;
Engine::init(argc, argv, conf);
const float ar = static_cast<float>(conf.windowWidth) / static_cast<float>(conf.windowHeight);
World* world2 = new World2;
world2->getCamera().lookAt(CAMERA_POSITION, CAMERA_POSITION + vector3(0.0f, 0.0f, -1.0f), vector3(0.0f, 1.0f, 0.0f));
world2->getCamera().changeLens(PerspectiveLens(FOVY, ar, CAMERA_Z_NEAR, CAMERA_Z_FAR));
gEngine->setWorld(world2);
gEngine->start();
return 0;
}
| 33.151515 | 118 | 0.710238 |
aede19bebef2025d433365c92bd970cd74a809aa | 57 | hpp | C++ | src/boost_fusion_sequence_comparison_equal_to.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_fusion_sequence_comparison_equal_to.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_fusion_sequence_comparison_equal_to.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/fusion/sequence/comparison/equal_to.hpp>
| 28.5 | 56 | 0.824561 |
aede8903b4395c28d2a04d5f065094bba39c31da | 3,738 | cpp | C++ | Engine/Core/Source/Molten/Renderer/Vulkan/Utility/VulkanDeviceQueues.cpp | jimmiebergmann/CurseEngine | 74a0502e36327f893c8e4f3e7cbe5b9d38fbe194 | [
"MIT"
] | 2 | 2019-11-11T21:17:14.000Z | 2019-11-11T22:07:26.000Z | Engine/Core/Source/Molten/Renderer/Vulkan/Utility/VulkanDeviceQueues.cpp | jimmiebergmann/CurseEngine | 74a0502e36327f893c8e4f3e7cbe5b9d38fbe194 | [
"MIT"
] | null | null | null | Engine/Core/Source/Molten/Renderer/Vulkan/Utility/VulkanDeviceQueues.cpp | jimmiebergmann/CurseEngine | 74a0502e36327f893c8e4f3e7cbe5b9d38fbe194 | [
"MIT"
] | 1 | 2020-04-05T03:50:57.000Z | 2020-04-05T03:50:57.000Z | /*
* MIT License
*
* Copyright (c) 2021 Jimmie Bergmann
*
* 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.
*
*/
#if defined(MOLTEN_ENABLE_VULKAN)
#include "Molten/Renderer/Vulkan/Utility/VulkanDeviceQueues.hpp"
MOLTEN_UNSCOPED_ENUM_BEGIN
namespace Molten::Vulkan
{
// Device queue indices implemenetations.
DeviceQueueIndices::DeviceQueueIndices() :
graphicsQueue{},
presentQueue{}
{}
// Device queues implementations.
DeviceQueues::DeviceQueues() :
graphicsQueue(VK_NULL_HANDLE),
presentQueue(VK_NULL_HANDLE),
graphicsQueueIndex(0),
presentQueueIndex(0)
{}
// Static implementations.
void FetchQueueFamilyProperties(
QueueFamilyProperties& queueFamilyProperties,
VkPhysicalDevice physicalDevice)
{
queueFamilyProperties.clear();
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr);
if (!queueFamilyCount)
{
return;
}
queueFamilyProperties.resize(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilyProperties.data());
}
bool FindRenderableDeviceQueueIndices(
DeviceQueueIndices& queueIndices,
VkPhysicalDevice physicalDevice,
const VkSurfaceKHR surface,
const QueueFamilyProperties& queueFamilies)
{
queueIndices.graphicsQueue.reset();
queueIndices.presentQueue.reset();
uint32_t finalGraphicsQueueIndex = 0;
uint32_t finalPresentQueueIndex = 0;
bool graphicsFamilySupport = false;
bool presentFamilySupport = false;
for (uint32_t i = 0; i < queueFamilies.size(); i++)
{
auto& queueFamily = queueFamilies[i];
if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT)
{
graphicsFamilySupport = true;
finalGraphicsQueueIndex = i;
}
VkBool32 presentSupport = false;
vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport);
if (presentSupport)
{
presentFamilySupport = true;
finalPresentQueueIndex = i;
}
if (graphicsFamilySupport && presentFamilySupport)
{
break;
}
}
if (!graphicsFamilySupport || !presentFamilySupport)
{
return false;
}
queueIndices.graphicsQueue = finalGraphicsQueueIndex;
queueIndices.presentQueue = finalPresentQueueIndex;
return true;
}
}
MOLTEN_UNSCOPED_ENUM_END
#endif | 30.390244 | 114 | 0.67817 |
aee11d7d4e9a3c4135f46a2909da6c8017d15bd2 | 4,614 | cpp | C++ | Development/Editor/Plugin/Warcraft3/yd_lua_engine/lua_engine/libs_runtime.cpp | shawwwn/YDWE | b83ffe041d9623409d9ffd951988e2b482d9cfc3 | [
"Apache-2.0"
] | 2 | 2016-05-30T11:42:33.000Z | 2017-10-31T11:53:42.000Z | Development/Editor/Plugin/Warcraft3/yd_lua_engine/lua_engine/libs_runtime.cpp | shawwwn/YDWE | b83ffe041d9623409d9ffd951988e2b482d9cfc3 | [
"Apache-2.0"
] | null | null | null | Development/Editor/Plugin/Warcraft3/yd_lua_engine/lua_engine/libs_runtime.cpp | shawwwn/YDWE | b83ffe041d9623409d9ffd951988e2b482d9cfc3 | [
"Apache-2.0"
] | null | null | null | #include <base/lua/state.h>
#include <base/util/console.h>
#include <cstring>
#include "libs_runtime.h"
namespace base { namespace warcraft3 { namespace lua_engine {
namespace runtime
{
int version = 2;
int handle_level = 2;
bool console = false;
bool sleep = true;
bool catch_crash = true;
void initialize()
{
handle_level = 2;
console = false;
sleep = true;
catch_crash = true;
}
int set_err_function(lua::state* ls, int index)
{
if (ls->isfunction(index) || ls->isnil(index))
{
ls->pushvalue(index);
ls->setfield(LUA_REGISTRYINDEX, "_JASS_ERROR_HANDLE");
}
return 0;
}
int get_err_function(lua::state* ls)
{
ls->getfield(LUA_REGISTRYINDEX, "_JASS_ERROR_HANDLE");
return 1;
}
int get_global_table(lua::state* ls, const char* name, bool weak)
{
ls->getfield(LUA_REGISTRYINDEX, name);
if (!ls->istable(-1))
{
ls->pop(1);
ls->newtable();
if (weak)
{
ls->newtable();
{
ls->pushstring("__mode");
ls->pushstring("kv");
ls->rawset(-3);
}
ls->setmetatable(-2);
}
ls->pushvalue(-1);
ls->setfield(LUA_REGISTRYINDEX, name);
}
return 1;
}
int thread_get_table(lua::state* ls)
{
return get_global_table(ls, "_JASS_THREAD_TABLE", true);
}
int thread_create(lua::state* ls, int index)
{
thread_get_table(ls);
ls->pushvalue(index);
ls->rawget(-2);
if (ls->isnil(-1))
{
ls->pop(1);
ls->newthread();
}
else
{
ls->pushvalue(index);
ls->pushnil();
ls->rawset(-4);
}
ls->remove(-2);
return 1;
}
int thread_save(lua::state* ls, int key, int value)
{
thread_get_table(ls);
ls->pushvalue(key);
ls->pushvalue(value);
ls->rawset(-3);
ls->pop(1);
return 0;
}
int handle_ud_get_table(lua::state* ls)
{
return get_global_table(ls, "_JASS_HANDLE_UD_TABLE", true);
}
int callback_get_table(lua::state* ls)
{
return get_global_table(ls, "_JASS_CALLBACK_TABLE", false);
}
int callback_push(lua::state* ls, int idx)
{
callback_get_table(ls);
// read t[v]
ls->pushvalue(idx);
ls->rawget(-2);
if (ls->isnumber(-1))
{
int ret = ls->tointeger(-1);
ls->pop(2);
return ret;
}
ls->pop(1);
// free = t[0] + 1
ls->rawgeti(-1, 0);
int free = 1 + ls->tointeger(-1);
ls->pop(1);
// t[0] = free
ls->pushinteger(free);
ls->rawseti(-2, 0);
// t[free] = v
ls->pushvalue(idx);
ls->rawseti(-2, free);
// t[v] = free
ls->pushvalue(idx);
ls->pushinteger(free);
ls->rawset(-3);
// pop t
ls->pop(1);
return free;
}
int callback_read(lua::state* ls, int ref)
{
callback_get_table(ls);
ls->rawgeti(-1, ref);
ls->remove(-2);
return 1;
}
}
int jass_runtime_set(lua_State* L)
{
lua::state* ls = (lua::state*)L;
const char* name = ls->tostring(2);
if (strcmp("error_handle", name) == 0)
{
runtime::set_err_function(ls, 3);
}
else if (strcmp("handle_level", name) == 0)
{
runtime::handle_level = ls->checkinteger(3);
}
else if (strcmp("console", name) == 0)
{
runtime::console = !!ls->toboolean(3);
if (runtime::console)
{
console::enable();
console::disable_close_button();
}
else
{
console::disable();
}
}
else if (strcmp("sleep", name) == 0)
{
runtime::sleep = !!ls->toboolean(3);
}
else if (strcmp("catch_crash", name) == 0)
{
runtime::catch_crash = !!ls->toboolean(3);
}
return 0;
}
int jass_runtime_get(lua_State* L)
{
lua::state* ls = (lua::state*)L;
const char* name = ls->tostring(2);
if (strcmp("version", name) == 0)
{
ls->pushinteger(runtime::version);
return 1;
}
else if (strcmp("error_handle", name) == 0)
{
return runtime::get_err_function(ls);
}
else if (strcmp("handle_level", name) == 0)
{
ls->pushinteger(runtime::handle_level);
return 1;
}
else if (strcmp("console", name) == 0)
{
ls->pushboolean(runtime::console);
return 1;
}
else if (strcmp("sleep", name) == 0)
{
ls->pushboolean(runtime::sleep);
return 1;
}
else if (strcmp("catch_crash", name) == 0)
{
ls->pushboolean(runtime::catch_crash);
return 1;
}
return 0;
}
int jass_runtime(lua::state* ls)
{
ls->newtable();
{
ls->newtable();
{
ls->pushstring("__index");
ls->pushcclosure((lua::cfunction)jass_runtime_get, 0);
ls->rawset(-3);
ls->pushstring("__newindex");
ls->pushcclosure((lua::cfunction)jass_runtime_set, 0);
ls->rawset(-3);
}
ls->setmetatable(-2);
}
return 1;
}
}}}
| 18.309524 | 67 | 0.584092 |
aee5dbfe6d334342322d1d2cccc32e28a8cdf42b | 209 | cpp | C++ | basic/12_fungsi/fungsi.cpp | khairanabila/CPP | 48b18b6bf835d8075fc96bbf183adf28a71ba819 | [
"MIT"
] | 23 | 2021-09-10T00:08:48.000Z | 2022-03-24T16:09:30.000Z | basic/12_fungsi/fungsi.cpp | khairanabila/CPP | 48b18b6bf835d8075fc96bbf183adf28a71ba819 | [
"MIT"
] | 20 | 2021-09-21T15:34:21.000Z | 2021-11-28T18:52:10.000Z | basic/12_fungsi/fungsi.cpp | khairanabila/CPP | 48b18b6bf835d8075fc96bbf183adf28a71ba819 | [
"MIT"
] | 27 | 2021-09-10T02:35:56.000Z | 2022-01-24T10:46:06.000Z | #include <iostream>
// membuat fungsi tanpa return nilai
void panggil() {
std::cout << "Fungsi tanpa return" << std::endl;
}
int main(){
// memanggil fungsi panggil()
panggil();
return 0;
}
| 14.928571 | 52 | 0.617225 |
aee7a2814780ca3c8a8e7c7aa5c504bcb70ef324 | 1,961 | cc | C++ | bin/scaling/traversal.cc | manopapad/flecsi | 8bb06e4375f454a0680564c76df2c60ffe49c770 | [
"Unlicense"
] | null | null | null | bin/scaling/traversal.cc | manopapad/flecsi | 8bb06e4375f454a0680564c76df2c60ffe49c770 | [
"Unlicense"
] | null | null | null | bin/scaling/traversal.cc | manopapad/flecsi | 8bb06e4375f454a0680564c76df2c60ffe49c770 | [
"Unlicense"
] | null | null | null | CINCH_CAPTURE() << "------------- forall cells, vertices" << endl;
for(auto cell : mesh->entities<2, $DOMAIN>()) {
CINCH_CAPTURE() << "------------- cell id: " << cell.id() << endl;
for(auto vertex : mesh->entities<0, $DOMAIN>(cell)) {
CINCH_CAPTURE() << "--- vertex id: " << vertex.id() << endl;
for(auto cell2 : mesh->entities<2, $DOMAIN>(vertex)) {
CINCH_CAPTURE() << "+ cell2 id: " << cell2.id() << endl;
}
}
}
CINCH_CAPTURE() << "------------- forall cells, edges" << endl;
for(auto cell : mesh->entities<2, $DOMAIN>()) {
CINCH_CAPTURE() << "------- cell id: " << cell.id() << endl;
for(auto edge : mesh->entities<1, $DOMAIN>(cell)) {
CINCH_CAPTURE() << "--- edge id: " << edge.id() << endl;
}
}
CINCH_CAPTURE() << "------------- forall vertices, edges" << endl;
for(auto vertex : mesh->entities<0, $DOMAIN>()) {
CINCH_CAPTURE() << "------- vertex id: " << vertex.id() << endl;
for(auto edge : mesh->entities<1, $DOMAIN>(vertex)) {
CINCH_CAPTURE() << "--- edge id: " << edge.id() << endl;
}
}
CINCH_CAPTURE() << "------------- forall vertices, cells" << endl;
for(auto vertex : mesh->entities<0, $DOMAIN>()) {
CINCH_CAPTURE() << "------- vertex id: " << vertex.id() << endl;
for(auto cell : mesh->entities<2, $DOMAIN>(vertex)) {
CINCH_CAPTURE() << "--- cell id: " << cell.id() << endl;
}
}
CINCH_CAPTURE() << "------------- forall edges, cells" << endl;
for(auto edge : mesh->entities<1, $DOMAIN>()) {
CINCH_CAPTURE() << "------- edge id: " << edge.id() << endl;
for(auto cell : mesh->entities<2, $DOMAIN>(edge)) {
CINCH_CAPTURE() << "--- cell id: " << cell.id() << endl;
}
}
CINCH_CAPTURE() << "------------- forall edges, vertices" << endl;
for(auto edge : mesh->entities<1, $DOMAIN>()) {
CINCH_CAPTURE() << "------- edge id: " << edge.id() << endl;
for(auto vertex : mesh->entities<0, $DOMAIN>(edge)) {
CINCH_CAPTURE() << "--- vertex id: " << vertex.id() << endl;
}
}
| 34.403509 | 68 | 0.529322 |
aef16175f836f498e1d48ed7f35241eb600ad19a | 1,860 | cpp | C++ | Paladin/BuildSystem/FileFactory.cpp | pahefu/Paladin | 4fcb66c6cda7bb50b7597532bd0d7469fc33655b | [
"MIT"
] | 45 | 2018-10-05T21:50:17.000Z | 2022-01-31T11:52:59.000Z | Paladin/BuildSystem/FileFactory.cpp | pahefu/Paladin | 4fcb66c6cda7bb50b7597532bd0d7469fc33655b | [
"MIT"
] | 163 | 2018-10-01T23:52:12.000Z | 2022-02-15T18:05:58.000Z | Paladin/BuildSystem/FileFactory.cpp | pahefu/Paladin | 4fcb66c6cda7bb50b7597532bd0d7469fc33655b | [
"MIT"
] | 9 | 2018-10-01T23:48:02.000Z | 2022-01-23T21:28:52.000Z | #include "FileFactory.h"
#include "DPath.h"
#include "SourceType.h"
#include "SourceTypeC.h"
#include "SourceTypeLex.h"
#include "SourceTypeLib.h"
#include "SourceTypeResource.h"
#include "SourceTypeRez.h"
#include "SourceTypeShell.h"
#include "SourceTypeText.h"
#include "SourceTypeYacc.h"
FileFactory gFileFactory;
FileFactory::FileFactory(void)
: fList(20,true)
{
LoadTypes();
}
void
FileFactory::LoadTypes(void)
{
// We have this method to update the types. If we had addons to support
// different types, we would be loading those here, too.
fList.AddItem(new SourceTypeC);
fList.AddItem(new SourceTypeLex);
fList.AddItem(new SourceTypeLib);
fList.AddItem(new SourceTypeResource);
fList.AddItem(new SourceTypeRez);
fList.AddItem(new SourceTypeShell);
fList.AddItem(new SourceTypeYacc);
fList.AddItem(new SourceTypeText);
}
SourceFile *
FileFactory::CreateSourceFileItem(const char *path)
{
if (!path)
return NULL;
DPath file(path);
for (int32 i = 0; i < fList.CountItems(); i++)
{
SourceType *item = fList.ItemAt(i);
if (item->HasExtension(file.GetExtension()))
return item->CreateSourceFileItem(path);
}
// The default source file class doesn't do anything significant
SourceFile *sourcefile = new SourceFile(path);
sourcefile->SetBuildFlag(BUILD_NO);
return sourcefile;
}
entry_ref
FileFactory::CreateSourceFile(const char *folder, const char *name, uint32 options)
{
DPath filename(name);
SourceType *type = FindTypeForExtension(filename.GetExtension());
if (!type)
return entry_ref();
return type->CreateSourceFile(folder, name, options);
}
SourceType *
FileFactory::FindTypeForExtension(const char *ext)
{
for (int32 i = 0; i < fList.CountItems(); i++)
{
SourceType *type = fList.ItemAt(i);
if (!type)
continue;
if (type->HasExtension(ext))
return type;
}
return NULL;
}
| 20.666667 | 83 | 0.73172 |
aef5cba87650b7ddc70acc522f6603139805e75e | 101 | hpp | C++ | exercises/4/seminar/8/Matrix/Matrix/utility.hpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 19 | 2020-02-21T16:46:50.000Z | 2022-01-26T19:59:49.000Z | exercises/4/seminar/9/Matrix/Matrix/utility.hpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 1 | 2020-03-14T08:09:45.000Z | 2020-03-14T08:09:45.000Z | exercises/4/seminar/8/Matrix - Complete/Matrix/utility.hpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 11 | 2020-02-23T12:29:58.000Z | 2021-04-11T08:30:12.000Z | #ifndef UTILITY
#define UTILITY
namespace utility {
int gcd(int a, int b);
}
#endif // !UTILITY | 12.625 | 26 | 0.673267 |
aef61af9e9f86157b2a0dd6386cbb49269321f3f | 2,670 | cpp | C++ | Interaction/albaAgentEventHandler.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | 9 | 2018-11-19T10:15:29.000Z | 2021-08-30T11:52:07.000Z | Interaction/albaAgentEventHandler.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Interaction/albaAgentEventHandler.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2018-06-10T22:56:29.000Z | 2019-12-12T06:22:56.000Z | /*=========================================================================
Program: Multimod Fundation Library
Module: $RCSfile: albaAgentEventHandler.cpp,v $
Language: C++
Date: $Date: 2006-06-14 14:46:33 $
Version: $Revision: 1.4 $
=========================================================================*/
#include "albaDefines.h" //SIL
#include "albaDecl.h"
#include "albaAgentEventHandler.h"
//----------------------------------------------------------------------------
// Constants
//----------------------------------------------------------------------------
enum DISPATCH_ENUM {ID_DISPATCH_EVENT = MINID};
enum WX_EVENT_ALBA { wxEVT_ALBA = 12000 /* SIL: wxEVT_USER_FIRST*/ + 1234 };
//----------------------------------------------------------------------------
class albaWXEventHandler:public wxEvtHandler
//----------------------------------------------------------------------------
{
protected:
virtual bool ProcessEvent(wxEvent& event);
public:
albaAgentEventHandler *m_Dispatcher;
};
//----------------------------------------------------------------------------
bool albaWXEventHandler::ProcessEvent(wxEvent& event)
//----------------------------------------------------------------------------
{
if (event.GetId()==ID_DISPATCH_EVENT)
{
if (m_Dispatcher)
{
m_Dispatcher->DispatchEvents();
}
}
return true;
}
//------------------------------------------------------------------------------
// Events
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
albaCxxTypeMacro(albaAgentEventHandler);
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
albaAgentEventHandler::albaAgentEventHandler()
//------------------------------------------------------------------------------
{
m_EventHandler = new albaWXEventHandler;
m_EventHandler->m_Dispatcher=this;
}
//------------------------------------------------------------------------------
albaAgentEventHandler::~albaAgentEventHandler()
//------------------------------------------------------------------------------
{
delete m_EventHandler;
//albaWarningMacro("Destroying albaAgentEventHandler");
}
//------------------------------------------------------------------------------
void albaAgentEventHandler::RequestForDispatching()
//------------------------------------------------------------------------------
{
wxIdleEvent wx_event;
wx_event.SetId(ID_DISPATCH_EVENT);
wxPostEvent(m_EventHandler,wx_event);
}
| 33.375 | 80 | 0.345693 |
aef6d7bb7d3fb685be390278a8c563fcd24b89ed | 223 | cpp | C++ | example/generate_word_example.cpp | arapelle/wgen | 53471bd78e7fd64c780f04cd132047e20abf254f | [
"MIT"
] | 1 | 2020-06-02T07:25:37.000Z | 2020-06-02T07:25:37.000Z | example/generate_word_example.cpp | arapelle/wgen | 53471bd78e7fd64c780f04cd132047e20abf254f | [
"MIT"
] | 6 | 2020-08-28T10:52:25.000Z | 2020-11-02T18:59:49.000Z | example/generate_word_example.cpp | arapelle/wgen | 53471bd78e7fd64c780f04cd132047e20abf254f | [
"MIT"
] | 1 | 2020-09-04T10:36:23.000Z | 2020-09-04T10:36:23.000Z | #include <wgen/default_syllabary.hpp>
#include <iostream>
int main()
{
wgen::default_syllabary syllabary;
std::string word = syllabary.random_word(7);
std::cout << word << std::endl;
return EXIT_SUCCESS;
}
| 20.272727 | 48 | 0.686099 |
aef727bef065101b0d3865e6feab392a7533689b | 4,240 | cpp | C++ | tests/test_basic_parsing.cpp | dlrobertson/warc-c | 9c94e4f4514b71d3c87df376d7687f92c1082b34 | [
"MIT"
] | 2 | 2018-07-22T11:10:20.000Z | 2018-09-01T01:39:01.000Z | tests/test_basic_parsing.cpp | dlrobertson/warc-c | 9c94e4f4514b71d3c87df376d7687f92c1082b34 | [
"MIT"
] | null | null | null | tests/test_basic_parsing.cpp | dlrobertson/warc-c | 9c94e4f4514b71d3c87df376d7687f92c1082b34 | [
"MIT"
] | null | null | null | // Copyright (c) 2018 Daniel L. Robertson
//
// 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 <cstdio>
#include <gtest/gtest.h>
extern "C" {
#include <warc-c/warc-c.h>
}
#include "util.hpp"
TEST(SimpleWarcFile, first) {
struct warc_file *file = NULL;
struct warc_file_entry *node = NULL;
struct warc_entry *entry = NULL;
struct warc_header *header = NULL;
FILE *f = fopen(TEST_FILES_EXAMPLES "/test.warc", "r");
int i = 0;
file = warc_parse_file(f, 1);
FOREACH_ENTRY(file, node) {
++i;
if (i == 0) {
ASSERT_TRUE(node);
entry = warc_file_entry_item(node);
ASSERT_TRUE(entry != NULL);
ASSERT_EQ(entry->version.major, 1);
ASSERT_EQ(entry->version.minor, 0);
// First Header
header = warc_headers_find(&entry->headers, "Something");
ASSERT_TRUE(header);
ASSERT_EQ(strcmp(header->name, "Something"), 0);
ASSERT_EQ(strncmp((const char *)header->value->bytes, "Else", header->value->len), 0);
// Second Header
header = warc_headers_find(&entry->headers, "And0");
ASSERT_TRUE(header);
ASSERT_EQ(strcmp(header->name, "And0"), 0);
ASSERT_FALSE(header->value);
// Third Header
header = warc_headers_find(&entry->headers, "And1");
ASSERT_TRUE(header);
ASSERT_EQ(strcmp(header->name, "And1"), 0);
ASSERT_EQ(
strncmp((const char *)header->value->bytes, "Multiple\r\n Lines", header->value->len), 0);
// Not a header
header = warc_headers_find(&entry->headers, "Not Found");
ASSERT_FALSE(header);
// Check the block
ASSERT_TRUE(entry->block);
ASSERT_EQ(strncmp((const char *)entry->block->bytes, "Hello,\r\nWorld!", entry->block->len),
0);
} else if (i == 1) {
ASSERT_TRUE(node);
entry = warc_file_entry_item(node);
ASSERT_TRUE(entry != NULL);
ASSERT_EQ(entry->version.major, 1);
ASSERT_EQ(entry->version.minor, 0);
// First Header
header = warc_headers_find(&entry->headers, "Wait");
ASSERT_TRUE(header);
ASSERT_EQ(strcmp(header->name, "Wait"), 0);
ASSERT_EQ(strncmp((const char *)header->value->bytes, "There", header->value->len), 0);
// Check the block
ASSERT_TRUE(entry->block);
ASSERT_EQ(strncmp((const char *)entry->block->bytes, "Is another entry!", entry->block->len),
0);
}
}
ASSERT_EQ(i, 2);
warc_file_free(file);
}
TEST(SimpleWarcFile, bbc) {
struct warc_entry *entry = NULL;
struct warc_file *file = NULL;
struct warc_file_entry *node = NULL;
struct warc_header *header = NULL;
FILE *f = fopen(TEST_FILES_EXAMPLES "/bbc.warc", "r");
int i = 0;
file = warc_parse_file(f, 0);
FOREACH_ENTRY(file, node) {
++i;
entry = warc_file_entry_item(node);
ASSERT_TRUE(entry != NULL);
ASSERT_EQ(entry->version.major, 1);
ASSERT_EQ(entry->version.minor, 0);
// First Header
header = warc_headers_find(&entry->headers, "WARC-Type");
ASSERT_TRUE(header);
ASSERT_EQ(strcmp(header->name, "WARC-Type"), 0);
ASSERT_EQ(strncmp((const char *)header->value->bytes, "response", header->value->len), 0);
}
ASSERT_EQ(i, 1);
warc_file_free(file);
}
| 35.041322 | 100 | 0.663679 |
aef7bda9a1cd6340cd0896868149deadd2a1165b | 4,959 | cxx | C++ | Servers/Filters/vtkPVExtractSelection.cxx | certik/paraview | 973d37b466552ce770ac0674f30040bb7e31d7fe | [
"BSD-3-Clause"
] | 1 | 2016-05-09T00:36:44.000Z | 2016-05-09T00:36:44.000Z | Servers/Filters/vtkPVExtractSelection.cxx | certik/paraview | 973d37b466552ce770ac0674f30040bb7e31d7fe | [
"BSD-3-Clause"
] | null | null | null | Servers/Filters/vtkPVExtractSelection.cxx | certik/paraview | 973d37b466552ce770ac0674f30040bb7e31d7fe | [
"BSD-3-Clause"
] | 3 | 2015-05-14T21:18:53.000Z | 2022-03-07T02:53:45.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: vtkPVExtractSelection.cxx,v $
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkPVExtractSelection.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkSelection.h"
#include "vtkDataObjectTypes.h"
#include "vtkDataSet.h"
#include "vtkIdTypeArray.h"
#include "vtkCellData.h"
#include "vtkPointData.h"
vtkCxxRevisionMacro(vtkPVExtractSelection, "$Revision: 1.6 $");
vtkStandardNewMacro(vtkPVExtractSelection);
//----------------------------------------------------------------------------
vtkPVExtractSelection::vtkPVExtractSelection()
{
this->SetNumberOfOutputPorts(2);
}
//----------------------------------------------------------------------------
vtkPVExtractSelection::~vtkPVExtractSelection()
{
}
//----------------------------------------------------------------------------
int vtkPVExtractSelection::FillOutputPortInformation(
int port, vtkInformation* info)
{
if (port==0)
{
info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkDataSet");
}
else
{
info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkSelection");
}
return 1;
}
//----------------------------------------------------------------------------
int vtkPVExtractSelection::RequestDataObject(
vtkInformation* request,
vtkInformationVector** inputVector ,
vtkInformationVector* outputVector)
{
if (!this->Superclass::RequestDataObject(request, inputVector, outputVector))
{
return 0;
}
vtkInformation* info = outputVector->GetInformationObject(1);
vtkSelection *selOut = vtkSelection::SafeDownCast(
info->Get(vtkDataObject::DATA_OBJECT()));
if (!selOut || !selOut->IsA("vtkSelection"))
{
vtkDataObject* newOutput =
vtkDataObjectTypes::NewDataObject("vtkSelection");
if (!newOutput)
{
vtkErrorMacro("Could not create vtkSelectionOutput");
return 0;
}
newOutput->SetPipelineInformation(info);
this->GetOutputPortInformation(1)->Set(
vtkDataObject::DATA_EXTENT_TYPE(), newOutput->GetExtentType());
newOutput->Delete();
}
return 1;
}
//----------------------------------------------------------------------------
int vtkPVExtractSelection::RequestData(
vtkInformation* request,
vtkInformationVector** inputVector ,
vtkInformationVector* outputVector)
{
if (!this->Superclass::RequestData(request, inputVector, outputVector))
{
return 0;
}
vtkSelection* sel = 0;
if (inputVector[1]->GetInformationObject(0))
{
sel = vtkSelection::SafeDownCast(
inputVector[1]->GetInformationObject(0)->Get(
vtkDataObject::DATA_OBJECT()));
}
vtkDataSet *geomOutput = vtkDataSet::SafeDownCast(
outputVector->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()));
//make an ids selection for the second output
//we can do this because all of the extractSelectedX filters produce
//arrays called "vtkOriginalXIds" that record what input cells produced
//each output cell, at least as long as PRESERVE_TOPOLOGY is off
//when we start allowing PreserveTopology, this will have to instead run
//through the vtkInsidedNess arrays, and for every on entry, record the
//entries index
vtkSelection *output = vtkSelection::SafeDownCast(
outputVector->GetInformationObject(1)->Get(vtkDataObject::DATA_OBJECT()));
output->Clear();
output->SetContentType(vtkSelection::INDICES);
int ft = vtkSelection::CELL;
if (sel && sel->GetProperties()->Has(vtkSelection::FIELD_TYPE()))
{
ft = sel->GetProperties()->Get(vtkSelection::FIELD_TYPE());
}
output->GetProperties()->Set(vtkSelection::FIELD_TYPE(), ft);
int inv = 0;
if (sel && sel->GetProperties()->Has(vtkSelection::INVERSE()))
{
inv = sel->GetProperties()->Get(vtkSelection::INVERSE());
}
output->GetProperties()->Set(vtkSelection::INVERSE(), inv);
vtkIdTypeArray *oids;
if (ft == vtkSelection::CELL)
{
oids = vtkIdTypeArray::SafeDownCast(
geomOutput->GetCellData()->GetArray("vtkOriginalCellIds"));
}
else
{
oids = vtkIdTypeArray::SafeDownCast(
geomOutput->GetPointData()->GetArray("vtkOriginalPointIds"));
}
if (oids)
{
output->SetSelectionList(oids);
}
return 1;
}
//----------------------------------------------------------------------------
void vtkPVExtractSelection::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
| 30.801242 | 79 | 0.623916 |
aef9062544f15dafcdc59c157db3412d0115a026 | 117 | cpp | C++ | src/main.cpp | tcaron01/opengl_template | 86ec3aaa1f42cfb02886a87213c0471b8fe26fe0 | [
"Unlicense"
] | null | null | null | src/main.cpp | tcaron01/opengl_template | 86ec3aaa1f42cfb02886a87213c0471b8fe26fe0 | [
"Unlicense"
] | null | null | null | src/main.cpp | tcaron01/opengl_template | 86ec3aaa1f42cfb02886a87213c0471b8fe26fe0 | [
"Unlicense"
] | null | null | null | #include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include "../include/test.hpp"
int main() {
return test();
} | 14.625 | 30 | 0.606838 |
aefa1c5a9c4ac52d9bcad3863423a1e077dad6ea | 1,281 | hpp | C++ | db/DBAppender.hpp | naivewong/timeunion | 8070492d2c6a2d68175e7d026c27b858c2aec8e6 | [
"Apache-2.0"
] | null | null | null | db/DBAppender.hpp | naivewong/timeunion | 8070492d2c6a2d68175e7d026c27b858c2aec8e6 | [
"Apache-2.0"
] | null | null | null | db/DBAppender.hpp | naivewong/timeunion | 8070492d2c6a2d68175e7d026c27b858c2aec8e6 | [
"Apache-2.0"
] | null | null | null | #ifndef DBAPPENDER_H
#define DBAPPENDER_H
#include "db/AppenderInterface.hpp"
#include "db/DB.hpp"
#include "leveldb/status.h"
namespace tsdb {
namespace db {
// DBAppender wraps the DB's head appender and triggers compactions on commit
// if necessary.
class DBAppender : public AppenderInterface {
private:
std::unique_ptr<db::AppenderInterface> app;
db::DB *db;
public:
DBAppender(std::unique_ptr<db::AppenderInterface> &&app, db::DB *db)
: app(std::move(app)), db(db) {}
std::pair<uint64_t, leveldb::Status> add(const label::Labels &lset, int64_t t,
double v) {
return app->add(lset, t, v);
}
leveldb::Status add_fast(uint64_t ref, int64_t t, double v) {
return app->add_fast(ref, t, v);
}
leveldb::Status commit() {
leveldb::Status err = app->commit();
// We could just run this check every few minutes practically. But for
// benchmarks and high frequency use cases this is the safer way.
if (db->head()->MaxTime() - db->head()->MinTime() >
db->head()->chunk_range / 2 * 3) {
db->compact_channel()->send(0);
}
return err;
}
leveldb::Status rollback() { return app->rollback(); }
~DBAppender() {}
};
} // namespace db
} // namespace tsdb
#endif | 25.62 | 80 | 0.637002 |
aefc07f39c103d371a4369ef6ae901d4e0e2a91f | 1,473 | cpp | C++ | engine/mysqlparser/listener/SqlErrorListener.cpp | zhukovaskychina/XSQL | f91db06bf86f7f6ad321722c3aea11f83d34dba1 | [
"MIT"
] | 1 | 2020-10-23T09:38:22.000Z | 2020-10-23T09:38:22.000Z | engine/mysqlparser/listener/SqlErrorListener.cpp | zhukovaskychina/XSQL | f91db06bf86f7f6ad321722c3aea11f83d34dba1 | [
"MIT"
] | null | null | null | engine/mysqlparser/listener/SqlErrorListener.cpp | zhukovaskychina/XSQL | f91db06bf86f7f6ad321722c3aea11f83d34dba1 | [
"MIT"
] | null | null | null | //
// Created by zhukovasky on 2020/9/30.
//
#include <common/Exceptions.h>
#include "SqlErrorListener.h"
SQLErrorListener::~SQLErrorListener() {
}
void SQLErrorListener::syntaxError(antlr4::Recognizer *recognizer, antlr4::Token *offendingSymbol, size_t line,
size_t charPositionInLine, const std::string &msg, std::exception_ptr e) {
std::cerr<<"语法解析异常:"<<msg<<std::endl;
throw SyntaxParseException(msg);
// throw MySQLErrorCode ::ER_PARSE_ERROR;
}
void SQLErrorListener::reportAmbiguity(antlr4::Parser *recognizer, const antlr4::dfa::DFA &dfa, size_t startIndex,
size_t stopIndex, bool exact, const antlrcpp::BitSet &ambigAlts,
antlr4::atn::ATNConfigSet *configs) {
}
void SQLErrorListener::reportAttemptingFullContext(antlr4::Parser *recognizer, const antlr4::dfa::DFA &dfa,
size_t startIndex, size_t stopIndex,
const antlrcpp::BitSet &conflictingAlts,
antlr4::atn::ATNConfigSet *configs) {
}
void
SQLErrorListener::reportContextSensitivity(antlr4::Parser *recognizer, const antlr4::dfa::DFA &dfa, size_t startIndex,
size_t stopIndex, size_t prediction, antlr4::atn::ATNConfigSet *configs) {
}
SQLErrorListener::SQLErrorListener() {
}
| 34.255814 | 118 | 0.604888 |
aefc2e747d34818630c7f0d8f2d53317886ac392 | 3,739 | cpp | C++ | Testing/Gui/16_testRWI/testRWILogic.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | 9 | 2018-11-19T10:15:29.000Z | 2021-08-30T11:52:07.000Z | Testing/Gui/16_testRWI/testRWILogic.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Testing/Gui/16_testRWI/testRWILogic.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2018-06-10T22:56:29.000Z | 2019-12-12T06:22:56.000Z | /*=========================================================================
Program: ALBA (Agile Library for Biomedical Applications)
Module: testRWILogic
Authors: Silvano Imboden
Copyright (c) BIC
All rights reserved. See Copyright.txt or
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 "albaDefines.h"
//----------------------------------------------------------------------------
// NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first.
// This force to include Window,wxWidgets and VTK exactly in this order.
// Failing in doing this will result in a run-time error saying:
// "Failure#0: The value of ESP was not properly saved across a function call"
//----------------------------------------------------------------------------
#include "testRWILogic.h"
#include "albaDecl.h"
#include "albaGUI.h"
#include "testRWIBaseDlg.h"
#include "testRWIDlg.h"
//--------------------------------------------------------------------------------
//const:
//--------------------------------------------------------------------------------
enum
{
ID_D1 = MINID,
ID_D2,
ID_D3,
};
//--------------------------------------------------------------------------------
testRWILogic::testRWILogic()
//--------------------------------------------------------------------------------
{
/**todo: PAOLO please read here */
// RESULT OF RWI TEST :
// RWIBASE produce a memory leak 5600 byte long, as follow -- by me (Silvano) this is not considered an error but a feature :-)
// C:\Program Files\VisualStudio7\Vc7\include\crtdbg.h(689) : {2804} normal block at 0x099C00A8, 5600 bytes long.
// Data: < Buil> 00 00 00 00 00 00 00 00 00 00 00 00 42 75 69 6C
// Object dump complete.
// the leaks is always 5600 bytes long, doesn't matter how many instances of RWI you have created,
// so maybe it is related to something concerned with the initialization of the OpenGL context,
// and the real problem could be in my NVidia OpenGL Driver
m_win = new wxFrame(NULL,-1,"TestRWI",wxDefaultPosition,wxDefaultSize,
wxMINIMIZE_BOX | wxMAXIMIZE_BOX | /*wxRESIZE_BORDER |*/ wxSYSTEM_MENU | wxCAPTION );
albaSetFrame(m_win);
albaGUI *gui = new albaGUI(this);
gui->Divider();
gui->Label("Examples of VTK RenderWindow");
gui->Button(ID_D1,"test RWIBase");
gui->Button(ID_D2,"test RWI");
gui->Label("");
gui->Label("");
gui->Button(ID_D3,"quit");
gui->Reparent(m_win);
m_win->Fit(); // resize m_win to fit it's content
}
//--------------------------------------------------------------------------------
testRWILogic::~testRWILogic()
//--------------------------------------------------------------------------------
{
}
//--------------------------------------------------------------------------------
void testRWILogic::OnEvent(albaEventBase *alba_event)
//--------------------------------------------------------------------------------
{
if (albaEvent *e = albaEvent::SafeDownCast(alba_event))
{
switch(e->GetId())
{
case ID_D1:
{
testRWIBaseDlg d("test RWIBase");
d.ShowModal();
}
break;
case ID_D2:
{
testRWIDlg d("test RWI");
d.ShowModal();
}
break;
case ID_D3:
m_win->Destroy();
break;
}
}
}
//--------------------------------------------------------------------------------
void testRWILogic::Show()
//--------------------------------------------------------------------------------
{
m_win->Show(true);
}
| 33.088496 | 129 | 0.472319 |
aefc38192acba82870d5413f54a656d15199680b | 511 | cpp | C++ | problems/acmicpc_14935.cpp | qawbecrdtey/BOJ-sol | e3f410e8f4e3a6ade51b68ce2024529870edac64 | [
"MIT"
] | null | null | null | problems/acmicpc_14935.cpp | qawbecrdtey/BOJ-sol | e3f410e8f4e3a6ade51b68ce2024529870edac64 | [
"MIT"
] | null | null | null | problems/acmicpc_14935.cpp | qawbecrdtey/BOJ-sol | e3f410e8f4e3a6ade51b68ce2024529870edac64 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
using namespace std;
void f(string &s,int x){
if(x<10){s.push_back(x+'0');return;}
f(s,x/10);
s.push_back(x%10+'0');
}
int main(){
string s;
cin>>s;
vector<string> v;
while(true){
for(auto str:v){
if(s==str)goto A;
}
v.push_back(s);
int x=(s[0]-'0')*(s.length());
string t;
f(t,x);
if(s==t)goto B;
s=t;
}
A: printf("N");
B: printf("FA");
} | 18.925926 | 40 | 0.471624 |
4e033a2418992d27b732cbcf8e73193025f3b40a | 1,521 | cpp | C++ | src/gpio_test.cpp | gbr1/upboard_ros | a4fd1ce54fc78724bcdfde5b09185feeca71225d | [
"MIT"
] | 24 | 2019-05-10T11:48:40.000Z | 2022-03-29T08:52:08.000Z | src/gpio_test.cpp | gbr1/upboard_ros | a4fd1ce54fc78724bcdfde5b09185feeca71225d | [
"MIT"
] | 1 | 2020-07-08T04:20:17.000Z | 2020-07-08T09:33:36.000Z | src/gpio_test.cpp | gbr1/upboard_ros | a4fd1ce54fc78724bcdfde5b09185feeca71225d | [
"MIT"
] | 1 | 2019-05-11T23:44:33.000Z | 2019-05-11T23:44:33.000Z | #include <ros/ros.h>
#include <upboard_ros/Gpio.h>
#include <upboard_ros/ListGpio.h>
#define BUTTON 24
#define LED 22
#define SLOW 1.0
#define FAST 0.2
upboard_ros::Gpio tmp_msg;
upboard_ros::ListGpio list_msg;
bool status=false;
ros::Time tp;
float blinkrate=SLOW;
ros::Publisher gpiopub;
void gpioCallback(const upboard_ros::ListGpio & msg){
int k=0;
bool found=false;
while((!found) && (k<msg.gpio.size())){
if (msg.gpio[k].pin==BUTTON){
found=true;
if (msg.gpio[k].value==0){
blinkrate=FAST;
}
else{
blinkrate=SLOW;
}
}
k++;
}
}
void blink(){
ros::Duration d=ros::Time::now()-tp;
if (d.toSec()>=blinkrate){
//create a message to turn on led on pin 22
tmp_msg.pin=22;
status=!status;
tmp_msg.value=status;
//add to list
list_msg.gpio.push_back(tmp_msg);
list_msg.header.stamp=ros::Time::now();
gpiopub.publish(list_msg);
list_msg.gpio.clear();
tp=ros::Time::now();
}
}
int main(int argc, char **argv){
ros::init(argc, argv, "gpio_test");
ros::NodeHandle nh;
gpiopub = nh.advertise<upboard_ros::ListGpio>("/upboard/gpio/write",10);
ros::Subscriber gpiosub = nh.subscribe("/upboard/gpio/read", 10, gpioCallback);
tp=ros::Time::now();
ros::Rate rate(100);
while (ros::ok){
blink();
ros::spinOnce();
rate.sleep();
}
} | 21.728571 | 83 | 0.565417 |
4e04a96449d7fcfc5f8e2e4005cf183d6c657597 | 8,476 | cpp | C++ | Testing/VME/mafPipeVolumeSliceTest.cpp | FusionBox2/MAF2 | b576955f4f6b954467021f12baedfebcaf79a382 | [
"Apache-2.0"
] | 1 | 2018-01-23T09:13:40.000Z | 2018-01-23T09:13:40.000Z | Testing/VME/mafPipeVolumeSliceTest.cpp | gradicosmo/MAF2 | 86ddf1f52a2de4479c09fd3f43dc321ff412af42 | [
"Apache-2.0"
] | null | null | null | Testing/VME/mafPipeVolumeSliceTest.cpp | gradicosmo/MAF2 | 86ddf1f52a2de4479c09fd3f43dc321ff412af42 | [
"Apache-2.0"
] | 3 | 2020-09-24T16:04:53.000Z | 2020-09-24T16:50:30.000Z | /*=========================================================================
Program: MAF2
Module: mafPipeVolumeSliceTest
Authors: Matteo Giacomoni
Copyright (c) B3C
All rights reserved. See Copyright.txt or
http://www.scsitaly.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "mafDefines.h"
//----------------------------------------------------------------------------
// NOTE: Every CPP file in the MAF must include "mafDefines.h" as first.
// This force to include Window,wxWidgets and VTK exactly in this order.
// Failing in doing this will result in a run-time error saying:
// "Failure#0: The value of ESP was not properly saved across a function call"
//----------------------------------------------------------------------------
#include <cppunit/config/SourcePrefix.h>
#include "mafPipeVolumeSliceTest.h"
#include "mafPipeVolumeSlice.h"
#include "mafSceneNode.h"
#include "mafVMEVolumeGray.h"
#include "mmaVolumeMaterial.h"
#include "vtkMAFAssembly.h"
#include "vtkMapper.h"
#include "vtkJPEGWriter.h"
#include "vtkJPEGReader.h"
#include "vtkWindowToImageFilter.h"
#include "vtkImageMathematics.h"
#include "vtkImageData.h"
#include "vtkPointData.h"
#include "vtkStructuredPointsReader.h"
#include "vtkCamera.h"
// render window stuff
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include <iostream>
#include <fstream>
enum PIPE_BOX_ACTORS
{
PIPE_BOX_ACTOR,
PIPE_BOX_ACTOR_WIRED,
PIPE_BOX_ACTOR_OUTLINE_CORNER,
PIPE_BOX_NUMBER_OF_ACTORS,
};
//----------------------------------------------------------------------------
void mafPipeVolumeSliceTest::TestFixture()
//----------------------------------------------------------------------------
{
}
//----------------------------------------------------------------------------
void mafPipeVolumeSliceTest::setUp()
//----------------------------------------------------------------------------
{
vtkNEW(m_Renderer);
vtkNEW(m_RenderWindow);
vtkNEW(m_RenderWindowInteractor);
}
//----------------------------------------------------------------------------
void mafPipeVolumeSliceTest::tearDown()
//----------------------------------------------------------------------------
{
vtkDEL(m_Renderer);
vtkDEL(m_RenderWindow);
vtkDEL(m_RenderWindowInteractor);
}
//----------------------------------------------------------------------------
void mafPipeVolumeSliceTest::TestPipeExecution()
//----------------------------------------------------------------------------
{
///////////////// render stuff /////////////////////////
m_Renderer->SetBackground(0.1, 0.1, 0.1);
m_RenderWindow->AddRenderer(m_Renderer);
m_RenderWindow->SetSize(640, 480);
m_RenderWindow->SetPosition(200,0);
m_RenderWindowInteractor->SetRenderWindow(m_RenderWindow);
///////////// end render stuff /////////////////////////
////// Create VME (import vtkData) ////////////////////
vtkStructuredPointsReader *importer;
vtkNEW(importer);
mafString filename1=MAF_DATA_ROOT;
filename1<<"/Test_PipeVolumeSlice/VolumeSP.vtk";
importer->SetFileName(filename1.GetCStr());
importer->Update();
mafVMEVolumeGray *volumeInput;
mafNEW(volumeInput);
volumeInput->SetData((vtkImageData*)importer->GetOutput(),0.0);
volumeInput->GetOutput()->GetVTKData()->Update();
volumeInput->GetOutput()->Update();
volumeInput->Update();
mmaVolumeMaterial *material;
mafNEW(material);
mafVMEOutputVolume::SafeDownCast(volumeInput->GetOutput())->SetMaterial(material);
//Assembly will be create when instancing mafSceneNode
mafSceneNode *sceneNode;
sceneNode = new mafSceneNode(NULL,NULL,volumeInput, NULL);
double zValue[3][3]={{4.0,4.0,0.0},{4.0,4.0,1.0},{4.0,4.0,2.0}};
for (int direction = SLICE_X ; direction<=SLICE_Z;direction++)
{
/////////// Pipe Instance and Creation ///////////
mafPipeVolumeSlice *pipeSlice = new mafPipeVolumeSlice;
pipeSlice->InitializeSliceParameters(direction,zValue[0],true);
pipeSlice->Create(sceneNode);
////////// ACTORS List ///////////////
vtkPropCollection *actorList = vtkPropCollection::New();
pipeSlice->GetAssemblyFront()->GetActors(actorList);
actorList->InitTraversal();
vtkProp *actor = actorList->GetNextProp();
while(actor)
{
m_Renderer->AddActor(actor);
m_RenderWindow->Render();
actor = actorList->GetNextProp();
}
double x,y,z,vx,vy,vz;
switch(direction)
{
case SLICE_X:
//x=-1 ;y=0; z=0; vx=0; vy=0; vz=1;
x=1 ;y=0; z=0; vx=0; vy=0; vz=1;
break;
case SLICE_Y:
x=0; y=-1; z=0; vx=0; vy=0; vz=1;
break;
case SLICE_Z:
//x=0; y=0; z=-1; vx=0; vy=-1; vz=0;
x=0; y=0; z=-1; vx=0; vy=-1; vz=0;
break;
}
m_Renderer->GetActiveCamera()->ParallelProjectionOn();
m_Renderer->GetActiveCamera()->SetFocalPoint(0,0,0);
m_Renderer->GetActiveCamera()->SetPosition(x*100,y*100,z*100);
m_Renderer->GetActiveCamera()->SetViewUp(vx,vy,vz);
m_Renderer->GetActiveCamera()->SetClippingRange(0.1,1000);
for(int i=0;i<3;i++)
{
pipeSlice->SetSlice(zValue[i]);
m_Renderer->ResetCamera();
char *strings="Slice";
m_RenderWindow->Render();
printf("\n Visualization: %s \n", strings);
mafSleep(1000);
CompareImages(3*direction+i);
}
m_Renderer->RemoveAllProps();
vtkDEL(actorList);
delete pipeSlice;
}
delete sceneNode;
mafDEL(material);
mafDEL(volumeInput);
vtkDEL(importer);
delete wxLog::SetActiveTarget(NULL);
}
//----------------------------------------------------------------------------
void mafPipeVolumeSliceTest::CompareImages(int imageIndex)
//----------------------------------------------------------------------------
{
char *file = __FILE__;
std::string name(file);
int slashIndex = name.find_last_of('\\');
name = name.substr(slashIndex+1);
int pointIndex = name.find_last_of('.');
name = name.substr(0, pointIndex);
mafString controlOriginFile=MAF_DATA_ROOT;
controlOriginFile<<"/Test_PipeVolumeSlice/";
controlOriginFile<<name.c_str();
controlOriginFile<<"_";
controlOriginFile<<"image";
controlOriginFile<<imageIndex;
controlOriginFile<<".jpg";
fstream controlStream;
controlStream.open(controlOriginFile.GetCStr());
// visualization control
m_RenderWindow->OffScreenRenderingOn();
vtkWindowToImageFilter *w2i;
vtkNEW(w2i);
w2i->SetInput(m_RenderWindow);
//w2i->SetMagnification(magnification);
w2i->Update();
m_RenderWindow->OffScreenRenderingOff();
//write comparing image
vtkJPEGWriter *w;
vtkNEW(w);
w->SetInput(w2i->GetOutput());
mafString imageFile=MAF_DATA_ROOT;
if(!controlStream)
{
imageFile<<"/Test_PipeVolumeSlice/";
imageFile<<name.c_str();
imageFile<<"_";
imageFile<<"image";
}
else
{
imageFile<<"/Test_PipeVolumeSlice/";
imageFile<<name.c_str();
imageFile<<"_";
imageFile<<"comp";
}
imageFile<<imageIndex;
imageFile<<".jpg";
w->SetFileName(imageFile.GetCStr());
w->Write();
if(!controlStream)
{
vtkDEL(w);
vtkDEL(w2i);
controlStream.close();
return;
}
controlStream.close();
//read original Image
vtkJPEGReader *rO;
vtkNEW(rO);
mafString imageFileOrig=MAF_DATA_ROOT;
imageFileOrig<<"/Test_PipeVolumeSlice/";
imageFileOrig<<name.c_str();
imageFileOrig<<"_";
imageFileOrig<<"image";
imageFileOrig<<imageIndex;
imageFileOrig<<".jpg";
rO->SetFileName(imageFileOrig.GetCStr());
rO->Update();
vtkImageData *imDataOrig = rO->GetOutput();
//read compared image
vtkJPEGReader *rC;
vtkNEW(rC);
rC->SetFileName(imageFile.GetCStr());
rC->Update();
vtkImageData *imDataComp = rC->GetOutput();
vtkImageMathematics *imageMath;
vtkNEW(imageMath);
imageMath->SetInput1(imDataOrig);
imageMath->SetInput2(imDataComp);
imageMath->SetOperationToSubtract();
imageMath->Update();
double srR[2] = {-1,1};
imageMath->GetOutput()->GetPointData()->GetScalars()->GetRange(srR);
CPPUNIT_ASSERT(srR[0] == 0.0 && srR[1] == 0.0);
// end visualization control
vtkDEL(imageMath);
vtkDEL(rC);
vtkDEL(rO);
vtkDEL(w);
vtkDEL(w2i);
} | 27.254019 | 84 | 0.597452 |
4e05c6ff8543a5859c72437968dd4af1e056ef18 | 253 | cpp | C++ | server/src/DatabaseProxy/PostgresqlProxy.cpp | yuryloshmanov/messenger | 98c2129cf2b5ca7e00cc5c1ba90535acf8be0ba1 | [
"MIT"
] | null | null | null | server/src/DatabaseProxy/PostgresqlProxy.cpp | yuryloshmanov/messenger | 98c2129cf2b5ca7e00cc5c1ba90535acf8be0ba1 | [
"MIT"
] | null | null | null | server/src/DatabaseProxy/PostgresqlProxy.cpp | yuryloshmanov/messenger | 98c2129cf2b5ca7e00cc5c1ba90535acf8be0ba1 | [
"MIT"
] | null | null | null | /**
* @file PostgresqlProxy.cpp
* @date 22 Feb 2022
* @author Yury Loshmanov
*/
#include "../../include/DatabaseProxy/PostgresqlProxy.hpp"
PostgresqlProxy::PostgresqlProxy(const std::string &endPoint) : connection(endPoint), work(connection) {
}
| 21.083333 | 104 | 0.72332 |
4e0c4243efa6ca0642bb4260c4daefdd7c40cd75 | 5,578 | cpp | C++ | Oem/dbxml/xqilla/src/ast/XQAttributeConstructor.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 2 | 2017-04-19T01:38:30.000Z | 2020-07-31T03:05:32.000Z | Oem/dbxml/xqilla/src/ast/XQAttributeConstructor.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | null | null | null | Oem/dbxml/xqilla/src/ast/XQAttributeConstructor.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 1 | 2021-12-29T10:46:12.000Z | 2021-12-29T10:46:12.000Z | /*
* Copyright (c) 2001-2008
* DecisionSoft Limited. All rights reserved.
* Copyright (c) 2004-2008
* Oracle. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* $Id$
*/
#include <xqilla/framework/XQillaExport.hpp>
#include <xqilla/ast/XQAttributeConstructor.hpp>
#include <xqilla/ast/StaticAnalysis.hpp>
#include <xqilla/ast/XQLiteral.hpp>
#include <xqilla/context/DynamicContext.hpp>
#include <xqilla/context/ItemFactory.hpp>
#include <xqilla/exceptions/ASTException.hpp>
#include <xqilla/exceptions/NamespaceLookupException.hpp>
#include <xqilla/exceptions/StaticErrorException.hpp>
#include <xqilla/utils/XPath2Utils.hpp>
#include <xqilla/utils/XPath2NSUtils.hpp>
#include <xqilla/items/Node.hpp>
#include <xqilla/ast/XQAtomize.hpp>
#include <xqilla/events/EventHandler.hpp>
#include <xqilla/exceptions/StaticErrorException.hpp>
#include <xercesc/validators/schema/SchemaSymbols.hpp>
#include <xercesc/framework/XMLBuffer.hpp>
#include <xercesc/util/XMLChar.hpp>
#if defined(XERCES_HAS_CPP_NAMESPACE)
XERCES_CPP_NAMESPACE_USE
#endif
XQAttributeConstructor::XQAttributeConstructor(ASTNode* name, VectorOfASTNodes* children, XPath2MemoryManager* mm)
: XQDOMConstructor(mm),
namespaceExpr(0),
m_name(name),
m_children(children)
{
}
EventGenerator::Ptr XQAttributeConstructor::generateEvents(EventHandler *events, DynamicContext *context,
bool preserveNS, bool preserveType) const
{
AnyAtomicType::Ptr itemName = m_name->createResult(context)->next(context);
const ATQNameOrDerived* pQName = (const ATQNameOrDerived*)itemName.get();
const XMLCh *prefix = pQName->getPrefix();
const XMLCh *uri = pQName->getURI();
const XMLCh *name = pQName->getName();
if((uri==NULL && XPath2Utils::equals(name, XMLUni::fgXMLNSString)) ||
XPath2Utils::equals(uri, XMLUni::fgXMLNSURIName))
XQThrow(ASTException,X("DOM Constructor"),X("A computed attribute constructor cannot create a namespace declaration [err:XQDY0044]"));
XMLBuffer value;
getStringValue(m_children, value, context);
const XMLCh *typeURI = SchemaSymbols::fgURI_SCHEMAFORSCHEMA;
const XMLCh *typeName = ATUntypedAtomic::fgDT_UNTYPEDATOMIC;
// check if it's xml:id
static const XMLCh id[] = { 'i', 'd', 0 };
if(XPath2Utils::equals(name, id) && XPath2Utils::equals(uri, XMLUni::fgXMLURIName)) {
// If the attribute name is xml:id, the string value and typed value of the attribute are further normalized by
// discarding any leading and trailing space (#x20) characters, and by replacing sequences of space (#x20) characters
// by a single space (#x20) character.
XMLString::collapseWS(value.getRawBuffer(), context->getMemoryManager());
typeURI = SchemaSymbols::fgURI_SCHEMAFORSCHEMA;
typeName = XMLUni::fgIDString;
}
events->attributeEvent(emptyToNull(prefix), emptyToNull(uri), name, value.getRawBuffer(), typeURI, typeName);
return 0;
}
ASTNode* XQAttributeConstructor::staticResolution(StaticContext *context)
{
XPath2MemoryManager *mm = context->getMemoryManager();
// and run static resolution
m_name = new (mm) XQNameExpression(m_name, mm);
m_name->setLocationInfo(this);
m_name = m_name->staticResolution(context);
unsigned int i;
for(i = 0;i < m_children->size(); ++i) {
// atomize content and run static resolution
(*m_children)[i] = new (mm) XQAtomize((*m_children)[i], mm);
(*m_children)[i]->setLocationInfo(this);
(*m_children)[i] = (*m_children)[i]->staticResolution(context);
}
return this;
}
ASTNode *XQAttributeConstructor::staticTypingImpl(StaticContext *context)
{
_src.clear();
_src.add(m_name->getStaticAnalysis());
if(m_name->getStaticAnalysis().isUpdating()) {
XQThrow(StaticErrorException,X("XQAttributeConstructor::staticTyping"),
X("It is a static error for the name expression of an attribute constructor "
"to be an updating expression [err:XUST0001]"));
}
unsigned int i;
for(i = 0; i < m_children->size(); ++i) {
_src.add((*m_children)[i]->getStaticAnalysis());
if((*m_children)[i]->getStaticAnalysis().isUpdating()) {
XQThrow(StaticErrorException,X("XQAttributeConstructor::staticTyping"),
X("It is a static error for the a value expression of an attribute constructor "
"to be an updating expression [err:XUST0001]"));
}
}
_src.getStaticType() = StaticType::ATTRIBUTE_TYPE;
_src.creative(true);
_src.setProperties(StaticAnalysis::DOCORDER | StaticAnalysis::GROUPED |
StaticAnalysis::PEER | StaticAnalysis::SUBTREE | StaticAnalysis::SAMEDOC |
StaticAnalysis::ONENODE);
return this;
}
const XMLCh* XQAttributeConstructor::getNodeType() const
{
return Node::attribute_string;
}
ASTNode *XQAttributeConstructor::getName() const
{
return m_name;
}
const VectorOfASTNodes *XQAttributeConstructor::getChildren() const
{
return m_children;
}
void XQAttributeConstructor::setName(ASTNode *name)
{
m_name = name;
}
| 34.8625 | 138 | 0.723378 |
4e0d154599f4a3108f64944bf741ed7bf06ac09b | 138 | cpp | C++ | base/stublibs/delay/delayimp.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/stublibs/delay/delayimp.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/stublibs/delay/delayimp.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | #include "windows.h"
#include "delayimp.h"
PUnloadInfo __puiHead;
extern "C"
void
__delayLoadHelper2 (
void
)
{
}
| 9.857143 | 23 | 0.608696 |
4e0d5432c50dea2d99c31ba762d86c899ec226d4 | 14,602 | cpp | C++ | src/mytsne.cpp | lijxug/CSOmapR | 0d05307563674f0ee810a3adfb1f2c6a8fb3d70e | [
"MIT"
] | 8 | 2020-11-25T07:51:43.000Z | 2021-12-16T01:02:36.000Z | src/mytsne.cpp | lijxug/CSOmapR | 0d05307563674f0ee810a3adfb1f2c6a8fb3d70e | [
"MIT"
] | 6 | 2020-12-01T03:11:22.000Z | 2021-04-26T01:31:38.000Z | src/mytsne.cpp | lijxug/CSOmapR | 0d05307563674f0ee810a3adfb1f2c6a8fb3d70e | [
"MIT"
] | 3 | 2020-12-22T15:15:48.000Z | 2021-12-06T07:08:45.000Z | /*
*
* Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the Delft University of Technology.
* 4. Neither the name of the Delft University of Technology 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 LAURENS VAN DER MAATEN ''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 LAURENS VAN DER MAATEN BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
*/
// #include "winlibs/stdafx.h"
#ifdef _WIN32
#define _CRT_SECURE_NO_DEPRECATE
#endif
#include <Rcpp.h>
#include <iostream>
#include <fstream>
#include <sstream>
// #include "nbodyfft.h"
#include <math.h>
// #include "annoylib.h"
#include "kissrandom.h"
#include <thread>
#include <float.h>
#include <cstring>
// #include "vptree.h"
// #include "sptree.h"
#include "mytsne.h"
// #include "progress_bar/ProgressBar.hpp"
// #include "parallel_for.h"
#include "time_code.h"
#include <unistd.h>
using namespace std::chrono;
// #ifdef _WIN32
// #include "winlibs/unistd.h"
// #else
// #include <unistd.h>
// #endif
#include <functional>
#define _CRT_SECURE_NO_WARNINGS
int itTest = 0;
using namespace std;
//Helper function for printing Y at each iteration. Useful for debugging
void print_progress(int iter, double *Y, int N, int no_dims) {
ofstream myfile;
std::ostringstream stringStream;
stringStream << "dat/intermediate" << iter << ".txt";
std::string copyOfStr = stringStream.str();
myfile.open(stringStream.str().c_str());
for (int j = 0; j < N; j++) {
for (int i = 0; i < no_dims; i++) {
myfile << Y[j * no_dims + i] << " ";
}
myfile << "\n";
}
myfile.close();
}
// Perform t-SNE
// int TSNE::run(double *X, int N, int D, double *Y, int no_dims, double perplexity, double theta, int rand_seed,
// bool skip_random_init, int max_iter, int stop_lying_iter, int mom_switch_iter,
// double momentum, double final_momentum, double learning_rate, int K, double sigma,
// int nbody_algorithm, int knn_algo, double early_exag_coeff, double *costs,
// bool no_momentum_during_exag, int start_late_exag_iter, double late_exag_coeff, int n_trees, int search_k,
// int nterms, double intervals_per_integer, int min_num_intervals, unsigned int nthreads,
// int load_affinities, int perplexity_list_length, double *perplexity_list, double df,
// double max_step_norm) {
int runExactTSNE(double* P, int N, int D, double* Y, int no_dims, int rand_seed,
bool skip_random_init, int max_iter, int mom_switch_iter,
double momentum, double final_momentum,
double* costs, double df, double max_step_norm, bool verbose) {
// Determine whether we are using an exact algorithm
// Allocate some memory
auto *dY = (double *) malloc(N * no_dims * sizeof(double));
auto *uY = (double *) malloc(N * no_dims * sizeof(double));
auto *gains = (double *) malloc(N * no_dims * sizeof(double));
if (dY == nullptr || uY == nullptr || gains == nullptr) throw std::bad_alloc();
// Initialize gradient to zeros and gains to ones.
for (int i = 0; i < N * no_dims; i++) uY[i] = .0;
for (int i = 0; i < N * no_dims; i++) gains[i] = 1.0;
// Set random seed
if (skip_random_init != true) {
if (rand_seed >= 0) {
if(verbose){Rprintf("Using random seed: %d\n", rand_seed);}
srand((unsigned int) rand_seed);
} else {
if(verbose){Rprintf("Using current time as random seed...\n");}
srand(time(NULL));
}
}
// Initialize solution (randomly)
if (skip_random_init != true) {
if(verbose) {Rprintf("Randomly initializing the solution.\n");}
for (int i = 0; i < N * no_dims; i++) Y[i] = randn() * .0001;
if(verbose) {Rprintf("Y[0] = %lf\n", Y[0]);}
} else {
if(verbose) {Rprintf("Using the given initialization.\n");}
}
if(verbose) {print_progress(0, Y, N, no_dims);}
// Perform main training loop
if(verbose) {Rprintf("Similarities loaded \nLearning embedding...\n");}
std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now();
if(verbose) { Rprintf("Running iterations: %d\n", max_iter); }
for (int iter = 0; iter < max_iter; iter++) {
itTest = iter;
computeExactGradient(P, Y, N, no_dims, dY,df);
// no_mementum_during_exag was = FALSE in .R
for (int i = 0; i < N * no_dims; i++)
gains[i] = (sign(dY[i]) != sign(uY[i])) ? (gains[i] + .2) : (gains[i] * .8);
for (int i = 0; i < N * no_dims; i++) if (gains[i] < .01) gains[i] = .01;
// for (int i = 0; i < N * no_dims; i++) uY[i] = momentum * uY[i] - learning_rate * gains[i] * dY[i];
for (int i = 0; i < N * no_dims; i++) uY[i] = momentum * uY[i] - gains[i] * dY[i]; // try remove learning rate
// Clip the step sizes if max_step_norm is provided
if (max_step_norm > 0) {
for (int i=0; i<N; i++) {
double step = 0;
for (int j=0; j<no_dims; j++) {
step += uY[i*no_dims + j] * uY[i*no_dims + j];
}
step = sqrt(step);
if (step > max_step_norm) {
for (int j=0; j<no_dims; j++) {
uY[i*no_dims + j] *= (max_step_norm/step);
}
}
}
}
for (int i = 0; i < N * no_dims; i++) Y[i] = Y[i] + uY[i];
// Make solution zero-mean
zeroMean(Y, N, no_dims);
if (iter == mom_switch_iter) momentum = final_momentum;
// Print out progress
if ((iter+1) % 50 == 0 || iter == max_iter - 1) {
INITIALIZE_TIME;
START_TIME;
double C = .0;
C = evaluateError(P, Y, N, no_dims,df, false);
costs[iter] = C;
END_TIME("Computing Error");
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
if(verbose) {
Rprintf("Iteration %d (50 iterations in %.2f seconds), cost %f\n", iter+1, std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time).count()/(float)1000.0, C);
}
start_time = std::chrono::steady_clock::now();
}
}
if(verbose) {Rprintf("All iterations done, cleaning now ...\n");}
usleep(100000); // pause a little bit to print out information
// Clean up memory
free(dY);
free(uY);
free(gains);
// free(P);
if(verbose) {Rprintf("Cleanup done ...\n");}
usleep(100000); // pause a little bit to print out information
return 0;
}
void computeExactGradientTest(double* Y, int N, int D, double df ) {
// Compute the squared Euclidean distance matrix
double *DD = (double *) malloc(N * N * sizeof(double));
if (DD == NULL) {
Rprintf("Memory allocation failed!\n");
exit(1);
}
computeSquaredEuclideanDistance(Y, N, D, DD);
// Compute Q-matrix and normalization sum
double *Q = (double *) malloc(N * N * sizeof(double));
if (Q == NULL) {
Rprintf("Memory allocation failed!\n");
exit(1);
}
double sum_Q = .0;
int nN = 0;
for (int n = 0; n < N; n++) {
for (int m = 0; m < N; m++) {
if (n != m) {
Q[nN + m] = 1.0 / pow(1.0 + DD[nN + m]/(double)df, (df));
sum_Q += Q[nN + m];
}
}
nN += N;
}
// Perform the computation of the gradient
char buffer[500];
sprintf(buffer, "temp/exact_gradient%d.txt", itTest);
FILE *fp = fopen(buffer, "w"); // Open file for writing
nN = 0;
int nD = 0;
for (int n = 0; n < N; n++) {
double testQij = 0;
double testPos = 0;
double testNeg1 = 0;
double testNeg2 = 0;
double testdC = 0;
int mD = 0;
for (int m = 0; m < N; m++) {
if (n != m) {
testNeg1 += pow(Q[nN + m],(df +1.0)/df) * (Y[nD + 0] - Y[mD + 0]) / sum_Q;
testNeg2 += pow(Q[nN + m],(df +1.0)/df) * (Y[nD + 1] - Y[mD + 1]) / sum_Q;
}
mD += D;
}
fprintf(fp, "%d, %.12e, %.12e\n", n, testNeg1,testNeg2);
nN += N;
nD += D;
}
fclose(fp);
free(DD);
free(Q);
}
// Compute the exact gradient of the t-SNE cost function
void computeExactGradient(double* P, double* Y, int N, int D, double* dC, double df) {
// Make sure the current gradient contains zeros
for (int i = 0; i < N * D; i++) dC[i] = 0.0;
// Compute the squared Euclidean distance matrix
auto *DD = (double *) malloc(N * N * sizeof(double));
if (DD == nullptr) throw std::bad_alloc();
computeSquaredEuclideanDistance(Y, N, D, DD);
// Compute Q-matrix and normalization sum
auto *Q = (double *) malloc(N * N * sizeof(double));
if (Q == nullptr) throw std::bad_alloc();
auto *Qpow = (double *) malloc(N * N * sizeof(double));
if (Qpow == nullptr) throw std::bad_alloc();
double sum_Q = .0;
int nN = 0;
for (int n = 0; n < N; n++) {
for (int m = 0; m < N; m++) {
if (n != m) {
//Q[nN + m] = 1.0 / pow(1.0 + DD[nN + m]/(double)df, df);
Q[nN + m] = 1.0 / (1.0 + DD[nN + m]/(double)df);
Qpow[nN + m] = pow(Q[nN + m], df);
sum_Q += Qpow[nN + m];
}
}
nN += N;
}
// Perform the computation of the gradient
nN = 0;
int nD = 0;
for (int n = 0; n < N; n++) {
int mD = 0;
for (int m = 0; m < N; m++) {
if (n != m) {
double mult = (P[nN + m] - (Qpow[nN + m] / sum_Q)) * (Q[nN + m]);
for (int d = 0; d < D; d++) {
dC[nD + d] += (Y[nD + d] - Y[mD + d]) * mult;
}
}
mD += D;
}
nN += N;
nD += D;
}
free(Q);
free(Qpow);
free(DD);
}
// Evaluate t-SNE cost function (exactly)
double evaluateError(double* P, double* Y, int N, int D, double df, bool verbose) {
// Compute the squared Euclidean distance matrix
double *DD = (double *) malloc(N * N * sizeof(double));
double *Q = (double *) malloc(N * N * sizeof(double));
if (DD == NULL || Q == NULL) {
Rprintf("Memory allocation failed!\n");
exit(1);
}
if(verbose){ Rprintf("computeSquared\n"); }
computeSquaredEuclideanDistance(Y, N, D, DD);
// Compute Q-matrix and normalization sum
if(verbose){ Rprintf("calculate Q-matrix\n"); }
int nN = 0;
double sum_Q = DBL_MIN;
for (int n = 0; n < N; n++) {
for (int m = 0; m < N; m++) {
if (n != m) {
//Q[nN + m] = 1.0 / pow(1.0 + DD[nN + m]/(double)df, df);
Q[nN + m] = 1.0 / (1.0 + DD[nN + m]/(double)df);
Q[nN +m ] = pow(Q[nN +m ], df);
sum_Q += Q[nN + m];
} else Q[nN + m] = DBL_MIN;
}
nN += N;
}
//Rprintf("sum_Q: %e", sum_Q);
if(verbose){ Rprintf("normalize Q-matrix\n"); }
for (int i = 0; i < N * N; i++) Q[i] /= sum_Q;
// for (int i = 0; i < N; i++) Rprintf("Q[%d]: %e\n", i, Q[i]);
//Rprintf("Q[N*N/2+1]: %e, Q[N*N-1]: %e\n", Q[N*N/2+1], Q[N*N/2+2]);
// Sum t-SNE error
if(verbose){ Rprintf("sum error, to %i\n", N*N); }
double C = .0;
for (int n = 0; n < N * N; n++) {
C += P[n] * log((P[n] + FLT_MIN) / (Q[n] + FLT_MIN));
}
// Clean up memory
free(DD);
free(Q);
return C;
}
// Compute squared Euclidean distance matrix
void computeSquaredEuclideanDistance(double* X, int N, int D, double* DD) {
const double *XnD = X;
for (int n = 0; n < N; ++n, XnD += D) {
const double *XmD = XnD + D;
double *curr_elem = &DD[n * N + n];
*curr_elem = 0.0;
double *curr_elem_sym = curr_elem + N;
for (int m = n + 1; m < N; ++m, XmD += D, curr_elem_sym += N) {
*(++curr_elem) = 0.0;
for (int d = 0; d < D; ++d) {
*curr_elem += (XnD[d] - XmD[d]) * (XnD[d] - XmD[d]);
}
*curr_elem_sym = *curr_elem;
}
}
}
// Makes data zero-mean
void zeroMean(double* X, int N, int D) {
// Compute data mean
double *mean = (double *) calloc(D, sizeof(double));
if (mean == NULL) throw std::bad_alloc();
int nD = 0;
for (int n = 0; n < N; n++) {
for (int d = 0; d < D; d++) {
mean[d] += X[nD + d];
}
nD += D;
}
for (int d = 0; d < D; d++) {
mean[d] /= (double) N;
}
// Subtract data mean
nD = 0;
for (int n = 0; n < N; n++) {
for (int d = 0; d < D; d++) {
X[nD + d] -= mean[d];
}
nD += D;
}
free(mean);
}
// Generates a Gaussian random number
double randn() {
double x, y, radius;
do {
x = 2 * (rand() / ((double) RAND_MAX + 1)) - 1;
y = 2 * (rand() / ((double) RAND_MAX + 1)) - 1;
radius = (x * x) + (y * y);
} while ((radius >= 1.0) || (radius == 0.0));
radius = sqrt(-2 * log(radius) / radius);
x *= radius;
return x;
}
| 33.800926 | 183 | 0.548076 |
4e1137c75d74b2effc529da7fe9de37e37846eb5 | 11,633 | cpp | C++ | MT2D/SDL/Render/MT2D_SDL_Render.cpp | ibm5155/MT2D | b9f1386cf3fe7d0bd2bba7e4fb40852048d253c1 | [
"MIT"
] | 3 | 2017-07-31T04:38:31.000Z | 2020-03-21T02:59:36.000Z | MT2D/SDL/Render/MT2D_SDL_Render.cpp | ibm5155/MT2D | b9f1386cf3fe7d0bd2bba7e4fb40852048d253c1 | [
"MIT"
] | 5 | 2020-10-13T14:34:47.000Z | 2021-08-17T15:02:02.000Z | MT2D/SDL/Render/MT2D_SDL_Render.cpp | ibm5155/MT2D | b9f1386cf3fe7d0bd2bba7e4fb40852048d253c1 | [
"MIT"
] | null | null | null | #include <MT2D/MT2D_Terminal_Define.h>
#if defined(SDL_USE)
#include "../../SDL/MT2D_SDL_Redefine.h"
#include "../../SDL/MT2D_SDL_Event_Handler.h"
#include "../../MT2D.h"
#include <stdio.h>
#include <stdlib.h>
extern MT2D_SDL_Texture* mTexture;
extern MT2D_SDL_Rect gSpriteClips[256];
extern int FRAMEBUFFER[MAX_VER][MAX_HOR]; //used to store what was draw under the screen, (it should avoid overdrawn)
extern MT2D_SDL_Texture *CharSprite[256];
extern MT2D_SDL_Texture *CharSpriteRotated[256];
extern SDL_DisplayMode mode;
extern MT2D_SDL_Texture *OffscrBuff[2];
extern MT2D_SDL_Texture *ScreenBuffer;
extern MT2D_SDL_Events MainEvents;
extern MT2D_SDL_Window* gWindow;
void SDL_Render_Sprites();
void CheckVideoEvent() {
MT2D_SDL_Event_Handler();
if (MainEvents.Window_Started && MainEvents.Window_Resized) {
if (MainEvents.Window_Resized = true){
MainEvents.Window_Resized = false;
mode.w = MainEvents.Window.data1;
mode.h = MainEvents.Window.data2;
MT2D_SDL_SetRenderTarget(MainEvents.Render, NULL);
SDL_DestroyTexture(ScreenBuffer);
// MainEvents.Render = MT2D_SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED);
// SDL_RenderClear(MainEvents.Render);
ScreenBuffer = SDL_CreateTexture(MainEvents.Render, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, mode.w, mode.h);
// MT2D_SDL_SetRenderTarget(MainEvents.Render, ScreenBuffer);
// SDL_SetRenderDrawColor(MainEvents.Render, 0, 0, 0, 255);
// ScreenBuffer_Size.w = mode.w;
// ScreenBuffer_Size.h = mode.h;
for (int i = 0; i < MAX_HOR; i++) {
for (int j = 0; j < MAX_VER; j++) {
FRAMEBUFFER[j][i] = -1;
}
}
// MT2D_SDL_SetRenderTarget(gRenderer, ScreenBuffer);
// SDL_RenderClear(MainEvents.Render);
// SDL_SetRenderDrawColor(MainEvents.Render, 0, 0, 0, 255);
// MT2D_SDL_SetRenderTarget(gRenderer, NULL);
}
}
}
void CheckASCIIbelowSprites() {
int Xstart, Xend, Ystart, Yend;
int X;
for (int i = 0; i < MainEvents.SpriteBuffer_Count; i++) {
Xstart = (MAX_HOR * (MainEvents.SpriteBufferX[i]-1)) / 320;
Xend = (MAX_HOR * (MainEvents.SpriteBufferX[i] + MainEvents.SpriteBuffer[i].ScaleX +1)) / 320;
Ystart = (MAX_VER * (MainEvents.SpriteBufferY[i]-1)) / 240;
Yend = (MAX_VER * (MainEvents.SpriteBufferY[i] + MainEvents.SpriteBuffer[i].ScaleY + 1)) / 240;
//now we clear the BUFFER behind the sprites
for (; Ystart <= Yend && Ystart < MAX_VER; Ystart++) {
for (X = Xstart; X <= Xend && X < MAX_HOR; X++) {
FRAMEBUFFER[Ystart][X] = -2;
}
}
}
}
void Clean_Render() {
SDL_RenderClear(MainEvents.Render);
/* MT2D_SDL_Rect renderQuad;
renderQuad.x = 0;
renderQuad.y = 0;
renderQuad.w = mode.w;
renderQuad.h = mode.h;
MT2D_SDL_RenderCopy(MainEvents.Render, mTexture, &gSpriteClips[32], &renderQuad);
*/
}
void Render_New2(unsigned char BUFFER[][MAX_HOR]);
void Render_NewOld(unsigned char BUFFER[][MAX_HOR]) {
// Render_New2(BUFFER);
// return;
int posx = 0;
int posy = 0;
int angle = 0;
int NextA = 0;
int NextB = 0;
MT2D_SDL_Rect renderQuad;
MT2D_SDL_Rect Original;
void *mPixels;
int mPitch;
int CHAR_ResizedX = 0;
int CHAR_ResizedY = 0;
int Heigth;
int Width;
int OffsetX, OffsetY;
char collide = 0;
bool inverte = false;
CheckVideoEvent();
CheckASCIIbelowSprites();
if (mode.h >= mode.w)
{
//smartphone
angle = 0;
inverte = true;
Heigth = mode.w;
Width = mode.h;
CHAR_ResizedX = Heigth / (MAX_VER);//afetando horizontal
CHAR_ResizedY = Width / (MAX_HOR);//afetando a vertical
}
else {
//desktop
Heigth = mode.h;
Width = mode.w;
CHAR_ResizedX = Width / (MAX_HOR);
CHAR_ResizedY = Heigth / (MAX_VER);
}
//Clean_Render();
// MT2D_SDL_RenderCopyEx(gRenderer, ScreenBuffer, &ScreenBuffer_Size, &ScreenBuffer_Size, NULL, NULL, SDL_FLIP_NONE);
// MT2D_SDL_SetRenderTarget(gRenderer, ScreenBuffer);
// SDL_RenderClear(gRenderer);
// SDL_SetRenderDrawColor(gRenderer, rand() % 255, rand() % 255, rand()%255, 255);
for (posx = 0; posx < MAX_HOR; posx++) {
NextA = 0;
for (posy = 0; posy < MAX_VER; posy++) {
collide = false;
if (FRAMEBUFFER[posy][posx] == -2) {
collide = true;
}
if (' ' != BUFFER[posy][posx]/*|| collide == true*/) {//avoids overdraw
//if (collide == false) {
FRAMEBUFFER[posy][posx] = BUFFER[posy][posx];
//}
Original.h = FONT_SIZEX;
Original.w = FONT_SIZEY;
Original.x = 0;
Original.y = 0;
if (mode.h >= mode.w){
//90�
renderQuad.x = mode.w - NextA - CHAR_ResizedX;
renderQuad.y = NextB;
renderQuad.w = CHAR_ResizedX;
renderQuad.h = CHAR_ResizedY;
NextA += CHAR_ResizedX;
MT2D_SDL_RenderCopyEx(MainEvents.Render, CharSpriteRotated[BUFFER[posy][posx]], &Original, &renderQuad, angle, NULL, SDL_FLIP_HORIZONTAL);
}
else {
renderQuad.x = NextB;
renderQuad.y = NextA;
renderQuad.w = CHAR_ResizedX;
renderQuad.h = CHAR_ResizedY;
NextA += CHAR_ResizedY;
MT2D_SDL_RenderCopyEx(MainEvents.Render, CharSprite[BUFFER[posy][posx]], &Original, &renderQuad, angle, NULL, SDL_FLIP_NONE);
}
}
else {
NextA += (mode.h >= mode.w ? CHAR_ResizedX : CHAR_ResizedY);
}
}
if (mode.h >= mode.w) {
NextB += CHAR_ResizedY;
}
else {
NextB += CHAR_ResizedX;
}
}
// MT2D_SDL_SetRenderTarget(gRenderer, NULL);
// MT2D_SDL_RenderCopy(gRenderer, ScreenBuffer, &ScreenBuffer_Size, &ScreenBuffer_Size);
SDL_Render_Sprites();
}
void Render_New(unsigned char BUFFER[][MAX_HOR]) {
int posx = 0;
int posy = 0;
int angle = 0;
int NextA = 0;
int NextB = 0;
MT2D_SDL_Rect renderQuad;
MT2D_SDL_Rect Original;
void *mPixels;
int mPitch;
int CHAR_ResizedX = 0;
int CHAR_ResizedY = 0;
int Heigth;
int Width;
int OffsetX, OffsetY;
bool inverte = false;
CheckVideoEvent();
if (mode.h >= mode.w)
{
//smartphone
angle = 0;
inverte = true;
Heigth = mode.w;
Width = mode.h;
MT2D_SDL_SetRenderTarget(MainEvents.Render, OffscrBuff[1]);
}
else {
//desktop
Heigth = mode.h;
Width = mode.w;
MT2D_SDL_SetRenderTarget(MainEvents.Render, OffscrBuff[0]);
}
Original.h = FONT_SIZEY;
Original.w = FONT_SIZEX;
Original.x = 0;
Original.y = 0;
for (posx = 0; posx < MAX_HOR; posx++) {
NextA = 0;
for (posy = 0; posy < MAX_VER; posy++) {
if (FRAMEBUFFER[posy][posx] != BUFFER[posy][posx]) {//avoids overdraw
FRAMEBUFFER[posy][posx] = BUFFER[posy][posx];
if (mode.h >= mode.w) {
//90�
renderQuad.x = mode.w - NextA - FONT_SIZEX;
renderQuad.y = NextB;
renderQuad.w = FONT_SIZEX;
renderQuad.h = FONT_SIZEY;
NextA += CHAR_ResizedX;
MT2D_SDL_RenderCopyEx(MainEvents.Render, CharSpriteRotated[BUFFER[posy][posx]], &Original, &renderQuad, angle, NULL, SDL_FLIP_HORIZONTAL);
/**/
renderQuad.y = posx * FONT_SIZEX;
renderQuad.x = ((MAX_VER-1) * FONT_SIZEY) - posy * FONT_SIZEY;
renderQuad.w = FONT_SIZEX;
renderQuad.h = FONT_SIZEY;
NextA += CHAR_ResizedX;
MT2D_SDL_RenderCopyEx(MainEvents.Render, CharSpriteRotated[BUFFER[posy][posx]], &Original, &renderQuad, angle, NULL, SDL_FLIP_HORIZONTAL);
}
else {
renderQuad.x = posx * FONT_SIZEX;
renderQuad.y = posy * FONT_SIZEY;
renderQuad.w = FONT_SIZEX;
renderQuad.h = FONT_SIZEY;
NextA += CHAR_ResizedY;
MT2D_SDL_RenderCopyEx(MainEvents.Render, CharSprite[BUFFER[posy][posx]], &Original, &renderQuad, angle, NULL, SDL_FLIP_NONE);
}
}
}
}
MT2D_SDL_SetRenderTarget(MainEvents.Render, NULL);
if (!inverte) {
Original.h = FONT_SIZEY*MAX_VER;
Original.w = FONT_SIZEX*MAX_HOR;
Original.x = 0;
Original.y = 0;
renderQuad.x = 0;
renderQuad.y = 0;
renderQuad.w = mode.w;
renderQuad.h = mode.h;
MT2D_SDL_RenderCopy(MainEvents.Render, OffscrBuff[0], &Original, &renderQuad);
}
else {
Original.w = FONT_SIZEY*MAX_VER;
Original.h = FONT_SIZEX*MAX_HOR;
Original.x = 0;
Original.y = 0;
renderQuad.x = 0;
renderQuad.y = 0;
renderQuad.w = mode.w;
renderQuad.h = mode.h;
MT2D_SDL_RenderCopy(MainEvents.Render, OffscrBuff[1], &Original, &renderQuad);
}
SDL_Render_Sprites();
}
void SDL_Render() {
MT2D_SDL_RenderPresent(MainEvents.Render);
}
void SDL_Add_ImagetoBuffer(Sprite *IMG,int X, int Y) {
if (MainEvents.SpriteBuffer_Count == 0) {
MainEvents.SpriteBuffer = (Sprite*)malloc(sizeof(Sprite));
MainEvents.SpriteBufferX = (int*)malloc(sizeof(int));
MainEvents.SpriteBufferY = (int*)malloc(sizeof(int));
MainEvents.SpriteBuffer[MainEvents.SpriteBuffer_Count] = *IMG;
MainEvents.SpriteBufferX[MainEvents.SpriteBuffer_Count] = X;
MainEvents.SpriteBufferY[MainEvents.SpriteBuffer_Count] = Y;
}
else {
MainEvents.SpriteBuffer = (Sprite*)realloc(MainEvents.SpriteBuffer,(MainEvents.SpriteBuffer_Count+1)*sizeof(Sprite));
MainEvents.SpriteBufferY = (int*)realloc(MainEvents.SpriteBufferY, (MainEvents.SpriteBuffer_Count + 1) * sizeof(int));
MainEvents.SpriteBufferX = (int*)realloc(MainEvents.SpriteBufferX, (MainEvents.SpriteBuffer_Count + 1) * sizeof(int));
MainEvents.SpriteBuffer[MainEvents.SpriteBuffer_Count] = *IMG;
MainEvents.SpriteBuffer[MainEvents.SpriteBuffer_Count] = *IMG;
MainEvents.SpriteBufferX[MainEvents.SpriteBuffer_Count] = X;
MainEvents.SpriteBufferY[MainEvents.SpriteBuffer_Count] = Y;
}
MainEvents.SpriteBuffer_Count++;
}
void SDL_Render_Sprites() {
MT2D_SDL_Rect renderQuad;
MT2D_SDL_Rect Original;
SDL_Point Center;
void *mPixels;
int i = 0;
int angle = 0;
while (i < MainEvents.SpriteBuffer_Count) {
if (mode.h >= mode.w) {
Original.h = MainEvents.SpriteBuffer[i].SizeX;
Original.w = MainEvents.SpriteBuffer[i].SizeY;
Original.x = 0;
Original.y = 0;
//90�
renderQuad.x = (( 320*(240 - MainEvents.SpriteBuffer[i].ScaleY - MainEvents.SpriteBufferY[i])/240 ) * mode.w) / 320;
renderQuad.y = ( (240*MainEvents.SpriteBufferX[i])/ 320 * mode.h) / 240;
// renderQuad.y = MainEvents.SpriteBuffer[i].ScaleX /2 +((MainEvents.SpriteBufferX[i] + 0) * mode.h) / 240;
renderQuad.h = (MainEvents.SpriteBuffer[i].ScaleX * mode.h ) / 320;
renderQuad.w = (MainEvents.SpriteBuffer[i].ScaleY * mode.w ) / 240;
MT2D_SDL_RenderCopyEx(MainEvents.Render, (MT2D_SDL_Texture*)MainEvents.SpriteBuffer[i].RotatedTexture, &Original, &renderQuad,0,0, SDL_FLIP_HORIZONTAL);
}
else {
Original.h = MainEvents.SpriteBuffer[i].SizeY;
Original.w = MainEvents.SpriteBuffer[i].SizeX;
Original.x = 0;
Original.y = 0;
renderQuad.x = (MainEvents.SpriteBufferX[i] * mode.w) / 320;
renderQuad.y = (MainEvents.SpriteBufferY[i] * mode.h) / 240;
renderQuad.w = (MainEvents.SpriteBuffer[i].ScaleX * mode.w ) / 320;
renderQuad.h = (MainEvents.SpriteBuffer[i].ScaleY * mode.h) / 240;
MT2D_SDL_RenderCopyEx(MainEvents.Render, (MT2D_SDL_Texture*)MainEvents.SpriteBuffer[i].Data, &Original, &renderQuad, 0, NULL, SDL_FLIP_NONE);
}
i++;
}
}
/**
Clear the sprite buffer and also the backup from the ASCII window so we can redraw everything again.
**/
void SDL_Clear_RenderBuffers() {
if (MainEvents.SpriteBuffer) {
free(MainEvents.SpriteBuffer);
MainEvents.SpriteBuffer = 0;
MainEvents.SpriteBuffer_Count = 0;
free(MainEvents.SpriteBufferX);
free(MainEvents.SpriteBufferY);
MainEvents.SpriteBufferY = 0;
MainEvents.SpriteBufferX = 0;
}
}
void MT2D_SDL_Clear_Main_Window() {
int i = 0, j = 0;
while (i <= MAX_VER) {
while (j<MAX_HOR) {
WINDOW1[i][j] = ' ';
j++;
}
i++;
j = 0;
}
WINDOW1[MAX_VER][MAX_HOR] = '\0';
SDL_Clear_RenderBuffers();
}
void MT2D_SDL_Draw_Window(int which) {
int i = 0;
int j = 0;
if (which == DISPLAY_WINDOW1) {
Render_New(WINDOW1);
}
else {
Render_New(WINDOW2);
}
SDL_Render();
}
#endif | 30.137306 | 155 | 0.693028 |
4e12d366112ece89a1a1b32ad66dde54bed8d0a7 | 6,673 | cc | C++ | src/modular/tests/module_context_test.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 210 | 2019-02-05T12:45:09.000Z | 2022-03-28T07:59:06.000Z | src/modular/tests/module_context_test.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 56 | 2021-06-03T03:16:25.000Z | 2022-03-20T01:07:44.000Z | src/modular/tests/module_context_test.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 73 | 2019-03-06T18:55:23.000Z | 2022-03-26T12:04:51.000Z | // Copyright 2019 The Fuchsia 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 <fuchsia/modular/testing/cpp/fidl.h>
#include <gmock/gmock.h>
#include "lib/syslog/cpp/macros.h"
#include "src/lib/fsl/vmo/strings.h"
#include "src/modular/lib/modular_test_harness/cpp/fake_module.h"
#include "src/modular/lib/modular_test_harness/cpp/fake_session_shell.h"
#include "src/modular/lib/modular_test_harness/cpp/test_harness_fixture.h"
using testing::ElementsAre;
namespace {
class ModuleContextTest : public modular_testing::TestHarnessFixture {
protected:
ModuleContextTest()
: session_shell_(modular_testing::FakeSessionShell::CreateWithDefaultOptions()) {}
void StartSession(modular_testing::TestHarnessBuilder builder) {
builder.InterceptSessionShell(session_shell_->BuildInterceptOptions());
builder.BuildAndRun(test_harness());
// Wait for our session shell to start.
RunLoopUntil([this] { return session_shell_->is_running(); });
}
void RestartStory(std::string story_name) {
fuchsia::modular::StoryControllerPtr story_controller;
session_shell_->story_provider()->GetController(story_name, story_controller.NewRequest());
bool restarted = false;
story_controller->Stop([&] {
story_controller->RequestStart();
restarted = true;
});
RunLoopUntil([&] { return restarted; });
}
std::unique_ptr<modular_testing::FakeSessionShell> session_shell_;
};
// A version of FakeModule which captures handled intents in a std::vector<>
// and exposes callbacks triggered on certain lifecycle events.
class TestModule : public modular_testing::FakeModule {
public:
explicit TestModule(std::string module_name = "")
: modular_testing::FakeModule(
{.url = modular_testing::TestHarnessBuilder::GenerateFakeUrl(module_name),
.sandbox_services = modular_testing::FakeModule::GetDefaultSandboxServices()}) {}
fit::function<void()> on_destroy;
fit::function<void()> on_create;
private:
// |modular_testing::FakeModule|
void OnCreate(fuchsia::sys::StartupInfo startup_info) override {
modular_testing::FakeModule::OnCreate(std::move(startup_info));
if (on_create)
on_create();
}
// |modular_testing::FakeModule|
void OnDestroy() override {
if (on_destroy)
on_destroy();
}
};
class TestStoryWatcher : fuchsia::modular::StoryWatcher {
public:
TestStoryWatcher(fit::function<void(fuchsia::modular::StoryState)> on_state_change)
: binding_(this), on_state_change_(std::move(on_state_change)) {}
~TestStoryWatcher() override = default;
// Registers itself as a watcher on the given story. Only one story at a time
// can be watched.
void Watch(fuchsia::modular::StoryController* const story_controller) {
story_controller->Watch(binding_.NewBinding());
}
private:
// |fuchsia::modular::StoryWatcher|
void OnStateChange(fuchsia::modular::StoryState state) override { on_state_change_(state); }
void OnModuleAdded(fuchsia::modular::ModuleData /*module_data*/) override {}
void OnModuleFocused(std::vector<std::string> /*module_path*/) override {}
fidl::Binding<fuchsia::modular::StoryWatcher> binding_;
fit::function<void(fuchsia::modular::StoryState)> on_state_change_;
};
// Test that ModuleContext.RemoveSelfFromStory() on the only mod in a story has
// the affect of shutting down the module and removing it permanently from the
// story (if the story is restarted, it is not relaunched).
TEST_F(ModuleContextTest, RemoveSelfFromStory) {
TestModule module1("module1");
modular_testing::TestHarnessBuilder builder;
builder.InterceptComponent(module1.BuildInterceptOptions());
StartSession(std::move(builder));
modular_testing::AddModToStory(test_harness(), "storyname", "modname1",
{.action = "action", .handler = module1.url()});
RunLoopUntil([&] { return module1.is_running(); });
// Instruct module1 to remove itself from the story. Expect to see that
// module1 is terminated.
module1.module_context()->RemoveSelfFromStory();
RunLoopUntil([&] { return !module1.is_running(); });
// Additionally, restarting the story should not result in module1 being
// restarted.
fuchsia::modular::StoryControllerPtr story_controller;
session_shell_->story_provider()->GetController("storyname", story_controller.NewRequest());
bool story_stopped = false;
bool story_restarted = false;
TestStoryWatcher story_watcher([&](fuchsia::modular::StoryState state) {
if (state == fuchsia::modular::StoryState::STOPPED) {
story_stopped = true;
} else if (state == fuchsia::modular::StoryState::RUNNING) {
story_restarted = true;
}
});
story_watcher.Watch(story_controller.get());
RestartStory("storyname");
RunLoopUntil([&] { return story_stopped && story_restarted; });
EXPECT_FALSE(module1.is_running());
}
// Test that when ModuleContext.RemoveSelfFromStory() is called on one of two
// modules in a story, it has the affect of shutting down the module and
// removing it permanently from the story (if the story is restarted, it is not
// relaunched).
TEST_F(ModuleContextTest, RemoveSelfFromStory_2mods) {
modular_testing::TestHarnessBuilder builder;
TestModule module1("module1");
TestModule module2("module2");
builder.InterceptComponent(module1.BuildInterceptOptions());
builder.InterceptComponent(module2.BuildInterceptOptions());
StartSession(std::move(builder));
modular_testing::AddModToStory(test_harness(), "storyname", "modname1",
{.action = "action", .handler = module1.url()});
modular_testing::AddModToStory(test_harness(), "storyname", "modname2",
{.action = "action", .handler = module2.url()});
RunLoopUntil([&] { return module1.is_running() && module2.is_running(); });
// Instruct module1 to remove itself from the story. Expect to see that
// module1 is terminated and module2 is not.
module1.module_context()->RemoveSelfFromStory();
RunLoopUntil([&] { return !module1.is_running(); });
ASSERT_TRUE(module2.is_running());
// Additionally, restarting the story should not result in module1 being
// restarted whereas it should for module2.
bool module2_destroyed = false;
bool module2_restarted = false;
module2.on_destroy = [&] { module2_destroyed = true; };
module2.on_create = [&] { module2_restarted = true; };
RestartStory("storyname");
RunLoopUntil([&] { return module2_restarted; });
EXPECT_FALSE(module1.is_running());
EXPECT_TRUE(module2_destroyed);
}
} // namespace
| 39.023392 | 95 | 0.728008 |
4e1306360ebcb70ea72f14a0dd65f5090fec2721 | 961 | hpp | C++ | include/codegen/include/System/IServiceProvider.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/System/IServiceProvider.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/System/IServiceProvider.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Type
class Type;
}
// Completed forward declares
// Begin il2cpp-utils forward declares
struct Il2CppObject;
// Completed il2cpp-utils forward declares
// Type namespace: System
namespace System {
// Autogenerated type: System.IServiceProvider
class IServiceProvider {
public:
// public System.Object GetService(System.Type serviceType)
// Offset: 0xFFFFFFFF
::Il2CppObject* GetService(System::Type* serviceType);
}; // System.IServiceProvider
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(System::IServiceProvider*, "System", "IServiceProvider");
#pragma pack(pop)
| 31 | 80 | 0.700312 |
4e13dd68b9e7fa96e93e3acd2797d589a6269baf | 2,019 | cc | C++ | core/src/psfcore/unused/psftest.cc | ma-laforge/LibPSFC.jl | 73a5176ca78cade63cc9c5da4d15b36f9042645c | [
"MIT"
] | null | null | null | core/src/psfcore/unused/psftest.cc | ma-laforge/LibPSFC.jl | 73a5176ca78cade63cc9c5da4d15b36f9042645c | [
"MIT"
] | null | null | null | core/src/psfcore/unused/psftest.cc | ma-laforge/LibPSFC.jl | 73a5176ca78cade63cc9c5da4d15b36f9042645c | [
"MIT"
] | null | null | null | #include "psf.h"
#include "psfdata.h"
#include <string>
void noisesummary() {
std::string pnoisefile("/nfs/home/henrik/spectre/1/pnoise.raw/pnoise_pout3g.pnoise");
PSFDataSet psfnoise(pnoisefile);
std::vector<std::string> names = psfnoise.get_signal_names();
double sum=0;
for(std::vector<std::string>::iterator i=names.begin(); i != names.end(); i++) {
if(*i != std::string("out")) {
StructVector *valvec = dynamic_cast<StructVector *>(psfnoise.get_signal_vector(*i));
Struct& data = (*valvec)[3];
if(data.find(std::string("total")) != data.end())
sum += (double)*data[std::string("total")];
delete(valvec);
}
}
std::cout << "Total: " << sum << std::endl;
}
int main() {
std::string dcopfile("../examples/data/opBegin");
std::string pssfdfile("../examples/data/pss0.fd.pss");
std::string tranfile("../examples/data/timeSweep");
std::string srcsweepfile("../examples/data/srcSweep");
// PSFDataSet psftran(tranfile);
// PSFDataSet pssfd(pssfdfile);
// PSFDataSet pssop(dcopfile);
PSFDataSet srcsweep(srcsweepfile);
noisesummary();
//pssop.get_signal_properties("XIRXRFMIXTRIM0.XRDAC4.XR.R1");
std::cout << "Header properties:" << std::endl;
PropertyMap headerprops(srcsweep.get_header_properties());
for(PropertyMap::iterator i=headerprops.begin(); i!=headerprops.end(); i++)
std::cout << i->first << ":" << *i->second << std::endl;
// {
// Float64Vector *parvec = (Float64Vector *)psfnoise.get_param_values();
// }
// Float64Vector *parvec = (Float64Vector *)psftran.get_param_values();
// for(Float64Vector::iterator i=parvec->begin(); i!=parvec->end(); i++)
// std::cout << *i << " ";
// std::cout << std::endl;
// std::cout << "len=" << parvec->size() << std::endl;
//PSFDataVector *valvec = psf.get_signal_vector("tx_lopath_hb_stop.tx_lopath_hb_top.tx_lopath_hb_driver.driver_hb_channel_q.Ismall.Idriver_n.nout_off.imod");
}
| 32.047619 | 161 | 0.634968 |
4e15065ca2ce0f75964a8116c46a77e630f247fe | 5,766 | cpp | C++ | src/qt/i2poptionswidget.cpp | eddef/anoncoin | 7a018e15c814bba30e805cfe83f187388eadc0a8 | [
"MIT"
] | 90 | 2015-01-13T14:32:43.000Z | 2020-10-15T23:07:11.000Z | src/qt/i2poptionswidget.cpp | nonlinear-chaos-order-etc-etal/anoncoin | 5e441d8746240072f1379577e14ff7a17390b81f | [
"MIT"
] | 91 | 2015-01-07T03:44:14.000Z | 2020-12-24T13:56:27.000Z | src/qt/i2poptionswidget.cpp | nonlinear-chaos-order-etc-etal/anoncoin | 5e441d8746240072f1379577e14ff7a17390b81f | [
"MIT"
] | 42 | 2015-01-28T12:34:14.000Z | 2021-05-06T16:16:48.000Z | // Copyright (c) 2013-2014 The Anoncoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Many builder specific things set in the config file, don't see a need for it here, still better to not forget to include it in your source files.
#if defined(HAVE_CONFIG_H)
#include "config/anoncoin-config.h"
#endif
#include "i2poptionswidget.h"
#include "ui_i2poptionswidget.h"
#include "optionsmodel.h"
#include "monitoreddatamapper.h"
#include "i2pshowaddresses.h"
#include "util.h"
#include "clientmodel.h"
I2POptionsWidget::I2POptionsWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::I2POptionsWidget),
clientModel(0)
{
ui->setupUi(this);
QObject::connect(ui->pushButtonCurrentI2PAddress, SIGNAL(clicked()), this, SLOT(ShowCurrentI2PAddress()));
QObject::connect(ui->pushButtonGenerateI2PAddress, SIGNAL(clicked()), this, SLOT(GenerateNewI2PAddress()));
QObject::connect(ui->checkBoxAllowZeroHop , SIGNAL(stateChanged(int)) , this, SIGNAL(settingsChanged()));
QObject::connect(ui->checkBoxInboundAllowZeroHop , SIGNAL(stateChanged(int)) , this, SIGNAL(settingsChanged()));
QObject::connect(ui->checkBoxUseI2POnly , SIGNAL(stateChanged(int)) , this, SIGNAL(settingsChanged()));
QObject::connect(ui->lineEditSAMHost , SIGNAL(textChanged(QString)), this, SIGNAL(settingsChanged()));
QObject::connect(ui->lineEditTunnelName , SIGNAL(textChanged(QString)), this, SIGNAL(settingsChanged()));
QObject::connect(ui->spinBoxInboundBackupQuality , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged()));
QObject::connect(ui->spinBoxInboundIPRestriction , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged()));
QObject::connect(ui->spinBoxInboundLength , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged()));
QObject::connect(ui->spinBoxInboundLengthVariance , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged()));
QObject::connect(ui->spinBoxInboundQuantity , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged()));
QObject::connect(ui->spinBoxOutboundBackupQuantity, SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged()));
QObject::connect(ui->spinBoxOutboundIPRestriction , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged()));
QObject::connect(ui->spinBoxOutboundLength , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged()));
QObject::connect(ui->spinBoxOutboundLengthVariance, SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged()));
QObject::connect(ui->spinBoxOutboundPriority , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged()));
QObject::connect(ui->spinBoxOutboundQuantity , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged()));
QObject::connect(ui->spinBoxSAMPort , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged()));
}
I2POptionsWidget::~I2POptionsWidget()
{
delete ui;
}
void I2POptionsWidget::setMapper(MonitoredDataMapper& mapper)
{
mapper.addMapping(ui->checkBoxUseI2POnly , OptionsModel::eI2PUseI2POnly);
mapper.addMapping(ui->lineEditSAMHost , OptionsModel::eI2PSAMHost);
mapper.addMapping(ui->spinBoxSAMPort , OptionsModel::eI2PSAMPort);
mapper.addMapping(ui->lineEditTunnelName , OptionsModel::eI2PSessionName);
mapper.addMapping(ui->spinBoxInboundQuantity , OptionsModel::I2PInboundQuantity);
mapper.addMapping(ui->spinBoxInboundLength , OptionsModel::I2PInboundLength);
mapper.addMapping(ui->spinBoxInboundLengthVariance , OptionsModel::I2PInboundLengthVariance);
mapper.addMapping(ui->spinBoxInboundBackupQuality , OptionsModel::I2PInboundBackupQuantity);
mapper.addMapping(ui->checkBoxInboundAllowZeroHop , OptionsModel::I2PInboundAllowZeroHop);
mapper.addMapping(ui->spinBoxInboundIPRestriction , OptionsModel::I2PInboundIPRestriction);
mapper.addMapping(ui->spinBoxOutboundQuantity , OptionsModel::I2POutboundQuantity);
mapper.addMapping(ui->spinBoxOutboundLength , OptionsModel::I2POutboundLength);
mapper.addMapping(ui->spinBoxOutboundLengthVariance, OptionsModel::I2POutboundLengthVariance);
mapper.addMapping(ui->spinBoxOutboundBackupQuantity, OptionsModel::I2POutboundBackupQuantity);
mapper.addMapping(ui->checkBoxAllowZeroHop , OptionsModel::I2POutboundAllowZeroHop);
mapper.addMapping(ui->spinBoxOutboundIPRestriction , OptionsModel::I2POutboundIPRestriction);
mapper.addMapping(ui->spinBoxOutboundPriority , OptionsModel::I2POutboundPriority);
}
void I2POptionsWidget::setModel(ClientModel* model)
{
clientModel = model;
}
void I2POptionsWidget::ShowCurrentI2PAddress()
{
if (clientModel)
{
const QString pub = clientModel->getPublicI2PKey();
const QString priv = clientModel->getPrivateI2PKey();
const QString b32 = clientModel->getB32Address(pub);
const QString configFile = QString::fromStdString(GetConfigFile().string());
ShowI2PAddresses i2pCurrDialog("Your current I2P-address", pub, priv, b32, configFile, this);
i2pCurrDialog.exec();
}
}
void I2POptionsWidget::GenerateNewI2PAddress()
{
if (clientModel)
{
QString pub, priv;
clientModel->generateI2PDestination(pub, priv);
const QString b32 = clientModel->getB32Address(pub);
const QString configFile = QString::fromStdString(GetConfigFile().string());
ShowI2PAddresses i2pCurrDialog("Generated I2P address", pub, priv, b32, configFile, this);
i2pCurrDialog.exec();
}
}
| 52.899083 | 148 | 0.73153 |
4e153ae850f05e9837dbc6d3d0a94180ce59ea71 | 1,893 | cpp | C++ | problems6/6A.cpp | Lopa10ko/ITMO-algo-2021-2022 | fa1ae8571e9cccd54faf1680fad21ffc6dbcef49 | [
"MIT"
] | 1 | 2021-11-11T12:08:14.000Z | 2021-11-11T12:08:14.000Z | problems6/6A.cpp | Lopa10ko/ITMO-algo-2021-2022 | fa1ae8571e9cccd54faf1680fad21ffc6dbcef49 | [
"MIT"
] | null | null | null | problems6/6A.cpp | Lopa10ko/ITMO-algo-2021-2022 | fa1ae8571e9cccd54faf1680fad21ffc6dbcef49 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <cmath>
#define HASH_SPACE 1000010
using namespace std;
int get_hash(int value) {
return abs(value % HASH_SPACE);
}
struct hashset {
int value;
struct hashset *next;
} **Hashtable;
bool exists_value(int value) {
hashset *current = Hashtable[get_hash(value)];
//iterative -- alternative binsearch on hashtable
while (current != NULL && current -> value != value) {
current = current -> next;
}
return ((current == NULL) ? false : true);
}
void insert_value(int value) {
//parenting
hashset *current, *current_next;
int index = get_hash(value);
current = new hashset;
if (exists_value(value)) return;
current_next = Hashtable[index];
Hashtable[index] = current;
current -> next = current_next;
current -> value = value;
return;
}
void delete_value(int value) {
hashset *current = Hashtable[get_hash(value)], *current_next = 0;
while (current != NULL && current -> value != value) {
current_next = current;
current = current -> next;
}
if (current == NULL) return;
if (current_next != NULL) {
current_next -> next = current -> next;
}
else {
Hashtable[get_hash(value)] = current -> next;
}
current = NULL;
}
int main() {
ifstream fin("set.in");
ofstream fout("set.out");
Hashtable = new hashset * [HASH_SPACE];
//g++ nullptr
for (int i = 0; i < HASH_SPACE; i++) Hashtable[i] = NULL;
int value = 0;
string action;
while (fin >> action) {
fin >> value;
if (action == "insert") {
insert_value(value);
}
else if (action == "delete") {
delete_value(value);
}
else if (action == "exists") {
fout << ((exists_value(value)) ? "true" : "false") << "\n";
}
}
return 0;
} | 24.907895 | 71 | 0.578447 |
4e17b9dc4559616a2786013d641833dbddf34747 | 2,588 | cpp | C++ | manager/spline/spline_manager.cpp | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | 1 | 2017-08-11T19:12:24.000Z | 2017-08-11T19:12:24.000Z | manager/spline/spline_manager.cpp | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | 11 | 2018-07-07T20:09:44.000Z | 2020-02-16T22:45:09.000Z | manager/spline/spline_manager.cpp | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | null | null | null | //------------------------------------------------------------
// snakeoil (c) Alexis Constantin Link
// Distributed under the MIT license
//------------------------------------------------------------
#include "spline_manager.h"
using namespace so_manager ;
//**********************************************************************************************
spline_manager::spline_manager( void_t )
{
}
//**********************************************************************************************
spline_manager::spline_manager( this_rref_t rhv )
{
_linears_res_mgr = std::move( rhv._linears_res_mgr ) ;
_counter = rhv._counter ;
}
//**********************************************************************************************
spline_manager::~spline_manager( void_t )
{
}
//**********************************************************************************************
spline_manager::this_ptr_t spline_manager::create( this_rref_t rhv, so_memory::purpose_cref_t p )
{
return so_manager::memory::alloc( std::move(rhv), p ) ;
}
//**********************************************************************************************
void_t spline_manager::destroy( this_ptr_t ptr )
{
so_manager::memory::dealloc( ptr ) ;
}
//**********************************************************************************************
bool_t spline_manager::acquire( so_manager::key_cref_t key_in,
so_resource::purpose_cref_t p, linears_handle_out_t hnd_out )
{
return _linears_res_mgr.acquire( key_in, p, hnd_out ) ;
}
//**********************************************************************************************
bool_t spline_manager::release( linears_handle_rref_t hnd )
{
return _linears_res_mgr.release( std::move(hnd) ) ;
}
//**********************************************************************************************
so_manager::result spline_manager::insert( so_manager::key_cref_t key_in,
linears_manage_params_cref_t mp )
{
linear_spline_store_item si ;
// fill si
auto si_ptr = so_manager::memory::alloc( std::move(si),
"[so_manager::spline_manager::insert] : linear spline store item for " + key_in ) ;
auto const res = _linears_res_mgr.insert( key_in, si_ptr ) ;
if( so_log::log::error( so_resource::no_success( res ),
"[so_manager::spline_manager::insert] : insert" ) )
{
so_manager::memory::dealloc( si_ptr ) ;
return so_manager::key_already_in_use;
}
return so_manager::ok ;
}
//********************************************************************************************** | 35.452055 | 97 | 0.435471 |
4e1d50433f0a8654ffa2386314841105761d6aa4 | 10,804 | cc | C++ | unit_tests/tests/base/ThreadGroup/ThreadGroup_test.cc | Wlgen/force-riscv | 9f09b86c5a21ca00f8e5ade8e5186d65bc3e26f8 | [
"Apache-2.0"
] | 111 | 2020-06-12T22:31:30.000Z | 2022-03-19T03:45:20.000Z | unit_tests/tests/base/ThreadGroup/ThreadGroup_test.cc | Wlgen/force-riscv | 9f09b86c5a21ca00f8e5ade8e5186d65bc3e26f8 | [
"Apache-2.0"
] | 34 | 2020-06-12T20:23:40.000Z | 2022-03-15T20:04:31.000Z | unit_tests/tests/base/ThreadGroup/ThreadGroup_test.cc | Wlgen/force-riscv | 9f09b86c5a21ca00f8e5ade8e5186d65bc3e26f8 | [
"Apache-2.0"
] | 32 | 2020-06-12T19:15:26.000Z | 2022-02-20T11:38:31.000Z | //
// Copyright (C) [2020] Futurewei Technologies, Inc.
//
// FORCE-RISCV 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
//
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
// FIT FOR A PARTICULAR PURPOSE.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <lest/lest.hpp>
#include <Log.h>
#include <Random.h>
//------------------------------------------------
// include necessary header files here
//------------------------------------------------
#include <Enums.h>
#include <ThreadGroup.h>
#include <Constraint.h>
#include <ThreadGroupPartitioner.h>
#include <vector>
using text = std::string;
const lest::test specification[] = {
CASE( "Test Thread Group Moderator APIs" ) {
SETUP( "Set up class" ) {
using namespace Force;
ThreadGroupModerator tg_mod(2,2,4); // 2 chip, 2 core and 4 thread
SECTION ("Test default behavior") {
EXPECT(tg_mod.GetThreadGroupId(0) == -1u);
std::vector<uint32> free_threads;
tg_mod.GetFreeThreads(free_threads);
EXPECT(free_threads.size() == 16u);
for (uint32 i = 0u; i < 16u; i++)
EXPECT(free_threads[i] == i);
std::vector<ThreadGroup* > thread_groups;
tg_mod.QueryThreadGroup(-1u, thread_groups);
EXPECT(thread_groups.size() == 0u);
}
SECTION ("Test partition: same chip") {
tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::SameChip);
std::vector<ThreadGroup* > thread_groups;
tg_mod.QueryThreadGroup(-1, thread_groups);
EXPECT(thread_groups.size() == 2u);
EXPECT(thread_groups[0]->GetThreads()->ToSimpleString() == "0x0-0x7");
EXPECT(thread_groups[1]->GetThreads()->ToSimpleString() == "0x8-0xf");
std::vector<uint32> free_threads;
tg_mod.GetFreeThreads(free_threads);
EXPECT(free_threads.size() == 0u);
EXPECT(tg_mod.GetThreadGroupId(7u) == 0u); // thread id 7 belongs to group 0
EXPECT(tg_mod.GetThreadGroupId(8u) == 1u); // thread id 8 belongs to group 1
}
SECTION ("Test partition: same core") {
tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::SameCore);
std::vector<ThreadGroup* > thread_groups;
tg_mod.QueryThreadGroup(-1, thread_groups);
EXPECT(thread_groups.size() == 4u);
EXPECT(thread_groups[0]->GetThreads()->ToSimpleString() == "0x0-0x3");
EXPECT(thread_groups[1]->GetThreads()->ToSimpleString() == "0x4-0x7");
EXPECT(thread_groups[2]->GetThreads()->ToSimpleString() == "0x8-0xb");
EXPECT(thread_groups[3]->GetThreads()->ToSimpleString() == "0xc-0xf");
std::vector<uint32> free_threads;
tg_mod.GetFreeThreads(free_threads);
EXPECT(free_threads.size() == 0u);
EXPECT(tg_mod.GetThreadGroupId(3u) == 0u); // thread id 0 belongs to group 0
EXPECT(tg_mod.GetThreadGroupId(7u) == 1u); // thread id 7 belongs to group 1
EXPECT(tg_mod.GetThreadGroupId(8u) == 2u); // thread id 8 belongs to group 2
EXPECT(tg_mod.GetThreadGroupId(15u) == 3u); // thread id 15 belongs to group 3
}
SECTION ("Test partition: diff chip") {
tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::DiffChip);
std::vector<ThreadGroup* > thread_groups;
tg_mod.QueryThreadGroup(-1, thread_groups);
EXPECT(thread_groups.size() == 8u);
for (unsigned i = 0; i < 8u ; i++) {
auto thread_constr = thread_groups[i]->GetThreads();
LOG(notice) << "Diff chip thread constraint:" << thread_constr->ToSimpleString() << ", group id: " << thread_groups[i]->GetId() << std::endl;
EXPECT(thread_constr->Size() == 2u);
std::vector<uint64> threads;
thread_constr->GetValues(threads);
if (threads[0] < 8u) {
EXPECT(threads[1] >=8u);
EXPECT(threads[1] <= 15u);
}
else
EXPECT(threads[1] < 8u);
}
std::vector<uint32> free_threads;
tg_mod.GetFreeThreads(free_threads);
EXPECT(free_threads.size() == 0u);
}
SECTION ("Test partition: diff core") {
tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::DiffCore);
std::vector<ThreadGroup* > thread_groups;
tg_mod.QueryThreadGroup(-1, thread_groups);
EXPECT(thread_groups.size() == 4u);
for (unsigned i = 0; i < 4u ; i++) {
auto thread_constr = thread_groups[i]->GetThreads();
LOG(notice) << "Diff core thread constraint:" << thread_constr->ToSimpleString() << ", group id: " << thread_groups[i]->GetId() << std::endl;
EXPECT(thread_constr->Size() == 4u);
std::vector<uint64> threads;
thread_constr->GetValues(threads);
EXPECT(threads[0] < 4u);
EXPECT(threads[1] >=4u);
EXPECT(threads[1] < 8u);
EXPECT(threads[2] >= 8u);
EXPECT(threads[2] < 12u);
EXPECT(threads[3] >= 12u);
EXPECT(threads[3] < 16u);
}
std::vector<uint32> free_threads;
tg_mod.GetFreeThreads(free_threads);
EXPECT(free_threads.size() == 0u);
}
SECTION("Test partition: random all") {
PartitionArgument arg(1); // one group
tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::Random, &arg);
std::vector<ThreadGroup* > thread_groups;
tg_mod.QueryThreadGroup(-1, thread_groups);
EXPECT(thread_groups.size() == 1u);
auto thread_constr = thread_groups[0]->GetThreads();
EXPECT(thread_constr->ToSimpleString() == "0x0-0xf");
std::vector<uint32> free_threads;
tg_mod.GetFreeThreads(free_threads);
EXPECT(free_threads.size() == 0u);
}
SECTION("Test partition: random gradual") {
PartitionArgument arg0(2, 2); // 2 groups, 2 threads in a group
tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::Random, &arg0);
std::vector<uint32> free_threads;
tg_mod.GetFreeThreads(free_threads);
EXPECT(free_threads.size() == 12u);
PartitionArgument arg1(4, 1); // 4 groups, 1 thread in a group
tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::Random, &arg1);
free_threads.clear();
tg_mod.GetFreeThreads(free_threads);
EXPECT(free_threads.size() == 8u);
PartitionArgument arg2(2); // 2 groups
tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::Random, &arg2);
free_threads.clear();
tg_mod.GetFreeThreads(free_threads);
EXPECT(free_threads.size() == 0u);
std::vector<ThreadGroup* > thread_groups;
tg_mod.QueryThreadGroup(-1, thread_groups);
EXPECT(thread_groups.size() == 8u);
EXPECT(thread_groups[0]->GetThreads()->Size() == 2u);
EXPECT(thread_groups[2]->GetThreads()->Size() == 1u);
EXPECT(thread_groups[6]->GetThreads()->Size() == 4u);
for (auto thread_group : thread_groups) {
LOG(notice) << "Random gradual group id:" << std::dec << thread_group->GetId() << ", job: " << thread_group->GetJob()
<< ", threads: " << thread_group->GetThreads()->ToSimpleString() << std::endl;
}
}
SECTION("Test Set thread group") {
PartitionArgument arg0(1, 2); // 1 groups with 2 threads
tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::Random, &arg0);
std::vector<ThreadGroup*> thread_groups;
tg_mod.QueryThreadGroup(-1, thread_groups);
EXPECT(thread_groups.size() == 1u);
auto g_id = thread_groups[0]->GetId();
tg_mod.SetThreadGroup(g_id, "Set0", ConstraintSet("2-5"));
EXPECT(thread_groups[0]->GetThreads()->ToSimpleString() == "0x2-0x5");
std::vector<uint32> free_threads;
tg_mod.GetFreeThreads(free_threads);
EXPECT(free_threads.size() == 12u);
EXPECT(tg_mod.GetThreadGroupId(0x2) == g_id);
tg_mod.SetThreadGroup(g_id, "Set1", ConstraintSet("8-10"));
EXPECT(thread_groups[0]->GetThreads()->ToSimpleString() == "0x8-0xa");
free_threads.clear();
tg_mod.GetFreeThreads(free_threads);
EXPECT(free_threads.size() == 13u);
EXPECT(tg_mod.GetThreadGroupId(0x8) == g_id);
EXPECT(tg_mod.GetThreadGroupId(0xa) == g_id);
EXPECT(tg_mod.GetThreadGroupId(0x2) == -1u);
EXPECT(tg_mod.GetThreadGroupId(0x5) == -1u);
}
SECTION("Test set thread group with multiple groups") {
tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::SameChip);
std::vector<ThreadGroup*> thread_groups;
tg_mod.QueryThreadGroup(-1, thread_groups);
ThreadGroup* thread_group_0 = thread_groups[0];
tg_mod.SetThreadGroup(thread_group_0->GetId(), "Set0_0", ConstraintSet("1,3,5"));
const ConstraintSet* group_0_thread_constr = thread_group_0->GetThreads();
EXPECT(group_0_thread_constr->ToSimpleString() == "0x1,0x3,0x5");
std::vector<uint64> group_0_threads;
group_0_thread_constr->GetValues(group_0_threads);
for (uint64 thread : group_0_threads) {
EXPECT(tg_mod.GetThreadGroupId(thread) == thread_group_0->GetId());
}
ThreadGroup* thread_group_1 = thread_groups[1];
tg_mod.SetThreadGroup(thread_group_1->GetId(), "Set1", ConstraintSet("2,4,6-10"));
const ConstraintSet* group_1_thread_constr = thread_group_1->GetThreads();
EXPECT(group_1_thread_constr->ToSimpleString() == "0x2,0x4,0x6-0xa");
std::vector<uint64> group_1_threads;
group_1_thread_constr->GetValues(group_1_threads);
for (uint64 thread : group_1_threads) {
EXPECT(tg_mod.GetThreadGroupId(thread) == thread_group_1->GetId());
}
tg_mod.SetThreadGroup(thread_group_0->GetId(), "Set0_1", ConstraintSet("3,11,13-14"));
group_0_thread_constr = thread_group_0->GetThreads();
EXPECT(group_0_thread_constr->ToSimpleString() == "0x3,0xb,0xd-0xe");
group_0_threads.clear();
group_0_thread_constr->GetValues(group_0_threads);
for (uint64 thread : group_0_threads) {
EXPECT(tg_mod.GetThreadGroupId(thread) == thread_group_0->GetId());
}
std::vector<uint32> free_threads;
tg_mod.GetFreeThreads(free_threads);
EXPECT(free_threads.size() == 5u);
for (uint32 free_thread : free_threads) {
EXPECT(tg_mod.GetThreadGroupId(free_thread) == -1u);
}
}
}
}
};
int main( int argc, char * argv[] )
{
Force::Logger::Initialize();
Force::Random::Initialize();
int ret = lest::run( specification, argc, argv );
Force::Random::Destroy();
Force::Logger::Destroy();
return ret;
}
| 37.776224 | 149 | 0.643003 |
4e1e89ed0e516be46415c2b1cf93c56d4e219c02 | 156 | cpp | C++ | PredPrey_Attempt2/main.cpp | 08jne01/Predator-Prey-Attempt2 | cfb1d259a73d3d038ca122cdf63e231968e93fa9 | [
"MIT"
] | null | null | null | PredPrey_Attempt2/main.cpp | 08jne01/Predator-Prey-Attempt2 | cfb1d259a73d3d038ca122cdf63e231968e93fa9 | [
"MIT"
] | null | null | null | PredPrey_Attempt2/main.cpp | 08jne01/Predator-Prey-Attempt2 | cfb1d259a73d3d038ca122cdf63e231968e93fa9 | [
"MIT"
] | null | null | null | #include "Header.h"
#include "Program.h"
int main()
{
sf::err().rdbuf(NULL);
Program p(700, 700, 2000, 100, 10, 0.0005, 0.01);
return p.mainLoop();
} | 13 | 50 | 0.615385 |
89ecdd94e91e2120da96013ca06296e6a66ffb1d | 5,368 | cpp | C++ | qttools/src/assistant/qhelpconverter/qhpwriter.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qttools/src/assistant/qhelpconverter/qhpwriter.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qttools/src/assistant/qhelpconverter/qhpwriter.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Assistant of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QFile>
#include "qhpwriter.h"
#include "adpreader.h"
QT_BEGIN_NAMESPACE
QhpWriter::QhpWriter(const QString &namespaceName,
const QString &virtualFolder)
{
m_namespaceName = namespaceName;
m_virtualFolder = virtualFolder;
setAutoFormatting(true);
}
void QhpWriter::setAdpReader(AdpReader *reader)
{
m_adpReader = reader;
}
void QhpWriter::setFilterAttributes(const QStringList &attributes)
{
m_filterAttributes = attributes;
}
void QhpWriter::setCustomFilters(const QList<CustomFilter> filters)
{
m_customFilters = filters;
}
void QhpWriter::setFiles(const QStringList &files)
{
m_files = files;
}
void QhpWriter::generateIdentifiers(IdentifierPrefix prefix,
const QString prefixString)
{
m_prefix = prefix;
m_prefixString = prefixString;
}
bool QhpWriter::writeFile(const QString &fileName)
{
QFile out(fileName);
if (!out.open(QIODevice::WriteOnly))
return false;
setDevice(&out);
writeStartDocument();
writeStartElement(QLatin1String("QtHelpProject"));
writeAttribute(QLatin1String("version"), QLatin1String("1.0"));
writeTextElement(QLatin1String("namespace"), m_namespaceName);
writeTextElement(QLatin1String("virtualFolder"), m_virtualFolder);
writeCustomFilters();
writeFilterSection();
writeEndDocument();
out.close();
return true;
}
void QhpWriter::writeCustomFilters()
{
if (!m_customFilters.count())
return;
foreach (const CustomFilter &f, m_customFilters) {
writeStartElement(QLatin1String("customFilter"));
writeAttribute(QLatin1String("name"), f.name);
foreach (const QString &a, f.filterAttributes)
writeTextElement(QLatin1String("filterAttribute"), a);
writeEndElement();
}
}
void QhpWriter::writeFilterSection()
{
writeStartElement(QLatin1String("filterSection"));
foreach (const QString &a, m_filterAttributes)
writeTextElement(QLatin1String("filterAttribute"), a);
writeToc();
writeKeywords();
writeFiles();
writeEndElement();
}
void QhpWriter::writeToc()
{
QList<ContentItem> lst = m_adpReader->contents();
if (lst.isEmpty())
return;
int depth = -1;
writeStartElement(QLatin1String("toc"));
foreach (const ContentItem &i, lst) {
while (depth-- >= i.depth)
writeEndElement();
writeStartElement(QLatin1String("section"));
writeAttribute(QLatin1String("title"), i.title);
writeAttribute(QLatin1String("ref"), i.reference);
depth = i.depth;
}
while (depth-- >= -1)
writeEndElement();
}
void QhpWriter::writeKeywords()
{
QList<KeywordItem> lst = m_adpReader->keywords();
if (lst.isEmpty())
return;
writeStartElement(QLatin1String("keywords"));
foreach (const KeywordItem &i, lst) {
writeEmptyElement(QLatin1String("keyword"));
writeAttribute(QLatin1String("name"), i.keyword);
writeAttribute(QLatin1String("ref"), i.reference);
if (m_prefix == FilePrefix) {
QString str = i.reference.mid(
i.reference.lastIndexOf(QLatin1Char('/'))+1);
str = str.left(str.lastIndexOf(QLatin1Char('.')));
writeAttribute(QLatin1String("id"), str + QLatin1String("::") + i.keyword);
} else if (m_prefix == GlobalPrefix) {
writeAttribute(QLatin1String("id"), m_prefixString + i.keyword);
}
}
writeEndElement();
}
void QhpWriter::writeFiles()
{
if (m_files.isEmpty())
return;
writeStartElement(QLatin1String("files"));
foreach (const QString &f, m_files)
writeTextElement(QLatin1String("file"), f);
writeEndElement();
}
QT_END_NAMESPACE
| 30.327684 | 87 | 0.668219 |
89f4fd7de675c72a755421110bd985e1a7a44779 | 8,401 | cpp | C++ | stromx/runtime/Compare.cpp | uboot/stromx | 5aff42008c576ca4aa9dbb1fdd238dac1d875ece | [
"Apache-2.0"
] | 11 | 2015-08-16T09:59:07.000Z | 2021-06-15T14:39:20.000Z | stromx/runtime/Compare.cpp | uboot/stromx | 5aff42008c576ca4aa9dbb1fdd238dac1d875ece | [
"Apache-2.0"
] | null | null | null | stromx/runtime/Compare.cpp | uboot/stromx | 5aff42008c576ca4aa9dbb1fdd238dac1d875ece | [
"Apache-2.0"
] | 8 | 2015-05-10T02:25:37.000Z | 2020-10-28T13:06:01.000Z | /*
* Copyright 2015 Matthias Fuchs
*
* 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 "stromx/runtime/Compare.h"
#include "stromx/runtime/DataProvider.h"
#include "stromx/runtime/EnumParameter.h"
#include "stromx/runtime/Id2DataComposite.h"
#include "stromx/runtime/Id2DataPair.h"
#include "stromx/runtime/Locale.h"
#include "stromx/runtime/NumericParameter.h"
#include "stromx/runtime/OperatorException.h"
#include "stromx/runtime/ReadAccess.h"
#include "stromx/runtime/Variant.h"
#include "stromx/runtime/VariantComposite.h"
#include <cmath>
namespace stromx
{
namespace runtime
{
const std::string Compare::TYPE("Compare");
const std::string Compare::PACKAGE(STROMX_RUNTIME_PACKAGE_NAME);
const Version Compare::VERSION(STROMX_RUNTIME_VERSION_MAJOR, STROMX_RUNTIME_VERSION_MINOR, STROMX_RUNTIME_VERSION_PATCH);
Compare::Compare()
: OperatorKernel(TYPE, PACKAGE, VERSION, setupInitParameters())
, m_compareToInput(false)
, m_comparisonType(LESS)
, m_value(0.0)
, m_epsilon(1e-6)
{
}
void Compare::setParameter(unsigned int id, const Data& value)
{
try
{
switch(id)
{
case COMPARE_TO_INPUT:
m_compareToInput = data_cast<Bool>(value);
break;
case COMPARISON_TYPE:
m_comparisonType = data_cast<Enum>(value);
break;
case PARAMETER_VALUE:
m_value = data_cast<Float64>(value);
break;
case EPSILON:
m_epsilon = data_cast<Float64>(value);
break;
default:
throw WrongParameterId(id, *this);
}
}
catch(runtime::BadCast&)
{
throw WrongParameterType(parameter(id), *this);
}
}
const DataRef Compare::getParameter(const unsigned int id) const
{
switch(id)
{
case COMPARE_TO_INPUT:
return m_compareToInput;
case COMPARISON_TYPE:
return m_comparisonType;
case PARAMETER_VALUE:
return m_value;
case EPSILON:
return m_epsilon;
default:
throw WrongParameterId(id, *this);
}
}
void Compare::initialize()
{
OperatorKernel::initialize(setupInputs(), setupOutputs(), setupParameters());
}
void Compare::execute(DataProvider& provider)
{
double value1 = 0.0;
double value2 = 0.0;
Id2DataPair number1Mapper(NUMBER_1);
Id2DataPair number2Mapper(NUMBER_2);
if (m_compareToInput)
{
provider.receiveInputData(number1Mapper && number2Mapper);
ReadAccess access1(number1Mapper.data());
ReadAccess access2(number2Mapper.data());
value1 = toDouble(access1.get());
value2 = toDouble(access2.get());
}
else
{
provider.receiveInputData(number1Mapper);
ReadAccess access(number1Mapper.data());
value1 = toDouble(access.get());
value2 = m_value;
}
bool result = false;
switch(m_comparisonType)
{
case LESS:
result = value1 < value2;
break;
case GREATER:
result = value1 > value2;
break;
case LESS_OR_EQUAL:
result = value1 < value2 + m_epsilon;
break;
case GREATER_OR_EQUAL:
result = value1 + m_epsilon > value2;
break;
case EQUAL:
result = std::abs(value1 - value2) < m_epsilon;
break;
case NOT_EQUAL:
result = std::abs(value1 - value2) >= m_epsilon;
break;
default:
throw InternalError("Unsupported comparison type.");
}
DataContainer resultContainer(new Bool(result));
provider.sendOutputData(Id2DataPair(RESULT, resultContainer));
}
const std::vector<const Input*> Compare::setupInputs()
{
std::vector<const Input*> inputs;
if (m_compareToInput)
{
Input* number1 = new Input(NUMBER_1, Variant::INT || Variant::FLOAT);
number1->setTitle(L_("Input 1"));
inputs.push_back(number1);
Input* number2 = new Input(NUMBER_2, Variant::INT || Variant::FLOAT);
number2->setTitle(L_("Number 2"));
inputs.push_back(number2);
}
else
{
Input* number = new Input(NUMBER_1, Variant::INT || Variant::FLOAT);
number->setTitle(L_("Number"));
inputs.push_back(number);
}
return inputs;
}
const std::vector<const Output*> Compare::setupOutputs()
{
std::vector<const Output*> outputs;
Output* result = new Output(RESULT, Variant::BOOL);
result->setTitle(L_("Result"));
outputs.push_back(result);
return outputs;
}
const std::vector<const Parameter*> Compare::setupInitParameters()
{
std::vector<const Parameter*> parameters;
Parameter* compareToInput = new Parameter(COMPARE_TO_INPUT, Variant::BOOL);
compareToInput->setAccessMode(Parameter::NONE_WRITE);
compareToInput->setTitle(L_("Compare to second input"));
parameters.push_back(compareToInput);
return parameters;
}
const std::vector<const Parameter*> Compare::setupParameters()
{
std::vector<const Parameter*> parameters;
EnumParameter* comparisonType = new EnumParameter(COMPARISON_TYPE);
comparisonType->setAccessMode(Parameter::ACTIVATED_WRITE);
comparisonType->setTitle(L_("Comparison type"));
comparisonType->add(EnumDescription(runtime::Enum(LESS), L_("Less")));
comparisonType->add(EnumDescription(runtime::Enum(LESS_OR_EQUAL), L_("Less or equal")));
comparisonType->add(EnumDescription(runtime::Enum(GREATER), L_("Greater")));
comparisonType->add(EnumDescription(runtime::Enum(GREATER_OR_EQUAL), L_("Greater or equal")));
comparisonType->add(EnumDescription(runtime::Enum(EQUAL), L_("Equal")));
comparisonType->add(EnumDescription(runtime::Enum(NOT_EQUAL), L_("Not equal")));
parameters.push_back(comparisonType);
if (! m_compareToInput)
{
NumericParameter<Float64>* parameterValue = new NumericParameter<Float64>(PARAMETER_VALUE);
parameterValue->setAccessMode(Parameter::ACTIVATED_WRITE);
parameterValue->setTitle(L_("Value"));
parameters.push_back(parameterValue);
}
NumericParameter<Float64>* epsilon = new NumericParameter<Float64>(EPSILON);
epsilon->setAccessMode(Parameter::ACTIVATED_WRITE);
epsilon->setTitle(L_("Epsilon"));
epsilon->setMin(Float64(0.0));
parameters.push_back(epsilon);
return parameters;
}
}
}
| 36.211207 | 129 | 0.548268 |
d602d70d3a27518ad0a3ce6df426b00285405dcb | 1,771 | cpp | C++ | compiler/src/Ast/AstDef.cpp | jadedrip/SimpleLang | f39c490e5a41151d1d0d2f8c77c6ce524b7842f0 | [
"BSD-3-Clause"
] | 16 | 2015-03-30T02:46:49.000Z | 2020-07-28T13:36:54.000Z | compiler/src/Ast/AstDef.cpp | jadedrip/SimpleLang | f39c490e5a41151d1d0d2f8c77c6ce524b7842f0 | [
"BSD-3-Clause"
] | 1 | 2020-09-01T09:38:30.000Z | 2020-09-01T09:38:30.000Z | compiler/src/Ast/AstDef.cpp | jadedrip/SimpleLang | f39c490e5a41151d1d0d2f8c77c6ce524b7842f0 | [
"BSD-3-Clause"
] | 2 | 2020-02-07T02:09:48.000Z | 2020-02-19T13:31:35.000Z | #include "stdafx.h"
#include "AstDef.h"
#include "AstContext.h"
#include "AstGetClass.h"
#include "utility.h"
#include "../Type/AutoType.h"
#include "../Type/ClassInstanceType.h"
#include "../CodeGenerate/DefGen.h"
#include "../CodeGenerate/GenList.h"
#include "../CodeGenerate/CastGen.h"
#include "../CodeGenerate/StringLiteGen.h"
#include <exception>
using namespace llvm;
using namespace std;
void AstDef::draw(std::ostream & os)
{
std::string n = "def ";
for (auto &i : vars) {
n += i.first + ",";
}
n.pop_back();
dotLable(os, n);
}
CodeGen * AstDef::makeGen(AstContext * parent)
{
AstType* p = AutoType::isAuto(type) ? nullptr : type;
if (vars.size() == 1) {
auto x=vars.at(0);
auto gen= makeDefGen(parent, p, x.first, x.second);
if (!gen)
throw std::runtime_error("Can't def " + x.first);
parent->setSymbolValue(x.first, gen );
return gen;
}
auto list = new GenList();
for (auto &i : vars) {
auto gen = makeDefGen(parent, p, i.first, i.second);
list->generates.push_back(gen);
parent->setSymbolValue(i.first, gen);
}
return list;
}
static string emptyStr;
CodeGen * AstDef::makeDefGen(AstContext * parent, AstType * type, const std::string& n, AstNode* var)
{
CodeGen* v = var ? var->makeGen(parent) : nullptr;
if (v && !type && v->type->isStructTy())
return v;
llvm::Type* t = nullptr;
LLVMContext& c = parent->context();
auto *a = dynamic_cast<AstGetClass*>(type);
if (a) {
a->context = parent;
// 创建新对象
auto *x = parent->findClass(a->name);
if (x) {
// TODO: 测试 x 类型和 v 一致
if (v) return v;
vector<pair<string, CodeGen*>> args;
return x->makeNew(parent, args);
}
} else if (type) {
t = type->llvmType(parent->context());
} else if (v)
t = v->type;
return new DefGen(n, t, v);
}
| 22.417722 | 101 | 0.640316 |
d6077ea40b8d56f29839f9970ac2762b305a2e24 | 8,750 | cpp | C++ | src/probability.cpp | Michael-Stevens-27/silverblaze | f0f001710589fe072545b00f0d3524fc993f4cbd | [
"MIT"
] | 3 | 2018-03-29T15:54:56.000Z | 2018-10-15T18:28:59.000Z | src/probability.cpp | Michael-Stevens-27/silverblaze | f0f001710589fe072545b00f0d3524fc993f4cbd | [
"MIT"
] | 2 | 2020-02-11T20:44:25.000Z | 2020-06-18T20:00:32.000Z | src/probability.cpp | Michael-Stevens-27/silverblaze | f0f001710589fe072545b00f0d3524fc993f4cbd | [
"MIT"
] | null | null | null |
#include <Rcpp.h>
#include <math.h>
#include "probability.h"
#include "misc.h"
using namespace std;
//------------------------------------------------
// draw a value from an exponential distribution with set rate parameter
double exp1(double rate){
return R::rexp(rate);
}
//------------------------------------------------
// draw a value from a chi squared distribution with set degrees of freedom
double rchisq1(double df){
return R::rchisq(df);
}
//------------------------------------------------
// draw from continuous uniform distribution on interval [0,1)
double runif_0_1() {
return R::runif(0,1);
}
//------------------------------------------------
// draw from continuous uniform distribution on interval [a,b)
double runif1(double a, double b) {
return R::runif(a,b);
}
//------------------------------------------------
// draw from Bernoulli(p) distribution
bool rbernoulli1(double p) {
return R::rbinom(1, p);
}
//------------------------------------------------
// draw from univariate normal distribution
double rnorm1(double mean, double sd) {
return R::rnorm(mean, sd);
}
//------------------------------------------------
// density of univariate normal distribution
double dnorm1(double x, double mean, double sd, bool log_on) {
return R::dnorm(x, mean, sd, log_on);
}
//------------------------------------------------
// density of log-normal distribution
double dlnorm1(double x, double meanlog, double sdlog, bool log_on) {
return R::dlnorm(x, meanlog, sdlog, log_on);
}
//------------------------------------------------
// draw from univariate normal distribution and reflect to interval (a,b)
double rnorm1_interval(double mean, double sd, double a, double b) {
// draw raw value relative to a
double ret = rnorm1(mean, sd) - a;
double interval_difference = b - a;
// std::cout << "Value " << ret << std::endl;
// reflect off boundries at 0 and (b-a)
if (ret < 0 || ret > interval_difference) {
// use multiple reflections to bring into range [-2(b-a), 2(b-a)]
double modded = std::fmod(ret, 2*interval_difference);
// use one more reflection to bring into range [0, (b-a)]
if (modded < 0) {
modded = -1*modded;
}
if (modded > interval_difference) {
modded = 2*interval_difference - modded;
}
ret = modded;
}
// no longer relative to a
ret += a;
// don't let ret equal exactly a or b
if (ret == a) {
ret += UNDERFLO;
} else if (ret == b) {
ret -= UNDERFLO;
}
return ret;
}
//------------------------------------------------
// sample single value from given probability vector (that sums to pSum)
int sample1(vector<double> &p, double pSum) {
double rand = pSum*runif_0_1();
double z = 0;
for (int i=0; i<int(p.size()); i++) {
z += p[i];
if (rand<z) {
return i+1;
}
}
return 0;
}
//------------------------------------------------
// sample single value x that lies between a and b (inclusive) with equal
// probability. Works on positive or negative values of a or b, and works
// irrespective of which of a or b is larger.
int sample2(int a, int b) {
if (a<b) {
return floor(runif1(a, b+1));
} else {
return floor(runif1(b, a+1));
}
}
//------------------------------------------------
// sample a given number of values from a vector without replacement (templated
// for different data types). Note, this function re-arranges the original
// vector (passed in by reference), and the result is stored in the first n
// elements.
// sample3
// DEFINED IN HEADER
//------------------------------------------------
// draw from gamma(shape,rate) distribution
// note all gamma functions from RCPP use a scale parameter in place of a rate,
// for more info see: https://teuder.github.io/rcpp4everyone_en/310_Rmath.html
// this is why all rates are inversed
double rgamma1(double shape, double rate) {
double x = R::rgamma(shape, 1/rate);
// check for zero or infinite values (catches bug present in Visual Studio 2010)
if (x<UNDERFLO) {
x = UNDERFLO;
}
if (x>OVERFLO) {
x = OVERFLO;
}
return x;
}
//------------------------------------------------
// density of gamma(shape,rate) distribution
double dgamma1(double x, double shape, double rate) {
double y = R::dgamma(x, shape, 1/rate, FALSE);
// check for zero or infinite values (catches bug present in Visual Studio 2010)
if (y<UNDERFLO) {
y = UNDERFLO;
}
if (y>OVERFLO) {
y = OVERFLO;
}
return y;
}
//------------------------------------------------
// draw from beta(alpha,beta) distribution
double rbeta1(double shape1, double shape2) {
if (shape1==1 && shape2==1) {
return runif_0_1();
}
return R::rbeta(shape1, shape2);
}
//------------------------------------------------
// probability density of beta(shape1,shape2) distribution
double dbeta1(double x, double shape1, double shape2, bool return_log) {
return R::dbeta(x, shape1, shape2, return_log);
}
//------------------------------------------------
// draw from dirichlet distribution using vector of shape parameters. Return vector of values.
vector<double> rdirichlet1(vector<double> &shapeVec) {
// draw a series of gamma random variables
int n = shapeVec.size();
vector<double> ret(n);
double retSum = 0;
for (int i=0; i<n; i++) {
ret[i] = rgamma1(shapeVec[i], 1.0);
retSum += ret[i];
}
// divide all by the sum
double retSumInv = 1.0/retSum;
for (int i=0; i<n; i++) {
ret[i] *= retSumInv;
}
return(ret);
}
//------------------------------------------------
// draw from dirichlet distribution using bespoke inputs. Outputs are stored in
// x, passed by reference for speed. Shape parameters are equal to alpha+beta,
// where alpha is an integer vector, and beta is a single double.
void rdirichlet2(std::vector<double> &x, std::vector<double> &alpha, double scale_factor) {
int n = x.size();
double xSum = 0;
for (int i = 0; i < n; i++) {
// print(alpha[i]);
x[i] = rgamma1(scale_factor*alpha[i], 1.0);
xSum += x[i];
}
double xSumInv = 1.0/xSum;
// print(scale_factor);
for (int i = 0; i < n; i++) {
x[i] *= xSumInv;
// print(x[i]);
if (x[i] <= UNDERFLO) {
x[i] = UNDERFLO;
}
}
}
//------------------------------------------------
// density of a dirichlet distribution in log space
double ddirichlet(std::vector<double> &x, std::vector<double> &alpha, double scale_factor) {
int n = x.size();
double logSum = 0;
for (int i = 0; i < n; i++) {
logSum += (scale_factor*alpha[i] - 1)*log(x[i]) - lgamma(scale_factor*alpha[i]);
}
return logSum;
}
//------------------------------------------------
// draw from Poisson(rate) distribution
int rpois1(double rate) {
return R::rpois(rate);
}
//------------------------------------------------
// probability mass of Poisson(rate) distribution
double dpois1(int n, double rate, bool returnLog) {
return R::dpois(n,rate,returnLog);
}
//------------------------------------------------
// draw from negative binomial distribution with mean lambda and variance gamma*lambda (gamma must be >1)
int rnbinom1(double lambda, double gamma) {
return R::rnbinom(lambda/(gamma-1), 1/gamma);
}
//------------------------------------------------
// probability mass of negative binomial distribution with mean lambda and
// variance gamma*lambda (gamma must be >1)
double dnbinom1(int n, double lambda, double gamma, bool returnLog) {
return R::dnbinom(n, lambda/(gamma-1), 1/gamma, returnLog);
}
//------------------------------------------------
// probability mass of negative binomial distribution with mean and variance
double dnbinom_mu1(int n, double size, double mean, bool returnLog) {
return R::dnbinom_mu(n, size, mean, returnLog);
}
//------------------------------------------------
// return closest value to a vector of target values
double closest(std::vector<double> const& vec, double value) {
auto const it = std::lower_bound(vec.begin(), vec.end(), value);
if (it == vec.end()) {
return -1;
}
return *it;
}
//------------------------------------------------
// draw from binomial(N,p) distribution
int rbinom1(int N, double p) {
if (p >= 1.0) {
return N;
} else if (p <= 0.0) {
return 0;
}
return R::rbinom(N, p);
}
//------------------------------------------------
// draw from multinomial(N,p) distribution, where p sums to p_sum
void rmultinom1(int N, const vector<double> &p, double p_sum, vector<int> &ret) {
int k = int(p.size());
fill(ret.begin(), ret.end(), 0);
for (int i = 0; i < (k-1); ++i) {
ret[i] = rbinom1(N, p[i] / p_sum);
N -= ret[i];
if (N == 0) {
break;
}
p_sum -= p[i];
}
ret[k-1] = N;
}
| 29.069767 | 105 | 0.551886 |
d609367837cf3353590aa149bec33ad2091ee04c | 386 | cpp | C++ | Chapter13/drills/Drill_01.cpp | JohnWoods11/learning_c- | 094509a4e96518e1aa12205615ca50849932f9fa | [
"Apache-2.0"
] | null | null | null | Chapter13/drills/Drill_01.cpp | JohnWoods11/learning_c- | 094509a4e96518e1aa12205615ca50849932f9fa | [
"Apache-2.0"
] | null | null | null | Chapter13/drills/Drill_01.cpp | JohnWoods11/learning_c- | 094509a4e96518e1aa12205615ca50849932f9fa | [
"Apache-2.0"
] | null | null | null | #include "GUI/Graph.h"
#include "GUI/Simple_window.h"
#include "GUI/std_lib_facilities.h"
#include <iostream>
void drill_1()
{
const Point py(50,50);
Simple_window win(py, 1000, 800, "Drill 1");
win.wait_for_button();
}
int main()
{
try
{
drill_1();
}
catch (...)
{
cout << "MAJOR ERROR!";
return -1;
}
return 0;
} | 14.296296 | 48 | 0.544041 |
d61643ba5639fa71ed176aef294c2198c0a17df3 | 1,207 | cpp | C++ | special/2/2.cpp | 249606097/Cpp-Experiment | 6d97388664f125853193e9d00a1f9ee53ffde21c | [
"MIT"
] | null | null | null | special/2/2.cpp | 249606097/Cpp-Experiment | 6d97388664f125853193e9d00a1f9ee53ffde21c | [
"MIT"
] | null | null | null | special/2/2.cpp | 249606097/Cpp-Experiment | 6d97388664f125853193e9d00a1f9ee53ffde21c | [
"MIT"
] | null | null | null | #include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <ctime>
using namespace std;
bool in_circle(double x, double y);
int main()
{
double e = 0.01;
int n = 1000;
double pi = 100.0;
double residual = 100.0;
int count = 0;
while (residual > e)
{
int m=0;
srand(unsigned(time(0)));
for (int i=0; i<n; i++)
{
int x = rand();
int y = rand();
if (in_circle(double(x)/double(RAND_MAX), double(y)/double(RAND_MAX)))
m += 1;
}
residual = fabs(pi - 4.0 * double(m) / double(n));
if (count == 1)
{
pi = 4.0 * double(m) / double(n);
}
else
{
pi = (pi * count + 4.0 * double(m) / double(n)) / (count + 1);
}
count++;
}
cout << pi << endl;
system("PAUSE");
return 0;
}
bool in_circle(double x, double y)
{
double distance;
bool is_in_circle = false;
distance = (x-0.5)*(x-0.5) + (y-0.5)*(y-0.5);
if (distance<=0.25)
is_in_circle = true;
return is_in_circle;
} | 21.175439 | 83 | 0.451533 |
d61ba495fd2b7c347312e10be17db6a4d5d4f7ad | 3,409 | cpp | C++ | src/system.cpp | MisaghM/Doodle-Jump | 850e529547e83e7a3a0607fea635517bf2e3bcc4 | [
"MIT"
] | 2 | 2021-09-02T20:05:34.000Z | 2021-11-05T19:38:15.000Z | src/system.cpp | MisaghM/Doodle-Jump | 850e529547e83e7a3a0607fea635517bf2e3bcc4 | [
"MIT"
] | null | null | null | src/system.cpp | MisaghM/Doodle-Jump | 850e529547e83e7a3a0607fea635517bf2e3bcc4 | [
"MIT"
] | null | null | null | #include "system.hpp"
#include "enemies/enemy_normal.hpp"
#include "items/spring.hpp"
#include "platforms/platform_breakable.hpp"
#include "platforms/platform_movable.hpp"
#include "platforms/platform_normal.hpp"
#include "spritesheet.hpp"
System::System(Window* win_)
: win_(win_),
menuScene_(&inputMan_),
pauseScene_(&inputMan_) {
scenes_.push_back(&menuScene_);
}
bool System::update() {
inputMan_.reset();
while (win_->has_pending_event()) {
Event e = win_->poll_for_event();
switch (e.get_type()) {
case Event::EventType::QUIT: return false;
case Event::EventType::KEY_PRESS:
inputMan_.keyPressed(e.get_pressed_key());
break;
case Event::EventType::KEY_RELEASE:
inputMan_.keyReleased(e.get_pressed_key());
break;
case Event::EventType::MMOTION:
inputMan_.setMousePos(e.get_mouse_position());
break;
case Event::EventType::LCLICK:
inputMan_.mouseHandle(InputMouse::Lclick);
break;
case Event::EventType::LRELEASE:
inputMan_.mouseHandle(InputMouse::Lrelease);
break;
default: break;
}
}
if (state_ == SceneState::gameover) scenes_[1]->update(win_, deltaTime, this);
return scenes_.back()->update(win_, deltaTime, this);
}
void System::draw() {
if (state_ == SceneState::pause ||
state_ == SceneState::gameover) scenes_[1]->draw(win_);
scenes_.back()->draw(win_);
}
void System::changeScene(SceneState to) {
switch (state_) {
case SceneState::menu:
if (to == SceneState::game) {
state_ = SceneState::game;
makeGameScene();
scenes_.push_back(gameScene_);
}
break;
case SceneState::game:
if (to == SceneState::pause) {
state_ = SceneState::pause;
scenes_.push_back(&pauseScene_);
}
else if (to == SceneState::gameover) {
state_ = SceneState::gameover;
int height = gameScene_->getScoreHeight();
if (height > recordHeight_) recordHeight_ = height;
gameoverScene_ = new GameoverScene(&inputMan_, height, recordHeight_);
scenes_.push_back(gameoverScene_);
}
break;
case SceneState::pause:
if (to == SceneState::game) {
state_ = SceneState::game;
scenes_.pop_back();
}
break;
case SceneState::gameover:
if (to == SceneState::game) {
state_ = SceneState::game;
delete scenes_.back();
scenes_.pop_back();
delete scenes_.back();
scenes_.pop_back();
makeGameScene();
scenes_.push_back(gameScene_);
}
else if (to == SceneState::menu) {
state_ = SceneState::menu;
delete scenes_.back();
scenes_.pop_back();
delete scenes_.back();
scenes_.pop_back();
}
break;
}
}
void System::makeGameScene() {
int doodleWidth = sprite::doodle[sprite::Doodle::LEFT].w;
int doodleHeight = sprite::doodle[sprite::Doodle::LEFT].h;
gameScene_ = new GameScene(&inputMan_,
RectangleF(win_->get_width() / 2 - doodleWidth / 2, win_->get_height() - doodleHeight, doodleWidth, doodleHeight));
} | 30.4375 | 146 | 0.581989 |
d6218f13c6dd06e76f4513ac32ef5a24ea4aa2d7 | 11,137 | cc | C++ | vector.cc | leiii/datamaps | fc134a5f00284feab8a527802cf930e74d351bda | [
"BSD-2-Clause"
] | 197 | 2015-01-13T01:01:35.000Z | 2021-07-22T02:05:00.000Z | vector.cc | thiagoramos23/datamaps | 76e620adabbedabd6866b23b30c145b53bae751e | [
"BSD-2-Clause"
] | 6 | 2015-01-16T15:08:26.000Z | 2018-09-30T07:55:30.000Z | vector.cc | thiagoramos23/datamaps | 76e620adabbedabd6866b23b30c145b53bae751e | [
"BSD-2-Clause"
] | 33 | 2015-04-03T16:00:47.000Z | 2020-10-06T07:25:03.000Z | #include <iostream>
#include <fstream>
#include <string>
#include <zlib.h>
#include "vector_tile.pb.h"
#define XMAX 4096
#define YMAX 4096
extern "C" {
#include "graphics.h"
#include "clip.h"
}
struct line {
int x0;
int y0;
int x1;
int y1;
};
struct point {
int x;
int y;
};
#define MAX_POINTS 10000
struct pointlayer {
struct point *points;
int npoints;
int npalloc;
struct pointlayer *next;
};
struct metapointlayer {
struct pointlayer *pointlayers;
struct pointlayer **used;
long long meta;
struct metapointlayer *next;
};
struct linelayer {
struct line *lines;
int nlines;
int nlalloc;
unsigned char *used;
struct linelayer *next;
};
struct metalinelayer {
struct linelayer *linelayers;
long long meta;
struct metalinelayer *next;
};
class env {
public:
mapnik::vector::tile tile;
mapnik::vector::tile_layer *layer;
mapnik::vector::tile_feature *feature;
int x;
int y;
int cmd_idx;
int cmd;
int length;
struct metapointlayer *metapointlayers;
struct metalinelayer *metalinelayers;
};
#define MOVE_TO 1
#define LINE_TO 2
#define CLOSE_PATH 7
#define CMD_BITS 3
struct graphics {
int width;
int height;
env *e;
};
struct pointlayer *new_pointlayer() {
struct pointlayer *p = (struct pointlayer *) malloc(sizeof(struct pointlayer));
p->npalloc = 1024;
p->npoints = 0;
p->points = (struct point *) malloc(p->npalloc * sizeof(struct point));
p->next = NULL;
return p;
}
struct metapointlayer *new_metapointlayer(long long meta, struct metapointlayer *next) {
struct metapointlayer *mpl = (struct metapointlayer *) malloc(sizeof(struct metapointlayer));
mpl->pointlayers = new_pointlayer();
mpl->meta = meta;
mpl->next = next;
mpl->used = (struct pointlayer **) malloc(256 * 256 * sizeof(struct pointlayer *));
int i;
for (i = 0; i < 256 * 256; i++) {
mpl->used[i] = mpl->pointlayers;
}
return mpl;
}
struct linelayer *new_linelayer() {
struct linelayer *l = (struct linelayer *) malloc(sizeof(struct linelayer));
l->nlalloc = 1024;
l->nlines = 0;
l->lines = (struct line *) malloc(l->nlalloc * sizeof(struct line));
l->next = NULL;
l->used = (unsigned char *) malloc(256 * 256 * sizeof(unsigned char));
return l;
}
struct metalinelayer *new_metalinelayer(long long meta, struct metalinelayer *next) {
struct metalinelayer *mll = (struct metalinelayer*) malloc(sizeof(struct metalinelayer));
mll->linelayers = NULL;
mll->meta = meta;
mll->next = next;
return mll;
}
struct graphics *graphics_init(int width, int height, char **filetype) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
env *e = new env;
e->metalinelayers = NULL;
e->metapointlayers = NULL;
struct graphics *g = (struct graphics *) malloc(sizeof(struct graphics));
g->e = e;
g->width = width;
g->height = height;
*filetype = strdup("pbf");
return g;
}
// from mapnik-vector-tile/src/vector_tile_compression.hpp
static inline int compress(std::string const& input, std::string & output)
{
z_stream deflate_s;
deflate_s.zalloc = Z_NULL;
deflate_s.zfree = Z_NULL;
deflate_s.opaque = Z_NULL;
deflate_s.avail_in = 0;
deflate_s.next_in = Z_NULL;
deflateInit(&deflate_s, Z_DEFAULT_COMPRESSION);
deflate_s.next_in = (Bytef *)input.data();
deflate_s.avail_in = input.size();
size_t length = 0;
do {
size_t increase = input.size() / 2 + 1024;
output.resize(length + increase);
deflate_s.avail_out = increase;
deflate_s.next_out = (Bytef *)(output.data() + length);
int ret = deflate(&deflate_s, Z_FINISH);
if (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR) {
return -1;
}
length += (increase - deflate_s.avail_out);
} while (deflate_s.avail_out == 0);
deflateEnd(&deflate_s);
output.resize(length);
return 0;
}
static void op(env *e, int cmd, int x, int y);
void out(struct graphics *gc, int transparency, double gamma, int invert, int color, int color2, int saturate, int mask, double color_cap, int cie) {
env *e = gc->e;
int i;
e->layer = e->tile.add_layers();
e->layer->set_name("lines");
e->layer->set_version(1);
e->layer->set_extent(XMAX);
e->layer->add_keys("meta", strlen("meta"));
int vals = -1;
struct metalinelayer *mll;
for (mll = e->metalinelayers; mll != NULL; mll = mll->next) {
mapnik::vector::tile_value *tv = e->layer->add_values();
tv->set_int_value(mll->meta);
vals++;
struct linelayer *l;
for (l = mll->linelayers; l != NULL; l = l->next){
e->feature = e->layer->add_features();
e->feature->set_type(mapnik::vector::tile::LineString);
e->feature->add_tags(0); /* key, "meta" */
e->feature->add_tags(vals); /* value */
e->x = 0;
e->y = 0;
e->cmd_idx = -1;
e->cmd = -1;
e->length = 0;
for (i = 0; i < l->nlines; i++) {
// printf("draw %d %d to %d %d\n", e->lines[i].x0, e->lines[i].y0, e->lines[i].x1, e->lines[i].y1);
if (l->lines[i].x0 != e->x || l->lines[i].y0 != e->y || e->length == 0) {
op(e, MOVE_TO, l->lines[i].x0, l->lines[i].y0);
}
op(e, LINE_TO, l->lines[i].x1, l->lines[i].y1);
}
if (e->cmd_idx >= 0) {
//printf("old command: %d %d\n", e->cmd, e->length);
e->feature->set_geometry(e->cmd_idx,
(e->length << CMD_BITS) |
(e->cmd & ((1 << CMD_BITS) - 1)));
}
}
}
//////////////////////////////////
e->layer = e->tile.add_layers();
e->layer->set_name("points");
e->layer->set_version(1);
e->layer->set_extent(XMAX);
e->layer->add_keys("meta", strlen("meta"));
vals = -1;
struct metapointlayer *mpl;
for (mpl = e->metapointlayers; mpl != NULL; mpl = mpl->next) {
mapnik::vector::tile_value *tv = e->layer->add_values();
tv->set_int_value(mpl->meta);
vals++;
struct pointlayer *p;
for (p = mpl->pointlayers; p != NULL; p = p->next) {
if (p->npoints != 0) {
e->feature = e->layer->add_features();
e->feature->set_type(mapnik::vector::tile::LineString);
e->feature->add_tags(0); /* key, "meta" */
e->feature->add_tags(vals); /* value */
e->x = 0;
e->y = 0;
e->cmd_idx = -1;
e->cmd = -1;
e->length = 0;
for (i = 0; i < p->npoints; i++) {
op(e, MOVE_TO, p->points[i].x, p->points[i].y);
op(e, LINE_TO, p->points[i].x + 1, p->points[i].y);
}
if (e->cmd_idx >= 0) {
e->feature->set_geometry(e->cmd_idx,
(e->length << CMD_BITS) |
(e->cmd & ((1 << CMD_BITS) - 1)));
}
}
}
}
//////////////////////////////////
std::string s;
e->tile.SerializeToString(&s);
std::string compressed;
compress(s, compressed);
std::cout << compressed;
}
static void op(env *e, int cmd, int x, int y) {
// printf("%d %d,%d\n", cmd, x, y);
// printf("from cmd %d to %d\n", e->cmd, cmd);
if (cmd != e->cmd) {
if (e->cmd_idx >= 0) {
// printf("old command: %d %d\n", e->cmd, e->length);
e->feature->set_geometry(e->cmd_idx,
(e->length << CMD_BITS) |
(e->cmd & ((1 << CMD_BITS) - 1)));
}
e->cmd = cmd;
e->length = 0;
e->cmd_idx = e->feature->geometry_size();
e->feature->add_geometry(0); // placeholder
}
if (cmd == MOVE_TO || cmd == LINE_TO) {
int dx = x - e->x;
int dy = y - e->y;
// printf("new geom: %d %d\n", x, y);
e->feature->add_geometry((dx << 1) ^ (dx >> 31));
e->feature->add_geometry((dy << 1) ^ (dy >> 31));
e->x = x;
e->y = y;
e->length++;
} else if (cmd == CLOSE_PATH) {
e->length++;
}
}
// http://rosettacode.org/wiki/Bitmap/Bresenham's_line_algorithm#C
int lineused(struct linelayer *l, int x0, int y0, int x1, int y1) {
int dx = abs(x1 - x0), sx = (x0 < x1) ? 1 : -1;
int dy = abs(y1 - y0), sy = (y0 < y1) ? 1 : -1;
int err = ((dx > dy) ? dx : -dy) / 2, e2;
while (1) {
if (x0 == x1 && y0 == y1) {
break;
}
if (x0 >= 0 && y0 >=0 && x0 < 256 && y0 < 256) {
if (l->used[y0 * 256 + x0]) {
return 1;
}
}
e2 = err;
if (e2 > -dx) {
err -= dy;
x0 += sx;
}
if (e2 < dy) {
err += dx;
y0 += sy;
}
}
return 0;
}
// http://rosettacode.org/wiki/Bitmap/Bresenham's_line_algorithm#C
void useline(struct linelayer *l, int x0, int y0, int x1, int y1) {
int dx = abs(x1 - x0), sx = (x0 < x1) ? 1 : -1;
int dy = abs(y1 - y0), sy = (y0 < y1) ? 1 : -1;
int err = ((dx > dy) ? dx : -dy) / 2, e2;
while (1) {
if (x0 == x1 && y0 == y1) {
break;
}
if (x0 >= 0 && y0 >=0 && x0 < 256 && y0 < 256) {
l->used[y0 * 256 + x0] = 1;
}
e2 = err;
if (e2 > -dx) {
err -= dy;
x0 += sx;
}
if (e2 < dy) {
err += dx;
y0 += sy;
}
}
}
int drawClip(double x0, double y0, double x1, double y1, struct graphics *gc, double bright, double hue, long long meta, int antialias, double thick, struct tilecontext *tc) {
double mult = XMAX / gc->width;
int accept = clip(&x0, &y0, &x1, &y1, -1, -1, XMAX / mult + 1, YMAX / mult + 1);
if (accept) {
int xx0 = x0 * mult;
int yy0 = y0 * mult;
int xx1 = x1 * mult;
int yy1 = y1 * mult;
env *e = gc->e;
struct metalinelayer **mll = &(e->metalinelayers);
while (*mll != NULL) {
if ((*mll)->meta == meta) {
break;
}
mll = &((*mll)->next);
}
if (*mll == NULL) {
*mll = new_metalinelayer(meta, *mll);
}
if ((*mll)->linelayers == NULL) {
(*mll)->linelayers = new_linelayer();
}
struct linelayer *l = (*mll)->linelayers;
if (xx0 != xx1 || yy0 != yy1) {
while (l->nlines > MAX_POINTS || lineused(l, x0, y0, x1, y1)) {
if (l->next == NULL) {
l->next = new_linelayer();
}
l = l->next;
}
if (l->nlines + 1 >= l->nlalloc) {
l->nlalloc *= 2;
l->lines = (struct line *) realloc((void *) l->lines, l->nlalloc * sizeof(struct line));
}
useline(l, x0, y0, x1, y1);
l->lines[l->nlines].x0 = xx0;
l->lines[l->nlines].y0 = yy0;
l->lines[l->nlines].x1 = xx1;
l->lines[l->nlines].y1 = yy1;
l->nlines++;
}
}
return 0;
}
void drawPixel(double x, double y, struct graphics *gc, double bright, double hue, long long meta, struct tilecontext *tc) {
x += .5;
y += .5;
double mult = XMAX / gc->width;
int xx = x * mult;
int yy = y * mult;
env *e = gc->e;
int xu = x * 256 / gc->width;
int yu = y * 256 / gc->height;
if (xu < 0) {
xu = 0;
}
if (xu > 255) {
xu = 255;
}
if (yu < 0) {
yu = 0;
}
if (yu > 255) {
yu = 255;
}
struct metapointlayer **mpl = &e->metapointlayers;
while (*mpl != NULL) {
if ((*mpl)->meta == meta) {
break;
}
mpl = &((*mpl)->next);
}
if (*mpl == NULL) {
*mpl = new_metapointlayer(meta, *mpl);
}
struct pointlayer *p = (*mpl)->used[256 * yu + xu];
while (p->npoints >= MAX_POINTS) {
if (p->next == NULL) {
p->next = new_pointlayer();
}
p = p->next;
}
if (p->next == NULL) {
p->next = new_pointlayer();
}
(*mpl)->used[256 * yu + xu] = p->next;
if (p->npoints + 1 >= p->npalloc) {
p->npalloc *= 2;
p->points = (struct point *) realloc((void *) p->points, p->npalloc * sizeof(struct point));
}
p->points[p->npoints].x = xx;
p->points[p->npoints].y = yy;
p->npoints++;
}
void drawBrush(double x, double y, struct graphics *gc, double bright, double brush, double hue, long long meta, int gaussian, struct tilecontext *tc) {
drawPixel(x - .5, y - .5, gc, bright, hue, meta, tc);
}
void setClip(struct graphics *gc, int x, int y, int w, int h) {
}
| 21.966469 | 175 | 0.585885 |
d62204e616f8edb2f0032058d3f6ad907800fbb3 | 1,091 | cc | C++ | test/test_flann.cc | mozuysal/virg-workspace | ff0df41ceb288609c5279a85d9d04dbbc178d33e | [
"BSD-3-Clause"
] | null | null | null | test/test_flann.cc | mozuysal/virg-workspace | ff0df41ceb288609c5279a85d9d04dbbc178d33e | [
"BSD-3-Clause"
] | 3 | 2017-02-07T11:26:33.000Z | 2017-02-07T12:43:41.000Z | test/test_flann.cc | mozuysal/virg-workspace | ff0df41ceb288609c5279a85d9d04dbbc178d33e | [
"BSD-3-Clause"
] | null | null | null | #include "gtest/gtest.h"
#include "flann/flann.hpp"
using flann::Matrix;
using flann::Index;
using flann::LinearIndexParams;
using flann::L2;
using flann::SearchParams;
TEST(flann, linear_index) {
int nn = 2;
float data[4] = { 0.0f, 0.0f,
1.0, 0.5};
Matrix<float> dataset(&data[0], 2, 2);
Index<L2<float> > index(dataset, LinearIndexParams());
index.buildIndex();
float qdata[2] = { 1.0f, 0.0f };
Matrix<float> query(&qdata[0], 1, 2);
Matrix<int> indices(new int[query.rows*nn], query.rows, nn);
Matrix<float> dists(new float[query.rows*nn], query.rows, nn);
index.knnSearch(query, indices, dists, nn, SearchParams());
EXPECT_EQ(1, indices.ptr()[0]);
EXPECT_FLOAT_EQ(0.25f, dists.ptr()[0]);
EXPECT_EQ(0, indices.ptr()[1]);
EXPECT_FLOAT_EQ(1.0f, dists.ptr()[1]);
delete [] indices.ptr();
delete [] dists.ptr();
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 27.275 | 70 | 0.578368 |
d628062af287155a56565c17c207e7965ee5875c | 1,315 | cpp | C++ | COURSE_WHITE/WEEK_2/CONTAINER/Middle_temperature/main.cpp | diekaltesonne/c-plus-plus-modern-development | d569bd20465e76aab97111bcd316cd02ebca41dd | [
"MIT"
] | null | null | null | COURSE_WHITE/WEEK_2/CONTAINER/Middle_temperature/main.cpp | diekaltesonne/c-plus-plus-modern-development | d569bd20465e76aab97111bcd316cd02ebca41dd | [
"MIT"
] | null | null | null | COURSE_WHITE/WEEK_2/CONTAINER/Middle_temperature/main.cpp | diekaltesonne/c-plus-plus-modern-development | d569bd20465e76aab97111bcd316cd02ebca41dd | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
/*
* Даны значения температуры, наблюдавшиеся в течение N подряд идущих дней.
* Найдите номера дней (в нумерации с нуля) со значением температуры выше среднего арифметического за все N дней.
* Гарантируется, что среднее арифметическое значений температуры является целым числом.
* Формат ввода
* Вводится число N, затем N неотрицательных целых чисел — значения температуры в 0-й, 1-й, ... (N−1)-й день.
* Формат вывода
* Первое число K — количество дней, значение температуры в которых выше среднего арифметического. Затем K целых чисел — номера этих дней.
* Реализуйте функцию vector<int> Reversed(const vector<int>& v), возвращающую копию вектора v, в которой числа переставлены в обратном порядке.
*
*/
int main(){
int n;
cin >> n;
vector<int> temperatures(n);
int sum = 0;
for (int& temperature : temperatures) {
cin >> temperature;
sum += temperature;
}
int average = sum / n;
vector<int> result_indices;
for (int i = 0; i < n; ++i) {
if (temperatures[i] > average) {
result_indices.push_back(i);
}
}
cout << result_indices.size() << endl;
for (int result_index : result_indices) {
cout << result_index << " ";
}
cout << endl;
return 0;
}
| 30.581395 | 144 | 0.669202 |
d62869904cc8110964fdb3a0ea0fd9355c5e0066 | 44,630 | cc | C++ | tacacsAuthProxy/src/proxy_server.cc | gkumar78/tacacs_auth_proxy | bffdfde75e67e075e47f345580bd6adbea8930d5 | [
"Apache-2.0"
] | null | null | null | tacacsAuthProxy/src/proxy_server.cc | gkumar78/tacacs_auth_proxy | bffdfde75e67e075e47f345580bd6adbea8930d5 | [
"Apache-2.0"
] | null | null | null | tacacsAuthProxy/src/proxy_server.cc | gkumar78/tacacs_auth_proxy | bffdfde75e67e075e47f345580bd6adbea8930d5 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018-present Open Networking Foundation
* 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 <iostream>
#include <memory>
#include <string>
#include <sstream>
#include <grpcpp/health_check_service_interface.h>
#include <grpcpp/ext/proto_server_reflection_plugin.h>
#include <grpcpp/grpcpp.h>
#include <voltha_protos/openolt.grpc.pb.h>
#include <voltha_protos/tech_profile.grpc.pb.h>
#include <voltha_protos/ext_config.grpc.pb.h>
#include "tacacs_controller.h"
#include "logger.h"
using grpc::Channel;
using grpc::ChannelArguments;
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerWriter;
using grpc::Status;
using grpc::ClientContext;
using namespace std;
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
static Server* ServerInstance;
std::string base64_decode(std::string const& encoded_string);
class ProxyServiceImpl final : public openolt::Openolt::Service {
TaccController *taccController;
unique_ptr<openolt::Openolt::Stub> openoltClientStub;
public:
TacacsContext extractDataFromGrpc(ServerContext* context) {
LOG_F(MAX, "Extracting the gRPC credentials");
const std::multimap<grpc::string_ref, grpc::string_ref> metadata = context->client_metadata();
std::multimap<grpc::string_ref, grpc::string_ref>::const_iterator data_iter = metadata.find("authorization");
TacacsContext tacCtx;
if(data_iter != metadata.end()) {
string str_withBasic((data_iter->second).data(),(data_iter->second).length());
std::string str_withoutBasic = str_withBasic.substr(6);
std::string decoded_str = base64_decode(str_withoutBasic);
int pos = decoded_str.find(":");
tacCtx.username = decoded_str.substr(0,pos);
tacCtx.password = decoded_str.substr(pos+1);
tacCtx.remote_addr = context->peer();
LOG_F(INFO, "Received gRPC credentials username=%s, password=%s from Remote %s", tacCtx.username.c_str(), tacCtx.password.c_str(), tacCtx.remote_addr.c_str());
} else {
LOG_F(WARNING, "Unable to find or extract credentials from incoming gRPC request");
tacCtx.username = "";
}
return tacCtx;
}
Status processTacacsAuth(TacacsContext* tacCtx){
LOG_F(MAX, "Calling Authenticate");
Status status = taccController->Authenticate(tacCtx);
if(status.error_code() == StatusCode::OK) {
LOG_F(MAX, "Calling Authorize");
status = taccController->Authorize(tacCtx);
}
return status;
}
Status DisableOlt(
ServerContext* context,
const openolt::Empty* request,
openolt::Empty* response) override {
LOG_F(INFO, "DisableOlt invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "disableolt";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling DisableOlt");
status = openoltClientStub->DisableOlt(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling DisableOlt");
return openoltClientStub->DisableOlt(&ctx, *request, response);
}
}
Status ReenableOlt(
ServerContext* context,
const openolt::Empty* request,
openolt::Empty* response) override {
LOG_F(INFO, "ReenableOlt invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "reenableolt";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling ReenableOlt");
status = openoltClientStub->ReenableOlt(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling ReenableOlt");
return openoltClientStub->ReenableOlt(&ctx, *request, response);
}
}
Status ActivateOnu(
ServerContext* context,
const openolt::Onu* request,
openolt::Empty* response) override {
LOG_F(INFO, "ActivateOnu invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "activateonu";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling ActivateOnu");
status = openoltClientStub->ActivateOnu(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling ActivateOnu");
return openoltClientStub->ActivateOnu(&ctx, *request, response);
}
}
Status DeactivateOnu(
ServerContext* context,
const openolt::Onu* request,
openolt::Empty* response) override {
LOG_F(INFO, "DeactivateOnu invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "deactivateonu";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling DeactivateOnu");
status = openoltClientStub->DeactivateOnu(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling DeactivateOnu");
return openoltClientStub->DeactivateOnu(&ctx, *request, response);
}
}
Status DeleteOnu(
ServerContext* context,
const openolt::Onu* request,
openolt::Empty* response) override {
LOG_F(INFO, "DeleteOnu invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "deleteonu";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling DeleteOnu");
status = openoltClientStub->DeleteOnu(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling DeleteOnu");
return openoltClientStub->DeleteOnu(&ctx, *request, response);
}
}
Status OmciMsgOut(
ServerContext* context,
const openolt::OmciMsg* request,
openolt::Empty* response) override {
LOG_F(INFO, "OmciMsgOut invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "omcimsgout";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling OmciMsgOut");
status = openoltClientStub->OmciMsgOut(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling OmciMsgOut");
return openoltClientStub->OmciMsgOut(&ctx, *request, response);
}
}
Status OnuPacketOut(
ServerContext* context,
const openolt::OnuPacket* request,
openolt::Empty* response) override {
LOG_F(INFO, "OnuPacketOut invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "onupacketout";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling OnuPacketOut");
status = openoltClientStub->OnuPacketOut(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling OnuPacketOut");
return openoltClientStub->OnuPacketOut(&ctx, *request, response);
}
}
Status UplinkPacketOut(
ServerContext* context,
const openolt::UplinkPacket* request,
openolt::Empty* response) override {
LOG_F(INFO, "UplinkPacketOut invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "uplinkpacketout";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling UplinkPacketOut");
status = openoltClientStub->UplinkPacketOut(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling UplinkPacketOut");
return openoltClientStub->UplinkPacketOut(&ctx, *request, response);
}
}
Status FlowAdd(
ServerContext* context,
const openolt::Flow* request,
openolt::Empty* response) override {
LOG_F(INFO, "FlowAdd invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "flowadd";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling FlowAdd");
status = openoltClientStub->FlowAdd(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling FlowAdd");
return openoltClientStub->FlowAdd(&ctx, *request, response);
}
}
Status FlowRemove(
ServerContext* context,
const openolt::Flow* request,
openolt::Empty* response) override {
LOG_F(INFO, "FlowRemove invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "flowremove";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling FlowRemove");
status = openoltClientStub->FlowRemove(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling FlowRemove");
return openoltClientStub->FlowRemove(&ctx, *request, response);
}
}
Status EnableIndication(
ServerContext* context,
const ::openolt::Empty* request,
ServerWriter<openolt::Indication>* writer) override {
LOG_F(INFO, "EnableIndication invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "enableindication";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling EnableIndication");
std::unique_ptr<ClientReader<openolt::Indication> > reader = openoltClientStub->EnableIndication(&ctx, *request);
openolt::Indication indication;
while( reader->Read(&indication) ) {
LOG_F(INFO, "Sending out Indication type %d", indication.data_case());
if( !writer->Write(indication) ) {
LOG_F(WARNING, "Grpc Stream broken while sending out Indication");
break;
}
}
status = reader->Finish();
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling EnableIndication");
std::unique_ptr<ClientReader<openolt::Indication> > reader = openoltClientStub->EnableIndication(&ctx, *request);
openolt::Indication indication;
while( reader->Read(&indication) ) {
LOG_F(INFO, "Sending out Indication type %d", indication.data_case());
if( !writer->Write(indication) ) {
LOG_F(WARNING, "Grpc Stream broken while sending out Indication");
break;
}
}
return reader->Finish();
}
}
Status HeartbeatCheck(
ServerContext* context,
const openolt::Empty* request,
openolt::Heartbeat* response) override {
LOG_F(INFO, "HeartbeatCheck invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "heartbeatcheck";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling HeartbeatCheck");
status = openoltClientStub->HeartbeatCheck(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling HeartbeatCheck");
return openoltClientStub->HeartbeatCheck(&ctx, *request, response);
}
}
Status EnablePonIf(
ServerContext* context,
const openolt::Interface* request,
openolt::Empty* response) override {
LOG_F(INFO, "EnablePonIf invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "enableponif";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling EnablePonIf");
status = openoltClientStub->EnablePonIf(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling EnablePonIf");
return openoltClientStub->EnablePonIf(&ctx, *request, response);
}
}
Status DisablePonIf(
ServerContext* context,
const openolt::Interface* request,
openolt::Empty* response) override {
LOG_F(INFO, "DisablePonIf invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "disableponif";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling DisablePonIf");
status = openoltClientStub->DisablePonIf(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling DisablePonIf");
return openoltClientStub->DisablePonIf(&ctx, *request, response);
}
}
Status CollectStatistics(
ServerContext* context,
const openolt::Empty* request,
openolt::Empty* response) override {
LOG_F(INFO, "CollectStatistics invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "collectstatistics";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling CollectStatistics");
status = openoltClientStub->CollectStatistics(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling CollectStatistics");
return openoltClientStub->CollectStatistics(&ctx, *request, response);
}
}
Status Reboot(
ServerContext* context,
const openolt::Empty* request,
openolt::Empty* response) override {
LOG_F(INFO, "Reboot invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "reboot";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling Reboot");
status = openoltClientStub->Reboot(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling Reboot");
return openoltClientStub->Reboot(&ctx, *request, response);
}
}
Status GetDeviceInfo(
ServerContext* context,
const openolt::Empty* request,
openolt::DeviceInfo* response) override {
LOG_F(MAX, "GetDeviceInfo invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "getdeviceinfo";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling GetDeviceInfo");
status = openoltClientStub->GetDeviceInfo(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling GetDeviceInfo");
return openoltClientStub->GetDeviceInfo(&ctx, *request, response);
}
}
Status CreateTrafficSchedulers(
ServerContext* context,
const tech_profile::TrafficSchedulers* request,
openolt::Empty* response) override {
LOG_F(INFO, "CreateTrafficSchedulers invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "createtrafficschedulers";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling CreateTrafficSchedulers");
status = openoltClientStub->CreateTrafficSchedulers(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling CreateTrafficSchedulers");
return openoltClientStub->CreateTrafficSchedulers(&ctx, *request, response);
}
}
Status RemoveTrafficSchedulers(
ServerContext* context,
const tech_profile::TrafficSchedulers* request,
openolt::Empty* response) override {
LOG_F(INFO, "RemoveTrafficSchedulers invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "removetrafficschedulers";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling RemoveTrafficSchedulers");
status = openoltClientStub->RemoveTrafficSchedulers(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling RemoveTrafficSchedulers");
return openoltClientStub->RemoveTrafficSchedulers(&ctx, *request, response);
}
}
Status CreateTrafficQueues(
ServerContext* context,
const tech_profile::TrafficQueues* request,
openolt::Empty* response) override {
LOG_F(INFO, "CreateTrafficQueues invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "createtrafficqueues";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling CreateTrafficQueues");
status = openoltClientStub->CreateTrafficQueues(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling CreateTrafficQueues");
return openoltClientStub->CreateTrafficQueues(&ctx, *request, response);
}
}
Status RemoveTrafficQueues(
ServerContext* context,
const tech_profile::TrafficQueues* request,
openolt::Empty* response) override {
LOG_F(INFO, "RemoveTrafficQueues invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "removetrafficqueues";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling RemoveTrafficQueues");
status = openoltClientStub->RemoveTrafficQueues(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling RemoveTrafficQueues");
return openoltClientStub->RemoveTrafficQueues(&ctx, *request, response);
}
}
Status PerformGroupOperation(
ServerContext* context,
const openolt::Group* request,
openolt::Empty* response) override {
LOG_F(INFO, "PerformGroupOperation invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "performgroupoperation";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling PerformGroupOperation");
status = openoltClientStub->PerformGroupOperation(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling PerformGroupOperation");
return openoltClientStub->PerformGroupOperation(&ctx, *request, response);
}
}
Status DeleteGroup(
ServerContext* context,
const openolt::Group* request,
openolt::Empty* response) override {
LOG_F(INFO, "DeleteGroup invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "deletegroup";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling DeleteGroup");
status = openoltClientStub->DeleteGroup(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling DeleteGroup");
return openoltClientStub->DeleteGroup(&ctx, *request, response);
}
}
Status OnuItuPonAlarmSet(
ServerContext* context,
const config::OnuItuPonAlarm* request,
openolt::Empty* response) override {
LOG_F(INFO, "OnuItuPonAlarmSet invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "onuituponalarmset";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling OnuItuPonAlarmSet");
status = openoltClientStub->OnuItuPonAlarmSet(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling OnuItuPonAlarmSet");
return openoltClientStub->OnuItuPonAlarmSet(&ctx, *request, response);
}
}
Status GetLogicalOnuDistanceZero(
ServerContext* context,
const openolt::Onu* request,
openolt::OnuLogicalDistance* response) override {
LOG_F(INFO, "GetLogicalOnuDistanceZero invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "getlogicalonudistancezero";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling GetLogicalOnuDistanceZero");
status = openoltClientStub->GetLogicalOnuDistanceZero(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling GetLogicalOnuDistanceZero");
return openoltClientStub->GetLogicalOnuDistanceZero(&ctx, *request, response);
}
}
Status GetLogicalOnuDistance(
ServerContext* context,
const openolt::Onu* request,
openolt::OnuLogicalDistance* response) override {
LOG_F(INFO, "GetLogicalOnuDistance invoked");
if (taccController->IsTacacsEnabled()) {
TacacsContext tacCtx = extractDataFromGrpc(context);
if (tacCtx.username.empty()) {
return Status(grpc::INVALID_ARGUMENT,"Unable to find or extract credentials from incoming gRPC request");
}
tacCtx.method_name = "getlogicalonudistance";
taccController->StartAccounting(&tacCtx);
Status status = processTacacsAuth(&tacCtx);
if(status.error_code() == StatusCode::OK) {
ClientContext ctx;
LOG_F(INFO, "Calling GetLogicalOnuDistance");
status = openoltClientStub->GetLogicalOnuDistance(&ctx, *request, response);
}
string error_msg = "no error";
if(status.error_code() != StatusCode::OK) {
error_msg = status.error_message();
}
taccController->StopAccounting(&tacCtx, error_msg);
return status;
} else {
ClientContext ctx;
LOG_F(INFO, "Tacacs disabled.. Calling GetLogicalOnuDistance");
return openoltClientStub->GetLogicalOnuDistance(&ctx, *request, response);
}
}
ProxyServiceImpl(TaccController* tacctrl, const char* addr) {
taccController = tacctrl;
LOG_F(INFO, "Creating GRPC Channel to Openolt Agent on %s", addr);
openoltClientStub = openolt::Openolt::NewStub(grpc::CreateChannel(addr, grpc::InsecureChannelCredentials()));
}
};
std::string base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
void RunServer(int argc, char** argv) {
const char* tacacs_server_address = NULL;
const char* tacacs_secure_key = NULL;
bool tacacs_fallback_pass = true;
const char* interface_address = NULL;
const char* openolt_agent_address = NULL;
TaccController* taccController = NULL;
LOG_F(INFO, "Starting up TACACS Proxy");
for (int i = 1; i < argc; ++i) {
if(strcmp(argv[i-1], "--tacacs_server_address") == 0 ) {
tacacs_server_address = argv[i];
} else if(strcmp(argv[i-1], "--tacacs_secure_key") == 0 ) {
tacacs_secure_key = argv[i];
} else if(strcmp(argv[i-1], "--tacacs_fallback_pass") == 0 ) {
tacacs_fallback_pass = ( *argv[i] == '0') ? false : true;
} else if(strcmp(argv[i-1], "--interface_address") == 0 ) {
interface_address = argv[i];
} else if(strcmp(argv[i-1], "--openolt_agent_address") == 0 ) {
openolt_agent_address = argv[i];
}
}
if(!interface_address || interface_address == ""){
LOG_F(FATAL, "Server Interface Bind address is missing. TACACS Proxy startup failed");
return;
}
if(!openolt_agent_address || openolt_agent_address == ""){
LOG_F(FATAL, "Openolt Agent address is missing. TACACS Proxy startup failed");
return;
}
if(!tacacs_server_address || tacacs_server_address == ""){
LOG_F(WARNING, "TACACS+ Server address is missing. TACACS+ AAA will be disabled");
}
LOG_F(INFO, "TACACS+ Server configured as %s", tacacs_server_address);
LOG_F(INFO, "TACACS Fallback configured as %s", tacacs_fallback_pass ? "PASS": "FAIL");
if(!tacacs_secure_key){
LOG_F(ERROR, "TACACS Secure Key is missing. No encryption will be used for TACACS channel");
tacacs_secure_key = "";
}
LOG_F(MAX, "Creating TaccController");
taccController = new TaccController(tacacs_server_address, tacacs_secure_key, tacacs_fallback_pass);
LOG_F(MAX, "Creating Proxy Server");
ProxyServiceImpl service(taccController, openolt_agent_address);
grpc::EnableDefaultHealthCheckService(true);
ServerBuilder builder;
LOG_F(INFO, "Starting Proxy Server");
builder.AddListeningPort(interface_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service);
std::unique_ptr<Server> server(builder.BuildAndStart());
ServerInstance = server.get();
LOG_F(INFO, "TACACS Proxy listening on %s", interface_address);
server->Wait();
}
void StopServer(int signum) {
LOG_F(INFO, "Received Signal %d", signum);
if( ServerInstance != NULL ) {
LOG_F(INFO, "Shutting down TACACS Proxy");
ServerInstance->Shutdown();
}
exit(0);
}
| 39.741763 | 171 | 0.588438 |
d62dd8cb0d504f37e451cdaf048bda0c3a22a3cc | 6,116 | cpp | C++ | src/jet/grid_forward_euler_diffusion_solver3.cpp | PavelBlend/fluid-engine-dev | 45b4bdbdb4c6d8c0beebc682180469198203b0ef | [
"MIT"
] | 1,355 | 2016-05-08T07:29:22.000Z | 2022-03-30T13:59:35.000Z | src/jet/grid_forward_euler_diffusion_solver3.cpp | Taiyuan-Zhang/fluid-engine-dev | 45b4bdbdb4c6d8c0beebc682180469198203b0ef | [
"MIT"
] | 208 | 2016-05-25T19:47:27.000Z | 2022-01-17T04:18:29.000Z | src/jet/grid_forward_euler_diffusion_solver3.cpp | Taiyuan-Zhang/fluid-engine-dev | 45b4bdbdb4c6d8c0beebc682180469198203b0ef | [
"MIT"
] | 218 | 2016-08-23T16:51:10.000Z | 2022-03-31T03:55:48.000Z | // Copyright (c) 2018 Doyub Kim
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include <pch.h>
#include <jet/fdm_utils.h>
#include <jet/grid_forward_euler_diffusion_solver3.h>
#include <jet/level_set_utils.h>
using namespace jet;
static const char kFluid = 0;
static const char kAir = 1;
static const char kBoundary = 2;
template <typename T>
T laplacian(
const ConstArrayAccessor3<T>& data,
const Array3<char>& marker,
const Vector3D& gridSpacing,
size_t i,
size_t j,
size_t k) {
const T center = data(i, j, k);
const Size3 ds = data.size();
JET_ASSERT(i < ds.x && j < ds.y && k < ds.z);
T dleft = zero<T>();
T dright = zero<T>();
T ddown = zero<T>();
T dup = zero<T>();
T dback = zero<T>();
T dfront = zero<T>();
if (i > 0 && marker(i - 1, j, k) == kFluid) {
dleft = center - data(i - 1, j, k);
}
if (i + 1 < ds.x && marker(i + 1, j, k) == kFluid) {
dright = data(i + 1, j, k) - center;
}
if (j > 0 && marker(i, j - 1, k) == kFluid) {
ddown = center - data(i, j - 1, k);
}
if (j + 1 < ds.y && marker(i, j + 1, k) == kFluid) {
dup = data(i, j + 1, k) - center;
}
if (k > 0 && marker(i, j, k - 1) == kFluid) {
dback = center - data(i, j, k - 1);
}
if (k + 1 < ds.z && marker(i, j, k + 1) == kFluid) {
dfront = data(i, j, k + 1) - center;
}
return (dright - dleft) / square(gridSpacing.x)
+ (dup - ddown) / square(gridSpacing.y)
+ (dfront - dback) / square(gridSpacing.z);
}
GridForwardEulerDiffusionSolver3::GridForwardEulerDiffusionSolver3() {
}
void GridForwardEulerDiffusionSolver3::solve(
const ScalarGrid3& source,
double diffusionCoefficient,
double timeIntervalInSeconds,
ScalarGrid3* dest,
const ScalarField3& boundarySdf,
const ScalarField3& fluidSdf) {
auto src = source.constDataAccessor();
Vector3D h = source.gridSpacing();
auto pos = source.dataPosition();
buildMarkers(source.resolution(), pos, boundarySdf, fluidSdf);
source.parallelForEachDataPointIndex(
[&](size_t i, size_t j, size_t k) {
if (_markers(i, j, k) == kFluid) {
(*dest)(i, j, k)
= source(i, j, k)
+ diffusionCoefficient
* timeIntervalInSeconds
* laplacian(src, _markers, h, i, j, k);
} else {
(*dest)(i, j, k) = source(i, j, k);
}
});
}
void GridForwardEulerDiffusionSolver3::solve(
const CollocatedVectorGrid3& source,
double diffusionCoefficient,
double timeIntervalInSeconds,
CollocatedVectorGrid3* dest,
const ScalarField3& boundarySdf,
const ScalarField3& fluidSdf) {
auto src = source.constDataAccessor();
Vector3D h = source.gridSpacing();
auto pos = source.dataPosition();
buildMarkers(source.resolution(), pos, boundarySdf, fluidSdf);
source.parallelForEachDataPointIndex(
[&](size_t i, size_t j, size_t k) {
if (_markers(i, j, k) == kFluid) {
(*dest)(i, j, k)
= src(i, j, k)
+ diffusionCoefficient
* timeIntervalInSeconds
* laplacian(src, _markers, h, i, j, k);
} else {
(*dest)(i, j, k) = source(i, j, k);
}
});
}
void GridForwardEulerDiffusionSolver3::solve(
const FaceCenteredGrid3& source,
double diffusionCoefficient,
double timeIntervalInSeconds,
FaceCenteredGrid3* dest,
const ScalarField3& boundarySdf,
const ScalarField3& fluidSdf) {
auto uSrc = source.uConstAccessor();
auto vSrc = source.vConstAccessor();
auto wSrc = source.wConstAccessor();
auto u = dest->uAccessor();
auto v = dest->vAccessor();
auto w = dest->wAccessor();
auto uPos = source.uPosition();
auto vPos = source.vPosition();
auto wPos = source.wPosition();
Vector3D h = source.gridSpacing();
buildMarkers(source.uSize(), uPos, boundarySdf, fluidSdf);
source.parallelForEachUIndex(
[&](size_t i, size_t j, size_t k) {
if (!isInsideSdf(boundarySdf.sample(uPos(i, j, k)))) {
u(i, j, k)
= uSrc(i, j, k)
+ diffusionCoefficient
* timeIntervalInSeconds
* laplacian3(uSrc, h, i, j, k);
}
});
buildMarkers(source.vSize(), vPos, boundarySdf, fluidSdf);
source.parallelForEachVIndex(
[&](size_t i, size_t j, size_t k) {
if (!isInsideSdf(boundarySdf.sample(vPos(i, j, k)))) {
v(i, j, k)
= vSrc(i, j, k)
+ diffusionCoefficient
* timeIntervalInSeconds
* laplacian3(vSrc, h, i, j, k);
}
});
buildMarkers(source.wSize(), wPos, boundarySdf, fluidSdf);
source.parallelForEachWIndex(
[&](size_t i, size_t j, size_t k) {
if (!isInsideSdf(boundarySdf.sample(wPos(i, j, k)))) {
w(i, j, k)
= wSrc(i, j, k)
+ diffusionCoefficient
* timeIntervalInSeconds
* laplacian3(wSrc, h, i, j, k);
}
});
}
void GridForwardEulerDiffusionSolver3::buildMarkers(
const Size3& size,
const std::function<Vector3D(size_t, size_t, size_t)>& pos,
const ScalarField3& boundarySdf,
const ScalarField3& fluidSdf) {
_markers.resize(size);
_markers.forEachIndex(
[&](size_t i, size_t j, size_t k) {
if (isInsideSdf(boundarySdf.sample(pos(i, j, k)))) {
_markers(i, j, k) = kBoundary;
} else if (isInsideSdf(fluidSdf.sample(pos(i, j, k)))) {
_markers(i, j, k) = kFluid;
} else {
_markers(i, j, k) = kAir;
}
});
}
| 31.045685 | 72 | 0.552158 |
d6320ffbbb1fd3681cb234be4d0f345d770834d1 | 3,724 | cpp | C++ | vnext/Microsoft.ReactNative/ReactNativeHost.cpp | tom-un/react-native-windows | c09b55cce76604fe0b379b10206a974915dafc25 | [
"MIT"
] | 2 | 2021-09-05T18:12:44.000Z | 2021-09-06T02:08:25.000Z | vnext/Microsoft.ReactNative/ReactNativeHost.cpp | zchronoz/react-native-windows | 111b727c50b4349b60ffe98f7ff70d487624add3 | [
"MIT"
] | 2 | 2021-05-09T03:34:28.000Z | 2021-09-02T14:49:43.000Z | vnext/Microsoft.ReactNative/ReactNativeHost.cpp | t0rr3sp3dr0/react-native-windows | 5ed2c5626fb2d126022ba215a71a1cb92f7337b3 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "pch.h"
#include "ReactNativeHost.h"
#include "ReactNativeHost.g.cpp"
#include "ReactInstanceManager.h"
#include "ReactInstanceManagerBuilder.h"
#include "ReactInstanceSettings.h"
#include "ReactRootView.h"
#include "ReactSupport.h"
#include <NativeModuleProvider.h>
#include <ViewManager.h>
#include <ViewManagerProvider.h>
using namespace winrt;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
namespace winrt::Microsoft::ReactNative::implementation {
ReactNativeHost::ReactNativeHost() noexcept {
Init();
}
void ReactNativeHost::Init() noexcept {
#if _DEBUG
facebook::react::InitializeLogging([](facebook::react::RCTLogLevel /*logLevel*/, const char *message) {
std::string str = std::string("ReactNative:") + message;
OutputDebugStringA(str.c_str());
});
#endif
}
Microsoft::ReactNative::ReactInstanceManager ReactNativeHost::CreateReactInstanceManager() noexcept {
auto builder = ReactInstanceManagerBuilder();
builder.InstanceSettings(InstanceSettings());
builder.UseDeveloperSupport(UseDeveloperSupport());
builder.InitialLifecycleState(LifecycleState::BeforeCreate);
builder.JavaScriptBundleFile(JavaScriptBundleFile());
builder.JavaScriptMainModuleName(JavaScriptMainModuleName());
builder.PackageProviders(PackageProviders().GetView());
return builder.Build();
}
std::shared_ptr<ReactRootView> ReactNativeHost::CreateRootView() noexcept {
auto rootView = std::make_shared<ReactRootView>();
return rootView;
}
Microsoft::ReactNative::ReactInstanceManager ReactNativeHost::ReactInstanceManager() noexcept {
if (m_reactInstanceManager == nullptr) {
m_reactInstanceManager = CreateReactInstanceManager();
}
return m_reactInstanceManager;
}
UIElement ReactNativeHost::GetOrCreateRootView(IInspectable initialProps) noexcept {
if (m_reactRootView != nullptr) {
return *m_reactRootView;
}
folly::dynamic props = Microsoft::ReactNative::Bridge::ConvertToDynamic(initialProps);
m_reactRootView = CreateRootView();
assert(m_reactRootView != nullptr);
m_reactRootView->OnCreate(*this);
m_reactRootView->StartReactApplicationAsync(ReactInstanceManager(), MainComponentName(), props);
return *m_reactRootView;
}
auto ReactNativeHost::InstanceSettings() noexcept -> Microsoft::ReactNative::ReactInstanceSettings {
if (!m_instanceSettings) {
m_instanceSettings = make<ReactInstanceSettings>();
m_instanceSettings.UseWebDebugger(false);
m_instanceSettings.UseLiveReload(true);
m_instanceSettings.UseJsi(true);
m_instanceSettings.EnableDeveloperMenu(REACT_DEFAULT_ENABLE_DEVELOPER_MENU);
}
return m_instanceSettings;
}
auto ReactNativeHost::PackageProviders() noexcept -> IVector<IReactPackageProvider> {
if (!m_packageProviders) {
m_packageProviders = single_threaded_vector<IReactPackageProvider>();
}
return m_packageProviders;
}
void ReactNativeHost::OnSuspend() noexcept {
if (HasInstance()) {
ReactInstanceManager().OnSuspend();
}
}
void ReactNativeHost::OnEnteredBackground() noexcept {
if (HasInstance()) {
ReactInstanceManager().OnEnteredBackground();
}
}
void ReactNativeHost::OnLeavingBackground() noexcept {
if (HasInstance()) {
ReactInstanceManager().OnLeavingBackground();
}
}
void ReactNativeHost::OnResume(Microsoft::ReactNative::OnResumeAction const &action) noexcept {
if (HasInstance()) {
ReactInstanceManager().OnResume(action);
}
}
} // namespace winrt::Microsoft::ReactNative::implementation
| 30.276423 | 106 | 0.747046 |
d6327b91a4596af3d13cdd3bb03e3b3689b79565 | 1,535 | cpp | C++ | app/src/main/cpp/native-lib.cpp | shahazzat/Python-Android | 41716e1960ab5b7ddb0dffe28567ae0f09e089ab | [
"MIT"
] | 1 | 2021-08-05T13:43:45.000Z | 2021-08-05T13:43:45.000Z | beeware/GaitAnalyzer/gaitanalyzer/android/gradle/Gait Analyzer/app/src/main/cpp/native-lib.cpp | gait-analyzer/GaitMonitoringForParkinsonsDiseasePatients | 2064375ddc36bf38f3ff65f09e776328b8b4612a | [
"MIT"
] | null | null | null | beeware/GaitAnalyzer/gaitanalyzer/android/gradle/Gait Analyzer/app/src/main/cpp/native-lib.cpp | gait-analyzer/GaitMonitoringForParkinsonsDiseasePatients | 2064375ddc36bf38f3ff65f09e776328b8b4612a | [
"MIT"
] | null | null | null | #include <jni.h>
#include <string>
#include <android/log.h>
#include <unistd.h>
#include <pthread.h>
// Inspired by https://codelab.wordpress.com/2014/11/03/how-to-use-standard-output-streams-for-logging-in-android-apps/
static int pfd[2];
static pthread_t thr;
static const char *tag = "stdio";
static void *android_logging_thread_func(void *ignored) {
__android_log_write(ANDROID_LOG_DEBUG, tag,
"Starting to capture stdout/stderr to Android log.");
ssize_t read_size;
char buf[PAGE_SIZE];
while ((read_size = read(pfd[0], buf, sizeof buf - 1)) > 0) {
if (buf[read_size - 1] == '\n')
--read_size;
buf[read_size] = '\0'; /* add null-terminator */
__android_log_write(ANDROID_LOG_DEBUG, tag, buf);
}
return 0;
}
int android_logging_start_logger() {
/* make stdout line-buffered and stderr unbuffered */
setvbuf(stdout, 0, _IOLBF, 0);
setvbuf(stderr, 0, _IONBF, 0);
/* create the pipe and redirect stdout and stderr */
pipe(pfd);
dup2(pfd[1], 1);
dup2(pfd[1], 2);
/* start the logging thread */
if (pthread_create(&thr, 0, android_logging_thread_func, 0) == -1)
return -1;
pthread_detach(thr);
printf("stdout now successfully routes into the stdio logger.\n");
return 0;
}
extern "C" JNIEXPORT jboolean JNICALL
Java_org_beeware_android_MainActivity_captureStdoutStderr(
JNIEnv *env,
jobject /* this */) {
return static_cast<jboolean>(android_logging_start_logger());
}
| 30.098039 | 119 | 0.658632 |
d63398010a208af19e5347957d12dcf82055b812 | 698 | cpp | C++ | Utils/StringUtils.cpp | paulross80/myoga-utils | ecdff503690bb0b3a521e7af66bb84dfbd899799 | [
"MIT"
] | null | null | null | Utils/StringUtils.cpp | paulross80/myoga-utils | ecdff503690bb0b3a521e7af66bb84dfbd899799 | [
"MIT"
] | null | null | null | Utils/StringUtils.cpp | paulross80/myoga-utils | ecdff503690bb0b3a521e7af66bb84dfbd899799 | [
"MIT"
] | null | null | null | #include <stdexcept>
#include <algorithm>
#include <cctype>
#include "StringUtils.hpp"
namespace myoga
{
// String to lowercase
auto lowercase(std::string_view str) -> std::string
{
std::string ret(str);
for (std::size_t i = 0U; i < ret.length(); i++)
ret[i] = charToLower(ret[i]);
return ret;
}
// String -> Boolean
auto boolFromStr(std::string_view str) -> bool
{
// Why this always returns false???
//std::istringstream(value.data()) >> std::boolalpha >> boolValue;
auto lowTrim = myoga::lowercase(myoga::trimStr(str.substr(0, 5))); // "false" -> 5 chars
if (lowTrim == "1" || lowTrim == "true")
return true;
return false;
}
} // myoga
| 19.388889 | 93 | 0.617479 |
d634459a8057739295b11d8375cfb44714bf6d9b | 4,816 | cpp | C++ | motif4struct_bin.cpp | devuci/bct-cpp | bbb33f476bffbb5669e051841f00c3241f4d6f69 | [
"MIT"
] | null | null | null | motif4struct_bin.cpp | devuci/bct-cpp | bbb33f476bffbb5669e051841f00c3241f4d6f69 | [
"MIT"
] | null | null | null | motif4struct_bin.cpp | devuci/bct-cpp | bbb33f476bffbb5669e051841f00c3241f4d6f69 | [
"MIT"
] | null | null | null | #include "bct.h"
/*
* Counts occurrences of four-node structural motifs in a binary graph.
*/
VECTOR_T* BCT_NAMESPACE::motif4struct_bin(const MATRIX_T* A, MATRIX_T** F) {
if (safe_mode) check_status(A, SQUARE | BINARY, "motif4struct_bin");
// load motif34lib M4n ID4
VECTOR_T* ID4;
MATRIX_T* M4 = motif4generate(&ID4);
// n=length(A);
int n = length(A);
// F=zeros(199,n);
if (F != NULL) {
*F = zeros(199, n);
}
// f=zeros(199,1);
VECTOR_T* f = zeros_vector(199);
// As=A|A.';
MATRIX_T* A_transpose = MATRIX_ID(alloc)(A->size2, A->size1);
MATRIX_ID(transpose_memcpy)(A_transpose, A);
MATRIX_T* As = logical_or(A, A_transpose);
MATRIX_ID(free)(A_transpose);
// for u=1:n-3
for (int u = 0; u < n - 3; u++) {
// V1=[false(1,u) As(u,u+1:n)];
VECTOR_T* V1 = VECTOR_ID(alloc)(n);
MATRIX_ID(get_row)(V1, As, u);
for (int i = 0; i <= u; i++) {
VECTOR_ID(set)(V1, i, 0.0);
}
// for v1=find(V1)
VECTOR_T* find_V1 = find(V1);
if (find_V1 != NULL) {
for (int i_find_V1 = 0; i_find_V1 < (int)find_V1->size; i_find_V1++) {
int v1 = (int)VECTOR_ID(get)(find_V1, i_find_V1);
// V2=[false(1,u) As(v1,u+1:n)];
VECTOR_T* V2 = VECTOR_ID(alloc)(n);
MATRIX_ID(get_row)(V2, As, v1);
for (int i = 0; i <= u; i++) {
VECTOR_ID(set)(V2, i, 0.0);
}
// V2(V1)=0;
logical_index_assign(V2, V1, 0.0);
// V2=V2|([false(1,v1) As(u,v1+1:n)]);
VECTOR_T* V2_1 = V2;
VECTOR_T* V2_2 = VECTOR_ID(alloc)(n);
MATRIX_ID(get_row)(V2_2, As, u);
for (int i = 0; i <= v1; i++) {
VECTOR_ID(set)(V2_2, i, 0.0);
}
V2 = logical_or(V2_1, V2_2);
VECTOR_ID(free)(V2_1);
VECTOR_ID(free)(V2_2);
// for v2=find(V2)
VECTOR_T* find_V2 = find(V2);
if (find_V2 != NULL) {
for (int i_find_V2 = 0; i_find_V2 < (int)find_V2->size; i_find_V2++) {
int v2 = (int)VECTOR_ID(get)(find_V2, i_find_V2);
// vz=max(v1,v2);
int vz = (v1 > v2) ? v1 : v2;
// V3=([false(1,u) As(v2,u+1:n)]);
VECTOR_T* V3 = VECTOR_ID(alloc)(n);
MATRIX_ID(get_row)(V3, As, v2);
for (int i = 0; i <= u; i++) {
VECTOR_ID(set)(V3, i, 0.0);
}
// V3(V2)=0;
logical_index_assign(V3, V2, 0.0);
// V3=V3|([false(1,v2) As(v1,v2+1:n)]);
VECTOR_T* V3_1 = V3;
VECTOR_T* V3_2 = VECTOR_ID(alloc)(n);
MATRIX_ID(get_row)(V3_2, As, v1);
for (int i = 0; i <= v2; i++) {
VECTOR_ID(set)(V3_2, i, 0.0);
}
V3 = logical_or(V3_1, V3_2);
VECTOR_ID(free)(V3_1);
VECTOR_ID(free)(V3_2);
// V3(V1)=0;
logical_index_assign(V3, V1, 0.0);
// V3=V3|([false(1,vz) As(u,vz+1:n)]);
V3_1 = V3;
V3_2 = VECTOR_ID(alloc)(n);
MATRIX_ID(get_row)(V3_2, As, u);
for (int i = 0; i <= vz; i++) {
VECTOR_ID(set)(V3_2, i, 0.0);
}
V3 = logical_or(V3_1, V3_2);
VECTOR_ID(free)(V3_1);
VECTOR_ID(free)(V3_2);
// for v3=find(V3)
VECTOR_T* find_V3 = find(V3);
if (find_V3 != NULL ) {
for (int i_find_V3 = 0; i_find_V3 < (int)find_V3->size; i_find_V3++) {
int v3 = (int)VECTOR_ID(get)(find_V3, i_find_V3);
// s=uint32(sum(10.^(11:-1:0).*[A(v1,u) A(v2,u) A(v3,u) A(u,v1) A(v2,v1) A(v3,v1) A(u,v2) A(v1,v2) A(v3,v2) A(u,v3) A(v1,v3) A(v2,v3)]));
int A_rows[] = { v1, v2, v3, u, v2, v3, u, v1, v3, u, v1, v2 };
int A_cols[] = { u, u, u, v1, v1, v1, v2, v2, v2, v3, v3, v3 };
VECTOR_T* s = VECTOR_ID(alloc)(12);
for (int i = 0; i < 12; i++) {
VECTOR_ID(set)(s, i, MATRIX_ID(get)(A, A_rows[i], A_cols[i]));
}
// ind=ID4(s==M4n);
int i_M4 = 0;
for ( ; i_M4 < (int)M4->size1; i_M4++) {
VECTOR_ID(view) M4_row_i_M4 = MATRIX_ID(row)(M4, i_M4);
if (compare_vectors(s, &M4_row_i_M4.vector) == 0) {
break;
}
}
VECTOR_ID(free)(s);
if (i_M4 < (int)M4->size1) {
int ind = (int)VECTOR_ID(get)(ID4, i_M4) - 1;
// if nargout==2; F(ind,[u v1 v2 v3])=F(ind,[u v1 v2 v3])+1; end
if (F != NULL) {
int F_cols[] = { u, v1, v2, v3 };
for (int i = 0; i < 4; i++) {
MATRIX_ID(set)(*F, ind, F_cols[i], MATRIX_ID(get)(*F, ind, F_cols[i]) + 1.0);
}
}
// f(ind)=f(ind)+1;
VECTOR_ID(set)(f, ind, VECTOR_ID(get)(f, ind) + 1.0);
}
}
VECTOR_ID(free)(find_V3);
}
VECTOR_ID(free)(V3);
}
VECTOR_ID(free)(find_V2);
}
VECTOR_ID(free)(V2);
}
VECTOR_ID(free)(find_V1);
}
VECTOR_ID(free)(V1);
}
VECTOR_ID(free)(ID4);
MATRIX_ID(free)(M4);
MATRIX_ID(free)(As);
return f;
}
| 27.83815 | 145 | 0.508721 |
d64117aa915e6ae0b088b4a29488fb5f0d38fad0 | 285 | cpp | C++ | Primer/Trials/check.cpp | siddheshpai/hello-world | 291456962d46c6ce857d75be86bc23634625925f | [
"Apache-2.0"
] | null | null | null | Primer/Trials/check.cpp | siddheshpai/hello-world | 291456962d46c6ce857d75be86bc23634625925f | [
"Apache-2.0"
] | null | null | null | Primer/Trials/check.cpp | siddheshpai/hello-world | 291456962d46c6ce857d75be86bc23634625925f | [
"Apache-2.0"
] | 1 | 2020-05-30T04:30:16.000Z | 2020-05-30T04:30:16.000Z | #include <iostream>
int main()
{
int n = 5;
void *p = &n;
int *pi = static_cast<int*>(p);
++*pi;
std::cout << *pi << std::endl;
//Checking ref to const
std::string const &s = "9-99-999-9999";
std::cout << s << std::endl;
return 0;
}
| 15.833333 | 43 | 0.477193 |
d64493de84c9e0f4f5f00dcbf845a5fd22bea3d7 | 1,798 | cxx | C++ | dicom2rawiv/zipextract/gdcm-2.6.3/Testing/Source/Common/Cxx/TestDirectory.cxx | chipbuster/skull-atlas | 7f3ee009e1d5f65f101fe853a2cf6e12662970ee | [
"BSD-3-Clause"
] | 47 | 2020-03-30T14:36:46.000Z | 2022-03-06T07:44:54.000Z | dicom2rawiv/zipextract/gdcm-2.6.3/Testing/Source/Common/Cxx/TestDirectory.cxx | chipbuster/skull-atlas | 7f3ee009e1d5f65f101fe853a2cf6e12662970ee | [
"BSD-3-Clause"
] | null | null | null | dicom2rawiv/zipextract/gdcm-2.6.3/Testing/Source/Common/Cxx/TestDirectory.cxx | chipbuster/skull-atlas | 7f3ee009e1d5f65f101fe853a2cf6e12662970ee | [
"BSD-3-Clause"
] | 8 | 2020-04-01T01:22:45.000Z | 2022-01-02T13:06:09.000Z | /*=========================================================================
Program: GDCM (Grassroots DICOM). A DICOM library
Copyright (c) 2006-2011 Mathieu Malaterre
All rights reserved.
See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html 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 "gdcmDirectory.h"
#include "gdcmTesting.h"
#include "gdcmSystem.h"
#include <stdlib.h> // atoi
int TestOneDirectory(const char *path, bool recursive = false )
{
if( !gdcm::System::FileIsDirectory(path) )
{
std::cerr << path << " is not a directory" << std::endl;
return 1;
}
gdcm::Directory d;
d.Load( path, recursive );
//d.Print( std::cout );
if( d.GetToplevel() != path )
{
std::cerr << d.GetToplevel() << " != " << path << std::endl;
return 1;
}
gdcm::Directory::FilenamesType const &files = d.GetFilenames();
for(gdcm::Directory::FilenamesType::const_iterator it = files.begin(); it != files.end(); ++it )
{
const char *filename = it->c_str();
if( !gdcm::System::FileExists(filename) )
{
return 1;
}
}
return 0;
}
int TestDirectory(int argc, char *argv[])
{
int res = 0;
if( argc > 1 )
{
bool recursive = false;
if ( argc > 2 )
{
recursive = (atoi(argv[2]) > 0 ? true : false);
}
res += TestOneDirectory( argv[1], recursive);
}
else
{
const char *path = gdcm::Testing::GetDataRoot();
res += TestOneDirectory( path );
}
//res += TestOneDirectory( "" );
return res;
}
| 24.972222 | 98 | 0.565628 |
d6460c3cda3662f4730f91a14731321247e446ed | 258 | cpp | C++ | PETCS/Intermediate/aplusb.cpp | dl4us/Competitive-Programming-1 | d42fab3bd68168adbe4b5f594f19ee5dfcd1389b | [
"MIT"
] | null | null | null | PETCS/Intermediate/aplusb.cpp | dl4us/Competitive-Programming-1 | d42fab3bd68168adbe4b5f594f19ee5dfcd1389b | [
"MIT"
] | null | null | null | PETCS/Intermediate/aplusb.cpp | dl4us/Competitive-Programming-1 | d42fab3bd68168adbe4b5f594f19ee5dfcd1389b | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int N;
int main() {
cin.sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> N;
int a, b;
for(int i = 0; i < N; i++) {
cin >> a >> b;
cout << a+b << "\n";
}
return 0;
}
| 17.2 | 32 | 0.453488 |
d6468e7220e5b770459d2c4cff62b1dff129a89a | 9,676 | cpp | C++ | Widgets/Datalog/dialogplotchannelchoose.cpp | cyferc/Empro-Datalog-Viewer | 8d66cefe64aa254c283e72034f9ea452938ad212 | [
"MIT"
] | 6 | 2017-03-29T14:44:06.000Z | 2021-08-17T06:11:09.000Z | Widgets/Datalog/dialogplotchannelchoose.cpp | cyferc/Empro-Datalog-Viewer | 8d66cefe64aa254c283e72034f9ea452938ad212 | [
"MIT"
] | 1 | 2018-11-24T11:12:08.000Z | 2018-11-24T11:12:08.000Z | Widgets/Datalog/dialogplotchannelchoose.cpp | cyferc/Empro-Datalog-Viewer | 8d66cefe64aa254c283e72034f9ea452938ad212 | [
"MIT"
] | 3 | 2018-01-20T21:53:03.000Z | 2020-09-23T19:02:42.000Z | #include "dialogplotchannelchoose.h"
#include "ui_dialogplotchannelchoose.h"
#include <QGridLayout>
#include <QCheckBox>
#include <QDebug>
#include "plotdatalog.h"
DialogPlotChannelChoose::DialogPlotChannelChoose(std::vector<PointList *> vecOfPointLists, QSplitter *pSplitterPlots, QWidget *pParent) :
QDialog(pParent),
m_pUi(new Ui::DialogPlotChannelChoose),
m_pSplitterPlots(pSplitterPlots),
m_VecOfPointLists(vecOfPointLists)
{
m_pUi->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
// Add stacked widget for tables
m_pStackedTablesWidget = new QStackedWidget();
QGridLayout *stackedLayout = new QGridLayout(m_pUi->widgetTableContainer);
stackedLayout->setSpacing(0);
stackedLayout->setContentsMargins(0, 0, 0, 0);
stackedLayout->addWidget(m_pStackedTablesWidget);
connect(m_pUi->comboBoxPlotNumber,
static_cast<void (QComboBox::*)(int)>(&QComboBox::activated),
m_pStackedTablesWidget,
&QStackedWidget::setCurrentIndex);
// Create table for each plot
for (int plotIndex = 0; plotIndex < pSplitterPlots->count(); plotIndex++)
{
PlotDatalog* plot = qobject_cast<PlotDatalog *>(pSplitterPlots->children().at(plotIndex));
// Add plot number to drop down list
m_pUi->comboBoxPlotNumber->addItem(QString::number(plotIndex + 1));
// Create table for each plot
QTableWidget *table = new QTableWidget(vecOfPointLists.size(), 3, this);
table->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
table->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
table->setSelectionMode(QAbstractItemView::NoSelection);
table->setAlternatingRowColors(true);
table->verticalHeader()->hide();
table->verticalHeader()->setDefaultSectionSize(17);
table->setHorizontalHeaderItem(cColumnChannel, new QTableWidgetItem("Channel"));
table->setColumnWidth(cColumnChannel, 228);
table->setHorizontalHeaderItem(cColumnPlot, new QTableWidgetItem("Plot"));
table->setColumnWidth(cColumnPlot, 40);
table->setHorizontalHeaderItem(cColumnYAxis, new QTableWidgetItem("Y Axis"));
table->setColumnWidth(cColumnYAxis, 40);
// Add channels to table
int vecOfPointListsSize = static_cast<int>(vecOfPointLists.size());
for (int channel = 0; channel < vecOfPointListsSize; channel++)
{
// Column: Channel
PointList *pList = vecOfPointLists[channel];
QTableWidgetItem *itemName = new QTableWidgetItem(pList->getName());
itemName->setFlags(itemName->flags() ^ Qt::ItemIsEditable);
table->setItem(channel, cColumnChannel, itemName);
// Column: Plot
QWidget *chBoxContainerWidget = new QWidget();
QCheckBox *chBoxDraw = new QCheckBox(chBoxContainerWidget);
chBoxDraw->setChecked(plot->vecChannelsDraw[channel]);
QObject::connect(chBoxDraw,
&QCheckBox::stateChanged,
this,
&DialogPlotChannelChoose::checkBoxPlotStateChanged);
// Centre the checkbox
QHBoxLayout *pLayout = new QHBoxLayout(chBoxContainerWidget);
pLayout->addWidget(chBoxDraw);
pLayout->setAlignment(Qt::AlignCenter);
pLayout->setContentsMargins(0, 0, 0, 0);
table->setCellWidget(channel, cColumnPlot, chBoxContainerWidget);
// Column: Y Axis
QWidget *chBoxContainerWidgetYAxis = new QWidget();
QCheckBox *chBoxYAxis = new QCheckBox(chBoxContainerWidgetYAxis);
if (chBoxDraw->isChecked())
{
chBoxYAxis->setChecked(plot->vecChannelsYAxis[channel]);
}
else
{
chBoxYAxis->setEnabled(false);
}
QObject::connect(chBoxYAxis,
&QCheckBox::stateChanged,
this,
&DialogPlotChannelChoose::checkBoxYAxisStateChanged);
// Centre the checkbox
QHBoxLayout *pLayoutYAxis = new QHBoxLayout(chBoxContainerWidgetYAxis);
pLayoutYAxis->addWidget(chBoxYAxis);
pLayoutYAxis->setAlignment(Qt::AlignCenter);
pLayoutYAxis->setContentsMargins(0, 0, 0, 0);
table->setCellWidget(channel, cColumnYAxis, chBoxContainerWidgetYAxis);
}
table->setFocus();
table->selectRow(0);
// Add widget to bottom of stack
m_pStackedTablesWidget->insertWidget(0, table);
m_pStackedTablesWidget->setCurrentIndex(0);
}
}
DialogPlotChannelChoose::~DialogPlotChannelChoose()
{
delete m_pUi;
}
///
/// \brief DialogPlotChannelChoose::getCurrentTable
/// \param index
/// \return Returns table at index. If index is not provided, current table is returned.
///
QTableWidget *DialogPlotChannelChoose::getCurrentTable(int index)
{
QWidget *table;
if (index >= 0)
{
table = m_pStackedTablesWidget->widget(index);
}
else
{
table = m_pStackedTablesWidget->widget(m_pUi->comboBoxPlotNumber->currentIndex());
}
return qobject_cast<QTableWidget*>(table);
}
void DialogPlotChannelChoose::checkBoxPlotStateChanged(int state)
{
int senderRow = -1;
QCheckBox* senderCheckBox = qobject_cast<QCheckBox*>(sender());
// Get the sender row in the table
for (int i = 0; i < getCurrentTable()->rowCount(); i++)
{
if (getCurrentTable()->cellWidget(i, cColumnPlot)->children().at(0) == senderCheckBox)
{
senderRow = i;
break;
}
}
if (senderRow < 0)
{
qDebug() << "sender row not found";
return;
}
QCheckBox *chBoxYAxis = qobject_cast<QCheckBox *>(getCurrentTable()->cellWidget(senderRow, cColumnYAxis)->children().at(0));
if (state == false)
{
chBoxYAxis->setChecked(false);
}
chBoxYAxis->setEnabled(state);
}
void DialogPlotChannelChoose::checkBoxYAxisStateChanged(int /*state*/)
{
int senderRow = -1;
QCheckBox* senderCheckBox = qobject_cast<QCheckBox*>(sender());
// Get the sender row in the table
for (int i = 0; i < getCurrentTable()->rowCount(); i++)
{
if (getCurrentTable()->cellWidget(i, cColumnPlot)->children().at(0) == senderCheckBox)
{
senderRow = i;
break;
}
}
if (senderRow < 0)
{
qDebug() << "sender row not found";
return;
}
}
/*
QVector<QVector<bool>> DialogPlotChannelChoose::getSelectedPlotIndices()
{
// Create / resize 2d vector
QVector<QVector<bool>> isSelectedVector2d(_stackedTables->count());
for(int outer = 0; outer < isSelectedVector2d.size(); outer++)
{
isSelectedVector2d[outer].resize(getCurrentTable()->rowCount());
}
for (int tableIndex = 0; tableIndex < _stackedTables->count(); tableIndex++)
{
for (int channel = 0; channel < getCurrentTable(tableIndex)->rowCount(); channel++)
{
QCheckBox *chBox = qobject_cast<QCheckBox *>(getCurrentTable(tableIndex)->cellWidget(channel, ColumnPlot)->children().at(0));
if (chBox->isChecked())
{
isSelectedVector2d[tableIndex][channel] = true;
}
else
{
isSelectedVector2d[tableIndex][channel] = false;
}
}
}
return isSelectedVector2d;
}
QList<int> DialogPlotChannelChoose::getSelectedYAxisIndices()
{
QList<int> selectedIndices;
for (int row = 0; row < getCurrentTable()->rowCount(); row++)
{
QCheckBox *chBox = qobject_cast<QCheckBox *>(getCurrentTable()->cellWidget(row, ColumnYAxis)->children().at(0));
if (chBox->isChecked())
{
//qDebug() << row;
selectedIndices.append(row);
}
}
return selectedIndices;
}
*/
void DialogPlotChannelChoose::on_btnSelectAll_clicked()
{
for (int row = 0; row < getCurrentTable()->rowCount(); row++)
{
QCheckBox *chBox = qobject_cast<QCheckBox *>(getCurrentTable()->cellWidget(row, cColumnPlot)->children().at(0));
chBox->setChecked(true);
}
}
void DialogPlotChannelChoose::on_btnDeselectAll_clicked()
{
for (int row = 0; row < getCurrentTable()->rowCount(); row++)
{
QCheckBox *chBox = qobject_cast<QCheckBox *>(getCurrentTable()->cellWidget(row, cColumnPlot)->children().at(0));
chBox->setChecked(false);
}
}
void DialogPlotChannelChoose::on_buttonBox_accepted()
{
for (int plotIndex = 0; plotIndex < m_pSplitterPlots->count(); plotIndex++)
{
PlotDatalog* plot = qobject_cast<PlotDatalog*>(m_pSplitterPlots->widget(plotIndex));
// Clear all points from all plots
plot->clearPointLists();
for (int channel = 0; channel < getCurrentTable(plotIndex)->rowCount(); channel++)
{
QCheckBox *chBoxDrawChannel = qobject_cast<QCheckBox *>(getCurrentTable(plotIndex)->cellWidget(channel, cColumnPlot)->children().at(0));
QCheckBox *chBoxYAxis = qobject_cast<QCheckBox *>(getCurrentTable(plotIndex)->cellWidget(channel, cColumnYAxis)->children().at(0));
if (chBoxDrawChannel->isChecked())
{
plot->addPointList(m_VecOfPointLists.at(channel));
}
plot->vecChannelsDraw[channel] = chBoxDrawChannel->isChecked();
plot->vecChannelsYAxis[channel] = chBoxYAxis->isChecked();
}
}
}
| 33.597222 | 148 | 0.632906 |
d6477a936a53840c19a74bddb1f90eb57f8b9541 | 9,898 | cpp | C++ | test/hotspot/gtest/metaspace/test_chunkManager_stress.cpp | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | null | null | null | test/hotspot/gtest/metaspace/test_chunkManager_stress.cpp | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | null | null | null | test/hotspot/gtest/metaspace/test_chunkManager_stress.cpp | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020 SAP SE. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "memory/metaspace/chunkManager.hpp"
#include "memory/metaspace/metaspaceSettings.hpp"
#include "memory/metaspace/virtualSpaceList.hpp"
//#define LOG_PLEASE
#include "metaspaceGtestCommon.hpp"
#include "metaspaceGtestContexts.hpp"
#include "metaspaceGtestRangeHelpers.hpp"
#include "metaspaceGtestSparseArray.hpp"
using metaspace::ChunkManager;
using metaspace::Settings;
class ChunkManagerRandomChunkAllocTest {
static const size_t max_footprint_words = 8 * M;
ChunkGtestContext _context;
// All allocated live chunks
typedef SparseArray<Metachunk*> SparseArrayOfChunks;
SparseArrayOfChunks _chunks;
const ChunkLevelRange _chunklevel_range;
const float _commit_factor;
// Depending on a probability pattern, come up with a reasonable limit to number of live chunks
static int max_num_live_chunks(ChunkLevelRange r, float commit_factor) {
// Assuming we allocate only the largest type of chunk, committed to the fullest commit factor,
// how many chunks can we accomodate before hitting max_footprint_words?
const size_t largest_chunk_size = word_size_for_level(r.lowest());
int max_chunks = (max_footprint_words * commit_factor) / largest_chunk_size;
// .. but cap at (min) 50 and (max) 1000
max_chunks = MIN2(1000, max_chunks);
max_chunks = MAX2(50, max_chunks);
return max_chunks;
}
// Return true if, after an allocation error happened, a reserve error seems likely.
bool could_be_reserve_error() {
return _context.vslist().is_full();
}
// Return true if, after an allocation error happened, a commit error seems likely.
bool could_be_commit_error(size_t additional_word_size) {
// could it be commit limit hit?
if (Settings::new_chunks_are_fully_committed()) {
// For all we know we may have just failed to fully-commit a new root chunk.
additional_word_size = MAX_CHUNK_WORD_SIZE;
}
// Note that this is difficult to verify precisely, since there are
// several layers of truth:
// a) at the lowest layer (RootChunkArea) we have a bitmap of committed granules;
// b) at the vslist layer, we keep running counters of committed/reserved words;
// c) at the chunk layer, we keep a commit watermark (committed_words).
//
// (a) should mirror reality.
// (a) and (b) should be precisely in sync. This is tested by
// VirtualSpaceList::verify().
// (c) can be, by design, imprecise (too low).
//
// Here, I check (b) and trust it to be correct. We also call vslist::verify().
DEBUG_ONLY(_context.verify();)
const size_t commit_add = align_up(additional_word_size, Settings::commit_granule_words());
if (_context.commit_limit() <= (commit_add + _context.vslist().committed_words())) {
return true;
}
return false;
}
// Given a chunk level and a factor, return a random commit size.
static size_t random_committed_words(chunklevel_t lvl, float commit_factor) {
const size_t sz = word_size_for_level(lvl) * commit_factor;
if (sz < 2) {
return 0;
}
return MIN2(SizeRange(sz).random_value(), sz);
}
//// Chunk allocation ////
// Given an slot index, allocate a random chunk and set it into that slot. Slot must be empty.
// Returns false if allocation fails.
bool allocate_random_chunk_at(int slot) {
DEBUG_ONLY(_chunks.check_slot_is_null(slot);)
const ChunkLevelRange r = _chunklevel_range.random_subrange();
const chunklevel_t pref_level = r.lowest();
const chunklevel_t max_level = r.highest();
const size_t min_committed = random_committed_words(max_level, _commit_factor);
Metachunk* c = NULL;
_context.alloc_chunk(&c, r.lowest(), r.highest(), min_committed);
if (c == NULL) {
EXPECT_TRUE(could_be_reserve_error() ||
could_be_commit_error(min_committed));
LOG("Alloc chunk at %d failed.", slot);
return false;
}
_chunks.set_at(slot, c);
LOG("Allocated chunk at %d: " METACHUNK_FORMAT ".", slot, METACHUNK_FORMAT_ARGS(c));
return true;
}
// Allocates a random number of random chunks
bool allocate_random_chunks() {
int to_alloc = 1 + IntRange(MAX2(1, _chunks.size() / 8)).random_value();
bool success = true;
int slot = _chunks.first_null_slot();
while (to_alloc > 0 && slot != -1 && success) {
success = allocate_random_chunk_at(slot);
slot = _chunks.next_null_slot(slot);
to_alloc --;
}
return success && to_alloc == 0;
}
bool fill_all_slots_with_random_chunks() {
bool success = true;
for (int slot = _chunks.first_null_slot();
slot != -1 && success; slot = _chunks.next_null_slot(slot)) {
success = allocate_random_chunk_at(slot);
}
return success;
}
//// Chunk return ////
// Given an slot index, return the chunk in that slot to the chunk manager.
void return_chunk_at(int slot) {
Metachunk* c = _chunks.at(slot);
LOG("Returning chunk at %d: " METACHUNK_FORMAT ".", slot, METACHUNK_FORMAT_ARGS(c));
_context.return_chunk(c);
_chunks.set_at(slot, NULL);
}
// return a random number of chunks (at most a quarter of the full slot range)
void return_random_chunks() {
int to_free = 1 + IntRange(MAX2(1, _chunks.size() / 8)).random_value();
int index = _chunks.first_non_null_slot();
while (to_free > 0 && index != -1) {
return_chunk_at(index);
index = _chunks.next_non_null_slot(index);
to_free --;
}
}
void return_all_chunks() {
for (int slot = _chunks.first_non_null_slot();
slot != -1; slot = _chunks.next_non_null_slot(slot)) {
return_chunk_at(slot);
}
}
// adjust test if we change levels
STATIC_ASSERT(HIGHEST_CHUNK_LEVEL == CHUNK_LEVEL_1K);
STATIC_ASSERT(LOWEST_CHUNK_LEVEL == CHUNK_LEVEL_4M);
void one_test() {
fill_all_slots_with_random_chunks();
_chunks.shuffle();
IntRange rand(100);
for (int j = 0; j < 1000; j++) {
bool force_alloc = false;
bool force_free = true;
bool do_alloc =
force_alloc ? true :
(force_free ? false : rand.random_value() >= 50);
force_alloc = force_free = false;
if (do_alloc) {
if (!allocate_random_chunks()) {
force_free = true;
}
} else {
return_random_chunks();
}
_chunks.shuffle();
}
return_all_chunks();
}
public:
// A test with no limits
ChunkManagerRandomChunkAllocTest(ChunkLevelRange r, float commit_factor) :
_context(),
_chunks(max_num_live_chunks(r, commit_factor)),
_chunklevel_range(r),
_commit_factor(commit_factor)
{}
// A test with no reserve limit but commit limit
ChunkManagerRandomChunkAllocTest(size_t commit_limit,
ChunkLevelRange r, float commit_factor) :
_context(commit_limit),
_chunks(max_num_live_chunks(r, commit_factor)),
_chunklevel_range(r),
_commit_factor(commit_factor)
{}
// A test with both reserve and commit limit
// ChunkManagerRandomChunkAllocTest(size_t commit_limit, size_t reserve_limit,
// ChunkLevelRange r, float commit_factor)
// : _helper(commit_limit, reserve_limit),
// _chunks(max_num_live_chunks(r, commit_factor)),
// _chunklevel_range(r),
// _commit_factor(commit_factor)
// {}
void do_tests() {
const int num_runs = 5;
for (int n = 0; n < num_runs; n++) {
one_test();
}
}
};
#define DEFINE_TEST(name, range, commit_factor) \
TEST_VM(metaspace, chunkmanager_random_alloc_##name) { \
ChunkManagerRandomChunkAllocTest test(range, commit_factor); \
test.do_tests(); \
}
DEFINE_TEST(test_nolimit_1, ChunkLevelRanges::small_chunks(), 0.0f)
DEFINE_TEST(test_nolimit_2, ChunkLevelRanges::small_chunks(), 0.5f)
DEFINE_TEST(test_nolimit_3, ChunkLevelRanges::small_chunks(), 1.0f)
DEFINE_TEST(test_nolimit_4, ChunkLevelRanges::all_chunks(), 0.0f)
DEFINE_TEST(test_nolimit_5, ChunkLevelRanges::all_chunks(), 0.5f)
DEFINE_TEST(test_nolimit_6, ChunkLevelRanges::all_chunks(), 1.0f)
#define DEFINE_TEST_2(name, range, commit_factor) \
TEST_VM(metaspace, chunkmanager_random_alloc_##name) { \
const size_t commit_limit = 256 * K; \
ChunkManagerRandomChunkAllocTest test(commit_limit, range, commit_factor); \
test.do_tests(); \
}
DEFINE_TEST_2(test_with_limit_1, ChunkLevelRanges::small_chunks(), 0.0f)
DEFINE_TEST_2(test_with_limit_2, ChunkLevelRanges::small_chunks(), 0.5f)
DEFINE_TEST_2(test_with_limit_3, ChunkLevelRanges::small_chunks(), 1.0f)
DEFINE_TEST_2(test_with_limit_4, ChunkLevelRanges::all_chunks(), 0.0f)
DEFINE_TEST_2(test_with_limit_5, ChunkLevelRanges::all_chunks(), 0.5f)
DEFINE_TEST_2(test_with_limit_6, ChunkLevelRanges::all_chunks(), 1.0f)
| 33.666667 | 99 | 0.703071 |
d64e446dff7144ca8d332cb99165bcb8e195f0bd | 707 | cpp | C++ | src/axl_fsm/axl_fsm_StdRegexNameMgr.cpp | wandns/axl | 5686b94b18033df13a9e1656e1aaaf086c442a21 | [
"MIT"
] | null | null | null | src/axl_fsm/axl_fsm_StdRegexNameMgr.cpp | wandns/axl | 5686b94b18033df13a9e1656e1aaaf086c442a21 | [
"MIT"
] | null | null | null | src/axl_fsm/axl_fsm_StdRegexNameMgr.cpp | wandns/axl | 5686b94b18033df13a9e1656e1aaaf086c442a21 | [
"MIT"
] | null | null | null | //..............................................................................
//
// This file is part of the AXL library.
//
// AXL is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/axl/license.txt
//
//..............................................................................
#include "pch.h"
#include "axl_fsm_StdRegexNameMgr.h"
namespace axl {
namespace fsm {
//..............................................................................
//..............................................................................
} // namespace fsm
} // namespace axl
| 29.458333 | 80 | 0.381895 |
d64e7ea4e4dabafa189a4fea5e17aaaaaa8ecd54 | 4,641 | hpp | C++ | ext/tatara/array/integer/int_array.hpp | S-H-GAMELINKS/tatara | b849be7c7a9d097b2c0bd0b5df5bbb21ec96d3c0 | [
"MIT"
] | 6 | 2019-08-16T11:35:43.000Z | 2019-11-16T07:57:06.000Z | ext/tatara/array/integer/int_array.hpp | S-H-GAMELINKS/tatara | b849be7c7a9d097b2c0bd0b5df5bbb21ec96d3c0 | [
"MIT"
] | 378 | 2019-08-15T07:55:18.000Z | 2020-02-16T12:22:34.000Z | ext/tatara/array/integer/int_array.hpp | S-H-GAMELINKS/tatara | b849be7c7a9d097b2c0bd0b5df5bbb21ec96d3c0 | [
"MIT"
] | 1 | 2019-09-02T15:32:58.000Z | 2019-09-02T15:32:58.000Z | #ifndef INT_ARRAY_HPP_
#define INT_ARRAY_HPP_
#include <ruby.h>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
static VALUE int_array_init(VALUE self) {
return self;
}
static VALUE int_array_first(VALUE self) {
return rb_ary_entry(self, 0);
}
static VALUE int_array_last(VALUE self) {
const long length = RARRAY_LEN(self);
if (length == 0) return Qnil;
return rb_ary_entry(self, length - 1);
}
static VALUE int_array_bracket(VALUE self, VALUE index) {
return rb_ary_entry(self, NUM2LONG(index));
}
static VALUE int_array_bracket_equal(VALUE self, VALUE index, VALUE value) {
if (FIXNUM_P(value)) {
long i = NUM2LONG(index);
rb_ary_store(self, i, value);
return value;
} else {
rb_raise(rb_eTypeError, "Worng Type! This Value type is %s !", rb_class_name(value));
return Qnil;
}
}
static VALUE int_array_push(VALUE self, VALUE value) {
if (FIXNUM_P(value)) {
rb_ary_push(self, value);
return self;
} else {
rb_raise(rb_eTypeError, "Worng Type! This Value type is %s !", rb_class_name(value));
return Qnil;
}
}
static VALUE int_array_size(VALUE self) {
return LONG2NUM(RARRAY_LEN(self));
}
static VALUE int_array_clear(VALUE self) {
rb_ary_clear(self);
return self;
}
static VALUE int_array_map(VALUE self) {
std::size_t size = RARRAY_LEN(self);
VALUE collection = rb_obj_dup(self);
for(int i = 0; i < size; i++) {
VALUE val = int_array_bracket(self, INT2NUM(i));
int_array_bracket_equal(collection, INT2NUM(i), rb_yield(val));
}
return collection;
}
static VALUE int_array_destructive_map(VALUE self) {
std::size_t size = RARRAY_LEN(self);
for(int i = 0; i < size; i++) {
VALUE val = int_array_bracket(self, INT2NUM(i));
int_array_bracket_equal(self, INT2NUM(i), rb_yield(val));
}
return self;
}
static VALUE int_array_each_with_index(VALUE self) {
std::size_t size = RARRAY_LEN(self);
VALUE collection = rb_obj_dup(self);
for(int i = 0; i < size; i++) {
VALUE val = int_array_bracket(self, INT2NUM(i));
VALUE key_value = rb_ary_new2(2);
rb_ary_push(key_value, val);
rb_ary_push(key_value, INT2NUM(i));
rb_ary_push(collection, rb_yield(key_value));
}
return collection;
}
static VALUE int_array_convert_array(VALUE self) {
std::size_t size = RARRAY_LEN(self);
VALUE collection = rb_ary_new2(size);
for(int i = 0; i < size; i++) {
VALUE val = int_array_bracket(self, INT2NUM(i));
rb_ary_push(collection, val);
}
return collection;
}
static VALUE int_array_import_array(VALUE self, VALUE ary) {
std::size_t size = RARRAY_LEN(ary);
for(int i = 0; i < size; i++) {
VALUE val = rb_ary_entry(ary, i);
int_array_push(self, val);
}
return self;
}
static VALUE int_array_sum(VALUE self) {
std::size_t size = RARRAY_LEN(self);
long result = 0;
for (int i = 0; i < size; i++) {
VALUE val = int_array_bracket(self, INT2NUM(i));
result += NUM2LONG(val);
}
return LONG2NUM(result);
}
static VALUE int_array_sort(VALUE self) {
return rb_ary_sort(self);
}
extern "C" {
inline void Init_int_array(VALUE mTatara) {
VALUE rb_cIntArray = rb_define_class_under(mTatara, "IntArray", rb_cArray);
rb_define_private_method(rb_cIntArray, "initialize", int_array_init, 0);
rb_define_method(rb_cIntArray, "first", int_array_first, 0);
rb_define_method(rb_cIntArray, "last", int_array_last, 0);
rb_define_method(rb_cIntArray, "[]", int_array_bracket, 1);
rb_define_method(rb_cIntArray, "[]=", int_array_bracket_equal, 2);
rb_define_method(rb_cIntArray, "push", int_array_push, 1);
rb_define_method(rb_cIntArray, "size", int_array_size, 0);
rb_define_method(rb_cIntArray, "clear", int_array_clear, 0);
rb_define_alias(rb_cIntArray, "<<", "push");
rb_define_method(rb_cIntArray, "map", int_array_map, 0);
rb_define_method(rb_cIntArray, "map!", int_array_destructive_map, 0);
rb_define_alias(rb_cIntArray, "each", "map");
rb_define_method(rb_cIntArray, "each_with_index", int_array_each_with_index, 0);
rb_define_method(rb_cIntArray, "to_array", int_array_convert_array, 0);
rb_define_method(rb_cIntArray, "import_array", int_array_import_array, 1);
rb_define_method(rb_cIntArray, "sum", int_array_sum, 0);
rb_define_method(rb_cIntArray, "sort", int_array_sort, 0);
}
}
#endif
| 27.3 | 93 | 0.664081 |
d65105f7124e34e006397ffc4eb686cf9b87ab8c | 627 | hpp | C++ | src/include/helper.hpp | allen880117/Simulated-Quantum-Annealing | 84ce0a475a9f132502c4bb4e9b4ca5824cdb7630 | [
"MIT"
] | 2 | 2021-09-08T08:01:27.000Z | 2021-11-21T00:08:56.000Z | src/include/helper.hpp | allen880117/Simulated-Quantum-Annealing | 84ce0a475a9f132502c4bb4e9b4ca5824cdb7630 | [
"MIT"
] | null | null | null | src/include/helper.hpp | allen880117/Simulated-Quantum-Annealing | 84ce0a475a9f132502c4bb4e9b4ca5824cdb7630 | [
"MIT"
] | null | null | null | #ifndef _HELPER_HPP_
#define _HELPER_HPP_
#include "sqa.hpp"
/* Progress Bar */
#define PBSTR "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
#define PBWIDTH 60
/* Print the progress bar */
void printProgress(double percentage);
/* Generate Random Initial State */
void generateRandomState(spin_t trotters[MAX_NTROT][MAX_NSPIN], int nTrot,
int nSpin);
/* Compute Energy Summation of A Trotter*/
fp_t computeEnergyPerTrotter(int nSpin, spin_t trotter[MAX_NSPIN],
fp_t Jcoup[MAX_NSPIN][MAX_NSPIN],
fp_t h[MAX_NSPIN]);
#endif
| 27.26087 | 76 | 0.590112 |
d651893644eb14548298ed0bad64c2821f706b20 | 3,457 | cpp | C++ | RandPass.cpp | abdulrahmanabdulazeez/RandPass | e7b11c2f577d3ca460358bfa826e7939825cccc4 | [
"MIT"
] | 2 | 2021-09-13T15:34:30.000Z | 2021-09-30T22:16:44.000Z | RandPass.cpp | abdulrahmanabdulazeez/RandPass | e7b11c2f577d3ca460358bfa826e7939825cccc4 | [
"MIT"
] | null | null | null | RandPass.cpp | abdulrahmanabdulazeez/RandPass | e7b11c2f577d3ca460358bfa826e7939825cccc4 | [
"MIT"
] | null | null | null | //Do not copy:
//More Advanced Version:
//Random Password Generator:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <fstream>
using namespace std;
void help();
void PASSINTRO(){
cout << "------------------------------------------------------------\n\n";
cout << " RANDOM PASSWORD GENERATOR\n";
cout << "\n\nIf you notice any bug, contact me @ \n"
<< "https://web.facebook.com/abdulrahman.abdulazeez.5243/ \n\n";
cout << "----------------------------------------------------------V2.0\n";
cout << "\n\n";
}
int main(){
system("COLOR A");
srand(time(0));
PASSINTRO();
string optionSelect;
cout << "\n [1] Generate Random Password.\n";
cout << " [2] Help.\n";
cout << " [3] Exit.\n\n";
cout << "Select an option: ";
cin >> optionSelect;
while (optionSelect != "1"){
if (optionSelect == "3"){
return 0;
}
else if (optionSelect == "2"){
help();
string key;
cout << "\n\nEnter any key to continue!";
cin >> key;
system ("CLS");
main();
}
cout << "Wrong Option!";
system ("CLS");
main();
}
if (optionSelect == "1"){
//Nothing;
}
else if (optionSelect == "2"){
return 0;
}
else {
return 0;
}
char NumLetSym[] = "zxcvbnmqpwoeirutyalskdjfhgQWERTYUIOPASDFGHJKLMNBVCZ1234567890:/.,()[]';?>|<!@#$%^&*";
int conv = sizeof(NumLetSym);
cout << "\nWhat do you want to generate a password for? \n\n"
<< "Hint: It could be Facebook, Google, name it and we would do just that \n"
<< "for you. \n\n";
string reason;
cout << "Reason: ";
cin >> reason;
cout << "\nEnter the length of password you want to generate: ";
int n;
cin >>n;
int load;
for (load=0; load <= 100; load++){
system("cls");
PASSINTRO();
cout << "Generating Password......." << load << "%";
cout << "\n\n";
}
int i;
ofstream RandomPass(reason + ".html");
for(i = 0; i < n; i++){
RandomPass << NumLetSym[rand() % conv];
}
RandomPass.close();
string Reader;
ifstream RandomPasser(reason + ".html");
while (getline (RandomPasser, Reader)) {
cout << "===================================================\n";
cout << " " << reason << " generated password: ";
cout << Reader;
cout << "\n===================================================\n\n";
}
cout << "Generated password has been saved in " << reason << ".html on your desktop.\n";
cout << "Note: You are to open it with any text viewer you have available.\n\n";
RandomPasser.close();
cout << "Do you want to re-generate another Password?[Y/N]: ";
string yesNo;
cin >> yesNo;
while (yesNo != "Y"){
if (yesNo == "N"){
return 0;
}
else if (yesNo == "y"){
system ("CLS");
}
else if (yesNo == "n"){
return 0;
}
cout << " Wrong option!!\n\n";
cout << "Do you want to re-generate another Password?[Y/N]: ";
cin >> yesNo;
}
if (yesNo == "Y"){
system("CLS");
cout << "\n";
main();
}
else if (yesNo == "N"){
return 0;
}
else if (yesNo == "y"){
system("CLS");
cout << "\n";
main();
}
else if (yesNo == "n"){
return 0;
}
else {
return 0;
}
return 0;
}
void help(){
cout << "\n\nAn advanced Random Password generator which generates very strong passwords \n"
<< "containing Letters(Small & Capital), Symbols and Numbers. This program also gives \n"
<< "you an option to specify the reason for the password to be created and stores the \n"
<< "generated password on your desktop with the reason you specified as filename \n"
<< "thereby making it easy to check on incase you forget the password generated \n"
<< "\nNote: The password stored on your desktop is in a HTML format. You can choose to \n"
<< "open with any text viewer of your choice.!";
} | 24.174825 | 105 | 0.596182 |
d65bf9553350916a22745d911554bdfcb4dff652 | 14,892 | cpp | C++ | Coda105/Coda105/Source/Serial/juce_serialport_Windows.cpp | Klepto63/CodaJUCE | 1930076f90832daa5c68c7cd09aeb1fce2934419 | [
"MIT"
] | null | null | null | Coda105/Coda105/Source/Serial/juce_serialport_Windows.cpp | Klepto63/CodaJUCE | 1930076f90832daa5c68c7cd09aeb1fce2934419 | [
"MIT"
] | null | null | null | Coda105/Coda105/Source/Serial/juce_serialport_Windows.cpp | Klepto63/CodaJUCE | 1930076f90832daa5c68c7cd09aeb1fce2934419 | [
"MIT"
] | null | null | null | //win32_SerialPort.cpp
//Serial Port classes in a Juce stylee, by graffiti
//see SerialPort.h for details
//
// Updated for current Juce API 8/1/13 Marc Lindahl
//
#include "../JuceLibraryCode/JuceHeader.h"
#if JUCE_WINDOWS
using namespace juce;
#include <windows.h>
#include <stdio.h>
#include "juce_serialport.h"
class CAutoHeapAlloc
{
public:
//Constructors / Destructors
CAutoHeapAlloc(HANDLE hHeap = GetProcessHeap(), DWORD dwHeapFreeFlags = 0) : m_pData(NULL),
m_hHeap(hHeap),
m_dwHeapFreeFlags(dwHeapFreeFlags)
{
}
BOOL Allocate(SIZE_T dwBytes, DWORD dwFlags = 0)
{
//Validate our parameters
jassert(m_pData == NULL);
m_pData = HeapAlloc(m_hHeap, dwFlags, dwBytes);
return (m_pData != NULL);
}
~CAutoHeapAlloc()
{
if (m_pData != NULL)
{
HeapFree(m_hHeap, m_dwHeapFreeFlags, m_pData);
m_pData = NULL;
}
}
//Methods
//Member variables
LPVOID m_pData;
HANDLE m_hHeap;
DWORD m_dwHeapFreeFlags;
};
StringPairArray SerialPort::getSerialPortPaths()
{
StringPairArray SerialPortPaths;
HKEY hSERIALCOMM;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM", 0, KEY_QUERY_VALUE, &hSERIALCOMM) == ERROR_SUCCESS)
{
//Get the max value name and max value lengths
DWORD dwMaxValueNameLen;
DWORD dwMaxValueLen;
DWORD dwQueryInfo = RegQueryInfoKey(hSERIALCOMM, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &dwMaxValueNameLen, &dwMaxValueLen, NULL, NULL);
if (dwQueryInfo == ERROR_SUCCESS)
{
DWORD dwMaxValueNameSizeInChars = dwMaxValueNameLen + 1; //Include space for the NULL terminator
DWORD dwMaxValueNameSizeInBytes = dwMaxValueNameSizeInChars * sizeof(TCHAR);
DWORD dwMaxValueDataSizeInChars = dwMaxValueLen / sizeof(TCHAR) + 1; //Include space for the NULL terminator
DWORD dwMaxValueDataSizeInBytes = dwMaxValueDataSizeInChars * sizeof(TCHAR);
//Allocate some space for the value name and value data
CAutoHeapAlloc valueName;
CAutoHeapAlloc valueData;
if (valueName.Allocate(dwMaxValueNameSizeInBytes) && valueData.Allocate(dwMaxValueDataSizeInBytes))
{
//Enumerate all the values underneath HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM
DWORD dwIndex = 0;
DWORD dwType;
DWORD dwValueNameSize = dwMaxValueNameSizeInChars;
DWORD dwDataSize = dwMaxValueDataSizeInBytes;
std::memset(valueName.m_pData, 0, dwMaxValueNameSizeInBytes);
std::memset(valueData.m_pData, 0, dwMaxValueDataSizeInBytes);
TCHAR* szValueName = static_cast<TCHAR*>(valueName.m_pData);
BYTE* byValue = static_cast<BYTE*>(valueData.m_pData);
LONG nEnum = RegEnumValue(hSERIALCOMM, dwIndex, szValueName, &dwValueNameSize, NULL, &dwType, byValue, &dwDataSize);
while (nEnum == ERROR_SUCCESS)
{
//If the value is of the correct type, then add it to the array
if (dwType == REG_SZ)
{
TCHAR* szPort = reinterpret_cast<TCHAR*>(byValue);
SerialPortPaths.set(szPort, String("\\\\.\\") + String(szPort));
}
//Prepare for the next time around
dwValueNameSize = dwMaxValueNameSizeInChars;
dwDataSize = dwMaxValueDataSizeInBytes;
std::memset(valueName.m_pData, 0, dwMaxValueNameSizeInBytes);
std::memset(valueData.m_pData, 0, dwMaxValueDataSizeInBytes);
++dwIndex;
nEnum = RegEnumValue(hSERIALCOMM, dwIndex, szValueName, &dwValueNameSize, NULL, &dwType, byValue, &dwDataSize);
}
}
else
SetLastError(ERROR_OUTOFMEMORY);
}
//Close the registry key now that we are finished with it
RegCloseKey(hSERIALCOMM);
if (dwQueryInfo != ERROR_SUCCESS)
SetLastError(dwQueryInfo);
}
return SerialPortPaths;
}
void SerialPort::close()
{
if (portHandle)
{
CloseHandle(portHandle);
portHandle = 0;
}
}
bool SerialPort::exists()
{
return portHandle ? true : false;
}
bool SerialPort::open(const String & newPortPath)
{
canceled = false;
portPath = newPortPath;
portHandle = CreateFile((const char*)portPath.toUTF8(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
if (portHandle == INVALID_HANDLE_VALUE)
{
//DBG_PRINTF((T("(SerialPort::open) CreateFile failed with error %d.\n"), GetLastError()));
portHandle = 0;
return false;
}
COMMTIMEOUTS commTimeout;
if (GetCommTimeouts(portHandle, &commTimeout))
{
commTimeout.ReadIntervalTimeout = MAXDWORD;
commTimeout.ReadTotalTimeoutConstant = 0;
commTimeout.ReadTotalTimeoutMultiplier = 0;
commTimeout.WriteTotalTimeoutConstant = 0;
commTimeout.WriteTotalTimeoutMultiplier = 0;
}
else
DBG("GetCommTimeouts error");
if (!SetCommTimeouts(portHandle, &commTimeout))
DBG("SetCommTimeouts error");
if (!SetCommMask(portHandle, EV_RXCHAR))
DBG("SetCommMask error");
return true;
}
void SerialPort::cancel ()
{
if (! canceled)
{
canceled = true;
// if (portHandle != nullptr)
// const auto result = CancelIoEx (portHandle, nullptr);
}
}
bool SerialPort::setConfig(const SerialPortConfig & config)
{
if (!portHandle)return false;
DCB dcb;
memset(&dcb, 0, sizeof(DCB));
dcb.DCBlength = sizeof(DCB);
dcb.fBinary = 1;
dcb.XonLim = 2048;
dcb.XoffLim = 512;
dcb.BaudRate = config.bps;
dcb.ByteSize = (BYTE)config.databits;
dcb.fParity = true;
switch (config.parity)
{
case SerialPortConfig::SERIALPORT_PARITY_ODD:
dcb.Parity = ODDPARITY;
break;
case SerialPortConfig::SERIALPORT_PARITY_EVEN:
dcb.Parity = EVENPARITY;
break;
case SerialPortConfig::SERIALPORT_PARITY_MARK:
dcb.Parity = MARKPARITY;
break;
case SerialPortConfig::SERIALPORT_PARITY_SPACE:
dcb.Parity = SPACEPARITY;
break;
case SerialPortConfig::SERIALPORT_PARITY_NONE:
default:
dcb.Parity = NOPARITY;
dcb.fParity = false;
break;
}
switch (config.stopbits)
{
case SerialPortConfig::STOPBITS_1:
default:
dcb.StopBits = ONESTOPBIT;
break;
case SerialPortConfig::STOPBITS_1ANDHALF:
dcb.StopBits = ONE5STOPBITS;
break;
case SerialPortConfig::STOPBITS_2:
dcb.StopBits = TWOSTOPBITS;
break;
}
switch (config.flowcontrol)
{
case SerialPortConfig::FLOWCONTROL_XONXOFF:
dcb.fOutxCtsFlow = 0;
dcb.fOutxDsrFlow = 0;
dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fOutX = 1;
dcb.fInX = 1;
dcb.fRtsControl = RTS_CONTROL_ENABLE;
break;
case SerialPortConfig::FLOWCONTROL_HARDWARE:
dcb.fOutxCtsFlow = 1;
dcb.fOutxDsrFlow = 1;
dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
dcb.fOutX = 0;
dcb.fInX = 0;
dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
break;
case SerialPortConfig::FLOWCONTROL_NONE:
default:
dcb.fOutxCtsFlow = 0;
dcb.fOutxDsrFlow = 0;
dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fOutX = 0;
dcb.fInX = 0;
dcb.fRtsControl = RTS_CONTROL_ENABLE;
break;
}
return (SetCommState(portHandle, &dcb) ? true : false);
}
bool SerialPort::getConfig(SerialPortConfig & config)
{
if (!portHandle)return false;
DCB dcb;
if (!GetCommState(portHandle, &dcb))
return false;
config.bps = dcb.BaudRate;
config.databits = dcb.ByteSize;
switch (dcb.Parity)
{
case ODDPARITY:
config.parity = SerialPortConfig::SERIALPORT_PARITY_ODD;
break;
case EVENPARITY:
config.parity = SerialPortConfig::SERIALPORT_PARITY_EVEN;
break;
case MARKPARITY:
config.parity = SerialPortConfig::SERIALPORT_PARITY_MARK;
break;
case SPACEPARITY:
config.parity = SerialPortConfig::SERIALPORT_PARITY_SPACE;
break;
case NOPARITY:
default:
config.parity = SerialPortConfig::SERIALPORT_PARITY_NONE;
break;
}
switch (dcb.StopBits)
{
case ONESTOPBIT:
default:
config.stopbits = SerialPortConfig::STOPBITS_1;
break;
case ONE5STOPBITS:
config.stopbits = SerialPortConfig::STOPBITS_1ANDHALF;
break;
case TWOSTOPBITS:
config.stopbits = SerialPortConfig::STOPBITS_2;
break;
}
if (dcb.fOutX && dcb.fInX)
config.flowcontrol = SerialPortConfig::FLOWCONTROL_XONXOFF;
else if ((dcb.fDtrControl == DTR_CONTROL_HANDSHAKE) && (dcb.fRtsControl == RTS_CONTROL_HANDSHAKE))
config.flowcontrol = SerialPortConfig::FLOWCONTROL_HARDWARE;
else
config.flowcontrol = SerialPortConfig::FLOWCONTROL_NONE;
return true;
}
/////////////////////////////////
// SerialPortInputStream
/////////////////////////////////
void SerialPortInputStream::run()
{
DWORD dwEventMask = 0;
//overlapped structure for the wait
OVERLAPPED ov;
memset(&ov, 0, sizeof(ov));
ov.hEvent = CreateEvent(0, true, 0, 0);
//overlapped structure for the read
OVERLAPPED ovRead;
memset(&ovRead, 0, sizeof(ovRead));
ovRead.hEvent = CreateEvent(0, true, 0, 0);
while (port && port->portHandle && !threadShouldExit())
{
unsigned char c;
DWORD bytesread = 0;
const auto wceReturn = WaitCommEvent(port->portHandle, &dwEventMask, &ov);
// if (dwEventMask != 0)
// Logger::outputDebugString (" dwEventMask: " + String::toHexString (dwEventMask));
if (wceReturn == 0 && GetLastError () != ERROR_IO_PENDING)
{
//Logger::outputDebugString ("SerialPortInputStream error");
port->close ();
break;
}
if (/*(dwEventMask & EV_RXCHAR) && */WAIT_OBJECT_0 == WaitForSingleObject(ov.hEvent, 100))
{
DWORD dwMask;
if (GetCommMask(port->portHandle, &dwMask))
{
//if (dwMask & EV_RXCHAR)
{
do
{
ResetEvent(ovRead.hEvent);
//Logger::outputDebugString (" ReadFile");
ReadFile(port->portHandle, &c, 1, &bytesread, &ovRead);
// if (GetLastError () != ERROR_SUCCESS)
// Logger::outputDebugString (" [SerialPortInputStream, getLastError: " + String (GetLastError ()) + "]");
if (bytesread == 1)
{
//Logger::outputDebugString (" add data to input buffer");
const ScopedLock l(bufferCriticalSection);
buffer.ensureSize(bufferedbytes + 1);
buffer[bufferedbytes] = c;
bufferedbytes++;
if (notify == NOTIFY_ALWAYS || ((notify == NOTIFY_ON_CHAR) && (c == notifyChar)))
sendChangeMessage();
}
} while (bytesread);
}
}
ResetEvent(ov.hEvent);
}
}
CloseHandle(ovRead.hEvent);
CloseHandle(ov.hEvent);
// Logger::outputDebugString ("SerialPortInputStream::run exiting");
}
void SerialPortInputStream::cancel ()
{
if (!port || port->portHandle == 0)
return;
port->cancel ();
}
int SerialPortInputStream::read(void *destBuffer, int maxBytesToRead)
{
if (!port || port->portHandle == 0)
return -1;
const ScopedLock l (bufferCriticalSection);
if (maxBytesToRead > bufferedbytes)maxBytesToRead = bufferedbytes;
memcpy (destBuffer, buffer.getData (), maxBytesToRead);
buffer.removeSection (0, maxBytesToRead);
bufferedbytes -= maxBytesToRead;
return maxBytesToRead;
}
/////////////////////////////////
// SerialPortOutputStream
/////////////////////////////////
void SerialPortOutputStream::run()
{
unsigned char tempbuffer[writeBufferSize];
OVERLAPPED ov;
memset(&ov, 0, sizeof(ov));
ov.hEvent = CreateEvent(0, true, 0, 0);
while (port && port->portHandle && !threadShouldExit())
{
if (!bufferedbytes)
triggerWrite.wait(100);
if (bufferedbytes)
{
DWORD byteswritten = 0;
bufferCriticalSection.enter ();
DWORD bytestowrite = bufferedbytes > writeBufferSize ? writeBufferSize : bufferedbytes;
memcpy (tempbuffer, buffer.getData (), bytestowrite);
bufferCriticalSection.exit ();
ResetEvent (ov.hEvent);
//Logger::outputDebugString (" WriteFile");
int iRet = WriteFile (port->portHandle, tempbuffer, bytestowrite, &byteswritten, &ov);
if (threadShouldExit () || (GetLastError () != ERROR_SUCCESS && GetLastError () != ERROR_IO_PENDING))
continue;
if (iRet == 0 && GetLastError() == ERROR_IO_PENDING)
{
//Logger::outputDebugString (" WaitForSingleObject");
DWORD waitResult = WaitForSingleObject (ov.hEvent, 1000);
if (threadShouldExit () || waitResult != WAIT_OBJECT_0)
continue;
}
//Logger::outputDebugString (" [getLastError: " + String(GetLastError ()) + "]");
//Logger::outputDebugString (" GetOverlappedResult ");
GetOverlappedResult (port->portHandle, &ov, &byteswritten, TRUE);
if (byteswritten)
{
const ScopedLock l (bufferCriticalSection);
buffer.removeSection (0, byteswritten);
bufferedbytes -= byteswritten;
}
}
}
CloseHandle(ov.hEvent);
// Logger::outputDebugString ("SerialPortOutputStream::run exiting");
}
void SerialPortOutputStream::cancel ()
{
if (!port || port->portHandle == 0)
return;
port->cancel ();
}
bool SerialPortOutputStream::write(const void *dataToWrite, size_t howManyBytes)
{
if (! port || port->portHandle == 0)
return false;
bufferCriticalSection.enter();
buffer.append(dataToWrite, howManyBytes);
bufferedbytes += (int)howManyBytes;
bufferCriticalSection.exit();
triggerWrite.signal();
return true;
}
#endif // JUCE_WIN
| 32.946903 | 147 | 0.599449 |
d6618d5c25345e95ecb195b5f0d64cc65ad2cd5f | 275 | cpp | C++ | 2021.10.03-homework-3/Project3/Source.cpp | st095227/homework_2021-2022 | 7b3abd8848ead7456972c5d2f0f4404532e299bc | [
"Apache-2.0"
] | null | null | null | 2021.10.03-homework-3/Project3/Source.cpp | st095227/homework_2021-2022 | 7b3abd8848ead7456972c5d2f0f4404532e299bc | [
"Apache-2.0"
] | null | null | null | 2021.10.03-homework-3/Project3/Source.cpp | st095227/homework_2021-2022 | 7b3abd8848ead7456972c5d2f0f4404532e299bc | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int main(int argv, char* argc[])
{
int n = 0;
cin >> n;
int i = 0;
int b = 0;
while (n != 0)
{
++i;
for (int j = 0; j < i && n>0; ++j)
{
++b;
cout << b << ' ';
--n;
}
cout << endl;
}
return EXIT_SUCCESS;
} | 11.956522 | 36 | 0.461818 |
d664e5f30f2b72c24f2066baad8a56b3552c82dc | 4,169 | cpp | C++ | DirectShow/Player.cpp | Marloxo/DirectShow | be99d025234ce750a9c92e71ff97d78e8e4ffcf3 | [
"MIT"
] | 6 | 2017-09-10T16:27:44.000Z | 2021-12-18T16:29:02.000Z | DirectShow/Player.cpp | Marloxo/DirectShow | be99d025234ce750a9c92e71ff97d78e8e4ffcf3 | [
"MIT"
] | null | null | null | DirectShow/Player.cpp | Marloxo/DirectShow | be99d025234ce750a9c92e71ff97d78e8e4ffcf3 | [
"MIT"
] | 2 | 2018-01-23T07:23:14.000Z | 2020-05-19T13:51:22.000Z | #include "stdafx.h"
#include <dshow.h>
//This is needed for virtually
//everything in BrowseFolder.
#include <Windows.h>
#include <Commdlg.h>
#include <tchar.h>
#include <string>
#include <iostream>
using namespace std;
//Define my function
int Stop();
void ThrowIfError(HRESULT hr);
bool GetCompletionEvent();
// TODO: Initialize Global Var
IGraphBuilder *pGraph = NULL;
IMediaControl *pControl = NULL;
IMediaEventEx *pEventEx = NULL;
bool ispaused=false;
void Play(HWND hwnd, TCHAR* FileName)
{
HRESULT hr;
try
{
if (pGraph)
return;
// Initialize the COM library.
hr = CoInitialize(NULL);
if (FAILED(hr))
{
Stop();
MessageBox(0, TEXT("ERROR !"), TEXT("ERROR - Could not initialize COM library"), 0);
return;
}
// Create the filter graph manager and query for interfaces.
hr = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
IID_IGraphBuilder, (void **)&pGraph);
if (FAILED(hr))
{
Stop();
MessageBox(0, TEXT("ERROR !"), TEXT("ERROR - Could not create the Filter Graph Manager."), 0);
return;
}
hr = pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
hr = pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEventEx);
// Build the graph. IMPORTANT: Change this string to a file on your system.
hr = pGraph->RenderFile(FileName, NULL);
//ThrowIfError(hr);
if (FAILED(hr))
MessageBox(0, TEXT("ERROR - Could not Find the request file to play."), TEXT("ERROR !"), 0);
if (SUCCEEDED(hr))
{ // Run the graph.
hr = pControl->Run();
ThrowIfError(hr);
// Wait for completion.
// Note: Do not use INFINITE in a real application, because it
// can block indefinitely.
/*long evCode;
pEventEx->WaitForCompletion(INFINITE, &evCode);*/
}
//Get notification when something happened
pEventEx->SetNotifyWindow((OAHWND)hwnd, WM_GRAPHNOTIFY, 0);
}
catch (TCHAR szErr)
{
ThrowIfError(hr);
}
}
int Stop()
{
if (pGraph)
{
pGraph->Release();
pGraph = NULL;
}
if (pControl)
{
pControl->Release();
pControl = NULL;
}
if (pEventEx)
{
pEventEx->SetNotifyWindow((OAHWND)NULL, WM_GRAPHNOTIFY, 0);
pEventEx->Release();
pEventEx = NULL;
}
CoUninitialize();
return 0;
}
bool GetCompletionEvent()
{
if (pEventEx == NULL)
return false;
while (true)
{
long evCode;
LONG_PTR param1, param2;
HRESULT hr = pEventEx->GetEvent(&evCode, ¶m1, ¶m2, 250);
if (FAILED(hr))
return false;
hr = pEventEx->FreeEventParams(evCode, param1, param2);
ThrowIfError(hr);
if (evCode == EC_COMPLETE)
return true;
}
}
//Show Error for HRESULT
void ThrowIfError(HRESULT hr)
{
if (FAILED(hr))
{
TCHAR szErr[MAX_ERROR_TEXT_LEN];
DWORD res = AMGetErrorText(hr, szErr, MAX_ERROR_TEXT_LEN);
if (res == 0)
{
StringCchPrintf(szErr, MAX_ERROR_TEXT_LEN, TEXT("Unknown Error: 0x%2x"), hr);
}
MessageBox(0, szErr, TEXT("Basically, without saying too much, you're screwed. Royally and totally."), MB_OK | MB_ICONERROR);
//throw szErr;
}
}
void Pause()
{
if (ispaused)
{
pControl->Run(); //resumes the media if it was previously paused
ispaused = false;
}
else
{
pControl->Pause(); //to pause the media
ispaused = true;
}
}
TCHAR* ShowDialog()
{
//check if there is file already playing
if (pGraph)
{
MessageBox(0, TEXT("Stop Played File First!!"), _T("Info"),
MB_OK | MB_ICONINFORMATION);
return NULL;
}
TCHAR*DefaultExtension = 0;
TCHAR*FileName = new TCHAR[MAX_PATH];;
TCHAR*Filter = 0;
int FilterIndex = 0;
int Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
TCHAR*InitialDir = 0;
HWND Owner = 0;
TCHAR*Title = 0;
OPENFILENAME ofn;
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = Owner;
ofn.lpstrDefExt = DefaultExtension;
ofn.lpstrFile = FileName;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = MAX_PATH;
ofn.lpstrFilter = Filter;
ofn.nFilterIndex = FilterIndex;
ofn.lpstrInitialDir = InitialDir;
ofn.lpstrTitle = Title;
ofn.Flags = Flags;
GetOpenFileName(&ofn);
if (_tcslen(FileName) == 0)
{
MessageBox(0, TEXT("NO File Selected!!"), _T("Info"),
MB_OK | MB_ICONINFORMATION);
return NULL;
}
return FileName;
} | 20.140097 | 127 | 0.676901 |
d666f64f883dacdd4b5404cdaeb89b92e1ea7a87 | 3,030 | cpp | C++ | portable-executable/portable-executable-library2/tests/test_resource_message_table/main.cpp | psneo/Pesidious | c36647d1b3ba86a9a4e6e1a0bda2a371d8875781 | [
"MIT"
] | 83 | 2020-09-14T16:51:42.000Z | 2022-03-31T23:23:02.000Z | portable-executable/portable-executable-library2/tests/test_resource_message_table/main.cpp | bedangSen/Pesidious-1 | 3348a8977951074eef41dbd8460934ef7a9093fd | [
"MIT"
] | 9 | 2020-11-13T19:08:15.000Z | 2022-03-12T00:50:20.000Z | portable-executable/portable-executable-library2/tests/test_resource_message_table/main.cpp | bedangSen/Pesidious-1 | 3348a8977951074eef41dbd8460934ef7a9093fd | [
"MIT"
] | 30 | 2020-09-13T15:05:22.000Z | 2022-03-28T05:51:05.000Z | #include <iostream>
#include <fstream>
#include <pe_bliss.h>
#include <pe_bliss_resources.h>
#include "test.h"
#ifdef PE_BLISS_WINDOWS
#include "lib.h"
#endif
using namespace pe_bliss;
int main(int argc, char* argv[])
{
PE_TEST_START
std::auto_ptr<std::ifstream> pe_file;
if(!open_pe_file(argc, argv, pe_file))
return -1;
pe_base image(pe_factory::create_pe(*pe_file));
resource_directory root(get_resources(image));
pe_resource_manager res(root);
resource_message_list_reader msg(res);
resource_message_list messages;
//Unicode tests
PE_TEST_EXCEPTION(messages = msg.get_message_table_by_id_lang(1049, 1), "Message Table Parser test 1", test_level_critical);
PE_TEST(messages.size() == 2, "Message Table Parser test 2", test_level_critical);
PE_TEST(messages.find(0x01000000) != messages.end()
&& messages.find(0xC1000001) != messages.end(), "Message Table Parser test 3", test_level_critical);
PE_TEST(messages[0xC1000001].is_unicode(), "Message Table Parser test 4", test_level_normal);
PE_TEST(messages[0xC1000001].get_unicode_string() == L"Ошибка!\r\n", "Message Table Parser test 5", test_level_normal);
PE_TEST_EXCEPTION(messages = msg.get_message_table_by_id_lang(1033, 1), "Message Table Parser test 6", test_level_critical);
PE_TEST(messages.size() == 2, "Message Table Parser test 7", test_level_critical);
PE_TEST(messages.find(0x01000000) != messages.end()
&& messages.find(0xC1000001) != messages.end(), "Message Table Parser test 8", test_level_critical);
PE_TEST(messages[0xC1000001].is_unicode(), "Message Table Parser test 9", test_level_normal);
PE_TEST(messages[0xC1000001].get_unicode_string() == L"Error!\r\n", "Message Table Parser test 10", test_level_normal);
//ANSI Tests
PE_TEST_EXCEPTION(messages = msg.get_message_table_by_id_lang(1049, 2), "Message Table Parser test 11", test_level_critical);
PE_TEST(messages.size() == 2, "Message Table Parser test 12", test_level_critical);
PE_TEST(messages.find(0x01000000) != messages.end()
&& messages.find(0xC1000001) != messages.end(), "Message Table Parser test 13", test_level_critical);
PE_TEST(!messages[0xC1000001].is_unicode(), "Message Table Parser test 14", test_level_normal);
PE_TEST(messages[0xC1000001].get_ansi_string() == "\xCE\xF8\xE8\xE1\xEA\xE0!\r\n", "Message Table Parser test 15", test_level_normal); //"Ошибка!\r\n"
PE_TEST_EXCEPTION(messages = msg.get_message_table_by_id_lang(1033, 2), "Message Table Parser test 16", test_level_critical);
PE_TEST(messages.size() == 2, "Message Table Parser test 17", test_level_critical);
PE_TEST(messages.find(0x01000000) != messages.end()
&& messages.find(0xC1000001) != messages.end(), "Message Table Parser test 18", test_level_critical);
PE_TEST(!messages[0xC1000001].is_unicode(), "Message Table Parser test 19", test_level_normal);
PE_TEST(messages[0xC1000001].get_ansi_string() == "Error!\r\n", "Message Table Parser test 20", test_level_normal);
PE_TEST_END
return 0;
}
| 48.095238 | 152 | 0.744884 |
d66735c18595db157d264abb51aafadb8eb3a8f3 | 2,361 | cpp | C++ | plugins/community/repos/BaconMusic/src/SampleDelay.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 233 | 2018-07-02T16:49:36.000Z | 2022-02-27T21:45:39.000Z | plugins/community/repos/BaconMusic/src/SampleDelay.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-09T11:32:15.000Z | 2022-01-07T01:45:43.000Z | plugins/community/repos/BaconMusic/src/SampleDelay.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-14T21:55:30.000Z | 2021-05-04T04:20:34.000Z |
#include "BaconPlugs.hpp"
#include "SampleDelay.hpp"
namespace rack_plugin_BaconMusic {
struct SampleDelayWidget : ModuleWidget {
typedef SampleDelay< Module > SD;
SampleDelayWidget( SD *module);
};
SampleDelayWidget::SampleDelayWidget( SD *module ) : ModuleWidget( module )
{
box.size = Vec( SCREW_WIDTH * 5, RACK_HEIGHT );
BaconBackground *bg = new BaconBackground( box.size, "SampDelay" );
addChild( bg->wrappedInFramebuffer());
int outy = 30;
int gap = 10;
int margin = 3;
// plug label is 29 x 49
Vec ppos = Vec( bg->cx( SizeTable<PJ301MPort>::X ), outy + 20 );
bg->addPlugLabel( ppos, BaconBackground::SIG_IN, "in" );
addInput( Port::create< PJ301MPort >( ppos, Port::INPUT,
module, SD::SIGNAL_IN ) );
outy += 49 + gap + margin;
bg->addRoundedBorder( Vec( bg->cx() - 14 * 1.5 - margin, outy - margin ),
Vec( 14 * 3 + 2 * margin , 14 + SizeTable<RoundBlackSnapKnob>::Y + 2 * margin + 22 + margin + 2 * margin) );
bg->addLabel( Vec( bg->cx(), outy ), "# samples", 11, NVG_ALIGN_CENTER | NVG_ALIGN_TOP );
outy += 14;
addParam( ParamWidget::create< RoundBlackSnapKnob >( Vec( bg->cx( SizeTable< RoundBlackSnapKnob >::X ), outy ),
module,
SD::DELAY_KNOB,
1, 99, 1 ) );
outy += SizeTable<RoundBlackSnapKnob>::Y + 2 * margin;
addChild( MultiDigitSevenSegmentLight<BlueLight, 2, 3>::create( Vec( bg->cx() - 14 * 1.5, outy ),
module,
SD::DELAY_VALUE_LIGHT ) );
outy += 22 + gap + margin;
ppos = Vec( bg->cx( SizeTable<PJ301MPort>::X ), outy + 20 );
bg->addPlugLabel( ppos, BaconBackground::SIG_OUT, "out" );
addOutput( Port::create< PJ301MPort >( ppos, Port::OUTPUT,
module, SD::SIGNAL_OUT ) );
}
} // namespace rack_plugin_BaconMusic
using namespace rack_plugin_BaconMusic;
RACK_PLUGIN_MODEL_INIT(BaconMusic, SampleDelay) {
Model *modelSampleDelay = Model::create<SampleDelayWidget::SD, SampleDelayWidget>("Bacon Music", "SampleDelay", "SampleDelay", DELAY_TAG );
return modelSampleDelay;
}
| 38.704918 | 143 | 0.565862 |
d6698da573210a66a18d0e558f4d95bb0b653ed3 | 2,928 | cpp | C++ | cpp/lambdas.cpp | MCJOHN974/fibonacci | b70f9cb99160273501668d2e471e8d08187a35c9 | [
"MIT"
] | 13 | 2022-01-11T16:49:21.000Z | 2022-03-05T02:53:40.000Z | cpp/lambdas.cpp | MCJOHN974/fibonacci | b70f9cb99160273501668d2e471e8d08187a35c9 | [
"MIT"
] | 31 | 2022-01-13T16:05:35.000Z | 2022-03-22T14:27:38.000Z | cpp/lambdas.cpp | MCJOHN974/fibonacci | b70f9cb99160273501668d2e471e8d08187a35c9 | [
"MIT"
] | 9 | 2022-01-13T14:56:44.000Z | 2022-03-09T14:56:12.000Z | // Copyright (c) 2022 Yegor Bugayenko
//
// 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 NON-INFRINGEMENT. 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 <cstdlib>
#include "./main.h"
constexpr size_t PROPER_ALIGMENT = 64;
struct lambda;
using func = int (*)(struct lambda*);
struct __attribute__((aligned(PROPER_ALIGMENT))) lambda {
func body;
int data;
struct lambda* first;
struct lambda* second;
struct lambda* third;
};
int call(struct lambda* l) {
int ret;
if (l->body == nullptr) {
ret = l->data;
} else {
ret = l->body(l);
}
free(l);
return ret;
}
struct lambda* make(
func body, struct lambda* a, struct lambda* b, struct lambda* c) {
auto* l = static_cast<lambda*>(malloc(sizeof(lambda)));
l->body = body;
l->first = a;
l->second = b;
l->third = c;
return l;
}
struct lambda* integer(int x) {
auto* l = make(nullptr, nullptr, nullptr, nullptr);
l->data = x;
return l;
}
void release(struct lambda* l) {
if (l == nullptr) {
return;
}
release(l->first);
release(l->second);
release(l->third);
free(l);
}
int iff(struct lambda* arg) {
int ret;
if (call(arg->first) == 1) {
ret = call(arg->second);
release(arg->third);
} else {
ret = call(arg->third);
release(arg->second);
}
return ret;
}
int less(struct lambda* arg) {
return static_cast<int>(call(arg->first) < call(arg->second));
}
int sub(struct lambda* arg) { return call(arg->first) - call(arg->second); }
int add(struct lambda* arg) { return call(arg->first) + call(arg->second); }
int fibo(struct lambda* arg) {
int x = call(arg->first);
return call(make(iff, make(less, integer(x), integer(2), nullptr), integer(1),
make(add,
make(fibo, make(sub, integer(x), integer(1), nullptr), nullptr, nullptr),
make(fibo, make(sub, integer(x), integer(2), nullptr), nullptr, nullptr),
nullptr)));
}
int calc(int x) { return call(make(fibo, integer(x), nullptr, nullptr)); }
| 29.575758 | 80 | 0.67862 |
d66c414f4a81ebcad706510e5398609143c5fec0 | 355 | cpp | C++ | src/ai/context/RedLine.cpp | elikos/elikos_decisionmaking | d48379643e69ad5fa5dfb2fc79034ca259cf0012 | [
"MIT"
] | 1 | 2019-02-24T08:29:06.000Z | 2019-02-24T08:29:06.000Z | src/ai/context/RedLine.cpp | elikos/elikos_decisionmaking | d48379643e69ad5fa5dfb2fc79034ca259cf0012 | [
"MIT"
] | null | null | null | src/ai/context/RedLine.cpp | elikos/elikos_decisionmaking | d48379643e69ad5fa5dfb2fc79034ca259cf0012 | [
"MIT"
] | 1 | 2019-02-12T23:06:13.000Z | 2019-02-12T23:06:13.000Z | //
// Created by olivier on 01/07/16.
//
#include "TargetRobot.h"
#include "RedLine.h"
namespace ai
{
RedLine::RedLine(tf::Point& cornerA, tf::Point& cornerB)
: AbstractLine(cornerA, cornerB)
{
}
RedLine::~RedLine()
{
}
bool RedLine::isGoodLineIntersection(const TargetRobot& target)
{
// TODO: check target color
return false;
}
}
| 12.678571 | 63 | 0.667606 |
698fc27608fd90d3e1f3a9d36213e8ef85c75628 | 1,507 | cpp | C++ | app/UseSelectionDialog.cpp | Toysoft/ciderpress | 640959dad551ba75a48bd3c49629579730ead351 | [
"BSD-3-Clause"
] | 84 | 2015-01-01T00:27:18.000Z | 2022-03-28T22:55:56.000Z | app/UseSelectionDialog.cpp | Toysoft/ciderpress | 640959dad551ba75a48bd3c49629579730ead351 | [
"BSD-3-Clause"
] | 49 | 2015-01-11T19:58:57.000Z | 2022-01-08T00:27:12.000Z | app/UseSelectionDialog.cpp | Toysoft/ciderpress | 640959dad551ba75a48bd3c49629579730ead351 | [
"BSD-3-Clause"
] | 19 | 2015-06-06T15:23:18.000Z | 2022-01-12T23:26:43.000Z | /*
* CiderPress
* Copyright (C) 2007 by faddenSoft, LLC. All Rights Reserved.
* See the file LICENSE for distribution terms.
*/
#include "stdafx.h"
#include "UseSelectionDialog.h"
BEGIN_MESSAGE_MAP(UseSelectionDialog, CDialog)
ON_WM_HELPINFO()
//ON_COMMAND(IDHELP, OnHelp)
END_MESSAGE_MAP()
BOOL UseSelectionDialog::OnInitDialog(void)
{
CString str;
CString selStr;
CWnd* pWnd;
CDialog::OnInitDialog();
/* grab the radio button with the selection count */
pWnd = GetDlgItem(IDC_USE_SELECTED);
ASSERT(pWnd != NULL);
/* set the string using a string table entry */
if (fSelectedCount == 1) {
CheckedLoadString(&str, fSelCountID);
pWnd->SetWindowText(str);
} else {
CheckedLoadString(&str, fSelCountsID);
selStr.Format((LPCWSTR) str, fSelectedCount);
pWnd->SetWindowText(selStr);
if (fSelectedCount == 0)
pWnd->EnableWindow(FALSE);
}
/* set the other strings */
CheckedLoadString(&str, fTitleID);
SetWindowText(str);
pWnd = GetDlgItem(IDC_USE_ALL);
ASSERT(pWnd != NULL);
CheckedLoadString(&str, fAllID);
pWnd->SetWindowText(str);
pWnd = GetDlgItem(IDOK);
ASSERT(pWnd != NULL);
CheckedLoadString(&str, fOkLabelID);
pWnd->SetWindowText(str);
return TRUE;
}
void UseSelectionDialog::DoDataExchange(CDataExchange* pDX)
{
DDX_Radio(pDX, IDC_USE_SELECTED, fFilesToAction);
}
| 24.704918 | 64 | 0.640345 |
6992ef5cb96dee2ed33ecffa86cf2fea2bbada98 | 1,054 | cpp | C++ | drake/util/closestExpmapmex.cpp | ericmanzi/double_pendulum_lqr | 76bba3091295abb7d412c4a3156258918f280c96 | [
"BSD-3-Clause"
] | 4 | 2018-04-16T09:54:52.000Z | 2021-03-29T21:59:27.000Z | drake/util/closestExpmapmex.cpp | ericmanzi/double_pendulum_lqr | 76bba3091295abb7d412c4a3156258918f280c96 | [
"BSD-3-Clause"
] | null | null | null | drake/util/closestExpmapmex.cpp | ericmanzi/double_pendulum_lqr | 76bba3091295abb7d412c4a3156258918f280c96 | [
"BSD-3-Clause"
] | 1 | 2017-08-24T20:32:03.000Z | 2017-08-24T20:32:03.000Z | #include "mex.h"
#include "drakeMexUtil.h"
#include "drakeGradientUtil.h"
#include "drakeGeometryUtil.h"
using namespace std;
using namespace Eigen;
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
if (nrhs != 2) {
mexErrMsgIdAndTxt("Drake:closestExpmapmex:InvalidInputs","Usage is closestExpmap(expmap1,expmap2)");
}
if (mxGetM(prhs[0]) != 3 || mxGetN(prhs[0]) != 1) {
mexErrMsgIdAndTxt("Drake:closestExpmapmex:InvalidInputs","expmap1 should be a 3 x 1 vector");
}
Map<Vector3d> expmap1(mxGetPr(prhs[0]));
if (mxGetM(prhs[1]) != 3 || mxGetN(prhs[1]) != 1) {
mexErrMsgIdAndTxt("Drake:closestExpmapmex:InvalidInputs","expmap2 should be a 3 x 1 vector");
}
Map<Vector3d> expmap2(mxGetPr(prhs[1]));
int gradient_order;
if (nlhs>1) {
gradient_order = 1;
}
else {
gradient_order = 0;
}
GradientVar<double,3,1> ret = closestExpmap(expmap1, expmap2,gradient_order);
plhs[0] = eigenToMatlab(ret.value());
if (nlhs>1) {
plhs[1] = eigenToMatlab(ret.gradient().value());
}
}
| 30.114286 | 104 | 0.680266 |
69936abdf09f2bb3af3d7e3ffd4be62b0809830e | 1,283 | cpp | C++ | ReactionPlus/Exec/InputDevice.cpp | stricq/AmigaSynergy | fd81da853b3c5a50a2bb5c160c5f7320daaa7571 | [
"MIT"
] | 1 | 2022-03-05T11:30:18.000Z | 2022-03-05T11:30:18.000Z | ReactionPlus/Exec/InputDevice.cpp | stricq/AmigaSynergy | fd81da853b3c5a50a2bb5c160c5f7320daaa7571 | [
"MIT"
] | null | null | null | ReactionPlus/Exec/InputDevice.cpp | stricq/AmigaSynergy | fd81da853b3c5a50a2bb5c160c5f7320daaa7571 | [
"MIT"
] | 1 | 2022-03-06T11:22:44.000Z | 2022-03-06T11:22:44.000Z | #include "InputDevice.hpp"
#include <proto/exec.h>
namespace RAPlus {
namespace Exec {
InputDevice::InputDevice() {
stdRequest = new StandardIORequest();
inputBit = stdRequest->getSignal();
inputStat = IExec->OpenDevice("input.device",0,stdRequest->getIORequest(),0);
if (inputStat != 0) {
delete stdRequest;
throw InputDeviceException();
}
}
InputDevice::~InputDevice() {
if (inputStat == 0) IExec->CloseDevice(stdRequest->getIORequest());
delete stdRequest;
}
void InputDevice::addEvent(InputEvent &event) {
stdRequest->setCommand(IND_ADDEVENT);
stdRequest->setData(event.getInputEvent());
stdRequest->setLength(event.getLength());
IExec->DoIO(stdRequest->getIORequest());
}
void InputDevice::writeEvent(InputEvent &event) {
stdRequest->setCommand(IND_WRITEEVENT);
stdRequest->setData(event.getInputEvent());
stdRequest->setLength(event.getLength());
IExec->DoIO(stdRequest->getIORequest());
}
void InputDevice::addHandler(Interrupt &interrupt) {
stdRequest->setCommand(IND_ADDHANDLER);
stdRequest->setData(interrupt.getInterrupt());
IExec->DoIO(stdRequest->getIORequest());
}
}
}
| 18.328571 | 83 | 0.64926 |
6996320db8fe0598e39bb64e6787114c0b66766d | 1,275 | hpp | C++ | vcl/math/interpolation/interpolation.hpp | PPonc/inf443-vcl | 4d7bb0130c4bc44e089059464223eca318fdbd00 | [
"MIT"
] | null | null | null | vcl/math/interpolation/interpolation.hpp | PPonc/inf443-vcl | 4d7bb0130c4bc44e089059464223eca318fdbd00 | [
"MIT"
] | null | null | null | vcl/math/interpolation/interpolation.hpp | PPonc/inf443-vcl | 4d7bb0130c4bc44e089059464223eca318fdbd00 | [
"MIT"
] | null | null | null | #pragma once
#include "../../containers/containers.hpp"
namespace vcl
{
/** Interpolate value(x,y) using bilinear interpolation
* - value: grid_2D - coordinates assumed to be its indices
* - (x,y): coordinates assumed to be \in [0,value.dimension.x-1] X [0,value.dimension.y]
*/
template <typename T>
T interpolation_bilinear(grid_2D<T> const& value, float x, float y);
}
namespace vcl
{
template <typename T>
T interpolation_bilinear(grid_2D<T> const& value, float x, float y)
{
int const x0 = int(std::floor(x));
int const y0 = int(std::floor(y));
int const x1 = x0+1;
int const y1 = y0+1;
assert_vcl_no_msg(x0>=0 && x0<value.dimension.x);
assert_vcl_no_msg(x1>=0 && x1<value.dimension.x);
assert_vcl_no_msg(y0>=0 && y0<value.dimension.y);
assert_vcl_no_msg(y1>=0 && y1<value.dimension.y);
float const dx = x-x0;
float const dy = y-y0;
assert_vcl_no_msg(dx>=0 && dx<1);
assert_vcl_no_msg(dy>=0 && dy<1);
T const v =
(1-dx)*(1-dy)*value(x0,y0) +
(1-dx)*dy*value(x0,y1) +
dx*(1-dy)*value(x1,y0) +
dx*dy*value(x1,y1);
return v;
}
}
| 28.333333 | 93 | 0.561569 |
6997e7c2e38f14160b33edd8880fd941a466dad3 | 2,799 | cpp | C++ | libraries/palindrome/palindrome.cpp | AndreTeixeira1998/Arduino | 16918bada3cf9dfee0f6baa72ee1de87602b84ca | [
"MIT"
] | 1,253 | 2015-01-03T17:07:53.000Z | 2022-03-22T11:46:42.000Z | libraries/palindrome/palindrome.cpp | AndreTeixeira1998/Arduino | 16918bada3cf9dfee0f6baa72ee1de87602b84ca | [
"MIT"
] | 134 | 2015-01-21T20:33:13.000Z | 2022-01-05T08:59:33.000Z | libraries/palindrome/palindrome.cpp | AndreTeixeira1998/Arduino | 16918bada3cf9dfee0f6baa72ee1de87602b84ca | [
"MIT"
] | 3,705 | 2015-01-02T17:03:16.000Z | 2022-03-31T13:20:30.000Z | //
// FILE: palindrome.cpp
// AUTHOR: Rob Tillaart
// VERSION: 0.1.1
// PURPOSE: Arduino library to do palindrome experiments.
// URL: https://github.com/RobTillaart/palindrome
//
// HISTORY:
// 0.1.0 2021-12-02 initial version
// 0.1.1 2021-12-03 add palindromeCount(), palindromePercentage()
#include "palindrome.h"
palindrome::palindrome()
{
}
bool palindrome::isPalindrome(const char * str)
{
if (str == NULL) return false;
int sl = strlen(str);
if (sl == 0) return false;
int j = 0;
int k = sl - 1;
bool palin = (str[j++] == str[k--]);
while (palin & ( j < k ))
{
palin = (str[j++] == str[k--]);
}
return palin;
}
int palindrome::findPalindrome(const char * str, int & position, int & length)
{
if (str == NULL) return 0;
int posOdd = 0, lengthOdd = 0;
int posEven = 0, lengthEven = 0;
findOddPalindrome(str, posOdd, lengthOdd);
findEvenPalindrome(str, posEven, lengthEven);
if (lengthEven > lengthOdd)
{
position = posEven;
length = lengthEven;
return length;
}
position = posOdd;
length = lengthOdd;
return length;
}
int palindrome::findEvenPalindrome(const char * str, int & position, int & length)
{
if (str == NULL) return 0;
int sl = strlen(str);
if (sl == 0) return -1;
int newpos = 0;
int newlen = 1;
for (int i = 0; i < sl; i++)
{
if (str[i] != str[i + 1]) continue;
int j = i - 1;
int k = i + 2;
while (0 <= j && k < sl)
{
if (str[j] != str[k]) break;
j--;
k++;
}
int pos = j + 1;
int len = k - j - 1;
if (len > newlen)
{
newlen = len;
newpos = pos;
}
}
position = newpos;
length = newlen;
return length;
}
int palindrome::findOddPalindrome(const char * str, int & position, int & length)
{
if (str == NULL) return 0;
int sl = strlen(str);
if (sl == 0) return -1;
int newpos = 0;
int newlen = 1;
for (int i = 1; i < sl; i++)
{
int j = i - 1;
int k = i + 1;
while (0 <= j && k < sl)
{
if (str[j] != str[k]) break;
j--;
k++;
}
int pos = j + 1;
int len = k - j - 1;
if (len > newlen)
{
newlen = len;
newpos = pos;
}
}
position = newpos;
length = newlen;
return length;
}
int palindrome::palindromeCount(const char * str)
{
if (str == NULL) return 0;
int sl = strlen(str);
if (sl == 0) return 0;
int j = 0;
int k = sl - 1;
int count = 0;
while (j <= k)
{
if (str[j++] == str[k--]) count++;
}
return count;
}
float palindrome::palindromePercentage(const char * str)
{
if (str == NULL) return 0;
int sl = strlen(str);
if (sl == 0) return 0;
if (sl % 2 == 1) sl++; // correction for odd length strings
return (200.0 * palindromeCount(str)) / sl;
}
// -- END OF FILE --
| 18.175325 | 82 | 0.548053 |
6997eb447539139d2be85fd1a995623a2736089d | 1,549 | cpp | C++ | src/eduroam.cpp | ShanghaitechGeekPie/Auth-esp32-to-ShanghaiTech-wifi | 5fe779fe64a46378efb8e8c97a42ece88e2bb486 | [
"MIT"
] | null | null | null | src/eduroam.cpp | ShanghaitechGeekPie/Auth-esp32-to-ShanghaiTech-wifi | 5fe779fe64a46378efb8e8c97a42ece88e2bb486 | [
"MIT"
] | null | null | null | src/eduroam.cpp | ShanghaitechGeekPie/Auth-esp32-to-ShanghaiTech-wifi | 5fe779fe64a46378efb8e8c97a42ece88e2bb486 | [
"MIT"
] | null | null | null | #include <eduroam.h>
void connect_to_eduroam_task(void* void_edrp){
const char* ssid = "eduroam";
eduroam_recipe *edrp = (eduroam_recipe *)void_edrp;
// WPA2 enterprise magic starts here
WiFi.disconnect(true);
WiFi.mode(WIFI_STA);
esp_wifi_sta_wpa2_ent_set_identity((uint8_t *)edrp->eduroam_id, strlen(edrp->eduroam_id));
esp_wifi_sta_wpa2_ent_set_username((uint8_t *)edrp->eduroam_id, strlen(edrp->eduroam_id));
esp_wifi_sta_wpa2_ent_set_password((uint8_t *)edrp->eduroam_password, strlen(edrp->eduroam_password));
esp_wpa2_config_t config = WPA2_CONFIG_INIT_DEFAULT();
esp_wifi_sta_wpa2_ent_enable(&config);
WiFi.begin(ssid);
// TODO: throw error if eduroam not in range
// TODO: throw error if account not valid
while (WiFi.status() != WL_CONNECTED) {
delay(200);
}
if(edrp->caller) xTaskNotifyGive(edrp->caller);
}
bool connect_to_eduroam(const char *eduroam_id, const char *eduroam_password){
eduroam_recipe edrp = {eduroam_id, eduroam_password, NULL};
connect_to_eduroam_task(&edrp);
return true;
}
bool connect_to_eduroam(const char *eduroam_id, const char *eduroam_password, int ms_to_wait){
TaskHandle_t edu_connect_task;
TickType_t xTicksToWait = ms_to_wait / portTICK_PERIOD_MS;
eduroam_recipe edrp = {eduroam_id, eduroam_password, xTaskGetCurrentTaskHandle()};
xTaskCreate(connect_to_eduroam_task, "eduroam_connecting_task", 2048, &edrp, 0, &edu_connect_task);
int success = ulTaskNotifyTake(pdTRUE, xTicksToWait);
vTaskDelete(edu_connect_task);
return (bool)success;
} | 34.422222 | 104 | 0.770174 |