blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
71adb909b0149e1a7b472c3464e6f1177fe08693
|
281029170ce96d1117985785df44977733a069df
|
/Arrays and Maths/Majority Element II/code.cpp
|
5d2379529e98777f917d4b2f0a306d4142a781a6
|
[] |
no_license
|
suniti0804/SDE-Sheet_LeetCode
|
e8ef66d85e00705328694e05a73485e90e1758d5
|
8d2c0a5f782437c6642165e2cc9ddb233ebd4659
|
refs/heads/main
| 2023-07-20T08:53:36.284186
| 2021-08-22T12:21:39
| 2021-08-22T12:21:39
| 391,435,763
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,056
|
cpp
|
code.cpp
|
int n = nums.size();
int count1 = 0, count2 = 0;
int first = INT_MAX, second = INT_MAX;
for(int i = 0; i < n; i++)
{
if(first == nums[i])
count1++;
else if(second == nums[i])
count2++;
else if(count1 == 0)
{
first = nums[i];
count1++;
}
else if(count2 == 0)
{
second = nums[i];
count2++;
}
else
{
count1--;
count2--;
}
}
count1 = 0, count2 = 0;
for(int i = 0; i < n; i++)
{
if(nums[i] == first)
count1++;
else if(nums[i] == second)
count2++;
}
vector<int> res;
if(count1 > n/3)
res.push_back(first);
if(count2 > n/3)
res.push_back(second);
return res;
}
|
4e5feed041f8af7d97b5639db318666db7cdc928
|
65d9f1776ce7111ebd256c62788756992483d133
|
/src/Pool/Semaphore.hpp
|
e2705cfc7389bf047c7dd70ebf377f9edae65992
|
[
"MIT"
] |
permissive
|
VVZhebel/FlyQueue
|
c64a2add481104875911d6e955a2a8e8c07e7885
|
26f8d193d299ee898d7f6c414ac14c0ffc21d5c8
|
refs/heads/main
| 2023-04-11T16:05:19.861419
| 2021-04-21T16:49:42
| 2021-04-21T16:49:42
| 357,977,033
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 661
|
hpp
|
Semaphore.hpp
|
#pragma once
#include <mutex>
#include <condition_variable>
class Semaphore{
public:
explicit Semaphore() : count(0) {}
void enter(){
std::unique_lock<std::mutex> lock(locker);
while (count == 0) cv.wait(lock);
--count;
}
void add(){
std::lock_guard<std::mutex> lock(locker);
++count;
cv.notify_all();
}
inline void unleash(){
count = -1;
cv.notify_all();
}
private:
int count;
std::mutex locker;
std::condition_variable cv;
};
|
f29eddea5eb19fef045c17376fd0371e2d8f1620
|
38b057c7dea2e7b9015e3fce67726cb1678a90b1
|
/libs/z3/src/muz/transforms/dl_mk_array_instantiation.h
|
51a818a3f3af87c30fda7d8e68bfb6ea21652da0
|
[
"MIT"
] |
permissive
|
anhvvcs/corana
|
3ef150667e8124c19238a3f75a875096bbf698c5
|
dc40868ee4ba1c6148547fb125fddccfb0d446c3
|
refs/heads/master
| 2023-08-10T07:04:37.740227
| 2023-07-24T20:41:30
| 2023-07-24T20:41:30
| 181,912,504
| 34
| 4
|
MIT
| 2023-06-29T03:32:18
| 2019-04-17T14:49:09
|
C
|
UTF-8
|
C++
| false
| false
| 5,736
|
h
|
dl_mk_array_instantiation.h
|
/*++
Module Name:
dl_mk_array_instantiation.h
Abstract:
Transforms predicates so that array invariants can be discovered.
Motivation : Given a predicate P(a), no quantifier-free solution can express that P(a) <=> forall i, P(a[i]) = 0
Solution : Introduce a fresh variable i, and transform P(a) into P!inst(i, a).
Now, (P!inst(i,a) := a[i] = 0) <=> P(a) := forall i, a[i] = 0.
Transformation on Horn rules:
P(a, args) /\ phi(a, args, args') => P'(args') (for simplicity, assume there are no arrays in args').
Is transformed into:
(/\_r in read_indices(phi) P!inst(r, a, args)) /\ phi(a, args, args') => P'(args')
Limitations : This technique can only discover invariants on arrays that depend on one quantifier.
Related work : Techniques relying on adding quantifiers and eliminating them. See dl_mk_quantifier_abstraction and dl_mk_quantifier_instantiation
Implementation:
The implementation follows the solution suggested above, with more options. The addition of options implies that in the simple
case described above, we in fact have P(a) transformed into P(i, a[i], a).
1) Dealing with multiple quantifiers -> The options fixedpoint.xform.instantiate_arrays.nb_quantifier gives the number of quantifiers per array.
2) Enforcing the instantiation -> We suggest an option (enforce_instantiation) to enforce this abstraction. This transforms
P(a) into P(i, a[i]). This enforces the solver to limit the space search at the cost of imprecise results. This option
corresponds to fixedpoint.xform.instantiate_arrays.enforce
3) Adding slices in the mix -> We wish to have the possibility to further restrict the search space: we want to smash cells, given a smashing rule.
For example, in for loops j=0; j<n; j++, it might be relevant to restrict the search space and look for invariants that only depend on whether
0<=i<j or j<=i, where i is the quantified variable.
Formally, a smashing rule is a function from the Index set (usually integer) to integers (the id set).
GetId(i) should return the id of the set i belongs in.
In our example, we can give 0 as the id of the set {n, 0<=n<j} and 1 for the set {n, j<=n}, and -1 for the set {n, n<0}. We then have
GetId(i) = ite(i<0, -1, ite(i<j, 0, 1))
Given that GetId function, P(a) /\ phi(a, ...) => P'(...) is transformed into
(/\_r in read_indices(phi) P!inst(id_r, a[r], a) /\ GetId(r) = id_r) /\ phi(a, ...) => P'(...).
Note : when no slicing is done, GetId(i) = i.
This option corresponds to fixedpoint.xform.instantiate_arrays.slice_technique
Although we described GetId as returning integers, there is no reason to restrict the type of ids to integers. A more direct method,
for the 0<=i<j or j<=i case could be :
GetId(i) = (i<0, i<j)
GetId is even more powerful as we deal with the multiple quantifiers on multiple arrays.
For example, we can use GetId to look for the same quantifiers in each array.
Assume we have arrays a and b, instantiated with one quantifier each i and j.
We can have GetId(i,j) = ite(i=j, (i, true), (fresh, false))
4) Reducing the set of r in read_indices(phi): in fact, we do not need to "instantiate" on all read indices of phi,
we can restrict ourselves to those "linked" to a, through equalities and stores.
Author:
Julien Braine
Revision History:
--*/
#ifndef DL_MK_ARRAY_INSTANTIATION_H_
#define DL_MK_ARRAY_INSTANTIATION_H_
#include "ast/rewriter/factor_equivs.h"
#include "muz/base/dl_rule_transformer.h"
namespace datalog {
class context;
class mk_array_instantiation : public rule_transformer::plugin {
//Context objects
ast_manager& m;
context& m_ctx;
array_util m_a;
//Rule set context
const rule_set*src_set;
rule_set*dst;
rule_manager* src_manager;
//Rule context
obj_map<expr, ptr_vector<expr> > selects;
expr_equiv_class eq_classes;
unsigned cnt;//Index for new variables
obj_map<expr, var*> done_selects;
expr_ref_vector ownership;
//Helper functions
void instantiate_rule(const rule& r, rule_set & dest);//Instantiates the rule
void retrieve_selects(expr* e);//Retrieves all selects (fills the selects and eq_classes members)
expr_ref rewrite_select(expr*array, expr*select);//Rewrites select(a, args) to select(array, args)
expr_ref_vector retrieve_all_selects(expr*array);//Retrieves all selects linked to a given array (using eq classes and selects)
expr_ref_vector instantiate_pred(app*old_pred);//Returns all the instantiation of a given predicate
expr_ref create_pred(app*old_pred, expr_ref_vector& new_args);//Creates a predicate
expr_ref create_head(app* old_head);//Creates the new head
var * mk_select_var(expr* select);
/*Given the old predicate, and the new arguments for the new predicate, returns the new setId arguments.
By default getId(P(x, y, a, b), (x, y, a[i], a[j], a, b[k], b[l], b)) (nb_quantifier=2, enforce=false)
returns (i,j,k,l)
So that the final created predicate is P!inst(x, y, a[i], a[j], a, b[k], b[l], b, i, j, k, l)
*/
expr_ref_vector getId(app*old_pred, const expr_ref_vector& new_args);
public:
mk_array_instantiation(context & ctx, unsigned priority);
rule_set * operator()(rule_set const & source) override;
~mk_array_instantiation() override{}
};
};
#endif /* DL_MK_ARRAY_INSTANTIATION_H_ */
|
4e348c86ec942d52ce6512ea068e940418202633
|
c8effd86fcef400d48ef420e1597a929078adde3
|
/C3DShellCodingTutorial (Qt)/C3DShellCodingTutorial/C3DShellCodingTutorial/res/texts/kernel/op_shell_parameter.h
|
f30c7f111b775b4c8d9ba337622bf3530ecb508f
|
[] |
no_license
|
proxzi/Projects
|
60d7d7c4de8d3e377f4b01df679ef3fa7fe72098
|
09749cce546dba1122ff53c153d83be4bf7d5f9f
|
refs/heads/main
| 2023-02-25T05:32:53.442023
| 2021-02-08T23:24:37
| 2021-02-08T23:24:37
| 337,149,007
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 202,797
|
h
|
op_shell_parameter.h
|
////////////////////////////////////////////////////////////////////////////////
/**
\file
\brief \ru Параметры операций над телами.
\en Parameters of operations on the solids. \~
*/
////////////////////////////////////////////////////////////////////////////////
#ifndef __OP_SHELL_PARAMETERS_H
#define __OP_SHELL_PARAMETERS_H
#include <templ_rp_array.h>
#include <templ_array2.h>
#include <templ_css_array.h>
#include <math_version.h>
#include <math_define.h>
#include <mb_nurbs_function.h>
#include <op_binding_data.h>
#include <op_boolean_flags.h>
#include <cr_split_data.h>
#include <vector>
#include <utility>
class MATH_CLASS MbPoint3D;
class MATH_CLASS MbPolyCurve3D;
class MATH_CLASS MbPolyline3D;
class MATH_CLASS MbSurface;
class MATH_CLASS MbSurfaceCurve;
class MATH_CLASS MbPlane;
class MATH_CLASS MbCurveEdge;
class MATH_CLASS MbFace;
class MATH_CLASS MbFaceShell;
class MATH_CLASS MbSolid;
class MATH_CLASS MbSNameMaker;
class MbRegTransform;
class MbRegDuplicate;
//------------------------------------------------------------------------------
/** \brief \ru Параметры скругления или фаски ребра.
\en Parameters of fillet or chamfer of edge. \~
\details \ru Параметры скругления или фаски ребра содержат информацию, необходимую для выполнения операции. \n
\en The parameter of fillet or chamfer of edge contain Information necessary to perform the operation. \n \~
\ingroup Build_Parameters
*/
// ---
struct MATH_CLASS SmoothValues {
public:
/// \ru Способы обработки углов стыковки трёх рёбер. \en Methods of processing corners of connection by three edges.
enum CornerForm {
ec_pointed = 0, ///< \ru Обработка угла отсутствует. \en Processing of corner is missing.
ec_either = 1, ///< \ru Стыкующиеся в одной точке три ребра обрабатываются в порядке внутренней нумерации ребер без учета выпуклости и вогнутости. \en Mating at one point of three edges are processed in the order of internal indexation of edges without convexity and concavity.
ec_uniform = 2, ///< \ru Если в точке стыкуются два выпуклых (вогнутых) и одно вогнутое (выпуклое) ребро, то первым обрабатывается вогнутое (выпуклое) ребро. \en If two convex (concave) and one concave (convex) edge are mated at the point, then concave (convex) edge is processed at the first.
ec_sharp = 3, ///< \ru Если в точке стыкуются два выпуклых (вогнутых) и одно вогнутое (выпуклое) ребро, то первыми обрабатываются выпуклые (вогнутые) ребра. \en If two convex (concave) and one concave (convex) edge are mated at the point, then concave (convex) edges are processed at the first.
};
public:
double distance1; ///< \ru Радиус кривизны/катет на первой поверхности. \en Radius of curvature/leg on the first surface.
double distance2; ///< \ru Радиус кривизны/катет на второй поверхности. \en Radius of curvature/leg on the second surface.
double conic; ///< \ru Коэффициент формы, изменяется от 0.05 до 0.95 (при 0 - дуга окружности). \en Coefficient of shape is changed from 0.05 to 0.95 (if 0 - circular arc).
double begLength; ///< \ru Расстояние от начала скругления до точки остановки (UNDEFINED_DBL - остановки нет). \en Distance from the beginning of fillet to the stop point (UNDEFINED_DBL - no stop).
double endLength; ///< \ru Расстояние от конца скругления до точки остановки (UNDEFINED_DBL - остановки нет). \en Distance from the end of fillet to the stop point (UNDEFINED_DBL - no stop).
MbeSmoothForm form; ///< \ru Тип сопряжения скругление/фаска. \en Mate type of fillet/chamfer.
CornerForm smoothCorner; ///< \ru Способ обработки углов стыковки трёх рёбер. \en Method of processing corners of connection by three edges.
bool prolong; ///< \ru Продолжить по касательной. \en Prolong along the tangent.
ThreeStates keepCant; ///< \ru Автоопределение сохранения кромки (ts_neutral), сохранение поверхности (ts_negative), сохранение кромки (ts_positive). \en Auto detection of boundary saving (ts_neutral), surface saving (ts_negative), boundary saving (ts_positive).
bool strict; ///< \ru При false скруглить хотя бы то, что возможно. \en If false - round at least what is possible.
bool equable; ///< \ru В углах сочленения вставлять тороидальную поверхность (для штамповки листового тела). \en In corners of the joint insert toroidal surface (for stamping sheet solid).
private:
MbVector3D vector1; ///< \ru Вектор нормали к плоскости, по которой выполняется усечение скругления в начале цепочки. \en Normal vector of the plane cutting the fillet at the beginning of chain.
MbVector3D vector2; ///< \ru Вектор нормали к плоскости, по которой выполняется усечение скругления в конце цепочки. \en Normal vector of the plane cutting the fillet at the end of chain.
public:
/// \ru Конструктор по умолчанию. \en Default constructor.
SmoothValues()
: distance1 ( 1.0 )
, distance2 ( 1.0 )
, conic ( c3d::_ARC_ )
, begLength (UNDEFINED_DBL)
, endLength (UNDEFINED_DBL)
, form ( st_Fillet )
, smoothCorner ( ec_uniform )
, prolong ( false )
, keepCant ( ts_negative )
, strict ( true )
, equable ( false )
, vector1 ( )
, vector2 ( )
{}
/** \brief \ru Конструктор.
\en Constructor. \~
\details \ru Конструктор по параметрам.
\en Constructor by parameters. \~
\param[in] d1, d2 - \ru Радиусы кривизны/катеты.
\en Radii of curvature/catheti. \~
\param[in] f - \ru Способ построения поверхности сопряжения.
\en Method of construction of mating surface. \~
\param[in] c - \ru Коэффициент формы, изменяется от 0.05 до 0.95 (при 0 - дуга окружности).
\en Coefficient of shape is changed from 0.05 to 0.95 (if 0 - circular arc). \~
\param[in] pro - \ru Продолжить по касательной.
\en Prolong along the tangent. \~
\param[in] cor - \ru Способ скругления "чемоданных" углов.
\en Method for bending corner of three surfaces. \~
\param[in] autoS - \ru Автоопределение сохранения кромки/поверхности.
\en Auto detection of boundary/surface saving. \~
\param[in] keep - \ru Сохранять кромку (true) или сохранять поверхность скругления/фаски (false).
\en Keep boundary (true) or keep surface of fillet/chamfer (false). \~
\param[in] str - \ru Строгое скругление. Если false, скруглить хотя бы то, что возможно.
\en Strict fillet. If false - round at least what is possible. \~
\param[in] equ - \ru В углах сочленения вставлять тороидальную поверхность.
\en In corners of the joint insert toroidal surface. \~
*/
SmoothValues( double d1, double d2, MbeSmoothForm f, double c, bool pro,
CornerForm cor, bool autoS, bool keep, bool str, bool equ )
: distance1 ( d1 )
, distance2 ( d2 )
, conic ( c )
, begLength (UNDEFINED_DBL)
, endLength (UNDEFINED_DBL)
, form ( f )
, smoothCorner ( cor )
, prolong ( pro )
, keepCant ( ts_negative )
, strict ( str )
, equable ( equ )
, vector1 ( )
, vector2 ( )
{
keepCant = autoS ? ts_neutral : ts_negative;
if ( keep )
keepCant = ts_positive;
}
/// \ru Конструктор копирования. \en Copy-constructor.
SmoothValues( const SmoothValues & other, MbRegDuplicate * iReg = NULL );
/// \ru Деструктор. \en Destructor.
virtual ~SmoothValues(){}
/// \ru Функция инициализации. \en Initialization function.
void Init( const SmoothValues & other );
public:
/// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix.
virtual void Transform( const MbMatrix3D &, MbRegTransform * ireg = NULL );
/// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector.
virtual void Move ( const MbVector3D &, MbRegTransform * /*ireg*/ = NULL ){}
/// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis.
virtual void Rotate ( const MbAxis3D &, double ang, MbRegTransform * ireg = NULL );
/// \ru Установить плоскость, параллельно которой будет выполнена остановка скругления в начале цепочки. \en Set the plane by which parallel will be carry out stop of the fillet at the begin.
bool SetStopObjectAtBeg( const MbSurface * object, bool byObject = true );
/// \ru Установить плоскость, параллельно которой будет выполнена остановка скругления в конце цепочки. \en Set the plane by which parallel will be carry out stop of the fillet at the end.
bool SetStopObjectAtEnd( const MbSurface * object, bool byObject = true );
/// \ru Установить вектор нормали к плоскости остановки скругления в начале цепочки. \en Set normal to the bound plane at the begin.
void SetBegVector( const MbVector3D & vect ) { vector1.Init( vect ); }
/// \ru Установить вектор нормали к плоскости остановки скругления в конце цепочки. \en Set normal to the bound plane at the end.
void SetEndVector( const MbVector3D & vect ) { vector2.Init( vect ); }
/// \ru Получить вектор нормали к плоскости остановки в начале скругления. \en Get normal vector to the bound plane at the begin of the fillet.
void GetBegVector( MbVector3D & vect ) const { vect.Init( vector1 ); }
/// \ru Получить вектор нормали к плоскости остановки в конце скругления. \en Get normal vector to the bound plane at the end of the fillet.
void GetEndVector( MbVector3D & vect ) const { vect.Init( vector2 ); }
/// \ru Оператор присваивания. \en Assignment operator.
SmoothValues & operator = ( const SmoothValues & other ) {
Init( other );
return *this;
}
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const SmoothValues & other, double accuracy ) const;
public:
KNOWN_OBJECTS_RW_REF_OPERATORS( SmoothValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class.
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры скругления грани.
\en Parameters of face fillet. \~
\details \ru Параметры скругления грани содержат информацию, необходимую для выполнения операции. \n
\en The parameters of face fillet contain Information necessary to perform the operation. \n \~
\ingroup Build_Parameters
*/
// ---
struct MATH_CLASS FullFilletValues {
public:
bool prolong; ///< \ru Продолжить по касательной. \en Prolong along the tangent.
public:
/// \ru Конструктор по умолчанию. \en Default constructor.
FullFilletValues()
: prolong ( true )
{}
/// \ru Конструктор по параметрам. \en Constructor by parameters.
FullFilletValues( bool prlg )
: prolong ( prlg )
{}
/// \ru Конструктор копирования. \en Copy-constructor.
FullFilletValues( const FullFilletValues & other, MbRegDuplicate * iReg = NULL );
/// \ru Деструктор. \en Destructor.
~FullFilletValues(){}
public:
/// \ru Функция инициализации. \en Initialization function.
void Init( const FullFilletValues & other );
/// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix.
void Transform( const MbMatrix3D &, MbRegTransform * ireg = NULL );
/// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector.
void Move ( const MbVector3D &, MbRegTransform * /*ireg*/ = NULL ){}
/// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis.
void Rotate ( const MbAxis3D &, double ang, MbRegTransform * ireg = NULL );
/// \ru Оператор присваивания. \en Assignment operator.
FullFilletValues & operator = ( const FullFilletValues & other ) {
Init( other );
return *this;
}
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const FullFilletValues & other, double accuracy ) const;
public:
KNOWN_OBJECTS_RW_REF_OPERATORS( FullFilletValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class.
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры скругления вершины.
\en Parameters of vertex fillet. \~
\details \ru Параметры скругления вершины, в которой стыкуются три ребра, содержат информацию, необходимую для выполнения операции. \n
\en Fillet parameters of vertex (where three edges are connected) contain information necessary to perform the operation \n \~
\ingroup Build_Parameters
*/
// ---
struct MATH_CLASS CornerValues {
public:
/// \ru Способы скругления вершины стыковки трёх рёбер. \en Methods of vertices fillet of connection by three edges.
enum CornerForm {
ef_sphere = 0, ///< \ru Скругление вершины сферической поверхностью. \en Vertex fillet by spherical surface.
ef_smart = 1, ///< \ru Скругление вершины гладкой поверхностью. \en Vertex fillet by smooth surface.
ef_delta = 3, ///< \ru Скругление вершины треугольной поверхностью. \en Vertex fillet by triangular surface.
ef_elbow1 = 4, ///< \ru Скругление вершины четырёхугольной поверхностью, четвёртую сторону располагать напротив range1. \en Vertex fillet by quadrangular surface, the fourth side is opposite the range1.
ef_elbow2 = 5, ///< \ru Скругление вершины четырёхугольной поверхностью, четвёртую сторону располагать напротив range2. \en Vertex fillet by quadrangular surface, the fourth side is opposite the range2.
ef_elbow3 = 6, ///< \ru Скругление вершины четырёхугольной поверхностью, четвёртую сторону располагать напротив range3. \en Vertex fillet by quadrangular surface, the fourth side is opposite the range3.
};
public:
double radius0; ///< \ru Радиус сферы в вершине. \en Radius of the sphere of the vertex.
double radius1; ///< \ru Радиус первого ребра вершины. \en Radius of the first edge of the vertex.
double radius2; ///< \ru Радиус второго ребра вершины. \en Radius of the second edge of the vertex.
double radius3; ///< \ru Радиус третьего ребра вершины. \en Radius of the third edge of the vertex.
CornerForm cornerForm; ///< \ru Способ скругления вершины стыковки трёх рёбер. \en Method of vertex fillet of connection by three edges.
uint8 additive; ///< \ru Сдвиг в нумерации рёбер вершины (добавка к номеру ребра). \en Shift in the indexation of vertex edges (addition to the index of edge).
public:
/// \ru Конструктор по умолчанию. \en Default constructor.
CornerValues()
: radius0 ( 0.0 )
, radius1 ( 1.0 )
, radius2 ( 1.0 )
, radius3 ( 1.0 )
, cornerForm( ef_smart )
, additive ( 0 )
{}
/// \ru Конструктор по параметрам. \en Constructor by parameters.
CornerValues( double r0, double r1, double r2, double r3, CornerForm ck )
: radius0 ( ::fabs(r0) )
, radius1 ( ::fabs(r1) )
, radius2 ( ::fabs(r2) )
, radius3 ( ::fabs(r3) )
, cornerForm( ck )
, additive ( 0 )
{}
/// \ru Конструктор копирования. \en Copy-constructor.
CornerValues( const CornerValues & other )
: radius0 ( other.radius0 )
, radius1 ( other.radius1 )
, radius2 ( other.radius2 )
, radius3 ( other.radius3 )
, cornerForm( other.cornerForm )
, additive ( other.additive )
{}
/// \ru Деструктор. \en Destructor.
virtual ~CornerValues();
/// \ru Функция инициализации. \en Initialization function.
void Init( const CornerValues & other ) {
radius0 = other.radius0;
radius1 = other.radius1;
radius2 = other.radius2;
radius3 = other.radius3;
cornerForm = other.cornerForm;
additive = other.additive;
}
/// \ru Циклическая перестановка параметров. \en Cyclic permutation of the parameters.
void CiclicSwap( bool increase );
/// \ru Поменять местами радиусы (constRadius = 1,2,3). \en Swap radii (constRadius = 1,2,3).
void Swap( int constRadius );
/// \ru Оператор присваивания. \en Assignment operator.
CornerValues & operator = ( const CornerValues & other ) {
Init( other );
return *this;
}
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const CornerValues & other, double accuracy ) const;
KNOWN_OBJECTS_RW_REF_OPERATORS( CornerValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class.
};
//------------------------------------------------------------------------------
/** \brief \ru Типы выемки.
\en Types of notch. \~
\details \ru Типы выемки. Служат для определения одного из построений: отверстий, карманов, пазов. \n
\en Types of notch. These are used to determine one from the constructions: holes, pockets, grooves. \n \~
\ingroup Build_Parameters
*/
// ---
enum MbeHoleType {
ht_BorerValues = 0, ///< \ru Отверстие. \en Hole.
ht_PocketValues = 1, ///< \ru Карман. \en Pocket.
ht_SlotValues = 2, ///< \ru Паз. \en Slot.
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры выемки.
\en The parameters of notch. \~
\details \ru Общие параметры построения выемки: отверстия, фигурного паза, кармана (бобышки). \n
\en The common parameters of notch construction: holes, figure slot, pocket (boss). \n \~
\ingroup Build_Parameters
*/
// ---
class MATH_CLASS HoleValues {
public:
double placeAngle; ///< \ru Угол между осью и нормалью к поверхности (0 <= placeAngle <= M_PI_2). \en Angle between axis and normal to the surface (0 <= placeAngle <= M_PI_2).
double azimuthAngle; ///< \ru Угол поворота оси вокруг нормали поверхности (-M_PI2 <= azimuthAngle <= M_PI2). \en Angle of rotation around the surface normal (-M_PI2 <= azimuthAngle <= M_PI2).
protected:
MbSurface * surface; ///< \ru Обрабатываемая поверхность (если NULL, то считается плоской). \en Processing surface (if NULL, then is considered planar).
bool doPhantom; ///< \ru Создавать фантом результата операции. \en Create the phantom of the operation.
protected:
/** \brief \ru Конструктор по умолчанию.
\en Default constructor. \~
\details \ru Конструктор параметров выемки с нулевыми углами и плоской поверхностью.
\en Constructor of notch parameters with zero angles and planar surfaces. \~
*/
HoleValues();
// \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default.
HoleValues( const HoleValues & other );
/// \ru Конструктор копирования. \en Copy-constructor.
HoleValues( const HoleValues & other, MbRegDuplicate * iReg );
public:
/// \ru Деструктор. \en Destructor.
virtual ~HoleValues();
public:
/// \ru Тип выемки. \en Type of notch.
virtual MbeHoleType Type() const = 0;
/// \ru Построить копию объекта. \en Create a copy of the object.
virtual HoleValues & Duplicate( MbRegDuplicate * ireg = NULL ) const = 0;
/// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix.
virtual void Transform( const MbMatrix3D &, MbRegTransform * ireg = NULL ) = 0;
/// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector.
virtual void Move ( const MbVector3D &, MbRegTransform * ireg = NULL );
/// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis.
virtual void Rotate ( const MbAxis3D &, double ang, MbRegTransform * ireg = NULL );
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
virtual bool IsSame( const HoleValues &, double accuracy ) const;
/// \ru Оператор присваивания. \en Assignment operator.
virtual void operator = ( const HoleValues & other ) = 0;
/// \ru Функция копирования. \en Copy function.
void Init( const HoleValues & init );
/// \ru Получить поверхность. \en Get the surface.
const MbSurface * GetSurface() const { return surface; }
/// \ru Заменить поверхность. \en Replace surface.
void SetSurface( MbSurface * s );
/// \ru Установить флаг создания фантома. \en Set the phantom flag.
void SetPhantom( bool s ) { doPhantom = s; }
/// \ru Получить флаг создания фантома. \en Get the phantom flag.
bool GetPhantom() const { return doPhantom; }
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры отверстия.
\en The hole parameters. \~
\details \ru Параметры для построения отверстий различных типов. \n
Законцовка отверстия управляется параметром spikeAngle.
При #spikeAngle = 0 - сферическая законцовка отверстия, \n
при #spikeAngle = M_PI - плоская законцовка отверстия, \n
в остальных случаях - коническая законцовка отверстия. \n
\en The parameters for construction of holes with different types. \n
Tip of hole is controlled by the spikeAngle parameter.
If # spikeAngle = 0 - spherical tip of hole, \n
If # spikeAngle = M - planar tip of hole, \n
in other cases - conical tip of hole. \n \~
\ingroup Build_Parameters
*/
// ---
class MATH_CLASS BorerValues : public HoleValues {
public:
/** \brief \ru Типы отверстий.
\en Types of holes. \~
\details \ru Тип определяет форму отверстия.
\en The type determines the hole shape. \~
\ingroup Build_Parameters
*/
enum BorerType {
//
// _______________
// /| |
// +-+-------------+
bt_SimpleCylinder = 0, ///< \ru Простое цилиндрическое отверстие. \en Simple cylindrical hole.
// __
// _____________||
// /| ||
// +-+------------++
bt_TwofoldCylinder = 1, ///< \ru Двойное цилиндрическое отверстие. \en Double cylindrical hole.
// /
// _____________/|
// /| ||
// +-+------------++
bt_ChamferCylinder = 2, ///< \ru Цилиндрическое отверстие с фаской. \en Cylindrical hole with a chamfer.
// ____
// __________/| |
// /| || |
// +-+---------++--+
bt_ComplexCylinder = 3, ///< \ru Двойное цилиндрическое отверстие с переходом. \en Double cylindrical hole with a transition.
//
// _______________
// /| |
// +-+-------------+
bt_SimpleCone = 4, ///< \ru Простое коническое отверстие. \en Simple conical hole.
// |
// ____________ /|
// /| | |
// +-+---------+---+
bt_ArcCylinder = 5, ///< \ru Центровое отверстие формы R (дугообразное). \en Center hole of form R (arcuate).
};
public:
double capDiameter; ///< \ru Диаметр головки (для отверстий типа #bt_TwofoldCylinder, #bt_ChamferCylinder, #bt_ComplexCylinder). \en Diameter cap (for hole with type #bt_TwofoldCylinder, #bt_ChamferCylinder, #bt_ComplexCylinder).
double capDepth; ///< \ru Глубина под головку (для отверстий типа #bt_TwofoldCylinder, #bt_ComplexCylinder). \en Depth for cap (for hole with type #bt_TwofoldCylinder, #bt_ChamferCylinder, #bt_ComplexCylinder).
double capAngle; ///< \ru Угол фаски под головку (для отверстий типа #bt_ChamferCylinder, #bt_ComplexCylinder), capAngle <= M_PI. \en Chamfer angle for cap (for holes with type #bt_ChamferCylinder, #bt_ComplexCylinder), capAngle <= M_PI.
double diameter; ///< \ru Диаметр отверстия под резьбу (для всех типов отверстий). \en Hole diameter for thread (for all the types of holes).
double depth; ///< \ru Глубина отверстия под резьбу (для всех типов отверстий). \en Hole depth for thread (for all the types of holes).
double angle; ///< \ru Угол конусности отверстия под резьбу (для отверстия типа #bt_SimpleCone), 0 < angle < M_PI. \en Angle of hole conicity for thread (for hole with type #bt_SimpleCone), 0 < angle < M_PI.
double spikeAngle; ///< \ru Угол раствора конца отверстия (для всех типов отверстий), spikeAngle <= M_PI. \en Apex angle of the hole end (for all the types of holes), spikeAngle <= M_PI.
double arcRadius; ///< \ru Радиус дуги (для отверстия типа #bt_ArcCylinder). \en Arc radius (for hole with type #bt_ArcCylinder).
bool prolong; ///< \ru Флаг продления сверла в обратную сторону (для всех типов отверстий), по умолчанию true (есть продление). \en Flag of drill extension along the opposite direction (for all the types of holes), default true (the extension exists).
bool down; ///< \ru Направление оси отверстия: true - прямое (против оси Z локальной системы), false - обратное. \en Direction of hole axis: true - forward (opposite to the Z of the local system), false - backward.
BorerType type; ///< \ru Тип отверстия. \en Type of hole.
private :
// \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default.
BorerValues( const BorerValues & other );
/// \ru Конструктор копирования. \en Copy-constructor.
BorerValues( const BorerValues & other, MbRegDuplicate * ireg );
public:
/** \brief \ru Конструктор по умолчанию.
\en Default constructor. \~
\details \ru Конструктор простого цилиндрического отверстия.
\en Constructor of simple cylindrical hole. \~
*/
BorerValues()
: HoleValues ()
, capDiameter( 20.0 )
, capDepth ( 5.0 )
, capAngle ( M_PI_2 )
, diameter ( 10.0 )
, depth ( 25.0 )
, angle ( M_PI_2 )
, spikeAngle ( M_PI * c3d::TWO_THIRD )
, arcRadius ( 10. )
, prolong ( true )
, down ( true )
, type ( bt_SimpleCylinder )
{}
/// \ru Деструктор. \en Destructor.
virtual ~BorerValues();
public:
virtual MbeHoleType Type() const; // \ru Тип выемки. \en Type of notch.
virtual HoleValues & Duplicate( MbRegDuplicate * ireg = NULL ) const; // \ru Построить копию. \en Create a copy.
virtual void Transform( const MbMatrix3D & matr, MbRegTransform * ireg = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix.
virtual bool IsSame( const HoleValues &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal?
virtual void operator = ( const HoleValues & other ); // \ru Оператор присваивания. \en Assignment operator.
private:
// \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default.
void operator = ( const BorerValues & other );
public:
KNOWN_OBJECTS_RW_REF_OPERATORS( BorerValues ) // \ru Для работы со ссылками и объектами класса \en For treatment of references and objects of the class
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры кармана или бобышки.
\en The parameters of pocket or boss. \~
\details \ru Параметры прямоугольного кармана или бобышки со скруглёнными углами. \n
\en The parameters of rectangular pocket or boss with rounded corners. \n \~
\ingroup Build_Parameters
*/
// ---
class MATH_CLASS PocketValues : public HoleValues {
public:
double length; ///< \ru Длина кармана или бобышки. \en The length of pocket or boss.
double width; ///< \ru Ширина кармана или бобышки. \en The width of pocket or boss.
double depth; ///< \ru Глубина кармана или бобышки. \en The depth of pocket or boss.
/** \brief \ru Радиус скругления углов кармана или бобышки.
\en Fillet radius of corners of pocket or boss. \~
\details \ru Радиус скругления углов кармана или бобышки, 2 * cornerRadius <= std_min( width, length ).
При length == width == 2 * cornerRadius получим карман в виде отверстия.
\en Fillet radius of corners of pocket or boss, 2 * cornerRadius <= std_min( width, length ).
If length == width == 2 * cornerRadius, then pocket as a hole. \~
*/
double cornerRadius;
double floorRadius; ///< \ru Радиус скругления дна кармана или верха бобышки. \en Fillet radius of bottom of pocket or top of boss.
double taperAngle; ///< \ru Угол уклона стенок кармана или верха бобышки (отклонение от вертикали в радианах). \en Draft angle of pocket walls or top of boss (vertical deviation in radians)
bool type; ///< \ru type == false - карман, type == true - бобышка. \en Type == false - pocket, type == true - boss.
private :
// \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default.
PocketValues( const PocketValues & other );
/// \ru Конструктор копирования. \en Copy-constructor.
PocketValues( const PocketValues & other, MbRegDuplicate * ireg );
public:
/** \brief \ru Конструктор по умолчанию.
\en Default constructor. \~
\details \ru Конструктор кармана.
\en Constructor of pocket. \~
*/
PocketValues()
: HoleValues ()
, length ( 20.0 )
, width ( 10.0 )
, depth ( 5.0 )
, cornerRadius( 2.0 )
, floorRadius ( 1.0 )
, taperAngle ( 0.0 )
, type ( false )
{}
/// \ru Деструктор. \en Destructor.
virtual ~PocketValues();
public:
virtual MbeHoleType Type() const; // \ru Тип выемки. \en Type of notch.
virtual HoleValues & Duplicate( MbRegDuplicate * ireg = NULL ) const; // \ru Построить копию. \en Create a copy.
virtual void Transform( const MbMatrix3D & matr, MbRegTransform * ireg = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix.
virtual bool IsSame( const HoleValues &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal?
virtual void operator = ( const HoleValues & other ); // \ru Оператор присваивания. \en Assignment operator.
private:
// \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default.
void operator = ( const PocketValues & other );
public:
KNOWN_OBJECTS_RW_REF_OPERATORS( PocketValues ) // \ru Для работы со ссылками и объектами класса \en For treatment of references and objects of the class
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры паза.
\en The parameters of slot. \~
\details \ru Параметры фигурного паза. \n
Вид паза сверху представляет собой разрезанную пополам окружность,
половинки которой раздвинуты на длину паза, а края соединены отрезками.
\en The parameters of figure slot. \n
View of slot from above is cut in half to circle,
halves of which are spread apart by the length of slot and the edges are connected by segments. \~
\ingroup Build_Parameters
*/
// ---
class MATH_CLASS SlotValues : public HoleValues {
public:
// \ru Вид паза сверху. \en View of slot from above. \~
// --
// / \
// | |
// | |
// | |
// | |
// \ /
// --
enum SlotType {
// ________ *
// | | *
// +------+ *
// \ / *
// -- *
st_BallEnd = 0, ///< \ru Цилиндрический в донной части. \en Cylindrical in the bottom part.
// ________ *
// | | *
// | | *
// | | *
// +------+ *
st_Rectangular = 1, ///< \ru Прямоугольный. \en Rectangular.
// ________ *
// | | *
// +--+------+--+ *
// | | *
// +------------+ *
st_TShaped = 2, ///< \ru T-образный. \en T-shaped.
// ________ *
// / \ *
// / \ *
// / \ *
// +--------------+ *
st_DoveTail = 3, ///< \ru Ласточкин хвост. \en Dovetail
};
public:
double length; ///< \ru Длина паза. \en Slot length.
double width; ///< \ru Ширина паза. \en Slot width.
double depth; ///< \ru Глубина паза. \en Slot depth.
double bottomWidth; ///< \ru Ширина донной части T-образного паза, должна превосходить ширину width. \en Width of the bottom part of T-shaped slot must be greater than the width "width".
double bottomDepth; ///< \ru Глубина донной части ласточкиного хвоста. \en Depth of the bottom part of dovetail.
/** \brief \ru Радиус скругления дна паза.
\en Fillet radius of the slot bottom. \~
\details \ru Радиус скругления дна паза (2 * floorRadius <= width).
При width == 2 * floorRadius получим паз типа st_BallEnd.
floorRadius = 0 для пазов типа st_TShaped и st_DoveTail.
\en Fillet radius of slot bottom (2 * floorRadius <= width).
If width == 2 * floorRadius, then slot has type st_BallEnd.
floorRadius = 0 for slots with type st_TShaped and st_DoveTail. \~
*/
double floorRadius;
double tailAngle; ///< \ru Угол уклона стенок паза типа st_DoveTail (отклонение от вертикали в радианах). \en Draft angle of walls of slot with type st_DoveTail (vertical deviation in radians).
SlotType type; ///< \ru Тип паза. \en Type of slot.
private :
// \ru Объявление конструктора копирования без реализации, чтобы не было копирования по умолчанию. \en Declaration without implementation of the copy-constructor to prevent copying by default.
SlotValues( const SlotValues & other );
/// \ru Конструктор копирования. \en Copy-constructor.
SlotValues( const SlotValues & other, MbRegDuplicate * ireg );
public:
/** \brief \ru Конструктор по умолчанию.
\en Default constructor. \~
\details \ru Конструктор прямоугольного паза.
\en Constructor of rectangular slot. \~
*/
SlotValues()
: HoleValues ()
, length ( 10.0 )
, width ( 10.0 )
, depth ( 5.0 )
, bottomWidth( 15.0 )
, bottomDepth( 10.0 )
, floorRadius( 1.0 )
, tailAngle ( M_PI_4 )
, type ( st_Rectangular )
{}
/// \ru Деструктор. \en Destructor.
virtual ~SlotValues();
public:
virtual MbeHoleType Type() const; // \ru Тип выемки. \en Type of notch.
virtual HoleValues & Duplicate( MbRegDuplicate * ireg = NULL ) const; // \ru Построить копию. \en Create a copy.
virtual void Transform( const MbMatrix3D & matr, MbRegTransform * ireg = NULL ); // \ru Преобразовать элемент согласно матрице. \en Transform element according to the matrix.
virtual bool IsSame( const HoleValues &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal?
virtual void operator = ( const HoleValues & other ); // \ru Оператор присваивания. \en Assignment operator.
private:
// \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию. \en The declaration of the assignment operator without implementation to prevent an assignment by default.
void operator = ( const SlotValues & other );
public:
KNOWN_OBJECTS_RW_REF_OPERATORS( SlotValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class.
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры крепежа.
\en The parameters of fastener elements. \~
\details \ru Параметры крепежных элементов. \n
\en The parameters of fastener elements. \n \~
*/
// ---
class MATH_CLASS FastenersValues {
public:
//------------------------------------------------------------------------------
/** \brief \ru Типы крепежа.
\en Fastener Types. \~
*/
// ---
enum MbeFastenerType {
ft_CountersunkHeadRivet = 0, ///< \ru Заклепка с (полу)потайной головкой. \en (semi)Countersunk head rivet.
ft_UniversalHeadRivet, ///< \ru Заклепка с универсальной головкой. \en Universal head rivet.
ft_RoundHeadRivet, ///< \ru Заклепка с полукруглой головкой. \en Round head rivet.
ft_FlatHeadRivet ///< \ru Заклепка с плоской головкой. \en Flat head rivet.
};
private:
MbeFastenerType fastenerType; ///< \ru Тип крепежа. \en Fastener type.
double diameter; ///< \ru Диаметр крепежа. \en Fastener diameter.
double angle; ///< \ru Угол фаски. \en Countersunk angle.
double depth; ///< \ru Глубина фаски. \en Depth of chamfer.
double headDiameter; ///< \ru Диаметр основания головки. \en Diameter of the head base.
double headHeight; ///< \ru Высота головки. \en Head height.
ThreeStates rivetAndHole; ///< \ru ts_negative - создать только отверстия (без крепежа), ts_neutral - создать только крепёж (без отверстий), ts_positive - создать крепеж и отверстия.
///< \en ts_negative - create holes only (without rivets), ts_neutral - create rivets only (without holes), ts_positive - create rivets and holes. \~
public:
/** \brief \ru Конструктор крепежа по типу и диаметру.
\en Constructor of fastener based on type and diameter. \~
\details \ru Конструктор крепежа по типу и диаметру.
\en Constructor of fastener based on type and diameter. \~
\param[in] ft - \ru Тип крепежа.
\en Fastener type. \~
\param[in] d - \ru Диаметр крепежа.
\en Fastener diameter. \~
*/
FastenersValues( MbeFastenerType ft, double d )
: fastenerType ( ft )
, diameter ( d )
, angle ( M_PI_4 )
, depth ( d * c3d::ONE_HALF )
, headDiameter ( 2 * d )
, headHeight ( d )
, rivetAndHole ( ts_positive )
{}
/** \brief \ru Конструктор крепежа по типу, диаметру, углу, катету.
\en Constructor of fastener based on type, diameter, angle and side length. \~
\details \ru Конструктор крепежа по типу, диаметру, углу, катету.
\en Constructor of fastener based on type, diameter, angle and side length. \~
\param[in] ft - \ru Тип крепежа.
\en Fastener type. \~
\param[in] d - \ru Диаметр крепежа.
\en Fastener diameter. \~
\param[in] a - \ru Угол.
\en Angle. \~
\param[in] dd - \ru Глубина (фаски).
\en Depth. \~
\param[in] hd - \ru Диаметр основания головки.
\en Head base diameter \~
\param[in] hh - \ru Высота головки.
\en Head height. \~
\param[in] ho - \ru Создать только отверстие.
\en Create hole only. \~
*/
FastenersValues( MbeFastenerType ft, double d, double a, double dd, double hd, double hh, ThreeStates ho )
: fastenerType ( ft )
, diameter ( d )
, angle ( a )
, depth ( dd )
, headDiameter ( hd )
, headHeight ( hh )
, rivetAndHole ( ho )
{}
/// \ru Выдать тип крепежа. \en Return type of fastener.
MbeFastenerType GetType() const { return fastenerType; }
/// \ru Выдать значение диаметра. \en Return diameter value.
double GetDiameter() const { return diameter; }
/// \ru Установить значение диаметра. \en Set diameter value.
void SetDiameter( double d ) { diameter = d; }
/// \ru Выдать значение угла. \en Return angle value.
double GetAngle() const { return angle; }
/// \ru Установить значение угла. \en Set angle value.
void SetAngle( double a ) { angle = a; }
/// \ru Выдать значение глубины фаски. \en Return chamfer depth value.
double GetDepth() const { return depth; }
/// \ru Установить значение глубины фаски. \en Set chamfer depth value.
void SetDepth( double d ) { depth = d; }
/// \ru Выдать значение диаметра основания головки. \en Return chamfer depth value.
double GetHeadDiameter() const { return headDiameter; }
/// \ru Установить значение диаметра основания головки. \en Set chamfer depth value.
void SetHeadDiameter( double hd ) { headDiameter = hd; }
/// \ru Выдать значение высоты головки. \en Return head height value.
double GetHeadHeight() const { return headHeight; }
/// \ru Установить значение высоты головки. \en Set head height value.
void SetHeadHeight( double hh ) { headHeight = hh; }
/// \ru Только отверстие? \en Hole only?
ThreeStates RivetAndHole() const { return rivetAndHole; }
/// \ru Функция инициализации. \en Initialization function.
void Init( const FastenersValues & other ) {
fastenerType = other.fastenerType;
diameter = other.diameter;
angle = other.angle;
depth = other.depth;
headDiameter = other.headDiameter;
headHeight = other.headHeight;
rivetAndHole = other.rivetAndHole;
}
/// \ru Оператор присваивания. \en Assignment operator.
FastenersValues & operator = ( const FastenersValues & other ) {
Init( other );
return *this;
}
private:
/// \ru Конструктор по умолчанию - запрещен. \en Default constructor - forbidden.
FastenersValues()
{}
public:
KNOWN_OBJECTS_RW_REF_OPERATORS( FastenersValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class.
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры заплатки.
\en The parameters of patch. \~
\details \ru Параметры заплатки. \n
Содержат информацию о типе заплатки и флаге проверки самопересечений.
\en The parameters of patch. \n
Contain Information about type of patch and flag of checking self-intersection. \~
\ingroup Build_Parameters
*/
// ---
struct MATH_CLASS PatchValues {
public:
/** \brief \ru Тип заплатки.
\en Type of patch. \~
\details \ru Флаг можно установить через вызов PatchValues::SetType().
\en The flag can be set by calling PatchValues::SetType(). \~
*/
enum SurfaceType {
ts_tang, ///< \ru По касательной. \en Along the tangent.
ts_norm, ///< \ru По нормали. \en Along the normal.
ts_none, ///< \ru Не определено. \en Undefined.
ts_plane ///< \ru Плоская заплатка. \en Plane patch.
};
private:
SurfaceType type; ///< \ru Тип заплатки. \en Type of patch.
bool checkSelfInt; ///< \ru Флаг проверки самопересечений (вычислительно "тяжелыми" методами). \en Flag for checking of self-intersection (computationally by "heavy" methods).
public:
/** \brief \ru Конструктор по умолчанию.
\en Default constructor. \~
\details \ru Конструктор параметров заплатки не определенного типа без проверки самопересечений.
\en Constructor of parameters of patch with undefined type and without checking of self-intersection. \~
*/
PatchValues()
: type ( ts_none )
, checkSelfInt( false )
{}
/// \ru Конструктор копирования. \en Copy-constructor.
PatchValues( const PatchValues & other )
: type ( other.type )
, checkSelfInt( other.checkSelfInt )
{}
/// \ru Деструктор. \en Destructor.
~PatchValues()
{}
public:
/// \ru Выдать тип заплатки. \en Get type of patch.
SurfaceType GetType() const { return type; }
/// \ru Выдать тип заплатки для изменения. \en Get type of patch for changing.
SurfaceType & SetType() { return type; }
/// \ru Получить флаг проверки самопересечений. \en Get the flag of checking self-intersection.
bool CheckSelfInt() const { return checkSelfInt; }
/// \ru Установить флаг проверки самопересечений. \en Set the flag of checking self-intersection.
void SetCheckSelfInt( bool c ) { checkSelfInt = c; }
/// \ru Оператор присваивания. \en Assignment operator.
void operator = ( const PatchValues & other ) { type = other.type; checkSelfInt = other.checkSelfInt; }
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const PatchValues & obj, double ) const { return ((obj.type == type) && (obj.checkSelfInt == checkSelfInt)); }
KNOWN_OBJECTS_RW_REF_OPERATORS( PatchValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class.
};
//------------------------------------------------------------------------------
/** \brief \ru Кривая для построения заплатки.
\en Curve for the patch construction. \~
\details \ru Кривая для построения заплатки и параметры её окружения. \n
\en Curve for the patch construction and parameters of its environment. \n \~
\ingroup Build_Parameters
*/
// ---
class MATH_CLASS MbPatchCurve : public MbRefItem {
private:
MbCurve3D * curve; ///< \ru Кривая. \en A curve.
double begTolerance; ///< \ru Толерантность привязки в начале. \en Binding tolerance at the start.
double endTolerance; ///< \ru Толерантность привязки в начале. \en Binding tolerance at the start.
bool isSurfaceOne; ///< \ru В ребре есть грань с первой поверхностью из кривой пересечения. \en There is face with the first surface from the intersection curve in the edge.
bool isSurfaceTwo; ///< \ru В ребре есть грань со второй поверхностью из кривой пересечения. \en There is face with the second surface from the intersection curve in the edge.
mutable bool isUsed; ///< \ru Флаг использования. \en An using flag.
public:
/// \ru Конструктор по кривой (копирует кривую, трансформируя по матрице). \en Constructor by a curve (copies a curve, transforms by the matrix).
MbPatchCurve( const MbCurve3D & crv, const MbMatrix3D & mtr );
/// \ru Конструктор по ребру (копирует кривую, трансформируя по матрице). \en Constructor by an edge (copies a curve, transforms by the matrix).
MbPatchCurve( const MbCurveEdge & edge, const MbMatrix3D & mtr );
/// \ru Деструктор. \en Destructor.
virtual ~MbPatchCurve();
public:
/// \ru В ребре есть грань с первой поверхностью из кривой пересечения. \en There is face with the first surface from the intersection curve in the edge.
bool IsSurfOne() const { return isSurfaceOne; }
/// \ru В ребре есть грань со второй поверхностью из кривой пересечения. \en There is face with the second surface from the intersection curve in the edge.
bool IsSurfTwo() const { return isSurfaceTwo; }
/// \ru Толерантность привязки в начале. \en Binding tolerance at the start.
double GetBegTolerance() const { return begTolerance; }
/// \ru Толерантность привязки в начале. \en Binding tolerance at the start.
double GetEndTolerance() const { return endTolerance; }
/// \ru Получить кривую. \en Get a curve.
const MbCurve3D & GetCurve() const { return *curve; }
/// \ru Получить кривую для изменения. \en Get a curve for changing.
MbCurve3D & SetCurve() { return *curve; }
/// \ru Кривая используется? \en Is curve used?
bool IsUsed() const { return isUsed; }
/// \ru Установить флаг использования кривой. \en Set flag of using curve.
void SetUsed( bool b ) const { isUsed = b; }
OBVIOUS_PRIVATE_COPY( MbPatchCurve )
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры масштабирования объекта.
\en The parameters of object scaling. \~
\details \ru Масштабирование объекта выполняется преобразованием по матрице. \n
\en Object scaling is performed by the transformation matrix. \n \~
\ingroup Build_Parameters
*/
// ---
struct MATH_CLASS TransformValues {
protected:
MbMatrix3D matrix; ///< \ru Матрица преобразования . \en A transformation matrix.
// \ru Остальные параметры не обязательны (нужны для расчета matrix по деформации габаритного куба функцией MbCube::CalculateMatrix) \en Other parameters are optional (they are necessary for the calculation of matrix by deformation of bounding box by the function MbCube::CalculateMatrix)
MbCartPoint3D fixedPoint; ///< \ru Неподвижная точка преобразования (используется, если useFixed = true). \en A fixed point of transformation. (It is used if useFixed = true).
bool useFixed; ///< \ru Использовать неподвижную точку преобразования (если true). \en Use fixed point of transformation (if true).
bool isotropy; ///< \ru Использовать одинаковое масштабирование по осям (если true). \en Use the same axes scaling (if true).
public:
/// \ru Конструктор по умолчанию. \en Default constructor.
TransformValues()
: matrix()
, fixedPoint()
, useFixed( false )
, isotropy( false )
{}
/// \ru Конструктор по матрице. \en Constructor by matrix.
TransformValues( const MbMatrix3D & m )
: matrix( m )
, fixedPoint()
, useFixed( false )
, isotropy( false )
{}
/// \ru Конструктор по матрице и неподвижной точке преобразования. \en Constructor by matrix and fixed point of transformation.
TransformValues( const MbMatrix3D & m, const MbCartPoint3D & f, bool fix = false, bool iso = false )
: matrix( m )
, fixedPoint( f )
, useFixed( fix )
, isotropy( iso )
{}
/// \ru Конструктор по неподвижной точке преобразования и масштабам по осям. \en Constructor by fixed point of transformation and axes scale.
TransformValues( double sX, double sY, double sZ, const MbCartPoint3D & fP );
/// \ru Конструктор. \en Constructor.
TransformValues( const TransformValues & other )
: matrix ( other.matrix )
, fixedPoint ( other.fixedPoint )
, useFixed ( other.useFixed )
, isotropy ( other.isotropy )
{}
/// \ru Деструктор. \en Destructor.
~TransformValues() {}
public:
/// \ru Функция инициализации. \en Initialization function.
void Init( const TransformValues & other ) {
matrix = other.matrix;
fixedPoint = other.fixedPoint;
useFixed = other.useFixed;
isotropy = other.isotropy;
}
/// \ru Оператор присваивания. \en Assignment operator.
TransformValues & operator = ( const TransformValues & other ) {
matrix = other.matrix;
fixedPoint = other.fixedPoint;
useFixed = other.useFixed;
isotropy = other.isotropy;
return *this;
}
/// \ru Выдать матрицу преобразования для использования. \en Get a transformation matrix for use.
const MbMatrix3D & GetMatrix() const { return matrix; }
/// \ru Выдать неподвижную точку преобразования для использования. \en A fixed point of transformation for use.
const MbCartPoint3D & GetFixedPoint() const { return fixedPoint; }
/// \ru Использовать неподвижную точку преобразования?. \en Is fixed point use?
bool IsFixed() const { return useFixed; }
/// \ru Одинаковое масштабирование по осям? \en Is the isotropic scaling?
bool Isisotropy() const { return isotropy; }
/// \ru Выдать матрицу преобразования для редактирования. \en Get a transformation matrix for modify.
MbMatrix3D & SetMatrix() { return matrix; }
/// \ru Выдать неподвижную точку преобразования для редактирования. \en A fixed point of transformation for modify.
MbCartPoint3D & SetFixedPoint() { return fixedPoint; }
/// \ru Использовать неподвижную точку преобразования. \en Use fixed point of transformation.
void SetFixed( bool b ) { useFixed = b; }
/// \ru Использовать одинаковое масштабирование по осям. \en Use the same axes scaling.
void SetIsotropy( bool b ) { isotropy = b; }
/// \ru Используется ли неподвижная точка преобразования? \en Whether the fixed point of transformation is used?
bool IsUsingFixed() const { return useFixed; }
/// \ru Является ли преобразование изотропным? \en Whether the transformation is isotropic?
bool IsIsotropy() const { return isotropy; }
/// \ru Рассчитать неподвижную точку преобразования. \en Calculate a fixed point of transformation.
bool CalculateFixedPoint();
/// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix.
void Transform( const MbMatrix3D & matr );
/// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector.
void Move ( const MbVector3D & to );
/// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis.
void Rotate ( const MbAxis3D & axis, double ang );
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const TransformValues & other, double accuracy ) const;
KNOWN_OBJECTS_RW_REF_OPERATORS( TransformValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class.
};
//------------------------------------------------------------------------------
/** \brief \ru Типы модификации.
\en Type of modification. \~
\details \ru Тип определяет действия при прямом моделировании.
\en Type determines direct modeling actions. \~
\ingroup Build_Parameters
*/
enum MbeModifyingType {
dmt_Remove = 0, ///< \ru Удаление из тела выбранных граней с окружением. \en Removal of the specified faces with the neighborhood from a solid.
dmt_Create, ///< \ru Создание тела из выбранных граней с окружением. \en Creation of a solid from the specified faces with the neighborhood.
dmt_Action, ///< \ru Перемещение выбранных граней с окружением относительно оставшихся граней тела. \en Translation of the specified faces with neighborhood relative to the other faces of the solid.
dmt_Offset, ///< \ru Замена выбранных граней тела эквидистантными гранями (перемещение по нормали, изменение радиуса). \en Replacement of the specified faces of a solid with the offset faces (translation along the normal, change of the radius).
dmt_Fillet, ///< \ru Изменение радиусов выбранных граней скругления. \en Change of radii of the specified fillet faces.
dmt_Supple, ///< \ru Замена выбранных граней тела деформируемыми гранями (превращение в NURBS для редактирования). \en Replacement of the specified faces of a solid with a deformable faces (conversion to NURBS for editing).
dmt_Purify, ///< \ru Удаление из тела выбранных скруглений. \en Removal of the specified fillets from a solid.
dmt_Merger, ///< \ru Слияние вершин ребёр и удаление рёбер. \en Merging vertices of edges and edges removal.
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры прямого редактирования тела.
\en Parameter for direct editing of solid. \~
\details \ru Параметры прямого редактирования тела. \n
Параметры содержат информацию о типе модификации и векторе перемещения.
\en Parameter for direct editing of solid. \n
The parameters contain Information about modification type and movement vector. \~
\ingroup Build_Parameters
*/
// ---
struct MATH_CLASS ModifyValues {
public:
MbeModifyingType way; ///< \ru Тип модификации. \en Type of modification.
MbVector3D direction; ///< \ru Перемещение при модификации. \en Moving when modifying.
public:
/** \brief \ru Конструктор по умолчанию.
\en Default constructor. \~
\details \ru Конструктор параметров операции удаления из тела выбранных граней.
\en Constructor of operation parameters of removing the specified faces from the solid. \~
*/
ModifyValues()
: way( dmt_Remove )
, direction( 0.0, 0.0, 0.0 )
{}
/// \ru Конструктор по способу модификации и вектору перемещения. \en Constructor by way of modification and movement vector.
ModifyValues( MbeModifyingType w, const MbVector3D & p )
: way ( w )
, direction( p )
{}
/// \ru Конструктор копирования. \en Copy-constructor.
ModifyValues( const ModifyValues & other )
: way ( other.way )
, direction( other.direction )
{}
/// \ru Деструктор. \en Destructor.
~ModifyValues() {}
public:
/// \ru Функция копирования. \en Copy function.
void Init( const ModifyValues & other ) {
way = other.way;
direction = other.direction;
}
/// \ru Оператор присваивания. \en Assignment operator.
ModifyValues & operator = ( const ModifyValues & other ) {
way = other.way;
direction = other.direction;
return *this;
}
/// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix.
void Transform( const MbMatrix3D & matr );
/// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector.
void Move ( const MbVector3D & to );
/// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis.
void Rotate ( const MbAxis3D & axis, double ang );
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const ModifyValues & other, double accuracy ) const;
KNOWN_OBJECTS_RW_REF_OPERATORS( ModifyValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class.
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры деформируемой грани.
\en Parameters of the deformable face. \~
\details \ru Параметры деформируемой грани используются при замене поверхности выбранной грани тела
NURBS-поверхностью и при дальнейшем редактировании этой грани. \n
\en Parameters of the deformable face are used when replacing the surface of selected face of solid
by NURBS-surface and with further editing of this face. \n \~
\ingroup Build_Parameters
*/
// ---
struct MATH_CLASS NurbsValues {
public:
MbNurbsParameters uParameters; ///< \ru Параметры u-направления NURBS-поверхности. \en Parameters of u-direction of NURBS-surface.
MbNurbsParameters vParameters; ///< \ru Параметры v-направления NURBS-поверхности. \en Parameters of v-direction of NURBS-surface.
public:
/** \brief \ru Конструктор по умолчанию.
\en Default constructor. \~
\details \ru Конструктор параметров деформированной грани для замены
поверхности NURBS-поверхностью 4 порядка по всей области определения по направлениям u и v.
\en Constructor of parameters of deformed face for replacement
of surface by NURBS-surface of the fourth order in the entire domain along the u and v directions. \~
*/
NurbsValues()
: uParameters()
, vParameters()
{}
/** \brief \ru Конструктор по параметрам.
\en Constructor by parameters. \~
\details \ru Конструктор параметров деформированной грани.
\en Constructor of parameters of deformed face. \~
\param[in] ud, vd - \ru Порядок NURBS-копии по u и по v.
\en Order of NURBS-copy along u and v. \~
\param[in] uc, vc - \ru Количество контрольных точек по u и по v.
\en The count of control points along u and v. \~
\param[in] umin, umax, vmin, vmax - \ru Диапазоны параметров по u и v для деформирования грани.
\en Parameter ranges along u and v for deforming face. \~
\param[in] uapprox, vapprox - \ru Флаги возможного построения приближенной поверхности, а не точной.
\en Flags of the possible constructing of approximate surface, not exact. \~
*/
NurbsValues( size_t ud, size_t uc, double umin, double umax, bool uapprox,
size_t vd, size_t vc, double vmin, double vmax, bool vapprox )
: uParameters( ud, uc, umin, umax, uapprox )
, vParameters( vd, vc, vmin, vmax, vapprox )
{}
/// \ru Конструктор копирования. \en Copy-constructor.
NurbsValues( const NurbsValues & other )
: uParameters( other.uParameters )
, vParameters( other.vParameters )
{}
/// \ru Деструктор. \en Destructor.
~NurbsValues() {}
public:
/// \ru Функция копирования. \en Copy function.
void Init( const NurbsValues & other ) {
uParameters = other.uParameters;
vParameters = other.vParameters;
}
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const NurbsValues & other, double accuracy ) const;
/// \ru Оператор присваивания. \en Assignment operator.
NurbsValues & operator = ( const NurbsValues & other ) {
uParameters = other.uParameters;
vParameters = other.vParameters;
return *this;
}
KNOWN_OBJECTS_RW_REF_OPERATORS( NurbsValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class.
};
//--------------------------------------------------------------------
/** \brief \ru Параметры для построения NURBS-блока.
\en The parameters for construction of NURBS-block. \~
\details \ru Параметры для построения блока из NURBS-поверхностей. \n
\en The parameters for construction of block.from NURBS-surfaces. \n \~
\ingroup Build_Parameters
*/
// ---
struct MATH_CLASS NurbsBlockValues {
public:
// \ru Параметры для построения блока из nurbs-поверхностей. \en The parameters for construction of block.from nurbs-surfaces.
//
// \ru +Z (N) - номер грани *-----* \en +Z (N) - index of face *-----*
// | | |
// *--------* | (5) |
// /| /| | |
// / | / | *-----*-----*-----*-----*
// / | / | | | | | |
// *---+----* | | (2) | (3) | (4) | (1) |
// | | | | | | | | |
// | *----+---*-- +Y *-----*-----*-----*-----*
// | / | / | |
// | / | / | (0) |
// |/ |/ | |
// *--------* *-----*
// /
// \ru +X Развертка граней блока внешней стороной к наблюдателю. \en +X Unfolding the outer side of block faces to the viewer.
//
// \ru Принцип соответствия номеров и граней. \en Principle of correspondence of indices and faces.
// \ru Элементы матрицы структуры соответствуют параметрам поверхностей следующих граней блока: \en Matrix elements of the structure correspond to surfaces parameters the following blocks:
// \ru - элемент 0 - грани 0, 5 ( нижняя и верхняя грани ); \en - element 0 - faces 0, 5 ( lower and upper faces );
// \ru - элемент 1 - грани 1, 3 ( боковые грани ); \en - element 1 - faces 1, 3 ( lateral faces );
// \ru - элемент 2 - грани 2, 4 ( боковые грани ). \en - element 2 - faces 2, 4 ( lateral faces ).
ptrdiff_t udeg[3]; ///< \ru Порядок nurbs-сплайнов по первому параметру для трех пар поверхностей граней блока. \en Order of nurbs-splines along the first parameter for three pairs of block faces.
ptrdiff_t vdeg[3]; ///< \ru Порядок nurbs-сплайнов по второму параметру для трех пар поверхностей граней блока. \en Order of nurbs-splines along the second parameter for three pairs of block faces.
ptrdiff_t ucnt[3]; ///< \ru Количество контрольных точек вдоль первого параметра для трех пар поверхностей граней блока. \en The count of matrix elements of control points along the first and for three pairs of block faces.
ptrdiff_t vcnt[3]; ///< \ru Количество контрольных точек вдоль второго параметра для трех пар поверхностей граней блока. \en The count of matrix elements of control points along the second and for three pairs of block faces.
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры сплайновой поверхности.
\en The parameters of spline surface. \~
\details \ru Параметры определяют контрольные точки, веса, узлы сплайновой поверхности. \n
\en The parameters determines control points, weights, knots of spline surface. \n \~
\ingroup Build_Parameters
*/
// ---
struct MATH_CLASS NurbsSurfaceValues {
friend class MbNurbsSurfacesSolid;
private:
ptrdiff_t udegree; ///< \ru Порядок В-сплайна по U. \en Spline degree along U.
ptrdiff_t vdegree; ///< \ru Порядок В-сплайна по V. \en Spline degree along V.
bool uclosed; ///< \ru Признак замкнутости по U. \en Attribute of closedness along U.
bool vclosed; ///< \ru Признак замкнутости по V. \en Attribute of closedness along V.
Array2<MbCartPoint3D> points; ///< \ru Множество точек. \en Set of points.
double weight; ///< \ru Вес точек в случае одинаковости весов. \en Points weight in the case of equal weights.
Array2<double> * weights; ///< \ru Веса точек (может быть NULL). \en Weights of points (can be NULL).
bool throughPoints; ///< \ru Строить поверхность, проходящую через точки. \en Build surface passing through points.
bool pointsCloud; ///< \ru Облако точек (массив не упорядочен). \en Point cloud (disordered array).
MbPlane * cloudPlane; ///< \ru Опорная плоскость облака точек. \en Support plane of point cloud.
bool ownCloudPlane; ///< \ru Собственная опорная плоскость облака точек. \en Own support plane of point cloud.
bool checkSelfInt; ///< \ru Искать самопересечения. \en Find self-intersection.
mutable CSSArray<size_t> checkLnNumbers; ///< \ru Номера проверяемых строк. \en The indices of checked rows.
mutable CSSArray<size_t> checkCnNumbers; ///< \ru Номера проверяемых столбцов. \en The indices of checked columns.
mutable ptrdiff_t minCloudDegree; ///< \ru Минимально возможный порядок сплайнов по облаку точек. \en The smallest possible order of splines by point cloud.
mutable ptrdiff_t maxCloudDegree; ///< \ru Максимально возможный порядок сплайнов по облаку точек. \en The maximum possible order of splines by point cloud.
public:
/** \brief \ru Конструктор по умолчанию.
\en Default constructor. \~
\details \ru Конструктор параметров не замкнутой сплайновой поверхности
второго порядка по направлениям u и v.
\en Constructor of parameters of non-closed spline surface
of second order along the u and v directions. \~
*/
NurbsSurfaceValues();
/// \ru Конструктор копирования. \en Copy-constructor.
NurbsSurfaceValues( const NurbsSurfaceValues & );
/// \ru Деструктор. \en Destructor.
~NurbsSurfaceValues();
public:
/** \brief \ru Инициализация по сетке точек.
\en Initialization by grid of points. \~
\details \ru Инициализация параметров сплайновой поверхности по сетке точек.
\en Initialization of parameters of spline surface by grid of points. \~
\param[in] uDeg, vDeg - \ru Порядок по u и по v.
\en Order along u and v. \~
\param[in] uCls, vCls - \ru Признаки замкнутости поверхности по u и по v.
\en Attribute of surface closedness along u and v. \~
\param[in] pnts - \ru Набор точек.
\en A point set. \~
\param[in] checkSelfInt - \ru Признак проверки на самопересечение.
\en Attribute of check for self-intersection. \~
\return \ru false при некорректных параметрах.
\en False if incorrect parameters. \~
*/
bool InitMesh( ptrdiff_t uDeg, bool uCls,
ptrdiff_t vDeg, bool vCls,
const Array2<MbCartPoint3D> & pnts,
bool checkSelfInt );
/** \brief \ru Инициализация по сетке точек.
\en Initialization by grid of points. \~
\details \ru Инициализация параметров сплайновой поверхности по сетке точек.
\en Initialization of parameters of spline surface by grid of points. \~
\param[in] uDeg, vDeg - \ru Порядок по u и по v.
\en Order along u and v. \~
\param[in] uCls, vCls - \ru Признаки замкнутости поверхности по u и по v.
\en Attribute of surface closedness along u and v. \~
\param[in] pnts - \ru Набор точек.
\en A point set. \~
\param[in] wts - \ru Веса точек.
\en Weights of points. \~
\param[in] checkSelfInt - \ru Признак проверки на самопересечение.
\en Attribute of check for self-intersection. \~
\return \ru false при некорректных параметрах.
\en False if incorrect parameters. \~
*/
bool InitMesh( ptrdiff_t uDeg, bool uCls,
ptrdiff_t vDeg, bool vCls,
const Array2<MbCartPoint3D> & pnts,
const Array2<double> * wts, bool checkSelfInt );
/** \brief \ru Инициализация по облаку точек.
\en Initialization by point cloud. \~
\details \ru Инициализация по облаку точек (используется оригинал плоскости).\n
Если uvDeg < 0, то будет создаваться набор треугольных пластин \n
(триангуляцией проекций точек на cloudPlace)
\en Initialization by point cloud (used the original plane).\n
If uvDeg < 0, then set of triangular plates is created \n
(by triangulation of points projections on the cloudPlace) \~
\param[in] uvDeg - \ru Порядок по u и по v.
\en Order along u and v. \~
\param[in] pnts - \ru Множество точек.\n
Набор точек подходит для инициализации (является облаком точек)
в случае, если это одномерный массив точек,
не лежащих на одной прямой, без совпадений.
\en Set of points.\n
Set of points is suitable for initialization (is a point cloud)
if it is one-dimensional array of points
which don't lie on a straight line without coincidence. \~
\param[in] cloudPlace - \ru Опорная плоскость облака точек.
\en Support plane of point cloud. \~
\param[in] checkSelfInt - \ru Признак проверки на самопересечение.
\en Attribute of check for self-intersection. \~
\return \ru true при корректных параметрах.
\en True if correct parameters. \~
*/
bool InitCloud( ptrdiff_t uvDeg,
const Array2<MbCartPoint3D> & pnts,
const MbPlacement3D * cloudPlace,
bool checkSelfInt );
/// \ru Оператор копирования. \en Copy-operator.
void operator = ( const NurbsSurfaceValues & );
public:
/// \ru Первичная проверка корректности параметров. \en Initial check of parameters correctness
bool IsValid( bool checkPoints ) const;
/// \ru Получить порядок сплайнов по U. \en Get splines degree along U.
ptrdiff_t GetUDegree() const { return udegree; }
/// \ru Получить порядок сплайнов по V. \en Get splines degree along V.
ptrdiff_t GetVDegree() const { return vdegree; }
/// \ru Замкнутость по U. \en Closedness along U.
bool GetUClosed() const { return uclosed; }
/// \ru Замкнутость по V. \en Closedness along V.
bool GetVClosed() const { return vclosed; }
/// \ru Количество точек по U. \en A count of points along U.
size_t GetUCount() const { return points.Columns(); }
/// \ru Количество точек по V. \en A count of points along V.
size_t GetVCount() const { return points.Lines(); }
/// \ru Установить порядок сплайна по u. \en Set spline degree along u.
bool SetUDegree( size_t uDeg );
/// \ru Установить порядок сплайна по v. \en Set spline degree along v.
bool SetVDegree( size_t vDeg );
/// \ru Установить замкнутость по U. \en Set closedness along U.
void SetUClosed( bool uCls ) { uclosed = uCls; }
/// \ru Установить замкнутость по V. \en Set closedness along V.
void SetVClosed( bool vCls ) { vclosed = vCls; }
/// \ru Получить точку по позиции. \en Get point by position.
bool GetUVPoint ( size_t ui, size_t vi, MbCartPoint3D & ) const;
/// \ru Получить вес по позиции. \en Get weight by position.
bool GetUVWeight( size_t ui, size_t vi, double & ) const;
/// \ru Получить общий вес (вернет true, если вес у всех точек одинаковый). \en Get total weight (return true if all the weights are the same).
bool GetCommonWeight( double & ) const;
/// \ru Установить точки по позиции. \en Set points by position.
bool SetUVPoint ( size_t ui, size_t vi, const MbCartPoint3D & );
/// \ru Установить вес по позиции. \en Set weight by position.
bool SetUVWeight( size_t ui, size_t vi, const double & );
/// \ru Установить общий вес. \en Set total weight.
bool SetCommonWeight( double );
/// \ru Преобразовать данные согласно матрице. \en Transform data according to the matrix.
void Transform( const MbMatrix3D &, MbRegTransform * ireg );
/// \ru Сдвинуть данные вдоль вектора. \en Move data along a vector.
void Move ( const MbVector3D &, MbRegTransform * ireg );
/// \ru Повернуть данные вокруг оси на заданный угол. \en Rotate data at a given angle around an axis.
void Rotate ( const MbAxis3D &, double angle, MbRegTransform * ireg );
bool IsSame( const NurbsSurfaceValues &, double accuracy ) const; // \ru Являются ли объекты равными? \en Determine whether an object is equal?
/// \ru Установить размерность массивов точек и весов без сохранения или с сохранением имеющихся данных. \en Set the size of arrays of points and weights without saving or with saving of existing data.
bool SetSize( size_t ucnt, size_t vcnt, bool keepData = false );
/// \ru Установить флаг прохождения поверхности через точки. \en Set flag of surface passing through the points.
void SetThroughPoints( bool tp );
/// \ru Будет ли поверхность проходить через точки? \en Whether the surface passes through the points?
bool IsThroughPoints() const { return throughPoints; }
/// \ru Является ли массив облаком точек? \en Whether the array is point cloud?
bool IsPointsCloud() const { return pointsCloud; }
/// \ru Используется ли собственная плоскость проецирования (в случае массива по облаку точек)? \en Whether the own plane of projection is used (in the case of array by point cloud)?
bool IsOwnCloudPlane() const { return ownCloudPlane; }
/// \ru Нужно ли проверять самопересечения? \en Whether it is necessary to check self-intersections?
bool CheckSelfInt() const { return checkSelfInt; }
/// \ru Получить массив номеров проверяемых строк. \en Get the array of indices of checked rows.
void GetCheckLines( CSSArray<size_t> & checkNumbers ) const { checkNumbers = checkLnNumbers; }
/// \ru Получить массив номеров проверяемых столбцов. \en Get the array of indices of checked columns.
void GetCheckCols ( CSSArray<size_t> & checkNumbers ) const { checkNumbers = checkCnNumbers; }
/// \ru Получить количество строк. \en Get the count of rows.
size_t GetPointsLines () const { return points.Lines(); } //-V524
/// \ru Получить количество столбцов. \en Get the count of columns.
size_t GetPointsColumns() const { return points.Columns(); } //-V524
/// \ru Получить массив точек. \en Get array of points.
bool GetPoints ( Array2<MbCartPoint3D> & pnts ) const { return pnts.Init( points ); }
/// \ru Если ли веса? \en Is there weights?
bool IsWeighted() const { return (weights != NULL); }
/// \ru Получить массив весов. \en Get array of weights.
bool GetWeights( Array2<double> & wts ) const;
/// \ru Получить плоскость проецирования. \en Get the plane of projection.
const MbPlane * GetCloudPlane() const { return (pointsCloud ? cloudPlane : NULL);}
/** \brief \ru Минимально возможный порядок сплайнов в случае облака точек.
\en The smallest possible order of splines in the case of point cloud. \~
\details \ru Минимально возможный порядок сплайнов в случае облака точек.\n
Запрашивать после успешного создания поверхности, иначе вернет отрицательное значение.
\en The smallest possible order of splines in the case of point cloud.\n
Request after the successful creation of the surface otherwise returns a negative value. \~
*/
ptrdiff_t GetMinCloudDegree() const { return minCloudDegree; }
/** \brief \ru Максимально возможный порядок сплайнов в случае облака точек.
\en The maximum possible order of splines in the case of point cloud. \~
\details \ru Максимально возможный порядок сплайнов в случае облака точек.\n
Запрашивать после успешного создания поверхности, иначе вернет отрицательное значение.
\en The maximum possible order of splines in the case of point cloud.\n
Request after the successful creation of the surface otherwise returns a negative value. \~
*/
ptrdiff_t GetMaxCloudDegree() const { return maxCloudDegree; }
/// \ru Выставить максимально возможный порядок по обработанному (регуляризованному) облаку точек. \en Set the maximum possible order by processed (regularized) point cloud.
bool SetCloudDegreeRange( const NurbsSurfaceValues & meshParam ) const;
private:
void DeleteWeights();
bool CreateWeights( double wt );
void SetCloudPlane( MbPlane * );
bool CreateOwnCloudPlane();
public:
KNOWN_OBJECTS_RW_REF_OPERATORS_EX( NurbsSurfaceValues, MATH_FUNC_EX )
};
//------------------------------------------------------------------------------
// \ru Получить веса \en Get weights
// ---
inline bool NurbsSurfaceValues::GetWeights( Array2<double> & wts ) const
{
if ( weights != NULL ) {
if ( wts.Init( *weights ) )
return true;
}
return false;
}
//------------------------------------------------------------------------------
// \ru Установить порядок сплайна по u \en Set spline degree along u
// ---
inline bool NurbsSurfaceValues::SetUDegree( size_t uDeg )
{
if ( uDeg > 1 ) {
udegree = uDeg;
return true;
}
return false;
}
//------------------------------------------------------------------------------
// \ru Установить порядок сплайна по v \en Set spline degree along v
// ---
inline bool NurbsSurfaceValues::SetVDegree( size_t vDeg )
{
if ( vDeg > 1 ) {
vdegree = vDeg;
return true;
}
return false;
}
//------------------------------------------------------------------------------
// \ru Получить точку \en Get a point
// ---
inline bool NurbsSurfaceValues::GetUVPoint( size_t ui, size_t vi, MbCartPoint3D & pnt ) const
{
if ( ui < GetUCount() && vi < GetVCount() ) {
pnt = points( vi, ui );
return true;
}
return false;
}
//------------------------------------------------------------------------------
// \ru Установить точку \en Set a point
// ---
inline bool NurbsSurfaceValues::SetUVPoint( size_t ui, size_t vi, const MbCartPoint3D & pnt )
{
bool bRes = false;
if ( ui < GetUCount() && vi < GetVCount() ) {
MbCartPoint3D bakPoint( points( vi, ui ) );
points( vi, ui ) = pnt;
if ( pointsCloud && ownCloudPlane ) {
if ( CreateOwnCloudPlane() )
bRes = true;
else
points( vi, ui ) = bakPoint;
}
}
return bRes;
}
//------------------------------------------------------------------------------
// \ru Получить вес \en Get a weight
// ---
inline bool NurbsSurfaceValues::GetUVWeight( size_t ui, size_t vi, double & wt ) const
{
if ( weights != NULL && ui < GetUCount() && vi < GetVCount() ) {
wt = (*weights)( vi, ui );
return (wt != UNDEFINED_DBL); //-V550
}
wt = weight;
return (wt != UNDEFINED_DBL); //-V550
}
//------------------------------------------------------------------------------
// \ru Получить общий вес, вернет true, если вес у вес одинаковый \en Get total weight, return true if all the weights are the same
// ---
inline bool NurbsSurfaceValues::GetCommonWeight( double & wt ) const
{
if ( weights == NULL && weight != UNDEFINED_DBL ) { //-V550
wt = weight;
return true;
}
return false;
}
//------------------------------------------------------------------------------
// \ru Установить флаг прохождения поверхности через точки \en Set flag of surface passing through the points
// ---
inline void NurbsSurfaceValues::SetThroughPoints( bool tp )
{
throughPoints = tp;
if ( throughPoints ) {
DeleteWeights();
weight = 1.0;
}
if ( weights == NULL && weight == UNDEFINED_DBL ) //-V550
weight = 1.0;
}
//-----------------------------------------------------------------------------
/** \brief \ru Параметры поверхности по сетке кривых.
\en Surface parameter by grid of curves. \~
\details \ru Параметры содержат необходимые данные для построения поверхности по сетке кривых. \n
\en The parameters contain the necessary data to construct a surface by grid of curves. \n \~
\ingroup Build_Parameters
*/
//---
struct MATH_CLASS MeshSurfaceValues {
friend class MbMeshShell;
private:
RPArray<MbCurve3D> curvesU; ///< \ru Набор кривых по первому направлению. \en Set of curves along the first direction.
RPArray<MbCurve3D> curvesV; ///< \ru Набор кривых по второму направлению. \en Set of curves along the second direction.
RPArray<MbPolyline3D> chainsU; ///< \ru Набор цепочек по первому направлению. \en Set of chains along the first direction.
RPArray<MbPolyline3D> chainsV; ///< \ru Набор цепочек по второму направлению. \en Set of chains along the second direction.
bool uClosed; ///< \ru Замкнутость по U направлению. \en Closedness along U direction.
bool vClosed; ///< \ru Замкнутость по V направлению. \en Closedness along V direction.
bool checkSelfInt;///< \ru Искать самопересечения. \en Find self-intersections.
// \ru Сопряжения на границе (если сопряжения заданы, то кривые должны быть SurfaceCurve или контур из SurfaceCurve). \en Mates on the boundary (if mates are given, then curves must be SurfaceCurve or contour from SurfaceCurve).
MbeMatingType type0; ///< \ru Сопряжение на границе 0. \en Mate on the boundary 0.
MbeMatingType type1; ///< \ru Сопряжение на границе 1. \en Mate on the boundary 1.
MbeMatingType type2; ///< \ru Сопряжение на границе 2. \en Mate on the boundary 2.
MbeMatingType type3; ///< \ru Сопряжение на границе 3. \en Mate on the boundary 3.
MbSurface * surface0; ///< \ru Сопрягаемая поверхность через границу 0 (curvesU[0]). \en Mating surface through the boundary 0 (curvesU[0]).
MbSurface * surface1; ///< \ru Сопрягаемая поверхность через границу 1 (curvesV[0]). \en Mating surface through the boundary 1 (curvesV[0]).
MbSurface * surface2; ///< \ru Сопрягаемая поверхность через границу 2 (curvesU[maxU]). \en Mating surface through the boundary 2 (curvesU[maxU]).
MbSurface * surface3; ///< \ru Сопрягаемая поверхность через границу 3 (curvesV[maxV]). \en Mating surface through the boundary 3 (curvesV[maxV]).
MbPoint3D * point; ///< \ru Точка на поверхности. Используется для уточнения. \en Point on the surface. Used for specializing.
bool defaultDir0; ///< \ru Направление сопряжения на границе 0 по умолчанию. \en Default mate direction through the boundary 0.
bool defaultDir1; ///< \ru Направление сопряжения на границе 1 по умолчанию. \en Default mate direction through the boundary 1.
bool defaultDir2; ///< \ru Направление сопряжения на границе 2 по умолчанию. \en Default mate direction through the boundary 2.
bool defaultDir3; ///< \ru Направление сопряжения на границе 3 по умолчанию. \en Default mate direction through the boundary 3.
mutable uint8 directOrderV;///< \ru По второму семейству кривых порядок кривых совпадает. \en Order of the curves coincides by the second set of curves.
private:
/// \ru Конструктор копирования. \en Copy-constructor.
MeshSurfaceValues( const MeshSurfaceValues &, MbRegDuplicate * ireg );
public:
/// \ru Конструктор по умолчанию. \en Default constructor.
MeshSurfaceValues();
/// \ru Деструктор. \en Destructor.
~MeshSurfaceValues();
public:
/** \brief \ru Функция инициализации.
\en Initialization function. \~
\details \ru Функция инициализации на оригиналах кривых и копиях поверхностей.
\en Initialization function on the original curves and copies of surfaces. \~
\param[in] curvesU, curvesV - \ru Наборы кривых по первому и второму направлению.
\en Sets of curves along the first and second directions. \~
\param[in] chainsU, chainsV - \ru Наборы цепочек по первому и второму направлению.
\en Sets of chains along the first and second directions. \~
\param[in] uClosed, vClosed - \ru Признак замкнутости по направлениям u и v.
\en Closedness attribute along the u and v directions. \~
\param[in] checkSelfInt - \ru Флаг проверки на самопересечение.
\en Flag of check for self-intersection. \~
\param[in] type0, type1, type2, type3 - \ru Типы сопряжений на границах.
\en Mates types on the boundaries. \~
\param[in] surfaces0, surfaces1, surfaces2, surfaces3 - \ru Соответствующие сопрягаемые поверхности.
\en Corresponding mating surfaces. \~
\param[in] modify - \ru Флаг модификации кривых по сопряжениям.
\en Flag of curves modification by mates. \~
*/
bool Init( const RPArray<MbCurve3D> & curvesU, bool uClosed,
const RPArray<MbCurve3D> & curvesV, bool vClosed,
bool checkSelfInt,
const RPArray<MbPolyline3D> * chainsU = NULL,
const RPArray<MbPolyline3D> * chainsV = NULL,
MbeMatingType type0 = trt_Position, MbeMatingType type1 = trt_Position,
MbeMatingType type2 = trt_Position, MbeMatingType type3 = trt_Position,
const MbSurface * surf_0 = NULL, // \ru Сопрягаемые поверхности через curvesU[0] \en Mating surfaces through curvesU[0]
const MbSurface * surf_1 = NULL, // \ru Сопрягаемые поверхности через curvesV[0] \en Mating surfaces through curvesV[0]
const MbSurface * surf_2 = NULL, // \ru Сопрягаемые поверхности через curvesU[maxU] \en Mating surfaces through curvesU[maxU]
const MbSurface * surf_3 = NULL, // \ru Сопрягаемые поверхности через curvesV[maxV] \en Mating surfaces through curvesV[maxV]
const MbPoint3D * pnt = NULL,
bool modify = true,
bool direct0 = true, bool direct1 = true, bool direct2 = true, bool direct3 = true );
/** \brief \ru Функция инициализации.
\en Initialization function. \~
\details \ru Функция инициализации на оригиналах или копиях кривых и поверхностей.
\en Initialization function on the originals or copies of curves and surfaces. \~
\param[in] pars - \ru Исходные параметры.
\en Initial parameters. \~
\param[in] sameItems - \ru Флаг использования оригиналов кривых и поверхностей.
\en Flag of using originals of curves and surfaces. \~
*/
void Init( const MeshSurfaceValues & pars, bool sameItems );
/** \brief \ru Лежит ли кривая на поверхности.
\en Determine whether the curve lies on the surface. \~
\details \ru Лежит ли кривая полностью на поверхности.
\en Determine whether the curve entirely lies on the surface. \~
\param[in] curve - \ru Проверяемая кривая.
\en Checking curve. \~
\param[in] surf - \ru Проверяемая поверхность.
\en Checking surface. \~
*/
bool IsCurveOnSurface( const MbCurve3D & curve, const MbSurface & surf ) const;
/** \brief \ru Сопрягаются ли кривые с поверхностью точках пересечения с otherCurve.
\en Whether the curves are mated with surface in the points of intersection with otherCurve. \~
\details \ru Сопрягаются ли кривые (касательно, по нормали, гладко) с поверхностью в точках пересечения с otherCurve.
\en Whether the curves are mated (tangentially, along the normal, smoothly) with surface in the points of intersection with otherCurve. \~
\param[in] curves - \ru Набор проверяемых кривых.
\en Set of checking curves. \~
\param[in] surf - \ru Поверхность.
\en The surface. \~
\param[in] otherCurve - \ru Кривая на этой поверхности.
\en Curve on this surface. \~
\param[out] isTangent - \ru Признак касательного сопряжения.
\en Attribute of the tangent mate. \~
\param[out] isNormal - \ru Признак сопряжения по нормали.
\en Attribute of normal mate. \~
\param[out] isSmooth - \ru Признак гладкого сопряжения.
\en Attribute of the smooth mate. \~
*/
void AreCurvesMatingToSurface( const RPArray<MbCurve3D> & curves,
const MbSurface & surf,
const MbCurve3D * otherCurve,
bool & isTangent,
bool & isNormal,
bool & isSmooth ) const;
/// \ru Получить точки скрещивания-пересечения кривой с семейством кривых. \en Get crossing-intersection points of curves with the set of curves.
bool GetPointsOfCrossing( const MbCurve3D & curve, const RPArray<MbCurve3D> & otherCurves,
SArray<MbCartPoint3D> & res ) const;
/// \ru Проверка на наличие контуров и ломаных. \en Check for contours and broken lines.
bool CheckMultiSegment( const MbSNameMaker & snMaker ) const;
/// \ru Обратить порядок следования кривых по второму направлению, чтобы directOrderV был true. \en Invert order of curves along the second direction to directOrderV is true.
void InvertCurvesV ();
/// \ru Получить кривую на границе с номером i. \en Get i-th curve on the boundary.
const MbCurve3D * GetBorderCurve( ptrdiff_t i ) const;
/// \ru Получить тип сопряжения на границе с номером i. \en Get i-th mate type on the boundary.
MbeMatingType GetTransitType( ptrdiff_t i ) const;
/// \ru Получить поверхность сопряжения на границе с номером i. \en Get i-th mate surface on the boundary.
const MbSurface * GetSurface( size_t i ) const;
/// \ru Получить поверхность сопряжения на границе с номером i. \en Get i-th mate surface on the boundary.
MbSurface * SetSurface( size_t i );
/// \ru Получить направление сопряжения на границе с номером i. \en Get i-th mate direction on the boundary.
bool IsDefaultDirection( size_t i ) const;
/// \ru Замкнутость по U направлению. \en Closedness along U direction.
bool GetUClosed() const { return uClosed; }
/// \ru Замкнутость по V направлению. \en Closedness along V direction.
bool GetVClosed() const { return vClosed; }
/// \ru Замкнутость по U направлению. \en Closedness along U direction.
void SetUClosed( bool cls ) { uClosed = cls; }
/// \ru Замкнутость по V направлению. \en Closedness along V direction.
void SetVClosed( bool cls ) { vClosed = cls; }
/// \ru Количество кривых по U. \en The count of curves along U.
size_t GetCurvesUCount() const { return curvesU.Count(); }
/// \ru Максимальный индекс в массиве кривых по U. \en The maximum index in the array of curves along U.
ptrdiff_t GetCurvesUMaxIndex() const { return curvesU.MaxIndex(); }
/// \ru Получить кривую по индексу. \en Get the curve by the index.
const MbCurve3D * GetCurveU( size_t k ) const { return ((k < curvesU.Count()) ? curvesU[k] : NULL); }
/// \ru Получить кривую по индексу. \en Get the curve by the index.
MbCurve3D * SetCurveU( size_t k ) { return ((k < curvesU.Count()) ? curvesU[k] : NULL); }
/// \ru Получить кривые по U. \en Get curves along U.
void GetCurvesU( RPArray<MbCurve3D> & curves ) const { curves.AddArray(curvesU); }
/// \ru Установить кривые по U. \en Set curves along U.
void SetCurvesU( const RPArray<MbCurve3D> & newCurves );
/// \ru Отцепить кривые по U. \en Detach curves along U.
void DetachCurvesU( RPArray<MbCurve3D> & curves );
/// \ru Найти кривую. \en Find curve.
size_t FindCurveU( const MbCurve3D * curve ) const { return curvesU.FindIt( curve ); }
/// \ru Количество кривых по V. \en The count of curves along V.
size_t GetCurvesVCount() const { return curvesV.Count(); }
/// \ru Максимальный индекс в массиве кривых по V. \en The maximum index in the array of curves along V.
ptrdiff_t GetCurvesVMaxIndex() const { return curvesV.MaxIndex(); }
/// \ru Получить кривую по индексу. \en Get the curve by the index.
const MbCurve3D * GetCurveV( size_t k ) const { return ((k < curvesV.Count()) ? curvesV[k] : NULL); }
/// \ru Получить кривую по индексу. \en Get the curve by the index.
MbCurve3D * SetCurveV( size_t k ) const { return ((k < curvesV.Count()) ? curvesV[k] : NULL); }
/// \ru Получить кривые по V. \en Get curves along V.
void GetCurvesV( RPArray<MbCurve3D> & curves ) const { curves.AddArray(curvesV); }
/// \ru Установить кривые по V. \en Set curves along V.
void SetCurvesV( const RPArray<MbCurve3D> & newCurves );
/// \ru Отцепить кривые по V. \en Detach curves along V.
void DetachCurvesV( RPArray<MbCurve3D> & curves );
/// \ru Найти кривую. \en Find curve.
size_t FindCurveV( const MbCurve3D * curve ) const { return curvesV.FindIt( curve ); }
/// \ru Количество цепочек по U. \en The count of chains along U.
size_t GetChainsUCount() const { return chainsU.Count(); }
/// \ru Максимальный индекс в массиве цепочек по U. \en The maximum index in the array of chains along U.
ptrdiff_t GetChainsUMaxIndex() const { return chainsU.MaxIndex(); }
/// \ru Получить цепочку по индексу. \en Get the chain by the index.
const MbPolyline3D * GetChainU( size_t k ) const { return ( ( k < chainsU.Count() ) ? chainsU[k] : NULL ); }
/// \ru Получить цепочку по индексу. \en Get the chain by the index.
MbPolyline3D * SetChainU( size_t k ) { return ( ( k < chainsU.Count() ) ? chainsU[k] : NULL ); }
/// \ru Получить цепочки по U. \en Get chains along U.
void GetChainsU( RPArray<MbPolyline3D> & chains ) const { chains.AddArray( chainsU ); }
/// \ru Установить цепочки по U. \en Set chains along U.
void SetChainsU( const RPArray<MbPolyline3D> & newChains );
/// \ru Отцепить цепочки по U. \en Detach chains along U.
void DetachChainsU( RPArray<MbPolyline3D> & chains );
/// \ru Найти цепочку. \en Find chain.
size_t FindChainU( const MbPolyline3D * curve ) const { return chainsU.FindIt( curve ); }
/// \ru Количество цепочек по V. \en The count of chains along V.
size_t GetChainsVCount() const { return chainsV.Count(); }
/// \ru Максимальный индекс в массиве цепочек по V. \en The maximum index in the array of chains along V.
ptrdiff_t GetChainsVMaxIndex() const { return chainsV.MaxIndex(); }
/// \ru Получить цепочку по индексу. \en Get the chain by the index.
const MbPolyline3D * GetChainV( size_t k ) const { return ( ( k < chainsV.Count() ) ? chainsV[k] : NULL ); }
/// \ru Получить цепочку по индексу. \en Get the chain by the index.
MbPolyline3D * SetChainV( size_t k ) { return ( ( k < chainsV.Count() ) ? chainsV[k] : NULL ); }
/// \ru Получить цепочки по V. \en Get chains along V.
void GetChainsV( RPArray<MbPolyline3D> & chains ) const { chains.AddArray( chainsV ); }
/// \ru Установить цепочки по V. \en Set chains along V.
void SetChainsV( const RPArray<MbPolyline3D> & newChains );
/// \ru Отцепить цепочки по V. \en Detach chains along V.
void DetachChainsV( RPArray<MbPolyline3D> & chains );
/// \ru Найти цепочку. \en Find chain.
size_t FindChainV( const MbPolyline3D * curve ) const { return chainsV.FindIt( curve ); }
/// \ru Установить точку. \en Set point.
void SetPoint( const MbPoint3D * pnt );
/// \ru Получить точку. \en Get point.
const MbPoint3D * GetPoint() const { return point; }
/// \ru Получить точку. \en Get point.
MbPoint3D * SetPoint() { return point; }
/**
\ru \name Вспомогательные функции геометрических преобразований.
\en \name Auxiliary functions of geometric transformations.
\{ */
/// \ru Преобразовать кривые согласно матрице. \en Transform curves according to the matrix.
void Transform( const MbMatrix3D &, MbRegTransform * ireg );
/// \ru Сдвинуть кривые вдоль вектора. \en Move curves along a vector.
void Move ( const MbVector3D &, MbRegTransform * ireg );
/// \ru Повернуть кривые вокруг оси на заданный угол. \en Rotate curves at a given angle around an axis.
void Rotate ( const MbAxis3D &, double angle, MbRegTransform * ireg );
/// \ru Привести кривые к поверхностной форме (кривые на поверхности) \en Convert curves to the surface form (curves on the surface)
bool TransformCurves();
/** \} */
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const MeshSurfaceValues &, double accuracy ) const;
/// \ru Набор граничных поверхность пуст? \en Whether the set of boundary surfaces is empty?
bool AreSurfacesEmpty() const { return (surface0 == NULL && surface1 == NULL && surface2 == NULL && surface3 == NULL); }
/// \ru Нужно ли проверять самопересечения? \en Whether it is necessary to check self-intersections?
bool CheckSelfInt() const { return checkSelfInt; }
private:
void AddRefCurves(); // \ru Увеличить счетчик ссылок у кривых. \en Increase the reference count of curves.
void AddRefPoint(); // \ru Увеличить счетчик ссылок у точки. \en Increase the reference count of point.
void AddRefSurfaces(); // \ru Увеличить счетчик ссылок у поверхностей. \en Increase the reference count of surfaces.
void ReleaseCurves(); // \ru Удалить кривые. \en Release curves.
void ReleasePoint(); // \ru Удалить точку. \en Release point.
void ReleaseSurfaces(); // \ru Удалить поверхности. \en Release surfaces.
// \ru Определить порядок следования кривых по второму направлению. \en Determine the order of curves along the second direction.
void CalculateOrderV() const;
// \ru Привести кривую к типу поверхностной кривой или к контура из SurfaceCurve. \en Convert the curve to type of surface curve or contour from SurfaceCurve.
bool TransformToSurfaceCurve( const MbCurve3D & initCurve,
const MbSurface & surface,
const RPArray<MbCurve3D> & constrCurves,
MbSurfaceCurve *& resCurve ) const;
public:
KNOWN_OBJECTS_RW_REF_OPERATORS_EX( MeshSurfaceValues, MATH_FUNC_EX )
OBVIOUS_PRIVATE_COPY( MeshSurfaceValues )
};
//------------------------------------------------------------------------------
// \ru Получить тип сопряжения на границе с номером i \en Get i-th mate type on the boundary
//---
inline
MbeMatingType MeshSurfaceValues::GetTransitType( ptrdiff_t i ) const
{
MbeMatingType res = trt_Position;
switch ( i ) {
case 0: res = type0; break;
case 1: res = type1; break;
case 2: res = type2; break;
case 3: res = type3; break;
}
return res;
}
//------------------------------------------------------------------------------
/** \brief \ru Данные для построения линейчатой поверхности.
\en Data for the construction of a ruled surface. \~
\details \ru Данные для построения линейчатой поверхности по двум кривым. \n
\en Data for the construction of a ruled surface by two curves. \n \~
\ingroup Build_Parameters
*/
//---
struct MATH_CLASS RuledSurfaceValues {
friend class MbRuledShell;
private:
MbCurve3D * curve0; ///< \ru Первая кривая \en The first curve.
MbCurve3D * curve1; ///< \ru Вторая кривая. \en The second curve.
SArray<double> breaks0; ///< \ru Параметры разбиения первой кривой curve0. \en Splitting parameters of the first curve0 curve.
SArray<double> breaks1; ///< \ru Параметры разбиения второй кривой curve1. \en Splitting parameters of the second curve1 curve.
bool joinByVertices; ///< \ru Соединять контура с одинаковым количеством сегментов через вершины. \en Join contour with the same count of segments through vertices.
bool checkSelfInt; ///< \ru Искать самопересечения. \en Find self-intersections.
bool simplifyFaces; ///< \ru Упрощать грани. \en SimplifyFaces.
private:
/// \ru Конструктор копирования. \en Copy-constructor.
RuledSurfaceValues( const RuledSurfaceValues &, MbRegDuplicate * ireg );
public:
/// \ru Конструктор по умолчанию. \en Default constructor.
RuledSurfaceValues();
/// \ru Деструктор. \en Destructor.
~RuledSurfaceValues();
public:
/** \brief \ru Функция инициализации.
\en Initialization function. \~
\details \ru Функция инициализации на оригиналах кривых.
Контейнеры параметров разбиения кривых будут очищены.
\en Initialization function on the curves originals.
Containers of parameters of splitting curves will be cleared. \~
\param[in] inCurve0 - \ru Кривая для замены первой кривой.
\en The curve for the replacement of the first curve. \~
\param[in] inCurve1 - \ru Кривая для замены второй кривой.
\en The curve for the replacement of the second curve. \~
\param[in] selfInt - \ru Флаг проверки самопересечений.
\en Flag of self-intersections checking. \~
\return \ru Результат первичной проверки параметров.
\en The result of the primary scan of parameters. \~
*/
bool Init( const MbCurve3D & inCurve0,
const MbCurve3D & inCurve1,
bool selfInt = false );
/** \brief \ru Функция инициализации.
\en Initialization function. \~
\details \ru Функция инициализации на оригиналах кривых.
\en Initialization function on the curves originals. \~
\param[in] inCurve0 - \ru Кривая для замены первой кривой.
\en The curve for the replacement of the first curve. \~
\param[in] inCurve1 - \ru Кривая для замены второй кривой.
\en The curve for the replacement of the second curve. \~
\param[in] pars0 - \ru Параметры разбиения кривой inCurve0.
\en The parameters of splitting curve inCurve0. \~
\param[in] pars1 - \ru Параметры разбиения кривой inCurve1.
\en The parameters of splitting curve inCurve1. \~
\param[in] selfInt - \ru Флаг проверки самопересечений.
\en Flag of self-intersections checking. \~
\return \ru Результат первичной проверки параметров.
\en The result of the primary scan of parameters. \~
*/
bool Init( const MbCurve3D & inCurve0,
const MbCurve3D & inCurve1,
const SArray<double> & pars0,
const SArray<double> & pars1,
bool selfInt = false );
/** \brief \ru Функция инициализации.
\en Initialization function. \~
\details \ru Функция инициализации на оригиналах или копиях кривых.
\en Initialization function on the curves originals or copies of curve. \~
\param[in] obj - \ru Копируемые параметры.
\en Copy parameters. \~
\param[in] sameCurves - \ru Флаг использования оригиналов кривых.
\en Flag of using originals of curves. \~
*/
void Init( const RuledSurfaceValues & obj, bool sameCurves );
/// \ru Первичная проверка корректности параметров. \en Initial check of parameters correctness
bool IsValid() const;
/// \ru Преобразовать по матрице. \en Transform by matrix.
void Transform( const MbMatrix3D &, MbRegTransform * ireg );
/// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector.
void Move ( const MbVector3D &, MbRegTransform * ireg );
/// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis.
void Rotate ( const MbAxis3D &, double angle, MbRegTransform * ireg );
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const RuledSurfaceValues &, double accuracy ) const;
/// \ru Получить кривую (первую или вторую). \en Get curve (the first or second).
const MbCurve3D * GetCurve( bool first ) const { return (first ? curve0 : curve1); }
/// \ru Получить кривую (первую или вторую). \en Get curve (the first or second).
MbCurve3D * SetCurve( bool first ) { return (first ? curve0 : curve1); }
/// \ru Выдать количество параметров разбиения. \en Get the count of splitting parameters.
size_t GetParamsCount( bool first ) const { return (first ? breaks0.Count() : breaks1.Count()); }
/// \ru Выдать массив разбиения. \en Get splitting array.
void GetParams( bool first, SArray<double> & breaks ) const { breaks = (first ? breaks0 : breaks1); }
/// \ru Получить параметр разбиения по индексу. \en Get splitting parameter by index.
double GetParam( bool first, size_t k ) const { C3D_ASSERT( k < GetParamsCount( first ) ); return (first ? breaks0[k] : breaks1[k]); }
/// \ru Установить массив параметров разбиения. \en Set array of splitting parameters.
void SetParams( bool first, const SArray<double> & ps ) { if ( first ) breaks0 = ps; else breaks1 = ps; }
/// \ru Заполнены ли массивы параметров разбиения? \en Whether arrays of splitting parameters are filled?
bool IsEmpty() const { return (breaks0.Count() < 1); }
/// \ru Нужно ли проверять самопересечения \en Whether it is necessary to check self-intersections
bool CheckSelfInt() const { return checkSelfInt; }
/// \ru Установить флаг соединения через вершины \en Set flag of connection through vertices
void SetJoinByVertices( bool byVerts ) { joinByVertices = byVerts; }
/// \ru Соединяются ли кривые через вершины? \en Whether curves are joined through vertices?
bool GetJoinByVertices() const { return joinByVertices; }
/// \ru Установить флаг упрощения граней. \en Set flag of faces simplification.
void SetSimplifyFaces( bool simplFaces ) { simplifyFaces = simplFaces; }
/// \ru Получить флаг упрощения граней. \en Get flag of faces simplification.
bool GetSimplifyFaces() const { return simplifyFaces; }
private:
// \ru Проверить наличие параметров вершин контура в массиве параметров \en Check for loop vertices parameters in the parameters array
bool CheckVertices( const MbCurve3D & curve,
const SArray<double> & breaks ) const;
public:
KNOWN_OBJECTS_RW_REF_OPERATORS_EX( RuledSurfaceValues, MATH_FUNC_EX )
OBVIOUS_PRIVATE_COPY( RuledSurfaceValues )
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры удлинения оболочки.
\en The shell extension parameters. \~
\details \ru Параметры удлинения оболочки путём продления грани или достраивания грани. \n
\en The parameters of extension shell by extending or face-filling. \n \~
\ingroup Build_Parameters
*/
// ---
struct MATH_CLASS ExtensionValues {
public:
/** \brief \ru Типы удлинения.
\en Types of extension. \~
\details \ru Типы удлинения оболочки. Указывает форму поверхности удлинения.
\en Types of shell extension. Indicates the form extension surface. \~
*/
enum ExtensionType {
et_same = 0, ///< \ru По той же поверхности. \en Along the same surface.
et_tangent, ///< \ru По касательной к краю. \en Along tangent to the edge.
et_direction, ///< \ru По направлению. \en Along the direction.
};
/** \brief \ru Способы удлинения.
\en Ways of extension. \~
\details \ru Способы удлинения оболочки.
\en Ways of shell extension. \~
*/
enum ExtensionWay {
ew_distance = -2, ///< \ru Продолжить на расстояние. \en Prolong on the distance.
ew_vertex = -1, ///< \ru Продолжить до вершины. \en Prolong to the vertex.
ew_surface = 0, ///< \ru Продолжить до поверхности. \en Prolong to the surface.
};
/** \brief \ru Способы построения боковых рёбер.
\en Methods of construction of the lateral edges. \~
\details \ru Способы построения боковых рёбер при удлинении оболочки.
\en Methods of construction of the lateral edges when extending shell. \~
*/
enum LateralKind {
le_normal = 0, ///< \ru По нормали к кромке. \en Along the normal to boundary.
le_prolong, ///< \ru Продлить исходные рёбра. \en Extend the initial edges.
};
public:
ExtensionType type; ///< \ru Тип удлинения. \en Type of extension.
ExtensionWay way; ///< \ru Способ удлинения. \en Way of extension.
LateralKind kind; ///< \ru Способ построения боковых рёбер. \en Method of construction of the lateral edges.
MbCartPoint3D point; ///< \ru Точка, до которой удлинить. \en The point to extend.up to which.
MbVector3D direction; ///< \ru Направление удлинения. \en Direction of extension.
double distance; ///< \ru Расстояние. \en Distance.
bool prolong; ///< \ru Продолжить по гладко стыкующимся рёбрам. \en Prolong along smoothly mating edges.
bool combine; ///< \ru Объединять грани при возможности. \en Combine faces if it is possible.
private:
MbFaceShell * shell; ///< \ru Оболочка. \en A shell.
MbItemIndex faceIndex; ///< \ru Номер грани в оболочке. \en The index of face in the shell.
public:
/// \ru Конструктор по умолчанию. \en Default constructor.
ExtensionValues();
/// \ru Конструктор копирования. \en Copy-constructor.
ExtensionValues( const ExtensionValues & other );
/// \ru Конструктор. \en Constructor.
ExtensionValues( ExtensionType t, ExtensionWay w, LateralKind k, const MbCartPoint3D & p,
const MbVector3D & dir, double d, bool pro, bool comb, const MbFaceShell * s, const MbItemIndex & fIndex );
/// \ru Деструктор. \en Destructor.
virtual ~ExtensionValues();
public:
/** \brief \ru Функция инициализации.
\en Initialization function. \~
\details \ru Функция инициализации удлинения на расстояние.
\en Initialization function of extending to a distance. \~
\param[in] t - \ru Тип удлинения.
\en Type of extension. \~
\param[in] k - \ru Способ построения боковых рёбер.
\en Method of construction of the lateral edges. \~
\param[in] v - \ru Направление удлинения.
\en Direction of extension. \~
\param[in] d - \ru Величина удлинения.
\en Value of extension. \~
*/
void InitByDistance( ExtensionType t, LateralKind k, const MbVector3D & v, double d );
/** \brief \ru Функция инициализации.
\en Initialization function. \~
\details \ru Функция инициализации удлинения до вершины.
\en Initialization function of extension to the vertex. \~
\param[in] t - \ru Тип удлинения.
\en Type of extension. \~
\param[in] k - \ru Способ построения боковых рёбер.
\en Method of construction of the lateral edges. \~
\param[in] v - \ru Вершина, до которой строится удлинение.
\en The vertex to construct up to. \~
*/
void InitByVertex ( ExtensionType t, LateralKind k, const MbCartPoint3D & v );
/** \brief \ru Функция инициализации.
\en Initialization function. \~
\details \ru Функция инициализации удлинения до поверхности.
\en Initialization function of extension to the surface. \~
\param[in] t - \ru Тип удлинения.
\en Type of extension. \~
\param[in] k - \ru Способ построения боковых рёбер.
\en Method of construction of the lateral edges. \~
\param[in] f - \ru Грань оболочки.
\en Face of the shell. \~
\param[in] s - \ru Тело для замены оболочки.
\en Solid for replacement of shell. \~
*/
void InitBySurface ( ExtensionType t, LateralKind k, const MbFace * f, const MbSolid * s );
/// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix.
void Transform( const MbMatrix3D & matr, MbRegTransform * ireg = NULL );
/// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector.
void Move ( const MbVector3D & to, MbRegTransform * ireg = NULL );
/// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis.
void Rotate ( const MbAxis3D & axis, double ang, MbRegTransform * ireg = NULL );
/// \ru Получить оболочку. \en Get the shell.
const MbFaceShell * GetShell() const { return shell; }
/// \ru Номер грани в оболочке. \en The index of face in the shell.
const MbItemIndex & GetFaceIndex() const { return faceIndex; }
/// \ru Замена оболочки и ее выбранной грани. \en Replacement of shell and its selected face.
void SetShell( const MbFace * f, const MbSolid * s );
/// \ru Оператор присваивания. \en Assignment operator.
void operator = ( const ExtensionValues & other );
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const ExtensionValues & other, double accuracy ) const;
KNOWN_OBJECTS_RW_REF_OPERATORS( ExtensionValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class.
};
//------------------------------------------------------------------------------
/** \brief \ru Данные для построения поверхности соединения.
\en Data for construction of surface of the joint. \~
\details \ru Данные для построения поверхности соединения по двум кривым на поверхностях. \n
\en Data for the construction of surface of the joint by two curves on the surfaces. \n \~
\ingroup Build_Parameters
*/
//---
struct MATH_CLASS JoinSurfaceValues {
public:
/** \brief \ru Типы сопряжения поверхностей.
\en Type of surfaces join. \~
\details \ru Типы сопряжения поверхностей определяет стыковку края сопрягаемой поверхности и поверхности сопряжения.
\en Types of join of surfaces determines join of edge of joining surface and surface of the joint. \~
*/
enum JoinConnType {
js_Position = 0, ///< \ru По позиции. \en By position.
js_NormPlus, ///< \ru По нормали в положительном направлении вектора нормали. \en Along the normal in the positive direction of normal vector.
js_NormMinus, ///< \ru По нормали в отрицательном направлении вектора нормали. \en Along the normal in the negative direction of normal vector.
js_G1Plus, ///< \ru По касательной к поверхности, слева по направлению касательной к кривой пересечения. \en The type of conjugation along the tangent to the surface, to the left along the tangent to the intersection curve.
js_G1Minus, ///< \ru По касательной к поверхности, справа по направлению касательной к кривой пересечения. \en The type of conjugation along the tangent to the surface, to the right along the tangent to the intersection curve.
js_G2Plus, ///< \ru По касательной к поверхности, слева по направлению касательной к кривой пересечения, гладкая. \en The type of conjugation along the tangent to the surface, to the left along the tangent to the intersection curve, smooth.
js_G2Minus, ///< \ru По касательной к поверхности, справа по направлению касательной к кривой пересечения, гладкая. \en The type of conjugation along the tangent to the surface, to the right along the tangent to the intersection curve, smooth.
};
public:
JoinConnType connType1; ///< \ru Тип сопряжения поверхности соединения с поверхностью 1. \en Join type of surface of the joint with the surface 1.
JoinConnType connType2; ///< \ru Тип сопряжения поверхности соединения с поверхностью 2. \en Join type of surface of the joint with the surface 2.
double tension1; ///< \ru Натяжение для соединения с поверхностью 1. \en Tension for joining with surface 1.
double tension2; ///< \ru Натяжение для соединения с поверхностью 2. \en Tension for joining with surface 2.
SArray<double> breaks0; ///< \ru Параметры разбиения первой кривой curve0. \en Splitting parameters of the first curve0 curve.
SArray<double> breaks1; ///< \ru Параметры разбиения первой кривой curve1. \en Splitting parameters of the first curve1 curve.
bool checkSelfInt; ///< \ru Искать самопересечения. \en Find self-intersections.
bool edgeConnType1; ///< \ru Построение боковой границы как продолжение ребра. \en Construct lateral boundary as edge extension.
bool edgeConnType2; ///< \ru Построение боковой границы как продолжение ребра. \en Construct lateral boundary as edge extension.
MbVector3D * boundDirection11; ///< \ru Вектор направления, определяющий боковую границу, в точке (0, 0) поверхности. \en Direction vector determines lateral boundary in the point (0, 0) of the surface.
MbVector3D * boundDirection12; ///< \ru Вектор направления, определяющий боковую границу, в точке (1, 0) поверхности. \en Direction vector determines lateral boundary in the point (1, 0) of the surface.
MbVector3D * boundDirection21; ///< \ru Вектор направления, определяющий боковую границу, в точке (0, 1) поверхности. \en Direction vector determines lateral boundary in the point (0, 1) of the surface.
MbVector3D * boundDirection22; ///< \ru Вектор направления, определяющий боковую границу, в точке (1, 1) поверхности. \en Direction vector determines lateral boundary in the point (1, 1) of the surface.
public:
/// \ru Конструктор по умолчанию. \en Default constructor.
JoinSurfaceValues()
: connType1 ( js_G1Plus )
, connType2 ( js_G1Plus )
, tension1 ( 0.5 )
, tension2 ( 0.5 )
, breaks0 ( 0, 1 )
, breaks1 ( 0, 1 )
, checkSelfInt ( false )
, edgeConnType1 ( false )
, edgeConnType2 ( false )
, boundDirection11 ( NULL )
, boundDirection12 ( NULL )
, boundDirection21 ( NULL )
, boundDirection22 ( NULL )
{}
/// \ru Конструктор по параметрам. \en Constructor by parameters.
JoinSurfaceValues( JoinConnType t1, JoinConnType t2, double tens1, double tens2, bool selfInt = false )
: connType1 ( t1 )
, connType2 ( t2 )
, tension1 ( tens1 )
, tension2 ( tens2 )
, breaks0 ( 0, 1 )
, breaks1 ( 0, 1 )
, checkSelfInt ( selfInt )
, edgeConnType1 ( false )
, edgeConnType2 ( false )
, boundDirection11 ( NULL )
, boundDirection12 ( NULL )
, boundDirection21 ( NULL )
, boundDirection22 ( NULL )
{}
/// \ru Конструктор копирования. \en Copy-constructor.
JoinSurfaceValues( const JoinSurfaceValues & other );
public:
/// \ru Деструктор. \en Destructor.
virtual ~JoinSurfaceValues();
/// \ru Функция инициализации. \en Initialization function.
bool Init( const SArray<double> & initBreaks0,
const SArray<double> & initBreaks1,
bool initCheckSelfInt,
JoinConnType initConnType1,
double initTension1,
bool initEdgeConnType1,
const MbVector3D * initBoundDir11,
const MbVector3D * initBoundDir12,
JoinConnType initConnType2,
double initTension2,
bool initEdgeConnType2,
const MbVector3D * initBoundDir21,
const MbVector3D * initBoundDir22 );
/// \ru Функция копирования. \en Copy function.
void Init( const JoinSurfaceValues & other );
/// \ru Оператор присваивания. \en Assignment operator.
void operator = ( const JoinSurfaceValues & other ) { Init( other ); }
/// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix.
void Transform( const MbMatrix3D &, MbRegTransform * ireg );
/// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector.
void Move ( const MbVector3D &, MbRegTransform * ireg );
/// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis.
void Rotate ( const MbAxis3D &, double angle, MbRegTransform * ireg );
/// \ru Выдать количество параметров разбивки. \en Get the count of splitting parameters.
size_t GetParamsCount( bool first ) const { return (first ? breaks0.size() : breaks1.size()); }
/// \ru Получить параметры разбивки (первую или вторую группу). \en Get splitting parameters (the first or second group).
void GetParams( bool first, SArray<double> & breaks ) const { breaks = (first ? breaks0 : breaks1); }
/// \ru Получить параметры разбивки (первую или вторую группу). \en Get splitting parameters (the first or second group).
double GetParam( bool first, size_t k ) const { C3D_ASSERT( k < GetParamsCount( first ) ); return (first ? breaks0[k] : breaks1[k]); }
/// \ru Установить параметры разбивки. \en Set splitting parameters.
void SetParams( bool first, const SArray<double> & ps ) { if ( first ) breaks0 = ps; else breaks1 = ps; }
/// \ru Параметры разбивки не заполнены? \en Whether splitting parameters are not filled?
bool IsEmpty() const { return breaks0.empty(); }
/// \ru Получить флаг проверки самопересечений. \en Get the flag of checking self-intersection.
bool CheckSelfInt() const { return checkSelfInt; }
/// \ru Установить флаг проверки самопересечений. \en Set the flag of checking self-intersection.
void SetSelfInt( bool aChech ) { checkSelfInt = aChech; }
/// \ru Выдать параметры параметры установки боковых граней. \en Get setting parameters of lateral faces.
bool GetEdgeConnType( bool isFirst = true ) const { return isFirst ? edgeConnType1 : edgeConnType2; }
/// \ru Установить параметры параметры установки боковых граней. \en Set setting parameters of lateral faces.
void SetEdgeConnType( bool connType, bool isFirst = true ) { isFirst ? edgeConnType1 = connType : edgeConnType2 = connType; }
/** \brief \ru Выдать вектор направления.
\en Get the direction vector. \~
\details \ru Выдать вектор направления, определяющий боковую границу.
\en Get the direction vector determining lateral boundary. \~
\param[in] num - \ru Номер границы:\n
num = 1 - вектор boundDirection11,\n
num = 2 - вектор boundDirection12,\n
num = 3 - вектор boundDirection21,\n
num = 4 - вектор boundDirection22.
\en The index of boundary:\n
num = 1 - vector boundDirection11,\n
num = 2 - vector boundDirection12,\n
num = 3 - vector boundDirection21,\n
num = 4 - vector boundDirection22. \~
*/
const MbVector3D * GetBoundDirection( size_t num ) const;
/** \brief \ru Установить вектор направления.
\en Set the direction vector. \~
\details \ru Установить вектор направления, определяющий боковую границу.
\en Set the direction vector determining lateral boundary. \~
\param[in] num - \ru Номер границы:\n
num = 1 - изменяем вектор boundDirection11,\n
num = 2 - изменяем вектор boundDirection12,\n
num = 3 - изменяем вектор boundDirection21,\n
num = 4 - изменяем вектор boundDirection22.
\en The index of boundary:\n
num = 1 - change vector boundDirection11,\n
num = 2 - change vector boundDirection12,\n
num = 3 - change vector boundDirection21,\n
num = 4 - change vector boundDirection22. \~
\param[in] aDirect - \ru Новый вектор направления.
\en The new direction vector. \~
*/
void SetBoundDirection( size_t num, const MbVector3D * aDirect );
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const JoinSurfaceValues & other, double accuracy ) const
{
bool isSame = false;
if ( (other.connType1 == connType1) &&
(other.connType2 == connType2) &&
(other.checkSelfInt == checkSelfInt) &&
(other.edgeConnType1 == edgeConnType1) &&
(other.edgeConnType2 == edgeConnType2) &&
(::fabs(other.tension1 - tension1) < accuracy) &&
(::fabs(other.tension2 - tension2) < accuracy) )
{
const size_t breaksCnt0 = breaks0.size();
const size_t breaksCnt1 = breaks1.size();
if ( (other.breaks0.size() == breaksCnt0) && (other.breaks1.size() == breaksCnt1) ) {
isSame = true;
size_t k;
for ( k = 0; k < breaksCnt0 && isSame; ++k ) {
if ( ::fabs(other.breaks0[k] - breaks0[k]) > accuracy )
isSame = false;
}
if ( isSame ) {
for ( k = 0; k < breaksCnt1 && isSame; ++k ) {
if ( ::fabs(other.breaks1[k] - breaks1[k]) > accuracy )
isSame = false;
}
}
if ( isSame ) {
bool isBoundDir11 = ((other.boundDirection11 != NULL) && (boundDirection11 != NULL));
bool isBoundDir12 = ((other.boundDirection12 != NULL) && (boundDirection12 != NULL));
bool isBoundDir21 = ((other.boundDirection21 != NULL) && (boundDirection21 != NULL));
bool isBoundDir22 = ((other.boundDirection22 != NULL) && (boundDirection22 != NULL));
if ( isSame && isBoundDir11 )
isSame = c3d::EqualVectors( *other.boundDirection11, *boundDirection11, accuracy );
if ( isSame && isBoundDir12 )
isSame = c3d::EqualVectors( *other.boundDirection12, *boundDirection12, accuracy );
if ( isSame && isBoundDir21 )
isSame = c3d::EqualVectors( *other.boundDirection21, *boundDirection21, accuracy );
if ( isSame && isBoundDir22 )
isSame = c3d::EqualVectors( *other.boundDirection22, *boundDirection22, accuracy );
}
}
}
return isSame;
}
public:
KNOWN_OBJECTS_RW_REF_OPERATORS( JoinSurfaceValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class.
DECLARE_NEW_DELETE_CLASS( JoinSurfaceValues )
DECLARE_NEW_DELETE_CLASS_EX( JoinSurfaceValues )
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры преобразования триангуляции в оболочку.
\en Operation parameters of grids-to-shell conversion. \~
\details \ru Параметры преобразования триангуляции в оболочку.
\en Operation parameters of grids-to-shell conversion. \~
\ingroup Build_Parameters
*/
// ---
struct MATH_CLASS GridsToShellValues {
public:
bool sewGrids; ///< \ru Сшивать наборы граней от разных сеток триангуляции. \en Sew together faces of grids.
bool mergeFaces; ///< \ru Сливать подобные грани (true). \en Whether to merge similar faces (true).
bool useGridSurface; ///< \ru Использовать поверхность на базе триангуляции. \en Use the surface based on triangulation.
public:
/// \ru Конструктор по умолчанию. \en Default constructor.
GridsToShellValues()
: sewGrids ( true )
, mergeFaces ( false )
, useGridSurface( false )
{}
/// \ru Конструктор копирования. \en Copy-constructor.
GridsToShellValues( const GridsToShellValues & other )
: sewGrids ( other.sewGrids )
, mergeFaces ( other.mergeFaces )
, useGridSurface( other.useGridSurface )
{}
/// \ru Конструктор по параметрам. \en Constructor by parameters.
GridsToShellValues( bool sg, bool mf, bool ugs = false )
: sewGrids ( sg )
, mergeFaces ( mf )
, useGridSurface( ugs )
{}
/// \ru Оператор присваивания. \en Assignment operator.
GridsToShellValues & operator = ( const GridsToShellValues & other )
{
sewGrids = other.sewGrids;
mergeFaces = other.mergeFaces;
useGridSurface = other.useGridSurface;
return *this;
}
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры создания срединной оболочки между выбранными гранями тела.
\en Operation parameters of median shell between selected faces of solid. \~
\details \ru Параметры создания срединной оболочки между выбранными гранями тела.
Выбранные грани должны быть эквидистантны по отношению друг к другу.
Грани должны принадлежать одному и тому же телу.
\en Operation parameters of median shell between selected faces of solid.
Selected face pairs should be offset from each other.
The faces must belong to the same body.\~
\ingroup Build_Parameters
*/
// ---
struct MATH_CLASS MedianShellValues {
public:
double position; ///< \ru Параметр смещения срединной оболочки относительно первой грани из пары. По умолчанию равен 50% расстояния между гранями. \en Parameter of shift the median surface from first face in faces pair. By default is 50% from distance between faces in pair.
double dmin; ///< \ru Минимальный параметр эквидистантности. \en Minimal equidistation value.
double dmax; ///< \ru Максимальный параметр эквидистантности. \en Maximal equidistation value.
public:
/// \ru Конструктор по умолчанию. \en Default constructor.
MedianShellValues()
: position ( 0.5 )
, dmin ( 0.0 )
, dmax ( 0.0 )
{}
/// \ru Конструктор копирования. \en Copy-constructor.
MedianShellValues( const MedianShellValues & other )
: position ( other.position )
, dmin ( other.dmin )
, dmax ( other.dmax )
{}
/// \ru Конструктор по параметрам. \en Constructor by parameters.
MedianShellValues( double pos, double d1, double d2 )
: position ( pos )
, dmin ( d1 )
, dmax ( d2 )
{}
public:
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const MedianShellValues & obj, double accuracy ) const
{
if ( (::fabs(dmin - obj.dmin) < accuracy) &&
(::fabs(dmax - obj.dmax) < accuracy) &&
(::fabs( position - obj.position) < accuracy ) )
{
return true;
}
return false;
}
public:
/// \ru Оператор присваивания. \en Assignment operator.
MedianShellValues & operator = ( const MedianShellValues & other )
{
position = other.position;
dmin = other.dmin;
dmax = other.dmax;
return *this;
}
KNOWN_OBJECTS_RW_REF_OPERATORS( MedianShellValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class.
};
//------------------------------------------------------------------------------
/** \brief \ru Множество граней для создания срединной оболочки.
\en Set of faces for build a median shell. \~
\details \ru Множество граней для создания срединной оболочки.
\en Set of faces for build a median shell.\~
\ingroup Build_Parameters
*/
// ---
class MATH_CLASS MedianShellFaces {
private:
std::vector<c3d::ItemIndexPair> facePairs; ///< \ru Набор пар выбранных граней. \en Set of selected faces pairs.
std::vector<double> distances; ///< \ru Вектор смещений второй грани по отношению к первой в каждой паре. \en Vector of shift values of second face in reference to first face in each pair.
public:
/// \ru Конструктор по умолчанию. \en Default constructor.
MedianShellFaces() {
facePairs.resize( 0 );
distances.resize( 0 );
}
/// \ru Конструктор по параметрам. \en Constructor by parameters.
MedianShellFaces( const std::vector<c3d::ItemIndexPair> & pairs )
{
facePairs = pairs;
distances.resize( pairs.size() );
}
/// \ru Деструктор. \en Destructor.
~MedianShellFaces() {}
public:
/// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix.
void Transform( const MbMatrix3D & );
/// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector.
void Move( const MbVector3D & );
/// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis.
void Rotate( const MbAxis3D &, double angle );
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const MedianShellFaces & obj, double accuracy ) const;
public:
/// \ru Добавить в набор пару граней. \en Add pair of faces.
void AddFacePair( const MbItemIndex & f1, const MbItemIndex & f2, double dist = 0.0 )
{
facePairs.push_back( c3d::ItemIndexPair(f1,f2) );
distances.push_back( dist );
}
/// \ru Получить пару граней по индексу. \en Get pair of faces by index.
const c3d::ItemIndexPair & _GetFacePair( size_t index ) const { return facePairs[index];}
/// \ru Удалить пару граней из набора. \en Remove pair of faces from set.
void RemovePairByIndex( size_t index )
{
facePairs.erase( facePairs.begin() + index );
distances.erase( distances.begin() + index );
}
/// \ru Вернуть расстояние между гранями. \en Get distance between faces.
const double & _GetDistance( size_t index ) const { return distances[index]; }
/// \ru Установить расстояние между гранями. \en Set distance between faces.
void _SetDistance( size_t index, double value ) { distances[index] = value; }
/// \ru Вернуть количество пар граней в наборе. \en Get count of pairs in given set.
size_t Count() const { return facePairs.size(); }
/// \ru Оператор присваивания. \en Assignment operator.
MedianShellFaces & operator = ( const MedianShellFaces & other ) {
facePairs = other.facePairs;
distances = other.distances;
return *this;
}
/// \ru Очистка текущего набора. \en Clear current faces set.
void Clear() { facePairs.clear(); distances.clear(); }
KNOWN_OBJECTS_RW_REF_OPERATORS( MedianShellFaces ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class.
};
//------------------------------------------------------------------------------
/// \ru Типы продления секущих поверхностей. \en Prolongation types of cutter surfaces.
// ---
enum MbeSurfaceProlongType {
cspt_None = 0x00, // 0000 ///< \ru Не продлевать. \en Don't prolong.
cspt_Planar = 0x01, // 0001 ///< \ru Плоские поверхности. \en Planar surfaces.
cspt_RevolutionAxis = 0x02, // 0010 ///< \ru Поверхности вращения (вдоль оси). \en Revolution surfaces (along axis).
cspt_RevolutionAngle = 0x04, // 0100 ///< \ru Поверхности вращения (по углу). \en Revolution surfaces (by angle).
cspt_Revolution = 0x06, // 0110 ///< \ru Поверхности вращения. \en Revolution surfaces.
};
//------------------------------------------------------------------------------
/** \brief \ru Параметры операции резки оболочки.
\en Shell cutting operation parameters. \~
\details \ru Параметры операции резки оболочки. \n
\en Shell cutting operation parameters. \n \~
\ingroup Build_Parameters
*/
// ---
class MATH_CLASS MbShellCuttingParams {
public:
/// \ru Состояние типа продления секущих поверхностей. \en State of prolongation types of cutter surfaces.
struct ProlongState {
typedef uint8 UintType;
protected:
bool active; ///< \ru Включено ли дополнительное управление продлением. \en Whether additional prolongation control is active.
UintType type; ///< \ru Тип продления секущей поверхности. \en Prolongation type of cutting surface.
public:
ProlongState() : active( false ), type( cspt_None ) {}
explicit ProlongState( MbeSurfaceProlongType t ) : active( true ), type( (UintType)t ) {}
ProlongState( const ProlongState & ps ) { active = ps.active; type = ps.type; }
public:
const ProlongState & operator = ( const ProlongState & ps ) { active = ps.active; type = ps.type; return *this; }
bool operator == ( const ProlongState & ps ) const { return (active == ps.active && type == ps.type); }
public:
void Reset() { active = false; type = cspt_None; }
void Init( const ProlongState & ps ) { active = ps.active; type = ps.type; }
void Init( bool a, UintType t ) { active = a; type = t; }
bool IsActive() const { return active; }
void SetActive( bool a ) { active = a; }
UintType GetType() const { return type; }
void SetType( MbeSurfaceProlongType t ) { type = (UintType)t; }
void AddType( MbeSurfaceProlongType t ) { type |= (UintType)t; }
void SetActiveType( bool a, MbeSurfaceProlongType t ) { active = a; type = (UintType)t; }
void AddActiveType( bool a, MbeSurfaceProlongType t ) { active = a; type |= (UintType)t; }
};
private:
MbSplitData cutterData; ///< \ru Данные секущего объекта. \en Cutter object(s) data.
MbBooleanFlags booleanFlags; ///< \ru Управляющие флаги булевой операции. \en Control flags of the Boolean operation.
MbSNameMaker nameMaker; ///< \ru Именователь операции. \en An object defining names generation in the operation.
ThreeStates retainedPart; ///< \ru Направление отсечения (сохраняемая часть исходной оболочки). \en The direction of cutting off (a part of the source shell to be kept).
ProlongState prolongState; ///< \ru Тип продления режущей поверхности. \en Prolongation type of cutter surface.
public:
/** \brief \ru Конструктор.
\en Constructor. \~
\details \ru Конструктор. \n
\en Constructor. \n \~
\param[in] part - \ru Сохраняемая часть исходной оболочки (+1, -1).
\en A part of the source shell to be kept (+1, -1). \~
\param[in] mergingFlags - \ru Флаги слияния элементов оболочки.
\en Control flags of shell items merging. \~
\param[in] cutAsClosed - \ru Построить замкнутую оболочку.
\en Create a closed shell. \~
\param[in] snMaker - \ru Именователь операции.
\en An object defining names generation in the operation. \~
*/
MbShellCuttingParams( int part, const MbMergingFlags & mergingFlags, bool cutAsClosed,
const MbSNameMaker & snMaker )
: cutterData ( )
, booleanFlags( )
, nameMaker ( snMaker )
, retainedPart( ts_neutral )
, prolongState( )
{
booleanFlags.InitCutting( cutAsClosed );
booleanFlags.SetMerging( mergingFlags );
SetRetainedPart( part );
}
/** \brief \ru Конструктор по контуру.
\en Constructor by a contour. \~
\details \ru Конструктор по контуру. \n
\en Constructor by a contour. \n \~
\param[in] place - \ru Локальная система координат, в плоскости XY которой расположен двумерный контур.
\en A local coordinate system the two-dimensional contour is located in XY plane of. \~
\param[in] contour - \ru Двумерный контур выдавливания расположен в плоскости XY локальной системы координат.
\en The two-dimensional contour of extrusion is located in XY plane of the local coordinate system. \~
\param[in] sameContour - \ru Использовать исходный контур (true) или его копию (false).
\en Use the source contour (true) or its copy (false). \~
\param[in] dir - \ru Направление выдавливания контура.
\en Extrusion direction of the contour. \~
\param[in] part - \ru Сохраняемая часть исходной оболочки (+1, -1).
\en A part of the source shell to be kept (+1, -1). \~
\param[in] mergingFlags - \ru Флаги слияния элементов оболочки.
\en Control flags of shell items merging. \~
\param[in] cutAsClosed - \ru Построить замкнутую оболочку.
\en Create a closed shell. \~
\param[in] snMaker - \ru Именователь операции.
\en An object defining names generation in the operation. \~
*/
MbShellCuttingParams( const MbPlacement3D & place, const MbContour & contour, bool sameContour, const MbVector3D & dir, int part,
const MbMergingFlags & mergingFlags, bool cutAsClosed,
const MbSNameMaker & snMaker )
: cutterData( place, dir, contour, sameContour )
, booleanFlags( )
, nameMaker ( snMaker )
, retainedPart( ts_neutral )
, prolongState( )
{
booleanFlags.InitCutting( cutAsClosed );
booleanFlags.SetMerging( mergingFlags );
SetRetainedPart( part );
}
/** \brief \ru Конструктор по контуру.
\en Constructor by a contour. \~
\details \ru Конструктор по контуру. \n
\en Constructor by a contour. \n \~
\param[in] place - \ru Локальная система координат, в плоскости XY которой расположен двумерный контур.
\en A local coordinate system the two-dimensional contour is located in XY plane of. \~
\param[in] contour - \ru Двумерный контур выдавливания расположен в плоскости XY локальной системы координат.
\en The two-dimensional contour of extrusion is located in XY plane of the local coordinate system. \~
\param[in] sameContour - \ru Использовать исходный контур (true) или его копию (false).
\en Use the source contour (true) or its copy (false). \~
\param[in] dir - \ru Направление выдавливания контура.
\en Extrusion direction of the contour. \~
\param[in] part - \ru Сохраняемая часть исходной оболочки (+1, -1).
\en A part of the source shell to be kept (+1, -1). \~
\param[in] mergingFlags - \ru Флаги слияния элементов оболочки.
\en Control flags of shell items merging. \~
\param[in] cutAsClosed - \ru Построить замкнутую оболочку.
\en Create a closed shell. \~
\param[in] snMaker - \ru Именователь операции.
\en An object defining names generation in the operation. \~
*/
MbShellCuttingParams( const MbPlacement3D & place, const MbContour & contour, bool sameContour, const MbVector3D & dir,
const MbMergingFlags & mergingFlags, bool cutAsClosed,
const MbSNameMaker & snMaker )
: cutterData( place, dir, contour, sameContour )
, booleanFlags( )
, nameMaker ( snMaker )
, retainedPart( ts_neutral )
, prolongState( )
{
booleanFlags.InitCutting( cutAsClosed );
booleanFlags.SetMerging( mergingFlags );
}
/** \brief \ru Конструктор по поверхности.
\en Constructor by a surface. \~
\details \ru Конструктор по поверхности. \n
\en Constructor by a surface. \n \~
\param[in] surface - \ru Режущая поверхность.
\en Cutting plane. \~
\param[in] sameSurface - \ru Использовать исходную поверхность (true) или её копию (false).
\en Use the source surface (true) or its copy (false). \~
\param[in] part - \ru Сохраняемая часть исходной оболочки (+1, -1).
\en A part of the source shell to be kept (+1, -1). \~
\param[in] mergingFlags - \ru Флаги слияния элементов оболочки.
\en Control flags of shell items merging. \~
\param[in] cutAsClosed - \ru Построить замкнутую оболочку.
\en Create a closed shell. \~
\param[in] snMaker - \ru Именователь операции.
\en An object defining names generation in the operation. \~
*/
MbShellCuttingParams( const MbSurface & surface, bool sameSurface, int part,
const MbMergingFlags & mergingFlags, bool cutAsClosed,
const MbSNameMaker & snMaker )
: cutterData( surface, sameSurface )
, booleanFlags( )
, nameMaker ( snMaker )
, retainedPart( ts_neutral )
, prolongState( )
{
booleanFlags.InitCutting( cutAsClosed );
booleanFlags.SetMerging( mergingFlags );
SetRetainedPart( part );
}
/** \brief \ru Конструктор по поверхности.
\en Constructor by a surface. \~
\details \ru Конструктор по поверхности. \n
\en Constructor by a surface. \n \~
\param[in] surface - \ru Режущая поверхность.
\en Cutting plane. \~
\param[in] sameSurface - \ru Использовать исходную поверхность (true) или её копию (false).
\en Use the source surface (true) or its copy (false). \~
\param[in] part - \ru Сохраняемая часть исходной оболочки (+1, -1).
\en A part of the source shell to be kept (+1, -1). \~
\param[in] mergingFlags - \ru Флаги слияния элементов оболочки.
\en Control flags of shell items merging. \~
\param[in] cutAsClosed - \ru Построить замкнутую оболочку.
\en Create a closed shell. \~
\param[in] snMaker - \ru Именователь операции.
\en An object defining names generation in the operation. \~
*/
MbShellCuttingParams( const MbSurface & surface, bool sameSurface,
const MbMergingFlags & mergingFlags, bool cutAsClosed,
const MbSNameMaker & snMaker )
: cutterData( surface, sameSurface )
, booleanFlags( )
, nameMaker ( snMaker )
, retainedPart( ts_neutral )
, prolongState( )
{
booleanFlags.InitCutting( cutAsClosed );
booleanFlags.SetMerging( mergingFlags );
}
/** \brief \ru Конструктор по оболочке.
\en Constructor by a shell. \~
\details \ru Конструктор по оболочке. \n
\en Constructor by a shell. \n \~
\param[in] solid - \ru Режущая оболочка.
\en Cutting shell. \~
\param[in] sameSolid - \ru Использовать исходную поверхность (true) или её копию (false).
\en Use the source surface (true) or its copy (false). \~
\param[in] part - \ru Сохраняемая часть исходной оболочки (+1, -1).
\en A part of the source shell to be kept (+1, -1). \~
\param[in] mergingFlags - \ru Флаги слияния элементов оболочки.
\en Control flags of shell items merging. \~
\param[in] cutAsClosed - \ru Построить замкнутую оболочку.
\en Create a closed shell. \~
\param[in] snMaker - \ru Именователь операции.
\en An object defining names generation in the operation. \~
*/
MbShellCuttingParams( const MbSolid & solid, bool sameSolid,
int part, const MbMergingFlags & mergingFlags, bool cutAsClosed,
const MbSNameMaker & snMaker )
: cutterData( solid, sameSolid, true )
, booleanFlags( )
, nameMaker ( snMaker )
, retainedPart( ts_neutral )
, prolongState( )
{
booleanFlags.InitCutting( cutAsClosed );
booleanFlags.SetMerging( mergingFlags );
SetRetainedPart( part );
}
/// \ru Копирующий конструктор. \en Copy constructor.
MbShellCuttingParams( const MbShellCuttingParams & other, MbRegDuplicate * iReg )
: cutterData ( other.cutterData, false, iReg )
, booleanFlags( other.booleanFlags )
, nameMaker ( other.nameMaker )
, retainedPart( other.retainedPart )
, prolongState( other.prolongState )
{
}
~MbShellCuttingParams()
{}
public:
/** \brief \ru Инициализация по контуру.
\en Initialize by a contour. \~
\details \ru Инициализация по контуру. \n
\en Initialize by a contour. \n \~
\param[in] place - \ru Локальная система координат, в плоскости XY которой расположен двумерный контур.
\en A local coordinate system the two-dimensional contour is located in XY plane of. \~
\param[in] contour - \ru Двумерный контур выдавливания расположен в плоскости XY локальной системы координат.
\en The two-dimensional contour of extrusion is located in XY plane of the local coordinate system. \~
\param[in] sameContour - \ru Использовать исходный контур (true) или его копию (false).
\en Use the source contour (true) or its copy (false). \~
\param[in] dir - \ru Направление выдавливания контура.
\en Extrusion direction of the contour. \~
\param[in] part - \ru Сохраняемая часть исходной оболочки (+1, -1).
\en A part of the source shell to be kept (+1, -1). \~
\param[in] mergingFlags - \ru Флаги слияния элементов оболочки.
\en Control flags of shell items merging. \~
\param[in] cutAsClosed - \ru Построить замкнутую оболочку.
\en Create a closed shell. \~
\param[in] snMaker - \ru Именователь операции.
\en An object defining names generation in the operation. \~
*/
bool InitPlaneContour( const MbPlacement3D & place, const MbContour & contour, bool sameContour, const MbVector3D & dir,
int part, const MbMergingFlags & mergingFlags, bool cutAsClosed,
const MbSNameMaker & snMaker )
{
if ( cutterData.InitPlaneContour( place, dir, contour, sameContour ) ) {
nameMaker.SetName( snMaker, true );
booleanFlags.InitCutting( cutAsClosed );
booleanFlags.SetMerging( mergingFlags );
SetRetainedPart( part );
prolongState.Reset();
return true;
}
return false;
}
/** \brief \ru Инициализация по контуру.
\en Initialize by a contour. \~
\details \ru Инициализация по контуру. \n
\en Initialize by a contour. \n \~
\param[in] place - \ru Локальная система координат, в плоскости XY которой расположен двумерный контур.
\en A local coordinate system the two-dimensional contour is located in XY plane of. \~
\param[in] contour - \ru Двумерный контур выдавливания расположен в плоскости XY локальной системы координат.
\en The two-dimensional contour of extrusion is located in XY plane of the local coordinate system. \~
\param[in] sameContour - \ru Использовать исходный контур (true) или его копию (false).
\en Use the source contour (true) or its copy (false). \~
\param[in] dir - \ru Направление выдавливания контура.
\en Extrusion direction of the contour. \~
*/
bool InitPlaneContour( const MbPlacement3D & place, const MbContour & contour, bool sameContour, const MbVector3D & dir )
{
if ( cutterData.InitPlaneContour( place, dir, contour, sameContour ) ) {
prolongState.Reset();
return true;
}
return false;
}
/** \brief \ru Конструктор по поверхности.
\en Constructor by a surface. \~
\details \ru Конструктор по поверхности. \n
\en Constructor by a surface. \n \~
\param[in] surface - \ru Режущая поверхность.
\en Cutting plane. \~
\param[in] sameSurface - \ru Использовать исходную поверхность (true) или её копию (false).
\en Use the source surface (true) or its copy (false). \~
\param[in] part - \ru Сохраняемая часть исходной оболочки (+1, -1).
\en A part of the source shell to be kept (+1, -1). \~
\param[in] mergingFlags - \ru Флаги слияния элементов оболочки.
\en Control flags of shell items merging. \~
\param[in] cutAsClosed - \ru Построить замкнутую оболочку.
\en Create a closed shell. \~
\param[in] snMaker - \ru Именователь операции.
\en An object defining names generation in the operation. \~
*/
bool InitSurface( const MbSurface & surface, bool sameSurface,
int part, const MbMergingFlags & mergingFlags, bool cutAsClosed,
const MbSNameMaker & snMaker )
{
if ( cutterData.InitSurfaces( surface, sameSurface ) ) {
nameMaker.SetName( snMaker, true );
booleanFlags.InitCutting( cutAsClosed );
booleanFlags.SetMerging( mergingFlags );
SetRetainedPart( part );
prolongState.Reset();
return true;
}
return false;
}
/** \brief \ru Конструктор по поверхности.
\en Constructor by a surface. \~
\details \ru Конструктор по поверхности. \n
\en Constructor by a surface. \n \~
\param[in] surface - \ru Режущая поверхность.
\en Cutting plane. \~
\param[in] sameSurface - \ru Использовать исходную поверхность (true) или её копию (false).
\en Use the source surface (true) or its copy (false). \~
\param[in] prType - \ru Тип продления режущей поверхности.
\en Cutter surface prolong type. \~
*/
bool InitSurface( const MbSurface & surface, bool sameSurface, ProlongState prState )
{
if ( cutterData.InitSurfaces( surface, sameSurface ) ) {
prolongState.Init( prState );
return true;
}
return false;
}
/** \brief \ru Конструктор по оболочке.
\en Constructor by a shell. \~
\details \ru Конструктор по оболочке. \n
\en Constructor by a shell. \n \~
\param[in] solid - \ru Режущая оболочка.
\en Cutting shell. \~
\param[in] sameSolid - \ru Использовать исходную поверхность (true) или её копию (false).
\en Use the source surface (true) or its copy (false). \~
\param[in] part - \ru Сохраняемая часть исходной оболочки (+1, -1).
\en A part of the source shell to be kept (+1, -1). \~
\param[in] mergingFlags - \ru Флаги слияния элементов оболочки.
\en Control flags of shell items merging. \~
\param[in] cutAsClosed - \ru Построить замкнутую оболочку.
\en Create a closed shell. \~
\param[in] snMaker - \ru Именователь операции.
\en An object defining names generation in the operation. \~
*/
bool InitSolid( const MbSolid & solid, bool sameSolid,
int part, const MbMergingFlags & mergingFlags, bool cutAsClosed,
const MbSNameMaker & snMaker )
{
if ( cutterData.InitSolid( solid, sameSolid, true ) ) {
nameMaker.SetName( snMaker, true );
booleanFlags.InitCutting( cutAsClosed );
booleanFlags.SetMerging( mergingFlags );
SetRetainedPart( part );
prolongState.Reset();
return true;
}
return false;
}
/** \brief \ru Конструктор по оболочке.
\en Constructor by a shell. \~
\details \ru Конструктор по оболочке. \n
\en Constructor by a shell. \n \~
\param[in] solid - \ru Режущая оболочка.
\en Cutting shell. \~
\param[in] sameSolid - \ru Использовать исходную поверхность (true) или её копию (false).
\en Use the source surface (true) or its copy (false). \~
*/
bool InitSolid( const MbSolid & solid, bool sameSolid )
{
if ( cutterData.InitSolid( solid, sameSolid, true ) ) {
prolongState.Reset();
return true;
}
return false;
}
/** \brief \ru Конструктор по оболочке.
\en Constructor by a shell. \~
\details \ru Конструктор по оболочке. \n
\en Constructor by a shell. \n \~
\param[in] creators - \ru Построители режущей оболочки.
\en Cutting shell creators. \~
\param[in] sameCreators - \ru Использовать оригиналы (true) или копии (false) построителей.
\en Use original creators (true) or its copies (false). \~
*/
template <class CreatorsVector>
bool InitSolid( const CreatorsVector & creators, bool sameCreators )
{
if ( cutterData.InitSolid( creators, sameCreators ) ) {
prolongState.Reset();
return true;
}
return false;
}
public:
/// \ru Это резка плоским контуром? \en Is cutting by planar contour?
bool IsCuttingByPlanarContour() const { return (cutterData.GetSketchCurvesCount() > 0 && cutterData.GetSketchCurve(0) != NULL); }
/// \ru Это резка поверхностью? \en Is cutting by surface?
bool IsCuttingBySurface() const { return (cutterData.GetSurfacesCount() > 0 && cutterData.GetSurface(0) != NULL); }
/// \ru Это резка оболочкой? \en Is cutting by shell?
bool IsCuttingBySolid() const { return (cutterData.GetCreatorsCount() > 0 && cutterData.GetCreator(0) != NULL) || (cutterData.GetSolidShell() != NULL); }
/// \ru Получить данные секущего объекта. \en Get cutter object(s) data.
const MbSplitData & GetCutterData() const { return cutterData; }
/// \ru Получить управляющие флаги булевой операции. \en Get control flags of the Boolean operation.
const MbBooleanFlags & GetBooleanFlags() const { return booleanFlags; }
/// \ru Получить управляющие флаги булевой операции. \en Get control flags of the Boolean operation.
MbBooleanFlags & SetBooleanFlags() { return booleanFlags; }
/// \ru Получить именователь операции. \en Get the object defining names generation in the operation.
const MbSNameMaker & GetNameMaker() const { return nameMaker; }
/// \ru Получить требование по оставляемой части. \en Get retained part demand.
ThreeStates GetRetainedPart() const { return retainedPart; }
/// \ru Установить требование по оставляемой части. \en Set retained part demand.
void SetRetainedPart( int part );
/// \ru Получить тип продления режущей поверхности. \en Get cutter surface prolong type.
const ProlongState & GetProlongState() const { return prolongState; }
/// \ru Получить тип продления режущей поверхности. \en Get cutter surface prolong type.
void ResetProlongState() { prolongState.Reset(); }
/// \ru Добавить тип продления режущей поверхности. \en Add cutter surface prolong type.
void SetSurfaceProlongType( MbeSurfaceProlongType pt ) { prolongState.SetActiveType( true, pt ); }
/// \ru Добавить тип продления режущей поверхности. \en Add cutter surface prolong type.
void AddSurfaceProlongType( MbeSurfaceProlongType pt ) { prolongState.AddActiveType( true, pt ); }
/// \ru Получить локальную систему координат двумерных кривых. \en Get the local coordinate system of two-dimensional curves.
const MbPlacement3D & GetSketchPlace() const { return cutterData.GetSketchPlace(); }
/// \ru Получить вектор направления выдавливания двумерных кривых. \en Get the extrusion direction vector of two-dimensional curves.
const MbVector3D & GetSketchDirection() const { return cutterData.GetSketchDirection(); }
/// \ru Получить двумерную кривую. \en Get two-dimensional curve.
const MbContour * GetSketchCurve() const { return cutterData.GetSketchCurve( 0 ); }
/// \ru Получить поверхность. \en Get a surface.
const MbSurface * GetSurface() const { return cutterData.GetSurface( 0 ); }
/// \ru Сливать подобные грани (true)? \en Whether to merge similar faces (true)?
bool MergeFaces() const { return booleanFlags.MergeFaces(); }
/// \ru Сливать подобные ребра (true)? \en Whether to merge similar edges (true)?
bool MergeEdges() const { return booleanFlags.MergeEdges(); }
/// \ru Построить замкнутую оболочку. \en Create a closed shell.
bool IsCuttingAsClosed() const { return booleanFlags.IsCutting(); }
OBVIOUS_PRIVATE_COPY ( MbShellCuttingParams )
};
//------------------------------------------------------------------------------
// \ru Установить требование по оставляемой части. \en Set retained part demand.
// ---
inline
void MbShellCuttingParams::SetRetainedPart( int part )
{
retainedPart = ts_neutral; // If part == 0 retain both parts
if ( part > 0 ) // If part > 0
retainedPart = ts_positive; // retain a part above cutter surface.
else if ( part < 0 ) // if part < 0
retainedPart = ts_negative; // Retain part below cutter surface..
}
//------------------------------------------------------------------------------
/** \brief \ru Параметры развёртки грани на плоскость.
\en Parameter for an unwrapping the face on a plane. \~
\details \ru Параметры развёртки грани на плоскость. \n
Параметры содержат информацию о положении развёртки и свойствах материала.
\en Parameter for an unwrapping the face on a plane. \n
The parameters contain information about the scan position and material properties. \~
\ingroup Build_Parameters
*/
// ---
struct MATH_CLASS RectifyValues {
protected :
MbPlacement3D place; ///< \ru Локальная система координат развернутой поверхности грани. \en The local coordinat system for result surface. \~
MbCartPoint init; ///< \ru Параметры поверхности, которые будут соответствовать начальной точке place. \en The parameters of the surface, which will correspond to the origin of the place. \~
MbStepData stepData; ///< \ru Данные для вычисления шага при триангуляции. \en Data for step calculation during triangulation. \~
double myu; ///< \ru Коэффициент Пуассона материала грани. \en The Poisson's ratio of face material. \~
bool faceted; ///< \ru Добавить в атрибуты мозаичный объект (true) или нет (false). \en Add to the attributes a mosaic object (true), or do't. \~
public :
/** \brief \ru Конструктор по умолчанию.
\en Default constructor. \~
\details \ru Конструктор параметров операции удаления из тела выбранных граней.
\en Constructor of operation parameters of removing the specified faces from the solid. \~
*/
RectifyValues()
: place()
, init()
, stepData()
, myu( 0.25 )
, faceted( false )
{}
/// \ru Конструктор по способу модификации и вектору перемещения. \en Constructor by way of modification and movement vector.
RectifyValues( const MbPlacement3D & pl, const MbCartPoint & r, const MbStepData & s, double m = 0.25, bool fset = false )
: place( pl )
, init( r )
, stepData( s )
, myu( m )
, faceted( fset )
{}
/// \ru Конструктор копирования. \en Copy-constructor.
RectifyValues( const RectifyValues & other )
: place ( other.place )
, init ( other.init )
, stepData( other.stepData )
, myu ( other.myu )
, faceted ( other.faceted )
{}
/// \ru Деструктор. \en Destructor.
~RectifyValues() {}
public:
/// \ru Функция копирования. \en Copy function.
void Init( const RectifyValues & other ) {
place.Init( other.place );
init.Init( other.init );
stepData.Init( other.stepData );
myu = other.myu;
faceted = other.faceted;
}
/// \ru Оператор присваивания. \en Assignment operator.
RectifyValues & operator = ( const RectifyValues & other ) {
place.Init( other.place );
init.Init( other.init );
stepData.Init( other.stepData );
myu = other.myu;
faceted = other.faceted;
return *this;
}
// \ru Локальная система координат развернутой поверхности грани. \en The local coordinat system for result surface. \~
void SetPlacement( const MbPlacement3D & pl ) { place.Init( pl ); }
const MbPlacement3D & GetPlacement() const { return place; }
// \ru Параметры поверхности, которые будут соответствовать начальной точке place. \en The parameters of the surface, which will correspond to the origin of the place. \~
void SetOrigin( const MbCartPoint & r ) { init = r; }
const MbCartPoint & GetOrigin() const { return init; }
// \ru Данные для вычисления шага при триангуляции. \en Data for step calculation during triangulation. \~
void SetStepData( const MbStepData & step ) { stepData = step; }
const MbStepData & GetStepData() const { return stepData; }
// \ru Коэффициент Пуассона материала грани. \en The Poisson's ratio of face material. \~
void SetPoissonsRatio( double m ) { myu = m; }
double GetPoissonsRatio() const { return myu; }
// \ru Добавить в атрибуты мозаичный объект (true) или нет (false). \en Add to the attributes a mosaic object (true), or do't. \~
void SetAddFacet( bool b ) { faceted = b; }
bool AddFacet() const { return faceted; }
/// \ru Преобразовать объект согласно матрице. \en Transform an object according to the matrix.
void Transform( const MbMatrix3D & matr );
/// \ru Сдвинуть объект вдоль вектора. \en Move an object along a vector.
void Move ( const MbVector3D & to );
/// \ru Повернуть объект вокруг оси на заданный угол. \en Rotate an object at a given angle around an axis.
void Rotate ( const MbAxis3D & axis, double ang );
/// \ru Являются ли объекты равными? \en Determine whether an object is equal?
bool IsSame( const RectifyValues & other, double accuracy ) const;
KNOWN_OBJECTS_RW_REF_OPERATORS( RectifyValues ) // \ru Для работы со ссылками и объектами класса. \en For working with references and objects of the class.
}; // RectifyValues
#endif // __OP_SHELL_PARAMETERS_H
|
049224690c21bd1e52775ab07e5103507761f342
|
6d08402c80b22e2ebcfe8e66e3a269e42710f623
|
/Labs/lab8/lab8.cpp
|
90f186fb81efdc895647be07879436c128c51a3a
|
[] |
no_license
|
gabe-pier/cs201
|
2a919404cdad270dd383ddfbbe371778c63d6d24
|
c5c5a1a05a66e29b1c32f76ddf0e8b80b475a19e
|
refs/heads/master
| 2023-04-07T22:17:27.159016
| 2021-04-26T17:41:42
| 2021-04-26T17:41:42
| 332,127,010
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 184
|
cpp
|
lab8.cpp
|
#include <iostream>
#include "intio.hpp"
#include "lab8.hpp"
int doInput() {
int a;
a = getInt();
return a;
}
int compute(int n) {
int square;
square = n * n;
return square;
}
|
102863c28022dd7d969c44f22a8dcddb7f17d0db
|
9f63b75a1ac13e181ca99d558580e3527a45c0c6
|
/14.BST/4.Deletion_in_BST.cpp
|
f0a55bae4e64a95e3a94eb02df69e0a4b39b513a
|
[] |
no_license
|
smritipradhan/Datastructure
|
3934cfb27406d84b6840955645026e7b7595f8ea
|
74ecf07496fc571f9d676efe95dcdb796dc069e3
|
refs/heads/master
| 2023-07-11T11:58:33.515265
| 2021-08-11T14:26:11
| 2021-08-11T14:26:11
| 322,194,016
| 1
| 0
| null | 2021-08-11T14:26:12
| 2020-12-17T05:46:07
|
C++
|
UTF-8
|
C++
| false
| false
| 1,557
|
cpp
|
4.Deletion_in_BST.cpp
|
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node* right ;
Node* left;
Node(int d)
{
data = d;
left = NULL;
right = NULL;
}
};
Node* getSucessor(Node* cur) //case when the succesor is present
{
if(cur==NULL)return cur;
cur = cur->right;
while(cur!=NULL && cur->left!=NULL)
{
cur = cur->left;
}
return cur;
}
Node* delete_(Node* root,int key)
{
if(root==NULL)return root;
//first need to search the key
if(root->data > key) //when the key is on left side
{
root->left = delete_(root->left,key);
}
else if(root->data<key) //when the key is on right side
{
root->right = delete_(root->right,key);
}
else //when root->data is same as
{
//when the left node is NULL
//also handles when we need to delete the leaf node
if(root->left==NULL)
{
Node* temp = root->right;
delete root;
return temp;
}
//when the right node is NULL
//also handles when we need to delete the leaf node
else if(root->right==NULL)
{
Node* temp = root->left;
delete root;
return temp;
}
//when nothing is NULL
else
{
Node* temp = getSucessor(root);
root->data = temp->data; //just replace
root->right = delete_(root->right,temp->data);
}
}
}
void inorder(Node *root){
if(root!=NULL){
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
}
int main()
{
Node *root=new Node(10);
root->left=new Node(5);
root->right=new Node(15);
root->right->left=new Node(12);
root->right->right=new Node(18);
int x=15;
root=delete_(root,x);
inorder(root);
}
|
34b56ed7de87f33759576fbc458a63d8bd92f686
|
0c6ad83017727a71da52800e5d648eaaa646f43b
|
/Src/Tools/EffectCompiler/ueToolEffect.h
|
d60cd50ecaec4b912009873b1e90c45c91d8a30b
|
[] |
no_license
|
macieks/uberengine
|
4a7f707d7dad226bed172ecf9173ab72e7c37c71
|
090a5e4cf160da579f2ea46b839ece8e1928c724
|
refs/heads/master
| 2021-06-06T05:14:16.729673
| 2018-06-20T21:21:43
| 2018-06-20T21:21:43
| 18,791,692
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 573
|
h
|
ueToolEffect.h
|
#pragma once
#include "ContentPipeline/ueContentPipeline.h"
class ioPackageWriter;
class ioSegmentWriter;
struct gxEffectTypeData;
class ueToolEffect
{
public:
struct LoadSettings
{
std::string m_sourceFileName;
};
gxEffectTypeData* m_data;
std::vector< std::vector<std::string> > m_textureNames; // An array of gxEmitterType::Texture_MAX per emitter
ueToolEffect() : m_data(NULL) {}
void LoadFromXml();
bool Serialize(ioPackageWriter* pw);
// Utils
static void DumpSettings();
static bool ParseSettings(LoadSettings& s, const ueAssetParams& params);
};
|
69fd21607a6e43887bb0f577cafdf00dc20b4203
|
2904cf511cded879e90331209ca017a7a3c3e609
|
/l2estimator.cpp
|
a7d1dcf13fc79987fee23d9b7bd62441536caec7
|
[] |
no_license
|
404-Geoscience/maginvlib
|
40e76a316335de741ac7888f86ee0745fc8d6ff7
|
5529d76e0a34e6b24c184314ed54b961d4e16172
|
refs/heads/master
| 2020-05-30T22:53:29.448694
| 2017-02-05T18:31:38
| 2017-02-05T18:31:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,740
|
cpp
|
l2estimator.cpp
|
//
// @(#)l2estimator.cpp 1.1 misha-16may103
//
// Copyright (c) 2003 of Geometrics.
// All rights reserved.
//
// Created: 16may103 by misha@misha.local
// Version: 16may103 by misha@misha.local
//
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "magfunc.h"
#include "l2estimator.h"
int dz29rls_(double *a, double *b, double *x, double *u, double *v,
double *s, double *rv, double *vu, int *mn, int *m, int *n,
double *eps, double *epsm, double *dm, double *am, int *k);
_z29rls_params::_z29rls_params() {
eps=0.;
epsm=0.;
dm=1.e+20;
am=1.e-20;
}
int Estimate_L2_rls(int n, int m, double *a, double *y, double *x, void * param, double * synt, double * fit,
double * max_fit, double *st_err, char * message) {
double eps, epsm, dm, am;
int k;
eps=0.;
epsm=0.;
dm=1.e+20;
am=1.e-20;
int ret = 0;
if(param) {
Z29RLS_PARAMS * p = (Z29RLS_PARAMS *)param;
eps = p->eps;
epsm = p->epsm;
dm = p->dm;
am = p->am;
}
double *u, *v, *vu, *s, *rv;
int mn_rls = n;
int m_rls = n;
int n_rls = m;
u = v = vu = s = rv = NULL;
u = (double *)malloc(n*m*sizeof(double)); if(!u) goto err_return;
v = (double *)malloc(n*m*sizeof(double)); if(!v) goto err_return;
vu = (double *)malloc(n*m*sizeof(double)); if(!vu) goto err_return;
s = (double *)malloc(m*sizeof(double)); if(!s) goto err_return;
rv = (double *)malloc(m*sizeof(double)); if(!rv) goto err_return;
// for(int i=0; i<n; i++) {
// for(int j=0; j<m; j++) fprintf(stdout, "%le ", a[n*j+i]);
// fprintf(stdout,"\n%lf\n", y[i]);
// }
dz29rls_(a, y, x, u,v,s,rv, vu, &mn_rls, &m_rls,
&n_rls, &eps, &epsm, &dm, &am, &k);
//for(int i=0; i<m; i++) fprintf(stdout, "s[%d]=%lf rv[%d]=%lf\n", i, s[i],i,rv[i]);
// compute synthetic field and related values
if(synt) {
MatMultVect(a, x, n, m, synt);
if(fit && max_fit) {
compute_fit(n, y, synt, fit, max_fit);
if(st_err) {
int i, j, ll;
double b1 = 0.;
for(i=0; i<m; i++)
for(j=0; j<m; j++) {
b1 = 0.;
for(ll=0; ll<k; ll++) {
b1 = b1 + v[m*ll+i]*pow(1./s[ll], 2)*v[m*ll+j];
}
u[m*j+i] = b1;
}
for(i=0; i<m; i++) st_err[i] = (*fit)*sqrt(u[i*m+i]);
} // end st_err
} // end fit & max_fit
} // end compute synt. field
ret = 1;
err_return:
if(u) { free(u); u = NULL; }
if(v) { free(v); v = NULL; }
if(vu) { free(vu); vu = NULL; }
if(s) { free(s); s = NULL; }
if(rv) { free(rv); rv = NULL; }
return ret;
}
|
d0bb2e9a980daffc9c0a043bd6b6217d26ba6e6a
|
334558bf31b6a8fd3caaf09c24898ff331c7e2da
|
/GenieWindow/plugins/genie_module/src/uiframe/QGenieFrameAbout.h
|
f882aa19d84a7ffa07afc37d90fd0e8e64308212
|
[] |
no_license
|
roygaogit/Bigit_Genie
|
e38bac558e81d9966ec6efbdeef0a7e2592156a7
|
936a56154a5f933b1e9c049ee044d76ff1d6d4db
|
refs/heads/master
| 2020-03-31T04:20:04.177461
| 2013-12-09T03:38:15
| 2013-12-09T03:38:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 844
|
h
|
QGenieFrameAbout.h
|
#ifndef _QGENIEFRAMEABOUT_H
#define _QGENIEFRAMEABOUT_H
#ifndef IN_STABLE_H
#include <QObject>
#include <QDialog>
#include <QPoint>
#include "ui_QGenieFrameAbout.h"
#endif
namespace Ui {
class QGenieFrameAbout;
}
class QGenieFrameAbout : public QDialog {
Q_OBJECT
public:
QGenieFrameAbout(QWidget *parent = 0);
~QGenieFrameAbout();
protected:
void changeEvent(QEvent *e);
#ifndef SHEET_STYLE_FORMAC
protected:
void mouseMoveEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
bool mDrag;
QPoint mDragPosition;
#endif
private:
Ui::QGenieFrameAbout *ui;
// QRect boardRect() const {return QRect(1, 1, width()-2, height()-2);}
// QRect frameRect() const {return QRect(0, 0, width()-1, height()-1);}
};
#endif // QGENIEFRAMEABOUT_H
|
49be79ea880c13e158d2f03ef526eb756649160f
|
63c8dc51fa8d0c228ee15cb229d9548f2495e0a6
|
/BossBullet.h
|
8c16ffda87b7e1223d62731ca8ed1b662e71874b
|
[] |
no_license
|
MatheusAmboni/Game-Space_Invaders
|
f075833230039ba2fa0b4dc268a30695f7f3a34b
|
2093a3476281497fd91e3ef3257d3210d8ab9ce9
|
refs/heads/master
| 2023-05-15T03:41:22.722778
| 2021-06-09T14:44:18
| 2021-06-09T14:44:18
| 375,386,839
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 277
|
h
|
BossBullet.h
|
#ifndef BOSSBULLET_H
#define BOSSBULLET_H
#include <QGraphicsPixmapItem>
#include <QObject>
class BossBullet : public QObject,public QGraphicsPixmapItem{
Q_OBJECT
public:
BossBullet(QGraphicsItem * parent=0);
public slots:
void move();
};
#endif // BOSSBULLET_H
|
26352290fb0b94ded7cf68799a5f94a9290db71f
|
d1a247872f81e2d50f08755076f8b0e660e35c18
|
/cpp/base/buildings/specific/production/powerplant.h
|
a1fa1587d9da17327c90352586e91acdaacf07ec
|
[] |
no_license
|
kangshung/Adversity
|
97671767a9c551708cbd1d4d8f269dc8af68f4d0
|
3516e4c7ffac76186082650cba4ff6921d1da1b2
|
refs/heads/master
| 2022-12-16T16:15:47.289414
| 2018-04-16T21:07:23
| 2018-04-16T21:09:26
| 298,070,393
| 0
| 0
| null | 2020-09-23T19:14:10
| 2020-09-23T19:14:09
| null |
UTF-8
|
C++
| false
| false
| 2,175
|
h
|
powerplant.h
|
#pragma once
#include <QVector>
#include "base/buildings/building.h"
#include "base/buildings/levelsinfo.h"
struct PowerplantLevelInfo : public BuildingLevelInfo
{
PowerplantLevelInfo()
: aetheriteOreTaken(0), energyLimit(0), energyGiven(0), maxCycles(0) {}
unsigned aetheriteOreTaken;
unsigned energyLimit;
unsigned energyGiven;
unsigned maxCycles;
};
class Powerplant : public Building
{
Q_OBJECT
public:
explicit Powerplant(Base *base, unsigned level, const AnyBuildingLevelsInfo *levelsInfo) noexcept;
Q_INVOKABLE int useCostInEnergy() const noexcept;
Q_INVOKABLE int productionInEnergySingle() const noexcept;
Q_INVOKABLE int productionInEnergySingleAfterUpgrade() const noexcept;
Q_INVOKABLE inline int basicCostInFoodSupplies() const noexcept
{
return 0;
}
Q_INVOKABLE inline int useCostInFoodSupplies() const noexcept
{
return 0;
}
Q_INVOKABLE inline int basicCostInBuildingMaterials() const noexcept
{
return 0;
}
Q_INVOKABLE inline int useCostInBuildingMaterials() const noexcept
{
return 0;
}
Q_INVOKABLE inline int basicCostInAetherite() const noexcept
{
return 0;
}
Q_INVOKABLE int useCostInAetherite() const noexcept;
Q_INVOKABLE int useCostInAetheriteSingle() const noexcept;
Q_INVOKABLE int useCostInAetheriteSingleAfterUpgrade() const noexcept;
Q_INVOKABLE int energyLimit() const noexcept;
Q_INVOKABLE int energyLimitAfterUpgrade() const noexcept;
void exchangeResources() noexcept;
Q_INVOKABLE void setCurrentCycles(unsigned amount) noexcept;
Q_INVOKABLE inline unsigned currentCycles() const noexcept
{
return m_currentCycles;
}
Q_INVOKABLE unsigned maxCycles() const noexcept;
Q_INVOKABLE unsigned maxCyclesAfterUpgrade() const noexcept;
void setLevelsInfo(const QVector <PowerplantLevelInfo *> &info) noexcept;
Q_INVOKABLE unsigned upgradeTimeRemaining() noexcept;
private:
PowerplantLevelInfo *currentLevelInfo() const noexcept;
PowerplantLevelInfo *nextLevelInfo() const noexcept;
unsigned m_currentCycles;
};
|
976cac4a1689c7bcd0ef1629297ce7b3839ef9d1
|
9b9736c27ab3abcd258ecc02ea229f047821f396
|
/main.cpp
|
0227cd89052d79d38cc525d5d4fe2cef5a69fce2
|
[] |
no_license
|
peterlee909/Define-Family
|
a76c2315fdebc01a2150b7f580ad0c2a68416f4a
|
e07633829356c9d42bba149cbb10a54cf0e9a96b
|
refs/heads/master
| 2020-06-08T13:18:15.234747
| 2019-06-22T12:57:21
| 2019-06-22T12:59:38
| 193,234,232
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 655
|
cpp
|
main.cpp
|
#include <iostream>
using namespace std;
#define FLAG
#ifdef FLAG //if defined
#define test 1
#else
#define test 2
#endif
#undef FLAG //undefined FLAG
#ifndef FLAG //if not defined
#define test1 3
#else
#define test1 4
#endif
int main(int argc, char *argv[])
{
cout << "After FLAG was defined, ifdef FLAG is true." << endl;
cout << "Then test is defined to 1." << endl;
cout << "test = " << test << endl; //test = 1
cout << "After FLAG was undefined, ifndef FLAG is true." << endl;
cout << "Then test1 is defined to 3." << endl;
cout << "test1 = " << test1 << endl; //test1 = 3
cin.get();
return 0;
}
|
f60df27fddb1180e79de6ddc72a4d77069ea2434
|
0986b80b009448a9e560ea39ecff8a19a9c195e5
|
/hw4/problem.h
|
90a41f2bb40a5db4dbb28d8e0dbaae9357a15210
|
[] |
no_license
|
jasonzliang/scalableMLAssignments
|
eafc3965dd20686282eca3c724524a1144d64d8a
|
7ac6b37d9c8044b57f0a43c146ea7a941928c9eb
|
refs/heads/master
| 2021-01-22T05:28:14.138888
| 2015-01-13T06:28:02
| 2015-01-13T06:28:02
| 29,174,548
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 454
|
h
|
problem.h
|
#ifndef PROBLEM
#define PROBLEM
#include "sparse_matrix.h"
#include <algorithm>
using namespace std;
struct centrality
{
int index;
double value;
};
void testMultiplyRunningTime(sparseMatrix &mat);
void computeCentrality(sparseMatrix &mat);
void normalize(double *x, int nRows);
double calculateLambda(sparseMatrix &mat, double *x, int nRows);
bool centrality_sort(centrality a, centrality b);
void topRankedNodes(double *x, int nRows);
#endif
|
be85b578ff1967b44974f2f24766a2f20d91d1ca
|
af9c1566c7f8b7e30ee957ef40de647c1d86d17a
|
/tek2/maths/207demographie/Core.hpp
|
d2186b515481d6fa6bdbb620308eec714f80c7e0
|
[] |
no_license
|
Vasrek77/epitech-projects
|
471b7503e189000ad1ab491915c950af4b661c01
|
6db30340f7accd04d037ba1ea2bc3e3ecd736251
|
refs/heads/master
| 2021-01-17T22:41:05.342477
| 2015-08-12T19:10:24
| 2015-08-12T19:10:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,027
|
hpp
|
Core.hpp
|
#ifndef CORE_HPP_
# define CORE_HPP_
# include <iostream>
# include <iomanip>
# include <algorithm>
# include <cmath>
# include <cstdlib>
# include <list>
# include <vector>
#include "Exception.hpp"
using namespace std;
class Core {
fstream _file;
char **_env;
ostringstream _stream;
list<string> _args;
list<string> _names;
vector<int> _years;
vector<double> _values;
double _a1;
double _b1;
double _a2;
double _b2;
double _e1;
double _e2;
double _c;
public:
Core() {};
~Core() {};
void init(int argc, char **argv, char **envp) {
this->_env = envp;
this->_stream << "./display.py ";
this->_years.resize(51);
this->_years.assign(51, 0);
this->_values.resize(51);
this->_values.assign(51, 0);
for (int i = 1; i < argc; i++) {
string toArg(argv[i]);
std::transform(toArg.begin(), toArg.end(), toArg.begin(), ::toupper);
if (std::find(this->_args.begin(), this->_args.end(), toArg) != this->_args.end()) {
throw Exception("Same code written twice");
} else {
this->_args.push_back(toArg);
}
}
}
void run(void) {
this->fill();
cout << setprecision(2) << fixed;
cout << "\033[1;4mPays:\033[0m" << endl;
for (list<string>::iterator it = this->_names.begin(); it != this->_names.end(); it++) {
cout << "\t" << *it << endl;
}
cout << endl;
this->ajust(this->_years, this->_values, &this->_a1, &this->_b1);
this->firstCovariance();
cout << "\033[1;4mAjustement de Y en X:\033[0m" << endl;
cout << "\ty = " << (this->_a1 / 1000000) << "x";
cout << ((this->_b1 > 0) ? " + " : " - ");
cout << (abs(this->_b1) / 1000000) << endl;
cout << "\tEcart-Type:\t\t\t\t" << (this->_e1 / 1000000) << endl;
cout << "\tEstimation de la population en 2050:\t" << ((this->_a1 / 1000000) * 2050 + (this->_b1 / 1000000)) << endl;
cout << endl;
this->_stream << (this->_a1 / 1000000) << " " << (this->_b1 / 1000000);
this->ajust(this->_values, this->_years, &this->_a2, &this->_b2);
this->secondCovariance();
if (this->_a2 < 0) {
throw Exception("Division by zero");
} else {
cout << "\033[1;4mAjustement de X en Y:\033[0m" << endl;
cout << "\tx = " << (this->_a2 * 1000000) << "y";
cout << ((this->_b2 > 0) ? " + " : " - ");
cout << abs(this->_b2) << endl;
cout << "\tEcart-Type:\t\t\t\t" << (this->_e2 / 1000000) << endl;
cout << "\tEstimation de la population en 2050:\t" << (((-(this->_b2) + 2050) / this->_a2) / 1000000) << endl;
cout << endl;
this->_stream << " " << (this->_a2 * 1000000) << " " << this->_b2;
this->correlation();
cout << setprecision(4) << fixed;
cout << "\033[1;4mCoéfficient de corrélation:\033[0m\t\t\t" << this->_c << endl;
for (vector<double>::iterator it = this->_values.begin(); it != this->_values.end(); it++) {
this->_stream << " " << (*it / 1000000);
}
system(this->_stream.str().c_str());
}
}
void end(void) {
this->_file.close();
this->_args.clear();
this->_names.clear();
this->_values.clear();
this->_years.clear();
}
void fill(void) {
for (int i = 0; i <= 50; i++) {
this->_years[i] = 1961 + i;
}
for (list<string>::iterator it = this->_args.begin(); it != this->_args.end(); it++) {
string line;
char name[512];
char code[512];
char token[512];
bool exist(false);
this->open();
while (getline(this->_file, line)) {
istringstream cell(line);
cell.getline(name, 512, ';');
cell.getline(code, 512, ';');
if (*it == code) {
this->_names.push_back(name);
exist = true;
int i(0);
while (cell.getline(token, 512, ';') and i < 51) {
this->_values[i] += stringToNumber(token);
i++;
}
break;
}
}
if (exist == false) {
ostringstream stream;
stream << *it;
stream << " code is not in .csv file";
throw Exception(stream.str());
}
this->close();
}
}
template <typename T, typename U>
void ajust(T x, U y, double *a, double *b) {
double xsomme(0);
double ysomme(0);
double xysomme(0);
double xxsomme(0);
int n(51);
for (int i = 0; i < n; i++) {
xsomme += x[i];
ysomme += y[i];
xxsomme += pow(x[i], 2);
xysomme += x[i] * y[i];
}
if ((n * xxsomme - xsomme * xsomme) < 0) {
throw Exception("Division by zero");
} else if ((n * xxsomme - xsomme * xsomme) < 0) {
throw Exception("Division by zero");
} else {
*a = (n * xysomme - xsomme * ysomme) / (n * xxsomme - pow(xsomme, 2));
*b = (ysomme * xxsomme - xsomme * xysomme) / (n * xxsomme - pow(xsomme, 2));
}
}
void firstCovariance(void) {
double ecart(0);
int n(51);
for (int i = 0; i < n; i++) {
ecart += pow(this->_values[i] - (this->_a1 * this->_years[i] + this->_b1), 2);
}
this->_e1 = sqrt(ecart / n);
}
void secondCovariance(void) {
double ecart(0);
int n(51);
for (int i = 0; i < n; i++) {
ecart += pow(this->_values[i] - ((-(this->_b2) + this->_years[i]) / this->_a2), 2);
}
this->_e2 = sqrt(ecart / n);
}
void correlation(void) {
double ecart(0);
int n(51);
for (int i = 0; i < n; i++) {
ecart += (this->_values[i] - (this->_a1 * this->_years[i] + this->_b1)) * (this->_values[i] - ((-(this->_b2) + this->_years[i]) / this->_a2));
}
ecart /= n;
this->_c = ecart / (this->_e1 * this->_e2);
}
double stringToNumber(const std::string &value) {
stringstream stream(value);
double number(0);
stream >> number;
return number;
}
string numberToString(double value) {
stringstream stream;
string str;
stream << value;
stream >> str;
return str;
}
void open(void) {
this->_file.open("data.csv");
if (!this->_file) {
throw Exception("File data.csv missing");
}
}
void close(void) {
this->_file.close();
}
};
#endif /* CORE_HPP_ */
|
f382ffdcf04ebcb100f21bd1a3fd4039277d25d4
|
ff6593f9ccbd8e7f898a15ab0b4be6e01306eede
|
/src/Point.h
|
348835db892ae824ef15153e3d5f76d4069da9da
|
[] |
no_license
|
Basasuya/scanline
|
4ccddff3c92b96f0a6fbebecb9e7c99284e1fdc6
|
9fe56cb9adb8b8e60ad7c0a617de6079efe8c852
|
refs/heads/master
| 2020-04-14T17:22:31.352602
| 2019-01-05T04:54:16
| 2019-01-05T04:54:16
| 163,977,702
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 848
|
h
|
Point.h
|
#ifndef BASASUYA_POINT_H
#define BASASUYA_POINT_H
#include <iostream>
#include <cstring>
template <typename T>
struct Point {
T x, y, z;
Point() {}
Point(T _x, T _y, T _z) : x(_x), y(_y), z(_z) {}
Point<T> operator + (Point<T> &other) {
return Point<T>(x + other.x, y + other.y, z + other.z);
}
Point<T> operator - (const Point<T>& other) {
return Point<T>(x - other.x, y - other.y, z - other.z);
}
Point<T> operator *(const Point<T>& other) {
return Point<T>(y*other.z - z*other.y, z*other.x - x*other.z, x*other.y - y*other.x);
}
Point<T> operator /(const T &num) {
return Point<T>(x / num, y / num, z / num);
}
Point<T> operator += (Point<T> &other) {
return Point<T>(x + other.x, y + other.y, z + other.z);
}
Point<T> operator *(const T &num) {
return Point<T>(x*num, y*num, z*num);
}
};
#endif
|
3efbcef35c9279898e0c86fa00ba17ac30a530b3
|
ba963924a404093eee02dda19f0b991a6743d80d
|
/Graph/LongestPath.cpp
|
7f114e672db727023bb282c43d819bbbe3dbed7d
|
[] |
no_license
|
bnacheva/Data-Structures-and-Algorithms-course
|
bee90c238bcf242a6fb5ba99c3c89ec3f5359eaa
|
6c8f17d1f038a072def497f0543e76545dcc4a34
|
refs/heads/master
| 2020-04-24T11:34:46.980079
| 2019-03-01T14:25:24
| 2019-03-01T14:25:24
| 171,930,010
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,133
|
cpp
|
LongestPath.cpp
|
#include <iostream>
#include <limits.h>
#include <list>
#include <stack>
#define NINF INT_MIN
using namespace std;
class Node
{
int v;
int weight;
public:
Node(int _v, int _w)
{
v = _v;
weight = _w;
}
int getV() { return v; }
int getWeight() { return weight; }
};
class Graph
{
int V;
list<Node>* nodes;
void topologicalSort(int v, bool visited[], stack<int>& Stack);
public:
Graph(int V);
void addEdge(int u, int v, int weight);
int longestPath(int s, int t);
};
Graph::Graph(int V)
{
this->V = V;
nodes = new list<Node>[V];
}
void Graph::addEdge(int u, int v, int weight)
{
Node node(v, weight);
nodes[u].push_back(node);
}
void Graph::topologicalSort(int v, bool visited[], stack<int>& Stack)
{
visited[v] = true;
list<Node>::iterator i;
for (i = nodes[v].begin(); i != nodes[v].end(); ++i)
{
Node node = *i;
if (!visited[node.getV()])
topologicalSort(node.getV(), visited, Stack);
}
Stack.push(v);
}
int Graph::longestPath(int s, int t)
{
stack<int> Stack;
int dist[V];
bool* visited = new bool[V];
for (int i = 0; i < V; i++)
{
visited[i] = false;
}
for (int i = 0; i < V; i++)
if (visited[i] == false)
topologicalSort(i, visited, Stack);
for (int i = 0; i < V; i++)
dist[i] = NINF;
dist[s] = 0;
while (Stack.empty() == false)
{
int u = Stack.top();
Stack.pop();
list<Node>::iterator i;
if (dist[u] != NINF)
{
for (i = nodes[u].begin(); i != nodes[u].end(); ++i)
if (dist[i->getV()] < dist[u] + i->getWeight())
dist[i->getV()] = dist[u] + i->getWeight();
}
}
return (dist[t] == NINF) ? -1 : dist[t];
}
int main()
{
int n, m, s, t;
cin >> n >> m >> s >> t;
Graph g(n);
for(int i = 0; i < m; ++i)
{
int src, dest, weight;
cin >> src >> dest >> weight;
g.addEdge(src - 1, dest - 1, weight);
}
cout << g.longestPath(s - 1, t - 1);
return 0;
}
|
e641abeb246ecfc289e492eaa55910bbdc9e46be
|
f67b47259c734b4355057246ac7111ab59086dd6
|
/lib/KFCConfiguration/src/JsonConfigReader.cpp
|
1a2d2f5e304bfd41c36bd6140642b43abeb1fdaa
|
[] |
no_license
|
externall-projects/esp8266-kfc-fw
|
2b28b848f9ab54a7107e6b27319606b5ad17f727
|
5889f7dce2ced0347ff96db3cbf27d1ea50dc466
|
refs/heads/master
| 2022-04-22T07:59:02.233681
| 2020-04-12T03:46:03
| 2020-04-12T03:46:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,027
|
cpp
|
JsonConfigReader.cpp
|
/**
* Author: sascha_lammers@gmx.de
*/
#include "JsonConfigReader.h"
PROGMEM_STRING_DEF(config_object_name, "config");
JsonConfigReader::JsonConfigReader(Stream* stream, Configuration &config, Configuration::Handle_t *handles) : JsonBaseReader(stream), _config(config), _handles(handles), _handle(INVALID_HANDLE), _isConfigObject(false) {
}
JsonConfigReader::JsonConfigReader(Configuration &config, Configuration::Handle_t *handles) : JsonConfigReader(nullptr, config, handles) {
}
bool JsonConfigReader::beginObject(bool isArray)
{
if (_isConfigObject) {
if (getLevel() == 3) {
_handle = (uint16_t)stringToLl(getKey());
_type = ConfigurationParameter::_INVALID;
_length = 0;
_data = String();
//Serial.printf("key %s\n", getKey().c_str());
}
}
else if (!isArray && getLevel() == 2 && !strcmp_P(getKey().c_str(), SPGM(config_object_name))) {
_isConfigObject = true;
}
return true;
}
bool JsonConfigReader::endObject()
{
if (_isConfigObject) {
if (getLevel() == 3) {
if (_handle != INVALID_HANDLE && _type != ConfigurationParameter::_INVALID) {
if (_handles) {
bool found = false;
auto current = _handles;
while(*current != 0 && *current != INVALID_HANDLE) {
if (*current == _handle) {
found = true;
break;
}
current++;
}
if (!found) {
_type = ConfigurationParameter::_INVALID;
}
}
_debug_printf_P(PSTR("JsonConfigReader::endObject(): handle %04x type %u valid %u\n"), _handle, _type, _type != ConfigurationParameter::_INVALID);
bool imported = true;
switch (_type) {
case ConfigurationParameter::BYTE: {
uint8_t byte = (uint8_t)stringToLl(_data);
_config.set<uint8_t>(_handle, byte);
}
break;
case ConfigurationParameter::WORD: {
uint16_t word = (uint16_t)stringToLl(_data);
_config.set<uint16_t>(_handle, word);
}
break;
case ConfigurationParameter::DWORD: {
uint32_t dword = (uint32_t)stringToLl(_data);
_config.set<uint32_t>(_handle, dword);
}
break;
case ConfigurationParameter::QWORD: {
uint64_t qword = (uint64_t)stringToLl(_data);
_config.set<uint64_t>(_handle, qword);
}
break;
case ConfigurationParameter::FLOAT: {
float number = _data.toFloat();
_config.set<float>(_handle, number);
}
break;
case ConfigurationParameter::DOUBLE: {
double number = strtod(_data.c_str(), nullptr);
_config.set<double>(_handle, number);
}
break;
case ConfigurationParameter::BINARY: {
if (_length * 2 == _data.length()) {
Buffer buffer;
auto ptr = _data.c_str();
while (_length--) {
uint8_t byte;
char buf[3] = { *ptr++, *ptr++, 0 };
byte = (uint8_t)strtol(buf, nullptr, 16);
buffer.write(byte);
}
_config.setBinary(_handle, buffer.get(), (uint16_t)buffer.length());
}
}
break;
case ConfigurationParameter::STRING:
_config.setString(_handle, _data);
break;
case ConfigurationParameter::_INVALID:
default:
imported = false;
break;
}
if (imported) {
_imported.push_back(_handle);
}
}
//Serial.printf("handle %04x done\n", _handle);
_handle = INVALID_HANDLE;
}
else if (getLevel() == 2 && !strcmp_P(getKey().c_str(), SPGM(config_object_name))) {
_isConfigObject = false;
}
}
return true;
}
bool JsonConfigReader::processElement()
{
if (_isConfigObject) {
auto keyStr = getKey();
auto key = keyStr.c_str();
//auto pathStr = getPath(false);
//auto path = pathStr.c_str();
//Serial.printf("key %s value %s type %s path %s index %d\n", key, getValue().c_str(), jsonType2String(getType()).c_str(), path, getObjectIndex());
if (!strcmp_P(key, PSTR("type"))) {
_type = (ConfigurationParameter::TypeEnum_t)stringToLl(getValue());
}
else if (!strcmp_P(key, PSTR("length"))) {
_length = (uint16_t)stringToLl(getValue());
}
else if (!strcmp_P(key, PSTR("data"))) {
_data = getValue();
}
}
return true;
}
bool JsonConfigReader::recoverableError(JsonErrorEnum_t errorType)
{
return true;
}
long long JsonConfigReader::stringToLl(const String& value) const
{
auto ptr = value.c_str();
if (*ptr == '"') {
ptr++;
}
return strtoll(ptr, nullptr, 0);
//if (*ptr == '0' && *(ptr + 1) == 'x') {
// return (long long)strtoull(ptr + 2, nullptr, 16);
//}
//else {
// if (*ptr == '-') {
// return strtoll(ptr, nullptr, 10);
// }
// return (long long)strtoull(ptr, nullptr, 10);
//}
}
|
c8ce229e7c6ad3414ec251c79c98b33cef31ead5
|
e343a62ba8b3d2563c360b85f362498e78da5f9b
|
/driver.cpp
|
ee351dbdba4a3fef55918a64ea36c6365f42ee48
|
[] |
no_license
|
AnthonyWaddell/Skip-List
|
9626dfe5dc23b0944c9c51b01ae8712b3d10d9da
|
acc4f7593097f01b9409850fb0bc16a889665a8f
|
refs/heads/master
| 2020-03-23T06:17:43.819244
| 2018-07-16T22:38:30
| 2018-07-16T22:38:30
| 141,201,588
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,813
|
cpp
|
driver.cpp
|
//----------------------------------------------------------------------------
// File: driver.cpp
//
// Description: Test Driver for the slist class
//
// Programmer: Anthony Waddell
//
// Functions: main()
//
// Environment: Hardware: PC, i7
// Software: OS: Windows 10
// Compiles under Microsoft Visual C++ 2015
//
// Comments: Only provided full function definitions for functions that
// had to be implemented by myself (insert and remove)
//-------------------------------------------------------------------------
#include <iostream>
#include <string>
#include "slist.h"
using namespace std;
//---------------------------------------------------------------------------
// Function: main()
// Title: Using Step List
// Description: This file contains function main() which tests slist class
//
// Programmer: Anthony Waddell
// Date: 11-17-17
// Version: 1.0
// Environment: Hardware: PC, i7
// Software: OS: Windows 10
// Compiles under Microsoft Visual C++ 2015
//
// Input: N/A
// Output: Various operations performed on a step list output to console
// Calls: SList<Object>; constructor
// insert()
// show()
// size()
// remove()
// find()
// getCost()
// Called By: n/a
// Parameters: None
// Returns: EXIT_SUCCESS upon successful execution
//
// History Log: 11-13-17 AW Began Project
// 11-17-17 AW Completed project
// Known Bugs: random not seeded
//----------------------------------------------------------------------------
int main()
{
// Test of constructor
SList<int> *intList = new SList<int>;
delete intList;
SList<string> facultyList;
// Test of insert
facultyList.insert("unknown");
facultyList.insert("erdly");
facultyList.insert("sung");
facultyList.insert("olson");
facultyList.insert("zander");
facultyList.insert("berger");
facultyList.insert("cioch");
facultyList.insert("fukuda");
facultyList.insert("stiber");
facultyList.insert("jackels");
// Test of size and show
cout << "#faculty members: " << facultyList.size() << endl;
facultyList.show();
cout << endl;
// Test of remove
cout << "deleting unknown" << endl;
facultyList.remove("unknown");
cout << "#faculty members: " << facultyList.size() << endl;
facultyList.show();
cout << endl;
// Test of find
cout << "finding stiber = " << facultyList.find("stiber") << endl;
cout << endl;
// Test of copy constructor
cout << "create another list" << endl;
SList<string> studentList = facultyList;
cout << "finding stiber = " << facultyList.find("stiber") << endl;
cout << "#faculty members: " << facultyList.size() << endl;
cout << endl;
cout << "cost of find = " << facultyList.getCost() << endl;
// Hold screen
system("pause");
return EXIT_SUCCESS;
}
|
3d8fac218817507fb346023ae38878d8031d71d5
|
02e2accd33e8810cb50bd8555cdb92f2a49301e7
|
/cegui/src/ScriptModules/Python/bindings/output/CEGUI/XMLHandler.pypp.hpp
|
446fdbca88a2b24bfea409d5d5f3f45b3a9b646d
|
[
"MIT"
] |
permissive
|
cegui/cegui
|
fa6440e848d5aea309006496d2211ddcd41fefdf
|
35809470b0530608039ab89fc1ffd041cef39434
|
refs/heads/master
| 2023-08-25T18:03:36.587944
| 2023-08-12T15:50:41
| 2023-08-12T15:50:41
| 232,757,330
| 426
| 78
|
MIT
| 2023-08-12T15:40:02
| 2020-01-09T08:15:37
|
C++
|
UTF-8
|
C++
| false
| false
| 207
|
hpp
|
XMLHandler.pypp.hpp
|
// This file has been generated by Py++.
#ifndef XMLHandler_hpp__pyplusplus_wrapper
#define XMLHandler_hpp__pyplusplus_wrapper
void register_XMLHandler_class();
#endif//XMLHandler_hpp__pyplusplus_wrapper
|
0b143908593e2310c9249db4c7613aae2eed234e
|
880607c476459904a6c25a03204ddaeb3de4cd38
|
/randomGenerator.ino
|
c6c75432a294094e51f908d706df73f9240832dc
|
[] |
no_license
|
JonahVincent/ArduinoRandom
|
4f2b41a7a4fb264ed5d53cb0b7aa033cc267e846
|
a921b0a60a220934c631ec0e4e6509f0d56fa203
|
refs/heads/master
| 2021-08-23T00:35:19.153619
| 2017-12-01T23:07:33
| 2017-12-01T23:07:33
| 112,794,829
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 410
|
ino
|
randomGenerator.ino
|
void setup() {
randomSeed(analogRead(0)); //generates random seed off of unused serial port
//if this is a used port change the 0 to an unused one
}
void loop() {
int randomNumber = random(1,9); //generates random number between 1 and 9 and places it in a variable
Serial.println(randomNumber); //this is just here to output the random number to make sure its working
}
|
0a0a3bac5eb7fbea9bb41ba6369ef2c6d3200f99
|
1aedde94661728716b2576503c36f76fd19bda0b
|
/realizedOrdersFilter.cpp
|
802d6f15a420bcc02242b41f39eff951757b0a3c
|
[] |
no_license
|
lukaszc27/eSawmill
|
e36662f88e77212377fa8cb293dc622d4716cca3
|
abf49c939692052ce43610663e1ed223e7c8b6f9
|
refs/heads/master
| 2020-03-14T10:49:27.683207
| 2018-05-18T12:52:49
| 2018-05-18T12:52:49
| 131,396,717
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,336
|
cpp
|
realizedOrdersFilter.cpp
|
#include "realizedOrdersFilter.h"
#include <qmessagebox.h>
RealizedOrdersFilter::RealizedOrdersFilter(QObject* parent)
: QSortFilterProxyModel(parent)
{
m_db = QSqlDatabase::database();
m_filterEnable = false;
}
//-------------------------------------------------
// aktywuje lub dezaktywuje filter zamówień
// zrealizowanych
void RealizedOrdersFilter::setFilterEnable(int state)
{
if (state)
m_filterEnable = true;
else m_filterEnable = false;
invalidateFilter();
}
//-------------------------------------------------
// odfiltorwuje zamówienia zrealizowane
// od niezrealizowanych
bool RealizedOrdersFilter::filterAcceptsRow(int sourceRow, const QModelIndex & sourceParent) const
{
if (!m_filterEnable)
{
if (m_db.isOpen() && m_db.isValid())
{
QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
QVariant value = index.data(Qt::UserRole);
QSqlQuery q;
q.prepare("SELECT zrealizowane FROM zamowienia WHERE zamowienieId = ?");
q.bindValue(0, value.toInt());
if (q.exec())
{
if (q.first())
{
if (q.value(0).toBool())
return false;
return true;
}
}
else
{
QMessageBox::critical(0, tr("Błąd"),
q.lastError().text());
return false;
}
}
}
return true;
}
|
cf4e729c041cd1dde71faa04c3a50bf2c28bd9e2
|
bf155131dc49357f82d304b7a3799d2ffa055e0c
|
/Player.cpp
|
b907ad8ddf48ed5f5340d6228772cb6e3a69f327
|
[] |
no_license
|
CodingZwen/FairyOfLife
|
ed5c3c8e2007968e16a7103eb0a20b17c687f9c9
|
7069324b00e033996c11746f0c2e3032c17fc002
|
refs/heads/master
| 2020-07-10T17:39:47.446036
| 2020-01-18T15:01:57
| 2020-01-18T15:01:57
| 204,324,476
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,759
|
cpp
|
Player.cpp
|
#include "Player.h"
Player::Player(sf::Vector2f spawnpos, sf::Texture const *texture, sf::Texture const * weaponTexture)
{
initStats();
playerweapon = new PlayerWeapon(weaponTexture);
setKeys(sf::Keyboard::Up, sf::Keyboard::Down, sf::Keyboard::Left, sf::Keyboard::Right, sf::Keyboard::Space);
direction = 2;
initAnimations(texture);
animatedSprite.setPosition(spawnpos);
//animatedSprite.setPosition(spawnpos);
//achtung initalisiert animation ptr von movement class
createMovementComponent(100.f, 30.f, 15.f);
}
Player::~Player()
{
if (playerweapon)delete playerweapon;
}
void Player::initAnimations(const sf::Texture *texture)
{
int spritex = 32;
int spritey = 48;
animatedSprite.insertAnimation(sf::IntRect(0, 0, spritex, spritey), 5,* texture,"WALKING_UP");
animatedSprite.insertAnimation(sf::IntRect(0, 48, spritex, spritey), 5,* texture, "WALKING_DOWN");
animatedSprite.insertAnimation(sf::IntRect(0, 48 * 2, spritex, spritey), 5,* texture, "WALKING_LEFT");
animatedSprite.insertAnimation(sf::IntRect(0, 48 * 3, spritex, spritey), 5,* texture, "WALKING_RIGHT");
animatedSprite.insertAnimation(sf::IntRect(0, 48*4, spritex, spritey), 5,* texture, "STANDING_UP");
animatedSprite.insertAnimation(sf::IntRect(0, 48*5, spritex, spritey), 5,* texture, "STANDING_DOWN");
animatedSprite.insertAnimation(sf::IntRect(0, 48 * 6, spritex, spritey), 5,* texture, "STANDING_LEFT");
animatedSprite.insertAnimation(sf::IntRect(0, 48 * 7, spritex, spritey), 5,* texture, "STANDING_RIGHT");
animatedSprite.insertAnimation(sf::IntRect(0, 48 * 8, spritex, spritey), 5,* texture, "STANDING_AFK");
animatedSprite.insertAnimation(sf::IntRect(0, 48 * 9, spritex, spritey), 5, *texture, "DEATHANIMATION");
animatedSprite.insertAnimation(sf::IntRect(0, 48 * 11, spritex, spritey), 5, *texture, "ATTACKING_DOWN");
animatedSprite.insertAnimation(sf::IntRect(0, 48 * 12, spritex, spritey), 5, *texture, "ATTACKING_LEFT");
animatedSprite.insertAnimation(sf::IntRect(0, 48 * 13, spritex, spritey), 5, *texture, "ATTACKING_RIGHT");
animatedSprite.setCurrentAnimation("STANDING_AFK");
animatedSprite.setFrameTime(sf::seconds(0.2));
}
void Player::move(const float dir_x, const float dir_y, const float & dt)
{
if (this->movementComponent)
{
this->movementComponent->move(dir_x, dir_y, dt);//xetzt bewegung fest
//printf("x: %d \n", dir_x);
}
}
void Player::update(sf::Time elapsed, sf::Vector2f ownerPos)
{
_elapsed += elapsed;
CastTimer += elapsed;
haventMoved = true;
if (attributs.isalive())
{
attributs.update(elapsed.asSeconds());
if (!playerweapon->attack) {
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::Up) || sf::Keyboard::isKeyPressed(sf::Keyboard::W))
&& (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) || sf::Keyboard::isKeyPressed(sf::Keyboard::D)))
{
moveNE(elapsed);
}
else if ((sf::Keyboard::isKeyPressed(sf::Keyboard::Up) || sf::Keyboard::isKeyPressed(sf::Keyboard::W))
&& (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) || sf::Keyboard::isKeyPressed(sf::Keyboard::A)))
{
moveNW(elapsed);
}
else if ((sf::Keyboard::isKeyPressed(sf::Keyboard::Down)|| sf::Keyboard::isKeyPressed(sf::Keyboard::S))
&& (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) ||sf::Keyboard::isKeyPressed(sf::Keyboard::D)))
{
moveSE(elapsed);
}
else if ((sf::Keyboard::isKeyPressed(sf::Keyboard::Down) || sf::Keyboard::isKeyPressed(sf::Keyboard::S))
&& (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) || sf::Keyboard::isKeyPressed(sf::Keyboard::A)))
{
moveSW(elapsed);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) || sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
moveUp(elapsed);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) || sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
moveDown(elapsed);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) || sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
moveLeft(elapsed);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) || sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
moveRight(elapsed);
}
}
if (haventMoved)
{
if (!playerweapon->attack)
{
switch (direction) {
case 2:
if (movementComponent->isAFK()) {
animatedSprite.setCurrentAnimation("STANDING_AFK");
}
else {
animatedSprite.setCurrentAnimation("STANDING_DOWN");
}break;
case 1: animatedSprite.setCurrentAnimation("STANDING_UP"); break;
case 3: animatedSprite.setCurrentAnimation("STANDING_LEFT"); break;
case 4: animatedSprite.setCurrentAnimation("STANDING_RIGHT"); break;
default:break;
}
}
else {
switch (direction) {
case 1: animatedSprite.setCurrentAnimation("STANDING_UP"); break;
case 2: animatedSprite.setCurrentAnimation("ATTACKING_DOWN"); break;
case 3: animatedSprite.setCurrentAnimation("ATTACKING_LEFT"); break;
case 4: animatedSprite.setCurrentAnimation("ATTACKING_RIGHT"); break;
default:break;
}
}
}
else
{
switch (direction)
{
case 1: animatedSprite.setCurrentAnimation("WALKING_UP");
angleForWeapon = 270;
break;
case 2: animatedSprite.setCurrentAnimation("WALKING_DOWN");
angleForWeapon = 90;
break;
case 3: animatedSprite.setCurrentAnimation("WALKING_LEFT");
angleForWeapon = 180;
break;
case 4: animatedSprite.setCurrentAnimation("WALKING_RIGHT");
angleForWeapon = 0;
break;
default: animatedSprite.setCurrentAnimation("DEATHANIMATION"); break;
}
}
drawWeaponBehind = (direction == 1)? true : false;
if (playerweapon)
{
playerweapon->update(elapsed, movementComponent->getPosition(), angleForWeapon);
playerweapon->update_offset(direction);
}
}
else {
animatedSprite.setCurrentAnimation("DEATHANIMATION");
animatedSprite.setLooped(0);
}
animatedSprite.update(elapsed);
movementComponent->update(elapsed.asSeconds());
}
void Player::setKeys(sf::Keyboard::Key u, sf::Keyboard::Key d, sf::Keyboard::Key l, sf::Keyboard::Key r, sf::Keyboard::Key s)
{
kUp = u;
kDown = d;
kLeft = l;
kRight = r;
kShoot = s;
}
void Player::draw(sf::RenderWindow & target)
{
if (drawWeaponBehind)
{
if (playerweapon)
playerweapon->draw(target);
target.draw(animatedSprite);
}
else
{
target.draw(animatedSprite);
if (playerweapon)
playerweapon->draw(target);
}
}
//diese funktion scheint iwie zugriffsverletzungen zu machen....
void Player::setplayerpos(sf::Vector2f const pos)
{
// rect.setPosition(sf::Vector2f(pos));
movementComponent->setPosition(pos);
}
void Player::hurt(int dmg)
{
//hp-=dmg;
Bgotdmg = true;
//printf("Spieler hat noch %d HP\n", playerstats.hp- playerstats.takendmg);
attributs.hurt(dmg);
}
bool Player::is_attacking()
{
return 1;
}
sf::Vector2f Player::getviewsetoff(sf::Vector2f playerpos, int mapwidth, int mapheight)
{
sf::Vector2f buffer;
buffer.x = playerpos.x;
buffer.y = playerpos.y;
buffer.x /= 32;
buffer.y /= 32;
//kante 5x 32
buffer.x -= 17;
buffer.y -= 15;
if (buffer.x < 0)buffer.x = 0;
if (buffer.x > mapwidth)buffer.x = mapwidth;
if (buffer.y < 0)buffer.y = 0;
if (buffer.y > mapheight)buffer.y = static_cast<float>(mapheight);
return buffer;
}
sf::Vector2f Player::getviewsetoff_right(sf::Vector2f playerpos, int mapwidth, int mapheight)
{
sf::Vector2f buffer;
buffer.x = playerpos.x;
buffer.y = playerpos.y;
buffer.x /= 32;
buffer.y /= 32;
//kante 5x 32
buffer.x += 17; //17
buffer.y += 15; //15
if (buffer.x < 0)buffer.x = 0;
if (buffer.x > mapwidth)buffer.x = mapwidth;
if (buffer.y < 0)buffer.y = 0;
if (buffer.y > mapheight)buffer.y = mapheight;
return buffer;
}
float Player::getAngleToTarget(sf::Vector2f target)
{
float a = atan2(target.y - movementComponent->getPosition().y, target.x - movementComponent->getPosition().x);
a *= (180.f / M_PI);
// if (a < 0)a += 360;
return a;
}
bool Player::CanSpell()
{
if (CastTimer.asSeconds() > attributs.getCastTime()) return true;
else return false;
}
bool Player::HaveEnoughMana(unsigned const int spellcost)
{
if (spellcost < attributs.getCurrentMana())return true;
else return false;
}
void Player::initStats()
{
attributs.setCastTime(0.8f);
attributs.setStats(1,5, 5, 20, 1.f, 200);
attributs.setEquipStats(0, 0, 0, 0,0);
}
/*
if (noKeyWasPressed)
{
switch (direction) {
case 2:
blinktimer += elapsed;
if (blinktimer.asSeconds() > 5) {
animatedSprite.setCurrentAnimation("STANDING_AFK");
if (blinktimer.asSeconds() > 7) {
blinktimer = blinktimer.Zero;
}
}
else {
animatedSprite.setCurrentAnimation("STANDING_DOWN");
}break;
case 1: animatedSprite.setCurrentAnimation("STANDING_UP"); break;
case 3: animatedSprite.setCurrentAnimation("STANDING_LEFT"); break;
case 4: animatedSprite.setCurrentAnimation("STANDING_RIGHT"); break;
default:break;
}
}
else
{
switch (direction)
{
case 1: animatedSprite.setCurrentAnimation("WALKING_UP"); break;
case 2: animatedSprite.setCurrentAnimation("WALKING_DOWN"); break;
case 3: animatedSprite.setCurrentAnimation("WALKING_LEFT"); break;
case 4: animatedSprite.setCurrentAnimation("WALKING_RIGHT"); break;
default:break;
}
}
*/
|
a118198098d3c2e60abae5107ce57ff6dc707b7d
|
8a5c80a355fc01fc08bd264962ab156f6976cd0a
|
/puzzlesolver/include/enums.h
|
ebaa7cda1dbf88a2bd3961e1fee8ef476e268a5a
|
[] |
no_license
|
mkrakiewicz/PuzzleSolver
|
3e53490dcf6c00f23564754fb33e2f1b763525dd
|
fa20616ead48004f96f4430bac1ffddadf65f49d
|
refs/heads/master
| 2020-08-14T03:56:37.610637
| 2014-01-05T22:14:13
| 2019-10-14T16:59:17
| 215,093,432
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 307
|
h
|
enums.h
|
#ifndef ENUMS_H
#define ENUMS_H
#include <string>
namespace board
{
enum SLIDE_DIRECTIONS
{
UP,
DOWN,
LEFT,
RIGHT
};
SLIDE_DIRECTIONS operator-(const SLIDE_DIRECTIONS& d);
std::string dirToStr(board::SLIDE_DIRECTIONS direction);
}
#endif // ENUMS_H
|
815404cced18de2aaef41c75662b23076e7de4d7
|
2f1572dccdae76748a2a0e41d0a21311f5d1fc90
|
/src/RedisDefine.h
|
f4c6a026a8c8af7073273d8266dd454cab2002f3
|
[
"MIT"
] |
permissive
|
glc400/rediscpp
|
9ffa2f0c4f0a416ab9886a56098bb2d0dd2498d4
|
bc5998a0487de688b7f347fa328df23eb2fb015b
|
refs/heads/master
| 2021-01-10T11:25:32.603809
| 2016-03-27T09:32:32
| 2016-03-27T09:32:32
| 54,821,476
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,971
|
h
|
RedisDefine.h
|
#ifndef REDISDEFINE_H_
#define REDISDEFINE_H_
#include <list>
#include <map>
#include <new>
#include <vector>
#include <unistd.h>
#include <stdint.h>
#include <string.h>
#include <string>
#include <sstream>
#include <functional>
#include <iostream>
#define THREAD_STACK_SIZE 10*1024*1024 //10M
#define LEN_ERROR_INFO 1024
#define LEN_REPLAY_ITEM 4096
#define SLEEP_SECONDS 1
#define ERROR_GET_CONNECT "Get redis connection error"
#define ERROR_CONNECT_CLOSED "Redis connection be closed"
#define ERROR_NULL_CONTEXT "Null RedisContext"
#define ERROR_ARGS_COMMAND "ERR arguments for '%s' command"
#define ERROR_APPEND_COMMAND "ERR "
typedef struct _TReplyItem{
int type;
std::string str;
_TReplyItem& operator=(const _TReplyItem&data){
type = data.type;
str = data.str;
return *this;
}
} TReplyItem;
typedef enum _ESortOrder
{
ASC = 0,
DESC = 1
} ESortOrder;
typedef enum _EBitOP
{
AND = 0,
OR = 1,
XOR = 2,
NOT = 3
} EBitOP;
typedef struct _TSortLimit
{
int offset;
int count;
} TSortLimit;
typedef enum _ELIST_MODE{
BEFORE = 0,
AFTER = 1
} ELIST_MODE;
typedef std::map<std::string, std::string> MapReply;
typedef std::vector<TReplyItem> ArrayReply;
typedef std::vector<TReplyItem> ReplyData;
typedef std::string KEY;
typedef std::string VALUE;
typedef std::vector<KEY> KEYS;
typedef std::vector<VALUE> VALUES;
typedef std::vector<std::string> VDATA;
template<class T>
static std::string toString(const T &t) {
std::ostringstream oss;
oss << t;
return oss.str();
}
template<class Type>
static Type fromString(const std::string& str) {
std::istringstream iss(str);
Type num;
iss >> num;
return num;
}
static bool inString(const std::string& str, const std::string& fromstr){
std::istringstream istr(fromstr);
std::string tmp;
while(istr >> tmp){
if(tmp == str) return true;
}
return false;
}
#endif /* REDISDEFINE_H_ */
|
9f6dee1088b2dc9f39170467f38386662b6184e9
|
f0610b8452d1addcb026144516550829a558616f
|
/UVA/301 - Transportation.cpp
|
e8eaa6d07406643cdac6a5eeff1ba078e76fac79
|
[] |
no_license
|
ahmedelsaie/AlgorithmsProblems
|
dd8578e04590e71c13f7aa0cb02f77bea4599beb
|
acdfc86ef642c5249a15f59bcea10a31d7c58d0d
|
refs/heads/master
| 2021-09-17T11:23:48.711877
| 2018-06-26T01:07:16
| 2018-06-26T01:07:16
| 115,373,592
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,938
|
cpp
|
301 - Transportation.cpp
|
#include <stdio.h>
struct order
{
int start;
int end;
int passen;
};
int max(int x, int y);
int fn(int city, int curr_order, int left_passen, bool flag);
void bsort();
int people_arrive[25];
order orders[25];
int no_city, no_order, train_cap;
const int inf = 99999999;
int main()
{
bool flag = true;
for(int i = 0; i < 25; i++)
people_arrive[i] = 0;
while(true)
{
scanf("%d %d %d", &train_cap, &no_city, &no_order);
if(train_cap == 0 && no_city == 0 && no_order == 0)
break;
for(int i = 0; i < no_order; i++)
scanf("%d %d %d", &orders[i].start, &orders[i].end, &orders[i].passen);
bsort();
int ans = fn(0, 0, train_cap, true);
printf("%d\n", ans);
}
return 0;
}
int fn(int city, int curr_order, int left_passen, bool flag)
{
if(left_passen < 0)
return -1 * inf;
if(city == no_city || curr_order == no_order)
return 0;
if (flag)
left_passen += people_arrive[city];
int temp = -1 * inf;
int ret = -1 * inf;
if(orders[curr_order].start == city)
{
if(orders[curr_order + 1].start == city)
{
temp = fn(city, curr_order + 1, left_passen, false);
ret = max(temp, ret);
people_arrive[orders[curr_order].end] += orders[curr_order].passen;
temp = fn(city, curr_order + 1, left_passen - orders[curr_order].passen, false);
if(temp != -1 * inf)
temp += orders[curr_order].passen * (orders[curr_order].end - orders[curr_order].start);
ret = max(temp, ret);
people_arrive[orders[curr_order].end] -= orders[curr_order].passen;
}
else
{
temp = fn(city + 1, curr_order + 1, left_passen, true);
ret = max(temp, ret);
people_arrive[orders[curr_order].end] += orders[curr_order].passen;
temp = fn(city + 1, curr_order + 1, left_passen - orders[curr_order].passen, true);
if(temp != -1 * inf)
temp += orders[curr_order].passen * (orders[curr_order].end - orders[curr_order].start);
ret = max(temp, ret);
people_arrive[orders[curr_order].end] -= orders[curr_order].passen;
}
}
else
temp = fn(city + 1, curr_order, left_passen, true);
ret = max(ret, temp);
return ret;
}
int max(int x, int y)
{
if(x > y)
return x;
else
return y;
}
void bsort()
{
order swap;
bool flag;
for(int i = 0; i < no_order - 1; i++)
{
flag = true;
for(int j = 0; j < no_order - 1; j++)
if(orders[j].start > orders[j + 1].start)
{
swap = orders[j];
orders[j] = orders[j + 1];
orders[j + 1] = swap;
flag = false;
}
if(flag)
return;
}
return ;
}
|
d50114a2a98af3487753af46da6b2733a78eb588
|
29808df6c872a41f4580fa8e5d3edc838787faec
|
/taller Kevin Carano Bonilla- Daniel Andrés Pimiento/punto4.cpp
|
67f7cb1271dcc8352785c9b500597acfdfa4d681
|
[] |
no_license
|
DanielPimiento/Programicion-2
|
95626dbfe130f34816c5b878f391394c51d638b4
|
b92c56fcf27e29b6c585b6b7931d0503b0eadffd
|
refs/heads/master
| 2022-12-14T03:03:23.555164
| 2020-09-16T20:38:50
| 2020-09-16T20:38:50
| 288,859,933
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,867
|
cpp
|
punto4.cpp
|
#include <iostream>
using namespace std;
class Carro{
private:
string modelo;
string color;
string matricula;
int numeropuertas;
int numeropasajeros;
string aire;
public:
Carro(string _modelo, string _color, string _matricula, int _numeropuertas, int _numeropasajeros, string _aire);
Carro(string _modelo, string _color, string _matricula, string _aire);
void setmodelo(string _modelo);
string getmodelo();
void setcolor(string _color);
string getcolor();
void setmatricula(string _matricula);
string getmatricula();
void setnumeropuertas(int _numeropuertas);
int getnumeropuertas();
void setnumeropasajeros(int _numeropasajeros);
int getnumeropasajeros();
void setaire(string _aire);
string getaire();
void mostrarmodelo();
void mostrarcolor();
void mostrarmatricula();
void mostrarnumeropuertas();
void mostrarnumeropasajeros();
void mostraraire();
};
Carro:: Carro(string _modelo, string _color, string _matricula, string _aire){
modelo = _modelo;
color = _color;
matricula = _matricula;
aire = _aire;
}
Carro::Carro(string _modelo, string _color, string _matricula, int _numeropuertas, int _numeropasajeros, string _aire){
modelo = _modelo;
color = _color;
matricula = _matricula;
numeropuertas = _numeropuertas;
numeropasajeros = _numeropasajeros;
aire = _aire;
}
void Carro::setmodelo(string _modelo){
modelo = _modelo;
}
string Carro::getmodelo(){
return modelo;
}
void Carro::setcolor(string _color){
color = _color;
}
string Carro::getcolor(){
return color;
}
void Carro::setmatricula(string _matricula){
matricula = _matricula;
}
string Carro::getmatricula(){
return matricula;
}
void Carro::setnumeropuertas(int _numeropuertas){
numeropuertas = _numeropuertas;
}
int Carro::getnumeropuertas(){
return numeropuertas;
}
void Carro::setnumeropasajeros(int _numeropasajeros){
numeropasajeros = _numeropasajeros;
}
int Carro::getnumeropasajeros(){
return numeropasajeros;
}
void Carro::setaire(string _aire){
aire = _aire;
}
string Carro::getaire(){
return aire;
}
void Carro::mostrarmodelo(){
cout<<"el modelo del auto es "<<modelo<<endl;
}
void Carro::mostrarcolor(){
cout<<"el color del carro es: "<<color<<endl;
}
void Carro::mostrarmatricula(){
cout<<"la matricula del carro es: "<<matricula<<endl;
}
void Carro::mostrarnumeropuertas(){
cout<<"el numero de puertas en el carro es: "<<numeropuertas<<endl;
}
void Carro::mostrarnumeropasajeros(){
cout<<"el numero de pasajeros que puede llevar el carro es: "<<numeropasajeros<<endl;
}
void Carro::mostraraire(){
cout<<"el vehiculo posee aire acondicionado: "<<aire<<endl;
}
int main(int argc, char** argv) {
string a,b,c,f;
int d,e,g;
for(int i=0; i<1; i++){
cout<<"bienvenido al concesionario virtual utp"<<endl;
cout<<"porfavor ingrese los siguientes datos"<<endl;
cout<<"modelo del vehiculo"<<endl;
cin>>a;
cout<<"color del vehiculo"<<endl;
cin>>b;
cout<<"matricula del vehiculo"<<endl;
cin>>c;
cout<<"ingrese el numero de puertas que tiene el vehiculo"<<endl;
cin>>d;
cout<<"el numero de pasajeros que soporta el vehiculo"<<endl;
cin>>e;
cout<<"indique si el aire acondicionado funciona o no"<<endl;
cin>>f;
Carro carro1 = Carro(a,b,c,d,e,f);
carro1.setmodelo(a);
carro1.setcolor(b);
carro1.setmatricula(c);
carro1.setaire(f);
carro1.setnumeropasajeros(e);
carro1.setnumeropuertas(d);
carro1.mostrarmodelo();
carro1.mostrarcolor();
carro1.mostrarmatricula();
carro1.mostrarnumeropuertas();
carro1.mostrarnumeropasajeros();
carro1.mostraraire();
cout<<"si desea cambiar algo ingrese 1, de lo contrario presione cualquie boton"<<endl;
cin>>g;
if(g == 1){
i= i-1;
}
}
return 0;
}
|
c4ca435094916c37bcb4f81017d44907710de26c
|
3ca7dd1e368194aa2f884139d01f802073cbbe0d
|
/Codeforces/solved/450B/450B.cpp
|
dc69a42574d99969420de32a82b1fd81ab6d0b47
|
[] |
no_license
|
callistusystan/Algorithms-and-Data-Structures
|
07fd1a87ff3cfb07326f9f18513386a575359447
|
560e860ca1e546b7e7930d4e1bf2dd7c3acbcbc5
|
refs/heads/master
| 2023-02-17T17:29:21.678463
| 2023-02-11T09:12:40
| 2023-02-11T09:12:40
| 113,574,821
| 8
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 388
|
cpp
|
450B.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
ll MOD = 1e9+7;
ll mod(ll a) {
a %= MOD;
if (a < 0) a += MOD;
return a;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
ll X, Y; cin >> X >> Y;
ll N; cin >> N;
ll A[6] = {mod(X), mod(Y), mod(Y-X), mod(-X), mod(-Y), mod(X-Y)};
cout << A[(N-1)%6] << endl;
return 0;
}
|
1b7d9619d84bdc460f8541a2a9f5f6593eded45f
|
869d13aab1ca4bd50f7d471a424d4b52c128c35a
|
/Info student.cxx
|
3b2a6441fcbedbfcb14e883b672da5cf255fbc18
|
[] |
no_license
|
Aqiblone/linkedlist
|
7c1c50626f5a334ff524a6ff6d4f2c164cf2dfbf
|
293178031626868bcf4373023d09217a0c792c5e
|
refs/heads/main
| 2023-08-10T17:34:43.163436
| 2021-09-27T10:13:18
| 2021-09-27T10:13:18
| 410,833,923
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 993
|
cxx
|
Info student.cxx
|
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
struct Student
{
int rollnumber;
char name[100];
char phone[100];
float percentage;
struct Student *next;
}* head;
void insert(int rollnumber, char* name, char* phone, float percentage)
{
struct Student * student = (struct Student *) malloc(sizeof(struct Student));
student->rollnumber = rollnumber;
strcpy(student->name, name);
strcpy(student->phone, phone);
student->percentage = percentage;
student->next = NULL;
if(head==NULL){
// if head is NULL
// set student as the new head
head = student;
}
else{
// if list is not empty
// insert student in beginning of head
student->next = head;
head = student;
}
}
void search(int rollnumber)
{
struct Student * temp = head;
while(temp!=NULL){
if(temp->rollnumber==rollnumber){
printf("Roll Number: %d\n", temp->rollnumber);
printf("Name: %s\n", temp->name);
printf("Phone: %s\n", temp->phone);
printf("Percentage: %0.4f\n", temp->percentage);
return;
|
7a8ec4b8b495be09b857fdf0310ad1e115122318
|
3857b68582f103745205ddaaea4b9df4c02e332d
|
/aimc-read-only/src/Modules/Profile/ModuleScaler.cc
|
cc6e0d5a0cd294fc5999817fef79645518789683
|
[
"Apache-2.0"
] |
permissive
|
galv/carfac
|
598061d53a578e98228f1f482fba676295a0b999
|
58c5b36bd8eb583d98ba99c72815e43f10290636
|
refs/heads/master
| 2021-01-18T12:48:26.288366
| 2013-11-08T04:09:55
| 2013-11-08T04:09:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,588
|
cc
|
ModuleScaler.cc
|
// Copyright 2010, Thomas Walters
//
// AIM-C: A C++ implementation of the Auditory Image Model
// http://www.acousticscale.org/AIMC
//
// 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.
/*!
* \author Thomas Walters <tom@acousticscale.org>
* \date created 2010/02/22
* \version \$Id: ModuleScaler.cc 62 2010-07-22 04:14:20Z tomwalters $
*/
#include "Modules/Profile/ModuleScaler.h"
namespace aimc {
ModuleScaler::ModuleScaler(Parameters *params) : Module(params) {
module_description_ = "Scale each value by the channel centre frequency";
module_identifier_ = "scaler";
module_type_ = "profile";
module_version_ = "$Id: ModuleScaler.cc 62 2010-07-22 04:14:20Z tomwalters $";
}
ModuleScaler::~ModuleScaler() {
}
bool ModuleScaler::InitializeInternal(const SignalBank &input) {
// Copy the parameters of the input signal bank into internal variables, so
// that they can be checked later.
sample_rate_ = input.sample_rate();
buffer_length_ = input.buffer_length();
channel_count_ = input.channel_count();
output_.Initialize(channel_count_, buffer_length_, sample_rate_);
return true;
}
void ModuleScaler::ResetInternal() {
}
void ModuleScaler::Process(const SignalBank &input) {
// Check to see if the module has been initialized. If not, processing
// should not continue.
if (!initialized_) {
LOG_ERROR(_T("Module %s not initialized."), module_identifier_.c_str());
return;
}
// Check that ths input this time is the same as the input passed to
// Initialize()
if (buffer_length_ != input.buffer_length()
|| channel_count_ != input.channel_count()) {
LOG_ERROR(_T("Mismatch between input to Initialize() and input to "
"Process() in module %s."), module_identifier_.c_str());
return;
}
output_.set_start_time(input.start_time());
for (int ch = 0; ch < input.channel_count(); ++ch) {
float cf = input.centre_frequency(ch);
for (int i = 0; i < input.buffer_length(); ++i) {
output_.set_sample(ch, i, cf * input.sample(ch, i));
}
}
PushOutput();
}
} // namespace aimc
|
26cad023727592ae006059f81c73e701f4c3bb7d
|
3de02272025e9c2b7c741be20929eb304fd3301a
|
/codeforces/Educational Codeforces Round 81/E.cpp
|
e8d8a8ce35a0756e0b68e0df34277b89fbf0cd44
|
[] |
no_license
|
fanshixiong/Algorithm
|
4fd937799d537d4f9f91932d4c32e9a96b6d7ea7
|
ad65b163958329f781ba36d4294b32fae7a51520
|
refs/heads/master
| 2021-06-23T16:30:37.655248
| 2021-05-12T12:33:40
| 2021-05-12T12:33:40
| 222,182,342
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,059
|
cpp
|
E.cpp
|
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 3e5 + 10;
struct node{
int l, r;
ll laze, val;
} segment_tree[maxn << 2];
int n, p[maxn], id[maxn];
ll a[maxn], sum[maxn];
void push_Up(int rt){
segment_tree[rt].val = min(segment_tree[rt << 1].val, segment_tree[rt << 1 | 1].val);
}
void build(int rt, int l, int r){
segment_tree[rt].l = l;
segment_tree[rt].r = r;
if (l == r){
segment_tree[rt].val = sum[l];
segment_tree[rt].laze = 0ll;
return;
}
int mid = (l + r) >> 1;
build(rt << 1, l, mid);
build(rt << 1 | 1, mid + 1, r);
push_Up(rt);
}
void push_Down(int rt){
segment_tree[rt << 1 | 1].val += segment_tree[rt].laze;
segment_tree[rt << 1 | 1].laze += segment_tree[rt].laze;
segment_tree[rt << 1].val += segment_tree[rt].laze;
segment_tree[rt << 1].laze += segment_tree[rt].laze;
segment_tree[rt].laze = 0;
}
void update(int rt, int l, int r, int num){
if(segment_tree[rt].laze && l != r)
push_Down(rt);
if(segment_tree[rt].l >= l && segment_tree[rt].r <= r){
segment_tree[rt].val += num;
segment_tree[rt].laze += num;
return;
}
int mid = segment_tree[rt].l + segment_tree[rt].r >> 1;
if(r > mid){
update(rt << 1 | 1, l, r, num);
}
if(l <= mid){
update(rt << 1, l, r, num);
}
push_Up(rt);
}
int main(){
ios_base::sync_with_stdio(0);
cin >> n;
for (int i = 1; i <= n; i++){
cin >> p[i];
id[p[i]] = i;
}
for (int i = 1; i <= n; i++){
cin >> a[i];
sum[i] = sum[i - 1] + a[i];
}
ll ans = a[n];
build(1, 1, n - 1);
ans = min(ans, segment_tree[1].val);
int x;
for (int i = 1; i <= n; i++){
x = id[i];
if(x != n){
update(1, x, n - 1, -a[x]);
}
if(x != 1){
update(1, 1, x - 1, a[x]);
}
ans = min(ans, segment_tree[1].val);
//cout << ans << " ";
}
cout << ans << endl;
return 0;
}
|
37a99b93025efa6d74fa29a3a8941aa20b0ac585
|
0cb808cbc8087602107e0e4724f2d177c77a00f3
|
/Mess Around/Mess Around/File 1.cpp
|
14683d2ba30bc249b260ab269291dac091c0d6ec
|
[] |
no_license
|
mikecolistro/First_Year_C-Cplusplus
|
861eb965cc3b06f7ae0419701d13c9cb8fe5bb9a
|
e4898d8983e7373b9aadbc34d809e755cff96a0a
|
refs/heads/master
| 2021-01-10T06:39:29.737468
| 2015-05-28T04:02:35
| 2015-05-28T04:02:35
| 36,413,808
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 107
|
cpp
|
File 1.cpp
|
#include <stdio.h>
void main (void){
char c;
c = 1;
printf(" -----------\n / '%c' \n", c);
}
|
5fc46752457ac9d9a5c89bb09b0d2092711a2c80
|
32b85530d86994c6b6f62051b2ff6e04ef03510e
|
/test/test-asio-grpc.cpp
|
9f75d2e602c7fe8c22894303f44243de29715b4a
|
[
"Apache-2.0"
] |
permissive
|
stan-sack/asio-grpc
|
4bed53822df3dc31617deccbd595d573593bcdac
|
13fde46f7e847ca6618a255856c0571901399d27
|
refs/heads/master
| 2023-08-05T20:11:27.180152
| 2021-09-26T17:56:19
| 2021-09-26T17:56:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 25,803
|
cpp
|
test-asio-grpc.cpp
|
// Copyright 2021 Dennis Hezel
//
// 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 "agrpc/asioGrpc.hpp"
#include "protos/test.grpc.pb.h"
#include "utils/asioUtils.hpp"
#include "utils/grpcClientServerTest.hpp"
#include "utils/grpcContextTest.hpp"
#include <boost/asio/coroutine.hpp>
#include <boost/asio/post.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/asio/thread_pool.hpp>
#include <doctest/doctest.h>
#include <grpcpp/alarm.h>
#include <cstddef>
#include <optional>
#include <string_view>
#include <thread>
namespace test_asio_grpc
{
using namespace agrpc;
TEST_SUITE_BEGIN(ASIO_GRPC_TEST_CPP_VERSION* doctest::timeout(180.0));
TEST_CASE("GrpcExecutor fulfills Executor TS traits")
{
using Exec = agrpc::GrpcContext::executor_type;
CHECK(asio::execution::can_execute_v<std::add_const_t<Exec>, asio::execution::invocable_archetype>);
CHECK(asio::execution::is_executor_v<Exec>);
CHECK(asio::can_require_v<Exec, asio::execution::blocking_t::never_t>);
CHECK(asio::can_prefer_v<Exec, asio::execution::blocking_t::possibly_t>);
CHECK(asio::can_prefer_v<Exec, asio::execution::relationship_t::fork_t>);
CHECK(asio::can_prefer_v<Exec, asio::execution::relationship_t::continuation_t>);
CHECK(asio::can_prefer_v<Exec, asio::execution::outstanding_work_t::tracked_t>);
CHECK(asio::can_prefer_v<Exec, asio::execution::outstanding_work_t::untracked_t>);
CHECK(asio::can_prefer_v<Exec, asio::execution::allocator_t<agrpc::detail::pmr::polymorphic_allocator<std::byte>>>);
CHECK(asio::can_query_v<Exec, asio::execution::blocking_t>);
CHECK(asio::can_query_v<Exec, asio::execution::relationship_t>);
CHECK(asio::can_query_v<Exec, asio::execution::outstanding_work_t>);
CHECK(asio::can_query_v<Exec, asio::execution::mapping_t>);
CHECK(asio::can_query_v<Exec, asio::execution::allocator_t<void>>);
CHECK(asio::can_query_v<Exec, asio::execution::context_t>);
CHECK(std::is_constructible_v<asio::any_io_executor, Exec>);
agrpc::GrpcContext grpc_context{std::make_unique<grpc::CompletionQueue>()};
auto executor = grpc_context.get_executor();
CHECK_EQ(asio::execution::blocking.possibly,
asio::query(asio::require(executor, asio::execution::blocking.possibly), asio::execution::blocking));
CHECK_EQ(
asio::execution::relationship.continuation,
asio::query(asio::prefer(executor, asio::execution::relationship.continuation), asio::execution::relationship));
CHECK_EQ(asio::execution::outstanding_work.tracked,
asio::query(asio::prefer(executor, asio::execution::outstanding_work.tracked),
asio::execution::outstanding_work));
}
TEST_CASE("GrpcExecutor is mostly trivial")
{
CHECK(std::is_trivially_copy_constructible_v<agrpc::GrpcExecutor>);
CHECK(std::is_trivially_move_constructible_v<agrpc::GrpcExecutor>);
CHECK(std::is_trivially_destructible_v<agrpc::GrpcExecutor>);
CHECK(std::is_trivially_copy_assignable_v<agrpc::GrpcExecutor>);
CHECK(std::is_trivially_move_assignable_v<agrpc::GrpcExecutor>);
CHECK_EQ(sizeof(void*), sizeof(agrpc::GrpcExecutor));
}
TEST_CASE("Work tracking GrpcExecutor constructor and assignment")
{
agrpc::GrpcContext grpc_context{std::make_unique<grpc::CompletionQueue>()};
auto ex = asio::require(grpc_context.get_executor(), asio::execution::outstanding_work.tracked,
asio::execution::allocator(agrpc::detail::pmr::polymorphic_allocator<std::byte>()));
const auto ex1{ex};
auto ex2{ex};
auto ex3{std::move(ex)};
ex2 = ex1;
ex2 = std::move(ex3);
}
TEST_CASE_FIXTURE(test::GrpcContextTest, "asio::spawn an Alarm and yield its wait")
{
bool ok = false;
asio::spawn(asio::bind_executor(get_work_tracking_executor(), [] {}),
[&](auto&& yield)
{
grpc::Alarm alarm;
ok = agrpc::wait(alarm, test::ten_milliseconds_from_now(), yield);
});
grpc_context.run();
CHECK(ok);
}
TEST_CASE_FIXTURE(test::GrpcContextTest, "asio::post a asio::steady_timer")
{
std::optional<boost::system::error_code> error_code;
auto guard = asio::make_work_guard(grpc_context);
asio::steady_timer timer{get_executor()};
asio::post(get_executor(),
[&]
{
timer.expires_after(std::chrono::milliseconds(10));
timer.async_wait(
[&](const boost::system::error_code& ec)
{
error_code.emplace(ec);
guard.reset();
});
});
grpc_context.run();
CHECK_EQ(boost::system::error_code{}, error_code);
}
TEST_CASE_FIXTURE(test::GrpcContextTest, "asio::spawn with yield_context")
{
bool ok = false;
std::optional<asio::executor_work_guard<agrpc::GrpcExecutor>> guard;
asio::spawn(get_executor(),
[&](asio::yield_context yield)
{
grpc::Alarm alarm;
ok = agrpc::wait(alarm, test::ten_milliseconds_from_now(), yield);
guard.reset();
});
guard.emplace(asio::make_work_guard(grpc_context));
grpc_context.run();
CHECK(ok);
}
TEST_CASE_FIXTURE(test::GrpcContextTest, "post from multiple threads")
{
static constexpr auto THREAD_COUNT = 32;
std::atomic_int counter{};
asio::thread_pool pool{THREAD_COUNT};
auto guard = asio::make_work_guard(grpc_context);
for (size_t i = 0; i < THREAD_COUNT; ++i)
{
asio::post(pool,
[&]
{
asio::post(grpc_context,
[&]
{
if (++counter == THREAD_COUNT)
{
guard.reset();
}
});
});
}
asio::post(pool,
[&]
{
grpc_context.run();
});
pool.join();
CHECK_EQ(THREAD_COUNT, counter);
}
TEST_CASE_FIXTURE(test::GrpcContextTest, "post/execute with allocator")
{
SUBCASE("asio::post")
{
asio::post(grpc_context,
test::HandlerWithAssociatedAllocator{
[] {}, agrpc::detail::pmr::polymorphic_allocator<std::byte>(&resource)});
}
SUBCASE("asio::execute before grpc_context.run()")
{
get_pmr_executor().execute([] {});
}
SUBCASE("asio::execute after grpc_context.run() from same thread")
{
asio::post(grpc_context,
[&, exec = get_work_tracking_pmr_executor()]
{
exec.execute([] {});
});
}
SUBCASE("agrpc::wait")
{
asio::execution::execute(get_executor(),
[&, executor = get_work_tracking_pmr_executor()]() mutable
{
auto alarm = std::make_shared<grpc::Alarm>();
auto& alarm_ref = *alarm;
agrpc::wait(alarm_ref, test::ten_milliseconds_from_now(),
asio::bind_executor(std::move(executor),
[a = std::move(alarm)](bool ok)
{
CHECK(ok);
}));
});
}
grpc_context.run();
CHECK(std::any_of(buffer.begin(), buffer.end(),
[](auto&& value)
{
return value != std::byte{};
}));
}
TEST_CASE_FIXTURE(test::GrpcContextTest, "dispatch with allocator")
{
asio::post(grpc_context,
[&, exec = get_work_tracking_executor()]
{
asio::dispatch(get_pmr_executor(), [] {});
});
grpc_context.run();
CHECK(std::all_of(buffer.begin(), buffer.end(),
[](auto&& value)
{
return value == std::byte{};
}));
}
template <class Function>
struct Coro : asio::coroutine
{
using executor_type =
asio::require_result<agrpc::GrpcContext::executor_type, asio::execution::outstanding_work_t::tracked_t>::type;
executor_type executor;
Function function;
Coro(agrpc::GrpcContext& grpc_context, Function&& f)
: executor(asio::require(grpc_context.get_executor(), asio::execution::outstanding_work.tracked)),
function(std::forward<Function>(f))
{
}
void operator()(bool ok) { function(ok, this); }
executor_type get_executor() const noexcept { return executor; }
};
TEST_CASE_FIXTURE(test::GrpcClientServerTest, "unary stackless coroutine")
{
grpc::ServerAsyncResponseWriter<test::v1::Response> writer{&server_context};
test::v1::Request server_request;
test::v1::Response server_response;
auto server_loop = [&](bool ok, auto* coro) mutable
{
BOOST_ASIO_CORO_REENTER(*coro)
{
BOOST_ASIO_CORO_YIELD
agrpc::request(&test::v1::Test::AsyncService::RequestUnary, service, server_context, server_request, writer,
*coro);
CHECK(ok);
CHECK_EQ(42, server_request.integer());
server_response.set_integer(21);
BOOST_ASIO_CORO_YIELD agrpc::finish(writer, server_response, grpc::Status::OK, *coro);
CHECK(ok);
}
};
std::thread server_thread(
[&, server_coro = Coro{grpc_context, std::move(server_loop)}]() mutable
{
server_coro(true);
});
test::v1::Request client_request;
client_request.set_integer(42);
test::v1::Response client_response;
grpc::Status status;
std::unique_ptr<grpc::ClientAsyncResponseReader<test::v1::Response>> reader;
auto client_loop = [&](bool ok, auto* coro) mutable
{
BOOST_ASIO_CORO_REENTER(*coro)
{
reader = stub->AsyncUnary(&client_context, client_request, agrpc::get_completion_queue(*coro));
BOOST_ASIO_CORO_YIELD agrpc::finish(*reader, client_response, status, *coro);
CHECK(ok);
CHECK(status.ok());
CHECK_EQ(21, client_response.integer());
}
};
std::thread client_thread(
[&, client_coro = Coro{grpc_context, std::move(client_loop)}]() mutable
{
client_coro(true);
});
grpc_context.run();
server_thread.join();
client_thread.join();
}
TEST_CASE_FIXTURE(test::GrpcClientServerTest, "yield_context server streaming")
{
bool use_write_and_finish{false};
SUBCASE("server write_and_finish") { use_write_and_finish = true; }
bool use_client_convenience{false};
SUBCASE("client use convenience") { use_client_convenience = true; }
asio::spawn(get_work_tracking_executor(),
[&](asio::yield_context yield)
{
test::v1::Request request;
grpc::ServerAsyncWriter<test::v1::Response> writer{&server_context};
CHECK(agrpc::request(&test::v1::Test::AsyncService::RequestServerStreaming, service, server_context,
request, writer, yield));
CHECK(agrpc::send_initial_metadata(writer, yield));
CHECK_EQ(42, request.integer());
test::v1::Response response;
response.set_integer(21);
if (use_write_and_finish)
{
CHECK(agrpc::write_and_finish(writer, response, {}, grpc::Status::OK, yield));
}
else
{
CHECK(agrpc::write(writer, response, yield));
CHECK(agrpc::finish(writer, grpc::Status::OK, yield));
}
});
asio::spawn(get_work_tracking_executor(),
[&](asio::yield_context yield)
{
test::v1::Request request;
request.set_integer(42);
auto [reader, ok] = [&]
{
if (use_client_convenience)
{
return agrpc::request(&test::v1::Test::Stub::AsyncServerStreaming, *stub, client_context,
request, yield);
}
std::unique_ptr<grpc::ClientAsyncReader<test::v1::Response>> reader;
bool ok = agrpc::request(&test::v1::Test::Stub::AsyncServerStreaming, *stub, client_context,
request, reader, yield);
return std::pair{std::move(reader), ok};
}();
CHECK(ok);
CHECK(agrpc::read_initial_metadata(*reader, yield));
test::v1::Response response;
CHECK(agrpc::read(*reader, response, yield));
grpc::Status status;
CHECK(agrpc::finish(*reader, status, yield));
CHECK(status.ok());
CHECK_EQ(21, response.integer());
});
grpc_context.run();
}
TEST_CASE_FIXTURE(test::GrpcClientServerTest, "yield_context client streaming")
{
bool use_client_convenience{};
SUBCASE("client use convenience") { use_client_convenience = true; }
SUBCASE("client do not use convenience") { use_client_convenience = false; }
asio::spawn(get_work_tracking_executor(),
[&](asio::yield_context yield)
{
grpc::ServerAsyncReader<test::v1::Response, test::v1::Request> reader{&server_context};
CHECK(agrpc::request(&test::v1::Test::AsyncService::RequestClientStreaming, service, server_context,
reader, yield));
CHECK(agrpc::send_initial_metadata(reader, yield));
test::v1::Request request;
CHECK(agrpc::read(reader, request, yield));
CHECK_EQ(42, request.integer());
test::v1::Response response;
response.set_integer(21);
CHECK(agrpc::finish(reader, response, grpc::Status::OK, yield));
});
asio::spawn(get_work_tracking_executor(),
[&](asio::yield_context yield)
{
test::v1::Response response;
auto [writer, ok] = [&]
{
if (use_client_convenience)
{
return agrpc::request(&test::v1::Test::Stub::AsyncClientStreaming, *stub, client_context,
response, yield);
}
std::unique_ptr<grpc::ClientAsyncWriter<test::v1::Request>> writer;
bool ok = agrpc::request(&test::v1::Test::Stub::AsyncClientStreaming, *stub, client_context,
writer, response, yield);
return std::pair{std::move(writer), ok};
}();
CHECK(ok);
CHECK(agrpc::read_initial_metadata(*writer, yield));
test::v1::Request request;
request.set_integer(42);
CHECK(agrpc::write(*writer, request, yield));
CHECK(agrpc::writes_done(*writer, yield));
grpc::Status status;
CHECK(agrpc::finish(*writer, status, yield));
CHECK(status.ok());
CHECK_EQ(21, response.integer());
});
grpc_context.run();
}
TEST_CASE_FIXTURE(test::GrpcClientServerTest, "yield_context unary")
{
bool use_finish_with_error;
SUBCASE("server finish_with_error") { use_finish_with_error = true; }
SUBCASE("server finish with OK") { use_finish_with_error = false; }
asio::spawn(get_work_tracking_executor(),
[&](asio::yield_context yield)
{
test::v1::Request request;
grpc::ServerAsyncResponseWriter<test::v1::Response> writer{&server_context};
CHECK(agrpc::request(&test::v1::Test::AsyncService::RequestUnary, service, server_context, request,
writer, yield));
CHECK(agrpc::send_initial_metadata(writer, yield));
CHECK_EQ(42, request.integer());
test::v1::Response response;
response.set_integer(21);
if (use_finish_with_error)
{
CHECK(agrpc::finish_with_error(writer, grpc::Status::CANCELLED, yield));
}
else
{
CHECK(agrpc::finish(writer, response, grpc::Status::OK, yield));
}
});
asio::spawn(get_work_tracking_executor(),
[&](asio::yield_context yield)
{
test::v1::Request request;
request.set_integer(42);
auto reader =
stub->AsyncUnary(&client_context, request, agrpc::get_completion_queue(get_executor()));
CHECK(agrpc::read_initial_metadata(*reader, yield));
test::v1::Response response;
grpc::Status status;
CHECK(agrpc::finish(*reader, response, status, yield));
if (use_finish_with_error)
{
CHECK_EQ(grpc::StatusCode::CANCELLED, status.error_code());
}
else
{
CHECK(status.ok());
CHECK_EQ(21, response.integer());
}
});
grpc_context.run();
}
TEST_CASE_FIXTURE(test::GrpcClientServerTest, "yield_context bidirectional streaming")
{
bool use_write_and_finish{false};
SUBCASE("server write_and_finish") { use_write_and_finish = true; }
bool use_client_convenience{false};
SUBCASE("client use convenience") { use_client_convenience = true; }
asio::spawn(get_work_tracking_executor(),
[&](asio::yield_context yield)
{
grpc::ServerAsyncReaderWriter<test::v1::Response, test::v1::Request> reader_writer{&server_context};
CHECK(agrpc::request(&test::v1::Test::AsyncService::RequestBidirectionalStreaming, service,
server_context, reader_writer, yield));
CHECK(agrpc::send_initial_metadata(reader_writer, yield));
test::v1::Request request;
CHECK(agrpc::read(reader_writer, request, yield));
CHECK_EQ(42, request.integer());
test::v1::Response response;
response.set_integer(21);
if (use_write_and_finish)
{
CHECK(agrpc::write_and_finish(reader_writer, response, {}, grpc::Status::OK, yield));
}
else
{
CHECK(agrpc::write(reader_writer, response, yield));
CHECK(agrpc::finish(reader_writer, grpc::Status::OK, yield));
}
});
asio::spawn(
get_work_tracking_executor(),
[&](asio::yield_context yield)
{
auto [reader_writer, ok] = [&]
{
if (use_client_convenience)
{
return agrpc::request(&test::v1::Test::Stub::AsyncBidirectionalStreaming, *stub, client_context,
yield);
}
std::unique_ptr<grpc::ClientAsyncReaderWriter<test::v1::Request, test::v1::Response>> reader_writer;
bool ok = agrpc::request(&test::v1::Test::Stub::AsyncBidirectionalStreaming, *stub, client_context,
reader_writer, yield);
return std::pair{std::move(reader_writer), ok};
}();
CHECK(ok);
CHECK(agrpc::read_initial_metadata(*reader_writer, yield));
test::v1::Request request;
request.set_integer(42);
CHECK(agrpc::write(*reader_writer, request, yield));
CHECK(agrpc::writes_done(*reader_writer, yield));
test::v1::Response response;
CHECK(agrpc::read(*reader_writer, response, yield));
grpc::Status status;
CHECK(agrpc::finish(*reader_writer, status, yield));
CHECK(status.ok());
CHECK_EQ(21, response.integer());
});
grpc_context.run();
}
struct GrpcRepeatedlyRequestTest : test::GrpcClientServerTest
{
template <class RPC, class Service, class ServerFunction, class ClientFunction>
auto test(RPC rpc, Service& service, ServerFunction server_function, ClientFunction client_function)
{
agrpc::repeatedly_request(
rpc, service, test::RpcSpawner{asio::bind_executor(this->get_executor(), std::move(server_function))});
asio::spawn(get_work_tracking_executor(), std::move(client_function));
}
};
TEST_CASE_FIXTURE(GrpcRepeatedlyRequestTest, "yield_context repeatedly_request unary")
{
bool is_shutdown{false};
auto request_count{0};
this->test(
&test::v1::Test::AsyncService::RequestUnary, service,
[&](grpc::ServerContext&, test::v1::Request& request,
grpc::ServerAsyncResponseWriter<test::v1::Response> writer, asio::yield_context yield)
{
CHECK_EQ(42, request.integer());
test::v1::Response response;
response.set_integer(21);
++request_count;
if (request_count > 3)
{
is_shutdown = true;
}
CHECK(agrpc::finish(writer, response, grpc::Status::OK, yield));
},
[&](asio::yield_context yield)
{
while (!is_shutdown)
{
test::v1::Request request;
request.set_integer(42);
grpc::ClientContext new_client_context;
auto reader =
stub->AsyncUnary(&new_client_context, request, agrpc::get_completion_queue(get_executor()));
test::v1::Response response;
grpc::Status status;
CHECK(agrpc::finish(*reader, response, status, yield));
CHECK(status.ok());
CHECK_EQ(21, response.integer());
}
});
grpc_context.run();
CHECK_EQ(4, request_count);
}
TEST_CASE_FIXTURE(GrpcRepeatedlyRequestTest, "yield_context repeatedly_request client streaming")
{
bool is_shutdown{false};
auto request_count{0};
this->test(
&test::v1::Test::AsyncService::RequestClientStreaming, service,
[&](grpc::ServerContext&, grpc::ServerAsyncReader<test::v1::Response, test::v1::Request> reader,
asio::yield_context yield)
{
test::v1::Request request;
CHECK(agrpc::read(reader, request, yield));
CHECK_EQ(42, request.integer());
test::v1::Response response;
response.set_integer(21);
++request_count;
if (request_count > 3)
{
is_shutdown = true;
}
CHECK(agrpc::finish(reader, response, grpc::Status::OK, yield));
},
[&](asio::yield_context yield)
{
while (!is_shutdown)
{
test::v1::Response response;
grpc::ClientContext new_client_context;
auto [writer, ok] = agrpc::request(&test::v1::Test::Stub::AsyncClientStreaming, *stub,
new_client_context, response, yield);
CHECK(ok);
test::v1::Request request;
request.set_integer(42);
CHECK(agrpc::write(*writer, request, yield));
CHECK(agrpc::writes_done(*writer, yield));
grpc::Status status;
CHECK(agrpc::finish(*writer, status, yield));
CHECK(status.ok());
CHECK_EQ(21, response.integer());
}
});
grpc_context.run();
CHECK_EQ(4, request_count);
}
TEST_SUITE_END();
} // namespace test_asio_grpc
|
9bde661d135770aeca4e5997a959ef0d9957359c
|
dff8a221638932704df714b30df53de003342571
|
/code_modified_20150323/6/11.cpp
|
43e244f504eb4a2434a691ac2549b312e1617dd9
|
[] |
no_license
|
DevinChang/cpp
|
1327da268cbbde4981c055c2e98301d63e9ca46b
|
f35ee6f7b2d9217bd2d40db55a697330aeffc7e8
|
refs/heads/master
| 2021-01-20T13:55:55.399888
| 2017-05-18T08:01:15
| 2017-05-18T08:01:15
| 90,538,499
| 3
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 246
|
cpp
|
11.cpp
|
#include <iostream>
using namespace std;
void reset(int &i)
{
i = 0;
}
int main()
{
int num = 10;
cout << "ÖØÖÃǰ£ºnum = " << num << endl;
reset(num);
cout << "ÖØÖúó£ºnum = " << num << endl;
return 0;
}
|
aa95a018ec1c34276db6daf0b65535b5c0e566f2
|
1ae9bf1c1c55d3b1a7f293577cc87ce864fdd482
|
/src/tracker/mswindowsbgrunner.h
|
91ff4b79b8220b5f2966edef83a35ed5c0757714
|
[
"Beerware",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
loganek/workertracker
|
2c2d462d911fd44bd7fee6b13f25c34feed2d991
|
b4e66f02e6a7cdf91e5f0a418cabbd23ac636f2e
|
refs/heads/master
| 2021-01-12T11:45:28.329817
| 2017-01-10T20:26:44
| 2017-01-10T20:26:44
| 72,291,489
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,016
|
h
|
mswindowsbgrunner.h
|
/*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <marcin.kolny@gmail.com> wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return. Marcin Kolny
* ----------------------------------------------------------------------------
*/
#ifndef MSWINDOWSBGRUNNER_H
#define MSWINDOWSBGRUNNER_H
#include "backgroundrunner.h"
#include <string>
namespace WT {
class MSWindowsBGRunner : public BackgroundRunner
{
std::string log_file_name;
static RegistrarSingle<MSWindowsBGRunner> registrar;
std::string MSWindowsBGRunner::get_current_process_name();
public:
MSWindowsBGRunner(const std::string &log_file_name);
int move_to_background() override;
int kill_process() override;
void register_kill_method(void(*handler)(int)) override;
};
}
#endif // MSWINDOWSBGRUNNER_H
|
8ad68261481c40d6f17ce2b9042a212017dee374
|
4707400f71b9004b47380581a76b279329a160e3
|
/Sprawdzarka UAM/Zrobione zadania/Wielomian.cpp
|
47dc0ca22e1f8e7b944a0e8cae00c15e2eca3fa3
|
[] |
no_license
|
swacisko/CODES
|
e5c73594374608ee8b3688f4e51e5ca4867d79f9
|
5e492c9711c93be493c7952bb08e30f9ad7a57b6
|
refs/heads/master
| 2021-01-19T00:37:03.262832
| 2017-01-09T21:00:04
| 2017-01-09T21:00:04
| 73,085,634
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 717
|
cpp
|
Wielomian.cpp
|
#include<iostream>
using namespace std;
int pot(int a, int b)
{
int suma=1;
for(int i=0; i<b; i++)
{
suma*=a;
}
return suma;
}
int main()
{
int n, m, k, R, s_wsp=0, t, tab[11]={0};
cin>>t;
while(t--)
{
cin>>n>>k>>m>>R;
for(int k=0; k<=n; k++)
{
if(k==0) { tab[0]=R%m; s_wsp=tab[0]; }
if(k>0)
{
tab[k]= ((R-s_wsp)%(pot(m,k+1)))/pot(m,k) ;
s_wsp+=tab[k]*pot(m,k);
}
}
for(int k=n; k>=0; k--)
{
if(k<n)
{
if(k>0)
{
cout<<"+"<<tab[k]<<"x^"<<k;
}
else cout<<"+"<<tab[k];
}
else cout<<tab[k]<<"x^"<<k;
}
cout<<endl;
}
return 0;
}
|
012697740628af671287abd2f06d74697b5dc242
|
e71e72b23a2f8645f6c2c97334a46e9fe47ce2b2
|
/5.3/sum2arrays.cpp
|
230d07c0e4dde817d2a2d6d4bcfef81ffc70aebc
|
[] |
no_license
|
puffikru/algorithms_base
|
710052b77cd53b4690dd964d796c1eb0f6a9297e
|
8815d8fdb79661614b3fae512bccb57c1b17f3c6
|
refs/heads/master
| 2022-07-03T02:39:36.713971
| 2020-05-10T19:20:32
| 2020-05-10T19:20:32
| 255,335,109
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 547
|
cpp
|
sum2arrays.cpp
|
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m, sum;
cin >> n >> m >> sum;
vector<int> a(n);
vector<int> b(m);
for (int& x : a) {
cin >> x;
}
for (int& x : b) {
cin >> x;
}
int j = b.size() - 1;
for (size_t i = 0; i < a.size(); ++i) {
while (j >= 0 && a[i] + b[j] > sum) {
--j;
}
if (j >= 0 && a[i] + b[j] == sum) {
cout << i + 1 << ' ' << j + 1;
return 0;
}
}
cout << "0 0";
}
|
a9885edcc60c5bcdc8cd4d9cc1f5651a7642afd2
|
f76b7fa7eb3b4871e4dfb8d3cf9cf151a0938c74
|
/command.cpp
|
b440abdbdffe5999051eeb699da2ca075df87a9b
|
[] |
no_license
|
peterkvt80/vbit2
|
7056dec56a5a9dfd0cce02c25bb5d95bb4d37a35
|
6ec1769bc0a229059320ce7e6d0da6688136a97b
|
refs/heads/master
| 2023-08-04T18:05:13.331453
| 2023-07-25T18:26:05
| 2023-07-25T18:26:05
| 68,154,722
| 128
| 15
| null | 2021-10-06T18:21:10
| 2016-09-13T23:09:21
|
C++
|
UTF-8
|
C++
| false
| false
| 4,171
|
cpp
|
command.cpp
|
/**
***************************************************************************
* Description : Class for Newfor subtitles
* Compiler : C++
*
* Copyright (C) 2017, Peter Kwan
*
* Permission to use, copy, modify, and distribute this software
* and its documentation for any purpose and without fee is hereby
* granted, provided that the above copyright notice appear in all
* copies and that both that the copyright notice and this
* permission notice and warranty disclaimer appear in supporting
* documentation, and that the name of the author not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
*
* The author disclaims all warranties with regard to this
* software, including all implied warranties of merchantability
* and fitness. In no event shall the author be liable for any
* special, indirect or consequential damages or any damages
* whatsoever resulting from loss of use, data or profits, whether
* in an action of contract, negligence or other tortious action,
* arising out of or in connection with the use or performance of
* this software.
***************************************************************************
* The command processor accepts commands over TCP.
* The primary use is to accept Newfor subtitles
* but other inserter commands could be done this way
* It arbitrarily uses port 5570 and accepts Newfor commands
**/
#include "command.h"
using namespace vbit;
using namespace ttx;
Command::Command(Configure *configure, PacketSubtitle* subtitle=nullptr, PageList *pageList=nullptr) :
_portNumber(configure->GetCommandPort()),
_client(subtitle, pageList)
{
// Constructor
// Start a listener thread
}
Command::~Command()
{
//destructor
}
void Command::DieWithError(std::string errorMessage)
{
perror(errorMessage.c_str());
exit(1);
}
void Command::run()
{
std::cerr << "[Command::run] Newfor subtitle listener started\n";
int serverSock; /* Socket descriptor for server */
int clientSock; /* Socket descriptor for client */
struct sockaddr_in echoServAddr; /* Local address */
struct sockaddr_in echoClntAddr; /* Client address */
unsigned short echoServPort; /* Server port */
#ifdef WIN32
int clntLen; /* needs to be signed int for winsock */
WSADATA wsaData;
int iResult;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0)
{
DieWithError("WSAStartup failed");
}
#else
unsigned int clntLen; /* Length of client address data structure */
#endif
echoServPort = _portNumber; /* This is the local port */
// System initialisations
/* Construct local address structure */
std::memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */
echoServAddr.sin_family = AF_INET; /* Internet address family */
echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
echoServAddr.sin_port = htons(echoServPort); /* Local port */
/* Create socket for incoming connections */
if ((serverSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithError("socket() failed\n");
/* Bind to the local address */
if (bind(serverSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
DieWithError("bind() failed");
/* Mark the socket so it will listen for incoming connections */
if (listen(serverSock, MAXPENDING) < 0)
DieWithError("listen() failed");
/* Set the size of the in-out parameter */
clntLen = sizeof(echoClntAddr);
while(1)
{
std::cerr << "[Command::run] Ready for a client to connect\n";
/* Wait for a client to connect */
if ((clientSock = accept(serverSock, (struct sockaddr *) &echoClntAddr, &clntLen)) < 0)
DieWithError("accept() failed");
std::cerr << "[Command::run] Connected\n";
/* clientSock is connected to a client! */
_client.Handler(clientSock);
}
}
|
b436f3f6e4f9a6585156567bd28153a814de3081
|
f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab
|
/games/eboard/patches/patch-cimg.cc
|
1a553ef002a9c871a5acf25aca52e06b1b1b9543
|
[] |
no_license
|
jsonn/pkgsrc
|
fb34c4a6a2d350e8e415f3c4955d4989fcd86881
|
c1514b5f4a3726d90e30aa16b0c209adbc276d17
|
refs/heads/trunk
| 2021-01-24T09:10:01.038867
| 2017-07-07T15:49:43
| 2017-07-07T15:49:43
| 2,095,004
| 106
| 47
| null | 2016-09-19T09:26:01
| 2011-07-23T23:49:04
|
Makefile
|
UTF-8
|
C++
| false
| false
| 880
|
cc
|
patch-cimg.cc
|
$NetBSD: patch-cimg.cc,v 1.2 2012/08/12 21:38:11 wiz Exp $
Fix build with png-1.5.
https://sourceforge.net/tracker/?func=detail&aid=3515237&group_id=11164&atid=111164
--- cimg.cc.orig 2007-05-23 18:57:45.000000000 +0000
+++ cimg.cc
@@ -95,16 +95,16 @@ CImg::CImg(const char *filename) {
ct == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(pngp);
- alloc(pngp->width,pngp->height);
+ alloc(png_get_image_width(pngp, infp),png_get_image_height(pngp, infp));
if (!ok) { fclose(f); return; }
ok = 0;
- rp = (png_bytep *) malloc(sizeof(png_bytep) * (pngp->height));
+ rp = (png_bytep *) malloc(sizeof(png_bytep) * (png_get_image_height(pngp, infp)));
if (rp==NULL) {
fclose(f); return;
}
- for(i=0;i<pngp->height;i++) {
+ for(i=0;i<png_get_image_height(pngp, infp);i++) {
png_read_row(pngp, (png_bytep) (&data[i*rowlen]), NULL);
}
|
8e648f452c64398ca179d0c4a05e53b2f0694be0
|
24876b26db45aeb55a5c6e91e2d911c907b1820a
|
/project2D/Ground.cpp
|
9b74eb9dd0d29bc2298a38cdbb7d9a0a0117d3db
|
[
"MIT"
] |
permissive
|
JamesCreaton/BasicGeneticAlgorithm
|
ad5c0166c9e3e49bde65e6ee1ec89c18e46cd8d7
|
057c2283101625948867747b8e8cd01712b0a952
|
refs/heads/master
| 2021-01-02T23:09:19.053373
| 2017-08-06T09:26:46
| 2017-08-06T09:26:46
| 99,475,849
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 744
|
cpp
|
Ground.cpp
|
#include "Ground.h"
Ground::Ground()
{
}
Ground::~Ground()
{
}
void Ground::init(b2World * world, const glm::vec2 & position, const glm::vec2 & dimensions)
{
m_dimensions = dimensions;
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set(position.x, position.y);
m_body = world->CreateBody(&bodyDef);
b2PolygonShape boxShape;
boxShape.SetAsBox(dimensions.x / 2, dimensions.y / 2);
b2FixtureDef fixtureDef;
fixtureDef.shape = &boxShape;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
m_fixture = m_body->CreateFixture(&fixtureDef);
}
void Ground::Draw(aie::Renderer2D * renderer)
{
renderer->drawSprite(nullptr, m_body->GetPosition().x, m_body->GetPosition().y,
m_dimensions.x, m_dimensions.y);
}
|
e4ca98380f39f7e7d8a632ffce3ca8808c2018d1
|
a18fb77abe542d131435ce197574c9a011203f12
|
/src/V4L2Manager.cpp
|
248a6813f74fe2d921c696b4348fed67a69ae5df
|
[] |
no_license
|
okinp/DeviceListing
|
8c4aaf0667f668c4f34e6671abcb47b1ef82f670
|
ec2402b0864d059f21798465c60becc543828f80
|
refs/heads/master
| 2020-05-20T13:47:38.635933
| 2014-05-24T09:13:38
| 2014-05-24T09:13:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,284
|
cpp
|
V4L2Manager.cpp
|
//
// V4L2Manager.cpp
// DeviceListing
//
// Created by Nikolas Psaroudakis on 5/12/14.
//
//
#include "V4L2Manager.h"
#include <boost/filesystem.hpp>
std::vector< std::string > V4L2Manager::getVideoDevices()
{
boost::filesystem::directory_iterator iterator(std::string("/dev"));
std::vector< std::string > devices;
for(; iterator != boost::filesystem::directory_iterator(); ++iterator)
{
std::string fileName = iterator->path().filename().string();
if (fileName.find("video") != std::string::npos) {
devices.push_back("/dev/"+fileName);
}
}
return devices;
}
bool V4L2Manager::checkSucceed( int er )
{
if ( er == -1 )
return false;
return true;
}
int V4L2Manager::openDevice( const string& dev )
{
return open(dev.c_str(), O_RDONLY);
}
int V4L2Manager::getWidth( const string& dev )
{
int fd = openDevice(dev);
int minWidth = 0;
// if ( checkSucceed(fd) )
// {
// struct video_capability video_cap;
// if ( checkSucceed(ioctl( fd, VIDIOCGCAP, &video_cap )))
// {
// minWidth = video_cap.minwidth;
// }
// }
close(fd);
return minWidth;
}
int V4L2Manager::getHeight( const string& dev )
{
int fd = openDevice(dev);
int minHeight = 0;
// if ( checkSucceed(fd) )
// {
// struct video_capability video_cap;
// if ( checkSucceed(ioctl( fd, VIDIOCGCAP, &video_cap )))
// {
// minHeight = video_cap.minheight;
// }
// }
close(fd);
return minHeight;
}
unsigned char * V4L2Manager::getPixels(const string& dev)
{
return nullptr;
}
int V4L2Manager::print_caps(int fd)
{
struct v4l2_capability caps = {};
if (-1 == V4L2Manager::xioctl(fd, VIDIOC_QUERYCAP, &caps))
{
perror("Querying Capabilities");
return 1;
}
printf( "Driver Caps:\n"
" Driver: \"%s\"\n"
" Card: \"%s\"\n"
" Bus: \"%s\"\n"
" Version: %d.%d\n"
" Capabilities: %08x\n",
caps.driver,
caps.card,
caps.bus_info,
(caps.version>>16)&&0xff,
(caps.version>>24)&&0xff,
caps.capabilities );
char fourcc[5] = {0};
struct v4l2_format fmt = {0};
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.width = 640;
fmt.fmt.pix.height = 480;
//fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_BGR24;
//fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_GREY;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
fmt.fmt.pix.field = V4L2_FIELD_NONE;
if (-1 == xioctl(fd, VIDIOC_S_FMT, &fmt))
{
perror("Setting Pixel Format");
return 1;
}
strncpy(fourcc, (char *)&fmt.fmt.pix.pixelformat, 4);
printf( "Selected Camera Mode:\n"
" Width: %d\n"
" Height: %d\n"
" PixFmt: %s\n"
" Field: %d\n",
fmt.fmt.pix.width,
fmt.fmt.pix.height,
fourcc,
fmt.fmt.pix.field);
return 0;
}
// int init_mmap(int fd)
// {
// struct v4l2_requestbuffers req = {0};
// req.count = 1;
// req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
// req.memory = V4L2_MEMORY_MMAP;
// if (-1 == V4L2Manager::xioctl(fd, VIDIOC_REQBUFS, &req))
// {
// perror("Requesting Buffer");
// return 1;
// }
// struct v4l2_buffer buf = {0};
// buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
// buf.memory = V4L2_MEMORY_MMAP;
// buf.index = 0;
// if(-1 == V4L2Manager::xioctl(fd, VIDIOC_QUERYBUF, &buf))
// {
// perror("Querying Buffer");
// return 1;
// }
// // buffer = mmap (NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, buf.m.offset);
// //printf("Length: %d\nAddress: %p\n", buf.length, buffer);
// //printf("Image Length: %d\n", buf.bytesused);
// return 0;
// }
// int capture_image(int fd)
// {
// struct v4l2_buffer buf = {0};
// buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
// buf.memory = V4L2_MEMORY_MMAP;
// buf.index = 0;
// if(-1 == xioctl(fd, VIDIOC_QBUF, &buf))
// {
// perror("Query Buffer");
// return 1;
// }
// if(-1 == xioctl(fd, VIDIOC_STREAMON, &buf.type))
// {
// perror("Start Capture");
// return 1;
// }
// fd_set fds;
// FD_ZERO(&fds);
// FD_SET(fd, &fds);
// struct timeval tv = {0};
// tv.tv_sec = 2;
// int r = select(fd+1, &fds, NULL, NULL, &tv);
// if(-1 == r)
// {
// perror("Waiting for Frame");
// return 1;
// }
// if(-1 == xioctl(fd, VIDIOC_DQBUF, &buf))
// {
// perror("Retrieving Frame");
// return 1;
// }
// printf ("saving image\n");
// // IplImage* frame;
// // CvMat cvmat = cvMat(480, 640, CV_8UC3, (void*)buffer);
// // frame = cvDecodeImage(&cvmat, 1);
// // cvNamedWindow("window",CV_WINDOW_AUTOSIZE);
// // cvShowImage("window", frame);
// // cvWaitKey(0);
// // cvSaveImage("image.jpg", frame, 0);
// return 0;
// }
|
df3a299efbee1d4e65946ac1757b7d490d62e45d
|
7418c9f87fdc8be65f10a9bd36ff139c8c619a07
|
/Blocks.h
|
5742927701b1a1fc74867cfe5021ac044c812cc1
|
[
"Zlib"
] |
permissive
|
Kirieshke/Arcanoid
|
743e758f87064f646354d97675c42eef9b5a7099
|
e3a5e57af67d68332bc627748f508d689df6f542
|
refs/heads/master
| 2022-10-18T10:23:23.188171
| 2020-06-17T15:05:29
| 2020-06-17T15:05:29
| 273,001,963
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 286
|
h
|
Blocks.h
|
#include<SFML/Graphics.hpp>
using namespace sf;
class Block
{
private:
Vector2f position;
public:
bool destroyed = false;
Block();
Block(float startX, float startY);
RectangleShape blockShape;
FloatRect getPosition();
RectangleShape getShape();
void update();
};
|
25200ec90bab690626e8b5f75740a67ef475261b
|
4e8f53a51ac928556adce378b42a9e3baed6415e
|
/cuckoo.cpp
|
cc06b4a8d69b9a81e8adc1ae1e69df4cc0a7b23c
|
[] |
no_license
|
oliviamaciejewska/hash_tables
|
ef436c1e44a35bf6287a6f41461059e026f2602b
|
151264682f6f815475edb0049b49693af5113b11
|
refs/heads/master
| 2020-12-01T04:26:02.607319
| 2019-12-28T04:14:00
| 2019-12-28T04:14:00
| 230,556,929
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,462
|
cpp
|
cuckoo.cpp
|
#include "CUCKOO.hpp"
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <sstream>
#include <time.h>
#include <windows.h>
#include <iomanip>
#include <algorithm>
#include <random>
using namespace std;
HashTable::HashTable() {
// M = 10009;
table1 = new int[M];
table2 = new int[M];
for (int i=0; i<M; i++)
{
table1[i] = -1;
table2[i] = -1;
}
}
void HashTable::rehash()
{
int tempSize=M;
int newSize= nextPrime(M);
M=newSize;
int *tempTable1= new int[M];
int *tempTable2= new int[M];
for (int i=0; i<tempSize; i++)
{
tempTable1[i]=table1[i];
tempTable2[i]=table2[i];
}
delete[] table1;
delete[] table2;
// HashTable();
// for (int i=0; i<M; i++)
// {
// if(tempTable1[i] != -1)
// { int key=tempTable1[i];
// insert(key);
// }
// }
// for (int i=0; i<M;i++)
// {
// if(tempTable2[i] != -1)
// {
// insert(tempTable2[i]);
// }
// }
table1=tempTable1;
table2=tempTable2;
// delete[] tempTable1;
// delete[] tempTable2;
}
int HashTable::h1(int k) {
return k % M;
}
int HashTable::h2(int k) {
return (k/M) % M;
}
bool HashTable::isPrime(int N)
{
if (N%2==0 || N%3==0)
{
return false;
}
for (int i=5; i*i<=N; i=i+6)
{
if (N%i==0 || N%(i+2)==0)
return false;
}
return true;
}
int HashTable::nextPrime(int n)
{
int prime=n;
bool found=false;
while(!found){
prime++;
if (isPrime(prime))
{
found=true;
}
}
return prime;
}
int HashTable::insertHelper(int k, int initialK, int index, int count)
{
int temp=table1[index];
if (temp==initialK)
{
rehash();
cout << "rehash" << endl;
}
int altIndex=h2(table1[index]);
table1[index]=k;
if (table2[altIndex]==-1)
{
table2[altIndex]=temp;
return k;
}
else
{
insertHelper(temp, initialK, altIndex, count +1);
}
}
int HashTable::insert(int k)
{
int indexInsert=h1(k);
if (table1[indexInsert]==-1)
{
table1[indexInsert]=k;
return k;
}
int indexInsert2=h2(k);
if(table2[indexInsert2]==-1)
{
table2[indexInsert2]=k;
return k;
}
else
{
int count=0;
insertHelper(k, k, indexInsert, count);
}
}
int HashTable::search(int k)
{
int index1=h1(k);
if (table1[index1]==k)
{
return table1[index1];
}
else
{
int index2=h2(k);
if(table2[index2]==k);
return table2[index2];
}
return -1;
}
void HashTable::deleteKey(int k)
{
int index1=h1(k);
if(table1[index1]==k)
{
table1[index1]=-1;
}
else
{
int index2=h2(k);
if (table2[index2]==k)
{
table2[index2]=-1;
}
}
}
void HashTable::printTable() {
ofstream outStream;
outStream.open("cuckooA3.csv");
for (int i=0; i<M; i++)
outStream << table1[i] << ',' << table2[i] << endl;
}
void HashTable::insertTimer(vector<int> &dataSet){
LARGE_INTEGER frequency;
LARGE_INTEGER startTime, endTime, totalTime;
// auto startTime= chrono::high_resolution_clock::now();
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&startTime);
for(int i=0; i<100; i++)
{
insert(dataSet[i]);
}
QueryPerformanceCounter(&endTime);
totalTime.QuadPart = ((endTime.QuadPart - startTime.QuadPart) * 1e9) / frequency.QuadPart;
//1e9 is nanoseconds, 1e6 microseconds, 1e3 is milliseconds
cout << "Insert time: " << totalTime.QuadPart << endl;
}
void HashTable::deleteTimer(vector<int> &dataSet){
LARGE_INTEGER frequency;
LARGE_INTEGER startTime, endTime, totalTime;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&startTime);
for(int i=0; i<100; i++)
{
deleteKey(dataSet[i]);
}
QueryPerformanceCounter(&endTime);
totalTime.QuadPart = ((endTime.QuadPart - startTime.QuadPart) * 1e9) / frequency.QuadPart;
//1e9 is nanoseconds, 1e6 microseconds, 1e3 is milliseconds
cout << "Delete time: " << totalTime.QuadPart << endl;
}
void HashTable::searchTimer(vector<int> &dataSet){
LARGE_INTEGER frequency;
LARGE_INTEGER startTime, endTime, totalTime;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&startTime);
for(int i=0; i<100; i++)
{
search(dataSet[i]);
}
QueryPerformanceCounter(&endTime);
totalTime.QuadPart = ((endTime.QuadPart - startTime.QuadPart) * 1e9) / frequency.QuadPart;
//1e9 is nanoseconds, 1e6 microseconds, 1e3 is milliseconds
cout << "Search time: " << totalTime.QuadPart << endl;
}
|
9dd45c3479d93833e2fa0f28cd4ee2a93f030089
|
be2f784ca805383936579cfed7acec933db3ee39
|
/CFractal/Mandel.cpp
|
9b27602072f678c9c03396c0aeef8cc475555a37
|
[] |
no_license
|
maitchison/cfractal
|
f1c3b107f3e2429b26271744a45d29613b344a2b
|
ae7a8d44948249ae7536a5576e15cb707e9b4a12
|
refs/heads/master
| 2021-01-18T18:42:31.476006
| 2016-07-08T10:50:20
| 2016-07-08T10:50:20
| 62,693,843
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,091
|
cpp
|
Mandel.cpp
|
// Solver for Mandelbrot set
//
// Date: 2016/06/27
#include "stdafx.h"
#include "Mandel.h"
#include "xmmintrin.h"
FractalBlock MandelbrotSolver::CreateBlock(double x, double y, double scale)
{
FractalBlock result;
result.width = block_size;
result.height = block_size;
result.x_in = new double[block_size*block_size];
result.y_in = new double[block_size*block_size];
result.values_out = new int[block_size*block_size];
for (int xlp = 0; xlp < block_size; xlp++)
{
for (int ylp = 0; ylp < block_size; ylp++)
{
result.x_in[xlp + ylp * block_size] = x + (double)xlp * scale;
result.y_in[xlp + ylp * block_size] = y + (double)ylp * scale;
}
}
return result;
}
/// Simple mandelbrot solver, just written in c++
void MandelbrotSolver::simple_solve(FractalBlock block)
{
int length = block.width * block.height;
double thresholdSquared = threshold * threshold;
int index = 0;
for (int i = 0; i < length; i++)
{
double c = block.x_in[i];
double ci = block.y_in[i];
double z = 0;
double zi = 0;
int it = 0;
for (int j = 0; j < itterations; j++)
{
it ++;
// z = z*z + c
double _z = z * z - zi * zi;
double _zi = 2 * z * zi;
z = _z + c;
zi = _zi + ci;
// check length of z
if (z*z + zi*zi > thresholdSquared) {
break;
}
}
block.values_out[index] = it;
index++;
}
}
/// SIMD solver, uses SSE.
void MandelbrotSolver::intrinsic_solve_32(FractalBlock block)
{
int length = block.width * block.height;
float thresholdSquared = threshold * threshold;
int index = 0;
for (int i = 0; i < length/4; i++)
{
// pack into a 4 vector
__m128 c = _mm_set_ps(block.x_in[index], block.x_in[index + 1], block.x_in[index + 2], block.x_in[index + 3]);
__m128 ci = _mm_set_ps(block.y_in[index], block.y_in[index + 1], block.y_in[index + 2], block.y_in[index + 3]);
__m128 z = _mm_set_ps(0.0f, 0.0f, 0.0f, 0.0f);
__m128 zi = _mm_set_ps(0.0f, 0.0f, 0.0f, 0.0f);
__m128 _z = _mm_set_ps(0.0f, 0.0f, 0.0f, 0.0f);
__m128 _zi = _mm_set_ps(0.0f, 0.0f, 0.0f, 0.0f);
__m128 marker = _mm_set_ps(1.0f, 1.0f, 1.0f, 1.0f);
__m128 counter = _mm_set_ps(0.0f, 0.0f, 0.0f, 0.0f);
__m128 limit = _mm_set_ps(thresholdSquared, thresholdSquared, thresholdSquared, thresholdSquared);
for (int j = 0; j < 1000; j++)
{
__m128 _z2 = _mm_mul_ps(z, z);
__m128 _zi2 = _mm_mul_ps(zi, zi);
_z = _mm_sub_ps(_z2, _zi2);
_zi = _mm_mul_ps(z, zi);
_zi = _mm_add_ps(_zi, _zi);
z = _mm_add_ps(_z, c);
zi = _mm_add_ps(_zi, ci);
__m128 late_check = _mm_add_ps(_z2, _zi2);
__m128 mask = _mm_cmple_ps(late_check, limit);
marker = _mm_and_ps(marker, mask);
counter = _mm_add_ps(counter, marker);
if (marker.m128_u64[0] == 0 && marker.m128_u64[1] == 0)
break;
}
for (int k = 0; k < 4; k++) {
block.values_out[index++] = (int)counter.m128_f32[3-k];
}
}
}
void MandelbrotSolver::SSE_solve(FractalBlock block)
{
int length = block.width * block.height;
float thresholdSquared = threshold * threshold;
int index = 0;
for (int i = 0; i < length / 4; i++)
{
// pack into a 4 vector
__m128 c = _mm_set_ps(block.x_in[index], block.x_in[index + 1], block.x_in[index + 2], block.x_in[index + 3]);
__m128 ci = _mm_set_ps(block.y_in[index], block.y_in[index + 1], block.y_in[index + 2], block.y_in[index + 3]);
__m128 z = _mm_set_ps(0.0f, 0.0f, 0.0f, 0.0f);
__m128 zi = _mm_set_ps(0.0f, 0.0f, 0.0f, 0.0f);
__m128 _z = _mm_set_ps(0.0f, 0.0f, 0.0f, 0.0f);
__m128 _zi = _mm_set_ps(0.0f, 0.0f, 0.0f, 0.0f);
__m128 marker = _mm_set_ps(1.0f, 1.0f, 1.0f, 1.0f);
__m128 counter = _mm_set_ps(0.0f, 0.0f, 0.0f, 0.0f);
__m128 limit = _mm_set_ps(thresholdSquared, thresholdSquared, thresholdSquared, thresholdSquared);
__asm
{
// setup:
// xmm0 c
// xmm1 ci
// loop:
mov cx, 1000
_LOOP:
dec cx
jnz _LOOP
/*
//__m128 _z2 = _mm_mul_ps(z, z);
movaps xmm0, xmmword ptr[ebp - 90h]
mulps xmm0, xmmword ptr[ebp - 90h]
movaps xmmword ptr[ebp - 570h], xmm0
movaps xmm0, xmmword ptr[ebp - 570h]
movaps xmmword ptr[ebp - 180h], xmm0
//__m128 _zi2 = _mm_mul_ps(zi, zi);
movaps xmm0, xmmword ptr[ebp - 0B0h]
mulps xmm0, xmmword ptr[ebp - 0B0h]
movaps xmmword ptr[ebp - 590h], xmm0
movaps xmm0, xmmword ptr[ebp - 590h]
movaps xmmword ptr[ebp - 1A0h], xmm0
// _z = _mm_sub_ps(_z2, _zi2);
movaps xmm0, xmmword ptr[ebp - 180h]
subps xmm0, xmmword ptr[ebp - 1A0h]
movaps xmmword ptr[ebp - 5B0h], xmm0
movaps xmm0, xmmword ptr[ebp - 5B0h]
movaps xmmword ptr[ebp - 0D0h], xmm0
// _zi = _mm_mul_ps(z, zi);
movaps xmm0, xmmword ptr[ebp - 90h]
mulps xmm0, xmmword ptr[ebp - 0B0h]
movaps xmmword ptr[ebp - 5D0h], xmm0
movaps xmm0, xmmword ptr[ebp - 5D0h]
movaps xmmword ptr[ebp - 0F0h], xmm0
// _zi = _mm_add_ps(_zi, _zi);
movaps xmm0, xmmword ptr[ebp - 0F0h]
addps xmm0, xmmword ptr[ebp - 0F0h]
movaps xmmword ptr[ebp - 5F0h], xmm0
movaps xmm0, xmmword ptr[ebp - 5F0h]
movaps xmmword ptr[ebp - 0F0h], xmm0
// z = _mm_add_ps(_z, c);
movaps xmm0, xmmword ptr[ebp - 0D0h]
addps xmm0, xmmword ptr[ebp - 50h]
movaps xmmword ptr[ebp - 610h], xmm0
movaps xmm0, xmmword ptr[ebp - 610h]
movaps xmmword ptr[ebp - 90h], xmm0
// zi = _mm_add_ps(_zi, ci);
movaps xmm0, xmmword ptr[ebp - 0F0h]
addps xmm0, xmmword ptr[ebp - 70h]
movaps xmmword ptr[ebp - 630h], xmm0
movaps xmm0, xmmword ptr[ebp - 630h]
movaps xmmword ptr[ebp - 0B0h], xmm0
// __m128 late_check = _mm_add_ps(_z2, _zi2);
movaps xmm0, xmmword ptr[ebp - 180h]
addps xmm0, xmmword ptr[ebp - 1A0h]
movaps xmmword ptr[ebp - 650h], xmm0
movaps xmm0, xmmword ptr[ebp - 650h]
movaps xmmword ptr[ebp - 1C0h], xmm0
// __m128 mask = _mm_cmple_ps(late_check, limit);
movaps xmm0, xmmword ptr[ebp - 1C0h]
cmpleps xmm0, xmmword ptr[ebp - 150h]
movaps xmmword ptr[ebp - 670h], xmm0
movaps xmm0, xmmword ptr[ebp - 670h]
movaps xmmword ptr[ebp - 1E0h], xmm0
// marker = _mm_and_ps(marker, mask);
movaps xmm0, xmmword ptr[ebp - 110h]
andps xmm0, xmmword ptr[ebp - 1E0h]
movaps xmmword ptr[ebp - 690h], xmm0
movaps xmm0, xmmword ptr[ebp - 690h]
movaps xmmword ptr[ebp - 110h], xmm0
// counter = _mm_add_ps(counter, marker);
movaps xmm0, xmmword ptr[ebp - 130h]
addps xmm0, xmmword ptr[ebp - 110h]
movaps xmmword ptr[ebp - 6B0h], xmm0
movaps xmm0, xmmword ptr[ebp - 6B0h]
movaps xmmword ptr[ebp - 130h], xmm0
// if (marker.m128_u64[0] == 0 && marker.m128_u64[1] == 0)
mov eax, 8
imul ecx, eax, 0
mov dword ptr[ebp - 6B8h], ecx
*/
// if (marker.m128_u64[0] == 0 && marker.m128_u64[1] == 0)
/*
008FC99D mov edx, dword ptr[ebp - 6B8h]
008FC9A3 mov eax, dword ptr[ebp - 6B8h]
008FC9A9 mov ecx, dword ptr[ebp + edx - 110h]
008FC9B0 or ecx, dword ptr[ebp + eax - 10Ch]
008FC9B7 jne MandelbrotSolver::intrinsicSSE_solve + 3C5h(08FC9E5h)
008FC9B9 mov eax, 8
008FC9BE shl eax, 0
008FC9C1 mov dword ptr[ebp - 6B8h], eax
008FC9C7 mov ecx, dword ptr[ebp - 6B8h]
008FC9CD mov edx, dword ptr[ebp - 6B8h]
008FC9D3 mov eax, dword ptr[ebp + ecx - 110h]
008FC9DA or eax, dword ptr[ebp + edx - 10Ch]
008FC9E1 jne MandelbrotSolver::intrinsicSSE_solve + 3C5h(08FC9E5h)
break;
008FC9E3 jmp MandelbrotSolver::intrinsicSSE_solve + 3CAh(08FC9EAh)
}
008FC9E5 jmp MandelbrotSolver::intrinsicSSE_solve + 1D4h(08FC7F4h)
*/
}
for (int k = 0; k < 4; k++) {
block.values_out[index++] = (int)counter.m128_f32[3 - k];
}
}
}
|
e41185396303f6bc975ce2dd75425163fd79e1d1
|
914a06b7a1d0a7c78c73c3ff931510b0ff6250ed
|
/src/system/xio.h
|
060c710316fc36c8614d2b9ee5e3162d42a90a45
|
[] |
no_license
|
GeomaticsAndRS/flow123d
|
fac71d281f0c7b64ef5f76be2503b4242b6fc846
|
93502c2ac524f7028549f6497d109a38a08bd971
|
refs/heads/master
| 2022-11-17T02:13:26.923282
| 2020-07-02T09:03:08
| 2020-07-02T09:03:08
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,511
|
h
|
xio.h
|
/*!
*
* Copyright (C) 2015 Technical University of Liberec. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation. (http://www.gnu.org/licenses/gpl-3.0.en.html)
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
*
* @file xio.h
* @brief I/O functions with filename storing, able to track current line in opened file. All standard
* stdio functions working with files (not stdin, stdout, stderr) should be replaced
* by their equivalents from XIO library.
* @author Jiri Jenicek
*/
/*
*
* Commented lines contains functions of stdio library that are not used in Flow123d.
* Their equivalents are currently not implemented in XIO library.
*
*/
#ifndef XIO_H_
#define XIO_H_
#include "global_defs.h"
#include "system/system.hh"
#include <map>
// Size of buffer for text input lines.
#define LINE_SIZE 65536
//! @brief XFILE structure holds additional info to generic FILE
/// @{
typedef struct xfile {
char * filename; ///< file name in the time of opening
char * mode; ///< opening mode
int lineno; ///< last read line (only for text files)
} XFILE;
//! @}
/**
* Base class of XIO library.
*
* The class implements a singleton pattern.
* Stores data of file mapping and debug output for XIO function.
*/
class Xio {
public:
/// mapping of ptr to regular file structure to extended structure
typedef map< FILE *, XFILE * > XFILEMAP;
/// return instance
static Xio *get_instance();
/// initialize XIO library
static void init();
/// Enable/Disable XIO debug output for EACH XIO function call
void set_verbosity(int verb);
/// Get current XIO debug verbosity level
int get_verbosity();
/// Get XIO mapping instance
XFILEMAP &get_xfile_map();
private:
// Singleton instance
static Xio *instance;
/**
* Constructor.
*
* Initialize XIO library.
*/
Xio();
/// mapping instance
XFILEMAP xfiles_map_;
/// internal XIO debug: print info at each XIO function
int verbosity_;
};
//! @brief XIO library extensions
/// @{
char * xio_getfname( FILE * f ); ///< Get file name from file stream
char * xio_getfmode( FILE * f ); ///< Get file mode from file stream
int xio_getlinesread( FILE * f ); ///< Get number of read lines from stream
char * xio_getfulldescription( FILE * f ); ///< Get pointer to string with full file description
//! @}
//! @brief File access
/// @{
FILE * xfopen( const char * fname, const char * mode ); ///< Open file (function)
FILE * xfopen( const std::string &fname, const char * mode );
int xfclose( FILE * stream ); ///< Close file (function)
int xfflush( FILE * f ); ///< Flush stream (function)
FILE * xfreopen( const char * filename, const char * mode, FILE * stream );
//! @}
//! @brief Formatted input/output
/// @{
int xfprintf( FILE * out, const char * fmt, ... ); ///< Write formatted output to stream (function)
int xfscanf( FILE * in, const char * fmt, ... ); ///< Read formatted data from stream (function)
//! @}
//! @brief Character input/output
/// @{
char * xfgets( char *s, int n, FILE *in ); ///< Get string from stream (function)
int xfgetc( FILE * f ); ///< Get character from stream (function)
int xgetc( FILE * f ); ///< Get character from stream (function)
int xungetc( int c, FILE * f ); ///< Unget character from stream (function)
//! @}
//! @brief Direct input/output
/// @{
size_t xfread( void * ptr, size_t size, size_t count, FILE * stream ); ///< Read block of data from stream (function)
size_t xfwrite( const void * ptr, size_t size, size_t count, FILE * stream ); ///< Write block of data to stream (function)
//! @}
//! @brief File positioning
/// @{
void xrewind( FILE * f ); ///< Set position indicator to the beginning (function)
//! @}
//! @brief Error-handling
/// @{
int xfeof ( FILE * f ); ///< Check End-of-File indicator (function)
//! @}
#endif /* XIO_H_ */
|
491b54ba6b90746e5733330c84bdb245243392f1
|
e9b3b076ebd977a7810c093201e46bb4be4712a9
|
/analyze.cpp
|
fa1de170515e22d16151fe7951dbba5210b0c8a1
|
[] |
no_license
|
zleba/mcEventDisplay
|
fb50b30543dafd447cee1e7911491c33ab1b57a6
|
20451a399f48223ba0e68766f448f9184b150050
|
refs/heads/master
| 2021-01-12T09:46:07.418418
| 2018-10-28T13:09:24
| 2018-10-28T13:09:24
| 76,244,954
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 54,021
|
cpp
|
analyze.cpp
|
#include "analyze.h"
//#include "draw.h"
//#include <GL/glut.h>
//#include "logo.h"
//#include "diagram.h"
//#include <QPointF>
#include "TCanvas.h"
#include "TCurlyLine.h"
#include "TArrow.h"
const double lastScale = 0.01;
const double lastScaleEm = 1e-6;
bool Tree::fillStrings()
{
String string;
bool isIn = false;
for(int i=0; i < event.size(); ++i) {
if(event[i].status == -71) {
string.partons.push_back(i);
isIn = true;
}
else {
isIn = false;
if(string.partons.size() > 0) {
strings.push_back(string);
string.partons.clear();
}
}
}
for(int i=0; i < strings.size(); ++i) {
int j1 = event[strings[i].partons[0]].daughter1;
int j2 = event[strings[i].partons[0]].daughter2;
for(int j=j1; j <= j2; ++j) {
strings[i].hadrons.push_back(j);
}
}
}
vector<Color> Tree::CreateColors(int maxCol)
{
/*
//set<int> colors;
int maxCol= 0;
for(tree<Edge>::iterator it = tr.begin(); it != tr.end(); ++it) {
maxCol = max(maxCol, it->col);
maxCol = max(maxCol, it->acol);
}
maxCol-=100-3;
*/
vector<Color> colors(maxCol);
for(int i=0; i < maxCol; ++i) {
colors[i].r = rand()/double(RAND_MAX);
colors[i].g = rand()/double(RAND_MAX);
colors[i].b = rand()/double(RAND_MAX);
//TColor::HLS2RGB(hue,light, sat, r, g, b);
//Int_t ci = 1500+i; // color index
//TColor *color = new TColor(ci, r, g, b);
}
vector< vector<double> > Distances(maxCol);
vector<double> DistancesNew(maxCol);
for(int i=0; i < maxCol; ++i) {
Distances[i].resize(maxCol);
}
bool doNext = true;
for(int k = 0; k < 400 && doNext; ++k) {
//cout << "Step " << k << endl;
double minDist=1e30;
int iMin, jMin;
for(int i=0; i < maxCol; ++i)
for(int j=0; j < maxCol; ++j) {
if(i==j) continue;
Distances[i][j] = distance(colors[i], colors[j]);
if(Distances[i][j] < minDist) {
minDist = Distances[i][j];
iMin = i; jMin = j;
}
}
Color col;
double smaller;
int counter = 0;
do {
col.r = rand()/double(RAND_MAX);
col.g = rand()/double(RAND_MAX);
col.b = rand()/double(RAND_MAX);
//Calc new distances
smaller = 1e30;
for(int i=0; i < maxCol; ++i) {
DistancesNew[i]= distance(col, colors[i]);
smaller = min(smaller,DistancesNew[i]);
}
++counter;
if(counter > 1000)
doNext = false;
} while(smaller < minDist);
//calc second min
double minDistI = 1e30;
for(int j=0; j < maxCol; ++j) {
if(j == jMin || j == iMin) continue;
minDistI=min(minDistI,Distances[iMin][j]);
}
double minDistJ = 1e30;
for(int i=0; i < maxCol; ++i) {
if(i == iMin || i == jMin) continue;
minDistJ=min(minDistJ,Distances[i][jMin]);
}
if(minDistI < minDistJ)
colors[iMin] = col;
else
colors[jMin] = col;
}
return colors;
}
bool Tree::isIntersect(tree<Edge>::iterator it1, tree<Edge>::iterator it2)
{
if(it1 == it2) {
//cout << "Iterators are identical1" << endl;
return false;
}
tree<Edge>::iterator par1 = tr.parent(it1);
tree<Edge>::iterator par2 = tr.parent(it2);
if(par1 == it2 || par2 == it1) {
//cout << "Iterators are identical2" << endl;
return false;
}
tree<Edge>::iterator s1 = tr.previous_sibling(it1);
tree<Edge>::iterator s2 = tr.next_sibling(it1);
tree<Edge>::iterator s = (s1 != 0) ? s1 : s2;
if(it2 == s) {
//cout << "Iterators are identical3" << endl;
return false;
}
double eps = 1e-8;
double a11 = par1->x - it1->x;
double a21 = par1->y - it1->y;
double a12 =-(par2->x - it2->x );
double a22 =-(par2->y - it2->y );
double b1 = - it1->x + it2->x;
double b2 = - it1->y + it2->y;
double Det = a11*a22 - a12*a21;
if(abs(Det) < eps)
return false;
double Det1 = b1*a22 - a12*b2;
double Det2 = a11*b2 - b1*a21;
double t1 = Det1 /Det;
double t2 = Det2 /Det;
double lim = 0.6;
/*
if( t1 >= 1+lim || t1 <=-lim)
return false;
if( t2 >= 1+lim || t2 <=-lim)
return false;
*/
if( (t1-1) * it1->l >= lim || t1 * it1->l <=-lim)
return false;
if( (t2-1) * it2->l >= lim || t2 * it2->l <=-lim)
return false;
cout << "Intersect : " << it1->id << " "<<it2->id << endl;
return true;
}
void Tree::Iterate(tree<Edge>::iterator it, bool isFin)
{
//if(event[it->id].status <= -60 || event[it->id].status == -23)
//return;
/*
if(it->daughter1 == it->daughter2) {
cout << "Fist case "<< it->id <<" : "<< it->daughter1<<" "<< it->daughter2 << endl;
it->id = it->daughter1;
it->daughter1 = event[it->daughter1].daughter1;
it->daughter2 = event[it->daughter1].daughter2;
if( event[it->id].status > -60 && event[it->id].status != -23 )
Iterate(it);
return;
}
*/
int daughter1, daughter2;
daughter1 = it->daughter1;
daughter2 = it->daughter2;
int oldId = it->id;
while((daughter1 == daughter2 && daughter2 > 0) || (daughter1 > 0 && daughter2 == 0) ) {
int id = daughter1;
//cout << "Helax "<< daughter1 <<": isOk "<< isOK(daughter1, isFin)<< endl;
if( !isOK(daughter1, isFin) ) {
if(!isFin && event[daughter1].status == -22)
it->id = oldId; //is it ok?
return;
}
daughter1 = event[id].daughter1;
daughter2 = event[id].daughter2;
oldId = id;
}
if(daughter1 <= daughter2) {
//cout << "Second case "<< it->id <<" "<<event[it->id].status<<" : "<< daughter1<<" "<< daughter2 << endl;
tree<Edge>:: iterator it1;
for(int id = daughter1; id <= daughter2; ++id) {
if(!isOK(id, isFin) ) continue;
it1 = tr.append_child(it, Edge(event[id].id, event[id].col, event[id].acol, event[id].daughter1, event[id].daughter2) );
Iterate(it1, isFin);
}
return;
}
else {
int id;
tree<Edge>::iterator it1;
id = daughter1;
if(isOK(id, isFin) ) {
it1 = tr.append_child(it, Edge(event[id].id, event[id].col, event[id].acol, event[id].daughter1, event[id].daughter2) );
Iterate(it1, isFin);
}
id = daughter2;
if( isOK(id, isFin) ) {
it1 = tr.append_child(it, Edge(event[id].id, event[id].col, event[id].acol, event[id].daughter1, event[id].daughter2) );
Iterate(it1, isFin);
}
}
}
void Tree::read()
{
Particle p;
bool stat;
string name;
fstream file;
file.open ("eventFiles/eventGG2H.txt", std::fstream::in);
getline (file,name);
getline (file,name);
getline (file,name);
getline (file,name);
do {
stat = true;
if( !(file >> p.id >> p.pdg >> p.name >> p.status
>> p.mother1 >> p.mother2 >> p.daughter1 >> p.daughter2
>> p.col >> p.acol >> p.px >> p.py >> p.pz >> p.e >> p.m ))
stat = false;
if( !(file >> p.scale >> p.pol >> p.xProd >> p.yProd >> p.zProd >> p.tProd >>p.tau
))
stat = false;
if(!stat)
break;
//cout << "RADEK " << event.size() <<" "<< p.id << endl;
event.push_back(p);
} while(stat);
//for(int i = 0; i < event.size(); ++i)
//cout <<i <<" "<< event[i].id << endl;
//cout << event.size() << endl;
pdgNames[1] = "d";
pdgNames[2] = "u";
pdgNames[3] = "s";
pdgNames[4] = "c";
pdgNames[5] = "b";
pdgNames[6] = "t";
pdgNames[-1] = "#bar d";
pdgNames[-2] = "#bar u";
pdgNames[-3] = "#bar s";
pdgNames[-4] = "#bar c";
pdgNames[-5] = "#bar b";
pdgNames[-6] = "#bar t";
pdgNames[11] = "e-";
pdgNames[13] = "#mu-";
pdgNames[15] = "#tau-";
pdgNames[-11] = "e+";
pdgNames[-13] = "#mu+";
pdgNames[-15] = "#tau+";
pdgNames[21] = "g";
pdgNames[22] = "#gamma";
pdgNames[23] = "Z^{0}";
pdgNames[24] = "W^{+}";
pdgNames[-24] = "W^{-}";
pdgNames[25] = "H";
showColLines=false;
fillStrings();
}
int Tree::FindStart(int id)
{
//id = event[id].mother1;
while(isOK(event[id].mother1) ) {
id = event[id].mother1;
//cout << "Test id " << id << endl;
}
return id;
}
void Tree::MarkFixed(double angle)
{
set<int> fixed;
int id;
id = idHard1;
fixed.insert(id);
while(isOK(event[id].mother1) ) {
id = event[id].mother1;
fixed.insert(id);
}
id = idHard2;
fixed.insert(id);
while(isOK(event[id].mother1) ) {
id = event[id].mother1;
fixed.insert(id);
}
tree<Edge>::iterator it= tr.begin();
for(; it != tr.end(); ++it) {
tree<Edge>::iterator s1 = tr.previous_sibling(it);
tree<Edge>::iterator s2 = tr.next_sibling(it);
tree<Edge>::iterator s = (s1!=0) ? s1 : s2;
if( fixed.count(it->id) > 0) {
it->isFixed = true;
it->angle = 0;
}
else if(s != 0 && fixed.count(s->id) > 0) {
it->isFixed = false;
it->angle = 2.2*angle; //0.65
}
else {
//if(it->angle < -0.5) {
it->isFixed = false;
it->angle = angle;
}
}
}
void Tree::Limits(int n, double &xmin, double &xmax, double &ymin, double &ymax)
{
tree<Edge>::sibling_iterator itS= tr.begin();
for(int i = 0; i < n; ++i)
++itS;
xmin = ymin = 1e20;
xmax = ymax = -1e20;
tree<Edge>::iterator it = itS;
do {
if(it->isFixed == false) {
xmin = min(xmin, it->x);
xmax = max(xmax, it->x);
ymin = min(ymin, it->y);
ymax = max(ymax, it->y);
}
else {
if( abs(it->l -2) < 0.1) {
xmin = min(xmin, it->x);
xmax = max(xmax, it->x);
ymin = min(ymin, it->y);
ymax = max(ymax, it->y);
}
else {
tree<Edge>::iterator par = tr.parent(it);
if(n==0) {
xmin = min(xmin, par->x+2);
xmax = max(xmax, par->x+2);
}
else {
xmin = min(xmin, par->x-2);
xmax = max(xmax, par->x-2);
}
ymin = min(ymin, it->y);
ymax = max(ymax, it->y);
}
}
++it;
} while(tr.depth(it) !=0 && it != tr.end() );
}
void Tree::ChangeHardLeg(int n, double newPos)
{
tree<Edge>::sibling_iterator itS= tr.begin();
for(int i = 0; i < n; ++i)
++itS;
tree<Edge>::iterator it = itS;
tree<Edge>::iterator itHard;
double minLen = 1e20;
do {
if(it->isFixed == true) {
int len;
if(n==0)
len = -it->x;
else
len = it->x;
if(len < minLen) {
minLen = len;
itHard = it;
}
}
++it;
} while(tr.depth(it) !=0 && it != tr.end() );
//cout << "I am here " << minLen << endl;
tree<Edge>::iterator par = tr.parent(itHard);
itHard->x = (n == 0) ? -newPos : newPos;
itHard->y = 0;
itHard->l = abs(par->x - itHard->x);
//cout << "Coordinate " << itHard->x << endl;
}
void Tree::Shift (int n, double shiftX, double shiftY)
{
tree<Edge>::sibling_iterator itS= tr.begin();
for(int i = 0; i < n; ++i)
++itS;
tree<Edge>::iterator it = itS;
do {
it->x += shiftX;
it->y += shiftY;
++it;
} while(tr.depth(it) !=0 && it != tr.end() );
}
bool Tree::fill(int k)
{
mpiId = k;
tree<Edge>::iterator itP1, itP2, itP3, itP4, it1, it2, it3, it4;
//cout << "SECRET "<< FindStart(3) << endl;
//cout << "SECRET "<< FindStart(4) << endl;
//int id1 = event[event[1].daughter1].daughter1;
//int id2 = event[event[2].daughter1].daughter1;
//cout << "SECRETt "<< id1 << endl;
//cout << "SECRETt "<< id2 << endl;
cout << "Helenka size " << event.size() << endl;
vector<int> hardIds;
vector<int> hardIds23;
vector<int> hardIds22;
for(int i = 0; i < event.size(); ++i) {
if( event[i].status == -21 )
hardIds.push_back(i);
}
for(int i = 0; i < event.size(); ++i) {
if( abs(event[i].status) == 23 )
hardIds23.push_back(i);
}
for(int i = 0; i < event.size(); ++i) {
if( abs(event[i].status) == 22 )
hardIds22.push_back(i);
}
if(hardIds22.size() == 3 && hardIds23.size() == 4) {
hardIds.push_back(hardIds22[1]);
hardIds.push_back(hardIds22[2]);
}
else if(hardIds22.size() == 2 && hardIds23.size() == 3) {
hardIds.push_back(hardIds23[0]);
hardIds.push_back(hardIds22[1]);
}
else if(hardIds23.size() == 2) {
hardIds.push_back(hardIds23[0]);
hardIds.push_back(hardIds23[1]);
}
else {
cout << "Unknown hard process" << endl;
cout << "Event size " << event.size() << endl;
cout << hardIds22.size() <<" "<< hardIds23.size() << endl;
for(auto id : hardIds22)
cout <<"id22 " << id << endl;
for(auto id : hardIds23)
cout <<"id23 "<< id << endl;
exit(1);
}
/*
for(int i = 0; i < event.size(); ++i) {
if( abs(event[i].status) == 22 &&
abs(event[i].pdg) == 23
)
hardIds.push_back(i);
}
*/
//for(int i = 0; i < hardIds.size(); ++i)
//cout <<i << " "<< hardIds[i] << endl;
//exit(1);
for(int i = 0; i < event.size(); ++i) {
if(event[i].status == -31 || event[i].status == -33 )
hardIds.push_back(i);
}
cout << "Stesti " << hardIds.size()/4 << endl;
Nmpi = hardIds.size()/4;
if(k >= hardIds.size()/4)
return false;
cout << "Stesti" << hardIds.size()/4<< endl;
//int k=0;
idHard1 = hardIds[4*k+0];
idHard2 = hardIds[4*k+1];
idHard3 = hardIds[4*k+2];
idHard4 = hardIds[4*k+3];
int id1 = FindStart(hardIds[4*k+0]);
int id2 = FindStart(hardIds[4*k+1]);
int id3 = hardIds[4*k+2];
int id4 = hardIds[4*k+3];
cout <<"Hard ids : "<< id1 <<" "<< id2 <<" "<< id3 << " "<< id4 << endl;
double l = 2;
double inPos = 1000;
tr.clear();
//Initial state
itP1 = tr.insert(tr.end(), Edge(event[id1].id, event[id1].col, event[id1].acol, event[id1].daughter1, event[id1].daughter2, -inPos, 0 ) );
itP2 = tr.insert(tr.end(), Edge(event[id2].id, event[id2].col, event[id2].acol, event[id2].daughter1, event[id2].daughter2, +inPos, 0 ) );
//Final state
itP3 = tr.insert(tr.end(), Edge(event[id3].id, event[id3].col, event[id3].acol, event[id3].daughter1, event[id3].daughter2, 0, +2 ) );
itP4 = tr.insert(tr.end(), Edge(event[id4].id, event[id4].col, event[id4].acol, event[id4].daughter1, event[id4].daughter2, 0, -2 ) );
//Initial state
it1 = tr.append_child(itP1, Edge(event[id1].id, event[id1].col, event[id1].acol, event[id1].daughter1, event[id1].daughter2,-inPos+l, 0) );
it2 = tr.append_child(itP2, Edge(event[id2].id, event[id2].col, event[id2].acol, event[id2].daughter1, event[id2].daughter2,+inPos-l, 0) );
//Final state
it3 = tr.append_child(itP3, Edge(event[id3].id, event[id3].col, event[id3].acol, event[id3].daughter1, event[id3].daughter2, 0, +2+l+1) );
it4 = tr.append_child(itP4, Edge(event[id4].id, event[id4].col, event[id4].acol, event[id4].daughter1, event[id4].daughter2, 0, -2-l-1) );
event[itP1->id].scale = event[itP2->id].scale = lastScale;
event[it1->id].scale = event[it2->id].scale = lastScale;
//it3 = tr.append_child(itP, Edge(event[5].id, event[5].col, event[5].acol, event[5].daughter1, event[5].daughter2) );
//it4 = tr.append_child(itP, Edge(event[6].id, event[6].col, event[6].acol, event[6].daughter1, event[6].daughter2) );
Iterate(it1);
Iterate(it2);
//exit(0);
Iterate(it3, true);
Iterate(it4, true);
//Tag edges that are fixed
MarkFixed();
itP1->isFixed = itP2->isFixed = true;
it1->isFixed = it2->isFixed = true;
return true;
}
void Tree::CalcLayout()
{
//cout << "RADEK is here - size : " << tr.size() << endl;
tree<Edge>::iterator iter = tr.begin();
for(; iter != tr.end(); ++iter) {
//tree<Edge>::iterator it = tr.parent(iter);
//cout << tr.depth(iter)<<" "<< iter->id << endl;
if(tr.depth(iter) < 2) {
continue;
}
tree<Edge>::iterator par2 = tr.parent(iter);
tree<Edge>::iterator par1 = tr.parent(par2);
double vx = par2->x - par1->x;
double vy = par2->y - par1->y;
double lOrg = sqrt(vx*vx + vy*vy);
//iter->l = event[iter->id].e/70.;
vx *= iter->l / lOrg;
vy *= iter->l / lOrg;
double theta;
tree<Edge>::iterator s1 = tr.previous_sibling(iter);
tree<Edge>::iterator s2 = tr.next_sibling(iter);
if(s1 == 0 && s2 == 0) {
iter->x = par2->x + vx;
iter->y = par2->y + vy;
}
else{
if(par2->col != 0 && par2->acol != 0) {
theta = (par2->acol == iter->acol) ? iter->angle : -iter->angle;
}
else if(par2->col != 0 && par2->acol == 0) {
theta = (par2->col == iter->col ) ? -iter->angle : iter->angle;
}
else if(par2->col == 0 && par2->acol != 0) {
theta = (par2->acol == iter->acol) ? iter->angle : -iter->angle;
}
else {
theta = (s1 == 0) ? iter->angle : -iter->angle;
}
iter->x = par2->x + vx*cos(theta) + vy*sin(theta);
iter->y = par2->y - vx*sin(theta) + vy*cos(theta);
}
}
//AddHard();
ChangeHardLeg(0,200);
ChangeHardLeg(1,200);
}
int Tree::GetFinalId(int id)
{
cout << "GetFinalId start "<< id <<" "<<event[id].status<<" "<<event[id].pdg<< endl;
while(1) {
//cout << "Loop " <<id<<" "<<event[id].status << endl;
int d1 = event[id].daughter1;
int d2 = event[id].daughter2;
if(d1==0 && d2==0)
return id;
else if(d1 == d2 || (d1 > 0 && d2 == 0) ) {
if(event[d1].status <= -71 || event[d1].status >= -73)
return id;
else
id = d1;
}
else if( d1 > 0 && d2 > d1 ) {
if(abs(event[d1].status) == 91 ||
(82<= abs(event[d1].status) && abs(event[d1].status) <= 84) )
return id;
else {
cout <<"There is problem "<< id << endl;
exit(1);
}
}
else {
cout <<"There is problem "<< id << endl;
exit(1);
}
}
cout << "GetFinalId end" << endl;
}
void Tree::CalcCorrP()
{
double boostEta = Settings::Instance().getBoostEta();
tree<Edge>::iterator iter = tr.begin();
for(; iter != tr.end(); ++iter) {
tree<Edge>::iterator child = iter;
++child;
if(child == tr.end() || tr.depth(child) <= tr.depth(iter)) { //no child
if(iter->pCorr.isDummy())
if(!iter->isFixed) {
int Id = GetFinalId(iter->id);
//int Id = iter->id;
//iter->pCorr.px = event[Id].px;
//iter->pCorr.py = event[Id].py;
//iter->pCorr.pz = event[Id].pz;
//iter->pCorr.e = event[Id].e;
iter->pCorr = Vec4::boost(boostEta, event[Id].px, event[Id].py, event[Id].pz, event[Id].e);
cout <<"RADECEK "<< boostEta << endl;
}
}
else {
tree<Edge>::iterator s1 = tr.previous_sibling(child);
tree<Edge>::iterator s2 = tr.next_sibling(child);
if(s1 == 0 && s2 == 0) {
if( !child->pCorr.isDummy() && !iter->isFixed) {
iter->pCorr.px = child->pCorr.px;
iter->pCorr.py = child->pCorr.py;
iter->pCorr.pz = child->pCorr.pz;
iter->pCorr.e = child->pCorr.e;
}
}
else {
tree<Edge>::iterator s = (s1 != 0) ? s1 : s2;
//cout <<"Hela "<< event[s->id].scale << " "<< event[child->id].scale << endl;
//if(s->isFixed || child->isFixed)
//event[s->id].scale=event[child->id].scale=min(event[s->id].scale,event[child->id].scale);
if(s->isFixed)
event[s->id].scale=event[child->id].scale;
if(child->isFixed)
event[child->id].scale=event[s->id].scale;
if(s->isFixed || child->isFixed)
continue;
if( !child->pCorr.isDummy() && !s->pCorr.isDummy() ) {
iter->pCorr.px = child->pCorr.px + s->pCorr.px;
iter->pCorr.py = child->pCorr.py + s->pCorr.py;
iter->pCorr.pz = child->pCorr.pz + s->pCorr.pz;
iter->pCorr.e = child->pCorr.e + s->pCorr.e;
}
}
}
}
}
void Tree::CalcPcorrISR(int idHard)
{
int id = FindStart(idHard);
tree<Edge>::iterator iter = tr.begin();
//Left IS leg
for(; iter != tr.end(); ++iter) {
if(iter->id == id)
break;
}
double boostEta = Settings::Instance().getBoostEta();
int idCorr = event[id].mother1;
iter->pCorr = Vec4::boost(boostEta, event[idCorr].px, event[idCorr].py, event[idCorr].pz, event[idCorr].e);
//iter->pCorr.px = event[idCorr].px;
//iter->pCorr.py = event[idCorr].py;
//iter->pCorr.pz = event[idCorr].pz;
//iter->pCorr.e = event[idCorr].e;
while(1) {
tree<Edge>::iterator child = iter;
++child;
if(child == tr.end() || tr.depth(child) <= tr.depth(iter)) { //no child
break;
}
//cout <<"Iterator id " << iter->id <<" "<< child->id<< endl;
//cout << "Depth : " << tr.depth(iter)<<" "<< tr.depth(child) << endl;
//cout << "isFixed : " << iter->isFixed<<" "<< child->isFixed << endl;
tree<Edge>::iterator s1 = tr.previous_sibling(child);
tree<Edge>::iterator s2 = tr.next_sibling(child);
if(s1==0 && s2==0) {
child->pCorr = iter->pCorr;
}
else {
tree<Edge>::iterator s = (s1 != 0) ? s1 : s2;
if(s->isFixed)
swap(child, s);
child->pCorr.px = iter->pCorr.px - s->pCorr.px;
child->pCorr.py = iter->pCorr.py - s->pCorr.py;
child->pCorr.pz = iter->pCorr.pz - s->pCorr.pz;
child->pCorr.e = iter->pCorr.e - s->pCorr.e;
}
iter = child;
}
}
int Tree::FindLastFixed(int idHard)
{
tree<Edge>::iterator iter;
for(iter = tr.begin(); iter != tr.end(); ++iter)
if(iter->id == idHard)
break;
if(!iter->isFixed) {
cout << "Input not fixed "<< iter->id<<" "<< (int)iter->isFixed << endl;
exit(1);
}
while(1) {
tree<Edge>::iterator child = iter;
++child;
if(child == tr.end() || tr.depth(child) <= tr.depth(iter) )
return iter->id;
tree<Edge>::iterator s1 = tr.previous_sibling(child);
tree<Edge>::iterator s2 = tr.next_sibling(child);
if(s1 == 0 && s2 == 0) {
iter = child;
if(!iter->isFixed) {
cout << "Problem with fixing1 "<<iter->id << endl;
exit(1);
}
}
else {
tree<Edge>::iterator s = (s1 != 0) ? s1 : s2;
if(child->isFixed) {
iter = child;
}
else if(s->isFixed) {
iter = s;
}
else {
cout << "Problem with fixing2" << endl;
exit(1);
}
}
//if(child != tr.end() && tr.depth(child) > tr.depth(iter)) {
}
cout << "Problem with fixing3" << endl;
exit(1);
}
void Tree::resetPcorr()
{
tree<Edge>::iterator iter;
for(iter = tr.begin(); iter != tr.end(); ++iter) {
iter->pCorr.dummy();
}
}
void Tree::CalcLayout3D()
{
tree<Edge>::iterator iter;
for(int i = 0; i < 100; ++i)
CalcCorrP();
cout << "idHard1, idHard2 "<< idHard1 <<" "<< idHard2 << endl;
//exit(0);
cout << "Start hadr correcting" << endl;
CalcPcorrISR(idHard1);
CalcPcorrISR(idHard2);
cout << "End hadr correcting" << endl;
int id1 = FindStart(idHard1);
int id2 = FindStart(idHard2);
cout << "id1,id2 " << id1 <<" "<<id2 << endl;
int lastFix1 = FindLastFixed(id1);
int lastFix2 = FindLastFixed(id2);
cout << "My Last Ids "<< lastFix1 <<" "<< lastFix2 << endl;
Vec3 Shift1, Shift2;
//iter = tr.next_sibling(iter);
//iter = tr.next_sibling(iter);
//iter = tr.next_sibling(iter);
for(iter = tr.begin(); iter != tr.end(); ++iter) {
//tree<Edge>::iterator it = tr.parent(iter);
//if(tr.depth(iter) == 0) break;
if(tr.depth(iter) < 1) {
continue;
}
//double px = event[iter->id].px;
//double py = event[iter->id].py;
//double pz = event[iter->id].pz;
double px = iter->pCorr.px;
double py = iter->pCorr.py;
double pz = iter->pCorr.pz;
//cout << "RAD "<< tr.depth(iter)<<" "<< iter->id <<" "<<iter->pCorr.e << endl;
double pNorm = sqrt(px*px+py*py+pz*pz);
if(pNorm < 1e-5) {
px=py=pz=0;
}
else {
px/=pNorm;
py/=pNorm;
pz/=pNorm;
}
//if(pNorm < 1e-6) {
//cout <<"Holka "<< iter->id << " " << pNorm <<" "<< event.size()<< endl;
//cout <<"depth "<< tr.depth(iter) << endl;
//exit(1);
//}
double scaleDiff;
tree<Edge>::iterator child = iter;
++child;
double Scale = max(lastScaleEm, event[iter->id].scale);
double ScaleChild = max(lastScaleEm, event[child->id].scale);
if(child != tr.end() && tr.depth(child) > tr.depth(iter)) {
//scaleDiff = event[iter->id].scale - event[child->id].scale;
scaleDiff = abs( log(Scale/lastScale) - log(ScaleChild/lastScale) );
}
else {
//scaleDiff = event[iter->id].scale;
if(!iter->isFixed) {
if(event[iter->id].pdg == 21 || abs(event[iter->id].pdg)<6)
scaleDiff = abs( log(Scale/lastScale) );
else
scaleDiff = abs( log(Scale/lastScaleEm) );
}
else {
scaleDiff = abs( log(Scale/event[idHard3].scale) );
}
}
//cout << idHard1 <<" "<< event[idHard1].scale << endl;
//cout << idHard2 <<" "<< event[idHard2].scale << endl;
//cout << idHard3 <<" "<< event[idHard3].scale << endl;
//cout << idHard4 <<" "<< event[idHard4].scale << endl;
//exit(1);
//scaleDiff = log(scaleDiff/
//cout <<"HELENKAaaa "<<iter->id<<" "<< event[iter->id].pz <<" "<< event[iter->id].scale <<" : "<<scaleDiff << endl;
tree<Edge>::iterator par = tr.parent(iter);
//cout <<"Marketka "<< iter->id << " " << scaleDiff << endl;
iter->point.x = par->point.x + scaleDiff * px;
iter->point.y = par->point.y + scaleDiff * py;
iter->point.z = par->point.z + scaleDiff * pz;
//cout << "Elza " << scaleDiff << endl;
//cout <<"RADEK "<< tr.depth(iter) <<" "<<event[iter->id].scale<<" :: "<< iter->point.x <<" "<< iter->point.y <<" "<< iter->point.z << endl;
//Save shifts
if(iter->id == lastFix1 ) {
Shift1 = iter->point;
cout << "Hard1 found" << endl;
}
if(iter->id == lastFix2 ) {
Shift2 = iter->point;
cout << "Hard2 found" << endl;
}
}
//cout <<"PUSA "<< Shift1.z << " "<< Shift2.z << endl;
cout << "IdHard1, IdHard2 "<< idHard1 << " "<< idHard2 << endl;
cout << "IdLast1, IdLast2 "<< lastFix1 << " "<< lastFix2 << endl;
//cout <<"Hard2 "<< idHard1 <<" "<< idHard2 << endl;
//exit(0);
//Aply shifts to ISR
iter = tr.begin();
do {
iter->point.x -= Shift1.x;
iter->point.y -= Shift1.y;
iter->point.z -= Shift1.z;
++iter;
} while(tr.depth(iter) > 0);
do {
iter->point.x -= Shift2.x;
iter->point.y -= Shift2.y;
iter->point.z -= Shift2.z;
++iter;
} while(tr.depth(iter) > 0);
cout << "Shift1 "<< Shift1.x<<" "<<Shift1.y<<" "<<Shift1.z << endl;
cout << "Shift2 "<< Shift2.x<<" "<<Shift2.y<<" "<<Shift2.z << endl;
int maxCol= 0;
for(tree<Edge>::iterator it = tr.begin(); it != tr.end(); ++it) {
maxCol = max(maxCol, it->col);
maxCol = max(maxCol, it->acol);
}
maxCol-=100-3;
partonColors = CreateColors(maxCol);
}
void Tree::AddHard()
{
double xmin1, xmax1, ymin1, ymax1;
double xmin2, xmax2, ymin2, ymax2;
double xmin3, xmax3, ymin3, ymax3;
double xmin4, xmax4, ymin4, ymax4;
Limits(0, xmin1, xmax1, ymin1, ymax1);
Limits(1, xmin2, xmax2, ymin2, ymax2);
Limits(2, xmin3, xmax3, ymin3, ymax3);
Limits(3, xmin4, xmax4, ymin4, ymax4);
cout << "Limits1"<<" "<< xmin1<<" "<<xmax1<<" "<<ymin1<<" "<<ymax1<<endl;
cout << "Limits2"<<" "<< xmin2<<" "<<xmax2<<" "<<ymin2<<" "<<ymax2<<endl;
cout << "Limits3"<<" "<< xmin3<<" "<<xmax3<<" "<<ymin3<<" "<<ymax3<<endl;
cout << "Limits4"<<" "<< xmin4<<" "<<xmax4<<" "<<ymin4<<" "<<ymax4<<endl;
double sizeLeft = min(min(xmin3, xmin4), -2.);
double sizeRight = max(max(xmax3, xmax4), 2.);
//double size
//cout << xmin << " "<< xmax << " "<< ymin << " "<< ymax << endl;
Shift(0, sizeLeft -xmax1 , 0);
Shift(1, sizeRight-xmin2 , 0);
//Shift(2,
ChangeHardLeg(0,2);
ChangeHardLeg(1,2);
//CalcInterects(tr.begin());
}
void Tree::ImproveLayout()
{
//for(tree<Edge>::sibling_iterator it= tr.begin(); it != tr.end(); ++it)
double angle = 0.3;
for(int i = 0; i < 7; ++i) {
MarkFixed(angle);
bool isOK = CorrectIntersects(0);
if(isOK)
break;
angle *= 0.9;
}
cout <<"Corrections done " << endl;
AddHard();
}
bool Tree::CorrectIntersects(tree<Edge>::iterator itDo)
{
while(1) {
CalcLayout();
vector<tree<Edge>::iterator> comm = CalcInterects(itDo);
if(comm.size() == 0) break;
int last;
for(last=0; last < comm.size() && tr.depth(comm[0]) == tr.depth(comm[last]); ++last)
;
for(int i = 0; i < comm.size(); ++i)
cout << "RADEK " << i <<" "<< tr.depth(comm[i]) <<" "<<comm[i]->id<< endl;
cout << "LAST " << last << endl;
for(int i=0; i < last; ++i) {
//cout << "Ahoj " << comm[i] <<" "<< int(tr.is_valid(tr.begin(comm[i]) )) << endl;
do {
for(tree<Edge>::sibling_iterator it = tr.begin(comm[i]); it != tr.end(comm[i]); ++it) {
it->angle = (it->angle <0.001) ? 0 : it->angle+0.04;
cout << "Angle " << it->angle << endl;
if(it->angle *180./M_PI> 150)
return false;
}
CalcLayout();
cout << "Common " << comm[i]->id << endl;
} while ( CalcInterects(comm[i]).size() != 0 );
}
cout << "DONE" << endl;
}
return true;
}
vector<tree<Edge>::iterator> Tree::CalcInterects(tree<Edge>::iterator base)
{
vector<tree<Edge>::iterator> common;
//cout << "Start: Intersect checking" << endl;
int minDepth = -1;
tree<Edge>::iterator stop;
if(base == 0) {
base = tr.begin();
stop = tr.end();
}
else {
stop = tr.next_sibling(base);
minDepth = tr.depth(base);
}
for(tree<Edge>::iterator it1 = base; it1 != stop && tr.depth(it1) >=minDepth; ++it1)
for(tree<Edge>::iterator it2 = it1; it2 != stop && tr.depth(it2) >=minDepth; ++it2) {
if(tr.depth(it1)>0 && tr.depth(it2)>0 && isIntersect(it1, it2) ) {
tree<Edge>::iterator it = tr.lowest_common_ancestor(it1, it2);
common.push_back(it);
cout << "There is intersect "<<it->id<<" : "<<it1->id<<" "<<it2->id << endl;
}
}
//cout << "End: Intersect checking" << endl;
sort(common.begin(), common.end(), [&](tree<Edge>::iterator a, tree<Edge>::iterator b) {return a->id > b->id;} );
auto lastIt = std::unique(common.begin(), common.end() );
common.erase(lastIt, common.end());
sort(common.begin(), common.end(), [&](tree<Edge>::iterator a, tree<Edge>::iterator b) {return tr.depth(a) > tr.depth(b);} );
/*
sort(common.begin(), common.end(), [&](tree<Edge>::iterator a, tree<Edge>::iterator b) {return tr.depth(a) > tr.depth(b);} );
auto lastIt = std::unique(common.begin(), common.end(), [&](tree<Edge>::iterator a, tree<Edge>::iterator b) {return tr.depth(a) > tr.depth(b);} );
common.erase(lastIt, common.end());
*/
return common;
}
/*
void Tree::plotHard()
{
TEllipse *el1 = new TEllipse(0.0,0.0,2);
el1->Draw();
TPaveText *pt1 = new TPaveText(-2, -0.5, -0.5, 0.5 );
pt1->SetBorderSize(0);
pt1->SetFillStyle(0);
pt1->AddText( GetNamePDG(event[idHard1].pdg).c_str() );
pt1->Draw();
TPaveText *pt2 = new TPaveText(0.5, -0.5, 2, 0.5 );
pt2->SetBorderSize(0);
pt2->SetFillStyle(0);
pt2->AddText(GetNamePDG(event[idHard2].pdg).c_str() );
pt2->Draw();
TPaveText *pt3 = new TPaveText(-1, 1, 1, 2 );
pt3->SetBorderSize(0);
pt3->SetFillStyle(0);
pt3->AddText(GetNamePDG(event[idHard3].pdg).c_str() );
pt3->Draw();
TPaveText *pt4 = new TPaveText(-1, -1.7, 1, -0.7 );
pt4->SetBorderSize(0);
pt4->SetFillStyle(0);
pt4->AddText(GetNamePDG(event[idHard4].pdg).c_str() );
pt4->Draw();
//Draw hard lines
int col1, acol1, col2, acol2;
int col3, acol3, col4, acol4;
for(tree<Edge>::iterator it= tr.begin(); it != tr.end(); ++it) {
if(it->id == idHard1) {
col1 = it->col;
acol1 = it->acol;
}
if(it->id == idHard2) {
col2 = it->col;
acol2 = it->acol;
}
if(it->id == idHard3) {
col3 = it->col;
acol3 = it->acol;
}
if(it->id == idHard4) {
col4 = it->col;
acol4 = it->acol;
}
}
//idHard1
//idHard2
//idHard3
//idHard4
}
*/
/*
void Tree::plot()
{
//can = new TCanvas("can", "Canvas", 400, 400);
gPad->Range(-30,-30,30,30);
gPad->Clear();
plotHard();
//CreateColors();
TLine *line = new TLine;
tree<Edge>::iterator itS= tr.begin();
for(; itS != tr.end(); ++itS) {
if( tr.depth(itS) == 0 ) continue;
tree<Edge>::iterator par = tr.parent(itS);
//cout << "RADEK " << itS->id <<" : " << itS->x <<" "<< itS->y << endl;
double nX = itS->y - par->y;
double nY =-(itS->x - par->x);
double ll = sqrt(nX*nX+nY*nY);
nX *= 0.10/ll;
nY *= 0.10/ll;
//cout << "ID,col,acol "<< itS->id<<" "<<event[itS->id].pdg<<" "<< itS->col <<" "<< itS->acol << endl;
TPaveText *pt = new TPaveText(itS->x, itS->y, itS->x+1, itS->y+0.5 );
pt->SetBorderSize(0);
pt->SetFillStyle(0);
//pt->AddText(TString::Format("%d,%d", itS->col-100, itS->acol-100) );
//pt->AddText(TString::Format("%d", event[itS->id].pdg) );
pt->AddText( GetNamePDG(event[itS->id].pdg).c_str() );
pt->Draw();
//TLatex pL;
//pL.DrawLatex(itS->x, itS->y, GetNamePDG(event[itS->id].pdg).c_str() );
int col, acol;
col = itS->col-100;
acol = itS->acol-100;
//if(col >=100) col+=420;
//if(acol >=100) acol+=420;
if(itS->col != 0) {
line->SetLineColor(kBlack);
line->SetLineColor(1500+col);
//line->SetLineStyle(3);
line->DrawLine(par->x, par->y, itS->x, itS->y );
}
if(itS->acol != 0) {
line->SetLineColor(kBlack);
line->SetLineColor(1500+acol);
//line->SetLineStyle(3);
line->DrawLine(par->x+nX, par->y+nY, itS->x+nX, itS->y+nY );
}
//If particle is color neutral
if(itS->col == 0 && itS->acol == 0) {
if( abs(event[itS->id].pdg) <= 6 || 11<=abs(event[itS->id].pdg) && abs(event[itS->id].pdg) <= 18 ) {
//line->SetLineColor(kRed);
//line->SetLineColor(col);
//line->DrawLine(par->x, par->y, itS->x, itS->y );
string type = event[itS->id].pdg > 0 ? "->-" : "-<-";
TArrow *arr = new TArrow(par->x, par->y, itS->x, itS->y, 0.003, type.c_str());
arr->SetLineColor(kRed);
arr->Draw();
}
else if( 21 <= event[itS->id].pdg && event[itS->id].pdg <= 24){
TCurlyLine *line = new TCurlyLine(par->x, par->y, itS->x, itS->y );
line->SetLineColor(kBlack);
//line->SetLineColor(col);
line->SetWaveLength(0.003);
line->SetAmplitude(0.001);
if( event[itS->id].pdg != 21 )
line->SetWavy();
line->Draw();
}
}
}
//can->SaveAs("ahoj.eps");
}
*/
#if 0
void Tree::plotFeyn3D()
{
tree<Edge>::iterator iter = tr.begin();
//iter = tr.next_sibling(iter);
//iter = tr.next_sibling(iter);
//iter = tr.next_sibling(iter);
int id1 = FindStart(idHard1);
int id2 = FindStart(idHard2);
int id3 = idHard3;
int id4 = idHard4;
bool plotISR1 = Settings::Instance().getISR1();
bool plotISR2 = Settings::Instance().getISR2();
bool plotFSR1 = Settings::Instance().getFSR1();
bool plotFSR2 = Settings::Instance().getFSR2();
bool sameWidth = int(Settings::Instance().widthType) == 1;
bool plotColLines= int(Settings::Instance().colorType) == 1;
double jetsR = Settings::Instance().getJetsR();
int IdFocus = Settings::Instance().getFocusId();
Color col;
//cout <<"RADEK start " << endl;
int cat = 0;
for(; iter != tr.end(); ++iter) {
if(iter->id == id1 ) cat = 1;
if(iter->id == id2 ) cat = 2;
if(iter->id == id3 ) cat = 3;
if(iter->id == id4 ) cat = 4;
if(cat == 1) { col.r =1.0; col.g=1.0; col.b=0.0; }
if(cat == 2) { col.r =1.0; col.g=1.0; col.b=0.0; }
if(cat == 3) { col.r =0.0; col.g=1.0; col.b=0.0; }
if(cat == 4) { col.r =0.0; col.g=1.0; col.b=0.0; }
col.g = iter->isFixed ? 0.5 : 1;
if( tr.depth(iter) < 1 ) continue;
tree<Edge>::iterator par = tr.parent(iter);
tree<Edge>::iterator child = iter;
++child;
bool isFinal = tr.depth(child) <= tr.depth(iter) && !iter->isFixed;
double pMy = abs(par->pCorr.e);
float wid = sameWidth ? 0.02: 0.002*sqrt(pMy);
//col.r=0; col.g=1; col.b=0;
if( (cat==1 && plotISR1) || (cat==2 && plotISR2) || (cat==3 && plotFSR1) || (cat==4 && plotFSR2) ) {
double ll = sqrt( pow(par->point.x-iter->point.x,2)+pow(par->point.y-iter->point.y,2)+pow(par->point.z-iter->point.z,2) );
//cout <<"Drawing cat " << cat <<" " <<event[iter->id].pdg <<" "<< ll<<endl;// col.r<<" "<< col.g<<" "<<col.b << endl;
//cout <<"S "<< par->point.x<<" "<<par->point.y<<" "<<par->point.z<<endl;
//cout <<"E "<< iter->point.x<<" "<<iter->point.y<<" "<<iter->point.z<<endl;
Color colTemp = col;
if(jetsR > 0.15) {
if(jetsMap.count(iter->id) > 0)
colTemp = jetsColors[ jetsMap[iter->id] ];
else
colTemp = Color(1,0.5,0);
}
if(iter->id == IdFocus)
colTemp = Color(1,1,1);
Color c1, c2;
c1 = c2 = colTemp;
if( plotColLines && jetsR <= 0.15) {
c1 = partonColors[ event[iter->id].col - 100 ];
c2 = partonColors[ event[iter->id].acol - 100 ];
if(event[iter->id].acol == 0)
c2 = c1;
if(event[iter->id].col == 0)
c1 = c2;
}
logo->DrawCylinder(event[iter->id].pdg, wid, c1, c2, par->point, iter->point, 4.*isFinal*wid );
//cout <<"Plotting line" << endl;
//DrawLine( wid/*sqrt(pMy/3.)*/, colTemp, par->point, iter->point );
}
//static int kk= 0;
//if(kk < 27)
//logo->DrawCylinder(float(0.05*wid), col, par->point, iter->point );
//kk++;
if(tr.depth(iter) >= 2) {
tree<Edge>::iterator s1 = tr.previous_sibling(iter);
tree<Edge>::iterator s2 = tr.next_sibling(iter);
if(s1 == 0 && s2 == 0)
continue;
//cout <<"org "<< event[par->id].px <<" "<<event[par->id].py <<" "<< event[par->id].pz << endl;
//if(s1 != 0) {
//cout <<"sum "<< event[s1->id].px+event[iter->id].px <<" "<<event[s1->id].py+event[iter->id].py <<" "<< event[s1->id].pz+event[iter->id].pz << endl;
//}
//if(s2 != 0)
//cout <<"sum "<< event[s2->id].px+event[iter->id].px <<" "<<event[s2->id].py+event[iter->id].py <<" "<< event[s2->id].pz+event[iter->id].pz << endl;
//cout <<"org "<< par->pCorr.x<<" "<<par->pCorr.y <<" "<< par->pCorr.z << endl;
//if(s1 != 0) {
//cout <<"sum "<< s1->pCorr.x+iter->pCorr.x <<" "<<s1->pCorr.y+iter->pCorr.y <<" "<< s1->pCorr.z+iter->pCorr.z << endl;
//}
//if(s2 != 0)
//cout <<"sum "<< s2->pCorr.x+iter->pCorr.x <<" "<<s2->pCorr.y+iter->pCorr.y <<" "<< s2->pCorr.z+iter->pCorr.z << endl;
//cout << endl;
}
//cout << tr.depth(iter)<<","<<event[iter->id].scale<<" || "<<par->point.x<<","<<par->point.y <<","<<par->point.z<<" ::: "<<iter->point.x<<","<<iter->point.y<<","<<iter->point.z << endl;
//if(iter->id == idHard1) cout << "Hard1 " << iter->pCorr.px<<" "<< iter->pCorr.py<<" "<<iter->pCorr.pz <<" "<<iter->pCorr.e << endl;
//if(iter->id == idHard2) cout << "Hard2 " << iter->pCorr.px<<" "<< iter->pCorr.py<<" "<<iter->pCorr.pz <<" "<<iter->pCorr.e << endl;
//if(iter->id == idHard3) cout << "Hard3 " << iter->pCorr.px<<" "<< iter->pCorr.py<<" "<<iter->pCorr.pz <<" "<<iter->pCorr.e << endl;
//if(iter->id == idHard4) cout << "Hard4 " << iter->pCorr.px<<" "<< iter->pCorr.py<<" "<<iter->pCorr.pz <<" "<<iter->pCorr.e << endl;
}
cout <<"RADEK end " << endl;
glColor3d(0.0, 1, 0);
glPointSize(10);
glBegin(GL_POINTS);
glVertex3d(0,0,0);
glEnd();
//Draw color lines
if(showColLines) {
map<int,int> colConnections;
for(tree<Edge>::leaf_iterator it = tr.begin(); it != tr.end(); ++it) {
if(it->id == idHard1 || it->id == idHard2) continue;
int reconWith[2] = {-1, -1};
if(event[it->id].col != 0) {
if(colConnections.count(event[it->id].col ) ) {
reconWith[0] = colConnections[event[it->id].col];
}
else {
colConnections[event[it->id].col] = it->id;
}
}
if(event[it->id].acol != 0) {
if(colConnections.count(event[it->id].acol ) ) {
reconWith[1] = colConnections[event[it->id].acol];
}
else {
colConnections[event[it->id].acol] = it->id;
}
}
for(int a = 0; a < 2; ++a) {
if(reconWith[a] == -1) continue;
tree<Edge>::leaf_iterator it2;
for(it2 = tr.begin(); it2 != tr.end(); ++it2)
if(it2->id == reconWith[a]) break;
Color colNow(0,1,0);
//DrawLine( 1, colNow, it->point, it2->point );
}
}
}
/*
iter = tr.begin();
for(; iter != tr.end(); ++iter) {
//if( tr.depth(iter) < 1 ) continue;
if(iter->id == id1) break;
}
Vec3 lineL1 = iter->point;
Vec3 lineR1 ( iter->point.x, iter->point.y, -iter->point.z);
col.r = 0; col.g=1; col.b = 0;
DrawLine( 2, col, lineL1, lineR1 );
iter = tr.begin();
for(; iter != tr.end(); ++iter) {
//if( tr.depth(iter) < 1 ) continue;
if(iter->id == id2) break;
}
Vec3 lineL2 = iter->point;
Vec3 lineR2 ( iter->point.x, iter->point.y, -iter->point.z);
col.r = 0; col.g=1; col.b = 0;
DrawLine( 2, col, lineL2, lineR2 );
*/
}
#endif
void Tree::plotFeyn(bool showNames, bool showScales)
{
//plotHard();
/*
cout << "All Entries Start " << endl;
tree<Edge>::iterator itSS= tr.begin();
for(; itSS != tr.end(); ++itSS) {
cout <<"Ids "<< itSS->id << endl;
}
cout << "All Entries End " << endl;
exit(0);
*/
int id1 = FindStart(idHard1);
int id2 = FindStart(idHard2);
int id3 = idHard3;
int id4 = idHard4;
int IdFocus = Settings::Instance().getFocusId();
double jetsR = Settings::Instance().getJetsR();
Color col;
cout <<"RADEK start " << endl;
int cat = 0;
tree<Edge>::iterator itS;
for(itS= tr.begin(); itS != tr.end(); ++itS) {
if( tr.depth(itS) == 0 ) continue;
tree<Edge>::iterator par = tr.parent(itS);
if(itS->id == id1 ) cat = 1;
if(itS->id == id2 ) cat = 2;
if(itS->id == id3 ) cat = 3;
if(itS->id == id4 ) cat = 4;
if(cat == 1) { col.r =1.0; col.g=1.0; col.b=0.0; }
if(cat == 2) { col.r =1.0; col.g=1.0; col.b=0.0; }
if(cat == 3) { col.r =0.0; col.g=1.0; col.b=0.0; }
if(cat == 4) { col.r =0.0; col.g=1.0; col.b=0.0; }
col.g = itS->isFixed ? 0.5 : 1;
//TPaveText *pt = new TPaveText(itS->x, itS->y, itS->x+1, itS->y+0.5 );
//pt->SetBorderSize(0);
//pt->SetFillStyle(0);
//pt->AddText(TString::Format("%d,%d", itS->col-100, itS->acol-100) );
//pt->AddText(TString::Format("%d", event[itS->id].pdg) );
//pt->AddText(TString::Format("%d", itS->id) );
//pt->AddText( GetNamePDG(event[itS->id].pdg).c_str() );
//pt->Draw();
//TString str = TString::Format("%2.1f", event[itS->id].scale);
//displayText( par->x, par->y, 0, 0, 1, str.Data() );
//TString str = TString::Format("%d", event[itS->id].pdg);
//displayText( itS->x, itS->y, 0, 0, 1, str.Data() );
//TString str = TString::Format("%g", itS->pCorr.norm());
Color colTemp = col;
if(jetsR >0.15 && jetsMap.count(itS->id) > 0)
colTemp = jetsColors[ jetsMap[itS->id] ];
colTemp = (itS->id == IdFocus) ? Color(1,1,1) : colTemp;
//DrawLine(colTemp, par->x, par->y, itS->x, itS->y );
/* RADEK comment QT
QColor qCol;
qCol.setRgbF( colTemp.r, colTemp.g, colTemp.b );
QPen pp = painter->pen();
pp.setColor(qCol);
painter->setPen(pp);
//( (QPen) painter->pen() ).setColor(qCol);
if( event[itS->id].pdg == 21)
cout << "Drawing gluon" << endl;
//Diagram::DrawGluon(painter, 0.4, QPointF(par->x,par->y) , QPointF(itS->x, itS->y) );
else if(abs(event[itS->id].pdg) >= 22 && abs(event[itS->id].pdg) <= 24)
cout << "Drawing photon" << endl;
//Diagram::DrawPhoton(painter, 0.4, QPointF(par->x,par->y) , QPointF(itS->x, itS->y) );
else if( event[itS->id].pdg > 0 )
cout << "Drawing fermion" << endl;
//Diagram::DrawFermion(painter, QPointF(par->x,par->y) , QPointF(itS->x, itS->y) );
else
cout << "Drawing fermion" << endl;
//Diagram::DrawFermion(painter, QPointF(itS->x,itS->y) , QPointF(par->x, par->y) );
//TString str = TString::Format("%2.1f", event[itS->id].scale);
QFont font("Arial");
font.setPointSizeF(0.4);
painter->setFont(font);
if(showScales)
painter->drawText( QPointF(par->x, par->y), QString::number(event[itS->id].scale,'f',1) );
if(showNames) {
QString pName = event[itS->id].name.c_str();
pName.replace(QString("("), QString(""));
pName.replace(QString(")"), QString(""));
pName.replace(QString("bar"), QString("~"));
pName.replace(QString("gamma"), QString("A"));
pName.replace(QString("nu_tau"), QString("vt"));
pName.replace(QString("nu_mu"), QString("vm"));
pName.replace(QString("nu_e"), QString("ve"));
pName.replace(QString("tau"), QString("ta"));
painter->drawText( QPointF(itS->x, itS->y), pName );
}
*/
/*
int col = kBlack;
if( colorsMap.count(itS->id) > 0 ) {
col = colorsMap[itS->id];
cout << "Color is " << col << endl;
}
*/
if( abs(event[itS->id].pdg) <= 6 || 11<=abs(event[itS->id].pdg) && abs(event[itS->id].pdg) <= 18 ) {
//line->SetLineColor(kRed);
//line->SetLineColor(col);
//line->DrawLine(par->x, par->y, itS->x, itS->y );
string type = event[itS->id].pdg > 0 ? "->-" : "-<-";
TArrow *arr = new TArrow(par->x, par->y, itS->x, itS->y, 0.003, type.c_str());
arr->SetLineColor(kRed);
//arr->SetLineColor(col.r+col.g+col.b);
arr->Draw();
cout << "Helenka arrow " << par->x<<" "<< par->y<<" "<< itS->x <<" "<< itS->y << endl;
}
else if( 21 <= event[itS->id].pdg && event[itS->id].pdg <= 24){
TCurlyLine *line = new TCurlyLine(par->x, par->y, itS->x, itS->y );
line->SetLineColor(kBlack);
//line->SetLineColor(col.r+col.g+col.b);
line->SetWaveLength(0.003);
line->SetAmplitude(0.001);
if( event[itS->id].pdg != 21 )
line->SetWavy();
line->Draw();
cout << "Helenka line " << par->x<<" "<< par->y<<" "<< itS->x <<" "<< itS->y << endl;
}
}
/*
for(tree<Edge>::leaf_iterator it = tr.begin(); it != tr.end(); ++it) {
if(it->id == idHard1 || it->id == idHard2) continue;
int col = event[it->id].col;
int acol = event[it->id].acol;
col = (col ==0) ? 0 : col - 100;
acol = (acol==0) ? 0 : acol - 100;
TString str = TString::Format("%d,%d", col, acol);
displayText( it->x, it->y, 0, 1, 0, str.Data() );
}
*/
}
void Tree::PlotAll(string fName)
{
//read();
TCanvas *can = new TCanvas("can", "Canvas", 1200, 1200);
gPad->Range(-30,-30,30,30);
gPad->Clear();
for(int k = 0; k < 100; ++k) {
bool status = fill(k);
if(status == false) {
break;
}
CalcLayout();
ImproveLayout();
plotFeyn(true,true);
cout << "RADEK plotting " << k << endl;
can->SaveAs(Form("diagrams/test_%d_%d.svg",eventId, k));
can->Clear();
}
/*
for(int k=0; k < 100; ++k) {
bool status = fill(k);
if(status == false) {
can->SaveAs("ahoj.png)");
break;
}
CalcLayout();
ImproveLayout();
plotFeyn(true,true);
cout << "RADEK plotting " << k << endl;
can->SaveAs(fName.c_str());
return;
if(k==0)
can->SaveAs("ahoj.png(");
else
can->SaveAs("ahoj.png");
}
*/
}
bool compare_pt (fastjet::PseudoJet i, fastjet::PseudoJet j) { return (i.perp()>=j.perp()); }
void Tree::PlotEtaPhi()
{
//bool status = fill(k);
for(tree<Edge>::leaf_iterator it = tr.begin(); it != tr.end(); ++it) {
if(it->id == idHard1 || it->id == idHard2) continue;
//if(!( event[it->id].pdg == 21 || abs(event[it->id].pdg) <= 6) ) continue;
double pt, eta, phi;
GetPtEtaPhi(it->id, pt, eta, phi);
Color colTemp(0,0,0);
if(jetsR >0.15 && jetsMap.count(it->id) > 0)
colTemp = jetsColors[ jetsMap[it->id] ];
//DrawPoint(sqrt(pt/1.), colTemp, eta, phi);
}
}
void Tree::GetPtEtaPhi(int indx, double &pt, double &eta, double &phi)
{
double px = event[indx].px;
double py = event[indx].py;
double pz = event[indx].pz;
double e = event[indx].e;
pt = sqrt( px*px + py*py );
phi = atan2(py, px);
double theta = atan2(pt, pz);
//eta = -log(tan(theta/2));
eta = 0.5*log( (e+pz)/(e-pz) );
}
void Tree::PlotStrings()
{
double pt, eta, phi;
double ptL, etaL, phiL;
//cout << "RADEK " << strings.size()<<" "<< strings[0].hadrons.size() << endl;
for(int i = 1; i < strings.size() && i<=1; ++i) {
for(int j = 0; j < strings[i].partons.size(); ++j) {
int indx = strings[i].partons[j];
GetPtEtaPhi(indx, pt, eta, phi);
Color colTemp(0,0,0);
//DrawPoint(sqrt(pt/1.), colTemp, eta, phi);
if( j >= 1 ) {
int indxL = strings[i].partons[j-1];
GetPtEtaPhi(indxL, ptL, etaL, phiL);
//DrawLine(colTemp, etaL, phiL, eta, phi);
}
}
for(int j = 0; j < strings[i].hadrons.size(); ++j) {
int indx = strings[i].hadrons[j];
GetPtEtaPhi(indx, pt, eta, phi);
Color colTemp(0,1,0);
//DrawPoint(sqrt(pt/1.), colTemp, eta, phi);
//continue;
if( j >= 1 ) {
int indxL = strings[i].hadrons[j-1];
GetPtEtaPhi(indxL, ptL, etaL, phiL);
//DrawLine(colTemp, etaL, phiL, eta, phi);
}
}
}
}
/*
void Tree::Plot3D()
{
//bool status = fill(k);
for(tree<Edge>::leaf_iterator it = tr.begin(); it != tr.end(); ++it) {
if(it->id == idHard1 || it->id == idHard2) continue;
//if(!( event[it->id].pdg == 21 || abs(event[it->id].pdg) <= 6) ) continue;
double px = event[it->id].px;
double py = event[it->id].py;
double pz = event[it->id].pz;
double pt = sqrt( px*px + py*py );
double p = sqrt(pt*pt + pz*pz);
double phi = atan2(py, px);
double theta = atan2(pt, pz);
double eta = -log(tan(theta/2));
//DrawVector(sqrt(p/1.), px/p, py/p, pz/p);
}
glLineWidth(20);
glColor3d(0.0, 0.0, 1.0);
glBegin(GL_LINES);
glVertex3d(0, 0, -5);
glVertex3d(0, 0, 5);
glEnd();
}
*/
void Tree::FindJets(double R)
{
fastjet::JetDefinition *jet_def = new fastjet::JetDefinition(fastjet::antikt_algorithm, R, fastjet::pt_scheme);
vector<fastjet::PseudoJet> partons;
//fill jets -- start
partons.clear();
for(tree<Edge>::leaf_iterator it = tr.begin(); it != tr.end(); ++it) {
if(it->id == idHard1 || it->id == idHard2) continue;
fastjet::PseudoJet jet = fastjet::PseudoJet( it->pCorr.px, it->pCorr.py, it->pCorr.pz, it->pCorr.e );
jet.set_user_index( it->id );
partons.push_back( jet );
}
//vector<int> colors(i+2);
fastjet::ClusterSequence cs(partons, *jet_def);
vector<fastjet::PseudoJet> jets_in = cs.inclusive_jets(2.0);
std::sort (jets_in.begin(), jets_in.end(), compare_pt);
Njets = jets_in.size();
jetsMap.clear();
for(int j = 0; j < jets_in.size(); ++j) {
vector<fastjet::PseudoJet> constituents = jets_in[j].constituents();
for(int l = 0; l < constituents.size(); ++l) {
cout << j <<" "<< constituents[l].user_index() << endl;
jetsMap[constituents[l].user_index()] = j+1;
//if(j+2 <10)
//colorsMap[constituents[l].user_index()] = j+2;
//else
//colorsMap[constituents[l].user_index()] = j+3;
}
}
//fill jets -- end
cout << "Creating color array - start : "<< Njets+2 << endl;
jetsColors = CreateColors(Njets+2);
cout << "Creating color array - end" << endl;
delete jet_def;
}
double distance(Color c1, Color c2)
{
double Matr[3][3] ={
{ 0.299, 0.587, 0.114},
{-0.14713, -0.28886, 0.436},
{0.615, -0.51499, -0.10001}};
double y1, u1, v1, y2, u2, v2;
y1 = Matr[0][0]*c1.r+Matr[0][1]*c1.g+Matr[0][2]*c1.b;
u1 = Matr[1][0]*c1.r+Matr[1][1]*c1.g+Matr[1][2]*c1.b;
v1 = Matr[2][0]*c1.r+Matr[2][1]*c1.g+Matr[2][2]*c1.b;
y2 = Matr[0][0]*c2.r+Matr[0][1]*c2.g+Matr[0][2]*c2.b;
u2 = Matr[1][0]*c2.r+Matr[1][1]*c2.g+Matr[1][2]*c2.b;
v2 = Matr[2][0]*c2.r+Matr[2][1]*c2.g+Matr[2][2]*c2.b;
return ( (y1-y2)*(y1-y2) + (u1-u2)*(u1-u2) + (v1-v2)*(v1-v2) );
}
/*
Edge Tree::findFocusId(QVector3D p1, QVector3D p2)
{
tree<Edge>::iterator iter;
//iter = tr.next_sibling(iter);
//iter = tr.next_sibling(iter);
//iter = tr.next_sibling(iter);
int id1 = FindStart(idHard1);
int id2 = FindStart(idHard2);
int id3 = idHard3;
int id4 = idHard4;
bool plotISR1 = Settings::Instance().getISR1();
bool plotISR2 = Settings::Instance().getISR2();
bool plotFSR1 = Settings::Instance().getFSR1();
bool plotFSR2 = Settings::Instance().getFSR2();
bool sameWidth = int(Settings::Instance().widthType) == 1;
int lastIdFocus = Settings::Instance().getFocusId();
int cat = 0;
double minDistance = 1e20;
int minId = -1;
tree<Edge>::iterator minIter;
for(iter=tr.begin(); iter != tr.end(); ++iter) {
if(iter->id == id1 ) cat = 1;
if(iter->id == id2 ) cat = 2;
if(iter->id == id3 ) cat = 3;
if(iter->id == id4 ) cat = 4;
if( tr.depth(iter) < 1 ) continue;
tree<Edge>::iterator par = tr.parent(iter);
double pMy = abs(par->pCorr.e);
float wid = sameWidth ? 0.02: 0.002*sqrt(pMy);
//col.r=0; col.g=1; col.b=0;
if( (cat==1 && plotISR1) || (cat==2 && plotISR2) || (cat==3 && plotFSR1) || (cat==4 && plotFSR2) ) {
QVector3D a(par->point.x, par->point.y, par->point.z);
QVector3D b(iter->point.x, iter->point.y, iter->point.z);
double dist = distance(a, b, p1, p2) / wid;
if(dist < minDistance) {
minDistance = dist;
minId = iter->id;
minIter = iter;
}
}
}
if(minId == lastIdFocus )
Settings::Instance().setFocusId(-1);
else {
Settings::Instance().setFocusId(minId);
return *minIter;
}
}
*/
Edge Tree::findFocusId(QVector2D v)
{
tree<Edge>::iterator iter;
//iter = tr.next_sibling(iter);
//iter = tr.next_sibling(iter);
//iter = tr.next_sibling(iter);
int lastIdFocus = Settings::Instance().getFocusId();
double minDistance = 1e20;
int minId = -1;
tree<Edge>::iterator minIter;
for(iter=tr.begin(); iter != tr.end(); ++iter) {
if( tr.depth(iter) < 1 ) continue;
tree<Edge>::iterator par = tr.parent(iter);
QVector2D a( par->x, par->y);
QVector2D b( iter->x, iter->y);
double t = QVector2D::dotProduct(b-a, v-a)/ (b-a).lengthSquared();
if(t > 1)
t = 1;
else if(t < 0)
t = 0;
QVector2D pos = (1-t)*a + t*b;
double dist = (pos-v).length();
if(dist < minDistance) {
minDistance = dist;
minId = iter->id;
minIter = iter;
}
}
if(minId == lastIdFocus )
Settings::Instance().setFocusId(-1);
else {
Settings::Instance().setFocusId(minId);
return *minIter;
}
}
|
033183cc9b751ef105e478067485c39e19935644
|
23012559f8099fbb6a4c86d3d86ab5c5212de48e
|
/kasten/gui/io/streamencoder/viewtext/bordercolumntextrenderer.cpp
|
6cad1598b8e1146684f351b6bb81f64374bcb12e
|
[] |
no_license
|
KDE/okteta
|
a916cdb9e16cdc6c48a756205604df600a3b271c
|
cb7d9884a52d0c08c1496d4a3578f5dfe0c2a404
|
refs/heads/master
| 2023-09-01T09:33:47.395026
| 2023-08-29T04:33:32
| 2023-08-29T04:33:32
| 42,718,476
| 92
| 9
| null | 2020-12-29T18:58:56
| 2015-09-18T11:44:12
|
C++
|
UTF-8
|
C++
| false
| false
| 727
|
cpp
|
bordercolumntextrenderer.cpp
|
/*
This file is part of the Okteta Kasten module, made within the KDE community.
SPDX-FileCopyrightText: 2003, 2008 Friedrich W. H. Kossebau <kossebau@kde.org>
SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
*/
#include "bordercolumntextrenderer.hpp"
// Qt
#include <QTextStream>
namespace Kasten {
void BorderColumnTextRenderer::renderFirstLine(QTextStream* stream, int lineIndex) const
{
Q_UNUSED(lineIndex)
render(stream);
}
void BorderColumnTextRenderer::renderNextLine(QTextStream* stream, bool isSubline) const
{
Q_UNUSED(isSubline)
render(stream);
}
void BorderColumnTextRenderer::render(QTextStream* stream) const
{
*stream << " | ";
}
}
|
d038f73e916b638565b5ad18165d4598abc61ccd
|
f8c161b7bfc127385495890e5282df7eef58a6c1
|
/tests/src/astro/propagators/unitTestEnvironmentUpdater.cpp
|
4263255273100ab27ab6796241ffc14f74c10d09
|
[] |
permissive
|
Tudat/tudat
|
7c7d552e190a3360bde5ec8527a2f377a54ef288
|
02dbcb385be5a39e5dbc0563f0dc1219cbfb25ac
|
refs/heads/master
| 2023-04-27T19:16:07.061328
| 2022-11-30T14:33:12
| 2022-11-30T14:33:12
| 50,173,176
| 91
| 153
|
BSD-3-Clause
| 2023-04-15T18:33:02
| 2016-01-22T10:01:27
|
C++
|
UTF-8
|
C++
| false
| false
| 32,120
|
cpp
|
unitTestEnvironmentUpdater.cpp
|
/* Copyright (c) 2010-2019, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <limits>
#include <boost/test/unit_test.hpp>
#include <boost/make_shared.hpp>
#include <Eigen/Core>
#include "tudat/astro/basic_astro/physicalConstants.h"
#include "tudat/astro/basic_astro/unitConversions.h"
#include "tudat/astro/ephemerides/approximatePlanetPositions.h"
#include "tudat/astro/ephemerides/tabulatedEphemeris.h"
#include "tudat/simulation/propagation_setup/propagationSettings.h"
#include "tudat/simulation/propagation_setup/dynamicsSimulator.h"
#include "tudat/basics/testMacros.h"
#include "tudat/interface/spice/spiceEphemeris.h"
#include "tudat/io/basicInputOutput.h"
#include "tudat/math/interpolators/linearInterpolator.h"
#include "tudat/simulation/estimation_setup/createNumericalSimulator.h"
#include "tudat/simulation/environment_setup/createBodies.h"
#include "tudat/simulation/environment_setup/defaultBodies.h"
#include "tudat/astro/aerodynamics/testApolloCapsuleCoefficients.h"
namespace tudat
{
namespace unit_tests
{
using namespace simulation_setup;
using namespace basic_astrodynamics;
using namespace spice_interface;
using namespace input_output;
using namespace reference_frames;
using namespace propagators;
BOOST_AUTO_TEST_SUITE( test_environment_updater )
//! Test set up of point mass gravitational accelerations, both direct and third-body.
BOOST_AUTO_TEST_CASE( test_centralGravityEnvironmentUpdate )
{
double initialTime = 86400.0;
double finalTime = 2.0 * 86400.0;
// Load Spice kernels
spice_interface::loadStandardSpiceKernels( );
// Get settings for celestial bodies
BodyListSettings bodySettings;
bodySettings.addSettings( getDefaultSingleBodySettings( "Earth", 0.0, 10.0 * 86400.0 ), "Earth" );
bodySettings.addSettings( getDefaultSingleBodySettings( "Sun", 0.0,10.0 * 86400.0 ), "Sun" );
bodySettings.addSettings( getDefaultSingleBodySettings( "Moon", 0.0,10.0 * 86400.0 ), "Moon" );
bodySettings.addSettings( getDefaultSingleBodySettings( "Mars", 0.0,10.0 * 86400.0 ), "Mars" );
bodySettings.addSettings( getDefaultSingleBodySettings( "Venus", 0.0,10.0 * 86400.0 ), "Venus" );
// Create settings for sh gravity field.
double gravitationalParameter = 398600.4418E9;
Eigen::MatrixXd cosineCoefficients =
( Eigen::MatrixXd( 6, 6 ) <<
1.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
-4.841651437908150e-4, -2.066155090741760e-10, 2.439383573283130e-6, 0.0, 0.0, 0.0,
9.571612070934730e-7, 2.030462010478640e-6, 9.047878948095281e-7,
7.213217571215680e-7, 0.0, 0.0, 5.399658666389910e-7, -5.361573893888670e-7,
3.505016239626490e-7, 9.908567666723210e-7, -1.885196330230330e-7, 0.0,
6.867029137366810e-8, -6.292119230425290e-8, 6.520780431761640e-7,
-4.518471523288430e-7, -2.953287611756290e-7, 1.748117954960020e-7
).finished( );
Eigen::MatrixXd sineCoefficients =
( Eigen::MatrixXd( 6, 6 ) <<
0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 1.384413891379790e-9, -1.400273703859340e-6, 0.0, 0.0, 0.0,
0.0, 2.482004158568720e-7, -6.190054751776180e-7, 1.414349261929410e-6, 0.0, 0.0,
0.0, -4.735673465180860e-7, 6.624800262758290e-7, -2.009567235674520e-7,
3.088038821491940e-7, 0.0, 0.0, -9.436980733957690e-8, -3.233531925405220e-7,
-2.149554083060460e-7, 4.980705501023510e-8, -6.693799351801650e-7
).finished( );
bodySettings.at( "Earth" )->gravityFieldSettings = std::make_shared< SphericalHarmonicsGravityFieldSettings >(
gravitationalParameter, 6378.0E3, cosineCoefficients, sineCoefficients,
"IAU_Earth" );
// Create bodies
SystemOfBodies bodies = createSystemOfBodies( bodySettings );
// Define variables used in tests.
SelectedAccelerationMap accelerationSettingsMap;
std::map< std::string, std::string > centralBodies;
std::vector< std::string > propagatedBodyList;
std::vector< std::string > centralBodyList;
std::unordered_map< IntegratedStateType, Eigen::VectorXd > integratedStateToSet;
double testTime = 0.0;
{
// Define (arbitrary) test state.
Eigen::VectorXd testState = ( Eigen::VectorXd( 6 ) << 1.44E6, 2.234E8, -3343.246E7, 1.2E4, 1.344E3, -22.343E3 ).finished( );
integratedStateToSet[ translational_state ] = testState;
testTime = 2.0 * 86400.0;
// Test if environment is updated for inly central gravity accelerations
{
// Define accelerations
accelerationSettingsMap[ "Moon" ][ "Sun" ].push_back(
std::make_shared< AccelerationSettings >( point_mass_gravity ) );
accelerationSettingsMap[ "Moon" ][ "Earth" ].push_back(
std::make_shared< AccelerationSettings >( point_mass_gravity ) );
// Define origin of integration to be barycenter.
centralBodies[ "Moon" ] = "SSB";
propagatedBodyList.push_back( "Moon" );
centralBodyList.push_back( centralBodies[ "Moon" ] );
// Create accelerations
AccelerationMap accelerationsMap = createAccelerationModelsMap(
bodies, accelerationSettingsMap, centralBodies );
// Create environment update settings.
std::shared_ptr< SingleArcPropagatorSettings< double > > propagatorSettings =
std::make_shared< TranslationalStatePropagatorSettings< double > >(
centralBodyList, accelerationsMap, propagatedBodyList, getInitialStateOfBody(
"Moon", centralBodies[ "Moon" ], bodies, initialTime ), finalTime );
std::map< propagators::EnvironmentModelsToUpdate, std::vector< std::string > > environmentModelsToUpdate =
createEnvironmentUpdaterSettings< double >( propagatorSettings, bodies );
// Test update settings
BOOST_CHECK_EQUAL( environmentModelsToUpdate.size( ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.count( body_translational_state_update ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.at( body_translational_state_update ).size( ), 2 );
// Create and call updater.
std::shared_ptr< propagators::EnvironmentUpdater< double, double > > updater =
createEnvironmentUpdaterForDynamicalEquations< double, double >(
propagatorSettings, bodies );
updater->updateEnvironment( testTime, integratedStateToSet );
// Test if Earth, Sun and Moon are updated
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Earth" )->getState( ),
bodies.at( "Earth" )->getEphemeris( )->getCartesianState( testTime ),
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Sun" )->getState( ),
bodies.at( "Sun" )->getEphemeris( )->getCartesianState( testTime ),
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Moon" )->getState( ), testState,
std::numeric_limits< double >::epsilon( ) );
// Test if Mars is not updated
bool exceptionIsCaught = false;
try
{
bodies.at( "Mars" )->getState( );
}
catch( ... )
{
exceptionIsCaught = true;
}
BOOST_CHECK_EQUAL( exceptionIsCaught, true );
// Update environment to new time, and state from environment.
updater->updateEnvironment(
0.5 * testTime, std::unordered_map< IntegratedStateType, Eigen::VectorXd >( ), { translational_state } );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Earth" )->getState( ),
bodies.at( "Earth" )->getEphemeris( )->getCartesianState( 0.5 * testTime ),
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Sun" )->getState( ),
bodies.at( "Sun" )->getEphemeris( )->getCartesianState( 0.5 * testTime ),
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Moon" )->getState( ),
bodies.at( "Moon" )->getEphemeris( )->getCartesianState( 0.5 * testTime ),
std::numeric_limits< double >::epsilon( ) );
}
// Test third body acceleration updates.
{
accelerationSettingsMap.clear( );
centralBodies.clear( );
propagatedBodyList.clear( );
centralBodyList.clear( );
// Set acceleration models.
accelerationSettingsMap[ "Moon" ][ "Sun" ].push_back(
std::make_shared< AccelerationSettings >( point_mass_gravity ) );
accelerationSettingsMap[ "Moon" ][ "Mars" ].push_back(
std::make_shared< AccelerationSettings >( point_mass_gravity ) );
// Define origin of integration
centralBodies[ "Moon" ] = "Earth";
propagatedBodyList.push_back( "Moon" );
centralBodyList.push_back( centralBodies[ "Moon" ] );
// Create accelerations
AccelerationMap accelerationsMap = createAccelerationModelsMap(
bodies, accelerationSettingsMap, centralBodies );
// Create environment update settings.
std::shared_ptr< SingleArcPropagatorSettings< double > > propagatorSettings =
std::make_shared< TranslationalStatePropagatorSettings< double > >(
centralBodyList, accelerationsMap, propagatedBodyList, getInitialStateOfBody(
"Moon", centralBodies[ "Moon" ], bodies, initialTime ), finalTime );
std::map< propagators::EnvironmentModelsToUpdate, std::vector< std::string > > environmentModelsToUpdate =
createEnvironmentUpdaterSettings< double >( propagatorSettings, bodies );
// Test update settings
BOOST_CHECK_EQUAL( environmentModelsToUpdate.size( ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.count( body_translational_state_update ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.at( body_translational_state_update ).size( ), 3 );
// Create and call updater.
std::shared_ptr< propagators::EnvironmentUpdater< double, double > > updater =
createEnvironmentUpdaterForDynamicalEquations< double, double >(
propagatorSettings, bodies );
updater->updateEnvironment( testTime, integratedStateToSet );
// Test if Earth, Sun, Mars and Moon are updated
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Earth" )->getState( ),
bodies.at( "Earth" )->getEphemeris( )->getCartesianState( testTime ),
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Sun" )->getState( ),
bodies.at( "Sun" )->getEphemeris( )->getCartesianState( testTime ),
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Moon" )->getState( ), testState,
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Mars" )->getState( ),
bodies.at( "Mars" )->getEphemeris( )->getCartesianState( testTime ),
std::numeric_limits< double >::epsilon( ) );
// Test if Mars is not updated
bool exceptionIsCaught = false;
try
{
bodies.at( "Venus" )->getState( );
}
catch( ... )
{
exceptionIsCaught = true;
}
BOOST_CHECK_EQUAL( exceptionIsCaught, true );
// Update environment to new time, and state from environment.
updater->updateEnvironment(
0.5 * testTime, std::unordered_map< IntegratedStateType, Eigen::VectorXd >( ), { translational_state } );
}
// Test spherical harmonic acceleration update
{
accelerationSettingsMap.clear( );
centralBodies.clear( );
propagatedBodyList.clear( );
centralBodyList.clear( );
// Set acceleration models.
accelerationSettingsMap[ "Moon" ][ "Sun" ].push_back(
std::make_shared< AccelerationSettings >( point_mass_gravity ) );
accelerationSettingsMap[ "Moon" ][ "Earth" ].push_back(
std::make_shared< SphericalHarmonicAccelerationSettings >( 5, 5 ) );
accelerationSettingsMap[ "Moon" ][ "Mars" ].push_back(
std::make_shared< AccelerationSettings >( point_mass_gravity ) );
// Define origin of integration
centralBodies[ "Moon" ] = "Earth";
propagatedBodyList.push_back( "Moon" );
centralBodyList.push_back( centralBodies[ "Moon" ] );
// Create accelerations
AccelerationMap accelerationsMap = createAccelerationModelsMap(
bodies, accelerationSettingsMap, centralBodies );
// Create environment update settings.
std::shared_ptr< SingleArcPropagatorSettings< double > > propagatorSettings =
std::make_shared< TranslationalStatePropagatorSettings< double > >(
centralBodyList, accelerationsMap, propagatedBodyList, getInitialStateOfBody(
"Moon", centralBodies[ "Moon" ], bodies, initialTime ), finalTime );
std::map< propagators::EnvironmentModelsToUpdate, std::vector< std::string > > environmentModelsToUpdate =
createEnvironmentUpdaterSettings< double >( propagatorSettings, bodies );
// Test update settings
BOOST_CHECK_EQUAL( environmentModelsToUpdate.size( ), 3 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.count( body_translational_state_update ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.at( body_translational_state_update ).size( ), 3 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.count( body_rotational_state_update ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.at( body_rotational_state_update ).size( ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.count( spherical_harmonic_gravity_field_update ), 1 );
// Create and call updater.
std::shared_ptr< propagators::EnvironmentUpdater< double, double > > updater =
createEnvironmentUpdaterForDynamicalEquations< double, double >(
propagatorSettings, bodies );
updater->updateEnvironment( testTime, integratedStateToSet );
// Test if Earth, Sun, Mars and Moon are updated
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Earth" )->getState( ),
bodies.at( "Earth" )->getEphemeris( )->getCartesianState( testTime ),
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Sun" )->getState( ),
bodies.at( "Sun" )->getEphemeris( )->getCartesianState( testTime ),
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Moon" )->getState( ), testState,
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Mars" )->getState( ),
bodies.at( "Mars" )->getEphemeris( )->getCartesianState( testTime ),
std::numeric_limits< double >::epsilon( ) );
// Test if Mars is not updated
bool exceptionIsCaught = false;
try
{
bodies.at( "Venus" )->getState( );
}
catch( ... )
{
exceptionIsCaught = true;
}
BOOST_CHECK_EQUAL( exceptionIsCaught, true );
// Test if Earth rotation is updated
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Earth" )->getCurrentRotationToGlobalFrame( ).toRotationMatrix( ),
bodies.at( "Earth" )->getRotationalEphemeris( )->getRotationToBaseFrame( testTime ).toRotationMatrix( ),
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Earth" )->getCurrentRotationToLocalFrame( ).toRotationMatrix( ),
bodies.at( "Earth" )->getRotationalEphemeris( )->getRotationToTargetFrame( testTime ).toRotationMatrix( ),
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Earth" )->getCurrentRotationMatrixDerivativeToGlobalFrame( ),
bodies.at( "Earth" )->getRotationalEphemeris( )->getDerivativeOfRotationToBaseFrame( testTime ),
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Earth" )->getCurrentRotationMatrixDerivativeToLocalFrame( ),
bodies.at( "Earth" )->getRotationalEphemeris( )->getDerivativeOfRotationToTargetFrame( testTime ),
std::numeric_limits< double >::epsilon( ) );
// Test if Mars is not updated
exceptionIsCaught = false;
try
{
bodies.at( "Mars" )->getCurrentRotationToLocalFrame( ).toRotationMatrix( );
}
catch( ... )
{
exceptionIsCaught = true;
}
BOOST_CHECK_EQUAL( exceptionIsCaught, true );
exceptionIsCaught = false;
try
{
bodies.at( "Mars" )->getCurrentRotationMatrixDerivativeToGlobalFrame( );
}
catch( ... )
{
exceptionIsCaught = true;
}
BOOST_CHECK_EQUAL( exceptionIsCaught, true );
// Update environment to new time, and state from environment.
updater->updateEnvironment(
0.5 * testTime, std::unordered_map< IntegratedStateType, Eigen::VectorXd >( ), { translational_state } );
}
}
}
//! Dummy function to calculate mass as a function of time.
double getBodyMass( const double time )
{
return 1000.0 - 500.0 * ( time / ( 10.0 * 86400.0 ) );
}
//! Test radiation pressure acceleration
BOOST_AUTO_TEST_CASE( test_NonConservativeForceEnvironmentUpdate )
{
double initialTime = 86400.0;
double finalTime = 2.0 * 86400.0;
using namespace tudat::simulation_setup;
using namespace tudat;
// Load Spice kernels
spice_interface::loadStandardSpiceKernels( );
// Get settings for celestial bodies
BodyListSettings bodySettings;
bodySettings.addSettings( getDefaultSingleBodySettings( "Earth", 0.0, 10.0 * 86400.0 ), "Earth" );
bodySettings.addSettings( getDefaultSingleBodySettings( "Sun", 0.0,10.0 * 86400.0 ), "Sun" );
// Get settings for vehicle
double area = 2.34;
double coefficient = 1.2;
bodySettings.addSettings( "Vehicle" );
bodySettings.at( "Vehicle" )->radiationPressureSettings[ "Sun" ] =
std::make_shared< CannonBallRadiationPressureInterfaceSettings >( "Sun", area, coefficient );
bodySettings.at( "Vehicle" )->ephemerisSettings =
std::make_shared< KeplerEphemerisSettings >(
( Eigen::Vector6d( ) << 7000.0E3, 0.05, 0.3, 0.0, 0.0, 0.0 ).finished( ),
0.0, spice_interface::getBodyGravitationalParameter( "Earth" ), "Earth", "ECLIPJ2000" );
// Create bodies
SystemOfBodies bodies = createSystemOfBodies( bodySettings );
bodies.at( "Vehicle" )->setAerodynamicCoefficientInterface(
getApolloCoefficientInterface( ) );
bodies.at( "Vehicle" )->setBodyMassFunction( &getBodyMass );
// Define test time and state.
double testTime = 2.0 * 86400.0;
std::unordered_map< IntegratedStateType, Eigen::VectorXd > integratedStateToSet;
Eigen::VectorXd testState = 1.1 * bodies.at( "Vehicle" )->getEphemeris( )->getCartesianState( testTime ) +
bodies.at( "Earth" )->getEphemeris( )->getCartesianState( testTime );
integratedStateToSet[ translational_state ] = testState;
{
// Define settings for accelerations
SelectedAccelerationMap accelerationSettingsMap;
accelerationSettingsMap[ "Vehicle" ][ "Sun" ].push_back(
std::make_shared< AccelerationSettings >( cannon_ball_radiation_pressure ) );
// Define origin of integration
std::map< std::string, std::string > centralBodies;
centralBodies[ "Vehicle" ] = "Earth";
std::vector< std::string > propagatedBodyList;
propagatedBodyList.push_back( "Vehicle" );
std::vector< std::string > centralBodyList;
centralBodyList.push_back( centralBodies[ "Vehicle" ] );
// Create accelerations
AccelerationMap accelerationsMap = createAccelerationModelsMap(
bodies, accelerationSettingsMap, centralBodies );
// Create environment update settings.
std::shared_ptr< SingleArcPropagatorSettings< double > > propagatorSettings =
std::make_shared< TranslationalStatePropagatorSettings< double > >(
centralBodyList, accelerationsMap, propagatedBodyList, getInitialStateOfBody(
"Vehicle", centralBodies[ "Vehicle" ], bodies, initialTime ), finalTime );
std::map< propagators::EnvironmentModelsToUpdate, std::vector< std::string > > environmentModelsToUpdate =
createEnvironmentUpdaterSettings< double >( propagatorSettings, bodies );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.size( ), 3 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.count( body_translational_state_update ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.at( body_translational_state_update ).size( ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.count( radiation_pressure_interface_update ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.at( radiation_pressure_interface_update ).size( ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.count( body_mass_update ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.at( body_mass_update ).size( ), 1 );
std::shared_ptr< propagators::EnvironmentUpdater< double, double > > updater =
createEnvironmentUpdaterForDynamicalEquations< double, double >(
propagatorSettings, bodies );
updater->updateEnvironment( testTime, integratedStateToSet );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Sun" )->getState( ),
bodies.at( "Sun" )->getEphemeris( )->getCartesianState( testTime ),
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Vehicle" )->getState( ), testState,
std::numeric_limits< double >::epsilon( ) );
BOOST_CHECK_CLOSE_FRACTION(
bodies.at( "Vehicle" )->getBodyMass( ), getBodyMass( testTime ),
std::numeric_limits< double >::epsilon( ) );
updater->updateEnvironment(
0.5 * testTime, std::unordered_map< IntegratedStateType, Eigen::VectorXd >( ), { translational_state } );
}
{
// Define settings for accelerations
SelectedAccelerationMap accelerationSettingsMap;
accelerationSettingsMap[ "Vehicle" ][ "Sun" ].push_back(
std::make_shared< AccelerationSettings >( cannon_ball_radiation_pressure ) );
accelerationSettingsMap[ "Vehicle" ][ "Earth" ].push_back(
std::make_shared< AccelerationSettings >( aerodynamic ) );
// Define origin of integration
std::map< std::string, std::string > centralBodies;
centralBodies[ "Vehicle" ] = "Earth";
std::vector< std::string > propagatedBodyList;
propagatedBodyList.push_back( "Vehicle" );
std::vector< std::string > centralBodyList;
centralBodyList.push_back( centralBodies[ "Vehicle" ] );
// Create accelerations
AccelerationMap accelerationsMap = createAccelerationModelsMap(
bodies, accelerationSettingsMap, centralBodies );
// Define orientation angles.
std::shared_ptr< aerodynamics::AtmosphericFlightConditions > vehicleFlightConditions =
std::dynamic_pointer_cast< aerodynamics::AtmosphericFlightConditions >(
bodies.at( "Vehicle" )->getFlightConditions( ) );
double angleOfAttack = 35.0 * mathematical_constants::PI / 180.0;
double angleOfSideslip = -0.00322;
double bankAngle = 2.323432;
vehicleFlightConditions->getAerodynamicAngleCalculator( )->setOrientationAngleFunctions(
[ & ]( ){ return angleOfAttack; },
[ & ]( ){ return angleOfSideslip; },
[ & ]( ){ return bankAngle; } );
std::shared_ptr< SingleArcPropagatorSettings< double > > propagatorSettings =
std::make_shared< TranslationalStatePropagatorSettings< double > >(
centralBodyList, accelerationsMap, propagatedBodyList, getInitialStateOfBody(
"Vehicle", centralBodies[ "Vehicle" ], bodies, initialTime ), finalTime );
std::map< propagators::EnvironmentModelsToUpdate, std::vector< std::string > > environmentModelsToUpdate =
createEnvironmentUpdaterSettings< double >( propagatorSettings, bodies );
// Test update settings
BOOST_CHECK_EQUAL( environmentModelsToUpdate.size( ), 5 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.count( body_translational_state_update ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.at( body_translational_state_update ).size( ), 2 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.count( radiation_pressure_interface_update ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.at( radiation_pressure_interface_update ).size( ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.count( body_mass_update ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.at( body_mass_update ).size( ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.count( body_rotational_state_update ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.at( body_rotational_state_update ).size( ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.count( vehicle_flight_conditions_update ), 1 );
BOOST_CHECK_EQUAL( environmentModelsToUpdate.at( vehicle_flight_conditions_update ).size( ), 1 );
// Create and call updater.
std::shared_ptr< propagators::EnvironmentUpdater< double, double > > updater =
createEnvironmentUpdaterForDynamicalEquations< double, double >(
propagatorSettings, bodies );
updater->updateEnvironment( testTime, integratedStateToSet );
// Test if Earth, Sun and Vehicle states are updated.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Earth" )->getState( ),
bodies.at( "Earth" )->getEphemeris( )->getCartesianState( testTime ),
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Sun" )->getState( ),
bodies.at( "Sun" )->getEphemeris( )->getCartesianState( testTime ),
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Vehicle" )->getState( ), testState,
std::numeric_limits< double >::epsilon( ) );
// Test if Earth rotation is updated.
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Earth" )->getCurrentRotationToGlobalFrame( ).toRotationMatrix( ),
bodies.at( "Earth" )->getRotationalEphemeris( )->getRotationToBaseFrame( testTime ).toRotationMatrix( ),
std::numeric_limits< double >::epsilon( ) );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
bodies.at( "Earth" )->getCurrentRotationToLocalFrame( ).toRotationMatrix( ),
bodies.at( "Earth" )->getRotationalEphemeris( )->getRotationToTargetFrame( testTime ).toRotationMatrix( ),
std::numeric_limits< double >::epsilon( ) );
// Test if body mass is updated
BOOST_CHECK_CLOSE_FRACTION(
bodies.at( "Vehicle" )->getBodyMass( ), getBodyMass( testTime ),
std::numeric_limits< double >::epsilon( ) );
// Check if flight conditions update has been called
BOOST_CHECK_EQUAL(
( vehicleFlightConditions->getCurrentAirspeed( ) == vehicleFlightConditions->getCurrentAirspeed( ) ), 1 );
BOOST_CHECK_EQUAL(
( vehicleFlightConditions->getCurrentAltitude( ) == vehicleFlightConditions->getCurrentAltitude( ) ), 1 );
BOOST_CHECK_EQUAL(
( vehicleFlightConditions->getCurrentDensity( ) == vehicleFlightConditions->getCurrentDensity( ) ), 1 );
BOOST_CHECK_EQUAL( vehicleFlightConditions->getCurrentTime( ), testTime );
// Check if radiation pressure update is updated.
std::shared_ptr< electromagnetism::RadiationPressureInterface > radiationPressureInterface =
bodies.at( "Vehicle" )->getRadiationPressureInterfaces( ).at( "Sun" );
BOOST_CHECK_EQUAL(
( radiationPressureInterface->getCurrentTime( ) == radiationPressureInterface->getCurrentTime( ) ), 1 );
BOOST_CHECK_EQUAL(
( radiationPressureInterface->getCurrentRadiationPressure( ) ==
radiationPressureInterface->getCurrentRadiationPressure( ) ), 1 );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
radiationPressureInterface->getCurrentSolarVector( ),
( bodies.at( "Sun" )->getPosition( ) - bodies.at( "Vehicle" )->getPosition( ) ),
std::numeric_limits< double >::epsilon( ) );
updater->updateEnvironment(
0.5 * testTime, std::unordered_map< IntegratedStateType, Eigen::VectorXd >( ), { translational_state } );
}
}
BOOST_AUTO_TEST_SUITE_END( )
} // namespace unit_tests
} // namespace tudat
|
55246d16043a14b29681200cd61cf5ef951c14e2
|
7085e387992c8f71a3b772475ed329aa98cdd83e
|
/process/process_output_svg.cpp
|
d6529b10594b9a58bf55b266da93a4b5a4119b49
|
[] |
no_license
|
olivierchatry/obj-2-svg
|
f8b0ed84f4516e3ef62f4414d54cde0af0ebaa14
|
b0410d1fa0867a29f470e6e4a25b0ab988aafa7a
|
refs/heads/master
| 2021-08-09T02:52:25.858381
| 2016-10-07T08:29:43
| 2016-10-07T08:29:43
| 68,088,151
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,361
|
cpp
|
process_output_svg.cpp
|
#include "process.h"
struct edge_info_t {
int material;
int count;
};
typedef std::pair<int, int> edge_t;
typedef std::map<edge_t, edge_info_t> edge_infos_t;
struct element_t {
int material;
float z;
size_t id;
std::vector<int> indices;
std::vector<v3> vertices;
};
typedef std::vector<element_t> elements_t;
static void build_edge_list(process_t& process, edge_infos_t& edges) {
for (auto triangle : process.triangles) {
if (triangle.valid) {
auto addEdge = [&](int a, int b, int material) {
if (a > b) {
std::swap(a, b);
}
auto& e = edges[edge_t(a, b)];
e.count++;
e.material = material;
};
addEdge(triangle.a, triangle.b, triangle.material);
addEdge(triangle.b, triangle.c, triangle.material);
addEdge(triangle.c, triangle.a, triangle.material);
}
}
}
static void remove_shared_edge(edge_infos_t& edges) {
auto iter = edges.begin(), end = edges.end();
while (iter != end) {
if (iter->second.count > 1) {
edges.erase(iter++);
}
else {
++iter;
}
}
}
static void build_element_list(process_t& process, edge_infos_t& edges, elements_t& elements) {
auto iter = edges.begin(), end = edges.end();
while (iter != end) {
std::vector<int> stack;
int material = iter->second.material;
stack.push_back(iter->first.first);
stack.push_back(iter->first.second);
edges.erase(iter);
int found = 1;
while (found) {
int to_find = stack.back();
auto it = std::find_if(edges.begin(), edges.end(), [=](auto& e) -> bool { return to_find == e.first.first || to_find == e.first.second; });
found = it != edges.end();
if (found) {
stack.push_back(it->first.first == to_find ? it->first.second : it->first.first);
edges.erase(it);
}
}
stack.pop_back();
elements.push_back(element_t());
element_t& element = elements.back();
element.id = elements.size();
element.material = material;
element.z = -std::numeric_limits<float>::max();
for (auto eit : stack) {
const auto& a = process.vertices[eit];
element.indices.push_back(eit);
element.vertices.push_back(a);
element.z = std::max(element.z, a.z);
}
iter = edges.begin();
}
}
void process_output_svg(process_t& process) {
edge_infos_t edges;
build_edge_list(process, edges);
remove_shared_edge(edges);
elements_t elements;
build_element_list(process, edges, elements);
std::ofstream svg;
svg.open(process.file_name + ".svg");
svg << "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"" << process.min.x << " " << process.min.y << " " << (process.max.x - process.min.x) << " " << (process.max.y - process.min.y) << "\" >";
std::sort(elements.begin(), elements.end(), [](auto a, auto b) { return a.z < b.z; });
int previous_material = -1;
int id = 0;
for (auto element : elements) {
int need_change_material = previous_material != element.material;
if (need_change_material) {
if (previous_material != -1) {
svg << "</g>";
}
previous_material = element.material;
char color[16];
get_diffuse_from_tinyobj_material(process, element.material, color);
svg << "<g id=\"" << id << "\" stroke=\"black\" fill=\"" << color << "\" stroke-width=\"0.01\">";
id++;
}
svg << "<polygon points=\"";
for (auto a : element.vertices) {
svg << a.x << "," << a.y << " ";
}
svg << "\"/>";
}
svg << "</g></svg>";
}
|
2f3dd20e04c1633a39c45f33a817d354d0d90494
|
69b9cb379b4da73fa9f62ab4b51613c11c29bb6b
|
/submissions/kupc2018_b/main.cpp
|
51b2ad4548fdc48f81ec7ac2a7135f9acf1d35dd
|
[] |
no_license
|
tatt61880/atcoder
|
459163aa3dbbe7cea7352d84cbc5b1b4d9853360
|
923ec4d5d4ae5454bc6da2ac877946672ff807e7
|
refs/heads/main
| 2023-07-16T16:19:22.404571
| 2021-08-15T20:54:24
| 2021-08-15T20:54:24
| 118,358,608
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,275
|
cpp
|
main.cpp
|
//{{{
#include <bits/stdc++.h>
using namespace std;
#define repX(a,b,c,x,...) x
#define repN(a) repX a
#define rep(...) repN((__VA_ARGS__,rep3,rep2,loop))(__VA_ARGS__)
#define rrep(...) repN((__VA_ARGS__,rrep3,rrep2))(__VA_ARGS__)
#define loop(n) rep2(i_,n)
#define rep2(i,n) rep3(i,0,n)
#define rep3(i,begin,end) for(int i=(int)(begin),i##_end=(int)(end);i<i##_end;++i)
#define rrep2(i,n) rrep3(i,n,0)
#define rrep3(i,begin,end) for(int i=(int)(begin-1),i##_end=(int)(end);i>=i##_end;--i)
#define foreach(x,a) for(auto&x:a)
using ll=long long;
const ll mod=(ll)1e9+7;
//}}}
char c[10][11];
int main(){
int H, W;
cin >> H >> W;
rep(h, H) cin >> c[H - 1 - h];
int startPos = -1;
rep(w, W) if(c[0][w] == 's') startPos = w;
rep(i, pow(3, H - 1)){
int num = i;
int pos = startPos;
rep(j, 1, H){
switch(num % 3){
case 0: pos--; break;
case 1: break;
case 2: pos++; break;
}
num /= 3;
if(pos < 0 || W <= pos) goto F;
if(c[j][pos] == 'x') goto F;
}
rep(j, 1, H){
switch(i % 3){
case 0: cout << 'L'; break;
case 1: cout << 'S'; break;
case 2: cout << 'R'; break;
}
i /= 3;
}
cout << endl;
return 0;
F:;
}
cout << "impossible" << endl;
return 0;
}
|
0ee0de6e839d0aa28ac19898d3c657d1c74a82e3
|
e94559835dec204537927865800f95b81a191b7f
|
/Tympan/core/logging.h
|
c512538f2c85a19fbe4500f9d396054ada5e89a6
|
[] |
no_license
|
FDiot/code_tympan3
|
64530a3fc8a392cdbe26f478a9ea9ce03abab051
|
cf4383c4a162962b68df470e2bf757ad534880b9
|
refs/heads/master
| 2022-04-07T10:54:05.711913
| 2019-10-24T13:27:42
| 2019-10-24T13:27:42
| 239,812,326
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,689
|
h
|
logging.h
|
/*
* Copyright (C) <2012-2014> <EDF-R&D> <FRANCE>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef TY_LOGGING
#define TY_LOGGING
#include <iostream>
#include <time.h>
#include <qstring.h>
#include "Tympan/core/smartptr.h"
#define MSG_DEBUG 0x0001
#define MSG_BENCH 0x0002
#define MSG_INFO 0x0004
#define MSG_WARNING 0x0008
#define MSG_ERROR 0x0010
#define MSG_FATAL 0x0012
class OMessageManager;
///Smart pointer sur OMessageManager.
typedef SmartPtr<OMessageManager> LPOMessageManager;
/**
* Classe utilitaire pour la gestion des messages.
* Les messages sont formates et affiches selon leur type (info,
* toDo...) ou niveau d'erreur (warning, error, fatal).
* Cette classe peut etre derivee afin de surcharger notamment
* les methodes format() et output(), pour respectivement
* modifier le formatage des messages et les rediriger.
* Reprise du code C de Pascal Mobuchon.
*/
class OMessageManager : public IRefCount
{
// Methods
public:
/**
* Constructeur.
*/
OMessageManager();
/**
* Destructeur.
*/
virtual ~OMessageManager();
/**
* Definit cette instance comme singleton.
* Attention : cette instance doit absolument avoir ete creee
* sur la heap (operateur new).
*
* @return Indique si un singleton etait deja defini ou pas.
*/
bool setAsSingleton();
/**
* Retourne l'instance singleton.
*/
static OMessageManager* get();
/**
* Message de type warning.
*/
virtual void warning(const char* message, ...);
/**
* Message de type erreur.
*/
virtual void error(const char* message, ...);
/**
* Message de type erreur.
*/
virtual void fatal(const char* message, ...);
/**
* Message de type information.
*/
virtual void info(const char* message, ...);
/**
* Message de type debug.
*/
virtual void debug(const char* message, ...);
/**
* Message d'erreur general pour un fichier absent.
*/
virtual void missingFile(const char* nomFic);
/**
* Message informant que la fonctionnalite n'est pas encore implementee.
*/
virtual void toDo(const char* message);
/**
* Trace dans un fichier.
*/
virtual void trace(const char* message, ...);
/**
* Message de type warning.
*/
virtual void warning(const QString& message, ...);
/**
* Message de type erreur.
*/
virtual void error(const QString& message, ...);
/**
* Message de type erreur.
*/
virtual void fatal(const QString& message, ...);
/**
* Message de type information.
*/
virtual void info(const QString& message, ...);
/**
* Message de type debug.
*/
virtual void debug(const QString& message, ...);
/**
* Message d'erreur general pour un fichier absent.
*/
virtual void missingFile(const QString& nomFic);
/**
* Message informant que la fonctionnalite n'est pas encore implementee.
*/
virtual void toDo(const QString& message);
/**
* Trace dans un fichier.
*/
virtual void trace(const QString& message, ...);
/**
* Formate les messages.
* Cette methode est utilisee par les methodes specifiques
* a chaque type de message (warning(), toDo(), etc.).
* Elle peut etre surchargee pour formater les messages d'une
* maniere differente.
*
* @param level Niveau du message (MSG_DEBUG, MSG_INFO, MSG_WARNING, ...).
* @param message Contenu du message (format printf).
*/
virtual void format(int level, const char* message, ...);
/**
* \brief Variable argument list version of format */
void vformat(int level, const char* message, va_list args);
/**
* Affiche/ecrit le message final, le niveau du message est passe dans
* le cas ou la redirection des messages depend de celui-ci.
* Cette methode est appelee une fois que le message est ete formate.
* Elle peut etre surchargee pour rediriger les messages, par
* defaut ils sont envoyes vers stdout ou stderr selon le type.
*
* @param message Message final a afficher/ecrire.
* @param level Niveau du message (MSG_DEBUG, MSG_INFO, MSG_WARNING, ...).
*
* @see format()
*/
virtual void output(const char* message, int level);
/**
* Convertit et formate la date en une chaine de caractere.
*/
static char* getStrDate();
/**
* Test la validite dans le temps d'un fichier de trace.
*/
#ifdef _WIN32
static void checkFile(struct _finddata_t* c_file, time_t theTime);
#else
static void checkFile(const char* c_file, time_t theTime);
#endif
protected:
/**
* Initialise le fichier de trace.
*/
virtual int initTrace();
// Members
protected:
///Le fichier de trace.
FILE* _ficTrace;
private:
///Instance unique du singleton.
static LPOMessageManager _pInstance;
};
#endif // TY_LOGGING
|
ac3d846e4e40bb06787cc4c00d7b3045a0428945
|
8cf29d0b26119188660f148c8a72f38653552a6b
|
/tower_defence/src/lib/init_functions.cpp
|
ee2e883ebcfd7ad84449583b825388f1fc21324d
|
[] |
no_license
|
FilippovIvan19/4th-sem
|
b81dae65e6a3081f7820ec470248ab9481835381
|
7ec1a7b6fa69aa6fba41406c05931bb2726f75fa
|
refs/heads/master
| 2021-01-01T07:50:53.283026
| 2020-06-02T00:11:42
| 2020-06-02T00:11:42
| 239,180,248
| 0
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,608
|
cpp
|
init_functions.cpp
|
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include "../headers/constants.h"
#define TEXTURE_DEFINE(obj) \
textures->obj##_texture = new sf::Texture; \
textures->obj##_texture->loadFromFile("textures/" #obj ".png"); \
textures->obj##_texture->setSmooth(true);
void load_textures(all_textures *textures)
{
#include "../headers/textures_list.h"
}
#undef TEXTURE_DEFINE
#define TEXTURE_DEFINE(obj) \
sprites->obj##_sprite = new sf::Sprite; \
sprites->obj##_sprite->setTexture(* textures->obj##_texture);
#define SET_SCALE(obj, x, y) \
sprites->obj##_sprite->setScale(x, y);
void load_sprites(all_sprites *sprites, all_textures *textures)
{
#include "../headers/textures_list.h"
SET_SCALE(pill_tower_base, (float)PILL_TOWER_BASE_SIZE / PILL_TOWER_BASE_PIC_SIZE,
(float)PILL_TOWER_BASE_SIZE / PILL_TOWER_BASE_PIC_SIZE)
SET_SCALE(pill_tower_gun, (float)PILL_TOWER_GUN_SIZE / PILL_TOWER_GUN_PIC_SIZE,
(float)PILL_TOWER_GUN_SIZE / PILL_TOWER_GUN_PIC_SIZE)
SET_SCALE(pill_tower_bullet, (float)PILL_TOWER_BULLET_SIZE / PILL_TOWER_BULLET_PIC_SIZE,
(float)PILL_TOWER_BULLET_SIZE / PILL_TOWER_BULLET_PIC_SIZE)
SET_SCALE(capsule_tower_base, (float)CAPSULE_TOWER_BASE_SIZE / CAPSULE_TOWER_BASE_PIC_SIZE,
(float)CAPSULE_TOWER_BASE_SIZE / CAPSULE_TOWER_BASE_PIC_SIZE)
SET_SCALE(capsule_tower_gun, (float)CAPSULE_TOWER_GUN_SIZE / CAPSULE_TOWER_GUN_PIC_SIZE,
(float)CAPSULE_TOWER_GUN_SIZE / CAPSULE_TOWER_GUN_PIC_SIZE)
SET_SCALE(capsule_tower_bullet, (float)CAPSULE_TOWER_BULLET_SIZE / CAPSULE_TOWER_BULLET_PIC_SIZE,
(float)CAPSULE_TOWER_BULLET_SIZE / CAPSULE_TOWER_BULLET_PIC_SIZE)
SET_SCALE(map, (float)CELL_SIZE / CELL_PIC_SIZE,
(float)CELL_SIZE / CELL_PIC_SIZE)
SET_SCALE(bacteria, (float)CELL_SIZE / BACTERIA_UNIT_PIC_SIZE,
(float)CELL_SIZE / BACTERIA_UNIT_PIC_SIZE)
SET_SCALE(virus, (float)CELL_SIZE / VIRUS_UNIT_PIC_SIZE,
(float)CELL_SIZE / VIRUS_UNIT_PIC_SIZE)
SET_SCALE(rank, (float)RANK_SIZE / RANK_PIC_SIZE,
(float)RANK_SIZE / RANK_PIC_SIZE)
SET_SCALE(level_icon, (float)LEVEL_ICON_SIZE / LEVEL_ICON_PIC_SIZE,
(float)LEVEL_ICON_SIZE / LEVEL_ICON_PIC_SIZE)
SET_SCALE(menu_background, (float)WINDOW_WIDTH / MENU_PIC_WIDTH,
(float)WINDOW_HEIGHT / MENU_PIC_HEIGHT)
SET_SCALE(level_completed, (float)WINDOW_WIDTH / LEVEL_COMPLETED_PIC_WIDTH,
(float)WINDOW_HEIGHT / LEVEL_COMPLETED_PIC_HEIGHT)
SET_SCALE(buttons, (float)CELL_SIZE / CELL_PIC_SIZE,
(float)CELL_SIZE / CELL_PIC_SIZE)
SET_SCALE(heart, (float)HEART_SIZE / HEART_PIC_SIZE,
(float)HEART_SIZE / HEART_PIC_SIZE)
SET_SCALE(lock, (float)LEVEL_LOCK_SIZE / LEVEL_LOCK_PIC_SIZE,
(float)LEVEL_LOCK_SIZE / LEVEL_LOCK_PIC_SIZE)
SET_SCALE(health_bar, (float)HEALTH_BAR_WIDTH / HEALTH_BAR_PIC_WIDTH,
(float)HEALTH_BAR_HEIGHT / HEALTH_BAR_PIC_HEIGHT)
}
#undef TEXTURE_DEFINE
#undef SET_SCALE
#define FONT_DEFINE(obj) \
fonts->obj##_font = new sf::Font; \
fonts->obj##_font->loadFromFile("fonts/" #obj ".ttf");
void load_fonts(all_fonts *fonts)
{
#include "../headers/fonts_list.h"
}
#undef FONT_DEFINE
|
4598c008009262e809776974928f2ffe29aacf7a
|
0af1eceaa610a84d78d92a7ecef7b7be09ff690a
|
/OOP-Azhar/list/list.cpp
|
7417455e3c2c1d8725f4a528a9d4d5624068df3b
|
[] |
no_license
|
AzharMithani/SE-Assignmments
|
a297191035f90201054bdbaa63066f5b788a2990
|
221f954203392098d127d62b22b783cea1f34c89
|
refs/heads/master
| 2021-09-01T05:42:41.614939
| 2017-12-25T05:55:54
| 2017-12-25T05:55:54
| 115,308,202
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,017
|
cpp
|
list.cpp
|
#include "iostream"
#include "list"
using namespace std;
void Create_List(list<int> &l,int n)
{
int no;
for(int i=0;i<n;i++)
{
cin>>no;
l.push_back(no);
}
}
void display(list<int> &l)
{
if(l.empty())
cout<<"List Empty.....\n";
else
{
list<int> ::iterator itr=l.begin();
for(itr=l.begin();itr!=l.end();itr++)
cout<<*itr<<" ";
}
cout<<"\n";
}
int main(int argc, char **argv) {
list<int> l1,l2,l4;
int no,i,ch,n,ans;
list<int>::iterator itr,itr1;
do
{
cout<<"1: Create List.\n";
cout<<"2: Display List.\n";
cout<<"3: Insert Element. \n";
cout<<"4: Merge 2 Lists.\n";
cout<<"5: Reverse List.\n";
cout<<"6: Sort List.\n";
cout<<"7: Unique Element.\n";
cout<<"8: Delete Element.\n";
cout<<"9: Remove element.\n";
cout<<"10: Swap Lists.\n";
cout<<"11: Clear List.\n";
cout<<"\nEnter Your Choice: ";
cin>>ch;
switch(ch)
{
case 1:
cout<<"How Many Elements To be Entered: ";
cin>>n;
Create_List(l1,n);
break;
case 2:
display(l1);
break;
case 3:
cout<<"Enter Element To Be Inserted: ";
cin>>no;
itr=l1.begin();
itr++;
l1.insert(itr,no);
break;
case 4:
Create_List(l2,n);
cout<<"Second List\n";
display(l2);
l1.merge(l2);
cout<<"List After Merge : \n";
display(l1);
break;
case 5:
cout<<"Original List: ";
display(l1);
l1.reverse();
cout<<"Reverse List: ";
display(l1);
break;
case 6:
cout<<"Before Sort List: ";
display(l1);
l1.sort();
cout<<"After Sort List: ";
display(l1);
cout<<"In Descending Order \n";
l1.sort(greater<int>());
display(l1);
break;
case 7:
cout<<"How Many Elements To be Entered for Second List: ";
cin>>n;
Create_List(l2,n);
l2.unique();
display(l2);
break;
case 8:
if(l1.empty())
cout<<"List Empty .......";
else
{
cout<<"Before Delete......";
display(l1);
l1.pop_back();
cout<<"After Delete ..........";
display(l1);
}
break;
case 9:
if(l1.empty())
cout<<"List Empty .......";
else
{
l1.remove(30);
cout<<"After Remove...";
display(l1);
}
itr=itr1=l1.begin();
std::advance(itr,2);
std::advance(itr1,4);
cout<<"After Erase........";
l1.erase(itr,itr1);
display(l1);
break;
case 10:
cout<<"How Many Elements To be Entered in List: ";
cin>>n;
cout<<"Enter List : 1";
Create_List(l1,n);
cout<<"Enter List : 2";
Create_List(l2,n);
cout<<"Before SWAP.....\n";
display(l1);
display(l2);
cout<<"After SWAP..... \n";
l1.swap(l2);
display(l1);
display(l2);
break;
case 11:
l1.clear();
display(l1);
break;
}
cout<<"Do you Want TO Continue ......[1/0]: ";
cin>>ans;
}while(ans == 1);
cout<<"How Many Elements To be Entered for Second List: ";
cin>>n;
itr=l1.begin();
std::advance(itr,2);
Create_List(l4,n);
l1.splice(itr,l4);
display(l1);
return 1;
}
|
06e2dd7a020c5b9345b33f8b0d95959d8b2912b4
|
310f244bf7e5acef22d32202ed577a3fd7692dd0
|
/Section4/lab43/lab43.cpp
|
e9d026eede541d5d699983184499d0776a2ba2eb
|
[] |
no_license
|
asylum14/MichaelSilva-CSCI20-Fall2017
|
1e55d1e0ddbbc7ad361b621b0044b2de041f9fbc
|
4506b7360b176ccd13683ac41f46f719ecac1944
|
refs/heads/master
| 2021-01-19T16:02:01.403958
| 2017-12-11T20:18:55
| 2017-12-11T20:18:55
| 100,982,691
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,663
|
cpp
|
lab43.cpp
|
/*
Created by:Michael Silva
Created on: 10/23/2017
Description: this program is used to simulate a shopping cart for a store(array of objects)
*/
#include <iostream>
#include <string>
using namespace std;
class Product{
private:
int Inventory_;
double Price_;
string Name_;
int Quantity_;
public:
Product(){
Inventory_=0;
Price_=0;
}
Product(int inventory, double price,string name){
Inventory_=inventory;
Price_=price;
Name_=name;
}
int GetQuantity(){
return Quantity_;
}
int GetInventory(){
return Inventory_;
}
double GetPrice(){
return Price_;
}
string GetName(){
return Name_;
}
double BuyItem(int quantity){
double totalPrice=0.0;
if((quantity<=Inventory_)){
Inventory_=Inventory_-quantity;
totalPrice=(quantity*Price_)+totalPrice;
Quantity_=quantity;
return totalPrice;
}else {return -1;}
}
void Print(){
cout<<"The Store has "<<Inventory_<<" "<<Name_<<"(s) left"<<endl;
cout<<"you currently have "<<Quantity_<<" "<<Name_<<"(s) in your cart"<<endl;
}
};
int main(){
int const NUM_ITEMS =10;
double totalPrice=0;
int amountOfItems=0;
Product shoppingCart[NUM_ITEMS];
shoppingCart[0]=Product(20,3.25,"Apple");
shoppingCart[1]=Product(10,4.5,"Bannana");
shoppingCart[2]=Product(5,8,"Tomato");
shoppingCart[3]=Product(3,4.25,"Potato");
shoppingCart[4]=Product(15,7.3,"Jalepeno");
shoppingCart[5]=Product(60,6.2,"Lettuce");
shoppingCart[6]=Product(30,1.5,"Carrot");
shoppingCart[7]=Product(15,8,"Rice");
shoppingCart[8]=Product(40,6.5,"Peas");
shoppingCart[9]=Product(25,3.85,"Peach");
for(int i =0; i<NUM_ITEMS;i++){
cout<<"How many "<<shoppingCart[i].GetName()<<" do you want?";
cin>>amountOfItems;
if(shoppingCart[i].BuyItem(amountOfItems)!=-1){
totalPrice=shoppingCart[i].BuyItem(amountOfItems)+totalPrice;
}else{
while(shoppingCart[i].BuyItem(amountOfItems)==-1){
cout<<"Please enter a valid amount. anything less than or equal to "<<shoppingCart[i].GetInventory()<<" will work"<<endl;
cin>>amountOfItems;
}
totalPrice=shoppingCart[i].BuyItem(amountOfItems)+totalPrice;
}
shoppingCart[i].Print();
}
cout<<"The total Price of all your Items is "<<totalPrice<<endl;
}/*
*/
|
188069ea6b4abe4e398c4844d51ffbb8e9d8c50e
|
9f9e8ba1e1a36453aa222b2969d6077cd35c33b4
|
/Source/MainSonificationProcessor.h
|
b7001c428e8983ca7646d62c89cc157a88ab9e42
|
[
"MIT"
] |
permissive
|
citron0xa9/FalconSonification
|
db8963b24dbb6f55c01c248fbee5ac3d8bcf92da
|
b34fb4fca2c76fd4bfc318633c632fd26ac58066
|
refs/heads/main
| 2023-03-27T18:13:32.011972
| 2021-03-29T18:52:25
| 2021-03-29T18:52:53
| 352,699,398
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,530
|
h
|
MainSonificationProcessor.h
|
#pragma once
#include <JuceHeader.h>
#include "FalconSimulation.h"
#include "SampledSound.h"
#include "exprtk.h"
namespace falconSound {
class MainSonificationProcessor : public juce::PositionableAudioSource {
public:
explicit MainSonificationProcessor();
void prepareToPlay(int samplesPerBlockExpected, double sampleRate) override;
void getNextAudioBlock(const juce::AudioSourceChannelInfo& bufferToFill) override;
void releaseResources() override;
void setNextReadPosition(juce::int64 newPosition) override;
juce::int64 getNextReadPosition() const override;
juce::int64 getTotalLength() const override;
bool isLooping() const override;
void setLooping(bool shouldLoop) override;
void falconSimulation(FalconSimulation* simulationPtr);
void engineCloseSoundGainExpression(const std::string& expressionString);
const std::string& engineCloseSoundGainExpression() const noexcept;
void engineDistantSoundGainExpression(const std::string& expressionString);
const std::string& engineDistantSoundGainExpression() const noexcept;
void engineAllSoundGainExpression(const std::string& expressionString);
const std::string& engineAllSoundGainExpression() const noexcept;
void engineSoundModulatorFrequencyExpression(const std::string& expressionString);
const std::string& engineSoundModulatorFrequencyExpression() const noexcept;
void engineSoundModulatorGainExpression(const std::string& expressionString);
const std::string& engineSoundModulatorGainExpression() const noexcept;
void airodynamicPressureLowGainExpression(const std::string& expressionString);
const std::string& airodynamicPressureLowGainExpression() const noexcept;
void airodynamicPressureHighGainExpression(const std::string& expressionString);
const std::string& airodynamicPressureHighGainExpression() const noexcept;
void lowpassCutoffFrequencyExpression(const std::string& expressionString);
const std::string& lowpassCutoffFrequencyExpression() const noexcept;
void enableEngineSound(bool shouldEnable);
bool isEngineSoundEnabled() const noexcept;
void enableEngineModulation(bool shouldEnable);
bool isEngineModulationEnabled() const noexcept;
void enableSonicBoom(bool shouldEnable);
bool isSonicBoomEnabled() const noexcept;
void enableLowpass(bool shouldEnable);
bool isLowpassEnabled() const noexcept;
void enableAirodynamicPressureSound(bool shouldEnable);
bool isAirodynamicPressureSoundEnabled() const noexcept;
void masterGain(float gain);
float masterGain() const noexcept;
float currentSonificationTimeInSeconds() const;
void onPositionChangedExternally();
private:
FalconSimulation* mSimulationPtr = nullptr;
float mSonificationTimeSeconds = 0.0f;
juce::int64 mCurrentSamplePosition = 0;
juce::int64 mLengthInSamples = 0;
bool mIsLooping = false;
double mSampleRate;
int mSamplesPerBlockExpected;
bool mAudioIsInitialized = false;
float mLastMachNumber;
juce::AudioFormatManager mAudioFormatManager;
juce::dsp::ProcessorChain<juce::dsp::Oscillator<float>, juce::dsp::Gain<float>> mPressureLow;
juce::dsp::ProcessorChain<juce::dsp::Oscillator<float>, juce::dsp::Gain<float>> mPressureHigh;
juce::dsp::StateVariableTPTFilter<float> mLowPass;
juce::dsp::ProcessorChain<juce::dsp::Oscillator<float>, juce::dsp::Gain<float>> mEngineSoundModulator;
std::unique_ptr<SampledSound> mEngineCloseSoundPtr;
std::unique_ptr<SampledSound> mEngineDistantSoundPtr;
std::unique_ptr<SampledSound> mSonicBoomSoundPtr;
juce::AudioBuffer<float> mTemporaryAudioBuffer;
std::string mEngineCloseSoundGainExpressionStr;
std::string mEngineDistantSoundGainExpressionStr;
std::string mEngineAllSoundGainExpressionStr;
std::string mEngineSoundModulatorFrequencyExpressionStr;
std::string mEngineSoundModulatorGainExpressionStr;
std::string mAirodynamicPressureLowGainExpressionStr;
std::string mAirodynamicPressureHighGainExpressionStr;
std::string mLowpassCutoffFrequencyExpressionStr;
exprtk::expression<float> mEngineCloseSoundGainExpression;
exprtk::expression<float> mEngineDistantSoundGainExpression;
exprtk::expression<float> mEngineAllSoundGainExpression;
exprtk::expression<float> mEngineSoundModulatorFrequencyExpression;
exprtk::expression<float> mEngineSoundModulatorGainExpression;
exprtk::expression<float> mAirodynamicPressureLowGainExpression;
exprtk::expression<float> mAirodynamicPressureHighGainExpression;
exprtk::expression<float> mLowpassCutoffFrequencyExpression;
bool mEnableEngineSound = true;
bool mEnableEngineModulation = true;
bool mEnableSonicBoom = true;
bool mEnableLowpass = true;
bool mEnableAirodynamicPressureSound = true;
float mMasterGain = 1.0f;
exprtk::symbol_table<float> mExpressionSymbolTable;
std::unique_ptr<exprtk::parser<float>> mExpressionParserPtr;
void updateSonificationParameters(float sonificationTimeSeconds);
static void addToMix(const juce::AudioSourceChannelInfo& mixAudioInfo, const juce::AudioSourceChannelInfo& partialAudioInfo);
static void modulateMix(const juce::AudioSourceChannelInfo& mixAudioInfo, const juce::AudioSourceChannelInfo& modulateAudioInfo);
void compileExpression(exprtk::expression<float>& expression, const std::string& expressionString);
static std::unique_ptr<exprtk::parser<float>> createExpressionParser();
};
}
|
2e5b62095d7d77ccf84b5ad70b91ac6f6602b4f5
|
c8bb4cd63e577fadd1dc0ac820be166810d1a148
|
/Game/Game/Level/Replays/Recording.cpp
|
bfa1c63b63f2d2994b1c1ff17aa9ce88d2900ab9
|
[] |
no_license
|
rodrigobmg/Cloudberry-Kingdom-Port
|
c2a0aac9c7cb387775f6f00b3b12aae109a7ea39
|
74cd72e29ff5dfd8757d93abc92ed7e48a945fc8
|
refs/heads/master
| 2021-06-01T06:19:25.283550
| 2016-08-10T01:35:16
| 2016-08-10T01:35:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,792
|
cpp
|
Recording.cpp
|
#include <small_header.h>
#include "Game/Level/Replays/Recording.h"
#include "Core/Animation/SpriteAnim.h"
#include "Core/Graphics/Draw/Quads/QuadClass.h"
#include "Core/Particle Effects/Specific Effects/CloudberryKingdom.ParticleEffects.h"
#include "Core/Tools/CoreMath.h"
#include "Game/Level/Make/ComputerRecording.h"
#include "Game/Objects/Bob/Bob.h"
#include "Game/Objects/Bob/BobLink.h"
#include "Game/Objects/In Game Objects/Grab/MakeData.h"
#include "Game/Level/Level.h"
#include "Game/Player/Hero Physics/Spaceship.h"
#include "Game/Tools/Globals.h"
#include "Game/Tools/Tools.h"
#include "Game/Games/GameType.h"
#include "Core/Texture/EzTexture.h"
#include "Core/Texture/EzTextureWad.h"
#include "Hacks/NET/Path.h"
#include "Hacks/NET/Directory.h"
namespace CloudberryKingdom
{
std::wstring Recording::DefaultRecordingDirectory()
{
return Path::Combine( Globals::ContentDirectory, std::wstring( L"Recordings" ) );
}
std::wstring Recording::SourceRecordingDirectory()
{
return Path::Combine( Path::GetDirectoryName( Path::GetDirectoryName( Path::GetDirectoryName( Directory::GetCurrentDirectory() ) ) ), std::wstring( L"Content/Recordings" ) );
}
void Recording::Save( const std::wstring &file, bool Bin )
{
// First move to standard directory for .rec files
std::wstring fullpath;
if ( Bin )
fullpath = Path::Combine( DefaultRecordingDirectory(), file );
else
fullpath = Path::Combine( SourceRecordingDirectory(), file );
// Now write to file
Tools::UseInvariantCulture();
//boost::shared_ptr<FileStream> stream = File->Open( fullpath, FileMode::Create, FileAccess::Write, FileShare::None );
//boost::shared_ptr<BinaryWriter> writer = boost::make_shared<BinaryWriter>( stream, Encoding::UTF8 );
{
boost::shared_ptr<BinaryWriter> writer = boost::make_shared<FileBinaryWriter>( fullpath );
Write( writer );
}
//writer->Close();
//stream->Close();
}
void Recording::Load( const std::wstring &file )
{
SourceFile = file;
// First move to standard directory for .rec files
std::wstring fullpath = Path::Combine( DefaultRecordingDirectory(), file );
// Now read the file
Tools::UseInvariantCulture();
//boost::shared_ptr<FileStream> stream = File->Open( fullpath, FileMode::Open, FileAccess::Read, FileShare::None );
//boost::shared_ptr<BinaryReader> reader = boost::make_shared<FileBinaryReader>( stream, Encoding::UTF8 );
boost::shared_ptr<BinaryReader> reader = boost::make_shared<FileBinaryReader>( fullpath );
Read( reader );
//reader->Close();
//stream->Close();
}
void Recording::Write( const boost::shared_ptr<BinaryWriter> &writer )
{
writer->Write( NumBobs );
writer->Write( Length );
for ( int i = 0; i < NumBobs; i++ )
Recordings[ i ]->Write( writer, Length );
}
void Recording::Read( const boost::shared_ptr<BinaryReader> &reader )
{
NumBobs = reader->ReadInt32();
Length = reader->ReadInt32();
Init( NumBobs, Length );
for ( int i = 0; i < NumBobs; i++ )
Recordings[ i ]->Read( reader, Length );
}
void Recording::Draw( const boost::shared_ptr<QuadClass> &BobQuad, int Step, const boost::shared_ptr<Level> &level, std::vector<boost::shared_ptr<SpriteAnimGroup> > AnimGroup, std::vector<boost::shared_ptr<BobLink> > &BobLinks )
{
if ( level->MyGame->MyGameFlags.IsTethered && Step < Length - 1 )
{
for ( std::vector<boost::shared_ptr<BobLink> >::const_iterator link = BobLinks.begin(); link != BobLinks.end(); ++link )
{
if ( boost::dynamic_pointer_cast<BobPhsxSpaceship>( level->DefaultHeroType ) != 0 &&
( Recordings[ ( *link )->_j ]->Gett( Step ) == 0 || Recordings[ ( *link )->_k ]->Gett( Step ) == 0 ) )
continue;
( *link )->Draw( Recordings[ ( *link )->_j ]->GetBoxCenter( Step ), Recordings[ ( *link )->_k ]->GetBoxCenter( Step ) );
}
}
for ( int i = 0; i < NumBobs; i++ )
{
if ( i >= static_cast<int>( level->Bobs.size() ) ) continue;
if ( Step > 3 && Step == Recordings[i]->Box_BL.size() - 3 ) ParticleEffects::AddPop( level, Recordings[i]->GetBoxCenter( Step - 3 ) );
if ( Step >= Recordings[ i ]->Box_BL.size() ) continue;
if ( Step < Length - 1 )
{
//if ( boost::dynamic_pointer_cast<BobPhsxSpaceship>( level->DefaultHeroType ) != 0 )
if ( Step > 0 && Recordings[ i ]->Gett( Step ) <= 0 )
{
if ( Recordings[ i ]->Gett( Step - 1 ) > 0 )
{
ParticleEffects::AddPop( level, Recordings[ i ]->GetBoxCenter( Step ) );
}
continue;
}
Vector2 padding = Vector2();
//BobQuad->Quad_Renamed.getMyTexture()->setTex( AnimGroup[ i ]->Get( anim, Recordings[ i ]->Gett( Step ), padding ) );
int texture_index = Recordings[ i ]->Gett( Step );
if ( texture_index == 0 ) continue;
BobQuad->Quad_Renamed.getMyTexture()->_Tex = Tools::TextureWad->TextureList[ texture_index ]->_Tex;
Vector2 size = Recordings[ i ]->GetBoxSize( Step ) / 2.0f;
BobQuad->Base.e1 = Vector2( size.X, 0 );
BobQuad->Base.e2 = Vector2( 0, size.Y );
float a = Bob::UnpackIntIntoVector_Angle( Recordings[ i ]->Box_Size[ Step ] );
if (a != 0)
CoreMath::PointxAxisToAngle( BobQuad->Base, a );
BobQuad->Base.Origin = Recordings[ i ]->GetBoxCenter( Step );
if ( BobQuad->Base.Origin == Vector2() )
continue;
BobQuad->Draw();
Tools::QDrawer->Flush();
}
//else
// if ( Step == Length - 1 && !level->ReplayPaused && !( boost::dynamic_pointer_cast<BobPhsxSpaceship>( level->DefaultHeroType ) != 0 && !Recordings[ i ]->GetAlive( Length - 1 ) ) )
// ParticleEffects::AddPop( level, Recordings[ i ]->GetBoxCenter( Length - 1 ) );
}
}
void Recording::ConvertToSuperSparse( int Step )
{
for ( int i = 0; i < static_cast<int>( Recordings.size() ); i++ )
{
Recordings[ i ]->ConvertToSuperSparse( this->Length );
}
}
void Recording::Release()
{
if ( Recordings.size() > 0 )
for ( int i = 0; i < static_cast<int>( Recordings.size() ); i++ )
{
Recordings[ i ]->Release();
}
Recordings.clear();
}
Recording::Recording( int NumBobs, int Length ) :
Length( 0 )
{
Init( NumBobs, Length );
}
void Recording::Init( int NumBobs, int Length )
{
this->NumBobs = NumBobs;
Recordings = std::vector<boost::shared_ptr<ComputerRecording> >( NumBobs );
for ( int i = 0; i < NumBobs; i++ )
{
Recordings[ i ] = boost::make_shared<ComputerRecording>();
Recordings[ i ]->Init( Length, true );
}
}
void Recording::Record( const boost::shared_ptr<Level> &level )
{
if ( level->Bobs.size() <= 0 )
return;
if ( level->PlayMode != 0 || level->Watching )
return;
if ( level->CurPhsxStep < 0 )
return;
Length = level->CurPhsxStep;
for ( int i = 0; i < NumBobs; i++ )
{
if ( i >= static_cast<int>( level->Bobs.size() ) ) continue;
if ( level->CurPhsxStep >= static_cast<int>( Recordings[i]->t.capacity() ) ) continue;
Recordings[i]->t[ level->CurPhsxStep ] = level->Bobs[i]->StoredRecordTexture;
if (level->CurPhsxStep < Recordings[i]->Box_BL.size() )
{
Recordings[i]->Box_BL[ level->CurPhsxStep ] = level->Bobs[i]->StoredRecord_BL;
Recordings[i]->Box_Size[ level->CurPhsxStep ] = level->Bobs[i]->StoredRecord_QuadSize;
}
Recordings[ i ]->AutoLocs[ level->CurPhsxStep ] = level->Bobs[ i ]->getCore()->Data.Position;
Recordings[ i ]->AutoVel[ level->CurPhsxStep ] = level->Bobs[ i ]->getCore()->Data.Velocity;
Recordings[ i ]->Input[ level->CurPhsxStep ] = level->Bobs[ i ]->CurInput;
if ( !level->Bobs[ i ]->getCore()->Show )
{
Recordings[ i ]->t[ level->CurPhsxStep ] = 0;
Recordings[ i ]->Box_BL[ level->CurPhsxStep ] = 0;
Recordings[ i ]->AutoLocs[ level->CurPhsxStep ] = Vector2();
}
}
}
void Recording::MarkEnd( const boost::shared_ptr<Level> &level )
{
Length = level->CurPhsxStep;
}
}
|
c5da4675542cf555f376cf246e043bc4ded922ba
|
ef187d259d33e97c7b9ed07dfbf065cec3e41f59
|
/work/atcoder/arc/arc099/E/answers/721819_diamond_duke.cpp
|
7ac845a967978293877ed91471efb006ad401231
|
[] |
no_license
|
kjnh10/pcw
|
847f7295ea3174490485ffe14ce4cdea0931c032
|
8f677701bce15517fb9362cc5b596644da62dca8
|
refs/heads/master
| 2020-03-18T09:54:23.442772
| 2018-07-19T00:26:09
| 2018-07-19T00:26:09
| 134,586,379
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,540
|
cpp
|
721819_diamond_duke.cpp
|
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <utility>
#include <cstdio>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <cmath>
#include <set>
#include <map>
#define my_abs(x) ((x) < 0 ? -(x) : (x))
#define mp std::make_pair
#define pb push_back
typedef long long ll;
int col[705], w, b;
bool dp[705][705], app[705][705];
std::pair<int, int> arr[705];
std::vector<int> adj[705];
void dfs(int u, int c)
{
if (~col[u])
{
if (col[u] != c)
{
puts("-1");
exit(0);
}
return;
}
col[u] = c;
(c ? w : b)++;
for (int v : adj[u])
dfs(v, c ^ 1);
}
int main()
{
// freopen("ARC099-E.in", "r", stdin);
memset(col, -1, sizeof(col));
int n, m, len = 0;
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++)
{
int u, v;
scanf("%d%d", &u, &v);
u--;
v--;
app[u][v] = app[v][u] = true;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (!app[i][j] && i != j)
adj[i].pb(j);
}
}
for (int i = 0; i < n; i++)
{
if (~col[i])
continue;
w = 0;
b = 0;
dfs(i, 0);
arr[len++] = {w, b};
}
dp[0][0] = true;
for (int i = 0; i < len; i++)
{
for (int x = 0; x <= n; x++)
{
if (dp[i][x])
{
dp[i + 1][x + arr[i].first] = true;
dp[i + 1][x + arr[i].second] = true;
}
}
}
int ans = 1e9;
for (int i = 0; i <= n; i++)
{
if (dp[len][i])
ans = std::min(ans, i * (i - 1) / 2 + (n - i) * (n - i - 1) / 2);
}
printf("%d\n", ans >= 1e9 ? -1 : ans);
return 0;
}
|
b6e3ada8e7e659b41699b347d472d28da8788886
|
9889e7fd73314382fb2f9e8f63d92cf3254b75fb
|
/GranularSim/src/Simulations/DEM/CavityExpansion.cpp
|
ec1ad8c51ef0768f47a3007dacf2975a54563be0
|
[
"BSD-3-Clause",
"MIT"
] |
permissive
|
bbanerjee/ParSim
|
0b05f43cff8e878658dc179b4a604eabd873f594
|
87f87816b146f40013a5e6648dfe20f6d2d002bb
|
refs/heads/master
| 2023-04-27T11:30:36.252023
| 2023-04-13T22:04:50
| 2023-04-13T22:04:50
| 13,608,512
| 16
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,311
|
cpp
|
CavityExpansion.cpp
|
#include <Simulations/DEM/CavityExpansion.h>
#include <Core/Util/Utility.h>
using namespace dem;
void
CavityExpansion::execute(DiscreteElements* dem)
{
dem->allowPatchDomainResize(Boundary::BoundaryID::ZPLUS);
if (dem->getMPIRank() == 0) {
auto inputParticle = util::getFilename("particleFilename");
REAL percent = util::getParam<REAL>("expandPercent");
dem->readParticles(inputParticle);
REAL x1 = util::getParam<REAL>("cavityMinX");
REAL y1 = util::getParam<REAL>("cavityMinY");
REAL z1 = util::getParam<REAL>("cavityMinZ");
REAL x2 = util::getParam<REAL>("cavityMaxX");
REAL y2 = util::getParam<REAL>("cavityMaxY");
REAL z2 = util::getParam<REAL>("cavityMaxZ");
DEMParticlePArray cavityParticleVec;
Vec center;
for (const auto& it : dem->getAllDEMParticleVec()) {
center = it->currentPosition();
if (center.x() > x1 && center.x() < x2 && center.y() > y1 &&
center.y() < y2 && center.z() > z1 && center.z() < z2) {
it->expand(percent);
cavityParticleVec.push_back(it);
}
}
dem->printParticlesCSV(".", "cavity_particle_ini", cavityParticleVec, 0, 0);
dem->printParticlesCSV(".", "expand_particle_ini", 0, 0);
}
dem->deposit(util::getFilename("boundaryFilename"), "expand_particle_ini");
}
|
7bd06dcb12f6b189880bdd86ed035cd41ae8d9e5
|
b47b241b4b9ad946e52ab92dc2dd4b0bbb8c0d96
|
/IPlugExamples/Voltex/VoiceManager.cpp
|
c9a900e8e4616d377fbf9fc52f607c6f14a69e13
|
[
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
eriser/Voltex
|
141abf9d8f45f9cd65ee71cb661b6aa22b3b1885
|
e9e412350b33c6ad6a6734ea5cddd714c9d4cac2
|
refs/heads/master
| 2021-01-24T01:34:36.729388
| 2015-06-13T15:13:10
| 2015-06-13T15:13:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,771
|
cpp
|
VoiceManager.cpp
|
//
// VoiceManager.cpp
// Voltex
//
// Created by Samuel Dewan on 2015-04-11.
//
//
#include "VoiceManager.h"
Voice VoiceManager::getVoice(int index) {
return voices[index];
}
Voice* VoiceManager::findFreeVoice() {
Voice* freeVoice = NULL;
for (int i = 0; i < NumberOfVoices; i++) {
if (!voices[i].isActive) {
freeVoice = &(voices[i]);
break;
}
}
return freeVoice;
}
void VoiceManager::onNoteOn(int noteNumber, int velocity) {
//Find a free voice, if there are no free voices it means that someone is either playing a black MIDI file of leaning on a MIDI keyboard, either way they won't notice that the 65th note didn't play so implementing vocie "stealing" (forcing a voice to become free) is not a priority. If it becomes a problem we could go up to 96 voices.
Voice* voice = findFreeVoice();
if (!voice) {
return;
}
//Make sure that our voice is shiny and new (we do this when we are about to use it since we don't want to waste time reseting a vocie that might not every be used again)
voice->reset();
voice->setNoteNumber(noteNumber);
//Velocity is essentialy a respresentation of how hard the key is being pressed, we use it to directly effect the volume of the note.
voice->mVelocity = velocity;
voice->isActive = true;
//Start the envelope
voice->mEnvelope.enterStage(EnvelopeGenerator::ENVELOPE_STAGE_ATTACK);
}
void VoiceManager::onNoteOff(int noteNumber, int velocity) {
// Find the voice(s) with the given noteNumber:
for (int i = 0; i < NumberOfVoices; i++) {
Voice& voice = voices[i];
if (voice.isActive && voice.mNoteNumber == noteNumber) {
//The voice does not turn off when the key is not being pressed, it goes into the release stage so that the sound can be faded out. If the note didn't fade their would be a sharp click whenever a note stoped playing since the waveform would be cut. The release phase of the envelope is also used for effect, it is alot like the right pedal of a piano.
voice.mEnvelope.enterStage(EnvelopeGenerator::ENVELOPE_STAGE_RELEASE);
}
}
}
double VoiceManager::nextSample() {
//Returns the sum of all voices.
double output = 0.0;
for (int i = 0; i < NumberOfVoices; i++) {
output += voices[i].nextSample();
}
//Unlike inside of each synth the voices are not averaged, they are summed. This creates the effect of multiple notes being louder then a single note. There is a small chance that this could become too loud if all of the notes happen to be in phase but this is not likely (the same chance exists with a piano or other physical insturment that playes multiple notes at the same time).
return output;
}
|
9c4aae3a1f95c31668b154dc34cb7391cceb12a4
|
cdf35d55493acd581ff2ca1fa469636189d8817d
|
/test/unit_test/sigslot_unittest.cpp
|
9dae045833f2cb4ee8e98d2ff2a6892f1bc1b83a
|
[] |
no_license
|
yagnze/vzenith_tcp_protocol
|
ba2ea7bfcc034d8555bf87f7e45710a1e2ffb82c
|
2d83e9de4d90aa80ad81b2d7b2561cf14163e1cb
|
refs/heads/master
| 2021-01-21T08:43:40.803479
| 2016-05-20T09:07:59
| 2016-05-20T09:07:59
| 54,008,143
| 1
| 0
| null | 2016-03-16T06:55:25
| 2016-03-16T06:55:24
| null |
UTF-8
|
C++
| false
| false
| 8,141
|
cpp
|
sigslot_unittest.cpp
|
/*
* vzsdk
* Copyright 2013 - 2016, Vzenith Inc.
*
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "base/sigslot.h"
#include "gunit.h"
// This function, when passed a has_slots or signalx, will break the build if
// its threading requirement is not single threaded
static bool TemplateIsST(const sigslot::single_threaded* p) {
return true;
}
// This function, when passed a has_slots or signalx, will break the build if
// its threading requirement is not multi threaded
static bool TemplateIsMT(const sigslot::multi_threaded_local* p) {
return true;
}
class SigslotDefault : public testing::Test, public sigslot::has_slots<> {
protected:
sigslot::signal0<> signal_;
};
template<class slot_policy = sigslot::single_threaded,
class signal_policy = sigslot::single_threaded>
class SigslotReceiver : public sigslot::has_slots<slot_policy> {
public:
SigslotReceiver() : signal_(NULL), signal_count_(0) {
}
~SigslotReceiver() {
}
void Connect(sigslot::signal0<signal_policy>* signal) {
if (!signal) return;
Disconnect();
signal_ = signal;
signal->connect(this,
&SigslotReceiver<slot_policy, signal_policy>::OnSignal);
}
void Disconnect() {
if (!signal_) return;
signal_->disconnect(this);
signal_ = NULL;
}
void OnSignal() {
++signal_count_;
}
int signal_count() { return signal_count_; }
private:
sigslot::signal0<signal_policy>* signal_;
int signal_count_;
};
template<class slot_policy = sigslot::single_threaded,
class mt_signal_policy = sigslot::multi_threaded_local>
class SigslotSlotTest : public testing::Test {
protected:
SigslotSlotTest() {
mt_signal_policy mt_policy;
TemplateIsMT(&mt_policy);
}
virtual void SetUp() {
Connect();
}
virtual void TearDown() {
Disconnect();
}
void Disconnect() {
st_receiver_.Disconnect();
mt_receiver_.Disconnect();
}
void Connect() {
st_receiver_.Connect(&SignalSTLoopback);
mt_receiver_.Connect(&SignalMTLoopback);
}
int st_loop_back_count() { return st_receiver_.signal_count(); }
int mt_loop_back_count() { return mt_receiver_.signal_count(); }
sigslot::signal0<> SignalSTLoopback;
SigslotReceiver<slot_policy, sigslot::single_threaded> st_receiver_;
sigslot::signal0<mt_signal_policy> SignalMTLoopback;
SigslotReceiver<slot_policy, mt_signal_policy> mt_receiver_;
};
typedef SigslotSlotTest<> SigslotSTSlotTest;
typedef SigslotSlotTest<sigslot::multi_threaded_local,
sigslot::multi_threaded_local> SigslotMTSlotTest;
class multi_threaded_local_fake : public sigslot::multi_threaded_local {
public:
multi_threaded_local_fake() : lock_count_(0), unlock_count_(0) {
}
virtual void lock() {
++lock_count_;
}
virtual void unlock() {
++unlock_count_;
}
int lock_count() { return lock_count_; }
bool InCriticalSection() { return lock_count_ != unlock_count_; }
protected:
int lock_count_;
int unlock_count_;
};
typedef SigslotSlotTest<multi_threaded_local_fake,
multi_threaded_local_fake> SigslotMTLockBase;
class SigslotMTLockTest : public SigslotMTLockBase {
protected:
SigslotMTLockTest() {}
virtual void SetUp() {
EXPECT_EQ(0, SlotLockCount());
SigslotMTLockBase::SetUp();
// Connects to two signals (ST and MT). However,
// SlotLockCount() only gets the count for the
// MT signal (there are two separate SigslotReceiver which
// keep track of their own count).
EXPECT_EQ(1, SlotLockCount());
}
virtual void TearDown() {
const int previous_lock_count = SlotLockCount();
SigslotMTLockBase::TearDown();
// Disconnects from two signals. Note analogous to SetUp().
EXPECT_EQ(previous_lock_count + 1, SlotLockCount());
}
int SlotLockCount() { return mt_receiver_.lock_count(); }
void Signal() { SignalMTLoopback(); }
int SignalLockCount() { return SignalMTLoopback.lock_count(); }
int signal_count() { return mt_loop_back_count(); }
bool InCriticalSection() { return SignalMTLoopback.InCriticalSection(); }
};
// This test will always succeed. However, if the default template instantiation
// changes from single threaded to multi threaded it will break the build here.
TEST_F(SigslotDefault, DefaultIsST) {
EXPECT_TRUE(TemplateIsST(this));
EXPECT_TRUE(TemplateIsST(&signal_));
}
// ST slot, ST signal
TEST_F(SigslotSTSlotTest, STLoopbackTest) {
SignalSTLoopback();
EXPECT_EQ(1, st_loop_back_count());
EXPECT_EQ(0, mt_loop_back_count());
}
// ST slot, MT signal
TEST_F(SigslotSTSlotTest, MTLoopbackTest) {
SignalMTLoopback();
EXPECT_EQ(1, mt_loop_back_count());
EXPECT_EQ(0, st_loop_back_count());
}
// ST slot, both ST and MT (separate) signal
TEST_F(SigslotSTSlotTest, AllLoopbackTest) {
SignalSTLoopback();
SignalMTLoopback();
EXPECT_EQ(1, mt_loop_back_count());
EXPECT_EQ(1, st_loop_back_count());
}
TEST_F(SigslotSTSlotTest, Reconnect) {
SignalSTLoopback();
SignalMTLoopback();
EXPECT_EQ(1, mt_loop_back_count());
EXPECT_EQ(1, st_loop_back_count());
Disconnect();
SignalSTLoopback();
SignalMTLoopback();
EXPECT_EQ(1, mt_loop_back_count());
EXPECT_EQ(1, st_loop_back_count());
Connect();
SignalSTLoopback();
SignalMTLoopback();
EXPECT_EQ(2, mt_loop_back_count());
EXPECT_EQ(2, st_loop_back_count());
}
// MT slot, ST signal
TEST_F(SigslotMTSlotTest, STLoopbackTest) {
SignalSTLoopback();
EXPECT_EQ(1, st_loop_back_count());
EXPECT_EQ(0, mt_loop_back_count());
}
// MT slot, MT signal
TEST_F(SigslotMTSlotTest, MTLoopbackTest) {
SignalMTLoopback();
EXPECT_EQ(1, mt_loop_back_count());
EXPECT_EQ(0, st_loop_back_count());
}
// MT slot, both ST and MT (separate) signal
TEST_F(SigslotMTSlotTest, AllLoopbackTest) {
SignalMTLoopback();
SignalSTLoopback();
EXPECT_EQ(1, st_loop_back_count());
EXPECT_EQ(1, mt_loop_back_count());
}
// Test that locks are acquired and released correctly.
TEST_F(SigslotMTLockTest, LockSanity) {
const int lock_count = SignalLockCount();
Signal();
EXPECT_FALSE(InCriticalSection());
EXPECT_EQ(lock_count + 1, SignalLockCount());
EXPECT_EQ(1, signal_count());
}
// Destroy signal and slot in different orders.
TEST(DestructionOrder, SignalFirst) {
sigslot::signal0<>* signal = new sigslot::signal0<>;
SigslotReceiver<>* receiver = new SigslotReceiver<>();
receiver->Connect(signal);
(*signal)();
EXPECT_EQ(1, receiver->signal_count());
delete signal;
delete receiver;
}
TEST(DestructionOrder, SlotFirst) {
sigslot::signal0<>* signal = new sigslot::signal0<>;
SigslotReceiver<>* receiver = new SigslotReceiver<>();
receiver->Connect(signal);
(*signal)();
EXPECT_EQ(1, receiver->signal_count());
delete receiver;
(*signal)();
delete signal;
}
|
6170023e607a90b8a3c81259a2b53334eb0506fa
|
03b5b626962b6c62fc3215154b44bbc663a44cf6
|
/src/instruction/VPCMPQ.cpp
|
bdc032f71324c72da0b1cbcac8f274ff52bb87ec
|
[] |
no_license
|
haochenprophet/iwant
|
8b1f9df8ee428148549253ce1c5d821ece0a4b4c
|
1c9bd95280216ee8cd7892a10a7355f03d77d340
|
refs/heads/master
| 2023-06-09T11:10:27.232304
| 2023-05-31T02:41:18
| 2023-05-31T02:41:18
| 67,756,957
| 17
| 5
| null | 2018-08-11T16:37:37
| 2016-09-09T02:08:46
|
C++
|
UTF-8
|
C++
| false
| false
| 183
|
cpp
|
VPCMPQ.cpp
|
#include "VPCMPQ.h"
int CVPCMPQ::my_init(void *p)
{
this->name = "CVPCMPQ";
this->alias = "VPCMPQ";
return 0;
}
CVPCMPQ::CVPCMPQ()
{
this->my_init();
}
CVPCMPQ::~CVPCMPQ()
{
}
|
3961dce0dac691bbc267648cf9a923140d18ddc6
|
f3d628043cf15afe9c7074035322f850dfbd836d
|
/codeforces/593/a/a.cpp
|
1ef9b35640237b60b13bd294f47ef743119ec841
|
[
"MIT"
] |
permissive
|
Shahraaz/CP_S5
|
6f812c37700400ea8b5ea07f3eff8dcf21a8f468
|
2cfb5467841d660c1e47cb8338ea692f10ca6e60
|
refs/heads/master
| 2021-07-26T13:19:34.205574
| 2021-06-30T07:34:30
| 2021-06-30T07:34:30
| 197,087,890
| 5
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,266
|
cpp
|
a.cpp
|
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "/debug.h"
#else
#define db(...)
#endif
#define all(v) v.begin(), v.end()
#define pb push_back
using ll = long long;
const int NAX = 2e5 + 5, MOD = 1000000007;
void solveCase()
{
int n;
cin >> n;
map<pair<char, char>, int> mp;
for (size_t i = 0; i < n; i++)
{
string str;
cin >> str;
map<char, int> cnt;
for (auto &x : str)
cnt[x]++;
if (cnt.size() == 1)
{
auto x = (cnt.begin())->first;
for (char c = 'a'; c <= 'z'; c++)
{
mp[{x, c}] += str.size();
if (x != c)
mp[{c, x}] += str.size();
}
}
else if (cnt.size() == 2)
{
auto x = (cnt.begin())->first;
auto y = (++cnt.begin())->first;
mp[{x, y}] += str.size();
mp[{y, x}] += str.size();
}
}
int res = 0;
for (auto &x : mp)
res = max(res, x.second);
cout << res << '\n';
}
int32_t main()
{
#ifndef LOCAL
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif
int t = 1;
// cin >> t;
for (int i = 1; i <= t; ++i)
solveCase();
return 0;
}
|
d72933922fc58e2afa5e48fffbae25428395498f
|
99df60ec8653b7a0c36561f06f0cc663a1ff5736
|
/poKval2017A.cpp
|
24d0c18b136a6464a96a045ea742f3032c1f0418
|
[] |
no_license
|
Istlemin/poKval2017
|
74190654d72e7c1ac773df7b6e02fd9c6d2cb209
|
ad03ce73084d82fd507ebb22b122a258f38da578
|
refs/heads/master
| 2021-08-22T13:49:03.753913
| 2017-11-30T10:38:31
| 2017-11-30T10:38:31
| 112,586,250
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 905
|
cpp
|
poKval2017A.cpp
|
#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i = a; i<int(b);++i)
#define all(v) v.begin(),v.end()
typedef long long ll;
typedef vector<ll> vi;
typedef pair<ll,ll> pii;
/*
4- och 3-grupper behöver egna sätesgrupper,
men i varje 3-grupp kan även en 1-grupp sitta,
så vi subtraherar min(3grupper,1grupper) från antal 1grupper.
Nu har vi endast 2- och 1-grupper kvar, och då går det alltid
att fylla ut så att endast en sätesgrupp inte blir tom.
Därför adderar vi bara (antal personer kvar)/4 avrundat uppåt till svaret.
Notera att om man man gör heltalsdivition avrundas default neråt,
så man måste addera 1 så länge det inte är delbart med 4
*/
int main(){
cin.sync_with_stdio(false);
vi v(5);
rep(i,1,5)
cin>>v[i];
ll ans = v[4]+v[3];
v[1] -= min(v[3],v[1]);
ans += (v[2]*2+v[1])/4;
if((v[2]*2+v[1])%4!=0) ans++;
cout<<ans<<endl;
}
|
70acfa516b5ed17d039c3ce2ba9a9678de576098
|
7eab404b358bb4b0e82d6b3a6352a29c36458422
|
/build/driver_for_ros/ros_driver/include/ros_driver/moc_qnode.cxx
|
d91dfbaf24e9a1e989e3973a5766b76f8753d46b
|
[] |
no_license
|
notlixiang/modular_joint_ws_1
|
ab682f072c90c093a5287fcdc63a6bcf040c1774
|
7249679027487dd500afc63084cdbfdf29f4750c
|
refs/heads/master
| 2021-06-28T12:08:11.456721
| 2017-09-18T12:30:39
| 2017-09-18T12:30:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,845
|
cxx
|
moc_qnode.cxx
|
/****************************************************************************
** Meta object code from reading C++ file 'qnode.hpp'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../../../../src/driver_for_ros/ros_driver/include/ros_driver/qnode.hpp"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'qnode.hpp' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.6. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_CFollowJointTrajectoryAction[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_CFollowJointTrajectoryAction[] = {
"CFollowJointTrajectoryAction\0"
};
void CFollowJointTrajectoryAction::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObjectExtraData CFollowJointTrajectoryAction::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject CFollowJointTrajectoryAction::staticMetaObject = {
{ &QThread::staticMetaObject, qt_meta_stringdata_CFollowJointTrajectoryAction,
qt_meta_data_CFollowJointTrajectoryAction, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &CFollowJointTrajectoryAction::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *CFollowJointTrajectoryAction::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *CFollowJointTrajectoryAction::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_CFollowJointTrajectoryAction))
return static_cast<void*>(const_cast< CFollowJointTrajectoryAction*>(this));
return QThread::qt_metacast(_clname);
}
int CFollowJointTrajectoryAction::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QThread::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
static const uint qt_meta_data_CJointPublisher[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_CJointPublisher[] = {
"CJointPublisher\0"
};
void CJointPublisher::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObjectExtraData CJointPublisher::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject CJointPublisher::staticMetaObject = {
{ &QThread::staticMetaObject, qt_meta_stringdata_CJointPublisher,
qt_meta_data_CJointPublisher, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &CJointPublisher::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *CJointPublisher::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *CJointPublisher::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_CJointPublisher))
return static_cast<void*>(const_cast< CJointPublisher*>(this));
return QThread::qt_metacast(_clname);
}
int CJointPublisher::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QThread::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
static const uint qt_meta_data_CDownToUp[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_CDownToUp[] = {
"CDownToUp\0"
};
void CDownToUp::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObjectExtraData CDownToUp::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject CDownToUp::staticMetaObject = {
{ &QThread::staticMetaObject, qt_meta_stringdata_CDownToUp,
qt_meta_data_CDownToUp, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &CDownToUp::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *CDownToUp::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *CDownToUp::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_CDownToUp))
return static_cast<void*>(const_cast< CDownToUp*>(this));
return QThread::qt_metacast(_clname);
}
int CDownToUp::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QThread::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
|
b8ed3e02271ac5e1afd8b7f1bdbc4ed4e4c8ba26
|
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
|
/main/source/src/core/scoring/loop_graph/Loop.hh
|
622d21225e4fa5c7d11664d2a2c01372f2f73554
|
[] |
no_license
|
MedicaicloudLink/Rosetta
|
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
|
01affdf77abb773ed375b83cdbbf58439edd8719
|
refs/heads/master
| 2020-12-07T17:52:01.350906
| 2020-01-10T08:24:09
| 2020-01-10T08:24:09
| 232,757,729
| 2
| 6
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,995
|
hh
|
Loop.hh
|
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: license@uw.edu.
/// @file core/scoring/loop_graph/Loop.hh
/// @brief
/// @details
/// @author Rhiju Das, rhiju@stanford.edu
#ifndef INCLUDED_core_scoring_loop_graph_Loop_HH
#define INCLUDED_core_scoring_loop_graph_Loop_HH
#include <utility/pointer/ReferenceCount.hh>
#include <core/scoring/loop_graph/Loop.fwd.hh>
#include <core/scoring/types.hh>
#include <iostream>
namespace core {
namespace scoring {
namespace loop_graph {
/// Directed edge between one position in the pose to another position.
/// Records takeoff_pos & landing_pos (in full_model numbering).
/// Also records 'domain', i.e. if there are multiple poses in a collection,
/// which pose.
class Loop: public utility::pointer::ReferenceCount {
public:
Loop();
Loop( Size const takeoff_pos,
Size const landing_pos,
Size const takeoff_domain,
Size const landing_domain );
//constructor
// Undefined, commenting out to fix PyRosetta build Loop();
//destructor
~Loop();
/// @brief copy constructor
Loop( Loop const & src );
Loop &
operator=( Loop const & src );
public:
void set_takeoff_pos( core::Size const & setting ){ takeoff_pos_ = setting; }
core::Size takeoff_pos() const{ return takeoff_pos_; }
void set_landing_pos( core::Size const & setting ){ landing_pos_ = setting; }
core::Size landing_pos() const{ return landing_pos_; }
void set_takeoff_domain( core::Size const & setting ){ takeoff_domain_ = setting; }
core::Size takeoff_domain() const{ return takeoff_domain_; }
void set_landing_domain( core::Size const & setting ){ landing_domain_ = setting; }
core::Size landing_domain() const{ return landing_domain_; }
/// @brief a and b are the same atom
friend
inline
bool
operator ==(
Loop const & a,
Loop const & b ){
return ( ( a.takeoff_pos_ == b.takeoff_pos_ ) &&
( a.landing_pos_ == b.landing_pos_ ) &&
( a.takeoff_domain_ == b.takeoff_domain_ ) &&
( a.landing_domain_ == b.landing_domain_ ) );
}
/// @brief Test IO operator for debug and Python bindings
friend
std::ostream & operator << ( std::ostream & os, Loop const & loop){
os << "LOOP ";
os << "TAKEOFF: ";
os << loop.takeoff_pos_ << " from domain " << loop.takeoff_domain_ << "; ";
os << "LANDING: ";
os << loop.landing_pos_ << " from domain " << loop.landing_domain_;
return os;
}
private:
core::Size takeoff_pos_;
core::Size landing_pos_;
core::Size takeoff_domain_;
core::Size landing_domain_;
};
} //loop_graph
} //scoring
} //core
#endif
|
dd458a606ae6652678050eb0da227aac9ea5477e
|
7d35157eaebee03d6532aea9fe9b4c6f636867b1
|
/MiniEngine/DescriptorHeap.cpp
|
b9d5cffa76ff961171546af096c060e2de54bae1
|
[
"MIT"
] |
permissive
|
eorfeorf/hlsl-grimoire-sample-my
|
47609214881831d38f840d037260128f59a49357
|
75de1dc9e2d003d70e398dea7f9d8783e6e36ab9
|
refs/heads/main
| 2023-06-06T22:14:42.939030
| 2021-07-20T14:53:40
| 2021-07-20T14:53:40
| 378,725,928
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,319
|
cpp
|
DescriptorHeap.cpp
|
#include "stdafx.h"
#include "DescriptorHeap.h"
DescriptorHeap::DescriptorHeap()
{
m_shaderResources.resize(MAX_SHADER_RESOURCE);
m_uavResoruces.resize(MAX_SHADER_RESOURCE);
m_constantBuffers.resize(MAX_CONSTANT_BUFFER);
for (auto& srv : m_shaderResources) {
srv = nullptr;
}
for (auto& uav : m_uavResoruces) {
uav = nullptr;
}
for (auto& cbv : m_constantBuffers) {
cbv = nullptr;
}
}
DescriptorHeap::~DescriptorHeap()
{
for (auto& ds : m_descriptorHeap) {
if (ds) {
ds->Release();
}
}
}
void DescriptorHeap::CommitSamperHeap()
{
const auto& d3dDevice = g_graphicsEngine->GetD3DDevice();
D3D12_DESCRIPTOR_HEAP_DESC srvHeapDesc = {};
srvHeapDesc.NumDescriptors = m_numSamplerDesc;
srvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER;
srvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
for (auto& ds : m_descriptorHeap) {
auto hr = d3dDevice->CreateDescriptorHeap(&srvHeapDesc, IID_PPV_ARGS(&ds));
if (FAILED(hr)) {
MessageBox(nullptr, L"DescriptorHeap::Commit ディスクリプタヒープの作成に失敗しました。", L"エラー", MB_OK);
std::abort();
}
}
int bufferNo = 0;
for (auto& descriptorHeap : m_descriptorHeap) {
auto cpuHandle = descriptorHeap->GetCPUDescriptorHandleForHeapStart();
auto gpuHandle = descriptorHeap->GetGPUDescriptorHandleForHeapStart();
for (int i = 0; i < m_numSamplerDesc; i++) {
//サンプラステートをディスクリプタヒープに登録していく。
d3dDevice->CreateSampler(&m_samplerDescs[i], cpuHandle);
cpuHandle.ptr += g_graphicsEngine->GetSapmerDescriptorSize();
}
m_samplerGpuDescriptorStart[bufferNo] = gpuHandle;
bufferNo++;
}
}
int g_numDescriptorHeap = 0;
void DescriptorHeap::Commit()
{
const auto& d3dDevice = g_graphicsEngine->GetD3DDevice();
D3D12_DESCRIPTOR_HEAP_DESC srvHeapDesc = {};
srvHeapDesc.NumDescriptors = m_numShaderResource + m_numConstantBuffer + m_numUavResource;
srvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
srvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
for (auto& ds : m_descriptorHeap) {
auto hr = d3dDevice->CreateDescriptorHeap(&srvHeapDesc, IID_PPV_ARGS(&ds));
g_numDescriptorHeap++;
if (FAILED(hr)) {
MessageBox(nullptr, L"DescriptorHeap::Commit ディスクリプタヒープの作成に失敗しました。", L"エラー", MB_OK);
std::abort();
}
}
//定数バッファやシェーダーリソースのディスクリプタをヒープに書き込んでいく。
int bufferNo = 0;
for (auto& descriptorHeap : m_descriptorHeap) {
auto cpuHandle = descriptorHeap->GetCPUDescriptorHandleForHeapStart();
auto gpuHandle = descriptorHeap->GetGPUDescriptorHandleForHeapStart();
//定数バッファを登録していく。
for (int i = 0; i < m_numConstantBuffer; i++) {
//@todo bug
if (m_constantBuffers[i] != nullptr) {
m_constantBuffers[i]->RegistConstantBufferView(cpuHandle, bufferNo);
}
//次に進める。
cpuHandle.ptr += g_graphicsEngine->GetCbrSrvDescriptorSize();
}
//続いてシェーダーリソース。
for (int i = 0; i < m_numShaderResource; i++) {
if (m_shaderResources[i] != nullptr) {
m_shaderResources[i]->RegistShaderResourceView(cpuHandle, bufferNo);
}
//次に進める。
cpuHandle.ptr += g_graphicsEngine->GetCbrSrvDescriptorSize();
}
//続いてUAV。
for (int i = 0; i < m_numUavResource; i++) {
if (m_uavResoruces[i] != nullptr) {
m_uavResoruces[i]->RegistUnorderAccessView(cpuHandle, bufferNo);
}
//次に進める。
cpuHandle.ptr += g_graphicsEngine->GetCbrSrvDescriptorSize();
}
//定数バッファのディスクリプタヒープの開始ハンドルを計算。
m_cbGpuDescriptorStart[bufferNo] = gpuHandle;
//シェーダーリソースのディスクリプタヒープの開始ハンドルを計算。
m_srGpuDescriptorStart[bufferNo] = gpuHandle;
m_srGpuDescriptorStart[bufferNo].ptr += (UINT64)g_graphicsEngine->GetCbrSrvDescriptorSize() * m_numConstantBuffer;
//UAVリソースのディスクリプタヒープの開始ハンドルを計算。
m_uavGpuDescriptorStart[bufferNo] = gpuHandle;
m_uavGpuDescriptorStart[bufferNo].ptr += (UINT64)g_graphicsEngine->GetCbrSrvDescriptorSize() * ( m_numShaderResource + m_numConstantBuffer );
bufferNo++;
}
}
|
677decd2c4b344bbe07e0c1e84820e25b69beaf1
|
a5799f38ea44cf003add43413222800bd6f0a192
|
/qmlinteg/main.cpp
|
dc0c10f906b7fde39d931d99f466b0f78002746a
|
[] |
no_license
|
muchirajunior/QTprojects
|
03a7b616e66ff95e657f6b8f4c0fb55708f04d70
|
920d6b9a97c76b674c46ed842396c1ab0db51ad5
|
refs/heads/master
| 2021-07-11T08:43:57.906077
| 2021-03-09T09:52:07
| 2021-03-09T09:52:07
| 237,191,341
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,071
|
cpp
|
main.cpp
|
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <network.h>
#include <QQmlContext>
#include <QQuickView>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
Network *net=new Network;
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("name",net);
QStringList dataList;
dataList.append("Item 1");
dataList.append("Item 2");
dataList.append("Item 3");
dataList.append("Item 4");
engine.rootContext()->setContextProperty("myModel",QVariant::fromValue(dataList));
engine.rootContext()->setContextProperty("mydel",QVariant::fromValue(dataList));
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
|
ec43d20bec1802a6983184fc6f0c10e46aa77013
|
321e235276dd0c8e23e346b518a8c1c8bbb76b44
|
/Lab -2/Задание 4.cpp
|
c5d259287cd4f8fbbf91bd5de799bbfc47a13854
|
[] |
no_license
|
Gorand174/CppLabs
|
b8441534f8f743eff9e98b9c45e35749cd2468b3
|
7f331c9b6259fd833ba9124689bfe015cff4ac0d
|
refs/heads/master
| 2021-03-12T19:28:01.683132
| 2018-02-21T08:33:54
| 2018-02-21T08:33:54
| 102,879,400
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 857
|
cpp
|
Задание 4.cpp
|
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n;
cout << "Введите размерность квадратной матрицы, а затем все её элементы: ";
cin >> n;
int **x = new int*[n];
int *y = new int[2 * n];
for (int i = 0; i < n; i++)
{
x[i] = new int[n];
for (int j = 0; j < n; j++)
cin >> x[i][j];
}
int k = 0, sum;
for (int i = n - 1; i > 0; i--)
{
sum = 0;
for (int j = i; j < n; j++)
sum += x[j][j - i];
y[k++] = sum;
}
for (int i = 0; i < n; i++)
{
sum = 0;
for (int j = i; j < n; j++)
sum += x[j - i][j];
y[k++] = sum;
}
cout << "Суммы по диагоналям: ";
for (int i = 0; i < 2 * n - 1; i++)
cout << y[i] << " ";
system("pause");
delete[]x;
delete[]y;
return 0;
}
|
2c2759d7eeada0cf2fa373f8ab8d0156b16ade47
|
c8021516af6ff81203add05d50514e2a190c8a76
|
/uart.cpp
|
f8b93fa156e9ad04692bef18b75f8b9e2e749bc2
|
[
"MIT"
] |
permissive
|
zhongchengyong/krv-os
|
bd5dd7bb5e7c4f7954f229eb822a57cb29222e7d
|
76db0ea137f06936845012f9208d37498d697968
|
refs/heads/main
| 2023-05-15T06:44:48.706426
| 2021-06-06T07:34:11
| 2021-06-06T07:34:11
| 361,130,672
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,044
|
cpp
|
uart.cpp
|
#include <cstdint>
#include "os.hh"
#include "platform.hh"
/*
* The UART control registers are memory-mapped at address UART0.
* This macro returns the address of one of the registers.
*/
#define UART_REG(reg) ((volatile uint8_t *)(UART0 + reg))
/*
* Reference
* [1]: TECHNICAL DATA ON 16550, http://byterunner.com/16550.html
*/
/*
* UART control registers map. see [1] "PROGRAMMING TABLE"
* note some are reused by multiple functions
* 0 (write mode): THR/DLL
* 1 (write mode): IER/DLM
*/
#define RHR 0 // Receive Holding Register (read mode)
#define THR 0 // Transmit Holding Register (write mode)
#define DLL 0 // LSB of Divisor Latch (write mode)
#define IER 1 // Interrupt Enable Register (write mode)
#define DLM 1 // MSB of Divisor Latch (write mode)
#define FCR 2 // FIFO Control Register (write mode)
#define ISR 2 // Interrupt Status Register (read mode)
#define LCR 3 // Line Control Register
#define MCR 4 // Modem Control Register
#define LSR 5 // Line Status Register
#define MSR 6 // Modem Status Register
#define SPR 7 // ScratchPad Register
/*
* POWER UP DEFAULTS
* IER = 0: TX/RX holding register interrupts are bith disabled
* ISR = 1: no interrupt penting
* LCR = 0
* MCR = 0
* LSR = 60 HEX
* MSR = BITS 0-3 = 0, BITS 4-7 = inputs
* FCR = 0
* TX = High
* OP1 = High
* OP2 = High
* RTS = High
* DTR = High
* RXRDY = High
* TXRDY = Low
* INT = Low
*/
/*
* LINE STATUS REGISTER (LSR)
* LSR BIT 0:
* 0 = no data in receive holding register or FIFO.
* 1 = data has been receive and saved in the receive holding register or FIFO.
* ......
* LSR BIT 5:
* 0 = transmit holding register is full. 16550 will not accept any data for
* transmission. 1 = transmitter hold register (or FIFO) is empty. CPU can load
* the next character.
* ......
*/
#define LSR_RX_READY (1 << 0)
#define LSR_TX_IDLE (1 << 5)
#define uart_read_reg(reg) (*(UART_REG(reg)))
#define uart_write_reg(reg, v) (*(UART_REG(reg)) = (v))
void uart_init() {
/* disable interrupts. */
uart_write_reg(IER, 0x00);
/*
* Setting baud rate. Just a demo here if we care about the divisor,
* but for our purpose [QEMU-virt], this doesn't really do anything.
*
* Notice that the divisor register DLL (divisor latch least) and DLM (divisor
* latch most) have the same base address as the receiver/transmitter and the
* interrupt enable register. To change what the base address points to, we
* open the "divisor latch" by writing 1 into the Divisor Latch Access Bit
* (DLAB), which is bit index 7 of the Line Control Register (LCR).
*
* Regarding the baud rate value, see [1] "BAUD RATE GENERATOR PROGRAMMING
* TABLE". We use 38.4K when 1.8432 MHZ crystal, so the corresponding value
* is 3. And due to the divisor register is two bytes (16 bits), so we need to
* split the value of 3(0x0003) into two bytes, DLL stores the low byte,
* DLM stores the high byte.
*/
uint8_t lcr = uart_read_reg(LCR);
uart_write_reg(LCR, lcr | (1 << 7));
uart_write_reg(DLL, 0x03);
uart_write_reg(DLM, 0x00);
/*
* Continue setting the asynchronous data communication format.
* - number of the word length: 8 bits
* - number of stop bits:1 bit when word length is 8 bits
* - no parity
* - no break control
* - disabled baud latch
*/
lcr = 0;
uart_write_reg(LCR, lcr | (3 << 0));
/*
* enable receive interrupts.
*/
uint8_t ier = uart_read_reg(IER);
uart_write_reg(IER, ier | (1 << 0));
}
int uart_putc(const char ch) {
while ((uart_read_reg(LSR) & LSR_TX_IDLE) == 0)
;
return uart_write_reg(THR, ch);
}
void uart_puts(const char *s) {
while (*s) {
uart_putc(*s++);
}
}
/**
* Get char from RX
*/
int uart_getc(void) {
if (uart_read_reg(LSR) & LSR_RX_READY) {
return uart_read_reg(RHR);
} else {
return -1;
}
}
/**
* Uart trap handler
*/
void uart_isr() {
while (1) {
int c = uart_getc();
if (c == -1) {
break;
} else {
uart_putc((char)c);
uart_putc('\n');
}
}
}
|
cdc78977f58f77b435885ba2023b348c92dbce46
|
9c1ccd9bd02acee2e2bce759f32580258ec9389a
|
/c++file/nonlinear/src/Ham_Dirac.hpp
|
14edd0c119caf3c654fb2cd3b71dbb3f947bf5e7
|
[] |
no_license
|
YoshihiroMichishita/Test_Codes
|
220c0afef0aa9249ba64b42dcddc64dd93409d4d
|
faffe66a402cc0b825d814af815c1e4c35d2d7a6
|
refs/heads/master
| 2023-05-11T21:32:14.399405
| 2021-05-30T10:45:29
| 2021-05-30T10:45:29
| 324,497,442
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,158
|
hpp
|
Ham_Dirac.hpp
|
#pragma once
#include "const.hpp"
#include "parm_Dirac.hpp"
#include "matrix_op_mypc.hpp"
using namespace std;
// THis is the class for calculating the concrete Hamiltonian, velocity operator, and Green functions.
static const int M = 2;
static const int Mf = 2;
static const int D = 3;
void H_mom(parm parm_, double k[D], Complex H[M*M]);
void H_mom_BI(parm parm_, double k[D], Complex H[M*M], Complex VR_k[M*M], Complex VL_b[M*M],Complex E[M]);
void BI_Velocity(Complex Vx[M*M],Complex Vy[M*M],Complex Vxx[M*M],Complex Vyx[M*M], Complex VR_k[M*M], Complex VL_b[M*M], Complex Vx_LR[M*M], Complex Vy_LR[M*M], Complex Vxx_LR[M*M], Complex Vyx_LR[M*M]);
void H_mom_NH(parm parm_, double k[D], Complex H[M*M], Complex VR_k[M*M], Complex VR_b[M*M], Complex VL_k[M*M],Complex VL_b[M*M],Complex E_NH[M]);
void NH_factor(Complex Vx[M*M],Complex Vxx[M*M], Complex VR_k[M*M], Complex VR_b[M*M], Complex VL_k[M*M],Complex VL_b[M*M]
, Complex Vx_LL[M*M], Complex Vx_RR[M*M], Complex Vx_LR[M*M],Complex Vxx_LL[M*M],Complex Vxx_LR[M*M], double NH_fac[M]);
void Vx(parm parm_, double k[D], Complex H[M*M]);
void Vxx(parm parm_, double k[D], Complex H[M*M]);
void GreenR_mom(parm parm_, double w, double im[Mf], double re[Mf],Complex H[M*M], Complex G[M*M]);
void dGreenR_mom(parm parm_, double w,double dw, double im[Mf], double re[Mf],Complex H[M*M], Complex G[M*M], Complex dG[M*M]);
void dGreenR_mom2(Complex G[M*M], Complex dG[M*M]);
void GreenA_mom(parm parm_, double w, double im[Mf], double re[Mf],Complex H[M*M], Complex G[M*M]);
void GreenR_minusA(Complex GR[M*M], Complex GA[M*M], Complex G[M*M]);
void GreenR_mom_p(parm parm_,double w,double W,double im[Mf],double re[Mf],Complex H[M*M],Complex GRp[M*M]);
void GreenR_mom_m(parm parm_,double w,double W,double im[Mf],double re[Mf],Complex H[M*M],Complex GRm[M*M]);
void GreenA_mom_p(parm parm_,double w,double W,double im[Mf],double re[Mf],Complex H[M*M],Complex GAp[M*M]);
void GreenA_mom_m(parm parm_,double w,double W,double im[Mf],double re[Mf],Complex H[M*M],Complex GAm[M*M]);
void GreenR_mom_pp(parm parm_,double w,double W,double im[Mf],double re[Mf],Complex H[M*M],Complex GRpp[M*M]);
void GreenA_mom_mm(parm parm_,double w,double W,double im[Mf],double re[Mf],Complex H[M*M],Complex GAmm[M*M]);
class Ham{
public:
Complex H_k[M*M];
Complex VX[M*M],VY[M*M],VZ[M*M];
Complex VXX[M*M],VYX[M*M],VYXX[M*M];
Complex VR_k[M*M],VL_b[M*M],VR_b[M*M],VL_k[M*M],E_NH[M];
double EN[M];
Complex VX_LL[M*M],VX_LR[M*M],VX_RR[M*M],VZ_LL[M*M],VZ_LR[M*M],VZ_RR[M*M],VY_RR[M*M],VY_LR[M*M],VY_LL[M*M];
Complex VXX_LR[M*M],VXX_LL[M*M];
double NH_fac[M];
Ham();
Ham(parm parm_,double k[D],int sw);
~Ham();
};
class Green{
public:
Complex GR[M*M],dGR[M*M],GA[M*M],GRp[M*M],GRm[M*M],GAp[M*M],GAm[M*M],GRpp[M*M],GAmm[M*M],GRmA[M*M];
Green();
Green(parm parm_,double w,double im[Mf],double re[Mf],Complex H[M*M]);
Green(parm parm_,double w, double dw, double im[Mf],double re[Mf],Complex H[M*M]);
~Green();
};
|
5492b2c3bf73797f4c8d5ddced042bfb47f1bea7
|
e2847929f485edb74dda23e63dff0b59e93998d2
|
/0119.pascals-triangle-ii/pascals-triangle-ii.cpp
|
477666a737efbbccab9f68f8717d63d2797fb4e0
|
[] |
no_license
|
hbsun2113/LeetCodeCrawler
|
36b068641fa0b485ac51c2cd151498ce7c27599f
|
43507e04eb41160ecfd859de41fd42d798431d00
|
refs/heads/master
| 2020-05-23T21:11:32.158160
| 2019-10-18T07:20:39
| 2019-10-18T07:20:39
| 186,947,546
| 5
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 406
|
cpp
|
pascals-triangle-ii.cpp
|
//经验题:https://www.cnblogs.com/springfor/p/3887913.html。
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> result(rowIndex+1);
result[0]=1;
for(int i=0;i<rowIndex+1;i++){//其实外循环就是挨层算的。
for(int j=i;j>0;j--){
result[j]=result[j]+result[j-1];
}
}
return result;
}
};
|
1e0c1591bc76508f80777faac7dba2d08b8e9348
|
fb31b110bf497183e8121d646d0746d14c6f90e2
|
/eactivity/OnlineAdvices.cpp
|
e2861ed64fc541d595f1b01f018e14c69fd3413b
|
[] |
no_license
|
densaface/eactivity
|
b829df9e7451fc7bdc60e1d507164b5ee64ffe23
|
4cd442410137b87591aa7c967f1b9aec0e89b71a
|
refs/heads/master
| 2022-12-07T20:25:33.498652
| 2020-08-30T10:58:44
| 2020-08-30T10:58:44
| 291,453,744
| 1
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 13,187
|
cpp
|
OnlineAdvices.cpp
|
// OnlineAdvices.cpp : implementation file
//
#include "stdafx.h"
#include "eactivity.h"
#include "OnlineAdvices.h"
//#include "externals/sqlite/sqlitetchar.h"
//#include "externals/sqlite/sha512/sha512_helper.h"
// COnlineAdvices dialog
IMPLEMENT_DYNAMIC(COnlineAdvices, CDialog)
COnlineAdvices::COnlineAdvices(CWnd* pParent /*=NULL*/)
: CDialog(COnlineAdvices::IDD, pParent)
{
dRate = -1;
}
COnlineAdvices::~COnlineAdvices()
{
}
void COnlineAdvices::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_STATIC_rate, stat_rate);
DDX_Control(pDX, IDC_CHECK1, check_details);
DDX_Control(pDX, IDC_SLIDER4, slider_rate);
DDX_Control(pDX, IDC_SLIDER1, slider_rate1);
DDX_Control(pDX, IDC_SLIDER3, slider_rate2);
DDX_Control(pDX, IDC_SLIDER2, slider_rate3);
DDX_Control(pDX, IDC_STATIC1, stat_rate_desc);
DDX_Control(pDX, IDC_STATIC2, stat_rate_desc1);
DDX_Control(pDX, IDC_STATIC3, stat_rate_desc2);
DDX_Control(pDX, IDC_STATIC4, stat_rate_desc3);
DDX_Control(pDX, IDC_EDIT1, edit_message);
}
BEGIN_MESSAGE_MAP(COnlineAdvices, CDialog)
ON_BN_CLICKED(IDC_BUTTON1, &COnlineAdvices::OnBnClickedButton1)
ON_BN_CLICKED(IDOK, &COnlineAdvices::OnBnClickedOk)
ON_BN_CLICKED(IDCANCEL, &COnlineAdvices::OnBnClickedCancel)
ON_BN_CLICKED(IDC_CHECK1, &COnlineAdvices::OnBnClickedCheck1)
ON_WM_HSCROLL()
// ON_NOTIFY(NM_CUSTOMDRAW, IDC_SLIDER4, &COnlineAdvices::OnNMCustomdrawSlider4)
// ON_NOTIFY(NM_CUSTOMDRAW, IDC_SLIDER1, &COnlineAdvices::OnNMCustomdrawSlider1)
// ON_NOTIFY(NM_CUSTOMDRAW, IDC_SLIDER3, &COnlineAdvices::OnNMCustomdrawSlider3)
// ON_NOTIFY(NM_CUSTOMDRAW, IDC_SLIDER2, &COnlineAdvices::OnNMCustomdrawSlider2)
ON_BN_CLICKED(IDC_BUTTON2, &COnlineAdvices::OnBnClickedButton2)
END_MESSAGE_MAP()
//если все сообщения показывались раньше, то снова берется с самой высокой
// оценкой и записывается в журнал как показанное во второй раз
BOOL COnlineAdvices::OnInitDialog()
{
CDialog::OnInitDialog();
slider_rate .SetRange(1,6);
slider_rate1.SetRange(1,6);
slider_rate2.SetRange(1,6);
slider_rate3.SetRange(1,6);
slider_rate .SetPos(6);
slider_rate1.SetPos(6);
slider_rate2.SetPos(6);
slider_rate3.SetPos(6);
CString str;
str.LoadString(trif.GetIds(IDS_STRING1763));
string ip = trif.getSqlIp(path_actuser.c_str());
if (ip == "")
{
abnormalExit("get_sql_ip_error!");
return FALSE;
}
mySql = new ConnWorkMySql(ip, "eactivity_user", "djgvyetgjdbu",
"eactivity_text_messages", 3306);
if (mySql->connectError)
{
abnormalExit("sql_connect_error!");
return FALSE;
}
// mySql = new ConnWorkMySql("localhost", "eactivity_user", "djgvyetgjdbu",
// "eactivity_text_messages", 3306);
mysql_row *myRows;
mySql->query("SET NAMES \'cp1251\'");
myRows = mySql->fetch(mySql->query(
"SELECT * FROM text_mes WHERE moderate_type = 1 ORDER BY rate DESC;"));
int minShown = 9999999; int index_min=0;
bool shown = false;
for (int ii = 0; ii < myRows->fields; ii++)
{
int shwnCount = isMessageShown(atoi(myRows[ii].row[0]._data.c_str()));
if (!shwnCount)
{
ShowMessage(atoi(myRows[ii].row[0]._data.c_str()),
myRows[ii].row[1]._data,
myRows[ii].row[2]._data,
myRows[ii].row[3]._data,
atoi(myRows[ii].row[4]._data.c_str()),
atof(myRows[ii].row[5]._data.c_str()),
atof(myRows[ii].row[6]._data.c_str()),
atof(myRows[ii].row[7]._data.c_str()),
atof(myRows[ii].row[8]._data.c_str())
/*, atof(myRows[ii].row[8]._data.c_str())*/);
shown = true;
break;
} else {
if (shwnCount < minShown)
{
minShown = shwnCount; index_min = ii;
}
}
}
//если все сообщения уже показаны, то показываем сообщение, которое
//меньше других показывалось
if (!shown)
{
ShowMessage(atoi(myRows[index_min].row[0]._data.c_str()),
myRows[index_min].row[1]._data,
myRows[index_min].row[2]._data,
myRows[index_min].row[3]._data,
atoi(myRows[index_min].row[4]._data.c_str()),
atof(myRows[index_min].row[5]._data.c_str()),
atof(myRows[index_min].row[6]._data.c_str()),
atof(myRows[index_min].row[7]._data.c_str()),
atof(myRows[index_min].row[8]._data.c_str())
/*, atof(myRows[ii].row[8]._data.c_str())*/);
}
char ch[2048];
CAddOnlineAdvice dialAddAdvice;
userSID = dialAddAdvice.getUserSID();
noVote = false;
if (userSID.length())
{
sprintf_s(ch, "SELECT * FROM rates WHERE id = %d AND user_sid = '%s';", id_mes, userSID.c_str());
myRows = mySql->fetch(mySql->query(ch));
if (myRows && myRows->fields>0)
noVote = true;
}
if (noVote)
{ //отменяем голосование - уже раньше за это выражение голосовали
GetDlgItem(IDC_STATIC7)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_STATIC1)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_STATIC2)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_STATIC3)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_STATIC4)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_STATIC10)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_SLIDER1)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_SLIDER2)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_SLIDER3)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_SLIDER4)->ShowWindow(SW_HIDE);
}
delete myRows;
return TRUE;
}
// экстренный выход из диалога
BOOL COnlineAdvices::abnormalExit(CString textError)
{
CStdioFile sfLog;
string fileName = path_actuser + "journal_online_advices.txt";
if (sfLog.Open(fileName.c_str(), CFile::modeWrite) ||
sfLog.Open(fileName.c_str(), CFile::modeWrite|CFile::modeCreate))
{
sfLog.SeekToEnd();
CTime ct=CTime::GetCurrentTime();
char ch[1024];
sprintf_s(ch, "%02d.%02d.%02d %02d:%02d:%02d\t %s\n",
ct.GetYear(), ct.GetMonth(), ct.GetDay(),
ct.GetHour(), ct.GetMinute(), ct.GetSecond(), textError);
sfLog.WriteString(ch);
sfLog.Close();
}
CDialog::OnCancel();
return TRUE;
}
void COnlineAdvices::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
CSliderCtrl* pSlider = reinterpret_cast<CSliderCtrl*>(pScrollBar);
int sliderNum = -1;
if (pSlider == &slider_rate)
sliderNum = 0;
else if (pSlider == &slider_rate1)
sliderNum = 1;
else if (pSlider == &slider_rate2)
sliderNum = 2;
else if (pSlider == &slider_rate3)
sliderNum = 3;
// switch(nSBCode)
// {
// case TB_LINEUP:
// case TB_LINEDOWN:
// case TB_PAGEUP:
// case TB_PAGEDOWN:
// case TB_THUMBPOSITION:
// case TB_TOP:
// case TB_BOTTOM:
// case TB_THUMBTRACK:
// case TB_ENDTRACK:
// default:
// break;
//
CString str;
char ch[1024];
switch (sliderNum)
{
case 0:
str.LoadString(trif.GetIds(IDS_STRING1761));
sprintf_s(ch, str, slider_rate.GetPos());
str = ch;
if (slider_rate.GetPos() == 6)
str.Replace("(6)", "(?)");
stat_rate_desc.SetWindowText(str);
break;
case 1:
if (slider_rate1.GetPos() < 6)
{
str.LoadString(trif.GetIds(IDS_STRING1763+2*slider_rate1.GetPos()));
} else {
str.LoadString(trif.GetIds(IDS_STRING1763));
}
stat_rate_desc1.SetWindowText(str);
break;
case 2:
if (slider_rate2.GetPos() < 6)
{
str.LoadString(trif.GetIds(IDS_STRING1775+2*slider_rate2.GetPos()));
} else {
str.LoadString(trif.GetIds(IDS_STRING1775));
}
stat_rate_desc2.SetWindowText(str);
break;
case 3:
if (slider_rate3.GetPos() < 6)
{
str.LoadString(trif.GetIds(IDS_STRING1787 + 2*slider_rate3.GetPos()));
} else {
str.LoadString(trif.GetIds(IDS_STRING1787));
}
stat_rate_desc3.SetWindowText(str);
break;
}
CDialog::OnHScroll(nSBCode, nPos, pScrollBar);
}
void COnlineAdvices::OnBnClickedButton1()
{
CAddOnlineAdvice dialAddAdvice;
dialAddAdvice.path_actuser = path_actuser;
dialAddAdvice.DoModal();
}
//Проверка: показывалось ли сообщение ранее (присутствует в
//журнале показанных сообщений)
BOOL COnlineAdvices::isMessageShown(int id_mes)
{
string fileName = path_actuser + "journal_online_advices.txt";
ifstream ifstr(fileName.c_str());
if (ifstr==NULL)
return FALSE;
char ch[1024];
string str;
char patt[] = "(id_mes = %d";
char for_find[100];
sprintf_s(for_find, patt, id_mes);
int res=0;
for (;;)
{
ifstr.getline(ch, 1024, '\n');
str = ch;
if (str.find(for_find)!=std::string::npos)
{
res++;
}
if (!ifstr)
{
ifstr.close();
return res;
}
}
ifstr.close();
return res;
}
void COnlineAdvices::ShowMessage(int id, string message, string owner_mes,
string user, int moderate_type, double rate, double rate1, double rate2,
double rate3/*, float rate4*/)
{
LOGFONT lf;
CFont* old = edit_message.GetFont();
old->GetLogFont(&lf);
CFont newfont;
newfont.CreateFont(lf.lfHeight+30, 0, lf.lfEscapement, lf.lfOrientation,
lf.lfWeight, lf.lfItalic, lf.lfUnderline,
lf.lfStrikeOut, lf.lfCharSet, lf.lfOutPrecision,
lf.lfClipPrecision, lf.lfQuality, lf.lfPitchAndFamily, lf.lfFaceName);
edit_message.SetFont(&newfont);
char ch[5000];
CString patMes;
patMes.LoadString(trif.GetIds(IDS_STRING1849));
sprintf_s(ch, patMes, message.c_str(), owner_mes.c_str(), user.c_str());
edit_message.SetWindowText(ch);
id_mes = id;
dRate = rate;
dRate1 = rate1;
dRate2 = rate2;
dRate3 = rate3;
CStdioFile sfLog;
string fileName = path_actuser + "journal_online_advices.txt";
if (!sfLog.Open(fileName.c_str(), CFile::modeWrite))
if (!sfLog.Open(fileName.c_str(), CFile::modeWrite|CFile::modeCreate))
return;
sfLog.SeekToEnd();
CTime ct=CTime::GetCurrentTime();
sprintf_s(ch, "%02d.%02d.%02d %02d:%02d:%02d\t %s (id_mes = %d, user = %s, owner = %s, rate = %0.2f)\n",
ct.GetYear(), ct.GetMonth(), ct.GetDay(),
ct.GetHour(), ct.GetMinute(), ct.GetSecond(),
message.c_str(), id, user.c_str(), owner_mes.c_str(), dRate);
sfLog.WriteString(ch);
sfLog.Close();
OnBnClickedCheck1();
}
void COnlineAdvices::OnBnClickedOk()
{
OnOK();
}
void COnlineAdvices::OnCancel()
{
CDialog::OnCancel();
}
void COnlineAdvices::OnBnClickedCancel()
{
if (!noVote && slider_rate .GetPos()==6 && slider_rate1.GetPos()==6 &&
slider_rate2.GetPos()==6 && slider_rate3.GetPos()==6)
{
AfxMessageBox(trif.GetIds(IDS_STRING1799));
return;
}
char ch[4096];
sprintf_s(ch,
"insert into rates (id, rate, rate1, rate2, rate3, rate4, user_sid) values (%d,'%d','%d','%d','%d','%d','%s');",
id_mes, slider_rate.GetPos(), slider_rate1.GetPos(), slider_rate2.GetPos(), slider_rate3.GetPos(), 0, userSID.c_str());
CString strReq = ch;
strReq.Replace("'6'", "NULL"); //6-ка - это отсуствие голоса и для более
//точного вычисления среднего ставим оценку NULL
string sReq = strReq;
mySql->query(sReq);
OnCancel();
CDialog::OnCancel();
}
void COnlineAdvices::OnBnClickedCheck1()
{
if (dRate==-1)
return;
char ch_mes[5000];
CString sRate;
if (dRate==0 && dRate1==0 && dRate2==0 && dRate3==0)
{
stat_rate.ShowWindow(SW_HIDE);
check_details.ShowWindow(SW_HIDE);
}
if (check_details.GetCheck())
{
sRate.LoadString(trif.GetIds(IDS_STRING1757));
sprintf_s(ch_mes, sRate, dRate, dRate1, dRate2, dRate3);
stat_rate.SetWindowText(ch_mes);
} else {
sRate.LoadString(trif.GetIds(IDS_STRING1759));
sprintf_s(ch_mes, sRate, dRate);
stat_rate.SetWindowText(ch_mes);
}
}
void COnlineAdvices::OnNMCustomdrawSlider4(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR);
CString str;
str.LoadString(trif.GetIds(IDS_STRING1761));
char ch[1024];
sprintf_s(ch, str, slider_rate.GetPos());
str = ch;
if (slider_rate.GetPos() == 6)
str.Replace("(6)", "(?)");
stat_rate_desc.SetWindowText(str);
*pResult = 0;
}
void COnlineAdvices::OnNMCustomdrawSlider1(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR);
CString str;
if (slider_rate1.GetPos() < 6)
{
str.LoadString(trif.GetIds(IDS_STRING1763+2*slider_rate1.GetPos()));
} else {
str.LoadString(trif.GetIds(IDS_STRING1763));
}
stat_rate_desc1.SetWindowText(str);
*pResult = 0;
}
void COnlineAdvices::OnNMCustomdrawSlider3(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR);
CString str;
if (slider_rate2.GetPos() < 6)
{
str.LoadString(trif.GetIds(IDS_STRING1775+2*slider_rate2.GetPos()));
} else {
str.LoadString(trif.GetIds(IDS_STRING1775));
}
stat_rate_desc2.SetWindowText(str);
*pResult = 0;
}
void COnlineAdvices::OnNMCustomdrawSlider2(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR);
CString str;
if (slider_rate3.GetPos() < 6)
{
str.LoadString(trif.GetIds(IDS_STRING1787 + 2*slider_rate3.GetPos()));
} else {
str.LoadString(trif.GetIds(IDS_STRING1787));
}
stat_rate_desc3.SetWindowText(str);
*pResult = 0;
}
void COnlineAdvices::OnBnClickedButton2()
{
string fileName = path_actuser + "journal_online_advices.txt";
ShellExecute(0,"open", "notepad.exe", fileName.c_str(), NULL,SW_MAXIMIZE);
}
|
65b79909193da31c07d045d60047df05fc8cd5f4
|
07871afa90e215e0e1868e50f1fba45322963de1
|
/src/akonadi/akonaditaskqueries.h
|
37f6025744ac9e628fb2e7f918bcc46213414f83
|
[] |
no_license
|
KDE/zanshin
|
8b9ab01e44649ef28f2b37bdf95feae2da0db82c
|
8da5c5f37de387c7551cbc63551eed9465c8004c
|
refs/heads/master
| 2023-09-01T00:05:00.128302
| 2023-08-28T02:17:16
| 2023-08-28T02:17:16
| 42,735,781
| 17
| 5
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,022
|
h
|
akonaditaskqueries.h
|
/*
* SPDX-FileCopyrightText: 2014 Kevin Ottens <ervin@kde.org>
* SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#ifndef AKONADI_TASKQUERIES_H
#define AKONADI_TASKQUERIES_H
#include "domain/taskqueries.h"
#include "akonadi/akonadicache.h"
#include "akonadi/akonadilivequeryhelpers.h"
#include "akonadi/akonadilivequeryintegrator.h"
class QTimer;
namespace Akonadi {
class TaskQueries : public QObject, public Domain::TaskQueries
{
Q_OBJECT
public:
typedef QSharedPointer<TaskQueries> Ptr;
typedef Domain::LiveQueryInput<Akonadi::Item> ItemInputQuery;
typedef Domain::LiveQueryOutput<Domain::Task::Ptr> TaskQueryOutput;
typedef Domain::QueryResultProvider<Domain::Task::Ptr> TaskProvider;
typedef Domain::QueryResult<Domain::Task::Ptr> TaskResult;
typedef Domain::QueryResult<Domain::Context::Ptr> ContextResult;
typedef Domain::LiveQueryOutput<Domain::Context::Ptr> ContextQueryOutput;
typedef Domain::QueryResult<Domain::Project::Ptr> ProjectResult;
typedef Domain::LiveQueryOutput<Domain::Project::Ptr> ProjectQueryOutput;
typedef Domain::QueryResult<Domain::DataSource::Ptr> DataSourceResult;
typedef Domain::LiveQueryOutput<Domain::DataSource::Ptr> DataSourceQueryOutput;
TaskQueries(const StorageInterface::Ptr &storage,
const SerializerInterface::Ptr &serializer,
const MonitorInterface::Ptr &monitor,
const Cache::Ptr &cache);
int workdayPollInterval() const;
void setWorkdayPollInterval(int interval);
TaskResult::Ptr findAll() const override;
TaskResult::Ptr findChildren(Domain::Task::Ptr task) const override;
TaskResult::Ptr findTopLevel() const override;
TaskResult::Ptr findInboxTopLevel() const override;
TaskResult::Ptr findWorkdayTopLevel() const override;
ContextResult::Ptr findContexts(Domain::Task::Ptr task) const override;
ProjectResult::Ptr findProject(Domain::Task::Ptr task) const override;
DataSourceResult::Ptr findDataSource(Domain::Task::Ptr task) const override;
private slots:
void onWorkdayPollTimeout();
private:
SerializerInterface::Ptr m_serializer;
MonitorInterface::Ptr m_monitor;
Cache::Ptr m_cache;
LiveQueryHelpers::Ptr m_helpers;
LiveQueryIntegrator::Ptr m_integrator;
QTimer *m_workdayPollTimer;
mutable QDate m_today;
mutable TaskQueryOutput::Ptr m_findAll;
mutable QHash<Akonadi::Item::Id, TaskQueryOutput::Ptr> m_findChildren;
mutable QHash<Akonadi::Item::Id, ProjectQueryOutput::Ptr> m_findProject;
mutable QHash<Akonadi::Item::Id, ContextQueryOutput::Ptr> m_findContexts;
mutable QHash<Akonadi::Item::Id, Akonadi::Item> m_findContextsItem;
mutable QHash<Akonadi::Item::Id, DataSourceQueryOutput::Ptr> m_findDataSource;
mutable TaskQueryOutput::Ptr m_findTopLevel;
mutable TaskQueryOutput::Ptr m_findInboxTopLevel;
mutable TaskQueryOutput::Ptr m_findWorkdayTopLevel;
};
}
#endif // AKONADI_TASKQUERIES_H
|
f1b4728956ecc7281616cbd1b2c363f15347e377
|
c3fa72d4894941c121f4acf675fb7c4deaa4c4b8
|
/17.audio_player_decode_by_ffmpeg_play_by_qt/main.cpp
|
149d11509a9aaf1d049476bd34c58ab13be68b44
|
[
"MIT"
] |
permissive
|
asdlei99/ffmpeg_beginner
|
d8e0a318574f86ba2c792bc7d9e0096663be6cad
|
3b1f086cb568f3ed2167c111bc7b59df1ba0308b
|
refs/heads/main
| 2023-08-15T12:22:00.208740
| 2021-10-15T09:24:56
| 2021-10-15T09:24:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,027
|
cpp
|
main.cpp
|
#include <iostream>
using namespace std;
#include <QString>
#include <QByteArray>
#include <QDebug>
#include <QFile>
#include <QAudioFormat>
#include <QAudioOutput>
#include <QTimer>
#include <QTest>
extern "C"{
#include "libavcodec/avcodec.h"
#include "libavfilter/avfilter.h"
#include "libavformat/avformat.h"
#include "libavutil/avutil.h"
#include "libavutil/ffversion.h"
#include "libswresample/swresample.h"
#include "libswscale/swscale.h"
#include "libpostproc/postprocess.h"
}
#define MAX_AUDIO_FRAME_SIZE 192000
int main()
{
QString _url="/home/jackey/Music/test.mp3";
QAudioOutput *audioOutput;
QIODevice *streamOut;
QAudioFormat audioFmt;
audioFmt.setSampleRate(44100);
audioFmt.setChannelCount(2);
audioFmt.setSampleSize(16);
audioFmt.setCodec("audio/pcm");
audioFmt.setByteOrder(QAudioFormat::LittleEndian);
audioFmt.setSampleType(QAudioFormat::SignedInt);
QAudioDeviceInfo info = QAudioDeviceInfo::defaultOutputDevice();
if(!info.isFormatSupported(audioFmt)){
audioFmt = info.nearestFormat(audioFmt);
}
audioOutput = new QAudioOutput(audioFmt);
audioOutput->setVolume(100);
streamOut = audioOutput->start();
AVFormatContext *fmtCtx =avformat_alloc_context();
AVCodecContext *codecCtx = NULL;
AVPacket *pkt=av_packet_alloc();
AVFrame *frame = av_frame_alloc();
int aStreamIndex = -1;
do{
if(avformat_open_input(&fmtCtx,_url.toLocal8Bit().data(),NULL,NULL)<0){
qDebug("Cannot open input file.");
return -1;
}
if(avformat_find_stream_info(fmtCtx,NULL)<0){
qDebug("Cannot find any stream in file.");
return -1;
}
av_dump_format(fmtCtx,0,_url.toLocal8Bit().data(),0);
for(size_t i=0;i<fmtCtx->nb_streams;i++){
if(fmtCtx->streams[i]->codecpar->codec_type==AVMEDIA_TYPE_AUDIO){
aStreamIndex=(int)i;
break;
}
}
if(aStreamIndex==-1){
qDebug("Cannot find audio stream.");
return -1;
}
AVCodecParameters *aCodecPara = fmtCtx->streams[aStreamIndex]->codecpar;
AVCodec *codec = avcodec_find_decoder(aCodecPara->codec_id);
if(!codec){
qDebug("Cannot find any codec for audio.");
return -1;
}
codecCtx = avcodec_alloc_context3(codec);
if(avcodec_parameters_to_context(codecCtx,aCodecPara)<0){
qDebug("Cannot alloc codec context.");
return -1;
}
codecCtx->pkt_timebase = fmtCtx->streams[aStreamIndex]->time_base;
if(avcodec_open2(codecCtx,codec,NULL)<0){
qDebug("Cannot open audio codec.");
return -1;
}
//设置转码参数
uint64_t out_channel_layout = codecCtx->channel_layout;
enum AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;
int out_sample_rate = codecCtx->sample_rate;
int out_channels = av_get_channel_layout_nb_channels(out_channel_layout);
//printf("out rate : %d , out_channel is: %d\n",out_sample_rate,out_channels);
uint8_t *audio_out_buffer = (uint8_t*)av_malloc(MAX_AUDIO_FRAME_SIZE*2);
SwrContext *swr_ctx = swr_alloc_set_opts(NULL,
out_channel_layout,
out_sample_fmt,
out_sample_rate,
codecCtx->channel_layout,
codecCtx->sample_fmt,
codecCtx->sample_rate,
0,NULL);
swr_init(swr_ctx);
double sleep_time=0;
while(av_read_frame(fmtCtx,pkt)>=0){
if(pkt->stream_index==aStreamIndex){
if(avcodec_send_packet(codecCtx,pkt)>=0){
while(avcodec_receive_frame(codecCtx,frame)>=0){
if(av_sample_fmt_is_planar(codecCtx->sample_fmt)){
int len = swr_convert(swr_ctx,
&audio_out_buffer,
MAX_AUDIO_FRAME_SIZE*2,
(const uint8_t**)frame->data,
frame->nb_samples);
if(len<=0){
continue;
}
//qDebug("convert length is: %d.\n",len);
int out_size = av_samples_get_buffer_size(0,
out_channels,
len,
out_sample_fmt,
1);
//qDebug("buffer size is: %d.",dst_bufsize);
sleep_time=(out_sample_rate*16*2/8)/out_size;
if(audioOutput->bytesFree()<out_size){
QTest::qSleep(sleep_time);
streamOut->write((char*)audio_out_buffer,out_size);
}else {
streamOut->write((char*)audio_out_buffer,out_size);
}
//将数据写入PCM文件
//fwrite(audio_out_buffer,1,dst_bufsize,file);
}
}
}
}
av_packet_unref(pkt);
}
}while(0);
av_frame_free(&frame);
av_packet_free(&pkt);
avcodec_close(codecCtx);
avcodec_free_context(&codecCtx);
avformat_free_context(fmtCtx);
streamOut->close();
return 0;
}
|
ad99ae3a71c353e463eb002389f903f7663002be
|
a0408c9c0022ef1d12dd1b4524426864f1390ffe
|
/21调整数组顺序使奇数位于偶数前面.cpp
|
fbea59f5b003f50cb5edcd0a5f2e52a8a684a0e8
|
[] |
no_license
|
Snowstorm0/SwordtoOffer
|
fbfa36139289e968556c05a9b0f5be70da9a5784
|
12611618848409c62727ff6520d90cc589dc9c89
|
refs/heads/master
| 2022-12-23T18:26:19.987369
| 2020-09-18T14:06:36
| 2020-09-18T14:06:36
| 275,362,185
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,078
|
cpp
|
21调整数组顺序使奇数位于偶数前面.cpp
|
// 面试题21:调整数组顺序使奇数位于偶数前面
// 题目:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有
// 奇数位于数组的前半部分,所有偶数位于数组的后半部分。
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <queue>
#include<iostream>
#include <stack>
#include<cstdlib>
#include <string>
using namespace std;
void reOrderArray(vector<int> &arr)
{
int len = arr.size();
if (len == 0)
return;
vector<int> res;
for (int i = 0; i < len; i++)
{
if (arr[i] & 1) // 奇数
res.push_back(arr[i]);
}
for (int i = 0; i < len; i++)
{
if (!(arr[i] & 1)) // 偶数
res.push_back(arr[i]);
}
arr = res;
}
// ====================测试代码====================
int main()
{
vector<int> array = { 1,2,3,4,5 };
reOrderArray(array);
int len = array.size();
for (int i = 0; i < len; i++)
{
cout << array[i];
}
system("pause");
}
|
a9c58a98b95a135a416bec7d31387b63e7ac1af3
|
4ae7357ab97ee31519c67ea3ce3b1822d5035062
|
/ISort.cpp
|
993f337fa10c1c67c9e5b012da5b2d5a216810f5
|
[] |
no_license
|
s33dd/lab3_2021
|
65e2ed515e173a552f29554b3147bc4f8268d76c
|
0b4965523592d0c594285812183147515da235b0
|
refs/heads/master
| 2023-05-04T10:02:40.631925
| 2021-05-22T13:12:51
| 2021-05-22T13:12:51
| 368,268,122
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,122
|
cpp
|
ISort.cpp
|
#include "ISort.h"
ISort::ISort() {
m_switchCounter = 0;
m_compareCounter = 0;
}
BubbleSort::BubbleSort() {
m_compareCounter = 0;
m_switchCounter = 0;
}
void BubbleSort::SortMatrix(Matrix& matrix) {
int temp = 0;
m_compareCounter = 0;
m_switchCounter = 0;
for (int n = 0; n < (matrix.m_matrixColumns * matrix.m_matrixRows); n++) {
bool switched = false;
for (int j = 0; j < matrix.m_matrixColumns; j++) {
for (int i = 0; i < matrix.m_matrixRows; i++) {
if(i == matrix.m_matrixRows - 1) {
continue;
}
m_compareCounter++;
if (matrix.m_matrix[i][j] < matrix.m_matrix[i + 1][j]) {
m_switchCounter++;
switched = true;
temp = matrix.m_matrix[i + 1][j];
matrix.m_matrix[i + 1][j] = matrix.m_matrix[i][j];
matrix.m_matrix[i][j] = temp;
}
}
}
if (!switched) {
break;
}
}
}
void BubbleSort::SortNumber(Matrix &matrix) {
char temp;
std::string number;
for (int i = 0; i < matrix.m_matrixRows; i++) {
for (int j = 0; j < matrix.m_matrixColumns; j++) {
number = std::to_string(abs(matrix.m_matrix[i][j]));
__int64 digits = (__int64)number.length();
for (__int64 k = digits - 1; k > 0; k--) {
bool switched = false;
for (__int64 n = 0; n < k; n++) {
m_compareCounter++;
if (number[n] > number[n + 1]) {
temp = number[n];
number[n] = number[n + 1];
number[n + 1] = temp;
m_switchCounter++;
switched = true;
if (matrix.m_matrix[i][j] < 0) {
matrix.m_matrix[i][j] = -stoi(number);
}
else {
matrix.m_matrix[i][j] = stoi(number);
}
}
}
if(!switched) {
break;
}
}
}
}
}
int BubbleSort::GetCompares(void){
return m_compareCounter;
}
int BubbleSort::GetSwitches(void) {
return m_switchCounter;
}
SelectionSort::SelectionSort() {
m_compareCounter = 0;
m_switchCounter = 0;
}
void SelectionSort::SortMatrix(Matrix &matrix) {
int temp = 0;
m_compareCounter = 0;
m_switchCounter = 0;
for (int j = 0; j < matrix.m_matrixColumns; j++) {
for (int start = 0; start < matrix.m_matrixRows - 1; start++) {
int biggest = start;
for (int current = start + 1; current < matrix.m_matrixRows; current++) {
m_compareCounter++;
if (matrix.m_matrix[current][j] > matrix.m_matrix[biggest][j]) {
biggest = current;
}
}
if (start != biggest) {
temp = matrix.m_matrix[start][j];
matrix.m_matrix[start][j] = matrix.m_matrix[biggest][j];
matrix.m_matrix[biggest][j] = temp;
m_switchCounter++;
}
}
}
}
void SelectionSort::SortNumber(Matrix &matrix) {
char temp;
std::string number;
for (int i = 0; i < matrix.m_matrixRows; i++) {
for (int j = 0; j < matrix.m_matrixColumns; j++) {
number = std::to_string(abs(matrix.m_matrix[i][j]));
__int64 digits = (__int64)number.length();
for (int start = 0; start < digits - 1; start++) {
int smallest = start;
for (int current = start + 1; current < digits; current++) {
m_compareCounter++;
if (number[current] < number[smallest]) {
smallest = current;
}
}
if (start != smallest) {
temp = number[start];
number[start] = number[smallest];
number[smallest] = temp;
m_switchCounter++;
if (matrix.m_matrix[i][j] < 0) {
matrix.m_matrix[i][j] = -stoi(number);
}
else {
matrix.m_matrix[i][j] = stoi(number);
}
}
}
}
}
}
int SelectionSort::GetCompares(void) {
return m_compareCounter;
}
int SelectionSort::GetSwitches(void) {
return m_switchCounter;
}
InsertionSort::InsertionSort() {
m_compareCounter = 0;
m_switchCounter = 0;
}
void InsertionSort::SortMatrix(Matrix &matrix) {
int temp = 0;
int compare = 0;
m_compareCounter = 0;
m_switchCounter = 0;
for (int j = 0; j < matrix.m_matrixColumns; j++) {
for (int i = 0; i < matrix.m_matrixRows - 1; i++) {
compare = i + 1;
temp = matrix.m_matrix[compare][j];
bool switched = true;
for (int next = i + 1; ((next > 0) && (switched == true)); next--) {
switched = false;
m_compareCounter++;
if (matrix.m_matrix[next - 1][j] < temp) {
switched = true;
m_switchCounter++;
matrix.m_matrix[next][j] = matrix.m_matrix[next - 1][j];
compare = next-1;
}
}
matrix.m_matrix[compare][j] = temp;
}
}
}
void InsertionSort::SortNumber(Matrix &matrix) {
char temp;
__int64 compare = 0;
std::string number;
for (int i = 0; i < matrix.m_matrixRows; i++) {
for (int j = 0; j < matrix.m_matrixColumns; j++) {
number = std::to_string(abs(matrix.m_matrix[i][j]));
__int64 digits = (__int64)number.length();
for (__int64 k = 0; k < digits - 1; k++) {
compare = k + 1;
temp = number[compare];
bool switched = true;
for (__int64 next = k + 1; ((next > 0) && (switched == true)); next--) {
switched = false;
m_compareCounter++;
if (number[next - 1] > temp) {
switched = true;
m_switchCounter++;
number[next] = number[next - 1];
compare = next - 1;
}
}
number[compare] = temp;
}
if (matrix.m_matrix[i][j] < 0) {
matrix.m_matrix[i][j] = -stoi(number);
}
else {
matrix.m_matrix[i][j] = stoi(number);
}
}
}
}
int InsertionSort::GetCompares(void) {
return m_compareCounter;
}
int InsertionSort::GetSwitches(void) {
return m_switchCounter;
}
ShellSort::ShellSort() {
m_compareCounter = 0;
m_switchCounter = 0;
}
void ShellSort::SortMatrix(Matrix &matrix) {
int temp = 0;
int distance = matrix.m_matrixRows;
distance /= 2;
m_compareCounter = 0;
m_switchCounter = 0;
while (distance > 0) {
for (int j = 0; j < matrix.m_matrixColumns; j++) {
for (int i = 0; i < matrix.m_matrixRows - distance; i++) {
bool switched = true;
for (int k = i; ((k >= 0) && (switched == true)); k--) {
switched = false;
m_compareCounter++;
if (matrix.m_matrix[k][j] < matrix.m_matrix[k + distance][j]) {
switched = true;
m_switchCounter++;
temp = matrix.m_matrix[k + distance][j];
matrix.m_matrix[k + distance][j] = matrix.m_matrix[k][j];
matrix.m_matrix[k][j] = temp;
}
}
}
}
distance /= 2;
}
}
void ShellSort::SortNumber(Matrix &matrix) {
char temp;
std::string number;
for (int i = 0; i < matrix.m_matrixRows; i++) {
for (int j = 0; j < matrix.m_matrixColumns; j++) {
number = std::to_string(abs(matrix.m_matrix[i][j]));
__int64 digits = (__int64)number.length();
__int64 distance = digits;
distance /= 2;
while (distance > 0) {
for (__int64 k = 0; k < digits - distance; k++) {
bool switched = true;
for (__int64 z = k; ((z >= 0) && (switched == true)); z--) {
switched = false;
m_compareCounter++;
if (number[z] > number[z + distance]) {
switched = true;
m_switchCounter++;
temp = number[z];
number[z] = number[z + distance];
number[z + distance] = temp;
}
}
}
distance /= 2;
if (matrix.m_matrix[i][j] < 0) {
matrix.m_matrix[i][j] = -stoi(number);
}
else {
matrix.m_matrix[i][j] = stoi(number);
}
}
}
}
}
int ShellSort::GetCompares(void) {
return m_compareCounter;
}
int ShellSort::GetSwitches(void) {
return m_switchCounter;
}
QuickSort::QuickSort() {
m_compareCounter = 0;
m_switchCounter = 0;
}
void QuickSort::SortMatrix(Matrix &matrix) {
int *column = new int[matrix.m_matrixRows];
for (int j = 0; j < matrix.m_matrixColumns; j++) {
for (int i = 0; i < matrix.m_matrixRows; i++) {
column[i] = matrix.m_matrix[i][j];
}
OneDimensionalSort(column, 0, matrix.m_matrixRows);
for (int k = 0; k < matrix.m_matrixRows; k++) {
matrix.m_matrix[k][j] = column[k];
}
}
delete[] column;
}
void QuickSort::SortNumber(Matrix &matrix) {
std::string number;
for (int i = 0; i < matrix.m_matrixRows; i++) {
for (int j = 0; j < matrix.m_matrixColumns; j++) {
number = std::to_string(abs(matrix.m_matrix[i][j]));
__int64 digits = (__int64)number.length();
OneDimensionalNumberSort(number, 0, digits);
if (matrix.m_matrix[i][j] < 0) {
matrix.m_matrix[i][j] = -stoi(number);
}
else {
matrix.m_matrix[i][j] = stoi(number);
}
}
}
}
void QuickSort::OneDimensionalNumberSort(std::string &number, __int64 firstIndex, __int64 size) {
__int64 leftBorder = firstIndex;
__int64 rightBorder = size - 1;
char temp;
char comparingElement = number[firstIndex];
while (leftBorder <= rightBorder) {
while (number[leftBorder] < comparingElement) {
leftBorder++;
m_compareCounter++;
}
while (number[rightBorder] > comparingElement) {
rightBorder--;
m_compareCounter++;
}
if (leftBorder <= rightBorder) {
m_switchCounter++;
temp = number[leftBorder];
number[leftBorder] = number[rightBorder];
number[rightBorder] = temp;
leftBorder++;
rightBorder--;
}
}
if (rightBorder > firstIndex) {
OneDimensionalNumberSort(number, firstIndex, rightBorder + 1);
}
if (leftBorder < size) {
OneDimensionalNumberSort(number, leftBorder, size);
}
}
void QuickSort::OneDimensionalSort(int *array, int firstIndex, int size) {
int leftBorder = firstIndex;
int rightBorder = size - 1;
int temp = 0;
int comparingElement = array[firstIndex];
while (leftBorder <= rightBorder) {
m_compareCounter++;
while (array[leftBorder] > comparingElement) {
leftBorder++;
m_compareCounter++;
}
m_compareCounter++;
while (array[rightBorder] < comparingElement) {
rightBorder--;
m_compareCounter++;
}
if (leftBorder <= rightBorder) {
m_switchCounter++;
temp = array[rightBorder];
array[rightBorder] = array[leftBorder];
array[leftBorder] = temp;
leftBorder++;
rightBorder--;
}
}
if (rightBorder > firstIndex) {
OneDimensionalSort(array, firstIndex, rightBorder + 1);
}
if (leftBorder < size) {
OneDimensionalSort(array, leftBorder, size);
}
}
int QuickSort::GetCompares(void) {
return m_compareCounter;
}
int QuickSort::GetSwitches(void) {
return m_switchCounter;
}
void QuickSort::SetCompares(int compares) {
m_compareCounter = compares;
}
void QuickSort::SetSwitches(int switches) {
m_switchCounter = switches;
}
|
16b98055e5aeada77c2e75ff0e0a10c9936af766
|
3fa71d87dc2a9ecc7c04d525e71a51f3a02ada01
|
/Hmwk/C++_Review/Gaddis_8thEd_Chap5_Prob11/Chap5_Prob11.cpp
|
46ae602ee4ef3ad2d66449e3b15ebf800a97636b
|
[] |
no_license
|
kinnaripatel03/CSC17A-1
|
b176d8307a73fc051f49adc8c7c52babcef1ef70
|
89192346c3d0de705095d97e468926484b9529d2
|
refs/heads/master
| 2020-04-04T14:52:56.805532
| 2017-12-04T08:08:59
| 2017-12-04T08:08:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,584
|
cpp
|
Chap5_Prob11.cpp
|
/*
* File: Population
* Author: Jose Morales
* Purpose: Temp for all the programs
* Created on September 13, 2016, 11:19 AM
*/
//System Libraries
#include <iostream>
using namespace std;
//Global Constants
//Function Prototypes
void ttlPop(int,int,float);
//Execution Begins Here
int main(int argc, char** argv) {
//Declare Variables
float popIncr;
int srtPop,numDays;
//Input Data
cout<<"Population Prediction"<<endl;
//Don't accept a number less than 2
do{
cout<<"Enter the starting number of organisms:"<<endl;
cin>>srtPop;
cout<<endl;
if(srtPop < 2){
cout<<"Number has to be more than 1."<<endl;
}
}while(srtPop < 2);
//Don't accept a negative number
do{
cout<<"Enter the the average daily population increase as a percent:"<<endl;
cin>>popIncr;
cout<<endl;
if(popIncr < 0){
cout<<"Can't be a negative number."<<endl;
}
}while(popIncr < 0);
//Don't accept a number less than 1.
do{
cout<<"Enter the number of days they should multiply:"<<endl;
cin>>numDays;
cout<<endl;
if(numDays <2){
cout<<"Number has to be more than 1."<<endl;
}
}while(numDays < 2);
//Process Data
//Output Data
ttlPop(srtPop,numDays,popIncr);
return 0;
}
void ttlPop(int Pop,int Days,float Cent){
for(int c = 0; c <= Days; c++){
cout<<"Day:"<<c<<" Space:"<<Pop<<endl;
Pop+=(Pop * Cent)/100.0f ;
}
}
|
65f647c229a8a4c4d817c34999f812f924ff4205
|
e1a2fdc28415080e14b0cb76313c01e9c102ed12
|
/src/dp/dp.h
|
13531410ab8a914f8835928c47903b71a554c3e2
|
[
"BSD-3-Clause"
] |
permissive
|
stevendbrown/diamond
|
ab088ed43718065ae1020392d46baef368f2e92b
|
5162c0919dbef3022c8e73a7085dbd7960ec8e96
|
refs/heads/master
| 2021-01-17T20:48:45.128145
| 2017-02-21T23:51:01
| 2017-02-21T23:51:01
| 65,657,999
| 0
| 0
| null | 2017-02-21T23:51:02
| 2016-08-14T08:53:25
|
C++
|
UTF-8
|
C++
| false
| false
| 5,236
|
h
|
dp.h
|
/****
Copyright (c) 2016, University of Tuebingen, Benjamin Buchfink
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.
****/
#ifndef DP_H_
#define DP_H_
#include <utility>
#include "../basic/match.h"
#include "../align/align.h"
#include "score_profile.h"
void init_cbs();
struct No_score_correction
{
void operator()(int &score, int i, int query_anchor, int mult) const
{}
};
struct Bias_correction : public vector<float>
{
Bias_correction(const sequence &seq);
void operator()(float &score, int i, int query_anchor, int mult) const
{
score += (*this)[query_anchor + i*mult];
}
int operator()(const Hsp_data &hsp) const;
};
template<typename _score>
void smith_waterman(const Letter *query, local_match &segment, _score gap_open, _score gap_extend, vector<char> &transcript_buf, const _score& = int());
int smith_waterman(const sequence &query, const sequence &subject, unsigned band, unsigned padding, int op, int ep);
int xdrop_ungapped(const Letter *query, const Letter *subject, unsigned seed_len, unsigned &delta, unsigned &len);
int xdrop_ungapped(const Letter *query, const Letter *subject, unsigned &delta, unsigned &len);
int xdrop_ungapped_right(const Letter *query, const Letter *subject, int &len);
void greedy_align(sequence query, sequence subject, const vector<Diagonal_segment> &sh, bool log);
void greedy_align(sequence query, sequence subject, const Diagonal_segment &sh, bool log);
void greedy_align(sequence query, const Long_score_profile &qp, sequence subject, const Diagonal_segment &sh, bool log);
void greedy_align2(sequence query, const Long_score_profile &qp, sequence subject, const vector<Diagonal_segment> &sh, bool log, Hsp_data &out);
void greedy_align(sequence query, const Long_score_profile &qp, sequence subject, int qa, int sa, bool log);
int estimate_score(const Long_score_profile &qp, sequence s, int d, int d1, bool log);
template<typename _t>
struct Fixed_score_buffer
{
inline void init(size_t col_size, size_t cols, _t init)
{
col_size_ = col_size;
data_.clear();
data_.reserve(col_size * cols);
data_.resize(col_size);
for (size_t i = 0; i<col_size; ++i)
data_[i] = init;
}
inline std::pair<_t*, _t*> get()
{
data_.resize(data_.size() + col_size_);
_t* ptr = last();
return std::pair<_t*, _t*>(ptr - col_size_, ptr);
}
inline _t* last()
{
return &*(data_.end() - col_size_);
}
const _t* column(int col) const
{
return &data_[col_size_*col];
}
_t operator()(int i, int j) const
{
return data_[j*col_size_ + i];
}
friend std::ostream& operator<<(std::ostream &s, const Fixed_score_buffer &buf)
{
for (int i = 0; i < buf.col_size_; ++i) {
for (int j = 0; j < buf.data_.size() / buf.col_size_; ++j)
s << buf(i, j) << '\t';
s << endl;
}
return s;
}
private:
vector<_t> data_;
size_t col_size_;
};
struct Diagonal_node : public Diagonal_segment
{
struct Edge
{
Edge() :
prefix_score(0),
node(),
exact(true)
{}
Edge(int prefix_score, int j, unsigned node, bool exact) :
prefix_score(prefix_score),
j(j),
node(node),
exact(exact)
{}
operator int() const
{
return prefix_score;
}
int prefix_score, j;
unsigned node;
bool exact;
};
Diagonal_node() :
Diagonal_segment(),
diff(std::numeric_limits<int>::min())
{}
Diagonal_node(int query_pos, int subject_pos, int len, int score) :
Diagonal_segment(query_pos, subject_pos, len, score),
diff(std::numeric_limits<int>::min())
{}
Diagonal_node(const Diagonal_segment &d) :
Diagonal_segment(d),
diff(std::numeric_limits<int>::min())
{}
enum { n_path = 2 };
Top_list<Edge, n_path> edges;
int diff;
};
int needleman_wunsch(sequence query, sequence subject, int qbegin, int qend, int sbegin, int send, unsigned node, unsigned edge, vector<Diagonal_node> &diags, bool log);
#endif /* FLOATING_SW_H_ */
|
120b4c2b0f6781a3da0332fbad5d75ff710adc1e
|
38af1e7e3ed5a993dc6db6bb172c2471ea9e192f
|
/grammar/statements/methods/MethodInvocation.cpp
|
e0aba12994c292c5e967b16b76a0a5818ba7bc7e
|
[] |
no_license
|
zhukovp0101/compilers
|
b87f118ae2b3874f51ab1a0bd0e2e4e8170ff28e
|
8299dcdd8f577538e4a83e03490d5f5eafef65f3
|
refs/heads/master
| 2022-07-14T20:43:05.809153
| 2020-05-22T01:16:36
| 2020-05-22T01:16:36
| 265,988,081
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 367
|
cpp
|
MethodInvocation.cpp
|
//
// Created by bevertax on 02.04.2020.
//
#include "MethodInvocation.h"
MethodInvocation::MethodInvocation(Expression *caller, std::string_view identifier,
List<Expression> *arguments): caller_(caller), identifier_(identifier), arguments_(arguments) {}
void MethodInvocation::Accept(Visitor *visitor) {
visitor->Visit(this);
}
|
ac4f7d1526e8506d2bcdb1922bec34a964375d2e
|
4c08d143040db7f8c638481612455ee318f2478d
|
/Leetcode/Easy/L198.cpp
|
d84ff8dc2a9df8fef0065038798923b53ea0e3a9
|
[] |
no_license
|
ganeshskudva/Algorithms
|
1e8f47767ffcfc8e381d054cfb6816f42030d9c9
|
530a8c38d92d65003e0f8dcf57757a1147c42c65
|
refs/heads/master
| 2021-07-14T01:22:00.788658
| 2021-03-29T17:56:17
| 2021-03-29T17:56:17
| 25,098,710
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 715
|
cpp
|
L198.cpp
|
// 198. House Robber
class Solution {
public:
int rob(vector<int>& nums) {
int n=nums.size();
vector<int> dp(n);
if(n==0){return 0;}
if(n==1){
return nums[0];
}
if(n==2){
if(nums[0]>nums[1]){
return nums[0];
}
else{
return nums[1];
}
}
dp[0]=nums[0];
dp[1]=nums[1];
dp[2]=dp[0]+nums[2];
for(int i=3;i<n;i++){
dp[i]=max(nums[i]+dp[i-2],nums[i]+dp[i-3]);
}
int max=0;
for(int i=0;i<n;i++){
if(dp[i]>max){
max=dp[i];
}
}
return max;
}
};
|
4eb3b556eb78c11a7fa49d45493c931e68bf312c
|
83913b4691c2436ba95e0221f4ac3cba21e79ec7
|
/main.cpp
|
cce605083d864ea400aabbcb332bcdcaa482865b
|
[] |
no_license
|
tinkertom/ELEC143-buggy_enhancement_2
|
3cb8a6d7a5c5760bc0dfe3853cdb1804de7ed771
|
d6a05a4d8ec288dcccd8d7488f02421a0addd4ec
|
refs/heads/master
| 2020-11-26T03:33:40.676258
| 2020-01-05T21:46:06
| 2020-01-05T21:46:06
| 228,953,547
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,556
|
cpp
|
main.cpp
|
#include "mbed.h"
#include "buggy.h"
int main()
{
// Debugging serial connection.
Serial terminal(USBTX, USBRX);
terminal.baud(115200);
// Indication LED.
DigitalOut led(LED1);
// User control switch.
DigitalIn user_switch(USER_BUTTON);
// Declare buggy struct, passing all the necessary pin names.
// |left motor______________| |right motor________________|
// |PWM pin| |PWM pin|
// | |direction pin| | |direction pin|
// | |hall sensor pins| | |hall sensor pins|
Buggy buggy = {{PA_8, PA_9, {PB_2, PB_1}}, {PB_4, PB_10, {PB_15, PB_14}}};
// Calibrate motors.
terminal.printf("press button to calibrate\n\r");
while (user_switch == 1);
calibrate_motor(&buggy.motor_a);
calibrate_motor(&buggy.motor_b);
terminal.printf("motor_a inversion = %d\n\r", buggy.motor_a.inverted);
terminal.printf("motor_b inversion = %d\n\r", buggy.motor_b.inverted);
// LED1 indicates that buggy has been calibrated.
led = 1;
while (user_switch == 0);
while (true) {
while (user_switch == 1);
// Wait for finger to clear from buggy.
wait_us(500000);
// Buggy triangle sequence instructions.
// Travel forward, wiat, rotate, and repeat.
move_buggy(&buggy, FORWARD, 1.7f);
wait_us(5000);
rotate_buggy(&buggy, 144.0f);
wait_us(5000);
move_buggy(&buggy, FORWARD, 2.04f);
wait_us(5000);
rotate_buggy(&buggy, 116.0f);
wait_us(5000);
move_buggy(&buggy, FORWARD, 1.02f);
wait_us(5000);
rotate_buggy(&buggy, 90.0f);
}
}
|
6877cdaf2ea93224e850a2042a2ffa5d0e4e3b55
|
88b130d5ff52d96248d8b946cfb0faaadb731769
|
/document/src/vespa/document/datatype/datatype.h
|
8deca98eb742b92c9de0a706a3d82316faae5094
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
vespa-engine/vespa
|
b8cfe266de7f9a9be6f2557c55bef52c3a9d7cdb
|
1f8213997718c25942c38402202ae9e51572d89f
|
refs/heads/master
| 2023-08-16T21:01:12.296208
| 2023-08-16T17:03:08
| 2023-08-16T17:03:08
| 60,377,070
| 4,889
| 619
|
Apache-2.0
| 2023-09-14T21:02:11
| 2016-06-03T20:54:20
|
Java
|
UTF-8
|
C++
| false
| false
| 5,941
|
h
|
datatype.h
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
* \class document::DataType
* \ingroup datatype
*
* \brief Specifies what is legal to store in a given field value.
*/
#pragma once
#include <vespa/document/util/printable.h>
#include <vespa/vespalib/stllike/string.h>
#include <memory>
#include <vector>
namespace document {
class FieldValue;
class Field;
class FieldPath;
class ArrayDataType;
class CollectionDataType;
class DocumentType;
class MapDataType;
class NumericDataType;
class PrimitiveDataType;
class ReferenceDataType;
class TensorDataType;
class WeightedSetDataType;
class DataType : public Printable
{
int _dataTypeId;
vespalib::string _name;
protected:
/**
* Creates a datatype. Note that datatypes must be configured to work with
* the entire system, you can't just create them on the fly and expect
* everyone to be able to use them. Only tests and the type manager reading
* config should need to create datatypes.
*/
DataType(vespalib::stringref name, int dataTypeId) noexcept;
/**
* Creates a datatype using the hash of name as the id.
*/
explicit DataType(vespalib::stringref name) noexcept;
public:
~DataType() override;
using UP = std::unique_ptr<DataType>;
using SP = std::shared_ptr<DataType>;
/**
* Enumeration of primitive data type identifiers. (Complex types uses
* hashed identifiers.
*
* <b>NOTE:</b> These types are also defined in the java source (in file
* "document/src/java/com/yahoo/document/DataType.java". Changes done
* here must also be applied there.
*/
enum Type {
T_INT = 0,
T_FLOAT = 1,
T_STRING = 2,
T_RAW = 3,
T_LONG = 4,
T_DOUBLE = 5,
T_BOOL = 6,
T_DOCUMENT = 8, // Type of super document type Document.0 that all documents inherit.
// T_TIMESTAMP = 9, // Not used anymore, Id should probably not be reused
T_URI = 10,
// T_EXACTSTRING = 11, // Not used anymore, Id should probably not be reused
// T_CONTENT = 12, // Not used anymore, Id should probably not be reused
// T_CONTENTMETA = 13, // Not used anymore, Id should probably not be reused
// T_MAILADDRESS = 14, // Not used anymore, Id should probably not be reused
// T_TERMBOOST = 15, // Not used anymore, Id should probably not be reused
T_BYTE = 16,
T_TAG = 18,
T_SHORT = 19,
T_PREDICATE = 20,
T_TENSOR = 21,
MAX
};
static const DataType *const BYTE;
static const DataType *const SHORT;
static const DataType *const INT;
static const DataType *const LONG;
static const DataType *const FLOAT;
static const DataType *const DOUBLE;
static const DataType *const BOOL;
static const DataType *const STRING;
static const DataType *const RAW;
static const DocumentType *const DOCUMENT;
static const DataType *const TAG;
static const DataType *const URI;
static const DataType *const PREDICATE;
static const DataType *const TENSOR;
/** Used by type manager to fetch default types to register. */
static std::vector<const DataType *> getDefaultDataTypes();
const vespalib::string& getName() const noexcept { return _name; }
int getId() const noexcept { return _dataTypeId; }
bool isValueType(const FieldValue & fv) const;
/**
* Create a field value using this datatype.
*/
virtual std::unique_ptr<FieldValue> createFieldValue() const = 0;
virtual bool isWeightedSet() const noexcept { return false; }
virtual bool isArray() const noexcept { return false; }
virtual bool isDocument() const noexcept { return false; }
virtual bool isTensor() const noexcept { return false; }
virtual bool isPrimitive() const noexcept { return false; }
virtual bool isNumeric() const noexcept { return false; }
virtual bool isStructured() const noexcept { return false; }
virtual const CollectionDataType * cast_collection() const noexcept { return nullptr; }
virtual const MapDataType * cast_map() const noexcept { return nullptr; }
virtual const ReferenceDataType * cast_reference() const noexcept { return nullptr; }
virtual const TensorDataType* cast_tensor() const noexcept { return nullptr; }
bool isMap() const { return cast_map() != nullptr; }
/**
* Whether another datatype is a supertype of this one. Document types may
* be due to inheritance. For other types, they must be identical for this
* to match.
*/
virtual bool isA(const DataType& other) const { return equals(other); }
virtual bool equals(const DataType & other) const noexcept {
return _dataTypeId == other._dataTypeId;
}
bool operator == (const DataType & other) const noexcept {
return equals(other);
}
int cmpId(const DataType& b) const {
return (_dataTypeId < b._dataTypeId)
? -1
: (b._dataTypeId < _dataTypeId)
? 1
: 0;
}
/**
* This takes a . separated fieldname and gives you back the path of
* fields you have to apply to get to your leaf.
* @param remainFieldName. The remaining part of the fieldname that you want the path of.
* MUST be null-terminated.
* @return pointer to field path or null if an error occured
*/
void buildFieldPath(FieldPath & fieldPath, vespalib::stringref remainFieldName) const;
/** @throws FieldNotFoundException if field does not exist. */
virtual const Field& getField(int fieldId) const;
private:
virtual void onBuildFieldPath(FieldPath & fieldPath, vespalib::stringref remainFieldName) const = 0;
};
} // document
|
c31ec2c4f81d5ee31881bf0a5b567fe3bea6dc8e
|
c2a7acc0367fedf6e2b26437680f9749a4a47985
|
/Spoj/TOANDFRO.cpp
|
cbfea779665396b969be07c04df4b89ee76227c7
|
[] |
no_license
|
UtkarshGupta-CS/Mind-Sport
|
2d94ecc8ca1a26193b427c9d1d254718607060bc
|
05270782780ff1c9cbea844b3d89e8b09e30a0db
|
refs/heads/master
| 2021-01-19T17:25:54.815642
| 2018-04-07T01:26:13
| 2018-04-07T01:26:13
| 82,457,095
| 1
| 1
| null | 2017-07-07T06:53:55
| 2017-02-19T12:25:20
|
C++
|
UTF-8
|
C++
| false
| false
| 807
|
cpp
|
TOANDFRO.cpp
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
int c;
cin >> c;
while (c != 0)
{
string s;
cin >> s;
int len = s.length();
int i = 0, j = 0, count = 0, cond1 = 2 * c - 1, cond2 = 1;
bool choice = true;
while (count != len)
{
if (i < len)
{
cout << s[i];
count++;
if (choice)
{
i += cond1;
choice = false;
}
else
{
i += cond2;
choice = true;
}
}
else
{
++j;
i = j;
cond1 -= 2;
cond2 += 2;
choice = true;
}
}
cout << "\n";
cin >> c;
}
}
|
1d9913308c9804b3e64dc051dca457e26a905db9
|
81f1f2006d7c1787e1be8f153f45f05f95f68c60
|
/kernel.cpp
|
b28ad5e16f6b924c119e50eec3240cebc6f6e822
|
[] |
no_license
|
kriot/Contrast
|
ad7934cb2824b9c1f5a3ae2b5031b731e4f3e565
|
8cc269d005f22dfa7c6b3c0a1245ba4d038bd183
|
HEAD
| 2016-09-06T15:13:20.346473
| 2015-07-06T23:07:14
| 2015-07-06T23:07:14
| 38,651,269
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,102
|
cpp
|
kernel.cpp
|
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <opencv2/opencv.hpp>
const double alpha = 0.01/255;
const int kernel_size = 20;
std::vector<long long> calcHist(const cv::Mat& img, int ch, int i0, int j0, int i1, int j1)
{
std::vector<long long> res(256, 0);
for(int i = i0; i < i1; ++i)
for(int j = j0; j < j1; ++j)
{
res[img.at<cv::Vec3b>(i, j)[ch]]++;
}
return res;
}
int main(int argc, char** argv)
{
if(argc == 1)
{
std::cerr << "Image name is needed\n";
return -1;
}
cv::Mat image = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);
if(!image.data)
{
std::cerr << "Cant read image\n";
return -1;
}
std::cout << "Image is read\n";
//Contrast
for(int i = 0; i < image.rows - 1; ++i) //Awful thing
for(int j = 0; j < image.cols; ++j)
for(int ch = 0; ch < 3; ++ch)
{
int begin = 0, end = 255;
std::vector<std::vector<long long>> hist = {
calcHist(image, 0, std::max(i - kernel_size, 0), std::max(j - kernel_size, 0), std::min(i + kernel_size, image.rows), std::min(j + kernel_size, image.cols)),
calcHist(image, 1, std::max(i - kernel_size, 0), std::max(j - kernel_size, 0), std::min(i + kernel_size, image.rows), std::min(j + kernel_size, image.cols)),
calcHist(image, 2, std::max(i - kernel_size, 0), std::max(j - kernel_size, 0), std::min(i + kernel_size, image.rows), std::min(j + kernel_size, image.cols))};
auto y = [=](int begin){ return 0.11*hist[0][begin] + 0.59*hist[1][begin] + 0.3*hist[2][begin]; };
while(y(begin) < alpha*kernel_size*kernel_size && begin < end - 1)
begin++;
while(y(end) < alpha*kernel_size*kernel_size && begin < end - 1)
end--;
auto f = [&](int x) { return std::min(std::max((x - begin) * 255 / (end - begin), 0), 255); };
int v = image.at<cv::Vec3b>(i, j)[ch];
image.at<cv::Vec3b>(i, j)[ch] = f(v);
}
cv::namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
cv::imshow( "Display window", image ); // Show our image inside it.
cv::waitKey(0);
cv::imwrite( "output.tif", image);
}
|
8f0bc6f389e3a9113da2dcbbfeefc5152bd8759e
|
6caded3fe4e999d3061a2f9bd44c704f80e53b52
|
/C++/ex6_objet_classe/ex6_objet_classe/Clavier.cpp
|
63608147423d3bcf91cf1962fb99654195e66bbf
|
[] |
no_license
|
Galliezb/exProgrammation
|
f0cce833764a4f9d98b9aecdb41ea2f11df658b1
|
9832f052c7df043ba4498b1c75445f8a5af58ce3
|
refs/heads/master
| 2021-01-13T05:50:02.195449
| 2017-06-08T06:13:08
| 2017-06-08T06:13:08
| 68,911,957
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 745
|
cpp
|
Clavier.cpp
|
#include "Clavier.h"
int Clavier::cptNombreObjet=0;
Clavier::Clavier(){
marque_ = "";
nombreTouche_ = 0;
prix_ = 0;
Clavier::cptNombreObjet++;
}
Clavier::Clavier(string marque, short int nombreTouches, float prix){
marque_ = marque;
nombreTouche_ = nombreTouches;
prix_ = prix;
Clavier::cptNombreObjet++;
}
void Clavier::afficherTouches(){
cout << " Le clavier possede " << nombreTouche_ << "touches pour un prix de " << prix_ << endl;
}
double Clavier::afficherPrixAvecTva(){
return ( prix_ * 0.21 + prix_ );
}
double Clavier::augmenterPrix(){
prix_++;
return prix_;
}
double Clavier::diminuerPrix(){
prix_--;
return prix_;
}
Clavier::~Clavier(){
}
int Clavier::getNombreStatic(){
return Clavier::cptNombreObjet;
}
|
2f90b88be5bb2b95f4900a46a93414b5162c44c8
|
bcfcad1c5d202cdaa172014afd260e02ad802cb4
|
/ModelLoader/Include/ModelLoader.hpp
|
ef971fb4e68a6dbf70012f502b263b9a56f84f5a
|
[
"BSL-1.0",
"LicenseRef-scancode-khronos",
"Zlib",
"MIT"
] |
permissive
|
jordanlittlefair/Foundation
|
0ee67940f405573a41be6c46cd9d2e84e34ae8b1
|
ab737b933ea5bbe2be76133ed78c8e882f072fd0
|
refs/heads/master
| 2016-09-06T15:43:27.380878
| 2015-01-20T19:34:32
| 2015-01-20T19:34:32
| 26,716,271
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 529
|
hpp
|
ModelLoader.hpp
|
#pragma once
#ifndef _MODELLOADER_MODELLOADER_HPP_
#define _MODELLOADER_MODELLOADER_HPP_
#include <string>
namespace Fnd
{
namespace AssetManager
{
struct ModelData;
}
}
namespace Fnd
{
namespace ModelLoader
{
class ModelLoader
{
public:
static bool LoadModel( const std::string& filename,
float scale, // scale all axes- can't see any situation where an (x,y,z) scale would be needed
unsigned int flags,
Fnd::AssetManager::ModelData& model_data );
};
}
}
#endif
|
9a4b2aac2208676aca456e1d2715303dafda5868
|
a3d6556180e74af7b555f8d47d3fea55b94bcbda
|
/third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.cc
|
905dca681d980f0753ca07e5c91ff88c3fdc79dc
|
[
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] |
permissive
|
chromium/chromium
|
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
|
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
|
refs/heads/main
| 2023-08-24T00:35:12.585945
| 2023-08-23T22:01:11
| 2023-08-23T22:01:11
| 120,360,765
| 17,408
| 7,102
|
BSD-3-Clause
| 2023-09-10T23:44:27
| 2018-02-05T20:55:32
| null |
UTF-8
|
C++
| false
| false
| 4,860
|
cc
|
animation_and_paint_worklet_thread.cc
|
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/worklet/animation_and_paint_worklet_thread.h"
#include "base/memory/ptr_util.h"
#include "base/synchronization/waitable_event.h"
#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/worker_backing_thread.h"
#include "third_party/blink/renderer/core/workers/worklet_thread_holder.h"
#include "third_party/blink/renderer/modules/animationworklet/animation_worklet_global_scope.h"
#include "third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.h"
#include "third_party/blink/renderer/platform/heap/thread_state.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
namespace {
unsigned s_ref_count = 0;
} // namespace
std::unique_ptr<AnimationAndPaintWorkletThread>
AnimationAndPaintWorkletThread::CreateForAnimationWorklet(
WorkerReportingProxy& worker_reporting_proxy) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("animation-worklet"),
"AnimationAndPaintWorkletThread::CreateForAnimationWorklet");
DCHECK(IsMainThread());
return base::WrapUnique(new AnimationAndPaintWorkletThread(
WorkletType::kAnimation, worker_reporting_proxy));
}
std::unique_ptr<AnimationAndPaintWorkletThread>
AnimationAndPaintWorkletThread::CreateForPaintWorklet(
WorkerReportingProxy& worker_reporting_proxy) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("paint-worklet"),
"AnimationAndPaintWorkletThread::CreateForPaintWorklet");
DCHECK(IsMainThread());
return base::WrapUnique(new AnimationAndPaintWorkletThread(
WorkletType::kPaint, worker_reporting_proxy));
}
template class WorkletThreadHolder<AnimationAndPaintWorkletThread>;
AnimationAndPaintWorkletThread::AnimationAndPaintWorkletThread(
WorkletType worklet_type,
WorkerReportingProxy& worker_reporting_proxy)
: WorkerThread(worker_reporting_proxy), worklet_type_(worklet_type) {
DCHECK(IsMainThread());
if (++s_ref_count == 1) {
EnsureSharedBackingThread();
}
}
AnimationAndPaintWorkletThread::~AnimationAndPaintWorkletThread() {
DCHECK(IsMainThread());
if (--s_ref_count == 0) {
ClearSharedBackingThread();
}
}
WorkerBackingThread& AnimationAndPaintWorkletThread::GetWorkerBackingThread() {
return *WorkletThreadHolder<AnimationAndPaintWorkletThread>::GetInstance()
->GetThread();
}
static void CollectAllGarbageOnThreadForTesting(
base::WaitableEvent* done_event) {
blink::ThreadState::Current()->CollectAllGarbageForTesting();
done_event->Signal();
}
void AnimationAndPaintWorkletThread::CollectAllGarbageForTesting() {
DCHECK(IsMainThread());
base::WaitableEvent done_event;
auto* holder =
WorkletThreadHolder<AnimationAndPaintWorkletThread>::GetInstance();
if (!holder)
return;
PostCrossThreadTask(*holder->GetThread()->BackingThread().GetTaskRunner(),
FROM_HERE,
CrossThreadBindOnce(&CollectAllGarbageOnThreadForTesting,
CrossThreadUnretained(&done_event)));
done_event.Wait();
}
WorkerOrWorkletGlobalScope*
AnimationAndPaintWorkletThread::CreateWorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params) {
switch (worklet_type_) {
case WorkletType::kAnimation: {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("animation-worklet"),
"AnimationAndPaintWorkletThread::CreateWorkerGlobalScope");
return MakeGarbageCollected<AnimationWorkletGlobalScope>(
std::move(creation_params), this);
}
case WorkletType::kPaint:
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("paint-worklet"),
"AnimationAndPaintWorkletThread::CreateWorkerGlobalScope");
return PaintWorkletGlobalScope::Create(std::move(creation_params), this);
};
}
void AnimationAndPaintWorkletThread::EnsureSharedBackingThread() {
DCHECK(IsMainThread());
WorkletThreadHolder<AnimationAndPaintWorkletThread>::EnsureInstance(
ThreadCreationParams(ThreadType::kAnimationAndPaintWorkletThread));
}
void AnimationAndPaintWorkletThread::ClearSharedBackingThread() {
DCHECK(IsMainThread());
DCHECK_EQ(s_ref_count, 0u);
WorkletThreadHolder<AnimationAndPaintWorkletThread>::ClearInstance();
}
// static
WorkletThreadHolder<AnimationAndPaintWorkletThread>*
AnimationAndPaintWorkletThread::GetWorkletThreadHolderForTesting() {
return WorkletThreadHolder<AnimationAndPaintWorkletThread>::GetInstance();
}
} // namespace blink
|
f22b843527384a6749c16e8132e808bf760ec82b
|
72108ee7eccc397a2df452d75f568f949752111e
|
/Quartz/Engine/Source/Core/QuartzPCH.cpp
|
cf9938b0ad05427450180d4d6f4b5cf9a0eaf9f7
|
[
"BSD-3-Clause"
] |
permissive
|
Gerold55/quartz-engine
|
dc959b00618c9277d403d06a579f8dddde8ab8bc
|
908d84fda247bdaea185dbeddc99f187f8b84713
|
refs/heads/develop
| 2020-05-14T20:40:08.707824
| 2019-06-12T04:40:31
| 2019-06-12T04:40:31
| 181,948,295
| 0
| 1
|
BSD-3-Clause
| 2019-06-12T04:23:58
| 2019-04-17T18:35:36
|
C++
|
UTF-8
|
C++
| false
| false
| 37
|
cpp
|
QuartzPCH.cpp
|
#include <Quartz/Core/QuartzPCH.hpp>
|
36a242b3e4a220e3e181c663b7a6f0c30f935c50
|
53f5b9531da15e898a4e1c20f0a0028eb8ffd664
|
/src/Autonomous.h
|
5cc22d09a8900ac8278ad8da4b2b40a1e449dd40
|
[] |
no_license
|
Team2959/2018-FIRST-Power-Up
|
2053737b35df570acb4a427a6d93e953425c2ca5
|
e0ead7fd201d3153a7157aec880144c535e3ed7b
|
refs/heads/master
| 2023-02-28T09:17:28.724171
| 2018-04-13T02:47:19
| 2018-04-13T02:47:19
| 334,466,439
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,001
|
h
|
Autonomous.h
|
/*
* Autonomous.h
*
* Created on: Feb 8, 2018
* Author: Kevin
*/
#ifndef SRC_AUTONOMOUS_H_
#define SRC_AUTONOMOUS_H_
#include <Commands/Command.h>
#include <SmartDashboard/SendableChooser.h>
enum class Side { Left, Right };
class Autonomous
{
private:
// The chooser seems problematic updating the SmartDashboard when it uses an frc::Command* as its stored data.
// So, use an enum, and map from that enum to our command.
enum class AutoCommand
{
Default,
PlaceInitialCubeOnSwitch,
PlaceCubeOnOurSide,
NoVisionCenter,
AutonStraight,
AutonRotate,
ScriptAuton,
TwoWheelLeftRightSwitch,
TwoWheelSwitchAndPyramidFromCenter,
TwScaleOnlyCommandGroup
};
frc::SendableChooser<AutoCommand> m_chooser;
std::unique_ptr<frc::Command> m_autonomousCommand;
bool m_foundGameData;
int m_cycleCount;
void StartAutonomousFromGameData();
public:
Autonomous();
void AutoInit();
void AutoPeriodic();
void CancelAutonomousCommand();
};
#endif /* SRC_AUTONOMOUS_H_ */
|
fcbf151a9f99663a0d5a047655771c3d601c62a3
|
852427c818afb5550b05ea59d58477c18eb4db00
|
/Problems/HEADBOB.cpp
|
54f462a28e064ded0e883138b0fc3c615acdad07
|
[] |
no_license
|
jonorsky/Competitive-Programming
|
3209e6a780114e22bcc4463d0dda93ceaaf67cf8
|
4c27e416b3bf223a1d59bd1cbc873c3766fe41dd
|
refs/heads/master
| 2020-04-09T18:25:46.521423
| 2019-02-18T07:03:46
| 2019-02-18T07:03:46
| 160,511,950
| 0
| 0
| null | 2019-01-16T15:41:17
| 2018-12-05T12:01:49
|
C++
|
UTF-8
|
C++
| false
| false
| 1,944
|
cpp
|
HEADBOB.cpp
|
/* https://www.codechef.com/LTIME17/problems/HEADBOB */
#pragma warning(disable:4786)
#define _CRT_SECURE_NO_WARNINGS
#pragma comment(linker, "/stack:16777216")
#include <bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(false);
#define endl '\n'
#define gc getchar
#define file freopen("iceparticle.in","r",stdin);
#define terminate exit (EXIT_FAILURE)
#define os_iterator ostream_iterator<data> screen(cout,endl)
#define output(vec) copy(vec.begin(),vec.end(),screen)
#define memory(dt,fill,length) memset ((dt),(fill),(length))
#define MAX int(1e9) + 7;
#define timer 0
typedef vector<int> vec;
typedef vector<vec> vvec;
typedef long long ll;
typedef vector<ll> vecll;
typedef vector<vecll> vvecll;
typedef char character;
typedef int data;
typedef pair<data, data> pint;
typedef vector<pint> vpint;
typedef float decimal;
typedef map<char,ll> trace;
inline ll input() {
register int c = gc();
ll x = 0;
ll neg = 0;
for(; ((c<48 || c>57) && c != '-');
c = gc());
if(c == '-')
{
neg = 1;
c = gc();
}
for(; c>47 && c<58 ; c = gc())
x = (x<<1) + (x<<3) + c - 48;
return (neg)?
-x:x;
}
inline void process() {
ll t=input();
string str;
ll des;
bool _n,_y,_i;
while(t--) {
des=input();
cin >> str;
_n=0; _y=0; _i=0;
for( ll i=0; i<str.length(); i++) {
if(str[i]=='N')
_n=1;
if(str[i]=='Y')
_y=1;
if(str[i]=='I')
_i=1;
}
if(_n==1 && _i==1 && _y==0)
cout << "INDIAN" << endl;
else if(_n==1 && _i==0 && _y==0)
cout << "NOT SURE" << endl;
else if(_n==0 && _i==1 && _y==0)
cout << "INDIAN" << endl;
else if(_n==0 && _i==0 && _y==1)
cout << "NOT INDIAN" << endl;
else
cout << "NOT INDIAN" << endl;
}
}
int main (int argc, char * const argv[]) {
if(timer) {
decimal bios_memsize;
clock_t execution;
execution=clock();
process();
bios_memsize=(clock()-execution)/(decimal)CLOCKS_PER_SEC;
printf("[%.4f] sec\n",bios_memsize); }
process();
return 0;
}
|
39e5eadee7c3eed9cbddbb8aecdd9211eb7f679d
|
726ed80ec958276eb8c4602a1fa81f0838e51260
|
/src/170418 potenziometri BT_1.ino
|
d11b8316b9478de2c969d3cf9dfed5fdf17c554a
|
[] |
no_license
|
ecotux/drone
|
849d0217cc4b3356383b30c12f6b41b9c7672c25
|
939f3aed01d22f6b88d635fd609f3582afd9aa3a
|
refs/heads/main
| 2023-08-29T07:46:04.335434
| 2021-11-02T18:10:54
| 2021-11-02T18:10:54
| 423,950,129
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 475
|
ino
|
170418 potenziometri BT_1.ino
|
/*
Arduino Pins Bluetooth Pins
RX (Pin 0) ———-> TX
TX (Pin 1) ———-> RX
*/
int potPin1 = A0;
int potPin2 = A1;
int speed1 = 0;
int speed2 = 0;
void setup() {
Serial.begin(38400);
}
void loop() {
speed1 = map( analogRead(potPin1), 0, 1023, 1000, 2000 );
speed2 = map( analogRead(potPin2), 0, 1023, 1000, 2000 );
Serial.print(speed1);
Serial.print("\t");
Serial.print(speed2);
Serial.print("\n");
delay(100);
}
|
f7a91b2ca6465cb64305c7fea5e2c9a30789445a
|
62994e774c4da539d93a9bc0da4195050b08fbf0
|
/src/Zombie.h
|
b85f1a4fe1f01e9550bbb77d4c2f86e73ba80b62
|
[
"MIT"
] |
permissive
|
svetoslaw/flora-vs-undead
|
ebbf446e5ca717af69e2a6c186f5ef432b30e862
|
828b4f7713c441e4be73d90cdc13116c14af9dfa
|
refs/heads/develop
| 2020-08-18T04:42:50.729758
| 2020-01-20T10:58:18
| 2020-01-20T10:58:18
| 215,748,683
| 0
| 0
|
MIT
| 2020-01-25T11:22:41
| 2019-10-17T09:02:48
|
C
|
UTF-8
|
C++
| false
| false
| 328
|
h
|
Zombie.h
|
#ifndef __ZOMBIE_H__
#define __ZOMBIE_H__
#include "GameObject.h"
#include <string>
class Zombie : public GameObject
{
public:
Zombie(SDL_Rect position);
void setType(std::string t);
std::string getType();
void updateHealth(int h);
int getHealth();
private:
std::string type;
int health = 0;
};
#endif // !__ZOMBIE_H__
|
521d38f4490af97944f23d0617bf5c262c6d2c2f
|
7e0aaa95ecac4959bf9766d438cb7351a61884fd
|
/SDL_1/src/Games/BreakOut/Ball.hpp
|
16a5160664acc20719e9a314cf8fd617afa0425d
|
[] |
no_license
|
sschaitanya/BreakOut
|
5e0522babb9b79bfcae8a4d80cbc5925054d1bd9
|
d1389a02641d0e741e90da9b62e91229b414e5d5
|
refs/heads/master
| 2023-01-18T15:30:14.921738
| 2020-11-29T01:57:09
| 2020-11-29T01:57:09
| 316,849,146
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,044
|
hpp
|
Ball.hpp
|
//
// Ball.hpp
// SDL_1
//
// Created by santhosh chaitanya singaraju on 10/24/20.
//
#ifndef Ball_hpp
#define Ball_hpp
#include "AARectangle.hpp"
#include "Screen.hpp"
struct BoundaryEdge;
class Ball{
public:
Ball();
Ball(const Vec2D& pos, float radius);
void Update(uint32_t dt);
void Draw(Screen& screen);
void MakeFlushWithEdge(const BoundaryEdge& edge, Vec2D& point_on_edge, bool limit_to_edge);
inline void Stop(){velocity_ = Vec2D::Zero;}
void MoveTo(const Vec2D& point);
inline const AARectangle GetBoundingRect() const{return bounding_box_;};
inline void SetVelocity(const Vec2D& vel) {velocity_ = vel;}
inline Vec2D GetVelocity() const {return velocity_;}
inline float GetRadius() const {return bounding_box_.GetWidth()/2.0f;}
inline Vec2D GetPosition() const {return bounding_box_.GetCenterPoint();}
void Bounce(const BoundaryEdge& edge);
private:
AARectangle bounding_box_;
Vec2D velocity_;
static const float RADIUS;
};
#endif /* Ball_hpp */
|
4dd7e1bc5d1f65ba6886ab84d629c7de4351fcb2
|
aa57f47c838c3acf5fc2ba8b14c00a3a235041f5
|
/Source/UnrealOpenCvTest/FaceDetectionActor.h
|
a0f7ea28be8a2fd5cb7104d618d4291e2554f768
|
[] |
no_license
|
RobertoE90/UnrealOpenCVBasicIntegration
|
756c076c7090dd36b3f46ed68f80baf7db565ac1
|
334b4eb3aa61815a33c294796b5853678ec63018
|
refs/heads/master
| 2022-12-29T14:27:06.380462
| 2020-10-12T19:09:02
| 2020-10-12T19:12:18
| 303,130,973
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 710
|
h
|
FaceDetectionActor.h
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "WebCamReader.h"
//#include "opencv2/core.hpp"
#include "opencv2/objdetect.hpp"
#include "FaceDetectionActor.generated.h"
UCLASS()
class UNREALOPENCVTEST_API AFaceDetectionActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AFaceDetectionActor();
UFUNCTION(BlueprintCallable)
void Initialize(AWebCamReader *WebCameraReader);
void OnOpenCVFrameUpdated(cv::Mat* frame);
private:
cv::CascadeClassifier FaceDetector;
bool bModelLoaded = false;
std::vector<cv::Rect>* Faces = nullptr;
};
|
3eb55cee6041f493701037624497251b4b8ea701
|
5f3ea05075d5937aa2b5f32aef6feb335325df3a
|
/src/Oscillator.h
|
51306a920f999ddc16a2e0558f385d99332bbab4
|
[] |
no_license
|
t3kt/LineThing4
|
2810924747be18246df74714a4b9574dbd1d4e58
|
2189ab20de1f9a70604311b6f916afc7ce1ef022
|
refs/heads/master
| 2020-05-18T11:19:30.279978
| 2015-01-06T05:03:05
| 2015-01-06T05:03:05
| 28,891,750
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 611
|
h
|
Oscillator.h
|
//
// Oscillator.h
// LineThing4
//
// Created by tekt on 1/4/15.
//
//
#ifndef __LineThing4__Oscillator__
#define __LineThing4__Oscillator__
#include "Common.h"
#include <utility>
#include <ofRange.h>
class Oscillator {
public:
enum Mode {
MODE_CONSTANT,
MODE_RAMP,
MODE_SINE
};
typedef float Value;
typedef ofRange_<Value> ValuePair;
Value getRaw(float t) const;
Value getScaled(float t) const;
private:
const ValuePair& getRawRange() const;
Mode _mode;
Value _constant;
ValuePair _outRange;
float _frequency;
};
#endif /* defined(__LineThing4__Oscillator__) */
|
f5dcc5a17444c8a7041a412426f515102f074ba4
|
b6e7fefcc288ede325ffc25d6040cee38b75d18a
|
/ch4/Point.hpp
|
86f7e1d51a89bdae43130af97070ca85a6cef8cf
|
[] |
no_license
|
iamcz/itcffe
|
60c70f40f6d7c30131cfc1467cedc220be78d0b9
|
ddfbe6a651b87cb587f3ca2ff9f26ab36544b1a9
|
refs/heads/master
| 2021-05-12T17:38:02.813040
| 2018-01-13T21:53:58
| 2018-01-13T21:53:58
| 117,049,363
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,155
|
hpp
|
Point.hpp
|
#ifndef Point_HPP
#define Point_HPP
#include <iostream>
using namespace std;
class Shape {
};
class Point : public Shape {
private:
double x; // X coordinate
double y; // Y coordinate
void init(double dx, double dy);
public:
// Constructors
Point(); // Default constructor
Point(double xval, double yval); // Initialize with x and y value
Point(const Point& pt); // Copy constructor
~Point(); // Destructor
// Accessing functions
double X() const; // The x-coordinate
double Y() const; // The y-coordinate
// Modifiers
void X(double NewX);
void Y(double NewY);
// Arithmetic functions
Point add(const Point& p) const; // Return current + p
Point subtract(const Point& p) const; // Return current - p
Point scale(const Point& pt) const; // Return current * p
Point MidPoint(const Point& pt) const; // Point midway
// Copy
Point& copy(const Point& p); // Copy p in current
};
ostream& operator<<(ostream& os, const Point& p);
#endif
|
d93150339c20185caaba5e493d1ddac9db6dbc67
|
5ec06dab1409d790496ce082dacb321392b32fe9
|
/clients/cpp-qt5/generated/client/OAIOrgApacheSlingEventJobsQueueConfigurationProperties.h
|
69404b3380be29e7a6cf70119137bc43292d67ae
|
[
"Apache-2.0"
] |
permissive
|
shinesolutions/swagger-aem-osgi
|
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
|
c2f6e076971d2592c1cbd3f70695c679e807396b
|
refs/heads/master
| 2022-10-29T13:07:40.422092
| 2021-04-09T07:46:03
| 2021-04-09T07:46:03
| 190,217,155
| 3
| 3
|
Apache-2.0
| 2022-10-05T03:26:20
| 2019-06-04T14:23:28
| null |
UTF-8
|
C++
| false
| false
| 4,077
|
h
|
OAIOrgApacheSlingEventJobsQueueConfigurationProperties.h
|
/**
* Adobe Experience Manager OSGI config (AEM) API
* Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API
*
* OpenAPI spec version: 1.0.0-pre.0
* Contact: opensource@shinesolutions.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/*
* OAIOrgApacheSlingEventJobsQueueConfigurationProperties.h
*
*
*/
#ifndef OAIOrgApacheSlingEventJobsQueueConfigurationProperties_H_
#define OAIOrgApacheSlingEventJobsQueueConfigurationProperties_H_
#include <QJsonObject>
#include "OAIOAIConfigNodePropertyArray.h"
#include "OAIOAIConfigNodePropertyBoolean.h"
#include "OAIOAIConfigNodePropertyDropDown.h"
#include "OAIOAIConfigNodePropertyFloat.h"
#include "OAIOAIConfigNodePropertyInteger.h"
#include "OAIOAIConfigNodePropertyString.h"
#include "OAIObject.h"
namespace OpenAPI {
class OAIOrgApacheSlingEventJobsQueueConfigurationProperties: public OAIObject {
public:
OAIOrgApacheSlingEventJobsQueueConfigurationProperties();
OAIOrgApacheSlingEventJobsQueueConfigurationProperties(QString json);
~OAIOrgApacheSlingEventJobsQueueConfigurationProperties();
void init();
void cleanup();
QString asJson () override;
QJsonObject asJsonObject() override;
void fromJsonObject(QJsonObject json) override;
OAIOrgApacheSlingEventJobsQueueConfigurationProperties* fromJson(QString jsonString) override;
OAIConfigNodePropertyString* getQueueName();
void setQueueName(OAIConfigNodePropertyString* queue_name);
OAIConfigNodePropertyArray* getQueueTopics();
void setQueueTopics(OAIConfigNodePropertyArray* queue_topics);
OAIConfigNodePropertyDropDown* getQueueType();
void setQueueType(OAIConfigNodePropertyDropDown* queue_type);
OAIConfigNodePropertyDropDown* getQueuePriority();
void setQueuePriority(OAIConfigNodePropertyDropDown* queue_priority);
OAIConfigNodePropertyInteger* getQueueRetries();
void setQueueRetries(OAIConfigNodePropertyInteger* queue_retries);
OAIConfigNodePropertyInteger* getQueueRetrydelay();
void setQueueRetrydelay(OAIConfigNodePropertyInteger* queue_retrydelay);
OAIConfigNodePropertyFloat* getQueueMaxparallel();
void setQueueMaxparallel(OAIConfigNodePropertyFloat* queue_maxparallel);
OAIConfigNodePropertyBoolean* getQueueKeepJobs();
void setQueueKeepJobs(OAIConfigNodePropertyBoolean* queue_keep_jobs);
OAIConfigNodePropertyBoolean* getQueuePreferRunOnCreationInstance();
void setQueuePreferRunOnCreationInstance(OAIConfigNodePropertyBoolean* queue_prefer_run_on_creation_instance);
OAIConfigNodePropertyInteger* getQueueThreadPoolSize();
void setQueueThreadPoolSize(OAIConfigNodePropertyInteger* queue_thread_pool_size);
OAIConfigNodePropertyInteger* getServiceRanking();
void setServiceRanking(OAIConfigNodePropertyInteger* service_ranking);
virtual bool isSet() override;
private:
OAIConfigNodePropertyString* queue_name;
bool m_queue_name_isSet;
OAIConfigNodePropertyArray* queue_topics;
bool m_queue_topics_isSet;
OAIConfigNodePropertyDropDown* queue_type;
bool m_queue_type_isSet;
OAIConfigNodePropertyDropDown* queue_priority;
bool m_queue_priority_isSet;
OAIConfigNodePropertyInteger* queue_retries;
bool m_queue_retries_isSet;
OAIConfigNodePropertyInteger* queue_retrydelay;
bool m_queue_retrydelay_isSet;
OAIConfigNodePropertyFloat* queue_maxparallel;
bool m_queue_maxparallel_isSet;
OAIConfigNodePropertyBoolean* queue_keep_jobs;
bool m_queue_keep_jobs_isSet;
OAIConfigNodePropertyBoolean* queue_prefer_run_on_creation_instance;
bool m_queue_prefer_run_on_creation_instance_isSet;
OAIConfigNodePropertyInteger* queue_thread_pool_size;
bool m_queue_thread_pool_size_isSet;
OAIConfigNodePropertyInteger* service_ranking;
bool m_service_ranking_isSet;
};
}
#endif /* OAIOrgApacheSlingEventJobsQueueConfigurationProperties_H_ */
|
64dbfaba897f3756fff6ce6f8a1def71ce68193e
|
61d720c020b08faa58a1e6c82aef3e75dc58dc10
|
/sizeOf/src/sizeof_single_array.cpp
|
5f56ebf8830530c9df4d1b92215225c3c37d0db1
|
[] |
no_license
|
VinothVB/CPP
|
e2186b8b9d643607dd7b8de261ff54f6759e7b3c
|
e8a2f33a8ef9e35abb3060c6da9a73d7301789e9
|
refs/heads/master
| 2022-12-30T22:49:54.866457
| 2020-10-24T06:25:53
| 2020-10-24T06:25:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 778
|
cpp
|
sizeof_single_array.cpp
|
/*
sizeof tells you the size of the variable.
int --> 4 bytes
float --> 4 bytes
char --> 1 byte
double --> 8 byte
here we are going to find the size of the single array i.e the number of elements in an array
*/
#include<iostream>
int main(int argc, char* argv[])
{
int values[] = { 4, 7, 3, 5 };
/*
this will return 16 bytes:
i.e 4 bytes x no of values/elements
*/
std::cout << sizeof(values) << std::endl;
/*
this will return 4 bytes:
i.e. int variable consumes 4 bytes of space
*/
std::cout << sizeof(int) << std::endl;
/*
finding the no of values in array:
i.e total no of bytes / no of bytes of a single int
*/
std::cout << "No of elements/values in an array :: " << sizeof(values) / sizeof(int) << std::endl;
return 0;
}
|
6b145097a60b566a07d9f6f4b578f9b6bd61edfc
|
f48cbb6890f22988e9e79bfa4c48e43e4e39384d
|
/GameData.h
|
1a88097f18ae2bc7523dec470813d0f7a6ff030d
|
[] |
no_license
|
FMock/GameEngine
|
b55f9777a08b7b8a42f242e5266531e1b2d1fcce
|
4edd326abfed5b6017a6b5422e94316bfd3ace87
|
refs/heads/master
| 2021-09-03T12:31:53.567375
| 2018-01-09T04:36:42
| 2018-01-09T04:36:42
| 115,837,836
| 0
| 0
| null | 2018-01-02T00:24:32
| 2017-12-31T02:33:14
|
C++
|
UTF-8
|
C++
| false
| false
| 284
|
h
|
GameData.h
|
#pragma once
#ifndef GAMEDATA_H
#define GAMEDATA_H
class GameData{
public:
// static members made available to other game objects
static enum gameState{START, PLAY, PAUSE, END};
static void setCurrentGameState(int);
private:
GameData(){}
static int currentGameState;
};
#endif
|
4e89b9ffd8b0bcbb2b96f0e44dc0c721ac0447e4
|
6328ec4ad6380c54f2c0c91877334b797c97dadb
|
/snake/lib/snake_controller.cpp
|
d7ab52ab3d70209e501209438061032a38bc9e54
|
[] |
no_license
|
homyak-coder/snakeproject
|
9294cdb1f8e7d6bdb3804b47fa6d6d92f1b00107
|
b9dc5e06d0641bde295da94268d5fa7f61947b7d
|
refs/heads/master
| 2022-10-06T21:11:12.058653
| 2020-06-07T10:13:02
| 2020-06-07T10:13:02
| 265,507,546
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,924
|
cpp
|
snake_controller.cpp
|
/**
*@file snake_controller.cpp
*/
#include "../headers/snake.hpp"
/**
* @brief Функция для выдержки частоты обновления
* @return true, если рано обновляться, true, если пора
*/
bool SnakeUserController::not_so_fast()
{
if (clock.getElapsedTime().asMilliseconds() >= 1000 / freq)
{
clock.restart();
return false;
}
return true;
}
/**
* @brief Конструктор контроллера
* @param window Ссылка на окно
* @param f Частота считывания событий
*/
SnakeUserController::SnakeUserController(sf::RenderWindow& window, const int f) :
window_(window),
freq(f)
{}
/**
* @brief Обновление контроллера
* Читает события с окна (крестик или кнопки), добавляет в очередь команд
* соответствующую команду
*/
void SnakeUserController::update()
{
if (not_so_fast())
return;
if (window_.pollEvent(event))
if (event.type == sf::Event::Closed)
commands_queue.push(Command::finish);
switch (event.key.code)
{
case sf::Keyboard::Key::Up:
commands_queue.push(Command::up);
break;
case sf::Keyboard::Key::Down:
commands_queue.push(Command::down);
break;
case sf::Keyboard::Key::Left:
commands_queue.push(Command::left);
break;
case sf::Keyboard::Key::Right:
commands_queue.push(Command::right);
break;
}
}
/**
* @brief Извлекает из очереди первую команду и возвращает её
* @return возвращает последнюю команду, сохранённую в контроллере
*/
Command SnakeUserController::get_cmd()
{
if (commands_queue.empty())
return Command::pass;
Command cmd = commands_queue.front();
commands_queue.pop();
return cmd;
}
|
a5b4c442d6fa63c300814db477f1dad262fef552
|
8bf096c857cde9c39398ff50b12ce6ecc0f69e68
|
/PCM/pcm_mesh.cpp
|
94b19447e6229740b2a34acfdadd6bedc65161b1
|
[] |
no_license
|
JackZhouSz/ebpd_vs2015
|
796a346907a5a6be6c02d82bf0aeaa92566ea44e
|
190248cd9e66ecaadb7111e50a4c30e34ff52f31
|
refs/heads/master
| 2023-03-20T09:14:38.661344
| 2017-06-30T14:26:20
| 2017-06-30T14:26:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 445
|
cpp
|
pcm_mesh.cpp
|
#include "mesh.h"
#include "MeshOpenGL.h"
#include "shader.h"
#include "QGLViewer\vec.h"
#include "QGLViewer\camera.h"
#include <sstream>
using namespace std;
namespace pcm
{
void Mesh::setupOpenglMesh()
{
opengl_mesh_->updateMesh();
}
void Mesh::draw(RenderMode::WhichColorMode mode, RenderMode::RenderType& r , Shader* openglShader, PaintCanvas* canvas)
{
if (opengl_mesh_)
opengl_mesh_->draw(mode, r, openglShader, canvas);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.