hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0cc9b82e0977cea065880c24f5b5c2df3ba8bce7
| 2,503
|
cpp
|
C++
|
src_smartcontract_vm/instance/instance_exception/NullPointerExceptionClassDeclare.cpp
|
alinous-core/codable-cash
|
32a86a152a146c592bcfd8cc712f4e8cb38ee1a0
|
[
"MIT"
] | 6
|
2019-01-06T05:02:39.000Z
|
2020-10-01T11:45:32.000Z
|
src_smartcontract_vm/instance/instance_exception/NullPointerExceptionClassDeclare.cpp
|
Codablecash/codablecash
|
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
|
[
"MIT"
] | 209
|
2018-05-18T03:07:02.000Z
|
2022-03-26T11:42:41.000Z
|
src_smartcontract_vm/instance/instance_exception/NullPointerExceptionClassDeclare.cpp
|
Codablecash/codablecash
|
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
|
[
"MIT"
] | 3
|
2019-07-06T09:16:36.000Z
|
2020-10-15T08:23:28.000Z
|
/*
* NullPointerExceptionClassDeclare.cpp
*
* Created on: 2020/04/17
* Author: iizuka
*/
#include "instance/instance_exception/NullPointerExceptionClassDeclare.h"
#include "base/UnicodeString.h"
#include "engine/sc_analyze/AnalyzedClass.h"
#include "engine/sc_analyze/AnalyzedType.h"
#include "engine/sc_analyze/IVmInstanceFactory.h"
#include "instance/instance_exception_class/ExceptionInstanceFactory.h"
#include "instance/instance_exception_class/ExceptionClassDeclare.h"
#include "instance/instance_exception_class/VmExceptionInstance.h"
#include "lang/sc_declare/ClassExtends.h"
#include "vm/vm_ctrl/ExecControlManager.h"
#include "vm/VirtualMachine.h"
#include "instance/reserved_classes/ReservedClassRegistory.h"
namespace alinous {
UnicodeString NullPointerExceptionClassDeclare::NAME{L"NullPointerException"};
NullPointerExceptionClassDeclare::NullPointerExceptionClassDeclare() : AbstractExceptionClassDeclare() {
addDefaultConstructor(&NAME);
this->extends = new ClassExtends();
this->extends->setClassName(&ExceptionClassDeclare::NAME);
}
AnalyzedClass* NullPointerExceptionClassDeclare::createAnalyzedClass() noexcept {
NullPointerExceptionClassDeclare* classDec = new NullPointerExceptionClassDeclare();
AnalyzedClass* aclass = new AnalyzedClass(classDec);
return aclass;
}
void NullPointerExceptionClassDeclare::throwException(VirtualMachine* vm, const CodeElement* element) noexcept {
ExecControlManager* ctrl = vm->getCtrl();
IVmInstanceFactory* factory = ExceptionInstanceFactory::getInstance();
AnalyzedClass* aclass = vm->getReservedClassRegistory()->getAnalyzedClass(&NAME);
VmClassInstance* inst = factory->createInstance(aclass, vm);
inst->init(vm);
VmExceptionInstance* exception = dynamic_cast<VmExceptionInstance*>(inst);
vm->throwException(exception, element);
}
NullPointerExceptionClassDeclare::~NullPointerExceptionClassDeclare() {
}
const UnicodeString* NullPointerExceptionClassDeclare::getName() noexcept {
return &NAME;
}
const UnicodeString* NullPointerExceptionClassDeclare::getFullQualifiedName() noexcept {
return &NAME;
}
ClassDeclare* NullPointerExceptionClassDeclare::getBaseClass() const noexcept {
AnalyzedType* atype = this->extends->getAnalyzedType();
AnalyzedClass* aclass = atype->getAnalyzedClass();
return aclass->getClassDeclare();
}
IVmInstanceFactory* NullPointerExceptionClassDeclare::getFactory() const noexcept {
return ExceptionInstanceFactory::getInstance();
}
} /* namespace alinous */
| 29.104651
| 112
| 0.80863
|
alinous-core
|
0cca2dcee75d53b3683ba341da2839bea77c76b2
| 534
|
hh
|
C++
|
dimensionanalysis/print.hh
|
dearoneesama/ctut
|
1a0fe75f435bc7b50dbeefa0ecb5eeed62a89f55
|
[
"BSL-1.0"
] | null | null | null |
dimensionanalysis/print.hh
|
dearoneesama/ctut
|
1a0fe75f435bc7b50dbeefa0ecb5eeed62a89f55
|
[
"BSL-1.0"
] | null | null | null |
dimensionanalysis/print.hh
|
dearoneesama/ctut
|
1a0fe75f435bc7b50dbeefa0ecb5eeed62a89f55
|
[
"BSL-1.0"
] | null | null | null |
#pragma once
#include <ostream>
#include "dim.hh"
namespace dim {
template<unitpw_t s, unitpw_t m, unitpw_t kg, unitpw_t A,
unitpw_t K, unitpw_t mol, unitpw_t cd, class T>
std::ostream &operator<<(std::ostream &out, const quantity<dimVec<s, m, kg, A, K, mol, cd>, T> &q) {
out << q.value
<< " [s: " << s
<< ", m: " << m
<< ", kg: " << kg
<< ", A: " << A
<< ", K: " << K
<< ", mol: " << mol
<< ", cd: " << cd
<< ']';
return out;
}
}
| 24.272727
| 104
| 0.434457
|
dearoneesama
|
0ccc3aeae323159016b55441cbbda4c7a228b511
| 15,978
|
tcc
|
C++
|
flens/lapack/la/laexc.tcc
|
stip/FLENS
|
80495fa97dda42a0acafc8f83fc9639ae36d2e10
|
[
"BSD-3-Clause"
] | 98
|
2015-01-26T20:31:37.000Z
|
2021-09-09T15:51:37.000Z
|
flens/lapack/la/laexc.tcc
|
stip/FLENS
|
80495fa97dda42a0acafc8f83fc9639ae36d2e10
|
[
"BSD-3-Clause"
] | 16
|
2015-01-21T07:43:45.000Z
|
2021-12-06T12:08:36.000Z
|
flens/lapack/la/laexc.tcc
|
stip/FLENS
|
80495fa97dda42a0acafc8f83fc9639ae36d2e10
|
[
"BSD-3-Clause"
] | 31
|
2015-01-05T08:06:45.000Z
|
2022-01-26T20:12:00.000Z
|
/*
* Copyright (c) 2011, Michael Lehn
*
* 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 FLENS development group nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* Based on
*
SUBROUTINE DLAEXC( WANTQ, N, T, LDT, Q, LDQ, J1, N1, N2, WORK,
$ INFO )
*
* -- LAPACK auxiliary routine (version 3.2.2) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* June 2010
*/
#ifndef FLENS_LAPACK_LA_LAEXC_TCC
#define FLENS_LAPACK_LA_LAEXC_TCC 1
#include <flens/auxiliary/auxiliary.h>
#include <flens/blas/blas.h>
#include <flens/lapack/lapack.h>
namespace flens { namespace lapack {
//== generic lapack implementation =============================================
namespace generic {
template <typename MT, typename MQ, typename IndexType, typename VWORK>
IndexType
laexc_impl(bool computeQ,
GeMatrix<MT> &T,
GeMatrix<MQ> &Q,
IndexType j1,
IndexType n1,
IndexType n2,
DenseVector<VWORK> &work)
{
using std::abs;
using flens::max;
typedef typename GeMatrix<MT>::View GeMatrixView;
typedef typename GeMatrix<MT>::VectorView DenseVectorView;
typedef typename GeMatrix<MT>::ElementType ElementType;
const ElementType Zero(0), One(1), Ten(10);
const IndexType n = T.numRows();
const Underscore<IndexType> _;
//
// .. Local Arrays ..
//
ElementType dData_[16], xData_[4];
GeMatrixView D = typename GeMatrixView::Engine(4, 4, dData_, 4);
GeMatrixView X = typename GeMatrixView::Engine(2, 2, xData_, 2);
ElementType uData_[3], u1Data_[3], u2Data_[3];
DenseVectorView u = typename DenseVectorView::Engine(3, uData_);
DenseVectorView u1 = typename DenseVectorView::Engine(3, u1Data_);
DenseVectorView u2 = typename DenseVectorView::Engine(3, u2Data_);
//
// Quick return if possible
//
if (n==0 || n1==0 || n2==0) {
return 0;
}
if (j1+n1>n) {
return 0;
}
const IndexType j2 = j1 + 1;
const IndexType j3 = j1 + 2;
const IndexType j4 = j1 + 3;
ElementType t11, t22, t33;
if (n1==1 && n2==1) {
//
// Swap two 1-by-1 blocks.
//
t11 = T(j1,j1);
t22 = T(j2,j2);
//
// Determine the transformation to perform the interchange.
//
ElementType cs, sn, temp;
lartg(T(j1,j2), t22-t11, cs, sn, temp);
//
// Apply transformation to the matrix T.
//
if (j3<=n) {
blas::rot(T(j1,_(j3,n)), T(j2,_(j3,n)), cs, sn);
}
blas::rot(T(_(1,j1-1),j1), T(_(1,j1-1),j2), cs, sn);
T(j1,j1) = t22;
T(j2,j2) = t11;
if (computeQ) {
//
// Accumulate transformation in the matrix Q.
//
blas::rot(Q(_,j1), Q(_,j2), cs, sn);
}
} else {
//
// Swapping involves at least one 2-by-2 block.
//
// Copy the diagonal block of order N1+N2 to the local array D
// and compute its norm.
//
const IndexType nd = n1 + n2;
auto D_ = D(_(1,nd),_(1,nd));
D_ = T(_(j1,j1+nd-1),_(j1,j1+nd-1));
ElementType normD = lan(MaximumNorm, D_);
ElementType cs, sn, wr1, wr2, wi1, wi2;
ElementType scale, normX, tau, tau1, tau2;
//
// Compute machine-dependent threshold for test for accepting
// swap.
//
const ElementType eps = lamch<ElementType>(Precision);
const ElementType smallNum = lamch<ElementType>(SafeMin) / eps;
const ElementType thresh = max(Ten*eps*normD, smallNum);
//
// Solve T11*X - X*T22 = scale*T12 for X.
//
const auto T11 = D(_(1,n1),_(1,n1));
const auto T12 = D(_(1,n1),_(n1+1,nd));
const auto T22 = D(_(n1+1,nd),_(n1+1,nd));
auto X_ = X(_(1,n1),_(1,n2));
lasy2(false, false, IndexType(-1), T11, T22, T12, scale, X_, normX);
//
// Swap the adjacent diagonal blocks.
//
const IndexType k = n1 + n1 + n2 - 3;
switch (k) {
//
// N1 = 1, N2 = 2: generate elementary reflector H so that:
//
// ( scale, X11, X12 ) H = ( 0, 0, * )
//
case 1:
u(1) = scale;
u(2) = X(1,1);
u(3) = X(1,2);
larfg(IndexType(3), u(3), u(_(1,2)), tau);
u(3) = One;
t11 = T(j1,j1);
//
// Perform swap provisionally on diagonal block in D.
//
larfx(Left, u, tau, D_, work(_(1,3)));
larfx(Right, u, tau, D_, work(_(1,3)));
//
// Test whether to reject swap.
//
if (max(abs(D(3,1)), abs(D(3,2)), abs(D(3,3)-t11))>thresh) {
//
// Return 1 if swap was rejected.
//
return 1;
}
//
// Accept swap: apply transformation to the entire matrix T.
//
larfx(Left, u, tau, T(_(j1,j1+3-1),_(j1,n)), work(_(1,n-j1+1)));
larfx(Right, u, tau, T(_(1,j2),_(j1,j1+3-1)), work(_(1,j2)));
T(j3,j1) = Zero;
T(j3,j2) = Zero;
T(j3,j3) = t11;
if (computeQ) {
//
// Accumulate transformation in the matrix Q.
//
larfx(Right, u, tau, Q(_,_(j1,j1+3-1)), work);
}
break;
case 2:
//
// N1 = 2, N2 = 1: generate elementary reflector H so that:
//
// H ( -X11 ) = ( * )
// ( -X21 ) = ( 0 )
// ( scale ) = ( 0 )
//
u(1) = -X(1,1);
u(2) = -X(2,1);
u(3) = scale;
larfg(IndexType(3), u(1), u(_(2,3)), tau);
u(1) = One;
t33 = T(j3,j3);
//
// Perform swap provisionally on diagonal block in D.
//
larfx(Left, u, tau, D(_(1,3),_(1,3)), work(_(1,3)));
larfx(Right, u, tau, D(_(1,3),_(1,3)), work(_(1,3)));
//
// Test whether to reject swap.
//
if (max(abs(D(2,1)), abs(D(3,1)), abs(D(1,1)-t33))>thresh) {
//
// Return 1 if swap was rejected.
//
return 1;
}
//
// Accept swap: apply transformation to the entire matrix T.
//
larfx(Right, u, tau, T(_(1,j3),_(j1, j1+3-1)), work(_(1,j3)));
larfx(Left, u, tau, T(_(j1,j1+3-1),_(j2,n)), work(_(1,n-j1)));
T(j1,j1) = t33;
T(j2,j1) = Zero;
T(j3,j1) = Zero;
if (computeQ) {
//
// Accumulate transformation in the matrix Q.
//
larfx(Right, u, tau, Q(_,_(j1,j1+3-1)), work);
}
break;
case 3:
//
// N1 = 2, N2 = 2: generate elementary reflectors H(1) and H(2) so
// that:
//
// H(2) H(1) ( -X11 -X12 ) = ( * * )
// ( -X21 -X22 ) ( 0 * )
// ( scale 0 ) ( 0 0 )
// ( 0 scale ) ( 0 0 )
//
u1(1) = -X(1,1);
u1(2) = -X(2,1);
u1(3) = scale;
larfg(IndexType(3), u1(1), u1(_(2,3)), tau1);
u1(1) = One;
const ElementType temp = -tau1*(X(1,2)+u1(2)*X(2,2));
u2(1) = -temp*u1(2) - X(2,2);
u2(2) = -temp*u1(3);
u2(3) = scale;
larfg(IndexType(3), u2(1), u2(_(2,3)), tau2);
u2(1) = One;
//
// Perform swap provisionally on diagonal block in D.
//
larfx(Left, u1, tau1, D(_(1,3),_(1,4)), work(_(1,4)));
larfx(Right, u1, tau1, D(_(1,4),_(1,3)), work(_(1,4)));
larfx(Left, u2, tau2, D(_(2,4),_(1,4)), work(_(1,4)));
larfx(Right, u2, tau2, D(_(1,4),_(2,4)), work(_(1,4)));
//
// Test whether to reject swap.
//
if (max(abs(D(3,1)), abs(D(3,2)), abs(D(4,1)), abs(D(4,2)))>thresh)
{
//
// Return 1 if swap was rejected.
//
return 1;
}
//
// Accept swap: apply transformation to the entire matrix T.
//
larfx(Left, u1, tau1, T(_(j1,j1+3-1),_(j1,n)), work(_(1,n-j1+1)));
larfx(Right, u1, tau1, T(_(1,j4),_(j1,j1+3-1)), work(_(1,j4)));
larfx(Left, u2, tau2, T(_(j2,j2+3-1),_(j1,n)), work(_(1,n-j1+1)));
larfx(Right, u2, tau2, T(_(1,j4),_(j2,j2+3-1)), work(_(1,j4)));
T(j3,j1) = Zero;
T(j3,j2) = Zero;
T(j4,j1) = Zero;
T(j4,j2) = Zero;
if (computeQ) {
//
// Accumulate transformation in the matrix Q.
//
larfx(Right, u1, tau1, Q(_,_(j1,j1+3-1)), work);
larfx(Right, u2, tau2, Q(_,_(j2,j2+3-1)), work);
}
}
if (n2==2) {
//
// Standardize new 2-by-2 block T11
//
lanv2(T(j1,j1), T(j1,j2), T(j2,j1), T(j2,j2),
wr1, wi1, wr2, wi2, cs, sn);
blas::rot(T(j1,_(j1+2,n)), T(j2,_(j1+2,n)), cs, sn);
blas::rot(T(_(1,j1-1),j1), T(_(1,j1-1),j2), cs, sn);
if (computeQ) {
blas::rot(Q(_,j1), Q(_,j2), cs, sn);
}
}
if (n1==2) {
//
// Standardize new 2-by-2 block T22
//
const IndexType j3 = j1 + n2;
const IndexType j4 = j3 + 1;
lanv2(T(j3,j3), T(j3,j4), T(j4,j3), T(j4,j4),
wr1, wi1, wr2, wi2, cs, sn);
if (j3+2<=n) {
blas::rot(T(j3,_(j3+2,n)), T(j4,_(j3+2,n)), cs, sn);
}
blas::rot(T(_(1,j3-1),j3), T(_(1,j3-1),j4), cs, sn);
if (computeQ) {
blas::rot(Q(_,j3), Q(_,j4), cs, sn);
}
}
}
return 0;
}
} // namespace generic
//== interface for native lapack ===============================================
#ifdef USE_CXXLAPACK
namespace external {
template <typename MT, typename MQ, typename IndexType, typename VWORK>
IndexType
laexc_impl(bool computeQ,
GeMatrix<MT> &T,
GeMatrix<MQ> &Q,
IndexType j1,
IndexType n1,
IndexType n2,
DenseVector<VWORK> &work)
{
IndexType info;
info = cxxlapack::laexc<IndexType>(computeQ,
T.numRows(),
T.data(),
T.leadingDimension(),
Q.data(),
Q.leadingDimension(),
j1,
n1,
n2,
work.data());
ASSERT(info>=0);
return info;
}
} // namespace external
#endif // USE_CXXLAPACK
//== public interface ==========================================================
template <typename MT, typename MQ, typename IndexType, typename VWORK>
IndexType
laexc(bool computeQ,
GeMatrix<MT> &T,
GeMatrix<MQ> &Q,
IndexType j1,
IndexType n1,
IndexType n2,
DenseVector<VWORK> &work)
{
LAPACK_DEBUG_OUT("BEGIN: laexc");
//
// Test the input parameters
//
# ifndef NDEBUG
ASSERT(T.firstRow()==1);
ASSERT(T.firstCol()==1);
ASSERT(T.numRows()==T.numCols());
const IndexType n = T.numRows();
if (computeQ) {
ASSERT(Q.firstRow()==1);
ASSERT(Q.firstCol()==1);
ASSERT(Q.numRows()==Q.numCols());
ASSERT(Q.numRows()==n);
}
ASSERT(j1>=1);
ASSERT((n1==0) || (n1==1) || (n1==2));
ASSERT((n2==0) || (n2==1) || (n2==2));
ASSERT(work.firstIndex()==1);
ASSERT(work.length()==n);
# endif
# ifdef CHECK_CXXLAPACK
//
// Make copies of output arguments
//
typename GeMatrix<MT>::NoView T_org = T;
typename GeMatrix<MQ>::NoView Q_org = Q;
typename DenseVector<VWORK>::NoView work_org = work;
# endif
//
// Call implementation
//
IndexType info = LAPACK_SELECT::laexc_impl(computeQ, T, Q,
j1, n1, n2, work);
# ifdef CHECK_CXXLAPACK
//
// Make copies of results computed by the generic implementation
//
typename GeMatrix<MT>::NoView T_generic = T;
typename GeMatrix<MQ>::NoView Q_generic = Q;
typename DenseVector<VWORK>::NoView work_generic = work;
//
// restore output arguments
//
T = T_org;
Q = Q_org;
work = work_org;
//
// Compare generic results with results from the native implementation
//
IndexType info_ = external::laexc_impl(computeQ, T, Q, j1, n1, n2, work);
bool failed = false;
if (! isIdentical(T_generic, T, "T_generic", "T")) {
std::cerr << "CXXLAPACK: T_generic = " << T_generic << std::endl;
std::cerr << "F77LAPACK: T = " << T << std::endl;
failed = true;
}
if (! isIdentical(Q_generic, Q, "Q_generic", "Q")) {
std::cerr << "CXXLAPACK: Q_generic = " << Q_generic << std::endl;
std::cerr << "F77LAPACK: Q = " << Q << std::endl;
failed = true;
}
if (! isIdentical(work_generic, work, "work_generic", "work")) {
std::cerr << "CXXLAPACK: work_generic = " << work_generic << std::endl;
std::cerr << "F77LAPACK: work = " << work << std::endl;
failed = true;
}
if (! isIdentical(info, info_, " info", "info_")) {
std::cerr << "CXXLAPACK: info = " << info << std::endl;
std::cerr << "F77LAPACK: info_ = " << info_ << std::endl;
failed = true;
}
if (failed) {
ASSERT(0);
}
# endif
LAPACK_DEBUG_OUT("END: laexc");
return info;
}
//-- forwarding ----------------------------------------------------------------
template <typename MT, typename MQ, typename IndexType, typename VWORK>
IndexType
laexc(bool computeQ,
MT &&T,
MQ &&Q,
IndexType j1,
IndexType n1,
IndexType n2,
VWORK &&work)
{
CHECKPOINT_ENTER;
const IndexType info = laexc(computeQ, T, Q, j1, n1, n2, work);
CHECKPOINT_LEAVE;
return info;
}
} } // namespace lapack, flens
#endif // FLENS_LAPACK_LA_LAEXC_TCC
| 30.318786
| 80
| 0.493992
|
stip
|
0ccf10af95ca2ca06d8dfa73140636014ff6a649
| 5,939
|
cpp
|
C++
|
particlepm/target.cpp
|
particletk/particlepm
|
f30d5d96a045ef65dd8a60ce91ee1fe17b0d54a7
|
[
"MIT"
] | null | null | null |
particlepm/target.cpp
|
particletk/particlepm
|
f30d5d96a045ef65dd8a60ce91ee1fe17b0d54a7
|
[
"MIT"
] | 1
|
2018-09-22T15:16:28.000Z
|
2018-09-22T15:16:28.000Z
|
particlepm/target.cpp
|
particletk/particlepm
|
f30d5d96a045ef65dd8a60ce91ee1fe17b0d54a7
|
[
"MIT"
] | null | null | null |
#include "libincludes.hpp"
#include "target.hpp"
#include <functional>
#include <mutex>
#include <queue>
#include <thread>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/regex.hpp>
PPM::Target::Target(const std::string& name, const std::string& dir, PPM::Target::Type type)
: marked(false)
, has_cpp(false)
, type_(type)
, name_(name)
, dir_(dir)
, c_("c11")
, cpp_("c++11")
, c_flags_("")
, cpp_flags_("")
, is_dynamic_(true)
{}
void PPM::Target::depends(const PPM::TargetPtr& other) {
deps_.insert(other);
}
void PPM::Target::build() {
if (marked) {
return;
}
marked = true;
for (PPM::TargetPtr dep : deps_) {
dep->build();
}
std::cerr << "Building " << name() << "(" << (int) type_ << ")" << std::endl;
std::string dbg = PPM::dev ? "-g -ggdb" : "";
auto has_updated_headers = [&] (const std::string& compiler, const std::string& ifile, const std::string& ofile, std::function<void()> do_build) -> bool {
std::string flags;
std::string std;
if (compiler == PPM_CC) {
flags = c_flags_;
std = c_;
} else if (compiler == PPM_CXX) {
flags = cpp_flags_;
std = cpp_;
}
PPM::Utils::ExecStatus st = PPM::Utils::exec(compiler + " " + dbg + " " + PPM::envflags + " " + flags + " -fPIC -std=" + std + " -M " + ifile);
if (st.code != 0) {
std::cerr << st.data << std::endl;
exit(1);
}
std::vector<std::string> files;
boost::algorithm::split_regex(files, st.data, boost::regex("[\\\\\\r\\n\\s]+"));
files.erase(files.begin(), files.begin() + 2);
for (const std::string& file : files) {
if (file.empty()) continue;
if (access(ofile.c_str(), 0) == 0) {
struct stat a, b;
::stat(file.c_str(), &a);
::stat(ofile.c_str(), &b);
if (a.st_mtime > b.st_mtime) {
do_build();
return true;
}
}
}
return false;
};
auto runner = [&] (PPM::FilePtr file) {
if (file->built) {
return;
}
file->built = true;
auto do_build = [&] () {
char* p_ = getcwd(NULL, 1024);
std::string p(p_);
free(p_);
PPM::Utils::chdir(dir_);
std::string flags;
std::string std;
if (file->compiler == PPM_CC) {
flags = c_flags_;
std = c_;
} else if (file->compiler == PPM_CXX) {
flags = cpp_flags_;
std = cpp_;
}
PPM::Utils::ExecStatus st = PPM::Utils::exec(file->compiler + " " + dbg + " " + PPM::envflags + " " + flags + " -Wl,-rpath='$ORIGIN' -fPIC -std=" + std + " -c " + file->ifile + " -o " + file->ofile);
if (st.code != 0) {
std::cerr << st.data << std::endl;
::exit(st.code);
}
PPM::Utils::chdir(p);
};
if (::access(file->ofile.c_str(), 0) != 0) {
do_build();
} else if (::access(file->ofile.c_str(), 0) == 0) {
struct stat a, b;
::stat(file->ifile.c_str(), &a);
::stat(file->ofile.c_str(), &b);
if (a.st_mtime > b.st_mtime) {
do_build();
} else if (has_updated_headers(file->compiler, file->ifile, file->ofile, do_build)) {}
} else if (has_updated_headers(file->compiler, file->ifile, file->ofile, do_build)) {
} else {
do_build();
}
};
std::queue<PPM::FilePtr> q;
std::mutex qm;
std::vector<std::thread> threads;
unsigned n = std::thread::hardware_concurrency();
auto thread_runner = [&] () {
while (!q.empty()) {
PPM::FilePtr f;
{
std::lock_guard<std::mutex> ql(qm);
if (q.empty()) break;
f = q.front();
q.pop();
}
runner(f);
}
};
for (int i = 0; i < n; ++i) {
threads.push_back(std::thread(thread_runner));
}
for (PPM::FilePtr file : files_) {
q.push(file);
}
for (std::thread& thr : threads) {
thr.join();
}
std::string compiler = has_cpp ? PPM_CXX : PPM_CC;
PPM::Utils::mkdir(PPM::dist_dir);
std::string out = PPM::Utils::to_path(std::vector<std::string>{ "dist", ((type_ == PPM::Target::Type::Executable) ? name() : ("lib" + name() + ".so")) });
std::string filenames = "";
for (PPM::FilePtr file : files_) {
filenames += (" " + file->ofile);
}
std::string lt = is_dynamic_ ? "-rdynamic" : "";
PPM::Utils::ExecStatus st;
if (type_ == PPM::Target::Type::Executable) {
st = PPM::Utils::exec(compiler + " " + dbg + " " + PPM::envflags + " -Wl,-rpath='$ORIGIN' -fPIC -o " + out + " " + filenames + " " + cpp_flags_ + " " + c_flags_);
} else {
st = PPM::Utils::exec(compiler + " " + dbg + " " + PPM::envflags + " " + lt + " -shared -Wl,-rpath='$ORIGIN' -fPIC -o " + out + " " + filenames + " " + cpp_flags_ + " " + c_flags_);
}
if (st.code != 0) {
std::cerr << st.data << std::endl;
::exit(st.code);
}
}
std::string PPM::Target::name() {
return name_;
}
void PPM::Target::name(const std::string& value) {
name_ = value;
}
std::string PPM::Target::c() {
return c_;
}
void PPM::Target::c(const std::string& value) {
c_ = value;
}
std::string PPM::Target::cpp() {
return cpp_;
}
void PPM::Target::cpp(const std::string& value) {
cpp_ = value;
}
void PPM::Target::c_files(const std::vector<std::string>& filenames) {
std::string suffix = (PPM::dev == true ? ".dev.o" : ".o");
for (const std::string& filename : filenames) {
std::string f = dir_ + "/" + filename;
files_.insert(PPM::FilePtr(new PPM::File(f, f + suffix, PPM_CC)));
}
}
void PPM::Target::cpp_files(const std::vector<std::string>& filenames) {
std::string suffix = (PPM::dev == true ? ".dev.o" : ".o");
has_cpp = true;
for (const std::string& filename : filenames) {
std::string f = dir_ + "/" + filename;
files_.insert(PPM::FilePtr(new PPM::File(f, f + suffix, PPM_CXX)));
}
}
void PPM::Target::c_flags(const std::string& flags) {
c_flags_ += (" " + flags);
}
void PPM::Target::cpp_flags(const std::string& flags) {
cpp_flags_ += (" " + flags);
}
| 26.632287
| 205
| 0.550261
|
particletk
|
7b4fc4f888c5991277a407c54dbe6a23c1547725
| 1,388
|
cpp
|
C++
|
073-set-matrix-zeroes/set-matrix-zeroes.cpp
|
TJUSsr/leetcodesolution
|
8244de2d76c9e8e5b9d98dd1e8efed4d680d44ee
|
[
"MIT"
] | null | null | null |
073-set-matrix-zeroes/set-matrix-zeroes.cpp
|
TJUSsr/leetcodesolution
|
8244de2d76c9e8e5b9d98dd1e8efed4d680d44ee
|
[
"MIT"
] | 2
|
2021-03-31T19:10:41.000Z
|
2021-12-13T19:58:15.000Z
|
073-set-matrix-zeroes/set-matrix-zeroes.cpp
|
TJUSsr/leetcodesolution
|
8244de2d76c9e8e5b9d98dd1e8efed4d680d44ee
|
[
"MIT"
] | null | null | null |
// Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
//
// Example 1:
//
//
// Input:
// [
// [1,1,1],
// [1,0,1],
// [1,1,1]
// ]
// Output:
// [
// [1,0,1],
// [0,0,0],
// [1,0,1]
// ]
//
//
// Example 2:
//
//
// Input:
// [
// [0,1,2,0],
// [3,4,5,2],
// [1,3,1,5]
// ]
// Output:
// [
// [0,0,0,0],
// [0,4,5,0],
// [0,3,1,0]
// ]
//
//
// Follow up:
//
//
// A straight forward solution using O(mn) space is probably a bad idea.
// A simple improvement uses O(m + n) space, but still not the best solution.
// Could you devise a constant space solution?
//
//
static const auto _=[](){
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int col0 = 1, rows = matrix.size(), cols = matrix[0].size();
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == 0) col0 = 0;
for (int j = 1; j < cols; j++)
if (matrix[i][j] == 0)
matrix[i][0] = matrix[0][j] = 0;
}
for (int i = rows - 1; i >= 0; i--) {
for (int j = cols - 1; j >= 1; j--)
if (matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
if (col0 == 0) matrix[i][0] = 0;
}
}
};
| 19.013699
| 96
| 0.43732
|
TJUSsr
|
7b5188433ee2cd8f6515d1dae2da47d8dce1c51d
| 5,120
|
cpp
|
C++
|
src/console.cpp
|
hammelm/mempeek
|
8e9d0de7a6a2313abfbe7e512b5048993a0a2e61
|
[
"BSD-2-Clause"
] | null | null | null |
src/console.cpp
|
hammelm/mempeek
|
8e9d0de7a6a2313abfbe7e512b5048993a0a2e61
|
[
"BSD-2-Clause"
] | 18
|
2015-10-13T04:31:19.000Z
|
2016-08-18T09:20:21.000Z
|
src/console.cpp
|
hammelm/mempeek
|
8e9d0de7a6a2313abfbe7e512b5048993a0a2e61
|
[
"BSD-2-Clause"
] | 3
|
2017-03-04T14:14:13.000Z
|
2020-01-13T08:42:25.000Z
|
/* Copyright (c) 2015-2018, Martin Hammel
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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.
*/
#include "console.h"
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef USE_EDITLINE
#include <fstream>
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#else
#include <iostream>
#endif
using namespace std;
//////////////////////////////////////////////////////////////////////////////
// class Console implementation
//////////////////////////////////////////////////////////////////////////////
char* Console::s_Prompt = nullptr;
Console::Console( string name, string histfile, size_t histsize )
{
// only one instance of Console is allowed
if( s_Prompt ) abort();
s_Prompt = strcpy( new char[3], "> " );
#ifdef USE_EDITLINE
// create histfile name
m_Histfile = histfile;
if( histfile.length() > 0 && histfile[0] == '~' ) {
passwd* pwd = getpwuid( getuid() );
if( pwd ) {
m_Histfile = pwd->pw_dir;
m_Histfile += histfile.substr(1);
}
}
// init history
HistEvent hev;
m_History = history_init();
history( m_History, &hev, H_SETSIZE, histsize );
history( m_History, &hev, H_SETUNIQUE, 1 );
if( m_Histfile.length() > 0 ) {
ifstream histfile( m_Histfile.c_str() );
for(;;) {
string line;
std::getline( histfile, line );
if( histfile.bad() || histfile.fail() ) break;
line += '\n';
history( m_History, &hev, H_ENTER, line.c_str() );
if( histfile.eof() ) break;
}
}
// init editline
m_Editline = el_init( name.c_str(), stdin, stdout, stderr );
el_set( m_Editline, EL_SIGNAL, 1 );
el_set( m_Editline, EL_EDITOR, "emacs" );
el_set( m_Editline, EL_PROMPT, Console::get_prompt );
el_set( m_Editline, EL_HIST, history, m_History );
el_set( m_Editline, EL_ADDFN, "ed-complete", "", completion_callback );
el_set( m_Editline, EL_BIND, "^I", "ed-complete", nullptr );
#else
(void)histfile;
(void)histsize;
#endif
}
Console::~Console()
{
#ifdef USE_EDITLINE
// save history
if( m_Histfile.length() > 0 ) {
ofstream histfile( m_Histfile.c_str(), ios::trunc );
HistEvent hev;
history( m_History, &hev, H_LAST );
for(;;) {
histfile << hev.str;
if( history( m_History, &hev, H_PREV ) < 0 ) break;
}
}
// cleanup
el_end( m_Editline );
history_end( m_History );
#endif
delete[] s_Prompt;
s_Prompt = nullptr;
}
void Console::set_prompt( string prompt )
{
delete[] s_Prompt;
s_Prompt = strcpy( new char[ prompt.length() + 1 ], prompt.c_str() );
}
void Console::set_completion( std::function<unsigned char( EditLine*, int )> completion )
{
#ifdef USE_EDITLINE
s_Completion = completion;
#else
(void)completion;
#endif
}
void Console::set_clientdata( void* data )
{
#ifdef USE_EDITLINE
el_set( m_Editline, EL_CLIENTDATA, data );
#else
(void)data;
#endif
}
string Console::get_line()
{
#ifdef USE_EDITLINE
int count;
const char* line = el_gets( m_Editline, &count );
// do not add to history if line is empty
if( line ) {
for( const char* l = line; *l; l++ ) {
if( !isspace(*l) ) {
HistEvent hev;
history( m_History, &hev, H_ENTER, line );
return line;
}
}
}
return "";
#else
cout << s_Prompt << flush;
string ret = "";
getline( cin, ret );
ret += '\n';
return ret;
#endif
}
Console::tokens_t Console::get_tokens()
{
istringstream line( get_line() );
tokens_t tokens;
for(;;) {
string token;
line >> token;
if( line.bad() || line.fail() ) return tokens;
tokens.push_back( token );
if( line.eof() ) return tokens;
}
}
#ifdef USE_EDITLINE
std::function<unsigned char( EditLine*, int )> Console::s_Completion = nullptr;
char* Console::get_prompt( EditLine* )
{
return s_Prompt;
}
unsigned char Console::completion_callback( EditLine* el, int ch )
{
if( s_Completion ) return s_Completion( el, ch );
else return CC_NORM;
}
#endif
| 24.7343
| 89
| 0.666992
|
hammelm
|
7b5289576635ef21eaf18cef85647c333164cf88
| 916
|
cpp
|
C++
|
samples/demo/src/source.cpp
|
ninjaoflight/appcenter-sdk-cpp
|
1e14459e3161694da6b8f313ee1cdd088cc21954
|
[
"BSD-3-Clause"
] | null | null | null |
samples/demo/src/source.cpp
|
ninjaoflight/appcenter-sdk-cpp
|
1e14459e3161694da6b8f313ee1cdd088cc21954
|
[
"BSD-3-Clause"
] | null | null | null |
samples/demo/src/source.cpp
|
ninjaoflight/appcenter-sdk-cpp
|
1e14459e3161694da6b8f313ee1cdd088cc21954
|
[
"BSD-3-Clause"
] | null | null | null |
#include <appcenter/analytics/analytics.hpp>
#include <appcenter/appcenter.hpp>
#include <string_view>
int main(int, char **) {
// get the enviroment variable
#ifdef APPCENTER_SAMPLE_APP_SECRET
const std::string_view appSecret = APPCENTER_SAMPLE_APP_SECRET;
#else
// if not using meson, you can setup your own app secret here
//* NOTE: it is not recommended to have the app secret directly in the
//* source code
constexpr std::string_view appSecret = "YOUR_APP_SECRET";
#endif
// we can control the SDK log level
appcenter::AppCenter &appCenterSDK = appcenter::AppCenter::getInstance();
appcenter::analytics::Analytics &analytics = appcenter::analytics::Analytics::getInstance();
appCenterSDK.setLogLevel(appcenter::core::logging::LogLevel::Verbose);
// or configure the SDK with an app secret
appCenterSDK.configure(appSecret);
if (appCenterSDK.isConfigured()){
appCenterSDK.start(&analytics);
}
}
| 36.64
| 93
| 0.768559
|
ninjaoflight
|
7b53a23a7e78b0b580267532415bd627f5a6e84a
| 469
|
cpp
|
C++
|
problems/T/T1011/std.cpp
|
Tiphereth-A/problems
|
78724d2f559bf18b4999c89ef3bf9b8523fc6d49
|
[
"MIT"
] | 1
|
2022-01-23T09:26:35.000Z
|
2022-01-23T09:26:35.000Z
|
problems/T/T1011/std.cpp
|
Tiphereth-A/problems
|
78724d2f559bf18b4999c89ef3bf9b8523fc6d49
|
[
"MIT"
] | null | null | null |
problems/T/T1011/std.cpp
|
Tiphereth-A/problems
|
78724d2f559bf18b4999c89ef3bf9b8523fc6d49
|
[
"MIT"
] | 1
|
2022-03-08T07:21:04.000Z
|
2022-03-08T07:21:04.000Z
|
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 1e4+5;
const int maxw = 1e7+5;
typedef long long ll;
ll m[maxn], w[maxn], v[maxn];
ll dp[maxw];
int main()
{
int n, W;
cin>>n>>W;
for(int i=1;i<=n;i++)
cin>>m[i]>>w[i]>>v[i];
for(int i=1;i<=n;i++)
for(int j=W;j>=0;j--)
for(int k=0;k*w[i]<=j&&k<=m[i];k++)
dp[j]=max(dp[j-k*w[i]]+k*v[i], dp[j]);
cout<<dp[W]<<endl;
return 0;
}
| 22.333333
| 54
| 0.492537
|
Tiphereth-A
|
7b54174cd2b5839bb7543172835d95979e8a1aaf
| 2,817
|
cpp
|
C++
|
keyzz/runners/runner.cpp
|
DmitryDzz/keyzz
|
85e63ea465116e0b7f37aa8633a6d6beeabd6779
|
[
"MIT"
] | null | null | null |
keyzz/runners/runner.cpp
|
DmitryDzz/keyzz
|
85e63ea465116e0b7f37aa8633a6d6beeabd6779
|
[
"MIT"
] | 6
|
2021-05-05T18:08:55.000Z
|
2021-05-15T16:01:00.000Z
|
keyzz/runners/runner.cpp
|
DmitryDzz/keyzz
|
85e63ea465116e0b7f37aa8633a6d6beeabd6779
|
[
"MIT"
] | null | null | null |
// Copyright 2021 DmitryDzz
#include "runner.hpp"
#include <logger/easylogging++.h>
#include <algorithm>
#include <minunity/engine.hpp>
#include "../tracks/race.hpp"
#include "../tracks/track.hpp"
using minunity::Engine;
using minunity::Layer;
using minunity::Sprite;
using keyzz::BaseRunner;
using keyzz::Race;
using keyzz::Runner;
using keyzz::Track;
Runner::Runner(int x, int y, std::shared_ptr<Track> track_record)
: BaseRunner(x, y, track_record) {
}
void Runner::awake() {
BaseRunner::awake();
}
void Runner::update() {
BaseRunner::update();
if (is_destroyed() || !get_active() || !start_time_) return;
uint32_t delta_time = Engine::get_instance()->get_time()->get_time() - start_time_.value();
bool is_previous_lap = false;
bool is_next_lap = false;
bool is_finish = false;
int32_t x = get_start_x() + track_->get_delta_x(delta_time, lap_first_index_, lap_last_index_,
&is_previous_lap, &is_next_lap, &is_finish);
// LOG(INFO) << "[Runner] " << track_->get_name() << ": x=" << x << " get_start_x()=" <<
// get_start_x() << " is_finish=" << is_finish;
if (get_sprite() != nullptr) {
if (is_previous_lap) {
get_sprite()->set_frame_index(1); // <<
} else if (is_next_lap) {
get_sprite()->set_frame_index(2); // >>
} else {
get_sprite()->set_frame_index(is_finish ? 3 : 0); // (x)
}
}
set_x(x);
if (is_finish)
finish_race();
}
void Runner::render_layer(Layer layer) {
if (is_destroyed() || get_sprite() == nullptr) return;
BaseRunner::render_layer(layer);
}
void Runner::start_lap(int lap_index, int laps_count) {
BaseRunner::start_lap(lap_index, laps_count);
if (!start_time_) {
start_time_ = Engine::get_instance()->get_time()->get_time();
// LOG(INFO) << "[Runner] n=" << track_->get_name().c_str() <<
// " start_time_=" << start_time_.value();
}
lap_first_index_ = lap_index * Race::LAP_MAX_SIZE;
lap_last_index_ = std::min(lap_first_index_ + Race::LAP_MAX_SIZE - 1, track_->get_size() - 2);
// LOG(INFO) << "[Runner] n=" << track_->get_name().c_str() <<
// " li=" << lap_index << " lc=" << laps_count <<
// " lfi=" << lap_first_index_ << " lli=" << lap_last_index_;
}
void Runner::finish_race() {
start_time_ = std::nullopt;
track_->set_finished(true);
}
Sprite* Runner::create_sprite() {
Sprite *result = new Sprite(3, 1, 4);
std::wstring name = track_->get_name();
std::wstring upper_name = name; // upper_name is for the finish.
std::transform(upper_name.begin(), upper_name.end(), upper_name.begin(), std::towupper);
std::wstring res = name + L"<< " + L" >>" + upper_name;
result->load(res.c_str());
return result;
}
| 30.290323
| 98
| 0.617678
|
DmitryDzz
|
7b5632ae2858a2ab540edf2ed8a5590e9828aafa
| 1,013
|
cpp
|
C++
|
test/Graphics/ConvexShape.cpp
|
jlmartinnc/SFML
|
709530d062ac9c452f50b06d37cdd800c2f9ba68
|
[
"Zlib"
] | 1
|
2020-09-11T06:28:37.000Z
|
2020-09-11T06:28:37.000Z
|
test/Graphics/ConvexShape.cpp
|
jlmartinnc/SFML
|
709530d062ac9c452f50b06d37cdd800c2f9ba68
|
[
"Zlib"
] | 1
|
2022-02-04T01:20:06.000Z
|
2022-02-04T01:20:06.000Z
|
test/Graphics/ConvexShape.cpp
|
ChrisThrasher/SFML
|
757cb36d30cb3090945657580f9b43d511535bc2
|
[
"Zlib"
] | null | null | null |
#include <SFML/Graphics/ConvexShape.hpp>
#include "SystemUtil.hpp"
#include <doctest.h>
TEST_CASE("sf::ConvexShape class - [graphics]")
{
SUBCASE("Default constructor")
{
const sf::ConvexShape convex;
CHECK(convex.getPointCount() == 0);
}
SUBCASE("Point count constructor")
{
const sf::ConvexShape convex(15);
CHECK(convex.getPointCount() == 15);
for (std::size_t i = 0; i < convex.getPointCount(); ++i)
CHECK(convex.getPoint(i) == sf::Vector2f(0, 0));
}
SUBCASE("Set point count")
{
sf::ConvexShape convex;
convex.setPointCount(42);
CHECK(convex.getPointCount() == 42);
for (std::size_t i = 0; i < convex.getPointCount(); ++i)
CHECK(convex.getPoint(i) == sf::Vector2f(0, 0));
}
SUBCASE("Set point")
{
sf::ConvexShape convex;
convex.setPointCount(1);
convex.setPoint(0, {3, 4});
CHECK(convex.getPoint(0) == sf::Vector2f(3, 4));
}
}
| 25.974359
| 64
| 0.572557
|
jlmartinnc
|
7b63c64671e7ccccef941ef5e3ec90c99898f461
| 2,190
|
cpp
|
C++
|
HTTPSYS/HttpQueryRequestQueueProperty.cpp
|
zYg-sys/Marlin
|
eeabb4d324c5f8d253a50c106208bb833cb824e8
|
[
"MIT"
] | 23
|
2016-09-16T11:25:54.000Z
|
2022-03-03T07:18:57.000Z
|
HTTPSYS/HttpQueryRequestQueueProperty.cpp
|
edwig/HTTPSYS
|
885f94149e7db9fb8c7dad2c42c916d31b80a862
|
[
"MIT"
] | 26
|
2016-10-21T11:07:54.000Z
|
2022-03-05T18:27:03.000Z
|
HTTPSYS/HttpQueryRequestQueueProperty.cpp
|
zYg-sys/Marlin
|
eeabb4d324c5f8d253a50c106208bb833cb824e8
|
[
"MIT"
] | 7
|
2018-09-11T12:17:46.000Z
|
2021-07-08T09:10:04.000Z
|
//////////////////////////////////////////////////////////////////////////
//
// USER-SPACE IMPLEMENTTION OF HTTP.SYS
//
// 2018 (c) ir. W.E. Huisman
// License: MIT
//
//////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "http_private.h"
#include "RequestQueue.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
HTTPAPI_LINKAGE
ULONG WINAPI
HttpQueryRequestQueueProperty(_In_ HANDLE RequestQueueHandle
,_In_ HTTP_SERVER_PROPERTY Property
,_Out_writes_bytes_to_opt_(PropertyInformationLength, *ReturnLength) PVOID PropertyInformation
,_In_ ULONG PropertyInformationLength
,_Reserved_ _In_ ULONG Reserved1
,_Out_opt_ PULONG ReturnLength OPTIONAL
,_Reserved_ _In_ PVOID Reserved2)
{
// Must always be zero
if(Reserved1 || Reserved2)
{
return ERROR_INVALID_PARAMETER;
}
// Parameters must be given
if(PropertyInformationLength == 0)
{
return ERROR_INVALID_PARAMETER;
}
// Finding our request queue
RequestQueue* queue = GetRequestQueueFromHandle(RequestQueueHandle);
if (queue == nullptr)
{
return ERROR_INVALID_PARAMETER;
}
if(Property == HttpServer503VerbosityProperty)
{
if(PropertyInformationLength >= sizeof(HTTP_503_RESPONSE_VERBOSITY))
{
*((PHTTP_503_RESPONSE_VERBOSITY)PropertyInformation) = queue->GetVerbosity();
return NO_ERROR;
}
}
else if(Property == HttpServerQueueLengthProperty)
{
if(PropertyInformationLength == sizeof(ULONG))
{
*((PULONG)PropertyInformation) = queue->GetQueueLength();
return NO_ERROR;
}
}
else if(Property == HttpServerStateProperty)
{
if(PropertyInformationLength >= sizeof(HTTP_STATE_INFO))
{
PHTTP_STATE_INFO info = (PHTTP_STATE_INFO)PropertyInformation;
info->Flags.Present = 1;
info->State = queue->GetEnabledState();
return NO_ERROR;
}
}
return ERROR_INVALID_PARAMETER;
}
| 28.441558
| 123
| 0.605479
|
zYg-sys
|
7b65ab7af31fb70217575f1e1d3ac1277e15408c
| 2,213
|
hpp
|
C++
|
compendium/ServiceComponent/include/cppmicroservices/servicecomponent/runtime/dto/ServiceReferenceDTO.hpp
|
fmilano/CppMicroServices
|
b7e79edb558a63e45f6788e4a8b4e787cf956689
|
[
"Apache-2.0"
] | 588
|
2015-10-07T15:55:08.000Z
|
2022-03-29T00:35:44.000Z
|
compendium/ServiceComponent/include/cppmicroservices/servicecomponent/runtime/dto/ServiceReferenceDTO.hpp
|
fmilano/CppMicroServices
|
b7e79edb558a63e45f6788e4a8b4e787cf956689
|
[
"Apache-2.0"
] | 459
|
2015-10-05T23:29:59.000Z
|
2022-03-29T14:13:37.000Z
|
compendium/ServiceComponent/include/cppmicroservices/servicecomponent/runtime/dto/ServiceReferenceDTO.hpp
|
fmilano/CppMicroServices
|
b7e79edb558a63e45f6788e4a8b4e787cf956689
|
[
"Apache-2.0"
] | 218
|
2015-11-04T08:19:48.000Z
|
2022-03-24T02:17:08.000Z
|
/*=============================================================================
Library: CppMicroServices
Copyright (c) The CppMicroServices developers. See the COPYRIGHT
file at the top-level directory of this distribution and at
https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT .
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================*/
#ifndef ServiceReferenceDTO_hpp
#define ServiceReferenceDTO_hpp
#include <string>
#include <unordered_map>
#include <vector>
#include "cppmicroservices/Any.h"
#include "cppmicroservices/servicecomponent/ServiceComponentExport.h"
namespace cppmicroservices {
namespace framework {
namespace dto {
/**
\defgroup gr_servicereferencedto ServiceReferenceDTO
\brief Groups ServiceReferenceDTO related symbols.
*/
/**
* \ingroup gr_servicereferencedto
*
* A representation of a satisfied reference.
*/
struct US_ServiceComponent_EXPORT ServiceReferenceDTO
{
/**
* The id of the service.
*
* @see Constants#SERVICE_ID
*/
unsigned long id;
/**
* The id of the bundle that registered the service.
*
* @see ServiceReference#GetBundle()
*/
unsigned long bundle;
/**
* The properties for the service.
*
* The value type must be a numerical type, Boolean, String or a container
* of any of the former.
*
* @see ServiceReference#GetProperty(String)
*/
std::unordered_map<std::string, cppmicroservices::Any> properties;
/**
* The ids of the bundles that are using the service.
*
* @see ServiceReference#GetUsingBundles()
*/
std::vector<unsigned long> usingBundles;
};
}
}
}
#endif /* ServiceReferenceDTO_hpp */
| 26.035294
| 81
| 0.685495
|
fmilano
|
7b69f349009cebdea5bc92cc227cefe110f64c60
| 1,214
|
cpp
|
C++
|
data/dailyCodingProblem672.cpp
|
vidit1999/daily_coding_problem
|
b90319cb4ddce11149f54010ba36c4bd6fa0a787
|
[
"MIT"
] | 2
|
2020-09-04T20:56:23.000Z
|
2021-06-11T07:42:26.000Z
|
data/dailyCodingProblem672.cpp
|
vidit1999/daily_coding_problem
|
b90319cb4ddce11149f54010ba36c4bd6fa0a787
|
[
"MIT"
] | null | null | null |
data/dailyCodingProblem672.cpp
|
vidit1999/daily_coding_problem
|
b90319cb4ddce11149f54010ba36c4bd6fa0a787
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
/*
You are given an array of arrays of integers, where each array
corresponds to a row in a triangle of numbers.
For example, [[1], [2, 3], [1, 5, 1]] represents the triangle:
1
2 3
1 5 1
We define a path in the triangle to start at the top and go down
one row at a time to an adjacent value, eventually ending with
an entry on the bottom row.
For example, 1 -> 3 -> 5.
The weight of the path is the sum of the entries.
Write a program that returns the weight of the maximum weight path.
*/
int maxSumPathHelper(int i, int j, int& n, vector<vector<int>>& arr, unordered_map<string, int>& dp){
if(i == n){
return 0;
}
string find_string = to_string(i) + "$" + to_string(j);
if(dp.find(find_string) != dp.end()) return dp[find_string];
dp[find_string] = arr[i][j] + max(maxSumPathHelper(i+1, j, n, arr, dp), maxSumPathHelper(i+1, j+1, n, arr, dp));
return dp[find_string];
}
int maxSumPath(vector<vector<int>>& arr){
int n = arr.size();
unordered_map<string, int> dp;
return maxSumPathHelper(0, 0, n, arr, dp);
}
// main function
int main(){
vector<vector<int>> arr = {{1}, {2, 3}, {1, 5, 1}};
cout << maxSumPath(arr) << "\n";
return 0;
}
| 25.829787
| 113
| 0.666392
|
vidit1999
|
7b6bf81fb3469f8133a3e0ad57675fd2d2cd3243
| 829
|
cpp
|
C++
|
utility/rep.cpp
|
Cyanmond/Library
|
e77bb2e46ebc8630983025045570bd094aca7aa7
|
[
"CC0-1.0"
] | 1
|
2021-11-04T05:41:45.000Z
|
2021-11-04T05:41:45.000Z
|
utility/rep.cpp
|
Cyanmond/Library
|
e77bb2e46ebc8630983025045570bd094aca7aa7
|
[
"CC0-1.0"
] | null | null | null |
utility/rep.cpp
|
Cyanmond/Library
|
e77bb2e46ebc8630983025045570bd094aca7aa7
|
[
"CC0-1.0"
] | null | null | null |
#pragma once
#include "../utility/int_alias.cpp"
#include <algorithm>
class rep {
struct rep_iterator {
usize itr;
constexpr rep_iterator(const usize pos) noexcept : itr(pos) {}
constexpr void operator++() noexcept {
++itr;
}
constexpr bool operator!=(const usize &other) const noexcept {
return itr != other;
}
constexpr usize operator*() const noexcept {
return itr;
}
};
const rep_iterator first;
const usize last;
public:
constexpr rep(const usize first_, const usize last_) noexcept
: first(first_), last(std::max(first_, last_)) {}
constexpr rep_iterator begin() const noexcept {
return first;
}
constexpr usize end() const noexcept {
return last;
}
};
| 24.382353
| 70
| 0.588661
|
Cyanmond
|
7b6df611b5cfd460401bdb79ade1fe1ddbdc13ae
| 1,313
|
cc
|
C++
|
RangeSim/src/StackingAction.cc
|
murffer/DetectorSim
|
1ba114c405eff42c0a52b6dc394cbecfc2d2bab0
|
[
"Apache-2.0"
] | 5
|
2018-01-13T22:42:24.000Z
|
2021-03-19T07:38:47.000Z
|
RangeSim/src/StackingAction.cc
|
murffer/DetectorSim
|
1ba114c405eff42c0a52b6dc394cbecfc2d2bab0
|
[
"Apache-2.0"
] | 1
|
2017-05-03T19:01:12.000Z
|
2017-05-03T19:01:12.000Z
|
RangeSim/src/StackingAction.cc
|
murffer/DetectorSim
|
1ba114c405eff42c0a52b6dc394cbecfc2d2bab0
|
[
"Apache-2.0"
] | 3
|
2015-10-10T15:12:22.000Z
|
2021-10-18T00:53:35.000Z
|
#include "StackingAction.hh"
#include "HistoManager.hh"
#include "G4Track.hh"
#include "G4VProcess.hh"
/**
* Default Constructor - nothing to be done
*/
StackingAction::StackingAction(){ }
/**
* Deconstructor
*/
StackingAction::~StackingAction(){ }
/**
* Classifies a new track, and fills the energy of the charged and neutral
* particles of the secondaries.
*/
G4ClassificationOfNewTrack
StackingAction::ClassifyNewTrack(const G4Track* track)
{
//keep primary particle
if (track->GetParentID() == 0) return fUrgent;
//
//energy spectrum of secondaries
G4double energy = track->GetKineticEnergy();
G4double charge = track->GetDefinition()->GetPDGCharge();
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
if (charge != 0.){
analysisManager->FillH1(5,energy);
/*
G4ParticleDefinition* p = track->GetDefinition();
// Only filling for electrons
if (p->GetPDGEncoding() == 11){
G4String procName = track->GetCreatorProcess()->GetProcessName();
if(procName == "hIoni")
analysisManager->FillH1(7,energy);
if(procName == "compt")
analysisManager->FillH1(8,energy);
//analysisManager->FillH1(5,energy);
}
*/
}
else analysisManager->FillH1(6,energy);
// return fKill;
return fUrgent;
}
| 25.745098
| 74
| 0.678599
|
murffer
|
7b75e8006e2687d18e5b2b5875ce4226d7fdd846
| 14,345
|
cpp
|
C++
|
NOLF/ObjectDLL/Editable.cpp
|
rastrup/no-one-lives-forever
|
dfbe22fb4cc01bf7e5f54a79174fa8f108dd2f54
|
[
"Unlicense"
] | 65
|
2015-02-28T03:35:14.000Z
|
2021-09-23T05:43:33.000Z
|
NOLF/ObjectDLL/Editable.cpp
|
rastrup/no-one-lives-forever
|
dfbe22fb4cc01bf7e5f54a79174fa8f108dd2f54
|
[
"Unlicense"
] | null | null | null |
NOLF/ObjectDLL/Editable.cpp
|
rastrup/no-one-lives-forever
|
dfbe22fb4cc01bf7e5f54a79174fa8f108dd2f54
|
[
"Unlicense"
] | 27
|
2015-02-28T07:42:01.000Z
|
2022-02-11T01:35:20.000Z
|
//----------------------------------------------------------
//
// MODULE : Editable.cpp
//
// PURPOSE : Editable aggreate
//
// CREATED : 3/10/99
//
//----------------------------------------------------------
#include "stdafx.h"
#include "Editable.h"
#include "iltserver.h"
#include "ObjectMsgs.h"
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::CEditable()
//
// PURPOSE: Constructor
//
// ----------------------------------------------------------------------- //
CEditable::CEditable() : IAggregate()
{
m_propList.Init(LTTRUE);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::~CEditable()
//
// PURPOSE: Destructor
//
// ----------------------------------------------------------------------- //
CEditable::~CEditable()
{
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::EngineMessageFn()
//
// PURPOSE: Handle engine messages
//
// ----------------------------------------------------------------------- //
uint32 CEditable::ObjectMessageFn(LPBASECLASS pObject, HOBJECT hSender, uint32 messageID, HMESSAGEREAD hRead)
{
switch(messageID)
{
case MID_TRIGGER:
{
const char* szMsg = (const char*)g_pLTServer->ReadFromMessageDWord(hRead);
TriggerMsg(pObject, hSender, szMsg);
}
break;
default : break;
}
return IAggregate::ObjectMessageFn(pObject, hSender, messageID, hRead);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::AddFloatProp
//
// PURPOSE: Add a float prop to our list
//
// ----------------------------------------------------------------------- //
void CEditable::AddFloatProp(char* pPropName, LTFLOAT* pPropAddress)
{
if (!pPropName || !pPropAddress) return;
CPropDef* pProp = debug_new(CPropDef);
if (!pProp) return;
pProp->Init(pPropName, CPropDef::PT_FLOAT_TYPE, (void*)pPropAddress);
m_propList.Add(pProp);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::AddDWordProp
//
// PURPOSE: Add a dword prop to our list
//
// ----------------------------------------------------------------------- //
void CEditable::AddDWordProp(char* pPropName, uint32* pPropAddress)
{
if (!pPropName || !pPropAddress) return;
CPropDef* pProp = debug_new(CPropDef);
if (!pProp) return;
pProp->Init(pPropName, CPropDef::PT_DWORD_TYPE, (void*)pPropAddress);
m_propList.Add(pProp);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::AddByteProp
//
// PURPOSE: Add a byte prop to our list
//
// ----------------------------------------------------------------------- //
void CEditable::AddByteProp(char* pPropName, uint8* pPropAddress)
{
if (!pPropName || !pPropAddress) return;
CPropDef* pProp = debug_new(CPropDef);
if (!pProp) return;
pProp->Init(pPropName, CPropDef::PT_BYTE_TYPE, (void*)pPropAddress);
m_propList.Add(pProp);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::AddBoolProp
//
// PURPOSE: Add a bool prop to our list
//
// ----------------------------------------------------------------------- //
void CEditable::AddBoolProp(char* pPropName, LTBOOL* pPropAddress)
{
if (!pPropName || !pPropAddress) return;
CPropDef* pProp = debug_new(CPropDef);
if (!pProp) return;
pProp->Init(pPropName, CPropDef::PT_BOOL_TYPE, (void*)pPropAddress);
m_propList.Add(pProp);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::AddVectorProp
//
// PURPOSE: Add a vector prop to our list
//
// ----------------------------------------------------------------------- //
void CEditable::AddVectorProp(char* pPropName, LTVector* pPropAddress)
{
if (!pPropName || !pPropAddress) return;
CPropDef* pProp = debug_new(CPropDef);
if (!pProp) return;
pProp->Init(pPropName, CPropDef::PT_VECTOR_TYPE, (void*)pPropAddress);
m_propList.Add(pProp);
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CEditable::TriggerMsg()
//
// PURPOSE: Process trigger messages
//
// --------------------------------------------------------------------------- //
void CEditable::TriggerMsg(LPBASECLASS pObject, HOBJECT hSender, const char* szMsg)
{
if (!szMsg) return;
ILTCommon* pCommon = g_pLTServer->Common();
if (!pCommon) return;
// ConParse does not destroy szMsg, so this is safe
ConParse parse;
parse.Init((char*)szMsg);
while (pCommon->Parse(&parse) == LT_OK)
{
if (parse.m_nArgs > 0 && parse.m_Args[0])
{
if (_stricmp(parse.m_Args[0], "DISPLAYPROPERTIES") == 0)
{
ListProperties(pObject);
}
else if (_stricmp(parse.m_Args[0], "EDIT") == 0)
{
if (parse.m_nArgs > 2)
{
EditProperty(pObject, parse.m_Args[1], parse.m_Args[2]);
}
}
}
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CEditable::EditProperty()
//
// PURPOSE: Edit the specified property
//
// --------------------------------------------------------------------------- //
void CEditable::EditProperty(LPBASECLASS pObject, char* pPropName, char* pPropValue)
{
if (!pObject || !pPropName || !pPropValue) return;
// Edit the appropriate property...
CPropDef** pCur = m_propList.GetItem(TLIT_FIRST);
CPropDef* pPropDef = LTNULL;
while (pCur)
{
pPropDef = *pCur;
if (pPropDef)
{
char* pName = pPropDef->GetPropName();
if (pName && _strnicmp(pName, pPropName, strlen(pName)) == 0)
{
if (pPropDef->SetValue(pPropName, pPropValue))
{
ListProperties(pObject);
}
else
{
g_pLTServer->CPrint("Couldn't set '%s' to '%s'!", pName, pPropValue);
}
return;
}
}
pCur = m_propList.GetItem(TLIT_NEXT);
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CEditable::ListProperties()
//
// PURPOSE: List our properties/values
//
// --------------------------------------------------------------------------- //
void CEditable::ListProperties(LPBASECLASS pObject)
{
if (!pObject) return;
g_pLTServer->CPrint("Object Properties------------------------");
g_pLTServer->CPrint("'Name' = '%s'", g_pLTServer->GetObjectName(pObject->m_hObject));
CPropDef** pCur = m_propList.GetItem(TLIT_FIRST);
CPropDef* pPropDef = LTNULL;
while (pCur)
{
pPropDef = *pCur;
if (pPropDef)
{
char* pPropName = pPropDef->GetPropName();
CString str;
pPropDef->GetStringValue(str);
g_pLTServer->CPrint("'%s' = %s", pPropName ? pPropName : "(Invalid name)",
str.GetLength() > 1 ? str.GetBuffer(1) : "(Invalid value)");
}
pCur = m_propList.GetItem(TLIT_NEXT);
}
g_pLTServer->CPrint("-----------------------------------------");
}
// --------------------------------------------------------------------------- //
// --------------------------------------------------------------------------- //
//
// CPropDef class methods
//
// --------------------------------------------------------------------------- //
// --------------------------------------------------------------------------- //
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::CPropDef()
//
// PURPOSE: Constructor
//
// --------------------------------------------------------------------------- //
CPropDef::CPropDef()
{
m_strPropName = LTNULL;
m_eType = PT_UNKNOWN_TYPE;
m_pAddress = LTNULL;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::~CPropDef()
//
// PURPOSE: Destructor
//
// --------------------------------------------------------------------------- //
CPropDef::~CPropDef()
{
if (m_strPropName)
{
g_pLTServer->FreeString(m_strPropName);
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::Init()
//
// PURPOSE: Set up our data members
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::Init(char* pName, PropType eType, void* pAddress)
{
if (m_strPropName || !pName) return LTFALSE;
m_strPropName = g_pLTServer->CreateString(pName);
m_eType = eType;
m_pAddress = pAddress;
return LTTRUE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetFloatValue()
//
// PURPOSE: Get the value of the property as a float
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetFloatValue(LTFLOAT & fRet)
{
if (m_eType == PT_FLOAT_TYPE && m_pAddress)
{
fRet = *((LTFLOAT*)m_pAddress);
return LTTRUE;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetDWordValue()
//
// PURPOSE: Get the value of the property as a dword
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetDWordValue(uint32 & dwRet)
{
if (m_eType == PT_DWORD_TYPE && m_pAddress)
{
dwRet = *((uint32*)m_pAddress);
return LTTRUE;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetByteValue()
//
// PURPOSE: Get the value of the property as a byte
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetByteValue(uint8 & nRet)
{
if (m_eType == PT_BYTE_TYPE && m_pAddress)
{
nRet = *((uint8*)m_pAddress);
return LTTRUE;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetBoolValue()
//
// PURPOSE: Get the value of the property as a bool
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetBoolValue(LTBOOL & bRet)
{
if (m_eType == PT_BOOL_TYPE && m_pAddress)
{
bRet = *((LTBOOL*)m_pAddress);
return LTTRUE;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetVectorValue()
//
// PURPOSE: Get the value of the property as a vector
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetVectorValue(LTVector & vRet)
{
if (m_eType == PT_VECTOR_TYPE && m_pAddress)
{
vRet = *((LTVector*)m_pAddress);
return LTTRUE;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetPropName()
//
// PURPOSE: Get the name of the property
//
// --------------------------------------------------------------------------- //
char* CPropDef::GetPropName()
{
if (!m_strPropName) return LTNULL;
return g_pLTServer->GetStringData(m_strPropName);
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetStringValue()
//
// PURPOSE: Get the value of the property as a string
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetStringValue(CString & str)
{
switch (m_eType)
{
case PT_BYTE_TYPE:
{
uint8 nVal;
if (GetByteValue(nVal))
{
str.Format("%d", nVal);
return LTTRUE;
}
}
break;
case PT_BOOL_TYPE:
{
LTBOOL bVal;
if (GetBoolValue(bVal))
{
str.Format("%s", bVal ? "True" : "False");
return LTTRUE;
}
}
break;
case PT_FLOAT_TYPE:
{
LTFLOAT fVal;
if (GetFloatValue(fVal))
{
str.Format("%.2f", fVal);
return LTTRUE;
}
}
break;
case PT_VECTOR_TYPE:
{
LTVector vVal;
if (GetVectorValue(vVal))
{
str.Format("(%.2f, %.2f, %.2f)", vVal.x, vVal.y, vVal.z);
return LTTRUE;
}
}
break;
case PT_DWORD_TYPE:
{
uint32 dwVal;
if (GetDWordValue(dwVal))
{
str.Format("%d", dwVal);
return LTTRUE;
}
}
break;
default : break;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::SetValue()
//
// PURPOSE: Set this property to the value specified...
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::SetValue(char* pPropName, char* pValue)
{
if (!pPropName || !pValue) return LTFALSE;
switch (m_eType)
{
case PT_BYTE_TYPE:
{
uint8 nVal = (uint8) atol(pValue);
*((uint8*)m_pAddress) = nVal;
}
break;
case PT_BOOL_TYPE:
{
LTBOOL bVal = (LTBOOL) atol(pValue);
*((LTBOOL*)m_pAddress) = bVal;
}
break;
case PT_FLOAT_TYPE:
{
LTFLOAT fVal = (LTFLOAT) atof(pValue);
*((LTFLOAT*)m_pAddress) = fVal;
}
break;
case PT_VECTOR_TYPE:
{
LTFLOAT fVal = (LTFLOAT) atof(pValue);
if (strstr(pPropName, ".x") || strstr(pPropName, ".r"))
{
((LTVector*)m_pAddress)->x = fVal;
}
else if (strstr(pPropName, ".y") || strstr(pPropName, ".g"))
{
((LTVector*)m_pAddress)->y = fVal;
}
else if (strstr(pPropName, ".z") || strstr(pPropName, ".b"))
{
((LTVector*)m_pAddress)->z = fVal;
}
}
break;
case PT_DWORD_TYPE:
{
uint32 dwVal = (uint32) atol(pValue);
*((uint32*)m_pAddress) = dwVal;
}
break;
default : break;
}
return LTTRUE;
}
| 24.190556
| 110
| 0.425793
|
rastrup
|
7b75fcd7ee901aa2bcc22a96bd5cdacaeb41602e
| 25,316
|
cc
|
C++
|
external/src/blosc/shuffle-sse2.cc
|
upj977155/TileDB
|
1c96c6a0c030e058930ff9d47409865fbfe2178f
|
[
"MIT"
] | 1,478
|
2017-06-15T13:58:50.000Z
|
2022-03-30T13:46:00.000Z
|
external/src/blosc/shuffle-sse2.cc
|
upj977155/TileDB
|
1c96c6a0c030e058930ff9d47409865fbfe2178f
|
[
"MIT"
] | 1,435
|
2017-05-25T01:16:18.000Z
|
2022-03-31T21:57:06.000Z
|
external/src/blosc/shuffle-sse2.cc
|
upj977155/TileDB
|
1c96c6a0c030e058930ff9d47409865fbfe2178f
|
[
"MIT"
] | 169
|
2017-06-09T18:35:45.000Z
|
2022-03-13T01:11:18.000Z
|
/*********************************************************************
Blosc - Blocked Shuffling and Compression Library
Author: Francesc Alted <francesc@blosc.org>
See LICENSES/BLOSC.txt for details about copyright and rights to use.
Modifications for TileDB by Tyler Denniston <tyler@tiledb.io>
**********************************************************************/
#include "shuffle-generic.h"
#include "shuffle-sse2.h"
#ifdef __SSE2__
#include <emmintrin.h>
/* The next is useful for debugging purposes */
#if 0
#include <stdio.h>
#include <string.h>
static void printxmm(__m128i xmm0)
{
uint8_t buf[16];
((__m128i *)buf)[0] = xmm0;
printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n",
buf[0], buf[1], buf[2], buf[3],
buf[4], buf[5], buf[6], buf[7],
buf[8], buf[9], buf[10], buf[11],
buf[12], buf[13], buf[14], buf[15]);
}
#endif
namespace blosc {
/* Routine optimized for shuffling a buffer for a type size of 2 bytes. */
static void
shuffle2_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
static const size_t bytesoftype = 2;
size_t j;
int k;
uint8_t* dest_for_jth_element;
__m128i xmm0[2], xmm1[2];
for (j = 0; j < vectorizable_elements; j += sizeof(__m128i)) {
/* Fetch 16 elements (32 bytes) then transpose bytes, words and double words. */
for (k = 0; k < 2; k++) {
xmm0[k] = _mm_loadu_si128((__m128i*)(src + (j * bytesoftype) + (k * sizeof(__m128i))));
xmm0[k] = _mm_shufflelo_epi16(xmm0[k], 0xd8);
xmm0[k] = _mm_shufflehi_epi16(xmm0[k], 0xd8);
xmm0[k] = _mm_shuffle_epi32(xmm0[k], 0xd8);
xmm1[k] = _mm_shuffle_epi32(xmm0[k], 0x4e);
xmm0[k] = _mm_unpacklo_epi8(xmm0[k], xmm1[k]);
xmm0[k] = _mm_shuffle_epi32(xmm0[k], 0xd8);
xmm1[k] = _mm_shuffle_epi32(xmm0[k], 0x4e);
xmm0[k] = _mm_unpacklo_epi16(xmm0[k], xmm1[k]);
xmm0[k] = _mm_shuffle_epi32(xmm0[k], 0xd8);
}
/* Transpose quad words */
for (k = 0; k < 1; k++) {
xmm1[k*2] = _mm_unpacklo_epi64(xmm0[k], xmm0[k+1]);
xmm1[k*2+1] = _mm_unpackhi_epi64(xmm0[k], xmm0[k+1]);
}
/* Store the result vectors */
dest_for_jth_element = dest + j;
for (k = 0; k < 2; k++) {
_mm_storeu_si128((__m128i*)(dest_for_jth_element + (k * total_elements)), xmm1[k]);
}
}
}
/* Routine optimized for shuffling a buffer for a type size of 4 bytes. */
static void
shuffle4_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
static const size_t bytesoftype = 4;
size_t i;
int j;
uint8_t* dest_for_ith_element;
__m128i xmm0[4], xmm1[4];
for (i = 0; i < vectorizable_elements; i += sizeof(__m128i)) {
/* Fetch 16 elements (64 bytes) then transpose bytes and words. */
for (j = 0; j < 4; j++) {
xmm0[j] = _mm_loadu_si128((__m128i*)(src + (i * bytesoftype) + (j * sizeof(__m128i))));
xmm1[j] = _mm_shuffle_epi32(xmm0[j], 0xd8);
xmm0[j] = _mm_shuffle_epi32(xmm0[j], 0x8d);
xmm0[j] = _mm_unpacklo_epi8(xmm1[j], xmm0[j]);
xmm1[j] = _mm_shuffle_epi32(xmm0[j], 0x04e);
xmm0[j] = _mm_unpacklo_epi16(xmm0[j], xmm1[j]);
}
/* Transpose double words */
for (j = 0; j < 2; j++) {
xmm1[j*2] = _mm_unpacklo_epi32(xmm0[j*2], xmm0[j*2+1]);
xmm1[j*2+1] = _mm_unpackhi_epi32(xmm0[j*2], xmm0[j*2+1]);
}
/* Transpose quad words */
for (j = 0; j < 2; j++) {
xmm0[j*2] = _mm_unpacklo_epi64(xmm1[j], xmm1[j+2]);
xmm0[j*2+1] = _mm_unpackhi_epi64(xmm1[j], xmm1[j+2]);
}
/* Store the result vectors */
dest_for_ith_element = dest + i;
for (j = 0; j < 4; j++) {
_mm_storeu_si128((__m128i*)(dest_for_ith_element + (j * total_elements)), xmm0[j]);
}
}
}
/* Routine optimized for shuffling a buffer for a type size of 8 bytes. */
static void
shuffle8_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
static const size_t bytesoftype = 8;
size_t j;
int k, l;
uint8_t* dest_for_jth_element;
__m128i xmm0[8], xmm1[8];
for (j = 0; j < vectorizable_elements; j += sizeof(__m128i)) {
/* Fetch 16 elements (128 bytes) then transpose bytes. */
for (k = 0; k < 8; k++) {
xmm0[k] = _mm_loadu_si128((__m128i*)(src + (j * bytesoftype) + (k * sizeof(__m128i))));
xmm1[k] = _mm_shuffle_epi32(xmm0[k], 0x4e);
xmm1[k] = _mm_unpacklo_epi8(xmm0[k], xmm1[k]);
}
/* Transpose words */
for (k = 0, l = 0; k < 4; k++, l +=2) {
xmm0[k*2] = _mm_unpacklo_epi16(xmm1[l], xmm1[l+1]);
xmm0[k*2+1] = _mm_unpackhi_epi16(xmm1[l], xmm1[l+1]);
}
/* Transpose double words */
for (k = 0, l = 0; k < 4; k++, l++) {
if (k == 2) l += 2;
xmm1[k*2] = _mm_unpacklo_epi32(xmm0[l], xmm0[l+2]);
xmm1[k*2+1] = _mm_unpackhi_epi32(xmm0[l], xmm0[l+2]);
}
/* Transpose quad words */
for (k = 0; k < 4; k++) {
xmm0[k*2] = _mm_unpacklo_epi64(xmm1[k], xmm1[k+4]);
xmm0[k*2+1] = _mm_unpackhi_epi64(xmm1[k], xmm1[k+4]);
}
/* Store the result vectors */
dest_for_jth_element = dest + j;
for (k = 0; k < 8; k++) {
_mm_storeu_si128((__m128i*)(dest_for_jth_element + (k * total_elements)), xmm0[k]);
}
}
}
/* Routine optimized for shuffling a buffer for a type size of 16 bytes. */
static void
shuffle16_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
static const size_t bytesoftype = 16;
size_t j;
int k, l;
uint8_t* dest_for_jth_element;
__m128i xmm0[16], xmm1[16];
for (j = 0; j < vectorizable_elements; j += sizeof(__m128i)) {
/* Fetch 16 elements (256 bytes). */
for (k = 0; k < 16; k++) {
xmm0[k] = _mm_loadu_si128((__m128i*)(src + (j * bytesoftype) + (k * sizeof(__m128i))));
}
/* Transpose bytes */
for (k = 0, l = 0; k < 8; k++, l +=2) {
xmm1[k*2] = _mm_unpacklo_epi8(xmm0[l], xmm0[l+1]);
xmm1[k*2+1] = _mm_unpackhi_epi8(xmm0[l], xmm0[l+1]);
}
/* Transpose words */
for (k = 0, l = -2; k < 8; k++, l++) {
if ((k%2) == 0) l += 2;
xmm0[k*2] = _mm_unpacklo_epi16(xmm1[l], xmm1[l+2]);
xmm0[k*2+1] = _mm_unpackhi_epi16(xmm1[l], xmm1[l+2]);
}
/* Transpose double words */
for (k = 0, l = -4; k < 8; k++, l++) {
if ((k%4) == 0) l += 4;
xmm1[k*2] = _mm_unpacklo_epi32(xmm0[l], xmm0[l+4]);
xmm1[k*2+1] = _mm_unpackhi_epi32(xmm0[l], xmm0[l+4]);
}
/* Transpose quad words */
for (k = 0; k < 8; k++) {
xmm0[k*2] = _mm_unpacklo_epi64(xmm1[k], xmm1[k+8]);
xmm0[k*2+1] = _mm_unpackhi_epi64(xmm1[k], xmm1[k+8]);
}
/* Store the result vectors */
dest_for_jth_element = dest + j;
for (k = 0; k < 16; k++) {
_mm_storeu_si128((__m128i*)(dest_for_jth_element + (k * total_elements)), xmm0[k]);
}
}
}
/* Routine optimized for shuffling a buffer for a type size larger than 16 bytes. */
static void
shuffle16_tiled_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements, const size_t bytesoftype)
{
size_t j;
const size_t vecs_per_el_rem = bytesoftype % sizeof(__m128i);
int k, l;
uint8_t* dest_for_jth_element;
__m128i xmm0[16], xmm1[16];
for (j = 0; j < vectorizable_elements; j += sizeof(__m128i)) {
/* Advance the offset into the type by the vector size (in bytes), unless this is
the initial iteration and the type size is not a multiple of the vector size.
In that case, only advance by the number of bytes necessary so that the number
of remaining bytes in the type will be a multiple of the vector size. */
size_t offset_into_type;
for (offset_into_type = 0; offset_into_type < bytesoftype;
offset_into_type += (offset_into_type == 0 && vecs_per_el_rem > 0 ? vecs_per_el_rem : sizeof(__m128i))) {
/* Fetch elements in groups of 256 bytes */
const uint8_t* const src_with_offset = src + offset_into_type;
for (k = 0; k < 16; k++) {
xmm0[k] = _mm_loadu_si128((__m128i*)(src_with_offset + (j + k) * bytesoftype));
}
/* Transpose bytes */
for (k = 0, l = 0; k < 8; k++, l +=2) {
xmm1[k*2] = _mm_unpacklo_epi8(xmm0[l], xmm0[l+1]);
xmm1[k*2+1] = _mm_unpackhi_epi8(xmm0[l], xmm0[l+1]);
}
/* Transpose words */
for (k = 0, l = -2; k < 8; k++, l++) {
if ((k%2) == 0) l += 2;
xmm0[k*2] = _mm_unpacklo_epi16(xmm1[l], xmm1[l+2]);
xmm0[k*2+1] = _mm_unpackhi_epi16(xmm1[l], xmm1[l+2]);
}
/* Transpose double words */
for (k = 0, l = -4; k < 8; k++, l++) {
if ((k%4) == 0) l += 4;
xmm1[k*2] = _mm_unpacklo_epi32(xmm0[l], xmm0[l+4]);
xmm1[k*2+1] = _mm_unpackhi_epi32(xmm0[l], xmm0[l+4]);
}
/* Transpose quad words */
for (k = 0; k < 8; k++) {
xmm0[k*2] = _mm_unpacklo_epi64(xmm1[k], xmm1[k+8]);
xmm0[k*2+1] = _mm_unpackhi_epi64(xmm1[k], xmm1[k+8]);
}
/* Store the result vectors */
dest_for_jth_element = dest + j;
for (k = 0; k < 16; k++) {
_mm_storeu_si128((__m128i*)(dest_for_jth_element + (total_elements * (offset_into_type + k))), xmm0[k]);
}
}
}
}
/* Routine optimized for unshuffling a buffer for a type size of 2 bytes. */
static void
unshuffle2_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
static const size_t bytesoftype = 2;
size_t i;
int j;
__m128i xmm0[2], xmm1[2];
for (i = 0; i < vectorizable_elements; i += sizeof(__m128i)) {
/* Load 16 elements (32 bytes) into 2 XMM registers. */
const uint8_t* const src_for_ith_element = src + i;
for (j = 0; j < 2; j++) {
xmm0[j] = _mm_loadu_si128((__m128i*)(src_for_ith_element + (j * total_elements)));
}
/* Shuffle bytes */
/* Compute the low 32 bytes */
xmm1[0] = _mm_unpacklo_epi8(xmm0[0], xmm0[1]);
/* Compute the hi 32 bytes */
xmm1[1] = _mm_unpackhi_epi8(xmm0[0], xmm0[1]);
/* Store the result vectors in proper order */
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (0 * sizeof(__m128i))), xmm1[0]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (1 * sizeof(__m128i))), xmm1[1]);
}
}
/* Routine optimized for unshuffling a buffer for a type size of 4 bytes. */
static void
unshuffle4_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
static const size_t bytesoftype = 4;
size_t i;
int j;
__m128i xmm0[4], xmm1[4];
for (i = 0; i < vectorizable_elements; i += sizeof(__m128i)) {
/* Load 16 elements (64 bytes) into 4 XMM registers. */
const uint8_t* const src_for_ith_element = src + i;
for (j = 0; j < 4; j++) {
xmm0[j] = _mm_loadu_si128((__m128i*)(src_for_ith_element + (j * total_elements)));
}
/* Shuffle bytes */
for (j = 0; j < 2; j++) {
/* Compute the low 32 bytes */
xmm1[j] = _mm_unpacklo_epi8(xmm0[j*2], xmm0[j*2+1]);
/* Compute the hi 32 bytes */
xmm1[2+j] = _mm_unpackhi_epi8(xmm0[j*2], xmm0[j*2+1]);
}
/* Shuffle 2-byte words */
for (j = 0; j < 2; j++) {
/* Compute the low 32 bytes */
xmm0[j] = _mm_unpacklo_epi16(xmm1[j*2], xmm1[j*2+1]);
/* Compute the hi 32 bytes */
xmm0[2+j] = _mm_unpackhi_epi16(xmm1[j*2], xmm1[j*2+1]);
}
/* Store the result vectors in proper order */
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (0 * sizeof(__m128i))), xmm0[0]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (1 * sizeof(__m128i))), xmm0[2]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (2 * sizeof(__m128i))), xmm0[1]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (3 * sizeof(__m128i))), xmm0[3]);
}
}
/* Routine optimized for unshuffling a buffer for a type size of 8 bytes. */
static void
unshuffle8_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
static const size_t bytesoftype = 8;
size_t i;
int j;
__m128i xmm0[8], xmm1[8];
for (i = 0; i < vectorizable_elements; i += sizeof(__m128i)) {
/* Load 16 elements (128 bytes) into 8 XMM registers. */
const uint8_t* const src_for_ith_element = src + i;
for (j = 0; j < 8; j++) {
xmm0[j] = _mm_loadu_si128((__m128i*)(src_for_ith_element + (j * total_elements)));
}
/* Shuffle bytes */
for (j = 0; j < 4; j++) {
/* Compute the low 32 bytes */
xmm1[j] = _mm_unpacklo_epi8(xmm0[j*2], xmm0[j*2+1]);
/* Compute the hi 32 bytes */
xmm1[4+j] = _mm_unpackhi_epi8(xmm0[j*2], xmm0[j*2+1]);
}
/* Shuffle 2-byte words */
for (j = 0; j < 4; j++) {
/* Compute the low 32 bytes */
xmm0[j] = _mm_unpacklo_epi16(xmm1[j*2], xmm1[j*2+1]);
/* Compute the hi 32 bytes */
xmm0[4+j] = _mm_unpackhi_epi16(xmm1[j*2], xmm1[j*2+1]);
}
/* Shuffle 4-byte dwords */
for (j = 0; j < 4; j++) {
/* Compute the low 32 bytes */
xmm1[j] = _mm_unpacklo_epi32(xmm0[j*2], xmm0[j*2+1]);
/* Compute the hi 32 bytes */
xmm1[4+j] = _mm_unpackhi_epi32(xmm0[j*2], xmm0[j*2+1]);
}
/* Store the result vectors in proper order */
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (0 * sizeof(__m128i))), xmm1[0]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (1 * sizeof(__m128i))), xmm1[4]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (2 * sizeof(__m128i))), xmm1[2]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (3 * sizeof(__m128i))), xmm1[6]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (4 * sizeof(__m128i))), xmm1[1]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (5 * sizeof(__m128i))), xmm1[5]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (6 * sizeof(__m128i))), xmm1[3]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (7 * sizeof(__m128i))), xmm1[7]);
}
}
/* Routine optimized for unshuffling a buffer for a type size of 16 bytes. */
static void
unshuffle16_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
static const size_t bytesoftype = 16;
size_t i;
int j;
__m128i xmm1[16], xmm2[16];
for (i = 0; i < vectorizable_elements; i += sizeof(__m128i)) {
/* Load 16 elements (256 bytes) into 16 XMM registers. */
const uint8_t* const src_for_ith_element = src + i;
for (j = 0; j < 16; j++) {
xmm1[j] = _mm_loadu_si128((__m128i*)(src_for_ith_element + (j * total_elements)));
}
/* Shuffle bytes */
for (j = 0; j < 8; j++) {
/* Compute the low 32 bytes */
xmm2[j] = _mm_unpacklo_epi8(xmm1[j*2], xmm1[j*2+1]);
/* Compute the hi 32 bytes */
xmm2[8+j] = _mm_unpackhi_epi8(xmm1[j*2], xmm1[j*2+1]);
}
/* Shuffle 2-byte words */
for (j = 0; j < 8; j++) {
/* Compute the low 32 bytes */
xmm1[j] = _mm_unpacklo_epi16(xmm2[j*2], xmm2[j*2+1]);
/* Compute the hi 32 bytes */
xmm1[8+j] = _mm_unpackhi_epi16(xmm2[j*2], xmm2[j*2+1]);
}
/* Shuffle 4-byte dwords */
for (j = 0; j < 8; j++) {
/* Compute the low 32 bytes */
xmm2[j] = _mm_unpacklo_epi32(xmm1[j*2], xmm1[j*2+1]);
/* Compute the hi 32 bytes */
xmm2[8+j] = _mm_unpackhi_epi32(xmm1[j*2], xmm1[j*2+1]);
}
/* Shuffle 8-byte qwords */
for (j = 0; j < 8; j++) {
/* Compute the low 32 bytes */
xmm1[j] = _mm_unpacklo_epi64(xmm2[j*2], xmm2[j*2+1]);
/* Compute the hi 32 bytes */
xmm1[8+j] = _mm_unpackhi_epi64(xmm2[j*2], xmm2[j*2+1]);
}
/* Store the result vectors in proper order */
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (0 * sizeof(__m128i))), xmm1[0]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (1 * sizeof(__m128i))), xmm1[8]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (2 * sizeof(__m128i))), xmm1[4]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (3 * sizeof(__m128i))), xmm1[12]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (4 * sizeof(__m128i))), xmm1[2]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (5 * sizeof(__m128i))), xmm1[10]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (6 * sizeof(__m128i))), xmm1[6]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (7 * sizeof(__m128i))), xmm1[14]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (8 * sizeof(__m128i))), xmm1[1]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (9 * sizeof(__m128i))), xmm1[9]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (10 * sizeof(__m128i))), xmm1[5]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (11 * sizeof(__m128i))), xmm1[13]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (12 * sizeof(__m128i))), xmm1[3]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (13 * sizeof(__m128i))), xmm1[11]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (14 * sizeof(__m128i))), xmm1[7]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (15 * sizeof(__m128i))), xmm1[15]);
}
}
/* Routine optimized for unshuffling a buffer for a type size larger than 16 bytes. */
static void
unshuffle16_tiled_sse2(uint8_t* const dest, const uint8_t* const orig,
const size_t vectorizable_elements, const size_t total_elements, const size_t bytesoftype)
{
size_t i;
const size_t vecs_per_el_rem = bytesoftype % sizeof(__m128i);
int j;
uint8_t* dest_with_offset;
__m128i xmm1[16], xmm2[16];
/* The unshuffle loops are inverted (compared to shuffle_tiled16_sse2)
to optimize cache utilization. */
size_t offset_into_type;
for (offset_into_type = 0; offset_into_type < bytesoftype;
offset_into_type += (offset_into_type == 0 && vecs_per_el_rem > 0 ? vecs_per_el_rem : sizeof(__m128i))) {
for (i = 0; i < vectorizable_elements; i += sizeof(__m128i)) {
/* Load the first 128 bytes in 16 XMM registers */
const uint8_t* const src_for_ith_element = orig + i;
for (j = 0; j < 16; j++) {
xmm1[j] = _mm_loadu_si128((__m128i*)(src_for_ith_element + (total_elements * (offset_into_type + j))));
}
/* Shuffle bytes */
for (j = 0; j < 8; j++) {
/* Compute the low 32 bytes */
xmm2[j] = _mm_unpacklo_epi8(xmm1[j*2], xmm1[j*2+1]);
/* Compute the hi 32 bytes */
xmm2[8+j] = _mm_unpackhi_epi8(xmm1[j*2], xmm1[j*2+1]);
}
/* Shuffle 2-byte words */
for (j = 0; j < 8; j++) {
/* Compute the low 32 bytes */
xmm1[j] = _mm_unpacklo_epi16(xmm2[j*2], xmm2[j*2+1]);
/* Compute the hi 32 bytes */
xmm1[8+j] = _mm_unpackhi_epi16(xmm2[j*2], xmm2[j*2+1]);
}
/* Shuffle 4-byte dwords */
for (j = 0; j < 8; j++) {
/* Compute the low 32 bytes */
xmm2[j] = _mm_unpacklo_epi32(xmm1[j*2], xmm1[j*2+1]);
/* Compute the hi 32 bytes */
xmm2[8+j] = _mm_unpackhi_epi32(xmm1[j*2], xmm1[j*2+1]);
}
/* Shuffle 8-byte qwords */
for (j = 0; j < 8; j++) {
/* Compute the low 32 bytes */
xmm1[j] = _mm_unpacklo_epi64(xmm2[j*2], xmm2[j*2+1]);
/* Compute the hi 32 bytes */
xmm1[8+j] = _mm_unpackhi_epi64(xmm2[j*2], xmm2[j*2+1]);
}
/* Store the result vectors in proper order */
dest_with_offset = dest + offset_into_type;
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 0) * bytesoftype), xmm1[0]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 1) * bytesoftype), xmm1[8]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 2) * bytesoftype), xmm1[4]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 3) * bytesoftype), xmm1[12]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 4) * bytesoftype), xmm1[2]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 5) * bytesoftype), xmm1[10]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 6) * bytesoftype), xmm1[6]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 7) * bytesoftype), xmm1[14]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 8) * bytesoftype), xmm1[1]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 9) * bytesoftype), xmm1[9]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 10) * bytesoftype), xmm1[5]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 11) * bytesoftype), xmm1[13]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 12) * bytesoftype), xmm1[3]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 13) * bytesoftype), xmm1[11]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 14) * bytesoftype), xmm1[7]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 15) * bytesoftype), xmm1[15]);
}
}
}
/* Shuffle a block. This can never fail. */
void
shuffle_sse2(const size_t bytesoftype, const size_t blocksize,
const uint8_t* const _src, uint8_t* const _dest) {
const size_t vectorized_chunk_size = bytesoftype * sizeof(__m128i);
/* If the blocksize is not a multiple of both the typesize and
the vector size, round the blocksize down to the next value
which is a multiple of both. The vectorized shuffle can be
used for that portion of the data, and the naive implementation
can be used for the remaining portion. */
const size_t vectorizable_bytes = blocksize - (blocksize % vectorized_chunk_size);
const size_t vectorizable_elements = vectorizable_bytes / bytesoftype;
const size_t total_elements = blocksize / bytesoftype;
/* If the block size is too small to be vectorized,
use the generic implementation. */
if (blocksize < vectorized_chunk_size) {
shuffle_generic(bytesoftype, blocksize, _src, _dest);
return;
}
/* Optimized shuffle implementations */
switch (bytesoftype)
{
case 2:
shuffle2_sse2(_dest, _src, vectorizable_elements, total_elements);
break;
case 4:
shuffle4_sse2(_dest, _src, vectorizable_elements, total_elements);
break;
case 8:
shuffle8_sse2(_dest, _src, vectorizable_elements, total_elements);
break;
case 16:
shuffle16_sse2(_dest, _src, vectorizable_elements, total_elements);
break;
default:
if (bytesoftype > sizeof(__m128i)) {
shuffle16_tiled_sse2(_dest, _src, vectorizable_elements, total_elements, bytesoftype);
}
else {
/* Non-optimized shuffle */
shuffle_generic(bytesoftype, blocksize, _src, _dest);
/* The non-optimized function covers the whole buffer,
so we're done processing here. */
return;
}
}
/* If the buffer had any bytes at the end which couldn't be handled
by the vectorized implementations, use the non-optimized version
to finish them up. */
if (vectorizable_bytes < blocksize) {
shuffle_generic_inline(bytesoftype, vectorizable_bytes, blocksize, _src, _dest);
}
}
/* Unshuffle a block. This can never fail. */
void
unshuffle_sse2(const size_t bytesoftype, const size_t blocksize,
const uint8_t* const _src, uint8_t* const _dest) {
const size_t vectorized_chunk_size = bytesoftype * sizeof(__m128i);
/* If the blocksize is not a multiple of both the typesize and
the vector size, round the blocksize down to the next value
which is a multiple of both. The vectorized unshuffle can be
used for that portion of the data, and the naive implementation
can be used for the remaining portion. */
const size_t vectorizable_bytes = blocksize - (blocksize % vectorized_chunk_size);
const size_t vectorizable_elements = vectorizable_bytes / bytesoftype;
const size_t total_elements = blocksize / bytesoftype;
/* If the block size is too small to be vectorized,
use the generic implementation. */
if (blocksize < vectorized_chunk_size) {
unshuffle_generic(bytesoftype, blocksize, _src, _dest);
return;
}
/* Optimized unshuffle implementations */
switch (bytesoftype)
{
case 2:
unshuffle2_sse2(_dest, _src, vectorizable_elements, total_elements);
break;
case 4:
unshuffle4_sse2(_dest, _src, vectorizable_elements, total_elements);
break;
case 8:
unshuffle8_sse2(_dest, _src, vectorizable_elements, total_elements);
break;
case 16:
unshuffle16_sse2(_dest, _src, vectorizable_elements, total_elements);
break;
default:
if (bytesoftype > sizeof(__m128i)) {
unshuffle16_tiled_sse2(_dest, _src, vectorizable_elements, total_elements, bytesoftype);
}
else {
/* Non-optimized unshuffle */
unshuffle_generic(bytesoftype, blocksize, _src, _dest);
/* The non-optimized function covers the whole buffer,
so we're done processing here. */
return;
}
}
/* If the buffer had any bytes at the end which couldn't be handled
by the vectorized implementations, use the non-optimized version
to finish them up. */
if (vectorizable_bytes < blocksize) {
unshuffle_generic_inline(bytesoftype, vectorizable_bytes, blocksize, _src, _dest);
}
}
}
#endif
| 40.184127
| 112
| 0.622808
|
upj977155
|
7b77bac2a43768468ac9619b6160875f737cbb8f
| 628
|
cpp
|
C++
|
W1/Project 1/Source.cpp
|
katookei/Code202
|
0b046e9f8812de00405c14e512da50c8c6ece378
|
[
"MIT"
] | null | null | null |
W1/Project 1/Source.cpp
|
katookei/Code202
|
0b046e9f8812de00405c14e512da50c8c6ece378
|
[
"MIT"
] | null | null | null |
W1/Project 1/Source.cpp
|
katookei/Code202
|
0b046e9f8812de00405c14e512da50c8c6ece378
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <fstream>
#include <string>
#include "Header.h"
using namespace std;
void fraction::readfile(fraction &b)
{
ifstream fou;
int data[10];
fou.open("a.txt");
for (int i = 0; i < 4; i++)
{
fou >> data[i];
}
fou.close();
nu = data[0]; de = data[1];
b.nu = data[2]; b.de = data[3];
cout << "Fraction 1: " << nu << "/" << de << endl;
cout << "Fraction 2: " << b.nu << "/" << b.de << endl;
}
void fraction::compare(fraction b)
{
if (nu*b.de - de* b.nu > 0)
cout << "f1>f2";
else if (nu*b.de - de * b.nu < 0)
cout << "f1<f2";
else
cout << "f1=f2";
}
| 19.625
| 56
| 0.509554
|
katookei
|
7b80fc0bde60c3e98bcde8a0d787d1c3cac08978
| 2,706
|
cpp
|
C++
|
apps/hls_examples/hls_support/syn_target.cpp
|
akifoezkan/Halide-HLS
|
1eee3f38f32722f3e725c29a5b7a084275062a7f
|
[
"MIT"
] | 71
|
2016-11-17T19:22:21.000Z
|
2022-01-10T10:03:58.000Z
|
apps/hls_examples/hls_support/syn_target.cpp
|
akifoezkan/Halide-HLS
|
1eee3f38f32722f3e725c29a5b7a084275062a7f
|
[
"MIT"
] | 30
|
2017-02-02T21:03:33.000Z
|
2018-06-27T20:49:31.000Z
|
apps/hls_examples/hls_support/syn_target.cpp
|
akifoezkan/Halide-HLS
|
1eee3f38f32722f3e725c29a5b7a084275062a7f
|
[
"MIT"
] | 22
|
2017-04-16T11:44:34.000Z
|
2022-03-26T13:27:10.000Z
|
#include "Linebuffer.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
void syn_target(hls::stream<PackedStencil<uint8_t, 2, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 2, 3> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<20, 12>(input_stream, output_stream);
}
void syn_target_3D2D1D(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 3, 3, 3, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<32, 32, 32, 1>(input_stream, output_stream);
}
void syn_target_3D2D(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 1, 3, 3, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<32, 32, 32, 1>(input_stream, output_stream);
}
void syn_target_3D1D(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 3, 1, 3, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<32, 32, 32, 1>(input_stream, output_stream);
}
void syn_target_3D(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 1, 1, 3, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<32, 32, 32, 1>(input_stream, output_stream);
}
void syn_target_2D1D(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 3, 3, 1, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<32, 32, 1, 1>(input_stream, output_stream);
}
void syn_target_2D(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 1, 3, 1, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<32, 32, 1, 1>(input_stream, output_stream);
}
void syn_target_1D(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 3, 1, 1, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<32, 1, 1, 1>(input_stream, output_stream);
}
//2D and 3D linebuffer has latency bug when IMG_EXTENT_0=IN_EXTENT_0=OUT_EXTENT_0
void syn_target_3D2D_bug(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 1, 3, 3, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<1, 32, 32, 1>(input_stream, output_stream);
}
void syn_target_2D_bug(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 1, 3, 1, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<1, 32, 1, 1>(input_stream, output_stream);
}
| 39.217391
| 91
| 0.665558
|
akifoezkan
|
7b83dab5444b86b4a95aaa0adc8f908e1bcef221
| 1,883
|
cpp
|
C++
|
mainwindow.cpp
|
Kronephon/Rasp4Home
|
162bd2a5ee2b718037862bffe9a117b188eff710
|
[
"MIT"
] | null | null | null |
mainwindow.cpp
|
Kronephon/Rasp4Home
|
162bd2a5ee2b718037862bffe9a117b188eff710
|
[
"MIT"
] | 11
|
2020-12-28T21:56:55.000Z
|
2021-09-25T23:46:30.000Z
|
mainwindow.cpp
|
Kronephon/Rasp4Home
|
162bd2a5ee2b718037862bffe9a117b188eff710
|
[
"MIT"
] | null | null | null |
#include <QApplication>
#include <QColor>
#include <QPalette>
#include <QFont>
#include <QBoxLayout>
#include "mainwindow.h"
namespace
{
const float Orange = 0xE95420;
const float WarmGrey = 0xAEA79F;
const float CoolGrey = 0x333333;
const float Aubergine = 0x772953;
const QFont sansFont("Helvetica [Cronyx]", 12);
}
rasp4home::ui::MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), mDisplay(this)
{
setCentralWidget(&mDisplay);
}
rasp4home::ui::MainWindow::~MainWindow()
{
}
rasp4home::ui::MainScreen* rasp4home::ui::MainWindow::getUI()
{
return &mDisplay;
}
/////
rasp4home::ui::MainScreen::MainScreen(QWidget *parent) : QWidget(parent)
{
paletteSetup();
setLayout(new QBoxLayout(QBoxLayout::TopToBottom));
auto tmpfont = sansFont;
tmpfont.setPointSize(30);
mTime.mHours.setFont(tmpfont);
mTime.mSeparator.setFont(tmpfont);
mTime.mMinutes.setFont(tmpfont);
tmpfont.setPointSize(10);
mTime.mSeconds.setFont(tmpfont);
mTime.layout()->setAlignment(Qt::AlignBottom);
layout()->addWidget(&mTime);
layout()->addWidget(&mWeather);
layout()->addWidget(&mQuote);
}
void rasp4home::ui::MainScreen::paletteSetup()
{
setAutoFillBackground(true);
auto palette = QApplication::palette();
palette.setColor(QPalette::All, QPalette::Background, QColor(Aubergine));
palette.setColor(QPalette::All, QPalette::WindowText, QColor(Orange));
setPalette(palette);
}
void rasp4home::ui::MainScreen::setTime(int h, int m, int s)
{
mTime.mHours.setText(QStringLiteral("%1").arg(h, 2, 10, QLatin1Char('0')));
mTime.mMinutes.setText(QStringLiteral("%1").arg(m, 2, 10, QLatin1Char('0')));
mTime.mSeconds.setText(QStringLiteral("%1").arg(s, 2, 10, QLatin1Char('0')));
if(s%2 == 0){
mTime.mSeparator.setText(" ");
} else{
mTime.mSeparator.setText(":");
}
}
| 23.246914
| 81
| 0.686139
|
Kronephon
|
7b83f9b2e9ed820773769516250107094068a8fc
| 2,797
|
cpp
|
C++
|
DarkSpace/StructureSolar.cpp
|
SnipeDragon/darkspace
|
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
|
[
"MIT"
] | 1
|
2016-05-22T21:28:29.000Z
|
2016-05-22T21:28:29.000Z
|
DarkSpace/StructureSolar.cpp
|
SnipeDragon/darkspace
|
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
|
[
"MIT"
] | null | null | null |
DarkSpace/StructureSolar.cpp
|
SnipeDragon/darkspace
|
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
|
[
"MIT"
] | null | null | null |
/*
StructureSolar.cpp
(c)2000 Palestar Inc, Richard Lyle
*/
#include "Debug/Assert.h"
#include "NounStar.h"
#include "GameContext.h"
#include "StructureSolar.h"
//----------------------------------------------------------------------------
const float MAX_STAR_RANGE = 300000.0f;
const float MAX_POWER = 100.0f;
//----------------------------------------------------------------------------
IMPLEMENT_FACTORY( StructureSolar, StructurePower );
REGISTER_FACTORY_KEY( StructureSolar, 4358662172126761340LL );
BEGIN_PROPERTY_LIST( StructureSolar, StructurePower )
ADD_PROPERTY( m_Power );
END_PROPERTY_LIST();
StructureSolar::StructureSolar() : m_nUpdateTick( 0 )
{
m_Power = 0;
}
//----------------------------------------------------------------------------
void StructureSolar::simulate( dword nTick )
{
if ( nTick >= m_nUpdateTick )
{
m_nUpdateTick = nTick + (TICKS_PER_SECOND * 60);
NounPlanet * pPlanet = planet();
ASSERT( pPlanet );
// determine the power output
m_Power = 0;
// get my current world position
Vector3 myPosition( worldPosition() );
// get all nouns within the specified range
Array< GameContext::NounCollision > nouns;
context()->proximityCheck( myPosition, MAX_STAR_RANGE, nouns, CLASS_KEY(NounStar) );
// enumerate all the stars close to this solar generator
for(int i=0;i<nouns.size();i++)
{
NounStar * pStar = WidgetCast<NounStar>( nouns[i].pNoun );
if ( pStar != NULL && nouns[i].fDistance < MAX_STAR_RANGE )
{
// invert the range, so it's higher the closer the planet
float fRange = MAX_STAR_RANGE - nouns[i].fDistance;
Vector3 lightDirection( pStar->worldPosition() - myPosition );
lightDirection.normalize();
Vector3 surfaceDirection( myPosition - pPlanet->worldPosition() );
surfaceDirection.normalize();
float dot = surfaceDirection | lightDirection;
if ( dot > 0 )
m_Power += ((fRange * MAX_POWER) / MAX_STAR_RANGE) * dot;
}
}
}
NounStructure::simulate( nTick );
}
//----------------------------------------------------------------------------
int StructureSolar::sortId() const
{
return 1;
}
int StructureSolar::groupId() const
{
return 4;
}
int StructureSolar::maxDamage() const
{
return 52920;
}
int StructureSolar::buildTechnology() const
{
return 10;
}
int StructureSolar::buildTime() const
{
return 50;
}
int StructureSolar::buildCost() const
{
return 200;
}
int StructureSolar::repairRate() const
{
return 200;
}
Color StructureSolar::color() const
{
return BLUE;
}
int StructureSolar::workers() const
{
return 1;
}
int StructureSolar::power() const
{
return m_Power * getTechPercentage();
}
int StructureSolar::technology() const
{
return 0;
}
//----------------------------------------------------------------------------
//EOF
| 20.718519
| 86
| 0.607079
|
SnipeDragon
|
7b8735dfcf5702cf6bd4302b7796ab83c70ddbc7
| 318
|
cpp
|
C++
|
src/2000/2193.cpp14.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | 8
|
2018-04-12T15:54:09.000Z
|
2020-06-05T07:41:15.000Z
|
src/2000/2193.cpp14.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | null | null | null |
src/2000/2193.cpp14.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | null | null | null |
#include <cstdio>
using namespace std;
int main()
{
int n;
long long ans = 0, dp[91][2] = {};
scanf("%d", &n);
dp[1][0] = 0;
dp[1][1] = 1;
for (int i = 2; i <= n; i++)
{
dp[i][0] = dp[i - 1][0] + dp[i - 1][1];
dp[i][1] = dp[i - 1][0];
}
ans = dp[n][0] + dp[n][1];
printf("%lld\n", ans);
return 0;
}
| 13.826087
| 41
| 0.440252
|
upple
|
7b8c9ad4a14e5a9f5b240f54706943637926380c
| 742
|
cpp
|
C++
|
src/racket.cpp
|
CS126SP20/Crazy-Pong
|
b26d348535f8cc884b49dc9b5541c8dd552c2e9f
|
[
"MIT"
] | 1
|
2020-07-29T03:49:11.000Z
|
2020-07-29T03:49:11.000Z
|
src/racket.cpp
|
CS126SP20/Crazy-Pong
|
b26d348535f8cc884b49dc9b5541c8dd552c2e9f
|
[
"MIT"
] | null | null | null |
src/racket.cpp
|
CS126SP20/Crazy-Pong
|
b26d348535f8cc884b49dc9b5541c8dd552c2e9f
|
[
"MIT"
] | null | null | null |
//
// Created by Riya Gupta on 4/27/20.
//
#include "mylibrary/racket.h";
using namespace mylibrary;
Racket::Racket() { x = 0.0f; y = 0.0f; score = 0; }
float Racket::getX() const { return x; }
float Racket::getY() const { return y; }
void Racket::Init( float a, float b) { x = a; y = b; }
int Racket::getScore() const { return score; }
void Racket::setScore(int score) { Racket::score = score; }
void Racket::Draw() {
cinder::gl::color(Color(0, 1, 0));
cinder::gl::drawSolidRect(Rectf(x,
y,
x + kRacket_width,
y + kRacket_height));
}
void Racket::MoveUp() {
y -= kRacket_speed;
}
void Racket::MoveDown() {
y += kRacket_speed;
}
| 26.5
| 59
| 0.552561
|
CS126SP20
|
7b90342ee9f4e6fca9ff2bfc0e5d68458ab25bc0
| 411
|
cpp
|
C++
|
samples/snippets/cpp/VS_Snippets_CLR_System/system.Char.CompareTo/CPP/compareto.cpp
|
hamarb123/dotnet-api-docs
|
6aeb55784944a2f1f5e773b657791cbd73a92dd4
|
[
"CC-BY-4.0",
"MIT"
] | 421
|
2018-04-01T01:57:50.000Z
|
2022-03-28T15:24:42.000Z
|
samples/snippets/cpp/VS_Snippets_CLR_System/system.Char.CompareTo/CPP/compareto.cpp
|
hamarb123/dotnet-api-docs
|
6aeb55784944a2f1f5e773b657791cbd73a92dd4
|
[
"CC-BY-4.0",
"MIT"
] | 5,797
|
2018-04-02T21:12:23.000Z
|
2022-03-31T23:54:38.000Z
|
samples/snippets/cpp/VS_Snippets_CLR_System/system.Char.CompareTo/CPP/compareto.cpp
|
hamarb123/dotnet-api-docs
|
6aeb55784944a2f1f5e773b657791cbd73a92dd4
|
[
"CC-BY-4.0",
"MIT"
] | 1,482
|
2018-03-31T11:26:20.000Z
|
2022-03-30T22:36:45.000Z
|
// <snippet19>
using namespace System;
int main()
{
char chA = 'A';
char chB = 'B';
Console::WriteLine( chA.CompareTo( 'A' ) ); // Output: "0" (meaning they're equal)
Console::WriteLine( 'b'.CompareTo( chB ) ); // Output: "32" (meaning 'b' is greater than 'B' by 32)
Console::WriteLine( chA.CompareTo( chB ) ); // Output: "-1" (meaning 'A' is less than 'B' by 1)
}
// </snippet19>
| 29.357143
| 103
| 0.579075
|
hamarb123
|
7b92b2674214aeea2c32f3eb186fa8d9b8177513
| 5,235
|
hpp
|
C++
|
src/centurion/initialization.hpp
|
Creeperface01/centurion
|
e3b674c11849367a18c2d976ce94071108e1590d
|
[
"MIT"
] | 14
|
2020-05-17T21:38:03.000Z
|
2020-11-21T00:16:25.000Z
|
src/centurion/initialization.hpp
|
Creeperface01/centurion
|
e3b674c11849367a18c2d976ce94071108e1590d
|
[
"MIT"
] | 70
|
2020-04-26T17:08:52.000Z
|
2020-11-21T17:34:03.000Z
|
src/centurion/initialization.hpp
|
Creeperface01/centurion
|
e3b674c11849367a18c2d976ce94071108e1590d
|
[
"MIT"
] | null | null | null |
/*
* MIT License
*
* Copyright (c) 2019-2022 Albin Johansson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef CENTURION_INITIALIZATION_HPP_
#define CENTURION_INITIALIZATION_HPP_
#include <SDL.h>
#include <cassert> // assert
#include <optional> // optional
#include "common.hpp"
#include "features.hpp"
#ifndef CENTURION_NO_SDL_IMAGE
#include <SDL_image.h>
#endif // CENTURION_NO_SDL_IMAGE
#ifndef CENTURION_NO_SDL_MIXER
#include <SDL_mixer.h>
#endif // CENTURION_NO_SDL_MIXER
#ifndef CENTURION_NO_SDL_TTF
#include <SDL_ttf.h>
#endif // CENTURION_NO_SDL_TTF
namespace cen {
/**
* \ingroup common
* \defgroup initialization Initialization
*
* \brief Contains components related to SDL initialization.
*/
/// \addtogroup initialization
/// \{
/**
* \brief Used to specify how the core SDL library is initialized.
*/
struct sdl_cfg final
{
/// \brief Controls which SDL subsystems are initialized, see `SDL_INIT_` macros.
uint32 flags{SDL_INIT_EVERYTHING};
};
/**
* \brief Used to load and subsequently unload the core SDL library.
*
* \see `img`
* \see `mix`
* \see `ttf`
*/
class sdl final
{
public:
/**
* \brief Loads the core SDL library.
*
* \param cfg the configuration that will be used.
*
* \throws sdl_error if the SDL library cannot be initialized.
*/
CENTURION_NODISCARD_CTOR explicit sdl(const sdl_cfg& cfg = {})
{
if (SDL_Init(cfg.flags) < 0) {
throw sdl_error{};
}
}
~sdl() noexcept { SDL_Quit(); }
};
#ifndef CENTURION_NO_SDL_IMAGE
/**
* \brief Used to specify how the SDL_image library is initialized.
*/
struct img_cfg final
{
/// \brief Controls which image formats to support, see `IMG_INIT_` macros.
int flags{IMG_INIT_PNG | IMG_INIT_JPG | IMG_INIT_TIF | IMG_INIT_WEBP};
};
/**
* \brief Used to load and subsequently unload the SDL_image library.
*/
class img final
{
public:
/**
* \brief Loads the SDL_image library.
*
* \param cfg the configuration that will be used.
*
* \throws img_error if the SDL_image library cannot be initialized.
*/
CENTURION_NODISCARD_CTOR explicit img(const img_cfg& cfg = {})
{
if (!IMG_Init(cfg.flags)) {
throw img_error{};
}
}
~img() noexcept { IMG_Quit(); }
};
#endif // CENTURION_NO_SDL_IMAGE
#ifndef CENTURION_NO_SDL_MIXER
/**
* \brief Used to specify how the SDL_mixer library is initialized.
*/
struct mix_cfg final
{
/// \brief Controls which file formats to be supported, see `MIX_INIT_` macros.
int flags{MIX_INIT_MP3 | MIX_INIT_OGG | MIX_INIT_FLAC | MIX_INIT_MID | MIX_INIT_MOD |
MIX_INIT_OPUS};
/// \brief The mixer frequency.
int frequency{MIX_DEFAULT_FREQUENCY};
/// \brief The mixer format.
uint16 format{MIX_DEFAULT_FORMAT};
/// \brief The amount of mixer channels.
int channels{MIX_DEFAULT_CHANNELS};
/// \brief The mixer chunk size, in bytes.
int chunk_size{4096};
};
/**
* \brief Used to load and subsequently unload the SDL_mixer library.
*/
class mix final
{
public:
/**
* \brief Loads the SDL_mixer library.
*
* \param cfg the configuration that will be used.
*
* \throws mix_error if the SDL_mixer library cannot be initialized or if the audio device
* couldn't be opened.
*/
CENTURION_NODISCARD_CTOR explicit mix(const mix_cfg& cfg = {})
{
if (!Mix_Init(cfg.flags)) {
throw mix_error{};
}
if (Mix_OpenAudio(cfg.frequency, cfg.format, cfg.channels, cfg.chunk_size) == -1) {
throw mix_error{};
}
}
~mix() noexcept
{
Mix_CloseAudio();
Mix_Quit();
}
};
#endif // CENTURION_NO_SDL_MIXER
#ifndef CENTURION_NO_SDL_TTF
/**
* \brief Used to load and subsequently unload the SDL_ttf library.
*/
class ttf final
{
public:
/**
* \brief Loads the SDL_ttf library.
*
* \param cfg the configuration that will be used.
*
* \throws ttf_error if the SDL_ttf library cannot be initialized.
*/
CENTURION_NODISCARD_CTOR ttf()
{
if (TTF_Init() == -1) {
throw ttf_error{};
}
}
~ttf() noexcept { TTF_Quit(); }
};
#endif // CENTURION_NO_SDL_TTF
/// \} End of group initialization
} // namespace cen
#endif // CENTURION_INITIALIZATION_HPP_
| 23.581081
| 92
| 0.697994
|
Creeperface01
|
7ba5c8510ca867c972b3377b1e628d4e31576afa
| 291
|
hpp
|
C++
|
SQL/FactoryRedis.hpp
|
useryoung-2019/MyHttpServer
|
ce23c1bf161edba08a82d54de6693167a8917d18
|
[
"MIT"
] | null | null | null |
SQL/FactoryRedis.hpp
|
useryoung-2019/MyHttpServer
|
ce23c1bf161edba08a82d54de6693167a8917d18
|
[
"MIT"
] | null | null | null |
SQL/FactoryRedis.hpp
|
useryoung-2019/MyHttpServer
|
ce23c1bf161edba08a82d54de6693167a8917d18
|
[
"MIT"
] | null | null | null |
#ifndef FACTORYREDIS_H
#define FACTORYREDIS_H
#include"AbstractFactory.hpp"
#include"ProductRedis.hpp"
class FactoryRedis:public AbstractFactory
{
public:
shared_ptr<AbstractProductSQL> createSQL()
{
return shared_ptr<AbstractProductSQL>(new ProductRedis);
}
};
#endif
| 18.1875
| 64
| 0.762887
|
useryoung-2019
|
7bb11b832ba20d98c9d7c8a8d06658affa55c560
| 3,919
|
cpp
|
C++
|
src/cipher.cpp
|
chrisballinger/OLMKit
|
daab2a58af947cddd67fe9f30dd3a9fc327650c0
|
[
"Apache-2.0"
] | 2
|
2016-04-14T13:48:33.000Z
|
2021-01-11T03:48:19.000Z
|
src/cipher.cpp
|
chrisballinger/OLMKit
|
daab2a58af947cddd67fe9f30dd3a9fc327650c0
|
[
"Apache-2.0"
] | 1
|
2019-01-25T16:20:41.000Z
|
2020-10-28T13:54:39.000Z
|
src/cipher.cpp
|
chrisballinger/OLMKit
|
daab2a58af947cddd67fe9f30dd3a9fc327650c0
|
[
"Apache-2.0"
] | 1
|
2017-01-11T18:13:00.000Z
|
2017-01-11T18:13:00.000Z
|
/* Copyright 2015 OpenMarket Ltd
*
* 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 "olm/cipher.hh"
#include "olm/crypto.hh"
#include "olm/memory.hh"
#include <cstring>
olm::Cipher::~Cipher() {
}
namespace {
struct DerivedKeys {
olm::Aes256Key aes_key;
std::uint8_t mac_key[olm::KEY_LENGTH];
olm::Aes256Iv aes_iv;
};
static void derive_keys(
std::uint8_t const * kdf_info, std::size_t kdf_info_length,
std::uint8_t const * key, std::size_t key_length,
DerivedKeys & keys
) {
std::uint8_t derived_secrets[2 * olm::KEY_LENGTH + olm::IV_LENGTH];
olm::hkdf_sha256(
key, key_length,
nullptr, 0,
kdf_info, kdf_info_length,
derived_secrets, sizeof(derived_secrets)
);
std::uint8_t const * pos = derived_secrets;
pos = olm::load_array(keys.aes_key.key, pos);
pos = olm::load_array(keys.mac_key, pos);
pos = olm::load_array(keys.aes_iv.iv, pos);
olm::unset(derived_secrets);
}
static const std::size_t MAC_LENGTH = 8;
} // namespace
olm::CipherAesSha256::CipherAesSha256(
std::uint8_t const * kdf_info, std::size_t kdf_info_length
) : kdf_info(kdf_info), kdf_info_length(kdf_info_length) {
}
std::size_t olm::CipherAesSha256::mac_length() const {
return MAC_LENGTH;
}
std::size_t olm::CipherAesSha256::encrypt_ciphertext_length(
std::size_t plaintext_length
) const {
return olm::aes_encrypt_cbc_length(plaintext_length);
}
std::size_t olm::CipherAesSha256::encrypt(
std::uint8_t const * key, std::size_t key_length,
std::uint8_t const * plaintext, std::size_t plaintext_length,
std::uint8_t * ciphertext, std::size_t ciphertext_length,
std::uint8_t * output, std::size_t output_length
) const {
if (encrypt_ciphertext_length(plaintext_length) < ciphertext_length) {
return std::size_t(-1);
}
struct DerivedKeys keys;
std::uint8_t mac[olm::SHA256_OUTPUT_LENGTH];
derive_keys(kdf_info, kdf_info_length, key, key_length, keys);
olm::aes_encrypt_cbc(
keys.aes_key, keys.aes_iv, plaintext, plaintext_length, ciphertext
);
olm::hmac_sha256(
keys.mac_key, olm::KEY_LENGTH, output, output_length - MAC_LENGTH, mac
);
std::memcpy(output + output_length - MAC_LENGTH, mac, MAC_LENGTH);
olm::unset(keys);
return output_length;
}
std::size_t olm::CipherAesSha256::decrypt_max_plaintext_length(
std::size_t ciphertext_length
) const {
return ciphertext_length;
}
std::size_t olm::CipherAesSha256::decrypt(
std::uint8_t const * key, std::size_t key_length,
std::uint8_t const * input, std::size_t input_length,
std::uint8_t const * ciphertext, std::size_t ciphertext_length,
std::uint8_t * plaintext, std::size_t max_plaintext_length
) const {
DerivedKeys keys;
std::uint8_t mac[olm::SHA256_OUTPUT_LENGTH];
derive_keys(kdf_info, kdf_info_length, key, key_length, keys);
olm::hmac_sha256(
keys.mac_key, olm::KEY_LENGTH, input, input_length - MAC_LENGTH, mac
);
std::uint8_t const * input_mac = input + input_length - MAC_LENGTH;
if (!olm::is_equal(input_mac, mac, MAC_LENGTH)) {
olm::unset(keys);
return std::size_t(-1);
}
std::size_t plaintext_length = olm::aes_decrypt_cbc(
keys.aes_key, keys.aes_iv, ciphertext, ciphertext_length, plaintext
);
olm::unset(keys);
return plaintext_length;
}
| 28.194245
| 78
| 0.700944
|
chrisballinger
|
7bb208e8ba6f8a0ce70f31250587a31f0cf1ed7b
| 4,387
|
hpp
|
C++
|
mod/wrd/src/ast/node.hpp
|
kniz/worldlang
|
78701ab003c158211d42d129f91259d17febbb22
|
[
"MIT"
] | 7
|
2019-03-12T03:04:32.000Z
|
2021-12-26T04:33:44.000Z
|
mod/wrd/src/ast/node.hpp
|
kniz/worldlang
|
78701ab003c158211d42d129f91259d17febbb22
|
[
"MIT"
] | 7
|
2019-02-13T14:01:43.000Z
|
2020-11-20T11:09:06.000Z
|
mod/wrd/src/ast/node.hpp
|
kniz/worldlang
|
78701ab003c158211d42d129f91259d17febbb22
|
[
"MIT"
] | null | null | null |
#pragma once
#include "clonable.hpp"
#include "../builtin/container/native/tnarr.hpp"
#include "validable.hpp"
namespace wrd {
class ases;
/// node provides common API to manipulate its sub nodes.
class node : public instance, public clonable {
WRD(INTERFACE(node, instance))
public:
node& operator[](const std::string& name) const { return sub(name); }
public:
wbool isSub(const type& it) const { return getType().isSub(it); }
wbool isSuper(const type& it) const { return getType().isSuper(it); }
template <typename T>
wbool isSub() const { return getType().isSub<T>(); }
template <typename T>
wbool isSuper() const { return getType().isSuper<T>(); }
virtual ncontainer& subs() = 0;
const ncontainer& subs() const WRD_UNCONST_FUNC(subs())
template <typename T>
T& sub(std::function<wbool(const T&)> l) const {
return subs().get<T>(l);
}
template <typename T = me>
T& sub(const std::string& name) const;
template <typename T = me>
T& sub(const std::string& name, const ncontainer& args);
template <typename T = me>
T& sub(const std::string& name, const wtypes& types);
template <typename T = me>
T& sub(const std::string& name, const ncontainer& args) const;
template <typename T = me>
T& sub(const std::string& name, const wtypes& types) const;
template <typename T>
tnarr<T> subAll(std::function<wbool(const T&)> l) const {
return subs().getAll<T>(l);
}
template <typename T = me>
tnarr<T> subAll(const std::string& name) const;
template <typename T = me>
tnarr<T> subAll(const std::string& name, const ncontainer& args);
template <typename T = me>
tnarr<T> subAll(const std::string& name, const wtypes& types);
template <typename T = me>
tnarr<T> subAll(const std::string& name, const ncontainer& args) const;
template <typename T = me>
tnarr<T> subAll(const std::string& name, const wtypes& types) const;
virtual wbool canRun(const wtypes& typs) const = 0;
wbool canRun(const containable& args) const {
return canRun(createTypesFromArgs(args));
}
virtual str run(const containable& args) = 0;
str run();
/// release all holding resources and ready to be terminated.
/// @remark some class won't be able to reinitialize after rel() got called.
virtual void rel() {}
virtual const std::string& getName() const {
static std::string dummy = "";
return dummy;
}
template <typename T>
wbool is() const {
return is(ttype<T>::get());
}
wbool is(const type& to) const {
return getType().is(to);
}
template <typename T>
tstr<T> as() const {
return as(ttype<T>::get());
}
str as(const type& to) const {
return getType().as(*this, to);
}
template <typename T>
wbool isImpli() const {
return isImpli(ttype<T>::get());
}
wbool isImpli(const type& to) const {
return getType().isImpli(to);
}
template <typename T>
tstr<T> asImpli() const {
return asImpli(ttype<T>::get());
}
str asImpli(const type& to) const {
return getType().asImpli(*this, to);
}
/// getType() returns what it is. opposite to it, this returns what this class will
/// represents after evaluation.
///
/// for example, the 'expr' class has derived from this node class. and if an user call the
/// funcs to get type of it, class 'wtype' of 'expr' will be returned.
/// but if that user call the 'getEvalType()' then the 'expr' object evaluate its terms and
/// returns type of the output. it could be integer if it was 'addExpr' and all terms are
/// constructed with integers.
virtual const wtype& getEvalType() const {
return getType();
}
static wtypes createTypesFromArgs(const containable& args) {
wtypes ret;
for(iter e=args.begin(); e ;e++)
ret.push_back((wtype*) &e->getEvalType());
return ret;
}
};
}
| 34.543307
| 99
| 0.578527
|
kniz
|
7bb29975b2420b277accdb5621008b6c37ad4fbd
| 1,776
|
hpp
|
C++
|
Example/src/MYENG_DB/ModuleBase.hpp
|
heesok2/MFC
|
1ff13a425609addbf458d00f9853d16ada2b29ec
|
[
"MIT"
] | null | null | null |
Example/src/MYENG_DB/ModuleBase.hpp
|
heesok2/MFC
|
1ff13a425609addbf458d00f9853d16ada2b29ec
|
[
"MIT"
] | null | null | null |
Example/src/MYENG_DB/ModuleBase.hpp
|
heesok2/MFC
|
1ff13a425609addbf458d00f9853d16ada2b29ec
|
[
"MIT"
] | null | null | null |
#pragma once
#ifndef MODULEDATA_DEF
#define MODULEDATA_DEF
#include "Module.h"
#include "EntityDictionary.hpp"
namespace mydb
{
template <class ENTITY_DATA>
class CModuleData : public mydb::CModule
{
public:
CModuleData(CPackage * pPackage)
: CModule(pPackage)
{}
virtual ~CModuleData() {}
public: // Data
virtual void Clear()
{
m_Dictionary.Clear();
}
virtual BOOL Empty()
{
return m_Dictionary.IsEmpty();
}
virtual BOOL Exist(MYKEY key)
{
auto itr = m_Dictionary.Find(key);
return ITR_IS_VALID(itr);
}
virtual MYITR Find(MYKEY key)
{
return m_Dictionary.Find(key);
}
virtual BOOL Lookup(MYKEY key, ENTITY_DATA& data)
{
auto itr = m_Dictionary.Find(key);
if (!ITR_IS_VALID(itr))
return FALSE;
data = m_Dictionary.GetAtNU(itr);
return TRUE;
}
virtual MYITR InsertNU(const ENTITY_DATA& data)
{
return m_Dictionary.InsertNU(data);
}
virtual BOOL SetAtNU(MYITR itr, const ENTITY_DATA& data)
{
return m_Dictionary.SetAtNU(itr, data);
}
virtual BOOL Remove(MYITR itr)
{
return m_Dictionary.Remove(itr);
}
virtual const ENTITY_DATA& GetAtNU(MYITR itr) const
{
return m_Dictionary.GetAtNU(itr);
}
virtual long GetItrList(std::vector<MYITR>& aItr)
{
return m_Dictionary.GetList(aItr);
}
virtual long GetDataList(std::vector<ENTITY_DATA>& aData)
{
return m_Dictionary.GetListData(aData);
}
virtual MYKEY GetNewKey()
{
return m_Dictionary.GetNewKey();
}
public:
virtual MYITR GetDefaultData()
{
ASSERT(g_warning);
return (MYITR)nullptr;
}
virtual void SetDefaultData()
{
ASSERT(g_warning);
}
protected:
MYTYPE m_myType;
CEntityDictionary<ENTITY_DATA> m_Dictionary;
};
}
#endif // !MODULEDATA_DEF
| 16.444444
| 59
| 0.684122
|
heesok2
|
7bb36148ad788f1fa9884d648231660a92519887
| 10,501
|
cpp
|
C++
|
test/jhash_test.cpp
|
MrVoi/ric-plt-xapp-frame-cpp
|
dad910695faf755da932bdbd07430f58718fd910
|
[
"Apache-2.0",
"CC-BY-4.0"
] | 1
|
2021-07-19T21:29:30.000Z
|
2021-07-19T21:29:30.000Z
|
test/jhash_test.cpp
|
MrVoi/ric-plt-xapp-frame-cpp
|
dad910695faf755da932bdbd07430f58718fd910
|
[
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null |
test/jhash_test.cpp
|
MrVoi/ric-plt-xapp-frame-cpp
|
dad910695faf755da932bdbd07430f58718fd910
|
[
"Apache-2.0",
"CC-BY-4.0"
] | 1
|
2022-03-11T02:36:36.000Z
|
2022-03-11T02:36:36.000Z
|
// vim: ts=4 sw=4 noet :
/*
==================================================================================
Copyright (c) 2020 Nokia
Copyright (c) 2020 AT&T Intellectual Property.
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.
==================================================================================
*/
/*
Mnemonic: json_test.cpp
Abstract: Unit test for the json module. This expects that a static json
file exist in the current directory with a known set of fields,
arrays and objects that can be sussed out after parsing. The
expected file is test.json.
Date: 26 June 2020
Author: E. Scott Daniels
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <string>
#include <memory>
/*
Very simple file reader. Reads up to 8k into a single buffer and
returns the buffer as char*. Easier to put json test things in
a file than strings.
*/
static char* read_jstring( char* fname ) {
char* rbuf;
int fd;
int len;
rbuf = (char *) malloc( sizeof( char ) * 8192 );
fd = open( fname, O_RDONLY, 0 );
if( fd < 0 ) {
fprintf( stderr, "<ABORT> can't open test file: %s: %s\n", fname, strerror( errno ) );
exit( 1 );
}
len = read( fd, rbuf, 8190 );
if( len < 0 ) {
close( fd );
fprintf( stderr, "<ABORT> read from file failed: %s: %s\n", fname, strerror( errno ) );
exit( 1 );
}
rbuf[len] = 0;
close( fd );
return rbuf;
}
// this also tests jwrapper.c but that is built as a special object to link in
// rather than including here.
//
#include "../src/json/jhash.hpp"
#include "../src/json/jhash.cpp"
#include "ut_support.cpp"
int main( int argc, char** argv ) {
int errors = 0;
xapp::Jhash* jh;
char* jstr;
std::string sval;
double val;
bool state;
int i;
int len;
int true_count = 0;
set_test_name( "jhash_test" );
jstr = read_jstring( (char *) "test.json" ); // read and parse the json
fprintf( stderr, "read: (%s)\n", jstr );
jh = new xapp::Jhash( jstr );
free( jstr );
if( jh == NULL ) {
fprintf( stderr, "<FAIL> could not parse json string from: test.json\n" );
exit( 1 );
}
sval = jh->String( (char *) "meeting_day" );
fprintf( stderr, "<INFO> sval=(%s)\n", sval.c_str() );
errors += fail_if( sval.compare( "" ) == 0, "did not get meeting day string" );
errors += fail_if( sval.compare( "Tuesday" ) != 0, "meeting day was not expected string" );
sval = jh->String( (char *) "meeting_place" );
fprintf( stderr, "<INFO> sval=(%s)\n", sval.c_str() );
errors += fail_if( sval.compare( "" ) == 0, "did not get meeting place" );
errors += fail_if( sval.compare( "16801 East Green Drive" ) != 0, "meeting place stirng was not correct" );
state = jh->Exists( (char *) "meeting_place" );
errors += fail_if( !state, "test for meeting place exists did not return true" );
state = jh->Exists( (char *) "no-name" );
errors += fail_if( state, "test for non-existant thing returned true" );
state = jh->Is_missing( (char *) "no-name" );
errors += fail_if( !state, "missing test for non-existant thing returned false" );
state = jh->Is_missing( (char *) "meeting_place" );
errors += fail_if( state, "missing test for existing thing returned true" );
val = jh->Value( (char *) "lodge_number" );
errors += fail_if( val != 41.0, "lodge number value was not correct" );
val = jh->Value( (char *) "monthly_dues" );
fprintf( stderr, "<INFO> got dues: %.2f\n", val );
errors += fail_if( val != (double) 43.5, "lodge dues value was not correct" );
len = jh->Array_len( (char *) "members" );
fprintf( stderr, "<INFO> got %d members\n", len );
errors += fail_if( len != 4, "array length was not correct" );
if( len > 0 ) {
for( i = 0; i < len; i++ ) {
if( ! jh->Set_blob_ele( (char *) "members", i ) ) {
errors++;
fprintf( stderr, (char *) "couldn't set blob for element %d\n", i );
} else {
fprintf( stderr, (char *) "<INFO> testing element %d of %d\n", i, len );
state = jh->Is_value( (char *) "age" );
errors += fail_if( !state, "is value test for age returned false" );
state = jh->Is_value( (char *) "married" );
errors += fail_if( state, "is value test for married returned true" );
state = jh->Is_string( (char *) "occupation" );
errors += fail_if( !state, "is string test for spouse returned false" );
state = jh->Is_string( (char *) "married" );
errors += fail_if( state, "is string test for married returned true" );
state = jh->Is_bool( (char *) "married" );
errors += fail_if( !state, "is bool test for married returned false" );
state = jh->Is_bool( (char *) "occupation" );
errors += fail_if( state, "is bool test for spouse returned true" );
val = jh->Value( (char *) "age" );
fprintf( stderr, "<INFO> got age: %.2f\n", (double) val );
errors += fail_if( val < 0, "age value wasn't positive" );
sval = jh->String( (char *) "name" );
fprintf( stderr, "<INFO> sval=(%s)\n", sval.c_str() );
errors += fail_if( sval.compare( "" ) == 0, "no name found in element" );
if( jh->Bool( (char *) "married" ) ) {
true_count++;
}
}
jh->Unset_blob(); // must return to root
}
fprintf( stderr, "<INFO> true count = %d\n", true_count );
errors += fail_if( true_count != 3, "married == true count was not right" );
}
state = jh->Set_blob( (char *) "no-such-thing" );
errors += fail_if( state, "setting blob to non-existant blob returned true" );
state = jh->Set_blob( (char *) "grand_poobah" );
errors += fail_if( !state, "setting blob to existing blob failed" );
if( state ) {
sval = jh->String( (char *) "elected" );
fprintf( stderr, "<INFO> sval=(%s)\n", sval.c_str() );
errors += fail_if( sval != "February 2019", "blob 'elected' didn't return the expected string" );
state = jh->Exists( (char *) "monthly_dues" );
errors += fail_if( state, "blob that shouldn't have a field reports it does" );
jh->Unset_blob( ); // ensure that this is found once we unset to root
state = jh->Exists( (char *) "monthly_dues" );
errors += fail_if( !state, "after rest, root blob, that should have a field, reports it does not" );
}
// ---- test array element value type checks -------------------------------------------------
state = jh->Is_string_ele( (char *) "sponser", 1 );
errors += fail_if( !state, "string element check on sponser failed" );
state = jh->Is_string_ele( (char *) "current_on_dues", 1 );
errors += fail_if( state, "string element check on non-stirng element returned true" );
state = jh->Is_value_ele( (char *) "dues_assistance", 1 );
errors += fail_if( !state, "value element type check on value element reported false" );
state = jh->Is_value_ele( (char *) "current_on_dues", 1 );
errors += fail_if( state, "value element type check on non-value element returned true" );
state = jh->Is_bool_ele( (char *) "current_on_dues", 1 );
errors += fail_if( !state, "string element check on sponser failed" );
state = jh->Is_bool_ele( (char *) "sponser", 1 );
errors += fail_if( state, "string element check on non-stirng element returned true" );
state = jh->Is_null( (char *) "nvt" );
errors += fail_if( !state, "test for nil value returned false" );
state = jh->Is_null( (char *) "lodge_number" );
errors += fail_if( state, "nil test for non-nil value returned true" );
state = jh->Is_null_ele( (char *) "nvat", 0 );
errors += fail_if( !state, "test for nil array element value returned false" );
// ---- test sussing of elements from arrays -------------------------------------------------
sval = jh->String_ele( (char *) "sponser", 1 );
errors += fail_if( sval.compare( "" ) == 0, "get string element failed for sponser (empty string)" );
errors += fail_if( sval.compare( "slate" ) != 0, "get string element failed for sponser (wrong value for[1])" );
sval = jh->String_ele( (char *) "sponser", 0 );
errors += fail_if( sval.compare( "slate" ) != 0, "get string element failed for sponser (wrong value for [0])" );
sval = jh->String_ele( (char *) "sponser", 3 );
errors += fail_if( sval.compare( "brick" ) != 0, "get string element failed for sponser (wrong value for [3])" );
val = jh->Value_ele( (char *) "dues_assistance", 1 );
errors += fail_if( val == 0.0, "get value element for dues_assistance was zero" );
state = jh->Bool_ele( (char *) "current_on_dues", 1 );
errors += fail_if( state, "bool ele test returned true for a false value" );
state = jh->Bool_ele( (char *) "current_on_dues", 0 );
errors += fail_if( !state, "bool ele test returned false for a true value" );
val = jh->Value( (char *) "timestamp" );
fprintf( stderr, "<INFO> timestamp: %.10f\n", val );
jh->Dump(); // for coverage of debug things
// ----- jhashes can be moved, drive that logic for coverage
xapp::Jhash j2( "{}" );
xapp::Jhash j1 = std::move( *jh ); // drives move constructor function
j2 = std::move( j1 ); // drives move operator function
delete jh;
fprintf( stderr, "<INFO> testing for failures; jwrapper error and warning messages expected\n" );
// ---- these shouild all fail to parse, generate warnings to stderr, and drive error handling coverage ----
jh = new xapp::Jhash( (char *) "{ \"bad\": [ [ 1, 2, 3 ], [ 3, 4, 5]] }" ); // drive the exception process for bad json
delete jh;
jh = new xapp::Jhash( (char *) " \"bad\": 5 }" ); // no opening brace
state = jh->Parse_errors();
errors += fail_if( !state, "parse errors check returned false when known errors exist" );
delete jh;
jh = new xapp::Jhash( (char *) "{ \"bad\": fred }" ); // no quotes
delete jh;
jh = new xapp::Jhash( (char *) "{ \"bad: 456, \"good\": 100 }" ); // missing quote; impossible to detect error
jh->Dump(); // but dump should provide details
fprintf( stderr, "<INFO> good value=%d\n", (int) val );
delete jh;
// ---------------------------- end housekeeping ---------------------------
announce_results( errors );
return !!errors;
}
| 36.975352
| 124
| 0.614799
|
MrVoi
|
7bb4eac23f8ec73f6d3b79e9a42265c3740afa8e
| 20,282
|
cpp
|
C++
|
src/binance/wallet.cpp
|
Hsin-Hung/binance_api_cpp
|
1c7662cf0cd682122644dc5819dfe9b88e06b8a6
|
[
"Apache-2.0"
] | 1
|
2022-02-06T17:40:55.000Z
|
2022-02-06T17:40:55.000Z
|
src/binance/wallet.cpp
|
Hsin-Hung/binance_api_cpp
|
1c7662cf0cd682122644dc5819dfe9b88e06b8a6
|
[
"Apache-2.0"
] | null | null | null |
src/binance/wallet.cpp
|
Hsin-Hung/binance_api_cpp
|
1c7662cf0cd682122644dc5819dfe9b88e06b8a6
|
[
"Apache-2.0"
] | 1
|
2022-03-31T07:54:23.000Z
|
2022-03-31T07:54:23.000Z
|
/*
Binance API Wrapper for C++
Copyright (c) 2022 Hsin-Hung <https://github.com/Hsin-Hung>
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 "wallet.h"
#include <ctime>
using namespace Binance;
void Wallet::SystemStatus(json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
std::string url = endpoint + "/sapi/v1/system/status";
SetUpCurlOpt(curl, url, "", std::vector<Header>(), Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::AllCoins(WalletAllCoinsParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/capital/config/getall?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::DailyAccountSnapshot(WalletAccountSnapParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("type", params.type);
query_params.add_new_query("startTime", params.startTime);
query_params.add_new_query("endTime", params.endTime);
query_params.add_new_query("limit", params.limit);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/accountSnapshot?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::DisableFastWithdrawSwitch(WalletFastWithdrawSwitchParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/account/disableFastWithdrawSwitch?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::POST, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::EnableFastWithdrawSwitch(WalletFastWithdrawSwitchParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/account/enableFastWithdrawSwitch?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::POST, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::Withdraw(WalletWithdrawParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("coin", params.coin);
query_params.add_new_query("withdrawOrderId", params.withdrawOrderId);
query_params.add_new_query("network", params.network);
query_params.add_new_query("address", params.address);
query_params.add_new_query("addressTag", params.addressTag);
query_params.add_new_query("amount", params.amount);
query_params.add_new_query("transactionFeeFlag", params.transactionFeeFlag);
query_params.add_new_query("name", params.name);
query_params.add_new_query("walletType", params.walletType);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/capital/withdraw/apply?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::POST, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::DepositHistory(WalletDepositHistoryParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("coin", params.coin);
query_params.add_new_query("status", params.status);
query_params.add_new_query("startTime", params.startTime);
query_params.add_new_query("endTime", params.endTime);
query_params.add_new_query("offset", params.offset);
query_params.add_new_query("limit", params.limit);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/capital/deposit/hisrec?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::WithdrawHistory(WalletWithdrawHistoryParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("coin", params.coin);
query_params.add_new_query("withdrawOrderId", params.withdrawOrderId);
query_params.add_new_query("status", params.status);
query_params.add_new_query("offset", params.offset);
query_params.add_new_query("limit", params.limit);
query_params.add_new_query("startTime", params.startTime);
query_params.add_new_query("endTime", params.endTime);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/capital/withdraw/history?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::DepositAddress(WalletDepositAddressParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("coin", params.coin);
query_params.add_new_query("network", params.network);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/capital/deposit/address?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::AccountStatus(WalletAccountStatusParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/account/status?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::AccountAPITradeStatus(WalletAccountAPITradeStatusParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/account/apiTradingStatus?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::DustLog(WalletDustLogParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("startTime", params.startTime);
query_params.add_new_query("endTime", params.endTime);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/asset/dribblet?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::DustTransfer(WalletDustTransferParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("asset", params.asset);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/asset/dust?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::POST, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::AssetDividendRecord(WalletAssetDividendRecordParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("asset", params.asset);
query_params.add_new_query("startTime", params.startTime);
query_params.add_new_query("endTime", params.endTime);
query_params.add_new_query("limit", params.limit);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/asset/assetDividend?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::AssetDetail(WalletAssetDetailParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("asset", params.asset);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/asset/assetDetail?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::TradeFee(WalletTradeFeeParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("symbol", params.symbol);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/asset/tradeFee?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::UniversalTransfer(WalletUniversalTransferParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("type", get_OrderType(params.type));
query_params.add_new_query("asset", params.asset);
query_params.add_new_query("amount", params.amount);
query_params.add_new_query("fromSymbol", params.fromSymbol);
query_params.add_new_query("toSymbol", params.toSymbol);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/asset/transfer?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::POST, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::QueryUniversalTransfer(WalletQueryUniversalTransferParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("type", get_OrderType(params.type));
query_params.add_new_query("startTime", params.startTime);
query_params.add_new_query("endTime", params.endTime);
query_params.add_new_query("current", params.current);
query_params.add_new_query("size", params.size);
query_params.add_new_query("fromSymbol", params.fromSymbol);
query_params.add_new_query("toSymbol", params.toSymbol);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/asset/transfer?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::Funding(WalletFundingParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("asset", params.asset);
query_params.add_new_query("needBtcValuation", params.needBtcValuation);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/asset/get-funding-asset?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::POST, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::GetAPIKeyPermission(WalletGetAPIKeyPermissionParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/account/apiRestrictions?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
| 33.57947
| 107
| 0.671383
|
Hsin-Hung
|
7bb9222e4be394a7c69581b489375ab5b69c9a15
| 8,253
|
cpp
|
C++
|
Sourcecode/mxtest/core/MusicDataGroupTest.cpp
|
diskzero/MusicXML-Class-Library
|
bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db
|
[
"MIT"
] | null | null | null |
Sourcecode/mxtest/core/MusicDataGroupTest.cpp
|
diskzero/MusicXML-Class-Library
|
bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db
|
[
"MIT"
] | null | null | null |
Sourcecode/mxtest/core/MusicDataGroupTest.cpp
|
diskzero/MusicXML-Class-Library
|
bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db
|
[
"MIT"
] | null | null | null |
// MusicXML Class Library
// Copyright (c) by Matthew James Briggs
// Distributed under the MIT License
#include "mxtest/control/CompileControl.h"
#ifdef MX_COMPILE_CORE_TESTS
#include "cpul/cpulTestHarness.h"
#include "mxtest/core/HelperFunctions.h"
#include "mxtest/core/MusicDataGroupTest.h"
#include "mxtest/core/MusicDataChoiceTest.h"
#include "mxtest/core/NoteTest.h"
#include "mxtest/core/BackupTest.h"
#include "mxtest/core/ForwardTest.h"
#include "mxtest/core/DirectionTest.h"
#include "mxtest/core/PropertiesTest.h"
#include "mxtest/core/HarmonyTest.h"
#include "mxtest/core/FiguredBassTest.h"
#include "mxtest/core/PrintTest.h"
#include "mxtest/core/SoundTest.h"
#include "mxtest/core/BarlineTest.h"
#include "mxtest/core/GroupingTest.h"
using namespace mx::core;
using namespace std;
using namespace mxtest;
TEST( Test01, MusicDataGroup )
{
variant v = variant::one;
MusicDataGroupPtr object = tgenMusicDataGroup( v );
stringstream expected;
tgenMusicDataGroupExpected( expected, 1, v );
stringstream actual;
bool isOneLineOnly;
object->streamContents( actual, 1, isOneLineOnly );
CHECK_EQUAL( expected.str(), actual.str() )
CHECK( ! object->hasAttributes() )
CHECK( ! object->hasContents() )
}
TEST( Test02, MusicDataGroup )
{
variant v = variant::two;
MusicDataGroupPtr object = tgenMusicDataGroup( v );
stringstream expected;
tgenMusicDataGroupExpected( expected, 1, v );
stringstream actual;
bool isOneLineOnly;
object->streamContents( actual, 1, isOneLineOnly );
CHECK_EQUAL( expected.str(), actual.str() )
CHECK( ! object->hasAttributes() )
CHECK( object->hasContents() )
}
TEST( Test03, MusicDataGroup )
{
variant v = variant::three;
MusicDataGroupPtr object = tgenMusicDataGroup( v );
stringstream expected;
tgenMusicDataGroupExpected( expected, 1, v );
stringstream actual;
bool isOneLineOnly;
object->streamContents( actual, 1, isOneLineOnly );
CHECK_EQUAL( expected.str(), actual.str() )
CHECK( ! object->hasAttributes() )
CHECK( object->hasContents() )
}
namespace mxtest
{
MusicDataGroupPtr tgenMusicDataGroup( variant v )
{
MusicDataGroupPtr o = makeMusicDataGroup();
switch ( v )
{
case variant::one:
{
}
break;
case variant::two:
{
/* <xs:element name="note" type="note"/>
<xs:element name="backup" type="backup"/>
<xs:element name="forward" type="forward"/>
<xs:element name="direction" type="direction"/>
<xs:element name="attributes" type="attributes"/>
<xs:element name="harmony" type="harmony"/>
<xs:element name="figured-bass" type="figured-bass"/>
<xs:element name="print" type="print"/>
<xs:element name="sound" type="sound"/>
<xs:element name="barline" type="barline"/>
<xs:element name="grouping" type="grouping"/>
<xs:element name="link" type="link"/>
<xs:element name="bookmark" type="bookmark"/> */
auto x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::note );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::forward );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::properties );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::figuredBass );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::sound );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::grouping );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::bookmark );
o->addMusicDataChoice( x );
x.reset();
}
break;
case variant::three:
{
/* <xs:element name="note" type="note"/>
<xs:element name="backup" type="backup"/>
<xs:element name="forward" type="forward"/>
<xs:element name="direction" type="direction"/>
<xs:element name="attributes" type="attributes"/>
<xs:element name="harmony" type="harmony"/>
<xs:element name="figured-bass" type="figured-bass"/>
<xs:element name="print" type="print"/>
<xs:element name="sound" type="sound"/>
<xs:element name="barline" type="barline"/>
<xs:element name="grouping" type="grouping"/>
<xs:element name="link" type="link"/>
<xs:element name="bookmark" type="bookmark"/> */
auto x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::backup );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::direction );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::harmony );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::print );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::barline );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::link );
o->addMusicDataChoice( x );
x.reset();
}
break;
default:
break;
}
return o;
}
void tgenMusicDataGroupExpected( std::ostream& os, int i, variant v )
{
switch ( v )
{
case variant::one:
{
}
break;
case variant::two:
{
tgenNoteExpected( os, i, v );
os << std::endl;
tgenForwardExpected( os, i, v );
os << std::endl;
tgenPropertiesExpected( os, i, v );
os << std::endl;
tgenFiguredBassExpected( os, i, v );
os << std::endl;
tgenSoundExpected( os, i, v );
os << std::endl;
tgenGroupingExpected( os, i, v );
os << std::endl;
streamLine( os, i, R"(<bookmark id="ID" name="bookmarkStringTwo"/>)", false );
}
break;
case variant::three:
{
tgenBackupExpected( os, i, v );
os << std::endl;
tgenDirectionExpected( os, i, v );
os << std::endl;
tgenHarmonyExpected( os, i, v );
os << std::endl;
tgenPrintExpected( os, i, v );
os << std::endl;
tgenBarlineExpected( os, i, v );
os << std::endl;
streamLine( os, i, R"(<link xlink:href="linkStringThree"/>)", false );
}
break;
default:
break;
}
}
}
#endif
| 35.573276
| 94
| 0.515691
|
diskzero
|
7bb9d944f93d87f4a9c032404c24759ef5e140b6
| 5,320
|
cpp
|
C++
|
tools/unittests/Runtime/ArgmaxTest.cpp
|
jdh8/onnc
|
018ff007e20734585579aac87ca9a573aa012909
|
[
"BSD-3-Clause"
] | 1
|
2021-02-25T13:36:26.000Z
|
2021-02-25T13:36:26.000Z
|
tools/unittests/Runtime/ArgmaxTest.cpp
|
jdh8/onnc
|
018ff007e20734585579aac87ca9a573aa012909
|
[
"BSD-3-Clause"
] | null | null | null |
tools/unittests/Runtime/ArgmaxTest.cpp
|
jdh8/onnc
|
018ff007e20734585579aac87ca9a573aa012909
|
[
"BSD-3-Clause"
] | null | null | null |
#if defined(__GNUC__) || defined(_MSC_VER)
# define restrict __restrict
#else
# define restrict
#endif
extern "C" {
#include <onnc/Runtime/onnc-runtime.h>
}
#undef restrict
#include "norm.hpp"
#include <skypat/skypat.h>
SKYPAT_F(Operator_ArgMax, test_argmax_no_keepdims_example)
{
const float input_0[] = {2.0, 1.0, 3.0, 10.0};
const int32_t input_0_ndim = 2;
const int32_t input_0_dims[] = {2, 2};
float output_0[2];
const int32_t output_0_ndim = 1;
const int32_t output_0_dims[] = {2};
const float answer_0[] = {0, 1};
const int32_t axis = 1;
const int32_t keepdims = 0;
using dragonite::norm;
ONNC_RUNTIME_argmax_float(nullptr, input_0, input_0_ndim, input_0_dims, output_0, output_0_ndim, output_0_dims, axis,
keepdims);
ASSERT_TRUE(norm(answer_0, output_0, 2) <= 1e-5 * norm(answer_0, 2));
}
SKYPAT_F(Operator_ArgMax, test_argmax_no_keepdims_random)
{
const float input_0[] = {7.916196, -5.050213, -6.5481505, -2.372179, 3.4055011, -5.259473, -5.876902, 9.181546,
3.8622417, 3.1683996, -4.334476, -7.461097, 8.506922, 5.0490994, 7.3549848, 0.19403115,
9.845381, 4.322886, 8.492865, -3.9024255, -3.6774218, -7.866902, 9.484194, 4.339801};
const int32_t input_0_ndim = 3;
const int32_t input_0_dims[] = {2, 3, 4};
float output_0[8];
const int32_t output_0_ndim = 2;
const int32_t output_0_dims[] = {2, 4};
const float answer_0[] = {0, 2, 2, 1, 1, 0, 2, 2};
const int32_t axis = 1;
const int32_t keepdims = 0;
using dragonite::norm;
ONNC_RUNTIME_argmax_float(nullptr, input_0, input_0_ndim, input_0_dims, output_0, output_0_ndim, output_0_dims, axis,
keepdims);
ASSERT_TRUE(norm(answer_0, output_0, 8) <= 1e-5 * norm(answer_0, 8));
}
SKYPAT_F(Operator_ArgMax, test_argmax_keepdims_example)
{
const float input_0[] = {2.0, 1.0, 3.0, 10.0};
const int32_t input_0_ndim = 2;
const int32_t input_0_dims[] = {2, 2};
float output_0[2];
const int32_t output_0_ndim = 2;
const int32_t output_0_dims[] = {2, 1};
const float answer_0[] = {0, 1};
const int32_t axis = 1;
const int32_t keepdims = 1;
using dragonite::norm;
ONNC_RUNTIME_argmax_float(nullptr, input_0, input_0_ndim, input_0_dims, output_0, output_0_ndim, output_0_dims, axis,
keepdims);
ASSERT_TRUE(norm(answer_0, output_0, 2) <= 1e-5 * norm(answer_0, 2));
}
SKYPAT_F(Operator_ArgMax, test_argmax_keepdims_random)
{
const float input_0[] = {-2.8666658, -9.930011, 8.533137, 9.542501, 2.6286595, 6.1863194, 0.39168122, 3.0457706,
-8.771415, 9.400704, 1.3585372, -1.9816046, -0.8143469, -2.7263594, -8.583799, -5.656237,
7.053225, 7.5800247, -9.178458, 2.4859655, 0.41899338, 5.0151973, -4.177078, -8.727053};
const int32_t input_0_ndim = 3;
const int32_t input_0_dims[] = {2, 3, 4};
float output_0[8];
const int32_t output_0_ndim = 3;
const int32_t output_0_dims[] = {2, 1, 4};
const float answer_0[] = {1, 2, 0, 0, 1, 1, 2, 1};
const int32_t axis = 1;
const int32_t keepdims = 1;
using dragonite::norm;
ONNC_RUNTIME_argmax_float(nullptr, input_0, input_0_ndim, input_0_dims, output_0, output_0_ndim, output_0_dims, axis,
keepdims);
ASSERT_TRUE(norm(answer_0, output_0, 8) <= 1e-5 * norm(answer_0, 8));
}
SKYPAT_F(Operator_ArgMax, test_argmax_default_axis_example)
{
const float input_0[] = {2.0, 1.0, 3.0, 10.0};
const int32_t input_0_ndim = 2;
const int32_t input_0_dims[] = {2, 2};
float output_0[2];
const int32_t output_0_ndim = 2;
const int32_t output_0_dims[] = {1, 2};
const float answer_0[] = {1, 1};
const int32_t keepdims = 1;
const int32_t axis = 0;
using dragonite::norm;
ONNC_RUNTIME_argmax_float(nullptr, input_0, input_0_ndim, input_0_dims, output_0, output_0_ndim, output_0_dims, axis,
keepdims);
ASSERT_TRUE(norm(answer_0, output_0, 2) <= 1e-5 * norm(answer_0, 2));
}
SKYPAT_F(Operator_ArgMax, test_argmax_default_axis_random)
{
const float input_0[] = {-9.826185, -7.196741, 7.7552886, -7.4781475, -1.815236, -5.1710205,
3.1197412, -5.936099, 9.407172, 1.4273096, -1.4433477, -7.499204,
0.024073577, -6.7123213, 8.195043, -6.8797135, -7.130009, -9.179616,
-2.3986602, 9.803744, 5.5405087, -0.44200945, -1.0355306, -2.874489};
const int32_t input_0_ndim = 3;
const int32_t input_0_dims[] = {2, 3, 4};
float output_0[12];
const int32_t output_0_ndim = 3;
const int32_t output_0_dims[] = {1, 3, 4};
const float answer_0[] = {1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1};
const int32_t keepdims = 1;
const int32_t axis = 0;
using dragonite::norm;
ONNC_RUNTIME_argmax_float(nullptr, input_0, input_0_ndim, input_0_dims, output_0, output_0_ndim, output_0_dims, axis,
keepdims);
ASSERT_TRUE(norm(answer_0, output_0, 12) <= 1e-5 * norm(answer_0, 12));
}
| 41.24031
| 120
| 0.618233
|
jdh8
|
7bba4af1cef957d08f16b1d9a35229cdbbf47e4a
| 1,755
|
cc
|
C++
|
servlib/bundling/ForwardingInfo.cc
|
delay-tolerant-networking/DTN2
|
1c12a9dea32c5cbae8c46db105012a2031f4161e
|
[
"Apache-2.0"
] | 14
|
2016-06-27T19:28:23.000Z
|
2021-06-28T20:41:17.000Z
|
servlib/bundling/ForwardingInfo.cc
|
delay-tolerant-networking/DTN2
|
1c12a9dea32c5cbae8c46db105012a2031f4161e
|
[
"Apache-2.0"
] | 3
|
2020-09-18T13:48:53.000Z
|
2021-05-27T18:28:14.000Z
|
servlib/bundling/ForwardingInfo.cc
|
lauramazzuca21/DTNME
|
c97b598b09a8c8e97c2e4136879d9f0e157c8df7
|
[
"Apache-2.0"
] | 10
|
2020-09-26T05:08:40.000Z
|
2022-01-25T12:57:55.000Z
|
/*
* Copyright 2006-2007 The MITRE Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* The US Government will not be charged any license fee and/or royalties
* related to this software. Neither name of The MITRE Corporation; nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*/
#ifdef HAVE_CONFIG_H
# include <dtn-config.h>
#endif
#include "ForwardingInfo.h"
#include "bundling/BundleDaemon.h"
#include "contacts/ContactManager.h"
namespace dtn {
void
ForwardingInfo::serialize(oasys::SerializeAction *a)
{
a->process("state", &state_);
a->process("action", &action_);
a->process("link_name", &link_name_);
a->process("regid", ®id_);
a->process("remote_eid", &remote_eid_);
a->process("timestamp_sec", ×tamp_.sec_);
a->process("timestamp_usec", ×tamp_.usec_);
if(a->action_code() == oasys::Serialize::UNMARSHAL) {
if(state_ == QUEUED && !BundleDaemon::instance()->contactmgr()->has_link(link_name_.c_str())) {
state_ = TRANSMIT_FAILED;
timestamp_.get_time();
}
}
}
} // namespace dtn
| 34.411765
| 103
| 0.688319
|
delay-tolerant-networking
|
7bbc2d3f991fedd2498b0bab564e00a59c5e82d6
| 3,303
|
cpp
|
C++
|
test/PAGFontTest.cpp
|
henryzt/libpag
|
9d3bb92a5a90240615884ff7f8afc3ea6c34d7a1
|
[
"BSL-1.0",
"CC0-1.0",
"MIT"
] | 1
|
2022-02-15T03:04:01.000Z
|
2022-02-15T03:04:01.000Z
|
test/PAGFontTest.cpp
|
henryzt/libpag
|
9d3bb92a5a90240615884ff7f8afc3ea6c34d7a1
|
[
"BSL-1.0",
"CC0-1.0",
"MIT"
] | null | null | null |
test/PAGFontTest.cpp
|
henryzt/libpag
|
9d3bb92a5a90240615884ff7f8afc3ea6c34d7a1
|
[
"BSL-1.0",
"CC0-1.0",
"MIT"
] | null | null | null |
/////////////////////////////////////////////////////////////////////////////////////////////////
//
// Tencent is pleased to support the open source community by making libpag available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// unless required by applicable law or agreed to in writing, software distributed under the
// license is distributed on an "as is" basis, without warranties or conditions of any kind,
// either express or implied. see the license for the specific language governing permissions
// and limitations under the license.
//
/////////////////////////////////////////////////////////////////////////////////////////////////
#include <fstream>
#include <vector>
#include "base/utils/TimeUtil.h"
#include "framework/pag_test.h"
#include "framework/utils/PAGTestUtils.h"
#include "nlohmann/json.hpp"
namespace pag {
using nlohmann::json;
/**
* 用例描述: 字体相关功能测试
*/
PAG_TEST(PAGFontTest, TestFont) {
json dumpJson;
json compareJson;
std::ifstream inputFile("../test/res/compare_font_md5.json");
bool needCompare = false;
if (inputFile) {
needCompare = true;
inputFile >> compareJson;
}
std::vector<std::string> compareVector;
std::string fileName = "test_font";
if (needCompare && compareJson.contains(fileName) && compareJson[fileName].is_array()) {
compareVector = compareJson[fileName].get<std::vector<std::string>>();
}
PAGFont::RegisterFont("../resources/font/NotoSerifSC-Regular.otf", 0, "TTTGBMedium", "Regular");
auto TestPAGFile = PAGFile::Load("../resources/apitest/test_font.pag");
ASSERT_NE(TestPAGFile, nullptr);
auto pagSurface = PAGSurface::MakeOffscreen(TestPAGFile->width(), TestPAGFile->height());
ASSERT_NE(pagSurface, nullptr);
auto pagPlayer = std::make_shared<PAGPlayer>();
pagPlayer->setSurface(pagSurface);
pagPlayer->setComposition(TestPAGFile);
Frame totalFrames = TimeToFrame(TestPAGFile->duration(), TestPAGFile->frameRate());
Frame currentFrame = 0;
std::vector<std::string> md5Vector;
std::string errorMsg;
bool status = true;
while (currentFrame < totalFrames) {
//添加0.1帧目的是保证progress不会由于精度问题帧数计算错误,frame应该使用totalFrames作为总体帧数。因为对于file来说总时长为[0,totalFrames],对应于[0,1],因此归一化时,分母应该为totalFrames
pagPlayer->setProgress((currentFrame + 0.1) * 1.0 / totalFrames);
pagPlayer->flush();
auto skImage = MakeSnapshot(pagSurface);
std::string md5 = DumpMD5(skImage);
md5Vector.push_back(md5);
if (needCompare && compareVector[currentFrame] != md5) {
errorMsg += (std::to_string(currentFrame) + ";");
if (status) {
std::string imagePath =
"../test/out/" + fileName + "_" + std::to_string(currentFrame) + ".png";
Trace(skImage, imagePath);
status = false;
}
}
currentFrame++;
}
EXPECT_EQ(errorMsg, "") << fileName << " frame fail";
dumpJson[fileName] = md5Vector;
std::ofstream outFile("../test/out/compare_font_md5.json");
outFile << std::setw(4) << dumpJson << std::endl;
outFile.close();
}
} // namespace pag
| 35.902174
| 129
| 0.659098
|
henryzt
|
7bc678974e45c20f132531188608fd8281d719b1
| 6,182
|
hpp
|
C++
|
Source/Terrain/TerrainConstructionData.hpp
|
storm20200/UniversitySecondYearTerrain
|
4455f9804e165202839fdd05f660f6a9bbc999eb
|
[
"MIT"
] | 2
|
2016-06-05T04:52:35.000Z
|
2016-07-10T04:18:04.000Z
|
Source/Terrain/TerrainConstructionData.hpp
|
storm20200/University3DGraphicsTerrain
|
4455f9804e165202839fdd05f660f6a9bbc999eb
|
[
"MIT"
] | null | null | null |
Source/Terrain/TerrainConstructionData.hpp
|
storm20200/University3DGraphicsTerrain
|
4455f9804e165202839fdd05f660f6a9bbc999eb
|
[
"MIT"
] | null | null | null |
#ifndef TERRAIN_CONSTRUCTION_DATA_3GP_HPP
#define TERRAIN_CONSTRUCTION_DATA_3GP_HPP
// Personal headers.
#include <Terrain/Terrain.hpp>
/// <summary>
/// A structure containing all the information required to generate terrain elements and vertices.
/// </summary>
class Terrain::ConstructionData final
{
public:
/////////////////////////////////
// Constructors and destructor //
/////////////////////////////////
/// <summary> Constructs a Terrain::ConstructionData object with the given dimensions. </summary>
/// <parma name="width"> How many vertices wide should the terrain be? </param>
/// <param name="depth"> How many vertices deep should the terrain be? </param>
/// <param name="divisor"> What will the terrain dimensions be subdivided by? </param>
/// <param name="worldWidth"> How many world units wide is the terrain? </param>
/// <param name="worldDepth"> How many world units deep is the terrain? </param>
ConstructionData (const unsigned int width, const unsigned int depth, const unsigned int divisor,
const float worldWidth, const float worldDepth);
ConstructionData (ConstructionData&& move);
ConstructionData& operator= (ConstructionData&& move);
ConstructionData() = default;
ConstructionData (const ConstructionData& copy) = default;
ConstructionData& operator= (const ConstructionData& copy) = default;
~ConstructionData() = default;
//////////////////////
// Public interface //
//////////////////////
/// <summary> Causes all stored values to be recalculated from different values. </summary>
/// <parma name="width"> How many vertices wide should the terrain be? </param>
/// <param name="depth"> How many vertices deep should the terrain be? </param>
/// <param name="divisor"> What will the terrain dimensions be subdivided by? </param>
/// <param name="worldWidth"> How many world units wide is the terrain? </param>
/// <param name="worldDepth"> How many world units deep is the terrain? </param>
void recalculate (const unsigned int width, const unsigned int depth, const unsigned int divisor,
const float worldWidth, const float worldDepth);
/// <summary> Gets the width of the terrain. </summary>
/// <returns> How many vertices wide the terrain should be. </returns>
unsigned int getWidth() const { return m_width; }
/// <summary> Gets the depth of the terrain. </summary>
/// <returns> How many vertices deep the terrain should be. </returns>
unsigned int getDepth() const { return m_depth; }
/// <summary> Gets the total number of vertices for the terrain. </summary>
/// <returns> How many total vertices the terrain should be. </returns>
unsigned int getVertexCount() const { return m_vertexCount; }
/// <summary> Gets the divisor of the terrain. </summary>
/// <returns> How many vertices wide and deep terrain patches should be. </returns>
unsigned int getDivisor() const { return m_divisor; }
/// <summary> Gets the number of vertices per segment. </summary>
/// <returns> The amount of vertices that make up a segment of terrain. </returns>
unsigned int getMeshVertices() const { return m_meshVertices; }
/// <summary> Gets the mesh width of the terrain </summary>
/// <returns> How many meshes wide the terrain should be. </returns>
unsigned int getMeshCountX() const { return m_meshCountX; }
/// <summary> Gets the mesh depth of the terrain. </summary>
/// <returns> How many meshes deep the terrain should be. </returns>
unsigned int getMeshCountZ() const { return m_meshCountZ; }
/// <summary> Gets the total number of meshes of the terrain. </summary>
/// <returns> How many total meshes there should be. </returns>
unsigned int getMeshTotal() const { return m_meshTotal; }
/// <summary> Gets the width of the terrain in world units. </summary>
/// <returns> The width of the terrain in world units. </returns>
float getWorldWidth() const { return m_worldWidth; }
/// <summary> Gets the depth of the terrain in world units. </summary>
/// <returns> The depth of the terrain in world units. </returns>
float getWorldDepth() const { return m_worldDepth; }
/// <summary> Gets the area of the terrain in world units. </summary>
/// <returns> The width of the terrain in world units. </returns>
float getWorldArea() const { return m_worldArea; }
private:
///////////////////
// Internal data //
///////////////////
unsigned int m_width { 0 }; //!< How many vertices wide should the terrain be?
unsigned int m_depth { 0 }; //!< How many vertices deep should the terrain be?
unsigned int m_vertexCount { 0 }; //!< The total number of vertices that make up the terrain.
unsigned int m_divisor { 0 }; //!< The width and depth of each terrain partition.
unsigned int m_meshVertices { 0 }; //!< How many vertices make up a segment of terrain.
unsigned int m_meshCountX { 0 }; //!< How many meshes wide the terrain is.
unsigned int m_meshCountZ { 0 }; //!< How many meshes deep the terrain is.
unsigned int m_meshTotal { 0 }; //!< How many total meshes will there be when the terrain is completed.
float m_worldWidth { 0.f }; //!< How many world units wide is the terrain?
float m_worldDepth { 0.f }; //!< How many world units deep is the terrain?
float m_worldArea { 0.f }; //!< The total area of the terrain in world units.
};
#endif // TERRAIN_CONSTRUCTION_DATA_3GP_HPP
| 52.837607
| 119
| 0.602232
|
storm20200
|
0d00a7b0316dc482655c9c851accaecb555a66bd
| 12,255
|
hpp
|
C++
|
DT3Windows8/DeviceGraphicsDX11Material.hpp
|
9heart/DT3
|
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
|
[
"MIT"
] | 3
|
2016-01-27T13:17:18.000Z
|
2019-03-19T09:18:25.000Z
|
DT3Windows8/DeviceGraphicsDX11Material.hpp
|
pakoito/DT3
|
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
|
[
"MIT"
] | 1
|
2016-01-28T14:39:49.000Z
|
2016-01-28T22:12:07.000Z
|
DT3Windows8/DeviceGraphicsDX11Material.hpp
|
adderly/DT3
|
e2605be091ec903d3582e182313837cbaf790857
|
[
"MIT"
] | 3
|
2016-01-25T16:44:51.000Z
|
2021-01-29T19:59:45.000Z
|
#ifndef DT2_DEVICEGRAPHICSDX11MATERIAL
#define DT2_DEVICEGRAPHICSDX11MATERIAL
//==============================================================================
///
/// File: DeviceGraphicsDX11Material.hpp
///
/// Copyright (C) 2000-2013 by Smells Like Donkey, Inc. All rights reserved.
///
/// This file is subject to the terms and conditions defined in
/// file 'LICENSE.txt', which is part of this source code package.
///
//==============================================================================
#include "pch.h"
#include "BaseClass.hpp"
#include "TextureResource.hpp"
#include "Color.hpp"
#include "Vector.hpp"
#include "Matrix.hpp"
//==============================================================================
/// Namespace
//==============================================================================
namespace DT2 {
//==============================================================================
/// Forward declarations
//==============================================================================
class MaterialResource;
class ShaderResource;
//==============================================================================
/// Class
//==============================================================================
class DeviceGraphicsDX11MaterialTexture {
public:
DEFINE_TYPE_SIMPLE_BASE(DeviceGraphicsDX11MaterialTexture)
DeviceGraphicsDX11MaterialTexture (void);
~DeviceGraphicsDX11MaterialTexture (void);
public:
TextureResource* _texture;
DTuint _wrap_mode_s;
DTuint _wrap_mode_t;
DTuint _wrap_mode_r;
DTuint _filter_mode;
Vector3 _scroll;
DTfloat _rotation;
Vector3 _scale;
Vector3 _pre_translate;
Vector3 _post_translate;
Matrix4 _texture_matrix;
ID3D11SamplerState *_sampler_state;
};
//==============================================================================
/// Class
//==============================================================================
class DeviceGraphicsDX11MaterialState {
public:
DEFINE_TYPE_SIMPLE_BASE(DeviceGraphicsDX11MaterialState)
DeviceGraphicsDX11MaterialState (void);
~DeviceGraphicsDX11MaterialState (void);
public:
DTboolean _blending_enabled;
DTuint _blending_src;
DTuint _blending_dst;
DTuint _blending_alpha_src;
DTuint _blending_alpha_dst;
DTboolean _color_mask_r;
DTboolean _color_mask_g;
DTboolean _color_mask_b;
DTboolean _color_mask_a;
DTboolean _depth_test_enabled;
DTint _depth_func;
DTboolean _depth_mask;
DTboolean _culling_enabled;
DTint _cull_face;
DTboolean _stencil_test_enabled;
DTuint _stencil_mask;
DTint _stencil_func;
DTuint _stencil_bit_mask;
DTint _stencil_front_sfail;
DTint _stencil_front_dpfail;
DTint _stencil_front_dppass;
DTint _stencil_back_sfail;
DTint _stencil_back_dpfail;
DTint _stencil_back_dppass;
Color _color;
ShaderResource *_shader;
ID3D11DepthStencilState *_depth_stencil_state;
ID3D11BlendState *_blend_state;
ID3D11RasterizerState *_rasterizer_state;
DeviceGraphicsDX11MaterialTexture _textures[8];
ID3D11ShaderResourceView *_textures_state[D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT];
ID3D11SamplerState *_samplers_state[D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT];
};
//==============================================================================
/// Class
//==============================================================================
class DeviceGraphicsDX11Material: public BaseClass {
public:
DEFINE_TYPE(DeviceGraphicsDX11Material,BaseClass)
DEFINE_CREATE
DeviceGraphicsDX11Material (void);
private:
DeviceGraphicsDX11Material (const DeviceGraphicsDX11Material &rhs);
DeviceGraphicsDX11Material & operator = (const DeviceGraphicsDX11Material &rhs);
public:
virtual ~DeviceGraphicsDX11Material (void);
public:
/// Description
/// \param param description
/// \return description
void syncToResource (MaterialResource *material);
/// Description
/// \param param description
/// \return description
void activateMaterial (void);
// Blending
DEFINE_ACCESSORS(getBlending, setBlending, DTboolean, _current_state._blending_enabled)
DEFINE_ACCESSORS(getBlendFuncSrc, setBlendFuncSrc, DTint, _current_state._blending_src)
DEFINE_ACCESSORS(getBlendFuncDst, setBlendFuncDst, DTint, _current_state._blending_dst)
DEFINE_ACCESSORS(getAlphaBlendFuncSrc, setAlphaBlendFuncSrc, DTint, _current_state._blending_alpha_src)
DEFINE_ACCESSORS(getAlphaBlendFuncDst, setAlphaBlendFuncDst, DTint, _current_state._blending_alpha_dst)
DEFINE_ACCESSORS(getColorMaskR, setColorMaskR, DTboolean, _current_state._color_mask_r)
DEFINE_ACCESSORS(getColorMaskG, setColorMaskG, DTboolean, _current_state._color_mask_g)
DEFINE_ACCESSORS(getColorMaskB, setColorMaskB, DTboolean, _current_state._color_mask_b)
DEFINE_ACCESSORS(getColorMaskA, setColorMaskA, DTboolean, _current_state._color_mask_a)
// Depth
DEFINE_ACCESSORS(getDepthMask, setDepthMask, DTboolean, _current_state._depth_mask)
DEFINE_ACCESSORS(getDepthTest, setDepthTest, DTboolean, _current_state._depth_test_enabled)
DEFINE_ACCESSORS(getDepthFunc, setDepthFunc, DTint, _current_state._depth_func)
// Culling
DEFINE_ACCESSORS(getCulling, setCulling, DTboolean, _current_state._culling_enabled)
DEFINE_ACCESSORS(getCullFace, setCullFace, DTint, _current_state._cull_face)
// Stenciling
DEFINE_ACCESSORS(getStencilTest, setStencilTest, DTboolean, _current_state._stencil_test_enabled)
DEFINE_ACCESSORS(getStencilMask, setStencilMask, DTuint, _current_state._stencil_mask)
DEFINE_ACCESSORS(getStencilFunc, setStencilFunc, DTint, _current_state._stencil_func)
DEFINE_ACCESSORS(getStencilBitMask, setStencilBitMask, DTuint, _current_state._stencil_bit_mask)
DEFINE_ACCESSORS(getStencilFrontsFail, setStencilFrontsFail, DTint, _current_state._stencil_front_sfail)
DEFINE_ACCESSORS(getStencilFrontdpFail, setStencilFrontdpFail, DTint, _current_state._stencil_front_dpfail)
DEFINE_ACCESSORS(getStencilFrontdpPass, setStencilFrontdpPass, DTint, _current_state._stencil_front_dppass)
DEFINE_ACCESSORS(getStencilBacksFail, setStencilBacksFail, DTint, _current_state._stencil_back_sfail)
DEFINE_ACCESSORS(getStencilBackdpFail, setStencilBackdpFail, DTint, _current_state._stencil_back_dpfail)
DEFINE_ACCESSORS(getStencilBackdpPass, setStencilBackdpPass, DTint, _current_state._stencil_back_dppass)
// Color
DEFINE_ACCESSORS(getColor, setColor, Color, _current_state._color)
/// Description
/// \param param description
/// \return description
void setShader (ShaderResource *p);
/// Description
/// \param param description
/// \return description
ShaderResource*& getShader (void) { return _current_state._shader; }
/// Description
/// \param param description
/// \return description
void setTex (TextureResource *tex);
/// Description
/// \param param description
/// \return description
TextureResource* getTex (void) const;
/// Description
/// \param param description
/// \return description
void setScroll (const Vector3 &scroll) { _current_state._textures[_unit]._scroll = scroll; }
/// Description
/// \param param description
/// \return description
Vector3 getScroll (void) const { return _current_state._textures[_unit]._scroll; }
/// Description
/// \param param description
/// \return description
void setPreTranslate (const Vector3 &translate) { _current_state._textures[_unit]._pre_translate = translate; }
/// Description
/// \param param description
/// \return description
Vector3 getPreTranslate (void) const { return _current_state._textures[_unit]._pre_translate; }
/// Description
/// \param param description
/// \return description
void setPostTranslate (const Vector3 &translate) { _current_state._textures[_unit]._post_translate = translate; }
/// Description
/// \param param description
/// \return description
Vector3 getPostTranslate (void) const { return _current_state._textures[_unit]._post_translate; }
/// Description
/// \param param description
/// \return description
void setRotation (const DTfloat rotation) { _current_state._textures[_unit]._rotation = rotation; }
/// Description
/// \param param description
/// \return description
DTfloat getRotation (void) const { return _current_state._textures[_unit]._rotation; }
/// Description
/// \param param description
/// \return description
void setScale (const Vector3 &scale) { _current_state._textures[_unit]._scale = scale; }
/// Description
/// \param param description
/// \return description
Vector3 getScale (void) const { return _current_state._textures[_unit]._scale; }
/// Description
/// \param param description
/// \return description
const Matrix4& getTextureMatrix (void) const { return _current_state._textures[_unit]._texture_matrix; }
/// Description
/// \param param description
/// \return description
void setWrapS (DTuint wrap_mode_s) { _current_state._textures[_unit]._wrap_mode_s = wrap_mode_s; }
/// Description
/// \param param description
/// \return description
DTuint getWrapS (void) const { return _current_state._textures[_unit]._wrap_mode_s; }
/// Description
/// \param param description
/// \return description
void setWrapT (DTuint wrap_mode_t) { _current_state._textures[_unit]._wrap_mode_t = wrap_mode_t; }
/// Description
/// \param param description
/// \return description
DTuint getWrapT (void) const { return _current_state._textures[_unit]._wrap_mode_t; }
/// Description
/// \param param description
/// \return description
void setWrapR (DTuint wrap_mode_r) { _current_state._textures[_unit]._wrap_mode_r = wrap_mode_r; }
/// Description
/// \param param description
/// \return description
DTuint getWrapR (void) const { return _current_state._textures[_unit]._wrap_mode_r; }
/// Description
/// \param param description
/// \return description
void setFilter (DTuint filter_mode) { _current_state._textures[_unit]._filter_mode = filter_mode; }
/// Description
/// \param param description
/// \return description
DTuint getFilter (void) const { return _current_state._textures[_unit]._filter_mode; }
/// Description
/// \param param description
/// \return description
void setMode (DTint mode) {}
/// Description
/// \param param description
/// \return description
DTint getMode (void) const { return 0; }
/// Description
/// \param param description
/// \return description
void setCurrentUnit (const DTuint unit) { _unit = unit; }
private:
DTuint _unit;
DeviceGraphicsDX11MaterialState _current_state;
void syncTexture (DTuint unit);
};
//==============================================================================
//==============================================================================
} // DT2
#endif
| 35.938416
| 125
| 0.616157
|
9heart
|
0d030c0917640d62afef953096945e7e1dedf137
| 1,432
|
cpp
|
C++
|
Codechef_Long_Chalenge_2021/shortestPath.cpp
|
AkashKumarSingh11032001/Coding-Challenge-Solutions
|
c46b5d466b1403b8e58b6ac9081298d617ad8611
|
[
"MIT"
] | null | null | null |
Codechef_Long_Chalenge_2021/shortestPath.cpp
|
AkashKumarSingh11032001/Coding-Challenge-Solutions
|
c46b5d466b1403b8e58b6ac9081298d617ad8611
|
[
"MIT"
] | null | null | null |
Codechef_Long_Chalenge_2021/shortestPath.cpp
|
AkashKumarSingh11032001/Coding-Challenge-Solutions
|
c46b5d466b1403b8e58b6ac9081298d617ad8611
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
#define maxn 3E5 + 5
void solve()
{
int n, m;
cin >> n >> m;
int a[n];
int b[m];
int i, j;
for (i = 0; i < n; i++)
{
cin >> a[i];
}
for (i = 0; i < m; i++)
{
cin >> b[i];
}
int max_i = maxn;
int rough[n];
int low = -1, high = -1;
for (i = 0; i < n; i++)
{
if (i == 0)
{
rough[i] = 0;
}
else if (a[i] != 0)
{
rough[i] = 0;
}
else
{
rough[i] = max_i;
}
}
for (i = 0; i < n; i++)
{
if (a[i] == 1)
{
high = i;
}
if (high != -1)
{
if (a[i] == 0)
{
rough[i] = min(rough[i], i - high);
}
}
}
for (i = n - 1; i >= 0; i--)
{
if (a[i] == 2)
{
low = i;
}
if (low != -1)
{
if (a[i] == 0)
{
rough[i] = min(rough[i], low - i);
}
}
}
for (i = 0; i < m; i++)
{
j = b[i] - 1;
if (rough[j] != max_i)
{
cout << rough[j] << " ";
}
else
{
cout << -1 << " ";
}
}
cout << endl;
}
int main()
{
int test;
cin >> test;
while (test--)
{
solve();
}
}
| 16.45977
| 51
| 0.261872
|
AkashKumarSingh11032001
|
0d040c97e20584697571dd9a08d3888e732af4b9
| 444
|
cpp
|
C++
|
CompetitiveProgramming/Exercise2.2.1/5-LongestContiguousSubArray.cpp
|
omarcespedes/algorithms-cpp
|
5c66e41d0f4080ccd2c384ff9658ceb721545b19
|
[
"MIT"
] | null | null | null |
CompetitiveProgramming/Exercise2.2.1/5-LongestContiguousSubArray.cpp
|
omarcespedes/algorithms-cpp
|
5c66e41d0f4080ccd2c384ff9658ceb721545b19
|
[
"MIT"
] | null | null | null |
CompetitiveProgramming/Exercise2.2.1/5-LongestContiguousSubArray.cpp
|
omarcespedes/algorithms-cpp
|
5c66e41d0f4080ccd2c384ff9658ceb721545b19
|
[
"MIT"
] | null | null | null |
//increasing
#include <iostream>
using namespace std;
#define N 12
int arr[N] = {12, 13, 14, 15, 4, 7, 8, 1, 10, 11,25,26};
int main(){
int max = 1, len = 1;
for(int i = 1 ; i < N ; i++) {
if(arr[i] > arr[i-1]) {
len++;
} else {
if(len > max) {
max = len;
}
len = 1;
}
}
if(len > max) max = len;
cout << max << endl;
return 0;
}
| 17.76
| 56
| 0.394144
|
omarcespedes
|
0d0438ec54dbbc75f365e7d3a351ed9b2661df27
| 4,453
|
cpp
|
C++
|
test/integration_tests/src/config.cpp
|
Paycasso/cpp-driver
|
9e6efd4842afc226d999baf890a55275e7e94cf8
|
[
"Apache-2.0"
] | null | null | null |
test/integration_tests/src/config.cpp
|
Paycasso/cpp-driver
|
9e6efd4842afc226d999baf890a55275e7e94cf8
|
[
"Apache-2.0"
] | null | null | null |
test/integration_tests/src/config.cpp
|
Paycasso/cpp-driver
|
9e6efd4842afc226d999baf890a55275e7e94cf8
|
[
"Apache-2.0"
] | null | null | null |
#define BOOST_TEST_DYN_LINK
#ifdef STAND_ALONE
# define BOOST_TEST_MODULE cassandra
#endif
#include <boost/test/unit_test.hpp>
#include "cassandra.h"
#include "test_utils.hpp"
struct ConfigTests {
ConfigTests() { }
};
BOOST_FIXTURE_TEST_SUITE(config, ConfigTests)
BOOST_AUTO_TEST_CASE(test_options)
{
test_utils::CassClusterPtr cluster(cass_cluster_new());
{
cass_size_t data_length;
cass_size_t connect_timeout = 9999;
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONNECT_TIMEOUT, &connect_timeout, sizeof(connect_timeout));
cass_size_t connect_timeout_out = 0;
data_length = sizeof(connect_timeout_out);
cass_cluster_getopt(cluster.get(), CASS_OPTION_CONNECT_TIMEOUT, &connect_timeout_out, &data_length);
BOOST_REQUIRE(connect_timeout == connect_timeout_out && data_length == sizeof(connect_timeout_out));
}
{
cass_size_t data_length;
cass_int32_t port = 7000;
cass_cluster_setopt(cluster.get(), CASS_OPTION_PORT, &port, sizeof(port));
cass_int32_t port_out = 0;
data_length = sizeof(port_out);
cass_cluster_getopt(cluster.get(), CASS_OPTION_PORT, &port_out, &data_length);
BOOST_REQUIRE(port == port_out && data_length == sizeof(port_out));
}
}
BOOST_AUTO_TEST_CASE(test_invalid)
{
test_utils::CassClusterPtr cluster(cass_cluster_new());
cass_size_t temp = 0;
BOOST_REQUIRE(cass_cluster_setopt(cluster.get(), CASS_OPTION_CONNECT_TIMEOUT, &temp, sizeof(temp) - 1) == CASS_ERROR_LIB_INVALID_OPTION_SIZE);
cass_size_t temp_out = 0;
cass_size_t temp_out_size = sizeof(temp_out) - 1;
BOOST_REQUIRE(cass_cluster_getopt(cluster.get(), CASS_OPTION_CONNECT_TIMEOUT, &temp_out, &temp_out_size) == CASS_ERROR_LIB_INVALID_OPTION_SIZE);
}
BOOST_AUTO_TEST_CASE(test_contact_points)
{
char buffer[1024];
cass_size_t buffer_size;
test_utils::CassClusterPtr cluster(cass_cluster_new());
// Simple
const char* contact_points1 = "127.0.0.1,127.0.0.2,127.0.0.3";
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, contact_points1, strlen(contact_points1));
buffer_size = sizeof(buffer);
cass_cluster_getopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, buffer, &buffer_size);
BOOST_REQUIRE(strcmp(contact_points1, buffer) == 0);
// Clear
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, "", 0);
buffer_size = sizeof(buffer);
cass_cluster_getopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, buffer, &buffer_size);
BOOST_REQUIRE(buffer_size == 0);
// Extra commas
const char* contact_points1_commas = ",,,,127.0.0.1,,,,127.0.0.2,127.0.0.3,,,,";
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, contact_points1_commas, strlen(contact_points1_commas));
buffer_size = sizeof(buffer);
cass_cluster_getopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, buffer, &buffer_size);
BOOST_REQUIRE(strcmp(contact_points1, buffer) == 0);
// Clear
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, "", 0);
buffer_size = sizeof(buffer);
cass_cluster_getopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, buffer, &buffer_size);
BOOST_REQUIRE(buffer_size == 0);
// Extra whitespace
const char* contact_points1_ws = " ,\r\n, , , 127.0.0.1 ,,, ,\t127.0.0.2,127.0.0.3, \t\n, ,, ";
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, contact_points1_ws, strlen(contact_points1_ws));
buffer_size = sizeof(buffer);
cass_cluster_getopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, buffer, &buffer_size);
BOOST_REQUIRE(strcmp(contact_points1, buffer) == 0);
// Clear
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, "", 0);
buffer_size = sizeof(buffer);
cass_cluster_getopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, buffer, &buffer_size);
BOOST_REQUIRE(buffer_size == 0);
// Append
const char* contact_point1 = "127.0.0.1";
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, contact_point1, strlen(contact_point1));
const char* contact_point2 = "127.0.0.2";
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, contact_point2, strlen(contact_point2));
const char* contact_point3 = "127.0.0.3";
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, contact_point3, strlen(contact_point3));
buffer_size = sizeof(buffer);
cass_cluster_getopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, buffer, &buffer_size);
BOOST_REQUIRE(strcmp(contact_points1, buffer) == 0);
}
BOOST_AUTO_TEST_SUITE_END()
| 37.108333
| 146
| 0.760835
|
Paycasso
|
0d0446ac2835a18565812064ad6568f2fc69d033
| 6,268
|
cpp
|
C++
|
src/Auxiliary/Aux_Check_Conservation.cpp
|
zhulianhua/Daino
|
db88f5738aba76fa8a28d7672450e0c5c832b3de
|
[
"MIT"
] | 3
|
2019-04-13T02:08:01.000Z
|
2020-11-17T12:45:37.000Z
|
src/Auxiliary/Aux_Check_Conservation.cpp
|
zhulianhua/Daino
|
db88f5738aba76fa8a28d7672450e0c5c832b3de
|
[
"MIT"
] | null | null | null |
src/Auxiliary/Aux_Check_Conservation.cpp
|
zhulianhua/Daino
|
db88f5738aba76fa8a28d7672450e0c5c832b3de
|
[
"MIT"
] | 2
|
2019-11-12T02:00:20.000Z
|
2019-12-09T14:52:31.000Z
|
#include "DAINO.h"
#if ( MODEL == MHD )
#warning : WAIT MHD !!!
#endif
//-------------------------------------------------------------------------------------------------------
// Function : Aux_Check_Conservation
// Description : Verify the conservation laws
// --> HYDRO : check mass, momenum, and energy
// MHD : check mass, momenum, and energy
// ELBDM : check mass only
//
// Note : 1. This check only works with the models HYDRO, MHD, and ELBDM
// 2. The values measured during the first time this function is invoked will be taken as the
// reference values to estimate errors
// 3. The following gnuplot command can be used to plot "error vs. time", assuming
// "TVar = [0 ... NVar-1]"
//
// plot 'Record__Conservation' u 1:7 every NCOMP+1::(2+TVar) w lp ps 4
//
// Parameter : Output2File : true --> Output results to file instead of showing on the screen
// comment : You can put the location where this function is invoked in this string
//-------------------------------------------------------------------------------------------------------
void Aux_Check_Conservation( const bool Output2File, const char *comment )
{
static bool FirstTime = true;
const char *FileName = "Record__Conservation";
// check
# if ( MODEL != HYDRO && MODEL != MHD && MODEL != ELBDM )
Aux_Message( stderr, "Warning : function \"%s\" is supported only in the models HYDRO, MHD, and ELBDM !!\n",
__FUNCTION__ );
OPT__CK_CONSERVATION = false;
return;
# endif
if ( FirstTime && MPI_Rank == 0 && Output2File )
{
FILE *File_Check = fopen( FileName, "r" );
if ( File_Check != NULL )
{
Aux_Message( stderr, "WARNING : the file \"%s\" already exists !!\n", FileName );
fclose( File_Check );
}
}
# if ( MODEL == HYDRO )
const int NVar = NCOMP;
# elif ( MODEL == MHD )
# warning : WAIT MHD !!!
# elif ( MODEL == ELBDM )
const int NVar = 1;
# else
# error : ERROR : unsupported MODEL !!
# endif
double dV, Total_local[NVar], Total_sum[NVar], Total_lv[NVar]; // dV : cell volume at each level
int Sg;
FILE *File = NULL;
// output message if Output2File is off
if ( MPI_Rank == 0 && !Output2File )
{
if ( FirstTime )
Aux_Message( stdout, "\"%s\" : <%s> referencing at Time = %13.7e, Step = %7ld\n",
comment, __FUNCTION__, Time[0], Step );
else
Aux_Message( stdout, "\"%s\" : <%s> checking at Time = %13.7e, Step = %7ld\n",
comment, __FUNCTION__, Time[0], Step );
}
// measure the total amount of the targeted variables
for (int v=0; v<NVar; v++)
{
Total_local[v] = 0.0;
Total_sum [v] = 0.0;
}
for (int lv=0; lv<NLEVEL; lv++)
{
for (int v=0; v<NVar; v++) Total_lv[v] = 0.0;
dV = patch->dh[lv] * patch->dh[lv] * patch->dh[lv];
Sg = patch->FluSg[lv];
for (int PID=0; PID<patch->NPatchComma[lv][1]; PID++)
{
if ( patch->ptr[0][lv][PID]->son == -1 )
{
# if ( MODEL == HYDRO )
for (int v=0; v<NVar; v++)
for (int k=0; k<PATCH_SIZE; k++)
for (int j=0; j<PATCH_SIZE; j++)
for (int i=0; i<PATCH_SIZE; i++)
Total_lv[v] += (double)patch->ptr[Sg][lv][PID]->fluid[v][k][j][i];
# elif ( MODEL == MHD )
# warning : WAIT MHD !!!
# elif ( MODEL == ELBDM )
for (int k=0; k<PATCH_SIZE; k++)
for (int j=0; j<PATCH_SIZE; j++)
for (int i=0; i<PATCH_SIZE; i++)
Total_lv[0] += (double)patch->ptr[Sg][lv][PID]->fluid[DENS][k][j][i];
# endif // MODEL
}
} // for (int PID=0; PID<patch->NPatchComma[lv][1]; PID++)
// sum over NLEVEL levels
for (int v=0; v<NVar; v++)
{
Total_lv [v] *= dV;
Total_local[v] += Total_lv[v];
}
} // for (int lv=0; lv<NLEVEL; lv++)
// sum over all ranks
MPI_Reduce( Total_local, Total_sum, NVar, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD );
// output
if ( MPI_Rank == 0 )
{
static double RefTotal[NVar];
double AbsErr[NVar], RelErr[NVar];
// record the reference values
if ( FirstTime )
{
for (int v=0; v<NVar; v++) RefTotal[v] = Total_sum[v];
if ( Output2File )
{
File = fopen( FileName, "a" );
Aux_Message( File, "%16s%10s%13s%18s%18s%18s%18s\n",
"Time", "Step", "Attribute", "Evaluate", "Reference", "Absolute Error", "Error" );
Aux_Message( File, "-----------------------------------------------------------------------------" );
Aux_Message( File, "----------------------------------\n" );
fclose( File );
}
}
// calculate errors
else
{
for (int v=0; v<NVar; v++)
{
AbsErr[v] = Total_sum[v] - RefTotal[v];
RelErr[v] = AbsErr[v] / RefTotal[v];
}
if ( Output2File )
{
File = fopen( FileName, "a" );
for (int v=0; v<NVar; v++)
Aux_Message( File, "%16.7e%10ld%13d%18.7e%18.7e%18.7e%18.7e\n",
Time[0], Step, v, Total_sum[v], RefTotal[v], AbsErr[v], RelErr[v] );
Aux_Message( File, "-----------------------------------------------------------------------------" );
Aux_Message( File, "----------------------------------\n" );
fclose( File );
}
else
{
Aux_Message( stdout, "%13s%20s%20s%20s%20s\n",
"Attribute", "Evaluate", "Reference", "Absolute Error", "Error" );
for (int v=0; v<NVar; v++)
Aux_Message( stdout, "%13d%20.7e%20.7e%20.7e%20.7e\n",
v, Total_sum[v], RefTotal[v], AbsErr[v], RelErr[v] );
}
} // if ( FirstTime ) ... else ...
} // if ( MPI_Rank == 0 )
if ( FirstTime ) FirstTime = false;
} // FUNCTION : Aux_Check_Conservation
| 31.979592
| 113
| 0.469368
|
zhulianhua
|
0d0d6309cc3d18e9b97b348f1e2afd22e039ddea
| 1,897
|
cpp
|
C++
|
crazyrc/rc_parser.cpp
|
mojmir-svoboda/BlackBoxTT
|
0c87b989827107695538e1bf1266c08b083dda44
|
[
"MIT"
] | 11
|
2017-06-19T14:21:15.000Z
|
2020-03-04T06:43:16.000Z
|
crazyrc/rc_parser.cpp
|
mojmir-svoboda/BlackBoxTT
|
0c87b989827107695538e1bf1266c08b083dda44
|
[
"MIT"
] | null | null | null |
crazyrc/rc_parser.cpp
|
mojmir-svoboda/BlackBoxTT
|
0c87b989827107695538e1bf1266c08b083dda44
|
[
"MIT"
] | 3
|
2017-07-23T18:08:55.000Z
|
2019-09-16T16:28:18.000Z
|
#include <boost/spirit/include/qi.hpp>
#include <boost/foreach.hpp>
#include <boost/assert.hpp>
#include <boost/variant/variant.hpp>
#include <iostream>
#include <string>
#include <cstdlib>
#include <map>
#include "rc_grammar.h"
#include "rc_dump.h"
#include "unicode.h"
#include "utils_file.h"
#include "rc_cache.h"
using namespace boost::spirit::standard_wide;
#include <fstream>
#include <string>
#include <cerrno>
#include <tchar.h>
#include <string>
#include <vector>
#include <windef.h>
#include "rgb_txt_parser.h"
namespace rc {
namespace qi = boost::spirit::qi;
ColorSymbols::ColorSymbols()
{
for (auto const & item : rgb_txt::getColorTable())
this->add(item.second, item.first);
}
bool parseFile (tstring const & fname, tstring & err)
{
tstring content;
if (readFileContent(fname, content))
{
static rc::Grammar<tstring::iterator> const g;
tstring::iterator begin = content.begin();
tstring::iterator end = content.end();
ParsedFileRecord rec;
try
{
bool const r = qi::phrase_parse(begin, end, g, qi::blank, rec.m_parsedFile);
if (r && begin == end)
{
getParsedFileCache().Add(fname, rec);
getParsedFileCache().MakeIndex();
//std::cout << m;
return true;
}
else
{
tstringstream ss;
ss << "+---- parser stopped here\n";
ss << "V\n";
if (std::distance(begin, end) > 128)
{
tstring rest(begin, begin + 128);
ss << rest << "\n";
}
else
{
tstring rest(begin, end);
ss << rest << "\n";
}
err = ss.str();
return false;
}
}
catch (...)
{
tstringstream ss;
ss << "Exception caught while parsing!" << std::endl;
err = ss.str();
return false;
}
return true;
}
return false;
}
bool parseFile (tstring const & fname)
{
tstring err;
bool const parsed = parseFile(fname, err);
if (!parsed)
{
//LogError(fname, err);
}
return parsed;
}
}
| 18.066667
| 79
| 0.633632
|
mojmir-svoboda
|
0d0df500dc9c7cc3755a92e5f113f6e931144607
| 2,552
|
cpp
|
C++
|
LibraryDX12/Resource/D2DWrappedResource.cpp
|
DziubanMaciej/DirectX-Deconfused
|
a8a4177beeb40436f6e0734e6d28d60aa1867d40
|
[
"MIT"
] | null | null | null |
LibraryDX12/Resource/D2DWrappedResource.cpp
|
DziubanMaciej/DirectX-Deconfused
|
a8a4177beeb40436f6e0734e6d28d60aa1867d40
|
[
"MIT"
] | null | null | null |
LibraryDX12/Resource/D2DWrappedResource.cpp
|
DziubanMaciej/DirectX-Deconfused
|
a8a4177beeb40436f6e0734e6d28d60aa1867d40
|
[
"MIT"
] | null | null | null |
#include "D2DWrappedResource.h"
#include "Application/ApplicationImpl.h"
#include "Resource/Resource.h"
#include "Utility/ThrowIfFailed.h"
#include <cassert>
void D2DWrappedResource::wrap(float dpi) {
auto &d2dContext = ApplicationImpl::getInstance().getD2DContext();
// Create DX11 Resource
const D3D11_RESOURCE_FLAGS d3d11Flags = {D3D11_BIND_RENDER_TARGET};
throwIfFailed(d2dContext.getD3D11On12Device()->CreateWrappedResource(
d12Resource.getResource().Get(), &d3d11Flags,
inState, outState,
IID_PPV_ARGS(&d3d11Resource)));
// Convert to DXGI surface
IDXGISurfacePtr surface = {};
throwIfFailed(d3d11Resource.As(&surface));
// Create D2D Resource
const auto bitmapProperties = D2D1::BitmapProperties1(
D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED),
dpi, dpi);
throwIfFailed(d2dContext.getD2DDeviceContext()->CreateBitmapFromDxgiSurface(
surface.Get(),
&bitmapProperties,
&d2dResource));
}
void D2DWrappedResource::reset() {
d3d11Resource.Reset();
d2dResource.Reset();
}
AcquiredD2DWrappedResource D2DWrappedResource::acquire() {
assert(!this->acquired);
return AcquiredD2DWrappedResource{*this};
}
inline AcquiredD2DWrappedResource::AcquiredD2DWrappedResource(D2DWrappedResource &parent) : parent(&parent) {
assert(!parent.acquired);
auto &device = ApplicationImpl::getInstance().getD2DContext().getD3D11On12Device();
device->AcquireWrappedResources(parent.d3d11Resource.GetAddressOf(), 1);
parent.acquired = true;
}
AcquiredD2DWrappedResource::AcquiredD2DWrappedResource(AcquiredD2DWrappedResource &&other) : parent(other.parent) {
other.parent = nullptr;
}
AcquiredD2DWrappedResource::~AcquiredD2DWrappedResource() {
if (parent == nullptr) {
return;
}
assert(parent->acquired);
// Release
parent->acquired = false;
auto &device = ApplicationImpl::getInstance().getD2DContext().getD3D11On12Device();
device->ReleaseWrappedResources(parent->d3d11Resource.GetAddressOf(), 1); // This call makes implicit state transition
// Manage state
assert(parent->d12Resource.getState().areAllSubresourcesInState(parent->inState));
parent->d12Resource.setState(Resource::ResourceState{parent->outState});
// Flush to submit the D2D command list to the shared command queue.
ApplicationImpl::getInstance().getD2DContext().getD3D11DeviceContext()->Flush();
}
| 34.486486
| 122
| 0.738245
|
DziubanMaciej
|
0d11f1dccbf81b4bfe3341997c844aed40fcb94a
| 22,910
|
hpp
|
C++
|
3rdparty/sospd/include/litiv/3rdparty/sospd/sospd.hpp
|
jpjodoin/litiv
|
435556bea20d60816aff492f50587b1a2d748b21
|
[
"BSD-3-Clause"
] | 97
|
2015-10-16T04:32:33.000Z
|
2022-03-29T07:04:02.000Z
|
3rdparty/sospd/include/litiv/3rdparty/sospd/sospd.hpp
|
jpjodoin/litiv
|
435556bea20d60816aff492f50587b1a2d748b21
|
[
"BSD-3-Clause"
] | 19
|
2016-07-01T16:37:02.000Z
|
2020-09-10T06:09:39.000Z
|
3rdparty/sospd/include/litiv/3rdparty/sospd/sospd.hpp
|
jpjodoin/litiv
|
435556bea20d60816aff492f50587b1a2d748b21
|
[
"BSD-3-Clause"
] | 41
|
2015-11-17T05:59:23.000Z
|
2022-02-16T09:30:28.000Z
|
#pragma once
#include "litiv/3rdparty/sospd/multilabel-energy.hpp"
#include "litiv/3rdparty/sospd/submodular-ibfs.hpp"
namespace sospd {
/** Optimizer using Sum-of-submodular Primal Dual algorithm.
*
* Implements SoSPD algorithm from Fix, Wang, Zabih in CVPR 14.
*/
template<typename ValueType, typename IndexType, typename LabelType, typename Flow = SubmodularIBFS<ValueType,IndexType>>
class SoSPD {
public:
typedef MultilabelEnergy<ValueType,IndexType,LabelType> MLE;
typedef typename MLE::REAL REAL;
typedef typename MLE::VarId VarId;
typedef typename MLE::Label Label;
typedef sospd::Assgn Assgn;
/** Proposal callbacks take as input the iteration number and current
* labeling (as a vector of labels) and write the next proposal to the
* final parameter.
*/
typedef std::function<void(IndexType niter,const std::vector<Label>& current,std::vector<Label>& proposed)> ProposalCallback;
/** Set up SoSPD to optimize a particular energy function
*
* \param energy Energy function to optimize.
*/
explicit SoSPD(const MLE* energy);
explicit SoSPD(const MLE* energy, SubmodularIBFSParams& params);
/** Run SoSPD algorithm either to completion, or for a number of steps.
*
* Each iteration has a single proposal (determined by
* SetProposalCallback), and solves a corresponding Sum-of-Submodular
* flow problem.
*
* Resulting labeling can be queried from GetLabel.
*
* \param niters Number of iterations
*/
void Solve(IndexType niters = std::numeric_limits<IndexType>::max());
/** Return label of a node i, returns -1 if Solve has not been called.*/
LabelType GetLabel(VarId i) const;
/** Give hint that energy is expansion submodular. Enables optimizations
* because we don't need to find submodular upper/lower bounds for the
* function.
*/
void SetExpansionSubmodular(bool b) { m_expansion_submodular = b; }
/** Choose whether to use lower/upper bound in approximating function.
*/
void SetLowerBound(bool b) { m_lower_bound = b; }
/** Specify method for choosing proposals. */
void SetProposalCallback(const ProposalCallback& pc) { m_pc = pc; }
/** Set the proposal method to alpha-expansion
*
* Alpha-expansion proposals simply cycle through the labels, proposing
* a constant labeling (i.e., all "alpha") at each iteration.
*/
void SetAlphaExpansion() {
m_pc = [&](IndexType,const std::vector<Label>&,std::vector<Label>&) {
AlphaProposal();
};
}
/** Set the proposal method to best-height alpha-expansion
*
* Best-height alpha-expansion, instead of cycling through labels,
* chooses the single alpha with the biggest sum of differences in
* heights.
*/
void SetHeightAlphaExpansion() {
m_pc = [&](IndexType,const std::vector<Label>&,std::vector<Label>&) {
HeightAlphaProposal();
};
}
/** Return lower bound on optimum, determined by current dual */
double LowerBound();
REAL dualVariable(IndexType alpha, VarId i, Label l) const;
Flow* GetFlow() { return &m_ibfs; }
private:
typedef typename MLE::CliquePtr CliquePtr;
typedef std::vector<REAL> LambdaAlpha;
typedef std::vector<std::pair<IndexType,IndexType>> NodeNeighborList;
typedef std::vector<NodeNeighborList> NodeCliqueList;
REAL ComputeHeight(VarId, Label);
REAL ComputeHeightDiff(VarId i, Label l1, Label l2) const;
void SetupGraph(Flow& crf);
// TODO(afix): redo this
void SetupAlphaEnergy(Flow& crf);
void InitialLabeling();
void InitialDual();
void InitialNodeCliqueList();
bool InitialFusionLabeling();
void PreEditDual(Flow& crf);
bool UpdatePrimalDual(Flow& crf);
void PostEditDual();
void DualFit();
REAL& Height(VarId i, Label l) { return m_heights[i*m_num_labels+l]; }
REAL& dualVariable(IndexType alpha, VarId i, Label l);
REAL dualVariable(const LambdaAlpha& lambdaAlpha,
VarId i, Label l) const;
REAL& dualVariable(LambdaAlpha& lambdaAlpha,
VarId i, Label l);
LambdaAlpha& lambdaAlpha(IndexType alpha);
const LambdaAlpha& lambdaAlpha(IndexType alpha) const;
// Move Proposals
void HeightAlphaProposal();
void AlphaProposal();
const MLE* m_energy;
// Unique ptr so we can forward declare?
Flow m_ibfs;
const IndexType m_num_labels;
std::vector<Label> m_labels;
/// The proposed labeling in a given iteration
std::vector<Label> m_fusion_labels;
// Factor this list back into a node list?
NodeCliqueList m_node_clique_list;
// FIXME(afix) change way m_dual is stored. Put lambda_alpha as separate
// REAL* for each clique, indexed by i, l.
std::vector<LambdaAlpha> m_dual;
std::vector<REAL> m_heights;
bool m_expansion_submodular;
bool m_lower_bound;
IndexType m_iter;
ProposalCallback m_pc;
};
} // namespace sospd
template<typename V, typename I, typename L, typename F>
inline sospd::SoSPD<V,I,L,F>::SoSPD(const MLE* energy)
: m_energy(energy),
m_num_labels(energy->numLabels()),
m_labels(energy->numVars(), 0),
m_fusion_labels(energy->numVars(), 0),
m_expansion_submodular(false),
m_lower_bound(false),
m_iter(0),
m_pc([&](I,const std::vector<Label>&,std::vector<Label>&) {HeightAlphaProposal();})
{ }
template<typename V, typename I, typename L, typename F>
inline sospd::SoSPD<V,I,L,F>::SoSPD(const MLE* energy, SubmodularIBFSParams& params)
: m_energy(energy),
m_ibfs(params),
m_num_labels(energy->numLabels()),
m_labels(energy->numVars(), 0),
m_fusion_labels(energy->numVars(), 0),
m_expansion_submodular(false),
m_lower_bound(false),
m_iter(0),
m_pc([&](I,const std::vector<Label>&,std::vector<Label>&) {HeightAlphaProposal();})
{ }
template<typename V, typename I, typename L, typename F>
inline L sospd::SoSPD<V,I,L,F>::GetLabel(VarId i) const {
return L(m_labels[i]);
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::InitialLabeling() {
const VarId n = m_energy->numVars();
for (VarId i = 0; i < n; ++i) {
REAL best_cost = std::numeric_limits<REAL>::max();
for (I l = 0; l < m_num_labels; ++l) {
if (m_energy->unary(i, l) < best_cost) {
best_cost = m_energy->unary(i, l);
m_labels[i] = l;
}
}
}
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::InitialDual() {
// Initialize heights
m_heights = std::vector<REAL>(m_energy->numVars()*m_num_labels, 0);
for (VarId i = 0; i < m_energy->numVars(); ++i)
for (Label l = 0; l < m_num_labels; ++l)
Height(i, l) = m_energy->unary(i, l);
m_dual.clear();
Label labelBuf[32];
for (const CliquePtr& cp : m_energy->cliques()) {
const Clique<V,I,L>& c = *cp;
const VarId* nodes = c.nodes();
I k = I(c.size());
ASSERT(k < I(32));
for (I i = 0; i < k; ++i) {
labelBuf[i] = m_labels[nodes[i]];
}
REAL energy = c.energy(labelBuf);
m_dual.emplace_back(k*m_num_labels, 0);
LambdaAlpha& lambda_a = m_dual.back();
ASSERT(energy >= 0);
REAL avg = energy / k;
int remainder = int(energy) % k;
for (I i = 0; i < k; ++i) {
Label l = m_labels[nodes[i]];
REAL& lambda_ail = dualVariable(lambda_a, i, l);
lambda_ail = avg;
if(int(i) < remainder) // Have to distribute remainder to maintain average
lambda_ail += 1;
Height(nodes[i], l) += lambda_ail;
}
}
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::InitialNodeCliqueList() {
I n = I(m_labels.size());
m_node_clique_list.clear();
m_node_clique_list.resize(n);
I clique_index = 0;
for (const CliquePtr& cp : m_energy->cliques()) {
const Clique<V,I,L>& c = *cp;
const VarId* nodes = c.nodes();
const I k = I(c.size());
for (I i = 0; i < k; ++i) {
m_node_clique_list[nodes[i]].push_back(std::make_pair(clique_index, i));
}
++clique_index;
}
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::PreEditDual(F& crf) {
auto& fixedVars = crf.Params().fixedVars;
fixedVars.resize(m_labels.size());
for (I i = 0; i < I(m_labels.size()); ++i)
fixedVars[i] = (m_labels[i] == m_fusion_labels[i]);
// Allocate all the buffers we need in one place, resize as necessary
Label label_buf[32];
std::vector<Label> current_labels;
std::vector<Label> fusion_labels;
std::vector<REAL> psi;
std::vector<REAL> current_lambda;
std::vector<REAL> fusion_lambda;
auto& ibfs_cliques = crf.Graph().GetCliques();
ASSERT(ibfs_cliques.size() == m_energy->cliques().size());
I clique_index = 0;
for (const CliquePtr& cp : m_energy->cliques()) {
const Clique<V,I,L>& c = *cp;
const I k = I(c.size());
ASSERT(k < I(32));
auto& lambda_a = lambdaAlpha(clique_index);
auto& ibfs_c = ibfs_cliques[clique_index];
ASSERT(k == ibfs_c.Size());
std::vector<REAL>& energy_table = ibfs_c.EnergyTable();
sospd::Assgn max_assgn = 1u << k;
ASSERT(energy_table.size() == max_assgn);
psi.resize(k);
current_labels.resize(k);
fusion_labels.resize(k);
current_lambda.resize(k);
fusion_lambda.resize(k);
for (I i = 0; i < k; ++i) {
current_labels[i] = m_labels[c.nodes()[i]];
fusion_labels[i] = m_fusion_labels[c.nodes()[i]];
/*
*ASSERT(0 <= c.nodes()[i] && c.nodes()[i] < m_labels.size());
*ASSERT(0 <= current_labels[i] && current_labels[i] < m_num_labels);
*ASSERT(0 <= fusion_labels[i] && fusion_labels[i] < m_num_labels);
*/
current_lambda[i] = dualVariable(lambda_a, i, current_labels[i]);
fusion_lambda[i] = dualVariable(lambda_a, i, fusion_labels[i]);
}
// Compute costs of all fusion assignments
{
Assgn last_gray = 0;
for (I i_idx = 0; i_idx < k; ++i_idx)
label_buf[i_idx] = current_labels[i_idx];
energy_table[0] = c.energy(label_buf);
for (Assgn a = 1; a < max_assgn; ++a) {
Assgn gray = a ^ (a >> 1);
Assgn diff = gray ^ last_gray;
int changed_idx = __builtin_ctz(diff);
if (diff & gray)
label_buf[changed_idx] = fusion_labels[changed_idx];
else
label_buf[changed_idx] = current_labels[changed_idx];
last_gray = gray;
energy_table[gray] = c.energy(label_buf);
}
}
// Compute the residual function
// g(S) - lambda_fusion(S) - lambda_current(C\S)
sospd::SubtractLinear(k, energy_table, fusion_lambda, current_lambda);
ASSERT(energy_table[0] == 0); // Check tightness of current labeling
++clique_index;
}
}
template<typename V, typename I, typename L, typename F>
inline typename sospd::SoSPD<V,I,L,F>::REAL sospd::SoSPD<V,I,L,F>::ComputeHeight(VarId i, Label x) {
REAL ret = m_energy->unary(i, x);
for (const auto& p : m_node_clique_list[i]) {
ret += dualVariable(p.first, p.second, x);
}
return ret;
}
template<typename V, typename I, typename L, typename F>
inline typename sospd::SoSPD<V,I,L,F>::REAL sospd::SoSPD<V,I,L,F>::ComputeHeightDiff(VarId i, Label l1, Label l2) const {
REAL ret = m_energy->unary(i, l1) - m_energy->unary(i, l2);
for (const auto& p : m_node_clique_list[i]) {
ret += dualVariable(p.first, p.second, l1)
- dualVariable(p.first, p.second, l2);
}
return ret;
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::SetupGraph(F& crf) {
const I n = I(m_labels.size());
crf.AddNode(n);
for (const CliquePtr& cp : m_energy->cliques()) {
const Clique<V,I,L>& c = *cp;
const I k = I(c.size());
ASSERT(k < I(32));
const I max_assgn = 1u << k;
std::vector<typename F::NodeId> nodes(c.nodes(), c.nodes() + c.size());
crf.AddClique(nodes, std::vector<REAL>(max_assgn, 0));
}
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::SetupAlphaEnergy(F& crf) {
const I n = I(m_labels.size());
crf.ClearUnaries();
crf.AddConstantTerm(-crf.GetConstantTerm());
for (I i = 0; i < n; ++i) {
REAL height_diff = ComputeHeightDiff(i, m_labels[i], m_fusion_labels[i]);
if (height_diff > 0) {
crf.AddUnaryTerm(i, height_diff, 0);
}
else {
crf.AddUnaryTerm(i, 0, -height_diff);
}
}
}
template<typename V, typename I, typename L, typename F>
inline bool sospd::SoSPD<V,I,L,F>::UpdatePrimalDual(F& crf) {
bool ret = false;
SetupAlphaEnergy(crf);
crf.Solve();
VarId n = m_labels.size();
for (VarId i = 0; i < n; ++i) {
int crf_label = crf.GetLabel(i);
if (crf_label == 1) {
Label alpha = m_fusion_labels[i];
if (m_labels[i] != alpha) ret = true;
m_labels[i] = alpha;
}
}
const auto& clique = crf.Graph().GetCliques();
I i = 0;
for (const CliquePtr& cp : m_energy->cliques()) {
const Clique<V,I,L>& c = *cp;
auto& ibfs_c = clique[i];
const std::vector<REAL>& phiCi = ibfs_c.AlphaCi();
for (I j = 0; j < I(phiCi.size()); ++j) {
dualVariable(i, j, m_fusion_labels[c.nodes()[j]]) += phiCi[j];
Height(c.nodes()[j], m_fusion_labels[c.nodes()[j]]) += phiCi[j];
}
++i;
}
return ret;
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::PostEditDual() {
Label labelBuf[32];
I clique_index = 0;
for (const CliquePtr& cp : m_energy->cliques()) {
const Clique<V,I,L>& c = *cp;
const VarId* nodes = c.nodes();
I k = I(c.size());
ASSERT(k < I(32));
REAL lambdaSum = 0;
for (I i = 0; i < k; ++i) {
labelBuf[i] = m_labels[nodes[i]];
lambdaSum += dualVariable(clique_index, i, labelBuf[i]);
}
REAL energy = c.energy(labelBuf);
REAL correction = energy - lambdaSum;
if (correction > 0) {
std::cout << "Bad clique in PostEditDual!\t Id:" << clique_index << "\n";
std::cout << "Correction: " << correction << "\tenergy: " << energy << "\tlambdaSum " << lambdaSum << "\n";
const auto& c2 = m_ibfs.Graph().GetCliques()[clique_index];
std::cout << "EnergyTable: ";
for (const auto& e : c2.EnergyTable())
std::cout << e << ", ";
std::cout << "\n";
}
ASSERT(correction <= 0);
REAL avg = correction / k;
int remainder = int(correction) % k;
if (remainder < 0) {
avg -= 1;
remainder += k;
}
for (I i = 0; i < k; ++i) {
auto& lambda_ail = dualVariable(clique_index, i, labelBuf[i]);
Height(nodes[i], labelBuf[i]) -= lambda_ail;
lambda_ail += avg;
if (int(i) < remainder)
lambda_ail += 1;
Height(nodes[i], labelBuf[i]) += lambda_ail;
}
++clique_index;
}
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::DualFit() {
// FIXME: This is the only function that doesn't work with integer division.
// It's also not really used for anything at the moment
/*
for (I i = 0; i < I(m_dual.size()); ++i)
for (I j = 0; j < I(m_dual[i].size()); ++j)
for (I k = 0; k < I(m_dual[i][j].size()); ++k)
m_dual[i][j][k] /= (m_mu * m_rho);
*/
ASSERT(false /* unimplemented */);
}
template<typename V, typename I, typename L, typename F>
inline bool sospd::SoSPD<V,I,L,F>::InitialFusionLabeling() {
m_pc(m_iter, m_labels, m_fusion_labels);
bool allDiff = false;
for (I i = 0; i < I(m_labels.size()); ++i) {
if (m_fusion_labels[i] < 0) m_fusion_labels[i] = 0;
if (m_fusion_labels[i] >= m_num_labels) m_fusion_labels[i] = m_num_labels-1;
if (m_labels[i] != m_fusion_labels[i])
allDiff = true;
}
return allDiff;
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::HeightAlphaProposal() {
const I n = I(m_labels.size());
REAL max_s_capacity = 0;
Label alpha = 0;
for (Label l = 0; l < m_num_labels; ++l) {
REAL s_capacity = 0;
for (I i = 0; i < n; ++i) {
REAL diff = Height(i, m_labels[i]) - Height(i, l);
if (diff > V(0))
s_capacity += diff;
}
if (s_capacity > max_s_capacity) {
max_s_capacity = s_capacity;
alpha = l;
}
}
for (I i = 0; i < n; ++i)
m_fusion_labels[i] = alpha;
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::AlphaProposal() {
Label alpha = m_iter % m_num_labels;
const I n = I(m_labels.size());
for (I i = 0; i < n; ++i)
m_fusion_labels[i] = alpha;
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::Solve(I niters) {
if (m_iter == I(0)) {
SetupGraph(m_ibfs);
InitialLabeling();
InitialDual();
InitialNodeCliqueList();
}
#ifdef PROGRESS_DISPLAY
REAL energy = m_energy->ComputeEnergy(m_labels);
std::cout << "Iteration " << m_iter << ": " << energy << std::endl;
#endif
bool labelChanged = true;
I this_iter = 0;
while (labelChanged && this_iter < niters){
labelChanged = InitialFusionLabeling();
if (!labelChanged) break;
PreEditDual(m_ibfs);
UpdatePrimalDual(m_ibfs);
PostEditDual();
this_iter++;
m_iter++;
#ifdef PROGRESS_DISPLAY
energy = m_energy->ComputeEnergy(m_labels);
std::cout << "Iteration " << m_iter << ": " << energy << std::endl;
#endif
}
//LowerBound();
}
template<typename V, typename I, typename L, typename F>
inline typename sospd::SoSPD<V,I,L,F>::REAL sospd::SoSPD<V,I,L,F>::dualVariable(I alpha, VarId i, Label l) const {
return m_dual[alpha][i*m_num_labels+l];
}
template<typename V, typename I, typename L, typename F>
inline typename sospd::SoSPD<V,I,L,F>::REAL& sospd::SoSPD<V,I,L,F>::dualVariable(I alpha, VarId i, Label l) {
return m_dual[alpha][i*m_num_labels+l];
}
template<typename V, typename I, typename L, typename F>
inline typename sospd::SoSPD<V,I,L,F>::REAL sospd::SoSPD<V,I,L,F>::dualVariable(const LambdaAlpha& lambdaAlpha, VarId i, Label l) const {
return lambdaAlpha[i*m_num_labels+l];
}
template<typename V, typename I, typename L, typename F>
inline typename sospd::SoSPD<V,I,L,F>::REAL& sospd::SoSPD<V,I,L,F>::dualVariable(LambdaAlpha& lambdaAlpha, VarId i, Label l) {
return lambdaAlpha[i*m_num_labels+l];
}
template<typename V, typename I, typename L, typename F>
inline typename sospd::SoSPD<V,I,L,F>::LambdaAlpha& sospd::SoSPD<V,I,L,F>::lambdaAlpha(I alpha) {
return m_dual[alpha];
}
template<typename V, typename I, typename L, typename F>
inline const typename sospd::SoSPD<V,I,L,F>::LambdaAlpha& sospd::SoSPD<V,I,L,F>::lambdaAlpha(I alpha) const {
return m_dual[alpha];
}
template<typename V, typename I, typename L, typename F>
inline double sospd::SoSPD<V,I,L,F>::LowerBound() {
std::cout << "Computing Lower Bound\n";
double max_ratio = 0;
I clique_index = 0;
for (const CliquePtr& cp : m_energy->cliques()) {
const Clique<V,I,L>& c = *cp;
const I k = I(c.size());
ASSERT(k == 3); // Lower bound doesn't work for larger numbers
Label buf[3];
for (buf[0] = 0; buf[0] < m_num_labels; ++buf[0]) {
for (buf[1] = 0; buf[1] < m_num_labels; ++buf[1]) {
for (buf[2] = 0; buf[2] < m_num_labels; ++buf[2]) {
REAL energy = c.energy(buf);
REAL dualSum = dualVariable(clique_index, 0, buf[0])
+ dualVariable(clique_index, 1, buf[1])
+ dualVariable(clique_index, 2, buf[2]);
if (energy == 0) {
for (I i = 0; i < I(3); ++i) {
if (buf[i] != m_labels[c.nodes()[i]]) {
dualVariable(clique_index, i, buf[i]) -= dualSum - energy;
Height(c.nodes()[i], buf[i]) -= dualSum - energy;
dualSum = energy;
break;
}
}
ASSERT(dualSum == energy);
} else {
max_ratio = std::max(max_ratio, double(dualSum)/double(energy));
}
}
}
}
clique_index++;
}
REAL dual_objective = 0;
for (VarId i = 0; i < m_energy->numVars(); ++i) {
REAL min_height = std::numeric_limits<REAL>::max();
for (Label l = 0; l < m_num_labels; ++l)
min_height = std::min(min_height, Height(i, l));
dual_objective += min_height;
}
std::cout << "Max Ratio: " << max_ratio << "\n";
std::cout << "Dual objective: " << dual_objective << "\n";
return dual_objective / max_ratio;
}
| 38.056478
| 137
| 0.564426
|
jpjodoin
|
0d1c148b5ab0de3d48c69dc629e369d28b987032
| 5,090
|
cpp
|
C++
|
AGVCCON/fDurationTasks.cpp
|
jluzardo1971/ActiveGanttVC
|
4748cb4d942551dc64c9017f279c90969cdcc634
|
[
"MIT"
] | null | null | null |
AGVCCON/fDurationTasks.cpp
|
jluzardo1971/ActiveGanttVC
|
4748cb4d942551dc64c9017f279c90969cdcc634
|
[
"MIT"
] | null | null | null |
AGVCCON/fDurationTasks.cpp
|
jluzardo1971/ActiveGanttVC
|
4748cb4d942551dc64c9017f279c90969cdcc634
|
[
"MIT"
] | null | null | null |
// ----------------------------------------------------------------------------------------
// COPYRIGHT NOTICE
// ----------------------------------------------------------------------------------------
//
// The Source Code Store LLC
// ACTIVEGANTT SCHEDULER COMPONENT FOR C++ - ActiveGanttVC
// ActiveX Control
// Copyright (c) 2002-2017 The Source Code Store LLC
//
// All Rights Reserved. No parts of this file may be reproduced, modified or transmitted
// in any form or by any means without the written permission of the author.
//
// ----------------------------------------------------------------------------------------
#include "stdafx.h"
#include "AGVCCON.h"
#include "fDurationTasks.h"
IMPLEMENT_DYNAMIC(fDurationTasks, CDialog)
fDurationTasks::fDurationTasks(CWnd* pParent /*=NULL*/)
: CDialog(fDurationTasks::IDD, pParent)
{
}
fDurationTasks::~fDurationTasks()
{
}
void fDurationTasks::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_ACTIVEGANTTVCCTL1, ActiveGanttVCCtl1);
}
BEGIN_MESSAGE_MAP(fDurationTasks, CDialog)
ON_WM_SIZE()
END_MESSAGE_MAP()
BOOL fDurationTasks::OnInitDialog()
{
CDialog::OnInitDialog();
g_MaximizeWindowsDim(this);
CWnd::ShowWindow(SW_SHOWMAXIMIZED);
//If you open the form: Styles And Templates -> Available Templates in the main menu (fTemplates.vb)
//you can preview all available Templates.
//Or you can also build your own:
//fMSProject11.vb shows you how to build a Solid Template in the InitializeAG Method.
//fMSProject14.vb shows you how to build a Gradient Template in the InitializeAG Method.
ActiveGanttVCCtl1.ApplyTemplate(STC_CH_VGRAD_ANAKIWA_BLUE, STO_DEFAULT);
ActiveGanttVCCtl1.SetAddMode(AT_DURATION_BOTH);
ActiveGanttVCCtl1.SetAddDurationInterval(IL_HOUR);
CclsView oView;
oView = ActiveGanttVCCtl1.GetViews().Add(IL_MINUTE, 10, ST_MONTH, ST_NOT_VISIBLE, ST_DAYOFWEEK, _T("View1"));
oView.GetTimeLine().GetTickMarkArea().SetVisible(FALSE);
ActiveGanttVCCtl1.SetCurrentView(_T("View1"));
LONG i = 0;
for (i = 0; i <= 110; i++)
{
ActiveGanttVCCtl1.GetRows().Add(_T("K") + CStr(i), _T(""), FALSE, TRUE, _T(""));
}
CclsTimeBlock oTimeBlock;
//Note: non-working overlapping TimeBlock objects are combined for duration calculation purposes.
// TimeBlock starts at 6:00pm and ends on 7:00am next day (13 Hours)
// This TimeBlock is repeated every day.
oTimeBlock = ActiveGanttVCCtl1.GetTimeBlocks().Add(_T("TB_OutOfOfficeHours"));
oTimeBlock.SetNonWorking(TRUE);
oTimeBlock.SetBaseDate(GetDateTime(2000, 1, 1, 18, 0, 0));
oTimeBlock.SetDurationInterval(IL_HOUR);
oTimeBlock.SetDurationFactor(13);
oTimeBlock.SetTimeBlockType(TBT_RECURRING);
oTimeBlock.SetRecurringType(RCT_DAY);
// TimeBlock starts at 12:00pm (noon) and ends at 1:30pm (90 Minutes)
// This TimeBlock is repeated every day.
oTimeBlock = ActiveGanttVCCtl1.GetTimeBlocks().Add(_T("TB_LunchBreak"));
oTimeBlock.SetNonWorking(TRUE);
oTimeBlock.SetBaseDate(GetDateTime(2000, 1, 1, 12, 0, 0));
oTimeBlock.SetDurationInterval(IL_MINUTE);
oTimeBlock.SetDurationFactor(90);
oTimeBlock.SetTimeBlockType(TBT_RECURRING);
oTimeBlock.SetRecurringType(RCT_DAY);
// Timeblock starts at 12:00am Saturday and ends on 12:00am Monday (48 Hours)
// This TimeBlock is repeated every week.
oTimeBlock = ActiveGanttVCCtl1.GetTimeBlocks().Add(_T("TB_Weekend"));
oTimeBlock.SetNonWorking(TRUE);
oTimeBlock.SetBaseDate(GetDateTime(2000, 1, 1, 0, 0, 0));
oTimeBlock.SetDurationInterval(IL_HOUR);
oTimeBlock.SetDurationFactor(48);
oTimeBlock.SetTimeBlockType(TBT_RECURRING);
oTimeBlock.SetRecurringType(RCT_WEEK);
oTimeBlock.SetBaseWeekDay(WD_SATURDAY);
// Arbitrary holiday that starts at 12:00am January 8th and ends on 12:00am January 9th (24 hours)
// This TimeBlock is repeated every year.
oTimeBlock = ActiveGanttVCCtl1.GetTimeBlocks().Add(_T("TB_Jan8"));
oTimeBlock.SetNonWorking(TRUE);
oTimeBlock.SetBaseDate(GetDateTime(2000, 1, 8, 0, 0, 0));
oTimeBlock.SetDurationInterval(IL_HOUR);
oTimeBlock.SetDurationFactor(24);
oTimeBlock.SetTimeBlockType(TBT_RECURRING);
oTimeBlock.SetRecurringType(RCT_YEAR);
ActiveGanttVCCtl1.GetTimeBlocks().SetIntervalStart(GetDateTime(2012, 1, 1));
ActiveGanttVCCtl1.GetTimeBlocks().SetIntervalEnd(GetDateTime(2023, 6, 1));
ActiveGanttVCCtl1.GetTimeBlocks().SetIntervalType(TBIT_MANUAL);
ActiveGanttVCCtl1.GetTimeBlocks().CalculateInterval();
CclsTask oTask;
for (i = 0; i <= 100; i++)
{
oTask = ActiveGanttVCCtl1.GetTasks().DAdd(_T("K") + CStr(i), GetDateTime(2013, 1, 1, 0, 0, 0), IL_HOUR, i, CStr(i), _T(""), _T(""), _T(""));
}
ActiveGanttVCCtl1.GetCurrentViewObject().GetTimeLine().Position(GetDateTime(2013, 1, 1, 0, 0, 0));
ActiveGanttVCCtl1.Redraw();
return TRUE;
}
void fDurationTasks::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
g_Resize(this, &ActiveGanttVCCtl1);
}
| 37.426471
| 148
| 0.68998
|
jluzardo1971
|
0d1d42bb1a2bbac80182053dd249695c15c4e76e
| 2,919
|
cpp
|
C++
|
PickerControls/WxColourPickerCtrl1/src/WxColourPickerCtrl1Frame.cpp
|
wxIshiko/wxWidgetsTutorials
|
83efacbad925a78b3111e055c2f0646ab68b973f
|
[
"Unlicense"
] | 38
|
2018-05-10T08:01:05.000Z
|
2022-03-28T23:14:45.000Z
|
PickerControls/WxColourPickerCtrl1/src/WxColourPickerCtrl1Frame.cpp
|
zhuhui09/wxWidgetsTutorials
|
83efacbad925a78b3111e055c2f0646ab68b973f
|
[
"Unlicense"
] | null | null | null |
PickerControls/WxColourPickerCtrl1/src/WxColourPickerCtrl1Frame.cpp
|
zhuhui09/wxWidgetsTutorials
|
83efacbad925a78b3111e055c2f0646ab68b973f
|
[
"Unlicense"
] | 16
|
2018-01-14T09:53:12.000Z
|
2022-03-20T00:34:56.000Z
|
/*
Copyright (c) 2015 Xavier Leclercq
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#include "WxColourPickerCtrl1Frame.h"
#include "WindowIDs.h"
#include <wx/panel.h>
#include <wx/sizer.h>
WxColourPickerCtrl1Frame::WxColourPickerCtrl1Frame(const wxString& title)
: wxFrame(NULL, wxID_ANY, title), m_textCtrl(0)
{
// Create a top-level panel to hold all the contents of the frame
wxPanel* panel = new wxPanel(this, wxID_ANY);
// Create a wxTextCtrl to have some text we can select the color of
m_textCtrl = new wxTextCtrl(panel, wxID_ANY, "Some text of the selected color.",
wxDefaultPosition, wxSize(200, wxDefaultCoord));
// Create a wxColourPickerCtrl control
wxColourPickerCtrl* colourPickerCtrl = new wxColourPickerCtrl(panel, ColourPickerID);
// Set up the sizer for the panel
wxBoxSizer* panelSizer = new wxBoxSizer(wxHORIZONTAL);
panelSizer->Add(m_textCtrl, 0, wxEXPAND | wxALL, 15);
panelSizer->Add(colourPickerCtrl, 0, wxEXPAND | wxALL, 15);
panel->SetSizer(panelSizer);
// Set up the sizer for the frame and resize the frame
// according to its contents
wxBoxSizer* topSizer = new wxBoxSizer(wxHORIZONTAL);
topSizer->Add(panel, 1, wxEXPAND);
SetSizerAndFit(topSizer);
}
void WxColourPickerCtrl1Frame::OnColourChanged(wxColourPickerEvent& evt)
{
// Use the wxColourPickerEvent::GetColour() function to get the selected
// color and set the color of the text control accordingly.
m_textCtrl->SetForegroundColour(evt.GetColour());
m_textCtrl->Refresh();
}
// Add the event handler to the event table. As you can see we use the
// window ID to link the event handler to the wxColourPickerCtrl we created.
wxBEGIN_EVENT_TABLE(WxColourPickerCtrl1Frame, wxFrame)
EVT_COLOURPICKER_CHANGED(ColourPickerID, WxColourPickerCtrl1Frame::OnColourChanged)
wxEND_EVENT_TABLE()
| 43.567164
| 89
| 0.7506
|
wxIshiko
|
0d20612ce77898f7ac8dbf6c3b055826f72b798d
| 3,010
|
cpp
|
C++
|
src/dialog/vinserttabledialog.cpp
|
linails/vnote
|
97810731db97292f474951c3450aac150acef0bc
|
[
"MIT"
] | 1
|
2020-10-13T14:28:59.000Z
|
2020-10-13T14:28:59.000Z
|
src/dialog/vinserttabledialog.cpp
|
linails/vnote
|
97810731db97292f474951c3450aac150acef0bc
|
[
"MIT"
] | 1
|
2022-01-22T13:10:44.000Z
|
2022-01-22T13:10:44.000Z
|
src/dialog/vinserttabledialog.cpp
|
linails/vnote
|
97810731db97292f474951c3450aac150acef0bc
|
[
"MIT"
] | 1
|
2021-06-17T02:43:27.000Z
|
2021-06-17T02:43:27.000Z
|
#include "vinserttabledialog.h"
#include <QSpinBox>
#include <QRadioButton>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QDialogButtonBox>
#include <QPushButton>
#include <QButtonGroup>
VInsertTableDialog::VInsertTableDialog(QWidget *p_parent)
: QDialog(p_parent),
m_alignment(VTable::None)
{
setupUI();
}
void VInsertTableDialog::setupUI()
{
m_rowCount = new QSpinBox(this);
m_rowCount->setToolTip(tr("Number of rows of the table body"));
m_rowCount->setMaximum(1000);
m_rowCount->setMinimum(0);
m_colCount = new QSpinBox(this);
m_colCount->setToolTip(tr("Number of columns of the table"));
m_colCount->setMaximum(1000);
m_colCount->setMinimum(1);
QRadioButton *noneBtn = new QRadioButton(tr("None"), this);
QRadioButton *leftBtn = new QRadioButton(tr("Left"), this);
QRadioButton *centerBtn = new QRadioButton(tr("Center"), this);
QRadioButton *rightBtn = new QRadioButton(tr("Right"), this);
QHBoxLayout *alignLayout = new QHBoxLayout();
alignLayout->addWidget(noneBtn);
alignLayout->addWidget(leftBtn);
alignLayout->addWidget(centerBtn);
alignLayout->addWidget(rightBtn);
alignLayout->addStretch();
noneBtn->setChecked(true);
QButtonGroup *bg = new QButtonGroup(this);
bg->addButton(noneBtn, VTable::None);
bg->addButton(leftBtn, VTable::Left);
bg->addButton(centerBtn, VTable::Center);
bg->addButton(rightBtn, VTable::Right);
connect(bg, static_cast<void(QButtonGroup::*)(int, bool)>(&QButtonGroup::buttonToggled),
this, [this](int p_id, bool p_checked){
if (p_checked) {
m_alignment = static_cast<VTable::Alignment>(p_id);
}
});
QGridLayout *topLayout = new QGridLayout();
topLayout->addWidget(new QLabel(tr("Row:")), 0, 0, 1, 1);
topLayout->addWidget(m_rowCount, 0, 1, 1, 1);
topLayout->addWidget(new QLabel(tr("Column:")), 0, 2, 1, 1);
topLayout->addWidget(m_colCount, 0, 3, 1, 1);
topLayout->addWidget(new QLabel(tr("Alignment:")), 1, 0, 1, 1);
topLayout->addLayout(alignLayout, 1, 1, 1, 3);
// Ok is the default button.
m_btnBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(m_btnBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(m_btnBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
QPushButton *okBtn = m_btnBox->button(QDialogButtonBox::Ok);
okBtn->setProperty("SpecialBtn", true);
QVBoxLayout *mainLayout = new QVBoxLayout();
mainLayout->addLayout(topLayout);
mainLayout->addWidget(m_btnBox);
setLayout(mainLayout);
setWindowTitle(tr("Insert Table"));
}
int VInsertTableDialog::getRowCount() const
{
return m_rowCount->value();
}
int VInsertTableDialog::getColumnCount() const
{
return m_colCount->value();
}
VTable::Alignment VInsertTableDialog::getAlignment() const
{
return m_alignment;
}
| 31.354167
| 92
| 0.68505
|
linails
|
0d22b3c91dc6464f08e620187d9368e7af62be64
| 5,644
|
hpp
|
C++
|
pythran/pythonic/numpy/reduce.hpp
|
xmar/pythran
|
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
|
[
"BSD-3-Clause"
] | null | null | null |
pythran/pythonic/numpy/reduce.hpp
|
xmar/pythran
|
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
|
[
"BSD-3-Clause"
] | null | null | null |
pythran/pythonic/numpy/reduce.hpp
|
xmar/pythran
|
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef PYTHONIC_NUMPY_REDUCE_HPP
#define PYTHONIC_NUMPY_REDUCE_HPP
#include "pythonic/include/numpy/reduce.hpp"
#include "pythonic/types/ndarray.hpp"
#include "pythonic/__builtin__/None.hpp"
#include "pythonic/__builtin__/ValueError.hpp"
#include "pythonic/utils/neutral.hpp"
#include <algorithm>
namespace pythonic
{
namespace numpy
{
template <class Op, size_t N, class vector_form>
struct _reduce {
template <class E, class F>
F operator()(E e, F acc)
{
for (auto const &value : e)
acc = _reduce<Op, N - 1, vector_form>{}(value, acc);
return acc;
}
};
template <class Op, class vector_form>
struct _reduce<Op, 1, vector_form> {
template <class E, class F>
F operator()(E e, F acc)
{
for (auto const &value : e)
Op{}(acc, value);
return acc;
}
};
#ifdef USE_BOOST_SIMD
template <class vectorizer, class Op, class E, class F>
F vreduce(E e, F acc)
{
using T = typename E::dtype;
using vT = boost::simd::pack<T>;
static const size_t vN = vT::static_size;
const long n = e.size();
auto viter = vectorizer::vbegin(e), vend = vectorizer::vend(e);
const long bound = std::distance(viter, vend);
if (bound > 0) {
auto vacc = *viter;
++viter;
for (long i = 1; i < bound; ++i, ++viter)
Op{}(vacc, *viter);
alignas(sizeof(vT)) T stored[vN];
boost::simd::store(vacc, &stored[0]);
for (size_t j = 0; j < vN; ++j)
Op{}(acc, stored[j]);
}
auto iter = e.begin() + bound * vN;
for (long i = bound * vN; i < n; ++i, ++iter) {
Op{}(acc, *iter);
}
return acc;
}
template <class Op>
struct _reduce<Op, 1, types::vectorizer> {
template <class E, class F>
F operator()(E e, F acc)
{
return vreduce<types::vectorizer, Op>(e, acc);
}
};
template <class Op>
struct _reduce<Op, 1, types::vectorizer_nobroadcast> {
template <class E, class F>
F operator()(E e, F acc)
{
return vreduce<types::vectorizer_nobroadcast, Op>(e, acc);
}
};
#endif
template <class Op, class E, bool vector_form>
struct reduce_helper;
template <class Op, class E>
struct reduce_helper<Op, E, false> {
reduce_result_type<E> operator()(E const &expr,
reduce_result_type<E> p) const
{
return _reduce<Op, E::value, types::novectorizer>{}(expr, p);
}
};
template <class Op, class E>
struct reduce_helper<Op, E, true> {
reduce_result_type<E> operator()(E const &expr,
reduce_result_type<E> p) const
{
if (utils::no_broadcast(expr))
return _reduce<Op, E::value, types::vectorizer_nobroadcast>{}(expr,
p);
else
return _reduce<Op, E::value, types::vectorizer>{}(expr, p);
}
};
template <class Op, class E>
typename std::enable_if<types::is_numexpr_arg<E>::value,
reduce_result_type<E>>::type
reduce(E const &expr, types::none_type)
{
bool constexpr is_vectorizable =
E::is_vectorizable and
not std::is_same<typename E::dtype, bool>::value;
reduce_result_type<E> p = utils::neutral<Op, typename E::dtype>::value;
return reduce_helper<Op, E, is_vectorizable>{}(expr, p);
}
template <class Op, class E>
typename std::enable_if<
std::is_scalar<E>::value or types::is_complex<E>::value, E>::type
reduce(E const &expr, types::none_type)
{
return expr;
}
template <class Op, class E>
auto reduce(E const &array, long axis) ->
typename std::enable_if<std::is_scalar<E>::value or
types::is_complex<E>::value,
decltype(reduce<Op>(array))>::type
{
if (axis != 0)
throw types::ValueError("axis out of bounds");
return reduce<Op>(array);
}
template <class Op, class E>
auto reduce(E const &array, long axis) ->
typename std::enable_if<E::value == 1,
decltype(reduce<Op>(array))>::type
{
if (axis != 0)
throw types::ValueError("axis out of bounds");
return reduce<Op>(array);
}
template <class Op, class E>
typename std::enable_if<E::value != 1, reduced_type<E>>::type
reduce(E const &array, long axis)
{
if (axis < 0)
axis += E::value;
if (axis < 0 || size_t(axis) >= E::value)
throw types::ValueError("axis out of bounds");
auto shape = array.shape();
if (axis == 0) {
types::array<long, E::value - 1> shp;
std::copy(shape.begin() + 1, shape.end(), shp.begin());
return _reduce<Op, 1, types::novectorizer /* not on scalars*/>{}(
array,
reduced_type<E>{shp, utils::neutral<Op, typename E::dtype>::value});
} else {
types::array<long, E::value - 1> shp;
auto next = std::copy(shape.begin(), shape.begin() + axis, shp.begin());
std::copy(shape.begin() + axis + 1, shape.end(), next);
reduced_type<E> sumy{shp, __builtin__::None};
std::transform(array.begin(), array.end(), sumy.begin(),
[axis](typename E::const_iterator::value_type other) {
return reduce<Op>(other, axis - 1);
});
return sumy;
}
}
}
}
#endif
| 31.18232
| 80
| 0.546244
|
xmar
|
0d2d08597e179e4c55fc483afeed40178a2fc5e5
| 1,804
|
hpp
|
C++
|
host/include/serial_can_dump.hpp
|
hephaisto/serial-can-dump
|
a3aa3e6e166327ad86b491ca8d89fbcc1090f597
|
[
"MIT"
] | 1
|
2016-09-20T20:20:00.000Z
|
2016-09-20T20:20:00.000Z
|
host/include/serial_can_dump.hpp
|
hephaisto/serial-can-dump
|
a3aa3e6e166327ad86b491ca8d89fbcc1090f597
|
[
"MIT"
] | null | null | null |
host/include/serial_can_dump.hpp
|
hephaisto/serial-can-dump
|
a3aa3e6e166327ad86b491ca8d89fbcc1090f597
|
[
"MIT"
] | null | null | null |
#include <memory>
#include <string>
#include <boost/signals2.hpp>
#include <boost/asio.hpp>
namespace bs2 = boost::signals2;
class ExtendedCanFrame
{
public:
ExtendedCanFrame(const uint32_t id, const uint8_t data_len, const uint8_t *data, const bool rtr=false);
ExtendedCanFrame(const uint32_t id, const bool rtr=false);
ExtendedCanFrame(const uint32_t id, const uint8_t data, const bool rtr=false);
ExtendedCanFrame(const uint32_t id, const int8_t data, const bool rtr=false);
ExtendedCanFrame(const uint32_t id, const uint16_t data, const bool rtr=false);
ExtendedCanFrame(const uint32_t id, const int16_t data, const bool rtr=false);
~ExtendedCanFrame();
uint32_t id;
uint8_t data_len;
uint8_t *data;
bool rtr;
uint8_t getData_uint8() const;
int8_t getData_int8() const;
uint16_t getData_uint16() const;
int16_t getData_int16() const;
};
typedef bs2::signal<void (std::shared_ptr<const ExtendedCanFrame>)> ReceiveSignal;
class SerialCanDumpPort
{
public:
SerialCanDumpPort(boost::asio::io_service &io, const std::string &device, unsigned int baud_rate);
~SerialCanDumpPort();
ReceiveSignal& onReceive();
void send(const ExtendedCanFrame& frame);
void startWaitingForPacket();
void threadWorker(boost::asio::io_service &io);
private:
static const size_t HEADER_LEN = 5;
static const size_t MAX_DATA_LEN = 16;
static const size_t DATA_LEN_FIELD = 4;
static const uint32_t EXT_MASK = (1 << (5+24) );
static const uint32_t RTR_MASK = (1 << (6+24) );
static const uint32_t ID_MASK = ~( RTR_MASK | EXT_MASK );
ReceiveSignal _onReceive;
boost::asio::serial_port serial;
uint8_t* getDataBuffer();
void handleHeader(const boost::system::error_code& error);
void handleData(const boost::system::error_code& error);
uint8_t serialBuffer[HEADER_LEN + MAX_DATA_LEN];
};
| 30.066667
| 104
| 0.764412
|
hephaisto
|
0d2f8d0b7c16eab8cc09638155ac707c42c53665
| 4,256
|
cpp
|
C++
|
Sources/Modules/Renderer/Stub/RendererStub.cpp
|
benkaraban/anima-games-engine
|
8aa7a5368933f1b82c90f24814f1447119346c3b
|
[
"BSD-3-Clause"
] | 2
|
2015-04-16T01:05:53.000Z
|
2019-08-26T07:38:43.000Z
|
Sources/Modules/Renderer/Stub/RendererStub.cpp
|
benkaraban/anima-games-engine
|
8aa7a5368933f1b82c90f24814f1447119346c3b
|
[
"BSD-3-Clause"
] | null | null | null |
Sources/Modules/Renderer/Stub/RendererStub.cpp
|
benkaraban/anima-games-engine
|
8aa7a5368933f1b82c90f24814f1447119346c3b
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider,
* Jérémie Comarmond, Didier Colin.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <Renderer/Stub/RendererStub.h>
#include <Renderer/Stub/RenderViewStub.h>
#include <Renderer/Stub/SceneStub.h>
#include <Renderer/Stub/MeshStub.h>
#include <Renderer/Stub/TextureStub.h>
namespace Renderer
{
//-----------------------------------------------------------------------------
RendererStub::RendererStub() :
_pDefaultView(new RenderViewStub(100, 100)),
_pDefaultTexture(new TextureMapStub(null))
{
}
//-----------------------------------------------------------------------------
bool RendererStub::initialise()
{
return true;
}
//-----------------------------------------------------------------------------
Ptr<IMesh> RendererStub::uploadMesh(const Ptr<Assets::ModelMesh> & pMesh, ITextureGrabber & texGrabber)
{
return Ptr<IMesh>(new MeshStub(pMesh));
}
//-----------------------------------------------------------------------------
Ptr<ISkinMesh> RendererStub::uploadSkinMesh(const Ptr<Assets::ModelMesh> & pMesh, ITextureGrabber & texGrabber)
{
return Ptr<ISkinMesh>(new SkinMeshStub(pMesh));
}
//-----------------------------------------------------------------------------
Ptr<ITextureMap> RendererStub::uploadTexture(const Ptr<Assets::Texture> & pTexture)
{
return Ptr<ITextureMap>(new TextureMapStub(pTexture));
}
//-----------------------------------------------------------------------------
Ptr<ICubeTextureMap> RendererStub::uploadTexture(const Ptr<Assets::CubeTexture> & pTexture)
{
return Ptr<ICubeTextureMap>(null);
}
//-----------------------------------------------------------------------------
Ptr<IScene> RendererStub::createScene()
{
return Ptr<IScene>(new SceneStub());
}
//-----------------------------------------------------------------------------
Ptr<ITextureMap> RendererStub::getDefaultTexture() const
{
return _pDefaultTexture;
}
//-----------------------------------------------------------------------------
void RendererStub::renderScene(const Ptr<IRenderView> & pView, const Ptr<IScene> & pScene, const Ptr<ICamera> & pCamera)
{
}
//-----------------------------------------------------------------------------
Ptr<IRenderView> RendererStub::getDefaultView() const
{
return _pDefaultView;
}
//-----------------------------------------------------------------------------
Ptr<IRenderView> RendererStub::createView(int32 width, int32 height, int32 bufferCount, void * pHandle)
{
return Ptr<IRenderView>(new RenderViewStub(width, height));
}
//-----------------------------------------------------------------------------
}
| 44.8
| 121
| 0.574718
|
benkaraban
|
0d2ff67406c27f944c704f1a3394a211baa512ca
| 18,585
|
cpp
|
C++
|
source/fontpage.cpp
|
tomorrow-wakeup/Font-Creator-For-Unity3D
|
6bcb740def77679f8f6f7d9c08e4c6afca6fe2ab
|
[
"BSD-3-Clause"
] | null | null | null |
source/fontpage.cpp
|
tomorrow-wakeup/Font-Creator-For-Unity3D
|
6bcb740def77679f8f6f7d9c08e4c6afca6fe2ab
|
[
"BSD-3-Clause"
] | null | null | null |
source/fontpage.cpp
|
tomorrow-wakeup/Font-Creator-For-Unity3D
|
6bcb740def77679f8f6f7d9c08e4c6afca6fe2ab
|
[
"BSD-3-Clause"
] | 1
|
2019-09-09T06:44:23.000Z
|
2019-09-09T06:44:23.000Z
|
/*
AngelCode Bitmap Font Generator
Copyright (c) 2004-2014 Andreas Jonsson
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you
must not claim that you wrote the original software. If you use
this software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
Andreas Jonsson
andreas@angelcode.com
*/
#include <algorithm>
#include <fstream>
#include "fontpage.h"
#include "fontchar.h"
#include "fontgen.h"
using namespace std;
#define CLR_BORDER 0x007F00ul
#define CLR_UNUSED 0xFF0000ul
CFontPage::CFontPage(CFontGen *gen, int id, int width, int height, int spacingH, int spacingV)
{
this->gen = gen;
pageId = id;
// Allocate and clear the image with the unused color
pageImg = new (std::nothrow) cImage(width, height);
pageImg->Clear(CLR_UNUSED);
// Initialize the height array that shows free space
heights[0] = new (std::nothrow) int[width];
if( heights[0] )
memset(heights[0], 0, width*4);
heights[1] = 0;
heights[2] = 0;
heights[3] = 0;
currX = 0;
this->spacingH = spacingH;
this->spacingV = spacingV;
paddingRight = 0;
paddingLeft = 0;
paddingUp = 0;
paddingDown = 0;
}
bool CFontPage::IsOK()
{
if( pageImg == 0 || heights[0] == 0 ) return false;
if( pageImg->pixels == 0 ) return false;
return true;
}
CFontPage::~CFontPage()
{
if( pageImg )
delete pageImg;
for( int n = 0; n < 4; n++ )
if( heights[n] )
delete[] heights[n];
}
void CFontPage::SetIntendedFormat(int bitDepth, bool fourChnlPacked, int a, int r, int g, int b)
{
this->bitDepth = bitDepth;
this->fourChnlPacked = fourChnlPacked;
alphaChnl = a;
redChnl = r;
greenChnl = g;
blueChnl = b;
}
void CFontPage::AddChar(int cx, int cy, CFontChar *ch, int channel)
{
// Update the charInfo with the extra draw rect
ch->m_x = cx;
ch->m_y = cy;
ch->m_page = pageId;
ch->m_width += paddingLeft + paddingRight;
ch->m_height += paddingUp + paddingDown;
ch->m_xoffset -= paddingLeft;
ch->m_yoffset -= paddingUp;
if( bitDepth == 32 && fourChnlPacked )
ch->m_chnl = !ch->m_isChar ? 0xF : 1<<channel;
else
ch->m_chnl = 0xF;
// Update heights
cImage *img = ch->m_charImg;
for( int x = -spacingH; x < img->width + paddingLeft + paddingRight + spacingH; x++ )
{
int tempX = x + cx;
if( tempX < 0 ) tempX += pageImg->width;
if( cy + img->height + spacingV + paddingUp + paddingDown > heights[channel][tempX] )
heights[channel][tempX] = cy + img->height + spacingV + paddingUp + paddingDown;
}
chars.push_back(ch);
// Increment counter in CFontGen
gen->counter++;
}
int CFontPage::AddChar(CFontChar *ch, int channel)
{
int origX = currX;
cImage *img = ch->m_charImg;
// Iterate for each possible x position
int i = 0;
while( i++ < pageImg->width - img->width - paddingRight - paddingLeft - spacingH )
{
// Is the character narrow enough to fit?
if( img->width + currX + paddingRight + paddingLeft > pageImg->width - spacingH )
{
// Start from the left side again
currX = 0;
}
// Will the character fit in this place?
int cy = 0;
for( int n = 0; n < img->width + paddingLeft + paddingRight; n++ )
{
if( heights[channel][n+currX] > cy )
cy = heights[channel][n+currX];
}
if( cy + img->height + paddingUp + paddingDown <= pageImg->height - spacingV )
{
// Are we creating any holes?
for( int x = 0; x < img->width + paddingLeft + paddingRight; x++ )
{
int tempX = x + currX;
if( cy - spacingV > heights[channel][tempX] )
{
SHole hole;
hole.x = tempX;
hole.y = heights[channel][tempX];
hole.w = 1;
hole.h = cy - spacingV - hole.y;
hole.chnl = channel;
// Determine the width of the hole
for( x++; x < img->width + paddingLeft + paddingRight; x++ )
{
int tempX = x + currX;
if( hole.y == heights[channel][tempX] )
hole.w++;
else
break;
}
// TODO: Should need to search for more holes.
holes.push_back(hole);
break;
}
}
AddChar(currX, cy, ch, channel);
currX += img->width + spacingH + paddingLeft + paddingRight;
return 0;
}
else
{
currX++;
}
}
currX = origX;
return -1;
}
cImage *CFontPage::GetPageImage()
{
return pageImg;
}
void CFontPage::SetPadding(int left, int up, int right, int down)
{
paddingLeft = left;
paddingUp = up;
paddingRight = right;
paddingDown = down;
}
int CFontPage::GetNextIdealImageWidth()
{
return pageImg->width - currX - paddingRight - paddingLeft - spacingH;
}
void CFontPage::GeneratePreviewTexture(int channel)
{
pageImg->Clear(CLR_UNUSED);
// Copy the font char images to the texture
for( unsigned int n = 0; n < chars.size(); n++ )
{
if( chars[n]->m_chnl & (1<<channel) )
{
int cx = chars[n]->m_x + paddingLeft;
int cy = chars[n]->m_y + paddingUp;
cImage *img = chars[n]->m_charImg;
if( chars[n]->HasOutline() )
{
// Show the outline, by blending against blue background
for( int y = 0; y < img->height; y++ )
{
for( int x = 0; x < img->width; x++ )
{
DWORD p = img->pixels[y*img->width+x];
if( (p >> 24) < 0xFF )
p += 255 - (p>>24);
pageImg->pixels[(y+cy)*pageImg->width+(x+cx)] = p;
}
}
}
else
{
for( int y = 0; y < img->height; y++ )
{
for( int x = 0; x < img->width; x++ )
pageImg->pixels[(y+cy)*pageImg->width+(x+cx)] = img->pixels[y*img->width+x];
}
}
// Draw the spacing borders
if( spacingH > 0 )
{
int cx1 = chars[n]->m_x - 1;
if( cx1 < 0 ) cx1 += pageImg->width;
int cx2 = chars[n]->m_x + chars[n]->m_width;
if( cx2 >= pageImg->width ) cx2 -= pageImg->width;
int cy = chars[n]->m_y;
for( int y = 0; y < chars[n]->m_height; y++ )
{
pageImg->pixels[(cy+y)*pageImg->width+cx1] = CLR_BORDER;
pageImg->pixels[(cy+y)*pageImg->width+cx2] = CLR_BORDER;
}
}
if( spacingV > 0 )
{
int cy1 = chars[n]->m_y - 1;
if( cy1 < 0 ) cy1 += pageImg->height;
int cy2 = chars[n]->m_y + chars[n]->m_height;
if( cy2 >= pageImg->height ) cy2 -= pageImg->height;
int cx = chars[n]->m_x;
for( int x = 0; x < chars[n]->m_width; x++ )
{
pageImg->pixels[cy1*pageImg->width+x+cx] = CLR_BORDER;
pageImg->pixels[cy2*pageImg->width+x+cx] = CLR_BORDER;
}
}
}
}
}
void CFontPage::GenerateOutputTexture()
{
// Clear the image
DWORD color = 0;
if( alphaChnl == e_one && !gen->IsAlphaInverted() || gen->IsAlphaInverted() )
color = 0xFF << 24;
if( fourChnlPacked )
{
// Fill all channels with the same color
color |= (color >> 24) << 16;
color |= (color >> 24) << 8;
color |= (color >> 24);
}
else
{
if( redChnl == e_one && !gen->IsRedInverted() || gen->IsRedInverted() )
color |= 0xFF << 16;
if( greenChnl == e_one && !gen->IsGreenInverted() || gen->IsGreenInverted() )
color |= 0xFF << 8;
if( blueChnl == e_one && !gen->IsBlueInverted() || gen->IsBlueInverted() )
color |= 0xFF;
}
pageImg->Clear(color);
// Copy the font char images to the texture
for( unsigned int n = 0; n < chars.size(); n++ )
{
int cx = chars[n]->m_x + paddingLeft;
int cy = chars[n]->m_y + paddingUp;
cImage *img = chars[n]->m_charImg;
if( !chars[n]->m_isChar )
{
// Colored images are copied as is
for( int y = 0; y < img->height; y++ )
{
for( int x = 0; x < img->width; x++ )
pageImg->pixels[(y+cy)*pageImg->width+(x+cx)] = img->pixels[y*img->width+x];
}
}
else
{
if( bitDepth == 32 && fourChnlPacked )
{
// When packing multiple characters we
// use the alpha channel to determine the content
for( int y = 0; y < img->height; y++ )
{
for( int x = 0; x < img->width; x++ )
{
DWORD p = chars[n]->GetPixelValue(x, y, alphaChnl);
if( gen->IsAlphaInverted() ) p = 255 - p;
DWORD c = pageImg->pixels[(y+cy)*pageImg->width+(x+cx)];
if( chars[n]->m_chnl == 1 )
{
c &= 0xFFFFFF00;
c |= p;
}
else if( chars[n]->m_chnl == 2 )
{
c &= 0xFFFF00FF;
c |= p << 8;
}
else if( chars[n]->m_chnl == 4 )
{
c &= 0xFF00FFFF;
c |= p << 16;
}
else if( chars[n]->m_chnl == 8 )
{
c &= 0x00FFFFFF;
c |= p << 24;
}
pageImg->pixels[(y+cy)*pageImg->width+(x+cx)] = c;
}
}
}
else
{
for( int y = 0; y < img->height; y++ )
{
for( int x = 0; x < img->width; x++ )
{
DWORD p = 0;
DWORD t;
t = (BYTE)chars[n]->GetPixelValue(x, y, blueChnl); if( gen->IsBlueInverted() ) t = 255 - t; p |= t << 0;
t = (BYTE)chars[n]->GetPixelValue(x, y, greenChnl); if( gen->IsGreenInverted() ) t = 255 - t; p |= t << 8;
t = (BYTE)chars[n]->GetPixelValue(x, y, redChnl); if( gen->IsRedInverted() ) t = 255 - t; p |= t << 16;
t = (BYTE)chars[n]->GetPixelValue(x, y, alphaChnl); if( gen->IsAlphaInverted() ) t = 255 - t; p |= t << 24;
pageImg->pixels[(y+cy)*pageImg->width+(x+cx)] = p;
}
}
}
}
}
}
// This global pointer will be used by the sorting algorithm
CFontChar **g_chars = 0;
// Define a structure and comparison operator for the sorting algorithm
struct element { int index; };
bool operator<(const element &a, const element &b)
{
// We want to sort the characters from larger to smaller
if( g_chars[a.index]->m_height > g_chars[b.index]->m_height ||
(g_chars[a.index]->m_height == g_chars[b.index]->m_height &&
g_chars[a.index]->m_width > g_chars[b.index]->m_width) )
return true;
return false;
}
void CFontPage::SortList(CFontChar **chars, int *index, int numChars)
{
g_chars = chars;
std::sort((element*)index, (element*)(&index[numChars]));
}
#ifdef TRACE_GENERATE
extern ofstream trace;
#endif
void CFontPage::AddChars(CFontChar **chars, int maxChars)
{
#ifdef TRACE_GENERATE
trace << "Adding colored images\n";
trace.flush();
#endif
// Add the colored images first
AddCharsToPage(chars, maxChars, true, 0);
// Check if we should stop
if( gen->stopWorking ) return;
#ifdef TRACE_GENERATE
trace << "Duplicating the height array to all channels\n";
trace.flush();
#endif
// Duplicate the height array for the other channels
for( int n = 1; n < 4; n++ )
{
heights[n] = new (std::nothrow) int[pageImg->width];
if( heights[n] == 0 )
{
#ifdef TRACE_GENERATE
trace << "Out of memory while allocating height buffer\n";
trace.flush();
#endif
gen->stopWorking = true;
gen->outOfMemory = true;
return;
}
memcpy(heights[n], heights[0], pageImg->width*sizeof(int));
}
// Remove the current holes
holes.resize(0);
#ifdef TRACE_GENERATE
trace << "Adding monochrome images to channel 0\n";
trace.flush();
#endif
// Then the black & white images
AddCharsToPage(chars, maxChars, false, 0);
// Check if we should stop
if( gen->stopWorking ) return;
if( bitDepth == 32 && fourChnlPacked )
{
for( int n = 1; n < 4; n++ )
{
#ifdef TRACE_GENERATE
trace << "Adding monochrome images to channel " << n << "\n";
trace.flush();
#endif
AddCharsToPage(chars, maxChars, false, n);
// Check if we should stop
if( gen->stopWorking ) return;
}
}
}
void CFontPage::AddCharsToPage(CFontChar **chars, int maxChars, bool colored, int channel)
{
static int indexA[maxUnicodeChar+1], indexB[maxUnicodeChar+1];
int *index = indexA, *index2 = indexB;
int numChars = 0, numChars2 = 0;
// Add images to the list
for( int n = 0; n < maxChars; n++ )
{
if( chars[n] && chars[n]->m_isChar != colored )
index[numChars++] = n;
}
#ifdef TRACE_GENERATE
trace << "Sorting list of " << numChars << " candidates\n";
trace.flush();
#endif
// Sort the characters by height/width, largest first
SortList(chars, index, numChars);
// Add the images to the page
while( numChars > 0 )
{
#ifdef TRACE_GENERATE
trace << "There are " << numChars << " candidates left, and " << holes.size() << " holes to fill\n";
trace.flush();
#endif
// Fill holes
for( int h = 0; h < (signed)holes.size(); h++ )
{
int bestMatch;
bestMatch = -1;
// Find the best matching character to fill the hole
for( int n = 0; n < numChars; n++ )
{
if( (holes[h].w == chars[index[n]]->m_charImg->width + paddingLeft + paddingRight) &&
(holes[h].h == chars[index[n]]->m_charImg->height + paddingUp + paddingDown) )
{
bestMatch = n;
break;
}
else if( (holes[h].w >= chars[index[n]]->m_charImg->width + paddingLeft + paddingRight) &&
(holes[h].h >= chars[index[n]]->m_charImg->height + paddingUp + paddingDown) )
{
if( bestMatch != -1 )
{
if( (chars[index[n]]->m_charImg->width > chars[index[bestMatch]]->m_charImg->width) ||
(chars[index[n]]->m_charImg->height > chars[index[bestMatch]]->m_charImg->height) )
bestMatch = n;
}
else
bestMatch = n;
}
}
if( bestMatch != -1 )
{
int x = holes[h].x;
int y = holes[h].y;
// There may still be room for more
if( holes[h].w - spacingH > chars[index[bestMatch]]->m_charImg->width + paddingLeft + paddingRight )
{
// Create a new hole to the right of the newly inserted character, with the same height of the previous hole
SHole hole2;
hole2.x = holes[h].x + (chars[index[bestMatch]]->m_charImg->width + paddingLeft + paddingRight + spacingH);
hole2.y = holes[h].y;
hole2.w = holes[h].w - (chars[index[bestMatch]]->m_charImg->width + paddingLeft + paddingRight + spacingH);
hole2.h = holes[h].h;
hole2.chnl = holes[h].chnl;
holes.push_back(hole2);
}
if( holes[h].h - spacingV > chars[index[bestMatch]]->m_charImg->height + paddingUp + paddingDown )
{
// Create a new hole below the newly inserted character, with the width of the character
SHole hole2;
hole2.x = holes[h].x;
hole2.y = holes[h].y + (chars[index[bestMatch]]->m_charImg->height + paddingUp + paddingDown + spacingV);
hole2.w = (chars[index[bestMatch]]->m_charImg->width + paddingLeft + paddingRight);
hole2.h = holes[h].h - (chars[index[bestMatch]]->m_charImg->height + paddingUp + paddingDown + spacingV);
hole2.chnl = holes[h].chnl;
holes.push_back(hole2);
}
AddChar(x, y, chars[index[bestMatch]], channel);
chars[index[bestMatch]] = 0;
#ifdef TRACE_GENERATE
trace << "Character [" << index[bestMatch] << "] was used to fill hole\n";
trace.flush();
#endif
// Check if we should stop
if( gen->stopWorking ) return;
// Compact the list
numChars--;
for( int n = bestMatch; n < numChars; n++ )
index[n] = index[n+1];
}
// Remove the hole
if( h < (signed)holes.size() - 1 )
holes[h] = holes[holes.size()-1];
holes.pop_back();
h--;
}
#ifdef TRACE_GENERATE
trace << "All holes have been filled\n";
trace.flush();
#endif
numChars2 = 0;
bool allTooWide = true;
bool drawn = false;
// Determine if there is a large height difference anywhere, and if so start filling from that location
// This happens for example when importing images that are out of proportion to the rest of the glyphs
currX = DetermineStartX(chars, index, numChars, channel);
#ifdef TRACE_GENERATE
trace << "currX is " << currX << " and heights is " << heights[channel][currX] << "\n";
trace << "tallest char is " << chars[index[0]]->m_height << "x" << chars[index[0]]->m_width << " and shortest char is " << chars[index[numChars-1]]->m_height << "x" << chars[index[numChars-1]]->m_width << "\n";
trace << "GetNextIdealImageWidth() = " << GetNextIdealImageWidth() << "\n";
trace.flush();
#endif
// Sanity check. This could become negative if previous code failed to catch out of memory
if( GetNextIdealImageWidth() < 0 )
{
#ifdef TRACE_GENERATE
trace << "GetNextIdealImageWidth() < 0. Something is wrong\n";
trace.flush();
#endif
gen->stopWorking = true;
gen->outOfMemory = true;
return;
}
// Add one row of chars to texture
for( int n = 0; n < numChars; n++ )
{
bool ok = false;
if( chars[index[n]]->m_charImg->width <= GetNextIdealImageWidth() )
{
allTooWide = false;
int r = AddChar(chars[index[n]], channel);
if( r >= 0 )
{
#ifdef TRACE_GENERATE
trace << "Character [" << index[n] << "] was added\n";
trace.flush();
#endif
chars[index[n]] = 0;
ok = true;
drawn = true;
// Check if we should stop
if( gen->stopWorking ) return;
}
}
if( !ok )
{
#ifdef TRACE_GENERATE
// trace << "Character [" << index[n] << "] didn't fit on this row\n";
// trace.flush();
#endif
// Move it to the next index list
index2[numChars2++] = index[n];
}
}
if( index == indexA )
{
// Swap indices
index = indexB;
index2 = indexA;
}
else
{
index = indexA;
index2 = indexB;
}
numChars = numChars2;
numChars2 = 0;
#ifdef TRACE_GENERATE
trace << "allTooWide = " << allTooWide << ", drawn = " << drawn << "\n";
trace.flush();
#endif
if( !allTooWide && !drawn )
{
// Next page
break;
}
}
}
int CFontPage::DetermineStartX(CFontChar **chars, int *index, int numChars, int channel)
{
int startX = 0;
// Determine if there is a large height difference anywhere, and if so start filling from that location
// This happens for example when importing images that are out of proportion to the rest of the glyphs
int thinnestChar = pageImg->width;
for( int n = 0; n < numChars; n++ )
if( thinnestChar > (chars[index[n]]->m_width + paddingLeft + paddingRight + spacingH) )
thinnestChar = chars[index[n]]->m_width + paddingLeft + paddingRight + spacingH;
for( int n = 0; n < pageImg->width - 1 - thinnestChar; n++ )
{
// Compare against the largest glyph that we'll add (first in list)
if( heights[channel][n] - heights[channel][n+1] >= (chars[index[0]]->m_height + paddingUp + paddingDown + spacingV) )
{
startX = n+1;
break;
}
}
return startX;
}
| 26.324363
| 212
| 0.612429
|
tomorrow-wakeup
|
0d3a74e11d00f485465ebcb165fa432dc5095dc5
| 306
|
hpp
|
C++
|
vm/os-solaris-x86.64.hpp
|
seckar/factor
|
9683b081e3d93a996d00c91a139b533139dfb945
|
[
"BSD-2-Clause"
] | 1
|
2016-05-08T19:43:03.000Z
|
2016-05-08T19:43:03.000Z
|
vm/os-solaris-x86.64.hpp
|
seckar/factor
|
9683b081e3d93a996d00c91a139b533139dfb945
|
[
"BSD-2-Clause"
] | null | null | null |
vm/os-solaris-x86.64.hpp
|
seckar/factor
|
9683b081e3d93a996d00c91a139b533139dfb945
|
[
"BSD-2-Clause"
] | null | null | null |
#include <ucontext.h>
namespace factor
{
inline static void *ucontext_stack_pointer(void *uap)
{
ucontext_t *ucontext = (ucontext_t *)uap;
return (void *)ucontext->uc_mcontext.gregs[RSP];
}
#define UAP_PROGRAM_COUNTER(ucontext) \
(((ucontext_t *)(ucontext))->uc_mcontext.gregs[RIP])
}
| 19.125
| 56
| 0.699346
|
seckar
|
0d3c0e729231216556dd90d9abf9febc31be5e36
| 1,409
|
cpp
|
C++
|
plugins/ChannelMute/Source/PluginEditor.cpp
|
COx2/slPlugins
|
72f6e8e70b23e97d44d27001df02433585c7fb81
|
[
"BSD-3-Clause"
] | 39
|
2020-04-24T10:36:31.000Z
|
2022-02-15T17:09:03.000Z
|
plugins/ChannelMute/Source/PluginEditor.cpp
|
COx2/slPlugins
|
72f6e8e70b23e97d44d27001df02433585c7fb81
|
[
"BSD-3-Clause"
] | 3
|
2020-04-28T00:24:43.000Z
|
2020-11-09T21:43:34.000Z
|
plugins/ChannelMute/Source/PluginEditor.cpp
|
COx2/slPlugins
|
72f6e8e70b23e97d44d27001df02433585c7fb81
|
[
"BSD-3-Clause"
] | 5
|
2020-06-15T08:42:12.000Z
|
2021-06-10T06:49:57.000Z
|
/*
==============================================================================
This file was auto-generated by the Introjucer!
It contains the basic framework code for a JUCE plugin editor.
==============================================================================
*/
#include "PluginProcessor.h"
#include "PluginEditor.h"
using namespace gin;
//==============================================================================
ChannelMuteAudioProcessorEditor::ChannelMuteAudioProcessorEditor (ChannelMuteAudioProcessor& p)
: gin::ProcessorEditor (p), cmProcessor (p)
{
for (auto pp : p.getPluginParameters())
{
ParamComponent* pc;
if (pp->isOnOff())
pc = new Switch (pp);
else
pc = new Knob (pp);
addAndMakeVisible (pc);
controls.add (pc);
}
setGridSize (4, 1);
}
ChannelMuteAudioProcessorEditor::~ChannelMuteAudioProcessorEditor()
{
}
//==============================================================================
void ChannelMuteAudioProcessorEditor::resized()
{
gin::ProcessorEditor::resized();
componentForId (PARAM_MUTE_L)->setBounds (getGridArea (0, 0));
componentForId (PARAM_LEVEL_L)->setBounds (getGridArea (1, 0));
componentForId (PARAM_MUTE_R)->setBounds (getGridArea (2, 0));
componentForId (PARAM_LEVEL_R)->setBounds (getGridArea (3, 0));
}
| 28.18
| 95
| 0.51171
|
COx2
|
0d40e47199a89b577d1743a70e3572f4f2b20088
| 1,723
|
cpp
|
C++
|
array/pair-with-sum-in-unsorted-array.cpp
|
HarshitKaushik/ds-algorithms-revision
|
98fddca7b196179dd795dfde822a1d9bb1518b74
|
[
"MIT"
] | 1
|
2018-08-28T17:44:45.000Z
|
2018-08-28T17:44:45.000Z
|
array/pair-with-sum-in-unsorted-array.cpp
|
HarshitKaushik/ds-algorithms-revision
|
98fddca7b196179dd795dfde822a1d9bb1518b74
|
[
"MIT"
] | null | null | null |
array/pair-with-sum-in-unsorted-array.cpp
|
HarshitKaushik/ds-algorithms-revision
|
98fddca7b196179dd795dfde822a1d9bb1518b74
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
// Given an array A[] and a number x, check for pair in A[] with sum as x
// https://www.geeksforgeeks.org/write-a-c-program-that-given-a-set-a-of-n-numbers-and-another-number-x-determines-whether-or-not-there-exist-two-elements-in-s-whose-sum-is-exactly-x/
// Method to swap the integer values
void swapValues(int *i, int *j)
{
int temp = *i;
*i = *j;
*j = temp;
}
// Partition method to place last element in its right place in the array. All smaller and equal elements before it
// and all greater elements after it
int partition(int array[], int low, int high)
{
int pivot = array[high];
int i = low - 1;
for (int j = low; j < high; j++)
{
if (array[j] <= pivot)
{
i++;
swapValues(&array[i], &array[j]);
}
}
// Place pivot in its right place
swapValues(&array[i + 1], &array[high]);
return (i + 1);
}
// Recursive quick sort algorithm
void quickSort(int array[], int low, int high)
{
// low is lower index and high is upper index
// taking the last element as pivot
if (low < high)
{
int partitioningIndex = partition(array, low, high);
quickSort(array, low, partitioningIndex - 1);
quickSort(array, partitioningIndex + 1, high);
}
}
int main()
{
int arraySize = 10;
int testArray[] = { 8, 9 , 7, 4, 7, 2, 4, 1, 6, 9 };
int sumOfPair = 18;
quickSort(testArray, 0, arraySize - 1);
int i = 0;
int j = arraySize - 1;
while(i < j) {
if (testArray[i] + testArray[j] == sumOfPair) {
cout << testArray[i] << " " << testArray[j] << endl;
break;
} else if (testArray[i] + testArray[j] < sumOfPair) {
i++;
} else {
j++;
}
}
// Output
// 9 9
return 0;
}
| 24.971014
| 183
| 0.611143
|
HarshitKaushik
|
0d4686544a5e554f737ac86f116d4c7c3f948baa
| 435
|
cpp
|
C++
|
LAB-1/CODE/Lab-1-Program-5-Write a program to receive marks of physics, chemistry & maths from user.cpp
|
CSIT-Knowledge-Hub-EBulk/PPS-C-Lang.-Lab-Based-Programs-AKTU--KCS-151P-KCS-251P-
|
7e6fcf1658d7122cfeeb04ce97ecda0355f6c4e1
|
[
"Apache-2.0"
] | 2
|
2022-02-24T14:28:03.000Z
|
2022-03-03T06:18:10.000Z
|
LAB-1/CODE/Lab-1-Program-5-Write a program to receive marks of physics, chemistry & maths from user.cpp
|
CSIT-Knowledge-Hub-EBulk/PPS-C-Lang.-Lab-Based-Programs-AKTU--KCS-151P-KCS-251P-
|
7e6fcf1658d7122cfeeb04ce97ecda0355f6c4e1
|
[
"Apache-2.0"
] | null | null | null |
LAB-1/CODE/Lab-1-Program-5-Write a program to receive marks of physics, chemistry & maths from user.cpp
|
CSIT-Knowledge-Hub-EBulk/PPS-C-Lang.-Lab-Based-Programs-AKTU--KCS-151P-KCS-251P-
|
7e6fcf1658d7122cfeeb04ce97ecda0355f6c4e1
|
[
"Apache-2.0"
] | null | null | null |
#include<stdio.h>
#include<math.h>
int main()
{
int phy,che,math,total,PM;
printf("Enter the marks of the physics chemistry and math's\n");
scanf("%d%d%d",&phy,&che,&math);
total=(phy+che+math);
PM=phy+math;
if(phy>40 && che>50 && math>60 && (PM>150||total>200))
{
printf("You are eligible for the course\n");
}
else
printf("Not eligible\n");
return 0;
}
| 22.894737
| 69
| 0.542529
|
CSIT-Knowledge-Hub-EBulk
|
0d4bf48003af45391df0befebd85e79a05dbde89
| 182
|
cpp
|
C++
|
server/main.cpp
|
kaiqiangren/webrtc
|
f898ba54714a58d387282b4a9bbd4ab2b9bc7659
|
[
"MIT"
] | 1
|
2020-06-16T05:05:40.000Z
|
2020-06-16T05:05:40.000Z
|
server/main.cpp
|
kaiqiangren/webrtc
|
f898ba54714a58d387282b4a9bbd4ab2b9bc7659
|
[
"MIT"
] | null | null | null |
server/main.cpp
|
kaiqiangren/webrtc
|
f898ba54714a58d387282b4a9bbd4ab2b9bc7659
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "server.h"
int main (int argc, char* argv[]){
avdance::Server* server = new avdance::Server();
if (server)
{
server->run();
}
return 0;
};
| 16.545455
| 50
| 0.604396
|
kaiqiangren
|
0d502432df28a49db97ff275ca967b2453e10b19
| 765
|
cpp
|
C++
|
tools/WmarkEditor/src/viewmodel/commands/ReplaceCommand.cpp
|
meilj/CppTS
|
00b077c264a7c32fcbd416f73c4bdc2e0027afd8
|
[
"BSD-2-Clause"
] | null | null | null |
tools/WmarkEditor/src/viewmodel/commands/ReplaceCommand.cpp
|
meilj/CppTS
|
00b077c264a7c32fcbd416f73c4bdc2e0027afd8
|
[
"BSD-2-Clause"
] | null | null | null |
tools/WmarkEditor/src/viewmodel/commands/ReplaceCommand.cpp
|
meilj/CppTS
|
00b077c264a7c32fcbd416f73c4bdc2e0027afd8
|
[
"BSD-2-Clause"
] | null | null | null |
/*
** Mei Lijuan, 2019
*/
////////////////////////////////////////////////////////////////////////////////
#include "precomp.h"
#include "../../model/TextModel.h"
#include "../TextViewModel.h"
////////////////////////////////////////////////////////////////////////////////
namespace CSL {
////////////////////////////////////////////////////////////////////////////////
// TextViewModel
CommandFunc TextViewModel::get_ReplaceCommand()
{
return [this](std::any&& param)->bool
{
return this->m_spModel->Replace(std::any_cast<ReplacePara>(param));
};
}
////////////////////////////////////////////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////
| 26.37931
| 82
| 0.282353
|
meilj
|
0d553ac226f783748c49c6bfb439bac18b562242
| 3,078
|
cpp
|
C++
|
demos/FileInstrument.cpp
|
michaelwillis/sfizz
|
0461f6e5e288da71aeccf7b7dfd71302bf0ba175
|
[
"BSD-2-Clause"
] | 281
|
2019-06-06T05:58:59.000Z
|
2022-03-06T12:20:09.000Z
|
demos/FileInstrument.cpp
|
michaelwillis/sfizz
|
0461f6e5e288da71aeccf7b7dfd71302bf0ba175
|
[
"BSD-2-Clause"
] | 590
|
2019-09-22T00:26:10.000Z
|
2022-03-31T19:21:58.000Z
|
demos/FileInstrument.cpp
|
michaelwillis/sfizz
|
0461f6e5e288da71aeccf7b7dfd71302bf0ba175
|
[
"BSD-2-Clause"
] | 44
|
2019-10-08T08:24:20.000Z
|
2022-02-26T04:21:44.000Z
|
// SPDX-License-Identifier: BSD-2-Clause
// This code is part of the sfizz library and is licensed under a BSD 2-clause
// license. You should have receive a LICENSE.md file along with the code.
// If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz
#include "sfizz/FileMetadata.h"
#include "absl/strings/string_view.h"
#include <sndfile.hh>
#include <cstdio>
static const char* modeString(int mode, const char* valueFallback = nullptr)
{
switch (mode) {
case sfz::LoopNone:
return "none";
case sfz::LoopForward:
return "forward";
case sfz::LoopBackward:
return "backward";
case sfz::LoopAlternating:
return "alternating";
default:
return valueFallback;
}
}
template <class Instrument>
static void printInstrument(const Instrument& ins)
{
printf("Gain: %d\n", ins.gain);
printf("Base note: %d\n", ins.basenote);
printf("Detune: %d\n", ins.detune);
printf("Velocity: %d:%d\n", ins.velocity_lo, ins.velocity_hi);
printf("Key: %d:%d\n", ins.key_lo, ins.key_hi);
printf("Loop count: %d\n", ins.loop_count);
for (unsigned i = 0, n = ins.loop_count; i < n; ++i) {
printf("\nLoop %d:\n", i + 1);
printf("\tMode: %s\n", modeString(ins.loops[i].mode, "(unknown)"));
printf("\tStart: %u\n", ins.loops[i].start);
printf("\tEnd: %u\n", ins.loops[i].end);
printf("\tCount: %u\n", ins.loops[i].count);
}
}
static void usage(const char* argv0)
{
fprintf(
stderr,
"Usage: %s [-s|-f] <sound-file>\n"
" -s: extract the instrument using libsndfile\n"
" -f: extract the instrument using RIFF metadata\n",
argv0);
}
enum FileMethod {
kMethodSndfile,
kMethodRiff,
};
int main(int argc, char *argv[])
{
fs::path path;
FileMethod method = kMethodSndfile;
if (argc == 2) {
path = argv[1];
}
else if (argc == 3) {
absl::string_view flag = argv[1];
if (flag == "-s")
method = kMethodSndfile;
else if (flag == "-f")
method = kMethodRiff;
else {
usage(argv[0]);
return 1;
}
path = argv[2];
}
else {
usage(argv[0]);
return 1;
}
if (method == kMethodRiff) {
sfz::FileMetadataReader reader;
if (!reader.open(path)) {
fprintf(stderr, "Cannot open file\n");
return 1;
}
sfz::InstrumentInfo ins {};
if (!reader.extractInstrument(ins)) {
fprintf(stderr, "Cannot get instrument\n");
return 1;
}
printInstrument(ins);
}
else {
SndfileHandle sndFile(path);
if (!sndFile) {
fprintf(stderr, "Cannot open file\n");
return 1;
}
SF_INSTRUMENT ins {};
if (sndFile.command(SFC_GET_INSTRUMENT, &ins, sizeof(ins)) != 1) {
fprintf(stderr, "Cannot get instrument\n");
return 1;
}
printInstrument(ins);
}
return 0;
}
| 26.534483
| 78
| 0.561079
|
michaelwillis
|
0d5d22d011900ffe9b83e68d7fcc64c80ca902cb
| 259
|
cpp
|
C++
|
Benchine/BenchineCore/Core/BaseGame.cpp
|
DatTestBench/Benchine
|
7f2034dc9d486f8eae39cb5bf917012d3b234955
|
[
"MIT"
] | null | null | null |
Benchine/BenchineCore/Core/BaseGame.cpp
|
DatTestBench/Benchine
|
7f2034dc9d486f8eae39cb5bf917012d3b234955
|
[
"MIT"
] | null | null | null |
Benchine/BenchineCore/Core/BaseGame.cpp
|
DatTestBench/Benchine
|
7f2034dc9d486f8eae39cb5bf917012d3b234955
|
[
"MIT"
] | null | null | null |
#include "BenchinePCH.h"
#include "Core/BaseGame.h"
void BaseGame::BaseInitialize()
{
// User Definined Initialize
Initialize();
}
void BaseGame::BaseUpdate(const float dT)
{
SceneManager::GetInstance()->Update(dT);
// User Defined Update
Update(dT);
}
| 17.266667
| 41
| 0.725869
|
DatTestBench
|
0d5d8f71c15c0ac407463b55c1f1a842b07ffcfa
| 1,687
|
cpp
|
C++
|
Stack/ImplementStackusingQueues_225.cpp
|
obviouskkk/leetcode
|
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
|
[
"BSD-3-Clause"
] | null | null | null |
Stack/ImplementStackusingQueues_225.cpp
|
obviouskkk/leetcode
|
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
|
[
"BSD-3-Clause"
] | null | null | null |
Stack/ImplementStackusingQueues_225.cpp
|
obviouskkk/leetcode
|
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
|
[
"BSD-3-Clause"
] | null | null | null |
/* ***********************************************************************
> File Name: ImplementStackusingQueues_225.cpp
> Author: zzy
> Mail: 942744575@qq.com
> Created Time: Mon 08 Jul 2019 05:14:47 PM CST
********************************************************************** */
#include <stdio.h>
#include <vector>
#include <string>
#include <stdio.h>
#include <climits>
#include <queue>
#include <gtest/gtest.h>
using std::vector;
using std::string;
/*
*
* 225. 用队列实现栈
*
* 使用队列实现栈的下列操作:
*
* push(x) -- 元素 x 入栈
* pop() -- 移除栈顶元素
* top() -- 获取栈顶元素
* empty() -- 返回栈是否为空
*
*/
/*
* 队列没有栈那种来回颠倒的能力。从一个队列移动到另一个队列还是一样的
* 因此每次插入都要往最前面插。所以就需要另一个队列来回倒腾:
* 每次放入空队列,把另一个队列的元素全部移到追加到这个空队列
* 结果:原来有数的队列变空,元素都移动到 原来的空队列,新插入的元素在队首
*
*/
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
auto & st_null = A.empty() ? A : B;
st_null.push(x);
auto & st_not_null = A.empty() ? A : B;
while (!st_not_null.empty()) {
int ele = st_not_null.front();
st_not_null.pop();
st_null.push(ele);
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
auto & st = A.empty() ? B : A;
int ele = st.front();
st.pop();
return ele;
}
/** Get the top element. */
int top() {
auto & st = A.empty() ? B : A;
return st.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return A.empty() && B.empty();
}
protected:
std::queue<int> A;
std::queue<int> B;
};
TEST(testCase,test0) {
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc,argv);
return RUN_ALL_TESTS();
}
| 17.572917
| 74
| 0.559573
|
obviouskkk
|
0d6185bf85c772eee717b669d205d60c550916cf
| 683
|
cpp
|
C++
|
Codeforces/1409/D.cpp
|
noobie7/Codes
|
4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4
|
[
"MIT"
] | 2
|
2021-09-14T15:57:24.000Z
|
2022-03-18T14:11:04.000Z
|
Codeforces/1409/D.cpp
|
noobie7/Codes
|
4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4
|
[
"MIT"
] | null | null | null |
Codeforces/1409/D.cpp
|
noobie7/Codes
|
4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int sum(ll n){
int res = 0;
while(n){
res+= n%10;
n/=10;
}
return res;
}
int main(){
int t; cin>>t;
while(t--){
ll n; cin>>n;
int s; cin>>s;
if(sum(n)<=s){
cout<<0<<endl;
continue;
}
ll ans = 0;
ll pw = 1;
for(int i = 0 ; i < 18; i++){
int dig = (n/pw)%10;
ll add = pw*((10 - dig)%10);
n+=add;
ans+=add;
if(sum(n)<=s){
break;
}
pw*=10;
}
cout<<ans<<endl;
}
return 0;
}
| 18.972222
| 40
| 0.358712
|
noobie7
|
0d66d7240298fc05d53ee3e0e879d17a5781870f
| 1,202
|
cpp
|
C++
|
data_structures/disjoint_union.cpp
|
vedantiitkgp/CP-Algorithms
|
81d1a64624f8b0e918b7d5b7f8dc1e2cdcbc88b4
|
[
"MIT"
] | null | null | null |
data_structures/disjoint_union.cpp
|
vedantiitkgp/CP-Algorithms
|
81d1a64624f8b0e918b7d5b7f8dc1e2cdcbc88b4
|
[
"MIT"
] | null | null | null |
data_structures/disjoint_union.cpp
|
vedantiitkgp/CP-Algorithms
|
81d1a64624f8b0e918b7d5b7f8dc1e2cdcbc88b4
|
[
"MIT"
] | null | null | null |
// https://cp-algorithms.com/data_structures/disjoint_set_union.html
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<string, string> pss;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vii;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<bool> vb;
// Path compression optimization applied and Union by size (Similar union by rank)
void swap(vi &a, vi &b)
{
vi temp;
temp = a;
a = b;
b = temp;
}
void make_set(int v, vi &parent,vi &size)
{
parent[v] = v;
size[v] = 1;
}
void find_set(int v, vi &parent)
{
if(v==parent[v]) return v;
return parent[v] = find_set(parent[v]);
}
void union_sets(int a,int b,vi &parent,vi &size)
{
a = find_set(a);
b = find_set(b);
if(a!=b)
{
if(size[a]<size[b]) swap(a,b);
parent[b] = a;
size[a]+=size[b];
}
}
// Applications
// 1. Connected components - Completing a Minimum spanning tree
// 2. Search connected components in a image.
// 3. Arpa's trick for finding long range minimum queries
// 4. Offline LCA - O(alpha(n))
// 5. Online bridge finding algorithm help
| 21.087719
| 82
| 0.647255
|
vedantiitkgp
|
0d6a1c5c4ca0b2f1b23eb3d286c935b6eadc9bde
| 6,013
|
cpp
|
C++
|
ql/experimental/preexperimental/oneFactorGauss.cpp
|
universe1987/QuantLib
|
bbb0145aff285853755b9f6ed013f53a41163acb
|
[
"BSD-3-Clause"
] | 4
|
2016-03-28T15:05:23.000Z
|
2020-02-17T23:05:57.000Z
|
ql/experimental/preexperimental/oneFactorGauss.cpp
|
universe1987/QuantLib
|
bbb0145aff285853755b9f6ed013f53a41163acb
|
[
"BSD-3-Clause"
] | 1
|
2015-02-02T20:32:43.000Z
|
2015-02-02T20:32:43.000Z
|
ql/experimental/preexperimental/oneFactorGauss.cpp
|
pcaspers/quantlib
|
bbb0145aff285853755b9f6ed013f53a41163acb
|
[
"BSD-3-Clause"
] | 10
|
2015-01-26T14:50:24.000Z
|
2015-10-23T07:41:30.000Z
|
#include <oneFactorGauss.hpp>
using namespace std;
namespace QuantLib {
OneFactorGauss::OneFactorGauss() {
nd_ = NormalDistribution();
cnd_ = CumulativeNormalDistribution();
icn_ = InverseCumulativeNormal();
gh_= new GaussHermiteIntegration(64);
}
boost::shared_ptr<KernelDensity> OneFactorGauss::empiricalPdDensity(long numberOfObligors, double pd, double correlation, int seed, long samples) {
MersenneTwisterUniformRng mt(seed);
vector<double> sam;
double spd;
for(int i=0;i<samples;i++) {
spd=((double)sampleNumberOfDefaults(numberOfObligors,pd,correlation,mt)) / ((double)numberOfObligors);
sam.push_back(spd);
}
//return estimator with default bandwidth, can be computed by user later
return boost::shared_ptr<KernelDensity>(new KernelDensity(sam,0.05,0.01));
}
boost::shared_ptr<KernelDensity> OneFactorGauss::empiricalGordyVarDensity(long numberOfObligors, double pd, double quantile, double correlation, int seed, long samples) {
MersenneTwisterUniformRng mt(seed);
vector<double> sam;
double spd,gvar;
for(int i=0;i<samples;i++) {
spd=((double)sampleNumberOfDefaults(numberOfObligors,pd,correlation,mt)) / ((double)numberOfObligors);
if(spd>0.0&&spd<1.0) {
gvar=spd>0.0?cnd_(pow(1.0-correlation*correlation,-0.5)*icn_(spd)+pow(correlation*correlation/(1.0-correlation*correlation),0.5)*icn_(quantile)) : 0.0;
}
else {
gvar=spd==0.0?0.0:1.0;
}
sam.push_back(gvar);
}
//return estimator with default bandwidth, can be computed by user later
return boost::shared_ptr<KernelDensity>(new KernelDensity(sam,0.3,0.1));
}
double OneFactorGauss::empiricalBootstrapVariance(long numberOfObligors, double pd, double correlation, int seed, long samples) {
Array roots = gh_->x();
Array weights = gh_->weights();
double i1=0.0,i2=0.0;
double icnPd=icn_(pd);
double condPd;
double u,df;
//FILE* out=fopen("ASFR.log","a");
for(int i=0;i<roots.size();i++) {
u=roots[i]*sqrt(2.0);
df=exp(-roots[i]*roots[i]);
condPd=cnd_((icnPd-correlation*u)/sqrt(1.0-correlation*correlation));
i1+=condPd*weights[i]*df;
i2+=condPd*condPd*weights[i]*df;
}
i1/=sqrt(M_PI);
i2/=sqrt(M_PI);
//fclose(out);
return (i1-i2)/((double)numberOfObligors)+i2-i1*i1;
/*MersenneTwisterUniformRng mt(seed);
IncrementalStatistics stat1;
double spd,globalFactor,condPd,condSpr,defTime,rn;
double icnPd=icn_(pd);
int nod;
for(int i=0;i<samples;i++) {
//spd=((double)sampleNumberOfDefaults(numberOfObligors,pd,correlation,mt)) / ((double)numberOfObligors);
// fast implementation
globalFactor=icn_(mt.next().value);
condPd=cnd_((icnPd-correlation*globalFactor)/sqrt(1.0-correlation*correlation));
//condSpr=condPd<1.0 ? -log(1-condPd) : 1000.0;
nod=0;
for(int i=0;i<numberOfObligors;i++) {
rn=mt.next().value;
//defTime=condSpr>0.0 && rn<1.0 ? -log(1.0-mt.next().value)/condSpr : 100000.0;
//if(defTime<1.0) nod++;
if(rn<condPd) nod++;
}
spd=nod/((double)numberOfObligors);
stat1.add(spd);
}
//return estimator with default bandwidth, can be computed by user later
//fprintf(out,"mean=%f,var=%f\n",stat1.mean(),stat1.variance());
//fclose(out);
return stat1.variance();*/
}
boost::shared_ptr<KernelDensity> OneFactorGauss::convexityAdjGordyVarDensity(long numberOfObligors, double pd, double quantile, double correlation, bool useCorr, int seed, long samples) {
MersenneTwisterUniformRng mt(seed);
vector<double> sam;
double spd,gvar,spd2,conv;
boost::shared_ptr<KernelDensity> eg;
double A=1.0/sqrt(1.0-correlation*correlation);
double B=sqrt(correlation*correlation/(1.0-correlation*correlation))*icn_(quantile);
double icnSpd,phi1,phi1p,phi2,phi2p,alpha,alphaP,alphaPP,der2;
double m2a,m2b,m2c,m2Corr,bv2der;
double h=1E-5; // for 2nd derivative computation
for(int i=0;i<samples;i++) {
spd=((double)sampleNumberOfDefaults(numberOfObligors,pd,correlation,mt)) / ((double)numberOfObligors);
if(spd>0.0&&spd<1.0) {
gvar=spd>0.0?cnd_(pow(1.0-correlation*correlation,-0.5)*icn_(spd)+pow(correlation*correlation/(1.0-correlation*correlation),0.5)*icn_(quantile)) : 0.0;
}
else {
gvar=spd==0.0?0.0:1.0;
}
// compute convexity adjustment
// estimate variance of pd estimator and 2nd derivative
if(spd>h && spd<1.0) {
m2a=empiricalBootstrapVariance(numberOfObligors,spd-h,correlation,0,0);
m2b=empiricalBootstrapVariance(numberOfObligors,spd,correlation,0,0);
m2c=empiricalBootstrapVariance(numberOfObligors,spd+h,correlation,0,0);
if(useCorr) bv2der=(m2c-2.0*m2b+m2a)/(h*h);
else bv2der=0.0;
m2Corr=m2b-0.5*bv2der*m2b; // convexity correction for m2
//fprintf(out,"%f;%f;%f\n",m2b,bv2der,m2Corr);
// compute conv adj
icnSpd=icn_(spd);
phi1=exp(-0.5*icnSpd*icnSpd)/sqrt(2.0*M_PI);
//if(phi1>0.0) {
phi1p=-phi1*icnSpd;
alpha=A*icnSpd+B;
alphaP=A/phi1;
alphaPP=-A*phi1p/(phi1*phi1*phi1);
phi2=exp(-0.5*alpha*alpha)/sqrt(2.0*M_PI);
phi2p=-phi2*alpha;
der2=phi2p*alphaP*alphaP+phi2*alphaPP;
conv=0.5*m2Corr*der2;
//}
//else {
// conv=0.0;
//}
}
else {
conv=0.0;
}
sam.push_back(gvar-conv);
}
//return estimator with default bandwidth, can be computed by user later
return boost::shared_ptr<KernelDensity>(new KernelDensity(sam,0.3,0.1));
}
long OneFactorGauss::sampleNumberOfDefaults(long numberOfObligors, double pd, double correlation, MersenneTwisterUniformRng& mt) {
double globalFactor, condPd, condSpr, defTime, rn;
long numberOfDefaults=0;
globalFactor=icn_(mt.next().value);
condPd=cnd_((icn_(pd)-correlation*globalFactor)/sqrt(1.0-correlation*correlation));
condSpr=condPd<1.0 ? -log(1-condPd) : 1000.0;
for(int i=0;i<numberOfObligors;i++) {
rn=mt.next().value;
defTime=condSpr>0.0 && rn<1.0 ? -log(1.0-mt.next().value)/condSpr : 100000.0;
if(defTime<1.0) numberOfDefaults++;
}
return numberOfDefaults;
}
}
| 32.502703
| 188
| 0.695493
|
universe1987
|
0d729f3d3e2f57eec981b42bebd09c63a0404270
| 1,004
|
cpp
|
C++
|
chapter13/ex03_arrow.cpp
|
ClassAteam/stroustrup-ppp
|
ea9e85d4ea9890038eb5611c3bc82734c8706ce7
|
[
"MIT"
] | 124
|
2018-06-23T10:16:56.000Z
|
2022-03-19T15:16:12.000Z
|
chapter13/ex03_arrow.cpp
|
therootfolder/stroustrup-ppp
|
b1e936c9a67b9205fdc9712c42496b45200514e2
|
[
"MIT"
] | 23
|
2018-02-08T20:57:46.000Z
|
2021-10-08T13:58:29.000Z
|
chapter13/ex03_arrow.cpp
|
ClassAteam/stroustrup-ppp
|
ea9e85d4ea9890038eb5611c3bc82734c8706ce7
|
[
"MIT"
] | 65
|
2019-05-27T03:05:56.000Z
|
2022-03-26T03:43:05.000Z
|
#include "../GUI/Simple_window.h"
#include "../GUI/Graph.h"
#include "./Arrow.h"
#include <string>
#include <iostream>
using namespace Graph_lib;
int main()
try {
// Window
const Point tl {100, 100};
Simple_window win {tl, 600, 400, "Chapter 12 Ex 3"};
Arrow a1 {Point{100, 100}, Point{250, 200}};
win.attach(a1);
Arrow a2 {Point{500, 300}, Point{500, 100}};
a2.set_color(Color::dark_green);
win.attach(a2);
Arrow a3 {Point{525, 100}, Point{525, 300}};
a3.set_color(Color::blue);
win.attach(a3);
Arrow a4 {Point{300, 50}, Point{100, 300}};
a4.set_color(Color::red);
win.attach(a4);
win.wait_for_button();
}
catch(exception& e) {
cerr << "exception: " << e.what() << '\n';
return 1;
}
catch(...) {
cerr << "error\n";
return 2;
}
/* Compile command
g++ -w -Wall -std=c++11 ../GUI/Graph.cpp ../GUI/Window.cpp ../GUI/GUI.cpp ../GUI/Simple_window.cpp Arrow.cpp ex03_arrow.cpp `fltk-config --ldflags --use-images` -o a.out
*/
| 22.818182
| 169
| 0.605578
|
ClassAteam
|
0d730f69c1a1a9e1651ac8a1ba1a5cb1be303c01
| 597
|
cpp
|
C++
|
hackerrank.com/crush/main.cpp
|
bepec/challenge
|
cf2d4fcf11a9a1724b6f620fdda86afbb1ba9ddc
|
[
"MIT"
] | null | null | null |
hackerrank.com/crush/main.cpp
|
bepec/challenge
|
cf2d4fcf11a9a1724b6f620fdda86afbb1ba9ddc
|
[
"MIT"
] | null | null | null |
hackerrank.com/crush/main.cpp
|
bepec/challenge
|
cf2d4fcf11a9a1724b6f620fdda86afbb1ba9ddc
|
[
"MIT"
] | null | null | null |
#include <cstdio>
using namespace std;
#define out if(1)cout
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
#define abs(a) (((a)<0)?(-(a)):(a))
static const int MAXN = 10000001;
typedef long long int i64;
static i64 ar[MAXN];
int main()
{
ios::sync_with_stdio(false);
int N, M;
scanf("%d %d", &N, &M);
for (int i = 0; i < M; i++) {
int a, b, k;
scanf("%d %d %d", &a, &b, &k);
ar[a] += k;
ar[b+1] -= k;
}
i64 cur = 0;
i64 max = 0;
for (int i = 1; i <= N; i++) {
cur += ar[i];
if (cur > max) max = cur;
}
printf("%lld\n", max);
return 0;
}
| 16.135135
| 37
| 0.499162
|
bepec
|
0d80b0bae4b066968105b537e4245878c1aee91a
| 3,156
|
hpp
|
C++
|
include/GTGE/Physics/CollisionShapeTypes.hpp
|
mackron/GTGameEngine
|
380d1e01774fe6bc2940979e4e5983deef0bf082
|
[
"BSD-3-Clause"
] | 31
|
2015-03-19T08:44:48.000Z
|
2021-12-15T20:52:31.000Z
|
include/GTGE/Physics/CollisionShapeTypes.hpp
|
mackron/GTGameEngine
|
380d1e01774fe6bc2940979e4e5983deef0bf082
|
[
"BSD-3-Clause"
] | 19
|
2015-07-09T09:02:44.000Z
|
2016-06-09T03:51:03.000Z
|
include/GTGE/Physics/CollisionShapeTypes.hpp
|
mackron/GTGameEngine
|
380d1e01774fe6bc2940979e4e5983deef0bf082
|
[
"BSD-3-Clause"
] | 3
|
2017-10-04T23:38:18.000Z
|
2022-03-07T08:27:13.000Z
|
// Copyright (C) 2011 - 2014 David Reid. See included LICENCE.
#ifndef GT_CollisionShapeTypes
#define GT_CollisionShapeTypes
#include <BulletCollision/CollisionShapes/btCylinderShape.h>
#include <BulletCollision/CollisionShapes/btCapsuleShape.h>
namespace GT
{
enum CollisionShapeType
{
CollisionShapeType_None = 0,
CollisionShapeType_Box = 1,
CollisionShapeType_Sphere = 2,
CollisionShapeType_Ellipsoid = 3,
CollisionShapeType_CylinderX = 4,
CollisionShapeType_CylinderY = 5,
CollisionShapeType_CylinderZ = 6,
CollisionShapeType_CapsuleX = 7,
CollisionShapeType_CapsuleY = 8,
CollisionShapeType_CapsuleZ = 9,
CollisionShapeType_ConvexHull = 10,
CollisionShapeType_ModelConvexHulls = 11,
};
inline CollisionShapeType GetCollisionShapeType(const btCollisionShape* shape)
{
if (shape != nullptr)
{
switch (shape->getShapeType())
{
case BOX_SHAPE_PROXYTYPE:
{
return CollisionShapeType_Box;
}
case SPHERE_SHAPE_PROXYTYPE:
{
return CollisionShapeType_Sphere;
}
case CUSTOM_CONVEX_SHAPE_TYPE:
{
return CollisionShapeType_Ellipsoid;
}
case CYLINDER_SHAPE_PROXYTYPE:
{
int upAxis = static_cast<const btCylinderShape*>(shape)->getUpAxis();
if (upAxis == 0)
{
return CollisionShapeType_CylinderX;
}
else if (upAxis == 2)
{
return CollisionShapeType_CylinderZ;
}
return CollisionShapeType_CylinderY;
}
case CAPSULE_SHAPE_PROXYTYPE:
{
int upAxis = static_cast<const btCapsuleShape*>(shape)->getUpAxis();
if (upAxis == 0)
{
return CollisionShapeType_CapsuleX;
}
else if (upAxis == 2)
{
return CollisionShapeType_CapsuleZ;
}
return CollisionShapeType_CapsuleY;
}
case CONVEX_HULL_SHAPE_PROXYTYPE:
{
return CollisionShapeType_ConvexHull;
}
case COMPOUND_SHAPE_PROXYTYPE: // <-- Will be the model convex hulls.
{
return CollisionShapeType_ModelConvexHulls;
}
default:
{
break;
}
}
}
return CollisionShapeType_None;
}
inline CollisionShapeType GetCollisionShapeType(const btCollisionShape &shape)
{
return GetCollisionShapeType(&shape);
}
}
#endif
| 29.495327
| 98
| 0.498733
|
mackron
|
0d82f71a6ee579f7c7271823129651b733a44cf2
| 203
|
hpp
|
C++
|
Paramedic.hpp
|
liorls/wargame-a
|
b4e2f65259defe5664dfc0f83294269beb18fea0
|
[
"MIT"
] | null | null | null |
Paramedic.hpp
|
liorls/wargame-a
|
b4e2f65259defe5664dfc0f83294269beb18fea0
|
[
"MIT"
] | null | null | null |
Paramedic.hpp
|
liorls/wargame-a
|
b4e2f65259defe5664dfc0f83294269beb18fea0
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Soldier.hpp"
class Paramedic : public Soldier {
public:
Paramedic(int p): Soldier(p, 100, 0, 100) {}
void attack(vector<vector<Soldier*>> &b, pair<int,int> location);
};
| 20.3
| 69
| 0.669951
|
liorls
|
0d877b6c00c091ecbac688cf441eab948af5189c
| 237
|
hpp
|
C++
|
src/lattice_boltzmann/LBUtils/Stencil.hpp
|
flowzario/mesoBasic
|
0a86c98e784a7446a7b6f03b48eef4c9dbfe5940
|
[
"MIT"
] | null | null | null |
src/lattice_boltzmann/LBUtils/Stencil.hpp
|
flowzario/mesoBasic
|
0a86c98e784a7446a7b6f03b48eef4c9dbfe5940
|
[
"MIT"
] | null | null | null |
src/lattice_boltzmann/LBUtils/Stencil.hpp
|
flowzario/mesoBasic
|
0a86c98e784a7446a7b6f03b48eef4c9dbfe5940
|
[
"MIT"
] | null | null | null |
# ifndef STENCIL_H
# define STENCIL_H
# include <vector>
# include <string>
struct Stencil {
int nn;
std::vector<int> exi,eyi,ezi;
std::vector<double> ex,ey,ez,wa;
void setStencil(const std::string);
};
# endif // STENCIL_H
| 11.85
| 36
| 0.675105
|
flowzario
|
0d891d182cebe76956d01f5c436f5b1cb77a5a8d
| 11,123
|
cpp
|
C++
|
ModelGenerator/src/ModelGenerator.cpp
|
adam-lafontaine/AugmentedAI
|
a4736ce59963ee86313a5936aaf09f0f659e4184
|
[
"MIT"
] | null | null | null |
ModelGenerator/src/ModelGenerator.cpp
|
adam-lafontaine/AugmentedAI
|
a4736ce59963ee86313a5936aaf09f0f659e4184
|
[
"MIT"
] | null | null | null |
ModelGenerator/src/ModelGenerator.cpp
|
adam-lafontaine/AugmentedAI
|
a4736ce59963ee86313a5936aaf09f0f659e4184
|
[
"MIT"
] | null | null | null |
/*
Copyright (c) 2021 Adam Lafontaine
*/
#include "ModelGenerator.hpp"
#include "pixel_conversion.hpp"
#include "cluster_distance.hpp"
#include "../../utils/cluster_config.hpp"
#include "../../utils/dirhelper.hpp"
#include "../../DataAdaptor/src/data_adaptor.hpp"
#include <algorithm>
#include <numeric>
#include <functional>
#include <iomanip>
#include <sstream>
#include <cassert>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <string>
namespace dir = dirhelper;
namespace img = libimage;
namespace data = data_adaptor;
namespace model_generator
{
using hist_value_t = unsigned; // represent a pixel as a single value for a histogram
constexpr hist_value_t MAX_COLOR_VALUE = 255;
using color_qty_t = unsigned;
constexpr color_qty_t MAX_RELATIVE_QTY = 255;
// provides a count for every shade that is found
using color_hist_t = std::array<color_qty_t, MAX_COLOR_VALUE>;
// provides shade counts for every column in the data image
using column_hists_t = std::vector<color_hist_t>;
// shade counts by column for each class
using class_column_hists_t = std::array<column_hists_t, mlclass::ML_CLASS_COUNT>;
using cluster_t = cluster::Cluster;
using centroid_list_t = cluster::value_row_list_t;
using data_list_t = std::vector<cluster::data_row_t>;
using class_cluster_data_t = std::array<data_list_t, mlclass::ML_CLASS_COUNT>;
using index_list_t = std::vector<size_t>;
using file_path_t = ModelGenerator::file_path_t;
//======= HELPERS ===================
static std::string make_model_file_name();
//======= CONVERSION =============
// converts a data pixel to a value between 0 and MAX_COLOR_VALUE
static hist_value_t to_hist_value(data_pixel_t const& pix);
//======= CLUSTERING =======================
// finds the indeces of the data that contribute to determining the class
static index_list_t find_relevant_positions(class_column_hists_t const& class_pos_hists);
//======= HISTOGRAM ============================
static void update_histograms(column_hists_t& pos_hists, img::view_t const& view);
static void append_data(data_list_t& data, img::view_t const& data_view);
// sets all values in the histograms to a value between 0 and MAX_RELATIVE_QTY
static void normalize_histograms(column_hists_t& pos);
static class_column_hists_t make_empty_histograms();
//======= CLASS METHODS ==================
// for cleaning up after reading data
void ModelGenerator::purge_class_data()
{
mlclass::for_each_class([&](auto c) { m_class_data[c].clear(); });
}
// check if data exists for every class
bool ModelGenerator::has_class_data()
{
auto const pred = [&](auto const& list) { return !list.empty(); };
return std::all_of(m_class_data.begin(), m_class_data.end(), pred);
}
// reads directory of raw data for a given class
void ModelGenerator::add_class_data(const char* src_dir, MLClass class_index)
{
// convert the class enum to an array index
auto const index = mlclass::to_class_index(class_index);
// data is organized in directories by class
m_class_data[index] = dir::get_files_of_type(src_dir, data::DATA_IMAGE_EXTENSION);
}
// saves properties based on all of the data read
void ModelGenerator::save_model(const char* save_dir)
{
if (!has_class_data())
return;
/* get all of the data */
class_cluster_data_t cluster_data;
auto hists = make_empty_histograms();
auto const get_data = [&](auto class_index)
{
for (auto const& data_file : m_class_data[class_index])
{
img::image_t data_image;
img::read_image_from_file(data_file, data_image);
auto data_view = img::make_view(data_image);
assert(static_cast<size_t>(data_view.width) == data::data_image_width());
append_data(cluster_data[class_index], data_view);
update_histograms(hists[class_index], data_view);
}
normalize_histograms(hists[class_index]);
};
mlclass::for_each_class(get_data);
/* cluster the data */
auto const data_indeces = find_relevant_positions(hists); // This needs to be right
cluster_t cluster;
centroid_list_t centroids;
auto const class_clusters = mlclass::make_class_clusters(cluster::CLUSTER_COUNT);
cluster.set_distance(build_cluster_distance(data_indeces));
auto const cluster_class_data = [&](auto c)
{
auto const cents = cluster.cluster_data(cluster_data[c], class_clusters[c]);
centroids.insert(centroids.end(), cents.begin(), cents.end());
};
mlclass::for_each_class(cluster_class_data);
/* create the model and save it */
auto const save_path = fs::path(save_dir) / make_model_file_name();
auto const width = static_cast<u32>(data::data_image_width());
auto const height = static_cast<u32>(centroids.size());
img::image_t image;
img::make_image(image, width, height);
auto view = img::make_view(image);
for(u32 y = 0; y < height; ++y)
{
auto const list = centroids[y];
auto ptr = view.row_begin(y);
for (u32 x = 0; x < width; ++x)
{
auto is_counted = std::find(data_indeces.begin(), data_indeces.end(), x) != data_indeces.end();
ptr[x] = model_value_to_model_pixel(list[x], is_counted);
}
}
img::write_view(view, save_path);
/*
This is a long function and it could be broken up into smaller ones.
However, this logic is only used here so there is no sense in creating more class members
*/
}
//======= CLUSTERING =======================
static index_list_t set_indeces_manually(class_column_hists_t const& class_pos_hists)
{
// here you can cheat by choosing indeces after inspecting the data images
//index_list_t list{ 0 }; // uses only the first index of the data image values
// just return all of the indeces
index_list_t list(class_pos_hists[0].size());
std::iota(list.begin(), list.end(), 0);
return list;
}
typedef struct
{
double min;
double max;
} minmax_t;
// returns the mean +/- one std dev
static minmax_t get_stat_range(color_hist_t const& hist)
{
auto const calc_mean = [](color_hist_t const& hist)
{
size_t qty_total = 0;
size_t val_total = 0;
for (size_t shade = 0; shade < hist.size(); ++shade)
{
auto qty = hist[shade];
if (!qty)
continue;
qty_total += qty;
val_total += qty * shade;
}
return qty_total == 0 ? 0 : val_total / qty_total;
};
auto const calc_sigma = [](color_hist_t const& hist, size_t mean)
{
double total = 0;
size_t qty_total = 0;
for (size_t shade = 0; shade < hist.size(); ++shade)
{
auto val = shade;
auto qty = hist[shade];
if (!qty)
continue;
qty_total += qty;
auto const diff = val - mean;
total += qty * diff * diff;
}
return qty_total == 0 ? 0 : std::sqrt(total / qty_total);
};
auto const m = calc_mean(hist);
auto const s = calc_sigma(hist, m);
return{ m - s, m + s }; // mean +/- one std dev
}
// determine if any of the ranges overlap each other
static bool has_overlap(std::array<minmax_t, mlclass::ML_CLASS_COUNT> const& ranges)
{
assert(ranges.size() >= 2);
auto const r_min = std::min_element(ranges.begin(), ranges.end(), [](auto const& a, auto const& b) { return a.min < b.min; });
auto const r_max = std::max_element(ranges.begin(), ranges.end(), [](auto const& a, auto const& b) { return a.max < b.max; });
return r_min->max >= r_max->min;
}
// An attempt at programatically finding data image indeces that contribute to classification
// finds the indeces of the data that contribute to determining the class
static index_list_t try_find_indeces(class_column_hists_t const& class_pos_hists)
{
const size_t num_pos = class_pos_hists[0].size();
std::array<minmax_t, mlclass::ML_CLASS_COUNT> class_ranges;
index_list_t list;
for (size_t pos = 0; pos < num_pos; ++pos)
{
class_ranges = { 0 };
auto const set_class_range = [&](auto class_index) { class_ranges[class_index] = get_stat_range(class_pos_hists[class_index][pos]); };
mlclass::for_each_class(set_class_range);
if (has_overlap(class_ranges))
continue;
list.push_back(pos);
}
return list;
}
static index_list_t find_relevant_positions(class_column_hists_t const& class_pos_hists)
{
auto const indeces = try_find_indeces(class_pos_hists);
if(indeces.empty())
return set_indeces_manually(class_pos_hists);
return indeces;
}
//======= HISTOGRAM ============================
// update the counts in the histograms with data from a data image
static void update_histograms(column_hists_t& pos_hists, img::view_t const& data_view)
{
u32 column = 0;
auto const update_pred = [&](auto const& p)
{
data_pixel_t dp{ p };
++pos_hists[column][to_hist_value(dp)];
};
for (; column < data_view.width; ++column)
{
auto column_view = img::column_view(data_view, column);
std::for_each(column_view.begin(), column_view.end(), update_pred);
}
}
// add converted data from a data image
static void append_data(data_list_t& data, img::view_t const& data_view)
{
auto const height = data_view.height;
for (u32 y = 0; y < height; ++y)
{
cluster::data_row_t data_row;
auto row_view = img::row_view(data_view, y);
std::transform(row_view.begin(), row_view.end(), std::back_inserter(data_row), data_pixel_to_model_value);
data.push_back(std::move(data_row));
}
}
// sets all values in the histograms to a value between 0 and MAX_RELATIVE_QTY
static void normalize_histograms(column_hists_t& pos)
{
std::vector<unsigned> hists;
hists.reserve(pos.size());
auto const max_val = [](auto const& list)
{
auto it = std::max_element(list.begin(), list.end());
return *it;
};
std::transform(pos.begin(), pos.end(), std::back_inserter(hists), max_val);
const double max = max_val(hists);
auto const norm = [&](unsigned count)
{
return static_cast<unsigned>(count / max * MAX_RELATIVE_QTY);
};
for (auto& list : pos)
{
for (auto& count : list)
{
count = norm(count);
}
}
}
static class_column_hists_t make_empty_histograms()
{
class_column_hists_t position_hists;
auto const width = data::data_image_width();
auto const set_column_zeros = [&](auto c)
{
position_hists[c] = column_hists_t(width, {0});
};
mlclass::for_each_class(set_column_zeros);
return position_hists;
}
//======= HELPERS =====================
static std::string make_model_file_name()
{
std::ostringstream oss;
std::time_t t = std::time(nullptr);
struct tm buf;
// TODO: C++20 chrono
#ifdef __linux
localtime_r(&t, &buf);
#else
localtime_s(&buf, &t);
#endif
oss << "model_" << std::put_time(&buf, "%F_%T");
auto date_file = oss.str() + MODEL_FILE_EXTENSION;
std::replace(date_file.begin(), date_file.end(), ':', '-');
return date_file;
}
//======= CONVERSION =============
// converts a data pixel to a value between 0 and MAX_COLOR_VALUE
static hist_value_t to_hist_value(data_pixel_t const& pix)
{
auto const val = static_cast<double>(pix.value);
auto const ratio = val / UINT32_MAX;
return static_cast<hist_value_t>(ratio * MAX_COLOR_VALUE);
}
}
| 24.286026
| 137
| 0.685427
|
adam-lafontaine
|
0d8a3cfa3854dfce410e87e120e2042b9ee5860e
| 7,571
|
cc
|
C++
|
server/src/JsonNode.cc
|
shawndfl/http_server
|
f4a0e13146ca95cc9f7c4e1145fbc52bfd45a8a0
|
[
"MIT"
] | null | null | null |
server/src/JsonNode.cc
|
shawndfl/http_server
|
f4a0e13146ca95cc9f7c4e1145fbc52bfd45a8a0
|
[
"MIT"
] | null | null | null |
server/src/JsonNode.cc
|
shawndfl/http_server
|
f4a0e13146ca95cc9f7c4e1145fbc52bfd45a8a0
|
[
"MIT"
] | null | null | null |
/*
* JsonNode.cc
*
* Created on: Jun 1, 2020
* Author: sdady
*/
#include "JsonNode.h"
namespace ehs {
/*************************************************/
JsonNode::JsonNode() {
type_ = JsonNull;
valueNum_ = 0;
}
/*************************************************/
JsonNode::~JsonNode() {
}
/*************************************************/
JsonNode& JsonNode::setString(const std::string& value) {
type_= JsonString;
valueStr_ = value;
return *this;
}
/*************************************************/
JsonNode& JsonNode::setNumber(double value) {
type_= JsonNumber;
valueNum_ = value;
return *this;
}
/*************************************************/
JsonNode& JsonNode::setBool(bool value) {
type_= value? JsonTrue: JsonFalse;
return *this;
}
/*************************************************/
JsonNode& JsonNode::setNull() {
type_= JsonNull;
return *this;
}
/*************************************************/
JsonNode& JsonNode::setObject(const std::string& key, const JsonNode& value) {
type_= JsonObject;
valueObj_[key] = value;
return *this;
}
/*************************************************/
JsonNode& JsonNode::setArray(int index, const JsonNode &value) {
type_ = JsonArray;
JsonNode newNode;
for (int i = valueArray_.size(); i <= index; i++) {
valueArray_.push_back(JsonNode());
}
return valueArray_[index];
}
/*************************************************/
void JsonNode::clear() {
valueArray_.clear();
valueObj_.clear();
type_ = JsonNull;
valueNum_ = 0;
valueStr_ = "";
}
/*************************************************/
std::string JsonNode::toString(bool humanReadable) const {
std::string json;
// we can only start with objects or arrays
if (type_ == JsonObject || type_ == JsonArray) {
if(humanReadable){
toStringReadableImpl(json, 0);
} else {
toStringImpl(json);
}
} else {
json = "{}";
}
return json;
}
/*************************************************/
std::string JsonNode::getString(const std::string &key, const std::string &defaultValue) {
auto itt = valueObj_.find(key);
if(itt == valueObj_.end() || (*itt).second.type_ != JsonString) {
return defaultValue;
} else {
return (*itt).second.valueStr_;
}
}
/*************************************************/
double JsonNode::getNumber(const std::string &key, const double defaultValue) {
auto itt = valueObj_.find(key);
if (itt == valueObj_.end() || (*itt).second.type_ != JsonNumber) {
return defaultValue;
} else {
return (*itt).second.valueNum_;
}
}
/*************************************************/
bool JsonNode::getBool(const std::string &key, const bool defaultValue) {
auto itt = valueObj_.find(key);
if (itt == valueObj_.end() ||
((*itt).second.type_ != JsonFalse &&
(*itt).second.type_ != JsonTrue)) {
return defaultValue;
} else {
return (*itt).second.valueNum_ == 1;
}
}
/*************************************************/
JsonNode& JsonNode::append() {
type_= JsonArray;
valueArray_.push_back(JsonNode());
return valueArray_[valueArray_.size() - 1];
}
/*************************************************/
JsonNode& JsonNode::operator [](int index) {
type_ = JsonArray;
JsonNode newNode;
// add nodes until we get to this index
for (int i = valueArray_.size(); i <= index; i++) {
valueArray_.push_back(JsonNode());
}
return valueArray_[index];
}
/*************************************************/
JsonNode& JsonNode::operator [](const std::string& key) {
type_= JsonObject;
return valueObj_[key];
}
/*************************************************/
JsonNode& JsonNode::operator =(ulong value) {
return setNumber(value);
}
/*************************************************/
JsonNode& JsonNode::operator =(int value) {
type_= JsonNumber;
valueNum_ = value;
return *this;
}
/*************************************************/
JsonNode& JsonNode::operator =(uint value) {
type_= JsonNumber;
valueNum_ = value;
return *this;
}
/*************************************************/
JsonNode& JsonNode::operator =(long value) {
type_= JsonNumber;
valueNum_ = value;
return *this;
}
/*************************************************/
JsonNode& JsonNode::operator =(double value) {
type_= JsonNumber;
valueNum_ = value;
return *this;
}
/*************************************************/
JsonNode& JsonNode::operator =(const std::string& value) {
type_= JsonString;
valueStr_ = value;
return *this;
}
/*************************************************/
JsonNode& JsonNode::operator =(const char* value) {
type_= JsonString;
valueStr_ = value;
return *this;
}
/*************************************************/
void JsonNode::toStringReadableImpl(std::string& json, int tab) const {
std::string tabs;
for(int i =0; i < tab; i++) {
tabs +="\t";
}
switch (type_) {
case JsonNull:
json += "null";
break;
case JsonObject: {
size_t i = 0;
json += "{\n";
++tab;
for (auto& pair : valueObj_) {
json += tabs + "\t\"" + pair.first + "\": ";
pair.second.toStringReadableImpl(json, tab);
if (i < valueObj_.size() - 1) {
json += ",";
}
i++;
json += '\n';
}
json += tabs + "}";
break;
}
case JsonArray: {
size_t i = 0;
json += "[\n";
++tab;
for (auto& item : valueArray_) {
json += tabs + "\t";
item.toStringReadableImpl(json, tab);
if (i < valueArray_.size() - 1) {
json += ",";
}
i++;
json += '\n';
}
json += tabs + "]";
break;
}
break;
case JsonTrue:
json += "true";
break;
case JsonFalse:
json += "false";
break;
case JsonString:
json += "\"" + valueStr_ + "\"";
break;
case JsonNumber:
try {
json += std::to_string(valueNum_);
} catch(std::exception& ) {
json += "0";
}
break;
}
}
/*************************************************/
void JsonNode::toStringImpl(std::string& json) const {
switch (type_) {
case JsonNull:
json += "null";
break;
case JsonObject: {
size_t i = 0;
json += "{";
for (auto& pair : valueObj_) {
json += "\"" + pair.first + "\":";
pair.second.toStringImpl(json);
if (i < valueObj_.size() - 1) {
json += ",";
}
i++;
}
json += "}";
break;
}
case JsonArray: {
size_t i = 0;
json += "[";
for (auto& item : valueArray_) {
item.toStringImpl(json);
if (i < valueArray_.size() - 1) {
json += ",";
}
i++;
}
json += "]";
break;
}
break;
case JsonTrue:
json += "true";
break;
case JsonFalse:
json += "false";
break;
case JsonString:
json += "\"" + valueStr_ + "\"";
break;
case JsonNumber:
try {
json += std::to_string(valueNum_);
} catch(std::exception& ) {
json += "0";
}
break;
}
}
}
| 24.188498
| 90
| 0.439704
|
shawndfl
|
0d8cd40a38502f306fcf411fca8525436a599e58
| 5,382
|
cpp
|
C++
|
src/UDPSocket.cpp
|
MaoChen1980/wrighteaglebase
|
12b29e5d6d9ada4dd98ec288f7cb6fb845596717
|
[
"BSD-2-Clause"
] | 86
|
2016-06-16T05:10:57.000Z
|
2022-03-01T08:02:43.000Z
|
src/UDPSocket.cpp
|
rc2dcc/wrighteaglebase
|
f6be453447b657fa4c7417b5b62b5ea2067409bc
|
[
"BSD-2-Clause"
] | 1
|
2020-03-04T16:59:58.000Z
|
2020-03-04T16:59:58.000Z
|
src/UDPSocket.cpp
|
rc2dcc/wrighteaglebase
|
f6be453447b657fa4c7417b5b62b5ea2067409bc
|
[
"BSD-2-Clause"
] | 43
|
2016-07-08T03:19:19.000Z
|
2022-01-12T12:28:44.000Z
|
/************************************************************************************
* WrightEagle (Soccer Simulation League 2D) *
* BASE SOURCE CODE RELEASE 2016 *
* Copyright (c) 1998-2016 WrightEagle 2D Soccer Simulation Team, *
* Multi-Agent Systems Lab., *
* School of Computer Science and Technology, *
* University of Science and Technology of China *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are met: *
* * Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* * Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* * Neither the name of the WrightEagle 2D Soccer Simulation Team 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 WrightEagle 2D Soccer Simulation Team 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 "UDPSocket.h"
//==============================================================================
UDPSocket::UDPSocket()
{
mIsInitialOK = false;
}
//==============================================================================
UDPSocket::~UDPSocket()
{
}
//==============================================================================
UDPSocket & UDPSocket::instance()
{
static UDPSocket udp_socket;
return udp_socket;
}
//==============================================================================
void UDPSocket::Initial(const char *host, int port)
{
struct hostent *host_ent ;
struct in_addr *addr_ptr ;
#ifdef WIN32
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD( 2, 2 );
if (WSAStartup(wVersionRequested, &wsaData) != 0)
{
PRINT_ERROR("WSAStartup failed");
}
if (LOBYTE( wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
{
WSACleanup();
PRINT_ERROR("WSASTartup version mismatch");
}
#endif
if ((host_ent = (struct hostent *)gethostbyname(host)) == 0)
{
if (inet_addr(host) == INADDR_NONE)
PRINT_ERROR("Invalid host name");
}
else
{
addr_ptr = (struct in_addr *) *host_ent->h_addr_list ;
host = inet_ntoa(*addr_ptr) ;
}
if( (mSockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
PRINT_ERROR("Can't create socket") ;
}
memset(&mAddress, 0, sizeof(mAddress)) ;
mAddress.sin_family = AF_INET ;
mAddress.sin_addr.s_addr = htonl(INADDR_ANY) ;
mAddress.sin_port = htons(0) ;
if(bind(mSockfd, (sockaddr *)&mAddress, sizeof(mAddress)) < 0)
{
#ifdef WIN32
closesocket(mSockfd);
#else
close(mSockfd);
#endif
PRINT_ERROR("Can't bind client to any port") ;
}
memset(&mAddress, 0, sizeof(mAddress)) ;
mAddress.sin_family = AF_INET ;
mAddress.sin_addr.s_addr = inet_addr( host ) ;
mAddress.sin_port = htons( port ) ;
mIsInitialOK = true;
}
//==============================================================================
int UDPSocket::Receive(char *msg)
{
#ifdef WIN32
int servlen;
#else
socklen_t servlen ;
#endif
sockaddr_in serv_addr;
servlen = sizeof(serv_addr);
int n = recvfrom(mSockfd, msg, MAX_MESSAGE, 0, (sockaddr *)&serv_addr, &servlen);
if (n > 0)
{
msg[n] = '\0' ; // rccparser will crash if msg has no end
mAddress.sin_port = serv_addr.sin_port ;
}
return n ;
}
//==============================================================================
int UDPSocket::Send(const char *msg)
{
if (mIsInitialOK == true)
{
int n = std::strlen(msg) ;
n = sendto(mSockfd, msg, n+1, 0, (sockaddr *)&mAddress, sizeof(mAddress));
return n;
}
std::cout << msg << std::endl;
return std::strlen(msg);
}
//end of UDPSocket.cpp
| 34.722581
| 86
| 0.533631
|
MaoChen1980
|
0d8e59b76d9e6fc939bee9474ebe232cef51a86f
| 1,088
|
cpp
|
C++
|
src/backlight_set.cpp
|
klokik/JemUtilities
|
21dd11aae53557109e1b1613c2343c8a1eb5d165
|
[
"MIT"
] | 1
|
2021-01-13T07:57:05.000Z
|
2021-01-13T07:57:05.000Z
|
src/backlight_set.cpp
|
klokik/JemUtilities
|
21dd11aae53557109e1b1613c2343c8a1eb5d165
|
[
"MIT"
] | null | null | null |
src/backlight_set.cpp
|
klokik/JemUtilities
|
21dd11aae53557109e1b1613c2343c8a1eb5d165
|
[
"MIT"
] | null | null | null |
#include <cstring>
#include <iostream>
#include <fstream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char **argv) {
if (argc != 2) {
std::cout << "Invalid parameters" << std::endl;
return 0;
}
int delta = atoi(argv[1]);
int max_level = 7;
int cur_level = 3;
if (setuid(0)) {
std::cout << "Failed to set uid 0, trying with curent id ..." << std::endl;
}
std::string path = "/sys/class/backlight/backlight";
try {
std::ifstream ifs_max(path + "/max_brightness");
ifs_max >> max_level;
ifs_max.close();
std::ifstream ifs_cur(path + "/actual_brightness");
ifs_cur >> cur_level;
ifs_cur.close();
int new_level = cur_level+delta;
if (new_level < 0)
new_level = 0;
if (new_level > max_level)
new_level = max_level;
char buf[15];
sprintf(&buf[0], "%d", new_level);
std::ofstream ofs_set(path + "/brightness");
ofs_set.write(&buf[0], strlen(buf));
ofs_set.close();
}
catch (...) {
std::cout << "An IO error occured, do you have enough permissions?" << std::endl;
return -1;
}
return 0;
}
| 18.758621
| 83
| 0.629596
|
klokik
|
0d8f9eaa121e233592aaf3d98c930b091a2cf348
| 924
|
hpp
|
C++
|
include/platform/internal/list/top_type.hpp
|
vladankor/types_library
|
9f0f64946b621c447c5f72a6df34ced9438b1ff2
|
[
"MIT"
] | null | null | null |
include/platform/internal/list/top_type.hpp
|
vladankor/types_library
|
9f0f64946b621c447c5f72a6df34ced9438b1ff2
|
[
"MIT"
] | null | null | null |
include/platform/internal/list/top_type.hpp
|
vladankor/types_library
|
9f0f64946b621c447c5f72a6df34ced9438b1ff2
|
[
"MIT"
] | null | null | null |
// ----------------------------------------------------------------------------
// Copyright (C) 2019 Korobov Vladislav
// ----------------------------------------------------------------------------
#pragma once
//- platform ------------------------------------------------------------------
#include <platform/internal/list/list_type.hpp>
// ----------------------------------------------------------------------------
namespace platform::internal {
//-----------------------------------------------------------------------------
// struct top_type
//-----------------------------------------------------------------------------
template<class ...>
struct top_type;
template<class ...TArgs>
struct top_type<list_type<TArgs...>> {
using type = typename list_type<TArgs...>::head_type;
}; // top_type
template<class ...TArgs>
using top_t = typename top_type<TArgs...>::type;
} // namespace platform::internal
| 28.875
| 79
| 0.351732
|
vladankor
|
0d964f38068ef7aecaf433a374b4bd07436db0ab
| 4,857
|
cc
|
C++
|
lib/pods-trie-builder.cc
|
rockeet/taiju
|
90f152d5e66b1741d35b9d871f7a5db68699d48d
|
[
"BSD-3-Clause"
] | null | null | null |
lib/pods-trie-builder.cc
|
rockeet/taiju
|
90f152d5e66b1741d35b9d871f7a5db68699d48d
|
[
"BSD-3-Clause"
] | null | null | null |
lib/pods-trie-builder.cc
|
rockeet/taiju
|
90f152d5e66b1741d35b9d871f7a5db68699d48d
|
[
"BSD-3-Clause"
] | null | null | null |
#include <taiju/pods-trie-builder.h>
#include <algorithm>
namespace taiju {
PodsTrieBuilder::PodsTrieBuilder() : node_order_(DEFAULT_NODE_ORDER),
num_keys_(0), child_diffs_(), has_siblings_(), labels_(),
is_terminals_(), inters_(), finished_(false) {}
UInt64 PodsTrieBuilder::size() const
{
return sizeof(TrieType) + sizeof(UInt64) + child_diffs_.size()
+ has_siblings_.size() + labels_.size() + is_terminals_.size();
}
void PodsTrieBuilder::open(NodeOrder node_order)
{
PodsTrieBuilder temp;
switch (node_order)
{
case ASCENDING_LABEL_ORDER:
case DESCENDING_LABEL_ORDER:
case TOTAL_WEIGHT_ORDER:
case MAX_WEIGHT_ORDER:
case RANDOM_ORDER:
temp.node_order_ = node_order;
break;
default:
TAIJU_THROW("failed to open PodsTrieBuilder: invalid NodeOrder");
}
temp.child_diffs_.open();
temp.has_siblings_.open();
temp.labels_.open();
temp.is_terminals_.open(ONLY_RANK_INDEX);
temp.append_inter(TrieNode());
swap(&temp);
}
void PodsTrieBuilder::close()
{
node_order_ = DEFAULT_NODE_ORDER;
num_keys_ = 0;
child_diffs_.clear();
has_siblings_.clear();
labels_.clear();
is_terminals_.clear();
inters_.clear();
finished_ = false;
}
void PodsTrieBuilder::append(const void *ptr, UInt64 size, double weight)
{
if (finished())
TAIJU_THROW("failed to append: the builder is finished");
append_key(static_cast<const UInt8 *>(ptr), size, weight);
}
void PodsTrieBuilder::finish()
{
finished_ = true;
flush(0);
if (!inters_.empty())
{
append_node(inters_[0]);
inters_.clear();
}
child_diffs_.finish();
has_siblings_.finish();
labels_.finish();
is_terminals_.finish();
}
void PodsTrieBuilder::swap(PodsTrieBuilder *target)
{
std::swap(node_order_, target->node_order_);
std::swap(num_keys_, target->num_keys_);
child_diffs_.swap(&target->child_diffs_);
has_siblings_.swap(&target->has_siblings_);
labels_.swap(&target->labels_);
is_terminals_.swap(&target->is_terminals_);
inters_.swap(&target->inters_);
std::swap(finished_, target->finished_);
}
void PodsTrieBuilder::write(Writer writer)
{
finish();
writer.write(type());
writer.write(num_keys_);
child_diffs_.write(writer);
has_siblings_.write(writer);
labels_.write(writer);
is_terminals_.write(writer);
}
void PodsTrieBuilder::append_key(const UInt8 *key, UInt64 length,
double weight)
{
UInt64 id = 0;
for ( ; length > 0; ++key, --length)
{
if (!inters_[id].has_child())
break;
UInt64 child_id = inters_[id].child();
UInt8 label = inters_[child_id].label();
if (*key < label)
TAIJU_THROW("failed to append: wrong key order");
else if (*key > label)
{
flush(child_id);
inters_[child_id].set_has_sibling(true);
break;
}
switch (node_order_)
{
case ASCENDING_LABEL_ORDER:
case DESCENDING_LABEL_ORDER:
break;
case TOTAL_WEIGHT_ORDER:
inters_[id].set_weight(inters_[id].weight() + weight);
break;
case MAX_WEIGHT_ORDER:
if (weight > inters_[id].weight())
inters_[id].set_weight(weight);
break;
case RANDOM_ORDER:
break;
}
id = child_id;
}
for ( ; length > 0; ++key, --length)
{
UInt64 child_id = inters_.num_objs();
inters_[id].set_has_child(true);
inters_[id].set_child(child_id);
TrieNode node;
node.set_label(*key);
node.set_weight(weight);
append_inter(node);
id = child_id;
}
inters_[id].set_is_terminal(true);
++num_keys_;
}
void PodsTrieBuilder::append_inter(const TrieNode &node)
{
if (!inters_.push(node))
TAIJU_THROW("failed to append: Vector::push() failed");
}
void PodsTrieBuilder::append_node(const TrieNode &node)
{
if (node.has_child())
child_diffs_.append(labels_.num_objs() - node.child());
else
child_diffs_.append(0);
has_siblings_.append(node.has_sibling());
labels_.append(node.label());
is_terminals_.append(node.is_terminal());
}
void PodsTrieBuilder::flush(UInt64 root)
{
while (root + 1 < inters_.num_objs())
{
std::size_t end_id = static_cast<std::size_t>(inters_.num_objs());
std::size_t begin_id = end_id - 1;
while (inters_[begin_id - 1].has_sibling())
--begin_id;
if (end_id - begin_id > 1)
{
inters_[end_id - 1].set_has_sibling(true);
switch (node_order_)
{
case ASCENDING_LABEL_ORDER:
break;
case DESCENDING_LABEL_ORDER:
std::reverse(inters_.begin() + begin_id,
inters_.begin() + end_id);
break;
case TOTAL_WEIGHT_ORDER:
case MAX_WEIGHT_ORDER:
std::stable_sort(inters_.begin() + begin_id,
inters_.begin() + end_id, TrieNode::WeightComparer());
break;
case RANDOM_ORDER:
std::random_shuffle(inters_.begin() + begin_id,
inters_.begin() + end_id);
break;
}
inters_[end_id - 1].set_has_sibling(false);
}
for (UInt64 id = end_id; id > begin_id; --id)
append_node(inters_[id - 1]);
inters_.resize(begin_id);
inters_[begin_id - 1].set_child(labels_.num_objs() - 1);
}
}
} // namespace taiju
| 21.977376
| 73
| 0.704756
|
rockeet
|
0d98aabd50b6a9bbb935961018a67849b610b39d
| 10,763
|
cpp
|
C++
|
Bicycle.cpp
|
MKoi/BicycleAdventure
|
238464e1546edd332522e375e92c022ec0174dd9
|
[
"MIT"
] | null | null | null |
Bicycle.cpp
|
MKoi/BicycleAdventure
|
238464e1546edd332522e375e92c022ec0174dd9
|
[
"MIT"
] | null | null | null |
Bicycle.cpp
|
MKoi/BicycleAdventure
|
238464e1546edd332522e375e92c022ec0174dd9
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "Bicycle.h"
#include "GameArea.h"
#include <vector>
using namespace DirectX;
using namespace std;
using namespace Windows::Storage;
Bicycle::Bicycle(b2World* world, const b2Vec2& pos, const Physics::Parameters& params, GameAudio* audio) :
m_wheelRadius(0.5f), m_hubRadius(m_wheelRadius/3.0f), m_controls(this),
m_fWheelCenter(2 * m_wheelRadius, 0.0f), m_rWheelCenter(-2 * m_wheelRadius, 0.0f), m_pedalOffset(m_hubRadius, 0.0f),
m_frame(nullptr), m_frontWheel(nullptr), m_rearWheel(nullptr), m_pedals(nullptr),
m_frontJoint(nullptr), m_rearJoint(nullptr), m_pedalJoint(nullptr),
m_frameGfx(D3D_PRIMITIVE_TOPOLOGY::D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST),
m_fWheelGfx(D3D_PRIMITIVE_TOPOLOGY::D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST),
m_rWheelGfx(D3D_PRIMITIVE_TOPOLOGY::D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST),
m_pedalsGfx(D3D_PRIMITIVE_TOPOLOGY::D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST),
m_dirt(world),
m_rearWheelContacts(0),
m_frontWheelContacts(0),
m_pedalAngle(0.0f),
m_audio(audio)
{
b2Vec2 framePos = pos + b2Vec2(2 * m_wheelRadius, m_wheelRadius);
m_vertices[e_hub].Set(-0.2f, 0.0f);
m_vertices[e_handle].Set(0.8f, 1.0f);
m_vertices[e_saddle].Set(-0.5f, 1.0f);
// m_fWheelCenter.Set(2*m_wheelRadius, 0.0f);
// m_rWheelCenter.Set(-2*m_wheelRadius, 0.0f);
// m_pedalOffset.Set(m_hubRadius, 0.0f);
m_frame = Physics::CreatePolygon(world, params, m_vertices, e_size, framePos);
m_frontWheel = Physics::CreateCircle(world, params, m_wheelRadius, m_frame->GetWorldPoint(m_fWheelCenter));
m_rearWheel = Physics::CreateCircle(world, params, m_wheelRadius, m_frame->GetWorldPoint(m_rWheelCenter));
m_pedals = Physics::CreateCircle(world, params, m_hubRadius, m_frame->GetWorldPoint(m_vertices[e_hub]));
CreateWheelJoints();
m_pedalJoint = Physics::CreateRevoluteJoint(m_frame, m_pedals, m_pedals->GetPosition());
CreateFrameGfx();
CreateWheelGfx();
CreatePedalsGfx();
AddPart(m_frontWheel, &m_fWheelGfx);
AddPart(m_rearWheel, &m_rWheelGfx);
AddPart(m_frame, &m_frameGfx);
AddPart(m_pedals, &m_pedalsGfx);
m_pedalAngle = m_pedals->GetAngle();
}
void Bicycle::Reset(const b2Vec2& pos)
{
b2Vec2 framePos = pos + b2Vec2(2 * m_wheelRadius, m_wheelRadius);
Physics::ResetBody(m_frame, framePos);
Physics::ResetBody(m_frontWheel, m_frame->GetWorldPoint(m_fWheelCenter));
Physics::ResetBody(m_rearWheel, m_frame->GetWorldPoint(m_rWheelCenter));
Physics::ResetBody(m_pedals, m_frame->GetWorldPoint(m_vertices[e_hub]));
CreateWheelJoints();
m_controls.Reset();
m_dirt.Clear();
Update(0.0f);
m_rearWheelContacts = 0;
m_frontWheelContacts = 0;
}
void Bicycle::StartSound()
{
if (OnGround())
{
m_audio->Play(GameAudio::eRolling);
}
}
void Bicycle::SaveState(Streams::DataWriter^ state) const
{
GameObject::SaveState(state);
state->WriteInt32(m_rearWheelContacts);
state->WriteInt32(m_frontWheelContacts);
}
void Bicycle::RestoreState(Streams::DataReader^ state)
{
GameObject::RestoreState(state);
m_rearWheelContacts = state->ReadInt32();
m_frontWheelContacts = state->ReadInt32();
}
/*
void Bicycle::DrawDebugData(Graphics* draw) const
{
if (!RearWheelGround())
draw->DrawSolidCircle(m_rearWheel->GetPosition(), m_wheelRadius*1.2f, b2Vec2_zero, Graphics::red);
if (!FrontWheelGround())
draw->DrawSolidCircle(m_frontWheel->GetPosition(), m_wheelRadius*1.2f, b2Vec2_zero, Graphics::red);
}
*/
void Bicycle::Draw(Renderer^ renderBatch) const
{
m_dirt.Draw(renderBatch);
GameObject::Draw(renderBatch);
}
void Bicycle::Update(float dt)
{
m_controls.Update(dt);
GameObject::Update(dt);
CheckJointForces(dt);
m_dirt.Update(dt);
EmitDirt();
PlayPedalSound();
PlayWheelSound();
}
void Bicycle::BeginContact(b2Contact* c)
{
if (Physics::Touching(c, m_rearWheel, Physics::GroundCategory))
{
m_rearWheelContacts++;
}
else if (Physics::Touching(c, m_rearWheel, Physics::WallCategory))
{
m_rearWheelContacts++;
}
else if (Physics::Touching(c, m_frontWheel, Physics::GroundCategory))
{
m_frontWheelContacts++;
}
else if (Physics::Touching(c, m_frontWheel, Physics::WallCategory))
{
m_frontWheelContacts++;
}
}
void Bicycle::EndContact(b2Contact* c)
{
if (Physics::Touching(c, m_rearWheel, Physics::GroundCategory))
{
m_rearWheelContacts--;
}
else if (Physics::Touching(c, m_rearWheel, Physics::WallCategory))
{
m_rearWheelContacts--;
}
else if (Physics::Touching(c, m_frontWheel, Physics::GroundCategory))
{
m_frontWheelContacts--;
}
else if (Physics::Touching(c, m_frontWheel, Physics::WallCategory))
{
m_frontWheelContacts--;
}
}
void Bicycle::SetSpeed(float speed, bool rollFree)
{
const float pedalToWheelRatio = 5.0f;
const float maxTorque = 20.0f;
if (m_rearJoint != nullptr)
{
Physics::SetMotor(m_rearJoint, speed, maxTorque, !rollFree);
}
Physics::SetMotor(m_pedalJoint, speed/pedalToWheelRatio, maxTorque, true);
}
void Bicycle::CreateFrameGfx()
{
const float ratio = 0.06f;
Graphics::CreateSolidLine(m_vertices[e_hub], m_vertices[e_handle], ratio, Graphics::red, m_frameGfx);
Graphics::CreateSolidLine(m_vertices[e_handle], m_vertices[e_saddle], ratio, Graphics::red, m_frameGfx);
Graphics::CreateSolidLine(m_vertices[e_saddle], m_vertices[e_hub], ratio, Graphics::red, m_frameGfx);
Graphics::CreateSolidLine(m_vertices[e_saddle], m_rWheelCenter, ratio, Graphics::red, m_frameGfx);
Graphics::CreateSolidLine(m_vertices[e_hub], m_rWheelCenter, ratio, Graphics::red, m_frameGfx);
Graphics::CreateSolidLine(m_vertices[e_handle], m_fWheelCenter, ratio, Graphics::red, m_frameGfx);
}
void Bicycle::CreateWheelGfx()
{
const int spokeCount = 7;
const float thicknessRatio = 0.02f;
const float inner_r1 = 0.15f;
const float inner_r2 = 0.2f;
const float outer_r1 = 0.85f;
const float outer_r2 = 0.9f;
CreateSpokeGfx(outer_r1*m_wheelRadius, spokeCount, thicknessRatio, Graphics::black, m_fWheelGfx);
//Graphics::CreateSolidCircle(b2Vec2_zero, m_wheelRadius * inner_r2, Graphics::black, m_wheelGfx);
Graphics::CreateSolidCircle(b2Vec2_zero, m_wheelRadius * inner_r2, Graphics::grey, m_fWheelGfx);
//Graphics::CreateSphere(b2Vec2_zero, m_wheelRadius * outer_r2, outer_r1/outer_r2, Graphics::grey, m_wheelGfx);
Graphics::CreateSphere(b2Vec2_zero, m_wheelRadius, outer_r2, Graphics::black, m_fWheelGfx);
m_rWheelGfx = m_fWheelGfx;
}
void Bicycle::CreatePedalsGfx()
{
const int spokeCount = 5;
const float spokeThickness = 0.2f;
const float pedalThickness = 0.2f;
const float inner_r = 0.3f;
const float outer_r = 0.6f;
CreateSpokeGfx(outer_r*m_hubRadius, spokeCount, spokeThickness, Graphics::grey, m_pedalsGfx);
Graphics::CreateSolidCircle(b2Vec2_zero, inner_r*m_hubRadius, Graphics::grey, m_pedalsGfx);
Graphics::CreateSphere(b2Vec2_zero, m_hubRadius, outer_r, Graphics::grey, m_pedalsGfx);
Graphics::CreateSolidLine(b2Vec2_zero, m_pedalOffset, pedalThickness, Graphics::darkGrey, m_pedalsGfx);
}
void Bicycle::CreateSpokeGfx(float radius, int spokeCount, float thicknessRatio, b2Color color, VerticeBatch& target)
{
XMMATRIX xf = Graphics::CircleTransform(b2Vec2_zero, spokeCount);
XMVECTOR point = XMVectorSet(radius, 0.0f, 0.0f, 0.0f);
b2Vec2 point2d;
for (int i = 0; i < spokeCount; ++i)
{
point2d.Set(XMVectorGetX(point), XMVectorGetY(point));
Graphics::CreateSolidLine(b2Vec2_zero, point2d, thicknessRatio, Graphics::grey, target);
point = XMVector2Transform(point, xf);
}
}
void Bicycle::EmitDirt()
{
const unsigned int interval = 10;
static unsigned int count = 0;
b2Vec2 point;
b2Vec2 normal;
if (RearWheelGround())
{
Physics::TouchingGround(m_rearWheel, point, normal);
float angular = -m_rearWheel->GetAngularVelocity() * m_wheelRadius;
b2Vec2 linear = m_rearWheel->GetLinearVelocity();
float diff = abs(angular - linear.Length());
bool lockedBreaks = angular < 1.0f && linear.Length() > 5.0f;
bool spinningOnSpot = angular > 5.0f && linear.Length() < 2.0f;
++count;
if (lockedBreaks || spinningOnSpot)
{
m_dirt.Emit(1, point - 0.2f * normal, -0.0001f * diff * normal);
if (count % interval == 0)
{
m_audio->Play(GameAudio::eGravel, 0.7f);
count = 0;
}
#if 0
char buf[64];
sprintf_s(buf, "dirt %d\n", (int)diff);
OutputDebugStringA(buf);
#endif
}
}
}
void Bicycle::PlayPedalSound()
{
float newAngle = m_pedals->GetAngle();
float a1 = DirectX::XMScalarModAngle(m_pedalAngle);
float a2 = DirectX::XMScalarModAngle(newAngle);
if (a1 > 0.0f && a2 < 0.0f)
{
m_audio->Play(GameAudio::ePedalUp, 0.7f);
}
if (a1 < 0.0f && a2 > 0.0f)
{
m_audio->Play(GameAudio::ePedalDown, 0.7f);
}
m_pedalAngle = newAngle;
}
void Bicycle::PlayWheelSound()
{
float v1 = (m_rearJoint && m_rearWheelContacts) ? abs(m_rearWheel->GetAngularVelocity()) : 0.0f;
float v2 = (m_frontJoint && m_frontWheelContacts) ? abs(m_rearWheel->GetAngularVelocity()) : 0.0f;
float v = max(v1, v2);
float vol = 0.01f * v;
m_audio->SetVolume(GameAudio::eRolling, vol);
}
void Bicycle::PlayBrakeSound()
{
int ipos = static_cast<int>(GetPosition().x);
float vel = GetSpeed().Length();
float vol = min(1.0f, vel / 40.0f);
m_audio->Play((vol >= 1.0) ? GameAudio::eBrakeLong : GameAudio::eBrakeShort, vol);
}
void Bicycle::CheckJointForces(float dt)
{
if (dt == 0.0f)
{
return;
}
const float maxForceSq = 1000000;
if (m_rearJoint != nullptr)
{
b2Vec2 reactionForce = m_rearJoint->GetReactionForce(1.0f / dt);
float forceModuleSq = reactionForce.LengthSquared();
if (forceModuleSq > maxForceSq)
{
m_frame->GetWorld()->DestroyJoint(m_rearJoint);
m_rearJoint = nullptr;
}
}
if (m_frontJoint != nullptr)
{
b2Vec2 reactionForce = m_frontJoint->GetReactionForce(1.0f / dt);
float forceModuleSq = reactionForce.LengthSquared();
if (forceModuleSq > maxForceSq)
{
m_frame->GetWorld()->DestroyJoint(m_frontJoint);
m_frontJoint = nullptr;
}
}
}
void Bicycle::CreateWheelJoints()
{
b2Vec2 axis = m_fWheelCenter - m_vertices[e_handle];
if (m_frontJoint == nullptr)
{
m_frontJoint = Physics::CreateWheelJoint(m_frame, m_frontWheel, m_frontWheel->GetPosition(), axis);
}
axis = m_rWheelCenter - m_vertices[e_saddle];
if (m_rearJoint == nullptr)
{
m_rearJoint = Physics::CreateWheelJoint(m_frame, m_rearWheel, m_rearWheel->GetPosition(), axis);
}
}
void Bicycle::ApplyDamping(float damping)
{
m_frame->SetLinearDamping(damping);
m_frontWheel->SetLinearDamping(damping);
m_rearWheel->SetLinearDamping(damping);
m_pedals->SetLinearDamping(damping);
}
| 31.017291
| 118
| 0.720524
|
MKoi
|
0d98ab6daf849b0743bdc26a428e0712ecb22227
| 2,111
|
cpp
|
C++
|
src/implementation/backends/DirectX11/DirectX11_Renderer.cpp
|
LarsHagemann/OrbitEngine
|
33e01efaac617c53a701f01729581932fc81e8bf
|
[
"MIT"
] | null | null | null |
src/implementation/backends/DirectX11/DirectX11_Renderer.cpp
|
LarsHagemann/OrbitEngine
|
33e01efaac617c53a701f01729581932fc81e8bf
|
[
"MIT"
] | 2
|
2022-01-18T21:31:01.000Z
|
2022-01-20T21:02:09.000Z
|
src/implementation/backends/DirectX11/DirectX11_Renderer.cpp
|
LarsHagemann/OrbitEngine
|
33e01efaac617c53a701f01729581932fc81e8bf
|
[
"MIT"
] | null | null | null |
#ifdef ORBIT_DIRECTX_11
#include "implementation/backends/DirectX11/DirectX11_Renderer.hpp"
#include "implementation/engine/Engine.hpp"
#include "implementation/backends/impl/PipelineStateImpl.hpp"
#include "interfaces/rendering/Material.hpp"
namespace orbit
{
void DirectX11Renderer::Draw(const Submesh& submesh, uint32_t instanceCount) const
{
if (submesh.pipelineStateId != m_currentPipelineState)
{
m_currentPipelineState = submesh.pipelineStateId;
ENGINE->RMLoadResource<PipelineState>(submesh.pipelineStateId)->Bind();
}
if (submesh.materialId != m_currentMaterial && submesh.materialId != 0)
{
m_currentMaterial = submesh.materialId;
ENGINE->RMLoadResource<MaterialBase>(submesh.materialId)->Bind(1);
}
if (submesh.indexCount > 0)
ENGINE->Context()->DrawIndexedInstanced(submesh.indexCount, instanceCount, submesh.startIndex, submesh.startVertex, 0);
else
ENGINE->Context()->DrawInstanced(submesh.vertexCount, instanceCount, submesh.startVertex, 0);
}
void DirectX11Renderer::BindTextureImpl(ResourceId id, uint32_t slot) const
{
ENGINE->RMLoadResource<Texture>(id)->Bind(slot);
}
void DirectX11Renderer::BindMaterialImpl(ResourceId id) const
{
ENGINE->RMLoadResource<MaterialBase>(id)->Bind(1);
}
void DirectX11Renderer::BindVertexShaderImpl(ResourceId id) const
{
ENGINE->RMLoadResource<VertexShader>(id)->Bind();
}
void DirectX11Renderer::BindPixelShaderImpl(ResourceId id) const
{
ENGINE->RMLoadResource<PixelShader>(id)->Bind();
}
void DirectX11Renderer::BindGeometryShaderImpl(ResourceId id) const
{
ENGINE->RMLoadResource<GeometryShader>(id)->Bind();
}
void DirectX11Renderer::BindDomainShaderImpl(ResourceId id) const
{
ENGINE->RMLoadResource<DomainShader>(id)->Bind();
}
void DirectX11Renderer::BindHullShaderImpl(ResourceId id) const
{
ENGINE->RMLoadResource<HullShader>(id)->Bind();
}
}
#endif
| 31.984848
| 131
| 0.690668
|
LarsHagemann
|
0d99559cc43104cf0ac5c62438a402e35ae4156f
| 278
|
hpp
|
C++
|
include/toy/parser/Export.hpp
|
ToyAuthor/ToyBox
|
f517a64d00e00ccaedd76e33ed5897edc6fde55e
|
[
"Unlicense"
] | 4
|
2017-07-06T22:18:41.000Z
|
2021-05-24T21:28:37.000Z
|
include/toy/parser/Export.hpp
|
ToyAuthor/ToyBox
|
f517a64d00e00ccaedd76e33ed5897edc6fde55e
|
[
"Unlicense"
] | null | null | null |
include/toy/parser/Export.hpp
|
ToyAuthor/ToyBox
|
f517a64d00e00ccaedd76e33ed5897edc6fde55e
|
[
"Unlicense"
] | 1
|
2020-08-02T13:00:38.000Z
|
2020-08-02T13:00:38.000Z
|
#pragma once
#include "toy/CompilerConfig.hpp"
#if defined(TOY_WINDOWS) && TOY_OPTION_DYNAMIC_LIBRARY
#ifdef TOY_EXPORT_PARSER
#define TOY_API_PARSER __declspec(dllexport)
#else
#define TOY_API_PARSER __declspec(dllimport)
#endif
#else
#define TOY_API_PARSER
#endif
| 17.375
| 54
| 0.794964
|
ToyAuthor
|
0d9d85336096deb9daab6754a5cbf138af6dbb34
| 180
|
cpp
|
C++
|
bin/test-libsept/main.cpp
|
vdods/sept
|
08ee1faf1af4feb0dc440a3002eb8cc52681f946
|
[
"Apache-2.0"
] | null | null | null |
bin/test-libsept/main.cpp
|
vdods/sept
|
08ee1faf1af4feb0dc440a3002eb8cc52681f946
|
[
"Apache-2.0"
] | null | null | null |
bin/test-libsept/main.cpp
|
vdods/sept
|
08ee1faf1af4feb0dc440a3002eb8cc52681f946
|
[
"Apache-2.0"
] | null | null | null |
// 2020.03.13 - Victor Dods
#include <lvd/test.hpp>
int main (int argc, char **argv) {
return lvd::test::basic_test_main("septtest -- unit tests for libsept", argc, argv);
}
| 22.5
| 88
| 0.666667
|
vdods
|
d3ffe19f4e5d73c8e68d7f80abde58c3135ea1df
| 4,875
|
cpp
|
C++
|
TopCoderSRM/SRM603/GraphWalkWithProbabilities.cpp
|
zombiecry/AlgorithmPractice
|
f42933883bd62a86aeef9740356f5010c6c9bebf
|
[
"MIT"
] | null | null | null |
TopCoderSRM/SRM603/GraphWalkWithProbabilities.cpp
|
zombiecry/AlgorithmPractice
|
f42933883bd62a86aeef9740356f5010c6c9bebf
|
[
"MIT"
] | null | null | null |
TopCoderSRM/SRM603/GraphWalkWithProbabilities.cpp
|
zombiecry/AlgorithmPractice
|
f42933883bd62a86aeef9740356f5010c6c9bebf
|
[
"MIT"
] | null | null | null |
// BEGIN CUT HERE
// END CUT HERE
#line 5 "GraphWalkWithProbabilities.cpp"
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
using namespace std;
typedef std::pair <int,int> scPair2i;
typedef std::vector <int> scVeci;
typedef std::vector <scPair2i> scVec2i;
typedef std::stack <int> scStacki;
typedef std::queue <int> scQueuei;
typedef std::set <int> scSeti;
typedef std::map<int,int> scMapii;
typedef std::map<int,int>::iterator scMapiiIter;
typedef std::map<int,int>::reverse_iterator scMapiiRevIter;
#define tr(container,it) \
for (it=container.begin();it!=container.end();it++)
#define trRev(container,it) \
for (it=container.rbegin();it!=container.rend();it++)
#define scFor0(x,num) \
for (int x=0;x<num;x++)
#define scFor1(x,start,num) \
for (int x=start;x<num;x++)
int m,n;
class GraphWalkWithProbabilities
{
public:
double c[2][51];
double findprob(vector <string> graph, vector <int> winprob, vector <int> looseprob, int Start)
{
//$CARETPOSITION$
n=winprob.size();
scFor0(i,n){
c[0][i]=c[1][i]=0.0;
}
scVeci conProb;
conProb.resize(n);
scFor0(i,n){
conProb[i]=100-winprob[i]-looseprob[i];
}
scFor0(t,10000){
scFor0(i,n){
c[1][i]=0.0;
scFor0(j,n){
if (graph[i][j]=='1'){
double q=winprob[j]/100.0 + conProb[j]*c[0][j]/100.0;
c[1][i]=max(c[1][i],q);
}
}
}
memcpy(c[0],c[1],sizeof(c[1]));
}
return c[0][Start];
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"1"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {1}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 0; double Arg4 = 0.5; verify_case(0, Arg4, findprob(Arg0, Arg1, Arg2, Arg3)); }
void test_case_1() { string Arr0[] = {"11","11"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {60,40}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {40,60}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 0; double Arg4 = 0.6; verify_case(1, Arg4, findprob(Arg0, Arg1, Arg2, Arg3)); }
void test_case_2() { string Arr0[] = {"11","11"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {2,3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {3,4}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 0; double Arg4 = 0.4285714285714286; verify_case(2, Arg4, findprob(Arg0, Arg1, Arg2, Arg3)); }
void test_case_3() { string Arr0[] = {"110","011","001"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {2,1,10}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {20,20,10}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 0; double Arg4 = 0.405; verify_case(3, Arg4, findprob(Arg0, Arg1, Arg2, Arg3)); }
void test_case_4() { string Arr0[] = {"111","111","011"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {100,1,1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {0,50,50}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 2; double Arg4 = 0.5; verify_case(4, Arg4, findprob(Arg0, Arg1, Arg2, Arg3)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
GraphWalkWithProbabilities ___test;
___test.run_test(-1);
system("pause");
}
// END CUT HERE
| 47.794118
| 400
| 0.59959
|
zombiecry
|
31050df677ea032ac1c4b7779ecc6c6aa402a152
| 1,290
|
cpp
|
C++
|
src/row.cpp
|
dashboardvision/aspose-php
|
e2931773cbb1f47ae4086d632faa3012bd952b99
|
[
"MIT"
] | null | null | null |
src/row.cpp
|
dashboardvision/aspose-php
|
e2931773cbb1f47ae4086d632faa3012bd952b99
|
[
"MIT"
] | null | null | null |
src/row.cpp
|
dashboardvision/aspose-php
|
e2931773cbb1f47ae4086d632faa3012bd952b99
|
[
"MIT"
] | 1
|
2021-06-23T08:02:03.000Z
|
2021-06-23T08:02:03.000Z
|
#include "../include/aspose.h"
#include "../include/collection.h"
#include "../include/cell.h"
#include "../include/row.h"
#include <phpcpp.h>
using namespace Aspose::Slides;
using namespace System;
using namespace std;
using namespace Aspose::Slides;
namespace AsposePhp {
/**
* @brief Desc.
*
* @throw System::ArgumentOutOfRangeException Index is invalid or does not exist
* @return Php::Value
*/
Php::Value Row::idx_get(Php::Parameters ¶ms) {
int index = params[0].numericValue();
try {
return Php::Object("AsposePhp\\Slides\\Cell", wrapObject<ICell, AsposePhp::Cell, &IRow::idx_get>(index));
}
catch(System::ArgumentOutOfRangeException &e) {
throw Php::Exception("Invalid index: " + to_string(index));
}
}
/**
* @brief Returns the number of items in collection
*
* @return Php::Value
*/
Php::Value Row::get_Count() {
return _asposeObj->get_Count();
}
/**
* @brief Sets the minimal possible height of a row. Write double
*
* @param params
*/
void Row::set_MinimalHeight(Php::Parameters ¶ms) {
double value = params[0].numericValue();
_asposeObj->set_MinimalHeight(value);
}
}
| 25.294118
| 117
| 0.608527
|
dashboardvision
|
310a0721b4f1babad3b580d662ee60138e02bbe8
| 4,085
|
cc
|
C++
|
sample/src/Program.cc
|
pengrui2009/aliyun-oss-cpp-sdk-windows
|
db3b42fb949d38c577876bcc8d65cd67e31d6dcd
|
[
"Apache-2.0"
] | null | null | null |
sample/src/Program.cc
|
pengrui2009/aliyun-oss-cpp-sdk-windows
|
db3b42fb949d38c577876bcc8d65cd67e31d6dcd
|
[
"Apache-2.0"
] | null | null | null |
sample/src/Program.cc
|
pengrui2009/aliyun-oss-cpp-sdk-windows
|
db3b42fb949d38c577876bcc8d65cd67e31d6dcd
|
[
"Apache-2.0"
] | null | null | null |
#include <alibabacloud/oss/OssClient.h>
#include <iostream>
#include "Config.h"
#if !defined(OSS_DISABLE_BUCKET)
#include "service/ServiceSample.h"
#include "bucket/BucketSample.h"
#endif
#include "object/ObjectSample.h"
#include "presignedurl/PresignedUrlSample.h"
#if !defined(OSS_DISABLE_LIVECHANNEL)
#include "LiveChannel/LiveChannelSample.h"
#endif
#if !defined(OSS_DISABLE_ENCRYPTION)
#include "encryption/EncryptionSample.h"
#endif
using namespace AlibabaCloud::OSS;
void LogCallbackFunc(LogLevel level, const std::string &stream)
{
if (level == LogLevel::LogOff)
return;
std::cout << stream;
}
int main(void)
{
std::cout << "oss-cpp-sdk samples" << std::endl;
std::string bucketName = "<YourBucketName>";
InitializeSdk();
SetLogLevel(LogLevel::LogDebug);
SetLogCallback(LogCallbackFunc);
#if !defined(OSS_DISABLE_BUCKET)
ServiceSample serviceSample;
serviceSample.ListBuckets();
serviceSample.ListBucketsWithMarker();
serviceSample.ListBucketsWithPrefix();
BucketSample bucketSample(bucketName);
bucketSample.InvalidBucketName();
bucketSample.CreateAndDeleteBucket();
bucketSample.SetBucketAcl();
bucketSample.SetBucketLogging();
bucketSample.SetBucketWebsite();
bucketSample.SetBucketReferer();
bucketSample.SetBucketLifecycle();
bucketSample.SetBucketCors();
bucketSample.GetBucketCors();
bucketSample.DeleteBucketLogging();
bucketSample.DeleteBucketWebsite();
bucketSample.DeleteBucketLifecycle();
bucketSample.DeleteBucketCors();
bucketSample.GetBucketAcl();
bucketSample.GetBucketLocation();
bucketSample.GetBucketLogging();
bucketSample.GetBucketWebsite();
bucketSample.GetBucketReferer();
bucketSample.GetBucketStat();
bucketSample.GetBucketLifecycle();
//bucketSample.DeleteBucketsByPrefix();
#endif
ObjectSample objectSample(bucketName);
objectSample.PutObjectFromBuffer();
objectSample.PutObjectFromFile();
objectSample.GetObjectToBuffer();
objectSample.GetObjectToFile();
objectSample.DeleteObject();
objectSample.DeleteObjects();
objectSample.HeadObject();
objectSample.GetObjectMeta();
objectSample.AppendObject();
objectSample.PutObjectProgress();
objectSample.GetObjectProgress();
objectSample.PutObjectCallable();
objectSample.GetObjectCallable();
objectSample.CopyObject();
//objectSample.RestoreArchiveObject("your-archive", "oss_archive_object.PNG", 1);
objectSample.ListObjects();
objectSample.ListObjectWithMarker();
objectSample.ListObjectWithEncodeType();
#if !defined(OSS_DISABLE_RESUAMABLE)
objectSample.UploadObjectProgress();
objectSample.MultiCopyObjectProcess();
objectSample.DownloadObjectProcess();
#endif
PresignedUrlSample signedUrlSample(bucketName);
signedUrlSample.GenGetPresignedUrl();
signedUrlSample.PutObjectByUrlFromBuffer();
signedUrlSample.PutObjectByUrlFromFile();
signedUrlSample.GetObjectByUrlToBuffer();
signedUrlSample.GetObjectByUrlToFile();
#if !defined(OSS_DISABLE_LIVECHANNEL)
// LiveChannel
LiveChannelSample liveChannelSample(bucketName, "test_channel");
liveChannelSample.PutLiveChannel();
liveChannelSample.GetLiveChannelInfo();
liveChannelSample.GetLiveChannelStat();
liveChannelSample.ListLiveChannel();
liveChannelSample.GetLiveChannelHistory();
liveChannelSample.PostVodPlayList();
liveChannelSample.GetVodPlayList();
liveChannelSample.PutLiveChannelStatus();
liveChannelSample.DeleteLiveChannel();
#endif
#if !defined(OSS_DISABLE_ENCRYPTION)
// Encryption
EncryptionSample encryptionSample(bucketName);
encryptionSample.PutObjectFromBuffer();
encryptionSample.PutObjectFromFile();
encryptionSample.GetObjectToBuffer();
encryptionSample.GetObjectToFile();
#if !defined(DISABLE_RESUAMABLE)
encryptionSample.UploadObjectProgress();
encryptionSample.DownloadObjectProcess();
encryptionSample.MultipartUploadObject();
#endif
#endif
ShutdownSdk();
return 0;
}
| 29.388489
| 85
| 0.761812
|
pengrui2009
|
310d40b2fa9336c32c12b3962ecc8dc38036cdaa
| 595
|
cpp
|
C++
|
src/Bubblewrap/Render/BgfxFont.cpp
|
bubblewrap-engine/bubblewrap_bfxr
|
dd41c8f2f43ce79c25ede39c3376292e83257d21
|
[
"MIT"
] | null | null | null |
src/Bubblewrap/Render/BgfxFont.cpp
|
bubblewrap-engine/bubblewrap_bfxr
|
dd41c8f2f43ce79c25ede39c3376292e83257d21
|
[
"MIT"
] | null | null | null |
src/Bubblewrap/Render/BgfxFont.cpp
|
bubblewrap-engine/bubblewrap_bfxr
|
dd41c8f2f43ce79c25ede39c3376292e83257d21
|
[
"MIT"
] | null | null | null |
#include "Bubblewrap/Render/BgfxFont.hpp"
#include "Bubblewrap/Base/Entity.hpp"
#include "Bubblewrap/Base/Base.hpp"
#include "Bubblewrap/Base/BgfxPhysFsInputStream.hpp"
namespace Bubblewrap
{
namespace Render
{
BgfxFont::BgfxFont()
{
}
void BgfxFont::Initialise( Json::Value Params )
{
Font::Initialise( Params );
Stream_.open( Params[ "fontFile" ].asString().c_str() );
// TODO
}
void BgfxFont::Copy( BgfxFont* Target, BgfxFont* Base )
{
Font::Copy( Target, Base );
}
void BgfxFont::OnAttach()
{
}
void BgfxFont::Update( float dt )
{
}
}
}
| 15.25641
| 59
| 0.657143
|
bubblewrap-engine
|
310e6d46935b569640730afeb553dbc4f447fcd2
| 5,316
|
hxx
|
C++
|
Modules/Search/binary_log.hxx
|
Hurna/Hurna-Lib
|
61c267fc6ccf617e92560a84800f6a719cc5c6c8
|
[
"MIT"
] | 2
|
2019-03-29T21:23:02.000Z
|
2019-04-02T19:13:32.000Z
|
Modules/Search/binary_log.hxx
|
Hurna/Hurna-Lib
|
61c267fc6ccf617e92560a84800f6a719cc5c6c8
|
[
"MIT"
] | null | null | null |
Modules/Search/binary_log.hxx
|
Hurna/Hurna-Lib
|
61c267fc6ccf617e92560a84800f6a719cc5c6c8
|
[
"MIT"
] | null | null | null |
/*===========================================================================================================
*
* HUL - Hurna Lib
*
* Copyright (c) Michael Jeulin-Lagarrigue
*
* Licensed under the MIT License, you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/Hurna/Hurna-Lib/blob/master/LICENSE
*
* 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.
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
*=========================================================================================================*/
#ifndef MODULE_SEARCH_BINARY_LOG_HXX
#define MODULE_SEARCH_BINARY_LOG_HXX
#include <Logger/algorithm.hxx>
#include <Logger/vector.hxx>
namespace hul
{
namespace search
{
/// @class Binary
///
template <typename IT, typename Equal = std::equal_to<typename std::iterator_traits<IT>::value_type>>
class Binary
{
typedef typename std::iterator_traits<IT>::value_type T;
public:
static const String GetName() { return "Binary Search"; }
static const String GetVersion() { return "1.0.0"; }
static const String GetType() { return "algorithm"; }
///
static Ostream& Build(Ostream& os, const IT& begin, const IT& end, const T& key)
{
auto builder = std::unique_ptr<Binary>(new Binary(os));
builder->Write(begin, end, key);
return os;
}
///
static IT Build(Logger& logger, const IT& begin, const IT& end, const T& key)
{ return Write(logger, begin, end, key); }
private:
Binary(Ostream& os) : logger(std::unique_ptr<Logger>(new Logger(os))) {}
Binary operator=(Binary&) {} // Not Implemented
IT Write(const IT& begin, const IT& end, const T& key) { return Write(*this->logger, begin, end, key); }
///
static IT Write(Logger& logger, const IT& begin, const IT& end, const T& key)
{
logger.Start(); // Start Logging Procedure
Algo_Traits<Binary>::Build(logger); // Write description
WriteParameters(logger, begin, end, key); // Write parameters
auto it = WriteComputation(logger, begin, end, key); // Write computation
logger.End(); // Close Logging Procedure
return it;
}
///
static void WriteParameters(Logger& logger, const IT& begin, const IT& end, const T& key)
{
logger.StartArray("parameters");
if (logger.GetCurrentLevel() > 0) // Only iterators
{
logger.AddObject(begin, true);
logger.AddObject(end, true);
logger.AddValue("key", key);
}
else // All data
{
logger.AddDataDetails(begin, end, true);
logger.AddValue("key", key);
}
logger.EndArray();
}
///
static IT WriteComputation(Logger& logger, const IT& begin, const IT& end, const T& key)
{
const auto size = static_cast<const int>(std::distance(begin, end));
if (size < 2)
{
if (logger.GetCurrentLevel() == 0)
{
logger.Comment("Sequence too small to be procesed: already sorted.");
logger.Return("void");
}
return end;
}
// Locals
logger.StartArray("locals");
bool found = false;
auto lowIt = begin;
auto highIt = end;
auto curIt = IT(end, "current", true);
logger.EndArray();
// Computation
logger.StartArray("logs");
logger.StartLoop();
while (lowIt < highIt)
{
curIt = lowIt + (highIt.GetIndex() - lowIt.GetIndex()) / 2;
logger.Comment("Select middle element: " + curIt.String());
if (Equal()(key, *curIt))
{
found = true;
logger.Comment("Key {" + ToString(key) + "} Found at index [" + ToString(curIt.GetIndex()) + "]");
break;
}
else if (key > *curIt)
{
lowIt = curIt + 1;
logger.Comment("Key{" + ToString(key) + "} > " + curIt.String() + ": search in upper sequence.");
}
else
{
highIt = curIt;
logger.Comment("Key{" + ToString(key) + "} < " + curIt.String() + ": search in lower sequence.");
}
// Notify new search space
logger.SetRange(std::make_pair(lowIt.GetIndex(), highIt.GetIndex()));
}
logger.EndLoop();
if (!found) logger.Comment("Key {" + ToString(key) + "} was not found.");
logger.Return((found) ? curIt.String() : end.String());
logger.EndArray();
// Statistics
if (logger.GetCurrentLevel() == 0)
{
logger.StartArray("stats");
logger.AddStats(curIt, true);
logger.EndArray();
}
return (found) ? curIt : end;
}
// Unique as created only at execution as a RAII ressource
std::unique_ptr<Logger> logger; // Logger used to fill the stream
};
}
}
#endif // MODULE_SEARCH_BINARY_LOG_HXX
| 31.832335
| 109
| 0.571482
|
Hurna
|
31125abc4fb8d5845287c0c3750e9053c61bd4b7
| 4,869
|
cpp
|
C++
|
Lib-ZeroG/src/ZeroG/metal/MetalCommandList.cpp
|
PetorSFZ/ZeroG
|
0e3330c2877c3dd840f2a7864b5767d53a92b97d
|
[
"Zlib"
] | null | null | null |
Lib-ZeroG/src/ZeroG/metal/MetalCommandList.cpp
|
PetorSFZ/ZeroG
|
0e3330c2877c3dd840f2a7864b5767d53a92b97d
|
[
"Zlib"
] | null | null | null |
Lib-ZeroG/src/ZeroG/metal/MetalCommandList.cpp
|
PetorSFZ/ZeroG
|
0e3330c2877c3dd840f2a7864b5767d53a92b97d
|
[
"Zlib"
] | null | null | null |
// Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se)
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
#include "ZeroG/metal/MetalCommandList.hpp"
#include "ZeroG/util/Assert.hpp"
namespace zg {
// MetalCommandList: Virtual methods
// ------------------------------------------------------------------------------------------------
ZgResult MetalCommandList::memcpyBufferToBuffer(
ZgBuffer* dstBuffer,
uint64_t dstBufferOffsetBytes,
ZgBuffer* srcBuffer,
uint64_t srcBufferOffsetBytes,
uint64_t numBytes) noexcept
{
(void)dstBuffer;
(void)dstBufferOffsetBytes;
(void)srcBuffer;
(void)srcBufferOffsetBytes;
(void)numBytes;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult MetalCommandList::memcpyToTexture(
ZgTexture2D* dstTexture,
uint32_t dstTextureMipLevel,
const ZgImageViewConstCpu& srcImageCpu,
ZgBuffer* tempUploadBuffer) noexcept
{
(void)dstTexture;
(void)dstTextureMipLevel;
(void)srcImageCpu;
(void)tempUploadBuffer;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult MetalCommandList::enableQueueTransitionBuffer(ZgBuffer* buffer) noexcept
{
(void)buffer;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult MetalCommandList::enableQueueTransitionTexture(ZgTexture2D* texture) noexcept
{
(void)texture;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult MetalCommandList::setPushConstant(
uint32_t shaderRegister,
const void* data,
uint32_t dataSizeInBytes) noexcept
{
(void)shaderRegister;
(void)data;
(void)dataSizeInBytes;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult MetalCommandList::setPipelineBindings(
const ZgPipelineBindings& bindings) noexcept
{
(void)bindings;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult MetalCommandList::setPipelineRender(
ZgPipelineRender* pipeline) noexcept
{
(void)pipeline;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult MetalCommandList::setFramebuffer(
ZgFramebuffer* framebuffer,
const ZgFramebufferRect* optionalViewport,
const ZgFramebufferRect* optionalScissor) noexcept
{
(void)optionalViewport;
(void)optionalScissor;
mFramebuffer = static_cast<MetalFramebuffer*>(framebuffer);
return ZG_SUCCESS;
}
ZgResult MetalCommandList::setFramebufferViewport(
const ZgFramebufferRect& viewport) noexcept
{
(void)viewport;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult MetalCommandList::setFramebufferScissor(
const ZgFramebufferRect& scissor) noexcept
{
(void)scissor;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult MetalCommandList::clearFramebufferOptimal() noexcept
{
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult MetalCommandList::clearRenderTargets(
float red,
float green,
float blue,
float alpha) noexcept
{
ZG_ASSERT(mFramebuffer != nullptr);
mtlpp::ClearColor clearColor = mtlpp::ClearColor(red, green, blue, alpha);
mtlpp::RenderPassDescriptor pass;
pass.GetColorAttachments()[0].SetClearColor(clearColor);
pass.GetColorAttachments()[0].SetLoadAction(mtlpp::LoadAction::Clear);
pass.GetColorAttachments()[0].SetStoreAction(mtlpp::StoreAction::Store);
pass.GetColorAttachments()[0].SetTexture(mFramebuffer->texture);
#warning "This is a huge hack"
mtlpp::RenderCommandEncoder encoder = cmdBuffer.RenderCommandEncoder(pass);
encoder.EndEncoding();
return ZG_SUCCESS;
}
ZgResult MetalCommandList::clearDepthBuffer(
float depth) noexcept
{
(void)depth;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult MetalCommandList::setIndexBuffer(
ZgBuffer* indexBuffer,
ZgIndexBufferType type) noexcept
{
(void)indexBuffer;
(void)type;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult MetalCommandList::setVertexBuffer(
uint32_t vertexBufferSlot,
ZgBuffer* vertexBuffer) noexcept
{
(void)vertexBufferSlot;
(void)vertexBuffer;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult MetalCommandList::drawTriangles(
uint32_t startVertexIndex,
uint32_t numVertices) noexcept
{
(void)startVertexIndex;
(void)numVertices;
return ZG_WARNING_UNIMPLEMENTED;
}
ZgResult MetalCommandList::drawTrianglesIndexed(
uint32_t startIndex,
uint32_t numTriangles) noexcept
{
(void)startIndex;
(void)numTriangles;
return ZG_WARNING_UNIMPLEMENTED;
}
} // namespace zg
| 25.761905
| 99
| 0.783528
|
PetorSFZ
|
3112732b8811a4eeae7b5b91902208b0d3af7c6f
| 1,933
|
cpp
|
C++
|
listas_PO/lista_1_1/src/Data.cpp
|
Tassany/Pesquisa_Operacional
|
93890fef63dfd48a0e7867bf681ec01e05560fdc
|
[
"MIT"
] | null | null | null |
listas_PO/lista_1_1/src/Data.cpp
|
Tassany/Pesquisa_Operacional
|
93890fef63dfd48a0e7867bf681ec01e05560fdc
|
[
"MIT"
] | null | null | null |
listas_PO/lista_1_1/src/Data.cpp
|
Tassany/Pesquisa_Operacional
|
93890fef63dfd48a0e7867bf681ec01e05560fdc
|
[
"MIT"
] | null | null | null |
#include "../include/Data.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
Data::Data(char* filePath)
{
FILE* f = fopen(filePath,"r");
if(fscanf(f, "%d", &numCulturas) != 1)
{
printf("Problem while reading instance.1\n");
//exit(1);
}
//lendo limite do armazem
if(fscanf(f, "%lf", &limiteArm) != 1)
{
printf("Problem while reading instance.2\n");
// exit(1);
}
//lendo area cultivavel
if(fscanf(f, "%lf", &areaCultivavel) != 1)
{
printf("Problem while reading instance.3\n");
// exit(1);
}
//lendo produtividade por cultura
prodCultura = std::vector<double>(numCulturas);
for(int i = 0; i <numCulturas; i++){
if(fscanf(f, "%lf", &prodCultura[i]) != 1)
{
printf("Problem while reading instance.4\n");
//exit(1);
}
}
//lendo lucro por cultura
lucroCultura = std::vector<double>(numCulturas);
for(int i = 0; i < numCulturas; i++)
{
if(fscanf(f, "%lf", &lucroCultura[i]) != 1)
{
printf("Problem while reading instance.5\n");
// exit(1);
}
}
//lendo semanda por cultura
demandaCultura = std::vector<double>(numCulturas);
for(int i = 0; i < numCulturas; i++)
{
if(fscanf(f, "%lf", &demandaCultura[i]) != 1)
{
printf("Problem while reading instance.6\n");
//exit(1);
}
}
fclose(f);
}
int Data::getNumCulturas()
{
return numCulturas;
}
double Data::getLimiteArm()
{
return limiteArm;
}
double Data::getAreaCultivavel()
{
return areaCultivavel;
}
double Data::getProdCultura(int cultura)
{
return prodCultura[cultura];
}
double Data::getLucroCultura(int cultura)
{
return lucroCultura[cultura];
}
double Data::getDemandaCultura(int cultura)
{
return demandaCultura[cultura];
}
| 19.72449
| 57
| 0.561304
|
Tassany
|
3113c3e5f164969cbf8a0db598b70c326f61d0e8
| 946
|
cpp
|
C++
|
src/homework/tic_tac_toe/main.cpp
|
acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-LeytonLL
|
0c544a3fa189dec5da827efe70fccb9f395cbe7d
|
[
"MIT"
] | null | null | null |
src/homework/tic_tac_toe/main.cpp
|
acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-LeytonLL
|
0c544a3fa189dec5da827efe70fccb9f395cbe7d
|
[
"MIT"
] | null | null | null |
src/homework/tic_tac_toe/main.cpp
|
acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-LeytonLL
|
0c544a3fa189dec5da827efe70fccb9f395cbe7d
|
[
"MIT"
] | null | null | null |
#include "tic_tac_toe_manager.h"
#include <tic_tac_toe_3.h>
#include <tic_tac_toe_4.h>
#include<iostream>
#include<string>
using std::cout;
using std::cin;
using std::string;
int main()
//tic TacToe3
{
auto response = 'y';
unique_ptr<TicTacToeManager> manager = std::make_unique<TicTacToeManager>();
string player = "";
int game_type;
do
{
cout << "Play win by 3 or 4: ";
cin >> game_type;
unique_ptr<TicTacToe> game;
if(game_type == 3)
{
game = std::make_unique<TicTacToe3>();
}
else
{
game = std::make_unique<TicTacToe4>();
}
cout << "Enter X or O";
cin >> player;
game->start_game(player);
while (game->game_over() == false)
{
cin >> *game;
cout << *game;
}
manager->save_game(game);
cout << "Game over: \n";
cout << "Continue y or n ";
cin >> response;
} while (response == 'y' || response == 'Y');
cout << "History: \n";
cout << *manager;
return 0;
}
| 14.119403
| 77
| 0.602537
|
acc-cosc-1337-fall-2019
|
311bf9b19e24a8ed6bd79eebcea947eabb5ad94f
| 4,237
|
cpp
|
C++
|
src/prim/hldr.cpp
|
311Volt/axxegro
|
61d7a1fb48f9bb581e0f4171d58499cf8c543728
|
[
"MIT"
] | null | null | null |
src/prim/hldr.cpp
|
311Volt/axxegro
|
61d7a1fb48f9bb581e0f4171d58499cf8c543728
|
[
"MIT"
] | null | null | null |
src/prim/hldr.cpp
|
311Volt/axxegro
|
61d7a1fb48f9bb581e0f4171d58499cf8c543728
|
[
"MIT"
] | null | null | null |
#include <axxegro/prim/hldr.hpp>
#include <allegro5/allegro.h>
#include <allegro5/allegro_primitives.h>
void al::DrawLine(
const al::Coord<>& a,
const al::Coord<>& b,
const Color& color,
float thickness
)
{
al_draw_line(a.x, a.y, b.x, b.y, color, thickness);
}
void al::DrawTriangle(
const al::Coord<>& a,
const al::Coord<>& b,
const al::Coord<>& c,
const Color& color,
float thickness
)
{
al_draw_triangle(a.x, a.y, b.x, b.y, c.x, c.y, color, thickness);
}
void al::DrawFilledTriangle(
const al::Coord<>& a,
const al::Coord<>& b,
const al::Coord<>& c,
const Color& color
)
{
al_draw_filled_triangle(a.x, a.y, b.x, b.y, c.x, c.y, color);
}
void al::DrawRectangle(
const Rect<>& r,
const Color& color,
float thickness
)
{
al_draw_rectangle(r.a.x, r.a.y, r.b.x, r.b.y, color, thickness);
}
void al::DrawFilledRectangle(
const Rect<>& rect,
const Color& color
)
{
al_draw_filled_rectangle(rect.a.x, rect.a.y, rect.b.x, rect.b.y, color);
}
void al::DrawRoundRect(
const Rect<>& rect,
const Vec2<>& radius,
const Color& color,
float thickness
)
{
al_draw_rounded_rectangle(
rect.a.x, rect.a.y, rect.b.x, rect.b.y,
radius.x, radius.y,
color, thickness
);
}
void al::DrawFilledRoundRect(
const Rect<>& rect,
const Vec2<>& radius,
const Color& color
)
{
al_draw_filled_rounded_rectangle(
rect.a.x, rect.a.y, rect.b.x, rect.b.y,
radius.x, radius.y,
color
);
}
void al::DrawPieslice(
const al::Coord<>& center,
float radius,
float startTheta,
float deltaTheta,
const Color& color,
float thickness
)
{
al_draw_pieslice(
center.x, center.y,
radius,
startTheta, deltaTheta,
color, thickness
);
}
void al::DrawFilledPieslice(
const al::Coord<>& center,
float radius,
float startTheta,
float deltaTheta,
const Color& color
)
{
al_draw_filled_pieslice(
center.x, center.y,
radius,
startTheta, deltaTheta,
color
);
}
void al::DrawEllipse(
const al::Coord<>& center,
const Vec2<>& radius,
const Color& color,
float thickness
)
{
al_draw_ellipse(
center.x, center.y,
radius.x, radius.y,
color, thickness
);
}
void al::DrawFilledEllipse(
const al::Coord<>& center,
const Vec2<>& radius,
const Color& color
)
{
al_draw_filled_ellipse(
center.x, center.y,
radius.x, radius.y,
color
);
}
void al::DrawCircle(
const al::Coord<>& center,
float radius,
const Color& color,
float thickness
)
{
al_draw_circle(
center.x, center.y,
radius,
color, thickness
);
}
void al::DrawFilledCircle(
const al::Coord<>& center,
float radius,
const Color& color
)
{
al_draw_filled_circle(
center.x, center.y,
radius,
color
);
}
void al::DrawArc(
const al::Coord<>& center,
float radius,
float startTheta,
float deltaTheta,
const Color& color,
float thickness
)
{
al_draw_arc(
center.x, center.y,
radius,
startTheta, deltaTheta,
color, thickness
);
}
void al::DrawEllipticalArc(
const al::Coord<>& center,
const Vec2<>& radius,
float startTheta,
float deltaTheta,
const Color& color,
float thickness
)
{
al_draw_elliptical_arc(
center.x, center.y,
radius.x, radius.y,
startTheta, deltaTheta,
color, thickness
);
}
void al::DrawSpline(
const std::array<al::Coord<>, 4>& points,
const Color& color,
float thickness
)
{
std::vector<float> pts(8);
for(unsigned i=0; i<points.size(); i++) {
pts[i*2 + 0] = points[i].x;
pts[i*2 + 1] = points[i].y;
}
al_draw_spline(pts.data(), color, thickness);
}
std::vector<al::Coord<>> al::CalculateArc(
const al::Coord<>& center,
const al::Coord<>& radius,
float startTheta,
float deltaTheta,
float thickness,
unsigned numPoints
)
{
std::vector<float> outData(2*numPoints*(1 + !!(thickness>0)));
al_calculate_arc(
outData.data(), 2*sizeof(outData[0]),
center.x, center.y,
radius.x, radius.y,
startTheta, deltaTheta,
thickness,
numPoints
);
std::vector<Coord<>> ret(outData.size() / 2);
for(unsigned i=0; i<ret.size(); i++) {
ret[i] = {outData[i*2 + 0], outData[i*2 + 1]};
}
return ret;
}
| 17.654167
| 74
| 0.631579
|
311Volt
|
311f77ac5a87b6e4a5958b9324f13d2d3fd0905e
| 3,768
|
hpp
|
C++
|
include/gl/tone_mapping/segmentation_tmo_approx.hpp
|
ecarpita93/HPC_projet_1
|
a2c00e056c03227711c43cf2ad23d75c6afbe698
|
[
"Xnet",
"X11"
] | null | null | null |
include/gl/tone_mapping/segmentation_tmo_approx.hpp
|
ecarpita93/HPC_projet_1
|
a2c00e056c03227711c43cf2ad23d75c6afbe698
|
[
"Xnet",
"X11"
] | null | null | null |
include/gl/tone_mapping/segmentation_tmo_approx.hpp
|
ecarpita93/HPC_projet_1
|
a2c00e056c03227711c43cf2ad23d75c6afbe698
|
[
"Xnet",
"X11"
] | null | null | null |
/*
PICCANTE
The hottest HDR imaging library!
http://vcg.isti.cnr.it/piccante
Copyright (C) 2014
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
First author: Francesco Banterle
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef PIC_GL_TONE_MAPPING_SEGMENTATION_TMO_APPROX_HPP
#define PIC_GL_TONE_MAPPING_SEGMENTATION_TMO_APPROX_HPP
#include "../../gl/filtering/filter_luminance.hpp"
#include "../../gl/filtering/filter_remove_nuked.hpp"
#include "../../gl/filtering/filter_iterative.hpp"
#include "../../gl/filtering/filter_bilateral_2ds.hpp"
#include "../../gl/filtering/filter_op.hpp"
namespace pic {
/**
* @brief The SegmentationGL class
*/
class SegmentationGL
{
protected:
FilterGLLuminance *flt_lum;
FilterGLRemoveNuked *flt_nuked;
FilterGLIterative *flt_it;
FilterGLBilateral2DS *flt_bil;
FilterGLOp *flt_seg;
ImageGL *L, *imgIn_flt;
float perCent, nLayer;
int iterations;
public:
ImageGLVec stack;
float minVal, maxVal;
/**
* @brief SegmentationGL
*/
SegmentationGL()
{
flt_nuked = NULL;
flt_lum = NULL;
flt_bil = NULL;
flt_it = NULL;
flt_seg = NULL;
nLayer = 0.0f;
iterations = 0;
L = NULL;
imgIn_flt = NULL;
maxVal = FLT_MAX;
minVal = 0.0f;
perCent = 0.005f;
}
~SegmentationGL()
{
if(imgIn_flt != NULL) {
delete imgIn_flt;
imgIn_flt = NULL;
}
if(L != NULL) {
delete L;
L = NULL;
}
delete flt_it;
delete flt_bil;
delete flt_seg;
delete flt_nuked;
}
/**
* @brief computeStatistics
* @param imgIn
*/
void computeStatistics(Image *imgIn)
{
float nLevels, area;
nLevels = log10f(maxVal) - log10f(minVal) + 1.0f;
nLayer = ((maxVal - minVal) / nLevels) / 4.0f;
area = imgIn->widthf * imgIn->heightf * perCent;
iterations = MAX(int(sqrtf(area)) / 8, 1);
}
/**
* @brief execute
* @param imgIn
* @param imgOut
* @return
*/
ImageGL *execute(ImageGL *imgIn, ImageGL *imgOut)
{
if(imgIn == NULL) {
return imgOut;
}
if(!imgIn->isValid()) {
return imgOut;
}
if(imgOut == NULL) {
imgOut = new ImageGL(1, imgIn->width, imgIn->height, 1, IMG_GPU, GL_TEXTURE_2D);
}
//compute luminance
if(flt_lum == NULL) {
flt_lum = new FilterGLLuminance();
}
L = flt_lum->Process(SingleGL(imgIn), L);
L->getMinVal(&minVal);
L->getMaxVal(&maxVal);
//iterative bilateral filtering
if(flt_it == NULL) {
flt_bil = new FilterGLBilateral2DS(1.0f, nLayer);
flt_it = new FilterGLIterative(flt_bil, iterations);
}
imgIn_flt = flt_it->Process(SingleGL(imgIn), imgIn_flt);
L = flt_lum->Process(SingleGL(imgIn_flt), L);
//threshold
if(flt_seg == NULL) {
flt_seg = FilterGLOp::CreateOpSegmentation(false, floor(log10f(minVal)));
}
flt_seg->Process(SingleGL(L), L);
//remove nuked pixels
if(flt_nuked == NULL) {
flt_nuked = new FilterGLRemoveNuked(0.9f);
}
flt_nuked->Process(SingleGL(L), imgOut);
return imgOut;
}
};
} // end namespace pic
#endif /* PIC_GL_TONE_MAPPING_SEGMENTATION_TMO_APPROX_HPP */
| 22.97561
| 92
| 0.568737
|
ecarpita93
|
3120a5fd12929fd16cd8a0b29840088e4c5070a4
| 5,544
|
hpp
|
C++
|
libcore/src/network/ASIOConnectAndHandshake.hpp
|
ericruth/sirikata
|
9b4cad53b9bef46d318d52581d489d691b6f9e58
|
[
"BSD-3-Clause"
] | 1
|
2016-05-09T11:45:31.000Z
|
2016-05-09T11:45:31.000Z
|
libcore/src/network/ASIOConnectAndHandshake.hpp
|
mullwaden/sirikata
|
bedcf22c97f733d82bffcd787f21c25b4e6710ed
|
[
"BSD-3-Clause"
] | null | null | null |
libcore/src/network/ASIOConnectAndHandshake.hpp
|
mullwaden/sirikata
|
bedcf22c97f733d82bffcd787f21c25b4e6710ed
|
[
"BSD-3-Clause"
] | null | null | null |
/* Sirikata Network Utilities
* ASIOConnectAndHandshake.hpp
*
* Copyright (c) 2009, Daniel Reiter Horn
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace Sirikata { namespace Network {
class ASIOConnectAndHandshake{
boost::asio::ip::tcp::resolver mResolver;
std::tr1::weak_ptr<MultiplexedSocket> mConnection;
///num positive checks remaining (or -n for n sockets of which at least 1 failed)
int mFinishedCheckCount;
UUID mHeaderUUID;
Array<uint8,TCPStream::TcpSstHeaderSize> mFirstReceivedHeader;
typedef boost::system::error_code ErrorCode;
/**
* This function checks a particular sockets initial handshake header.
* If this is the first header read, it will save it for comparison
* If this is the nth header read and everythign is successful it will decrement the first header check integer
* If anything goes wrong and it is the first time, it will decrement the first header check integer below zero to indiate error and call connectionFailed
* If anything goes wrong and the first header check integer is already below zero it will decline to take action
* The buffer passed in will be deleted by this function
*/
void checkHeaderContents(unsigned int whichSocket,
Array<uint8,TCPStream::TcpSstHeaderSize>* buffer,
const ErrorCode&error,
std::size_t bytes_received);
/**
* This function simply wraps checkHeaderContents having been passed a shared_ptr from an asio_callback
*/
static void checkHeader(const std::tr1::shared_ptr<ASIOConnectAndHandshake>&thus,
unsigned int whichSocket,
Array<uint8,TCPStream::TcpSstHeaderSize>* buffer,
const ErrorCode&error,
std::size_t bytes_received) {
thus->checkHeaderContents(whichSocket,buffer,error,bytes_received);
}
/**
* This function checks if a particular sockets has connected to its destination IP address
* If everything is successful it will decrement the first header check integer
* If the last resolver fails and it is the first time, it will decrement the first header check integer below zero to indiate error and call connectionFailed
* If anything goes wrong and the first header check integer is already below zero it will decline to take action
* The buffer passed in will be deleted by this function
*/
static void connectToIPAddress(const std::tr1::shared_ptr<ASIOConnectAndHandshake>&thus,
unsigned int whichSocket,
const boost::asio::ip::tcp::resolver::iterator &it,
const ErrorCode &error);
/**
* This function is a callback from the async_resolve call from ASIO initialized from the public interface connect
* It may get an error if the host was not found or otherwise a valid iterator to a number of ip addresses
*/
static void handleResolve(const std::tr1::shared_ptr<ASIOConnectAndHandshake>&thus,
const boost::system::error_code &error,
boost::asio::ip::tcp::resolver::iterator it);
public:
/**
* This function transforms the member mConnection from the PRECONNECTION socket phase to the CONNECTED socket phase
* It first performs a resolution on the address and handles the callback in handleResolve.
* If the header checks out and matches with the other live sockets to the same sockets
* - MultiplexedSocket::connectedCallback() is called
* - An ASIOReadBuffer is created for handling future reads
*/
static void connect(const std::tr1::shared_ptr<ASIOConnectAndHandshake> &thus,
const Address&address);
ASIOConnectAndHandshake(const std::tr1::shared_ptr<MultiplexedSocket> &connection,
const UUID&sharedUuid);
};
} }
| 56.571429
| 161
| 0.696789
|
ericruth
|
3120b4168fba48e658841be45de6c8c54eaaa1f9
| 733
|
cpp
|
C++
|
code-examples/lab_k28c_15_09_20_oop.cpp
|
kzhereb/knu-ips-ooop-2020-2021
|
777b4a847a537510048fd582eda0816ce05db4b5
|
[
"MIT"
] | null | null | null |
code-examples/lab_k28c_15_09_20_oop.cpp
|
kzhereb/knu-ips-ooop-2020-2021
|
777b4a847a537510048fd582eda0816ce05db4b5
|
[
"MIT"
] | 34
|
2021-03-25T08:28:26.000Z
|
2021-05-20T13:12:48.000Z
|
code-examples/lab_k28c_15_09_20_oop.cpp
|
kzhereb/knu-ips-ooop-2020-2021
|
777b4a847a537510048fd582eda0816ce05db4b5
|
[
"MIT"
] | 1
|
2020-09-28T12:58:26.000Z
|
2020-09-28T12:58:26.000Z
|
/*
* lab_k28c_15_09_20_oop.cpp
*
* Created on: Sep 15, 2020
* Author: KZ
*/
#include "doctest.h"
#include <string>
class Human {
private:
double height; // in cm
double weight; // in kg
std::string name;
public:
Human(double height, double weight, std::string name): height{height}, weight{weight}, name{name} { }
double get_height() { return this->height;}
bool is_tankist() { return height <= 170; }
};
TEST_CASE("creating human and accessing properties") {
Human someone(170, 50, "Yehor");
CHECK(someone.get_height() == 170);
CHECK(someone.is_tankist());
Human someone2(171, 50, "Andrii");
CHECK(someone2.get_height() == 171);
CHECK_FALSE(someone2.is_tankist());
}
| 20.942857
| 103
| 0.645293
|
kzhereb
|
3124ad00a21443fa67c5c606c398bfe5cd9d957c
| 7,321
|
cpp
|
C++
|
Libraries/RobsJuceModules/jura_framework/gui/panels/jura_WaveformDisplay.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 34
|
2017-04-19T18:26:02.000Z
|
2022-02-15T17:47:26.000Z
|
Libraries/RobsJuceModules/jura_framework/gui/panels/jura_WaveformDisplay.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 307
|
2017-05-04T21:45:01.000Z
|
2022-02-03T00:59:01.000Z
|
Libraries/RobsJuceModules/jura_framework/gui/panels/jura_WaveformDisplay.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 4
|
2017-09-05T17:04:31.000Z
|
2021-12-15T21:24:28.000Z
|
//-------------------------------------------------------------------------------------------------
// construction/destruction:
WaveformDisplay::WaveformDisplay(AudioFileBuffer *newBuffer)
: InteractiveCoordinateSystem("WaveformDisplay"), AudioFileBufferUser(newBuffer)
{
ScopedLock pointerLock(audioFileBufferPointerLock);
Component::setName(String("WaveformDisplay"));
firstChannelToPlot = 0;
lastChannelToPlot = 7; // restrict plot to 8 channels by default
//setValueFieldPopup(false);
if( bufferToUse != NULL )
{
double maxTime = jmax(bufferToUse->getLengthInSeconds(), 0.0001); // 1/10 ms minimum range
setMaximumRangeX(0.0, maxTime);
setCurrentRangeX(0.0, maxTime);
minVisibleTime = 0.0;
maxVisibleTime = maxTime;
//numChannels = bufferToUse->getNumChannels();
//numSamples = bufferToUse->getNumSamples();
//sampleRate = bufferToUse->getFileSampleRate(); // mmmhh. could be used directly in plot...
}
else
{
// use some fallback-values when we got a NULL pointer
setMaximumRange(0.0, 0.001, -1.0, +1.0);
setCurrentRange(0.0, 0.001, -1.0, +1.0);
minVisibleTime = 0.0;
maxVisibleTime = 0.001;
//numChannels = 0;
//numSamples = 0;
//sampleRate = 44100.0;
}
}
//-------------------------------------------------------------------------------------------------
// setup:
void WaveformDisplay::assignAudioFileBuffer(AudioFileBuffer *newBuffer)
{
ScopedLock pointerLock(audioFileBufferPointerLock);
if( newBuffer != bufferToUse )
{
AudioFileBufferUser::assignAudioFileBuffer(newBuffer);
setRangeToBufferLength();
/*
if( bufferToUse != NULL )
{
double maxTime = jmax(bufferToUse->getLengthInSeconds(), 0.0001); // 1/10 ms minimum range
setMaximumRangeX(0.0, maxTime);
setCurrentRangeX(0.0, maxTime);
minVisibleTime = 0.0;
maxVisibleTime = maxTime;
//numChannels = bufferToUse->getNumChannels();
//numSamples = bufferToUse->getNumSamples();
//sampleRate = bufferToUse->getFileSampleRate(); // mmmhh. could be used directly in plot...
}
*/
}
}
void WaveformDisplay::setRangeToBufferLength()
{
ScopedLock pointerLock(audioFileBufferPointerLock);
if( bufferToUse != NULL )
{
double maxTime = jmax(bufferToUse->getLengthInSeconds(), 0.0001); // 1/10 ms minimum range
setMaximumRangeX(0.0, maxTime);
setCurrentRangeX(0.0, maxTime);
minVisibleTime = 0.0;
maxVisibleTime = maxTime;
}
}
/*
void WaveformDisplay::setSampleRate(double newSampleRate)
{
jassert(newSampleRate > 0.0); // zero or negative sample-rates are not supported ;-)
if( newSampleRate > 0.0 )
sampleRate = newSampleRate;
repaint();
}
*/
void WaveformDisplay::setFirstChannelToPlot(int newFirstChannelIndex)
{
jassert(newFirstChannelIndex >= 0); // negative channel-index? no! counting starts at 0
if( newFirstChannelIndex >= 0 )
firstChannelToPlot = newFirstChannelIndex;
}
void WaveformDisplay::setLastChannelToPlot(int newLastChannelIndex)
{
jassert(newLastChannelIndex >= 0); // negative channel-index? no! counting starts at 0
if( newLastChannelIndex >= 0 )
lastChannelToPlot = newLastChannelIndex;
}
void WaveformDisplay::plotOnlyOneChannel(int channelToPlotIndex)
{
setFirstChannelToPlot(channelToPlotIndex);
setLastChannelToPlot(channelToPlotIndex);
}
void WaveformDisplay::setVisibleTimeRange(double newMinTimeInSeconds, double newMaxTimeInSeconds)
{
minVisibleTime = newMinTimeInSeconds;
maxVisibleTime = newMaxTimeInSeconds;
}
//-------------------------------------------------------------------------------------------------
// others:
/*
void WaveformDisplay::resized()
{
Panel::resized();
ThreadedDrawingComponent::resized();
}
void WaveformDisplay::setDirty(bool shouldBeSetToDirty)
{
Panel::setDirty(shouldBeSetToDirty);
ThreadedDrawingComponent::setDirty(shouldBeSetToDirty);
}
*/
//-------------------------------------------------------------------------------------------------
// drawing:
void WaveformDisplay::drawComponent(Image* imageToDrawOnto)
{
Graphics g(*imageToDrawOnto);
drawCoordinateSystem(g, imageToDrawOnto);
//g.fillAll(Colours::white); // preliminary - call CoordinateSystem background drawing stuff here
plotWaveform(imageToDrawOnto);
g.drawRect(0, 0, imageToDrawOnto->getWidth(), imageToDrawOnto->getHeight(), 1);
}
void WaveformDisplay::plotWaveform(Image *targetImage)
{
if( targetImage == NULL )
return;
Graphics g(*targetImage);
// make sure that the pointer to the bufferToUse is not modified during this function:
bool pointerLockAcquired = audioFileBufferPointerLock.tryEnter();
if( pointerLockAcquired == false )
return;
// check if we have a valid buffer - if not, return - we don't need to aquire the readlock for
// the data here, because we use getMinMaxSamples to retrieve the data which in itself aquires
// the read-lock:
if( bufferToUse == NULL )
{
audioFileBufferPointerLock.exit();
return;
}
//ScopedReadLock dataLock(bufferToUse->audioDataReadWriteLock);
bufferToUse->acquireReadLock();
// we have our read-lock - do the work:
int numChannels = bufferToUse->getNumChannels();
int numSamples = bufferToUse->getNumSamples();
double sampleRate = bufferToUse->getFileSampleRate();
double pixelWidth = (double) getWidth();
if( targetImage != NULL )
pixelWidth = (double) targetImage->getWidth();
double tSecMin = currentRange.getMinX(); // min-time in seconds
double tSecMax = currentRange.getMaxX(); // max-time in seconds
double tSecInc = (tSecMax-tSecMin) / pixelWidth; // increment per pixel
double tSmpMin = tSecMin * sampleRate; // min-time in samples
double tSmpMax = tSecMax * sampleRate; // max-time in samples
double tSmpInc = (tSmpMax-tSmpMin) / pixelWidth; // increment per pixel
int cMin = jmax(0, firstChannelToPlot);
int cMax = jmin(numChannels-1, lastChannelToPlot);
//int curveDrawn = 0;
//float dotRadius = 3.f;
// outer loop over the channels:
double tSec, tSmp;
double x1, x2, y1, y2;
int nMin, nMax;
g.setColour(Colours::blue);
for(int c=cMin ; c<=cMax; c++)
{
// inner loop over pixels:
tSec = tSecMin;
tSmp = tSmpMin;
while( tSmp <= tSmpMax )
{
nMin = jlimit(0, numSamples-1, (int) floor(tSmp) );
nMax = jlimit(0, numSamples-1, (int) ceil( tSmp+tSmpInc) );
x1 = (float) tSec;
x2 = (float) (tSec+tSecInc);
//bufferToUse->getMinMaxSamples(c, nMin, nMax-nMin+1, y1, y2);
bufferToUse->getMinMaxSamplesWithoutLock(c, nMin, nMax-nMin+1, y1, y2);
toPixelCoordinates(x1, y1);
toPixelCoordinates(x2, y2);
g.drawLine((float)x1, (float)y1, (float)x2, (float)y2);
tSec += tSecInc;
tSmp += tSmpInc;
}
}
bufferToUse->releaseReadLock();
audioFileBufferPointerLock.exit();
}
void WaveformDisplay::restrictToVisibleSection(double &tMin, double &tMax,
double marginInPercent) const
{
double marginAbsolute = 0.01*marginInPercent*(maxVisibleTime-minVisibleTime);
tMin = jmax(tMin, minVisibleTime-marginAbsolute);
tMax = jmin(tMax, maxVisibleTime+marginAbsolute);
}
| 31.692641
| 102
| 0.657014
|
RobinSchmidt
|
3124b9703540d2b0d976ae3e7c1f2238c0a049d9
| 630
|
cpp
|
C++
|
LeetCode/1000/812.cpp
|
K-ona/C-_Training
|
d54970f7923607bdc54fc13677220d1b3daf09e5
|
[
"Apache-2.0"
] | null | null | null |
LeetCode/1000/812.cpp
|
K-ona/C-_Training
|
d54970f7923607bdc54fc13677220d1b3daf09e5
|
[
"Apache-2.0"
] | null | null | null |
LeetCode/1000/812.cpp
|
K-ona/C-_Training
|
d54970f7923607bdc54fc13677220d1b3daf09e5
|
[
"Apache-2.0"
] | null | null | null |
class Solution {
public:
int cross(int x1, int y1, int x2, int y2) { return x1 * y2 - x2 * y1; }
double largestTriangleArea(vector<vector<int>>& points) {
double res = 0;
for (int i = 0; i < points.size(); i++) {
for (int j = i + 1; j < points.size(); j++) {
for (int k = j + 1; k < points.size(); k++) {
int x1 = points[j][0] - points[i][0];
int y1 = points[j][1] - points[i][1];
int x2 = points[k][0] - points[i][0];
int y2 = points[k][1] - points[i][1];
res = max(res, abs(cross(x1, y1, x2, y2) / 2.0));
}
}
}
return res;
}
};
| 33.157895
| 73
| 0.474603
|
K-ona
|
3125fd3d0369289349e3de0ea4dde1efd2eac79b
| 15,526
|
cpp
|
C++
|
Source/Lib/Uncompressed/WAV/WAV.cpp
|
g-maxime/RAWCooked
|
6b2ef51208a6b23822560112b024bdc2d3f595b0
|
[
"BSD-2-Clause"
] | null | null | null |
Source/Lib/Uncompressed/WAV/WAV.cpp
|
g-maxime/RAWCooked
|
6b2ef51208a6b23822560112b024bdc2d3f595b0
|
[
"BSD-2-Clause"
] | null | null | null |
Source/Lib/Uncompressed/WAV/WAV.cpp
|
g-maxime/RAWCooked
|
6b2ef51208a6b23822560112b024bdc2d3f595b0
|
[
"BSD-2-Clause"
] | null | null | null |
/* Copyright (c) MediaArea.net SARL & AV Preservation by reto.ch.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
#include "Lib/Uncompressed/WAV/WAV.h"
#include "Lib/Compressed/RAWcooked/RAWcooked.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Errors
namespace wav_issue {
namespace undecodable
{
static const char* MessageText[] =
{
"file smaller than expected",
"RIFF chunk size",
"fmt chunk size",
"truncated chunk",
};
enum code : uint8_t
{
BufferOverflow,
RIFF_ChunkSize,
fmt__ChunkSize,
TruncatedChunk,
Max
};
namespace undecodable { static_assert(Max == sizeof(MessageText) / sizeof(const char*), IncoherencyMessage); }
} // unparsable
namespace unsupported
{
static const char* MessageText[] =
{
// Unsupported
"RF64 (4GB+ WAV)",
"fmt FormatTag not WAVE_FORMAT_PCM 1",
"fmt AvgBytesPerSec",
"fmt BlockAlign",
"fmt extension",
"fmt cbSize",
"fmt ValidBitsPerSample",
"fmt ChannelMask",
"fmt SubFormat not KSDATAFORMAT_SUBTYPE_PCM 00000001-0000-0010-8000-00AA00389B71",
"fmt chunk not before data chunk",
"Flavor (SamplesPerSec / BitDepth / Channels / Endianness combination)",
"data chunk size is not a multiple of BlockAlign",
};
enum code : uint8_t
{
RF64,
fmt__FormatTag,
fmt__AvgBytesPerSec,
fmt__BlockAlign,
fmt__extension,
fmt__cbSize,
fmt__ValidBitsPerSample,
fmt__ChannelMask,
fmt__SubFormat,
fmt__Location,
Flavor,
data_Size,
Max
};
namespace undecodable { static_assert(Max == sizeof(MessageText) / sizeof(const char*), IncoherencyMessage); }
} // unsupported
const char** ErrorTexts[] =
{
undecodable::MessageText,
unsupported::MessageText,
nullptr,
nullptr,
};
static_assert(error::type_Max == sizeof(ErrorTexts) / sizeof(const char**), IncoherencyMessage);
} // wav_issue
using namespace wav_issue;
//---------------------------------------------------------------------------
// Enums
enum class sample_per_sec_code : uint8_t
{
_44100,
_48000,
_96000,
};
//---------------------------------------------------------------------------
// Tested cases
struct wav_tested
{
sample_per_sec_code SamplesPerSecCode;
uint8_t BitDepth;
uint8_t Channels;
bool operator == (const wav_tested& Value) const
{
return SamplesPerSecCode == Value.SamplesPerSecCode
&& BitDepth == Value.BitDepth
&& Channels == Value.Channels
;
}
};
struct wav_tested WAV_Tested[] =
{
{ sample_per_sec_code::_44100, 8, 1 },
{ sample_per_sec_code::_44100, 8, 2 },
{ sample_per_sec_code::_44100, 8, 6 },
{ sample_per_sec_code::_44100, 16, 1 },
{ sample_per_sec_code::_44100, 16, 2 },
{ sample_per_sec_code::_44100, 16, 6 },
{ sample_per_sec_code::_44100, 24, 1 },
{ sample_per_sec_code::_44100, 24, 2 },
{ sample_per_sec_code::_44100, 24, 6 },
{ sample_per_sec_code::_48000, 8, 1 },
{ sample_per_sec_code::_48000, 8, 2 },
{ sample_per_sec_code::_48000, 8, 6 },
{ sample_per_sec_code::_48000, 16, 1 },
{ sample_per_sec_code::_48000, 16, 2 },
{ sample_per_sec_code::_48000, 16, 6 },
{ sample_per_sec_code::_48000, 24, 1 },
{ sample_per_sec_code::_48000, 24, 2 },
{ sample_per_sec_code::_48000, 24, 6 },
{ sample_per_sec_code::_96000, 8, 1 },
{ sample_per_sec_code::_96000, 8, 2 },
{ sample_per_sec_code::_96000, 8, 6 },
{ sample_per_sec_code::_96000, 16, 1 },
{ sample_per_sec_code::_96000, 16, 2 },
{ sample_per_sec_code::_96000, 16, 6 },
{ sample_per_sec_code::_96000, 24, 1 },
{ sample_per_sec_code::_96000, 24, 2 },
{ sample_per_sec_code::_96000, 24, 6 },
};
static_assert(wav::flavor_Max == sizeof(WAV_Tested) / sizeof(wav_tested), IncoherencyMessage);
//---------------------------------------------------------------------------
#define ELEMENT_BEGIN(_VALUE) \
wav::call wav::SubElements_##_VALUE(uint64_t Name) \
{ \
switch (Name) \
{ \
#define ELEMENT_CASE(_VALUE,_NAME) \
case 0x##_VALUE: Levels[Level].SubElements = &wav::SubElements_##_NAME; return &wav::_NAME;
#define ELEMENT_VOID(_VALUE,_NAME) \
case 0x##_VALUE: Levels[Level].SubElements = &wav::SubElements_Void; return &wav::_NAME;
#define ELEMENT_END() \
default: return SubElements_Void(Name); \
} \
} \
ELEMENT_BEGIN(_)
ELEMENT_CASE(5249464657415645LL, WAVE)
ELEMENT_END()
ELEMENT_BEGIN(WAVE)
ELEMENT_VOID(64617461, WAVE_data)
ELEMENT_VOID(666D7420, WAVE_fmt_)
ELEMENT_END()
//---------------------------------------------------------------------------
wav::call wav::SubElements_Void(uint64_t /*Name*/)
{
Levels[Level].SubElements = &wav::SubElements_Void; return &wav::Void;
}
//***************************************************************************
// WAV
//***************************************************************************
//---------------------------------------------------------------------------
wav::wav(errors* Errors_Source) :
input_base_uncompressed_audio(Errors_Source, Parser_WAV)
{
}
//---------------------------------------------------------------------------
void wav::ParseBuffer()
{
if (Buffer.Size() < 12)
return;
if (Buffer[8] != 'W' || Buffer[9] != 'A' || Buffer[10] != 'V' || Buffer[11] != 'E')
return;
if (Buffer[0] == 'R' && Buffer[1] == 'F' && Buffer[2] == '6' && Buffer[3] == '4')
{
Unsupported(unsupported::RF64);
return;
}
if (Buffer[0] != 'R' || Buffer[1] != 'I' || Buffer[2] != 'F' || Buffer[3] != 'F')
return;
SetDetected();
Flavor = flavor_Max; // Used for detected if fmt chunk is parsed
Buffer_Offset = 0;
Levels[0].Offset_End = Buffer.Size();
Levels[0].SubElements = &wav::SubElements__;
Level=1;
while (Buffer_Offset < Buffer.Size())
{
// Find the current nesting level
while (Buffer_Offset >= Levels[Level - 1].Offset_End)
{
Levels[Level].SubElements = NULL;
Level--;
}
uint64_t End = Levels[Level - 1].Offset_End;
// Parse the chunk header
uint64_t Name;
uint64_t Size;
if (Buffer_Offset + 8 > End)
{
Undecodable(undecodable::TruncatedChunk);
return;
}
Name = Get_B4();
Size = Get_L4();
if (Name == 0x52494646) // "RIFF"
{
if (Size < 4 || Buffer_Offset + 4 > End)
{
Undecodable(undecodable::RIFF_ChunkSize);
return;
}
Name <<= 32;
Name |= Get_B4();
Size -= 4;
}
if (Buffer_Offset + Size > End)
{
if (!Actions[Action_AcceptTruncated])
{
Undecodable(undecodable::TruncatedChunk);
return;
}
Size = Levels[Level - 1].Offset_End - Buffer_Offset;
}
// Parse the chunk content
Levels[Level].Offset_End = Buffer_Offset + Size;
call Call = (this->*Levels[Level - 1].SubElements)(Name);
IsList = false;
(this->*Call)();
if (!IsList)
{
Buffer_Offset = Levels[Level].Offset_End;
// Padding byte
if (Buffer_Offset % 2 && Buffer_Offset < Buffer.Size() && !Buffer[Buffer_Offset])
{
Buffer_Offset++;
Levels[Level].Offset_End = Buffer_Offset;
}
}
// Next chunk (or sub-chunk)
if (Buffer_Offset < Levels[Level].Offset_End)
Level++;
}
}
//---------------------------------------------------------------------------
void wav::Void()
{
}
//---------------------------------------------------------------------------
void wav::WAVE()
{
IsList = true;
}
//---------------------------------------------------------------------------
void wav::WAVE_data()
{
// Test if fmt chunk was parsed
if (!HasErrors() && Flavor == flavor_Max)
Unsupported(unsupported::fmt__Location);
// Coherency test
if (BlockAlign)
{
uint64_t Size = Levels[Level].Offset_End - Buffer_Offset;
if (Size % BlockAlign)
Unsupported(unsupported::data_Size);
if (InputInfo && !InputInfo->SampleCount)
InputInfo->SampleCount = Size / BlockAlign;
}
// Can we compress?
if (!HasErrors())
SetSupported();
// Write RAWcooked file
if (IsSupported() && RAWcooked)
{
RAWcooked->Unique = true;
RAWcooked->BeforeData = Buffer.Data();
RAWcooked->BeforeData_Size = Buffer_Offset;
RAWcooked->AfterData = Buffer.Data() + Levels[Level].Offset_End;
RAWcooked->AfterData_Size = Buffer.Size() - Levels[Level].Offset_End;
RAWcooked->InData = nullptr;
RAWcooked->InData_Size = 0;
RAWcooked->FileSize = (uint64_t)-1;
if (Actions[Action_Hash])
{
Hash();
RAWcooked->HashValue = &HashValue;
}
else
RAWcooked->HashValue = nullptr;
RAWcooked->IsAttachment = false;
RAWcooked->Parse();
}
}
//---------------------------------------------------------------------------
void wav::WAVE_fmt_()
{
if (Levels[Level].Offset_End - Buffer_Offset < 16)
{
Undecodable(undecodable::fmt__ChunkSize);
return;
}
uint16_t FormatTag = Get_L2();
if (FormatTag != 1 && FormatTag != 0xFFFE)
Unsupported(unsupported::fmt__FormatTag);
wav_tested Info;
uint16_t Channels = Get_L2();
uint32_t SamplesPerSec = Get_L4();
uint32_t AvgBytesPerSec = Get_L4();
BlockAlign = Get_L2();
uint16_t BitDepth = Get_L2();
if (AvgBytesPerSec * 8 != Channels * BitDepth * SamplesPerSec)
Unsupported(unsupported::fmt__AvgBytesPerSec);
if (BlockAlign * 8 != Channels * BitDepth)
Unsupported(unsupported::fmt__BlockAlign);
if (FormatTag == 1)
{
// Some files have zeroes after actual fmt content, it does not hurt so we accept them
while (Buffer_Offset + 2 <= Levels[Level].Offset_End)
{
uint16_t Padding0 = Get_L2();
if (Padding0)
{
Unsupported(unsupported::fmt__extension);
return;
}
}
if (Levels[Level].Offset_End - Buffer_Offset)
{
Unsupported(unsupported::fmt__extension);
return;
}
}
if (FormatTag == 0xFFFE)
{
if (Levels[Level].Offset_End - Buffer_Offset != 24)
{
Unsupported(unsupported::fmt__extension);
return;
}
uint16_t cbSize = Get_L2();
if (cbSize != 22)
{
Unsupported(unsupported::fmt__cbSize);
return;
}
uint16_t ValidBitsPerSample = Get_L2();
if (ValidBitsPerSample != BitDepth)
Unsupported(unsupported::fmt__ValidBitsPerSample);
uint32_t ChannelMask = Get_L4();
if ((Channels != 1 || (ChannelMask != 0x00000000 && ChannelMask != 0x00000004))
&& (Channels != 2 || (ChannelMask != 0x00000000 && ChannelMask != 0x00000003))
&& (Channels != 6 || (ChannelMask != 0x00000000 && ChannelMask != 0x0000003F && ChannelMask != 0x0000060F)))
Unsupported(unsupported::fmt__ChannelMask);
uint32_t SubFormat1 = Get_L4();
uint32_t SubFormat2 = Get_L4();
uint32_t SubFormat3 = Get_B4();
uint64_t SubFormat4 = Get_B4();
if (SubFormat1 != 0x00000001
|| SubFormat2 != 0x00100000
|| SubFormat3 != 0x800000aa
|| SubFormat4 != 0x00389b71)
Unsupported(unsupported::fmt__SubFormat);
}
// Supported?
if (BitDepth > (decltype(wav_tested::BitDepth))-1
|| Channels > (decltype(wav_tested::Channels))-1)
{
Unsupported(unsupported::Flavor);
return;
}
switch (SamplesPerSec)
{
case 44100: Info.SamplesPerSecCode = sample_per_sec_code::_44100; break;
case 48000: Info.SamplesPerSecCode = sample_per_sec_code::_48000; break;
case 96000: Info.SamplesPerSecCode = sample_per_sec_code::_96000; break;
default : Info.SamplesPerSecCode = (decltype(Info.SamplesPerSecCode))-1;
}
Info.BitDepth = (decltype(wav_tested::BitDepth))BitDepth;
Info.Channels = (decltype(wav_tested::Channels))Channels;
for (const auto& WAV_Tested_Item : WAV_Tested)
{
if (WAV_Tested_Item == Info)
{
Flavor = (decltype(Flavor))(&WAV_Tested_Item - WAV_Tested);
break;
}
}
if (Flavor == (decltype(Flavor))-1)
Unsupported(unsupported::Flavor);
if (HasErrors())
return;
if (InputInfo && !InputInfo->SampleRate)
InputInfo->SampleRate = SamplesPerSec;
}
//---------------------------------------------------------------------------
void wav::BufferOverflow()
{
Undecodable(undecodable::BufferOverflow);
}
//---------------------------------------------------------------------------
string wav::Flavor_String()
{
return WAV_Flavor_String(Flavor);
}
//---------------------------------------------------------------------------
uint8_t wav::BitDepth()
{
return WAV_Tested[Flavor].BitDepth;
}
//---------------------------------------------------------------------------
endianness wav::Endianness()
{
return endianness::LE;
}
//---------------------------------------------------------------------------
static const char* SamplesPerSec_String(wav::flavor Flavor)
{
switch (WAV_Tested[(size_t)Flavor].SamplesPerSecCode)
{
case sample_per_sec_code::_44100: return "44";
case sample_per_sec_code::_48000: return "48";
case sample_per_sec_code::_96000: return "96";
}
return nullptr;
}
//---------------------------------------------------------------------------
static string BitDepth_String(wav::flavor Flavor)
{
return to_string(WAV_Tested[(size_t)Flavor].BitDepth);
}
//---------------------------------------------------------------------------
static string Channels_String(wav::flavor Flavor)
{
return to_string(WAV_Tested[(size_t)Flavor].Channels);
}
//---------------------------------------------------------------------------
string WAV_Flavor_String(uint8_t Flavor)
{
string ToReturn("WAV/PCM/");
ToReturn += SamplesPerSec_String((wav::flavor)Flavor);
ToReturn += "kHz/";
ToReturn += BitDepth_String((wav::flavor)Flavor);
ToReturn += "bit/";
ToReturn += Channels_String((wav::flavor)Flavor);
ToReturn += "ch/LE";
return ToReturn;
}
| 30.265107
| 118
| 0.51797
|
g-maxime
|
312791034812c6809945ca4b7f033363c0df0ae7
| 2,756
|
cpp
|
C++
|
18_lab/main.cpp
|
TimmiJK/2021-spring-polytech-cpp
|
1e957a2619e5c61f1dc1b7941ffae5d70b86870c
|
[
"MIT"
] | 6
|
2021-02-08T15:26:20.000Z
|
2021-03-22T10:19:07.000Z
|
18_lab/main.cpp
|
TimmiJK/2021-spring-polytech-cpp
|
1e957a2619e5c61f1dc1b7941ffae5d70b86870c
|
[
"MIT"
] | 11
|
2021-02-09T06:41:50.000Z
|
2021-04-18T08:36:32.000Z
|
18_lab/main.cpp
|
TimmiJK/2021-spring-polytech-cpp
|
1e957a2619e5c61f1dc1b7941ffae5d70b86870c
|
[
"MIT"
] | 48
|
2021-02-03T18:28:55.000Z
|
2021-05-24T18:54:14.000Z
|
// Напишите программу, используя технику TDD. Реализуйте калькулятор,
// поддерживающий операции: +, -, *, /. Проверьте тестами свойства операций
// и законы элементарной алгебры.
#include <cassert>
enum class Command {
Add,
Sub,
Mul,
Div
};
double calc(enum class Command operation, double x, double y) {
double result;
switch (operation) {
case Command::Add:
result = x + y;
break;
case Command::Sub:
result = x - y;
break;
case Command::Mul:
result = x * y;
break;
case Command::Div:
if (y != 0) {
result = x / y;
}
break;
default:
result = 0;
break;
}
return result;
}
int main() {
// Операции с нулями
assert(calc(Command::Add, 0.0, 0.0) == 0.0);
assert(calc(Command::Sub, 0.0, 0.0) == 0.0);
assert(calc(Command::Mul, 0.0, 0.0) == 0.0);
assert(calc(Command::Div, 0.0, 5.0) == 0.0);
// Коммутативность сложения
assert(calc(Command::Add, 2.0, 1.0) == calc(Command::Add, 1.0, 2.0));
// Ассоциативность сложения
assert(calc(Command::Add, calc(Command::Add, 2.0, 3.0), 5.0) ==
calc(Command::Add, calc(Command::Add, 5.0, 3.0), 2.0));
// Коммутативность умножения
assert(calc(Command::Mul, 2.0, 8.0) == calc(Command::Mul, 8.0, 2.0));
// Ассоциативность умножения
assert(calc(Command::Mul, calc(Command::Mul, 3.0, 4.0), 2.0) ==
calc(Command::Mul, calc(Command::Mul, 2.0, 4.0), 3.0));
// Дистрибутивность умножения
assert(calc(Command::Mul, calc(Command::Add, 3.0, 4.0), 5.0) ==
calc(Command::Add, calc(Command::Mul, 3.0, 5.0), calc(Command::Mul, 4.0, 5.0)));
// Операции с проверкой знаков
// + +
// - -
// - +
// + -
// Сложение
assert(calc(Command::Add, 3.0, 5.0) == 8.0);
assert(calc(Command::Add, -3.0, -5.0) == -8.0);
assert(calc(Command::Add, -3.0, 5.0) == 2.0);
assert(calc(Command::Add, 3.0, -5.0) == -2.0);
// Вычитание
assert(calc(Command::Sub, 2.0, 1.0) == 1.0);
assert(calc(Command::Sub, -2.0, -1.0) == -1.0);
assert(calc(Command::Sub, 2.0, -1.0) == 3.0);
assert(calc(Command::Sub, -2.0, 1.0) == -3.0);
// Умножение
assert(calc(Command::Mul, 5.0, 5.0) == 25.0);
assert(calc(Command::Mul, -5.0, -5.0) == 25.0);
assert(calc(Command::Mul, 5.0, -5.0) == -25.0);
assert(calc(Command::Mul, -5.0, 5.0) == -25.0);
// Деление
assert(calc(Command::Div, 10.0, 5.0) == 2.0);
assert(calc(Command::Div, -10.0, -5.0) == 2.0);
assert(calc(Command::Div, 10.0, -5.0) == -2.0);
assert(calc(Command::Div, -10.0, 5.0) == -2.0);
return 0;
}
| 30.285714
| 91
| 0.527213
|
TimmiJK
|
3129be97eea2a7d5b651ef849823a159f0d5711b
| 5,935
|
cpp
|
C++
|
SourceFile/SearchSystem.cpp
|
hsu0602/oop_final_project
|
53feacddaf7c5abb0b09c83ba9390f047b8fb5c8
|
[
"MIT"
] | null | null | null |
SourceFile/SearchSystem.cpp
|
hsu0602/oop_final_project
|
53feacddaf7c5abb0b09c83ba9390f047b8fb5c8
|
[
"MIT"
] | null | null | null |
SourceFile/SearchSystem.cpp
|
hsu0602/oop_final_project
|
53feacddaf7c5abb0b09c83ba9390f047b8fb5c8
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "../HeaderFile/SearchSystem.h"
#include "../HeaderFile/FileConnector.h"
#include "../HeaderFile/ConvertorOfTimeAndString.h"
//return the goodInventory of tech input id
GoodInventory SearchSystem::findInventoryById(int input_id){
FileConnector file("Inventory.csv");
file.search("id", std::to_string(input_id));
return tableToInventories(file.getResult())[0];
}
GoodInventory SearchSystem::findInventoryByName(std::string input_name){
FileConnector file("Inventory.csv");
file.search("name", input_name);
return tableToInventories(file.getResult())[0];
}
// Find the good of input id and set the quantity to input_quantity for reciept.
GoodInventory SearchSystem::findInventoryByIdAndSetQuantity(int input_id, int input_quantity){
GoodInventory tmp = findInventoryById(input_id);
return GoodInventory(tmp.getId(), tmp.getCategory(), tmp.getName(), tmp.getPrice(), input_quantity);
}
// return all goodInvantory of the input category
std::vector<GoodInventory> SearchSystem::findInventoriesByCategory(std::string input_category){
FileConnector file("Inventory.csv");
file.search("category", input_category);
return tableToInventories(file.getResult());
}
// use id search the quantity of that good
int SearchSystem::findQuantityOfGood(int input_id){
return findInventoryById(input_id).getQuantity();
}
// put the reciept to database for processing
void SearchSystem::purchaseConfirm(std::vector<GoodInventory> the_reciept){
FileConnector inventory_file("Inventory.csv");
for(int i=0; i<the_reciept.size(); i++){
std::string target_id = std::to_string(the_reciept[i].getId());
inventory_file.search("id", target_id);
std::vector<std::string> result = inventory_file.getResult()[0];
inventory_file.update("id", target_id, "quantity", std::to_string(stoi(result[4]) - the_reciept[i].getQuantity()));
}
//file.close():
FileConnector activity_file("Activity.csv");
for(GoodInventory i : the_reciept){
activity_file.append(addActivity(i, "purchase"));
}
//file.close();
}
void SearchSystem::supplyConfirm(std::vector<GoodInventory> old_reciept, std::vector<GoodInventory> new_reciept){
std::cout << "opening Inventory.cvs" << std::endl;
FileConnector inventory_file("Inventory.csv");
std::cout << "Inserting old good into Inventory..." << std::endl;
for(int i=0; i<old_reciept.size(); i++){
std::string target_id = std::to_string(old_reciept[i].getId());
inventory_file.search("id", target_id);
std::vector<std::string> result = inventory_file.getResult()[0];
inventory_file.update("id", target_id, "quantity", std::to_string(stoi(result[4]) + old_reciept[i].getQuantity()));
}
std::cout << "Appending new good into Inventory..." << std::endl;
for(int i=0; i<new_reciept.size(); i++){
std::cout << "Inventory size is " << inventory_file.getResult().size() << std::endl;
std::string id = std::to_string(inventory_file.getResult().size())
, category = new_reciept[i].getCategory()
, name = new_reciept[i].getName()
, price = std::to_string(new_reciept[i].getPrice())
, quantity = std::to_string(new_reciept[i].getQuantity());
inventory_file.append( {id, category, name, price, quantity} );
}
//file.close();
std::cout << "Appending new activity..." << std::endl;
FileConnector activity_file("Activity.csv");
for(GoodInventory i : old_reciept){
activity_file.append(addActivity(i, "supply"));
}
for(GoodInventory i : new_reciept){
activity_file.append(addActivity(i, "supply"));
}
//file.close();
}
std::vector<std::string> SearchSystem::addActivity(GoodInventory input_good, std::string input_type){
std::vector<std::string> tmp;
tmp.push_back( getTimeString() );
tmp.push_back( input_type );
tmp.push_back( input_good.getCategory() );
tmp.push_back( input_good.getName() );
tmp.push_back( std::to_string(input_good.getPrice()) );
tmp.push_back( std::to_string(input_good.getQuantity()) );
return tmp;
}
std::vector<Good> SearchSystem::tableToGoods(std::vector<std::vector<std::string> > input){
std::vector<Good> tmp;
for(int i=0; i<input.size(); i++){
// id(int), name(string), category(string), price(int)
tmp.push_back( Good(stoi(input[i][0]), input[i][1], input[i][2], stoi(input[i][3])) );
}
if(tmp.size())
return tmp;
else
{
std::cout << "empty search!" << std::endl;
tmp.push_back(Good(-1, "-1", "-1", -1));
return tmp;
}
}
std::vector<GoodInventory> SearchSystem::tableToInventories(std::vector<std::vector<std::string> > input){
std::vector<GoodInventory> tmp;
for(int i=0; i<input.size(); i++){
// id(int), name(string), category(string), price(int)
tmp.push_back( GoodInventory(stoi(input[i][0]), input[i][1], input[i][2], stoi(input[i][3]), stoi(input[i][4])) );
}
if(tmp.size())
return tmp;
else
{
std::cout << "empty search!" << std::endl;
tmp.push_back(GoodInventory(-1, "-1", "-1", -1, -1));
return tmp;
}
}
std::vector<GoodActivity> SearchSystem::tableToActivities(std::vector<std::vector<std::string> > input){
std::vector<GoodActivity> tmp;
for(int i=0; i<input.size(); i++){
// id(int), name(string), category(string), price(int)
tmp.push_back( GoodActivity(stoi(input[i][0]), input[i][1], input[i][2], stoi(input[i][3]), stoi(input[i][4]), StringToDatetime(input[i][5])) );
}
if(tmp.size())
return tmp;
else
{
std::cout << "empty search!" << std::endl;
tmp.push_back(GoodActivity(-1, "-1", "-1", -1, -1, StringToDatetime(getTimeString())));
return tmp;
}
}
| 35.327381
| 152
| 0.648526
|
hsu0602
|
312a3aa1d9be22370491ec2085c1fd6baa85b9df
| 1,019
|
cpp
|
C++
|
Paladin/Templates/Sample HaikuFortune/App.cpp
|
humdingerb/Paladin
|
ef42b060656833f2887241c809690b263ddf2852
|
[
"MIT"
] | 45
|
2018-10-05T21:50:17.000Z
|
2022-01-31T11:52:59.000Z
|
Paladin/Templates/Sample HaikuFortune/App.cpp
|
humdingerb/Paladin
|
ef42b060656833f2887241c809690b263ddf2852
|
[
"MIT"
] | 163
|
2018-10-01T23:52:12.000Z
|
2022-02-15T18:05:58.000Z
|
Paladin/Templates/Sample HaikuFortune/App.cpp
|
humdingerb/Paladin
|
ef42b060656833f2887241c809690b263ddf2852
|
[
"MIT"
] | 9
|
2018-10-01T23:48:02.000Z
|
2022-01-23T21:28:52.000Z
|
#include "App.h"
#include <FindDirectory.h>
#include <OS.h>
#include <Path.h>
#include <stdlib.h>
#include "FortuneFunctions.h"
#include "MainWindow.h"
App::App(void)
: BApplication("application/x-vnd.test-HaikuFortune")
{
BPath path;
// We have to use an #ifdef here because the fortune files under R5
// and Zeta are in the system/etc/ directory, but in Haiku they're
// kept in the system/data directory.
#ifdef __HAIKU__
find_directory(B_SYSTEM_DATA_DIRECTORY,&path);
#else
find_directory(B_BEOS_ETC_DIRECTORY,&path);
#endif
path.Append("fortunes");
gFortunePath = path.Path();
// If we want the rand() function to actually be pretty close to random
// we will need to seed the random number generator with the time. If we
// don't, we will get the same "random" numbers each time the program is
// run.
srand(system_time());
MainWindow *win = new MainWindow();
win->Show();
}
int
main(void)
{
srand(system_time());
App *app = new App();
app->Run();
delete app;
return 0;
}
| 20.795918
| 73
| 0.701668
|
humdingerb
|
312b59b41269d179c28f1161a79d007df5d067aa
| 710
|
hpp
|
C++
|
external/boost_1_60_0/qsboost/config/abi_prefix.hpp
|
wouterboomsma/quickstep
|
a33447562eca1350c626883f21c68125bd9f776c
|
[
"MIT"
] | 1
|
2019-06-27T17:54:13.000Z
|
2019-06-27T17:54:13.000Z
|
external/boost_1_60_0/qsboost/config/abi_prefix.hpp
|
wouterboomsma/quickstep
|
a33447562eca1350c626883f21c68125bd9f776c
|
[
"MIT"
] | null | null | null |
external/boost_1_60_0/qsboost/config/abi_prefix.hpp
|
wouterboomsma/quickstep
|
a33447562eca1350c626883f21c68125bd9f776c
|
[
"MIT"
] | null | null | null |
// abi_prefix header -------------------------------------------------------//
// (c) Copyright John Maddock 2003
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#ifndef QSBOOST_CONFIG_ABI_PREFIX_HPP
# define QSBOOST_CONFIG_ABI_PREFIX_HPP
#else
# error double inclusion of header qsboost/config/abi_prefix.hpp is an error
#endif
#include <qsboost/config.hpp>
// this must occur after all other includes and before any code appears:
#ifdef QSBOOST_HAS_ABI_HEADERS
# include QSBOOST_ABI_PREFIX
#endif
#if defined( __BORLANDC__ )
#pragma nopushoptwarn
#endif
| 27.307692
| 80
| 0.71831
|
wouterboomsma
|
312b616126ca8b4a9c023a4b2f9327f3db395ce7
| 1,775
|
cpp
|
C++
|
boj/gold/1753.cpp
|
pseudowasabi/Resolucion-de-problemas
|
47164c106d666aa07a48b8c2909a3d81f26d3dc9
|
[
"MIT"
] | null | null | null |
boj/gold/1753.cpp
|
pseudowasabi/Resolucion-de-problemas
|
47164c106d666aa07a48b8c2909a3d81f26d3dc9
|
[
"MIT"
] | null | null | null |
boj/gold/1753.cpp
|
pseudowasabi/Resolucion-de-problemas
|
47164c106d666aa07a48b8c2909a3d81f26d3dc9
|
[
"MIT"
] | 1
|
2020-03-14T10:58:54.000Z
|
2020-03-14T10:58:54.000Z
|
// basic dijkstra algorithm
#include <iostream>
#include <queue>
#include <cstring>
#include <utility>
using namespace std;
int v, e;
int stp;
class Edge {
public:
Edge *next_one;
int from, to, weight;
bool checked;
Edge() {
next_one = nullptr;
from = to = weight = 0;
checked = false;
}
};
Edge *graph[20001];
typedef pair<int, int> ipair;
auto cmp = [](const ipair& left, const ipair& right) {
return left.second > right.second;
};
priority_queue<ipair, vector<ipair>, decltype(cmp)> dijk(cmp);
int cost[20001];
const int inf = 0x7fffffff;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> v >> e;
cin >> stp;
for(int i=1;i<=v;++i) {
graph[i] = new Edge;
cost[i] = inf;
}
for(int i=0;i<e;++i) {
int u, v, w;
cin >> u >> v >> w;
Edge *new_edge = new Edge;
new_edge->from = u;
new_edge->to = v;
new_edge->weight = w;
new_edge->next_one = graph[u]->next_one;
graph[u]->next_one = new_edge;
}
dijk.push({stp, 0});
while(!dijk.empty()) {
ipair now = dijk.top();
dijk.pop();
if(cost[now.first] <= now.second) { // 같은 경우에도 pass
continue;
}
cost[now.first] = now.second;
// idea: 모든 edge를 다 보는 경우(=worst case)
for(Edge *it=graph[now.first]->next_one;it != nullptr;it = it->next_one) {
if(!(it->checked)) {
dijk.push({it->to, it->weight + now.second});
it->checked = true;
}
}
}
for(int i=1;i<=v;++i) {
if(cost[i] != inf) {
cout << cost[i] << '\n';
} else {
cout << "INF\n";
}
}
return 0;
}
| 22.1875
| 82
| 0.502535
|
pseudowasabi
|
312c1a31a41e87631e38e0111c20f9c1c2f82adb
| 1,876
|
hpp
|
C++
|
cpp-learn3d/Render.hpp
|
robotjunkyard/cl-learn3d
|
040207b06117f7a6a9d5bd5f120c6209aa1157f5
|
[
"MIT"
] | null | null | null |
cpp-learn3d/Render.hpp
|
robotjunkyard/cl-learn3d
|
040207b06117f7a6a9d5bd5f120c6209aa1157f5
|
[
"MIT"
] | null | null | null |
cpp-learn3d/Render.hpp
|
robotjunkyard/cl-learn3d
|
040207b06117f7a6a9d5bd5f120c6209aa1157f5
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Camera.hpp"
#include "CanvasDef.hpp"
#include "Mat.hpp"
#include "Mesh.hpp"
#include "Vec.hpp"
class Render {
public:
static void drawFlat3DTriangle(Canvas& canvas, const Camera& camera, byte color,
const Vec3& v1, const Vec3& v2, const Vec3& v3,
const Mat& tmat,
bool cullBackfaces);
static void drawMeshFlat(Canvas& canvas, const Camera& camera, const Mesh& mesh); // flat-shaded debug mesh draw
static void drawMeshTextured(Canvas& canvas, const Camera& camera, const Mesh& mesh); // textured mesh draw
static float drawSubtriangleTextured(Canvas& canvas,
float start_sx0, float start_sx1,
float dsx0, // dupper, // dsx0
float dsx1, // dlong, // dsx1
int yi_start, // yi_start
int yi_end, // std::min(midy, h), // yi_end
const Bitmap& bitmap,
const Triangle2& screenTri,
const Triangle2& uvtri);
static void drawMeshTriangleTextured (Canvas& canvas, const Mesh& mesh,
const Triangle2& uvtri,
int x1, int y1, int x2, int y2, int x3, int y3);
static void drawTexturedMeshFace(Canvas& canvas, const Mesh& mesh, const Camera& camera,
const Mat& tmat,
unsigned short facenum,
const Triangle3& faceTri, const Triangle2& uvTri,
bool cullBackfaces);
};
| 50.702703
| 120
| 0.471748
|
robotjunkyard
|
3132fc26d8801af1baa8b3ae4d13f42bed8d8cbe
| 34,407
|
cpp
|
C++
|
src/Ligg.SeqExec/main.cpp
|
Liggin2019/Ligg.SeqExec
|
f4d770a6ed50aa0874b6aa410d54074cd1251fa5
|
[
"Apache-2.0"
] | 2
|
2019-10-29T05:15:03.000Z
|
2019-11-01T18:18:02.000Z
|
src/Ligg.SeqExec/main.cpp
|
ligg2018/Ligg.SeqExec
|
677d4bcca3b809443b9100cfa9bdf8cb49f96777
|
[
"Apache-2.0"
] | null | null | null |
src/Ligg.SeqExec/main.cpp
|
ligg2018/Ligg.SeqExec
|
677d4bcca3b809443b9100cfa9bdf8cb49f96777
|
[
"Apache-2.0"
] | 1
|
2019-11-01T18:18:03.000Z
|
2019-11-01T18:18:03.000Z
|
// includes
#include <windows.h>
//for _ASSERTE
#include <crtdbg.h>
#include <tchar.h>
#include <stdio.h>
#include "lm.h"
#include "CSingleInstance.hxx" // CSingleInstance implementation
#include "CError.h" // CError definition
#include "resource.h" // string defines
#include "SetupCodes.h" // setup-related error codes
#include "CSettings.h" // ini-based app globals/setting
#include "main.h"
#include "..\Share\Encrpt\EncryptHelper.h"
#include "..\Share\CommonDefine.h"
#include "..\Share\ProcessHelper.h"
#include "..\Share\StringHelper.h"
CSettings settings;
DWORD threadNoDw = 0;
HANDLE threadHandle = NULL;
TCHAR windowsDir[512];
TCHAR windowsSystemDir[512];
TCHAR message[255];
HWND billBoard;
int windowCount = 0;
TCHAR curDlgCaption[64];
TCHAR curDlgMsg[255];
ProcessHelper processHelper;
StringHelper stringHelper;
// ==========================================================================
// WinMain(): application entry point
// ==========================================================================
int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{
UINT uRetCode = 0; // bootstrapper return code
BOOL isFxReboot = FALSE; // reboot indicated due to fx install
BOOL isAppReboot = FALSE; // reboot indicated after host app install
BOOL isAppInstallSucceeded = TRUE;
//##for testing
/*if(ip != NULL)
{
MessageBox(NULL, "test11", "Test", MB_OK | MB_ICONINFORMATION);
}*/
TCHAR mutexName[MAX_PATH+1];
GetModuleFileName(settings.GetHInstance(), mutexName, LENGTH(mutexName));
for(int i = 0;i < LENGTH(mutexName);++i)
{
if(mutexName[i]==':')
{
mutexName[i]='-';
}
else if(mutexName[i]=='\\')
{
mutexName[i]='-';
}
}
CSingleInstance si(mutexName);
// initialize hInstance in global settings
settings.SetHInstance(hInstance);
try
{
// validate single instance if we are not alone, throw an error
if( !si.IsUnique() )
{
CError se( 0, ERR_NOT_SINGLE_INSTANCE, MB_ICONERROR, COR_NOT_SINGLE_INSTANCE );
throw( se );
}
// if there was a problem creating mutex, throw an error
else if( !si.IsHandleOK() )
{
CError se(0,ERR_SINGLE_INSTANCE_FAIL, MB_ICONERROR, COR_SINGLE_INSTANCE_FAIL );
//throw( se );
se.ShowMessage();
}
if (!GetWindowsDirectory(windowsDir, LENGTH(windowsDir)))
{
HandleResult(GetLastError());
}
if (!GetSystemDirectory(windowsSystemDir, LENGTH(windowsSystemDir)))
{
HandleResult(GetLastError());
}
SetWorkingDir();
RemoveRegistryRun();
//put ourselves in install mode, if running on Terminal Server.
SetTSInInstallMode();
settings.Parse();
if(_tcsicmp(settings.StartPolicy,"1") ==0)
{
//input password
bool b=DialogBox(hInstance, MAKEINTRESOURCE(DIALOG_PASSWORDVERIFICATION), NULL, ProcDlgPasswordVerification);
if(!b)
{
return 0;
}
}
if(!settings.IsDefaultMode)
{
bool ifClickNext=DialogBox(hInstance, MAKEINTRESOURCE(DIALOG_MAIN), NULL, ProcDlgMain);
if(!ifClickNext) return 0;
}
WCHAR domain_w[MAX_INI_DECRPTED_STR_LEN+1];
swprintf(domain_w,L"%S",settings.Domain);
WCHAR id_w[MAX_INI_DECRPTED_STR_LEN+1];
swprintf(id_w,L"%S",settings.Id);
WCHAR password_w[MAX_INI_DECRPTED_STR_LEN+1];
swprintf(password_w,L"%S",(settings.Password));
bool isProcessRunByAdmin=false;
if(settings.IsProcessRunByAdmin)
{
isProcessRunByAdmin=true;
}
//=======================================================================
//** begin to do sequencing Exec
//=======================================================================
int i;
DWORD resultDw;
int resultInt= 0;
for(i = 0;i < settings.StepNo;++i)
{
char stepNo[3];
sprintf(stepNo,"%d",i);
char step[8];
sprintf(step,"%s%s","Step-",stepNo);
_sntprintf(settings.CurStepDes, LENGTH(settings.CurStepDes)-1, _T("%s"), step);
_sntprintf(settings.CurMsgCaptionText, LENGTH(settings.CurMsgCaptionText)-1, _T("%s %s"), settings.CurStepDes,"Error");
if(!settings.IsQuietMode&&!settings.IsUnselected[i])
{
ShowBillboard(&threadNoDw, &threadHandle);
TCHAR billBdMsg[MAX_INI_BILLBOARD_MSG_STR_LEN];
if(!_tcsicmp(settings.BillboardMsg[i],_T("")) ==0)
{
_sntprintf(billBdMsg, LENGTH(billBdMsg)-1,"%s",settings.BillboardMsg[i]);
}
else
{
TCHAR plzWait[15];
::LoadString(settings.GetHInstance(),
MSG_PLZ_WAIT,
plzWait,
LENGTH(plzWait) ) ;
_sntprintf(billBdMsg, LENGTH(billBdMsg)-1,"%s..., %s!",settings.StepDes[i],plzWait);
}
SetBillBoardText(settings.BillboardTitle,billBdMsg);
}
if((_tcsicmp(settings.RunType[i],_T("Run")) == 0)&&(!settings.IsUnselected[i]))
{
TCHAR cmdLine[MAX_PATH+MAX_INI_STEP_RUN_OPTION_STR_LEN+MAX_INI_STEP_ARGS_STR_LEN+5+1];
_sntprintf(cmdLine, LENGTH(cmdLine)-1,"%s %s %s",settings.FilePath[i],settings.RunOption[i],settings.Args[i]);
if(settings.RunByAdmin[i])
{
if(isProcessRunByAdmin)
{
resultDw = processHelper.Run(false,cmdLine);
}
else
{
WCHAR cmdLine_w[MAX_PATH+MAX_INI_STEP_RUN_OPTION_STR_LEN+MAX_INI_STEP_ARGS_STR_LEN+5+1];
swprintf(cmdLine_w,L"%S",cmdLine);
resultDw = processHelper.RunAsUser(false,cmdLine_w,domain_w,id_w,password_w);
}
}
else
{
resultDw = processHelper.Run(false,cmdLine);
}
}
else if((_tcsicmp(settings.RunType[i],_T("ExecCmd")) == 0)&&(!settings.IsUnselected[i]))
{
TCHAR cmdLine[MAX_INI_STEP_RUN_OPTION_STR_LEN+MAX_INI_STEP_ARGS_STR_LEN+1+1];
char* runOption=settings.RunOption[i];
if(_tcsicmp(settings.RunOption[i],_T("")) ==0)
{
sprintf(runOption,"%s","/c");
}
_sntprintf(cmdLine, LENGTH(cmdLine)-1,"%s %s",runOption,settings.Args[i]);
if(settings.RunByAdmin[i])
{
if(isProcessRunByAdmin)
{
///resultDw = ExecCmd(cmdLine);
resultDw =processHelper.Run(true,cmdLine);
}
else
{
WCHAR cmdLine_w[MAX_INI_STEP_RUN_OPTION_STR_LEN+MAX_INI_STEP_ARGS_STR_LEN+3+1];
swprintf(cmdLine_w,L"%S",cmdLine);
resultDw = processHelper.RunAsUser(true,cmdLine_w,domain_w,id_w,password_w);
}
}
else
{
resultDw =processHelper.Run(true,cmdLine);
}
}
else if((_tcsicmp(settings.RunType[i],_T("RunCmd")) == 0)&&(!settings.IsUnselected[i]))
{
char* runOption=settings.RunOption[i];
if(_tcsicmp(settings.RunOption[i],_T("")) ==0)
{
sprintf(runOption,"%s","/c");
}
TCHAR cmdLine[MAX_PATH+MAX_INI_STEP_RUN_OPTION_STR_LEN+MAX_INI_STEP_ARGS_STR_LEN+3+1];
_sntprintf(cmdLine, LENGTH(cmdLine)-1,"%s %s %s",runOption,settings.AbsoluteFilePath[i],settings.Args[i]);
if(settings.RunByAdmin[i])
{
if(isProcessRunByAdmin)
{
resultDw =processHelper.Run(true,cmdLine);
}
else
{
WCHAR cmdLine_w[MAX_INI_STEP_RUN_OPTION_STR_LEN+MAX_INI_STEP_ARGS_STR_LEN+3+1];
swprintf(cmdLine_w,L"%S",cmdLine);
resultDw = processHelper.RunAsUser(true,cmdLine_w,domain_w,id_w,password_w);
}
}
else
{
resultDw =processHelper.Run(true,cmdLine);
}
}
else if((_tcsicmp(settings.RunType[i],_T("GetDesEncryptCode")) == 0)&&(!settings.IsUnselected[i]))
{
bool b=DialogBox(hInstance, MAKEINTRESOURCE(DIALOG_ENCRPT), NULL, ProcDlgEncrpt);
}
else if((_tcsicmp(settings.RunType[i],_T("CheckAdmin")) == 0)&&(!settings.IsUnselected[i]))
{
if(!isProcessRunByAdmin)
{
CError se(0,ERR_INSUFFICIENT_PRIVILEGES, MB_ICONERROR, COR_SINGLE_INSTANCE_FAIL );
throw( se );
}
}
else if((_tcsicmp(settings.RunType[i],_T("InstallMsi")) == 0)&&(!settings.IsUnselected[i]))
{
TCHAR msiCmdLine[50] = _T("Msiexec.exe");
_sntprintf(msiCmdLine, LENGTH(msiCmdLine)-1,"%s %s",msiCmdLine,settings.RunOption[i]);
TCHAR msiInstallCmd[MAX_PATH + LENGTH(msiCmdLine) + 2];
_sntprintf(msiInstallCmd, LENGTH(msiInstallCmd)-1,"%s\\%s %s %s",windowsSystemDir,msiCmdLine,settings.FilePath[i],settings.Args[i]);
if(settings.RunByAdmin[i])
{
if(isProcessRunByAdmin)
{
resultDw = processHelper.Run(false,msiInstallCmd);
}
else
{
WCHAR cmdLine_w[MAX_PATH + LENGTH(msiCmdLine) + 2];
swprintf(cmdLine_w,L"%S",msiInstallCmd);
resultDw = processHelper.RunAsUser(false,cmdLine_w,domain_w,id_w,password_w);
}
}
else
{
resultDw = processHelper.Run(false,msiInstallCmd);
}
if ( ERROR_SUCCESS_REBOOT_REQUIRED == resultDw ||ERROR_SUCCESS == resultDw )
{
isAppReboot = (resultDw == ERROR_SUCCESS_REBOOT_REQUIRED) ? true : isAppReboot;
}
else if ( resultDw == ERROR_INSTALL_USEREXIT)
{
isAppInstallSucceeded = FALSE;
}
else
{
// we display the error msg here and do not rethrow this is because we need to continue with a system reboot in the event
//that fx was installed successfully before msi-install failure
CError se( 0,ERR_FILE_HAS_PROBLEM, MB_ICONERROR, resultDw );
se.ShowMessage();
isAppInstallSucceeded = FALSE;
}
}
else if((_tcsicmp(settings.RunType[i],_T("ShowNetFxDownloadUrl")) == 0)&&(!settings.IsUnselected[i]))
{
char * runOptionString=settings.RunOption[i];
char * runOptionStringArry[16];
int returnCount = 0;
stringHelper.Split(runOptionString,"^",runOptionStringArry,&returnCount);
if(returnCount==1)
{
runOptionStringArry[1]=new char[1];
runOptionStringArry[2]=new char[1];
sprintf(runOptionStringArry[1],"%s","");
sprintf(runOptionStringArry[2],"%s","");
}
else if(returnCount==2)
{
runOptionStringArry[2]=new char[1];
sprintf(runOptionStringArry[2],"%s","");
}
if (IfNeedToInstallNetFx(runOptionStringArry[0],runOptionStringArry[1],runOptionStringArry[2]) ==true)
{
_sntprintf(curDlgCaption, LENGTH(curDlgCaption)-1, _T("%s %s %s"), ".Net Framework",runOptionStringArry[0],
"was needed to install to run this app! ");
_sntprintf(curDlgMsg, LENGTH(curDlgMsg)-1, _T("%s"), settings.Args[i]);
bool b=DialogBox(hInstance, MAKEINTRESOURCE(DIALOG_MSG), NULL, ProcDlgMsg);
}
/*}*/
}
else if((_tcsicmp(settings.RunType[i],_T("InstallNetFx")) == 0)&&(!settings.IsUnselected[i]))
{
char * argsString=settings.Args[i];
char * argsStringArry[16];
int returnCount = 0;
stringHelper.Split(argsString,"^",argsStringArry,&returnCount);
if(returnCount==1)
{
argsStringArry[1]=new char[1];
argsStringArry[2]=new char[1];
sprintf(argsStringArry[1],"%s","");
sprintf(argsStringArry[2],"%s","");
}
else if(returnCount==2)
{
argsStringArry[2]=new char[1];
sprintf(argsStringArry[2],"%s","");
}
if (IfNeedToInstallNetFx(argsStringArry[0],argsStringArry[1],argsStringArry[2]) ==true)
{
TCHAR* fxInstallerPath=settings.AbsoluteFilePath[i];
// 2 add'l chars for zero-term and space embedded between app name & cmd-line
TCHAR fxInstallCmd[MAX_PATH + LENGTH(settings.AbsoluteFilePath[i]) + LENGTH(settings.RunOption[i])+ 5];
if(strstr(settings.RunOption[i], "^") != NULL)
{
char * runOptionString=settings.RunOption[i];
char * runOptionStringArry[16];
int returnCount = 0;
stringHelper.Split(runOptionString,"^",runOptionStringArry,&returnCount);
_sntprintf(fxInstallCmd, LENGTH(fxInstallCmd)-1,
_T("%s %s"),
_T("/c"),
runOptionStringArry[1]);
}
else
{
// build fully-qualified path to dotnetfx.exe
_sntprintf(fxInstallCmd,
LENGTH(fxInstallCmd)-1,
_T("%s %s %s"),
_T("/c"),
settings.AbsoluteFilePath[i],
settings.RunOption[i]);
}
if(isProcessRunByAdmin)
{
resultDw = processHelper.Run(true,fxInstallCmd);
}
else
{
WCHAR cmdLine_w[MAX_PATH + LENGTH(settings.AbsoluteFilePath[i]) + LENGTH(settings.RunOption[i])+ 2];
swprintf(cmdLine_w,L"%S",fxInstallCmd);
resultDw = processHelper.RunAsUser(true,cmdLine_w,domain_w,id_w,password_w);
}
if ( ERROR_SUCCESS_REBOOT_REQUIRED == resultDw ||ERROR_SUCCESS == resultDw )
{
isFxReboot = true;
}
else
{
switch(resultDw)
{
case 8192: // Reboot
isFxReboot = true;
break;
case 4096:
{
CError se(0, ERR_ERROR1, MB_ICONERROR, resultDw );
throw ( se );
break ;
}
case 4097:
{
CError se( 0, ERR_ERROR2, MB_ICONERROR, resultDw );
throw ( se );
break ;
}
case 4098:
{
CError se( 0, ERR_ERROR3, MB_ICONERROR, resultDw );
throw ( se );
break ;
}
case 4099:
{
CError se( 0, ERR_ERROR4, MB_ICONERROR, resultDw );
throw ( se );
break ;
}
case 4100:
{
CError se( 0, ERR_ERROR5,MB_ICONERROR,resultDw );
throw ( se );
break ;
}
case 4101:
{
CError se( 0, ERR_ERROR6, MB_ICONERROR, resultDw );
throw ( se );
break ;
}
case 4104:
{
CError se(0, ERR_ERROR7,MB_ICONERROR,resultDw );
throw ( se );
break ;
}
case 4111:
{
CError se( 0, ERR_ERROR8, MB_ICONERROR, resultDw );
throw ( se );
break ;
}
case 4113:
{
CError se(0, ERR_ERROR9, MB_ICONERROR, resultDw );
throw ( se );
break ;
}
case 4114:
{
CError se( 0, ERR_ERROR10, MB_ICONERROR, resultDw );
throw ( se );
break ;
}
case 8191:
{
CError se( 0, ERR_ERROR5, MB_ICONERROR, resultDw );
throw ( se );
break ;
}
default :
{
break ;
}
}
}
}
} //end else if settings.RunType[i]==_T("InstallNetFx")
// Are we running in quiet mode?
if(!settings.IsQuietMode)
{
TeardownBillboard(threadNoDw, threadHandle);
}
}//end for
//now handle the reboot
if (isFxReboot || isAppReboot)
{
CError se(MSG_REBOOT_QUERY, 0, MB_YESNO);
resultInt = se.ShowMessage();
//if (resultInt == IDYES)
if (resultInt == 1)
{
InsertRegistryRun();
InitiateReboot();
}
}
}
catch (HRESULT)
{
// hresult exception msg display is handled by the originator. the exception is rethrown and caught here in order to exit.
}
catch( CError se )
{
uRetCode = se.m_nRetCode;
se.ShowMessage();
}
catch( ... )
{
CError se( 0, ERR_FILE_HAS_PROBLEM, MB_ICONERROR, COR_EXIT_FAILURE );
uRetCode = se.m_nRetCode;
se.ShowMessage();
}
return uRetCode;
}
BOOL Reboot(DWORD resultDw)
{
if ( ERROR_SUCCESS_REBOOT_REQUIRED == resultDw ||
ERROR_SUCCESS == resultDw )
{
return (resultDw == ERROR_SUCCESS_REBOOT_REQUIRED);
}
return false;
}
BOOL HandleResult(DWORD resultDw)
{
if ( ERROR_SUCCESS_REBOOT_REQUIRED == resultDw ||
ERROR_SUCCESS == resultDw )
{
return true;
}
else
{
// we display the error msg here and do not rethrow
// this is because we need to continue with a system
// reboot in the event that fx was installed
// successfully before msi-install failure
CError se( 0, ERR_FILE_HAS_PROBLEM, MB_ICONERROR, resultDw );
se.ShowMessage();
return false;
}
return true;
}
// ==========================================================================
// CheckNetFxVersion()
// Purpose: Checks whether the provided Microsoft .Net Framework redistributable files should be installed to the local machine
// ==========================================================================
//old time, no use
BOOL CheckNetFxVersion(LPTSTR fxInstallerPath,char* netVersion)
{
BOOL ifNeedToInstall = TRUE;
TCHAR fxInstaller[MAX_PATH + 1];
_sntprintf(fxInstaller, LENGTH(fxInstaller)-1, _T("%s"), fxInstallerPath);
try
{
HRESULT hr;
VS_FIXEDFILEINFO vsf;
//hr = settings.GetFileVersion (fxInstaller, &vsf);
if (FAILED(hr))
{
//throw hr;
CError se( 0,ERR_VERSION_DETECT_FAILED,MB_ICONERROR,COR_EXIT_FAILURE,fxInstaller);
throw( se );
}
// retrieve dotnetfx.exe build #
DWORD dwFileVersionLS = vsf.dwFileVersionLS >> 16;
// we need a text representation
TCHAR subVersion[11]; // sufficient for DWORD max + zero term
_stprintf(subVersion, _T("%u"), dwFileVersionLS);
// now we'll check the registry for this value
LONG regQueryResult;
HKEY hkey = NULL;
// Append the version to the key
TCHAR fxRegKey[MAX_PATH+1];
sprintf(fxRegKey, "%s%s", FX_REG_KEY, netVersion);
regQueryResult = RegOpenKeyEx( HKEY_LOCAL_MACHINE, // handle to open key
fxRegKey, // name of subkey to open
NULL,
KEY_READ,
&hkey // handle to open key
);
// we don't proceed unless the call above succeeds
if (ERROR_FILE_NOT_FOUND == regQueryResult)
{
//MessageBox(NULL, "Couldn't find .Net Key", "Error", MB_OK | MB_ICONINFORMATION);
return ERROR_FILE_NOT_FOUND;
}
if (ERROR_SUCCESS == regQueryResult)
{
TCHAR policyStr[256];
DWORD bufLen = LENGTH(policyStr);
regQueryResult = RegQueryValueEx( hkey,
subVersion,
NULL,
NULL,
(LPBYTE)policyStr,
&bufLen);
if (ERROR_SUCCESS == regQueryResult)
{
// key found, now we need to check for the existence of the appropriate language install dir.
strncat(windowsDir,
_T("\\Microsoft.Net\\Framework\\"),
LENGTH(windowsDir));
strncat(windowsDir,
settings.GetNetVersion(),
LENGTH(windowsDir));
strncat(windowsDir,
_T("."),
LENGTH(windowsDir));
strncat(windowsDir,
subVersion,
LENGTH(windowsDir));
strncat(windowsDir,
_T("\\"),
LENGTH(windowsDir));
strncat(windowsDir,
"",//settings.GetLanguageDirectory(),
LENGTH(windowsDir));
DWORD resultDw = GetFileAttributes(windowsDir);
if (resultDw != INVALID_FILE_ATTRIBUTES && (resultDw & FILE_ATTRIBUTE_DIRECTORY))
{
// we found our subdirectory, no need to install
ifNeedToInstall = FALSE;
}
}
// if we receive an error other than 0x2, throw
else if (ERROR_FILE_NOT_FOUND != regQueryResult)
{
RegCloseKey(hkey);
throw HRESULT_FROM_WIN32(regQueryResult);
}
else
{
MessageBox( NULL, "Could not find the .Net Version Number in the registry", "Error", MB_OK | MB_ICONINFORMATION );
}
RegCloseKey(hkey);
}
}
catch( HRESULT hr )
{
CError se;
se.ShowHResultMessage(ERR_VERSION_DETECT_FAILED,
0,
MB_OK,
hr,
fxInstaller);
throw hr;
}
return ifNeedToInstall;
}
BOOL IfNeedToInstallNetFx(char* fxSetupNpdKey,char* keyValueName,char* keyValue)
{
BOOL ifNeedToInstall =false;
LONG regQueryResult;
HKEY hkey = NULL;
// Append the version to the key
TCHAR fullFxSetupNpdKey[MAX_PATH+1];
sprintf(fullFxSetupNpdKey, "%s%s%s",FX_INSTALL_REG_KEY,"\\",fxSetupNpdKey);
regQueryResult = RegOpenKeyEx( HKEY_LOCAL_MACHINE, // handle to open key
fullFxSetupNpdKey, // name of subkey to open
NULL,
KEY_READ,
&hkey // handle to open key
);
if (ERROR_SUCCESS != regQueryResult)
{
RegCloseKey(hkey);
ifNeedToInstall=true;
return ifNeedToInstall;
}
if(_tcsicmp(keyValueName,_T("")) !=0)
{
DWORD dwType;
//wchar_t data[MAX_PATH];
TCHAR data[MAX_PATH];
DWORD bufLen = LENGTH(data);
DWORD dwSize;
regQueryResult = RegQueryValueEx( hkey,
keyValueName,
NULL,
&dwType,
(LPBYTE)data,
&bufLen);
if(ERROR_SUCCESS != regQueryResult)
{
RegCloseKey(hkey);
ifNeedToInstall=true;
return ifNeedToInstall;
}
if(_tcsicmp(keyValue,_T("")) !=0)
{
TCHAR data1[MAX_PATH];
if(dwType==REG_EXPAND_SZ||dwType==REG_SZ||dwType==REG_MULTI_SZ)
{
//printf("%s/n",data);
sprintf(data1, "%s",data);
}
else if(dwType==REG_DWORD||dwType==REG_BINARY)
{
sprintf(data1, "%d",(long)*(short *)data);
}
if(_tcsicmp(data1, keyValue)!=0)
{
ifNeedToInstall=true;
}
}
}
RegCloseKey(hkey);
return ifNeedToInstall;
}
// ==========================================================================
// LastError
// ==========================================================================
HRESULT LastError ()
{
HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
if (SUCCEEDED(hr))
{
hr = E_FAIL;
}
return hr;
}
// ==========================================================================
// InitiateReboot(): initiates a system reboot
// ==========================================================================
BOOL InitiateReboot()
{
#if(_WIN32_WINNT >= 0x0500)
return ExitWindowsEx( EWX_REBOOT, EWX_FORCEIFHUNG);
#else
return ExitWindowsEx( EWX_REBOOT, 0);
#endif /* _WIN32_WINNT >= 0x0500 */
}
// ==========================================================================
//TerminalServices
// ==========================================================================
// SetTSInInstallMode(): checks if Terminal Services is enabled and if so switches machine to INSTALL mode
void SetTSInInstallMode()
{
if (IsTerminalServicesEnabled())
{
processHelper.Run(false,TS_CHANGE_USER_TO_INSTALL);
}
}
//Detecting If Terminal Services is Installed, code is taken directly from http://msdndevstg/library/psdk/termserv/termserv_7mp0.htm
BOOL IsTerminalServicesEnabled()
{
BOOL bResult = FALSE;
DWORD dwVersion;
OSVERSIONINFOEXA osVersion;
DWORDLONG dwlCondition = 0;
HMODULE hmodK32 = NULL;
HMODULE hmodNtDll = NULL;
typedef ULONGLONG (WINAPI *PFnVerSetCondition) (ULONGLONG, ULONG, UCHAR);
typedef BOOL (WINAPI *PFnVerifyVersionA) (POSVERSIONINFOEXA, DWORD, DWORDLONG);
PFnVerSetCondition pfnVerSetCondition;
PFnVerifyVersionA pfnVerifyVersionA;
dwVersion = GetVersion();
// Are we running Windows NT?
if (!(dwVersion & 0x80000000))
{
// Is it Windows 2000 or greater?
if (LOBYTE(LOWORD(dwVersion)) > 4)
{
// In Windows 2000, use the VerifyVersionInfo and VerSetConditionMask functions. Don't static link because it won't load on earlier systems.
hmodNtDll = GetModuleHandleA( "ntdll.dll" );
if (hmodNtDll)
{
pfnVerSetCondition = (PFnVerSetCondition) GetProcAddress(hmodNtDll, "VerSetConditionMask");
if (pfnVerSetCondition != NULL)
{
dwlCondition = (*pfnVerSetCondition) (dwlCondition,VER_SUITENAME, VER_AND);
// Get a VerifyVersionInfo pointer.
hmodK32 = GetModuleHandleA( "KERNEL32.DLL" );
if (hmodK32 != NULL)
{
pfnVerifyVersionA = (PFnVerifyVersionA) GetProcAddress(hmodK32, "VerifyVersionInfoA") ;
if (pfnVerifyVersionA != NULL)
{
ZeroMemory(&osVersion, sizeof(osVersion));
osVersion.dwOSVersionInfoSize = sizeof(osVersion);
osVersion.wSuiteMask = VER_SUITE_TERMINAL;
bResult = (*pfnVerifyVersionA) (&osVersion,
VER_SUITENAME, dwlCondition);
}
}
}
}
}
else // This is Windows NT 4.0 or earlier.
bResult = ValidateProductSuite( "Terminal Server" );
}
return bResult;
}
// ValidateProductSuite() : Terminal Services detection code for systems running Windows NT 4.0 and earlier.
BOOL ValidateProductSuite (LPSTR lpszSuiteToValidate)
{
BOOL fValidated = FALSE;
LONG lResult;
HKEY hKey = NULL;
DWORD dwType = 0;
DWORD dwSize = 0;
LPSTR lpszProductSuites = NULL;
LPSTR lpszSuite;
// Open the ProductOptions key.
lResult = RegOpenKeyA(
HKEY_LOCAL_MACHINE,
"System\\CurrentControlSet\\Control\\ProductOptions",
&hKey
);
if (lResult != ERROR_SUCCESS)
goto exit;
// Determine required size of ProductSuite buffer.
lResult = RegQueryValueExA( hKey, "ProductSuite", NULL, &dwType,NULL, &dwSize );
if (lResult != ERROR_SUCCESS || !dwSize)
goto exit;
// Allocate buffer.
lpszProductSuites = (LPSTR) LocalAlloc( LPTR, dwSize );
if (!lpszProductSuites)
goto exit;
// Retrieve array of product suite strings.
lResult = RegQueryValueExA( hKey, "ProductSuite", NULL, &dwType,(LPBYTE) lpszProductSuites, &dwSize );
if (lResult != ERROR_SUCCESS || dwType != REG_MULTI_SZ)
goto exit;
// Search for suite name in array of strings.
lpszSuite = lpszProductSuites;
while (*lpszSuite)
{
if (lstrcmpA( lpszSuite, lpszSuiteToValidate ) == 0)
{
fValidated = TRUE;
break;
}
lpszSuite += (lstrlenA( lpszSuite ) + 1);
}
exit:
if (lpszProductSuites)
LocalFree( lpszProductSuites );
if (hKey)
RegCloseKey( hKey );
return fValidated;
}
// ==========================================================================
// Billboard
// ==========================================================================
// BillboardProc() Purpose: Callback proc used to set HWND_TOPMOST on billboard
void ShowBillboard(DWORD * pdwThreadId, HANDLE * phThread)
{
if (windowCount != 0)
return;
HANDLE threadEvent = CreateEvent(
NULL, // no security attributes
FALSE, // auto-reset event
FALSE, // initial state is not signaled
NULL); // object not named
*phThread = CreateThread(NULL,
0L,
StaticThreadProc,
(LPVOID)&threadEvent,
0,
pdwThreadId );
// Wait for any message sent or posted to this queue or for one of the passed handles be set to signaled.
// This is important as the window does not get created until the StaticThreadProc gets called
HANDLE handles[1];
handles[0] = threadEvent;
DWORD result = WaitForMultipleObjects(1, handles, FALSE, INFINITE);
}
void TeardownBillboard(DWORD dwThreadId, HANDLE hThread)
{
if (windowCount != 1 || hThread == NULL)
return;
// Tell the thread to destroy the modeless dialog
while (!(PostThreadMessage(dwThreadId, PWM_THREADDESTROYWND, 0, 0 )))
{
Sleep(5);
}
WaitForSingleObject( hThread, INFINITE );
CloseHandle( hThread );
hThread = NULL;
windowCount = 0;
}
BOOL CALLBACK BillboardProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
SetWindowPos( hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, /*SWP_NOMOVE |*/ SWP_NOSIZE );
return TRUE;
}
return FALSE;
}
// StaticThreadProc()
// Purpose: Thread proc that creates our billboard dialog
DWORD WINAPI StaticThreadProc( LPVOID lpParameter )
{
MSG msg;
HANDLE startEvent = *(HANDLE*)lpParameter; // thread's read event
// Create the billboard dialog up front so we can change the text
billBoard = CreateDialog(settings.GetHInstance(), MAKEINTRESOURCE(DIALOG_BILLBOARD), GetDesktopWindow(), BillboardProc);
ShowWindow(billBoard, SW_SHOW);
windowCount = 1;
SetEvent(startEvent); // Signal event
while( GetMessage( &msg, NULL, 0, 0 ) )
{
if (!::IsDialogMessage( billBoard, &msg ))
{
if (msg.message == PWM_THREADDESTROYWND)
{
//Tell the dialog to destroy itself
DestroyWindow(billBoard);
//Tell our thread to break out of message pump
PostThreadMessage( threadNoDw, WM_QUIT, 0, 0 );
}
}
}
return( 0L );
}
void SetBillBoardText(LPTSTR cap, LPTSTR msg)
{
SetWindowText(billBoard,cap);
SetDlgItemText(billBoard, TXT_BillboardMsg, msg);
}
// ==========================================================================
// DlgProc
// ==========================================================================
INT_PTR CALLBACK ProcDlgMain(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_INITDIALOG:
{
HWND desktop = GetDesktopWindow();
RECT screenRect, dialogRect;
GetClientRect(desktop, &screenRect);
GetClientRect(hwnd, &dialogRect);
SetWindowPos(hwnd, HWND_TOP, (screenRect.right-screenRect.left)/2 - (dialogRect.right - dialogRect.left)/2,
(screenRect.bottom-screenRect.top)/2 - (dialogRect.bottom - dialogRect.top)/2,
dialogRect.right - dialogRect.left, dialogRect.bottom - dialogRect.top, SWP_NOSIZE);
SetWindowText(hwnd,settings.AppTitle);
HWND control = GetDlgItem(hwnd, CKBOX_SelectAll);
CheckDlgButton(hwnd, 9999, BST_CHECKED);
int i=0;
for(i = 0;i < settings.StepNo;++i)
{
control = GetDlgItem(hwnd, 9900+i);
ShowWindow(control, true);
if(!settings.IsUnselected[i])
{
CheckDlgButton(hwnd, 9900+i, BST_CHECKED);
}
if(settings.IsCompulsory[i])
{
CheckDlgButton(hwnd, 9900+i, BST_CHECKED);
EnableWindow(control, false);
}
SetWindowText(control,settings.StepDes[i]);
}
BringWindowToTop(hwnd);
}
break;
case WM_COMMAND:
switch(LOWORD(wParam))
{
case CKBOX_SelectAll:
{
int i=0;
if (IsDlgButtonChecked(hwnd, 9999) == BST_CHECKED)
{
for(i = 0;i < settings.StepNo;++i)
{
if(!settings.IsCompulsory[i])
{
CheckDlgButton(hwnd, 9900+i, BST_CHECKED);
}
}
}
else
{
for(i = 0;i < settings.StepNo;++i)
{
if(!settings.IsCompulsory[i])
{
CheckDlgButton(hwnd, 9900+i, BST_UNCHECKED);
}
}
}
return TRUE;
}
case BTN_Next:
{
int i=0;
for(i = 0;i < settings.StepNo;++i)
{
if (IsDlgButtonChecked(hwnd, 9900+i) == BST_CHECKED)
{
settings.IsUnselected[i]=false;
}
else
{
settings.IsUnselected[i]=TRUE;
}
}
EndDialog(hwnd, TRUE);
return TRUE;
}
case BTN_Cancel:
EndDialog(hwnd, FALSE);
return FALSE;
default:
return TRUE;
}
case WM_DESTROY:
EndDialog(hwnd, FALSE);
return FALSE;
default:
return FALSE;
}
return TRUE;
}
INT_PTR CALLBACK ProcDlgEncrpt(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_INITDIALOG:
{
HWND desktop = GetDesktopWindow();
RECT screenRect, dialogRect;
GetClientRect(desktop, &screenRect);
GetClientRect(hwnd, &dialogRect);
SetWindowPos(hwnd, HWND_TOP, (screenRect.right-screenRect.left)/2 - (dialogRect.right - dialogRect.left)/2,
(screenRect.bottom-screenRect.top)/2 - (dialogRect.bottom - dialogRect.top)/2,
dialogRect.right - dialogRect.left, dialogRect.bottom - dialogRect.top, SWP_NOSIZE);
BringWindowToTop(hwnd);
}
break;
case WM_COMMAND:
switch(LOWORD(wParam))
{
case BTN_Caculate:
{
HWND controlClear = GetDlgItem(hwnd, EDIT_ClearCode);
HWND controlEncrp = GetDlgItem(hwnd, EDIT_EncrptCode);
char txtClear[300];
char txtEncrp[300];
GetWindowText(controlClear,txtClear,300);
GetWindowText(controlEncrp,txtEncrp,300);
if(_tcsicmp(txtClear,"") != 0)
{
EncryptHelper eh;
unsigned char* key= (unsigned char *)DES_KEY;
char *p=eh.DesEncrypt(key,txtClear);
SetWindowText(controlEncrp,p);
}
else{
SetWindowText(controlEncrp,"");
}
break;
}
case BTN_Cancel:
EndDialog(hwnd, FALSE);
break;
}
case WM_DESTROY:
break;
default:
return FALSE;
}
return TRUE;
}
INT_PTR CALLBACK ProcDlgPasswordVerification(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_INITDIALOG:
{
HWND desktop = GetDesktopWindow();
RECT screenRect, dialogRect;
GetClientRect(desktop, &screenRect);
GetClientRect(hwnd, &dialogRect);
SetWindowPos(hwnd, HWND_TOP, (screenRect.right-screenRect.left)/2 - (dialogRect.right - dialogRect.left)/2,
(screenRect.bottom-screenRect.top)/2 - (dialogRect.bottom - dialogRect.top)/2,
dialogRect.right - dialogRect.left, dialogRect.bottom - dialogRect.top, SWP_NOSIZE);
BringWindowToTop(hwnd);
}
break;
case WM_COMMAND:
switch(LOWORD(wParam))
{
case BTN_Ok:
{
HWND control = GetDlgItem(hwnd, EDIT_Password);
char a[300];
GetWindowText(control,a,300);
if(_tcsicmp(a,settings.StartPassword) == 0)
{
EndDialog(hwnd, TRUE);
}
else{
}
break;
}
case BTN_Cancel:
EndDialog(hwnd, FALSE);
break;
}
case WM_DESTROY:
break;
default:
return FALSE;
}
return TRUE;
}
INT_PTR CALLBACK ProcDlgMsg(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_INITDIALOG:
{
HWND desktop = GetDesktopWindow();
RECT screenRect, dialogRect;
GetClientRect(desktop, &screenRect);
GetClientRect(hwnd, &dialogRect);
SetWindowPos(hwnd, HWND_TOP, (screenRect.right-screenRect.left)/2 - (dialogRect.right - dialogRect.left)/2,
(screenRect.bottom-screenRect.top)/2 - (dialogRect.bottom - dialogRect.top)/2,
dialogRect.right - dialogRect.left, dialogRect.bottom - dialogRect.top, SWP_NOSIZE);
BringWindowToTop(hwnd);
SetWindowText(hwnd,curDlgCaption);
SetDlgItemText(hwnd, EDIT_Msg, curDlgMsg);
}
break;
case WM_COMMAND:
switch(LOWORD(wParam))
{
case BTN_Ok:
EndDialog(hwnd, FALSE);
break;
}
case WM_DESTROY:
break;
default:
return FALSE;
}
return TRUE;
}
// ==========================================================================
// Registry operation
// ==========================================================================
void InsertRegistryRun()
{
try
{
HKEY l_HKey;
LONG l_result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
CURVER_REG_KEY,
0,
KEY_WRITE,
&l_HKey);
if (l_result != ERROR_SUCCESS)
return;
TCHAR l_ExeName[2000];
GetModuleFileName(NULL,(LPTSTR)l_ExeName,LENGTH(l_ExeName));
RegSetValueEx(l_HKey, C_DOT_NET_INSTALLER,0,REG_SZ,(LPBYTE)(LPCTSTR)l_ExeName, (DWORD)(LENGTH(l_ExeName)+1) );
RegCloseKey(l_HKey);
}
catch(...)
{
_ASSERT(false);
}
};
void RemoveRegistryRun()
{
try
{
HKEY l_HKey;
LONG l_result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
CURVER_REG_KEY,
0,
KEY_WRITE,
&l_HKey);
if (l_result != ERROR_SUCCESS)
return;
RegDeleteValue(l_HKey, C_DOT_NET_INSTALLER);
RegCloseKey(l_HKey);
}
catch(...)
{
_ASSERT(false);
}
};
// ==========================================================================
// WorkingDir
// ==========================================================================
BOOL SetWorkingDir()
{
// Desc: Retrieves the directory of the application.
// Pre: None.
// Post: The return value is the directory of the application ending in
//'\'.
TCHAR app_path[2000];
GetModuleFileName(NULL,(LPTSTR)app_path,LENGTH(app_path));
LONG len = LENGTH(app_path );
while ((len > 0) && ('\\' != app_path[ len - 1 ]))
--len;
app_path[ len ] = '\0';
return SetCurrentDirectory((LPCTSTR)app_path);
}
// ==========================================================================
// IsProcessRunByAdmin
// ==========================================================================
| 25.869925
| 145
| 0.630773
|
Liggin2019
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.